xref: /qemu/block/file-posix.c (revision 4ec8df01)
1c1bb86cdSEric Blake /*
2c1bb86cdSEric Blake  * Block driver for RAW files (posix)
3c1bb86cdSEric Blake  *
4c1bb86cdSEric Blake  * Copyright (c) 2006 Fabrice Bellard
5c1bb86cdSEric Blake  *
6c1bb86cdSEric Blake  * Permission is hereby granted, free of charge, to any person obtaining a copy
7c1bb86cdSEric Blake  * of this software and associated documentation files (the "Software"), to deal
8c1bb86cdSEric Blake  * in the Software without restriction, including without limitation the rights
9c1bb86cdSEric Blake  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10c1bb86cdSEric Blake  * copies of the Software, and to permit persons to whom the Software is
11c1bb86cdSEric Blake  * furnished to do so, subject to the following conditions:
12c1bb86cdSEric Blake  *
13c1bb86cdSEric Blake  * The above copyright notice and this permission notice shall be included in
14c1bb86cdSEric Blake  * all copies or substantial portions of the Software.
15c1bb86cdSEric Blake  *
16c1bb86cdSEric Blake  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17c1bb86cdSEric Blake  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18c1bb86cdSEric Blake  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19c1bb86cdSEric Blake  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20c1bb86cdSEric Blake  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21c1bb86cdSEric Blake  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22c1bb86cdSEric Blake  * THE SOFTWARE.
23c1bb86cdSEric Blake  */
24922a01a0SMarkus Armbruster 
25c1bb86cdSEric Blake #include "qemu/osdep.h"
26c1bb86cdSEric Blake #include "qapi/error.h"
27c1bb86cdSEric Blake #include "qemu/cutils.h"
28c1bb86cdSEric Blake #include "qemu/error-report.h"
29e2c1c34fSMarkus Armbruster #include "block/block-io.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"
345df022cfSPeter Maydell #include "qemu/memalign.h"
35c1bb86cdSEric Blake #include "trace.h"
36c1bb86cdSEric Blake #include "block/thread-pool.h"
37c1bb86cdSEric Blake #include "qemu/iov.h"
38c1bb86cdSEric Blake #include "block/raw-aio.h"
39452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
40c1bb86cdSEric Blake #include "qapi/qmp/qstring.h"
41c1bb86cdSEric Blake 
427c9e5276SPaolo Bonzini #include "scsi/pr-manager.h"
437c9e5276SPaolo Bonzini #include "scsi/constants.h"
447c9e5276SPaolo Bonzini 
45c1bb86cdSEric Blake #if defined(__APPLE__) && (__MACH__)
4614176c8dSJoelle van Dyne #include <sys/ioctl.h>
4714176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
48c1bb86cdSEric Blake #include <paths.h>
49c1bb86cdSEric Blake #include <sys/param.h>
500dfc7af2SAkihiko Odaki #include <sys/mount.h>
51c1bb86cdSEric Blake #include <IOKit/IOKitLib.h>
52c1bb86cdSEric Blake #include <IOKit/IOBSD.h>
53c1bb86cdSEric Blake #include <IOKit/storage/IOMediaBSDClient.h>
54c1bb86cdSEric Blake #include <IOKit/storage/IOMedia.h>
55c1bb86cdSEric Blake #include <IOKit/storage/IOCDMedia.h>
56c1bb86cdSEric Blake //#include <IOKit/storage/IOCDTypes.h>
57c1bb86cdSEric Blake #include <IOKit/storage/IODVDMedia.h>
58c1bb86cdSEric Blake #include <CoreFoundation/CoreFoundation.h>
5914176c8dSJoelle van Dyne #endif /* defined(HAVE_HOST_BLOCK_DEVICE) */
60c1bb86cdSEric Blake #endif
61c1bb86cdSEric Blake 
62c1bb86cdSEric Blake #ifdef __sun__
63c1bb86cdSEric Blake #define _POSIX_PTHREAD_SEMANTICS 1
64c1bb86cdSEric Blake #include <sys/dkio.h>
65c1bb86cdSEric Blake #endif
66c1bb86cdSEric Blake #ifdef __linux__
67c1bb86cdSEric Blake #include <sys/ioctl.h>
68c1bb86cdSEric Blake #include <sys/param.h>
691efad060SFam Zheng #include <sys/syscall.h>
705edc8557SKevin Wolf #include <sys/vfs.h>
71c1bb86cdSEric Blake #include <linux/cdrom.h>
72c1bb86cdSEric Blake #include <linux/fd.h>
73c1bb86cdSEric Blake #include <linux/fs.h>
74c1bb86cdSEric Blake #include <linux/hdreg.h>
755edc8557SKevin Wolf #include <linux/magic.h>
76c1bb86cdSEric Blake #include <scsi/sg.h>
77c1bb86cdSEric Blake #ifdef __s390__
78c1bb86cdSEric Blake #include <asm/dasd.h>
79c1bb86cdSEric Blake #endif
80c1bb86cdSEric Blake #ifndef FS_NOCOW_FL
81c1bb86cdSEric Blake #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
82c1bb86cdSEric Blake #endif
83c1bb86cdSEric Blake #endif
84c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
85c1bb86cdSEric Blake #include <linux/falloc.h>
86c1bb86cdSEric Blake #endif
87c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
88c1bb86cdSEric Blake #include <sys/disk.h>
89c1bb86cdSEric Blake #include <sys/cdio.h>
90c1bb86cdSEric Blake #endif
91c1bb86cdSEric Blake 
92c1bb86cdSEric Blake #ifdef __OpenBSD__
93c1bb86cdSEric Blake #include <sys/ioctl.h>
94c1bb86cdSEric Blake #include <sys/disklabel.h>
95c1bb86cdSEric Blake #include <sys/dkio.h>
96c1bb86cdSEric Blake #endif
97c1bb86cdSEric Blake 
98c1bb86cdSEric Blake #ifdef __NetBSD__
99c1bb86cdSEric Blake #include <sys/ioctl.h>
100c1bb86cdSEric Blake #include <sys/disklabel.h>
101c1bb86cdSEric Blake #include <sys/dkio.h>
102c1bb86cdSEric Blake #include <sys/disk.h>
103c1bb86cdSEric Blake #endif
104c1bb86cdSEric Blake 
105c1bb86cdSEric Blake #ifdef __DragonFly__
106c1bb86cdSEric Blake #include <sys/ioctl.h>
107c1bb86cdSEric Blake #include <sys/diskslice.h>
108c1bb86cdSEric Blake #endif
109c1bb86cdSEric Blake 
110c1bb86cdSEric Blake /* OS X does not have O_DSYNC */
111c1bb86cdSEric Blake #ifndef O_DSYNC
112c1bb86cdSEric Blake #ifdef O_SYNC
113c1bb86cdSEric Blake #define O_DSYNC O_SYNC
114c1bb86cdSEric Blake #elif defined(O_FSYNC)
115c1bb86cdSEric Blake #define O_DSYNC O_FSYNC
116c1bb86cdSEric Blake #endif
117c1bb86cdSEric Blake #endif
118c1bb86cdSEric Blake 
119c1bb86cdSEric Blake /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
120c1bb86cdSEric Blake #ifndef O_DIRECT
121c1bb86cdSEric Blake #define O_DIRECT O_DSYNC
122c1bb86cdSEric Blake #endif
123c1bb86cdSEric Blake 
124c1bb86cdSEric Blake #define FTYPE_FILE   0
125c1bb86cdSEric Blake #define FTYPE_CD     1
126c1bb86cdSEric Blake 
127c1bb86cdSEric Blake #define MAX_BLOCKSIZE	4096
128c1bb86cdSEric Blake 
129244a5668SFam Zheng /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
130244a5668SFam Zheng  * leaving a few more bytes for its future use. */
131244a5668SFam Zheng #define RAW_LOCK_PERM_BASE             100
132244a5668SFam Zheng #define RAW_LOCK_SHARED_BASE           200
133244a5668SFam Zheng 
134c1bb86cdSEric Blake typedef struct BDRVRawState {
135c1bb86cdSEric Blake     int fd;
136244a5668SFam Zheng     bool use_lock;
137c1bb86cdSEric Blake     int type;
138c1bb86cdSEric Blake     int open_flags;
139c1bb86cdSEric Blake     size_t buf_align;
140c1bb86cdSEric Blake 
141244a5668SFam Zheng     /* The current permissions. */
142244a5668SFam Zheng     uint64_t perm;
143244a5668SFam Zheng     uint64_t shared_perm;
144244a5668SFam Zheng 
1452996ffadSFam Zheng     /* The perms bits whose corresponding bytes are already locked in
146f2e3af29SFam Zheng      * s->fd. */
1472996ffadSFam Zheng     uint64_t locked_perm;
1482996ffadSFam Zheng     uint64_t locked_shared_perm;
1492996ffadSFam Zheng 
150684960d4SStefano Garzarella     uint64_t aio_max_batch;
151684960d4SStefano Garzarella 
1526ceabe6fSKevin Wolf     int perm_change_fd;
153094e3639SMax Reitz     int perm_change_flags;
154e0c9cf3aSKevin Wolf     BDRVReopenState *reopen_state;
155e0c9cf3aSKevin Wolf 
156c1bb86cdSEric Blake     bool has_discard:1;
157c1bb86cdSEric Blake     bool has_write_zeroes:1;
158c1bb86cdSEric Blake     bool use_linux_aio:1;
159c6447510SAarushi Mehta     bool use_linux_io_uring:1;
160c7ddc882SDaniel P. Berrangé     int page_cache_inconsistent; /* errno from fdatasync failure */
161c1bb86cdSEric Blake     bool has_fallocate;
162c1bb86cdSEric Blake     bool needs_alignment;
1635dbd0ce1SKevin Wolf     bool force_alignment;
164f357fcd8SStefan Hajnoczi     bool drop_cache;
16531be8a2aSStefan Hajnoczi     bool check_cache_dropped;
1661c450366SAnton Nefedov     struct {
1671c450366SAnton Nefedov         uint64_t discard_nb_ok;
1681c450366SAnton Nefedov         uint64_t discard_nb_failed;
1691c450366SAnton Nefedov         uint64_t discard_bytes_ok;
1701c450366SAnton Nefedov     } stats;
1717c9e5276SPaolo Bonzini 
1727c9e5276SPaolo Bonzini     PRManager *pr_mgr;
173c1bb86cdSEric Blake } BDRVRawState;
174c1bb86cdSEric Blake 
175c1bb86cdSEric Blake typedef struct BDRVRawReopenState {
176c1bb86cdSEric Blake     int open_flags;
177f357fcd8SStefan Hajnoczi     bool drop_cache;
17831be8a2aSStefan Hajnoczi     bool check_cache_dropped;
179c1bb86cdSEric Blake } BDRVRawReopenState;
180c1bb86cdSEric Blake 
18114176c8dSJoelle van Dyne static int fd_open(BlockDriverState *bs)
18214176c8dSJoelle van Dyne {
18314176c8dSJoelle van Dyne     BDRVRawState *s = bs->opaque;
18414176c8dSJoelle van Dyne 
18514176c8dSJoelle van Dyne     /* this is just to ensure s->fd is sane (its called by io ops) */
18614176c8dSJoelle van Dyne     if (s->fd >= 0) {
18714176c8dSJoelle van Dyne         return 0;
18814176c8dSJoelle van Dyne     }
18914176c8dSJoelle van Dyne     return -EIO;
19014176c8dSJoelle van Dyne }
19114176c8dSJoelle van Dyne 
192c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs);
193c1bb86cdSEric Blake 
194c1bb86cdSEric Blake typedef struct RawPosixAIOData {
195c1bb86cdSEric Blake     BlockDriverState *bs;
196c1bb86cdSEric Blake     int aio_type;
197d57c44d0SKevin Wolf     int aio_fildes;
198d57c44d0SKevin Wolf 
199d57c44d0SKevin Wolf     off_t aio_offset;
200d57c44d0SKevin Wolf     uint64_t aio_nbytes;
201d57c44d0SKevin Wolf 
20293f4e2ffSKevin Wolf     union {
20393f4e2ffSKevin Wolf         struct {
204d57c44d0SKevin Wolf             struct iovec *iov;
205d57c44d0SKevin Wolf             int niov;
206d57c44d0SKevin Wolf         } io;
207d57c44d0SKevin Wolf         struct {
208d57c44d0SKevin Wolf             uint64_t cmd;
209d57c44d0SKevin Wolf             void *buf;
210d57c44d0SKevin Wolf         } ioctl;
211d57c44d0SKevin Wolf         struct {
2121efad060SFam Zheng             int aio_fd2;
2131efad060SFam Zheng             off_t aio_offset2;
214d57c44d0SKevin Wolf         } copy_range;
21593f4e2ffSKevin Wolf         struct {
21693f4e2ffSKevin Wolf             PreallocMode prealloc;
21793f4e2ffSKevin Wolf             Error **errp;
218d57c44d0SKevin Wolf         } truncate;
21993f4e2ffSKevin Wolf     };
220c1bb86cdSEric Blake } RawPosixAIOData;
221c1bb86cdSEric Blake 
222c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
223c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs);
224c1bb86cdSEric Blake #endif
225c1bb86cdSEric Blake 
226797e3e38SDavid Edmondson /*
227797e3e38SDavid Edmondson  * Elide EAGAIN and EACCES details when failing to lock, as this
228797e3e38SDavid Edmondson  * indicates that the specified file region is already locked by
229797e3e38SDavid Edmondson  * another process, which is considered a common scenario.
230797e3e38SDavid Edmondson  */
231797e3e38SDavid Edmondson #define raw_lock_error_setg_errno(errp, err, fmt, ...)                  \
232797e3e38SDavid Edmondson     do {                                                                \
233797e3e38SDavid Edmondson         if ((err) == EAGAIN || (err) == EACCES) {                       \
234797e3e38SDavid Edmondson             error_setg((errp), (fmt), ## __VA_ARGS__);                  \
235797e3e38SDavid Edmondson         } else {                                                        \
236797e3e38SDavid Edmondson             error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__);     \
237797e3e38SDavid Edmondson         }                                                               \
238797e3e38SDavid Edmondson     } while (0)
239797e3e38SDavid Edmondson 
240c1bb86cdSEric Blake #if defined(__NetBSD__)
241db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
242c1bb86cdSEric Blake {
243c1bb86cdSEric Blake     static char namebuf[PATH_MAX];
244c1bb86cdSEric Blake     const char *dp, *fname;
245c1bb86cdSEric Blake     struct stat sb;
246c1bb86cdSEric Blake 
247c1bb86cdSEric Blake     fname = *filename;
248c1bb86cdSEric Blake     dp = strrchr(fname, '/');
249c1bb86cdSEric Blake     if (lstat(fname, &sb) < 0) {
250f6fc1e30SPaolo Bonzini         error_setg_file_open(errp, errno, fname);
251c1bb86cdSEric Blake         return -errno;
252c1bb86cdSEric Blake     }
253c1bb86cdSEric Blake 
254c1bb86cdSEric Blake     if (!S_ISBLK(sb.st_mode)) {
255c1bb86cdSEric Blake         return 0;
256c1bb86cdSEric Blake     }
257c1bb86cdSEric Blake 
258c1bb86cdSEric Blake     if (dp == NULL) {
259c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "r%s", fname);
260c1bb86cdSEric Blake     } else {
261c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
262c1bb86cdSEric Blake             (int)(dp - fname), fname, dp + 1);
263c1bb86cdSEric Blake     }
264c1bb86cdSEric Blake     *filename = namebuf;
265db0754dfSFam Zheng     warn_report("%s is a block device, using %s", fname, *filename);
266c1bb86cdSEric Blake 
267c1bb86cdSEric Blake     return 0;
268c1bb86cdSEric Blake }
269c1bb86cdSEric Blake #else
270db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
271c1bb86cdSEric Blake {
272c1bb86cdSEric Blake     return 0;
273c1bb86cdSEric Blake }
274c1bb86cdSEric Blake #endif
275c1bb86cdSEric Blake 
276c1bb86cdSEric Blake /*
277c1bb86cdSEric Blake  * Get logical block size via ioctl. On success store it in @sector_size_p.
278c1bb86cdSEric Blake  */
279c1bb86cdSEric Blake static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
280c1bb86cdSEric Blake {
281c1bb86cdSEric Blake     unsigned int sector_size;
282c1bb86cdSEric Blake     bool success = false;
283700f9ce0SPeter Maydell     int i;
284c1bb86cdSEric Blake 
285c1bb86cdSEric Blake     errno = ENOTSUP;
286700f9ce0SPeter Maydell     static const unsigned long ioctl_list[] = {
287c1bb86cdSEric Blake #ifdef BLKSSZGET
288700f9ce0SPeter Maydell         BLKSSZGET,
289c1bb86cdSEric Blake #endif
290c1bb86cdSEric Blake #ifdef DKIOCGETBLOCKSIZE
291700f9ce0SPeter Maydell         DKIOCGETBLOCKSIZE,
292c1bb86cdSEric Blake #endif
293c1bb86cdSEric Blake #ifdef DIOCGSECTORSIZE
294700f9ce0SPeter Maydell         DIOCGSECTORSIZE,
295700f9ce0SPeter Maydell #endif
296700f9ce0SPeter Maydell     };
297700f9ce0SPeter Maydell 
298700f9ce0SPeter Maydell     /* Try a few ioctls to get the right size */
299700f9ce0SPeter Maydell     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
300700f9ce0SPeter Maydell         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
301c1bb86cdSEric Blake             *sector_size_p = sector_size;
302c1bb86cdSEric Blake             success = true;
303c1bb86cdSEric Blake         }
304700f9ce0SPeter Maydell     }
305c1bb86cdSEric Blake 
306c1bb86cdSEric Blake     return success ? 0 : -errno;
307c1bb86cdSEric Blake }
308c1bb86cdSEric Blake 
309c1bb86cdSEric Blake /**
310c1bb86cdSEric Blake  * Get physical block size of @fd.
311c1bb86cdSEric Blake  * On success, store it in @blk_size and return 0.
312c1bb86cdSEric Blake  * On failure, return -errno.
313c1bb86cdSEric Blake  */
314c1bb86cdSEric Blake static int probe_physical_blocksize(int fd, unsigned int *blk_size)
315c1bb86cdSEric Blake {
316c1bb86cdSEric Blake #ifdef BLKPBSZGET
317c1bb86cdSEric Blake     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
318c1bb86cdSEric Blake         return -errno;
319c1bb86cdSEric Blake     }
320c1bb86cdSEric Blake     return 0;
321c1bb86cdSEric Blake #else
322c1bb86cdSEric Blake     return -ENOTSUP;
323c1bb86cdSEric Blake #endif
324c1bb86cdSEric Blake }
325c1bb86cdSEric Blake 
3265edc8557SKevin Wolf /*
3275edc8557SKevin Wolf  * Returns true if no alignment restrictions are necessary even for files
3285edc8557SKevin Wolf  * opened with O_DIRECT.
3295edc8557SKevin Wolf  *
3305edc8557SKevin Wolf  * raw_probe_alignment() probes the required alignment and assume that 1 means
3315edc8557SKevin Wolf  * the probing failed, so it falls back to a safe default of 4k. This can be
3325edc8557SKevin Wolf  * avoided if we know that byte alignment is okay for the file.
3335edc8557SKevin Wolf  */
3345edc8557SKevin Wolf static bool dio_byte_aligned(int fd)
3355edc8557SKevin Wolf {
3365edc8557SKevin Wolf #ifdef __linux__
3375edc8557SKevin Wolf     struct statfs buf;
3385edc8557SKevin Wolf     int ret;
3395edc8557SKevin Wolf 
3405edc8557SKevin Wolf     ret = fstatfs(fd, &buf);
3415edc8557SKevin Wolf     if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
3425edc8557SKevin Wolf         return true;
3435edc8557SKevin Wolf     }
3445edc8557SKevin Wolf #endif
3455edc8557SKevin Wolf     return false;
3465edc8557SKevin Wolf }
3475edc8557SKevin Wolf 
3485dbd0ce1SKevin Wolf static bool raw_needs_alignment(BlockDriverState *bs)
3495dbd0ce1SKevin Wolf {
3505dbd0ce1SKevin Wolf     BDRVRawState *s = bs->opaque;
3515dbd0ce1SKevin Wolf 
3525dbd0ce1SKevin Wolf     if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
3535dbd0ce1SKevin Wolf         return true;
3545dbd0ce1SKevin Wolf     }
3555dbd0ce1SKevin Wolf 
3565dbd0ce1SKevin Wolf     return s->force_alignment;
3575dbd0ce1SKevin Wolf }
3585dbd0ce1SKevin Wolf 
359c1bb86cdSEric Blake /* Check if read is allowed with given memory buffer and length.
360c1bb86cdSEric Blake  *
361c1bb86cdSEric Blake  * This function is used to check O_DIRECT memory buffer and request alignment.
362c1bb86cdSEric Blake  */
363c1bb86cdSEric Blake static bool raw_is_io_aligned(int fd, void *buf, size_t len)
364c1bb86cdSEric Blake {
365c1bb86cdSEric Blake     ssize_t ret = pread(fd, buf, len, 0);
366c1bb86cdSEric Blake 
367c1bb86cdSEric Blake     if (ret >= 0) {
368c1bb86cdSEric Blake         return true;
369c1bb86cdSEric Blake     }
370c1bb86cdSEric Blake 
371c1bb86cdSEric Blake #ifdef __linux__
372c1bb86cdSEric Blake     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
373c1bb86cdSEric Blake      * other errors (e.g. real I/O error), which could happen on a failed
374c1bb86cdSEric Blake      * drive, since we only care about probing alignment.
375c1bb86cdSEric Blake      */
376c1bb86cdSEric Blake     if (errno != EINVAL) {
377c1bb86cdSEric Blake         return true;
378c1bb86cdSEric Blake     }
379c1bb86cdSEric Blake #endif
380c1bb86cdSEric Blake 
381c1bb86cdSEric Blake     return false;
382c1bb86cdSEric Blake }
383c1bb86cdSEric Blake 
384c1bb86cdSEric Blake static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
385c1bb86cdSEric Blake {
386c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
387c1bb86cdSEric Blake     char *buf;
3888e3b0cbbSMarc-André Lureau     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
389a6b257a0SNir Soffer     size_t alignments[] = {1, 512, 1024, 2048, 4096};
390c1bb86cdSEric Blake 
391c1bb86cdSEric Blake     /* For SCSI generic devices the alignment is not really used.
392c1bb86cdSEric Blake        With buffered I/O, we don't have any restrictions. */
393c1bb86cdSEric Blake     if (bdrv_is_sg(bs) || !s->needs_alignment) {
394c1bb86cdSEric Blake         bs->bl.request_alignment = 1;
395c1bb86cdSEric Blake         s->buf_align = 1;
396c1bb86cdSEric Blake         return;
397c1bb86cdSEric Blake     }
398c1bb86cdSEric Blake 
399c1bb86cdSEric Blake     bs->bl.request_alignment = 0;
400c1bb86cdSEric Blake     s->buf_align = 0;
401c1bb86cdSEric Blake     /* Let's try to use the logical blocksize for the alignment. */
402c1bb86cdSEric Blake     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
403c1bb86cdSEric Blake         bs->bl.request_alignment = 0;
404c1bb86cdSEric Blake     }
405a5730b8bSThomas Huth 
406a5730b8bSThomas Huth #ifdef __linux__
407a5730b8bSThomas Huth     /*
408a5730b8bSThomas Huth      * The XFS ioctl definitions are shipped in extra packages that might
409a5730b8bSThomas Huth      * not always be available. Since we just need the XFS_IOC_DIOINFO ioctl
410a5730b8bSThomas Huth      * here, we simply use our own definition instead:
411a5730b8bSThomas Huth      */
412a5730b8bSThomas Huth     struct xfs_dioattr {
413a5730b8bSThomas Huth         uint32_t d_mem;
414a5730b8bSThomas Huth         uint32_t d_miniosz;
415a5730b8bSThomas Huth         uint32_t d_maxiosz;
416a5730b8bSThomas Huth     } da;
417a5730b8bSThomas Huth     if (ioctl(fd, _IOR('X', 30, struct xfs_dioattr), &da) >= 0) {
418c1bb86cdSEric Blake         bs->bl.request_alignment = da.d_miniosz;
419c1bb86cdSEric Blake         /* The kernel returns wrong information for d_mem */
420c1bb86cdSEric Blake         /* s->buf_align = da.d_mem; */
421c1bb86cdSEric Blake     }
422c1bb86cdSEric Blake #endif
423c1bb86cdSEric Blake 
424a6b257a0SNir Soffer     /*
425a6b257a0SNir Soffer      * If we could not get the sizes so far, we can only guess them. First try
426a6b257a0SNir Soffer      * to detect request alignment, since it is more likely to succeed. Then
427a6b257a0SNir Soffer      * try to detect buf_align, which cannot be detected in some cases (e.g.
428a6b257a0SNir Soffer      * Gluster). If buf_align cannot be detected, we fallback to the value of
429a6b257a0SNir Soffer      * request_alignment.
430a6b257a0SNir Soffer      */
431a6b257a0SNir Soffer 
432a6b257a0SNir Soffer     if (!bs->bl.request_alignment) {
433a6b257a0SNir Soffer         int i;
434c1bb86cdSEric Blake         size_t align;
435a6b257a0SNir Soffer         buf = qemu_memalign(max_align, max_align);
436a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
437a6b257a0SNir Soffer             align = alignments[i];
438a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf, align)) {
439a6b257a0SNir Soffer                 /* Fallback to safe value. */
440a6b257a0SNir Soffer                 bs->bl.request_alignment = (align != 1) ? align : max_align;
441c1bb86cdSEric Blake                 break;
442c1bb86cdSEric Blake             }
443c1bb86cdSEric Blake         }
444c1bb86cdSEric Blake         qemu_vfree(buf);
445c1bb86cdSEric Blake     }
446c1bb86cdSEric Blake 
447a6b257a0SNir Soffer     if (!s->buf_align) {
448a6b257a0SNir Soffer         int i;
449c1bb86cdSEric Blake         size_t align;
450a6b257a0SNir Soffer         buf = qemu_memalign(max_align, 2 * max_align);
451a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
452a6b257a0SNir Soffer             align = alignments[i];
453a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf + align, max_align)) {
454236094c7SStefan Hajnoczi                 /* Fallback to request_alignment. */
455a6b257a0SNir Soffer                 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
456c1bb86cdSEric Blake                 break;
457c1bb86cdSEric Blake             }
458c1bb86cdSEric Blake         }
459c1bb86cdSEric Blake         qemu_vfree(buf);
460c1bb86cdSEric Blake     }
461c1bb86cdSEric Blake 
462c1bb86cdSEric Blake     if (!s->buf_align || !bs->bl.request_alignment) {
463c1bb86cdSEric Blake         error_setg(errp, "Could not find working O_DIRECT alignment");
464c1bb86cdSEric Blake         error_append_hint(errp, "Try cache.direct=off\n");
465c1bb86cdSEric Blake     }
466c1bb86cdSEric Blake }
467c1bb86cdSEric Blake 
468bca5283bSKevin Wolf static int check_hdev_writable(int fd)
46920eaf1bfSKevin Wolf {
47020eaf1bfSKevin Wolf #if defined(BLKROGET)
47120eaf1bfSKevin Wolf     /* Linux block devices can be configured "read-only" using blockdev(8).
47220eaf1bfSKevin Wolf      * This is independent of device node permissions and therefore open(2)
47320eaf1bfSKevin Wolf      * with O_RDWR succeeds.  Actual writes fail with EPERM.
47420eaf1bfSKevin Wolf      *
47520eaf1bfSKevin Wolf      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
47620eaf1bfSKevin Wolf      * check for read-only block devices so that Linux block devices behave
47720eaf1bfSKevin Wolf      * properly.
47820eaf1bfSKevin Wolf      */
47920eaf1bfSKevin Wolf     struct stat st;
48020eaf1bfSKevin Wolf     int readonly = 0;
48120eaf1bfSKevin Wolf 
482bca5283bSKevin Wolf     if (fstat(fd, &st)) {
48320eaf1bfSKevin Wolf         return -errno;
48420eaf1bfSKevin Wolf     }
48520eaf1bfSKevin Wolf 
48620eaf1bfSKevin Wolf     if (!S_ISBLK(st.st_mode)) {
48720eaf1bfSKevin Wolf         return 0;
48820eaf1bfSKevin Wolf     }
48920eaf1bfSKevin Wolf 
490bca5283bSKevin Wolf     if (ioctl(fd, BLKROGET, &readonly) < 0) {
49120eaf1bfSKevin Wolf         return -errno;
49220eaf1bfSKevin Wolf     }
49320eaf1bfSKevin Wolf 
49420eaf1bfSKevin Wolf     if (readonly) {
49520eaf1bfSKevin Wolf         return -EACCES;
49620eaf1bfSKevin Wolf     }
49720eaf1bfSKevin Wolf #endif /* defined(BLKROGET) */
49820eaf1bfSKevin Wolf     return 0;
49920eaf1bfSKevin Wolf }
50020eaf1bfSKevin Wolf 
50123dece19SKevin Wolf static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
502c1bb86cdSEric Blake {
50323dece19SKevin Wolf     bool read_write = false;
504c1bb86cdSEric Blake     assert(open_flags != NULL);
505c1bb86cdSEric Blake 
506c1bb86cdSEric Blake     *open_flags |= O_BINARY;
507c1bb86cdSEric Blake     *open_flags &= ~O_ACCMODE;
50823dece19SKevin Wolf 
50923dece19SKevin Wolf     if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
51023dece19SKevin Wolf         read_write = has_writers;
51123dece19SKevin Wolf     } else if (bdrv_flags & BDRV_O_RDWR) {
51223dece19SKevin Wolf         read_write = true;
51323dece19SKevin Wolf     }
51423dece19SKevin Wolf 
51523dece19SKevin Wolf     if (read_write) {
516c1bb86cdSEric Blake         *open_flags |= O_RDWR;
517c1bb86cdSEric Blake     } else {
518c1bb86cdSEric Blake         *open_flags |= O_RDONLY;
519c1bb86cdSEric Blake     }
520c1bb86cdSEric Blake 
521c1bb86cdSEric Blake     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
522c1bb86cdSEric Blake      * and O_DIRECT for no caching. */
523c1bb86cdSEric Blake     if ((bdrv_flags & BDRV_O_NOCACHE)) {
524c1bb86cdSEric Blake         *open_flags |= O_DIRECT;
525c1bb86cdSEric Blake     }
526c1bb86cdSEric Blake }
527c1bb86cdSEric Blake 
528c1bb86cdSEric Blake static void raw_parse_filename(const char *filename, QDict *options,
529c1bb86cdSEric Blake                                Error **errp)
530c1bb86cdSEric Blake {
53103c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "file:", options);
532c1bb86cdSEric Blake }
533c1bb86cdSEric Blake 
534c1bb86cdSEric Blake static QemuOptsList raw_runtime_opts = {
535c1bb86cdSEric Blake     .name = "raw",
536c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
537c1bb86cdSEric Blake     .desc = {
538c1bb86cdSEric Blake         {
539c1bb86cdSEric Blake             .name = "filename",
540c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
541c1bb86cdSEric Blake             .help = "File name of the image",
542c1bb86cdSEric Blake         },
543c1bb86cdSEric Blake         {
544c1bb86cdSEric Blake             .name = "aio",
545c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
546c6447510SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
547c1bb86cdSEric Blake         },
54816b48d5dSFam Zheng         {
549684960d4SStefano Garzarella             .name = "aio-max-batch",
550684960d4SStefano Garzarella             .type = QEMU_OPT_NUMBER,
551684960d4SStefano Garzarella             .help = "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
552684960d4SStefano Garzarella         },
553684960d4SStefano Garzarella         {
55416b48d5dSFam Zheng             .name = "locking",
55516b48d5dSFam Zheng             .type = QEMU_OPT_STRING,
55616b48d5dSFam Zheng             .help = "file locking mode (on/off/auto, default: auto)",
55716b48d5dSFam Zheng         },
5587c9e5276SPaolo Bonzini         {
5597c9e5276SPaolo Bonzini             .name = "pr-manager",
5607c9e5276SPaolo Bonzini             .type = QEMU_OPT_STRING,
5617c9e5276SPaolo Bonzini             .help = "id of persistent reservation manager object (default: none)",
5627c9e5276SPaolo Bonzini         },
563f357fcd8SStefan Hajnoczi #if defined(__linux__)
564f357fcd8SStefan Hajnoczi         {
565f357fcd8SStefan Hajnoczi             .name = "drop-cache",
566f357fcd8SStefan Hajnoczi             .type = QEMU_OPT_BOOL,
567f357fcd8SStefan Hajnoczi             .help = "invalidate page cache during live migration (default: on)",
568f357fcd8SStefan Hajnoczi         },
569f357fcd8SStefan Hajnoczi #endif
57031be8a2aSStefan Hajnoczi         {
57131be8a2aSStefan Hajnoczi             .name = "x-check-cache-dropped",
57231be8a2aSStefan Hajnoczi             .type = QEMU_OPT_BOOL,
57331be8a2aSStefan Hajnoczi             .help = "check that page cache was dropped on live migration (default: off)"
57431be8a2aSStefan Hajnoczi         },
575c1bb86cdSEric Blake         { /* end of list */ }
576c1bb86cdSEric Blake     },
577c1bb86cdSEric Blake };
578c1bb86cdSEric Blake 
5798a2ce0bcSAlberto Garcia static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
5808a2ce0bcSAlberto Garcia 
581c1bb86cdSEric Blake static int raw_open_common(BlockDriverState *bs, QDict *options,
582230ff739SJohn Snow                            int bdrv_flags, int open_flags,
583230ff739SJohn Snow                            bool device, Error **errp)
584c1bb86cdSEric Blake {
585c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
586c1bb86cdSEric Blake     QemuOpts *opts;
587c1bb86cdSEric Blake     Error *local_err = NULL;
588c1bb86cdSEric Blake     const char *filename = NULL;
5897c9e5276SPaolo Bonzini     const char *str;
590c1bb86cdSEric Blake     BlockdevAioOptions aio, aio_default;
591c1bb86cdSEric Blake     int fd, ret;
592c1bb86cdSEric Blake     struct stat st;
593244a5668SFam Zheng     OnOffAuto locking;
594c1bb86cdSEric Blake 
595c1bb86cdSEric Blake     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
596af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
597c1bb86cdSEric Blake         ret = -EINVAL;
598c1bb86cdSEric Blake         goto fail;
599c1bb86cdSEric Blake     }
600c1bb86cdSEric Blake 
601c1bb86cdSEric Blake     filename = qemu_opt_get(opts, "filename");
602c1bb86cdSEric Blake 
603db0754dfSFam Zheng     ret = raw_normalize_devicepath(&filename, errp);
604c1bb86cdSEric Blake     if (ret != 0) {
605c1bb86cdSEric Blake         goto fail;
606c1bb86cdSEric Blake     }
607c1bb86cdSEric Blake 
608c6447510SAarushi Mehta     if (bdrv_flags & BDRV_O_NATIVE_AIO) {
609c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
610c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
611c6447510SAarushi Mehta     } else if (bdrv_flags & BDRV_O_IO_URING) {
612c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
613c6447510SAarushi Mehta #endif
614c6447510SAarushi Mehta     } else {
615c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
616c6447510SAarushi Mehta     }
617c6447510SAarushi Mehta 
618f7abe0ecSMarc-André Lureau     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
619f7abe0ecSMarc-André Lureau                           qemu_opt_get(opts, "aio"),
62006c60b6cSMarkus Armbruster                           aio_default, &local_err);
621c1bb86cdSEric Blake     if (local_err) {
622c1bb86cdSEric Blake         error_propagate(errp, local_err);
623c1bb86cdSEric Blake         ret = -EINVAL;
624c1bb86cdSEric Blake         goto fail;
625c1bb86cdSEric Blake     }
626c6447510SAarushi Mehta 
627c1bb86cdSEric Blake     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
628c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
629c6447510SAarushi Mehta     s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
630c6447510SAarushi Mehta #endif
631c1bb86cdSEric Blake 
632684960d4SStefano Garzarella     s->aio_max_batch = qemu_opt_get_number(opts, "aio-max-batch", 0);
633684960d4SStefano Garzarella 
634f7abe0ecSMarc-André Lureau     locking = qapi_enum_parse(&OnOffAuto_lookup,
635f7abe0ecSMarc-André Lureau                               qemu_opt_get(opts, "locking"),
63606c60b6cSMarkus Armbruster                               ON_OFF_AUTO_AUTO, &local_err);
637244a5668SFam Zheng     if (local_err) {
638244a5668SFam Zheng         error_propagate(errp, local_err);
639244a5668SFam Zheng         ret = -EINVAL;
640244a5668SFam Zheng         goto fail;
641244a5668SFam Zheng     }
642244a5668SFam Zheng     switch (locking) {
643244a5668SFam Zheng     case ON_OFF_AUTO_ON:
644244a5668SFam Zheng         s->use_lock = true;
6452b218f5dSFam Zheng         if (!qemu_has_ofd_lock()) {
646db0754dfSFam Zheng             warn_report("File lock requested but OFD locking syscall is "
647db0754dfSFam Zheng                         "unavailable, falling back to POSIX file locks");
648db0754dfSFam Zheng             error_printf("Due to the implementation, locks can be lost "
6492b218f5dSFam Zheng                          "unexpectedly.\n");
6502b218f5dSFam Zheng         }
651244a5668SFam Zheng         break;
652244a5668SFam Zheng     case ON_OFF_AUTO_OFF:
653244a5668SFam Zheng         s->use_lock = false;
654244a5668SFam Zheng         break;
655244a5668SFam Zheng     case ON_OFF_AUTO_AUTO:
6562b218f5dSFam Zheng         s->use_lock = qemu_has_ofd_lock();
657244a5668SFam Zheng         break;
658244a5668SFam Zheng     default:
659244a5668SFam Zheng         abort();
660244a5668SFam Zheng     }
661244a5668SFam Zheng 
6627c9e5276SPaolo Bonzini     str = qemu_opt_get(opts, "pr-manager");
6637c9e5276SPaolo Bonzini     if (str) {
6647c9e5276SPaolo Bonzini         s->pr_mgr = pr_manager_lookup(str, &local_err);
6657c9e5276SPaolo Bonzini         if (local_err) {
6667c9e5276SPaolo Bonzini             error_propagate(errp, local_err);
6677c9e5276SPaolo Bonzini             ret = -EINVAL;
6687c9e5276SPaolo Bonzini             goto fail;
6697c9e5276SPaolo Bonzini         }
6707c9e5276SPaolo Bonzini     }
6717c9e5276SPaolo Bonzini 
672f357fcd8SStefan Hajnoczi     s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
67331be8a2aSStefan Hajnoczi     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
67431be8a2aSStefan Hajnoczi                                                false);
67531be8a2aSStefan Hajnoczi 
676c1bb86cdSEric Blake     s->open_flags = open_flags;
67723dece19SKevin Wolf     raw_parse_flags(bdrv_flags, &s->open_flags, false);
678c1bb86cdSEric Blake 
679c1bb86cdSEric Blake     s->fd = -1;
680b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, s->open_flags, errp);
68164107dc0SKevin Wolf     ret = fd < 0 ? -errno : 0;
68264107dc0SKevin Wolf 
68364107dc0SKevin Wolf     if (ret < 0) {
684c1bb86cdSEric Blake         if (ret == -EROFS) {
685c1bb86cdSEric Blake             ret = -EACCES;
686c1bb86cdSEric Blake         }
687c1bb86cdSEric Blake         goto fail;
688c1bb86cdSEric Blake     }
689c1bb86cdSEric Blake     s->fd = fd;
690c1bb86cdSEric Blake 
691bca5283bSKevin Wolf     /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
692bca5283bSKevin Wolf     if (s->open_flags & O_RDWR) {
693bca5283bSKevin Wolf         ret = check_hdev_writable(s->fd);
694bca5283bSKevin Wolf         if (ret < 0) {
695bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
696bca5283bSKevin Wolf             goto fail;
697bca5283bSKevin Wolf         }
698bca5283bSKevin Wolf     }
699bca5283bSKevin Wolf 
700244a5668SFam Zheng     s->perm = 0;
701244a5668SFam Zheng     s->shared_perm = BLK_PERM_ALL;
702244a5668SFam Zheng 
703c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
704c1bb86cdSEric Blake      /* Currently Linux does AIO only for files opened with O_DIRECT */
705ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
706ed6e2161SNishanth Aravamudan         if (!(s->open_flags & O_DIRECT)) {
707c1bb86cdSEric Blake             error_setg(errp, "aio=native was specified, but it requires "
708c1bb86cdSEric Blake                              "cache.direct=on, which was not specified.");
709c1bb86cdSEric Blake             ret = -EINVAL;
710c1bb86cdSEric Blake             goto fail;
711c1bb86cdSEric Blake         }
712ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
713ed6e2161SNishanth Aravamudan             error_prepend(errp, "Unable to use native AIO: ");
714ed6e2161SNishanth Aravamudan             goto fail;
715ed6e2161SNishanth Aravamudan         }
716ed6e2161SNishanth Aravamudan     }
717c1bb86cdSEric Blake #else
718c1bb86cdSEric Blake     if (s->use_linux_aio) {
719c1bb86cdSEric Blake         error_setg(errp, "aio=native was specified, but is not supported "
720c1bb86cdSEric Blake                          "in this build.");
721c1bb86cdSEric Blake         ret = -EINVAL;
722c1bb86cdSEric Blake         goto fail;
723c1bb86cdSEric Blake     }
724c1bb86cdSEric Blake #endif /* !defined(CONFIG_LINUX_AIO) */
725c1bb86cdSEric Blake 
726c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
727c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
728c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
729c6447510SAarushi Mehta             error_prepend(errp, "Unable to use io_uring: ");
730c6447510SAarushi Mehta             goto fail;
731c6447510SAarushi Mehta         }
732c6447510SAarushi Mehta     }
733c6447510SAarushi Mehta #else
734c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
735c6447510SAarushi Mehta         error_setg(errp, "aio=io_uring was specified, but is not supported "
736c6447510SAarushi Mehta                          "in this build.");
737c6447510SAarushi Mehta         ret = -EINVAL;
738c6447510SAarushi Mehta         goto fail;
739c6447510SAarushi Mehta     }
740c6447510SAarushi Mehta #endif /* !defined(CONFIG_LINUX_IO_URING) */
741c6447510SAarushi Mehta 
742c1bb86cdSEric Blake     s->has_discard = true;
743c1bb86cdSEric Blake     s->has_write_zeroes = true;
744c1bb86cdSEric Blake 
745c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
746c1bb86cdSEric Blake         ret = -errno;
747c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not stat file");
748c1bb86cdSEric Blake         goto fail;
749c1bb86cdSEric Blake     }
750230ff739SJohn Snow 
751230ff739SJohn Snow     if (!device) {
7528d17adf3SDaniel P. Berrangé         if (!S_ISREG(st.st_mode)) {
7538d17adf3SDaniel P. Berrangé             error_setg(errp, "'%s' driver requires '%s' to be a regular file",
7548d17adf3SDaniel P. Berrangé                        bs->drv->format_name, bs->filename);
755230ff739SJohn Snow             ret = -EINVAL;
756230ff739SJohn Snow             goto fail;
757230ff739SJohn Snow         } else {
758c1bb86cdSEric Blake             s->has_fallocate = true;
759c1bb86cdSEric Blake         }
760230ff739SJohn Snow     } else {
761230ff739SJohn Snow         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
7628d17adf3SDaniel P. Berrangé             error_setg(errp, "'%s' driver requires '%s' to be either "
7638d17adf3SDaniel P. Berrangé                        "a character or block device",
7648d17adf3SDaniel P. Berrangé                        bs->drv->format_name, bs->filename);
765230ff739SJohn Snow             ret = -EINVAL;
766230ff739SJohn Snow             goto fail;
767230ff739SJohn Snow         }
768230ff739SJohn Snow     }
769230ff739SJohn Snow 
770c1bb86cdSEric Blake     if (S_ISBLK(st.st_mode)) {
771c1bb86cdSEric Blake #ifdef __linux__
772c1bb86cdSEric Blake         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
773c1bb86cdSEric Blake          * not rely on the contents of discarded blocks unless using O_DIRECT.
774c1bb86cdSEric Blake          * Same for BLKZEROOUT.
775c1bb86cdSEric Blake          */
776c1bb86cdSEric Blake         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
777c1bb86cdSEric Blake             s->has_write_zeroes = false;
778c1bb86cdSEric Blake         }
779c1bb86cdSEric Blake #endif
780c1bb86cdSEric Blake     }
781c1bb86cdSEric Blake #ifdef __FreeBSD__
782c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode)) {
783c1bb86cdSEric Blake         /*
784c1bb86cdSEric Blake          * The file is a char device (disk), which on FreeBSD isn't behind
785c1bb86cdSEric Blake          * a pager, so force all requests to be aligned. This is needed
786c1bb86cdSEric Blake          * so QEMU makes sure all IO operations on the device are aligned
787c1bb86cdSEric Blake          * to sector size, or else FreeBSD will reject them with EINVAL.
788c1bb86cdSEric Blake          */
7895dbd0ce1SKevin Wolf         s->force_alignment = true;
790c1bb86cdSEric Blake     }
791c1bb86cdSEric Blake #endif
7925dbd0ce1SKevin Wolf     s->needs_alignment = raw_needs_alignment(bs);
793c1bb86cdSEric Blake 
794738301e1SKevin Wolf     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
7952f0c6e7aSKevin Wolf     if (S_ISREG(st.st_mode)) {
7962f0c6e7aSKevin Wolf         /* When extending regular files, we get zeros from the OS */
7972f0c6e7aSKevin Wolf         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
7982f0c6e7aSKevin Wolf     }
799c1bb86cdSEric Blake     ret = 0;
800c1bb86cdSEric Blake fail:
801a8c5cf27SKevin Wolf     if (ret < 0 && s->fd != -1) {
802a8c5cf27SKevin Wolf         qemu_close(s->fd);
803a8c5cf27SKevin Wolf     }
804c1bb86cdSEric Blake     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
805c1bb86cdSEric Blake         unlink(filename);
806c1bb86cdSEric Blake     }
807c1bb86cdSEric Blake     qemu_opts_del(opts);
808c1bb86cdSEric Blake     return ret;
809c1bb86cdSEric Blake }
810c1bb86cdSEric Blake 
811c1bb86cdSEric Blake static int raw_open(BlockDriverState *bs, QDict *options, int flags,
812c1bb86cdSEric Blake                     Error **errp)
813c1bb86cdSEric Blake {
814c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
815c1bb86cdSEric Blake 
816c1bb86cdSEric Blake     s->type = FTYPE_FILE;
817230ff739SJohn Snow     return raw_open_common(bs, options, flags, 0, false, errp);
818c1bb86cdSEric Blake }
819c1bb86cdSEric Blake 
820244a5668SFam Zheng typedef enum {
821244a5668SFam Zheng     RAW_PL_PREPARE,
822244a5668SFam Zheng     RAW_PL_COMMIT,
823244a5668SFam Zheng     RAW_PL_ABORT,
824244a5668SFam Zheng } RawPermLockOp;
825244a5668SFam Zheng 
826244a5668SFam Zheng #define PERM_FOREACH(i) \
827244a5668SFam Zheng     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
828244a5668SFam Zheng 
829244a5668SFam Zheng /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
830244a5668SFam Zheng  * file; if @unlock == true, also unlock the unneeded bytes.
831244a5668SFam Zheng  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
832244a5668SFam Zheng  */
8332996ffadSFam Zheng static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
834244a5668SFam Zheng                                 uint64_t perm_lock_bits,
835244a5668SFam Zheng                                 uint64_t shared_perm_lock_bits,
836244a5668SFam Zheng                                 bool unlock, Error **errp)
837244a5668SFam Zheng {
838244a5668SFam Zheng     int ret;
839244a5668SFam Zheng     int i;
8402996ffadSFam Zheng     uint64_t locked_perm, locked_shared_perm;
8412996ffadSFam Zheng 
8422996ffadSFam Zheng     if (s) {
8432996ffadSFam Zheng         locked_perm = s->locked_perm;
8442996ffadSFam Zheng         locked_shared_perm = s->locked_shared_perm;
8452996ffadSFam Zheng     } else {
8462996ffadSFam Zheng         /*
8472996ffadSFam Zheng          * We don't have the previous bits, just lock/unlock for each of the
8482996ffadSFam Zheng          * requested bits.
8492996ffadSFam Zheng          */
8502996ffadSFam Zheng         if (unlock) {
8512996ffadSFam Zheng             locked_perm = BLK_PERM_ALL;
8522996ffadSFam Zheng             locked_shared_perm = BLK_PERM_ALL;
8532996ffadSFam Zheng         } else {
8542996ffadSFam Zheng             locked_perm = 0;
8552996ffadSFam Zheng             locked_shared_perm = 0;
8562996ffadSFam Zheng         }
8572996ffadSFam Zheng     }
858244a5668SFam Zheng 
859244a5668SFam Zheng     PERM_FOREACH(i) {
860244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
8612996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8622996ffadSFam Zheng         if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
863d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
864244a5668SFam Zheng             if (ret) {
865797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
866797e3e38SDavid Edmondson                                           off);
867244a5668SFam Zheng                 return ret;
8682996ffadSFam Zheng             } else if (s) {
8692996ffadSFam Zheng                 s->locked_perm |= bit;
870244a5668SFam Zheng             }
8712996ffadSFam Zheng         } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
872d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
873244a5668SFam Zheng             if (ret) {
874797e3e38SDavid Edmondson                 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
875244a5668SFam Zheng                 return ret;
8762996ffadSFam Zheng             } else if (s) {
8772996ffadSFam Zheng                 s->locked_perm &= ~bit;
878244a5668SFam Zheng             }
879244a5668SFam Zheng         }
880244a5668SFam Zheng     }
881244a5668SFam Zheng     PERM_FOREACH(i) {
882244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
8832996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8842996ffadSFam Zheng         if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
885d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
886244a5668SFam Zheng             if (ret) {
887797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
888797e3e38SDavid Edmondson                                           off);
889244a5668SFam Zheng                 return ret;
8902996ffadSFam Zheng             } else if (s) {
8912996ffadSFam Zheng                 s->locked_shared_perm |= bit;
892244a5668SFam Zheng             }
8932996ffadSFam Zheng         } else if (unlock && (locked_shared_perm & bit) &&
8942996ffadSFam Zheng                    !(shared_perm_lock_bits & bit)) {
895d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
896244a5668SFam Zheng             if (ret) {
897797e3e38SDavid Edmondson                 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
898244a5668SFam Zheng                 return ret;
8992996ffadSFam Zheng             } else if (s) {
9002996ffadSFam Zheng                 s->locked_shared_perm &= ~bit;
901244a5668SFam Zheng             }
902244a5668SFam Zheng         }
903244a5668SFam Zheng     }
904244a5668SFam Zheng     return 0;
905244a5668SFam Zheng }
906244a5668SFam Zheng 
907244a5668SFam Zheng /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
908d0a96155SMax Reitz static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
909244a5668SFam Zheng                                 Error **errp)
910244a5668SFam Zheng {
911244a5668SFam Zheng     int ret;
912244a5668SFam Zheng     int i;
913244a5668SFam Zheng 
914244a5668SFam Zheng     PERM_FOREACH(i) {
915244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
916244a5668SFam Zheng         uint64_t p = 1ULL << i;
917244a5668SFam Zheng         if (perm & p) {
918d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
919244a5668SFam Zheng             if (ret) {
920244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
921797e3e38SDavid Edmondson 
922797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret,
923244a5668SFam Zheng                                           "Failed to get \"%s\" lock",
924244a5668SFam Zheng                                           perm_name);
925244a5668SFam Zheng                 g_free(perm_name);
926244a5668SFam Zheng                 return ret;
927244a5668SFam Zheng             }
928244a5668SFam Zheng         }
929244a5668SFam Zheng     }
930244a5668SFam Zheng     PERM_FOREACH(i) {
931244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
932244a5668SFam Zheng         uint64_t p = 1ULL << i;
933244a5668SFam Zheng         if (!(shared_perm & p)) {
934d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
935244a5668SFam Zheng             if (ret) {
936244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
937797e3e38SDavid Edmondson 
938797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret,
939244a5668SFam Zheng                                           "Failed to get shared \"%s\" lock",
940244a5668SFam Zheng                                           perm_name);
941244a5668SFam Zheng                 g_free(perm_name);
942244a5668SFam Zheng                 return ret;
943244a5668SFam Zheng             }
944244a5668SFam Zheng         }
945244a5668SFam Zheng     }
946244a5668SFam Zheng     return 0;
947244a5668SFam Zheng }
948244a5668SFam Zheng 
949244a5668SFam Zheng static int raw_handle_perm_lock(BlockDriverState *bs,
950244a5668SFam Zheng                                 RawPermLockOp op,
951244a5668SFam Zheng                                 uint64_t new_perm, uint64_t new_shared,
952244a5668SFam Zheng                                 Error **errp)
953244a5668SFam Zheng {
954244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
955244a5668SFam Zheng     int ret = 0;
956244a5668SFam Zheng     Error *local_err = NULL;
957244a5668SFam Zheng 
958244a5668SFam Zheng     if (!s->use_lock) {
959244a5668SFam Zheng         return 0;
960244a5668SFam Zheng     }
961244a5668SFam Zheng 
962244a5668SFam Zheng     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
963244a5668SFam Zheng         return 0;
964244a5668SFam Zheng     }
965244a5668SFam Zheng 
966244a5668SFam Zheng     switch (op) {
967244a5668SFam Zheng     case RAW_PL_PREPARE:
968696aaaedSVladimir Sementsov-Ogievskiy         if ((s->perm | new_perm) == s->perm &&
969696aaaedSVladimir Sementsov-Ogievskiy             (s->shared_perm & new_shared) == s->shared_perm)
970696aaaedSVladimir Sementsov-Ogievskiy         {
971696aaaedSVladimir Sementsov-Ogievskiy             /*
972696aaaedSVladimir Sementsov-Ogievskiy              * We are going to unlock bytes, it should not fail. If it fail due
973696aaaedSVladimir Sementsov-Ogievskiy              * to some fs-dependent permission-unrelated reasons (which occurs
974696aaaedSVladimir Sementsov-Ogievskiy              * sometimes on NFS and leads to abort in bdrv_replace_child) we
975696aaaedSVladimir Sementsov-Ogievskiy              * can't prevent such errors by any check here. And we ignore them
976696aaaedSVladimir Sementsov-Ogievskiy              * anyway in ABORT and COMMIT.
977696aaaedSVladimir Sementsov-Ogievskiy              */
978696aaaedSVladimir Sementsov-Ogievskiy             return 0;
979696aaaedSVladimir Sementsov-Ogievskiy         }
980f2e3af29SFam Zheng         ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
981244a5668SFam Zheng                                    ~s->shared_perm | ~new_shared,
982244a5668SFam Zheng                                    false, errp);
983244a5668SFam Zheng         if (!ret) {
984f2e3af29SFam Zheng             ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
985244a5668SFam Zheng             if (!ret) {
986244a5668SFam Zheng                 return 0;
987244a5668SFam Zheng             }
988b857431dSFam Zheng             error_append_hint(errp,
989b857431dSFam Zheng                               "Is another process using the image [%s]?\n",
990b857431dSFam Zheng                               bs->filename);
991244a5668SFam Zheng         }
992244a5668SFam Zheng         /* fall through to unlock bytes. */
993244a5668SFam Zheng     case RAW_PL_ABORT:
994f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
995d0a96155SMax Reitz                              true, &local_err);
996244a5668SFam Zheng         if (local_err) {
997244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
998244a5668SFam Zheng              * fail. Something weird happened, report it.
999244a5668SFam Zheng              */
1000db0754dfSFam Zheng             warn_report_err(local_err);
1001244a5668SFam Zheng         }
1002244a5668SFam Zheng         break;
1003244a5668SFam Zheng     case RAW_PL_COMMIT:
1004f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
1005d0a96155SMax Reitz                              true, &local_err);
1006244a5668SFam Zheng         if (local_err) {
1007244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
1008244a5668SFam Zheng              * fail. Something weird happened, report it.
1009244a5668SFam Zheng              */
1010db0754dfSFam Zheng             warn_report_err(local_err);
1011244a5668SFam Zheng         }
1012244a5668SFam Zheng         break;
1013244a5668SFam Zheng     }
1014244a5668SFam Zheng     return ret;
1015244a5668SFam Zheng }
1016244a5668SFam Zheng 
1017ad24b679SMarc-André Lureau /* Sets a specific flag */
1018ad24b679SMarc-André Lureau static int fcntl_setfl(int fd, int flag)
1019ad24b679SMarc-André Lureau {
1020ad24b679SMarc-André Lureau     int flags;
1021ad24b679SMarc-André Lureau 
1022ad24b679SMarc-André Lureau     flags = fcntl(fd, F_GETFL);
1023ad24b679SMarc-André Lureau     if (flags == -1) {
1024ad24b679SMarc-André Lureau         return -errno;
1025ad24b679SMarc-André Lureau     }
1026ad24b679SMarc-André Lureau     if (fcntl(fd, F_SETFL, flags | flag) == -1) {
1027ad24b679SMarc-André Lureau         return -errno;
1028ad24b679SMarc-André Lureau     }
1029ad24b679SMarc-André Lureau     return 0;
1030ad24b679SMarc-André Lureau }
1031ad24b679SMarc-André Lureau 
10325cec2870SKevin Wolf static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
103323dece19SKevin Wolf                                  int *open_flags, uint64_t perm, bool force_dup,
10346ceabe6fSKevin Wolf                                  Error **errp)
10355cec2870SKevin Wolf {
10365cec2870SKevin Wolf     BDRVRawState *s = bs->opaque;
10375cec2870SKevin Wolf     int fd = -1;
10385cec2870SKevin Wolf     int ret;
103923dece19SKevin Wolf     bool has_writers = perm &
104023dece19SKevin Wolf         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
10415cec2870SKevin Wolf     int fcntl_flags = O_APPEND | O_NONBLOCK;
10425cec2870SKevin Wolf #ifdef O_NOATIME
10435cec2870SKevin Wolf     fcntl_flags |= O_NOATIME;
10445cec2870SKevin Wolf #endif
10455cec2870SKevin Wolf 
10465cec2870SKevin Wolf     *open_flags = 0;
10475cec2870SKevin Wolf     if (s->type == FTYPE_CD) {
10485cec2870SKevin Wolf         *open_flags |= O_NONBLOCK;
10495cec2870SKevin Wolf     }
10505cec2870SKevin Wolf 
105123dece19SKevin Wolf     raw_parse_flags(flags, open_flags, has_writers);
10525cec2870SKevin Wolf 
10535cec2870SKevin Wolf #ifdef O_ASYNC
10545cec2870SKevin Wolf     /* Not all operating systems have O_ASYNC, and those that don't
10555cec2870SKevin Wolf      * will not let us track the state into rs->open_flags (typically
10565cec2870SKevin Wolf      * you achieve the same effect with an ioctl, for example I_SETSIG
10575cec2870SKevin Wolf      * on Solaris). But we do not use O_ASYNC, so that's fine.
10585cec2870SKevin Wolf      */
10595cec2870SKevin Wolf     assert((s->open_flags & O_ASYNC) == 0);
10605cec2870SKevin Wolf #endif
10615cec2870SKevin Wolf 
10626ceabe6fSKevin Wolf     if (!force_dup && *open_flags == s->open_flags) {
10636ceabe6fSKevin Wolf         /* We're lucky, the existing fd is fine */
10646ceabe6fSKevin Wolf         return s->fd;
10656ceabe6fSKevin Wolf     }
10666ceabe6fSKevin Wolf 
10675cec2870SKevin Wolf     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
10685cec2870SKevin Wolf         /* dup the original fd */
10695cec2870SKevin Wolf         fd = qemu_dup(s->fd);
10705cec2870SKevin Wolf         if (fd >= 0) {
10715cec2870SKevin Wolf             ret = fcntl_setfl(fd, *open_flags);
10725cec2870SKevin Wolf             if (ret) {
10735cec2870SKevin Wolf                 qemu_close(fd);
10745cec2870SKevin Wolf                 fd = -1;
10755cec2870SKevin Wolf             }
10765cec2870SKevin Wolf         }
10775cec2870SKevin Wolf     }
10785cec2870SKevin Wolf 
1079b18a24a9SDaniel P. Berrangé     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
10805cec2870SKevin Wolf     if (fd == -1) {
10815cec2870SKevin Wolf         const char *normalized_filename = bs->filename;
10825cec2870SKevin Wolf         ret = raw_normalize_devicepath(&normalized_filename, errp);
10835cec2870SKevin Wolf         if (ret >= 0) {
1084b18a24a9SDaniel P. Berrangé             fd = qemu_open(normalized_filename, *open_flags, errp);
10855cec2870SKevin Wolf             if (fd == -1) {
10865cec2870SKevin Wolf                 return -1;
10875cec2870SKevin Wolf             }
10885cec2870SKevin Wolf         }
10895cec2870SKevin Wolf     }
10905cec2870SKevin Wolf 
1091bca5283bSKevin Wolf     if (fd != -1 && (*open_flags & O_RDWR)) {
1092bca5283bSKevin Wolf         ret = check_hdev_writable(fd);
1093bca5283bSKevin Wolf         if (ret < 0) {
1094bca5283bSKevin Wolf             qemu_close(fd);
1095bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
1096bca5283bSKevin Wolf             return -1;
1097bca5283bSKevin Wolf         }
1098bca5283bSKevin Wolf     }
1099bca5283bSKevin Wolf 
11005cec2870SKevin Wolf     return fd;
11015cec2870SKevin Wolf }
11025cec2870SKevin Wolf 
1103c1bb86cdSEric Blake static int raw_reopen_prepare(BDRVReopenState *state,
1104c1bb86cdSEric Blake                               BlockReopenQueue *queue, Error **errp)
1105c1bb86cdSEric Blake {
1106c1bb86cdSEric Blake     BDRVRawState *s;
1107c1bb86cdSEric Blake     BDRVRawReopenState *rs;
110831be8a2aSStefan Hajnoczi     QemuOpts *opts;
1109a6aeca0cSKevin Wolf     int ret;
1110c1bb86cdSEric Blake 
1111c1bb86cdSEric Blake     assert(state != NULL);
1112c1bb86cdSEric Blake     assert(state->bs != NULL);
1113c1bb86cdSEric Blake 
1114c1bb86cdSEric Blake     s = state->bs->opaque;
1115c1bb86cdSEric Blake 
1116c1bb86cdSEric Blake     state->opaque = g_new0(BDRVRawReopenState, 1);
1117c1bb86cdSEric Blake     rs = state->opaque;
111831be8a2aSStefan Hajnoczi 
111931be8a2aSStefan Hajnoczi     /* Handle options changes */
112031be8a2aSStefan Hajnoczi     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1121af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
112231be8a2aSStefan Hajnoczi         ret = -EINVAL;
112331be8a2aSStefan Hajnoczi         goto out;
112431be8a2aSStefan Hajnoczi     }
112531be8a2aSStefan Hajnoczi 
1126f357fcd8SStefan Hajnoczi     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
11278d324575SAlberto Garcia     rs->check_cache_dropped =
11288d324575SAlberto Garcia         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
11298d324575SAlberto Garcia 
11308d324575SAlberto Garcia     /* This driver's reopen function doesn't currently allow changing
11318d324575SAlberto Garcia      * other options, so let's put them back in the original QDict and
11328d324575SAlberto Garcia      * bdrv_reopen_prepare() will detect changes and complain. */
11338d324575SAlberto Garcia     qemu_opts_to_qdict(opts, state->options);
1134c1bb86cdSEric Blake 
113572373e40SVladimir Sementsov-Ogievskiy     /*
113672373e40SVladimir Sementsov-Ogievskiy      * As part of reopen prepare we also want to create new fd by
113772373e40SVladimir Sementsov-Ogievskiy      * raw_reconfigure_getfd(). But it wants updated "perm", when in
113872373e40SVladimir Sementsov-Ogievskiy      * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
113972373e40SVladimir Sementsov-Ogievskiy      * permission update. Happily, permission update is always a part (a seprate
114072373e40SVladimir Sementsov-Ogievskiy      * stage) of bdrv_reopen_multiple() so we can rely on this fact and
114172373e40SVladimir Sementsov-Ogievskiy      * reconfigure fd in raw_check_perm().
114272373e40SVladimir Sementsov-Ogievskiy      */
1143c1bb86cdSEric Blake 
1144e0c9cf3aSKevin Wolf     s->reopen_state = state;
1145a6aeca0cSKevin Wolf     ret = 0;
114672373e40SVladimir Sementsov-Ogievskiy 
114731be8a2aSStefan Hajnoczi out:
114831be8a2aSStefan Hajnoczi     qemu_opts_del(opts);
1149c1bb86cdSEric Blake     return ret;
1150c1bb86cdSEric Blake }
1151c1bb86cdSEric Blake 
1152c1bb86cdSEric Blake static void raw_reopen_commit(BDRVReopenState *state)
1153c1bb86cdSEric Blake {
1154c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1155c1bb86cdSEric Blake     BDRVRawState *s = state->bs->opaque;
1156c1bb86cdSEric Blake 
1157f357fcd8SStefan Hajnoczi     s->drop_cache = rs->drop_cache;
115831be8a2aSStefan Hajnoczi     s->check_cache_dropped = rs->check_cache_dropped;
1159c1bb86cdSEric Blake     s->open_flags = rs->open_flags;
1160c1bb86cdSEric Blake     g_free(state->opaque);
1161c1bb86cdSEric Blake     state->opaque = NULL;
1162e0c9cf3aSKevin Wolf 
1163e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1164e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1165c1bb86cdSEric Blake }
1166c1bb86cdSEric Blake 
1167c1bb86cdSEric Blake 
1168c1bb86cdSEric Blake static void raw_reopen_abort(BDRVReopenState *state)
1169c1bb86cdSEric Blake {
1170c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1171e0c9cf3aSKevin Wolf     BDRVRawState *s = state->bs->opaque;
1172c1bb86cdSEric Blake 
1173c1bb86cdSEric Blake      /* nothing to do if NULL, we didn't get far enough */
1174c1bb86cdSEric Blake     if (rs == NULL) {
1175c1bb86cdSEric Blake         return;
1176c1bb86cdSEric Blake     }
1177c1bb86cdSEric Blake 
1178c1bb86cdSEric Blake     g_free(state->opaque);
1179c1bb86cdSEric Blake     state->opaque = NULL;
1180e0c9cf3aSKevin Wolf 
1181e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1182e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1183c1bb86cdSEric Blake }
1184c1bb86cdSEric Blake 
118518473467SPaolo Bonzini static int hdev_get_max_hw_transfer(int fd, struct stat *st)
1186c1bb86cdSEric Blake {
1187c1bb86cdSEric Blake #ifdef BLKSECTGET
118818473467SPaolo Bonzini     if (S_ISBLK(st->st_mode)) {
118918473467SPaolo Bonzini         unsigned short max_sectors = 0;
119018473467SPaolo Bonzini         if (ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
119118473467SPaolo Bonzini             return max_sectors * 512;
119218473467SPaolo Bonzini         }
119318473467SPaolo Bonzini     } else {
119448265250SEric Farman         int max_bytes = 0;
1195867eccfeSMaxim Levitsky         if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
119648265250SEric Farman             return max_bytes;
1197c1bb86cdSEric Blake         }
119818473467SPaolo Bonzini     }
119918473467SPaolo Bonzini     return -errno;
1200c1bb86cdSEric Blake #else
1201c1bb86cdSEric Blake     return -ENOSYS;
1202c1bb86cdSEric Blake #endif
1203c1bb86cdSEric Blake }
1204c1bb86cdSEric Blake 
120518473467SPaolo Bonzini static int hdev_get_max_segments(int fd, struct stat *st)
12069103f1ceSFam Zheng {
12079103f1ceSFam Zheng #ifdef CONFIG_LINUX
12089103f1ceSFam Zheng     char buf[32];
12099103f1ceSFam Zheng     const char *end;
1210867eccfeSMaxim Levitsky     char *sysfspath = NULL;
12119103f1ceSFam Zheng     int ret;
1212867eccfeSMaxim Levitsky     int sysfd = -1;
12139103f1ceSFam Zheng     long max_segments;
1214867eccfeSMaxim Levitsky 
121518473467SPaolo Bonzini     if (S_ISCHR(st->st_mode)) {
12168ad5ab61SPaolo Bonzini         if (ioctl(fd, SG_GET_SG_TABLESIZE, &ret) == 0) {
12178ad5ab61SPaolo Bonzini             return ret;
12188ad5ab61SPaolo Bonzini         }
12198ad5ab61SPaolo Bonzini         return -ENOTSUP;
12208ad5ab61SPaolo Bonzini     }
12218ad5ab61SPaolo Bonzini 
122218473467SPaolo Bonzini     if (!S_ISBLK(st->st_mode)) {
12238ad5ab61SPaolo Bonzini         return -ENOTSUP;
12248ad5ab61SPaolo Bonzini     }
12258ad5ab61SPaolo Bonzini 
12269103f1ceSFam Zheng     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
122718473467SPaolo Bonzini                                 major(st->st_rdev), minor(st->st_rdev));
1228867eccfeSMaxim Levitsky     sysfd = open(sysfspath, O_RDONLY);
1229867eccfeSMaxim Levitsky     if (sysfd == -1) {
12309103f1ceSFam Zheng         ret = -errno;
12319103f1ceSFam Zheng         goto out;
12329103f1ceSFam Zheng     }
123337b0b24eSNikita Ivanov     ret = RETRY_ON_EINTR(read(sysfd, buf, sizeof(buf) - 1));
12349103f1ceSFam Zheng     if (ret < 0) {
12359103f1ceSFam Zheng         ret = -errno;
12369103f1ceSFam Zheng         goto out;
12379103f1ceSFam Zheng     } else if (ret == 0) {
12389103f1ceSFam Zheng         ret = -EIO;
12399103f1ceSFam Zheng         goto out;
12409103f1ceSFam Zheng     }
12419103f1ceSFam Zheng     buf[ret] = 0;
12429103f1ceSFam Zheng     /* The file is ended with '\n', pass 'end' to accept that. */
12439103f1ceSFam Zheng     ret = qemu_strtol(buf, &end, 10, &max_segments);
12449103f1ceSFam Zheng     if (ret == 0 && end && *end == '\n') {
12459103f1ceSFam Zheng         ret = max_segments;
12469103f1ceSFam Zheng     }
12479103f1ceSFam Zheng 
12489103f1ceSFam Zheng out:
1249867eccfeSMaxim Levitsky     if (sysfd != -1) {
1250867eccfeSMaxim Levitsky         close(sysfd);
1251fed414dfSFam Zheng     }
12529103f1ceSFam Zheng     g_free(sysfspath);
12539103f1ceSFam Zheng     return ret;
12549103f1ceSFam Zheng #else
12559103f1ceSFam Zheng     return -ENOTSUP;
12569103f1ceSFam Zheng #endif
12579103f1ceSFam Zheng }
12589103f1ceSFam Zheng 
1259c1bb86cdSEric Blake static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1260c1bb86cdSEric Blake {
1261c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
126218473467SPaolo Bonzini     struct stat st;
1263c1bb86cdSEric Blake 
12645dbd0ce1SKevin Wolf     s->needs_alignment = raw_needs_alignment(bs);
1265c1bb86cdSEric Blake     raw_probe_alignment(bs, s->fd, errp);
12665dbd0ce1SKevin Wolf 
1267c1bb86cdSEric Blake     bs->bl.min_mem_alignment = s->buf_align;
12688e3b0cbbSMarc-André Lureau     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size());
126918473467SPaolo Bonzini 
127018473467SPaolo Bonzini     /*
127118473467SPaolo Bonzini      * Maximum transfers are best effort, so it is okay to ignore any
127218473467SPaolo Bonzini      * errors.  That said, based on the man page errors in fstat would be
127318473467SPaolo Bonzini      * very much unexpected; the only possible case seems to be ENOMEM.
127418473467SPaolo Bonzini      */
127518473467SPaolo Bonzini     if (fstat(s->fd, &st)) {
127618473467SPaolo Bonzini         return;
127718473467SPaolo Bonzini     }
127818473467SPaolo Bonzini 
12790dfc7af2SAkihiko Odaki #if defined(__APPLE__) && (__MACH__)
12800dfc7af2SAkihiko Odaki     struct statfs buf;
12810dfc7af2SAkihiko Odaki 
12820dfc7af2SAkihiko Odaki     if (!fstatfs(s->fd, &buf)) {
12830dfc7af2SAkihiko Odaki         bs->bl.opt_transfer = buf.f_iosize;
12840dfc7af2SAkihiko Odaki         bs->bl.pdiscard_alignment = buf.f_bsize;
12850dfc7af2SAkihiko Odaki     }
12860dfc7af2SAkihiko Odaki #endif
12870dfc7af2SAkihiko Odaki 
1288006e1962SDenis V. Lunev     if (bdrv_is_sg(bs) || S_ISBLK(st.st_mode)) {
128918473467SPaolo Bonzini         int ret = hdev_get_max_hw_transfer(s->fd, &st);
129018473467SPaolo Bonzini 
129118473467SPaolo Bonzini         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
129218473467SPaolo Bonzini             bs->bl.max_hw_transfer = ret;
129318473467SPaolo Bonzini         }
129418473467SPaolo Bonzini 
129518473467SPaolo Bonzini         ret = hdev_get_max_segments(s->fd, &st);
129618473467SPaolo Bonzini         if (ret > 0) {
1297cc071629SPaolo Bonzini             bs->bl.max_hw_iov = ret;
129818473467SPaolo Bonzini         }
129918473467SPaolo Bonzini     }
1300c1bb86cdSEric Blake }
1301c1bb86cdSEric Blake 
1302c1bb86cdSEric Blake static int check_for_dasd(int fd)
1303c1bb86cdSEric Blake {
1304c1bb86cdSEric Blake #ifdef BIODASDINFO2
1305c1bb86cdSEric Blake     struct dasd_information2_t info = {0};
1306c1bb86cdSEric Blake 
1307c1bb86cdSEric Blake     return ioctl(fd, BIODASDINFO2, &info);
1308c1bb86cdSEric Blake #else
1309c1bb86cdSEric Blake     return -1;
1310c1bb86cdSEric Blake #endif
1311c1bb86cdSEric Blake }
1312c1bb86cdSEric Blake 
1313c1bb86cdSEric Blake /**
1314c1bb86cdSEric Blake  * Try to get @bs's logical and physical block size.
1315c1bb86cdSEric Blake  * On success, store them in @bsz and return zero.
1316c1bb86cdSEric Blake  * On failure, return negative errno.
1317c1bb86cdSEric Blake  */
1318c1bb86cdSEric Blake static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1319c1bb86cdSEric Blake {
1320c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1321c1bb86cdSEric Blake     int ret;
1322c1bb86cdSEric Blake 
1323c1bb86cdSEric Blake     /* If DASD, get blocksizes */
1324c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1325c1bb86cdSEric Blake         return -ENOTSUP;
1326c1bb86cdSEric Blake     }
1327c1bb86cdSEric Blake     ret = probe_logical_blocksize(s->fd, &bsz->log);
1328c1bb86cdSEric Blake     if (ret < 0) {
1329c1bb86cdSEric Blake         return ret;
1330c1bb86cdSEric Blake     }
1331c1bb86cdSEric Blake     return probe_physical_blocksize(s->fd, &bsz->phys);
1332c1bb86cdSEric Blake }
1333c1bb86cdSEric Blake 
1334c1bb86cdSEric Blake /**
1335c1bb86cdSEric Blake  * Try to get @bs's geometry: cyls, heads, sectors.
1336c1bb86cdSEric Blake  * On success, store them in @geo and return 0.
1337c1bb86cdSEric Blake  * On failure return -errno.
1338c1bb86cdSEric Blake  * (Allows block driver to assign default geometry values that guest sees)
1339c1bb86cdSEric Blake  */
1340c1bb86cdSEric Blake #ifdef __linux__
1341c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1342c1bb86cdSEric Blake {
1343c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1344c1bb86cdSEric Blake     struct hd_geometry ioctl_geo = {0};
1345c1bb86cdSEric Blake 
1346c1bb86cdSEric Blake     /* If DASD, get its geometry */
1347c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1348c1bb86cdSEric Blake         return -ENOTSUP;
1349c1bb86cdSEric Blake     }
1350c1bb86cdSEric Blake     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1351c1bb86cdSEric Blake         return -errno;
1352c1bb86cdSEric Blake     }
1353c1bb86cdSEric Blake     /* HDIO_GETGEO may return success even though geo contains zeros
1354c1bb86cdSEric Blake        (e.g. certain multipath setups) */
1355c1bb86cdSEric Blake     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1356c1bb86cdSEric Blake         return -ENOTSUP;
1357c1bb86cdSEric Blake     }
1358c1bb86cdSEric Blake     /* Do not return a geometry for partition */
1359c1bb86cdSEric Blake     if (ioctl_geo.start != 0) {
1360c1bb86cdSEric Blake         return -ENOTSUP;
1361c1bb86cdSEric Blake     }
1362c1bb86cdSEric Blake     geo->heads = ioctl_geo.heads;
1363c1bb86cdSEric Blake     geo->sectors = ioctl_geo.sectors;
1364c1bb86cdSEric Blake     geo->cylinders = ioctl_geo.cylinders;
1365c1bb86cdSEric Blake 
1366c1bb86cdSEric Blake     return 0;
1367c1bb86cdSEric Blake }
1368c1bb86cdSEric Blake #else /* __linux__ */
1369c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1370c1bb86cdSEric Blake {
1371c1bb86cdSEric Blake     return -ENOTSUP;
1372c1bb86cdSEric Blake }
1373c1bb86cdSEric Blake #endif
1374c1bb86cdSEric Blake 
137503425671SKevin Wolf #if defined(__linux__)
137603425671SKevin Wolf static int handle_aiocb_ioctl(void *opaque)
1377c1bb86cdSEric Blake {
137803425671SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1379c1bb86cdSEric Blake     int ret;
1380c1bb86cdSEric Blake 
138137b0b24eSNikita Ivanov     ret = RETRY_ON_EINTR(
138237b0b24eSNikita Ivanov         ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf)
138337b0b24eSNikita Ivanov     );
1384c1bb86cdSEric Blake     if (ret == -1) {
1385c1bb86cdSEric Blake         return -errno;
1386c1bb86cdSEric Blake     }
1387c1bb86cdSEric Blake 
1388c1bb86cdSEric Blake     return 0;
1389c1bb86cdSEric Blake }
139003425671SKevin Wolf #endif /* linux */
1391c1bb86cdSEric Blake 
139206dc9bd5SKevin Wolf static int handle_aiocb_flush(void *opaque)
1393c1bb86cdSEric Blake {
139406dc9bd5SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1395e5bcf967SKevin Wolf     BDRVRawState *s = aiocb->bs->opaque;
1396c1bb86cdSEric Blake     int ret;
1397c1bb86cdSEric Blake 
1398e5bcf967SKevin Wolf     if (s->page_cache_inconsistent) {
1399c7ddc882SDaniel P. Berrangé         return -s->page_cache_inconsistent;
1400e5bcf967SKevin Wolf     }
1401e5bcf967SKevin Wolf 
1402c1bb86cdSEric Blake     ret = qemu_fdatasync(aiocb->aio_fildes);
1403c1bb86cdSEric Blake     if (ret == -1) {
140460ff2ae2SDaniel P. Berrangé         trace_file_flush_fdatasync_failed(errno);
140560ff2ae2SDaniel P. Berrangé 
1406e5bcf967SKevin Wolf         /* There is no clear definition of the semantics of a failing fsync(),
1407e5bcf967SKevin Wolf          * so we may have to assume the worst. The sad truth is that this
1408e5bcf967SKevin Wolf          * assumption is correct for Linux. Some pages are now probably marked
1409e5bcf967SKevin Wolf          * clean in the page cache even though they are inconsistent with the
1410e5bcf967SKevin Wolf          * on-disk contents. The next fdatasync() call would succeed, but no
1411e5bcf967SKevin Wolf          * further writeback attempt will be made. We can't get back to a state
1412e5bcf967SKevin Wolf          * in which we know what is on disk (we would have to rewrite
1413e5bcf967SKevin Wolf          * everything that was touched since the last fdatasync() at least), so
1414e5bcf967SKevin Wolf          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1415e5bcf967SKevin Wolf          * really defined, I have little hope that other OSes are doing better.
1416e5bcf967SKevin Wolf          *
1417e5bcf967SKevin Wolf          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1418e5bcf967SKevin Wolf          * cache. */
1419e5bcf967SKevin Wolf         if ((s->open_flags & O_DIRECT) == 0) {
1420c7ddc882SDaniel P. Berrangé             s->page_cache_inconsistent = errno;
1421e5bcf967SKevin Wolf         }
1422c1bb86cdSEric Blake         return -errno;
1423c1bb86cdSEric Blake     }
1424c1bb86cdSEric Blake     return 0;
1425c1bb86cdSEric Blake }
1426c1bb86cdSEric Blake 
1427c1bb86cdSEric Blake #ifdef CONFIG_PREADV
1428c1bb86cdSEric Blake 
1429c1bb86cdSEric Blake static bool preadv_present = true;
1430c1bb86cdSEric Blake 
1431c1bb86cdSEric Blake static ssize_t
1432c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1433c1bb86cdSEric Blake {
1434c1bb86cdSEric Blake     return preadv(fd, iov, nr_iov, offset);
1435c1bb86cdSEric Blake }
1436c1bb86cdSEric Blake 
1437c1bb86cdSEric Blake static ssize_t
1438c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1439c1bb86cdSEric Blake {
1440c1bb86cdSEric Blake     return pwritev(fd, iov, nr_iov, offset);
1441c1bb86cdSEric Blake }
1442c1bb86cdSEric Blake 
1443c1bb86cdSEric Blake #else
1444c1bb86cdSEric Blake 
1445c1bb86cdSEric Blake static bool preadv_present = false;
1446c1bb86cdSEric Blake 
1447c1bb86cdSEric Blake static ssize_t
1448c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1449c1bb86cdSEric Blake {
1450c1bb86cdSEric Blake     return -ENOSYS;
1451c1bb86cdSEric Blake }
1452c1bb86cdSEric Blake 
1453c1bb86cdSEric Blake static ssize_t
1454c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1455c1bb86cdSEric Blake {
1456c1bb86cdSEric Blake     return -ENOSYS;
1457c1bb86cdSEric Blake }
1458c1bb86cdSEric Blake 
1459c1bb86cdSEric Blake #endif
1460c1bb86cdSEric Blake 
1461c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1462c1bb86cdSEric Blake {
1463c1bb86cdSEric Blake     ssize_t len;
1464c1bb86cdSEric Blake 
146537b0b24eSNikita Ivanov     len = RETRY_ON_EINTR(
146637b0b24eSNikita Ivanov         (aiocb->aio_type & QEMU_AIO_WRITE) ?
146737b0b24eSNikita Ivanov             qemu_pwritev(aiocb->aio_fildes,
1468d57c44d0SKevin Wolf                            aiocb->io.iov,
1469d57c44d0SKevin Wolf                            aiocb->io.niov,
147037b0b24eSNikita Ivanov                            aiocb->aio_offset) :
147137b0b24eSNikita Ivanov             qemu_preadv(aiocb->aio_fildes,
1472d57c44d0SKevin Wolf                           aiocb->io.iov,
1473d57c44d0SKevin Wolf                           aiocb->io.niov,
147437b0b24eSNikita Ivanov                           aiocb->aio_offset)
147537b0b24eSNikita Ivanov     );
1476c1bb86cdSEric Blake 
1477c1bb86cdSEric Blake     if (len == -1) {
1478c1bb86cdSEric Blake         return -errno;
1479c1bb86cdSEric Blake     }
1480c1bb86cdSEric Blake     return len;
1481c1bb86cdSEric Blake }
1482c1bb86cdSEric Blake 
1483c1bb86cdSEric Blake /*
1484c1bb86cdSEric Blake  * Read/writes the data to/from a given linear buffer.
1485c1bb86cdSEric Blake  *
1486c1bb86cdSEric Blake  * Returns the number of bytes handles or -errno in case of an error. Short
1487c1bb86cdSEric Blake  * reads are only returned if the end of the file is reached.
1488c1bb86cdSEric Blake  */
1489c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1490c1bb86cdSEric Blake {
1491c1bb86cdSEric Blake     ssize_t offset = 0;
1492c1bb86cdSEric Blake     ssize_t len;
1493c1bb86cdSEric Blake 
1494c1bb86cdSEric Blake     while (offset < aiocb->aio_nbytes) {
1495c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1496c1bb86cdSEric Blake             len = pwrite(aiocb->aio_fildes,
1497c1bb86cdSEric Blake                          (const char *)buf + offset,
1498c1bb86cdSEric Blake                          aiocb->aio_nbytes - offset,
1499c1bb86cdSEric Blake                          aiocb->aio_offset + offset);
1500c1bb86cdSEric Blake         } else {
1501c1bb86cdSEric Blake             len = pread(aiocb->aio_fildes,
1502c1bb86cdSEric Blake                         buf + offset,
1503c1bb86cdSEric Blake                         aiocb->aio_nbytes - offset,
1504c1bb86cdSEric Blake                         aiocb->aio_offset + offset);
1505c1bb86cdSEric Blake         }
1506c1bb86cdSEric Blake         if (len == -1 && errno == EINTR) {
1507c1bb86cdSEric Blake             continue;
1508c1bb86cdSEric Blake         } else if (len == -1 && errno == EINVAL &&
1509c1bb86cdSEric Blake                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1510c1bb86cdSEric Blake                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1511c1bb86cdSEric Blake                    offset > 0) {
1512c1bb86cdSEric Blake             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1513c1bb86cdSEric Blake              * after a short read.  Assume that O_DIRECT short reads only occur
1514c1bb86cdSEric Blake              * at EOF.  Therefore this is a short read, not an I/O error.
1515c1bb86cdSEric Blake              */
1516c1bb86cdSEric Blake             break;
1517c1bb86cdSEric Blake         } else if (len == -1) {
1518c1bb86cdSEric Blake             offset = -errno;
1519c1bb86cdSEric Blake             break;
1520c1bb86cdSEric Blake         } else if (len == 0) {
1521c1bb86cdSEric Blake             break;
1522c1bb86cdSEric Blake         }
1523c1bb86cdSEric Blake         offset += len;
1524c1bb86cdSEric Blake     }
1525c1bb86cdSEric Blake 
1526c1bb86cdSEric Blake     return offset;
1527c1bb86cdSEric Blake }
1528c1bb86cdSEric Blake 
1529999e6b69SKevin Wolf static int handle_aiocb_rw(void *opaque)
1530c1bb86cdSEric Blake {
1531999e6b69SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1532c1bb86cdSEric Blake     ssize_t nbytes;
1533c1bb86cdSEric Blake     char *buf;
1534c1bb86cdSEric Blake 
1535c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1536c1bb86cdSEric Blake         /*
1537c1bb86cdSEric Blake          * If there is just a single buffer, and it is properly aligned
1538c1bb86cdSEric Blake          * we can just use plain pread/pwrite without any problems.
1539c1bb86cdSEric Blake          */
1540d57c44d0SKevin Wolf         if (aiocb->io.niov == 1) {
154154c7ca1bSKevin Wolf             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
154254c7ca1bSKevin Wolf             goto out;
1543c1bb86cdSEric Blake         }
1544c1bb86cdSEric Blake         /*
1545c1bb86cdSEric Blake          * We have more than one iovec, and all are properly aligned.
1546c1bb86cdSEric Blake          *
1547c1bb86cdSEric Blake          * Try preadv/pwritev first and fall back to linearizing the
1548c1bb86cdSEric Blake          * buffer if it's not supported.
1549c1bb86cdSEric Blake          */
1550c1bb86cdSEric Blake         if (preadv_present) {
1551c1bb86cdSEric Blake             nbytes = handle_aiocb_rw_vector(aiocb);
1552c1bb86cdSEric Blake             if (nbytes == aiocb->aio_nbytes ||
1553c1bb86cdSEric Blake                 (nbytes < 0 && nbytes != -ENOSYS)) {
155454c7ca1bSKevin Wolf                 goto out;
1555c1bb86cdSEric Blake             }
1556c1bb86cdSEric Blake             preadv_present = false;
1557c1bb86cdSEric Blake         }
1558c1bb86cdSEric Blake 
1559c1bb86cdSEric Blake         /*
1560c1bb86cdSEric Blake          * XXX(hch): short read/write.  no easy way to handle the reminder
1561c1bb86cdSEric Blake          * using these interfaces.  For now retry using plain
1562c1bb86cdSEric Blake          * pread/pwrite?
1563c1bb86cdSEric Blake          */
1564c1bb86cdSEric Blake     }
1565c1bb86cdSEric Blake 
1566c1bb86cdSEric Blake     /*
1567c1bb86cdSEric Blake      * Ok, we have to do it the hard way, copy all segments into
1568c1bb86cdSEric Blake      * a single aligned buffer.
1569c1bb86cdSEric Blake      */
1570c1bb86cdSEric Blake     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1571c1bb86cdSEric Blake     if (buf == NULL) {
157254c7ca1bSKevin Wolf         nbytes = -ENOMEM;
157354c7ca1bSKevin Wolf         goto out;
1574c1bb86cdSEric Blake     }
1575c1bb86cdSEric Blake 
1576c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1577c1bb86cdSEric Blake         char *p = buf;
1578c1bb86cdSEric Blake         int i;
1579c1bb86cdSEric Blake 
1580d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov; ++i) {
1581d57c44d0SKevin Wolf             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1582d57c44d0SKevin Wolf             p += aiocb->io.iov[i].iov_len;
1583c1bb86cdSEric Blake         }
1584c1bb86cdSEric Blake         assert(p - buf == aiocb->aio_nbytes);
1585c1bb86cdSEric Blake     }
1586c1bb86cdSEric Blake 
1587c1bb86cdSEric Blake     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1588c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1589c1bb86cdSEric Blake         char *p = buf;
1590c1bb86cdSEric Blake         size_t count = aiocb->aio_nbytes, copy;
1591c1bb86cdSEric Blake         int i;
1592c1bb86cdSEric Blake 
1593d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov && count; ++i) {
1594c1bb86cdSEric Blake             copy = count;
1595d57c44d0SKevin Wolf             if (copy > aiocb->io.iov[i].iov_len) {
1596d57c44d0SKevin Wolf                 copy = aiocb->io.iov[i].iov_len;
1597c1bb86cdSEric Blake             }
1598d57c44d0SKevin Wolf             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1599c1bb86cdSEric Blake             assert(count >= copy);
1600c1bb86cdSEric Blake             p     += copy;
1601c1bb86cdSEric Blake             count -= copy;
1602c1bb86cdSEric Blake         }
1603c1bb86cdSEric Blake         assert(count == 0);
1604c1bb86cdSEric Blake     }
1605c1bb86cdSEric Blake     qemu_vfree(buf);
1606c1bb86cdSEric Blake 
160754c7ca1bSKevin Wolf out:
160854c7ca1bSKevin Wolf     if (nbytes == aiocb->aio_nbytes) {
160954c7ca1bSKevin Wolf         return 0;
161054c7ca1bSKevin Wolf     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
161154c7ca1bSKevin Wolf         if (aiocb->aio_type & QEMU_AIO_WRITE) {
161254c7ca1bSKevin Wolf             return -EINVAL;
161354c7ca1bSKevin Wolf         } else {
161454c7ca1bSKevin Wolf             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
161554c7ca1bSKevin Wolf                       0, aiocb->aio_nbytes - nbytes);
161654c7ca1bSKevin Wolf             return 0;
161754c7ca1bSKevin Wolf         }
161854c7ca1bSKevin Wolf     } else {
161954c7ca1bSKevin Wolf         assert(nbytes < 0);
1620c1bb86cdSEric Blake         return nbytes;
1621c1bb86cdSEric Blake     }
162254c7ca1bSKevin Wolf }
1623c1bb86cdSEric Blake 
16240dfc7af2SAkihiko Odaki #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1625c1bb86cdSEric Blake static int translate_err(int err)
1626c1bb86cdSEric Blake {
1627c1bb86cdSEric Blake     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1628c1bb86cdSEric Blake         err == -ENOTTY) {
1629c1bb86cdSEric Blake         err = -ENOTSUP;
1630c1bb86cdSEric Blake     }
1631c1bb86cdSEric Blake     return err;
1632c1bb86cdSEric Blake }
16330dfc7af2SAkihiko Odaki #endif
1634c1bb86cdSEric Blake 
1635c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
1636c1bb86cdSEric Blake static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1637c1bb86cdSEric Blake {
1638c1bb86cdSEric Blake     do {
1639c1bb86cdSEric Blake         if (fallocate(fd, mode, offset, len) == 0) {
1640c1bb86cdSEric Blake             return 0;
1641c1bb86cdSEric Blake         }
1642c1bb86cdSEric Blake     } while (errno == EINTR);
1643c1bb86cdSEric Blake     return translate_err(-errno);
1644c1bb86cdSEric Blake }
1645c1bb86cdSEric Blake #endif
1646c1bb86cdSEric Blake 
1647c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1648c1bb86cdSEric Blake {
1649c1bb86cdSEric Blake     int ret = -ENOTSUP;
1650c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1651c1bb86cdSEric Blake 
1652c1bb86cdSEric Blake     if (!s->has_write_zeroes) {
1653c1bb86cdSEric Blake         return -ENOTSUP;
1654c1bb86cdSEric Blake     }
1655c1bb86cdSEric Blake 
1656c1bb86cdSEric Blake #ifdef BLKZEROOUT
1657738301e1SKevin Wolf     /* The BLKZEROOUT implementation in the kernel doesn't set
1658738301e1SKevin Wolf      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1659738301e1SKevin Wolf      * fallbacks. */
1660738301e1SKevin Wolf     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1661c1bb86cdSEric Blake         do {
1662c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1663c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1664c1bb86cdSEric Blake                 return 0;
1665c1bb86cdSEric Blake             }
1666c1bb86cdSEric Blake         } while (errno == EINTR);
1667c1bb86cdSEric Blake 
1668c1bb86cdSEric Blake         ret = translate_err(-errno);
1669c1bb86cdSEric Blake         if (ret == -ENOTSUP) {
1670c1bb86cdSEric Blake             s->has_write_zeroes = false;
1671c1bb86cdSEric Blake         }
1672effecce6SKevin Wolf     }
1673effecce6SKevin Wolf #endif
1674effecce6SKevin Wolf 
1675c1bb86cdSEric Blake     return ret;
1676c1bb86cdSEric Blake }
1677c1bb86cdSEric Blake 
16787154d8aeSKevin Wolf static int handle_aiocb_write_zeroes(void *opaque)
1679c1bb86cdSEric Blake {
16807154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
168170d9110bSDenis V. Lunev #ifdef CONFIG_FALLOCATE
1682b2c6f23fSMax Reitz     BDRVRawState *s = aiocb->bs->opaque;
168370d9110bSDenis V. Lunev     int64_t len;
168470d9110bSDenis V. Lunev #endif
1685c1bb86cdSEric Blake 
1686c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1687c1bb86cdSEric Blake         return handle_aiocb_write_zeroes_block(aiocb);
1688c1bb86cdSEric Blake     }
1689c1bb86cdSEric Blake 
1690c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1691c1bb86cdSEric Blake     if (s->has_write_zeroes) {
1692c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1693c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1694fa95e9fbSThomas Huth         if (ret == -ENOTSUP) {
1695fa95e9fbSThomas Huth             s->has_write_zeroes = false;
1696fa95e9fbSThomas Huth         } else if (ret == 0 || ret != -EINVAL) {
1697c1bb86cdSEric Blake             return ret;
1698c1bb86cdSEric Blake         }
1699fa95e9fbSThomas Huth         /*
1700fa95e9fbSThomas Huth          * Note: Some file systems do not like unaligned byte ranges, and
1701fa95e9fbSThomas Huth          * return EINVAL in such a case, though they should not do it according
1702fa95e9fbSThomas Huth          * to the man-page of fallocate(). Thus we simply ignore this return
1703fa95e9fbSThomas Huth          * value and try the other fallbacks instead.
1704fa95e9fbSThomas Huth          */
1705c1bb86cdSEric Blake     }
1706c1bb86cdSEric Blake #endif
1707c1bb86cdSEric Blake 
1708c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1709c1bb86cdSEric Blake     if (s->has_discard && s->has_fallocate) {
1710c1bb86cdSEric Blake         int ret = do_fallocate(s->fd,
1711c1bb86cdSEric Blake                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1712c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1713c1bb86cdSEric Blake         if (ret == 0) {
1714c1bb86cdSEric Blake             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1715c1bb86cdSEric Blake             if (ret == 0 || ret != -ENOTSUP) {
1716c1bb86cdSEric Blake                 return ret;
1717c1bb86cdSEric Blake             }
1718c1bb86cdSEric Blake             s->has_fallocate = false;
171973ebf297SThomas Huth         } else if (ret == -EINVAL) {
172073ebf297SThomas Huth             /*
172173ebf297SThomas Huth              * Some file systems like older versions of GPFS do not like un-
172273ebf297SThomas Huth              * aligned byte ranges, and return EINVAL in such a case, though
172373ebf297SThomas Huth              * they should not do it according to the man-page of fallocate().
172473ebf297SThomas Huth              * Warn about the bad filesystem and try the final fallback instead.
172573ebf297SThomas Huth              */
172673ebf297SThomas Huth             warn_report_once("Your file system is misbehaving: "
172773ebf297SThomas Huth                              "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
172868857f13SMichael Tokarev                              "Please report this bug to your file system "
172973ebf297SThomas Huth                              "vendor.");
1730c1bb86cdSEric Blake         } else if (ret != -ENOTSUP) {
1731c1bb86cdSEric Blake             return ret;
1732c1bb86cdSEric Blake         } else {
1733c1bb86cdSEric Blake             s->has_discard = false;
1734c1bb86cdSEric Blake         }
1735c1bb86cdSEric Blake     }
1736c1bb86cdSEric Blake #endif
1737c1bb86cdSEric Blake 
1738c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
173970d9110bSDenis V. Lunev     /* Last resort: we are trying to extend the file with zeroed data. This
174070d9110bSDenis V. Lunev      * can be done via fallocate(fd, 0) */
1741005ee3cdSEmanuele Giuseppe Esposito     len = raw_co_getlength(aiocb->bs);
174270d9110bSDenis V. Lunev     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1743c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1744c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1745c1bb86cdSEric Blake             return ret;
1746c1bb86cdSEric Blake         }
1747c1bb86cdSEric Blake         s->has_fallocate = false;
1748c1bb86cdSEric Blake     }
1749c1bb86cdSEric Blake #endif
1750c1bb86cdSEric Blake 
1751c1bb86cdSEric Blake     return -ENOTSUP;
1752c1bb86cdSEric Blake }
1753c1bb86cdSEric Blake 
17547154d8aeSKevin Wolf static int handle_aiocb_write_zeroes_unmap(void *opaque)
175534fa110eSKevin Wolf {
17567154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
175734fa110eSKevin Wolf     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
175834fa110eSKevin Wolf 
175934fa110eSKevin Wolf     /* First try to write zeros and unmap at the same time */
176034fa110eSKevin Wolf 
176134fa110eSKevin Wolf #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1762b3ac2b94SSimran Singhal     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
176334fa110eSKevin Wolf                            aiocb->aio_offset, aiocb->aio_nbytes);
1764bae127d4SAntoine Damhet     switch (ret) {
1765bae127d4SAntoine Damhet     case -ENOTSUP:
1766bae127d4SAntoine Damhet     case -EINVAL:
1767ece4fa91SMaxim Levitsky     case -EBUSY:
1768bae127d4SAntoine Damhet         break;
1769bae127d4SAntoine Damhet     default:
177034fa110eSKevin Wolf         return ret;
177134fa110eSKevin Wolf     }
177234fa110eSKevin Wolf #endif
177334fa110eSKevin Wolf 
177434fa110eSKevin Wolf     /* If we couldn't manage to unmap while guaranteed that the area reads as
177534fa110eSKevin Wolf      * all-zero afterwards, just write zeroes without unmapping */
1776b3ac2b94SSimran Singhal     return handle_aiocb_write_zeroes(aiocb);
177734fa110eSKevin Wolf }
177834fa110eSKevin Wolf 
17791efad060SFam Zheng #ifndef HAVE_COPY_FILE_RANGE
17801efad060SFam Zheng static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
17811efad060SFam Zheng                              off_t *out_off, size_t len, unsigned int flags)
17821efad060SFam Zheng {
17831efad060SFam Zheng #ifdef __NR_copy_file_range
17841efad060SFam Zheng     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
17851efad060SFam Zheng                    out_off, len, flags);
17861efad060SFam Zheng #else
17871efad060SFam Zheng     errno = ENOSYS;
17881efad060SFam Zheng     return -1;
17891efad060SFam Zheng #endif
17901efad060SFam Zheng }
17911efad060SFam Zheng #endif
17921efad060SFam Zheng 
179358a209c4SKevin Wolf static int handle_aiocb_copy_range(void *opaque)
17941efad060SFam Zheng {
179558a209c4SKevin Wolf     RawPosixAIOData *aiocb = opaque;
17961efad060SFam Zheng     uint64_t bytes = aiocb->aio_nbytes;
17971efad060SFam Zheng     off_t in_off = aiocb->aio_offset;
1798d57c44d0SKevin Wolf     off_t out_off = aiocb->copy_range.aio_offset2;
17991efad060SFam Zheng 
18001efad060SFam Zheng     while (bytes) {
18011efad060SFam Zheng         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
1802d57c44d0SKevin Wolf                                       aiocb->copy_range.aio_fd2, &out_off,
18031efad060SFam Zheng                                       bytes, 0);
1804ecc983a5SFam Zheng         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1805d57c44d0SKevin Wolf                                    aiocb->copy_range.aio_fd2, out_off, bytes,
1806d57c44d0SKevin Wolf                                    0, ret);
1807c436e3d0SFam Zheng         if (ret == 0) {
1808c436e3d0SFam Zheng             /* No progress (e.g. when beyond EOF), let the caller fall back to
1809c436e3d0SFam Zheng              * buffer I/O. */
1810c436e3d0SFam Zheng             return -ENOSPC;
18111efad060SFam Zheng         }
18121efad060SFam Zheng         if (ret < 0) {
1813c436e3d0SFam Zheng             switch (errno) {
1814c436e3d0SFam Zheng             case ENOSYS:
18151efad060SFam Zheng                 return -ENOTSUP;
1816c436e3d0SFam Zheng             case EINTR:
1817c436e3d0SFam Zheng                 continue;
1818c436e3d0SFam Zheng             default:
18191efad060SFam Zheng                 return -errno;
18201efad060SFam Zheng             }
18211efad060SFam Zheng         }
18221efad060SFam Zheng         bytes -= ret;
18231efad060SFam Zheng     }
18241efad060SFam Zheng     return 0;
18251efad060SFam Zheng }
18261efad060SFam Zheng 
182746ee0f46SKevin Wolf static int handle_aiocb_discard(void *opaque)
1828c1bb86cdSEric Blake {
182946ee0f46SKevin Wolf     RawPosixAIOData *aiocb = opaque;
183013a02833SAri Sundholm     int ret = -ENOTSUP;
1831c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1832c1bb86cdSEric Blake 
1833c1bb86cdSEric Blake     if (!s->has_discard) {
1834c1bb86cdSEric Blake         return -ENOTSUP;
1835c1bb86cdSEric Blake     }
1836c1bb86cdSEric Blake 
1837c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1838c1bb86cdSEric Blake #ifdef BLKDISCARD
1839c1bb86cdSEric Blake         do {
1840c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1841c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1842c1bb86cdSEric Blake                 return 0;
1843c1bb86cdSEric Blake             }
1844c1bb86cdSEric Blake         } while (errno == EINTR);
1845c1bb86cdSEric Blake 
18460dfc7af2SAkihiko Odaki         ret = translate_err(-errno);
1847c1bb86cdSEric Blake #endif
1848c1bb86cdSEric Blake     } else {
1849c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1850c1bb86cdSEric Blake         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1851c1bb86cdSEric Blake                            aiocb->aio_offset, aiocb->aio_nbytes);
185213a02833SAri Sundholm         ret = translate_err(ret);
18530dfc7af2SAkihiko Odaki #elif defined(__APPLE__) && (__MACH__)
18540dfc7af2SAkihiko Odaki         fpunchhole_t fpunchhole;
18550dfc7af2SAkihiko Odaki         fpunchhole.fp_flags = 0;
18560dfc7af2SAkihiko Odaki         fpunchhole.reserved = 0;
18570dfc7af2SAkihiko Odaki         fpunchhole.fp_offset = aiocb->aio_offset;
18580dfc7af2SAkihiko Odaki         fpunchhole.fp_length = aiocb->aio_nbytes;
18590dfc7af2SAkihiko Odaki         if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
18600dfc7af2SAkihiko Odaki             ret = errno == ENODEV ? -ENOTSUP : -errno;
18610dfc7af2SAkihiko Odaki         } else {
18620dfc7af2SAkihiko Odaki             ret = 0;
18630dfc7af2SAkihiko Odaki         }
1864c1bb86cdSEric Blake #endif
1865c1bb86cdSEric Blake     }
1866c1bb86cdSEric Blake 
1867c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1868c1bb86cdSEric Blake         s->has_discard = false;
1869c1bb86cdSEric Blake     }
1870c1bb86cdSEric Blake     return ret;
1871c1bb86cdSEric Blake }
1872c1bb86cdSEric Blake 
18733a20013fSNir Soffer /*
18743a20013fSNir Soffer  * Help alignment probing by allocating the first block.
18753a20013fSNir Soffer  *
18763a20013fSNir Soffer  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
18773a20013fSNir Soffer  * reading succeeds regardless of request length. In this case we fallback to
18783a20013fSNir Soffer  * safe alignment which is not optimal. Allocating the first block avoids this
18793a20013fSNir Soffer  * fallback.
18803a20013fSNir Soffer  *
18813a20013fSNir Soffer  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
18823a20013fSNir Soffer  * request alignment, so we use safe values.
18833a20013fSNir Soffer  *
18843a20013fSNir Soffer  * Returns: 0 on success, -errno on failure. Since this is an optimization,
18853a20013fSNir Soffer  * caller may ignore failures.
18863a20013fSNir Soffer  */
18873a20013fSNir Soffer static int allocate_first_block(int fd, size_t max_size)
18883a20013fSNir Soffer {
18893a20013fSNir Soffer     size_t write_size = (max_size < MAX_BLOCKSIZE)
18903a20013fSNir Soffer         ? BDRV_SECTOR_SIZE
18913a20013fSNir Soffer         : MAX_BLOCKSIZE;
18928e3b0cbbSMarc-André Lureau     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
18933a20013fSNir Soffer     void *buf;
18943a20013fSNir Soffer     ssize_t n;
18953a20013fSNir Soffer     int ret;
18963a20013fSNir Soffer 
18973a20013fSNir Soffer     buf = qemu_memalign(max_align, write_size);
18983a20013fSNir Soffer     memset(buf, 0, write_size);
18993a20013fSNir Soffer 
190037b0b24eSNikita Ivanov     n = RETRY_ON_EINTR(pwrite(fd, buf, write_size, 0));
19013a20013fSNir Soffer 
19023a20013fSNir Soffer     ret = (n == -1) ? -errno : 0;
19033a20013fSNir Soffer 
19043a20013fSNir Soffer     qemu_vfree(buf);
19053a20013fSNir Soffer     return ret;
19063a20013fSNir Soffer }
19073a20013fSNir Soffer 
190829cb4c01SKevin Wolf static int handle_aiocb_truncate(void *opaque)
190993f4e2ffSKevin Wolf {
191029cb4c01SKevin Wolf     RawPosixAIOData *aiocb = opaque;
191193f4e2ffSKevin Wolf     int result = 0;
191293f4e2ffSKevin Wolf     int64_t current_length = 0;
191393f4e2ffSKevin Wolf     char *buf = NULL;
191493f4e2ffSKevin Wolf     struct stat st;
191593f4e2ffSKevin Wolf     int fd = aiocb->aio_fildes;
191693f4e2ffSKevin Wolf     int64_t offset = aiocb->aio_offset;
1917d57c44d0SKevin Wolf     PreallocMode prealloc = aiocb->truncate.prealloc;
1918d57c44d0SKevin Wolf     Error **errp = aiocb->truncate.errp;
191993f4e2ffSKevin Wolf 
192093f4e2ffSKevin Wolf     if (fstat(fd, &st) < 0) {
192193f4e2ffSKevin Wolf         result = -errno;
192293f4e2ffSKevin Wolf         error_setg_errno(errp, -result, "Could not stat file");
192393f4e2ffSKevin Wolf         return result;
192493f4e2ffSKevin Wolf     }
192593f4e2ffSKevin Wolf 
192693f4e2ffSKevin Wolf     current_length = st.st_size;
1927d57c44d0SKevin Wolf     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
192893f4e2ffSKevin Wolf         error_setg(errp, "Cannot use preallocation for shrinking files");
192993f4e2ffSKevin Wolf         return -ENOTSUP;
193093f4e2ffSKevin Wolf     }
193193f4e2ffSKevin Wolf 
1932d57c44d0SKevin Wolf     switch (prealloc) {
193393f4e2ffSKevin Wolf #ifdef CONFIG_POSIX_FALLOCATE
193493f4e2ffSKevin Wolf     case PREALLOC_MODE_FALLOC:
193593f4e2ffSKevin Wolf         /*
193693f4e2ffSKevin Wolf          * Truncating before posix_fallocate() makes it about twice slower on
193793f4e2ffSKevin Wolf          * file systems that do not support fallocate(), trying to check if a
193893f4e2ffSKevin Wolf          * block is allocated before allocating it, so don't do that here.
193993f4e2ffSKevin Wolf          */
194093f4e2ffSKevin Wolf         if (offset != current_length) {
194193f4e2ffSKevin Wolf             result = -posix_fallocate(fd, current_length,
194293f4e2ffSKevin Wolf                                       offset - current_length);
194393f4e2ffSKevin Wolf             if (result != 0) {
194493f4e2ffSKevin Wolf                 /* posix_fallocate() doesn't set errno. */
194593f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
194693f4e2ffSKevin Wolf                                  "Could not preallocate new data");
19473a20013fSNir Soffer             } else if (current_length == 0) {
19483a20013fSNir Soffer                 /*
19493a20013fSNir Soffer                  * posix_fallocate() uses fallocate() if the filesystem
19503a20013fSNir Soffer                  * supports it, or fallback to manually writing zeroes. If
19513a20013fSNir Soffer                  * fallocate() was used, unaligned reads from the fallocated
19523a20013fSNir Soffer                  * area in raw_probe_alignment() will succeed, hence we need to
19533a20013fSNir Soffer                  * allocate the first block.
19543a20013fSNir Soffer                  *
19553a20013fSNir Soffer                  * Optimize future alignment probing; ignore failures.
19563a20013fSNir Soffer                  */
19573a20013fSNir Soffer                 allocate_first_block(fd, offset);
195893f4e2ffSKevin Wolf             }
195993f4e2ffSKevin Wolf         } else {
196093f4e2ffSKevin Wolf             result = 0;
196193f4e2ffSKevin Wolf         }
196293f4e2ffSKevin Wolf         goto out;
196393f4e2ffSKevin Wolf #endif
196493f4e2ffSKevin Wolf     case PREALLOC_MODE_FULL:
196593f4e2ffSKevin Wolf     {
196693f4e2ffSKevin Wolf         int64_t num = 0, left = offset - current_length;
196793f4e2ffSKevin Wolf         off_t seek_result;
196893f4e2ffSKevin Wolf 
196993f4e2ffSKevin Wolf         /*
197093f4e2ffSKevin Wolf          * Knowing the final size from the beginning could allow the file
197193f4e2ffSKevin Wolf          * system driver to do less allocations and possibly avoid
197293f4e2ffSKevin Wolf          * fragmentation of the file.
197393f4e2ffSKevin Wolf          */
197493f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
197593f4e2ffSKevin Wolf             result = -errno;
197693f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
197793f4e2ffSKevin Wolf             goto out;
197893f4e2ffSKevin Wolf         }
197993f4e2ffSKevin Wolf 
198093f4e2ffSKevin Wolf         buf = g_malloc0(65536);
198193f4e2ffSKevin Wolf 
198293f4e2ffSKevin Wolf         seek_result = lseek(fd, current_length, SEEK_SET);
198393f4e2ffSKevin Wolf         if (seek_result < 0) {
198493f4e2ffSKevin Wolf             result = -errno;
198593f4e2ffSKevin Wolf             error_setg_errno(errp, -result,
198693f4e2ffSKevin Wolf                              "Failed to seek to the old end of file");
198793f4e2ffSKevin Wolf             goto out;
198893f4e2ffSKevin Wolf         }
198993f4e2ffSKevin Wolf 
199093f4e2ffSKevin Wolf         while (left > 0) {
199193f4e2ffSKevin Wolf             num = MIN(left, 65536);
199293f4e2ffSKevin Wolf             result = write(fd, buf, num);
199393f4e2ffSKevin Wolf             if (result < 0) {
1994a1c81f4fSFam Zheng                 if (errno == EINTR) {
1995a1c81f4fSFam Zheng                     continue;
1996a1c81f4fSFam Zheng                 }
199793f4e2ffSKevin Wolf                 result = -errno;
199893f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
199993f4e2ffSKevin Wolf                                  "Could not write zeros for preallocation");
200093f4e2ffSKevin Wolf                 goto out;
200193f4e2ffSKevin Wolf             }
200293f4e2ffSKevin Wolf             left -= result;
200393f4e2ffSKevin Wolf         }
200493f4e2ffSKevin Wolf         if (result >= 0) {
200593f4e2ffSKevin Wolf             result = fsync(fd);
200693f4e2ffSKevin Wolf             if (result < 0) {
200793f4e2ffSKevin Wolf                 result = -errno;
200893f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
200993f4e2ffSKevin Wolf                                  "Could not flush file to disk");
201093f4e2ffSKevin Wolf                 goto out;
201193f4e2ffSKevin Wolf             }
201293f4e2ffSKevin Wolf         }
201393f4e2ffSKevin Wolf         goto out;
201493f4e2ffSKevin Wolf     }
201593f4e2ffSKevin Wolf     case PREALLOC_MODE_OFF:
201693f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
201793f4e2ffSKevin Wolf             result = -errno;
201893f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
20193a20013fSNir Soffer         } else if (current_length == 0 && offset > current_length) {
20203a20013fSNir Soffer             /* Optimize future alignment probing; ignore failures. */
20213a20013fSNir Soffer             allocate_first_block(fd, offset);
202293f4e2ffSKevin Wolf         }
202393f4e2ffSKevin Wolf         return result;
202493f4e2ffSKevin Wolf     default:
202593f4e2ffSKevin Wolf         result = -ENOTSUP;
202693f4e2ffSKevin Wolf         error_setg(errp, "Unsupported preallocation mode: %s",
2027d57c44d0SKevin Wolf                    PreallocMode_str(prealloc));
202893f4e2ffSKevin Wolf         return result;
202993f4e2ffSKevin Wolf     }
203093f4e2ffSKevin Wolf 
203193f4e2ffSKevin Wolf out:
203293f4e2ffSKevin Wolf     if (result < 0) {
203393f4e2ffSKevin Wolf         if (ftruncate(fd, current_length) < 0) {
203493f4e2ffSKevin Wolf             error_report("Failed to restore old file length: %s",
203593f4e2ffSKevin Wolf                          strerror(errno));
203693f4e2ffSKevin Wolf         }
203793f4e2ffSKevin Wolf     }
203893f4e2ffSKevin Wolf 
203993f4e2ffSKevin Wolf     g_free(buf);
204093f4e2ffSKevin Wolf     return result;
204193f4e2ffSKevin Wolf }
204293f4e2ffSKevin Wolf 
20435d5de250SKevin Wolf static int coroutine_fn raw_thread_pool_submit(BlockDriverState *bs,
20445d5de250SKevin Wolf                                                ThreadPoolFunc func, void *arg)
20455d5de250SKevin Wolf {
20465d5de250SKevin Wolf     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
20475d5de250SKevin Wolf     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
20485d5de250SKevin Wolf     return thread_pool_submit_co(pool, func, arg);
20495d5de250SKevin Wolf }
20505d5de250SKevin Wolf 
2051a7c5f67aSKeith Busch /*
2052a7c5f67aSKeith Busch  * Check if all memory in this vector is sector aligned.
2053a7c5f67aSKeith Busch  */
2054a7c5f67aSKeith Busch static bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2055a7c5f67aSKeith Busch {
2056a7c5f67aSKeith Busch     int i;
2057a7c5f67aSKeith Busch     size_t alignment = bdrv_min_mem_align(bs);
205825474d90SKeith Busch     size_t len = bs->bl.request_alignment;
2059a7c5f67aSKeith Busch     IO_CODE();
2060a7c5f67aSKeith Busch 
2061a7c5f67aSKeith Busch     for (i = 0; i < qiov->niov; i++) {
2062a7c5f67aSKeith Busch         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2063a7c5f67aSKeith Busch             return false;
2064a7c5f67aSKeith Busch         }
206525474d90SKeith Busch         if (qiov->iov[i].iov_len % len) {
2066a7c5f67aSKeith Busch             return false;
2067a7c5f67aSKeith Busch         }
2068a7c5f67aSKeith Busch     }
2069a7c5f67aSKeith Busch 
2070a7c5f67aSKeith Busch     return true;
2071a7c5f67aSKeith Busch }
2072a7c5f67aSKeith Busch 
2073c1bb86cdSEric Blake static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
2074c1bb86cdSEric Blake                                    uint64_t bytes, QEMUIOVector *qiov, int type)
2075c1bb86cdSEric Blake {
2076c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2077999e6b69SKevin Wolf     RawPosixAIOData acb;
2078c1bb86cdSEric Blake 
2079c1bb86cdSEric Blake     if (fd_open(bs) < 0)
2080c1bb86cdSEric Blake         return -EIO;
2081c1bb86cdSEric Blake 
2082c1bb86cdSEric Blake     /*
2083c6447510SAarushi Mehta      * When using O_DIRECT, the request must be aligned to be able to use
2084c6447510SAarushi Mehta      * either libaio or io_uring interface. If not fail back to regular thread
2085c6447510SAarushi Mehta      * pool read/write code which emulates this for us if we
2086c6447510SAarushi Mehta      * set QEMU_AIO_MISALIGNED.
2087c1bb86cdSEric Blake      */
2088c6447510SAarushi Mehta     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
2089c1bb86cdSEric Blake         type |= QEMU_AIO_MISALIGNED;
2090c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2091c6447510SAarushi Mehta     } else if (s->use_linux_io_uring) {
2092c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2093c6447510SAarushi Mehta         assert(qiov->size == bytes);
2094c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, offset, qiov, type);
2095c6447510SAarushi Mehta #endif
2096c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2097c1bb86cdSEric Blake     } else if (s->use_linux_aio) {
2098c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2099c1bb86cdSEric Blake         assert(qiov->size == bytes);
2100512da211SStefano Garzarella         return laio_co_submit(bs, aio, s->fd, offset, qiov, type,
2101512da211SStefano Garzarella                               s->aio_max_batch);
2102c1bb86cdSEric Blake #endif
2103c1bb86cdSEric Blake     }
2104c1bb86cdSEric Blake 
2105999e6b69SKevin Wolf     acb = (RawPosixAIOData) {
2106999e6b69SKevin Wolf         .bs             = bs,
2107999e6b69SKevin Wolf         .aio_fildes     = s->fd,
2108999e6b69SKevin Wolf         .aio_type       = type,
2109999e6b69SKevin Wolf         .aio_offset     = offset,
2110999e6b69SKevin Wolf         .aio_nbytes     = bytes,
2111999e6b69SKevin Wolf         .io             = {
2112999e6b69SKevin Wolf             .iov            = qiov->iov,
2113999e6b69SKevin Wolf             .niov           = qiov->niov,
2114999e6b69SKevin Wolf         },
2115999e6b69SKevin Wolf     };
2116999e6b69SKevin Wolf 
2117999e6b69SKevin Wolf     assert(qiov->size == bytes);
2118999e6b69SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_rw, &acb);
2119c1bb86cdSEric Blake }
2120c1bb86cdSEric Blake 
2121f7ef38ddSVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_preadv(BlockDriverState *bs, int64_t offset,
2122f7ef38ddSVladimir Sementsov-Ogievskiy                                       int64_t bytes, QEMUIOVector *qiov,
2123f7ef38ddSVladimir Sementsov-Ogievskiy                                       BdrvRequestFlags flags)
2124c1bb86cdSEric Blake {
2125c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
2126c1bb86cdSEric Blake }
2127c1bb86cdSEric Blake 
2128e75abedaSVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, int64_t offset,
2129e75abedaSVladimir Sementsov-Ogievskiy                                        int64_t bytes, QEMUIOVector *qiov,
2130e75abedaSVladimir Sementsov-Ogievskiy                                        BdrvRequestFlags flags)
2131c1bb86cdSEric Blake {
2132c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
2133c1bb86cdSEric Blake }
2134c1bb86cdSEric Blake 
21358f497454SEmanuele Giuseppe Esposito static void coroutine_fn raw_co_io_plug(BlockDriverState *bs)
2136c1bb86cdSEric Blake {
2137c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2138c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2139c1bb86cdSEric Blake     if (s->use_linux_aio) {
2140c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2141c1bb86cdSEric Blake         laio_io_plug(bs, aio);
2142c1bb86cdSEric Blake     }
2143c1bb86cdSEric Blake #endif
2144c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2145c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2146c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2147c6447510SAarushi Mehta         luring_io_plug(bs, aio);
2148c6447510SAarushi Mehta     }
2149c6447510SAarushi Mehta #endif
2150c1bb86cdSEric Blake }
2151c1bb86cdSEric Blake 
215209d9fc97SEmanuele Giuseppe Esposito static void coroutine_fn raw_co_io_unplug(BlockDriverState *bs)
2153c1bb86cdSEric Blake {
2154c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2155c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2156c1bb86cdSEric Blake     if (s->use_linux_aio) {
2157c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
215868d79466SStefano Garzarella         laio_io_unplug(bs, aio, s->aio_max_batch);
2159c1bb86cdSEric Blake     }
2160c1bb86cdSEric Blake #endif
2161c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2162c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2163c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2164c6447510SAarushi Mehta         luring_io_unplug(bs, aio);
2165c6447510SAarushi Mehta     }
2166c6447510SAarushi Mehta #endif
2167c1bb86cdSEric Blake }
2168c1bb86cdSEric Blake 
2169dda56b75SPaolo Bonzini static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
2170c1bb86cdSEric Blake {
2171c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
217206dc9bd5SKevin Wolf     RawPosixAIOData acb;
217333d70fb6SKevin Wolf     int ret;
2174c1bb86cdSEric Blake 
217533d70fb6SKevin Wolf     ret = fd_open(bs);
217633d70fb6SKevin Wolf     if (ret < 0) {
217733d70fb6SKevin Wolf         return ret;
217833d70fb6SKevin Wolf     }
2179c1bb86cdSEric Blake 
218006dc9bd5SKevin Wolf     acb = (RawPosixAIOData) {
218106dc9bd5SKevin Wolf         .bs             = bs,
218206dc9bd5SKevin Wolf         .aio_fildes     = s->fd,
218306dc9bd5SKevin Wolf         .aio_type       = QEMU_AIO_FLUSH,
218406dc9bd5SKevin Wolf     };
218506dc9bd5SKevin Wolf 
2186c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2187c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2188c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2189c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2190c6447510SAarushi Mehta     }
2191c6447510SAarushi Mehta #endif
219206dc9bd5SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_flush, &acb);
2193c1bb86cdSEric Blake }
2194c1bb86cdSEric Blake 
2195ed6e2161SNishanth Aravamudan static void raw_aio_attach_aio_context(BlockDriverState *bs,
2196ed6e2161SNishanth Aravamudan                                        AioContext *new_context)
2197ed6e2161SNishanth Aravamudan {
2198c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2199ed6e2161SNishanth Aravamudan #ifdef CONFIG_LINUX_AIO
2200ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
2201cb09104eSMarkus Armbruster         Error *local_err = NULL;
2202ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(new_context, &local_err)) {
2203ed6e2161SNishanth Aravamudan             error_reportf_err(local_err, "Unable to use native AIO, "
2204ed6e2161SNishanth Aravamudan                                          "falling back to thread pool: ");
2205ed6e2161SNishanth Aravamudan             s->use_linux_aio = false;
2206ed6e2161SNishanth Aravamudan         }
2207ed6e2161SNishanth Aravamudan     }
2208ed6e2161SNishanth Aravamudan #endif
2209c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2210c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2211cb8d0851SPan Nengyuan         Error *local_err = NULL;
2212c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2213c6447510SAarushi Mehta             error_reportf_err(local_err, "Unable to use linux io_uring, "
2214c6447510SAarushi Mehta                                          "falling back to thread pool: ");
2215c6447510SAarushi Mehta             s->use_linux_io_uring = false;
2216c6447510SAarushi Mehta         }
2217c6447510SAarushi Mehta     }
2218c6447510SAarushi Mehta #endif
2219ed6e2161SNishanth Aravamudan }
2220ed6e2161SNishanth Aravamudan 
2221c1bb86cdSEric Blake static void raw_close(BlockDriverState *bs)
2222c1bb86cdSEric Blake {
2223c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2224c1bb86cdSEric Blake 
2225c1bb86cdSEric Blake     if (s->fd >= 0) {
2226c1bb86cdSEric Blake         qemu_close(s->fd);
2227c1bb86cdSEric Blake         s->fd = -1;
2228c1bb86cdSEric Blake     }
2229c1bb86cdSEric Blake }
2230c1bb86cdSEric Blake 
2231d0bc9e5dSMax Reitz /**
2232d0bc9e5dSMax Reitz  * Truncates the given regular file @fd to @offset and, when growing, fills the
2233d0bc9e5dSMax Reitz  * new space according to @prealloc.
2234d0bc9e5dSMax Reitz  *
2235d0bc9e5dSMax Reitz  * Returns: 0 on success, -errno on failure.
2236d0bc9e5dSMax Reitz  */
223793f4e2ffSKevin Wolf static int coroutine_fn
223893f4e2ffSKevin Wolf raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
223993f4e2ffSKevin Wolf                      PreallocMode prealloc, Error **errp)
22409f63b07eSMax Reitz {
224129cb4c01SKevin Wolf     RawPosixAIOData acb;
2242d0bc9e5dSMax Reitz 
224329cb4c01SKevin Wolf     acb = (RawPosixAIOData) {
224493f4e2ffSKevin Wolf         .bs             = bs,
224593f4e2ffSKevin Wolf         .aio_fildes     = fd,
224693f4e2ffSKevin Wolf         .aio_type       = QEMU_AIO_TRUNCATE,
224793f4e2ffSKevin Wolf         .aio_offset     = offset,
2248d57c44d0SKevin Wolf         .truncate       = {
224993f4e2ffSKevin Wolf             .prealloc       = prealloc,
225093f4e2ffSKevin Wolf             .errp           = errp,
2251d57c44d0SKevin Wolf         },
225293f4e2ffSKevin Wolf     };
2253d0bc9e5dSMax Reitz 
225429cb4c01SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_truncate, &acb);
22559f63b07eSMax Reitz }
22569f63b07eSMax Reitz 
2257061ca8a3SKevin Wolf static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2258c80d8b06SMax Reitz                                         bool exact, PreallocMode prealloc,
225992b92799SKevin Wolf                                         BdrvRequestFlags flags, Error **errp)
2260c1bb86cdSEric Blake {
2261c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2262c1bb86cdSEric Blake     struct stat st;
2263f59adb32SMax Reitz     int ret;
2264c1bb86cdSEric Blake 
2265c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
2266f59adb32SMax Reitz         ret = -errno;
2267f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2268f59adb32SMax Reitz         return ret;
2269c1bb86cdSEric Blake     }
2270c1bb86cdSEric Blake 
2271c1bb86cdSEric Blake     if (S_ISREG(st.st_mode)) {
227282325ae5SMax Reitz         /* Always resizes to the exact @offset */
227393f4e2ffSKevin Wolf         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2274c1bb86cdSEric Blake     }
227535d72602SMax Reitz 
227635d72602SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
227735d72602SMax Reitz         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2278977c736fSMarkus Armbruster                    "non-regular file", PreallocMode_str(prealloc));
227935d72602SMax Reitz         return -ENOTSUP;
228035d72602SMax Reitz     }
228135d72602SMax Reitz 
228235d72602SMax Reitz     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2283c86422c5SEmanuele Giuseppe Esposito         int64_t cur_length = raw_co_getlength(bs);
228482325ae5SMax Reitz 
228582325ae5SMax Reitz         if (offset != cur_length && exact) {
228682325ae5SMax Reitz             error_setg(errp, "Cannot resize device files");
228782325ae5SMax Reitz             return -ENOTSUP;
228882325ae5SMax Reitz         } else if (offset > cur_length) {
2289f59adb32SMax Reitz             error_setg(errp, "Cannot grow device files");
2290c1bb86cdSEric Blake             return -EINVAL;
2291c1bb86cdSEric Blake         }
2292c1bb86cdSEric Blake     } else {
2293f59adb32SMax Reitz         error_setg(errp, "Resizing this file is not supported");
2294c1bb86cdSEric Blake         return -ENOTSUP;
2295c1bb86cdSEric Blake     }
2296c1bb86cdSEric Blake 
2297c1bb86cdSEric Blake     return 0;
2298c1bb86cdSEric Blake }
2299c1bb86cdSEric Blake 
2300c1bb86cdSEric Blake #ifdef __OpenBSD__
2301c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2302c1bb86cdSEric Blake {
2303c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2304c1bb86cdSEric Blake     int fd = s->fd;
2305c1bb86cdSEric Blake     struct stat st;
2306c1bb86cdSEric Blake 
2307c1bb86cdSEric Blake     if (fstat(fd, &st))
2308c1bb86cdSEric Blake         return -errno;
2309c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2310c1bb86cdSEric Blake         struct disklabel dl;
2311c1bb86cdSEric Blake 
2312c1bb86cdSEric Blake         if (ioctl(fd, DIOCGDINFO, &dl))
2313c1bb86cdSEric Blake             return -errno;
2314c1bb86cdSEric Blake         return (uint64_t)dl.d_secsize *
2315c1bb86cdSEric Blake             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2316c1bb86cdSEric Blake     } else
2317c1bb86cdSEric Blake         return st.st_size;
2318c1bb86cdSEric Blake }
2319c1bb86cdSEric Blake #elif defined(__NetBSD__)
2320c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2321c1bb86cdSEric Blake {
2322c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2323c1bb86cdSEric Blake     int fd = s->fd;
2324c1bb86cdSEric Blake     struct stat st;
2325c1bb86cdSEric Blake 
2326c1bb86cdSEric Blake     if (fstat(fd, &st))
2327c1bb86cdSEric Blake         return -errno;
2328c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2329c1bb86cdSEric Blake         struct dkwedge_info dkw;
2330c1bb86cdSEric Blake 
2331c1bb86cdSEric Blake         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2332c1bb86cdSEric Blake             return dkw.dkw_size * 512;
2333c1bb86cdSEric Blake         } else {
2334c1bb86cdSEric Blake             struct disklabel dl;
2335c1bb86cdSEric Blake 
2336c1bb86cdSEric Blake             if (ioctl(fd, DIOCGDINFO, &dl))
2337c1bb86cdSEric Blake                 return -errno;
2338c1bb86cdSEric Blake             return (uint64_t)dl.d_secsize *
2339c1bb86cdSEric Blake                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2340c1bb86cdSEric Blake         }
2341c1bb86cdSEric Blake     } else
2342c1bb86cdSEric Blake         return st.st_size;
2343c1bb86cdSEric Blake }
2344c1bb86cdSEric Blake #elif defined(__sun__)
2345c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2346c1bb86cdSEric Blake {
2347c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2348c1bb86cdSEric Blake     struct dk_minfo minfo;
2349c1bb86cdSEric Blake     int ret;
2350c1bb86cdSEric Blake     int64_t size;
2351c1bb86cdSEric Blake 
2352c1bb86cdSEric Blake     ret = fd_open(bs);
2353c1bb86cdSEric Blake     if (ret < 0) {
2354c1bb86cdSEric Blake         return ret;
2355c1bb86cdSEric Blake     }
2356c1bb86cdSEric Blake 
2357c1bb86cdSEric Blake     /*
2358c1bb86cdSEric Blake      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2359c1bb86cdSEric Blake      */
2360c1bb86cdSEric Blake     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2361c1bb86cdSEric Blake     if (ret != -1) {
2362c1bb86cdSEric Blake         return minfo.dki_lbsize * minfo.dki_capacity;
2363c1bb86cdSEric Blake     }
2364c1bb86cdSEric Blake 
2365c1bb86cdSEric Blake     /*
2366c1bb86cdSEric Blake      * There are reports that lseek on some devices fails, but
2367c1bb86cdSEric Blake      * irc discussion said that contingency on contingency was overkill.
2368c1bb86cdSEric Blake      */
2369c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2370c1bb86cdSEric Blake     if (size < 0) {
2371c1bb86cdSEric Blake         return -errno;
2372c1bb86cdSEric Blake     }
2373c1bb86cdSEric Blake     return size;
2374c1bb86cdSEric Blake }
2375c1bb86cdSEric Blake #elif defined(CONFIG_BSD)
2376c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2377c1bb86cdSEric Blake {
2378c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2379c1bb86cdSEric Blake     int fd = s->fd;
2380c1bb86cdSEric Blake     int64_t size;
2381c1bb86cdSEric Blake     struct stat sb;
2382c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2383c1bb86cdSEric Blake     int reopened = 0;
2384c1bb86cdSEric Blake #endif
2385c1bb86cdSEric Blake     int ret;
2386c1bb86cdSEric Blake 
2387c1bb86cdSEric Blake     ret = fd_open(bs);
2388c1bb86cdSEric Blake     if (ret < 0)
2389c1bb86cdSEric Blake         return ret;
2390c1bb86cdSEric Blake 
2391c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2392c1bb86cdSEric Blake again:
2393c1bb86cdSEric Blake #endif
2394c1bb86cdSEric Blake     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2395267cd53fSPaolo Bonzini         size = 0;
2396c1bb86cdSEric Blake #ifdef DIOCGMEDIASIZE
2397267cd53fSPaolo Bonzini         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size)) {
2398c1bb86cdSEric Blake             size = 0;
2399c1bb86cdSEric Blake         }
2400267cd53fSPaolo Bonzini #endif
2401267cd53fSPaolo Bonzini #ifdef DIOCGPART
2402267cd53fSPaolo Bonzini         if (size == 0) {
2403267cd53fSPaolo Bonzini             struct partinfo pi;
2404267cd53fSPaolo Bonzini             if (ioctl(fd, DIOCGPART, &pi) == 0) {
2405267cd53fSPaolo Bonzini                 size = pi.media_size;
2406267cd53fSPaolo Bonzini             }
2407267cd53fSPaolo Bonzini         }
2408c1bb86cdSEric Blake #endif
240909e20abdSJoelle van Dyne #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2410267cd53fSPaolo Bonzini         if (size == 0) {
2411c1bb86cdSEric Blake             uint64_t sectors = 0;
2412c1bb86cdSEric Blake             uint32_t sector_size = 0;
2413c1bb86cdSEric Blake 
2414c1bb86cdSEric Blake             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2415c1bb86cdSEric Blake                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2416c1bb86cdSEric Blake                 size = sectors * sector_size;
2417c1bb86cdSEric Blake             }
2418c1bb86cdSEric Blake         }
2419c1bb86cdSEric Blake #endif
2420267cd53fSPaolo Bonzini         if (size == 0) {
2421267cd53fSPaolo Bonzini             size = lseek(fd, 0LL, SEEK_END);
2422267cd53fSPaolo Bonzini         }
2423267cd53fSPaolo Bonzini         if (size < 0) {
2424267cd53fSPaolo Bonzini             return -errno;
2425267cd53fSPaolo Bonzini         }
2426c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2427c1bb86cdSEric Blake         switch(s->type) {
2428c1bb86cdSEric Blake         case FTYPE_CD:
2429c1bb86cdSEric Blake             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2430c1bb86cdSEric Blake             if (size == 2048LL * (unsigned)-1)
2431c1bb86cdSEric Blake                 size = 0;
2432c1bb86cdSEric Blake             /* XXX no disc?  maybe we need to reopen... */
2433c1bb86cdSEric Blake             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2434c1bb86cdSEric Blake                 reopened = 1;
2435c1bb86cdSEric Blake                 goto again;
2436c1bb86cdSEric Blake             }
2437c1bb86cdSEric Blake         }
2438c1bb86cdSEric Blake #endif
2439c1bb86cdSEric Blake     } else {
2440c1bb86cdSEric Blake         size = lseek(fd, 0, SEEK_END);
2441c1bb86cdSEric Blake         if (size < 0) {
2442c1bb86cdSEric Blake             return -errno;
2443c1bb86cdSEric Blake         }
2444c1bb86cdSEric Blake     }
2445c1bb86cdSEric Blake     return size;
2446c1bb86cdSEric Blake }
2447c1bb86cdSEric Blake #else
2448c86422c5SEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2449c1bb86cdSEric Blake {
2450c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2451c1bb86cdSEric Blake     int ret;
2452c1bb86cdSEric Blake     int64_t size;
2453c1bb86cdSEric Blake 
2454c1bb86cdSEric Blake     ret = fd_open(bs);
2455c1bb86cdSEric Blake     if (ret < 0) {
2456c1bb86cdSEric Blake         return ret;
2457c1bb86cdSEric Blake     }
2458c1bb86cdSEric Blake 
2459c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2460c1bb86cdSEric Blake     if (size < 0) {
2461c1bb86cdSEric Blake         return -errno;
2462c1bb86cdSEric Blake     }
2463c1bb86cdSEric Blake     return size;
2464c1bb86cdSEric Blake }
2465c1bb86cdSEric Blake #endif
2466c1bb86cdSEric Blake 
246782618d7bSEmanuele Giuseppe Esposito static int64_t coroutine_fn raw_co_get_allocated_file_size(BlockDriverState *bs)
2468c1bb86cdSEric Blake {
2469c1bb86cdSEric Blake     struct stat st;
2470c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2471c1bb86cdSEric Blake 
2472c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
2473c1bb86cdSEric Blake         return -errno;
2474c1bb86cdSEric Blake     }
2475c1bb86cdSEric Blake     return (int64_t)st.st_blocks * 512;
2476c1bb86cdSEric Blake }
2477c1bb86cdSEric Blake 
247893f4e2ffSKevin Wolf static int coroutine_fn
247993f4e2ffSKevin Wolf raw_co_create(BlockdevCreateOptions *options, Error **errp)
2480c1bb86cdSEric Blake {
2481927f11e1SKevin Wolf     BlockdevCreateOptionsFile *file_opts;
24827c20c808SMax Reitz     Error *local_err = NULL;
2483c1bb86cdSEric Blake     int fd;
2484d815efcaSMax Reitz     uint64_t perm, shared;
2485c1bb86cdSEric Blake     int result = 0;
2486c1bb86cdSEric Blake 
2487927f11e1SKevin Wolf     /* Validate options and set default values */
2488927f11e1SKevin Wolf     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2489927f11e1SKevin Wolf     file_opts = &options->u.file;
2490c1bb86cdSEric Blake 
2491927f11e1SKevin Wolf     if (!file_opts->has_nocow) {
2492927f11e1SKevin Wolf         file_opts->nocow = false;
2493927f11e1SKevin Wolf     }
2494927f11e1SKevin Wolf     if (!file_opts->has_preallocation) {
2495927f11e1SKevin Wolf         file_opts->preallocation = PREALLOC_MODE_OFF;
2496c1bb86cdSEric Blake     }
2497ffa244c8SKevin Wolf     if (!file_opts->has_extent_size_hint) {
2498ffa244c8SKevin Wolf         file_opts->extent_size_hint = 1 * MiB;
2499ffa244c8SKevin Wolf     }
2500ffa244c8SKevin Wolf     if (file_opts->extent_size_hint > UINT32_MAX) {
2501ffa244c8SKevin Wolf         result = -EINVAL;
2502ffa244c8SKevin Wolf         error_setg(errp, "Extent size hint is too large");
2503ffa244c8SKevin Wolf         goto out;
2504ffa244c8SKevin Wolf     }
2505c1bb86cdSEric Blake 
2506927f11e1SKevin Wolf     /* Create file */
2507b18a24a9SDaniel P. Berrangé     fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
2508c1bb86cdSEric Blake     if (fd < 0) {
2509c1bb86cdSEric Blake         result = -errno;
2510c1bb86cdSEric Blake         goto out;
2511c1bb86cdSEric Blake     }
2512c1bb86cdSEric Blake 
2513b8cf1913SMax Reitz     /* Take permissions: We want to discard everything, so we need
2514b8cf1913SMax Reitz      * BLK_PERM_WRITE; and truncation to the desired size requires
2515b8cf1913SMax Reitz      * BLK_PERM_RESIZE.
2516b8cf1913SMax Reitz      * On the other hand, we cannot share the RESIZE permission
2517b8cf1913SMax Reitz      * because we promise that after this function, the file has the
2518b8cf1913SMax Reitz      * size given in the options.  If someone else were to resize it
2519b8cf1913SMax Reitz      * concurrently, we could not guarantee that.
2520b8cf1913SMax Reitz      * Note that after this function, we can no longer guarantee that
2521b8cf1913SMax Reitz      * the file is not touched by a third party, so it may be resized
2522b8cf1913SMax Reitz      * then. */
2523b8cf1913SMax Reitz     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2524b8cf1913SMax Reitz     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2525b8cf1913SMax Reitz 
2526b8cf1913SMax Reitz     /* Step one: Take locks */
25272996ffadSFam Zheng     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2528b8cf1913SMax Reitz     if (result < 0) {
2529b8cf1913SMax Reitz         goto out_close;
2530b8cf1913SMax Reitz     }
2531b8cf1913SMax Reitz 
2532b8cf1913SMax Reitz     /* Step two: Check that nobody else has taken conflicting locks */
2533b8cf1913SMax Reitz     result = raw_check_lock_bytes(fd, perm, shared, errp);
2534b8cf1913SMax Reitz     if (result < 0) {
2535b857431dSFam Zheng         error_append_hint(errp,
2536b857431dSFam Zheng                           "Is another process using the image [%s]?\n",
2537b857431dSFam Zheng                           file_opts->filename);
25387c20c808SMax Reitz         goto out_unlock;
2539b8cf1913SMax Reitz     }
2540b8cf1913SMax Reitz 
2541b8cf1913SMax Reitz     /* Clear the file by truncating it to 0 */
254293f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2543b8cf1913SMax Reitz     if (result < 0) {
25447c20c808SMax Reitz         goto out_unlock;
2545b8cf1913SMax Reitz     }
2546b8cf1913SMax Reitz 
2547927f11e1SKevin Wolf     if (file_opts->nocow) {
2548c1bb86cdSEric Blake #ifdef __linux__
2549c1bb86cdSEric Blake         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2550c1bb86cdSEric Blake          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2551c1bb86cdSEric Blake          * will be ignored since any failure of this operation should not
2552c1bb86cdSEric Blake          * block the left work.
2553c1bb86cdSEric Blake          */
2554c1bb86cdSEric Blake         int attr;
2555c1bb86cdSEric Blake         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2556c1bb86cdSEric Blake             attr |= FS_NOCOW_FL;
2557c1bb86cdSEric Blake             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2558c1bb86cdSEric Blake         }
2559c1bb86cdSEric Blake #endif
2560c1bb86cdSEric Blake     }
2561ffa244c8SKevin Wolf #ifdef FS_IOC_FSSETXATTR
2562ffa244c8SKevin Wolf     /*
2563ffa244c8SKevin Wolf      * Try to set the extent size hint. Failure is not fatal, and a warning is
2564ffa244c8SKevin Wolf      * only printed if the option was explicitly specified.
2565ffa244c8SKevin Wolf      */
2566ffa244c8SKevin Wolf     {
2567ffa244c8SKevin Wolf         struct fsxattr attr;
2568ffa244c8SKevin Wolf         result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2569ffa244c8SKevin Wolf         if (result == 0) {
2570ffa244c8SKevin Wolf             attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2571ffa244c8SKevin Wolf             attr.fsx_extsize = file_opts->extent_size_hint;
2572ffa244c8SKevin Wolf             result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2573ffa244c8SKevin Wolf         }
2574ffa244c8SKevin Wolf         if (result < 0 && file_opts->has_extent_size_hint &&
2575ffa244c8SKevin Wolf             file_opts->extent_size_hint)
2576ffa244c8SKevin Wolf         {
2577ffa244c8SKevin Wolf             warn_report("Failed to set extent size hint: %s",
2578ffa244c8SKevin Wolf                         strerror(errno));
2579ffa244c8SKevin Wolf         }
2580ffa244c8SKevin Wolf     }
2581ffa244c8SKevin Wolf #endif
2582c1bb86cdSEric Blake 
2583b8cf1913SMax Reitz     /* Resize and potentially preallocate the file to the desired
2584b8cf1913SMax Reitz      * final size */
258593f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, file_opts->size,
258693f4e2ffSKevin Wolf                                   file_opts->preallocation, errp);
25879f63b07eSMax Reitz     if (result < 0) {
25887c20c808SMax Reitz         goto out_unlock;
25897c20c808SMax Reitz     }
25907c20c808SMax Reitz 
25917c20c808SMax Reitz out_unlock:
25922996ffadSFam Zheng     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
25937c20c808SMax Reitz     if (local_err) {
25947c20c808SMax Reitz         /* The above call should not fail, and if it does, that does
25957c20c808SMax Reitz          * not mean the whole creation operation has failed.  So
25967c20c808SMax Reitz          * report it the user for their convenience, but do not report
25977c20c808SMax Reitz          * it to the caller. */
2598db0754dfSFam Zheng         warn_report_err(local_err);
25995a1dad9dSNir Soffer     }
26005a1dad9dSNir Soffer 
26015a1dad9dSNir Soffer out_close:
2602c1bb86cdSEric Blake     if (qemu_close(fd) != 0 && result == 0) {
2603c1bb86cdSEric Blake         result = -errno;
2604c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not close the new file");
2605c1bb86cdSEric Blake     }
2606c1bb86cdSEric Blake out:
2607c1bb86cdSEric Blake     return result;
2608c1bb86cdSEric Blake }
2609c1bb86cdSEric Blake 
26104ec8df01SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
26114ec8df01SKevin Wolf raw_co_create_opts(BlockDriver *drv, const char *filename,
26124ec8df01SKevin Wolf                    QemuOpts *opts, Error **errp)
2613927f11e1SKevin Wolf {
2614927f11e1SKevin Wolf     BlockdevCreateOptions options;
2615927f11e1SKevin Wolf     int64_t total_size = 0;
2616ffa244c8SKevin Wolf     int64_t extent_size_hint = 0;
2617ffa244c8SKevin Wolf     bool has_extent_size_hint = false;
2618927f11e1SKevin Wolf     bool nocow = false;
2619927f11e1SKevin Wolf     PreallocMode prealloc;
2620927f11e1SKevin Wolf     char *buf = NULL;
2621927f11e1SKevin Wolf     Error *local_err = NULL;
2622927f11e1SKevin Wolf 
2623927f11e1SKevin Wolf     /* Skip file: protocol prefix */
2624927f11e1SKevin Wolf     strstart(filename, "file:", &filename);
2625927f11e1SKevin Wolf 
2626927f11e1SKevin Wolf     /* Read out options */
2627927f11e1SKevin Wolf     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2628927f11e1SKevin Wolf                           BDRV_SECTOR_SIZE);
2629ffa244c8SKevin Wolf     if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
2630ffa244c8SKevin Wolf         has_extent_size_hint = true;
2631ffa244c8SKevin Wolf         extent_size_hint =
2632ffa244c8SKevin Wolf             qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
2633ffa244c8SKevin Wolf     }
2634927f11e1SKevin Wolf     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2635927f11e1SKevin Wolf     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2636927f11e1SKevin Wolf     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2637927f11e1SKevin Wolf                                PREALLOC_MODE_OFF, &local_err);
2638927f11e1SKevin Wolf     g_free(buf);
2639927f11e1SKevin Wolf     if (local_err) {
2640927f11e1SKevin Wolf         error_propagate(errp, local_err);
2641927f11e1SKevin Wolf         return -EINVAL;
2642927f11e1SKevin Wolf     }
2643927f11e1SKevin Wolf 
2644927f11e1SKevin Wolf     options = (BlockdevCreateOptions) {
2645927f11e1SKevin Wolf         .driver     = BLOCKDEV_DRIVER_FILE,
2646927f11e1SKevin Wolf         .u.file     = {
2647927f11e1SKevin Wolf             .filename           = (char *) filename,
2648927f11e1SKevin Wolf             .size               = total_size,
2649927f11e1SKevin Wolf             .has_preallocation  = true,
2650927f11e1SKevin Wolf             .preallocation      = prealloc,
2651927f11e1SKevin Wolf             .has_nocow          = true,
2652927f11e1SKevin Wolf             .nocow              = nocow,
2653ffa244c8SKevin Wolf             .has_extent_size_hint = has_extent_size_hint,
2654ffa244c8SKevin Wolf             .extent_size_hint   = extent_size_hint,
2655927f11e1SKevin Wolf         },
2656927f11e1SKevin Wolf     };
2657927f11e1SKevin Wolf     return raw_co_create(&options, errp);
2658927f11e1SKevin Wolf }
2659927f11e1SKevin Wolf 
26609bffae14SDaniel Henrique Barboza static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
26619bffae14SDaniel Henrique Barboza                                            Error **errp)
26629bffae14SDaniel Henrique Barboza {
26639bffae14SDaniel Henrique Barboza     struct stat st;
26649bffae14SDaniel Henrique Barboza     int ret;
26659bffae14SDaniel Henrique Barboza 
26669bffae14SDaniel Henrique Barboza     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
26679bffae14SDaniel Henrique Barboza         error_setg_errno(errp, ENOENT, "%s is not a regular file",
26689bffae14SDaniel Henrique Barboza                          bs->filename);
26699bffae14SDaniel Henrique Barboza         return -ENOENT;
26709bffae14SDaniel Henrique Barboza     }
26719bffae14SDaniel Henrique Barboza 
26729bffae14SDaniel Henrique Barboza     ret = unlink(bs->filename);
26739bffae14SDaniel Henrique Barboza     if (ret < 0) {
26749bffae14SDaniel Henrique Barboza         ret = -errno;
26759bffae14SDaniel Henrique Barboza         error_setg_errno(errp, -ret, "Error when deleting file %s",
26769bffae14SDaniel Henrique Barboza                          bs->filename);
26779bffae14SDaniel Henrique Barboza     }
26789bffae14SDaniel Henrique Barboza 
26799bffae14SDaniel Henrique Barboza     return ret;
26809bffae14SDaniel Henrique Barboza }
26819bffae14SDaniel Henrique Barboza 
2682c1bb86cdSEric Blake /*
2683c1bb86cdSEric Blake  * Find allocation range in @bs around offset @start.
2684c1bb86cdSEric Blake  * May change underlying file descriptor's file offset.
2685c1bb86cdSEric Blake  * If @start is not in a hole, store @start in @data, and the
2686c1bb86cdSEric Blake  * beginning of the next hole in @hole, and return 0.
2687c1bb86cdSEric Blake  * If @start is in a non-trailing hole, store @start in @hole and the
2688c1bb86cdSEric Blake  * beginning of the next non-hole in @data, and return 0.
2689c1bb86cdSEric Blake  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2690c1bb86cdSEric Blake  * If we can't find out, return a negative errno other than -ENXIO.
2691c1bb86cdSEric Blake  */
2692c1bb86cdSEric Blake static int find_allocation(BlockDriverState *bs, off_t start,
2693c1bb86cdSEric Blake                            off_t *data, off_t *hole)
2694c1bb86cdSEric Blake {
2695c1bb86cdSEric Blake #if defined SEEK_HOLE && defined SEEK_DATA
2696c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2697c1bb86cdSEric Blake     off_t offs;
2698c1bb86cdSEric Blake 
2699c1bb86cdSEric Blake     /*
2700c1bb86cdSEric Blake      * SEEK_DATA cases:
2701c1bb86cdSEric Blake      * D1. offs == start: start is in data
2702c1bb86cdSEric Blake      * D2. offs > start: start is in a hole, next data at offs
2703c1bb86cdSEric Blake      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2704c1bb86cdSEric Blake      *                              or start is beyond EOF
2705c1bb86cdSEric Blake      *     If the latter happens, the file has been truncated behind
2706c1bb86cdSEric Blake      *     our back since we opened it.  All bets are off then.
2707c1bb86cdSEric Blake      *     Treating like a trailing hole is simplest.
2708c1bb86cdSEric Blake      * D4. offs < 0, errno != ENXIO: we learned nothing
2709c1bb86cdSEric Blake      */
2710c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_DATA);
2711c1bb86cdSEric Blake     if (offs < 0) {
2712c1bb86cdSEric Blake         return -errno;          /* D3 or D4 */
2713c1bb86cdSEric Blake     }
2714a03083a0SJeff Cody 
2715a03083a0SJeff Cody     if (offs < start) {
2716a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2717a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like D4. */
2718a03083a0SJeff Cody         return -EIO;
2719a03083a0SJeff Cody     }
2720c1bb86cdSEric Blake 
2721c1bb86cdSEric Blake     if (offs > start) {
2722c1bb86cdSEric Blake         /* D2: in hole, next data at offs */
2723c1bb86cdSEric Blake         *hole = start;
2724c1bb86cdSEric Blake         *data = offs;
2725c1bb86cdSEric Blake         return 0;
2726c1bb86cdSEric Blake     }
2727c1bb86cdSEric Blake 
2728c1bb86cdSEric Blake     /* D1: in data, end not yet known */
2729c1bb86cdSEric Blake 
2730c1bb86cdSEric Blake     /*
2731c1bb86cdSEric Blake      * SEEK_HOLE cases:
2732c1bb86cdSEric Blake      * H1. offs == start: start is in a hole
2733c1bb86cdSEric Blake      *     If this happens here, a hole has been dug behind our back
2734c1bb86cdSEric Blake      *     since the previous lseek().
2735c1bb86cdSEric Blake      * H2. offs > start: either start is in data, next hole at offs,
2736c1bb86cdSEric Blake      *                   or start is in trailing hole, EOF at offs
2737c1bb86cdSEric Blake      *     Linux treats trailing holes like any other hole: offs ==
2738c1bb86cdSEric Blake      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2739c1bb86cdSEric Blake      *     If that happens here, a hole has been dug behind our back
2740c1bb86cdSEric Blake      *     since the previous lseek().
2741c1bb86cdSEric Blake      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2742c1bb86cdSEric Blake      *     If this happens, the file has been truncated behind our
2743c1bb86cdSEric Blake      *     back since we opened it.  Treat it like a trailing hole.
2744c1bb86cdSEric Blake      * H4. offs < 0, errno != ENXIO: we learned nothing
2745c1bb86cdSEric Blake      *     Pretend we know nothing at all, i.e. "forget" about D1.
2746c1bb86cdSEric Blake      */
2747c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_HOLE);
2748c1bb86cdSEric Blake     if (offs < 0) {
2749c1bb86cdSEric Blake         return -errno;          /* D1 and (H3 or H4) */
2750c1bb86cdSEric Blake     }
2751a03083a0SJeff Cody 
2752a03083a0SJeff Cody     if (offs < start) {
2753a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2754a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like H4. */
2755a03083a0SJeff Cody         return -EIO;
2756a03083a0SJeff Cody     }
2757c1bb86cdSEric Blake 
2758c1bb86cdSEric Blake     if (offs > start) {
2759c1bb86cdSEric Blake         /*
2760c1bb86cdSEric Blake          * D1 and H2: either in data, next hole at offs, or it was in
2761c1bb86cdSEric Blake          * data but is now in a trailing hole.  In the latter case,
2762c1bb86cdSEric Blake          * all bets are off.  Treating it as if it there was data all
2763c1bb86cdSEric Blake          * the way to EOF is safe, so simply do that.
2764c1bb86cdSEric Blake          */
2765c1bb86cdSEric Blake         *data = start;
2766c1bb86cdSEric Blake         *hole = offs;
2767c1bb86cdSEric Blake         return 0;
2768c1bb86cdSEric Blake     }
2769c1bb86cdSEric Blake 
2770c1bb86cdSEric Blake     /* D1 and H1 */
2771c1bb86cdSEric Blake     return -EBUSY;
2772c1bb86cdSEric Blake #else
2773c1bb86cdSEric Blake     return -ENOTSUP;
2774c1bb86cdSEric Blake #endif
2775c1bb86cdSEric Blake }
2776c1bb86cdSEric Blake 
2777c1bb86cdSEric Blake /*
2778a290f085SEric Blake  * Returns the allocation status of the specified offset.
2779c1bb86cdSEric Blake  *
2780a290f085SEric Blake  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2781c1bb86cdSEric Blake  *
2782a290f085SEric Blake  * 'pnum' is set to the number of bytes (including and immediately following
2783a290f085SEric Blake  * the specified offset) that are known to be in the same
2784c1bb86cdSEric Blake  * allocated/unallocated state.
2785c1bb86cdSEric Blake  *
2786869e7ee8SHanna Reitz  * 'bytes' is a soft cap for 'pnum'.  If the information is free, 'pnum' may
2787869e7ee8SHanna Reitz  * well exceed it.
2788c1bb86cdSEric Blake  */
2789a290f085SEric Blake static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2790a290f085SEric Blake                                             bool want_zero,
2791a290f085SEric Blake                                             int64_t offset,
2792a290f085SEric Blake                                             int64_t bytes, int64_t *pnum,
2793a290f085SEric Blake                                             int64_t *map,
2794c1bb86cdSEric Blake                                             BlockDriverState **file)
2795c1bb86cdSEric Blake {
2796a290f085SEric Blake     off_t data = 0, hole = 0;
2797c1bb86cdSEric Blake     int ret;
2798c1bb86cdSEric Blake 
27999c3db310SMax Reitz     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
28009c3db310SMax Reitz 
2801c1bb86cdSEric Blake     ret = fd_open(bs);
2802c1bb86cdSEric Blake     if (ret < 0) {
2803c1bb86cdSEric Blake         return ret;
2804c1bb86cdSEric Blake     }
2805c1bb86cdSEric Blake 
2806a290f085SEric Blake     if (!want_zero) {
2807a290f085SEric Blake         *pnum = bytes;
2808a290f085SEric Blake         *map = offset;
2809a290f085SEric Blake         *file = bs;
2810a290f085SEric Blake         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2811c1bb86cdSEric Blake     }
2812c1bb86cdSEric Blake 
2813a290f085SEric Blake     ret = find_allocation(bs, offset, &data, &hole);
2814c1bb86cdSEric Blake     if (ret == -ENXIO) {
2815c1bb86cdSEric Blake         /* Trailing hole */
2816a290f085SEric Blake         *pnum = bytes;
2817c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2818c1bb86cdSEric Blake     } else if (ret < 0) {
2819c1bb86cdSEric Blake         /* No info available, so pretend there are no holes */
2820a290f085SEric Blake         *pnum = bytes;
2821c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2822a290f085SEric Blake     } else if (data == offset) {
2823a290f085SEric Blake         /* On a data extent, compute bytes to the end of the extent,
2824c1bb86cdSEric Blake          * possibly including a partial sector at EOF. */
2825869e7ee8SHanna Reitz         *pnum = hole - offset;
28269c3db310SMax Reitz 
28279c3db310SMax Reitz         /*
28289c3db310SMax Reitz          * We are not allowed to return partial sectors, though, so
28299c3db310SMax Reitz          * round up if necessary.
28309c3db310SMax Reitz          */
28319c3db310SMax Reitz         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
2832c86422c5SEmanuele Giuseppe Esposito             int64_t file_length = raw_co_getlength(bs);
28339c3db310SMax Reitz             if (file_length > 0) {
28349c3db310SMax Reitz                 /* Ignore errors, this is just a safeguard */
28359c3db310SMax Reitz                 assert(hole == file_length);
28369c3db310SMax Reitz             }
28379c3db310SMax Reitz             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
28389c3db310SMax Reitz         }
28399c3db310SMax Reitz 
2840c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2841c1bb86cdSEric Blake     } else {
2842a290f085SEric Blake         /* On a hole, compute bytes to the beginning of the next extent.  */
2843a290f085SEric Blake         assert(hole == offset);
2844869e7ee8SHanna Reitz         *pnum = data - offset;
2845c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2846c1bb86cdSEric Blake     }
2847a290f085SEric Blake     *map = offset;
2848c1bb86cdSEric Blake     *file = bs;
2849a290f085SEric Blake     return ret | BDRV_BLOCK_OFFSET_VALID;
2850c1bb86cdSEric Blake }
2851c1bb86cdSEric Blake 
285231be8a2aSStefan Hajnoczi #if defined(__linux__)
285331be8a2aSStefan Hajnoczi /* Verify that the file is not in the page cache */
2854c86422c5SEmanuele Giuseppe Esposito static void coroutine_fn check_cache_dropped(BlockDriverState *bs, Error **errp)
285531be8a2aSStefan Hajnoczi {
285631be8a2aSStefan Hajnoczi     const size_t window_size = 128 * 1024 * 1024;
285731be8a2aSStefan Hajnoczi     BDRVRawState *s = bs->opaque;
285831be8a2aSStefan Hajnoczi     void *window = NULL;
285931be8a2aSStefan Hajnoczi     size_t length = 0;
286031be8a2aSStefan Hajnoczi     unsigned char *vec;
286131be8a2aSStefan Hajnoczi     size_t page_size;
286231be8a2aSStefan Hajnoczi     off_t offset;
286331be8a2aSStefan Hajnoczi     off_t end;
286431be8a2aSStefan Hajnoczi 
286531be8a2aSStefan Hajnoczi     /* mincore(2) page status information requires 1 byte per page */
286631be8a2aSStefan Hajnoczi     page_size = sysconf(_SC_PAGESIZE);
286731be8a2aSStefan Hajnoczi     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
286831be8a2aSStefan Hajnoczi 
2869c86422c5SEmanuele Giuseppe Esposito     end = raw_co_getlength(bs);
287031be8a2aSStefan Hajnoczi 
287131be8a2aSStefan Hajnoczi     for (offset = 0; offset < end; offset += window_size) {
287231be8a2aSStefan Hajnoczi         void *new_window;
287331be8a2aSStefan Hajnoczi         size_t new_length;
287431be8a2aSStefan Hajnoczi         size_t vec_end;
287531be8a2aSStefan Hajnoczi         size_t i;
287631be8a2aSStefan Hajnoczi         int ret;
287731be8a2aSStefan Hajnoczi 
287831be8a2aSStefan Hajnoczi         /* Unmap previous window if size has changed */
287931be8a2aSStefan Hajnoczi         new_length = MIN(end - offset, window_size);
288031be8a2aSStefan Hajnoczi         if (new_length != length) {
288131be8a2aSStefan Hajnoczi             munmap(window, length);
288231be8a2aSStefan Hajnoczi             window = NULL;
288331be8a2aSStefan Hajnoczi             length = 0;
288431be8a2aSStefan Hajnoczi         }
288531be8a2aSStefan Hajnoczi 
288631be8a2aSStefan Hajnoczi         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
288731be8a2aSStefan Hajnoczi                           s->fd, offset);
288831be8a2aSStefan Hajnoczi         if (new_window == MAP_FAILED) {
288931be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mmap failed");
289031be8a2aSStefan Hajnoczi             break;
289131be8a2aSStefan Hajnoczi         }
289231be8a2aSStefan Hajnoczi 
289331be8a2aSStefan Hajnoczi         window = new_window;
289431be8a2aSStefan Hajnoczi         length = new_length;
289531be8a2aSStefan Hajnoczi 
289631be8a2aSStefan Hajnoczi         ret = mincore(window, length, vec);
289731be8a2aSStefan Hajnoczi         if (ret < 0) {
289831be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mincore failed");
289931be8a2aSStefan Hajnoczi             break;
290031be8a2aSStefan Hajnoczi         }
290131be8a2aSStefan Hajnoczi 
290231be8a2aSStefan Hajnoczi         vec_end = DIV_ROUND_UP(length, page_size);
290331be8a2aSStefan Hajnoczi         for (i = 0; i < vec_end; i++) {
290431be8a2aSStefan Hajnoczi             if (vec[i] & 0x1) {
290531be8a2aSStefan Hajnoczi                 break;
290631be8a2aSStefan Hajnoczi             }
290731be8a2aSStefan Hajnoczi         }
290877ed971bSMarkus Armbruster         if (i < vec_end) {
290977ed971bSMarkus Armbruster             error_setg(errp, "page cache still in use!");
291077ed971bSMarkus Armbruster             break;
291177ed971bSMarkus Armbruster         }
291231be8a2aSStefan Hajnoczi     }
291331be8a2aSStefan Hajnoczi 
291431be8a2aSStefan Hajnoczi     if (window) {
291531be8a2aSStefan Hajnoczi         munmap(window, length);
291631be8a2aSStefan Hajnoczi     }
291731be8a2aSStefan Hajnoczi 
291831be8a2aSStefan Hajnoczi     g_free(vec);
291931be8a2aSStefan Hajnoczi }
292031be8a2aSStefan Hajnoczi #endif /* __linux__ */
292131be8a2aSStefan Hajnoczi 
292288095349SEmanuele Giuseppe Esposito static void coroutine_fn GRAPH_RDLOCK
292388095349SEmanuele Giuseppe Esposito raw_co_invalidate_cache(BlockDriverState *bs, Error **errp)
2924dd577a26SStefan Hajnoczi {
2925dd577a26SStefan Hajnoczi     BDRVRawState *s = bs->opaque;
2926dd577a26SStefan Hajnoczi     int ret;
2927dd577a26SStefan Hajnoczi 
2928dd577a26SStefan Hajnoczi     ret = fd_open(bs);
2929dd577a26SStefan Hajnoczi     if (ret < 0) {
2930dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "The file descriptor is not open");
2931dd577a26SStefan Hajnoczi         return;
2932dd577a26SStefan Hajnoczi     }
2933dd577a26SStefan Hajnoczi 
2934f357fcd8SStefan Hajnoczi     if (!s->drop_cache) {
2935f357fcd8SStefan Hajnoczi         return;
2936f357fcd8SStefan Hajnoczi     }
2937f357fcd8SStefan Hajnoczi 
2938dd577a26SStefan Hajnoczi     if (s->open_flags & O_DIRECT) {
2939dd577a26SStefan Hajnoczi         return; /* No host kernel page cache */
2940dd577a26SStefan Hajnoczi     }
2941dd577a26SStefan Hajnoczi 
2942dd577a26SStefan Hajnoczi #if defined(__linux__)
2943dd577a26SStefan Hajnoczi     /* This sets the scene for the next syscall... */
2944dd577a26SStefan Hajnoczi     ret = bdrv_co_flush(bs);
2945dd577a26SStefan Hajnoczi     if (ret < 0) {
2946dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "flush failed");
2947dd577a26SStefan Hajnoczi         return;
2948dd577a26SStefan Hajnoczi     }
2949dd577a26SStefan Hajnoczi 
2950dd577a26SStefan Hajnoczi     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2951dd577a26SStefan Hajnoczi      * process.  These limitations are okay because we just fsynced the file,
2952dd577a26SStefan Hajnoczi      * we don't use mmap, and the file should not be in use by other processes.
2953dd577a26SStefan Hajnoczi      */
2954dd577a26SStefan Hajnoczi     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2955dd577a26SStefan Hajnoczi     if (ret != 0) { /* the return value is a positive errno */
2956dd577a26SStefan Hajnoczi         error_setg_errno(errp, ret, "fadvise failed");
2957dd577a26SStefan Hajnoczi         return;
2958dd577a26SStefan Hajnoczi     }
295931be8a2aSStefan Hajnoczi 
296031be8a2aSStefan Hajnoczi     if (s->check_cache_dropped) {
296131be8a2aSStefan Hajnoczi         check_cache_dropped(bs, errp);
296231be8a2aSStefan Hajnoczi     }
2963dd577a26SStefan Hajnoczi #else /* __linux__ */
2964dd577a26SStefan Hajnoczi     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2965dd577a26SStefan Hajnoczi      * unsupported on other host operating systems.  Cache consistency issues
2966dd577a26SStefan Hajnoczi      * may occur but no error is reported here, partly because that's the
2967dd577a26SStefan Hajnoczi      * historical behavior and partly because it's hard to differentiate valid
2968dd577a26SStefan Hajnoczi      * configurations that should not cause errors.
2969dd577a26SStefan Hajnoczi      */
2970dd577a26SStefan Hajnoczi #endif /* !__linux__ */
2971dd577a26SStefan Hajnoczi }
2972dd577a26SStefan Hajnoczi 
29731c450366SAnton Nefedov static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
29741c450366SAnton Nefedov {
29751c450366SAnton Nefedov     if (ret) {
29761c450366SAnton Nefedov         s->stats.discard_nb_failed++;
29771c450366SAnton Nefedov     } else {
29781c450366SAnton Nefedov         s->stats.discard_nb_ok++;
29791c450366SAnton Nefedov         s->stats.discard_bytes_ok += nbytes;
29801c450366SAnton Nefedov     }
29811c450366SAnton Nefedov }
29821c450366SAnton Nefedov 
298333d70fb6SKevin Wolf static coroutine_fn int
29840c802287SVladimir Sementsov-Ogievskiy raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes,
29850c802287SVladimir Sementsov-Ogievskiy                 bool blkdev)
2986c1bb86cdSEric Blake {
2987c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
298846ee0f46SKevin Wolf     RawPosixAIOData acb;
29891c450366SAnton Nefedov     int ret;
2990c1bb86cdSEric Blake 
299146ee0f46SKevin Wolf     acb = (RawPosixAIOData) {
299246ee0f46SKevin Wolf         .bs             = bs,
299346ee0f46SKevin Wolf         .aio_fildes     = s->fd,
299446ee0f46SKevin Wolf         .aio_type       = QEMU_AIO_DISCARD,
299546ee0f46SKevin Wolf         .aio_offset     = offset,
299646ee0f46SKevin Wolf         .aio_nbytes     = bytes,
299746ee0f46SKevin Wolf     };
299846ee0f46SKevin Wolf 
299946ee0f46SKevin Wolf     if (blkdev) {
300046ee0f46SKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
300146ee0f46SKevin Wolf     }
300246ee0f46SKevin Wolf 
30031c450366SAnton Nefedov     ret = raw_thread_pool_submit(bs, handle_aiocb_discard, &acb);
30041c450366SAnton Nefedov     raw_account_discard(s, bytes, ret);
30051c450366SAnton Nefedov     return ret;
300646ee0f46SKevin Wolf }
300746ee0f46SKevin Wolf 
300846ee0f46SKevin Wolf static coroutine_fn int
30090c802287SVladimir Sementsov-Ogievskiy raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
301046ee0f46SKevin Wolf {
301146ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, false);
3012c1bb86cdSEric Blake }
3013c1bb86cdSEric Blake 
30147154d8aeSKevin Wolf static int coroutine_fn
3015f34b2bcfSVladimir Sementsov-Ogievskiy raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
30167154d8aeSKevin Wolf                      BdrvRequestFlags flags, bool blkdev)
30177154d8aeSKevin Wolf {
30187154d8aeSKevin Wolf     BDRVRawState *s = bs->opaque;
30197154d8aeSKevin Wolf     RawPosixAIOData acb;
30207154d8aeSKevin Wolf     ThreadPoolFunc *handler;
30217154d8aeSKevin Wolf 
3022292d06b9SMax Reitz #ifdef CONFIG_FALLOCATE
3023292d06b9SMax Reitz     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3024292d06b9SMax Reitz         BdrvTrackedRequest *req;
3025292d06b9SMax Reitz 
3026292d06b9SMax Reitz         /*
3027292d06b9SMax Reitz          * This is a workaround for a bug in the Linux XFS driver,
3028292d06b9SMax Reitz          * where writes submitted through the AIO interface will be
3029292d06b9SMax Reitz          * discarded if they happen beyond a concurrently running
3030292d06b9SMax Reitz          * fallocate() that increases the file length (i.e., both the
3031292d06b9SMax Reitz          * write and the fallocate() happen beyond the EOF).
3032292d06b9SMax Reitz          *
3033292d06b9SMax Reitz          * To work around it, we extend the tracked request for this
3034292d06b9SMax Reitz          * zero write until INT64_MAX (effectively infinity), and mark
3035292d06b9SMax Reitz          * it as serializing.
3036292d06b9SMax Reitz          *
3037292d06b9SMax Reitz          * We have to enable this workaround for all filesystems and
3038292d06b9SMax Reitz          * AIO modes (not just XFS with aio=native), because for
3039292d06b9SMax Reitz          * remote filesystems we do not know the host configuration.
3040292d06b9SMax Reitz          */
3041292d06b9SMax Reitz 
3042292d06b9SMax Reitz         req = bdrv_co_get_self_request(bs);
3043292d06b9SMax Reitz         assert(req);
3044292d06b9SMax Reitz         assert(req->type == BDRV_TRACKED_WRITE);
3045292d06b9SMax Reitz         assert(req->offset <= offset);
3046292d06b9SMax Reitz         assert(req->offset + req->bytes >= offset + bytes);
3047292d06b9SMax Reitz 
30488b117001SVladimir Sementsov-Ogievskiy         req->bytes = BDRV_MAX_LENGTH - req->offset;
30498b117001SVladimir Sementsov-Ogievskiy 
305069b55e03SVladimir Sementsov-Ogievskiy         bdrv_check_request(req->offset, req->bytes, &error_abort);
3051292d06b9SMax Reitz 
30528ac5aab2SVladimir Sementsov-Ogievskiy         bdrv_make_request_serialising(req, bs->bl.request_alignment);
3053292d06b9SMax Reitz     }
3054292d06b9SMax Reitz #endif
3055292d06b9SMax Reitz 
30567154d8aeSKevin Wolf     acb = (RawPosixAIOData) {
30577154d8aeSKevin Wolf         .bs             = bs,
30587154d8aeSKevin Wolf         .aio_fildes     = s->fd,
30597154d8aeSKevin Wolf         .aio_type       = QEMU_AIO_WRITE_ZEROES,
30607154d8aeSKevin Wolf         .aio_offset     = offset,
30617154d8aeSKevin Wolf         .aio_nbytes     = bytes,
30627154d8aeSKevin Wolf     };
30637154d8aeSKevin Wolf 
30647154d8aeSKevin Wolf     if (blkdev) {
30657154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
30667154d8aeSKevin Wolf     }
3067738301e1SKevin Wolf     if (flags & BDRV_REQ_NO_FALLBACK) {
3068738301e1SKevin Wolf         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
3069738301e1SKevin Wolf     }
30707154d8aeSKevin Wolf 
30717154d8aeSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
30727154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_DISCARD;
30737154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes_unmap;
30747154d8aeSKevin Wolf     } else {
30757154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes;
30767154d8aeSKevin Wolf     }
30777154d8aeSKevin Wolf 
30787154d8aeSKevin Wolf     return raw_thread_pool_submit(bs, handler, &acb);
30797154d8aeSKevin Wolf }
30807154d8aeSKevin Wolf 
3081c1bb86cdSEric Blake static int coroutine_fn raw_co_pwrite_zeroes(
3082c1bb86cdSEric Blake     BlockDriverState *bs, int64_t offset,
3083f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t bytes, BdrvRequestFlags flags)
3084c1bb86cdSEric Blake {
30857154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
3086c1bb86cdSEric Blake }
3087c1bb86cdSEric Blake 
30883d47eb0aSEmanuele Giuseppe Esposito static int coroutine_fn
30893d47eb0aSEmanuele Giuseppe Esposito raw_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3090c1bb86cdSEric Blake {
3091c1bb86cdSEric Blake     return 0;
3092c1bb86cdSEric Blake }
3093c1bb86cdSEric Blake 
30947f36a50aSHanna Reitz static ImageInfoSpecific *raw_get_specific_info(BlockDriverState *bs,
30957f36a50aSHanna Reitz                                                 Error **errp)
30967f36a50aSHanna Reitz {
30977f36a50aSHanna Reitz     ImageInfoSpecificFile *file_info = g_new0(ImageInfoSpecificFile, 1);
30987f36a50aSHanna Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
30997f36a50aSHanna Reitz 
31007f36a50aSHanna Reitz     *spec_info = (ImageInfoSpecific){
31017f36a50aSHanna Reitz         .type = IMAGE_INFO_SPECIFIC_KIND_FILE,
31027f36a50aSHanna Reitz         .u.file.data = file_info,
31037f36a50aSHanna Reitz     };
31047f36a50aSHanna Reitz 
31057f36a50aSHanna Reitz #ifdef FS_IOC_FSGETXATTR
31067f36a50aSHanna Reitz     {
31077f36a50aSHanna Reitz         BDRVRawState *s = bs->opaque;
31087f36a50aSHanna Reitz         struct fsxattr attr;
31097f36a50aSHanna Reitz         int ret;
31107f36a50aSHanna Reitz 
31117f36a50aSHanna Reitz         ret = ioctl(s->fd, FS_IOC_FSGETXATTR, &attr);
31127f36a50aSHanna Reitz         if (!ret && attr.fsx_extsize != 0) {
31137f36a50aSHanna Reitz             file_info->has_extent_size_hint = true;
31147f36a50aSHanna Reitz             file_info->extent_size_hint = attr.fsx_extsize;
31157f36a50aSHanna Reitz         }
31167f36a50aSHanna Reitz     }
31177f36a50aSHanna Reitz #endif
31187f36a50aSHanna Reitz 
31197f36a50aSHanna Reitz     return spec_info;
31207f36a50aSHanna Reitz }
31217f36a50aSHanna Reitz 
3122d9245599SAnton Nefedov static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
3123d9245599SAnton Nefedov {
3124d9245599SAnton Nefedov     BDRVRawState *s = bs->opaque;
3125d9245599SAnton Nefedov     return (BlockStatsSpecificFile) {
3126d9245599SAnton Nefedov         .discard_nb_ok = s->stats.discard_nb_ok,
3127d9245599SAnton Nefedov         .discard_nb_failed = s->stats.discard_nb_failed,
3128d9245599SAnton Nefedov         .discard_bytes_ok = s->stats.discard_bytes_ok,
3129d9245599SAnton Nefedov     };
3130d9245599SAnton Nefedov }
3131d9245599SAnton Nefedov 
3132d9245599SAnton Nefedov static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3133d9245599SAnton Nefedov {
3134d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3135d9245599SAnton Nefedov 
3136d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_FILE;
3137d9245599SAnton Nefedov     stats->u.file = get_blockstats_specific_file(bs);
3138d9245599SAnton Nefedov 
3139d9245599SAnton Nefedov     return stats;
3140d9245599SAnton Nefedov }
3141d9245599SAnton Nefedov 
314214176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
3143d9245599SAnton Nefedov static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3144d9245599SAnton Nefedov {
3145d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3146d9245599SAnton Nefedov 
3147d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3148d9245599SAnton Nefedov     stats->u.host_device = get_blockstats_specific_file(bs);
3149d9245599SAnton Nefedov 
3150d9245599SAnton Nefedov     return stats;
3151d9245599SAnton Nefedov }
315214176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
3153d9245599SAnton Nefedov 
3154c1bb86cdSEric Blake static QemuOptsList raw_create_opts = {
3155c1bb86cdSEric Blake     .name = "raw-create-opts",
3156c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3157c1bb86cdSEric Blake     .desc = {
3158c1bb86cdSEric Blake         {
3159c1bb86cdSEric Blake             .name = BLOCK_OPT_SIZE,
3160c1bb86cdSEric Blake             .type = QEMU_OPT_SIZE,
3161c1bb86cdSEric Blake             .help = "Virtual disk size"
3162c1bb86cdSEric Blake         },
3163c1bb86cdSEric Blake         {
3164c1bb86cdSEric Blake             .name = BLOCK_OPT_NOCOW,
3165c1bb86cdSEric Blake             .type = QEMU_OPT_BOOL,
3166c1bb86cdSEric Blake             .help = "Turn off copy-on-write (valid only on btrfs)"
3167c1bb86cdSEric Blake         },
3168c1bb86cdSEric Blake         {
3169c1bb86cdSEric Blake             .name = BLOCK_OPT_PREALLOC,
3170c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
3171abea0053SStefano Garzarella             .help = "Preallocation mode (allowed values: off"
3172abea0053SStefano Garzarella #ifdef CONFIG_POSIX_FALLOCATE
3173abea0053SStefano Garzarella                     ", falloc"
3174abea0053SStefano Garzarella #endif
3175abea0053SStefano Garzarella                     ", full)"
3176c1bb86cdSEric Blake         },
3177ffa244c8SKevin Wolf         {
3178ffa244c8SKevin Wolf             .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3179ffa244c8SKevin Wolf             .type = QEMU_OPT_SIZE,
3180ffa244c8SKevin Wolf             .help = "Extent size hint for the image file, 0 to disable"
3181ffa244c8SKevin Wolf         },
3182c1bb86cdSEric Blake         { /* end of list */ }
3183c1bb86cdSEric Blake     }
3184c1bb86cdSEric Blake };
3185c1bb86cdSEric Blake 
3186244a5668SFam Zheng static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3187244a5668SFam Zheng                           Error **errp)
3188244a5668SFam Zheng {
31896ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
319072373e40SVladimir Sementsov-Ogievskiy     int input_flags = s->reopen_state ? s->reopen_state->flags : bs->open_flags;
31916ceabe6fSKevin Wolf     int open_flags;
31926ceabe6fSKevin Wolf     int ret;
31936ceabe6fSKevin Wolf 
31946ceabe6fSKevin Wolf     /* We may need a new fd if auto-read-only switches the mode */
319572373e40SVladimir Sementsov-Ogievskiy     ret = raw_reconfigure_getfd(bs, input_flags, &open_flags, perm,
31966ceabe6fSKevin Wolf                                 false, errp);
31976ceabe6fSKevin Wolf     if (ret < 0) {
31986ceabe6fSKevin Wolf         return ret;
31996ceabe6fSKevin Wolf     } else if (ret != s->fd) {
320072373e40SVladimir Sementsov-Ogievskiy         Error *local_err = NULL;
320172373e40SVladimir Sementsov-Ogievskiy 
320272373e40SVladimir Sementsov-Ogievskiy         /*
320372373e40SVladimir Sementsov-Ogievskiy          * Fail already check_perm() if we can't get a working O_DIRECT
320472373e40SVladimir Sementsov-Ogievskiy          * alignment with the new fd.
320572373e40SVladimir Sementsov-Ogievskiy          */
320672373e40SVladimir Sementsov-Ogievskiy         raw_probe_alignment(bs, ret, &local_err);
320772373e40SVladimir Sementsov-Ogievskiy         if (local_err) {
320872373e40SVladimir Sementsov-Ogievskiy             error_propagate(errp, local_err);
320972373e40SVladimir Sementsov-Ogievskiy             return -EINVAL;
321072373e40SVladimir Sementsov-Ogievskiy         }
321172373e40SVladimir Sementsov-Ogievskiy 
32126ceabe6fSKevin Wolf         s->perm_change_fd = ret;
3213094e3639SMax Reitz         s->perm_change_flags = open_flags;
32146ceabe6fSKevin Wolf     }
32156ceabe6fSKevin Wolf 
32166ceabe6fSKevin Wolf     /* Prepare permissions on old fd to avoid conflicts between old and new,
32176ceabe6fSKevin Wolf      * but keep everything locked that new will need. */
32186ceabe6fSKevin Wolf     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
32196ceabe6fSKevin Wolf     if (ret < 0) {
32206ceabe6fSKevin Wolf         goto fail;
32216ceabe6fSKevin Wolf     }
32226ceabe6fSKevin Wolf 
32236ceabe6fSKevin Wolf     /* Copy locks to the new fd */
3224eb43ea16SLi Feng     if (s->perm_change_fd && s->use_lock) {
32256ceabe6fSKevin Wolf         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
32266ceabe6fSKevin Wolf                                    false, errp);
32276ceabe6fSKevin Wolf         if (ret < 0) {
32286ceabe6fSKevin Wolf             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
32296ceabe6fSKevin Wolf             goto fail;
32306ceabe6fSKevin Wolf         }
32316ceabe6fSKevin Wolf     }
32326ceabe6fSKevin Wolf     return 0;
32336ceabe6fSKevin Wolf 
32346ceabe6fSKevin Wolf fail:
323572373e40SVladimir Sementsov-Ogievskiy     if (s->perm_change_fd) {
32366ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
32376ceabe6fSKevin Wolf     }
32386ceabe6fSKevin Wolf     s->perm_change_fd = 0;
32396ceabe6fSKevin Wolf     return ret;
3240244a5668SFam Zheng }
3241244a5668SFam Zheng 
3242244a5668SFam Zheng static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3243244a5668SFam Zheng {
3244244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
32456ceabe6fSKevin Wolf 
32466ceabe6fSKevin Wolf     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
32476ceabe6fSKevin Wolf      * called after .bdrv_reopen_commit) */
32486ceabe6fSKevin Wolf     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
32496ceabe6fSKevin Wolf         qemu_close(s->fd);
32506ceabe6fSKevin Wolf         s->fd = s->perm_change_fd;
3251094e3639SMax Reitz         s->open_flags = s->perm_change_flags;
32526ceabe6fSKevin Wolf     }
32536ceabe6fSKevin Wolf     s->perm_change_fd = 0;
32546ceabe6fSKevin Wolf 
3255244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3256244a5668SFam Zheng     s->perm = perm;
3257244a5668SFam Zheng     s->shared_perm = shared;
3258244a5668SFam Zheng }
3259244a5668SFam Zheng 
3260244a5668SFam Zheng static void raw_abort_perm_update(BlockDriverState *bs)
3261244a5668SFam Zheng {
32626ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
32636ceabe6fSKevin Wolf 
32646ceabe6fSKevin Wolf     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
32656ceabe6fSKevin Wolf      * the file descriptor. */
326672373e40SVladimir Sementsov-Ogievskiy     if (s->perm_change_fd) {
32676ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
32686ceabe6fSKevin Wolf     }
32696ceabe6fSKevin Wolf     s->perm_change_fd = 0;
32706ceabe6fSKevin Wolf 
3271244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3272244a5668SFam Zheng }
3273244a5668SFam Zheng 
3274742bf09bSEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK raw_co_copy_range_from(
327548535049SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
327648535049SVladimir Sementsov-Ogievskiy         BdrvChild *dst, int64_t dst_offset, int64_t bytes,
327767b51fb9SVladimir Sementsov-Ogievskiy         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
32781efad060SFam Zheng {
327967b51fb9SVladimir Sementsov-Ogievskiy     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
328067b51fb9SVladimir Sementsov-Ogievskiy                                  read_flags, write_flags);
32811efad060SFam Zheng }
32821efad060SFam Zheng 
3283742bf09bSEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK
3284742bf09bSEmanuele Giuseppe Esposito raw_co_copy_range_to(BlockDriverState *bs,
3285742bf09bSEmanuele Giuseppe Esposito                      BdrvChild *src, int64_t src_offset,
3286742bf09bSEmanuele Giuseppe Esposito                      BdrvChild *dst, int64_t dst_offset,
3287742bf09bSEmanuele Giuseppe Esposito                      int64_t bytes, BdrvRequestFlags read_flags,
328867b51fb9SVladimir Sementsov-Ogievskiy                      BdrvRequestFlags write_flags)
32891efad060SFam Zheng {
329058a209c4SKevin Wolf     RawPosixAIOData acb;
32911efad060SFam Zheng     BDRVRawState *s = bs->opaque;
32921efad060SFam Zheng     BDRVRawState *src_s;
32931efad060SFam Zheng 
32941efad060SFam Zheng     assert(dst->bs == bs);
32951efad060SFam Zheng     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
32961efad060SFam Zheng         return -ENOTSUP;
32971efad060SFam Zheng     }
32981efad060SFam Zheng 
32991efad060SFam Zheng     src_s = src->bs->opaque;
33009f850f67SFam Zheng     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
33011efad060SFam Zheng         return -EIO;
33021efad060SFam Zheng     }
330358a209c4SKevin Wolf 
330458a209c4SKevin Wolf     acb = (RawPosixAIOData) {
330558a209c4SKevin Wolf         .bs             = bs,
330658a209c4SKevin Wolf         .aio_type       = QEMU_AIO_COPY_RANGE,
330758a209c4SKevin Wolf         .aio_fildes     = src_s->fd,
330858a209c4SKevin Wolf         .aio_offset     = src_offset,
330958a209c4SKevin Wolf         .aio_nbytes     = bytes,
331058a209c4SKevin Wolf         .copy_range     = {
331158a209c4SKevin Wolf             .aio_fd2        = s->fd,
331258a209c4SKevin Wolf             .aio_offset2    = dst_offset,
331358a209c4SKevin Wolf         },
331458a209c4SKevin Wolf     };
331558a209c4SKevin Wolf 
331658a209c4SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_copy_range, &acb);
33171efad060SFam Zheng }
33181efad060SFam Zheng 
3319c1bb86cdSEric Blake BlockDriver bdrv_file = {
3320c1bb86cdSEric Blake     .format_name = "file",
3321c1bb86cdSEric Blake     .protocol_name = "file",
3322c1bb86cdSEric Blake     .instance_size = sizeof(BDRVRawState),
3323c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3324c1bb86cdSEric Blake     .bdrv_probe = NULL, /* no probe for protocols */
3325c1bb86cdSEric Blake     .bdrv_parse_filename = raw_parse_filename,
3326c1bb86cdSEric Blake     .bdrv_file_open = raw_open,
3327c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3328c1bb86cdSEric Blake     .bdrv_reopen_commit = raw_reopen_commit,
3329c1bb86cdSEric Blake     .bdrv_reopen_abort = raw_reopen_abort,
3330c1bb86cdSEric Blake     .bdrv_close = raw_close,
3331927f11e1SKevin Wolf     .bdrv_co_create = raw_co_create,
3332efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = raw_co_create_opts,
3333c1bb86cdSEric Blake     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3334a290f085SEric Blake     .bdrv_co_block_status = raw_co_block_status,
3335dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3336c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
33379bffae14SDaniel Henrique Barboza     .bdrv_co_delete_file = raw_co_delete_file,
3338c1bb86cdSEric Blake 
3339c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3340c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
334133d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
334233d70fb6SKevin Wolf     .bdrv_co_pdiscard       = raw_co_pdiscard,
33431efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
33441efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3345c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
33468f497454SEmanuele Giuseppe Esposito     .bdrv_co_io_plug        = raw_co_io_plug,
334709d9fc97SEmanuele Giuseppe Esposito     .bdrv_co_io_unplug      = raw_co_io_unplug,
3348ed6e2161SNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3349c1bb86cdSEric Blake 
3350061ca8a3SKevin Wolf     .bdrv_co_truncate                   = raw_co_truncate,
3351c86422c5SEmanuele Giuseppe Esposito     .bdrv_co_getlength                  = raw_co_getlength,
33523d47eb0aSEmanuele Giuseppe Esposito     .bdrv_co_get_info                   = raw_co_get_info,
33537f36a50aSHanna Reitz     .bdrv_get_specific_info             = raw_get_specific_info,
335482618d7bSEmanuele Giuseppe Esposito     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
3355d9245599SAnton Nefedov     .bdrv_get_specific_stats = raw_get_specific_stats,
3356244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3357244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3358244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3359c1bb86cdSEric Blake     .create_opts = &raw_create_opts,
33608a2ce0bcSAlberto Garcia     .mutable_opts = mutable_opts,
3361c1bb86cdSEric Blake };
3362c1bb86cdSEric Blake 
3363c1bb86cdSEric Blake /***********************************************/
3364c1bb86cdSEric Blake /* host device */
3365c1bb86cdSEric Blake 
336614176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
336714176c8dSJoelle van Dyne 
3368c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3369c1bb86cdSEric Blake static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3370c1bb86cdSEric Blake                                 CFIndex maxPathSize, int flags);
3371aa44d3f6SPhilippe Mathieu-Daudé 
3372aa44d3f6SPhilippe Mathieu-Daudé #if !defined(MAC_OS_VERSION_12_0) \
3373aa44d3f6SPhilippe Mathieu-Daudé     || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3374aa44d3f6SPhilippe Mathieu-Daudé #define IOMainPort IOMasterPort
3375aa44d3f6SPhilippe Mathieu-Daudé #endif
3376aa44d3f6SPhilippe Mathieu-Daudé 
3377c1bb86cdSEric Blake static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3378c1bb86cdSEric Blake {
3379c1bb86cdSEric Blake     kern_return_t kernResult = KERN_FAILURE;
3380aa44d3f6SPhilippe Mathieu-Daudé     mach_port_t mainPort;
3381c1bb86cdSEric Blake     CFMutableDictionaryRef  classesToMatch;
3382c1bb86cdSEric Blake     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3383c1bb86cdSEric Blake     char *mediaType = NULL;
3384c1bb86cdSEric Blake 
3385aa44d3f6SPhilippe Mathieu-Daudé     kernResult = IOMainPort(MACH_PORT_NULL, &mainPort);
3386c1bb86cdSEric Blake     if ( KERN_SUCCESS != kernResult ) {
3387aa44d3f6SPhilippe Mathieu-Daudé         printf("IOMainPort returned %d\n", kernResult);
3388c1bb86cdSEric Blake     }
3389c1bb86cdSEric Blake 
3390c1bb86cdSEric Blake     int index;
3391c1bb86cdSEric Blake     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3392c1bb86cdSEric Blake         classesToMatch = IOServiceMatching(matching_array[index]);
3393c1bb86cdSEric Blake         if (classesToMatch == NULL) {
3394c1bb86cdSEric Blake             error_report("IOServiceMatching returned NULL for %s",
3395c1bb86cdSEric Blake                          matching_array[index]);
3396c1bb86cdSEric Blake             continue;
3397c1bb86cdSEric Blake         }
3398c1bb86cdSEric Blake         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3399c1bb86cdSEric Blake                              kCFBooleanTrue);
3400aa44d3f6SPhilippe Mathieu-Daudé         kernResult = IOServiceGetMatchingServices(mainPort, classesToMatch,
3401c1bb86cdSEric Blake                                                   mediaIterator);
3402c1bb86cdSEric Blake         if (kernResult != KERN_SUCCESS) {
3403c1bb86cdSEric Blake             error_report("Note: IOServiceGetMatchingServices returned %d",
3404c1bb86cdSEric Blake                          kernResult);
3405c1bb86cdSEric Blake             continue;
3406c1bb86cdSEric Blake         }
3407c1bb86cdSEric Blake 
3408c1bb86cdSEric Blake         /* If a match was found, leave the loop */
3409c1bb86cdSEric Blake         if (*mediaIterator != 0) {
34104f7d28d7SLaurent Vivier             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3411c1bb86cdSEric Blake             mediaType = g_strdup(matching_array[index]);
3412c1bb86cdSEric Blake             break;
3413c1bb86cdSEric Blake         }
3414c1bb86cdSEric Blake     }
3415c1bb86cdSEric Blake     return mediaType;
3416c1bb86cdSEric Blake }
3417c1bb86cdSEric Blake 
3418c1bb86cdSEric Blake kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3419c1bb86cdSEric Blake                          CFIndex maxPathSize, int flags)
3420c1bb86cdSEric Blake {
3421c1bb86cdSEric Blake     io_object_t     nextMedia;
3422c1bb86cdSEric Blake     kern_return_t   kernResult = KERN_FAILURE;
3423c1bb86cdSEric Blake     *bsdPath = '\0';
3424c1bb86cdSEric Blake     nextMedia = IOIteratorNext( mediaIterator );
3425c1bb86cdSEric Blake     if ( nextMedia )
3426c1bb86cdSEric Blake     {
3427c1bb86cdSEric Blake         CFTypeRef   bsdPathAsCFString;
3428c1bb86cdSEric Blake     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3429c1bb86cdSEric Blake         if ( bsdPathAsCFString ) {
3430c1bb86cdSEric Blake             size_t devPathLength;
3431c1bb86cdSEric Blake             strcpy( bsdPath, _PATH_DEV );
3432c1bb86cdSEric Blake             if (flags & BDRV_O_NOCACHE) {
3433c1bb86cdSEric Blake                 strcat(bsdPath, "r");
3434c1bb86cdSEric Blake             }
3435c1bb86cdSEric Blake             devPathLength = strlen( bsdPath );
3436c1bb86cdSEric Blake             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3437c1bb86cdSEric Blake                 kernResult = KERN_SUCCESS;
3438c1bb86cdSEric Blake             }
3439c1bb86cdSEric Blake             CFRelease( bsdPathAsCFString );
3440c1bb86cdSEric Blake         }
3441c1bb86cdSEric Blake         IOObjectRelease( nextMedia );
3442c1bb86cdSEric Blake     }
3443c1bb86cdSEric Blake 
3444c1bb86cdSEric Blake     return kernResult;
3445c1bb86cdSEric Blake }
3446c1bb86cdSEric Blake 
3447c1bb86cdSEric Blake /* Sets up a real cdrom for use in QEMU */
3448c1bb86cdSEric Blake static bool setup_cdrom(char *bsd_path, Error **errp)
3449c1bb86cdSEric Blake {
3450c1bb86cdSEric Blake     int index, num_of_test_partitions = 2, fd;
3451c1bb86cdSEric Blake     char test_partition[MAXPATHLEN];
3452c1bb86cdSEric Blake     bool partition_found = false;
3453c1bb86cdSEric Blake 
3454c1bb86cdSEric Blake     /* look for a working partition */
3455c1bb86cdSEric Blake     for (index = 0; index < num_of_test_partitions; index++) {
3456c1bb86cdSEric Blake         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3457c1bb86cdSEric Blake                  index);
3458b18a24a9SDaniel P. Berrangé         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
3459c1bb86cdSEric Blake         if (fd >= 0) {
3460c1bb86cdSEric Blake             partition_found = true;
3461c1bb86cdSEric Blake             qemu_close(fd);
3462c1bb86cdSEric Blake             break;
3463c1bb86cdSEric Blake         }
3464c1bb86cdSEric Blake     }
3465c1bb86cdSEric Blake 
3466c1bb86cdSEric Blake     /* if a working partition on the device was not found */
3467c1bb86cdSEric Blake     if (partition_found == false) {
3468c1bb86cdSEric Blake         error_setg(errp, "Failed to find a working partition on disc");
3469c1bb86cdSEric Blake     } else {
34704f7d28d7SLaurent Vivier         trace_file_setup_cdrom(test_partition);
3471c1bb86cdSEric Blake         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
3472c1bb86cdSEric Blake     }
3473c1bb86cdSEric Blake     return partition_found;
3474c1bb86cdSEric Blake }
3475c1bb86cdSEric Blake 
3476c1bb86cdSEric Blake /* Prints directions on mounting and unmounting a device */
3477c1bb86cdSEric Blake static void print_unmounting_directions(const char *file_name)
3478c1bb86cdSEric Blake {
3479c1bb86cdSEric Blake     error_report("If device %s is mounted on the desktop, unmount"
3480c1bb86cdSEric Blake                  " it first before using it in QEMU", file_name);
3481c1bb86cdSEric Blake     error_report("Command to unmount device: diskutil unmountDisk %s",
3482c1bb86cdSEric Blake                  file_name);
3483c1bb86cdSEric Blake     error_report("Command to mount device: diskutil mountDisk %s", file_name);
3484c1bb86cdSEric Blake }
3485c1bb86cdSEric Blake 
3486c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3487c1bb86cdSEric Blake 
3488c1bb86cdSEric Blake static int hdev_probe_device(const char *filename)
3489c1bb86cdSEric Blake {
3490c1bb86cdSEric Blake     struct stat st;
3491c1bb86cdSEric Blake 
3492c1bb86cdSEric Blake     /* allow a dedicated CD-ROM driver to match with a higher priority */
3493c1bb86cdSEric Blake     if (strstart(filename, "/dev/cdrom", NULL))
3494c1bb86cdSEric Blake         return 50;
3495c1bb86cdSEric Blake 
3496c1bb86cdSEric Blake     if (stat(filename, &st) >= 0 &&
3497c1bb86cdSEric Blake             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
3498c1bb86cdSEric Blake         return 100;
3499c1bb86cdSEric Blake     }
3500c1bb86cdSEric Blake 
3501c1bb86cdSEric Blake     return 0;
3502c1bb86cdSEric Blake }
3503c1bb86cdSEric Blake 
3504c1bb86cdSEric Blake static void hdev_parse_filename(const char *filename, QDict *options,
3505c1bb86cdSEric Blake                                 Error **errp)
3506c1bb86cdSEric Blake {
350703c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
3508c1bb86cdSEric Blake }
3509c1bb86cdSEric Blake 
3510c1bb86cdSEric Blake static bool hdev_is_sg(BlockDriverState *bs)
3511c1bb86cdSEric Blake {
3512c1bb86cdSEric Blake 
3513c1bb86cdSEric Blake #if defined(__linux__)
3514c1bb86cdSEric Blake 
3515c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3516c1bb86cdSEric Blake     struct stat st;
3517c1bb86cdSEric Blake     struct sg_scsi_id scsiid;
3518c1bb86cdSEric Blake     int sg_version;
3519c1bb86cdSEric Blake     int ret;
3520c1bb86cdSEric Blake 
3521c1bb86cdSEric Blake     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
3522c1bb86cdSEric Blake         return false;
3523c1bb86cdSEric Blake     }
3524c1bb86cdSEric Blake 
3525c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
3526c1bb86cdSEric Blake     if (ret < 0) {
3527c1bb86cdSEric Blake         return false;
3528c1bb86cdSEric Blake     }
3529c1bb86cdSEric Blake 
3530c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
3531c1bb86cdSEric Blake     if (ret >= 0) {
35324f7d28d7SLaurent Vivier         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3533c1bb86cdSEric Blake         return true;
3534c1bb86cdSEric Blake     }
3535c1bb86cdSEric Blake 
3536c1bb86cdSEric Blake #endif
3537c1bb86cdSEric Blake 
3538c1bb86cdSEric Blake     return false;
3539c1bb86cdSEric Blake }
3540c1bb86cdSEric Blake 
3541c1bb86cdSEric Blake static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
3542c1bb86cdSEric Blake                      Error **errp)
3543c1bb86cdSEric Blake {
3544c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3545c1bb86cdSEric Blake     int ret;
3546c1bb86cdSEric Blake 
3547c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3548129c7d1cSMarkus Armbruster     /*
3549129c7d1cSMarkus Armbruster      * Caution: while qdict_get_str() is fine, getting non-string types
3550129c7d1cSMarkus Armbruster      * would require more care.  When @options come from -blockdev or
3551129c7d1cSMarkus Armbruster      * blockdev_add, its members are typed according to the QAPI
3552129c7d1cSMarkus Armbruster      * schema, but when they come from -drive, they're all QString.
3553129c7d1cSMarkus Armbruster      */
3554c1bb86cdSEric Blake     const char *filename = qdict_get_str(options, "filename");
3555c1bb86cdSEric Blake     char bsd_path[MAXPATHLEN] = "";
3556c1bb86cdSEric Blake     bool error_occurred = false;
3557c1bb86cdSEric Blake 
3558c1bb86cdSEric Blake     /* If using a real cdrom */
3559c1bb86cdSEric Blake     if (strcmp(filename, "/dev/cdrom") == 0) {
3560c1bb86cdSEric Blake         char *mediaType = NULL;
3561c1bb86cdSEric Blake         kern_return_t ret_val;
3562c1bb86cdSEric Blake         io_iterator_t mediaIterator = 0;
3563c1bb86cdSEric Blake 
3564c1bb86cdSEric Blake         mediaType = FindEjectableOpticalMedia(&mediaIterator);
3565c1bb86cdSEric Blake         if (mediaType == NULL) {
3566c1bb86cdSEric Blake             error_setg(errp, "Please make sure your CD/DVD is in the optical"
3567c1bb86cdSEric Blake                        " drive");
3568c1bb86cdSEric Blake             error_occurred = true;
3569c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3570c1bb86cdSEric Blake         }
3571c1bb86cdSEric Blake 
3572c1bb86cdSEric Blake         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
3573c1bb86cdSEric Blake         if (ret_val != KERN_SUCCESS) {
3574c1bb86cdSEric Blake             error_setg(errp, "Could not get BSD path for optical drive");
3575c1bb86cdSEric Blake             error_occurred = true;
3576c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3577c1bb86cdSEric Blake         }
3578c1bb86cdSEric Blake 
3579c1bb86cdSEric Blake         /* If a real optical drive was not found */
3580c1bb86cdSEric Blake         if (bsd_path[0] == '\0') {
3581c1bb86cdSEric Blake             error_setg(errp, "Failed to obtain bsd path for optical drive");
3582c1bb86cdSEric Blake             error_occurred = true;
3583c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3584c1bb86cdSEric Blake         }
3585c1bb86cdSEric Blake 
3586c1bb86cdSEric Blake         /* If using a cdrom disc and finding a partition on the disc failed */
3587c1bb86cdSEric Blake         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
3588c1bb86cdSEric Blake             setup_cdrom(bsd_path, errp) == false) {
3589c1bb86cdSEric Blake             print_unmounting_directions(bsd_path);
3590c1bb86cdSEric Blake             error_occurred = true;
3591c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3592c1bb86cdSEric Blake         }
3593c1bb86cdSEric Blake 
359446f5ac20SEric Blake         qdict_put_str(options, "filename", bsd_path);
3595c1bb86cdSEric Blake 
3596c1bb86cdSEric Blake hdev_open_Mac_error:
3597c1bb86cdSEric Blake         g_free(mediaType);
3598c1bb86cdSEric Blake         if (mediaIterator) {
3599c1bb86cdSEric Blake             IOObjectRelease(mediaIterator);
3600c1bb86cdSEric Blake         }
3601c1bb86cdSEric Blake         if (error_occurred) {
3602c1bb86cdSEric Blake             return -ENOENT;
3603c1bb86cdSEric Blake         }
3604c1bb86cdSEric Blake     }
3605c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3606c1bb86cdSEric Blake 
3607c1bb86cdSEric Blake     s->type = FTYPE_FILE;
3608c1bb86cdSEric Blake 
3609668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3610c1bb86cdSEric Blake     if (ret < 0) {
3611c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3612c1bb86cdSEric Blake         if (*bsd_path) {
3613c1bb86cdSEric Blake             filename = bsd_path;
3614c1bb86cdSEric Blake         }
3615c1bb86cdSEric Blake         /* if a physical device experienced an error while being opened */
3616c1bb86cdSEric Blake         if (strncmp(filename, "/dev/", 5) == 0) {
3617c1bb86cdSEric Blake             print_unmounting_directions(filename);
3618c1bb86cdSEric Blake         }
3619c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3620c1bb86cdSEric Blake         return ret;
3621c1bb86cdSEric Blake     }
3622c1bb86cdSEric Blake 
3623c1bb86cdSEric Blake     /* Since this does ioctl the device must be already opened */
3624c1bb86cdSEric Blake     bs->sg = hdev_is_sg(bs);
3625c1bb86cdSEric Blake 
3626c1bb86cdSEric Blake     return ret;
3627c1bb86cdSEric Blake }
3628c1bb86cdSEric Blake 
3629c1bb86cdSEric Blake #if defined(__linux__)
36302f3a7ab3SKevin Wolf static int coroutine_fn
36312f3a7ab3SKevin Wolf hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3632c1bb86cdSEric Blake {
3633c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
363403425671SKevin Wolf     RawPosixAIOData acb;
36352f3a7ab3SKevin Wolf     int ret;
3636c1bb86cdSEric Blake 
36372f3a7ab3SKevin Wolf     ret = fd_open(bs);
36382f3a7ab3SKevin Wolf     if (ret < 0) {
36392f3a7ab3SKevin Wolf         return ret;
36402f3a7ab3SKevin Wolf     }
3641c1bb86cdSEric Blake 
36427c9e5276SPaolo Bonzini     if (req == SG_IO && s->pr_mgr) {
36437c9e5276SPaolo Bonzini         struct sg_io_hdr *io_hdr = buf;
36447c9e5276SPaolo Bonzini         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
36457c9e5276SPaolo Bonzini             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
36467c9e5276SPaolo Bonzini             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
36472f3a7ab3SKevin Wolf                                       s->fd, io_hdr);
36487c9e5276SPaolo Bonzini         }
36497c9e5276SPaolo Bonzini     }
36507c9e5276SPaolo Bonzini 
365103425671SKevin Wolf     acb = (RawPosixAIOData) {
365203425671SKevin Wolf         .bs         = bs,
365303425671SKevin Wolf         .aio_type   = QEMU_AIO_IOCTL,
365403425671SKevin Wolf         .aio_fildes = s->fd,
365503425671SKevin Wolf         .aio_offset = 0,
365603425671SKevin Wolf         .ioctl      = {
365703425671SKevin Wolf             .buf        = buf,
365803425671SKevin Wolf             .cmd        = req,
365903425671SKevin Wolf         },
366003425671SKevin Wolf     };
366103425671SKevin Wolf 
366203425671SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_ioctl, &acb);
3663c1bb86cdSEric Blake }
3664c1bb86cdSEric Blake #endif /* linux */
3665c1bb86cdSEric Blake 
366633d70fb6SKevin Wolf static coroutine_fn int
36670c802287SVladimir Sementsov-Ogievskiy hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
3668c1bb86cdSEric Blake {
36691c450366SAnton Nefedov     BDRVRawState *s = bs->opaque;
367033d70fb6SKevin Wolf     int ret;
3671c1bb86cdSEric Blake 
367233d70fb6SKevin Wolf     ret = fd_open(bs);
367333d70fb6SKevin Wolf     if (ret < 0) {
36741c450366SAnton Nefedov         raw_account_discard(s, bytes, ret);
367533d70fb6SKevin Wolf         return ret;
3676c1bb86cdSEric Blake     }
367746ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, true);
3678c1bb86cdSEric Blake }
3679c1bb86cdSEric Blake 
3680c1bb86cdSEric Blake static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3681f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
3682c1bb86cdSEric Blake {
3683c1bb86cdSEric Blake     int rc;
3684c1bb86cdSEric Blake 
3685c1bb86cdSEric Blake     rc = fd_open(bs);
3686c1bb86cdSEric Blake     if (rc < 0) {
3687c1bb86cdSEric Blake         return rc;
3688c1bb86cdSEric Blake     }
368934fa110eSKevin Wolf 
36907154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
3691c1bb86cdSEric Blake }
3692c1bb86cdSEric Blake 
3693c1bb86cdSEric Blake static BlockDriver bdrv_host_device = {
3694c1bb86cdSEric Blake     .format_name        = "host_device",
3695c1bb86cdSEric Blake     .protocol_name        = "host_device",
3696c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3697c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3698c1bb86cdSEric Blake     .bdrv_probe_device  = hdev_probe_device,
3699c1bb86cdSEric Blake     .bdrv_parse_filename = hdev_parse_filename,
3700c1bb86cdSEric Blake     .bdrv_file_open     = hdev_open,
3701c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3702c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3703c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3704c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
37055a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
37065a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
37078a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3708dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3709c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3710c1bb86cdSEric Blake 
3711c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3712c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
371333d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
371433d70fb6SKevin Wolf     .bdrv_co_pdiscard       = hdev_co_pdiscard,
37151efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
37161efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3717c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
37188f497454SEmanuele Giuseppe Esposito     .bdrv_co_io_plug        = raw_co_io_plug,
371909d9fc97SEmanuele Giuseppe Esposito     .bdrv_co_io_unplug      = raw_co_io_unplug,
3720042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3721c1bb86cdSEric Blake 
3722061ca8a3SKevin Wolf     .bdrv_co_truncate                   = raw_co_truncate,
3723c86422c5SEmanuele Giuseppe Esposito     .bdrv_co_getlength                  = raw_co_getlength,
37243d47eb0aSEmanuele Giuseppe Esposito     .bdrv_co_get_info                   = raw_co_get_info,
37257f36a50aSHanna Reitz     .bdrv_get_specific_info             = raw_get_specific_info,
372682618d7bSEmanuele Giuseppe Esposito     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
3727d9245599SAnton Nefedov     .bdrv_get_specific_stats = hdev_get_specific_stats,
3728244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3729244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3730244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3731c1bb86cdSEric Blake     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3732c1bb86cdSEric Blake     .bdrv_probe_geometry = hdev_probe_geometry,
3733c1bb86cdSEric Blake 
3734c1bb86cdSEric Blake     /* generic scsi device */
3735c1bb86cdSEric Blake #ifdef __linux__
37362f3a7ab3SKevin Wolf     .bdrv_co_ioctl          = hdev_co_ioctl,
3737c1bb86cdSEric Blake #endif
3738c1bb86cdSEric Blake };
3739c1bb86cdSEric Blake 
3740c1bb86cdSEric Blake #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3741c1bb86cdSEric Blake static void cdrom_parse_filename(const char *filename, QDict *options,
3742c1bb86cdSEric Blake                                  Error **errp)
3743c1bb86cdSEric Blake {
374403c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3745c1bb86cdSEric Blake }
3746c1bb86cdSEric Blake #endif
3747c1bb86cdSEric Blake 
3748c1bb86cdSEric Blake #ifdef __linux__
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 
3754c1bb86cdSEric Blake     s->type = FTYPE_CD;
3755c1bb86cdSEric Blake 
3756c1bb86cdSEric Blake     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3757230ff739SJohn Snow     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3758c1bb86cdSEric Blake }
3759c1bb86cdSEric Blake 
3760c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3761c1bb86cdSEric Blake {
3762c1bb86cdSEric Blake     int fd, ret;
3763c1bb86cdSEric Blake     int prio = 0;
3764c1bb86cdSEric Blake     struct stat st;
3765c1bb86cdSEric Blake 
3766b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
3767c1bb86cdSEric Blake     if (fd < 0) {
3768c1bb86cdSEric Blake         goto out;
3769c1bb86cdSEric Blake     }
3770c1bb86cdSEric Blake     ret = fstat(fd, &st);
3771c1bb86cdSEric Blake     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3772c1bb86cdSEric Blake         goto outc;
3773c1bb86cdSEric Blake     }
3774c1bb86cdSEric Blake 
3775c1bb86cdSEric Blake     /* Attempt to detect via a CDROM specific ioctl */
3776c1bb86cdSEric Blake     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3777c1bb86cdSEric Blake     if (ret >= 0)
3778c1bb86cdSEric Blake         prio = 100;
3779c1bb86cdSEric Blake 
3780c1bb86cdSEric Blake outc:
3781c1bb86cdSEric Blake     qemu_close(fd);
3782c1bb86cdSEric Blake out:
3783c1bb86cdSEric Blake     return prio;
3784c1bb86cdSEric Blake }
3785c1bb86cdSEric Blake 
37861e97be91SEmanuele Giuseppe Esposito static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
3787c1bb86cdSEric Blake {
3788c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3789c1bb86cdSEric Blake     int ret;
3790c1bb86cdSEric Blake 
3791c1bb86cdSEric Blake     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3792c1bb86cdSEric Blake     return ret == CDS_DISC_OK;
3793c1bb86cdSEric Blake }
3794c1bb86cdSEric Blake 
37952531b390SEmanuele Giuseppe Esposito static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
3796c1bb86cdSEric Blake {
3797c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3798c1bb86cdSEric Blake 
3799c1bb86cdSEric Blake     if (eject_flag) {
3800c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3801c1bb86cdSEric Blake             perror("CDROMEJECT");
3802c1bb86cdSEric Blake     } else {
3803c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3804c1bb86cdSEric Blake             perror("CDROMEJECT");
3805c1bb86cdSEric Blake     }
3806c1bb86cdSEric Blake }
3807c1bb86cdSEric Blake 
38082c75261cSEmanuele Giuseppe Esposito static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
3809c1bb86cdSEric Blake {
3810c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3811c1bb86cdSEric Blake 
3812c1bb86cdSEric Blake     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3813c1bb86cdSEric Blake         /*
3814c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3815c1bb86cdSEric Blake          * mounts the CD-ROM
3816c1bb86cdSEric Blake          */
3817c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3818c1bb86cdSEric Blake     }
3819c1bb86cdSEric Blake }
3820c1bb86cdSEric Blake 
3821c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3822c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3823c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3824c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3825c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3826c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3827c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3828c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3829c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3830c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3831c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3832c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
38335a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
38345a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
38358a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3836dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3837c1bb86cdSEric Blake 
3838c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3839c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
384033d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3841c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
38428f497454SEmanuele Giuseppe Esposito     .bdrv_co_io_plug        = raw_co_io_plug,
384309d9fc97SEmanuele Giuseppe Esposito     .bdrv_co_io_unplug      = raw_co_io_unplug,
3844042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3845c1bb86cdSEric Blake 
3846061ca8a3SKevin Wolf     .bdrv_co_truncate                   = raw_co_truncate,
3847c86422c5SEmanuele Giuseppe Esposito     .bdrv_co_getlength                  = raw_co_getlength,
3848c1bb86cdSEric Blake     .has_variable_length                = true,
384982618d7bSEmanuele Giuseppe Esposito     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
3850c1bb86cdSEric Blake 
3851c1bb86cdSEric Blake     /* removable device support */
38521e97be91SEmanuele Giuseppe Esposito     .bdrv_co_is_inserted    = cdrom_co_is_inserted,
38532531b390SEmanuele Giuseppe Esposito     .bdrv_co_eject          = cdrom_co_eject,
38542c75261cSEmanuele Giuseppe Esposito     .bdrv_co_lock_medium    = cdrom_co_lock_medium,
3855c1bb86cdSEric Blake 
3856c1bb86cdSEric Blake     /* generic scsi device */
38572f3a7ab3SKevin Wolf     .bdrv_co_ioctl      = hdev_co_ioctl,
3858c1bb86cdSEric Blake };
3859c1bb86cdSEric Blake #endif /* __linux__ */
3860c1bb86cdSEric Blake 
3861c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3862c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3863c1bb86cdSEric Blake                       Error **errp)
3864c1bb86cdSEric Blake {
3865c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3866c1bb86cdSEric Blake     int ret;
3867c1bb86cdSEric Blake 
3868c1bb86cdSEric Blake     s->type = FTYPE_CD;
3869c1bb86cdSEric Blake 
3870668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3871c1bb86cdSEric Blake     if (ret) {
3872c1bb86cdSEric Blake         return ret;
3873c1bb86cdSEric Blake     }
3874c1bb86cdSEric Blake 
3875c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3876c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3877c1bb86cdSEric Blake     return 0;
3878c1bb86cdSEric Blake }
3879c1bb86cdSEric Blake 
3880c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3881c1bb86cdSEric Blake {
3882c1bb86cdSEric Blake     if (strstart(filename, "/dev/cd", NULL) ||
3883c1bb86cdSEric Blake             strstart(filename, "/dev/acd", NULL))
3884c1bb86cdSEric Blake         return 100;
3885c1bb86cdSEric Blake     return 0;
3886c1bb86cdSEric Blake }
3887c1bb86cdSEric Blake 
3888c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs)
3889c1bb86cdSEric Blake {
3890c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3891c1bb86cdSEric Blake     int fd;
3892c1bb86cdSEric Blake 
3893c1bb86cdSEric Blake     /*
3894c1bb86cdSEric Blake      * Force reread of possibly changed/newly loaded disc,
3895c1bb86cdSEric Blake      * FreeBSD seems to not notice sometimes...
3896c1bb86cdSEric Blake      */
3897c1bb86cdSEric Blake     if (s->fd >= 0)
3898c1bb86cdSEric Blake         qemu_close(s->fd);
3899b18a24a9SDaniel P. Berrangé     fd = qemu_open(bs->filename, s->open_flags, NULL);
3900c1bb86cdSEric Blake     if (fd < 0) {
3901c1bb86cdSEric Blake         s->fd = -1;
3902c1bb86cdSEric Blake         return -EIO;
3903c1bb86cdSEric Blake     }
3904c1bb86cdSEric Blake     s->fd = fd;
3905c1bb86cdSEric Blake 
3906c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3907c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3908c1bb86cdSEric Blake     return 0;
3909c1bb86cdSEric Blake }
3910c1bb86cdSEric Blake 
39111e97be91SEmanuele Giuseppe Esposito static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
3912c1bb86cdSEric Blake {
3913c86422c5SEmanuele Giuseppe Esposito     return raw_co_getlength(bs) > 0;
3914c1bb86cdSEric Blake }
3915c1bb86cdSEric Blake 
39162531b390SEmanuele Giuseppe Esposito static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
3917c1bb86cdSEric Blake {
3918c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3919c1bb86cdSEric Blake 
3920c1bb86cdSEric Blake     if (s->fd < 0)
3921c1bb86cdSEric Blake         return;
3922c1bb86cdSEric Blake 
3923c1bb86cdSEric Blake     (void) ioctl(s->fd, CDIOCALLOW);
3924c1bb86cdSEric Blake 
3925c1bb86cdSEric Blake     if (eject_flag) {
3926c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCEJECT) < 0)
3927c1bb86cdSEric Blake             perror("CDIOCEJECT");
3928c1bb86cdSEric Blake     } else {
3929c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3930c1bb86cdSEric Blake             perror("CDIOCCLOSE");
3931c1bb86cdSEric Blake     }
3932c1bb86cdSEric Blake 
3933c1bb86cdSEric Blake     cdrom_reopen(bs);
3934c1bb86cdSEric Blake }
3935c1bb86cdSEric Blake 
39362c75261cSEmanuele Giuseppe Esposito static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
3937c1bb86cdSEric Blake {
3938c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3939c1bb86cdSEric Blake 
3940c1bb86cdSEric Blake     if (s->fd < 0)
3941c1bb86cdSEric Blake         return;
3942c1bb86cdSEric Blake     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3943c1bb86cdSEric Blake         /*
3944c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3945c1bb86cdSEric Blake          * mounts the CD-ROM
3946c1bb86cdSEric Blake          */
3947c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3948c1bb86cdSEric Blake     }
3949c1bb86cdSEric Blake }
3950c1bb86cdSEric Blake 
3951c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3952c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3953c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3954c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3955c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3956c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3957c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3958c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3959c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3960c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3961c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3962c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
39635a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
39645a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
39658a2ce0bcSAlberto Garcia     .mutable_opts       = mutable_opts,
3966c1bb86cdSEric Blake 
3967c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3968c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
396933d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3970c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
39718f497454SEmanuele Giuseppe Esposito     .bdrv_co_io_plug        = raw_co_io_plug,
397209d9fc97SEmanuele Giuseppe Esposito     .bdrv_co_io_unplug      = raw_co_io_unplug,
3973042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3974c1bb86cdSEric Blake 
3975061ca8a3SKevin Wolf     .bdrv_co_truncate                   = raw_co_truncate,
3976c86422c5SEmanuele Giuseppe Esposito     .bdrv_co_getlength                  = raw_co_getlength,
3977c1bb86cdSEric Blake     .has_variable_length                = true,
397882618d7bSEmanuele Giuseppe Esposito     .bdrv_co_get_allocated_file_size    = raw_co_get_allocated_file_size,
3979c1bb86cdSEric Blake 
3980c1bb86cdSEric Blake     /* removable device support */
39811e97be91SEmanuele Giuseppe Esposito     .bdrv_co_is_inserted     = cdrom_co_is_inserted,
39822531b390SEmanuele Giuseppe Esposito     .bdrv_co_eject           = cdrom_co_eject,
39832c75261cSEmanuele Giuseppe Esposito     .bdrv_co_lock_medium     = cdrom_co_lock_medium,
3984c1bb86cdSEric Blake };
3985c1bb86cdSEric Blake #endif /* __FreeBSD__ */
3986c1bb86cdSEric Blake 
398714176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
398814176c8dSJoelle van Dyne 
3989c1bb86cdSEric Blake static void bdrv_file_init(void)
3990c1bb86cdSEric Blake {
3991c1bb86cdSEric Blake     /*
3992c1bb86cdSEric Blake      * Register all the drivers.  Note that order is important, the driver
3993c1bb86cdSEric Blake      * registered last will get probed first.
3994c1bb86cdSEric Blake      */
3995c1bb86cdSEric Blake     bdrv_register(&bdrv_file);
399614176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
3997c1bb86cdSEric Blake     bdrv_register(&bdrv_host_device);
3998c1bb86cdSEric Blake #ifdef __linux__
3999c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
4000c1bb86cdSEric Blake #endif
4001c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4002c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
4003c1bb86cdSEric Blake #endif
400414176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
4005c1bb86cdSEric Blake }
4006c1bb86cdSEric Blake 
4007c1bb86cdSEric Blake block_init(bdrv_file_init);
4008