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