xref: /qemu/block/file-posix.c (revision cb8d0851)
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"
33ffa244c8SKevin Wolf #include "qemu/units.h"
34c1bb86cdSEric Blake #include "trace.h"
35c1bb86cdSEric Blake #include "block/thread-pool.h"
36c1bb86cdSEric Blake #include "qemu/iov.h"
37c1bb86cdSEric Blake #include "block/raw-aio.h"
38452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
39c1bb86cdSEric Blake #include "qapi/qmp/qstring.h"
40c1bb86cdSEric Blake 
417c9e5276SPaolo Bonzini #include "scsi/pr-manager.h"
427c9e5276SPaolo Bonzini #include "scsi/constants.h"
437c9e5276SPaolo Bonzini 
44c1bb86cdSEric Blake #if defined(__APPLE__) && (__MACH__)
45c1bb86cdSEric Blake #include <paths.h>
46c1bb86cdSEric Blake #include <sys/param.h>
47c1bb86cdSEric Blake #include <IOKit/IOKitLib.h>
48c1bb86cdSEric Blake #include <IOKit/IOBSD.h>
49c1bb86cdSEric Blake #include <IOKit/storage/IOMediaBSDClient.h>
50c1bb86cdSEric Blake #include <IOKit/storage/IOMedia.h>
51c1bb86cdSEric Blake #include <IOKit/storage/IOCDMedia.h>
52c1bb86cdSEric Blake //#include <IOKit/storage/IOCDTypes.h>
53c1bb86cdSEric Blake #include <IOKit/storage/IODVDMedia.h>
54c1bb86cdSEric Blake #include <CoreFoundation/CoreFoundation.h>
55c1bb86cdSEric Blake #endif
56c1bb86cdSEric Blake 
57c1bb86cdSEric Blake #ifdef __sun__
58c1bb86cdSEric Blake #define _POSIX_PTHREAD_SEMANTICS 1
59c1bb86cdSEric Blake #include <sys/dkio.h>
60c1bb86cdSEric Blake #endif
61c1bb86cdSEric Blake #ifdef __linux__
62c1bb86cdSEric Blake #include <sys/ioctl.h>
63c1bb86cdSEric Blake #include <sys/param.h>
641efad060SFam Zheng #include <sys/syscall.h>
655edc8557SKevin Wolf #include <sys/vfs.h>
66c1bb86cdSEric Blake #include <linux/cdrom.h>
67c1bb86cdSEric Blake #include <linux/fd.h>
68c1bb86cdSEric Blake #include <linux/fs.h>
69c1bb86cdSEric Blake #include <linux/hdreg.h>
705edc8557SKevin Wolf #include <linux/magic.h>
71c1bb86cdSEric Blake #include <scsi/sg.h>
72c1bb86cdSEric Blake #ifdef __s390__
73c1bb86cdSEric Blake #include <asm/dasd.h>
74c1bb86cdSEric Blake #endif
75c1bb86cdSEric Blake #ifndef FS_NOCOW_FL
76c1bb86cdSEric Blake #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
77c1bb86cdSEric Blake #endif
78c1bb86cdSEric Blake #endif
79c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
80c1bb86cdSEric Blake #include <linux/falloc.h>
81c1bb86cdSEric Blake #endif
82c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
83c1bb86cdSEric Blake #include <sys/disk.h>
84c1bb86cdSEric Blake #include <sys/cdio.h>
85c1bb86cdSEric Blake #endif
86c1bb86cdSEric Blake 
87c1bb86cdSEric Blake #ifdef __OpenBSD__
88c1bb86cdSEric Blake #include <sys/ioctl.h>
89c1bb86cdSEric Blake #include <sys/disklabel.h>
90c1bb86cdSEric Blake #include <sys/dkio.h>
91c1bb86cdSEric Blake #endif
92c1bb86cdSEric Blake 
93c1bb86cdSEric Blake #ifdef __NetBSD__
94c1bb86cdSEric Blake #include <sys/ioctl.h>
95c1bb86cdSEric Blake #include <sys/disklabel.h>
96c1bb86cdSEric Blake #include <sys/dkio.h>
97c1bb86cdSEric Blake #include <sys/disk.h>
98c1bb86cdSEric Blake #endif
99c1bb86cdSEric Blake 
100c1bb86cdSEric Blake #ifdef __DragonFly__
101c1bb86cdSEric Blake #include <sys/ioctl.h>
102c1bb86cdSEric Blake #include <sys/diskslice.h>
103c1bb86cdSEric Blake #endif
104c1bb86cdSEric Blake 
105c1bb86cdSEric Blake #ifdef CONFIG_XFS
106c1bb86cdSEric Blake #include <xfs/xfs.h>
107c1bb86cdSEric Blake #endif
108c1bb86cdSEric Blake 
1094f7d28d7SLaurent Vivier #include "trace.h"
110c1bb86cdSEric Blake 
111c1bb86cdSEric Blake /* OS X does not have O_DSYNC */
112c1bb86cdSEric Blake #ifndef O_DSYNC
113c1bb86cdSEric Blake #ifdef O_SYNC
114c1bb86cdSEric Blake #define O_DSYNC O_SYNC
115c1bb86cdSEric Blake #elif defined(O_FSYNC)
116c1bb86cdSEric Blake #define O_DSYNC O_FSYNC
117c1bb86cdSEric Blake #endif
118c1bb86cdSEric Blake #endif
119c1bb86cdSEric Blake 
120c1bb86cdSEric Blake /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
121c1bb86cdSEric Blake #ifndef O_DIRECT
122c1bb86cdSEric Blake #define O_DIRECT O_DSYNC
123c1bb86cdSEric Blake #endif
124c1bb86cdSEric Blake 
125c1bb86cdSEric Blake #define FTYPE_FILE   0
126c1bb86cdSEric Blake #define FTYPE_CD     1
127c1bb86cdSEric Blake 
128c1bb86cdSEric Blake #define MAX_BLOCKSIZE	4096
129c1bb86cdSEric Blake 
130244a5668SFam Zheng /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
131244a5668SFam Zheng  * leaving a few more bytes for its future use. */
132244a5668SFam Zheng #define RAW_LOCK_PERM_BASE             100
133244a5668SFam Zheng #define RAW_LOCK_SHARED_BASE           200
134244a5668SFam Zheng 
135c1bb86cdSEric Blake typedef struct BDRVRawState {
136c1bb86cdSEric Blake     int fd;
137244a5668SFam Zheng     bool use_lock;
138c1bb86cdSEric Blake     int type;
139c1bb86cdSEric Blake     int open_flags;
140c1bb86cdSEric Blake     size_t buf_align;
141c1bb86cdSEric Blake 
142244a5668SFam Zheng     /* The current permissions. */
143244a5668SFam Zheng     uint64_t perm;
144244a5668SFam Zheng     uint64_t shared_perm;
145244a5668SFam Zheng 
1462996ffadSFam Zheng     /* The perms bits whose corresponding bytes are already locked in
147f2e3af29SFam Zheng      * s->fd. */
1482996ffadSFam Zheng     uint64_t locked_perm;
1492996ffadSFam Zheng     uint64_t locked_shared_perm;
1502996ffadSFam Zheng 
1516ceabe6fSKevin Wolf     int perm_change_fd;
152094e3639SMax Reitz     int perm_change_flags;
153e0c9cf3aSKevin Wolf     BDRVReopenState *reopen_state;
154e0c9cf3aSKevin Wolf 
155c1bb86cdSEric Blake #ifdef CONFIG_XFS
156c1bb86cdSEric Blake     bool is_xfs:1;
157c1bb86cdSEric Blake #endif
158c1bb86cdSEric Blake     bool has_discard:1;
159c1bb86cdSEric Blake     bool has_write_zeroes:1;
160c1bb86cdSEric Blake     bool discard_zeroes:1;
161c1bb86cdSEric Blake     bool use_linux_aio:1;
162c6447510SAarushi Mehta     bool use_linux_io_uring:1;
163e5bcf967SKevin Wolf     bool page_cache_inconsistent:1;
164c1bb86cdSEric Blake     bool has_fallocate;
165c1bb86cdSEric Blake     bool needs_alignment;
166f357fcd8SStefan Hajnoczi     bool drop_cache;
16731be8a2aSStefan Hajnoczi     bool check_cache_dropped;
1681c450366SAnton Nefedov     struct {
1691c450366SAnton Nefedov         uint64_t discard_nb_ok;
1701c450366SAnton Nefedov         uint64_t discard_nb_failed;
1711c450366SAnton Nefedov         uint64_t discard_bytes_ok;
1721c450366SAnton Nefedov     } stats;
1737c9e5276SPaolo Bonzini 
1747c9e5276SPaolo Bonzini     PRManager *pr_mgr;
175c1bb86cdSEric Blake } BDRVRawState;
176c1bb86cdSEric Blake 
177c1bb86cdSEric Blake typedef struct BDRVRawReopenState {
178c1bb86cdSEric Blake     int fd;
179c1bb86cdSEric Blake     int open_flags;
180f357fcd8SStefan Hajnoczi     bool drop_cache;
18131be8a2aSStefan Hajnoczi     bool check_cache_dropped;
182c1bb86cdSEric Blake } BDRVRawReopenState;
183c1bb86cdSEric Blake 
184c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs);
185c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs);
186c1bb86cdSEric Blake 
187c1bb86cdSEric Blake typedef struct RawPosixAIOData {
188c1bb86cdSEric Blake     BlockDriverState *bs;
189c1bb86cdSEric Blake     int aio_type;
190d57c44d0SKevin Wolf     int aio_fildes;
191d57c44d0SKevin Wolf 
192d57c44d0SKevin Wolf     off_t aio_offset;
193d57c44d0SKevin Wolf     uint64_t aio_nbytes;
194d57c44d0SKevin Wolf 
19593f4e2ffSKevin Wolf     union {
19693f4e2ffSKevin Wolf         struct {
197d57c44d0SKevin Wolf             struct iovec *iov;
198d57c44d0SKevin Wolf             int niov;
199d57c44d0SKevin Wolf         } io;
200d57c44d0SKevin Wolf         struct {
201d57c44d0SKevin Wolf             uint64_t cmd;
202d57c44d0SKevin Wolf             void *buf;
203d57c44d0SKevin Wolf         } ioctl;
204d57c44d0SKevin Wolf         struct {
2051efad060SFam Zheng             int aio_fd2;
2061efad060SFam Zheng             off_t aio_offset2;
207d57c44d0SKevin Wolf         } copy_range;
20893f4e2ffSKevin Wolf         struct {
20993f4e2ffSKevin Wolf             PreallocMode prealloc;
21093f4e2ffSKevin Wolf             Error **errp;
211d57c44d0SKevin Wolf         } truncate;
21293f4e2ffSKevin Wolf     };
213c1bb86cdSEric Blake } RawPosixAIOData;
214c1bb86cdSEric Blake 
215c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
216c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs);
217c1bb86cdSEric Blake #endif
218c1bb86cdSEric Blake 
219c1bb86cdSEric Blake #if defined(__NetBSD__)
220db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
221c1bb86cdSEric Blake {
222c1bb86cdSEric Blake     static char namebuf[PATH_MAX];
223c1bb86cdSEric Blake     const char *dp, *fname;
224c1bb86cdSEric Blake     struct stat sb;
225c1bb86cdSEric Blake 
226c1bb86cdSEric Blake     fname = *filename;
227c1bb86cdSEric Blake     dp = strrchr(fname, '/');
228c1bb86cdSEric Blake     if (lstat(fname, &sb) < 0) {
229f6fc1e30SPaolo Bonzini         error_setg_file_open(errp, errno, fname);
230c1bb86cdSEric Blake         return -errno;
231c1bb86cdSEric Blake     }
232c1bb86cdSEric Blake 
233c1bb86cdSEric Blake     if (!S_ISBLK(sb.st_mode)) {
234c1bb86cdSEric Blake         return 0;
235c1bb86cdSEric Blake     }
236c1bb86cdSEric Blake 
237c1bb86cdSEric Blake     if (dp == NULL) {
238c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "r%s", fname);
239c1bb86cdSEric Blake     } else {
240c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
241c1bb86cdSEric Blake             (int)(dp - fname), fname, dp + 1);
242c1bb86cdSEric Blake     }
243c1bb86cdSEric Blake     *filename = namebuf;
244db0754dfSFam Zheng     warn_report("%s is a block device, using %s", fname, *filename);
245c1bb86cdSEric Blake 
246c1bb86cdSEric Blake     return 0;
247c1bb86cdSEric Blake }
248c1bb86cdSEric Blake #else
249db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
250c1bb86cdSEric Blake {
251c1bb86cdSEric Blake     return 0;
252c1bb86cdSEric Blake }
253c1bb86cdSEric Blake #endif
254c1bb86cdSEric Blake 
255c1bb86cdSEric Blake /*
256c1bb86cdSEric Blake  * Get logical block size via ioctl. On success store it in @sector_size_p.
257c1bb86cdSEric Blake  */
258c1bb86cdSEric Blake static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
259c1bb86cdSEric Blake {
260c1bb86cdSEric Blake     unsigned int sector_size;
261c1bb86cdSEric Blake     bool success = false;
262700f9ce0SPeter Maydell     int i;
263c1bb86cdSEric Blake 
264c1bb86cdSEric Blake     errno = ENOTSUP;
265700f9ce0SPeter Maydell     static const unsigned long ioctl_list[] = {
266c1bb86cdSEric Blake #ifdef BLKSSZGET
267700f9ce0SPeter Maydell         BLKSSZGET,
268c1bb86cdSEric Blake #endif
269c1bb86cdSEric Blake #ifdef DKIOCGETBLOCKSIZE
270700f9ce0SPeter Maydell         DKIOCGETBLOCKSIZE,
271c1bb86cdSEric Blake #endif
272c1bb86cdSEric Blake #ifdef DIOCGSECTORSIZE
273700f9ce0SPeter Maydell         DIOCGSECTORSIZE,
274700f9ce0SPeter Maydell #endif
275700f9ce0SPeter Maydell     };
276700f9ce0SPeter Maydell 
277700f9ce0SPeter Maydell     /* Try a few ioctls to get the right size */
278700f9ce0SPeter Maydell     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
279700f9ce0SPeter Maydell         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
280c1bb86cdSEric Blake             *sector_size_p = sector_size;
281c1bb86cdSEric Blake             success = true;
282c1bb86cdSEric Blake         }
283700f9ce0SPeter Maydell     }
284c1bb86cdSEric Blake 
285c1bb86cdSEric Blake     return success ? 0 : -errno;
286c1bb86cdSEric Blake }
287c1bb86cdSEric Blake 
288c1bb86cdSEric Blake /**
289c1bb86cdSEric Blake  * Get physical block size of @fd.
290c1bb86cdSEric Blake  * On success, store it in @blk_size and return 0.
291c1bb86cdSEric Blake  * On failure, return -errno.
292c1bb86cdSEric Blake  */
293c1bb86cdSEric Blake static int probe_physical_blocksize(int fd, unsigned int *blk_size)
294c1bb86cdSEric Blake {
295c1bb86cdSEric Blake #ifdef BLKPBSZGET
296c1bb86cdSEric Blake     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
297c1bb86cdSEric Blake         return -errno;
298c1bb86cdSEric Blake     }
299c1bb86cdSEric Blake     return 0;
300c1bb86cdSEric Blake #else
301c1bb86cdSEric Blake     return -ENOTSUP;
302c1bb86cdSEric Blake #endif
303c1bb86cdSEric Blake }
304c1bb86cdSEric Blake 
3055edc8557SKevin Wolf /*
3065edc8557SKevin Wolf  * Returns true if no alignment restrictions are necessary even for files
3075edc8557SKevin Wolf  * opened with O_DIRECT.
3085edc8557SKevin Wolf  *
3095edc8557SKevin Wolf  * raw_probe_alignment() probes the required alignment and assume that 1 means
3105edc8557SKevin Wolf  * the probing failed, so it falls back to a safe default of 4k. This can be
3115edc8557SKevin Wolf  * avoided if we know that byte alignment is okay for the file.
3125edc8557SKevin Wolf  */
3135edc8557SKevin Wolf static bool dio_byte_aligned(int fd)
3145edc8557SKevin Wolf {
3155edc8557SKevin Wolf #ifdef __linux__
3165edc8557SKevin Wolf     struct statfs buf;
3175edc8557SKevin Wolf     int ret;
3185edc8557SKevin Wolf 
3195edc8557SKevin Wolf     ret = fstatfs(fd, &buf);
3205edc8557SKevin Wolf     if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
3215edc8557SKevin Wolf         return true;
3225edc8557SKevin Wolf     }
3235edc8557SKevin Wolf #endif
3245edc8557SKevin Wolf     return false;
3255edc8557SKevin Wolf }
3265edc8557SKevin Wolf 
327c1bb86cdSEric Blake /* Check if read is allowed with given memory buffer and length.
328c1bb86cdSEric Blake  *
329c1bb86cdSEric Blake  * This function is used to check O_DIRECT memory buffer and request alignment.
330c1bb86cdSEric Blake  */
331c1bb86cdSEric Blake static bool raw_is_io_aligned(int fd, void *buf, size_t len)
332c1bb86cdSEric Blake {
333c1bb86cdSEric Blake     ssize_t ret = pread(fd, buf, len, 0);
334c1bb86cdSEric Blake 
335c1bb86cdSEric Blake     if (ret >= 0) {
336c1bb86cdSEric Blake         return true;
337c1bb86cdSEric Blake     }
338c1bb86cdSEric Blake 
339c1bb86cdSEric Blake #ifdef __linux__
340c1bb86cdSEric Blake     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
341c1bb86cdSEric Blake      * other errors (e.g. real I/O error), which could happen on a failed
342c1bb86cdSEric Blake      * drive, since we only care about probing alignment.
343c1bb86cdSEric Blake      */
344c1bb86cdSEric Blake     if (errno != EINVAL) {
345c1bb86cdSEric Blake         return true;
346c1bb86cdSEric Blake     }
347c1bb86cdSEric Blake #endif
348c1bb86cdSEric Blake 
349c1bb86cdSEric Blake     return false;
350c1bb86cdSEric Blake }
351c1bb86cdSEric Blake 
352c1bb86cdSEric Blake static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
353c1bb86cdSEric Blake {
354c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
355c1bb86cdSEric Blake     char *buf;
356038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
357a6b257a0SNir Soffer     size_t alignments[] = {1, 512, 1024, 2048, 4096};
358c1bb86cdSEric Blake 
359c1bb86cdSEric Blake     /* For SCSI generic devices the alignment is not really used.
360c1bb86cdSEric Blake        With buffered I/O, we don't have any restrictions. */
361c1bb86cdSEric Blake     if (bdrv_is_sg(bs) || !s->needs_alignment) {
362c1bb86cdSEric Blake         bs->bl.request_alignment = 1;
363c1bb86cdSEric Blake         s->buf_align = 1;
364c1bb86cdSEric Blake         return;
365c1bb86cdSEric Blake     }
366c1bb86cdSEric Blake 
367c1bb86cdSEric Blake     bs->bl.request_alignment = 0;
368c1bb86cdSEric Blake     s->buf_align = 0;
369c1bb86cdSEric Blake     /* Let's try to use the logical blocksize for the alignment. */
370c1bb86cdSEric Blake     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
371c1bb86cdSEric Blake         bs->bl.request_alignment = 0;
372c1bb86cdSEric Blake     }
373c1bb86cdSEric Blake #ifdef CONFIG_XFS
374c1bb86cdSEric Blake     if (s->is_xfs) {
375c1bb86cdSEric Blake         struct dioattr da;
376c1bb86cdSEric Blake         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
377c1bb86cdSEric Blake             bs->bl.request_alignment = da.d_miniosz;
378c1bb86cdSEric Blake             /* The kernel returns wrong information for d_mem */
379c1bb86cdSEric Blake             /* s->buf_align = da.d_mem; */
380c1bb86cdSEric Blake         }
381c1bb86cdSEric Blake     }
382c1bb86cdSEric Blake #endif
383c1bb86cdSEric Blake 
384a6b257a0SNir Soffer     /*
385a6b257a0SNir Soffer      * If we could not get the sizes so far, we can only guess them. First try
386a6b257a0SNir Soffer      * to detect request alignment, since it is more likely to succeed. Then
387a6b257a0SNir Soffer      * try to detect buf_align, which cannot be detected in some cases (e.g.
388a6b257a0SNir Soffer      * Gluster). If buf_align cannot be detected, we fallback to the value of
389a6b257a0SNir Soffer      * request_alignment.
390a6b257a0SNir Soffer      */
391a6b257a0SNir Soffer 
392a6b257a0SNir Soffer     if (!bs->bl.request_alignment) {
393a6b257a0SNir Soffer         int i;
394c1bb86cdSEric Blake         size_t align;
395a6b257a0SNir Soffer         buf = qemu_memalign(max_align, max_align);
396a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
397a6b257a0SNir Soffer             align = alignments[i];
398a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf, align)) {
399a6b257a0SNir Soffer                 /* Fallback to safe value. */
400a6b257a0SNir Soffer                 bs->bl.request_alignment = (align != 1) ? align : max_align;
401c1bb86cdSEric Blake                 break;
402c1bb86cdSEric Blake             }
403c1bb86cdSEric Blake         }
404c1bb86cdSEric Blake         qemu_vfree(buf);
405c1bb86cdSEric Blake     }
406c1bb86cdSEric Blake 
407a6b257a0SNir Soffer     if (!s->buf_align) {
408a6b257a0SNir Soffer         int i;
409c1bb86cdSEric Blake         size_t align;
410a6b257a0SNir Soffer         buf = qemu_memalign(max_align, 2 * max_align);
411a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
412a6b257a0SNir Soffer             align = alignments[i];
413a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf + align, max_align)) {
414236094c7SStefan Hajnoczi                 /* Fallback to request_alignment. */
415a6b257a0SNir Soffer                 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
416c1bb86cdSEric Blake                 break;
417c1bb86cdSEric Blake             }
418c1bb86cdSEric Blake         }
419c1bb86cdSEric Blake         qemu_vfree(buf);
420c1bb86cdSEric Blake     }
421c1bb86cdSEric Blake 
422c1bb86cdSEric Blake     if (!s->buf_align || !bs->bl.request_alignment) {
423c1bb86cdSEric Blake         error_setg(errp, "Could not find working O_DIRECT alignment");
424c1bb86cdSEric Blake         error_append_hint(errp, "Try cache.direct=off\n");
425c1bb86cdSEric Blake     }
426c1bb86cdSEric Blake }
427c1bb86cdSEric Blake 
428bca5283bSKevin Wolf static int check_hdev_writable(int fd)
42920eaf1bfSKevin Wolf {
43020eaf1bfSKevin Wolf #if defined(BLKROGET)
43120eaf1bfSKevin Wolf     /* Linux block devices can be configured "read-only" using blockdev(8).
43220eaf1bfSKevin Wolf      * This is independent of device node permissions and therefore open(2)
43320eaf1bfSKevin Wolf      * with O_RDWR succeeds.  Actual writes fail with EPERM.
43420eaf1bfSKevin Wolf      *
43520eaf1bfSKevin Wolf      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
43620eaf1bfSKevin Wolf      * check for read-only block devices so that Linux block devices behave
43720eaf1bfSKevin Wolf      * properly.
43820eaf1bfSKevin Wolf      */
43920eaf1bfSKevin Wolf     struct stat st;
44020eaf1bfSKevin Wolf     int readonly = 0;
44120eaf1bfSKevin Wolf 
442bca5283bSKevin Wolf     if (fstat(fd, &st)) {
44320eaf1bfSKevin Wolf         return -errno;
44420eaf1bfSKevin Wolf     }
44520eaf1bfSKevin Wolf 
44620eaf1bfSKevin Wolf     if (!S_ISBLK(st.st_mode)) {
44720eaf1bfSKevin Wolf         return 0;
44820eaf1bfSKevin Wolf     }
44920eaf1bfSKevin Wolf 
450bca5283bSKevin Wolf     if (ioctl(fd, BLKROGET, &readonly) < 0) {
45120eaf1bfSKevin Wolf         return -errno;
45220eaf1bfSKevin Wolf     }
45320eaf1bfSKevin Wolf 
45420eaf1bfSKevin Wolf     if (readonly) {
45520eaf1bfSKevin Wolf         return -EACCES;
45620eaf1bfSKevin Wolf     }
45720eaf1bfSKevin Wolf #endif /* defined(BLKROGET) */
45820eaf1bfSKevin Wolf     return 0;
45920eaf1bfSKevin Wolf }
46020eaf1bfSKevin Wolf 
46123dece19SKevin Wolf static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
462c1bb86cdSEric Blake {
46323dece19SKevin Wolf     bool read_write = false;
464c1bb86cdSEric Blake     assert(open_flags != NULL);
465c1bb86cdSEric Blake 
466c1bb86cdSEric Blake     *open_flags |= O_BINARY;
467c1bb86cdSEric Blake     *open_flags &= ~O_ACCMODE;
46823dece19SKevin Wolf 
46923dece19SKevin Wolf     if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
47023dece19SKevin Wolf         read_write = has_writers;
47123dece19SKevin Wolf     } else if (bdrv_flags & BDRV_O_RDWR) {
47223dece19SKevin Wolf         read_write = true;
47323dece19SKevin Wolf     }
47423dece19SKevin Wolf 
47523dece19SKevin Wolf     if (read_write) {
476c1bb86cdSEric Blake         *open_flags |= O_RDWR;
477c1bb86cdSEric Blake     } else {
478c1bb86cdSEric Blake         *open_flags |= O_RDONLY;
479c1bb86cdSEric Blake     }
480c1bb86cdSEric Blake 
481c1bb86cdSEric Blake     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
482c1bb86cdSEric Blake      * and O_DIRECT for no caching. */
483c1bb86cdSEric Blake     if ((bdrv_flags & BDRV_O_NOCACHE)) {
484c1bb86cdSEric Blake         *open_flags |= O_DIRECT;
485c1bb86cdSEric Blake     }
486c1bb86cdSEric Blake }
487c1bb86cdSEric Blake 
488c1bb86cdSEric Blake static void raw_parse_filename(const char *filename, QDict *options,
489c1bb86cdSEric Blake                                Error **errp)
490c1bb86cdSEric Blake {
49103c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "file:", options);
492c1bb86cdSEric Blake }
493c1bb86cdSEric Blake 
494c1bb86cdSEric Blake static QemuOptsList raw_runtime_opts = {
495c1bb86cdSEric Blake     .name = "raw",
496c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
497c1bb86cdSEric Blake     .desc = {
498c1bb86cdSEric Blake         {
499c1bb86cdSEric Blake             .name = "filename",
500c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
501c1bb86cdSEric Blake             .help = "File name of the image",
502c1bb86cdSEric Blake         },
503c1bb86cdSEric Blake         {
504c1bb86cdSEric Blake             .name = "aio",
505c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
506c6447510SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
507c1bb86cdSEric Blake         },
50816b48d5dSFam Zheng         {
50916b48d5dSFam Zheng             .name = "locking",
51016b48d5dSFam Zheng             .type = QEMU_OPT_STRING,
51116b48d5dSFam Zheng             .help = "file locking mode (on/off/auto, default: auto)",
51216b48d5dSFam Zheng         },
5137c9e5276SPaolo Bonzini         {
5147c9e5276SPaolo Bonzini             .name = "pr-manager",
5157c9e5276SPaolo Bonzini             .type = QEMU_OPT_STRING,
5167c9e5276SPaolo Bonzini             .help = "id of persistent reservation manager object (default: none)",
5177c9e5276SPaolo Bonzini         },
518f357fcd8SStefan Hajnoczi #if defined(__linux__)
519f357fcd8SStefan Hajnoczi         {
520f357fcd8SStefan Hajnoczi             .name = "drop-cache",
521f357fcd8SStefan Hajnoczi             .type = QEMU_OPT_BOOL,
522f357fcd8SStefan Hajnoczi             .help = "invalidate page cache during live migration (default: on)",
523f357fcd8SStefan Hajnoczi         },
524f357fcd8SStefan Hajnoczi #endif
52531be8a2aSStefan Hajnoczi         {
52631be8a2aSStefan Hajnoczi             .name = "x-check-cache-dropped",
52731be8a2aSStefan Hajnoczi             .type = QEMU_OPT_BOOL,
52831be8a2aSStefan Hajnoczi             .help = "check that page cache was dropped on live migration (default: off)"
52931be8a2aSStefan Hajnoczi         },
530c1bb86cdSEric Blake         { /* end of list */ }
531c1bb86cdSEric Blake     },
532c1bb86cdSEric Blake };
533c1bb86cdSEric Blake 
5348a2ce0bcSAlberto Garcia static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
5358a2ce0bcSAlberto Garcia 
536c1bb86cdSEric Blake static int raw_open_common(BlockDriverState *bs, QDict *options,
537230ff739SJohn Snow                            int bdrv_flags, int open_flags,
538230ff739SJohn Snow                            bool device, Error **errp)
539c1bb86cdSEric Blake {
540c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
541c1bb86cdSEric Blake     QemuOpts *opts;
542c1bb86cdSEric Blake     Error *local_err = NULL;
543c1bb86cdSEric Blake     const char *filename = NULL;
5447c9e5276SPaolo Bonzini     const char *str;
545c1bb86cdSEric Blake     BlockdevAioOptions aio, aio_default;
546c1bb86cdSEric Blake     int fd, ret;
547c1bb86cdSEric Blake     struct stat st;
548244a5668SFam Zheng     OnOffAuto locking;
549c1bb86cdSEric Blake 
550c1bb86cdSEric Blake     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
551af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
552c1bb86cdSEric Blake         ret = -EINVAL;
553c1bb86cdSEric Blake         goto fail;
554c1bb86cdSEric Blake     }
555c1bb86cdSEric Blake 
556c1bb86cdSEric Blake     filename = qemu_opt_get(opts, "filename");
557c1bb86cdSEric Blake 
558db0754dfSFam Zheng     ret = raw_normalize_devicepath(&filename, errp);
559c1bb86cdSEric Blake     if (ret != 0) {
560c1bb86cdSEric Blake         goto fail;
561c1bb86cdSEric Blake     }
562c1bb86cdSEric Blake 
563c6447510SAarushi Mehta     if (bdrv_flags & BDRV_O_NATIVE_AIO) {
564c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
565c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
566c6447510SAarushi Mehta     } else if (bdrv_flags & BDRV_O_IO_URING) {
567c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
568c6447510SAarushi Mehta #endif
569c6447510SAarushi Mehta     } else {
570c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
571c6447510SAarushi Mehta     }
572c6447510SAarushi Mehta 
573f7abe0ecSMarc-André Lureau     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
574f7abe0ecSMarc-André Lureau                           qemu_opt_get(opts, "aio"),
57506c60b6cSMarkus Armbruster                           aio_default, &local_err);
576c1bb86cdSEric Blake     if (local_err) {
577c1bb86cdSEric Blake         error_propagate(errp, local_err);
578c1bb86cdSEric Blake         ret = -EINVAL;
579c1bb86cdSEric Blake         goto fail;
580c1bb86cdSEric Blake     }
581c6447510SAarushi Mehta 
582c1bb86cdSEric Blake     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
583c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
584c6447510SAarushi Mehta     s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
585c6447510SAarushi Mehta #endif
586c1bb86cdSEric Blake 
587f7abe0ecSMarc-André Lureau     locking = qapi_enum_parse(&OnOffAuto_lookup,
588f7abe0ecSMarc-André Lureau                               qemu_opt_get(opts, "locking"),
58906c60b6cSMarkus Armbruster                               ON_OFF_AUTO_AUTO, &local_err);
590244a5668SFam Zheng     if (local_err) {
591244a5668SFam Zheng         error_propagate(errp, local_err);
592244a5668SFam Zheng         ret = -EINVAL;
593244a5668SFam Zheng         goto fail;
594244a5668SFam Zheng     }
595244a5668SFam Zheng     switch (locking) {
596244a5668SFam Zheng     case ON_OFF_AUTO_ON:
597244a5668SFam Zheng         s->use_lock = true;
5982b218f5dSFam Zheng         if (!qemu_has_ofd_lock()) {
599db0754dfSFam Zheng             warn_report("File lock requested but OFD locking syscall is "
600db0754dfSFam Zheng                         "unavailable, falling back to POSIX file locks");
601db0754dfSFam Zheng             error_printf("Due to the implementation, locks can be lost "
6022b218f5dSFam Zheng                          "unexpectedly.\n");
6032b218f5dSFam Zheng         }
604244a5668SFam Zheng         break;
605244a5668SFam Zheng     case ON_OFF_AUTO_OFF:
606244a5668SFam Zheng         s->use_lock = false;
607244a5668SFam Zheng         break;
608244a5668SFam Zheng     case ON_OFF_AUTO_AUTO:
6092b218f5dSFam Zheng         s->use_lock = qemu_has_ofd_lock();
610244a5668SFam Zheng         break;
611244a5668SFam Zheng     default:
612244a5668SFam Zheng         abort();
613244a5668SFam Zheng     }
614244a5668SFam Zheng 
6157c9e5276SPaolo Bonzini     str = qemu_opt_get(opts, "pr-manager");
6167c9e5276SPaolo Bonzini     if (str) {
6177c9e5276SPaolo Bonzini         s->pr_mgr = pr_manager_lookup(str, &local_err);
6187c9e5276SPaolo Bonzini         if (local_err) {
6197c9e5276SPaolo Bonzini             error_propagate(errp, local_err);
6207c9e5276SPaolo Bonzini             ret = -EINVAL;
6217c9e5276SPaolo Bonzini             goto fail;
6227c9e5276SPaolo Bonzini         }
6237c9e5276SPaolo Bonzini     }
6247c9e5276SPaolo Bonzini 
625f357fcd8SStefan Hajnoczi     s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
62631be8a2aSStefan Hajnoczi     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
62731be8a2aSStefan Hajnoczi                                                false);
62831be8a2aSStefan Hajnoczi 
629c1bb86cdSEric Blake     s->open_flags = open_flags;
63023dece19SKevin Wolf     raw_parse_flags(bdrv_flags, &s->open_flags, false);
631c1bb86cdSEric Blake 
632c1bb86cdSEric Blake     s->fd = -1;
633b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, s->open_flags, errp);
63464107dc0SKevin Wolf     ret = fd < 0 ? -errno : 0;
63564107dc0SKevin Wolf 
63664107dc0SKevin Wolf     if (ret < 0) {
637c1bb86cdSEric Blake         if (ret == -EROFS) {
638c1bb86cdSEric Blake             ret = -EACCES;
639c1bb86cdSEric Blake         }
640c1bb86cdSEric Blake         goto fail;
641c1bb86cdSEric Blake     }
642c1bb86cdSEric Blake     s->fd = fd;
643c1bb86cdSEric Blake 
644bca5283bSKevin Wolf     /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
645bca5283bSKevin Wolf     if (s->open_flags & O_RDWR) {
646bca5283bSKevin Wolf         ret = check_hdev_writable(s->fd);
647bca5283bSKevin Wolf         if (ret < 0) {
648bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
649bca5283bSKevin Wolf             goto fail;
650bca5283bSKevin Wolf         }
651bca5283bSKevin Wolf     }
652bca5283bSKevin Wolf 
653244a5668SFam Zheng     s->perm = 0;
654244a5668SFam Zheng     s->shared_perm = BLK_PERM_ALL;
655244a5668SFam Zheng 
656c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
657c1bb86cdSEric Blake      /* Currently Linux does AIO only for files opened with O_DIRECT */
658ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
659ed6e2161SNishanth Aravamudan         if (!(s->open_flags & O_DIRECT)) {
660c1bb86cdSEric Blake             error_setg(errp, "aio=native was specified, but it requires "
661c1bb86cdSEric Blake                              "cache.direct=on, which was not specified.");
662c1bb86cdSEric Blake             ret = -EINVAL;
663c1bb86cdSEric Blake             goto fail;
664c1bb86cdSEric Blake         }
665ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
666ed6e2161SNishanth Aravamudan             error_prepend(errp, "Unable to use native AIO: ");
667ed6e2161SNishanth Aravamudan             goto fail;
668ed6e2161SNishanth Aravamudan         }
669ed6e2161SNishanth Aravamudan     }
670c1bb86cdSEric Blake #else
671c1bb86cdSEric Blake     if (s->use_linux_aio) {
672c1bb86cdSEric Blake         error_setg(errp, "aio=native was specified, but is not supported "
673c1bb86cdSEric Blake                          "in this build.");
674c1bb86cdSEric Blake         ret = -EINVAL;
675c1bb86cdSEric Blake         goto fail;
676c1bb86cdSEric Blake     }
677c1bb86cdSEric Blake #endif /* !defined(CONFIG_LINUX_AIO) */
678c1bb86cdSEric Blake 
679c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
680c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
681c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
682c6447510SAarushi Mehta             error_prepend(errp, "Unable to use io_uring: ");
683c6447510SAarushi Mehta             goto fail;
684c6447510SAarushi Mehta         }
685c6447510SAarushi Mehta     }
686c6447510SAarushi Mehta #else
687c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
688c6447510SAarushi Mehta         error_setg(errp, "aio=io_uring was specified, but is not supported "
689c6447510SAarushi Mehta                          "in this build.");
690c6447510SAarushi Mehta         ret = -EINVAL;
691c6447510SAarushi Mehta         goto fail;
692c6447510SAarushi Mehta     }
693c6447510SAarushi Mehta #endif /* !defined(CONFIG_LINUX_IO_URING) */
694c6447510SAarushi Mehta 
695c1bb86cdSEric Blake     s->has_discard = true;
696c1bb86cdSEric Blake     s->has_write_zeroes = true;
6975edc8557SKevin Wolf     if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
698c1bb86cdSEric Blake         s->needs_alignment = true;
699c1bb86cdSEric Blake     }
700c1bb86cdSEric Blake 
701c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
702c1bb86cdSEric Blake         ret = -errno;
703c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not stat file");
704c1bb86cdSEric Blake         goto fail;
705c1bb86cdSEric Blake     }
706230ff739SJohn Snow 
707230ff739SJohn Snow     if (!device) {
708230ff739SJohn Snow         if (S_ISBLK(st.st_mode)) {
709230ff739SJohn Snow             warn_report("Opening a block device as a file using the '%s' "
710230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
711230ff739SJohn Snow         } else if (S_ISCHR(st.st_mode)) {
712230ff739SJohn Snow             warn_report("Opening a character device as a file using the '%s' "
713230ff739SJohn Snow                         "driver is deprecated", bs->drv->format_name);
714230ff739SJohn Snow         } else if (!S_ISREG(st.st_mode)) {
715230ff739SJohn Snow             error_setg(errp, "A regular file was expected by the '%s' driver, "
716230ff739SJohn Snow                        "but something else was given", bs->drv->format_name);
717230ff739SJohn Snow             ret = -EINVAL;
718230ff739SJohn Snow             goto fail;
719230ff739SJohn Snow         } else {
720c1bb86cdSEric Blake             s->discard_zeroes = true;
721c1bb86cdSEric Blake             s->has_fallocate = true;
722c1bb86cdSEric Blake         }
723230ff739SJohn Snow     } else {
724230ff739SJohn Snow         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
725230ff739SJohn Snow             error_setg(errp, "'%s' driver expects either "
726230ff739SJohn Snow                        "a character or block device", bs->drv->format_name);
727230ff739SJohn Snow             ret = -EINVAL;
728230ff739SJohn Snow             goto fail;
729230ff739SJohn Snow         }
730230ff739SJohn Snow     }
731230ff739SJohn Snow 
732c1bb86cdSEric Blake     if (S_ISBLK(st.st_mode)) {
733c1bb86cdSEric Blake #ifdef BLKDISCARDZEROES
734c1bb86cdSEric Blake         unsigned int arg;
735c1bb86cdSEric Blake         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
736c1bb86cdSEric Blake             s->discard_zeroes = true;
737c1bb86cdSEric Blake         }
738c1bb86cdSEric Blake #endif
739c1bb86cdSEric Blake #ifdef __linux__
740c1bb86cdSEric Blake         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
741c1bb86cdSEric Blake          * not rely on the contents of discarded blocks unless using O_DIRECT.
742c1bb86cdSEric Blake          * Same for BLKZEROOUT.
743c1bb86cdSEric Blake          */
744c1bb86cdSEric Blake         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
745c1bb86cdSEric Blake             s->discard_zeroes = false;
746c1bb86cdSEric Blake             s->has_write_zeroes = false;
747c1bb86cdSEric Blake         }
748c1bb86cdSEric Blake #endif
749c1bb86cdSEric Blake     }
750c1bb86cdSEric Blake #ifdef __FreeBSD__
751c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode)) {
752c1bb86cdSEric Blake         /*
753c1bb86cdSEric Blake          * The file is a char device (disk), which on FreeBSD isn't behind
754c1bb86cdSEric Blake          * a pager, so force all requests to be aligned. This is needed
755c1bb86cdSEric Blake          * so QEMU makes sure all IO operations on the device are aligned
756c1bb86cdSEric Blake          * to sector size, or else FreeBSD will reject them with EINVAL.
757c1bb86cdSEric Blake          */
758c1bb86cdSEric Blake         s->needs_alignment = true;
759c1bb86cdSEric Blake     }
760c1bb86cdSEric Blake #endif
761c1bb86cdSEric Blake 
762c1bb86cdSEric Blake #ifdef CONFIG_XFS
763c1bb86cdSEric Blake     if (platform_test_xfs_fd(s->fd)) {
764c1bb86cdSEric Blake         s->is_xfs = true;
765c1bb86cdSEric Blake     }
766c1bb86cdSEric Blake #endif
767c1bb86cdSEric Blake 
768738301e1SKevin Wolf     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
7692f0c6e7aSKevin Wolf     if (S_ISREG(st.st_mode)) {
7702f0c6e7aSKevin Wolf         /* When extending regular files, we get zeros from the OS */
7712f0c6e7aSKevin Wolf         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
7722f0c6e7aSKevin Wolf     }
773c1bb86cdSEric Blake     ret = 0;
774c1bb86cdSEric Blake fail:
775a8c5cf27SKevin Wolf     if (ret < 0 && s->fd != -1) {
776a8c5cf27SKevin Wolf         qemu_close(s->fd);
777a8c5cf27SKevin Wolf     }
778c1bb86cdSEric Blake     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
779c1bb86cdSEric Blake         unlink(filename);
780c1bb86cdSEric Blake     }
781c1bb86cdSEric Blake     qemu_opts_del(opts);
782c1bb86cdSEric Blake     return ret;
783c1bb86cdSEric Blake }
784c1bb86cdSEric Blake 
785c1bb86cdSEric Blake static int raw_open(BlockDriverState *bs, QDict *options, int flags,
786c1bb86cdSEric Blake                     Error **errp)
787c1bb86cdSEric Blake {
788c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
789c1bb86cdSEric Blake 
790c1bb86cdSEric Blake     s->type = FTYPE_FILE;
791230ff739SJohn Snow     return raw_open_common(bs, options, flags, 0, false, errp);
792c1bb86cdSEric Blake }
793c1bb86cdSEric Blake 
794244a5668SFam Zheng typedef enum {
795244a5668SFam Zheng     RAW_PL_PREPARE,
796244a5668SFam Zheng     RAW_PL_COMMIT,
797244a5668SFam Zheng     RAW_PL_ABORT,
798244a5668SFam Zheng } RawPermLockOp;
799244a5668SFam Zheng 
800244a5668SFam Zheng #define PERM_FOREACH(i) \
801244a5668SFam Zheng     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
802244a5668SFam Zheng 
803244a5668SFam Zheng /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
804244a5668SFam Zheng  * file; if @unlock == true, also unlock the unneeded bytes.
805244a5668SFam Zheng  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
806244a5668SFam Zheng  */
8072996ffadSFam Zheng static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
808244a5668SFam Zheng                                 uint64_t perm_lock_bits,
809244a5668SFam Zheng                                 uint64_t shared_perm_lock_bits,
810244a5668SFam Zheng                                 bool unlock, Error **errp)
811244a5668SFam Zheng {
812244a5668SFam Zheng     int ret;
813244a5668SFam Zheng     int i;
8142996ffadSFam Zheng     uint64_t locked_perm, locked_shared_perm;
8152996ffadSFam Zheng 
8162996ffadSFam Zheng     if (s) {
8172996ffadSFam Zheng         locked_perm = s->locked_perm;
8182996ffadSFam Zheng         locked_shared_perm = s->locked_shared_perm;
8192996ffadSFam Zheng     } else {
8202996ffadSFam Zheng         /*
8212996ffadSFam Zheng          * We don't have the previous bits, just lock/unlock for each of the
8222996ffadSFam Zheng          * requested bits.
8232996ffadSFam Zheng          */
8242996ffadSFam Zheng         if (unlock) {
8252996ffadSFam Zheng             locked_perm = BLK_PERM_ALL;
8262996ffadSFam Zheng             locked_shared_perm = BLK_PERM_ALL;
8272996ffadSFam Zheng         } else {
8282996ffadSFam Zheng             locked_perm = 0;
8292996ffadSFam Zheng             locked_shared_perm = 0;
8302996ffadSFam Zheng         }
8312996ffadSFam Zheng     }
832244a5668SFam Zheng 
833244a5668SFam Zheng     PERM_FOREACH(i) {
834244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
8352996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8362996ffadSFam Zheng         if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
837d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
838244a5668SFam Zheng             if (ret) {
839244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
840244a5668SFam Zheng                 return ret;
8412996ffadSFam Zheng             } else if (s) {
8422996ffadSFam Zheng                 s->locked_perm |= bit;
843244a5668SFam Zheng             }
8442996ffadSFam Zheng         } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
845d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
846244a5668SFam Zheng             if (ret) {
847244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
848244a5668SFam Zheng                 return ret;
8492996ffadSFam Zheng             } else if (s) {
8502996ffadSFam Zheng                 s->locked_perm &= ~bit;
851244a5668SFam Zheng             }
852244a5668SFam Zheng         }
853244a5668SFam Zheng     }
854244a5668SFam Zheng     PERM_FOREACH(i) {
855244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
8562996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8572996ffadSFam Zheng         if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
858d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
859244a5668SFam Zheng             if (ret) {
860244a5668SFam Zheng                 error_setg(errp, "Failed to lock byte %d", off);
861244a5668SFam Zheng                 return ret;
8622996ffadSFam Zheng             } else if (s) {
8632996ffadSFam Zheng                 s->locked_shared_perm |= bit;
864244a5668SFam Zheng             }
8652996ffadSFam Zheng         } else if (unlock && (locked_shared_perm & bit) &&
8662996ffadSFam Zheng                    !(shared_perm_lock_bits & bit)) {
867d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
868244a5668SFam Zheng             if (ret) {
869244a5668SFam Zheng                 error_setg(errp, "Failed to unlock byte %d", off);
870244a5668SFam Zheng                 return ret;
8712996ffadSFam Zheng             } else if (s) {
8722996ffadSFam Zheng                 s->locked_shared_perm &= ~bit;
873244a5668SFam Zheng             }
874244a5668SFam Zheng         }
875244a5668SFam Zheng     }
876244a5668SFam Zheng     return 0;
877244a5668SFam Zheng }
878244a5668SFam Zheng 
879244a5668SFam Zheng /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
880d0a96155SMax Reitz static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
881244a5668SFam Zheng                                 Error **errp)
882244a5668SFam Zheng {
883244a5668SFam Zheng     int ret;
884244a5668SFam Zheng     int i;
885244a5668SFam Zheng 
886244a5668SFam Zheng     PERM_FOREACH(i) {
887244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
888244a5668SFam Zheng         uint64_t p = 1ULL << i;
889244a5668SFam Zheng         if (perm & p) {
890d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
891244a5668SFam Zheng             if (ret) {
892244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
893244a5668SFam Zheng                 error_setg(errp,
894244a5668SFam Zheng                            "Failed to get \"%s\" lock",
895244a5668SFam Zheng                            perm_name);
896244a5668SFam Zheng                 g_free(perm_name);
897244a5668SFam Zheng                 return ret;
898244a5668SFam Zheng             }
899244a5668SFam Zheng         }
900244a5668SFam Zheng     }
901244a5668SFam Zheng     PERM_FOREACH(i) {
902244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
903244a5668SFam Zheng         uint64_t p = 1ULL << i;
904244a5668SFam Zheng         if (!(shared_perm & p)) {
905d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
906244a5668SFam Zheng             if (ret) {
907244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
908244a5668SFam Zheng                 error_setg(errp,
909244a5668SFam Zheng                            "Failed to get shared \"%s\" lock",
910244a5668SFam Zheng                            perm_name);
911244a5668SFam Zheng                 g_free(perm_name);
912244a5668SFam Zheng                 return ret;
913244a5668SFam Zheng             }
914244a5668SFam Zheng         }
915244a5668SFam Zheng     }
916244a5668SFam Zheng     return 0;
917244a5668SFam Zheng }
918244a5668SFam Zheng 
919244a5668SFam Zheng static int raw_handle_perm_lock(BlockDriverState *bs,
920244a5668SFam Zheng                                 RawPermLockOp op,
921244a5668SFam Zheng                                 uint64_t new_perm, uint64_t new_shared,
922244a5668SFam Zheng                                 Error **errp)
923244a5668SFam Zheng {
924244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
925244a5668SFam Zheng     int ret = 0;
926244a5668SFam Zheng     Error *local_err = NULL;
927244a5668SFam Zheng 
928244a5668SFam Zheng     if (!s->use_lock) {
929244a5668SFam Zheng         return 0;
930244a5668SFam Zheng     }
931244a5668SFam Zheng 
932244a5668SFam Zheng     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
933244a5668SFam Zheng         return 0;
934244a5668SFam Zheng     }
935244a5668SFam Zheng 
936244a5668SFam Zheng     switch (op) {
937244a5668SFam Zheng     case RAW_PL_PREPARE:
938696aaaedSVladimir Sementsov-Ogievskiy         if ((s->perm | new_perm) == s->perm &&
939696aaaedSVladimir Sementsov-Ogievskiy             (s->shared_perm & new_shared) == s->shared_perm)
940696aaaedSVladimir Sementsov-Ogievskiy         {
941696aaaedSVladimir Sementsov-Ogievskiy             /*
942696aaaedSVladimir Sementsov-Ogievskiy              * We are going to unlock bytes, it should not fail. If it fail due
943696aaaedSVladimir Sementsov-Ogievskiy              * to some fs-dependent permission-unrelated reasons (which occurs
944696aaaedSVladimir Sementsov-Ogievskiy              * sometimes on NFS and leads to abort in bdrv_replace_child) we
945696aaaedSVladimir Sementsov-Ogievskiy              * can't prevent such errors by any check here. And we ignore them
946696aaaedSVladimir Sementsov-Ogievskiy              * anyway in ABORT and COMMIT.
947696aaaedSVladimir Sementsov-Ogievskiy              */
948696aaaedSVladimir Sementsov-Ogievskiy             return 0;
949696aaaedSVladimir Sementsov-Ogievskiy         }
950f2e3af29SFam Zheng         ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
951244a5668SFam Zheng                                    ~s->shared_perm | ~new_shared,
952244a5668SFam Zheng                                    false, errp);
953244a5668SFam Zheng         if (!ret) {
954f2e3af29SFam Zheng             ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
955244a5668SFam Zheng             if (!ret) {
956244a5668SFam Zheng                 return 0;
957244a5668SFam Zheng             }
958b857431dSFam Zheng             error_append_hint(errp,
959b857431dSFam Zheng                               "Is another process using the image [%s]?\n",
960b857431dSFam Zheng                               bs->filename);
961244a5668SFam Zheng         }
962244a5668SFam Zheng         /* fall through to unlock bytes. */
963244a5668SFam Zheng     case RAW_PL_ABORT:
964f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
965d0a96155SMax Reitz                              true, &local_err);
966244a5668SFam Zheng         if (local_err) {
967244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
968244a5668SFam Zheng              * fail. Something weird happened, report it.
969244a5668SFam Zheng              */
970db0754dfSFam Zheng             warn_report_err(local_err);
971244a5668SFam Zheng         }
972244a5668SFam Zheng         break;
973244a5668SFam Zheng     case RAW_PL_COMMIT:
974f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
975d0a96155SMax Reitz                              true, &local_err);
976244a5668SFam Zheng         if (local_err) {
977244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
978244a5668SFam Zheng              * fail. Something weird happened, report it.
979244a5668SFam Zheng              */
980db0754dfSFam Zheng             warn_report_err(local_err);
981244a5668SFam Zheng         }
982244a5668SFam Zheng         break;
983244a5668SFam Zheng     }
984244a5668SFam Zheng     return ret;
985244a5668SFam Zheng }
986244a5668SFam Zheng 
9875cec2870SKevin Wolf static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
98823dece19SKevin Wolf                                  int *open_flags, uint64_t perm, bool force_dup,
9896ceabe6fSKevin Wolf                                  Error **errp)
9905cec2870SKevin Wolf {
9915cec2870SKevin Wolf     BDRVRawState *s = bs->opaque;
9925cec2870SKevin Wolf     int fd = -1;
9935cec2870SKevin Wolf     int ret;
99423dece19SKevin Wolf     bool has_writers = perm &
99523dece19SKevin Wolf         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
9965cec2870SKevin Wolf     int fcntl_flags = O_APPEND | O_NONBLOCK;
9975cec2870SKevin Wolf #ifdef O_NOATIME
9985cec2870SKevin Wolf     fcntl_flags |= O_NOATIME;
9995cec2870SKevin Wolf #endif
10005cec2870SKevin Wolf 
10015cec2870SKevin Wolf     *open_flags = 0;
10025cec2870SKevin Wolf     if (s->type == FTYPE_CD) {
10035cec2870SKevin Wolf         *open_flags |= O_NONBLOCK;
10045cec2870SKevin Wolf     }
10055cec2870SKevin Wolf 
100623dece19SKevin Wolf     raw_parse_flags(flags, open_flags, has_writers);
10075cec2870SKevin Wolf 
10085cec2870SKevin Wolf #ifdef O_ASYNC
10095cec2870SKevin Wolf     /* Not all operating systems have O_ASYNC, and those that don't
10105cec2870SKevin Wolf      * will not let us track the state into rs->open_flags (typically
10115cec2870SKevin Wolf      * you achieve the same effect with an ioctl, for example I_SETSIG
10125cec2870SKevin Wolf      * on Solaris). But we do not use O_ASYNC, so that's fine.
10135cec2870SKevin Wolf      */
10145cec2870SKevin Wolf     assert((s->open_flags & O_ASYNC) == 0);
10155cec2870SKevin Wolf #endif
10165cec2870SKevin Wolf 
10176ceabe6fSKevin Wolf     if (!force_dup && *open_flags == s->open_flags) {
10186ceabe6fSKevin Wolf         /* We're lucky, the existing fd is fine */
10196ceabe6fSKevin Wolf         return s->fd;
10206ceabe6fSKevin Wolf     }
10216ceabe6fSKevin Wolf 
10225cec2870SKevin Wolf     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
10235cec2870SKevin Wolf         /* dup the original fd */
10245cec2870SKevin Wolf         fd = qemu_dup(s->fd);
10255cec2870SKevin Wolf         if (fd >= 0) {
10265cec2870SKevin Wolf             ret = fcntl_setfl(fd, *open_flags);
10275cec2870SKevin Wolf             if (ret) {
10285cec2870SKevin Wolf                 qemu_close(fd);
10295cec2870SKevin Wolf                 fd = -1;
10305cec2870SKevin Wolf             }
10315cec2870SKevin Wolf         }
10325cec2870SKevin Wolf     }
10335cec2870SKevin Wolf 
1034b18a24a9SDaniel P. Berrangé     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
10355cec2870SKevin Wolf     if (fd == -1) {
10365cec2870SKevin Wolf         const char *normalized_filename = bs->filename;
10375cec2870SKevin Wolf         ret = raw_normalize_devicepath(&normalized_filename, errp);
10385cec2870SKevin Wolf         if (ret >= 0) {
1039b18a24a9SDaniel P. Berrangé             fd = qemu_open(normalized_filename, *open_flags, errp);
10405cec2870SKevin Wolf             if (fd == -1) {
10415cec2870SKevin Wolf                 return -1;
10425cec2870SKevin Wolf             }
10435cec2870SKevin Wolf         }
10445cec2870SKevin Wolf     }
10455cec2870SKevin Wolf 
1046bca5283bSKevin Wolf     if (fd != -1 && (*open_flags & O_RDWR)) {
1047bca5283bSKevin Wolf         ret = check_hdev_writable(fd);
1048bca5283bSKevin Wolf         if (ret < 0) {
1049bca5283bSKevin Wolf             qemu_close(fd);
1050bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
1051bca5283bSKevin Wolf             return -1;
1052bca5283bSKevin Wolf         }
1053bca5283bSKevin Wolf     }
1054bca5283bSKevin Wolf 
10555cec2870SKevin Wolf     return fd;
10565cec2870SKevin Wolf }
10575cec2870SKevin Wolf 
1058c1bb86cdSEric Blake static int raw_reopen_prepare(BDRVReopenState *state,
1059c1bb86cdSEric Blake                               BlockReopenQueue *queue, Error **errp)
1060c1bb86cdSEric Blake {
1061c1bb86cdSEric Blake     BDRVRawState *s;
1062c1bb86cdSEric Blake     BDRVRawReopenState *rs;
106331be8a2aSStefan Hajnoczi     QemuOpts *opts;
1064a6aeca0cSKevin Wolf     int ret;
1065c1bb86cdSEric Blake     Error *local_err = NULL;
1066c1bb86cdSEric Blake 
1067c1bb86cdSEric Blake     assert(state != NULL);
1068c1bb86cdSEric Blake     assert(state->bs != NULL);
1069c1bb86cdSEric Blake 
1070c1bb86cdSEric Blake     s = state->bs->opaque;
1071c1bb86cdSEric Blake 
1072c1bb86cdSEric Blake     state->opaque = g_new0(BDRVRawReopenState, 1);
1073c1bb86cdSEric Blake     rs = state->opaque;
107431be8a2aSStefan Hajnoczi 
107531be8a2aSStefan Hajnoczi     /* Handle options changes */
107631be8a2aSStefan Hajnoczi     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1077af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
107831be8a2aSStefan Hajnoczi         ret = -EINVAL;
107931be8a2aSStefan Hajnoczi         goto out;
108031be8a2aSStefan Hajnoczi     }
108131be8a2aSStefan Hajnoczi 
1082f357fcd8SStefan Hajnoczi     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
10838d324575SAlberto Garcia     rs->check_cache_dropped =
10848d324575SAlberto Garcia         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
10858d324575SAlberto Garcia 
10868d324575SAlberto Garcia     /* This driver's reopen function doesn't currently allow changing
10878d324575SAlberto Garcia      * other options, so let's put them back in the original QDict and
10888d324575SAlberto Garcia      * bdrv_reopen_prepare() will detect changes and complain. */
10898d324575SAlberto Garcia     qemu_opts_to_qdict(opts, state->options);
1090c1bb86cdSEric Blake 
10915cec2870SKevin Wolf     rs->fd = raw_reconfigure_getfd(state->bs, state->flags, &rs->open_flags,
109223dece19SKevin Wolf                                    state->perm, true, &local_err);
10935cec2870SKevin Wolf     if (local_err) {
10945cec2870SKevin Wolf         error_propagate(errp, local_err);
1095c1bb86cdSEric Blake         ret = -1;
10965cec2870SKevin Wolf         goto out;
1097c1bb86cdSEric Blake     }
1098c1bb86cdSEric Blake 
1099c1bb86cdSEric Blake     /* Fail already reopen_prepare() if we can't get a working O_DIRECT
1100c1bb86cdSEric Blake      * alignment with the new fd. */
1101c1bb86cdSEric Blake     if (rs->fd != -1) {
1102c1bb86cdSEric Blake         raw_probe_alignment(state->bs, rs->fd, &local_err);
1103c1bb86cdSEric Blake         if (local_err) {
1104c1bb86cdSEric Blake             error_propagate(errp, local_err);
1105c1bb86cdSEric Blake             ret = -EINVAL;
1106a6aeca0cSKevin Wolf             goto out_fd;
1107a6aeca0cSKevin Wolf         }
1108c1bb86cdSEric Blake     }
1109c1bb86cdSEric Blake 
1110e0c9cf3aSKevin Wolf     s->reopen_state = state;
1111a6aeca0cSKevin Wolf     ret = 0;
1112a6aeca0cSKevin Wolf out_fd:
1113a6aeca0cSKevin Wolf     if (ret < 0) {
1114a6aeca0cSKevin Wolf         qemu_close(rs->fd);
1115a6aeca0cSKevin Wolf         rs->fd = -1;
1116a6aeca0cSKevin Wolf     }
111731be8a2aSStefan Hajnoczi out:
111831be8a2aSStefan Hajnoczi     qemu_opts_del(opts);
1119c1bb86cdSEric Blake     return ret;
1120c1bb86cdSEric Blake }
1121c1bb86cdSEric Blake 
1122c1bb86cdSEric Blake static void raw_reopen_commit(BDRVReopenState *state)
1123c1bb86cdSEric Blake {
1124c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1125c1bb86cdSEric Blake     BDRVRawState *s = state->bs->opaque;
1126c1bb86cdSEric Blake 
1127f357fcd8SStefan Hajnoczi     s->drop_cache = rs->drop_cache;
112831be8a2aSStefan Hajnoczi     s->check_cache_dropped = rs->check_cache_dropped;
1129c1bb86cdSEric Blake     s->open_flags = rs->open_flags;
1130c1bb86cdSEric Blake 
1131c1bb86cdSEric Blake     qemu_close(s->fd);
1132c1bb86cdSEric Blake     s->fd = rs->fd;
1133c1bb86cdSEric Blake 
1134c1bb86cdSEric Blake     g_free(state->opaque);
1135c1bb86cdSEric Blake     state->opaque = NULL;
1136e0c9cf3aSKevin Wolf 
1137e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1138e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1139c1bb86cdSEric Blake }
1140c1bb86cdSEric Blake 
1141c1bb86cdSEric Blake 
1142c1bb86cdSEric Blake static void raw_reopen_abort(BDRVReopenState *state)
1143c1bb86cdSEric Blake {
1144c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1145e0c9cf3aSKevin Wolf     BDRVRawState *s = state->bs->opaque;
1146c1bb86cdSEric Blake 
1147c1bb86cdSEric Blake      /* nothing to do if NULL, we didn't get far enough */
1148c1bb86cdSEric Blake     if (rs == NULL) {
1149c1bb86cdSEric Blake         return;
1150c1bb86cdSEric Blake     }
1151c1bb86cdSEric Blake 
1152c1bb86cdSEric Blake     if (rs->fd >= 0) {
1153c1bb86cdSEric Blake         qemu_close(rs->fd);
1154c1bb86cdSEric Blake         rs->fd = -1;
1155c1bb86cdSEric Blake     }
1156c1bb86cdSEric Blake     g_free(state->opaque);
1157c1bb86cdSEric Blake     state->opaque = NULL;
1158e0c9cf3aSKevin Wolf 
1159e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1160e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1161c1bb86cdSEric Blake }
1162c1bb86cdSEric Blake 
1163867eccfeSMaxim Levitsky static int sg_get_max_transfer_length(int fd)
1164c1bb86cdSEric Blake {
1165c1bb86cdSEric Blake #ifdef BLKSECTGET
116648265250SEric Farman     int max_bytes = 0;
1167867eccfeSMaxim Levitsky 
1168867eccfeSMaxim Levitsky     if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
116948265250SEric Farman         return max_bytes;
1170c1bb86cdSEric Blake     } else {
1171c1bb86cdSEric Blake         return -errno;
1172c1bb86cdSEric Blake     }
1173c1bb86cdSEric Blake #else
1174c1bb86cdSEric Blake     return -ENOSYS;
1175c1bb86cdSEric Blake #endif
1176c1bb86cdSEric Blake }
1177c1bb86cdSEric Blake 
1178867eccfeSMaxim Levitsky static int sg_get_max_segments(int fd)
11799103f1ceSFam Zheng {
11809103f1ceSFam Zheng #ifdef CONFIG_LINUX
11819103f1ceSFam Zheng     char buf[32];
11829103f1ceSFam Zheng     const char *end;
1183867eccfeSMaxim Levitsky     char *sysfspath = NULL;
11849103f1ceSFam Zheng     int ret;
1185867eccfeSMaxim Levitsky     int sysfd = -1;
11869103f1ceSFam Zheng     long max_segments;
1187867eccfeSMaxim Levitsky     struct stat st;
1188867eccfeSMaxim Levitsky 
1189867eccfeSMaxim Levitsky     if (fstat(fd, &st)) {
1190867eccfeSMaxim Levitsky         ret = -errno;
1191867eccfeSMaxim Levitsky         goto out;
1192867eccfeSMaxim Levitsky     }
11939103f1ceSFam Zheng 
11949103f1ceSFam Zheng     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
1195867eccfeSMaxim Levitsky                                 major(st.st_rdev), minor(st.st_rdev));
1196867eccfeSMaxim Levitsky     sysfd = open(sysfspath, O_RDONLY);
1197867eccfeSMaxim Levitsky     if (sysfd == -1) {
11989103f1ceSFam Zheng         ret = -errno;
11999103f1ceSFam Zheng         goto out;
12009103f1ceSFam Zheng     }
12019103f1ceSFam Zheng     do {
1202867eccfeSMaxim Levitsky         ret = read(sysfd, buf, sizeof(buf) - 1);
12039103f1ceSFam Zheng     } while (ret == -1 && errno == EINTR);
12049103f1ceSFam Zheng     if (ret < 0) {
12059103f1ceSFam Zheng         ret = -errno;
12069103f1ceSFam Zheng         goto out;
12079103f1ceSFam Zheng     } else if (ret == 0) {
12089103f1ceSFam Zheng         ret = -EIO;
12099103f1ceSFam Zheng         goto out;
12109103f1ceSFam Zheng     }
12119103f1ceSFam Zheng     buf[ret] = 0;
12129103f1ceSFam Zheng     /* The file is ended with '\n', pass 'end' to accept that. */
12139103f1ceSFam Zheng     ret = qemu_strtol(buf, &end, 10, &max_segments);
12149103f1ceSFam Zheng     if (ret == 0 && end && *end == '\n') {
12159103f1ceSFam Zheng         ret = max_segments;
12169103f1ceSFam Zheng     }
12179103f1ceSFam Zheng 
12189103f1ceSFam Zheng out:
1219867eccfeSMaxim Levitsky     if (sysfd != -1) {
1220867eccfeSMaxim Levitsky         close(sysfd);
1221fed414dfSFam Zheng     }
12229103f1ceSFam Zheng     g_free(sysfspath);
12239103f1ceSFam Zheng     return ret;
12249103f1ceSFam Zheng #else
12259103f1ceSFam Zheng     return -ENOTSUP;
12269103f1ceSFam Zheng #endif
12279103f1ceSFam Zheng }
12289103f1ceSFam Zheng 
1229c1bb86cdSEric Blake static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1230c1bb86cdSEric Blake {
1231c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1232c1bb86cdSEric Blake 
1233867eccfeSMaxim Levitsky     if (bs->sg) {
1234867eccfeSMaxim Levitsky         int ret = sg_get_max_transfer_length(s->fd);
1235867eccfeSMaxim Levitsky 
123648265250SEric Farman         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
123748265250SEric Farman             bs->bl.max_transfer = pow2floor(ret);
1238c1bb86cdSEric Blake         }
1239867eccfeSMaxim Levitsky 
1240867eccfeSMaxim Levitsky         ret = sg_get_max_segments(s->fd);
12419103f1ceSFam Zheng         if (ret > 0) {
1242038adc2fSWei Yang             bs->bl.max_transfer = MIN(bs->bl.max_transfer,
1243038adc2fSWei Yang                                       ret * qemu_real_host_page_size);
1244c1bb86cdSEric Blake         }
1245c1bb86cdSEric Blake     }
1246c1bb86cdSEric Blake 
1247c1bb86cdSEric Blake     raw_probe_alignment(bs, s->fd, errp);
1248c1bb86cdSEric Blake     bs->bl.min_mem_alignment = s->buf_align;
1249038adc2fSWei Yang     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size);
1250c1bb86cdSEric Blake }
1251c1bb86cdSEric Blake 
1252c1bb86cdSEric Blake static int check_for_dasd(int fd)
1253c1bb86cdSEric Blake {
1254c1bb86cdSEric Blake #ifdef BIODASDINFO2
1255c1bb86cdSEric Blake     struct dasd_information2_t info = {0};
1256c1bb86cdSEric Blake 
1257c1bb86cdSEric Blake     return ioctl(fd, BIODASDINFO2, &info);
1258c1bb86cdSEric Blake #else
1259c1bb86cdSEric Blake     return -1;
1260c1bb86cdSEric Blake #endif
1261c1bb86cdSEric Blake }
1262c1bb86cdSEric Blake 
1263c1bb86cdSEric Blake /**
1264c1bb86cdSEric Blake  * Try to get @bs's logical and physical block size.
1265c1bb86cdSEric Blake  * On success, store them in @bsz and return zero.
1266c1bb86cdSEric Blake  * On failure, return negative errno.
1267c1bb86cdSEric Blake  */
1268c1bb86cdSEric Blake static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1269c1bb86cdSEric Blake {
1270c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1271c1bb86cdSEric Blake     int ret;
1272c1bb86cdSEric Blake 
1273c1bb86cdSEric Blake     /* If DASD, get blocksizes */
1274c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1275c1bb86cdSEric Blake         return -ENOTSUP;
1276c1bb86cdSEric Blake     }
1277c1bb86cdSEric Blake     ret = probe_logical_blocksize(s->fd, &bsz->log);
1278c1bb86cdSEric Blake     if (ret < 0) {
1279c1bb86cdSEric Blake         return ret;
1280c1bb86cdSEric Blake     }
1281c1bb86cdSEric Blake     return probe_physical_blocksize(s->fd, &bsz->phys);
1282c1bb86cdSEric Blake }
1283c1bb86cdSEric Blake 
1284c1bb86cdSEric Blake /**
1285c1bb86cdSEric Blake  * Try to get @bs's geometry: cyls, heads, sectors.
1286c1bb86cdSEric Blake  * On success, store them in @geo and return 0.
1287c1bb86cdSEric Blake  * On failure return -errno.
1288c1bb86cdSEric Blake  * (Allows block driver to assign default geometry values that guest sees)
1289c1bb86cdSEric Blake  */
1290c1bb86cdSEric Blake #ifdef __linux__
1291c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1292c1bb86cdSEric Blake {
1293c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1294c1bb86cdSEric Blake     struct hd_geometry ioctl_geo = {0};
1295c1bb86cdSEric Blake 
1296c1bb86cdSEric Blake     /* If DASD, get its geometry */
1297c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1298c1bb86cdSEric Blake         return -ENOTSUP;
1299c1bb86cdSEric Blake     }
1300c1bb86cdSEric Blake     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1301c1bb86cdSEric Blake         return -errno;
1302c1bb86cdSEric Blake     }
1303c1bb86cdSEric Blake     /* HDIO_GETGEO may return success even though geo contains zeros
1304c1bb86cdSEric Blake        (e.g. certain multipath setups) */
1305c1bb86cdSEric Blake     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1306c1bb86cdSEric Blake         return -ENOTSUP;
1307c1bb86cdSEric Blake     }
1308c1bb86cdSEric Blake     /* Do not return a geometry for partition */
1309c1bb86cdSEric Blake     if (ioctl_geo.start != 0) {
1310c1bb86cdSEric Blake         return -ENOTSUP;
1311c1bb86cdSEric Blake     }
1312c1bb86cdSEric Blake     geo->heads = ioctl_geo.heads;
1313c1bb86cdSEric Blake     geo->sectors = ioctl_geo.sectors;
1314c1bb86cdSEric Blake     geo->cylinders = ioctl_geo.cylinders;
1315c1bb86cdSEric Blake 
1316c1bb86cdSEric Blake     return 0;
1317c1bb86cdSEric Blake }
1318c1bb86cdSEric Blake #else /* __linux__ */
1319c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1320c1bb86cdSEric Blake {
1321c1bb86cdSEric Blake     return -ENOTSUP;
1322c1bb86cdSEric Blake }
1323c1bb86cdSEric Blake #endif
1324c1bb86cdSEric Blake 
132503425671SKevin Wolf #if defined(__linux__)
132603425671SKevin Wolf static int handle_aiocb_ioctl(void *opaque)
1327c1bb86cdSEric Blake {
132803425671SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1329c1bb86cdSEric Blake     int ret;
1330c1bb86cdSEric Blake 
1331d57c44d0SKevin Wolf     ret = ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf);
1332c1bb86cdSEric Blake     if (ret == -1) {
1333c1bb86cdSEric Blake         return -errno;
1334c1bb86cdSEric Blake     }
1335c1bb86cdSEric Blake 
1336c1bb86cdSEric Blake     return 0;
1337c1bb86cdSEric Blake }
133803425671SKevin Wolf #endif /* linux */
1339c1bb86cdSEric Blake 
134006dc9bd5SKevin Wolf static int handle_aiocb_flush(void *opaque)
1341c1bb86cdSEric Blake {
134206dc9bd5SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1343e5bcf967SKevin Wolf     BDRVRawState *s = aiocb->bs->opaque;
1344c1bb86cdSEric Blake     int ret;
1345c1bb86cdSEric Blake 
1346e5bcf967SKevin Wolf     if (s->page_cache_inconsistent) {
1347e5bcf967SKevin Wolf         return -EIO;
1348e5bcf967SKevin Wolf     }
1349e5bcf967SKevin Wolf 
1350c1bb86cdSEric Blake     ret = qemu_fdatasync(aiocb->aio_fildes);
1351c1bb86cdSEric Blake     if (ret == -1) {
1352e5bcf967SKevin Wolf         /* There is no clear definition of the semantics of a failing fsync(),
1353e5bcf967SKevin Wolf          * so we may have to assume the worst. The sad truth is that this
1354e5bcf967SKevin Wolf          * assumption is correct for Linux. Some pages are now probably marked
1355e5bcf967SKevin Wolf          * clean in the page cache even though they are inconsistent with the
1356e5bcf967SKevin Wolf          * on-disk contents. The next fdatasync() call would succeed, but no
1357e5bcf967SKevin Wolf          * further writeback attempt will be made. We can't get back to a state
1358e5bcf967SKevin Wolf          * in which we know what is on disk (we would have to rewrite
1359e5bcf967SKevin Wolf          * everything that was touched since the last fdatasync() at least), so
1360e5bcf967SKevin Wolf          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1361e5bcf967SKevin Wolf          * really defined, I have little hope that other OSes are doing better.
1362e5bcf967SKevin Wolf          *
1363e5bcf967SKevin Wolf          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1364e5bcf967SKevin Wolf          * cache. */
1365e5bcf967SKevin Wolf         if ((s->open_flags & O_DIRECT) == 0) {
1366e5bcf967SKevin Wolf             s->page_cache_inconsistent = true;
1367e5bcf967SKevin Wolf         }
1368c1bb86cdSEric Blake         return -errno;
1369c1bb86cdSEric Blake     }
1370c1bb86cdSEric Blake     return 0;
1371c1bb86cdSEric Blake }
1372c1bb86cdSEric Blake 
1373c1bb86cdSEric Blake #ifdef CONFIG_PREADV
1374c1bb86cdSEric Blake 
1375c1bb86cdSEric Blake static bool preadv_present = true;
1376c1bb86cdSEric Blake 
1377c1bb86cdSEric Blake static ssize_t
1378c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1379c1bb86cdSEric Blake {
1380c1bb86cdSEric Blake     return preadv(fd, iov, nr_iov, offset);
1381c1bb86cdSEric Blake }
1382c1bb86cdSEric Blake 
1383c1bb86cdSEric Blake static ssize_t
1384c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1385c1bb86cdSEric Blake {
1386c1bb86cdSEric Blake     return pwritev(fd, iov, nr_iov, offset);
1387c1bb86cdSEric Blake }
1388c1bb86cdSEric Blake 
1389c1bb86cdSEric Blake #else
1390c1bb86cdSEric Blake 
1391c1bb86cdSEric Blake static bool preadv_present = false;
1392c1bb86cdSEric Blake 
1393c1bb86cdSEric Blake static ssize_t
1394c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1395c1bb86cdSEric Blake {
1396c1bb86cdSEric Blake     return -ENOSYS;
1397c1bb86cdSEric Blake }
1398c1bb86cdSEric Blake 
1399c1bb86cdSEric Blake static ssize_t
1400c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1401c1bb86cdSEric Blake {
1402c1bb86cdSEric Blake     return -ENOSYS;
1403c1bb86cdSEric Blake }
1404c1bb86cdSEric Blake 
1405c1bb86cdSEric Blake #endif
1406c1bb86cdSEric Blake 
1407c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1408c1bb86cdSEric Blake {
1409c1bb86cdSEric Blake     ssize_t len;
1410c1bb86cdSEric Blake 
1411c1bb86cdSEric Blake     do {
1412c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE)
1413c1bb86cdSEric Blake             len = qemu_pwritev(aiocb->aio_fildes,
1414d57c44d0SKevin Wolf                                aiocb->io.iov,
1415d57c44d0SKevin Wolf                                aiocb->io.niov,
1416c1bb86cdSEric Blake                                aiocb->aio_offset);
1417c1bb86cdSEric Blake          else
1418c1bb86cdSEric Blake             len = qemu_preadv(aiocb->aio_fildes,
1419d57c44d0SKevin Wolf                               aiocb->io.iov,
1420d57c44d0SKevin Wolf                               aiocb->io.niov,
1421c1bb86cdSEric Blake                               aiocb->aio_offset);
1422c1bb86cdSEric Blake     } while (len == -1 && errno == EINTR);
1423c1bb86cdSEric Blake 
1424c1bb86cdSEric Blake     if (len == -1) {
1425c1bb86cdSEric Blake         return -errno;
1426c1bb86cdSEric Blake     }
1427c1bb86cdSEric Blake     return len;
1428c1bb86cdSEric Blake }
1429c1bb86cdSEric Blake 
1430c1bb86cdSEric Blake /*
1431c1bb86cdSEric Blake  * Read/writes the data to/from a given linear buffer.
1432c1bb86cdSEric Blake  *
1433c1bb86cdSEric Blake  * Returns the number of bytes handles or -errno in case of an error. Short
1434c1bb86cdSEric Blake  * reads are only returned if the end of the file is reached.
1435c1bb86cdSEric Blake  */
1436c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1437c1bb86cdSEric Blake {
1438c1bb86cdSEric Blake     ssize_t offset = 0;
1439c1bb86cdSEric Blake     ssize_t len;
1440c1bb86cdSEric Blake 
1441c1bb86cdSEric Blake     while (offset < aiocb->aio_nbytes) {
1442c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1443c1bb86cdSEric Blake             len = pwrite(aiocb->aio_fildes,
1444c1bb86cdSEric Blake                          (const char *)buf + offset,
1445c1bb86cdSEric Blake                          aiocb->aio_nbytes - offset,
1446c1bb86cdSEric Blake                          aiocb->aio_offset + offset);
1447c1bb86cdSEric Blake         } else {
1448c1bb86cdSEric Blake             len = pread(aiocb->aio_fildes,
1449c1bb86cdSEric Blake                         buf + offset,
1450c1bb86cdSEric Blake                         aiocb->aio_nbytes - offset,
1451c1bb86cdSEric Blake                         aiocb->aio_offset + offset);
1452c1bb86cdSEric Blake         }
1453c1bb86cdSEric Blake         if (len == -1 && errno == EINTR) {
1454c1bb86cdSEric Blake             continue;
1455c1bb86cdSEric Blake         } else if (len == -1 && errno == EINVAL &&
1456c1bb86cdSEric Blake                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1457c1bb86cdSEric Blake                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1458c1bb86cdSEric Blake                    offset > 0) {
1459c1bb86cdSEric Blake             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1460c1bb86cdSEric Blake              * after a short read.  Assume that O_DIRECT short reads only occur
1461c1bb86cdSEric Blake              * at EOF.  Therefore this is a short read, not an I/O error.
1462c1bb86cdSEric Blake              */
1463c1bb86cdSEric Blake             break;
1464c1bb86cdSEric Blake         } else if (len == -1) {
1465c1bb86cdSEric Blake             offset = -errno;
1466c1bb86cdSEric Blake             break;
1467c1bb86cdSEric Blake         } else if (len == 0) {
1468c1bb86cdSEric Blake             break;
1469c1bb86cdSEric Blake         }
1470c1bb86cdSEric Blake         offset += len;
1471c1bb86cdSEric Blake     }
1472c1bb86cdSEric Blake 
1473c1bb86cdSEric Blake     return offset;
1474c1bb86cdSEric Blake }
1475c1bb86cdSEric Blake 
1476999e6b69SKevin Wolf static int handle_aiocb_rw(void *opaque)
1477c1bb86cdSEric Blake {
1478999e6b69SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1479c1bb86cdSEric Blake     ssize_t nbytes;
1480c1bb86cdSEric Blake     char *buf;
1481c1bb86cdSEric Blake 
1482c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1483c1bb86cdSEric Blake         /*
1484c1bb86cdSEric Blake          * If there is just a single buffer, and it is properly aligned
1485c1bb86cdSEric Blake          * we can just use plain pread/pwrite without any problems.
1486c1bb86cdSEric Blake          */
1487d57c44d0SKevin Wolf         if (aiocb->io.niov == 1) {
148854c7ca1bSKevin Wolf             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
148954c7ca1bSKevin Wolf             goto out;
1490c1bb86cdSEric Blake         }
1491c1bb86cdSEric Blake         /*
1492c1bb86cdSEric Blake          * We have more than one iovec, and all are properly aligned.
1493c1bb86cdSEric Blake          *
1494c1bb86cdSEric Blake          * Try preadv/pwritev first and fall back to linearizing the
1495c1bb86cdSEric Blake          * buffer if it's not supported.
1496c1bb86cdSEric Blake          */
1497c1bb86cdSEric Blake         if (preadv_present) {
1498c1bb86cdSEric Blake             nbytes = handle_aiocb_rw_vector(aiocb);
1499c1bb86cdSEric Blake             if (nbytes == aiocb->aio_nbytes ||
1500c1bb86cdSEric Blake                 (nbytes < 0 && nbytes != -ENOSYS)) {
150154c7ca1bSKevin Wolf                 goto out;
1502c1bb86cdSEric Blake             }
1503c1bb86cdSEric Blake             preadv_present = false;
1504c1bb86cdSEric Blake         }
1505c1bb86cdSEric Blake 
1506c1bb86cdSEric Blake         /*
1507c1bb86cdSEric Blake          * XXX(hch): short read/write.  no easy way to handle the reminder
1508c1bb86cdSEric Blake          * using these interfaces.  For now retry using plain
1509c1bb86cdSEric Blake          * pread/pwrite?
1510c1bb86cdSEric Blake          */
1511c1bb86cdSEric Blake     }
1512c1bb86cdSEric Blake 
1513c1bb86cdSEric Blake     /*
1514c1bb86cdSEric Blake      * Ok, we have to do it the hard way, copy all segments into
1515c1bb86cdSEric Blake      * a single aligned buffer.
1516c1bb86cdSEric Blake      */
1517c1bb86cdSEric Blake     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1518c1bb86cdSEric Blake     if (buf == NULL) {
151954c7ca1bSKevin Wolf         nbytes = -ENOMEM;
152054c7ca1bSKevin Wolf         goto out;
1521c1bb86cdSEric Blake     }
1522c1bb86cdSEric Blake 
1523c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1524c1bb86cdSEric Blake         char *p = buf;
1525c1bb86cdSEric Blake         int i;
1526c1bb86cdSEric Blake 
1527d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov; ++i) {
1528d57c44d0SKevin Wolf             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1529d57c44d0SKevin Wolf             p += aiocb->io.iov[i].iov_len;
1530c1bb86cdSEric Blake         }
1531c1bb86cdSEric Blake         assert(p - buf == aiocb->aio_nbytes);
1532c1bb86cdSEric Blake     }
1533c1bb86cdSEric Blake 
1534c1bb86cdSEric Blake     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1535c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1536c1bb86cdSEric Blake         char *p = buf;
1537c1bb86cdSEric Blake         size_t count = aiocb->aio_nbytes, copy;
1538c1bb86cdSEric Blake         int i;
1539c1bb86cdSEric Blake 
1540d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov && count; ++i) {
1541c1bb86cdSEric Blake             copy = count;
1542d57c44d0SKevin Wolf             if (copy > aiocb->io.iov[i].iov_len) {
1543d57c44d0SKevin Wolf                 copy = aiocb->io.iov[i].iov_len;
1544c1bb86cdSEric Blake             }
1545d57c44d0SKevin Wolf             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1546c1bb86cdSEric Blake             assert(count >= copy);
1547c1bb86cdSEric Blake             p     += copy;
1548c1bb86cdSEric Blake             count -= copy;
1549c1bb86cdSEric Blake         }
1550c1bb86cdSEric Blake         assert(count == 0);
1551c1bb86cdSEric Blake     }
1552c1bb86cdSEric Blake     qemu_vfree(buf);
1553c1bb86cdSEric Blake 
155454c7ca1bSKevin Wolf out:
155554c7ca1bSKevin Wolf     if (nbytes == aiocb->aio_nbytes) {
155654c7ca1bSKevin Wolf         return 0;
155754c7ca1bSKevin Wolf     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
155854c7ca1bSKevin Wolf         if (aiocb->aio_type & QEMU_AIO_WRITE) {
155954c7ca1bSKevin Wolf             return -EINVAL;
156054c7ca1bSKevin Wolf         } else {
156154c7ca1bSKevin Wolf             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
156254c7ca1bSKevin Wolf                       0, aiocb->aio_nbytes - nbytes);
156354c7ca1bSKevin Wolf             return 0;
156454c7ca1bSKevin Wolf         }
156554c7ca1bSKevin Wolf     } else {
156654c7ca1bSKevin Wolf         assert(nbytes < 0);
1567c1bb86cdSEric Blake         return nbytes;
1568c1bb86cdSEric Blake     }
156954c7ca1bSKevin Wolf }
1570c1bb86cdSEric Blake 
1571c1bb86cdSEric Blake static int translate_err(int err)
1572c1bb86cdSEric Blake {
1573c1bb86cdSEric Blake     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1574c1bb86cdSEric Blake         err == -ENOTTY) {
1575c1bb86cdSEric Blake         err = -ENOTSUP;
1576c1bb86cdSEric Blake     }
1577c1bb86cdSEric Blake     return err;
1578c1bb86cdSEric Blake }
1579c1bb86cdSEric Blake 
1580c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
1581c1bb86cdSEric Blake static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1582c1bb86cdSEric Blake {
1583c1bb86cdSEric Blake     do {
1584c1bb86cdSEric Blake         if (fallocate(fd, mode, offset, len) == 0) {
1585c1bb86cdSEric Blake             return 0;
1586c1bb86cdSEric Blake         }
1587c1bb86cdSEric Blake     } while (errno == EINTR);
1588c1bb86cdSEric Blake     return translate_err(-errno);
1589c1bb86cdSEric Blake }
1590c1bb86cdSEric Blake #endif
1591c1bb86cdSEric Blake 
1592c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1593c1bb86cdSEric Blake {
1594c1bb86cdSEric Blake     int ret = -ENOTSUP;
1595c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1596c1bb86cdSEric Blake 
1597c1bb86cdSEric Blake     if (!s->has_write_zeroes) {
1598c1bb86cdSEric Blake         return -ENOTSUP;
1599c1bb86cdSEric Blake     }
1600c1bb86cdSEric Blake 
1601c1bb86cdSEric Blake #ifdef BLKZEROOUT
1602738301e1SKevin Wolf     /* The BLKZEROOUT implementation in the kernel doesn't set
1603738301e1SKevin Wolf      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1604738301e1SKevin Wolf      * fallbacks. */
1605738301e1SKevin Wolf     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1606c1bb86cdSEric Blake         do {
1607c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1608c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1609c1bb86cdSEric Blake                 return 0;
1610c1bb86cdSEric Blake             }
1611c1bb86cdSEric Blake         } while (errno == EINTR);
1612c1bb86cdSEric Blake 
1613c1bb86cdSEric Blake         ret = translate_err(-errno);
1614c1bb86cdSEric Blake         if (ret == -ENOTSUP) {
1615c1bb86cdSEric Blake             s->has_write_zeroes = false;
1616c1bb86cdSEric Blake         }
1617effecce6SKevin Wolf     }
1618effecce6SKevin Wolf #endif
1619effecce6SKevin Wolf 
1620c1bb86cdSEric Blake     return ret;
1621c1bb86cdSEric Blake }
1622c1bb86cdSEric Blake 
16237154d8aeSKevin Wolf static int handle_aiocb_write_zeroes(void *opaque)
1624c1bb86cdSEric Blake {
16257154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
162670d9110bSDenis V. Lunev #ifdef CONFIG_FALLOCATE
1627b2c6f23fSMax Reitz     BDRVRawState *s = aiocb->bs->opaque;
162870d9110bSDenis V. Lunev     int64_t len;
162970d9110bSDenis V. Lunev #endif
1630c1bb86cdSEric Blake 
1631c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1632c1bb86cdSEric Blake         return handle_aiocb_write_zeroes_block(aiocb);
1633c1bb86cdSEric Blake     }
1634c1bb86cdSEric Blake 
1635c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1636c1bb86cdSEric Blake     if (s->has_write_zeroes) {
1637c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1638c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1639294682ccSAndrey Shinkevich         if (ret == -EINVAL) {
1640294682ccSAndrey Shinkevich             /*
1641294682ccSAndrey Shinkevich              * Allow falling back to pwrite for file systems that
1642294682ccSAndrey Shinkevich              * do not support fallocate() for an unaligned byte range.
1643294682ccSAndrey Shinkevich              */
1644294682ccSAndrey Shinkevich             return -ENOTSUP;
1645294682ccSAndrey Shinkevich         }
1646c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1647c1bb86cdSEric Blake             return ret;
1648c1bb86cdSEric Blake         }
1649c1bb86cdSEric Blake         s->has_write_zeroes = false;
1650c1bb86cdSEric Blake     }
1651c1bb86cdSEric Blake #endif
1652c1bb86cdSEric Blake 
1653c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1654c1bb86cdSEric Blake     if (s->has_discard && s->has_fallocate) {
1655c1bb86cdSEric Blake         int ret = do_fallocate(s->fd,
1656c1bb86cdSEric Blake                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1657c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1658c1bb86cdSEric Blake         if (ret == 0) {
1659c1bb86cdSEric Blake             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1660c1bb86cdSEric Blake             if (ret == 0 || ret != -ENOTSUP) {
1661c1bb86cdSEric Blake                 return ret;
1662c1bb86cdSEric Blake             }
1663c1bb86cdSEric Blake             s->has_fallocate = false;
1664c1bb86cdSEric Blake         } else if (ret != -ENOTSUP) {
1665c1bb86cdSEric Blake             return ret;
1666c1bb86cdSEric Blake         } else {
1667c1bb86cdSEric Blake             s->has_discard = false;
1668c1bb86cdSEric Blake         }
1669c1bb86cdSEric Blake     }
1670c1bb86cdSEric Blake #endif
1671c1bb86cdSEric Blake 
1672c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
167370d9110bSDenis V. Lunev     /* Last resort: we are trying to extend the file with zeroed data. This
167470d9110bSDenis V. Lunev      * can be done via fallocate(fd, 0) */
167570d9110bSDenis V. Lunev     len = bdrv_getlength(aiocb->bs);
167670d9110bSDenis V. Lunev     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1677c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1678c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1679c1bb86cdSEric Blake             return ret;
1680c1bb86cdSEric Blake         }
1681c1bb86cdSEric Blake         s->has_fallocate = false;
1682c1bb86cdSEric Blake     }
1683c1bb86cdSEric Blake #endif
1684c1bb86cdSEric Blake 
1685c1bb86cdSEric Blake     return -ENOTSUP;
1686c1bb86cdSEric Blake }
1687c1bb86cdSEric Blake 
16887154d8aeSKevin Wolf static int handle_aiocb_write_zeroes_unmap(void *opaque)
168934fa110eSKevin Wolf {
16907154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
169134fa110eSKevin Wolf     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
169234fa110eSKevin Wolf 
169334fa110eSKevin Wolf     /* First try to write zeros and unmap at the same time */
169434fa110eSKevin Wolf 
169534fa110eSKevin Wolf #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1696b3ac2b94SSimran Singhal     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
169734fa110eSKevin Wolf                            aiocb->aio_offset, aiocb->aio_nbytes);
1698bae127d4SAntoine Damhet     switch (ret) {
1699bae127d4SAntoine Damhet     case -ENOTSUP:
1700bae127d4SAntoine Damhet     case -EINVAL:
1701ece4fa91SMaxim Levitsky     case -EBUSY:
1702bae127d4SAntoine Damhet         break;
1703bae127d4SAntoine Damhet     default:
170434fa110eSKevin Wolf         return ret;
170534fa110eSKevin Wolf     }
170634fa110eSKevin Wolf #endif
170734fa110eSKevin Wolf 
170834fa110eSKevin Wolf     /* If we couldn't manage to unmap while guaranteed that the area reads as
170934fa110eSKevin Wolf      * all-zero afterwards, just write zeroes without unmapping */
1710b3ac2b94SSimran Singhal     return handle_aiocb_write_zeroes(aiocb);
171134fa110eSKevin Wolf }
171234fa110eSKevin Wolf 
17131efad060SFam Zheng #ifndef HAVE_COPY_FILE_RANGE
17141efad060SFam Zheng static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
17151efad060SFam Zheng                              off_t *out_off, size_t len, unsigned int flags)
17161efad060SFam Zheng {
17171efad060SFam Zheng #ifdef __NR_copy_file_range
17181efad060SFam Zheng     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
17191efad060SFam Zheng                    out_off, len, flags);
17201efad060SFam Zheng #else
17211efad060SFam Zheng     errno = ENOSYS;
17221efad060SFam Zheng     return -1;
17231efad060SFam Zheng #endif
17241efad060SFam Zheng }
17251efad060SFam Zheng #endif
17261efad060SFam Zheng 
172758a209c4SKevin Wolf static int handle_aiocb_copy_range(void *opaque)
17281efad060SFam Zheng {
172958a209c4SKevin Wolf     RawPosixAIOData *aiocb = opaque;
17301efad060SFam Zheng     uint64_t bytes = aiocb->aio_nbytes;
17311efad060SFam Zheng     off_t in_off = aiocb->aio_offset;
1732d57c44d0SKevin Wolf     off_t out_off = aiocb->copy_range.aio_offset2;
17331efad060SFam Zheng 
17341efad060SFam Zheng     while (bytes) {
17351efad060SFam Zheng         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
1736d57c44d0SKevin Wolf                                       aiocb->copy_range.aio_fd2, &out_off,
17371efad060SFam Zheng                                       bytes, 0);
1738ecc983a5SFam Zheng         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1739d57c44d0SKevin Wolf                                    aiocb->copy_range.aio_fd2, out_off, bytes,
1740d57c44d0SKevin Wolf                                    0, ret);
1741c436e3d0SFam Zheng         if (ret == 0) {
1742c436e3d0SFam Zheng             /* No progress (e.g. when beyond EOF), let the caller fall back to
1743c436e3d0SFam Zheng              * buffer I/O. */
1744c436e3d0SFam Zheng             return -ENOSPC;
17451efad060SFam Zheng         }
17461efad060SFam Zheng         if (ret < 0) {
1747c436e3d0SFam Zheng             switch (errno) {
1748c436e3d0SFam Zheng             case ENOSYS:
17491efad060SFam Zheng                 return -ENOTSUP;
1750c436e3d0SFam Zheng             case EINTR:
1751c436e3d0SFam Zheng                 continue;
1752c436e3d0SFam Zheng             default:
17531efad060SFam Zheng                 return -errno;
17541efad060SFam Zheng             }
17551efad060SFam Zheng         }
17561efad060SFam Zheng         bytes -= ret;
17571efad060SFam Zheng     }
17581efad060SFam Zheng     return 0;
17591efad060SFam Zheng }
17601efad060SFam Zheng 
176146ee0f46SKevin Wolf static int handle_aiocb_discard(void *opaque)
1762c1bb86cdSEric Blake {
176346ee0f46SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1764c1bb86cdSEric Blake     int ret = -EOPNOTSUPP;
1765c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1766c1bb86cdSEric Blake 
1767c1bb86cdSEric Blake     if (!s->has_discard) {
1768c1bb86cdSEric Blake         return -ENOTSUP;
1769c1bb86cdSEric Blake     }
1770c1bb86cdSEric Blake 
1771c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1772c1bb86cdSEric Blake #ifdef BLKDISCARD
1773c1bb86cdSEric Blake         do {
1774c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1775c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1776c1bb86cdSEric Blake                 return 0;
1777c1bb86cdSEric Blake             }
1778c1bb86cdSEric Blake         } while (errno == EINTR);
1779c1bb86cdSEric Blake 
1780c1bb86cdSEric Blake         ret = -errno;
1781c1bb86cdSEric Blake #endif
1782c1bb86cdSEric Blake     } else {
1783c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1784c1bb86cdSEric Blake         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1785c1bb86cdSEric Blake                            aiocb->aio_offset, aiocb->aio_nbytes);
1786c1bb86cdSEric Blake #endif
1787c1bb86cdSEric Blake     }
1788c1bb86cdSEric Blake 
1789c1bb86cdSEric Blake     ret = translate_err(ret);
1790c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1791c1bb86cdSEric Blake         s->has_discard = false;
1792c1bb86cdSEric Blake     }
1793c1bb86cdSEric Blake     return ret;
1794c1bb86cdSEric Blake }
1795c1bb86cdSEric Blake 
17963a20013fSNir Soffer /*
17973a20013fSNir Soffer  * Help alignment probing by allocating the first block.
17983a20013fSNir Soffer  *
17993a20013fSNir Soffer  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
18003a20013fSNir Soffer  * reading succeeds regardless of request length. In this case we fallback to
18013a20013fSNir Soffer  * safe alignment which is not optimal. Allocating the first block avoids this
18023a20013fSNir Soffer  * fallback.
18033a20013fSNir Soffer  *
18043a20013fSNir Soffer  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
18053a20013fSNir Soffer  * request alignment, so we use safe values.
18063a20013fSNir Soffer  *
18073a20013fSNir Soffer  * Returns: 0 on success, -errno on failure. Since this is an optimization,
18083a20013fSNir Soffer  * caller may ignore failures.
18093a20013fSNir Soffer  */
18103a20013fSNir Soffer static int allocate_first_block(int fd, size_t max_size)
18113a20013fSNir Soffer {
18123a20013fSNir Soffer     size_t write_size = (max_size < MAX_BLOCKSIZE)
18133a20013fSNir Soffer         ? BDRV_SECTOR_SIZE
18143a20013fSNir Soffer         : MAX_BLOCKSIZE;
1815038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
18163a20013fSNir Soffer     void *buf;
18173a20013fSNir Soffer     ssize_t n;
18183a20013fSNir Soffer     int ret;
18193a20013fSNir Soffer 
18203a20013fSNir Soffer     buf = qemu_memalign(max_align, write_size);
18213a20013fSNir Soffer     memset(buf, 0, write_size);
18223a20013fSNir Soffer 
18233a20013fSNir Soffer     do {
18243a20013fSNir Soffer         n = pwrite(fd, buf, write_size, 0);
18253a20013fSNir Soffer     } while (n == -1 && errno == EINTR);
18263a20013fSNir Soffer 
18273a20013fSNir Soffer     ret = (n == -1) ? -errno : 0;
18283a20013fSNir Soffer 
18293a20013fSNir Soffer     qemu_vfree(buf);
18303a20013fSNir Soffer     return ret;
18313a20013fSNir Soffer }
18323a20013fSNir Soffer 
183329cb4c01SKevin Wolf static int handle_aiocb_truncate(void *opaque)
183493f4e2ffSKevin Wolf {
183529cb4c01SKevin Wolf     RawPosixAIOData *aiocb = opaque;
183693f4e2ffSKevin Wolf     int result = 0;
183793f4e2ffSKevin Wolf     int64_t current_length = 0;
183893f4e2ffSKevin Wolf     char *buf = NULL;
183993f4e2ffSKevin Wolf     struct stat st;
184093f4e2ffSKevin Wolf     int fd = aiocb->aio_fildes;
184193f4e2ffSKevin Wolf     int64_t offset = aiocb->aio_offset;
1842d57c44d0SKevin Wolf     PreallocMode prealloc = aiocb->truncate.prealloc;
1843d57c44d0SKevin Wolf     Error **errp = aiocb->truncate.errp;
184493f4e2ffSKevin Wolf 
184593f4e2ffSKevin Wolf     if (fstat(fd, &st) < 0) {
184693f4e2ffSKevin Wolf         result = -errno;
184793f4e2ffSKevin Wolf         error_setg_errno(errp, -result, "Could not stat file");
184893f4e2ffSKevin Wolf         return result;
184993f4e2ffSKevin Wolf     }
185093f4e2ffSKevin Wolf 
185193f4e2ffSKevin Wolf     current_length = st.st_size;
1852d57c44d0SKevin Wolf     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
185393f4e2ffSKevin Wolf         error_setg(errp, "Cannot use preallocation for shrinking files");
185493f4e2ffSKevin Wolf         return -ENOTSUP;
185593f4e2ffSKevin Wolf     }
185693f4e2ffSKevin Wolf 
1857d57c44d0SKevin Wolf     switch (prealloc) {
185893f4e2ffSKevin Wolf #ifdef CONFIG_POSIX_FALLOCATE
185993f4e2ffSKevin Wolf     case PREALLOC_MODE_FALLOC:
186093f4e2ffSKevin Wolf         /*
186193f4e2ffSKevin Wolf          * Truncating before posix_fallocate() makes it about twice slower on
186293f4e2ffSKevin Wolf          * file systems that do not support fallocate(), trying to check if a
186393f4e2ffSKevin Wolf          * block is allocated before allocating it, so don't do that here.
186493f4e2ffSKevin Wolf          */
186593f4e2ffSKevin Wolf         if (offset != current_length) {
186693f4e2ffSKevin Wolf             result = -posix_fallocate(fd, current_length,
186793f4e2ffSKevin Wolf                                       offset - current_length);
186893f4e2ffSKevin Wolf             if (result != 0) {
186993f4e2ffSKevin Wolf                 /* posix_fallocate() doesn't set errno. */
187093f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
187193f4e2ffSKevin Wolf                                  "Could not preallocate new data");
18723a20013fSNir Soffer             } else if (current_length == 0) {
18733a20013fSNir Soffer                 /*
18743a20013fSNir Soffer                  * posix_fallocate() uses fallocate() if the filesystem
18753a20013fSNir Soffer                  * supports it, or fallback to manually writing zeroes. If
18763a20013fSNir Soffer                  * fallocate() was used, unaligned reads from the fallocated
18773a20013fSNir Soffer                  * area in raw_probe_alignment() will succeed, hence we need to
18783a20013fSNir Soffer                  * allocate the first block.
18793a20013fSNir Soffer                  *
18803a20013fSNir Soffer                  * Optimize future alignment probing; ignore failures.
18813a20013fSNir Soffer                  */
18823a20013fSNir Soffer                 allocate_first_block(fd, offset);
188393f4e2ffSKevin Wolf             }
188493f4e2ffSKevin Wolf         } else {
188593f4e2ffSKevin Wolf             result = 0;
188693f4e2ffSKevin Wolf         }
188793f4e2ffSKevin Wolf         goto out;
188893f4e2ffSKevin Wolf #endif
188993f4e2ffSKevin Wolf     case PREALLOC_MODE_FULL:
189093f4e2ffSKevin Wolf     {
189193f4e2ffSKevin Wolf         int64_t num = 0, left = offset - current_length;
189293f4e2ffSKevin Wolf         off_t seek_result;
189393f4e2ffSKevin Wolf 
189493f4e2ffSKevin Wolf         /*
189593f4e2ffSKevin Wolf          * Knowing the final size from the beginning could allow the file
189693f4e2ffSKevin Wolf          * system driver to do less allocations and possibly avoid
189793f4e2ffSKevin Wolf          * fragmentation of the file.
189893f4e2ffSKevin Wolf          */
189993f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
190093f4e2ffSKevin Wolf             result = -errno;
190193f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
190293f4e2ffSKevin Wolf             goto out;
190393f4e2ffSKevin Wolf         }
190493f4e2ffSKevin Wolf 
190593f4e2ffSKevin Wolf         buf = g_malloc0(65536);
190693f4e2ffSKevin Wolf 
190793f4e2ffSKevin Wolf         seek_result = lseek(fd, current_length, SEEK_SET);
190893f4e2ffSKevin Wolf         if (seek_result < 0) {
190993f4e2ffSKevin Wolf             result = -errno;
191093f4e2ffSKevin Wolf             error_setg_errno(errp, -result,
191193f4e2ffSKevin Wolf                              "Failed to seek to the old end of file");
191293f4e2ffSKevin Wolf             goto out;
191393f4e2ffSKevin Wolf         }
191493f4e2ffSKevin Wolf 
191593f4e2ffSKevin Wolf         while (left > 0) {
191693f4e2ffSKevin Wolf             num = MIN(left, 65536);
191793f4e2ffSKevin Wolf             result = write(fd, buf, num);
191893f4e2ffSKevin Wolf             if (result < 0) {
1919a1c81f4fSFam Zheng                 if (errno == EINTR) {
1920a1c81f4fSFam Zheng                     continue;
1921a1c81f4fSFam Zheng                 }
192293f4e2ffSKevin Wolf                 result = -errno;
192393f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
192493f4e2ffSKevin Wolf                                  "Could not write zeros for preallocation");
192593f4e2ffSKevin Wolf                 goto out;
192693f4e2ffSKevin Wolf             }
192793f4e2ffSKevin Wolf             left -= result;
192893f4e2ffSKevin Wolf         }
192993f4e2ffSKevin Wolf         if (result >= 0) {
193093f4e2ffSKevin Wolf             result = fsync(fd);
193193f4e2ffSKevin Wolf             if (result < 0) {
193293f4e2ffSKevin Wolf                 result = -errno;
193393f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
193493f4e2ffSKevin Wolf                                  "Could not flush file to disk");
193593f4e2ffSKevin Wolf                 goto out;
193693f4e2ffSKevin Wolf             }
193793f4e2ffSKevin Wolf         }
193893f4e2ffSKevin Wolf         goto out;
193993f4e2ffSKevin Wolf     }
194093f4e2ffSKevin Wolf     case PREALLOC_MODE_OFF:
194193f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
194293f4e2ffSKevin Wolf             result = -errno;
194393f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
19443a20013fSNir Soffer         } else if (current_length == 0 && offset > current_length) {
19453a20013fSNir Soffer             /* Optimize future alignment probing; ignore failures. */
19463a20013fSNir Soffer             allocate_first_block(fd, offset);
194793f4e2ffSKevin Wolf         }
194893f4e2ffSKevin Wolf         return result;
194993f4e2ffSKevin Wolf     default:
195093f4e2ffSKevin Wolf         result = -ENOTSUP;
195193f4e2ffSKevin Wolf         error_setg(errp, "Unsupported preallocation mode: %s",
1952d57c44d0SKevin Wolf                    PreallocMode_str(prealloc));
195393f4e2ffSKevin Wolf         return result;
195493f4e2ffSKevin Wolf     }
195593f4e2ffSKevin Wolf 
195693f4e2ffSKevin Wolf out:
195793f4e2ffSKevin Wolf     if (result < 0) {
195893f4e2ffSKevin Wolf         if (ftruncate(fd, current_length) < 0) {
195993f4e2ffSKevin Wolf             error_report("Failed to restore old file length: %s",
196093f4e2ffSKevin Wolf                          strerror(errno));
196193f4e2ffSKevin Wolf         }
196293f4e2ffSKevin Wolf     }
196393f4e2ffSKevin Wolf 
196493f4e2ffSKevin Wolf     g_free(buf);
196593f4e2ffSKevin Wolf     return result;
196693f4e2ffSKevin Wolf }
196793f4e2ffSKevin Wolf 
19685d5de250SKevin Wolf static int coroutine_fn raw_thread_pool_submit(BlockDriverState *bs,
19695d5de250SKevin Wolf                                                ThreadPoolFunc func, void *arg)
19705d5de250SKevin Wolf {
19715d5de250SKevin Wolf     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
19725d5de250SKevin Wolf     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
19735d5de250SKevin Wolf     return thread_pool_submit_co(pool, func, arg);
19745d5de250SKevin Wolf }
19755d5de250SKevin Wolf 
1976c1bb86cdSEric Blake static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1977c1bb86cdSEric Blake                                    uint64_t bytes, QEMUIOVector *qiov, int type)
1978c1bb86cdSEric Blake {
1979c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1980999e6b69SKevin Wolf     RawPosixAIOData acb;
1981c1bb86cdSEric Blake 
1982c1bb86cdSEric Blake     if (fd_open(bs) < 0)
1983c1bb86cdSEric Blake         return -EIO;
1984c1bb86cdSEric Blake 
1985c1bb86cdSEric Blake     /*
1986c6447510SAarushi Mehta      * When using O_DIRECT, the request must be aligned to be able to use
1987c6447510SAarushi Mehta      * either libaio or io_uring interface. If not fail back to regular thread
1988c6447510SAarushi Mehta      * pool read/write code which emulates this for us if we
1989c6447510SAarushi Mehta      * set QEMU_AIO_MISALIGNED.
1990c1bb86cdSEric Blake      */
1991c6447510SAarushi Mehta     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
1992c1bb86cdSEric Blake         type |= QEMU_AIO_MISALIGNED;
1993c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
1994c6447510SAarushi Mehta     } else if (s->use_linux_io_uring) {
1995c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
1996c6447510SAarushi Mehta         assert(qiov->size == bytes);
1997c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, offset, qiov, type);
1998c6447510SAarushi Mehta #endif
1999c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2000c1bb86cdSEric Blake     } else if (s->use_linux_aio) {
2001c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2002c1bb86cdSEric Blake         assert(qiov->size == bytes);
2003c1bb86cdSEric Blake         return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
2004c1bb86cdSEric Blake #endif
2005c1bb86cdSEric Blake     }
2006c1bb86cdSEric Blake 
2007999e6b69SKevin Wolf     acb = (RawPosixAIOData) {
2008999e6b69SKevin Wolf         .bs             = bs,
2009999e6b69SKevin Wolf         .aio_fildes     = s->fd,
2010999e6b69SKevin Wolf         .aio_type       = type,
2011999e6b69SKevin Wolf         .aio_offset     = offset,
2012999e6b69SKevin Wolf         .aio_nbytes     = bytes,
2013999e6b69SKevin Wolf         .io             = {
2014999e6b69SKevin Wolf             .iov            = qiov->iov,
2015999e6b69SKevin Wolf             .niov           = qiov->niov,
2016999e6b69SKevin Wolf         },
2017999e6b69SKevin Wolf     };
2018999e6b69SKevin Wolf 
2019999e6b69SKevin Wolf     assert(qiov->size == bytes);
2020999e6b69SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_rw, &acb);
2021c1bb86cdSEric Blake }
2022c1bb86cdSEric Blake 
2023c1bb86cdSEric Blake static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
2024c1bb86cdSEric Blake                                       uint64_t bytes, QEMUIOVector *qiov,
2025c1bb86cdSEric Blake                                       int flags)
2026c1bb86cdSEric Blake {
2027c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
2028c1bb86cdSEric Blake }
2029c1bb86cdSEric Blake 
2030c1bb86cdSEric Blake static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
2031c1bb86cdSEric Blake                                        uint64_t bytes, QEMUIOVector *qiov,
2032c1bb86cdSEric Blake                                        int flags)
2033c1bb86cdSEric Blake {
2034c1bb86cdSEric Blake     assert(flags == 0);
2035c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
2036c1bb86cdSEric Blake }
2037c1bb86cdSEric Blake 
2038c1bb86cdSEric Blake static void raw_aio_plug(BlockDriverState *bs)
2039c1bb86cdSEric Blake {
2040c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2041c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2042c1bb86cdSEric Blake     if (s->use_linux_aio) {
2043c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2044c1bb86cdSEric Blake         laio_io_plug(bs, aio);
2045c1bb86cdSEric Blake     }
2046c1bb86cdSEric Blake #endif
2047c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2048c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2049c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2050c6447510SAarushi Mehta         luring_io_plug(bs, aio);
2051c6447510SAarushi Mehta     }
2052c6447510SAarushi Mehta #endif
2053c1bb86cdSEric Blake }
2054c1bb86cdSEric Blake 
2055c1bb86cdSEric Blake static void raw_aio_unplug(BlockDriverState *bs)
2056c1bb86cdSEric Blake {
2057c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2058c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2059c1bb86cdSEric Blake     if (s->use_linux_aio) {
2060c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2061c1bb86cdSEric Blake         laio_io_unplug(bs, aio);
2062c1bb86cdSEric Blake     }
2063c1bb86cdSEric Blake #endif
2064c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2065c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2066c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2067c6447510SAarushi Mehta         luring_io_unplug(bs, aio);
2068c6447510SAarushi Mehta     }
2069c6447510SAarushi Mehta #endif
2070c1bb86cdSEric Blake }
2071c1bb86cdSEric Blake 
207233d70fb6SKevin Wolf static int raw_co_flush_to_disk(BlockDriverState *bs)
2073c1bb86cdSEric Blake {
2074c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
207506dc9bd5SKevin Wolf     RawPosixAIOData acb;
207633d70fb6SKevin Wolf     int ret;
2077c1bb86cdSEric Blake 
207833d70fb6SKevin Wolf     ret = fd_open(bs);
207933d70fb6SKevin Wolf     if (ret < 0) {
208033d70fb6SKevin Wolf         return ret;
208133d70fb6SKevin Wolf     }
2082c1bb86cdSEric Blake 
208306dc9bd5SKevin Wolf     acb = (RawPosixAIOData) {
208406dc9bd5SKevin Wolf         .bs             = bs,
208506dc9bd5SKevin Wolf         .aio_fildes     = s->fd,
208606dc9bd5SKevin Wolf         .aio_type       = QEMU_AIO_FLUSH,
208706dc9bd5SKevin Wolf     };
208806dc9bd5SKevin Wolf 
2089c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2090c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2091c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2092c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2093c6447510SAarushi Mehta     }
2094c6447510SAarushi Mehta #endif
209506dc9bd5SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_flush, &acb);
2096c1bb86cdSEric Blake }
2097c1bb86cdSEric Blake 
2098ed6e2161SNishanth Aravamudan static void raw_aio_attach_aio_context(BlockDriverState *bs,
2099ed6e2161SNishanth Aravamudan                                        AioContext *new_context)
2100ed6e2161SNishanth Aravamudan {
2101c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2102ed6e2161SNishanth Aravamudan #ifdef CONFIG_LINUX_AIO
2103ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
2104cb09104eSMarkus Armbruster         Error *local_err = NULL;
2105ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(new_context, &local_err)) {
2106ed6e2161SNishanth Aravamudan             error_reportf_err(local_err, "Unable to use native AIO, "
2107ed6e2161SNishanth Aravamudan                                          "falling back to thread pool: ");
2108ed6e2161SNishanth Aravamudan             s->use_linux_aio = false;
2109ed6e2161SNishanth Aravamudan         }
2110ed6e2161SNishanth Aravamudan     }
2111ed6e2161SNishanth Aravamudan #endif
2112c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2113c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2114*cb8d0851SPan Nengyuan         Error *local_err = NULL;
2115c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2116c6447510SAarushi Mehta             error_reportf_err(local_err, "Unable to use linux io_uring, "
2117c6447510SAarushi Mehta                                          "falling back to thread pool: ");
2118c6447510SAarushi Mehta             s->use_linux_io_uring = false;
2119c6447510SAarushi Mehta         }
2120c6447510SAarushi Mehta     }
2121c6447510SAarushi Mehta #endif
2122ed6e2161SNishanth Aravamudan }
2123ed6e2161SNishanth Aravamudan 
2124c1bb86cdSEric Blake static void raw_close(BlockDriverState *bs)
2125c1bb86cdSEric Blake {
2126c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2127c1bb86cdSEric Blake 
2128c1bb86cdSEric Blake     if (s->fd >= 0) {
2129c1bb86cdSEric Blake         qemu_close(s->fd);
2130c1bb86cdSEric Blake         s->fd = -1;
2131c1bb86cdSEric Blake     }
2132c1bb86cdSEric Blake }
2133c1bb86cdSEric Blake 
2134d0bc9e5dSMax Reitz /**
2135d0bc9e5dSMax Reitz  * Truncates the given regular file @fd to @offset and, when growing, fills the
2136d0bc9e5dSMax Reitz  * new space according to @prealloc.
2137d0bc9e5dSMax Reitz  *
2138d0bc9e5dSMax Reitz  * Returns: 0 on success, -errno on failure.
2139d0bc9e5dSMax Reitz  */
214093f4e2ffSKevin Wolf static int coroutine_fn
214193f4e2ffSKevin Wolf raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
214293f4e2ffSKevin Wolf                      PreallocMode prealloc, Error **errp)
21439f63b07eSMax Reitz {
214429cb4c01SKevin Wolf     RawPosixAIOData acb;
2145d0bc9e5dSMax Reitz 
214629cb4c01SKevin Wolf     acb = (RawPosixAIOData) {
214793f4e2ffSKevin Wolf         .bs             = bs,
214893f4e2ffSKevin Wolf         .aio_fildes     = fd,
214993f4e2ffSKevin Wolf         .aio_type       = QEMU_AIO_TRUNCATE,
215093f4e2ffSKevin Wolf         .aio_offset     = offset,
2151d57c44d0SKevin Wolf         .truncate       = {
215293f4e2ffSKevin Wolf             .prealloc       = prealloc,
215393f4e2ffSKevin Wolf             .errp           = errp,
2154d57c44d0SKevin Wolf         },
215593f4e2ffSKevin Wolf     };
2156d0bc9e5dSMax Reitz 
215729cb4c01SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_truncate, &acb);
21589f63b07eSMax Reitz }
21599f63b07eSMax Reitz 
2160061ca8a3SKevin Wolf static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2161c80d8b06SMax Reitz                                         bool exact, PreallocMode prealloc,
216292b92799SKevin Wolf                                         BdrvRequestFlags flags, Error **errp)
2163c1bb86cdSEric Blake {
2164c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2165c1bb86cdSEric Blake     struct stat st;
2166f59adb32SMax Reitz     int ret;
2167c1bb86cdSEric Blake 
2168c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
2169f59adb32SMax Reitz         ret = -errno;
2170f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2171f59adb32SMax Reitz         return ret;
2172c1bb86cdSEric Blake     }
2173c1bb86cdSEric Blake 
2174c1bb86cdSEric Blake     if (S_ISREG(st.st_mode)) {
217582325ae5SMax Reitz         /* Always resizes to the exact @offset */
217693f4e2ffSKevin Wolf         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2177c1bb86cdSEric Blake     }
217835d72602SMax Reitz 
217935d72602SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
218035d72602SMax Reitz         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2181977c736fSMarkus Armbruster                    "non-regular file", PreallocMode_str(prealloc));
218235d72602SMax Reitz         return -ENOTSUP;
218335d72602SMax Reitz     }
218435d72602SMax Reitz 
218535d72602SMax Reitz     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
218682325ae5SMax Reitz         int64_t cur_length = raw_getlength(bs);
218782325ae5SMax Reitz 
218882325ae5SMax Reitz         if (offset != cur_length && exact) {
218982325ae5SMax Reitz             error_setg(errp, "Cannot resize device files");
219082325ae5SMax Reitz             return -ENOTSUP;
219182325ae5SMax Reitz         } else if (offset > cur_length) {
2192f59adb32SMax Reitz             error_setg(errp, "Cannot grow device files");
2193c1bb86cdSEric Blake             return -EINVAL;
2194c1bb86cdSEric Blake         }
2195c1bb86cdSEric Blake     } else {
2196f59adb32SMax Reitz         error_setg(errp, "Resizing this file is not supported");
2197c1bb86cdSEric Blake         return -ENOTSUP;
2198c1bb86cdSEric Blake     }
2199c1bb86cdSEric Blake 
2200c1bb86cdSEric Blake     return 0;
2201c1bb86cdSEric Blake }
2202c1bb86cdSEric Blake 
2203c1bb86cdSEric Blake #ifdef __OpenBSD__
2204c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2205c1bb86cdSEric Blake {
2206c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2207c1bb86cdSEric Blake     int fd = s->fd;
2208c1bb86cdSEric Blake     struct stat st;
2209c1bb86cdSEric Blake 
2210c1bb86cdSEric Blake     if (fstat(fd, &st))
2211c1bb86cdSEric Blake         return -errno;
2212c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2213c1bb86cdSEric Blake         struct disklabel dl;
2214c1bb86cdSEric Blake 
2215c1bb86cdSEric Blake         if (ioctl(fd, DIOCGDINFO, &dl))
2216c1bb86cdSEric Blake             return -errno;
2217c1bb86cdSEric Blake         return (uint64_t)dl.d_secsize *
2218c1bb86cdSEric Blake             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2219c1bb86cdSEric Blake     } else
2220c1bb86cdSEric Blake         return st.st_size;
2221c1bb86cdSEric Blake }
2222c1bb86cdSEric Blake #elif defined(__NetBSD__)
2223c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2224c1bb86cdSEric Blake {
2225c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2226c1bb86cdSEric Blake     int fd = s->fd;
2227c1bb86cdSEric Blake     struct stat st;
2228c1bb86cdSEric Blake 
2229c1bb86cdSEric Blake     if (fstat(fd, &st))
2230c1bb86cdSEric Blake         return -errno;
2231c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2232c1bb86cdSEric Blake         struct dkwedge_info dkw;
2233c1bb86cdSEric Blake 
2234c1bb86cdSEric Blake         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2235c1bb86cdSEric Blake             return dkw.dkw_size * 512;
2236c1bb86cdSEric Blake         } else {
2237c1bb86cdSEric Blake             struct disklabel dl;
2238c1bb86cdSEric Blake 
2239c1bb86cdSEric Blake             if (ioctl(fd, DIOCGDINFO, &dl))
2240c1bb86cdSEric Blake                 return -errno;
2241c1bb86cdSEric Blake             return (uint64_t)dl.d_secsize *
2242c1bb86cdSEric Blake                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2243c1bb86cdSEric Blake         }
2244c1bb86cdSEric Blake     } else
2245c1bb86cdSEric Blake         return st.st_size;
2246c1bb86cdSEric Blake }
2247c1bb86cdSEric Blake #elif defined(__sun__)
2248c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2249c1bb86cdSEric Blake {
2250c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2251c1bb86cdSEric Blake     struct dk_minfo minfo;
2252c1bb86cdSEric Blake     int ret;
2253c1bb86cdSEric Blake     int64_t size;
2254c1bb86cdSEric Blake 
2255c1bb86cdSEric Blake     ret = fd_open(bs);
2256c1bb86cdSEric Blake     if (ret < 0) {
2257c1bb86cdSEric Blake         return ret;
2258c1bb86cdSEric Blake     }
2259c1bb86cdSEric Blake 
2260c1bb86cdSEric Blake     /*
2261c1bb86cdSEric Blake      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2262c1bb86cdSEric Blake      */
2263c1bb86cdSEric Blake     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2264c1bb86cdSEric Blake     if (ret != -1) {
2265c1bb86cdSEric Blake         return minfo.dki_lbsize * minfo.dki_capacity;
2266c1bb86cdSEric Blake     }
2267c1bb86cdSEric Blake 
2268c1bb86cdSEric Blake     /*
2269c1bb86cdSEric Blake      * There are reports that lseek on some devices fails, but
2270c1bb86cdSEric Blake      * irc discussion said that contingency on contingency was overkill.
2271c1bb86cdSEric Blake      */
2272c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2273c1bb86cdSEric Blake     if (size < 0) {
2274c1bb86cdSEric Blake         return -errno;
2275c1bb86cdSEric Blake     }
2276c1bb86cdSEric Blake     return size;
2277c1bb86cdSEric Blake }
2278c1bb86cdSEric Blake #elif defined(CONFIG_BSD)
2279c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2280c1bb86cdSEric Blake {
2281c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2282c1bb86cdSEric Blake     int fd = s->fd;
2283c1bb86cdSEric Blake     int64_t size;
2284c1bb86cdSEric Blake     struct stat sb;
2285c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2286c1bb86cdSEric Blake     int reopened = 0;
2287c1bb86cdSEric Blake #endif
2288c1bb86cdSEric Blake     int ret;
2289c1bb86cdSEric Blake 
2290c1bb86cdSEric Blake     ret = fd_open(bs);
2291c1bb86cdSEric Blake     if (ret < 0)
2292c1bb86cdSEric Blake         return ret;
2293c1bb86cdSEric Blake 
2294c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2295c1bb86cdSEric Blake again:
2296c1bb86cdSEric Blake #endif
2297c1bb86cdSEric Blake     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2298c1bb86cdSEric Blake #ifdef DIOCGMEDIASIZE
2299c1bb86cdSEric Blake         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
2300c1bb86cdSEric Blake #elif defined(DIOCGPART)
2301c1bb86cdSEric Blake         {
2302c1bb86cdSEric Blake                 struct partinfo pi;
2303c1bb86cdSEric Blake                 if (ioctl(fd, DIOCGPART, &pi) == 0)
2304c1bb86cdSEric Blake                         size = pi.media_size;
2305c1bb86cdSEric Blake                 else
2306c1bb86cdSEric Blake                         size = 0;
2307c1bb86cdSEric Blake         }
2308c1bb86cdSEric Blake         if (size == 0)
2309c1bb86cdSEric Blake #endif
2310c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
2311c1bb86cdSEric Blake         {
2312c1bb86cdSEric Blake             uint64_t sectors = 0;
2313c1bb86cdSEric Blake             uint32_t sector_size = 0;
2314c1bb86cdSEric Blake 
2315c1bb86cdSEric Blake             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2316c1bb86cdSEric Blake                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2317c1bb86cdSEric Blake                 size = sectors * sector_size;
2318c1bb86cdSEric Blake             } else {
2319c1bb86cdSEric Blake                 size = lseek(fd, 0LL, SEEK_END);
2320c1bb86cdSEric Blake                 if (size < 0) {
2321c1bb86cdSEric Blake                     return -errno;
2322c1bb86cdSEric Blake                 }
2323c1bb86cdSEric Blake             }
2324c1bb86cdSEric Blake         }
2325c1bb86cdSEric Blake #else
2326c1bb86cdSEric Blake         size = lseek(fd, 0LL, SEEK_END);
2327c1bb86cdSEric Blake         if (size < 0) {
2328c1bb86cdSEric Blake             return -errno;
2329c1bb86cdSEric Blake         }
2330c1bb86cdSEric Blake #endif
2331c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2332c1bb86cdSEric Blake         switch(s->type) {
2333c1bb86cdSEric Blake         case FTYPE_CD:
2334c1bb86cdSEric Blake             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2335c1bb86cdSEric Blake             if (size == 2048LL * (unsigned)-1)
2336c1bb86cdSEric Blake                 size = 0;
2337c1bb86cdSEric Blake             /* XXX no disc?  maybe we need to reopen... */
2338c1bb86cdSEric Blake             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2339c1bb86cdSEric Blake                 reopened = 1;
2340c1bb86cdSEric Blake                 goto again;
2341c1bb86cdSEric Blake             }
2342c1bb86cdSEric Blake         }
2343c1bb86cdSEric Blake #endif
2344c1bb86cdSEric Blake     } else {
2345c1bb86cdSEric Blake         size = lseek(fd, 0, SEEK_END);
2346c1bb86cdSEric Blake         if (size < 0) {
2347c1bb86cdSEric Blake             return -errno;
2348c1bb86cdSEric Blake         }
2349c1bb86cdSEric Blake     }
2350c1bb86cdSEric Blake     return size;
2351c1bb86cdSEric Blake }
2352c1bb86cdSEric Blake #else
2353c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2354c1bb86cdSEric Blake {
2355c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2356c1bb86cdSEric Blake     int ret;
2357c1bb86cdSEric Blake     int64_t size;
2358c1bb86cdSEric Blake 
2359c1bb86cdSEric Blake     ret = fd_open(bs);
2360c1bb86cdSEric Blake     if (ret < 0) {
2361c1bb86cdSEric Blake         return ret;
2362c1bb86cdSEric Blake     }
2363c1bb86cdSEric Blake 
2364c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2365c1bb86cdSEric Blake     if (size < 0) {
2366c1bb86cdSEric Blake         return -errno;
2367c1bb86cdSEric Blake     }
2368c1bb86cdSEric Blake     return size;
2369c1bb86cdSEric Blake }
2370c1bb86cdSEric Blake #endif
2371c1bb86cdSEric Blake 
2372c1bb86cdSEric Blake static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
2373c1bb86cdSEric Blake {
2374c1bb86cdSEric Blake     struct stat st;
2375c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2376c1bb86cdSEric Blake 
2377c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
2378c1bb86cdSEric Blake         return -errno;
2379c1bb86cdSEric Blake     }
2380c1bb86cdSEric Blake     return (int64_t)st.st_blocks * 512;
2381c1bb86cdSEric Blake }
2382c1bb86cdSEric Blake 
238393f4e2ffSKevin Wolf static int coroutine_fn
238493f4e2ffSKevin Wolf raw_co_create(BlockdevCreateOptions *options, Error **errp)
2385c1bb86cdSEric Blake {
2386927f11e1SKevin Wolf     BlockdevCreateOptionsFile *file_opts;
23877c20c808SMax Reitz     Error *local_err = NULL;
2388c1bb86cdSEric Blake     int fd;
2389d815efcaSMax Reitz     uint64_t perm, shared;
2390c1bb86cdSEric Blake     int result = 0;
2391c1bb86cdSEric Blake 
2392927f11e1SKevin Wolf     /* Validate options and set default values */
2393927f11e1SKevin Wolf     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2394927f11e1SKevin Wolf     file_opts = &options->u.file;
2395c1bb86cdSEric Blake 
2396927f11e1SKevin Wolf     if (!file_opts->has_nocow) {
2397927f11e1SKevin Wolf         file_opts->nocow = false;
2398927f11e1SKevin Wolf     }
2399927f11e1SKevin Wolf     if (!file_opts->has_preallocation) {
2400927f11e1SKevin Wolf         file_opts->preallocation = PREALLOC_MODE_OFF;
2401c1bb86cdSEric Blake     }
2402ffa244c8SKevin Wolf     if (!file_opts->has_extent_size_hint) {
2403ffa244c8SKevin Wolf         file_opts->extent_size_hint = 1 * MiB;
2404ffa244c8SKevin Wolf     }
2405ffa244c8SKevin Wolf     if (file_opts->extent_size_hint > UINT32_MAX) {
2406ffa244c8SKevin Wolf         result = -EINVAL;
2407ffa244c8SKevin Wolf         error_setg(errp, "Extent size hint is too large");
2408ffa244c8SKevin Wolf         goto out;
2409ffa244c8SKevin Wolf     }
2410c1bb86cdSEric Blake 
2411927f11e1SKevin Wolf     /* Create file */
2412b18a24a9SDaniel P. Berrangé     fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
2413c1bb86cdSEric Blake     if (fd < 0) {
2414c1bb86cdSEric Blake         result = -errno;
2415c1bb86cdSEric Blake         goto out;
2416c1bb86cdSEric Blake     }
2417c1bb86cdSEric Blake 
2418b8cf1913SMax Reitz     /* Take permissions: We want to discard everything, so we need
2419b8cf1913SMax Reitz      * BLK_PERM_WRITE; and truncation to the desired size requires
2420b8cf1913SMax Reitz      * BLK_PERM_RESIZE.
2421b8cf1913SMax Reitz      * On the other hand, we cannot share the RESIZE permission
2422b8cf1913SMax Reitz      * because we promise that after this function, the file has the
2423b8cf1913SMax Reitz      * size given in the options.  If someone else were to resize it
2424b8cf1913SMax Reitz      * concurrently, we could not guarantee that.
2425b8cf1913SMax Reitz      * Note that after this function, we can no longer guarantee that
2426b8cf1913SMax Reitz      * the file is not touched by a third party, so it may be resized
2427b8cf1913SMax Reitz      * then. */
2428b8cf1913SMax Reitz     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2429b8cf1913SMax Reitz     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2430b8cf1913SMax Reitz 
2431b8cf1913SMax Reitz     /* Step one: Take locks */
24322996ffadSFam Zheng     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2433b8cf1913SMax Reitz     if (result < 0) {
2434b8cf1913SMax Reitz         goto out_close;
2435b8cf1913SMax Reitz     }
2436b8cf1913SMax Reitz 
2437b8cf1913SMax Reitz     /* Step two: Check that nobody else has taken conflicting locks */
2438b8cf1913SMax Reitz     result = raw_check_lock_bytes(fd, perm, shared, errp);
2439b8cf1913SMax Reitz     if (result < 0) {
2440b857431dSFam Zheng         error_append_hint(errp,
2441b857431dSFam Zheng                           "Is another process using the image [%s]?\n",
2442b857431dSFam Zheng                           file_opts->filename);
24437c20c808SMax Reitz         goto out_unlock;
2444b8cf1913SMax Reitz     }
2445b8cf1913SMax Reitz 
2446b8cf1913SMax Reitz     /* Clear the file by truncating it to 0 */
244793f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2448b8cf1913SMax Reitz     if (result < 0) {
24497c20c808SMax Reitz         goto out_unlock;
2450b8cf1913SMax Reitz     }
2451b8cf1913SMax Reitz 
2452927f11e1SKevin Wolf     if (file_opts->nocow) {
2453c1bb86cdSEric Blake #ifdef __linux__
2454c1bb86cdSEric Blake         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2455c1bb86cdSEric Blake          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2456c1bb86cdSEric Blake          * will be ignored since any failure of this operation should not
2457c1bb86cdSEric Blake          * block the left work.
2458c1bb86cdSEric Blake          */
2459c1bb86cdSEric Blake         int attr;
2460c1bb86cdSEric Blake         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2461c1bb86cdSEric Blake             attr |= FS_NOCOW_FL;
2462c1bb86cdSEric Blake             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2463c1bb86cdSEric Blake         }
2464c1bb86cdSEric Blake #endif
2465c1bb86cdSEric Blake     }
2466ffa244c8SKevin Wolf #ifdef FS_IOC_FSSETXATTR
2467ffa244c8SKevin Wolf     /*
2468ffa244c8SKevin Wolf      * Try to set the extent size hint. Failure is not fatal, and a warning is
2469ffa244c8SKevin Wolf      * only printed if the option was explicitly specified.
2470ffa244c8SKevin Wolf      */
2471ffa244c8SKevin Wolf     {
2472ffa244c8SKevin Wolf         struct fsxattr attr;
2473ffa244c8SKevin Wolf         result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2474ffa244c8SKevin Wolf         if (result == 0) {
2475ffa244c8SKevin Wolf             attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2476ffa244c8SKevin Wolf             attr.fsx_extsize = file_opts->extent_size_hint;
2477ffa244c8SKevin Wolf             result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2478ffa244c8SKevin Wolf         }
2479ffa244c8SKevin Wolf         if (result < 0 && file_opts->has_extent_size_hint &&
2480ffa244c8SKevin Wolf             file_opts->extent_size_hint)
2481ffa244c8SKevin Wolf         {
2482ffa244c8SKevin Wolf             warn_report("Failed to set extent size hint: %s",
2483ffa244c8SKevin Wolf                         strerror(errno));
2484ffa244c8SKevin Wolf         }
2485ffa244c8SKevin Wolf     }
2486ffa244c8SKevin Wolf #endif
2487c1bb86cdSEric Blake 
2488b8cf1913SMax Reitz     /* Resize and potentially preallocate the file to the desired
2489b8cf1913SMax Reitz      * final size */
249093f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, file_opts->size,
249193f4e2ffSKevin Wolf                                   file_opts->preallocation, errp);
24929f63b07eSMax Reitz     if (result < 0) {
24937c20c808SMax Reitz         goto out_unlock;
24947c20c808SMax Reitz     }
24957c20c808SMax Reitz 
24967c20c808SMax Reitz out_unlock:
24972996ffadSFam Zheng     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
24987c20c808SMax Reitz     if (local_err) {
24997c20c808SMax Reitz         /* The above call should not fail, and if it does, that does
25007c20c808SMax Reitz          * not mean the whole creation operation has failed.  So
25017c20c808SMax Reitz          * report it the user for their convenience, but do not report
25027c20c808SMax Reitz          * it to the caller. */
2503db0754dfSFam Zheng         warn_report_err(local_err);
25045a1dad9dSNir Soffer     }
25055a1dad9dSNir Soffer 
25065a1dad9dSNir Soffer out_close:
2507c1bb86cdSEric Blake     if (qemu_close(fd) != 0 && result == 0) {
2508c1bb86cdSEric Blake         result = -errno;
2509c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not close the new file");
2510c1bb86cdSEric Blake     }
2511c1bb86cdSEric Blake out:
2512c1bb86cdSEric Blake     return result;
2513c1bb86cdSEric Blake }
2514c1bb86cdSEric Blake 
2515b92902dfSMaxim Levitsky static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
2516b92902dfSMaxim Levitsky                                            const char *filename,
2517b92902dfSMaxim Levitsky                                            QemuOpts *opts,
2518927f11e1SKevin Wolf                                            Error **errp)
2519927f11e1SKevin Wolf {
2520927f11e1SKevin Wolf     BlockdevCreateOptions options;
2521927f11e1SKevin Wolf     int64_t total_size = 0;
2522ffa244c8SKevin Wolf     int64_t extent_size_hint = 0;
2523ffa244c8SKevin Wolf     bool has_extent_size_hint = false;
2524927f11e1SKevin Wolf     bool nocow = false;
2525927f11e1SKevin Wolf     PreallocMode prealloc;
2526927f11e1SKevin Wolf     char *buf = NULL;
2527927f11e1SKevin Wolf     Error *local_err = NULL;
2528927f11e1SKevin Wolf 
2529927f11e1SKevin Wolf     /* Skip file: protocol prefix */
2530927f11e1SKevin Wolf     strstart(filename, "file:", &filename);
2531927f11e1SKevin Wolf 
2532927f11e1SKevin Wolf     /* Read out options */
2533927f11e1SKevin Wolf     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2534927f11e1SKevin Wolf                           BDRV_SECTOR_SIZE);
2535ffa244c8SKevin Wolf     if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
2536ffa244c8SKevin Wolf         has_extent_size_hint = true;
2537ffa244c8SKevin Wolf         extent_size_hint =
2538ffa244c8SKevin Wolf             qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
2539ffa244c8SKevin Wolf     }
2540927f11e1SKevin Wolf     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2541927f11e1SKevin Wolf     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2542927f11e1SKevin Wolf     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2543927f11e1SKevin Wolf                                PREALLOC_MODE_OFF, &local_err);
2544927f11e1SKevin Wolf     g_free(buf);
2545927f11e1SKevin Wolf     if (local_err) {
2546927f11e1SKevin Wolf         error_propagate(errp, local_err);
2547927f11e1SKevin Wolf         return -EINVAL;
2548927f11e1SKevin Wolf     }
2549927f11e1SKevin Wolf 
2550927f11e1SKevin Wolf     options = (BlockdevCreateOptions) {
2551927f11e1SKevin Wolf         .driver     = BLOCKDEV_DRIVER_FILE,
2552927f11e1SKevin Wolf         .u.file     = {
2553927f11e1SKevin Wolf             .filename           = (char *) filename,
2554927f11e1SKevin Wolf             .size               = total_size,
2555927f11e1SKevin Wolf             .has_preallocation  = true,
2556927f11e1SKevin Wolf             .preallocation      = prealloc,
2557927f11e1SKevin Wolf             .has_nocow          = true,
2558927f11e1SKevin Wolf             .nocow              = nocow,
2559ffa244c8SKevin Wolf             .has_extent_size_hint = has_extent_size_hint,
2560ffa244c8SKevin Wolf             .extent_size_hint   = extent_size_hint,
2561927f11e1SKevin Wolf         },
2562927f11e1SKevin Wolf     };
2563927f11e1SKevin Wolf     return raw_co_create(&options, errp);
2564927f11e1SKevin Wolf }
2565927f11e1SKevin Wolf 
25669bffae14SDaniel Henrique Barboza static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
25679bffae14SDaniel Henrique Barboza                                            Error **errp)
25689bffae14SDaniel Henrique Barboza {
25699bffae14SDaniel Henrique Barboza     struct stat st;
25709bffae14SDaniel Henrique Barboza     int ret;
25719bffae14SDaniel Henrique Barboza 
25729bffae14SDaniel Henrique Barboza     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
25739bffae14SDaniel Henrique Barboza         error_setg_errno(errp, ENOENT, "%s is not a regular file",
25749bffae14SDaniel Henrique Barboza                          bs->filename);
25759bffae14SDaniel Henrique Barboza         return -ENOENT;
25769bffae14SDaniel Henrique Barboza     }
25779bffae14SDaniel Henrique Barboza 
25789bffae14SDaniel Henrique Barboza     ret = unlink(bs->filename);
25799bffae14SDaniel Henrique Barboza     if (ret < 0) {
25809bffae14SDaniel Henrique Barboza         ret = -errno;
25819bffae14SDaniel Henrique Barboza         error_setg_errno(errp, -ret, "Error when deleting file %s",
25829bffae14SDaniel Henrique Barboza                          bs->filename);
25839bffae14SDaniel Henrique Barboza     }
25849bffae14SDaniel Henrique Barboza 
25859bffae14SDaniel Henrique Barboza     return ret;
25869bffae14SDaniel Henrique Barboza }
25879bffae14SDaniel Henrique Barboza 
2588c1bb86cdSEric Blake /*
2589c1bb86cdSEric Blake  * Find allocation range in @bs around offset @start.
2590c1bb86cdSEric Blake  * May change underlying file descriptor's file offset.
2591c1bb86cdSEric Blake  * If @start is not in a hole, store @start in @data, and the
2592c1bb86cdSEric Blake  * beginning of the next hole in @hole, and return 0.
2593c1bb86cdSEric Blake  * If @start is in a non-trailing hole, store @start in @hole and the
2594c1bb86cdSEric Blake  * beginning of the next non-hole in @data, and return 0.
2595c1bb86cdSEric Blake  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2596c1bb86cdSEric Blake  * If we can't find out, return a negative errno other than -ENXIO.
2597c1bb86cdSEric Blake  */
2598c1bb86cdSEric Blake static int find_allocation(BlockDriverState *bs, off_t start,
2599c1bb86cdSEric Blake                            off_t *data, off_t *hole)
2600c1bb86cdSEric Blake {
2601c1bb86cdSEric Blake #if defined SEEK_HOLE && defined SEEK_DATA
2602c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2603c1bb86cdSEric Blake     off_t offs;
2604c1bb86cdSEric Blake 
2605c1bb86cdSEric Blake     /*
2606c1bb86cdSEric Blake      * SEEK_DATA cases:
2607c1bb86cdSEric Blake      * D1. offs == start: start is in data
2608c1bb86cdSEric Blake      * D2. offs > start: start is in a hole, next data at offs
2609c1bb86cdSEric Blake      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2610c1bb86cdSEric Blake      *                              or start is beyond EOF
2611c1bb86cdSEric Blake      *     If the latter happens, the file has been truncated behind
2612c1bb86cdSEric Blake      *     our back since we opened it.  All bets are off then.
2613c1bb86cdSEric Blake      *     Treating like a trailing hole is simplest.
2614c1bb86cdSEric Blake      * D4. offs < 0, errno != ENXIO: we learned nothing
2615c1bb86cdSEric Blake      */
2616c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_DATA);
2617c1bb86cdSEric Blake     if (offs < 0) {
2618c1bb86cdSEric Blake         return -errno;          /* D3 or D4 */
2619c1bb86cdSEric Blake     }
2620a03083a0SJeff Cody 
2621a03083a0SJeff Cody     if (offs < start) {
2622a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2623a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like D4. */
2624a03083a0SJeff Cody         return -EIO;
2625a03083a0SJeff Cody     }
2626c1bb86cdSEric Blake 
2627c1bb86cdSEric Blake     if (offs > start) {
2628c1bb86cdSEric Blake         /* D2: in hole, next data at offs */
2629c1bb86cdSEric Blake         *hole = start;
2630c1bb86cdSEric Blake         *data = offs;
2631c1bb86cdSEric Blake         return 0;
2632c1bb86cdSEric Blake     }
2633c1bb86cdSEric Blake 
2634c1bb86cdSEric Blake     /* D1: in data, end not yet known */
2635c1bb86cdSEric Blake 
2636c1bb86cdSEric Blake     /*
2637c1bb86cdSEric Blake      * SEEK_HOLE cases:
2638c1bb86cdSEric Blake      * H1. offs == start: start is in a hole
2639c1bb86cdSEric Blake      *     If this happens here, a hole has been dug behind our back
2640c1bb86cdSEric Blake      *     since the previous lseek().
2641c1bb86cdSEric Blake      * H2. offs > start: either start is in data, next hole at offs,
2642c1bb86cdSEric Blake      *                   or start is in trailing hole, EOF at offs
2643c1bb86cdSEric Blake      *     Linux treats trailing holes like any other hole: offs ==
2644c1bb86cdSEric Blake      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2645c1bb86cdSEric Blake      *     If that happens here, a hole has been dug behind our back
2646c1bb86cdSEric Blake      *     since the previous lseek().
2647c1bb86cdSEric Blake      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2648c1bb86cdSEric Blake      *     If this happens, the file has been truncated behind our
2649c1bb86cdSEric Blake      *     back since we opened it.  Treat it like a trailing hole.
2650c1bb86cdSEric Blake      * H4. offs < 0, errno != ENXIO: we learned nothing
2651c1bb86cdSEric Blake      *     Pretend we know nothing at all, i.e. "forget" about D1.
2652c1bb86cdSEric Blake      */
2653c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_HOLE);
2654c1bb86cdSEric Blake     if (offs < 0) {
2655c1bb86cdSEric Blake         return -errno;          /* D1 and (H3 or H4) */
2656c1bb86cdSEric Blake     }
2657a03083a0SJeff Cody 
2658a03083a0SJeff Cody     if (offs < start) {
2659a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2660a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like H4. */
2661a03083a0SJeff Cody         return -EIO;
2662a03083a0SJeff Cody     }
2663c1bb86cdSEric Blake 
2664c1bb86cdSEric Blake     if (offs > start) {
2665c1bb86cdSEric Blake         /*
2666c1bb86cdSEric Blake          * D1 and H2: either in data, next hole at offs, or it was in
2667c1bb86cdSEric Blake          * data but is now in a trailing hole.  In the latter case,
2668c1bb86cdSEric Blake          * all bets are off.  Treating it as if it there was data all
2669c1bb86cdSEric Blake          * the way to EOF is safe, so simply do that.
2670c1bb86cdSEric Blake          */
2671c1bb86cdSEric Blake         *data = start;
2672c1bb86cdSEric Blake         *hole = offs;
2673c1bb86cdSEric Blake         return 0;
2674c1bb86cdSEric Blake     }
2675c1bb86cdSEric Blake 
2676c1bb86cdSEric Blake     /* D1 and H1 */
2677c1bb86cdSEric Blake     return -EBUSY;
2678c1bb86cdSEric Blake #else
2679c1bb86cdSEric Blake     return -ENOTSUP;
2680c1bb86cdSEric Blake #endif
2681c1bb86cdSEric Blake }
2682c1bb86cdSEric Blake 
2683c1bb86cdSEric Blake /*
2684a290f085SEric Blake  * Returns the allocation status of the specified offset.
2685c1bb86cdSEric Blake  *
2686a290f085SEric Blake  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2687c1bb86cdSEric Blake  *
2688a290f085SEric Blake  * 'pnum' is set to the number of bytes (including and immediately following
2689a290f085SEric Blake  * the specified offset) that are known to be in the same
2690c1bb86cdSEric Blake  * allocated/unallocated state.
2691c1bb86cdSEric Blake  *
2692a290f085SEric Blake  * 'bytes' is the max value 'pnum' should be set to.
2693c1bb86cdSEric Blake  */
2694a290f085SEric Blake static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2695a290f085SEric Blake                                             bool want_zero,
2696a290f085SEric Blake                                             int64_t offset,
2697a290f085SEric Blake                                             int64_t bytes, int64_t *pnum,
2698a290f085SEric Blake                                             int64_t *map,
2699c1bb86cdSEric Blake                                             BlockDriverState **file)
2700c1bb86cdSEric Blake {
2701a290f085SEric Blake     off_t data = 0, hole = 0;
2702c1bb86cdSEric Blake     int ret;
2703c1bb86cdSEric Blake 
27049c3db310SMax Reitz     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
27059c3db310SMax Reitz 
2706c1bb86cdSEric Blake     ret = fd_open(bs);
2707c1bb86cdSEric Blake     if (ret < 0) {
2708c1bb86cdSEric Blake         return ret;
2709c1bb86cdSEric Blake     }
2710c1bb86cdSEric Blake 
2711a290f085SEric Blake     if (!want_zero) {
2712a290f085SEric Blake         *pnum = bytes;
2713a290f085SEric Blake         *map = offset;
2714a290f085SEric Blake         *file = bs;
2715a290f085SEric Blake         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2716c1bb86cdSEric Blake     }
2717c1bb86cdSEric Blake 
2718a290f085SEric Blake     ret = find_allocation(bs, offset, &data, &hole);
2719c1bb86cdSEric Blake     if (ret == -ENXIO) {
2720c1bb86cdSEric Blake         /* Trailing hole */
2721a290f085SEric Blake         *pnum = bytes;
2722c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2723c1bb86cdSEric Blake     } else if (ret < 0) {
2724c1bb86cdSEric Blake         /* No info available, so pretend there are no holes */
2725a290f085SEric Blake         *pnum = bytes;
2726c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2727a290f085SEric Blake     } else if (data == offset) {
2728a290f085SEric Blake         /* On a data extent, compute bytes to the end of the extent,
2729c1bb86cdSEric Blake          * possibly including a partial sector at EOF. */
2730a290f085SEric Blake         *pnum = MIN(bytes, hole - offset);
27319c3db310SMax Reitz 
27329c3db310SMax Reitz         /*
27339c3db310SMax Reitz          * We are not allowed to return partial sectors, though, so
27349c3db310SMax Reitz          * round up if necessary.
27359c3db310SMax Reitz          */
27369c3db310SMax Reitz         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
27379c3db310SMax Reitz             int64_t file_length = raw_getlength(bs);
27389c3db310SMax Reitz             if (file_length > 0) {
27399c3db310SMax Reitz                 /* Ignore errors, this is just a safeguard */
27409c3db310SMax Reitz                 assert(hole == file_length);
27419c3db310SMax Reitz             }
27429c3db310SMax Reitz             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
27439c3db310SMax Reitz         }
27449c3db310SMax Reitz 
2745c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2746c1bb86cdSEric Blake     } else {
2747a290f085SEric Blake         /* On a hole, compute bytes to the beginning of the next extent.  */
2748a290f085SEric Blake         assert(hole == offset);
2749a290f085SEric Blake         *pnum = MIN(bytes, data - offset);
2750c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2751c1bb86cdSEric Blake     }
2752a290f085SEric Blake     *map = offset;
2753c1bb86cdSEric Blake     *file = bs;
2754a290f085SEric Blake     return ret | BDRV_BLOCK_OFFSET_VALID;
2755c1bb86cdSEric Blake }
2756c1bb86cdSEric Blake 
275731be8a2aSStefan Hajnoczi #if defined(__linux__)
275831be8a2aSStefan Hajnoczi /* Verify that the file is not in the page cache */
275931be8a2aSStefan Hajnoczi static void check_cache_dropped(BlockDriverState *bs, Error **errp)
276031be8a2aSStefan Hajnoczi {
276131be8a2aSStefan Hajnoczi     const size_t window_size = 128 * 1024 * 1024;
276231be8a2aSStefan Hajnoczi     BDRVRawState *s = bs->opaque;
276331be8a2aSStefan Hajnoczi     void *window = NULL;
276431be8a2aSStefan Hajnoczi     size_t length = 0;
276531be8a2aSStefan Hajnoczi     unsigned char *vec;
276631be8a2aSStefan Hajnoczi     size_t page_size;
276731be8a2aSStefan Hajnoczi     off_t offset;
276831be8a2aSStefan Hajnoczi     off_t end;
276931be8a2aSStefan Hajnoczi 
277031be8a2aSStefan Hajnoczi     /* mincore(2) page status information requires 1 byte per page */
277131be8a2aSStefan Hajnoczi     page_size = sysconf(_SC_PAGESIZE);
277231be8a2aSStefan Hajnoczi     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
277331be8a2aSStefan Hajnoczi 
277431be8a2aSStefan Hajnoczi     end = raw_getlength(bs);
277531be8a2aSStefan Hajnoczi 
277631be8a2aSStefan Hajnoczi     for (offset = 0; offset < end; offset += window_size) {
277731be8a2aSStefan Hajnoczi         void *new_window;
277831be8a2aSStefan Hajnoczi         size_t new_length;
277931be8a2aSStefan Hajnoczi         size_t vec_end;
278031be8a2aSStefan Hajnoczi         size_t i;
278131be8a2aSStefan Hajnoczi         int ret;
278231be8a2aSStefan Hajnoczi 
278331be8a2aSStefan Hajnoczi         /* Unmap previous window if size has changed */
278431be8a2aSStefan Hajnoczi         new_length = MIN(end - offset, window_size);
278531be8a2aSStefan Hajnoczi         if (new_length != length) {
278631be8a2aSStefan Hajnoczi             munmap(window, length);
278731be8a2aSStefan Hajnoczi             window = NULL;
278831be8a2aSStefan Hajnoczi             length = 0;
278931be8a2aSStefan Hajnoczi         }
279031be8a2aSStefan Hajnoczi 
279131be8a2aSStefan Hajnoczi         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
279231be8a2aSStefan Hajnoczi                           s->fd, offset);
279331be8a2aSStefan Hajnoczi         if (new_window == MAP_FAILED) {
279431be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mmap failed");
279531be8a2aSStefan Hajnoczi             break;
279631be8a2aSStefan Hajnoczi         }
279731be8a2aSStefan Hajnoczi 
279831be8a2aSStefan Hajnoczi         window = new_window;
279931be8a2aSStefan Hajnoczi         length = new_length;
280031be8a2aSStefan Hajnoczi 
280131be8a2aSStefan Hajnoczi         ret = mincore(window, length, vec);
280231be8a2aSStefan Hajnoczi         if (ret < 0) {
280331be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mincore failed");
280431be8a2aSStefan Hajnoczi             break;
280531be8a2aSStefan Hajnoczi         }
280631be8a2aSStefan Hajnoczi 
280731be8a2aSStefan Hajnoczi         vec_end = DIV_ROUND_UP(length, page_size);
280831be8a2aSStefan Hajnoczi         for (i = 0; i < vec_end; i++) {
280931be8a2aSStefan Hajnoczi             if (vec[i] & 0x1) {
281031be8a2aSStefan Hajnoczi                 break;
281131be8a2aSStefan Hajnoczi             }
281231be8a2aSStefan Hajnoczi         }
281377ed971bSMarkus Armbruster         if (i < vec_end) {
281477ed971bSMarkus Armbruster             error_setg(errp, "page cache still in use!");
281577ed971bSMarkus Armbruster             break;
281677ed971bSMarkus Armbruster         }
281731be8a2aSStefan Hajnoczi     }
281831be8a2aSStefan Hajnoczi 
281931be8a2aSStefan Hajnoczi     if (window) {
282031be8a2aSStefan Hajnoczi         munmap(window, length);
282131be8a2aSStefan Hajnoczi     }
282231be8a2aSStefan Hajnoczi 
282331be8a2aSStefan Hajnoczi     g_free(vec);
282431be8a2aSStefan Hajnoczi }
282531be8a2aSStefan Hajnoczi #endif /* __linux__ */
282631be8a2aSStefan Hajnoczi 
2827dd577a26SStefan Hajnoczi static void coroutine_fn raw_co_invalidate_cache(BlockDriverState *bs,
2828dd577a26SStefan Hajnoczi                                                  Error **errp)
2829dd577a26SStefan Hajnoczi {
2830dd577a26SStefan Hajnoczi     BDRVRawState *s = bs->opaque;
2831dd577a26SStefan Hajnoczi     int ret;
2832dd577a26SStefan Hajnoczi 
2833dd577a26SStefan Hajnoczi     ret = fd_open(bs);
2834dd577a26SStefan Hajnoczi     if (ret < 0) {
2835dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "The file descriptor is not open");
2836dd577a26SStefan Hajnoczi         return;
2837dd577a26SStefan Hajnoczi     }
2838dd577a26SStefan Hajnoczi 
2839f357fcd8SStefan Hajnoczi     if (!s->drop_cache) {
2840f357fcd8SStefan Hajnoczi         return;
2841f357fcd8SStefan Hajnoczi     }
2842f357fcd8SStefan Hajnoczi 
2843dd577a26SStefan Hajnoczi     if (s->open_flags & O_DIRECT) {
2844dd577a26SStefan Hajnoczi         return; /* No host kernel page cache */
2845dd577a26SStefan Hajnoczi     }
2846dd577a26SStefan Hajnoczi 
2847dd577a26SStefan Hajnoczi #if defined(__linux__)
2848dd577a26SStefan Hajnoczi     /* This sets the scene for the next syscall... */
2849dd577a26SStefan Hajnoczi     ret = bdrv_co_flush(bs);
2850dd577a26SStefan Hajnoczi     if (ret < 0) {
2851dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "flush failed");
2852dd577a26SStefan Hajnoczi         return;
2853dd577a26SStefan Hajnoczi     }
2854dd577a26SStefan Hajnoczi 
2855dd577a26SStefan Hajnoczi     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2856dd577a26SStefan Hajnoczi      * process.  These limitations are okay because we just fsynced the file,
2857dd577a26SStefan Hajnoczi      * we don't use mmap, and the file should not be in use by other processes.
2858dd577a26SStefan Hajnoczi      */
2859dd577a26SStefan Hajnoczi     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2860dd577a26SStefan Hajnoczi     if (ret != 0) { /* the return value is a positive errno */
2861dd577a26SStefan Hajnoczi         error_setg_errno(errp, ret, "fadvise failed");
2862dd577a26SStefan Hajnoczi         return;
2863dd577a26SStefan Hajnoczi     }
286431be8a2aSStefan Hajnoczi 
286531be8a2aSStefan Hajnoczi     if (s->check_cache_dropped) {
286631be8a2aSStefan Hajnoczi         check_cache_dropped(bs, errp);
286731be8a2aSStefan Hajnoczi     }
2868dd577a26SStefan Hajnoczi #else /* __linux__ */
2869dd577a26SStefan Hajnoczi     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2870dd577a26SStefan Hajnoczi      * unsupported on other host operating systems.  Cache consistency issues
2871dd577a26SStefan Hajnoczi      * may occur but no error is reported here, partly because that's the
2872dd577a26SStefan Hajnoczi      * historical behavior and partly because it's hard to differentiate valid
2873dd577a26SStefan Hajnoczi      * configurations that should not cause errors.
2874dd577a26SStefan Hajnoczi      */
2875dd577a26SStefan Hajnoczi #endif /* !__linux__ */
2876dd577a26SStefan Hajnoczi }
2877dd577a26SStefan Hajnoczi 
28781c450366SAnton Nefedov static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
28791c450366SAnton Nefedov {
28801c450366SAnton Nefedov     if (ret) {
28811c450366SAnton Nefedov         s->stats.discard_nb_failed++;
28821c450366SAnton Nefedov     } else {
28831c450366SAnton Nefedov         s->stats.discard_nb_ok++;
28841c450366SAnton Nefedov         s->stats.discard_bytes_ok += nbytes;
28851c450366SAnton Nefedov     }
28861c450366SAnton Nefedov }
28871c450366SAnton Nefedov 
288833d70fb6SKevin Wolf static coroutine_fn int
288946ee0f46SKevin Wolf raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int bytes, bool blkdev)
2890c1bb86cdSEric Blake {
2891c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
289246ee0f46SKevin Wolf     RawPosixAIOData acb;
28931c450366SAnton Nefedov     int ret;
2894c1bb86cdSEric Blake 
289546ee0f46SKevin Wolf     acb = (RawPosixAIOData) {
289646ee0f46SKevin Wolf         .bs             = bs,
289746ee0f46SKevin Wolf         .aio_fildes     = s->fd,
289846ee0f46SKevin Wolf         .aio_type       = QEMU_AIO_DISCARD,
289946ee0f46SKevin Wolf         .aio_offset     = offset,
290046ee0f46SKevin Wolf         .aio_nbytes     = bytes,
290146ee0f46SKevin Wolf     };
290246ee0f46SKevin Wolf 
290346ee0f46SKevin Wolf     if (blkdev) {
290446ee0f46SKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
290546ee0f46SKevin Wolf     }
290646ee0f46SKevin Wolf 
29071c450366SAnton Nefedov     ret = raw_thread_pool_submit(bs, handle_aiocb_discard, &acb);
29081c450366SAnton Nefedov     raw_account_discard(s, bytes, ret);
29091c450366SAnton Nefedov     return ret;
291046ee0f46SKevin Wolf }
291146ee0f46SKevin Wolf 
291246ee0f46SKevin Wolf static coroutine_fn int
291346ee0f46SKevin Wolf raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
291446ee0f46SKevin Wolf {
291546ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, false);
2916c1bb86cdSEric Blake }
2917c1bb86cdSEric Blake 
29187154d8aeSKevin Wolf static int coroutine_fn
29197154d8aeSKevin Wolf raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int bytes,
29207154d8aeSKevin Wolf                      BdrvRequestFlags flags, bool blkdev)
29217154d8aeSKevin Wolf {
29227154d8aeSKevin Wolf     BDRVRawState *s = bs->opaque;
29237154d8aeSKevin Wolf     RawPosixAIOData acb;
29247154d8aeSKevin Wolf     ThreadPoolFunc *handler;
29257154d8aeSKevin Wolf 
2926292d06b9SMax Reitz #ifdef CONFIG_FALLOCATE
2927292d06b9SMax Reitz     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2928292d06b9SMax Reitz         BdrvTrackedRequest *req;
2929292d06b9SMax Reitz 
2930292d06b9SMax Reitz         /*
2931292d06b9SMax Reitz          * This is a workaround for a bug in the Linux XFS driver,
2932292d06b9SMax Reitz          * where writes submitted through the AIO interface will be
2933292d06b9SMax Reitz          * discarded if they happen beyond a concurrently running
2934292d06b9SMax Reitz          * fallocate() that increases the file length (i.e., both the
2935292d06b9SMax Reitz          * write and the fallocate() happen beyond the EOF).
2936292d06b9SMax Reitz          *
2937292d06b9SMax Reitz          * To work around it, we extend the tracked request for this
2938292d06b9SMax Reitz          * zero write until INT64_MAX (effectively infinity), and mark
2939292d06b9SMax Reitz          * it as serializing.
2940292d06b9SMax Reitz          *
2941292d06b9SMax Reitz          * We have to enable this workaround for all filesystems and
2942292d06b9SMax Reitz          * AIO modes (not just XFS with aio=native), because for
2943292d06b9SMax Reitz          * remote filesystems we do not know the host configuration.
2944292d06b9SMax Reitz          */
2945292d06b9SMax Reitz 
2946292d06b9SMax Reitz         req = bdrv_co_get_self_request(bs);
2947292d06b9SMax Reitz         assert(req);
2948292d06b9SMax Reitz         assert(req->type == BDRV_TRACKED_WRITE);
2949292d06b9SMax Reitz         assert(req->offset <= offset);
2950292d06b9SMax Reitz         assert(req->offset + req->bytes >= offset + bytes);
2951292d06b9SMax Reitz 
29528b117001SVladimir Sementsov-Ogievskiy         req->bytes = BDRV_MAX_LENGTH - req->offset;
29538b117001SVladimir Sementsov-Ogievskiy 
29548b117001SVladimir Sementsov-Ogievskiy         assert(bdrv_check_request(req->offset, req->bytes) == 0);
2955292d06b9SMax Reitz 
2956292d06b9SMax Reitz         bdrv_mark_request_serialising(req, bs->bl.request_alignment);
2957292d06b9SMax Reitz     }
2958292d06b9SMax Reitz #endif
2959292d06b9SMax Reitz 
29607154d8aeSKevin Wolf     acb = (RawPosixAIOData) {
29617154d8aeSKevin Wolf         .bs             = bs,
29627154d8aeSKevin Wolf         .aio_fildes     = s->fd,
29637154d8aeSKevin Wolf         .aio_type       = QEMU_AIO_WRITE_ZEROES,
29647154d8aeSKevin Wolf         .aio_offset     = offset,
29657154d8aeSKevin Wolf         .aio_nbytes     = bytes,
29667154d8aeSKevin Wolf     };
29677154d8aeSKevin Wolf 
29687154d8aeSKevin Wolf     if (blkdev) {
29697154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
29707154d8aeSKevin Wolf     }
2971738301e1SKevin Wolf     if (flags & BDRV_REQ_NO_FALLBACK) {
2972738301e1SKevin Wolf         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
2973738301e1SKevin Wolf     }
29747154d8aeSKevin Wolf 
29757154d8aeSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
29767154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_DISCARD;
29777154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes_unmap;
29787154d8aeSKevin Wolf     } else {
29797154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes;
29807154d8aeSKevin Wolf     }
29817154d8aeSKevin Wolf 
29827154d8aeSKevin Wolf     return raw_thread_pool_submit(bs, handler, &acb);
29837154d8aeSKevin Wolf }
29847154d8aeSKevin Wolf 
2985c1bb86cdSEric Blake static int coroutine_fn raw_co_pwrite_zeroes(
2986c1bb86cdSEric Blake     BlockDriverState *bs, int64_t offset,
2987f5a5ca79SManos Pitsidianakis     int bytes, BdrvRequestFlags flags)
2988c1bb86cdSEric Blake {
29897154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
2990c1bb86cdSEric Blake }
2991c1bb86cdSEric Blake 
2992c1bb86cdSEric Blake static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2993c1bb86cdSEric Blake {
2994c1bb86cdSEric Blake     return 0;
2995c1bb86cdSEric Blake }
2996c1bb86cdSEric Blake 
2997d9245599SAnton Nefedov static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
2998d9245599SAnton Nefedov {
2999d9245599SAnton Nefedov     BDRVRawState *s = bs->opaque;
3000d9245599SAnton Nefedov     return (BlockStatsSpecificFile) {
3001d9245599SAnton Nefedov         .discard_nb_ok = s->stats.discard_nb_ok,
3002d9245599SAnton Nefedov         .discard_nb_failed = s->stats.discard_nb_failed,
3003d9245599SAnton Nefedov         .discard_bytes_ok = s->stats.discard_bytes_ok,
3004d9245599SAnton Nefedov     };
3005d9245599SAnton Nefedov }
3006d9245599SAnton Nefedov 
3007d9245599SAnton Nefedov static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3008d9245599SAnton Nefedov {
3009d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3010d9245599SAnton Nefedov 
3011d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_FILE;
3012d9245599SAnton Nefedov     stats->u.file = get_blockstats_specific_file(bs);
3013d9245599SAnton Nefedov 
3014d9245599SAnton Nefedov     return stats;
3015d9245599SAnton Nefedov }
3016d9245599SAnton Nefedov 
3017d9245599SAnton Nefedov static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3018d9245599SAnton Nefedov {
3019d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3020d9245599SAnton Nefedov 
3021d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3022d9245599SAnton Nefedov     stats->u.host_device = get_blockstats_specific_file(bs);
3023d9245599SAnton Nefedov 
3024d9245599SAnton Nefedov     return stats;
3025d9245599SAnton Nefedov }
3026d9245599SAnton Nefedov 
3027c1bb86cdSEric Blake static QemuOptsList raw_create_opts = {
3028c1bb86cdSEric Blake     .name = "raw-create-opts",
3029c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3030c1bb86cdSEric Blake     .desc = {
3031c1bb86cdSEric Blake         {
3032c1bb86cdSEric Blake             .name = BLOCK_OPT_SIZE,
3033c1bb86cdSEric Blake             .type = QEMU_OPT_SIZE,
3034c1bb86cdSEric Blake             .help = "Virtual disk size"
3035c1bb86cdSEric Blake         },
3036c1bb86cdSEric Blake         {
3037c1bb86cdSEric Blake             .name = BLOCK_OPT_NOCOW,
3038c1bb86cdSEric Blake             .type = QEMU_OPT_BOOL,
3039c1bb86cdSEric Blake             .help = "Turn off copy-on-write (valid only on btrfs)"
3040c1bb86cdSEric Blake         },
3041c1bb86cdSEric Blake         {
3042c1bb86cdSEric Blake             .name = BLOCK_OPT_PREALLOC,
3043c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
3044abea0053SStefano Garzarella             .help = "Preallocation mode (allowed values: off"
3045abea0053SStefano Garzarella #ifdef CONFIG_POSIX_FALLOCATE
3046abea0053SStefano Garzarella                     ", falloc"
3047abea0053SStefano Garzarella #endif
3048abea0053SStefano Garzarella                     ", full)"
3049c1bb86cdSEric Blake         },
3050ffa244c8SKevin Wolf         {
3051ffa244c8SKevin Wolf             .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3052ffa244c8SKevin Wolf             .type = QEMU_OPT_SIZE,
3053ffa244c8SKevin Wolf             .help = "Extent size hint for the image file, 0 to disable"
3054ffa244c8SKevin Wolf         },
3055c1bb86cdSEric Blake         { /* end of list */ }
3056c1bb86cdSEric Blake     }
3057c1bb86cdSEric Blake };
3058c1bb86cdSEric Blake 
3059244a5668SFam Zheng static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3060244a5668SFam Zheng                           Error **errp)
3061244a5668SFam Zheng {
30626ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
30636ceabe6fSKevin Wolf     BDRVRawReopenState *rs = NULL;
30646ceabe6fSKevin Wolf     int open_flags;
30656ceabe6fSKevin Wolf     int ret;
30666ceabe6fSKevin Wolf 
30676ceabe6fSKevin Wolf     if (s->perm_change_fd) {
30686ceabe6fSKevin Wolf         /*
30696ceabe6fSKevin Wolf          * In the context of reopen, this function may be called several times
30706ceabe6fSKevin Wolf          * (directly and recursively while change permissions of the parent).
30716ceabe6fSKevin Wolf          * This is even true for children that don't inherit from the original
30726ceabe6fSKevin Wolf          * reopen node, so s->reopen_state is not set.
30736ceabe6fSKevin Wolf          *
30746ceabe6fSKevin Wolf          * Ignore all but the first call.
30756ceabe6fSKevin Wolf          */
30766ceabe6fSKevin Wolf         return 0;
30776ceabe6fSKevin Wolf     }
30786ceabe6fSKevin Wolf 
30796ceabe6fSKevin Wolf     if (s->reopen_state) {
30806ceabe6fSKevin Wolf         /* We already have a new file descriptor to set permissions for */
30816ceabe6fSKevin Wolf         assert(s->reopen_state->perm == perm);
30826ceabe6fSKevin Wolf         assert(s->reopen_state->shared_perm == shared);
30836ceabe6fSKevin Wolf         rs = s->reopen_state->opaque;
30846ceabe6fSKevin Wolf         s->perm_change_fd = rs->fd;
3085094e3639SMax Reitz         s->perm_change_flags = rs->open_flags;
30866ceabe6fSKevin Wolf     } else {
30876ceabe6fSKevin Wolf         /* We may need a new fd if auto-read-only switches the mode */
308823dece19SKevin Wolf         ret = raw_reconfigure_getfd(bs, bs->open_flags, &open_flags, perm,
30896ceabe6fSKevin Wolf                                     false, errp);
30906ceabe6fSKevin Wolf         if (ret < 0) {
30916ceabe6fSKevin Wolf             return ret;
30926ceabe6fSKevin Wolf         } else if (ret != s->fd) {
30936ceabe6fSKevin Wolf             s->perm_change_fd = ret;
3094094e3639SMax Reitz             s->perm_change_flags = open_flags;
30956ceabe6fSKevin Wolf         }
30966ceabe6fSKevin Wolf     }
30976ceabe6fSKevin Wolf 
30986ceabe6fSKevin Wolf     /* Prepare permissions on old fd to avoid conflicts between old and new,
30996ceabe6fSKevin Wolf      * but keep everything locked that new will need. */
31006ceabe6fSKevin Wolf     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
31016ceabe6fSKevin Wolf     if (ret < 0) {
31026ceabe6fSKevin Wolf         goto fail;
31036ceabe6fSKevin Wolf     }
31046ceabe6fSKevin Wolf 
31056ceabe6fSKevin Wolf     /* Copy locks to the new fd */
3106eb43ea16SLi Feng     if (s->perm_change_fd && s->use_lock) {
31076ceabe6fSKevin Wolf         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
31086ceabe6fSKevin Wolf                                    false, errp);
31096ceabe6fSKevin Wolf         if (ret < 0) {
31106ceabe6fSKevin Wolf             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
31116ceabe6fSKevin Wolf             goto fail;
31126ceabe6fSKevin Wolf         }
31136ceabe6fSKevin Wolf     }
31146ceabe6fSKevin Wolf     return 0;
31156ceabe6fSKevin Wolf 
31166ceabe6fSKevin Wolf fail:
31176ceabe6fSKevin Wolf     if (s->perm_change_fd && !s->reopen_state) {
31186ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
31196ceabe6fSKevin Wolf     }
31206ceabe6fSKevin Wolf     s->perm_change_fd = 0;
31216ceabe6fSKevin Wolf     return ret;
3122244a5668SFam Zheng }
3123244a5668SFam Zheng 
3124244a5668SFam Zheng static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3125244a5668SFam Zheng {
3126244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
31276ceabe6fSKevin Wolf 
31286ceabe6fSKevin Wolf     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
31296ceabe6fSKevin Wolf      * called after .bdrv_reopen_commit) */
31306ceabe6fSKevin Wolf     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
31316ceabe6fSKevin Wolf         qemu_close(s->fd);
31326ceabe6fSKevin Wolf         s->fd = s->perm_change_fd;
3133094e3639SMax Reitz         s->open_flags = s->perm_change_flags;
31346ceabe6fSKevin Wolf     }
31356ceabe6fSKevin Wolf     s->perm_change_fd = 0;
31366ceabe6fSKevin Wolf 
3137244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3138244a5668SFam Zheng     s->perm = perm;
3139244a5668SFam Zheng     s->shared_perm = shared;
3140244a5668SFam Zheng }
3141244a5668SFam Zheng 
3142244a5668SFam Zheng static void raw_abort_perm_update(BlockDriverState *bs)
3143244a5668SFam Zheng {
31446ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
31456ceabe6fSKevin Wolf 
31466ceabe6fSKevin Wolf     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
31476ceabe6fSKevin Wolf      * the file descriptor. */
31486ceabe6fSKevin Wolf     if (s->perm_change_fd && !s->reopen_state) {
31496ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
31506ceabe6fSKevin Wolf     }
31516ceabe6fSKevin Wolf     s->perm_change_fd = 0;
31526ceabe6fSKevin Wolf 
3153244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3154244a5668SFam Zheng }
3155244a5668SFam Zheng 
315667b51fb9SVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_copy_range_from(
315767b51fb9SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, BdrvChild *src, uint64_t src_offset,
315867b51fb9SVladimir Sementsov-Ogievskiy         BdrvChild *dst, uint64_t dst_offset, uint64_t bytes,
315967b51fb9SVladimir Sementsov-Ogievskiy         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
31601efad060SFam Zheng {
316167b51fb9SVladimir Sementsov-Ogievskiy     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
316267b51fb9SVladimir Sementsov-Ogievskiy                                  read_flags, write_flags);
31631efad060SFam Zheng }
31641efad060SFam Zheng 
31651efad060SFam Zheng static int coroutine_fn raw_co_copy_range_to(BlockDriverState *bs,
316667b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *src,
316767b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t src_offset,
316867b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *dst,
316967b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t dst_offset,
317067b51fb9SVladimir Sementsov-Ogievskiy                                              uint64_t bytes,
317167b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags read_flags,
317267b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags write_flags)
31731efad060SFam Zheng {
317458a209c4SKevin Wolf     RawPosixAIOData acb;
31751efad060SFam Zheng     BDRVRawState *s = bs->opaque;
31761efad060SFam Zheng     BDRVRawState *src_s;
31771efad060SFam Zheng 
31781efad060SFam Zheng     assert(dst->bs == bs);
31791efad060SFam Zheng     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
31801efad060SFam Zheng         return -ENOTSUP;
31811efad060SFam Zheng     }
31821efad060SFam Zheng 
31831efad060SFam Zheng     src_s = src->bs->opaque;
31849f850f67SFam Zheng     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
31851efad060SFam Zheng         return -EIO;
31861efad060SFam Zheng     }
318758a209c4SKevin Wolf 
318858a209c4SKevin Wolf     acb = (RawPosixAIOData) {
318958a209c4SKevin Wolf         .bs             = bs,
319058a209c4SKevin Wolf         .aio_type       = QEMU_AIO_COPY_RANGE,
319158a209c4SKevin Wolf         .aio_fildes     = src_s->fd,
319258a209c4SKevin Wolf         .aio_offset     = src_offset,
319358a209c4SKevin Wolf         .aio_nbytes     = bytes,
319458a209c4SKevin Wolf         .copy_range     = {
319558a209c4SKevin Wolf             .aio_fd2        = s->fd,
319658a209c4SKevin Wolf             .aio_offset2    = dst_offset,
319758a209c4SKevin Wolf         },
319858a209c4SKevin Wolf     };
319958a209c4SKevin Wolf 
320058a209c4SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_copy_range, &acb);
32011efad060SFam Zheng }
32021efad060SFam Zheng 
3203c1bb86cdSEric Blake BlockDriver bdrv_file = {
3204c1bb86cdSEric Blake     .format_name = "file",
3205c1bb86cdSEric Blake     .protocol_name = "file",
3206c1bb86cdSEric Blake     .instance_size = sizeof(BDRVRawState),
3207c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3208c1bb86cdSEric Blake     .bdrv_probe = NULL, /* no probe for protocols */
3209c1bb86cdSEric Blake     .bdrv_parse_filename = raw_parse_filename,
3210c1bb86cdSEric Blake     .bdrv_file_open = raw_open,
3211c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3212c1bb86cdSEric Blake     .bdrv_reopen_commit = raw_reopen_commit,
3213c1bb86cdSEric Blake     .bdrv_reopen_abort = raw_reopen_abort,
3214c1bb86cdSEric Blake     .bdrv_close = raw_close,
3215927f11e1SKevin Wolf     .bdrv_co_create = raw_co_create,
3216efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = raw_co_create_opts,
3217c1bb86cdSEric Blake     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3218a290f085SEric Blake     .bdrv_co_block_status = raw_co_block_status,
3219dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3220c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
32219bffae14SDaniel Henrique Barboza     .bdrv_co_delete_file = raw_co_delete_file,
3222c1bb86cdSEric Blake 
3223c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3224c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
322533d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
322633d70fb6SKevin Wolf     .bdrv_co_pdiscard       = raw_co_pdiscard,
32271efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
32281efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3229c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3230c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3231c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3232ed6e2161SNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3233c1bb86cdSEric Blake 
3234061ca8a3SKevin Wolf     .bdrv_co_truncate = raw_co_truncate,
3235c1bb86cdSEric Blake     .bdrv_getlength = raw_getlength,
3236c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3237c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3238c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3239d9245599SAnton Nefedov     .bdrv_get_specific_stats = raw_get_specific_stats,
3240244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3241244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3242244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3243c1bb86cdSEric Blake     .create_opts = &raw_create_opts,
32448a2ce0bcSAlberto Garcia     .mutable_opts = mutable_opts,
3245c1bb86cdSEric Blake };
3246c1bb86cdSEric Blake 
3247c1bb86cdSEric Blake /***********************************************/
3248c1bb86cdSEric Blake /* host device */
3249c1bb86cdSEric Blake 
3250c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3251c1bb86cdSEric Blake static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3252c1bb86cdSEric Blake                                 CFIndex maxPathSize, int flags);
3253c1bb86cdSEric Blake static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3254c1bb86cdSEric Blake {
3255c1bb86cdSEric Blake     kern_return_t kernResult = KERN_FAILURE;
3256c1bb86cdSEric Blake     mach_port_t     masterPort;
3257c1bb86cdSEric Blake     CFMutableDictionaryRef  classesToMatch;
3258c1bb86cdSEric Blake     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3259c1bb86cdSEric Blake     char *mediaType = NULL;
3260c1bb86cdSEric Blake 
3261c1bb86cdSEric Blake     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
3262c1bb86cdSEric Blake     if ( KERN_SUCCESS != kernResult ) {
3263c1bb86cdSEric Blake         printf( "IOMasterPort returned %d\n", kernResult );
3264c1bb86cdSEric Blake     }
3265c1bb86cdSEric Blake 
3266c1bb86cdSEric Blake     int index;
3267c1bb86cdSEric Blake     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3268c1bb86cdSEric Blake         classesToMatch = IOServiceMatching(matching_array[index]);
3269c1bb86cdSEric Blake         if (classesToMatch == NULL) {
3270c1bb86cdSEric Blake             error_report("IOServiceMatching returned NULL for %s",
3271c1bb86cdSEric Blake                          matching_array[index]);
3272c1bb86cdSEric Blake             continue;
3273c1bb86cdSEric Blake         }
3274c1bb86cdSEric Blake         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3275c1bb86cdSEric Blake                              kCFBooleanTrue);
3276c1bb86cdSEric Blake         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
3277c1bb86cdSEric Blake                                                   mediaIterator);
3278c1bb86cdSEric Blake         if (kernResult != KERN_SUCCESS) {
3279c1bb86cdSEric Blake             error_report("Note: IOServiceGetMatchingServices returned %d",
3280c1bb86cdSEric Blake                          kernResult);
3281c1bb86cdSEric Blake             continue;
3282c1bb86cdSEric Blake         }
3283c1bb86cdSEric Blake 
3284c1bb86cdSEric Blake         /* If a match was found, leave the loop */
3285c1bb86cdSEric Blake         if (*mediaIterator != 0) {
32864f7d28d7SLaurent Vivier             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3287c1bb86cdSEric Blake             mediaType = g_strdup(matching_array[index]);
3288c1bb86cdSEric Blake             break;
3289c1bb86cdSEric Blake         }
3290c1bb86cdSEric Blake     }
3291c1bb86cdSEric Blake     return mediaType;
3292c1bb86cdSEric Blake }
3293c1bb86cdSEric Blake 
3294c1bb86cdSEric Blake kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3295c1bb86cdSEric Blake                          CFIndex maxPathSize, int flags)
3296c1bb86cdSEric Blake {
3297c1bb86cdSEric Blake     io_object_t     nextMedia;
3298c1bb86cdSEric Blake     kern_return_t   kernResult = KERN_FAILURE;
3299c1bb86cdSEric Blake     *bsdPath = '\0';
3300c1bb86cdSEric Blake     nextMedia = IOIteratorNext( mediaIterator );
3301c1bb86cdSEric Blake     if ( nextMedia )
3302c1bb86cdSEric Blake     {
3303c1bb86cdSEric Blake         CFTypeRef   bsdPathAsCFString;
3304c1bb86cdSEric Blake     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3305c1bb86cdSEric Blake         if ( bsdPathAsCFString ) {
3306c1bb86cdSEric Blake             size_t devPathLength;
3307c1bb86cdSEric Blake             strcpy( bsdPath, _PATH_DEV );
3308c1bb86cdSEric Blake             if (flags & BDRV_O_NOCACHE) {
3309c1bb86cdSEric Blake                 strcat(bsdPath, "r");
3310c1bb86cdSEric Blake             }
3311c1bb86cdSEric Blake             devPathLength = strlen( bsdPath );
3312c1bb86cdSEric Blake             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3313c1bb86cdSEric Blake                 kernResult = KERN_SUCCESS;
3314c1bb86cdSEric Blake             }
3315c1bb86cdSEric Blake             CFRelease( bsdPathAsCFString );
3316c1bb86cdSEric Blake         }
3317c1bb86cdSEric Blake         IOObjectRelease( nextMedia );
3318c1bb86cdSEric Blake     }
3319c1bb86cdSEric Blake 
3320c1bb86cdSEric Blake     return kernResult;
3321c1bb86cdSEric Blake }
3322c1bb86cdSEric Blake 
3323c1bb86cdSEric Blake /* Sets up a real cdrom for use in QEMU */
3324c1bb86cdSEric Blake static bool setup_cdrom(char *bsd_path, Error **errp)
3325c1bb86cdSEric Blake {
3326c1bb86cdSEric Blake     int index, num_of_test_partitions = 2, fd;
3327c1bb86cdSEric Blake     char test_partition[MAXPATHLEN];
3328c1bb86cdSEric Blake     bool partition_found = false;
3329c1bb86cdSEric Blake 
3330c1bb86cdSEric Blake     /* look for a working partition */
3331c1bb86cdSEric Blake     for (index = 0; index < num_of_test_partitions; index++) {
3332c1bb86cdSEric Blake         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3333c1bb86cdSEric Blake                  index);
3334b18a24a9SDaniel P. Berrangé         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
3335c1bb86cdSEric Blake         if (fd >= 0) {
3336c1bb86cdSEric Blake             partition_found = true;
3337c1bb86cdSEric Blake             qemu_close(fd);
3338c1bb86cdSEric Blake             break;
3339c1bb86cdSEric Blake         }
3340c1bb86cdSEric Blake     }
3341c1bb86cdSEric Blake 
3342c1bb86cdSEric Blake     /* if a working partition on the device was not found */
3343c1bb86cdSEric Blake     if (partition_found == false) {
3344c1bb86cdSEric Blake         error_setg(errp, "Failed to find a working partition on disc");
3345c1bb86cdSEric Blake     } else {
33464f7d28d7SLaurent Vivier         trace_file_setup_cdrom(test_partition);
3347c1bb86cdSEric Blake         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
3348c1bb86cdSEric Blake     }
3349c1bb86cdSEric Blake     return partition_found;
3350c1bb86cdSEric Blake }
3351c1bb86cdSEric Blake 
3352c1bb86cdSEric Blake /* Prints directions on mounting and unmounting a device */
3353c1bb86cdSEric Blake static void print_unmounting_directions(const char *file_name)
3354c1bb86cdSEric Blake {
3355c1bb86cdSEric Blake     error_report("If device %s is mounted on the desktop, unmount"
3356c1bb86cdSEric Blake                  " it first before using it in QEMU", file_name);
3357c1bb86cdSEric Blake     error_report("Command to unmount device: diskutil unmountDisk %s",
3358c1bb86cdSEric Blake                  file_name);
3359c1bb86cdSEric Blake     error_report("Command to mount device: diskutil mountDisk %s", file_name);
3360c1bb86cdSEric Blake }
3361c1bb86cdSEric Blake 
3362c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3363c1bb86cdSEric Blake 
3364c1bb86cdSEric Blake static int hdev_probe_device(const char *filename)
3365c1bb86cdSEric Blake {
3366c1bb86cdSEric Blake     struct stat st;
3367c1bb86cdSEric Blake 
3368c1bb86cdSEric Blake     /* allow a dedicated CD-ROM driver to match with a higher priority */
3369c1bb86cdSEric Blake     if (strstart(filename, "/dev/cdrom", NULL))
3370c1bb86cdSEric Blake         return 50;
3371c1bb86cdSEric Blake 
3372c1bb86cdSEric Blake     if (stat(filename, &st) >= 0 &&
3373c1bb86cdSEric Blake             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
3374c1bb86cdSEric Blake         return 100;
3375c1bb86cdSEric Blake     }
3376c1bb86cdSEric Blake 
3377c1bb86cdSEric Blake     return 0;
3378c1bb86cdSEric Blake }
3379c1bb86cdSEric Blake 
3380c1bb86cdSEric Blake static void hdev_parse_filename(const char *filename, QDict *options,
3381c1bb86cdSEric Blake                                 Error **errp)
3382c1bb86cdSEric Blake {
338303c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
3384c1bb86cdSEric Blake }
3385c1bb86cdSEric Blake 
3386c1bb86cdSEric Blake static bool hdev_is_sg(BlockDriverState *bs)
3387c1bb86cdSEric Blake {
3388c1bb86cdSEric Blake 
3389c1bb86cdSEric Blake #if defined(__linux__)
3390c1bb86cdSEric Blake 
3391c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3392c1bb86cdSEric Blake     struct stat st;
3393c1bb86cdSEric Blake     struct sg_scsi_id scsiid;
3394c1bb86cdSEric Blake     int sg_version;
3395c1bb86cdSEric Blake     int ret;
3396c1bb86cdSEric Blake 
3397c1bb86cdSEric Blake     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
3398c1bb86cdSEric Blake         return false;
3399c1bb86cdSEric Blake     }
3400c1bb86cdSEric Blake 
3401c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
3402c1bb86cdSEric Blake     if (ret < 0) {
3403c1bb86cdSEric Blake         return false;
3404c1bb86cdSEric Blake     }
3405c1bb86cdSEric Blake 
3406c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
3407c1bb86cdSEric Blake     if (ret >= 0) {
34084f7d28d7SLaurent Vivier         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3409c1bb86cdSEric Blake         return true;
3410c1bb86cdSEric Blake     }
3411c1bb86cdSEric Blake 
3412c1bb86cdSEric Blake #endif
3413c1bb86cdSEric Blake 
3414c1bb86cdSEric Blake     return false;
3415c1bb86cdSEric Blake }
3416c1bb86cdSEric Blake 
3417c1bb86cdSEric Blake static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
3418c1bb86cdSEric Blake                      Error **errp)
3419c1bb86cdSEric Blake {
3420c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3421c1bb86cdSEric Blake     int ret;
3422c1bb86cdSEric Blake 
3423c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3424129c7d1cSMarkus Armbruster     /*
3425129c7d1cSMarkus Armbruster      * Caution: while qdict_get_str() is fine, getting non-string types
3426129c7d1cSMarkus Armbruster      * would require more care.  When @options come from -blockdev or
3427129c7d1cSMarkus Armbruster      * blockdev_add, its members are typed according to the QAPI
3428129c7d1cSMarkus Armbruster      * schema, but when they come from -drive, they're all QString.
3429129c7d1cSMarkus Armbruster      */
3430c1bb86cdSEric Blake     const char *filename = qdict_get_str(options, "filename");
3431c1bb86cdSEric Blake     char bsd_path[MAXPATHLEN] = "";
3432c1bb86cdSEric Blake     bool error_occurred = false;
3433c1bb86cdSEric Blake 
3434c1bb86cdSEric Blake     /* If using a real cdrom */
3435c1bb86cdSEric Blake     if (strcmp(filename, "/dev/cdrom") == 0) {
3436c1bb86cdSEric Blake         char *mediaType = NULL;
3437c1bb86cdSEric Blake         kern_return_t ret_val;
3438c1bb86cdSEric Blake         io_iterator_t mediaIterator = 0;
3439c1bb86cdSEric Blake 
3440c1bb86cdSEric Blake         mediaType = FindEjectableOpticalMedia(&mediaIterator);
3441c1bb86cdSEric Blake         if (mediaType == NULL) {
3442c1bb86cdSEric Blake             error_setg(errp, "Please make sure your CD/DVD is in the optical"
3443c1bb86cdSEric Blake                        " drive");
3444c1bb86cdSEric Blake             error_occurred = true;
3445c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3446c1bb86cdSEric Blake         }
3447c1bb86cdSEric Blake 
3448c1bb86cdSEric Blake         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
3449c1bb86cdSEric Blake         if (ret_val != KERN_SUCCESS) {
3450c1bb86cdSEric Blake             error_setg(errp, "Could not get BSD path for optical drive");
3451c1bb86cdSEric Blake             error_occurred = true;
3452c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3453c1bb86cdSEric Blake         }
3454c1bb86cdSEric Blake 
3455c1bb86cdSEric Blake         /* If a real optical drive was not found */
3456c1bb86cdSEric Blake         if (bsd_path[0] == '\0') {
3457c1bb86cdSEric Blake             error_setg(errp, "Failed to obtain bsd path for optical drive");
3458c1bb86cdSEric Blake             error_occurred = true;
3459c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3460c1bb86cdSEric Blake         }
3461c1bb86cdSEric Blake 
3462c1bb86cdSEric Blake         /* If using a cdrom disc and finding a partition on the disc failed */
3463c1bb86cdSEric Blake         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
3464c1bb86cdSEric Blake             setup_cdrom(bsd_path, errp) == false) {
3465c1bb86cdSEric Blake             print_unmounting_directions(bsd_path);
3466c1bb86cdSEric Blake             error_occurred = true;
3467c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3468c1bb86cdSEric Blake         }
3469c1bb86cdSEric Blake 
347046f5ac20SEric Blake         qdict_put_str(options, "filename", bsd_path);
3471c1bb86cdSEric Blake 
3472c1bb86cdSEric Blake hdev_open_Mac_error:
3473c1bb86cdSEric Blake         g_free(mediaType);
3474c1bb86cdSEric Blake         if (mediaIterator) {
3475c1bb86cdSEric Blake             IOObjectRelease(mediaIterator);
3476c1bb86cdSEric Blake         }
3477c1bb86cdSEric Blake         if (error_occurred) {
3478c1bb86cdSEric Blake             return -ENOENT;
3479c1bb86cdSEric Blake         }
3480c1bb86cdSEric Blake     }
3481c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3482c1bb86cdSEric Blake 
3483c1bb86cdSEric Blake     s->type = FTYPE_FILE;
3484c1bb86cdSEric Blake 
3485668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3486c1bb86cdSEric Blake     if (ret < 0) {
3487c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3488c1bb86cdSEric Blake         if (*bsd_path) {
3489c1bb86cdSEric Blake             filename = bsd_path;
3490c1bb86cdSEric Blake         }
3491c1bb86cdSEric Blake         /* if a physical device experienced an error while being opened */
3492c1bb86cdSEric Blake         if (strncmp(filename, "/dev/", 5) == 0) {
3493c1bb86cdSEric Blake             print_unmounting_directions(filename);
3494c1bb86cdSEric Blake         }
3495c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3496c1bb86cdSEric Blake         return ret;
3497c1bb86cdSEric Blake     }
3498c1bb86cdSEric Blake 
3499c1bb86cdSEric Blake     /* Since this does ioctl the device must be already opened */
3500c1bb86cdSEric Blake     bs->sg = hdev_is_sg(bs);
3501c1bb86cdSEric Blake 
3502c1bb86cdSEric Blake     return ret;
3503c1bb86cdSEric Blake }
3504c1bb86cdSEric Blake 
3505c1bb86cdSEric Blake #if defined(__linux__)
35062f3a7ab3SKevin Wolf static int coroutine_fn
35072f3a7ab3SKevin Wolf hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3508c1bb86cdSEric Blake {
3509c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
351003425671SKevin Wolf     RawPosixAIOData acb;
35112f3a7ab3SKevin Wolf     int ret;
3512c1bb86cdSEric Blake 
35132f3a7ab3SKevin Wolf     ret = fd_open(bs);
35142f3a7ab3SKevin Wolf     if (ret < 0) {
35152f3a7ab3SKevin Wolf         return ret;
35162f3a7ab3SKevin Wolf     }
3517c1bb86cdSEric Blake 
35187c9e5276SPaolo Bonzini     if (req == SG_IO && s->pr_mgr) {
35197c9e5276SPaolo Bonzini         struct sg_io_hdr *io_hdr = buf;
35207c9e5276SPaolo Bonzini         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
35217c9e5276SPaolo Bonzini             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
35227c9e5276SPaolo Bonzini             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
35232f3a7ab3SKevin Wolf                                       s->fd, io_hdr);
35247c9e5276SPaolo Bonzini         }
35257c9e5276SPaolo Bonzini     }
35267c9e5276SPaolo Bonzini 
352703425671SKevin Wolf     acb = (RawPosixAIOData) {
352803425671SKevin Wolf         .bs         = bs,
352903425671SKevin Wolf         .aio_type   = QEMU_AIO_IOCTL,
353003425671SKevin Wolf         .aio_fildes = s->fd,
353103425671SKevin Wolf         .aio_offset = 0,
353203425671SKevin Wolf         .ioctl      = {
353303425671SKevin Wolf             .buf        = buf,
353403425671SKevin Wolf             .cmd        = req,
353503425671SKevin Wolf         },
353603425671SKevin Wolf     };
353703425671SKevin Wolf 
353803425671SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_ioctl, &acb);
3539c1bb86cdSEric Blake }
3540c1bb86cdSEric Blake #endif /* linux */
3541c1bb86cdSEric Blake 
3542c1bb86cdSEric Blake static int fd_open(BlockDriverState *bs)
3543c1bb86cdSEric Blake {
3544c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3545c1bb86cdSEric Blake 
3546c1bb86cdSEric Blake     /* this is just to ensure s->fd is sane (its called by io ops) */
3547c1bb86cdSEric Blake     if (s->fd >= 0)
3548c1bb86cdSEric Blake         return 0;
3549c1bb86cdSEric Blake     return -EIO;
3550c1bb86cdSEric Blake }
3551c1bb86cdSEric Blake 
355233d70fb6SKevin Wolf static coroutine_fn int
355333d70fb6SKevin Wolf hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
3554c1bb86cdSEric Blake {
35551c450366SAnton Nefedov     BDRVRawState *s = bs->opaque;
355633d70fb6SKevin Wolf     int ret;
3557c1bb86cdSEric Blake 
355833d70fb6SKevin Wolf     ret = fd_open(bs);
355933d70fb6SKevin Wolf     if (ret < 0) {
35601c450366SAnton Nefedov         raw_account_discard(s, bytes, ret);
356133d70fb6SKevin Wolf         return ret;
3562c1bb86cdSEric Blake     }
356346ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, true);
3564c1bb86cdSEric Blake }
3565c1bb86cdSEric Blake 
3566c1bb86cdSEric Blake static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3567f5a5ca79SManos Pitsidianakis     int64_t offset, int bytes, BdrvRequestFlags flags)
3568c1bb86cdSEric Blake {
3569c1bb86cdSEric Blake     int rc;
3570c1bb86cdSEric Blake 
3571c1bb86cdSEric Blake     rc = fd_open(bs);
3572c1bb86cdSEric Blake     if (rc < 0) {
3573c1bb86cdSEric Blake         return rc;
3574c1bb86cdSEric Blake     }
357534fa110eSKevin Wolf 
35767154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
3577c1bb86cdSEric Blake }
3578c1bb86cdSEric Blake 
3579c1bb86cdSEric Blake static BlockDriver bdrv_host_device = {
3580c1bb86cdSEric Blake     .format_name        = "host_device",
3581c1bb86cdSEric Blake     .protocol_name        = "host_device",
3582c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3583c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3584c1bb86cdSEric Blake     .bdrv_probe_device  = hdev_probe_device,
3585c1bb86cdSEric Blake     .bdrv_parse_filename = hdev_parse_filename,
3586c1bb86cdSEric Blake     .bdrv_file_open     = hdev_open,
3587c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3588c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3589c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3590c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
35915a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
35925a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
35938a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3594dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3595c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3596c1bb86cdSEric Blake 
3597c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3598c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
359933d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
360033d70fb6SKevin Wolf     .bdrv_co_pdiscard       = hdev_co_pdiscard,
36011efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
36021efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3603c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3604c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3605c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3606042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3607c1bb86cdSEric Blake 
3608061ca8a3SKevin Wolf     .bdrv_co_truncate       = raw_co_truncate,
3609c1bb86cdSEric Blake     .bdrv_getlength	= raw_getlength,
3610c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3611c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3612c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3613d9245599SAnton Nefedov     .bdrv_get_specific_stats = hdev_get_specific_stats,
3614244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3615244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3616244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3617c1bb86cdSEric Blake     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3618c1bb86cdSEric Blake     .bdrv_probe_geometry = hdev_probe_geometry,
3619c1bb86cdSEric Blake 
3620c1bb86cdSEric Blake     /* generic scsi device */
3621c1bb86cdSEric Blake #ifdef __linux__
36222f3a7ab3SKevin Wolf     .bdrv_co_ioctl          = hdev_co_ioctl,
3623c1bb86cdSEric Blake #endif
3624c1bb86cdSEric Blake };
3625c1bb86cdSEric Blake 
3626c1bb86cdSEric Blake #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3627c1bb86cdSEric Blake static void cdrom_parse_filename(const char *filename, QDict *options,
3628c1bb86cdSEric Blake                                  Error **errp)
3629c1bb86cdSEric Blake {
363003c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3631c1bb86cdSEric Blake }
3632c1bb86cdSEric Blake #endif
3633c1bb86cdSEric Blake 
3634c1bb86cdSEric Blake #ifdef __linux__
3635c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3636c1bb86cdSEric Blake                       Error **errp)
3637c1bb86cdSEric Blake {
3638c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3639c1bb86cdSEric Blake 
3640c1bb86cdSEric Blake     s->type = FTYPE_CD;
3641c1bb86cdSEric Blake 
3642c1bb86cdSEric Blake     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3643230ff739SJohn Snow     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3644c1bb86cdSEric Blake }
3645c1bb86cdSEric Blake 
3646c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3647c1bb86cdSEric Blake {
3648c1bb86cdSEric Blake     int fd, ret;
3649c1bb86cdSEric Blake     int prio = 0;
3650c1bb86cdSEric Blake     struct stat st;
3651c1bb86cdSEric Blake 
3652b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
3653c1bb86cdSEric Blake     if (fd < 0) {
3654c1bb86cdSEric Blake         goto out;
3655c1bb86cdSEric Blake     }
3656c1bb86cdSEric Blake     ret = fstat(fd, &st);
3657c1bb86cdSEric Blake     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3658c1bb86cdSEric Blake         goto outc;
3659c1bb86cdSEric Blake     }
3660c1bb86cdSEric Blake 
3661c1bb86cdSEric Blake     /* Attempt to detect via a CDROM specific ioctl */
3662c1bb86cdSEric Blake     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3663c1bb86cdSEric Blake     if (ret >= 0)
3664c1bb86cdSEric Blake         prio = 100;
3665c1bb86cdSEric Blake 
3666c1bb86cdSEric Blake outc:
3667c1bb86cdSEric Blake     qemu_close(fd);
3668c1bb86cdSEric Blake out:
3669c1bb86cdSEric Blake     return prio;
3670c1bb86cdSEric Blake }
3671c1bb86cdSEric Blake 
3672c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3673c1bb86cdSEric Blake {
3674c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3675c1bb86cdSEric Blake     int ret;
3676c1bb86cdSEric Blake 
3677c1bb86cdSEric Blake     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3678c1bb86cdSEric Blake     return ret == CDS_DISC_OK;
3679c1bb86cdSEric Blake }
3680c1bb86cdSEric Blake 
3681c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3682c1bb86cdSEric Blake {
3683c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3684c1bb86cdSEric Blake 
3685c1bb86cdSEric Blake     if (eject_flag) {
3686c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3687c1bb86cdSEric Blake             perror("CDROMEJECT");
3688c1bb86cdSEric Blake     } else {
3689c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3690c1bb86cdSEric Blake             perror("CDROMEJECT");
3691c1bb86cdSEric Blake     }
3692c1bb86cdSEric Blake }
3693c1bb86cdSEric Blake 
3694c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3695c1bb86cdSEric Blake {
3696c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3697c1bb86cdSEric Blake 
3698c1bb86cdSEric Blake     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3699c1bb86cdSEric Blake         /*
3700c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3701c1bb86cdSEric Blake          * mounts the CD-ROM
3702c1bb86cdSEric Blake          */
3703c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3704c1bb86cdSEric Blake     }
3705c1bb86cdSEric Blake }
3706c1bb86cdSEric Blake 
3707c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3708c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3709c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3710c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3711c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3712c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3713c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3714c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3715c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3716c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3717c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3718c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
37195a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
37205a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
37218a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3722dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3723c1bb86cdSEric Blake 
3724c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3725c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
372633d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3727c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3728c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3729c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3730042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3731c1bb86cdSEric Blake 
3732061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3733c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3734c1bb86cdSEric Blake     .has_variable_length = true,
3735c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3736c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3737c1bb86cdSEric Blake 
3738c1bb86cdSEric Blake     /* removable device support */
3739c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3740c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3741c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3742c1bb86cdSEric Blake 
3743c1bb86cdSEric Blake     /* generic scsi device */
37442f3a7ab3SKevin Wolf     .bdrv_co_ioctl      = hdev_co_ioctl,
3745c1bb86cdSEric Blake };
3746c1bb86cdSEric Blake #endif /* __linux__ */
3747c1bb86cdSEric Blake 
3748c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3749c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3750c1bb86cdSEric Blake                       Error **errp)
3751c1bb86cdSEric Blake {
3752c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3753c1bb86cdSEric Blake     int ret;
3754c1bb86cdSEric Blake 
3755c1bb86cdSEric Blake     s->type = FTYPE_CD;
3756c1bb86cdSEric Blake 
3757668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3758c1bb86cdSEric Blake     if (ret) {
3759c1bb86cdSEric Blake         return ret;
3760c1bb86cdSEric Blake     }
3761c1bb86cdSEric Blake 
3762c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3763c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3764c1bb86cdSEric Blake     return 0;
3765c1bb86cdSEric Blake }
3766c1bb86cdSEric Blake 
3767c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3768c1bb86cdSEric Blake {
3769c1bb86cdSEric Blake     if (strstart(filename, "/dev/cd", NULL) ||
3770c1bb86cdSEric Blake             strstart(filename, "/dev/acd", NULL))
3771c1bb86cdSEric Blake         return 100;
3772c1bb86cdSEric Blake     return 0;
3773c1bb86cdSEric Blake }
3774c1bb86cdSEric Blake 
3775c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs)
3776c1bb86cdSEric Blake {
3777c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3778c1bb86cdSEric Blake     int fd;
3779c1bb86cdSEric Blake 
3780c1bb86cdSEric Blake     /*
3781c1bb86cdSEric Blake      * Force reread of possibly changed/newly loaded disc,
3782c1bb86cdSEric Blake      * FreeBSD seems to not notice sometimes...
3783c1bb86cdSEric Blake      */
3784c1bb86cdSEric Blake     if (s->fd >= 0)
3785c1bb86cdSEric Blake         qemu_close(s->fd);
3786b18a24a9SDaniel P. Berrangé     fd = qemu_open(bs->filename, s->open_flags, NULL);
3787c1bb86cdSEric Blake     if (fd < 0) {
3788c1bb86cdSEric Blake         s->fd = -1;
3789c1bb86cdSEric Blake         return -EIO;
3790c1bb86cdSEric Blake     }
3791c1bb86cdSEric Blake     s->fd = fd;
3792c1bb86cdSEric Blake 
3793c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3794c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3795c1bb86cdSEric Blake     return 0;
3796c1bb86cdSEric Blake }
3797c1bb86cdSEric Blake 
3798c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3799c1bb86cdSEric Blake {
3800c1bb86cdSEric Blake     return raw_getlength(bs) > 0;
3801c1bb86cdSEric Blake }
3802c1bb86cdSEric Blake 
3803c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3804c1bb86cdSEric Blake {
3805c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3806c1bb86cdSEric Blake 
3807c1bb86cdSEric Blake     if (s->fd < 0)
3808c1bb86cdSEric Blake         return;
3809c1bb86cdSEric Blake 
3810c1bb86cdSEric Blake     (void) ioctl(s->fd, CDIOCALLOW);
3811c1bb86cdSEric Blake 
3812c1bb86cdSEric Blake     if (eject_flag) {
3813c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCEJECT) < 0)
3814c1bb86cdSEric Blake             perror("CDIOCEJECT");
3815c1bb86cdSEric Blake     } else {
3816c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3817c1bb86cdSEric Blake             perror("CDIOCCLOSE");
3818c1bb86cdSEric Blake     }
3819c1bb86cdSEric Blake 
3820c1bb86cdSEric Blake     cdrom_reopen(bs);
3821c1bb86cdSEric Blake }
3822c1bb86cdSEric Blake 
3823c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3824c1bb86cdSEric Blake {
3825c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3826c1bb86cdSEric Blake 
3827c1bb86cdSEric Blake     if (s->fd < 0)
3828c1bb86cdSEric Blake         return;
3829c1bb86cdSEric Blake     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3830c1bb86cdSEric Blake         /*
3831c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3832c1bb86cdSEric Blake          * mounts the CD-ROM
3833c1bb86cdSEric Blake          */
3834c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3835c1bb86cdSEric Blake     }
3836c1bb86cdSEric Blake }
3837c1bb86cdSEric Blake 
3838c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3839c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3840c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3841c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3842c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3843c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3844c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3845c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3846c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3847c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3848c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3849c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
38505a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
38515a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
38528a2ce0bcSAlberto Garcia     .mutable_opts       = mutable_opts,
3853c1bb86cdSEric Blake 
3854c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3855c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
385633d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3857c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3858c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3859c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3860042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3861c1bb86cdSEric Blake 
3862061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3863c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3864c1bb86cdSEric Blake     .has_variable_length = true,
3865c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3866c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3867c1bb86cdSEric Blake 
3868c1bb86cdSEric Blake     /* removable device support */
3869c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3870c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3871c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3872c1bb86cdSEric Blake };
3873c1bb86cdSEric Blake #endif /* __FreeBSD__ */
3874c1bb86cdSEric Blake 
3875c1bb86cdSEric Blake static void bdrv_file_init(void)
3876c1bb86cdSEric Blake {
3877c1bb86cdSEric Blake     /*
3878c1bb86cdSEric Blake      * Register all the drivers.  Note that order is important, the driver
3879c1bb86cdSEric Blake      * registered last will get probed first.
3880c1bb86cdSEric Blake      */
3881c1bb86cdSEric Blake     bdrv_register(&bdrv_file);
3882c1bb86cdSEric Blake     bdrv_register(&bdrv_host_device);
3883c1bb86cdSEric Blake #ifdef __linux__
3884c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3885c1bb86cdSEric Blake #endif
3886c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3887c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3888c1bb86cdSEric Blake #endif
3889c1bb86cdSEric Blake }
3890c1bb86cdSEric Blake 
3891c1bb86cdSEric Blake block_init(bdrv_file_init);
3892