qemu-char: convert null backend to data-driven creation
[qemu/ar7.git] / block / raw-posix.c
blobcc1b8743ac08bc20ea59a3c71731bf89fadf00f1
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 #endif
524 s->has_discard = true;
525 s->has_write_zeroes = true;
526 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
527 s->needs_alignment = true;
530 if (fstat(s->fd, &st) < 0) {
531 ret = -errno;
532 error_setg_errno(errp, errno, "Could not stat file");
533 goto fail;
535 if (S_ISREG(st.st_mode)) {
536 s->discard_zeroes = true;
537 s->has_fallocate = true;
539 if (S_ISBLK(st.st_mode)) {
540 #ifdef BLKDISCARDZEROES
541 unsigned int arg;
542 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
543 s->discard_zeroes = true;
545 #endif
546 #ifdef __linux__
547 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
548 * not rely on the contents of discarded blocks unless using O_DIRECT.
549 * Same for BLKZEROOUT.
551 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
552 s->discard_zeroes = false;
553 s->has_write_zeroes = false;
555 #endif
557 #ifdef __FreeBSD__
558 if (S_ISCHR(st.st_mode)) {
560 * The file is a char device (disk), which on FreeBSD isn't behind
561 * a pager, so force all requests to be aligned. This is needed
562 * so QEMU makes sure all IO operations on the device are aligned
563 * to sector size, or else FreeBSD will reject them with EINVAL.
565 s->needs_alignment = true;
567 #endif
569 #ifdef CONFIG_XFS
570 if (platform_test_xfs_fd(s->fd)) {
571 s->is_xfs = true;
573 #endif
575 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
577 ret = 0;
578 fail:
579 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
580 unlink(filename);
582 qemu_opts_del(opts);
583 return ret;
586 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
587 Error **errp)
589 BDRVRawState *s = bs->opaque;
590 Error *local_err = NULL;
591 int ret;
593 s->type = FTYPE_FILE;
594 ret = raw_open_common(bs, options, flags, 0, &local_err);
595 if (local_err) {
596 error_propagate(errp, local_err);
598 return ret;
601 static int raw_reopen_prepare(BDRVReopenState *state,
602 BlockReopenQueue *queue, Error **errp)
604 BDRVRawState *s;
605 BDRVRawReopenState *raw_s;
606 int ret = 0;
607 Error *local_err = NULL;
609 assert(state != NULL);
610 assert(state->bs != NULL);
612 s = state->bs->opaque;
614 state->opaque = g_new0(BDRVRawReopenState, 1);
615 raw_s = state->opaque;
617 #ifdef CONFIG_LINUX_AIO
618 raw_s->use_aio = s->use_aio;
620 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
621 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
622 * won't override aio_ctx if aio_ctx is non-NULL */
623 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
624 error_setg(errp, "Could not set AIO state");
625 return -1;
627 #endif
629 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
630 raw_s->open_flags |= O_NONBLOCK;
633 raw_parse_flags(state->flags, &raw_s->open_flags);
635 raw_s->fd = -1;
637 int fcntl_flags = O_APPEND | O_NONBLOCK;
638 #ifdef O_NOATIME
639 fcntl_flags |= O_NOATIME;
640 #endif
642 #ifdef O_ASYNC
643 /* Not all operating systems have O_ASYNC, and those that don't
644 * will not let us track the state into raw_s->open_flags (typically
645 * you achieve the same effect with an ioctl, for example I_SETSIG
646 * on Solaris). But we do not use O_ASYNC, so that's fine.
648 assert((s->open_flags & O_ASYNC) == 0);
649 #endif
651 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
652 /* dup the original fd */
653 /* TODO: use qemu fcntl wrapper */
654 #ifdef F_DUPFD_CLOEXEC
655 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
656 #else
657 raw_s->fd = dup(s->fd);
658 if (raw_s->fd != -1) {
659 qemu_set_cloexec(raw_s->fd);
661 #endif
662 if (raw_s->fd >= 0) {
663 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
664 if (ret) {
665 qemu_close(raw_s->fd);
666 raw_s->fd = -1;
671 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
672 if (raw_s->fd == -1) {
673 const char *normalized_filename = state->bs->filename;
674 ret = raw_normalize_devicepath(&normalized_filename);
675 if (ret < 0) {
676 error_setg_errno(errp, -ret, "Could not normalize device path");
677 } else {
678 assert(!(raw_s->open_flags & O_CREAT));
679 raw_s->fd = qemu_open(normalized_filename, raw_s->open_flags);
680 if (raw_s->fd == -1) {
681 error_setg_errno(errp, errno, "Could not reopen file");
682 ret = -1;
687 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
688 * alignment with the new fd. */
689 if (raw_s->fd != -1) {
690 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
691 if (local_err) {
692 qemu_close(raw_s->fd);
693 raw_s->fd = -1;
694 error_propagate(errp, local_err);
695 ret = -EINVAL;
699 return ret;
702 static void raw_reopen_commit(BDRVReopenState *state)
704 BDRVRawReopenState *raw_s = state->opaque;
705 BDRVRawState *s = state->bs->opaque;
707 s->open_flags = raw_s->open_flags;
709 qemu_close(s->fd);
710 s->fd = raw_s->fd;
711 #ifdef CONFIG_LINUX_AIO
712 s->use_aio = raw_s->use_aio;
713 #endif
715 g_free(state->opaque);
716 state->opaque = NULL;
720 static void raw_reopen_abort(BDRVReopenState *state)
722 BDRVRawReopenState *raw_s = state->opaque;
724 /* nothing to do if NULL, we didn't get far enough */
725 if (raw_s == NULL) {
726 return;
729 if (raw_s->fd >= 0) {
730 qemu_close(raw_s->fd);
731 raw_s->fd = -1;
733 g_free(state->opaque);
734 state->opaque = NULL;
737 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
739 BDRVRawState *s = bs->opaque;
741 raw_probe_alignment(bs, s->fd, errp);
742 bs->bl.min_mem_alignment = s->buf_align;
743 bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
746 static int check_for_dasd(int fd)
748 #ifdef BIODASDINFO2
749 struct dasd_information2_t info = {0};
751 return ioctl(fd, BIODASDINFO2, &info);
752 #else
753 return -1;
754 #endif
758 * Try to get @bs's logical and physical block size.
759 * On success, store them in @bsz and return zero.
760 * On failure, return negative errno.
762 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
764 BDRVRawState *s = bs->opaque;
765 int ret;
767 /* If DASD, get blocksizes */
768 if (check_for_dasd(s->fd) < 0) {
769 return -ENOTSUP;
771 ret = probe_logical_blocksize(s->fd, &bsz->log);
772 if (ret < 0) {
773 return ret;
775 return probe_physical_blocksize(s->fd, &bsz->phys);
779 * Try to get @bs's geometry: cyls, heads, sectors.
780 * On success, store them in @geo and return 0.
781 * On failure return -errno.
782 * (Allows block driver to assign default geometry values that guest sees)
784 #ifdef __linux__
785 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
787 BDRVRawState *s = bs->opaque;
788 struct hd_geometry ioctl_geo = {0};
789 uint32_t blksize;
791 /* If DASD, get its geometry */
792 if (check_for_dasd(s->fd) < 0) {
793 return -ENOTSUP;
795 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
796 return -errno;
798 /* HDIO_GETGEO may return success even though geo contains zeros
799 (e.g. certain multipath setups) */
800 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
801 return -ENOTSUP;
803 /* Do not return a geometry for partition */
804 if (ioctl_geo.start != 0) {
805 return -ENOTSUP;
807 geo->heads = ioctl_geo.heads;
808 geo->sectors = ioctl_geo.sectors;
809 if (!probe_physical_blocksize(s->fd, &blksize)) {
810 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
811 geo->cylinders = bdrv_nb_sectors(bs) / (blksize / BDRV_SECTOR_SIZE)
812 / (geo->heads * geo->sectors);
813 return 0;
815 geo->cylinders = ioctl_geo.cylinders;
817 return 0;
819 #else /* __linux__ */
820 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
822 return -ENOTSUP;
824 #endif
826 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
828 int ret;
830 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
831 if (ret == -1) {
832 return -errno;
835 return 0;
838 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
840 int ret;
842 ret = qemu_fdatasync(aiocb->aio_fildes);
843 if (ret == -1) {
844 return -errno;
846 return 0;
849 #ifdef CONFIG_PREADV
851 static bool preadv_present = true;
853 static ssize_t
854 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
856 return preadv(fd, iov, nr_iov, offset);
859 static ssize_t
860 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
862 return pwritev(fd, iov, nr_iov, offset);
865 #else
867 static bool preadv_present = false;
869 static ssize_t
870 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
872 return -ENOSYS;
875 static ssize_t
876 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
878 return -ENOSYS;
881 #endif
883 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
885 ssize_t len;
887 do {
888 if (aiocb->aio_type & QEMU_AIO_WRITE)
889 len = qemu_pwritev(aiocb->aio_fildes,
890 aiocb->aio_iov,
891 aiocb->aio_niov,
892 aiocb->aio_offset);
893 else
894 len = qemu_preadv(aiocb->aio_fildes,
895 aiocb->aio_iov,
896 aiocb->aio_niov,
897 aiocb->aio_offset);
898 } while (len == -1 && errno == EINTR);
900 if (len == -1) {
901 return -errno;
903 return len;
907 * Read/writes the data to/from a given linear buffer.
909 * Returns the number of bytes handles or -errno in case of an error. Short
910 * reads are only returned if the end of the file is reached.
912 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
914 ssize_t offset = 0;
915 ssize_t len;
917 while (offset < aiocb->aio_nbytes) {
918 if (aiocb->aio_type & QEMU_AIO_WRITE) {
919 len = pwrite(aiocb->aio_fildes,
920 (const char *)buf + offset,
921 aiocb->aio_nbytes - offset,
922 aiocb->aio_offset + offset);
923 } else {
924 len = pread(aiocb->aio_fildes,
925 buf + offset,
926 aiocb->aio_nbytes - offset,
927 aiocb->aio_offset + offset);
929 if (len == -1 && errno == EINTR) {
930 continue;
931 } else if (len == -1 && errno == EINVAL &&
932 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
933 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
934 offset > 0) {
935 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
936 * after a short read. Assume that O_DIRECT short reads only occur
937 * at EOF. Therefore this is a short read, not an I/O error.
939 break;
940 } else if (len == -1) {
941 offset = -errno;
942 break;
943 } else if (len == 0) {
944 break;
946 offset += len;
949 return offset;
952 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
954 ssize_t nbytes;
955 char *buf;
957 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
959 * If there is just a single buffer, and it is properly aligned
960 * we can just use plain pread/pwrite without any problems.
962 if (aiocb->aio_niov == 1) {
963 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
966 * We have more than one iovec, and all are properly aligned.
968 * Try preadv/pwritev first and fall back to linearizing the
969 * buffer if it's not supported.
971 if (preadv_present) {
972 nbytes = handle_aiocb_rw_vector(aiocb);
973 if (nbytes == aiocb->aio_nbytes ||
974 (nbytes < 0 && nbytes != -ENOSYS)) {
975 return nbytes;
977 preadv_present = false;
981 * XXX(hch): short read/write. no easy way to handle the reminder
982 * using these interfaces. For now retry using plain
983 * pread/pwrite?
988 * Ok, we have to do it the hard way, copy all segments into
989 * a single aligned buffer.
991 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
992 if (buf == NULL) {
993 return -ENOMEM;
996 if (aiocb->aio_type & QEMU_AIO_WRITE) {
997 char *p = buf;
998 int i;
1000 for (i = 0; i < aiocb->aio_niov; ++i) {
1001 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1002 p += aiocb->aio_iov[i].iov_len;
1004 assert(p - buf == aiocb->aio_nbytes);
1007 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1008 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1009 char *p = buf;
1010 size_t count = aiocb->aio_nbytes, copy;
1011 int i;
1013 for (i = 0; i < aiocb->aio_niov && count; ++i) {
1014 copy = count;
1015 if (copy > aiocb->aio_iov[i].iov_len) {
1016 copy = aiocb->aio_iov[i].iov_len;
1018 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1019 assert(count >= copy);
1020 p += copy;
1021 count -= copy;
1023 assert(count == 0);
1025 qemu_vfree(buf);
1027 return nbytes;
1030 #ifdef CONFIG_XFS
1031 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1033 struct xfs_flock64 fl;
1034 int err;
1036 memset(&fl, 0, sizeof(fl));
1037 fl.l_whence = SEEK_SET;
1038 fl.l_start = offset;
1039 fl.l_len = bytes;
1041 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1042 err = errno;
1043 DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1044 return -err;
1047 return 0;
1050 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1052 struct xfs_flock64 fl;
1053 int err;
1055 memset(&fl, 0, sizeof(fl));
1056 fl.l_whence = SEEK_SET;
1057 fl.l_start = offset;
1058 fl.l_len = bytes;
1060 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1061 err = errno;
1062 DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1063 return -err;
1066 return 0;
1068 #endif
1070 static int translate_err(int err)
1072 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1073 err == -ENOTTY) {
1074 err = -ENOTSUP;
1076 return err;
1079 #ifdef CONFIG_FALLOCATE
1080 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1082 do {
1083 if (fallocate(fd, mode, offset, len) == 0) {
1084 return 0;
1086 } while (errno == EINTR);
1087 return translate_err(-errno);
1089 #endif
1091 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1093 int ret = -ENOTSUP;
1094 BDRVRawState *s = aiocb->bs->opaque;
1096 if (!s->has_write_zeroes) {
1097 return -ENOTSUP;
1100 #ifdef BLKZEROOUT
1101 do {
1102 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1103 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1104 return 0;
1106 } while (errno == EINTR);
1108 ret = translate_err(-errno);
1109 #endif
1111 if (ret == -ENOTSUP) {
1112 s->has_write_zeroes = false;
1114 return ret;
1117 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1119 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1120 BDRVRawState *s = aiocb->bs->opaque;
1121 #endif
1123 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1124 return handle_aiocb_write_zeroes_block(aiocb);
1127 #ifdef CONFIG_XFS
1128 if (s->is_xfs) {
1129 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1131 #endif
1133 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1134 if (s->has_write_zeroes) {
1135 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1136 aiocb->aio_offset, aiocb->aio_nbytes);
1137 if (ret == 0 || ret != -ENOTSUP) {
1138 return ret;
1140 s->has_write_zeroes = false;
1142 #endif
1144 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1145 if (s->has_discard && s->has_fallocate) {
1146 int ret = do_fallocate(s->fd,
1147 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1148 aiocb->aio_offset, aiocb->aio_nbytes);
1149 if (ret == 0) {
1150 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1151 if (ret == 0 || ret != -ENOTSUP) {
1152 return ret;
1154 s->has_fallocate = false;
1155 } else if (ret != -ENOTSUP) {
1156 return ret;
1157 } else {
1158 s->has_discard = false;
1161 #endif
1163 #ifdef CONFIG_FALLOCATE
1164 if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1165 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1166 if (ret == 0 || ret != -ENOTSUP) {
1167 return ret;
1169 s->has_fallocate = false;
1171 #endif
1173 return -ENOTSUP;
1176 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1178 int ret = -EOPNOTSUPP;
1179 BDRVRawState *s = aiocb->bs->opaque;
1181 if (!s->has_discard) {
1182 return -ENOTSUP;
1185 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1186 #ifdef BLKDISCARD
1187 do {
1188 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1189 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1190 return 0;
1192 } while (errno == EINTR);
1194 ret = -errno;
1195 #endif
1196 } else {
1197 #ifdef CONFIG_XFS
1198 if (s->is_xfs) {
1199 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1201 #endif
1203 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1204 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1205 aiocb->aio_offset, aiocb->aio_nbytes);
1206 #endif
1209 ret = translate_err(ret);
1210 if (ret == -ENOTSUP) {
1211 s->has_discard = false;
1213 return ret;
1216 static int aio_worker(void *arg)
1218 RawPosixAIOData *aiocb = arg;
1219 ssize_t ret = 0;
1221 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1222 case QEMU_AIO_READ:
1223 ret = handle_aiocb_rw(aiocb);
1224 if (ret >= 0 && ret < aiocb->aio_nbytes) {
1225 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1226 0, aiocb->aio_nbytes - ret);
1228 ret = aiocb->aio_nbytes;
1230 if (ret == aiocb->aio_nbytes) {
1231 ret = 0;
1232 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1233 ret = -EINVAL;
1235 break;
1236 case QEMU_AIO_WRITE:
1237 ret = handle_aiocb_rw(aiocb);
1238 if (ret == aiocb->aio_nbytes) {
1239 ret = 0;
1240 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1241 ret = -EINVAL;
1243 break;
1244 case QEMU_AIO_FLUSH:
1245 ret = handle_aiocb_flush(aiocb);
1246 break;
1247 case QEMU_AIO_IOCTL:
1248 ret = handle_aiocb_ioctl(aiocb);
1249 break;
1250 case QEMU_AIO_DISCARD:
1251 ret = handle_aiocb_discard(aiocb);
1252 break;
1253 case QEMU_AIO_WRITE_ZEROES:
1254 ret = handle_aiocb_write_zeroes(aiocb);
1255 break;
1256 default:
1257 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1258 ret = -EINVAL;
1259 break;
1262 g_free(aiocb);
1263 return ret;
1266 static int paio_submit_co(BlockDriverState *bs, int fd,
1267 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1268 int type)
1270 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1271 ThreadPool *pool;
1273 acb->bs = bs;
1274 acb->aio_type = type;
1275 acb->aio_fildes = fd;
1277 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1278 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1280 if (qiov) {
1281 acb->aio_iov = qiov->iov;
1282 acb->aio_niov = qiov->niov;
1283 assert(qiov->size == acb->aio_nbytes);
1286 trace_paio_submit_co(sector_num, nb_sectors, type);
1287 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1288 return thread_pool_submit_co(pool, aio_worker, acb);
1291 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1292 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1293 BlockCompletionFunc *cb, void *opaque, int type)
1295 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1296 ThreadPool *pool;
1298 acb->bs = bs;
1299 acb->aio_type = type;
1300 acb->aio_fildes = fd;
1302 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1303 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1305 if (qiov) {
1306 acb->aio_iov = qiov->iov;
1307 acb->aio_niov = qiov->niov;
1308 assert(qiov->size == acb->aio_nbytes);
1311 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1312 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1313 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1316 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1317 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1318 BlockCompletionFunc *cb, void *opaque, int type)
1320 BDRVRawState *s = bs->opaque;
1322 if (fd_open(bs) < 0)
1323 return NULL;
1326 * Check if the underlying device requires requests to be aligned,
1327 * and if the request we are trying to submit is aligned or not.
1328 * If this is the case tell the low-level driver that it needs
1329 * to copy the buffer.
1331 if (s->needs_alignment) {
1332 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1333 type |= QEMU_AIO_MISALIGNED;
1334 #ifdef CONFIG_LINUX_AIO
1335 } else if (s->use_aio) {
1336 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1337 nb_sectors, cb, opaque, type);
1338 #endif
1342 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1343 cb, opaque, type);
1346 static void raw_aio_plug(BlockDriverState *bs)
1348 #ifdef CONFIG_LINUX_AIO
1349 BDRVRawState *s = bs->opaque;
1350 if (s->use_aio) {
1351 laio_io_plug(bs, s->aio_ctx);
1353 #endif
1356 static void raw_aio_unplug(BlockDriverState *bs)
1358 #ifdef CONFIG_LINUX_AIO
1359 BDRVRawState *s = bs->opaque;
1360 if (s->use_aio) {
1361 laio_io_unplug(bs, s->aio_ctx, true);
1363 #endif
1366 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1368 #ifdef CONFIG_LINUX_AIO
1369 BDRVRawState *s = bs->opaque;
1370 if (s->use_aio) {
1371 laio_io_unplug(bs, s->aio_ctx, false);
1373 #endif
1376 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1377 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1378 BlockCompletionFunc *cb, void *opaque)
1380 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1381 cb, opaque, QEMU_AIO_READ);
1384 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1385 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1386 BlockCompletionFunc *cb, void *opaque)
1388 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1389 cb, opaque, QEMU_AIO_WRITE);
1392 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1393 BlockCompletionFunc *cb, void *opaque)
1395 BDRVRawState *s = bs->opaque;
1397 if (fd_open(bs) < 0)
1398 return NULL;
1400 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1403 static void raw_close(BlockDriverState *bs)
1405 BDRVRawState *s = bs->opaque;
1407 raw_detach_aio_context(bs);
1409 #ifdef CONFIG_LINUX_AIO
1410 if (s->use_aio) {
1411 laio_cleanup(s->aio_ctx);
1413 #endif
1414 if (s->fd >= 0) {
1415 qemu_close(s->fd);
1416 s->fd = -1;
1420 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1422 BDRVRawState *s = bs->opaque;
1423 struct stat st;
1425 if (fstat(s->fd, &st)) {
1426 return -errno;
1429 if (S_ISREG(st.st_mode)) {
1430 if (ftruncate(s->fd, offset) < 0) {
1431 return -errno;
1433 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1434 if (offset > raw_getlength(bs)) {
1435 return -EINVAL;
1437 } else {
1438 return -ENOTSUP;
1441 return 0;
1444 #ifdef __OpenBSD__
1445 static int64_t raw_getlength(BlockDriverState *bs)
1447 BDRVRawState *s = bs->opaque;
1448 int fd = s->fd;
1449 struct stat st;
1451 if (fstat(fd, &st))
1452 return -errno;
1453 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1454 struct disklabel dl;
1456 if (ioctl(fd, DIOCGDINFO, &dl))
1457 return -errno;
1458 return (uint64_t)dl.d_secsize *
1459 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1460 } else
1461 return st.st_size;
1463 #elif defined(__NetBSD__)
1464 static int64_t raw_getlength(BlockDriverState *bs)
1466 BDRVRawState *s = bs->opaque;
1467 int fd = s->fd;
1468 struct stat st;
1470 if (fstat(fd, &st))
1471 return -errno;
1472 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1473 struct dkwedge_info dkw;
1475 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1476 return dkw.dkw_size * 512;
1477 } else {
1478 struct disklabel dl;
1480 if (ioctl(fd, DIOCGDINFO, &dl))
1481 return -errno;
1482 return (uint64_t)dl.d_secsize *
1483 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1485 } else
1486 return st.st_size;
1488 #elif defined(__sun__)
1489 static int64_t raw_getlength(BlockDriverState *bs)
1491 BDRVRawState *s = bs->opaque;
1492 struct dk_minfo minfo;
1493 int ret;
1494 int64_t size;
1496 ret = fd_open(bs);
1497 if (ret < 0) {
1498 return ret;
1502 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1504 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1505 if (ret != -1) {
1506 return minfo.dki_lbsize * minfo.dki_capacity;
1510 * There are reports that lseek on some devices fails, but
1511 * irc discussion said that contingency on contingency was overkill.
1513 size = lseek(s->fd, 0, SEEK_END);
1514 if (size < 0) {
1515 return -errno;
1517 return size;
1519 #elif defined(CONFIG_BSD)
1520 static int64_t raw_getlength(BlockDriverState *bs)
1522 BDRVRawState *s = bs->opaque;
1523 int fd = s->fd;
1524 int64_t size;
1525 struct stat sb;
1526 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1527 int reopened = 0;
1528 #endif
1529 int ret;
1531 ret = fd_open(bs);
1532 if (ret < 0)
1533 return ret;
1535 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1536 again:
1537 #endif
1538 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1539 #ifdef DIOCGMEDIASIZE
1540 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1541 #elif defined(DIOCGPART)
1543 struct partinfo pi;
1544 if (ioctl(fd, DIOCGPART, &pi) == 0)
1545 size = pi.media_size;
1546 else
1547 size = 0;
1549 if (size == 0)
1550 #endif
1551 #if defined(__APPLE__) && defined(__MACH__)
1553 uint64_t sectors = 0;
1554 uint32_t sector_size = 0;
1556 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1557 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1558 size = sectors * sector_size;
1559 } else {
1560 size = lseek(fd, 0LL, SEEK_END);
1561 if (size < 0) {
1562 return -errno;
1566 #else
1567 size = lseek(fd, 0LL, SEEK_END);
1568 if (size < 0) {
1569 return -errno;
1571 #endif
1572 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1573 switch(s->type) {
1574 case FTYPE_CD:
1575 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1576 if (size == 2048LL * (unsigned)-1)
1577 size = 0;
1578 /* XXX no disc? maybe we need to reopen... */
1579 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1580 reopened = 1;
1581 goto again;
1584 #endif
1585 } else {
1586 size = lseek(fd, 0, SEEK_END);
1587 if (size < 0) {
1588 return -errno;
1591 return size;
1593 #else
1594 static int64_t raw_getlength(BlockDriverState *bs)
1596 BDRVRawState *s = bs->opaque;
1597 int ret;
1598 int64_t size;
1600 ret = fd_open(bs);
1601 if (ret < 0) {
1602 return ret;
1605 size = lseek(s->fd, 0, SEEK_END);
1606 if (size < 0) {
1607 return -errno;
1609 return size;
1611 #endif
1613 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1615 struct stat st;
1616 BDRVRawState *s = bs->opaque;
1618 if (fstat(s->fd, &st) < 0) {
1619 return -errno;
1621 return (int64_t)st.st_blocks * 512;
1624 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1626 int fd;
1627 int result = 0;
1628 int64_t total_size = 0;
1629 bool nocow = false;
1630 PreallocMode prealloc;
1631 char *buf = NULL;
1632 Error *local_err = NULL;
1634 strstart(filename, "file:", &filename);
1636 /* Read out options */
1637 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1638 BDRV_SECTOR_SIZE);
1639 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1640 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1641 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1642 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1643 &local_err);
1644 g_free(buf);
1645 if (local_err) {
1646 error_propagate(errp, local_err);
1647 result = -EINVAL;
1648 goto out;
1651 fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
1652 0644);
1653 if (fd < 0) {
1654 result = -errno;
1655 error_setg_errno(errp, -result, "Could not create file");
1656 goto out;
1659 if (nocow) {
1660 #ifdef __linux__
1661 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1662 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1663 * will be ignored since any failure of this operation should not
1664 * block the left work.
1666 int attr;
1667 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1668 attr |= FS_NOCOW_FL;
1669 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1671 #endif
1674 if (ftruncate(fd, total_size) != 0) {
1675 result = -errno;
1676 error_setg_errno(errp, -result, "Could not resize file");
1677 goto out_close;
1680 switch (prealloc) {
1681 #ifdef CONFIG_POSIX_FALLOCATE
1682 case PREALLOC_MODE_FALLOC:
1683 /* posix_fallocate() doesn't set errno. */
1684 result = -posix_fallocate(fd, 0, total_size);
1685 if (result != 0) {
1686 error_setg_errno(errp, -result,
1687 "Could not preallocate data for the new file");
1689 break;
1690 #endif
1691 case PREALLOC_MODE_FULL:
1693 int64_t num = 0, left = total_size;
1694 buf = g_malloc0(65536);
1696 while (left > 0) {
1697 num = MIN(left, 65536);
1698 result = write(fd, buf, num);
1699 if (result < 0) {
1700 result = -errno;
1701 error_setg_errno(errp, -result,
1702 "Could not write to the new file");
1703 break;
1705 left -= result;
1707 if (result >= 0) {
1708 result = fsync(fd);
1709 if (result < 0) {
1710 result = -errno;
1711 error_setg_errno(errp, -result,
1712 "Could not flush new file to disk");
1715 g_free(buf);
1716 break;
1718 case PREALLOC_MODE_OFF:
1719 break;
1720 default:
1721 result = -EINVAL;
1722 error_setg(errp, "Unsupported preallocation mode: %s",
1723 PreallocMode_lookup[prealloc]);
1724 break;
1727 out_close:
1728 if (qemu_close(fd) != 0 && result == 0) {
1729 result = -errno;
1730 error_setg_errno(errp, -result, "Could not close the new file");
1732 out:
1733 return result;
1737 * Find allocation range in @bs around offset @start.
1738 * May change underlying file descriptor's file offset.
1739 * If @start is not in a hole, store @start in @data, and the
1740 * beginning of the next hole in @hole, and return 0.
1741 * If @start is in a non-trailing hole, store @start in @hole and the
1742 * beginning of the next non-hole in @data, and return 0.
1743 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1744 * If we can't find out, return a negative errno other than -ENXIO.
1746 static int find_allocation(BlockDriverState *bs, off_t start,
1747 off_t *data, off_t *hole)
1749 #if defined SEEK_HOLE && defined SEEK_DATA
1750 BDRVRawState *s = bs->opaque;
1751 off_t offs;
1754 * SEEK_DATA cases:
1755 * D1. offs == start: start is in data
1756 * D2. offs > start: start is in a hole, next data at offs
1757 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1758 * or start is beyond EOF
1759 * If the latter happens, the file has been truncated behind
1760 * our back since we opened it. All bets are off then.
1761 * Treating like a trailing hole is simplest.
1762 * D4. offs < 0, errno != ENXIO: we learned nothing
1764 offs = lseek(s->fd, start, SEEK_DATA);
1765 if (offs < 0) {
1766 return -errno; /* D3 or D4 */
1768 assert(offs >= start);
1770 if (offs > start) {
1771 /* D2: in hole, next data at offs */
1772 *hole = start;
1773 *data = offs;
1774 return 0;
1777 /* D1: in data, end not yet known */
1780 * SEEK_HOLE cases:
1781 * H1. offs == start: start is in a hole
1782 * If this happens here, a hole has been dug behind our back
1783 * since the previous lseek().
1784 * H2. offs > start: either start is in data, next hole at offs,
1785 * or start is in trailing hole, EOF at offs
1786 * Linux treats trailing holes like any other hole: offs ==
1787 * start. Solaris seeks to EOF instead: offs > start (blech).
1788 * If that happens here, a hole has been dug behind our back
1789 * since the previous lseek().
1790 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1791 * If this happens, the file has been truncated behind our
1792 * back since we opened it. Treat it like a trailing hole.
1793 * H4. offs < 0, errno != ENXIO: we learned nothing
1794 * Pretend we know nothing at all, i.e. "forget" about D1.
1796 offs = lseek(s->fd, start, SEEK_HOLE);
1797 if (offs < 0) {
1798 return -errno; /* D1 and (H3 or H4) */
1800 assert(offs >= start);
1802 if (offs > start) {
1804 * D1 and H2: either in data, next hole at offs, or it was in
1805 * data but is now in a trailing hole. In the latter case,
1806 * all bets are off. Treating it as if it there was data all
1807 * the way to EOF is safe, so simply do that.
1809 *data = start;
1810 *hole = offs;
1811 return 0;
1814 /* D1 and H1 */
1815 return -EBUSY;
1816 #else
1817 return -ENOTSUP;
1818 #endif
1822 * Returns the allocation status of the specified sectors.
1824 * If 'sector_num' is beyond the end of the disk image the return value is 0
1825 * and 'pnum' is set to 0.
1827 * 'pnum' is set to the number of sectors (including and immediately following
1828 * the specified sector) that are known to be in the same
1829 * allocated/unallocated state.
1831 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1832 * beyond the end of the disk image it will be clamped.
1834 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1835 int64_t sector_num,
1836 int nb_sectors, int *pnum)
1838 off_t start, data = 0, hole = 0;
1839 int64_t total_size;
1840 int ret;
1842 ret = fd_open(bs);
1843 if (ret < 0) {
1844 return ret;
1847 start = sector_num * BDRV_SECTOR_SIZE;
1848 total_size = bdrv_getlength(bs);
1849 if (total_size < 0) {
1850 return total_size;
1851 } else if (start >= total_size) {
1852 *pnum = 0;
1853 return 0;
1854 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1855 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1858 ret = find_allocation(bs, start, &data, &hole);
1859 if (ret == -ENXIO) {
1860 /* Trailing hole */
1861 *pnum = nb_sectors;
1862 ret = BDRV_BLOCK_ZERO;
1863 } else if (ret < 0) {
1864 /* No info available, so pretend there are no holes */
1865 *pnum = nb_sectors;
1866 ret = BDRV_BLOCK_DATA;
1867 } else if (data == start) {
1868 /* On a data extent, compute sectors to the end of the extent,
1869 * possibly including a partial sector at EOF. */
1870 *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
1871 ret = BDRV_BLOCK_DATA;
1872 } else {
1873 /* On a hole, compute sectors to the beginning of the next extent. */
1874 assert(hole == start);
1875 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1876 ret = BDRV_BLOCK_ZERO;
1878 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1881 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1882 int64_t sector_num, int nb_sectors,
1883 BlockCompletionFunc *cb, void *opaque)
1885 BDRVRawState *s = bs->opaque;
1887 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1888 cb, opaque, QEMU_AIO_DISCARD);
1891 static int coroutine_fn raw_co_write_zeroes(
1892 BlockDriverState *bs, int64_t sector_num,
1893 int nb_sectors, BdrvRequestFlags flags)
1895 BDRVRawState *s = bs->opaque;
1897 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1898 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1899 QEMU_AIO_WRITE_ZEROES);
1900 } else if (s->discard_zeroes) {
1901 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1902 QEMU_AIO_DISCARD);
1904 return -ENOTSUP;
1907 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1909 BDRVRawState *s = bs->opaque;
1911 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1912 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1913 return 0;
1916 static QemuOptsList raw_create_opts = {
1917 .name = "raw-create-opts",
1918 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1919 .desc = {
1921 .name = BLOCK_OPT_SIZE,
1922 .type = QEMU_OPT_SIZE,
1923 .help = "Virtual disk size"
1926 .name = BLOCK_OPT_NOCOW,
1927 .type = QEMU_OPT_BOOL,
1928 .help = "Turn off copy-on-write (valid only on btrfs)"
1931 .name = BLOCK_OPT_PREALLOC,
1932 .type = QEMU_OPT_STRING,
1933 .help = "Preallocation mode (allowed values: off, falloc, full)"
1935 { /* end of list */ }
1939 BlockDriver bdrv_file = {
1940 .format_name = "file",
1941 .protocol_name = "file",
1942 .instance_size = sizeof(BDRVRawState),
1943 .bdrv_needs_filename = true,
1944 .bdrv_probe = NULL, /* no probe for protocols */
1945 .bdrv_parse_filename = raw_parse_filename,
1946 .bdrv_file_open = raw_open,
1947 .bdrv_reopen_prepare = raw_reopen_prepare,
1948 .bdrv_reopen_commit = raw_reopen_commit,
1949 .bdrv_reopen_abort = raw_reopen_abort,
1950 .bdrv_close = raw_close,
1951 .bdrv_create = raw_create,
1952 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1953 .bdrv_co_get_block_status = raw_co_get_block_status,
1954 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1956 .bdrv_aio_readv = raw_aio_readv,
1957 .bdrv_aio_writev = raw_aio_writev,
1958 .bdrv_aio_flush = raw_aio_flush,
1959 .bdrv_aio_discard = raw_aio_discard,
1960 .bdrv_refresh_limits = raw_refresh_limits,
1961 .bdrv_io_plug = raw_aio_plug,
1962 .bdrv_io_unplug = raw_aio_unplug,
1963 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1965 .bdrv_truncate = raw_truncate,
1966 .bdrv_getlength = raw_getlength,
1967 .bdrv_get_info = raw_get_info,
1968 .bdrv_get_allocated_file_size
1969 = raw_get_allocated_file_size,
1971 .bdrv_detach_aio_context = raw_detach_aio_context,
1972 .bdrv_attach_aio_context = raw_attach_aio_context,
1974 .create_opts = &raw_create_opts,
1977 /***********************************************/
1978 /* host device */
1980 #if defined(__APPLE__) && defined(__MACH__)
1981 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1982 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1984 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1986 kern_return_t kernResult;
1987 mach_port_t masterPort;
1988 CFMutableDictionaryRef classesToMatch;
1990 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1991 if ( KERN_SUCCESS != kernResult ) {
1992 printf( "IOMasterPort returned %d\n", kernResult );
1995 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1996 if ( classesToMatch == NULL ) {
1997 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1998 } else {
1999 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
2001 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
2002 if ( KERN_SUCCESS != kernResult )
2004 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
2007 return kernResult;
2010 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
2012 io_object_t nextMedia;
2013 kern_return_t kernResult = KERN_FAILURE;
2014 *bsdPath = '\0';
2015 nextMedia = IOIteratorNext( mediaIterator );
2016 if ( nextMedia )
2018 CFTypeRef bsdPathAsCFString;
2019 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2020 if ( bsdPathAsCFString ) {
2021 size_t devPathLength;
2022 strcpy( bsdPath, _PATH_DEV );
2023 strcat( bsdPath, "r" );
2024 devPathLength = strlen( bsdPath );
2025 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2026 kernResult = KERN_SUCCESS;
2028 CFRelease( bsdPathAsCFString );
2030 IOObjectRelease( nextMedia );
2033 return kernResult;
2036 #endif
2038 static int hdev_probe_device(const char *filename)
2040 struct stat st;
2042 /* allow a dedicated CD-ROM driver to match with a higher priority */
2043 if (strstart(filename, "/dev/cdrom", NULL))
2044 return 50;
2046 if (stat(filename, &st) >= 0 &&
2047 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2048 return 100;
2051 return 0;
2054 static int check_hdev_writable(BDRVRawState *s)
2056 #if defined(BLKROGET)
2057 /* Linux block devices can be configured "read-only" using blockdev(8).
2058 * This is independent of device node permissions and therefore open(2)
2059 * with O_RDWR succeeds. Actual writes fail with EPERM.
2061 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2062 * check for read-only block devices so that Linux block devices behave
2063 * properly.
2065 struct stat st;
2066 int readonly = 0;
2068 if (fstat(s->fd, &st)) {
2069 return -errno;
2072 if (!S_ISBLK(st.st_mode)) {
2073 return 0;
2076 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2077 return -errno;
2080 if (readonly) {
2081 return -EACCES;
2083 #endif /* defined(BLKROGET) */
2084 return 0;
2087 static void hdev_parse_filename(const char *filename, QDict *options,
2088 Error **errp)
2090 /* The prefix is optional, just as for "file". */
2091 strstart(filename, "host_device:", &filename);
2093 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2096 static bool hdev_is_sg(BlockDriverState *bs)
2099 #if defined(__linux__)
2101 struct stat st;
2102 struct sg_scsi_id scsiid;
2103 int sg_version;
2105 if (stat(bs->filename, &st) >= 0 && S_ISCHR(st.st_mode) &&
2106 !bdrv_ioctl(bs, SG_GET_VERSION_NUM, &sg_version) &&
2107 !bdrv_ioctl(bs, SG_GET_SCSI_ID, &scsiid)) {
2108 DPRINTF("SG device found: type=%d, version=%d\n",
2109 scsiid.scsi_type, sg_version);
2110 return true;
2113 #endif
2115 return false;
2118 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2119 Error **errp)
2121 BDRVRawState *s = bs->opaque;
2122 Error *local_err = NULL;
2123 int ret;
2125 #if defined(__APPLE__) && defined(__MACH__)
2126 const char *filename = qdict_get_str(options, "filename");
2128 if (strstart(filename, "/dev/cdrom", NULL)) {
2129 kern_return_t kernResult;
2130 io_iterator_t mediaIterator;
2131 char bsdPath[ MAXPATHLEN ];
2132 int fd;
2134 kernResult = FindEjectableCDMedia( &mediaIterator );
2135 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
2137 if ( bsdPath[ 0 ] != '\0' ) {
2138 strcat(bsdPath,"s0");
2139 /* some CDs don't have a partition 0 */
2140 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
2141 if (fd < 0) {
2142 bsdPath[strlen(bsdPath)-1] = '1';
2143 } else {
2144 qemu_close(fd);
2146 filename = bsdPath;
2147 qdict_put(options, "filename", qstring_from_str(filename));
2150 if ( mediaIterator )
2151 IOObjectRelease( mediaIterator );
2153 #endif
2155 s->type = FTYPE_FILE;
2157 ret = raw_open_common(bs, options, flags, 0, &local_err);
2158 if (ret < 0) {
2159 if (local_err) {
2160 error_propagate(errp, local_err);
2162 return ret;
2165 /* Since this does ioctl the device must be already opened */
2166 bs->sg = hdev_is_sg(bs);
2168 if (flags & BDRV_O_RDWR) {
2169 ret = check_hdev_writable(s);
2170 if (ret < 0) {
2171 raw_close(bs);
2172 error_setg_errno(errp, -ret, "The device is not writable");
2173 return ret;
2177 return ret;
2180 #if defined(__linux__)
2181 /* Note: we do not have a reliable method to detect if the floppy is
2182 present. The current method is to try to open the floppy at every
2183 I/O and to keep it opened during a few hundreds of ms. */
2184 static int fd_open(BlockDriverState *bs)
2186 BDRVRawState *s = bs->opaque;
2187 int last_media_present;
2189 if (s->type != FTYPE_FD)
2190 return 0;
2191 last_media_present = (s->fd >= 0);
2192 if (s->fd >= 0 &&
2193 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
2194 qemu_close(s->fd);
2195 s->fd = -1;
2196 DPRINTF("Floppy closed\n");
2198 if (s->fd < 0) {
2199 if (s->fd_got_error &&
2200 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
2201 DPRINTF("No floppy (open delayed)\n");
2202 return -EIO;
2204 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
2205 if (s->fd < 0) {
2206 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2207 s->fd_got_error = 1;
2208 if (last_media_present)
2209 s->fd_media_changed = 1;
2210 DPRINTF("No floppy\n");
2211 return -EIO;
2213 DPRINTF("Floppy opened\n");
2215 if (!last_media_present)
2216 s->fd_media_changed = 1;
2217 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2218 s->fd_got_error = 0;
2219 return 0;
2222 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2224 BDRVRawState *s = bs->opaque;
2226 return ioctl(s->fd, req, buf);
2229 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2230 unsigned long int req, void *buf,
2231 BlockCompletionFunc *cb, void *opaque)
2233 BDRVRawState *s = bs->opaque;
2234 RawPosixAIOData *acb;
2235 ThreadPool *pool;
2237 if (fd_open(bs) < 0)
2238 return NULL;
2240 acb = g_new(RawPosixAIOData, 1);
2241 acb->bs = bs;
2242 acb->aio_type = QEMU_AIO_IOCTL;
2243 acb->aio_fildes = s->fd;
2244 acb->aio_offset = 0;
2245 acb->aio_ioctl_buf = buf;
2246 acb->aio_ioctl_cmd = req;
2247 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2248 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2251 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2252 static int fd_open(BlockDriverState *bs)
2254 BDRVRawState *s = bs->opaque;
2256 /* this is just to ensure s->fd is sane (its called by io ops) */
2257 if (s->fd >= 0)
2258 return 0;
2259 return -EIO;
2261 #else /* !linux && !FreeBSD */
2263 static int fd_open(BlockDriverState *bs)
2265 return 0;
2268 #endif /* !linux && !FreeBSD */
2270 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2271 int64_t sector_num, int nb_sectors,
2272 BlockCompletionFunc *cb, void *opaque)
2274 BDRVRawState *s = bs->opaque;
2276 if (fd_open(bs) < 0) {
2277 return NULL;
2279 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2280 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2283 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2284 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2286 BDRVRawState *s = bs->opaque;
2287 int rc;
2289 rc = fd_open(bs);
2290 if (rc < 0) {
2291 return rc;
2293 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2294 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2295 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2296 } else if (s->discard_zeroes) {
2297 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2298 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2300 return -ENOTSUP;
2303 static int hdev_create(const char *filename, QemuOpts *opts,
2304 Error **errp)
2306 int fd;
2307 int ret = 0;
2308 struct stat stat_buf;
2309 int64_t total_size = 0;
2310 bool has_prefix;
2312 /* This function is used by all three protocol block drivers and therefore
2313 * any of these three prefixes may be given.
2314 * The return value has to be stored somewhere, otherwise this is an error
2315 * due to -Werror=unused-value. */
2316 has_prefix =
2317 strstart(filename, "host_device:", &filename) ||
2318 strstart(filename, "host_cdrom:" , &filename) ||
2319 strstart(filename, "host_floppy:", &filename);
2321 (void)has_prefix;
2323 ret = raw_normalize_devicepath(&filename);
2324 if (ret < 0) {
2325 error_setg_errno(errp, -ret, "Could not normalize device path");
2326 return ret;
2329 /* Read out options */
2330 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2331 BDRV_SECTOR_SIZE);
2333 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2334 if (fd < 0) {
2335 ret = -errno;
2336 error_setg_errno(errp, -ret, "Could not open device");
2337 return ret;
2340 if (fstat(fd, &stat_buf) < 0) {
2341 ret = -errno;
2342 error_setg_errno(errp, -ret, "Could not stat device");
2343 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2344 error_setg(errp,
2345 "The given file is neither a block nor a character device");
2346 ret = -ENODEV;
2347 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2348 error_setg(errp, "Device is too small");
2349 ret = -ENOSPC;
2352 qemu_close(fd);
2353 return ret;
2356 static BlockDriver bdrv_host_device = {
2357 .format_name = "host_device",
2358 .protocol_name = "host_device",
2359 .instance_size = sizeof(BDRVRawState),
2360 .bdrv_needs_filename = true,
2361 .bdrv_probe_device = hdev_probe_device,
2362 .bdrv_parse_filename = hdev_parse_filename,
2363 .bdrv_file_open = hdev_open,
2364 .bdrv_close = raw_close,
2365 .bdrv_reopen_prepare = raw_reopen_prepare,
2366 .bdrv_reopen_commit = raw_reopen_commit,
2367 .bdrv_reopen_abort = raw_reopen_abort,
2368 .bdrv_create = hdev_create,
2369 .create_opts = &raw_create_opts,
2370 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2372 .bdrv_aio_readv = raw_aio_readv,
2373 .bdrv_aio_writev = raw_aio_writev,
2374 .bdrv_aio_flush = raw_aio_flush,
2375 .bdrv_aio_discard = hdev_aio_discard,
2376 .bdrv_refresh_limits = raw_refresh_limits,
2377 .bdrv_io_plug = raw_aio_plug,
2378 .bdrv_io_unplug = raw_aio_unplug,
2379 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2381 .bdrv_truncate = raw_truncate,
2382 .bdrv_getlength = raw_getlength,
2383 .bdrv_get_info = raw_get_info,
2384 .bdrv_get_allocated_file_size
2385 = raw_get_allocated_file_size,
2386 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2387 .bdrv_probe_geometry = hdev_probe_geometry,
2389 .bdrv_detach_aio_context = raw_detach_aio_context,
2390 .bdrv_attach_aio_context = raw_attach_aio_context,
2392 /* generic scsi device */
2393 #ifdef __linux__
2394 .bdrv_ioctl = hdev_ioctl,
2395 .bdrv_aio_ioctl = hdev_aio_ioctl,
2396 #endif
2399 #ifdef __linux__
2400 static void floppy_parse_filename(const char *filename, QDict *options,
2401 Error **errp)
2403 /* The prefix is optional, just as for "file". */
2404 strstart(filename, "host_floppy:", &filename);
2406 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2409 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2410 Error **errp)
2412 BDRVRawState *s = bs->opaque;
2413 Error *local_err = NULL;
2414 int ret;
2416 s->type = FTYPE_FD;
2418 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2419 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2420 if (ret) {
2421 if (local_err) {
2422 error_propagate(errp, local_err);
2424 return ret;
2427 /* close fd so that we can reopen it as needed */
2428 qemu_close(s->fd);
2429 s->fd = -1;
2430 s->fd_media_changed = 1;
2432 error_report("Host floppy pass-through is deprecated");
2433 error_printf("Support for it will be removed in a future release.\n");
2434 return 0;
2437 static int floppy_probe_device(const char *filename)
2439 int fd, ret;
2440 int prio = 0;
2441 struct floppy_struct fdparam;
2442 struct stat st;
2444 if (strstart(filename, "/dev/fd", NULL) &&
2445 !strstart(filename, "/dev/fdset/", NULL) &&
2446 !strstart(filename, "/dev/fd/", NULL)) {
2447 prio = 50;
2450 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2451 if (fd < 0) {
2452 goto out;
2454 ret = fstat(fd, &st);
2455 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2456 goto outc;
2459 /* Attempt to detect via a floppy specific ioctl */
2460 ret = ioctl(fd, FDGETPRM, &fdparam);
2461 if (ret >= 0)
2462 prio = 100;
2464 outc:
2465 qemu_close(fd);
2466 out:
2467 return prio;
2471 static int floppy_is_inserted(BlockDriverState *bs)
2473 return fd_open(bs) >= 0;
2476 static int floppy_media_changed(BlockDriverState *bs)
2478 BDRVRawState *s = bs->opaque;
2479 int ret;
2482 * XXX: we do not have a true media changed indication.
2483 * It does not work if the floppy is changed without trying to read it.
2485 fd_open(bs);
2486 ret = s->fd_media_changed;
2487 s->fd_media_changed = 0;
2488 DPRINTF("Floppy changed=%d\n", ret);
2489 return ret;
2492 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2494 BDRVRawState *s = bs->opaque;
2495 int fd;
2497 if (s->fd >= 0) {
2498 qemu_close(s->fd);
2499 s->fd = -1;
2501 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2502 if (fd >= 0) {
2503 if (ioctl(fd, FDEJECT, 0) < 0)
2504 perror("FDEJECT");
2505 qemu_close(fd);
2509 static BlockDriver bdrv_host_floppy = {
2510 .format_name = "host_floppy",
2511 .protocol_name = "host_floppy",
2512 .instance_size = sizeof(BDRVRawState),
2513 .bdrv_needs_filename = true,
2514 .bdrv_probe_device = floppy_probe_device,
2515 .bdrv_parse_filename = floppy_parse_filename,
2516 .bdrv_file_open = floppy_open,
2517 .bdrv_close = raw_close,
2518 .bdrv_reopen_prepare = raw_reopen_prepare,
2519 .bdrv_reopen_commit = raw_reopen_commit,
2520 .bdrv_reopen_abort = raw_reopen_abort,
2521 .bdrv_create = hdev_create,
2522 .create_opts = &raw_create_opts,
2524 .bdrv_aio_readv = raw_aio_readv,
2525 .bdrv_aio_writev = raw_aio_writev,
2526 .bdrv_aio_flush = raw_aio_flush,
2527 .bdrv_refresh_limits = raw_refresh_limits,
2528 .bdrv_io_plug = raw_aio_plug,
2529 .bdrv_io_unplug = raw_aio_unplug,
2530 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2532 .bdrv_truncate = raw_truncate,
2533 .bdrv_getlength = raw_getlength,
2534 .has_variable_length = true,
2535 .bdrv_get_allocated_file_size
2536 = raw_get_allocated_file_size,
2538 .bdrv_detach_aio_context = raw_detach_aio_context,
2539 .bdrv_attach_aio_context = raw_attach_aio_context,
2541 /* removable device support */
2542 .bdrv_is_inserted = floppy_is_inserted,
2543 .bdrv_media_changed = floppy_media_changed,
2544 .bdrv_eject = floppy_eject,
2546 #endif
2548 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2549 static void cdrom_parse_filename(const char *filename, QDict *options,
2550 Error **errp)
2552 /* The prefix is optional, just as for "file". */
2553 strstart(filename, "host_cdrom:", &filename);
2555 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2557 #endif
2559 #ifdef __linux__
2560 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2561 Error **errp)
2563 BDRVRawState *s = bs->opaque;
2564 Error *local_err = NULL;
2565 int ret;
2567 s->type = FTYPE_CD;
2569 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2570 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2571 if (local_err) {
2572 error_propagate(errp, local_err);
2574 return ret;
2577 static int cdrom_probe_device(const char *filename)
2579 int fd, ret;
2580 int prio = 0;
2581 struct stat st;
2583 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2584 if (fd < 0) {
2585 goto out;
2587 ret = fstat(fd, &st);
2588 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2589 goto outc;
2592 /* Attempt to detect via a CDROM specific ioctl */
2593 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2594 if (ret >= 0)
2595 prio = 100;
2597 outc:
2598 qemu_close(fd);
2599 out:
2600 return prio;
2603 static int cdrom_is_inserted(BlockDriverState *bs)
2605 BDRVRawState *s = bs->opaque;
2606 int ret;
2608 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2609 if (ret == CDS_DISC_OK)
2610 return 1;
2611 return 0;
2614 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2616 BDRVRawState *s = bs->opaque;
2618 if (eject_flag) {
2619 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2620 perror("CDROMEJECT");
2621 } else {
2622 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2623 perror("CDROMEJECT");
2627 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2629 BDRVRawState *s = bs->opaque;
2631 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2633 * Note: an error can happen if the distribution automatically
2634 * mounts the CD-ROM
2636 /* perror("CDROM_LOCKDOOR"); */
2640 static BlockDriver bdrv_host_cdrom = {
2641 .format_name = "host_cdrom",
2642 .protocol_name = "host_cdrom",
2643 .instance_size = sizeof(BDRVRawState),
2644 .bdrv_needs_filename = true,
2645 .bdrv_probe_device = cdrom_probe_device,
2646 .bdrv_parse_filename = cdrom_parse_filename,
2647 .bdrv_file_open = cdrom_open,
2648 .bdrv_close = raw_close,
2649 .bdrv_reopen_prepare = raw_reopen_prepare,
2650 .bdrv_reopen_commit = raw_reopen_commit,
2651 .bdrv_reopen_abort = raw_reopen_abort,
2652 .bdrv_create = hdev_create,
2653 .create_opts = &raw_create_opts,
2655 .bdrv_aio_readv = raw_aio_readv,
2656 .bdrv_aio_writev = raw_aio_writev,
2657 .bdrv_aio_flush = raw_aio_flush,
2658 .bdrv_refresh_limits = raw_refresh_limits,
2659 .bdrv_io_plug = raw_aio_plug,
2660 .bdrv_io_unplug = raw_aio_unplug,
2661 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2663 .bdrv_truncate = raw_truncate,
2664 .bdrv_getlength = raw_getlength,
2665 .has_variable_length = true,
2666 .bdrv_get_allocated_file_size
2667 = raw_get_allocated_file_size,
2669 .bdrv_detach_aio_context = raw_detach_aio_context,
2670 .bdrv_attach_aio_context = raw_attach_aio_context,
2672 /* removable device support */
2673 .bdrv_is_inserted = cdrom_is_inserted,
2674 .bdrv_eject = cdrom_eject,
2675 .bdrv_lock_medium = cdrom_lock_medium,
2677 /* generic scsi device */
2678 .bdrv_ioctl = hdev_ioctl,
2679 .bdrv_aio_ioctl = hdev_aio_ioctl,
2681 #endif /* __linux__ */
2683 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2684 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2685 Error **errp)
2687 BDRVRawState *s = bs->opaque;
2688 Error *local_err = NULL;
2689 int ret;
2691 s->type = FTYPE_CD;
2693 ret = raw_open_common(bs, options, flags, 0, &local_err);
2694 if (ret) {
2695 if (local_err) {
2696 error_propagate(errp, local_err);
2698 return ret;
2701 /* make sure the door isn't locked at this time */
2702 ioctl(s->fd, CDIOCALLOW);
2703 return 0;
2706 static int cdrom_probe_device(const char *filename)
2708 if (strstart(filename, "/dev/cd", NULL) ||
2709 strstart(filename, "/dev/acd", NULL))
2710 return 100;
2711 return 0;
2714 static int cdrom_reopen(BlockDriverState *bs)
2716 BDRVRawState *s = bs->opaque;
2717 int fd;
2720 * Force reread of possibly changed/newly loaded disc,
2721 * FreeBSD seems to not notice sometimes...
2723 if (s->fd >= 0)
2724 qemu_close(s->fd);
2725 fd = qemu_open(bs->filename, s->open_flags, 0644);
2726 if (fd < 0) {
2727 s->fd = -1;
2728 return -EIO;
2730 s->fd = fd;
2732 /* make sure the door isn't locked at this time */
2733 ioctl(s->fd, CDIOCALLOW);
2734 return 0;
2737 static int cdrom_is_inserted(BlockDriverState *bs)
2739 return raw_getlength(bs) > 0;
2742 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2744 BDRVRawState *s = bs->opaque;
2746 if (s->fd < 0)
2747 return;
2749 (void) ioctl(s->fd, CDIOCALLOW);
2751 if (eject_flag) {
2752 if (ioctl(s->fd, CDIOCEJECT) < 0)
2753 perror("CDIOCEJECT");
2754 } else {
2755 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2756 perror("CDIOCCLOSE");
2759 cdrom_reopen(bs);
2762 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2764 BDRVRawState *s = bs->opaque;
2766 if (s->fd < 0)
2767 return;
2768 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2770 * Note: an error can happen if the distribution automatically
2771 * mounts the CD-ROM
2773 /* perror("CDROM_LOCKDOOR"); */
2777 static BlockDriver bdrv_host_cdrom = {
2778 .format_name = "host_cdrom",
2779 .protocol_name = "host_cdrom",
2780 .instance_size = sizeof(BDRVRawState),
2781 .bdrv_needs_filename = true,
2782 .bdrv_probe_device = cdrom_probe_device,
2783 .bdrv_parse_filename = cdrom_parse_filename,
2784 .bdrv_file_open = cdrom_open,
2785 .bdrv_close = raw_close,
2786 .bdrv_reopen_prepare = raw_reopen_prepare,
2787 .bdrv_reopen_commit = raw_reopen_commit,
2788 .bdrv_reopen_abort = raw_reopen_abort,
2789 .bdrv_create = hdev_create,
2790 .create_opts = &raw_create_opts,
2792 .bdrv_aio_readv = raw_aio_readv,
2793 .bdrv_aio_writev = raw_aio_writev,
2794 .bdrv_aio_flush = raw_aio_flush,
2795 .bdrv_refresh_limits = raw_refresh_limits,
2796 .bdrv_io_plug = raw_aio_plug,
2797 .bdrv_io_unplug = raw_aio_unplug,
2798 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2800 .bdrv_truncate = raw_truncate,
2801 .bdrv_getlength = raw_getlength,
2802 .has_variable_length = true,
2803 .bdrv_get_allocated_file_size
2804 = raw_get_allocated_file_size,
2806 .bdrv_detach_aio_context = raw_detach_aio_context,
2807 .bdrv_attach_aio_context = raw_attach_aio_context,
2809 /* removable device support */
2810 .bdrv_is_inserted = cdrom_is_inserted,
2811 .bdrv_eject = cdrom_eject,
2812 .bdrv_lock_medium = cdrom_lock_medium,
2814 #endif /* __FreeBSD__ */
2816 static void bdrv_file_init(void)
2819 * Register all the drivers. Note that order is important, the driver
2820 * registered last will get probed first.
2822 bdrv_register(&bdrv_file);
2823 bdrv_register(&bdrv_host_device);
2824 #ifdef __linux__
2825 bdrv_register(&bdrv_host_floppy);
2826 bdrv_register(&bdrv_host_cdrom);
2827 #endif
2828 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2829 bdrv_register(&bdrv_host_cdrom);
2830 #endif
2833 block_init(bdrv_file_init);