xref: /openbmc/qemu/block/file-posix.c (revision 719c6819)
1 /*
2  * Block driver for RAW files (posix)
3  *
4  * Copyright (c) 2006 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
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"
41 
42 #include "scsi/pr-manager.h"
43 #include "scsi/constants.h"
44 
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
61 
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
94 
95 #ifdef __OpenBSD__
96 #include <sys/ioctl.h>
97 #include <sys/disklabel.h>
98 #include <sys/dkio.h>
99 #endif
100 
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
107 
108 #ifdef __DragonFly__
109 #include <sys/ioctl.h>
110 #include <sys/diskslice.h>
111 #endif
112 
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
121 
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
126 
127 #define FTYPE_FILE   0
128 #define FTYPE_CD     1
129 
130 #define MAX_BLOCKSIZE	4096
131 
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
136 
137 typedef struct BDRVRawState {
138     int fd;
139     bool use_lock;
140     int type;
141     int open_flags;
142     size_t buf_align;
143 
144     /* The current permissions. */
145     uint64_t perm;
146     uint64_t shared_perm;
147 
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;
152 
153     uint64_t aio_max_batch;
154 
155     int perm_change_fd;
156     int perm_change_flags;
157     BDRVReopenState *reopen_state;
158 
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;
174 
175     PRManager *pr_mgr;
176 } BDRVRawState;
177 
178 typedef struct BDRVRawReopenState {
179     int open_flags;
180     bool drop_cache;
181     bool check_cache_dropped;
182 } BDRVRawReopenState;
183 
184 static int fd_open(BlockDriverState *bs)
185 {
186     BDRVRawState *s = bs->opaque;
187 
188     /* this is just to ensure s->fd is sane (its called by io ops) */
189     if (s->fd >= 0) {
190         return 0;
191     }
192     return -EIO;
193 }
194 
195 static int64_t raw_getlength(BlockDriverState *bs);
196 
197 typedef struct RawPosixAIOData {
198     BlockDriverState *bs;
199     int aio_type;
200     int aio_fildes;
201 
202     off_t aio_offset;
203     uint64_t aio_nbytes;
204 
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;
229     };
230 } RawPosixAIOData;
231 
232 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
233 static int cdrom_reopen(BlockDriverState *bs);
234 #endif
235 
236 /*
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.
240  */
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__);     \
247         }                                                               \
248     } while (0)
249 
250 #if defined(__NetBSD__)
251 static int raw_normalize_devicepath(const char **filename, Error **errp)
252 {
253     static char namebuf[PATH_MAX];
254     const char *dp, *fname;
255     struct stat sb;
256 
257     fname = *filename;
258     dp = strrchr(fname, '/');
259     if (lstat(fname, &sb) < 0) {
260         error_setg_file_open(errp, errno, fname);
261         return -errno;
262     }
263 
264     if (!S_ISBLK(sb.st_mode)) {
265         return 0;
266     }
267 
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);
273     }
274     *filename = namebuf;
275     warn_report("%s is a block device, using %s", fname, *filename);
276 
277     return 0;
278 }
279 #else
280 static int raw_normalize_devicepath(const char **filename, Error **errp)
281 {
282     return 0;
283 }
284 #endif
285 
286 /*
287  * Get logical block size via ioctl. On success store it in @sector_size_p.
288  */
289 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
290 {
291     unsigned int sector_size;
292     bool success = false;
293     int i;
294 
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
306     };
307 
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;
313         }
314     }
315 
316     return success ? 0 : -errno;
317 }
318 
319 /**
320  * Get physical block size of @fd.
321  * On success, store it in @blk_size and return 0.
322  * On failure, return -errno.
323  */
324 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
325 {
326 #ifdef BLKPBSZGET
327     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
328         return -errno;
329     }
330     return 0;
331 #else
332     return -ENOTSUP;
333 #endif
334 }
335 
336 /*
337  * Returns true if no alignment restrictions are necessary even for files
338  * opened with O_DIRECT.
339  *
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.
343  */
344 static bool dio_byte_aligned(int fd)
345 {
346 #ifdef __linux__
347     struct statfs buf;
348     int ret;
349 
350     ret = fstatfs(fd, &buf);
351     if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
352         return true;
353     }
354 #endif
355     return false;
356 }
357 
358 static bool raw_needs_alignment(BlockDriverState *bs)
359 {
360     BDRVRawState *s = bs->opaque;
361 
362     if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
363         return true;
364     }
365 
366     return s->force_alignment;
367 }
368 
369 /* Check if read is allowed with given memory buffer and length.
370  *
371  * This function is used to check O_DIRECT memory buffer and request alignment.
372  */
373 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
374 {
375     ssize_t ret = pread(fd, buf, len, 0);
376 
377     if (ret >= 0) {
378         return true;
379     }
380 
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.
385      */
386     if (errno != EINVAL) {
387         return true;
388     }
389 #endif
390 
391     return false;
392 }
393 
394 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
395 {
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};
400 
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;
407     }
408 
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;
414     }
415 
416 #ifdef __linux__
417     /*
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:
421      */
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; */
431     }
432 #endif
433 
434     /*
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.
440      */
441 
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;
452             }
453         }
454         qemu_vfree(buf);
455     }
456 
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;
467             }
468         }
469         qemu_vfree(buf);
470     }
471 
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");
475     }
476 }
477 
478 static int check_hdev_writable(int fd)
479 {
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.
484      *
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.
488      */
489     struct stat st;
490     int readonly = 0;
491 
492     if (fstat(fd, &st)) {
493         return -errno;
494     }
495 
496     if (!S_ISBLK(st.st_mode)) {
497         return 0;
498     }
499 
500     if (ioctl(fd, BLKROGET, &readonly) < 0) {
501         return -errno;
502     }
503 
504     if (readonly) {
505         return -EACCES;
506     }
507 #endif /* defined(BLKROGET) */
508     return 0;
509 }
510 
511 static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
512 {
513     bool read_write = false;
514     assert(open_flags != NULL);
515 
516     *open_flags |= O_BINARY;
517     *open_flags &= ~O_ACCMODE;
518 
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;
523     }
524 
525     if (read_write) {
526         *open_flags |= O_RDWR;
527     } else {
528         *open_flags |= O_RDONLY;
529     }
530 
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;
535     }
536 }
537 
538 static void raw_parse_filename(const char *filename, QDict *options,
539                                Error **errp)
540 {
541     bdrv_parse_filename_strip_prefix(filename, "file:", options);
542 }
543 
544 static QemuOptsList raw_runtime_opts = {
545     .name = "raw",
546     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
547     .desc = {
548         {
549             .name = "filename",
550             .type = QEMU_OPT_STRING,
551             .help = "File name of the image",
552         },
553         {
554             .name = "aio",
555             .type = QEMU_OPT_STRING,
556             .help = "host AIO implementation (threads, native, io_uring)",
557         },
558         {
559             .name = "aio-max-batch",
560             .type = QEMU_OPT_NUMBER,
561             .help = "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
562         },
563         {
564             .name = "locking",
565             .type = QEMU_OPT_STRING,
566             .help = "file locking mode (on/off/auto, default: auto)",
567         },
568         {
569             .name = "pr-manager",
570             .type = QEMU_OPT_STRING,
571             .help = "id of persistent reservation manager object (default: none)",
572         },
573 #if defined(__linux__)
574         {
575             .name = "drop-cache",
576             .type = QEMU_OPT_BOOL,
577             .help = "invalidate page cache during live migration (default: on)",
578         },
579 #endif
580         {
581             .name = "x-check-cache-dropped",
582             .type = QEMU_OPT_BOOL,
583             .help = "check that page cache was dropped on live migration (default: off)"
584         },
585         { /* end of list */ }
586     },
587 };
588 
589 static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
590 
591 static int raw_open_common(BlockDriverState *bs, QDict *options,
592                            int bdrv_flags, int open_flags,
593                            bool device, Error **errp)
594 {
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;
604 
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;
609     }
610 
611     filename = qemu_opt_get(opts, "filename");
612 
613     ret = raw_normalize_devicepath(&filename, errp);
614     if (ret != 0) {
615         goto fail;
616     }
617 
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;
626     }
627 
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;
635     }
636 
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
641 
642     s->aio_max_batch = qemu_opt_get_number(opts, "aio-max-batch", 0);
643 
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;
651     }
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");
660         }
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();
670     }
671 
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;
679         }
680     }
681 
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);
685 
686     s->open_flags = open_flags;
687     raw_parse_flags(bdrv_flags, &s->open_flags, false);
688 
689     s->fd = -1;
690     fd = qemu_open(filename, s->open_flags, errp);
691     ret = fd < 0 ? -errno : 0;
692 
693     if (ret < 0) {
694         if (ret == -EROFS) {
695             ret = -EACCES;
696         }
697         goto fail;
698     }
699     s->fd = fd;
700 
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;
707         }
708     }
709 
710     s->perm = 0;
711     s->shared_perm = BLK_PERM_ALL;
712 
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;
720     }
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;
727     }
728 #endif /* !defined(CONFIG_LINUX_AIO) */
729 
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;
736     }
737 #endif /* !defined(CONFIG_LINUX_IO_URING) */
738 
739     s->has_discard = true;
740     s->has_write_zeroes = true;
741 
742     if (fstat(s->fd, &st) < 0) {
743         ret = -errno;
744         error_setg_errno(errp, errno, "Could not stat file");
745         goto fail;
746     }
747 
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;
756         }
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;
764         }
765     }
766 #ifdef CONFIG_BLKZONED
767     /*
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.
770      */
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 */
776     }
777 #endif
778 
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.
784          */
785         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
786             s->has_write_zeroes = false;
787         }
788 #endif
789     }
790 #ifdef __FreeBSD__
791     if (S_ISCHR(st.st_mode)) {
792         /*
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.
797          */
798         s->force_alignment = true;
799     }
800 #endif
801     s->needs_alignment = raw_needs_alignment(bs);
802 
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;
807     }
808     ret = 0;
809 fail:
810     if (ret < 0 && s->fd != -1) {
811         qemu_close(s->fd);
812     }
813     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
814         unlink(filename);
815     }
816     qemu_opts_del(opts);
817     return ret;
818 }
819 
820 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
821                     Error **errp)
822 {
823     BDRVRawState *s = bs->opaque;
824 
825     s->type = FTYPE_FILE;
826     return raw_open_common(bs, options, flags, 0, false, errp);
827 }
828 
829 typedef enum {
830     RAW_PL_PREPARE,
831     RAW_PL_COMMIT,
832     RAW_PL_ABORT,
833 } RawPermLockOp;
834 
835 #define PERM_FOREACH(i) \
836     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
837 
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.
841  */
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)
846 {
847     int ret;
848     int i;
849     uint64_t locked_perm, locked_shared_perm;
850 
851     if (s) {
852         locked_perm = s->locked_perm;
853         locked_shared_perm = s->locked_shared_perm;
854     } else {
855         /*
856          * We don't have the previous bits, just lock/unlock for each of the
857          * requested bits.
858          */
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;
865         }
866     }
867 
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;
879             }
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;
887             }
888         }
889     }
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;
901             }
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;
910             }
911         }
912     }
913     return 0;
914 }
915 
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)
919 {
920     int ret;
921     int i;
922 
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);
930 
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;
936             }
937         }
938     }
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);
946 
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;
952             }
953         }
954     }
955     return 0;
956 }
957 
958 static int raw_handle_perm_lock(BlockDriverState *bs,
959                                 RawPermLockOp op,
960                                 uint64_t new_perm, uint64_t new_shared,
961                                 Error **errp)
962 {
963     BDRVRawState *s = bs->opaque;
964     int ret = 0;
965     Error *local_err = NULL;
966 
967     if (!s->use_lock) {
968         return 0;
969     }
970 
971     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
972         return 0;
973     }
974 
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)
979         {
980             /*
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.
986              */
987             return 0;
988         }
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;
996             }
997             error_append_hint(errp,
998                               "Is another process using the image [%s]?\n",
999                               bs->filename);
1000         }
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.
1008              */
1009             warn_report_err(local_err);
1010         }
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.
1018              */
1019             warn_report_err(local_err);
1020         }
1021         break;
1022     }
1023     return ret;
1024 }
1025 
1026 /* Sets a specific flag */
1027 static int fcntl_setfl(int fd, int flag)
1028 {
1029     int flags;
1030 
1031     flags = fcntl(fd, F_GETFL);
1032     if (flags == -1) {
1033         return -errno;
1034     }
1035     if (fcntl(fd, F_SETFL, flags | flag) == -1) {
1036         return -errno;
1037     }
1038     return 0;
1039 }
1040 
1041 static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
1042                                  int *open_flags, uint64_t perm, Error **errp)
1043 {
1044     BDRVRawState *s = bs->opaque;
1045     int fd = -1;
1046     int ret;
1047     bool has_writers = perm &
1048         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
1049     int fcntl_flags = O_APPEND | O_NONBLOCK;
1050 #ifdef O_NOATIME
1051     fcntl_flags |= O_NOATIME;
1052 #endif
1053 
1054     *open_flags = 0;
1055     if (s->type == FTYPE_CD) {
1056         *open_flags |= O_NONBLOCK;
1057     }
1058 
1059     raw_parse_flags(flags, open_flags, has_writers);
1060 
1061 #ifdef O_ASYNC
1062     /* Not all operating systems have O_ASYNC, and those that don't
1063      * will not let us track the state into rs->open_flags (typically
1064      * you achieve the same effect with an ioctl, for example I_SETSIG
1065      * on Solaris). But we do not use O_ASYNC, so that's fine.
1066      */
1067     assert((s->open_flags & O_ASYNC) == 0);
1068 #endif
1069 
1070     if (*open_flags == s->open_flags) {
1071         /* We're lucky, the existing fd is fine */
1072         return s->fd;
1073     }
1074 
1075     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
1076         /* dup the original fd */
1077         fd = qemu_dup(s->fd);
1078         if (fd >= 0) {
1079             ret = fcntl_setfl(fd, *open_flags);
1080             if (ret) {
1081                 qemu_close(fd);
1082                 fd = -1;
1083             }
1084         }
1085     }
1086 
1087     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
1088     if (fd == -1) {
1089         const char *normalized_filename = bs->filename;
1090         ret = raw_normalize_devicepath(&normalized_filename, errp);
1091         if (ret >= 0) {
1092             fd = qemu_open(normalized_filename, *open_flags, errp);
1093             if (fd == -1) {
1094                 return -1;
1095             }
1096         }
1097     }
1098 
1099     if (fd != -1 && (*open_flags & O_RDWR)) {
1100         ret = check_hdev_writable(fd);
1101         if (ret < 0) {
1102             qemu_close(fd);
1103             error_setg_errno(errp, -ret, "The device is not writable");
1104             return -1;
1105         }
1106     }
1107 
1108     return fd;
1109 }
1110 
1111 static int raw_reopen_prepare(BDRVReopenState *state,
1112                               BlockReopenQueue *queue, Error **errp)
1113 {
1114     BDRVRawState *s;
1115     BDRVRawReopenState *rs;
1116     QemuOpts *opts;
1117     int ret;
1118 
1119     assert(state != NULL);
1120     assert(state->bs != NULL);
1121 
1122     s = state->bs->opaque;
1123 
1124     state->opaque = g_new0(BDRVRawReopenState, 1);
1125     rs = state->opaque;
1126 
1127     /* Handle options changes */
1128     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1129     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
1130         ret = -EINVAL;
1131         goto out;
1132     }
1133 
1134     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
1135     rs->check_cache_dropped =
1136         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
1137 
1138     /* This driver's reopen function doesn't currently allow changing
1139      * other options, so let's put them back in the original QDict and
1140      * bdrv_reopen_prepare() will detect changes and complain. */
1141     qemu_opts_to_qdict(opts, state->options);
1142 
1143     /*
1144      * As part of reopen prepare we also want to create new fd by
1145      * raw_reconfigure_getfd(). But it wants updated "perm", when in
1146      * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1147      * permission update. Happily, permission update is always a part
1148      * (a separate stage) of bdrv_reopen_multiple() so we can rely on this
1149      * fact and reconfigure fd in raw_check_perm().
1150      */
1151 
1152     s->reopen_state = state;
1153     ret = 0;
1154 
1155 out:
1156     qemu_opts_del(opts);
1157     return ret;
1158 }
1159 
1160 static void raw_reopen_commit(BDRVReopenState *state)
1161 {
1162     BDRVRawReopenState *rs = state->opaque;
1163     BDRVRawState *s = state->bs->opaque;
1164 
1165     s->drop_cache = rs->drop_cache;
1166     s->check_cache_dropped = rs->check_cache_dropped;
1167     s->open_flags = rs->open_flags;
1168     g_free(state->opaque);
1169     state->opaque = NULL;
1170 
1171     assert(s->reopen_state == state);
1172     s->reopen_state = NULL;
1173 }
1174 
1175 
1176 static void raw_reopen_abort(BDRVReopenState *state)
1177 {
1178     BDRVRawReopenState *rs = state->opaque;
1179     BDRVRawState *s = state->bs->opaque;
1180 
1181      /* nothing to do if NULL, we didn't get far enough */
1182     if (rs == NULL) {
1183         return;
1184     }
1185 
1186     g_free(state->opaque);
1187     state->opaque = NULL;
1188 
1189     assert(s->reopen_state == state);
1190     s->reopen_state = NULL;
1191 }
1192 
1193 static int hdev_get_max_hw_transfer(int fd, struct stat *st)
1194 {
1195 #ifdef BLKSECTGET
1196     if (S_ISBLK(st->st_mode)) {
1197         unsigned short max_sectors = 0;
1198         if (ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
1199             return max_sectors * 512;
1200         }
1201     } else {
1202         int max_bytes = 0;
1203         if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
1204             return max_bytes;
1205         }
1206     }
1207     return -errno;
1208 #else
1209     return -ENOSYS;
1210 #endif
1211 }
1212 
1213 /*
1214  * Get a sysfs attribute value as character string.
1215  */
1216 #ifdef CONFIG_LINUX
1217 static int get_sysfs_str_val(struct stat *st, const char *attribute,
1218                              char **val) {
1219     g_autofree char *sysfspath = NULL;
1220     size_t len;
1221 
1222     if (!S_ISBLK(st->st_mode)) {
1223         return -ENOTSUP;
1224     }
1225 
1226     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/%s",
1227                                 major(st->st_rdev), minor(st->st_rdev),
1228                                 attribute);
1229     if (!g_file_get_contents(sysfspath, val, &len, NULL)) {
1230         return -ENOENT;
1231     }
1232 
1233     /* The file is ended with '\n' */
1234     char *p;
1235     p = *val;
1236     if (*(p + len - 1) == '\n') {
1237         *(p + len - 1) = '\0';
1238     }
1239     return 0;
1240 }
1241 #endif
1242 
1243 #if defined(CONFIG_BLKZONED)
1244 static int get_sysfs_zoned_model(struct stat *st, BlockZoneModel *zoned)
1245 {
1246     g_autofree char *val = NULL;
1247     int ret;
1248 
1249     ret = get_sysfs_str_val(st, "zoned", &val);
1250     if (ret < 0) {
1251         return ret;
1252     }
1253 
1254     if (strcmp(val, "host-managed") == 0) {
1255         *zoned = BLK_Z_HM;
1256     } else if (strcmp(val, "host-aware") == 0) {
1257         *zoned = BLK_Z_HA;
1258     } else if (strcmp(val, "none") == 0) {
1259         *zoned = BLK_Z_NONE;
1260     } else {
1261         return -ENOTSUP;
1262     }
1263     return 0;
1264 }
1265 #endif /* defined(CONFIG_BLKZONED) */
1266 
1267 /*
1268  * Get a sysfs attribute value as a long integer.
1269  */
1270 #ifdef CONFIG_LINUX
1271 static long get_sysfs_long_val(struct stat *st, const char *attribute)
1272 {
1273     g_autofree char *str = NULL;
1274     const char *end;
1275     long val;
1276     int ret;
1277 
1278     ret = get_sysfs_str_val(st, attribute, &str);
1279     if (ret < 0) {
1280         return ret;
1281     }
1282 
1283     /* The file is ended with '\n', pass 'end' to accept that. */
1284     ret = qemu_strtol(str, &end, 10, &val);
1285     if (ret == 0 && end && *end == '\0') {
1286         ret = val;
1287     }
1288     return ret;
1289 }
1290 #endif
1291 
1292 static int hdev_get_max_segments(int fd, struct stat *st)
1293 {
1294 #ifdef CONFIG_LINUX
1295     int ret;
1296 
1297     if (S_ISCHR(st->st_mode)) {
1298         if (ioctl(fd, SG_GET_SG_TABLESIZE, &ret) == 0) {
1299             return ret;
1300         }
1301         return -ENOTSUP;
1302     }
1303     return get_sysfs_long_val(st, "max_segments");
1304 #else
1305     return -ENOTSUP;
1306 #endif
1307 }
1308 
1309 #if defined(CONFIG_BLKZONED)
1310 /*
1311  * If the reset_all flag is true, then the wps of zone whose state is
1312  * not readonly or offline should be all reset to the start sector.
1313  * Else, take the real wp of the device.
1314  */
1315 static int get_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1316                         unsigned int nrz, bool reset_all)
1317 {
1318     struct blk_zone *blkz;
1319     size_t rep_size;
1320     uint64_t sector = offset >> BDRV_SECTOR_BITS;
1321     BlockZoneWps *wps = bs->wps;
1322     unsigned int j = offset / bs->bl.zone_size;
1323     unsigned int n = 0, i = 0;
1324     int ret;
1325     rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
1326     g_autofree struct blk_zone_report *rep = NULL;
1327 
1328     rep = g_malloc(rep_size);
1329     blkz = (struct blk_zone *)(rep + 1);
1330     while (n < nrz) {
1331         memset(rep, 0, rep_size);
1332         rep->sector = sector;
1333         rep->nr_zones = nrz - n;
1334 
1335         do {
1336             ret = ioctl(fd, BLKREPORTZONE, rep);
1337         } while (ret != 0 && errno == EINTR);
1338         if (ret != 0) {
1339             error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
1340                     fd, offset, errno);
1341             return -errno;
1342         }
1343 
1344         if (!rep->nr_zones) {
1345             break;
1346         }
1347 
1348         for (i = 0; i < rep->nr_zones; ++i, ++n, ++j) {
1349             /*
1350              * The wp tracking cares only about sequential writes required and
1351              * sequential write preferred zones so that the wp can advance to
1352              * the right location.
1353              * Use the most significant bit of the wp location to indicate the
1354              * zone type: 0 for SWR/SWP zones and 1 for conventional zones.
1355              */
1356             if (blkz[i].type == BLK_ZONE_TYPE_CONVENTIONAL) {
1357                 wps->wp[j] |= 1ULL << 63;
1358             } else {
1359                 switch(blkz[i].cond) {
1360                 case BLK_ZONE_COND_FULL:
1361                 case BLK_ZONE_COND_READONLY:
1362                     /* Zone not writable */
1363                     wps->wp[j] = (blkz[i].start + blkz[i].len) << BDRV_SECTOR_BITS;
1364                     break;
1365                 case BLK_ZONE_COND_OFFLINE:
1366                     /* Zone not writable nor readable */
1367                     wps->wp[j] = (blkz[i].start) << BDRV_SECTOR_BITS;
1368                     break;
1369                 default:
1370                     if (reset_all) {
1371                         wps->wp[j] = blkz[i].start << BDRV_SECTOR_BITS;
1372                     } else {
1373                         wps->wp[j] = blkz[i].wp << BDRV_SECTOR_BITS;
1374                     }
1375                     break;
1376                 }
1377             }
1378         }
1379         sector = blkz[i - 1].start + blkz[i - 1].len;
1380     }
1381 
1382     return 0;
1383 }
1384 
1385 static void update_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1386                             unsigned int nrz)
1387 {
1388     if (get_zones_wp(bs, fd, offset, nrz, 0) < 0) {
1389         error_report("update zone wp failed");
1390     }
1391 }
1392 
1393 static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1394                                      Error **errp)
1395 {
1396     BDRVRawState *s = bs->opaque;
1397     BlockZoneModel zoned;
1398     int ret;
1399 
1400     ret = get_sysfs_zoned_model(st, &zoned);
1401     if (ret < 0 || zoned == BLK_Z_NONE) {
1402         goto no_zoned;
1403     }
1404     bs->bl.zoned = zoned;
1405 
1406     ret = get_sysfs_long_val(st, "max_open_zones");
1407     if (ret >= 0) {
1408         bs->bl.max_open_zones = ret;
1409     }
1410 
1411     ret = get_sysfs_long_val(st, "max_active_zones");
1412     if (ret >= 0) {
1413         bs->bl.max_active_zones = ret;
1414     }
1415 
1416     /*
1417      * The zoned device must at least have zone size and nr_zones fields.
1418      */
1419     ret = get_sysfs_long_val(st, "chunk_sectors");
1420     if (ret < 0) {
1421         error_setg_errno(errp, -ret, "Unable to read chunk_sectors "
1422                                      "sysfs attribute");
1423         goto no_zoned;
1424     } else if (!ret) {
1425         error_setg(errp, "Read 0 from chunk_sectors sysfs attribute");
1426         goto no_zoned;
1427     }
1428     bs->bl.zone_size = ret << BDRV_SECTOR_BITS;
1429 
1430     ret = get_sysfs_long_val(st, "nr_zones");
1431     if (ret < 0) {
1432         error_setg_errno(errp, -ret, "Unable to read nr_zones "
1433                                      "sysfs attribute");
1434         goto no_zoned;
1435     } else if (!ret) {
1436         error_setg(errp, "Read 0 from nr_zones sysfs attribute");
1437         goto no_zoned;
1438     }
1439     bs->bl.nr_zones = ret;
1440 
1441     ret = get_sysfs_long_val(st, "zone_append_max_bytes");
1442     if (ret > 0) {
1443         bs->bl.max_append_sectors = ret >> BDRV_SECTOR_BITS;
1444     }
1445 
1446     ret = get_sysfs_long_val(st, "physical_block_size");
1447     if (ret >= 0) {
1448         bs->bl.write_granularity = ret;
1449     }
1450 
1451     /* The refresh_limits() function can be called multiple times. */
1452     g_free(bs->wps);
1453     bs->wps = g_malloc(sizeof(BlockZoneWps) +
1454             sizeof(int64_t) * bs->bl.nr_zones);
1455     ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 0);
1456     if (ret < 0) {
1457         error_setg_errno(errp, -ret, "report wps failed");
1458         goto no_zoned;
1459     }
1460     qemu_co_mutex_init(&bs->wps->colock);
1461     return;
1462 
1463 no_zoned:
1464     bs->bl.zoned = BLK_Z_NONE;
1465     g_free(bs->wps);
1466     bs->wps = NULL;
1467 }
1468 #else /* !defined(CONFIG_BLKZONED) */
1469 static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1470                                      Error **errp)
1471 {
1472     bs->bl.zoned = BLK_Z_NONE;
1473 }
1474 #endif /* !defined(CONFIG_BLKZONED) */
1475 
1476 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1477 {
1478     BDRVRawState *s = bs->opaque;
1479     struct stat st;
1480 
1481     s->needs_alignment = raw_needs_alignment(bs);
1482     raw_probe_alignment(bs, s->fd, errp);
1483 
1484     bs->bl.min_mem_alignment = s->buf_align;
1485     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size());
1486 
1487     /*
1488      * Maximum transfers are best effort, so it is okay to ignore any
1489      * errors.  That said, based on the man page errors in fstat would be
1490      * very much unexpected; the only possible case seems to be ENOMEM.
1491      */
1492     if (fstat(s->fd, &st)) {
1493         return;
1494     }
1495 
1496 #if defined(__APPLE__) && (__MACH__)
1497     struct statfs buf;
1498 
1499     if (!fstatfs(s->fd, &buf)) {
1500         bs->bl.opt_transfer = buf.f_iosize;
1501         bs->bl.pdiscard_alignment = buf.f_bsize;
1502     }
1503 #endif
1504 
1505     if (bdrv_is_sg(bs) || S_ISBLK(st.st_mode)) {
1506         int ret = hdev_get_max_hw_transfer(s->fd, &st);
1507 
1508         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
1509             bs->bl.max_hw_transfer = ret;
1510         }
1511 
1512         ret = hdev_get_max_segments(s->fd, &st);
1513         if (ret > 0) {
1514             bs->bl.max_hw_iov = ret;
1515         }
1516     }
1517 
1518     raw_refresh_zoned_limits(bs, &st, errp);
1519 }
1520 
1521 static int check_for_dasd(int fd)
1522 {
1523 #ifdef BIODASDINFO2
1524     struct dasd_information2_t info = {0};
1525 
1526     return ioctl(fd, BIODASDINFO2, &info);
1527 #else
1528     return -1;
1529 #endif
1530 }
1531 
1532 /**
1533  * Try to get @bs's logical and physical block size.
1534  * On success, store them in @bsz and return zero.
1535  * On failure, return negative errno.
1536  */
1537 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1538 {
1539     BDRVRawState *s = bs->opaque;
1540     int ret;
1541 
1542     /* If DASD or zoned devices, get blocksizes */
1543     if (check_for_dasd(s->fd) < 0) {
1544         /* zoned devices are not DASD */
1545         if (bs->bl.zoned == BLK_Z_NONE) {
1546             return -ENOTSUP;
1547         }
1548     }
1549     ret = probe_logical_blocksize(s->fd, &bsz->log);
1550     if (ret < 0) {
1551         return ret;
1552     }
1553     return probe_physical_blocksize(s->fd, &bsz->phys);
1554 }
1555 
1556 /**
1557  * Try to get @bs's geometry: cyls, heads, sectors.
1558  * On success, store them in @geo and return 0.
1559  * On failure return -errno.
1560  * (Allows block driver to assign default geometry values that guest sees)
1561  */
1562 #ifdef __linux__
1563 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1564 {
1565     BDRVRawState *s = bs->opaque;
1566     struct hd_geometry ioctl_geo = {0};
1567 
1568     /* If DASD, get its geometry */
1569     if (check_for_dasd(s->fd) < 0) {
1570         return -ENOTSUP;
1571     }
1572     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1573         return -errno;
1574     }
1575     /* HDIO_GETGEO may return success even though geo contains zeros
1576        (e.g. certain multipath setups) */
1577     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1578         return -ENOTSUP;
1579     }
1580     /* Do not return a geometry for partition */
1581     if (ioctl_geo.start != 0) {
1582         return -ENOTSUP;
1583     }
1584     geo->heads = ioctl_geo.heads;
1585     geo->sectors = ioctl_geo.sectors;
1586     geo->cylinders = ioctl_geo.cylinders;
1587 
1588     return 0;
1589 }
1590 #else /* __linux__ */
1591 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1592 {
1593     return -ENOTSUP;
1594 }
1595 #endif
1596 
1597 #if defined(__linux__)
1598 static int handle_aiocb_ioctl(void *opaque)
1599 {
1600     RawPosixAIOData *aiocb = opaque;
1601     int ret;
1602 
1603     ret = RETRY_ON_EINTR(
1604         ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf)
1605     );
1606     if (ret == -1) {
1607         return -errno;
1608     }
1609 
1610     return 0;
1611 }
1612 #endif /* linux */
1613 
1614 static int handle_aiocb_flush(void *opaque)
1615 {
1616     RawPosixAIOData *aiocb = opaque;
1617     BDRVRawState *s = aiocb->bs->opaque;
1618     int ret;
1619 
1620     if (s->page_cache_inconsistent) {
1621         return -s->page_cache_inconsistent;
1622     }
1623 
1624     ret = qemu_fdatasync(aiocb->aio_fildes);
1625     if (ret == -1) {
1626         trace_file_flush_fdatasync_failed(errno);
1627 
1628         /* There is no clear definition of the semantics of a failing fsync(),
1629          * so we may have to assume the worst. The sad truth is that this
1630          * assumption is correct for Linux. Some pages are now probably marked
1631          * clean in the page cache even though they are inconsistent with the
1632          * on-disk contents. The next fdatasync() call would succeed, but no
1633          * further writeback attempt will be made. We can't get back to a state
1634          * in which we know what is on disk (we would have to rewrite
1635          * everything that was touched since the last fdatasync() at least), so
1636          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1637          * really defined, I have little hope that other OSes are doing better.
1638          *
1639          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1640          * cache. */
1641         if ((s->open_flags & O_DIRECT) == 0) {
1642             s->page_cache_inconsistent = errno;
1643         }
1644         return -errno;
1645     }
1646     return 0;
1647 }
1648 
1649 #ifdef CONFIG_PREADV
1650 
1651 static bool preadv_present = true;
1652 
1653 static ssize_t
1654 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1655 {
1656     return preadv(fd, iov, nr_iov, offset);
1657 }
1658 
1659 static ssize_t
1660 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1661 {
1662     return pwritev(fd, iov, nr_iov, offset);
1663 }
1664 
1665 #else
1666 
1667 static bool preadv_present = false;
1668 
1669 static ssize_t
1670 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1671 {
1672     return -ENOSYS;
1673 }
1674 
1675 static ssize_t
1676 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1677 {
1678     return -ENOSYS;
1679 }
1680 
1681 #endif
1682 
1683 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1684 {
1685     ssize_t len;
1686 
1687     len = RETRY_ON_EINTR(
1688         (aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) ?
1689             qemu_pwritev(aiocb->aio_fildes,
1690                            aiocb->io.iov,
1691                            aiocb->io.niov,
1692                            aiocb->aio_offset) :
1693             qemu_preadv(aiocb->aio_fildes,
1694                           aiocb->io.iov,
1695                           aiocb->io.niov,
1696                           aiocb->aio_offset)
1697     );
1698 
1699     if (len == -1) {
1700         return -errno;
1701     }
1702     return len;
1703 }
1704 
1705 /*
1706  * Read/writes the data to/from a given linear buffer.
1707  *
1708  * Returns the number of bytes handles or -errno in case of an error. Short
1709  * reads are only returned if the end of the file is reached.
1710  */
1711 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1712 {
1713     ssize_t offset = 0;
1714     ssize_t len;
1715 
1716     while (offset < aiocb->aio_nbytes) {
1717         if (aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) {
1718             len = pwrite(aiocb->aio_fildes,
1719                          (const char *)buf + offset,
1720                          aiocb->aio_nbytes - offset,
1721                          aiocb->aio_offset + offset);
1722         } else {
1723             len = pread(aiocb->aio_fildes,
1724                         buf + offset,
1725                         aiocb->aio_nbytes - offset,
1726                         aiocb->aio_offset + offset);
1727         }
1728         if (len == -1 && errno == EINTR) {
1729             continue;
1730         } else if (len == -1 && errno == EINVAL &&
1731                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1732                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1733                    offset > 0) {
1734             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1735              * after a short read.  Assume that O_DIRECT short reads only occur
1736              * at EOF.  Therefore this is a short read, not an I/O error.
1737              */
1738             break;
1739         } else if (len == -1) {
1740             offset = -errno;
1741             break;
1742         } else if (len == 0) {
1743             break;
1744         }
1745         offset += len;
1746     }
1747 
1748     return offset;
1749 }
1750 
1751 static int handle_aiocb_rw(void *opaque)
1752 {
1753     RawPosixAIOData *aiocb = opaque;
1754     ssize_t nbytes;
1755     char *buf;
1756 
1757     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1758         /*
1759          * If there is just a single buffer, and it is properly aligned
1760          * we can just use plain pread/pwrite without any problems.
1761          */
1762         if (aiocb->io.niov == 1) {
1763             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
1764             goto out;
1765         }
1766         /*
1767          * We have more than one iovec, and all are properly aligned.
1768          *
1769          * Try preadv/pwritev first and fall back to linearizing the
1770          * buffer if it's not supported.
1771          */
1772         if (preadv_present) {
1773             nbytes = handle_aiocb_rw_vector(aiocb);
1774             if (nbytes == aiocb->aio_nbytes ||
1775                 (nbytes < 0 && nbytes != -ENOSYS)) {
1776                 goto out;
1777             }
1778             preadv_present = false;
1779         }
1780 
1781         /*
1782          * XXX(hch): short read/write.  no easy way to handle the reminder
1783          * using these interfaces.  For now retry using plain
1784          * pread/pwrite?
1785          */
1786     }
1787 
1788     /*
1789      * Ok, we have to do it the hard way, copy all segments into
1790      * a single aligned buffer.
1791      */
1792     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1793     if (buf == NULL) {
1794         nbytes = -ENOMEM;
1795         goto out;
1796     }
1797 
1798     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1799         char *p = buf;
1800         int i;
1801 
1802         for (i = 0; i < aiocb->io.niov; ++i) {
1803             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1804             p += aiocb->io.iov[i].iov_len;
1805         }
1806         assert(p - buf == aiocb->aio_nbytes);
1807     }
1808 
1809     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1810     if (!(aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND))) {
1811         char *p = buf;
1812         size_t count = aiocb->aio_nbytes, copy;
1813         int i;
1814 
1815         for (i = 0; i < aiocb->io.niov && count; ++i) {
1816             copy = count;
1817             if (copy > aiocb->io.iov[i].iov_len) {
1818                 copy = aiocb->io.iov[i].iov_len;
1819             }
1820             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1821             assert(count >= copy);
1822             p     += copy;
1823             count -= copy;
1824         }
1825         assert(count == 0);
1826     }
1827     qemu_vfree(buf);
1828 
1829 out:
1830     if (nbytes == aiocb->aio_nbytes) {
1831         return 0;
1832     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
1833         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1834             return -EINVAL;
1835         } else {
1836             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
1837                       0, aiocb->aio_nbytes - nbytes);
1838             return 0;
1839         }
1840     } else {
1841         assert(nbytes < 0);
1842         return nbytes;
1843     }
1844 }
1845 
1846 #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1847 static int translate_err(int err)
1848 {
1849     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1850         err == -ENOTTY) {
1851         err = -ENOTSUP;
1852     }
1853     return err;
1854 }
1855 #endif
1856 
1857 #ifdef CONFIG_FALLOCATE
1858 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1859 {
1860     do {
1861         if (fallocate(fd, mode, offset, len) == 0) {
1862             return 0;
1863         }
1864     } while (errno == EINTR);
1865     return translate_err(-errno);
1866 }
1867 #endif
1868 
1869 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1870 {
1871     int ret = -ENOTSUP;
1872     BDRVRawState *s = aiocb->bs->opaque;
1873 
1874     if (!s->has_write_zeroes) {
1875         return -ENOTSUP;
1876     }
1877 
1878 #ifdef BLKZEROOUT
1879     /* The BLKZEROOUT implementation in the kernel doesn't set
1880      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1881      * fallbacks. */
1882     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1883         do {
1884             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1885             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1886                 return 0;
1887             }
1888         } while (errno == EINTR);
1889 
1890         ret = translate_err(-errno);
1891         if (ret == -ENOTSUP) {
1892             s->has_write_zeroes = false;
1893         }
1894     }
1895 #endif
1896 
1897     return ret;
1898 }
1899 
1900 static int handle_aiocb_write_zeroes(void *opaque)
1901 {
1902     RawPosixAIOData *aiocb = opaque;
1903 #ifdef CONFIG_FALLOCATE
1904     BDRVRawState *s = aiocb->bs->opaque;
1905     int64_t len;
1906 #endif
1907 
1908     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1909         return handle_aiocb_write_zeroes_block(aiocb);
1910     }
1911 
1912 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1913     if (s->has_write_zeroes) {
1914         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1915                                aiocb->aio_offset, aiocb->aio_nbytes);
1916         if (ret == -ENOTSUP) {
1917             s->has_write_zeroes = false;
1918         } else if (ret == 0 || ret != -EINVAL) {
1919             return ret;
1920         }
1921         /*
1922          * Note: Some file systems do not like unaligned byte ranges, and
1923          * return EINVAL in such a case, though they should not do it according
1924          * to the man-page of fallocate(). Thus we simply ignore this return
1925          * value and try the other fallbacks instead.
1926          */
1927     }
1928 #endif
1929 
1930 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1931     if (s->has_discard && s->has_fallocate) {
1932         int ret = do_fallocate(s->fd,
1933                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1934                                aiocb->aio_offset, aiocb->aio_nbytes);
1935         if (ret == 0) {
1936             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1937             if (ret == 0 || ret != -ENOTSUP) {
1938                 return ret;
1939             }
1940             s->has_fallocate = false;
1941         } else if (ret == -EINVAL) {
1942             /*
1943              * Some file systems like older versions of GPFS do not like un-
1944              * aligned byte ranges, and return EINVAL in such a case, though
1945              * they should not do it according to the man-page of fallocate().
1946              * Warn about the bad filesystem and try the final fallback instead.
1947              */
1948             warn_report_once("Your file system is misbehaving: "
1949                              "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
1950                              "Please report this bug to your file system "
1951                              "vendor.");
1952         } else if (ret != -ENOTSUP) {
1953             return ret;
1954         } else {
1955             s->has_discard = false;
1956         }
1957     }
1958 #endif
1959 
1960 #ifdef CONFIG_FALLOCATE
1961     /* Last resort: we are trying to extend the file with zeroed data. This
1962      * can be done via fallocate(fd, 0) */
1963     len = raw_getlength(aiocb->bs);
1964     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1965         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1966         if (ret == 0 || ret != -ENOTSUP) {
1967             return ret;
1968         }
1969         s->has_fallocate = false;
1970     }
1971 #endif
1972 
1973     return -ENOTSUP;
1974 }
1975 
1976 static int handle_aiocb_write_zeroes_unmap(void *opaque)
1977 {
1978     RawPosixAIOData *aiocb = opaque;
1979     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
1980 
1981     /* First try to write zeros and unmap at the same time */
1982 
1983 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1984     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1985                            aiocb->aio_offset, aiocb->aio_nbytes);
1986     switch (ret) {
1987     case -ENOTSUP:
1988     case -EINVAL:
1989     case -EBUSY:
1990         break;
1991     default:
1992         return ret;
1993     }
1994 #endif
1995 
1996     /* If we couldn't manage to unmap while guaranteed that the area reads as
1997      * all-zero afterwards, just write zeroes without unmapping */
1998     return handle_aiocb_write_zeroes(aiocb);
1999 }
2000 
2001 #ifndef HAVE_COPY_FILE_RANGE
2002 static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
2003                              off_t *out_off, size_t len, unsigned int flags)
2004 {
2005 #ifdef __NR_copy_file_range
2006     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
2007                    out_off, len, flags);
2008 #else
2009     errno = ENOSYS;
2010     return -1;
2011 #endif
2012 }
2013 #endif
2014 
2015 /*
2016  * parse_zone - Fill a zone descriptor
2017  */
2018 #if defined(CONFIG_BLKZONED)
2019 static inline int parse_zone(struct BlockZoneDescriptor *zone,
2020                               const struct blk_zone *blkz) {
2021     zone->start = blkz->start << BDRV_SECTOR_BITS;
2022     zone->length = blkz->len << BDRV_SECTOR_BITS;
2023     zone->wp = blkz->wp << BDRV_SECTOR_BITS;
2024 
2025 #ifdef HAVE_BLK_ZONE_REP_CAPACITY
2026     zone->cap = blkz->capacity << BDRV_SECTOR_BITS;
2027 #else
2028     zone->cap = blkz->len << BDRV_SECTOR_BITS;
2029 #endif
2030 
2031     switch (blkz->type) {
2032     case BLK_ZONE_TYPE_SEQWRITE_REQ:
2033         zone->type = BLK_ZT_SWR;
2034         break;
2035     case BLK_ZONE_TYPE_SEQWRITE_PREF:
2036         zone->type = BLK_ZT_SWP;
2037         break;
2038     case BLK_ZONE_TYPE_CONVENTIONAL:
2039         zone->type = BLK_ZT_CONV;
2040         break;
2041     default:
2042         error_report("Unsupported zone type: 0x%x", blkz->type);
2043         return -ENOTSUP;
2044     }
2045 
2046     switch (blkz->cond) {
2047     case BLK_ZONE_COND_NOT_WP:
2048         zone->state = BLK_ZS_NOT_WP;
2049         break;
2050     case BLK_ZONE_COND_EMPTY:
2051         zone->state = BLK_ZS_EMPTY;
2052         break;
2053     case BLK_ZONE_COND_IMP_OPEN:
2054         zone->state = BLK_ZS_IOPEN;
2055         break;
2056     case BLK_ZONE_COND_EXP_OPEN:
2057         zone->state = BLK_ZS_EOPEN;
2058         break;
2059     case BLK_ZONE_COND_CLOSED:
2060         zone->state = BLK_ZS_CLOSED;
2061         break;
2062     case BLK_ZONE_COND_READONLY:
2063         zone->state = BLK_ZS_RDONLY;
2064         break;
2065     case BLK_ZONE_COND_FULL:
2066         zone->state = BLK_ZS_FULL;
2067         break;
2068     case BLK_ZONE_COND_OFFLINE:
2069         zone->state = BLK_ZS_OFFLINE;
2070         break;
2071     default:
2072         error_report("Unsupported zone state: 0x%x", blkz->cond);
2073         return -ENOTSUP;
2074     }
2075     return 0;
2076 }
2077 #endif
2078 
2079 #if defined(CONFIG_BLKZONED)
2080 static int handle_aiocb_zone_report(void *opaque)
2081 {
2082     RawPosixAIOData *aiocb = opaque;
2083     int fd = aiocb->aio_fildes;
2084     unsigned int *nr_zones = aiocb->zone_report.nr_zones;
2085     BlockZoneDescriptor *zones = aiocb->zone_report.zones;
2086     /* zoned block devices use 512-byte sectors */
2087     uint64_t sector = aiocb->aio_offset / 512;
2088 
2089     struct blk_zone *blkz;
2090     size_t rep_size;
2091     unsigned int nrz;
2092     int ret;
2093     unsigned int n = 0, i = 0;
2094 
2095     nrz = *nr_zones;
2096     rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
2097     g_autofree struct blk_zone_report *rep = NULL;
2098     rep = g_malloc(rep_size);
2099 
2100     blkz = (struct blk_zone *)(rep + 1);
2101     while (n < nrz) {
2102         memset(rep, 0, rep_size);
2103         rep->sector = sector;
2104         rep->nr_zones = nrz - n;
2105 
2106         do {
2107             ret = ioctl(fd, BLKREPORTZONE, rep);
2108         } while (ret != 0 && errno == EINTR);
2109         if (ret != 0) {
2110             error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
2111                          fd, sector, errno);
2112             return -errno;
2113         }
2114 
2115         if (!rep->nr_zones) {
2116             break;
2117         }
2118 
2119         for (i = 0; i < rep->nr_zones; i++, n++) {
2120             ret = parse_zone(&zones[n], &blkz[i]);
2121             if (ret != 0) {
2122                 return ret;
2123             }
2124 
2125             /* The next report should start after the last zone reported */
2126             sector = blkz[i].start + blkz[i].len;
2127         }
2128     }
2129 
2130     *nr_zones = n;
2131     return 0;
2132 }
2133 #endif
2134 
2135 #if defined(CONFIG_BLKZONED)
2136 static int handle_aiocb_zone_mgmt(void *opaque)
2137 {
2138     RawPosixAIOData *aiocb = opaque;
2139     int fd = aiocb->aio_fildes;
2140     uint64_t sector = aiocb->aio_offset / 512;
2141     int64_t nr_sectors = aiocb->aio_nbytes / 512;
2142     struct blk_zone_range range;
2143     int ret;
2144 
2145     /* Execute the operation */
2146     range.sector = sector;
2147     range.nr_sectors = nr_sectors;
2148     do {
2149         ret = ioctl(fd, aiocb->zone_mgmt.op, &range);
2150     } while (ret != 0 && errno == EINTR);
2151 
2152     return ret < 0 ? -errno : ret;
2153 }
2154 #endif
2155 
2156 static int handle_aiocb_copy_range(void *opaque)
2157 {
2158     RawPosixAIOData *aiocb = opaque;
2159     uint64_t bytes = aiocb->aio_nbytes;
2160     off_t in_off = aiocb->aio_offset;
2161     off_t out_off = aiocb->copy_range.aio_offset2;
2162 
2163     while (bytes) {
2164         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
2165                                       aiocb->copy_range.aio_fd2, &out_off,
2166                                       bytes, 0);
2167         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
2168                                    aiocb->copy_range.aio_fd2, out_off, bytes,
2169                                    0, ret);
2170         if (ret == 0) {
2171             /* No progress (e.g. when beyond EOF), let the caller fall back to
2172              * buffer I/O. */
2173             return -ENOSPC;
2174         }
2175         if (ret < 0) {
2176             switch (errno) {
2177             case ENOSYS:
2178                 return -ENOTSUP;
2179             case EINTR:
2180                 continue;
2181             default:
2182                 return -errno;
2183             }
2184         }
2185         bytes -= ret;
2186     }
2187     return 0;
2188 }
2189 
2190 static int handle_aiocb_discard(void *opaque)
2191 {
2192     RawPosixAIOData *aiocb = opaque;
2193     int ret = -ENOTSUP;
2194     BDRVRawState *s = aiocb->bs->opaque;
2195 
2196     if (!s->has_discard) {
2197         return -ENOTSUP;
2198     }
2199 
2200     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
2201 #ifdef BLKDISCARD
2202         do {
2203             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
2204             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
2205                 return 0;
2206             }
2207         } while (errno == EINTR);
2208 
2209         ret = translate_err(-errno);
2210 #endif
2211     } else {
2212 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
2213         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
2214                            aiocb->aio_offset, aiocb->aio_nbytes);
2215         ret = translate_err(ret);
2216 #elif defined(__APPLE__) && (__MACH__)
2217         fpunchhole_t fpunchhole;
2218         fpunchhole.fp_flags = 0;
2219         fpunchhole.reserved = 0;
2220         fpunchhole.fp_offset = aiocb->aio_offset;
2221         fpunchhole.fp_length = aiocb->aio_nbytes;
2222         if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
2223             ret = errno == ENODEV ? -ENOTSUP : -errno;
2224         } else {
2225             ret = 0;
2226         }
2227 #endif
2228     }
2229 
2230     if (ret == -ENOTSUP) {
2231         s->has_discard = false;
2232     }
2233     return ret;
2234 }
2235 
2236 /*
2237  * Help alignment probing by allocating the first block.
2238  *
2239  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
2240  * reading succeeds regardless of request length. In this case we fallback to
2241  * safe alignment which is not optimal. Allocating the first block avoids this
2242  * fallback.
2243  *
2244  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
2245  * request alignment, so we use safe values.
2246  *
2247  * Returns: 0 on success, -errno on failure. Since this is an optimization,
2248  * caller may ignore failures.
2249  */
2250 static int allocate_first_block(int fd, size_t max_size)
2251 {
2252     size_t write_size = (max_size < MAX_BLOCKSIZE)
2253         ? BDRV_SECTOR_SIZE
2254         : MAX_BLOCKSIZE;
2255     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
2256     void *buf;
2257     ssize_t n;
2258     int ret;
2259 
2260     buf = qemu_memalign(max_align, write_size);
2261     memset(buf, 0, write_size);
2262 
2263     n = RETRY_ON_EINTR(pwrite(fd, buf, write_size, 0));
2264 
2265     ret = (n == -1) ? -errno : 0;
2266 
2267     qemu_vfree(buf);
2268     return ret;
2269 }
2270 
2271 static int handle_aiocb_truncate(void *opaque)
2272 {
2273     RawPosixAIOData *aiocb = opaque;
2274     int result = 0;
2275     int64_t current_length = 0;
2276     char *buf = NULL;
2277     struct stat st;
2278     int fd = aiocb->aio_fildes;
2279     int64_t offset = aiocb->aio_offset;
2280     PreallocMode prealloc = aiocb->truncate.prealloc;
2281     Error **errp = aiocb->truncate.errp;
2282 
2283     if (fstat(fd, &st) < 0) {
2284         result = -errno;
2285         error_setg_errno(errp, -result, "Could not stat file");
2286         return result;
2287     }
2288 
2289     current_length = st.st_size;
2290     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
2291         error_setg(errp, "Cannot use preallocation for shrinking files");
2292         return -ENOTSUP;
2293     }
2294 
2295     switch (prealloc) {
2296 #ifdef CONFIG_POSIX_FALLOCATE
2297     case PREALLOC_MODE_FALLOC:
2298         /*
2299          * Truncating before posix_fallocate() makes it about twice slower on
2300          * file systems that do not support fallocate(), trying to check if a
2301          * block is allocated before allocating it, so don't do that here.
2302          */
2303         if (offset != current_length) {
2304             result = -posix_fallocate(fd, current_length,
2305                                       offset - current_length);
2306             if (result != 0) {
2307                 /* posix_fallocate() doesn't set errno. */
2308                 error_setg_errno(errp, -result,
2309                                  "Could not preallocate new data");
2310             } else if (current_length == 0) {
2311                 /*
2312                  * posix_fallocate() uses fallocate() if the filesystem
2313                  * supports it, or fallback to manually writing zeroes. If
2314                  * fallocate() was used, unaligned reads from the fallocated
2315                  * area in raw_probe_alignment() will succeed, hence we need to
2316                  * allocate the first block.
2317                  *
2318                  * Optimize future alignment probing; ignore failures.
2319                  */
2320                 allocate_first_block(fd, offset);
2321             }
2322         } else {
2323             result = 0;
2324         }
2325         goto out;
2326 #endif
2327     case PREALLOC_MODE_FULL:
2328     {
2329         int64_t num = 0, left = offset - current_length;
2330         off_t seek_result;
2331 
2332         /*
2333          * Knowing the final size from the beginning could allow the file
2334          * system driver to do less allocations and possibly avoid
2335          * fragmentation of the file.
2336          */
2337         if (ftruncate(fd, offset) != 0) {
2338             result = -errno;
2339             error_setg_errno(errp, -result, "Could not resize file");
2340             goto out;
2341         }
2342 
2343         buf = g_malloc0(65536);
2344 
2345         seek_result = lseek(fd, current_length, SEEK_SET);
2346         if (seek_result < 0) {
2347             result = -errno;
2348             error_setg_errno(errp, -result,
2349                              "Failed to seek to the old end of file");
2350             goto out;
2351         }
2352 
2353         while (left > 0) {
2354             num = MIN(left, 65536);
2355             result = write(fd, buf, num);
2356             if (result < 0) {
2357                 if (errno == EINTR) {
2358                     continue;
2359                 }
2360                 result = -errno;
2361                 error_setg_errno(errp, -result,
2362                                  "Could not write zeros for preallocation");
2363                 goto out;
2364             }
2365             left -= result;
2366         }
2367         if (result >= 0) {
2368             result = fsync(fd);
2369             if (result < 0) {
2370                 result = -errno;
2371                 error_setg_errno(errp, -result,
2372                                  "Could not flush file to disk");
2373                 goto out;
2374             }
2375         }
2376         goto out;
2377     }
2378     case PREALLOC_MODE_OFF:
2379         if (ftruncate(fd, offset) != 0) {
2380             result = -errno;
2381             error_setg_errno(errp, -result, "Could not resize file");
2382         } else if (current_length == 0 && offset > current_length) {
2383             /* Optimize future alignment probing; ignore failures. */
2384             allocate_first_block(fd, offset);
2385         }
2386         return result;
2387     default:
2388         result = -ENOTSUP;
2389         error_setg(errp, "Unsupported preallocation mode: %s",
2390                    PreallocMode_str(prealloc));
2391         return result;
2392     }
2393 
2394 out:
2395     if (result < 0) {
2396         if (ftruncate(fd, current_length) < 0) {
2397             error_report("Failed to restore old file length: %s",
2398                          strerror(errno));
2399         }
2400     }
2401 
2402     g_free(buf);
2403     return result;
2404 }
2405 
2406 static int coroutine_fn raw_thread_pool_submit(ThreadPoolFunc func, void *arg)
2407 {
2408     return thread_pool_submit_co(func, arg);
2409 }
2410 
2411 /*
2412  * Check if all memory in this vector is sector aligned.
2413  */
2414 static bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2415 {
2416     int i;
2417     size_t alignment = bdrv_min_mem_align(bs);
2418     size_t len = bs->bl.request_alignment;
2419     IO_CODE();
2420 
2421     for (i = 0; i < qiov->niov; i++) {
2422         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2423             return false;
2424         }
2425         if (qiov->iov[i].iov_len % len) {
2426             return false;
2427         }
2428     }
2429 
2430     return true;
2431 }
2432 
2433 #ifdef CONFIG_LINUX_IO_URING
2434 static inline bool raw_check_linux_io_uring(BDRVRawState *s)
2435 {
2436     Error *local_err = NULL;
2437     AioContext *ctx;
2438 
2439     if (!s->use_linux_io_uring) {
2440         return false;
2441     }
2442 
2443     ctx = qemu_get_current_aio_context();
2444     if (unlikely(!aio_setup_linux_io_uring(ctx, &local_err))) {
2445         error_reportf_err(local_err, "Unable to use linux io_uring, "
2446                                      "falling back to thread pool: ");
2447         s->use_linux_io_uring = false;
2448         return false;
2449     }
2450     return true;
2451 }
2452 #endif
2453 
2454 #ifdef CONFIG_LINUX_AIO
2455 static inline bool raw_check_linux_aio(BDRVRawState *s)
2456 {
2457     Error *local_err = NULL;
2458     AioContext *ctx;
2459 
2460     if (!s->use_linux_aio) {
2461         return false;
2462     }
2463 
2464     ctx = qemu_get_current_aio_context();
2465     if (unlikely(!aio_setup_linux_aio(ctx, &local_err))) {
2466         error_reportf_err(local_err, "Unable to use Linux AIO, "
2467                                      "falling back to thread pool: ");
2468         s->use_linux_aio = false;
2469         return false;
2470     }
2471     return true;
2472 }
2473 #endif
2474 
2475 static int coroutine_fn raw_co_prw(BlockDriverState *bs, int64_t *offset_ptr,
2476                                    uint64_t bytes, QEMUIOVector *qiov, int type)
2477 {
2478     BDRVRawState *s = bs->opaque;
2479     RawPosixAIOData acb;
2480     int ret;
2481     uint64_t offset = *offset_ptr;
2482 
2483     if (fd_open(bs) < 0)
2484         return -EIO;
2485 #if defined(CONFIG_BLKZONED)
2486     if ((type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) &&
2487         bs->bl.zoned != BLK_Z_NONE) {
2488         qemu_co_mutex_lock(&bs->wps->colock);
2489         if (type & QEMU_AIO_ZONE_APPEND) {
2490             int index = offset / bs->bl.zone_size;
2491             offset = bs->wps->wp[index];
2492         }
2493     }
2494 #endif
2495 
2496     /*
2497      * When using O_DIRECT, the request must be aligned to be able to use
2498      * either libaio or io_uring interface. If not fail back to regular thread
2499      * pool read/write code which emulates this for us if we
2500      * set QEMU_AIO_MISALIGNED.
2501      */
2502     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
2503         type |= QEMU_AIO_MISALIGNED;
2504 #ifdef CONFIG_LINUX_IO_URING
2505     } else if (raw_check_linux_io_uring(s)) {
2506         assert(qiov->size == bytes);
2507         ret = luring_co_submit(bs, s->fd, offset, qiov, type);
2508         goto out;
2509 #endif
2510 #ifdef CONFIG_LINUX_AIO
2511     } else if (raw_check_linux_aio(s)) {
2512         assert(qiov->size == bytes);
2513         ret = laio_co_submit(s->fd, offset, qiov, type,
2514                               s->aio_max_batch);
2515         goto out;
2516 #endif
2517     }
2518 
2519     acb = (RawPosixAIOData) {
2520         .bs             = bs,
2521         .aio_fildes     = s->fd,
2522         .aio_type       = type,
2523         .aio_offset     = offset,
2524         .aio_nbytes     = bytes,
2525         .io             = {
2526             .iov            = qiov->iov,
2527             .niov           = qiov->niov,
2528         },
2529     };
2530 
2531     assert(qiov->size == bytes);
2532     ret = raw_thread_pool_submit(handle_aiocb_rw, &acb);
2533     goto out; /* Avoid the compiler err of unused label */
2534 
2535 out:
2536 #if defined(CONFIG_BLKZONED)
2537     if ((type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) &&
2538         bs->bl.zoned != BLK_Z_NONE) {
2539         BlockZoneWps *wps = bs->wps;
2540         if (ret == 0) {
2541             uint64_t *wp = &wps->wp[offset / bs->bl.zone_size];
2542             if (!BDRV_ZT_IS_CONV(*wp)) {
2543                 if (type & QEMU_AIO_ZONE_APPEND) {
2544                     *offset_ptr = *wp;
2545                     trace_zbd_zone_append_complete(bs, *offset_ptr
2546                         >> BDRV_SECTOR_BITS);
2547                 }
2548                 /* Advance the wp if needed */
2549                 if (offset + bytes > *wp) {
2550                     *wp = offset + bytes;
2551                 }
2552             }
2553         } else {
2554             /*
2555              * write and append write are not allowed to cross zone boundaries
2556              */
2557             update_zones_wp(bs, s->fd, offset, 1);
2558         }
2559 
2560         qemu_co_mutex_unlock(&wps->colock);
2561     }
2562 #endif
2563     return ret;
2564 }
2565 
2566 static int coroutine_fn raw_co_preadv(BlockDriverState *bs, int64_t offset,
2567                                       int64_t bytes, QEMUIOVector *qiov,
2568                                       BdrvRequestFlags flags)
2569 {
2570     return raw_co_prw(bs, &offset, bytes, qiov, QEMU_AIO_READ);
2571 }
2572 
2573 static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, int64_t offset,
2574                                        int64_t bytes, QEMUIOVector *qiov,
2575                                        BdrvRequestFlags flags)
2576 {
2577     return raw_co_prw(bs, &offset, bytes, qiov, QEMU_AIO_WRITE);
2578 }
2579 
2580 static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
2581 {
2582     BDRVRawState *s = bs->opaque;
2583     RawPosixAIOData acb;
2584     int ret;
2585 
2586     ret = fd_open(bs);
2587     if (ret < 0) {
2588         return ret;
2589     }
2590 
2591     acb = (RawPosixAIOData) {
2592         .bs             = bs,
2593         .aio_fildes     = s->fd,
2594         .aio_type       = QEMU_AIO_FLUSH,
2595     };
2596 
2597 #ifdef CONFIG_LINUX_IO_URING
2598     if (raw_check_linux_io_uring(s)) {
2599         return luring_co_submit(bs, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2600     }
2601 #endif
2602     return raw_thread_pool_submit(handle_aiocb_flush, &acb);
2603 }
2604 
2605 static void raw_close(BlockDriverState *bs)
2606 {
2607     BDRVRawState *s = bs->opaque;
2608 
2609     if (s->fd >= 0) {
2610 #if defined(CONFIG_BLKZONED)
2611         g_free(bs->wps);
2612 #endif
2613         qemu_close(s->fd);
2614         s->fd = -1;
2615     }
2616 }
2617 
2618 /**
2619  * Truncates the given regular file @fd to @offset and, when growing, fills the
2620  * new space according to @prealloc.
2621  *
2622  * Returns: 0 on success, -errno on failure.
2623  */
2624 static int coroutine_fn
2625 raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
2626                      PreallocMode prealloc, Error **errp)
2627 {
2628     RawPosixAIOData acb;
2629 
2630     acb = (RawPosixAIOData) {
2631         .bs             = bs,
2632         .aio_fildes     = fd,
2633         .aio_type       = QEMU_AIO_TRUNCATE,
2634         .aio_offset     = offset,
2635         .truncate       = {
2636             .prealloc       = prealloc,
2637             .errp           = errp,
2638         },
2639     };
2640 
2641     return raw_thread_pool_submit(handle_aiocb_truncate, &acb);
2642 }
2643 
2644 static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2645                                         bool exact, PreallocMode prealloc,
2646                                         BdrvRequestFlags flags, Error **errp)
2647 {
2648     BDRVRawState *s = bs->opaque;
2649     struct stat st;
2650     int ret;
2651 
2652     if (fstat(s->fd, &st)) {
2653         ret = -errno;
2654         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2655         return ret;
2656     }
2657 
2658     if (S_ISREG(st.st_mode)) {
2659         /* Always resizes to the exact @offset */
2660         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2661     }
2662 
2663     if (prealloc != PREALLOC_MODE_OFF) {
2664         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2665                    "non-regular file", PreallocMode_str(prealloc));
2666         return -ENOTSUP;
2667     }
2668 
2669     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2670         int64_t cur_length = raw_getlength(bs);
2671 
2672         if (offset != cur_length && exact) {
2673             error_setg(errp, "Cannot resize device files");
2674             return -ENOTSUP;
2675         } else if (offset > cur_length) {
2676             error_setg(errp, "Cannot grow device files");
2677             return -EINVAL;
2678         }
2679     } else {
2680         error_setg(errp, "Resizing this file is not supported");
2681         return -ENOTSUP;
2682     }
2683 
2684     return 0;
2685 }
2686 
2687 #ifdef __OpenBSD__
2688 static int64_t raw_getlength(BlockDriverState *bs)
2689 {
2690     BDRVRawState *s = bs->opaque;
2691     int fd = s->fd;
2692     struct stat st;
2693 
2694     if (fstat(fd, &st))
2695         return -errno;
2696     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2697         struct disklabel dl;
2698 
2699         if (ioctl(fd, DIOCGDINFO, &dl))
2700             return -errno;
2701         return (uint64_t)dl.d_secsize *
2702             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2703     } else
2704         return st.st_size;
2705 }
2706 #elif defined(__NetBSD__)
2707 static int64_t raw_getlength(BlockDriverState *bs)
2708 {
2709     BDRVRawState *s = bs->opaque;
2710     int fd = s->fd;
2711     struct stat st;
2712 
2713     if (fstat(fd, &st))
2714         return -errno;
2715     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2716         struct dkwedge_info dkw;
2717 
2718         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2719             return dkw.dkw_size * 512;
2720         } else {
2721             struct disklabel dl;
2722 
2723             if (ioctl(fd, DIOCGDINFO, &dl))
2724                 return -errno;
2725             return (uint64_t)dl.d_secsize *
2726                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2727         }
2728     } else
2729         return st.st_size;
2730 }
2731 #elif defined(__sun__)
2732 static int64_t raw_getlength(BlockDriverState *bs)
2733 {
2734     BDRVRawState *s = bs->opaque;
2735     struct dk_minfo minfo;
2736     int ret;
2737     int64_t size;
2738 
2739     ret = fd_open(bs);
2740     if (ret < 0) {
2741         return ret;
2742     }
2743 
2744     /*
2745      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2746      */
2747     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2748     if (ret != -1) {
2749         return minfo.dki_lbsize * minfo.dki_capacity;
2750     }
2751 
2752     /*
2753      * There are reports that lseek on some devices fails, but
2754      * irc discussion said that contingency on contingency was overkill.
2755      */
2756     size = lseek(s->fd, 0, SEEK_END);
2757     if (size < 0) {
2758         return -errno;
2759     }
2760     return size;
2761 }
2762 #elif defined(CONFIG_BSD)
2763 static int64_t raw_getlength(BlockDriverState *bs)
2764 {
2765     BDRVRawState *s = bs->opaque;
2766     int fd = s->fd;
2767     int64_t size;
2768     struct stat sb;
2769 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2770     int reopened = 0;
2771 #endif
2772     int ret;
2773 
2774     ret = fd_open(bs);
2775     if (ret < 0)
2776         return ret;
2777 
2778 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2779 again:
2780 #endif
2781     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2782         size = 0;
2783 #ifdef DIOCGMEDIASIZE
2784         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size)) {
2785             size = 0;
2786         }
2787 #endif
2788 #ifdef DIOCGPART
2789         if (size == 0) {
2790             struct partinfo pi;
2791             if (ioctl(fd, DIOCGPART, &pi) == 0) {
2792                 size = pi.media_size;
2793             }
2794         }
2795 #endif
2796 #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2797         if (size == 0) {
2798             uint64_t sectors = 0;
2799             uint32_t sector_size = 0;
2800 
2801             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2802                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2803                 size = sectors * sector_size;
2804             }
2805         }
2806 #endif
2807         if (size == 0) {
2808             size = lseek(fd, 0LL, SEEK_END);
2809         }
2810         if (size < 0) {
2811             return -errno;
2812         }
2813 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2814         switch(s->type) {
2815         case FTYPE_CD:
2816             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2817             if (size == 2048LL * (unsigned)-1)
2818                 size = 0;
2819             /* XXX no disc?  maybe we need to reopen... */
2820             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2821                 reopened = 1;
2822                 goto again;
2823             }
2824         }
2825 #endif
2826     } else {
2827         size = lseek(fd, 0, SEEK_END);
2828         if (size < 0) {
2829             return -errno;
2830         }
2831     }
2832     return size;
2833 }
2834 #else
2835 static int64_t raw_getlength(BlockDriverState *bs)
2836 {
2837     BDRVRawState *s = bs->opaque;
2838     int ret;
2839     int64_t size;
2840 
2841     ret = fd_open(bs);
2842     if (ret < 0) {
2843         return ret;
2844     }
2845 
2846     size = lseek(s->fd, 0, SEEK_END);
2847     if (size < 0) {
2848         return -errno;
2849     }
2850     return size;
2851 }
2852 #endif
2853 
2854 static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2855 {
2856     return raw_getlength(bs);
2857 }
2858 
2859 static int64_t coroutine_fn raw_co_get_allocated_file_size(BlockDriverState *bs)
2860 {
2861     struct stat st;
2862     BDRVRawState *s = bs->opaque;
2863 
2864     if (fstat(s->fd, &st) < 0) {
2865         return -errno;
2866     }
2867     return (int64_t)st.st_blocks * 512;
2868 }
2869 
2870 static int coroutine_fn
2871 raw_co_create(BlockdevCreateOptions *options, Error **errp)
2872 {
2873     BlockdevCreateOptionsFile *file_opts;
2874     Error *local_err = NULL;
2875     int fd;
2876     uint64_t perm, shared;
2877     int result = 0;
2878 
2879     /* Validate options and set default values */
2880     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2881     file_opts = &options->u.file;
2882 
2883     if (!file_opts->has_nocow) {
2884         file_opts->nocow = false;
2885     }
2886     if (!file_opts->has_preallocation) {
2887         file_opts->preallocation = PREALLOC_MODE_OFF;
2888     }
2889     if (!file_opts->has_extent_size_hint) {
2890         file_opts->extent_size_hint = 1 * MiB;
2891     }
2892     if (file_opts->extent_size_hint > UINT32_MAX) {
2893         result = -EINVAL;
2894         error_setg(errp, "Extent size hint is too large");
2895         goto out;
2896     }
2897 
2898     /* Create file */
2899     fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
2900     if (fd < 0) {
2901         result = -errno;
2902         goto out;
2903     }
2904 
2905     /* Take permissions: We want to discard everything, so we need
2906      * BLK_PERM_WRITE; and truncation to the desired size requires
2907      * BLK_PERM_RESIZE.
2908      * On the other hand, we cannot share the RESIZE permission
2909      * because we promise that after this function, the file has the
2910      * size given in the options.  If someone else were to resize it
2911      * concurrently, we could not guarantee that.
2912      * Note that after this function, we can no longer guarantee that
2913      * the file is not touched by a third party, so it may be resized
2914      * then. */
2915     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2916     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2917 
2918     /* Step one: Take locks */
2919     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2920     if (result < 0) {
2921         goto out_close;
2922     }
2923 
2924     /* Step two: Check that nobody else has taken conflicting locks */
2925     result = raw_check_lock_bytes(fd, perm, shared, errp);
2926     if (result < 0) {
2927         error_append_hint(errp,
2928                           "Is another process using the image [%s]?\n",
2929                           file_opts->filename);
2930         goto out_unlock;
2931     }
2932 
2933     /* Clear the file by truncating it to 0 */
2934     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2935     if (result < 0) {
2936         goto out_unlock;
2937     }
2938 
2939     if (file_opts->nocow) {
2940 #ifdef __linux__
2941         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2942          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2943          * will be ignored since any failure of this operation should not
2944          * block the left work.
2945          */
2946         int attr;
2947         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2948             attr |= FS_NOCOW_FL;
2949             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2950         }
2951 #endif
2952     }
2953 #ifdef FS_IOC_FSSETXATTR
2954     /*
2955      * Try to set the extent size hint. Failure is not fatal, and a warning is
2956      * only printed if the option was explicitly specified.
2957      */
2958     {
2959         struct fsxattr attr;
2960         result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2961         if (result == 0) {
2962             attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2963             attr.fsx_extsize = file_opts->extent_size_hint;
2964             result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2965         }
2966         if (result < 0 && file_opts->has_extent_size_hint &&
2967             file_opts->extent_size_hint)
2968         {
2969             warn_report("Failed to set extent size hint: %s",
2970                         strerror(errno));
2971         }
2972     }
2973 #endif
2974 
2975     /* Resize and potentially preallocate the file to the desired
2976      * final size */
2977     result = raw_regular_truncate(NULL, fd, file_opts->size,
2978                                   file_opts->preallocation, errp);
2979     if (result < 0) {
2980         goto out_unlock;
2981     }
2982 
2983 out_unlock:
2984     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
2985     if (local_err) {
2986         /* The above call should not fail, and if it does, that does
2987          * not mean the whole creation operation has failed.  So
2988          * report it the user for their convenience, but do not report
2989          * it to the caller. */
2990         warn_report_err(local_err);
2991     }
2992 
2993 out_close:
2994     if (qemu_close(fd) != 0 && result == 0) {
2995         result = -errno;
2996         error_setg_errno(errp, -result, "Could not close the new file");
2997     }
2998 out:
2999     return result;
3000 }
3001 
3002 static int coroutine_fn GRAPH_RDLOCK
3003 raw_co_create_opts(BlockDriver *drv, const char *filename,
3004                    QemuOpts *opts, Error **errp)
3005 {
3006     BlockdevCreateOptions options;
3007     int64_t total_size = 0;
3008     int64_t extent_size_hint = 0;
3009     bool has_extent_size_hint = false;
3010     bool nocow = false;
3011     PreallocMode prealloc;
3012     char *buf = NULL;
3013     Error *local_err = NULL;
3014 
3015     /* Skip file: protocol prefix */
3016     strstart(filename, "file:", &filename);
3017 
3018     /* Read out options */
3019     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3020                           BDRV_SECTOR_SIZE);
3021     if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
3022         has_extent_size_hint = true;
3023         extent_size_hint =
3024             qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
3025     }
3026     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
3027     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3028     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
3029                                PREALLOC_MODE_OFF, &local_err);
3030     g_free(buf);
3031     if (local_err) {
3032         error_propagate(errp, local_err);
3033         return -EINVAL;
3034     }
3035 
3036     options = (BlockdevCreateOptions) {
3037         .driver     = BLOCKDEV_DRIVER_FILE,
3038         .u.file     = {
3039             .filename           = (char *) filename,
3040             .size               = total_size,
3041             .has_preallocation  = true,
3042             .preallocation      = prealloc,
3043             .has_nocow          = true,
3044             .nocow              = nocow,
3045             .has_extent_size_hint = has_extent_size_hint,
3046             .extent_size_hint   = extent_size_hint,
3047         },
3048     };
3049     return raw_co_create(&options, errp);
3050 }
3051 
3052 static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
3053                                            Error **errp)
3054 {
3055     struct stat st;
3056     int ret;
3057 
3058     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
3059         error_setg_errno(errp, ENOENT, "%s is not a regular file",
3060                          bs->filename);
3061         return -ENOENT;
3062     }
3063 
3064     ret = unlink(bs->filename);
3065     if (ret < 0) {
3066         ret = -errno;
3067         error_setg_errno(errp, -ret, "Error when deleting file %s",
3068                          bs->filename);
3069     }
3070 
3071     return ret;
3072 }
3073 
3074 /*
3075  * Find allocation range in @bs around offset @start.
3076  * May change underlying file descriptor's file offset.
3077  * If @start is not in a hole, store @start in @data, and the
3078  * beginning of the next hole in @hole, and return 0.
3079  * If @start is in a non-trailing hole, store @start in @hole and the
3080  * beginning of the next non-hole in @data, and return 0.
3081  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
3082  * If we can't find out, return a negative errno other than -ENXIO.
3083  */
3084 static int find_allocation(BlockDriverState *bs, off_t start,
3085                            off_t *data, off_t *hole)
3086 {
3087 #if defined SEEK_HOLE && defined SEEK_DATA
3088     BDRVRawState *s = bs->opaque;
3089     off_t offs;
3090 
3091     /*
3092      * SEEK_DATA cases:
3093      * D1. offs == start: start is in data
3094      * D2. offs > start: start is in a hole, next data at offs
3095      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
3096      *                              or start is beyond EOF
3097      *     If the latter happens, the file has been truncated behind
3098      *     our back since we opened it.  All bets are off then.
3099      *     Treating like a trailing hole is simplest.
3100      * D4. offs < 0, errno != ENXIO: we learned nothing
3101      */
3102     offs = lseek(s->fd, start, SEEK_DATA);
3103     if (offs < 0) {
3104         return -errno;          /* D3 or D4 */
3105     }
3106 
3107     if (offs < start) {
3108         /* This is not a valid return by lseek().  We are safe to just return
3109          * -EIO in this case, and we'll treat it like D4. */
3110         return -EIO;
3111     }
3112 
3113     if (offs > start) {
3114         /* D2: in hole, next data at offs */
3115         *hole = start;
3116         *data = offs;
3117         return 0;
3118     }
3119 
3120     /* D1: in data, end not yet known */
3121 
3122     /*
3123      * SEEK_HOLE cases:
3124      * H1. offs == start: start is in a hole
3125      *     If this happens here, a hole has been dug behind our back
3126      *     since the previous lseek().
3127      * H2. offs > start: either start is in data, next hole at offs,
3128      *                   or start is in trailing hole, EOF at offs
3129      *     Linux treats trailing holes like any other hole: offs ==
3130      *     start.  Solaris seeks to EOF instead: offs > start (blech).
3131      *     If that happens here, a hole has been dug behind our back
3132      *     since the previous lseek().
3133      * H3. offs < 0, errno = ENXIO: start is beyond EOF
3134      *     If this happens, the file has been truncated behind our
3135      *     back since we opened it.  Treat it like a trailing hole.
3136      * H4. offs < 0, errno != ENXIO: we learned nothing
3137      *     Pretend we know nothing at all, i.e. "forget" about D1.
3138      */
3139     offs = lseek(s->fd, start, SEEK_HOLE);
3140     if (offs < 0) {
3141         return -errno;          /* D1 and (H3 or H4) */
3142     }
3143 
3144     if (offs < start) {
3145         /* This is not a valid return by lseek().  We are safe to just return
3146          * -EIO in this case, and we'll treat it like H4. */
3147         return -EIO;
3148     }
3149 
3150     if (offs > start) {
3151         /*
3152          * D1 and H2: either in data, next hole at offs, or it was in
3153          * data but is now in a trailing hole.  In the latter case,
3154          * all bets are off.  Treating it as if it there was data all
3155          * the way to EOF is safe, so simply do that.
3156          */
3157         *data = start;
3158         *hole = offs;
3159         return 0;
3160     }
3161 
3162     /* D1 and H1 */
3163     return -EBUSY;
3164 #else
3165     return -ENOTSUP;
3166 #endif
3167 }
3168 
3169 /*
3170  * Returns the allocation status of the specified offset.
3171  *
3172  * The block layer guarantees 'offset' and 'bytes' are within bounds.
3173  *
3174  * 'pnum' is set to the number of bytes (including and immediately following
3175  * the specified offset) that are known to be in the same
3176  * allocated/unallocated state.
3177  *
3178  * 'bytes' is a soft cap for 'pnum'.  If the information is free, 'pnum' may
3179  * well exceed it.
3180  */
3181 static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
3182                                             bool want_zero,
3183                                             int64_t offset,
3184                                             int64_t bytes, int64_t *pnum,
3185                                             int64_t *map,
3186                                             BlockDriverState **file)
3187 {
3188     off_t data = 0, hole = 0;
3189     int ret;
3190 
3191     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
3192 
3193     ret = fd_open(bs);
3194     if (ret < 0) {
3195         return ret;
3196     }
3197 
3198     if (!want_zero) {
3199         *pnum = bytes;
3200         *map = offset;
3201         *file = bs;
3202         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
3203     }
3204 
3205     ret = find_allocation(bs, offset, &data, &hole);
3206     if (ret == -ENXIO) {
3207         /* Trailing hole */
3208         *pnum = bytes;
3209         ret = BDRV_BLOCK_ZERO;
3210     } else if (ret < 0) {
3211         /* No info available, so pretend there are no holes */
3212         *pnum = bytes;
3213         ret = BDRV_BLOCK_DATA;
3214     } else if (data == offset) {
3215         /* On a data extent, compute bytes to the end of the extent,
3216          * possibly including a partial sector at EOF. */
3217         *pnum = hole - offset;
3218 
3219         /*
3220          * We are not allowed to return partial sectors, though, so
3221          * round up if necessary.
3222          */
3223         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
3224             int64_t file_length = raw_getlength(bs);
3225             if (file_length > 0) {
3226                 /* Ignore errors, this is just a safeguard */
3227                 assert(hole == file_length);
3228             }
3229             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
3230         }
3231 
3232         ret = BDRV_BLOCK_DATA;
3233     } else {
3234         /* On a hole, compute bytes to the beginning of the next extent.  */
3235         assert(hole == offset);
3236         *pnum = data - offset;
3237         ret = BDRV_BLOCK_ZERO;
3238     }
3239     *map = offset;
3240     *file = bs;
3241     return ret | BDRV_BLOCK_OFFSET_VALID;
3242 }
3243 
3244 #if defined(__linux__)
3245 /* Verify that the file is not in the page cache */
3246 static void check_cache_dropped(BlockDriverState *bs, Error **errp)
3247 {
3248     const size_t window_size = 128 * 1024 * 1024;
3249     BDRVRawState *s = bs->opaque;
3250     void *window = NULL;
3251     size_t length = 0;
3252     unsigned char *vec;
3253     size_t page_size;
3254     off_t offset;
3255     off_t end;
3256 
3257     /* mincore(2) page status information requires 1 byte per page */
3258     page_size = sysconf(_SC_PAGESIZE);
3259     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
3260 
3261     end = raw_getlength(bs);
3262 
3263     for (offset = 0; offset < end; offset += window_size) {
3264         void *new_window;
3265         size_t new_length;
3266         size_t vec_end;
3267         size_t i;
3268         int ret;
3269 
3270         /* Unmap previous window if size has changed */
3271         new_length = MIN(end - offset, window_size);
3272         if (new_length != length) {
3273             munmap(window, length);
3274             window = NULL;
3275             length = 0;
3276         }
3277 
3278         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
3279                           s->fd, offset);
3280         if (new_window == MAP_FAILED) {
3281             error_setg_errno(errp, errno, "mmap failed");
3282             break;
3283         }
3284 
3285         window = new_window;
3286         length = new_length;
3287 
3288         ret = mincore(window, length, vec);
3289         if (ret < 0) {
3290             error_setg_errno(errp, errno, "mincore failed");
3291             break;
3292         }
3293 
3294         vec_end = DIV_ROUND_UP(length, page_size);
3295         for (i = 0; i < vec_end; i++) {
3296             if (vec[i] & 0x1) {
3297                 break;
3298             }
3299         }
3300         if (i < vec_end) {
3301             error_setg(errp, "page cache still in use!");
3302             break;
3303         }
3304     }
3305 
3306     if (window) {
3307         munmap(window, length);
3308     }
3309 
3310     g_free(vec);
3311 }
3312 #endif /* __linux__ */
3313 
3314 static void coroutine_fn GRAPH_RDLOCK
3315 raw_co_invalidate_cache(BlockDriverState *bs, Error **errp)
3316 {
3317     BDRVRawState *s = bs->opaque;
3318     int ret;
3319 
3320     ret = fd_open(bs);
3321     if (ret < 0) {
3322         error_setg_errno(errp, -ret, "The file descriptor is not open");
3323         return;
3324     }
3325 
3326     if (!s->drop_cache) {
3327         return;
3328     }
3329 
3330     if (s->open_flags & O_DIRECT) {
3331         return; /* No host kernel page cache */
3332     }
3333 
3334 #if defined(__linux__)
3335     /* This sets the scene for the next syscall... */
3336     ret = bdrv_co_flush(bs);
3337     if (ret < 0) {
3338         error_setg_errno(errp, -ret, "flush failed");
3339         return;
3340     }
3341 
3342     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
3343      * process.  These limitations are okay because we just fsynced the file,
3344      * we don't use mmap, and the file should not be in use by other processes.
3345      */
3346     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
3347     if (ret != 0) { /* the return value is a positive errno */
3348         error_setg_errno(errp, ret, "fadvise failed");
3349         return;
3350     }
3351 
3352     if (s->check_cache_dropped) {
3353         check_cache_dropped(bs, errp);
3354     }
3355 #else /* __linux__ */
3356     /* Do nothing.  Live migration to a remote host with cache.direct=off is
3357      * unsupported on other host operating systems.  Cache consistency issues
3358      * may occur but no error is reported here, partly because that's the
3359      * historical behavior and partly because it's hard to differentiate valid
3360      * configurations that should not cause errors.
3361      */
3362 #endif /* !__linux__ */
3363 }
3364 
3365 static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
3366 {
3367     if (ret) {
3368         s->stats.discard_nb_failed++;
3369     } else {
3370         s->stats.discard_nb_ok++;
3371         s->stats.discard_bytes_ok += nbytes;
3372     }
3373 }
3374 
3375 /*
3376  * zone report - Get a zone block device's information in the form
3377  * of an array of zone descriptors.
3378  * zones is an array of zone descriptors to hold zone information on reply;
3379  * offset can be any byte within the entire size of the device;
3380  * nr_zones is the maximum number of sectors the command should operate on.
3381  */
3382 #if defined(CONFIG_BLKZONED)
3383 static int coroutine_fn raw_co_zone_report(BlockDriverState *bs, int64_t offset,
3384                                            unsigned int *nr_zones,
3385                                            BlockZoneDescriptor *zones) {
3386     BDRVRawState *s = bs->opaque;
3387     RawPosixAIOData acb = (RawPosixAIOData) {
3388         .bs         = bs,
3389         .aio_fildes = s->fd,
3390         .aio_type   = QEMU_AIO_ZONE_REPORT,
3391         .aio_offset = offset,
3392         .zone_report    = {
3393             .nr_zones       = nr_zones,
3394             .zones          = zones,
3395         },
3396     };
3397 
3398     trace_zbd_zone_report(bs, *nr_zones, offset >> BDRV_SECTOR_BITS);
3399     return raw_thread_pool_submit(handle_aiocb_zone_report, &acb);
3400 }
3401 #endif
3402 
3403 /*
3404  * zone management operations - Execute an operation on a zone
3405  */
3406 #if defined(CONFIG_BLKZONED)
3407 static int coroutine_fn raw_co_zone_mgmt(BlockDriverState *bs, BlockZoneOp op,
3408         int64_t offset, int64_t len) {
3409     BDRVRawState *s = bs->opaque;
3410     RawPosixAIOData acb;
3411     int64_t zone_size, zone_size_mask;
3412     const char *op_name;
3413     unsigned long zo;
3414     int ret;
3415     BlockZoneWps *wps = bs->wps;
3416     int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
3417 
3418     zone_size = bs->bl.zone_size;
3419     zone_size_mask = zone_size - 1;
3420     if (offset & zone_size_mask) {
3421         error_report("sector offset %" PRId64 " is not aligned to zone size "
3422                      "%" PRId64 "", offset / 512, zone_size / 512);
3423         return -EINVAL;
3424     }
3425 
3426     if (((offset + len) < capacity && len & zone_size_mask) ||
3427         offset + len > capacity) {
3428         error_report("number of sectors %" PRId64 " is not aligned to zone size"
3429                       " %" PRId64 "", len / 512, zone_size / 512);
3430         return -EINVAL;
3431     }
3432 
3433     uint32_t i = offset / bs->bl.zone_size;
3434     uint32_t nrz = len / bs->bl.zone_size;
3435     uint64_t *wp = &wps->wp[i];
3436     if (BDRV_ZT_IS_CONV(*wp) && len != capacity) {
3437         error_report("zone mgmt operations are not allowed for conventional zones");
3438         return -EIO;
3439     }
3440 
3441     switch (op) {
3442     case BLK_ZO_OPEN:
3443         op_name = "BLKOPENZONE";
3444         zo = BLKOPENZONE;
3445         break;
3446     case BLK_ZO_CLOSE:
3447         op_name = "BLKCLOSEZONE";
3448         zo = BLKCLOSEZONE;
3449         break;
3450     case BLK_ZO_FINISH:
3451         op_name = "BLKFINISHZONE";
3452         zo = BLKFINISHZONE;
3453         break;
3454     case BLK_ZO_RESET:
3455         op_name = "BLKRESETZONE";
3456         zo = BLKRESETZONE;
3457         break;
3458     default:
3459         error_report("Unsupported zone op: 0x%x", op);
3460         return -ENOTSUP;
3461     }
3462 
3463     acb = (RawPosixAIOData) {
3464         .bs             = bs,
3465         .aio_fildes     = s->fd,
3466         .aio_type       = QEMU_AIO_ZONE_MGMT,
3467         .aio_offset     = offset,
3468         .aio_nbytes     = len,
3469         .zone_mgmt  = {
3470             .op = zo,
3471         },
3472     };
3473 
3474     trace_zbd_zone_mgmt(bs, op_name, offset >> BDRV_SECTOR_BITS,
3475                         len >> BDRV_SECTOR_BITS);
3476     ret = raw_thread_pool_submit(handle_aiocb_zone_mgmt, &acb);
3477     if (ret != 0) {
3478         update_zones_wp(bs, s->fd, offset, nrz);
3479         error_report("ioctl %s failed %d", op_name, ret);
3480         return ret;
3481     }
3482 
3483     if (zo == BLKRESETZONE && len == capacity) {
3484         ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 1);
3485         if (ret < 0) {
3486             error_report("reporting single wp failed");
3487             return ret;
3488         }
3489     } else if (zo == BLKRESETZONE) {
3490         for (unsigned int j = 0; j < nrz; ++j) {
3491             wp[j] = offset + j * zone_size;
3492         }
3493     } else if (zo == BLKFINISHZONE) {
3494         for (unsigned int j = 0; j < nrz; ++j) {
3495             /* The zoned device allows the last zone smaller that the
3496              * zone size. */
3497             wp[j] = MIN(offset + (j + 1) * zone_size, offset + len);
3498         }
3499     }
3500 
3501     return ret;
3502 }
3503 #endif
3504 
3505 #if defined(CONFIG_BLKZONED)
3506 static int coroutine_fn raw_co_zone_append(BlockDriverState *bs,
3507                                            int64_t *offset,
3508                                            QEMUIOVector *qiov,
3509                                            BdrvRequestFlags flags) {
3510     assert(flags == 0);
3511     int64_t zone_size_mask = bs->bl.zone_size - 1;
3512     int64_t iov_len = 0;
3513     int64_t len = 0;
3514 
3515     if (*offset & zone_size_mask) {
3516         error_report("sector offset %" PRId64 " is not aligned to zone size "
3517                      "%" PRId32 "", *offset / 512, bs->bl.zone_size / 512);
3518         return -EINVAL;
3519     }
3520 
3521     int64_t wg = bs->bl.write_granularity;
3522     int64_t wg_mask = wg - 1;
3523     for (int i = 0; i < qiov->niov; i++) {
3524         iov_len = qiov->iov[i].iov_len;
3525         if (iov_len & wg_mask) {
3526             error_report("len of IOVector[%d] %" PRId64 " is not aligned to "
3527                          "block size %" PRId64 "", i, iov_len, wg);
3528             return -EINVAL;
3529         }
3530         len += iov_len;
3531     }
3532 
3533     trace_zbd_zone_append(bs, *offset >> BDRV_SECTOR_BITS);
3534     return raw_co_prw(bs, offset, len, qiov, QEMU_AIO_ZONE_APPEND);
3535 }
3536 #endif
3537 
3538 static coroutine_fn int
3539 raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes,
3540                 bool blkdev)
3541 {
3542     BDRVRawState *s = bs->opaque;
3543     RawPosixAIOData acb;
3544     int ret;
3545 
3546     acb = (RawPosixAIOData) {
3547         .bs             = bs,
3548         .aio_fildes     = s->fd,
3549         .aio_type       = QEMU_AIO_DISCARD,
3550         .aio_offset     = offset,
3551         .aio_nbytes     = bytes,
3552     };
3553 
3554     if (blkdev) {
3555         acb.aio_type |= QEMU_AIO_BLKDEV;
3556     }
3557 
3558     ret = raw_thread_pool_submit(handle_aiocb_discard, &acb);
3559     raw_account_discard(s, bytes, ret);
3560     return ret;
3561 }
3562 
3563 static coroutine_fn int
3564 raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
3565 {
3566     return raw_do_pdiscard(bs, offset, bytes, false);
3567 }
3568 
3569 static int coroutine_fn
3570 raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
3571                      BdrvRequestFlags flags, bool blkdev)
3572 {
3573     BDRVRawState *s = bs->opaque;
3574     RawPosixAIOData acb;
3575     ThreadPoolFunc *handler;
3576 
3577 #ifdef CONFIG_FALLOCATE
3578     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3579         BdrvTrackedRequest *req;
3580 
3581         /*
3582          * This is a workaround for a bug in the Linux XFS driver,
3583          * where writes submitted through the AIO interface will be
3584          * discarded if they happen beyond a concurrently running
3585          * fallocate() that increases the file length (i.e., both the
3586          * write and the fallocate() happen beyond the EOF).
3587          *
3588          * To work around it, we extend the tracked request for this
3589          * zero write until INT64_MAX (effectively infinity), and mark
3590          * it as serializing.
3591          *
3592          * We have to enable this workaround for all filesystems and
3593          * AIO modes (not just XFS with aio=native), because for
3594          * remote filesystems we do not know the host configuration.
3595          */
3596 
3597         req = bdrv_co_get_self_request(bs);
3598         assert(req);
3599         assert(req->type == BDRV_TRACKED_WRITE);
3600         assert(req->offset <= offset);
3601         assert(req->offset + req->bytes >= offset + bytes);
3602 
3603         req->bytes = BDRV_MAX_LENGTH - req->offset;
3604 
3605         bdrv_check_request(req->offset, req->bytes, &error_abort);
3606 
3607         bdrv_make_request_serialising(req, bs->bl.request_alignment);
3608     }
3609 #endif
3610 
3611     acb = (RawPosixAIOData) {
3612         .bs             = bs,
3613         .aio_fildes     = s->fd,
3614         .aio_type       = QEMU_AIO_WRITE_ZEROES,
3615         .aio_offset     = offset,
3616         .aio_nbytes     = bytes,
3617     };
3618 
3619     if (blkdev) {
3620         acb.aio_type |= QEMU_AIO_BLKDEV;
3621     }
3622     if (flags & BDRV_REQ_NO_FALLBACK) {
3623         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
3624     }
3625 
3626     if (flags & BDRV_REQ_MAY_UNMAP) {
3627         acb.aio_type |= QEMU_AIO_DISCARD;
3628         handler = handle_aiocb_write_zeroes_unmap;
3629     } else {
3630         handler = handle_aiocb_write_zeroes;
3631     }
3632 
3633     return raw_thread_pool_submit(handler, &acb);
3634 }
3635 
3636 static int coroutine_fn raw_co_pwrite_zeroes(
3637     BlockDriverState *bs, int64_t offset,
3638     int64_t bytes, BdrvRequestFlags flags)
3639 {
3640     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
3641 }
3642 
3643 static int coroutine_fn
3644 raw_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3645 {
3646     return 0;
3647 }
3648 
3649 static ImageInfoSpecific *raw_get_specific_info(BlockDriverState *bs,
3650                                                 Error **errp)
3651 {
3652     ImageInfoSpecificFile *file_info = g_new0(ImageInfoSpecificFile, 1);
3653     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
3654 
3655     *spec_info = (ImageInfoSpecific){
3656         .type = IMAGE_INFO_SPECIFIC_KIND_FILE,
3657         .u.file.data = file_info,
3658     };
3659 
3660 #ifdef FS_IOC_FSGETXATTR
3661     {
3662         BDRVRawState *s = bs->opaque;
3663         struct fsxattr attr;
3664         int ret;
3665 
3666         ret = ioctl(s->fd, FS_IOC_FSGETXATTR, &attr);
3667         if (!ret && attr.fsx_extsize != 0) {
3668             file_info->has_extent_size_hint = true;
3669             file_info->extent_size_hint = attr.fsx_extsize;
3670         }
3671     }
3672 #endif
3673 
3674     return spec_info;
3675 }
3676 
3677 static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
3678 {
3679     BDRVRawState *s = bs->opaque;
3680     return (BlockStatsSpecificFile) {
3681         .discard_nb_ok = s->stats.discard_nb_ok,
3682         .discard_nb_failed = s->stats.discard_nb_failed,
3683         .discard_bytes_ok = s->stats.discard_bytes_ok,
3684     };
3685 }
3686 
3687 static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3688 {
3689     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3690 
3691     stats->driver = BLOCKDEV_DRIVER_FILE;
3692     stats->u.file = get_blockstats_specific_file(bs);
3693 
3694     return stats;
3695 }
3696 
3697 #if defined(HAVE_HOST_BLOCK_DEVICE)
3698 static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3699 {
3700     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3701 
3702     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3703     stats->u.host_device = get_blockstats_specific_file(bs);
3704 
3705     return stats;
3706 }
3707 #endif /* HAVE_HOST_BLOCK_DEVICE */
3708 
3709 static QemuOptsList raw_create_opts = {
3710     .name = "raw-create-opts",
3711     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3712     .desc = {
3713         {
3714             .name = BLOCK_OPT_SIZE,
3715             .type = QEMU_OPT_SIZE,
3716             .help = "Virtual disk size"
3717         },
3718         {
3719             .name = BLOCK_OPT_NOCOW,
3720             .type = QEMU_OPT_BOOL,
3721             .help = "Turn off copy-on-write (valid only on btrfs)"
3722         },
3723         {
3724             .name = BLOCK_OPT_PREALLOC,
3725             .type = QEMU_OPT_STRING,
3726             .help = "Preallocation mode (allowed values: off"
3727 #ifdef CONFIG_POSIX_FALLOCATE
3728                     ", falloc"
3729 #endif
3730                     ", full)"
3731         },
3732         {
3733             .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3734             .type = QEMU_OPT_SIZE,
3735             .help = "Extent size hint for the image file, 0 to disable"
3736         },
3737         { /* end of list */ }
3738     }
3739 };
3740 
3741 static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3742                           Error **errp)
3743 {
3744     BDRVRawState *s = bs->opaque;
3745     int input_flags = s->reopen_state ? s->reopen_state->flags : bs->open_flags;
3746     int open_flags;
3747     int ret;
3748 
3749     /* We may need a new fd if auto-read-only switches the mode */
3750     ret = raw_reconfigure_getfd(bs, input_flags, &open_flags, perm, errp);
3751     if (ret < 0) {
3752         return ret;
3753     } else if (ret != s->fd) {
3754         Error *local_err = NULL;
3755 
3756         /*
3757          * Fail already check_perm() if we can't get a working O_DIRECT
3758          * alignment with the new fd.
3759          */
3760         raw_probe_alignment(bs, ret, &local_err);
3761         if (local_err) {
3762             error_propagate(errp, local_err);
3763             return -EINVAL;
3764         }
3765 
3766         s->perm_change_fd = ret;
3767         s->perm_change_flags = open_flags;
3768     }
3769 
3770     /* Prepare permissions on old fd to avoid conflicts between old and new,
3771      * but keep everything locked that new will need. */
3772     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
3773     if (ret < 0) {
3774         goto fail;
3775     }
3776 
3777     /* Copy locks to the new fd */
3778     if (s->perm_change_fd && s->use_lock) {
3779         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
3780                                    false, errp);
3781         if (ret < 0) {
3782             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3783             goto fail;
3784         }
3785     }
3786     return 0;
3787 
3788 fail:
3789     if (s->perm_change_fd) {
3790         qemu_close(s->perm_change_fd);
3791     }
3792     s->perm_change_fd = 0;
3793     return ret;
3794 }
3795 
3796 static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3797 {
3798     BDRVRawState *s = bs->opaque;
3799 
3800     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3801      * called after .bdrv_reopen_commit) */
3802     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
3803         qemu_close(s->fd);
3804         s->fd = s->perm_change_fd;
3805         s->open_flags = s->perm_change_flags;
3806     }
3807     s->perm_change_fd = 0;
3808 
3809     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3810     s->perm = perm;
3811     s->shared_perm = shared;
3812 }
3813 
3814 static void raw_abort_perm_update(BlockDriverState *bs)
3815 {
3816     BDRVRawState *s = bs->opaque;
3817 
3818     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3819      * the file descriptor. */
3820     if (s->perm_change_fd) {
3821         qemu_close(s->perm_change_fd);
3822     }
3823     s->perm_change_fd = 0;
3824 
3825     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3826 }
3827 
3828 static int coroutine_fn GRAPH_RDLOCK raw_co_copy_range_from(
3829         BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
3830         BdrvChild *dst, int64_t dst_offset, int64_t bytes,
3831         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
3832 {
3833     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3834                                  read_flags, write_flags);
3835 }
3836 
3837 static int coroutine_fn GRAPH_RDLOCK
3838 raw_co_copy_range_to(BlockDriverState *bs,
3839                      BdrvChild *src, int64_t src_offset,
3840                      BdrvChild *dst, int64_t dst_offset,
3841                      int64_t bytes, BdrvRequestFlags read_flags,
3842                      BdrvRequestFlags write_flags)
3843 {
3844     RawPosixAIOData acb;
3845     BDRVRawState *s = bs->opaque;
3846     BDRVRawState *src_s;
3847 
3848     assert(dst->bs == bs);
3849     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
3850         return -ENOTSUP;
3851     }
3852 
3853     src_s = src->bs->opaque;
3854     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
3855         return -EIO;
3856     }
3857 
3858     acb = (RawPosixAIOData) {
3859         .bs             = bs,
3860         .aio_type       = QEMU_AIO_COPY_RANGE,
3861         .aio_fildes     = src_s->fd,
3862         .aio_offset     = src_offset,
3863         .aio_nbytes     = bytes,
3864         .copy_range     = {
3865             .aio_fd2        = s->fd,
3866             .aio_offset2    = dst_offset,
3867         },
3868     };
3869 
3870     return raw_thread_pool_submit(handle_aiocb_copy_range, &acb);
3871 }
3872 
3873 BlockDriver bdrv_file = {
3874     .format_name = "file",
3875     .protocol_name = "file",
3876     .instance_size = sizeof(BDRVRawState),
3877     .bdrv_needs_filename = true,
3878     .bdrv_probe = NULL, /* no probe for protocols */
3879     .bdrv_parse_filename = raw_parse_filename,
3880     .bdrv_file_open = raw_open,
3881     .bdrv_reopen_prepare = raw_reopen_prepare,
3882     .bdrv_reopen_commit = raw_reopen_commit,
3883     .bdrv_reopen_abort = raw_reopen_abort,
3884     .bdrv_close = raw_close,
3885     .bdrv_co_create = raw_co_create,
3886     .bdrv_co_create_opts = raw_co_create_opts,
3887     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3888     .bdrv_co_block_status = raw_co_block_status,
3889     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3890     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
3891     .bdrv_co_delete_file = raw_co_delete_file,
3892 
3893     .bdrv_co_preadv         = raw_co_preadv,
3894     .bdrv_co_pwritev        = raw_co_pwritev,
3895     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3896     .bdrv_co_pdiscard       = raw_co_pdiscard,
3897     .bdrv_co_copy_range_from = raw_co_copy_range_from,
3898     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3899     .bdrv_refresh_limits = raw_refresh_limits,
3900 
3901     .bdrv_co_truncate                   = raw_co_truncate,
3902     .bdrv_co_getlength                  = raw_co_getlength,
3903     .bdrv_co_get_info                   = raw_co_get_info,
3904     .bdrv_get_specific_info             = raw_get_specific_info,
3905     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
3906     .bdrv_get_specific_stats = raw_get_specific_stats,
3907     .bdrv_check_perm = raw_check_perm,
3908     .bdrv_set_perm   = raw_set_perm,
3909     .bdrv_abort_perm_update = raw_abort_perm_update,
3910     .create_opts = &raw_create_opts,
3911     .mutable_opts = mutable_opts,
3912 };
3913 
3914 /***********************************************/
3915 /* host device */
3916 
3917 #if defined(HAVE_HOST_BLOCK_DEVICE)
3918 
3919 #if defined(__APPLE__) && defined(__MACH__)
3920 static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3921                                 CFIndex maxPathSize, int flags);
3922 
3923 #if !defined(MAC_OS_VERSION_12_0) \
3924     || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3925 #define IOMainPort IOMasterPort
3926 #endif
3927 
3928 static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3929 {
3930     kern_return_t kernResult = KERN_FAILURE;
3931     mach_port_t mainPort;
3932     CFMutableDictionaryRef  classesToMatch;
3933     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3934     char *mediaType = NULL;
3935 
3936     kernResult = IOMainPort(MACH_PORT_NULL, &mainPort);
3937     if ( KERN_SUCCESS != kernResult ) {
3938         printf("IOMainPort returned %d\n", kernResult);
3939     }
3940 
3941     int index;
3942     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3943         classesToMatch = IOServiceMatching(matching_array[index]);
3944         if (classesToMatch == NULL) {
3945             error_report("IOServiceMatching returned NULL for %s",
3946                          matching_array[index]);
3947             continue;
3948         }
3949         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3950                              kCFBooleanTrue);
3951         kernResult = IOServiceGetMatchingServices(mainPort, classesToMatch,
3952                                                   mediaIterator);
3953         if (kernResult != KERN_SUCCESS) {
3954             error_report("Note: IOServiceGetMatchingServices returned %d",
3955                          kernResult);
3956             continue;
3957         }
3958 
3959         /* If a match was found, leave the loop */
3960         if (*mediaIterator != 0) {
3961             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3962             mediaType = g_strdup(matching_array[index]);
3963             break;
3964         }
3965     }
3966     return mediaType;
3967 }
3968 
3969 kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3970                          CFIndex maxPathSize, int flags)
3971 {
3972     io_object_t     nextMedia;
3973     kern_return_t   kernResult = KERN_FAILURE;
3974     *bsdPath = '\0';
3975     nextMedia = IOIteratorNext( mediaIterator );
3976     if ( nextMedia )
3977     {
3978         CFTypeRef   bsdPathAsCFString;
3979     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3980         if ( bsdPathAsCFString ) {
3981             size_t devPathLength;
3982             strcpy( bsdPath, _PATH_DEV );
3983             if (flags & BDRV_O_NOCACHE) {
3984                 strcat(bsdPath, "r");
3985             }
3986             devPathLength = strlen( bsdPath );
3987             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3988                 kernResult = KERN_SUCCESS;
3989             }
3990             CFRelease( bsdPathAsCFString );
3991         }
3992         IOObjectRelease( nextMedia );
3993     }
3994 
3995     return kernResult;
3996 }
3997 
3998 /* Sets up a real cdrom for use in QEMU */
3999 static bool setup_cdrom(char *bsd_path, Error **errp)
4000 {
4001     int index, num_of_test_partitions = 2, fd;
4002     char test_partition[MAXPATHLEN];
4003     bool partition_found = false;
4004 
4005     /* look for a working partition */
4006     for (index = 0; index < num_of_test_partitions; index++) {
4007         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
4008                  index);
4009         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
4010         if (fd >= 0) {
4011             partition_found = true;
4012             qemu_close(fd);
4013             break;
4014         }
4015     }
4016 
4017     /* if a working partition on the device was not found */
4018     if (partition_found == false) {
4019         error_setg(errp, "Failed to find a working partition on disc");
4020     } else {
4021         trace_file_setup_cdrom(test_partition);
4022         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
4023     }
4024     return partition_found;
4025 }
4026 
4027 /* Prints directions on mounting and unmounting a device */
4028 static void print_unmounting_directions(const char *file_name)
4029 {
4030     error_report("If device %s is mounted on the desktop, unmount"
4031                  " it first before using it in QEMU", file_name);
4032     error_report("Command to unmount device: diskutil unmountDisk %s",
4033                  file_name);
4034     error_report("Command to mount device: diskutil mountDisk %s", file_name);
4035 }
4036 
4037 #endif /* defined(__APPLE__) && defined(__MACH__) */
4038 
4039 static int hdev_probe_device(const char *filename)
4040 {
4041     struct stat st;
4042 
4043     /* allow a dedicated CD-ROM driver to match with a higher priority */
4044     if (strstart(filename, "/dev/cdrom", NULL))
4045         return 50;
4046 
4047     if (stat(filename, &st) >= 0 &&
4048             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
4049         return 100;
4050     }
4051 
4052     return 0;
4053 }
4054 
4055 static void hdev_parse_filename(const char *filename, QDict *options,
4056                                 Error **errp)
4057 {
4058     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
4059 }
4060 
4061 static bool hdev_is_sg(BlockDriverState *bs)
4062 {
4063 
4064 #if defined(__linux__)
4065 
4066     BDRVRawState *s = bs->opaque;
4067     struct stat st;
4068     struct sg_scsi_id scsiid;
4069     int sg_version;
4070     int ret;
4071 
4072     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
4073         return false;
4074     }
4075 
4076     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
4077     if (ret < 0) {
4078         return false;
4079     }
4080 
4081     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
4082     if (ret >= 0) {
4083         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
4084         return true;
4085     }
4086 
4087 #endif
4088 
4089     return false;
4090 }
4091 
4092 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
4093                      Error **errp)
4094 {
4095     BDRVRawState *s = bs->opaque;
4096     int ret;
4097 
4098 #if defined(__APPLE__) && defined(__MACH__)
4099     /*
4100      * Caution: while qdict_get_str() is fine, getting non-string types
4101      * would require more care.  When @options come from -blockdev or
4102      * blockdev_add, its members are typed according to the QAPI
4103      * schema, but when they come from -drive, they're all QString.
4104      */
4105     const char *filename = qdict_get_str(options, "filename");
4106     char bsd_path[MAXPATHLEN] = "";
4107     bool error_occurred = false;
4108 
4109     /* If using a real cdrom */
4110     if (strcmp(filename, "/dev/cdrom") == 0) {
4111         char *mediaType = NULL;
4112         kern_return_t ret_val;
4113         io_iterator_t mediaIterator = 0;
4114 
4115         mediaType = FindEjectableOpticalMedia(&mediaIterator);
4116         if (mediaType == NULL) {
4117             error_setg(errp, "Please make sure your CD/DVD is in the optical"
4118                        " drive");
4119             error_occurred = true;
4120             goto hdev_open_Mac_error;
4121         }
4122 
4123         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
4124         if (ret_val != KERN_SUCCESS) {
4125             error_setg(errp, "Could not get BSD path for optical drive");
4126             error_occurred = true;
4127             goto hdev_open_Mac_error;
4128         }
4129 
4130         /* If a real optical drive was not found */
4131         if (bsd_path[0] == '\0') {
4132             error_setg(errp, "Failed to obtain bsd path for optical drive");
4133             error_occurred = true;
4134             goto hdev_open_Mac_error;
4135         }
4136 
4137         /* If using a cdrom disc and finding a partition on the disc failed */
4138         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
4139             setup_cdrom(bsd_path, errp) == false) {
4140             print_unmounting_directions(bsd_path);
4141             error_occurred = true;
4142             goto hdev_open_Mac_error;
4143         }
4144 
4145         qdict_put_str(options, "filename", bsd_path);
4146 
4147 hdev_open_Mac_error:
4148         g_free(mediaType);
4149         if (mediaIterator) {
4150             IOObjectRelease(mediaIterator);
4151         }
4152         if (error_occurred) {
4153             return -ENOENT;
4154         }
4155     }
4156 #endif /* defined(__APPLE__) && defined(__MACH__) */
4157 
4158     s->type = FTYPE_FILE;
4159 
4160     ret = raw_open_common(bs, options, flags, 0, true, errp);
4161     if (ret < 0) {
4162 #if defined(__APPLE__) && defined(__MACH__)
4163         if (*bsd_path) {
4164             filename = bsd_path;
4165         }
4166         /* if a physical device experienced an error while being opened */
4167         if (strncmp(filename, "/dev/", 5) == 0) {
4168             print_unmounting_directions(filename);
4169         }
4170 #endif /* defined(__APPLE__) && defined(__MACH__) */
4171         return ret;
4172     }
4173 
4174     /* Since this does ioctl the device must be already opened */
4175     bs->sg = hdev_is_sg(bs);
4176 
4177     return ret;
4178 }
4179 
4180 #if defined(__linux__)
4181 static int coroutine_fn
4182 hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4183 {
4184     BDRVRawState *s = bs->opaque;
4185     RawPosixAIOData acb;
4186     int ret;
4187 
4188     ret = fd_open(bs);
4189     if (ret < 0) {
4190         return ret;
4191     }
4192 
4193     if (req == SG_IO && s->pr_mgr) {
4194         struct sg_io_hdr *io_hdr = buf;
4195         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
4196             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
4197             return pr_manager_execute(s->pr_mgr, qemu_get_current_aio_context(),
4198                                       s->fd, io_hdr);
4199         }
4200     }
4201 
4202     acb = (RawPosixAIOData) {
4203         .bs         = bs,
4204         .aio_type   = QEMU_AIO_IOCTL,
4205         .aio_fildes = s->fd,
4206         .aio_offset = 0,
4207         .ioctl      = {
4208             .buf        = buf,
4209             .cmd        = req,
4210         },
4211     };
4212 
4213     return raw_thread_pool_submit(handle_aiocb_ioctl, &acb);
4214 }
4215 #endif /* linux */
4216 
4217 static coroutine_fn int
4218 hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
4219 {
4220     BDRVRawState *s = bs->opaque;
4221     int ret;
4222 
4223     ret = fd_open(bs);
4224     if (ret < 0) {
4225         raw_account_discard(s, bytes, ret);
4226         return ret;
4227     }
4228     return raw_do_pdiscard(bs, offset, bytes, true);
4229 }
4230 
4231 static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
4232     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
4233 {
4234     int rc;
4235 
4236     rc = fd_open(bs);
4237     if (rc < 0) {
4238         return rc;
4239     }
4240 
4241     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
4242 }
4243 
4244 static BlockDriver bdrv_host_device = {
4245     .format_name        = "host_device",
4246     .protocol_name        = "host_device",
4247     .instance_size      = sizeof(BDRVRawState),
4248     .bdrv_needs_filename = true,
4249     .bdrv_probe_device  = hdev_probe_device,
4250     .bdrv_parse_filename = hdev_parse_filename,
4251     .bdrv_file_open     = hdev_open,
4252     .bdrv_close         = raw_close,
4253     .bdrv_reopen_prepare = raw_reopen_prepare,
4254     .bdrv_reopen_commit  = raw_reopen_commit,
4255     .bdrv_reopen_abort   = raw_reopen_abort,
4256     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4257     .create_opts         = &bdrv_create_opts_simple,
4258     .mutable_opts        = mutable_opts,
4259     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
4260     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
4261 
4262     .bdrv_co_preadv         = raw_co_preadv,
4263     .bdrv_co_pwritev        = raw_co_pwritev,
4264     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
4265     .bdrv_co_pdiscard       = hdev_co_pdiscard,
4266     .bdrv_co_copy_range_from = raw_co_copy_range_from,
4267     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
4268     .bdrv_refresh_limits = raw_refresh_limits,
4269 
4270     .bdrv_co_truncate                   = raw_co_truncate,
4271     .bdrv_co_getlength                  = raw_co_getlength,
4272     .bdrv_co_get_info                   = raw_co_get_info,
4273     .bdrv_get_specific_info             = raw_get_specific_info,
4274     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
4275     .bdrv_get_specific_stats = hdev_get_specific_stats,
4276     .bdrv_check_perm = raw_check_perm,
4277     .bdrv_set_perm   = raw_set_perm,
4278     .bdrv_abort_perm_update = raw_abort_perm_update,
4279     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
4280     .bdrv_probe_geometry = hdev_probe_geometry,
4281 
4282     /* generic scsi device */
4283 #ifdef __linux__
4284     .bdrv_co_ioctl          = hdev_co_ioctl,
4285 #endif
4286 
4287     /* zoned device */
4288 #if defined(CONFIG_BLKZONED)
4289     /* zone management operations */
4290     .bdrv_co_zone_report = raw_co_zone_report,
4291     .bdrv_co_zone_mgmt = raw_co_zone_mgmt,
4292     .bdrv_co_zone_append = raw_co_zone_append,
4293 #endif
4294 };
4295 
4296 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4297 static void cdrom_parse_filename(const char *filename, QDict *options,
4298                                  Error **errp)
4299 {
4300     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
4301 }
4302 
4303 static void cdrom_refresh_limits(BlockDriverState *bs, Error **errp)
4304 {
4305     bs->bl.has_variable_length = true;
4306     raw_refresh_limits(bs, errp);
4307 }
4308 #endif
4309 
4310 #ifdef __linux__
4311 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4312                       Error **errp)
4313 {
4314     BDRVRawState *s = bs->opaque;
4315 
4316     s->type = FTYPE_CD;
4317 
4318     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
4319     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
4320 }
4321 
4322 static int cdrom_probe_device(const char *filename)
4323 {
4324     int fd, ret;
4325     int prio = 0;
4326     struct stat st;
4327 
4328     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
4329     if (fd < 0) {
4330         goto out;
4331     }
4332     ret = fstat(fd, &st);
4333     if (ret == -1 || !S_ISBLK(st.st_mode)) {
4334         goto outc;
4335     }
4336 
4337     /* Attempt to detect via a CDROM specific ioctl */
4338     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
4339     if (ret >= 0)
4340         prio = 100;
4341 
4342 outc:
4343     qemu_close(fd);
4344 out:
4345     return prio;
4346 }
4347 
4348 static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
4349 {
4350     BDRVRawState *s = bs->opaque;
4351     int ret;
4352 
4353     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
4354     return ret == CDS_DISC_OK;
4355 }
4356 
4357 static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
4358 {
4359     BDRVRawState *s = bs->opaque;
4360 
4361     if (eject_flag) {
4362         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
4363             perror("CDROMEJECT");
4364     } else {
4365         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
4366             perror("CDROMEJECT");
4367     }
4368 }
4369 
4370 static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
4371 {
4372     BDRVRawState *s = bs->opaque;
4373 
4374     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
4375         /*
4376          * Note: an error can happen if the distribution automatically
4377          * mounts the CD-ROM
4378          */
4379         /* perror("CDROM_LOCKDOOR"); */
4380     }
4381 }
4382 
4383 static BlockDriver bdrv_host_cdrom = {
4384     .format_name        = "host_cdrom",
4385     .protocol_name      = "host_cdrom",
4386     .instance_size      = sizeof(BDRVRawState),
4387     .bdrv_needs_filename = true,
4388     .bdrv_probe_device	= cdrom_probe_device,
4389     .bdrv_parse_filename = cdrom_parse_filename,
4390     .bdrv_file_open     = cdrom_open,
4391     .bdrv_close         = raw_close,
4392     .bdrv_reopen_prepare = raw_reopen_prepare,
4393     .bdrv_reopen_commit  = raw_reopen_commit,
4394     .bdrv_reopen_abort   = raw_reopen_abort,
4395     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4396     .create_opts         = &bdrv_create_opts_simple,
4397     .mutable_opts        = mutable_opts,
4398     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
4399 
4400     .bdrv_co_preadv         = raw_co_preadv,
4401     .bdrv_co_pwritev        = raw_co_pwritev,
4402     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
4403     .bdrv_refresh_limits    = cdrom_refresh_limits,
4404 
4405     .bdrv_co_truncate                   = raw_co_truncate,
4406     .bdrv_co_getlength                  = raw_co_getlength,
4407     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
4408 
4409     /* removable device support */
4410     .bdrv_co_is_inserted    = cdrom_co_is_inserted,
4411     .bdrv_co_eject          = cdrom_co_eject,
4412     .bdrv_co_lock_medium    = cdrom_co_lock_medium,
4413 
4414     /* generic scsi device */
4415     .bdrv_co_ioctl      = hdev_co_ioctl,
4416 };
4417 #endif /* __linux__ */
4418 
4419 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
4420 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4421                       Error **errp)
4422 {
4423     BDRVRawState *s = bs->opaque;
4424     int ret;
4425 
4426     s->type = FTYPE_CD;
4427 
4428     ret = raw_open_common(bs, options, flags, 0, true, errp);
4429     if (ret) {
4430         return ret;
4431     }
4432 
4433     /* make sure the door isn't locked at this time */
4434     ioctl(s->fd, CDIOCALLOW);
4435     return 0;
4436 }
4437 
4438 static int cdrom_probe_device(const char *filename)
4439 {
4440     if (strstart(filename, "/dev/cd", NULL) ||
4441             strstart(filename, "/dev/acd", NULL))
4442         return 100;
4443     return 0;
4444 }
4445 
4446 static int cdrom_reopen(BlockDriverState *bs)
4447 {
4448     BDRVRawState *s = bs->opaque;
4449     int fd;
4450 
4451     /*
4452      * Force reread of possibly changed/newly loaded disc,
4453      * FreeBSD seems to not notice sometimes...
4454      */
4455     if (s->fd >= 0)
4456         qemu_close(s->fd);
4457     fd = qemu_open(bs->filename, s->open_flags, NULL);
4458     if (fd < 0) {
4459         s->fd = -1;
4460         return -EIO;
4461     }
4462     s->fd = fd;
4463 
4464     /* make sure the door isn't locked at this time */
4465     ioctl(s->fd, CDIOCALLOW);
4466     return 0;
4467 }
4468 
4469 static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
4470 {
4471     return raw_getlength(bs) > 0;
4472 }
4473 
4474 static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
4475 {
4476     BDRVRawState *s = bs->opaque;
4477 
4478     if (s->fd < 0)
4479         return;
4480 
4481     (void) ioctl(s->fd, CDIOCALLOW);
4482 
4483     if (eject_flag) {
4484         if (ioctl(s->fd, CDIOCEJECT) < 0)
4485             perror("CDIOCEJECT");
4486     } else {
4487         if (ioctl(s->fd, CDIOCCLOSE) < 0)
4488             perror("CDIOCCLOSE");
4489     }
4490 
4491     cdrom_reopen(bs);
4492 }
4493 
4494 static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
4495 {
4496     BDRVRawState *s = bs->opaque;
4497 
4498     if (s->fd < 0)
4499         return;
4500     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
4501         /*
4502          * Note: an error can happen if the distribution automatically
4503          * mounts the CD-ROM
4504          */
4505         /* perror("CDROM_LOCKDOOR"); */
4506     }
4507 }
4508 
4509 static BlockDriver bdrv_host_cdrom = {
4510     .format_name        = "host_cdrom",
4511     .protocol_name      = "host_cdrom",
4512     .instance_size      = sizeof(BDRVRawState),
4513     .bdrv_needs_filename = true,
4514     .bdrv_probe_device	= cdrom_probe_device,
4515     .bdrv_parse_filename = cdrom_parse_filename,
4516     .bdrv_file_open     = cdrom_open,
4517     .bdrv_close         = raw_close,
4518     .bdrv_reopen_prepare = raw_reopen_prepare,
4519     .bdrv_reopen_commit  = raw_reopen_commit,
4520     .bdrv_reopen_abort   = raw_reopen_abort,
4521     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4522     .create_opts         = &bdrv_create_opts_simple,
4523     .mutable_opts       = mutable_opts,
4524 
4525     .bdrv_co_preadv         = raw_co_preadv,
4526     .bdrv_co_pwritev        = raw_co_pwritev,
4527     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
4528     .bdrv_refresh_limits    = cdrom_refresh_limits,
4529 
4530     .bdrv_co_truncate                   = raw_co_truncate,
4531     .bdrv_co_getlength                  = raw_co_getlength,
4532     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
4533 
4534     /* removable device support */
4535     .bdrv_co_is_inserted     = cdrom_co_is_inserted,
4536     .bdrv_co_eject           = cdrom_co_eject,
4537     .bdrv_co_lock_medium     = cdrom_co_lock_medium,
4538 };
4539 #endif /* __FreeBSD__ */
4540 
4541 #endif /* HAVE_HOST_BLOCK_DEVICE */
4542 
4543 static void bdrv_file_init(void)
4544 {
4545     /*
4546      * Register all the drivers.  Note that order is important, the driver
4547      * registered last will get probed first.
4548      */
4549     bdrv_register(&bdrv_file);
4550 #if defined(HAVE_HOST_BLOCK_DEVICE)
4551     bdrv_register(&bdrv_host_device);
4552 #ifdef __linux__
4553     bdrv_register(&bdrv_host_cdrom);
4554 #endif
4555 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4556     bdrv_register(&bdrv_host_cdrom);
4557 #endif
4558 #endif /* HAVE_HOST_BLOCK_DEVICE */
4559 }
4560 
4561 block_init(bdrv_file_init);
4562