xref: /qemu/block/file-posix.c (revision 512da211)
1c1bb86cdSEric Blake /*
2c1bb86cdSEric Blake  * Block driver for RAW files (posix)
3c1bb86cdSEric Blake  *
4c1bb86cdSEric Blake  * Copyright (c) 2006 Fabrice Bellard
5c1bb86cdSEric Blake  *
6c1bb86cdSEric Blake  * Permission is hereby granted, free of charge, to any person obtaining a copy
7c1bb86cdSEric Blake  * of this software and associated documentation files (the "Software"), to deal
8c1bb86cdSEric Blake  * in the Software without restriction, including without limitation the rights
9c1bb86cdSEric Blake  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10c1bb86cdSEric Blake  * copies of the Software, and to permit persons to whom the Software is
11c1bb86cdSEric Blake  * furnished to do so, subject to the following conditions:
12c1bb86cdSEric Blake  *
13c1bb86cdSEric Blake  * The above copyright notice and this permission notice shall be included in
14c1bb86cdSEric Blake  * all copies or substantial portions of the Software.
15c1bb86cdSEric Blake  *
16c1bb86cdSEric Blake  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17c1bb86cdSEric Blake  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18c1bb86cdSEric Blake  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19c1bb86cdSEric Blake  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20c1bb86cdSEric Blake  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21c1bb86cdSEric Blake  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22c1bb86cdSEric Blake  * THE SOFTWARE.
23c1bb86cdSEric Blake  */
24922a01a0SMarkus Armbruster 
25c1bb86cdSEric Blake #include "qemu/osdep.h"
26a8d25326SMarkus Armbruster #include "qemu-common.h"
27c1bb86cdSEric Blake #include "qapi/error.h"
28c1bb86cdSEric Blake #include "qemu/cutils.h"
29c1bb86cdSEric Blake #include "qemu/error-report.h"
30c1bb86cdSEric Blake #include "block/block_int.h"
31c1bb86cdSEric Blake #include "qemu/module.h"
32922a01a0SMarkus Armbruster #include "qemu/option.h"
33ffa244c8SKevin Wolf #include "qemu/units.h"
34c1bb86cdSEric Blake #include "trace.h"
35c1bb86cdSEric Blake #include "block/thread-pool.h"
36c1bb86cdSEric Blake #include "qemu/iov.h"
37c1bb86cdSEric Blake #include "block/raw-aio.h"
38452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
39c1bb86cdSEric Blake #include "qapi/qmp/qstring.h"
40c1bb86cdSEric Blake 
417c9e5276SPaolo Bonzini #include "scsi/pr-manager.h"
427c9e5276SPaolo Bonzini #include "scsi/constants.h"
437c9e5276SPaolo Bonzini 
44c1bb86cdSEric Blake #if defined(__APPLE__) && (__MACH__)
4514176c8dSJoelle van Dyne #include <sys/ioctl.h>
4614176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
47c1bb86cdSEric Blake #include <paths.h>
48c1bb86cdSEric Blake #include <sys/param.h>
490dfc7af2SAkihiko Odaki #include <sys/mount.h>
50c1bb86cdSEric Blake #include <IOKit/IOKitLib.h>
51c1bb86cdSEric Blake #include <IOKit/IOBSD.h>
52c1bb86cdSEric Blake #include <IOKit/storage/IOMediaBSDClient.h>
53c1bb86cdSEric Blake #include <IOKit/storage/IOMedia.h>
54c1bb86cdSEric Blake #include <IOKit/storage/IOCDMedia.h>
55c1bb86cdSEric Blake //#include <IOKit/storage/IOCDTypes.h>
56c1bb86cdSEric Blake #include <IOKit/storage/IODVDMedia.h>
57c1bb86cdSEric Blake #include <CoreFoundation/CoreFoundation.h>
5814176c8dSJoelle van Dyne #endif /* defined(HAVE_HOST_BLOCK_DEVICE) */
59c1bb86cdSEric Blake #endif
60c1bb86cdSEric Blake 
61c1bb86cdSEric Blake #ifdef __sun__
62c1bb86cdSEric Blake #define _POSIX_PTHREAD_SEMANTICS 1
63c1bb86cdSEric Blake #include <sys/dkio.h>
64c1bb86cdSEric Blake #endif
65c1bb86cdSEric Blake #ifdef __linux__
66c1bb86cdSEric Blake #include <sys/ioctl.h>
67c1bb86cdSEric Blake #include <sys/param.h>
681efad060SFam Zheng #include <sys/syscall.h>
695edc8557SKevin Wolf #include <sys/vfs.h>
70c1bb86cdSEric Blake #include <linux/cdrom.h>
71c1bb86cdSEric Blake #include <linux/fd.h>
72c1bb86cdSEric Blake #include <linux/fs.h>
73c1bb86cdSEric Blake #include <linux/hdreg.h>
745edc8557SKevin Wolf #include <linux/magic.h>
75c1bb86cdSEric Blake #include <scsi/sg.h>
76c1bb86cdSEric Blake #ifdef __s390__
77c1bb86cdSEric Blake #include <asm/dasd.h>
78c1bb86cdSEric Blake #endif
79c1bb86cdSEric Blake #ifndef FS_NOCOW_FL
80c1bb86cdSEric Blake #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
81c1bb86cdSEric Blake #endif
82c1bb86cdSEric Blake #endif
83c1bb86cdSEric Blake #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
84c1bb86cdSEric Blake #include <linux/falloc.h>
85c1bb86cdSEric Blake #endif
86c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
87c1bb86cdSEric Blake #include <sys/disk.h>
88c1bb86cdSEric Blake #include <sys/cdio.h>
89c1bb86cdSEric Blake #endif
90c1bb86cdSEric Blake 
91c1bb86cdSEric Blake #ifdef __OpenBSD__
92c1bb86cdSEric Blake #include <sys/ioctl.h>
93c1bb86cdSEric Blake #include <sys/disklabel.h>
94c1bb86cdSEric Blake #include <sys/dkio.h>
95c1bb86cdSEric Blake #endif
96c1bb86cdSEric Blake 
97c1bb86cdSEric Blake #ifdef __NetBSD__
98c1bb86cdSEric Blake #include <sys/ioctl.h>
99c1bb86cdSEric Blake #include <sys/disklabel.h>
100c1bb86cdSEric Blake #include <sys/dkio.h>
101c1bb86cdSEric Blake #include <sys/disk.h>
102c1bb86cdSEric Blake #endif
103c1bb86cdSEric Blake 
104c1bb86cdSEric Blake #ifdef __DragonFly__
105c1bb86cdSEric Blake #include <sys/ioctl.h>
106c1bb86cdSEric Blake #include <sys/diskslice.h>
107c1bb86cdSEric Blake #endif
108c1bb86cdSEric Blake 
109c1bb86cdSEric Blake #ifdef CONFIG_XFS
110c1bb86cdSEric Blake #include <xfs/xfs.h>
111c1bb86cdSEric Blake #endif
112c1bb86cdSEric Blake 
113c1bb86cdSEric Blake /* OS X does not have O_DSYNC */
114c1bb86cdSEric Blake #ifndef O_DSYNC
115c1bb86cdSEric Blake #ifdef O_SYNC
116c1bb86cdSEric Blake #define O_DSYNC O_SYNC
117c1bb86cdSEric Blake #elif defined(O_FSYNC)
118c1bb86cdSEric Blake #define O_DSYNC O_FSYNC
119c1bb86cdSEric Blake #endif
120c1bb86cdSEric Blake #endif
121c1bb86cdSEric Blake 
122c1bb86cdSEric Blake /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
123c1bb86cdSEric Blake #ifndef O_DIRECT
124c1bb86cdSEric Blake #define O_DIRECT O_DSYNC
125c1bb86cdSEric Blake #endif
126c1bb86cdSEric Blake 
127c1bb86cdSEric Blake #define FTYPE_FILE   0
128c1bb86cdSEric Blake #define FTYPE_CD     1
129c1bb86cdSEric Blake 
130c1bb86cdSEric Blake #define MAX_BLOCKSIZE	4096
131c1bb86cdSEric Blake 
132244a5668SFam Zheng /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
133244a5668SFam Zheng  * leaving a few more bytes for its future use. */
134244a5668SFam Zheng #define RAW_LOCK_PERM_BASE             100
135244a5668SFam Zheng #define RAW_LOCK_SHARED_BASE           200
136244a5668SFam Zheng 
137c1bb86cdSEric Blake typedef struct BDRVRawState {
138c1bb86cdSEric Blake     int fd;
139244a5668SFam Zheng     bool use_lock;
140c1bb86cdSEric Blake     int type;
141c1bb86cdSEric Blake     int open_flags;
142c1bb86cdSEric Blake     size_t buf_align;
143c1bb86cdSEric Blake 
144244a5668SFam Zheng     /* The current permissions. */
145244a5668SFam Zheng     uint64_t perm;
146244a5668SFam Zheng     uint64_t shared_perm;
147244a5668SFam Zheng 
1482996ffadSFam Zheng     /* The perms bits whose corresponding bytes are already locked in
149f2e3af29SFam Zheng      * s->fd. */
1502996ffadSFam Zheng     uint64_t locked_perm;
1512996ffadSFam Zheng     uint64_t locked_shared_perm;
1522996ffadSFam Zheng 
153684960d4SStefano Garzarella     uint64_t aio_max_batch;
154684960d4SStefano Garzarella 
1556ceabe6fSKevin Wolf     int perm_change_fd;
156094e3639SMax Reitz     int perm_change_flags;
157e0c9cf3aSKevin Wolf     BDRVReopenState *reopen_state;
158e0c9cf3aSKevin Wolf 
159c1bb86cdSEric Blake #ifdef CONFIG_XFS
160c1bb86cdSEric Blake     bool is_xfs:1;
161c1bb86cdSEric Blake #endif
162c1bb86cdSEric Blake     bool has_discard:1;
163c1bb86cdSEric Blake     bool has_write_zeroes:1;
164c1bb86cdSEric Blake     bool discard_zeroes:1;
165c1bb86cdSEric Blake     bool use_linux_aio:1;
166c6447510SAarushi Mehta     bool use_linux_io_uring:1;
167c7ddc882SDaniel P. Berrangé     int page_cache_inconsistent; /* errno from fdatasync failure */
168c1bb86cdSEric Blake     bool has_fallocate;
169c1bb86cdSEric Blake     bool needs_alignment;
170f357fcd8SStefan Hajnoczi     bool drop_cache;
17131be8a2aSStefan Hajnoczi     bool check_cache_dropped;
1721c450366SAnton Nefedov     struct {
1731c450366SAnton Nefedov         uint64_t discard_nb_ok;
1741c450366SAnton Nefedov         uint64_t discard_nb_failed;
1751c450366SAnton Nefedov         uint64_t discard_bytes_ok;
1761c450366SAnton Nefedov     } stats;
1777c9e5276SPaolo Bonzini 
1787c9e5276SPaolo Bonzini     PRManager *pr_mgr;
179c1bb86cdSEric Blake } BDRVRawState;
180c1bb86cdSEric Blake 
181c1bb86cdSEric Blake typedef struct BDRVRawReopenState {
182c1bb86cdSEric Blake     int open_flags;
183f357fcd8SStefan Hajnoczi     bool drop_cache;
18431be8a2aSStefan Hajnoczi     bool check_cache_dropped;
185c1bb86cdSEric Blake } BDRVRawReopenState;
186c1bb86cdSEric Blake 
18714176c8dSJoelle van Dyne static int fd_open(BlockDriverState *bs)
18814176c8dSJoelle van Dyne {
18914176c8dSJoelle van Dyne     BDRVRawState *s = bs->opaque;
19014176c8dSJoelle van Dyne 
19114176c8dSJoelle van Dyne     /* this is just to ensure s->fd is sane (its called by io ops) */
19214176c8dSJoelle van Dyne     if (s->fd >= 0) {
19314176c8dSJoelle van Dyne         return 0;
19414176c8dSJoelle van Dyne     }
19514176c8dSJoelle van Dyne     return -EIO;
19614176c8dSJoelle van Dyne }
19714176c8dSJoelle van Dyne 
198c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs);
199c1bb86cdSEric Blake 
200c1bb86cdSEric Blake typedef struct RawPosixAIOData {
201c1bb86cdSEric Blake     BlockDriverState *bs;
202c1bb86cdSEric Blake     int aio_type;
203d57c44d0SKevin Wolf     int aio_fildes;
204d57c44d0SKevin Wolf 
205d57c44d0SKevin Wolf     off_t aio_offset;
206d57c44d0SKevin Wolf     uint64_t aio_nbytes;
207d57c44d0SKevin Wolf 
20893f4e2ffSKevin Wolf     union {
20993f4e2ffSKevin Wolf         struct {
210d57c44d0SKevin Wolf             struct iovec *iov;
211d57c44d0SKevin Wolf             int niov;
212d57c44d0SKevin Wolf         } io;
213d57c44d0SKevin Wolf         struct {
214d57c44d0SKevin Wolf             uint64_t cmd;
215d57c44d0SKevin Wolf             void *buf;
216d57c44d0SKevin Wolf         } ioctl;
217d57c44d0SKevin Wolf         struct {
2181efad060SFam Zheng             int aio_fd2;
2191efad060SFam Zheng             off_t aio_offset2;
220d57c44d0SKevin Wolf         } copy_range;
22193f4e2ffSKevin Wolf         struct {
22293f4e2ffSKevin Wolf             PreallocMode prealloc;
22393f4e2ffSKevin Wolf             Error **errp;
224d57c44d0SKevin Wolf         } truncate;
22593f4e2ffSKevin Wolf     };
226c1bb86cdSEric Blake } RawPosixAIOData;
227c1bb86cdSEric Blake 
228c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
229c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs);
230c1bb86cdSEric Blake #endif
231c1bb86cdSEric Blake 
232797e3e38SDavid Edmondson /*
233797e3e38SDavid Edmondson  * Elide EAGAIN and EACCES details when failing to lock, as this
234797e3e38SDavid Edmondson  * indicates that the specified file region is already locked by
235797e3e38SDavid Edmondson  * another process, which is considered a common scenario.
236797e3e38SDavid Edmondson  */
237797e3e38SDavid Edmondson #define raw_lock_error_setg_errno(errp, err, fmt, ...)                  \
238797e3e38SDavid Edmondson     do {                                                                \
239797e3e38SDavid Edmondson         if ((err) == EAGAIN || (err) == EACCES) {                       \
240797e3e38SDavid Edmondson             error_setg((errp), (fmt), ## __VA_ARGS__);                  \
241797e3e38SDavid Edmondson         } else {                                                        \
242797e3e38SDavid Edmondson             error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__);     \
243797e3e38SDavid Edmondson         }                                                               \
244797e3e38SDavid Edmondson     } while (0)
245797e3e38SDavid Edmondson 
246c1bb86cdSEric Blake #if defined(__NetBSD__)
247db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
248c1bb86cdSEric Blake {
249c1bb86cdSEric Blake     static char namebuf[PATH_MAX];
250c1bb86cdSEric Blake     const char *dp, *fname;
251c1bb86cdSEric Blake     struct stat sb;
252c1bb86cdSEric Blake 
253c1bb86cdSEric Blake     fname = *filename;
254c1bb86cdSEric Blake     dp = strrchr(fname, '/');
255c1bb86cdSEric Blake     if (lstat(fname, &sb) < 0) {
256f6fc1e30SPaolo Bonzini         error_setg_file_open(errp, errno, fname);
257c1bb86cdSEric Blake         return -errno;
258c1bb86cdSEric Blake     }
259c1bb86cdSEric Blake 
260c1bb86cdSEric Blake     if (!S_ISBLK(sb.st_mode)) {
261c1bb86cdSEric Blake         return 0;
262c1bb86cdSEric Blake     }
263c1bb86cdSEric Blake 
264c1bb86cdSEric Blake     if (dp == NULL) {
265c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "r%s", fname);
266c1bb86cdSEric Blake     } else {
267c1bb86cdSEric Blake         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
268c1bb86cdSEric Blake             (int)(dp - fname), fname, dp + 1);
269c1bb86cdSEric Blake     }
270c1bb86cdSEric Blake     *filename = namebuf;
271db0754dfSFam Zheng     warn_report("%s is a block device, using %s", fname, *filename);
272c1bb86cdSEric Blake 
273c1bb86cdSEric Blake     return 0;
274c1bb86cdSEric Blake }
275c1bb86cdSEric Blake #else
276db0754dfSFam Zheng static int raw_normalize_devicepath(const char **filename, Error **errp)
277c1bb86cdSEric Blake {
278c1bb86cdSEric Blake     return 0;
279c1bb86cdSEric Blake }
280c1bb86cdSEric Blake #endif
281c1bb86cdSEric Blake 
282c1bb86cdSEric Blake /*
283c1bb86cdSEric Blake  * Get logical block size via ioctl. On success store it in @sector_size_p.
284c1bb86cdSEric Blake  */
285c1bb86cdSEric Blake static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
286c1bb86cdSEric Blake {
287c1bb86cdSEric Blake     unsigned int sector_size;
288c1bb86cdSEric Blake     bool success = false;
289700f9ce0SPeter Maydell     int i;
290c1bb86cdSEric Blake 
291c1bb86cdSEric Blake     errno = ENOTSUP;
292700f9ce0SPeter Maydell     static const unsigned long ioctl_list[] = {
293c1bb86cdSEric Blake #ifdef BLKSSZGET
294700f9ce0SPeter Maydell         BLKSSZGET,
295c1bb86cdSEric Blake #endif
296c1bb86cdSEric Blake #ifdef DKIOCGETBLOCKSIZE
297700f9ce0SPeter Maydell         DKIOCGETBLOCKSIZE,
298c1bb86cdSEric Blake #endif
299c1bb86cdSEric Blake #ifdef DIOCGSECTORSIZE
300700f9ce0SPeter Maydell         DIOCGSECTORSIZE,
301700f9ce0SPeter Maydell #endif
302700f9ce0SPeter Maydell     };
303700f9ce0SPeter Maydell 
304700f9ce0SPeter Maydell     /* Try a few ioctls to get the right size */
305700f9ce0SPeter Maydell     for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
306700f9ce0SPeter Maydell         if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
307c1bb86cdSEric Blake             *sector_size_p = sector_size;
308c1bb86cdSEric Blake             success = true;
309c1bb86cdSEric Blake         }
310700f9ce0SPeter Maydell     }
311c1bb86cdSEric Blake 
312c1bb86cdSEric Blake     return success ? 0 : -errno;
313c1bb86cdSEric Blake }
314c1bb86cdSEric Blake 
315c1bb86cdSEric Blake /**
316c1bb86cdSEric Blake  * Get physical block size of @fd.
317c1bb86cdSEric Blake  * On success, store it in @blk_size and return 0.
318c1bb86cdSEric Blake  * On failure, return -errno.
319c1bb86cdSEric Blake  */
320c1bb86cdSEric Blake static int probe_physical_blocksize(int fd, unsigned int *blk_size)
321c1bb86cdSEric Blake {
322c1bb86cdSEric Blake #ifdef BLKPBSZGET
323c1bb86cdSEric Blake     if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
324c1bb86cdSEric Blake         return -errno;
325c1bb86cdSEric Blake     }
326c1bb86cdSEric Blake     return 0;
327c1bb86cdSEric Blake #else
328c1bb86cdSEric Blake     return -ENOTSUP;
329c1bb86cdSEric Blake #endif
330c1bb86cdSEric Blake }
331c1bb86cdSEric Blake 
3325edc8557SKevin Wolf /*
3335edc8557SKevin Wolf  * Returns true if no alignment restrictions are necessary even for files
3345edc8557SKevin Wolf  * opened with O_DIRECT.
3355edc8557SKevin Wolf  *
3365edc8557SKevin Wolf  * raw_probe_alignment() probes the required alignment and assume that 1 means
3375edc8557SKevin Wolf  * the probing failed, so it falls back to a safe default of 4k. This can be
3385edc8557SKevin Wolf  * avoided if we know that byte alignment is okay for the file.
3395edc8557SKevin Wolf  */
3405edc8557SKevin Wolf static bool dio_byte_aligned(int fd)
3415edc8557SKevin Wolf {
3425edc8557SKevin Wolf #ifdef __linux__
3435edc8557SKevin Wolf     struct statfs buf;
3445edc8557SKevin Wolf     int ret;
3455edc8557SKevin Wolf 
3465edc8557SKevin Wolf     ret = fstatfs(fd, &buf);
3475edc8557SKevin Wolf     if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
3485edc8557SKevin Wolf         return true;
3495edc8557SKevin Wolf     }
3505edc8557SKevin Wolf #endif
3515edc8557SKevin Wolf     return false;
3525edc8557SKevin Wolf }
3535edc8557SKevin Wolf 
354c1bb86cdSEric Blake /* Check if read is allowed with given memory buffer and length.
355c1bb86cdSEric Blake  *
356c1bb86cdSEric Blake  * This function is used to check O_DIRECT memory buffer and request alignment.
357c1bb86cdSEric Blake  */
358c1bb86cdSEric Blake static bool raw_is_io_aligned(int fd, void *buf, size_t len)
359c1bb86cdSEric Blake {
360c1bb86cdSEric Blake     ssize_t ret = pread(fd, buf, len, 0);
361c1bb86cdSEric Blake 
362c1bb86cdSEric Blake     if (ret >= 0) {
363c1bb86cdSEric Blake         return true;
364c1bb86cdSEric Blake     }
365c1bb86cdSEric Blake 
366c1bb86cdSEric Blake #ifdef __linux__
367c1bb86cdSEric Blake     /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
368c1bb86cdSEric Blake      * other errors (e.g. real I/O error), which could happen on a failed
369c1bb86cdSEric Blake      * drive, since we only care about probing alignment.
370c1bb86cdSEric Blake      */
371c1bb86cdSEric Blake     if (errno != EINVAL) {
372c1bb86cdSEric Blake         return true;
373c1bb86cdSEric Blake     }
374c1bb86cdSEric Blake #endif
375c1bb86cdSEric Blake 
376c1bb86cdSEric Blake     return false;
377c1bb86cdSEric Blake }
378c1bb86cdSEric Blake 
379c1bb86cdSEric Blake static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
380c1bb86cdSEric Blake {
381c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
382c1bb86cdSEric Blake     char *buf;
383038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
384a6b257a0SNir Soffer     size_t alignments[] = {1, 512, 1024, 2048, 4096};
385c1bb86cdSEric Blake 
386c1bb86cdSEric Blake     /* For SCSI generic devices the alignment is not really used.
387c1bb86cdSEric Blake        With buffered I/O, we don't have any restrictions. */
388c1bb86cdSEric Blake     if (bdrv_is_sg(bs) || !s->needs_alignment) {
389c1bb86cdSEric Blake         bs->bl.request_alignment = 1;
390c1bb86cdSEric Blake         s->buf_align = 1;
391c1bb86cdSEric Blake         return;
392c1bb86cdSEric Blake     }
393c1bb86cdSEric Blake 
394c1bb86cdSEric Blake     bs->bl.request_alignment = 0;
395c1bb86cdSEric Blake     s->buf_align = 0;
396c1bb86cdSEric Blake     /* Let's try to use the logical blocksize for the alignment. */
397c1bb86cdSEric Blake     if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
398c1bb86cdSEric Blake         bs->bl.request_alignment = 0;
399c1bb86cdSEric Blake     }
400c1bb86cdSEric Blake #ifdef CONFIG_XFS
401c1bb86cdSEric Blake     if (s->is_xfs) {
402c1bb86cdSEric Blake         struct dioattr da;
403c1bb86cdSEric Blake         if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
404c1bb86cdSEric Blake             bs->bl.request_alignment = da.d_miniosz;
405c1bb86cdSEric Blake             /* The kernel returns wrong information for d_mem */
406c1bb86cdSEric Blake             /* s->buf_align = da.d_mem; */
407c1bb86cdSEric Blake         }
408c1bb86cdSEric Blake     }
409c1bb86cdSEric Blake #endif
410c1bb86cdSEric Blake 
411a6b257a0SNir Soffer     /*
412a6b257a0SNir Soffer      * If we could not get the sizes so far, we can only guess them. First try
413a6b257a0SNir Soffer      * to detect request alignment, since it is more likely to succeed. Then
414a6b257a0SNir Soffer      * try to detect buf_align, which cannot be detected in some cases (e.g.
415a6b257a0SNir Soffer      * Gluster). If buf_align cannot be detected, we fallback to the value of
416a6b257a0SNir Soffer      * request_alignment.
417a6b257a0SNir Soffer      */
418a6b257a0SNir Soffer 
419a6b257a0SNir Soffer     if (!bs->bl.request_alignment) {
420a6b257a0SNir Soffer         int i;
421c1bb86cdSEric Blake         size_t align;
422a6b257a0SNir Soffer         buf = qemu_memalign(max_align, max_align);
423a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
424a6b257a0SNir Soffer             align = alignments[i];
425a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf, align)) {
426a6b257a0SNir Soffer                 /* Fallback to safe value. */
427a6b257a0SNir Soffer                 bs->bl.request_alignment = (align != 1) ? align : max_align;
428c1bb86cdSEric Blake                 break;
429c1bb86cdSEric Blake             }
430c1bb86cdSEric Blake         }
431c1bb86cdSEric Blake         qemu_vfree(buf);
432c1bb86cdSEric Blake     }
433c1bb86cdSEric Blake 
434a6b257a0SNir Soffer     if (!s->buf_align) {
435a6b257a0SNir Soffer         int i;
436c1bb86cdSEric Blake         size_t align;
437a6b257a0SNir Soffer         buf = qemu_memalign(max_align, 2 * max_align);
438a6b257a0SNir Soffer         for (i = 0; i < ARRAY_SIZE(alignments); i++) {
439a6b257a0SNir Soffer             align = alignments[i];
440a6b257a0SNir Soffer             if (raw_is_io_aligned(fd, buf + align, max_align)) {
441236094c7SStefan Hajnoczi                 /* Fallback to request_alignment. */
442a6b257a0SNir Soffer                 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
443c1bb86cdSEric Blake                 break;
444c1bb86cdSEric Blake             }
445c1bb86cdSEric Blake         }
446c1bb86cdSEric Blake         qemu_vfree(buf);
447c1bb86cdSEric Blake     }
448c1bb86cdSEric Blake 
449c1bb86cdSEric Blake     if (!s->buf_align || !bs->bl.request_alignment) {
450c1bb86cdSEric Blake         error_setg(errp, "Could not find working O_DIRECT alignment");
451c1bb86cdSEric Blake         error_append_hint(errp, "Try cache.direct=off\n");
452c1bb86cdSEric Blake     }
453c1bb86cdSEric Blake }
454c1bb86cdSEric Blake 
455bca5283bSKevin Wolf static int check_hdev_writable(int fd)
45620eaf1bfSKevin Wolf {
45720eaf1bfSKevin Wolf #if defined(BLKROGET)
45820eaf1bfSKevin Wolf     /* Linux block devices can be configured "read-only" using blockdev(8).
45920eaf1bfSKevin Wolf      * This is independent of device node permissions and therefore open(2)
46020eaf1bfSKevin Wolf      * with O_RDWR succeeds.  Actual writes fail with EPERM.
46120eaf1bfSKevin Wolf      *
46220eaf1bfSKevin Wolf      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
46320eaf1bfSKevin Wolf      * check for read-only block devices so that Linux block devices behave
46420eaf1bfSKevin Wolf      * properly.
46520eaf1bfSKevin Wolf      */
46620eaf1bfSKevin Wolf     struct stat st;
46720eaf1bfSKevin Wolf     int readonly = 0;
46820eaf1bfSKevin Wolf 
469bca5283bSKevin Wolf     if (fstat(fd, &st)) {
47020eaf1bfSKevin Wolf         return -errno;
47120eaf1bfSKevin Wolf     }
47220eaf1bfSKevin Wolf 
47320eaf1bfSKevin Wolf     if (!S_ISBLK(st.st_mode)) {
47420eaf1bfSKevin Wolf         return 0;
47520eaf1bfSKevin Wolf     }
47620eaf1bfSKevin Wolf 
477bca5283bSKevin Wolf     if (ioctl(fd, BLKROGET, &readonly) < 0) {
47820eaf1bfSKevin Wolf         return -errno;
47920eaf1bfSKevin Wolf     }
48020eaf1bfSKevin Wolf 
48120eaf1bfSKevin Wolf     if (readonly) {
48220eaf1bfSKevin Wolf         return -EACCES;
48320eaf1bfSKevin Wolf     }
48420eaf1bfSKevin Wolf #endif /* defined(BLKROGET) */
48520eaf1bfSKevin Wolf     return 0;
48620eaf1bfSKevin Wolf }
48720eaf1bfSKevin Wolf 
48823dece19SKevin Wolf static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
489c1bb86cdSEric Blake {
49023dece19SKevin Wolf     bool read_write = false;
491c1bb86cdSEric Blake     assert(open_flags != NULL);
492c1bb86cdSEric Blake 
493c1bb86cdSEric Blake     *open_flags |= O_BINARY;
494c1bb86cdSEric Blake     *open_flags &= ~O_ACCMODE;
49523dece19SKevin Wolf 
49623dece19SKevin Wolf     if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
49723dece19SKevin Wolf         read_write = has_writers;
49823dece19SKevin Wolf     } else if (bdrv_flags & BDRV_O_RDWR) {
49923dece19SKevin Wolf         read_write = true;
50023dece19SKevin Wolf     }
50123dece19SKevin Wolf 
50223dece19SKevin Wolf     if (read_write) {
503c1bb86cdSEric Blake         *open_flags |= O_RDWR;
504c1bb86cdSEric Blake     } else {
505c1bb86cdSEric Blake         *open_flags |= O_RDONLY;
506c1bb86cdSEric Blake     }
507c1bb86cdSEric Blake 
508c1bb86cdSEric Blake     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
509c1bb86cdSEric Blake      * and O_DIRECT for no caching. */
510c1bb86cdSEric Blake     if ((bdrv_flags & BDRV_O_NOCACHE)) {
511c1bb86cdSEric Blake         *open_flags |= O_DIRECT;
512c1bb86cdSEric Blake     }
513c1bb86cdSEric Blake }
514c1bb86cdSEric Blake 
515c1bb86cdSEric Blake static void raw_parse_filename(const char *filename, QDict *options,
516c1bb86cdSEric Blake                                Error **errp)
517c1bb86cdSEric Blake {
51803c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "file:", options);
519c1bb86cdSEric Blake }
520c1bb86cdSEric Blake 
521c1bb86cdSEric Blake static QemuOptsList raw_runtime_opts = {
522c1bb86cdSEric Blake     .name = "raw",
523c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
524c1bb86cdSEric Blake     .desc = {
525c1bb86cdSEric Blake         {
526c1bb86cdSEric Blake             .name = "filename",
527c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
528c1bb86cdSEric Blake             .help = "File name of the image",
529c1bb86cdSEric Blake         },
530c1bb86cdSEric Blake         {
531c1bb86cdSEric Blake             .name = "aio",
532c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
533c6447510SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
534c1bb86cdSEric Blake         },
53516b48d5dSFam Zheng         {
536684960d4SStefano Garzarella             .name = "aio-max-batch",
537684960d4SStefano Garzarella             .type = QEMU_OPT_NUMBER,
538684960d4SStefano Garzarella             .help = "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
539684960d4SStefano Garzarella         },
540684960d4SStefano Garzarella         {
54116b48d5dSFam Zheng             .name = "locking",
54216b48d5dSFam Zheng             .type = QEMU_OPT_STRING,
54316b48d5dSFam Zheng             .help = "file locking mode (on/off/auto, default: auto)",
54416b48d5dSFam Zheng         },
5457c9e5276SPaolo Bonzini         {
5467c9e5276SPaolo Bonzini             .name = "pr-manager",
5477c9e5276SPaolo Bonzini             .type = QEMU_OPT_STRING,
5487c9e5276SPaolo Bonzini             .help = "id of persistent reservation manager object (default: none)",
5497c9e5276SPaolo Bonzini         },
550f357fcd8SStefan Hajnoczi #if defined(__linux__)
551f357fcd8SStefan Hajnoczi         {
552f357fcd8SStefan Hajnoczi             .name = "drop-cache",
553f357fcd8SStefan Hajnoczi             .type = QEMU_OPT_BOOL,
554f357fcd8SStefan Hajnoczi             .help = "invalidate page cache during live migration (default: on)",
555f357fcd8SStefan Hajnoczi         },
556f357fcd8SStefan Hajnoczi #endif
55731be8a2aSStefan Hajnoczi         {
55831be8a2aSStefan Hajnoczi             .name = "x-check-cache-dropped",
55931be8a2aSStefan Hajnoczi             .type = QEMU_OPT_BOOL,
56031be8a2aSStefan Hajnoczi             .help = "check that page cache was dropped on live migration (default: off)"
56131be8a2aSStefan Hajnoczi         },
562c1bb86cdSEric Blake         { /* end of list */ }
563c1bb86cdSEric Blake     },
564c1bb86cdSEric Blake };
565c1bb86cdSEric Blake 
5668a2ce0bcSAlberto Garcia static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
5678a2ce0bcSAlberto Garcia 
568c1bb86cdSEric Blake static int raw_open_common(BlockDriverState *bs, QDict *options,
569230ff739SJohn Snow                            int bdrv_flags, int open_flags,
570230ff739SJohn Snow                            bool device, Error **errp)
571c1bb86cdSEric Blake {
572c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
573c1bb86cdSEric Blake     QemuOpts *opts;
574c1bb86cdSEric Blake     Error *local_err = NULL;
575c1bb86cdSEric Blake     const char *filename = NULL;
5767c9e5276SPaolo Bonzini     const char *str;
577c1bb86cdSEric Blake     BlockdevAioOptions aio, aio_default;
578c1bb86cdSEric Blake     int fd, ret;
579c1bb86cdSEric Blake     struct stat st;
580244a5668SFam Zheng     OnOffAuto locking;
581c1bb86cdSEric Blake 
582c1bb86cdSEric Blake     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
583af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
584c1bb86cdSEric Blake         ret = -EINVAL;
585c1bb86cdSEric Blake         goto fail;
586c1bb86cdSEric Blake     }
587c1bb86cdSEric Blake 
588c1bb86cdSEric Blake     filename = qemu_opt_get(opts, "filename");
589c1bb86cdSEric Blake 
590db0754dfSFam Zheng     ret = raw_normalize_devicepath(&filename, errp);
591c1bb86cdSEric Blake     if (ret != 0) {
592c1bb86cdSEric Blake         goto fail;
593c1bb86cdSEric Blake     }
594c1bb86cdSEric Blake 
595c6447510SAarushi Mehta     if (bdrv_flags & BDRV_O_NATIVE_AIO) {
596c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
597c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
598c6447510SAarushi Mehta     } else if (bdrv_flags & BDRV_O_IO_URING) {
599c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
600c6447510SAarushi Mehta #endif
601c6447510SAarushi Mehta     } else {
602c6447510SAarushi Mehta         aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
603c6447510SAarushi Mehta     }
604c6447510SAarushi Mehta 
605f7abe0ecSMarc-André Lureau     aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
606f7abe0ecSMarc-André Lureau                           qemu_opt_get(opts, "aio"),
60706c60b6cSMarkus Armbruster                           aio_default, &local_err);
608c1bb86cdSEric Blake     if (local_err) {
609c1bb86cdSEric Blake         error_propagate(errp, local_err);
610c1bb86cdSEric Blake         ret = -EINVAL;
611c1bb86cdSEric Blake         goto fail;
612c1bb86cdSEric Blake     }
613c6447510SAarushi Mehta 
614c1bb86cdSEric Blake     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
615c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
616c6447510SAarushi Mehta     s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
617c6447510SAarushi Mehta #endif
618c1bb86cdSEric Blake 
619684960d4SStefano Garzarella     s->aio_max_batch = qemu_opt_get_number(opts, "aio-max-batch", 0);
620684960d4SStefano Garzarella 
621f7abe0ecSMarc-André Lureau     locking = qapi_enum_parse(&OnOffAuto_lookup,
622f7abe0ecSMarc-André Lureau                               qemu_opt_get(opts, "locking"),
62306c60b6cSMarkus Armbruster                               ON_OFF_AUTO_AUTO, &local_err);
624244a5668SFam Zheng     if (local_err) {
625244a5668SFam Zheng         error_propagate(errp, local_err);
626244a5668SFam Zheng         ret = -EINVAL;
627244a5668SFam Zheng         goto fail;
628244a5668SFam Zheng     }
629244a5668SFam Zheng     switch (locking) {
630244a5668SFam Zheng     case ON_OFF_AUTO_ON:
631244a5668SFam Zheng         s->use_lock = true;
6322b218f5dSFam Zheng         if (!qemu_has_ofd_lock()) {
633db0754dfSFam Zheng             warn_report("File lock requested but OFD locking syscall is "
634db0754dfSFam Zheng                         "unavailable, falling back to POSIX file locks");
635db0754dfSFam Zheng             error_printf("Due to the implementation, locks can be lost "
6362b218f5dSFam Zheng                          "unexpectedly.\n");
6372b218f5dSFam Zheng         }
638244a5668SFam Zheng         break;
639244a5668SFam Zheng     case ON_OFF_AUTO_OFF:
640244a5668SFam Zheng         s->use_lock = false;
641244a5668SFam Zheng         break;
642244a5668SFam Zheng     case ON_OFF_AUTO_AUTO:
6432b218f5dSFam Zheng         s->use_lock = qemu_has_ofd_lock();
644244a5668SFam Zheng         break;
645244a5668SFam Zheng     default:
646244a5668SFam Zheng         abort();
647244a5668SFam Zheng     }
648244a5668SFam Zheng 
6497c9e5276SPaolo Bonzini     str = qemu_opt_get(opts, "pr-manager");
6507c9e5276SPaolo Bonzini     if (str) {
6517c9e5276SPaolo Bonzini         s->pr_mgr = pr_manager_lookup(str, &local_err);
6527c9e5276SPaolo Bonzini         if (local_err) {
6537c9e5276SPaolo Bonzini             error_propagate(errp, local_err);
6547c9e5276SPaolo Bonzini             ret = -EINVAL;
6557c9e5276SPaolo Bonzini             goto fail;
6567c9e5276SPaolo Bonzini         }
6577c9e5276SPaolo Bonzini     }
6587c9e5276SPaolo Bonzini 
659f357fcd8SStefan Hajnoczi     s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
66031be8a2aSStefan Hajnoczi     s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
66131be8a2aSStefan Hajnoczi                                                false);
66231be8a2aSStefan Hajnoczi 
663c1bb86cdSEric Blake     s->open_flags = open_flags;
66423dece19SKevin Wolf     raw_parse_flags(bdrv_flags, &s->open_flags, false);
665c1bb86cdSEric Blake 
666c1bb86cdSEric Blake     s->fd = -1;
667b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, s->open_flags, errp);
66864107dc0SKevin Wolf     ret = fd < 0 ? -errno : 0;
66964107dc0SKevin Wolf 
67064107dc0SKevin Wolf     if (ret < 0) {
671c1bb86cdSEric Blake         if (ret == -EROFS) {
672c1bb86cdSEric Blake             ret = -EACCES;
673c1bb86cdSEric Blake         }
674c1bb86cdSEric Blake         goto fail;
675c1bb86cdSEric Blake     }
676c1bb86cdSEric Blake     s->fd = fd;
677c1bb86cdSEric Blake 
678bca5283bSKevin Wolf     /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
679bca5283bSKevin Wolf     if (s->open_flags & O_RDWR) {
680bca5283bSKevin Wolf         ret = check_hdev_writable(s->fd);
681bca5283bSKevin Wolf         if (ret < 0) {
682bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
683bca5283bSKevin Wolf             goto fail;
684bca5283bSKevin Wolf         }
685bca5283bSKevin Wolf     }
686bca5283bSKevin Wolf 
687244a5668SFam Zheng     s->perm = 0;
688244a5668SFam Zheng     s->shared_perm = BLK_PERM_ALL;
689244a5668SFam Zheng 
690c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
691c1bb86cdSEric Blake      /* Currently Linux does AIO only for files opened with O_DIRECT */
692ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
693ed6e2161SNishanth Aravamudan         if (!(s->open_flags & O_DIRECT)) {
694c1bb86cdSEric Blake             error_setg(errp, "aio=native was specified, but it requires "
695c1bb86cdSEric Blake                              "cache.direct=on, which was not specified.");
696c1bb86cdSEric Blake             ret = -EINVAL;
697c1bb86cdSEric Blake             goto fail;
698c1bb86cdSEric Blake         }
699ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
700ed6e2161SNishanth Aravamudan             error_prepend(errp, "Unable to use native AIO: ");
701ed6e2161SNishanth Aravamudan             goto fail;
702ed6e2161SNishanth Aravamudan         }
703ed6e2161SNishanth Aravamudan     }
704c1bb86cdSEric Blake #else
705c1bb86cdSEric Blake     if (s->use_linux_aio) {
706c1bb86cdSEric Blake         error_setg(errp, "aio=native was specified, but is not supported "
707c1bb86cdSEric Blake                          "in this build.");
708c1bb86cdSEric Blake         ret = -EINVAL;
709c1bb86cdSEric Blake         goto fail;
710c1bb86cdSEric Blake     }
711c1bb86cdSEric Blake #endif /* !defined(CONFIG_LINUX_AIO) */
712c1bb86cdSEric Blake 
713c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
714c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
715c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
716c6447510SAarushi Mehta             error_prepend(errp, "Unable to use io_uring: ");
717c6447510SAarushi Mehta             goto fail;
718c6447510SAarushi Mehta         }
719c6447510SAarushi Mehta     }
720c6447510SAarushi Mehta #else
721c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
722c6447510SAarushi Mehta         error_setg(errp, "aio=io_uring was specified, but is not supported "
723c6447510SAarushi Mehta                          "in this build.");
724c6447510SAarushi Mehta         ret = -EINVAL;
725c6447510SAarushi Mehta         goto fail;
726c6447510SAarushi Mehta     }
727c6447510SAarushi Mehta #endif /* !defined(CONFIG_LINUX_IO_URING) */
728c6447510SAarushi Mehta 
729c1bb86cdSEric Blake     s->has_discard = true;
730c1bb86cdSEric Blake     s->has_write_zeroes = true;
7315edc8557SKevin Wolf     if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
732c1bb86cdSEric Blake         s->needs_alignment = true;
733c1bb86cdSEric Blake     }
734c1bb86cdSEric Blake 
735c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
736c1bb86cdSEric Blake         ret = -errno;
737c1bb86cdSEric Blake         error_setg_errno(errp, errno, "Could not stat file");
738c1bb86cdSEric Blake         goto fail;
739c1bb86cdSEric Blake     }
740230ff739SJohn Snow 
741230ff739SJohn Snow     if (!device) {
7428d17adf3SDaniel P. Berrangé         if (!S_ISREG(st.st_mode)) {
7438d17adf3SDaniel P. Berrangé             error_setg(errp, "'%s' driver requires '%s' to be a regular file",
7448d17adf3SDaniel P. Berrangé                        bs->drv->format_name, bs->filename);
745230ff739SJohn Snow             ret = -EINVAL;
746230ff739SJohn Snow             goto fail;
747230ff739SJohn Snow         } else {
748c1bb86cdSEric Blake             s->discard_zeroes = true;
749c1bb86cdSEric Blake             s->has_fallocate = true;
750c1bb86cdSEric Blake         }
751230ff739SJohn Snow     } else {
752230ff739SJohn Snow         if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
7538d17adf3SDaniel P. Berrangé             error_setg(errp, "'%s' driver requires '%s' to be either "
7548d17adf3SDaniel P. Berrangé                        "a character or block device",
7558d17adf3SDaniel P. Berrangé                        bs->drv->format_name, bs->filename);
756230ff739SJohn Snow             ret = -EINVAL;
757230ff739SJohn Snow             goto fail;
758230ff739SJohn Snow         }
759230ff739SJohn Snow     }
760230ff739SJohn Snow 
761c1bb86cdSEric Blake     if (S_ISBLK(st.st_mode)) {
762c1bb86cdSEric Blake #ifdef BLKDISCARDZEROES
763c1bb86cdSEric Blake         unsigned int arg;
764c1bb86cdSEric Blake         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
765c1bb86cdSEric Blake             s->discard_zeroes = true;
766c1bb86cdSEric Blake         }
767c1bb86cdSEric Blake #endif
768c1bb86cdSEric Blake #ifdef __linux__
769c1bb86cdSEric Blake         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
770c1bb86cdSEric Blake          * not rely on the contents of discarded blocks unless using O_DIRECT.
771c1bb86cdSEric Blake          * Same for BLKZEROOUT.
772c1bb86cdSEric Blake          */
773c1bb86cdSEric Blake         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
774c1bb86cdSEric Blake             s->discard_zeroes = false;
775c1bb86cdSEric Blake             s->has_write_zeroes = false;
776c1bb86cdSEric Blake         }
777c1bb86cdSEric Blake #endif
778c1bb86cdSEric Blake     }
779c1bb86cdSEric Blake #ifdef __FreeBSD__
780c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode)) {
781c1bb86cdSEric Blake         /*
782c1bb86cdSEric Blake          * The file is a char device (disk), which on FreeBSD isn't behind
783c1bb86cdSEric Blake          * a pager, so force all requests to be aligned. This is needed
784c1bb86cdSEric Blake          * so QEMU makes sure all IO operations on the device are aligned
785c1bb86cdSEric Blake          * to sector size, or else FreeBSD will reject them with EINVAL.
786c1bb86cdSEric Blake          */
787c1bb86cdSEric Blake         s->needs_alignment = true;
788c1bb86cdSEric Blake     }
789c1bb86cdSEric Blake #endif
790c1bb86cdSEric Blake 
791c1bb86cdSEric Blake #ifdef CONFIG_XFS
792c1bb86cdSEric Blake     if (platform_test_xfs_fd(s->fd)) {
793c1bb86cdSEric Blake         s->is_xfs = true;
794c1bb86cdSEric Blake     }
795c1bb86cdSEric Blake #endif
796c1bb86cdSEric Blake 
797738301e1SKevin Wolf     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
7982f0c6e7aSKevin Wolf     if (S_ISREG(st.st_mode)) {
7992f0c6e7aSKevin Wolf         /* When extending regular files, we get zeros from the OS */
8002f0c6e7aSKevin Wolf         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
8012f0c6e7aSKevin Wolf     }
802c1bb86cdSEric Blake     ret = 0;
803c1bb86cdSEric Blake fail:
804a8c5cf27SKevin Wolf     if (ret < 0 && s->fd != -1) {
805a8c5cf27SKevin Wolf         qemu_close(s->fd);
806a8c5cf27SKevin Wolf     }
807c1bb86cdSEric Blake     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
808c1bb86cdSEric Blake         unlink(filename);
809c1bb86cdSEric Blake     }
810c1bb86cdSEric Blake     qemu_opts_del(opts);
811c1bb86cdSEric Blake     return ret;
812c1bb86cdSEric Blake }
813c1bb86cdSEric Blake 
814c1bb86cdSEric Blake static int raw_open(BlockDriverState *bs, QDict *options, int flags,
815c1bb86cdSEric Blake                     Error **errp)
816c1bb86cdSEric Blake {
817c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
818c1bb86cdSEric Blake 
819c1bb86cdSEric Blake     s->type = FTYPE_FILE;
820230ff739SJohn Snow     return raw_open_common(bs, options, flags, 0, false, errp);
821c1bb86cdSEric Blake }
822c1bb86cdSEric Blake 
823244a5668SFam Zheng typedef enum {
824244a5668SFam Zheng     RAW_PL_PREPARE,
825244a5668SFam Zheng     RAW_PL_COMMIT,
826244a5668SFam Zheng     RAW_PL_ABORT,
827244a5668SFam Zheng } RawPermLockOp;
828244a5668SFam Zheng 
829244a5668SFam Zheng #define PERM_FOREACH(i) \
830244a5668SFam Zheng     for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
831244a5668SFam Zheng 
832244a5668SFam Zheng /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
833244a5668SFam Zheng  * file; if @unlock == true, also unlock the unneeded bytes.
834244a5668SFam Zheng  * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
835244a5668SFam Zheng  */
8362996ffadSFam Zheng static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
837244a5668SFam Zheng                                 uint64_t perm_lock_bits,
838244a5668SFam Zheng                                 uint64_t shared_perm_lock_bits,
839244a5668SFam Zheng                                 bool unlock, Error **errp)
840244a5668SFam Zheng {
841244a5668SFam Zheng     int ret;
842244a5668SFam Zheng     int i;
8432996ffadSFam Zheng     uint64_t locked_perm, locked_shared_perm;
8442996ffadSFam Zheng 
8452996ffadSFam Zheng     if (s) {
8462996ffadSFam Zheng         locked_perm = s->locked_perm;
8472996ffadSFam Zheng         locked_shared_perm = s->locked_shared_perm;
8482996ffadSFam Zheng     } else {
8492996ffadSFam Zheng         /*
8502996ffadSFam Zheng          * We don't have the previous bits, just lock/unlock for each of the
8512996ffadSFam Zheng          * requested bits.
8522996ffadSFam Zheng          */
8532996ffadSFam Zheng         if (unlock) {
8542996ffadSFam Zheng             locked_perm = BLK_PERM_ALL;
8552996ffadSFam Zheng             locked_shared_perm = BLK_PERM_ALL;
8562996ffadSFam Zheng         } else {
8572996ffadSFam Zheng             locked_perm = 0;
8582996ffadSFam Zheng             locked_shared_perm = 0;
8592996ffadSFam Zheng         }
8602996ffadSFam Zheng     }
861244a5668SFam Zheng 
862244a5668SFam Zheng     PERM_FOREACH(i) {
863244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
8642996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8652996ffadSFam Zheng         if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
866d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
867244a5668SFam Zheng             if (ret) {
868797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
869797e3e38SDavid Edmondson                                           off);
870244a5668SFam Zheng                 return ret;
8712996ffadSFam Zheng             } else if (s) {
8722996ffadSFam Zheng                 s->locked_perm |= bit;
873244a5668SFam Zheng             }
8742996ffadSFam Zheng         } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
875d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
876244a5668SFam Zheng             if (ret) {
877797e3e38SDavid Edmondson                 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
878244a5668SFam Zheng                 return ret;
8792996ffadSFam Zheng             } else if (s) {
8802996ffadSFam Zheng                 s->locked_perm &= ~bit;
881244a5668SFam Zheng             }
882244a5668SFam Zheng         }
883244a5668SFam Zheng     }
884244a5668SFam Zheng     PERM_FOREACH(i) {
885244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
8862996ffadSFam Zheng         uint64_t bit = (1ULL << i);
8872996ffadSFam Zheng         if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
888d0a96155SMax Reitz             ret = qemu_lock_fd(fd, off, 1, false);
889244a5668SFam Zheng             if (ret) {
890797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
891797e3e38SDavid Edmondson                                           off);
892244a5668SFam Zheng                 return ret;
8932996ffadSFam Zheng             } else if (s) {
8942996ffadSFam Zheng                 s->locked_shared_perm |= bit;
895244a5668SFam Zheng             }
8962996ffadSFam Zheng         } else if (unlock && (locked_shared_perm & bit) &&
8972996ffadSFam Zheng                    !(shared_perm_lock_bits & bit)) {
898d0a96155SMax Reitz             ret = qemu_unlock_fd(fd, off, 1);
899244a5668SFam Zheng             if (ret) {
900797e3e38SDavid Edmondson                 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
901244a5668SFam Zheng                 return ret;
9022996ffadSFam Zheng             } else if (s) {
9032996ffadSFam Zheng                 s->locked_shared_perm &= ~bit;
904244a5668SFam Zheng             }
905244a5668SFam Zheng         }
906244a5668SFam Zheng     }
907244a5668SFam Zheng     return 0;
908244a5668SFam Zheng }
909244a5668SFam Zheng 
910244a5668SFam Zheng /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
911d0a96155SMax Reitz static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
912244a5668SFam Zheng                                 Error **errp)
913244a5668SFam Zheng {
914244a5668SFam Zheng     int ret;
915244a5668SFam Zheng     int i;
916244a5668SFam Zheng 
917244a5668SFam Zheng     PERM_FOREACH(i) {
918244a5668SFam Zheng         int off = RAW_LOCK_SHARED_BASE + i;
919244a5668SFam Zheng         uint64_t p = 1ULL << i;
920244a5668SFam Zheng         if (perm & p) {
921d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
922244a5668SFam Zheng             if (ret) {
923244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
924797e3e38SDavid Edmondson 
925797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret,
926244a5668SFam Zheng                                           "Failed to get \"%s\" lock",
927244a5668SFam Zheng                                           perm_name);
928244a5668SFam Zheng                 g_free(perm_name);
929244a5668SFam Zheng                 return ret;
930244a5668SFam Zheng             }
931244a5668SFam Zheng         }
932244a5668SFam Zheng     }
933244a5668SFam Zheng     PERM_FOREACH(i) {
934244a5668SFam Zheng         int off = RAW_LOCK_PERM_BASE + i;
935244a5668SFam Zheng         uint64_t p = 1ULL << i;
936244a5668SFam Zheng         if (!(shared_perm & p)) {
937d0a96155SMax Reitz             ret = qemu_lock_fd_test(fd, off, 1, true);
938244a5668SFam Zheng             if (ret) {
939244a5668SFam Zheng                 char *perm_name = bdrv_perm_names(p);
940797e3e38SDavid Edmondson 
941797e3e38SDavid Edmondson                 raw_lock_error_setg_errno(errp, -ret,
942244a5668SFam Zheng                                           "Failed to get shared \"%s\" lock",
943244a5668SFam Zheng                                           perm_name);
944244a5668SFam Zheng                 g_free(perm_name);
945244a5668SFam Zheng                 return ret;
946244a5668SFam Zheng             }
947244a5668SFam Zheng         }
948244a5668SFam Zheng     }
949244a5668SFam Zheng     return 0;
950244a5668SFam Zheng }
951244a5668SFam Zheng 
952244a5668SFam Zheng static int raw_handle_perm_lock(BlockDriverState *bs,
953244a5668SFam Zheng                                 RawPermLockOp op,
954244a5668SFam Zheng                                 uint64_t new_perm, uint64_t new_shared,
955244a5668SFam Zheng                                 Error **errp)
956244a5668SFam Zheng {
957244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
958244a5668SFam Zheng     int ret = 0;
959244a5668SFam Zheng     Error *local_err = NULL;
960244a5668SFam Zheng 
961244a5668SFam Zheng     if (!s->use_lock) {
962244a5668SFam Zheng         return 0;
963244a5668SFam Zheng     }
964244a5668SFam Zheng 
965244a5668SFam Zheng     if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
966244a5668SFam Zheng         return 0;
967244a5668SFam Zheng     }
968244a5668SFam Zheng 
969244a5668SFam Zheng     switch (op) {
970244a5668SFam Zheng     case RAW_PL_PREPARE:
971696aaaedSVladimir Sementsov-Ogievskiy         if ((s->perm | new_perm) == s->perm &&
972696aaaedSVladimir Sementsov-Ogievskiy             (s->shared_perm & new_shared) == s->shared_perm)
973696aaaedSVladimir Sementsov-Ogievskiy         {
974696aaaedSVladimir Sementsov-Ogievskiy             /*
975696aaaedSVladimir Sementsov-Ogievskiy              * We are going to unlock bytes, it should not fail. If it fail due
976696aaaedSVladimir Sementsov-Ogievskiy              * to some fs-dependent permission-unrelated reasons (which occurs
977696aaaedSVladimir Sementsov-Ogievskiy              * sometimes on NFS and leads to abort in bdrv_replace_child) we
978696aaaedSVladimir Sementsov-Ogievskiy              * can't prevent such errors by any check here. And we ignore them
979696aaaedSVladimir Sementsov-Ogievskiy              * anyway in ABORT and COMMIT.
980696aaaedSVladimir Sementsov-Ogievskiy              */
981696aaaedSVladimir Sementsov-Ogievskiy             return 0;
982696aaaedSVladimir Sementsov-Ogievskiy         }
983f2e3af29SFam Zheng         ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
984244a5668SFam Zheng                                    ~s->shared_perm | ~new_shared,
985244a5668SFam Zheng                                    false, errp);
986244a5668SFam Zheng         if (!ret) {
987f2e3af29SFam Zheng             ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
988244a5668SFam Zheng             if (!ret) {
989244a5668SFam Zheng                 return 0;
990244a5668SFam Zheng             }
991b857431dSFam Zheng             error_append_hint(errp,
992b857431dSFam Zheng                               "Is another process using the image [%s]?\n",
993b857431dSFam Zheng                               bs->filename);
994244a5668SFam Zheng         }
995244a5668SFam Zheng         /* fall through to unlock bytes. */
996244a5668SFam Zheng     case RAW_PL_ABORT:
997f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
998d0a96155SMax Reitz                              true, &local_err);
999244a5668SFam Zheng         if (local_err) {
1000244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
1001244a5668SFam Zheng              * fail. Something weird happened, report it.
1002244a5668SFam Zheng              */
1003db0754dfSFam Zheng             warn_report_err(local_err);
1004244a5668SFam Zheng         }
1005244a5668SFam Zheng         break;
1006244a5668SFam Zheng     case RAW_PL_COMMIT:
1007f2e3af29SFam Zheng         raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
1008d0a96155SMax Reitz                              true, &local_err);
1009244a5668SFam Zheng         if (local_err) {
1010244a5668SFam Zheng             /* Theoretically the above call only unlocks bytes and it cannot
1011244a5668SFam Zheng              * fail. Something weird happened, report it.
1012244a5668SFam Zheng              */
1013db0754dfSFam Zheng             warn_report_err(local_err);
1014244a5668SFam Zheng         }
1015244a5668SFam Zheng         break;
1016244a5668SFam Zheng     }
1017244a5668SFam Zheng     return ret;
1018244a5668SFam Zheng }
1019244a5668SFam Zheng 
10205cec2870SKevin Wolf static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
102123dece19SKevin Wolf                                  int *open_flags, uint64_t perm, bool force_dup,
10226ceabe6fSKevin Wolf                                  Error **errp)
10235cec2870SKevin Wolf {
10245cec2870SKevin Wolf     BDRVRawState *s = bs->opaque;
10255cec2870SKevin Wolf     int fd = -1;
10265cec2870SKevin Wolf     int ret;
102723dece19SKevin Wolf     bool has_writers = perm &
102823dece19SKevin Wolf         (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
10295cec2870SKevin Wolf     int fcntl_flags = O_APPEND | O_NONBLOCK;
10305cec2870SKevin Wolf #ifdef O_NOATIME
10315cec2870SKevin Wolf     fcntl_flags |= O_NOATIME;
10325cec2870SKevin Wolf #endif
10335cec2870SKevin Wolf 
10345cec2870SKevin Wolf     *open_flags = 0;
10355cec2870SKevin Wolf     if (s->type == FTYPE_CD) {
10365cec2870SKevin Wolf         *open_flags |= O_NONBLOCK;
10375cec2870SKevin Wolf     }
10385cec2870SKevin Wolf 
103923dece19SKevin Wolf     raw_parse_flags(flags, open_flags, has_writers);
10405cec2870SKevin Wolf 
10415cec2870SKevin Wolf #ifdef O_ASYNC
10425cec2870SKevin Wolf     /* Not all operating systems have O_ASYNC, and those that don't
10435cec2870SKevin Wolf      * will not let us track the state into rs->open_flags (typically
10445cec2870SKevin Wolf      * you achieve the same effect with an ioctl, for example I_SETSIG
10455cec2870SKevin Wolf      * on Solaris). But we do not use O_ASYNC, so that's fine.
10465cec2870SKevin Wolf      */
10475cec2870SKevin Wolf     assert((s->open_flags & O_ASYNC) == 0);
10485cec2870SKevin Wolf #endif
10495cec2870SKevin Wolf 
10506ceabe6fSKevin Wolf     if (!force_dup && *open_flags == s->open_flags) {
10516ceabe6fSKevin Wolf         /* We're lucky, the existing fd is fine */
10526ceabe6fSKevin Wolf         return s->fd;
10536ceabe6fSKevin Wolf     }
10546ceabe6fSKevin Wolf 
10555cec2870SKevin Wolf     if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
10565cec2870SKevin Wolf         /* dup the original fd */
10575cec2870SKevin Wolf         fd = qemu_dup(s->fd);
10585cec2870SKevin Wolf         if (fd >= 0) {
10595cec2870SKevin Wolf             ret = fcntl_setfl(fd, *open_flags);
10605cec2870SKevin Wolf             if (ret) {
10615cec2870SKevin Wolf                 qemu_close(fd);
10625cec2870SKevin Wolf                 fd = -1;
10635cec2870SKevin Wolf             }
10645cec2870SKevin Wolf         }
10655cec2870SKevin Wolf     }
10665cec2870SKevin Wolf 
1067b18a24a9SDaniel P. Berrangé     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
10685cec2870SKevin Wolf     if (fd == -1) {
10695cec2870SKevin Wolf         const char *normalized_filename = bs->filename;
10705cec2870SKevin Wolf         ret = raw_normalize_devicepath(&normalized_filename, errp);
10715cec2870SKevin Wolf         if (ret >= 0) {
1072b18a24a9SDaniel P. Berrangé             fd = qemu_open(normalized_filename, *open_flags, errp);
10735cec2870SKevin Wolf             if (fd == -1) {
10745cec2870SKevin Wolf                 return -1;
10755cec2870SKevin Wolf             }
10765cec2870SKevin Wolf         }
10775cec2870SKevin Wolf     }
10785cec2870SKevin Wolf 
1079bca5283bSKevin Wolf     if (fd != -1 && (*open_flags & O_RDWR)) {
1080bca5283bSKevin Wolf         ret = check_hdev_writable(fd);
1081bca5283bSKevin Wolf         if (ret < 0) {
1082bca5283bSKevin Wolf             qemu_close(fd);
1083bca5283bSKevin Wolf             error_setg_errno(errp, -ret, "The device is not writable");
1084bca5283bSKevin Wolf             return -1;
1085bca5283bSKevin Wolf         }
1086bca5283bSKevin Wolf     }
1087bca5283bSKevin Wolf 
10885cec2870SKevin Wolf     return fd;
10895cec2870SKevin Wolf }
10905cec2870SKevin Wolf 
1091c1bb86cdSEric Blake static int raw_reopen_prepare(BDRVReopenState *state,
1092c1bb86cdSEric Blake                               BlockReopenQueue *queue, Error **errp)
1093c1bb86cdSEric Blake {
1094c1bb86cdSEric Blake     BDRVRawState *s;
1095c1bb86cdSEric Blake     BDRVRawReopenState *rs;
109631be8a2aSStefan Hajnoczi     QemuOpts *opts;
1097a6aeca0cSKevin Wolf     int ret;
1098c1bb86cdSEric Blake 
1099c1bb86cdSEric Blake     assert(state != NULL);
1100c1bb86cdSEric Blake     assert(state->bs != NULL);
1101c1bb86cdSEric Blake 
1102c1bb86cdSEric Blake     s = state->bs->opaque;
1103c1bb86cdSEric Blake 
1104c1bb86cdSEric Blake     state->opaque = g_new0(BDRVRawReopenState, 1);
1105c1bb86cdSEric Blake     rs = state->opaque;
110631be8a2aSStefan Hajnoczi 
110731be8a2aSStefan Hajnoczi     /* Handle options changes */
110831be8a2aSStefan Hajnoczi     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1109af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
111031be8a2aSStefan Hajnoczi         ret = -EINVAL;
111131be8a2aSStefan Hajnoczi         goto out;
111231be8a2aSStefan Hajnoczi     }
111331be8a2aSStefan Hajnoczi 
1114f357fcd8SStefan Hajnoczi     rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
11158d324575SAlberto Garcia     rs->check_cache_dropped =
11168d324575SAlberto Garcia         qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
11178d324575SAlberto Garcia 
11188d324575SAlberto Garcia     /* This driver's reopen function doesn't currently allow changing
11198d324575SAlberto Garcia      * other options, so let's put them back in the original QDict and
11208d324575SAlberto Garcia      * bdrv_reopen_prepare() will detect changes and complain. */
11218d324575SAlberto Garcia     qemu_opts_to_qdict(opts, state->options);
1122c1bb86cdSEric Blake 
112372373e40SVladimir Sementsov-Ogievskiy     /*
112472373e40SVladimir Sementsov-Ogievskiy      * As part of reopen prepare we also want to create new fd by
112572373e40SVladimir Sementsov-Ogievskiy      * raw_reconfigure_getfd(). But it wants updated "perm", when in
112672373e40SVladimir Sementsov-Ogievskiy      * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
112772373e40SVladimir Sementsov-Ogievskiy      * permission update. Happily, permission update is always a part (a seprate
112872373e40SVladimir Sementsov-Ogievskiy      * stage) of bdrv_reopen_multiple() so we can rely on this fact and
112972373e40SVladimir Sementsov-Ogievskiy      * reconfigure fd in raw_check_perm().
113072373e40SVladimir Sementsov-Ogievskiy      */
1131c1bb86cdSEric Blake 
1132e0c9cf3aSKevin Wolf     s->reopen_state = state;
1133a6aeca0cSKevin Wolf     ret = 0;
113472373e40SVladimir Sementsov-Ogievskiy 
113531be8a2aSStefan Hajnoczi out:
113631be8a2aSStefan Hajnoczi     qemu_opts_del(opts);
1137c1bb86cdSEric Blake     return ret;
1138c1bb86cdSEric Blake }
1139c1bb86cdSEric Blake 
1140c1bb86cdSEric Blake static void raw_reopen_commit(BDRVReopenState *state)
1141c1bb86cdSEric Blake {
1142c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1143c1bb86cdSEric Blake     BDRVRawState *s = state->bs->opaque;
1144c1bb86cdSEric Blake 
1145f357fcd8SStefan Hajnoczi     s->drop_cache = rs->drop_cache;
114631be8a2aSStefan Hajnoczi     s->check_cache_dropped = rs->check_cache_dropped;
1147c1bb86cdSEric Blake     s->open_flags = rs->open_flags;
1148c1bb86cdSEric Blake     g_free(state->opaque);
1149c1bb86cdSEric Blake     state->opaque = NULL;
1150e0c9cf3aSKevin Wolf 
1151e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1152e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1153c1bb86cdSEric Blake }
1154c1bb86cdSEric Blake 
1155c1bb86cdSEric Blake 
1156c1bb86cdSEric Blake static void raw_reopen_abort(BDRVReopenState *state)
1157c1bb86cdSEric Blake {
1158c1bb86cdSEric Blake     BDRVRawReopenState *rs = state->opaque;
1159e0c9cf3aSKevin Wolf     BDRVRawState *s = state->bs->opaque;
1160c1bb86cdSEric Blake 
1161c1bb86cdSEric Blake      /* nothing to do if NULL, we didn't get far enough */
1162c1bb86cdSEric Blake     if (rs == NULL) {
1163c1bb86cdSEric Blake         return;
1164c1bb86cdSEric Blake     }
1165c1bb86cdSEric Blake 
1166c1bb86cdSEric Blake     g_free(state->opaque);
1167c1bb86cdSEric Blake     state->opaque = NULL;
1168e0c9cf3aSKevin Wolf 
1169e0c9cf3aSKevin Wolf     assert(s->reopen_state == state);
1170e0c9cf3aSKevin Wolf     s->reopen_state = NULL;
1171c1bb86cdSEric Blake }
1172c1bb86cdSEric Blake 
117318473467SPaolo Bonzini static int hdev_get_max_hw_transfer(int fd, struct stat *st)
1174c1bb86cdSEric Blake {
1175c1bb86cdSEric Blake #ifdef BLKSECTGET
117618473467SPaolo Bonzini     if (S_ISBLK(st->st_mode)) {
117718473467SPaolo Bonzini         unsigned short max_sectors = 0;
117818473467SPaolo Bonzini         if (ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
117918473467SPaolo Bonzini             return max_sectors * 512;
118018473467SPaolo Bonzini         }
118118473467SPaolo Bonzini     } else {
118248265250SEric Farman         int max_bytes = 0;
1183867eccfeSMaxim Levitsky         if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
118448265250SEric Farman             return max_bytes;
1185c1bb86cdSEric Blake         }
118618473467SPaolo Bonzini     }
118718473467SPaolo Bonzini     return -errno;
1188c1bb86cdSEric Blake #else
1189c1bb86cdSEric Blake     return -ENOSYS;
1190c1bb86cdSEric Blake #endif
1191c1bb86cdSEric Blake }
1192c1bb86cdSEric Blake 
119318473467SPaolo Bonzini static int hdev_get_max_segments(int fd, struct stat *st)
11949103f1ceSFam Zheng {
11959103f1ceSFam Zheng #ifdef CONFIG_LINUX
11969103f1ceSFam Zheng     char buf[32];
11979103f1ceSFam Zheng     const char *end;
1198867eccfeSMaxim Levitsky     char *sysfspath = NULL;
11999103f1ceSFam Zheng     int ret;
1200867eccfeSMaxim Levitsky     int sysfd = -1;
12019103f1ceSFam Zheng     long max_segments;
1202867eccfeSMaxim Levitsky 
120318473467SPaolo Bonzini     if (S_ISCHR(st->st_mode)) {
12048ad5ab61SPaolo Bonzini         if (ioctl(fd, SG_GET_SG_TABLESIZE, &ret) == 0) {
12058ad5ab61SPaolo Bonzini             return ret;
12068ad5ab61SPaolo Bonzini         }
12078ad5ab61SPaolo Bonzini         return -ENOTSUP;
12088ad5ab61SPaolo Bonzini     }
12098ad5ab61SPaolo Bonzini 
121018473467SPaolo Bonzini     if (!S_ISBLK(st->st_mode)) {
12118ad5ab61SPaolo Bonzini         return -ENOTSUP;
12128ad5ab61SPaolo Bonzini     }
12138ad5ab61SPaolo Bonzini 
12149103f1ceSFam Zheng     sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
121518473467SPaolo Bonzini                                 major(st->st_rdev), minor(st->st_rdev));
1216867eccfeSMaxim Levitsky     sysfd = open(sysfspath, O_RDONLY);
1217867eccfeSMaxim Levitsky     if (sysfd == -1) {
12189103f1ceSFam Zheng         ret = -errno;
12199103f1ceSFam Zheng         goto out;
12209103f1ceSFam Zheng     }
12219103f1ceSFam Zheng     do {
1222867eccfeSMaxim Levitsky         ret = read(sysfd, buf, sizeof(buf) - 1);
12239103f1ceSFam Zheng     } while (ret == -1 && errno == EINTR);
12249103f1ceSFam Zheng     if (ret < 0) {
12259103f1ceSFam Zheng         ret = -errno;
12269103f1ceSFam Zheng         goto out;
12279103f1ceSFam Zheng     } else if (ret == 0) {
12289103f1ceSFam Zheng         ret = -EIO;
12299103f1ceSFam Zheng         goto out;
12309103f1ceSFam Zheng     }
12319103f1ceSFam Zheng     buf[ret] = 0;
12329103f1ceSFam Zheng     /* The file is ended with '\n', pass 'end' to accept that. */
12339103f1ceSFam Zheng     ret = qemu_strtol(buf, &end, 10, &max_segments);
12349103f1ceSFam Zheng     if (ret == 0 && end && *end == '\n') {
12359103f1ceSFam Zheng         ret = max_segments;
12369103f1ceSFam Zheng     }
12379103f1ceSFam Zheng 
12389103f1ceSFam Zheng out:
1239867eccfeSMaxim Levitsky     if (sysfd != -1) {
1240867eccfeSMaxim Levitsky         close(sysfd);
1241fed414dfSFam Zheng     }
12429103f1ceSFam Zheng     g_free(sysfspath);
12439103f1ceSFam Zheng     return ret;
12449103f1ceSFam Zheng #else
12459103f1ceSFam Zheng     return -ENOTSUP;
12469103f1ceSFam Zheng #endif
12479103f1ceSFam Zheng }
12489103f1ceSFam Zheng 
1249c1bb86cdSEric Blake static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1250c1bb86cdSEric Blake {
1251c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
125218473467SPaolo Bonzini     struct stat st;
1253c1bb86cdSEric Blake 
1254c1bb86cdSEric Blake     raw_probe_alignment(bs, s->fd, errp);
1255c1bb86cdSEric Blake     bs->bl.min_mem_alignment = s->buf_align;
1256038adc2fSWei Yang     bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size);
125718473467SPaolo Bonzini 
125818473467SPaolo Bonzini     /*
125918473467SPaolo Bonzini      * Maximum transfers are best effort, so it is okay to ignore any
126018473467SPaolo Bonzini      * errors.  That said, based on the man page errors in fstat would be
126118473467SPaolo Bonzini      * very much unexpected; the only possible case seems to be ENOMEM.
126218473467SPaolo Bonzini      */
126318473467SPaolo Bonzini     if (fstat(s->fd, &st)) {
126418473467SPaolo Bonzini         return;
126518473467SPaolo Bonzini     }
126618473467SPaolo Bonzini 
12670dfc7af2SAkihiko Odaki #if defined(__APPLE__) && (__MACH__)
12680dfc7af2SAkihiko Odaki     struct statfs buf;
12690dfc7af2SAkihiko Odaki 
12700dfc7af2SAkihiko Odaki     if (!fstatfs(s->fd, &buf)) {
12710dfc7af2SAkihiko Odaki         bs->bl.opt_transfer = buf.f_iosize;
12720dfc7af2SAkihiko Odaki         bs->bl.pdiscard_alignment = buf.f_bsize;
12730dfc7af2SAkihiko Odaki     }
12740dfc7af2SAkihiko Odaki #endif
12750dfc7af2SAkihiko Odaki 
127618473467SPaolo Bonzini     if (bs->sg || S_ISBLK(st.st_mode)) {
127718473467SPaolo Bonzini         int ret = hdev_get_max_hw_transfer(s->fd, &st);
127818473467SPaolo Bonzini 
127918473467SPaolo Bonzini         if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
128018473467SPaolo Bonzini             bs->bl.max_hw_transfer = ret;
128118473467SPaolo Bonzini         }
128218473467SPaolo Bonzini 
128318473467SPaolo Bonzini         ret = hdev_get_max_segments(s->fd, &st);
128418473467SPaolo Bonzini         if (ret > 0) {
1285cc071629SPaolo Bonzini             bs->bl.max_hw_iov = ret;
128618473467SPaolo Bonzini         }
128718473467SPaolo Bonzini     }
1288c1bb86cdSEric Blake }
1289c1bb86cdSEric Blake 
1290c1bb86cdSEric Blake static int check_for_dasd(int fd)
1291c1bb86cdSEric Blake {
1292c1bb86cdSEric Blake #ifdef BIODASDINFO2
1293c1bb86cdSEric Blake     struct dasd_information2_t info = {0};
1294c1bb86cdSEric Blake 
1295c1bb86cdSEric Blake     return ioctl(fd, BIODASDINFO2, &info);
1296c1bb86cdSEric Blake #else
1297c1bb86cdSEric Blake     return -1;
1298c1bb86cdSEric Blake #endif
1299c1bb86cdSEric Blake }
1300c1bb86cdSEric Blake 
1301c1bb86cdSEric Blake /**
1302c1bb86cdSEric Blake  * Try to get @bs's logical and physical block size.
1303c1bb86cdSEric Blake  * On success, store them in @bsz and return zero.
1304c1bb86cdSEric Blake  * On failure, return negative errno.
1305c1bb86cdSEric Blake  */
1306c1bb86cdSEric Blake static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1307c1bb86cdSEric Blake {
1308c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1309c1bb86cdSEric Blake     int ret;
1310c1bb86cdSEric Blake 
1311c1bb86cdSEric Blake     /* If DASD, get blocksizes */
1312c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1313c1bb86cdSEric Blake         return -ENOTSUP;
1314c1bb86cdSEric Blake     }
1315c1bb86cdSEric Blake     ret = probe_logical_blocksize(s->fd, &bsz->log);
1316c1bb86cdSEric Blake     if (ret < 0) {
1317c1bb86cdSEric Blake         return ret;
1318c1bb86cdSEric Blake     }
1319c1bb86cdSEric Blake     return probe_physical_blocksize(s->fd, &bsz->phys);
1320c1bb86cdSEric Blake }
1321c1bb86cdSEric Blake 
1322c1bb86cdSEric Blake /**
1323c1bb86cdSEric Blake  * Try to get @bs's geometry: cyls, heads, sectors.
1324c1bb86cdSEric Blake  * On success, store them in @geo and return 0.
1325c1bb86cdSEric Blake  * On failure return -errno.
1326c1bb86cdSEric Blake  * (Allows block driver to assign default geometry values that guest sees)
1327c1bb86cdSEric Blake  */
1328c1bb86cdSEric Blake #ifdef __linux__
1329c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1330c1bb86cdSEric Blake {
1331c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
1332c1bb86cdSEric Blake     struct hd_geometry ioctl_geo = {0};
1333c1bb86cdSEric Blake 
1334c1bb86cdSEric Blake     /* If DASD, get its geometry */
1335c1bb86cdSEric Blake     if (check_for_dasd(s->fd) < 0) {
1336c1bb86cdSEric Blake         return -ENOTSUP;
1337c1bb86cdSEric Blake     }
1338c1bb86cdSEric Blake     if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1339c1bb86cdSEric Blake         return -errno;
1340c1bb86cdSEric Blake     }
1341c1bb86cdSEric Blake     /* HDIO_GETGEO may return success even though geo contains zeros
1342c1bb86cdSEric Blake        (e.g. certain multipath setups) */
1343c1bb86cdSEric Blake     if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1344c1bb86cdSEric Blake         return -ENOTSUP;
1345c1bb86cdSEric Blake     }
1346c1bb86cdSEric Blake     /* Do not return a geometry for partition */
1347c1bb86cdSEric Blake     if (ioctl_geo.start != 0) {
1348c1bb86cdSEric Blake         return -ENOTSUP;
1349c1bb86cdSEric Blake     }
1350c1bb86cdSEric Blake     geo->heads = ioctl_geo.heads;
1351c1bb86cdSEric Blake     geo->sectors = ioctl_geo.sectors;
1352c1bb86cdSEric Blake     geo->cylinders = ioctl_geo.cylinders;
1353c1bb86cdSEric Blake 
1354c1bb86cdSEric Blake     return 0;
1355c1bb86cdSEric Blake }
1356c1bb86cdSEric Blake #else /* __linux__ */
1357c1bb86cdSEric Blake static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1358c1bb86cdSEric Blake {
1359c1bb86cdSEric Blake     return -ENOTSUP;
1360c1bb86cdSEric Blake }
1361c1bb86cdSEric Blake #endif
1362c1bb86cdSEric Blake 
136303425671SKevin Wolf #if defined(__linux__)
136403425671SKevin Wolf static int handle_aiocb_ioctl(void *opaque)
1365c1bb86cdSEric Blake {
136603425671SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1367c1bb86cdSEric Blake     int ret;
1368c1bb86cdSEric Blake 
1369bd80936aSPaolo Bonzini     do {
1370d57c44d0SKevin Wolf         ret = ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf);
1371bd80936aSPaolo Bonzini     } while (ret == -1 && errno == EINTR);
1372c1bb86cdSEric Blake     if (ret == -1) {
1373c1bb86cdSEric Blake         return -errno;
1374c1bb86cdSEric Blake     }
1375c1bb86cdSEric Blake 
1376c1bb86cdSEric Blake     return 0;
1377c1bb86cdSEric Blake }
137803425671SKevin Wolf #endif /* linux */
1379c1bb86cdSEric Blake 
138006dc9bd5SKevin Wolf static int handle_aiocb_flush(void *opaque)
1381c1bb86cdSEric Blake {
138206dc9bd5SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1383e5bcf967SKevin Wolf     BDRVRawState *s = aiocb->bs->opaque;
1384c1bb86cdSEric Blake     int ret;
1385c1bb86cdSEric Blake 
1386e5bcf967SKevin Wolf     if (s->page_cache_inconsistent) {
1387c7ddc882SDaniel P. Berrangé         return -s->page_cache_inconsistent;
1388e5bcf967SKevin Wolf     }
1389e5bcf967SKevin Wolf 
1390c1bb86cdSEric Blake     ret = qemu_fdatasync(aiocb->aio_fildes);
1391c1bb86cdSEric Blake     if (ret == -1) {
139260ff2ae2SDaniel P. Berrangé         trace_file_flush_fdatasync_failed(errno);
139360ff2ae2SDaniel P. Berrangé 
1394e5bcf967SKevin Wolf         /* There is no clear definition of the semantics of a failing fsync(),
1395e5bcf967SKevin Wolf          * so we may have to assume the worst. The sad truth is that this
1396e5bcf967SKevin Wolf          * assumption is correct for Linux. Some pages are now probably marked
1397e5bcf967SKevin Wolf          * clean in the page cache even though they are inconsistent with the
1398e5bcf967SKevin Wolf          * on-disk contents. The next fdatasync() call would succeed, but no
1399e5bcf967SKevin Wolf          * further writeback attempt will be made. We can't get back to a state
1400e5bcf967SKevin Wolf          * in which we know what is on disk (we would have to rewrite
1401e5bcf967SKevin Wolf          * everything that was touched since the last fdatasync() at least), so
1402e5bcf967SKevin Wolf          * make bdrv_flush() fail permanently. Given that the behaviour isn't
1403e5bcf967SKevin Wolf          * really defined, I have little hope that other OSes are doing better.
1404e5bcf967SKevin Wolf          *
1405e5bcf967SKevin Wolf          * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1406e5bcf967SKevin Wolf          * cache. */
1407e5bcf967SKevin Wolf         if ((s->open_flags & O_DIRECT) == 0) {
1408c7ddc882SDaniel P. Berrangé             s->page_cache_inconsistent = errno;
1409e5bcf967SKevin Wolf         }
1410c1bb86cdSEric Blake         return -errno;
1411c1bb86cdSEric Blake     }
1412c1bb86cdSEric Blake     return 0;
1413c1bb86cdSEric Blake }
1414c1bb86cdSEric Blake 
1415c1bb86cdSEric Blake #ifdef CONFIG_PREADV
1416c1bb86cdSEric Blake 
1417c1bb86cdSEric Blake static bool preadv_present = true;
1418c1bb86cdSEric Blake 
1419c1bb86cdSEric Blake static ssize_t
1420c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1421c1bb86cdSEric Blake {
1422c1bb86cdSEric Blake     return preadv(fd, iov, nr_iov, offset);
1423c1bb86cdSEric Blake }
1424c1bb86cdSEric Blake 
1425c1bb86cdSEric Blake static ssize_t
1426c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1427c1bb86cdSEric Blake {
1428c1bb86cdSEric Blake     return pwritev(fd, iov, nr_iov, offset);
1429c1bb86cdSEric Blake }
1430c1bb86cdSEric Blake 
1431c1bb86cdSEric Blake #else
1432c1bb86cdSEric Blake 
1433c1bb86cdSEric Blake static bool preadv_present = false;
1434c1bb86cdSEric Blake 
1435c1bb86cdSEric Blake static ssize_t
1436c1bb86cdSEric Blake qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1437c1bb86cdSEric Blake {
1438c1bb86cdSEric Blake     return -ENOSYS;
1439c1bb86cdSEric Blake }
1440c1bb86cdSEric Blake 
1441c1bb86cdSEric Blake static ssize_t
1442c1bb86cdSEric Blake qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1443c1bb86cdSEric Blake {
1444c1bb86cdSEric Blake     return -ENOSYS;
1445c1bb86cdSEric Blake }
1446c1bb86cdSEric Blake 
1447c1bb86cdSEric Blake #endif
1448c1bb86cdSEric Blake 
1449c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1450c1bb86cdSEric Blake {
1451c1bb86cdSEric Blake     ssize_t len;
1452c1bb86cdSEric Blake 
1453c1bb86cdSEric Blake     do {
1454c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE)
1455c1bb86cdSEric Blake             len = qemu_pwritev(aiocb->aio_fildes,
1456d57c44d0SKevin Wolf                                aiocb->io.iov,
1457d57c44d0SKevin Wolf                                aiocb->io.niov,
1458c1bb86cdSEric Blake                                aiocb->aio_offset);
1459c1bb86cdSEric Blake          else
1460c1bb86cdSEric Blake             len = qemu_preadv(aiocb->aio_fildes,
1461d57c44d0SKevin Wolf                               aiocb->io.iov,
1462d57c44d0SKevin Wolf                               aiocb->io.niov,
1463c1bb86cdSEric Blake                               aiocb->aio_offset);
1464c1bb86cdSEric Blake     } while (len == -1 && errno == EINTR);
1465c1bb86cdSEric Blake 
1466c1bb86cdSEric Blake     if (len == -1) {
1467c1bb86cdSEric Blake         return -errno;
1468c1bb86cdSEric Blake     }
1469c1bb86cdSEric Blake     return len;
1470c1bb86cdSEric Blake }
1471c1bb86cdSEric Blake 
1472c1bb86cdSEric Blake /*
1473c1bb86cdSEric Blake  * Read/writes the data to/from a given linear buffer.
1474c1bb86cdSEric Blake  *
1475c1bb86cdSEric Blake  * Returns the number of bytes handles or -errno in case of an error. Short
1476c1bb86cdSEric Blake  * reads are only returned if the end of the file is reached.
1477c1bb86cdSEric Blake  */
1478c1bb86cdSEric Blake static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1479c1bb86cdSEric Blake {
1480c1bb86cdSEric Blake     ssize_t offset = 0;
1481c1bb86cdSEric Blake     ssize_t len;
1482c1bb86cdSEric Blake 
1483c1bb86cdSEric Blake     while (offset < aiocb->aio_nbytes) {
1484c1bb86cdSEric Blake         if (aiocb->aio_type & QEMU_AIO_WRITE) {
1485c1bb86cdSEric Blake             len = pwrite(aiocb->aio_fildes,
1486c1bb86cdSEric Blake                          (const char *)buf + offset,
1487c1bb86cdSEric Blake                          aiocb->aio_nbytes - offset,
1488c1bb86cdSEric Blake                          aiocb->aio_offset + offset);
1489c1bb86cdSEric Blake         } else {
1490c1bb86cdSEric Blake             len = pread(aiocb->aio_fildes,
1491c1bb86cdSEric Blake                         buf + offset,
1492c1bb86cdSEric Blake                         aiocb->aio_nbytes - offset,
1493c1bb86cdSEric Blake                         aiocb->aio_offset + offset);
1494c1bb86cdSEric Blake         }
1495c1bb86cdSEric Blake         if (len == -1 && errno == EINTR) {
1496c1bb86cdSEric Blake             continue;
1497c1bb86cdSEric Blake         } else if (len == -1 && errno == EINVAL &&
1498c1bb86cdSEric Blake                    (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1499c1bb86cdSEric Blake                    !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1500c1bb86cdSEric Blake                    offset > 0) {
1501c1bb86cdSEric Blake             /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1502c1bb86cdSEric Blake              * after a short read.  Assume that O_DIRECT short reads only occur
1503c1bb86cdSEric Blake              * at EOF.  Therefore this is a short read, not an I/O error.
1504c1bb86cdSEric Blake              */
1505c1bb86cdSEric Blake             break;
1506c1bb86cdSEric Blake         } else if (len == -1) {
1507c1bb86cdSEric Blake             offset = -errno;
1508c1bb86cdSEric Blake             break;
1509c1bb86cdSEric Blake         } else if (len == 0) {
1510c1bb86cdSEric Blake             break;
1511c1bb86cdSEric Blake         }
1512c1bb86cdSEric Blake         offset += len;
1513c1bb86cdSEric Blake     }
1514c1bb86cdSEric Blake 
1515c1bb86cdSEric Blake     return offset;
1516c1bb86cdSEric Blake }
1517c1bb86cdSEric Blake 
1518999e6b69SKevin Wolf static int handle_aiocb_rw(void *opaque)
1519c1bb86cdSEric Blake {
1520999e6b69SKevin Wolf     RawPosixAIOData *aiocb = opaque;
1521c1bb86cdSEric Blake     ssize_t nbytes;
1522c1bb86cdSEric Blake     char *buf;
1523c1bb86cdSEric Blake 
1524c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1525c1bb86cdSEric Blake         /*
1526c1bb86cdSEric Blake          * If there is just a single buffer, and it is properly aligned
1527c1bb86cdSEric Blake          * we can just use plain pread/pwrite without any problems.
1528c1bb86cdSEric Blake          */
1529d57c44d0SKevin Wolf         if (aiocb->io.niov == 1) {
153054c7ca1bSKevin Wolf             nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
153154c7ca1bSKevin Wolf             goto out;
1532c1bb86cdSEric Blake         }
1533c1bb86cdSEric Blake         /*
1534c1bb86cdSEric Blake          * We have more than one iovec, and all are properly aligned.
1535c1bb86cdSEric Blake          *
1536c1bb86cdSEric Blake          * Try preadv/pwritev first and fall back to linearizing the
1537c1bb86cdSEric Blake          * buffer if it's not supported.
1538c1bb86cdSEric Blake          */
1539c1bb86cdSEric Blake         if (preadv_present) {
1540c1bb86cdSEric Blake             nbytes = handle_aiocb_rw_vector(aiocb);
1541c1bb86cdSEric Blake             if (nbytes == aiocb->aio_nbytes ||
1542c1bb86cdSEric Blake                 (nbytes < 0 && nbytes != -ENOSYS)) {
154354c7ca1bSKevin Wolf                 goto out;
1544c1bb86cdSEric Blake             }
1545c1bb86cdSEric Blake             preadv_present = false;
1546c1bb86cdSEric Blake         }
1547c1bb86cdSEric Blake 
1548c1bb86cdSEric Blake         /*
1549c1bb86cdSEric Blake          * XXX(hch): short read/write.  no easy way to handle the reminder
1550c1bb86cdSEric Blake          * using these interfaces.  For now retry using plain
1551c1bb86cdSEric Blake          * pread/pwrite?
1552c1bb86cdSEric Blake          */
1553c1bb86cdSEric Blake     }
1554c1bb86cdSEric Blake 
1555c1bb86cdSEric Blake     /*
1556c1bb86cdSEric Blake      * Ok, we have to do it the hard way, copy all segments into
1557c1bb86cdSEric Blake      * a single aligned buffer.
1558c1bb86cdSEric Blake      */
1559c1bb86cdSEric Blake     buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1560c1bb86cdSEric Blake     if (buf == NULL) {
156154c7ca1bSKevin Wolf         nbytes = -ENOMEM;
156254c7ca1bSKevin Wolf         goto out;
1563c1bb86cdSEric Blake     }
1564c1bb86cdSEric Blake 
1565c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_WRITE) {
1566c1bb86cdSEric Blake         char *p = buf;
1567c1bb86cdSEric Blake         int i;
1568c1bb86cdSEric Blake 
1569d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov; ++i) {
1570d57c44d0SKevin Wolf             memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1571d57c44d0SKevin Wolf             p += aiocb->io.iov[i].iov_len;
1572c1bb86cdSEric Blake         }
1573c1bb86cdSEric Blake         assert(p - buf == aiocb->aio_nbytes);
1574c1bb86cdSEric Blake     }
1575c1bb86cdSEric Blake 
1576c1bb86cdSEric Blake     nbytes = handle_aiocb_rw_linear(aiocb, buf);
1577c1bb86cdSEric Blake     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1578c1bb86cdSEric Blake         char *p = buf;
1579c1bb86cdSEric Blake         size_t count = aiocb->aio_nbytes, copy;
1580c1bb86cdSEric Blake         int i;
1581c1bb86cdSEric Blake 
1582d57c44d0SKevin Wolf         for (i = 0; i < aiocb->io.niov && count; ++i) {
1583c1bb86cdSEric Blake             copy = count;
1584d57c44d0SKevin Wolf             if (copy > aiocb->io.iov[i].iov_len) {
1585d57c44d0SKevin Wolf                 copy = aiocb->io.iov[i].iov_len;
1586c1bb86cdSEric Blake             }
1587d57c44d0SKevin Wolf             memcpy(aiocb->io.iov[i].iov_base, p, copy);
1588c1bb86cdSEric Blake             assert(count >= copy);
1589c1bb86cdSEric Blake             p     += copy;
1590c1bb86cdSEric Blake             count -= copy;
1591c1bb86cdSEric Blake         }
1592c1bb86cdSEric Blake         assert(count == 0);
1593c1bb86cdSEric Blake     }
1594c1bb86cdSEric Blake     qemu_vfree(buf);
1595c1bb86cdSEric Blake 
159654c7ca1bSKevin Wolf out:
159754c7ca1bSKevin Wolf     if (nbytes == aiocb->aio_nbytes) {
159854c7ca1bSKevin Wolf         return 0;
159954c7ca1bSKevin Wolf     } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
160054c7ca1bSKevin Wolf         if (aiocb->aio_type & QEMU_AIO_WRITE) {
160154c7ca1bSKevin Wolf             return -EINVAL;
160254c7ca1bSKevin Wolf         } else {
160354c7ca1bSKevin Wolf             iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
160454c7ca1bSKevin Wolf                       0, aiocb->aio_nbytes - nbytes);
160554c7ca1bSKevin Wolf             return 0;
160654c7ca1bSKevin Wolf         }
160754c7ca1bSKevin Wolf     } else {
160854c7ca1bSKevin Wolf         assert(nbytes < 0);
1609c1bb86cdSEric Blake         return nbytes;
1610c1bb86cdSEric Blake     }
161154c7ca1bSKevin Wolf }
1612c1bb86cdSEric Blake 
16130dfc7af2SAkihiko Odaki #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1614c1bb86cdSEric Blake static int translate_err(int err)
1615c1bb86cdSEric Blake {
1616c1bb86cdSEric Blake     if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1617c1bb86cdSEric Blake         err == -ENOTTY) {
1618c1bb86cdSEric Blake         err = -ENOTSUP;
1619c1bb86cdSEric Blake     }
1620c1bb86cdSEric Blake     return err;
1621c1bb86cdSEric Blake }
16220dfc7af2SAkihiko Odaki #endif
1623c1bb86cdSEric Blake 
1624c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
1625c1bb86cdSEric Blake static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1626c1bb86cdSEric Blake {
1627c1bb86cdSEric Blake     do {
1628c1bb86cdSEric Blake         if (fallocate(fd, mode, offset, len) == 0) {
1629c1bb86cdSEric Blake             return 0;
1630c1bb86cdSEric Blake         }
1631c1bb86cdSEric Blake     } while (errno == EINTR);
1632c1bb86cdSEric Blake     return translate_err(-errno);
1633c1bb86cdSEric Blake }
1634c1bb86cdSEric Blake #endif
1635c1bb86cdSEric Blake 
1636c1bb86cdSEric Blake static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1637c1bb86cdSEric Blake {
1638c1bb86cdSEric Blake     int ret = -ENOTSUP;
1639c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1640c1bb86cdSEric Blake 
1641c1bb86cdSEric Blake     if (!s->has_write_zeroes) {
1642c1bb86cdSEric Blake         return -ENOTSUP;
1643c1bb86cdSEric Blake     }
1644c1bb86cdSEric Blake 
1645c1bb86cdSEric Blake #ifdef BLKZEROOUT
1646738301e1SKevin Wolf     /* The BLKZEROOUT implementation in the kernel doesn't set
1647738301e1SKevin Wolf      * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1648738301e1SKevin Wolf      * fallbacks. */
1649738301e1SKevin Wolf     if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1650c1bb86cdSEric Blake         do {
1651c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1652c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1653c1bb86cdSEric Blake                 return 0;
1654c1bb86cdSEric Blake             }
1655c1bb86cdSEric Blake         } while (errno == EINTR);
1656c1bb86cdSEric Blake 
1657c1bb86cdSEric Blake         ret = translate_err(-errno);
1658c1bb86cdSEric Blake         if (ret == -ENOTSUP) {
1659c1bb86cdSEric Blake             s->has_write_zeroes = false;
1660c1bb86cdSEric Blake         }
1661effecce6SKevin Wolf     }
1662effecce6SKevin Wolf #endif
1663effecce6SKevin Wolf 
1664c1bb86cdSEric Blake     return ret;
1665c1bb86cdSEric Blake }
1666c1bb86cdSEric Blake 
16677154d8aeSKevin Wolf static int handle_aiocb_write_zeroes(void *opaque)
1668c1bb86cdSEric Blake {
16697154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
167070d9110bSDenis V. Lunev #ifdef CONFIG_FALLOCATE
1671b2c6f23fSMax Reitz     BDRVRawState *s = aiocb->bs->opaque;
167270d9110bSDenis V. Lunev     int64_t len;
167370d9110bSDenis V. Lunev #endif
1674c1bb86cdSEric Blake 
1675c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1676c1bb86cdSEric Blake         return handle_aiocb_write_zeroes_block(aiocb);
1677c1bb86cdSEric Blake     }
1678c1bb86cdSEric Blake 
1679c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1680c1bb86cdSEric Blake     if (s->has_write_zeroes) {
1681c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1682c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1683fa95e9fbSThomas Huth         if (ret == -ENOTSUP) {
1684fa95e9fbSThomas Huth             s->has_write_zeroes = false;
1685fa95e9fbSThomas Huth         } else if (ret == 0 || ret != -EINVAL) {
1686c1bb86cdSEric Blake             return ret;
1687c1bb86cdSEric Blake         }
1688fa95e9fbSThomas Huth         /*
1689fa95e9fbSThomas Huth          * Note: Some file systems do not like unaligned byte ranges, and
1690fa95e9fbSThomas Huth          * return EINVAL in such a case, though they should not do it according
1691fa95e9fbSThomas Huth          * to the man-page of fallocate(). Thus we simply ignore this return
1692fa95e9fbSThomas Huth          * value and try the other fallbacks instead.
1693fa95e9fbSThomas Huth          */
1694c1bb86cdSEric Blake     }
1695c1bb86cdSEric Blake #endif
1696c1bb86cdSEric Blake 
1697c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1698c1bb86cdSEric Blake     if (s->has_discard && s->has_fallocate) {
1699c1bb86cdSEric Blake         int ret = do_fallocate(s->fd,
1700c1bb86cdSEric Blake                                FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1701c1bb86cdSEric Blake                                aiocb->aio_offset, aiocb->aio_nbytes);
1702c1bb86cdSEric Blake         if (ret == 0) {
1703c1bb86cdSEric Blake             ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1704c1bb86cdSEric Blake             if (ret == 0 || ret != -ENOTSUP) {
1705c1bb86cdSEric Blake                 return ret;
1706c1bb86cdSEric Blake             }
1707c1bb86cdSEric Blake             s->has_fallocate = false;
170873ebf297SThomas Huth         } else if (ret == -EINVAL) {
170973ebf297SThomas Huth             /*
171073ebf297SThomas Huth              * Some file systems like older versions of GPFS do not like un-
171173ebf297SThomas Huth              * aligned byte ranges, and return EINVAL in such a case, though
171273ebf297SThomas Huth              * they should not do it according to the man-page of fallocate().
171373ebf297SThomas Huth              * Warn about the bad filesystem and try the final fallback instead.
171473ebf297SThomas Huth              */
171573ebf297SThomas Huth             warn_report_once("Your file system is misbehaving: "
171673ebf297SThomas Huth                              "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
171768857f13SMichael Tokarev                              "Please report this bug to your file system "
171873ebf297SThomas Huth                              "vendor.");
1719c1bb86cdSEric Blake         } else if (ret != -ENOTSUP) {
1720c1bb86cdSEric Blake             return ret;
1721c1bb86cdSEric Blake         } else {
1722c1bb86cdSEric Blake             s->has_discard = false;
1723c1bb86cdSEric Blake         }
1724c1bb86cdSEric Blake     }
1725c1bb86cdSEric Blake #endif
1726c1bb86cdSEric Blake 
1727c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE
172870d9110bSDenis V. Lunev     /* Last resort: we are trying to extend the file with zeroed data. This
172970d9110bSDenis V. Lunev      * can be done via fallocate(fd, 0) */
173070d9110bSDenis V. Lunev     len = bdrv_getlength(aiocb->bs);
173170d9110bSDenis V. Lunev     if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1732c1bb86cdSEric Blake         int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1733c1bb86cdSEric Blake         if (ret == 0 || ret != -ENOTSUP) {
1734c1bb86cdSEric Blake             return ret;
1735c1bb86cdSEric Blake         }
1736c1bb86cdSEric Blake         s->has_fallocate = false;
1737c1bb86cdSEric Blake     }
1738c1bb86cdSEric Blake #endif
1739c1bb86cdSEric Blake 
1740c1bb86cdSEric Blake     return -ENOTSUP;
1741c1bb86cdSEric Blake }
1742c1bb86cdSEric Blake 
17437154d8aeSKevin Wolf static int handle_aiocb_write_zeroes_unmap(void *opaque)
174434fa110eSKevin Wolf {
17457154d8aeSKevin Wolf     RawPosixAIOData *aiocb = opaque;
174634fa110eSKevin Wolf     BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
174734fa110eSKevin Wolf 
174834fa110eSKevin Wolf     /* First try to write zeros and unmap at the same time */
174934fa110eSKevin Wolf 
175034fa110eSKevin Wolf #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1751b3ac2b94SSimran Singhal     int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
175234fa110eSKevin Wolf                            aiocb->aio_offset, aiocb->aio_nbytes);
1753bae127d4SAntoine Damhet     switch (ret) {
1754bae127d4SAntoine Damhet     case -ENOTSUP:
1755bae127d4SAntoine Damhet     case -EINVAL:
1756ece4fa91SMaxim Levitsky     case -EBUSY:
1757bae127d4SAntoine Damhet         break;
1758bae127d4SAntoine Damhet     default:
175934fa110eSKevin Wolf         return ret;
176034fa110eSKevin Wolf     }
176134fa110eSKevin Wolf #endif
176234fa110eSKevin Wolf 
176334fa110eSKevin Wolf     /* If we couldn't manage to unmap while guaranteed that the area reads as
176434fa110eSKevin Wolf      * all-zero afterwards, just write zeroes without unmapping */
1765b3ac2b94SSimran Singhal     return handle_aiocb_write_zeroes(aiocb);
176634fa110eSKevin Wolf }
176734fa110eSKevin Wolf 
17681efad060SFam Zheng #ifndef HAVE_COPY_FILE_RANGE
17691efad060SFam Zheng static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
17701efad060SFam Zheng                              off_t *out_off, size_t len, unsigned int flags)
17711efad060SFam Zheng {
17721efad060SFam Zheng #ifdef __NR_copy_file_range
17731efad060SFam Zheng     return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
17741efad060SFam Zheng                    out_off, len, flags);
17751efad060SFam Zheng #else
17761efad060SFam Zheng     errno = ENOSYS;
17771efad060SFam Zheng     return -1;
17781efad060SFam Zheng #endif
17791efad060SFam Zheng }
17801efad060SFam Zheng #endif
17811efad060SFam Zheng 
178258a209c4SKevin Wolf static int handle_aiocb_copy_range(void *opaque)
17831efad060SFam Zheng {
178458a209c4SKevin Wolf     RawPosixAIOData *aiocb = opaque;
17851efad060SFam Zheng     uint64_t bytes = aiocb->aio_nbytes;
17861efad060SFam Zheng     off_t in_off = aiocb->aio_offset;
1787d57c44d0SKevin Wolf     off_t out_off = aiocb->copy_range.aio_offset2;
17881efad060SFam Zheng 
17891efad060SFam Zheng     while (bytes) {
17901efad060SFam Zheng         ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
1791d57c44d0SKevin Wolf                                       aiocb->copy_range.aio_fd2, &out_off,
17921efad060SFam Zheng                                       bytes, 0);
1793ecc983a5SFam Zheng         trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
1794d57c44d0SKevin Wolf                                    aiocb->copy_range.aio_fd2, out_off, bytes,
1795d57c44d0SKevin Wolf                                    0, ret);
1796c436e3d0SFam Zheng         if (ret == 0) {
1797c436e3d0SFam Zheng             /* No progress (e.g. when beyond EOF), let the caller fall back to
1798c436e3d0SFam Zheng              * buffer I/O. */
1799c436e3d0SFam Zheng             return -ENOSPC;
18001efad060SFam Zheng         }
18011efad060SFam Zheng         if (ret < 0) {
1802c436e3d0SFam Zheng             switch (errno) {
1803c436e3d0SFam Zheng             case ENOSYS:
18041efad060SFam Zheng                 return -ENOTSUP;
1805c436e3d0SFam Zheng             case EINTR:
1806c436e3d0SFam Zheng                 continue;
1807c436e3d0SFam Zheng             default:
18081efad060SFam Zheng                 return -errno;
18091efad060SFam Zheng             }
18101efad060SFam Zheng         }
18111efad060SFam Zheng         bytes -= ret;
18121efad060SFam Zheng     }
18131efad060SFam Zheng     return 0;
18141efad060SFam Zheng }
18151efad060SFam Zheng 
181646ee0f46SKevin Wolf static int handle_aiocb_discard(void *opaque)
1817c1bb86cdSEric Blake {
181846ee0f46SKevin Wolf     RawPosixAIOData *aiocb = opaque;
181913a02833SAri Sundholm     int ret = -ENOTSUP;
1820c1bb86cdSEric Blake     BDRVRawState *s = aiocb->bs->opaque;
1821c1bb86cdSEric Blake 
1822c1bb86cdSEric Blake     if (!s->has_discard) {
1823c1bb86cdSEric Blake         return -ENOTSUP;
1824c1bb86cdSEric Blake     }
1825c1bb86cdSEric Blake 
1826c1bb86cdSEric Blake     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1827c1bb86cdSEric Blake #ifdef BLKDISCARD
1828c1bb86cdSEric Blake         do {
1829c1bb86cdSEric Blake             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1830c1bb86cdSEric Blake             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1831c1bb86cdSEric Blake                 return 0;
1832c1bb86cdSEric Blake             }
1833c1bb86cdSEric Blake         } while (errno == EINTR);
1834c1bb86cdSEric Blake 
18350dfc7af2SAkihiko Odaki         ret = translate_err(-errno);
1836c1bb86cdSEric Blake #endif
1837c1bb86cdSEric Blake     } else {
1838c1bb86cdSEric Blake #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1839c1bb86cdSEric Blake         ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1840c1bb86cdSEric Blake                            aiocb->aio_offset, aiocb->aio_nbytes);
184113a02833SAri Sundholm         ret = translate_err(ret);
18420dfc7af2SAkihiko Odaki #elif defined(__APPLE__) && (__MACH__)
18430dfc7af2SAkihiko Odaki         fpunchhole_t fpunchhole;
18440dfc7af2SAkihiko Odaki         fpunchhole.fp_flags = 0;
18450dfc7af2SAkihiko Odaki         fpunchhole.reserved = 0;
18460dfc7af2SAkihiko Odaki         fpunchhole.fp_offset = aiocb->aio_offset;
18470dfc7af2SAkihiko Odaki         fpunchhole.fp_length = aiocb->aio_nbytes;
18480dfc7af2SAkihiko Odaki         if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
18490dfc7af2SAkihiko Odaki             ret = errno == ENODEV ? -ENOTSUP : -errno;
18500dfc7af2SAkihiko Odaki         } else {
18510dfc7af2SAkihiko Odaki             ret = 0;
18520dfc7af2SAkihiko Odaki         }
1853c1bb86cdSEric Blake #endif
1854c1bb86cdSEric Blake     }
1855c1bb86cdSEric Blake 
1856c1bb86cdSEric Blake     if (ret == -ENOTSUP) {
1857c1bb86cdSEric Blake         s->has_discard = false;
1858c1bb86cdSEric Blake     }
1859c1bb86cdSEric Blake     return ret;
1860c1bb86cdSEric Blake }
1861c1bb86cdSEric Blake 
18623a20013fSNir Soffer /*
18633a20013fSNir Soffer  * Help alignment probing by allocating the first block.
18643a20013fSNir Soffer  *
18653a20013fSNir Soffer  * When reading with direct I/O from unallocated area on Gluster backed by XFS,
18663a20013fSNir Soffer  * reading succeeds regardless of request length. In this case we fallback to
18673a20013fSNir Soffer  * safe alignment which is not optimal. Allocating the first block avoids this
18683a20013fSNir Soffer  * fallback.
18693a20013fSNir Soffer  *
18703a20013fSNir Soffer  * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
18713a20013fSNir Soffer  * request alignment, so we use safe values.
18723a20013fSNir Soffer  *
18733a20013fSNir Soffer  * Returns: 0 on success, -errno on failure. Since this is an optimization,
18743a20013fSNir Soffer  * caller may ignore failures.
18753a20013fSNir Soffer  */
18763a20013fSNir Soffer static int allocate_first_block(int fd, size_t max_size)
18773a20013fSNir Soffer {
18783a20013fSNir Soffer     size_t write_size = (max_size < MAX_BLOCKSIZE)
18793a20013fSNir Soffer         ? BDRV_SECTOR_SIZE
18803a20013fSNir Soffer         : MAX_BLOCKSIZE;
1881038adc2fSWei Yang     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size);
18823a20013fSNir Soffer     void *buf;
18833a20013fSNir Soffer     ssize_t n;
18843a20013fSNir Soffer     int ret;
18853a20013fSNir Soffer 
18863a20013fSNir Soffer     buf = qemu_memalign(max_align, write_size);
18873a20013fSNir Soffer     memset(buf, 0, write_size);
18883a20013fSNir Soffer 
18893a20013fSNir Soffer     do {
18903a20013fSNir Soffer         n = pwrite(fd, buf, write_size, 0);
18913a20013fSNir Soffer     } while (n == -1 && errno == EINTR);
18923a20013fSNir Soffer 
18933a20013fSNir Soffer     ret = (n == -1) ? -errno : 0;
18943a20013fSNir Soffer 
18953a20013fSNir Soffer     qemu_vfree(buf);
18963a20013fSNir Soffer     return ret;
18973a20013fSNir Soffer }
18983a20013fSNir Soffer 
189929cb4c01SKevin Wolf static int handle_aiocb_truncate(void *opaque)
190093f4e2ffSKevin Wolf {
190129cb4c01SKevin Wolf     RawPosixAIOData *aiocb = opaque;
190293f4e2ffSKevin Wolf     int result = 0;
190393f4e2ffSKevin Wolf     int64_t current_length = 0;
190493f4e2ffSKevin Wolf     char *buf = NULL;
190593f4e2ffSKevin Wolf     struct stat st;
190693f4e2ffSKevin Wolf     int fd = aiocb->aio_fildes;
190793f4e2ffSKevin Wolf     int64_t offset = aiocb->aio_offset;
1908d57c44d0SKevin Wolf     PreallocMode prealloc = aiocb->truncate.prealloc;
1909d57c44d0SKevin Wolf     Error **errp = aiocb->truncate.errp;
191093f4e2ffSKevin Wolf 
191193f4e2ffSKevin Wolf     if (fstat(fd, &st) < 0) {
191293f4e2ffSKevin Wolf         result = -errno;
191393f4e2ffSKevin Wolf         error_setg_errno(errp, -result, "Could not stat file");
191493f4e2ffSKevin Wolf         return result;
191593f4e2ffSKevin Wolf     }
191693f4e2ffSKevin Wolf 
191793f4e2ffSKevin Wolf     current_length = st.st_size;
1918d57c44d0SKevin Wolf     if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
191993f4e2ffSKevin Wolf         error_setg(errp, "Cannot use preallocation for shrinking files");
192093f4e2ffSKevin Wolf         return -ENOTSUP;
192193f4e2ffSKevin Wolf     }
192293f4e2ffSKevin Wolf 
1923d57c44d0SKevin Wolf     switch (prealloc) {
192493f4e2ffSKevin Wolf #ifdef CONFIG_POSIX_FALLOCATE
192593f4e2ffSKevin Wolf     case PREALLOC_MODE_FALLOC:
192693f4e2ffSKevin Wolf         /*
192793f4e2ffSKevin Wolf          * Truncating before posix_fallocate() makes it about twice slower on
192893f4e2ffSKevin Wolf          * file systems that do not support fallocate(), trying to check if a
192993f4e2ffSKevin Wolf          * block is allocated before allocating it, so don't do that here.
193093f4e2ffSKevin Wolf          */
193193f4e2ffSKevin Wolf         if (offset != current_length) {
193293f4e2ffSKevin Wolf             result = -posix_fallocate(fd, current_length,
193393f4e2ffSKevin Wolf                                       offset - current_length);
193493f4e2ffSKevin Wolf             if (result != 0) {
193593f4e2ffSKevin Wolf                 /* posix_fallocate() doesn't set errno. */
193693f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
193793f4e2ffSKevin Wolf                                  "Could not preallocate new data");
19383a20013fSNir Soffer             } else if (current_length == 0) {
19393a20013fSNir Soffer                 /*
19403a20013fSNir Soffer                  * posix_fallocate() uses fallocate() if the filesystem
19413a20013fSNir Soffer                  * supports it, or fallback to manually writing zeroes. If
19423a20013fSNir Soffer                  * fallocate() was used, unaligned reads from the fallocated
19433a20013fSNir Soffer                  * area in raw_probe_alignment() will succeed, hence we need to
19443a20013fSNir Soffer                  * allocate the first block.
19453a20013fSNir Soffer                  *
19463a20013fSNir Soffer                  * Optimize future alignment probing; ignore failures.
19473a20013fSNir Soffer                  */
19483a20013fSNir Soffer                 allocate_first_block(fd, offset);
194993f4e2ffSKevin Wolf             }
195093f4e2ffSKevin Wolf         } else {
195193f4e2ffSKevin Wolf             result = 0;
195293f4e2ffSKevin Wolf         }
195393f4e2ffSKevin Wolf         goto out;
195493f4e2ffSKevin Wolf #endif
195593f4e2ffSKevin Wolf     case PREALLOC_MODE_FULL:
195693f4e2ffSKevin Wolf     {
195793f4e2ffSKevin Wolf         int64_t num = 0, left = offset - current_length;
195893f4e2ffSKevin Wolf         off_t seek_result;
195993f4e2ffSKevin Wolf 
196093f4e2ffSKevin Wolf         /*
196193f4e2ffSKevin Wolf          * Knowing the final size from the beginning could allow the file
196293f4e2ffSKevin Wolf          * system driver to do less allocations and possibly avoid
196393f4e2ffSKevin Wolf          * fragmentation of the file.
196493f4e2ffSKevin Wolf          */
196593f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
196693f4e2ffSKevin Wolf             result = -errno;
196793f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
196893f4e2ffSKevin Wolf             goto out;
196993f4e2ffSKevin Wolf         }
197093f4e2ffSKevin Wolf 
197193f4e2ffSKevin Wolf         buf = g_malloc0(65536);
197293f4e2ffSKevin Wolf 
197393f4e2ffSKevin Wolf         seek_result = lseek(fd, current_length, SEEK_SET);
197493f4e2ffSKevin Wolf         if (seek_result < 0) {
197593f4e2ffSKevin Wolf             result = -errno;
197693f4e2ffSKevin Wolf             error_setg_errno(errp, -result,
197793f4e2ffSKevin Wolf                              "Failed to seek to the old end of file");
197893f4e2ffSKevin Wolf             goto out;
197993f4e2ffSKevin Wolf         }
198093f4e2ffSKevin Wolf 
198193f4e2ffSKevin Wolf         while (left > 0) {
198293f4e2ffSKevin Wolf             num = MIN(left, 65536);
198393f4e2ffSKevin Wolf             result = write(fd, buf, num);
198493f4e2ffSKevin Wolf             if (result < 0) {
1985a1c81f4fSFam Zheng                 if (errno == EINTR) {
1986a1c81f4fSFam Zheng                     continue;
1987a1c81f4fSFam Zheng                 }
198893f4e2ffSKevin Wolf                 result = -errno;
198993f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
199093f4e2ffSKevin Wolf                                  "Could not write zeros for preallocation");
199193f4e2ffSKevin Wolf                 goto out;
199293f4e2ffSKevin Wolf             }
199393f4e2ffSKevin Wolf             left -= result;
199493f4e2ffSKevin Wolf         }
199593f4e2ffSKevin Wolf         if (result >= 0) {
199693f4e2ffSKevin Wolf             result = fsync(fd);
199793f4e2ffSKevin Wolf             if (result < 0) {
199893f4e2ffSKevin Wolf                 result = -errno;
199993f4e2ffSKevin Wolf                 error_setg_errno(errp, -result,
200093f4e2ffSKevin Wolf                                  "Could not flush file to disk");
200193f4e2ffSKevin Wolf                 goto out;
200293f4e2ffSKevin Wolf             }
200393f4e2ffSKevin Wolf         }
200493f4e2ffSKevin Wolf         goto out;
200593f4e2ffSKevin Wolf     }
200693f4e2ffSKevin Wolf     case PREALLOC_MODE_OFF:
200793f4e2ffSKevin Wolf         if (ftruncate(fd, offset) != 0) {
200893f4e2ffSKevin Wolf             result = -errno;
200993f4e2ffSKevin Wolf             error_setg_errno(errp, -result, "Could not resize file");
20103a20013fSNir Soffer         } else if (current_length == 0 && offset > current_length) {
20113a20013fSNir Soffer             /* Optimize future alignment probing; ignore failures. */
20123a20013fSNir Soffer             allocate_first_block(fd, offset);
201393f4e2ffSKevin Wolf         }
201493f4e2ffSKevin Wolf         return result;
201593f4e2ffSKevin Wolf     default:
201693f4e2ffSKevin Wolf         result = -ENOTSUP;
201793f4e2ffSKevin Wolf         error_setg(errp, "Unsupported preallocation mode: %s",
2018d57c44d0SKevin Wolf                    PreallocMode_str(prealloc));
201993f4e2ffSKevin Wolf         return result;
202093f4e2ffSKevin Wolf     }
202193f4e2ffSKevin Wolf 
202293f4e2ffSKevin Wolf out:
202393f4e2ffSKevin Wolf     if (result < 0) {
202493f4e2ffSKevin Wolf         if (ftruncate(fd, current_length) < 0) {
202593f4e2ffSKevin Wolf             error_report("Failed to restore old file length: %s",
202693f4e2ffSKevin Wolf                          strerror(errno));
202793f4e2ffSKevin Wolf         }
202893f4e2ffSKevin Wolf     }
202993f4e2ffSKevin Wolf 
203093f4e2ffSKevin Wolf     g_free(buf);
203193f4e2ffSKevin Wolf     return result;
203293f4e2ffSKevin Wolf }
203393f4e2ffSKevin Wolf 
20345d5de250SKevin Wolf static int coroutine_fn raw_thread_pool_submit(BlockDriverState *bs,
20355d5de250SKevin Wolf                                                ThreadPoolFunc func, void *arg)
20365d5de250SKevin Wolf {
20375d5de250SKevin Wolf     /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
20385d5de250SKevin Wolf     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
20395d5de250SKevin Wolf     return thread_pool_submit_co(pool, func, arg);
20405d5de250SKevin Wolf }
20415d5de250SKevin Wolf 
2042c1bb86cdSEric Blake static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
2043c1bb86cdSEric Blake                                    uint64_t bytes, QEMUIOVector *qiov, int type)
2044c1bb86cdSEric Blake {
2045c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2046999e6b69SKevin Wolf     RawPosixAIOData acb;
2047c1bb86cdSEric Blake 
2048c1bb86cdSEric Blake     if (fd_open(bs) < 0)
2049c1bb86cdSEric Blake         return -EIO;
2050c1bb86cdSEric Blake 
2051c1bb86cdSEric Blake     /*
2052c6447510SAarushi Mehta      * When using O_DIRECT, the request must be aligned to be able to use
2053c6447510SAarushi Mehta      * either libaio or io_uring interface. If not fail back to regular thread
2054c6447510SAarushi Mehta      * pool read/write code which emulates this for us if we
2055c6447510SAarushi Mehta      * set QEMU_AIO_MISALIGNED.
2056c1bb86cdSEric Blake      */
2057c6447510SAarushi Mehta     if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
2058c1bb86cdSEric Blake         type |= QEMU_AIO_MISALIGNED;
2059c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2060c6447510SAarushi Mehta     } else if (s->use_linux_io_uring) {
2061c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2062c6447510SAarushi Mehta         assert(qiov->size == bytes);
2063c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, offset, qiov, type);
2064c6447510SAarushi Mehta #endif
2065c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2066c1bb86cdSEric Blake     } else if (s->use_linux_aio) {
2067c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2068c1bb86cdSEric Blake         assert(qiov->size == bytes);
2069*512da211SStefano Garzarella         return laio_co_submit(bs, aio, s->fd, offset, qiov, type,
2070*512da211SStefano Garzarella                               s->aio_max_batch);
2071c1bb86cdSEric Blake #endif
2072c1bb86cdSEric Blake     }
2073c1bb86cdSEric Blake 
2074999e6b69SKevin Wolf     acb = (RawPosixAIOData) {
2075999e6b69SKevin Wolf         .bs             = bs,
2076999e6b69SKevin Wolf         .aio_fildes     = s->fd,
2077999e6b69SKevin Wolf         .aio_type       = type,
2078999e6b69SKevin Wolf         .aio_offset     = offset,
2079999e6b69SKevin Wolf         .aio_nbytes     = bytes,
2080999e6b69SKevin Wolf         .io             = {
2081999e6b69SKevin Wolf             .iov            = qiov->iov,
2082999e6b69SKevin Wolf             .niov           = qiov->niov,
2083999e6b69SKevin Wolf         },
2084999e6b69SKevin Wolf     };
2085999e6b69SKevin Wolf 
2086999e6b69SKevin Wolf     assert(qiov->size == bytes);
2087999e6b69SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_rw, &acb);
2088c1bb86cdSEric Blake }
2089c1bb86cdSEric Blake 
2090f7ef38ddSVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_preadv(BlockDriverState *bs, int64_t offset,
2091f7ef38ddSVladimir Sementsov-Ogievskiy                                       int64_t bytes, QEMUIOVector *qiov,
2092f7ef38ddSVladimir Sementsov-Ogievskiy                                       BdrvRequestFlags flags)
2093c1bb86cdSEric Blake {
2094c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
2095c1bb86cdSEric Blake }
2096c1bb86cdSEric Blake 
2097e75abedaSVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, int64_t offset,
2098e75abedaSVladimir Sementsov-Ogievskiy                                        int64_t bytes, QEMUIOVector *qiov,
2099e75abedaSVladimir Sementsov-Ogievskiy                                        BdrvRequestFlags flags)
2100c1bb86cdSEric Blake {
2101c1bb86cdSEric Blake     assert(flags == 0);
2102c1bb86cdSEric Blake     return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
2103c1bb86cdSEric Blake }
2104c1bb86cdSEric Blake 
2105c1bb86cdSEric Blake static void raw_aio_plug(BlockDriverState *bs)
2106c1bb86cdSEric Blake {
2107c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2108c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2109c1bb86cdSEric Blake     if (s->use_linux_aio) {
2110c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2111c1bb86cdSEric Blake         laio_io_plug(bs, aio);
2112c1bb86cdSEric Blake     }
2113c1bb86cdSEric Blake #endif
2114c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2115c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2116c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2117c6447510SAarushi Mehta         luring_io_plug(bs, aio);
2118c6447510SAarushi Mehta     }
2119c6447510SAarushi Mehta #endif
2120c1bb86cdSEric Blake }
2121c1bb86cdSEric Blake 
2122c1bb86cdSEric Blake static void raw_aio_unplug(BlockDriverState *bs)
2123c1bb86cdSEric Blake {
2124c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2125c1bb86cdSEric Blake #ifdef CONFIG_LINUX_AIO
2126c1bb86cdSEric Blake     if (s->use_linux_aio) {
2127c1bb86cdSEric Blake         LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
2128c1bb86cdSEric Blake         laio_io_unplug(bs, aio);
2129c1bb86cdSEric Blake     }
2130c1bb86cdSEric Blake #endif
2131c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2132c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2133c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2134c6447510SAarushi Mehta         luring_io_unplug(bs, aio);
2135c6447510SAarushi Mehta     }
2136c6447510SAarushi Mehta #endif
2137c1bb86cdSEric Blake }
2138c1bb86cdSEric Blake 
213933d70fb6SKevin Wolf static int raw_co_flush_to_disk(BlockDriverState *bs)
2140c1bb86cdSEric Blake {
2141c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
214206dc9bd5SKevin Wolf     RawPosixAIOData acb;
214333d70fb6SKevin Wolf     int ret;
2144c1bb86cdSEric Blake 
214533d70fb6SKevin Wolf     ret = fd_open(bs);
214633d70fb6SKevin Wolf     if (ret < 0) {
214733d70fb6SKevin Wolf         return ret;
214833d70fb6SKevin Wolf     }
2149c1bb86cdSEric Blake 
215006dc9bd5SKevin Wolf     acb = (RawPosixAIOData) {
215106dc9bd5SKevin Wolf         .bs             = bs,
215206dc9bd5SKevin Wolf         .aio_fildes     = s->fd,
215306dc9bd5SKevin Wolf         .aio_type       = QEMU_AIO_FLUSH,
215406dc9bd5SKevin Wolf     };
215506dc9bd5SKevin Wolf 
2156c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2157c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2158c6447510SAarushi Mehta         LuringState *aio = aio_get_linux_io_uring(bdrv_get_aio_context(bs));
2159c6447510SAarushi Mehta         return luring_co_submit(bs, aio, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2160c6447510SAarushi Mehta     }
2161c6447510SAarushi Mehta #endif
216206dc9bd5SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_flush, &acb);
2163c1bb86cdSEric Blake }
2164c1bb86cdSEric Blake 
2165ed6e2161SNishanth Aravamudan static void raw_aio_attach_aio_context(BlockDriverState *bs,
2166ed6e2161SNishanth Aravamudan                                        AioContext *new_context)
2167ed6e2161SNishanth Aravamudan {
2168c6447510SAarushi Mehta     BDRVRawState __attribute__((unused)) *s = bs->opaque;
2169ed6e2161SNishanth Aravamudan #ifdef CONFIG_LINUX_AIO
2170ed6e2161SNishanth Aravamudan     if (s->use_linux_aio) {
2171cb09104eSMarkus Armbruster         Error *local_err = NULL;
2172ed6e2161SNishanth Aravamudan         if (!aio_setup_linux_aio(new_context, &local_err)) {
2173ed6e2161SNishanth Aravamudan             error_reportf_err(local_err, "Unable to use native AIO, "
2174ed6e2161SNishanth Aravamudan                                          "falling back to thread pool: ");
2175ed6e2161SNishanth Aravamudan             s->use_linux_aio = false;
2176ed6e2161SNishanth Aravamudan         }
2177ed6e2161SNishanth Aravamudan     }
2178ed6e2161SNishanth Aravamudan #endif
2179c6447510SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
2180c6447510SAarushi Mehta     if (s->use_linux_io_uring) {
2181cb8d0851SPan Nengyuan         Error *local_err = NULL;
2182c6447510SAarushi Mehta         if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2183c6447510SAarushi Mehta             error_reportf_err(local_err, "Unable to use linux io_uring, "
2184c6447510SAarushi Mehta                                          "falling back to thread pool: ");
2185c6447510SAarushi Mehta             s->use_linux_io_uring = false;
2186c6447510SAarushi Mehta         }
2187c6447510SAarushi Mehta     }
2188c6447510SAarushi Mehta #endif
2189ed6e2161SNishanth Aravamudan }
2190ed6e2161SNishanth Aravamudan 
2191c1bb86cdSEric Blake static void raw_close(BlockDriverState *bs)
2192c1bb86cdSEric Blake {
2193c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2194c1bb86cdSEric Blake 
2195c1bb86cdSEric Blake     if (s->fd >= 0) {
2196c1bb86cdSEric Blake         qemu_close(s->fd);
2197c1bb86cdSEric Blake         s->fd = -1;
2198c1bb86cdSEric Blake     }
2199c1bb86cdSEric Blake }
2200c1bb86cdSEric Blake 
2201d0bc9e5dSMax Reitz /**
2202d0bc9e5dSMax Reitz  * Truncates the given regular file @fd to @offset and, when growing, fills the
2203d0bc9e5dSMax Reitz  * new space according to @prealloc.
2204d0bc9e5dSMax Reitz  *
2205d0bc9e5dSMax Reitz  * Returns: 0 on success, -errno on failure.
2206d0bc9e5dSMax Reitz  */
220793f4e2ffSKevin Wolf static int coroutine_fn
220893f4e2ffSKevin Wolf raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
220993f4e2ffSKevin Wolf                      PreallocMode prealloc, Error **errp)
22109f63b07eSMax Reitz {
221129cb4c01SKevin Wolf     RawPosixAIOData acb;
2212d0bc9e5dSMax Reitz 
221329cb4c01SKevin Wolf     acb = (RawPosixAIOData) {
221493f4e2ffSKevin Wolf         .bs             = bs,
221593f4e2ffSKevin Wolf         .aio_fildes     = fd,
221693f4e2ffSKevin Wolf         .aio_type       = QEMU_AIO_TRUNCATE,
221793f4e2ffSKevin Wolf         .aio_offset     = offset,
2218d57c44d0SKevin Wolf         .truncate       = {
221993f4e2ffSKevin Wolf             .prealloc       = prealloc,
222093f4e2ffSKevin Wolf             .errp           = errp,
2221d57c44d0SKevin Wolf         },
222293f4e2ffSKevin Wolf     };
2223d0bc9e5dSMax Reitz 
222429cb4c01SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_truncate, &acb);
22259f63b07eSMax Reitz }
22269f63b07eSMax Reitz 
2227061ca8a3SKevin Wolf static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2228c80d8b06SMax Reitz                                         bool exact, PreallocMode prealloc,
222992b92799SKevin Wolf                                         BdrvRequestFlags flags, Error **errp)
2230c1bb86cdSEric Blake {
2231c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2232c1bb86cdSEric Blake     struct stat st;
2233f59adb32SMax Reitz     int ret;
2234c1bb86cdSEric Blake 
2235c1bb86cdSEric Blake     if (fstat(s->fd, &st)) {
2236f59adb32SMax Reitz         ret = -errno;
2237f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to fstat() the file");
2238f59adb32SMax Reitz         return ret;
2239c1bb86cdSEric Blake     }
2240c1bb86cdSEric Blake 
2241c1bb86cdSEric Blake     if (S_ISREG(st.st_mode)) {
224282325ae5SMax Reitz         /* Always resizes to the exact @offset */
224393f4e2ffSKevin Wolf         return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2244c1bb86cdSEric Blake     }
224535d72602SMax Reitz 
224635d72602SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
224735d72602SMax Reitz         error_setg(errp, "Preallocation mode '%s' unsupported for this "
2248977c736fSMarkus Armbruster                    "non-regular file", PreallocMode_str(prealloc));
224935d72602SMax Reitz         return -ENOTSUP;
225035d72602SMax Reitz     }
225135d72602SMax Reitz 
225235d72602SMax Reitz     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
225382325ae5SMax Reitz         int64_t cur_length = raw_getlength(bs);
225482325ae5SMax Reitz 
225582325ae5SMax Reitz         if (offset != cur_length && exact) {
225682325ae5SMax Reitz             error_setg(errp, "Cannot resize device files");
225782325ae5SMax Reitz             return -ENOTSUP;
225882325ae5SMax Reitz         } else if (offset > cur_length) {
2259f59adb32SMax Reitz             error_setg(errp, "Cannot grow device files");
2260c1bb86cdSEric Blake             return -EINVAL;
2261c1bb86cdSEric Blake         }
2262c1bb86cdSEric Blake     } else {
2263f59adb32SMax Reitz         error_setg(errp, "Resizing this file is not supported");
2264c1bb86cdSEric Blake         return -ENOTSUP;
2265c1bb86cdSEric Blake     }
2266c1bb86cdSEric Blake 
2267c1bb86cdSEric Blake     return 0;
2268c1bb86cdSEric Blake }
2269c1bb86cdSEric Blake 
2270c1bb86cdSEric Blake #ifdef __OpenBSD__
2271c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2272c1bb86cdSEric Blake {
2273c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2274c1bb86cdSEric Blake     int fd = s->fd;
2275c1bb86cdSEric Blake     struct stat st;
2276c1bb86cdSEric Blake 
2277c1bb86cdSEric Blake     if (fstat(fd, &st))
2278c1bb86cdSEric Blake         return -errno;
2279c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2280c1bb86cdSEric Blake         struct disklabel dl;
2281c1bb86cdSEric Blake 
2282c1bb86cdSEric Blake         if (ioctl(fd, DIOCGDINFO, &dl))
2283c1bb86cdSEric Blake             return -errno;
2284c1bb86cdSEric Blake         return (uint64_t)dl.d_secsize *
2285c1bb86cdSEric Blake             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2286c1bb86cdSEric Blake     } else
2287c1bb86cdSEric Blake         return st.st_size;
2288c1bb86cdSEric Blake }
2289c1bb86cdSEric Blake #elif defined(__NetBSD__)
2290c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2291c1bb86cdSEric Blake {
2292c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2293c1bb86cdSEric Blake     int fd = s->fd;
2294c1bb86cdSEric Blake     struct stat st;
2295c1bb86cdSEric Blake 
2296c1bb86cdSEric Blake     if (fstat(fd, &st))
2297c1bb86cdSEric Blake         return -errno;
2298c1bb86cdSEric Blake     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2299c1bb86cdSEric Blake         struct dkwedge_info dkw;
2300c1bb86cdSEric Blake 
2301c1bb86cdSEric Blake         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2302c1bb86cdSEric Blake             return dkw.dkw_size * 512;
2303c1bb86cdSEric Blake         } else {
2304c1bb86cdSEric Blake             struct disklabel dl;
2305c1bb86cdSEric Blake 
2306c1bb86cdSEric Blake             if (ioctl(fd, DIOCGDINFO, &dl))
2307c1bb86cdSEric Blake                 return -errno;
2308c1bb86cdSEric Blake             return (uint64_t)dl.d_secsize *
2309c1bb86cdSEric Blake                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2310c1bb86cdSEric Blake         }
2311c1bb86cdSEric Blake     } else
2312c1bb86cdSEric Blake         return st.st_size;
2313c1bb86cdSEric Blake }
2314c1bb86cdSEric Blake #elif defined(__sun__)
2315c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2316c1bb86cdSEric Blake {
2317c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2318c1bb86cdSEric Blake     struct dk_minfo minfo;
2319c1bb86cdSEric Blake     int ret;
2320c1bb86cdSEric Blake     int64_t size;
2321c1bb86cdSEric Blake 
2322c1bb86cdSEric Blake     ret = fd_open(bs);
2323c1bb86cdSEric Blake     if (ret < 0) {
2324c1bb86cdSEric Blake         return ret;
2325c1bb86cdSEric Blake     }
2326c1bb86cdSEric Blake 
2327c1bb86cdSEric Blake     /*
2328c1bb86cdSEric Blake      * Use the DKIOCGMEDIAINFO ioctl to read the size.
2329c1bb86cdSEric Blake      */
2330c1bb86cdSEric Blake     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2331c1bb86cdSEric Blake     if (ret != -1) {
2332c1bb86cdSEric Blake         return minfo.dki_lbsize * minfo.dki_capacity;
2333c1bb86cdSEric Blake     }
2334c1bb86cdSEric Blake 
2335c1bb86cdSEric Blake     /*
2336c1bb86cdSEric Blake      * There are reports that lseek on some devices fails, but
2337c1bb86cdSEric Blake      * irc discussion said that contingency on contingency was overkill.
2338c1bb86cdSEric Blake      */
2339c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2340c1bb86cdSEric Blake     if (size < 0) {
2341c1bb86cdSEric Blake         return -errno;
2342c1bb86cdSEric Blake     }
2343c1bb86cdSEric Blake     return size;
2344c1bb86cdSEric Blake }
2345c1bb86cdSEric Blake #elif defined(CONFIG_BSD)
2346c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2347c1bb86cdSEric Blake {
2348c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2349c1bb86cdSEric Blake     int fd = s->fd;
2350c1bb86cdSEric Blake     int64_t size;
2351c1bb86cdSEric Blake     struct stat sb;
2352c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2353c1bb86cdSEric Blake     int reopened = 0;
2354c1bb86cdSEric Blake #endif
2355c1bb86cdSEric Blake     int ret;
2356c1bb86cdSEric Blake 
2357c1bb86cdSEric Blake     ret = fd_open(bs);
2358c1bb86cdSEric Blake     if (ret < 0)
2359c1bb86cdSEric Blake         return ret;
2360c1bb86cdSEric Blake 
2361c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2362c1bb86cdSEric Blake again:
2363c1bb86cdSEric Blake #endif
2364c1bb86cdSEric Blake     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2365267cd53fSPaolo Bonzini         size = 0;
2366c1bb86cdSEric Blake #ifdef DIOCGMEDIASIZE
2367267cd53fSPaolo Bonzini         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size)) {
2368c1bb86cdSEric Blake             size = 0;
2369c1bb86cdSEric Blake         }
2370267cd53fSPaolo Bonzini #endif
2371267cd53fSPaolo Bonzini #ifdef DIOCGPART
2372267cd53fSPaolo Bonzini         if (size == 0) {
2373267cd53fSPaolo Bonzini             struct partinfo pi;
2374267cd53fSPaolo Bonzini             if (ioctl(fd, DIOCGPART, &pi) == 0) {
2375267cd53fSPaolo Bonzini                 size = pi.media_size;
2376267cd53fSPaolo Bonzini             }
2377267cd53fSPaolo Bonzini         }
2378c1bb86cdSEric Blake #endif
237909e20abdSJoelle van Dyne #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2380267cd53fSPaolo Bonzini         if (size == 0) {
2381c1bb86cdSEric Blake             uint64_t sectors = 0;
2382c1bb86cdSEric Blake             uint32_t sector_size = 0;
2383c1bb86cdSEric Blake 
2384c1bb86cdSEric Blake             if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2385c1bb86cdSEric Blake                && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2386c1bb86cdSEric Blake                 size = sectors * sector_size;
2387c1bb86cdSEric Blake             }
2388c1bb86cdSEric Blake         }
2389c1bb86cdSEric Blake #endif
2390267cd53fSPaolo Bonzini         if (size == 0) {
2391267cd53fSPaolo Bonzini             size = lseek(fd, 0LL, SEEK_END);
2392267cd53fSPaolo Bonzini         }
2393267cd53fSPaolo Bonzini         if (size < 0) {
2394267cd53fSPaolo Bonzini             return -errno;
2395267cd53fSPaolo Bonzini         }
2396c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2397c1bb86cdSEric Blake         switch(s->type) {
2398c1bb86cdSEric Blake         case FTYPE_CD:
2399c1bb86cdSEric Blake             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2400c1bb86cdSEric Blake             if (size == 2048LL * (unsigned)-1)
2401c1bb86cdSEric Blake                 size = 0;
2402c1bb86cdSEric Blake             /* XXX no disc?  maybe we need to reopen... */
2403c1bb86cdSEric Blake             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2404c1bb86cdSEric Blake                 reopened = 1;
2405c1bb86cdSEric Blake                 goto again;
2406c1bb86cdSEric Blake             }
2407c1bb86cdSEric Blake         }
2408c1bb86cdSEric Blake #endif
2409c1bb86cdSEric Blake     } else {
2410c1bb86cdSEric Blake         size = lseek(fd, 0, SEEK_END);
2411c1bb86cdSEric Blake         if (size < 0) {
2412c1bb86cdSEric Blake             return -errno;
2413c1bb86cdSEric Blake         }
2414c1bb86cdSEric Blake     }
2415c1bb86cdSEric Blake     return size;
2416c1bb86cdSEric Blake }
2417c1bb86cdSEric Blake #else
2418c1bb86cdSEric Blake static int64_t raw_getlength(BlockDriverState *bs)
2419c1bb86cdSEric Blake {
2420c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2421c1bb86cdSEric Blake     int ret;
2422c1bb86cdSEric Blake     int64_t size;
2423c1bb86cdSEric Blake 
2424c1bb86cdSEric Blake     ret = fd_open(bs);
2425c1bb86cdSEric Blake     if (ret < 0) {
2426c1bb86cdSEric Blake         return ret;
2427c1bb86cdSEric Blake     }
2428c1bb86cdSEric Blake 
2429c1bb86cdSEric Blake     size = lseek(s->fd, 0, SEEK_END);
2430c1bb86cdSEric Blake     if (size < 0) {
2431c1bb86cdSEric Blake         return -errno;
2432c1bb86cdSEric Blake     }
2433c1bb86cdSEric Blake     return size;
2434c1bb86cdSEric Blake }
2435c1bb86cdSEric Blake #endif
2436c1bb86cdSEric Blake 
2437c1bb86cdSEric Blake static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
2438c1bb86cdSEric Blake {
2439c1bb86cdSEric Blake     struct stat st;
2440c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2441c1bb86cdSEric Blake 
2442c1bb86cdSEric Blake     if (fstat(s->fd, &st) < 0) {
2443c1bb86cdSEric Blake         return -errno;
2444c1bb86cdSEric Blake     }
2445c1bb86cdSEric Blake     return (int64_t)st.st_blocks * 512;
2446c1bb86cdSEric Blake }
2447c1bb86cdSEric Blake 
244893f4e2ffSKevin Wolf static int coroutine_fn
244993f4e2ffSKevin Wolf raw_co_create(BlockdevCreateOptions *options, Error **errp)
2450c1bb86cdSEric Blake {
2451927f11e1SKevin Wolf     BlockdevCreateOptionsFile *file_opts;
24527c20c808SMax Reitz     Error *local_err = NULL;
2453c1bb86cdSEric Blake     int fd;
2454d815efcaSMax Reitz     uint64_t perm, shared;
2455c1bb86cdSEric Blake     int result = 0;
2456c1bb86cdSEric Blake 
2457927f11e1SKevin Wolf     /* Validate options and set default values */
2458927f11e1SKevin Wolf     assert(options->driver == BLOCKDEV_DRIVER_FILE);
2459927f11e1SKevin Wolf     file_opts = &options->u.file;
2460c1bb86cdSEric Blake 
2461927f11e1SKevin Wolf     if (!file_opts->has_nocow) {
2462927f11e1SKevin Wolf         file_opts->nocow = false;
2463927f11e1SKevin Wolf     }
2464927f11e1SKevin Wolf     if (!file_opts->has_preallocation) {
2465927f11e1SKevin Wolf         file_opts->preallocation = PREALLOC_MODE_OFF;
2466c1bb86cdSEric Blake     }
2467ffa244c8SKevin Wolf     if (!file_opts->has_extent_size_hint) {
2468ffa244c8SKevin Wolf         file_opts->extent_size_hint = 1 * MiB;
2469ffa244c8SKevin Wolf     }
2470ffa244c8SKevin Wolf     if (file_opts->extent_size_hint > UINT32_MAX) {
2471ffa244c8SKevin Wolf         result = -EINVAL;
2472ffa244c8SKevin Wolf         error_setg(errp, "Extent size hint is too large");
2473ffa244c8SKevin Wolf         goto out;
2474ffa244c8SKevin Wolf     }
2475c1bb86cdSEric Blake 
2476927f11e1SKevin Wolf     /* Create file */
2477b18a24a9SDaniel P. Berrangé     fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
2478c1bb86cdSEric Blake     if (fd < 0) {
2479c1bb86cdSEric Blake         result = -errno;
2480c1bb86cdSEric Blake         goto out;
2481c1bb86cdSEric Blake     }
2482c1bb86cdSEric Blake 
2483b8cf1913SMax Reitz     /* Take permissions: We want to discard everything, so we need
2484b8cf1913SMax Reitz      * BLK_PERM_WRITE; and truncation to the desired size requires
2485b8cf1913SMax Reitz      * BLK_PERM_RESIZE.
2486b8cf1913SMax Reitz      * On the other hand, we cannot share the RESIZE permission
2487b8cf1913SMax Reitz      * because we promise that after this function, the file has the
2488b8cf1913SMax Reitz      * size given in the options.  If someone else were to resize it
2489b8cf1913SMax Reitz      * concurrently, we could not guarantee that.
2490b8cf1913SMax Reitz      * Note that after this function, we can no longer guarantee that
2491b8cf1913SMax Reitz      * the file is not touched by a third party, so it may be resized
2492b8cf1913SMax Reitz      * then. */
2493b8cf1913SMax Reitz     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2494b8cf1913SMax Reitz     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2495b8cf1913SMax Reitz 
2496b8cf1913SMax Reitz     /* Step one: Take locks */
24972996ffadSFam Zheng     result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2498b8cf1913SMax Reitz     if (result < 0) {
2499b8cf1913SMax Reitz         goto out_close;
2500b8cf1913SMax Reitz     }
2501b8cf1913SMax Reitz 
2502b8cf1913SMax Reitz     /* Step two: Check that nobody else has taken conflicting locks */
2503b8cf1913SMax Reitz     result = raw_check_lock_bytes(fd, perm, shared, errp);
2504b8cf1913SMax Reitz     if (result < 0) {
2505b857431dSFam Zheng         error_append_hint(errp,
2506b857431dSFam Zheng                           "Is another process using the image [%s]?\n",
2507b857431dSFam Zheng                           file_opts->filename);
25087c20c808SMax Reitz         goto out_unlock;
2509b8cf1913SMax Reitz     }
2510b8cf1913SMax Reitz 
2511b8cf1913SMax Reitz     /* Clear the file by truncating it to 0 */
251293f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2513b8cf1913SMax Reitz     if (result < 0) {
25147c20c808SMax Reitz         goto out_unlock;
2515b8cf1913SMax Reitz     }
2516b8cf1913SMax Reitz 
2517927f11e1SKevin Wolf     if (file_opts->nocow) {
2518c1bb86cdSEric Blake #ifdef __linux__
2519c1bb86cdSEric Blake         /* Set NOCOW flag to solve performance issue on fs like btrfs.
2520c1bb86cdSEric Blake          * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2521c1bb86cdSEric Blake          * will be ignored since any failure of this operation should not
2522c1bb86cdSEric Blake          * block the left work.
2523c1bb86cdSEric Blake          */
2524c1bb86cdSEric Blake         int attr;
2525c1bb86cdSEric Blake         if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2526c1bb86cdSEric Blake             attr |= FS_NOCOW_FL;
2527c1bb86cdSEric Blake             ioctl(fd, FS_IOC_SETFLAGS, &attr);
2528c1bb86cdSEric Blake         }
2529c1bb86cdSEric Blake #endif
2530c1bb86cdSEric Blake     }
2531ffa244c8SKevin Wolf #ifdef FS_IOC_FSSETXATTR
2532ffa244c8SKevin Wolf     /*
2533ffa244c8SKevin Wolf      * Try to set the extent size hint. Failure is not fatal, and a warning is
2534ffa244c8SKevin Wolf      * only printed if the option was explicitly specified.
2535ffa244c8SKevin Wolf      */
2536ffa244c8SKevin Wolf     {
2537ffa244c8SKevin Wolf         struct fsxattr attr;
2538ffa244c8SKevin Wolf         result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2539ffa244c8SKevin Wolf         if (result == 0) {
2540ffa244c8SKevin Wolf             attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2541ffa244c8SKevin Wolf             attr.fsx_extsize = file_opts->extent_size_hint;
2542ffa244c8SKevin Wolf             result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2543ffa244c8SKevin Wolf         }
2544ffa244c8SKevin Wolf         if (result < 0 && file_opts->has_extent_size_hint &&
2545ffa244c8SKevin Wolf             file_opts->extent_size_hint)
2546ffa244c8SKevin Wolf         {
2547ffa244c8SKevin Wolf             warn_report("Failed to set extent size hint: %s",
2548ffa244c8SKevin Wolf                         strerror(errno));
2549ffa244c8SKevin Wolf         }
2550ffa244c8SKevin Wolf     }
2551ffa244c8SKevin Wolf #endif
2552c1bb86cdSEric Blake 
2553b8cf1913SMax Reitz     /* Resize and potentially preallocate the file to the desired
2554b8cf1913SMax Reitz      * final size */
255593f4e2ffSKevin Wolf     result = raw_regular_truncate(NULL, fd, file_opts->size,
255693f4e2ffSKevin Wolf                                   file_opts->preallocation, errp);
25579f63b07eSMax Reitz     if (result < 0) {
25587c20c808SMax Reitz         goto out_unlock;
25597c20c808SMax Reitz     }
25607c20c808SMax Reitz 
25617c20c808SMax Reitz out_unlock:
25622996ffadSFam Zheng     raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
25637c20c808SMax Reitz     if (local_err) {
25647c20c808SMax Reitz         /* The above call should not fail, and if it does, that does
25657c20c808SMax Reitz          * not mean the whole creation operation has failed.  So
25667c20c808SMax Reitz          * report it the user for their convenience, but do not report
25677c20c808SMax Reitz          * it to the caller. */
2568db0754dfSFam Zheng         warn_report_err(local_err);
25695a1dad9dSNir Soffer     }
25705a1dad9dSNir Soffer 
25715a1dad9dSNir Soffer out_close:
2572c1bb86cdSEric Blake     if (qemu_close(fd) != 0 && result == 0) {
2573c1bb86cdSEric Blake         result = -errno;
2574c1bb86cdSEric Blake         error_setg_errno(errp, -result, "Could not close the new file");
2575c1bb86cdSEric Blake     }
2576c1bb86cdSEric Blake out:
2577c1bb86cdSEric Blake     return result;
2578c1bb86cdSEric Blake }
2579c1bb86cdSEric Blake 
2580b92902dfSMaxim Levitsky static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
2581b92902dfSMaxim Levitsky                                            const char *filename,
2582b92902dfSMaxim Levitsky                                            QemuOpts *opts,
2583927f11e1SKevin Wolf                                            Error **errp)
2584927f11e1SKevin Wolf {
2585927f11e1SKevin Wolf     BlockdevCreateOptions options;
2586927f11e1SKevin Wolf     int64_t total_size = 0;
2587ffa244c8SKevin Wolf     int64_t extent_size_hint = 0;
2588ffa244c8SKevin Wolf     bool has_extent_size_hint = false;
2589927f11e1SKevin Wolf     bool nocow = false;
2590927f11e1SKevin Wolf     PreallocMode prealloc;
2591927f11e1SKevin Wolf     char *buf = NULL;
2592927f11e1SKevin Wolf     Error *local_err = NULL;
2593927f11e1SKevin Wolf 
2594927f11e1SKevin Wolf     /* Skip file: protocol prefix */
2595927f11e1SKevin Wolf     strstart(filename, "file:", &filename);
2596927f11e1SKevin Wolf 
2597927f11e1SKevin Wolf     /* Read out options */
2598927f11e1SKevin Wolf     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2599927f11e1SKevin Wolf                           BDRV_SECTOR_SIZE);
2600ffa244c8SKevin Wolf     if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
2601ffa244c8SKevin Wolf         has_extent_size_hint = true;
2602ffa244c8SKevin Wolf         extent_size_hint =
2603ffa244c8SKevin Wolf             qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
2604ffa244c8SKevin Wolf     }
2605927f11e1SKevin Wolf     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2606927f11e1SKevin Wolf     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2607927f11e1SKevin Wolf     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2608927f11e1SKevin Wolf                                PREALLOC_MODE_OFF, &local_err);
2609927f11e1SKevin Wolf     g_free(buf);
2610927f11e1SKevin Wolf     if (local_err) {
2611927f11e1SKevin Wolf         error_propagate(errp, local_err);
2612927f11e1SKevin Wolf         return -EINVAL;
2613927f11e1SKevin Wolf     }
2614927f11e1SKevin Wolf 
2615927f11e1SKevin Wolf     options = (BlockdevCreateOptions) {
2616927f11e1SKevin Wolf         .driver     = BLOCKDEV_DRIVER_FILE,
2617927f11e1SKevin Wolf         .u.file     = {
2618927f11e1SKevin Wolf             .filename           = (char *) filename,
2619927f11e1SKevin Wolf             .size               = total_size,
2620927f11e1SKevin Wolf             .has_preallocation  = true,
2621927f11e1SKevin Wolf             .preallocation      = prealloc,
2622927f11e1SKevin Wolf             .has_nocow          = true,
2623927f11e1SKevin Wolf             .nocow              = nocow,
2624ffa244c8SKevin Wolf             .has_extent_size_hint = has_extent_size_hint,
2625ffa244c8SKevin Wolf             .extent_size_hint   = extent_size_hint,
2626927f11e1SKevin Wolf         },
2627927f11e1SKevin Wolf     };
2628927f11e1SKevin Wolf     return raw_co_create(&options, errp);
2629927f11e1SKevin Wolf }
2630927f11e1SKevin Wolf 
26319bffae14SDaniel Henrique Barboza static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
26329bffae14SDaniel Henrique Barboza                                            Error **errp)
26339bffae14SDaniel Henrique Barboza {
26349bffae14SDaniel Henrique Barboza     struct stat st;
26359bffae14SDaniel Henrique Barboza     int ret;
26369bffae14SDaniel Henrique Barboza 
26379bffae14SDaniel Henrique Barboza     if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
26389bffae14SDaniel Henrique Barboza         error_setg_errno(errp, ENOENT, "%s is not a regular file",
26399bffae14SDaniel Henrique Barboza                          bs->filename);
26409bffae14SDaniel Henrique Barboza         return -ENOENT;
26419bffae14SDaniel Henrique Barboza     }
26429bffae14SDaniel Henrique Barboza 
26439bffae14SDaniel Henrique Barboza     ret = unlink(bs->filename);
26449bffae14SDaniel Henrique Barboza     if (ret < 0) {
26459bffae14SDaniel Henrique Barboza         ret = -errno;
26469bffae14SDaniel Henrique Barboza         error_setg_errno(errp, -ret, "Error when deleting file %s",
26479bffae14SDaniel Henrique Barboza                          bs->filename);
26489bffae14SDaniel Henrique Barboza     }
26499bffae14SDaniel Henrique Barboza 
26509bffae14SDaniel Henrique Barboza     return ret;
26519bffae14SDaniel Henrique Barboza }
26529bffae14SDaniel Henrique Barboza 
2653c1bb86cdSEric Blake /*
2654c1bb86cdSEric Blake  * Find allocation range in @bs around offset @start.
2655c1bb86cdSEric Blake  * May change underlying file descriptor's file offset.
2656c1bb86cdSEric Blake  * If @start is not in a hole, store @start in @data, and the
2657c1bb86cdSEric Blake  * beginning of the next hole in @hole, and return 0.
2658c1bb86cdSEric Blake  * If @start is in a non-trailing hole, store @start in @hole and the
2659c1bb86cdSEric Blake  * beginning of the next non-hole in @data, and return 0.
2660c1bb86cdSEric Blake  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2661c1bb86cdSEric Blake  * If we can't find out, return a negative errno other than -ENXIO.
2662c1bb86cdSEric Blake  */
2663c1bb86cdSEric Blake static int find_allocation(BlockDriverState *bs, off_t start,
2664c1bb86cdSEric Blake                            off_t *data, off_t *hole)
2665c1bb86cdSEric Blake {
2666c1bb86cdSEric Blake #if defined SEEK_HOLE && defined SEEK_DATA
2667c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
2668c1bb86cdSEric Blake     off_t offs;
2669c1bb86cdSEric Blake 
2670c1bb86cdSEric Blake     /*
2671c1bb86cdSEric Blake      * SEEK_DATA cases:
2672c1bb86cdSEric Blake      * D1. offs == start: start is in data
2673c1bb86cdSEric Blake      * D2. offs > start: start is in a hole, next data at offs
2674c1bb86cdSEric Blake      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2675c1bb86cdSEric Blake      *                              or start is beyond EOF
2676c1bb86cdSEric Blake      *     If the latter happens, the file has been truncated behind
2677c1bb86cdSEric Blake      *     our back since we opened it.  All bets are off then.
2678c1bb86cdSEric Blake      *     Treating like a trailing hole is simplest.
2679c1bb86cdSEric Blake      * D4. offs < 0, errno != ENXIO: we learned nothing
2680c1bb86cdSEric Blake      */
2681c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_DATA);
2682c1bb86cdSEric Blake     if (offs < 0) {
2683c1bb86cdSEric Blake         return -errno;          /* D3 or D4 */
2684c1bb86cdSEric Blake     }
2685a03083a0SJeff Cody 
2686a03083a0SJeff Cody     if (offs < start) {
2687a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2688a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like D4. */
2689a03083a0SJeff Cody         return -EIO;
2690a03083a0SJeff Cody     }
2691c1bb86cdSEric Blake 
2692c1bb86cdSEric Blake     if (offs > start) {
2693c1bb86cdSEric Blake         /* D2: in hole, next data at offs */
2694c1bb86cdSEric Blake         *hole = start;
2695c1bb86cdSEric Blake         *data = offs;
2696c1bb86cdSEric Blake         return 0;
2697c1bb86cdSEric Blake     }
2698c1bb86cdSEric Blake 
2699c1bb86cdSEric Blake     /* D1: in data, end not yet known */
2700c1bb86cdSEric Blake 
2701c1bb86cdSEric Blake     /*
2702c1bb86cdSEric Blake      * SEEK_HOLE cases:
2703c1bb86cdSEric Blake      * H1. offs == start: start is in a hole
2704c1bb86cdSEric Blake      *     If this happens here, a hole has been dug behind our back
2705c1bb86cdSEric Blake      *     since the previous lseek().
2706c1bb86cdSEric Blake      * H2. offs > start: either start is in data, next hole at offs,
2707c1bb86cdSEric Blake      *                   or start is in trailing hole, EOF at offs
2708c1bb86cdSEric Blake      *     Linux treats trailing holes like any other hole: offs ==
2709c1bb86cdSEric Blake      *     start.  Solaris seeks to EOF instead: offs > start (blech).
2710c1bb86cdSEric Blake      *     If that happens here, a hole has been dug behind our back
2711c1bb86cdSEric Blake      *     since the previous lseek().
2712c1bb86cdSEric Blake      * H3. offs < 0, errno = ENXIO: start is beyond EOF
2713c1bb86cdSEric Blake      *     If this happens, the file has been truncated behind our
2714c1bb86cdSEric Blake      *     back since we opened it.  Treat it like a trailing hole.
2715c1bb86cdSEric Blake      * H4. offs < 0, errno != ENXIO: we learned nothing
2716c1bb86cdSEric Blake      *     Pretend we know nothing at all, i.e. "forget" about D1.
2717c1bb86cdSEric Blake      */
2718c1bb86cdSEric Blake     offs = lseek(s->fd, start, SEEK_HOLE);
2719c1bb86cdSEric Blake     if (offs < 0) {
2720c1bb86cdSEric Blake         return -errno;          /* D1 and (H3 or H4) */
2721c1bb86cdSEric Blake     }
2722a03083a0SJeff Cody 
2723a03083a0SJeff Cody     if (offs < start) {
2724a03083a0SJeff Cody         /* This is not a valid return by lseek().  We are safe to just return
2725a03083a0SJeff Cody          * -EIO in this case, and we'll treat it like H4. */
2726a03083a0SJeff Cody         return -EIO;
2727a03083a0SJeff Cody     }
2728c1bb86cdSEric Blake 
2729c1bb86cdSEric Blake     if (offs > start) {
2730c1bb86cdSEric Blake         /*
2731c1bb86cdSEric Blake          * D1 and H2: either in data, next hole at offs, or it was in
2732c1bb86cdSEric Blake          * data but is now in a trailing hole.  In the latter case,
2733c1bb86cdSEric Blake          * all bets are off.  Treating it as if it there was data all
2734c1bb86cdSEric Blake          * the way to EOF is safe, so simply do that.
2735c1bb86cdSEric Blake          */
2736c1bb86cdSEric Blake         *data = start;
2737c1bb86cdSEric Blake         *hole = offs;
2738c1bb86cdSEric Blake         return 0;
2739c1bb86cdSEric Blake     }
2740c1bb86cdSEric Blake 
2741c1bb86cdSEric Blake     /* D1 and H1 */
2742c1bb86cdSEric Blake     return -EBUSY;
2743c1bb86cdSEric Blake #else
2744c1bb86cdSEric Blake     return -ENOTSUP;
2745c1bb86cdSEric Blake #endif
2746c1bb86cdSEric Blake }
2747c1bb86cdSEric Blake 
2748c1bb86cdSEric Blake /*
2749a290f085SEric Blake  * Returns the allocation status of the specified offset.
2750c1bb86cdSEric Blake  *
2751a290f085SEric Blake  * The block layer guarantees 'offset' and 'bytes' are within bounds.
2752c1bb86cdSEric Blake  *
2753a290f085SEric Blake  * 'pnum' is set to the number of bytes (including and immediately following
2754a290f085SEric Blake  * the specified offset) that are known to be in the same
2755c1bb86cdSEric Blake  * allocated/unallocated state.
2756c1bb86cdSEric Blake  *
2757869e7ee8SHanna Reitz  * 'bytes' is a soft cap for 'pnum'.  If the information is free, 'pnum' may
2758869e7ee8SHanna Reitz  * well exceed it.
2759c1bb86cdSEric Blake  */
2760a290f085SEric Blake static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2761a290f085SEric Blake                                             bool want_zero,
2762a290f085SEric Blake                                             int64_t offset,
2763a290f085SEric Blake                                             int64_t bytes, int64_t *pnum,
2764a290f085SEric Blake                                             int64_t *map,
2765c1bb86cdSEric Blake                                             BlockDriverState **file)
2766c1bb86cdSEric Blake {
2767a290f085SEric Blake     off_t data = 0, hole = 0;
2768c1bb86cdSEric Blake     int ret;
2769c1bb86cdSEric Blake 
27709c3db310SMax Reitz     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
27719c3db310SMax Reitz 
2772c1bb86cdSEric Blake     ret = fd_open(bs);
2773c1bb86cdSEric Blake     if (ret < 0) {
2774c1bb86cdSEric Blake         return ret;
2775c1bb86cdSEric Blake     }
2776c1bb86cdSEric Blake 
2777a290f085SEric Blake     if (!want_zero) {
2778a290f085SEric Blake         *pnum = bytes;
2779a290f085SEric Blake         *map = offset;
2780a290f085SEric Blake         *file = bs;
2781a290f085SEric Blake         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2782c1bb86cdSEric Blake     }
2783c1bb86cdSEric Blake 
2784a290f085SEric Blake     ret = find_allocation(bs, offset, &data, &hole);
2785c1bb86cdSEric Blake     if (ret == -ENXIO) {
2786c1bb86cdSEric Blake         /* Trailing hole */
2787a290f085SEric Blake         *pnum = bytes;
2788c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2789c1bb86cdSEric Blake     } else if (ret < 0) {
2790c1bb86cdSEric Blake         /* No info available, so pretend there are no holes */
2791a290f085SEric Blake         *pnum = bytes;
2792c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2793a290f085SEric Blake     } else if (data == offset) {
2794a290f085SEric Blake         /* On a data extent, compute bytes to the end of the extent,
2795c1bb86cdSEric Blake          * possibly including a partial sector at EOF. */
2796869e7ee8SHanna Reitz         *pnum = hole - offset;
27979c3db310SMax Reitz 
27989c3db310SMax Reitz         /*
27999c3db310SMax Reitz          * We are not allowed to return partial sectors, though, so
28009c3db310SMax Reitz          * round up if necessary.
28019c3db310SMax Reitz          */
28029c3db310SMax Reitz         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
28039c3db310SMax Reitz             int64_t file_length = raw_getlength(bs);
28049c3db310SMax Reitz             if (file_length > 0) {
28059c3db310SMax Reitz                 /* Ignore errors, this is just a safeguard */
28069c3db310SMax Reitz                 assert(hole == file_length);
28079c3db310SMax Reitz             }
28089c3db310SMax Reitz             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
28099c3db310SMax Reitz         }
28109c3db310SMax Reitz 
2811c1bb86cdSEric Blake         ret = BDRV_BLOCK_DATA;
2812c1bb86cdSEric Blake     } else {
2813a290f085SEric Blake         /* On a hole, compute bytes to the beginning of the next extent.  */
2814a290f085SEric Blake         assert(hole == offset);
2815869e7ee8SHanna Reitz         *pnum = data - offset;
2816c1bb86cdSEric Blake         ret = BDRV_BLOCK_ZERO;
2817c1bb86cdSEric Blake     }
2818a290f085SEric Blake     *map = offset;
2819c1bb86cdSEric Blake     *file = bs;
2820a290f085SEric Blake     return ret | BDRV_BLOCK_OFFSET_VALID;
2821c1bb86cdSEric Blake }
2822c1bb86cdSEric Blake 
282331be8a2aSStefan Hajnoczi #if defined(__linux__)
282431be8a2aSStefan Hajnoczi /* Verify that the file is not in the page cache */
282531be8a2aSStefan Hajnoczi static void check_cache_dropped(BlockDriverState *bs, Error **errp)
282631be8a2aSStefan Hajnoczi {
282731be8a2aSStefan Hajnoczi     const size_t window_size = 128 * 1024 * 1024;
282831be8a2aSStefan Hajnoczi     BDRVRawState *s = bs->opaque;
282931be8a2aSStefan Hajnoczi     void *window = NULL;
283031be8a2aSStefan Hajnoczi     size_t length = 0;
283131be8a2aSStefan Hajnoczi     unsigned char *vec;
283231be8a2aSStefan Hajnoczi     size_t page_size;
283331be8a2aSStefan Hajnoczi     off_t offset;
283431be8a2aSStefan Hajnoczi     off_t end;
283531be8a2aSStefan Hajnoczi 
283631be8a2aSStefan Hajnoczi     /* mincore(2) page status information requires 1 byte per page */
283731be8a2aSStefan Hajnoczi     page_size = sysconf(_SC_PAGESIZE);
283831be8a2aSStefan Hajnoczi     vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
283931be8a2aSStefan Hajnoczi 
284031be8a2aSStefan Hajnoczi     end = raw_getlength(bs);
284131be8a2aSStefan Hajnoczi 
284231be8a2aSStefan Hajnoczi     for (offset = 0; offset < end; offset += window_size) {
284331be8a2aSStefan Hajnoczi         void *new_window;
284431be8a2aSStefan Hajnoczi         size_t new_length;
284531be8a2aSStefan Hajnoczi         size_t vec_end;
284631be8a2aSStefan Hajnoczi         size_t i;
284731be8a2aSStefan Hajnoczi         int ret;
284831be8a2aSStefan Hajnoczi 
284931be8a2aSStefan Hajnoczi         /* Unmap previous window if size has changed */
285031be8a2aSStefan Hajnoczi         new_length = MIN(end - offset, window_size);
285131be8a2aSStefan Hajnoczi         if (new_length != length) {
285231be8a2aSStefan Hajnoczi             munmap(window, length);
285331be8a2aSStefan Hajnoczi             window = NULL;
285431be8a2aSStefan Hajnoczi             length = 0;
285531be8a2aSStefan Hajnoczi         }
285631be8a2aSStefan Hajnoczi 
285731be8a2aSStefan Hajnoczi         new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
285831be8a2aSStefan Hajnoczi                           s->fd, offset);
285931be8a2aSStefan Hajnoczi         if (new_window == MAP_FAILED) {
286031be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mmap failed");
286131be8a2aSStefan Hajnoczi             break;
286231be8a2aSStefan Hajnoczi         }
286331be8a2aSStefan Hajnoczi 
286431be8a2aSStefan Hajnoczi         window = new_window;
286531be8a2aSStefan Hajnoczi         length = new_length;
286631be8a2aSStefan Hajnoczi 
286731be8a2aSStefan Hajnoczi         ret = mincore(window, length, vec);
286831be8a2aSStefan Hajnoczi         if (ret < 0) {
286931be8a2aSStefan Hajnoczi             error_setg_errno(errp, errno, "mincore failed");
287031be8a2aSStefan Hajnoczi             break;
287131be8a2aSStefan Hajnoczi         }
287231be8a2aSStefan Hajnoczi 
287331be8a2aSStefan Hajnoczi         vec_end = DIV_ROUND_UP(length, page_size);
287431be8a2aSStefan Hajnoczi         for (i = 0; i < vec_end; i++) {
287531be8a2aSStefan Hajnoczi             if (vec[i] & 0x1) {
287631be8a2aSStefan Hajnoczi                 break;
287731be8a2aSStefan Hajnoczi             }
287831be8a2aSStefan Hajnoczi         }
287977ed971bSMarkus Armbruster         if (i < vec_end) {
288077ed971bSMarkus Armbruster             error_setg(errp, "page cache still in use!");
288177ed971bSMarkus Armbruster             break;
288277ed971bSMarkus Armbruster         }
288331be8a2aSStefan Hajnoczi     }
288431be8a2aSStefan Hajnoczi 
288531be8a2aSStefan Hajnoczi     if (window) {
288631be8a2aSStefan Hajnoczi         munmap(window, length);
288731be8a2aSStefan Hajnoczi     }
288831be8a2aSStefan Hajnoczi 
288931be8a2aSStefan Hajnoczi     g_free(vec);
289031be8a2aSStefan Hajnoczi }
289131be8a2aSStefan Hajnoczi #endif /* __linux__ */
289231be8a2aSStefan Hajnoczi 
2893dd577a26SStefan Hajnoczi static void coroutine_fn raw_co_invalidate_cache(BlockDriverState *bs,
2894dd577a26SStefan Hajnoczi                                                  Error **errp)
2895dd577a26SStefan Hajnoczi {
2896dd577a26SStefan Hajnoczi     BDRVRawState *s = bs->opaque;
2897dd577a26SStefan Hajnoczi     int ret;
2898dd577a26SStefan Hajnoczi 
2899dd577a26SStefan Hajnoczi     ret = fd_open(bs);
2900dd577a26SStefan Hajnoczi     if (ret < 0) {
2901dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "The file descriptor is not open");
2902dd577a26SStefan Hajnoczi         return;
2903dd577a26SStefan Hajnoczi     }
2904dd577a26SStefan Hajnoczi 
2905f357fcd8SStefan Hajnoczi     if (!s->drop_cache) {
2906f357fcd8SStefan Hajnoczi         return;
2907f357fcd8SStefan Hajnoczi     }
2908f357fcd8SStefan Hajnoczi 
2909dd577a26SStefan Hajnoczi     if (s->open_flags & O_DIRECT) {
2910dd577a26SStefan Hajnoczi         return; /* No host kernel page cache */
2911dd577a26SStefan Hajnoczi     }
2912dd577a26SStefan Hajnoczi 
2913dd577a26SStefan Hajnoczi #if defined(__linux__)
2914dd577a26SStefan Hajnoczi     /* This sets the scene for the next syscall... */
2915dd577a26SStefan Hajnoczi     ret = bdrv_co_flush(bs);
2916dd577a26SStefan Hajnoczi     if (ret < 0) {
2917dd577a26SStefan Hajnoczi         error_setg_errno(errp, -ret, "flush failed");
2918dd577a26SStefan Hajnoczi         return;
2919dd577a26SStefan Hajnoczi     }
2920dd577a26SStefan Hajnoczi 
2921dd577a26SStefan Hajnoczi     /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2922dd577a26SStefan Hajnoczi      * process.  These limitations are okay because we just fsynced the file,
2923dd577a26SStefan Hajnoczi      * we don't use mmap, and the file should not be in use by other processes.
2924dd577a26SStefan Hajnoczi      */
2925dd577a26SStefan Hajnoczi     ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
2926dd577a26SStefan Hajnoczi     if (ret != 0) { /* the return value is a positive errno */
2927dd577a26SStefan Hajnoczi         error_setg_errno(errp, ret, "fadvise failed");
2928dd577a26SStefan Hajnoczi         return;
2929dd577a26SStefan Hajnoczi     }
293031be8a2aSStefan Hajnoczi 
293131be8a2aSStefan Hajnoczi     if (s->check_cache_dropped) {
293231be8a2aSStefan Hajnoczi         check_cache_dropped(bs, errp);
293331be8a2aSStefan Hajnoczi     }
2934dd577a26SStefan Hajnoczi #else /* __linux__ */
2935dd577a26SStefan Hajnoczi     /* Do nothing.  Live migration to a remote host with cache.direct=off is
2936dd577a26SStefan Hajnoczi      * unsupported on other host operating systems.  Cache consistency issues
2937dd577a26SStefan Hajnoczi      * may occur but no error is reported here, partly because that's the
2938dd577a26SStefan Hajnoczi      * historical behavior and partly because it's hard to differentiate valid
2939dd577a26SStefan Hajnoczi      * configurations that should not cause errors.
2940dd577a26SStefan Hajnoczi      */
2941dd577a26SStefan Hajnoczi #endif /* !__linux__ */
2942dd577a26SStefan Hajnoczi }
2943dd577a26SStefan Hajnoczi 
29441c450366SAnton Nefedov static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
29451c450366SAnton Nefedov {
29461c450366SAnton Nefedov     if (ret) {
29471c450366SAnton Nefedov         s->stats.discard_nb_failed++;
29481c450366SAnton Nefedov     } else {
29491c450366SAnton Nefedov         s->stats.discard_nb_ok++;
29501c450366SAnton Nefedov         s->stats.discard_bytes_ok += nbytes;
29511c450366SAnton Nefedov     }
29521c450366SAnton Nefedov }
29531c450366SAnton Nefedov 
295433d70fb6SKevin Wolf static coroutine_fn int
29550c802287SVladimir Sementsov-Ogievskiy raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes,
29560c802287SVladimir Sementsov-Ogievskiy                 bool blkdev)
2957c1bb86cdSEric Blake {
2958c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
295946ee0f46SKevin Wolf     RawPosixAIOData acb;
29601c450366SAnton Nefedov     int ret;
2961c1bb86cdSEric Blake 
296246ee0f46SKevin Wolf     acb = (RawPosixAIOData) {
296346ee0f46SKevin Wolf         .bs             = bs,
296446ee0f46SKevin Wolf         .aio_fildes     = s->fd,
296546ee0f46SKevin Wolf         .aio_type       = QEMU_AIO_DISCARD,
296646ee0f46SKevin Wolf         .aio_offset     = offset,
296746ee0f46SKevin Wolf         .aio_nbytes     = bytes,
296846ee0f46SKevin Wolf     };
296946ee0f46SKevin Wolf 
297046ee0f46SKevin Wolf     if (blkdev) {
297146ee0f46SKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
297246ee0f46SKevin Wolf     }
297346ee0f46SKevin Wolf 
29741c450366SAnton Nefedov     ret = raw_thread_pool_submit(bs, handle_aiocb_discard, &acb);
29751c450366SAnton Nefedov     raw_account_discard(s, bytes, ret);
29761c450366SAnton Nefedov     return ret;
297746ee0f46SKevin Wolf }
297846ee0f46SKevin Wolf 
297946ee0f46SKevin Wolf static coroutine_fn int
29800c802287SVladimir Sementsov-Ogievskiy raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
298146ee0f46SKevin Wolf {
298246ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, false);
2983c1bb86cdSEric Blake }
2984c1bb86cdSEric Blake 
29857154d8aeSKevin Wolf static int coroutine_fn
2986f34b2bcfSVladimir Sementsov-Ogievskiy raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
29877154d8aeSKevin Wolf                      BdrvRequestFlags flags, bool blkdev)
29887154d8aeSKevin Wolf {
29897154d8aeSKevin Wolf     BDRVRawState *s = bs->opaque;
29907154d8aeSKevin Wolf     RawPosixAIOData acb;
29917154d8aeSKevin Wolf     ThreadPoolFunc *handler;
29927154d8aeSKevin Wolf 
2993292d06b9SMax Reitz #ifdef CONFIG_FALLOCATE
2994292d06b9SMax Reitz     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2995292d06b9SMax Reitz         BdrvTrackedRequest *req;
2996292d06b9SMax Reitz 
2997292d06b9SMax Reitz         /*
2998292d06b9SMax Reitz          * This is a workaround for a bug in the Linux XFS driver,
2999292d06b9SMax Reitz          * where writes submitted through the AIO interface will be
3000292d06b9SMax Reitz          * discarded if they happen beyond a concurrently running
3001292d06b9SMax Reitz          * fallocate() that increases the file length (i.e., both the
3002292d06b9SMax Reitz          * write and the fallocate() happen beyond the EOF).
3003292d06b9SMax Reitz          *
3004292d06b9SMax Reitz          * To work around it, we extend the tracked request for this
3005292d06b9SMax Reitz          * zero write until INT64_MAX (effectively infinity), and mark
3006292d06b9SMax Reitz          * it as serializing.
3007292d06b9SMax Reitz          *
3008292d06b9SMax Reitz          * We have to enable this workaround for all filesystems and
3009292d06b9SMax Reitz          * AIO modes (not just XFS with aio=native), because for
3010292d06b9SMax Reitz          * remote filesystems we do not know the host configuration.
3011292d06b9SMax Reitz          */
3012292d06b9SMax Reitz 
3013292d06b9SMax Reitz         req = bdrv_co_get_self_request(bs);
3014292d06b9SMax Reitz         assert(req);
3015292d06b9SMax Reitz         assert(req->type == BDRV_TRACKED_WRITE);
3016292d06b9SMax Reitz         assert(req->offset <= offset);
3017292d06b9SMax Reitz         assert(req->offset + req->bytes >= offset + bytes);
3018292d06b9SMax Reitz 
30198b117001SVladimir Sementsov-Ogievskiy         req->bytes = BDRV_MAX_LENGTH - req->offset;
30208b117001SVladimir Sementsov-Ogievskiy 
302169b55e03SVladimir Sementsov-Ogievskiy         bdrv_check_request(req->offset, req->bytes, &error_abort);
3022292d06b9SMax Reitz 
30238ac5aab2SVladimir Sementsov-Ogievskiy         bdrv_make_request_serialising(req, bs->bl.request_alignment);
3024292d06b9SMax Reitz     }
3025292d06b9SMax Reitz #endif
3026292d06b9SMax Reitz 
30277154d8aeSKevin Wolf     acb = (RawPosixAIOData) {
30287154d8aeSKevin Wolf         .bs             = bs,
30297154d8aeSKevin Wolf         .aio_fildes     = s->fd,
30307154d8aeSKevin Wolf         .aio_type       = QEMU_AIO_WRITE_ZEROES,
30317154d8aeSKevin Wolf         .aio_offset     = offset,
30327154d8aeSKevin Wolf         .aio_nbytes     = bytes,
30337154d8aeSKevin Wolf     };
30347154d8aeSKevin Wolf 
30357154d8aeSKevin Wolf     if (blkdev) {
30367154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_BLKDEV;
30377154d8aeSKevin Wolf     }
3038738301e1SKevin Wolf     if (flags & BDRV_REQ_NO_FALLBACK) {
3039738301e1SKevin Wolf         acb.aio_type |= QEMU_AIO_NO_FALLBACK;
3040738301e1SKevin Wolf     }
30417154d8aeSKevin Wolf 
30427154d8aeSKevin Wolf     if (flags & BDRV_REQ_MAY_UNMAP) {
30437154d8aeSKevin Wolf         acb.aio_type |= QEMU_AIO_DISCARD;
30447154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes_unmap;
30457154d8aeSKevin Wolf     } else {
30467154d8aeSKevin Wolf         handler = handle_aiocb_write_zeroes;
30477154d8aeSKevin Wolf     }
30487154d8aeSKevin Wolf 
30497154d8aeSKevin Wolf     return raw_thread_pool_submit(bs, handler, &acb);
30507154d8aeSKevin Wolf }
30517154d8aeSKevin Wolf 
3052c1bb86cdSEric Blake static int coroutine_fn raw_co_pwrite_zeroes(
3053c1bb86cdSEric Blake     BlockDriverState *bs, int64_t offset,
3054f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t bytes, BdrvRequestFlags flags)
3055c1bb86cdSEric Blake {
30567154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
3057c1bb86cdSEric Blake }
3058c1bb86cdSEric Blake 
3059c1bb86cdSEric Blake static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3060c1bb86cdSEric Blake {
3061c1bb86cdSEric Blake     return 0;
3062c1bb86cdSEric Blake }
3063c1bb86cdSEric Blake 
3064d9245599SAnton Nefedov static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
3065d9245599SAnton Nefedov {
3066d9245599SAnton Nefedov     BDRVRawState *s = bs->opaque;
3067d9245599SAnton Nefedov     return (BlockStatsSpecificFile) {
3068d9245599SAnton Nefedov         .discard_nb_ok = s->stats.discard_nb_ok,
3069d9245599SAnton Nefedov         .discard_nb_failed = s->stats.discard_nb_failed,
3070d9245599SAnton Nefedov         .discard_bytes_ok = s->stats.discard_bytes_ok,
3071d9245599SAnton Nefedov     };
3072d9245599SAnton Nefedov }
3073d9245599SAnton Nefedov 
3074d9245599SAnton Nefedov static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3075d9245599SAnton Nefedov {
3076d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3077d9245599SAnton Nefedov 
3078d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_FILE;
3079d9245599SAnton Nefedov     stats->u.file = get_blockstats_specific_file(bs);
3080d9245599SAnton Nefedov 
3081d9245599SAnton Nefedov     return stats;
3082d9245599SAnton Nefedov }
3083d9245599SAnton Nefedov 
308414176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
3085d9245599SAnton Nefedov static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3086d9245599SAnton Nefedov {
3087d9245599SAnton Nefedov     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3088d9245599SAnton Nefedov 
3089d9245599SAnton Nefedov     stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3090d9245599SAnton Nefedov     stats->u.host_device = get_blockstats_specific_file(bs);
3091d9245599SAnton Nefedov 
3092d9245599SAnton Nefedov     return stats;
3093d9245599SAnton Nefedov }
309414176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
3095d9245599SAnton Nefedov 
3096c1bb86cdSEric Blake static QemuOptsList raw_create_opts = {
3097c1bb86cdSEric Blake     .name = "raw-create-opts",
3098c1bb86cdSEric Blake     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3099c1bb86cdSEric Blake     .desc = {
3100c1bb86cdSEric Blake         {
3101c1bb86cdSEric Blake             .name = BLOCK_OPT_SIZE,
3102c1bb86cdSEric Blake             .type = QEMU_OPT_SIZE,
3103c1bb86cdSEric Blake             .help = "Virtual disk size"
3104c1bb86cdSEric Blake         },
3105c1bb86cdSEric Blake         {
3106c1bb86cdSEric Blake             .name = BLOCK_OPT_NOCOW,
3107c1bb86cdSEric Blake             .type = QEMU_OPT_BOOL,
3108c1bb86cdSEric Blake             .help = "Turn off copy-on-write (valid only on btrfs)"
3109c1bb86cdSEric Blake         },
3110c1bb86cdSEric Blake         {
3111c1bb86cdSEric Blake             .name = BLOCK_OPT_PREALLOC,
3112c1bb86cdSEric Blake             .type = QEMU_OPT_STRING,
3113abea0053SStefano Garzarella             .help = "Preallocation mode (allowed values: off"
3114abea0053SStefano Garzarella #ifdef CONFIG_POSIX_FALLOCATE
3115abea0053SStefano Garzarella                     ", falloc"
3116abea0053SStefano Garzarella #endif
3117abea0053SStefano Garzarella                     ", full)"
3118c1bb86cdSEric Blake         },
3119ffa244c8SKevin Wolf         {
3120ffa244c8SKevin Wolf             .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3121ffa244c8SKevin Wolf             .type = QEMU_OPT_SIZE,
3122ffa244c8SKevin Wolf             .help = "Extent size hint for the image file, 0 to disable"
3123ffa244c8SKevin Wolf         },
3124c1bb86cdSEric Blake         { /* end of list */ }
3125c1bb86cdSEric Blake     }
3126c1bb86cdSEric Blake };
3127c1bb86cdSEric Blake 
3128244a5668SFam Zheng static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3129244a5668SFam Zheng                           Error **errp)
3130244a5668SFam Zheng {
31316ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
313272373e40SVladimir Sementsov-Ogievskiy     int input_flags = s->reopen_state ? s->reopen_state->flags : bs->open_flags;
31336ceabe6fSKevin Wolf     int open_flags;
31346ceabe6fSKevin Wolf     int ret;
31356ceabe6fSKevin Wolf 
31366ceabe6fSKevin Wolf     /* We may need a new fd if auto-read-only switches the mode */
313772373e40SVladimir Sementsov-Ogievskiy     ret = raw_reconfigure_getfd(bs, input_flags, &open_flags, perm,
31386ceabe6fSKevin Wolf                                 false, errp);
31396ceabe6fSKevin Wolf     if (ret < 0) {
31406ceabe6fSKevin Wolf         return ret;
31416ceabe6fSKevin Wolf     } else if (ret != s->fd) {
314272373e40SVladimir Sementsov-Ogievskiy         Error *local_err = NULL;
314372373e40SVladimir Sementsov-Ogievskiy 
314472373e40SVladimir Sementsov-Ogievskiy         /*
314572373e40SVladimir Sementsov-Ogievskiy          * Fail already check_perm() if we can't get a working O_DIRECT
314672373e40SVladimir Sementsov-Ogievskiy          * alignment with the new fd.
314772373e40SVladimir Sementsov-Ogievskiy          */
314872373e40SVladimir Sementsov-Ogievskiy         raw_probe_alignment(bs, ret, &local_err);
314972373e40SVladimir Sementsov-Ogievskiy         if (local_err) {
315072373e40SVladimir Sementsov-Ogievskiy             error_propagate(errp, local_err);
315172373e40SVladimir Sementsov-Ogievskiy             return -EINVAL;
315272373e40SVladimir Sementsov-Ogievskiy         }
315372373e40SVladimir Sementsov-Ogievskiy 
31546ceabe6fSKevin Wolf         s->perm_change_fd = ret;
3155094e3639SMax Reitz         s->perm_change_flags = open_flags;
31566ceabe6fSKevin Wolf     }
31576ceabe6fSKevin Wolf 
31586ceabe6fSKevin Wolf     /* Prepare permissions on old fd to avoid conflicts between old and new,
31596ceabe6fSKevin Wolf      * but keep everything locked that new will need. */
31606ceabe6fSKevin Wolf     ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
31616ceabe6fSKevin Wolf     if (ret < 0) {
31626ceabe6fSKevin Wolf         goto fail;
31636ceabe6fSKevin Wolf     }
31646ceabe6fSKevin Wolf 
31656ceabe6fSKevin Wolf     /* Copy locks to the new fd */
3166eb43ea16SLi Feng     if (s->perm_change_fd && s->use_lock) {
31676ceabe6fSKevin Wolf         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
31686ceabe6fSKevin Wolf                                    false, errp);
31696ceabe6fSKevin Wolf         if (ret < 0) {
31706ceabe6fSKevin Wolf             raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
31716ceabe6fSKevin Wolf             goto fail;
31726ceabe6fSKevin Wolf         }
31736ceabe6fSKevin Wolf     }
31746ceabe6fSKevin Wolf     return 0;
31756ceabe6fSKevin Wolf 
31766ceabe6fSKevin Wolf fail:
317772373e40SVladimir Sementsov-Ogievskiy     if (s->perm_change_fd) {
31786ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
31796ceabe6fSKevin Wolf     }
31806ceabe6fSKevin Wolf     s->perm_change_fd = 0;
31816ceabe6fSKevin Wolf     return ret;
3182244a5668SFam Zheng }
3183244a5668SFam Zheng 
3184244a5668SFam Zheng static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3185244a5668SFam Zheng {
3186244a5668SFam Zheng     BDRVRawState *s = bs->opaque;
31876ceabe6fSKevin Wolf 
31886ceabe6fSKevin Wolf     /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
31896ceabe6fSKevin Wolf      * called after .bdrv_reopen_commit) */
31906ceabe6fSKevin Wolf     if (s->perm_change_fd && s->fd != s->perm_change_fd) {
31916ceabe6fSKevin Wolf         qemu_close(s->fd);
31926ceabe6fSKevin Wolf         s->fd = s->perm_change_fd;
3193094e3639SMax Reitz         s->open_flags = s->perm_change_flags;
31946ceabe6fSKevin Wolf     }
31956ceabe6fSKevin Wolf     s->perm_change_fd = 0;
31966ceabe6fSKevin Wolf 
3197244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3198244a5668SFam Zheng     s->perm = perm;
3199244a5668SFam Zheng     s->shared_perm = shared;
3200244a5668SFam Zheng }
3201244a5668SFam Zheng 
3202244a5668SFam Zheng static void raw_abort_perm_update(BlockDriverState *bs)
3203244a5668SFam Zheng {
32046ceabe6fSKevin Wolf     BDRVRawState *s = bs->opaque;
32056ceabe6fSKevin Wolf 
32066ceabe6fSKevin Wolf     /* For reopen, .bdrv_reopen_abort is called afterwards and will close
32076ceabe6fSKevin Wolf      * the file descriptor. */
320872373e40SVladimir Sementsov-Ogievskiy     if (s->perm_change_fd) {
32096ceabe6fSKevin Wolf         qemu_close(s->perm_change_fd);
32106ceabe6fSKevin Wolf     }
32116ceabe6fSKevin Wolf     s->perm_change_fd = 0;
32126ceabe6fSKevin Wolf 
3213244a5668SFam Zheng     raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3214244a5668SFam Zheng }
3215244a5668SFam Zheng 
321667b51fb9SVladimir Sementsov-Ogievskiy static int coroutine_fn raw_co_copy_range_from(
321748535049SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
321848535049SVladimir Sementsov-Ogievskiy         BdrvChild *dst, int64_t dst_offset, int64_t bytes,
321967b51fb9SVladimir Sementsov-Ogievskiy         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
32201efad060SFam Zheng {
322167b51fb9SVladimir Sementsov-Ogievskiy     return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
322267b51fb9SVladimir Sementsov-Ogievskiy                                  read_flags, write_flags);
32231efad060SFam Zheng }
32241efad060SFam Zheng 
32251efad060SFam Zheng static int coroutine_fn raw_co_copy_range_to(BlockDriverState *bs,
322667b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *src,
322748535049SVladimir Sementsov-Ogievskiy                                              int64_t src_offset,
322867b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvChild *dst,
322948535049SVladimir Sementsov-Ogievskiy                                              int64_t dst_offset,
323048535049SVladimir Sementsov-Ogievskiy                                              int64_t bytes,
323167b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags read_flags,
323267b51fb9SVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags write_flags)
32331efad060SFam Zheng {
323458a209c4SKevin Wolf     RawPosixAIOData acb;
32351efad060SFam Zheng     BDRVRawState *s = bs->opaque;
32361efad060SFam Zheng     BDRVRawState *src_s;
32371efad060SFam Zheng 
32381efad060SFam Zheng     assert(dst->bs == bs);
32391efad060SFam Zheng     if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
32401efad060SFam Zheng         return -ENOTSUP;
32411efad060SFam Zheng     }
32421efad060SFam Zheng 
32431efad060SFam Zheng     src_s = src->bs->opaque;
32449f850f67SFam Zheng     if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
32451efad060SFam Zheng         return -EIO;
32461efad060SFam Zheng     }
324758a209c4SKevin Wolf 
324858a209c4SKevin Wolf     acb = (RawPosixAIOData) {
324958a209c4SKevin Wolf         .bs             = bs,
325058a209c4SKevin Wolf         .aio_type       = QEMU_AIO_COPY_RANGE,
325158a209c4SKevin Wolf         .aio_fildes     = src_s->fd,
325258a209c4SKevin Wolf         .aio_offset     = src_offset,
325358a209c4SKevin Wolf         .aio_nbytes     = bytes,
325458a209c4SKevin Wolf         .copy_range     = {
325558a209c4SKevin Wolf             .aio_fd2        = s->fd,
325658a209c4SKevin Wolf             .aio_offset2    = dst_offset,
325758a209c4SKevin Wolf         },
325858a209c4SKevin Wolf     };
325958a209c4SKevin Wolf 
326058a209c4SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_copy_range, &acb);
32611efad060SFam Zheng }
32621efad060SFam Zheng 
3263c1bb86cdSEric Blake BlockDriver bdrv_file = {
3264c1bb86cdSEric Blake     .format_name = "file",
3265c1bb86cdSEric Blake     .protocol_name = "file",
3266c1bb86cdSEric Blake     .instance_size = sizeof(BDRVRawState),
3267c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3268c1bb86cdSEric Blake     .bdrv_probe = NULL, /* no probe for protocols */
3269c1bb86cdSEric Blake     .bdrv_parse_filename = raw_parse_filename,
3270c1bb86cdSEric Blake     .bdrv_file_open = raw_open,
3271c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3272c1bb86cdSEric Blake     .bdrv_reopen_commit = raw_reopen_commit,
3273c1bb86cdSEric Blake     .bdrv_reopen_abort = raw_reopen_abort,
3274c1bb86cdSEric Blake     .bdrv_close = raw_close,
3275927f11e1SKevin Wolf     .bdrv_co_create = raw_co_create,
3276efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts = raw_co_create_opts,
3277c1bb86cdSEric Blake     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3278a290f085SEric Blake     .bdrv_co_block_status = raw_co_block_status,
3279dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3280c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
32819bffae14SDaniel Henrique Barboza     .bdrv_co_delete_file = raw_co_delete_file,
3282c1bb86cdSEric Blake 
3283c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3284c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
328533d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
328633d70fb6SKevin Wolf     .bdrv_co_pdiscard       = raw_co_pdiscard,
32871efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
32881efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3289c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3290c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3291c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3292ed6e2161SNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3293c1bb86cdSEric Blake 
3294061ca8a3SKevin Wolf     .bdrv_co_truncate = raw_co_truncate,
3295c1bb86cdSEric Blake     .bdrv_getlength = raw_getlength,
3296c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3297c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3298c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3299d9245599SAnton Nefedov     .bdrv_get_specific_stats = raw_get_specific_stats,
3300244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3301244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3302244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3303c1bb86cdSEric Blake     .create_opts = &raw_create_opts,
33048a2ce0bcSAlberto Garcia     .mutable_opts = mutable_opts,
3305c1bb86cdSEric Blake };
3306c1bb86cdSEric Blake 
3307c1bb86cdSEric Blake /***********************************************/
3308c1bb86cdSEric Blake /* host device */
3309c1bb86cdSEric Blake 
331014176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
331114176c8dSJoelle van Dyne 
3312c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3313c1bb86cdSEric Blake static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3314c1bb86cdSEric Blake                                 CFIndex maxPathSize, int flags);
3315c1bb86cdSEric Blake static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3316c1bb86cdSEric Blake {
3317c1bb86cdSEric Blake     kern_return_t kernResult = KERN_FAILURE;
3318c1bb86cdSEric Blake     mach_port_t     masterPort;
3319c1bb86cdSEric Blake     CFMutableDictionaryRef  classesToMatch;
3320c1bb86cdSEric Blake     const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3321c1bb86cdSEric Blake     char *mediaType = NULL;
3322c1bb86cdSEric Blake 
3323c1bb86cdSEric Blake     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
3324c1bb86cdSEric Blake     if ( KERN_SUCCESS != kernResult ) {
3325c1bb86cdSEric Blake         printf( "IOMasterPort returned %d\n", kernResult );
3326c1bb86cdSEric Blake     }
3327c1bb86cdSEric Blake 
3328c1bb86cdSEric Blake     int index;
3329c1bb86cdSEric Blake     for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3330c1bb86cdSEric Blake         classesToMatch = IOServiceMatching(matching_array[index]);
3331c1bb86cdSEric Blake         if (classesToMatch == NULL) {
3332c1bb86cdSEric Blake             error_report("IOServiceMatching returned NULL for %s",
3333c1bb86cdSEric Blake                          matching_array[index]);
3334c1bb86cdSEric Blake             continue;
3335c1bb86cdSEric Blake         }
3336c1bb86cdSEric Blake         CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3337c1bb86cdSEric Blake                              kCFBooleanTrue);
3338c1bb86cdSEric Blake         kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
3339c1bb86cdSEric Blake                                                   mediaIterator);
3340c1bb86cdSEric Blake         if (kernResult != KERN_SUCCESS) {
3341c1bb86cdSEric Blake             error_report("Note: IOServiceGetMatchingServices returned %d",
3342c1bb86cdSEric Blake                          kernResult);
3343c1bb86cdSEric Blake             continue;
3344c1bb86cdSEric Blake         }
3345c1bb86cdSEric Blake 
3346c1bb86cdSEric Blake         /* If a match was found, leave the loop */
3347c1bb86cdSEric Blake         if (*mediaIterator != 0) {
33484f7d28d7SLaurent Vivier             trace_file_FindEjectableOpticalMedia(matching_array[index]);
3349c1bb86cdSEric Blake             mediaType = g_strdup(matching_array[index]);
3350c1bb86cdSEric Blake             break;
3351c1bb86cdSEric Blake         }
3352c1bb86cdSEric Blake     }
3353c1bb86cdSEric Blake     return mediaType;
3354c1bb86cdSEric Blake }
3355c1bb86cdSEric Blake 
3356c1bb86cdSEric Blake kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3357c1bb86cdSEric Blake                          CFIndex maxPathSize, int flags)
3358c1bb86cdSEric Blake {
3359c1bb86cdSEric Blake     io_object_t     nextMedia;
3360c1bb86cdSEric Blake     kern_return_t   kernResult = KERN_FAILURE;
3361c1bb86cdSEric Blake     *bsdPath = '\0';
3362c1bb86cdSEric Blake     nextMedia = IOIteratorNext( mediaIterator );
3363c1bb86cdSEric Blake     if ( nextMedia )
3364c1bb86cdSEric Blake     {
3365c1bb86cdSEric Blake         CFTypeRef   bsdPathAsCFString;
3366c1bb86cdSEric Blake     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3367c1bb86cdSEric Blake         if ( bsdPathAsCFString ) {
3368c1bb86cdSEric Blake             size_t devPathLength;
3369c1bb86cdSEric Blake             strcpy( bsdPath, _PATH_DEV );
3370c1bb86cdSEric Blake             if (flags & BDRV_O_NOCACHE) {
3371c1bb86cdSEric Blake                 strcat(bsdPath, "r");
3372c1bb86cdSEric Blake             }
3373c1bb86cdSEric Blake             devPathLength = strlen( bsdPath );
3374c1bb86cdSEric Blake             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3375c1bb86cdSEric Blake                 kernResult = KERN_SUCCESS;
3376c1bb86cdSEric Blake             }
3377c1bb86cdSEric Blake             CFRelease( bsdPathAsCFString );
3378c1bb86cdSEric Blake         }
3379c1bb86cdSEric Blake         IOObjectRelease( nextMedia );
3380c1bb86cdSEric Blake     }
3381c1bb86cdSEric Blake 
3382c1bb86cdSEric Blake     return kernResult;
3383c1bb86cdSEric Blake }
3384c1bb86cdSEric Blake 
3385c1bb86cdSEric Blake /* Sets up a real cdrom for use in QEMU */
3386c1bb86cdSEric Blake static bool setup_cdrom(char *bsd_path, Error **errp)
3387c1bb86cdSEric Blake {
3388c1bb86cdSEric Blake     int index, num_of_test_partitions = 2, fd;
3389c1bb86cdSEric Blake     char test_partition[MAXPATHLEN];
3390c1bb86cdSEric Blake     bool partition_found = false;
3391c1bb86cdSEric Blake 
3392c1bb86cdSEric Blake     /* look for a working partition */
3393c1bb86cdSEric Blake     for (index = 0; index < num_of_test_partitions; index++) {
3394c1bb86cdSEric Blake         snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3395c1bb86cdSEric Blake                  index);
3396b18a24a9SDaniel P. Berrangé         fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
3397c1bb86cdSEric Blake         if (fd >= 0) {
3398c1bb86cdSEric Blake             partition_found = true;
3399c1bb86cdSEric Blake             qemu_close(fd);
3400c1bb86cdSEric Blake             break;
3401c1bb86cdSEric Blake         }
3402c1bb86cdSEric Blake     }
3403c1bb86cdSEric Blake 
3404c1bb86cdSEric Blake     /* if a working partition on the device was not found */
3405c1bb86cdSEric Blake     if (partition_found == false) {
3406c1bb86cdSEric Blake         error_setg(errp, "Failed to find a working partition on disc");
3407c1bb86cdSEric Blake     } else {
34084f7d28d7SLaurent Vivier         trace_file_setup_cdrom(test_partition);
3409c1bb86cdSEric Blake         pstrcpy(bsd_path, MAXPATHLEN, test_partition);
3410c1bb86cdSEric Blake     }
3411c1bb86cdSEric Blake     return partition_found;
3412c1bb86cdSEric Blake }
3413c1bb86cdSEric Blake 
3414c1bb86cdSEric Blake /* Prints directions on mounting and unmounting a device */
3415c1bb86cdSEric Blake static void print_unmounting_directions(const char *file_name)
3416c1bb86cdSEric Blake {
3417c1bb86cdSEric Blake     error_report("If device %s is mounted on the desktop, unmount"
3418c1bb86cdSEric Blake                  " it first before using it in QEMU", file_name);
3419c1bb86cdSEric Blake     error_report("Command to unmount device: diskutil unmountDisk %s",
3420c1bb86cdSEric Blake                  file_name);
3421c1bb86cdSEric Blake     error_report("Command to mount device: diskutil mountDisk %s", file_name);
3422c1bb86cdSEric Blake }
3423c1bb86cdSEric Blake 
3424c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3425c1bb86cdSEric Blake 
3426c1bb86cdSEric Blake static int hdev_probe_device(const char *filename)
3427c1bb86cdSEric Blake {
3428c1bb86cdSEric Blake     struct stat st;
3429c1bb86cdSEric Blake 
3430c1bb86cdSEric Blake     /* allow a dedicated CD-ROM driver to match with a higher priority */
3431c1bb86cdSEric Blake     if (strstart(filename, "/dev/cdrom", NULL))
3432c1bb86cdSEric Blake         return 50;
3433c1bb86cdSEric Blake 
3434c1bb86cdSEric Blake     if (stat(filename, &st) >= 0 &&
3435c1bb86cdSEric Blake             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
3436c1bb86cdSEric Blake         return 100;
3437c1bb86cdSEric Blake     }
3438c1bb86cdSEric Blake 
3439c1bb86cdSEric Blake     return 0;
3440c1bb86cdSEric Blake }
3441c1bb86cdSEric Blake 
3442c1bb86cdSEric Blake static void hdev_parse_filename(const char *filename, QDict *options,
3443c1bb86cdSEric Blake                                 Error **errp)
3444c1bb86cdSEric Blake {
344503c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
3446c1bb86cdSEric Blake }
3447c1bb86cdSEric Blake 
3448c1bb86cdSEric Blake static bool hdev_is_sg(BlockDriverState *bs)
3449c1bb86cdSEric Blake {
3450c1bb86cdSEric Blake 
3451c1bb86cdSEric Blake #if defined(__linux__)
3452c1bb86cdSEric Blake 
3453c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3454c1bb86cdSEric Blake     struct stat st;
3455c1bb86cdSEric Blake     struct sg_scsi_id scsiid;
3456c1bb86cdSEric Blake     int sg_version;
3457c1bb86cdSEric Blake     int ret;
3458c1bb86cdSEric Blake 
3459c1bb86cdSEric Blake     if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
3460c1bb86cdSEric Blake         return false;
3461c1bb86cdSEric Blake     }
3462c1bb86cdSEric Blake 
3463c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
3464c1bb86cdSEric Blake     if (ret < 0) {
3465c1bb86cdSEric Blake         return false;
3466c1bb86cdSEric Blake     }
3467c1bb86cdSEric Blake 
3468c1bb86cdSEric Blake     ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
3469c1bb86cdSEric Blake     if (ret >= 0) {
34704f7d28d7SLaurent Vivier         trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3471c1bb86cdSEric Blake         return true;
3472c1bb86cdSEric Blake     }
3473c1bb86cdSEric Blake 
3474c1bb86cdSEric Blake #endif
3475c1bb86cdSEric Blake 
3476c1bb86cdSEric Blake     return false;
3477c1bb86cdSEric Blake }
3478c1bb86cdSEric Blake 
3479c1bb86cdSEric Blake static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
3480c1bb86cdSEric Blake                      Error **errp)
3481c1bb86cdSEric Blake {
3482c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3483c1bb86cdSEric Blake     int ret;
3484c1bb86cdSEric Blake 
3485c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3486129c7d1cSMarkus Armbruster     /*
3487129c7d1cSMarkus Armbruster      * Caution: while qdict_get_str() is fine, getting non-string types
3488129c7d1cSMarkus Armbruster      * would require more care.  When @options come from -blockdev or
3489129c7d1cSMarkus Armbruster      * blockdev_add, its members are typed according to the QAPI
3490129c7d1cSMarkus Armbruster      * schema, but when they come from -drive, they're all QString.
3491129c7d1cSMarkus Armbruster      */
3492c1bb86cdSEric Blake     const char *filename = qdict_get_str(options, "filename");
3493c1bb86cdSEric Blake     char bsd_path[MAXPATHLEN] = "";
3494c1bb86cdSEric Blake     bool error_occurred = false;
3495c1bb86cdSEric Blake 
3496c1bb86cdSEric Blake     /* If using a real cdrom */
3497c1bb86cdSEric Blake     if (strcmp(filename, "/dev/cdrom") == 0) {
3498c1bb86cdSEric Blake         char *mediaType = NULL;
3499c1bb86cdSEric Blake         kern_return_t ret_val;
3500c1bb86cdSEric Blake         io_iterator_t mediaIterator = 0;
3501c1bb86cdSEric Blake 
3502c1bb86cdSEric Blake         mediaType = FindEjectableOpticalMedia(&mediaIterator);
3503c1bb86cdSEric Blake         if (mediaType == NULL) {
3504c1bb86cdSEric Blake             error_setg(errp, "Please make sure your CD/DVD is in the optical"
3505c1bb86cdSEric Blake                        " drive");
3506c1bb86cdSEric Blake             error_occurred = true;
3507c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3508c1bb86cdSEric Blake         }
3509c1bb86cdSEric Blake 
3510c1bb86cdSEric Blake         ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
3511c1bb86cdSEric Blake         if (ret_val != KERN_SUCCESS) {
3512c1bb86cdSEric Blake             error_setg(errp, "Could not get BSD path for optical drive");
3513c1bb86cdSEric Blake             error_occurred = true;
3514c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3515c1bb86cdSEric Blake         }
3516c1bb86cdSEric Blake 
3517c1bb86cdSEric Blake         /* If a real optical drive was not found */
3518c1bb86cdSEric Blake         if (bsd_path[0] == '\0') {
3519c1bb86cdSEric Blake             error_setg(errp, "Failed to obtain bsd path for optical drive");
3520c1bb86cdSEric Blake             error_occurred = true;
3521c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3522c1bb86cdSEric Blake         }
3523c1bb86cdSEric Blake 
3524c1bb86cdSEric Blake         /* If using a cdrom disc and finding a partition on the disc failed */
3525c1bb86cdSEric Blake         if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
3526c1bb86cdSEric Blake             setup_cdrom(bsd_path, errp) == false) {
3527c1bb86cdSEric Blake             print_unmounting_directions(bsd_path);
3528c1bb86cdSEric Blake             error_occurred = true;
3529c1bb86cdSEric Blake             goto hdev_open_Mac_error;
3530c1bb86cdSEric Blake         }
3531c1bb86cdSEric Blake 
353246f5ac20SEric Blake         qdict_put_str(options, "filename", bsd_path);
3533c1bb86cdSEric Blake 
3534c1bb86cdSEric Blake hdev_open_Mac_error:
3535c1bb86cdSEric Blake         g_free(mediaType);
3536c1bb86cdSEric Blake         if (mediaIterator) {
3537c1bb86cdSEric Blake             IOObjectRelease(mediaIterator);
3538c1bb86cdSEric Blake         }
3539c1bb86cdSEric Blake         if (error_occurred) {
3540c1bb86cdSEric Blake             return -ENOENT;
3541c1bb86cdSEric Blake         }
3542c1bb86cdSEric Blake     }
3543c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3544c1bb86cdSEric Blake 
3545c1bb86cdSEric Blake     s->type = FTYPE_FILE;
3546c1bb86cdSEric Blake 
3547668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3548c1bb86cdSEric Blake     if (ret < 0) {
3549c1bb86cdSEric Blake #if defined(__APPLE__) && defined(__MACH__)
3550c1bb86cdSEric Blake         if (*bsd_path) {
3551c1bb86cdSEric Blake             filename = bsd_path;
3552c1bb86cdSEric Blake         }
3553c1bb86cdSEric Blake         /* if a physical device experienced an error while being opened */
3554c1bb86cdSEric Blake         if (strncmp(filename, "/dev/", 5) == 0) {
3555c1bb86cdSEric Blake             print_unmounting_directions(filename);
3556c1bb86cdSEric Blake         }
3557c1bb86cdSEric Blake #endif /* defined(__APPLE__) && defined(__MACH__) */
3558c1bb86cdSEric Blake         return ret;
3559c1bb86cdSEric Blake     }
3560c1bb86cdSEric Blake 
3561c1bb86cdSEric Blake     /* Since this does ioctl the device must be already opened */
3562c1bb86cdSEric Blake     bs->sg = hdev_is_sg(bs);
3563c1bb86cdSEric Blake 
3564c1bb86cdSEric Blake     return ret;
3565c1bb86cdSEric Blake }
3566c1bb86cdSEric Blake 
3567c1bb86cdSEric Blake #if defined(__linux__)
35682f3a7ab3SKevin Wolf static int coroutine_fn
35692f3a7ab3SKevin Wolf hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3570c1bb86cdSEric Blake {
3571c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
357203425671SKevin Wolf     RawPosixAIOData acb;
35732f3a7ab3SKevin Wolf     int ret;
3574c1bb86cdSEric Blake 
35752f3a7ab3SKevin Wolf     ret = fd_open(bs);
35762f3a7ab3SKevin Wolf     if (ret < 0) {
35772f3a7ab3SKevin Wolf         return ret;
35782f3a7ab3SKevin Wolf     }
3579c1bb86cdSEric Blake 
35807c9e5276SPaolo Bonzini     if (req == SG_IO && s->pr_mgr) {
35817c9e5276SPaolo Bonzini         struct sg_io_hdr *io_hdr = buf;
35827c9e5276SPaolo Bonzini         if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
35837c9e5276SPaolo Bonzini             io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
35847c9e5276SPaolo Bonzini             return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
35852f3a7ab3SKevin Wolf                                       s->fd, io_hdr);
35867c9e5276SPaolo Bonzini         }
35877c9e5276SPaolo Bonzini     }
35887c9e5276SPaolo Bonzini 
358903425671SKevin Wolf     acb = (RawPosixAIOData) {
359003425671SKevin Wolf         .bs         = bs,
359103425671SKevin Wolf         .aio_type   = QEMU_AIO_IOCTL,
359203425671SKevin Wolf         .aio_fildes = s->fd,
359303425671SKevin Wolf         .aio_offset = 0,
359403425671SKevin Wolf         .ioctl      = {
359503425671SKevin Wolf             .buf        = buf,
359603425671SKevin Wolf             .cmd        = req,
359703425671SKevin Wolf         },
359803425671SKevin Wolf     };
359903425671SKevin Wolf 
360003425671SKevin Wolf     return raw_thread_pool_submit(bs, handle_aiocb_ioctl, &acb);
3601c1bb86cdSEric Blake }
3602c1bb86cdSEric Blake #endif /* linux */
3603c1bb86cdSEric Blake 
360433d70fb6SKevin Wolf static coroutine_fn int
36050c802287SVladimir Sementsov-Ogievskiy hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
3606c1bb86cdSEric Blake {
36071c450366SAnton Nefedov     BDRVRawState *s = bs->opaque;
360833d70fb6SKevin Wolf     int ret;
3609c1bb86cdSEric Blake 
361033d70fb6SKevin Wolf     ret = fd_open(bs);
361133d70fb6SKevin Wolf     if (ret < 0) {
36121c450366SAnton Nefedov         raw_account_discard(s, bytes, ret);
361333d70fb6SKevin Wolf         return ret;
3614c1bb86cdSEric Blake     }
361546ee0f46SKevin Wolf     return raw_do_pdiscard(bs, offset, bytes, true);
3616c1bb86cdSEric Blake }
3617c1bb86cdSEric Blake 
3618c1bb86cdSEric Blake static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
3619f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
3620c1bb86cdSEric Blake {
3621c1bb86cdSEric Blake     int rc;
3622c1bb86cdSEric Blake 
3623c1bb86cdSEric Blake     rc = fd_open(bs);
3624c1bb86cdSEric Blake     if (rc < 0) {
3625c1bb86cdSEric Blake         return rc;
3626c1bb86cdSEric Blake     }
362734fa110eSKevin Wolf 
36287154d8aeSKevin Wolf     return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
3629c1bb86cdSEric Blake }
3630c1bb86cdSEric Blake 
3631c1bb86cdSEric Blake static BlockDriver bdrv_host_device = {
3632c1bb86cdSEric Blake     .format_name        = "host_device",
3633c1bb86cdSEric Blake     .protocol_name        = "host_device",
3634c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3635c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3636c1bb86cdSEric Blake     .bdrv_probe_device  = hdev_probe_device,
3637c1bb86cdSEric Blake     .bdrv_parse_filename = hdev_parse_filename,
3638c1bb86cdSEric Blake     .bdrv_file_open     = hdev_open,
3639c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3640c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3641c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3642c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
36435a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
36445a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
36458a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3646dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3647c1bb86cdSEric Blake     .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3648c1bb86cdSEric Blake 
3649c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3650c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
365133d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
365233d70fb6SKevin Wolf     .bdrv_co_pdiscard       = hdev_co_pdiscard,
36531efad060SFam Zheng     .bdrv_co_copy_range_from = raw_co_copy_range_from,
36541efad060SFam Zheng     .bdrv_co_copy_range_to  = raw_co_copy_range_to,
3655c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3656c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3657c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3658042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3659c1bb86cdSEric Blake 
3660061ca8a3SKevin Wolf     .bdrv_co_truncate       = raw_co_truncate,
3661c1bb86cdSEric Blake     .bdrv_getlength	= raw_getlength,
3662c1bb86cdSEric Blake     .bdrv_get_info = raw_get_info,
3663c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3664c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3665d9245599SAnton Nefedov     .bdrv_get_specific_stats = hdev_get_specific_stats,
3666244a5668SFam Zheng     .bdrv_check_perm = raw_check_perm,
3667244a5668SFam Zheng     .bdrv_set_perm   = raw_set_perm,
3668244a5668SFam Zheng     .bdrv_abort_perm_update = raw_abort_perm_update,
3669c1bb86cdSEric Blake     .bdrv_probe_blocksizes = hdev_probe_blocksizes,
3670c1bb86cdSEric Blake     .bdrv_probe_geometry = hdev_probe_geometry,
3671c1bb86cdSEric Blake 
3672c1bb86cdSEric Blake     /* generic scsi device */
3673c1bb86cdSEric Blake #ifdef __linux__
36742f3a7ab3SKevin Wolf     .bdrv_co_ioctl          = hdev_co_ioctl,
3675c1bb86cdSEric Blake #endif
3676c1bb86cdSEric Blake };
3677c1bb86cdSEric Blake 
3678c1bb86cdSEric Blake #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3679c1bb86cdSEric Blake static void cdrom_parse_filename(const char *filename, QDict *options,
3680c1bb86cdSEric Blake                                  Error **errp)
3681c1bb86cdSEric Blake {
368203c320d8SMax Reitz     bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
3683c1bb86cdSEric Blake }
3684c1bb86cdSEric Blake #endif
3685c1bb86cdSEric Blake 
3686c1bb86cdSEric Blake #ifdef __linux__
3687c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3688c1bb86cdSEric Blake                       Error **errp)
3689c1bb86cdSEric Blake {
3690c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3691c1bb86cdSEric Blake 
3692c1bb86cdSEric Blake     s->type = FTYPE_CD;
3693c1bb86cdSEric Blake 
3694c1bb86cdSEric Blake     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3695230ff739SJohn Snow     return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
3696c1bb86cdSEric Blake }
3697c1bb86cdSEric Blake 
3698c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3699c1bb86cdSEric Blake {
3700c1bb86cdSEric Blake     int fd, ret;
3701c1bb86cdSEric Blake     int prio = 0;
3702c1bb86cdSEric Blake     struct stat st;
3703c1bb86cdSEric Blake 
3704b18a24a9SDaniel P. Berrangé     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
3705c1bb86cdSEric Blake     if (fd < 0) {
3706c1bb86cdSEric Blake         goto out;
3707c1bb86cdSEric Blake     }
3708c1bb86cdSEric Blake     ret = fstat(fd, &st);
3709c1bb86cdSEric Blake     if (ret == -1 || !S_ISBLK(st.st_mode)) {
3710c1bb86cdSEric Blake         goto outc;
3711c1bb86cdSEric Blake     }
3712c1bb86cdSEric Blake 
3713c1bb86cdSEric Blake     /* Attempt to detect via a CDROM specific ioctl */
3714c1bb86cdSEric Blake     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3715c1bb86cdSEric Blake     if (ret >= 0)
3716c1bb86cdSEric Blake         prio = 100;
3717c1bb86cdSEric Blake 
3718c1bb86cdSEric Blake outc:
3719c1bb86cdSEric Blake     qemu_close(fd);
3720c1bb86cdSEric Blake out:
3721c1bb86cdSEric Blake     return prio;
3722c1bb86cdSEric Blake }
3723c1bb86cdSEric Blake 
3724c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3725c1bb86cdSEric Blake {
3726c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3727c1bb86cdSEric Blake     int ret;
3728c1bb86cdSEric Blake 
3729c1bb86cdSEric Blake     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
3730c1bb86cdSEric Blake     return ret == CDS_DISC_OK;
3731c1bb86cdSEric Blake }
3732c1bb86cdSEric Blake 
3733c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3734c1bb86cdSEric Blake {
3735c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3736c1bb86cdSEric Blake 
3737c1bb86cdSEric Blake     if (eject_flag) {
3738c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
3739c1bb86cdSEric Blake             perror("CDROMEJECT");
3740c1bb86cdSEric Blake     } else {
3741c1bb86cdSEric Blake         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
3742c1bb86cdSEric Blake             perror("CDROMEJECT");
3743c1bb86cdSEric Blake     }
3744c1bb86cdSEric Blake }
3745c1bb86cdSEric Blake 
3746c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3747c1bb86cdSEric Blake {
3748c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3749c1bb86cdSEric Blake 
3750c1bb86cdSEric Blake     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
3751c1bb86cdSEric Blake         /*
3752c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3753c1bb86cdSEric Blake          * mounts the CD-ROM
3754c1bb86cdSEric Blake          */
3755c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3756c1bb86cdSEric Blake     }
3757c1bb86cdSEric Blake }
3758c1bb86cdSEric Blake 
3759c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3760c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3761c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3762c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3763c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3764c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3765c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3766c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3767c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3768c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3769c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3770c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
37715a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
37725a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
37738a2ce0bcSAlberto Garcia     .mutable_opts        = mutable_opts,
3774dd577a26SStefan Hajnoczi     .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3775c1bb86cdSEric Blake 
3776c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3777c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
377833d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3779c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3780c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3781c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3782042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3783c1bb86cdSEric Blake 
3784061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3785c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3786c1bb86cdSEric Blake     .has_variable_length = true,
3787c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3788c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3789c1bb86cdSEric Blake 
3790c1bb86cdSEric Blake     /* removable device support */
3791c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3792c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3793c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3794c1bb86cdSEric Blake 
3795c1bb86cdSEric Blake     /* generic scsi device */
37962f3a7ab3SKevin Wolf     .bdrv_co_ioctl      = hdev_co_ioctl,
3797c1bb86cdSEric Blake };
3798c1bb86cdSEric Blake #endif /* __linux__ */
3799c1bb86cdSEric Blake 
3800c1bb86cdSEric Blake #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3801c1bb86cdSEric Blake static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
3802c1bb86cdSEric Blake                       Error **errp)
3803c1bb86cdSEric Blake {
3804c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3805c1bb86cdSEric Blake     int ret;
3806c1bb86cdSEric Blake 
3807c1bb86cdSEric Blake     s->type = FTYPE_CD;
3808c1bb86cdSEric Blake 
3809668f62ecSMarkus Armbruster     ret = raw_open_common(bs, options, flags, 0, true, errp);
3810c1bb86cdSEric Blake     if (ret) {
3811c1bb86cdSEric Blake         return ret;
3812c1bb86cdSEric Blake     }
3813c1bb86cdSEric Blake 
3814c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3815c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3816c1bb86cdSEric Blake     return 0;
3817c1bb86cdSEric Blake }
3818c1bb86cdSEric Blake 
3819c1bb86cdSEric Blake static int cdrom_probe_device(const char *filename)
3820c1bb86cdSEric Blake {
3821c1bb86cdSEric Blake     if (strstart(filename, "/dev/cd", NULL) ||
3822c1bb86cdSEric Blake             strstart(filename, "/dev/acd", NULL))
3823c1bb86cdSEric Blake         return 100;
3824c1bb86cdSEric Blake     return 0;
3825c1bb86cdSEric Blake }
3826c1bb86cdSEric Blake 
3827c1bb86cdSEric Blake static int cdrom_reopen(BlockDriverState *bs)
3828c1bb86cdSEric Blake {
3829c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3830c1bb86cdSEric Blake     int fd;
3831c1bb86cdSEric Blake 
3832c1bb86cdSEric Blake     /*
3833c1bb86cdSEric Blake      * Force reread of possibly changed/newly loaded disc,
3834c1bb86cdSEric Blake      * FreeBSD seems to not notice sometimes...
3835c1bb86cdSEric Blake      */
3836c1bb86cdSEric Blake     if (s->fd >= 0)
3837c1bb86cdSEric Blake         qemu_close(s->fd);
3838b18a24a9SDaniel P. Berrangé     fd = qemu_open(bs->filename, s->open_flags, NULL);
3839c1bb86cdSEric Blake     if (fd < 0) {
3840c1bb86cdSEric Blake         s->fd = -1;
3841c1bb86cdSEric Blake         return -EIO;
3842c1bb86cdSEric Blake     }
3843c1bb86cdSEric Blake     s->fd = fd;
3844c1bb86cdSEric Blake 
3845c1bb86cdSEric Blake     /* make sure the door isn't locked at this time */
3846c1bb86cdSEric Blake     ioctl(s->fd, CDIOCALLOW);
3847c1bb86cdSEric Blake     return 0;
3848c1bb86cdSEric Blake }
3849c1bb86cdSEric Blake 
3850c1bb86cdSEric Blake static bool cdrom_is_inserted(BlockDriverState *bs)
3851c1bb86cdSEric Blake {
3852c1bb86cdSEric Blake     return raw_getlength(bs) > 0;
3853c1bb86cdSEric Blake }
3854c1bb86cdSEric Blake 
3855c1bb86cdSEric Blake static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3856c1bb86cdSEric Blake {
3857c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3858c1bb86cdSEric Blake 
3859c1bb86cdSEric Blake     if (s->fd < 0)
3860c1bb86cdSEric Blake         return;
3861c1bb86cdSEric Blake 
3862c1bb86cdSEric Blake     (void) ioctl(s->fd, CDIOCALLOW);
3863c1bb86cdSEric Blake 
3864c1bb86cdSEric Blake     if (eject_flag) {
3865c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCEJECT) < 0)
3866c1bb86cdSEric Blake             perror("CDIOCEJECT");
3867c1bb86cdSEric Blake     } else {
3868c1bb86cdSEric Blake         if (ioctl(s->fd, CDIOCCLOSE) < 0)
3869c1bb86cdSEric Blake             perror("CDIOCCLOSE");
3870c1bb86cdSEric Blake     }
3871c1bb86cdSEric Blake 
3872c1bb86cdSEric Blake     cdrom_reopen(bs);
3873c1bb86cdSEric Blake }
3874c1bb86cdSEric Blake 
3875c1bb86cdSEric Blake static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3876c1bb86cdSEric Blake {
3877c1bb86cdSEric Blake     BDRVRawState *s = bs->opaque;
3878c1bb86cdSEric Blake 
3879c1bb86cdSEric Blake     if (s->fd < 0)
3880c1bb86cdSEric Blake         return;
3881c1bb86cdSEric Blake     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3882c1bb86cdSEric Blake         /*
3883c1bb86cdSEric Blake          * Note: an error can happen if the distribution automatically
3884c1bb86cdSEric Blake          * mounts the CD-ROM
3885c1bb86cdSEric Blake          */
3886c1bb86cdSEric Blake         /* perror("CDROM_LOCKDOOR"); */
3887c1bb86cdSEric Blake     }
3888c1bb86cdSEric Blake }
3889c1bb86cdSEric Blake 
3890c1bb86cdSEric Blake static BlockDriver bdrv_host_cdrom = {
3891c1bb86cdSEric Blake     .format_name        = "host_cdrom",
3892c1bb86cdSEric Blake     .protocol_name      = "host_cdrom",
3893c1bb86cdSEric Blake     .instance_size      = sizeof(BDRVRawState),
3894c1bb86cdSEric Blake     .bdrv_needs_filename = true,
3895c1bb86cdSEric Blake     .bdrv_probe_device	= cdrom_probe_device,
3896c1bb86cdSEric Blake     .bdrv_parse_filename = cdrom_parse_filename,
3897c1bb86cdSEric Blake     .bdrv_file_open     = cdrom_open,
3898c1bb86cdSEric Blake     .bdrv_close         = raw_close,
3899c1bb86cdSEric Blake     .bdrv_reopen_prepare = raw_reopen_prepare,
3900c1bb86cdSEric Blake     .bdrv_reopen_commit  = raw_reopen_commit,
3901c1bb86cdSEric Blake     .bdrv_reopen_abort   = raw_reopen_abort,
39025a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts = bdrv_co_create_opts_simple,
39035a5e7f8cSMaxim Levitsky     .create_opts         = &bdrv_create_opts_simple,
39048a2ce0bcSAlberto Garcia     .mutable_opts       = mutable_opts,
3905c1bb86cdSEric Blake 
3906c1bb86cdSEric Blake     .bdrv_co_preadv         = raw_co_preadv,
3907c1bb86cdSEric Blake     .bdrv_co_pwritev        = raw_co_pwritev,
390833d70fb6SKevin Wolf     .bdrv_co_flush_to_disk  = raw_co_flush_to_disk,
3909c1bb86cdSEric Blake     .bdrv_refresh_limits = raw_refresh_limits,
3910c1bb86cdSEric Blake     .bdrv_io_plug = raw_aio_plug,
3911c1bb86cdSEric Blake     .bdrv_io_unplug = raw_aio_unplug,
3912042b757cSNishanth Aravamudan     .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3913c1bb86cdSEric Blake 
3914061ca8a3SKevin Wolf     .bdrv_co_truncate    = raw_co_truncate,
3915c1bb86cdSEric Blake     .bdrv_getlength      = raw_getlength,
3916c1bb86cdSEric Blake     .has_variable_length = true,
3917c1bb86cdSEric Blake     .bdrv_get_allocated_file_size
3918c1bb86cdSEric Blake                         = raw_get_allocated_file_size,
3919c1bb86cdSEric Blake 
3920c1bb86cdSEric Blake     /* removable device support */
3921c1bb86cdSEric Blake     .bdrv_is_inserted   = cdrom_is_inserted,
3922c1bb86cdSEric Blake     .bdrv_eject         = cdrom_eject,
3923c1bb86cdSEric Blake     .bdrv_lock_medium   = cdrom_lock_medium,
3924c1bb86cdSEric Blake };
3925c1bb86cdSEric Blake #endif /* __FreeBSD__ */
3926c1bb86cdSEric Blake 
392714176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
392814176c8dSJoelle van Dyne 
3929c1bb86cdSEric Blake static void bdrv_file_init(void)
3930c1bb86cdSEric Blake {
3931c1bb86cdSEric Blake     /*
3932c1bb86cdSEric Blake      * Register all the drivers.  Note that order is important, the driver
3933c1bb86cdSEric Blake      * registered last will get probed first.
3934c1bb86cdSEric Blake      */
3935c1bb86cdSEric Blake     bdrv_register(&bdrv_file);
393614176c8dSJoelle van Dyne #if defined(HAVE_HOST_BLOCK_DEVICE)
3937c1bb86cdSEric Blake     bdrv_register(&bdrv_host_device);
3938c1bb86cdSEric Blake #ifdef __linux__
3939c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3940c1bb86cdSEric Blake #endif
3941c1bb86cdSEric Blake #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3942c1bb86cdSEric Blake     bdrv_register(&bdrv_host_cdrom);
3943c1bb86cdSEric Blake #endif
394414176c8dSJoelle van Dyne #endif /* HAVE_HOST_BLOCK_DEVICE */
3945c1bb86cdSEric Blake }
3946c1bb86cdSEric Blake 
3947c1bb86cdSEric Blake block_init(bdrv_file_init);
3948