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