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