]> git.proxmox.com Git - mirror_qemu.git/blame - block/file-posix.c
file-posix: add tracking of the zone write pointers
[mirror_qemu.git] / block / file-posix.c
CommitLineData
83f64091 1/*
223d4670 2 * Block driver for RAW files (posix)
5fafdf24 3 *
83f64091 4 * Copyright (c) 2006 Fabrice Bellard
5fafdf24 5 *
83f64091
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
922a01a0 24
80c71a24 25#include "qemu/osdep.h"
da34e65c 26#include "qapi/error.h"
f348b6d1 27#include "qemu/cutils.h"
d49b6836 28#include "qemu/error-report.h"
e2c1c34f 29#include "block/block-io.h"
737e150e 30#include "block/block_int.h"
1de7afc9 31#include "qemu/module.h"
922a01a0 32#include "qemu/option.h"
ffa244c8 33#include "qemu/units.h"
5df022cf 34#include "qemu/memalign.h"
de81a169 35#include "trace.h"
737e150e 36#include "block/thread-pool.h"
1de7afc9 37#include "qemu/iov.h"
0187f5c9 38#include "block/raw-aio.h"
452fcdbc 39#include "qapi/qmp/qdict.h"
d49b6836 40#include "qapi/qmp/qstring.h"
83f64091 41
7c9e5276
PB
42#include "scsi/pr-manager.h"
43#include "scsi/constants.h"
44
83affaa6 45#if defined(__APPLE__) && (__MACH__)
14176c8d
JD
46#include <sys/ioctl.h>
47#if defined(HAVE_HOST_BLOCK_DEVICE)
83f64091
FB
48#include <paths.h>
49#include <sys/param.h>
0dfc7af2 50#include <sys/mount.h>
83f64091
FB
51#include <IOKit/IOKitLib.h>
52#include <IOKit/IOBSD.h>
53#include <IOKit/storage/IOMediaBSDClient.h>
54#include <IOKit/storage/IOMedia.h>
55#include <IOKit/storage/IOCDMedia.h>
56//#include <IOKit/storage/IOCDTypes.h>
d0855f12 57#include <IOKit/storage/IODVDMedia.h>
83f64091 58#include <CoreFoundation/CoreFoundation.h>
14176c8d 59#endif /* defined(HAVE_HOST_BLOCK_DEVICE) */
83f64091
FB
60#endif
61
62#ifdef __sun__
2e9671da 63#define _POSIX_PTHREAD_SEMANTICS 1
83f64091
FB
64#include <sys/dkio.h>
65#endif
19cb3738
FB
66#ifdef __linux__
67#include <sys/ioctl.h>
05acda4d 68#include <sys/param.h>
1efad060 69#include <sys/syscall.h>
5edc8557 70#include <sys/vfs.h>
6d43eaa3
SL
71#if defined(CONFIG_BLKZONED)
72#include <linux/blkzoned.h>
73#endif
19cb3738
FB
74#include <linux/cdrom.h>
75#include <linux/fd.h>
5500316d 76#include <linux/fs.h>
1a9335e4 77#include <linux/hdreg.h>
5edc8557 78#include <linux/magic.h>
3307ed7b 79#include <scsi/sg.h>
1a9335e4
ET
80#ifdef __s390__
81#include <asm/dasd.h>
82#endif
4ab15590
CL
83#ifndef FS_NOCOW_FL
84#define FS_NOCOW_FL 0x00800000 /* Do not cow file */
85#endif
5500316d 86#endif
b953f075 87#if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
3d4fa43e
KK
88#include <linux/falloc.h>
89#endif
a167ba50 90#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1cb6c3fd 91#include <sys/disk.h>
9f23011a 92#include <sys/cdio.h>
1cb6c3fd 93#endif
83f64091 94
128ab2ff
BS
95#ifdef __OpenBSD__
96#include <sys/ioctl.h>
97#include <sys/disklabel.h>
98#include <sys/dkio.h>
99#endif
100
d1f6fd8d
CE
101#ifdef __NetBSD__
102#include <sys/ioctl.h>
103#include <sys/disklabel.h>
104#include <sys/dkio.h>
105#include <sys/disk.h>
106#endif
107
c5e97233
BS
108#ifdef __DragonFly__
109#include <sys/ioctl.h>
110#include <sys/diskslice.h>
111#endif
112
f6465578
AL
113/* OS X does not have O_DSYNC */
114#ifndef O_DSYNC
1c27a8b3 115#ifdef O_SYNC
7ab064d2 116#define O_DSYNC O_SYNC
1c27a8b3
JA
117#elif defined(O_FSYNC)
118#define O_DSYNC O_FSYNC
119#endif
f6465578
AL
120#endif
121
9f7965c7
AL
122/* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
123#ifndef O_DIRECT
124#define O_DIRECT O_DSYNC
125#endif
126
19cb3738
FB
127#define FTYPE_FILE 0
128#define FTYPE_CD 1
83f64091 129
581b9e29
CH
130#define MAX_BLOCKSIZE 4096
131
244a5668
FZ
132/* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
133 * leaving a few more bytes for its future use. */
134#define RAW_LOCK_PERM_BASE 100
135#define RAW_LOCK_SHARED_BASE 200
136
19cb3738
FB
137typedef struct BDRVRawState {
138 int fd;
244a5668 139 bool use_lock;
19cb3738 140 int type;
0e1d8f4c 141 int open_flags;
c25f53b0
PB
142 size_t buf_align;
143
244a5668
FZ
144 /* The current permissions. */
145 uint64_t perm;
146 uint64_t shared_perm;
147
2996ffad 148 /* The perms bits whose corresponding bytes are already locked in
f2e3af29 149 * s->fd. */
2996ffad
FZ
150 uint64_t locked_perm;
151 uint64_t locked_shared_perm;
152
684960d4
SG
153 uint64_t aio_max_batch;
154
6ceabe6f 155 int perm_change_fd;
094e3639 156 int perm_change_flags;
e0c9cf3a
KW
157 BDRVReopenState *reopen_state;
158
260a82e5 159 bool has_discard:1;
97a2ae34 160 bool has_write_zeroes:1;
0a4279d9 161 bool use_linux_aio:1;
c6447510 162 bool use_linux_io_uring:1;
c7ddc882 163 int page_cache_inconsistent; /* errno from fdatasync failure */
d50d8222 164 bool has_fallocate;
3cad8307 165 bool needs_alignment;
5dbd0ce1 166 bool force_alignment;
f357fcd8 167 bool drop_cache;
31be8a2a 168 bool check_cache_dropped;
1c450366
AN
169 struct {
170 uint64_t discard_nb_ok;
171 uint64_t discard_nb_failed;
172 uint64_t discard_bytes_ok;
173 } stats;
7c9e5276
PB
174
175 PRManager *pr_mgr;
19cb3738
FB
176} BDRVRawState;
177
eeb6b45d 178typedef struct BDRVRawReopenState {
eeb6b45d 179 int open_flags;
f357fcd8 180 bool drop_cache;
31be8a2a 181 bool check_cache_dropped;
eeb6b45d
JC
182} BDRVRawReopenState;
183
14176c8d
JD
184static int fd_open(BlockDriverState *bs)
185{
186 BDRVRawState *s = bs->opaque;
187
188 /* this is just to ensure s->fd is sane (its called by io ops) */
189 if (s->fd >= 0) {
190 return 0;
191 }
192 return -EIO;
193}
194
c86422c5 195static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs);
83f64091 196
de81a169
PB
197typedef struct RawPosixAIOData {
198 BlockDriverState *bs;
d57c44d0 199 int aio_type;
de81a169 200 int aio_fildes;
d57c44d0 201
de81a169 202 off_t aio_offset;
d57c44d0
KW
203 uint64_t aio_nbytes;
204
93f4e2ff 205 union {
d57c44d0
KW
206 struct {
207 struct iovec *iov;
208 int niov;
209 } io;
210 struct {
211 uint64_t cmd;
212 void *buf;
213 } ioctl;
93f4e2ff
KW
214 struct {
215 int aio_fd2;
216 off_t aio_offset2;
d57c44d0 217 } copy_range;
93f4e2ff
KW
218 struct {
219 PreallocMode prealloc;
220 Error **errp;
d57c44d0 221 } truncate;
6d43eaa3
SL
222 struct {
223 unsigned int *nr_zones;
224 BlockZoneDescriptor *zones;
225 } zone_report;
226 struct {
227 unsigned long op;
228 } zone_mgmt;
93f4e2ff 229 };
de81a169
PB
230} RawPosixAIOData;
231
a167ba50 232#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8 233static int cdrom_reopen(BlockDriverState *bs);
9f23011a
BS
234#endif
235
797e3e38
DE
236/*
237 * Elide EAGAIN and EACCES details when failing to lock, as this
238 * indicates that the specified file region is already locked by
239 * another process, which is considered a common scenario.
240 */
241#define raw_lock_error_setg_errno(errp, err, fmt, ...) \
242 do { \
243 if ((err) == EAGAIN || (err) == EACCES) { \
244 error_setg((errp), (fmt), ## __VA_ARGS__); \
245 } else { \
246 error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__); \
247 } \
248 } while (0)
249
1de1ae0a 250#if defined(__NetBSD__)
db0754df 251static int raw_normalize_devicepath(const char **filename, Error **errp)
1de1ae0a
CE
252{
253 static char namebuf[PATH_MAX];
254 const char *dp, *fname;
255 struct stat sb;
256
257 fname = *filename;
258 dp = strrchr(fname, '/');
259 if (lstat(fname, &sb) < 0) {
f6fc1e30 260 error_setg_file_open(errp, errno, fname);
1de1ae0a
CE
261 return -errno;
262 }
263
264 if (!S_ISBLK(sb.st_mode)) {
265 return 0;
266 }
267
268 if (dp == NULL) {
269 snprintf(namebuf, PATH_MAX, "r%s", fname);
270 } else {
271 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
272 (int)(dp - fname), fname, dp + 1);
273 }
1de1ae0a 274 *filename = namebuf;
db0754df 275 warn_report("%s is a block device, using %s", fname, *filename);
1de1ae0a
CE
276
277 return 0;
278}
279#else
db0754df 280static int raw_normalize_devicepath(const char **filename, Error **errp)
1de1ae0a
CE
281{
282 return 0;
283}
284#endif
285
8a4ed0d1
ET
286/*
287 * Get logical block size via ioctl. On success store it in @sector_size_p.
288 */
289static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
c25f53b0 290{
c25f53b0 291 unsigned int sector_size;
8a4ed0d1 292 bool success = false;
700f9ce0 293 int i;
c25f53b0 294
8a4ed0d1 295 errno = ENOTSUP;
700f9ce0 296 static const unsigned long ioctl_list[] = {
c25f53b0 297#ifdef BLKSSZGET
700f9ce0 298 BLKSSZGET,
c25f53b0
PB
299#endif
300#ifdef DKIOCGETBLOCKSIZE
700f9ce0 301 DKIOCGETBLOCKSIZE,
c25f53b0
PB
302#endif
303#ifdef DIOCGSECTORSIZE
700f9ce0 304 DIOCGSECTORSIZE,
c25f53b0 305#endif
700f9ce0
PM
306 };
307
308 /* Try a few ioctls to get the right size */
309 for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
310 if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
311 *sector_size_p = sector_size;
312 success = true;
313 }
314 }
8a4ed0d1
ET
315
316 return success ? 0 : -errno;
317}
318
1a9335e4
ET
319/**
320 * Get physical block size of @fd.
321 * On success, store it in @blk_size and return 0.
322 * On failure, return -errno.
323 */
324static int probe_physical_blocksize(int fd, unsigned int *blk_size)
325{
326#ifdef BLKPBSZGET
327 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
328 return -errno;
329 }
330 return 0;
331#else
332 return -ENOTSUP;
333#endif
334}
335
5edc8557
KW
336/*
337 * Returns true if no alignment restrictions are necessary even for files
338 * opened with O_DIRECT.
339 *
340 * raw_probe_alignment() probes the required alignment and assume that 1 means
341 * the probing failed, so it falls back to a safe default of 4k. This can be
342 * avoided if we know that byte alignment is okay for the file.
343 */
344static bool dio_byte_aligned(int fd)
345{
346#ifdef __linux__
347 struct statfs buf;
348 int ret;
349
350 ret = fstatfs(fd, &buf);
351 if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
352 return true;
353 }
354#endif
355 return false;
356}
357
5dbd0ce1
KW
358static bool raw_needs_alignment(BlockDriverState *bs)
359{
360 BDRVRawState *s = bs->opaque;
361
362 if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
363 return true;
364 }
365
366 return s->force_alignment;
367}
368
22d182e8
SH
369/* Check if read is allowed with given memory buffer and length.
370 *
371 * This function is used to check O_DIRECT memory buffer and request alignment.
372 */
373static bool raw_is_io_aligned(int fd, void *buf, size_t len)
374{
375 ssize_t ret = pread(fd, buf, len, 0);
376
377 if (ret >= 0) {
378 return true;
379 }
380
381#ifdef __linux__
382 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
383 * other errors (e.g. real I/O error), which could happen on a failed
384 * drive, since we only care about probing alignment.
385 */
386 if (errno != EINVAL) {
387 return true;
388 }
389#endif
390
391 return false;
392}
393
8a4ed0d1
ET
394static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
395{
396 BDRVRawState *s = bs->opaque;
397 char *buf;
8e3b0cbb 398 size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
a6b257a0 399 size_t alignments[] = {1, 512, 1024, 2048, 4096};
8a4ed0d1 400
b192af8a 401 /* For SCSI generic devices the alignment is not really used.
8a4ed0d1 402 With buffered I/O, we don't have any restrictions. */
b192af8a 403 if (bdrv_is_sg(bs) || !s->needs_alignment) {
a5b8dd2c 404 bs->bl.request_alignment = 1;
8a4ed0d1
ET
405 s->buf_align = 1;
406 return;
407 }
408
a5b8dd2c 409 bs->bl.request_alignment = 0;
8a4ed0d1
ET
410 s->buf_align = 0;
411 /* Let's try to use the logical blocksize for the alignment. */
a5b8dd2c
EB
412 if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
413 bs->bl.request_alignment = 0;
8a4ed0d1 414 }
a5730b8b
TH
415
416#ifdef __linux__
417 /*
418 * The XFS ioctl definitions are shipped in extra packages that might
419 * not always be available. Since we just need the XFS_IOC_DIOINFO ioctl
420 * here, we simply use our own definition instead:
421 */
422 struct xfs_dioattr {
423 uint32_t d_mem;
424 uint32_t d_miniosz;
425 uint32_t d_maxiosz;
426 } da;
427 if (ioctl(fd, _IOR('X', 30, struct xfs_dioattr), &da) >= 0) {
428 bs->bl.request_alignment = da.d_miniosz;
429 /* The kernel returns wrong information for d_mem */
430 /* s->buf_align = da.d_mem; */
c25f53b0
PB
431 }
432#endif
433
a6b257a0
NS
434 /*
435 * If we could not get the sizes so far, we can only guess them. First try
436 * to detect request alignment, since it is more likely to succeed. Then
437 * try to detect buf_align, which cannot be detected in some cases (e.g.
438 * Gluster). If buf_align cannot be detected, we fallback to the value of
439 * request_alignment.
440 */
441
442 if (!bs->bl.request_alignment) {
443 int i;
c25f53b0 444 size_t align;
a6b257a0
NS
445 buf = qemu_memalign(max_align, max_align);
446 for (i = 0; i < ARRAY_SIZE(alignments); i++) {
447 align = alignments[i];
448 if (raw_is_io_aligned(fd, buf, align)) {
449 /* Fallback to safe value. */
450 bs->bl.request_alignment = (align != 1) ? align : max_align;
c25f53b0
PB
451 break;
452 }
453 }
454 qemu_vfree(buf);
455 }
456
a6b257a0
NS
457 if (!s->buf_align) {
458 int i;
c25f53b0 459 size_t align;
a6b257a0
NS
460 buf = qemu_memalign(max_align, 2 * max_align);
461 for (i = 0; i < ARRAY_SIZE(alignments); i++) {
462 align = alignments[i];
463 if (raw_is_io_aligned(fd, buf + align, max_align)) {
236094c7 464 /* Fallback to request_alignment. */
a6b257a0 465 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
c25f53b0
PB
466 break;
467 }
468 }
469 qemu_vfree(buf);
470 }
df26a350 471
a5b8dd2c 472 if (!s->buf_align || !bs->bl.request_alignment) {
8cc9c6e9
EB
473 error_setg(errp, "Could not find working O_DIRECT alignment");
474 error_append_hint(errp, "Try cache.direct=off\n");
df26a350 475 }
c25f53b0
PB
476}
477
bca5283b 478static int check_hdev_writable(int fd)
20eaf1bf
KW
479{
480#if defined(BLKROGET)
481 /* Linux block devices can be configured "read-only" using blockdev(8).
482 * This is independent of device node permissions and therefore open(2)
483 * with O_RDWR succeeds. Actual writes fail with EPERM.
484 *
485 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
486 * check for read-only block devices so that Linux block devices behave
487 * properly.
488 */
489 struct stat st;
490 int readonly = 0;
491
bca5283b 492 if (fstat(fd, &st)) {
20eaf1bf
KW
493 return -errno;
494 }
495
496 if (!S_ISBLK(st.st_mode)) {
497 return 0;
498 }
499
bca5283b 500 if (ioctl(fd, BLKROGET, &readonly) < 0) {
20eaf1bf
KW
501 return -errno;
502 }
503
504 if (readonly) {
505 return -EACCES;
506 }
507#endif /* defined(BLKROGET) */
508 return 0;
509}
510
23dece19 511static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
6a8dc042 512{
23dece19 513 bool read_write = false;
6a8dc042
JC
514 assert(open_flags != NULL);
515
516 *open_flags |= O_BINARY;
517 *open_flags &= ~O_ACCMODE;
23dece19
KW
518
519 if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
520 read_write = has_writers;
521 } else if (bdrv_flags & BDRV_O_RDWR) {
522 read_write = true;
523 }
524
525 if (read_write) {
6a8dc042
JC
526 *open_flags |= O_RDWR;
527 } else {
528 *open_flags |= O_RDONLY;
529 }
530
531 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
532 * and O_DIRECT for no caching. */
533 if ((bdrv_flags & BDRV_O_NOCACHE)) {
534 *open_flags |= O_DIRECT;
535 }
6a8dc042
JC
536}
537
078896a9
HR
538static void raw_parse_filename(const char *filename, QDict *options,
539 Error **errp)
540{
03c320d8 541 bdrv_parse_filename_strip_prefix(filename, "file:", options);
078896a9
HR
542}
543
c66a6157
KW
544static QemuOptsList raw_runtime_opts = {
545 .name = "raw",
546 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
547 .desc = {
548 {
549 .name = "filename",
550 .type = QEMU_OPT_STRING,
551 .help = "File name of the image",
552 },
0a4279d9
KW
553 {
554 .name = "aio",
555 .type = QEMU_OPT_STRING,
c6447510 556 .help = "host AIO implementation (threads, native, io_uring)",
0a4279d9 557 },
684960d4
SG
558 {
559 .name = "aio-max-batch",
560 .type = QEMU_OPT_NUMBER,
561 .help = "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
562 },
16b48d5d
FZ
563 {
564 .name = "locking",
565 .type = QEMU_OPT_STRING,
566 .help = "file locking mode (on/off/auto, default: auto)",
567 },
7c9e5276
PB
568 {
569 .name = "pr-manager",
570 .type = QEMU_OPT_STRING,
571 .help = "id of persistent reservation manager object (default: none)",
572 },
f357fcd8
SH
573#if defined(__linux__)
574 {
575 .name = "drop-cache",
576 .type = QEMU_OPT_BOOL,
577 .help = "invalidate page cache during live migration (default: on)",
578 },
579#endif
31be8a2a
SH
580 {
581 .name = "x-check-cache-dropped",
582 .type = QEMU_OPT_BOOL,
583 .help = "check that page cache was dropped on live migration (default: off)"
584 },
c66a6157
KW
585 { /* end of list */ }
586 },
587};
588
8a2ce0bc
AG
589static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
590
c66a6157 591static int raw_open_common(BlockDriverState *bs, QDict *options,
230ff739
JS
592 int bdrv_flags, int open_flags,
593 bool device, Error **errp)
83f64091
FB
594{
595 BDRVRawState *s = bs->opaque;
c66a6157
KW
596 QemuOpts *opts;
597 Error *local_err = NULL;
8bfea15d 598 const char *filename = NULL;
7c9e5276 599 const char *str;
0a4279d9 600 BlockdevAioOptions aio, aio_default;
0e1d8f4c 601 int fd, ret;
260a82e5 602 struct stat st;
244a5668 603 OnOffAuto locking;
83f64091 604
87ea75d5 605 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
af175e85 606 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
c66a6157
KW
607 ret = -EINVAL;
608 goto fail;
609 }
610
611 filename = qemu_opt_get(opts, "filename");
612
db0754df 613 ret = raw_normalize_devicepath(&filename, errp);
1de1ae0a 614 if (ret != 0) {
c66a6157 615 goto fail;
1de1ae0a
CE
616 }
617
c6447510
AM
618 if (bdrv_flags & BDRV_O_NATIVE_AIO) {
619 aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
620#ifdef CONFIG_LINUX_IO_URING
621 } else if (bdrv_flags & BDRV_O_IO_URING) {
622 aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
623#endif
624 } else {
625 aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
626 }
627
f7abe0ec
MAL
628 aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
629 qemu_opt_get(opts, "aio"),
06c60b6c 630 aio_default, &local_err);
0a4279d9
KW
631 if (local_err) {
632 error_propagate(errp, local_err);
633 ret = -EINVAL;
634 goto fail;
635 }
c6447510 636
0a4279d9 637 s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
c6447510
AM
638#ifdef CONFIG_LINUX_IO_URING
639 s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
640#endif
0a4279d9 641
684960d4
SG
642 s->aio_max_batch = qemu_opt_get_number(opts, "aio-max-batch", 0);
643
f7abe0ec
MAL
644 locking = qapi_enum_parse(&OnOffAuto_lookup,
645 qemu_opt_get(opts, "locking"),
06c60b6c 646 ON_OFF_AUTO_AUTO, &local_err);
244a5668
FZ
647 if (local_err) {
648 error_propagate(errp, local_err);
649 ret = -EINVAL;
650 goto fail;
651 }
652 switch (locking) {
653 case ON_OFF_AUTO_ON:
654 s->use_lock = true;
2b218f5d 655 if (!qemu_has_ofd_lock()) {
db0754df
FZ
656 warn_report("File lock requested but OFD locking syscall is "
657 "unavailable, falling back to POSIX file locks");
658 error_printf("Due to the implementation, locks can be lost "
659 "unexpectedly.\n");
2b218f5d 660 }
244a5668
FZ
661 break;
662 case ON_OFF_AUTO_OFF:
663 s->use_lock = false;
664 break;
665 case ON_OFF_AUTO_AUTO:
2b218f5d 666 s->use_lock = qemu_has_ofd_lock();
244a5668
FZ
667 break;
668 default:
669 abort();
670 }
671
7c9e5276
PB
672 str = qemu_opt_get(opts, "pr-manager");
673 if (str) {
674 s->pr_mgr = pr_manager_lookup(str, &local_err);
675 if (local_err) {
676 error_propagate(errp, local_err);
677 ret = -EINVAL;
678 goto fail;
679 }
680 }
681
f357fcd8 682 s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
31be8a2a
SH
683 s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
684 false);
685
6a8dc042 686 s->open_flags = open_flags;
23dece19 687 raw_parse_flags(bdrv_flags, &s->open_flags, false);
83f64091 688
90babde0 689 s->fd = -1;
b18a24a9 690 fd = qemu_open(filename, s->open_flags, errp);
64107dc0
KW
691 ret = fd < 0 ? -errno : 0;
692
64107dc0 693 if (ret < 0) {
c66a6157 694 if (ret == -EROFS) {
19cb3738 695 ret = -EACCES;
c66a6157
KW
696 }
697 goto fail;
19cb3738 698 }
83f64091 699 s->fd = fd;
9ef91a67 700
bca5283b
KW
701 /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
702 if (s->open_flags & O_RDWR) {
703 ret = check_hdev_writable(s->fd);
704 if (ret < 0) {
705 error_setg_errno(errp, -ret, "The device is not writable");
706 goto fail;
707 }
708 }
709
244a5668
FZ
710 s->perm = 0;
711 s->shared_perm = BLK_PERM_ALL;
712
5c6c3a6c 713#ifdef CONFIG_LINUX_AIO
0a4279d9 714 /* Currently Linux does AIO only for files opened with O_DIRECT */
ed6e2161
NA
715 if (s->use_linux_aio) {
716 if (!(s->open_flags & O_DIRECT)) {
717 error_setg(errp, "aio=native was specified, but it requires "
718 "cache.direct=on, which was not specified.");
719 ret = -EINVAL;
720 goto fail;
721 }
722 if (!aio_setup_linux_aio(bdrv_get_aio_context(bs), errp)) {
723 error_prepend(errp, "Unable to use native AIO: ");
724 goto fail;
725 }
96518254 726 }
1501ecc1 727#else
0a4279d9 728 if (s->use_linux_aio) {
d657c0c2
KW
729 error_setg(errp, "aio=native was specified, but is not supported "
730 "in this build.");
731 ret = -EINVAL;
732 goto fail;
1501ecc1
SH
733 }
734#endif /* !defined(CONFIG_LINUX_AIO) */
9ef91a67 735
c6447510
AM
736#ifdef CONFIG_LINUX_IO_URING
737 if (s->use_linux_io_uring) {
738 if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs), errp)) {
739 error_prepend(errp, "Unable to use io_uring: ");
740 goto fail;
741 }
742 }
743#else
744 if (s->use_linux_io_uring) {
745 error_setg(errp, "aio=io_uring was specified, but is not supported "
746 "in this build.");
747 ret = -EINVAL;
748 goto fail;
749 }
750#endif /* !defined(CONFIG_LINUX_IO_URING) */
751
7ce21016 752 s->has_discard = true;
97a2ae34 753 s->has_write_zeroes = true;
260a82e5
PB
754
755 if (fstat(s->fd, &st) < 0) {
01212d4e 756 ret = -errno;
260a82e5
PB
757 error_setg_errno(errp, errno, "Could not stat file");
758 goto fail;
759 }
230ff739
JS
760
761 if (!device) {
8d17adf3
DB
762 if (!S_ISREG(st.st_mode)) {
763 error_setg(errp, "'%s' driver requires '%s' to be a regular file",
764 bs->drv->format_name, bs->filename);
230ff739
JS
765 ret = -EINVAL;
766 goto fail;
767 } else {
230ff739
JS
768 s->has_fallocate = true;
769 }
770 } else {
771 if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
8d17adf3
DB
772 error_setg(errp, "'%s' driver requires '%s' to be either "
773 "a character or block device",
774 bs->drv->format_name, bs->filename);
230ff739
JS
775 ret = -EINVAL;
776 goto fail;
777 }
260a82e5 778 }
774c726c
SL
779#ifdef CONFIG_BLKZONED
780 /*
781 * The kernel page cache does not reliably work for writes to SWR zones
782 * of zoned block device because it can not guarantee the order of writes.
783 */
784 if ((bs->bl.zoned != BLK_Z_NONE) &&
785 (!(s->open_flags & O_DIRECT))) {
786 error_setg(errp, "The driver supports zoned devices, and it requires "
787 "cache.direct=on, which was not specified.");
788 return -EINVAL; /* No host kernel page cache */
789 }
790#endif
230ff739 791
d0b4503e 792 if (S_ISBLK(st.st_mode)) {
d0b4503e
PB
793#ifdef __linux__
794 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
795 * not rely on the contents of discarded blocks unless using O_DIRECT.
97a2ae34 796 * Same for BLKZEROOUT.
d0b4503e
PB
797 */
798 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
97a2ae34 799 s->has_write_zeroes = false;
d0b4503e
PB
800 }
801#endif
802 }
3cad8307
RPM
803#ifdef __FreeBSD__
804 if (S_ISCHR(st.st_mode)) {
805 /*
806 * The file is a char device (disk), which on FreeBSD isn't behind
807 * a pager, so force all requests to be aligned. This is needed
808 * so QEMU makes sure all IO operations on the device are aligned
809 * to sector size, or else FreeBSD will reject them with EINVAL.
810 */
5dbd0ce1 811 s->force_alignment = true;
3cad8307
RPM
812 }
813#endif
5dbd0ce1 814 s->needs_alignment = raw_needs_alignment(bs);
260a82e5 815
738301e1 816 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
2f0c6e7a
KW
817 if (S_ISREG(st.st_mode)) {
818 /* When extending regular files, we get zeros from the OS */
819 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
820 }
c66a6157
KW
821 ret = 0;
822fail:
a8c5cf27
KW
823 if (ret < 0 && s->fd != -1) {
824 qemu_close(s->fd);
825 }
8bfea15d
KW
826 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
827 unlink(filename);
828 }
c66a6157
KW
829 qemu_opts_del(opts);
830 return ret;
83f64091
FB
831}
832
015a1036
HR
833static int raw_open(BlockDriverState *bs, QDict *options, int flags,
834 Error **errp)
90babde0
CH
835{
836 BDRVRawState *s = bs->opaque;
837
838 s->type = FTYPE_FILE;
230ff739 839 return raw_open_common(bs, options, flags, 0, false, errp);
90babde0
CH
840}
841
244a5668
FZ
842typedef enum {
843 RAW_PL_PREPARE,
844 RAW_PL_COMMIT,
845 RAW_PL_ABORT,
846} RawPermLockOp;
847
848#define PERM_FOREACH(i) \
849 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
850
851/* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
852 * file; if @unlock == true, also unlock the unneeded bytes.
853 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
854 */
2996ffad 855static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
244a5668
FZ
856 uint64_t perm_lock_bits,
857 uint64_t shared_perm_lock_bits,
858 bool unlock, Error **errp)
859{
860 int ret;
861 int i;
2996ffad
FZ
862 uint64_t locked_perm, locked_shared_perm;
863
864 if (s) {
865 locked_perm = s->locked_perm;
866 locked_shared_perm = s->locked_shared_perm;
867 } else {
868 /*
869 * We don't have the previous bits, just lock/unlock for each of the
870 * requested bits.
871 */
872 if (unlock) {
873 locked_perm = BLK_PERM_ALL;
874 locked_shared_perm = BLK_PERM_ALL;
875 } else {
876 locked_perm = 0;
877 locked_shared_perm = 0;
878 }
879 }
244a5668
FZ
880
881 PERM_FOREACH(i) {
882 int off = RAW_LOCK_PERM_BASE + i;
2996ffad
FZ
883 uint64_t bit = (1ULL << i);
884 if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
d0a96155 885 ret = qemu_lock_fd(fd, off, 1, false);
244a5668 886 if (ret) {
797e3e38
DE
887 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
888 off);
244a5668 889 return ret;
2996ffad
FZ
890 } else if (s) {
891 s->locked_perm |= bit;
244a5668 892 }
2996ffad 893 } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
d0a96155 894 ret = qemu_unlock_fd(fd, off, 1);
244a5668 895 if (ret) {
797e3e38 896 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
244a5668 897 return ret;
2996ffad
FZ
898 } else if (s) {
899 s->locked_perm &= ~bit;
244a5668
FZ
900 }
901 }
902 }
903 PERM_FOREACH(i) {
904 int off = RAW_LOCK_SHARED_BASE + i;
2996ffad
FZ
905 uint64_t bit = (1ULL << i);
906 if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
d0a96155 907 ret = qemu_lock_fd(fd, off, 1, false);
244a5668 908 if (ret) {
797e3e38
DE
909 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
910 off);
244a5668 911 return ret;
2996ffad
FZ
912 } else if (s) {
913 s->locked_shared_perm |= bit;
244a5668 914 }
2996ffad
FZ
915 } else if (unlock && (locked_shared_perm & bit) &&
916 !(shared_perm_lock_bits & bit)) {
d0a96155 917 ret = qemu_unlock_fd(fd, off, 1);
244a5668 918 if (ret) {
797e3e38 919 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
244a5668 920 return ret;
2996ffad
FZ
921 } else if (s) {
922 s->locked_shared_perm &= ~bit;
244a5668
FZ
923 }
924 }
925 }
926 return 0;
927}
928
929/* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
d0a96155 930static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
244a5668
FZ
931 Error **errp)
932{
933 int ret;
934 int i;
935
936 PERM_FOREACH(i) {
937 int off = RAW_LOCK_SHARED_BASE + i;
938 uint64_t p = 1ULL << i;
939 if (perm & p) {
d0a96155 940 ret = qemu_lock_fd_test(fd, off, 1, true);
244a5668
FZ
941 if (ret) {
942 char *perm_name = bdrv_perm_names(p);
797e3e38
DE
943
944 raw_lock_error_setg_errno(errp, -ret,
945 "Failed to get \"%s\" lock",
946 perm_name);
244a5668 947 g_free(perm_name);
244a5668
FZ
948 return ret;
949 }
950 }
951 }
952 PERM_FOREACH(i) {
953 int off = RAW_LOCK_PERM_BASE + i;
954 uint64_t p = 1ULL << i;
955 if (!(shared_perm & p)) {
d0a96155 956 ret = qemu_lock_fd_test(fd, off, 1, true);
244a5668
FZ
957 if (ret) {
958 char *perm_name = bdrv_perm_names(p);
797e3e38
DE
959
960 raw_lock_error_setg_errno(errp, -ret,
961 "Failed to get shared \"%s\" lock",
962 perm_name);
244a5668 963 g_free(perm_name);
244a5668
FZ
964 return ret;
965 }
966 }
967 }
968 return 0;
969}
970
971static int raw_handle_perm_lock(BlockDriverState *bs,
972 RawPermLockOp op,
973 uint64_t new_perm, uint64_t new_shared,
974 Error **errp)
975{
976 BDRVRawState *s = bs->opaque;
977 int ret = 0;
978 Error *local_err = NULL;
979
980 if (!s->use_lock) {
981 return 0;
982 }
983
984 if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
985 return 0;
986 }
987
244a5668
FZ
988 switch (op) {
989 case RAW_PL_PREPARE:
696aaaed
VSO
990 if ((s->perm | new_perm) == s->perm &&
991 (s->shared_perm & new_shared) == s->shared_perm)
992 {
993 /*
994 * We are going to unlock bytes, it should not fail. If it fail due
995 * to some fs-dependent permission-unrelated reasons (which occurs
996 * sometimes on NFS and leads to abort in bdrv_replace_child) we
997 * can't prevent such errors by any check here. And we ignore them
998 * anyway in ABORT and COMMIT.
999 */
1000 return 0;
1001 }
f2e3af29 1002 ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
244a5668
FZ
1003 ~s->shared_perm | ~new_shared,
1004 false, errp);
1005 if (!ret) {
f2e3af29 1006 ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
244a5668
FZ
1007 if (!ret) {
1008 return 0;
1009 }
b857431d
FZ
1010 error_append_hint(errp,
1011 "Is another process using the image [%s]?\n",
1012 bs->filename);
244a5668 1013 }
244a5668
FZ
1014 /* fall through to unlock bytes. */
1015 case RAW_PL_ABORT:
f2e3af29 1016 raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
d0a96155 1017 true, &local_err);
244a5668
FZ
1018 if (local_err) {
1019 /* Theoretically the above call only unlocks bytes and it cannot
1020 * fail. Something weird happened, report it.
1021 */
db0754df 1022 warn_report_err(local_err);
244a5668
FZ
1023 }
1024 break;
1025 case RAW_PL_COMMIT:
f2e3af29 1026 raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
d0a96155 1027 true, &local_err);
244a5668
FZ
1028 if (local_err) {
1029 /* Theoretically the above call only unlocks bytes and it cannot
1030 * fail. Something weird happened, report it.
1031 */
db0754df 1032 warn_report_err(local_err);
244a5668
FZ
1033 }
1034 break;
1035 }
1036 return ret;
1037}
1038
ad24b679
MAL
1039/* Sets a specific flag */
1040static int fcntl_setfl(int fd, int flag)
1041{
1042 int flags;
1043
1044 flags = fcntl(fd, F_GETFL);
1045 if (flags == -1) {
1046 return -errno;
1047 }
1048 if (fcntl(fd, F_SETFL, flags | flag) == -1) {
1049 return -errno;
1050 }
1051 return 0;
1052}
1053
5cec2870 1054static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
23dece19 1055 int *open_flags, uint64_t perm, bool force_dup,
6ceabe6f 1056 Error **errp)
5cec2870
KW
1057{
1058 BDRVRawState *s = bs->opaque;
1059 int fd = -1;
1060 int ret;
23dece19
KW
1061 bool has_writers = perm &
1062 (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
5cec2870
KW
1063 int fcntl_flags = O_APPEND | O_NONBLOCK;
1064#ifdef O_NOATIME
1065 fcntl_flags |= O_NOATIME;
1066#endif
1067
1068 *open_flags = 0;
1069 if (s->type == FTYPE_CD) {
1070 *open_flags |= O_NONBLOCK;
1071 }
1072
23dece19 1073 raw_parse_flags(flags, open_flags, has_writers);
5cec2870
KW
1074
1075#ifdef O_ASYNC
1076 /* Not all operating systems have O_ASYNC, and those that don't
1077 * will not let us track the state into rs->open_flags (typically
1078 * you achieve the same effect with an ioctl, for example I_SETSIG
1079 * on Solaris). But we do not use O_ASYNC, so that's fine.
1080 */
1081 assert((s->open_flags & O_ASYNC) == 0);
1082#endif
1083
6ceabe6f
KW
1084 if (!force_dup && *open_flags == s->open_flags) {
1085 /* We're lucky, the existing fd is fine */
1086 return s->fd;
1087 }
1088
5cec2870
KW
1089 if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
1090 /* dup the original fd */
1091 fd = qemu_dup(s->fd);
1092 if (fd >= 0) {
1093 ret = fcntl_setfl(fd, *open_flags);
1094 if (ret) {
1095 qemu_close(fd);
1096 fd = -1;
1097 }
1098 }
1099 }
1100
b18a24a9 1101 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
5cec2870
KW
1102 if (fd == -1) {
1103 const char *normalized_filename = bs->filename;
1104 ret = raw_normalize_devicepath(&normalized_filename, errp);
1105 if (ret >= 0) {
b18a24a9 1106 fd = qemu_open(normalized_filename, *open_flags, errp);
5cec2870 1107 if (fd == -1) {
5cec2870
KW
1108 return -1;
1109 }
1110 }
1111 }
1112
bca5283b
KW
1113 if (fd != -1 && (*open_flags & O_RDWR)) {
1114 ret = check_hdev_writable(fd);
1115 if (ret < 0) {
1116 qemu_close(fd);
1117 error_setg_errno(errp, -ret, "The device is not writable");
1118 return -1;
1119 }
1120 }
1121
5cec2870
KW
1122 return fd;
1123}
1124
eeb6b45d
JC
1125static int raw_reopen_prepare(BDRVReopenState *state,
1126 BlockReopenQueue *queue, Error **errp)
1127{
1128 BDRVRawState *s;
4e6d13c9 1129 BDRVRawReopenState *rs;
31be8a2a 1130 QemuOpts *opts;
a6aeca0c 1131 int ret;
eeb6b45d
JC
1132
1133 assert(state != NULL);
1134 assert(state->bs != NULL);
1135
1136 s = state->bs->opaque;
1137
5839e53b 1138 state->opaque = g_new0(BDRVRawReopenState, 1);
4e6d13c9 1139 rs = state->opaque;
31be8a2a
SH
1140
1141 /* Handle options changes */
1142 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
af175e85 1143 if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
31be8a2a
SH
1144 ret = -EINVAL;
1145 goto out;
1146 }
1147
f357fcd8 1148 rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
8d324575
AG
1149 rs->check_cache_dropped =
1150 qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
1151
1152 /* This driver's reopen function doesn't currently allow changing
1153 * other options, so let's put them back in the original QDict and
1154 * bdrv_reopen_prepare() will detect changes and complain. */
1155 qemu_opts_to_qdict(opts, state->options);
eeb6b45d 1156
72373e40
VSO
1157 /*
1158 * As part of reopen prepare we also want to create new fd by
1159 * raw_reconfigure_getfd(). But it wants updated "perm", when in
1160 * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1161 * permission update. Happily, permission update is always a part (a seprate
1162 * stage) of bdrv_reopen_multiple() so we can rely on this fact and
1163 * reconfigure fd in raw_check_perm().
1164 */
df26a350 1165
e0c9cf3a 1166 s->reopen_state = state;
a6aeca0c 1167 ret = 0;
72373e40 1168
31be8a2a
SH
1169out:
1170 qemu_opts_del(opts);
eeb6b45d
JC
1171 return ret;
1172}
1173
eeb6b45d
JC
1174static void raw_reopen_commit(BDRVReopenState *state)
1175{
4e6d13c9 1176 BDRVRawReopenState *rs = state->opaque;
eeb6b45d
JC
1177 BDRVRawState *s = state->bs->opaque;
1178
f357fcd8 1179 s->drop_cache = rs->drop_cache;
31be8a2a 1180 s->check_cache_dropped = rs->check_cache_dropped;
4e6d13c9 1181 s->open_flags = rs->open_flags;
eeb6b45d
JC
1182 g_free(state->opaque);
1183 state->opaque = NULL;
e0c9cf3a
KW
1184
1185 assert(s->reopen_state == state);
1186 s->reopen_state = NULL;
eeb6b45d
JC
1187}
1188
1189
1190static void raw_reopen_abort(BDRVReopenState *state)
1191{
4e6d13c9 1192 BDRVRawReopenState *rs = state->opaque;
e0c9cf3a 1193 BDRVRawState *s = state->bs->opaque;
eeb6b45d
JC
1194
1195 /* nothing to do if NULL, we didn't get far enough */
4e6d13c9 1196 if (rs == NULL) {
eeb6b45d
JC
1197 return;
1198 }
1199
eeb6b45d
JC
1200 g_free(state->opaque);
1201 state->opaque = NULL;
e0c9cf3a
KW
1202
1203 assert(s->reopen_state == state);
1204 s->reopen_state = NULL;
eeb6b45d
JC
1205}
1206
18473467 1207static int hdev_get_max_hw_transfer(int fd, struct stat *st)
6f607174
FZ
1208{
1209#ifdef BLKSECTGET
18473467
PB
1210 if (S_ISBLK(st->st_mode)) {
1211 unsigned short max_sectors = 0;
1212 if (ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
1213 return max_sectors * 512;
1214 }
6f607174 1215 } else {
18473467
PB
1216 int max_bytes = 0;
1217 if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
1218 return max_bytes;
1219 }
6f607174 1220 }
18473467 1221 return -errno;
6f607174
FZ
1222#else
1223 return -ENOSYS;
1224#endif
1225}
1226
a735b56e
SL
1227/*
1228 * Get a sysfs attribute value as character string.
1229 */
9103f1ce 1230#ifdef CONFIG_LINUX
a735b56e
SL
1231static int get_sysfs_str_val(struct stat *st, const char *attribute,
1232 char **val) {
1233 g_autofree char *sysfspath = NULL;
9103f1ce 1234 int ret;
a735b56e 1235 size_t len;
867eccfe 1236
a735b56e 1237 if (!S_ISBLK(st->st_mode)) {
8ad5ab61
PB
1238 return -ENOTSUP;
1239 }
1240
a735b56e
SL
1241 sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/%s",
1242 major(st->st_rdev), minor(st->st_rdev),
1243 attribute);
1244 ret = g_file_get_contents(sysfspath, val, &len, NULL);
1245 if (ret == -1) {
1246 return -ENOENT;
8ad5ab61
PB
1247 }
1248
a735b56e
SL
1249 /* The file is ended with '\n' */
1250 char *p;
1251 p = *val;
1252 if (*(p + len - 1) == '\n') {
1253 *(p + len - 1) = '\0';
9103f1ce 1254 }
a735b56e
SL
1255 return ret;
1256}
1257#endif
1258
6d43eaa3 1259#if defined(CONFIG_BLKZONED)
a735b56e
SL
1260static int get_sysfs_zoned_model(struct stat *st, BlockZoneModel *zoned)
1261{
1262 g_autofree char *val = NULL;
1263 int ret;
1264
1265 ret = get_sysfs_str_val(st, "zoned", &val);
9103f1ce 1266 if (ret < 0) {
a735b56e 1267 return ret;
9103f1ce 1268 }
a735b56e
SL
1269
1270 if (strcmp(val, "host-managed") == 0) {
1271 *zoned = BLK_Z_HM;
1272 } else if (strcmp(val, "host-aware") == 0) {
1273 *zoned = BLK_Z_HA;
1274 } else if (strcmp(val, "none") == 0) {
1275 *zoned = BLK_Z_NONE;
1276 } else {
1277 return -ENOTSUP;
9103f1ce 1278 }
a735b56e
SL
1279 return 0;
1280}
6d43eaa3 1281#endif /* defined(CONFIG_BLKZONED) */
9103f1ce 1282
a735b56e
SL
1283/*
1284 * Get a sysfs attribute value as a long integer.
1285 */
1286#ifdef CONFIG_LINUX
1287static long get_sysfs_long_val(struct stat *st, const char *attribute)
1288{
1289 g_autofree char *str = NULL;
1290 const char *end;
1291 long val;
1292 int ret;
1293
1294 ret = get_sysfs_str_val(st, attribute, &str);
1295 if (ret < 0) {
1296 return ret;
1297 }
1298
1299 /* The file is ended with '\n', pass 'end' to accept that. */
1300 ret = qemu_strtol(str, &end, 10, &val);
1301 if (ret == 0 && end && *end == '\0') {
1302 ret = val;
fed414df 1303 }
9103f1ce 1304 return ret;
a735b56e
SL
1305}
1306#endif
1307
1308static int hdev_get_max_segments(int fd, struct stat *st)
1309{
1310#ifdef CONFIG_LINUX
1311 int ret;
1312
1313 if (S_ISCHR(st->st_mode)) {
1314 if (ioctl(fd, SG_GET_SG_TABLESIZE, &ret) == 0) {
1315 return ret;
1316 }
1317 return -ENOTSUP;
1318 }
1319 return get_sysfs_long_val(st, "max_segments");
9103f1ce
FZ
1320#else
1321 return -ENOTSUP;
1322#endif
1323}
1324
6d43eaa3 1325#if defined(CONFIG_BLKZONED)
a3c41f06
SL
1326/*
1327 * If the reset_all flag is true, then the wps of zone whose state is
1328 * not readonly or offline should be all reset to the start sector.
1329 * Else, take the real wp of the device.
1330 */
1331static int get_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1332 unsigned int nrz, bool reset_all)
1333{
1334 struct blk_zone *blkz;
1335 size_t rep_size;
1336 uint64_t sector = offset >> BDRV_SECTOR_BITS;
1337 BlockZoneWps *wps = bs->wps;
1338 unsigned int j = offset / bs->bl.zone_size;
1339 unsigned int n = 0, i = 0;
1340 int ret;
1341 rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
1342 g_autofree struct blk_zone_report *rep = NULL;
1343
1344 rep = g_malloc(rep_size);
1345 blkz = (struct blk_zone *)(rep + 1);
1346 while (n < nrz) {
1347 memset(rep, 0, rep_size);
1348 rep->sector = sector;
1349 rep->nr_zones = nrz - n;
1350
1351 do {
1352 ret = ioctl(fd, BLKREPORTZONE, rep);
1353 } while (ret != 0 && errno == EINTR);
1354 if (ret != 0) {
1355 error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
1356 fd, offset, errno);
1357 return -errno;
1358 }
1359
1360 if (!rep->nr_zones) {
1361 break;
1362 }
1363
1364 for (i = 0; i < rep->nr_zones; ++i, ++n, ++j) {
1365 /*
1366 * The wp tracking cares only about sequential writes required and
1367 * sequential write preferred zones so that the wp can advance to
1368 * the right location.
1369 * Use the most significant bit of the wp location to indicate the
1370 * zone type: 0 for SWR/SWP zones and 1 for conventional zones.
1371 */
1372 if (blkz[i].type == BLK_ZONE_TYPE_CONVENTIONAL) {
1373 wps->wp[j] |= 1ULL << 63;
1374 } else {
1375 switch(blkz[i].cond) {
1376 case BLK_ZONE_COND_FULL:
1377 case BLK_ZONE_COND_READONLY:
1378 /* Zone not writable */
1379 wps->wp[j] = (blkz[i].start + blkz[i].len) << BDRV_SECTOR_BITS;
1380 break;
1381 case BLK_ZONE_COND_OFFLINE:
1382 /* Zone not writable nor readable */
1383 wps->wp[j] = (blkz[i].start) << BDRV_SECTOR_BITS;
1384 break;
1385 default:
1386 if (reset_all) {
1387 wps->wp[j] = blkz[i].start << BDRV_SECTOR_BITS;
1388 } else {
1389 wps->wp[j] = blkz[i].wp << BDRV_SECTOR_BITS;
1390 }
1391 break;
1392 }
1393 }
1394 }
1395 sector = blkz[i - 1].start + blkz[i - 1].len;
1396 }
1397
1398 return 0;
1399}
1400
1401static void update_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1402 unsigned int nrz)
1403{
1404 if (get_zones_wp(bs, fd, offset, nrz, 0) < 0) {
1405 error_report("update zone wp failed");
1406 }
1407}
1408
a735b56e
SL
1409static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1410 Error **errp)
1411{
a3c41f06 1412 BDRVRawState *s = bs->opaque;
a735b56e
SL
1413 BlockZoneModel zoned;
1414 int ret;
1415
1416 bs->bl.zoned = BLK_Z_NONE;
1417
1418 ret = get_sysfs_zoned_model(st, &zoned);
1419 if (ret < 0 || zoned == BLK_Z_NONE) {
1420 return;
1421 }
1422 bs->bl.zoned = zoned;
6d43eaa3
SL
1423
1424 ret = get_sysfs_long_val(st, "max_open_zones");
1425 if (ret >= 0) {
1426 bs->bl.max_open_zones = ret;
1427 }
1428
1429 ret = get_sysfs_long_val(st, "max_active_zones");
1430 if (ret >= 0) {
1431 bs->bl.max_active_zones = ret;
1432 }
1433
1434 /*
1435 * The zoned device must at least have zone size and nr_zones fields.
1436 */
1437 ret = get_sysfs_long_val(st, "chunk_sectors");
1438 if (ret < 0) {
1439 error_setg_errno(errp, -ret, "Unable to read chunk_sectors "
1440 "sysfs attribute");
1441 return;
1442 } else if (!ret) {
1443 error_setg(errp, "Read 0 from chunk_sectors sysfs attribute");
1444 return;
1445 }
1446 bs->bl.zone_size = ret << BDRV_SECTOR_BITS;
1447
1448 ret = get_sysfs_long_val(st, "nr_zones");
1449 if (ret < 0) {
1450 error_setg_errno(errp, -ret, "Unable to read nr_zones "
1451 "sysfs attribute");
1452 return;
1453 } else if (!ret) {
1454 error_setg(errp, "Read 0 from nr_zones sysfs attribute");
1455 return;
1456 }
1457 bs->bl.nr_zones = ret;
1458
1459 ret = get_sysfs_long_val(st, "zone_append_max_bytes");
1460 if (ret > 0) {
1461 bs->bl.max_append_sectors = ret >> BDRV_SECTOR_BITS;
1462 }
a3c41f06
SL
1463
1464 ret = get_sysfs_long_val(st, "physical_block_size");
1465 if (ret >= 0) {
1466 bs->bl.write_granularity = ret;
1467 }
1468
1469 /* The refresh_limits() function can be called multiple times. */
1470 g_free(bs->wps);
1471 bs->wps = g_malloc(sizeof(BlockZoneWps) +
1472 sizeof(int64_t) * bs->bl.nr_zones);
1473 ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 0);
1474 if (ret < 0) {
1475 error_setg_errno(errp, -ret, "report wps failed");
1476 bs->wps = NULL;
1477 return;
1478 }
1479 qemu_co_mutex_init(&bs->wps->colock);
6d43eaa3
SL
1480}
1481#else /* !defined(CONFIG_BLKZONED) */
1482static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1483 Error **errp)
1484{
1485 bs->bl.zoned = BLK_Z_NONE;
a735b56e 1486}
6d43eaa3 1487#endif /* !defined(CONFIG_BLKZONED) */
a735b56e 1488
3baca891 1489static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
c25f53b0
PB
1490{
1491 BDRVRawState *s = bs->opaque;
18473467 1492 struct stat st;
6f607174 1493
5dbd0ce1 1494 s->needs_alignment = raw_needs_alignment(bs);
18473467 1495 raw_probe_alignment(bs, s->fd, errp);
5dbd0ce1 1496
18473467 1497 bs->bl.min_mem_alignment = s->buf_align;
8e3b0cbb 1498 bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size());
18473467
PB
1499
1500 /*
1501 * Maximum transfers are best effort, so it is okay to ignore any
1502 * errors. That said, based on the man page errors in fstat would be
1503 * very much unexpected; the only possible case seems to be ENOMEM.
1504 */
1505 if (fstat(s->fd, &st)) {
1506 return;
1507 }
1508
0dfc7af2
AO
1509#if defined(__APPLE__) && (__MACH__)
1510 struct statfs buf;
1511
1512 if (!fstatfs(s->fd, &buf)) {
1513 bs->bl.opt_transfer = buf.f_iosize;
1514 bs->bl.pdiscard_alignment = buf.f_bsize;
1515 }
1516#endif
1517
006e1962 1518 if (bdrv_is_sg(bs) || S_ISBLK(st.st_mode)) {
18473467 1519 int ret = hdev_get_max_hw_transfer(s->fd, &st);
867eccfe
ML
1520
1521 if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
18473467 1522 bs->bl.max_hw_transfer = ret;
867eccfe
ML
1523 }
1524
18473467 1525 ret = hdev_get_max_segments(s->fd, &st);
867eccfe 1526 if (ret > 0) {
cc071629 1527 bs->bl.max_hw_iov = ret;
6f607174
FZ
1528 }
1529 }
a735b56e
SL
1530
1531 raw_refresh_zoned_limits(bs, &st, errp);
c25f53b0 1532}
83f64091 1533
1a9335e4
ET
1534static int check_for_dasd(int fd)
1535{
1536#ifdef BIODASDINFO2
1537 struct dasd_information2_t info = {0};
1538
1539 return ioctl(fd, BIODASDINFO2, &info);
1540#else
1541 return -1;
1542#endif
1543}
1544
1545/**
1546 * Try to get @bs's logical and physical block size.
1547 * On success, store them in @bsz and return zero.
1548 * On failure, return negative errno.
1549 */
1550static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1551{
1552 BDRVRawState *s = bs->opaque;
1553 int ret;
1554
6d43eaa3 1555 /* If DASD or zoned devices, get blocksizes */
1a9335e4 1556 if (check_for_dasd(s->fd) < 0) {
6d43eaa3
SL
1557 /* zoned devices are not DASD */
1558 if (bs->bl.zoned == BLK_Z_NONE) {
1559 return -ENOTSUP;
1560 }
1a9335e4
ET
1561 }
1562 ret = probe_logical_blocksize(s->fd, &bsz->log);
1563 if (ret < 0) {
1564 return ret;
1565 }
1566 return probe_physical_blocksize(s->fd, &bsz->phys);
1567}
1568
1569/**
1570 * Try to get @bs's geometry: cyls, heads, sectors.
1571 * On success, store them in @geo and return 0.
1572 * On failure return -errno.
1573 * (Allows block driver to assign default geometry values that guest sees)
1574 */
1575#ifdef __linux__
1576static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1577{
1578 BDRVRawState *s = bs->opaque;
1579 struct hd_geometry ioctl_geo = {0};
1a9335e4
ET
1580
1581 /* If DASD, get its geometry */
1582 if (check_for_dasd(s->fd) < 0) {
1583 return -ENOTSUP;
1584 }
1585 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1586 return -errno;
1587 }
1588 /* HDIO_GETGEO may return success even though geo contains zeros
1589 (e.g. certain multipath setups) */
1590 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1591 return -ENOTSUP;
1592 }
1593 /* Do not return a geometry for partition */
1594 if (ioctl_geo.start != 0) {
1595 return -ENOTSUP;
1596 }
1597 geo->heads = ioctl_geo.heads;
1598 geo->sectors = ioctl_geo.sectors;
1a9335e4
ET
1599 geo->cylinders = ioctl_geo.cylinders;
1600
1601 return 0;
1602}
1603#else /* __linux__ */
1604static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1605{
1606 return -ENOTSUP;
1607}
1608#endif
1609
03425671
KW
1610#if defined(__linux__)
1611static int handle_aiocb_ioctl(void *opaque)
de81a169 1612{
03425671 1613 RawPosixAIOData *aiocb = opaque;
de81a169
PB
1614 int ret;
1615
37b0b24e
NI
1616 ret = RETRY_ON_EINTR(
1617 ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf)
1618 );
de81a169
PB
1619 if (ret == -1) {
1620 return -errno;
1621 }
1622
b608c8dc 1623 return 0;
de81a169 1624}
03425671 1625#endif /* linux */
de81a169 1626
06dc9bd5 1627static int handle_aiocb_flush(void *opaque)
de81a169 1628{
06dc9bd5 1629 RawPosixAIOData *aiocb = opaque;
e5bcf967 1630 BDRVRawState *s = aiocb->bs->opaque;
de81a169
PB
1631 int ret;
1632
e5bcf967 1633 if (s->page_cache_inconsistent) {
c7ddc882 1634 return -s->page_cache_inconsistent;
e5bcf967
KW
1635 }
1636
de81a169
PB
1637 ret = qemu_fdatasync(aiocb->aio_fildes);
1638 if (ret == -1) {
60ff2ae2
DB
1639 trace_file_flush_fdatasync_failed(errno);
1640
e5bcf967
KW
1641 /* There is no clear definition of the semantics of a failing fsync(),
1642 * so we may have to assume the worst. The sad truth is that this
1643 * assumption is correct for Linux. Some pages are now probably marked
1644 * clean in the page cache even though they are inconsistent with the
1645 * on-disk contents. The next fdatasync() call would succeed, but no
1646 * further writeback attempt will be made. We can't get back to a state
1647 * in which we know what is on disk (we would have to rewrite
1648 * everything that was touched since the last fdatasync() at least), so
1649 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1650 * really defined, I have little hope that other OSes are doing better.
1651 *
1652 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1653 * cache. */
1654 if ((s->open_flags & O_DIRECT) == 0) {
c7ddc882 1655 s->page_cache_inconsistent = errno;
e5bcf967 1656 }
de81a169
PB
1657 return -errno;
1658 }
1659 return 0;
1660}
1661
1662#ifdef CONFIG_PREADV
1663
1664static bool preadv_present = true;
1665
1666static ssize_t
1667qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1668{
1669 return preadv(fd, iov, nr_iov, offset);
1670}
1671
1672static ssize_t
1673qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1674{
1675 return pwritev(fd, iov, nr_iov, offset);
1676}
1677
1678#else
1679
1680static bool preadv_present = false;
1681
1682static ssize_t
1683qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1684{
1685 return -ENOSYS;
1686}
1687
1688static ssize_t
1689qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1690{
1691 return -ENOSYS;
1692}
1693
1694#endif
1695
1696static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1697{
1698 ssize_t len;
1699
37b0b24e
NI
1700 len = RETRY_ON_EINTR(
1701 (aiocb->aio_type & QEMU_AIO_WRITE) ?
1702 qemu_pwritev(aiocb->aio_fildes,
1703 aiocb->io.iov,
1704 aiocb->io.niov,
1705 aiocb->aio_offset) :
1706 qemu_preadv(aiocb->aio_fildes,
1707 aiocb->io.iov,
1708 aiocb->io.niov,
1709 aiocb->aio_offset)
1710 );
de81a169
PB
1711
1712 if (len == -1) {
1713 return -errno;
1714 }
1715 return len;
1716}
1717
1718/*
1719 * Read/writes the data to/from a given linear buffer.
1720 *
1721 * Returns the number of bytes handles or -errno in case of an error. Short
1722 * reads are only returned if the end of the file is reached.
1723 */
1724static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1725{
1726 ssize_t offset = 0;
1727 ssize_t len;
1728
1729 while (offset < aiocb->aio_nbytes) {
1730 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1731 len = pwrite(aiocb->aio_fildes,
1732 (const char *)buf + offset,
1733 aiocb->aio_nbytes - offset,
1734 aiocb->aio_offset + offset);
1735 } else {
1736 len = pread(aiocb->aio_fildes,
1737 buf + offset,
1738 aiocb->aio_nbytes - offset,
1739 aiocb->aio_offset + offset);
1740 }
1741 if (len == -1 && errno == EINTR) {
1742 continue;
61ed73cf
SH
1743 } else if (len == -1 && errno == EINVAL &&
1744 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1745 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1746 offset > 0) {
1747 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1748 * after a short read. Assume that O_DIRECT short reads only occur
1749 * at EOF. Therefore this is a short read, not an I/O error.
1750 */
1751 break;
de81a169
PB
1752 } else if (len == -1) {
1753 offset = -errno;
1754 break;
1755 } else if (len == 0) {
1756 break;
1757 }
1758 offset += len;
1759 }
1760
1761 return offset;
1762}
1763
999e6b69 1764static int handle_aiocb_rw(void *opaque)
de81a169 1765{
999e6b69 1766 RawPosixAIOData *aiocb = opaque;
de81a169
PB
1767 ssize_t nbytes;
1768 char *buf;
1769
1770 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1771 /*
1772 * If there is just a single buffer, and it is properly aligned
1773 * we can just use plain pread/pwrite without any problems.
1774 */
d57c44d0 1775 if (aiocb->io.niov == 1) {
54c7ca1b
KW
1776 nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
1777 goto out;
de81a169
PB
1778 }
1779 /*
1780 * We have more than one iovec, and all are properly aligned.
1781 *
1782 * Try preadv/pwritev first and fall back to linearizing the
1783 * buffer if it's not supported.
1784 */
1785 if (preadv_present) {
1786 nbytes = handle_aiocb_rw_vector(aiocb);
1787 if (nbytes == aiocb->aio_nbytes ||
1788 (nbytes < 0 && nbytes != -ENOSYS)) {
54c7ca1b 1789 goto out;
de81a169
PB
1790 }
1791 preadv_present = false;
1792 }
1793
1794 /*
1795 * XXX(hch): short read/write. no easy way to handle the reminder
1796 * using these interfaces. For now retry using plain
1797 * pread/pwrite?
1798 */
1799 }
1800
1801 /*
1802 * Ok, we have to do it the hard way, copy all segments into
1803 * a single aligned buffer.
1804 */
50d4a858
KW
1805 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1806 if (buf == NULL) {
54c7ca1b
KW
1807 nbytes = -ENOMEM;
1808 goto out;
50d4a858
KW
1809 }
1810
de81a169
PB
1811 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1812 char *p = buf;
1813 int i;
1814
d57c44d0
KW
1815 for (i = 0; i < aiocb->io.niov; ++i) {
1816 memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1817 p += aiocb->io.iov[i].iov_len;
de81a169 1818 }
8eb029c2 1819 assert(p - buf == aiocb->aio_nbytes);
de81a169
PB
1820 }
1821
1822 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1823 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1824 char *p = buf;
1825 size_t count = aiocb->aio_nbytes, copy;
1826 int i;
1827
d57c44d0 1828 for (i = 0; i < aiocb->io.niov && count; ++i) {
de81a169 1829 copy = count;
d57c44d0
KW
1830 if (copy > aiocb->io.iov[i].iov_len) {
1831 copy = aiocb->io.iov[i].iov_len;
de81a169 1832 }
d57c44d0 1833 memcpy(aiocb->io.iov[i].iov_base, p, copy);
8eb029c2 1834 assert(count >= copy);
de81a169
PB
1835 p += copy;
1836 count -= copy;
1837 }
8eb029c2 1838 assert(count == 0);
de81a169
PB
1839 }
1840 qemu_vfree(buf);
1841
54c7ca1b
KW
1842out:
1843 if (nbytes == aiocb->aio_nbytes) {
1844 return 0;
1845 } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
1846 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1847 return -EINVAL;
1848 } else {
1849 iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
1850 0, aiocb->aio_nbytes - nbytes);
1851 return 0;
1852 }
1853 } else {
1854 assert(nbytes < 0);
1855 return nbytes;
1856 }
de81a169
PB
1857}
1858
0dfc7af2 1859#if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1486df0e
DL
1860static int translate_err(int err)
1861{
1862 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1863 err == -ENOTTY) {
1864 err = -ENOTSUP;
1865 }
1866 return err;
1867}
0dfc7af2 1868#endif
1486df0e 1869
d50d8222 1870#ifdef CONFIG_FALLOCATE
0b991712
DL
1871static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1872{
1873 do {
1874 if (fallocate(fd, mode, offset, len) == 0) {
1875 return 0;
1876 }
1877 } while (errno == EINTR);
1878 return translate_err(-errno);
1879}
1880#endif
1881
37cc9f7f 1882static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
97a2ae34 1883{
37cc9f7f 1884 int ret = -ENOTSUP;
97a2ae34
PB
1885 BDRVRawState *s = aiocb->bs->opaque;
1886
37cc9f7f 1887 if (!s->has_write_zeroes) {
97a2ae34
PB
1888 return -ENOTSUP;
1889 }
1890
97a2ae34 1891#ifdef BLKZEROOUT
738301e1
KW
1892 /* The BLKZEROOUT implementation in the kernel doesn't set
1893 * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1894 * fallbacks. */
1895 if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1896 do {
1897 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1898 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1899 return 0;
1900 }
1901 } while (errno == EINTR);
37cc9f7f 1902
738301e1 1903 ret = translate_err(-errno);
effecce6
KW
1904 if (ret == -ENOTSUP) {
1905 s->has_write_zeroes = false;
1906 }
738301e1 1907 }
97a2ae34 1908#endif
97a2ae34 1909
97a2ae34
PB
1910 return ret;
1911}
1912
7154d8ae 1913static int handle_aiocb_write_zeroes(void *opaque)
37cc9f7f 1914{
7154d8ae 1915 RawPosixAIOData *aiocb = opaque;
70d9110b 1916#ifdef CONFIG_FALLOCATE
b2c6f23f 1917 BDRVRawState *s = aiocb->bs->opaque;
70d9110b
DL
1918 int64_t len;
1919#endif
37cc9f7f
DL
1920
1921 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1922 return handle_aiocb_write_zeroes_block(aiocb);
1923 }
1924
b953f075
DL
1925#ifdef CONFIG_FALLOCATE_ZERO_RANGE
1926 if (s->has_write_zeroes) {
1927 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1928 aiocb->aio_offset, aiocb->aio_nbytes);
fa95e9fb
TH
1929 if (ret == -ENOTSUP) {
1930 s->has_write_zeroes = false;
1931 } else if (ret == 0 || ret != -EINVAL) {
b953f075
DL
1932 return ret;
1933 }
fa95e9fb
TH
1934 /*
1935 * Note: Some file systems do not like unaligned byte ranges, and
1936 * return EINVAL in such a case, though they should not do it according
1937 * to the man-page of fallocate(). Thus we simply ignore this return
1938 * value and try the other fallbacks instead.
1939 */
b953f075
DL
1940 }
1941#endif
1942
1cdc3239
DL
1943#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1944 if (s->has_discard && s->has_fallocate) {
1945 int ret = do_fallocate(s->fd,
1946 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1947 aiocb->aio_offset, aiocb->aio_nbytes);
1948 if (ret == 0) {
1949 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1950 if (ret == 0 || ret != -ENOTSUP) {
1951 return ret;
1952 }
1953 s->has_fallocate = false;
73ebf297
TH
1954 } else if (ret == -EINVAL) {
1955 /*
1956 * Some file systems like older versions of GPFS do not like un-
1957 * aligned byte ranges, and return EINVAL in such a case, though
1958 * they should not do it according to the man-page of fallocate().
1959 * Warn about the bad filesystem and try the final fallback instead.
1960 */
1961 warn_report_once("Your file system is misbehaving: "
1962 "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
68857f13 1963 "Please report this bug to your file system "
73ebf297 1964 "vendor.");
1cdc3239
DL
1965 } else if (ret != -ENOTSUP) {
1966 return ret;
1967 } else {
1968 s->has_discard = false;
1969 }
1970 }
1971#endif
1972
d50d8222 1973#ifdef CONFIG_FALLOCATE
70d9110b
DL
1974 /* Last resort: we are trying to extend the file with zeroed data. This
1975 * can be done via fallocate(fd, 0) */
005ee3cd 1976 len = raw_co_getlength(aiocb->bs);
70d9110b 1977 if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
d50d8222
DL
1978 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1979 if (ret == 0 || ret != -ENOTSUP) {
1980 return ret;
1981 }
1982 s->has_fallocate = false;
1983 }
1984#endif
1985
37cc9f7f
DL
1986 return -ENOTSUP;
1987}
1988
7154d8ae 1989static int handle_aiocb_write_zeroes_unmap(void *opaque)
34fa110e 1990{
7154d8ae 1991 RawPosixAIOData *aiocb = opaque;
34fa110e 1992 BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
34fa110e
KW
1993
1994 /* First try to write zeros and unmap at the same time */
1995
1996#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
b3ac2b94
SS
1997 int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1998 aiocb->aio_offset, aiocb->aio_nbytes);
bae127d4
AD
1999 switch (ret) {
2000 case -ENOTSUP:
2001 case -EINVAL:
ece4fa91 2002 case -EBUSY:
bae127d4
AD
2003 break;
2004 default:
34fa110e
KW
2005 return ret;
2006 }
2007#endif
2008
34fa110e
KW
2009 /* If we couldn't manage to unmap while guaranteed that the area reads as
2010 * all-zero afterwards, just write zeroes without unmapping */
b3ac2b94 2011 return handle_aiocb_write_zeroes(aiocb);
34fa110e
KW
2012}
2013
1efad060
FZ
2014#ifndef HAVE_COPY_FILE_RANGE
2015static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
2016 off_t *out_off, size_t len, unsigned int flags)
2017{
2018#ifdef __NR_copy_file_range
2019 return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
2020 out_off, len, flags);
2021#else
2022 errno = ENOSYS;
2023 return -1;
2024#endif
2025}
2026#endif
2027
6d43eaa3
SL
2028/*
2029 * parse_zone - Fill a zone descriptor
2030 */
2031#if defined(CONFIG_BLKZONED)
2032static inline int parse_zone(struct BlockZoneDescriptor *zone,
2033 const struct blk_zone *blkz) {
2034 zone->start = blkz->start << BDRV_SECTOR_BITS;
2035 zone->length = blkz->len << BDRV_SECTOR_BITS;
2036 zone->wp = blkz->wp << BDRV_SECTOR_BITS;
2037
2038#ifdef HAVE_BLK_ZONE_REP_CAPACITY
2039 zone->cap = blkz->capacity << BDRV_SECTOR_BITS;
2040#else
2041 zone->cap = blkz->len << BDRV_SECTOR_BITS;
2042#endif
2043
2044 switch (blkz->type) {
2045 case BLK_ZONE_TYPE_SEQWRITE_REQ:
2046 zone->type = BLK_ZT_SWR;
2047 break;
2048 case BLK_ZONE_TYPE_SEQWRITE_PREF:
2049 zone->type = BLK_ZT_SWP;
2050 break;
2051 case BLK_ZONE_TYPE_CONVENTIONAL:
2052 zone->type = BLK_ZT_CONV;
2053 break;
2054 default:
2055 error_report("Unsupported zone type: 0x%x", blkz->type);
2056 return -ENOTSUP;
2057 }
2058
2059 switch (blkz->cond) {
2060 case BLK_ZONE_COND_NOT_WP:
2061 zone->state = BLK_ZS_NOT_WP;
2062 break;
2063 case BLK_ZONE_COND_EMPTY:
2064 zone->state = BLK_ZS_EMPTY;
2065 break;
2066 case BLK_ZONE_COND_IMP_OPEN:
2067 zone->state = BLK_ZS_IOPEN;
2068 break;
2069 case BLK_ZONE_COND_EXP_OPEN:
2070 zone->state = BLK_ZS_EOPEN;
2071 break;
2072 case BLK_ZONE_COND_CLOSED:
2073 zone->state = BLK_ZS_CLOSED;
2074 break;
2075 case BLK_ZONE_COND_READONLY:
2076 zone->state = BLK_ZS_RDONLY;
2077 break;
2078 case BLK_ZONE_COND_FULL:
2079 zone->state = BLK_ZS_FULL;
2080 break;
2081 case BLK_ZONE_COND_OFFLINE:
2082 zone->state = BLK_ZS_OFFLINE;
2083 break;
2084 default:
2085 error_report("Unsupported zone state: 0x%x", blkz->cond);
2086 return -ENOTSUP;
2087 }
2088 return 0;
2089}
2090#endif
2091
2092#if defined(CONFIG_BLKZONED)
2093static int handle_aiocb_zone_report(void *opaque)
2094{
2095 RawPosixAIOData *aiocb = opaque;
2096 int fd = aiocb->aio_fildes;
2097 unsigned int *nr_zones = aiocb->zone_report.nr_zones;
2098 BlockZoneDescriptor *zones = aiocb->zone_report.zones;
2099 /* zoned block devices use 512-byte sectors */
2100 uint64_t sector = aiocb->aio_offset / 512;
2101
2102 struct blk_zone *blkz;
2103 size_t rep_size;
2104 unsigned int nrz;
2105 int ret;
2106 unsigned int n = 0, i = 0;
2107
2108 nrz = *nr_zones;
2109 rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
2110 g_autofree struct blk_zone_report *rep = NULL;
2111 rep = g_malloc(rep_size);
2112
2113 blkz = (struct blk_zone *)(rep + 1);
2114 while (n < nrz) {
2115 memset(rep, 0, rep_size);
2116 rep->sector = sector;
2117 rep->nr_zones = nrz - n;
2118
2119 do {
2120 ret = ioctl(fd, BLKREPORTZONE, rep);
2121 } while (ret != 0 && errno == EINTR);
2122 if (ret != 0) {
2123 error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
2124 fd, sector, errno);
2125 return -errno;
2126 }
2127
2128 if (!rep->nr_zones) {
2129 break;
2130 }
2131
2132 for (i = 0; i < rep->nr_zones; i++, n++) {
2133 ret = parse_zone(&zones[n], &blkz[i]);
2134 if (ret != 0) {
2135 return ret;
2136 }
2137
2138 /* The next report should start after the last zone reported */
2139 sector = blkz[i].start + blkz[i].len;
2140 }
2141 }
2142
2143 *nr_zones = n;
2144 return 0;
2145}
2146#endif
2147
2148#if defined(CONFIG_BLKZONED)
2149static int handle_aiocb_zone_mgmt(void *opaque)
2150{
2151 RawPosixAIOData *aiocb = opaque;
2152 int fd = aiocb->aio_fildes;
2153 uint64_t sector = aiocb->aio_offset / 512;
2154 int64_t nr_sectors = aiocb->aio_nbytes / 512;
2155 struct blk_zone_range range;
2156 int ret;
2157
2158 /* Execute the operation */
2159 range.sector = sector;
2160 range.nr_sectors = nr_sectors;
2161 do {
2162 ret = ioctl(fd, aiocb->zone_mgmt.op, &range);
2163 } while (ret != 0 && errno == EINTR);
2164
a3c41f06 2165 return ret < 0 ? -errno : ret;
6d43eaa3
SL
2166}
2167#endif
2168
58a209c4 2169static int handle_aiocb_copy_range(void *opaque)
1efad060 2170{
58a209c4 2171 RawPosixAIOData *aiocb = opaque;
1efad060
FZ
2172 uint64_t bytes = aiocb->aio_nbytes;
2173 off_t in_off = aiocb->aio_offset;
d57c44d0 2174 off_t out_off = aiocb->copy_range.aio_offset2;
1efad060
FZ
2175
2176 while (bytes) {
2177 ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
d57c44d0 2178 aiocb->copy_range.aio_fd2, &out_off,
1efad060 2179 bytes, 0);
ecc983a5 2180 trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
d57c44d0
KW
2181 aiocb->copy_range.aio_fd2, out_off, bytes,
2182 0, ret);
c436e3d0
FZ
2183 if (ret == 0) {
2184 /* No progress (e.g. when beyond EOF), let the caller fall back to
2185 * buffer I/O. */
2186 return -ENOSPC;
1efad060
FZ
2187 }
2188 if (ret < 0) {
c436e3d0
FZ
2189 switch (errno) {
2190 case ENOSYS:
1efad060 2191 return -ENOTSUP;
c436e3d0
FZ
2192 case EINTR:
2193 continue;
2194 default:
1efad060
FZ
2195 return -errno;
2196 }
2197 }
1efad060
FZ
2198 bytes -= ret;
2199 }
2200 return 0;
2201}
2202
46ee0f46 2203static int handle_aiocb_discard(void *opaque)
8238010b 2204{
46ee0f46 2205 RawPosixAIOData *aiocb = opaque;
13a02833 2206 int ret = -ENOTSUP;
8238010b
PB
2207 BDRVRawState *s = aiocb->bs->opaque;
2208
7ce21016
PB
2209 if (!s->has_discard) {
2210 return -ENOTSUP;
8238010b
PB
2211 }
2212
2213 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
2214#ifdef BLKDISCARD
2215 do {
2216 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
2217 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
2218 return 0;
2219 }
2220 } while (errno == EINTR);
2221
0dfc7af2 2222 ret = translate_err(-errno);
8238010b
PB
2223#endif
2224 } else {
8238010b 2225#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
0b991712
DL
2226 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
2227 aiocb->aio_offset, aiocb->aio_nbytes);
13a02833 2228 ret = translate_err(ret);
0dfc7af2
AO
2229#elif defined(__APPLE__) && (__MACH__)
2230 fpunchhole_t fpunchhole;
2231 fpunchhole.fp_flags = 0;
2232 fpunchhole.reserved = 0;
2233 fpunchhole.fp_offset = aiocb->aio_offset;
2234 fpunchhole.fp_length = aiocb->aio_nbytes;
2235 if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
2236 ret = errno == ENODEV ? -ENOTSUP : -errno;
2237 } else {
2238 ret = 0;
2239 }
8238010b
PB
2240#endif
2241 }
2242
1486df0e 2243 if (ret == -ENOTSUP) {
7ce21016 2244 s->has_discard = false;
8238010b
PB
2245 }
2246 return ret;
2247}
2248
3a20013f
NS
2249/*
2250 * Help alignment probing by allocating the first block.
2251 *
2252 * When reading with direct I/O from unallocated area on Gluster backed by XFS,
2253 * reading succeeds regardless of request length. In this case we fallback to
2254 * safe alignment which is not optimal. Allocating the first block avoids this
2255 * fallback.
2256 *
2257 * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
2258 * request alignment, so we use safe values.
2259 *
2260 * Returns: 0 on success, -errno on failure. Since this is an optimization,
2261 * caller may ignore failures.
2262 */
2263static int allocate_first_block(int fd, size_t max_size)
2264{
2265 size_t write_size = (max_size < MAX_BLOCKSIZE)
2266 ? BDRV_SECTOR_SIZE
2267 : MAX_BLOCKSIZE;
8e3b0cbb 2268 size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
3a20013f
NS
2269 void *buf;
2270 ssize_t n;
2271 int ret;
2272
2273 buf = qemu_memalign(max_align, write_size);
2274 memset(buf, 0, write_size);
2275
37b0b24e 2276 n = RETRY_ON_EINTR(pwrite(fd, buf, write_size, 0));
3a20013f
NS
2277
2278 ret = (n == -1) ? -errno : 0;
2279
2280 qemu_vfree(buf);
2281 return ret;
2282}
2283
29cb4c01 2284static int handle_aiocb_truncate(void *opaque)
93f4e2ff 2285{
29cb4c01 2286 RawPosixAIOData *aiocb = opaque;
93f4e2ff
KW
2287 int result = 0;
2288 int64_t current_length = 0;
2289 char *buf = NULL;
2290 struct stat st;
2291 int fd = aiocb->aio_fildes;
2292 int64_t offset = aiocb->aio_offset;
d57c44d0
KW
2293 PreallocMode prealloc = aiocb->truncate.prealloc;
2294 Error **errp = aiocb->truncate.errp;
93f4e2ff
KW
2295
2296 if (fstat(fd, &st) < 0) {
2297 result = -errno;
2298 error_setg_errno(errp, -result, "Could not stat file");
2299 return result;
2300 }
2301
2302 current_length = st.st_size;
d57c44d0 2303 if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
93f4e2ff
KW
2304 error_setg(errp, "Cannot use preallocation for shrinking files");
2305 return -ENOTSUP;
2306 }
2307
d57c44d0 2308 switch (prealloc) {
93f4e2ff
KW
2309#ifdef CONFIG_POSIX_FALLOCATE
2310 case PREALLOC_MODE_FALLOC:
2311 /*
2312 * Truncating before posix_fallocate() makes it about twice slower on
2313 * file systems that do not support fallocate(), trying to check if a
2314 * block is allocated before allocating it, so don't do that here.
2315 */
2316 if (offset != current_length) {
2317 result = -posix_fallocate(fd, current_length,
2318 offset - current_length);
2319 if (result != 0) {
2320 /* posix_fallocate() doesn't set errno. */
2321 error_setg_errno(errp, -result,
2322 "Could not preallocate new data");
3a20013f
NS
2323 } else if (current_length == 0) {
2324 /*
2325 * posix_fallocate() uses fallocate() if the filesystem
2326 * supports it, or fallback to manually writing zeroes. If
2327 * fallocate() was used, unaligned reads from the fallocated
2328 * area in raw_probe_alignment() will succeed, hence we need to
2329 * allocate the first block.
2330 *
2331 * Optimize future alignment probing; ignore failures.
2332 */
2333 allocate_first_block(fd, offset);
93f4e2ff
KW
2334 }
2335 } else {
2336 result = 0;
2337 }
2338 goto out;
2339#endif
2340 case PREALLOC_MODE_FULL:
2341 {
2342 int64_t num = 0, left = offset - current_length;
2343 off_t seek_result;
2344
2345 /*
2346 * Knowing the final size from the beginning could allow the file
2347 * system driver to do less allocations and possibly avoid
2348 * fragmentation of the file.
2349 */
2350 if (ftruncate(fd, offset) != 0) {
2351 result = -errno;
2352 error_setg_errno(errp, -result, "Could not resize file");
2353 goto out;
2354 }
2355
2356 buf = g_malloc0(65536);
2357
2358 seek_result = lseek(fd, current_length, SEEK_SET);
2359 if (seek_result < 0) {
2360 result = -errno;
2361 error_setg_errno(errp, -result,
2362 "Failed to seek to the old end of file");
2363 goto out;
2364 }
2365
2366 while (left > 0) {
2367 num = MIN(left, 65536);
2368 result = write(fd, buf, num);
2369 if (result < 0) {
a1c81f4f
FZ
2370 if (errno == EINTR) {
2371 continue;
2372 }
93f4e2ff
KW
2373 result = -errno;
2374 error_setg_errno(errp, -result,
2375 "Could not write zeros for preallocation");
2376 goto out;
2377 }
2378 left -= result;
2379 }
2380 if (result >= 0) {
2381 result = fsync(fd);
2382 if (result < 0) {
2383 result = -errno;
2384 error_setg_errno(errp, -result,
2385 "Could not flush file to disk");
2386 goto out;
2387 }
2388 }
2389 goto out;
2390 }
2391 case PREALLOC_MODE_OFF:
2392 if (ftruncate(fd, offset) != 0) {
2393 result = -errno;
2394 error_setg_errno(errp, -result, "Could not resize file");
3a20013f
NS
2395 } else if (current_length == 0 && offset > current_length) {
2396 /* Optimize future alignment probing; ignore failures. */
2397 allocate_first_block(fd, offset);
93f4e2ff
KW
2398 }
2399 return result;
2400 default:
2401 result = -ENOTSUP;
2402 error_setg(errp, "Unsupported preallocation mode: %s",
d57c44d0 2403 PreallocMode_str(prealloc));
93f4e2ff
KW
2404 return result;
2405 }
2406
2407out:
2408 if (result < 0) {
2409 if (ftruncate(fd, current_length) < 0) {
2410 error_report("Failed to restore old file length: %s",
2411 strerror(errno));
2412 }
2413 }
2414
2415 g_free(buf);
2416 return result;
2417}
2418
0fdb7311 2419static int coroutine_fn raw_thread_pool_submit(ThreadPoolFunc func, void *arg)
5d5de250 2420{
aef04fc7 2421 return thread_pool_submit_co(func, arg);
5d5de250
KW
2422}
2423
a7c5f67a
KB
2424/*
2425 * Check if all memory in this vector is sector aligned.
2426 */
2427static bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2428{
2429 int i;
2430 size_t alignment = bdrv_min_mem_align(bs);
25474d90 2431 size_t len = bs->bl.request_alignment;
a7c5f67a
KB
2432 IO_CODE();
2433
2434 for (i = 0; i < qiov->niov; i++) {
2435 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2436 return false;
2437 }
25474d90 2438 if (qiov->iov[i].iov_len % len) {
a7c5f67a
KB
2439 return false;
2440 }
2441 }
2442
2443 return true;
2444}
2445
9d52aa3c
KW
2446static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
2447 uint64_t bytes, QEMUIOVector *qiov, int type)
83f64091 2448{
ce1a14dc 2449 BDRVRawState *s = bs->opaque;
999e6b69 2450 RawPosixAIOData acb;
a3c41f06 2451 int ret;
ce1a14dc 2452
19cb3738 2453 if (fd_open(bs) < 0)
2174f12b 2454 return -EIO;
a3c41f06
SL
2455#if defined(CONFIG_BLKZONED)
2456 if (type & QEMU_AIO_WRITE && bs->wps) {
2457 qemu_co_mutex_lock(&bs->wps->colock);
2458 }
2459#endif
19cb3738 2460
f141eafe 2461 /*
c6447510
AM
2462 * When using O_DIRECT, the request must be aligned to be able to use
2463 * either libaio or io_uring interface. If not fail back to regular thread
2464 * pool read/write code which emulates this for us if we
2465 * set QEMU_AIO_MISALIGNED.
f141eafe 2466 */
c6447510
AM
2467 if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
2468 type |= QEMU_AIO_MISALIGNED;
2469#ifdef CONFIG_LINUX_IO_URING
2470 } else if (s->use_linux_io_uring) {
c6447510 2471 assert(qiov->size == bytes);
a3c41f06
SL
2472 ret = luring_co_submit(bs, s->fd, offset, qiov, type);
2473 goto out;
c6447510 2474#endif
e44bd6fc 2475#ifdef CONFIG_LINUX_AIO
c6447510 2476 } else if (s->use_linux_aio) {
c6447510 2477 assert(qiov->size == bytes);
a3c41f06
SL
2478 ret = laio_co_submit(s->fd, offset, qiov, type,
2479 s->aio_max_batch);
2480 goto out;
e44bd6fc 2481#endif
9ef91a67 2482 }
f141eafe 2483
999e6b69
KW
2484 acb = (RawPosixAIOData) {
2485 .bs = bs,
2486 .aio_fildes = s->fd,
2487 .aio_type = type,
2488 .aio_offset = offset,
2489 .aio_nbytes = bytes,
2490 .io = {
2491 .iov = qiov->iov,
2492 .niov = qiov->niov,
2493 },
2494 };
2495
2496 assert(qiov->size == bytes);
a3c41f06
SL
2497 ret = raw_thread_pool_submit(handle_aiocb_rw, &acb);
2498 goto out; /* Avoid the compiler err of unused label */
2499
2500out:
2501#if defined(CONFIG_BLKZONED)
2502{
2503 BlockZoneWps *wps = bs->wps;
2504 if (ret == 0) {
2505 if (type & QEMU_AIO_WRITE && wps && bs->bl.zone_size) {
2506 uint64_t *wp = &wps->wp[offset / bs->bl.zone_size];
2507 if (!BDRV_ZT_IS_CONV(*wp)) {
2508 /* Advance the wp if needed */
2509 if (offset + bytes > *wp) {
2510 *wp = offset + bytes;
2511 }
2512 }
2513 }
2514 } else {
2515 if (type & QEMU_AIO_WRITE) {
2516 update_zones_wp(bs, s->fd, 0, 1);
2517 }
2518 }
2519
2520 if (type & QEMU_AIO_WRITE && wps) {
2521 qemu_co_mutex_unlock(&wps->colock);
2522 }
2523}
2524#endif
2525 return ret;
2174f12b
KW
2526}
2527
f7ef38dd
VSO
2528static int coroutine_fn raw_co_preadv(BlockDriverState *bs, int64_t offset,
2529 int64_t bytes, QEMUIOVector *qiov,
2530 BdrvRequestFlags flags)
2174f12b 2531{
9d52aa3c 2532 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
2174f12b
KW
2533}
2534
e75abeda
VSO
2535static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, int64_t offset,
2536 int64_t bytes, QEMUIOVector *qiov,
2537 BdrvRequestFlags flags)
2174f12b 2538{
9d52aa3c 2539 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
83f64091
FB
2540}
2541
8f497454 2542static void coroutine_fn raw_co_io_plug(BlockDriverState *bs)
1b3abdcc 2543{
c6447510 2544 BDRVRawState __attribute__((unused)) *s = bs->opaque;
1b3abdcc 2545#ifdef CONFIG_LINUX_AIO
0a4279d9 2546 if (s->use_linux_aio) {
ab50533b 2547 laio_io_plug();
1b3abdcc
ML
2548 }
2549#endif
c6447510
AM
2550#ifdef CONFIG_LINUX_IO_URING
2551 if (s->use_linux_io_uring) {
a75e4e43 2552 luring_io_plug();
c6447510
AM
2553 }
2554#endif
1b3abdcc
ML
2555}
2556
09d9fc97 2557static void coroutine_fn raw_co_io_unplug(BlockDriverState *bs)
1b3abdcc 2558{
c6447510 2559 BDRVRawState __attribute__((unused)) *s = bs->opaque;
1b3abdcc 2560#ifdef CONFIG_LINUX_AIO
0a4279d9 2561 if (s->use_linux_aio) {
ab50533b 2562 laio_io_unplug(s->aio_max_batch);
1b3abdcc
ML
2563 }
2564#endif
c6447510
AM
2565#ifdef CONFIG_LINUX_IO_URING
2566 if (s->use_linux_io_uring) {
a75e4e43 2567 luring_io_unplug();
c6447510
AM
2568 }
2569#endif
1b3abdcc
ML
2570}
2571
dda56b75 2572static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
b2e12bc6
CH
2573{
2574 BDRVRawState *s = bs->opaque;
06dc9bd5 2575 RawPosixAIOData acb;
33d70fb6 2576 int ret;
b2e12bc6 2577
33d70fb6
KW
2578 ret = fd_open(bs);
2579 if (ret < 0) {
2580 return ret;
2581 }
b2e12bc6 2582
06dc9bd5
KW
2583 acb = (RawPosixAIOData) {
2584 .bs = bs,
2585 .aio_fildes = s->fd,
2586 .aio_type = QEMU_AIO_FLUSH,
2587 };
2588
c6447510
AM
2589#ifdef CONFIG_LINUX_IO_URING
2590 if (s->use_linux_io_uring) {
a75e4e43 2591 return luring_co_submit(bs, s->fd, 0, NULL, QEMU_AIO_FLUSH);
c6447510
AM
2592 }
2593#endif
0fdb7311 2594 return raw_thread_pool_submit(handle_aiocb_flush, &acb);
b2e12bc6
CH
2595}
2596
ed6e2161
NA
2597static void raw_aio_attach_aio_context(BlockDriverState *bs,
2598 AioContext *new_context)
2599{
c6447510 2600 BDRVRawState __attribute__((unused)) *s = bs->opaque;
ed6e2161 2601#ifdef CONFIG_LINUX_AIO
ed6e2161 2602 if (s->use_linux_aio) {
cb09104e 2603 Error *local_err = NULL;
ed6e2161
NA
2604 if (!aio_setup_linux_aio(new_context, &local_err)) {
2605 error_reportf_err(local_err, "Unable to use native AIO, "
2606 "falling back to thread pool: ");
2607 s->use_linux_aio = false;
2608 }
2609 }
2610#endif
c6447510
AM
2611#ifdef CONFIG_LINUX_IO_URING
2612 if (s->use_linux_io_uring) {
cb8d0851 2613 Error *local_err = NULL;
c6447510
AM
2614 if (!aio_setup_linux_io_uring(new_context, &local_err)) {
2615 error_reportf_err(local_err, "Unable to use linux io_uring, "
2616 "falling back to thread pool: ");
2617 s->use_linux_io_uring = false;
2618 }
2619 }
2620#endif
ed6e2161
NA
2621}
2622
83f64091
FB
2623static void raw_close(BlockDriverState *bs)
2624{
2625 BDRVRawState *s = bs->opaque;
c2f3426c 2626
19cb3738 2627 if (s->fd >= 0) {
a3c41f06
SL
2628#if defined(CONFIG_BLKZONED)
2629 g_free(bs->wps);
2630#endif
2e1e79da 2631 qemu_close(s->fd);
19cb3738
FB
2632 s->fd = -1;
2633 }
83f64091
FB
2634}
2635
d0bc9e5d
HR
2636/**
2637 * Truncates the given regular file @fd to @offset and, when growing, fills the
2638 * new space according to @prealloc.
2639 *
2640 * Returns: 0 on success, -errno on failure.
2641 */
93f4e2ff
KW
2642static int coroutine_fn
2643raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
2644 PreallocMode prealloc, Error **errp)
9f63b07e 2645{
29cb4c01 2646 RawPosixAIOData acb;
d0bc9e5d 2647
29cb4c01 2648 acb = (RawPosixAIOData) {
93f4e2ff
KW
2649 .bs = bs,
2650 .aio_fildes = fd,
2651 .aio_type = QEMU_AIO_TRUNCATE,
2652 .aio_offset = offset,
d57c44d0
KW
2653 .truncate = {
2654 .prealloc = prealloc,
2655 .errp = errp,
2656 },
93f4e2ff 2657 };
d0bc9e5d 2658
0fdb7311 2659 return raw_thread_pool_submit(handle_aiocb_truncate, &acb);
9f63b07e
HR
2660}
2661
061ca8a3 2662static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
c80d8b06 2663 bool exact, PreallocMode prealloc,
92b92799 2664 BdrvRequestFlags flags, Error **errp)
83f64091
FB
2665{
2666 BDRVRawState *s = bs->opaque;
55b949c8 2667 struct stat st;
f59adb32 2668 int ret;
55b949c8
CH
2669
2670 if (fstat(s->fd, &st)) {
f59adb32
HR
2671 ret = -errno;
2672 error_setg_errno(errp, -ret, "Failed to fstat() the file");
2673 return ret;
55b949c8
CH
2674 }
2675
2676 if (S_ISREG(st.st_mode)) {
82325ae5 2677 /* Always resizes to the exact @offset */
93f4e2ff 2678 return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
35d72602
HR
2679 }
2680
2681 if (prealloc != PREALLOC_MODE_OFF) {
2682 error_setg(errp, "Preallocation mode '%s' unsupported for this "
977c736f 2683 "non-regular file", PreallocMode_str(prealloc));
35d72602
HR
2684 return -ENOTSUP;
2685 }
2686
2687 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
c86422c5 2688 int64_t cur_length = raw_co_getlength(bs);
82325ae5
HR
2689
2690 if (offset != cur_length && exact) {
2691 error_setg(errp, "Cannot resize device files");
2692 return -ENOTSUP;
2693 } else if (offset > cur_length) {
f59adb32
HR
2694 error_setg(errp, "Cannot grow device files");
2695 return -EINVAL;
2696 }
55b949c8 2697 } else {
f59adb32 2698 error_setg(errp, "Resizing this file is not supported");
55b949c8
CH
2699 return -ENOTSUP;
2700 }
2701
83f64091
FB
2702 return 0;
2703}
2704
128ab2ff 2705#ifdef __OpenBSD__
c86422c5 2706static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
128ab2ff
BS
2707{
2708 BDRVRawState *s = bs->opaque;
2709 int fd = s->fd;
2710 struct stat st;
2711
2712 if (fstat(fd, &st))
aa729704 2713 return -errno;
128ab2ff
BS
2714 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2715 struct disklabel dl;
2716
2717 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 2718 return -errno;
128ab2ff
BS
2719 return (uint64_t)dl.d_secsize *
2720 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2721 } else
2722 return st.st_size;
2723}
d1f6fd8d 2724#elif defined(__NetBSD__)
c86422c5 2725static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
d1f6fd8d
CE
2726{
2727 BDRVRawState *s = bs->opaque;
2728 int fd = s->fd;
2729 struct stat st;
2730
2731 if (fstat(fd, &st))
aa729704 2732 return -errno;
d1f6fd8d
CE
2733 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2734 struct dkwedge_info dkw;
2735
2736 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2737 return dkw.dkw_size * 512;
2738 } else {
2739 struct disklabel dl;
2740
2741 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 2742 return -errno;
d1f6fd8d
CE
2743 return (uint64_t)dl.d_secsize *
2744 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2745 }
2746 } else
2747 return st.st_size;
2748}
50779cc2 2749#elif defined(__sun__)
c86422c5 2750static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
50779cc2
CH
2751{
2752 BDRVRawState *s = bs->opaque;
2753 struct dk_minfo minfo;
2754 int ret;
aa729704 2755 int64_t size;
50779cc2
CH
2756
2757 ret = fd_open(bs);
2758 if (ret < 0) {
2759 return ret;
2760 }
2761
2762 /*
2763 * Use the DKIOCGMEDIAINFO ioctl to read the size.
2764 */
2765 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2766 if (ret != -1) {
2767 return minfo.dki_lbsize * minfo.dki_capacity;
2768 }
2769
2770 /*
2771 * There are reports that lseek on some devices fails, but
2772 * irc discussion said that contingency on contingency was overkill.
2773 */
aa729704
MA
2774 size = lseek(s->fd, 0, SEEK_END);
2775 if (size < 0) {
2776 return -errno;
2777 }
2778 return size;
50779cc2
CH
2779}
2780#elif defined(CONFIG_BSD)
c86422c5 2781static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
83f64091
FB
2782{
2783 BDRVRawState *s = bs->opaque;
2784 int fd = s->fd;
2785 int64_t size;
83f64091 2786 struct stat sb;
a167ba50 2787#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a 2788 int reopened = 0;
83f64091 2789#endif
19cb3738
FB
2790 int ret;
2791
2792 ret = fd_open(bs);
2793 if (ret < 0)
2794 return ret;
83f64091 2795
a167ba50 2796#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
2797again:
2798#endif
83f64091 2799 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
267cd53f 2800 size = 0;
83f64091 2801#ifdef DIOCGMEDIASIZE
267cd53f
PB
2802 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size)) {
2803 size = 0;
2804 }
2805#endif
2806#ifdef DIOCGPART
2807 if (size == 0) {
2808 struct partinfo pi;
2809 if (ioctl(fd, DIOCGPART, &pi) == 0) {
2810 size = pi.media_size;
2811 }
c5e97233 2812 }
83f64091 2813#endif
09e20abd 2814#if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
267cd53f 2815 if (size == 0) {
728dacbd
JA
2816 uint64_t sectors = 0;
2817 uint32_t sector_size = 0;
2818
2819 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2820 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2821 size = sectors * sector_size;
728dacbd
JA
2822 }
2823 }
267cd53f
PB
2824#endif
2825 if (size == 0) {
2826 size = lseek(fd, 0LL, SEEK_END);
2827 }
aa729704
MA
2828 if (size < 0) {
2829 return -errno;
2830 }
a167ba50 2831#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
2832 switch(s->type) {
2833 case FTYPE_CD:
2834 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2835 if (size == 2048LL * (unsigned)-1)
2836 size = 0;
2837 /* XXX no disc? maybe we need to reopen... */
f3a5d3f8 2838 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
9f23011a
BS
2839 reopened = 1;
2840 goto again;
2841 }
2842 }
83f64091 2843#endif
50779cc2 2844 } else {
83f64091 2845 size = lseek(fd, 0, SEEK_END);
aa729704
MA
2846 if (size < 0) {
2847 return -errno;
2848 }
83f64091 2849 }
83f64091
FB
2850 return size;
2851}
50779cc2 2852#else
c86422c5 2853static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
50779cc2
CH
2854{
2855 BDRVRawState *s = bs->opaque;
2856 int ret;
aa729704 2857 int64_t size;
50779cc2
CH
2858
2859 ret = fd_open(bs);
2860 if (ret < 0) {
2861 return ret;
2862 }
2863
aa729704
MA
2864 size = lseek(s->fd, 0, SEEK_END);
2865 if (size < 0) {
2866 return -errno;
2867 }
2868 return size;
50779cc2 2869}
128ab2ff 2870#endif
83f64091 2871
82618d7b 2872static int64_t coroutine_fn raw_co_get_allocated_file_size(BlockDriverState *bs)
4a1d5e1f
FZ
2873{
2874 struct stat st;
2875 BDRVRawState *s = bs->opaque;
2876
2877 if (fstat(s->fd, &st) < 0) {
2878 return -errno;
2879 }
2880 return (int64_t)st.st_blocks * 512;
2881}
2882
93f4e2ff
KW
2883static int coroutine_fn
2884raw_co_create(BlockdevCreateOptions *options, Error **errp)
83f64091 2885{
927f11e1 2886 BlockdevCreateOptionsFile *file_opts;
7c20c808 2887 Error *local_err = NULL;
83f64091 2888 int fd;
d815efca 2889 uint64_t perm, shared;
1e37d059 2890 int result = 0;
83f64091 2891
927f11e1
KW
2892 /* Validate options and set default values */
2893 assert(options->driver == BLOCKDEV_DRIVER_FILE);
2894 file_opts = &options->u.file;
464d9f64 2895
927f11e1
KW
2896 if (!file_opts->has_nocow) {
2897 file_opts->nocow = false;
2898 }
2899 if (!file_opts->has_preallocation) {
2900 file_opts->preallocation = PREALLOC_MODE_OFF;
06247428 2901 }
ffa244c8
KW
2902 if (!file_opts->has_extent_size_hint) {
2903 file_opts->extent_size_hint = 1 * MiB;
2904 }
2905 if (file_opts->extent_size_hint > UINT32_MAX) {
2906 result = -EINVAL;
2907 error_setg(errp, "Extent size hint is too large");
2908 goto out;
2909 }
83f64091 2910
927f11e1 2911 /* Create file */
b18a24a9 2912 fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
1e37d059
SW
2913 if (fd < 0) {
2914 result = -errno;
06247428
HT
2915 goto out;
2916 }
2917
b8cf1913
HR
2918 /* Take permissions: We want to discard everything, so we need
2919 * BLK_PERM_WRITE; and truncation to the desired size requires
2920 * BLK_PERM_RESIZE.
2921 * On the other hand, we cannot share the RESIZE permission
2922 * because we promise that after this function, the file has the
2923 * size given in the options. If someone else were to resize it
2924 * concurrently, we could not guarantee that.
2925 * Note that after this function, we can no longer guarantee that
2926 * the file is not touched by a third party, so it may be resized
2927 * then. */
2928 perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2929 shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2930
2931 /* Step one: Take locks */
2996ffad 2932 result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
b8cf1913
HR
2933 if (result < 0) {
2934 goto out_close;
2935 }
2936
2937 /* Step two: Check that nobody else has taken conflicting locks */
2938 result = raw_check_lock_bytes(fd, perm, shared, errp);
2939 if (result < 0) {
b857431d
FZ
2940 error_append_hint(errp,
2941 "Is another process using the image [%s]?\n",
2942 file_opts->filename);
7c20c808 2943 goto out_unlock;
b8cf1913
HR
2944 }
2945
2946 /* Clear the file by truncating it to 0 */
93f4e2ff 2947 result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
b8cf1913 2948 if (result < 0) {
7c20c808 2949 goto out_unlock;
b8cf1913
HR
2950 }
2951
927f11e1 2952 if (file_opts->nocow) {
4ab15590 2953#ifdef __linux__
06247428
HT
2954 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2955 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2956 * will be ignored since any failure of this operation should not
2957 * block the left work.
2958 */
2959 int attr;
2960 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2961 attr |= FS_NOCOW_FL;
2962 ioctl(fd, FS_IOC_SETFLAGS, &attr);
4ab15590 2963 }
06247428
HT
2964#endif
2965 }
ffa244c8
KW
2966#ifdef FS_IOC_FSSETXATTR
2967 /*
2968 * Try to set the extent size hint. Failure is not fatal, and a warning is
2969 * only printed if the option was explicitly specified.
2970 */
2971 {
2972 struct fsxattr attr;
2973 result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2974 if (result == 0) {
2975 attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2976 attr.fsx_extsize = file_opts->extent_size_hint;
2977 result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2978 }
2979 if (result < 0 && file_opts->has_extent_size_hint &&
2980 file_opts->extent_size_hint)
2981 {
2982 warn_report("Failed to set extent size hint: %s",
2983 strerror(errno));
2984 }
2985 }
2986#endif
06247428 2987
b8cf1913
HR
2988 /* Resize and potentially preallocate the file to the desired
2989 * final size */
93f4e2ff
KW
2990 result = raw_regular_truncate(NULL, fd, file_opts->size,
2991 file_opts->preallocation, errp);
9f63b07e 2992 if (result < 0) {
7c20c808
HR
2993 goto out_unlock;
2994 }
2995
2996out_unlock:
2996ffad 2997 raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
7c20c808
HR
2998 if (local_err) {
2999 /* The above call should not fail, and if it does, that does
3000 * not mean the whole creation operation has failed. So
3001 * report it the user for their convenience, but do not report
3002 * it to the caller. */
db0754df 3003 warn_report_err(local_err);
1e37d059 3004 }
06247428 3005
5a1dad9d 3006out_close:
06247428
HT
3007 if (qemu_close(fd) != 0 && result == 0) {
3008 result = -errno;
3009 error_setg_errno(errp, -result, "Could not close the new file");
3010 }
3011out:
1e37d059 3012 return result;
83f64091
FB
3013}
3014
4ec8df01
KW
3015static int coroutine_fn GRAPH_RDLOCK
3016raw_co_create_opts(BlockDriver *drv, const char *filename,
3017 QemuOpts *opts, Error **errp)
927f11e1
KW
3018{
3019 BlockdevCreateOptions options;
3020 int64_t total_size = 0;
ffa244c8
KW
3021 int64_t extent_size_hint = 0;
3022 bool has_extent_size_hint = false;
927f11e1
KW
3023 bool nocow = false;
3024 PreallocMode prealloc;
3025 char *buf = NULL;
3026 Error *local_err = NULL;
3027
3028 /* Skip file: protocol prefix */
3029 strstart(filename, "file:", &filename);
3030
3031 /* Read out options */
3032 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3033 BDRV_SECTOR_SIZE);
ffa244c8
KW
3034 if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
3035 has_extent_size_hint = true;
3036 extent_size_hint =
3037 qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
3038 }
927f11e1
KW
3039 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
3040 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3041 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
3042 PREALLOC_MODE_OFF, &local_err);
3043 g_free(buf);
3044 if (local_err) {
3045 error_propagate(errp, local_err);
3046 return -EINVAL;
3047 }
3048
3049 options = (BlockdevCreateOptions) {
3050 .driver = BLOCKDEV_DRIVER_FILE,
3051 .u.file = {
3052 .filename = (char *) filename,
3053 .size = total_size,
3054 .has_preallocation = true,
3055 .preallocation = prealloc,
3056 .has_nocow = true,
3057 .nocow = nocow,
ffa244c8
KW
3058 .has_extent_size_hint = has_extent_size_hint,
3059 .extent_size_hint = extent_size_hint,
927f11e1
KW
3060 },
3061 };
3062 return raw_co_create(&options, errp);
3063}
3064
9bffae14
DHB
3065static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
3066 Error **errp)
3067{
3068 struct stat st;
3069 int ret;
3070
3071 if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
3072 error_setg_errno(errp, ENOENT, "%s is not a regular file",
3073 bs->filename);
3074 return -ENOENT;
3075 }
3076
3077 ret = unlink(bs->filename);
3078 if (ret < 0) {
3079 ret = -errno;
3080 error_setg_errno(errp, -ret, "Error when deleting file %s",
3081 bs->filename);
3082 }
3083
3084 return ret;
3085}
3086
d1f06fe6
MA
3087/*
3088 * Find allocation range in @bs around offset @start.
3089 * May change underlying file descriptor's file offset.
3090 * If @start is not in a hole, store @start in @data, and the
3091 * beginning of the next hole in @hole, and return 0.
3092 * If @start is in a non-trailing hole, store @start in @hole and the
3093 * beginning of the next non-hole in @data, and return 0.
3094 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
3095 * If we can't find out, return a negative errno other than -ENXIO.
3096 */
3097static int find_allocation(BlockDriverState *bs, off_t start,
3098 off_t *data, off_t *hole)
4f11aa8a
HR
3099{
3100#if defined SEEK_HOLE && defined SEEK_DATA
94282e71 3101 BDRVRawState *s = bs->opaque;
d1f06fe6 3102 off_t offs;
94282e71 3103
d1f06fe6
MA
3104 /*
3105 * SEEK_DATA cases:
3106 * D1. offs == start: start is in data
3107 * D2. offs > start: start is in a hole, next data at offs
3108 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
3109 * or start is beyond EOF
3110 * If the latter happens, the file has been truncated behind
3111 * our back since we opened it. All bets are off then.
3112 * Treating like a trailing hole is simplest.
3113 * D4. offs < 0, errno != ENXIO: we learned nothing
3114 */
3115 offs = lseek(s->fd, start, SEEK_DATA);
3116 if (offs < 0) {
3117 return -errno; /* D3 or D4 */
3118 }
a03083a0
JC
3119
3120 if (offs < start) {
3121 /* This is not a valid return by lseek(). We are safe to just return
3122 * -EIO in this case, and we'll treat it like D4. */
3123 return -EIO;
3124 }
d1f06fe6
MA
3125
3126 if (offs > start) {
3127 /* D2: in hole, next data at offs */
3128 *hole = start;
3129 *data = offs;
3130 return 0;
5500316d
PB
3131 }
3132
d1f06fe6
MA
3133 /* D1: in data, end not yet known */
3134
3135 /*
3136 * SEEK_HOLE cases:
3137 * H1. offs == start: start is in a hole
3138 * If this happens here, a hole has been dug behind our back
3139 * since the previous lseek().
3140 * H2. offs > start: either start is in data, next hole at offs,
3141 * or start is in trailing hole, EOF at offs
3142 * Linux treats trailing holes like any other hole: offs ==
3143 * start. Solaris seeks to EOF instead: offs > start (blech).
3144 * If that happens here, a hole has been dug behind our back
3145 * since the previous lseek().
3146 * H3. offs < 0, errno = ENXIO: start is beyond EOF
3147 * If this happens, the file has been truncated behind our
3148 * back since we opened it. Treat it like a trailing hole.
3149 * H4. offs < 0, errno != ENXIO: we learned nothing
3150 * Pretend we know nothing at all, i.e. "forget" about D1.
3151 */
3152 offs = lseek(s->fd, start, SEEK_HOLE);
3153 if (offs < 0) {
3154 return -errno; /* D1 and (H3 or H4) */
3155 }
a03083a0
JC
3156
3157 if (offs < start) {
3158 /* This is not a valid return by lseek(). We are safe to just return
3159 * -EIO in this case, and we'll treat it like H4. */
3160 return -EIO;
3161 }
d1f06fe6
MA
3162
3163 if (offs > start) {
3164 /*
3165 * D1 and H2: either in data, next hole at offs, or it was in
3166 * data but is now in a trailing hole. In the latter case,
3167 * all bets are off. Treating it as if it there was data all
3168 * the way to EOF is safe, so simply do that.
3169 */
4f11aa8a 3170 *data = start;
d1f06fe6
MA
3171 *hole = offs;
3172 return 0;
5500316d 3173 }
4f11aa8a 3174
d1f06fe6
MA
3175 /* D1 and H1 */
3176 return -EBUSY;
5500316d 3177#else
4f11aa8a 3178 return -ENOTSUP;
5500316d 3179#endif
4f11aa8a
HR
3180}
3181
3182/*
a290f085 3183 * Returns the allocation status of the specified offset.
4f11aa8a 3184 *
a290f085 3185 * The block layer guarantees 'offset' and 'bytes' are within bounds.
4f11aa8a 3186 *
a290f085
EB
3187 * 'pnum' is set to the number of bytes (including and immediately following
3188 * the specified offset) that are known to be in the same
4f11aa8a
HR
3189 * allocated/unallocated state.
3190 *
869e7ee8
HR
3191 * 'bytes' is a soft cap for 'pnum'. If the information is free, 'pnum' may
3192 * well exceed it.
4f11aa8a 3193 */
a290f085
EB
3194static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
3195 bool want_zero,
3196 int64_t offset,
3197 int64_t bytes, int64_t *pnum,
3198 int64_t *map,
3199 BlockDriverState **file)
3200{
3201 off_t data = 0, hole = 0;
d7f62751 3202 int ret;
4f11aa8a 3203
9c3db310
HR
3204 assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
3205
4f11aa8a
HR
3206 ret = fd_open(bs);
3207 if (ret < 0) {
3208 return ret;
3209 }
3210
a290f085
EB
3211 if (!want_zero) {
3212 *pnum = bytes;
3213 *map = offset;
3214 *file = bs;
3215 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
e6d7ec32 3216 }
4f11aa8a 3217
a290f085 3218 ret = find_allocation(bs, offset, &data, &hole);
d1f06fe6
MA
3219 if (ret == -ENXIO) {
3220 /* Trailing hole */
a290f085 3221 *pnum = bytes;
d1f06fe6
MA
3222 ret = BDRV_BLOCK_ZERO;
3223 } else if (ret < 0) {
3224 /* No info available, so pretend there are no holes */
a290f085 3225 *pnum = bytes;
d1f06fe6 3226 ret = BDRV_BLOCK_DATA;
a290f085
EB
3227 } else if (data == offset) {
3228 /* On a data extent, compute bytes to the end of the extent,
f4a769ab 3229 * possibly including a partial sector at EOF. */
869e7ee8 3230 *pnum = hole - offset;
9c3db310
HR
3231
3232 /*
3233 * We are not allowed to return partial sectors, though, so
3234 * round up if necessary.
3235 */
3236 if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
c86422c5 3237 int64_t file_length = raw_co_getlength(bs);
9c3db310
HR
3238 if (file_length > 0) {
3239 /* Ignore errors, this is just a safeguard */
3240 assert(hole == file_length);
3241 }
3242 *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
3243 }
3244
d1f06fe6 3245 ret = BDRV_BLOCK_DATA;
5500316d 3246 } else {
a290f085
EB
3247 /* On a hole, compute bytes to the beginning of the next extent. */
3248 assert(hole == offset);
869e7ee8 3249 *pnum = data - offset;
d1f06fe6 3250 ret = BDRV_BLOCK_ZERO;
5500316d 3251 }
a290f085 3252 *map = offset;
02650acb 3253 *file = bs;
a290f085 3254 return ret | BDRV_BLOCK_OFFSET_VALID;
5500316d
PB
3255}
3256
31be8a2a
SH
3257#if defined(__linux__)
3258/* Verify that the file is not in the page cache */
c86422c5 3259static void coroutine_fn check_cache_dropped(BlockDriverState *bs, Error **errp)
31be8a2a
SH
3260{
3261 const size_t window_size = 128 * 1024 * 1024;
3262 BDRVRawState *s = bs->opaque;
3263 void *window = NULL;
3264 size_t length = 0;
3265 unsigned char *vec;
3266 size_t page_size;
3267 off_t offset;
3268 off_t end;
3269
3270 /* mincore(2) page status information requires 1 byte per page */
3271 page_size = sysconf(_SC_PAGESIZE);
3272 vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
3273
c86422c5 3274 end = raw_co_getlength(bs);
31be8a2a
SH
3275
3276 for (offset = 0; offset < end; offset += window_size) {
3277 void *new_window;
3278 size_t new_length;
3279 size_t vec_end;
3280 size_t i;
3281 int ret;
3282
3283 /* Unmap previous window if size has changed */
3284 new_length = MIN(end - offset, window_size);
3285 if (new_length != length) {
3286 munmap(window, length);
3287 window = NULL;
3288 length = 0;
3289 }
3290
3291 new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
3292 s->fd, offset);
3293 if (new_window == MAP_FAILED) {
3294 error_setg_errno(errp, errno, "mmap failed");
3295 break;
3296 }
3297
3298 window = new_window;
3299 length = new_length;
3300
3301 ret = mincore(window, length, vec);
3302 if (ret < 0) {
3303 error_setg_errno(errp, errno, "mincore failed");
3304 break;
3305 }
3306
3307 vec_end = DIV_ROUND_UP(length, page_size);
3308 for (i = 0; i < vec_end; i++) {
3309 if (vec[i] & 0x1) {
31be8a2a
SH
3310 break;
3311 }
3312 }
77ed971b
MA
3313 if (i < vec_end) {
3314 error_setg(errp, "page cache still in use!");
3315 break;
3316 }
31be8a2a
SH
3317 }
3318
3319 if (window) {
3320 munmap(window, length);
3321 }
3322
3323 g_free(vec);
3324}
3325#endif /* __linux__ */
3326
88095349
EGE
3327static void coroutine_fn GRAPH_RDLOCK
3328raw_co_invalidate_cache(BlockDriverState *bs, Error **errp)
dd577a26
SH
3329{
3330 BDRVRawState *s = bs->opaque;
3331 int ret;
3332
3333 ret = fd_open(bs);
3334 if (ret < 0) {
3335 error_setg_errno(errp, -ret, "The file descriptor is not open");
3336 return;
3337 }
3338
f357fcd8
SH
3339 if (!s->drop_cache) {
3340 return;
3341 }
3342
dd577a26
SH
3343 if (s->open_flags & O_DIRECT) {
3344 return; /* No host kernel page cache */
3345 }
3346
3347#if defined(__linux__)
3348 /* This sets the scene for the next syscall... */
3349 ret = bdrv_co_flush(bs);
3350 if (ret < 0) {
3351 error_setg_errno(errp, -ret, "flush failed");
3352 return;
3353 }
3354
3355 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
3356 * process. These limitations are okay because we just fsynced the file,
3357 * we don't use mmap, and the file should not be in use by other processes.
3358 */
3359 ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
3360 if (ret != 0) { /* the return value is a positive errno */
3361 error_setg_errno(errp, ret, "fadvise failed");
3362 return;
3363 }
31be8a2a
SH
3364
3365 if (s->check_cache_dropped) {
3366 check_cache_dropped(bs, errp);
3367 }
dd577a26
SH
3368#else /* __linux__ */
3369 /* Do nothing. Live migration to a remote host with cache.direct=off is
3370 * unsupported on other host operating systems. Cache consistency issues
3371 * may occur but no error is reported here, partly because that's the
3372 * historical behavior and partly because it's hard to differentiate valid
3373 * configurations that should not cause errors.
3374 */
3375#endif /* !__linux__ */
3376}
3377
1c450366
AN
3378static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
3379{
3380 if (ret) {
3381 s->stats.discard_nb_failed++;
3382 } else {
3383 s->stats.discard_nb_ok++;
3384 s->stats.discard_bytes_ok += nbytes;
3385 }
3386}
3387
6d43eaa3
SL
3388/*
3389 * zone report - Get a zone block device's information in the form
3390 * of an array of zone descriptors.
3391 * zones is an array of zone descriptors to hold zone information on reply;
3392 * offset can be any byte within the entire size of the device;
3393 * nr_zones is the maxium number of sectors the command should operate on.
3394 */
3395#if defined(CONFIG_BLKZONED)
3396static int coroutine_fn raw_co_zone_report(BlockDriverState *bs, int64_t offset,
3397 unsigned int *nr_zones,
3398 BlockZoneDescriptor *zones) {
3399 BDRVRawState *s = bs->opaque;
3400 RawPosixAIOData acb = (RawPosixAIOData) {
3401 .bs = bs,
3402 .aio_fildes = s->fd,
3403 .aio_type = QEMU_AIO_ZONE_REPORT,
3404 .aio_offset = offset,
3405 .zone_report = {
3406 .nr_zones = nr_zones,
3407 .zones = zones,
3408 },
3409 };
3410
142e307e 3411 trace_zbd_zone_report(bs, *nr_zones, offset >> BDRV_SECTOR_BITS);
6d43eaa3
SL
3412 return raw_thread_pool_submit(handle_aiocb_zone_report, &acb);
3413}
3414#endif
3415
3416/*
3417 * zone management operations - Execute an operation on a zone
3418 */
3419#if defined(CONFIG_BLKZONED)
3420static int coroutine_fn raw_co_zone_mgmt(BlockDriverState *bs, BlockZoneOp op,
3421 int64_t offset, int64_t len) {
3422 BDRVRawState *s = bs->opaque;
3423 RawPosixAIOData acb;
3424 int64_t zone_size, zone_size_mask;
3425 const char *op_name;
3426 unsigned long zo;
3427 int ret;
a3c41f06 3428 BlockZoneWps *wps = bs->wps;
6d43eaa3
SL
3429 int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
3430
3431 zone_size = bs->bl.zone_size;
3432 zone_size_mask = zone_size - 1;
3433 if (offset & zone_size_mask) {
3434 error_report("sector offset %" PRId64 " is not aligned to zone size "
3435 "%" PRId64 "", offset / 512, zone_size / 512);
3436 return -EINVAL;
3437 }
3438
3439 if (((offset + len) < capacity && len & zone_size_mask) ||
3440 offset + len > capacity) {
3441 error_report("number of sectors %" PRId64 " is not aligned to zone size"
3442 " %" PRId64 "", len / 512, zone_size / 512);
3443 return -EINVAL;
3444 }
3445
a3c41f06
SL
3446 uint32_t i = offset / bs->bl.zone_size;
3447 uint32_t nrz = len / bs->bl.zone_size;
3448 uint64_t *wp = &wps->wp[i];
3449 if (BDRV_ZT_IS_CONV(*wp) && len != capacity) {
3450 error_report("zone mgmt operations are not allowed for conventional zones");
3451 return -EIO;
3452 }
3453
6d43eaa3
SL
3454 switch (op) {
3455 case BLK_ZO_OPEN:
3456 op_name = "BLKOPENZONE";
3457 zo = BLKOPENZONE;
3458 break;
3459 case BLK_ZO_CLOSE:
3460 op_name = "BLKCLOSEZONE";
3461 zo = BLKCLOSEZONE;
3462 break;
3463 case BLK_ZO_FINISH:
3464 op_name = "BLKFINISHZONE";
3465 zo = BLKFINISHZONE;
3466 break;
3467 case BLK_ZO_RESET:
3468 op_name = "BLKRESETZONE";
3469 zo = BLKRESETZONE;
3470 break;
3471 default:
3472 error_report("Unsupported zone op: 0x%x", op);
3473 return -ENOTSUP;
3474 }
3475
3476 acb = (RawPosixAIOData) {
3477 .bs = bs,
3478 .aio_fildes = s->fd,
3479 .aio_type = QEMU_AIO_ZONE_MGMT,
3480 .aio_offset = offset,
3481 .aio_nbytes = len,
3482 .zone_mgmt = {
3483 .op = zo,
3484 },
3485 };
3486
142e307e
SL
3487 trace_zbd_zone_mgmt(bs, op_name, offset >> BDRV_SECTOR_BITS,
3488 len >> BDRV_SECTOR_BITS);
6d43eaa3
SL
3489 ret = raw_thread_pool_submit(handle_aiocb_zone_mgmt, &acb);
3490 if (ret != 0) {
a3c41f06 3491 update_zones_wp(bs, s->fd, offset, i);
6d43eaa3 3492 error_report("ioctl %s failed %d", op_name, ret);
a3c41f06
SL
3493 return ret;
3494 }
3495
3496 if (zo == BLKRESETZONE && len == capacity) {
3497 ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 1);
3498 if (ret < 0) {
3499 error_report("reporting single wp failed");
3500 return ret;
3501 }
3502 } else if (zo == BLKRESETZONE) {
3503 for (unsigned int j = 0; j < nrz; ++j) {
3504 wp[j] = offset + j * zone_size;
3505 }
3506 } else if (zo == BLKFINISHZONE) {
3507 for (unsigned int j = 0; j < nrz; ++j) {
3508 /* The zoned device allows the last zone smaller that the
3509 * zone size. */
3510 wp[j] = MIN(offset + (j + 1) * zone_size, offset + len);
3511 }
6d43eaa3
SL
3512 }
3513
3514 return ret;
3515}
3516#endif
3517
33d70fb6 3518static coroutine_fn int
0c802287
VSO
3519raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes,
3520 bool blkdev)
dce512de 3521{
dce512de 3522 BDRVRawState *s = bs->opaque;
46ee0f46 3523 RawPosixAIOData acb;
1c450366 3524 int ret;
46ee0f46
KW
3525
3526 acb = (RawPosixAIOData) {
3527 .bs = bs,
3528 .aio_fildes = s->fd,
3529 .aio_type = QEMU_AIO_DISCARD,
3530 .aio_offset = offset,
3531 .aio_nbytes = bytes,
3532 };
dce512de 3533
46ee0f46
KW
3534 if (blkdev) {
3535 acb.aio_type |= QEMU_AIO_BLKDEV;
3536 }
3537
0fdb7311 3538 ret = raw_thread_pool_submit(handle_aiocb_discard, &acb);
1c450366
AN
3539 raw_account_discard(s, bytes, ret);
3540 return ret;
46ee0f46
KW
3541}
3542
3543static coroutine_fn int
0c802287 3544raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
46ee0f46
KW
3545{
3546 return raw_do_pdiscard(bs, offset, bytes, false);
dce512de 3547}
0e7e1989 3548
7154d8ae 3549static int coroutine_fn
f34b2bcf 3550raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
7154d8ae 3551 BdrvRequestFlags flags, bool blkdev)
260a82e5
PB
3552{
3553 BDRVRawState *s = bs->opaque;
7154d8ae
KW
3554 RawPosixAIOData acb;
3555 ThreadPoolFunc *handler;
3556
292d06b9
HR
3557#ifdef CONFIG_FALLOCATE
3558 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3559 BdrvTrackedRequest *req;
292d06b9
HR
3560
3561 /*
3562 * This is a workaround for a bug in the Linux XFS driver,
3563 * where writes submitted through the AIO interface will be
3564 * discarded if they happen beyond a concurrently running
3565 * fallocate() that increases the file length (i.e., both the
3566 * write and the fallocate() happen beyond the EOF).
3567 *
3568 * To work around it, we extend the tracked request for this
3569 * zero write until INT64_MAX (effectively infinity), and mark
3570 * it as serializing.
3571 *
3572 * We have to enable this workaround for all filesystems and
3573 * AIO modes (not just XFS with aio=native), because for
3574 * remote filesystems we do not know the host configuration.
3575 */
3576
3577 req = bdrv_co_get_self_request(bs);
3578 assert(req);
3579 assert(req->type == BDRV_TRACKED_WRITE);
3580 assert(req->offset <= offset);
3581 assert(req->offset + req->bytes >= offset + bytes);
3582
8b117001
VSO
3583 req->bytes = BDRV_MAX_LENGTH - req->offset;
3584
69b55e03 3585 bdrv_check_request(req->offset, req->bytes, &error_abort);
292d06b9 3586
8ac5aab2 3587 bdrv_make_request_serialising(req, bs->bl.request_alignment);
292d06b9
HR
3588 }
3589#endif
3590
7154d8ae
KW
3591 acb = (RawPosixAIOData) {
3592 .bs = bs,
3593 .aio_fildes = s->fd,
3594 .aio_type = QEMU_AIO_WRITE_ZEROES,
3595 .aio_offset = offset,
3596 .aio_nbytes = bytes,
3597 };
3598
3599 if (blkdev) {
3600 acb.aio_type |= QEMU_AIO_BLKDEV;
3601 }
738301e1
KW
3602 if (flags & BDRV_REQ_NO_FALLBACK) {
3603 acb.aio_type |= QEMU_AIO_NO_FALLBACK;
3604 }
260a82e5 3605
34fa110e 3606 if (flags & BDRV_REQ_MAY_UNMAP) {
7154d8ae
KW
3607 acb.aio_type |= QEMU_AIO_DISCARD;
3608 handler = handle_aiocb_write_zeroes_unmap;
3609 } else {
3610 handler = handle_aiocb_write_zeroes;
260a82e5 3611 }
34fa110e 3612
0fdb7311 3613 return raw_thread_pool_submit(handler, &acb);
7154d8ae
KW
3614}
3615
3616static int coroutine_fn raw_co_pwrite_zeroes(
3617 BlockDriverState *bs, int64_t offset,
f34b2bcf 3618 int64_t bytes, BdrvRequestFlags flags)
7154d8ae
KW
3619{
3620 return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
260a82e5
PB
3621}
3622
3d47eb0a
EGE
3623static int coroutine_fn
3624raw_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
260a82e5 3625{
260a82e5
PB
3626 return 0;
3627}
3628
7f36a50a
HR
3629static ImageInfoSpecific *raw_get_specific_info(BlockDriverState *bs,
3630 Error **errp)
3631{
3632 ImageInfoSpecificFile *file_info = g_new0(ImageInfoSpecificFile, 1);
3633 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
3634
3635 *spec_info = (ImageInfoSpecific){
3636 .type = IMAGE_INFO_SPECIFIC_KIND_FILE,
3637 .u.file.data = file_info,
3638 };
3639
3640#ifdef FS_IOC_FSGETXATTR
3641 {
3642 BDRVRawState *s = bs->opaque;
3643 struct fsxattr attr;
3644 int ret;
3645
3646 ret = ioctl(s->fd, FS_IOC_FSGETXATTR, &attr);
3647 if (!ret && attr.fsx_extsize != 0) {
3648 file_info->has_extent_size_hint = true;
3649 file_info->extent_size_hint = attr.fsx_extsize;
3650 }
3651 }
3652#endif
3653
3654 return spec_info;
3655}
3656
d9245599
AN
3657static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
3658{
3659 BDRVRawState *s = bs->opaque;
3660 return (BlockStatsSpecificFile) {
3661 .discard_nb_ok = s->stats.discard_nb_ok,
3662 .discard_nb_failed = s->stats.discard_nb_failed,
3663 .discard_bytes_ok = s->stats.discard_bytes_ok,
3664 };
3665}
3666
3667static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3668{
3669 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3670
3671 stats->driver = BLOCKDEV_DRIVER_FILE;
3672 stats->u.file = get_blockstats_specific_file(bs);
3673
3674 return stats;
3675}
3676
14176c8d 3677#if defined(HAVE_HOST_BLOCK_DEVICE)
d9245599
AN
3678static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3679{
3680 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3681
3682 stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3683 stats->u.host_device = get_blockstats_specific_file(bs);
3684
3685 return stats;
3686}
14176c8d 3687#endif /* HAVE_HOST_BLOCK_DEVICE */
d9245599 3688
6f482f74
CL
3689static QemuOptsList raw_create_opts = {
3690 .name = "raw-create-opts",
3691 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3692 .desc = {
3693 {
3694 .name = BLOCK_OPT_SIZE,
3695 .type = QEMU_OPT_SIZE,
3696 .help = "Virtual disk size"
3697 },
4ab15590
CL
3698 {
3699 .name = BLOCK_OPT_NOCOW,
3700 .type = QEMU_OPT_BOOL,
3701 .help = "Turn off copy-on-write (valid only on btrfs)"
3702 },
06247428
HT
3703 {
3704 .name = BLOCK_OPT_PREALLOC,
3705 .type = QEMU_OPT_STRING,
abea0053
SG
3706 .help = "Preallocation mode (allowed values: off"
3707#ifdef CONFIG_POSIX_FALLOCATE
3708 ", falloc"
3709#endif
3710 ", full)"
06247428 3711 },
ffa244c8
KW
3712 {
3713 .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3714 .type = QEMU_OPT_SIZE,
3715 .help = "Extent size hint for the image file, 0 to disable"
3716 },
6f482f74
CL
3717 { /* end of list */ }
3718 }
0e7e1989
KW
3719};
3720
244a5668
FZ
3721static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3722 Error **errp)
3723{
6ceabe6f 3724 BDRVRawState *s = bs->opaque;
72373e40 3725 int input_flags = s->reopen_state ? s->reopen_state->flags : bs->open_flags;
6ceabe6f
KW
3726 int open_flags;
3727 int ret;
3728
72373e40
VSO
3729 /* We may need a new fd if auto-read-only switches the mode */
3730 ret = raw_reconfigure_getfd(bs, input_flags, &open_flags, perm,
3731 false, errp);
3732 if (ret < 0) {
3733 return ret;
3734 } else if (ret != s->fd) {
3735 Error *local_err = NULL;
3736
6ceabe6f 3737 /*
72373e40
VSO
3738 * Fail already check_perm() if we can't get a working O_DIRECT
3739 * alignment with the new fd.
6ceabe6f 3740 */
72373e40
VSO
3741 raw_probe_alignment(bs, ret, &local_err);
3742 if (local_err) {
3743 error_propagate(errp, local_err);
3744 return -EINVAL;
6ceabe6f 3745 }
72373e40
VSO
3746
3747 s->perm_change_fd = ret;
3748 s->perm_change_flags = open_flags;
6ceabe6f
KW
3749 }
3750
3751 /* Prepare permissions on old fd to avoid conflicts between old and new,
3752 * but keep everything locked that new will need. */
3753 ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
3754 if (ret < 0) {
3755 goto fail;
3756 }
3757
3758 /* Copy locks to the new fd */
eb43ea16 3759 if (s->perm_change_fd && s->use_lock) {
6ceabe6f
KW
3760 ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
3761 false, errp);
3762 if (ret < 0) {
3763 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3764 goto fail;
3765 }
3766 }
3767 return 0;
3768
3769fail:
72373e40 3770 if (s->perm_change_fd) {
6ceabe6f
KW
3771 qemu_close(s->perm_change_fd);
3772 }
3773 s->perm_change_fd = 0;
3774 return ret;
244a5668
FZ
3775}
3776
3777static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3778{
3779 BDRVRawState *s = bs->opaque;
6ceabe6f
KW
3780
3781 /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3782 * called after .bdrv_reopen_commit) */
3783 if (s->perm_change_fd && s->fd != s->perm_change_fd) {
3784 qemu_close(s->fd);
3785 s->fd = s->perm_change_fd;
094e3639 3786 s->open_flags = s->perm_change_flags;
6ceabe6f
KW
3787 }
3788 s->perm_change_fd = 0;
3789
244a5668
FZ
3790 raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3791 s->perm = perm;
3792 s->shared_perm = shared;
3793}
3794
3795static void raw_abort_perm_update(BlockDriverState *bs)
3796{
6ceabe6f
KW
3797 BDRVRawState *s = bs->opaque;
3798
3799 /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3800 * the file descriptor. */
72373e40 3801 if (s->perm_change_fd) {
6ceabe6f
KW
3802 qemu_close(s->perm_change_fd);
3803 }
3804 s->perm_change_fd = 0;
3805
244a5668
FZ
3806 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3807}
3808
742bf09b 3809static int coroutine_fn GRAPH_RDLOCK raw_co_copy_range_from(
48535049
VSO
3810 BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
3811 BdrvChild *dst, int64_t dst_offset, int64_t bytes,
67b51fb9 3812 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
1efad060 3813{
67b51fb9
VSO
3814 return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3815 read_flags, write_flags);
1efad060
FZ
3816}
3817
742bf09b
EGE
3818static int coroutine_fn GRAPH_RDLOCK
3819raw_co_copy_range_to(BlockDriverState *bs,
3820 BdrvChild *src, int64_t src_offset,
3821 BdrvChild *dst, int64_t dst_offset,
3822 int64_t bytes, BdrvRequestFlags read_flags,
3823 BdrvRequestFlags write_flags)
1efad060 3824{
58a209c4 3825 RawPosixAIOData acb;
1efad060
FZ
3826 BDRVRawState *s = bs->opaque;
3827 BDRVRawState *src_s;
3828
3829 assert(dst->bs == bs);
3830 if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
3831 return -ENOTSUP;
3832 }
3833
3834 src_s = src->bs->opaque;
9f850f67 3835 if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
1efad060
FZ
3836 return -EIO;
3837 }
58a209c4
KW
3838
3839 acb = (RawPosixAIOData) {
3840 .bs = bs,
3841 .aio_type = QEMU_AIO_COPY_RANGE,
3842 .aio_fildes = src_s->fd,
3843 .aio_offset = src_offset,
3844 .aio_nbytes = bytes,
3845 .copy_range = {
3846 .aio_fd2 = s->fd,
3847 .aio_offset2 = dst_offset,
3848 },
3849 };
3850
0fdb7311 3851 return raw_thread_pool_submit(handle_aiocb_copy_range, &acb);
1efad060
FZ
3852}
3853
5f535a94 3854BlockDriver bdrv_file = {
84a12e66
CH
3855 .format_name = "file",
3856 .protocol_name = "file",
856ae5c3 3857 .instance_size = sizeof(BDRVRawState),
030be321 3858 .bdrv_needs_filename = true,
856ae5c3 3859 .bdrv_probe = NULL, /* no probe for protocols */
078896a9 3860 .bdrv_parse_filename = raw_parse_filename,
66f82cee 3861 .bdrv_file_open = raw_open,
eeb6b45d
JC
3862 .bdrv_reopen_prepare = raw_reopen_prepare,
3863 .bdrv_reopen_commit = raw_reopen_commit,
3864 .bdrv_reopen_abort = raw_reopen_abort,
856ae5c3 3865 .bdrv_close = raw_close,
927f11e1 3866 .bdrv_co_create = raw_co_create,
efc75e2a 3867 .bdrv_co_create_opts = raw_co_create_opts,
3ac21627 3868 .bdrv_has_zero_init = bdrv_has_zero_init_1,
a290f085 3869 .bdrv_co_block_status = raw_co_block_status,
dd577a26 3870 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
2ffa76c2 3871 .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
9bffae14 3872 .bdrv_co_delete_file = raw_co_delete_file,
3b46e624 3873
9d52aa3c
KW
3874 .bdrv_co_preadv = raw_co_preadv,
3875 .bdrv_co_pwritev = raw_co_pwritev,
33d70fb6
KW
3876 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
3877 .bdrv_co_pdiscard = raw_co_pdiscard,
1efad060
FZ
3878 .bdrv_co_copy_range_from = raw_co_copy_range_from,
3879 .bdrv_co_copy_range_to = raw_co_copy_range_to,
c25f53b0 3880 .bdrv_refresh_limits = raw_refresh_limits,
8f497454 3881 .bdrv_co_io_plug = raw_co_io_plug,
09d9fc97 3882 .bdrv_co_io_unplug = raw_co_io_unplug,
ed6e2161 3883 .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3c529d93 3884
c86422c5
EGE
3885 .bdrv_co_truncate = raw_co_truncate,
3886 .bdrv_co_getlength = raw_co_getlength,
3d47eb0a 3887 .bdrv_co_get_info = raw_co_get_info,
7f36a50a 3888 .bdrv_get_specific_info = raw_get_specific_info,
82618d7b 3889 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
d9245599 3890 .bdrv_get_specific_stats = raw_get_specific_stats,
244a5668
FZ
3891 .bdrv_check_perm = raw_check_perm,
3892 .bdrv_set_perm = raw_set_perm,
3893 .bdrv_abort_perm_update = raw_abort_perm_update,
6f482f74 3894 .create_opts = &raw_create_opts,
8a2ce0bc 3895 .mutable_opts = mutable_opts,
83f64091
FB
3896};
3897
19cb3738
FB
3898/***********************************************/
3899/* host device */
3900
14176c8d
JD
3901#if defined(HAVE_HOST_BLOCK_DEVICE)
3902
83affaa6 3903#if defined(__APPLE__) && defined(__MACH__)
98caa5bc
JA
3904static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3905 CFIndex maxPathSize, int flags);
aa44d3f6
PMD
3906
3907#if !defined(MAC_OS_VERSION_12_0) \
3908 || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3909#define IOMainPort IOMasterPort
3910#endif
3911
d0855f12 3912static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
19cb3738 3913{
d0855f12 3914 kern_return_t kernResult = KERN_FAILURE;
aa44d3f6 3915 mach_port_t mainPort;
19cb3738 3916 CFMutableDictionaryRef classesToMatch;
d0855f12
JA
3917 const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3918 char *mediaType = NULL;
19cb3738 3919
aa44d3f6 3920 kernResult = IOMainPort(MACH_PORT_NULL, &mainPort);
19cb3738 3921 if ( KERN_SUCCESS != kernResult ) {
aa44d3f6 3922 printf("IOMainPort returned %d\n", kernResult);
19cb3738 3923 }
3b46e624 3924
d0855f12
JA
3925 int index;
3926 for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3927 classesToMatch = IOServiceMatching(matching_array[index]);
3928 if (classesToMatch == NULL) {
3929 error_report("IOServiceMatching returned NULL for %s",
3930 matching_array[index]);
3931 continue;
3932 }
3933 CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3934 kCFBooleanTrue);
aa44d3f6 3935 kernResult = IOServiceGetMatchingServices(mainPort, classesToMatch,
d0855f12
JA
3936 mediaIterator);
3937 if (kernResult != KERN_SUCCESS) {
3938 error_report("Note: IOServiceGetMatchingServices returned %d",
3939 kernResult);
3940 continue;
3941 }
3b46e624 3942
d0855f12
JA
3943 /* If a match was found, leave the loop */
3944 if (*mediaIterator != 0) {
4f7d28d7 3945 trace_file_FindEjectableOpticalMedia(matching_array[index]);
d0855f12
JA
3946 mediaType = g_strdup(matching_array[index]);
3947 break;
3948 }
3949 }
3950 return mediaType;
19cb3738
FB
3951}
3952
98caa5bc
JA
3953kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3954 CFIndex maxPathSize, int flags)
19cb3738
FB
3955{
3956 io_object_t nextMedia;
3957 kern_return_t kernResult = KERN_FAILURE;
3958 *bsdPath = '\0';
3959 nextMedia = IOIteratorNext( mediaIterator );
3960 if ( nextMedia )
3961 {
3962 CFTypeRef bsdPathAsCFString;
3963 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3964 if ( bsdPathAsCFString ) {
3965 size_t devPathLength;
3966 strcpy( bsdPath, _PATH_DEV );
98caa5bc
JA
3967 if (flags & BDRV_O_NOCACHE) {
3968 strcat(bsdPath, "r");
3969 }
19cb3738
FB
3970 devPathLength = strlen( bsdPath );
3971 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3972 kernResult = KERN_SUCCESS;
3973 }
3974 CFRelease( bsdPathAsCFString );
3975 }
3976 IOObjectRelease( nextMedia );
3977 }
3b46e624 3978
19cb3738
FB
3979 return kernResult;
3980}
3981
d0855f12
JA
3982/* Sets up a real cdrom for use in QEMU */
3983static bool setup_cdrom(char *bsd_path, Error **errp)
3984{
3985 int index, num_of_test_partitions = 2, fd;
3986 char test_partition[MAXPATHLEN];
3987 bool partition_found = false;
3988
3989 /* look for a working partition */
3990 for (index = 0; index < num_of_test_partitions; index++) {
3991 snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
3992 index);
b18a24a9 3993 fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
d0855f12
JA
3994 if (fd >= 0) {
3995 partition_found = true;
3996 qemu_close(fd);
3997 break;
3998 }
3999 }
4000
4001 /* if a working partition on the device was not found */
4002 if (partition_found == false) {
4003 error_setg(errp, "Failed to find a working partition on disc");
4004 } else {
4f7d28d7 4005 trace_file_setup_cdrom(test_partition);
d0855f12
JA
4006 pstrcpy(bsd_path, MAXPATHLEN, test_partition);
4007 }
4008 return partition_found;
4009}
4010
4011/* Prints directions on mounting and unmounting a device */
4012static void print_unmounting_directions(const char *file_name)
4013{
4014 error_report("If device %s is mounted on the desktop, unmount"
4015 " it first before using it in QEMU", file_name);
4016 error_report("Command to unmount device: diskutil unmountDisk %s",
4017 file_name);
4018 error_report("Command to mount device: diskutil mountDisk %s", file_name);
4019}
4020
4021#endif /* defined(__APPLE__) && defined(__MACH__) */
19cb3738 4022
508c7cb3
CH
4023static int hdev_probe_device(const char *filename)
4024{
4025 struct stat st;
4026
4027 /* allow a dedicated CD-ROM driver to match with a higher priority */
4028 if (strstart(filename, "/dev/cdrom", NULL))
4029 return 50;
4030
4031 if (stat(filename, &st) >= 0 &&
4032 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
4033 return 100;
4034 }
4035
4036 return 0;
4037}
4038
7af803d4
HR
4039static void hdev_parse_filename(const char *filename, QDict *options,
4040 Error **errp)
4041{
03c320d8 4042 bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
7af803d4
HR
4043}
4044
3307ed7b
DA
4045static bool hdev_is_sg(BlockDriverState *bs)
4046{
4047
4048#if defined(__linux__)
4049
0d4377b3 4050 BDRVRawState *s = bs->opaque;
3307ed7b
DA
4051 struct stat st;
4052 struct sg_scsi_id scsiid;
4053 int sg_version;
0d4377b3
KW
4054 int ret;
4055
4056 if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
4057 return false;
4058 }
3307ed7b 4059
0d4377b3
KW
4060 ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
4061 if (ret < 0) {
4062 return false;
4063 }
4064
4065 ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
4066 if (ret >= 0) {
4f7d28d7 4067 trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
3307ed7b
DA
4068 return true;
4069 }
4070
4071#endif
4072
4073 return false;
4074}
4075
015a1036
HR
4076static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
4077 Error **errp)
19cb3738
FB
4078{
4079 BDRVRawState *s = bs->opaque;
da888d37 4080 int ret;
a76bab49 4081
83affaa6 4082#if defined(__APPLE__) && defined(__MACH__)
129c7d1c
MA
4083 /*
4084 * Caution: while qdict_get_str() is fine, getting non-string types
4085 * would require more care. When @options come from -blockdev or
4086 * blockdev_add, its members are typed according to the QAPI
4087 * schema, but when they come from -drive, they're all QString.
4088 */
3307ed7b 4089 const char *filename = qdict_get_str(options, "filename");
d0855f12
JA
4090 char bsd_path[MAXPATHLEN] = "";
4091 bool error_occurred = false;
4092
4093 /* If using a real cdrom */
4094 if (strcmp(filename, "/dev/cdrom") == 0) {
4095 char *mediaType = NULL;
4096 kern_return_t ret_val;
4097 io_iterator_t mediaIterator = 0;
4098
4099 mediaType = FindEjectableOpticalMedia(&mediaIterator);
4100 if (mediaType == NULL) {
4101 error_setg(errp, "Please make sure your CD/DVD is in the optical"
4102 " drive");
4103 error_occurred = true;
4104 goto hdev_open_Mac_error;
4105 }
3307ed7b 4106
d0855f12
JA
4107 ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
4108 if (ret_val != KERN_SUCCESS) {
4109 error_setg(errp, "Could not get BSD path for optical drive");
4110 error_occurred = true;
4111 goto hdev_open_Mac_error;
4112 }
4113
4114 /* If a real optical drive was not found */
4115 if (bsd_path[0] == '\0') {
4116 error_setg(errp, "Failed to obtain bsd path for optical drive");
4117 error_occurred = true;
4118 goto hdev_open_Mac_error;
4119 }
4120
4121 /* If using a cdrom disc and finding a partition on the disc failed */
4122 if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
4123 setup_cdrom(bsd_path, errp) == false) {
4124 print_unmounting_directions(bsd_path);
4125 error_occurred = true;
4126 goto hdev_open_Mac_error;
19cb3738 4127 }
3b46e624 4128
46f5ac20 4129 qdict_put_str(options, "filename", bsd_path);
d0855f12
JA
4130
4131hdev_open_Mac_error:
4132 g_free(mediaType);
4133 if (mediaIterator) {
4134 IOObjectRelease(mediaIterator);
4135 }
4136 if (error_occurred) {
4137 return -ENOENT;
4138 }
19cb3738 4139 }
d0855f12 4140#endif /* defined(__APPLE__) && defined(__MACH__) */
19cb3738
FB
4141
4142 s->type = FTYPE_FILE;
90babde0 4143
668f62ec 4144 ret = raw_open_common(bs, options, flags, 0, true, errp);
da888d37 4145 if (ret < 0) {
d0855f12
JA
4146#if defined(__APPLE__) && defined(__MACH__)
4147 if (*bsd_path) {
4148 filename = bsd_path;
4149 }
4150 /* if a physical device experienced an error while being opened */
4151 if (strncmp(filename, "/dev/", 5) == 0) {
4152 print_unmounting_directions(filename);
4153 }
4154#endif /* defined(__APPLE__) && defined(__MACH__) */
da888d37
SH
4155 return ret;
4156 }
4157
3307ed7b
DA
4158 /* Since this does ioctl the device must be already opened */
4159 bs->sg = hdev_is_sg(bs);
4160
da888d37 4161 return ret;
19cb3738
FB
4162}
4163
03ff3ca3 4164#if defined(__linux__)
2f3a7ab3
KW
4165static int coroutine_fn
4166hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
221f715d 4167{
f141eafe 4168 BDRVRawState *s = bs->opaque;
03425671 4169 RawPosixAIOData acb;
2f3a7ab3 4170 int ret;
221f715d 4171
2f3a7ab3
KW
4172 ret = fd_open(bs);
4173 if (ret < 0) {
4174 return ret;
4175 }
c208e8c2 4176
7c9e5276
PB
4177 if (req == SG_IO && s->pr_mgr) {
4178 struct sg_io_hdr *io_hdr = buf;
4179 if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
4180 io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
0fdb7311 4181 return pr_manager_execute(s->pr_mgr, qemu_get_current_aio_context(),
2f3a7ab3 4182 s->fd, io_hdr);
7c9e5276
PB
4183 }
4184 }
4185
03425671
KW
4186 acb = (RawPosixAIOData) {
4187 .bs = bs,
4188 .aio_type = QEMU_AIO_IOCTL,
4189 .aio_fildes = s->fd,
4190 .aio_offset = 0,
4191 .ioctl = {
4192 .buf = buf,
4193 .cmd = req,
4194 },
4195 };
4196
0fdb7311 4197 return raw_thread_pool_submit(handle_aiocb_ioctl, &acb);
221f715d 4198}
f709623b 4199#endif /* linux */
221f715d 4200
33d70fb6 4201static coroutine_fn int
0c802287 4202hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
c36dd8a0 4203{
1c450366 4204 BDRVRawState *s = bs->opaque;
33d70fb6 4205 int ret;
c36dd8a0 4206
33d70fb6
KW
4207 ret = fd_open(bs);
4208 if (ret < 0) {
1c450366 4209 raw_account_discard(s, bytes, ret);
33d70fb6 4210 return ret;
c36dd8a0 4211 }
46ee0f46 4212 return raw_do_pdiscard(bs, offset, bytes, true);
c36dd8a0
AF
4213}
4214
2ffa76c2 4215static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
f34b2bcf 4216 int64_t offset, int64_t bytes, BdrvRequestFlags flags)
d0b4503e 4217{
d0b4503e
PB
4218 int rc;
4219
4220 rc = fd_open(bs);
4221 if (rc < 0) {
4222 return rc;
4223 }
34fa110e 4224
7154d8ae 4225 return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
d0b4503e
PB
4226}
4227
5efa9d5a 4228static BlockDriver bdrv_host_device = {
0b4ce02e 4229 .format_name = "host_device",
84a12e66 4230 .protocol_name = "host_device",
0b4ce02e 4231 .instance_size = sizeof(BDRVRawState),
030be321 4232 .bdrv_needs_filename = true,
0b4ce02e 4233 .bdrv_probe_device = hdev_probe_device,
7af803d4 4234 .bdrv_parse_filename = hdev_parse_filename,
66f82cee 4235 .bdrv_file_open = hdev_open,
0b4ce02e 4236 .bdrv_close = raw_close,
1bc6b705
JC
4237 .bdrv_reopen_prepare = raw_reopen_prepare,
4238 .bdrv_reopen_commit = raw_reopen_commit,
4239 .bdrv_reopen_abort = raw_reopen_abort,
5a5e7f8c
ML
4240 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4241 .create_opts = &bdrv_create_opts_simple,
8a2ce0bc 4242 .mutable_opts = mutable_opts,
dd577a26 4243 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
2ffa76c2 4244 .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3b46e624 4245
9d52aa3c
KW
4246 .bdrv_co_preadv = raw_co_preadv,
4247 .bdrv_co_pwritev = raw_co_pwritev,
33d70fb6
KW
4248 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
4249 .bdrv_co_pdiscard = hdev_co_pdiscard,
1efad060
FZ
4250 .bdrv_co_copy_range_from = raw_co_copy_range_from,
4251 .bdrv_co_copy_range_to = raw_co_copy_range_to,
c25f53b0 4252 .bdrv_refresh_limits = raw_refresh_limits,
8f497454 4253 .bdrv_co_io_plug = raw_co_io_plug,
09d9fc97 4254 .bdrv_co_io_unplug = raw_co_io_unplug,
042b757c 4255 .bdrv_attach_aio_context = raw_aio_attach_aio_context,
3c529d93 4256
c86422c5
EGE
4257 .bdrv_co_truncate = raw_co_truncate,
4258 .bdrv_co_getlength = raw_co_getlength,
3d47eb0a 4259 .bdrv_co_get_info = raw_co_get_info,
7f36a50a 4260 .bdrv_get_specific_info = raw_get_specific_info,
82618d7b 4261 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
d9245599 4262 .bdrv_get_specific_stats = hdev_get_specific_stats,
244a5668
FZ
4263 .bdrv_check_perm = raw_check_perm,
4264 .bdrv_set_perm = raw_set_perm,
4265 .bdrv_abort_perm_update = raw_abort_perm_update,
1a9335e4
ET
4266 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
4267 .bdrv_probe_geometry = hdev_probe_geometry,
19cb3738 4268
f3a5d3f8 4269 /* generic scsi device */
63ec93db 4270#ifdef __linux__
2f3a7ab3 4271 .bdrv_co_ioctl = hdev_co_ioctl,
63ec93db 4272#endif
6d43eaa3
SL
4273
4274 /* zoned device */
4275#if defined(CONFIG_BLKZONED)
4276 /* zone management operations */
4277 .bdrv_co_zone_report = raw_co_zone_report,
4278 .bdrv_co_zone_mgmt = raw_co_zone_mgmt,
4279#endif
f3a5d3f8
CH
4280};
4281
18fa1c42
HR
4282#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4283static void cdrom_parse_filename(const char *filename, QDict *options,
4284 Error **errp)
4285{
03c320d8 4286 bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
18fa1c42 4287}
8c6f27e7
PB
4288
4289static void cdrom_refresh_limits(BlockDriverState *bs, Error **errp)
4290{
4291 bs->bl.has_variable_length = true;
4292 raw_refresh_limits(bs, errp);
4293}
18fa1c42
HR
4294#endif
4295
4296#ifdef __linux__
015a1036
HR
4297static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4298 Error **errp)
f3a5d3f8
CH
4299{
4300 BDRVRawState *s = bs->opaque;
4301
f3a5d3f8
CH
4302 s->type = FTYPE_CD;
4303
19a3da7f 4304 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
230ff739 4305 return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
f3a5d3f8
CH
4306}
4307
508c7cb3
CH
4308static int cdrom_probe_device(const char *filename)
4309{
3baf720e
CR
4310 int fd, ret;
4311 int prio = 0;
343f8568 4312 struct stat st;
3baf720e 4313
b18a24a9 4314 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
3baf720e
CR
4315 if (fd < 0) {
4316 goto out;
4317 }
343f8568
JS
4318 ret = fstat(fd, &st);
4319 if (ret == -1 || !S_ISBLK(st.st_mode)) {
4320 goto outc;
4321 }
3baf720e
CR
4322
4323 /* Attempt to detect via a CDROM specific ioctl */
4324 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
4325 if (ret >= 0)
4326 prio = 100;
4327
343f8568 4328outc:
2e1e79da 4329 qemu_close(fd);
3baf720e
CR
4330out:
4331 return prio;
508c7cb3
CH
4332}
4333
1e97be91 4334static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
f3a5d3f8
CH
4335{
4336 BDRVRawState *s = bs->opaque;
4337 int ret;
4338
4339 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
e031f750 4340 return ret == CDS_DISC_OK;
f3a5d3f8
CH
4341}
4342
2531b390 4343static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
4344{
4345 BDRVRawState *s = bs->opaque;
4346
4347 if (eject_flag) {
4348 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
4349 perror("CDROMEJECT");
4350 } else {
4351 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
4352 perror("CDROMEJECT");
4353 }
f3a5d3f8
CH
4354}
4355
2c75261c 4356static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
4357{
4358 BDRVRawState *s = bs->opaque;
4359
4360 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
4361 /*
4362 * Note: an error can happen if the distribution automatically
4363 * mounts the CD-ROM
4364 */
4365 /* perror("CDROM_LOCKDOOR"); */
4366 }
f3a5d3f8
CH
4367}
4368
4369static BlockDriver bdrv_host_cdrom = {
4370 .format_name = "host_cdrom",
84a12e66 4371 .protocol_name = "host_cdrom",
f3a5d3f8 4372 .instance_size = sizeof(BDRVRawState),
030be321 4373 .bdrv_needs_filename = true,
508c7cb3 4374 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 4375 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 4376 .bdrv_file_open = cdrom_open,
f3a5d3f8 4377 .bdrv_close = raw_close,
1bc6b705
JC
4378 .bdrv_reopen_prepare = raw_reopen_prepare,
4379 .bdrv_reopen_commit = raw_reopen_commit,
4380 .bdrv_reopen_abort = raw_reopen_abort,
5a5e7f8c
ML
4381 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4382 .create_opts = &bdrv_create_opts_simple,
8a2ce0bc 4383 .mutable_opts = mutable_opts,
dd577a26 4384 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
f3a5d3f8 4385
9d52aa3c
KW
4386 .bdrv_co_preadv = raw_co_preadv,
4387 .bdrv_co_pwritev = raw_co_pwritev,
33d70fb6 4388 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
8c6f27e7 4389 .bdrv_refresh_limits = cdrom_refresh_limits,
8f497454 4390 .bdrv_co_io_plug = raw_co_io_plug,
09d9fc97 4391 .bdrv_co_io_unplug = raw_co_io_unplug,
042b757c 4392 .bdrv_attach_aio_context = raw_aio_attach_aio_context,
f3a5d3f8 4393
c86422c5
EGE
4394 .bdrv_co_truncate = raw_co_truncate,
4395 .bdrv_co_getlength = raw_co_getlength,
82618d7b 4396 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
f3a5d3f8
CH
4397
4398 /* removable device support */
1e97be91 4399 .bdrv_co_is_inserted = cdrom_co_is_inserted,
2531b390 4400 .bdrv_co_eject = cdrom_co_eject,
2c75261c 4401 .bdrv_co_lock_medium = cdrom_co_lock_medium,
f3a5d3f8
CH
4402
4403 /* generic scsi device */
2f3a7ab3 4404 .bdrv_co_ioctl = hdev_co_ioctl,
f3a5d3f8
CH
4405};
4406#endif /* __linux__ */
4407
a167ba50 4408#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
511018e4
AT
4409static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4410 Error **errp)
f3a5d3f8
CH
4411{
4412 BDRVRawState *s = bs->opaque;
4413 int ret;
4414
4415 s->type = FTYPE_CD;
4416
668f62ec 4417 ret = raw_open_common(bs, options, flags, 0, true, errp);
e428e439 4418 if (ret) {
f3a5d3f8 4419 return ret;
e428e439 4420 }
f3a5d3f8 4421
9b2260cb 4422 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
4423 ioctl(s->fd, CDIOCALLOW);
4424 return 0;
4425}
4426
508c7cb3
CH
4427static int cdrom_probe_device(const char *filename)
4428{
4429 if (strstart(filename, "/dev/cd", NULL) ||
4430 strstart(filename, "/dev/acd", NULL))
4431 return 100;
4432 return 0;
4433}
4434
f3a5d3f8
CH
4435static int cdrom_reopen(BlockDriverState *bs)
4436{
4437 BDRVRawState *s = bs->opaque;
4438 int fd;
4439
4440 /*
4441 * Force reread of possibly changed/newly loaded disc,
4442 * FreeBSD seems to not notice sometimes...
4443 */
4444 if (s->fd >= 0)
2e1e79da 4445 qemu_close(s->fd);
b18a24a9 4446 fd = qemu_open(bs->filename, s->open_flags, NULL);
f3a5d3f8
CH
4447 if (fd < 0) {
4448 s->fd = -1;
4449 return -EIO;
4450 }
4451 s->fd = fd;
4452
9b2260cb 4453 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
4454 ioctl(s->fd, CDIOCALLOW);
4455 return 0;
4456}
4457
1e97be91 4458static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
f3a5d3f8 4459{
c86422c5 4460 return raw_co_getlength(bs) > 0;
f3a5d3f8
CH
4461}
4462
2531b390 4463static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
4464{
4465 BDRVRawState *s = bs->opaque;
4466
4467 if (s->fd < 0)
822e1cd1 4468 return;
f3a5d3f8
CH
4469
4470 (void) ioctl(s->fd, CDIOCALLOW);
4471
4472 if (eject_flag) {
4473 if (ioctl(s->fd, CDIOCEJECT) < 0)
4474 perror("CDIOCEJECT");
4475 } else {
4476 if (ioctl(s->fd, CDIOCCLOSE) < 0)
4477 perror("CDIOCCLOSE");
4478 }
4479
822e1cd1 4480 cdrom_reopen(bs);
f3a5d3f8
CH
4481}
4482
2c75261c 4483static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
4484{
4485 BDRVRawState *s = bs->opaque;
4486
4487 if (s->fd < 0)
7bf37fed 4488 return;
f3a5d3f8
CH
4489 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
4490 /*
4491 * Note: an error can happen if the distribution automatically
4492 * mounts the CD-ROM
4493 */
4494 /* perror("CDROM_LOCKDOOR"); */
4495 }
f3a5d3f8
CH
4496}
4497
4498static BlockDriver bdrv_host_cdrom = {
4499 .format_name = "host_cdrom",
84a12e66 4500 .protocol_name = "host_cdrom",
f3a5d3f8 4501 .instance_size = sizeof(BDRVRawState),
030be321 4502 .bdrv_needs_filename = true,
508c7cb3 4503 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 4504 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 4505 .bdrv_file_open = cdrom_open,
f3a5d3f8 4506 .bdrv_close = raw_close,
1bc6b705
JC
4507 .bdrv_reopen_prepare = raw_reopen_prepare,
4508 .bdrv_reopen_commit = raw_reopen_commit,
4509 .bdrv_reopen_abort = raw_reopen_abort,
5a5e7f8c
ML
4510 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4511 .create_opts = &bdrv_create_opts_simple,
8a2ce0bc 4512 .mutable_opts = mutable_opts,
f3a5d3f8 4513
9d52aa3c
KW
4514 .bdrv_co_preadv = raw_co_preadv,
4515 .bdrv_co_pwritev = raw_co_pwritev,
33d70fb6 4516 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
8c6f27e7 4517 .bdrv_refresh_limits = cdrom_refresh_limits,
8f497454 4518 .bdrv_co_io_plug = raw_co_io_plug,
09d9fc97 4519 .bdrv_co_io_unplug = raw_co_io_unplug,
042b757c 4520 .bdrv_attach_aio_context = raw_aio_attach_aio_context,
f3a5d3f8 4521
c86422c5
EGE
4522 .bdrv_co_truncate = raw_co_truncate,
4523 .bdrv_co_getlength = raw_co_getlength,
82618d7b 4524 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
f3a5d3f8 4525
19cb3738 4526 /* removable device support */
1e97be91 4527 .bdrv_co_is_inserted = cdrom_co_is_inserted,
2531b390 4528 .bdrv_co_eject = cdrom_co_eject,
2c75261c 4529 .bdrv_co_lock_medium = cdrom_co_lock_medium,
19cb3738 4530};
f3a5d3f8 4531#endif /* __FreeBSD__ */
5efa9d5a 4532
14176c8d
JD
4533#endif /* HAVE_HOST_BLOCK_DEVICE */
4534
84a12e66 4535static void bdrv_file_init(void)
5efa9d5a 4536{
508c7cb3
CH
4537 /*
4538 * Register all the drivers. Note that order is important, the driver
4539 * registered last will get probed first.
4540 */
84a12e66 4541 bdrv_register(&bdrv_file);
14176c8d 4542#if defined(HAVE_HOST_BLOCK_DEVICE)
5efa9d5a 4543 bdrv_register(&bdrv_host_device);
f3a5d3f8 4544#ifdef __linux__
f3a5d3f8
CH
4545 bdrv_register(&bdrv_host_cdrom);
4546#endif
a167ba50 4547#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8
CH
4548 bdrv_register(&bdrv_host_cdrom);
4549#endif
14176c8d 4550#endif /* HAVE_HOST_BLOCK_DEVICE */
5efa9d5a
AL
4551}
4552
84a12e66 4553block_init(bdrv_file_init);