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