xref: /openbmc/qemu/block/file-posix.c (revision 795c40b8)
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 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
30 #include "trace.h"
31 #include "block/thread-pool.h"
32 #include "qemu/iov.h"
33 #include "block/raw-aio.h"
34 #include "qapi/util.h"
35 #include "qapi/qmp/qstring.h"
36 
37 #if defined(__APPLE__) && (__MACH__)
38 #include <paths.h>
39 #include <sys/param.h>
40 #include <IOKit/IOKitLib.h>
41 #include <IOKit/IOBSD.h>
42 #include <IOKit/storage/IOMediaBSDClient.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <IOKit/storage/IOCDMedia.h>
45 //#include <IOKit/storage/IOCDTypes.h>
46 #include <IOKit/storage/IODVDMedia.h>
47 #include <CoreFoundation/CoreFoundation.h>
48 #endif
49 
50 #ifdef __sun__
51 #define _POSIX_PTHREAD_SEMANTICS 1
52 #include <sys/dkio.h>
53 #endif
54 #ifdef __linux__
55 #include <sys/ioctl.h>
56 #include <sys/param.h>
57 #include <linux/cdrom.h>
58 #include <linux/fd.h>
59 #include <linux/fs.h>
60 #include <linux/hdreg.h>
61 #include <scsi/sg.h>
62 #ifdef __s390__
63 #include <asm/dasd.h>
64 #endif
65 #ifndef FS_NOCOW_FL
66 #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
67 #endif
68 #endif
69 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
70 #include <linux/falloc.h>
71 #endif
72 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
73 #include <sys/disk.h>
74 #include <sys/cdio.h>
75 #endif
76 
77 #ifdef __OpenBSD__
78 #include <sys/ioctl.h>
79 #include <sys/disklabel.h>
80 #include <sys/dkio.h>
81 #endif
82 
83 #ifdef __NetBSD__
84 #include <sys/ioctl.h>
85 #include <sys/disklabel.h>
86 #include <sys/dkio.h>
87 #include <sys/disk.h>
88 #endif
89 
90 #ifdef __DragonFly__
91 #include <sys/ioctl.h>
92 #include <sys/diskslice.h>
93 #endif
94 
95 #ifdef CONFIG_XFS
96 #include <xfs/xfs.h>
97 #endif
98 
99 //#define DEBUG_BLOCK
100 
101 #ifdef DEBUG_BLOCK
102 # define DEBUG_BLOCK_PRINT 1
103 #else
104 # define DEBUG_BLOCK_PRINT 0
105 #endif
106 #define DPRINTF(fmt, ...) \
107 do { \
108     if (DEBUG_BLOCK_PRINT) { \
109         printf(fmt, ## __VA_ARGS__); \
110     } \
111 } while (0)
112 
113 /* OS X does not have O_DSYNC */
114 #ifndef O_DSYNC
115 #ifdef O_SYNC
116 #define O_DSYNC O_SYNC
117 #elif defined(O_FSYNC)
118 #define O_DSYNC O_FSYNC
119 #endif
120 #endif
121 
122 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
123 #ifndef O_DIRECT
124 #define O_DIRECT O_DSYNC
125 #endif
126 
127 #define FTYPE_FILE   0
128 #define FTYPE_CD     1
129 
130 #define MAX_BLOCKSIZE	4096
131 
132 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
133  * leaving a few more bytes for its future use. */
134 #define RAW_LOCK_PERM_BASE             100
135 #define RAW_LOCK_SHARED_BASE           200
136 
137 typedef struct BDRVRawState {
138     int fd;
139     int lock_fd;
140     bool use_lock;
141     int type;
142     int open_flags;
143     size_t buf_align;
144 
145     /* The current permissions. */
146     uint64_t perm;
147     uint64_t shared_perm;
148 
149 #ifdef CONFIG_XFS
150     bool is_xfs:1;
151 #endif
152     bool has_discard:1;
153     bool has_write_zeroes:1;
154     bool discard_zeroes:1;
155     bool use_linux_aio:1;
156     bool page_cache_inconsistent:1;
157     bool has_fallocate;
158     bool needs_alignment;
159 } BDRVRawState;
160 
161 typedef struct BDRVRawReopenState {
162     int fd;
163     int open_flags;
164 } BDRVRawReopenState;
165 
166 static int fd_open(BlockDriverState *bs);
167 static int64_t raw_getlength(BlockDriverState *bs);
168 
169 typedef struct RawPosixAIOData {
170     BlockDriverState *bs;
171     int aio_fildes;
172     union {
173         struct iovec *aio_iov;
174         void *aio_ioctl_buf;
175     };
176     int aio_niov;
177     uint64_t aio_nbytes;
178 #define aio_ioctl_cmd   aio_nbytes /* for QEMU_AIO_IOCTL */
179     off_t aio_offset;
180     int aio_type;
181 } RawPosixAIOData;
182 
183 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184 static int cdrom_reopen(BlockDriverState *bs);
185 #endif
186 
187 #if defined(__NetBSD__)
188 static int raw_normalize_devicepath(const char **filename)
189 {
190     static char namebuf[PATH_MAX];
191     const char *dp, *fname;
192     struct stat sb;
193 
194     fname = *filename;
195     dp = strrchr(fname, '/');
196     if (lstat(fname, &sb) < 0) {
197         fprintf(stderr, "%s: stat failed: %s\n",
198             fname, strerror(errno));
199         return -errno;
200     }
201 
202     if (!S_ISBLK(sb.st_mode)) {
203         return 0;
204     }
205 
206     if (dp == NULL) {
207         snprintf(namebuf, PATH_MAX, "r%s", fname);
208     } else {
209         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
210             (int)(dp - fname), fname, dp + 1);
211     }
212     fprintf(stderr, "%s is a block device", fname);
213     *filename = namebuf;
214     fprintf(stderr, ", using %s\n", *filename);
215 
216     return 0;
217 }
218 #else
219 static int raw_normalize_devicepath(const char **filename)
220 {
221     return 0;
222 }
223 #endif
224 
225 /*
226  * Get logical block size via ioctl. On success store it in @sector_size_p.
227  */
228 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
229 {
230     unsigned int sector_size;
231     bool success = false;
232     int i;
233 
234     errno = ENOTSUP;
235     static const unsigned long ioctl_list[] = {
236 #ifdef BLKSSZGET
237         BLKSSZGET,
238 #endif
239 #ifdef DKIOCGETBLOCKSIZE
240         DKIOCGETBLOCKSIZE,
241 #endif
242 #ifdef DIOCGSECTORSIZE
243         DIOCGSECTORSIZE,
244 #endif
245     };
246 
247     /* Try a few ioctls to get the right size */
248     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
249         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
250             *sector_size_p = sector_size;
251             success = true;
252         }
253     }
254 
255     return success ? 0 : -errno;
256 }
257 
258 /**
259  * Get physical block size of @fd.
260  * On success, store it in @blk_size and return 0.
261  * On failure, return -errno.
262  */
263 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
264 {
265 #ifdef BLKPBSZGET
266     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
267         return -errno;
268     }
269     return 0;
270 #else
271     return -ENOTSUP;
272 #endif
273 }
274 
275 /* Check if read is allowed with given memory buffer and length.
276  *
277  * This function is used to check O_DIRECT memory buffer and request alignment.
278  */
279 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
280 {
281     ssize_t ret = pread(fd, buf, len, 0);
282 
283     if (ret >= 0) {
284         return true;
285     }
286 
287 #ifdef __linux__
288     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
289      * other errors (e.g. real I/O error), which could happen on a failed
290      * drive, since we only care about probing alignment.
291      */
292     if (errno != EINVAL) {
293         return true;
294     }
295 #endif
296 
297     return false;
298 }
299 
300 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
301 {
302     BDRVRawState *s = bs->opaque;
303     char *buf;
304     size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
305 
306     /* For SCSI generic devices the alignment is not really used.
307        With buffered I/O, we don't have any restrictions. */
308     if (bdrv_is_sg(bs) || !s->needs_alignment) {
309         bs->bl.request_alignment = 1;
310         s->buf_align = 1;
311         return;
312     }
313 
314     bs->bl.request_alignment = 0;
315     s->buf_align = 0;
316     /* Let's try to use the logical blocksize for the alignment. */
317     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
318         bs->bl.request_alignment = 0;
319     }
320 #ifdef CONFIG_XFS
321     if (s->is_xfs) {
322         struct dioattr da;
323         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
324             bs->bl.request_alignment = da.d_miniosz;
325             /* The kernel returns wrong information for d_mem */
326             /* s->buf_align = da.d_mem; */
327         }
328     }
329 #endif
330 
331     /* If we could not get the sizes so far, we can only guess them */
332     if (!s->buf_align) {
333         size_t align;
334         buf = qemu_memalign(max_align, 2 * max_align);
335         for (align = 512; align <= max_align; align <<= 1) {
336             if (raw_is_io_aligned(fd, buf + align, max_align)) {
337                 s->buf_align = align;
338                 break;
339             }
340         }
341         qemu_vfree(buf);
342     }
343 
344     if (!bs->bl.request_alignment) {
345         size_t align;
346         buf = qemu_memalign(s->buf_align, max_align);
347         for (align = 512; align <= max_align; align <<= 1) {
348             if (raw_is_io_aligned(fd, buf, align)) {
349                 bs->bl.request_alignment = align;
350                 break;
351             }
352         }
353         qemu_vfree(buf);
354     }
355 
356     if (!s->buf_align || !bs->bl.request_alignment) {
357         error_setg(errp, "Could not find working O_DIRECT alignment");
358         error_append_hint(errp, "Try cache.direct=off\n");
359     }
360 }
361 
362 static void raw_parse_flags(int bdrv_flags, int *open_flags)
363 {
364     assert(open_flags != NULL);
365 
366     *open_flags |= O_BINARY;
367     *open_flags &= ~O_ACCMODE;
368     if (bdrv_flags & BDRV_O_RDWR) {
369         *open_flags |= O_RDWR;
370     } else {
371         *open_flags |= O_RDONLY;
372     }
373 
374     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
375      * and O_DIRECT for no caching. */
376     if ((bdrv_flags & BDRV_O_NOCACHE)) {
377         *open_flags |= O_DIRECT;
378     }
379 }
380 
381 static void raw_parse_filename(const char *filename, QDict *options,
382                                Error **errp)
383 {
384     /* The filename does not have to be prefixed by the protocol name, since
385      * "file" is the default protocol; therefore, the return value of this
386      * function call can be ignored. */
387     strstart(filename, "file:", &filename);
388 
389     qdict_put_str(options, "filename", filename);
390 }
391 
392 static QemuOptsList raw_runtime_opts = {
393     .name = "raw",
394     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
395     .desc = {
396         {
397             .name = "filename",
398             .type = QEMU_OPT_STRING,
399             .help = "File name of the image",
400         },
401         {
402             .name = "aio",
403             .type = QEMU_OPT_STRING,
404             .help = "host AIO implementation (threads, native)",
405         },
406         {
407             .name = "locking",
408             .type = QEMU_OPT_STRING,
409             .help = "file locking mode (on/off/auto, default: auto)",
410         },
411         { /* end of list */ }
412     },
413 };
414 
415 static int raw_open_common(BlockDriverState *bs, QDict *options,
416                            int bdrv_flags, int open_flags, Error **errp)
417 {
418     BDRVRawState *s = bs->opaque;
419     QemuOpts *opts;
420     Error *local_err = NULL;
421     const char *filename = NULL;
422     BlockdevAioOptions aio, aio_default;
423     int fd, ret;
424     struct stat st;
425     OnOffAuto locking;
426 
427     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
428     qemu_opts_absorb_qdict(opts, options, &local_err);
429     if (local_err) {
430         error_propagate(errp, local_err);
431         ret = -EINVAL;
432         goto fail;
433     }
434 
435     filename = qemu_opt_get(opts, "filename");
436 
437     ret = raw_normalize_devicepath(&filename);
438     if (ret != 0) {
439         error_setg_errno(errp, -ret, "Could not normalize device path");
440         goto fail;
441     }
442 
443     aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
444                   ? BLOCKDEV_AIO_OPTIONS_NATIVE
445                   : BLOCKDEV_AIO_OPTIONS_THREADS;
446     aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
447                           BLOCKDEV_AIO_OPTIONS__MAX, aio_default, &local_err);
448     if (local_err) {
449         error_propagate(errp, local_err);
450         ret = -EINVAL;
451         goto fail;
452     }
453     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
454 
455     locking = qapi_enum_parse(OnOffAuto_lookup, qemu_opt_get(opts, "locking"),
456                               ON_OFF_AUTO__MAX, ON_OFF_AUTO_AUTO, &local_err);
457     if (local_err) {
458         error_propagate(errp, local_err);
459         ret = -EINVAL;
460         goto fail;
461     }
462     switch (locking) {
463     case ON_OFF_AUTO_ON:
464         s->use_lock = true;
465 #ifndef F_OFD_SETLK
466         fprintf(stderr,
467                 "File lock requested but OFD locking syscall is unavailable, "
468                 "falling back to POSIX file locks.\n"
469                 "Due to the implementation, locks can be lost unexpectedly.\n");
470 #endif
471         break;
472     case ON_OFF_AUTO_OFF:
473         s->use_lock = false;
474         break;
475     case ON_OFF_AUTO_AUTO:
476 #ifdef F_OFD_SETLK
477         s->use_lock = true;
478 #else
479         s->use_lock = false;
480 #endif
481         break;
482     default:
483         abort();
484     }
485 
486     s->open_flags = open_flags;
487     raw_parse_flags(bdrv_flags, &s->open_flags);
488 
489     s->fd = -1;
490     fd = qemu_open(filename, s->open_flags, 0644);
491     if (fd < 0) {
492         ret = -errno;
493         error_setg_errno(errp, errno, "Could not open '%s'", filename);
494         if (ret == -EROFS) {
495             ret = -EACCES;
496         }
497         goto fail;
498     }
499     s->fd = fd;
500 
501     s->lock_fd = -1;
502     if (s->use_lock) {
503         fd = qemu_open(filename, s->open_flags);
504         if (fd < 0) {
505             ret = -errno;
506             error_setg_errno(errp, errno, "Could not open '%s' for locking",
507                              filename);
508             qemu_close(s->fd);
509             goto fail;
510         }
511         s->lock_fd = fd;
512     }
513     s->perm = 0;
514     s->shared_perm = BLK_PERM_ALL;
515 
516 #ifdef CONFIG_LINUX_AIO
517      /* Currently Linux does AIO only for files opened with O_DIRECT */
518     if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {
519         error_setg(errp, "aio=native was specified, but it requires "
520                          "cache.direct=on, which was not specified.");
521         ret = -EINVAL;
522         goto fail;
523     }
524 #else
525     if (s->use_linux_aio) {
526         error_setg(errp, "aio=native was specified, but is not supported "
527                          "in this build.");
528         ret = -EINVAL;
529         goto fail;
530     }
531 #endif /* !defined(CONFIG_LINUX_AIO) */
532 
533     s->has_discard = true;
534     s->has_write_zeroes = true;
535     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
536     if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
537         s->needs_alignment = true;
538     }
539 
540     if (fstat(s->fd, &st) < 0) {
541         ret = -errno;
542         error_setg_errno(errp, errno, "Could not stat file");
543         goto fail;
544     }
545     if (S_ISREG(st.st_mode)) {
546         s->discard_zeroes = true;
547         s->has_fallocate = true;
548     }
549     if (S_ISBLK(st.st_mode)) {
550 #ifdef BLKDISCARDZEROES
551         unsigned int arg;
552         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
553             s->discard_zeroes = true;
554         }
555 #endif
556 #ifdef __linux__
557         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
558          * not rely on the contents of discarded blocks unless using O_DIRECT.
559          * Same for BLKZEROOUT.
560          */
561         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
562             s->discard_zeroes = false;
563             s->has_write_zeroes = false;
564         }
565 #endif
566     }
567 #ifdef __FreeBSD__
568     if (S_ISCHR(st.st_mode)) {
569         /*
570          * The file is a char device (disk), which on FreeBSD isn't behind
571          * a pager, so force all requests to be aligned. This is needed
572          * so QEMU makes sure all IO operations on the device are aligned
573          * to sector size, or else FreeBSD will reject them with EINVAL.
574          */
575         s->needs_alignment = true;
576     }
577 #endif
578 
579 #ifdef CONFIG_XFS
580     if (platform_test_xfs_fd(s->fd)) {
581         s->is_xfs = true;
582     }
583 #endif
584 
585     ret = 0;
586 fail:
587     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
588         unlink(filename);
589     }
590     qemu_opts_del(opts);
591     return ret;
592 }
593 
594 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
595                     Error **errp)
596 {
597     BDRVRawState *s = bs->opaque;
598 
599     s->type = FTYPE_FILE;
600     return raw_open_common(bs, options, flags, 0, errp);
601 }
602 
603 typedef enum {
604     RAW_PL_PREPARE,
605     RAW_PL_COMMIT,
606     RAW_PL_ABORT,
607 } RawPermLockOp;
608 
609 #define PERM_FOREACH(i) \
610     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
611 
612 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
613  * file; if @unlock == true, also unlock the unneeded bytes.
614  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
615  */
616 static int raw_apply_lock_bytes(BDRVRawState *s,
617                                 uint64_t perm_lock_bits,
618                                 uint64_t shared_perm_lock_bits,
619                                 bool unlock, Error **errp)
620 {
621     int ret;
622     int i;
623 
624     PERM_FOREACH(i) {
625         int off = RAW_LOCK_PERM_BASE + i;
626         if (perm_lock_bits & (1ULL << i)) {
627             ret = qemu_lock_fd(s->lock_fd, off, 1, false);
628             if (ret) {
629                 error_setg(errp, "Failed to lock byte %d", off);
630                 return ret;
631             }
632         } else if (unlock) {
633             ret = qemu_unlock_fd(s->lock_fd, off, 1);
634             if (ret) {
635                 error_setg(errp, "Failed to unlock byte %d", off);
636                 return ret;
637             }
638         }
639     }
640     PERM_FOREACH(i) {
641         int off = RAW_LOCK_SHARED_BASE + i;
642         if (shared_perm_lock_bits & (1ULL << i)) {
643             ret = qemu_lock_fd(s->lock_fd, off, 1, false);
644             if (ret) {
645                 error_setg(errp, "Failed to lock byte %d", off);
646                 return ret;
647             }
648         } else if (unlock) {
649             ret = qemu_unlock_fd(s->lock_fd, off, 1);
650             if (ret) {
651                 error_setg(errp, "Failed to unlock byte %d", off);
652                 return ret;
653             }
654         }
655     }
656     return 0;
657 }
658 
659 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
660 static int raw_check_lock_bytes(BDRVRawState *s,
661                                 uint64_t perm, uint64_t shared_perm,
662                                 Error **errp)
663 {
664     int ret;
665     int i;
666 
667     PERM_FOREACH(i) {
668         int off = RAW_LOCK_SHARED_BASE + i;
669         uint64_t p = 1ULL << i;
670         if (perm & p) {
671             ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
672             if (ret) {
673                 char *perm_name = bdrv_perm_names(p);
674                 error_setg(errp,
675                            "Failed to get \"%s\" lock",
676                            perm_name);
677                 g_free(perm_name);
678                 error_append_hint(errp,
679                                   "Is another process using the image?\n");
680                 return ret;
681             }
682         }
683     }
684     PERM_FOREACH(i) {
685         int off = RAW_LOCK_PERM_BASE + i;
686         uint64_t p = 1ULL << i;
687         if (!(shared_perm & p)) {
688             ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
689             if (ret) {
690                 char *perm_name = bdrv_perm_names(p);
691                 error_setg(errp,
692                            "Failed to get shared \"%s\" lock",
693                            perm_name);
694                 g_free(perm_name);
695                 error_append_hint(errp,
696                                   "Is another process using the image?\n");
697                 return ret;
698             }
699         }
700     }
701     return 0;
702 }
703 
704 static int raw_handle_perm_lock(BlockDriverState *bs,
705                                 RawPermLockOp op,
706                                 uint64_t new_perm, uint64_t new_shared,
707                                 Error **errp)
708 {
709     BDRVRawState *s = bs->opaque;
710     int ret = 0;
711     Error *local_err = NULL;
712 
713     if (!s->use_lock) {
714         return 0;
715     }
716 
717     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
718         return 0;
719     }
720 
721     assert(s->lock_fd > 0);
722 
723     switch (op) {
724     case RAW_PL_PREPARE:
725         ret = raw_apply_lock_bytes(s, s->perm | new_perm,
726                                    ~s->shared_perm | ~new_shared,
727                                    false, errp);
728         if (!ret) {
729             ret = raw_check_lock_bytes(s, new_perm, new_shared, errp);
730             if (!ret) {
731                 return 0;
732             }
733         }
734         op = RAW_PL_ABORT;
735         /* fall through to unlock bytes. */
736     case RAW_PL_ABORT:
737         raw_apply_lock_bytes(s, s->perm, ~s->shared_perm, true, &local_err);
738         if (local_err) {
739             /* Theoretically the above call only unlocks bytes and it cannot
740              * fail. Something weird happened, report it.
741              */
742             error_report_err(local_err);
743         }
744         break;
745     case RAW_PL_COMMIT:
746         raw_apply_lock_bytes(s, new_perm, ~new_shared, true, &local_err);
747         if (local_err) {
748             /* Theoretically the above call only unlocks bytes and it cannot
749              * fail. Something weird happened, report it.
750              */
751             error_report_err(local_err);
752         }
753         break;
754     }
755     return ret;
756 }
757 
758 static int raw_reopen_prepare(BDRVReopenState *state,
759                               BlockReopenQueue *queue, Error **errp)
760 {
761     BDRVRawState *s;
762     BDRVRawReopenState *rs;
763     int ret = 0;
764     Error *local_err = NULL;
765 
766     assert(state != NULL);
767     assert(state->bs != NULL);
768 
769     s = state->bs->opaque;
770 
771     state->opaque = g_new0(BDRVRawReopenState, 1);
772     rs = state->opaque;
773 
774     if (s->type == FTYPE_CD) {
775         rs->open_flags |= O_NONBLOCK;
776     }
777 
778     raw_parse_flags(state->flags, &rs->open_flags);
779 
780     rs->fd = -1;
781 
782     int fcntl_flags = O_APPEND | O_NONBLOCK;
783 #ifdef O_NOATIME
784     fcntl_flags |= O_NOATIME;
785 #endif
786 
787 #ifdef O_ASYNC
788     /* Not all operating systems have O_ASYNC, and those that don't
789      * will not let us track the state into rs->open_flags (typically
790      * you achieve the same effect with an ioctl, for example I_SETSIG
791      * on Solaris). But we do not use O_ASYNC, so that's fine.
792      */
793     assert((s->open_flags & O_ASYNC) == 0);
794 #endif
795 
796     if ((rs->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
797         /* dup the original fd */
798         rs->fd = qemu_dup(s->fd);
799         if (rs->fd >= 0) {
800             ret = fcntl_setfl(rs->fd, rs->open_flags);
801             if (ret) {
802                 qemu_close(rs->fd);
803                 rs->fd = -1;
804             }
805         }
806     }
807 
808     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
809     if (rs->fd == -1) {
810         const char *normalized_filename = state->bs->filename;
811         ret = raw_normalize_devicepath(&normalized_filename);
812         if (ret < 0) {
813             error_setg_errno(errp, -ret, "Could not normalize device path");
814         } else {
815             assert(!(rs->open_flags & O_CREAT));
816             rs->fd = qemu_open(normalized_filename, rs->open_flags);
817             if (rs->fd == -1) {
818                 error_setg_errno(errp, errno, "Could not reopen file");
819                 ret = -1;
820             }
821         }
822     }
823 
824     /* Fail already reopen_prepare() if we can't get a working O_DIRECT
825      * alignment with the new fd. */
826     if (rs->fd != -1) {
827         raw_probe_alignment(state->bs, rs->fd, &local_err);
828         if (local_err) {
829             qemu_close(rs->fd);
830             rs->fd = -1;
831             error_propagate(errp, local_err);
832             ret = -EINVAL;
833         }
834     }
835 
836     return ret;
837 }
838 
839 static void raw_reopen_commit(BDRVReopenState *state)
840 {
841     BDRVRawReopenState *rs = state->opaque;
842     BDRVRawState *s = state->bs->opaque;
843 
844     s->open_flags = rs->open_flags;
845 
846     qemu_close(s->fd);
847     s->fd = rs->fd;
848 
849     g_free(state->opaque);
850     state->opaque = NULL;
851 }
852 
853 
854 static void raw_reopen_abort(BDRVReopenState *state)
855 {
856     BDRVRawReopenState *rs = state->opaque;
857 
858      /* nothing to do if NULL, we didn't get far enough */
859     if (rs == NULL) {
860         return;
861     }
862 
863     if (rs->fd >= 0) {
864         qemu_close(rs->fd);
865         rs->fd = -1;
866     }
867     g_free(state->opaque);
868     state->opaque = NULL;
869 }
870 
871 static int hdev_get_max_transfer_length(BlockDriverState *bs, int fd)
872 {
873 #ifdef BLKSECTGET
874     int max_bytes = 0;
875     short max_sectors = 0;
876     if (bs->sg && ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
877         return max_bytes;
878     } else if (!bs->sg && ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
879         return max_sectors << BDRV_SECTOR_BITS;
880     } else {
881         return -errno;
882     }
883 #else
884     return -ENOSYS;
885 #endif
886 }
887 
888 static int hdev_get_max_segments(const struct stat *st)
889 {
890 #ifdef CONFIG_LINUX
891     char buf[32];
892     const char *end;
893     char *sysfspath;
894     int ret;
895     int fd = -1;
896     long max_segments;
897 
898     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
899                                 major(st->st_rdev), minor(st->st_rdev));
900     fd = open(sysfspath, O_RDONLY);
901     if (fd == -1) {
902         ret = -errno;
903         goto out;
904     }
905     do {
906         ret = read(fd, buf, sizeof(buf) - 1);
907     } while (ret == -1 && errno == EINTR);
908     if (ret < 0) {
909         ret = -errno;
910         goto out;
911     } else if (ret == 0) {
912         ret = -EIO;
913         goto out;
914     }
915     buf[ret] = 0;
916     /* The file is ended with '\n', pass 'end' to accept that. */
917     ret = qemu_strtol(buf, &end, 10, &max_segments);
918     if (ret == 0 && end && *end == '\n') {
919         ret = max_segments;
920     }
921 
922 out:
923     if (fd != -1) {
924         close(fd);
925     }
926     g_free(sysfspath);
927     return ret;
928 #else
929     return -ENOTSUP;
930 #endif
931 }
932 
933 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
934 {
935     BDRVRawState *s = bs->opaque;
936     struct stat st;
937 
938     if (!fstat(s->fd, &st)) {
939         if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
940             int ret = hdev_get_max_transfer_length(bs, s->fd);
941             if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
942                 bs->bl.max_transfer = pow2floor(ret);
943             }
944             ret = hdev_get_max_segments(&st);
945             if (ret > 0) {
946                 bs->bl.max_transfer = MIN(bs->bl.max_transfer,
947                                           ret * getpagesize());
948             }
949         }
950     }
951 
952     raw_probe_alignment(bs, s->fd, errp);
953     bs->bl.min_mem_alignment = s->buf_align;
954     bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
955 }
956 
957 static int check_for_dasd(int fd)
958 {
959 #ifdef BIODASDINFO2
960     struct dasd_information2_t info = {0};
961 
962     return ioctl(fd, BIODASDINFO2, &info);
963 #else
964     return -1;
965 #endif
966 }
967 
968 /**
969  * Try to get @bs's logical and physical block size.
970  * On success, store them in @bsz and return zero.
971  * On failure, return negative errno.
972  */
973 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
974 {
975     BDRVRawState *s = bs->opaque;
976     int ret;
977 
978     /* If DASD, get blocksizes */
979     if (check_for_dasd(s->fd) < 0) {
980         return -ENOTSUP;
981     }
982     ret = probe_logical_blocksize(s->fd, &bsz->log);
983     if (ret < 0) {
984         return ret;
985     }
986     return probe_physical_blocksize(s->fd, &bsz->phys);
987 }
988 
989 /**
990  * Try to get @bs's geometry: cyls, heads, sectors.
991  * On success, store them in @geo and return 0.
992  * On failure return -errno.
993  * (Allows block driver to assign default geometry values that guest sees)
994  */
995 #ifdef __linux__
996 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
997 {
998     BDRVRawState *s = bs->opaque;
999     struct hd_geometry ioctl_geo = {0};
1000 
1001     /* If DASD, get its geometry */
1002     if (check_for_dasd(s->fd) < 0) {
1003         return -ENOTSUP;
1004     }
1005     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1006         return -errno;
1007     }
1008     /* HDIO_GETGEO may return success even though geo contains zeros
1009        (e.g. certain multipath setups) */
1010     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1011         return -ENOTSUP;
1012     }
1013     /* Do not return a geometry for partition */
1014     if (ioctl_geo.start != 0) {
1015         return -ENOTSUP;
1016     }
1017     geo->heads = ioctl_geo.heads;
1018     geo->sectors = ioctl_geo.sectors;
1019     geo->cylinders = ioctl_geo.cylinders;
1020 
1021     return 0;
1022 }
1023 #else /* __linux__ */
1024 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1025 {
1026     return -ENOTSUP;
1027 }
1028 #endif
1029 
1030 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
1031 {
1032     int ret;
1033 
1034     ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
1035     if (ret == -1) {
1036         return -errno;
1037     }
1038 
1039     return 0;
1040 }
1041 
1042 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
1043 {
1044     BDRVRawState *s = aiocb->bs->opaque;
1045     int ret;
1046 
1047     if (s->page_cache_inconsistent) {
1048         return -EIO;
1049     }
1050 
1051     ret = qemu_fdatasync(aiocb->aio_fildes);
1052     if (ret == -1) {
1053         /* There is no clear definition of the semantics of a failing fsync(),
1054          * so we may have to assume the worst. The sad truth is that this
1055          * assumption is correct for Linux. Some pages are now probably marked
1056          * clean in the page cache even though they are inconsistent with the
1057          * on-disk contents. The next fdatasync() call would succeed, but no
1058          * further writeback attempt will be made. We can't get back to a state
1059          * in which we know what is on disk (we would have to rewrite
1060          * everything that was touched since the last fdatasync() at least), so
1061          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1062          * really defined, I have little hope that other OSes are doing better.
1063          *
1064          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1065          * cache. */
1066         if ((s->open_flags & O_DIRECT) == 0) {
1067             s->page_cache_inconsistent = true;
1068         }
1069         return -errno;
1070     }
1071     return 0;
1072 }
1073 
1074 #ifdef CONFIG_PREADV
1075 
1076 static bool preadv_present = true;
1077 
1078 static ssize_t
1079 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1080 {
1081     return preadv(fd, iov, nr_iov, offset);
1082 }
1083 
1084 static ssize_t
1085 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1086 {
1087     return pwritev(fd, iov, nr_iov, offset);
1088 }
1089 
1090 #else
1091 
1092 static bool preadv_present = false;
1093 
1094 static ssize_t
1095 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1096 {
1097     return -ENOSYS;
1098 }
1099 
1100 static ssize_t
1101 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1102 {
1103     return -ENOSYS;
1104 }
1105 
1106 #endif
1107 
1108 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1109 {
1110     ssize_t len;
1111 
1112     do {
1113         if (aiocb->aio_type & QEMU_AIO_WRITE)
1114             len = qemu_pwritev(aiocb->aio_fildes,
1115                                aiocb->aio_iov,
1116                                aiocb->aio_niov,
1117                                aiocb->aio_offset);
1118          else
1119             len = qemu_preadv(aiocb->aio_fildes,
1120                               aiocb->aio_iov,
1121                               aiocb->aio_niov,
1122                               aiocb->aio_offset);
1123     } while (len == -1 && errno == EINTR);
1124 
1125     if (len == -1) {
1126         return -errno;
1127     }
1128     return len;
1129 }
1130 
1131 /*
1132  * Read/writes the data to/from a given linear buffer.
1133  *
1134  * Returns the number of bytes handles or -errno in case of an error. Short
1135  * reads are only returned if the end of the file is reached.
1136  */
1137 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1138 {
1139     ssize_t offset = 0;
1140     ssize_t len;
1141 
1142     while (offset < aiocb->aio_nbytes) {
1143         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1144             len = pwrite(aiocb->aio_fildes,
1145                          (const char *)buf + offset,
1146                          aiocb->aio_nbytes - offset,
1147                          aiocb->aio_offset + offset);
1148         } else {
1149             len = pread(aiocb->aio_fildes,
1150                         buf + offset,
1151                         aiocb->aio_nbytes - offset,
1152                         aiocb->aio_offset + offset);
1153         }
1154         if (len == -1 && errno == EINTR) {
1155             continue;
1156         } else if (len == -1 && errno == EINVAL &&
1157                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1158                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1159                    offset > 0) {
1160             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1161              * after a short read.  Assume that O_DIRECT short reads only occur
1162              * at EOF.  Therefore this is a short read, not an I/O error.
1163              */
1164             break;
1165         } else if (len == -1) {
1166             offset = -errno;
1167             break;
1168         } else if (len == 0) {
1169             break;
1170         }
1171         offset += len;
1172     }
1173 
1174     return offset;
1175 }
1176 
1177 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
1178 {
1179     ssize_t nbytes;
1180     char *buf;
1181 
1182     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1183         /*
1184          * If there is just a single buffer, and it is properly aligned
1185          * we can just use plain pread/pwrite without any problems.
1186          */
1187         if (aiocb->aio_niov == 1) {
1188              return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
1189         }
1190         /*
1191          * We have more than one iovec, and all are properly aligned.
1192          *
1193          * Try preadv/pwritev first and fall back to linearizing the
1194          * buffer if it's not supported.
1195          */
1196         if (preadv_present) {
1197             nbytes = handle_aiocb_rw_vector(aiocb);
1198             if (nbytes == aiocb->aio_nbytes ||
1199                 (nbytes < 0 && nbytes != -ENOSYS)) {
1200                 return nbytes;
1201             }
1202             preadv_present = false;
1203         }
1204 
1205         /*
1206          * XXX(hch): short read/write.  no easy way to handle the reminder
1207          * using these interfaces.  For now retry using plain
1208          * pread/pwrite?
1209          */
1210     }
1211 
1212     /*
1213      * Ok, we have to do it the hard way, copy all segments into
1214      * a single aligned buffer.
1215      */
1216     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1217     if (buf == NULL) {
1218         return -ENOMEM;
1219     }
1220 
1221     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1222         char *p = buf;
1223         int i;
1224 
1225         for (i = 0; i < aiocb->aio_niov; ++i) {
1226             memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1227             p += aiocb->aio_iov[i].iov_len;
1228         }
1229         assert(p - buf == aiocb->aio_nbytes);
1230     }
1231 
1232     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1233     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1234         char *p = buf;
1235         size_t count = aiocb->aio_nbytes, copy;
1236         int i;
1237 
1238         for (i = 0; i < aiocb->aio_niov && count; ++i) {
1239             copy = count;
1240             if (copy > aiocb->aio_iov[i].iov_len) {
1241                 copy = aiocb->aio_iov[i].iov_len;
1242             }
1243             memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1244             assert(count >= copy);
1245             p     += copy;
1246             count -= copy;
1247         }
1248         assert(count == 0);
1249     }
1250     qemu_vfree(buf);
1251 
1252     return nbytes;
1253 }
1254 
1255 #ifdef CONFIG_XFS
1256 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1257 {
1258     struct xfs_flock64 fl;
1259     int err;
1260 
1261     memset(&fl, 0, sizeof(fl));
1262     fl.l_whence = SEEK_SET;
1263     fl.l_start = offset;
1264     fl.l_len = bytes;
1265 
1266     if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1267         err = errno;
1268         DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1269         return -err;
1270     }
1271 
1272     return 0;
1273 }
1274 
1275 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1276 {
1277     struct xfs_flock64 fl;
1278     int err;
1279 
1280     memset(&fl, 0, sizeof(fl));
1281     fl.l_whence = SEEK_SET;
1282     fl.l_start = offset;
1283     fl.l_len = bytes;
1284 
1285     if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1286         err = errno;
1287         DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1288         return -err;
1289     }
1290 
1291     return 0;
1292 }
1293 #endif
1294 
1295 static int translate_err(int err)
1296 {
1297     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1298         err == -ENOTTY) {
1299         err = -ENOTSUP;
1300     }
1301     return err;
1302 }
1303 
1304 #ifdef CONFIG_FALLOCATE
1305 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1306 {
1307     do {
1308         if (fallocate(fd, mode, offset, len) == 0) {
1309             return 0;
1310         }
1311     } while (errno == EINTR);
1312     return translate_err(-errno);
1313 }
1314 #endif
1315 
1316 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1317 {
1318     int ret = -ENOTSUP;
1319     BDRVRawState *s = aiocb->bs->opaque;
1320 
1321     if (!s->has_write_zeroes) {
1322         return -ENOTSUP;
1323     }
1324 
1325 #ifdef BLKZEROOUT
1326     do {
1327         uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1328         if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1329             return 0;
1330         }
1331     } while (errno == EINTR);
1332 
1333     ret = translate_err(-errno);
1334 #endif
1335 
1336     if (ret == -ENOTSUP) {
1337         s->has_write_zeroes = false;
1338     }
1339     return ret;
1340 }
1341 
1342 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1343 {
1344 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1345     BDRVRawState *s = aiocb->bs->opaque;
1346 #endif
1347 
1348     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1349         return handle_aiocb_write_zeroes_block(aiocb);
1350     }
1351 
1352 #ifdef CONFIG_XFS
1353     if (s->is_xfs) {
1354         return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1355     }
1356 #endif
1357 
1358 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1359     if (s->has_write_zeroes) {
1360         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1361                                aiocb->aio_offset, aiocb->aio_nbytes);
1362         if (ret == 0 || ret != -ENOTSUP) {
1363             return ret;
1364         }
1365         s->has_write_zeroes = false;
1366     }
1367 #endif
1368 
1369 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1370     if (s->has_discard && s->has_fallocate) {
1371         int ret = do_fallocate(s->fd,
1372                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1373                                aiocb->aio_offset, aiocb->aio_nbytes);
1374         if (ret == 0) {
1375             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1376             if (ret == 0 || ret != -ENOTSUP) {
1377                 return ret;
1378             }
1379             s->has_fallocate = false;
1380         } else if (ret != -ENOTSUP) {
1381             return ret;
1382         } else {
1383             s->has_discard = false;
1384         }
1385     }
1386 #endif
1387 
1388 #ifdef CONFIG_FALLOCATE
1389     if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1390         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1391         if (ret == 0 || ret != -ENOTSUP) {
1392             return ret;
1393         }
1394         s->has_fallocate = false;
1395     }
1396 #endif
1397 
1398     return -ENOTSUP;
1399 }
1400 
1401 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1402 {
1403     int ret = -EOPNOTSUPP;
1404     BDRVRawState *s = aiocb->bs->opaque;
1405 
1406     if (!s->has_discard) {
1407         return -ENOTSUP;
1408     }
1409 
1410     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1411 #ifdef BLKDISCARD
1412         do {
1413             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1414             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1415                 return 0;
1416             }
1417         } while (errno == EINTR);
1418 
1419         ret = -errno;
1420 #endif
1421     } else {
1422 #ifdef CONFIG_XFS
1423         if (s->is_xfs) {
1424             return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1425         }
1426 #endif
1427 
1428 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1429         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1430                            aiocb->aio_offset, aiocb->aio_nbytes);
1431 #endif
1432     }
1433 
1434     ret = translate_err(ret);
1435     if (ret == -ENOTSUP) {
1436         s->has_discard = false;
1437     }
1438     return ret;
1439 }
1440 
1441 static int aio_worker(void *arg)
1442 {
1443     RawPosixAIOData *aiocb = arg;
1444     ssize_t ret = 0;
1445 
1446     switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1447     case QEMU_AIO_READ:
1448         ret = handle_aiocb_rw(aiocb);
1449         if (ret >= 0 && ret < aiocb->aio_nbytes) {
1450             iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1451                       0, aiocb->aio_nbytes - ret);
1452 
1453             ret = aiocb->aio_nbytes;
1454         }
1455         if (ret == aiocb->aio_nbytes) {
1456             ret = 0;
1457         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1458             ret = -EINVAL;
1459         }
1460         break;
1461     case QEMU_AIO_WRITE:
1462         ret = handle_aiocb_rw(aiocb);
1463         if (ret == aiocb->aio_nbytes) {
1464             ret = 0;
1465         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1466             ret = -EINVAL;
1467         }
1468         break;
1469     case QEMU_AIO_FLUSH:
1470         ret = handle_aiocb_flush(aiocb);
1471         break;
1472     case QEMU_AIO_IOCTL:
1473         ret = handle_aiocb_ioctl(aiocb);
1474         break;
1475     case QEMU_AIO_DISCARD:
1476         ret = handle_aiocb_discard(aiocb);
1477         break;
1478     case QEMU_AIO_WRITE_ZEROES:
1479         ret = handle_aiocb_write_zeroes(aiocb);
1480         break;
1481     default:
1482         fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1483         ret = -EINVAL;
1484         break;
1485     }
1486 
1487     g_free(aiocb);
1488     return ret;
1489 }
1490 
1491 static int paio_submit_co(BlockDriverState *bs, int fd,
1492                           int64_t offset, QEMUIOVector *qiov,
1493                           int count, int type)
1494 {
1495     RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1496     ThreadPool *pool;
1497 
1498     acb->bs = bs;
1499     acb->aio_type = type;
1500     acb->aio_fildes = fd;
1501 
1502     acb->aio_nbytes = count;
1503     acb->aio_offset = offset;
1504 
1505     if (qiov) {
1506         acb->aio_iov = qiov->iov;
1507         acb->aio_niov = qiov->niov;
1508         assert(qiov->size == count);
1509     }
1510 
1511     trace_paio_submit_co(offset, count, type);
1512     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1513     return thread_pool_submit_co(pool, aio_worker, acb);
1514 }
1515 
1516 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1517         int64_t offset, QEMUIOVector *qiov, int count,
1518         BlockCompletionFunc *cb, void *opaque, int type)
1519 {
1520     RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1521     ThreadPool *pool;
1522 
1523     acb->bs = bs;
1524     acb->aio_type = type;
1525     acb->aio_fildes = fd;
1526 
1527     acb->aio_nbytes = count;
1528     acb->aio_offset = offset;
1529 
1530     if (qiov) {
1531         acb->aio_iov = qiov->iov;
1532         acb->aio_niov = qiov->niov;
1533         assert(qiov->size == acb->aio_nbytes);
1534     }
1535 
1536     trace_paio_submit(acb, opaque, offset, count, type);
1537     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1538     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1539 }
1540 
1541 static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1542                                    uint64_t bytes, QEMUIOVector *qiov, int type)
1543 {
1544     BDRVRawState *s = bs->opaque;
1545 
1546     if (fd_open(bs) < 0)
1547         return -EIO;
1548 
1549     /*
1550      * Check if the underlying device requires requests to be aligned,
1551      * and if the request we are trying to submit is aligned or not.
1552      * If this is the case tell the low-level driver that it needs
1553      * to copy the buffer.
1554      */
1555     if (s->needs_alignment) {
1556         if (!bdrv_qiov_is_aligned(bs, qiov)) {
1557             type |= QEMU_AIO_MISALIGNED;
1558 #ifdef CONFIG_LINUX_AIO
1559         } else if (s->use_linux_aio) {
1560             LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1561             assert(qiov->size == bytes);
1562             return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
1563 #endif
1564         }
1565     }
1566 
1567     return paio_submit_co(bs, s->fd, offset, qiov, bytes, type);
1568 }
1569 
1570 static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1571                                       uint64_t bytes, QEMUIOVector *qiov,
1572                                       int flags)
1573 {
1574     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
1575 }
1576 
1577 static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1578                                        uint64_t bytes, QEMUIOVector *qiov,
1579                                        int flags)
1580 {
1581     assert(flags == 0);
1582     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
1583 }
1584 
1585 static void raw_aio_plug(BlockDriverState *bs)
1586 {
1587 #ifdef CONFIG_LINUX_AIO
1588     BDRVRawState *s = bs->opaque;
1589     if (s->use_linux_aio) {
1590         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1591         laio_io_plug(bs, aio);
1592     }
1593 #endif
1594 }
1595 
1596 static void raw_aio_unplug(BlockDriverState *bs)
1597 {
1598 #ifdef CONFIG_LINUX_AIO
1599     BDRVRawState *s = bs->opaque;
1600     if (s->use_linux_aio) {
1601         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1602         laio_io_unplug(bs, aio);
1603     }
1604 #endif
1605 }
1606 
1607 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1608         BlockCompletionFunc *cb, void *opaque)
1609 {
1610     BDRVRawState *s = bs->opaque;
1611 
1612     if (fd_open(bs) < 0)
1613         return NULL;
1614 
1615     return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1616 }
1617 
1618 static void raw_close(BlockDriverState *bs)
1619 {
1620     BDRVRawState *s = bs->opaque;
1621 
1622     if (s->fd >= 0) {
1623         qemu_close(s->fd);
1624         s->fd = -1;
1625     }
1626     if (s->lock_fd >= 0) {
1627         qemu_close(s->lock_fd);
1628         s->lock_fd = -1;
1629     }
1630 }
1631 
1632 static int raw_truncate(BlockDriverState *bs, int64_t offset, Error **errp)
1633 {
1634     BDRVRawState *s = bs->opaque;
1635     struct stat st;
1636     int ret;
1637 
1638     if (fstat(s->fd, &st)) {
1639         ret = -errno;
1640         error_setg_errno(errp, -ret, "Failed to fstat() the file");
1641         return ret;
1642     }
1643 
1644     if (S_ISREG(st.st_mode)) {
1645         if (ftruncate(s->fd, offset) < 0) {
1646             ret = -errno;
1647             error_setg_errno(errp, -ret, "Failed to resize the file");
1648             return ret;
1649         }
1650     } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1651         if (offset > raw_getlength(bs)) {
1652             error_setg(errp, "Cannot grow device files");
1653             return -EINVAL;
1654         }
1655     } else {
1656         error_setg(errp, "Resizing this file is not supported");
1657         return -ENOTSUP;
1658     }
1659 
1660     return 0;
1661 }
1662 
1663 #ifdef __OpenBSD__
1664 static int64_t raw_getlength(BlockDriverState *bs)
1665 {
1666     BDRVRawState *s = bs->opaque;
1667     int fd = s->fd;
1668     struct stat st;
1669 
1670     if (fstat(fd, &st))
1671         return -errno;
1672     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1673         struct disklabel dl;
1674 
1675         if (ioctl(fd, DIOCGDINFO, &dl))
1676             return -errno;
1677         return (uint64_t)dl.d_secsize *
1678             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1679     } else
1680         return st.st_size;
1681 }
1682 #elif defined(__NetBSD__)
1683 static int64_t raw_getlength(BlockDriverState *bs)
1684 {
1685     BDRVRawState *s = bs->opaque;
1686     int fd = s->fd;
1687     struct stat st;
1688 
1689     if (fstat(fd, &st))
1690         return -errno;
1691     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1692         struct dkwedge_info dkw;
1693 
1694         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1695             return dkw.dkw_size * 512;
1696         } else {
1697             struct disklabel dl;
1698 
1699             if (ioctl(fd, DIOCGDINFO, &dl))
1700                 return -errno;
1701             return (uint64_t)dl.d_secsize *
1702                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1703         }
1704     } else
1705         return st.st_size;
1706 }
1707 #elif defined(__sun__)
1708 static int64_t raw_getlength(BlockDriverState *bs)
1709 {
1710     BDRVRawState *s = bs->opaque;
1711     struct dk_minfo minfo;
1712     int ret;
1713     int64_t size;
1714 
1715     ret = fd_open(bs);
1716     if (ret < 0) {
1717         return ret;
1718     }
1719 
1720     /*
1721      * Use the DKIOCGMEDIAINFO ioctl to read the size.
1722      */
1723     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1724     if (ret != -1) {
1725         return minfo.dki_lbsize * minfo.dki_capacity;
1726     }
1727 
1728     /*
1729      * There are reports that lseek on some devices fails, but
1730      * irc discussion said that contingency on contingency was overkill.
1731      */
1732     size = lseek(s->fd, 0, SEEK_END);
1733     if (size < 0) {
1734         return -errno;
1735     }
1736     return size;
1737 }
1738 #elif defined(CONFIG_BSD)
1739 static int64_t raw_getlength(BlockDriverState *bs)
1740 {
1741     BDRVRawState *s = bs->opaque;
1742     int fd = s->fd;
1743     int64_t size;
1744     struct stat sb;
1745 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1746     int reopened = 0;
1747 #endif
1748     int ret;
1749 
1750     ret = fd_open(bs);
1751     if (ret < 0)
1752         return ret;
1753 
1754 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1755 again:
1756 #endif
1757     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1758 #ifdef DIOCGMEDIASIZE
1759 	if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1760 #elif defined(DIOCGPART)
1761         {
1762                 struct partinfo pi;
1763                 if (ioctl(fd, DIOCGPART, &pi) == 0)
1764                         size = pi.media_size;
1765                 else
1766                         size = 0;
1767         }
1768         if (size == 0)
1769 #endif
1770 #if defined(__APPLE__) && defined(__MACH__)
1771         {
1772             uint64_t sectors = 0;
1773             uint32_t sector_size = 0;
1774 
1775             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1776                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1777                 size = sectors * sector_size;
1778             } else {
1779                 size = lseek(fd, 0LL, SEEK_END);
1780                 if (size < 0) {
1781                     return -errno;
1782                 }
1783             }
1784         }
1785 #else
1786         size = lseek(fd, 0LL, SEEK_END);
1787         if (size < 0) {
1788             return -errno;
1789         }
1790 #endif
1791 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1792         switch(s->type) {
1793         case FTYPE_CD:
1794             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1795             if (size == 2048LL * (unsigned)-1)
1796                 size = 0;
1797             /* XXX no disc?  maybe we need to reopen... */
1798             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1799                 reopened = 1;
1800                 goto again;
1801             }
1802         }
1803 #endif
1804     } else {
1805         size = lseek(fd, 0, SEEK_END);
1806         if (size < 0) {
1807             return -errno;
1808         }
1809     }
1810     return size;
1811 }
1812 #else
1813 static int64_t raw_getlength(BlockDriverState *bs)
1814 {
1815     BDRVRawState *s = bs->opaque;
1816     int ret;
1817     int64_t size;
1818 
1819     ret = fd_open(bs);
1820     if (ret < 0) {
1821         return ret;
1822     }
1823 
1824     size = lseek(s->fd, 0, SEEK_END);
1825     if (size < 0) {
1826         return -errno;
1827     }
1828     return size;
1829 }
1830 #endif
1831 
1832 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1833 {
1834     struct stat st;
1835     BDRVRawState *s = bs->opaque;
1836 
1837     if (fstat(s->fd, &st) < 0) {
1838         return -errno;
1839     }
1840     return (int64_t)st.st_blocks * 512;
1841 }
1842 
1843 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1844 {
1845     int fd;
1846     int result = 0;
1847     int64_t total_size = 0;
1848     bool nocow = false;
1849     PreallocMode prealloc;
1850     char *buf = NULL;
1851     Error *local_err = NULL;
1852 
1853     strstart(filename, "file:", &filename);
1854 
1855     /* Read out options */
1856     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1857                           BDRV_SECTOR_SIZE);
1858     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1859     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1860     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1861                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
1862                                &local_err);
1863     g_free(buf);
1864     if (local_err) {
1865         error_propagate(errp, local_err);
1866         result = -EINVAL;
1867         goto out;
1868     }
1869 
1870     fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
1871                    0644);
1872     if (fd < 0) {
1873         result = -errno;
1874         error_setg_errno(errp, -result, "Could not create file");
1875         goto out;
1876     }
1877 
1878     if (nocow) {
1879 #ifdef __linux__
1880         /* Set NOCOW flag to solve performance issue on fs like btrfs.
1881          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1882          * will be ignored since any failure of this operation should not
1883          * block the left work.
1884          */
1885         int attr;
1886         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1887             attr |= FS_NOCOW_FL;
1888             ioctl(fd, FS_IOC_SETFLAGS, &attr);
1889         }
1890 #endif
1891     }
1892 
1893     switch (prealloc) {
1894 #ifdef CONFIG_POSIX_FALLOCATE
1895     case PREALLOC_MODE_FALLOC:
1896         /*
1897          * Truncating before posix_fallocate() makes it about twice slower on
1898          * file systems that do not support fallocate(), trying to check if a
1899          * block is allocated before allocating it, so don't do that here.
1900          */
1901         result = -posix_fallocate(fd, 0, total_size);
1902         if (result != 0) {
1903             /* posix_fallocate() doesn't set errno. */
1904             error_setg_errno(errp, -result,
1905                              "Could not preallocate data for the new file");
1906         }
1907         break;
1908 #endif
1909     case PREALLOC_MODE_FULL:
1910     {
1911         /*
1912          * Knowing the final size from the beginning could allow the file
1913          * system driver to do less allocations and possibly avoid
1914          * fragmentation of the file.
1915          */
1916         if (ftruncate(fd, total_size) != 0) {
1917             result = -errno;
1918             error_setg_errno(errp, -result, "Could not resize file");
1919             goto out_close;
1920         }
1921 
1922         int64_t num = 0, left = total_size;
1923         buf = g_malloc0(65536);
1924 
1925         while (left > 0) {
1926             num = MIN(left, 65536);
1927             result = write(fd, buf, num);
1928             if (result < 0) {
1929                 result = -errno;
1930                 error_setg_errno(errp, -result,
1931                                  "Could not write to the new file");
1932                 break;
1933             }
1934             left -= result;
1935         }
1936         if (result >= 0) {
1937             result = fsync(fd);
1938             if (result < 0) {
1939                 result = -errno;
1940                 error_setg_errno(errp, -result,
1941                                  "Could not flush new file to disk");
1942             }
1943         }
1944         g_free(buf);
1945         break;
1946     }
1947     case PREALLOC_MODE_OFF:
1948         if (ftruncate(fd, total_size) != 0) {
1949             result = -errno;
1950             error_setg_errno(errp, -result, "Could not resize file");
1951         }
1952         break;
1953     default:
1954         result = -EINVAL;
1955         error_setg(errp, "Unsupported preallocation mode: %s",
1956                    PreallocMode_lookup[prealloc]);
1957         break;
1958     }
1959 
1960 out_close:
1961     if (qemu_close(fd) != 0 && result == 0) {
1962         result = -errno;
1963         error_setg_errno(errp, -result, "Could not close the new file");
1964     }
1965 out:
1966     return result;
1967 }
1968 
1969 /*
1970  * Find allocation range in @bs around offset @start.
1971  * May change underlying file descriptor's file offset.
1972  * If @start is not in a hole, store @start in @data, and the
1973  * beginning of the next hole in @hole, and return 0.
1974  * If @start is in a non-trailing hole, store @start in @hole and the
1975  * beginning of the next non-hole in @data, and return 0.
1976  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1977  * If we can't find out, return a negative errno other than -ENXIO.
1978  */
1979 static int find_allocation(BlockDriverState *bs, off_t start,
1980                            off_t *data, off_t *hole)
1981 {
1982 #if defined SEEK_HOLE && defined SEEK_DATA
1983     BDRVRawState *s = bs->opaque;
1984     off_t offs;
1985 
1986     /*
1987      * SEEK_DATA cases:
1988      * D1. offs == start: start is in data
1989      * D2. offs > start: start is in a hole, next data at offs
1990      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1991      *                              or start is beyond EOF
1992      *     If the latter happens, the file has been truncated behind
1993      *     our back since we opened it.  All bets are off then.
1994      *     Treating like a trailing hole is simplest.
1995      * D4. offs < 0, errno != ENXIO: we learned nothing
1996      */
1997     offs = lseek(s->fd, start, SEEK_DATA);
1998     if (offs < 0) {
1999         return -errno;          /* D3 or D4 */
2000     }
2001     assert(offs >= start);
2002 
2003     if (offs > start) {
2004         /* D2: in hole, next data at offs */
2005         *hole = start;
2006         *data = offs;
2007         return 0;
2008     }
2009 
2010     /* D1: in data, end not yet known */
2011 
2012     /*
2013      * SEEK_HOLE cases:
2014      * H1. offs == start: start is in a hole
2015      *     If this happens here, a hole has been dug behind our back
2016      *     since the previous lseek().
2017      * H2. offs > start: either start is in data, next hole at offs,
2018      *                   or start is in trailing hole, EOF at offs
2019      *     Linux treats trailing holes like any other hole: offs ==
2020      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2021      *     If that happens here, a hole has been dug behind our back
2022      *     since the previous lseek().
2023      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2024      *     If this happens, the file has been truncated behind our
2025      *     back since we opened it.  Treat it like a trailing hole.
2026      * H4. offs < 0, errno != ENXIO: we learned nothing
2027      *     Pretend we know nothing at all, i.e. "forget" about D1.
2028      */
2029     offs = lseek(s->fd, start, SEEK_HOLE);
2030     if (offs < 0) {
2031         return -errno;          /* D1 and (H3 or H4) */
2032     }
2033     assert(offs >= start);
2034 
2035     if (offs > start) {
2036         /*
2037          * D1 and H2: either in data, next hole at offs, or it was in
2038          * data but is now in a trailing hole.  In the latter case,
2039          * all bets are off.  Treating it as if it there was data all
2040          * the way to EOF is safe, so simply do that.
2041          */
2042         *data = start;
2043         *hole = offs;
2044         return 0;
2045     }
2046 
2047     /* D1 and H1 */
2048     return -EBUSY;
2049 #else
2050     return -ENOTSUP;
2051 #endif
2052 }
2053 
2054 /*
2055  * Returns the allocation status of the specified sectors.
2056  *
2057  * If 'sector_num' is beyond the end of the disk image the return value is 0
2058  * and 'pnum' is set to 0.
2059  *
2060  * 'pnum' is set to the number of sectors (including and immediately following
2061  * the specified sector) that are known to be in the same
2062  * allocated/unallocated state.
2063  *
2064  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2065  * beyond the end of the disk image it will be clamped.
2066  */
2067 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
2068                                                     int64_t sector_num,
2069                                                     int nb_sectors, int *pnum,
2070                                                     BlockDriverState **file)
2071 {
2072     off_t start, data = 0, hole = 0;
2073     int64_t total_size;
2074     int ret;
2075 
2076     ret = fd_open(bs);
2077     if (ret < 0) {
2078         return ret;
2079     }
2080 
2081     start = sector_num * BDRV_SECTOR_SIZE;
2082     total_size = bdrv_getlength(bs);
2083     if (total_size < 0) {
2084         return total_size;
2085     } else if (start >= total_size) {
2086         *pnum = 0;
2087         return 0;
2088     } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
2089         nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
2090     }
2091 
2092     ret = find_allocation(bs, start, &data, &hole);
2093     if (ret == -ENXIO) {
2094         /* Trailing hole */
2095         *pnum = nb_sectors;
2096         ret = BDRV_BLOCK_ZERO;
2097     } else if (ret < 0) {
2098         /* No info available, so pretend there are no holes */
2099         *pnum = nb_sectors;
2100         ret = BDRV_BLOCK_DATA;
2101     } else if (data == start) {
2102         /* On a data extent, compute sectors to the end of the extent,
2103          * possibly including a partial sector at EOF. */
2104         *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
2105         ret = BDRV_BLOCK_DATA;
2106     } else {
2107         /* On a hole, compute sectors to the beginning of the next extent.  */
2108         assert(hole == start);
2109         *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
2110         ret = BDRV_BLOCK_ZERO;
2111     }
2112     *file = bs;
2113     return ret | BDRV_BLOCK_OFFSET_VALID | start;
2114 }
2115 
2116 static coroutine_fn BlockAIOCB *raw_aio_pdiscard(BlockDriverState *bs,
2117     int64_t offset, int count,
2118     BlockCompletionFunc *cb, void *opaque)
2119 {
2120     BDRVRawState *s = bs->opaque;
2121 
2122     return paio_submit(bs, s->fd, offset, NULL, count,
2123                        cb, opaque, QEMU_AIO_DISCARD);
2124 }
2125 
2126 static int coroutine_fn raw_co_pwrite_zeroes(
2127     BlockDriverState *bs, int64_t offset,
2128     int count, BdrvRequestFlags flags)
2129 {
2130     BDRVRawState *s = bs->opaque;
2131 
2132     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2133         return paio_submit_co(bs, s->fd, offset, NULL, count,
2134                               QEMU_AIO_WRITE_ZEROES);
2135     } else if (s->discard_zeroes) {
2136         return paio_submit_co(bs, s->fd, offset, NULL, count,
2137                               QEMU_AIO_DISCARD);
2138     }
2139     return -ENOTSUP;
2140 }
2141 
2142 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2143 {
2144     BDRVRawState *s = bs->opaque;
2145 
2146     bdi->unallocated_blocks_are_zero = s->discard_zeroes;
2147     bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
2148     return 0;
2149 }
2150 
2151 static QemuOptsList raw_create_opts = {
2152     .name = "raw-create-opts",
2153     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2154     .desc = {
2155         {
2156             .name = BLOCK_OPT_SIZE,
2157             .type = QEMU_OPT_SIZE,
2158             .help = "Virtual disk size"
2159         },
2160         {
2161             .name = BLOCK_OPT_NOCOW,
2162             .type = QEMU_OPT_BOOL,
2163             .help = "Turn off copy-on-write (valid only on btrfs)"
2164         },
2165         {
2166             .name = BLOCK_OPT_PREALLOC,
2167             .type = QEMU_OPT_STRING,
2168             .help = "Preallocation mode (allowed values: off, falloc, full)"
2169         },
2170         { /* end of list */ }
2171     }
2172 };
2173 
2174 static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2175                           Error **errp)
2176 {
2177     return raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
2178 }
2179 
2180 static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
2181 {
2182     BDRVRawState *s = bs->opaque;
2183     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
2184     s->perm = perm;
2185     s->shared_perm = shared;
2186 }
2187 
2188 static void raw_abort_perm_update(BlockDriverState *bs)
2189 {
2190     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
2191 }
2192 
2193 BlockDriver bdrv_file = {
2194     .format_name = "file",
2195     .protocol_name = "file",
2196     .instance_size = sizeof(BDRVRawState),
2197     .bdrv_needs_filename = true,
2198     .bdrv_probe = NULL, /* no probe for protocols */
2199     .bdrv_parse_filename = raw_parse_filename,
2200     .bdrv_file_open = raw_open,
2201     .bdrv_reopen_prepare = raw_reopen_prepare,
2202     .bdrv_reopen_commit = raw_reopen_commit,
2203     .bdrv_reopen_abort = raw_reopen_abort,
2204     .bdrv_close = raw_close,
2205     .bdrv_create = raw_create,
2206     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2207     .bdrv_co_get_block_status = raw_co_get_block_status,
2208     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
2209 
2210     .bdrv_co_preadv         = raw_co_preadv,
2211     .bdrv_co_pwritev        = raw_co_pwritev,
2212     .bdrv_aio_flush = raw_aio_flush,
2213     .bdrv_aio_pdiscard = raw_aio_pdiscard,
2214     .bdrv_refresh_limits = raw_refresh_limits,
2215     .bdrv_io_plug = raw_aio_plug,
2216     .bdrv_io_unplug = raw_aio_unplug,
2217 
2218     .bdrv_truncate = raw_truncate,
2219     .bdrv_getlength = raw_getlength,
2220     .bdrv_get_info = raw_get_info,
2221     .bdrv_get_allocated_file_size
2222                         = raw_get_allocated_file_size,
2223     .bdrv_check_perm = raw_check_perm,
2224     .bdrv_set_perm   = raw_set_perm,
2225     .bdrv_abort_perm_update = raw_abort_perm_update,
2226     .create_opts = &raw_create_opts,
2227 };
2228 
2229 /***********************************************/
2230 /* host device */
2231 
2232 #if defined(__APPLE__) && defined(__MACH__)
2233 static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2234                                 CFIndex maxPathSize, int flags);
2235 static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
2236 {
2237     kern_return_t kernResult = KERN_FAILURE;
2238     mach_port_t     masterPort;
2239     CFMutableDictionaryRef  classesToMatch;
2240     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
2241     char *mediaType = NULL;
2242 
2243     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
2244     if ( KERN_SUCCESS != kernResult ) {
2245         printf( "IOMasterPort returned %d\n", kernResult );
2246     }
2247 
2248     int index;
2249     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
2250         classesToMatch = IOServiceMatching(matching_array[index]);
2251         if (classesToMatch == NULL) {
2252             error_report("IOServiceMatching returned NULL for %s",
2253                          matching_array[index]);
2254             continue;
2255         }
2256         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
2257                              kCFBooleanTrue);
2258         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
2259                                                   mediaIterator);
2260         if (kernResult != KERN_SUCCESS) {
2261             error_report("Note: IOServiceGetMatchingServices returned %d",
2262                          kernResult);
2263             continue;
2264         }
2265 
2266         /* If a match was found, leave the loop */
2267         if (*mediaIterator != 0) {
2268             DPRINTF("Matching using %s\n", matching_array[index]);
2269             mediaType = g_strdup(matching_array[index]);
2270             break;
2271         }
2272     }
2273     return mediaType;
2274 }
2275 
2276 kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2277                          CFIndex maxPathSize, int flags)
2278 {
2279     io_object_t     nextMedia;
2280     kern_return_t   kernResult = KERN_FAILURE;
2281     *bsdPath = '\0';
2282     nextMedia = IOIteratorNext( mediaIterator );
2283     if ( nextMedia )
2284     {
2285         CFTypeRef   bsdPathAsCFString;
2286     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2287         if ( bsdPathAsCFString ) {
2288             size_t devPathLength;
2289             strcpy( bsdPath, _PATH_DEV );
2290             if (flags & BDRV_O_NOCACHE) {
2291                 strcat(bsdPath, "r");
2292             }
2293             devPathLength = strlen( bsdPath );
2294             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2295                 kernResult = KERN_SUCCESS;
2296             }
2297             CFRelease( bsdPathAsCFString );
2298         }
2299         IOObjectRelease( nextMedia );
2300     }
2301 
2302     return kernResult;
2303 }
2304 
2305 /* Sets up a real cdrom for use in QEMU */
2306 static bool setup_cdrom(char *bsd_path, Error **errp)
2307 {
2308     int index, num_of_test_partitions = 2, fd;
2309     char test_partition[MAXPATHLEN];
2310     bool partition_found = false;
2311 
2312     /* look for a working partition */
2313     for (index = 0; index < num_of_test_partitions; index++) {
2314         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
2315                  index);
2316         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
2317         if (fd >= 0) {
2318             partition_found = true;
2319             qemu_close(fd);
2320             break;
2321         }
2322     }
2323 
2324     /* if a working partition on the device was not found */
2325     if (partition_found == false) {
2326         error_setg(errp, "Failed to find a working partition on disc");
2327     } else {
2328         DPRINTF("Using %s as optical disc\n", test_partition);
2329         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
2330     }
2331     return partition_found;
2332 }
2333 
2334 /* Prints directions on mounting and unmounting a device */
2335 static void print_unmounting_directions(const char *file_name)
2336 {
2337     error_report("If device %s is mounted on the desktop, unmount"
2338                  " it first before using it in QEMU", file_name);
2339     error_report("Command to unmount device: diskutil unmountDisk %s",
2340                  file_name);
2341     error_report("Command to mount device: diskutil mountDisk %s", file_name);
2342 }
2343 
2344 #endif /* defined(__APPLE__) && defined(__MACH__) */
2345 
2346 static int hdev_probe_device(const char *filename)
2347 {
2348     struct stat st;
2349 
2350     /* allow a dedicated CD-ROM driver to match with a higher priority */
2351     if (strstart(filename, "/dev/cdrom", NULL))
2352         return 50;
2353 
2354     if (stat(filename, &st) >= 0 &&
2355             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2356         return 100;
2357     }
2358 
2359     return 0;
2360 }
2361 
2362 static int check_hdev_writable(BDRVRawState *s)
2363 {
2364 #if defined(BLKROGET)
2365     /* Linux block devices can be configured "read-only" using blockdev(8).
2366      * This is independent of device node permissions and therefore open(2)
2367      * with O_RDWR succeeds.  Actual writes fail with EPERM.
2368      *
2369      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
2370      * check for read-only block devices so that Linux block devices behave
2371      * properly.
2372      */
2373     struct stat st;
2374     int readonly = 0;
2375 
2376     if (fstat(s->fd, &st)) {
2377         return -errno;
2378     }
2379 
2380     if (!S_ISBLK(st.st_mode)) {
2381         return 0;
2382     }
2383 
2384     if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2385         return -errno;
2386     }
2387 
2388     if (readonly) {
2389         return -EACCES;
2390     }
2391 #endif /* defined(BLKROGET) */
2392     return 0;
2393 }
2394 
2395 static void hdev_parse_filename(const char *filename, QDict *options,
2396                                 Error **errp)
2397 {
2398     /* The prefix is optional, just as for "file". */
2399     strstart(filename, "host_device:", &filename);
2400 
2401     qdict_put_str(options, "filename", filename);
2402 }
2403 
2404 static bool hdev_is_sg(BlockDriverState *bs)
2405 {
2406 
2407 #if defined(__linux__)
2408 
2409     BDRVRawState *s = bs->opaque;
2410     struct stat st;
2411     struct sg_scsi_id scsiid;
2412     int sg_version;
2413     int ret;
2414 
2415     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
2416         return false;
2417     }
2418 
2419     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
2420     if (ret < 0) {
2421         return false;
2422     }
2423 
2424     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
2425     if (ret >= 0) {
2426         DPRINTF("SG device found: type=%d, version=%d\n",
2427             scsiid.scsi_type, sg_version);
2428         return true;
2429     }
2430 
2431 #endif
2432 
2433     return false;
2434 }
2435 
2436 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2437                      Error **errp)
2438 {
2439     BDRVRawState *s = bs->opaque;
2440     Error *local_err = NULL;
2441     int ret;
2442 
2443 #if defined(__APPLE__) && defined(__MACH__)
2444     /*
2445      * Caution: while qdict_get_str() is fine, getting non-string types
2446      * would require more care.  When @options come from -blockdev or
2447      * blockdev_add, its members are typed according to the QAPI
2448      * schema, but when they come from -drive, they're all QString.
2449      */
2450     const char *filename = qdict_get_str(options, "filename");
2451     char bsd_path[MAXPATHLEN] = "";
2452     bool error_occurred = false;
2453 
2454     /* If using a real cdrom */
2455     if (strcmp(filename, "/dev/cdrom") == 0) {
2456         char *mediaType = NULL;
2457         kern_return_t ret_val;
2458         io_iterator_t mediaIterator = 0;
2459 
2460         mediaType = FindEjectableOpticalMedia(&mediaIterator);
2461         if (mediaType == NULL) {
2462             error_setg(errp, "Please make sure your CD/DVD is in the optical"
2463                        " drive");
2464             error_occurred = true;
2465             goto hdev_open_Mac_error;
2466         }
2467 
2468         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
2469         if (ret_val != KERN_SUCCESS) {
2470             error_setg(errp, "Could not get BSD path for optical drive");
2471             error_occurred = true;
2472             goto hdev_open_Mac_error;
2473         }
2474 
2475         /* If a real optical drive was not found */
2476         if (bsd_path[0] == '\0') {
2477             error_setg(errp, "Failed to obtain bsd path for optical drive");
2478             error_occurred = true;
2479             goto hdev_open_Mac_error;
2480         }
2481 
2482         /* If using a cdrom disc and finding a partition on the disc failed */
2483         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
2484             setup_cdrom(bsd_path, errp) == false) {
2485             print_unmounting_directions(bsd_path);
2486             error_occurred = true;
2487             goto hdev_open_Mac_error;
2488         }
2489 
2490         qdict_put_str(options, "filename", bsd_path);
2491 
2492 hdev_open_Mac_error:
2493         g_free(mediaType);
2494         if (mediaIterator) {
2495             IOObjectRelease(mediaIterator);
2496         }
2497         if (error_occurred) {
2498             return -ENOENT;
2499         }
2500     }
2501 #endif /* defined(__APPLE__) && defined(__MACH__) */
2502 
2503     s->type = FTYPE_FILE;
2504 
2505     ret = raw_open_common(bs, options, flags, 0, &local_err);
2506     if (ret < 0) {
2507         error_propagate(errp, local_err);
2508 #if defined(__APPLE__) && defined(__MACH__)
2509         if (*bsd_path) {
2510             filename = bsd_path;
2511         }
2512         /* if a physical device experienced an error while being opened */
2513         if (strncmp(filename, "/dev/", 5) == 0) {
2514             print_unmounting_directions(filename);
2515         }
2516 #endif /* defined(__APPLE__) && defined(__MACH__) */
2517         return ret;
2518     }
2519 
2520     /* Since this does ioctl the device must be already opened */
2521     bs->sg = hdev_is_sg(bs);
2522 
2523     if (flags & BDRV_O_RDWR) {
2524         ret = check_hdev_writable(s);
2525         if (ret < 0) {
2526             raw_close(bs);
2527             error_setg_errno(errp, -ret, "The device is not writable");
2528             return ret;
2529         }
2530     }
2531 
2532     return ret;
2533 }
2534 
2535 #if defined(__linux__)
2536 
2537 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2538         unsigned long int req, void *buf,
2539         BlockCompletionFunc *cb, void *opaque)
2540 {
2541     BDRVRawState *s = bs->opaque;
2542     RawPosixAIOData *acb;
2543     ThreadPool *pool;
2544 
2545     if (fd_open(bs) < 0)
2546         return NULL;
2547 
2548     acb = g_new(RawPosixAIOData, 1);
2549     acb->bs = bs;
2550     acb->aio_type = QEMU_AIO_IOCTL;
2551     acb->aio_fildes = s->fd;
2552     acb->aio_offset = 0;
2553     acb->aio_ioctl_buf = buf;
2554     acb->aio_ioctl_cmd = req;
2555     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2556     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2557 }
2558 #endif /* linux */
2559 
2560 static int fd_open(BlockDriverState *bs)
2561 {
2562     BDRVRawState *s = bs->opaque;
2563 
2564     /* this is just to ensure s->fd is sane (its called by io ops) */
2565     if (s->fd >= 0)
2566         return 0;
2567     return -EIO;
2568 }
2569 
2570 static coroutine_fn BlockAIOCB *hdev_aio_pdiscard(BlockDriverState *bs,
2571     int64_t offset, int count,
2572     BlockCompletionFunc *cb, void *opaque)
2573 {
2574     BDRVRawState *s = bs->opaque;
2575 
2576     if (fd_open(bs) < 0) {
2577         return NULL;
2578     }
2579     return paio_submit(bs, s->fd, offset, NULL, count,
2580                        cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2581 }
2582 
2583 static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
2584     int64_t offset, int count, BdrvRequestFlags flags)
2585 {
2586     BDRVRawState *s = bs->opaque;
2587     int rc;
2588 
2589     rc = fd_open(bs);
2590     if (rc < 0) {
2591         return rc;
2592     }
2593     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2594         return paio_submit_co(bs, s->fd, offset, NULL, count,
2595                               QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2596     } else if (s->discard_zeroes) {
2597         return paio_submit_co(bs, s->fd, offset, NULL, count,
2598                               QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2599     }
2600     return -ENOTSUP;
2601 }
2602 
2603 static int hdev_create(const char *filename, QemuOpts *opts,
2604                        Error **errp)
2605 {
2606     int fd;
2607     int ret = 0;
2608     struct stat stat_buf;
2609     int64_t total_size = 0;
2610     bool has_prefix;
2611 
2612     /* This function is used by both protocol block drivers and therefore either
2613      * of these prefixes may be given.
2614      * The return value has to be stored somewhere, otherwise this is an error
2615      * due to -Werror=unused-value. */
2616     has_prefix =
2617         strstart(filename, "host_device:", &filename) ||
2618         strstart(filename, "host_cdrom:" , &filename);
2619 
2620     (void)has_prefix;
2621 
2622     ret = raw_normalize_devicepath(&filename);
2623     if (ret < 0) {
2624         error_setg_errno(errp, -ret, "Could not normalize device path");
2625         return ret;
2626     }
2627 
2628     /* Read out options */
2629     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2630                           BDRV_SECTOR_SIZE);
2631 
2632     fd = qemu_open(filename, O_WRONLY | O_BINARY);
2633     if (fd < 0) {
2634         ret = -errno;
2635         error_setg_errno(errp, -ret, "Could not open device");
2636         return ret;
2637     }
2638 
2639     if (fstat(fd, &stat_buf) < 0) {
2640         ret = -errno;
2641         error_setg_errno(errp, -ret, "Could not stat device");
2642     } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2643         error_setg(errp,
2644                    "The given file is neither a block nor a character device");
2645         ret = -ENODEV;
2646     } else if (lseek(fd, 0, SEEK_END) < total_size) {
2647         error_setg(errp, "Device is too small");
2648         ret = -ENOSPC;
2649     }
2650 
2651     qemu_close(fd);
2652     return ret;
2653 }
2654 
2655 static BlockDriver bdrv_host_device = {
2656     .format_name        = "host_device",
2657     .protocol_name        = "host_device",
2658     .instance_size      = sizeof(BDRVRawState),
2659     .bdrv_needs_filename = true,
2660     .bdrv_probe_device  = hdev_probe_device,
2661     .bdrv_parse_filename = hdev_parse_filename,
2662     .bdrv_file_open     = hdev_open,
2663     .bdrv_close         = raw_close,
2664     .bdrv_reopen_prepare = raw_reopen_prepare,
2665     .bdrv_reopen_commit  = raw_reopen_commit,
2666     .bdrv_reopen_abort   = raw_reopen_abort,
2667     .bdrv_create         = hdev_create,
2668     .create_opts         = &raw_create_opts,
2669     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
2670 
2671     .bdrv_co_preadv         = raw_co_preadv,
2672     .bdrv_co_pwritev        = raw_co_pwritev,
2673     .bdrv_aio_flush	= raw_aio_flush,
2674     .bdrv_aio_pdiscard   = hdev_aio_pdiscard,
2675     .bdrv_refresh_limits = raw_refresh_limits,
2676     .bdrv_io_plug = raw_aio_plug,
2677     .bdrv_io_unplug = raw_aio_unplug,
2678 
2679     .bdrv_truncate      = raw_truncate,
2680     .bdrv_getlength	= raw_getlength,
2681     .bdrv_get_info = raw_get_info,
2682     .bdrv_get_allocated_file_size
2683                         = raw_get_allocated_file_size,
2684     .bdrv_check_perm = raw_check_perm,
2685     .bdrv_set_perm   = raw_set_perm,
2686     .bdrv_abort_perm_update = raw_abort_perm_update,
2687     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2688     .bdrv_probe_geometry = hdev_probe_geometry,
2689 
2690     /* generic scsi device */
2691 #ifdef __linux__
2692     .bdrv_aio_ioctl     = hdev_aio_ioctl,
2693 #endif
2694 };
2695 
2696 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2697 static void cdrom_parse_filename(const char *filename, QDict *options,
2698                                  Error **errp)
2699 {
2700     /* The prefix is optional, just as for "file". */
2701     strstart(filename, "host_cdrom:", &filename);
2702 
2703     qdict_put_str(options, "filename", filename);
2704 }
2705 #endif
2706 
2707 #ifdef __linux__
2708 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2709                       Error **errp)
2710 {
2711     BDRVRawState *s = bs->opaque;
2712 
2713     s->type = FTYPE_CD;
2714 
2715     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2716     return raw_open_common(bs, options, flags, O_NONBLOCK, errp);
2717 }
2718 
2719 static int cdrom_probe_device(const char *filename)
2720 {
2721     int fd, ret;
2722     int prio = 0;
2723     struct stat st;
2724 
2725     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2726     if (fd < 0) {
2727         goto out;
2728     }
2729     ret = fstat(fd, &st);
2730     if (ret == -1 || !S_ISBLK(st.st_mode)) {
2731         goto outc;
2732     }
2733 
2734     /* Attempt to detect via a CDROM specific ioctl */
2735     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2736     if (ret >= 0)
2737         prio = 100;
2738 
2739 outc:
2740     qemu_close(fd);
2741 out:
2742     return prio;
2743 }
2744 
2745 static bool cdrom_is_inserted(BlockDriverState *bs)
2746 {
2747     BDRVRawState *s = bs->opaque;
2748     int ret;
2749 
2750     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2751     return ret == CDS_DISC_OK;
2752 }
2753 
2754 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2755 {
2756     BDRVRawState *s = bs->opaque;
2757 
2758     if (eject_flag) {
2759         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2760             perror("CDROMEJECT");
2761     } else {
2762         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2763             perror("CDROMEJECT");
2764     }
2765 }
2766 
2767 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2768 {
2769     BDRVRawState *s = bs->opaque;
2770 
2771     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2772         /*
2773          * Note: an error can happen if the distribution automatically
2774          * mounts the CD-ROM
2775          */
2776         /* perror("CDROM_LOCKDOOR"); */
2777     }
2778 }
2779 
2780 static BlockDriver bdrv_host_cdrom = {
2781     .format_name        = "host_cdrom",
2782     .protocol_name      = "host_cdrom",
2783     .instance_size      = sizeof(BDRVRawState),
2784     .bdrv_needs_filename = true,
2785     .bdrv_probe_device	= cdrom_probe_device,
2786     .bdrv_parse_filename = cdrom_parse_filename,
2787     .bdrv_file_open     = cdrom_open,
2788     .bdrv_close         = raw_close,
2789     .bdrv_reopen_prepare = raw_reopen_prepare,
2790     .bdrv_reopen_commit  = raw_reopen_commit,
2791     .bdrv_reopen_abort   = raw_reopen_abort,
2792     .bdrv_create         = hdev_create,
2793     .create_opts         = &raw_create_opts,
2794 
2795 
2796     .bdrv_co_preadv         = raw_co_preadv,
2797     .bdrv_co_pwritev        = raw_co_pwritev,
2798     .bdrv_aio_flush	= raw_aio_flush,
2799     .bdrv_refresh_limits = raw_refresh_limits,
2800     .bdrv_io_plug = raw_aio_plug,
2801     .bdrv_io_unplug = raw_aio_unplug,
2802 
2803     .bdrv_truncate      = raw_truncate,
2804     .bdrv_getlength      = raw_getlength,
2805     .has_variable_length = true,
2806     .bdrv_get_allocated_file_size
2807                         = raw_get_allocated_file_size,
2808 
2809     /* removable device support */
2810     .bdrv_is_inserted   = cdrom_is_inserted,
2811     .bdrv_eject         = cdrom_eject,
2812     .bdrv_lock_medium   = cdrom_lock_medium,
2813 
2814     /* generic scsi device */
2815     .bdrv_aio_ioctl     = hdev_aio_ioctl,
2816 };
2817 #endif /* __linux__ */
2818 
2819 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2820 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2821                       Error **errp)
2822 {
2823     BDRVRawState *s = bs->opaque;
2824     Error *local_err = NULL;
2825     int ret;
2826 
2827     s->type = FTYPE_CD;
2828 
2829     ret = raw_open_common(bs, options, flags, 0, &local_err);
2830     if (ret) {
2831         error_propagate(errp, local_err);
2832         return ret;
2833     }
2834 
2835     /* make sure the door isn't locked at this time */
2836     ioctl(s->fd, CDIOCALLOW);
2837     return 0;
2838 }
2839 
2840 static int cdrom_probe_device(const char *filename)
2841 {
2842     if (strstart(filename, "/dev/cd", NULL) ||
2843             strstart(filename, "/dev/acd", NULL))
2844         return 100;
2845     return 0;
2846 }
2847 
2848 static int cdrom_reopen(BlockDriverState *bs)
2849 {
2850     BDRVRawState *s = bs->opaque;
2851     int fd;
2852 
2853     /*
2854      * Force reread of possibly changed/newly loaded disc,
2855      * FreeBSD seems to not notice sometimes...
2856      */
2857     if (s->fd >= 0)
2858         qemu_close(s->fd);
2859     fd = qemu_open(bs->filename, s->open_flags, 0644);
2860     if (fd < 0) {
2861         s->fd = -1;
2862         return -EIO;
2863     }
2864     s->fd = fd;
2865 
2866     /* make sure the door isn't locked at this time */
2867     ioctl(s->fd, CDIOCALLOW);
2868     return 0;
2869 }
2870 
2871 static bool cdrom_is_inserted(BlockDriverState *bs)
2872 {
2873     return raw_getlength(bs) > 0;
2874 }
2875 
2876 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2877 {
2878     BDRVRawState *s = bs->opaque;
2879 
2880     if (s->fd < 0)
2881         return;
2882 
2883     (void) ioctl(s->fd, CDIOCALLOW);
2884 
2885     if (eject_flag) {
2886         if (ioctl(s->fd, CDIOCEJECT) < 0)
2887             perror("CDIOCEJECT");
2888     } else {
2889         if (ioctl(s->fd, CDIOCCLOSE) < 0)
2890             perror("CDIOCCLOSE");
2891     }
2892 
2893     cdrom_reopen(bs);
2894 }
2895 
2896 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2897 {
2898     BDRVRawState *s = bs->opaque;
2899 
2900     if (s->fd < 0)
2901         return;
2902     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2903         /*
2904          * Note: an error can happen if the distribution automatically
2905          * mounts the CD-ROM
2906          */
2907         /* perror("CDROM_LOCKDOOR"); */
2908     }
2909 }
2910 
2911 static BlockDriver bdrv_host_cdrom = {
2912     .format_name        = "host_cdrom",
2913     .protocol_name      = "host_cdrom",
2914     .instance_size      = sizeof(BDRVRawState),
2915     .bdrv_needs_filename = true,
2916     .bdrv_probe_device	= cdrom_probe_device,
2917     .bdrv_parse_filename = cdrom_parse_filename,
2918     .bdrv_file_open     = cdrom_open,
2919     .bdrv_close         = raw_close,
2920     .bdrv_reopen_prepare = raw_reopen_prepare,
2921     .bdrv_reopen_commit  = raw_reopen_commit,
2922     .bdrv_reopen_abort   = raw_reopen_abort,
2923     .bdrv_create        = hdev_create,
2924     .create_opts        = &raw_create_opts,
2925 
2926     .bdrv_co_preadv         = raw_co_preadv,
2927     .bdrv_co_pwritev        = raw_co_pwritev,
2928     .bdrv_aio_flush	= raw_aio_flush,
2929     .bdrv_refresh_limits = raw_refresh_limits,
2930     .bdrv_io_plug = raw_aio_plug,
2931     .bdrv_io_unplug = raw_aio_unplug,
2932 
2933     .bdrv_truncate      = raw_truncate,
2934     .bdrv_getlength      = raw_getlength,
2935     .has_variable_length = true,
2936     .bdrv_get_allocated_file_size
2937                         = raw_get_allocated_file_size,
2938 
2939     /* removable device support */
2940     .bdrv_is_inserted   = cdrom_is_inserted,
2941     .bdrv_eject         = cdrom_eject,
2942     .bdrv_lock_medium   = cdrom_lock_medium,
2943 };
2944 #endif /* __FreeBSD__ */
2945 
2946 static void bdrv_file_init(void)
2947 {
2948     /*
2949      * Register all the drivers.  Note that order is important, the driver
2950      * registered last will get probed first.
2951      */
2952     bdrv_register(&bdrv_file);
2953     bdrv_register(&bdrv_host_device);
2954 #ifdef __linux__
2955     bdrv_register(&bdrv_host_cdrom);
2956 #endif
2957 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2958     bdrv_register(&bdrv_host_cdrom);
2959 #endif
2960 }
2961 
2962 block_init(bdrv_file_init);
2963