xref: /openbmc/qemu/block/file-posix.c (revision 2f3a57ee47df970d19fa5b324d44aab857d43517)
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 "qemu-common.h"
27 #include "qapi/error.h"
28 #include "qemu/cutils.h"
29 #include "qemu/error-report.h"
30 #include "block/block_int.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/units.h"
34 #include "trace.h"
35 #include "block/thread-pool.h"
36 #include "qemu/iov.h"
37 #include "block/raw-aio.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
40 
41 #include "scsi/pr-manager.h"
42 #include "scsi/constants.h"
43 
44 #if defined(__APPLE__) && (__MACH__)
45 #include <paths.h>
46 #include <sys/param.h>
47 #include <IOKit/IOKitLib.h>
48 #include <IOKit/IOBSD.h>
49 #include <IOKit/storage/IOMediaBSDClient.h>
50 #include <IOKit/storage/IOMedia.h>
51 #include <IOKit/storage/IOCDMedia.h>
52 //#include <IOKit/storage/IOCDTypes.h>
53 #include <IOKit/storage/IODVDMedia.h>
54 #include <CoreFoundation/CoreFoundation.h>
55 #endif
56 
57 #ifdef __sun__
58 #define _POSIX_PTHREAD_SEMANTICS 1
59 #include <sys/dkio.h>
60 #endif
61 #ifdef __linux__
62 #include <sys/ioctl.h>
63 #include <sys/param.h>
64 #include <sys/syscall.h>
65 #include <linux/cdrom.h>
66 #include <linux/fd.h>
67 #include <linux/fs.h>
68 #include <linux/hdreg.h>
69 #include <scsi/sg.h>
70 #ifdef __s390__
71 #include <asm/dasd.h>
72 #endif
73 #ifndef FS_NOCOW_FL
74 #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
75 #endif
76 #endif
77 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
78 #include <linux/falloc.h>
79 #endif
80 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
81 #include <sys/disk.h>
82 #include <sys/cdio.h>
83 #endif
84 
85 #ifdef __OpenBSD__
86 #include <sys/ioctl.h>
87 #include <sys/disklabel.h>
88 #include <sys/dkio.h>
89 #endif
90 
91 #ifdef __NetBSD__
92 #include <sys/ioctl.h>
93 #include <sys/disklabel.h>
94 #include <sys/dkio.h>
95 #include <sys/disk.h>
96 #endif
97 
98 #ifdef __DragonFly__
99 #include <sys/ioctl.h>
100 #include <sys/diskslice.h>
101 #endif
102 
103 #ifdef CONFIG_XFS
104 #include <xfs/xfs.h>
105 #endif
106 
107 #include "trace.h"
108 
109 /* OS X does not have O_DSYNC */
110 #ifndef O_DSYNC
111 #ifdef O_SYNC
112 #define O_DSYNC O_SYNC
113 #elif defined(O_FSYNC)
114 #define O_DSYNC O_FSYNC
115 #endif
116 #endif
117 
118 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
119 #ifndef O_DIRECT
120 #define O_DIRECT O_DSYNC
121 #endif
122 
123 #define FTYPE_FILE   0
124 #define FTYPE_CD     1
125 
126 #define MAX_BLOCKSIZE	4096
127 
128 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
129  * leaving a few more bytes for its future use. */
130 #define RAW_LOCK_PERM_BASE             100
131 #define RAW_LOCK_SHARED_BASE           200
132 
133 typedef struct BDRVRawState {
134     int fd;
135     bool use_lock;
136     int type;
137     int open_flags;
138     size_t buf_align;
139 
140     /* The current permissions. */
141     uint64_t perm;
142     uint64_t shared_perm;
143 
144     /* The perms bits whose corresponding bytes are already locked in
145      * s->fd. */
146     uint64_t locked_perm;
147     uint64_t locked_shared_perm;
148 
149     int perm_change_fd;
150     int perm_change_flags;
151     BDRVReopenState *reopen_state;
152 
153 #ifdef CONFIG_XFS
154     bool is_xfs:1;
155 #endif
156     bool has_discard:1;
157     bool has_write_zeroes:1;
158     bool discard_zeroes:1;
159     bool use_linux_aio:1;
160     bool use_linux_io_uring:1;
161     bool page_cache_inconsistent:1;
162     bool has_fallocate;
163     bool needs_alignment;
164     bool drop_cache;
165     bool check_cache_dropped;
166     struct {
167         uint64_t discard_nb_ok;
168         uint64_t discard_nb_failed;
169         uint64_t discard_bytes_ok;
170     } stats;
171 
172     PRManager *pr_mgr;
173 } BDRVRawState;
174 
175 typedef struct BDRVRawReopenState {
176     int fd;
177     int open_flags;
178     bool drop_cache;
179     bool check_cache_dropped;
180 } BDRVRawReopenState;
181 
182 static int fd_open(BlockDriverState *bs);
183 static int64_t raw_getlength(BlockDriverState *bs);
184 
185 typedef struct RawPosixAIOData {
186     BlockDriverState *bs;
187     int aio_type;
188     int aio_fildes;
189 
190     off_t aio_offset;
191     uint64_t aio_nbytes;
192 
193     union {
194         struct {
195             struct iovec *iov;
196             int niov;
197         } io;
198         struct {
199             uint64_t cmd;
200             void *buf;
201         } ioctl;
202         struct {
203             int aio_fd2;
204             off_t aio_offset2;
205         } copy_range;
206         struct {
207             PreallocMode prealloc;
208             Error **errp;
209         } truncate;
210     };
211 } RawPosixAIOData;
212 
213 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
214 static int cdrom_reopen(BlockDriverState *bs);
215 #endif
216 
217 #if defined(__NetBSD__)
218 static int raw_normalize_devicepath(const char **filename, Error **errp)
219 {
220     static char namebuf[PATH_MAX];
221     const char *dp, *fname;
222     struct stat sb;
223 
224     fname = *filename;
225     dp = strrchr(fname, '/');
226     if (lstat(fname, &sb) < 0) {
227         error_setg_file_open(errp, errno, fname);
228         return -errno;
229     }
230 
231     if (!S_ISBLK(sb.st_mode)) {
232         return 0;
233     }
234 
235     if (dp == NULL) {
236         snprintf(namebuf, PATH_MAX, "r%s", fname);
237     } else {
238         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
239             (int)(dp - fname), fname, dp + 1);
240     }
241     *filename = namebuf;
242     warn_report("%s is a block device, using %s", fname, *filename);
243 
244     return 0;
245 }
246 #else
247 static int raw_normalize_devicepath(const char **filename, Error **errp)
248 {
249     return 0;
250 }
251 #endif
252 
253 /*
254  * Get logical block size via ioctl. On success store it in @sector_size_p.
255  */
256 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
257 {
258     unsigned int sector_size;
259     bool success = false;
260     int i;
261 
262     errno = ENOTSUP;
263     static const unsigned long ioctl_list[] = {
264 #ifdef BLKSSZGET
265         BLKSSZGET,
266 #endif
267 #ifdef DKIOCGETBLOCKSIZE
268         DKIOCGETBLOCKSIZE,
269 #endif
270 #ifdef DIOCGSECTORSIZE
271         DIOCGSECTORSIZE,
272 #endif
273     };
274 
275     /* Try a few ioctls to get the right size */
276     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
277         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
278             *sector_size_p = sector_size;
279             success = true;
280         }
281     }
282 
283     return success ? 0 : -errno;
284 }
285 
286 /**
287  * Get physical block size of @fd.
288  * On success, store it in @blk_size and return 0.
289  * On failure, return -errno.
290  */
291 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
292 {
293 #ifdef BLKPBSZGET
294     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
295         return -errno;
296     }
297     return 0;
298 #else
299     return -ENOTSUP;
300 #endif
301 }
302 
303 /* Check if read is allowed with given memory buffer and length.
304  *
305  * This function is used to check O_DIRECT memory buffer and request alignment.
306  */
307 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
308 {
309     ssize_t ret = pread(fd, buf, len, 0);
310 
311     if (ret >= 0) {
312         return true;
313     }
314 
315 #ifdef __linux__
316     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
317      * other errors (e.g. real I/O error), which could happen on a failed
318      * drive, since we only care about probing alignment.
319      */
320     if (errno != EINVAL) {
321         return true;
322     }
323 #endif
324 
325     return false;
326 }
327 
328 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
329 {
330     BDRVRawState *s = bs->opaque;
331     char *buf;
332     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
333     size_t alignments[] = {1, 512, 1024, 2048, 4096};
334 
335     /* For SCSI generic devices the alignment is not really used.
336        With buffered I/O, we don't have any restrictions. */
337     if (bdrv_is_sg(bs) || !s->needs_alignment) {
338         bs->bl.request_alignment = 1;
339         s->buf_align = 1;
340         return;
341     }
342 
343     bs->bl.request_alignment = 0;
344     s->buf_align = 0;
345     /* Let's try to use the logical blocksize for the alignment. */
346     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
347         bs->bl.request_alignment = 0;
348     }
349 #ifdef CONFIG_XFS
350     if (s->is_xfs) {
351         struct dioattr da;
352         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
353             bs->bl.request_alignment = da.d_miniosz;
354             /* The kernel returns wrong information for d_mem */
355             /* s->buf_align = da.d_mem; */
356         }
357     }
358 #endif
359 
360     /*
361      * If we could not get the sizes so far, we can only guess them. First try
362      * to detect request alignment, since it is more likely to succeed. Then
363      * try to detect buf_align, which cannot be detected in some cases (e.g.
364      * Gluster). If buf_align cannot be detected, we fallback to the value of
365      * request_alignment.
366      */
367 
368     if (!bs->bl.request_alignment) {
369         int i;
370         size_t align;
371         buf = qemu_memalign(max_align, max_align);
372         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
373             align = alignments[i];
374             if (raw_is_io_aligned(fd, buf, align)) {
375                 /* Fallback to safe value. */
376                 bs->bl.request_alignment = (align != 1) ? align : max_align;
377                 break;
378             }
379         }
380         qemu_vfree(buf);
381     }
382 
383     if (!s->buf_align) {
384         int i;
385         size_t align;
386         buf = qemu_memalign(max_align, 2 * max_align);
387         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
388             align = alignments[i];
389             if (raw_is_io_aligned(fd, buf + align, max_align)) {
390                 /* Fallback to request_alignment. */
391                 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
392                 break;
393             }
394         }
395         qemu_vfree(buf);
396     }
397 
398     if (!s->buf_align || !bs->bl.request_alignment) {
399         error_setg(errp, "Could not find working O_DIRECT alignment");
400         error_append_hint(errp, "Try cache.direct=off\n");
401     }
402 }
403 
404 static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
405 {
406     bool read_write = false;
407     assert(open_flags != NULL);
408 
409     *open_flags |= O_BINARY;
410     *open_flags &= ~O_ACCMODE;
411 
412     if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
413         read_write = has_writers;
414     } else if (bdrv_flags & BDRV_O_RDWR) {
415         read_write = true;
416     }
417 
418     if (read_write) {
419         *open_flags |= O_RDWR;
420     } else {
421         *open_flags |= O_RDONLY;
422     }
423 
424     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
425      * and O_DIRECT for no caching. */
426     if ((bdrv_flags & BDRV_O_NOCACHE)) {
427         *open_flags |= O_DIRECT;
428     }
429 }
430 
431 static void raw_parse_filename(const char *filename, QDict *options,
432                                Error **errp)
433 {
434     bdrv_parse_filename_strip_prefix(filename, "file:", options);
435 }
436 
437 static QemuOptsList raw_runtime_opts = {
438     .name = "raw",
439     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
440     .desc = {
441         {
442             .name = "filename",
443             .type = QEMU_OPT_STRING,
444             .help = "File name of the image",
445         },
446         {
447             .name = "aio",
448             .type = QEMU_OPT_STRING,
449             .help = "host AIO implementation (threads, native, io_uring)",
450         },
451         {
452             .name = "locking",
453             .type = QEMU_OPT_STRING,
454             .help = "file locking mode (on/off/auto, default: auto)",
455         },
456         {
457             .name = "pr-manager",
458             .type = QEMU_OPT_STRING,
459             .help = "id of persistent reservation manager object (default: none)",
460         },
461 #if defined(__linux__)
462         {
463             .name = "drop-cache",
464             .type = QEMU_OPT_BOOL,
465             .help = "invalidate page cache during live migration (default: on)",
466         },
467 #endif
468         {
469             .name = "x-check-cache-dropped",
470             .type = QEMU_OPT_BOOL,
471             .help = "check that page cache was dropped on live migration (default: off)"
472         },
473         { /* end of list */ }
474     },
475 };
476 
477 static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
478 
479 static int raw_open_common(BlockDriverState *bs, QDict *options,
480                            int bdrv_flags, int open_flags,
481                            bool device, Error **errp)
482 {
483     BDRVRawState *s = bs->opaque;
484     QemuOpts *opts;
485     Error *local_err = NULL;
486     const char *filename = NULL;
487     const char *str;
488     BlockdevAioOptions aio, aio_default;
489     int fd, ret;
490     struct stat st;
491     OnOffAuto locking;
492 
493     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
494     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
495         ret = -EINVAL;
496         goto fail;
497     }
498 
499     filename = qemu_opt_get(opts, "filename");
500 
501     ret = raw_normalize_devicepath(&filename, errp);
502     if (ret != 0) {
503         goto fail;
504     }
505 
506     if (bdrv_flags & BDRV_O_NATIVE_AIO) {
507         aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
508 #ifdef CONFIG_LINUX_IO_URING
509     } else if (bdrv_flags & BDRV_O_IO_URING) {
510         aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
511 #endif
512     } else {
513         aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
514     }
515 
516     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
517                           qemu_opt_get(opts, "aio"),
518                           aio_default, &local_err);
519     if (local_err) {
520         error_propagate(errp, local_err);
521         ret = -EINVAL;
522         goto fail;
523     }
524 
525     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
526 #ifdef CONFIG_LINUX_IO_URING
527     s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
528 #endif
529 
530     locking = qapi_enum_parse(&OnOffAuto_lookup,
531                               qemu_opt_get(opts, "locking"),
532                               ON_OFF_AUTO_AUTO, &local_err);
533     if (local_err) {
534         error_propagate(errp, local_err);
535         ret = -EINVAL;
536         goto fail;
537     }
538     switch (locking) {
539     case ON_OFF_AUTO_ON:
540         s->use_lock = true;
541         if (!qemu_has_ofd_lock()) {
542             warn_report("File lock requested but OFD locking syscall is "
543                         "unavailable, falling back to POSIX file locks");
544             error_printf("Due to the implementation, locks can be lost "
545                          "unexpectedly.\n");
546         }
547         break;
548     case ON_OFF_AUTO_OFF:
549         s->use_lock = false;
550         break;
551     case ON_OFF_AUTO_AUTO:
552         s->use_lock = qemu_has_ofd_lock();
553         break;
554     default:
555         abort();
556     }
557 
558     str = qemu_opt_get(opts, "pr-manager");
559     if (str) {
560         s->pr_mgr = pr_manager_lookup(str, &local_err);
561         if (local_err) {
562             error_propagate(errp, local_err);
563             ret = -EINVAL;
564             goto fail;
565         }
566     }
567 
568     s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
569     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
570                                                false);
571 
572     s->open_flags = open_flags;
573     raw_parse_flags(bdrv_flags, &s->open_flags, false);
574 
575     s->fd = -1;
576     fd = qemu_open(filename, s->open_flags, 0644);
577     ret = fd < 0 ? -errno : 0;
578 
579     if (ret < 0) {
580         error_setg_file_open(errp, -ret, filename);
581         if (ret == -EROFS) {
582             ret = -EACCES;
583         }
584         goto fail;
585     }
586     s->fd = fd;
587 
588     s->perm = 0;
589     s->shared_perm = BLK_PERM_ALL;
590 
591 #ifdef CONFIG_LINUX_AIO
592      /* Currently Linux does AIO only for files opened with O_DIRECT */
593     if (s->use_linux_aio) {
594         if (!(s->open_flags & O_DIRECT)) {
595             error_setg(errp, "aio=native was specified, but it requires "
596                              "cache.direct=on, which was not specified.");
597             ret = -EINVAL;
598             goto fail;
599         }
600         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
601             error_prepend(errp, "Unable to use native AIO: ");
602             goto fail;
603         }
604     }
605 #else
606     if (s->use_linux_aio) {
607         error_setg(errp, "aio=native was specified, but is not supported "
608                          "in this build.");
609         ret = -EINVAL;
610         goto fail;
611     }
612 #endif /* !defined(CONFIG_LINUX_AIO) */
613 
614 #ifdef CONFIG_LINUX_IO_URING
615     if (s->use_linux_io_uring) {
616         if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
617             error_prepend(errp, "Unable to use io_uring: ");
618             goto fail;
619         }
620     }
621 #else
622     if (s->use_linux_io_uring) {
623         error_setg(errp, "aio=io_uring was specified, but is not supported "
624                          "in this build.");
625         ret = -EINVAL;
626         goto fail;
627     }
628 #endif /* !defined(CONFIG_LINUX_IO_URING) */
629 
630     s->has_discard = true;
631     s->has_write_zeroes = true;
632     if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
633         s->needs_alignment = true;
634     }
635 
636     if (fstat(s->fd, &st) < 0) {
637         ret = -errno;
638         error_setg_errno(errp, errno, "Could not stat file");
639         goto fail;
640     }
641 
642     if (!device) {
643         if (S_ISBLK(st.st_mode)) {
644             warn_report("Opening a block device as a file using the '%s' "
645                         "driver is deprecated", bs->drv->format_name);
646         } else if (S_ISCHR(st.st_mode)) {
647             warn_report("Opening a character device as a file using the '%s' "
648                         "driver is deprecated", bs->drv->format_name);
649         } else if (!S_ISREG(st.st_mode)) {
650             error_setg(errp, "A regular file was expected by the '%s' driver, "
651                        "but something else was given", bs->drv->format_name);
652             ret = -EINVAL;
653             goto fail;
654         } else {
655             s->discard_zeroes = true;
656             s->has_fallocate = true;
657         }
658     } else {
659         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
660             error_setg(errp, "'%s' driver expects either "
661                        "a character or block device", bs->drv->format_name);
662             ret = -EINVAL;
663             goto fail;
664         }
665     }
666 
667     if (S_ISBLK(st.st_mode)) {
668 #ifdef BLKDISCARDZEROES
669         unsigned int arg;
670         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
671             s->discard_zeroes = true;
672         }
673 #endif
674 #ifdef __linux__
675         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
676          * not rely on the contents of discarded blocks unless using O_DIRECT.
677          * Same for BLKZEROOUT.
678          */
679         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
680             s->discard_zeroes = false;
681             s->has_write_zeroes = false;
682         }
683 #endif
684     }
685 #ifdef __FreeBSD__
686     if (S_ISCHR(st.st_mode)) {
687         /*
688          * The file is a char device (disk), which on FreeBSD isn't behind
689          * a pager, so force all requests to be aligned. This is needed
690          * so QEMU makes sure all IO operations on the device are aligned
691          * to sector size, or else FreeBSD will reject them with EINVAL.
692          */
693         s->needs_alignment = true;
694     }
695 #endif
696 
697 #ifdef CONFIG_XFS
698     if (platform_test_xfs_fd(s->fd)) {
699         s->is_xfs = true;
700     }
701 #endif
702 
703     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
704     if (S_ISREG(st.st_mode)) {
705         /* When extending regular files, we get zeros from the OS */
706         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
707     }
708     ret = 0;
709 fail:
710     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
711         unlink(filename);
712     }
713     qemu_opts_del(opts);
714     return ret;
715 }
716 
717 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
718                     Error **errp)
719 {
720     BDRVRawState *s = bs->opaque;
721 
722     s->type = FTYPE_FILE;
723     return raw_open_common(bs, options, flags, 0, false, errp);
724 }
725 
726 typedef enum {
727     RAW_PL_PREPARE,
728     RAW_PL_COMMIT,
729     RAW_PL_ABORT,
730 } RawPermLockOp;
731 
732 #define PERM_FOREACH(i) \
733     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
734 
735 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
736  * file; if @unlock == true, also unlock the unneeded bytes.
737  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
738  */
739 static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
740                                 uint64_t perm_lock_bits,
741                                 uint64_t shared_perm_lock_bits,
742                                 bool unlock, Error **errp)
743 {
744     int ret;
745     int i;
746     uint64_t locked_perm, locked_shared_perm;
747 
748     if (s) {
749         locked_perm = s->locked_perm;
750         locked_shared_perm = s->locked_shared_perm;
751     } else {
752         /*
753          * We don't have the previous bits, just lock/unlock for each of the
754          * requested bits.
755          */
756         if (unlock) {
757             locked_perm = BLK_PERM_ALL;
758             locked_shared_perm = BLK_PERM_ALL;
759         } else {
760             locked_perm = 0;
761             locked_shared_perm = 0;
762         }
763     }
764 
765     PERM_FOREACH(i) {
766         int off = RAW_LOCK_PERM_BASE + i;
767         uint64_t bit = (1ULL << i);
768         if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
769             ret = qemu_lock_fd(fd, off, 1, false);
770             if (ret) {
771                 error_setg(errp, "Failed to lock byte %d", off);
772                 return ret;
773             } else if (s) {
774                 s->locked_perm |= bit;
775             }
776         } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
777             ret = qemu_unlock_fd(fd, off, 1);
778             if (ret) {
779                 error_setg(errp, "Failed to unlock byte %d", off);
780                 return ret;
781             } else if (s) {
782                 s->locked_perm &= ~bit;
783             }
784         }
785     }
786     PERM_FOREACH(i) {
787         int off = RAW_LOCK_SHARED_BASE + i;
788         uint64_t bit = (1ULL << i);
789         if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
790             ret = qemu_lock_fd(fd, off, 1, false);
791             if (ret) {
792                 error_setg(errp, "Failed to lock byte %d", off);
793                 return ret;
794             } else if (s) {
795                 s->locked_shared_perm |= bit;
796             }
797         } else if (unlock && (locked_shared_perm & bit) &&
798                    !(shared_perm_lock_bits & bit)) {
799             ret = qemu_unlock_fd(fd, off, 1);
800             if (ret) {
801                 error_setg(errp, "Failed to unlock byte %d", off);
802                 return ret;
803             } else if (s) {
804                 s->locked_shared_perm &= ~bit;
805             }
806         }
807     }
808     return 0;
809 }
810 
811 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
812 static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
813                                 Error **errp)
814 {
815     int ret;
816     int i;
817 
818     PERM_FOREACH(i) {
819         int off = RAW_LOCK_SHARED_BASE + i;
820         uint64_t p = 1ULL << i;
821         if (perm & p) {
822             ret = qemu_lock_fd_test(fd, off, 1, true);
823             if (ret) {
824                 char *perm_name = bdrv_perm_names(p);
825                 error_setg(errp,
826                            "Failed to get \"%s\" lock",
827                            perm_name);
828                 g_free(perm_name);
829                 return ret;
830             }
831         }
832     }
833     PERM_FOREACH(i) {
834         int off = RAW_LOCK_PERM_BASE + i;
835         uint64_t p = 1ULL << i;
836         if (!(shared_perm & p)) {
837             ret = qemu_lock_fd_test(fd, off, 1, true);
838             if (ret) {
839                 char *perm_name = bdrv_perm_names(p);
840                 error_setg(errp,
841                            "Failed to get shared \"%s\" lock",
842                            perm_name);
843                 g_free(perm_name);
844                 return ret;
845             }
846         }
847     }
848     return 0;
849 }
850 
851 static int raw_handle_perm_lock(BlockDriverState *bs,
852                                 RawPermLockOp op,
853                                 uint64_t new_perm, uint64_t new_shared,
854                                 Error **errp)
855 {
856     BDRVRawState *s = bs->opaque;
857     int ret = 0;
858     Error *local_err = NULL;
859 
860     if (!s->use_lock) {
861         return 0;
862     }
863 
864     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
865         return 0;
866     }
867 
868     switch (op) {
869     case RAW_PL_PREPARE:
870         if ((s->perm | new_perm) == s->perm &&
871             (s->shared_perm & new_shared) == s->shared_perm)
872         {
873             /*
874              * We are going to unlock bytes, it should not fail. If it fail due
875              * to some fs-dependent permission-unrelated reasons (which occurs
876              * sometimes on NFS and leads to abort in bdrv_replace_child) we
877              * can't prevent such errors by any check here. And we ignore them
878              * anyway in ABORT and COMMIT.
879              */
880             return 0;
881         }
882         ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
883                                    ~s->shared_perm | ~new_shared,
884                                    false, errp);
885         if (!ret) {
886             ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
887             if (!ret) {
888                 return 0;
889             }
890             error_append_hint(errp,
891                               "Is another process using the image [%s]?\n",
892                               bs->filename);
893         }
894         /* fall through to unlock bytes. */
895     case RAW_PL_ABORT:
896         raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
897                              true, &local_err);
898         if (local_err) {
899             /* Theoretically the above call only unlocks bytes and it cannot
900              * fail. Something weird happened, report it.
901              */
902             warn_report_err(local_err);
903         }
904         break;
905     case RAW_PL_COMMIT:
906         raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
907                              true, &local_err);
908         if (local_err) {
909             /* Theoretically the above call only unlocks bytes and it cannot
910              * fail. Something weird happened, report it.
911              */
912             warn_report_err(local_err);
913         }
914         break;
915     }
916     return ret;
917 }
918 
919 static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
920                                  int *open_flags, uint64_t perm, bool force_dup,
921                                  Error **errp)
922 {
923     BDRVRawState *s = bs->opaque;
924     int fd = -1;
925     int ret;
926     bool has_writers = perm &
927         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
928     int fcntl_flags = O_APPEND | O_NONBLOCK;
929 #ifdef O_NOATIME
930     fcntl_flags |= O_NOATIME;
931 #endif
932 
933     *open_flags = 0;
934     if (s->type == FTYPE_CD) {
935         *open_flags |= O_NONBLOCK;
936     }
937 
938     raw_parse_flags(flags, open_flags, has_writers);
939 
940 #ifdef O_ASYNC
941     /* Not all operating systems have O_ASYNC, and those that don't
942      * will not let us track the state into rs->open_flags (typically
943      * you achieve the same effect with an ioctl, for example I_SETSIG
944      * on Solaris). But we do not use O_ASYNC, so that's fine.
945      */
946     assert((s->open_flags & O_ASYNC) == 0);
947 #endif
948 
949     if (!force_dup && *open_flags == s->open_flags) {
950         /* We're lucky, the existing fd is fine */
951         return s->fd;
952     }
953 
954     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
955         /* dup the original fd */
956         fd = qemu_dup(s->fd);
957         if (fd >= 0) {
958             ret = fcntl_setfl(fd, *open_flags);
959             if (ret) {
960                 qemu_close(fd);
961                 fd = -1;
962             }
963         }
964     }
965 
966     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
967     if (fd == -1) {
968         const char *normalized_filename = bs->filename;
969         ret = raw_normalize_devicepath(&normalized_filename, errp);
970         if (ret >= 0) {
971             assert(!(*open_flags & O_CREAT));
972             fd = qemu_open(normalized_filename, *open_flags);
973             if (fd == -1) {
974                 error_setg_errno(errp, errno, "Could not reopen file");
975                 return -1;
976             }
977         }
978     }
979 
980     return fd;
981 }
982 
983 static int raw_reopen_prepare(BDRVReopenState *state,
984                               BlockReopenQueue *queue, Error **errp)
985 {
986     BDRVRawState *s;
987     BDRVRawReopenState *rs;
988     QemuOpts *opts;
989     int ret;
990     Error *local_err = NULL;
991 
992     assert(state != NULL);
993     assert(state->bs != NULL);
994 
995     s = state->bs->opaque;
996 
997     state->opaque = g_new0(BDRVRawReopenState, 1);
998     rs = state->opaque;
999 
1000     /* Handle options changes */
1001     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1002     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
1003         ret = -EINVAL;
1004         goto out;
1005     }
1006 
1007     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
1008     rs->check_cache_dropped =
1009         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
1010 
1011     /* This driver's reopen function doesn't currently allow changing
1012      * other options, so let's put them back in the original QDict and
1013      * bdrv_reopen_prepare() will detect changes and complain. */
1014     qemu_opts_to_qdict(opts, state->options);
1015 
1016     rs->fd = raw_reconfigure_getfd(state->bs, state->flags, &rs->open_flags,
1017                                    state->perm, true, &local_err);
1018     if (local_err) {
1019         error_propagate(errp, local_err);
1020         ret = -1;
1021         goto out;
1022     }
1023 
1024     /* Fail already reopen_prepare() if we can't get a working O_DIRECT
1025      * alignment with the new fd. */
1026     if (rs->fd != -1) {
1027         raw_probe_alignment(state->bs, rs->fd, &local_err);
1028         if (local_err) {
1029             error_propagate(errp, local_err);
1030             ret = -EINVAL;
1031             goto out_fd;
1032         }
1033     }
1034 
1035     s->reopen_state = state;
1036     ret = 0;
1037 out_fd:
1038     if (ret < 0) {
1039         qemu_close(rs->fd);
1040         rs->fd = -1;
1041     }
1042 out:
1043     qemu_opts_del(opts);
1044     return ret;
1045 }
1046 
1047 static void raw_reopen_commit(BDRVReopenState *state)
1048 {
1049     BDRVRawReopenState *rs = state->opaque;
1050     BDRVRawState *s = state->bs->opaque;
1051 
1052     s->drop_cache = rs->drop_cache;
1053     s->check_cache_dropped = rs->check_cache_dropped;
1054     s->open_flags = rs->open_flags;
1055 
1056     qemu_close(s->fd);
1057     s->fd = rs->fd;
1058 
1059     g_free(state->opaque);
1060     state->opaque = NULL;
1061 
1062     assert(s->reopen_state == state);
1063     s->reopen_state = NULL;
1064 }
1065 
1066 
1067 static void raw_reopen_abort(BDRVReopenState *state)
1068 {
1069     BDRVRawReopenState *rs = state->opaque;
1070     BDRVRawState *s = state->bs->opaque;
1071 
1072      /* nothing to do if NULL, we didn't get far enough */
1073     if (rs == NULL) {
1074         return;
1075     }
1076 
1077     if (rs->fd >= 0) {
1078         qemu_close(rs->fd);
1079         rs->fd = -1;
1080     }
1081     g_free(state->opaque);
1082     state->opaque = NULL;
1083 
1084     assert(s->reopen_state == state);
1085     s->reopen_state = NULL;
1086 }
1087 
1088 static int sg_get_max_transfer_length(int fd)
1089 {
1090 #ifdef BLKSECTGET
1091     int max_bytes = 0;
1092 
1093     if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
1094         return max_bytes;
1095     } else {
1096         return -errno;
1097     }
1098 #else
1099     return -ENOSYS;
1100 #endif
1101 }
1102 
1103 static int sg_get_max_segments(int fd)
1104 {
1105 #ifdef CONFIG_LINUX
1106     char buf[32];
1107     const char *end;
1108     char *sysfspath = NULL;
1109     int ret;
1110     int sysfd = -1;
1111     long max_segments;
1112     struct stat st;
1113 
1114     if (fstat(fd, &st)) {
1115         ret = -errno;
1116         goto out;
1117     }
1118 
1119     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
1120                                 major(st.st_rdev), minor(st.st_rdev));
1121     sysfd = open(sysfspath, O_RDONLY);
1122     if (sysfd == -1) {
1123         ret = -errno;
1124         goto out;
1125     }
1126     do {
1127         ret = read(sysfd, buf, sizeof(buf) - 1);
1128     } while (ret == -1 && errno == EINTR);
1129     if (ret < 0) {
1130         ret = -errno;
1131         goto out;
1132     } else if (ret == 0) {
1133         ret = -EIO;
1134         goto out;
1135     }
1136     buf[ret] = 0;
1137     /* The file is ended with '\n', pass 'end' to accept that. */
1138     ret = qemu_strtol(buf, &end, 10, &max_segments);
1139     if (ret == 0 && end && *end == '\n') {
1140         ret = max_segments;
1141     }
1142 
1143 out:
1144     if (sysfd != -1) {
1145         close(sysfd);
1146     }
1147     g_free(sysfspath);
1148     return ret;
1149 #else
1150     return -ENOTSUP;
1151 #endif
1152 }
1153 
1154 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1155 {
1156     BDRVRawState *s = bs->opaque;
1157 
1158     if (bs->sg) {
1159         int ret = sg_get_max_transfer_length(s->fd);
1160 
1161         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
1162             bs->bl.max_transfer = pow2floor(ret);
1163         }
1164 
1165         ret = sg_get_max_segments(s->fd);
1166         if (ret > 0) {
1167             bs->bl.max_transfer = MIN(bs->bl.max_transfer,
1168                                       ret * qemu_real_host_page_size);
1169         }
1170     }
1171 
1172     raw_probe_alignment(bs, s->fd, errp);
1173     bs->bl.min_mem_alignment = s->buf_align;
1174     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size);
1175 }
1176 
1177 static int check_for_dasd(int fd)
1178 {
1179 #ifdef BIODASDINFO2
1180     struct dasd_information2_t info = {0};
1181 
1182     return ioctl(fd, BIODASDINFO2, &info);
1183 #else
1184     return -1;
1185 #endif
1186 }
1187 
1188 /**
1189  * Try to get @bs's logical and physical block size.
1190  * On success, store them in @bsz and return zero.
1191  * On failure, return negative errno.
1192  */
1193 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1194 {
1195     BDRVRawState *s = bs->opaque;
1196     int ret;
1197 
1198     /* If DASD, get blocksizes */
1199     if (check_for_dasd(s->fd) < 0) {
1200         return -ENOTSUP;
1201     }
1202     ret = probe_logical_blocksize(s->fd, &bsz->log);
1203     if (ret < 0) {
1204         return ret;
1205     }
1206     return probe_physical_blocksize(s->fd, &bsz->phys);
1207 }
1208 
1209 /**
1210  * Try to get @bs's geometry: cyls, heads, sectors.
1211  * On success, store them in @geo and return 0.
1212  * On failure return -errno.
1213  * (Allows block driver to assign default geometry values that guest sees)
1214  */
1215 #ifdef __linux__
1216 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1217 {
1218     BDRVRawState *s = bs->opaque;
1219     struct hd_geometry ioctl_geo = {0};
1220 
1221     /* If DASD, get its geometry */
1222     if (check_for_dasd(s->fd) < 0) {
1223         return -ENOTSUP;
1224     }
1225     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1226         return -errno;
1227     }
1228     /* HDIO_GETGEO may return success even though geo contains zeros
1229        (e.g. certain multipath setups) */
1230     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1231         return -ENOTSUP;
1232     }
1233     /* Do not return a geometry for partition */
1234     if (ioctl_geo.start != 0) {
1235         return -ENOTSUP;
1236     }
1237     geo->heads = ioctl_geo.heads;
1238     geo->sectors = ioctl_geo.sectors;
1239     geo->cylinders = ioctl_geo.cylinders;
1240 
1241     return 0;
1242 }
1243 #else /* __linux__ */
1244 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1245 {
1246     return -ENOTSUP;
1247 }
1248 #endif
1249 
1250 #if defined(__linux__)
1251 static int handle_aiocb_ioctl(void *opaque)
1252 {
1253     RawPosixAIOData *aiocb = opaque;
1254     int ret;
1255 
1256     ret = ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf);
1257     if (ret == -1) {
1258         return -errno;
1259     }
1260 
1261     return 0;
1262 }
1263 #endif /* linux */
1264 
1265 static int handle_aiocb_flush(void *opaque)
1266 {
1267     RawPosixAIOData *aiocb = opaque;
1268     BDRVRawState *s = aiocb->bs->opaque;
1269     int ret;
1270 
1271     if (s->page_cache_inconsistent) {
1272         return -EIO;
1273     }
1274 
1275     ret = qemu_fdatasync(aiocb->aio_fildes);
1276     if (ret == -1) {
1277         /* There is no clear definition of the semantics of a failing fsync(),
1278          * so we may have to assume the worst. The sad truth is that this
1279          * assumption is correct for Linux. Some pages are now probably marked
1280          * clean in the page cache even though they are inconsistent with the
1281          * on-disk contents. The next fdatasync() call would succeed, but no
1282          * further writeback attempt will be made. We can't get back to a state
1283          * in which we know what is on disk (we would have to rewrite
1284          * everything that was touched since the last fdatasync() at least), so
1285          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1286          * really defined, I have little hope that other OSes are doing better.
1287          *
1288          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1289          * cache. */
1290         if ((s->open_flags & O_DIRECT) == 0) {
1291             s->page_cache_inconsistent = true;
1292         }
1293         return -errno;
1294     }
1295     return 0;
1296 }
1297 
1298 #ifdef CONFIG_PREADV
1299 
1300 static bool preadv_present = true;
1301 
1302 static ssize_t
1303 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1304 {
1305     return preadv(fd, iov, nr_iov, offset);
1306 }
1307 
1308 static ssize_t
1309 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1310 {
1311     return pwritev(fd, iov, nr_iov, offset);
1312 }
1313 
1314 #else
1315 
1316 static bool preadv_present = false;
1317 
1318 static ssize_t
1319 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1320 {
1321     return -ENOSYS;
1322 }
1323 
1324 static ssize_t
1325 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1326 {
1327     return -ENOSYS;
1328 }
1329 
1330 #endif
1331 
1332 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1333 {
1334     ssize_t len;
1335 
1336     do {
1337         if (aiocb->aio_type & QEMU_AIO_WRITE)
1338             len = qemu_pwritev(aiocb->aio_fildes,
1339                                aiocb->io.iov,
1340                                aiocb->io.niov,
1341                                aiocb->aio_offset);
1342          else
1343             len = qemu_preadv(aiocb->aio_fildes,
1344                               aiocb->io.iov,
1345                               aiocb->io.niov,
1346                               aiocb->aio_offset);
1347     } while (len == -1 && errno == EINTR);
1348 
1349     if (len == -1) {
1350         return -errno;
1351     }
1352     return len;
1353 }
1354 
1355 /*
1356  * Read/writes the data to/from a given linear buffer.
1357  *
1358  * Returns the number of bytes handles or -errno in case of an error. Short
1359  * reads are only returned if the end of the file is reached.
1360  */
1361 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1362 {
1363     ssize_t offset = 0;
1364     ssize_t len;
1365 
1366     while (offset < aiocb->aio_nbytes) {
1367         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1368             len = pwrite(aiocb->aio_fildes,
1369                          (const char *)buf + offset,
1370                          aiocb->aio_nbytes - offset,
1371                          aiocb->aio_offset + offset);
1372         } else {
1373             len = pread(aiocb->aio_fildes,
1374                         buf + offset,
1375                         aiocb->aio_nbytes - offset,
1376                         aiocb->aio_offset + offset);
1377         }
1378         if (len == -1 && errno == EINTR) {
1379             continue;
1380         } else if (len == -1 && errno == EINVAL &&
1381                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1382                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1383                    offset > 0) {
1384             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1385              * after a short read.  Assume that O_DIRECT short reads only occur
1386              * at EOF.  Therefore this is a short read, not an I/O error.
1387              */
1388             break;
1389         } else if (len == -1) {
1390             offset = -errno;
1391             break;
1392         } else if (len == 0) {
1393             break;
1394         }
1395         offset += len;
1396     }
1397 
1398     return offset;
1399 }
1400 
1401 static int handle_aiocb_rw(void *opaque)
1402 {
1403     RawPosixAIOData *aiocb = opaque;
1404     ssize_t nbytes;
1405     char *buf;
1406 
1407     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1408         /*
1409          * If there is just a single buffer, and it is properly aligned
1410          * we can just use plain pread/pwrite without any problems.
1411          */
1412         if (aiocb->io.niov == 1) {
1413             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
1414             goto out;
1415         }
1416         /*
1417          * We have more than one iovec, and all are properly aligned.
1418          *
1419          * Try preadv/pwritev first and fall back to linearizing the
1420          * buffer if it's not supported.
1421          */
1422         if (preadv_present) {
1423             nbytes = handle_aiocb_rw_vector(aiocb);
1424             if (nbytes == aiocb->aio_nbytes ||
1425                 (nbytes < 0 && nbytes != -ENOSYS)) {
1426                 goto out;
1427             }
1428             preadv_present = false;
1429         }
1430 
1431         /*
1432          * XXX(hch): short read/write.  no easy way to handle the reminder
1433          * using these interfaces.  For now retry using plain
1434          * pread/pwrite?
1435          */
1436     }
1437 
1438     /*
1439      * Ok, we have to do it the hard way, copy all segments into
1440      * a single aligned buffer.
1441      */
1442     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1443     if (buf == NULL) {
1444         nbytes = -ENOMEM;
1445         goto out;
1446     }
1447 
1448     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1449         char *p = buf;
1450         int i;
1451 
1452         for (i = 0; i < aiocb->io.niov; ++i) {
1453             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1454             p += aiocb->io.iov[i].iov_len;
1455         }
1456         assert(p - buf == aiocb->aio_nbytes);
1457     }
1458 
1459     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1460     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1461         char *p = buf;
1462         size_t count = aiocb->aio_nbytes, copy;
1463         int i;
1464 
1465         for (i = 0; i < aiocb->io.niov && count; ++i) {
1466             copy = count;
1467             if (copy > aiocb->io.iov[i].iov_len) {
1468                 copy = aiocb->io.iov[i].iov_len;
1469             }
1470             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1471             assert(count >= copy);
1472             p     += copy;
1473             count -= copy;
1474         }
1475         assert(count == 0);
1476     }
1477     qemu_vfree(buf);
1478 
1479 out:
1480     if (nbytes == aiocb->aio_nbytes) {
1481         return 0;
1482     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
1483         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1484             return -EINVAL;
1485         } else {
1486             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
1487                       0, aiocb->aio_nbytes - nbytes);
1488             return 0;
1489         }
1490     } else {
1491         assert(nbytes < 0);
1492         return nbytes;
1493     }
1494 }
1495 
1496 static int translate_err(int err)
1497 {
1498     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1499         err == -ENOTTY) {
1500         err = -ENOTSUP;
1501     }
1502     return err;
1503 }
1504 
1505 #ifdef CONFIG_FALLOCATE
1506 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1507 {
1508     do {
1509         if (fallocate(fd, mode, offset, len) == 0) {
1510             return 0;
1511         }
1512     } while (errno == EINTR);
1513     return translate_err(-errno);
1514 }
1515 #endif
1516 
1517 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1518 {
1519     int ret = -ENOTSUP;
1520     BDRVRawState *s = aiocb->bs->opaque;
1521 
1522     if (!s->has_write_zeroes) {
1523         return -ENOTSUP;
1524     }
1525 
1526 #ifdef BLKZEROOUT
1527     /* The BLKZEROOUT implementation in the kernel doesn't set
1528      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1529      * fallbacks. */
1530     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1531         do {
1532             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1533             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1534                 return 0;
1535             }
1536         } while (errno == EINTR);
1537 
1538         ret = translate_err(-errno);
1539         if (ret == -ENOTSUP) {
1540             s->has_write_zeroes = false;
1541         }
1542     }
1543 #endif
1544 
1545     return ret;
1546 }
1547 
1548 static int handle_aiocb_write_zeroes(void *opaque)
1549 {
1550     RawPosixAIOData *aiocb = opaque;
1551 #ifdef CONFIG_FALLOCATE
1552     BDRVRawState *s = aiocb->bs->opaque;
1553     int64_t len;
1554 #endif
1555 
1556     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1557         return handle_aiocb_write_zeroes_block(aiocb);
1558     }
1559 
1560 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1561     if (s->has_write_zeroes) {
1562         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1563                                aiocb->aio_offset, aiocb->aio_nbytes);
1564         if (ret == -EINVAL) {
1565             /*
1566              * Allow falling back to pwrite for file systems that
1567              * do not support fallocate() for an unaligned byte range.
1568              */
1569             return -ENOTSUP;
1570         }
1571         if (ret == 0 || ret != -ENOTSUP) {
1572             return ret;
1573         }
1574         s->has_write_zeroes = false;
1575     }
1576 #endif
1577 
1578 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1579     if (s->has_discard && s->has_fallocate) {
1580         int ret = do_fallocate(s->fd,
1581                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1582                                aiocb->aio_offset, aiocb->aio_nbytes);
1583         if (ret == 0) {
1584             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1585             if (ret == 0 || ret != -ENOTSUP) {
1586                 return ret;
1587             }
1588             s->has_fallocate = false;
1589         } else if (ret != -ENOTSUP) {
1590             return ret;
1591         } else {
1592             s->has_discard = false;
1593         }
1594     }
1595 #endif
1596 
1597 #ifdef CONFIG_FALLOCATE
1598     /* Last resort: we are trying to extend the file with zeroed data. This
1599      * can be done via fallocate(fd, 0) */
1600     len = bdrv_getlength(aiocb->bs);
1601     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1602         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1603         if (ret == 0 || ret != -ENOTSUP) {
1604             return ret;
1605         }
1606         s->has_fallocate = false;
1607     }
1608 #endif
1609 
1610     return -ENOTSUP;
1611 }
1612 
1613 static int handle_aiocb_write_zeroes_unmap(void *opaque)
1614 {
1615     RawPosixAIOData *aiocb = opaque;
1616     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
1617 
1618     /* First try to write zeros and unmap at the same time */
1619 
1620 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1621     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1622                            aiocb->aio_offset, aiocb->aio_nbytes);
1623     if (ret != -ENOTSUP) {
1624         return ret;
1625     }
1626 #endif
1627 
1628     /* If we couldn't manage to unmap while guaranteed that the area reads as
1629      * all-zero afterwards, just write zeroes without unmapping */
1630     return handle_aiocb_write_zeroes(aiocb);
1631 }
1632 
1633 #ifndef HAVE_COPY_FILE_RANGE
1634 static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
1635                              off_t *out_off, size_t len, unsigned int flags)
1636 {
1637 #ifdef __NR_copy_file_range
1638     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
1639                    out_off, len, flags);
1640 #else
1641     errno = ENOSYS;
1642     return -1;
1643 #endif
1644 }
1645 #endif
1646 
1647 static int handle_aiocb_copy_range(void *opaque)
1648 {
1649     RawPosixAIOData *aiocb = opaque;
1650     uint64_t bytes = aiocb->aio_nbytes;
1651     off_t in_off = aiocb->aio_offset;
1652     off_t out_off = aiocb->copy_range.aio_offset2;
1653 
1654     while (bytes) {
1655         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
1656                                       aiocb->copy_range.aio_fd2, &out_off,
1657                                       bytes, 0);
1658         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1659                                    aiocb->copy_range.aio_fd2, out_off, bytes,
1660                                    0, ret);
1661         if (ret == 0) {
1662             /* No progress (e.g. when beyond EOF), let the caller fall back to
1663              * buffer I/O. */
1664             return -ENOSPC;
1665         }
1666         if (ret < 0) {
1667             switch (errno) {
1668             case ENOSYS:
1669                 return -ENOTSUP;
1670             case EINTR:
1671                 continue;
1672             default:
1673                 return -errno;
1674             }
1675         }
1676         bytes -= ret;
1677     }
1678     return 0;
1679 }
1680 
1681 static int handle_aiocb_discard(void *opaque)
1682 {
1683     RawPosixAIOData *aiocb = opaque;
1684     int ret = -EOPNOTSUPP;
1685     BDRVRawState *s = aiocb->bs->opaque;
1686 
1687     if (!s->has_discard) {
1688         return -ENOTSUP;
1689     }
1690 
1691     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1692 #ifdef BLKDISCARD
1693         do {
1694             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1695             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1696                 return 0;
1697             }
1698         } while (errno == EINTR);
1699 
1700         ret = -errno;
1701 #endif
1702     } else {
1703 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1704         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1705                            aiocb->aio_offset, aiocb->aio_nbytes);
1706 #endif
1707     }
1708 
1709     ret = translate_err(ret);
1710     if (ret == -ENOTSUP) {
1711         s->has_discard = false;
1712     }
1713     return ret;
1714 }
1715 
1716 /*
1717  * Help alignment probing by allocating the first block.
1718  *
1719  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
1720  * reading succeeds regardless of request length. In this case we fallback to
1721  * safe alignment which is not optimal. Allocating the first block avoids this
1722  * fallback.
1723  *
1724  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
1725  * request alignment, so we use safe values.
1726  *
1727  * Returns: 0 on success, -errno on failure. Since this is an optimization,
1728  * caller may ignore failures.
1729  */
1730 static int allocate_first_block(int fd, size_t max_size)
1731 {
1732     size_t write_size = (max_size < MAX_BLOCKSIZE)
1733         ? BDRV_SECTOR_SIZE
1734         : MAX_BLOCKSIZE;
1735     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
1736     void *buf;
1737     ssize_t n;
1738     int ret;
1739 
1740     buf = qemu_memalign(max_align, write_size);
1741     memset(buf, 0, write_size);
1742 
1743     do {
1744         n = pwrite(fd, buf, write_size, 0);
1745     } while (n == -1 && errno == EINTR);
1746 
1747     ret = (n == -1) ? -errno : 0;
1748 
1749     qemu_vfree(buf);
1750     return ret;
1751 }
1752 
1753 static int handle_aiocb_truncate(void *opaque)
1754 {
1755     RawPosixAIOData *aiocb = opaque;
1756     int result = 0;
1757     int64_t current_length = 0;
1758     char *buf = NULL;
1759     struct stat st;
1760     int fd = aiocb->aio_fildes;
1761     int64_t offset = aiocb->aio_offset;
1762     PreallocMode prealloc = aiocb->truncate.prealloc;
1763     Error **errp = aiocb->truncate.errp;
1764 
1765     if (fstat(fd, &st) < 0) {
1766         result = -errno;
1767         error_setg_errno(errp, -result, "Could not stat file");
1768         return result;
1769     }
1770 
1771     current_length = st.st_size;
1772     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
1773         error_setg(errp, "Cannot use preallocation for shrinking files");
1774         return -ENOTSUP;
1775     }
1776 
1777     switch (prealloc) {
1778 #ifdef CONFIG_POSIX_FALLOCATE
1779     case PREALLOC_MODE_FALLOC:
1780         /*
1781          * Truncating before posix_fallocate() makes it about twice slower on
1782          * file systems that do not support fallocate(), trying to check if a
1783          * block is allocated before allocating it, so don't do that here.
1784          */
1785         if (offset != current_length) {
1786             result = -posix_fallocate(fd, current_length,
1787                                       offset - current_length);
1788             if (result != 0) {
1789                 /* posix_fallocate() doesn't set errno. */
1790                 error_setg_errno(errp, -result,
1791                                  "Could not preallocate new data");
1792             } else if (current_length == 0) {
1793                 /*
1794                  * posix_fallocate() uses fallocate() if the filesystem
1795                  * supports it, or fallback to manually writing zeroes. If
1796                  * fallocate() was used, unaligned reads from the fallocated
1797                  * area in raw_probe_alignment() will succeed, hence we need to
1798                  * allocate the first block.
1799                  *
1800                  * Optimize future alignment probing; ignore failures.
1801                  */
1802                 allocate_first_block(fd, offset);
1803             }
1804         } else {
1805             result = 0;
1806         }
1807         goto out;
1808 #endif
1809     case PREALLOC_MODE_FULL:
1810     {
1811         int64_t num = 0, left = offset - current_length;
1812         off_t seek_result;
1813 
1814         /*
1815          * Knowing the final size from the beginning could allow the file
1816          * system driver to do less allocations and possibly avoid
1817          * fragmentation of the file.
1818          */
1819         if (ftruncate(fd, offset) != 0) {
1820             result = -errno;
1821             error_setg_errno(errp, -result, "Could not resize file");
1822             goto out;
1823         }
1824 
1825         buf = g_malloc0(65536);
1826 
1827         seek_result = lseek(fd, current_length, SEEK_SET);
1828         if (seek_result < 0) {
1829             result = -errno;
1830             error_setg_errno(errp, -result,
1831                              "Failed to seek to the old end of file");
1832             goto out;
1833         }
1834 
1835         while (left > 0) {
1836             num = MIN(left, 65536);
1837             result = write(fd, buf, num);
1838             if (result < 0) {
1839                 if (errno == EINTR) {
1840                     continue;
1841                 }
1842                 result = -errno;
1843                 error_setg_errno(errp, -result,
1844                                  "Could not write zeros for preallocation");
1845                 goto out;
1846             }
1847             left -= result;
1848         }
1849         if (result >= 0) {
1850             result = fsync(fd);
1851             if (result < 0) {
1852                 result = -errno;
1853                 error_setg_errno(errp, -result,
1854                                  "Could not flush file to disk");
1855                 goto out;
1856             }
1857         }
1858         goto out;
1859     }
1860     case PREALLOC_MODE_OFF:
1861         if (ftruncate(fd, offset) != 0) {
1862             result = -errno;
1863             error_setg_errno(errp, -result, "Could not resize file");
1864         } else if (current_length == 0 && offset > current_length) {
1865             /* Optimize future alignment probing; ignore failures. */
1866             allocate_first_block(fd, offset);
1867         }
1868         return result;
1869     default:
1870         result = -ENOTSUP;
1871         error_setg(errp, "Unsupported preallocation mode: %s",
1872                    PreallocMode_str(prealloc));
1873         return result;
1874     }
1875 
1876 out:
1877     if (result < 0) {
1878         if (ftruncate(fd, current_length) < 0) {
1879             error_report("Failed to restore old file length: %s",
1880                          strerror(errno));
1881         }
1882     }
1883 
1884     g_free(buf);
1885     return result;
1886 }
1887 
1888 static int coroutine_fn raw_thread_pool_submit(BlockDriverState *bs,
1889                                                ThreadPoolFunc func, void *arg)
1890 {
1891     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
1892     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1893     return thread_pool_submit_co(pool, func, arg);
1894 }
1895 
1896 static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1897                                    uint64_t bytes, QEMUIOVector *qiov, int type)
1898 {
1899     BDRVRawState *s = bs->opaque;
1900     RawPosixAIOData acb;
1901 
1902     if (fd_open(bs) < 0)
1903         return -EIO;
1904 
1905     /*
1906      * When using O_DIRECT, the request must be aligned to be able to use
1907      * either libaio or io_uring interface. If not fail back to regular thread
1908      * pool read/write code which emulates this for us if we
1909      * set QEMU_AIO_MISALIGNED.
1910      */
1911     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
1912         type |= QEMU_AIO_MISALIGNED;
1913 #ifdef CONFIG_LINUX_IO_URING
1914     } else if (s->use_linux_io_uring) {
1915         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1916         assert(qiov->size == bytes);
1917         return luring_co_submit(bs, aio, s->fd, offset, qiov, type);
1918 #endif
1919 #ifdef CONFIG_LINUX_AIO
1920     } else if (s->use_linux_aio) {
1921         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1922         assert(qiov->size == bytes);
1923         return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
1924 #endif
1925     }
1926 
1927     acb = (RawPosixAIOData) {
1928         .bs             = bs,
1929         .aio_fildes     = s->fd,
1930         .aio_type       = type,
1931         .aio_offset     = offset,
1932         .aio_nbytes     = bytes,
1933         .io             = {
1934             .iov            = qiov->iov,
1935             .niov           = qiov->niov,
1936         },
1937     };
1938 
1939     assert(qiov->size == bytes);
1940     return raw_thread_pool_submit(bs, handle_aiocb_rw, &acb);
1941 }
1942 
1943 static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1944                                       uint64_t bytes, QEMUIOVector *qiov,
1945                                       int flags)
1946 {
1947     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
1948 }
1949 
1950 static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1951                                        uint64_t bytes, QEMUIOVector *qiov,
1952                                        int flags)
1953 {
1954     assert(flags == 0);
1955     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
1956 }
1957 
1958 static void raw_aio_plug(BlockDriverState *bs)
1959 {
1960     BDRVRawState __attribute__((unused)) *s = bs->opaque;
1961 #ifdef CONFIG_LINUX_AIO
1962     if (s->use_linux_aio) {
1963         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1964         laio_io_plug(bs, aio);
1965     }
1966 #endif
1967 #ifdef CONFIG_LINUX_IO_URING
1968     if (s->use_linux_io_uring) {
1969         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1970         luring_io_plug(bs, aio);
1971     }
1972 #endif
1973 }
1974 
1975 static void raw_aio_unplug(BlockDriverState *bs)
1976 {
1977     BDRVRawState __attribute__((unused)) *s = bs->opaque;
1978 #ifdef CONFIG_LINUX_AIO
1979     if (s->use_linux_aio) {
1980         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1981         laio_io_unplug(bs, aio);
1982     }
1983 #endif
1984 #ifdef CONFIG_LINUX_IO_URING
1985     if (s->use_linux_io_uring) {
1986         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1987         luring_io_unplug(bs, aio);
1988     }
1989 #endif
1990 }
1991 
1992 static int raw_co_flush_to_disk(BlockDriverState *bs)
1993 {
1994     BDRVRawState *s = bs->opaque;
1995     RawPosixAIOData acb;
1996     int ret;
1997 
1998     ret = fd_open(bs);
1999     if (ret < 0) {
2000         return ret;
2001     }
2002 
2003     acb = (RawPosixAIOData) {
2004         .bs             = bs,
2005         .aio_fildes     = s->fd,
2006         .aio_type       = QEMU_AIO_FLUSH,
2007     };
2008 
2009 #ifdef CONFIG_LINUX_IO_URING
2010     if (s->use_linux_io_uring) {
2011         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2012         return luring_co_submit(bs, aio, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2013     }
2014 #endif
2015     return raw_thread_pool_submit(bs, handle_aiocb_flush, &acb);
2016 }
2017 
2018 static void raw_aio_attach_aio_context(BlockDriverState *bs,
2019                                        AioContext *new_context)
2020 {
2021     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2022 #ifdef CONFIG_LINUX_AIO
2023     if (s->use_linux_aio) {
2024         Error *local_err = NULL;
2025         if (!aio_setup_linux_aio(new_context, &local_err)) {
2026             error_reportf_err(local_err, "Unable to use native AIO, "
2027                                          "falling back to thread pool: ");
2028             s->use_linux_aio = false;
2029         }
2030     }
2031 #endif
2032 #ifdef CONFIG_LINUX_IO_URING
2033     if (s->use_linux_io_uring) {
2034         Error *local_err;
2035         if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2036             error_reportf_err(local_err, "Unable to use linux io_uring, "
2037                                          "falling back to thread pool: ");
2038             s->use_linux_io_uring = false;
2039         }
2040     }
2041 #endif
2042 }
2043 
2044 static void raw_close(BlockDriverState *bs)
2045 {
2046     BDRVRawState *s = bs->opaque;
2047 
2048     if (s->fd >= 0) {
2049         qemu_close(s->fd);
2050         s->fd = -1;
2051     }
2052 }
2053 
2054 /**
2055  * Truncates the given regular file @fd to @offset and, when growing, fills the
2056  * new space according to @prealloc.
2057  *
2058  * Returns: 0 on success, -errno on failure.
2059  */
2060 static int coroutine_fn
2061 raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
2062                      PreallocMode prealloc, Error **errp)
2063 {
2064     RawPosixAIOData acb;
2065 
2066     acb = (RawPosixAIOData) {
2067         .bs             = bs,
2068         .aio_fildes     = fd,
2069         .aio_type       = QEMU_AIO_TRUNCATE,
2070         .aio_offset     = offset,
2071         .truncate       = {
2072             .prealloc       = prealloc,
2073             .errp           = errp,
2074         },
2075     };
2076 
2077     return raw_thread_pool_submit(bs, handle_aiocb_truncate, &acb);
2078 }
2079 
2080 static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2081                                         bool exact, PreallocMode prealloc,
2082                                         BdrvRequestFlags flags, Error **errp)
2083 {
2084     BDRVRawState *s = bs->opaque;
2085     struct stat st;
2086     int ret;
2087 
2088     if (fstat(s->fd, &st)) {
2089         ret = -errno;
2090         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2091         return ret;
2092     }
2093 
2094     if (S_ISREG(st.st_mode)) {
2095         /* Always resizes to the exact @offset */
2096         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2097     }
2098 
2099     if (prealloc != PREALLOC_MODE_OFF) {
2100         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2101                    "non-regular file", PreallocMode_str(prealloc));
2102         return -ENOTSUP;
2103     }
2104 
2105     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2106         int64_t cur_length = raw_getlength(bs);
2107 
2108         if (offset != cur_length && exact) {
2109             error_setg(errp, "Cannot resize device files");
2110             return -ENOTSUP;
2111         } else if (offset > cur_length) {
2112             error_setg(errp, "Cannot grow device files");
2113             return -EINVAL;
2114         }
2115     } else {
2116         error_setg(errp, "Resizing this file is not supported");
2117         return -ENOTSUP;
2118     }
2119 
2120     return 0;
2121 }
2122 
2123 #ifdef __OpenBSD__
2124 static int64_t raw_getlength(BlockDriverState *bs)
2125 {
2126     BDRVRawState *s = bs->opaque;
2127     int fd = s->fd;
2128     struct stat st;
2129 
2130     if (fstat(fd, &st))
2131         return -errno;
2132     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2133         struct disklabel dl;
2134 
2135         if (ioctl(fd, DIOCGDINFO, &dl))
2136             return -errno;
2137         return (uint64_t)dl.d_secsize *
2138             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2139     } else
2140         return st.st_size;
2141 }
2142 #elif defined(__NetBSD__)
2143 static int64_t raw_getlength(BlockDriverState *bs)
2144 {
2145     BDRVRawState *s = bs->opaque;
2146     int fd = s->fd;
2147     struct stat st;
2148 
2149     if (fstat(fd, &st))
2150         return -errno;
2151     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2152         struct dkwedge_info dkw;
2153 
2154         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2155             return dkw.dkw_size * 512;
2156         } else {
2157             struct disklabel dl;
2158 
2159             if (ioctl(fd, DIOCGDINFO, &dl))
2160                 return -errno;
2161             return (uint64_t)dl.d_secsize *
2162                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2163         }
2164     } else
2165         return st.st_size;
2166 }
2167 #elif defined(__sun__)
2168 static int64_t raw_getlength(BlockDriverState *bs)
2169 {
2170     BDRVRawState *s = bs->opaque;
2171     struct dk_minfo minfo;
2172     int ret;
2173     int64_t size;
2174 
2175     ret = fd_open(bs);
2176     if (ret < 0) {
2177         return ret;
2178     }
2179 
2180     /*
2181      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2182      */
2183     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2184     if (ret != -1) {
2185         return minfo.dki_lbsize * minfo.dki_capacity;
2186     }
2187 
2188     /*
2189      * There are reports that lseek on some devices fails, but
2190      * irc discussion said that contingency on contingency was overkill.
2191      */
2192     size = lseek(s->fd, 0, SEEK_END);
2193     if (size < 0) {
2194         return -errno;
2195     }
2196     return size;
2197 }
2198 #elif defined(CONFIG_BSD)
2199 static int64_t raw_getlength(BlockDriverState *bs)
2200 {
2201     BDRVRawState *s = bs->opaque;
2202     int fd = s->fd;
2203     int64_t size;
2204     struct stat sb;
2205 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2206     int reopened = 0;
2207 #endif
2208     int ret;
2209 
2210     ret = fd_open(bs);
2211     if (ret < 0)
2212         return ret;
2213 
2214 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2215 again:
2216 #endif
2217     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2218 #ifdef DIOCGMEDIASIZE
2219         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
2220 #elif defined(DIOCGPART)
2221         {
2222                 struct partinfo pi;
2223                 if (ioctl(fd, DIOCGPART, &pi) == 0)
2224                         size = pi.media_size;
2225                 else
2226                         size = 0;
2227         }
2228         if (size == 0)
2229 #endif
2230 #if defined(__APPLE__) && defined(__MACH__)
2231         {
2232             uint64_t sectors = 0;
2233             uint32_t sector_size = 0;
2234 
2235             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2236                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2237                 size = sectors * sector_size;
2238             } else {
2239                 size = lseek(fd, 0LL, SEEK_END);
2240                 if (size < 0) {
2241                     return -errno;
2242                 }
2243             }
2244         }
2245 #else
2246         size = lseek(fd, 0LL, SEEK_END);
2247         if (size < 0) {
2248             return -errno;
2249         }
2250 #endif
2251 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2252         switch(s->type) {
2253         case FTYPE_CD:
2254             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2255             if (size == 2048LL * (unsigned)-1)
2256                 size = 0;
2257             /* XXX no disc?  maybe we need to reopen... */
2258             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2259                 reopened = 1;
2260                 goto again;
2261             }
2262         }
2263 #endif
2264     } else {
2265         size = lseek(fd, 0, SEEK_END);
2266         if (size < 0) {
2267             return -errno;
2268         }
2269     }
2270     return size;
2271 }
2272 #else
2273 static int64_t raw_getlength(BlockDriverState *bs)
2274 {
2275     BDRVRawState *s = bs->opaque;
2276     int ret;
2277     int64_t size;
2278 
2279     ret = fd_open(bs);
2280     if (ret < 0) {
2281         return ret;
2282     }
2283 
2284     size = lseek(s->fd, 0, SEEK_END);
2285     if (size < 0) {
2286         return -errno;
2287     }
2288     return size;
2289 }
2290 #endif
2291 
2292 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
2293 {
2294     struct stat st;
2295     BDRVRawState *s = bs->opaque;
2296 
2297     if (fstat(s->fd, &st) < 0) {
2298         return -errno;
2299     }
2300     return (int64_t)st.st_blocks * 512;
2301 }
2302 
2303 static int coroutine_fn
2304 raw_co_create(BlockdevCreateOptions *options, Error **errp)
2305 {
2306     BlockdevCreateOptionsFile *file_opts;
2307     Error *local_err = NULL;
2308     int fd;
2309     uint64_t perm, shared;
2310     int result = 0;
2311 
2312     /* Validate options and set default values */
2313     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2314     file_opts = &options->u.file;
2315 
2316     if (!file_opts->has_nocow) {
2317         file_opts->nocow = false;
2318     }
2319     if (!file_opts->has_preallocation) {
2320         file_opts->preallocation = PREALLOC_MODE_OFF;
2321     }
2322     if (!file_opts->has_extent_size_hint) {
2323         file_opts->extent_size_hint = 1 * MiB;
2324     }
2325     if (file_opts->extent_size_hint > UINT32_MAX) {
2326         result = -EINVAL;
2327         error_setg(errp, "Extent size hint is too large");
2328         goto out;
2329     }
2330 
2331     /* Create file */
2332     fd = qemu_open(file_opts->filename, O_RDWR | O_CREAT | O_BINARY, 0644);
2333     if (fd < 0) {
2334         result = -errno;
2335         error_setg_errno(errp, -result, "Could not create file");
2336         goto out;
2337     }
2338 
2339     /* Take permissions: We want to discard everything, so we need
2340      * BLK_PERM_WRITE; and truncation to the desired size requires
2341      * BLK_PERM_RESIZE.
2342      * On the other hand, we cannot share the RESIZE permission
2343      * because we promise that after this function, the file has the
2344      * size given in the options.  If someone else were to resize it
2345      * concurrently, we could not guarantee that.
2346      * Note that after this function, we can no longer guarantee that
2347      * the file is not touched by a third party, so it may be resized
2348      * then. */
2349     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2350     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2351 
2352     /* Step one: Take locks */
2353     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2354     if (result < 0) {
2355         goto out_close;
2356     }
2357 
2358     /* Step two: Check that nobody else has taken conflicting locks */
2359     result = raw_check_lock_bytes(fd, perm, shared, errp);
2360     if (result < 0) {
2361         error_append_hint(errp,
2362                           "Is another process using the image [%s]?\n",
2363                           file_opts->filename);
2364         goto out_unlock;
2365     }
2366 
2367     /* Clear the file by truncating it to 0 */
2368     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2369     if (result < 0) {
2370         goto out_unlock;
2371     }
2372 
2373     if (file_opts->nocow) {
2374 #ifdef __linux__
2375         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2376          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2377          * will be ignored since any failure of this operation should not
2378          * block the left work.
2379          */
2380         int attr;
2381         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2382             attr |= FS_NOCOW_FL;
2383             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2384         }
2385 #endif
2386     }
2387 #ifdef FS_IOC_FSSETXATTR
2388     /*
2389      * Try to set the extent size hint. Failure is not fatal, and a warning is
2390      * only printed if the option was explicitly specified.
2391      */
2392     {
2393         struct fsxattr attr;
2394         result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2395         if (result == 0) {
2396             attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2397             attr.fsx_extsize = file_opts->extent_size_hint;
2398             result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2399         }
2400         if (result < 0 && file_opts->has_extent_size_hint &&
2401             file_opts->extent_size_hint)
2402         {
2403             warn_report("Failed to set extent size hint: %s",
2404                         strerror(errno));
2405         }
2406     }
2407 #endif
2408 
2409     /* Resize and potentially preallocate the file to the desired
2410      * final size */
2411     result = raw_regular_truncate(NULL, fd, file_opts->size,
2412                                   file_opts->preallocation, errp);
2413     if (result < 0) {
2414         goto out_unlock;
2415     }
2416 
2417 out_unlock:
2418     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
2419     if (local_err) {
2420         /* The above call should not fail, and if it does, that does
2421          * not mean the whole creation operation has failed.  So
2422          * report it the user for their convenience, but do not report
2423          * it to the caller. */
2424         warn_report_err(local_err);
2425     }
2426 
2427 out_close:
2428     if (qemu_close(fd) != 0 && result == 0) {
2429         result = -errno;
2430         error_setg_errno(errp, -result, "Could not close the new file");
2431     }
2432 out:
2433     return result;
2434 }
2435 
2436 static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
2437                                            const char *filename,
2438                                            QemuOpts *opts,
2439                                            Error **errp)
2440 {
2441     BlockdevCreateOptions options;
2442     int64_t total_size = 0;
2443     int64_t extent_size_hint = 0;
2444     bool has_extent_size_hint = false;
2445     bool nocow = false;
2446     PreallocMode prealloc;
2447     char *buf = NULL;
2448     Error *local_err = NULL;
2449 
2450     /* Skip file: protocol prefix */
2451     strstart(filename, "file:", &filename);
2452 
2453     /* Read out options */
2454     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2455                           BDRV_SECTOR_SIZE);
2456     if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
2457         has_extent_size_hint = true;
2458         extent_size_hint =
2459             qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
2460     }
2461     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2462     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2463     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2464                                PREALLOC_MODE_OFF, &local_err);
2465     g_free(buf);
2466     if (local_err) {
2467         error_propagate(errp, local_err);
2468         return -EINVAL;
2469     }
2470 
2471     options = (BlockdevCreateOptions) {
2472         .driver     = BLOCKDEV_DRIVER_FILE,
2473         .u.file     = {
2474             .filename           = (char *) filename,
2475             .size               = total_size,
2476             .has_preallocation  = true,
2477             .preallocation      = prealloc,
2478             .has_nocow          = true,
2479             .nocow              = nocow,
2480             .has_extent_size_hint = has_extent_size_hint,
2481             .extent_size_hint   = extent_size_hint,
2482         },
2483     };
2484     return raw_co_create(&options, errp);
2485 }
2486 
2487 static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
2488                                            Error **errp)
2489 {
2490     struct stat st;
2491     int ret;
2492 
2493     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
2494         error_setg_errno(errp, ENOENT, "%s is not a regular file",
2495                          bs->filename);
2496         return -ENOENT;
2497     }
2498 
2499     ret = unlink(bs->filename);
2500     if (ret < 0) {
2501         ret = -errno;
2502         error_setg_errno(errp, -ret, "Error when deleting file %s",
2503                          bs->filename);
2504     }
2505 
2506     return ret;
2507 }
2508 
2509 /*
2510  * Find allocation range in @bs around offset @start.
2511  * May change underlying file descriptor's file offset.
2512  * If @start is not in a hole, store @start in @data, and the
2513  * beginning of the next hole in @hole, and return 0.
2514  * If @start is in a non-trailing hole, store @start in @hole and the
2515  * beginning of the next non-hole in @data, and return 0.
2516  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2517  * If we can't find out, return a negative errno other than -ENXIO.
2518  */
2519 static int find_allocation(BlockDriverState *bs, off_t start,
2520                            off_t *data, off_t *hole)
2521 {
2522 #if defined SEEK_HOLE && defined SEEK_DATA
2523     BDRVRawState *s = bs->opaque;
2524     off_t offs;
2525 
2526     /*
2527      * SEEK_DATA cases:
2528      * D1. offs == start: start is in data
2529      * D2. offs > start: start is in a hole, next data at offs
2530      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2531      *                              or start is beyond EOF
2532      *     If the latter happens, the file has been truncated behind
2533      *     our back since we opened it.  All bets are off then.
2534      *     Treating like a trailing hole is simplest.
2535      * D4. offs < 0, errno != ENXIO: we learned nothing
2536      */
2537     offs = lseek(s->fd, start, SEEK_DATA);
2538     if (offs < 0) {
2539         return -errno;          /* D3 or D4 */
2540     }
2541 
2542     if (offs < start) {
2543         /* This is not a valid return by lseek().  We are safe to just return
2544          * -EIO in this case, and we'll treat it like D4. */
2545         return -EIO;
2546     }
2547 
2548     if (offs > start) {
2549         /* D2: in hole, next data at offs */
2550         *hole = start;
2551         *data = offs;
2552         return 0;
2553     }
2554 
2555     /* D1: in data, end not yet known */
2556 
2557     /*
2558      * SEEK_HOLE cases:
2559      * H1. offs == start: start is in a hole
2560      *     If this happens here, a hole has been dug behind our back
2561      *     since the previous lseek().
2562      * H2. offs > start: either start is in data, next hole at offs,
2563      *                   or start is in trailing hole, EOF at offs
2564      *     Linux treats trailing holes like any other hole: offs ==
2565      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2566      *     If that happens here, a hole has been dug behind our back
2567      *     since the previous lseek().
2568      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2569      *     If this happens, the file has been truncated behind our
2570      *     back since we opened it.  Treat it like a trailing hole.
2571      * H4. offs < 0, errno != ENXIO: we learned nothing
2572      *     Pretend we know nothing at all, i.e. "forget" about D1.
2573      */
2574     offs = lseek(s->fd, start, SEEK_HOLE);
2575     if (offs < 0) {
2576         return -errno;          /* D1 and (H3 or H4) */
2577     }
2578 
2579     if (offs < start) {
2580         /* This is not a valid return by lseek().  We are safe to just return
2581          * -EIO in this case, and we'll treat it like H4. */
2582         return -EIO;
2583     }
2584 
2585     if (offs > start) {
2586         /*
2587          * D1 and H2: either in data, next hole at offs, or it was in
2588          * data but is now in a trailing hole.  In the latter case,
2589          * all bets are off.  Treating it as if it there was data all
2590          * the way to EOF is safe, so simply do that.
2591          */
2592         *data = start;
2593         *hole = offs;
2594         return 0;
2595     }
2596 
2597     /* D1 and H1 */
2598     return -EBUSY;
2599 #else
2600     return -ENOTSUP;
2601 #endif
2602 }
2603 
2604 /*
2605  * Returns the allocation status of the specified offset.
2606  *
2607  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2608  *
2609  * 'pnum' is set to the number of bytes (including and immediately following
2610  * the specified offset) that are known to be in the same
2611  * allocated/unallocated state.
2612  *
2613  * 'bytes' is the max value 'pnum' should be set to.
2614  */
2615 static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2616                                             bool want_zero,
2617                                             int64_t offset,
2618                                             int64_t bytes, int64_t *pnum,
2619                                             int64_t *map,
2620                                             BlockDriverState **file)
2621 {
2622     off_t data = 0, hole = 0;
2623     int ret;
2624 
2625     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
2626 
2627     ret = fd_open(bs);
2628     if (ret < 0) {
2629         return ret;
2630     }
2631 
2632     if (!want_zero) {
2633         *pnum = bytes;
2634         *map = offset;
2635         *file = bs;
2636         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2637     }
2638 
2639     ret = find_allocation(bs, offset, &data, &hole);
2640     if (ret == -ENXIO) {
2641         /* Trailing hole */
2642         *pnum = bytes;
2643         ret = BDRV_BLOCK_ZERO;
2644     } else if (ret < 0) {
2645         /* No info available, so pretend there are no holes */
2646         *pnum = bytes;
2647         ret = BDRV_BLOCK_DATA;
2648     } else if (data == offset) {
2649         /* On a data extent, compute bytes to the end of the extent,
2650          * possibly including a partial sector at EOF. */
2651         *pnum = MIN(bytes, hole - offset);
2652 
2653         /*
2654          * We are not allowed to return partial sectors, though, so
2655          * round up if necessary.
2656          */
2657         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
2658             int64_t file_length = raw_getlength(bs);
2659             if (file_length > 0) {
2660                 /* Ignore errors, this is just a safeguard */
2661                 assert(hole == file_length);
2662             }
2663             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
2664         }
2665 
2666         ret = BDRV_BLOCK_DATA;
2667     } else {
2668         /* On a hole, compute bytes to the beginning of the next extent.  */
2669         assert(hole == offset);
2670         *pnum = MIN(bytes, data - offset);
2671         ret = BDRV_BLOCK_ZERO;
2672     }
2673     *map = offset;
2674     *file = bs;
2675     return ret | BDRV_BLOCK_OFFSET_VALID;
2676 }
2677 
2678 #if defined(__linux__)
2679 /* Verify that the file is not in the page cache */
2680 static void check_cache_dropped(BlockDriverState *bs, Error **errp)
2681 {
2682     const size_t window_size = 128 * 1024 * 1024;
2683     BDRVRawState *s = bs->opaque;
2684     void *window = NULL;
2685     size_t length = 0;
2686     unsigned char *vec;
2687     size_t page_size;
2688     off_t offset;
2689     off_t end;
2690 
2691     /* mincore(2) page status information requires 1 byte per page */
2692     page_size = sysconf(_SC_PAGESIZE);
2693     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
2694 
2695     end = raw_getlength(bs);
2696 
2697     for (offset = 0; offset < end; offset += window_size) {
2698         void *new_window;
2699         size_t new_length;
2700         size_t vec_end;
2701         size_t i;
2702         int ret;
2703 
2704         /* Unmap previous window if size has changed */
2705         new_length = MIN(end - offset, window_size);
2706         if (new_length != length) {
2707             munmap(window, length);
2708             window = NULL;
2709             length = 0;
2710         }
2711 
2712         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
2713                           s->fd, offset);
2714         if (new_window == MAP_FAILED) {
2715             error_setg_errno(errp, errno, "mmap failed");
2716             break;
2717         }
2718 
2719         window = new_window;
2720         length = new_length;
2721 
2722         ret = mincore(window, length, vec);
2723         if (ret < 0) {
2724             error_setg_errno(errp, errno, "mincore failed");
2725             break;
2726         }
2727 
2728         vec_end = DIV_ROUND_UP(length, page_size);
2729         for (i = 0; i < vec_end; i++) {
2730             if (vec[i] & 0x1) {
2731                 break;
2732             }
2733         }
2734         if (i < vec_end) {
2735             error_setg(errp, "page cache still in use!");
2736             break;
2737         }
2738     }
2739 
2740     if (window) {
2741         munmap(window, length);
2742     }
2743 
2744     g_free(vec);
2745 }
2746 #endif /* __linux__ */
2747 
2748 static void coroutine_fn raw_co_invalidate_cache(BlockDriverState *bs,
2749                                                  Error **errp)
2750 {
2751     BDRVRawState *s = bs->opaque;
2752     int ret;
2753 
2754     ret = fd_open(bs);
2755     if (ret < 0) {
2756         error_setg_errno(errp, -ret, "The file descriptor is not open");
2757         return;
2758     }
2759 
2760     if (!s->drop_cache) {
2761         return;
2762     }
2763 
2764     if (s->open_flags & O_DIRECT) {
2765         return; /* No host kernel page cache */
2766     }
2767 
2768 #if defined(__linux__)
2769     /* This sets the scene for the next syscall... */
2770     ret = bdrv_co_flush(bs);
2771     if (ret < 0) {
2772         error_setg_errno(errp, -ret, "flush failed");
2773         return;
2774     }
2775 
2776     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2777      * process.  These limitations are okay because we just fsynced the file,
2778      * we don't use mmap, and the file should not be in use by other processes.
2779      */
2780     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2781     if (ret != 0) { /* the return value is a positive errno */
2782         error_setg_errno(errp, ret, "fadvise failed");
2783         return;
2784     }
2785 
2786     if (s->check_cache_dropped) {
2787         check_cache_dropped(bs, errp);
2788     }
2789 #else /* __linux__ */
2790     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2791      * unsupported on other host operating systems.  Cache consistency issues
2792      * may occur but no error is reported here, partly because that's the
2793      * historical behavior and partly because it's hard to differentiate valid
2794      * configurations that should not cause errors.
2795      */
2796 #endif /* !__linux__ */
2797 }
2798 
2799 static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
2800 {
2801     if (ret) {
2802         s->stats.discard_nb_failed++;
2803     } else {
2804         s->stats.discard_nb_ok++;
2805         s->stats.discard_bytes_ok += nbytes;
2806     }
2807 }
2808 
2809 static coroutine_fn int
2810 raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int bytes, bool blkdev)
2811 {
2812     BDRVRawState *s = bs->opaque;
2813     RawPosixAIOData acb;
2814     int ret;
2815 
2816     acb = (RawPosixAIOData) {
2817         .bs             = bs,
2818         .aio_fildes     = s->fd,
2819         .aio_type       = QEMU_AIO_DISCARD,
2820         .aio_offset     = offset,
2821         .aio_nbytes     = bytes,
2822     };
2823 
2824     if (blkdev) {
2825         acb.aio_type |= QEMU_AIO_BLKDEV;
2826     }
2827 
2828     ret = raw_thread_pool_submit(bs, handle_aiocb_discard, &acb);
2829     raw_account_discard(s, bytes, ret);
2830     return ret;
2831 }
2832 
2833 static coroutine_fn int
2834 raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
2835 {
2836     return raw_do_pdiscard(bs, offset, bytes, false);
2837 }
2838 
2839 static int coroutine_fn
2840 raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int bytes,
2841                      BdrvRequestFlags flags, bool blkdev)
2842 {
2843     BDRVRawState *s = bs->opaque;
2844     RawPosixAIOData acb;
2845     ThreadPoolFunc *handler;
2846 
2847 #ifdef CONFIG_FALLOCATE
2848     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2849         BdrvTrackedRequest *req;
2850         uint64_t end;
2851 
2852         /*
2853          * This is a workaround for a bug in the Linux XFS driver,
2854          * where writes submitted through the AIO interface will be
2855          * discarded if they happen beyond a concurrently running
2856          * fallocate() that increases the file length (i.e., both the
2857          * write and the fallocate() happen beyond the EOF).
2858          *
2859          * To work around it, we extend the tracked request for this
2860          * zero write until INT64_MAX (effectively infinity), and mark
2861          * it as serializing.
2862          *
2863          * We have to enable this workaround for all filesystems and
2864          * AIO modes (not just XFS with aio=native), because for
2865          * remote filesystems we do not know the host configuration.
2866          */
2867 
2868         req = bdrv_co_get_self_request(bs);
2869         assert(req);
2870         assert(req->type == BDRV_TRACKED_WRITE);
2871         assert(req->offset <= offset);
2872         assert(req->offset + req->bytes >= offset + bytes);
2873 
2874         end = INT64_MAX & -(uint64_t)bs->bl.request_alignment;
2875         req->bytes = end - req->offset;
2876         req->overlap_bytes = req->bytes;
2877 
2878         bdrv_mark_request_serialising(req, bs->bl.request_alignment);
2879     }
2880 #endif
2881 
2882     acb = (RawPosixAIOData) {
2883         .bs             = bs,
2884         .aio_fildes     = s->fd,
2885         .aio_type       = QEMU_AIO_WRITE_ZEROES,
2886         .aio_offset     = offset,
2887         .aio_nbytes     = bytes,
2888     };
2889 
2890     if (blkdev) {
2891         acb.aio_type |= QEMU_AIO_BLKDEV;
2892     }
2893     if (flags & BDRV_REQ_NO_FALLBACK) {
2894         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
2895     }
2896 
2897     if (flags & BDRV_REQ_MAY_UNMAP) {
2898         acb.aio_type |= QEMU_AIO_DISCARD;
2899         handler = handle_aiocb_write_zeroes_unmap;
2900     } else {
2901         handler = handle_aiocb_write_zeroes;
2902     }
2903 
2904     return raw_thread_pool_submit(bs, handler, &acb);
2905 }
2906 
2907 static int coroutine_fn raw_co_pwrite_zeroes(
2908     BlockDriverState *bs, int64_t offset,
2909     int bytes, BdrvRequestFlags flags)
2910 {
2911     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
2912 }
2913 
2914 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2915 {
2916     return 0;
2917 }
2918 
2919 static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
2920 {
2921     BDRVRawState *s = bs->opaque;
2922     return (BlockStatsSpecificFile) {
2923         .discard_nb_ok = s->stats.discard_nb_ok,
2924         .discard_nb_failed = s->stats.discard_nb_failed,
2925         .discard_bytes_ok = s->stats.discard_bytes_ok,
2926     };
2927 }
2928 
2929 static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
2930 {
2931     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
2932 
2933     stats->driver = BLOCKDEV_DRIVER_FILE;
2934     stats->u.file = get_blockstats_specific_file(bs);
2935 
2936     return stats;
2937 }
2938 
2939 static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
2940 {
2941     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
2942 
2943     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
2944     stats->u.host_device = get_blockstats_specific_file(bs);
2945 
2946     return stats;
2947 }
2948 
2949 static QemuOptsList raw_create_opts = {
2950     .name = "raw-create-opts",
2951     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2952     .desc = {
2953         {
2954             .name = BLOCK_OPT_SIZE,
2955             .type = QEMU_OPT_SIZE,
2956             .help = "Virtual disk size"
2957         },
2958         {
2959             .name = BLOCK_OPT_NOCOW,
2960             .type = QEMU_OPT_BOOL,
2961             .help = "Turn off copy-on-write (valid only on btrfs)"
2962         },
2963         {
2964             .name = BLOCK_OPT_PREALLOC,
2965             .type = QEMU_OPT_STRING,
2966             .help = "Preallocation mode (allowed values: off"
2967 #ifdef CONFIG_POSIX_FALLOCATE
2968                     ", falloc"
2969 #endif
2970                     ", full)"
2971         },
2972         {
2973             .name = BLOCK_OPT_EXTENT_SIZE_HINT,
2974             .type = QEMU_OPT_SIZE,
2975             .help = "Extent size hint for the image file, 0 to disable"
2976         },
2977         { /* end of list */ }
2978     }
2979 };
2980 
2981 static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2982                           Error **errp)
2983 {
2984     BDRVRawState *s = bs->opaque;
2985     BDRVRawReopenState *rs = NULL;
2986     int open_flags;
2987     int ret;
2988 
2989     if (s->perm_change_fd) {
2990         /*
2991          * In the context of reopen, this function may be called several times
2992          * (directly and recursively while change permissions of the parent).
2993          * This is even true for children that don't inherit from the original
2994          * reopen node, so s->reopen_state is not set.
2995          *
2996          * Ignore all but the first call.
2997          */
2998         return 0;
2999     }
3000 
3001     if (s->reopen_state) {
3002         /* We already have a new file descriptor to set permissions for */
3003         assert(s->reopen_state->perm == perm);
3004         assert(s->reopen_state->shared_perm == shared);
3005         rs = s->reopen_state->opaque;
3006         s->perm_change_fd = rs->fd;
3007         s->perm_change_flags = rs->open_flags;
3008     } else {
3009         /* We may need a new fd if auto-read-only switches the mode */
3010         ret = raw_reconfigure_getfd(bs, bs->open_flags, &open_flags, perm,
3011                                     false, errp);
3012         if (ret < 0) {
3013             return ret;
3014         } else if (ret != s->fd) {
3015             s->perm_change_fd = ret;
3016             s->perm_change_flags = open_flags;
3017         }
3018     }
3019 
3020     /* Prepare permissions on old fd to avoid conflicts between old and new,
3021      * but keep everything locked that new will need. */
3022     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
3023     if (ret < 0) {
3024         goto fail;
3025     }
3026 
3027     /* Copy locks to the new fd */
3028     if (s->perm_change_fd) {
3029         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
3030                                    false, errp);
3031         if (ret < 0) {
3032             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3033             goto fail;
3034         }
3035     }
3036     return 0;
3037 
3038 fail:
3039     if (s->perm_change_fd && !s->reopen_state) {
3040         qemu_close(s->perm_change_fd);
3041     }
3042     s->perm_change_fd = 0;
3043     return ret;
3044 }
3045 
3046 static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3047 {
3048     BDRVRawState *s = bs->opaque;
3049 
3050     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3051      * called after .bdrv_reopen_commit) */
3052     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
3053         qemu_close(s->fd);
3054         s->fd = s->perm_change_fd;
3055         s->open_flags = s->perm_change_flags;
3056     }
3057     s->perm_change_fd = 0;
3058 
3059     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3060     s->perm = perm;
3061     s->shared_perm = shared;
3062 }
3063 
3064 static void raw_abort_perm_update(BlockDriverState *bs)
3065 {
3066     BDRVRawState *s = bs->opaque;
3067 
3068     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3069      * the file descriptor. */
3070     if (s->perm_change_fd && !s->reopen_state) {
3071         qemu_close(s->perm_change_fd);
3072     }
3073     s->perm_change_fd = 0;
3074 
3075     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3076 }
3077 
3078 static int coroutine_fn raw_co_copy_range_from(
3079         BlockDriverState *bs, BdrvChild *src, uint64_t src_offset,
3080         BdrvChild *dst, uint64_t dst_offset, uint64_t bytes,
3081         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
3082 {
3083     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3084                                  read_flags, write_flags);
3085 }
3086 
3087 static int coroutine_fn raw_co_copy_range_to(BlockDriverState *bs,
3088                                              BdrvChild *src,
3089                                              uint64_t src_offset,
3090                                              BdrvChild *dst,
3091                                              uint64_t dst_offset,
3092                                              uint64_t bytes,
3093                                              BdrvRequestFlags read_flags,
3094                                              BdrvRequestFlags write_flags)
3095 {
3096     RawPosixAIOData acb;
3097     BDRVRawState *s = bs->opaque;
3098     BDRVRawState *src_s;
3099 
3100     assert(dst->bs == bs);
3101     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
3102         return -ENOTSUP;
3103     }
3104 
3105     src_s = src->bs->opaque;
3106     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
3107         return -EIO;
3108     }
3109 
3110     acb = (RawPosixAIOData) {
3111         .bs             = bs,
3112         .aio_type       = QEMU_AIO_COPY_RANGE,
3113         .aio_fildes     = src_s->fd,
3114         .aio_offset     = src_offset,
3115         .aio_nbytes     = bytes,
3116         .copy_range     = {
3117             .aio_fd2        = s->fd,
3118             .aio_offset2    = dst_offset,
3119         },
3120     };
3121 
3122     return raw_thread_pool_submit(bs, handle_aiocb_copy_range, &acb);
3123 }
3124 
3125 BlockDriver bdrv_file = {
3126     .format_name = "file",
3127     .protocol_name = "file",
3128     .instance_size = sizeof(BDRVRawState),
3129     .bdrv_needs_filename = true,
3130     .bdrv_probe = NULL, /* no probe for protocols */
3131     .bdrv_parse_filename = raw_parse_filename,
3132     .bdrv_file_open = raw_open,
3133     .bdrv_reopen_prepare = raw_reopen_prepare,
3134     .bdrv_reopen_commit = raw_reopen_commit,
3135     .bdrv_reopen_abort = raw_reopen_abort,
3136     .bdrv_close = raw_close,
3137     .bdrv_co_create = raw_co_create,
3138     .bdrv_co_create_opts = raw_co_create_opts,
3139     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3140     .bdrv_co_block_status = raw_co_block_status,
3141     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3142     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
3143     .bdrv_co_delete_file = raw_co_delete_file,
3144 
3145     .bdrv_co_preadv         = raw_co_preadv,
3146     .bdrv_co_pwritev        = raw_co_pwritev,
3147     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3148     .bdrv_co_pdiscard       = raw_co_pdiscard,
3149     .bdrv_co_copy_range_from = raw_co_copy_range_from,
3150     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3151     .bdrv_refresh_limits = raw_refresh_limits,
3152     .bdrv_io_plug = raw_aio_plug,
3153     .bdrv_io_unplug = raw_aio_unplug,
3154     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3155 
3156     .bdrv_co_truncate = raw_co_truncate,
3157     .bdrv_getlength = raw_getlength,
3158     .bdrv_get_info = raw_get_info,
3159     .bdrv_get_allocated_file_size
3160                         = raw_get_allocated_file_size,
3161     .bdrv_get_specific_stats = raw_get_specific_stats,
3162     .bdrv_check_perm = raw_check_perm,
3163     .bdrv_set_perm   = raw_set_perm,
3164     .bdrv_abort_perm_update = raw_abort_perm_update,
3165     .create_opts = &raw_create_opts,
3166     .mutable_opts = mutable_opts,
3167 };
3168 
3169 /***********************************************/
3170 /* host device */
3171 
3172 #if defined(__APPLE__) && defined(__MACH__)
3173 static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3174                                 CFIndex maxPathSize, int flags);
3175 static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3176 {
3177     kern_return_t kernResult = KERN_FAILURE;
3178     mach_port_t     masterPort;
3179     CFMutableDictionaryRef  classesToMatch;
3180     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3181     char *mediaType = NULL;
3182 
3183     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
3184     if ( KERN_SUCCESS != kernResult ) {
3185         printf( "IOMasterPort returned %d\n", kernResult );
3186     }
3187 
3188     int index;
3189     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3190         classesToMatch = IOServiceMatching(matching_array[index]);
3191         if (classesToMatch == NULL) {
3192             error_report("IOServiceMatching returned NULL for %s",
3193                          matching_array[index]);
3194             continue;
3195         }
3196         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3197                              kCFBooleanTrue);
3198         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
3199                                                   mediaIterator);
3200         if (kernResult != KERN_SUCCESS) {
3201             error_report("Note: IOServiceGetMatchingServices returned %d",
3202                          kernResult);
3203             continue;
3204         }
3205 
3206         /* If a match was found, leave the loop */
3207         if (*mediaIterator != 0) {
3208             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3209             mediaType = g_strdup(matching_array[index]);
3210             break;
3211         }
3212     }
3213     return mediaType;
3214 }
3215 
3216 kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3217                          CFIndex maxPathSize, int flags)
3218 {
3219     io_object_t     nextMedia;
3220     kern_return_t   kernResult = KERN_FAILURE;
3221     *bsdPath = '\0';
3222     nextMedia = IOIteratorNext( mediaIterator );
3223     if ( nextMedia )
3224     {
3225         CFTypeRef   bsdPathAsCFString;
3226     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3227         if ( bsdPathAsCFString ) {
3228             size_t devPathLength;
3229             strcpy( bsdPath, _PATH_DEV );
3230             if (flags & BDRV_O_NOCACHE) {
3231                 strcat(bsdPath, "r");
3232             }
3233             devPathLength = strlen( bsdPath );
3234             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3235                 kernResult = KERN_SUCCESS;
3236             }
3237             CFRelease( bsdPathAsCFString );
3238         }
3239         IOObjectRelease( nextMedia );
3240     }
3241 
3242     return kernResult;
3243 }
3244 
3245 /* Sets up a real cdrom for use in QEMU */
3246 static bool setup_cdrom(char *bsd_path, Error **errp)
3247 {
3248     int index, num_of_test_partitions = 2, fd;
3249     char test_partition[MAXPATHLEN];
3250     bool partition_found = false;
3251 
3252     /* look for a working partition */
3253     for (index = 0; index < num_of_test_partitions; index++) {
3254         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3255                  index);
3256         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
3257         if (fd >= 0) {
3258             partition_found = true;
3259             qemu_close(fd);
3260             break;
3261         }
3262     }
3263 
3264     /* if a working partition on the device was not found */
3265     if (partition_found == false) {
3266         error_setg(errp, "Failed to find a working partition on disc");
3267     } else {
3268         trace_file_setup_cdrom(test_partition);
3269         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
3270     }
3271     return partition_found;
3272 }
3273 
3274 /* Prints directions on mounting and unmounting a device */
3275 static void print_unmounting_directions(const char *file_name)
3276 {
3277     error_report("If device %s is mounted on the desktop, unmount"
3278                  " it first before using it in QEMU", file_name);
3279     error_report("Command to unmount device: diskutil unmountDisk %s",
3280                  file_name);
3281     error_report("Command to mount device: diskutil mountDisk %s", file_name);
3282 }
3283 
3284 #endif /* defined(__APPLE__) && defined(__MACH__) */
3285 
3286 static int hdev_probe_device(const char *filename)
3287 {
3288     struct stat st;
3289 
3290     /* allow a dedicated CD-ROM driver to match with a higher priority */
3291     if (strstart(filename, "/dev/cdrom", NULL))
3292         return 50;
3293 
3294     if (stat(filename, &st) >= 0 &&
3295             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
3296         return 100;
3297     }
3298 
3299     return 0;
3300 }
3301 
3302 static int check_hdev_writable(BDRVRawState *s)
3303 {
3304 #if defined(BLKROGET)
3305     /* Linux block devices can be configured "read-only" using blockdev(8).
3306      * This is independent of device node permissions and therefore open(2)
3307      * with O_RDWR succeeds.  Actual writes fail with EPERM.
3308      *
3309      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
3310      * check for read-only block devices so that Linux block devices behave
3311      * properly.
3312      */
3313     struct stat st;
3314     int readonly = 0;
3315 
3316     if (fstat(s->fd, &st)) {
3317         return -errno;
3318     }
3319 
3320     if (!S_ISBLK(st.st_mode)) {
3321         return 0;
3322     }
3323 
3324     if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
3325         return -errno;
3326     }
3327 
3328     if (readonly) {
3329         return -EACCES;
3330     }
3331 #endif /* defined(BLKROGET) */
3332     return 0;
3333 }
3334 
3335 static void hdev_parse_filename(const char *filename, QDict *options,
3336                                 Error **errp)
3337 {
3338     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
3339 }
3340 
3341 static bool hdev_is_sg(BlockDriverState *bs)
3342 {
3343 
3344 #if defined(__linux__)
3345 
3346     BDRVRawState *s = bs->opaque;
3347     struct stat st;
3348     struct sg_scsi_id scsiid;
3349     int sg_version;
3350     int ret;
3351 
3352     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
3353         return false;
3354     }
3355 
3356     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
3357     if (ret < 0) {
3358         return false;
3359     }
3360 
3361     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
3362     if (ret >= 0) {
3363         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3364         return true;
3365     }
3366 
3367 #endif
3368 
3369     return false;
3370 }
3371 
3372 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
3373                      Error **errp)
3374 {
3375     BDRVRawState *s = bs->opaque;
3376     int ret;
3377 
3378 #if defined(__APPLE__) && defined(__MACH__)
3379     /*
3380      * Caution: while qdict_get_str() is fine, getting non-string types
3381      * would require more care.  When @options come from -blockdev or
3382      * blockdev_add, its members are typed according to the QAPI
3383      * schema, but when they come from -drive, they're all QString.
3384      */
3385     const char *filename = qdict_get_str(options, "filename");
3386     char bsd_path[MAXPATHLEN] = "";
3387     bool error_occurred = false;
3388 
3389     /* If using a real cdrom */
3390     if (strcmp(filename, "/dev/cdrom") == 0) {
3391         char *mediaType = NULL;
3392         kern_return_t ret_val;
3393         io_iterator_t mediaIterator = 0;
3394 
3395         mediaType = FindEjectableOpticalMedia(&mediaIterator);
3396         if (mediaType == NULL) {
3397             error_setg(errp, "Please make sure your CD/DVD is in the optical"
3398                        " drive");
3399             error_occurred = true;
3400             goto hdev_open_Mac_error;
3401         }
3402 
3403         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
3404         if (ret_val != KERN_SUCCESS) {
3405             error_setg(errp, "Could not get BSD path for optical drive");
3406             error_occurred = true;
3407             goto hdev_open_Mac_error;
3408         }
3409 
3410         /* If a real optical drive was not found */
3411         if (bsd_path[0] == '\0') {
3412             error_setg(errp, "Failed to obtain bsd path for optical drive");
3413             error_occurred = true;
3414             goto hdev_open_Mac_error;
3415         }
3416 
3417         /* If using a cdrom disc and finding a partition on the disc failed */
3418         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
3419             setup_cdrom(bsd_path, errp) == false) {
3420             print_unmounting_directions(bsd_path);
3421             error_occurred = true;
3422             goto hdev_open_Mac_error;
3423         }
3424 
3425         qdict_put_str(options, "filename", bsd_path);
3426 
3427 hdev_open_Mac_error:
3428         g_free(mediaType);
3429         if (mediaIterator) {
3430             IOObjectRelease(mediaIterator);
3431         }
3432         if (error_occurred) {
3433             return -ENOENT;
3434         }
3435     }
3436 #endif /* defined(__APPLE__) && defined(__MACH__) */
3437 
3438     s->type = FTYPE_FILE;
3439 
3440     ret = raw_open_common(bs, options, flags, 0, true, errp);
3441     if (ret < 0) {
3442 #if defined(__APPLE__) && defined(__MACH__)
3443         if (*bsd_path) {
3444             filename = bsd_path;
3445         }
3446         /* if a physical device experienced an error while being opened */
3447         if (strncmp(filename, "/dev/", 5) == 0) {
3448             print_unmounting_directions(filename);
3449         }
3450 #endif /* defined(__APPLE__) && defined(__MACH__) */
3451         return ret;
3452     }
3453 
3454     /* Since this does ioctl the device must be already opened */
3455     bs->sg = hdev_is_sg(bs);
3456 
3457     if (flags & BDRV_O_RDWR) {
3458         ret = check_hdev_writable(s);
3459         if (ret < 0) {
3460             raw_close(bs);
3461             error_setg_errno(errp, -ret, "The device is not writable");
3462             return ret;
3463         }
3464     }
3465 
3466     return ret;
3467 }
3468 
3469 #if defined(__linux__)
3470 static int coroutine_fn
3471 hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3472 {
3473     BDRVRawState *s = bs->opaque;
3474     RawPosixAIOData acb;
3475     int ret;
3476 
3477     ret = fd_open(bs);
3478     if (ret < 0) {
3479         return ret;
3480     }
3481 
3482     if (req == SG_IO && s->pr_mgr) {
3483         struct sg_io_hdr *io_hdr = buf;
3484         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
3485             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
3486             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
3487                                       s->fd, io_hdr);
3488         }
3489     }
3490 
3491     acb = (RawPosixAIOData) {
3492         .bs         = bs,
3493         .aio_type   = QEMU_AIO_IOCTL,
3494         .aio_fildes = s->fd,
3495         .aio_offset = 0,
3496         .ioctl      = {
3497             .buf        = buf,
3498             .cmd        = req,
3499         },
3500     };
3501 
3502     return raw_thread_pool_submit(bs, handle_aiocb_ioctl, &acb);
3503 }
3504 #endif /* linux */
3505 
3506 static int fd_open(BlockDriverState *bs)
3507 {
3508     BDRVRawState *s = bs->opaque;
3509 
3510     /* this is just to ensure s->fd is sane (its called by io ops) */
3511     if (s->fd >= 0)
3512         return 0;
3513     return -EIO;
3514 }
3515 
3516 static coroutine_fn int
3517 hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
3518 {
3519     BDRVRawState *s = bs->opaque;
3520     int ret;
3521 
3522     ret = fd_open(bs);
3523     if (ret < 0) {
3524         raw_account_discard(s, bytes, ret);
3525         return ret;
3526     }
3527     return raw_do_pdiscard(bs, offset, bytes, true);
3528 }
3529 
3530 static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3531     int64_t offset, int bytes, BdrvRequestFlags flags)
3532 {
3533     int rc;
3534 
3535     rc = fd_open(bs);
3536     if (rc < 0) {
3537         return rc;
3538     }
3539 
3540     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
3541 }
3542 
3543 static BlockDriver bdrv_host_device = {
3544     .format_name        = "host_device",
3545     .protocol_name        = "host_device",
3546     .instance_size      = sizeof(BDRVRawState),
3547     .bdrv_needs_filename = true,
3548     .bdrv_probe_device  = hdev_probe_device,
3549     .bdrv_parse_filename = hdev_parse_filename,
3550     .bdrv_file_open     = hdev_open,
3551     .bdrv_close         = raw_close,
3552     .bdrv_reopen_prepare = raw_reopen_prepare,
3553     .bdrv_reopen_commit  = raw_reopen_commit,
3554     .bdrv_reopen_abort   = raw_reopen_abort,
3555     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
3556     .create_opts         = &bdrv_create_opts_simple,
3557     .mutable_opts        = mutable_opts,
3558     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3559     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3560 
3561     .bdrv_co_preadv         = raw_co_preadv,
3562     .bdrv_co_pwritev        = raw_co_pwritev,
3563     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3564     .bdrv_co_pdiscard       = hdev_co_pdiscard,
3565     .bdrv_co_copy_range_from = raw_co_copy_range_from,
3566     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3567     .bdrv_refresh_limits = raw_refresh_limits,
3568     .bdrv_io_plug = raw_aio_plug,
3569     .bdrv_io_unplug = raw_aio_unplug,
3570     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3571 
3572     .bdrv_co_truncate       = raw_co_truncate,
3573     .bdrv_getlength	= raw_getlength,
3574     .bdrv_get_info = raw_get_info,
3575     .bdrv_get_allocated_file_size
3576                         = raw_get_allocated_file_size,
3577     .bdrv_get_specific_stats = hdev_get_specific_stats,
3578     .bdrv_check_perm = raw_check_perm,
3579     .bdrv_set_perm   = raw_set_perm,
3580     .bdrv_abort_perm_update = raw_abort_perm_update,
3581     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3582     .bdrv_probe_geometry = hdev_probe_geometry,
3583 
3584     /* generic scsi device */
3585 #ifdef __linux__
3586     .bdrv_co_ioctl          = hdev_co_ioctl,
3587 #endif
3588 };
3589 
3590 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3591 static void cdrom_parse_filename(const char *filename, QDict *options,
3592                                  Error **errp)
3593 {
3594     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3595 }
3596 #endif
3597 
3598 #ifdef __linux__
3599 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3600                       Error **errp)
3601 {
3602     BDRVRawState *s = bs->opaque;
3603 
3604     s->type = FTYPE_CD;
3605 
3606     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3607     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3608 }
3609 
3610 static int cdrom_probe_device(const char *filename)
3611 {
3612     int fd, ret;
3613     int prio = 0;
3614     struct stat st;
3615 
3616     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
3617     if (fd < 0) {
3618         goto out;
3619     }
3620     ret = fstat(fd, &st);
3621     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3622         goto outc;
3623     }
3624 
3625     /* Attempt to detect via a CDROM specific ioctl */
3626     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3627     if (ret >= 0)
3628         prio = 100;
3629 
3630 outc:
3631     qemu_close(fd);
3632 out:
3633     return prio;
3634 }
3635 
3636 static bool cdrom_is_inserted(BlockDriverState *bs)
3637 {
3638     BDRVRawState *s = bs->opaque;
3639     int ret;
3640 
3641     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3642     return ret == CDS_DISC_OK;
3643 }
3644 
3645 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3646 {
3647     BDRVRawState *s = bs->opaque;
3648 
3649     if (eject_flag) {
3650         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3651             perror("CDROMEJECT");
3652     } else {
3653         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3654             perror("CDROMEJECT");
3655     }
3656 }
3657 
3658 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3659 {
3660     BDRVRawState *s = bs->opaque;
3661 
3662     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3663         /*
3664          * Note: an error can happen if the distribution automatically
3665          * mounts the CD-ROM
3666          */
3667         /* perror("CDROM_LOCKDOOR"); */
3668     }
3669 }
3670 
3671 static BlockDriver bdrv_host_cdrom = {
3672     .format_name        = "host_cdrom",
3673     .protocol_name      = "host_cdrom",
3674     .instance_size      = sizeof(BDRVRawState),
3675     .bdrv_needs_filename = true,
3676     .bdrv_probe_device	= cdrom_probe_device,
3677     .bdrv_parse_filename = cdrom_parse_filename,
3678     .bdrv_file_open     = cdrom_open,
3679     .bdrv_close         = raw_close,
3680     .bdrv_reopen_prepare = raw_reopen_prepare,
3681     .bdrv_reopen_commit  = raw_reopen_commit,
3682     .bdrv_reopen_abort   = raw_reopen_abort,
3683     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
3684     .create_opts         = &bdrv_create_opts_simple,
3685     .mutable_opts        = mutable_opts,
3686     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3687 
3688     .bdrv_co_preadv         = raw_co_preadv,
3689     .bdrv_co_pwritev        = raw_co_pwritev,
3690     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3691     .bdrv_refresh_limits = raw_refresh_limits,
3692     .bdrv_io_plug = raw_aio_plug,
3693     .bdrv_io_unplug = raw_aio_unplug,
3694     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3695 
3696     .bdrv_co_truncate    = raw_co_truncate,
3697     .bdrv_getlength      = raw_getlength,
3698     .has_variable_length = true,
3699     .bdrv_get_allocated_file_size
3700                         = raw_get_allocated_file_size,
3701 
3702     /* removable device support */
3703     .bdrv_is_inserted   = cdrom_is_inserted,
3704     .bdrv_eject         = cdrom_eject,
3705     .bdrv_lock_medium   = cdrom_lock_medium,
3706 
3707     /* generic scsi device */
3708     .bdrv_co_ioctl      = hdev_co_ioctl,
3709 };
3710 #endif /* __linux__ */
3711 
3712 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3713 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3714                       Error **errp)
3715 {
3716     BDRVRawState *s = bs->opaque;
3717     int ret;
3718 
3719     s->type = FTYPE_CD;
3720 
3721     ret = raw_open_common(bs, options, flags, 0, true, errp);
3722     if (ret) {
3723         return ret;
3724     }
3725 
3726     /* make sure the door isn't locked at this time */
3727     ioctl(s->fd, CDIOCALLOW);
3728     return 0;
3729 }
3730 
3731 static int cdrom_probe_device(const char *filename)
3732 {
3733     if (strstart(filename, "/dev/cd", NULL) ||
3734             strstart(filename, "/dev/acd", NULL))
3735         return 100;
3736     return 0;
3737 }
3738 
3739 static int cdrom_reopen(BlockDriverState *bs)
3740 {
3741     BDRVRawState *s = bs->opaque;
3742     int fd;
3743 
3744     /*
3745      * Force reread of possibly changed/newly loaded disc,
3746      * FreeBSD seems to not notice sometimes...
3747      */
3748     if (s->fd >= 0)
3749         qemu_close(s->fd);
3750     fd = qemu_open(bs->filename, s->open_flags, 0644);
3751     if (fd < 0) {
3752         s->fd = -1;
3753         return -EIO;
3754     }
3755     s->fd = fd;
3756 
3757     /* make sure the door isn't locked at this time */
3758     ioctl(s->fd, CDIOCALLOW);
3759     return 0;
3760 }
3761 
3762 static bool cdrom_is_inserted(BlockDriverState *bs)
3763 {
3764     return raw_getlength(bs) > 0;
3765 }
3766 
3767 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3768 {
3769     BDRVRawState *s = bs->opaque;
3770 
3771     if (s->fd < 0)
3772         return;
3773 
3774     (void) ioctl(s->fd, CDIOCALLOW);
3775 
3776     if (eject_flag) {
3777         if (ioctl(s->fd, CDIOCEJECT) < 0)
3778             perror("CDIOCEJECT");
3779     } else {
3780         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3781             perror("CDIOCCLOSE");
3782     }
3783 
3784     cdrom_reopen(bs);
3785 }
3786 
3787 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3788 {
3789     BDRVRawState *s = bs->opaque;
3790 
3791     if (s->fd < 0)
3792         return;
3793     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3794         /*
3795          * Note: an error can happen if the distribution automatically
3796          * mounts the CD-ROM
3797          */
3798         /* perror("CDROM_LOCKDOOR"); */
3799     }
3800 }
3801 
3802 static BlockDriver bdrv_host_cdrom = {
3803     .format_name        = "host_cdrom",
3804     .protocol_name      = "host_cdrom",
3805     .instance_size      = sizeof(BDRVRawState),
3806     .bdrv_needs_filename = true,
3807     .bdrv_probe_device	= cdrom_probe_device,
3808     .bdrv_parse_filename = cdrom_parse_filename,
3809     .bdrv_file_open     = cdrom_open,
3810     .bdrv_close         = raw_close,
3811     .bdrv_reopen_prepare = raw_reopen_prepare,
3812     .bdrv_reopen_commit  = raw_reopen_commit,
3813     .bdrv_reopen_abort   = raw_reopen_abort,
3814     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
3815     .create_opts         = &bdrv_create_opts_simple,
3816     .mutable_opts       = mutable_opts,
3817 
3818     .bdrv_co_preadv         = raw_co_preadv,
3819     .bdrv_co_pwritev        = raw_co_pwritev,
3820     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3821     .bdrv_refresh_limits = raw_refresh_limits,
3822     .bdrv_io_plug = raw_aio_plug,
3823     .bdrv_io_unplug = raw_aio_unplug,
3824     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3825 
3826     .bdrv_co_truncate    = raw_co_truncate,
3827     .bdrv_getlength      = raw_getlength,
3828     .has_variable_length = true,
3829     .bdrv_get_allocated_file_size
3830                         = raw_get_allocated_file_size,
3831 
3832     /* removable device support */
3833     .bdrv_is_inserted   = cdrom_is_inserted,
3834     .bdrv_eject         = cdrom_eject,
3835     .bdrv_lock_medium   = cdrom_lock_medium,
3836 };
3837 #endif /* __FreeBSD__ */
3838 
3839 static void bdrv_file_init(void)
3840 {
3841     /*
3842      * Register all the drivers.  Note that order is important, the driver
3843      * registered last will get probed first.
3844      */
3845     bdrv_register(&bdrv_file);
3846     bdrv_register(&bdrv_host_device);
3847 #ifdef __linux__
3848     bdrv_register(&bdrv_host_cdrom);
3849 #endif
3850 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3851     bdrv_register(&bdrv_host_cdrom);
3852 #endif
3853 }
3854 
3855 block_init(bdrv_file_init);
3856