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