]> git.proxmox.com Git - mirror_qemu.git/blame - block/file-posix.c
block: Switch passthrough drivers to .bdrv_co_block_status()
[mirror_qemu.git] / block / file-posix.c
CommitLineData
83f64091 1/*
223d4670 2 * Block driver for RAW files (posix)
5fafdf24 3 *
83f64091 4 * Copyright (c) 2006 Fabrice Bellard
5fafdf24 5 *
83f64091
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
922a01a0 24
80c71a24 25#include "qemu/osdep.h"
da34e65c 26#include "qapi/error.h"
f348b6d1 27#include "qemu/cutils.h"
d49b6836 28#include "qemu/error-report.h"
737e150e 29#include "block/block_int.h"
1de7afc9 30#include "qemu/module.h"
922a01a0 31#include "qemu/option.h"
de81a169 32#include "trace.h"
737e150e 33#include "block/thread-pool.h"
1de7afc9 34#include "qemu/iov.h"
0187f5c9 35#include "block/raw-aio.h"
452fcdbc 36#include "qapi/qmp/qdict.h"
d49b6836 37#include "qapi/qmp/qstring.h"
83f64091 38
7c9e5276
PB
39#include "scsi/pr-manager.h"
40#include "scsi/constants.h"
41
83affaa6 42#if defined(__APPLE__) && (__MACH__)
83f64091
FB
43#include <paths.h>
44#include <sys/param.h>
45#include <IOKit/IOKitLib.h>
46#include <IOKit/IOBSD.h>
47#include <IOKit/storage/IOMediaBSDClient.h>
48#include <IOKit/storage/IOMedia.h>
49#include <IOKit/storage/IOCDMedia.h>
50//#include <IOKit/storage/IOCDTypes.h>
d0855f12 51#include <IOKit/storage/IODVDMedia.h>
83f64091
FB
52#include <CoreFoundation/CoreFoundation.h>
53#endif
54
55#ifdef __sun__
2e9671da 56#define _POSIX_PTHREAD_SEMANTICS 1
83f64091
FB
57#include <sys/dkio.h>
58#endif
19cb3738
FB
59#ifdef __linux__
60#include <sys/ioctl.h>
05acda4d 61#include <sys/param.h>
19cb3738
FB
62#include <linux/cdrom.h>
63#include <linux/fd.h>
5500316d 64#include <linux/fs.h>
1a9335e4 65#include <linux/hdreg.h>
3307ed7b 66#include <scsi/sg.h>
1a9335e4
ET
67#ifdef __s390__
68#include <asm/dasd.h>
69#endif
4ab15590
CL
70#ifndef FS_NOCOW_FL
71#define FS_NOCOW_FL 0x00800000 /* Do not cow file */
72#endif
5500316d 73#endif
b953f075 74#if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
3d4fa43e
KK
75#include <linux/falloc.h>
76#endif
a167ba50 77#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1cb6c3fd 78#include <sys/disk.h>
9f23011a 79#include <sys/cdio.h>
1cb6c3fd 80#endif
83f64091 81
128ab2ff
BS
82#ifdef __OpenBSD__
83#include <sys/ioctl.h>
84#include <sys/disklabel.h>
85#include <sys/dkio.h>
86#endif
87
d1f6fd8d
CE
88#ifdef __NetBSD__
89#include <sys/ioctl.h>
90#include <sys/disklabel.h>
91#include <sys/dkio.h>
92#include <sys/disk.h>
93#endif
94
c5e97233
BS
95#ifdef __DragonFly__
96#include <sys/ioctl.h>
97#include <sys/diskslice.h>
98#endif
99
dce512de
CH
100#ifdef CONFIG_XFS
101#include <xfs/xfs.h>
102#endif
103
faf07963 104//#define DEBUG_BLOCK
bcb22555
DA
105
106#ifdef DEBUG_BLOCK
107# define DEBUG_BLOCK_PRINT 1
8c05dbf9 108#else
bcb22555 109# define DEBUG_BLOCK_PRINT 0
8c05dbf9 110#endif
bcb22555
DA
111#define DPRINTF(fmt, ...) \
112do { \
113 if (DEBUG_BLOCK_PRINT) { \
114 printf(fmt, ## __VA_ARGS__); \
115 } \
116} while (0)
8c05dbf9 117
f6465578
AL
118/* OS X does not have O_DSYNC */
119#ifndef O_DSYNC
1c27a8b3 120#ifdef O_SYNC
7ab064d2 121#define O_DSYNC O_SYNC
1c27a8b3
JA
122#elif defined(O_FSYNC)
123#define O_DSYNC O_FSYNC
124#endif
f6465578
AL
125#endif
126
9f7965c7
AL
127/* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
128#ifndef O_DIRECT
129#define O_DIRECT O_DSYNC
130#endif
131
19cb3738
FB
132#define FTYPE_FILE 0
133#define FTYPE_CD 1
83f64091 134
581b9e29
CH
135#define MAX_BLOCKSIZE 4096
136
244a5668
FZ
137/* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
138 * leaving a few more bytes for its future use. */
139#define RAW_LOCK_PERM_BASE 100
140#define RAW_LOCK_SHARED_BASE 200
141
19cb3738
FB
142typedef struct BDRVRawState {
143 int fd;
244a5668
FZ
144 int lock_fd;
145 bool use_lock;
19cb3738 146 int type;
0e1d8f4c 147 int open_flags;
c25f53b0
PB
148 size_t buf_align;
149
244a5668
FZ
150 /* The current permissions. */
151 uint64_t perm;
152 uint64_t shared_perm;
153
dce512de 154#ifdef CONFIG_XFS
260a82e5 155 bool is_xfs:1;
dce512de 156#endif
260a82e5 157 bool has_discard:1;
97a2ae34 158 bool has_write_zeroes:1;
260a82e5 159 bool discard_zeroes:1;
0a4279d9 160 bool use_linux_aio:1;
e5bcf967 161 bool page_cache_inconsistent:1;
d50d8222 162 bool has_fallocate;
3cad8307 163 bool needs_alignment;
7c9e5276
PB
164
165 PRManager *pr_mgr;
19cb3738
FB
166} BDRVRawState;
167
eeb6b45d
JC
168typedef struct BDRVRawReopenState {
169 int fd;
170 int open_flags;
eeb6b45d
JC
171} BDRVRawReopenState;
172
19cb3738 173static int fd_open(BlockDriverState *bs);
22afa7b5 174static int64_t raw_getlength(BlockDriverState *bs);
83f64091 175
de81a169
PB
176typedef struct RawPosixAIOData {
177 BlockDriverState *bs;
178 int aio_fildes;
179 union {
180 struct iovec *aio_iov;
181 void *aio_ioctl_buf;
182 };
183 int aio_niov;
8238010b 184 uint64_t aio_nbytes;
de81a169
PB
185#define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
186 off_t aio_offset;
187 int aio_type;
188} RawPosixAIOData;
189
a167ba50 190#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8 191static int cdrom_reopen(BlockDriverState *bs);
9f23011a
BS
192#endif
193
1de1ae0a
CE
194#if defined(__NetBSD__)
195static int raw_normalize_devicepath(const char **filename)
196{
197 static char namebuf[PATH_MAX];
198 const char *dp, *fname;
199 struct stat sb;
200
201 fname = *filename;
202 dp = strrchr(fname, '/');
203 if (lstat(fname, &sb) < 0) {
204 fprintf(stderr, "%s: stat failed: %s\n",
205 fname, strerror(errno));
206 return -errno;
207 }
208
209 if (!S_ISBLK(sb.st_mode)) {
210 return 0;
211 }
212
213 if (dp == NULL) {
214 snprintf(namebuf, PATH_MAX, "r%s", fname);
215 } else {
216 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
217 (int)(dp - fname), fname, dp + 1);
218 }
219 fprintf(stderr, "%s is a block device", fname);
220 *filename = namebuf;
221 fprintf(stderr, ", using %s\n", *filename);
222
223 return 0;
224}
225#else
226static int raw_normalize_devicepath(const char **filename)
227{
228 return 0;
229}
230#endif
231
8a4ed0d1
ET
232/*
233 * Get logical block size via ioctl. On success store it in @sector_size_p.
234 */
235static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
c25f53b0 236{
c25f53b0 237 unsigned int sector_size;
8a4ed0d1 238 bool success = false;
700f9ce0 239 int i;
c25f53b0 240
8a4ed0d1 241 errno = ENOTSUP;
700f9ce0 242 static const unsigned long ioctl_list[] = {
c25f53b0 243#ifdef BLKSSZGET
700f9ce0 244 BLKSSZGET,
c25f53b0
PB
245#endif
246#ifdef DKIOCGETBLOCKSIZE
700f9ce0 247 DKIOCGETBLOCKSIZE,
c25f53b0
PB
248#endif
249#ifdef DIOCGSECTORSIZE
700f9ce0 250 DIOCGSECTORSIZE,
c25f53b0 251#endif
700f9ce0
PM
252 };
253
254 /* Try a few ioctls to get the right size */
255 for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
256 if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
257 *sector_size_p = sector_size;
258 success = true;
259 }
260 }
8a4ed0d1
ET
261
262 return success ? 0 : -errno;
263}
264
1a9335e4
ET
265/**
266 * Get physical block size of @fd.
267 * On success, store it in @blk_size and return 0.
268 * On failure, return -errno.
269 */
270static int probe_physical_blocksize(int fd, unsigned int *blk_size)
271{
272#ifdef BLKPBSZGET
273 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
274 return -errno;
275 }
276 return 0;
277#else
278 return -ENOTSUP;
279#endif
280}
281
22d182e8
SH
282/* Check if read is allowed with given memory buffer and length.
283 *
284 * This function is used to check O_DIRECT memory buffer and request alignment.
285 */
286static bool raw_is_io_aligned(int fd, void *buf, size_t len)
287{
288 ssize_t ret = pread(fd, buf, len, 0);
289
290 if (ret >= 0) {
291 return true;
292 }
293
294#ifdef __linux__
295 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
296 * other errors (e.g. real I/O error), which could happen on a failed
297 * drive, since we only care about probing alignment.
298 */
299 if (errno != EINVAL) {
300 return true;
301 }
302#endif
303
304 return false;
305}
306
8a4ed0d1
ET
307static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
308{
309 BDRVRawState *s = bs->opaque;
310 char *buf;
459b4e66 311 size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
8a4ed0d1 312
b192af8a 313 /* For SCSI generic devices the alignment is not really used.
8a4ed0d1 314 With buffered I/O, we don't have any restrictions. */
b192af8a 315 if (bdrv_is_sg(bs) || !s->needs_alignment) {
a5b8dd2c 316 bs->bl.request_alignment = 1;
8a4ed0d1
ET
317 s->buf_align = 1;
318 return;
319 }
320
a5b8dd2c 321 bs->bl.request_alignment = 0;
8a4ed0d1
ET
322 s->buf_align = 0;
323 /* Let's try to use the logical blocksize for the alignment. */
a5b8dd2c
EB
324 if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
325 bs->bl.request_alignment = 0;
8a4ed0d1 326 }
c25f53b0
PB
327#ifdef CONFIG_XFS
328 if (s->is_xfs) {
329 struct dioattr da;
df26a350 330 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
a5b8dd2c 331 bs->bl.request_alignment = da.d_miniosz;
c25f53b0
PB
332 /* The kernel returns wrong information for d_mem */
333 /* s->buf_align = da.d_mem; */
334 }
335 }
336#endif
337
338 /* If we could not get the sizes so far, we can only guess them */
339 if (!s->buf_align) {
340 size_t align;
459b4e66
DL
341 buf = qemu_memalign(max_align, 2 * max_align);
342 for (align = 512; align <= max_align; align <<= 1) {
343 if (raw_is_io_aligned(fd, buf + align, max_align)) {
c25f53b0
PB
344 s->buf_align = align;
345 break;
346 }
347 }
348 qemu_vfree(buf);
349 }
350
a5b8dd2c 351 if (!bs->bl.request_alignment) {
c25f53b0 352 size_t align;
459b4e66
DL
353 buf = qemu_memalign(s->buf_align, max_align);
354 for (align = 512; align <= max_align; align <<= 1) {
22d182e8 355 if (raw_is_io_aligned(fd, buf, align)) {
a5b8dd2c 356 bs->bl.request_alignment = align;
c25f53b0
PB
357 break;
358 }
359 }
360 qemu_vfree(buf);
361 }
df26a350 362
a5b8dd2c 363 if (!s->buf_align || !bs->bl.request_alignment) {
8cc9c6e9
EB
364 error_setg(errp, "Could not find working O_DIRECT alignment");
365 error_append_hint(errp, "Try cache.direct=off\n");
df26a350 366 }
c25f53b0
PB
367}
368
6a8dc042
JC
369static void raw_parse_flags(int bdrv_flags, int *open_flags)
370{
371 assert(open_flags != NULL);
372
373 *open_flags |= O_BINARY;
374 *open_flags &= ~O_ACCMODE;
375 if (bdrv_flags & BDRV_O_RDWR) {
376 *open_flags |= O_RDWR;
377 } else {
378 *open_flags |= O_RDONLY;
379 }
380
381 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
382 * and O_DIRECT for no caching. */
383 if ((bdrv_flags & BDRV_O_NOCACHE)) {
384 *open_flags |= O_DIRECT;
385 }
6a8dc042
JC
386}
387
078896a9
HR
388static void raw_parse_filename(const char *filename, QDict *options,
389 Error **errp)
390{
03c320d8 391 bdrv_parse_filename_strip_prefix(filename, "file:", options);
078896a9
HR
392}
393
c66a6157
KW
394static QemuOptsList raw_runtime_opts = {
395 .name = "raw",
396 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
397 .desc = {
398 {
399 .name = "filename",
400 .type = QEMU_OPT_STRING,
401 .help = "File name of the image",
402 },
0a4279d9
KW
403 {
404 .name = "aio",
405 .type = QEMU_OPT_STRING,
406 .help = "host AIO implementation (threads, native)",
407 },
16b48d5d
FZ
408 {
409 .name = "locking",
410 .type = QEMU_OPT_STRING,
411 .help = "file locking mode (on/off/auto, default: auto)",
412 },
7c9e5276
PB
413 {
414 .name = "pr-manager",
415 .type = QEMU_OPT_STRING,
416 .help = "id of persistent reservation manager object (default: none)",
417 },
c66a6157
KW
418 { /* end of list */ }
419 },
420};
421
422static int raw_open_common(BlockDriverState *bs, QDict *options,
e428e439 423 int bdrv_flags, int open_flags, Error **errp)
83f64091
FB
424{
425 BDRVRawState *s = bs->opaque;
c66a6157
KW
426 QemuOpts *opts;
427 Error *local_err = NULL;
8bfea15d 428 const char *filename = NULL;
7c9e5276 429 const char *str;
0a4279d9 430 BlockdevAioOptions aio, aio_default;
0e1d8f4c 431 int fd, ret;
260a82e5 432 struct stat st;
244a5668 433 OnOffAuto locking;
83f64091 434
87ea75d5 435 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
c66a6157 436 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 437 if (local_err) {
e428e439 438 error_propagate(errp, local_err);
c66a6157
KW
439 ret = -EINVAL;
440 goto fail;
441 }
442
443 filename = qemu_opt_get(opts, "filename");
444
1de1ae0a
CE
445 ret = raw_normalize_devicepath(&filename);
446 if (ret != 0) {
e428e439 447 error_setg_errno(errp, -ret, "Could not normalize device path");
c66a6157 448 goto fail;
1de1ae0a
CE
449 }
450
0a4279d9
KW
451 aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
452 ? BLOCKDEV_AIO_OPTIONS_NATIVE
453 : BLOCKDEV_AIO_OPTIONS_THREADS;
f7abe0ec
MAL
454 aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
455 qemu_opt_get(opts, "aio"),
06c60b6c 456 aio_default, &local_err);
0a4279d9
KW
457 if (local_err) {
458 error_propagate(errp, local_err);
459 ret = -EINVAL;
460 goto fail;
461 }
462 s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
463
f7abe0ec
MAL
464 locking = qapi_enum_parse(&OnOffAuto_lookup,
465 qemu_opt_get(opts, "locking"),
06c60b6c 466 ON_OFF_AUTO_AUTO, &local_err);
244a5668
FZ
467 if (local_err) {
468 error_propagate(errp, local_err);
469 ret = -EINVAL;
470 goto fail;
471 }
472 switch (locking) {
473 case ON_OFF_AUTO_ON:
474 s->use_lock = true;
2b218f5d
FZ
475 if (!qemu_has_ofd_lock()) {
476 fprintf(stderr,
477 "File lock requested but OFD locking syscall is "
478 "unavailable, falling back to POSIX file locks.\n"
479 "Due to the implementation, locks can be lost "
480 "unexpectedly.\n");
481 }
244a5668
FZ
482 break;
483 case ON_OFF_AUTO_OFF:
484 s->use_lock = false;
485 break;
486 case ON_OFF_AUTO_AUTO:
2b218f5d 487 s->use_lock = qemu_has_ofd_lock();
244a5668
FZ
488 break;
489 default:
490 abort();
491 }
492
7c9e5276
PB
493 str = qemu_opt_get(opts, "pr-manager");
494 if (str) {
495 s->pr_mgr = pr_manager_lookup(str, &local_err);
496 if (local_err) {
497 error_propagate(errp, local_err);
498 ret = -EINVAL;
499 goto fail;
500 }
501 }
502
6a8dc042
JC
503 s->open_flags = open_flags;
504 raw_parse_flags(bdrv_flags, &s->open_flags);
83f64091 505
90babde0 506 s->fd = -1;
40ff6d7e 507 fd = qemu_open(filename, s->open_flags, 0644);
19cb3738
FB
508 if (fd < 0) {
509 ret = -errno;
09237757 510 error_setg_errno(errp, errno, "Could not open '%s'", filename);
c66a6157 511 if (ret == -EROFS) {
19cb3738 512 ret = -EACCES;
c66a6157
KW
513 }
514 goto fail;
19cb3738 515 }
83f64091 516 s->fd = fd;
9ef91a67 517
244a5668
FZ
518 s->lock_fd = -1;
519 if (s->use_lock) {
520 fd = qemu_open(filename, s->open_flags);
521 if (fd < 0) {
522 ret = -errno;
523 error_setg_errno(errp, errno, "Could not open '%s' for locking",
524 filename);
525 qemu_close(s->fd);
526 goto fail;
527 }
528 s->lock_fd = fd;
529 }
530 s->perm = 0;
531 s->shared_perm = BLK_PERM_ALL;
532
5c6c3a6c 533#ifdef CONFIG_LINUX_AIO
0a4279d9
KW
534 /* Currently Linux does AIO only for files opened with O_DIRECT */
535 if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {
d657c0c2
KW
536 error_setg(errp, "aio=native was specified, but it requires "
537 "cache.direct=on, which was not specified.");
538 ret = -EINVAL;
539 goto fail;
96518254 540 }
1501ecc1 541#else
0a4279d9 542 if (s->use_linux_aio) {
d657c0c2
KW
543 error_setg(errp, "aio=native was specified, but is not supported "
544 "in this build.");
545 ret = -EINVAL;
546 goto fail;
1501ecc1
SH
547 }
548#endif /* !defined(CONFIG_LINUX_AIO) */
9ef91a67 549
7ce21016 550 s->has_discard = true;
97a2ae34 551 s->has_write_zeroes = true;
3cad8307
RPM
552 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
553 s->needs_alignment = true;
554 }
260a82e5
PB
555
556 if (fstat(s->fd, &st) < 0) {
01212d4e 557 ret = -errno;
260a82e5
PB
558 error_setg_errno(errp, errno, "Could not stat file");
559 goto fail;
560 }
561 if (S_ISREG(st.st_mode)) {
562 s->discard_zeroes = true;
d50d8222 563 s->has_fallocate = true;
260a82e5 564 }
d0b4503e
PB
565 if (S_ISBLK(st.st_mode)) {
566#ifdef BLKDISCARDZEROES
567 unsigned int arg;
568 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
569 s->discard_zeroes = true;
570 }
571#endif
572#ifdef __linux__
573 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
574 * not rely on the contents of discarded blocks unless using O_DIRECT.
97a2ae34 575 * Same for BLKZEROOUT.
d0b4503e
PB
576 */
577 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
578 s->discard_zeroes = false;
97a2ae34 579 s->has_write_zeroes = false;
d0b4503e
PB
580 }
581#endif
582 }
3cad8307
RPM
583#ifdef __FreeBSD__
584 if (S_ISCHR(st.st_mode)) {
585 /*
586 * The file is a char device (disk), which on FreeBSD isn't behind
587 * a pager, so force all requests to be aligned. This is needed
588 * so QEMU makes sure all IO operations on the device are aligned
589 * to sector size, or else FreeBSD will reject them with EINVAL.
590 */
591 s->needs_alignment = true;
592 }
593#endif
260a82e5 594
dce512de
CH
595#ifdef CONFIG_XFS
596 if (platform_test_xfs_fd(s->fd)) {
7ce21016 597 s->is_xfs = true;
dce512de
CH
598 }
599#endif
600
e24d813b 601 bs->supported_zero_flags = s->discard_zeroes ? BDRV_REQ_MAY_UNMAP : 0;
c66a6157
KW
602 ret = 0;
603fail:
8bfea15d
KW
604 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
605 unlink(filename);
606 }
c66a6157
KW
607 qemu_opts_del(opts);
608 return ret;
83f64091
FB
609}
610
015a1036
HR
611static int raw_open(BlockDriverState *bs, QDict *options, int flags,
612 Error **errp)
90babde0
CH
613{
614 BDRVRawState *s = bs->opaque;
615
616 s->type = FTYPE_FILE;
9be38598 617 return raw_open_common(bs, options, flags, 0, errp);
90babde0
CH
618}
619
244a5668
FZ
620typedef enum {
621 RAW_PL_PREPARE,
622 RAW_PL_COMMIT,
623 RAW_PL_ABORT,
624} RawPermLockOp;
625
626#define PERM_FOREACH(i) \
627 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
628
629/* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
630 * file; if @unlock == true, also unlock the unneeded bytes.
631 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
632 */
633static int raw_apply_lock_bytes(BDRVRawState *s,
634 uint64_t perm_lock_bits,
635 uint64_t shared_perm_lock_bits,
636 bool unlock, Error **errp)
637{
638 int ret;
639 int i;
640
641 PERM_FOREACH(i) {
642 int off = RAW_LOCK_PERM_BASE + i;
643 if (perm_lock_bits & (1ULL << i)) {
644 ret = qemu_lock_fd(s->lock_fd, off, 1, false);
645 if (ret) {
646 error_setg(errp, "Failed to lock byte %d", off);
647 return ret;
648 }
649 } else if (unlock) {
650 ret = qemu_unlock_fd(s->lock_fd, off, 1);
651 if (ret) {
652 error_setg(errp, "Failed to unlock byte %d", off);
653 return ret;
654 }
655 }
656 }
657 PERM_FOREACH(i) {
658 int off = RAW_LOCK_SHARED_BASE + i;
659 if (shared_perm_lock_bits & (1ULL << i)) {
660 ret = qemu_lock_fd(s->lock_fd, off, 1, false);
661 if (ret) {
662 error_setg(errp, "Failed to lock byte %d", off);
663 return ret;
664 }
665 } else if (unlock) {
666 ret = qemu_unlock_fd(s->lock_fd, off, 1);
667 if (ret) {
668 error_setg(errp, "Failed to unlock byte %d", off);
669 return ret;
670 }
671 }
672 }
673 return 0;
674}
675
676/* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
677static int raw_check_lock_bytes(BDRVRawState *s,
678 uint64_t perm, uint64_t shared_perm,
679 Error **errp)
680{
681 int ret;
682 int i;
683
684 PERM_FOREACH(i) {
685 int off = RAW_LOCK_SHARED_BASE + i;
686 uint64_t p = 1ULL << i;
687 if (perm & p) {
688 ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
689 if (ret) {
690 char *perm_name = bdrv_perm_names(p);
691 error_setg(errp,
692 "Failed to get \"%s\" lock",
693 perm_name);
694 g_free(perm_name);
695 error_append_hint(errp,
696 "Is another process using the image?\n");
697 return ret;
698 }
699 }
700 }
701 PERM_FOREACH(i) {
702 int off = RAW_LOCK_PERM_BASE + i;
703 uint64_t p = 1ULL << i;
704 if (!(shared_perm & p)) {
705 ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
706 if (ret) {
707 char *perm_name = bdrv_perm_names(p);
708 error_setg(errp,
709 "Failed to get shared \"%s\" lock",
710 perm_name);
711 g_free(perm_name);
712 error_append_hint(errp,
713 "Is another process using the image?\n");
714 return ret;
715 }
716 }
717 }
718 return 0;
719}
720
721static int raw_handle_perm_lock(BlockDriverState *bs,
722 RawPermLockOp op,
723 uint64_t new_perm, uint64_t new_shared,
724 Error **errp)
725{
726 BDRVRawState *s = bs->opaque;
727 int ret = 0;
728 Error *local_err = NULL;
729
730 if (!s->use_lock) {
731 return 0;
732 }
733
734 if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
735 return 0;
736 }
737
738 assert(s->lock_fd > 0);
739
740 switch (op) {
741 case RAW_PL_PREPARE:
742 ret = raw_apply_lock_bytes(s, s->perm | new_perm,
743 ~s->shared_perm | ~new_shared,
744 false, errp);
745 if (!ret) {
746 ret = raw_check_lock_bytes(s, new_perm, new_shared, errp);
747 if (!ret) {
748 return 0;
749 }
750 }
751 op = RAW_PL_ABORT;
752 /* fall through to unlock bytes. */
753 case RAW_PL_ABORT:
754 raw_apply_lock_bytes(s, s->perm, ~s->shared_perm, true, &local_err);
755 if (local_err) {
756 /* Theoretically the above call only unlocks bytes and it cannot
757 * fail. Something weird happened, report it.
758 */
759 error_report_err(local_err);
760 }
761 break;
762 case RAW_PL_COMMIT:
763 raw_apply_lock_bytes(s, new_perm, ~new_shared, true, &local_err);
764 if (local_err) {
765 /* Theoretically the above call only unlocks bytes and it cannot
766 * fail. Something weird happened, report it.
767 */
768 error_report_err(local_err);
769 }
770 break;
771 }
772 return ret;
773}
774
eeb6b45d
JC
775static int raw_reopen_prepare(BDRVReopenState *state,
776 BlockReopenQueue *queue, Error **errp)
777{
778 BDRVRawState *s;
4e6d13c9 779 BDRVRawReopenState *rs;
eeb6b45d 780 int ret = 0;
df26a350 781 Error *local_err = NULL;
eeb6b45d
JC
782
783 assert(state != NULL);
784 assert(state->bs != NULL);
785
786 s = state->bs->opaque;
787
5839e53b 788 state->opaque = g_new0(BDRVRawReopenState, 1);
4e6d13c9 789 rs = state->opaque;
eeb6b45d 790
f709623b 791 if (s->type == FTYPE_CD) {
4e6d13c9 792 rs->open_flags |= O_NONBLOCK;
1bc6b705
JC
793 }
794
4e6d13c9 795 raw_parse_flags(state->flags, &rs->open_flags);
eeb6b45d 796
4e6d13c9 797 rs->fd = -1;
eeb6b45d 798
fdf263f6 799 int fcntl_flags = O_APPEND | O_NONBLOCK;
eeb6b45d
JC
800#ifdef O_NOATIME
801 fcntl_flags |= O_NOATIME;
802#endif
803
fdf263f6
AF
804#ifdef O_ASYNC
805 /* Not all operating systems have O_ASYNC, and those that don't
4e6d13c9 806 * will not let us track the state into rs->open_flags (typically
fdf263f6
AF
807 * you achieve the same effect with an ioctl, for example I_SETSIG
808 * on Solaris). But we do not use O_ASYNC, so that's fine.
809 */
810 assert((s->open_flags & O_ASYNC) == 0);
811#endif
812
4e6d13c9 813 if ((rs->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
eeb6b45d 814 /* dup the original fd */
4e6d13c9
FZ
815 rs->fd = qemu_dup(s->fd);
816 if (rs->fd >= 0) {
817 ret = fcntl_setfl(rs->fd, rs->open_flags);
eeb6b45d 818 if (ret) {
4e6d13c9
FZ
819 qemu_close(rs->fd);
820 rs->fd = -1;
eeb6b45d
JC
821 }
822 }
823 }
824
825 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
4e6d13c9 826 if (rs->fd == -1) {
bdd03cdf
HR
827 const char *normalized_filename = state->bs->filename;
828 ret = raw_normalize_devicepath(&normalized_filename);
829 if (ret < 0) {
830 error_setg_errno(errp, -ret, "Could not normalize device path");
831 } else {
4e6d13c9
FZ
832 assert(!(rs->open_flags & O_CREAT));
833 rs->fd = qemu_open(normalized_filename, rs->open_flags);
834 if (rs->fd == -1) {
bdd03cdf
HR
835 error_setg_errno(errp, errno, "Could not reopen file");
836 ret = -1;
837 }
eeb6b45d
JC
838 }
839 }
df26a350
KW
840
841 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
842 * alignment with the new fd. */
4e6d13c9
FZ
843 if (rs->fd != -1) {
844 raw_probe_alignment(state->bs, rs->fd, &local_err);
df26a350 845 if (local_err) {
4e6d13c9
FZ
846 qemu_close(rs->fd);
847 rs->fd = -1;
df26a350
KW
848 error_propagate(errp, local_err);
849 ret = -EINVAL;
850 }
851 }
852
eeb6b45d
JC
853 return ret;
854}
855
eeb6b45d
JC
856static void raw_reopen_commit(BDRVReopenState *state)
857{
4e6d13c9 858 BDRVRawReopenState *rs = state->opaque;
eeb6b45d
JC
859 BDRVRawState *s = state->bs->opaque;
860
4e6d13c9 861 s->open_flags = rs->open_flags;
eeb6b45d
JC
862
863 qemu_close(s->fd);
4e6d13c9 864 s->fd = rs->fd;
eeb6b45d
JC
865
866 g_free(state->opaque);
867 state->opaque = NULL;
868}
869
870
871static void raw_reopen_abort(BDRVReopenState *state)
872{
4e6d13c9 873 BDRVRawReopenState *rs = state->opaque;
eeb6b45d
JC
874
875 /* nothing to do if NULL, we didn't get far enough */
4e6d13c9 876 if (rs == NULL) {
eeb6b45d
JC
877 return;
878 }
879
4e6d13c9
FZ
880 if (rs->fd >= 0) {
881 qemu_close(rs->fd);
882 rs->fd = -1;
eeb6b45d
JC
883 }
884 g_free(state->opaque);
885 state->opaque = NULL;
886}
887
48265250 888static int hdev_get_max_transfer_length(BlockDriverState *bs, int fd)
6f607174
FZ
889{
890#ifdef BLKSECTGET
48265250
EF
891 int max_bytes = 0;
892 short max_sectors = 0;
893 if (bs->sg && ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
894 return max_bytes;
895 } else if (!bs->sg && ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
896 return max_sectors << BDRV_SECTOR_BITS;
6f607174
FZ
897 } else {
898 return -errno;
899 }
900#else
901 return -ENOSYS;
902#endif
903}
904
9103f1ce
FZ
905static int hdev_get_max_segments(const struct stat *st)
906{
907#ifdef CONFIG_LINUX
908 char buf[32];
909 const char *end;
910 char *sysfspath;
911 int ret;
912 int fd = -1;
913 long max_segments;
914
915 sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
916 major(st->st_rdev), minor(st->st_rdev));
917 fd = open(sysfspath, O_RDONLY);
918 if (fd == -1) {
919 ret = -errno;
920 goto out;
921 }
922 do {
69583490 923 ret = read(fd, buf, sizeof(buf) - 1);
9103f1ce
FZ
924 } while (ret == -1 && errno == EINTR);
925 if (ret < 0) {
926 ret = -errno;
927 goto out;
928 } else if (ret == 0) {
929 ret = -EIO;
930 goto out;
931 }
932 buf[ret] = 0;
933 /* The file is ended with '\n', pass 'end' to accept that. */
934 ret = qemu_strtol(buf, &end, 10, &max_segments);
935 if (ret == 0 && end && *end == '\n') {
936 ret = max_segments;
937 }
938
939out:
fed414df
FZ
940 if (fd != -1) {
941 close(fd);
942 }
9103f1ce
FZ
943 g_free(sysfspath);
944 return ret;
945#else
946 return -ENOTSUP;
947#endif
948}
949
3baca891 950static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
c25f53b0
PB
951{
952 BDRVRawState *s = bs->opaque;
6f607174
FZ
953 struct stat st;
954
955 if (!fstat(s->fd, &st)) {
c4c41a0a 956 if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
48265250
EF
957 int ret = hdev_get_max_transfer_length(bs, s->fd);
958 if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
959 bs->bl.max_transfer = pow2floor(ret);
6f607174 960 }
9103f1ce
FZ
961 ret = hdev_get_max_segments(&st);
962 if (ret > 0) {
963 bs->bl.max_transfer = MIN(bs->bl.max_transfer,
964 ret * getpagesize());
965 }
6f607174
FZ
966 }
967 }
eeb6b45d 968
df26a350 969 raw_probe_alignment(bs, s->fd, errp);
4196d2f0 970 bs->bl.min_mem_alignment = s->buf_align;
459b4e66 971 bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
c25f53b0 972}
83f64091 973
1a9335e4
ET
974static int check_for_dasd(int fd)
975{
976#ifdef BIODASDINFO2
977 struct dasd_information2_t info = {0};
978
979 return ioctl(fd, BIODASDINFO2, &info);
980#else
981 return -1;
982#endif
983}
984
985/**
986 * Try to get @bs's logical and physical block size.
987 * On success, store them in @bsz and return zero.
988 * On failure, return negative errno.
989 */
990static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
991{
992 BDRVRawState *s = bs->opaque;
993 int ret;
994
995 /* If DASD, get blocksizes */
996 if (check_for_dasd(s->fd) < 0) {
997 return -ENOTSUP;
998 }
999 ret = probe_logical_blocksize(s->fd, &bsz->log);
1000 if (ret < 0) {
1001 return ret;
1002 }
1003 return probe_physical_blocksize(s->fd, &bsz->phys);
1004}
1005
1006/**
1007 * Try to get @bs's geometry: cyls, heads, sectors.
1008 * On success, store them in @geo and return 0.
1009 * On failure return -errno.
1010 * (Allows block driver to assign default geometry values that guest sees)
1011 */
1012#ifdef __linux__
1013static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1014{
1015 BDRVRawState *s = bs->opaque;
1016 struct hd_geometry ioctl_geo = {0};
1a9335e4
ET
1017
1018 /* If DASD, get its geometry */
1019 if (check_for_dasd(s->fd) < 0) {
1020 return -ENOTSUP;
1021 }
1022 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1023 return -errno;
1024 }
1025 /* HDIO_GETGEO may return success even though geo contains zeros
1026 (e.g. certain multipath setups) */
1027 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1028 return -ENOTSUP;
1029 }
1030 /* Do not return a geometry for partition */
1031 if (ioctl_geo.start != 0) {
1032 return -ENOTSUP;
1033 }
1034 geo->heads = ioctl_geo.heads;
1035 geo->sectors = ioctl_geo.sectors;
1a9335e4
ET
1036 geo->cylinders = ioctl_geo.cylinders;
1037
1038 return 0;
1039}
1040#else /* __linux__ */
1041static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1042{
1043 return -ENOTSUP;
1044}
1045#endif
1046
de81a169
PB
1047static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
1048{
1049 int ret;
1050
1051 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
1052 if (ret == -1) {
1053 return -errno;
1054 }
1055
b608c8dc 1056 return 0;
de81a169
PB
1057}
1058
1059static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
1060{
e5bcf967 1061 BDRVRawState *s = aiocb->bs->opaque;
de81a169
PB
1062 int ret;
1063
e5bcf967
KW
1064 if (s->page_cache_inconsistent) {
1065 return -EIO;
1066 }
1067
de81a169
PB
1068 ret = qemu_fdatasync(aiocb->aio_fildes);
1069 if (ret == -1) {
e5bcf967
KW
1070 /* There is no clear definition of the semantics of a failing fsync(),
1071 * so we may have to assume the worst. The sad truth is that this
1072 * assumption is correct for Linux. Some pages are now probably marked
1073 * clean in the page cache even though they are inconsistent with the
1074 * on-disk contents. The next fdatasync() call would succeed, but no
1075 * further writeback attempt will be made. We can't get back to a state
1076 * in which we know what is on disk (we would have to rewrite
1077 * everything that was touched since the last fdatasync() at least), so
1078 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1079 * really defined, I have little hope that other OSes are doing better.
1080 *
1081 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1082 * cache. */
1083 if ((s->open_flags & O_DIRECT) == 0) {
1084 s->page_cache_inconsistent = true;
1085 }
de81a169
PB
1086 return -errno;
1087 }
1088 return 0;
1089}
1090
1091#ifdef CONFIG_PREADV
1092
1093static bool preadv_present = true;
1094
1095static ssize_t
1096qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1097{
1098 return preadv(fd, iov, nr_iov, offset);
1099}
1100
1101static ssize_t
1102qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1103{
1104 return pwritev(fd, iov, nr_iov, offset);
1105}
1106
1107#else
1108
1109static bool preadv_present = false;
1110
1111static ssize_t
1112qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1113{
1114 return -ENOSYS;
1115}
1116
1117static ssize_t
1118qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1119{
1120 return -ENOSYS;
1121}
1122
1123#endif
1124
1125static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1126{
1127 ssize_t len;
1128
1129 do {
1130 if (aiocb->aio_type & QEMU_AIO_WRITE)
1131 len = qemu_pwritev(aiocb->aio_fildes,
1132 aiocb->aio_iov,
1133 aiocb->aio_niov,
1134 aiocb->aio_offset);
1135 else
1136 len = qemu_preadv(aiocb->aio_fildes,
1137 aiocb->aio_iov,
1138 aiocb->aio_niov,
1139 aiocb->aio_offset);
1140 } while (len == -1 && errno == EINTR);
1141
1142 if (len == -1) {
1143 return -errno;
1144 }
1145 return len;
1146}
1147
1148/*
1149 * Read/writes the data to/from a given linear buffer.
1150 *
1151 * Returns the number of bytes handles or -errno in case of an error. Short
1152 * reads are only returned if the end of the file is reached.
1153 */
1154static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1155{
1156 ssize_t offset = 0;
1157 ssize_t len;
1158
1159 while (offset < aiocb->aio_nbytes) {
1160 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1161 len = pwrite(aiocb->aio_fildes,
1162 (const char *)buf + offset,
1163 aiocb->aio_nbytes - offset,
1164 aiocb->aio_offset + offset);
1165 } else {
1166 len = pread(aiocb->aio_fildes,
1167 buf + offset,
1168 aiocb->aio_nbytes - offset,
1169 aiocb->aio_offset + offset);
1170 }
1171 if (len == -1 && errno == EINTR) {
1172 continue;
61ed73cf
SH
1173 } else if (len == -1 && errno == EINVAL &&
1174 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1175 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1176 offset > 0) {
1177 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1178 * after a short read. Assume that O_DIRECT short reads only occur
1179 * at EOF. Therefore this is a short read, not an I/O error.
1180 */
1181 break;
de81a169
PB
1182 } else if (len == -1) {
1183 offset = -errno;
1184 break;
1185 } else if (len == 0) {
1186 break;
1187 }
1188 offset += len;
1189 }
1190
1191 return offset;
1192}
1193
1194static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
1195{
1196 ssize_t nbytes;
1197 char *buf;
1198
1199 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1200 /*
1201 * If there is just a single buffer, and it is properly aligned
1202 * we can just use plain pread/pwrite without any problems.
1203 */
1204 if (aiocb->aio_niov == 1) {
1205 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
1206 }
1207 /*
1208 * We have more than one iovec, and all are properly aligned.
1209 *
1210 * Try preadv/pwritev first and fall back to linearizing the
1211 * buffer if it's not supported.
1212 */
1213 if (preadv_present) {
1214 nbytes = handle_aiocb_rw_vector(aiocb);
1215 if (nbytes == aiocb->aio_nbytes ||
1216 (nbytes < 0 && nbytes != -ENOSYS)) {
1217 return nbytes;
1218 }
1219 preadv_present = false;
1220 }
1221
1222 /*
1223 * XXX(hch): short read/write. no easy way to handle the reminder
1224 * using these interfaces. For now retry using plain
1225 * pread/pwrite?
1226 */
1227 }
1228
1229 /*
1230 * Ok, we have to do it the hard way, copy all segments into
1231 * a single aligned buffer.
1232 */
50d4a858
KW
1233 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1234 if (buf == NULL) {
1235 return -ENOMEM;
1236 }
1237
de81a169
PB
1238 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1239 char *p = buf;
1240 int i;
1241
1242 for (i = 0; i < aiocb->aio_niov; ++i) {
1243 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1244 p += aiocb->aio_iov[i].iov_len;
1245 }
8eb029c2 1246 assert(p - buf == aiocb->aio_nbytes);
de81a169
PB
1247 }
1248
1249 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1250 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1251 char *p = buf;
1252 size_t count = aiocb->aio_nbytes, copy;
1253 int i;
1254
1255 for (i = 0; i < aiocb->aio_niov && count; ++i) {
1256 copy = count;
1257 if (copy > aiocb->aio_iov[i].iov_len) {
1258 copy = aiocb->aio_iov[i].iov_len;
1259 }
1260 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
8eb029c2 1261 assert(count >= copy);
de81a169
PB
1262 p += copy;
1263 count -= copy;
1264 }
8eb029c2 1265 assert(count == 0);
de81a169
PB
1266 }
1267 qemu_vfree(buf);
1268
1269 return nbytes;
1270}
1271
8238010b 1272#ifdef CONFIG_XFS
97a2ae34
PB
1273static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1274{
1275 struct xfs_flock64 fl;
bcb22555 1276 int err;
97a2ae34
PB
1277
1278 memset(&fl, 0, sizeof(fl));
1279 fl.l_whence = SEEK_SET;
1280 fl.l_start = offset;
1281 fl.l_len = bytes;
1282
1283 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
bcb22555
DA
1284 err = errno;
1285 DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1286 return -err;
97a2ae34
PB
1287 }
1288
1289 return 0;
1290}
1291
8238010b
PB
1292static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1293{
1294 struct xfs_flock64 fl;
bcb22555 1295 int err;
8238010b
PB
1296
1297 memset(&fl, 0, sizeof(fl));
1298 fl.l_whence = SEEK_SET;
1299 fl.l_start = offset;
1300 fl.l_len = bytes;
1301
1302 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
bcb22555
DA
1303 err = errno;
1304 DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1305 return -err;
8238010b
PB
1306 }
1307
1308 return 0;
1309}
1310#endif
1311
1486df0e
DL
1312static int translate_err(int err)
1313{
1314 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1315 err == -ENOTTY) {
1316 err = -ENOTSUP;
1317 }
1318 return err;
1319}
1320
d50d8222 1321#ifdef CONFIG_FALLOCATE
0b991712
DL
1322static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1323{
1324 do {
1325 if (fallocate(fd, mode, offset, len) == 0) {
1326 return 0;
1327 }
1328 } while (errno == EINTR);
1329 return translate_err(-errno);
1330}
1331#endif
1332
37cc9f7f 1333static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
97a2ae34 1334{
37cc9f7f 1335 int ret = -ENOTSUP;
97a2ae34
PB
1336 BDRVRawState *s = aiocb->bs->opaque;
1337
37cc9f7f 1338 if (!s->has_write_zeroes) {
97a2ae34
PB
1339 return -ENOTSUP;
1340 }
1341
97a2ae34 1342#ifdef BLKZEROOUT
37cc9f7f
DL
1343 do {
1344 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1345 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1346 return 0;
97a2ae34 1347 }
37cc9f7f
DL
1348 } while (errno == EINTR);
1349
1350 ret = translate_err(-errno);
97a2ae34 1351#endif
97a2ae34 1352
1486df0e 1353 if (ret == -ENOTSUP) {
97a2ae34 1354 s->has_write_zeroes = false;
97a2ae34
PB
1355 }
1356 return ret;
1357}
1358
37cc9f7f
DL
1359static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1360{
a6dcf097 1361#if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
37cc9f7f 1362 BDRVRawState *s = aiocb->bs->opaque;
a6dcf097 1363#endif
70d9110b
DL
1364#ifdef CONFIG_FALLOCATE
1365 int64_t len;
1366#endif
37cc9f7f
DL
1367
1368 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1369 return handle_aiocb_write_zeroes_block(aiocb);
1370 }
1371
1372#ifdef CONFIG_XFS
1373 if (s->is_xfs) {
1374 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1375 }
1376#endif
1377
b953f075
DL
1378#ifdef CONFIG_FALLOCATE_ZERO_RANGE
1379 if (s->has_write_zeroes) {
1380 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1381 aiocb->aio_offset, aiocb->aio_nbytes);
1382 if (ret == 0 || ret != -ENOTSUP) {
1383 return ret;
1384 }
1385 s->has_write_zeroes = false;
1386 }
1387#endif
1388
1cdc3239
DL
1389#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1390 if (s->has_discard && s->has_fallocate) {
1391 int ret = do_fallocate(s->fd,
1392 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1393 aiocb->aio_offset, aiocb->aio_nbytes);
1394 if (ret == 0) {
1395 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1396 if (ret == 0 || ret != -ENOTSUP) {
1397 return ret;
1398 }
1399 s->has_fallocate = false;
1400 } else if (ret != -ENOTSUP) {
1401 return ret;
1402 } else {
1403 s->has_discard = false;
1404 }
1405 }
1406#endif
1407
d50d8222 1408#ifdef CONFIG_FALLOCATE
70d9110b
DL
1409 /* Last resort: we are trying to extend the file with zeroed data. This
1410 * can be done via fallocate(fd, 0) */
1411 len = bdrv_getlength(aiocb->bs);
1412 if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
d50d8222
DL
1413 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1414 if (ret == 0 || ret != -ENOTSUP) {
1415 return ret;
1416 }
1417 s->has_fallocate = false;
1418 }
1419#endif
1420
37cc9f7f
DL
1421 return -ENOTSUP;
1422}
1423
8238010b
PB
1424static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1425{
1426 int ret = -EOPNOTSUPP;
1427 BDRVRawState *s = aiocb->bs->opaque;
1428
7ce21016
PB
1429 if (!s->has_discard) {
1430 return -ENOTSUP;
8238010b
PB
1431 }
1432
1433 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1434#ifdef BLKDISCARD
1435 do {
1436 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1437 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1438 return 0;
1439 }
1440 } while (errno == EINTR);
1441
1442 ret = -errno;
1443#endif
1444 } else {
1445#ifdef CONFIG_XFS
1446 if (s->is_xfs) {
1447 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1448 }
1449#endif
1450
1451#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
0b991712
DL
1452 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1453 aiocb->aio_offset, aiocb->aio_nbytes);
8238010b
PB
1454#endif
1455 }
1456
1486df0e
DL
1457 ret = translate_err(ret);
1458 if (ret == -ENOTSUP) {
7ce21016 1459 s->has_discard = false;
8238010b
PB
1460 }
1461 return ret;
1462}
1463
de81a169
PB
1464static int aio_worker(void *arg)
1465{
1466 RawPosixAIOData *aiocb = arg;
1467 ssize_t ret = 0;
1468
1469 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1470 case QEMU_AIO_READ:
1471 ret = handle_aiocb_rw(aiocb);
c0191e76 1472 if (ret >= 0 && ret < aiocb->aio_nbytes) {
de81a169
PB
1473 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1474 0, aiocb->aio_nbytes - ret);
1475
1476 ret = aiocb->aio_nbytes;
1477 }
1478 if (ret == aiocb->aio_nbytes) {
1479 ret = 0;
1480 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1481 ret = -EINVAL;
1482 }
1483 break;
1484 case QEMU_AIO_WRITE:
1485 ret = handle_aiocb_rw(aiocb);
1486 if (ret == aiocb->aio_nbytes) {
1487 ret = 0;
1488 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1489 ret = -EINVAL;
1490 }
1491 break;
1492 case QEMU_AIO_FLUSH:
1493 ret = handle_aiocb_flush(aiocb);
1494 break;
1495 case QEMU_AIO_IOCTL:
1496 ret = handle_aiocb_ioctl(aiocb);
1497 break;
8238010b
PB
1498 case QEMU_AIO_DISCARD:
1499 ret = handle_aiocb_discard(aiocb);
1500 break;
97a2ae34
PB
1501 case QEMU_AIO_WRITE_ZEROES:
1502 ret = handle_aiocb_write_zeroes(aiocb);
1503 break;
de81a169
PB
1504 default:
1505 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1506 ret = -EINVAL;
1507 break;
1508 }
1509
c84b3192 1510 g_free(aiocb);
de81a169
PB
1511 return ret;
1512}
1513
260a82e5 1514static int paio_submit_co(BlockDriverState *bs, int fd,
2ffa76c2 1515 int64_t offset, QEMUIOVector *qiov,
f5a5ca79 1516 int bytes, int type)
260a82e5 1517{
c84b3192 1518 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
260a82e5
PB
1519 ThreadPool *pool;
1520
1521 acb->bs = bs;
1522 acb->aio_type = type;
1523 acb->aio_fildes = fd;
1524
f5a5ca79 1525 acb->aio_nbytes = bytes;
2ffa76c2 1526 acb->aio_offset = offset;
8eb029c2 1527
260a82e5
PB
1528 if (qiov) {
1529 acb->aio_iov = qiov->iov;
1530 acb->aio_niov = qiov->niov;
f5a5ca79 1531 assert(qiov->size == bytes);
260a82e5 1532 }
260a82e5 1533
f5a5ca79 1534 trace_paio_submit_co(offset, bytes, type);
260a82e5
PB
1535 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1536 return thread_pool_submit_co(pool, aio_worker, acb);
1537}
1538
7c84b1b8 1539static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
f5a5ca79 1540 int64_t offset, QEMUIOVector *qiov, int bytes,
097310b5 1541 BlockCompletionFunc *cb, void *opaque, int type)
de81a169 1542{
c84b3192 1543 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
c4d9d196 1544 ThreadPool *pool;
de81a169
PB
1545
1546 acb->bs = bs;
1547 acb->aio_type = type;
1548 acb->aio_fildes = fd;
1549
f5a5ca79 1550 acb->aio_nbytes = bytes;
36e3b2e7 1551 acb->aio_offset = offset;
8eb029c2 1552
de81a169
PB
1553 if (qiov) {
1554 acb->aio_iov = qiov->iov;
1555 acb->aio_niov = qiov->niov;
8eb029c2 1556 assert(qiov->size == acb->aio_nbytes);
de81a169 1557 }
de81a169 1558
f5a5ca79 1559 trace_paio_submit(acb, opaque, offset, bytes, type);
c4d9d196
SH
1560 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1561 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
de81a169
PB
1562}
1563
9d52aa3c
KW
1564static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1565 uint64_t bytes, QEMUIOVector *qiov, int type)
83f64091 1566{
ce1a14dc 1567 BDRVRawState *s = bs->opaque;
ce1a14dc 1568
19cb3738 1569 if (fd_open(bs) < 0)
2174f12b 1570 return -EIO;
19cb3738 1571
f141eafe 1572 /*
3cad8307
RPM
1573 * Check if the underlying device requires requests to be aligned,
1574 * and if the request we are trying to submit is aligned or not.
1575 * If this is the case tell the low-level driver that it needs
1576 * to copy the buffer.
f141eafe 1577 */
3cad8307 1578 if (s->needs_alignment) {
c53b1c51 1579 if (!bdrv_qiov_is_aligned(bs, qiov)) {
5c6c3a6c 1580 type |= QEMU_AIO_MISALIGNED;
e44bd6fc 1581#ifdef CONFIG_LINUX_AIO
0a4279d9 1582 } else if (s->use_linux_aio) {
0187f5c9 1583 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
9d52aa3c 1584 assert(qiov->size == bytes);
0187f5c9 1585 return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
e44bd6fc 1586#endif
5c6c3a6c 1587 }
9ef91a67 1588 }
f141eafe 1589
9d52aa3c 1590 return paio_submit_co(bs, s->fd, offset, qiov, bytes, type);
2174f12b
KW
1591}
1592
9d52aa3c
KW
1593static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1594 uint64_t bytes, QEMUIOVector *qiov,
1595 int flags)
2174f12b 1596{
9d52aa3c 1597 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
2174f12b
KW
1598}
1599
9d52aa3c
KW
1600static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1601 uint64_t bytes, QEMUIOVector *qiov,
1602 int flags)
2174f12b 1603{
9d52aa3c
KW
1604 assert(flags == 0);
1605 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
83f64091
FB
1606}
1607
1b3abdcc
ML
1608static void raw_aio_plug(BlockDriverState *bs)
1609{
1610#ifdef CONFIG_LINUX_AIO
0a4279d9
KW
1611 BDRVRawState *s = bs->opaque;
1612 if (s->use_linux_aio) {
0187f5c9
PB
1613 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1614 laio_io_plug(bs, aio);
1b3abdcc
ML
1615 }
1616#endif
1617}
1618
1619static void raw_aio_unplug(BlockDriverState *bs)
1620{
1621#ifdef CONFIG_LINUX_AIO
0a4279d9
KW
1622 BDRVRawState *s = bs->opaque;
1623 if (s->use_linux_aio) {
0187f5c9
PB
1624 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1625 laio_io_unplug(bs, aio);
1b3abdcc
ML
1626 }
1627#endif
1628}
1629
7c84b1b8 1630static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
097310b5 1631 BlockCompletionFunc *cb, void *opaque)
b2e12bc6
CH
1632{
1633 BDRVRawState *s = bs->opaque;
1634
1635 if (fd_open(bs) < 0)
1636 return NULL;
1637
1e5b9d2f 1638 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
b2e12bc6
CH
1639}
1640
83f64091
FB
1641static void raw_close(BlockDriverState *bs)
1642{
1643 BDRVRawState *s = bs->opaque;
c2f3426c 1644
19cb3738 1645 if (s->fd >= 0) {
2e1e79da 1646 qemu_close(s->fd);
19cb3738
FB
1647 s->fd = -1;
1648 }
244a5668
FZ
1649 if (s->lock_fd >= 0) {
1650 qemu_close(s->lock_fd);
1651 s->lock_fd = -1;
1652 }
83f64091
FB
1653}
1654
d0bc9e5d
HR
1655/**
1656 * Truncates the given regular file @fd to @offset and, when growing, fills the
1657 * new space according to @prealloc.
1658 *
1659 * Returns: 0 on success, -errno on failure.
1660 */
9f63b07e
HR
1661static int raw_regular_truncate(int fd, int64_t offset, PreallocMode prealloc,
1662 Error **errp)
1663{
1664 int result = 0;
d0bc9e5d
HR
1665 int64_t current_length = 0;
1666 char *buf = NULL;
1667 struct stat st;
1668
1669 if (fstat(fd, &st) < 0) {
1670 result = -errno;
1671 error_setg_errno(errp, -result, "Could not stat file");
1672 return result;
1673 }
1674
1675 current_length = st.st_size;
1676 if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
1677 error_setg(errp, "Cannot use preallocation for shrinking files");
1678 return -ENOTSUP;
1679 }
9f63b07e
HR
1680
1681 switch (prealloc) {
1682#ifdef CONFIG_POSIX_FALLOCATE
1683 case PREALLOC_MODE_FALLOC:
1684 /*
1685 * Truncating before posix_fallocate() makes it about twice slower on
1686 * file systems that do not support fallocate(), trying to check if a
1687 * block is allocated before allocating it, so don't do that here.
1688 */
d0bc9e5d 1689 result = -posix_fallocate(fd, current_length, offset - current_length);
9f63b07e
HR
1690 if (result != 0) {
1691 /* posix_fallocate() doesn't set errno. */
1692 error_setg_errno(errp, -result,
d0bc9e5d 1693 "Could not preallocate new data");
9f63b07e 1694 }
d0bc9e5d 1695 goto out;
9f63b07e
HR
1696#endif
1697 case PREALLOC_MODE_FULL:
1698 {
d0bc9e5d 1699 int64_t num = 0, left = offset - current_length;
9f63b07e
HR
1700
1701 /*
1702 * Knowing the final size from the beginning could allow the file
1703 * system driver to do less allocations and possibly avoid
1704 * fragmentation of the file.
1705 */
1706 if (ftruncate(fd, offset) != 0) {
1707 result = -errno;
1708 error_setg_errno(errp, -result, "Could not resize file");
d0bc9e5d 1709 goto out;
9f63b07e
HR
1710 }
1711
1712 buf = g_malloc0(65536);
1713
d0bc9e5d
HR
1714 result = lseek(fd, current_length, SEEK_SET);
1715 if (result < 0) {
1716 result = -errno;
1717 error_setg_errno(errp, -result,
1718 "Failed to seek to the old end of file");
1719 goto out;
1720 }
1721
9f63b07e
HR
1722 while (left > 0) {
1723 num = MIN(left, 65536);
1724 result = write(fd, buf, num);
1725 if (result < 0) {
1726 result = -errno;
1727 error_setg_errno(errp, -result,
d0bc9e5d
HR
1728 "Could not write zeros for preallocation");
1729 goto out;
9f63b07e
HR
1730 }
1731 left -= result;
1732 }
1733 if (result >= 0) {
1734 result = fsync(fd);
1735 if (result < 0) {
1736 result = -errno;
1737 error_setg_errno(errp, -result,
d0bc9e5d
HR
1738 "Could not flush file to disk");
1739 goto out;
9f63b07e
HR
1740 }
1741 }
d0bc9e5d 1742 goto out;
9f63b07e
HR
1743 }
1744 case PREALLOC_MODE_OFF:
1745 if (ftruncate(fd, offset) != 0) {
1746 result = -errno;
1747 error_setg_errno(errp, -result, "Could not resize file");
1748 }
1749 return result;
1750 default:
1751 result = -ENOTSUP;
1752 error_setg(errp, "Unsupported preallocation mode: %s",
977c736f 1753 PreallocMode_str(prealloc));
9f63b07e
HR
1754 return result;
1755 }
d0bc9e5d
HR
1756
1757out:
1758 if (result < 0) {
1759 if (ftruncate(fd, current_length) < 0) {
1760 error_report("Failed to restore old file length: %s",
1761 strerror(errno));
1762 }
1763 }
1764
1765 g_free(buf);
1766 return result;
9f63b07e
HR
1767}
1768
8243ccb7
HR
1769static int raw_truncate(BlockDriverState *bs, int64_t offset,
1770 PreallocMode prealloc, Error **errp)
83f64091
FB
1771{
1772 BDRVRawState *s = bs->opaque;
55b949c8 1773 struct stat st;
f59adb32 1774 int ret;
55b949c8
CH
1775
1776 if (fstat(s->fd, &st)) {
f59adb32
HR
1777 ret = -errno;
1778 error_setg_errno(errp, -ret, "Failed to fstat() the file");
1779 return ret;
55b949c8
CH
1780 }
1781
1782 if (S_ISREG(st.st_mode)) {
35d72602
HR
1783 return raw_regular_truncate(s->fd, offset, prealloc, errp);
1784 }
1785
1786 if (prealloc != PREALLOC_MODE_OFF) {
1787 error_setg(errp, "Preallocation mode '%s' unsupported for this "
977c736f 1788 "non-regular file", PreallocMode_str(prealloc));
35d72602
HR
1789 return -ENOTSUP;
1790 }
1791
1792 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
f59adb32
HR
1793 if (offset > raw_getlength(bs)) {
1794 error_setg(errp, "Cannot grow device files");
1795 return -EINVAL;
1796 }
55b949c8 1797 } else {
f59adb32 1798 error_setg(errp, "Resizing this file is not supported");
55b949c8
CH
1799 return -ENOTSUP;
1800 }
1801
83f64091
FB
1802 return 0;
1803}
1804
128ab2ff
BS
1805#ifdef __OpenBSD__
1806static int64_t raw_getlength(BlockDriverState *bs)
1807{
1808 BDRVRawState *s = bs->opaque;
1809 int fd = s->fd;
1810 struct stat st;
1811
1812 if (fstat(fd, &st))
aa729704 1813 return -errno;
128ab2ff
BS
1814 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1815 struct disklabel dl;
1816
1817 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 1818 return -errno;
128ab2ff
BS
1819 return (uint64_t)dl.d_secsize *
1820 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1821 } else
1822 return st.st_size;
1823}
d1f6fd8d
CE
1824#elif defined(__NetBSD__)
1825static int64_t raw_getlength(BlockDriverState *bs)
1826{
1827 BDRVRawState *s = bs->opaque;
1828 int fd = s->fd;
1829 struct stat st;
1830
1831 if (fstat(fd, &st))
aa729704 1832 return -errno;
d1f6fd8d
CE
1833 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1834 struct dkwedge_info dkw;
1835
1836 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1837 return dkw.dkw_size * 512;
1838 } else {
1839 struct disklabel dl;
1840
1841 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 1842 return -errno;
d1f6fd8d
CE
1843 return (uint64_t)dl.d_secsize *
1844 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1845 }
1846 } else
1847 return st.st_size;
1848}
50779cc2
CH
1849#elif defined(__sun__)
1850static int64_t raw_getlength(BlockDriverState *bs)
1851{
1852 BDRVRawState *s = bs->opaque;
1853 struct dk_minfo minfo;
1854 int ret;
aa729704 1855 int64_t size;
50779cc2
CH
1856
1857 ret = fd_open(bs);
1858 if (ret < 0) {
1859 return ret;
1860 }
1861
1862 /*
1863 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1864 */
1865 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1866 if (ret != -1) {
1867 return minfo.dki_lbsize * minfo.dki_capacity;
1868 }
1869
1870 /*
1871 * There are reports that lseek on some devices fails, but
1872 * irc discussion said that contingency on contingency was overkill.
1873 */
aa729704
MA
1874 size = lseek(s->fd, 0, SEEK_END);
1875 if (size < 0) {
1876 return -errno;
1877 }
1878 return size;
50779cc2
CH
1879}
1880#elif defined(CONFIG_BSD)
1881static int64_t raw_getlength(BlockDriverState *bs)
83f64091
FB
1882{
1883 BDRVRawState *s = bs->opaque;
1884 int fd = s->fd;
1885 int64_t size;
83f64091 1886 struct stat sb;
a167ba50 1887#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a 1888 int reopened = 0;
83f64091 1889#endif
19cb3738
FB
1890 int ret;
1891
1892 ret = fd_open(bs);
1893 if (ret < 0)
1894 return ret;
83f64091 1895
a167ba50 1896#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
1897again:
1898#endif
83f64091
FB
1899 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1900#ifdef DIOCGMEDIASIZE
1901 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
c5e97233
BS
1902#elif defined(DIOCGPART)
1903 {
1904 struct partinfo pi;
1905 if (ioctl(fd, DIOCGPART, &pi) == 0)
1906 size = pi.media_size;
1907 else
1908 size = 0;
1909 }
1910 if (size == 0)
83f64091 1911#endif
83affaa6 1912#if defined(__APPLE__) && defined(__MACH__)
728dacbd
JA
1913 {
1914 uint64_t sectors = 0;
1915 uint32_t sector_size = 0;
1916
1917 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1918 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1919 size = sectors * sector_size;
1920 } else {
1921 size = lseek(fd, 0LL, SEEK_END);
1922 if (size < 0) {
1923 return -errno;
1924 }
1925 }
1926 }
83f64091
FB
1927#else
1928 size = lseek(fd, 0LL, SEEK_END);
aa729704
MA
1929 if (size < 0) {
1930 return -errno;
1931 }
9f23011a 1932#endif
a167ba50 1933#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
1934 switch(s->type) {
1935 case FTYPE_CD:
1936 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1937 if (size == 2048LL * (unsigned)-1)
1938 size = 0;
1939 /* XXX no disc? maybe we need to reopen... */
f3a5d3f8 1940 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
9f23011a
BS
1941 reopened = 1;
1942 goto again;
1943 }
1944 }
83f64091 1945#endif
50779cc2 1946 } else {
83f64091 1947 size = lseek(fd, 0, SEEK_END);
aa729704
MA
1948 if (size < 0) {
1949 return -errno;
1950 }
83f64091 1951 }
83f64091
FB
1952 return size;
1953}
50779cc2
CH
1954#else
1955static int64_t raw_getlength(BlockDriverState *bs)
1956{
1957 BDRVRawState *s = bs->opaque;
1958 int ret;
aa729704 1959 int64_t size;
50779cc2
CH
1960
1961 ret = fd_open(bs);
1962 if (ret < 0) {
1963 return ret;
1964 }
1965
aa729704
MA
1966 size = lseek(s->fd, 0, SEEK_END);
1967 if (size < 0) {
1968 return -errno;
1969 }
1970 return size;
50779cc2 1971}
128ab2ff 1972#endif
83f64091 1973
4a1d5e1f
FZ
1974static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1975{
1976 struct stat st;
1977 BDRVRawState *s = bs->opaque;
1978
1979 if (fstat(s->fd, &st) < 0) {
1980 return -errno;
1981 }
1982 return (int64_t)st.st_blocks * 512;
1983}
1984
6f482f74 1985static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
83f64091
FB
1986{
1987 int fd;
1e37d059 1988 int result = 0;
0e7e1989 1989 int64_t total_size = 0;
4ab15590 1990 bool nocow = false;
06247428
HT
1991 PreallocMode prealloc;
1992 char *buf = NULL;
1993 Error *local_err = NULL;
83f64091 1994
464d9f64
HR
1995 strstart(filename, "file:", &filename);
1996
0e7e1989 1997 /* Read out options */
180e9526
HT
1998 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1999 BDRV_SECTOR_SIZE);
4ab15590 2000 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
06247428 2001 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
f7abe0ec 2002 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
06c60b6c 2003 PREALLOC_MODE_OFF, &local_err);
06247428
HT
2004 g_free(buf);
2005 if (local_err) {
2006 error_propagate(errp, local_err);
2007 result = -EINVAL;
2008 goto out;
2009 }
83f64091 2010
73ba05d9 2011 fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
6165f4d8 2012 0644);
1e37d059
SW
2013 if (fd < 0) {
2014 result = -errno;
e428e439 2015 error_setg_errno(errp, -result, "Could not create file");
06247428
HT
2016 goto out;
2017 }
2018
2019 if (nocow) {
4ab15590 2020#ifdef __linux__
06247428
HT
2021 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2022 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2023 * will be ignored since any failure of this operation should not
2024 * block the left work.
2025 */
2026 int attr;
2027 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2028 attr |= FS_NOCOW_FL;
2029 ioctl(fd, FS_IOC_SETFLAGS, &attr);
4ab15590 2030 }
06247428
HT
2031#endif
2032 }
2033
9f63b07e
HR
2034 result = raw_regular_truncate(fd, total_size, prealloc, errp);
2035 if (result < 0) {
2036 goto out_close;
1e37d059 2037 }
06247428 2038
5a1dad9d 2039out_close:
06247428
HT
2040 if (qemu_close(fd) != 0 && result == 0) {
2041 result = -errno;
2042 error_setg_errno(errp, -result, "Could not close the new file");
2043 }
2044out:
1e37d059 2045 return result;
83f64091
FB
2046}
2047
d1f06fe6
MA
2048/*
2049 * Find allocation range in @bs around offset @start.
2050 * May change underlying file descriptor's file offset.
2051 * If @start is not in a hole, store @start in @data, and the
2052 * beginning of the next hole in @hole, and return 0.
2053 * If @start is in a non-trailing hole, store @start in @hole and the
2054 * beginning of the next non-hole in @data, and return 0.
2055 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2056 * If we can't find out, return a negative errno other than -ENXIO.
2057 */
2058static int find_allocation(BlockDriverState *bs, off_t start,
2059 off_t *data, off_t *hole)
4f11aa8a
HR
2060{
2061#if defined SEEK_HOLE && defined SEEK_DATA
94282e71 2062 BDRVRawState *s = bs->opaque;
d1f06fe6 2063 off_t offs;
94282e71 2064
d1f06fe6
MA
2065 /*
2066 * SEEK_DATA cases:
2067 * D1. offs == start: start is in data
2068 * D2. offs > start: start is in a hole, next data at offs
2069 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2070 * or start is beyond EOF
2071 * If the latter happens, the file has been truncated behind
2072 * our back since we opened it. All bets are off then.
2073 * Treating like a trailing hole is simplest.
2074 * D4. offs < 0, errno != ENXIO: we learned nothing
2075 */
2076 offs = lseek(s->fd, start, SEEK_DATA);
2077 if (offs < 0) {
2078 return -errno; /* D3 or D4 */
2079 }
2080 assert(offs >= start);
2081
2082 if (offs > start) {
2083 /* D2: in hole, next data at offs */
2084 *hole = start;
2085 *data = offs;
2086 return 0;
5500316d
PB
2087 }
2088
d1f06fe6
MA
2089 /* D1: in data, end not yet known */
2090
2091 /*
2092 * SEEK_HOLE cases:
2093 * H1. offs == start: start is in a hole
2094 * If this happens here, a hole has been dug behind our back
2095 * since the previous lseek().
2096 * H2. offs > start: either start is in data, next hole at offs,
2097 * or start is in trailing hole, EOF at offs
2098 * Linux treats trailing holes like any other hole: offs ==
2099 * start. Solaris seeks to EOF instead: offs > start (blech).
2100 * If that happens here, a hole has been dug behind our back
2101 * since the previous lseek().
2102 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2103 * If this happens, the file has been truncated behind our
2104 * back since we opened it. Treat it like a trailing hole.
2105 * H4. offs < 0, errno != ENXIO: we learned nothing
2106 * Pretend we know nothing at all, i.e. "forget" about D1.
2107 */
2108 offs = lseek(s->fd, start, SEEK_HOLE);
2109 if (offs < 0) {
2110 return -errno; /* D1 and (H3 or H4) */
2111 }
2112 assert(offs >= start);
2113
2114 if (offs > start) {
2115 /*
2116 * D1 and H2: either in data, next hole at offs, or it was in
2117 * data but is now in a trailing hole. In the latter case,
2118 * all bets are off. Treating it as if it there was data all
2119 * the way to EOF is safe, so simply do that.
2120 */
4f11aa8a 2121 *data = start;
d1f06fe6
MA
2122 *hole = offs;
2123 return 0;
5500316d 2124 }
4f11aa8a 2125
d1f06fe6
MA
2126 /* D1 and H1 */
2127 return -EBUSY;
5500316d 2128#else
4f11aa8a 2129 return -ENOTSUP;
5500316d 2130#endif
4f11aa8a
HR
2131}
2132
2133/*
be2ebc6d 2134 * Returns the allocation status of the specified sectors.
4f11aa8a
HR
2135 *
2136 * If 'sector_num' is beyond the end of the disk image the return value is 0
2137 * and 'pnum' is set to 0.
2138 *
2139 * 'pnum' is set to the number of sectors (including and immediately following
2140 * the specified sector) that are known to be in the same
2141 * allocated/unallocated state.
2142 *
2143 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2144 * beyond the end of the disk image it will be clamped.
2145 */
2146static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
2147 int64_t sector_num,
67a0fd2a
FZ
2148 int nb_sectors, int *pnum,
2149 BlockDriverState **file)
4f11aa8a
HR
2150{
2151 off_t start, data = 0, hole = 0;
e6d7ec32 2152 int64_t total_size;
d7f62751 2153 int ret;
4f11aa8a
HR
2154
2155 ret = fd_open(bs);
2156 if (ret < 0) {
2157 return ret;
2158 }
2159
2160 start = sector_num * BDRV_SECTOR_SIZE;
e6d7ec32
HR
2161 total_size = bdrv_getlength(bs);
2162 if (total_size < 0) {
2163 return total_size;
2164 } else if (start >= total_size) {
2165 *pnum = 0;
2166 return 0;
2167 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
2168 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
2169 }
4f11aa8a 2170
d1f06fe6
MA
2171 ret = find_allocation(bs, start, &data, &hole);
2172 if (ret == -ENXIO) {
2173 /* Trailing hole */
2174 *pnum = nb_sectors;
2175 ret = BDRV_BLOCK_ZERO;
2176 } else if (ret < 0) {
2177 /* No info available, so pretend there are no holes */
2178 *pnum = nb_sectors;
2179 ret = BDRV_BLOCK_DATA;
2180 } else if (data == start) {
f4a769ab
KW
2181 /* On a data extent, compute sectors to the end of the extent,
2182 * possibly including a partial sector at EOF. */
2183 *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
d1f06fe6 2184 ret = BDRV_BLOCK_DATA;
5500316d
PB
2185 } else {
2186 /* On a hole, compute sectors to the beginning of the next extent. */
d1f06fe6 2187 assert(hole == start);
5500316d 2188 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
d1f06fe6 2189 ret = BDRV_BLOCK_ZERO;
5500316d 2190 }
02650acb 2191 *file = bs;
d1f06fe6 2192 return ret | BDRV_BLOCK_OFFSET_VALID | start;
5500316d
PB
2193}
2194
4da444a0 2195static coroutine_fn BlockAIOCB *raw_aio_pdiscard(BlockDriverState *bs,
f5a5ca79 2196 int64_t offset, int bytes,
097310b5 2197 BlockCompletionFunc *cb, void *opaque)
dce512de 2198{
dce512de
CH
2199 BDRVRawState *s = bs->opaque;
2200
f5a5ca79 2201 return paio_submit(bs, s->fd, offset, NULL, bytes,
8238010b 2202 cb, opaque, QEMU_AIO_DISCARD);
dce512de 2203}
0e7e1989 2204
2ffa76c2
EB
2205static int coroutine_fn raw_co_pwrite_zeroes(
2206 BlockDriverState *bs, int64_t offset,
f5a5ca79 2207 int bytes, BdrvRequestFlags flags)
260a82e5
PB
2208{
2209 BDRVRawState *s = bs->opaque;
2210
2211 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
f5a5ca79 2212 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
97a2ae34
PB
2213 QEMU_AIO_WRITE_ZEROES);
2214 } else if (s->discard_zeroes) {
f5a5ca79 2215 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
97a2ae34 2216 QEMU_AIO_DISCARD);
260a82e5 2217 }
97a2ae34 2218 return -ENOTSUP;
260a82e5
PB
2219}
2220
2221static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2222{
2223 BDRVRawState *s = bs->opaque;
2224
2225 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
260a82e5
PB
2226 return 0;
2227}
2228
6f482f74
CL
2229static QemuOptsList raw_create_opts = {
2230 .name = "raw-create-opts",
2231 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2232 .desc = {
2233 {
2234 .name = BLOCK_OPT_SIZE,
2235 .type = QEMU_OPT_SIZE,
2236 .help = "Virtual disk size"
2237 },
4ab15590
CL
2238 {
2239 .name = BLOCK_OPT_NOCOW,
2240 .type = QEMU_OPT_BOOL,
2241 .help = "Turn off copy-on-write (valid only on btrfs)"
2242 },
06247428
HT
2243 {
2244 .name = BLOCK_OPT_PREALLOC,
2245 .type = QEMU_OPT_STRING,
2246 .help = "Preallocation mode (allowed values: off, falloc, full)"
2247 },
6f482f74
CL
2248 { /* end of list */ }
2249 }
0e7e1989
KW
2250};
2251
244a5668
FZ
2252static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2253 Error **errp)
2254{
2255 return raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
2256}
2257
2258static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
2259{
2260 BDRVRawState *s = bs->opaque;
2261 raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
2262 s->perm = perm;
2263 s->shared_perm = shared;
2264}
2265
2266static void raw_abort_perm_update(BlockDriverState *bs)
2267{
2268 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
2269}
2270
5f535a94 2271BlockDriver bdrv_file = {
84a12e66
CH
2272 .format_name = "file",
2273 .protocol_name = "file",
856ae5c3 2274 .instance_size = sizeof(BDRVRawState),
030be321 2275 .bdrv_needs_filename = true,
856ae5c3 2276 .bdrv_probe = NULL, /* no probe for protocols */
078896a9 2277 .bdrv_parse_filename = raw_parse_filename,
66f82cee 2278 .bdrv_file_open = raw_open,
eeb6b45d
JC
2279 .bdrv_reopen_prepare = raw_reopen_prepare,
2280 .bdrv_reopen_commit = raw_reopen_commit,
2281 .bdrv_reopen_abort = raw_reopen_abort,
856ae5c3 2282 .bdrv_close = raw_close,
c282e1fd 2283 .bdrv_create = raw_create,
3ac21627 2284 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 2285 .bdrv_co_get_block_status = raw_co_get_block_status,
2ffa76c2 2286 .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
3b46e624 2287
9d52aa3c
KW
2288 .bdrv_co_preadv = raw_co_preadv,
2289 .bdrv_co_pwritev = raw_co_pwritev,
b2e12bc6 2290 .bdrv_aio_flush = raw_aio_flush,
4da444a0 2291 .bdrv_aio_pdiscard = raw_aio_pdiscard,
c25f53b0 2292 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2293 .bdrv_io_plug = raw_aio_plug,
2294 .bdrv_io_unplug = raw_aio_unplug,
3c529d93 2295
83f64091
FB
2296 .bdrv_truncate = raw_truncate,
2297 .bdrv_getlength = raw_getlength,
260a82e5 2298 .bdrv_get_info = raw_get_info,
4a1d5e1f
FZ
2299 .bdrv_get_allocated_file_size
2300 = raw_get_allocated_file_size,
244a5668
FZ
2301 .bdrv_check_perm = raw_check_perm,
2302 .bdrv_set_perm = raw_set_perm,
2303 .bdrv_abort_perm_update = raw_abort_perm_update,
6f482f74 2304 .create_opts = &raw_create_opts,
83f64091
FB
2305};
2306
19cb3738
FB
2307/***********************************************/
2308/* host device */
2309
83affaa6 2310#if defined(__APPLE__) && defined(__MACH__)
98caa5bc
JA
2311static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2312 CFIndex maxPathSize, int flags);
d0855f12 2313static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
19cb3738 2314{
d0855f12 2315 kern_return_t kernResult = KERN_FAILURE;
19cb3738
FB
2316 mach_port_t masterPort;
2317 CFMutableDictionaryRef classesToMatch;
d0855f12
JA
2318 const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
2319 char *mediaType = NULL;
19cb3738
FB
2320
2321 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
2322 if ( KERN_SUCCESS != kernResult ) {
2323 printf( "IOMasterPort returned %d\n", kernResult );
2324 }
3b46e624 2325
d0855f12
JA
2326 int index;
2327 for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
2328 classesToMatch = IOServiceMatching(matching_array[index]);
2329 if (classesToMatch == NULL) {
2330 error_report("IOServiceMatching returned NULL for %s",
2331 matching_array[index]);
2332 continue;
2333 }
2334 CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
2335 kCFBooleanTrue);
2336 kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
2337 mediaIterator);
2338 if (kernResult != KERN_SUCCESS) {
2339 error_report("Note: IOServiceGetMatchingServices returned %d",
2340 kernResult);
2341 continue;
2342 }
3b46e624 2343
d0855f12
JA
2344 /* If a match was found, leave the loop */
2345 if (*mediaIterator != 0) {
2346 DPRINTF("Matching using %s\n", matching_array[index]);
2347 mediaType = g_strdup(matching_array[index]);
2348 break;
2349 }
2350 }
2351 return mediaType;
19cb3738
FB
2352}
2353
98caa5bc
JA
2354kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2355 CFIndex maxPathSize, int flags)
19cb3738
FB
2356{
2357 io_object_t nextMedia;
2358 kern_return_t kernResult = KERN_FAILURE;
2359 *bsdPath = '\0';
2360 nextMedia = IOIteratorNext( mediaIterator );
2361 if ( nextMedia )
2362 {
2363 CFTypeRef bsdPathAsCFString;
2364 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2365 if ( bsdPathAsCFString ) {
2366 size_t devPathLength;
2367 strcpy( bsdPath, _PATH_DEV );
98caa5bc
JA
2368 if (flags & BDRV_O_NOCACHE) {
2369 strcat(bsdPath, "r");
2370 }
19cb3738
FB
2371 devPathLength = strlen( bsdPath );
2372 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2373 kernResult = KERN_SUCCESS;
2374 }
2375 CFRelease( bsdPathAsCFString );
2376 }
2377 IOObjectRelease( nextMedia );
2378 }
3b46e624 2379
19cb3738
FB
2380 return kernResult;
2381}
2382
d0855f12
JA
2383/* Sets up a real cdrom for use in QEMU */
2384static bool setup_cdrom(char *bsd_path, Error **errp)
2385{
2386 int index, num_of_test_partitions = 2, fd;
2387 char test_partition[MAXPATHLEN];
2388 bool partition_found = false;
2389
2390 /* look for a working partition */
2391 for (index = 0; index < num_of_test_partitions; index++) {
2392 snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
2393 index);
2394 fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
2395 if (fd >= 0) {
2396 partition_found = true;
2397 qemu_close(fd);
2398 break;
2399 }
2400 }
2401
2402 /* if a working partition on the device was not found */
2403 if (partition_found == false) {
2404 error_setg(errp, "Failed to find a working partition on disc");
2405 } else {
2406 DPRINTF("Using %s as optical disc\n", test_partition);
2407 pstrcpy(bsd_path, MAXPATHLEN, test_partition);
2408 }
2409 return partition_found;
2410}
2411
2412/* Prints directions on mounting and unmounting a device */
2413static void print_unmounting_directions(const char *file_name)
2414{
2415 error_report("If device %s is mounted on the desktop, unmount"
2416 " it first before using it in QEMU", file_name);
2417 error_report("Command to unmount device: diskutil unmountDisk %s",
2418 file_name);
2419 error_report("Command to mount device: diskutil mountDisk %s", file_name);
2420}
2421
2422#endif /* defined(__APPLE__) && defined(__MACH__) */
19cb3738 2423
508c7cb3
CH
2424static int hdev_probe_device(const char *filename)
2425{
2426 struct stat st;
2427
2428 /* allow a dedicated CD-ROM driver to match with a higher priority */
2429 if (strstart(filename, "/dev/cdrom", NULL))
2430 return 50;
2431
2432 if (stat(filename, &st) >= 0 &&
2433 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2434 return 100;
2435 }
2436
2437 return 0;
2438}
2439
da888d37
SH
2440static int check_hdev_writable(BDRVRawState *s)
2441{
2442#if defined(BLKROGET)
2443 /* Linux block devices can be configured "read-only" using blockdev(8).
2444 * This is independent of device node permissions and therefore open(2)
2445 * with O_RDWR succeeds. Actual writes fail with EPERM.
2446 *
2447 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2448 * check for read-only block devices so that Linux block devices behave
2449 * properly.
2450 */
2451 struct stat st;
2452 int readonly = 0;
2453
2454 if (fstat(s->fd, &st)) {
2455 return -errno;
2456 }
2457
2458 if (!S_ISBLK(st.st_mode)) {
2459 return 0;
2460 }
2461
2462 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2463 return -errno;
2464 }
2465
2466 if (readonly) {
2467 return -EACCES;
2468 }
2469#endif /* defined(BLKROGET) */
2470 return 0;
2471}
2472
7af803d4
HR
2473static void hdev_parse_filename(const char *filename, QDict *options,
2474 Error **errp)
2475{
03c320d8 2476 bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
7af803d4
HR
2477}
2478
3307ed7b
DA
2479static bool hdev_is_sg(BlockDriverState *bs)
2480{
2481
2482#if defined(__linux__)
2483
0d4377b3 2484 BDRVRawState *s = bs->opaque;
3307ed7b
DA
2485 struct stat st;
2486 struct sg_scsi_id scsiid;
2487 int sg_version;
0d4377b3
KW
2488 int ret;
2489
2490 if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
2491 return false;
2492 }
3307ed7b 2493
0d4377b3
KW
2494 ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
2495 if (ret < 0) {
2496 return false;
2497 }
2498
2499 ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
2500 if (ret >= 0) {
3307ed7b
DA
2501 DPRINTF("SG device found: type=%d, version=%d\n",
2502 scsiid.scsi_type, sg_version);
2503 return true;
2504 }
2505
2506#endif
2507
2508 return false;
2509}
2510
015a1036
HR
2511static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2512 Error **errp)
19cb3738
FB
2513{
2514 BDRVRawState *s = bs->opaque;
e428e439 2515 Error *local_err = NULL;
da888d37 2516 int ret;
a76bab49 2517
83affaa6 2518#if defined(__APPLE__) && defined(__MACH__)
129c7d1c
MA
2519 /*
2520 * Caution: while qdict_get_str() is fine, getting non-string types
2521 * would require more care. When @options come from -blockdev or
2522 * blockdev_add, its members are typed according to the QAPI
2523 * schema, but when they come from -drive, they're all QString.
2524 */
3307ed7b 2525 const char *filename = qdict_get_str(options, "filename");
d0855f12
JA
2526 char bsd_path[MAXPATHLEN] = "";
2527 bool error_occurred = false;
2528
2529 /* If using a real cdrom */
2530 if (strcmp(filename, "/dev/cdrom") == 0) {
2531 char *mediaType = NULL;
2532 kern_return_t ret_val;
2533 io_iterator_t mediaIterator = 0;
2534
2535 mediaType = FindEjectableOpticalMedia(&mediaIterator);
2536 if (mediaType == NULL) {
2537 error_setg(errp, "Please make sure your CD/DVD is in the optical"
2538 " drive");
2539 error_occurred = true;
2540 goto hdev_open_Mac_error;
2541 }
3307ed7b 2542
d0855f12
JA
2543 ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
2544 if (ret_val != KERN_SUCCESS) {
2545 error_setg(errp, "Could not get BSD path for optical drive");
2546 error_occurred = true;
2547 goto hdev_open_Mac_error;
2548 }
2549
2550 /* If a real optical drive was not found */
2551 if (bsd_path[0] == '\0') {
2552 error_setg(errp, "Failed to obtain bsd path for optical drive");
2553 error_occurred = true;
2554 goto hdev_open_Mac_error;
2555 }
2556
2557 /* If using a cdrom disc and finding a partition on the disc failed */
2558 if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
2559 setup_cdrom(bsd_path, errp) == false) {
2560 print_unmounting_directions(bsd_path);
2561 error_occurred = true;
2562 goto hdev_open_Mac_error;
19cb3738 2563 }
3b46e624 2564
46f5ac20 2565 qdict_put_str(options, "filename", bsd_path);
d0855f12
JA
2566
2567hdev_open_Mac_error:
2568 g_free(mediaType);
2569 if (mediaIterator) {
2570 IOObjectRelease(mediaIterator);
2571 }
2572 if (error_occurred) {
2573 return -ENOENT;
2574 }
19cb3738 2575 }
d0855f12 2576#endif /* defined(__APPLE__) && defined(__MACH__) */
19cb3738
FB
2577
2578 s->type = FTYPE_FILE;
90babde0 2579
e428e439 2580 ret = raw_open_common(bs, options, flags, 0, &local_err);
da888d37 2581 if (ret < 0) {
621ff94d 2582 error_propagate(errp, local_err);
d0855f12
JA
2583#if defined(__APPLE__) && defined(__MACH__)
2584 if (*bsd_path) {
2585 filename = bsd_path;
2586 }
2587 /* if a physical device experienced an error while being opened */
2588 if (strncmp(filename, "/dev/", 5) == 0) {
2589 print_unmounting_directions(filename);
2590 }
2591#endif /* defined(__APPLE__) && defined(__MACH__) */
da888d37
SH
2592 return ret;
2593 }
2594
3307ed7b
DA
2595 /* Since this does ioctl the device must be already opened */
2596 bs->sg = hdev_is_sg(bs);
2597
da888d37
SH
2598 if (flags & BDRV_O_RDWR) {
2599 ret = check_hdev_writable(s);
2600 if (ret < 0) {
2601 raw_close(bs);
e428e439 2602 error_setg_errno(errp, -ret, "The device is not writable");
da888d37
SH
2603 return ret;
2604 }
2605 }
2606
2607 return ret;
19cb3738
FB
2608}
2609
03ff3ca3 2610#if defined(__linux__)
221f715d 2611
7c84b1b8 2612static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
221f715d 2613 unsigned long int req, void *buf,
097310b5 2614 BlockCompletionFunc *cb, void *opaque)
221f715d 2615{
f141eafe 2616 BDRVRawState *s = bs->opaque;
c208e8c2 2617 RawPosixAIOData *acb;
c4d9d196 2618 ThreadPool *pool;
221f715d 2619
f141eafe
AL
2620 if (fd_open(bs) < 0)
2621 return NULL;
c208e8c2 2622
7c9e5276
PB
2623 if (req == SG_IO && s->pr_mgr) {
2624 struct sg_io_hdr *io_hdr = buf;
2625 if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
2626 io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
2627 return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
2628 s->fd, io_hdr, cb, opaque);
2629 }
2630 }
2631
c84b3192 2632 acb = g_new(RawPosixAIOData, 1);
c208e8c2
PB
2633 acb->bs = bs;
2634 acb->aio_type = QEMU_AIO_IOCTL;
2635 acb->aio_fildes = s->fd;
2636 acb->aio_offset = 0;
2637 acb->aio_ioctl_buf = buf;
2638 acb->aio_ioctl_cmd = req;
c4d9d196
SH
2639 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2640 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
221f715d 2641}
f709623b 2642#endif /* linux */
221f715d 2643
9f23011a
BS
2644static int fd_open(BlockDriverState *bs)
2645{
2646 BDRVRawState *s = bs->opaque;
2647
2648 /* this is just to ensure s->fd is sane (its called by io ops) */
2649 if (s->fd >= 0)
2650 return 0;
2651 return -EIO;
2652}
04eeb8b6 2653
4da444a0 2654static coroutine_fn BlockAIOCB *hdev_aio_pdiscard(BlockDriverState *bs,
f5a5ca79 2655 int64_t offset, int bytes,
097310b5 2656 BlockCompletionFunc *cb, void *opaque)
c36dd8a0
AF
2657{
2658 BDRVRawState *s = bs->opaque;
2659
2660 if (fd_open(bs) < 0) {
2661 return NULL;
2662 }
f5a5ca79 2663 return paio_submit(bs, s->fd, offset, NULL, bytes,
c36dd8a0
AF
2664 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2665}
2666
2ffa76c2 2667static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 2668 int64_t offset, int bytes, BdrvRequestFlags flags)
d0b4503e
PB
2669{
2670 BDRVRawState *s = bs->opaque;
2671 int rc;
2672
2673 rc = fd_open(bs);
2674 if (rc < 0) {
2675 return rc;
2676 }
2677 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
f5a5ca79 2678 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
97a2ae34
PB
2679 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2680 } else if (s->discard_zeroes) {
f5a5ca79 2681 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
97a2ae34 2682 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
d0b4503e 2683 }
97a2ae34 2684 return -ENOTSUP;
d0b4503e
PB
2685}
2686
6f482f74 2687static int hdev_create(const char *filename, QemuOpts *opts,
d5124c00 2688 Error **errp)
93c65b47
AL
2689{
2690 int fd;
2691 int ret = 0;
2692 struct stat stat_buf;
0e7e1989 2693 int64_t total_size = 0;
cc28c6aa
HR
2694 bool has_prefix;
2695
f709623b
HR
2696 /* This function is used by both protocol block drivers and therefore either
2697 * of these prefixes may be given.
cc28c6aa
HR
2698 * The return value has to be stored somewhere, otherwise this is an error
2699 * due to -Werror=unused-value. */
2700 has_prefix =
2701 strstart(filename, "host_device:", &filename) ||
f709623b 2702 strstart(filename, "host_cdrom:" , &filename);
cc28c6aa
HR
2703
2704 (void)has_prefix;
93c65b47 2705
bdd03cdf
HR
2706 ret = raw_normalize_devicepath(&filename);
2707 if (ret < 0) {
2708 error_setg_errno(errp, -ret, "Could not normalize device path");
2709 return ret;
2710 }
2711
0e7e1989 2712 /* Read out options */
180e9526
HT
2713 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2714 BDRV_SECTOR_SIZE);
93c65b47 2715
6165f4d8 2716 fd = qemu_open(filename, O_WRONLY | O_BINARY);
e428e439
HR
2717 if (fd < 0) {
2718 ret = -errno;
2719 error_setg_errno(errp, -ret, "Could not open device");
2720 return ret;
2721 }
93c65b47 2722
e428e439 2723 if (fstat(fd, &stat_buf) < 0) {
57e69b7d 2724 ret = -errno;
e428e439
HR
2725 error_setg_errno(errp, -ret, "Could not stat device");
2726 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2727 error_setg(errp,
2728 "The given file is neither a block nor a character device");
57e69b7d 2729 ret = -ENODEV;
180e9526 2730 } else if (lseek(fd, 0, SEEK_END) < total_size) {
e428e439 2731 error_setg(errp, "Device is too small");
93c65b47 2732 ret = -ENOSPC;
e428e439 2733 }
93c65b47 2734
97ec9117
FZ
2735 if (!ret && total_size) {
2736 uint8_t buf[BDRV_SECTOR_SIZE] = { 0 };
2737 int64_t zero_size = MIN(BDRV_SECTOR_SIZE, total_size);
2738 if (lseek(fd, 0, SEEK_SET) == -1) {
2739 ret = -errno;
2740 } else {
2741 ret = qemu_write_full(fd, buf, zero_size);
2742 ret = ret == zero_size ? 0 : -errno;
2743 }
2744 }
2e1e79da 2745 qemu_close(fd);
93c65b47
AL
2746 return ret;
2747}
2748
5efa9d5a 2749static BlockDriver bdrv_host_device = {
0b4ce02e 2750 .format_name = "host_device",
84a12e66 2751 .protocol_name = "host_device",
0b4ce02e 2752 .instance_size = sizeof(BDRVRawState),
030be321 2753 .bdrv_needs_filename = true,
0b4ce02e 2754 .bdrv_probe_device = hdev_probe_device,
7af803d4 2755 .bdrv_parse_filename = hdev_parse_filename,
66f82cee 2756 .bdrv_file_open = hdev_open,
0b4ce02e 2757 .bdrv_close = raw_close,
1bc6b705
JC
2758 .bdrv_reopen_prepare = raw_reopen_prepare,
2759 .bdrv_reopen_commit = raw_reopen_commit,
2760 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2761 .bdrv_create = hdev_create,
6f482f74 2762 .create_opts = &raw_create_opts,
2ffa76c2 2763 .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
3b46e624 2764
9d52aa3c
KW
2765 .bdrv_co_preadv = raw_co_preadv,
2766 .bdrv_co_pwritev = raw_co_pwritev,
b2e12bc6 2767 .bdrv_aio_flush = raw_aio_flush,
4da444a0 2768 .bdrv_aio_pdiscard = hdev_aio_pdiscard,
c25f53b0 2769 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2770 .bdrv_io_plug = raw_aio_plug,
2771 .bdrv_io_unplug = raw_aio_unplug,
3c529d93 2772
55b949c8 2773 .bdrv_truncate = raw_truncate,
e60f469c 2774 .bdrv_getlength = raw_getlength,
260a82e5 2775 .bdrv_get_info = raw_get_info,
4a1d5e1f
FZ
2776 .bdrv_get_allocated_file_size
2777 = raw_get_allocated_file_size,
244a5668
FZ
2778 .bdrv_check_perm = raw_check_perm,
2779 .bdrv_set_perm = raw_set_perm,
2780 .bdrv_abort_perm_update = raw_abort_perm_update,
1a9335e4
ET
2781 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2782 .bdrv_probe_geometry = hdev_probe_geometry,
19cb3738 2783
f3a5d3f8 2784 /* generic scsi device */
63ec93db 2785#ifdef __linux__
63ec93db
CH
2786 .bdrv_aio_ioctl = hdev_aio_ioctl,
2787#endif
f3a5d3f8
CH
2788};
2789
18fa1c42
HR
2790#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2791static void cdrom_parse_filename(const char *filename, QDict *options,
2792 Error **errp)
2793{
03c320d8 2794 bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
18fa1c42
HR
2795}
2796#endif
2797
2798#ifdef __linux__
015a1036
HR
2799static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2800 Error **errp)
f3a5d3f8
CH
2801{
2802 BDRVRawState *s = bs->opaque;
2803
f3a5d3f8
CH
2804 s->type = FTYPE_CD;
2805
19a3da7f 2806 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
9be38598 2807 return raw_open_common(bs, options, flags, O_NONBLOCK, errp);
f3a5d3f8
CH
2808}
2809
508c7cb3
CH
2810static int cdrom_probe_device(const char *filename)
2811{
3baf720e
CR
2812 int fd, ret;
2813 int prio = 0;
343f8568 2814 struct stat st;
3baf720e 2815
6165f4d8 2816 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
3baf720e
CR
2817 if (fd < 0) {
2818 goto out;
2819 }
343f8568
JS
2820 ret = fstat(fd, &st);
2821 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2822 goto outc;
2823 }
3baf720e
CR
2824
2825 /* Attempt to detect via a CDROM specific ioctl */
2826 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2827 if (ret >= 0)
2828 prio = 100;
2829
343f8568 2830outc:
2e1e79da 2831 qemu_close(fd);
3baf720e
CR
2832out:
2833 return prio;
508c7cb3
CH
2834}
2835
e031f750 2836static bool cdrom_is_inserted(BlockDriverState *bs)
f3a5d3f8
CH
2837{
2838 BDRVRawState *s = bs->opaque;
2839 int ret;
2840
2841 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
e031f750 2842 return ret == CDS_DISC_OK;
f3a5d3f8
CH
2843}
2844
f36f3949 2845static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
2846{
2847 BDRVRawState *s = bs->opaque;
2848
2849 if (eject_flag) {
2850 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2851 perror("CDROMEJECT");
2852 } else {
2853 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2854 perror("CDROMEJECT");
2855 }
f3a5d3f8
CH
2856}
2857
025e849a 2858static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
2859{
2860 BDRVRawState *s = bs->opaque;
2861
2862 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2863 /*
2864 * Note: an error can happen if the distribution automatically
2865 * mounts the CD-ROM
2866 */
2867 /* perror("CDROM_LOCKDOOR"); */
2868 }
f3a5d3f8
CH
2869}
2870
2871static BlockDriver bdrv_host_cdrom = {
2872 .format_name = "host_cdrom",
84a12e66 2873 .protocol_name = "host_cdrom",
f3a5d3f8 2874 .instance_size = sizeof(BDRVRawState),
030be321 2875 .bdrv_needs_filename = true,
508c7cb3 2876 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 2877 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 2878 .bdrv_file_open = cdrom_open,
f3a5d3f8 2879 .bdrv_close = raw_close,
1bc6b705
JC
2880 .bdrv_reopen_prepare = raw_reopen_prepare,
2881 .bdrv_reopen_commit = raw_reopen_commit,
2882 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2883 .bdrv_create = hdev_create,
6f482f74 2884 .create_opts = &raw_create_opts,
f3a5d3f8 2885
9d52aa3c
KW
2886
2887 .bdrv_co_preadv = raw_co_preadv,
2888 .bdrv_co_pwritev = raw_co_pwritev,
b2e12bc6 2889 .bdrv_aio_flush = raw_aio_flush,
c25f53b0 2890 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2891 .bdrv_io_plug = raw_aio_plug,
2892 .bdrv_io_unplug = raw_aio_unplug,
f3a5d3f8 2893
55b949c8 2894 .bdrv_truncate = raw_truncate,
b94a2610
KW
2895 .bdrv_getlength = raw_getlength,
2896 .has_variable_length = true,
4a1d5e1f
FZ
2897 .bdrv_get_allocated_file_size
2898 = raw_get_allocated_file_size,
f3a5d3f8
CH
2899
2900 /* removable device support */
2901 .bdrv_is_inserted = cdrom_is_inserted,
2902 .bdrv_eject = cdrom_eject,
025e849a 2903 .bdrv_lock_medium = cdrom_lock_medium,
f3a5d3f8
CH
2904
2905 /* generic scsi device */
63ec93db 2906 .bdrv_aio_ioctl = hdev_aio_ioctl,
f3a5d3f8
CH
2907};
2908#endif /* __linux__ */
2909
a167ba50 2910#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
511018e4
AT
2911static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2912 Error **errp)
f3a5d3f8
CH
2913{
2914 BDRVRawState *s = bs->opaque;
e428e439 2915 Error *local_err = NULL;
f3a5d3f8
CH
2916 int ret;
2917
2918 s->type = FTYPE_CD;
2919
e428e439
HR
2920 ret = raw_open_common(bs, options, flags, 0, &local_err);
2921 if (ret) {
621ff94d 2922 error_propagate(errp, local_err);
f3a5d3f8 2923 return ret;
e428e439 2924 }
f3a5d3f8 2925
9b2260cb 2926 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
2927 ioctl(s->fd, CDIOCALLOW);
2928 return 0;
2929}
2930
508c7cb3
CH
2931static int cdrom_probe_device(const char *filename)
2932{
2933 if (strstart(filename, "/dev/cd", NULL) ||
2934 strstart(filename, "/dev/acd", NULL))
2935 return 100;
2936 return 0;
2937}
2938
f3a5d3f8
CH
2939static int cdrom_reopen(BlockDriverState *bs)
2940{
2941 BDRVRawState *s = bs->opaque;
2942 int fd;
2943
2944 /*
2945 * Force reread of possibly changed/newly loaded disc,
2946 * FreeBSD seems to not notice sometimes...
2947 */
2948 if (s->fd >= 0)
2e1e79da 2949 qemu_close(s->fd);
6165f4d8 2950 fd = qemu_open(bs->filename, s->open_flags, 0644);
f3a5d3f8
CH
2951 if (fd < 0) {
2952 s->fd = -1;
2953 return -EIO;
2954 }
2955 s->fd = fd;
2956
9b2260cb 2957 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
2958 ioctl(s->fd, CDIOCALLOW);
2959 return 0;
2960}
2961
e031f750 2962static bool cdrom_is_inserted(BlockDriverState *bs)
f3a5d3f8
CH
2963{
2964 return raw_getlength(bs) > 0;
2965}
2966
f36f3949 2967static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
2968{
2969 BDRVRawState *s = bs->opaque;
2970
2971 if (s->fd < 0)
822e1cd1 2972 return;
f3a5d3f8
CH
2973
2974 (void) ioctl(s->fd, CDIOCALLOW);
2975
2976 if (eject_flag) {
2977 if (ioctl(s->fd, CDIOCEJECT) < 0)
2978 perror("CDIOCEJECT");
2979 } else {
2980 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2981 perror("CDIOCCLOSE");
2982 }
2983
822e1cd1 2984 cdrom_reopen(bs);
f3a5d3f8
CH
2985}
2986
025e849a 2987static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
2988{
2989 BDRVRawState *s = bs->opaque;
2990
2991 if (s->fd < 0)
7bf37fed 2992 return;
f3a5d3f8
CH
2993 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2994 /*
2995 * Note: an error can happen if the distribution automatically
2996 * mounts the CD-ROM
2997 */
2998 /* perror("CDROM_LOCKDOOR"); */
2999 }
f3a5d3f8
CH
3000}
3001
3002static BlockDriver bdrv_host_cdrom = {
3003 .format_name = "host_cdrom",
84a12e66 3004 .protocol_name = "host_cdrom",
f3a5d3f8 3005 .instance_size = sizeof(BDRVRawState),
030be321 3006 .bdrv_needs_filename = true,
508c7cb3 3007 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 3008 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 3009 .bdrv_file_open = cdrom_open,
f3a5d3f8 3010 .bdrv_close = raw_close,
1bc6b705
JC
3011 .bdrv_reopen_prepare = raw_reopen_prepare,
3012 .bdrv_reopen_commit = raw_reopen_commit,
3013 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 3014 .bdrv_create = hdev_create,
6f482f74 3015 .create_opts = &raw_create_opts,
f3a5d3f8 3016
9d52aa3c
KW
3017 .bdrv_co_preadv = raw_co_preadv,
3018 .bdrv_co_pwritev = raw_co_pwritev,
b2e12bc6 3019 .bdrv_aio_flush = raw_aio_flush,
c25f53b0 3020 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
3021 .bdrv_io_plug = raw_aio_plug,
3022 .bdrv_io_unplug = raw_aio_unplug,
f3a5d3f8 3023
55b949c8 3024 .bdrv_truncate = raw_truncate,
b94a2610
KW
3025 .bdrv_getlength = raw_getlength,
3026 .has_variable_length = true,
4a1d5e1f
FZ
3027 .bdrv_get_allocated_file_size
3028 = raw_get_allocated_file_size,
f3a5d3f8 3029
19cb3738 3030 /* removable device support */
f3a5d3f8
CH
3031 .bdrv_is_inserted = cdrom_is_inserted,
3032 .bdrv_eject = cdrom_eject,
025e849a 3033 .bdrv_lock_medium = cdrom_lock_medium,
19cb3738 3034};
f3a5d3f8 3035#endif /* __FreeBSD__ */
5efa9d5a 3036
84a12e66 3037static void bdrv_file_init(void)
5efa9d5a 3038{
508c7cb3
CH
3039 /*
3040 * Register all the drivers. Note that order is important, the driver
3041 * registered last will get probed first.
3042 */
84a12e66 3043 bdrv_register(&bdrv_file);
5efa9d5a 3044 bdrv_register(&bdrv_host_device);
f3a5d3f8 3045#ifdef __linux__
f3a5d3f8
CH
3046 bdrv_register(&bdrv_host_cdrom);
3047#endif
a167ba50 3048#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8
CH
3049 bdrv_register(&bdrv_host_cdrom);
3050#endif
5efa9d5a
AL
3051}
3052
84a12e66 3053block_init(bdrv_file_init);