xref: /qemu/block/file-posix.c (revision af175e85)
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"
26a8d25326SMarkus Armbruster #include "qemu-common.h"
27c1bb86cdSEric Blake #include "qapi/error.h"
28c1bb86cdSEric Blake #include "qemu/cutils.h"
29c1bb86cdSEric Blake #include "qemu/error-report.h"
30c1bb86cdSEric Blake #include "block/block_int.h"
31c1bb86cdSEric Blake #include "qemu/module.h"
32922a01a0SMarkus Armbruster #include "qemu/option.h"
33c1bb86cdSEric Blake #include "trace.h"
34c1bb86cdSEric Blake #include "block/thread-pool.h"
35c1bb86cdSEric Blake #include "qemu/iov.h"
36c1bb86cdSEric Blake #include "block/raw-aio.h"
37452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
38c1bb86cdSEric Blake #include "qapi/qmp/qstring.h"
39c1bb86cdSEric Blake 
407c9e5276SPaolo Bonzini #include "scsi/pr-manager.h"
417c9e5276SPaolo Bonzini #include "scsi/constants.h"
427c9e5276SPaolo Bonzini 
43c1bb86cdSEric Blake #if defined(__APPLE__) && (__MACH__)
44c1bb86cdSEric Blake #include <paths.h>
45c1bb86cdSEric Blake #include <sys/param.h>
46c1bb86cdSEric Blake #include <IOKit/IOKitLib.h>
47c1bb86cdSEric Blake #include <IOKit/IOBSD.h>
48c1bb86cdSEric Blake #include <IOKit/storage/IOMediaBSDClient.h>
49c1bb86cdSEric Blake #include <IOKit/storage/IOMedia.h>
50c1bb86cdSEric Blake #include <IOKit/storage/IOCDMedia.h>
51c1bb86cdSEric Blake //#include <IOKit/storage/IOCDTypes.h>
52c1bb86cdSEric Blake #include <IOKit/storage/IODVDMedia.h>
53c1bb86cdSEric Blake #include <CoreFoundation/CoreFoundation.h>
54c1bb86cdSEric Blake #endif
55c1bb86cdSEric Blake 
56c1bb86cdSEric Blake #ifdef __sun__
57c1bb86cdSEric Blake #define _POSIX_PTHREAD_SEMANTICS 1
58c1bb86cdSEric Blake #include <sys/dkio.h>
59c1bb86cdSEric Blake #endif
60c1bb86cdSEric Blake #ifdef __linux__
61c1bb86cdSEric Blake #include <sys/ioctl.h>
62c1bb86cdSEric Blake #include <sys/param.h>
631efad060SFam Zheng #include <sys/syscall.h>
64c1bb86cdSEric Blake #include <linux/cdrom.h>
65c1bb86cdSEric Blake #include <linux/fd.h>
66c1bb86cdSEric Blake #include <linux/fs.h>
67c1bb86cdSEric Blake #include <linux/hdreg.h>
68c1bb86cdSEric Blake #include <scsi/sg.h>
69c1bb86cdSEric Blake #ifdef __s390__
70c1bb86cdSEric Blake #include <asm/dasd.h>
71c1bb86cdSEric Blake #endif
72c1bb86cdSEric Blake #ifndef FS_NOCOW_FL
73c1bb86cdSEric Blake #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
74c1bb86cdSEric Blake #endif
75c1bb86cdSEric Blake #endif
76c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
77c1bb86cdSEric Blake #include <linux/falloc.h>
78c1bb86cdSEric Blake #endif
79c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
80c1bb86cdSEric Blake #include <sys/disk.h>
81c1bb86cdSEric Blake #include <sys/cdio.h>
82c1bb86cdSEric Blake #endif
83c1bb86cdSEric Blake 
84c1bb86cdSEric Blake #ifdef __OpenBSD__
85c1bb86cdSEric Blake #include <sys/ioctl.h>
86c1bb86cdSEric Blake #include <sys/disklabel.h>
87c1bb86cdSEric Blake #include <sys/dkio.h>
88c1bb86cdSEric Blake #endif
89c1bb86cdSEric Blake 
90c1bb86cdSEric Blake #ifdef __NetBSD__
91c1bb86cdSEric Blake #include <sys/ioctl.h>
92c1bb86cdSEric Blake #include <sys/disklabel.h>
93c1bb86cdSEric Blake #include <sys/dkio.h>
94c1bb86cdSEric Blake #include <sys/disk.h>
95c1bb86cdSEric Blake #endif
96c1bb86cdSEric Blake 
97c1bb86cdSEric Blake #ifdef __DragonFly__
98c1bb86cdSEric Blake #include <sys/ioctl.h>
99c1bb86cdSEric Blake #include <sys/diskslice.h>
100c1bb86cdSEric Blake #endif
101c1bb86cdSEric Blake 
102c1bb86cdSEric Blake #ifdef CONFIG_XFS
103c1bb86cdSEric Blake #include <xfs/xfs.h>
104c1bb86cdSEric Blake #endif
105c1bb86cdSEric Blake 
1064f7d28d7SLaurent Vivier #include "trace.h"
107c1bb86cdSEric Blake 
108c1bb86cdSEric Blake /* OS X does not have O_DSYNC */
109c1bb86cdSEric Blake #ifndef O_DSYNC
110c1bb86cdSEric Blake #ifdef O_SYNC
111c1bb86cdSEric Blake #define O_DSYNC O_SYNC
112c1bb86cdSEric Blake #elif defined(O_FSYNC)
113c1bb86cdSEric Blake #define O_DSYNC O_FSYNC
114c1bb86cdSEric Blake #endif
115c1bb86cdSEric Blake #endif
116c1bb86cdSEric Blake 
117c1bb86cdSEric Blake /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
118c1bb86cdSEric Blake #ifndef O_DIRECT
119c1bb86cdSEric Blake #define O_DIRECT O_DSYNC
120c1bb86cdSEric Blake #endif
121c1bb86cdSEric Blake 
122c1bb86cdSEric Blake #define FTYPE_FILE   0
123c1bb86cdSEric Blake #define FTYPE_CD     1
124c1bb86cdSEric Blake 
125c1bb86cdSEric Blake #define MAX_BLOCKSIZE	4096
126c1bb86cdSEric Blake 
127244a5668SFam Zheng /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
128244a5668SFam Zheng  * leaving a few more bytes for its future use. */
129244a5668SFam Zheng #define RAW_LOCK_PERM_BASE             100
130244a5668SFam Zheng #define RAW_LOCK_SHARED_BASE           200
131244a5668SFam Zheng 
132c1bb86cdSEric Blake typedef struct BDRVRawState {
133c1bb86cdSEric Blake     int fd;
134244a5668SFam Zheng     bool use_lock;
135c1bb86cdSEric Blake     int type;
136c1bb86cdSEric Blake     int open_flags;
137c1bb86cdSEric Blake     size_t buf_align;
138c1bb86cdSEric Blake 
139244a5668SFam Zheng     /* The current permissions. */
140244a5668SFam Zheng     uint64_t perm;
141244a5668SFam Zheng     uint64_t shared_perm;
142244a5668SFam Zheng 
1432996ffadSFam Zheng     /* The perms bits whose corresponding bytes are already locked in
144f2e3af29SFam Zheng      * s->fd. */
1452996ffadSFam Zheng     uint64_t locked_perm;
1462996ffadSFam Zheng     uint64_t locked_shared_perm;
1472996ffadSFam Zheng 
1486ceabe6fSKevin Wolf     int perm_change_fd;
149094e3639SMax Reitz     int perm_change_flags;
150e0c9cf3aSKevin Wolf     BDRVReopenState *reopen_state;
151e0c9cf3aSKevin Wolf 
152c1bb86cdSEric Blake #ifdef CONFIG_XFS
153c1bb86cdSEric Blake     bool is_xfs:1;
154c1bb86cdSEric Blake #endif
155c1bb86cdSEric Blake     bool has_discard:1;
156c1bb86cdSEric Blake     bool has_write_zeroes:1;
157c1bb86cdSEric Blake     bool discard_zeroes:1;
158c1bb86cdSEric Blake     bool use_linux_aio:1;
159c6447510SAarushi Mehta     bool use_linux_io_uring:1;
160e5bcf967SKevin Wolf     bool page_cache_inconsistent:1;
161c1bb86cdSEric Blake     bool has_fallocate;
162c1bb86cdSEric Blake     bool needs_alignment;
163f357fcd8SStefan Hajnoczi     bool drop_cache;
16431be8a2aSStefan Hajnoczi     bool check_cache_dropped;
1651c450366SAnton Nefedov     struct {
1661c450366SAnton Nefedov         uint64_t discard_nb_ok;
1671c450366SAnton Nefedov         uint64_t discard_nb_failed;
1681c450366SAnton Nefedov         uint64_t discard_bytes_ok;
1691c450366SAnton Nefedov     } stats;
1707c9e5276SPaolo Bonzini 
1717c9e5276SPaolo Bonzini     PRManager *pr_mgr;
172c1bb86cdSEric Blake } BDRVRawState;
173c1bb86cdSEric Blake 
174c1bb86cdSEric Blake typedef struct BDRVRawReopenState {
175c1bb86cdSEric Blake     int fd;
176c1bb86cdSEric Blake     int open_flags;
177f357fcd8SStefan Hajnoczi     bool drop_cache;
17831be8a2aSStefan Hajnoczi     bool check_cache_dropped;
179c1bb86cdSEric Blake } BDRVRawReopenState;
180c1bb86cdSEric Blake 
181c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs);
182c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs);
183c1bb86cdSEric Blake 
184c1bb86cdSEric Blake typedef struct RawPosixAIOData {
185c1bb86cdSEric Blake     BlockDriverState *bs;
186c1bb86cdSEric Blake     int aio_type;
187d57c44d0SKevin Wolf     int aio_fildes;
188d57c44d0SKevin Wolf 
189d57c44d0SKevin Wolf     off_t aio_offset;
190d57c44d0SKevin Wolf     uint64_t aio_nbytes;
191d57c44d0SKevin Wolf 
19293f4e2ffSKevin Wolf     union {
19393f4e2ffSKevin Wolf         struct {
194d57c44d0SKevin Wolf             struct iovec *iov;
195d57c44d0SKevin Wolf             int niov;
196d57c44d0SKevin Wolf         } io;
197d57c44d0SKevin Wolf         struct {
198d57c44d0SKevin Wolf             uint64_t cmd;
199d57c44d0SKevin Wolf             void *buf;
200d57c44d0SKevin Wolf         } ioctl;
201d57c44d0SKevin Wolf         struct {
2021efad060SFam Zheng             int aio_fd2;
2031efad060SFam Zheng             off_t aio_offset2;
204d57c44d0SKevin Wolf         } copy_range;
20593f4e2ffSKevin Wolf         struct {
20693f4e2ffSKevin Wolf             PreallocMode prealloc;
20793f4e2ffSKevin Wolf             Error **errp;
208d57c44d0SKevin Wolf         } truncate;
20993f4e2ffSKevin Wolf     };
210c1bb86cdSEric Blake } RawPosixAIOData;
211c1bb86cdSEric Blake 
212c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
213c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs);
214c1bb86cdSEric Blake #endif
215c1bb86cdSEric Blake 
216c1bb86cdSEric Blake #if defined(__NetBSD__)
217db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
218c1bb86cdSEric Blake {
219c1bb86cdSEric Blake     static char namebuf[PATH_MAX];
220c1bb86cdSEric Blake     const char *dp, *fname;
221c1bb86cdSEric Blake     struct stat sb;
222c1bb86cdSEric Blake 
223c1bb86cdSEric Blake     fname = *filename;
224c1bb86cdSEric Blake     dp = strrchr(fname, '/');
225c1bb86cdSEric Blake     if (lstat(fname, &sb) < 0) {
226f6fc1e30SPaolo Bonzini         error_setg_file_open(errp, errno, fname);
227c1bb86cdSEric Blake         return -errno;
228c1bb86cdSEric Blake     }
229c1bb86cdSEric Blake 
230c1bb86cdSEric Blake     if (!S_ISBLK(sb.st_mode)) {
231c1bb86cdSEric Blake         return 0;
232c1bb86cdSEric Blake     }
233c1bb86cdSEric Blake 
234c1bb86cdSEric Blake     if (dp == NULL) {
235c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "r%s", fname);
236c1bb86cdSEric Blake     } else {
237c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
238c1bb86cdSEric Blake             (int)(dp - fname), fname, dp + 1);
239c1bb86cdSEric Blake     }
240c1bb86cdSEric Blake     *filename = namebuf;
241db0754dfSFam Zheng     warn_report("%s is a block device, using %s", fname, *filename);
242c1bb86cdSEric Blake 
243c1bb86cdSEric Blake     return 0;
244c1bb86cdSEric Blake }
245c1bb86cdSEric Blake #else
246db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
247c1bb86cdSEric Blake {
248c1bb86cdSEric Blake     return 0;
249c1bb86cdSEric Blake }
250c1bb86cdSEric Blake #endif
251c1bb86cdSEric Blake 
252c1bb86cdSEric Blake /*
253c1bb86cdSEric Blake  * Get logical block size via ioctl. On success store it in @sector_size_p.
254c1bb86cdSEric Blake  */
255c1bb86cdSEric Blake static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
256c1bb86cdSEric Blake {
257c1bb86cdSEric Blake     unsigned int sector_size;
258c1bb86cdSEric Blake     bool success = false;
259700f9ce0SPeter Maydell     int i;
260c1bb86cdSEric Blake 
261c1bb86cdSEric Blake     errno = ENOTSUP;
262700f9ce0SPeter Maydell     static const unsigned long ioctl_list[] = {
263c1bb86cdSEric Blake #ifdef BLKSSZGET
264700f9ce0SPeter Maydell         BLKSSZGET,
265c1bb86cdSEric Blake #endif
266c1bb86cdSEric Blake #ifdef DKIOCGETBLOCKSIZE
267700f9ce0SPeter Maydell         DKIOCGETBLOCKSIZE,
268c1bb86cdSEric Blake #endif
269c1bb86cdSEric Blake #ifdef DIOCGSECTORSIZE
270700f9ce0SPeter Maydell         DIOCGSECTORSIZE,
271700f9ce0SPeter Maydell #endif
272700f9ce0SPeter Maydell     };
273700f9ce0SPeter Maydell 
274700f9ce0SPeter Maydell     /* Try a few ioctls to get the right size */
275700f9ce0SPeter Maydell     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
276700f9ce0SPeter Maydell         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
277c1bb86cdSEric Blake             *sector_size_p = sector_size;
278c1bb86cdSEric Blake             success = true;
279c1bb86cdSEric Blake         }
280700f9ce0SPeter Maydell     }
281c1bb86cdSEric Blake 
282c1bb86cdSEric Blake     return success ? 0 : -errno;
283c1bb86cdSEric Blake }
284c1bb86cdSEric Blake 
285c1bb86cdSEric Blake /**
286c1bb86cdSEric Blake  * Get physical block size of @fd.
287c1bb86cdSEric Blake  * On success, store it in @blk_size and return 0.
288c1bb86cdSEric Blake  * On failure, return -errno.
289c1bb86cdSEric Blake  */
290c1bb86cdSEric Blake static int probe_physical_blocksize(int fd, unsigned int *blk_size)
291c1bb86cdSEric Blake {
292c1bb86cdSEric Blake #ifdef BLKPBSZGET
293c1bb86cdSEric Blake     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
294c1bb86cdSEric Blake         return -errno;
295c1bb86cdSEric Blake     }
296c1bb86cdSEric Blake     return 0;
297c1bb86cdSEric Blake #else
298c1bb86cdSEric Blake     return -ENOTSUP;
299c1bb86cdSEric Blake #endif
300c1bb86cdSEric Blake }
301c1bb86cdSEric Blake 
302c1bb86cdSEric Blake /* Check if read is allowed with given memory buffer and length.
303c1bb86cdSEric Blake  *
304c1bb86cdSEric Blake  * This function is used to check O_DIRECT memory buffer and request alignment.
305c1bb86cdSEric Blake  */
306c1bb86cdSEric Blake static bool raw_is_io_aligned(int fd, void *buf, size_t len)
307c1bb86cdSEric Blake {
308c1bb86cdSEric Blake     ssize_t ret = pread(fd, buf, len, 0);
309c1bb86cdSEric Blake 
310c1bb86cdSEric Blake     if (ret >= 0) {
311c1bb86cdSEric Blake         return true;
312c1bb86cdSEric Blake     }
313c1bb86cdSEric Blake 
314c1bb86cdSEric Blake #ifdef __linux__
315c1bb86cdSEric Blake     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
316c1bb86cdSEric Blake      * other errors (e.g. real I/O error), which could happen on a failed
317c1bb86cdSEric Blake      * drive, since we only care about probing alignment.
318c1bb86cdSEric Blake      */
319c1bb86cdSEric Blake     if (errno != EINVAL) {
320c1bb86cdSEric Blake         return true;
321c1bb86cdSEric Blake     }
322c1bb86cdSEric Blake #endif
323c1bb86cdSEric Blake 
324c1bb86cdSEric Blake     return false;
325c1bb86cdSEric Blake }
326c1bb86cdSEric Blake 
327c1bb86cdSEric Blake static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
328c1bb86cdSEric Blake {
329c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
330c1bb86cdSEric Blake     char *buf;
331038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
332a6b257a0SNir Soffer     size_t alignments[] = {1, 512, 1024, 2048, 4096};
333c1bb86cdSEric Blake 
334c1bb86cdSEric Blake     /* For SCSI generic devices the alignment is not really used.
335c1bb86cdSEric Blake        With buffered I/O, we don't have any restrictions. */
336c1bb86cdSEric Blake     if (bdrv_is_sg(bs) || !s->needs_alignment) {
337c1bb86cdSEric Blake         bs->bl.request_alignment = 1;
338c1bb86cdSEric Blake         s->buf_align = 1;
339c1bb86cdSEric Blake         return;
340c1bb86cdSEric Blake     }
341c1bb86cdSEric Blake 
342c1bb86cdSEric Blake     bs->bl.request_alignment = 0;
343c1bb86cdSEric Blake     s->buf_align = 0;
344c1bb86cdSEric Blake     /* Let's try to use the logical blocksize for the alignment. */
345c1bb86cdSEric Blake     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
346c1bb86cdSEric Blake         bs->bl.request_alignment = 0;
347c1bb86cdSEric Blake     }
348c1bb86cdSEric Blake #ifdef CONFIG_XFS
349c1bb86cdSEric Blake     if (s->is_xfs) {
350c1bb86cdSEric Blake         struct dioattr da;
351c1bb86cdSEric Blake         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
352c1bb86cdSEric Blake             bs->bl.request_alignment = da.d_miniosz;
353c1bb86cdSEric Blake             /* The kernel returns wrong information for d_mem */
354c1bb86cdSEric Blake             /* s->buf_align = da.d_mem; */
355c1bb86cdSEric Blake         }
356c1bb86cdSEric Blake     }
357c1bb86cdSEric Blake #endif
358c1bb86cdSEric Blake 
359a6b257a0SNir Soffer     /*
360a6b257a0SNir Soffer      * If we could not get the sizes so far, we can only guess them. First try
361a6b257a0SNir Soffer      * to detect request alignment, since it is more likely to succeed. Then
362a6b257a0SNir Soffer      * try to detect buf_align, which cannot be detected in some cases (e.g.
363a6b257a0SNir Soffer      * Gluster). If buf_align cannot be detected, we fallback to the value of
364a6b257a0SNir Soffer      * request_alignment.
365a6b257a0SNir Soffer      */
366a6b257a0SNir Soffer 
367a6b257a0SNir Soffer     if (!bs->bl.request_alignment) {
368a6b257a0SNir Soffer         int i;
369c1bb86cdSEric Blake         size_t align;
370a6b257a0SNir Soffer         buf = qemu_memalign(max_align, max_align);
371a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
372a6b257a0SNir Soffer             align = alignments[i];
373a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf, align)) {
374a6b257a0SNir Soffer                 /* Fallback to safe value. */
375a6b257a0SNir Soffer                 bs->bl.request_alignment = (align != 1) ? align : max_align;
376c1bb86cdSEric Blake                 break;
377c1bb86cdSEric Blake             }
378c1bb86cdSEric Blake         }
379c1bb86cdSEric Blake         qemu_vfree(buf);
380c1bb86cdSEric Blake     }
381c1bb86cdSEric Blake 
382a6b257a0SNir Soffer     if (!s->buf_align) {
383a6b257a0SNir Soffer         int i;
384c1bb86cdSEric Blake         size_t align;
385a6b257a0SNir Soffer         buf = qemu_memalign(max_align, 2 * max_align);
386a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
387a6b257a0SNir Soffer             align = alignments[i];
388a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf + align, max_align)) {
389236094c7SStefan Hajnoczi                 /* Fallback to request_alignment. */
390a6b257a0SNir Soffer                 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
391c1bb86cdSEric Blake                 break;
392c1bb86cdSEric Blake             }
393c1bb86cdSEric Blake         }
394c1bb86cdSEric Blake         qemu_vfree(buf);
395c1bb86cdSEric Blake     }
396c1bb86cdSEric Blake 
397c1bb86cdSEric Blake     if (!s->buf_align || !bs->bl.request_alignment) {
398c1bb86cdSEric Blake         error_setg(errp, "Could not find working O_DIRECT alignment");
399c1bb86cdSEric Blake         error_append_hint(errp, "Try cache.direct=off\n");
400c1bb86cdSEric Blake     }
401c1bb86cdSEric Blake }
402c1bb86cdSEric Blake 
40323dece19SKevin Wolf static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
404c1bb86cdSEric Blake {
40523dece19SKevin Wolf     bool read_write = false;
406c1bb86cdSEric Blake     assert(open_flags != NULL);
407c1bb86cdSEric Blake 
408c1bb86cdSEric Blake     *open_flags |= O_BINARY;
409c1bb86cdSEric Blake     *open_flags &= ~O_ACCMODE;
41023dece19SKevin Wolf 
41123dece19SKevin Wolf     if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
41223dece19SKevin Wolf         read_write = has_writers;
41323dece19SKevin Wolf     } else if (bdrv_flags & BDRV_O_RDWR) {
41423dece19SKevin Wolf         read_write = true;
41523dece19SKevin Wolf     }
41623dece19SKevin Wolf 
41723dece19SKevin Wolf     if (read_write) {
418c1bb86cdSEric Blake         *open_flags |= O_RDWR;
419c1bb86cdSEric Blake     } else {
420c1bb86cdSEric Blake         *open_flags |= O_RDONLY;
421c1bb86cdSEric Blake     }
422c1bb86cdSEric Blake 
423c1bb86cdSEric Blake     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
424c1bb86cdSEric Blake      * and O_DIRECT for no caching. */
425c1bb86cdSEric Blake     if ((bdrv_flags & BDRV_O_NOCACHE)) {
426c1bb86cdSEric Blake         *open_flags |= O_DIRECT;
427c1bb86cdSEric Blake     }
428c1bb86cdSEric Blake }
429c1bb86cdSEric Blake 
430c1bb86cdSEric Blake static void raw_parse_filename(const char *filename, QDict *options,
431c1bb86cdSEric Blake                                Error **errp)
432c1bb86cdSEric Blake {
43303c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "file:", options);
434c1bb86cdSEric Blake }
435c1bb86cdSEric Blake 
436c1bb86cdSEric Blake static QemuOptsList raw_runtime_opts = {
437c1bb86cdSEric Blake     .name = "raw",
438c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
439c1bb86cdSEric Blake     .desc = {
440c1bb86cdSEric Blake         {
441c1bb86cdSEric Blake             .name = "filename",
442c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
443c1bb86cdSEric Blake             .help = "File name of the image",
444c1bb86cdSEric Blake         },
445c1bb86cdSEric Blake         {
446c1bb86cdSEric Blake             .name = "aio",
447c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
448c6447510SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
449c1bb86cdSEric Blake         },
45016b48d5dSFam Zheng         {
45116b48d5dSFam Zheng             .name = "locking",
45216b48d5dSFam Zheng             .type = QEMU_OPT_STRING,
45316b48d5dSFam Zheng             .help = "file locking mode (on/off/auto, default: auto)",
45416b48d5dSFam Zheng         },
4557c9e5276SPaolo Bonzini         {
4567c9e5276SPaolo Bonzini             .name = "pr-manager",
4577c9e5276SPaolo Bonzini             .type = QEMU_OPT_STRING,
4587c9e5276SPaolo Bonzini             .help = "id of persistent reservation manager object (default: none)",
4597c9e5276SPaolo Bonzini         },
460f357fcd8SStefan Hajnoczi #if defined(__linux__)
461f357fcd8SStefan Hajnoczi         {
462f357fcd8SStefan Hajnoczi             .name = "drop-cache",
463f357fcd8SStefan Hajnoczi             .type = QEMU_OPT_BOOL,
464f357fcd8SStefan Hajnoczi             .help = "invalidate page cache during live migration (default: on)",
465f357fcd8SStefan Hajnoczi         },
466f357fcd8SStefan Hajnoczi #endif
46731be8a2aSStefan Hajnoczi         {
46831be8a2aSStefan Hajnoczi             .name = "x-check-cache-dropped",
46931be8a2aSStefan Hajnoczi             .type = QEMU_OPT_BOOL,
47031be8a2aSStefan Hajnoczi             .help = "check that page cache was dropped on live migration (default: off)"
47131be8a2aSStefan Hajnoczi         },
472c1bb86cdSEric Blake         { /* end of list */ }
473c1bb86cdSEric Blake     },
474c1bb86cdSEric Blake };
475c1bb86cdSEric Blake 
4768a2ce0bcSAlberto Garcia static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
4778a2ce0bcSAlberto Garcia 
478c1bb86cdSEric Blake static int raw_open_common(BlockDriverState *bs, QDict *options,
479230ff739SJohn Snow                            int bdrv_flags, int open_flags,
480230ff739SJohn Snow                            bool device, Error **errp)
481c1bb86cdSEric Blake {
482c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
483c1bb86cdSEric Blake     QemuOpts *opts;
484c1bb86cdSEric Blake     Error *local_err = NULL;
485c1bb86cdSEric Blake     const char *filename = NULL;
4867c9e5276SPaolo Bonzini     const char *str;
487c1bb86cdSEric Blake     BlockdevAioOptions aio, aio_default;
488c1bb86cdSEric Blake     int fd, ret;
489c1bb86cdSEric Blake     struct stat st;
490244a5668SFam Zheng     OnOffAuto locking;
491c1bb86cdSEric Blake 
492c1bb86cdSEric Blake     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
493*af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
494c1bb86cdSEric Blake         ret = -EINVAL;
495c1bb86cdSEric Blake         goto fail;
496c1bb86cdSEric Blake     }
497c1bb86cdSEric Blake 
498c1bb86cdSEric Blake     filename = qemu_opt_get(opts, "filename");
499c1bb86cdSEric Blake 
500db0754dfSFam Zheng     ret = raw_normalize_devicepath(&filename, errp);
501c1bb86cdSEric Blake     if (ret != 0) {
502c1bb86cdSEric Blake         goto fail;
503c1bb86cdSEric Blake     }
504c1bb86cdSEric Blake 
505c6447510SAarushi Mehta     if (bdrv_flags & BDRV_O_NATIVE_AIO) {
506c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
507c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
508c6447510SAarushi Mehta     } else if (bdrv_flags & BDRV_O_IO_URING) {
509c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
510c6447510SAarushi Mehta #endif
511c6447510SAarushi Mehta     } else {
512c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
513c6447510SAarushi Mehta     }
514c6447510SAarushi Mehta 
515f7abe0ecSMarc-André Lureau     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
516f7abe0ecSMarc-André Lureau                           qemu_opt_get(opts, "aio"),
51706c60b6cSMarkus Armbruster                           aio_default, &local_err);
518c1bb86cdSEric Blake     if (local_err) {
519c1bb86cdSEric Blake         error_propagate(errp, local_err);
520c1bb86cdSEric Blake         ret = -EINVAL;
521c1bb86cdSEric Blake         goto fail;
522c1bb86cdSEric Blake     }
523c6447510SAarushi Mehta 
524c1bb86cdSEric Blake     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
525c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
526c6447510SAarushi Mehta     s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
527c6447510SAarushi Mehta #endif
528c1bb86cdSEric Blake 
529f7abe0ecSMarc-André Lureau     locking = qapi_enum_parse(&OnOffAuto_lookup,
530f7abe0ecSMarc-André Lureau                               qemu_opt_get(opts, "locking"),
53106c60b6cSMarkus Armbruster                               ON_OFF_AUTO_AUTO, &local_err);
532244a5668SFam Zheng     if (local_err) {
533244a5668SFam Zheng         error_propagate(errp, local_err);
534244a5668SFam Zheng         ret = -EINVAL;
535244a5668SFam Zheng         goto fail;
536244a5668SFam Zheng     }
537244a5668SFam Zheng     switch (locking) {
538244a5668SFam Zheng     case ON_OFF_AUTO_ON:
539244a5668SFam Zheng         s->use_lock = true;
5402b218f5dSFam Zheng         if (!qemu_has_ofd_lock()) {
541db0754dfSFam Zheng             warn_report("File lock requested but OFD locking syscall is "
542db0754dfSFam Zheng                         "unavailable, falling back to POSIX file locks");
543db0754dfSFam Zheng             error_printf("Due to the implementation, locks can be lost "
5442b218f5dSFam Zheng                          "unexpectedly.\n");
5452b218f5dSFam Zheng         }
546244a5668SFam Zheng         break;
547244a5668SFam Zheng     case ON_OFF_AUTO_OFF:
548244a5668SFam Zheng         s->use_lock = false;
549244a5668SFam Zheng         break;
550244a5668SFam Zheng     case ON_OFF_AUTO_AUTO:
5512b218f5dSFam Zheng         s->use_lock = qemu_has_ofd_lock();
552244a5668SFam Zheng         break;
553244a5668SFam Zheng     default:
554244a5668SFam Zheng         abort();
555244a5668SFam Zheng     }
556244a5668SFam Zheng 
5577c9e5276SPaolo Bonzini     str = qemu_opt_get(opts, "pr-manager");
5587c9e5276SPaolo Bonzini     if (str) {
5597c9e5276SPaolo Bonzini         s->pr_mgr = pr_manager_lookup(str, &local_err);
5607c9e5276SPaolo Bonzini         if (local_err) {
5617c9e5276SPaolo Bonzini             error_propagate(errp, local_err);
5627c9e5276SPaolo Bonzini             ret = -EINVAL;
5637c9e5276SPaolo Bonzini             goto fail;
5647c9e5276SPaolo Bonzini         }
5657c9e5276SPaolo Bonzini     }
5667c9e5276SPaolo Bonzini 
567f357fcd8SStefan Hajnoczi     s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
56831be8a2aSStefan Hajnoczi     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
56931be8a2aSStefan Hajnoczi                                                false);
57031be8a2aSStefan Hajnoczi 
571c1bb86cdSEric Blake     s->open_flags = open_flags;
57223dece19SKevin Wolf     raw_parse_flags(bdrv_flags, &s->open_flags, false);
573c1bb86cdSEric Blake 
574c1bb86cdSEric Blake     s->fd = -1;
575c1bb86cdSEric Blake     fd = qemu_open(filename, s->open_flags, 0644);
57664107dc0SKevin Wolf     ret = fd < 0 ? -errno : 0;
57764107dc0SKevin Wolf 
57864107dc0SKevin Wolf     if (ret < 0) {
579f6fc1e30SPaolo Bonzini         error_setg_file_open(errp, -ret, filename);
580c1bb86cdSEric Blake         if (ret == -EROFS) {
581c1bb86cdSEric Blake             ret = -EACCES;
582c1bb86cdSEric Blake         }
583c1bb86cdSEric Blake         goto fail;
584c1bb86cdSEric Blake     }
585c1bb86cdSEric Blake     s->fd = fd;
586c1bb86cdSEric Blake 
587244a5668SFam Zheng     s->perm = 0;
588244a5668SFam Zheng     s->shared_perm = BLK_PERM_ALL;
589244a5668SFam Zheng 
590c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
591c1bb86cdSEric Blake      /* Currently Linux does AIO only for files opened with O_DIRECT */
592ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
593ed6e2161SNishanth Aravamudan         if (!(s->open_flags & O_DIRECT)) {
594c1bb86cdSEric Blake             error_setg(errp, "aio=native was specified, but it requires "
595c1bb86cdSEric Blake                              "cache.direct=on, which was not specified.");
596c1bb86cdSEric Blake             ret = -EINVAL;
597c1bb86cdSEric Blake             goto fail;
598c1bb86cdSEric Blake         }
599ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
600ed6e2161SNishanth Aravamudan             error_prepend(errp, "Unable to use native AIO: ");
601ed6e2161SNishanth Aravamudan             goto fail;
602ed6e2161SNishanth Aravamudan         }
603ed6e2161SNishanth Aravamudan     }
604c1bb86cdSEric Blake #else
605c1bb86cdSEric Blake     if (s->use_linux_aio) {
606c1bb86cdSEric Blake         error_setg(errp, "aio=native was specified, but is not supported "
607c1bb86cdSEric Blake                          "in this build.");
608c1bb86cdSEric Blake         ret = -EINVAL;
609c1bb86cdSEric Blake         goto fail;
610c1bb86cdSEric Blake     }
611c1bb86cdSEric Blake #endif /* !defined(CONFIG_LINUX_AIO) */
612c1bb86cdSEric Blake 
613c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
614c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
615c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
616c6447510SAarushi Mehta             error_prepend(errp, "Unable to use io_uring: ");
617c6447510SAarushi Mehta             goto fail;
618c6447510SAarushi Mehta         }
619c6447510SAarushi Mehta     }
620c6447510SAarushi Mehta #else
621c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
622c6447510SAarushi Mehta         error_setg(errp, "aio=io_uring was specified, but is not supported "
623c6447510SAarushi Mehta                          "in this build.");
624c6447510SAarushi Mehta         ret = -EINVAL;
625c6447510SAarushi Mehta         goto fail;
626c6447510SAarushi Mehta     }
627c6447510SAarushi Mehta #endif /* !defined(CONFIG_LINUX_IO_URING) */
628c6447510SAarushi Mehta 
629c1bb86cdSEric Blake     s->has_discard = true;
630c1bb86cdSEric Blake     s->has_write_zeroes = true;
631c1bb86cdSEric Blake     if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
632c1bb86cdSEric Blake         s->needs_alignment = true;
633c1bb86cdSEric Blake     }
634c1bb86cdSEric Blake 
635c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
636c1bb86cdSEric Blake         ret = -errno;
637c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not stat file");
638c1bb86cdSEric Blake         goto fail;
639c1bb86cdSEric Blake     }
640230ff739SJohn Snow 
641230ff739SJohn Snow     if (!device) {
642230ff739SJohn Snow         if (S_ISBLK(st.st_mode)) {
643230ff739SJohn Snow             warn_report("Opening a block device as a file using the '%s' "
644230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
645230ff739SJohn Snow         } else if (S_ISCHR(st.st_mode)) {
646230ff739SJohn Snow             warn_report("Opening a character device as a file using the '%s' "
647230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
648230ff739SJohn Snow         } else if (!S_ISREG(st.st_mode)) {
649230ff739SJohn Snow             error_setg(errp, "A regular file was expected by the '%s' driver, "
650230ff739SJohn Snow                        "but something else was given", bs->drv->format_name);
651230ff739SJohn Snow             ret = -EINVAL;
652230ff739SJohn Snow             goto fail;
653230ff739SJohn Snow         } else {
654c1bb86cdSEric Blake             s->discard_zeroes = true;
655c1bb86cdSEric Blake             s->has_fallocate = true;
656c1bb86cdSEric Blake         }
657230ff739SJohn Snow     } else {
658230ff739SJohn Snow         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
659230ff739SJohn Snow             error_setg(errp, "'%s' driver expects either "
660230ff739SJohn Snow                        "a character or block device", bs->drv->format_name);
661230ff739SJohn Snow             ret = -EINVAL;
662230ff739SJohn Snow             goto fail;
663230ff739SJohn Snow         }
664230ff739SJohn Snow     }
665230ff739SJohn Snow 
666c1bb86cdSEric Blake     if (S_ISBLK(st.st_mode)) {
667c1bb86cdSEric Blake #ifdef BLKDISCARDZEROES
668c1bb86cdSEric Blake         unsigned int arg;
669c1bb86cdSEric Blake         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
670c1bb86cdSEric Blake             s->discard_zeroes = true;
671c1bb86cdSEric Blake         }
672c1bb86cdSEric Blake #endif
673c1bb86cdSEric Blake #ifdef __linux__
674c1bb86cdSEric Blake         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
675c1bb86cdSEric Blake          * not rely on the contents of discarded blocks unless using O_DIRECT.
676c1bb86cdSEric Blake          * Same for BLKZEROOUT.
677c1bb86cdSEric Blake          */
678c1bb86cdSEric Blake         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
679c1bb86cdSEric Blake             s->discard_zeroes = false;
680c1bb86cdSEric Blake             s->has_write_zeroes = false;
681c1bb86cdSEric Blake         }
682c1bb86cdSEric Blake #endif
683c1bb86cdSEric Blake     }
684c1bb86cdSEric Blake #ifdef __FreeBSD__
685c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode)) {
686c1bb86cdSEric Blake         /*
687c1bb86cdSEric Blake          * The file is a char device (disk), which on FreeBSD isn't behind
688c1bb86cdSEric Blake          * a pager, so force all requests to be aligned. This is needed
689c1bb86cdSEric Blake          * so QEMU makes sure all IO operations on the device are aligned
690c1bb86cdSEric Blake          * to sector size, or else FreeBSD will reject them with EINVAL.
691c1bb86cdSEric Blake          */
692c1bb86cdSEric Blake         s->needs_alignment = true;
693c1bb86cdSEric Blake     }
694c1bb86cdSEric Blake #endif
695c1bb86cdSEric Blake 
696c1bb86cdSEric Blake #ifdef CONFIG_XFS
697c1bb86cdSEric Blake     if (platform_test_xfs_fd(s->fd)) {
698c1bb86cdSEric Blake         s->is_xfs = true;
699c1bb86cdSEric Blake     }
700c1bb86cdSEric Blake #endif
701c1bb86cdSEric Blake 
702738301e1SKevin Wolf     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
7032f0c6e7aSKevin Wolf     if (S_ISREG(st.st_mode)) {
7042f0c6e7aSKevin Wolf         /* When extending regular files, we get zeros from the OS */
7052f0c6e7aSKevin Wolf         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
7062f0c6e7aSKevin Wolf     }
707c1bb86cdSEric Blake     ret = 0;
708c1bb86cdSEric Blake fail:
709c1bb86cdSEric Blake     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
710c1bb86cdSEric Blake         unlink(filename);
711c1bb86cdSEric Blake     }
712c1bb86cdSEric Blake     qemu_opts_del(opts);
713c1bb86cdSEric Blake     return ret;
714c1bb86cdSEric Blake }
715c1bb86cdSEric Blake 
716c1bb86cdSEric Blake static int raw_open(BlockDriverState *bs, QDict *options, int flags,
717c1bb86cdSEric Blake                     Error **errp)
718c1bb86cdSEric Blake {
719c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
720c1bb86cdSEric Blake 
721c1bb86cdSEric Blake     s->type = FTYPE_FILE;
722230ff739SJohn Snow     return raw_open_common(bs, options, flags, 0, false, errp);
723c1bb86cdSEric Blake }
724c1bb86cdSEric Blake 
725244a5668SFam Zheng typedef enum {
726244a5668SFam Zheng     RAW_PL_PREPARE,
727244a5668SFam Zheng     RAW_PL_COMMIT,
728244a5668SFam Zheng     RAW_PL_ABORT,
729244a5668SFam Zheng } RawPermLockOp;
730244a5668SFam Zheng 
731244a5668SFam Zheng #define PERM_FOREACH(i) \
732244a5668SFam Zheng     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
733244a5668SFam Zheng 
734244a5668SFam Zheng /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
735244a5668SFam Zheng  * file; if @unlock == true, also unlock the unneeded bytes.
736244a5668SFam Zheng  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
737244a5668SFam Zheng  */
7382996ffadSFam Zheng static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
739244a5668SFam Zheng                                 uint64_t perm_lock_bits,
740244a5668SFam Zheng                                 uint64_t shared_perm_lock_bits,
741244a5668SFam Zheng                                 bool unlock, Error **errp)
742244a5668SFam Zheng {
743244a5668SFam Zheng     int ret;
744244a5668SFam Zheng     int i;
7452996ffadSFam Zheng     uint64_t locked_perm, locked_shared_perm;
7462996ffadSFam Zheng 
7472996ffadSFam Zheng     if (s) {
7482996ffadSFam Zheng         locked_perm = s->locked_perm;
7492996ffadSFam Zheng         locked_shared_perm = s->locked_shared_perm;
7502996ffadSFam Zheng     } else {
7512996ffadSFam Zheng         /*
7522996ffadSFam Zheng          * We don't have the previous bits, just lock/unlock for each of the
7532996ffadSFam Zheng          * requested bits.
7542996ffadSFam Zheng          */
7552996ffadSFam Zheng         if (unlock) {
7562996ffadSFam Zheng             locked_perm = BLK_PERM_ALL;
7572996ffadSFam Zheng             locked_shared_perm = BLK_PERM_ALL;
7582996ffadSFam Zheng         } else {
7592996ffadSFam Zheng             locked_perm = 0;
7602996ffadSFam Zheng             locked_shared_perm = 0;
7612996ffadSFam Zheng         }
7622996ffadSFam Zheng     }
763244a5668SFam Zheng 
764244a5668SFam Zheng     PERM_FOREACH(i) {
765244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
7662996ffadSFam Zheng         uint64_t bit = (1ULL << i);
7672996ffadSFam Zheng         if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
768d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
769244a5668SFam Zheng             if (ret) {
770244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
771244a5668SFam Zheng                 return ret;
7722996ffadSFam Zheng             } else if (s) {
7732996ffadSFam Zheng                 s->locked_perm |= bit;
774244a5668SFam Zheng             }
7752996ffadSFam Zheng         } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
776d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
777244a5668SFam Zheng             if (ret) {
778244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
779244a5668SFam Zheng                 return ret;
7802996ffadSFam Zheng             } else if (s) {
7812996ffadSFam Zheng                 s->locked_perm &= ~bit;
782244a5668SFam Zheng             }
783244a5668SFam Zheng         }
784244a5668SFam Zheng     }
785244a5668SFam Zheng     PERM_FOREACH(i) {
786244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
7872996ffadSFam Zheng         uint64_t bit = (1ULL << i);
7882996ffadSFam Zheng         if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
789d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
790244a5668SFam Zheng             if (ret) {
791244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
792244a5668SFam Zheng                 return ret;
7932996ffadSFam Zheng             } else if (s) {
7942996ffadSFam Zheng                 s->locked_shared_perm |= bit;
795244a5668SFam Zheng             }
7962996ffadSFam Zheng         } else if (unlock && (locked_shared_perm & bit) &&
7972996ffadSFam Zheng                    !(shared_perm_lock_bits & bit)) {
798d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
799244a5668SFam Zheng             if (ret) {
800244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
801244a5668SFam Zheng                 return ret;
8022996ffadSFam Zheng             } else if (s) {
8032996ffadSFam Zheng                 s->locked_shared_perm &= ~bit;
804244a5668SFam Zheng             }
805244a5668SFam Zheng         }
806244a5668SFam Zheng     }
807244a5668SFam Zheng     return 0;
808244a5668SFam Zheng }
809244a5668SFam Zheng 
810244a5668SFam Zheng /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
811d0a96155SMax Reitz static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
812244a5668SFam Zheng                                 Error **errp)
813244a5668SFam Zheng {
814244a5668SFam Zheng     int ret;
815244a5668SFam Zheng     int i;
816244a5668SFam Zheng 
817244a5668SFam Zheng     PERM_FOREACH(i) {
818244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
819244a5668SFam Zheng         uint64_t p = 1ULL << i;
820244a5668SFam Zheng         if (perm & p) {
821d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
822244a5668SFam Zheng             if (ret) {
823244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
824244a5668SFam Zheng                 error_setg(errp,
825244a5668SFam Zheng                            "Failed to get \"%s\" lock",
826244a5668SFam Zheng                            perm_name);
827244a5668SFam Zheng                 g_free(perm_name);
828244a5668SFam Zheng                 return ret;
829244a5668SFam Zheng             }
830244a5668SFam Zheng         }
831244a5668SFam Zheng     }
832244a5668SFam Zheng     PERM_FOREACH(i) {
833244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
834244a5668SFam Zheng         uint64_t p = 1ULL << i;
835244a5668SFam Zheng         if (!(shared_perm & p)) {
836d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
837244a5668SFam Zheng             if (ret) {
838244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
839244a5668SFam Zheng                 error_setg(errp,
840244a5668SFam Zheng                            "Failed to get shared \"%s\" lock",
841244a5668SFam Zheng                            perm_name);
842244a5668SFam Zheng                 g_free(perm_name);
843244a5668SFam Zheng                 return ret;
844244a5668SFam Zheng             }
845244a5668SFam Zheng         }
846244a5668SFam Zheng     }
847244a5668SFam Zheng     return 0;
848244a5668SFam Zheng }
849244a5668SFam Zheng 
850244a5668SFam Zheng static int raw_handle_perm_lock(BlockDriverState *bs,
851244a5668SFam Zheng                                 RawPermLockOp op,
852244a5668SFam Zheng                                 uint64_t new_perm, uint64_t new_shared,
853244a5668SFam Zheng                                 Error **errp)
854244a5668SFam Zheng {
855244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
856244a5668SFam Zheng     int ret = 0;
857244a5668SFam Zheng     Error *local_err = NULL;
858244a5668SFam Zheng 
859244a5668SFam Zheng     if (!s->use_lock) {
860244a5668SFam Zheng         return 0;
861244a5668SFam Zheng     }
862244a5668SFam Zheng 
863244a5668SFam Zheng     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
864244a5668SFam Zheng         return 0;
865244a5668SFam Zheng     }
866244a5668SFam Zheng 
867244a5668SFam Zheng     switch (op) {
868244a5668SFam Zheng     case RAW_PL_PREPARE:
869696aaaedSVladimir Sementsov-Ogievskiy         if ((s->perm | new_perm) == s->perm &&
870696aaaedSVladimir Sementsov-Ogievskiy             (s->shared_perm & new_shared) == s->shared_perm)
871696aaaedSVladimir Sementsov-Ogievskiy         {
872696aaaedSVladimir Sementsov-Ogievskiy             /*
873696aaaedSVladimir Sementsov-Ogievskiy              * We are going to unlock bytes, it should not fail. If it fail due
874696aaaedSVladimir Sementsov-Ogievskiy              * to some fs-dependent permission-unrelated reasons (which occurs
875696aaaedSVladimir Sementsov-Ogievskiy              * sometimes on NFS and leads to abort in bdrv_replace_child) we
876696aaaedSVladimir Sementsov-Ogievskiy              * can't prevent such errors by any check here. And we ignore them
877696aaaedSVladimir Sementsov-Ogievskiy              * anyway in ABORT and COMMIT.
878696aaaedSVladimir Sementsov-Ogievskiy              */
879696aaaedSVladimir Sementsov-Ogievskiy             return 0;
880696aaaedSVladimir Sementsov-Ogievskiy         }
881f2e3af29SFam Zheng         ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
882244a5668SFam Zheng                                    ~s->shared_perm | ~new_shared,
883244a5668SFam Zheng                                    false, errp);
884244a5668SFam Zheng         if (!ret) {
885f2e3af29SFam Zheng             ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
886244a5668SFam Zheng             if (!ret) {
887244a5668SFam Zheng                 return 0;
888244a5668SFam Zheng             }
889b857431dSFam Zheng             error_append_hint(errp,
890b857431dSFam Zheng                               "Is another process using the image [%s]?\n",
891b857431dSFam Zheng                               bs->filename);
892244a5668SFam Zheng         }
893244a5668SFam Zheng         /* fall through to unlock bytes. */
894244a5668SFam Zheng     case RAW_PL_ABORT:
895f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
896d0a96155SMax Reitz                              true, &local_err);
897244a5668SFam Zheng         if (local_err) {
898244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
899244a5668SFam Zheng              * fail. Something weird happened, report it.
900244a5668SFam Zheng              */
901db0754dfSFam Zheng             warn_report_err(local_err);
902244a5668SFam Zheng         }
903244a5668SFam Zheng         break;
904244a5668SFam Zheng     case RAW_PL_COMMIT:
905f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
906d0a96155SMax Reitz                              true, &local_err);
907244a5668SFam Zheng         if (local_err) {
908244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
909244a5668SFam Zheng              * fail. Something weird happened, report it.
910244a5668SFam Zheng              */
911db0754dfSFam Zheng             warn_report_err(local_err);
912244a5668SFam Zheng         }
913244a5668SFam Zheng         break;
914244a5668SFam Zheng     }
915244a5668SFam Zheng     return ret;
916244a5668SFam Zheng }
917244a5668SFam Zheng 
9185cec2870SKevin Wolf static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
91923dece19SKevin Wolf                                  int *open_flags, uint64_t perm, bool force_dup,
9206ceabe6fSKevin Wolf                                  Error **errp)
9215cec2870SKevin Wolf {
9225cec2870SKevin Wolf     BDRVRawState *s = bs->opaque;
9235cec2870SKevin Wolf     int fd = -1;
9245cec2870SKevin Wolf     int ret;
92523dece19SKevin Wolf     bool has_writers = perm &
92623dece19SKevin Wolf         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
9275cec2870SKevin Wolf     int fcntl_flags = O_APPEND | O_NONBLOCK;
9285cec2870SKevin Wolf #ifdef O_NOATIME
9295cec2870SKevin Wolf     fcntl_flags |= O_NOATIME;
9305cec2870SKevin Wolf #endif
9315cec2870SKevin Wolf 
9325cec2870SKevin Wolf     *open_flags = 0;
9335cec2870SKevin Wolf     if (s->type == FTYPE_CD) {
9345cec2870SKevin Wolf         *open_flags |= O_NONBLOCK;
9355cec2870SKevin Wolf     }
9365cec2870SKevin Wolf 
93723dece19SKevin Wolf     raw_parse_flags(flags, open_flags, has_writers);
9385cec2870SKevin Wolf 
9395cec2870SKevin Wolf #ifdef O_ASYNC
9405cec2870SKevin Wolf     /* Not all operating systems have O_ASYNC, and those that don't
9415cec2870SKevin Wolf      * will not let us track the state into rs->open_flags (typically
9425cec2870SKevin Wolf      * you achieve the same effect with an ioctl, for example I_SETSIG
9435cec2870SKevin Wolf      * on Solaris). But we do not use O_ASYNC, so that's fine.
9445cec2870SKevin Wolf      */
9455cec2870SKevin Wolf     assert((s->open_flags & O_ASYNC) == 0);
9465cec2870SKevin Wolf #endif
9475cec2870SKevin Wolf 
9486ceabe6fSKevin Wolf     if (!force_dup && *open_flags == s->open_flags) {
9496ceabe6fSKevin Wolf         /* We're lucky, the existing fd is fine */
9506ceabe6fSKevin Wolf         return s->fd;
9516ceabe6fSKevin Wolf     }
9526ceabe6fSKevin Wolf 
9535cec2870SKevin Wolf     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
9545cec2870SKevin Wolf         /* dup the original fd */
9555cec2870SKevin Wolf         fd = qemu_dup(s->fd);
9565cec2870SKevin Wolf         if (fd >= 0) {
9575cec2870SKevin Wolf             ret = fcntl_setfl(fd, *open_flags);
9585cec2870SKevin Wolf             if (ret) {
9595cec2870SKevin Wolf                 qemu_close(fd);
9605cec2870SKevin Wolf                 fd = -1;
9615cec2870SKevin Wolf             }
9625cec2870SKevin Wolf         }
9635cec2870SKevin Wolf     }
9645cec2870SKevin Wolf 
9655cec2870SKevin Wolf     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
9665cec2870SKevin Wolf     if (fd == -1) {
9675cec2870SKevin Wolf         const char *normalized_filename = bs->filename;
9685cec2870SKevin Wolf         ret = raw_normalize_devicepath(&normalized_filename, errp);
9695cec2870SKevin Wolf         if (ret >= 0) {
9705cec2870SKevin Wolf             assert(!(*open_flags & O_CREAT));
9715cec2870SKevin Wolf             fd = qemu_open(normalized_filename, *open_flags);
9725cec2870SKevin Wolf             if (fd == -1) {
9735cec2870SKevin Wolf                 error_setg_errno(errp, errno, "Could not reopen file");
9745cec2870SKevin Wolf                 return -1;
9755cec2870SKevin Wolf             }
9765cec2870SKevin Wolf         }
9775cec2870SKevin Wolf     }
9785cec2870SKevin Wolf 
9795cec2870SKevin Wolf     return fd;
9805cec2870SKevin Wolf }
9815cec2870SKevin Wolf 
982c1bb86cdSEric Blake static int raw_reopen_prepare(BDRVReopenState *state,
983c1bb86cdSEric Blake                               BlockReopenQueue *queue, Error **errp)
984c1bb86cdSEric Blake {
985c1bb86cdSEric Blake     BDRVRawState *s;
986c1bb86cdSEric Blake     BDRVRawReopenState *rs;
98731be8a2aSStefan Hajnoczi     QemuOpts *opts;
988a6aeca0cSKevin Wolf     int ret;
989c1bb86cdSEric Blake     Error *local_err = NULL;
990c1bb86cdSEric Blake 
991c1bb86cdSEric Blake     assert(state != NULL);
992c1bb86cdSEric Blake     assert(state->bs != NULL);
993c1bb86cdSEric Blake 
994c1bb86cdSEric Blake     s = state->bs->opaque;
995c1bb86cdSEric Blake 
996c1bb86cdSEric Blake     state->opaque = g_new0(BDRVRawReopenState, 1);
997c1bb86cdSEric Blake     rs = state->opaque;
99831be8a2aSStefan Hajnoczi 
99931be8a2aSStefan Hajnoczi     /* Handle options changes */
100031be8a2aSStefan Hajnoczi     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1001*af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
100231be8a2aSStefan Hajnoczi         ret = -EINVAL;
100331be8a2aSStefan Hajnoczi         goto out;
100431be8a2aSStefan Hajnoczi     }
100531be8a2aSStefan Hajnoczi 
1006f357fcd8SStefan Hajnoczi     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
10078d324575SAlberto Garcia     rs->check_cache_dropped =
10088d324575SAlberto Garcia         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
10098d324575SAlberto Garcia 
10108d324575SAlberto Garcia     /* This driver's reopen function doesn't currently allow changing
10118d324575SAlberto Garcia      * other options, so let's put them back in the original QDict and
10128d324575SAlberto Garcia      * bdrv_reopen_prepare() will detect changes and complain. */
10138d324575SAlberto Garcia     qemu_opts_to_qdict(opts, state->options);
1014c1bb86cdSEric Blake 
10155cec2870SKevin Wolf     rs->fd = raw_reconfigure_getfd(state->bs, state->flags, &rs->open_flags,
101623dece19SKevin Wolf                                    state->perm, true, &local_err);
10175cec2870SKevin Wolf     if (local_err) {
10185cec2870SKevin Wolf         error_propagate(errp, local_err);
1019c1bb86cdSEric Blake         ret = -1;
10205cec2870SKevin Wolf         goto out;
1021c1bb86cdSEric Blake     }
1022c1bb86cdSEric Blake 
1023c1bb86cdSEric Blake     /* Fail already reopen_prepare() if we can't get a working O_DIRECT
1024c1bb86cdSEric Blake      * alignment with the new fd. */
1025c1bb86cdSEric Blake     if (rs->fd != -1) {
1026c1bb86cdSEric Blake         raw_probe_alignment(state->bs, rs->fd, &local_err);
1027c1bb86cdSEric Blake         if (local_err) {
1028c1bb86cdSEric Blake             error_propagate(errp, local_err);
1029c1bb86cdSEric Blake             ret = -EINVAL;
1030a6aeca0cSKevin Wolf             goto out_fd;
1031a6aeca0cSKevin Wolf         }
1032c1bb86cdSEric Blake     }
1033c1bb86cdSEric Blake 
1034e0c9cf3aSKevin Wolf     s->reopen_state = state;
1035a6aeca0cSKevin Wolf     ret = 0;
1036a6aeca0cSKevin Wolf out_fd:
1037a6aeca0cSKevin Wolf     if (ret < 0) {
1038a6aeca0cSKevin Wolf         qemu_close(rs->fd);
1039a6aeca0cSKevin Wolf         rs->fd = -1;
1040a6aeca0cSKevin Wolf     }
104131be8a2aSStefan Hajnoczi out:
104231be8a2aSStefan Hajnoczi     qemu_opts_del(opts);
1043c1bb86cdSEric Blake     return ret;
1044c1bb86cdSEric Blake }
1045c1bb86cdSEric Blake 
1046c1bb86cdSEric Blake static void raw_reopen_commit(BDRVReopenState *state)
1047c1bb86cdSEric Blake {
1048c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1049c1bb86cdSEric Blake     BDRVRawState *s = state->bs->opaque;
1050c1bb86cdSEric Blake 
1051f357fcd8SStefan Hajnoczi     s->drop_cache = rs->drop_cache;
105231be8a2aSStefan Hajnoczi     s->check_cache_dropped = rs->check_cache_dropped;
1053c1bb86cdSEric Blake     s->open_flags = rs->open_flags;
1054c1bb86cdSEric Blake 
1055c1bb86cdSEric Blake     qemu_close(s->fd);
1056c1bb86cdSEric Blake     s->fd = rs->fd;
1057c1bb86cdSEric Blake 
1058c1bb86cdSEric Blake     g_free(state->opaque);
1059c1bb86cdSEric Blake     state->opaque = NULL;
1060e0c9cf3aSKevin Wolf 
1061e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1062e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1063c1bb86cdSEric Blake }
1064c1bb86cdSEric Blake 
1065c1bb86cdSEric Blake 
1066c1bb86cdSEric Blake static void raw_reopen_abort(BDRVReopenState *state)
1067c1bb86cdSEric Blake {
1068c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1069e0c9cf3aSKevin Wolf     BDRVRawState *s = state->bs->opaque;
1070c1bb86cdSEric Blake 
1071c1bb86cdSEric Blake      /* nothing to do if NULL, we didn't get far enough */
1072c1bb86cdSEric Blake     if (rs == NULL) {
1073c1bb86cdSEric Blake         return;
1074c1bb86cdSEric Blake     }
1075c1bb86cdSEric Blake 
1076c1bb86cdSEric Blake     if (rs->fd >= 0) {
1077c1bb86cdSEric Blake         qemu_close(rs->fd);
1078c1bb86cdSEric Blake         rs->fd = -1;
1079c1bb86cdSEric Blake     }
1080c1bb86cdSEric Blake     g_free(state->opaque);
1081c1bb86cdSEric Blake     state->opaque = NULL;
1082e0c9cf3aSKevin Wolf 
1083e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1084e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1085c1bb86cdSEric Blake }
1086c1bb86cdSEric Blake 
1087867eccfeSMaxim Levitsky static int sg_get_max_transfer_length(int fd)
1088c1bb86cdSEric Blake {
1089c1bb86cdSEric Blake #ifdef BLKSECTGET
109048265250SEric Farman     int max_bytes = 0;
1091867eccfeSMaxim Levitsky 
1092867eccfeSMaxim Levitsky     if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
109348265250SEric Farman         return max_bytes;
1094c1bb86cdSEric Blake     } else {
1095c1bb86cdSEric Blake         return -errno;
1096c1bb86cdSEric Blake     }
1097c1bb86cdSEric Blake #else
1098c1bb86cdSEric Blake     return -ENOSYS;
1099c1bb86cdSEric Blake #endif
1100c1bb86cdSEric Blake }
1101c1bb86cdSEric Blake 
1102867eccfeSMaxim Levitsky static int sg_get_max_segments(int fd)
11039103f1ceSFam Zheng {
11049103f1ceSFam Zheng #ifdef CONFIG_LINUX
11059103f1ceSFam Zheng     char buf[32];
11069103f1ceSFam Zheng     const char *end;
1107867eccfeSMaxim Levitsky     char *sysfspath = NULL;
11089103f1ceSFam Zheng     int ret;
1109867eccfeSMaxim Levitsky     int sysfd = -1;
11109103f1ceSFam Zheng     long max_segments;
1111867eccfeSMaxim Levitsky     struct stat st;
1112867eccfeSMaxim Levitsky 
1113867eccfeSMaxim Levitsky     if (fstat(fd, &st)) {
1114867eccfeSMaxim Levitsky         ret = -errno;
1115867eccfeSMaxim Levitsky         goto out;
1116867eccfeSMaxim Levitsky     }
11179103f1ceSFam Zheng 
11189103f1ceSFam Zheng     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
1119867eccfeSMaxim Levitsky                                 major(st.st_rdev), minor(st.st_rdev));
1120867eccfeSMaxim Levitsky     sysfd = open(sysfspath, O_RDONLY);
1121867eccfeSMaxim Levitsky     if (sysfd == -1) {
11229103f1ceSFam Zheng         ret = -errno;
11239103f1ceSFam Zheng         goto out;
11249103f1ceSFam Zheng     }
11259103f1ceSFam Zheng     do {
1126867eccfeSMaxim Levitsky         ret = read(sysfd, buf, sizeof(buf) - 1);
11279103f1ceSFam Zheng     } while (ret == -1 && errno == EINTR);
11289103f1ceSFam Zheng     if (ret < 0) {
11299103f1ceSFam Zheng         ret = -errno;
11309103f1ceSFam Zheng         goto out;
11319103f1ceSFam Zheng     } else if (ret == 0) {
11329103f1ceSFam Zheng         ret = -EIO;
11339103f1ceSFam Zheng         goto out;
11349103f1ceSFam Zheng     }
11359103f1ceSFam Zheng     buf[ret] = 0;
11369103f1ceSFam Zheng     /* The file is ended with '\n', pass 'end' to accept that. */
11379103f1ceSFam Zheng     ret = qemu_strtol(buf, &end, 10, &max_segments);
11389103f1ceSFam Zheng     if (ret == 0 && end && *end == '\n') {
11399103f1ceSFam Zheng         ret = max_segments;
11409103f1ceSFam Zheng     }
11419103f1ceSFam Zheng 
11429103f1ceSFam Zheng out:
1143867eccfeSMaxim Levitsky     if (sysfd != -1) {
1144867eccfeSMaxim Levitsky         close(sysfd);
1145fed414dfSFam Zheng     }
11469103f1ceSFam Zheng     g_free(sysfspath);
11479103f1ceSFam Zheng     return ret;
11489103f1ceSFam Zheng #else
11499103f1ceSFam Zheng     return -ENOTSUP;
11509103f1ceSFam Zheng #endif
11519103f1ceSFam Zheng }
11529103f1ceSFam Zheng 
1153c1bb86cdSEric Blake static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1154c1bb86cdSEric Blake {
1155c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1156c1bb86cdSEric Blake 
1157867eccfeSMaxim Levitsky     if (bs->sg) {
1158867eccfeSMaxim Levitsky         int ret = sg_get_max_transfer_length(s->fd);
1159867eccfeSMaxim Levitsky 
116048265250SEric Farman         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
116148265250SEric Farman             bs->bl.max_transfer = pow2floor(ret);
1162c1bb86cdSEric Blake         }
1163867eccfeSMaxim Levitsky 
1164867eccfeSMaxim Levitsky         ret = sg_get_max_segments(s->fd);
11659103f1ceSFam Zheng         if (ret > 0) {
1166038adc2fSWei Yang             bs->bl.max_transfer = MIN(bs->bl.max_transfer,
1167038adc2fSWei Yang                                       ret * qemu_real_host_page_size);
1168c1bb86cdSEric Blake         }
1169c1bb86cdSEric Blake     }
1170c1bb86cdSEric Blake 
1171c1bb86cdSEric Blake     raw_probe_alignment(bs, s->fd, errp);
1172c1bb86cdSEric Blake     bs->bl.min_mem_alignment = s->buf_align;
1173038adc2fSWei Yang     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size);
1174c1bb86cdSEric Blake }
1175c1bb86cdSEric Blake 
1176c1bb86cdSEric Blake static int check_for_dasd(int fd)
1177c1bb86cdSEric Blake {
1178c1bb86cdSEric Blake #ifdef BIODASDINFO2
1179c1bb86cdSEric Blake     struct dasd_information2_t info = {0};
1180c1bb86cdSEric Blake 
1181c1bb86cdSEric Blake     return ioctl(fd, BIODASDINFO2, &info);
1182c1bb86cdSEric Blake #else
1183c1bb86cdSEric Blake     return -1;
1184c1bb86cdSEric Blake #endif
1185c1bb86cdSEric Blake }
1186c1bb86cdSEric Blake 
1187c1bb86cdSEric Blake /**
1188c1bb86cdSEric Blake  * Try to get @bs's logical and physical block size.
1189c1bb86cdSEric Blake  * On success, store them in @bsz and return zero.
1190c1bb86cdSEric Blake  * On failure, return negative errno.
1191c1bb86cdSEric Blake  */
1192c1bb86cdSEric Blake static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1193c1bb86cdSEric Blake {
1194c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1195c1bb86cdSEric Blake     int ret;
1196c1bb86cdSEric Blake 
1197c1bb86cdSEric Blake     /* If DASD, get blocksizes */
1198c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1199c1bb86cdSEric Blake         return -ENOTSUP;
1200c1bb86cdSEric Blake     }
1201c1bb86cdSEric Blake     ret = probe_logical_blocksize(s->fd, &bsz->log);
1202c1bb86cdSEric Blake     if (ret < 0) {
1203c1bb86cdSEric Blake         return ret;
1204c1bb86cdSEric Blake     }
1205c1bb86cdSEric Blake     return probe_physical_blocksize(s->fd, &bsz->phys);
1206c1bb86cdSEric Blake }
1207c1bb86cdSEric Blake 
1208c1bb86cdSEric Blake /**
1209c1bb86cdSEric Blake  * Try to get @bs's geometry: cyls, heads, sectors.
1210c1bb86cdSEric Blake  * On success, store them in @geo and return 0.
1211c1bb86cdSEric Blake  * On failure return -errno.
1212c1bb86cdSEric Blake  * (Allows block driver to assign default geometry values that guest sees)
1213c1bb86cdSEric Blake  */
1214c1bb86cdSEric Blake #ifdef __linux__
1215c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1216c1bb86cdSEric Blake {
1217c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1218c1bb86cdSEric Blake     struct hd_geometry ioctl_geo = {0};
1219c1bb86cdSEric Blake 
1220c1bb86cdSEric Blake     /* If DASD, get its geometry */
1221c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1222c1bb86cdSEric Blake         return -ENOTSUP;
1223c1bb86cdSEric Blake     }
1224c1bb86cdSEric Blake     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1225c1bb86cdSEric Blake         return -errno;
1226c1bb86cdSEric Blake     }
1227c1bb86cdSEric Blake     /* HDIO_GETGEO may return success even though geo contains zeros
1228c1bb86cdSEric Blake        (e.g. certain multipath setups) */
1229c1bb86cdSEric Blake     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1230c1bb86cdSEric Blake         return -ENOTSUP;
1231c1bb86cdSEric Blake     }
1232c1bb86cdSEric Blake     /* Do not return a geometry for partition */
1233c1bb86cdSEric Blake     if (ioctl_geo.start != 0) {
1234c1bb86cdSEric Blake         return -ENOTSUP;
1235c1bb86cdSEric Blake     }
1236c1bb86cdSEric Blake     geo->heads = ioctl_geo.heads;
1237c1bb86cdSEric Blake     geo->sectors = ioctl_geo.sectors;
1238c1bb86cdSEric Blake     geo->cylinders = ioctl_geo.cylinders;
1239c1bb86cdSEric Blake 
1240c1bb86cdSEric Blake     return 0;
1241c1bb86cdSEric Blake }
1242c1bb86cdSEric Blake #else /* __linux__ */
1243c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1244c1bb86cdSEric Blake {
1245c1bb86cdSEric Blake     return -ENOTSUP;
1246c1bb86cdSEric Blake }
1247c1bb86cdSEric Blake #endif
1248c1bb86cdSEric Blake 
124903425671SKevin Wolf #if defined(__linux__)
125003425671SKevin Wolf static int handle_aiocb_ioctl(void *opaque)
1251c1bb86cdSEric Blake {
125203425671SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1253c1bb86cdSEric Blake     int ret;
1254c1bb86cdSEric Blake 
1255d57c44d0SKevin Wolf     ret = ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf);
1256c1bb86cdSEric Blake     if (ret == -1) {
1257c1bb86cdSEric Blake         return -errno;
1258c1bb86cdSEric Blake     }
1259c1bb86cdSEric Blake 
1260c1bb86cdSEric Blake     return 0;
1261c1bb86cdSEric Blake }
126203425671SKevin Wolf #endif /* linux */
1263c1bb86cdSEric Blake 
126406dc9bd5SKevin Wolf static int handle_aiocb_flush(void *opaque)
1265c1bb86cdSEric Blake {
126606dc9bd5SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1267e5bcf967SKevin Wolf     BDRVRawState *s = aiocb->bs->opaque;
1268c1bb86cdSEric Blake     int ret;
1269c1bb86cdSEric Blake 
1270e5bcf967SKevin Wolf     if (s->page_cache_inconsistent) {
1271e5bcf967SKevin Wolf         return -EIO;
1272e5bcf967SKevin Wolf     }
1273e5bcf967SKevin Wolf 
1274c1bb86cdSEric Blake     ret = qemu_fdatasync(aiocb->aio_fildes);
1275c1bb86cdSEric Blake     if (ret == -1) {
1276e5bcf967SKevin Wolf         /* There is no clear definition of the semantics of a failing fsync(),
1277e5bcf967SKevin Wolf          * so we may have to assume the worst. The sad truth is that this
1278e5bcf967SKevin Wolf          * assumption is correct for Linux. Some pages are now probably marked
1279e5bcf967SKevin Wolf          * clean in the page cache even though they are inconsistent with the
1280e5bcf967SKevin Wolf          * on-disk contents. The next fdatasync() call would succeed, but no
1281e5bcf967SKevin Wolf          * further writeback attempt will be made. We can't get back to a state
1282e5bcf967SKevin Wolf          * in which we know what is on disk (we would have to rewrite
1283e5bcf967SKevin Wolf          * everything that was touched since the last fdatasync() at least), so
1284e5bcf967SKevin Wolf          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1285e5bcf967SKevin Wolf          * really defined, I have little hope that other OSes are doing better.
1286e5bcf967SKevin Wolf          *
1287e5bcf967SKevin Wolf          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1288e5bcf967SKevin Wolf          * cache. */
1289e5bcf967SKevin Wolf         if ((s->open_flags & O_DIRECT) == 0) {
1290e5bcf967SKevin Wolf             s->page_cache_inconsistent = true;
1291e5bcf967SKevin Wolf         }
1292c1bb86cdSEric Blake         return -errno;
1293c1bb86cdSEric Blake     }
1294c1bb86cdSEric Blake     return 0;
1295c1bb86cdSEric Blake }
1296c1bb86cdSEric Blake 
1297c1bb86cdSEric Blake #ifdef CONFIG_PREADV
1298c1bb86cdSEric Blake 
1299c1bb86cdSEric Blake static bool preadv_present = true;
1300c1bb86cdSEric Blake 
1301c1bb86cdSEric Blake static ssize_t
1302c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1303c1bb86cdSEric Blake {
1304c1bb86cdSEric Blake     return preadv(fd, iov, nr_iov, offset);
1305c1bb86cdSEric Blake }
1306c1bb86cdSEric Blake 
1307c1bb86cdSEric Blake static ssize_t
1308c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1309c1bb86cdSEric Blake {
1310c1bb86cdSEric Blake     return pwritev(fd, iov, nr_iov, offset);
1311c1bb86cdSEric Blake }
1312c1bb86cdSEric Blake 
1313c1bb86cdSEric Blake #else
1314c1bb86cdSEric Blake 
1315c1bb86cdSEric Blake static bool preadv_present = false;
1316c1bb86cdSEric Blake 
1317c1bb86cdSEric Blake static ssize_t
1318c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1319c1bb86cdSEric Blake {
1320c1bb86cdSEric Blake     return -ENOSYS;
1321c1bb86cdSEric Blake }
1322c1bb86cdSEric Blake 
1323c1bb86cdSEric Blake static ssize_t
1324c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1325c1bb86cdSEric Blake {
1326c1bb86cdSEric Blake     return -ENOSYS;
1327c1bb86cdSEric Blake }
1328c1bb86cdSEric Blake 
1329c1bb86cdSEric Blake #endif
1330c1bb86cdSEric Blake 
1331c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1332c1bb86cdSEric Blake {
1333c1bb86cdSEric Blake     ssize_t len;
1334c1bb86cdSEric Blake 
1335c1bb86cdSEric Blake     do {
1336c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE)
1337c1bb86cdSEric Blake             len = qemu_pwritev(aiocb->aio_fildes,
1338d57c44d0SKevin Wolf                                aiocb->io.iov,
1339d57c44d0SKevin Wolf                                aiocb->io.niov,
1340c1bb86cdSEric Blake                                aiocb->aio_offset);
1341c1bb86cdSEric Blake          else
1342c1bb86cdSEric Blake             len = qemu_preadv(aiocb->aio_fildes,
1343d57c44d0SKevin Wolf                               aiocb->io.iov,
1344d57c44d0SKevin Wolf                               aiocb->io.niov,
1345c1bb86cdSEric Blake                               aiocb->aio_offset);
1346c1bb86cdSEric Blake     } while (len == -1 && errno == EINTR);
1347c1bb86cdSEric Blake 
1348c1bb86cdSEric Blake     if (len == -1) {
1349c1bb86cdSEric Blake         return -errno;
1350c1bb86cdSEric Blake     }
1351c1bb86cdSEric Blake     return len;
1352c1bb86cdSEric Blake }
1353c1bb86cdSEric Blake 
1354c1bb86cdSEric Blake /*
1355c1bb86cdSEric Blake  * Read/writes the data to/from a given linear buffer.
1356c1bb86cdSEric Blake  *
1357c1bb86cdSEric Blake  * Returns the number of bytes handles or -errno in case of an error. Short
1358c1bb86cdSEric Blake  * reads are only returned if the end of the file is reached.
1359c1bb86cdSEric Blake  */
1360c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1361c1bb86cdSEric Blake {
1362c1bb86cdSEric Blake     ssize_t offset = 0;
1363c1bb86cdSEric Blake     ssize_t len;
1364c1bb86cdSEric Blake 
1365c1bb86cdSEric Blake     while (offset < aiocb->aio_nbytes) {
1366c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1367c1bb86cdSEric Blake             len = pwrite(aiocb->aio_fildes,
1368c1bb86cdSEric Blake                          (const char *)buf + offset,
1369c1bb86cdSEric Blake                          aiocb->aio_nbytes - offset,
1370c1bb86cdSEric Blake                          aiocb->aio_offset + offset);
1371c1bb86cdSEric Blake         } else {
1372c1bb86cdSEric Blake             len = pread(aiocb->aio_fildes,
1373c1bb86cdSEric Blake                         buf + offset,
1374c1bb86cdSEric Blake                         aiocb->aio_nbytes - offset,
1375c1bb86cdSEric Blake                         aiocb->aio_offset + offset);
1376c1bb86cdSEric Blake         }
1377c1bb86cdSEric Blake         if (len == -1 && errno == EINTR) {
1378c1bb86cdSEric Blake             continue;
1379c1bb86cdSEric Blake         } else if (len == -1 && errno == EINVAL &&
1380c1bb86cdSEric Blake                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1381c1bb86cdSEric Blake                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1382c1bb86cdSEric Blake                    offset > 0) {
1383c1bb86cdSEric Blake             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1384c1bb86cdSEric Blake              * after a short read.  Assume that O_DIRECT short reads only occur
1385c1bb86cdSEric Blake              * at EOF.  Therefore this is a short read, not an I/O error.
1386c1bb86cdSEric Blake              */
1387c1bb86cdSEric Blake             break;
1388c1bb86cdSEric Blake         } else if (len == -1) {
1389c1bb86cdSEric Blake             offset = -errno;
1390c1bb86cdSEric Blake             break;
1391c1bb86cdSEric Blake         } else if (len == 0) {
1392c1bb86cdSEric Blake             break;
1393c1bb86cdSEric Blake         }
1394c1bb86cdSEric Blake         offset += len;
1395c1bb86cdSEric Blake     }
1396c1bb86cdSEric Blake 
1397c1bb86cdSEric Blake     return offset;
1398c1bb86cdSEric Blake }
1399c1bb86cdSEric Blake 
1400999e6b69SKevin Wolf static int handle_aiocb_rw(void *opaque)
1401c1bb86cdSEric Blake {
1402999e6b69SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1403c1bb86cdSEric Blake     ssize_t nbytes;
1404c1bb86cdSEric Blake     char *buf;
1405c1bb86cdSEric Blake 
1406c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1407c1bb86cdSEric Blake         /*
1408c1bb86cdSEric Blake          * If there is just a single buffer, and it is properly aligned
1409c1bb86cdSEric Blake          * we can just use plain pread/pwrite without any problems.
1410c1bb86cdSEric Blake          */
1411d57c44d0SKevin Wolf         if (aiocb->io.niov == 1) {
141254c7ca1bSKevin Wolf             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
141354c7ca1bSKevin Wolf             goto out;
1414c1bb86cdSEric Blake         }
1415c1bb86cdSEric Blake         /*
1416c1bb86cdSEric Blake          * We have more than one iovec, and all are properly aligned.
1417c1bb86cdSEric Blake          *
1418c1bb86cdSEric Blake          * Try preadv/pwritev first and fall back to linearizing the
1419c1bb86cdSEric Blake          * buffer if it's not supported.
1420c1bb86cdSEric Blake          */
1421c1bb86cdSEric Blake         if (preadv_present) {
1422c1bb86cdSEric Blake             nbytes = handle_aiocb_rw_vector(aiocb);
1423c1bb86cdSEric Blake             if (nbytes == aiocb->aio_nbytes ||
1424c1bb86cdSEric Blake                 (nbytes < 0 && nbytes != -ENOSYS)) {
142554c7ca1bSKevin Wolf                 goto out;
1426c1bb86cdSEric Blake             }
1427c1bb86cdSEric Blake             preadv_present = false;
1428c1bb86cdSEric Blake         }
1429c1bb86cdSEric Blake 
1430c1bb86cdSEric Blake         /*
1431c1bb86cdSEric Blake          * XXX(hch): short read/write.  no easy way to handle the reminder
1432c1bb86cdSEric Blake          * using these interfaces.  For now retry using plain
1433c1bb86cdSEric Blake          * pread/pwrite?
1434c1bb86cdSEric Blake          */
1435c1bb86cdSEric Blake     }
1436c1bb86cdSEric Blake 
1437c1bb86cdSEric Blake     /*
1438c1bb86cdSEric Blake      * Ok, we have to do it the hard way, copy all segments into
1439c1bb86cdSEric Blake      * a single aligned buffer.
1440c1bb86cdSEric Blake      */
1441c1bb86cdSEric Blake     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1442c1bb86cdSEric Blake     if (buf == NULL) {
144354c7ca1bSKevin Wolf         nbytes = -ENOMEM;
144454c7ca1bSKevin Wolf         goto out;
1445c1bb86cdSEric Blake     }
1446c1bb86cdSEric Blake 
1447c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1448c1bb86cdSEric Blake         char *p = buf;
1449c1bb86cdSEric Blake         int i;
1450c1bb86cdSEric Blake 
1451d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov; ++i) {
1452d57c44d0SKevin Wolf             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1453d57c44d0SKevin Wolf             p += aiocb->io.iov[i].iov_len;
1454c1bb86cdSEric Blake         }
1455c1bb86cdSEric Blake         assert(p - buf == aiocb->aio_nbytes);
1456c1bb86cdSEric Blake     }
1457c1bb86cdSEric Blake 
1458c1bb86cdSEric Blake     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1459c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1460c1bb86cdSEric Blake         char *p = buf;
1461c1bb86cdSEric Blake         size_t count = aiocb->aio_nbytes, copy;
1462c1bb86cdSEric Blake         int i;
1463c1bb86cdSEric Blake 
1464d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov && count; ++i) {
1465c1bb86cdSEric Blake             copy = count;
1466d57c44d0SKevin Wolf             if (copy > aiocb->io.iov[i].iov_len) {
1467d57c44d0SKevin Wolf                 copy = aiocb->io.iov[i].iov_len;
1468c1bb86cdSEric Blake             }
1469d57c44d0SKevin Wolf             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1470c1bb86cdSEric Blake             assert(count >= copy);
1471c1bb86cdSEric Blake             p     += copy;
1472c1bb86cdSEric Blake             count -= copy;
1473c1bb86cdSEric Blake         }
1474c1bb86cdSEric Blake         assert(count == 0);
1475c1bb86cdSEric Blake     }
1476c1bb86cdSEric Blake     qemu_vfree(buf);
1477c1bb86cdSEric Blake 
147854c7ca1bSKevin Wolf out:
147954c7ca1bSKevin Wolf     if (nbytes == aiocb->aio_nbytes) {
148054c7ca1bSKevin Wolf         return 0;
148154c7ca1bSKevin Wolf     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
148254c7ca1bSKevin Wolf         if (aiocb->aio_type & QEMU_AIO_WRITE) {
148354c7ca1bSKevin Wolf             return -EINVAL;
148454c7ca1bSKevin Wolf         } else {
148554c7ca1bSKevin Wolf             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
148654c7ca1bSKevin Wolf                       0, aiocb->aio_nbytes - nbytes);
148754c7ca1bSKevin Wolf             return 0;
148854c7ca1bSKevin Wolf         }
148954c7ca1bSKevin Wolf     } else {
149054c7ca1bSKevin Wolf         assert(nbytes < 0);
1491c1bb86cdSEric Blake         return nbytes;
1492c1bb86cdSEric Blake     }
149354c7ca1bSKevin Wolf }
1494c1bb86cdSEric Blake 
1495c1bb86cdSEric Blake static int translate_err(int err)
1496c1bb86cdSEric Blake {
1497c1bb86cdSEric Blake     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1498c1bb86cdSEric Blake         err == -ENOTTY) {
1499c1bb86cdSEric Blake         err = -ENOTSUP;
1500c1bb86cdSEric Blake     }
1501c1bb86cdSEric Blake     return err;
1502c1bb86cdSEric Blake }
1503c1bb86cdSEric Blake 
1504c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
1505c1bb86cdSEric Blake static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1506c1bb86cdSEric Blake {
1507c1bb86cdSEric Blake     do {
1508c1bb86cdSEric Blake         if (fallocate(fd, mode, offset, len) == 0) {
1509c1bb86cdSEric Blake             return 0;
1510c1bb86cdSEric Blake         }
1511c1bb86cdSEric Blake     } while (errno == EINTR);
1512c1bb86cdSEric Blake     return translate_err(-errno);
1513c1bb86cdSEric Blake }
1514c1bb86cdSEric Blake #endif
1515c1bb86cdSEric Blake 
1516c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1517c1bb86cdSEric Blake {
1518c1bb86cdSEric Blake     int ret = -ENOTSUP;
1519c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1520c1bb86cdSEric Blake 
1521c1bb86cdSEric Blake     if (!s->has_write_zeroes) {
1522c1bb86cdSEric Blake         return -ENOTSUP;
1523c1bb86cdSEric Blake     }
1524c1bb86cdSEric Blake 
1525c1bb86cdSEric Blake #ifdef BLKZEROOUT
1526738301e1SKevin Wolf     /* The BLKZEROOUT implementation in the kernel doesn't set
1527738301e1SKevin Wolf      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1528738301e1SKevin Wolf      * fallbacks. */
1529738301e1SKevin Wolf     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1530c1bb86cdSEric Blake         do {
1531c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1532c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1533c1bb86cdSEric Blake                 return 0;
1534c1bb86cdSEric Blake             }
1535c1bb86cdSEric Blake         } while (errno == EINTR);
1536c1bb86cdSEric Blake 
1537c1bb86cdSEric Blake         ret = translate_err(-errno);
1538c1bb86cdSEric Blake         if (ret == -ENOTSUP) {
1539c1bb86cdSEric Blake             s->has_write_zeroes = false;
1540c1bb86cdSEric Blake         }
1541effecce6SKevin Wolf     }
1542effecce6SKevin Wolf #endif
1543effecce6SKevin Wolf 
1544c1bb86cdSEric Blake     return ret;
1545c1bb86cdSEric Blake }
1546c1bb86cdSEric Blake 
15477154d8aeSKevin Wolf static int handle_aiocb_write_zeroes(void *opaque)
1548c1bb86cdSEric Blake {
15497154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
155070d9110bSDenis V. Lunev #ifdef CONFIG_FALLOCATE
1551b2c6f23fSMax Reitz     BDRVRawState *s = aiocb->bs->opaque;
155270d9110bSDenis V. Lunev     int64_t len;
155370d9110bSDenis V. Lunev #endif
1554c1bb86cdSEric Blake 
1555c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1556c1bb86cdSEric Blake         return handle_aiocb_write_zeroes_block(aiocb);
1557c1bb86cdSEric Blake     }
1558c1bb86cdSEric Blake 
1559c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1560c1bb86cdSEric Blake     if (s->has_write_zeroes) {
1561c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1562c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1563294682ccSAndrey Shinkevich         if (ret == -EINVAL) {
1564294682ccSAndrey Shinkevich             /*
1565294682ccSAndrey Shinkevich              * Allow falling back to pwrite for file systems that
1566294682ccSAndrey Shinkevich              * do not support fallocate() for an unaligned byte range.
1567294682ccSAndrey Shinkevich              */
1568294682ccSAndrey Shinkevich             return -ENOTSUP;
1569294682ccSAndrey Shinkevich         }
1570c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1571c1bb86cdSEric Blake             return ret;
1572c1bb86cdSEric Blake         }
1573c1bb86cdSEric Blake         s->has_write_zeroes = false;
1574c1bb86cdSEric Blake     }
1575c1bb86cdSEric Blake #endif
1576c1bb86cdSEric Blake 
1577c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1578c1bb86cdSEric Blake     if (s->has_discard && s->has_fallocate) {
1579c1bb86cdSEric Blake         int ret = do_fallocate(s->fd,
1580c1bb86cdSEric Blake                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1581c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1582c1bb86cdSEric Blake         if (ret == 0) {
1583c1bb86cdSEric Blake             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1584c1bb86cdSEric Blake             if (ret == 0 || ret != -ENOTSUP) {
1585c1bb86cdSEric Blake                 return ret;
1586c1bb86cdSEric Blake             }
1587c1bb86cdSEric Blake             s->has_fallocate = false;
1588c1bb86cdSEric Blake         } else if (ret != -ENOTSUP) {
1589c1bb86cdSEric Blake             return ret;
1590c1bb86cdSEric Blake         } else {
1591c1bb86cdSEric Blake             s->has_discard = false;
1592c1bb86cdSEric Blake         }
1593c1bb86cdSEric Blake     }
1594c1bb86cdSEric Blake #endif
1595c1bb86cdSEric Blake 
1596c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
159770d9110bSDenis V. Lunev     /* Last resort: we are trying to extend the file with zeroed data. This
159870d9110bSDenis V. Lunev      * can be done via fallocate(fd, 0) */
159970d9110bSDenis V. Lunev     len = bdrv_getlength(aiocb->bs);
160070d9110bSDenis V. Lunev     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1601c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1602c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1603c1bb86cdSEric Blake             return ret;
1604c1bb86cdSEric Blake         }
1605c1bb86cdSEric Blake         s->has_fallocate = false;
1606c1bb86cdSEric Blake     }
1607c1bb86cdSEric Blake #endif
1608c1bb86cdSEric Blake 
1609c1bb86cdSEric Blake     return -ENOTSUP;
1610c1bb86cdSEric Blake }
1611c1bb86cdSEric Blake 
16127154d8aeSKevin Wolf static int handle_aiocb_write_zeroes_unmap(void *opaque)
161334fa110eSKevin Wolf {
16147154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
161534fa110eSKevin Wolf     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
161634fa110eSKevin Wolf 
161734fa110eSKevin Wolf     /* First try to write zeros and unmap at the same time */
161834fa110eSKevin Wolf 
161934fa110eSKevin Wolf #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1620b3ac2b94SSimran Singhal     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
162134fa110eSKevin Wolf                            aiocb->aio_offset, aiocb->aio_nbytes);
162234fa110eSKevin Wolf     if (ret != -ENOTSUP) {
162334fa110eSKevin Wolf         return ret;
162434fa110eSKevin Wolf     }
162534fa110eSKevin Wolf #endif
162634fa110eSKevin Wolf 
162734fa110eSKevin Wolf     /* If we couldn't manage to unmap while guaranteed that the area reads as
162834fa110eSKevin Wolf      * all-zero afterwards, just write zeroes without unmapping */
1629b3ac2b94SSimran Singhal     return handle_aiocb_write_zeroes(aiocb);
163034fa110eSKevin Wolf }
163134fa110eSKevin Wolf 
16321efad060SFam Zheng #ifndef HAVE_COPY_FILE_RANGE
16331efad060SFam Zheng static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
16341efad060SFam Zheng                              off_t *out_off, size_t len, unsigned int flags)
16351efad060SFam Zheng {
16361efad060SFam Zheng #ifdef __NR_copy_file_range
16371efad060SFam Zheng     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
16381efad060SFam Zheng                    out_off, len, flags);
16391efad060SFam Zheng #else
16401efad060SFam Zheng     errno = ENOSYS;
16411efad060SFam Zheng     return -1;
16421efad060SFam Zheng #endif
16431efad060SFam Zheng }
16441efad060SFam Zheng #endif
16451efad060SFam Zheng 
164658a209c4SKevin Wolf static int handle_aiocb_copy_range(void *opaque)
16471efad060SFam Zheng {
164858a209c4SKevin Wolf     RawPosixAIOData *aiocb = opaque;
16491efad060SFam Zheng     uint64_t bytes = aiocb->aio_nbytes;
16501efad060SFam Zheng     off_t in_off = aiocb->aio_offset;
1651d57c44d0SKevin Wolf     off_t out_off = aiocb->copy_range.aio_offset2;
16521efad060SFam Zheng 
16531efad060SFam Zheng     while (bytes) {
16541efad060SFam Zheng         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
1655d57c44d0SKevin Wolf                                       aiocb->copy_range.aio_fd2, &out_off,
16561efad060SFam Zheng                                       bytes, 0);
1657ecc983a5SFam Zheng         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1658d57c44d0SKevin Wolf                                    aiocb->copy_range.aio_fd2, out_off, bytes,
1659d57c44d0SKevin Wolf                                    0, ret);
1660c436e3d0SFam Zheng         if (ret == 0) {
1661c436e3d0SFam Zheng             /* No progress (e.g. when beyond EOF), let the caller fall back to
1662c436e3d0SFam Zheng              * buffer I/O. */
1663c436e3d0SFam Zheng             return -ENOSPC;
16641efad060SFam Zheng         }
16651efad060SFam Zheng         if (ret < 0) {
1666c436e3d0SFam Zheng             switch (errno) {
1667c436e3d0SFam Zheng             case ENOSYS:
16681efad060SFam Zheng                 return -ENOTSUP;
1669c436e3d0SFam Zheng             case EINTR:
1670c436e3d0SFam Zheng                 continue;
1671c436e3d0SFam Zheng             default:
16721efad060SFam Zheng                 return -errno;
16731efad060SFam Zheng             }
16741efad060SFam Zheng         }
16751efad060SFam Zheng         bytes -= ret;
16761efad060SFam Zheng     }
16771efad060SFam Zheng     return 0;
16781efad060SFam Zheng }
16791efad060SFam Zheng 
168046ee0f46SKevin Wolf static int handle_aiocb_discard(void *opaque)
1681c1bb86cdSEric Blake {
168246ee0f46SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1683c1bb86cdSEric Blake     int ret = -EOPNOTSUPP;
1684c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1685c1bb86cdSEric Blake 
1686c1bb86cdSEric Blake     if (!s->has_discard) {
1687c1bb86cdSEric Blake         return -ENOTSUP;
1688c1bb86cdSEric Blake     }
1689c1bb86cdSEric Blake 
1690c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1691c1bb86cdSEric Blake #ifdef BLKDISCARD
1692c1bb86cdSEric Blake         do {
1693c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1694c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1695c1bb86cdSEric Blake                 return 0;
1696c1bb86cdSEric Blake             }
1697c1bb86cdSEric Blake         } while (errno == EINTR);
1698c1bb86cdSEric Blake 
1699c1bb86cdSEric Blake         ret = -errno;
1700c1bb86cdSEric Blake #endif
1701c1bb86cdSEric Blake     } else {
1702c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1703c1bb86cdSEric Blake         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1704c1bb86cdSEric Blake                            aiocb->aio_offset, aiocb->aio_nbytes);
1705c1bb86cdSEric Blake #endif
1706c1bb86cdSEric Blake     }
1707c1bb86cdSEric Blake 
1708c1bb86cdSEric Blake     ret = translate_err(ret);
1709c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1710c1bb86cdSEric Blake         s->has_discard = false;
1711c1bb86cdSEric Blake     }
1712c1bb86cdSEric Blake     return ret;
1713c1bb86cdSEric Blake }
1714c1bb86cdSEric Blake 
17153a20013fSNir Soffer /*
17163a20013fSNir Soffer  * Help alignment probing by allocating the first block.
17173a20013fSNir Soffer  *
17183a20013fSNir Soffer  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
17193a20013fSNir Soffer  * reading succeeds regardless of request length. In this case we fallback to
17203a20013fSNir Soffer  * safe alignment which is not optimal. Allocating the first block avoids this
17213a20013fSNir Soffer  * fallback.
17223a20013fSNir Soffer  *
17233a20013fSNir Soffer  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
17243a20013fSNir Soffer  * request alignment, so we use safe values.
17253a20013fSNir Soffer  *
17263a20013fSNir Soffer  * Returns: 0 on success, -errno on failure. Since this is an optimization,
17273a20013fSNir Soffer  * caller may ignore failures.
17283a20013fSNir Soffer  */
17293a20013fSNir Soffer static int allocate_first_block(int fd, size_t max_size)
17303a20013fSNir Soffer {
17313a20013fSNir Soffer     size_t write_size = (max_size < MAX_BLOCKSIZE)
17323a20013fSNir Soffer         ? BDRV_SECTOR_SIZE
17333a20013fSNir Soffer         : MAX_BLOCKSIZE;
1734038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
17353a20013fSNir Soffer     void *buf;
17363a20013fSNir Soffer     ssize_t n;
17373a20013fSNir Soffer     int ret;
17383a20013fSNir Soffer 
17393a20013fSNir Soffer     buf = qemu_memalign(max_align, write_size);
17403a20013fSNir Soffer     memset(buf, 0, write_size);
17413a20013fSNir Soffer 
17423a20013fSNir Soffer     do {
17433a20013fSNir Soffer         n = pwrite(fd, buf, write_size, 0);
17443a20013fSNir Soffer     } while (n == -1 && errno == EINTR);
17453a20013fSNir Soffer 
17463a20013fSNir Soffer     ret = (n == -1) ? -errno : 0;
17473a20013fSNir Soffer 
17483a20013fSNir Soffer     qemu_vfree(buf);
17493a20013fSNir Soffer     return ret;
17503a20013fSNir Soffer }
17513a20013fSNir Soffer 
175229cb4c01SKevin Wolf static int handle_aiocb_truncate(void *opaque)
175393f4e2ffSKevin Wolf {
175429cb4c01SKevin Wolf     RawPosixAIOData *aiocb = opaque;
175593f4e2ffSKevin Wolf     int result = 0;
175693f4e2ffSKevin Wolf     int64_t current_length = 0;
175793f4e2ffSKevin Wolf     char *buf = NULL;
175893f4e2ffSKevin Wolf     struct stat st;
175993f4e2ffSKevin Wolf     int fd = aiocb->aio_fildes;
176093f4e2ffSKevin Wolf     int64_t offset = aiocb->aio_offset;
1761d57c44d0SKevin Wolf     PreallocMode prealloc = aiocb->truncate.prealloc;
1762d57c44d0SKevin Wolf     Error **errp = aiocb->truncate.errp;
176393f4e2ffSKevin Wolf 
176493f4e2ffSKevin Wolf     if (fstat(fd, &st) < 0) {
176593f4e2ffSKevin Wolf         result = -errno;
176693f4e2ffSKevin Wolf         error_setg_errno(errp, -result, "Could not stat file");
176793f4e2ffSKevin Wolf         return result;
176893f4e2ffSKevin Wolf     }
176993f4e2ffSKevin Wolf 
177093f4e2ffSKevin Wolf     current_length = st.st_size;
1771d57c44d0SKevin Wolf     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
177293f4e2ffSKevin Wolf         error_setg(errp, "Cannot use preallocation for shrinking files");
177393f4e2ffSKevin Wolf         return -ENOTSUP;
177493f4e2ffSKevin Wolf     }
177593f4e2ffSKevin Wolf 
1776d57c44d0SKevin Wolf     switch (prealloc) {
177793f4e2ffSKevin Wolf #ifdef CONFIG_POSIX_FALLOCATE
177893f4e2ffSKevin Wolf     case PREALLOC_MODE_FALLOC:
177993f4e2ffSKevin Wolf         /*
178093f4e2ffSKevin Wolf          * Truncating before posix_fallocate() makes it about twice slower on
178193f4e2ffSKevin Wolf          * file systems that do not support fallocate(), trying to check if a
178293f4e2ffSKevin Wolf          * block is allocated before allocating it, so don't do that here.
178393f4e2ffSKevin Wolf          */
178493f4e2ffSKevin Wolf         if (offset != current_length) {
178593f4e2ffSKevin Wolf             result = -posix_fallocate(fd, current_length,
178693f4e2ffSKevin Wolf                                       offset - current_length);
178793f4e2ffSKevin Wolf             if (result != 0) {
178893f4e2ffSKevin Wolf                 /* posix_fallocate() doesn't set errno. */
178993f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
179093f4e2ffSKevin Wolf                                  "Could not preallocate new data");
17913a20013fSNir Soffer             } else if (current_length == 0) {
17923a20013fSNir Soffer                 /*
17933a20013fSNir Soffer                  * posix_fallocate() uses fallocate() if the filesystem
17943a20013fSNir Soffer                  * supports it, or fallback to manually writing zeroes. If
17953a20013fSNir Soffer                  * fallocate() was used, unaligned reads from the fallocated
17963a20013fSNir Soffer                  * area in raw_probe_alignment() will succeed, hence we need to
17973a20013fSNir Soffer                  * allocate the first block.
17983a20013fSNir Soffer                  *
17993a20013fSNir Soffer                  * Optimize future alignment probing; ignore failures.
18003a20013fSNir Soffer                  */
18013a20013fSNir Soffer                 allocate_first_block(fd, offset);
180293f4e2ffSKevin Wolf             }
180393f4e2ffSKevin Wolf         } else {
180493f4e2ffSKevin Wolf             result = 0;
180593f4e2ffSKevin Wolf         }
180693f4e2ffSKevin Wolf         goto out;
180793f4e2ffSKevin Wolf #endif
180893f4e2ffSKevin Wolf     case PREALLOC_MODE_FULL:
180993f4e2ffSKevin Wolf     {
181093f4e2ffSKevin Wolf         int64_t num = 0, left = offset - current_length;
181193f4e2ffSKevin Wolf         off_t seek_result;
181293f4e2ffSKevin Wolf 
181393f4e2ffSKevin Wolf         /*
181493f4e2ffSKevin Wolf          * Knowing the final size from the beginning could allow the file
181593f4e2ffSKevin Wolf          * system driver to do less allocations and possibly avoid
181693f4e2ffSKevin Wolf          * fragmentation of the file.
181793f4e2ffSKevin Wolf          */
181893f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
181993f4e2ffSKevin Wolf             result = -errno;
182093f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
182193f4e2ffSKevin Wolf             goto out;
182293f4e2ffSKevin Wolf         }
182393f4e2ffSKevin Wolf 
182493f4e2ffSKevin Wolf         buf = g_malloc0(65536);
182593f4e2ffSKevin Wolf 
182693f4e2ffSKevin Wolf         seek_result = lseek(fd, current_length, SEEK_SET);
182793f4e2ffSKevin Wolf         if (seek_result < 0) {
182893f4e2ffSKevin Wolf             result = -errno;
182993f4e2ffSKevin Wolf             error_setg_errno(errp, -result,
183093f4e2ffSKevin Wolf                              "Failed to seek to the old end of file");
183193f4e2ffSKevin Wolf             goto out;
183293f4e2ffSKevin Wolf         }
183393f4e2ffSKevin Wolf 
183493f4e2ffSKevin Wolf         while (left > 0) {
183593f4e2ffSKevin Wolf             num = MIN(left, 65536);
183693f4e2ffSKevin Wolf             result = write(fd, buf, num);
183793f4e2ffSKevin Wolf             if (result < 0) {
1838a1c81f4fSFam Zheng                 if (errno == EINTR) {
1839a1c81f4fSFam Zheng                     continue;
1840a1c81f4fSFam Zheng                 }
184193f4e2ffSKevin Wolf                 result = -errno;
184293f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
184393f4e2ffSKevin Wolf                                  "Could not write zeros for preallocation");
184493f4e2ffSKevin Wolf                 goto out;
184593f4e2ffSKevin Wolf             }
184693f4e2ffSKevin Wolf             left -= result;
184793f4e2ffSKevin Wolf         }
184893f4e2ffSKevin Wolf         if (result >= 0) {
184993f4e2ffSKevin Wolf             result = fsync(fd);
185093f4e2ffSKevin Wolf             if (result < 0) {
185193f4e2ffSKevin Wolf                 result = -errno;
185293f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
185393f4e2ffSKevin Wolf                                  "Could not flush file to disk");
185493f4e2ffSKevin Wolf                 goto out;
185593f4e2ffSKevin Wolf             }
185693f4e2ffSKevin Wolf         }
185793f4e2ffSKevin Wolf         goto out;
185893f4e2ffSKevin Wolf     }
185993f4e2ffSKevin Wolf     case PREALLOC_MODE_OFF:
186093f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
186193f4e2ffSKevin Wolf             result = -errno;
186293f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
18633a20013fSNir Soffer         } else if (current_length == 0 && offset > current_length) {
18643a20013fSNir Soffer             /* Optimize future alignment probing; ignore failures. */
18653a20013fSNir Soffer             allocate_first_block(fd, offset);
186693f4e2ffSKevin Wolf         }
186793f4e2ffSKevin Wolf         return result;
186893f4e2ffSKevin Wolf     default:
186993f4e2ffSKevin Wolf         result = -ENOTSUP;
187093f4e2ffSKevin Wolf         error_setg(errp, "Unsupported preallocation mode: %s",
1871d57c44d0SKevin Wolf                    PreallocMode_str(prealloc));
187293f4e2ffSKevin Wolf         return result;
187393f4e2ffSKevin Wolf     }
187493f4e2ffSKevin Wolf 
187593f4e2ffSKevin Wolf out:
187693f4e2ffSKevin Wolf     if (result < 0) {
187793f4e2ffSKevin Wolf         if (ftruncate(fd, current_length) < 0) {
187893f4e2ffSKevin Wolf             error_report("Failed to restore old file length: %s",
187993f4e2ffSKevin Wolf                          strerror(errno));
188093f4e2ffSKevin Wolf         }
188193f4e2ffSKevin Wolf     }
188293f4e2ffSKevin Wolf 
188393f4e2ffSKevin Wolf     g_free(buf);
188493f4e2ffSKevin Wolf     return result;
188593f4e2ffSKevin Wolf }
188693f4e2ffSKevin Wolf 
18875d5de250SKevin Wolf static int coroutine_fn raw_thread_pool_submit(BlockDriverState *bs,
18885d5de250SKevin Wolf                                                ThreadPoolFunc func, void *arg)
18895d5de250SKevin Wolf {
18905d5de250SKevin Wolf     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
18915d5de250SKevin Wolf     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
18925d5de250SKevin Wolf     return thread_pool_submit_co(pool, func, arg);
18935d5de250SKevin Wolf }
18945d5de250SKevin Wolf 
1895c1bb86cdSEric Blake static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1896c1bb86cdSEric Blake                                    uint64_t bytes, QEMUIOVector *qiov, int type)
1897c1bb86cdSEric Blake {
1898c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1899999e6b69SKevin Wolf     RawPosixAIOData acb;
1900c1bb86cdSEric Blake 
1901c1bb86cdSEric Blake     if (fd_open(bs) < 0)
1902c1bb86cdSEric Blake         return -EIO;
1903c1bb86cdSEric Blake 
1904c1bb86cdSEric Blake     /*
1905c6447510SAarushi Mehta      * When using O_DIRECT, the request must be aligned to be able to use
1906c6447510SAarushi Mehta      * either libaio or io_uring interface. If not fail back to regular thread
1907c6447510SAarushi Mehta      * pool read/write code which emulates this for us if we
1908c6447510SAarushi Mehta      * set QEMU_AIO_MISALIGNED.
1909c1bb86cdSEric Blake      */
1910c6447510SAarushi Mehta     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
1911c1bb86cdSEric Blake         type |= QEMU_AIO_MISALIGNED;
1912c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
1913c6447510SAarushi Mehta     } else if (s->use_linux_io_uring) {
1914c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1915c6447510SAarushi Mehta         assert(qiov->size == bytes);
1916c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, offset, qiov, type);
1917c6447510SAarushi Mehta #endif
1918c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1919c1bb86cdSEric Blake     } else if (s->use_linux_aio) {
1920c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1921c1bb86cdSEric Blake         assert(qiov->size == bytes);
1922c1bb86cdSEric Blake         return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
1923c1bb86cdSEric Blake #endif
1924c1bb86cdSEric Blake     }
1925c1bb86cdSEric Blake 
1926999e6b69SKevin Wolf     acb = (RawPosixAIOData) {
1927999e6b69SKevin Wolf         .bs             = bs,
1928999e6b69SKevin Wolf         .aio_fildes     = s->fd,
1929999e6b69SKevin Wolf         .aio_type       = type,
1930999e6b69SKevin Wolf         .aio_offset     = offset,
1931999e6b69SKevin Wolf         .aio_nbytes     = bytes,
1932999e6b69SKevin Wolf         .io             = {
1933999e6b69SKevin Wolf             .iov            = qiov->iov,
1934999e6b69SKevin Wolf             .niov           = qiov->niov,
1935999e6b69SKevin Wolf         },
1936999e6b69SKevin Wolf     };
1937999e6b69SKevin Wolf 
1938999e6b69SKevin Wolf     assert(qiov->size == bytes);
1939999e6b69SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_rw, &acb);
1940c1bb86cdSEric Blake }
1941c1bb86cdSEric Blake 
1942c1bb86cdSEric Blake static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1943c1bb86cdSEric Blake                                       uint64_t bytes, QEMUIOVector *qiov,
1944c1bb86cdSEric Blake                                       int flags)
1945c1bb86cdSEric Blake {
1946c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
1947c1bb86cdSEric Blake }
1948c1bb86cdSEric Blake 
1949c1bb86cdSEric Blake static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1950c1bb86cdSEric Blake                                        uint64_t bytes, QEMUIOVector *qiov,
1951c1bb86cdSEric Blake                                        int flags)
1952c1bb86cdSEric Blake {
1953c1bb86cdSEric Blake     assert(flags == 0);
1954c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
1955c1bb86cdSEric Blake }
1956c1bb86cdSEric Blake 
1957c1bb86cdSEric Blake static void raw_aio_plug(BlockDriverState *bs)
1958c1bb86cdSEric Blake {
1959c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
1960c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1961c1bb86cdSEric Blake     if (s->use_linux_aio) {
1962c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1963c1bb86cdSEric Blake         laio_io_plug(bs, aio);
1964c1bb86cdSEric Blake     }
1965c1bb86cdSEric Blake #endif
1966c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
1967c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
1968c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1969c6447510SAarushi Mehta         luring_io_plug(bs, aio);
1970c6447510SAarushi Mehta     }
1971c6447510SAarushi Mehta #endif
1972c1bb86cdSEric Blake }
1973c1bb86cdSEric Blake 
1974c1bb86cdSEric Blake static void raw_aio_unplug(BlockDriverState *bs)
1975c1bb86cdSEric Blake {
1976c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
1977c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
1978c1bb86cdSEric Blake     if (s->use_linux_aio) {
1979c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1980c1bb86cdSEric Blake         laio_io_unplug(bs, aio);
1981c1bb86cdSEric Blake     }
1982c1bb86cdSEric Blake #endif
1983c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
1984c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
1985c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1986c6447510SAarushi Mehta         luring_io_unplug(bs, aio);
1987c6447510SAarushi Mehta     }
1988c6447510SAarushi Mehta #endif
1989c1bb86cdSEric Blake }
1990c1bb86cdSEric Blake 
199133d70fb6SKevin Wolf static int raw_co_flush_to_disk(BlockDriverState *bs)
1992c1bb86cdSEric Blake {
1993c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
199406dc9bd5SKevin Wolf     RawPosixAIOData acb;
199533d70fb6SKevin Wolf     int ret;
1996c1bb86cdSEric Blake 
199733d70fb6SKevin Wolf     ret = fd_open(bs);
199833d70fb6SKevin Wolf     if (ret < 0) {
199933d70fb6SKevin Wolf         return ret;
200033d70fb6SKevin Wolf     }
2001c1bb86cdSEric Blake 
200206dc9bd5SKevin Wolf     acb = (RawPosixAIOData) {
200306dc9bd5SKevin Wolf         .bs             = bs,
200406dc9bd5SKevin Wolf         .aio_fildes     = s->fd,
200506dc9bd5SKevin Wolf         .aio_type       = QEMU_AIO_FLUSH,
200606dc9bd5SKevin Wolf     };
200706dc9bd5SKevin Wolf 
2008c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2009c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2010c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2011c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2012c6447510SAarushi Mehta     }
2013c6447510SAarushi Mehta #endif
201406dc9bd5SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_flush, &acb);
2015c1bb86cdSEric Blake }
2016c1bb86cdSEric Blake 
2017ed6e2161SNishanth Aravamudan static void raw_aio_attach_aio_context(BlockDriverState *bs,
2018ed6e2161SNishanth Aravamudan                                        AioContext *new_context)
2019ed6e2161SNishanth Aravamudan {
2020c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2021ed6e2161SNishanth Aravamudan #ifdef CONFIG_LINUX_AIO
2022ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
2023cb09104eSMarkus Armbruster         Error *local_err = NULL;
2024ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(new_context, &local_err)) {
2025ed6e2161SNishanth Aravamudan             error_reportf_err(local_err, "Unable to use native AIO, "
2026ed6e2161SNishanth Aravamudan                                          "falling back to thread pool: ");
2027ed6e2161SNishanth Aravamudan             s->use_linux_aio = false;
2028ed6e2161SNishanth Aravamudan         }
2029ed6e2161SNishanth Aravamudan     }
2030ed6e2161SNishanth Aravamudan #endif
2031c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2032c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2033c6447510SAarushi Mehta         Error *local_err;
2034c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2035c6447510SAarushi Mehta             error_reportf_err(local_err, "Unable to use linux io_uring, "
2036c6447510SAarushi Mehta                                          "falling back to thread pool: ");
2037c6447510SAarushi Mehta             s->use_linux_io_uring = false;
2038c6447510SAarushi Mehta         }
2039c6447510SAarushi Mehta     }
2040c6447510SAarushi Mehta #endif
2041ed6e2161SNishanth Aravamudan }
2042ed6e2161SNishanth Aravamudan 
2043c1bb86cdSEric Blake static void raw_close(BlockDriverState *bs)
2044c1bb86cdSEric Blake {
2045c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2046c1bb86cdSEric Blake 
2047c1bb86cdSEric Blake     if (s->fd >= 0) {
2048c1bb86cdSEric Blake         qemu_close(s->fd);
2049c1bb86cdSEric Blake         s->fd = -1;
2050c1bb86cdSEric Blake     }
2051c1bb86cdSEric Blake }
2052c1bb86cdSEric Blake 
2053d0bc9e5dSMax Reitz /**
2054d0bc9e5dSMax Reitz  * Truncates the given regular file @fd to @offset and, when growing, fills the
2055d0bc9e5dSMax Reitz  * new space according to @prealloc.
2056d0bc9e5dSMax Reitz  *
2057d0bc9e5dSMax Reitz  * Returns: 0 on success, -errno on failure.
2058d0bc9e5dSMax Reitz  */
205993f4e2ffSKevin Wolf static int coroutine_fn
206093f4e2ffSKevin Wolf raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
206193f4e2ffSKevin Wolf                      PreallocMode prealloc, Error **errp)
20629f63b07eSMax Reitz {
206329cb4c01SKevin Wolf     RawPosixAIOData acb;
2064d0bc9e5dSMax Reitz 
206529cb4c01SKevin Wolf     acb = (RawPosixAIOData) {
206693f4e2ffSKevin Wolf         .bs             = bs,
206793f4e2ffSKevin Wolf         .aio_fildes     = fd,
206893f4e2ffSKevin Wolf         .aio_type       = QEMU_AIO_TRUNCATE,
206993f4e2ffSKevin Wolf         .aio_offset     = offset,
2070d57c44d0SKevin Wolf         .truncate       = {
207193f4e2ffSKevin Wolf             .prealloc       = prealloc,
207293f4e2ffSKevin Wolf             .errp           = errp,
2073d57c44d0SKevin Wolf         },
207493f4e2ffSKevin Wolf     };
2075d0bc9e5dSMax Reitz 
207629cb4c01SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_truncate, &acb);
20779f63b07eSMax Reitz }
20789f63b07eSMax Reitz 
2079061ca8a3SKevin Wolf static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2080c80d8b06SMax Reitz                                         bool exact, PreallocMode prealloc,
208192b92799SKevin Wolf                                         BdrvRequestFlags flags, Error **errp)
2082c1bb86cdSEric Blake {
2083c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2084c1bb86cdSEric Blake     struct stat st;
2085f59adb32SMax Reitz     int ret;
2086c1bb86cdSEric Blake 
2087c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
2088f59adb32SMax Reitz         ret = -errno;
2089f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2090f59adb32SMax Reitz         return ret;
2091c1bb86cdSEric Blake     }
2092c1bb86cdSEric Blake 
2093c1bb86cdSEric Blake     if (S_ISREG(st.st_mode)) {
209482325ae5SMax Reitz         /* Always resizes to the exact @offset */
209593f4e2ffSKevin Wolf         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2096c1bb86cdSEric Blake     }
209735d72602SMax Reitz 
209835d72602SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
209935d72602SMax Reitz         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2100977c736fSMarkus Armbruster                    "non-regular file", PreallocMode_str(prealloc));
210135d72602SMax Reitz         return -ENOTSUP;
210235d72602SMax Reitz     }
210335d72602SMax Reitz 
210435d72602SMax Reitz     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
210582325ae5SMax Reitz         int64_t cur_length = raw_getlength(bs);
210682325ae5SMax Reitz 
210782325ae5SMax Reitz         if (offset != cur_length && exact) {
210882325ae5SMax Reitz             error_setg(errp, "Cannot resize device files");
210982325ae5SMax Reitz             return -ENOTSUP;
211082325ae5SMax Reitz         } else if (offset > cur_length) {
2111f59adb32SMax Reitz             error_setg(errp, "Cannot grow device files");
2112c1bb86cdSEric Blake             return -EINVAL;
2113c1bb86cdSEric Blake         }
2114c1bb86cdSEric Blake     } else {
2115f59adb32SMax Reitz         error_setg(errp, "Resizing this file is not supported");
2116c1bb86cdSEric Blake         return -ENOTSUP;
2117c1bb86cdSEric Blake     }
2118c1bb86cdSEric Blake 
2119c1bb86cdSEric Blake     return 0;
2120c1bb86cdSEric Blake }
2121c1bb86cdSEric Blake 
2122c1bb86cdSEric Blake #ifdef __OpenBSD__
2123c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2124c1bb86cdSEric Blake {
2125c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2126c1bb86cdSEric Blake     int fd = s->fd;
2127c1bb86cdSEric Blake     struct stat st;
2128c1bb86cdSEric Blake 
2129c1bb86cdSEric Blake     if (fstat(fd, &st))
2130c1bb86cdSEric Blake         return -errno;
2131c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2132c1bb86cdSEric Blake         struct disklabel dl;
2133c1bb86cdSEric Blake 
2134c1bb86cdSEric Blake         if (ioctl(fd, DIOCGDINFO, &dl))
2135c1bb86cdSEric Blake             return -errno;
2136c1bb86cdSEric Blake         return (uint64_t)dl.d_secsize *
2137c1bb86cdSEric Blake             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2138c1bb86cdSEric Blake     } else
2139c1bb86cdSEric Blake         return st.st_size;
2140c1bb86cdSEric Blake }
2141c1bb86cdSEric Blake #elif defined(__NetBSD__)
2142c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2143c1bb86cdSEric Blake {
2144c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2145c1bb86cdSEric Blake     int fd = s->fd;
2146c1bb86cdSEric Blake     struct stat st;
2147c1bb86cdSEric Blake 
2148c1bb86cdSEric Blake     if (fstat(fd, &st))
2149c1bb86cdSEric Blake         return -errno;
2150c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2151c1bb86cdSEric Blake         struct dkwedge_info dkw;
2152c1bb86cdSEric Blake 
2153c1bb86cdSEric Blake         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2154c1bb86cdSEric Blake             return dkw.dkw_size * 512;
2155c1bb86cdSEric Blake         } else {
2156c1bb86cdSEric Blake             struct disklabel dl;
2157c1bb86cdSEric Blake 
2158c1bb86cdSEric Blake             if (ioctl(fd, DIOCGDINFO, &dl))
2159c1bb86cdSEric Blake                 return -errno;
2160c1bb86cdSEric Blake             return (uint64_t)dl.d_secsize *
2161c1bb86cdSEric Blake                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2162c1bb86cdSEric Blake         }
2163c1bb86cdSEric Blake     } else
2164c1bb86cdSEric Blake         return st.st_size;
2165c1bb86cdSEric Blake }
2166c1bb86cdSEric Blake #elif defined(__sun__)
2167c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2168c1bb86cdSEric Blake {
2169c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2170c1bb86cdSEric Blake     struct dk_minfo minfo;
2171c1bb86cdSEric Blake     int ret;
2172c1bb86cdSEric Blake     int64_t size;
2173c1bb86cdSEric Blake 
2174c1bb86cdSEric Blake     ret = fd_open(bs);
2175c1bb86cdSEric Blake     if (ret < 0) {
2176c1bb86cdSEric Blake         return ret;
2177c1bb86cdSEric Blake     }
2178c1bb86cdSEric Blake 
2179c1bb86cdSEric Blake     /*
2180c1bb86cdSEric Blake      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2181c1bb86cdSEric Blake      */
2182c1bb86cdSEric Blake     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2183c1bb86cdSEric Blake     if (ret != -1) {
2184c1bb86cdSEric Blake         return minfo.dki_lbsize * minfo.dki_capacity;
2185c1bb86cdSEric Blake     }
2186c1bb86cdSEric Blake 
2187c1bb86cdSEric Blake     /*
2188c1bb86cdSEric Blake      * There are reports that lseek on some devices fails, but
2189c1bb86cdSEric Blake      * irc discussion said that contingency on contingency was overkill.
2190c1bb86cdSEric Blake      */
2191c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2192c1bb86cdSEric Blake     if (size < 0) {
2193c1bb86cdSEric Blake         return -errno;
2194c1bb86cdSEric Blake     }
2195c1bb86cdSEric Blake     return size;
2196c1bb86cdSEric Blake }
2197c1bb86cdSEric Blake #elif defined(CONFIG_BSD)
2198c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2199c1bb86cdSEric Blake {
2200c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2201c1bb86cdSEric Blake     int fd = s->fd;
2202c1bb86cdSEric Blake     int64_t size;
2203c1bb86cdSEric Blake     struct stat sb;
2204c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2205c1bb86cdSEric Blake     int reopened = 0;
2206c1bb86cdSEric Blake #endif
2207c1bb86cdSEric Blake     int ret;
2208c1bb86cdSEric Blake 
2209c1bb86cdSEric Blake     ret = fd_open(bs);
2210c1bb86cdSEric Blake     if (ret < 0)
2211c1bb86cdSEric Blake         return ret;
2212c1bb86cdSEric Blake 
2213c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2214c1bb86cdSEric Blake again:
2215c1bb86cdSEric Blake #endif
2216c1bb86cdSEric Blake     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2217c1bb86cdSEric Blake #ifdef DIOCGMEDIASIZE
2218c1bb86cdSEric Blake         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
2219c1bb86cdSEric Blake #elif defined(DIOCGPART)
2220c1bb86cdSEric Blake         {
2221c1bb86cdSEric Blake                 struct partinfo pi;
2222c1bb86cdSEric Blake                 if (ioctl(fd, DIOCGPART, &pi) == 0)
2223c1bb86cdSEric Blake                         size = pi.media_size;
2224c1bb86cdSEric Blake                 else
2225c1bb86cdSEric Blake                         size = 0;
2226c1bb86cdSEric Blake         }
2227c1bb86cdSEric Blake         if (size == 0)
2228c1bb86cdSEric Blake #endif
2229c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
2230c1bb86cdSEric Blake         {
2231c1bb86cdSEric Blake             uint64_t sectors = 0;
2232c1bb86cdSEric Blake             uint32_t sector_size = 0;
2233c1bb86cdSEric Blake 
2234c1bb86cdSEric Blake             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2235c1bb86cdSEric Blake                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2236c1bb86cdSEric Blake                 size = sectors * sector_size;
2237c1bb86cdSEric Blake             } else {
2238c1bb86cdSEric Blake                 size = lseek(fd, 0LL, SEEK_END);
2239c1bb86cdSEric Blake                 if (size < 0) {
2240c1bb86cdSEric Blake                     return -errno;
2241c1bb86cdSEric Blake                 }
2242c1bb86cdSEric Blake             }
2243c1bb86cdSEric Blake         }
2244c1bb86cdSEric Blake #else
2245c1bb86cdSEric Blake         size = lseek(fd, 0LL, SEEK_END);
2246c1bb86cdSEric Blake         if (size < 0) {
2247c1bb86cdSEric Blake             return -errno;
2248c1bb86cdSEric Blake         }
2249c1bb86cdSEric Blake #endif
2250c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2251c1bb86cdSEric Blake         switch(s->type) {
2252c1bb86cdSEric Blake         case FTYPE_CD:
2253c1bb86cdSEric Blake             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2254c1bb86cdSEric Blake             if (size == 2048LL * (unsigned)-1)
2255c1bb86cdSEric Blake                 size = 0;
2256c1bb86cdSEric Blake             /* XXX no disc?  maybe we need to reopen... */
2257c1bb86cdSEric Blake             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2258c1bb86cdSEric Blake                 reopened = 1;
2259c1bb86cdSEric Blake                 goto again;
2260c1bb86cdSEric Blake             }
2261c1bb86cdSEric Blake         }
2262c1bb86cdSEric Blake #endif
2263c1bb86cdSEric Blake     } else {
2264c1bb86cdSEric Blake         size = lseek(fd, 0, SEEK_END);
2265c1bb86cdSEric Blake         if (size < 0) {
2266c1bb86cdSEric Blake             return -errno;
2267c1bb86cdSEric Blake         }
2268c1bb86cdSEric Blake     }
2269c1bb86cdSEric Blake     return size;
2270c1bb86cdSEric Blake }
2271c1bb86cdSEric Blake #else
2272c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2273c1bb86cdSEric Blake {
2274c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2275c1bb86cdSEric Blake     int ret;
2276c1bb86cdSEric Blake     int64_t size;
2277c1bb86cdSEric Blake 
2278c1bb86cdSEric Blake     ret = fd_open(bs);
2279c1bb86cdSEric Blake     if (ret < 0) {
2280c1bb86cdSEric Blake         return ret;
2281c1bb86cdSEric Blake     }
2282c1bb86cdSEric Blake 
2283c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2284c1bb86cdSEric Blake     if (size < 0) {
2285c1bb86cdSEric Blake         return -errno;
2286c1bb86cdSEric Blake     }
2287c1bb86cdSEric Blake     return size;
2288c1bb86cdSEric Blake }
2289c1bb86cdSEric Blake #endif
2290c1bb86cdSEric Blake 
2291c1bb86cdSEric Blake static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
2292c1bb86cdSEric Blake {
2293c1bb86cdSEric Blake     struct stat st;
2294c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2295c1bb86cdSEric Blake 
2296c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
2297c1bb86cdSEric Blake         return -errno;
2298c1bb86cdSEric Blake     }
2299c1bb86cdSEric Blake     return (int64_t)st.st_blocks * 512;
2300c1bb86cdSEric Blake }
2301c1bb86cdSEric Blake 
230293f4e2ffSKevin Wolf static int coroutine_fn
230393f4e2ffSKevin Wolf raw_co_create(BlockdevCreateOptions *options, Error **errp)
2304c1bb86cdSEric Blake {
2305927f11e1SKevin Wolf     BlockdevCreateOptionsFile *file_opts;
23067c20c808SMax Reitz     Error *local_err = NULL;
2307c1bb86cdSEric Blake     int fd;
2308d815efcaSMax Reitz     uint64_t perm, shared;
2309c1bb86cdSEric Blake     int result = 0;
2310c1bb86cdSEric Blake 
2311927f11e1SKevin Wolf     /* Validate options and set default values */
2312927f11e1SKevin Wolf     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2313927f11e1SKevin Wolf     file_opts = &options->u.file;
2314c1bb86cdSEric Blake 
2315927f11e1SKevin Wolf     if (!file_opts->has_nocow) {
2316927f11e1SKevin Wolf         file_opts->nocow = false;
2317927f11e1SKevin Wolf     }
2318927f11e1SKevin Wolf     if (!file_opts->has_preallocation) {
2319927f11e1SKevin Wolf         file_opts->preallocation = PREALLOC_MODE_OFF;
2320c1bb86cdSEric Blake     }
2321c1bb86cdSEric Blake 
2322927f11e1SKevin Wolf     /* Create file */
2323b8cf1913SMax Reitz     fd = qemu_open(file_opts->filename, O_RDWR | O_CREAT | O_BINARY, 0644);
2324c1bb86cdSEric Blake     if (fd < 0) {
2325c1bb86cdSEric Blake         result = -errno;
2326c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not create file");
2327c1bb86cdSEric Blake         goto out;
2328c1bb86cdSEric Blake     }
2329c1bb86cdSEric Blake 
2330b8cf1913SMax Reitz     /* Take permissions: We want to discard everything, so we need
2331b8cf1913SMax Reitz      * BLK_PERM_WRITE; and truncation to the desired size requires
2332b8cf1913SMax Reitz      * BLK_PERM_RESIZE.
2333b8cf1913SMax Reitz      * On the other hand, we cannot share the RESIZE permission
2334b8cf1913SMax Reitz      * because we promise that after this function, the file has the
2335b8cf1913SMax Reitz      * size given in the options.  If someone else were to resize it
2336b8cf1913SMax Reitz      * concurrently, we could not guarantee that.
2337b8cf1913SMax Reitz      * Note that after this function, we can no longer guarantee that
2338b8cf1913SMax Reitz      * the file is not touched by a third party, so it may be resized
2339b8cf1913SMax Reitz      * then. */
2340b8cf1913SMax Reitz     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2341b8cf1913SMax Reitz     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2342b8cf1913SMax Reitz 
2343b8cf1913SMax Reitz     /* Step one: Take locks */
23442996ffadSFam Zheng     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2345b8cf1913SMax Reitz     if (result < 0) {
2346b8cf1913SMax Reitz         goto out_close;
2347b8cf1913SMax Reitz     }
2348b8cf1913SMax Reitz 
2349b8cf1913SMax Reitz     /* Step two: Check that nobody else has taken conflicting locks */
2350b8cf1913SMax Reitz     result = raw_check_lock_bytes(fd, perm, shared, errp);
2351b8cf1913SMax Reitz     if (result < 0) {
2352b857431dSFam Zheng         error_append_hint(errp,
2353b857431dSFam Zheng                           "Is another process using the image [%s]?\n",
2354b857431dSFam Zheng                           file_opts->filename);
23557c20c808SMax Reitz         goto out_unlock;
2356b8cf1913SMax Reitz     }
2357b8cf1913SMax Reitz 
2358b8cf1913SMax Reitz     /* Clear the file by truncating it to 0 */
235993f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2360b8cf1913SMax Reitz     if (result < 0) {
23617c20c808SMax Reitz         goto out_unlock;
2362b8cf1913SMax Reitz     }
2363b8cf1913SMax Reitz 
2364927f11e1SKevin Wolf     if (file_opts->nocow) {
2365c1bb86cdSEric Blake #ifdef __linux__
2366c1bb86cdSEric Blake         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2367c1bb86cdSEric Blake          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2368c1bb86cdSEric Blake          * will be ignored since any failure of this operation should not
2369c1bb86cdSEric Blake          * block the left work.
2370c1bb86cdSEric Blake          */
2371c1bb86cdSEric Blake         int attr;
2372c1bb86cdSEric Blake         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2373c1bb86cdSEric Blake             attr |= FS_NOCOW_FL;
2374c1bb86cdSEric Blake             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2375c1bb86cdSEric Blake         }
2376c1bb86cdSEric Blake #endif
2377c1bb86cdSEric Blake     }
2378c1bb86cdSEric Blake 
2379b8cf1913SMax Reitz     /* Resize and potentially preallocate the file to the desired
2380b8cf1913SMax Reitz      * final size */
238193f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, file_opts->size,
238293f4e2ffSKevin Wolf                                   file_opts->preallocation, errp);
23839f63b07eSMax Reitz     if (result < 0) {
23847c20c808SMax Reitz         goto out_unlock;
23857c20c808SMax Reitz     }
23867c20c808SMax Reitz 
23877c20c808SMax Reitz out_unlock:
23882996ffadSFam Zheng     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
23897c20c808SMax Reitz     if (local_err) {
23907c20c808SMax Reitz         /* The above call should not fail, and if it does, that does
23917c20c808SMax Reitz          * not mean the whole creation operation has failed.  So
23927c20c808SMax Reitz          * report it the user for their convenience, but do not report
23937c20c808SMax Reitz          * it to the caller. */
2394db0754dfSFam Zheng         warn_report_err(local_err);
23955a1dad9dSNir Soffer     }
23965a1dad9dSNir Soffer 
23975a1dad9dSNir Soffer out_close:
2398c1bb86cdSEric Blake     if (qemu_close(fd) != 0 && result == 0) {
2399c1bb86cdSEric Blake         result = -errno;
2400c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not close the new file");
2401c1bb86cdSEric Blake     }
2402c1bb86cdSEric Blake out:
2403c1bb86cdSEric Blake     return result;
2404c1bb86cdSEric Blake }
2405c1bb86cdSEric Blake 
2406b92902dfSMaxim Levitsky static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
2407b92902dfSMaxim Levitsky                                            const char *filename,
2408b92902dfSMaxim Levitsky                                            QemuOpts *opts,
2409927f11e1SKevin Wolf                                            Error **errp)
2410927f11e1SKevin Wolf {
2411927f11e1SKevin Wolf     BlockdevCreateOptions options;
2412927f11e1SKevin Wolf     int64_t total_size = 0;
2413927f11e1SKevin Wolf     bool nocow = false;
2414927f11e1SKevin Wolf     PreallocMode prealloc;
2415927f11e1SKevin Wolf     char *buf = NULL;
2416927f11e1SKevin Wolf     Error *local_err = NULL;
2417927f11e1SKevin Wolf 
2418927f11e1SKevin Wolf     /* Skip file: protocol prefix */
2419927f11e1SKevin Wolf     strstart(filename, "file:", &filename);
2420927f11e1SKevin Wolf 
2421927f11e1SKevin Wolf     /* Read out options */
2422927f11e1SKevin Wolf     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2423927f11e1SKevin Wolf                           BDRV_SECTOR_SIZE);
2424927f11e1SKevin Wolf     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2425927f11e1SKevin Wolf     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2426927f11e1SKevin Wolf     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2427927f11e1SKevin Wolf                                PREALLOC_MODE_OFF, &local_err);
2428927f11e1SKevin Wolf     g_free(buf);
2429927f11e1SKevin Wolf     if (local_err) {
2430927f11e1SKevin Wolf         error_propagate(errp, local_err);
2431927f11e1SKevin Wolf         return -EINVAL;
2432927f11e1SKevin Wolf     }
2433927f11e1SKevin Wolf 
2434927f11e1SKevin Wolf     options = (BlockdevCreateOptions) {
2435927f11e1SKevin Wolf         .driver     = BLOCKDEV_DRIVER_FILE,
2436927f11e1SKevin Wolf         .u.file     = {
2437927f11e1SKevin Wolf             .filename           = (char *) filename,
2438927f11e1SKevin Wolf             .size               = total_size,
2439927f11e1SKevin Wolf             .has_preallocation  = true,
2440927f11e1SKevin Wolf             .preallocation      = prealloc,
2441927f11e1SKevin Wolf             .has_nocow          = true,
2442927f11e1SKevin Wolf             .nocow              = nocow,
2443927f11e1SKevin Wolf         },
2444927f11e1SKevin Wolf     };
2445927f11e1SKevin Wolf     return raw_co_create(&options, errp);
2446927f11e1SKevin Wolf }
2447927f11e1SKevin Wolf 
24489bffae14SDaniel Henrique Barboza static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
24499bffae14SDaniel Henrique Barboza                                            Error **errp)
24509bffae14SDaniel Henrique Barboza {
24519bffae14SDaniel Henrique Barboza     struct stat st;
24529bffae14SDaniel Henrique Barboza     int ret;
24539bffae14SDaniel Henrique Barboza 
24549bffae14SDaniel Henrique Barboza     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
24559bffae14SDaniel Henrique Barboza         error_setg_errno(errp, ENOENT, "%s is not a regular file",
24569bffae14SDaniel Henrique Barboza                          bs->filename);
24579bffae14SDaniel Henrique Barboza         return -ENOENT;
24589bffae14SDaniel Henrique Barboza     }
24599bffae14SDaniel Henrique Barboza 
24609bffae14SDaniel Henrique Barboza     ret = unlink(bs->filename);
24619bffae14SDaniel Henrique Barboza     if (ret < 0) {
24629bffae14SDaniel Henrique Barboza         ret = -errno;
24639bffae14SDaniel Henrique Barboza         error_setg_errno(errp, -ret, "Error when deleting file %s",
24649bffae14SDaniel Henrique Barboza                          bs->filename);
24659bffae14SDaniel Henrique Barboza     }
24669bffae14SDaniel Henrique Barboza 
24679bffae14SDaniel Henrique Barboza     return ret;
24689bffae14SDaniel Henrique Barboza }
24699bffae14SDaniel Henrique Barboza 
2470c1bb86cdSEric Blake /*
2471c1bb86cdSEric Blake  * Find allocation range in @bs around offset @start.
2472c1bb86cdSEric Blake  * May change underlying file descriptor's file offset.
2473c1bb86cdSEric Blake  * If @start is not in a hole, store @start in @data, and the
2474c1bb86cdSEric Blake  * beginning of the next hole in @hole, and return 0.
2475c1bb86cdSEric Blake  * If @start is in a non-trailing hole, store @start in @hole and the
2476c1bb86cdSEric Blake  * beginning of the next non-hole in @data, and return 0.
2477c1bb86cdSEric Blake  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2478c1bb86cdSEric Blake  * If we can't find out, return a negative errno other than -ENXIO.
2479c1bb86cdSEric Blake  */
2480c1bb86cdSEric Blake static int find_allocation(BlockDriverState *bs, off_t start,
2481c1bb86cdSEric Blake                            off_t *data, off_t *hole)
2482c1bb86cdSEric Blake {
2483c1bb86cdSEric Blake #if defined SEEK_HOLE && defined SEEK_DATA
2484c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2485c1bb86cdSEric Blake     off_t offs;
2486c1bb86cdSEric Blake 
2487c1bb86cdSEric Blake     /*
2488c1bb86cdSEric Blake      * SEEK_DATA cases:
2489c1bb86cdSEric Blake      * D1. offs == start: start is in data
2490c1bb86cdSEric Blake      * D2. offs > start: start is in a hole, next data at offs
2491c1bb86cdSEric Blake      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2492c1bb86cdSEric Blake      *                              or start is beyond EOF
2493c1bb86cdSEric Blake      *     If the latter happens, the file has been truncated behind
2494c1bb86cdSEric Blake      *     our back since we opened it.  All bets are off then.
2495c1bb86cdSEric Blake      *     Treating like a trailing hole is simplest.
2496c1bb86cdSEric Blake      * D4. offs < 0, errno != ENXIO: we learned nothing
2497c1bb86cdSEric Blake      */
2498c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_DATA);
2499c1bb86cdSEric Blake     if (offs < 0) {
2500c1bb86cdSEric Blake         return -errno;          /* D3 or D4 */
2501c1bb86cdSEric Blake     }
2502a03083a0SJeff Cody 
2503a03083a0SJeff Cody     if (offs < start) {
2504a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2505a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like D4. */
2506a03083a0SJeff Cody         return -EIO;
2507a03083a0SJeff Cody     }
2508c1bb86cdSEric Blake 
2509c1bb86cdSEric Blake     if (offs > start) {
2510c1bb86cdSEric Blake         /* D2: in hole, next data at offs */
2511c1bb86cdSEric Blake         *hole = start;
2512c1bb86cdSEric Blake         *data = offs;
2513c1bb86cdSEric Blake         return 0;
2514c1bb86cdSEric Blake     }
2515c1bb86cdSEric Blake 
2516c1bb86cdSEric Blake     /* D1: in data, end not yet known */
2517c1bb86cdSEric Blake 
2518c1bb86cdSEric Blake     /*
2519c1bb86cdSEric Blake      * SEEK_HOLE cases:
2520c1bb86cdSEric Blake      * H1. offs == start: start is in a hole
2521c1bb86cdSEric Blake      *     If this happens here, a hole has been dug behind our back
2522c1bb86cdSEric Blake      *     since the previous lseek().
2523c1bb86cdSEric Blake      * H2. offs > start: either start is in data, next hole at offs,
2524c1bb86cdSEric Blake      *                   or start is in trailing hole, EOF at offs
2525c1bb86cdSEric Blake      *     Linux treats trailing holes like any other hole: offs ==
2526c1bb86cdSEric Blake      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2527c1bb86cdSEric Blake      *     If that happens here, a hole has been dug behind our back
2528c1bb86cdSEric Blake      *     since the previous lseek().
2529c1bb86cdSEric Blake      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2530c1bb86cdSEric Blake      *     If this happens, the file has been truncated behind our
2531c1bb86cdSEric Blake      *     back since we opened it.  Treat it like a trailing hole.
2532c1bb86cdSEric Blake      * H4. offs < 0, errno != ENXIO: we learned nothing
2533c1bb86cdSEric Blake      *     Pretend we know nothing at all, i.e. "forget" about D1.
2534c1bb86cdSEric Blake      */
2535c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_HOLE);
2536c1bb86cdSEric Blake     if (offs < 0) {
2537c1bb86cdSEric Blake         return -errno;          /* D1 and (H3 or H4) */
2538c1bb86cdSEric Blake     }
2539a03083a0SJeff Cody 
2540a03083a0SJeff Cody     if (offs < start) {
2541a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2542a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like H4. */
2543a03083a0SJeff Cody         return -EIO;
2544a03083a0SJeff Cody     }
2545c1bb86cdSEric Blake 
2546c1bb86cdSEric Blake     if (offs > start) {
2547c1bb86cdSEric Blake         /*
2548c1bb86cdSEric Blake          * D1 and H2: either in data, next hole at offs, or it was in
2549c1bb86cdSEric Blake          * data but is now in a trailing hole.  In the latter case,
2550c1bb86cdSEric Blake          * all bets are off.  Treating it as if it there was data all
2551c1bb86cdSEric Blake          * the way to EOF is safe, so simply do that.
2552c1bb86cdSEric Blake          */
2553c1bb86cdSEric Blake         *data = start;
2554c1bb86cdSEric Blake         *hole = offs;
2555c1bb86cdSEric Blake         return 0;
2556c1bb86cdSEric Blake     }
2557c1bb86cdSEric Blake 
2558c1bb86cdSEric Blake     /* D1 and H1 */
2559c1bb86cdSEric Blake     return -EBUSY;
2560c1bb86cdSEric Blake #else
2561c1bb86cdSEric Blake     return -ENOTSUP;
2562c1bb86cdSEric Blake #endif
2563c1bb86cdSEric Blake }
2564c1bb86cdSEric Blake 
2565c1bb86cdSEric Blake /*
2566a290f085SEric Blake  * Returns the allocation status of the specified offset.
2567c1bb86cdSEric Blake  *
2568a290f085SEric Blake  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2569c1bb86cdSEric Blake  *
2570a290f085SEric Blake  * 'pnum' is set to the number of bytes (including and immediately following
2571a290f085SEric Blake  * the specified offset) that are known to be in the same
2572c1bb86cdSEric Blake  * allocated/unallocated state.
2573c1bb86cdSEric Blake  *
2574a290f085SEric Blake  * 'bytes' is the max value 'pnum' should be set to.
2575c1bb86cdSEric Blake  */
2576a290f085SEric Blake static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2577a290f085SEric Blake                                             bool want_zero,
2578a290f085SEric Blake                                             int64_t offset,
2579a290f085SEric Blake                                             int64_t bytes, int64_t *pnum,
2580a290f085SEric Blake                                             int64_t *map,
2581c1bb86cdSEric Blake                                             BlockDriverState **file)
2582c1bb86cdSEric Blake {
2583a290f085SEric Blake     off_t data = 0, hole = 0;
2584c1bb86cdSEric Blake     int ret;
2585c1bb86cdSEric Blake 
25869c3db310SMax Reitz     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
25879c3db310SMax Reitz 
2588c1bb86cdSEric Blake     ret = fd_open(bs);
2589c1bb86cdSEric Blake     if (ret < 0) {
2590c1bb86cdSEric Blake         return ret;
2591c1bb86cdSEric Blake     }
2592c1bb86cdSEric Blake 
2593a290f085SEric Blake     if (!want_zero) {
2594a290f085SEric Blake         *pnum = bytes;
2595a290f085SEric Blake         *map = offset;
2596a290f085SEric Blake         *file = bs;
2597a290f085SEric Blake         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2598c1bb86cdSEric Blake     }
2599c1bb86cdSEric Blake 
2600a290f085SEric Blake     ret = find_allocation(bs, offset, &data, &hole);
2601c1bb86cdSEric Blake     if (ret == -ENXIO) {
2602c1bb86cdSEric Blake         /* Trailing hole */
2603a290f085SEric Blake         *pnum = bytes;
2604c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2605c1bb86cdSEric Blake     } else if (ret < 0) {
2606c1bb86cdSEric Blake         /* No info available, so pretend there are no holes */
2607a290f085SEric Blake         *pnum = bytes;
2608c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2609a290f085SEric Blake     } else if (data == offset) {
2610a290f085SEric Blake         /* On a data extent, compute bytes to the end of the extent,
2611c1bb86cdSEric Blake          * possibly including a partial sector at EOF. */
2612a290f085SEric Blake         *pnum = MIN(bytes, hole - offset);
26139c3db310SMax Reitz 
26149c3db310SMax Reitz         /*
26159c3db310SMax Reitz          * We are not allowed to return partial sectors, though, so
26169c3db310SMax Reitz          * round up if necessary.
26179c3db310SMax Reitz          */
26189c3db310SMax Reitz         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
26199c3db310SMax Reitz             int64_t file_length = raw_getlength(bs);
26209c3db310SMax Reitz             if (file_length > 0) {
26219c3db310SMax Reitz                 /* Ignore errors, this is just a safeguard */
26229c3db310SMax Reitz                 assert(hole == file_length);
26239c3db310SMax Reitz             }
26249c3db310SMax Reitz             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
26259c3db310SMax Reitz         }
26269c3db310SMax Reitz 
2627c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2628c1bb86cdSEric Blake     } else {
2629a290f085SEric Blake         /* On a hole, compute bytes to the beginning of the next extent.  */
2630a290f085SEric Blake         assert(hole == offset);
2631a290f085SEric Blake         *pnum = MIN(bytes, data - offset);
2632c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2633c1bb86cdSEric Blake     }
2634a290f085SEric Blake     *map = offset;
2635c1bb86cdSEric Blake     *file = bs;
2636a290f085SEric Blake     return ret | BDRV_BLOCK_OFFSET_VALID;
2637c1bb86cdSEric Blake }
2638c1bb86cdSEric Blake 
263931be8a2aSStefan Hajnoczi #if defined(__linux__)
264031be8a2aSStefan Hajnoczi /* Verify that the file is not in the page cache */
264131be8a2aSStefan Hajnoczi static void check_cache_dropped(BlockDriverState *bs, Error **errp)
264231be8a2aSStefan Hajnoczi {
264331be8a2aSStefan Hajnoczi     const size_t window_size = 128 * 1024 * 1024;
264431be8a2aSStefan Hajnoczi     BDRVRawState *s = bs->opaque;
264531be8a2aSStefan Hajnoczi     void *window = NULL;
264631be8a2aSStefan Hajnoczi     size_t length = 0;
264731be8a2aSStefan Hajnoczi     unsigned char *vec;
264831be8a2aSStefan Hajnoczi     size_t page_size;
264931be8a2aSStefan Hajnoczi     off_t offset;
265031be8a2aSStefan Hajnoczi     off_t end;
265131be8a2aSStefan Hajnoczi 
265231be8a2aSStefan Hajnoczi     /* mincore(2) page status information requires 1 byte per page */
265331be8a2aSStefan Hajnoczi     page_size = sysconf(_SC_PAGESIZE);
265431be8a2aSStefan Hajnoczi     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
265531be8a2aSStefan Hajnoczi 
265631be8a2aSStefan Hajnoczi     end = raw_getlength(bs);
265731be8a2aSStefan Hajnoczi 
265831be8a2aSStefan Hajnoczi     for (offset = 0; offset < end; offset += window_size) {
265931be8a2aSStefan Hajnoczi         void *new_window;
266031be8a2aSStefan Hajnoczi         size_t new_length;
266131be8a2aSStefan Hajnoczi         size_t vec_end;
266231be8a2aSStefan Hajnoczi         size_t i;
266331be8a2aSStefan Hajnoczi         int ret;
266431be8a2aSStefan Hajnoczi 
266531be8a2aSStefan Hajnoczi         /* Unmap previous window if size has changed */
266631be8a2aSStefan Hajnoczi         new_length = MIN(end - offset, window_size);
266731be8a2aSStefan Hajnoczi         if (new_length != length) {
266831be8a2aSStefan Hajnoczi             munmap(window, length);
266931be8a2aSStefan Hajnoczi             window = NULL;
267031be8a2aSStefan Hajnoczi             length = 0;
267131be8a2aSStefan Hajnoczi         }
267231be8a2aSStefan Hajnoczi 
267331be8a2aSStefan Hajnoczi         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
267431be8a2aSStefan Hajnoczi                           s->fd, offset);
267531be8a2aSStefan Hajnoczi         if (new_window == MAP_FAILED) {
267631be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mmap failed");
267731be8a2aSStefan Hajnoczi             break;
267831be8a2aSStefan Hajnoczi         }
267931be8a2aSStefan Hajnoczi 
268031be8a2aSStefan Hajnoczi         window = new_window;
268131be8a2aSStefan Hajnoczi         length = new_length;
268231be8a2aSStefan Hajnoczi 
268331be8a2aSStefan Hajnoczi         ret = mincore(window, length, vec);
268431be8a2aSStefan Hajnoczi         if (ret < 0) {
268531be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mincore failed");
268631be8a2aSStefan Hajnoczi             break;
268731be8a2aSStefan Hajnoczi         }
268831be8a2aSStefan Hajnoczi 
268931be8a2aSStefan Hajnoczi         vec_end = DIV_ROUND_UP(length, page_size);
269031be8a2aSStefan Hajnoczi         for (i = 0; i < vec_end; i++) {
269131be8a2aSStefan Hajnoczi             if (vec[i] & 0x1) {
269231be8a2aSStefan Hajnoczi                 break;
269331be8a2aSStefan Hajnoczi             }
269431be8a2aSStefan Hajnoczi         }
269577ed971bSMarkus Armbruster         if (i < vec_end) {
269677ed971bSMarkus Armbruster             error_setg(errp, "page cache still in use!");
269777ed971bSMarkus Armbruster             break;
269877ed971bSMarkus Armbruster         }
269931be8a2aSStefan Hajnoczi     }
270031be8a2aSStefan Hajnoczi 
270131be8a2aSStefan Hajnoczi     if (window) {
270231be8a2aSStefan Hajnoczi         munmap(window, length);
270331be8a2aSStefan Hajnoczi     }
270431be8a2aSStefan Hajnoczi 
270531be8a2aSStefan Hajnoczi     g_free(vec);
270631be8a2aSStefan Hajnoczi }
270731be8a2aSStefan Hajnoczi #endif /* __linux__ */
270831be8a2aSStefan Hajnoczi 
2709dd577a26SStefan Hajnoczi static void coroutine_fn raw_co_invalidate_cache(BlockDriverState *bs,
2710dd577a26SStefan Hajnoczi                                                  Error **errp)
2711dd577a26SStefan Hajnoczi {
2712dd577a26SStefan Hajnoczi     BDRVRawState *s = bs->opaque;
2713dd577a26SStefan Hajnoczi     int ret;
2714dd577a26SStefan Hajnoczi 
2715dd577a26SStefan Hajnoczi     ret = fd_open(bs);
2716dd577a26SStefan Hajnoczi     if (ret < 0) {
2717dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "The file descriptor is not open");
2718dd577a26SStefan Hajnoczi         return;
2719dd577a26SStefan Hajnoczi     }
2720dd577a26SStefan Hajnoczi 
2721f357fcd8SStefan Hajnoczi     if (!s->drop_cache) {
2722f357fcd8SStefan Hajnoczi         return;
2723f357fcd8SStefan Hajnoczi     }
2724f357fcd8SStefan Hajnoczi 
2725dd577a26SStefan Hajnoczi     if (s->open_flags & O_DIRECT) {
2726dd577a26SStefan Hajnoczi         return; /* No host kernel page cache */
2727dd577a26SStefan Hajnoczi     }
2728dd577a26SStefan Hajnoczi 
2729dd577a26SStefan Hajnoczi #if defined(__linux__)
2730dd577a26SStefan Hajnoczi     /* This sets the scene for the next syscall... */
2731dd577a26SStefan Hajnoczi     ret = bdrv_co_flush(bs);
2732dd577a26SStefan Hajnoczi     if (ret < 0) {
2733dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "flush failed");
2734dd577a26SStefan Hajnoczi         return;
2735dd577a26SStefan Hajnoczi     }
2736dd577a26SStefan Hajnoczi 
2737dd577a26SStefan Hajnoczi     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2738dd577a26SStefan Hajnoczi      * process.  These limitations are okay because we just fsynced the file,
2739dd577a26SStefan Hajnoczi      * we don't use mmap, and the file should not be in use by other processes.
2740dd577a26SStefan Hajnoczi      */
2741dd577a26SStefan Hajnoczi     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2742dd577a26SStefan Hajnoczi     if (ret != 0) { /* the return value is a positive errno */
2743dd577a26SStefan Hajnoczi         error_setg_errno(errp, ret, "fadvise failed");
2744dd577a26SStefan Hajnoczi         return;
2745dd577a26SStefan Hajnoczi     }
274631be8a2aSStefan Hajnoczi 
274731be8a2aSStefan Hajnoczi     if (s->check_cache_dropped) {
274831be8a2aSStefan Hajnoczi         check_cache_dropped(bs, errp);
274931be8a2aSStefan Hajnoczi     }
2750dd577a26SStefan Hajnoczi #else /* __linux__ */
2751dd577a26SStefan Hajnoczi     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2752dd577a26SStefan Hajnoczi      * unsupported on other host operating systems.  Cache consistency issues
2753dd577a26SStefan Hajnoczi      * may occur but no error is reported here, partly because that's the
2754dd577a26SStefan Hajnoczi      * historical behavior and partly because it's hard to differentiate valid
2755dd577a26SStefan Hajnoczi      * configurations that should not cause errors.
2756dd577a26SStefan Hajnoczi      */
2757dd577a26SStefan Hajnoczi #endif /* !__linux__ */
2758dd577a26SStefan Hajnoczi }
2759dd577a26SStefan Hajnoczi 
27601c450366SAnton Nefedov static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
27611c450366SAnton Nefedov {
27621c450366SAnton Nefedov     if (ret) {
27631c450366SAnton Nefedov         s->stats.discard_nb_failed++;
27641c450366SAnton Nefedov     } else {
27651c450366SAnton Nefedov         s->stats.discard_nb_ok++;
27661c450366SAnton Nefedov         s->stats.discard_bytes_ok += nbytes;
27671c450366SAnton Nefedov     }
27681c450366SAnton Nefedov }
27691c450366SAnton Nefedov 
277033d70fb6SKevin Wolf static coroutine_fn int
277146ee0f46SKevin Wolf raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int bytes, bool blkdev)
2772c1bb86cdSEric Blake {
2773c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
277446ee0f46SKevin Wolf     RawPosixAIOData acb;
27751c450366SAnton Nefedov     int ret;
2776c1bb86cdSEric Blake 
277746ee0f46SKevin Wolf     acb = (RawPosixAIOData) {
277846ee0f46SKevin Wolf         .bs             = bs,
277946ee0f46SKevin Wolf         .aio_fildes     = s->fd,
278046ee0f46SKevin Wolf         .aio_type       = QEMU_AIO_DISCARD,
278146ee0f46SKevin Wolf         .aio_offset     = offset,
278246ee0f46SKevin Wolf         .aio_nbytes     = bytes,
278346ee0f46SKevin Wolf     };
278446ee0f46SKevin Wolf 
278546ee0f46SKevin Wolf     if (blkdev) {
278646ee0f46SKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
278746ee0f46SKevin Wolf     }
278846ee0f46SKevin Wolf 
27891c450366SAnton Nefedov     ret = raw_thread_pool_submit(bs, handle_aiocb_discard, &acb);
27901c450366SAnton Nefedov     raw_account_discard(s, bytes, ret);
27911c450366SAnton Nefedov     return ret;
279246ee0f46SKevin Wolf }
279346ee0f46SKevin Wolf 
279446ee0f46SKevin Wolf static coroutine_fn int
279546ee0f46SKevin Wolf raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
279646ee0f46SKevin Wolf {
279746ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, false);
2798c1bb86cdSEric Blake }
2799c1bb86cdSEric Blake 
28007154d8aeSKevin Wolf static int coroutine_fn
28017154d8aeSKevin Wolf raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int bytes,
28027154d8aeSKevin Wolf                      BdrvRequestFlags flags, bool blkdev)
28037154d8aeSKevin Wolf {
28047154d8aeSKevin Wolf     BDRVRawState *s = bs->opaque;
28057154d8aeSKevin Wolf     RawPosixAIOData acb;
28067154d8aeSKevin Wolf     ThreadPoolFunc *handler;
28077154d8aeSKevin Wolf 
2808292d06b9SMax Reitz #ifdef CONFIG_FALLOCATE
2809292d06b9SMax Reitz     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2810292d06b9SMax Reitz         BdrvTrackedRequest *req;
2811292d06b9SMax Reitz         uint64_t end;
2812292d06b9SMax Reitz 
2813292d06b9SMax Reitz         /*
2814292d06b9SMax Reitz          * This is a workaround for a bug in the Linux XFS driver,
2815292d06b9SMax Reitz          * where writes submitted through the AIO interface will be
2816292d06b9SMax Reitz          * discarded if they happen beyond a concurrently running
2817292d06b9SMax Reitz          * fallocate() that increases the file length (i.e., both the
2818292d06b9SMax Reitz          * write and the fallocate() happen beyond the EOF).
2819292d06b9SMax Reitz          *
2820292d06b9SMax Reitz          * To work around it, we extend the tracked request for this
2821292d06b9SMax Reitz          * zero write until INT64_MAX (effectively infinity), and mark
2822292d06b9SMax Reitz          * it as serializing.
2823292d06b9SMax Reitz          *
2824292d06b9SMax Reitz          * We have to enable this workaround for all filesystems and
2825292d06b9SMax Reitz          * AIO modes (not just XFS with aio=native), because for
2826292d06b9SMax Reitz          * remote filesystems we do not know the host configuration.
2827292d06b9SMax Reitz          */
2828292d06b9SMax Reitz 
2829292d06b9SMax Reitz         req = bdrv_co_get_self_request(bs);
2830292d06b9SMax Reitz         assert(req);
2831292d06b9SMax Reitz         assert(req->type == BDRV_TRACKED_WRITE);
2832292d06b9SMax Reitz         assert(req->offset <= offset);
2833292d06b9SMax Reitz         assert(req->offset + req->bytes >= offset + bytes);
2834292d06b9SMax Reitz 
2835292d06b9SMax Reitz         end = INT64_MAX & -(uint64_t)bs->bl.request_alignment;
2836292d06b9SMax Reitz         req->bytes = end - req->offset;
2837292d06b9SMax Reitz         req->overlap_bytes = req->bytes;
2838292d06b9SMax Reitz 
2839292d06b9SMax Reitz         bdrv_mark_request_serialising(req, bs->bl.request_alignment);
2840292d06b9SMax Reitz     }
2841292d06b9SMax Reitz #endif
2842292d06b9SMax Reitz 
28437154d8aeSKevin Wolf     acb = (RawPosixAIOData) {
28447154d8aeSKevin Wolf         .bs             = bs,
28457154d8aeSKevin Wolf         .aio_fildes     = s->fd,
28467154d8aeSKevin Wolf         .aio_type       = QEMU_AIO_WRITE_ZEROES,
28477154d8aeSKevin Wolf         .aio_offset     = offset,
28487154d8aeSKevin Wolf         .aio_nbytes     = bytes,
28497154d8aeSKevin Wolf     };
28507154d8aeSKevin Wolf 
28517154d8aeSKevin Wolf     if (blkdev) {
28527154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
28537154d8aeSKevin Wolf     }
2854738301e1SKevin Wolf     if (flags & BDRV_REQ_NO_FALLBACK) {
2855738301e1SKevin Wolf         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
2856738301e1SKevin Wolf     }
28577154d8aeSKevin Wolf 
28587154d8aeSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
28597154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_DISCARD;
28607154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes_unmap;
28617154d8aeSKevin Wolf     } else {
28627154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes;
28637154d8aeSKevin Wolf     }
28647154d8aeSKevin Wolf 
28657154d8aeSKevin Wolf     return raw_thread_pool_submit(bs, handler, &acb);
28667154d8aeSKevin Wolf }
28677154d8aeSKevin Wolf 
2868c1bb86cdSEric Blake static int coroutine_fn raw_co_pwrite_zeroes(
2869c1bb86cdSEric Blake     BlockDriverState *bs, int64_t offset,
2870f5a5ca79SManos Pitsidianakis     int bytes, BdrvRequestFlags flags)
2871c1bb86cdSEric Blake {
28727154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
2873c1bb86cdSEric Blake }
2874c1bb86cdSEric Blake 
2875c1bb86cdSEric Blake static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2876c1bb86cdSEric Blake {
2877c1bb86cdSEric Blake     return 0;
2878c1bb86cdSEric Blake }
2879c1bb86cdSEric Blake 
2880d9245599SAnton Nefedov static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
2881d9245599SAnton Nefedov {
2882d9245599SAnton Nefedov     BDRVRawState *s = bs->opaque;
2883d9245599SAnton Nefedov     return (BlockStatsSpecificFile) {
2884d9245599SAnton Nefedov         .discard_nb_ok = s->stats.discard_nb_ok,
2885d9245599SAnton Nefedov         .discard_nb_failed = s->stats.discard_nb_failed,
2886d9245599SAnton Nefedov         .discard_bytes_ok = s->stats.discard_bytes_ok,
2887d9245599SAnton Nefedov     };
2888d9245599SAnton Nefedov }
2889d9245599SAnton Nefedov 
2890d9245599SAnton Nefedov static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
2891d9245599SAnton Nefedov {
2892d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
2893d9245599SAnton Nefedov 
2894d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_FILE;
2895d9245599SAnton Nefedov     stats->u.file = get_blockstats_specific_file(bs);
2896d9245599SAnton Nefedov 
2897d9245599SAnton Nefedov     return stats;
2898d9245599SAnton Nefedov }
2899d9245599SAnton Nefedov 
2900d9245599SAnton Nefedov static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
2901d9245599SAnton Nefedov {
2902d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
2903d9245599SAnton Nefedov 
2904d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
2905d9245599SAnton Nefedov     stats->u.host_device = get_blockstats_specific_file(bs);
2906d9245599SAnton Nefedov 
2907d9245599SAnton Nefedov     return stats;
2908d9245599SAnton Nefedov }
2909d9245599SAnton Nefedov 
2910c1bb86cdSEric Blake static QemuOptsList raw_create_opts = {
2911c1bb86cdSEric Blake     .name = "raw-create-opts",
2912c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2913c1bb86cdSEric Blake     .desc = {
2914c1bb86cdSEric Blake         {
2915c1bb86cdSEric Blake             .name = BLOCK_OPT_SIZE,
2916c1bb86cdSEric Blake             .type = QEMU_OPT_SIZE,
2917c1bb86cdSEric Blake             .help = "Virtual disk size"
2918c1bb86cdSEric Blake         },
2919c1bb86cdSEric Blake         {
2920c1bb86cdSEric Blake             .name = BLOCK_OPT_NOCOW,
2921c1bb86cdSEric Blake             .type = QEMU_OPT_BOOL,
2922c1bb86cdSEric Blake             .help = "Turn off copy-on-write (valid only on btrfs)"
2923c1bb86cdSEric Blake         },
2924c1bb86cdSEric Blake         {
2925c1bb86cdSEric Blake             .name = BLOCK_OPT_PREALLOC,
2926c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
2927abea0053SStefano Garzarella             .help = "Preallocation mode (allowed values: off"
2928abea0053SStefano Garzarella #ifdef CONFIG_POSIX_FALLOCATE
2929abea0053SStefano Garzarella                     ", falloc"
2930abea0053SStefano Garzarella #endif
2931abea0053SStefano Garzarella                     ", full)"
2932c1bb86cdSEric Blake         },
2933c1bb86cdSEric Blake         { /* end of list */ }
2934c1bb86cdSEric Blake     }
2935c1bb86cdSEric Blake };
2936c1bb86cdSEric Blake 
2937244a5668SFam Zheng static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2938244a5668SFam Zheng                           Error **errp)
2939244a5668SFam Zheng {
29406ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
29416ceabe6fSKevin Wolf     BDRVRawReopenState *rs = NULL;
29426ceabe6fSKevin Wolf     int open_flags;
29436ceabe6fSKevin Wolf     int ret;
29446ceabe6fSKevin Wolf 
29456ceabe6fSKevin Wolf     if (s->perm_change_fd) {
29466ceabe6fSKevin Wolf         /*
29476ceabe6fSKevin Wolf          * In the context of reopen, this function may be called several times
29486ceabe6fSKevin Wolf          * (directly and recursively while change permissions of the parent).
29496ceabe6fSKevin Wolf          * This is even true for children that don't inherit from the original
29506ceabe6fSKevin Wolf          * reopen node, so s->reopen_state is not set.
29516ceabe6fSKevin Wolf          *
29526ceabe6fSKevin Wolf          * Ignore all but the first call.
29536ceabe6fSKevin Wolf          */
29546ceabe6fSKevin Wolf         return 0;
29556ceabe6fSKevin Wolf     }
29566ceabe6fSKevin Wolf 
29576ceabe6fSKevin Wolf     if (s->reopen_state) {
29586ceabe6fSKevin Wolf         /* We already have a new file descriptor to set permissions for */
29596ceabe6fSKevin Wolf         assert(s->reopen_state->perm == perm);
29606ceabe6fSKevin Wolf         assert(s->reopen_state->shared_perm == shared);
29616ceabe6fSKevin Wolf         rs = s->reopen_state->opaque;
29626ceabe6fSKevin Wolf         s->perm_change_fd = rs->fd;
2963094e3639SMax Reitz         s->perm_change_flags = rs->open_flags;
29646ceabe6fSKevin Wolf     } else {
29656ceabe6fSKevin Wolf         /* We may need a new fd if auto-read-only switches the mode */
296623dece19SKevin Wolf         ret = raw_reconfigure_getfd(bs, bs->open_flags, &open_flags, perm,
29676ceabe6fSKevin Wolf                                     false, errp);
29686ceabe6fSKevin Wolf         if (ret < 0) {
29696ceabe6fSKevin Wolf             return ret;
29706ceabe6fSKevin Wolf         } else if (ret != s->fd) {
29716ceabe6fSKevin Wolf             s->perm_change_fd = ret;
2972094e3639SMax Reitz             s->perm_change_flags = open_flags;
29736ceabe6fSKevin Wolf         }
29746ceabe6fSKevin Wolf     }
29756ceabe6fSKevin Wolf 
29766ceabe6fSKevin Wolf     /* Prepare permissions on old fd to avoid conflicts between old and new,
29776ceabe6fSKevin Wolf      * but keep everything locked that new will need. */
29786ceabe6fSKevin Wolf     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
29796ceabe6fSKevin Wolf     if (ret < 0) {
29806ceabe6fSKevin Wolf         goto fail;
29816ceabe6fSKevin Wolf     }
29826ceabe6fSKevin Wolf 
29836ceabe6fSKevin Wolf     /* Copy locks to the new fd */
29846ceabe6fSKevin Wolf     if (s->perm_change_fd) {
29856ceabe6fSKevin Wolf         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
29866ceabe6fSKevin Wolf                                    false, errp);
29876ceabe6fSKevin Wolf         if (ret < 0) {
29886ceabe6fSKevin Wolf             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
29896ceabe6fSKevin Wolf             goto fail;
29906ceabe6fSKevin Wolf         }
29916ceabe6fSKevin Wolf     }
29926ceabe6fSKevin Wolf     return 0;
29936ceabe6fSKevin Wolf 
29946ceabe6fSKevin Wolf fail:
29956ceabe6fSKevin Wolf     if (s->perm_change_fd && !s->reopen_state) {
29966ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
29976ceabe6fSKevin Wolf     }
29986ceabe6fSKevin Wolf     s->perm_change_fd = 0;
29996ceabe6fSKevin Wolf     return ret;
3000244a5668SFam Zheng }
3001244a5668SFam Zheng 
3002244a5668SFam Zheng static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3003244a5668SFam Zheng {
3004244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
30056ceabe6fSKevin Wolf 
30066ceabe6fSKevin Wolf     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
30076ceabe6fSKevin Wolf      * called after .bdrv_reopen_commit) */
30086ceabe6fSKevin Wolf     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
30096ceabe6fSKevin Wolf         qemu_close(s->fd);
30106ceabe6fSKevin Wolf         s->fd = s->perm_change_fd;
3011094e3639SMax Reitz         s->open_flags = s->perm_change_flags;
30126ceabe6fSKevin Wolf     }
30136ceabe6fSKevin Wolf     s->perm_change_fd = 0;
30146ceabe6fSKevin Wolf 
3015244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3016244a5668SFam Zheng     s->perm = perm;
3017244a5668SFam Zheng     s->shared_perm = shared;
3018244a5668SFam Zheng }
3019244a5668SFam Zheng 
3020244a5668SFam Zheng static void raw_abort_perm_update(BlockDriverState *bs)
3021244a5668SFam Zheng {
30226ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
30236ceabe6fSKevin Wolf 
30246ceabe6fSKevin Wolf     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
30256ceabe6fSKevin Wolf      * the file descriptor. */
30266ceabe6fSKevin Wolf     if (s->perm_change_fd && !s->reopen_state) {
30276ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
30286ceabe6fSKevin Wolf     }
30296ceabe6fSKevin Wolf     s->perm_change_fd = 0;
30306ceabe6fSKevin Wolf 
3031244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3032244a5668SFam Zheng }
3033244a5668SFam Zheng 
303467b51fb9SVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_copy_range_from(
303567b51fb9SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, BdrvChild *src, uint64_t src_offset,
303667b51fb9SVladimir Sementsov-Ogievskiy         BdrvChild *dst, uint64_t dst_offset, uint64_t bytes,
303767b51fb9SVladimir Sementsov-Ogievskiy         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
30381efad060SFam Zheng {
303967b51fb9SVladimir Sementsov-Ogievskiy     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
304067b51fb9SVladimir Sementsov-Ogievskiy                                  read_flags, write_flags);
30411efad060SFam Zheng }
30421efad060SFam Zheng 
30431efad060SFam Zheng static int coroutine_fn raw_co_copy_range_to(BlockDriverState *bs,
304467b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *src,
304567b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t src_offset,
304667b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *dst,
304767b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t dst_offset,
304867b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t bytes,
304967b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags read_flags,
305067b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags write_flags)
30511efad060SFam Zheng {
305258a209c4SKevin Wolf     RawPosixAIOData acb;
30531efad060SFam Zheng     BDRVRawState *s = bs->opaque;
30541efad060SFam Zheng     BDRVRawState *src_s;
30551efad060SFam Zheng 
30561efad060SFam Zheng     assert(dst->bs == bs);
30571efad060SFam Zheng     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
30581efad060SFam Zheng         return -ENOTSUP;
30591efad060SFam Zheng     }
30601efad060SFam Zheng 
30611efad060SFam Zheng     src_s = src->bs->opaque;
30629f850f67SFam Zheng     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
30631efad060SFam Zheng         return -EIO;
30641efad060SFam Zheng     }
306558a209c4SKevin Wolf 
306658a209c4SKevin Wolf     acb = (RawPosixAIOData) {
306758a209c4SKevin Wolf         .bs             = bs,
306858a209c4SKevin Wolf         .aio_type       = QEMU_AIO_COPY_RANGE,
306958a209c4SKevin Wolf         .aio_fildes     = src_s->fd,
307058a209c4SKevin Wolf         .aio_offset     = src_offset,
307158a209c4SKevin Wolf         .aio_nbytes     = bytes,
307258a209c4SKevin Wolf         .copy_range     = {
307358a209c4SKevin Wolf             .aio_fd2        = s->fd,
307458a209c4SKevin Wolf             .aio_offset2    = dst_offset,
307558a209c4SKevin Wolf         },
307658a209c4SKevin Wolf     };
307758a209c4SKevin Wolf 
307858a209c4SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_copy_range, &acb);
30791efad060SFam Zheng }
30801efad060SFam Zheng 
3081c1bb86cdSEric Blake BlockDriver bdrv_file = {
3082c1bb86cdSEric Blake     .format_name = "file",
3083c1bb86cdSEric Blake     .protocol_name = "file",
3084c1bb86cdSEric Blake     .instance_size = sizeof(BDRVRawState),
3085c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3086c1bb86cdSEric Blake     .bdrv_probe = NULL, /* no probe for protocols */
3087c1bb86cdSEric Blake     .bdrv_parse_filename = raw_parse_filename,
3088c1bb86cdSEric Blake     .bdrv_file_open = raw_open,
3089c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3090c1bb86cdSEric Blake     .bdrv_reopen_commit = raw_reopen_commit,
3091c1bb86cdSEric Blake     .bdrv_reopen_abort = raw_reopen_abort,
3092c1bb86cdSEric Blake     .bdrv_close = raw_close,
3093927f11e1SKevin Wolf     .bdrv_co_create = raw_co_create,
3094efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = raw_co_create_opts,
3095c1bb86cdSEric Blake     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3096a290f085SEric Blake     .bdrv_co_block_status = raw_co_block_status,
3097dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3098c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
30999bffae14SDaniel Henrique Barboza     .bdrv_co_delete_file = raw_co_delete_file,
3100c1bb86cdSEric Blake 
3101c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3102c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
310333d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
310433d70fb6SKevin Wolf     .bdrv_co_pdiscard       = raw_co_pdiscard,
31051efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
31061efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3107c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3108c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3109c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3110ed6e2161SNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3111c1bb86cdSEric Blake 
3112061ca8a3SKevin Wolf     .bdrv_co_truncate = raw_co_truncate,
3113c1bb86cdSEric Blake     .bdrv_getlength = raw_getlength,
3114c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3115c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3116c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3117d9245599SAnton Nefedov     .bdrv_get_specific_stats = raw_get_specific_stats,
3118244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3119244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3120244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3121c1bb86cdSEric Blake     .create_opts = &raw_create_opts,
31228a2ce0bcSAlberto Garcia     .mutable_opts = mutable_opts,
3123c1bb86cdSEric Blake };
3124c1bb86cdSEric Blake 
3125c1bb86cdSEric Blake /***********************************************/
3126c1bb86cdSEric Blake /* host device */
3127c1bb86cdSEric Blake 
3128c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3129c1bb86cdSEric Blake static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3130c1bb86cdSEric Blake                                 CFIndex maxPathSize, int flags);
3131c1bb86cdSEric Blake static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3132c1bb86cdSEric Blake {
3133c1bb86cdSEric Blake     kern_return_t kernResult = KERN_FAILURE;
3134c1bb86cdSEric Blake     mach_port_t     masterPort;
3135c1bb86cdSEric Blake     CFMutableDictionaryRef  classesToMatch;
3136c1bb86cdSEric Blake     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3137c1bb86cdSEric Blake     char *mediaType = NULL;
3138c1bb86cdSEric Blake 
3139c1bb86cdSEric Blake     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
3140c1bb86cdSEric Blake     if ( KERN_SUCCESS != kernResult ) {
3141c1bb86cdSEric Blake         printf( "IOMasterPort returned %d\n", kernResult );
3142c1bb86cdSEric Blake     }
3143c1bb86cdSEric Blake 
3144c1bb86cdSEric Blake     int index;
3145c1bb86cdSEric Blake     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3146c1bb86cdSEric Blake         classesToMatch = IOServiceMatching(matching_array[index]);
3147c1bb86cdSEric Blake         if (classesToMatch == NULL) {
3148c1bb86cdSEric Blake             error_report("IOServiceMatching returned NULL for %s",
3149c1bb86cdSEric Blake                          matching_array[index]);
3150c1bb86cdSEric Blake             continue;
3151c1bb86cdSEric Blake         }
3152c1bb86cdSEric Blake         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3153c1bb86cdSEric Blake                              kCFBooleanTrue);
3154c1bb86cdSEric Blake         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
3155c1bb86cdSEric Blake                                                   mediaIterator);
3156c1bb86cdSEric Blake         if (kernResult != KERN_SUCCESS) {
3157c1bb86cdSEric Blake             error_report("Note: IOServiceGetMatchingServices returned %d",
3158c1bb86cdSEric Blake                          kernResult);
3159c1bb86cdSEric Blake             continue;
3160c1bb86cdSEric Blake         }
3161c1bb86cdSEric Blake 
3162c1bb86cdSEric Blake         /* If a match was found, leave the loop */
3163c1bb86cdSEric Blake         if (*mediaIterator != 0) {
31644f7d28d7SLaurent Vivier             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3165c1bb86cdSEric Blake             mediaType = g_strdup(matching_array[index]);
3166c1bb86cdSEric Blake             break;
3167c1bb86cdSEric Blake         }
3168c1bb86cdSEric Blake     }
3169c1bb86cdSEric Blake     return mediaType;
3170c1bb86cdSEric Blake }
3171c1bb86cdSEric Blake 
3172c1bb86cdSEric Blake kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3173c1bb86cdSEric Blake                          CFIndex maxPathSize, int flags)
3174c1bb86cdSEric Blake {
3175c1bb86cdSEric Blake     io_object_t     nextMedia;
3176c1bb86cdSEric Blake     kern_return_t   kernResult = KERN_FAILURE;
3177c1bb86cdSEric Blake     *bsdPath = '\0';
3178c1bb86cdSEric Blake     nextMedia = IOIteratorNext( mediaIterator );
3179c1bb86cdSEric Blake     if ( nextMedia )
3180c1bb86cdSEric Blake     {
3181c1bb86cdSEric Blake         CFTypeRef   bsdPathAsCFString;
3182c1bb86cdSEric Blake     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3183c1bb86cdSEric Blake         if ( bsdPathAsCFString ) {
3184c1bb86cdSEric Blake             size_t devPathLength;
3185c1bb86cdSEric Blake             strcpy( bsdPath, _PATH_DEV );
3186c1bb86cdSEric Blake             if (flags & BDRV_O_NOCACHE) {
3187c1bb86cdSEric Blake                 strcat(bsdPath, "r");
3188c1bb86cdSEric Blake             }
3189c1bb86cdSEric Blake             devPathLength = strlen( bsdPath );
3190c1bb86cdSEric Blake             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3191c1bb86cdSEric Blake                 kernResult = KERN_SUCCESS;
3192c1bb86cdSEric Blake             }
3193c1bb86cdSEric Blake             CFRelease( bsdPathAsCFString );
3194c1bb86cdSEric Blake         }
3195c1bb86cdSEric Blake         IOObjectRelease( nextMedia );
3196c1bb86cdSEric Blake     }
3197c1bb86cdSEric Blake 
3198c1bb86cdSEric Blake     return kernResult;
3199c1bb86cdSEric Blake }
3200c1bb86cdSEric Blake 
3201c1bb86cdSEric Blake /* Sets up a real cdrom for use in QEMU */
3202c1bb86cdSEric Blake static bool setup_cdrom(char *bsd_path, Error **errp)
3203c1bb86cdSEric Blake {
3204c1bb86cdSEric Blake     int index, num_of_test_partitions = 2, fd;
3205c1bb86cdSEric Blake     char test_partition[MAXPATHLEN];
3206c1bb86cdSEric Blake     bool partition_found = false;
3207c1bb86cdSEric Blake 
3208c1bb86cdSEric Blake     /* look for a working partition */
3209c1bb86cdSEric Blake     for (index = 0; index < num_of_test_partitions; index++) {
3210c1bb86cdSEric Blake         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3211c1bb86cdSEric Blake                  index);
3212c1bb86cdSEric Blake         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
3213c1bb86cdSEric Blake         if (fd >= 0) {
3214c1bb86cdSEric Blake             partition_found = true;
3215c1bb86cdSEric Blake             qemu_close(fd);
3216c1bb86cdSEric Blake             break;
3217c1bb86cdSEric Blake         }
3218c1bb86cdSEric Blake     }
3219c1bb86cdSEric Blake 
3220c1bb86cdSEric Blake     /* if a working partition on the device was not found */
3221c1bb86cdSEric Blake     if (partition_found == false) {
3222c1bb86cdSEric Blake         error_setg(errp, "Failed to find a working partition on disc");
3223c1bb86cdSEric Blake     } else {
32244f7d28d7SLaurent Vivier         trace_file_setup_cdrom(test_partition);
3225c1bb86cdSEric Blake         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
3226c1bb86cdSEric Blake     }
3227c1bb86cdSEric Blake     return partition_found;
3228c1bb86cdSEric Blake }
3229c1bb86cdSEric Blake 
3230c1bb86cdSEric Blake /* Prints directions on mounting and unmounting a device */
3231c1bb86cdSEric Blake static void print_unmounting_directions(const char *file_name)
3232c1bb86cdSEric Blake {
3233c1bb86cdSEric Blake     error_report("If device %s is mounted on the desktop, unmount"
3234c1bb86cdSEric Blake                  " it first before using it in QEMU", file_name);
3235c1bb86cdSEric Blake     error_report("Command to unmount device: diskutil unmountDisk %s",
3236c1bb86cdSEric Blake                  file_name);
3237c1bb86cdSEric Blake     error_report("Command to mount device: diskutil mountDisk %s", file_name);
3238c1bb86cdSEric Blake }
3239c1bb86cdSEric Blake 
3240c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3241c1bb86cdSEric Blake 
3242c1bb86cdSEric Blake static int hdev_probe_device(const char *filename)
3243c1bb86cdSEric Blake {
3244c1bb86cdSEric Blake     struct stat st;
3245c1bb86cdSEric Blake 
3246c1bb86cdSEric Blake     /* allow a dedicated CD-ROM driver to match with a higher priority */
3247c1bb86cdSEric Blake     if (strstart(filename, "/dev/cdrom", NULL))
3248c1bb86cdSEric Blake         return 50;
3249c1bb86cdSEric Blake 
3250c1bb86cdSEric Blake     if (stat(filename, &st) >= 0 &&
3251c1bb86cdSEric Blake             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
3252c1bb86cdSEric Blake         return 100;
3253c1bb86cdSEric Blake     }
3254c1bb86cdSEric Blake 
3255c1bb86cdSEric Blake     return 0;
3256c1bb86cdSEric Blake }
3257c1bb86cdSEric Blake 
3258c1bb86cdSEric Blake static int check_hdev_writable(BDRVRawState *s)
3259c1bb86cdSEric Blake {
3260c1bb86cdSEric Blake #if defined(BLKROGET)
3261c1bb86cdSEric Blake     /* Linux block devices can be configured "read-only" using blockdev(8).
3262c1bb86cdSEric Blake      * This is independent of device node permissions and therefore open(2)
3263c1bb86cdSEric Blake      * with O_RDWR succeeds.  Actual writes fail with EPERM.
3264c1bb86cdSEric Blake      *
3265c1bb86cdSEric Blake      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
3266c1bb86cdSEric Blake      * check for read-only block devices so that Linux block devices behave
3267c1bb86cdSEric Blake      * properly.
3268c1bb86cdSEric Blake      */
3269c1bb86cdSEric Blake     struct stat st;
3270c1bb86cdSEric Blake     int readonly = 0;
3271c1bb86cdSEric Blake 
3272c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
3273c1bb86cdSEric Blake         return -errno;
3274c1bb86cdSEric Blake     }
3275c1bb86cdSEric Blake 
3276c1bb86cdSEric Blake     if (!S_ISBLK(st.st_mode)) {
3277c1bb86cdSEric Blake         return 0;
3278c1bb86cdSEric Blake     }
3279c1bb86cdSEric Blake 
3280c1bb86cdSEric Blake     if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
3281c1bb86cdSEric Blake         return -errno;
3282c1bb86cdSEric Blake     }
3283c1bb86cdSEric Blake 
3284c1bb86cdSEric Blake     if (readonly) {
3285c1bb86cdSEric Blake         return -EACCES;
3286c1bb86cdSEric Blake     }
3287c1bb86cdSEric Blake #endif /* defined(BLKROGET) */
3288c1bb86cdSEric Blake     return 0;
3289c1bb86cdSEric Blake }
3290c1bb86cdSEric Blake 
3291c1bb86cdSEric Blake static void hdev_parse_filename(const char *filename, QDict *options,
3292c1bb86cdSEric Blake                                 Error **errp)
3293c1bb86cdSEric Blake {
329403c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
3295c1bb86cdSEric Blake }
3296c1bb86cdSEric Blake 
3297c1bb86cdSEric Blake static bool hdev_is_sg(BlockDriverState *bs)
3298c1bb86cdSEric Blake {
3299c1bb86cdSEric Blake 
3300c1bb86cdSEric Blake #if defined(__linux__)
3301c1bb86cdSEric Blake 
3302c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3303c1bb86cdSEric Blake     struct stat st;
3304c1bb86cdSEric Blake     struct sg_scsi_id scsiid;
3305c1bb86cdSEric Blake     int sg_version;
3306c1bb86cdSEric Blake     int ret;
3307c1bb86cdSEric Blake 
3308c1bb86cdSEric Blake     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
3309c1bb86cdSEric Blake         return false;
3310c1bb86cdSEric Blake     }
3311c1bb86cdSEric Blake 
3312c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
3313c1bb86cdSEric Blake     if (ret < 0) {
3314c1bb86cdSEric Blake         return false;
3315c1bb86cdSEric Blake     }
3316c1bb86cdSEric Blake 
3317c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
3318c1bb86cdSEric Blake     if (ret >= 0) {
33194f7d28d7SLaurent Vivier         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3320c1bb86cdSEric Blake         return true;
3321c1bb86cdSEric Blake     }
3322c1bb86cdSEric Blake 
3323c1bb86cdSEric Blake #endif
3324c1bb86cdSEric Blake 
3325c1bb86cdSEric Blake     return false;
3326c1bb86cdSEric Blake }
3327c1bb86cdSEric Blake 
3328c1bb86cdSEric Blake static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
3329c1bb86cdSEric Blake                      Error **errp)
3330c1bb86cdSEric Blake {
3331c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3332c1bb86cdSEric Blake     int ret;
3333c1bb86cdSEric Blake 
3334c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3335129c7d1cSMarkus Armbruster     /*
3336129c7d1cSMarkus Armbruster      * Caution: while qdict_get_str() is fine, getting non-string types
3337129c7d1cSMarkus Armbruster      * would require more care.  When @options come from -blockdev or
3338129c7d1cSMarkus Armbruster      * blockdev_add, its members are typed according to the QAPI
3339129c7d1cSMarkus Armbruster      * schema, but when they come from -drive, they're all QString.
3340129c7d1cSMarkus Armbruster      */
3341c1bb86cdSEric Blake     const char *filename = qdict_get_str(options, "filename");
3342c1bb86cdSEric Blake     char bsd_path[MAXPATHLEN] = "";
3343c1bb86cdSEric Blake     bool error_occurred = false;
3344c1bb86cdSEric Blake 
3345c1bb86cdSEric Blake     /* If using a real cdrom */
3346c1bb86cdSEric Blake     if (strcmp(filename, "/dev/cdrom") == 0) {
3347c1bb86cdSEric Blake         char *mediaType = NULL;
3348c1bb86cdSEric Blake         kern_return_t ret_val;
3349c1bb86cdSEric Blake         io_iterator_t mediaIterator = 0;
3350c1bb86cdSEric Blake 
3351c1bb86cdSEric Blake         mediaType = FindEjectableOpticalMedia(&mediaIterator);
3352c1bb86cdSEric Blake         if (mediaType == NULL) {
3353c1bb86cdSEric Blake             error_setg(errp, "Please make sure your CD/DVD is in the optical"
3354c1bb86cdSEric Blake                        " drive");
3355c1bb86cdSEric Blake             error_occurred = true;
3356c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3357c1bb86cdSEric Blake         }
3358c1bb86cdSEric Blake 
3359c1bb86cdSEric Blake         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
3360c1bb86cdSEric Blake         if (ret_val != KERN_SUCCESS) {
3361c1bb86cdSEric Blake             error_setg(errp, "Could not get BSD path for optical drive");
3362c1bb86cdSEric Blake             error_occurred = true;
3363c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3364c1bb86cdSEric Blake         }
3365c1bb86cdSEric Blake 
3366c1bb86cdSEric Blake         /* If a real optical drive was not found */
3367c1bb86cdSEric Blake         if (bsd_path[0] == '\0') {
3368c1bb86cdSEric Blake             error_setg(errp, "Failed to obtain bsd path for optical drive");
3369c1bb86cdSEric Blake             error_occurred = true;
3370c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3371c1bb86cdSEric Blake         }
3372c1bb86cdSEric Blake 
3373c1bb86cdSEric Blake         /* If using a cdrom disc and finding a partition on the disc failed */
3374c1bb86cdSEric Blake         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
3375c1bb86cdSEric Blake             setup_cdrom(bsd_path, errp) == false) {
3376c1bb86cdSEric Blake             print_unmounting_directions(bsd_path);
3377c1bb86cdSEric Blake             error_occurred = true;
3378c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3379c1bb86cdSEric Blake         }
3380c1bb86cdSEric Blake 
338146f5ac20SEric Blake         qdict_put_str(options, "filename", bsd_path);
3382c1bb86cdSEric Blake 
3383c1bb86cdSEric Blake hdev_open_Mac_error:
3384c1bb86cdSEric Blake         g_free(mediaType);
3385c1bb86cdSEric Blake         if (mediaIterator) {
3386c1bb86cdSEric Blake             IOObjectRelease(mediaIterator);
3387c1bb86cdSEric Blake         }
3388c1bb86cdSEric Blake         if (error_occurred) {
3389c1bb86cdSEric Blake             return -ENOENT;
3390c1bb86cdSEric Blake         }
3391c1bb86cdSEric Blake     }
3392c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3393c1bb86cdSEric Blake 
3394c1bb86cdSEric Blake     s->type = FTYPE_FILE;
3395c1bb86cdSEric Blake 
3396668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3397c1bb86cdSEric Blake     if (ret < 0) {
3398c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3399c1bb86cdSEric Blake         if (*bsd_path) {
3400c1bb86cdSEric Blake             filename = bsd_path;
3401c1bb86cdSEric Blake         }
3402c1bb86cdSEric Blake         /* if a physical device experienced an error while being opened */
3403c1bb86cdSEric Blake         if (strncmp(filename, "/dev/", 5) == 0) {
3404c1bb86cdSEric Blake             print_unmounting_directions(filename);
3405c1bb86cdSEric Blake         }
3406c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3407c1bb86cdSEric Blake         return ret;
3408c1bb86cdSEric Blake     }
3409c1bb86cdSEric Blake 
3410c1bb86cdSEric Blake     /* Since this does ioctl the device must be already opened */
3411c1bb86cdSEric Blake     bs->sg = hdev_is_sg(bs);
3412c1bb86cdSEric Blake 
3413c1bb86cdSEric Blake     if (flags & BDRV_O_RDWR) {
3414c1bb86cdSEric Blake         ret = check_hdev_writable(s);
3415c1bb86cdSEric Blake         if (ret < 0) {
3416c1bb86cdSEric Blake             raw_close(bs);
3417c1bb86cdSEric Blake             error_setg_errno(errp, -ret, "The device is not writable");
3418c1bb86cdSEric Blake             return ret;
3419c1bb86cdSEric Blake         }
3420c1bb86cdSEric Blake     }
3421c1bb86cdSEric Blake 
3422c1bb86cdSEric Blake     return ret;
3423c1bb86cdSEric Blake }
3424c1bb86cdSEric Blake 
3425c1bb86cdSEric Blake #if defined(__linux__)
34262f3a7ab3SKevin Wolf static int coroutine_fn
34272f3a7ab3SKevin Wolf hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3428c1bb86cdSEric Blake {
3429c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
343003425671SKevin Wolf     RawPosixAIOData acb;
34312f3a7ab3SKevin Wolf     int ret;
3432c1bb86cdSEric Blake 
34332f3a7ab3SKevin Wolf     ret = fd_open(bs);
34342f3a7ab3SKevin Wolf     if (ret < 0) {
34352f3a7ab3SKevin Wolf         return ret;
34362f3a7ab3SKevin Wolf     }
3437c1bb86cdSEric Blake 
34387c9e5276SPaolo Bonzini     if (req == SG_IO && s->pr_mgr) {
34397c9e5276SPaolo Bonzini         struct sg_io_hdr *io_hdr = buf;
34407c9e5276SPaolo Bonzini         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
34417c9e5276SPaolo Bonzini             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
34427c9e5276SPaolo Bonzini             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
34432f3a7ab3SKevin Wolf                                       s->fd, io_hdr);
34447c9e5276SPaolo Bonzini         }
34457c9e5276SPaolo Bonzini     }
34467c9e5276SPaolo Bonzini 
344703425671SKevin Wolf     acb = (RawPosixAIOData) {
344803425671SKevin Wolf         .bs         = bs,
344903425671SKevin Wolf         .aio_type   = QEMU_AIO_IOCTL,
345003425671SKevin Wolf         .aio_fildes = s->fd,
345103425671SKevin Wolf         .aio_offset = 0,
345203425671SKevin Wolf         .ioctl      = {
345303425671SKevin Wolf             .buf        = buf,
345403425671SKevin Wolf             .cmd        = req,
345503425671SKevin Wolf         },
345603425671SKevin Wolf     };
345703425671SKevin Wolf 
345803425671SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_ioctl, &acb);
3459c1bb86cdSEric Blake }
3460c1bb86cdSEric Blake #endif /* linux */
3461c1bb86cdSEric Blake 
3462c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs)
3463c1bb86cdSEric Blake {
3464c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3465c1bb86cdSEric Blake 
3466c1bb86cdSEric Blake     /* this is just to ensure s->fd is sane (its called by io ops) */
3467c1bb86cdSEric Blake     if (s->fd >= 0)
3468c1bb86cdSEric Blake         return 0;
3469c1bb86cdSEric Blake     return -EIO;
3470c1bb86cdSEric Blake }
3471c1bb86cdSEric Blake 
347233d70fb6SKevin Wolf static coroutine_fn int
347333d70fb6SKevin Wolf hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
3474c1bb86cdSEric Blake {
34751c450366SAnton Nefedov     BDRVRawState *s = bs->opaque;
347633d70fb6SKevin Wolf     int ret;
3477c1bb86cdSEric Blake 
347833d70fb6SKevin Wolf     ret = fd_open(bs);
347933d70fb6SKevin Wolf     if (ret < 0) {
34801c450366SAnton Nefedov         raw_account_discard(s, bytes, ret);
348133d70fb6SKevin Wolf         return ret;
3482c1bb86cdSEric Blake     }
348346ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, true);
3484c1bb86cdSEric Blake }
3485c1bb86cdSEric Blake 
3486c1bb86cdSEric Blake static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3487f5a5ca79SManos Pitsidianakis     int64_t offset, int bytes, BdrvRequestFlags flags)
3488c1bb86cdSEric Blake {
3489c1bb86cdSEric Blake     int rc;
3490c1bb86cdSEric Blake 
3491c1bb86cdSEric Blake     rc = fd_open(bs);
3492c1bb86cdSEric Blake     if (rc < 0) {
3493c1bb86cdSEric Blake         return rc;
3494c1bb86cdSEric Blake     }
349534fa110eSKevin Wolf 
34967154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
3497c1bb86cdSEric Blake }
3498c1bb86cdSEric Blake 
3499c1bb86cdSEric Blake static BlockDriver bdrv_host_device = {
3500c1bb86cdSEric Blake     .format_name        = "host_device",
3501c1bb86cdSEric Blake     .protocol_name        = "host_device",
3502c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3503c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3504c1bb86cdSEric Blake     .bdrv_probe_device  = hdev_probe_device,
3505c1bb86cdSEric Blake     .bdrv_parse_filename = hdev_parse_filename,
3506c1bb86cdSEric Blake     .bdrv_file_open     = hdev_open,
3507c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3508c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3509c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3510c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
35115a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
35125a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
35138a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3514dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3515c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3516c1bb86cdSEric Blake 
3517c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3518c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
351933d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
352033d70fb6SKevin Wolf     .bdrv_co_pdiscard       = hdev_co_pdiscard,
35211efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
35221efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3523c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3524c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3525c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3526042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3527c1bb86cdSEric Blake 
3528061ca8a3SKevin Wolf     .bdrv_co_truncate       = raw_co_truncate,
3529c1bb86cdSEric Blake     .bdrv_getlength	= raw_getlength,
3530c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3531c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3532c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3533d9245599SAnton Nefedov     .bdrv_get_specific_stats = hdev_get_specific_stats,
3534244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3535244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3536244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3537c1bb86cdSEric Blake     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3538c1bb86cdSEric Blake     .bdrv_probe_geometry = hdev_probe_geometry,
3539c1bb86cdSEric Blake 
3540c1bb86cdSEric Blake     /* generic scsi device */
3541c1bb86cdSEric Blake #ifdef __linux__
35422f3a7ab3SKevin Wolf     .bdrv_co_ioctl          = hdev_co_ioctl,
3543c1bb86cdSEric Blake #endif
3544c1bb86cdSEric Blake };
3545c1bb86cdSEric Blake 
3546c1bb86cdSEric Blake #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3547c1bb86cdSEric Blake static void cdrom_parse_filename(const char *filename, QDict *options,
3548c1bb86cdSEric Blake                                  Error **errp)
3549c1bb86cdSEric Blake {
355003c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3551c1bb86cdSEric Blake }
3552c1bb86cdSEric Blake #endif
3553c1bb86cdSEric Blake 
3554c1bb86cdSEric Blake #ifdef __linux__
3555c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3556c1bb86cdSEric Blake                       Error **errp)
3557c1bb86cdSEric Blake {
3558c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3559c1bb86cdSEric Blake 
3560c1bb86cdSEric Blake     s->type = FTYPE_CD;
3561c1bb86cdSEric Blake 
3562c1bb86cdSEric Blake     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3563230ff739SJohn Snow     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3564c1bb86cdSEric Blake }
3565c1bb86cdSEric Blake 
3566c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3567c1bb86cdSEric Blake {
3568c1bb86cdSEric Blake     int fd, ret;
3569c1bb86cdSEric Blake     int prio = 0;
3570c1bb86cdSEric Blake     struct stat st;
3571c1bb86cdSEric Blake 
3572c1bb86cdSEric Blake     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
3573c1bb86cdSEric Blake     if (fd < 0) {
3574c1bb86cdSEric Blake         goto out;
3575c1bb86cdSEric Blake     }
3576c1bb86cdSEric Blake     ret = fstat(fd, &st);
3577c1bb86cdSEric Blake     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3578c1bb86cdSEric Blake         goto outc;
3579c1bb86cdSEric Blake     }
3580c1bb86cdSEric Blake 
3581c1bb86cdSEric Blake     /* Attempt to detect via a CDROM specific ioctl */
3582c1bb86cdSEric Blake     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3583c1bb86cdSEric Blake     if (ret >= 0)
3584c1bb86cdSEric Blake         prio = 100;
3585c1bb86cdSEric Blake 
3586c1bb86cdSEric Blake outc:
3587c1bb86cdSEric Blake     qemu_close(fd);
3588c1bb86cdSEric Blake out:
3589c1bb86cdSEric Blake     return prio;
3590c1bb86cdSEric Blake }
3591c1bb86cdSEric Blake 
3592c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3593c1bb86cdSEric Blake {
3594c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3595c1bb86cdSEric Blake     int ret;
3596c1bb86cdSEric Blake 
3597c1bb86cdSEric Blake     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3598c1bb86cdSEric Blake     return ret == CDS_DISC_OK;
3599c1bb86cdSEric Blake }
3600c1bb86cdSEric Blake 
3601c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3602c1bb86cdSEric Blake {
3603c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3604c1bb86cdSEric Blake 
3605c1bb86cdSEric Blake     if (eject_flag) {
3606c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3607c1bb86cdSEric Blake             perror("CDROMEJECT");
3608c1bb86cdSEric Blake     } else {
3609c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3610c1bb86cdSEric Blake             perror("CDROMEJECT");
3611c1bb86cdSEric Blake     }
3612c1bb86cdSEric Blake }
3613c1bb86cdSEric Blake 
3614c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3615c1bb86cdSEric Blake {
3616c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3617c1bb86cdSEric Blake 
3618c1bb86cdSEric Blake     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3619c1bb86cdSEric Blake         /*
3620c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3621c1bb86cdSEric Blake          * mounts the CD-ROM
3622c1bb86cdSEric Blake          */
3623c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3624c1bb86cdSEric Blake     }
3625c1bb86cdSEric Blake }
3626c1bb86cdSEric Blake 
3627c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3628c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3629c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3630c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3631c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3632c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3633c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3634c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3635c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3636c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3637c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3638c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
36395a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
36405a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
36418a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3642dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3643c1bb86cdSEric Blake 
3644c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3645c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
364633d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3647c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3648c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3649c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3650042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3651c1bb86cdSEric Blake 
3652061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3653c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3654c1bb86cdSEric Blake     .has_variable_length = true,
3655c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3656c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3657c1bb86cdSEric Blake 
3658c1bb86cdSEric Blake     /* removable device support */
3659c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3660c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3661c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3662c1bb86cdSEric Blake 
3663c1bb86cdSEric Blake     /* generic scsi device */
36642f3a7ab3SKevin Wolf     .bdrv_co_ioctl      = hdev_co_ioctl,
3665c1bb86cdSEric Blake };
3666c1bb86cdSEric Blake #endif /* __linux__ */
3667c1bb86cdSEric Blake 
3668c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3669c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3670c1bb86cdSEric Blake                       Error **errp)
3671c1bb86cdSEric Blake {
3672c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3673c1bb86cdSEric Blake     int ret;
3674c1bb86cdSEric Blake 
3675c1bb86cdSEric Blake     s->type = FTYPE_CD;
3676c1bb86cdSEric Blake 
3677668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3678c1bb86cdSEric Blake     if (ret) {
3679c1bb86cdSEric Blake         return ret;
3680c1bb86cdSEric Blake     }
3681c1bb86cdSEric Blake 
3682c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3683c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3684c1bb86cdSEric Blake     return 0;
3685c1bb86cdSEric Blake }
3686c1bb86cdSEric Blake 
3687c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3688c1bb86cdSEric Blake {
3689c1bb86cdSEric Blake     if (strstart(filename, "/dev/cd", NULL) ||
3690c1bb86cdSEric Blake             strstart(filename, "/dev/acd", NULL))
3691c1bb86cdSEric Blake         return 100;
3692c1bb86cdSEric Blake     return 0;
3693c1bb86cdSEric Blake }
3694c1bb86cdSEric Blake 
3695c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs)
3696c1bb86cdSEric Blake {
3697c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3698c1bb86cdSEric Blake     int fd;
3699c1bb86cdSEric Blake 
3700c1bb86cdSEric Blake     /*
3701c1bb86cdSEric Blake      * Force reread of possibly changed/newly loaded disc,
3702c1bb86cdSEric Blake      * FreeBSD seems to not notice sometimes...
3703c1bb86cdSEric Blake      */
3704c1bb86cdSEric Blake     if (s->fd >= 0)
3705c1bb86cdSEric Blake         qemu_close(s->fd);
3706c1bb86cdSEric Blake     fd = qemu_open(bs->filename, s->open_flags, 0644);
3707c1bb86cdSEric Blake     if (fd < 0) {
3708c1bb86cdSEric Blake         s->fd = -1;
3709c1bb86cdSEric Blake         return -EIO;
3710c1bb86cdSEric Blake     }
3711c1bb86cdSEric Blake     s->fd = fd;
3712c1bb86cdSEric Blake 
3713c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3714c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3715c1bb86cdSEric Blake     return 0;
3716c1bb86cdSEric Blake }
3717c1bb86cdSEric Blake 
3718c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3719c1bb86cdSEric Blake {
3720c1bb86cdSEric Blake     return raw_getlength(bs) > 0;
3721c1bb86cdSEric Blake }
3722c1bb86cdSEric Blake 
3723c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3724c1bb86cdSEric Blake {
3725c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3726c1bb86cdSEric Blake 
3727c1bb86cdSEric Blake     if (s->fd < 0)
3728c1bb86cdSEric Blake         return;
3729c1bb86cdSEric Blake 
3730c1bb86cdSEric Blake     (void) ioctl(s->fd, CDIOCALLOW);
3731c1bb86cdSEric Blake 
3732c1bb86cdSEric Blake     if (eject_flag) {
3733c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCEJECT) < 0)
3734c1bb86cdSEric Blake             perror("CDIOCEJECT");
3735c1bb86cdSEric Blake     } else {
3736c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3737c1bb86cdSEric Blake             perror("CDIOCCLOSE");
3738c1bb86cdSEric Blake     }
3739c1bb86cdSEric Blake 
3740c1bb86cdSEric Blake     cdrom_reopen(bs);
3741c1bb86cdSEric Blake }
3742c1bb86cdSEric Blake 
3743c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3744c1bb86cdSEric Blake {
3745c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3746c1bb86cdSEric Blake 
3747c1bb86cdSEric Blake     if (s->fd < 0)
3748c1bb86cdSEric Blake         return;
3749c1bb86cdSEric Blake     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3750c1bb86cdSEric Blake         /*
3751c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3752c1bb86cdSEric Blake          * mounts the CD-ROM
3753c1bb86cdSEric Blake          */
3754c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3755c1bb86cdSEric Blake     }
3756c1bb86cdSEric Blake }
3757c1bb86cdSEric Blake 
3758c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3759c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3760c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3761c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3762c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3763c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3764c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3765c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3766c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3767c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3768c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3769c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
37705a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
37715a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
37728a2ce0bcSAlberto Garcia     .mutable_opts       = mutable_opts,
3773c1bb86cdSEric Blake 
3774c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3775c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
377633d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3777c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3778c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3779c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3780042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3781c1bb86cdSEric Blake 
3782061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3783c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3784c1bb86cdSEric Blake     .has_variable_length = true,
3785c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3786c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3787c1bb86cdSEric Blake 
3788c1bb86cdSEric Blake     /* removable device support */
3789c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3790c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3791c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3792c1bb86cdSEric Blake };
3793c1bb86cdSEric Blake #endif /* __FreeBSD__ */
3794c1bb86cdSEric Blake 
3795c1bb86cdSEric Blake static void bdrv_file_init(void)
3796c1bb86cdSEric Blake {
3797c1bb86cdSEric Blake     /*
3798c1bb86cdSEric Blake      * Register all the drivers.  Note that order is important, the driver
3799c1bb86cdSEric Blake      * registered last will get probed first.
3800c1bb86cdSEric Blake      */
3801c1bb86cdSEric Blake     bdrv_register(&bdrv_file);
3802c1bb86cdSEric Blake     bdrv_register(&bdrv_host_device);
3803c1bb86cdSEric Blake #ifdef __linux__
3804c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3805c1bb86cdSEric Blake #endif
3806c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3807c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3808c1bb86cdSEric Blake #endif
3809c1bb86cdSEric Blake }
3810c1bb86cdSEric Blake 
3811c1bb86cdSEric Blake block_init(bdrv_file_init);
3812