ivshmem: improve debug messages
[qemu/ar7.git] / block / raw-posix.c
blob3a527f0b6b287a078126a05cbcda559aad3b8c76
1 /*
2 * Block driver for RAW files (posix)
4 * Copyright (c) 2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu-common.h"
25 #include "qemu/error-report.h"
26 #include "qemu/timer.h"
27 #include "qemu/log.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
30 #include "trace.h"
31 #include "block/thread-pool.h"
32 #include "qemu/iov.h"
33 #include "raw-aio.h"
34 #include "qapi/util.h"
35 #include "qapi/qmp/qstring.h"
37 #if defined(__APPLE__) && (__MACH__)
38 #include <paths.h>
39 #include <sys/param.h>
40 #include <IOKit/IOKitLib.h>
41 #include <IOKit/IOBSD.h>
42 #include <IOKit/storage/IOMediaBSDClient.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <IOKit/storage/IOCDMedia.h>
45 //#include <IOKit/storage/IOCDTypes.h>
46 #include <CoreFoundation/CoreFoundation.h>
47 #endif
49 #ifdef __sun__
50 #define _POSIX_PTHREAD_SEMANTICS 1
51 #include <sys/dkio.h>
52 #endif
53 #ifdef __linux__
54 #include <sys/types.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/param.h>
58 #include <linux/cdrom.h>
59 #include <linux/fd.h>
60 #include <linux/fs.h>
61 #include <linux/hdreg.h>
62 #include <scsi/sg.h>
63 #ifdef __s390__
64 #include <asm/dasd.h>
65 #endif
66 #ifndef FS_NOCOW_FL
67 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
68 #endif
69 #endif
70 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
71 #include <linux/falloc.h>
72 #endif
73 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
74 #include <sys/disk.h>
75 #include <sys/cdio.h>
76 #endif
78 #ifdef __OpenBSD__
79 #include <sys/ioctl.h>
80 #include <sys/disklabel.h>
81 #include <sys/dkio.h>
82 #endif
84 #ifdef __NetBSD__
85 #include <sys/ioctl.h>
86 #include <sys/disklabel.h>
87 #include <sys/dkio.h>
88 #include <sys/disk.h>
89 #endif
91 #ifdef __DragonFly__
92 #include <sys/ioctl.h>
93 #include <sys/diskslice.h>
94 #endif
96 #ifdef CONFIG_XFS
97 #include <xfs/xfs.h>
98 #endif
100 //#define DEBUG_BLOCK
102 #ifdef DEBUG_BLOCK
103 # define DEBUG_BLOCK_PRINT 1
104 #else
105 # define DEBUG_BLOCK_PRINT 0
106 #endif
107 #define DPRINTF(fmt, ...) \
108 do { \
109 if (DEBUG_BLOCK_PRINT) { \
110 printf(fmt, ## __VA_ARGS__); \
112 } while (0)
114 /* OS X does not have O_DSYNC */
115 #ifndef O_DSYNC
116 #ifdef O_SYNC
117 #define O_DSYNC O_SYNC
118 #elif defined(O_FSYNC)
119 #define O_DSYNC O_FSYNC
120 #endif
121 #endif
123 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
124 #ifndef O_DIRECT
125 #define O_DIRECT O_DSYNC
126 #endif
128 #define FTYPE_FILE 0
129 #define FTYPE_CD 1
130 #define FTYPE_FD 2
132 /* if the FD is not accessed during that time (in ns), we try to
133 reopen it to see if the disk has been changed */
134 #define FD_OPEN_TIMEOUT (1000000000)
136 #define MAX_BLOCKSIZE 4096
138 typedef struct BDRVRawState {
139 int fd;
140 int type;
141 int open_flags;
142 size_t buf_align;
144 #if defined(__linux__)
145 /* linux floppy specific */
146 int64_t fd_open_time;
147 int64_t fd_error_time;
148 int fd_got_error;
149 int fd_media_changed;
150 #endif
151 #ifdef CONFIG_LINUX_AIO
152 int use_aio;
153 void *aio_ctx;
154 #endif
155 #ifdef CONFIG_XFS
156 bool is_xfs:1;
157 #endif
158 bool has_discard:1;
159 bool has_write_zeroes:1;
160 bool discard_zeroes:1;
161 bool has_fallocate;
162 bool needs_alignment;
163 } BDRVRawState;
165 typedef struct BDRVRawReopenState {
166 int fd;
167 int open_flags;
168 #ifdef CONFIG_LINUX_AIO
169 int use_aio;
170 #endif
171 } BDRVRawReopenState;
173 static int fd_open(BlockDriverState *bs);
174 static int64_t raw_getlength(BlockDriverState *bs);
176 typedef struct RawPosixAIOData {
177 BlockDriverState *bs;
178 int aio_fildes;
179 union {
180 struct iovec *aio_iov;
181 void *aio_ioctl_buf;
183 int aio_niov;
184 uint64_t aio_nbytes;
185 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
186 off_t aio_offset;
187 int aio_type;
188 } RawPosixAIOData;
190 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
191 static int cdrom_reopen(BlockDriverState *bs);
192 #endif
194 #if defined(__NetBSD__)
195 static int raw_normalize_devicepath(const char **filename)
197 static char namebuf[PATH_MAX];
198 const char *dp, *fname;
199 struct stat sb;
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;
209 if (!S_ISBLK(sb.st_mode)) {
210 return 0;
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);
219 fprintf(stderr, "%s is a block device", fname);
220 *filename = namebuf;
221 fprintf(stderr, ", using %s\n", *filename);
223 return 0;
225 #else
226 static int raw_normalize_devicepath(const char **filename)
228 return 0;
230 #endif
233 * Get logical block size via ioctl. On success store it in @sector_size_p.
235 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
237 unsigned int sector_size;
238 bool success = false;
240 errno = ENOTSUP;
242 /* Try a few ioctls to get the right size */
243 #ifdef BLKSSZGET
244 if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
245 *sector_size_p = sector_size;
246 success = true;
248 #endif
249 #ifdef DKIOCGETBLOCKSIZE
250 if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
251 *sector_size_p = sector_size;
252 success = true;
254 #endif
255 #ifdef DIOCGSECTORSIZE
256 if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
257 *sector_size_p = sector_size;
258 success = true;
260 #endif
262 return success ? 0 : -errno;
266 * Get physical block size of @fd.
267 * On success, store it in @blk_size and return 0.
268 * On failure, return -errno.
270 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
272 #ifdef BLKPBSZGET
273 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
274 return -errno;
276 return 0;
277 #else
278 return -ENOTSUP;
279 #endif
282 /* Check if read is allowed with given memory buffer and length.
284 * This function is used to check O_DIRECT memory buffer and request alignment.
286 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
288 ssize_t ret = pread(fd, buf, len, 0);
290 if (ret >= 0) {
291 return true;
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.
299 if (errno != EINVAL) {
300 return true;
302 #endif
304 return false;
307 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
309 BDRVRawState *s = bs->opaque;
310 char *buf;
311 size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
313 /* For SCSI generic devices the alignment is not really used.
314 With buffered I/O, we don't have any restrictions. */
315 if (bdrv_is_sg(bs) || !s->needs_alignment) {
316 bs->request_alignment = 1;
317 s->buf_align = 1;
318 return;
321 bs->request_alignment = 0;
322 s->buf_align = 0;
323 /* Let's try to use the logical blocksize for the alignment. */
324 if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {
325 bs->request_alignment = 0;
327 #ifdef CONFIG_XFS
328 if (s->is_xfs) {
329 struct dioattr da;
330 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
331 bs->request_alignment = da.d_miniosz;
332 /* The kernel returns wrong information for d_mem */
333 /* s->buf_align = da.d_mem; */
336 #endif
338 /* If we could not get the sizes so far, we can only guess them */
339 if (!s->buf_align) {
340 size_t align;
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)) {
344 s->buf_align = align;
345 break;
348 qemu_vfree(buf);
351 if (!bs->request_alignment) {
352 size_t align;
353 buf = qemu_memalign(s->buf_align, max_align);
354 for (align = 512; align <= max_align; align <<= 1) {
355 if (raw_is_io_aligned(fd, buf, align)) {
356 bs->request_alignment = align;
357 break;
360 qemu_vfree(buf);
363 if (!s->buf_align || !bs->request_alignment) {
364 error_setg(errp, "Could not find working O_DIRECT alignment. "
365 "Try cache.direct=off.");
369 static void raw_parse_flags(int bdrv_flags, int *open_flags)
371 assert(open_flags != NULL);
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;
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;
388 static void raw_detach_aio_context(BlockDriverState *bs)
390 #ifdef CONFIG_LINUX_AIO
391 BDRVRawState *s = bs->opaque;
393 if (s->use_aio) {
394 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
396 #endif
399 static void raw_attach_aio_context(BlockDriverState *bs,
400 AioContext *new_context)
402 #ifdef CONFIG_LINUX_AIO
403 BDRVRawState *s = bs->opaque;
405 if (s->use_aio) {
406 laio_attach_aio_context(s->aio_ctx, new_context);
408 #endif
411 #ifdef CONFIG_LINUX_AIO
412 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
414 int ret = -1;
415 assert(aio_ctx != NULL);
416 assert(use_aio != NULL);
418 * Currently Linux do AIO only for files opened with O_DIRECT
419 * specified so check NOCACHE flag too
421 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
422 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
424 /* if non-NULL, laio_init() has already been run */
425 if (*aio_ctx == NULL) {
426 *aio_ctx = laio_init();
427 if (!*aio_ctx) {
428 goto error;
431 *use_aio = 1;
432 } else {
433 *use_aio = 0;
436 ret = 0;
438 error:
439 return ret;
441 #endif
443 static void raw_parse_filename(const char *filename, QDict *options,
444 Error **errp)
446 /* The filename does not have to be prefixed by the protocol name, since
447 * "file" is the default protocol; therefore, the return value of this
448 * function call can be ignored. */
449 strstart(filename, "file:", &filename);
451 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
454 static QemuOptsList raw_runtime_opts = {
455 .name = "raw",
456 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
457 .desc = {
459 .name = "filename",
460 .type = QEMU_OPT_STRING,
461 .help = "File name of the image",
463 { /* end of list */ }
467 static int raw_open_common(BlockDriverState *bs, QDict *options,
468 int bdrv_flags, int open_flags, Error **errp)
470 BDRVRawState *s = bs->opaque;
471 QemuOpts *opts;
472 Error *local_err = NULL;
473 const char *filename = NULL;
474 int fd, ret;
475 struct stat st;
477 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
478 qemu_opts_absorb_qdict(opts, options, &local_err);
479 if (local_err) {
480 error_propagate(errp, local_err);
481 ret = -EINVAL;
482 goto fail;
485 filename = qemu_opt_get(opts, "filename");
487 ret = raw_normalize_devicepath(&filename);
488 if (ret != 0) {
489 error_setg_errno(errp, -ret, "Could not normalize device path");
490 goto fail;
493 s->open_flags = open_flags;
494 raw_parse_flags(bdrv_flags, &s->open_flags);
496 s->fd = -1;
497 fd = qemu_open(filename, s->open_flags, 0644);
498 if (fd < 0) {
499 ret = -errno;
500 if (ret == -EROFS) {
501 ret = -EACCES;
503 goto fail;
505 s->fd = fd;
507 #ifdef CONFIG_LINUX_AIO
508 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
509 qemu_close(fd);
510 ret = -errno;
511 error_setg_errno(errp, -ret, "Could not set AIO state");
512 goto fail;
514 if (!s->use_aio && (bdrv_flags & BDRV_O_NATIVE_AIO)) {
515 error_printf("WARNING: aio=native was specified for '%s', but "
516 "it requires cache.direct=on, which was not "
517 "specified. Falling back to aio=threads.\n"
518 " This will become an error condition in "
519 "future QEMU versions.\n",
520 bs->filename);
522 #else
523 if (bdrv_flags & BDRV_O_NATIVE_AIO) {
524 error_printf("WARNING: aio=native was specified for '%s', but "
525 "is not supported in this build. Falling back to "
526 "aio=threads.\n"
527 " This will become an error condition in "
528 "future QEMU versions.\n",
529 bs->filename);
531 #endif /* !defined(CONFIG_LINUX_AIO) */
533 s->has_discard = true;
534 s->has_write_zeroes = true;
535 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
536 s->needs_alignment = true;
539 if (fstat(s->fd, &st) < 0) {
540 ret = -errno;
541 error_setg_errno(errp, errno, "Could not stat file");
542 goto fail;
544 if (S_ISREG(st.st_mode)) {
545 s->discard_zeroes = true;
546 s->has_fallocate = true;
548 if (S_ISBLK(st.st_mode)) {
549 #ifdef BLKDISCARDZEROES
550 unsigned int arg;
551 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
552 s->discard_zeroes = true;
554 #endif
555 #ifdef __linux__
556 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
557 * not rely on the contents of discarded blocks unless using O_DIRECT.
558 * Same for BLKZEROOUT.
560 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
561 s->discard_zeroes = false;
562 s->has_write_zeroes = false;
564 #endif
566 #ifdef __FreeBSD__
567 if (S_ISCHR(st.st_mode)) {
569 * The file is a char device (disk), which on FreeBSD isn't behind
570 * a pager, so force all requests to be aligned. This is needed
571 * so QEMU makes sure all IO operations on the device are aligned
572 * to sector size, or else FreeBSD will reject them with EINVAL.
574 s->needs_alignment = true;
576 #endif
578 #ifdef CONFIG_XFS
579 if (platform_test_xfs_fd(s->fd)) {
580 s->is_xfs = true;
582 #endif
584 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
586 ret = 0;
587 fail:
588 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
589 unlink(filename);
591 qemu_opts_del(opts);
592 return ret;
595 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
596 Error **errp)
598 BDRVRawState *s = bs->opaque;
599 Error *local_err = NULL;
600 int ret;
602 s->type = FTYPE_FILE;
603 ret = raw_open_common(bs, options, flags, 0, &local_err);
604 if (local_err) {
605 error_propagate(errp, local_err);
607 return ret;
610 static int raw_reopen_prepare(BDRVReopenState *state,
611 BlockReopenQueue *queue, Error **errp)
613 BDRVRawState *s;
614 BDRVRawReopenState *raw_s;
615 int ret = 0;
616 Error *local_err = NULL;
618 assert(state != NULL);
619 assert(state->bs != NULL);
621 s = state->bs->opaque;
623 state->opaque = g_new0(BDRVRawReopenState, 1);
624 raw_s = state->opaque;
626 #ifdef CONFIG_LINUX_AIO
627 raw_s->use_aio = s->use_aio;
629 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
630 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
631 * won't override aio_ctx if aio_ctx is non-NULL */
632 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
633 error_setg(errp, "Could not set AIO state");
634 return -1;
636 #endif
638 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
639 raw_s->open_flags |= O_NONBLOCK;
642 raw_parse_flags(state->flags, &raw_s->open_flags);
644 raw_s->fd = -1;
646 int fcntl_flags = O_APPEND | O_NONBLOCK;
647 #ifdef O_NOATIME
648 fcntl_flags |= O_NOATIME;
649 #endif
651 #ifdef O_ASYNC
652 /* Not all operating systems have O_ASYNC, and those that don't
653 * will not let us track the state into raw_s->open_flags (typically
654 * you achieve the same effect with an ioctl, for example I_SETSIG
655 * on Solaris). But we do not use O_ASYNC, so that's fine.
657 assert((s->open_flags & O_ASYNC) == 0);
658 #endif
660 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
661 /* dup the original fd */
662 /* TODO: use qemu fcntl wrapper */
663 #ifdef F_DUPFD_CLOEXEC
664 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
665 #else
666 raw_s->fd = dup(s->fd);
667 if (raw_s->fd != -1) {
668 qemu_set_cloexec(raw_s->fd);
670 #endif
671 if (raw_s->fd >= 0) {
672 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
673 if (ret) {
674 qemu_close(raw_s->fd);
675 raw_s->fd = -1;
680 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
681 if (raw_s->fd == -1) {
682 const char *normalized_filename = state->bs->filename;
683 ret = raw_normalize_devicepath(&normalized_filename);
684 if (ret < 0) {
685 error_setg_errno(errp, -ret, "Could not normalize device path");
686 } else {
687 assert(!(raw_s->open_flags & O_CREAT));
688 raw_s->fd = qemu_open(normalized_filename, raw_s->open_flags);
689 if (raw_s->fd == -1) {
690 error_setg_errno(errp, errno, "Could not reopen file");
691 ret = -1;
696 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
697 * alignment with the new fd. */
698 if (raw_s->fd != -1) {
699 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
700 if (local_err) {
701 qemu_close(raw_s->fd);
702 raw_s->fd = -1;
703 error_propagate(errp, local_err);
704 ret = -EINVAL;
708 return ret;
711 static void raw_reopen_commit(BDRVReopenState *state)
713 BDRVRawReopenState *raw_s = state->opaque;
714 BDRVRawState *s = state->bs->opaque;
716 s->open_flags = raw_s->open_flags;
718 qemu_close(s->fd);
719 s->fd = raw_s->fd;
720 #ifdef CONFIG_LINUX_AIO
721 s->use_aio = raw_s->use_aio;
722 #endif
724 g_free(state->opaque);
725 state->opaque = NULL;
729 static void raw_reopen_abort(BDRVReopenState *state)
731 BDRVRawReopenState *raw_s = state->opaque;
733 /* nothing to do if NULL, we didn't get far enough */
734 if (raw_s == NULL) {
735 return;
738 if (raw_s->fd >= 0) {
739 qemu_close(raw_s->fd);
740 raw_s->fd = -1;
742 g_free(state->opaque);
743 state->opaque = NULL;
746 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
748 BDRVRawState *s = bs->opaque;
750 raw_probe_alignment(bs, s->fd, errp);
751 bs->bl.min_mem_alignment = s->buf_align;
752 bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
755 static int check_for_dasd(int fd)
757 #ifdef BIODASDINFO2
758 struct dasd_information2_t info = {0};
760 return ioctl(fd, BIODASDINFO2, &info);
761 #else
762 return -1;
763 #endif
767 * Try to get @bs's logical and physical block size.
768 * On success, store them in @bsz and return zero.
769 * On failure, return negative errno.
771 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
773 BDRVRawState *s = bs->opaque;
774 int ret;
776 /* If DASD, get blocksizes */
777 if (check_for_dasd(s->fd) < 0) {
778 return -ENOTSUP;
780 ret = probe_logical_blocksize(s->fd, &bsz->log);
781 if (ret < 0) {
782 return ret;
784 return probe_physical_blocksize(s->fd, &bsz->phys);
788 * Try to get @bs's geometry: cyls, heads, sectors.
789 * On success, store them in @geo and return 0.
790 * On failure return -errno.
791 * (Allows block driver to assign default geometry values that guest sees)
793 #ifdef __linux__
794 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
796 BDRVRawState *s = bs->opaque;
797 struct hd_geometry ioctl_geo = {0};
798 uint32_t blksize;
800 /* If DASD, get its geometry */
801 if (check_for_dasd(s->fd) < 0) {
802 return -ENOTSUP;
804 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
805 return -errno;
807 /* HDIO_GETGEO may return success even though geo contains zeros
808 (e.g. certain multipath setups) */
809 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
810 return -ENOTSUP;
812 /* Do not return a geometry for partition */
813 if (ioctl_geo.start != 0) {
814 return -ENOTSUP;
816 geo->heads = ioctl_geo.heads;
817 geo->sectors = ioctl_geo.sectors;
818 if (!probe_physical_blocksize(s->fd, &blksize)) {
819 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
820 geo->cylinders = bdrv_nb_sectors(bs) / (blksize / BDRV_SECTOR_SIZE)
821 / (geo->heads * geo->sectors);
822 return 0;
824 geo->cylinders = ioctl_geo.cylinders;
826 return 0;
828 #else /* __linux__ */
829 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
831 return -ENOTSUP;
833 #endif
835 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
837 int ret;
839 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
840 if (ret == -1) {
841 return -errno;
844 return 0;
847 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
849 int ret;
851 ret = qemu_fdatasync(aiocb->aio_fildes);
852 if (ret == -1) {
853 return -errno;
855 return 0;
858 #ifdef CONFIG_PREADV
860 static bool preadv_present = true;
862 static ssize_t
863 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
865 return preadv(fd, iov, nr_iov, offset);
868 static ssize_t
869 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
871 return pwritev(fd, iov, nr_iov, offset);
874 #else
876 static bool preadv_present = false;
878 static ssize_t
879 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
881 return -ENOSYS;
884 static ssize_t
885 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
887 return -ENOSYS;
890 #endif
892 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
894 ssize_t len;
896 do {
897 if (aiocb->aio_type & QEMU_AIO_WRITE)
898 len = qemu_pwritev(aiocb->aio_fildes,
899 aiocb->aio_iov,
900 aiocb->aio_niov,
901 aiocb->aio_offset);
902 else
903 len = qemu_preadv(aiocb->aio_fildes,
904 aiocb->aio_iov,
905 aiocb->aio_niov,
906 aiocb->aio_offset);
907 } while (len == -1 && errno == EINTR);
909 if (len == -1) {
910 return -errno;
912 return len;
916 * Read/writes the data to/from a given linear buffer.
918 * Returns the number of bytes handles or -errno in case of an error. Short
919 * reads are only returned if the end of the file is reached.
921 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
923 ssize_t offset = 0;
924 ssize_t len;
926 while (offset < aiocb->aio_nbytes) {
927 if (aiocb->aio_type & QEMU_AIO_WRITE) {
928 len = pwrite(aiocb->aio_fildes,
929 (const char *)buf + offset,
930 aiocb->aio_nbytes - offset,
931 aiocb->aio_offset + offset);
932 } else {
933 len = pread(aiocb->aio_fildes,
934 buf + offset,
935 aiocb->aio_nbytes - offset,
936 aiocb->aio_offset + offset);
938 if (len == -1 && errno == EINTR) {
939 continue;
940 } else if (len == -1 && errno == EINVAL &&
941 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
942 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
943 offset > 0) {
944 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
945 * after a short read. Assume that O_DIRECT short reads only occur
946 * at EOF. Therefore this is a short read, not an I/O error.
948 break;
949 } else if (len == -1) {
950 offset = -errno;
951 break;
952 } else if (len == 0) {
953 break;
955 offset += len;
958 return offset;
961 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
963 ssize_t nbytes;
964 char *buf;
966 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
968 * If there is just a single buffer, and it is properly aligned
969 * we can just use plain pread/pwrite without any problems.
971 if (aiocb->aio_niov == 1) {
972 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
975 * We have more than one iovec, and all are properly aligned.
977 * Try preadv/pwritev first and fall back to linearizing the
978 * buffer if it's not supported.
980 if (preadv_present) {
981 nbytes = handle_aiocb_rw_vector(aiocb);
982 if (nbytes == aiocb->aio_nbytes ||
983 (nbytes < 0 && nbytes != -ENOSYS)) {
984 return nbytes;
986 preadv_present = false;
990 * XXX(hch): short read/write. no easy way to handle the reminder
991 * using these interfaces. For now retry using plain
992 * pread/pwrite?
997 * Ok, we have to do it the hard way, copy all segments into
998 * a single aligned buffer.
1000 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1001 if (buf == NULL) {
1002 return -ENOMEM;
1005 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1006 char *p = buf;
1007 int i;
1009 for (i = 0; i < aiocb->aio_niov; ++i) {
1010 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1011 p += aiocb->aio_iov[i].iov_len;
1013 assert(p - buf == aiocb->aio_nbytes);
1016 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1017 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1018 char *p = buf;
1019 size_t count = aiocb->aio_nbytes, copy;
1020 int i;
1022 for (i = 0; i < aiocb->aio_niov && count; ++i) {
1023 copy = count;
1024 if (copy > aiocb->aio_iov[i].iov_len) {
1025 copy = aiocb->aio_iov[i].iov_len;
1027 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1028 assert(count >= copy);
1029 p += copy;
1030 count -= copy;
1032 assert(count == 0);
1034 qemu_vfree(buf);
1036 return nbytes;
1039 #ifdef CONFIG_XFS
1040 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1042 struct xfs_flock64 fl;
1043 int err;
1045 memset(&fl, 0, sizeof(fl));
1046 fl.l_whence = SEEK_SET;
1047 fl.l_start = offset;
1048 fl.l_len = bytes;
1050 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1051 err = errno;
1052 DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1053 return -err;
1056 return 0;
1059 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1061 struct xfs_flock64 fl;
1062 int err;
1064 memset(&fl, 0, sizeof(fl));
1065 fl.l_whence = SEEK_SET;
1066 fl.l_start = offset;
1067 fl.l_len = bytes;
1069 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1070 err = errno;
1071 DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1072 return -err;
1075 return 0;
1077 #endif
1079 static int translate_err(int err)
1081 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1082 err == -ENOTTY) {
1083 err = -ENOTSUP;
1085 return err;
1088 #ifdef CONFIG_FALLOCATE
1089 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1091 do {
1092 if (fallocate(fd, mode, offset, len) == 0) {
1093 return 0;
1095 } while (errno == EINTR);
1096 return translate_err(-errno);
1098 #endif
1100 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1102 int ret = -ENOTSUP;
1103 BDRVRawState *s = aiocb->bs->opaque;
1105 if (!s->has_write_zeroes) {
1106 return -ENOTSUP;
1109 #ifdef BLKZEROOUT
1110 do {
1111 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1112 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1113 return 0;
1115 } while (errno == EINTR);
1117 ret = translate_err(-errno);
1118 #endif
1120 if (ret == -ENOTSUP) {
1121 s->has_write_zeroes = false;
1123 return ret;
1126 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1128 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1129 BDRVRawState *s = aiocb->bs->opaque;
1130 #endif
1132 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1133 return handle_aiocb_write_zeroes_block(aiocb);
1136 #ifdef CONFIG_XFS
1137 if (s->is_xfs) {
1138 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1140 #endif
1142 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1143 if (s->has_write_zeroes) {
1144 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1145 aiocb->aio_offset, aiocb->aio_nbytes);
1146 if (ret == 0 || ret != -ENOTSUP) {
1147 return ret;
1149 s->has_write_zeroes = false;
1151 #endif
1153 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1154 if (s->has_discard && s->has_fallocate) {
1155 int ret = do_fallocate(s->fd,
1156 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1157 aiocb->aio_offset, aiocb->aio_nbytes);
1158 if (ret == 0) {
1159 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1160 if (ret == 0 || ret != -ENOTSUP) {
1161 return ret;
1163 s->has_fallocate = false;
1164 } else if (ret != -ENOTSUP) {
1165 return ret;
1166 } else {
1167 s->has_discard = false;
1170 #endif
1172 #ifdef CONFIG_FALLOCATE
1173 if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1174 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1175 if (ret == 0 || ret != -ENOTSUP) {
1176 return ret;
1178 s->has_fallocate = false;
1180 #endif
1182 return -ENOTSUP;
1185 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1187 int ret = -EOPNOTSUPP;
1188 BDRVRawState *s = aiocb->bs->opaque;
1190 if (!s->has_discard) {
1191 return -ENOTSUP;
1194 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1195 #ifdef BLKDISCARD
1196 do {
1197 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1198 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1199 return 0;
1201 } while (errno == EINTR);
1203 ret = -errno;
1204 #endif
1205 } else {
1206 #ifdef CONFIG_XFS
1207 if (s->is_xfs) {
1208 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1210 #endif
1212 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1213 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1214 aiocb->aio_offset, aiocb->aio_nbytes);
1215 #endif
1218 ret = translate_err(ret);
1219 if (ret == -ENOTSUP) {
1220 s->has_discard = false;
1222 return ret;
1225 static int aio_worker(void *arg)
1227 RawPosixAIOData *aiocb = arg;
1228 ssize_t ret = 0;
1230 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1231 case QEMU_AIO_READ:
1232 ret = handle_aiocb_rw(aiocb);
1233 if (ret >= 0 && ret < aiocb->aio_nbytes) {
1234 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1235 0, aiocb->aio_nbytes - ret);
1237 ret = aiocb->aio_nbytes;
1239 if (ret == aiocb->aio_nbytes) {
1240 ret = 0;
1241 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1242 ret = -EINVAL;
1244 break;
1245 case QEMU_AIO_WRITE:
1246 ret = handle_aiocb_rw(aiocb);
1247 if (ret == aiocb->aio_nbytes) {
1248 ret = 0;
1249 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1250 ret = -EINVAL;
1252 break;
1253 case QEMU_AIO_FLUSH:
1254 ret = handle_aiocb_flush(aiocb);
1255 break;
1256 case QEMU_AIO_IOCTL:
1257 ret = handle_aiocb_ioctl(aiocb);
1258 break;
1259 case QEMU_AIO_DISCARD:
1260 ret = handle_aiocb_discard(aiocb);
1261 break;
1262 case QEMU_AIO_WRITE_ZEROES:
1263 ret = handle_aiocb_write_zeroes(aiocb);
1264 break;
1265 default:
1266 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1267 ret = -EINVAL;
1268 break;
1271 g_free(aiocb);
1272 return ret;
1275 static int paio_submit_co(BlockDriverState *bs, int fd,
1276 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1277 int type)
1279 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1280 ThreadPool *pool;
1282 acb->bs = bs;
1283 acb->aio_type = type;
1284 acb->aio_fildes = fd;
1286 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1287 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1289 if (qiov) {
1290 acb->aio_iov = qiov->iov;
1291 acb->aio_niov = qiov->niov;
1292 assert(qiov->size == acb->aio_nbytes);
1295 trace_paio_submit_co(sector_num, nb_sectors, type);
1296 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1297 return thread_pool_submit_co(pool, aio_worker, acb);
1300 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1301 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1302 BlockCompletionFunc *cb, void *opaque, int type)
1304 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1305 ThreadPool *pool;
1307 acb->bs = bs;
1308 acb->aio_type = type;
1309 acb->aio_fildes = fd;
1311 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1312 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1314 if (qiov) {
1315 acb->aio_iov = qiov->iov;
1316 acb->aio_niov = qiov->niov;
1317 assert(qiov->size == acb->aio_nbytes);
1320 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1321 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1322 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1325 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1326 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1327 BlockCompletionFunc *cb, void *opaque, int type)
1329 BDRVRawState *s = bs->opaque;
1331 if (fd_open(bs) < 0)
1332 return NULL;
1335 * Check if the underlying device requires requests to be aligned,
1336 * and if the request we are trying to submit is aligned or not.
1337 * If this is the case tell the low-level driver that it needs
1338 * to copy the buffer.
1340 if (s->needs_alignment) {
1341 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1342 type |= QEMU_AIO_MISALIGNED;
1343 #ifdef CONFIG_LINUX_AIO
1344 } else if (s->use_aio) {
1345 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1346 nb_sectors, cb, opaque, type);
1347 #endif
1351 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1352 cb, opaque, type);
1355 static void raw_aio_plug(BlockDriverState *bs)
1357 #ifdef CONFIG_LINUX_AIO
1358 BDRVRawState *s = bs->opaque;
1359 if (s->use_aio) {
1360 laio_io_plug(bs, s->aio_ctx);
1362 #endif
1365 static void raw_aio_unplug(BlockDriverState *bs)
1367 #ifdef CONFIG_LINUX_AIO
1368 BDRVRawState *s = bs->opaque;
1369 if (s->use_aio) {
1370 laio_io_unplug(bs, s->aio_ctx, true);
1372 #endif
1375 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1377 #ifdef CONFIG_LINUX_AIO
1378 BDRVRawState *s = bs->opaque;
1379 if (s->use_aio) {
1380 laio_io_unplug(bs, s->aio_ctx, false);
1382 #endif
1385 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1386 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1387 BlockCompletionFunc *cb, void *opaque)
1389 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1390 cb, opaque, QEMU_AIO_READ);
1393 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1394 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1395 BlockCompletionFunc *cb, void *opaque)
1397 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1398 cb, opaque, QEMU_AIO_WRITE);
1401 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1402 BlockCompletionFunc *cb, void *opaque)
1404 BDRVRawState *s = bs->opaque;
1406 if (fd_open(bs) < 0)
1407 return NULL;
1409 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1412 static void raw_close(BlockDriverState *bs)
1414 BDRVRawState *s = bs->opaque;
1416 raw_detach_aio_context(bs);
1418 #ifdef CONFIG_LINUX_AIO
1419 if (s->use_aio) {
1420 laio_cleanup(s->aio_ctx);
1422 #endif
1423 if (s->fd >= 0) {
1424 qemu_close(s->fd);
1425 s->fd = -1;
1429 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1431 BDRVRawState *s = bs->opaque;
1432 struct stat st;
1434 if (fstat(s->fd, &st)) {
1435 return -errno;
1438 if (S_ISREG(st.st_mode)) {
1439 if (ftruncate(s->fd, offset) < 0) {
1440 return -errno;
1442 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1443 if (offset > raw_getlength(bs)) {
1444 return -EINVAL;
1446 } else {
1447 return -ENOTSUP;
1450 return 0;
1453 #ifdef __OpenBSD__
1454 static int64_t raw_getlength(BlockDriverState *bs)
1456 BDRVRawState *s = bs->opaque;
1457 int fd = s->fd;
1458 struct stat st;
1460 if (fstat(fd, &st))
1461 return -errno;
1462 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1463 struct disklabel dl;
1465 if (ioctl(fd, DIOCGDINFO, &dl))
1466 return -errno;
1467 return (uint64_t)dl.d_secsize *
1468 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1469 } else
1470 return st.st_size;
1472 #elif defined(__NetBSD__)
1473 static int64_t raw_getlength(BlockDriverState *bs)
1475 BDRVRawState *s = bs->opaque;
1476 int fd = s->fd;
1477 struct stat st;
1479 if (fstat(fd, &st))
1480 return -errno;
1481 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1482 struct dkwedge_info dkw;
1484 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1485 return dkw.dkw_size * 512;
1486 } else {
1487 struct disklabel dl;
1489 if (ioctl(fd, DIOCGDINFO, &dl))
1490 return -errno;
1491 return (uint64_t)dl.d_secsize *
1492 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1494 } else
1495 return st.st_size;
1497 #elif defined(__sun__)
1498 static int64_t raw_getlength(BlockDriverState *bs)
1500 BDRVRawState *s = bs->opaque;
1501 struct dk_minfo minfo;
1502 int ret;
1503 int64_t size;
1505 ret = fd_open(bs);
1506 if (ret < 0) {
1507 return ret;
1511 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1513 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1514 if (ret != -1) {
1515 return minfo.dki_lbsize * minfo.dki_capacity;
1519 * There are reports that lseek on some devices fails, but
1520 * irc discussion said that contingency on contingency was overkill.
1522 size = lseek(s->fd, 0, SEEK_END);
1523 if (size < 0) {
1524 return -errno;
1526 return size;
1528 #elif defined(CONFIG_BSD)
1529 static int64_t raw_getlength(BlockDriverState *bs)
1531 BDRVRawState *s = bs->opaque;
1532 int fd = s->fd;
1533 int64_t size;
1534 struct stat sb;
1535 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1536 int reopened = 0;
1537 #endif
1538 int ret;
1540 ret = fd_open(bs);
1541 if (ret < 0)
1542 return ret;
1544 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1545 again:
1546 #endif
1547 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1548 #ifdef DIOCGMEDIASIZE
1549 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1550 #elif defined(DIOCGPART)
1552 struct partinfo pi;
1553 if (ioctl(fd, DIOCGPART, &pi) == 0)
1554 size = pi.media_size;
1555 else
1556 size = 0;
1558 if (size == 0)
1559 #endif
1560 #if defined(__APPLE__) && defined(__MACH__)
1562 uint64_t sectors = 0;
1563 uint32_t sector_size = 0;
1565 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1566 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1567 size = sectors * sector_size;
1568 } else {
1569 size = lseek(fd, 0LL, SEEK_END);
1570 if (size < 0) {
1571 return -errno;
1575 #else
1576 size = lseek(fd, 0LL, SEEK_END);
1577 if (size < 0) {
1578 return -errno;
1580 #endif
1581 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1582 switch(s->type) {
1583 case FTYPE_CD:
1584 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1585 if (size == 2048LL * (unsigned)-1)
1586 size = 0;
1587 /* XXX no disc? maybe we need to reopen... */
1588 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1589 reopened = 1;
1590 goto again;
1593 #endif
1594 } else {
1595 size = lseek(fd, 0, SEEK_END);
1596 if (size < 0) {
1597 return -errno;
1600 return size;
1602 #else
1603 static int64_t raw_getlength(BlockDriverState *bs)
1605 BDRVRawState *s = bs->opaque;
1606 int ret;
1607 int64_t size;
1609 ret = fd_open(bs);
1610 if (ret < 0) {
1611 return ret;
1614 size = lseek(s->fd, 0, SEEK_END);
1615 if (size < 0) {
1616 return -errno;
1618 return size;
1620 #endif
1622 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1624 struct stat st;
1625 BDRVRawState *s = bs->opaque;
1627 if (fstat(s->fd, &st) < 0) {
1628 return -errno;
1630 return (int64_t)st.st_blocks * 512;
1633 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1635 int fd;
1636 int result = 0;
1637 int64_t total_size = 0;
1638 bool nocow = false;
1639 PreallocMode prealloc;
1640 char *buf = NULL;
1641 Error *local_err = NULL;
1643 strstart(filename, "file:", &filename);
1645 /* Read out options */
1646 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1647 BDRV_SECTOR_SIZE);
1648 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1649 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1650 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1651 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1652 &local_err);
1653 g_free(buf);
1654 if (local_err) {
1655 error_propagate(errp, local_err);
1656 result = -EINVAL;
1657 goto out;
1660 fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
1661 0644);
1662 if (fd < 0) {
1663 result = -errno;
1664 error_setg_errno(errp, -result, "Could not create file");
1665 goto out;
1668 if (nocow) {
1669 #ifdef __linux__
1670 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1671 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1672 * will be ignored since any failure of this operation should not
1673 * block the left work.
1675 int attr;
1676 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1677 attr |= FS_NOCOW_FL;
1678 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1680 #endif
1683 if (ftruncate(fd, total_size) != 0) {
1684 result = -errno;
1685 error_setg_errno(errp, -result, "Could not resize file");
1686 goto out_close;
1689 switch (prealloc) {
1690 #ifdef CONFIG_POSIX_FALLOCATE
1691 case PREALLOC_MODE_FALLOC:
1692 /* posix_fallocate() doesn't set errno. */
1693 result = -posix_fallocate(fd, 0, total_size);
1694 if (result != 0) {
1695 error_setg_errno(errp, -result,
1696 "Could not preallocate data for the new file");
1698 break;
1699 #endif
1700 case PREALLOC_MODE_FULL:
1702 int64_t num = 0, left = total_size;
1703 buf = g_malloc0(65536);
1705 while (left > 0) {
1706 num = MIN(left, 65536);
1707 result = write(fd, buf, num);
1708 if (result < 0) {
1709 result = -errno;
1710 error_setg_errno(errp, -result,
1711 "Could not write to the new file");
1712 break;
1714 left -= result;
1716 if (result >= 0) {
1717 result = fsync(fd);
1718 if (result < 0) {
1719 result = -errno;
1720 error_setg_errno(errp, -result,
1721 "Could not flush new file to disk");
1724 g_free(buf);
1725 break;
1727 case PREALLOC_MODE_OFF:
1728 break;
1729 default:
1730 result = -EINVAL;
1731 error_setg(errp, "Unsupported preallocation mode: %s",
1732 PreallocMode_lookup[prealloc]);
1733 break;
1736 out_close:
1737 if (qemu_close(fd) != 0 && result == 0) {
1738 result = -errno;
1739 error_setg_errno(errp, -result, "Could not close the new file");
1741 out:
1742 return result;
1746 * Find allocation range in @bs around offset @start.
1747 * May change underlying file descriptor's file offset.
1748 * If @start is not in a hole, store @start in @data, and the
1749 * beginning of the next hole in @hole, and return 0.
1750 * If @start is in a non-trailing hole, store @start in @hole and the
1751 * beginning of the next non-hole in @data, and return 0.
1752 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1753 * If we can't find out, return a negative errno other than -ENXIO.
1755 static int find_allocation(BlockDriverState *bs, off_t start,
1756 off_t *data, off_t *hole)
1758 #if defined SEEK_HOLE && defined SEEK_DATA
1759 BDRVRawState *s = bs->opaque;
1760 off_t offs;
1763 * SEEK_DATA cases:
1764 * D1. offs == start: start is in data
1765 * D2. offs > start: start is in a hole, next data at offs
1766 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1767 * or start is beyond EOF
1768 * If the latter happens, the file has been truncated behind
1769 * our back since we opened it. All bets are off then.
1770 * Treating like a trailing hole is simplest.
1771 * D4. offs < 0, errno != ENXIO: we learned nothing
1773 offs = lseek(s->fd, start, SEEK_DATA);
1774 if (offs < 0) {
1775 return -errno; /* D3 or D4 */
1777 assert(offs >= start);
1779 if (offs > start) {
1780 /* D2: in hole, next data at offs */
1781 *hole = start;
1782 *data = offs;
1783 return 0;
1786 /* D1: in data, end not yet known */
1789 * SEEK_HOLE cases:
1790 * H1. offs == start: start is in a hole
1791 * If this happens here, a hole has been dug behind our back
1792 * since the previous lseek().
1793 * H2. offs > start: either start is in data, next hole at offs,
1794 * or start is in trailing hole, EOF at offs
1795 * Linux treats trailing holes like any other hole: offs ==
1796 * start. Solaris seeks to EOF instead: offs > start (blech).
1797 * If that happens here, a hole has been dug behind our back
1798 * since the previous lseek().
1799 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1800 * If this happens, the file has been truncated behind our
1801 * back since we opened it. Treat it like a trailing hole.
1802 * H4. offs < 0, errno != ENXIO: we learned nothing
1803 * Pretend we know nothing at all, i.e. "forget" about D1.
1805 offs = lseek(s->fd, start, SEEK_HOLE);
1806 if (offs < 0) {
1807 return -errno; /* D1 and (H3 or H4) */
1809 assert(offs >= start);
1811 if (offs > start) {
1813 * D1 and H2: either in data, next hole at offs, or it was in
1814 * data but is now in a trailing hole. In the latter case,
1815 * all bets are off. Treating it as if it there was data all
1816 * the way to EOF is safe, so simply do that.
1818 *data = start;
1819 *hole = offs;
1820 return 0;
1823 /* D1 and H1 */
1824 return -EBUSY;
1825 #else
1826 return -ENOTSUP;
1827 #endif
1831 * Returns the allocation status of the specified sectors.
1833 * If 'sector_num' is beyond the end of the disk image the return value is 0
1834 * and 'pnum' is set to 0.
1836 * 'pnum' is set to the number of sectors (including and immediately following
1837 * the specified sector) that are known to be in the same
1838 * allocated/unallocated state.
1840 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1841 * beyond the end of the disk image it will be clamped.
1843 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1844 int64_t sector_num,
1845 int nb_sectors, int *pnum)
1847 off_t start, data = 0, hole = 0;
1848 int64_t total_size;
1849 int ret;
1851 ret = fd_open(bs);
1852 if (ret < 0) {
1853 return ret;
1856 start = sector_num * BDRV_SECTOR_SIZE;
1857 total_size = bdrv_getlength(bs);
1858 if (total_size < 0) {
1859 return total_size;
1860 } else if (start >= total_size) {
1861 *pnum = 0;
1862 return 0;
1863 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1864 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1867 ret = find_allocation(bs, start, &data, &hole);
1868 if (ret == -ENXIO) {
1869 /* Trailing hole */
1870 *pnum = nb_sectors;
1871 ret = BDRV_BLOCK_ZERO;
1872 } else if (ret < 0) {
1873 /* No info available, so pretend there are no holes */
1874 *pnum = nb_sectors;
1875 ret = BDRV_BLOCK_DATA;
1876 } else if (data == start) {
1877 /* On a data extent, compute sectors to the end of the extent,
1878 * possibly including a partial sector at EOF. */
1879 *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
1880 ret = BDRV_BLOCK_DATA;
1881 } else {
1882 /* On a hole, compute sectors to the beginning of the next extent. */
1883 assert(hole == start);
1884 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1885 ret = BDRV_BLOCK_ZERO;
1887 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1890 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1891 int64_t sector_num, int nb_sectors,
1892 BlockCompletionFunc *cb, void *opaque)
1894 BDRVRawState *s = bs->opaque;
1896 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1897 cb, opaque, QEMU_AIO_DISCARD);
1900 static int coroutine_fn raw_co_write_zeroes(
1901 BlockDriverState *bs, int64_t sector_num,
1902 int nb_sectors, BdrvRequestFlags flags)
1904 BDRVRawState *s = bs->opaque;
1906 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1907 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1908 QEMU_AIO_WRITE_ZEROES);
1909 } else if (s->discard_zeroes) {
1910 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1911 QEMU_AIO_DISCARD);
1913 return -ENOTSUP;
1916 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1918 BDRVRawState *s = bs->opaque;
1920 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1921 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1922 return 0;
1925 static QemuOptsList raw_create_opts = {
1926 .name = "raw-create-opts",
1927 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1928 .desc = {
1930 .name = BLOCK_OPT_SIZE,
1931 .type = QEMU_OPT_SIZE,
1932 .help = "Virtual disk size"
1935 .name = BLOCK_OPT_NOCOW,
1936 .type = QEMU_OPT_BOOL,
1937 .help = "Turn off copy-on-write (valid only on btrfs)"
1940 .name = BLOCK_OPT_PREALLOC,
1941 .type = QEMU_OPT_STRING,
1942 .help = "Preallocation mode (allowed values: off, falloc, full)"
1944 { /* end of list */ }
1948 BlockDriver bdrv_file = {
1949 .format_name = "file",
1950 .protocol_name = "file",
1951 .instance_size = sizeof(BDRVRawState),
1952 .bdrv_needs_filename = true,
1953 .bdrv_probe = NULL, /* no probe for protocols */
1954 .bdrv_parse_filename = raw_parse_filename,
1955 .bdrv_file_open = raw_open,
1956 .bdrv_reopen_prepare = raw_reopen_prepare,
1957 .bdrv_reopen_commit = raw_reopen_commit,
1958 .bdrv_reopen_abort = raw_reopen_abort,
1959 .bdrv_close = raw_close,
1960 .bdrv_create = raw_create,
1961 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1962 .bdrv_co_get_block_status = raw_co_get_block_status,
1963 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1965 .bdrv_aio_readv = raw_aio_readv,
1966 .bdrv_aio_writev = raw_aio_writev,
1967 .bdrv_aio_flush = raw_aio_flush,
1968 .bdrv_aio_discard = raw_aio_discard,
1969 .bdrv_refresh_limits = raw_refresh_limits,
1970 .bdrv_io_plug = raw_aio_plug,
1971 .bdrv_io_unplug = raw_aio_unplug,
1972 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1974 .bdrv_truncate = raw_truncate,
1975 .bdrv_getlength = raw_getlength,
1976 .bdrv_get_info = raw_get_info,
1977 .bdrv_get_allocated_file_size
1978 = raw_get_allocated_file_size,
1980 .bdrv_detach_aio_context = raw_detach_aio_context,
1981 .bdrv_attach_aio_context = raw_attach_aio_context,
1983 .create_opts = &raw_create_opts,
1986 /***********************************************/
1987 /* host device */
1989 #if defined(__APPLE__) && defined(__MACH__)
1990 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1991 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1993 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1995 kern_return_t kernResult;
1996 mach_port_t masterPort;
1997 CFMutableDictionaryRef classesToMatch;
1999 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
2000 if ( KERN_SUCCESS != kernResult ) {
2001 printf( "IOMasterPort returned %d\n", kernResult );
2004 classesToMatch = IOServiceMatching( kIOCDMediaClass );
2005 if ( classesToMatch == NULL ) {
2006 printf( "IOServiceMatching returned a NULL dictionary.\n" );
2007 } else {
2008 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
2010 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
2011 if ( KERN_SUCCESS != kernResult )
2013 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
2016 return kernResult;
2019 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
2021 io_object_t nextMedia;
2022 kern_return_t kernResult = KERN_FAILURE;
2023 *bsdPath = '\0';
2024 nextMedia = IOIteratorNext( mediaIterator );
2025 if ( nextMedia )
2027 CFTypeRef bsdPathAsCFString;
2028 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2029 if ( bsdPathAsCFString ) {
2030 size_t devPathLength;
2031 strcpy( bsdPath, _PATH_DEV );
2032 strcat( bsdPath, "r" );
2033 devPathLength = strlen( bsdPath );
2034 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2035 kernResult = KERN_SUCCESS;
2037 CFRelease( bsdPathAsCFString );
2039 IOObjectRelease( nextMedia );
2042 return kernResult;
2045 #endif
2047 static int hdev_probe_device(const char *filename)
2049 struct stat st;
2051 /* allow a dedicated CD-ROM driver to match with a higher priority */
2052 if (strstart(filename, "/dev/cdrom", NULL))
2053 return 50;
2055 if (stat(filename, &st) >= 0 &&
2056 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2057 return 100;
2060 return 0;
2063 static int check_hdev_writable(BDRVRawState *s)
2065 #if defined(BLKROGET)
2066 /* Linux block devices can be configured "read-only" using blockdev(8).
2067 * This is independent of device node permissions and therefore open(2)
2068 * with O_RDWR succeeds. Actual writes fail with EPERM.
2070 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2071 * check for read-only block devices so that Linux block devices behave
2072 * properly.
2074 struct stat st;
2075 int readonly = 0;
2077 if (fstat(s->fd, &st)) {
2078 return -errno;
2081 if (!S_ISBLK(st.st_mode)) {
2082 return 0;
2085 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2086 return -errno;
2089 if (readonly) {
2090 return -EACCES;
2092 #endif /* defined(BLKROGET) */
2093 return 0;
2096 static void hdev_parse_filename(const char *filename, QDict *options,
2097 Error **errp)
2099 /* The prefix is optional, just as for "file". */
2100 strstart(filename, "host_device:", &filename);
2102 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2105 static bool hdev_is_sg(BlockDriverState *bs)
2108 #if defined(__linux__)
2110 struct stat st;
2111 struct sg_scsi_id scsiid;
2112 int sg_version;
2114 if (stat(bs->filename, &st) >= 0 && S_ISCHR(st.st_mode) &&
2115 !bdrv_ioctl(bs, SG_GET_VERSION_NUM, &sg_version) &&
2116 !bdrv_ioctl(bs, SG_GET_SCSI_ID, &scsiid)) {
2117 DPRINTF("SG device found: type=%d, version=%d\n",
2118 scsiid.scsi_type, sg_version);
2119 return true;
2122 #endif
2124 return false;
2127 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2128 Error **errp)
2130 BDRVRawState *s = bs->opaque;
2131 Error *local_err = NULL;
2132 int ret;
2134 #if defined(__APPLE__) && defined(__MACH__)
2135 const char *filename = qdict_get_str(options, "filename");
2137 if (strstart(filename, "/dev/cdrom", NULL)) {
2138 kern_return_t kernResult;
2139 io_iterator_t mediaIterator;
2140 char bsdPath[ MAXPATHLEN ];
2141 int fd;
2143 kernResult = FindEjectableCDMedia( &mediaIterator );
2144 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
2146 if ( bsdPath[ 0 ] != '\0' ) {
2147 strcat(bsdPath,"s0");
2148 /* some CDs don't have a partition 0 */
2149 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
2150 if (fd < 0) {
2151 bsdPath[strlen(bsdPath)-1] = '1';
2152 } else {
2153 qemu_close(fd);
2155 filename = bsdPath;
2156 qdict_put(options, "filename", qstring_from_str(filename));
2159 if ( mediaIterator )
2160 IOObjectRelease( mediaIterator );
2162 #endif
2164 s->type = FTYPE_FILE;
2166 ret = raw_open_common(bs, options, flags, 0, &local_err);
2167 if (ret < 0) {
2168 if (local_err) {
2169 error_propagate(errp, local_err);
2171 return ret;
2174 /* Since this does ioctl the device must be already opened */
2175 bs->sg = hdev_is_sg(bs);
2177 if (flags & BDRV_O_RDWR) {
2178 ret = check_hdev_writable(s);
2179 if (ret < 0) {
2180 raw_close(bs);
2181 error_setg_errno(errp, -ret, "The device is not writable");
2182 return ret;
2186 return ret;
2189 #if defined(__linux__)
2190 /* Note: we do not have a reliable method to detect if the floppy is
2191 present. The current method is to try to open the floppy at every
2192 I/O and to keep it opened during a few hundreds of ms. */
2193 static int fd_open(BlockDriverState *bs)
2195 BDRVRawState *s = bs->opaque;
2196 int last_media_present;
2198 if (s->type != FTYPE_FD)
2199 return 0;
2200 last_media_present = (s->fd >= 0);
2201 if (s->fd >= 0 &&
2202 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
2203 qemu_close(s->fd);
2204 s->fd = -1;
2205 DPRINTF("Floppy closed\n");
2207 if (s->fd < 0) {
2208 if (s->fd_got_error &&
2209 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
2210 DPRINTF("No floppy (open delayed)\n");
2211 return -EIO;
2213 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
2214 if (s->fd < 0) {
2215 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2216 s->fd_got_error = 1;
2217 if (last_media_present)
2218 s->fd_media_changed = 1;
2219 DPRINTF("No floppy\n");
2220 return -EIO;
2222 DPRINTF("Floppy opened\n");
2224 if (!last_media_present)
2225 s->fd_media_changed = 1;
2226 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2227 s->fd_got_error = 0;
2228 return 0;
2231 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2233 BDRVRawState *s = bs->opaque;
2235 return ioctl(s->fd, req, buf);
2238 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2239 unsigned long int req, void *buf,
2240 BlockCompletionFunc *cb, void *opaque)
2242 BDRVRawState *s = bs->opaque;
2243 RawPosixAIOData *acb;
2244 ThreadPool *pool;
2246 if (fd_open(bs) < 0)
2247 return NULL;
2249 acb = g_new(RawPosixAIOData, 1);
2250 acb->bs = bs;
2251 acb->aio_type = QEMU_AIO_IOCTL;
2252 acb->aio_fildes = s->fd;
2253 acb->aio_offset = 0;
2254 acb->aio_ioctl_buf = buf;
2255 acb->aio_ioctl_cmd = req;
2256 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2257 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2260 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2261 static int fd_open(BlockDriverState *bs)
2263 BDRVRawState *s = bs->opaque;
2265 /* this is just to ensure s->fd is sane (its called by io ops) */
2266 if (s->fd >= 0)
2267 return 0;
2268 return -EIO;
2270 #else /* !linux && !FreeBSD */
2272 static int fd_open(BlockDriverState *bs)
2274 return 0;
2277 #endif /* !linux && !FreeBSD */
2279 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2280 int64_t sector_num, int nb_sectors,
2281 BlockCompletionFunc *cb, void *opaque)
2283 BDRVRawState *s = bs->opaque;
2285 if (fd_open(bs) < 0) {
2286 return NULL;
2288 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2289 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2292 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2293 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2295 BDRVRawState *s = bs->opaque;
2296 int rc;
2298 rc = fd_open(bs);
2299 if (rc < 0) {
2300 return rc;
2302 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2303 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2304 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2305 } else if (s->discard_zeroes) {
2306 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2307 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2309 return -ENOTSUP;
2312 static int hdev_create(const char *filename, QemuOpts *opts,
2313 Error **errp)
2315 int fd;
2316 int ret = 0;
2317 struct stat stat_buf;
2318 int64_t total_size = 0;
2319 bool has_prefix;
2321 /* This function is used by all three protocol block drivers and therefore
2322 * any of these three prefixes may be given.
2323 * The return value has to be stored somewhere, otherwise this is an error
2324 * due to -Werror=unused-value. */
2325 has_prefix =
2326 strstart(filename, "host_device:", &filename) ||
2327 strstart(filename, "host_cdrom:" , &filename) ||
2328 strstart(filename, "host_floppy:", &filename);
2330 (void)has_prefix;
2332 ret = raw_normalize_devicepath(&filename);
2333 if (ret < 0) {
2334 error_setg_errno(errp, -ret, "Could not normalize device path");
2335 return ret;
2338 /* Read out options */
2339 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2340 BDRV_SECTOR_SIZE);
2342 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2343 if (fd < 0) {
2344 ret = -errno;
2345 error_setg_errno(errp, -ret, "Could not open device");
2346 return ret;
2349 if (fstat(fd, &stat_buf) < 0) {
2350 ret = -errno;
2351 error_setg_errno(errp, -ret, "Could not stat device");
2352 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2353 error_setg(errp,
2354 "The given file is neither a block nor a character device");
2355 ret = -ENODEV;
2356 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2357 error_setg(errp, "Device is too small");
2358 ret = -ENOSPC;
2361 qemu_close(fd);
2362 return ret;
2365 static BlockDriver bdrv_host_device = {
2366 .format_name = "host_device",
2367 .protocol_name = "host_device",
2368 .instance_size = sizeof(BDRVRawState),
2369 .bdrv_needs_filename = true,
2370 .bdrv_probe_device = hdev_probe_device,
2371 .bdrv_parse_filename = hdev_parse_filename,
2372 .bdrv_file_open = hdev_open,
2373 .bdrv_close = raw_close,
2374 .bdrv_reopen_prepare = raw_reopen_prepare,
2375 .bdrv_reopen_commit = raw_reopen_commit,
2376 .bdrv_reopen_abort = raw_reopen_abort,
2377 .bdrv_create = hdev_create,
2378 .create_opts = &raw_create_opts,
2379 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2381 .bdrv_aio_readv = raw_aio_readv,
2382 .bdrv_aio_writev = raw_aio_writev,
2383 .bdrv_aio_flush = raw_aio_flush,
2384 .bdrv_aio_discard = hdev_aio_discard,
2385 .bdrv_refresh_limits = raw_refresh_limits,
2386 .bdrv_io_plug = raw_aio_plug,
2387 .bdrv_io_unplug = raw_aio_unplug,
2388 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2390 .bdrv_truncate = raw_truncate,
2391 .bdrv_getlength = raw_getlength,
2392 .bdrv_get_info = raw_get_info,
2393 .bdrv_get_allocated_file_size
2394 = raw_get_allocated_file_size,
2395 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2396 .bdrv_probe_geometry = hdev_probe_geometry,
2398 .bdrv_detach_aio_context = raw_detach_aio_context,
2399 .bdrv_attach_aio_context = raw_attach_aio_context,
2401 /* generic scsi device */
2402 #ifdef __linux__
2403 .bdrv_ioctl = hdev_ioctl,
2404 .bdrv_aio_ioctl = hdev_aio_ioctl,
2405 #endif
2408 #ifdef __linux__
2409 static void floppy_parse_filename(const char *filename, QDict *options,
2410 Error **errp)
2412 /* The prefix is optional, just as for "file". */
2413 strstart(filename, "host_floppy:", &filename);
2415 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2418 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2419 Error **errp)
2421 BDRVRawState *s = bs->opaque;
2422 Error *local_err = NULL;
2423 int ret;
2425 s->type = FTYPE_FD;
2427 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2428 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2429 if (ret) {
2430 if (local_err) {
2431 error_propagate(errp, local_err);
2433 return ret;
2436 /* close fd so that we can reopen it as needed */
2437 qemu_close(s->fd);
2438 s->fd = -1;
2439 s->fd_media_changed = 1;
2441 error_report("Host floppy pass-through is deprecated");
2442 error_printf("Support for it will be removed in a future release.\n");
2443 return 0;
2446 static int floppy_probe_device(const char *filename)
2448 int fd, ret;
2449 int prio = 0;
2450 struct floppy_struct fdparam;
2451 struct stat st;
2453 if (strstart(filename, "/dev/fd", NULL) &&
2454 !strstart(filename, "/dev/fdset/", NULL) &&
2455 !strstart(filename, "/dev/fd/", NULL)) {
2456 prio = 50;
2459 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2460 if (fd < 0) {
2461 goto out;
2463 ret = fstat(fd, &st);
2464 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2465 goto outc;
2468 /* Attempt to detect via a floppy specific ioctl */
2469 ret = ioctl(fd, FDGETPRM, &fdparam);
2470 if (ret >= 0)
2471 prio = 100;
2473 outc:
2474 qemu_close(fd);
2475 out:
2476 return prio;
2480 static int floppy_is_inserted(BlockDriverState *bs)
2482 return fd_open(bs) >= 0;
2485 static int floppy_media_changed(BlockDriverState *bs)
2487 BDRVRawState *s = bs->opaque;
2488 int ret;
2491 * XXX: we do not have a true media changed indication.
2492 * It does not work if the floppy is changed without trying to read it.
2494 fd_open(bs);
2495 ret = s->fd_media_changed;
2496 s->fd_media_changed = 0;
2497 DPRINTF("Floppy changed=%d\n", ret);
2498 return ret;
2501 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2503 BDRVRawState *s = bs->opaque;
2504 int fd;
2506 if (s->fd >= 0) {
2507 qemu_close(s->fd);
2508 s->fd = -1;
2510 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2511 if (fd >= 0) {
2512 if (ioctl(fd, FDEJECT, 0) < 0)
2513 perror("FDEJECT");
2514 qemu_close(fd);
2518 static BlockDriver bdrv_host_floppy = {
2519 .format_name = "host_floppy",
2520 .protocol_name = "host_floppy",
2521 .instance_size = sizeof(BDRVRawState),
2522 .bdrv_needs_filename = true,
2523 .bdrv_probe_device = floppy_probe_device,
2524 .bdrv_parse_filename = floppy_parse_filename,
2525 .bdrv_file_open = floppy_open,
2526 .bdrv_close = raw_close,
2527 .bdrv_reopen_prepare = raw_reopen_prepare,
2528 .bdrv_reopen_commit = raw_reopen_commit,
2529 .bdrv_reopen_abort = raw_reopen_abort,
2530 .bdrv_create = hdev_create,
2531 .create_opts = &raw_create_opts,
2533 .bdrv_aio_readv = raw_aio_readv,
2534 .bdrv_aio_writev = raw_aio_writev,
2535 .bdrv_aio_flush = raw_aio_flush,
2536 .bdrv_refresh_limits = raw_refresh_limits,
2537 .bdrv_io_plug = raw_aio_plug,
2538 .bdrv_io_unplug = raw_aio_unplug,
2539 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2541 .bdrv_truncate = raw_truncate,
2542 .bdrv_getlength = raw_getlength,
2543 .has_variable_length = true,
2544 .bdrv_get_allocated_file_size
2545 = raw_get_allocated_file_size,
2547 .bdrv_detach_aio_context = raw_detach_aio_context,
2548 .bdrv_attach_aio_context = raw_attach_aio_context,
2550 /* removable device support */
2551 .bdrv_is_inserted = floppy_is_inserted,
2552 .bdrv_media_changed = floppy_media_changed,
2553 .bdrv_eject = floppy_eject,
2555 #endif
2557 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2558 static void cdrom_parse_filename(const char *filename, QDict *options,
2559 Error **errp)
2561 /* The prefix is optional, just as for "file". */
2562 strstart(filename, "host_cdrom:", &filename);
2564 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2566 #endif
2568 #ifdef __linux__
2569 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2570 Error **errp)
2572 BDRVRawState *s = bs->opaque;
2573 Error *local_err = NULL;
2574 int ret;
2576 s->type = FTYPE_CD;
2578 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2579 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2580 if (local_err) {
2581 error_propagate(errp, local_err);
2583 return ret;
2586 static int cdrom_probe_device(const char *filename)
2588 int fd, ret;
2589 int prio = 0;
2590 struct stat st;
2592 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2593 if (fd < 0) {
2594 goto out;
2596 ret = fstat(fd, &st);
2597 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2598 goto outc;
2601 /* Attempt to detect via a CDROM specific ioctl */
2602 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2603 if (ret >= 0)
2604 prio = 100;
2606 outc:
2607 qemu_close(fd);
2608 out:
2609 return prio;
2612 static int cdrom_is_inserted(BlockDriverState *bs)
2614 BDRVRawState *s = bs->opaque;
2615 int ret;
2617 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2618 if (ret == CDS_DISC_OK)
2619 return 1;
2620 return 0;
2623 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2625 BDRVRawState *s = bs->opaque;
2627 if (eject_flag) {
2628 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2629 perror("CDROMEJECT");
2630 } else {
2631 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2632 perror("CDROMEJECT");
2636 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2638 BDRVRawState *s = bs->opaque;
2640 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2642 * Note: an error can happen if the distribution automatically
2643 * mounts the CD-ROM
2645 /* perror("CDROM_LOCKDOOR"); */
2649 static BlockDriver bdrv_host_cdrom = {
2650 .format_name = "host_cdrom",
2651 .protocol_name = "host_cdrom",
2652 .instance_size = sizeof(BDRVRawState),
2653 .bdrv_needs_filename = true,
2654 .bdrv_probe_device = cdrom_probe_device,
2655 .bdrv_parse_filename = cdrom_parse_filename,
2656 .bdrv_file_open = cdrom_open,
2657 .bdrv_close = raw_close,
2658 .bdrv_reopen_prepare = raw_reopen_prepare,
2659 .bdrv_reopen_commit = raw_reopen_commit,
2660 .bdrv_reopen_abort = raw_reopen_abort,
2661 .bdrv_create = hdev_create,
2662 .create_opts = &raw_create_opts,
2664 .bdrv_aio_readv = raw_aio_readv,
2665 .bdrv_aio_writev = raw_aio_writev,
2666 .bdrv_aio_flush = raw_aio_flush,
2667 .bdrv_refresh_limits = raw_refresh_limits,
2668 .bdrv_io_plug = raw_aio_plug,
2669 .bdrv_io_unplug = raw_aio_unplug,
2670 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2672 .bdrv_truncate = raw_truncate,
2673 .bdrv_getlength = raw_getlength,
2674 .has_variable_length = true,
2675 .bdrv_get_allocated_file_size
2676 = raw_get_allocated_file_size,
2678 .bdrv_detach_aio_context = raw_detach_aio_context,
2679 .bdrv_attach_aio_context = raw_attach_aio_context,
2681 /* removable device support */
2682 .bdrv_is_inserted = cdrom_is_inserted,
2683 .bdrv_eject = cdrom_eject,
2684 .bdrv_lock_medium = cdrom_lock_medium,
2686 /* generic scsi device */
2687 .bdrv_ioctl = hdev_ioctl,
2688 .bdrv_aio_ioctl = hdev_aio_ioctl,
2690 #endif /* __linux__ */
2692 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2693 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2694 Error **errp)
2696 BDRVRawState *s = bs->opaque;
2697 Error *local_err = NULL;
2698 int ret;
2700 s->type = FTYPE_CD;
2702 ret = raw_open_common(bs, options, flags, 0, &local_err);
2703 if (ret) {
2704 if (local_err) {
2705 error_propagate(errp, local_err);
2707 return ret;
2710 /* make sure the door isn't locked at this time */
2711 ioctl(s->fd, CDIOCALLOW);
2712 return 0;
2715 static int cdrom_probe_device(const char *filename)
2717 if (strstart(filename, "/dev/cd", NULL) ||
2718 strstart(filename, "/dev/acd", NULL))
2719 return 100;
2720 return 0;
2723 static int cdrom_reopen(BlockDriverState *bs)
2725 BDRVRawState *s = bs->opaque;
2726 int fd;
2729 * Force reread of possibly changed/newly loaded disc,
2730 * FreeBSD seems to not notice sometimes...
2732 if (s->fd >= 0)
2733 qemu_close(s->fd);
2734 fd = qemu_open(bs->filename, s->open_flags, 0644);
2735 if (fd < 0) {
2736 s->fd = -1;
2737 return -EIO;
2739 s->fd = fd;
2741 /* make sure the door isn't locked at this time */
2742 ioctl(s->fd, CDIOCALLOW);
2743 return 0;
2746 static int cdrom_is_inserted(BlockDriverState *bs)
2748 return raw_getlength(bs) > 0;
2751 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2753 BDRVRawState *s = bs->opaque;
2755 if (s->fd < 0)
2756 return;
2758 (void) ioctl(s->fd, CDIOCALLOW);
2760 if (eject_flag) {
2761 if (ioctl(s->fd, CDIOCEJECT) < 0)
2762 perror("CDIOCEJECT");
2763 } else {
2764 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2765 perror("CDIOCCLOSE");
2768 cdrom_reopen(bs);
2771 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2773 BDRVRawState *s = bs->opaque;
2775 if (s->fd < 0)
2776 return;
2777 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2779 * Note: an error can happen if the distribution automatically
2780 * mounts the CD-ROM
2782 /* perror("CDROM_LOCKDOOR"); */
2786 static BlockDriver bdrv_host_cdrom = {
2787 .format_name = "host_cdrom",
2788 .protocol_name = "host_cdrom",
2789 .instance_size = sizeof(BDRVRawState),
2790 .bdrv_needs_filename = true,
2791 .bdrv_probe_device = cdrom_probe_device,
2792 .bdrv_parse_filename = cdrom_parse_filename,
2793 .bdrv_file_open = cdrom_open,
2794 .bdrv_close = raw_close,
2795 .bdrv_reopen_prepare = raw_reopen_prepare,
2796 .bdrv_reopen_commit = raw_reopen_commit,
2797 .bdrv_reopen_abort = raw_reopen_abort,
2798 .bdrv_create = hdev_create,
2799 .create_opts = &raw_create_opts,
2801 .bdrv_aio_readv = raw_aio_readv,
2802 .bdrv_aio_writev = raw_aio_writev,
2803 .bdrv_aio_flush = raw_aio_flush,
2804 .bdrv_refresh_limits = raw_refresh_limits,
2805 .bdrv_io_plug = raw_aio_plug,
2806 .bdrv_io_unplug = raw_aio_unplug,
2807 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2809 .bdrv_truncate = raw_truncate,
2810 .bdrv_getlength = raw_getlength,
2811 .has_variable_length = true,
2812 .bdrv_get_allocated_file_size
2813 = raw_get_allocated_file_size,
2815 .bdrv_detach_aio_context = raw_detach_aio_context,
2816 .bdrv_attach_aio_context = raw_attach_aio_context,
2818 /* removable device support */
2819 .bdrv_is_inserted = cdrom_is_inserted,
2820 .bdrv_eject = cdrom_eject,
2821 .bdrv_lock_medium = cdrom_lock_medium,
2823 #endif /* __FreeBSD__ */
2825 static void bdrv_file_init(void)
2828 * Register all the drivers. Note that order is important, the driver
2829 * registered last will get probed first.
2831 bdrv_register(&bdrv_file);
2832 bdrv_register(&bdrv_host_device);
2833 #ifdef __linux__
2834 bdrv_register(&bdrv_host_floppy);
2835 bdrv_register(&bdrv_host_cdrom);
2836 #endif
2837 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2838 bdrv_register(&bdrv_host_cdrom);
2839 #endif
2842 block_init(bdrv_file_init);