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