xref: /openbmc/qemu/block/file-posix.c (revision 8d324575)
1c1bb86cdSEric Blake /*
2c1bb86cdSEric Blake  * Block driver for RAW files (posix)
3c1bb86cdSEric Blake  *
4c1bb86cdSEric Blake  * Copyright (c) 2006 Fabrice Bellard
5c1bb86cdSEric Blake  *
6c1bb86cdSEric Blake  * Permission is hereby granted, free of charge, to any person obtaining a copy
7c1bb86cdSEric Blake  * of this software and associated documentation files (the "Software"), to deal
8c1bb86cdSEric Blake  * in the Software without restriction, including without limitation the rights
9c1bb86cdSEric Blake  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10c1bb86cdSEric Blake  * copies of the Software, and to permit persons to whom the Software is
11c1bb86cdSEric Blake  * furnished to do so, subject to the following conditions:
12c1bb86cdSEric Blake  *
13c1bb86cdSEric Blake  * The above copyright notice and this permission notice shall be included in
14c1bb86cdSEric Blake  * all copies or substantial portions of the Software.
15c1bb86cdSEric Blake  *
16c1bb86cdSEric Blake  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17c1bb86cdSEric Blake  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18c1bb86cdSEric Blake  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19c1bb86cdSEric Blake  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20c1bb86cdSEric Blake  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21c1bb86cdSEric Blake  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22c1bb86cdSEric Blake  * THE SOFTWARE.
23c1bb86cdSEric Blake  */
24922a01a0SMarkus Armbruster 
25c1bb86cdSEric Blake #include "qemu/osdep.h"
26c1bb86cdSEric Blake #include "qapi/error.h"
27c1bb86cdSEric Blake #include "qemu/cutils.h"
28c1bb86cdSEric Blake #include "qemu/error-report.h"
29c1bb86cdSEric Blake #include "block/block_int.h"
30c1bb86cdSEric Blake #include "qemu/module.h"
31922a01a0SMarkus Armbruster #include "qemu/option.h"
32c1bb86cdSEric Blake #include "trace.h"
33c1bb86cdSEric Blake #include "block/thread-pool.h"
34c1bb86cdSEric Blake #include "qemu/iov.h"
35c1bb86cdSEric Blake #include "block/raw-aio.h"
36452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
37c1bb86cdSEric Blake #include "qapi/qmp/qstring.h"
38c1bb86cdSEric Blake 
397c9e5276SPaolo Bonzini #include "scsi/pr-manager.h"
407c9e5276SPaolo Bonzini #include "scsi/constants.h"
417c9e5276SPaolo Bonzini 
42c1bb86cdSEric Blake #if defined(__APPLE__) && (__MACH__)
43c1bb86cdSEric Blake #include <paths.h>
44c1bb86cdSEric Blake #include <sys/param.h>
45c1bb86cdSEric Blake #include <IOKit/IOKitLib.h>
46c1bb86cdSEric Blake #include <IOKit/IOBSD.h>
47c1bb86cdSEric Blake #include <IOKit/storage/IOMediaBSDClient.h>
48c1bb86cdSEric Blake #include <IOKit/storage/IOMedia.h>
49c1bb86cdSEric Blake #include <IOKit/storage/IOCDMedia.h>
50c1bb86cdSEric Blake //#include <IOKit/storage/IOCDTypes.h>
51c1bb86cdSEric Blake #include <IOKit/storage/IODVDMedia.h>
52c1bb86cdSEric Blake #include <CoreFoundation/CoreFoundation.h>
53c1bb86cdSEric Blake #endif
54c1bb86cdSEric Blake 
55c1bb86cdSEric Blake #ifdef __sun__
56c1bb86cdSEric Blake #define _POSIX_PTHREAD_SEMANTICS 1
57c1bb86cdSEric Blake #include <sys/dkio.h>
58c1bb86cdSEric Blake #endif
59c1bb86cdSEric Blake #ifdef __linux__
60c1bb86cdSEric Blake #include <sys/ioctl.h>
61c1bb86cdSEric Blake #include <sys/param.h>
621efad060SFam Zheng #include <sys/syscall.h>
63c1bb86cdSEric Blake #include <linux/cdrom.h>
64c1bb86cdSEric Blake #include <linux/fd.h>
65c1bb86cdSEric Blake #include <linux/fs.h>
66c1bb86cdSEric Blake #include <linux/hdreg.h>
67c1bb86cdSEric Blake #include <scsi/sg.h>
68c1bb86cdSEric Blake #ifdef __s390__
69c1bb86cdSEric Blake #include <asm/dasd.h>
70c1bb86cdSEric Blake #endif
71c1bb86cdSEric Blake #ifndef FS_NOCOW_FL
72c1bb86cdSEric Blake #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
73c1bb86cdSEric Blake #endif
74c1bb86cdSEric Blake #endif
75c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
76c1bb86cdSEric Blake #include <linux/falloc.h>
77c1bb86cdSEric Blake #endif
78c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
79c1bb86cdSEric Blake #include <sys/disk.h>
80c1bb86cdSEric Blake #include <sys/cdio.h>
81c1bb86cdSEric Blake #endif
82c1bb86cdSEric Blake 
83c1bb86cdSEric Blake #ifdef __OpenBSD__
84c1bb86cdSEric Blake #include <sys/ioctl.h>
85c1bb86cdSEric Blake #include <sys/disklabel.h>
86c1bb86cdSEric Blake #include <sys/dkio.h>
87c1bb86cdSEric Blake #endif
88c1bb86cdSEric Blake 
89c1bb86cdSEric Blake #ifdef __NetBSD__
90c1bb86cdSEric Blake #include <sys/ioctl.h>
91c1bb86cdSEric Blake #include <sys/disklabel.h>
92c1bb86cdSEric Blake #include <sys/dkio.h>
93c1bb86cdSEric Blake #include <sys/disk.h>
94c1bb86cdSEric Blake #endif
95c1bb86cdSEric Blake 
96c1bb86cdSEric Blake #ifdef __DragonFly__
97c1bb86cdSEric Blake #include <sys/ioctl.h>
98c1bb86cdSEric Blake #include <sys/diskslice.h>
99c1bb86cdSEric Blake #endif
100c1bb86cdSEric Blake 
101c1bb86cdSEric Blake #ifdef CONFIG_XFS
102c1bb86cdSEric Blake #include <xfs/xfs.h>
103c1bb86cdSEric Blake #endif
104c1bb86cdSEric Blake 
105c1bb86cdSEric Blake //#define DEBUG_BLOCK
106c1bb86cdSEric Blake 
107c1bb86cdSEric Blake #ifdef DEBUG_BLOCK
108c1bb86cdSEric Blake # define DEBUG_BLOCK_PRINT 1
109c1bb86cdSEric Blake #else
110c1bb86cdSEric Blake # define DEBUG_BLOCK_PRINT 0
111c1bb86cdSEric Blake #endif
112c1bb86cdSEric Blake #define DPRINTF(fmt, ...) \
113c1bb86cdSEric Blake do { \
114c1bb86cdSEric Blake     if (DEBUG_BLOCK_PRINT) { \
115c1bb86cdSEric Blake         printf(fmt, ## __VA_ARGS__); \
116c1bb86cdSEric Blake     } \
117c1bb86cdSEric Blake } while (0)
118c1bb86cdSEric Blake 
119c1bb86cdSEric Blake /* OS X does not have O_DSYNC */
120c1bb86cdSEric Blake #ifndef O_DSYNC
121c1bb86cdSEric Blake #ifdef O_SYNC
122c1bb86cdSEric Blake #define O_DSYNC O_SYNC
123c1bb86cdSEric Blake #elif defined(O_FSYNC)
124c1bb86cdSEric Blake #define O_DSYNC O_FSYNC
125c1bb86cdSEric Blake #endif
126c1bb86cdSEric Blake #endif
127c1bb86cdSEric Blake 
128c1bb86cdSEric Blake /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
129c1bb86cdSEric Blake #ifndef O_DIRECT
130c1bb86cdSEric Blake #define O_DIRECT O_DSYNC
131c1bb86cdSEric Blake #endif
132c1bb86cdSEric Blake 
133c1bb86cdSEric Blake #define FTYPE_FILE   0
134c1bb86cdSEric Blake #define FTYPE_CD     1
135c1bb86cdSEric Blake 
136c1bb86cdSEric Blake #define MAX_BLOCKSIZE	4096
137c1bb86cdSEric Blake 
138244a5668SFam Zheng /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
139244a5668SFam Zheng  * leaving a few more bytes for its future use. */
140244a5668SFam Zheng #define RAW_LOCK_PERM_BASE             100
141244a5668SFam Zheng #define RAW_LOCK_SHARED_BASE           200
142244a5668SFam Zheng 
143c1bb86cdSEric Blake typedef struct BDRVRawState {
144c1bb86cdSEric Blake     int fd;
145244a5668SFam Zheng     int lock_fd;
146244a5668SFam Zheng     bool use_lock;
147c1bb86cdSEric Blake     int type;
148c1bb86cdSEric Blake     int open_flags;
149c1bb86cdSEric Blake     size_t buf_align;
150c1bb86cdSEric Blake 
151244a5668SFam Zheng     /* The current permissions. */
152244a5668SFam Zheng     uint64_t perm;
153244a5668SFam Zheng     uint64_t shared_perm;
154244a5668SFam Zheng 
155c1bb86cdSEric Blake #ifdef CONFIG_XFS
156c1bb86cdSEric Blake     bool is_xfs:1;
157c1bb86cdSEric Blake #endif
158c1bb86cdSEric Blake     bool has_discard:1;
159c1bb86cdSEric Blake     bool has_write_zeroes:1;
160c1bb86cdSEric Blake     bool discard_zeroes:1;
161c1bb86cdSEric Blake     bool use_linux_aio:1;
162e5bcf967SKevin Wolf     bool page_cache_inconsistent:1;
163c1bb86cdSEric Blake     bool has_fallocate;
164c1bb86cdSEric Blake     bool needs_alignment;
16531be8a2aSStefan Hajnoczi     bool check_cache_dropped;
1667c9e5276SPaolo Bonzini 
1677c9e5276SPaolo Bonzini     PRManager *pr_mgr;
168c1bb86cdSEric Blake } BDRVRawState;
169c1bb86cdSEric Blake 
170c1bb86cdSEric Blake typedef struct BDRVRawReopenState {
171c1bb86cdSEric Blake     int fd;
172c1bb86cdSEric Blake     int open_flags;
17331be8a2aSStefan Hajnoczi     bool check_cache_dropped;
174c1bb86cdSEric Blake } BDRVRawReopenState;
175c1bb86cdSEric Blake 
176c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs);
177c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs);
178c1bb86cdSEric Blake 
179c1bb86cdSEric Blake typedef struct RawPosixAIOData {
180c1bb86cdSEric Blake     BlockDriverState *bs;
181c1bb86cdSEric Blake     int aio_fildes;
182c1bb86cdSEric Blake     union {
183c1bb86cdSEric Blake         struct iovec *aio_iov;
184c1bb86cdSEric Blake         void *aio_ioctl_buf;
185c1bb86cdSEric Blake     };
186c1bb86cdSEric Blake     int aio_niov;
187c1bb86cdSEric Blake     uint64_t aio_nbytes;
188c1bb86cdSEric Blake #define aio_ioctl_cmd   aio_nbytes /* for QEMU_AIO_IOCTL */
189c1bb86cdSEric Blake     off_t aio_offset;
190c1bb86cdSEric Blake     int aio_type;
19193f4e2ffSKevin Wolf     union {
19293f4e2ffSKevin Wolf         struct {
1931efad060SFam Zheng             int aio_fd2;
1941efad060SFam Zheng             off_t aio_offset2;
19593f4e2ffSKevin Wolf         };
19693f4e2ffSKevin Wolf         struct {
19793f4e2ffSKevin Wolf             PreallocMode prealloc;
19893f4e2ffSKevin Wolf             Error **errp;
19993f4e2ffSKevin Wolf         };
20093f4e2ffSKevin Wolf     };
201c1bb86cdSEric Blake } RawPosixAIOData;
202c1bb86cdSEric Blake 
203c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
204c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs);
205c1bb86cdSEric Blake #endif
206c1bb86cdSEric Blake 
207c1bb86cdSEric Blake #if defined(__NetBSD__)
208c1bb86cdSEric Blake static int raw_normalize_devicepath(const char **filename)
209c1bb86cdSEric Blake {
210c1bb86cdSEric Blake     static char namebuf[PATH_MAX];
211c1bb86cdSEric Blake     const char *dp, *fname;
212c1bb86cdSEric Blake     struct stat sb;
213c1bb86cdSEric Blake 
214c1bb86cdSEric Blake     fname = *filename;
215c1bb86cdSEric Blake     dp = strrchr(fname, '/');
216c1bb86cdSEric Blake     if (lstat(fname, &sb) < 0) {
217c1bb86cdSEric Blake         fprintf(stderr, "%s: stat failed: %s\n",
218c1bb86cdSEric Blake             fname, strerror(errno));
219c1bb86cdSEric Blake         return -errno;
220c1bb86cdSEric Blake     }
221c1bb86cdSEric Blake 
222c1bb86cdSEric Blake     if (!S_ISBLK(sb.st_mode)) {
223c1bb86cdSEric Blake         return 0;
224c1bb86cdSEric Blake     }
225c1bb86cdSEric Blake 
226c1bb86cdSEric Blake     if (dp == NULL) {
227c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "r%s", fname);
228c1bb86cdSEric Blake     } else {
229c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
230c1bb86cdSEric Blake             (int)(dp - fname), fname, dp + 1);
231c1bb86cdSEric Blake     }
232c1bb86cdSEric Blake     fprintf(stderr, "%s is a block device", fname);
233c1bb86cdSEric Blake     *filename = namebuf;
234c1bb86cdSEric Blake     fprintf(stderr, ", using %s\n", *filename);
235c1bb86cdSEric Blake 
236c1bb86cdSEric Blake     return 0;
237c1bb86cdSEric Blake }
238c1bb86cdSEric Blake #else
239c1bb86cdSEric Blake static int raw_normalize_devicepath(const char **filename)
240c1bb86cdSEric Blake {
241c1bb86cdSEric Blake     return 0;
242c1bb86cdSEric Blake }
243c1bb86cdSEric Blake #endif
244c1bb86cdSEric Blake 
245c1bb86cdSEric Blake /*
246c1bb86cdSEric Blake  * Get logical block size via ioctl. On success store it in @sector_size_p.
247c1bb86cdSEric Blake  */
248c1bb86cdSEric Blake static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
249c1bb86cdSEric Blake {
250c1bb86cdSEric Blake     unsigned int sector_size;
251c1bb86cdSEric Blake     bool success = false;
252700f9ce0SPeter Maydell     int i;
253c1bb86cdSEric Blake 
254c1bb86cdSEric Blake     errno = ENOTSUP;
255700f9ce0SPeter Maydell     static const unsigned long ioctl_list[] = {
256c1bb86cdSEric Blake #ifdef BLKSSZGET
257700f9ce0SPeter Maydell         BLKSSZGET,
258c1bb86cdSEric Blake #endif
259c1bb86cdSEric Blake #ifdef DKIOCGETBLOCKSIZE
260700f9ce0SPeter Maydell         DKIOCGETBLOCKSIZE,
261c1bb86cdSEric Blake #endif
262c1bb86cdSEric Blake #ifdef DIOCGSECTORSIZE
263700f9ce0SPeter Maydell         DIOCGSECTORSIZE,
264700f9ce0SPeter Maydell #endif
265700f9ce0SPeter Maydell     };
266700f9ce0SPeter Maydell 
267700f9ce0SPeter Maydell     /* Try a few ioctls to get the right size */
268700f9ce0SPeter Maydell     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
269700f9ce0SPeter Maydell         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
270c1bb86cdSEric Blake             *sector_size_p = sector_size;
271c1bb86cdSEric Blake             success = true;
272c1bb86cdSEric Blake         }
273700f9ce0SPeter Maydell     }
274c1bb86cdSEric Blake 
275c1bb86cdSEric Blake     return success ? 0 : -errno;
276c1bb86cdSEric Blake }
277c1bb86cdSEric Blake 
278c1bb86cdSEric Blake /**
279c1bb86cdSEric Blake  * Get physical block size of @fd.
280c1bb86cdSEric Blake  * On success, store it in @blk_size and return 0.
281c1bb86cdSEric Blake  * On failure, return -errno.
282c1bb86cdSEric Blake  */
283c1bb86cdSEric Blake static int probe_physical_blocksize(int fd, unsigned int *blk_size)
284c1bb86cdSEric Blake {
285c1bb86cdSEric Blake #ifdef BLKPBSZGET
286c1bb86cdSEric Blake     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
287c1bb86cdSEric Blake         return -errno;
288c1bb86cdSEric Blake     }
289c1bb86cdSEric Blake     return 0;
290c1bb86cdSEric Blake #else
291c1bb86cdSEric Blake     return -ENOTSUP;
292c1bb86cdSEric Blake #endif
293c1bb86cdSEric Blake }
294c1bb86cdSEric Blake 
295c1bb86cdSEric Blake /* Check if read is allowed with given memory buffer and length.
296c1bb86cdSEric Blake  *
297c1bb86cdSEric Blake  * This function is used to check O_DIRECT memory buffer and request alignment.
298c1bb86cdSEric Blake  */
299c1bb86cdSEric Blake static bool raw_is_io_aligned(int fd, void *buf, size_t len)
300c1bb86cdSEric Blake {
301c1bb86cdSEric Blake     ssize_t ret = pread(fd, buf, len, 0);
302c1bb86cdSEric Blake 
303c1bb86cdSEric Blake     if (ret >= 0) {
304c1bb86cdSEric Blake         return true;
305c1bb86cdSEric Blake     }
306c1bb86cdSEric Blake 
307c1bb86cdSEric Blake #ifdef __linux__
308c1bb86cdSEric Blake     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
309c1bb86cdSEric Blake      * other errors (e.g. real I/O error), which could happen on a failed
310c1bb86cdSEric Blake      * drive, since we only care about probing alignment.
311c1bb86cdSEric Blake      */
312c1bb86cdSEric Blake     if (errno != EINVAL) {
313c1bb86cdSEric Blake         return true;
314c1bb86cdSEric Blake     }
315c1bb86cdSEric Blake #endif
316c1bb86cdSEric Blake 
317c1bb86cdSEric Blake     return false;
318c1bb86cdSEric Blake }
319c1bb86cdSEric Blake 
320c1bb86cdSEric Blake static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
321c1bb86cdSEric Blake {
322c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
323c1bb86cdSEric Blake     char *buf;
324c1bb86cdSEric Blake     size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
325c1bb86cdSEric Blake 
326c1bb86cdSEric Blake     /* For SCSI generic devices the alignment is not really used.
327c1bb86cdSEric Blake        With buffered I/O, we don't have any restrictions. */
328c1bb86cdSEric Blake     if (bdrv_is_sg(bs) || !s->needs_alignment) {
329c1bb86cdSEric Blake         bs->bl.request_alignment = 1;
330c1bb86cdSEric Blake         s->buf_align = 1;
331c1bb86cdSEric Blake         return;
332c1bb86cdSEric Blake     }
333c1bb86cdSEric Blake 
334c1bb86cdSEric Blake     bs->bl.request_alignment = 0;
335c1bb86cdSEric Blake     s->buf_align = 0;
336c1bb86cdSEric Blake     /* Let's try to use the logical blocksize for the alignment. */
337c1bb86cdSEric Blake     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
338c1bb86cdSEric Blake         bs->bl.request_alignment = 0;
339c1bb86cdSEric Blake     }
340c1bb86cdSEric Blake #ifdef CONFIG_XFS
341c1bb86cdSEric Blake     if (s->is_xfs) {
342c1bb86cdSEric Blake         struct dioattr da;
343c1bb86cdSEric Blake         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
344c1bb86cdSEric Blake             bs->bl.request_alignment = da.d_miniosz;
345c1bb86cdSEric Blake             /* The kernel returns wrong information for d_mem */
346c1bb86cdSEric Blake             /* s->buf_align = da.d_mem; */
347c1bb86cdSEric Blake         }
348c1bb86cdSEric Blake     }
349c1bb86cdSEric Blake #endif
350c1bb86cdSEric Blake 
351c1bb86cdSEric Blake     /* If we could not get the sizes so far, we can only guess them */
352c1bb86cdSEric Blake     if (!s->buf_align) {
353c1bb86cdSEric Blake         size_t align;
354c1bb86cdSEric Blake         buf = qemu_memalign(max_align, 2 * max_align);
355c1bb86cdSEric Blake         for (align = 512; align <= max_align; align <<= 1) {
356c1bb86cdSEric Blake             if (raw_is_io_aligned(fd, buf + align, max_align)) {
357c1bb86cdSEric Blake                 s->buf_align = align;
358c1bb86cdSEric Blake                 break;
359c1bb86cdSEric Blake             }
360c1bb86cdSEric Blake         }
361c1bb86cdSEric Blake         qemu_vfree(buf);
362c1bb86cdSEric Blake     }
363c1bb86cdSEric Blake 
364c1bb86cdSEric Blake     if (!bs->bl.request_alignment) {
365c1bb86cdSEric Blake         size_t align;
366c1bb86cdSEric Blake         buf = qemu_memalign(s->buf_align, max_align);
367c1bb86cdSEric Blake         for (align = 512; align <= max_align; align <<= 1) {
368c1bb86cdSEric Blake             if (raw_is_io_aligned(fd, buf, align)) {
369c1bb86cdSEric Blake                 bs->bl.request_alignment = align;
370c1bb86cdSEric Blake                 break;
371c1bb86cdSEric Blake             }
372c1bb86cdSEric Blake         }
373c1bb86cdSEric Blake         qemu_vfree(buf);
374c1bb86cdSEric Blake     }
375c1bb86cdSEric Blake 
376c1bb86cdSEric Blake     if (!s->buf_align || !bs->bl.request_alignment) {
377c1bb86cdSEric Blake         error_setg(errp, "Could not find working O_DIRECT alignment");
378c1bb86cdSEric Blake         error_append_hint(errp, "Try cache.direct=off\n");
379c1bb86cdSEric Blake     }
380c1bb86cdSEric Blake }
381c1bb86cdSEric Blake 
382c1bb86cdSEric Blake static void raw_parse_flags(int bdrv_flags, int *open_flags)
383c1bb86cdSEric Blake {
384c1bb86cdSEric Blake     assert(open_flags != NULL);
385c1bb86cdSEric Blake 
386c1bb86cdSEric Blake     *open_flags |= O_BINARY;
387c1bb86cdSEric Blake     *open_flags &= ~O_ACCMODE;
388c1bb86cdSEric Blake     if (bdrv_flags & BDRV_O_RDWR) {
389c1bb86cdSEric Blake         *open_flags |= O_RDWR;
390c1bb86cdSEric Blake     } else {
391c1bb86cdSEric Blake         *open_flags |= O_RDONLY;
392c1bb86cdSEric Blake     }
393c1bb86cdSEric Blake 
394c1bb86cdSEric Blake     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
395c1bb86cdSEric Blake      * and O_DIRECT for no caching. */
396c1bb86cdSEric Blake     if ((bdrv_flags & BDRV_O_NOCACHE)) {
397c1bb86cdSEric Blake         *open_flags |= O_DIRECT;
398c1bb86cdSEric Blake     }
399c1bb86cdSEric Blake }
400c1bb86cdSEric Blake 
401c1bb86cdSEric Blake static void raw_parse_filename(const char *filename, QDict *options,
402c1bb86cdSEric Blake                                Error **errp)
403c1bb86cdSEric Blake {
40403c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "file:", options);
405c1bb86cdSEric Blake }
406c1bb86cdSEric Blake 
407c1bb86cdSEric Blake static QemuOptsList raw_runtime_opts = {
408c1bb86cdSEric Blake     .name = "raw",
409c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
410c1bb86cdSEric Blake     .desc = {
411c1bb86cdSEric Blake         {
412c1bb86cdSEric Blake             .name = "filename",
413c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
414c1bb86cdSEric Blake             .help = "File name of the image",
415c1bb86cdSEric Blake         },
416c1bb86cdSEric Blake         {
417c1bb86cdSEric Blake             .name = "aio",
418c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
419c1bb86cdSEric Blake             .help = "host AIO implementation (threads, native)",
420c1bb86cdSEric Blake         },
42116b48d5dSFam Zheng         {
42216b48d5dSFam Zheng             .name = "locking",
42316b48d5dSFam Zheng             .type = QEMU_OPT_STRING,
42416b48d5dSFam Zheng             .help = "file locking mode (on/off/auto, default: auto)",
42516b48d5dSFam Zheng         },
4267c9e5276SPaolo Bonzini         {
4277c9e5276SPaolo Bonzini             .name = "pr-manager",
4287c9e5276SPaolo Bonzini             .type = QEMU_OPT_STRING,
4297c9e5276SPaolo Bonzini             .help = "id of persistent reservation manager object (default: none)",
4307c9e5276SPaolo Bonzini         },
43131be8a2aSStefan Hajnoczi         {
43231be8a2aSStefan Hajnoczi             .name = "x-check-cache-dropped",
43331be8a2aSStefan Hajnoczi             .type = QEMU_OPT_BOOL,
43431be8a2aSStefan Hajnoczi             .help = "check that page cache was dropped on live migration (default: off)"
43531be8a2aSStefan Hajnoczi         },
436c1bb86cdSEric Blake         { /* end of list */ }
437c1bb86cdSEric Blake     },
438c1bb86cdSEric Blake };
439c1bb86cdSEric Blake 
440c1bb86cdSEric Blake static int raw_open_common(BlockDriverState *bs, QDict *options,
441230ff739SJohn Snow                            int bdrv_flags, int open_flags,
442230ff739SJohn Snow                            bool device, Error **errp)
443c1bb86cdSEric Blake {
444c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
445c1bb86cdSEric Blake     QemuOpts *opts;
446c1bb86cdSEric Blake     Error *local_err = NULL;
447c1bb86cdSEric Blake     const char *filename = NULL;
4487c9e5276SPaolo Bonzini     const char *str;
449c1bb86cdSEric Blake     BlockdevAioOptions aio, aio_default;
450c1bb86cdSEric Blake     int fd, ret;
451c1bb86cdSEric Blake     struct stat st;
452244a5668SFam Zheng     OnOffAuto locking;
453c1bb86cdSEric Blake 
454c1bb86cdSEric Blake     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
455c1bb86cdSEric Blake     qemu_opts_absorb_qdict(opts, options, &local_err);
456c1bb86cdSEric Blake     if (local_err) {
457c1bb86cdSEric Blake         error_propagate(errp, local_err);
458c1bb86cdSEric Blake         ret = -EINVAL;
459c1bb86cdSEric Blake         goto fail;
460c1bb86cdSEric Blake     }
461c1bb86cdSEric Blake 
462c1bb86cdSEric Blake     filename = qemu_opt_get(opts, "filename");
463c1bb86cdSEric Blake 
464c1bb86cdSEric Blake     ret = raw_normalize_devicepath(&filename);
465c1bb86cdSEric Blake     if (ret != 0) {
466c1bb86cdSEric Blake         error_setg_errno(errp, -ret, "Could not normalize device path");
467c1bb86cdSEric Blake         goto fail;
468c1bb86cdSEric Blake     }
469c1bb86cdSEric Blake 
470c1bb86cdSEric Blake     aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
471c1bb86cdSEric Blake                   ? BLOCKDEV_AIO_OPTIONS_NATIVE
472c1bb86cdSEric Blake                   : BLOCKDEV_AIO_OPTIONS_THREADS;
473f7abe0ecSMarc-André Lureau     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
474f7abe0ecSMarc-André Lureau                           qemu_opt_get(opts, "aio"),
47506c60b6cSMarkus Armbruster                           aio_default, &local_err);
476c1bb86cdSEric Blake     if (local_err) {
477c1bb86cdSEric Blake         error_propagate(errp, local_err);
478c1bb86cdSEric Blake         ret = -EINVAL;
479c1bb86cdSEric Blake         goto fail;
480c1bb86cdSEric Blake     }
481c1bb86cdSEric Blake     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
482c1bb86cdSEric Blake 
483f7abe0ecSMarc-André Lureau     locking = qapi_enum_parse(&OnOffAuto_lookup,
484f7abe0ecSMarc-André Lureau                               qemu_opt_get(opts, "locking"),
48506c60b6cSMarkus Armbruster                               ON_OFF_AUTO_AUTO, &local_err);
486244a5668SFam Zheng     if (local_err) {
487244a5668SFam Zheng         error_propagate(errp, local_err);
488244a5668SFam Zheng         ret = -EINVAL;
489244a5668SFam Zheng         goto fail;
490244a5668SFam Zheng     }
491244a5668SFam Zheng     switch (locking) {
492244a5668SFam Zheng     case ON_OFF_AUTO_ON:
493244a5668SFam Zheng         s->use_lock = true;
4942b218f5dSFam Zheng         if (!qemu_has_ofd_lock()) {
495244a5668SFam Zheng             fprintf(stderr,
4962b218f5dSFam Zheng                     "File lock requested but OFD locking syscall is "
4972b218f5dSFam Zheng                     "unavailable, falling back to POSIX file locks.\n"
4982b218f5dSFam Zheng                     "Due to the implementation, locks can be lost "
4992b218f5dSFam Zheng                     "unexpectedly.\n");
5002b218f5dSFam Zheng         }
501244a5668SFam Zheng         break;
502244a5668SFam Zheng     case ON_OFF_AUTO_OFF:
503244a5668SFam Zheng         s->use_lock = false;
504244a5668SFam Zheng         break;
505244a5668SFam Zheng     case ON_OFF_AUTO_AUTO:
5062b218f5dSFam Zheng         s->use_lock = qemu_has_ofd_lock();
507244a5668SFam Zheng         break;
508244a5668SFam Zheng     default:
509244a5668SFam Zheng         abort();
510244a5668SFam Zheng     }
511244a5668SFam Zheng 
5127c9e5276SPaolo Bonzini     str = qemu_opt_get(opts, "pr-manager");
5137c9e5276SPaolo Bonzini     if (str) {
5147c9e5276SPaolo Bonzini         s->pr_mgr = pr_manager_lookup(str, &local_err);
5157c9e5276SPaolo Bonzini         if (local_err) {
5167c9e5276SPaolo Bonzini             error_propagate(errp, local_err);
5177c9e5276SPaolo Bonzini             ret = -EINVAL;
5187c9e5276SPaolo Bonzini             goto fail;
5197c9e5276SPaolo Bonzini         }
5207c9e5276SPaolo Bonzini     }
5217c9e5276SPaolo Bonzini 
52231be8a2aSStefan Hajnoczi     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
52331be8a2aSStefan Hajnoczi                                                false);
52431be8a2aSStefan Hajnoczi 
525c1bb86cdSEric Blake     s->open_flags = open_flags;
526c1bb86cdSEric Blake     raw_parse_flags(bdrv_flags, &s->open_flags);
527c1bb86cdSEric Blake 
528c1bb86cdSEric Blake     s->fd = -1;
529c1bb86cdSEric Blake     fd = qemu_open(filename, s->open_flags, 0644);
530c1bb86cdSEric Blake     if (fd < 0) {
531c1bb86cdSEric Blake         ret = -errno;
532c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not open '%s'", filename);
533c1bb86cdSEric Blake         if (ret == -EROFS) {
534c1bb86cdSEric Blake             ret = -EACCES;
535c1bb86cdSEric Blake         }
536c1bb86cdSEric Blake         goto fail;
537c1bb86cdSEric Blake     }
538c1bb86cdSEric Blake     s->fd = fd;
539c1bb86cdSEric Blake 
540244a5668SFam Zheng     s->lock_fd = -1;
541244a5668SFam Zheng     if (s->use_lock) {
542244a5668SFam Zheng         fd = qemu_open(filename, s->open_flags);
543244a5668SFam Zheng         if (fd < 0) {
544244a5668SFam Zheng             ret = -errno;
545244a5668SFam Zheng             error_setg_errno(errp, errno, "Could not open '%s' for locking",
546244a5668SFam Zheng                              filename);
547244a5668SFam Zheng             qemu_close(s->fd);
548244a5668SFam Zheng             goto fail;
549244a5668SFam Zheng         }
550244a5668SFam Zheng         s->lock_fd = fd;
551244a5668SFam Zheng     }
552244a5668SFam Zheng     s->perm = 0;
553244a5668SFam Zheng     s->shared_perm = BLK_PERM_ALL;
554244a5668SFam Zheng 
555c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
556c1bb86cdSEric Blake      /* Currently Linux does AIO only for files opened with O_DIRECT */
557ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
558ed6e2161SNishanth Aravamudan         if (!(s->open_flags & O_DIRECT)) {
559c1bb86cdSEric Blake             error_setg(errp, "aio=native was specified, but it requires "
560c1bb86cdSEric Blake                              "cache.direct=on, which was not specified.");
561c1bb86cdSEric Blake             ret = -EINVAL;
562c1bb86cdSEric Blake             goto fail;
563c1bb86cdSEric Blake         }
564ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
565ed6e2161SNishanth Aravamudan             error_prepend(errp, "Unable to use native AIO: ");
566ed6e2161SNishanth Aravamudan             goto fail;
567ed6e2161SNishanth Aravamudan         }
568ed6e2161SNishanth Aravamudan     }
569c1bb86cdSEric Blake #else
570c1bb86cdSEric Blake     if (s->use_linux_aio) {
571c1bb86cdSEric Blake         error_setg(errp, "aio=native was specified, but is not supported "
572c1bb86cdSEric Blake                          "in this build.");
573c1bb86cdSEric Blake         ret = -EINVAL;
574c1bb86cdSEric Blake         goto fail;
575c1bb86cdSEric Blake     }
576c1bb86cdSEric Blake #endif /* !defined(CONFIG_LINUX_AIO) */
577c1bb86cdSEric Blake 
578c1bb86cdSEric Blake     s->has_discard = true;
579c1bb86cdSEric Blake     s->has_write_zeroes = true;
580c1bb86cdSEric Blake     if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
581c1bb86cdSEric Blake         s->needs_alignment = true;
582c1bb86cdSEric Blake     }
583c1bb86cdSEric Blake 
584c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
585c1bb86cdSEric Blake         ret = -errno;
586c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not stat file");
587c1bb86cdSEric Blake         goto fail;
588c1bb86cdSEric Blake     }
589230ff739SJohn Snow 
590230ff739SJohn Snow     if (!device) {
591230ff739SJohn Snow         if (S_ISBLK(st.st_mode)) {
592230ff739SJohn Snow             warn_report("Opening a block device as a file using the '%s' "
593230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
594230ff739SJohn Snow         } else if (S_ISCHR(st.st_mode)) {
595230ff739SJohn Snow             warn_report("Opening a character device as a file using the '%s' "
596230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
597230ff739SJohn Snow         } else if (!S_ISREG(st.st_mode)) {
598230ff739SJohn Snow             error_setg(errp, "A regular file was expected by the '%s' driver, "
599230ff739SJohn Snow                        "but something else was given", bs->drv->format_name);
600230ff739SJohn Snow             ret = -EINVAL;
601230ff739SJohn Snow             goto fail;
602230ff739SJohn Snow         } else {
603c1bb86cdSEric Blake             s->discard_zeroes = true;
604c1bb86cdSEric Blake             s->has_fallocate = true;
605c1bb86cdSEric Blake         }
606230ff739SJohn Snow     } else {
607230ff739SJohn Snow         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
608230ff739SJohn Snow             error_setg(errp, "'%s' driver expects either "
609230ff739SJohn Snow                        "a character or block device", bs->drv->format_name);
610230ff739SJohn Snow             ret = -EINVAL;
611230ff739SJohn Snow             goto fail;
612230ff739SJohn Snow         }
613230ff739SJohn Snow     }
614230ff739SJohn Snow 
615c1bb86cdSEric Blake     if (S_ISBLK(st.st_mode)) {
616c1bb86cdSEric Blake #ifdef BLKDISCARDZEROES
617c1bb86cdSEric Blake         unsigned int arg;
618c1bb86cdSEric Blake         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
619c1bb86cdSEric Blake             s->discard_zeroes = true;
620c1bb86cdSEric Blake         }
621c1bb86cdSEric Blake #endif
622c1bb86cdSEric Blake #ifdef __linux__
623c1bb86cdSEric Blake         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
624c1bb86cdSEric Blake          * not rely on the contents of discarded blocks unless using O_DIRECT.
625c1bb86cdSEric Blake          * Same for BLKZEROOUT.
626c1bb86cdSEric Blake          */
627c1bb86cdSEric Blake         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
628c1bb86cdSEric Blake             s->discard_zeroes = false;
629c1bb86cdSEric Blake             s->has_write_zeroes = false;
630c1bb86cdSEric Blake         }
631c1bb86cdSEric Blake #endif
632c1bb86cdSEric Blake     }
633c1bb86cdSEric Blake #ifdef __FreeBSD__
634c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode)) {
635c1bb86cdSEric Blake         /*
636c1bb86cdSEric Blake          * The file is a char device (disk), which on FreeBSD isn't behind
637c1bb86cdSEric Blake          * a pager, so force all requests to be aligned. This is needed
638c1bb86cdSEric Blake          * so QEMU makes sure all IO operations on the device are aligned
639c1bb86cdSEric Blake          * to sector size, or else FreeBSD will reject them with EINVAL.
640c1bb86cdSEric Blake          */
641c1bb86cdSEric Blake         s->needs_alignment = true;
642c1bb86cdSEric Blake     }
643c1bb86cdSEric Blake #endif
644c1bb86cdSEric Blake 
645c1bb86cdSEric Blake #ifdef CONFIG_XFS
646c1bb86cdSEric Blake     if (platform_test_xfs_fd(s->fd)) {
647c1bb86cdSEric Blake         s->is_xfs = true;
648c1bb86cdSEric Blake     }
649c1bb86cdSEric Blake #endif
650c1bb86cdSEric Blake 
65134fa110eSKevin Wolf     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
652c1bb86cdSEric Blake     ret = 0;
653c1bb86cdSEric Blake fail:
654c1bb86cdSEric Blake     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
655c1bb86cdSEric Blake         unlink(filename);
656c1bb86cdSEric Blake     }
657c1bb86cdSEric Blake     qemu_opts_del(opts);
658c1bb86cdSEric Blake     return ret;
659c1bb86cdSEric Blake }
660c1bb86cdSEric Blake 
661c1bb86cdSEric Blake static int raw_open(BlockDriverState *bs, QDict *options, int flags,
662c1bb86cdSEric Blake                     Error **errp)
663c1bb86cdSEric Blake {
664c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
665c1bb86cdSEric Blake 
666c1bb86cdSEric Blake     s->type = FTYPE_FILE;
667230ff739SJohn Snow     return raw_open_common(bs, options, flags, 0, false, errp);
668c1bb86cdSEric Blake }
669c1bb86cdSEric Blake 
670244a5668SFam Zheng typedef enum {
671244a5668SFam Zheng     RAW_PL_PREPARE,
672244a5668SFam Zheng     RAW_PL_COMMIT,
673244a5668SFam Zheng     RAW_PL_ABORT,
674244a5668SFam Zheng } RawPermLockOp;
675244a5668SFam Zheng 
676244a5668SFam Zheng #define PERM_FOREACH(i) \
677244a5668SFam Zheng     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
678244a5668SFam Zheng 
679244a5668SFam Zheng /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
680244a5668SFam Zheng  * file; if @unlock == true, also unlock the unneeded bytes.
681244a5668SFam Zheng  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
682244a5668SFam Zheng  */
683d0a96155SMax Reitz static int raw_apply_lock_bytes(int fd,
684244a5668SFam Zheng                                 uint64_t perm_lock_bits,
685244a5668SFam Zheng                                 uint64_t shared_perm_lock_bits,
686244a5668SFam Zheng                                 bool unlock, Error **errp)
687244a5668SFam Zheng {
688244a5668SFam Zheng     int ret;
689244a5668SFam Zheng     int i;
690244a5668SFam Zheng 
691244a5668SFam Zheng     PERM_FOREACH(i) {
692244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
693244a5668SFam Zheng         if (perm_lock_bits & (1ULL << i)) {
694d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
695244a5668SFam Zheng             if (ret) {
696244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
697244a5668SFam Zheng                 return ret;
698244a5668SFam Zheng             }
699244a5668SFam Zheng         } else if (unlock) {
700d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
701244a5668SFam Zheng             if (ret) {
702244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
703244a5668SFam Zheng                 return ret;
704244a5668SFam Zheng             }
705244a5668SFam Zheng         }
706244a5668SFam Zheng     }
707244a5668SFam Zheng     PERM_FOREACH(i) {
708244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
709244a5668SFam Zheng         if (shared_perm_lock_bits & (1ULL << i)) {
710d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
711244a5668SFam Zheng             if (ret) {
712244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
713244a5668SFam Zheng                 return ret;
714244a5668SFam Zheng             }
715244a5668SFam Zheng         } else if (unlock) {
716d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
717244a5668SFam Zheng             if (ret) {
718244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
719244a5668SFam Zheng                 return ret;
720244a5668SFam Zheng             }
721244a5668SFam Zheng         }
722244a5668SFam Zheng     }
723244a5668SFam Zheng     return 0;
724244a5668SFam Zheng }
725244a5668SFam Zheng 
726244a5668SFam Zheng /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
727d0a96155SMax Reitz static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
728244a5668SFam Zheng                                 Error **errp)
729244a5668SFam Zheng {
730244a5668SFam Zheng     int ret;
731244a5668SFam Zheng     int i;
732244a5668SFam Zheng 
733244a5668SFam Zheng     PERM_FOREACH(i) {
734244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
735244a5668SFam Zheng         uint64_t p = 1ULL << i;
736244a5668SFam Zheng         if (perm & p) {
737d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
738244a5668SFam Zheng             if (ret) {
739244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
740244a5668SFam Zheng                 error_setg(errp,
741244a5668SFam Zheng                            "Failed to get \"%s\" lock",
742244a5668SFam Zheng                            perm_name);
743244a5668SFam Zheng                 g_free(perm_name);
744244a5668SFam Zheng                 return ret;
745244a5668SFam Zheng             }
746244a5668SFam Zheng         }
747244a5668SFam Zheng     }
748244a5668SFam Zheng     PERM_FOREACH(i) {
749244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
750244a5668SFam Zheng         uint64_t p = 1ULL << i;
751244a5668SFam Zheng         if (!(shared_perm & p)) {
752d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
753244a5668SFam Zheng             if (ret) {
754244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
755244a5668SFam Zheng                 error_setg(errp,
756244a5668SFam Zheng                            "Failed to get shared \"%s\" lock",
757244a5668SFam Zheng                            perm_name);
758244a5668SFam Zheng                 g_free(perm_name);
759244a5668SFam Zheng                 return ret;
760244a5668SFam Zheng             }
761244a5668SFam Zheng         }
762244a5668SFam Zheng     }
763244a5668SFam Zheng     return 0;
764244a5668SFam Zheng }
765244a5668SFam Zheng 
766244a5668SFam Zheng static int raw_handle_perm_lock(BlockDriverState *bs,
767244a5668SFam Zheng                                 RawPermLockOp op,
768244a5668SFam Zheng                                 uint64_t new_perm, uint64_t new_shared,
769244a5668SFam Zheng                                 Error **errp)
770244a5668SFam Zheng {
771244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
772244a5668SFam Zheng     int ret = 0;
773244a5668SFam Zheng     Error *local_err = NULL;
774244a5668SFam Zheng 
775244a5668SFam Zheng     if (!s->use_lock) {
776244a5668SFam Zheng         return 0;
777244a5668SFam Zheng     }
778244a5668SFam Zheng 
779244a5668SFam Zheng     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
780244a5668SFam Zheng         return 0;
781244a5668SFam Zheng     }
782244a5668SFam Zheng 
783244a5668SFam Zheng     assert(s->lock_fd > 0);
784244a5668SFam Zheng 
785244a5668SFam Zheng     switch (op) {
786244a5668SFam Zheng     case RAW_PL_PREPARE:
787d0a96155SMax Reitz         ret = raw_apply_lock_bytes(s->lock_fd, s->perm | new_perm,
788244a5668SFam Zheng                                    ~s->shared_perm | ~new_shared,
789244a5668SFam Zheng                                    false, errp);
790244a5668SFam Zheng         if (!ret) {
791d0a96155SMax Reitz             ret = raw_check_lock_bytes(s->lock_fd, new_perm, new_shared, errp);
792244a5668SFam Zheng             if (!ret) {
793244a5668SFam Zheng                 return 0;
794244a5668SFam Zheng             }
795b857431dSFam Zheng             error_append_hint(errp,
796b857431dSFam Zheng                               "Is another process using the image [%s]?\n",
797b857431dSFam Zheng                               bs->filename);
798244a5668SFam Zheng         }
799244a5668SFam Zheng         op = RAW_PL_ABORT;
800244a5668SFam Zheng         /* fall through to unlock bytes. */
801244a5668SFam Zheng     case RAW_PL_ABORT:
802d0a96155SMax Reitz         raw_apply_lock_bytes(s->lock_fd, s->perm, ~s->shared_perm,
803d0a96155SMax Reitz                              true, &local_err);
804244a5668SFam Zheng         if (local_err) {
805244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
806244a5668SFam Zheng              * fail. Something weird happened, report it.
807244a5668SFam Zheng              */
808244a5668SFam Zheng             error_report_err(local_err);
809244a5668SFam Zheng         }
810244a5668SFam Zheng         break;
811244a5668SFam Zheng     case RAW_PL_COMMIT:
812d0a96155SMax Reitz         raw_apply_lock_bytes(s->lock_fd, new_perm, ~new_shared,
813d0a96155SMax Reitz                              true, &local_err);
814244a5668SFam Zheng         if (local_err) {
815244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
816244a5668SFam Zheng              * fail. Something weird happened, report it.
817244a5668SFam Zheng              */
818244a5668SFam Zheng             error_report_err(local_err);
819244a5668SFam Zheng         }
820244a5668SFam Zheng         break;
821244a5668SFam Zheng     }
822244a5668SFam Zheng     return ret;
823244a5668SFam Zheng }
824244a5668SFam Zheng 
825c1bb86cdSEric Blake static int raw_reopen_prepare(BDRVReopenState *state,
826c1bb86cdSEric Blake                               BlockReopenQueue *queue, Error **errp)
827c1bb86cdSEric Blake {
828c1bb86cdSEric Blake     BDRVRawState *s;
829c1bb86cdSEric Blake     BDRVRawReopenState *rs;
83031be8a2aSStefan Hajnoczi     QemuOpts *opts;
831c1bb86cdSEric Blake     int ret = 0;
832c1bb86cdSEric Blake     Error *local_err = NULL;
833c1bb86cdSEric Blake 
834c1bb86cdSEric Blake     assert(state != NULL);
835c1bb86cdSEric Blake     assert(state->bs != NULL);
836c1bb86cdSEric Blake 
837c1bb86cdSEric Blake     s = state->bs->opaque;
838c1bb86cdSEric Blake 
839c1bb86cdSEric Blake     state->opaque = g_new0(BDRVRawReopenState, 1);
840c1bb86cdSEric Blake     rs = state->opaque;
84131be8a2aSStefan Hajnoczi     rs->fd = -1;
84231be8a2aSStefan Hajnoczi 
84331be8a2aSStefan Hajnoczi     /* Handle options changes */
84431be8a2aSStefan Hajnoczi     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
84531be8a2aSStefan Hajnoczi     qemu_opts_absorb_qdict(opts, state->options, &local_err);
84631be8a2aSStefan Hajnoczi     if (local_err) {
84731be8a2aSStefan Hajnoczi         error_propagate(errp, local_err);
84831be8a2aSStefan Hajnoczi         ret = -EINVAL;
84931be8a2aSStefan Hajnoczi         goto out;
85031be8a2aSStefan Hajnoczi     }
85131be8a2aSStefan Hajnoczi 
852*8d324575SAlberto Garcia     rs->check_cache_dropped =
853*8d324575SAlberto Garcia         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
854*8d324575SAlberto Garcia 
855*8d324575SAlberto Garcia     /* This driver's reopen function doesn't currently allow changing
856*8d324575SAlberto Garcia      * other options, so let's put them back in the original QDict and
857*8d324575SAlberto Garcia      * bdrv_reopen_prepare() will detect changes and complain. */
858*8d324575SAlberto Garcia     qemu_opts_to_qdict(opts, state->options);
859c1bb86cdSEric Blake 
860c1bb86cdSEric Blake     if (s->type == FTYPE_CD) {
861c1bb86cdSEric Blake         rs->open_flags |= O_NONBLOCK;
862c1bb86cdSEric Blake     }
863c1bb86cdSEric Blake 
864c1bb86cdSEric Blake     raw_parse_flags(state->flags, &rs->open_flags);
865c1bb86cdSEric Blake 
866c1bb86cdSEric Blake     int fcntl_flags = O_APPEND | O_NONBLOCK;
867c1bb86cdSEric Blake #ifdef O_NOATIME
868c1bb86cdSEric Blake     fcntl_flags |= O_NOATIME;
869c1bb86cdSEric Blake #endif
870c1bb86cdSEric Blake 
871c1bb86cdSEric Blake #ifdef O_ASYNC
872c1bb86cdSEric Blake     /* Not all operating systems have O_ASYNC, and those that don't
873c1bb86cdSEric Blake      * will not let us track the state into rs->open_flags (typically
874c1bb86cdSEric Blake      * you achieve the same effect with an ioctl, for example I_SETSIG
875c1bb86cdSEric Blake      * on Solaris). But we do not use O_ASYNC, so that's fine.
876c1bb86cdSEric Blake      */
877c1bb86cdSEric Blake     assert((s->open_flags & O_ASYNC) == 0);
878c1bb86cdSEric Blake #endif
879c1bb86cdSEric Blake 
880c1bb86cdSEric Blake     if ((rs->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
881c1bb86cdSEric Blake         /* dup the original fd */
882c1bb86cdSEric Blake         rs->fd = qemu_dup(s->fd);
883c1bb86cdSEric Blake         if (rs->fd >= 0) {
884c1bb86cdSEric Blake             ret = fcntl_setfl(rs->fd, rs->open_flags);
885c1bb86cdSEric Blake             if (ret) {
886c1bb86cdSEric Blake                 qemu_close(rs->fd);
887c1bb86cdSEric Blake                 rs->fd = -1;
888c1bb86cdSEric Blake             }
889c1bb86cdSEric Blake         }
890c1bb86cdSEric Blake     }
891c1bb86cdSEric Blake 
892c1bb86cdSEric Blake     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
893c1bb86cdSEric Blake     if (rs->fd == -1) {
894c1bb86cdSEric Blake         const char *normalized_filename = state->bs->filename;
895c1bb86cdSEric Blake         ret = raw_normalize_devicepath(&normalized_filename);
896c1bb86cdSEric Blake         if (ret < 0) {
897c1bb86cdSEric Blake             error_setg_errno(errp, -ret, "Could not normalize device path");
898c1bb86cdSEric Blake         } else {
899c1bb86cdSEric Blake             assert(!(rs->open_flags & O_CREAT));
900c1bb86cdSEric Blake             rs->fd = qemu_open(normalized_filename, rs->open_flags);
901c1bb86cdSEric Blake             if (rs->fd == -1) {
902c1bb86cdSEric Blake                 error_setg_errno(errp, errno, "Could not reopen file");
903c1bb86cdSEric Blake                 ret = -1;
904c1bb86cdSEric Blake             }
905c1bb86cdSEric Blake         }
906c1bb86cdSEric Blake     }
907c1bb86cdSEric Blake 
908c1bb86cdSEric Blake     /* Fail already reopen_prepare() if we can't get a working O_DIRECT
909c1bb86cdSEric Blake      * alignment with the new fd. */
910c1bb86cdSEric Blake     if (rs->fd != -1) {
911c1bb86cdSEric Blake         raw_probe_alignment(state->bs, rs->fd, &local_err);
912c1bb86cdSEric Blake         if (local_err) {
913c1bb86cdSEric Blake             qemu_close(rs->fd);
914c1bb86cdSEric Blake             rs->fd = -1;
915c1bb86cdSEric Blake             error_propagate(errp, local_err);
916c1bb86cdSEric Blake             ret = -EINVAL;
917c1bb86cdSEric Blake         }
918c1bb86cdSEric Blake     }
919c1bb86cdSEric Blake 
92031be8a2aSStefan Hajnoczi out:
92131be8a2aSStefan Hajnoczi     qemu_opts_del(opts);
922c1bb86cdSEric Blake     return ret;
923c1bb86cdSEric Blake }
924c1bb86cdSEric Blake 
925c1bb86cdSEric Blake static void raw_reopen_commit(BDRVReopenState *state)
926c1bb86cdSEric Blake {
927c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
928c1bb86cdSEric Blake     BDRVRawState *s = state->bs->opaque;
929c1bb86cdSEric Blake 
93031be8a2aSStefan Hajnoczi     s->check_cache_dropped = rs->check_cache_dropped;
931c1bb86cdSEric Blake     s->open_flags = rs->open_flags;
932c1bb86cdSEric Blake 
933c1bb86cdSEric Blake     qemu_close(s->fd);
934c1bb86cdSEric Blake     s->fd = rs->fd;
935c1bb86cdSEric Blake 
936c1bb86cdSEric Blake     g_free(state->opaque);
937c1bb86cdSEric Blake     state->opaque = NULL;
938c1bb86cdSEric Blake }
939c1bb86cdSEric Blake 
940c1bb86cdSEric Blake 
941c1bb86cdSEric Blake static void raw_reopen_abort(BDRVReopenState *state)
942c1bb86cdSEric Blake {
943c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
944c1bb86cdSEric Blake 
945c1bb86cdSEric Blake      /* nothing to do if NULL, we didn't get far enough */
946c1bb86cdSEric Blake     if (rs == NULL) {
947c1bb86cdSEric Blake         return;
948c1bb86cdSEric Blake     }
949c1bb86cdSEric Blake 
950c1bb86cdSEric Blake     if (rs->fd >= 0) {
951c1bb86cdSEric Blake         qemu_close(rs->fd);
952c1bb86cdSEric Blake         rs->fd = -1;
953c1bb86cdSEric Blake     }
954c1bb86cdSEric Blake     g_free(state->opaque);
955c1bb86cdSEric Blake     state->opaque = NULL;
956c1bb86cdSEric Blake }
957c1bb86cdSEric Blake 
95848265250SEric Farman static int hdev_get_max_transfer_length(BlockDriverState *bs, int fd)
959c1bb86cdSEric Blake {
960c1bb86cdSEric Blake #ifdef BLKSECTGET
96148265250SEric Farman     int max_bytes = 0;
96248265250SEric Farman     short max_sectors = 0;
96348265250SEric Farman     if (bs->sg && ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
96448265250SEric Farman         return max_bytes;
96548265250SEric Farman     } else if (!bs->sg && ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
96648265250SEric Farman         return max_sectors << BDRV_SECTOR_BITS;
967c1bb86cdSEric Blake     } else {
968c1bb86cdSEric Blake         return -errno;
969c1bb86cdSEric Blake     }
970c1bb86cdSEric Blake #else
971c1bb86cdSEric Blake     return -ENOSYS;
972c1bb86cdSEric Blake #endif
973c1bb86cdSEric Blake }
974c1bb86cdSEric Blake 
9759103f1ceSFam Zheng static int hdev_get_max_segments(const struct stat *st)
9769103f1ceSFam Zheng {
9779103f1ceSFam Zheng #ifdef CONFIG_LINUX
9789103f1ceSFam Zheng     char buf[32];
9799103f1ceSFam Zheng     const char *end;
9809103f1ceSFam Zheng     char *sysfspath;
9819103f1ceSFam Zheng     int ret;
9829103f1ceSFam Zheng     int fd = -1;
9839103f1ceSFam Zheng     long max_segments;
9849103f1ceSFam Zheng 
9859103f1ceSFam Zheng     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
9869103f1ceSFam Zheng                                 major(st->st_rdev), minor(st->st_rdev));
9879103f1ceSFam Zheng     fd = open(sysfspath, O_RDONLY);
9889103f1ceSFam Zheng     if (fd == -1) {
9899103f1ceSFam Zheng         ret = -errno;
9909103f1ceSFam Zheng         goto out;
9919103f1ceSFam Zheng     }
9929103f1ceSFam Zheng     do {
99369583490SStefan Hajnoczi         ret = read(fd, buf, sizeof(buf) - 1);
9949103f1ceSFam Zheng     } while (ret == -1 && errno == EINTR);
9959103f1ceSFam Zheng     if (ret < 0) {
9969103f1ceSFam Zheng         ret = -errno;
9979103f1ceSFam Zheng         goto out;
9989103f1ceSFam Zheng     } else if (ret == 0) {
9999103f1ceSFam Zheng         ret = -EIO;
10009103f1ceSFam Zheng         goto out;
10019103f1ceSFam Zheng     }
10029103f1ceSFam Zheng     buf[ret] = 0;
10039103f1ceSFam Zheng     /* The file is ended with '\n', pass 'end' to accept that. */
10049103f1ceSFam Zheng     ret = qemu_strtol(buf, &end, 10, &max_segments);
10059103f1ceSFam Zheng     if (ret == 0 && end && *end == '\n') {
10069103f1ceSFam Zheng         ret = max_segments;
10079103f1ceSFam Zheng     }
10089103f1ceSFam Zheng 
10099103f1ceSFam Zheng out:
1010fed414dfSFam Zheng     if (fd != -1) {
1011fed414dfSFam Zheng         close(fd);
1012fed414dfSFam Zheng     }
10139103f1ceSFam Zheng     g_free(sysfspath);
10149103f1ceSFam Zheng     return ret;
10159103f1ceSFam Zheng #else
10169103f1ceSFam Zheng     return -ENOTSUP;
10179103f1ceSFam Zheng #endif
10189103f1ceSFam Zheng }
10199103f1ceSFam Zheng 
1020c1bb86cdSEric Blake static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1021c1bb86cdSEric Blake {
1022c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1023c1bb86cdSEric Blake     struct stat st;
1024c1bb86cdSEric Blake 
1025c1bb86cdSEric Blake     if (!fstat(s->fd, &st)) {
1026c4c41a0aSEric Farman         if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
102748265250SEric Farman             int ret = hdev_get_max_transfer_length(bs, s->fd);
102848265250SEric Farman             if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
102948265250SEric Farman                 bs->bl.max_transfer = pow2floor(ret);
1030c1bb86cdSEric Blake             }
10319103f1ceSFam Zheng             ret = hdev_get_max_segments(&st);
10329103f1ceSFam Zheng             if (ret > 0) {
10339103f1ceSFam Zheng                 bs->bl.max_transfer = MIN(bs->bl.max_transfer,
10349103f1ceSFam Zheng                                           ret * getpagesize());
10359103f1ceSFam Zheng             }
1036c1bb86cdSEric Blake         }
1037c1bb86cdSEric Blake     }
1038c1bb86cdSEric Blake 
1039c1bb86cdSEric Blake     raw_probe_alignment(bs, s->fd, errp);
1040c1bb86cdSEric Blake     bs->bl.min_mem_alignment = s->buf_align;
1041c1bb86cdSEric Blake     bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
1042c1bb86cdSEric Blake }
1043c1bb86cdSEric Blake 
1044c1bb86cdSEric Blake static int check_for_dasd(int fd)
1045c1bb86cdSEric Blake {
1046c1bb86cdSEric Blake #ifdef BIODASDINFO2
1047c1bb86cdSEric Blake     struct dasd_information2_t info = {0};
1048c1bb86cdSEric Blake 
1049c1bb86cdSEric Blake     return ioctl(fd, BIODASDINFO2, &info);
1050c1bb86cdSEric Blake #else
1051c1bb86cdSEric Blake     return -1;
1052c1bb86cdSEric Blake #endif
1053c1bb86cdSEric Blake }
1054c1bb86cdSEric Blake 
1055c1bb86cdSEric Blake /**
1056c1bb86cdSEric Blake  * Try to get @bs's logical and physical block size.
1057c1bb86cdSEric Blake  * On success, store them in @bsz and return zero.
1058c1bb86cdSEric Blake  * On failure, return negative errno.
1059c1bb86cdSEric Blake  */
1060c1bb86cdSEric Blake static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1061c1bb86cdSEric Blake {
1062c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1063c1bb86cdSEric Blake     int ret;
1064c1bb86cdSEric Blake 
1065c1bb86cdSEric Blake     /* If DASD, get blocksizes */
1066c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1067c1bb86cdSEric Blake         return -ENOTSUP;
1068c1bb86cdSEric Blake     }
1069c1bb86cdSEric Blake     ret = probe_logical_blocksize(s->fd, &bsz->log);
1070c1bb86cdSEric Blake     if (ret < 0) {
1071c1bb86cdSEric Blake         return ret;
1072c1bb86cdSEric Blake     }
1073c1bb86cdSEric Blake     return probe_physical_blocksize(s->fd, &bsz->phys);
1074c1bb86cdSEric Blake }
1075c1bb86cdSEric Blake 
1076c1bb86cdSEric Blake /**
1077c1bb86cdSEric Blake  * Try to get @bs's geometry: cyls, heads, sectors.
1078c1bb86cdSEric Blake  * On success, store them in @geo and return 0.
1079c1bb86cdSEric Blake  * On failure return -errno.
1080c1bb86cdSEric Blake  * (Allows block driver to assign default geometry values that guest sees)
1081c1bb86cdSEric Blake  */
1082c1bb86cdSEric Blake #ifdef __linux__
1083c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1084c1bb86cdSEric Blake {
1085c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1086c1bb86cdSEric Blake     struct hd_geometry ioctl_geo = {0};
1087c1bb86cdSEric Blake 
1088c1bb86cdSEric Blake     /* If DASD, get its geometry */
1089c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1090c1bb86cdSEric Blake         return -ENOTSUP;
1091c1bb86cdSEric Blake     }
1092c1bb86cdSEric Blake     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1093c1bb86cdSEric Blake         return -errno;
1094c1bb86cdSEric Blake     }
1095c1bb86cdSEric Blake     /* HDIO_GETGEO may return success even though geo contains zeros
1096c1bb86cdSEric Blake        (e.g. certain multipath setups) */
1097c1bb86cdSEric Blake     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1098c1bb86cdSEric Blake         return -ENOTSUP;
1099c1bb86cdSEric Blake     }
1100c1bb86cdSEric Blake     /* Do not return a geometry for partition */
1101c1bb86cdSEric Blake     if (ioctl_geo.start != 0) {
1102c1bb86cdSEric Blake         return -ENOTSUP;
1103c1bb86cdSEric Blake     }
1104c1bb86cdSEric Blake     geo->heads = ioctl_geo.heads;
1105c1bb86cdSEric Blake     geo->sectors = ioctl_geo.sectors;
1106c1bb86cdSEric Blake     geo->cylinders = ioctl_geo.cylinders;
1107c1bb86cdSEric Blake 
1108c1bb86cdSEric Blake     return 0;
1109c1bb86cdSEric Blake }
1110c1bb86cdSEric Blake #else /* __linux__ */
1111c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1112c1bb86cdSEric Blake {
1113c1bb86cdSEric Blake     return -ENOTSUP;
1114c1bb86cdSEric Blake }
1115c1bb86cdSEric Blake #endif
1116c1bb86cdSEric Blake 
1117c1bb86cdSEric Blake static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
1118c1bb86cdSEric Blake {
1119c1bb86cdSEric Blake     int ret;
1120c1bb86cdSEric Blake 
1121c1bb86cdSEric Blake     ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
1122c1bb86cdSEric Blake     if (ret == -1) {
1123c1bb86cdSEric Blake         return -errno;
1124c1bb86cdSEric Blake     }
1125c1bb86cdSEric Blake 
1126c1bb86cdSEric Blake     return 0;
1127c1bb86cdSEric Blake }
1128c1bb86cdSEric Blake 
1129c1bb86cdSEric Blake static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
1130c1bb86cdSEric Blake {
1131e5bcf967SKevin Wolf     BDRVRawState *s = aiocb->bs->opaque;
1132c1bb86cdSEric Blake     int ret;
1133c1bb86cdSEric Blake 
1134e5bcf967SKevin Wolf     if (s->page_cache_inconsistent) {
1135e5bcf967SKevin Wolf         return -EIO;
1136e5bcf967SKevin Wolf     }
1137e5bcf967SKevin Wolf 
1138c1bb86cdSEric Blake     ret = qemu_fdatasync(aiocb->aio_fildes);
1139c1bb86cdSEric Blake     if (ret == -1) {
1140e5bcf967SKevin Wolf         /* There is no clear definition of the semantics of a failing fsync(),
1141e5bcf967SKevin Wolf          * so we may have to assume the worst. The sad truth is that this
1142e5bcf967SKevin Wolf          * assumption is correct for Linux. Some pages are now probably marked
1143e5bcf967SKevin Wolf          * clean in the page cache even though they are inconsistent with the
1144e5bcf967SKevin Wolf          * on-disk contents. The next fdatasync() call would succeed, but no
1145e5bcf967SKevin Wolf          * further writeback attempt will be made. We can't get back to a state
1146e5bcf967SKevin Wolf          * in which we know what is on disk (we would have to rewrite
1147e5bcf967SKevin Wolf          * everything that was touched since the last fdatasync() at least), so
1148e5bcf967SKevin Wolf          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1149e5bcf967SKevin Wolf          * really defined, I have little hope that other OSes are doing better.
1150e5bcf967SKevin Wolf          *
1151e5bcf967SKevin Wolf          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1152e5bcf967SKevin Wolf          * cache. */
1153e5bcf967SKevin Wolf         if ((s->open_flags & O_DIRECT) == 0) {
1154e5bcf967SKevin Wolf             s->page_cache_inconsistent = true;
1155e5bcf967SKevin Wolf         }
1156c1bb86cdSEric Blake         return -errno;
1157c1bb86cdSEric Blake     }
1158c1bb86cdSEric Blake     return 0;
1159c1bb86cdSEric Blake }
1160c1bb86cdSEric Blake 
1161c1bb86cdSEric Blake #ifdef CONFIG_PREADV
1162c1bb86cdSEric Blake 
1163c1bb86cdSEric Blake static bool preadv_present = true;
1164c1bb86cdSEric Blake 
1165c1bb86cdSEric Blake static ssize_t
1166c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1167c1bb86cdSEric Blake {
1168c1bb86cdSEric Blake     return preadv(fd, iov, nr_iov, offset);
1169c1bb86cdSEric Blake }
1170c1bb86cdSEric Blake 
1171c1bb86cdSEric Blake static ssize_t
1172c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1173c1bb86cdSEric Blake {
1174c1bb86cdSEric Blake     return pwritev(fd, iov, nr_iov, offset);
1175c1bb86cdSEric Blake }
1176c1bb86cdSEric Blake 
1177c1bb86cdSEric Blake #else
1178c1bb86cdSEric Blake 
1179c1bb86cdSEric Blake static bool preadv_present = false;
1180c1bb86cdSEric Blake 
1181c1bb86cdSEric Blake static ssize_t
1182c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1183c1bb86cdSEric Blake {
1184c1bb86cdSEric Blake     return -ENOSYS;
1185c1bb86cdSEric Blake }
1186c1bb86cdSEric Blake 
1187c1bb86cdSEric Blake static ssize_t
1188c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1189c1bb86cdSEric Blake {
1190c1bb86cdSEric Blake     return -ENOSYS;
1191c1bb86cdSEric Blake }
1192c1bb86cdSEric Blake 
1193c1bb86cdSEric Blake #endif
1194c1bb86cdSEric Blake 
1195c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1196c1bb86cdSEric Blake {
1197c1bb86cdSEric Blake     ssize_t len;
1198c1bb86cdSEric Blake 
1199c1bb86cdSEric Blake     do {
1200c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE)
1201c1bb86cdSEric Blake             len = qemu_pwritev(aiocb->aio_fildes,
1202c1bb86cdSEric Blake                                aiocb->aio_iov,
1203c1bb86cdSEric Blake                                aiocb->aio_niov,
1204c1bb86cdSEric Blake                                aiocb->aio_offset);
1205c1bb86cdSEric Blake          else
1206c1bb86cdSEric Blake             len = qemu_preadv(aiocb->aio_fildes,
1207c1bb86cdSEric Blake                               aiocb->aio_iov,
1208c1bb86cdSEric Blake                               aiocb->aio_niov,
1209c1bb86cdSEric Blake                               aiocb->aio_offset);
1210c1bb86cdSEric Blake     } while (len == -1 && errno == EINTR);
1211c1bb86cdSEric Blake 
1212c1bb86cdSEric Blake     if (len == -1) {
1213c1bb86cdSEric Blake         return -errno;
1214c1bb86cdSEric Blake     }
1215c1bb86cdSEric Blake     return len;
1216c1bb86cdSEric Blake }
1217c1bb86cdSEric Blake 
1218c1bb86cdSEric Blake /*
1219c1bb86cdSEric Blake  * Read/writes the data to/from a given linear buffer.
1220c1bb86cdSEric Blake  *
1221c1bb86cdSEric Blake  * Returns the number of bytes handles or -errno in case of an error. Short
1222c1bb86cdSEric Blake  * reads are only returned if the end of the file is reached.
1223c1bb86cdSEric Blake  */
1224c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1225c1bb86cdSEric Blake {
1226c1bb86cdSEric Blake     ssize_t offset = 0;
1227c1bb86cdSEric Blake     ssize_t len;
1228c1bb86cdSEric Blake 
1229c1bb86cdSEric Blake     while (offset < aiocb->aio_nbytes) {
1230c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1231c1bb86cdSEric Blake             len = pwrite(aiocb->aio_fildes,
1232c1bb86cdSEric Blake                          (const char *)buf + offset,
1233c1bb86cdSEric Blake                          aiocb->aio_nbytes - offset,
1234c1bb86cdSEric Blake                          aiocb->aio_offset + offset);
1235c1bb86cdSEric Blake         } else {
1236c1bb86cdSEric Blake             len = pread(aiocb->aio_fildes,
1237c1bb86cdSEric Blake                         buf + offset,
1238c1bb86cdSEric Blake                         aiocb->aio_nbytes - offset,
1239c1bb86cdSEric Blake                         aiocb->aio_offset + offset);
1240c1bb86cdSEric Blake         }
1241c1bb86cdSEric Blake         if (len == -1 && errno == EINTR) {
1242c1bb86cdSEric Blake             continue;
1243c1bb86cdSEric Blake         } else if (len == -1 && errno == EINVAL &&
1244c1bb86cdSEric Blake                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1245c1bb86cdSEric Blake                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1246c1bb86cdSEric Blake                    offset > 0) {
1247c1bb86cdSEric Blake             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1248c1bb86cdSEric Blake              * after a short read.  Assume that O_DIRECT short reads only occur
1249c1bb86cdSEric Blake              * at EOF.  Therefore this is a short read, not an I/O error.
1250c1bb86cdSEric Blake              */
1251c1bb86cdSEric Blake             break;
1252c1bb86cdSEric Blake         } else if (len == -1) {
1253c1bb86cdSEric Blake             offset = -errno;
1254c1bb86cdSEric Blake             break;
1255c1bb86cdSEric Blake         } else if (len == 0) {
1256c1bb86cdSEric Blake             break;
1257c1bb86cdSEric Blake         }
1258c1bb86cdSEric Blake         offset += len;
1259c1bb86cdSEric Blake     }
1260c1bb86cdSEric Blake 
1261c1bb86cdSEric Blake     return offset;
1262c1bb86cdSEric Blake }
1263c1bb86cdSEric Blake 
1264c1bb86cdSEric Blake static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
1265c1bb86cdSEric Blake {
1266c1bb86cdSEric Blake     ssize_t nbytes;
1267c1bb86cdSEric Blake     char *buf;
1268c1bb86cdSEric Blake 
1269c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1270c1bb86cdSEric Blake         /*
1271c1bb86cdSEric Blake          * If there is just a single buffer, and it is properly aligned
1272c1bb86cdSEric Blake          * we can just use plain pread/pwrite without any problems.
1273c1bb86cdSEric Blake          */
1274c1bb86cdSEric Blake         if (aiocb->aio_niov == 1) {
1275c1bb86cdSEric Blake              return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
1276c1bb86cdSEric Blake         }
1277c1bb86cdSEric Blake         /*
1278c1bb86cdSEric Blake          * We have more than one iovec, and all are properly aligned.
1279c1bb86cdSEric Blake          *
1280c1bb86cdSEric Blake          * Try preadv/pwritev first and fall back to linearizing the
1281c1bb86cdSEric Blake          * buffer if it's not supported.
1282c1bb86cdSEric Blake          */
1283c1bb86cdSEric Blake         if (preadv_present) {
1284c1bb86cdSEric Blake             nbytes = handle_aiocb_rw_vector(aiocb);
1285c1bb86cdSEric Blake             if (nbytes == aiocb->aio_nbytes ||
1286c1bb86cdSEric Blake                 (nbytes < 0 && nbytes != -ENOSYS)) {
1287c1bb86cdSEric Blake                 return nbytes;
1288c1bb86cdSEric Blake             }
1289c1bb86cdSEric Blake             preadv_present = false;
1290c1bb86cdSEric Blake         }
1291c1bb86cdSEric Blake 
1292c1bb86cdSEric Blake         /*
1293c1bb86cdSEric Blake          * XXX(hch): short read/write.  no easy way to handle the reminder
1294c1bb86cdSEric Blake          * using these interfaces.  For now retry using plain
1295c1bb86cdSEric Blake          * pread/pwrite?
1296c1bb86cdSEric Blake          */
1297c1bb86cdSEric Blake     }
1298c1bb86cdSEric Blake 
1299c1bb86cdSEric Blake     /*
1300c1bb86cdSEric Blake      * Ok, we have to do it the hard way, copy all segments into
1301c1bb86cdSEric Blake      * a single aligned buffer.
1302c1bb86cdSEric Blake      */
1303c1bb86cdSEric Blake     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1304c1bb86cdSEric Blake     if (buf == NULL) {
1305c1bb86cdSEric Blake         return -ENOMEM;
1306c1bb86cdSEric Blake     }
1307c1bb86cdSEric Blake 
1308c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1309c1bb86cdSEric Blake         char *p = buf;
1310c1bb86cdSEric Blake         int i;
1311c1bb86cdSEric Blake 
1312c1bb86cdSEric Blake         for (i = 0; i < aiocb->aio_niov; ++i) {
1313c1bb86cdSEric Blake             memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1314c1bb86cdSEric Blake             p += aiocb->aio_iov[i].iov_len;
1315c1bb86cdSEric Blake         }
1316c1bb86cdSEric Blake         assert(p - buf == aiocb->aio_nbytes);
1317c1bb86cdSEric Blake     }
1318c1bb86cdSEric Blake 
1319c1bb86cdSEric Blake     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1320c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1321c1bb86cdSEric Blake         char *p = buf;
1322c1bb86cdSEric Blake         size_t count = aiocb->aio_nbytes, copy;
1323c1bb86cdSEric Blake         int i;
1324c1bb86cdSEric Blake 
1325c1bb86cdSEric Blake         for (i = 0; i < aiocb->aio_niov && count; ++i) {
1326c1bb86cdSEric Blake             copy = count;
1327c1bb86cdSEric Blake             if (copy > aiocb->aio_iov[i].iov_len) {
1328c1bb86cdSEric Blake                 copy = aiocb->aio_iov[i].iov_len;
1329c1bb86cdSEric Blake             }
1330c1bb86cdSEric Blake             memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1331c1bb86cdSEric Blake             assert(count >= copy);
1332c1bb86cdSEric Blake             p     += copy;
1333c1bb86cdSEric Blake             count -= copy;
1334c1bb86cdSEric Blake         }
1335c1bb86cdSEric Blake         assert(count == 0);
1336c1bb86cdSEric Blake     }
1337c1bb86cdSEric Blake     qemu_vfree(buf);
1338c1bb86cdSEric Blake 
1339c1bb86cdSEric Blake     return nbytes;
1340c1bb86cdSEric Blake }
1341c1bb86cdSEric Blake 
1342c1bb86cdSEric Blake #ifdef CONFIG_XFS
1343c1bb86cdSEric Blake static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1344c1bb86cdSEric Blake {
1345c1bb86cdSEric Blake     struct xfs_flock64 fl;
1346c1bb86cdSEric Blake     int err;
1347c1bb86cdSEric Blake 
1348c1bb86cdSEric Blake     memset(&fl, 0, sizeof(fl));
1349c1bb86cdSEric Blake     fl.l_whence = SEEK_SET;
1350c1bb86cdSEric Blake     fl.l_start = offset;
1351c1bb86cdSEric Blake     fl.l_len = bytes;
1352c1bb86cdSEric Blake 
1353c1bb86cdSEric Blake     if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1354c1bb86cdSEric Blake         err = errno;
1355c1bb86cdSEric Blake         DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1356c1bb86cdSEric Blake         return -err;
1357c1bb86cdSEric Blake     }
1358c1bb86cdSEric Blake 
1359c1bb86cdSEric Blake     return 0;
1360c1bb86cdSEric Blake }
1361c1bb86cdSEric Blake 
1362c1bb86cdSEric Blake static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1363c1bb86cdSEric Blake {
1364c1bb86cdSEric Blake     struct xfs_flock64 fl;
1365c1bb86cdSEric Blake     int err;
1366c1bb86cdSEric Blake 
1367c1bb86cdSEric Blake     memset(&fl, 0, sizeof(fl));
1368c1bb86cdSEric Blake     fl.l_whence = SEEK_SET;
1369c1bb86cdSEric Blake     fl.l_start = offset;
1370c1bb86cdSEric Blake     fl.l_len = bytes;
1371c1bb86cdSEric Blake 
1372c1bb86cdSEric Blake     if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1373c1bb86cdSEric Blake         err = errno;
1374c1bb86cdSEric Blake         DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1375c1bb86cdSEric Blake         return -err;
1376c1bb86cdSEric Blake     }
1377c1bb86cdSEric Blake 
1378c1bb86cdSEric Blake     return 0;
1379c1bb86cdSEric Blake }
1380c1bb86cdSEric Blake #endif
1381c1bb86cdSEric Blake 
1382c1bb86cdSEric Blake static int translate_err(int err)
1383c1bb86cdSEric Blake {
1384c1bb86cdSEric Blake     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1385c1bb86cdSEric Blake         err == -ENOTTY) {
1386c1bb86cdSEric Blake         err = -ENOTSUP;
1387c1bb86cdSEric Blake     }
1388c1bb86cdSEric Blake     return err;
1389c1bb86cdSEric Blake }
1390c1bb86cdSEric Blake 
1391c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
1392c1bb86cdSEric Blake static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1393c1bb86cdSEric Blake {
1394c1bb86cdSEric Blake     do {
1395c1bb86cdSEric Blake         if (fallocate(fd, mode, offset, len) == 0) {
1396c1bb86cdSEric Blake             return 0;
1397c1bb86cdSEric Blake         }
1398c1bb86cdSEric Blake     } while (errno == EINTR);
1399c1bb86cdSEric Blake     return translate_err(-errno);
1400c1bb86cdSEric Blake }
1401c1bb86cdSEric Blake #endif
1402c1bb86cdSEric Blake 
1403c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1404c1bb86cdSEric Blake {
1405c1bb86cdSEric Blake     int ret = -ENOTSUP;
1406c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1407c1bb86cdSEric Blake 
1408c1bb86cdSEric Blake     if (!s->has_write_zeroes) {
1409c1bb86cdSEric Blake         return -ENOTSUP;
1410c1bb86cdSEric Blake     }
1411c1bb86cdSEric Blake 
1412c1bb86cdSEric Blake #ifdef BLKZEROOUT
1413c1bb86cdSEric Blake     do {
1414c1bb86cdSEric Blake         uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1415c1bb86cdSEric Blake         if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1416c1bb86cdSEric Blake             return 0;
1417c1bb86cdSEric Blake         }
1418c1bb86cdSEric Blake     } while (errno == EINTR);
1419c1bb86cdSEric Blake 
1420c1bb86cdSEric Blake     ret = translate_err(-errno);
1421c1bb86cdSEric Blake #endif
1422c1bb86cdSEric Blake 
1423c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1424c1bb86cdSEric Blake         s->has_write_zeroes = false;
1425c1bb86cdSEric Blake     }
1426c1bb86cdSEric Blake     return ret;
1427c1bb86cdSEric Blake }
1428c1bb86cdSEric Blake 
1429c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1430c1bb86cdSEric Blake {
1431c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1432c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1433c1bb86cdSEric Blake #endif
143470d9110bSDenis V. Lunev #ifdef CONFIG_FALLOCATE
143570d9110bSDenis V. Lunev     int64_t len;
143670d9110bSDenis V. Lunev #endif
1437c1bb86cdSEric Blake 
1438c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1439c1bb86cdSEric Blake         return handle_aiocb_write_zeroes_block(aiocb);
1440c1bb86cdSEric Blake     }
1441c1bb86cdSEric Blake 
1442c1bb86cdSEric Blake #ifdef CONFIG_XFS
1443c1bb86cdSEric Blake     if (s->is_xfs) {
1444c1bb86cdSEric Blake         return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1445c1bb86cdSEric Blake     }
1446c1bb86cdSEric Blake #endif
1447c1bb86cdSEric Blake 
1448c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1449c1bb86cdSEric Blake     if (s->has_write_zeroes) {
1450c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1451c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1452c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1453c1bb86cdSEric Blake             return ret;
1454c1bb86cdSEric Blake         }
1455c1bb86cdSEric Blake         s->has_write_zeroes = false;
1456c1bb86cdSEric Blake     }
1457c1bb86cdSEric Blake #endif
1458c1bb86cdSEric Blake 
1459c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1460c1bb86cdSEric Blake     if (s->has_discard && s->has_fallocate) {
1461c1bb86cdSEric Blake         int ret = do_fallocate(s->fd,
1462c1bb86cdSEric Blake                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1463c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1464c1bb86cdSEric Blake         if (ret == 0) {
1465c1bb86cdSEric Blake             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1466c1bb86cdSEric Blake             if (ret == 0 || ret != -ENOTSUP) {
1467c1bb86cdSEric Blake                 return ret;
1468c1bb86cdSEric Blake             }
1469c1bb86cdSEric Blake             s->has_fallocate = false;
1470c1bb86cdSEric Blake         } else if (ret != -ENOTSUP) {
1471c1bb86cdSEric Blake             return ret;
1472c1bb86cdSEric Blake         } else {
1473c1bb86cdSEric Blake             s->has_discard = false;
1474c1bb86cdSEric Blake         }
1475c1bb86cdSEric Blake     }
1476c1bb86cdSEric Blake #endif
1477c1bb86cdSEric Blake 
1478c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
147970d9110bSDenis V. Lunev     /* Last resort: we are trying to extend the file with zeroed data. This
148070d9110bSDenis V. Lunev      * can be done via fallocate(fd, 0) */
148170d9110bSDenis V. Lunev     len = bdrv_getlength(aiocb->bs);
148270d9110bSDenis V. Lunev     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1483c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1484c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1485c1bb86cdSEric Blake             return ret;
1486c1bb86cdSEric Blake         }
1487c1bb86cdSEric Blake         s->has_fallocate = false;
1488c1bb86cdSEric Blake     }
1489c1bb86cdSEric Blake #endif
1490c1bb86cdSEric Blake 
1491c1bb86cdSEric Blake     return -ENOTSUP;
1492c1bb86cdSEric Blake }
1493c1bb86cdSEric Blake 
149434fa110eSKevin Wolf static ssize_t handle_aiocb_write_zeroes_unmap(RawPosixAIOData *aiocb)
149534fa110eSKevin Wolf {
149634fa110eSKevin Wolf     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
149734fa110eSKevin Wolf     int ret;
149834fa110eSKevin Wolf 
149934fa110eSKevin Wolf     /* First try to write zeros and unmap at the same time */
150034fa110eSKevin Wolf 
150134fa110eSKevin Wolf #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
150234fa110eSKevin Wolf     ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
150334fa110eSKevin Wolf                        aiocb->aio_offset, aiocb->aio_nbytes);
150434fa110eSKevin Wolf     if (ret != -ENOTSUP) {
150534fa110eSKevin Wolf         return ret;
150634fa110eSKevin Wolf     }
150734fa110eSKevin Wolf #endif
150834fa110eSKevin Wolf 
150934fa110eSKevin Wolf #ifdef CONFIG_XFS
151034fa110eSKevin Wolf     if (s->is_xfs) {
151134fa110eSKevin Wolf         /* xfs_discard() guarantees that the discarded area reads as all-zero
151234fa110eSKevin Wolf          * afterwards, so we can use it here. */
151334fa110eSKevin Wolf         return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
151434fa110eSKevin Wolf     }
151534fa110eSKevin Wolf #endif
151634fa110eSKevin Wolf 
151734fa110eSKevin Wolf     /* If we couldn't manage to unmap while guaranteed that the area reads as
151834fa110eSKevin Wolf      * all-zero afterwards, just write zeroes without unmapping */
151934fa110eSKevin Wolf     ret = handle_aiocb_write_zeroes(aiocb);
152034fa110eSKevin Wolf     return ret;
152134fa110eSKevin Wolf }
152234fa110eSKevin Wolf 
15231efad060SFam Zheng #ifndef HAVE_COPY_FILE_RANGE
15241efad060SFam Zheng static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
15251efad060SFam Zheng                              off_t *out_off, size_t len, unsigned int flags)
15261efad060SFam Zheng {
15271efad060SFam Zheng #ifdef __NR_copy_file_range
15281efad060SFam Zheng     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
15291efad060SFam Zheng                    out_off, len, flags);
15301efad060SFam Zheng #else
15311efad060SFam Zheng     errno = ENOSYS;
15321efad060SFam Zheng     return -1;
15331efad060SFam Zheng #endif
15341efad060SFam Zheng }
15351efad060SFam Zheng #endif
15361efad060SFam Zheng 
15371efad060SFam Zheng static ssize_t handle_aiocb_copy_range(RawPosixAIOData *aiocb)
15381efad060SFam Zheng {
15391efad060SFam Zheng     uint64_t bytes = aiocb->aio_nbytes;
15401efad060SFam Zheng     off_t in_off = aiocb->aio_offset;
15411efad060SFam Zheng     off_t out_off = aiocb->aio_offset2;
15421efad060SFam Zheng 
15431efad060SFam Zheng     while (bytes) {
15441efad060SFam Zheng         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
15451efad060SFam Zheng                                       aiocb->aio_fd2, &out_off,
15461efad060SFam Zheng                                       bytes, 0);
1547ecc983a5SFam Zheng         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1548ecc983a5SFam Zheng                                    aiocb->aio_fd2, out_off, bytes, 0, ret);
1549c436e3d0SFam Zheng         if (ret == 0) {
1550c436e3d0SFam Zheng             /* No progress (e.g. when beyond EOF), let the caller fall back to
1551c436e3d0SFam Zheng              * buffer I/O. */
1552c436e3d0SFam Zheng             return -ENOSPC;
15531efad060SFam Zheng         }
15541efad060SFam Zheng         if (ret < 0) {
1555c436e3d0SFam Zheng             switch (errno) {
1556c436e3d0SFam Zheng             case ENOSYS:
15571efad060SFam Zheng                 return -ENOTSUP;
1558c436e3d0SFam Zheng             case EINTR:
1559c436e3d0SFam Zheng                 continue;
1560c436e3d0SFam Zheng             default:
15611efad060SFam Zheng                 return -errno;
15621efad060SFam Zheng             }
15631efad060SFam Zheng         }
15641efad060SFam Zheng         bytes -= ret;
15651efad060SFam Zheng     }
15661efad060SFam Zheng     return 0;
15671efad060SFam Zheng }
15681efad060SFam Zheng 
1569c1bb86cdSEric Blake static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1570c1bb86cdSEric Blake {
1571c1bb86cdSEric Blake     int ret = -EOPNOTSUPP;
1572c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1573c1bb86cdSEric Blake 
1574c1bb86cdSEric Blake     if (!s->has_discard) {
1575c1bb86cdSEric Blake         return -ENOTSUP;
1576c1bb86cdSEric Blake     }
1577c1bb86cdSEric Blake 
1578c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1579c1bb86cdSEric Blake #ifdef BLKDISCARD
1580c1bb86cdSEric Blake         do {
1581c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1582c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1583c1bb86cdSEric Blake                 return 0;
1584c1bb86cdSEric Blake             }
1585c1bb86cdSEric Blake         } while (errno == EINTR);
1586c1bb86cdSEric Blake 
1587c1bb86cdSEric Blake         ret = -errno;
1588c1bb86cdSEric Blake #endif
1589c1bb86cdSEric Blake     } else {
1590c1bb86cdSEric Blake #ifdef CONFIG_XFS
1591c1bb86cdSEric Blake         if (s->is_xfs) {
1592c1bb86cdSEric Blake             return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1593c1bb86cdSEric Blake         }
1594c1bb86cdSEric Blake #endif
1595c1bb86cdSEric Blake 
1596c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1597c1bb86cdSEric Blake         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1598c1bb86cdSEric Blake                            aiocb->aio_offset, aiocb->aio_nbytes);
1599c1bb86cdSEric Blake #endif
1600c1bb86cdSEric Blake     }
1601c1bb86cdSEric Blake 
1602c1bb86cdSEric Blake     ret = translate_err(ret);
1603c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1604c1bb86cdSEric Blake         s->has_discard = false;
1605c1bb86cdSEric Blake     }
1606c1bb86cdSEric Blake     return ret;
1607c1bb86cdSEric Blake }
1608c1bb86cdSEric Blake 
160993f4e2ffSKevin Wolf static int handle_aiocb_truncate(RawPosixAIOData *aiocb)
161093f4e2ffSKevin Wolf {
161193f4e2ffSKevin Wolf     int result = 0;
161293f4e2ffSKevin Wolf     int64_t current_length = 0;
161393f4e2ffSKevin Wolf     char *buf = NULL;
161493f4e2ffSKevin Wolf     struct stat st;
161593f4e2ffSKevin Wolf     int fd = aiocb->aio_fildes;
161693f4e2ffSKevin Wolf     int64_t offset = aiocb->aio_offset;
161793f4e2ffSKevin Wolf     Error **errp = aiocb->errp;
161893f4e2ffSKevin Wolf 
161993f4e2ffSKevin Wolf     if (fstat(fd, &st) < 0) {
162093f4e2ffSKevin Wolf         result = -errno;
162193f4e2ffSKevin Wolf         error_setg_errno(errp, -result, "Could not stat file");
162293f4e2ffSKevin Wolf         return result;
162393f4e2ffSKevin Wolf     }
162493f4e2ffSKevin Wolf 
162593f4e2ffSKevin Wolf     current_length = st.st_size;
162693f4e2ffSKevin Wolf     if (current_length > offset && aiocb->prealloc != PREALLOC_MODE_OFF) {
162793f4e2ffSKevin Wolf         error_setg(errp, "Cannot use preallocation for shrinking files");
162893f4e2ffSKevin Wolf         return -ENOTSUP;
162993f4e2ffSKevin Wolf     }
163093f4e2ffSKevin Wolf 
163193f4e2ffSKevin Wolf     switch (aiocb->prealloc) {
163293f4e2ffSKevin Wolf #ifdef CONFIG_POSIX_FALLOCATE
163393f4e2ffSKevin Wolf     case PREALLOC_MODE_FALLOC:
163493f4e2ffSKevin Wolf         /*
163593f4e2ffSKevin Wolf          * Truncating before posix_fallocate() makes it about twice slower on
163693f4e2ffSKevin Wolf          * file systems that do not support fallocate(), trying to check if a
163793f4e2ffSKevin Wolf          * block is allocated before allocating it, so don't do that here.
163893f4e2ffSKevin Wolf          */
163993f4e2ffSKevin Wolf         if (offset != current_length) {
164093f4e2ffSKevin Wolf             result = -posix_fallocate(fd, current_length,
164193f4e2ffSKevin Wolf                                       offset - current_length);
164293f4e2ffSKevin Wolf             if (result != 0) {
164393f4e2ffSKevin Wolf                 /* posix_fallocate() doesn't set errno. */
164493f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
164593f4e2ffSKevin Wolf                                  "Could not preallocate new data");
164693f4e2ffSKevin Wolf             }
164793f4e2ffSKevin Wolf         } else {
164893f4e2ffSKevin Wolf             result = 0;
164993f4e2ffSKevin Wolf         }
165093f4e2ffSKevin Wolf         goto out;
165193f4e2ffSKevin Wolf #endif
165293f4e2ffSKevin Wolf     case PREALLOC_MODE_FULL:
165393f4e2ffSKevin Wolf     {
165493f4e2ffSKevin Wolf         int64_t num = 0, left = offset - current_length;
165593f4e2ffSKevin Wolf         off_t seek_result;
165693f4e2ffSKevin Wolf 
165793f4e2ffSKevin Wolf         /*
165893f4e2ffSKevin Wolf          * Knowing the final size from the beginning could allow the file
165993f4e2ffSKevin Wolf          * system driver to do less allocations and possibly avoid
166093f4e2ffSKevin Wolf          * fragmentation of the file.
166193f4e2ffSKevin Wolf          */
166293f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
166393f4e2ffSKevin Wolf             result = -errno;
166493f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
166593f4e2ffSKevin Wolf             goto out;
166693f4e2ffSKevin Wolf         }
166793f4e2ffSKevin Wolf 
166893f4e2ffSKevin Wolf         buf = g_malloc0(65536);
166993f4e2ffSKevin Wolf 
167093f4e2ffSKevin Wolf         seek_result = lseek(fd, current_length, SEEK_SET);
167193f4e2ffSKevin Wolf         if (seek_result < 0) {
167293f4e2ffSKevin Wolf             result = -errno;
167393f4e2ffSKevin Wolf             error_setg_errno(errp, -result,
167493f4e2ffSKevin Wolf                              "Failed to seek to the old end of file");
167593f4e2ffSKevin Wolf             goto out;
167693f4e2ffSKevin Wolf         }
167793f4e2ffSKevin Wolf 
167893f4e2ffSKevin Wolf         while (left > 0) {
167993f4e2ffSKevin Wolf             num = MIN(left, 65536);
168093f4e2ffSKevin Wolf             result = write(fd, buf, num);
168193f4e2ffSKevin Wolf             if (result < 0) {
1682a1c81f4fSFam Zheng                 if (errno == EINTR) {
1683a1c81f4fSFam Zheng                     continue;
1684a1c81f4fSFam Zheng                 }
168593f4e2ffSKevin Wolf                 result = -errno;
168693f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
168793f4e2ffSKevin Wolf                                  "Could not write zeros for preallocation");
168893f4e2ffSKevin Wolf                 goto out;
168993f4e2ffSKevin Wolf             }
169093f4e2ffSKevin Wolf             left -= result;
169193f4e2ffSKevin Wolf         }
169293f4e2ffSKevin Wolf         if (result >= 0) {
169393f4e2ffSKevin Wolf             result = fsync(fd);
169493f4e2ffSKevin Wolf             if (result < 0) {
169593f4e2ffSKevin Wolf                 result = -errno;
169693f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
169793f4e2ffSKevin Wolf                                  "Could not flush file to disk");
169893f4e2ffSKevin Wolf                 goto out;
169993f4e2ffSKevin Wolf             }
170093f4e2ffSKevin Wolf         }
170193f4e2ffSKevin Wolf         goto out;
170293f4e2ffSKevin Wolf     }
170393f4e2ffSKevin Wolf     case PREALLOC_MODE_OFF:
170493f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
170593f4e2ffSKevin Wolf             result = -errno;
170693f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
170793f4e2ffSKevin Wolf         }
170893f4e2ffSKevin Wolf         return result;
170993f4e2ffSKevin Wolf     default:
171093f4e2ffSKevin Wolf         result = -ENOTSUP;
171193f4e2ffSKevin Wolf         error_setg(errp, "Unsupported preallocation mode: %s",
171293f4e2ffSKevin Wolf                    PreallocMode_str(aiocb->prealloc));
171393f4e2ffSKevin Wolf         return result;
171493f4e2ffSKevin Wolf     }
171593f4e2ffSKevin Wolf 
171693f4e2ffSKevin Wolf out:
171793f4e2ffSKevin Wolf     if (result < 0) {
171893f4e2ffSKevin Wolf         if (ftruncate(fd, current_length) < 0) {
171993f4e2ffSKevin Wolf             error_report("Failed to restore old file length: %s",
172093f4e2ffSKevin Wolf                          strerror(errno));
172193f4e2ffSKevin Wolf         }
172293f4e2ffSKevin Wolf     }
172393f4e2ffSKevin Wolf 
172493f4e2ffSKevin Wolf     g_free(buf);
172593f4e2ffSKevin Wolf     return result;
172693f4e2ffSKevin Wolf }
172793f4e2ffSKevin Wolf 
1728c1bb86cdSEric Blake static int aio_worker(void *arg)
1729c1bb86cdSEric Blake {
1730c1bb86cdSEric Blake     RawPosixAIOData *aiocb = arg;
1731c1bb86cdSEric Blake     ssize_t ret = 0;
1732c1bb86cdSEric Blake 
1733c1bb86cdSEric Blake     switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1734c1bb86cdSEric Blake     case QEMU_AIO_READ:
1735c1bb86cdSEric Blake         ret = handle_aiocb_rw(aiocb);
1736c1bb86cdSEric Blake         if (ret >= 0 && ret < aiocb->aio_nbytes) {
1737c1bb86cdSEric Blake             iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1738c1bb86cdSEric Blake                       0, aiocb->aio_nbytes - ret);
1739c1bb86cdSEric Blake 
1740c1bb86cdSEric Blake             ret = aiocb->aio_nbytes;
1741c1bb86cdSEric Blake         }
1742c1bb86cdSEric Blake         if (ret == aiocb->aio_nbytes) {
1743c1bb86cdSEric Blake             ret = 0;
1744c1bb86cdSEric Blake         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1745c1bb86cdSEric Blake             ret = -EINVAL;
1746c1bb86cdSEric Blake         }
1747c1bb86cdSEric Blake         break;
1748c1bb86cdSEric Blake     case QEMU_AIO_WRITE:
1749c1bb86cdSEric Blake         ret = handle_aiocb_rw(aiocb);
1750c1bb86cdSEric Blake         if (ret == aiocb->aio_nbytes) {
1751c1bb86cdSEric Blake             ret = 0;
1752c1bb86cdSEric Blake         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1753c1bb86cdSEric Blake             ret = -EINVAL;
1754c1bb86cdSEric Blake         }
1755c1bb86cdSEric Blake         break;
1756c1bb86cdSEric Blake     case QEMU_AIO_FLUSH:
1757c1bb86cdSEric Blake         ret = handle_aiocb_flush(aiocb);
1758c1bb86cdSEric Blake         break;
1759c1bb86cdSEric Blake     case QEMU_AIO_IOCTL:
1760c1bb86cdSEric Blake         ret = handle_aiocb_ioctl(aiocb);
1761c1bb86cdSEric Blake         break;
1762c1bb86cdSEric Blake     case QEMU_AIO_DISCARD:
1763c1bb86cdSEric Blake         ret = handle_aiocb_discard(aiocb);
1764c1bb86cdSEric Blake         break;
1765c1bb86cdSEric Blake     case QEMU_AIO_WRITE_ZEROES:
1766c1bb86cdSEric Blake         ret = handle_aiocb_write_zeroes(aiocb);
1767c1bb86cdSEric Blake         break;
176834fa110eSKevin Wolf     case QEMU_AIO_WRITE_ZEROES | QEMU_AIO_DISCARD:
176934fa110eSKevin Wolf         ret = handle_aiocb_write_zeroes_unmap(aiocb);
177034fa110eSKevin Wolf         break;
17711efad060SFam Zheng     case QEMU_AIO_COPY_RANGE:
17721efad060SFam Zheng         ret = handle_aiocb_copy_range(aiocb);
17731efad060SFam Zheng         break;
177493f4e2ffSKevin Wolf     case QEMU_AIO_TRUNCATE:
177593f4e2ffSKevin Wolf         ret = handle_aiocb_truncate(aiocb);
177693f4e2ffSKevin Wolf         break;
1777c1bb86cdSEric Blake     default:
1778c1bb86cdSEric Blake         fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1779c1bb86cdSEric Blake         ret = -EINVAL;
1780c1bb86cdSEric Blake         break;
1781c1bb86cdSEric Blake     }
1782c1bb86cdSEric Blake 
1783c1bb86cdSEric Blake     g_free(aiocb);
1784c1bb86cdSEric Blake     return ret;
1785c1bb86cdSEric Blake }
1786c1bb86cdSEric Blake 
17871efad060SFam Zheng static int paio_submit_co_full(BlockDriverState *bs, int fd,
17881efad060SFam Zheng                                int64_t offset, int fd2, int64_t offset2,
17891efad060SFam Zheng                                QEMUIOVector *qiov,
1790f5a5ca79SManos Pitsidianakis                                int bytes, int type)
1791c1bb86cdSEric Blake {
1792c1bb86cdSEric Blake     RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1793c1bb86cdSEric Blake     ThreadPool *pool;
1794c1bb86cdSEric Blake 
1795c1bb86cdSEric Blake     acb->bs = bs;
1796c1bb86cdSEric Blake     acb->aio_type = type;
1797c1bb86cdSEric Blake     acb->aio_fildes = fd;
17981efad060SFam Zheng     acb->aio_fd2 = fd2;
17991efad060SFam Zheng     acb->aio_offset2 = offset2;
1800c1bb86cdSEric Blake 
1801f5a5ca79SManos Pitsidianakis     acb->aio_nbytes = bytes;
1802c1bb86cdSEric Blake     acb->aio_offset = offset;
1803c1bb86cdSEric Blake 
1804c1bb86cdSEric Blake     if (qiov) {
1805c1bb86cdSEric Blake         acb->aio_iov = qiov->iov;
1806c1bb86cdSEric Blake         acb->aio_niov = qiov->niov;
1807f5a5ca79SManos Pitsidianakis         assert(qiov->size == bytes);
1808c1bb86cdSEric Blake     }
1809c1bb86cdSEric Blake 
1810f8a30874SFam Zheng     trace_file_paio_submit_co(offset, bytes, type);
1811c1bb86cdSEric Blake     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1812c1bb86cdSEric Blake     return thread_pool_submit_co(pool, aio_worker, acb);
1813c1bb86cdSEric Blake }
1814c1bb86cdSEric Blake 
18151efad060SFam Zheng static inline int paio_submit_co(BlockDriverState *bs, int fd,
18161efad060SFam Zheng                                  int64_t offset, QEMUIOVector *qiov,
18171efad060SFam Zheng                                  int bytes, int type)
18181efad060SFam Zheng {
18191efad060SFam Zheng     return paio_submit_co_full(bs, fd, offset, -1, 0, qiov, bytes, type);
18201efad060SFam Zheng }
18211efad060SFam Zheng 
1822c1bb86cdSEric Blake static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1823c1bb86cdSEric Blake                                    uint64_t bytes, QEMUIOVector *qiov, int type)
1824c1bb86cdSEric Blake {
1825c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1826c1bb86cdSEric Blake 
1827c1bb86cdSEric Blake     if (fd_open(bs) < 0)
1828c1bb86cdSEric Blake         return -EIO;
1829c1bb86cdSEric Blake 
1830c1bb86cdSEric Blake     /*
1831c1bb86cdSEric Blake      * Check if the underlying device requires requests to be aligned,
1832c1bb86cdSEric Blake      * and if the request we are trying to submit is aligned or not.
1833c1bb86cdSEric Blake      * If this is the case tell the low-level driver that it needs
1834c1bb86cdSEric Blake      * to copy the buffer.
1835c1bb86cdSEric Blake      */
1836c1bb86cdSEric Blake     if (s->needs_alignment) {
1837c1bb86cdSEric Blake         if (!bdrv_qiov_is_aligned(bs, qiov)) {
1838c1bb86cdSEric Blake             type |= QEMU_AIO_MISALIGNED;
1839c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1840c1bb86cdSEric Blake         } else if (s->use_linux_aio) {
1841c1bb86cdSEric Blake             LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1842c1bb86cdSEric Blake             assert(qiov->size == bytes);
1843c1bb86cdSEric Blake             return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
1844c1bb86cdSEric Blake #endif
1845c1bb86cdSEric Blake         }
1846c1bb86cdSEric Blake     }
1847c1bb86cdSEric Blake 
1848c1bb86cdSEric Blake     return paio_submit_co(bs, s->fd, offset, qiov, bytes, type);
1849c1bb86cdSEric Blake }
1850c1bb86cdSEric Blake 
1851c1bb86cdSEric Blake static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1852c1bb86cdSEric Blake                                       uint64_t bytes, QEMUIOVector *qiov,
1853c1bb86cdSEric Blake                                       int flags)
1854c1bb86cdSEric Blake {
1855c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
1856c1bb86cdSEric Blake }
1857c1bb86cdSEric Blake 
1858c1bb86cdSEric Blake static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1859c1bb86cdSEric Blake                                        uint64_t bytes, QEMUIOVector *qiov,
1860c1bb86cdSEric Blake                                        int flags)
1861c1bb86cdSEric Blake {
1862c1bb86cdSEric Blake     assert(flags == 0);
1863c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
1864c1bb86cdSEric Blake }
1865c1bb86cdSEric Blake 
1866c1bb86cdSEric Blake static void raw_aio_plug(BlockDriverState *bs)
1867c1bb86cdSEric Blake {
1868c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1869c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1870c1bb86cdSEric Blake     if (s->use_linux_aio) {
1871c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1872c1bb86cdSEric Blake         laio_io_plug(bs, aio);
1873c1bb86cdSEric Blake     }
1874c1bb86cdSEric Blake #endif
1875c1bb86cdSEric Blake }
1876c1bb86cdSEric Blake 
1877c1bb86cdSEric Blake static void raw_aio_unplug(BlockDriverState *bs)
1878c1bb86cdSEric Blake {
1879c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1880c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1881c1bb86cdSEric Blake     if (s->use_linux_aio) {
1882c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1883c1bb86cdSEric Blake         laio_io_unplug(bs, aio);
1884c1bb86cdSEric Blake     }
1885c1bb86cdSEric Blake #endif
1886c1bb86cdSEric Blake }
1887c1bb86cdSEric Blake 
188833d70fb6SKevin Wolf static int raw_co_flush_to_disk(BlockDriverState *bs)
1889c1bb86cdSEric Blake {
1890c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
189133d70fb6SKevin Wolf     int ret;
1892c1bb86cdSEric Blake 
189333d70fb6SKevin Wolf     ret = fd_open(bs);
189433d70fb6SKevin Wolf     if (ret < 0) {
189533d70fb6SKevin Wolf         return ret;
189633d70fb6SKevin Wolf     }
1897c1bb86cdSEric Blake 
189833d70fb6SKevin Wolf     return paio_submit_co(bs, s->fd, 0, NULL, 0, QEMU_AIO_FLUSH);
1899c1bb86cdSEric Blake }
1900c1bb86cdSEric Blake 
1901ed6e2161SNishanth Aravamudan static void raw_aio_attach_aio_context(BlockDriverState *bs,
1902ed6e2161SNishanth Aravamudan                                        AioContext *new_context)
1903ed6e2161SNishanth Aravamudan {
1904ed6e2161SNishanth Aravamudan #ifdef CONFIG_LINUX_AIO
1905ed6e2161SNishanth Aravamudan     BDRVRawState *s = bs->opaque;
1906ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
1907ed6e2161SNishanth Aravamudan         Error *local_err;
1908ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(new_context, &local_err)) {
1909ed6e2161SNishanth Aravamudan             error_reportf_err(local_err, "Unable to use native AIO, "
1910ed6e2161SNishanth Aravamudan                                          "falling back to thread pool: ");
1911ed6e2161SNishanth Aravamudan             s->use_linux_aio = false;
1912ed6e2161SNishanth Aravamudan         }
1913ed6e2161SNishanth Aravamudan     }
1914ed6e2161SNishanth Aravamudan #endif
1915ed6e2161SNishanth Aravamudan }
1916ed6e2161SNishanth Aravamudan 
1917c1bb86cdSEric Blake static void raw_close(BlockDriverState *bs)
1918c1bb86cdSEric Blake {
1919c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1920c1bb86cdSEric Blake 
1921c1bb86cdSEric Blake     if (s->fd >= 0) {
1922c1bb86cdSEric Blake         qemu_close(s->fd);
1923c1bb86cdSEric Blake         s->fd = -1;
1924c1bb86cdSEric Blake     }
1925244a5668SFam Zheng     if (s->lock_fd >= 0) {
1926244a5668SFam Zheng         qemu_close(s->lock_fd);
1927244a5668SFam Zheng         s->lock_fd = -1;
1928244a5668SFam Zheng     }
1929c1bb86cdSEric Blake }
1930c1bb86cdSEric Blake 
1931d0bc9e5dSMax Reitz /**
1932d0bc9e5dSMax Reitz  * Truncates the given regular file @fd to @offset and, when growing, fills the
1933d0bc9e5dSMax Reitz  * new space according to @prealloc.
1934d0bc9e5dSMax Reitz  *
1935d0bc9e5dSMax Reitz  * Returns: 0 on success, -errno on failure.
1936d0bc9e5dSMax Reitz  */
193793f4e2ffSKevin Wolf static int coroutine_fn
193893f4e2ffSKevin Wolf raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
193993f4e2ffSKevin Wolf                      PreallocMode prealloc, Error **errp)
19409f63b07eSMax Reitz {
194193f4e2ffSKevin Wolf     RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
194293f4e2ffSKevin Wolf     ThreadPool *pool;
1943d0bc9e5dSMax Reitz 
194493f4e2ffSKevin Wolf     *acb = (RawPosixAIOData) {
194593f4e2ffSKevin Wolf         .bs             = bs,
194693f4e2ffSKevin Wolf         .aio_fildes     = fd,
194793f4e2ffSKevin Wolf         .aio_type       = QEMU_AIO_TRUNCATE,
194893f4e2ffSKevin Wolf         .aio_offset     = offset,
194993f4e2ffSKevin Wolf         .prealloc       = prealloc,
195093f4e2ffSKevin Wolf         .errp           = errp,
195193f4e2ffSKevin Wolf     };
1952d0bc9e5dSMax Reitz 
195393f4e2ffSKevin Wolf     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
195493f4e2ffSKevin Wolf     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
195593f4e2ffSKevin Wolf     return thread_pool_submit_co(pool, aio_worker, acb);
19569f63b07eSMax Reitz }
19579f63b07eSMax Reitz 
1958061ca8a3SKevin Wolf static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
19598243ccb7SMax Reitz                                         PreallocMode prealloc, Error **errp)
1960c1bb86cdSEric Blake {
1961c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1962c1bb86cdSEric Blake     struct stat st;
1963f59adb32SMax Reitz     int ret;
1964c1bb86cdSEric Blake 
1965c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
1966f59adb32SMax Reitz         ret = -errno;
1967f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to fstat() the file");
1968f59adb32SMax Reitz         return ret;
1969c1bb86cdSEric Blake     }
1970c1bb86cdSEric Blake 
1971c1bb86cdSEric Blake     if (S_ISREG(st.st_mode)) {
197293f4e2ffSKevin Wolf         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
1973c1bb86cdSEric Blake     }
197435d72602SMax Reitz 
197535d72602SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
197635d72602SMax Reitz         error_setg(errp, "Preallocation mode '%s' unsupported for this "
1977977c736fSMarkus Armbruster                    "non-regular file", PreallocMode_str(prealloc));
197835d72602SMax Reitz         return -ENOTSUP;
197935d72602SMax Reitz     }
198035d72602SMax Reitz 
198135d72602SMax Reitz     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1982c1bb86cdSEric Blake         if (offset > raw_getlength(bs)) {
1983f59adb32SMax Reitz             error_setg(errp, "Cannot grow device files");
1984c1bb86cdSEric Blake             return -EINVAL;
1985c1bb86cdSEric Blake         }
1986c1bb86cdSEric Blake     } else {
1987f59adb32SMax Reitz         error_setg(errp, "Resizing this file is not supported");
1988c1bb86cdSEric Blake         return -ENOTSUP;
1989c1bb86cdSEric Blake     }
1990c1bb86cdSEric Blake 
1991c1bb86cdSEric Blake     return 0;
1992c1bb86cdSEric Blake }
1993c1bb86cdSEric Blake 
1994c1bb86cdSEric Blake #ifdef __OpenBSD__
1995c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
1996c1bb86cdSEric Blake {
1997c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1998c1bb86cdSEric Blake     int fd = s->fd;
1999c1bb86cdSEric Blake     struct stat st;
2000c1bb86cdSEric Blake 
2001c1bb86cdSEric Blake     if (fstat(fd, &st))
2002c1bb86cdSEric Blake         return -errno;
2003c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2004c1bb86cdSEric Blake         struct disklabel dl;
2005c1bb86cdSEric Blake 
2006c1bb86cdSEric Blake         if (ioctl(fd, DIOCGDINFO, &dl))
2007c1bb86cdSEric Blake             return -errno;
2008c1bb86cdSEric Blake         return (uint64_t)dl.d_secsize *
2009c1bb86cdSEric Blake             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2010c1bb86cdSEric Blake     } else
2011c1bb86cdSEric Blake         return st.st_size;
2012c1bb86cdSEric Blake }
2013c1bb86cdSEric Blake #elif defined(__NetBSD__)
2014c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2015c1bb86cdSEric Blake {
2016c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2017c1bb86cdSEric Blake     int fd = s->fd;
2018c1bb86cdSEric Blake     struct stat st;
2019c1bb86cdSEric Blake 
2020c1bb86cdSEric Blake     if (fstat(fd, &st))
2021c1bb86cdSEric Blake         return -errno;
2022c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2023c1bb86cdSEric Blake         struct dkwedge_info dkw;
2024c1bb86cdSEric Blake 
2025c1bb86cdSEric Blake         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2026c1bb86cdSEric Blake             return dkw.dkw_size * 512;
2027c1bb86cdSEric Blake         } else {
2028c1bb86cdSEric Blake             struct disklabel dl;
2029c1bb86cdSEric Blake 
2030c1bb86cdSEric Blake             if (ioctl(fd, DIOCGDINFO, &dl))
2031c1bb86cdSEric Blake                 return -errno;
2032c1bb86cdSEric Blake             return (uint64_t)dl.d_secsize *
2033c1bb86cdSEric Blake                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2034c1bb86cdSEric Blake         }
2035c1bb86cdSEric Blake     } else
2036c1bb86cdSEric Blake         return st.st_size;
2037c1bb86cdSEric Blake }
2038c1bb86cdSEric Blake #elif defined(__sun__)
2039c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2040c1bb86cdSEric Blake {
2041c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2042c1bb86cdSEric Blake     struct dk_minfo minfo;
2043c1bb86cdSEric Blake     int ret;
2044c1bb86cdSEric Blake     int64_t size;
2045c1bb86cdSEric Blake 
2046c1bb86cdSEric Blake     ret = fd_open(bs);
2047c1bb86cdSEric Blake     if (ret < 0) {
2048c1bb86cdSEric Blake         return ret;
2049c1bb86cdSEric Blake     }
2050c1bb86cdSEric Blake 
2051c1bb86cdSEric Blake     /*
2052c1bb86cdSEric Blake      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2053c1bb86cdSEric Blake      */
2054c1bb86cdSEric Blake     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2055c1bb86cdSEric Blake     if (ret != -1) {
2056c1bb86cdSEric Blake         return minfo.dki_lbsize * minfo.dki_capacity;
2057c1bb86cdSEric Blake     }
2058c1bb86cdSEric Blake 
2059c1bb86cdSEric Blake     /*
2060c1bb86cdSEric Blake      * There are reports that lseek on some devices fails, but
2061c1bb86cdSEric Blake      * irc discussion said that contingency on contingency was overkill.
2062c1bb86cdSEric Blake      */
2063c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2064c1bb86cdSEric Blake     if (size < 0) {
2065c1bb86cdSEric Blake         return -errno;
2066c1bb86cdSEric Blake     }
2067c1bb86cdSEric Blake     return size;
2068c1bb86cdSEric Blake }
2069c1bb86cdSEric Blake #elif defined(CONFIG_BSD)
2070c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2071c1bb86cdSEric Blake {
2072c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2073c1bb86cdSEric Blake     int fd = s->fd;
2074c1bb86cdSEric Blake     int64_t size;
2075c1bb86cdSEric Blake     struct stat sb;
2076c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2077c1bb86cdSEric Blake     int reopened = 0;
2078c1bb86cdSEric Blake #endif
2079c1bb86cdSEric Blake     int ret;
2080c1bb86cdSEric Blake 
2081c1bb86cdSEric Blake     ret = fd_open(bs);
2082c1bb86cdSEric Blake     if (ret < 0)
2083c1bb86cdSEric Blake         return ret;
2084c1bb86cdSEric Blake 
2085c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2086c1bb86cdSEric Blake again:
2087c1bb86cdSEric Blake #endif
2088c1bb86cdSEric Blake     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2089c1bb86cdSEric Blake #ifdef DIOCGMEDIASIZE
2090c1bb86cdSEric Blake 	if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
2091c1bb86cdSEric Blake #elif defined(DIOCGPART)
2092c1bb86cdSEric Blake         {
2093c1bb86cdSEric Blake                 struct partinfo pi;
2094c1bb86cdSEric Blake                 if (ioctl(fd, DIOCGPART, &pi) == 0)
2095c1bb86cdSEric Blake                         size = pi.media_size;
2096c1bb86cdSEric Blake                 else
2097c1bb86cdSEric Blake                         size = 0;
2098c1bb86cdSEric Blake         }
2099c1bb86cdSEric Blake         if (size == 0)
2100c1bb86cdSEric Blake #endif
2101c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
2102c1bb86cdSEric Blake         {
2103c1bb86cdSEric Blake             uint64_t sectors = 0;
2104c1bb86cdSEric Blake             uint32_t sector_size = 0;
2105c1bb86cdSEric Blake 
2106c1bb86cdSEric Blake             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2107c1bb86cdSEric Blake                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2108c1bb86cdSEric Blake                 size = sectors * sector_size;
2109c1bb86cdSEric Blake             } else {
2110c1bb86cdSEric Blake                 size = lseek(fd, 0LL, SEEK_END);
2111c1bb86cdSEric Blake                 if (size < 0) {
2112c1bb86cdSEric Blake                     return -errno;
2113c1bb86cdSEric Blake                 }
2114c1bb86cdSEric Blake             }
2115c1bb86cdSEric Blake         }
2116c1bb86cdSEric Blake #else
2117c1bb86cdSEric Blake         size = lseek(fd, 0LL, SEEK_END);
2118c1bb86cdSEric Blake         if (size < 0) {
2119c1bb86cdSEric Blake             return -errno;
2120c1bb86cdSEric Blake         }
2121c1bb86cdSEric Blake #endif
2122c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2123c1bb86cdSEric Blake         switch(s->type) {
2124c1bb86cdSEric Blake         case FTYPE_CD:
2125c1bb86cdSEric Blake             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2126c1bb86cdSEric Blake             if (size == 2048LL * (unsigned)-1)
2127c1bb86cdSEric Blake                 size = 0;
2128c1bb86cdSEric Blake             /* XXX no disc?  maybe we need to reopen... */
2129c1bb86cdSEric Blake             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2130c1bb86cdSEric Blake                 reopened = 1;
2131c1bb86cdSEric Blake                 goto again;
2132c1bb86cdSEric Blake             }
2133c1bb86cdSEric Blake         }
2134c1bb86cdSEric Blake #endif
2135c1bb86cdSEric Blake     } else {
2136c1bb86cdSEric Blake         size = lseek(fd, 0, SEEK_END);
2137c1bb86cdSEric Blake         if (size < 0) {
2138c1bb86cdSEric Blake             return -errno;
2139c1bb86cdSEric Blake         }
2140c1bb86cdSEric Blake     }
2141c1bb86cdSEric Blake     return size;
2142c1bb86cdSEric Blake }
2143c1bb86cdSEric Blake #else
2144c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2145c1bb86cdSEric Blake {
2146c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2147c1bb86cdSEric Blake     int ret;
2148c1bb86cdSEric Blake     int64_t size;
2149c1bb86cdSEric Blake 
2150c1bb86cdSEric Blake     ret = fd_open(bs);
2151c1bb86cdSEric Blake     if (ret < 0) {
2152c1bb86cdSEric Blake         return ret;
2153c1bb86cdSEric Blake     }
2154c1bb86cdSEric Blake 
2155c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2156c1bb86cdSEric Blake     if (size < 0) {
2157c1bb86cdSEric Blake         return -errno;
2158c1bb86cdSEric Blake     }
2159c1bb86cdSEric Blake     return size;
2160c1bb86cdSEric Blake }
2161c1bb86cdSEric Blake #endif
2162c1bb86cdSEric Blake 
2163c1bb86cdSEric Blake static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
2164c1bb86cdSEric Blake {
2165c1bb86cdSEric Blake     struct stat st;
2166c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2167c1bb86cdSEric Blake 
2168c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
2169c1bb86cdSEric Blake         return -errno;
2170c1bb86cdSEric Blake     }
2171c1bb86cdSEric Blake     return (int64_t)st.st_blocks * 512;
2172c1bb86cdSEric Blake }
2173c1bb86cdSEric Blake 
217493f4e2ffSKevin Wolf static int coroutine_fn
217593f4e2ffSKevin Wolf raw_co_create(BlockdevCreateOptions *options, Error **errp)
2176c1bb86cdSEric Blake {
2177927f11e1SKevin Wolf     BlockdevCreateOptionsFile *file_opts;
21787c20c808SMax Reitz     Error *local_err = NULL;
2179c1bb86cdSEric Blake     int fd;
2180d815efcaSMax Reitz     uint64_t perm, shared;
2181c1bb86cdSEric Blake     int result = 0;
2182c1bb86cdSEric Blake 
2183927f11e1SKevin Wolf     /* Validate options and set default values */
2184927f11e1SKevin Wolf     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2185927f11e1SKevin Wolf     file_opts = &options->u.file;
2186c1bb86cdSEric Blake 
2187927f11e1SKevin Wolf     if (!file_opts->has_nocow) {
2188927f11e1SKevin Wolf         file_opts->nocow = false;
2189927f11e1SKevin Wolf     }
2190927f11e1SKevin Wolf     if (!file_opts->has_preallocation) {
2191927f11e1SKevin Wolf         file_opts->preallocation = PREALLOC_MODE_OFF;
2192c1bb86cdSEric Blake     }
2193c1bb86cdSEric Blake 
2194927f11e1SKevin Wolf     /* Create file */
2195b8cf1913SMax Reitz     fd = qemu_open(file_opts->filename, O_RDWR | O_CREAT | O_BINARY, 0644);
2196c1bb86cdSEric Blake     if (fd < 0) {
2197c1bb86cdSEric Blake         result = -errno;
2198c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not create file");
2199c1bb86cdSEric Blake         goto out;
2200c1bb86cdSEric Blake     }
2201c1bb86cdSEric Blake 
2202b8cf1913SMax Reitz     /* Take permissions: We want to discard everything, so we need
2203b8cf1913SMax Reitz      * BLK_PERM_WRITE; and truncation to the desired size requires
2204b8cf1913SMax Reitz      * BLK_PERM_RESIZE.
2205b8cf1913SMax Reitz      * On the other hand, we cannot share the RESIZE permission
2206b8cf1913SMax Reitz      * because we promise that after this function, the file has the
2207b8cf1913SMax Reitz      * size given in the options.  If someone else were to resize it
2208b8cf1913SMax Reitz      * concurrently, we could not guarantee that.
2209b8cf1913SMax Reitz      * Note that after this function, we can no longer guarantee that
2210b8cf1913SMax Reitz      * the file is not touched by a third party, so it may be resized
2211b8cf1913SMax Reitz      * then. */
2212b8cf1913SMax Reitz     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2213b8cf1913SMax Reitz     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2214b8cf1913SMax Reitz 
2215b8cf1913SMax Reitz     /* Step one: Take locks */
2216d815efcaSMax Reitz     result = raw_apply_lock_bytes(fd, perm, ~shared, false, errp);
2217b8cf1913SMax Reitz     if (result < 0) {
2218b8cf1913SMax Reitz         goto out_close;
2219b8cf1913SMax Reitz     }
2220b8cf1913SMax Reitz 
2221b8cf1913SMax Reitz     /* Step two: Check that nobody else has taken conflicting locks */
2222b8cf1913SMax Reitz     result = raw_check_lock_bytes(fd, perm, shared, errp);
2223b8cf1913SMax Reitz     if (result < 0) {
2224b857431dSFam Zheng         error_append_hint(errp,
2225b857431dSFam Zheng                           "Is another process using the image [%s]?\n",
2226b857431dSFam Zheng                           file_opts->filename);
22277c20c808SMax Reitz         goto out_unlock;
2228b8cf1913SMax Reitz     }
2229b8cf1913SMax Reitz 
2230b8cf1913SMax Reitz     /* Clear the file by truncating it to 0 */
223193f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2232b8cf1913SMax Reitz     if (result < 0) {
22337c20c808SMax Reitz         goto out_unlock;
2234b8cf1913SMax Reitz     }
2235b8cf1913SMax Reitz 
2236927f11e1SKevin Wolf     if (file_opts->nocow) {
2237c1bb86cdSEric Blake #ifdef __linux__
2238c1bb86cdSEric Blake         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2239c1bb86cdSEric Blake          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2240c1bb86cdSEric Blake          * will be ignored since any failure of this operation should not
2241c1bb86cdSEric Blake          * block the left work.
2242c1bb86cdSEric Blake          */
2243c1bb86cdSEric Blake         int attr;
2244c1bb86cdSEric Blake         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2245c1bb86cdSEric Blake             attr |= FS_NOCOW_FL;
2246c1bb86cdSEric Blake             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2247c1bb86cdSEric Blake         }
2248c1bb86cdSEric Blake #endif
2249c1bb86cdSEric Blake     }
2250c1bb86cdSEric Blake 
2251b8cf1913SMax Reitz     /* Resize and potentially preallocate the file to the desired
2252b8cf1913SMax Reitz      * final size */
225393f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, file_opts->size,
225493f4e2ffSKevin Wolf                                   file_opts->preallocation, errp);
22559f63b07eSMax Reitz     if (result < 0) {
22567c20c808SMax Reitz         goto out_unlock;
22577c20c808SMax Reitz     }
22587c20c808SMax Reitz 
22597c20c808SMax Reitz out_unlock:
22607c20c808SMax Reitz     raw_apply_lock_bytes(fd, 0, 0, true, &local_err);
22617c20c808SMax Reitz     if (local_err) {
22627c20c808SMax Reitz         /* The above call should not fail, and if it does, that does
22637c20c808SMax Reitz          * not mean the whole creation operation has failed.  So
22647c20c808SMax Reitz          * report it the user for their convenience, but do not report
22657c20c808SMax Reitz          * it to the caller. */
22667c20c808SMax Reitz         error_report_err(local_err);
22675a1dad9dSNir Soffer     }
22685a1dad9dSNir Soffer 
22695a1dad9dSNir Soffer out_close:
2270c1bb86cdSEric Blake     if (qemu_close(fd) != 0 && result == 0) {
2271c1bb86cdSEric Blake         result = -errno;
2272c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not close the new file");
2273c1bb86cdSEric Blake     }
2274c1bb86cdSEric Blake out:
2275c1bb86cdSEric Blake     return result;
2276c1bb86cdSEric Blake }
2277c1bb86cdSEric Blake 
2278927f11e1SKevin Wolf static int coroutine_fn raw_co_create_opts(const char *filename, QemuOpts *opts,
2279927f11e1SKevin Wolf                                            Error **errp)
2280927f11e1SKevin Wolf {
2281927f11e1SKevin Wolf     BlockdevCreateOptions options;
2282927f11e1SKevin Wolf     int64_t total_size = 0;
2283927f11e1SKevin Wolf     bool nocow = false;
2284927f11e1SKevin Wolf     PreallocMode prealloc;
2285927f11e1SKevin Wolf     char *buf = NULL;
2286927f11e1SKevin Wolf     Error *local_err = NULL;
2287927f11e1SKevin Wolf 
2288927f11e1SKevin Wolf     /* Skip file: protocol prefix */
2289927f11e1SKevin Wolf     strstart(filename, "file:", &filename);
2290927f11e1SKevin Wolf 
2291927f11e1SKevin Wolf     /* Read out options */
2292927f11e1SKevin Wolf     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2293927f11e1SKevin Wolf                           BDRV_SECTOR_SIZE);
2294927f11e1SKevin Wolf     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2295927f11e1SKevin Wolf     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2296927f11e1SKevin Wolf     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2297927f11e1SKevin Wolf                                PREALLOC_MODE_OFF, &local_err);
2298927f11e1SKevin Wolf     g_free(buf);
2299927f11e1SKevin Wolf     if (local_err) {
2300927f11e1SKevin Wolf         error_propagate(errp, local_err);
2301927f11e1SKevin Wolf         return -EINVAL;
2302927f11e1SKevin Wolf     }
2303927f11e1SKevin Wolf 
2304927f11e1SKevin Wolf     options = (BlockdevCreateOptions) {
2305927f11e1SKevin Wolf         .driver     = BLOCKDEV_DRIVER_FILE,
2306927f11e1SKevin Wolf         .u.file     = {
2307927f11e1SKevin Wolf             .filename           = (char *) filename,
2308927f11e1SKevin Wolf             .size               = total_size,
2309927f11e1SKevin Wolf             .has_preallocation  = true,
2310927f11e1SKevin Wolf             .preallocation      = prealloc,
2311927f11e1SKevin Wolf             .has_nocow          = true,
2312927f11e1SKevin Wolf             .nocow              = nocow,
2313927f11e1SKevin Wolf         },
2314927f11e1SKevin Wolf     };
2315927f11e1SKevin Wolf     return raw_co_create(&options, errp);
2316927f11e1SKevin Wolf }
2317927f11e1SKevin Wolf 
2318c1bb86cdSEric Blake /*
2319c1bb86cdSEric Blake  * Find allocation range in @bs around offset @start.
2320c1bb86cdSEric Blake  * May change underlying file descriptor's file offset.
2321c1bb86cdSEric Blake  * If @start is not in a hole, store @start in @data, and the
2322c1bb86cdSEric Blake  * beginning of the next hole in @hole, and return 0.
2323c1bb86cdSEric Blake  * If @start is in a non-trailing hole, store @start in @hole and the
2324c1bb86cdSEric Blake  * beginning of the next non-hole in @data, and return 0.
2325c1bb86cdSEric Blake  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2326c1bb86cdSEric Blake  * If we can't find out, return a negative errno other than -ENXIO.
2327c1bb86cdSEric Blake  */
2328c1bb86cdSEric Blake static int find_allocation(BlockDriverState *bs, off_t start,
2329c1bb86cdSEric Blake                            off_t *data, off_t *hole)
2330c1bb86cdSEric Blake {
2331c1bb86cdSEric Blake #if defined SEEK_HOLE && defined SEEK_DATA
2332c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2333c1bb86cdSEric Blake     off_t offs;
2334c1bb86cdSEric Blake 
2335c1bb86cdSEric Blake     /*
2336c1bb86cdSEric Blake      * SEEK_DATA cases:
2337c1bb86cdSEric Blake      * D1. offs == start: start is in data
2338c1bb86cdSEric Blake      * D2. offs > start: start is in a hole, next data at offs
2339c1bb86cdSEric Blake      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2340c1bb86cdSEric Blake      *                              or start is beyond EOF
2341c1bb86cdSEric Blake      *     If the latter happens, the file has been truncated behind
2342c1bb86cdSEric Blake      *     our back since we opened it.  All bets are off then.
2343c1bb86cdSEric Blake      *     Treating like a trailing hole is simplest.
2344c1bb86cdSEric Blake      * D4. offs < 0, errno != ENXIO: we learned nothing
2345c1bb86cdSEric Blake      */
2346c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_DATA);
2347c1bb86cdSEric Blake     if (offs < 0) {
2348c1bb86cdSEric Blake         return -errno;          /* D3 or D4 */
2349c1bb86cdSEric Blake     }
2350a03083a0SJeff Cody 
2351a03083a0SJeff Cody     if (offs < start) {
2352a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2353a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like D4. */
2354a03083a0SJeff Cody         return -EIO;
2355a03083a0SJeff Cody     }
2356c1bb86cdSEric Blake 
2357c1bb86cdSEric Blake     if (offs > start) {
2358c1bb86cdSEric Blake         /* D2: in hole, next data at offs */
2359c1bb86cdSEric Blake         *hole = start;
2360c1bb86cdSEric Blake         *data = offs;
2361c1bb86cdSEric Blake         return 0;
2362c1bb86cdSEric Blake     }
2363c1bb86cdSEric Blake 
2364c1bb86cdSEric Blake     /* D1: in data, end not yet known */
2365c1bb86cdSEric Blake 
2366c1bb86cdSEric Blake     /*
2367c1bb86cdSEric Blake      * SEEK_HOLE cases:
2368c1bb86cdSEric Blake      * H1. offs == start: start is in a hole
2369c1bb86cdSEric Blake      *     If this happens here, a hole has been dug behind our back
2370c1bb86cdSEric Blake      *     since the previous lseek().
2371c1bb86cdSEric Blake      * H2. offs > start: either start is in data, next hole at offs,
2372c1bb86cdSEric Blake      *                   or start is in trailing hole, EOF at offs
2373c1bb86cdSEric Blake      *     Linux treats trailing holes like any other hole: offs ==
2374c1bb86cdSEric Blake      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2375c1bb86cdSEric Blake      *     If that happens here, a hole has been dug behind our back
2376c1bb86cdSEric Blake      *     since the previous lseek().
2377c1bb86cdSEric Blake      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2378c1bb86cdSEric Blake      *     If this happens, the file has been truncated behind our
2379c1bb86cdSEric Blake      *     back since we opened it.  Treat it like a trailing hole.
2380c1bb86cdSEric Blake      * H4. offs < 0, errno != ENXIO: we learned nothing
2381c1bb86cdSEric Blake      *     Pretend we know nothing at all, i.e. "forget" about D1.
2382c1bb86cdSEric Blake      */
2383c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_HOLE);
2384c1bb86cdSEric Blake     if (offs < 0) {
2385c1bb86cdSEric Blake         return -errno;          /* D1 and (H3 or H4) */
2386c1bb86cdSEric Blake     }
2387a03083a0SJeff Cody 
2388a03083a0SJeff Cody     if (offs < start) {
2389a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2390a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like H4. */
2391a03083a0SJeff Cody         return -EIO;
2392a03083a0SJeff Cody     }
2393c1bb86cdSEric Blake 
2394c1bb86cdSEric Blake     if (offs > start) {
2395c1bb86cdSEric Blake         /*
2396c1bb86cdSEric Blake          * D1 and H2: either in data, next hole at offs, or it was in
2397c1bb86cdSEric Blake          * data but is now in a trailing hole.  In the latter case,
2398c1bb86cdSEric Blake          * all bets are off.  Treating it as if it there was data all
2399c1bb86cdSEric Blake          * the way to EOF is safe, so simply do that.
2400c1bb86cdSEric Blake          */
2401c1bb86cdSEric Blake         *data = start;
2402c1bb86cdSEric Blake         *hole = offs;
2403c1bb86cdSEric Blake         return 0;
2404c1bb86cdSEric Blake     }
2405c1bb86cdSEric Blake 
2406c1bb86cdSEric Blake     /* D1 and H1 */
2407c1bb86cdSEric Blake     return -EBUSY;
2408c1bb86cdSEric Blake #else
2409c1bb86cdSEric Blake     return -ENOTSUP;
2410c1bb86cdSEric Blake #endif
2411c1bb86cdSEric Blake }
2412c1bb86cdSEric Blake 
2413c1bb86cdSEric Blake /*
2414a290f085SEric Blake  * Returns the allocation status of the specified offset.
2415c1bb86cdSEric Blake  *
2416a290f085SEric Blake  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2417c1bb86cdSEric Blake  *
2418a290f085SEric Blake  * 'pnum' is set to the number of bytes (including and immediately following
2419a290f085SEric Blake  * the specified offset) that are known to be in the same
2420c1bb86cdSEric Blake  * allocated/unallocated state.
2421c1bb86cdSEric Blake  *
2422a290f085SEric Blake  * 'bytes' is the max value 'pnum' should be set to.
2423c1bb86cdSEric Blake  */
2424a290f085SEric Blake static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2425a290f085SEric Blake                                             bool want_zero,
2426a290f085SEric Blake                                             int64_t offset,
2427a290f085SEric Blake                                             int64_t bytes, int64_t *pnum,
2428a290f085SEric Blake                                             int64_t *map,
2429c1bb86cdSEric Blake                                             BlockDriverState **file)
2430c1bb86cdSEric Blake {
2431a290f085SEric Blake     off_t data = 0, hole = 0;
2432c1bb86cdSEric Blake     int ret;
2433c1bb86cdSEric Blake 
2434c1bb86cdSEric Blake     ret = fd_open(bs);
2435c1bb86cdSEric Blake     if (ret < 0) {
2436c1bb86cdSEric Blake         return ret;
2437c1bb86cdSEric Blake     }
2438c1bb86cdSEric Blake 
2439a290f085SEric Blake     if (!want_zero) {
2440a290f085SEric Blake         *pnum = bytes;
2441a290f085SEric Blake         *map = offset;
2442a290f085SEric Blake         *file = bs;
2443a290f085SEric Blake         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2444c1bb86cdSEric Blake     }
2445c1bb86cdSEric Blake 
2446a290f085SEric Blake     ret = find_allocation(bs, offset, &data, &hole);
2447c1bb86cdSEric Blake     if (ret == -ENXIO) {
2448c1bb86cdSEric Blake         /* Trailing hole */
2449a290f085SEric Blake         *pnum = bytes;
2450c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2451c1bb86cdSEric Blake     } else if (ret < 0) {
2452c1bb86cdSEric Blake         /* No info available, so pretend there are no holes */
2453a290f085SEric Blake         *pnum = bytes;
2454c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2455a290f085SEric Blake     } else if (data == offset) {
2456a290f085SEric Blake         /* On a data extent, compute bytes to the end of the extent,
2457c1bb86cdSEric Blake          * possibly including a partial sector at EOF. */
2458a290f085SEric Blake         *pnum = MIN(bytes, hole - offset);
2459c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2460c1bb86cdSEric Blake     } else {
2461a290f085SEric Blake         /* On a hole, compute bytes to the beginning of the next extent.  */
2462a290f085SEric Blake         assert(hole == offset);
2463a290f085SEric Blake         *pnum = MIN(bytes, data - offset);
2464c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2465c1bb86cdSEric Blake     }
2466a290f085SEric Blake     *map = offset;
2467c1bb86cdSEric Blake     *file = bs;
2468a290f085SEric Blake     return ret | BDRV_BLOCK_OFFSET_VALID;
2469c1bb86cdSEric Blake }
2470c1bb86cdSEric Blake 
247131be8a2aSStefan Hajnoczi #if defined(__linux__)
247231be8a2aSStefan Hajnoczi /* Verify that the file is not in the page cache */
247331be8a2aSStefan Hajnoczi static void check_cache_dropped(BlockDriverState *bs, Error **errp)
247431be8a2aSStefan Hajnoczi {
247531be8a2aSStefan Hajnoczi     const size_t window_size = 128 * 1024 * 1024;
247631be8a2aSStefan Hajnoczi     BDRVRawState *s = bs->opaque;
247731be8a2aSStefan Hajnoczi     void *window = NULL;
247831be8a2aSStefan Hajnoczi     size_t length = 0;
247931be8a2aSStefan Hajnoczi     unsigned char *vec;
248031be8a2aSStefan Hajnoczi     size_t page_size;
248131be8a2aSStefan Hajnoczi     off_t offset;
248231be8a2aSStefan Hajnoczi     off_t end;
248331be8a2aSStefan Hajnoczi 
248431be8a2aSStefan Hajnoczi     /* mincore(2) page status information requires 1 byte per page */
248531be8a2aSStefan Hajnoczi     page_size = sysconf(_SC_PAGESIZE);
248631be8a2aSStefan Hajnoczi     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
248731be8a2aSStefan Hajnoczi 
248831be8a2aSStefan Hajnoczi     end = raw_getlength(bs);
248931be8a2aSStefan Hajnoczi 
249031be8a2aSStefan Hajnoczi     for (offset = 0; offset < end; offset += window_size) {
249131be8a2aSStefan Hajnoczi         void *new_window;
249231be8a2aSStefan Hajnoczi         size_t new_length;
249331be8a2aSStefan Hajnoczi         size_t vec_end;
249431be8a2aSStefan Hajnoczi         size_t i;
249531be8a2aSStefan Hajnoczi         int ret;
249631be8a2aSStefan Hajnoczi 
249731be8a2aSStefan Hajnoczi         /* Unmap previous window if size has changed */
249831be8a2aSStefan Hajnoczi         new_length = MIN(end - offset, window_size);
249931be8a2aSStefan Hajnoczi         if (new_length != length) {
250031be8a2aSStefan Hajnoczi             munmap(window, length);
250131be8a2aSStefan Hajnoczi             window = NULL;
250231be8a2aSStefan Hajnoczi             length = 0;
250331be8a2aSStefan Hajnoczi         }
250431be8a2aSStefan Hajnoczi 
250531be8a2aSStefan Hajnoczi         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
250631be8a2aSStefan Hajnoczi                           s->fd, offset);
250731be8a2aSStefan Hajnoczi         if (new_window == MAP_FAILED) {
250831be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mmap failed");
250931be8a2aSStefan Hajnoczi             break;
251031be8a2aSStefan Hajnoczi         }
251131be8a2aSStefan Hajnoczi 
251231be8a2aSStefan Hajnoczi         window = new_window;
251331be8a2aSStefan Hajnoczi         length = new_length;
251431be8a2aSStefan Hajnoczi 
251531be8a2aSStefan Hajnoczi         ret = mincore(window, length, vec);
251631be8a2aSStefan Hajnoczi         if (ret < 0) {
251731be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mincore failed");
251831be8a2aSStefan Hajnoczi             break;
251931be8a2aSStefan Hajnoczi         }
252031be8a2aSStefan Hajnoczi 
252131be8a2aSStefan Hajnoczi         vec_end = DIV_ROUND_UP(length, page_size);
252231be8a2aSStefan Hajnoczi         for (i = 0; i < vec_end; i++) {
252331be8a2aSStefan Hajnoczi             if (vec[i] & 0x1) {
252431be8a2aSStefan Hajnoczi                 error_setg(errp, "page cache still in use!");
252531be8a2aSStefan Hajnoczi                 break;
252631be8a2aSStefan Hajnoczi             }
252731be8a2aSStefan Hajnoczi         }
252831be8a2aSStefan Hajnoczi     }
252931be8a2aSStefan Hajnoczi 
253031be8a2aSStefan Hajnoczi     if (window) {
253131be8a2aSStefan Hajnoczi         munmap(window, length);
253231be8a2aSStefan Hajnoczi     }
253331be8a2aSStefan Hajnoczi 
253431be8a2aSStefan Hajnoczi     g_free(vec);
253531be8a2aSStefan Hajnoczi }
253631be8a2aSStefan Hajnoczi #endif /* __linux__ */
253731be8a2aSStefan Hajnoczi 
2538dd577a26SStefan Hajnoczi static void coroutine_fn raw_co_invalidate_cache(BlockDriverState *bs,
2539dd577a26SStefan Hajnoczi                                                  Error **errp)
2540dd577a26SStefan Hajnoczi {
2541dd577a26SStefan Hajnoczi     BDRVRawState *s = bs->opaque;
2542dd577a26SStefan Hajnoczi     int ret;
2543dd577a26SStefan Hajnoczi 
2544dd577a26SStefan Hajnoczi     ret = fd_open(bs);
2545dd577a26SStefan Hajnoczi     if (ret < 0) {
2546dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "The file descriptor is not open");
2547dd577a26SStefan Hajnoczi         return;
2548dd577a26SStefan Hajnoczi     }
2549dd577a26SStefan Hajnoczi 
2550dd577a26SStefan Hajnoczi     if (s->open_flags & O_DIRECT) {
2551dd577a26SStefan Hajnoczi         return; /* No host kernel page cache */
2552dd577a26SStefan Hajnoczi     }
2553dd577a26SStefan Hajnoczi 
2554dd577a26SStefan Hajnoczi #if defined(__linux__)
2555dd577a26SStefan Hajnoczi     /* This sets the scene for the next syscall... */
2556dd577a26SStefan Hajnoczi     ret = bdrv_co_flush(bs);
2557dd577a26SStefan Hajnoczi     if (ret < 0) {
2558dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "flush failed");
2559dd577a26SStefan Hajnoczi         return;
2560dd577a26SStefan Hajnoczi     }
2561dd577a26SStefan Hajnoczi 
2562dd577a26SStefan Hajnoczi     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2563dd577a26SStefan Hajnoczi      * process.  These limitations are okay because we just fsynced the file,
2564dd577a26SStefan Hajnoczi      * we don't use mmap, and the file should not be in use by other processes.
2565dd577a26SStefan Hajnoczi      */
2566dd577a26SStefan Hajnoczi     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2567dd577a26SStefan Hajnoczi     if (ret != 0) { /* the return value is a positive errno */
2568dd577a26SStefan Hajnoczi         error_setg_errno(errp, ret, "fadvise failed");
2569dd577a26SStefan Hajnoczi         return;
2570dd577a26SStefan Hajnoczi     }
257131be8a2aSStefan Hajnoczi 
257231be8a2aSStefan Hajnoczi     if (s->check_cache_dropped) {
257331be8a2aSStefan Hajnoczi         check_cache_dropped(bs, errp);
257431be8a2aSStefan Hajnoczi     }
2575dd577a26SStefan Hajnoczi #else /* __linux__ */
2576dd577a26SStefan Hajnoczi     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2577dd577a26SStefan Hajnoczi      * unsupported on other host operating systems.  Cache consistency issues
2578dd577a26SStefan Hajnoczi      * may occur but no error is reported here, partly because that's the
2579dd577a26SStefan Hajnoczi      * historical behavior and partly because it's hard to differentiate valid
2580dd577a26SStefan Hajnoczi      * configurations that should not cause errors.
2581dd577a26SStefan Hajnoczi      */
2582dd577a26SStefan Hajnoczi #endif /* !__linux__ */
2583dd577a26SStefan Hajnoczi }
2584dd577a26SStefan Hajnoczi 
258533d70fb6SKevin Wolf static coroutine_fn int
258633d70fb6SKevin Wolf raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
2587c1bb86cdSEric Blake {
2588c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2589c1bb86cdSEric Blake 
259033d70fb6SKevin Wolf     return paio_submit_co(bs, s->fd, offset, NULL, bytes, QEMU_AIO_DISCARD);
2591c1bb86cdSEric Blake }
2592c1bb86cdSEric Blake 
2593c1bb86cdSEric Blake static int coroutine_fn raw_co_pwrite_zeroes(
2594c1bb86cdSEric Blake     BlockDriverState *bs, int64_t offset,
2595f5a5ca79SManos Pitsidianakis     int bytes, BdrvRequestFlags flags)
2596c1bb86cdSEric Blake {
2597c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
259834fa110eSKevin Wolf     int operation = QEMU_AIO_WRITE_ZEROES;
2599c1bb86cdSEric Blake 
260034fa110eSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
260134fa110eSKevin Wolf         operation |= QEMU_AIO_DISCARD;
2602c1bb86cdSEric Blake     }
260334fa110eSKevin Wolf 
260434fa110eSKevin Wolf     return paio_submit_co(bs, s->fd, offset, NULL, bytes, operation);
2605c1bb86cdSEric Blake }
2606c1bb86cdSEric Blake 
2607c1bb86cdSEric Blake static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2608c1bb86cdSEric Blake {
2609c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2610c1bb86cdSEric Blake 
2611c1bb86cdSEric Blake     bdi->unallocated_blocks_are_zero = s->discard_zeroes;
2612c1bb86cdSEric Blake     return 0;
2613c1bb86cdSEric Blake }
2614c1bb86cdSEric Blake 
2615c1bb86cdSEric Blake static QemuOptsList raw_create_opts = {
2616c1bb86cdSEric Blake     .name = "raw-create-opts",
2617c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2618c1bb86cdSEric Blake     .desc = {
2619c1bb86cdSEric Blake         {
2620c1bb86cdSEric Blake             .name = BLOCK_OPT_SIZE,
2621c1bb86cdSEric Blake             .type = QEMU_OPT_SIZE,
2622c1bb86cdSEric Blake             .help = "Virtual disk size"
2623c1bb86cdSEric Blake         },
2624c1bb86cdSEric Blake         {
2625c1bb86cdSEric Blake             .name = BLOCK_OPT_NOCOW,
2626c1bb86cdSEric Blake             .type = QEMU_OPT_BOOL,
2627c1bb86cdSEric Blake             .help = "Turn off copy-on-write (valid only on btrfs)"
2628c1bb86cdSEric Blake         },
2629c1bb86cdSEric Blake         {
2630c1bb86cdSEric Blake             .name = BLOCK_OPT_PREALLOC,
2631c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
2632c1bb86cdSEric Blake             .help = "Preallocation mode (allowed values: off, falloc, full)"
2633c1bb86cdSEric Blake         },
2634c1bb86cdSEric Blake         { /* end of list */ }
2635c1bb86cdSEric Blake     }
2636c1bb86cdSEric Blake };
2637c1bb86cdSEric Blake 
2638244a5668SFam Zheng static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2639244a5668SFam Zheng                           Error **errp)
2640244a5668SFam Zheng {
2641244a5668SFam Zheng     return raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
2642244a5668SFam Zheng }
2643244a5668SFam Zheng 
2644244a5668SFam Zheng static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
2645244a5668SFam Zheng {
2646244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
2647244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
2648244a5668SFam Zheng     s->perm = perm;
2649244a5668SFam Zheng     s->shared_perm = shared;
2650244a5668SFam Zheng }
2651244a5668SFam Zheng 
2652244a5668SFam Zheng static void raw_abort_perm_update(BlockDriverState *bs)
2653244a5668SFam Zheng {
2654244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
2655244a5668SFam Zheng }
2656244a5668SFam Zheng 
265767b51fb9SVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_copy_range_from(
265867b51fb9SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, BdrvChild *src, uint64_t src_offset,
265967b51fb9SVladimir Sementsov-Ogievskiy         BdrvChild *dst, uint64_t dst_offset, uint64_t bytes,
266067b51fb9SVladimir Sementsov-Ogievskiy         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
26611efad060SFam Zheng {
266267b51fb9SVladimir Sementsov-Ogievskiy     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
266367b51fb9SVladimir Sementsov-Ogievskiy                                  read_flags, write_flags);
26641efad060SFam Zheng }
26651efad060SFam Zheng 
26661efad060SFam Zheng static int coroutine_fn raw_co_copy_range_to(BlockDriverState *bs,
266767b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *src,
266867b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t src_offset,
266967b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *dst,
267067b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t dst_offset,
267167b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t bytes,
267267b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags read_flags,
267367b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags write_flags)
26741efad060SFam Zheng {
26751efad060SFam Zheng     BDRVRawState *s = bs->opaque;
26761efad060SFam Zheng     BDRVRawState *src_s;
26771efad060SFam Zheng 
26781efad060SFam Zheng     assert(dst->bs == bs);
26791efad060SFam Zheng     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
26801efad060SFam Zheng         return -ENOTSUP;
26811efad060SFam Zheng     }
26821efad060SFam Zheng 
26831efad060SFam Zheng     src_s = src->bs->opaque;
26849f850f67SFam Zheng     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
26851efad060SFam Zheng         return -EIO;
26861efad060SFam Zheng     }
26871efad060SFam Zheng     return paio_submit_co_full(bs, src_s->fd, src_offset, s->fd, dst_offset,
26881efad060SFam Zheng                                NULL, bytes, QEMU_AIO_COPY_RANGE);
26891efad060SFam Zheng }
26901efad060SFam Zheng 
2691c1bb86cdSEric Blake BlockDriver bdrv_file = {
2692c1bb86cdSEric Blake     .format_name = "file",
2693c1bb86cdSEric Blake     .protocol_name = "file",
2694c1bb86cdSEric Blake     .instance_size = sizeof(BDRVRawState),
2695c1bb86cdSEric Blake     .bdrv_needs_filename = true,
2696c1bb86cdSEric Blake     .bdrv_probe = NULL, /* no probe for protocols */
2697c1bb86cdSEric Blake     .bdrv_parse_filename = raw_parse_filename,
2698c1bb86cdSEric Blake     .bdrv_file_open = raw_open,
2699c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
2700c1bb86cdSEric Blake     .bdrv_reopen_commit = raw_reopen_commit,
2701c1bb86cdSEric Blake     .bdrv_reopen_abort = raw_reopen_abort,
2702c1bb86cdSEric Blake     .bdrv_close = raw_close,
2703927f11e1SKevin Wolf     .bdrv_co_create = raw_co_create,
2704efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = raw_co_create_opts,
2705c1bb86cdSEric Blake     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2706a290f085SEric Blake     .bdrv_co_block_status = raw_co_block_status,
2707dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
2708c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
2709c1bb86cdSEric Blake 
2710c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
2711c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
271233d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
271333d70fb6SKevin Wolf     .bdrv_co_pdiscard       = raw_co_pdiscard,
27141efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
27151efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
2716c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
2717c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
2718c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
2719ed6e2161SNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
2720c1bb86cdSEric Blake 
2721061ca8a3SKevin Wolf     .bdrv_co_truncate = raw_co_truncate,
2722c1bb86cdSEric Blake     .bdrv_getlength = raw_getlength,
2723c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
2724c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
2725c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
2726244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
2727244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
2728244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
2729c1bb86cdSEric Blake     .create_opts = &raw_create_opts,
2730c1bb86cdSEric Blake };
2731c1bb86cdSEric Blake 
2732c1bb86cdSEric Blake /***********************************************/
2733c1bb86cdSEric Blake /* host device */
2734c1bb86cdSEric Blake 
2735c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
2736c1bb86cdSEric Blake static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2737c1bb86cdSEric Blake                                 CFIndex maxPathSize, int flags);
2738c1bb86cdSEric Blake static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
2739c1bb86cdSEric Blake {
2740c1bb86cdSEric Blake     kern_return_t kernResult = KERN_FAILURE;
2741c1bb86cdSEric Blake     mach_port_t     masterPort;
2742c1bb86cdSEric Blake     CFMutableDictionaryRef  classesToMatch;
2743c1bb86cdSEric Blake     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
2744c1bb86cdSEric Blake     char *mediaType = NULL;
2745c1bb86cdSEric Blake 
2746c1bb86cdSEric Blake     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
2747c1bb86cdSEric Blake     if ( KERN_SUCCESS != kernResult ) {
2748c1bb86cdSEric Blake         printf( "IOMasterPort returned %d\n", kernResult );
2749c1bb86cdSEric Blake     }
2750c1bb86cdSEric Blake 
2751c1bb86cdSEric Blake     int index;
2752c1bb86cdSEric Blake     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
2753c1bb86cdSEric Blake         classesToMatch = IOServiceMatching(matching_array[index]);
2754c1bb86cdSEric Blake         if (classesToMatch == NULL) {
2755c1bb86cdSEric Blake             error_report("IOServiceMatching returned NULL for %s",
2756c1bb86cdSEric Blake                          matching_array[index]);
2757c1bb86cdSEric Blake             continue;
2758c1bb86cdSEric Blake         }
2759c1bb86cdSEric Blake         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
2760c1bb86cdSEric Blake                              kCFBooleanTrue);
2761c1bb86cdSEric Blake         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
2762c1bb86cdSEric Blake                                                   mediaIterator);
2763c1bb86cdSEric Blake         if (kernResult != KERN_SUCCESS) {
2764c1bb86cdSEric Blake             error_report("Note: IOServiceGetMatchingServices returned %d",
2765c1bb86cdSEric Blake                          kernResult);
2766c1bb86cdSEric Blake             continue;
2767c1bb86cdSEric Blake         }
2768c1bb86cdSEric Blake 
2769c1bb86cdSEric Blake         /* If a match was found, leave the loop */
2770c1bb86cdSEric Blake         if (*mediaIterator != 0) {
2771c1bb86cdSEric Blake             DPRINTF("Matching using %s\n", matching_array[index]);
2772c1bb86cdSEric Blake             mediaType = g_strdup(matching_array[index]);
2773c1bb86cdSEric Blake             break;
2774c1bb86cdSEric Blake         }
2775c1bb86cdSEric Blake     }
2776c1bb86cdSEric Blake     return mediaType;
2777c1bb86cdSEric Blake }
2778c1bb86cdSEric Blake 
2779c1bb86cdSEric Blake kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2780c1bb86cdSEric Blake                          CFIndex maxPathSize, int flags)
2781c1bb86cdSEric Blake {
2782c1bb86cdSEric Blake     io_object_t     nextMedia;
2783c1bb86cdSEric Blake     kern_return_t   kernResult = KERN_FAILURE;
2784c1bb86cdSEric Blake     *bsdPath = '\0';
2785c1bb86cdSEric Blake     nextMedia = IOIteratorNext( mediaIterator );
2786c1bb86cdSEric Blake     if ( nextMedia )
2787c1bb86cdSEric Blake     {
2788c1bb86cdSEric Blake         CFTypeRef   bsdPathAsCFString;
2789c1bb86cdSEric Blake     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2790c1bb86cdSEric Blake         if ( bsdPathAsCFString ) {
2791c1bb86cdSEric Blake             size_t devPathLength;
2792c1bb86cdSEric Blake             strcpy( bsdPath, _PATH_DEV );
2793c1bb86cdSEric Blake             if (flags & BDRV_O_NOCACHE) {
2794c1bb86cdSEric Blake                 strcat(bsdPath, "r");
2795c1bb86cdSEric Blake             }
2796c1bb86cdSEric Blake             devPathLength = strlen( bsdPath );
2797c1bb86cdSEric Blake             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2798c1bb86cdSEric Blake                 kernResult = KERN_SUCCESS;
2799c1bb86cdSEric Blake             }
2800c1bb86cdSEric Blake             CFRelease( bsdPathAsCFString );
2801c1bb86cdSEric Blake         }
2802c1bb86cdSEric Blake         IOObjectRelease( nextMedia );
2803c1bb86cdSEric Blake     }
2804c1bb86cdSEric Blake 
2805c1bb86cdSEric Blake     return kernResult;
2806c1bb86cdSEric Blake }
2807c1bb86cdSEric Blake 
2808c1bb86cdSEric Blake /* Sets up a real cdrom for use in QEMU */
2809c1bb86cdSEric Blake static bool setup_cdrom(char *bsd_path, Error **errp)
2810c1bb86cdSEric Blake {
2811c1bb86cdSEric Blake     int index, num_of_test_partitions = 2, fd;
2812c1bb86cdSEric Blake     char test_partition[MAXPATHLEN];
2813c1bb86cdSEric Blake     bool partition_found = false;
2814c1bb86cdSEric Blake 
2815c1bb86cdSEric Blake     /* look for a working partition */
2816c1bb86cdSEric Blake     for (index = 0; index < num_of_test_partitions; index++) {
2817c1bb86cdSEric Blake         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
2818c1bb86cdSEric Blake                  index);
2819c1bb86cdSEric Blake         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
2820c1bb86cdSEric Blake         if (fd >= 0) {
2821c1bb86cdSEric Blake             partition_found = true;
2822c1bb86cdSEric Blake             qemu_close(fd);
2823c1bb86cdSEric Blake             break;
2824c1bb86cdSEric Blake         }
2825c1bb86cdSEric Blake     }
2826c1bb86cdSEric Blake 
2827c1bb86cdSEric Blake     /* if a working partition on the device was not found */
2828c1bb86cdSEric Blake     if (partition_found == false) {
2829c1bb86cdSEric Blake         error_setg(errp, "Failed to find a working partition on disc");
2830c1bb86cdSEric Blake     } else {
2831c1bb86cdSEric Blake         DPRINTF("Using %s as optical disc\n", test_partition);
2832c1bb86cdSEric Blake         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
2833c1bb86cdSEric Blake     }
2834c1bb86cdSEric Blake     return partition_found;
2835c1bb86cdSEric Blake }
2836c1bb86cdSEric Blake 
2837c1bb86cdSEric Blake /* Prints directions on mounting and unmounting a device */
2838c1bb86cdSEric Blake static void print_unmounting_directions(const char *file_name)
2839c1bb86cdSEric Blake {
2840c1bb86cdSEric Blake     error_report("If device %s is mounted on the desktop, unmount"
2841c1bb86cdSEric Blake                  " it first before using it in QEMU", file_name);
2842c1bb86cdSEric Blake     error_report("Command to unmount device: diskutil unmountDisk %s",
2843c1bb86cdSEric Blake                  file_name);
2844c1bb86cdSEric Blake     error_report("Command to mount device: diskutil mountDisk %s", file_name);
2845c1bb86cdSEric Blake }
2846c1bb86cdSEric Blake 
2847c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
2848c1bb86cdSEric Blake 
2849c1bb86cdSEric Blake static int hdev_probe_device(const char *filename)
2850c1bb86cdSEric Blake {
2851c1bb86cdSEric Blake     struct stat st;
2852c1bb86cdSEric Blake 
2853c1bb86cdSEric Blake     /* allow a dedicated CD-ROM driver to match with a higher priority */
2854c1bb86cdSEric Blake     if (strstart(filename, "/dev/cdrom", NULL))
2855c1bb86cdSEric Blake         return 50;
2856c1bb86cdSEric Blake 
2857c1bb86cdSEric Blake     if (stat(filename, &st) >= 0 &&
2858c1bb86cdSEric Blake             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2859c1bb86cdSEric Blake         return 100;
2860c1bb86cdSEric Blake     }
2861c1bb86cdSEric Blake 
2862c1bb86cdSEric Blake     return 0;
2863c1bb86cdSEric Blake }
2864c1bb86cdSEric Blake 
2865c1bb86cdSEric Blake static int check_hdev_writable(BDRVRawState *s)
2866c1bb86cdSEric Blake {
2867c1bb86cdSEric Blake #if defined(BLKROGET)
2868c1bb86cdSEric Blake     /* Linux block devices can be configured "read-only" using blockdev(8).
2869c1bb86cdSEric Blake      * This is independent of device node permissions and therefore open(2)
2870c1bb86cdSEric Blake      * with O_RDWR succeeds.  Actual writes fail with EPERM.
2871c1bb86cdSEric Blake      *
2872c1bb86cdSEric Blake      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
2873c1bb86cdSEric Blake      * check for read-only block devices so that Linux block devices behave
2874c1bb86cdSEric Blake      * properly.
2875c1bb86cdSEric Blake      */
2876c1bb86cdSEric Blake     struct stat st;
2877c1bb86cdSEric Blake     int readonly = 0;
2878c1bb86cdSEric Blake 
2879c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
2880c1bb86cdSEric Blake         return -errno;
2881c1bb86cdSEric Blake     }
2882c1bb86cdSEric Blake 
2883c1bb86cdSEric Blake     if (!S_ISBLK(st.st_mode)) {
2884c1bb86cdSEric Blake         return 0;
2885c1bb86cdSEric Blake     }
2886c1bb86cdSEric Blake 
2887c1bb86cdSEric Blake     if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2888c1bb86cdSEric Blake         return -errno;
2889c1bb86cdSEric Blake     }
2890c1bb86cdSEric Blake 
2891c1bb86cdSEric Blake     if (readonly) {
2892c1bb86cdSEric Blake         return -EACCES;
2893c1bb86cdSEric Blake     }
2894c1bb86cdSEric Blake #endif /* defined(BLKROGET) */
2895c1bb86cdSEric Blake     return 0;
2896c1bb86cdSEric Blake }
2897c1bb86cdSEric Blake 
2898c1bb86cdSEric Blake static void hdev_parse_filename(const char *filename, QDict *options,
2899c1bb86cdSEric Blake                                 Error **errp)
2900c1bb86cdSEric Blake {
290103c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
2902c1bb86cdSEric Blake }
2903c1bb86cdSEric Blake 
2904c1bb86cdSEric Blake static bool hdev_is_sg(BlockDriverState *bs)
2905c1bb86cdSEric Blake {
2906c1bb86cdSEric Blake 
2907c1bb86cdSEric Blake #if defined(__linux__)
2908c1bb86cdSEric Blake 
2909c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2910c1bb86cdSEric Blake     struct stat st;
2911c1bb86cdSEric Blake     struct sg_scsi_id scsiid;
2912c1bb86cdSEric Blake     int sg_version;
2913c1bb86cdSEric Blake     int ret;
2914c1bb86cdSEric Blake 
2915c1bb86cdSEric Blake     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
2916c1bb86cdSEric Blake         return false;
2917c1bb86cdSEric Blake     }
2918c1bb86cdSEric Blake 
2919c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
2920c1bb86cdSEric Blake     if (ret < 0) {
2921c1bb86cdSEric Blake         return false;
2922c1bb86cdSEric Blake     }
2923c1bb86cdSEric Blake 
2924c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
2925c1bb86cdSEric Blake     if (ret >= 0) {
2926c1bb86cdSEric Blake         DPRINTF("SG device found: type=%d, version=%d\n",
2927c1bb86cdSEric Blake             scsiid.scsi_type, sg_version);
2928c1bb86cdSEric Blake         return true;
2929c1bb86cdSEric Blake     }
2930c1bb86cdSEric Blake 
2931c1bb86cdSEric Blake #endif
2932c1bb86cdSEric Blake 
2933c1bb86cdSEric Blake     return false;
2934c1bb86cdSEric Blake }
2935c1bb86cdSEric Blake 
2936c1bb86cdSEric Blake static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2937c1bb86cdSEric Blake                      Error **errp)
2938c1bb86cdSEric Blake {
2939c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2940c1bb86cdSEric Blake     Error *local_err = NULL;
2941c1bb86cdSEric Blake     int ret;
2942c1bb86cdSEric Blake 
2943c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
2944129c7d1cSMarkus Armbruster     /*
2945129c7d1cSMarkus Armbruster      * Caution: while qdict_get_str() is fine, getting non-string types
2946129c7d1cSMarkus Armbruster      * would require more care.  When @options come from -blockdev or
2947129c7d1cSMarkus Armbruster      * blockdev_add, its members are typed according to the QAPI
2948129c7d1cSMarkus Armbruster      * schema, but when they come from -drive, they're all QString.
2949129c7d1cSMarkus Armbruster      */
2950c1bb86cdSEric Blake     const char *filename = qdict_get_str(options, "filename");
2951c1bb86cdSEric Blake     char bsd_path[MAXPATHLEN] = "";
2952c1bb86cdSEric Blake     bool error_occurred = false;
2953c1bb86cdSEric Blake 
2954c1bb86cdSEric Blake     /* If using a real cdrom */
2955c1bb86cdSEric Blake     if (strcmp(filename, "/dev/cdrom") == 0) {
2956c1bb86cdSEric Blake         char *mediaType = NULL;
2957c1bb86cdSEric Blake         kern_return_t ret_val;
2958c1bb86cdSEric Blake         io_iterator_t mediaIterator = 0;
2959c1bb86cdSEric Blake 
2960c1bb86cdSEric Blake         mediaType = FindEjectableOpticalMedia(&mediaIterator);
2961c1bb86cdSEric Blake         if (mediaType == NULL) {
2962c1bb86cdSEric Blake             error_setg(errp, "Please make sure your CD/DVD is in the optical"
2963c1bb86cdSEric Blake                        " drive");
2964c1bb86cdSEric Blake             error_occurred = true;
2965c1bb86cdSEric Blake             goto hdev_open_Mac_error;
2966c1bb86cdSEric Blake         }
2967c1bb86cdSEric Blake 
2968c1bb86cdSEric Blake         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
2969c1bb86cdSEric Blake         if (ret_val != KERN_SUCCESS) {
2970c1bb86cdSEric Blake             error_setg(errp, "Could not get BSD path for optical drive");
2971c1bb86cdSEric Blake             error_occurred = true;
2972c1bb86cdSEric Blake             goto hdev_open_Mac_error;
2973c1bb86cdSEric Blake         }
2974c1bb86cdSEric Blake 
2975c1bb86cdSEric Blake         /* If a real optical drive was not found */
2976c1bb86cdSEric Blake         if (bsd_path[0] == '\0') {
2977c1bb86cdSEric Blake             error_setg(errp, "Failed to obtain bsd path for optical drive");
2978c1bb86cdSEric Blake             error_occurred = true;
2979c1bb86cdSEric Blake             goto hdev_open_Mac_error;
2980c1bb86cdSEric Blake         }
2981c1bb86cdSEric Blake 
2982c1bb86cdSEric Blake         /* If using a cdrom disc and finding a partition on the disc failed */
2983c1bb86cdSEric Blake         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
2984c1bb86cdSEric Blake             setup_cdrom(bsd_path, errp) == false) {
2985c1bb86cdSEric Blake             print_unmounting_directions(bsd_path);
2986c1bb86cdSEric Blake             error_occurred = true;
2987c1bb86cdSEric Blake             goto hdev_open_Mac_error;
2988c1bb86cdSEric Blake         }
2989c1bb86cdSEric Blake 
299046f5ac20SEric Blake         qdict_put_str(options, "filename", bsd_path);
2991c1bb86cdSEric Blake 
2992c1bb86cdSEric Blake hdev_open_Mac_error:
2993c1bb86cdSEric Blake         g_free(mediaType);
2994c1bb86cdSEric Blake         if (mediaIterator) {
2995c1bb86cdSEric Blake             IOObjectRelease(mediaIterator);
2996c1bb86cdSEric Blake         }
2997c1bb86cdSEric Blake         if (error_occurred) {
2998c1bb86cdSEric Blake             return -ENOENT;
2999c1bb86cdSEric Blake         }
3000c1bb86cdSEric Blake     }
3001c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3002c1bb86cdSEric Blake 
3003c1bb86cdSEric Blake     s->type = FTYPE_FILE;
3004c1bb86cdSEric Blake 
3005230ff739SJohn Snow     ret = raw_open_common(bs, options, flags, 0, true, &local_err);
3006c1bb86cdSEric Blake     if (ret < 0) {
3007c1bb86cdSEric Blake         error_propagate(errp, local_err);
3008c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3009c1bb86cdSEric Blake         if (*bsd_path) {
3010c1bb86cdSEric Blake             filename = bsd_path;
3011c1bb86cdSEric Blake         }
3012c1bb86cdSEric Blake         /* if a physical device experienced an error while being opened */
3013c1bb86cdSEric Blake         if (strncmp(filename, "/dev/", 5) == 0) {
3014c1bb86cdSEric Blake             print_unmounting_directions(filename);
3015c1bb86cdSEric Blake         }
3016c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3017c1bb86cdSEric Blake         return ret;
3018c1bb86cdSEric Blake     }
3019c1bb86cdSEric Blake 
3020c1bb86cdSEric Blake     /* Since this does ioctl the device must be already opened */
3021c1bb86cdSEric Blake     bs->sg = hdev_is_sg(bs);
3022c1bb86cdSEric Blake 
3023c1bb86cdSEric Blake     if (flags & BDRV_O_RDWR) {
3024c1bb86cdSEric Blake         ret = check_hdev_writable(s);
3025c1bb86cdSEric Blake         if (ret < 0) {
3026c1bb86cdSEric Blake             raw_close(bs);
3027c1bb86cdSEric Blake             error_setg_errno(errp, -ret, "The device is not writable");
3028c1bb86cdSEric Blake             return ret;
3029c1bb86cdSEric Blake         }
3030c1bb86cdSEric Blake     }
3031c1bb86cdSEric Blake 
3032c1bb86cdSEric Blake     return ret;
3033c1bb86cdSEric Blake }
3034c1bb86cdSEric Blake 
3035c1bb86cdSEric Blake #if defined(__linux__)
3036c1bb86cdSEric Blake 
3037c1bb86cdSEric Blake static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
3038c1bb86cdSEric Blake         unsigned long int req, void *buf,
3039c1bb86cdSEric Blake         BlockCompletionFunc *cb, void *opaque)
3040c1bb86cdSEric Blake {
3041c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3042c1bb86cdSEric Blake     RawPosixAIOData *acb;
3043c1bb86cdSEric Blake     ThreadPool *pool;
3044c1bb86cdSEric Blake 
3045c1bb86cdSEric Blake     if (fd_open(bs) < 0)
3046c1bb86cdSEric Blake         return NULL;
3047c1bb86cdSEric Blake 
30487c9e5276SPaolo Bonzini     if (req == SG_IO && s->pr_mgr) {
30497c9e5276SPaolo Bonzini         struct sg_io_hdr *io_hdr = buf;
30507c9e5276SPaolo Bonzini         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
30517c9e5276SPaolo Bonzini             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
30527c9e5276SPaolo Bonzini             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
30537c9e5276SPaolo Bonzini                                       s->fd, io_hdr, cb, opaque);
30547c9e5276SPaolo Bonzini         }
30557c9e5276SPaolo Bonzini     }
30567c9e5276SPaolo Bonzini 
3057c1bb86cdSEric Blake     acb = g_new(RawPosixAIOData, 1);
3058c1bb86cdSEric Blake     acb->bs = bs;
3059c1bb86cdSEric Blake     acb->aio_type = QEMU_AIO_IOCTL;
3060c1bb86cdSEric Blake     acb->aio_fildes = s->fd;
3061c1bb86cdSEric Blake     acb->aio_offset = 0;
3062c1bb86cdSEric Blake     acb->aio_ioctl_buf = buf;
3063c1bb86cdSEric Blake     acb->aio_ioctl_cmd = req;
3064c1bb86cdSEric Blake     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
3065c1bb86cdSEric Blake     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
3066c1bb86cdSEric Blake }
3067c1bb86cdSEric Blake #endif /* linux */
3068c1bb86cdSEric Blake 
3069c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs)
3070c1bb86cdSEric Blake {
3071c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3072c1bb86cdSEric Blake 
3073c1bb86cdSEric Blake     /* this is just to ensure s->fd is sane (its called by io ops) */
3074c1bb86cdSEric Blake     if (s->fd >= 0)
3075c1bb86cdSEric Blake         return 0;
3076c1bb86cdSEric Blake     return -EIO;
3077c1bb86cdSEric Blake }
3078c1bb86cdSEric Blake 
307933d70fb6SKevin Wolf static coroutine_fn int
308033d70fb6SKevin Wolf hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
3081c1bb86cdSEric Blake {
3082c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
308333d70fb6SKevin Wolf     int ret;
3084c1bb86cdSEric Blake 
308533d70fb6SKevin Wolf     ret = fd_open(bs);
308633d70fb6SKevin Wolf     if (ret < 0) {
308733d70fb6SKevin Wolf         return ret;
3088c1bb86cdSEric Blake     }
308933d70fb6SKevin Wolf     return paio_submit_co(bs, s->fd, offset, NULL, bytes,
309033d70fb6SKevin Wolf                           QEMU_AIO_DISCARD | QEMU_AIO_BLKDEV);
3091c1bb86cdSEric Blake }
3092c1bb86cdSEric Blake 
3093c1bb86cdSEric Blake static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3094f5a5ca79SManos Pitsidianakis     int64_t offset, int bytes, BdrvRequestFlags flags)
3095c1bb86cdSEric Blake {
3096c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
309734fa110eSKevin Wolf     int operation = QEMU_AIO_WRITE_ZEROES | QEMU_AIO_BLKDEV;
3098c1bb86cdSEric Blake     int rc;
3099c1bb86cdSEric Blake 
3100c1bb86cdSEric Blake     rc = fd_open(bs);
3101c1bb86cdSEric Blake     if (rc < 0) {
3102c1bb86cdSEric Blake         return rc;
3103c1bb86cdSEric Blake     }
310434fa110eSKevin Wolf 
310534fa110eSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
310634fa110eSKevin Wolf         operation |= QEMU_AIO_DISCARD;
3107c1bb86cdSEric Blake     }
310834fa110eSKevin Wolf 
310934fa110eSKevin Wolf     return paio_submit_co(bs, s->fd, offset, NULL, bytes, operation);
3110c1bb86cdSEric Blake }
3111c1bb86cdSEric Blake 
3112efc75e2aSStefan Hajnoczi static int coroutine_fn hdev_co_create_opts(const char *filename, QemuOpts *opts,
3113c1bb86cdSEric Blake                                             Error **errp)
3114c1bb86cdSEric Blake {
3115c1bb86cdSEric Blake     int fd;
3116c1bb86cdSEric Blake     int ret = 0;
3117c1bb86cdSEric Blake     struct stat stat_buf;
3118c1bb86cdSEric Blake     int64_t total_size = 0;
3119c1bb86cdSEric Blake     bool has_prefix;
3120c1bb86cdSEric Blake 
3121c1bb86cdSEric Blake     /* This function is used by both protocol block drivers and therefore either
3122c1bb86cdSEric Blake      * of these prefixes may be given.
3123c1bb86cdSEric Blake      * The return value has to be stored somewhere, otherwise this is an error
3124c1bb86cdSEric Blake      * due to -Werror=unused-value. */
3125c1bb86cdSEric Blake     has_prefix =
3126c1bb86cdSEric Blake         strstart(filename, "host_device:", &filename) ||
3127c1bb86cdSEric Blake         strstart(filename, "host_cdrom:" , &filename);
3128c1bb86cdSEric Blake 
3129c1bb86cdSEric Blake     (void)has_prefix;
3130c1bb86cdSEric Blake 
3131c1bb86cdSEric Blake     ret = raw_normalize_devicepath(&filename);
3132c1bb86cdSEric Blake     if (ret < 0) {
3133c1bb86cdSEric Blake         error_setg_errno(errp, -ret, "Could not normalize device path");
3134c1bb86cdSEric Blake         return ret;
3135c1bb86cdSEric Blake     }
3136c1bb86cdSEric Blake 
3137c1bb86cdSEric Blake     /* Read out options */
3138c1bb86cdSEric Blake     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3139c1bb86cdSEric Blake                           BDRV_SECTOR_SIZE);
3140c1bb86cdSEric Blake 
3141c1bb86cdSEric Blake     fd = qemu_open(filename, O_WRONLY | O_BINARY);
3142c1bb86cdSEric Blake     if (fd < 0) {
3143c1bb86cdSEric Blake         ret = -errno;
3144c1bb86cdSEric Blake         error_setg_errno(errp, -ret, "Could not open device");
3145c1bb86cdSEric Blake         return ret;
3146c1bb86cdSEric Blake     }
3147c1bb86cdSEric Blake 
3148c1bb86cdSEric Blake     if (fstat(fd, &stat_buf) < 0) {
3149c1bb86cdSEric Blake         ret = -errno;
3150c1bb86cdSEric Blake         error_setg_errno(errp, -ret, "Could not stat device");
3151c1bb86cdSEric Blake     } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
3152c1bb86cdSEric Blake         error_setg(errp,
3153c1bb86cdSEric Blake                    "The given file is neither a block nor a character device");
3154c1bb86cdSEric Blake         ret = -ENODEV;
3155c1bb86cdSEric Blake     } else if (lseek(fd, 0, SEEK_END) < total_size) {
3156c1bb86cdSEric Blake         error_setg(errp, "Device is too small");
3157c1bb86cdSEric Blake         ret = -ENOSPC;
3158c1bb86cdSEric Blake     }
3159c1bb86cdSEric Blake 
316097ec9117SFam Zheng     if (!ret && total_size) {
316197ec9117SFam Zheng         uint8_t buf[BDRV_SECTOR_SIZE] = { 0 };
316297ec9117SFam Zheng         int64_t zero_size = MIN(BDRV_SECTOR_SIZE, total_size);
316397ec9117SFam Zheng         if (lseek(fd, 0, SEEK_SET) == -1) {
316497ec9117SFam Zheng             ret = -errno;
316597ec9117SFam Zheng         } else {
316697ec9117SFam Zheng             ret = qemu_write_full(fd, buf, zero_size);
316797ec9117SFam Zheng             ret = ret == zero_size ? 0 : -errno;
316897ec9117SFam Zheng         }
316997ec9117SFam Zheng     }
3170c1bb86cdSEric Blake     qemu_close(fd);
3171c1bb86cdSEric Blake     return ret;
3172c1bb86cdSEric Blake }
3173c1bb86cdSEric Blake 
3174c1bb86cdSEric Blake static BlockDriver bdrv_host_device = {
3175c1bb86cdSEric Blake     .format_name        = "host_device",
3176c1bb86cdSEric Blake     .protocol_name        = "host_device",
3177c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3178c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3179c1bb86cdSEric Blake     .bdrv_probe_device  = hdev_probe_device,
3180c1bb86cdSEric Blake     .bdrv_parse_filename = hdev_parse_filename,
3181c1bb86cdSEric Blake     .bdrv_file_open     = hdev_open,
3182c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3183c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3184c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3185c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
3186efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = hdev_co_create_opts,
3187c1bb86cdSEric Blake     .create_opts         = &raw_create_opts,
3188dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3189c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3190c1bb86cdSEric Blake 
3191c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3192c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
319333d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
319433d70fb6SKevin Wolf     .bdrv_co_pdiscard       = hdev_co_pdiscard,
31951efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
31961efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3197c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3198c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3199c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3200042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3201c1bb86cdSEric Blake 
3202061ca8a3SKevin Wolf     .bdrv_co_truncate       = raw_co_truncate,
3203c1bb86cdSEric Blake     .bdrv_getlength	= raw_getlength,
3204c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3205c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3206c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3207244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3208244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3209244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3210c1bb86cdSEric Blake     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3211c1bb86cdSEric Blake     .bdrv_probe_geometry = hdev_probe_geometry,
3212c1bb86cdSEric Blake 
3213c1bb86cdSEric Blake     /* generic scsi device */
3214c1bb86cdSEric Blake #ifdef __linux__
3215c1bb86cdSEric Blake     .bdrv_aio_ioctl     = hdev_aio_ioctl,
3216c1bb86cdSEric Blake #endif
3217c1bb86cdSEric Blake };
3218c1bb86cdSEric Blake 
3219c1bb86cdSEric Blake #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3220c1bb86cdSEric Blake static void cdrom_parse_filename(const char *filename, QDict *options,
3221c1bb86cdSEric Blake                                  Error **errp)
3222c1bb86cdSEric Blake {
322303c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3224c1bb86cdSEric Blake }
3225c1bb86cdSEric Blake #endif
3226c1bb86cdSEric Blake 
3227c1bb86cdSEric Blake #ifdef __linux__
3228c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3229c1bb86cdSEric Blake                       Error **errp)
3230c1bb86cdSEric Blake {
3231c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3232c1bb86cdSEric Blake 
3233c1bb86cdSEric Blake     s->type = FTYPE_CD;
3234c1bb86cdSEric Blake 
3235c1bb86cdSEric Blake     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3236230ff739SJohn Snow     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3237c1bb86cdSEric Blake }
3238c1bb86cdSEric Blake 
3239c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3240c1bb86cdSEric Blake {
3241c1bb86cdSEric Blake     int fd, ret;
3242c1bb86cdSEric Blake     int prio = 0;
3243c1bb86cdSEric Blake     struct stat st;
3244c1bb86cdSEric Blake 
3245c1bb86cdSEric Blake     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
3246c1bb86cdSEric Blake     if (fd < 0) {
3247c1bb86cdSEric Blake         goto out;
3248c1bb86cdSEric Blake     }
3249c1bb86cdSEric Blake     ret = fstat(fd, &st);
3250c1bb86cdSEric Blake     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3251c1bb86cdSEric Blake         goto outc;
3252c1bb86cdSEric Blake     }
3253c1bb86cdSEric Blake 
3254c1bb86cdSEric Blake     /* Attempt to detect via a CDROM specific ioctl */
3255c1bb86cdSEric Blake     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3256c1bb86cdSEric Blake     if (ret >= 0)
3257c1bb86cdSEric Blake         prio = 100;
3258c1bb86cdSEric Blake 
3259c1bb86cdSEric Blake outc:
3260c1bb86cdSEric Blake     qemu_close(fd);
3261c1bb86cdSEric Blake out:
3262c1bb86cdSEric Blake     return prio;
3263c1bb86cdSEric Blake }
3264c1bb86cdSEric Blake 
3265c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3266c1bb86cdSEric Blake {
3267c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3268c1bb86cdSEric Blake     int ret;
3269c1bb86cdSEric Blake 
3270c1bb86cdSEric Blake     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3271c1bb86cdSEric Blake     return ret == CDS_DISC_OK;
3272c1bb86cdSEric Blake }
3273c1bb86cdSEric Blake 
3274c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3275c1bb86cdSEric Blake {
3276c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3277c1bb86cdSEric Blake 
3278c1bb86cdSEric Blake     if (eject_flag) {
3279c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3280c1bb86cdSEric Blake             perror("CDROMEJECT");
3281c1bb86cdSEric Blake     } else {
3282c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3283c1bb86cdSEric Blake             perror("CDROMEJECT");
3284c1bb86cdSEric Blake     }
3285c1bb86cdSEric Blake }
3286c1bb86cdSEric Blake 
3287c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3288c1bb86cdSEric Blake {
3289c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3290c1bb86cdSEric Blake 
3291c1bb86cdSEric Blake     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3292c1bb86cdSEric Blake         /*
3293c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3294c1bb86cdSEric Blake          * mounts the CD-ROM
3295c1bb86cdSEric Blake          */
3296c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3297c1bb86cdSEric Blake     }
3298c1bb86cdSEric Blake }
3299c1bb86cdSEric Blake 
3300c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3301c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3302c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3303c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3304c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3305c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3306c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3307c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3308c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3309c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3310c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3311c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
3312efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = hdev_co_create_opts,
3313c1bb86cdSEric Blake     .create_opts         = &raw_create_opts,
3314dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3315c1bb86cdSEric Blake 
3316c1bb86cdSEric Blake 
3317c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3318c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
331933d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3320c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3321c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3322c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3323042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3324c1bb86cdSEric Blake 
3325061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3326c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3327c1bb86cdSEric Blake     .has_variable_length = true,
3328c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3329c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3330c1bb86cdSEric Blake 
3331c1bb86cdSEric Blake     /* removable device support */
3332c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3333c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3334c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3335c1bb86cdSEric Blake 
3336c1bb86cdSEric Blake     /* generic scsi device */
3337c1bb86cdSEric Blake     .bdrv_aio_ioctl     = hdev_aio_ioctl,
3338c1bb86cdSEric Blake };
3339c1bb86cdSEric Blake #endif /* __linux__ */
3340c1bb86cdSEric Blake 
3341c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3342c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3343c1bb86cdSEric Blake                       Error **errp)
3344c1bb86cdSEric Blake {
3345c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3346c1bb86cdSEric Blake     Error *local_err = NULL;
3347c1bb86cdSEric Blake     int ret;
3348c1bb86cdSEric Blake 
3349c1bb86cdSEric Blake     s->type = FTYPE_CD;
3350c1bb86cdSEric Blake 
3351230ff739SJohn Snow     ret = raw_open_common(bs, options, flags, 0, true, &local_err);
3352c1bb86cdSEric Blake     if (ret) {
3353c1bb86cdSEric Blake         error_propagate(errp, local_err);
3354c1bb86cdSEric Blake         return ret;
3355c1bb86cdSEric Blake     }
3356c1bb86cdSEric Blake 
3357c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3358c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3359c1bb86cdSEric Blake     return 0;
3360c1bb86cdSEric Blake }
3361c1bb86cdSEric Blake 
3362c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3363c1bb86cdSEric Blake {
3364c1bb86cdSEric Blake     if (strstart(filename, "/dev/cd", NULL) ||
3365c1bb86cdSEric Blake             strstart(filename, "/dev/acd", NULL))
3366c1bb86cdSEric Blake         return 100;
3367c1bb86cdSEric Blake     return 0;
3368c1bb86cdSEric Blake }
3369c1bb86cdSEric Blake 
3370c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs)
3371c1bb86cdSEric Blake {
3372c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3373c1bb86cdSEric Blake     int fd;
3374c1bb86cdSEric Blake 
3375c1bb86cdSEric Blake     /*
3376c1bb86cdSEric Blake      * Force reread of possibly changed/newly loaded disc,
3377c1bb86cdSEric Blake      * FreeBSD seems to not notice sometimes...
3378c1bb86cdSEric Blake      */
3379c1bb86cdSEric Blake     if (s->fd >= 0)
3380c1bb86cdSEric Blake         qemu_close(s->fd);
3381c1bb86cdSEric Blake     fd = qemu_open(bs->filename, s->open_flags, 0644);
3382c1bb86cdSEric Blake     if (fd < 0) {
3383c1bb86cdSEric Blake         s->fd = -1;
3384c1bb86cdSEric Blake         return -EIO;
3385c1bb86cdSEric Blake     }
3386c1bb86cdSEric Blake     s->fd = fd;
3387c1bb86cdSEric Blake 
3388c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3389c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3390c1bb86cdSEric Blake     return 0;
3391c1bb86cdSEric Blake }
3392c1bb86cdSEric Blake 
3393c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3394c1bb86cdSEric Blake {
3395c1bb86cdSEric Blake     return raw_getlength(bs) > 0;
3396c1bb86cdSEric Blake }
3397c1bb86cdSEric Blake 
3398c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3399c1bb86cdSEric Blake {
3400c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3401c1bb86cdSEric Blake 
3402c1bb86cdSEric Blake     if (s->fd < 0)
3403c1bb86cdSEric Blake         return;
3404c1bb86cdSEric Blake 
3405c1bb86cdSEric Blake     (void) ioctl(s->fd, CDIOCALLOW);
3406c1bb86cdSEric Blake 
3407c1bb86cdSEric Blake     if (eject_flag) {
3408c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCEJECT) < 0)
3409c1bb86cdSEric Blake             perror("CDIOCEJECT");
3410c1bb86cdSEric Blake     } else {
3411c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3412c1bb86cdSEric Blake             perror("CDIOCCLOSE");
3413c1bb86cdSEric Blake     }
3414c1bb86cdSEric Blake 
3415c1bb86cdSEric Blake     cdrom_reopen(bs);
3416c1bb86cdSEric Blake }
3417c1bb86cdSEric Blake 
3418c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3419c1bb86cdSEric Blake {
3420c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3421c1bb86cdSEric Blake 
3422c1bb86cdSEric Blake     if (s->fd < 0)
3423c1bb86cdSEric Blake         return;
3424c1bb86cdSEric Blake     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3425c1bb86cdSEric Blake         /*
3426c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3427c1bb86cdSEric Blake          * mounts the CD-ROM
3428c1bb86cdSEric Blake          */
3429c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3430c1bb86cdSEric Blake     }
3431c1bb86cdSEric Blake }
3432c1bb86cdSEric Blake 
3433c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3434c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3435c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3436c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3437c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3438c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3439c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3440c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3441c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3442c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3443c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3444c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
3445efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = hdev_co_create_opts,
3446c1bb86cdSEric Blake     .create_opts        = &raw_create_opts,
3447c1bb86cdSEric Blake 
3448c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3449c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
345033d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3451c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3452c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3453c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3454042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3455c1bb86cdSEric Blake 
3456061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3457c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3458c1bb86cdSEric Blake     .has_variable_length = true,
3459c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3460c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3461c1bb86cdSEric Blake 
3462c1bb86cdSEric Blake     /* removable device support */
3463c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3464c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3465c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3466c1bb86cdSEric Blake };
3467c1bb86cdSEric Blake #endif /* __FreeBSD__ */
3468c1bb86cdSEric Blake 
3469c1bb86cdSEric Blake static void bdrv_file_init(void)
3470c1bb86cdSEric Blake {
3471c1bb86cdSEric Blake     /*
3472c1bb86cdSEric Blake      * Register all the drivers.  Note that order is important, the driver
3473c1bb86cdSEric Blake      * registered last will get probed first.
3474c1bb86cdSEric Blake      */
3475c1bb86cdSEric Blake     bdrv_register(&bdrv_file);
3476c1bb86cdSEric Blake     bdrv_register(&bdrv_host_device);
3477c1bb86cdSEric Blake #ifdef __linux__
3478c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3479c1bb86cdSEric Blake #endif
3480c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3481c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3482c1bb86cdSEric Blake #endif
3483c1bb86cdSEric Blake }
3484c1bb86cdSEric Blake 
3485c1bb86cdSEric Blake block_init(bdrv_file_init);
3486