Merge remote-tracking branch 'remotes/afaerber/tags/qtest-for-2.3' into staging
[qemu/ar7.git] / block / raw-posix.c
blob24d85826c484bc25bf9e1f46a391da082601fa6e
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/timer.h"
26 #include "qemu/log.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "trace.h"
30 #include "block/thread-pool.h"
31 #include "qemu/iov.h"
32 #include "raw-aio.h"
33 #include "qapi/util.h"
35 #if defined(__APPLE__) && (__MACH__)
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
45 #endif
47 #ifdef __sun__
48 #define _POSIX_PTHREAD_SEMANTICS 1
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
57 #include <linux/fd.h>
58 #include <linux/fs.h>
59 #include <linux/hdreg.h>
60 #ifdef __s390__
61 #include <asm/dasd.h>
62 #endif
63 #ifndef FS_NOCOW_FL
64 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
65 #endif
66 #endif
67 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
68 #include <linux/falloc.h>
69 #endif
70 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
71 #include <sys/disk.h>
72 #include <sys/cdio.h>
73 #endif
75 #ifdef __OpenBSD__
76 #include <sys/ioctl.h>
77 #include <sys/disklabel.h>
78 #include <sys/dkio.h>
79 #endif
81 #ifdef __NetBSD__
82 #include <sys/ioctl.h>
83 #include <sys/disklabel.h>
84 #include <sys/dkio.h>
85 #include <sys/disk.h>
86 #endif
88 #ifdef __DragonFly__
89 #include <sys/ioctl.h>
90 #include <sys/diskslice.h>
91 #endif
93 #ifdef CONFIG_XFS
94 #include <xfs/xfs.h>
95 #endif
97 //#define DEBUG_FLOPPY
99 //#define DEBUG_BLOCK
100 #if defined(DEBUG_BLOCK)
101 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
102 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
103 #else
104 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
105 #endif
107 /* OS X does not have O_DSYNC */
108 #ifndef O_DSYNC
109 #ifdef O_SYNC
110 #define O_DSYNC O_SYNC
111 #elif defined(O_FSYNC)
112 #define O_DSYNC O_FSYNC
113 #endif
114 #endif
116 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
117 #ifndef O_DIRECT
118 #define O_DIRECT O_DSYNC
119 #endif
121 #define FTYPE_FILE 0
122 #define FTYPE_CD 1
123 #define FTYPE_FD 2
125 /* if the FD is not accessed during that time (in ns), we try to
126 reopen it to see if the disk has been changed */
127 #define FD_OPEN_TIMEOUT (1000000000)
129 #define MAX_BLOCKSIZE 4096
131 typedef struct BDRVRawState {
132 int fd;
133 int type;
134 int open_flags;
135 size_t buf_align;
137 #if defined(__linux__)
138 /* linux floppy specific */
139 int64_t fd_open_time;
140 int64_t fd_error_time;
141 int fd_got_error;
142 int fd_media_changed;
143 #endif
144 #ifdef CONFIG_LINUX_AIO
145 int use_aio;
146 void *aio_ctx;
147 #endif
148 #ifdef CONFIG_XFS
149 bool is_xfs:1;
150 #endif
151 bool has_discard:1;
152 bool has_write_zeroes:1;
153 bool discard_zeroes:1;
154 bool has_fallocate;
155 bool needs_alignment;
156 } BDRVRawState;
158 typedef struct BDRVRawReopenState {
159 int fd;
160 int open_flags;
161 #ifdef CONFIG_LINUX_AIO
162 int use_aio;
163 #endif
164 } BDRVRawReopenState;
166 static int fd_open(BlockDriverState *bs);
167 static int64_t raw_getlength(BlockDriverState *bs);
169 typedef struct RawPosixAIOData {
170 BlockDriverState *bs;
171 int aio_fildes;
172 union {
173 struct iovec *aio_iov;
174 void *aio_ioctl_buf;
176 int aio_niov;
177 uint64_t aio_nbytes;
178 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
179 off_t aio_offset;
180 int aio_type;
181 } RawPosixAIOData;
183 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184 static int cdrom_reopen(BlockDriverState *bs);
185 #endif
187 #if defined(__NetBSD__)
188 static int raw_normalize_devicepath(const char **filename)
190 static char namebuf[PATH_MAX];
191 const char *dp, *fname;
192 struct stat sb;
194 fname = *filename;
195 dp = strrchr(fname, '/');
196 if (lstat(fname, &sb) < 0) {
197 fprintf(stderr, "%s: stat failed: %s\n",
198 fname, strerror(errno));
199 return -errno;
202 if (!S_ISBLK(sb.st_mode)) {
203 return 0;
206 if (dp == NULL) {
207 snprintf(namebuf, PATH_MAX, "r%s", fname);
208 } else {
209 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
210 (int)(dp - fname), fname, dp + 1);
212 fprintf(stderr, "%s is a block device", fname);
213 *filename = namebuf;
214 fprintf(stderr, ", using %s\n", *filename);
216 return 0;
218 #else
219 static int raw_normalize_devicepath(const char **filename)
221 return 0;
223 #endif
226 * Get logical block size via ioctl. On success store it in @sector_size_p.
228 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
230 unsigned int sector_size;
231 bool success = false;
233 errno = ENOTSUP;
235 /* Try a few ioctls to get the right size */
236 #ifdef BLKSSZGET
237 if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
238 *sector_size_p = sector_size;
239 success = true;
241 #endif
242 #ifdef DKIOCGETBLOCKSIZE
243 if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
244 *sector_size_p = sector_size;
245 success = true;
247 #endif
248 #ifdef DIOCGSECTORSIZE
249 if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
250 *sector_size_p = sector_size;
251 success = true;
253 #endif
255 return success ? 0 : -errno;
259 * Get physical block size of @fd.
260 * On success, store it in @blk_size and return 0.
261 * On failure, return -errno.
263 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
265 #ifdef BLKPBSZGET
266 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
267 return -errno;
269 return 0;
270 #else
271 return -ENOTSUP;
272 #endif
275 /* Check if read is allowed with given memory buffer and length.
277 * This function is used to check O_DIRECT memory buffer and request alignment.
279 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
281 ssize_t ret = pread(fd, buf, len, 0);
283 if (ret >= 0) {
284 return true;
287 #ifdef __linux__
288 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
289 * other errors (e.g. real I/O error), which could happen on a failed
290 * drive, since we only care about probing alignment.
292 if (errno != EINVAL) {
293 return true;
295 #endif
297 return false;
300 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
302 BDRVRawState *s = bs->opaque;
303 char *buf;
305 /* For /dev/sg devices the alignment is not really used.
306 With buffered I/O, we don't have any restrictions. */
307 if (bs->sg || !s->needs_alignment) {
308 bs->request_alignment = 1;
309 s->buf_align = 1;
310 return;
313 bs->request_alignment = 0;
314 s->buf_align = 0;
315 /* Let's try to use the logical blocksize for the alignment. */
316 if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {
317 bs->request_alignment = 0;
319 #ifdef CONFIG_XFS
320 if (s->is_xfs) {
321 struct dioattr da;
322 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
323 bs->request_alignment = da.d_miniosz;
324 /* The kernel returns wrong information for d_mem */
325 /* s->buf_align = da.d_mem; */
328 #endif
330 /* If we could not get the sizes so far, we can only guess them */
331 if (!s->buf_align) {
332 size_t align;
333 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
334 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
335 if (raw_is_io_aligned(fd, buf + align, MAX_BLOCKSIZE)) {
336 s->buf_align = align;
337 break;
340 qemu_vfree(buf);
343 if (!bs->request_alignment) {
344 size_t align;
345 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
346 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
347 if (raw_is_io_aligned(fd, buf, align)) {
348 bs->request_alignment = align;
349 break;
352 qemu_vfree(buf);
355 if (!s->buf_align || !bs->request_alignment) {
356 error_setg(errp, "Could not find working O_DIRECT alignment. "
357 "Try cache.direct=off.");
361 static void raw_parse_flags(int bdrv_flags, int *open_flags)
363 assert(open_flags != NULL);
365 *open_flags |= O_BINARY;
366 *open_flags &= ~O_ACCMODE;
367 if (bdrv_flags & BDRV_O_RDWR) {
368 *open_flags |= O_RDWR;
369 } else {
370 *open_flags |= O_RDONLY;
373 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
374 * and O_DIRECT for no caching. */
375 if ((bdrv_flags & BDRV_O_NOCACHE)) {
376 *open_flags |= O_DIRECT;
380 static void raw_detach_aio_context(BlockDriverState *bs)
382 #ifdef CONFIG_LINUX_AIO
383 BDRVRawState *s = bs->opaque;
385 if (s->use_aio) {
386 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
388 #endif
391 static void raw_attach_aio_context(BlockDriverState *bs,
392 AioContext *new_context)
394 #ifdef CONFIG_LINUX_AIO
395 BDRVRawState *s = bs->opaque;
397 if (s->use_aio) {
398 laio_attach_aio_context(s->aio_ctx, new_context);
400 #endif
403 #ifdef CONFIG_LINUX_AIO
404 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
406 int ret = -1;
407 assert(aio_ctx != NULL);
408 assert(use_aio != NULL);
410 * Currently Linux do AIO only for files opened with O_DIRECT
411 * specified so check NOCACHE flag too
413 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
414 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
416 /* if non-NULL, laio_init() has already been run */
417 if (*aio_ctx == NULL) {
418 *aio_ctx = laio_init();
419 if (!*aio_ctx) {
420 goto error;
423 *use_aio = 1;
424 } else {
425 *use_aio = 0;
428 ret = 0;
430 error:
431 return ret;
433 #endif
435 static void raw_parse_filename(const char *filename, QDict *options,
436 Error **errp)
438 /* The filename does not have to be prefixed by the protocol name, since
439 * "file" is the default protocol; therefore, the return value of this
440 * function call can be ignored. */
441 strstart(filename, "file:", &filename);
443 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
446 static QemuOptsList raw_runtime_opts = {
447 .name = "raw",
448 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
449 .desc = {
451 .name = "filename",
452 .type = QEMU_OPT_STRING,
453 .help = "File name of the image",
455 { /* end of list */ }
459 static int raw_open_common(BlockDriverState *bs, QDict *options,
460 int bdrv_flags, int open_flags, Error **errp)
462 BDRVRawState *s = bs->opaque;
463 QemuOpts *opts;
464 Error *local_err = NULL;
465 const char *filename = NULL;
466 int fd, ret;
467 struct stat st;
469 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
470 qemu_opts_absorb_qdict(opts, options, &local_err);
471 if (local_err) {
472 error_propagate(errp, local_err);
473 ret = -EINVAL;
474 goto fail;
477 filename = qemu_opt_get(opts, "filename");
479 ret = raw_normalize_devicepath(&filename);
480 if (ret != 0) {
481 error_setg_errno(errp, -ret, "Could not normalize device path");
482 goto fail;
485 s->open_flags = open_flags;
486 raw_parse_flags(bdrv_flags, &s->open_flags);
488 s->fd = -1;
489 fd = qemu_open(filename, s->open_flags, 0644);
490 if (fd < 0) {
491 ret = -errno;
492 if (ret == -EROFS) {
493 ret = -EACCES;
495 goto fail;
497 s->fd = fd;
499 #ifdef CONFIG_LINUX_AIO
500 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
501 qemu_close(fd);
502 ret = -errno;
503 error_setg_errno(errp, -ret, "Could not set AIO state");
504 goto fail;
506 if (!s->use_aio && (bdrv_flags & BDRV_O_NATIVE_AIO)) {
507 error_printf("WARNING: aio=native was specified for '%s', but "
508 "it requires cache.direct=on, which was not "
509 "specified. Falling back to aio=threads.\n"
510 " This will become an error condition in "
511 "future QEMU versions.\n",
512 bs->filename);
514 #endif
516 s->has_discard = true;
517 s->has_write_zeroes = true;
518 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
519 s->needs_alignment = true;
522 if (fstat(s->fd, &st) < 0) {
523 ret = -errno;
524 error_setg_errno(errp, errno, "Could not stat file");
525 goto fail;
527 if (S_ISREG(st.st_mode)) {
528 s->discard_zeroes = true;
529 s->has_fallocate = true;
531 if (S_ISBLK(st.st_mode)) {
532 #ifdef BLKDISCARDZEROES
533 unsigned int arg;
534 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
535 s->discard_zeroes = true;
537 #endif
538 #ifdef __linux__
539 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
540 * not rely on the contents of discarded blocks unless using O_DIRECT.
541 * Same for BLKZEROOUT.
543 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
544 s->discard_zeroes = false;
545 s->has_write_zeroes = false;
547 #endif
549 #ifdef __FreeBSD__
550 if (S_ISCHR(st.st_mode)) {
552 * The file is a char device (disk), which on FreeBSD isn't behind
553 * a pager, so force all requests to be aligned. This is needed
554 * so QEMU makes sure all IO operations on the device are aligned
555 * to sector size, or else FreeBSD will reject them with EINVAL.
557 s->needs_alignment = true;
559 #endif
561 #ifdef CONFIG_XFS
562 if (platform_test_xfs_fd(s->fd)) {
563 s->is_xfs = true;
565 #endif
567 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
569 ret = 0;
570 fail:
571 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
572 unlink(filename);
574 qemu_opts_del(opts);
575 return ret;
578 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
579 Error **errp)
581 BDRVRawState *s = bs->opaque;
582 Error *local_err = NULL;
583 int ret;
585 s->type = FTYPE_FILE;
586 ret = raw_open_common(bs, options, flags, 0, &local_err);
587 if (local_err) {
588 error_propagate(errp, local_err);
590 return ret;
593 static int raw_reopen_prepare(BDRVReopenState *state,
594 BlockReopenQueue *queue, Error **errp)
596 BDRVRawState *s;
597 BDRVRawReopenState *raw_s;
598 int ret = 0;
599 Error *local_err = NULL;
601 assert(state != NULL);
602 assert(state->bs != NULL);
604 s = state->bs->opaque;
606 state->opaque = g_new0(BDRVRawReopenState, 1);
607 raw_s = state->opaque;
609 #ifdef CONFIG_LINUX_AIO
610 raw_s->use_aio = s->use_aio;
612 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
613 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
614 * won't override aio_ctx if aio_ctx is non-NULL */
615 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
616 error_setg(errp, "Could not set AIO state");
617 return -1;
619 #endif
621 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
622 raw_s->open_flags |= O_NONBLOCK;
625 raw_parse_flags(state->flags, &raw_s->open_flags);
627 raw_s->fd = -1;
629 int fcntl_flags = O_APPEND | O_NONBLOCK;
630 #ifdef O_NOATIME
631 fcntl_flags |= O_NOATIME;
632 #endif
634 #ifdef O_ASYNC
635 /* Not all operating systems have O_ASYNC, and those that don't
636 * will not let us track the state into raw_s->open_flags (typically
637 * you achieve the same effect with an ioctl, for example I_SETSIG
638 * on Solaris). But we do not use O_ASYNC, so that's fine.
640 assert((s->open_flags & O_ASYNC) == 0);
641 #endif
643 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
644 /* dup the original fd */
645 /* TODO: use qemu fcntl wrapper */
646 #ifdef F_DUPFD_CLOEXEC
647 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
648 #else
649 raw_s->fd = dup(s->fd);
650 if (raw_s->fd != -1) {
651 qemu_set_cloexec(raw_s->fd);
653 #endif
654 if (raw_s->fd >= 0) {
655 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
656 if (ret) {
657 qemu_close(raw_s->fd);
658 raw_s->fd = -1;
663 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
664 if (raw_s->fd == -1) {
665 assert(!(raw_s->open_flags & O_CREAT));
666 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
667 if (raw_s->fd == -1) {
668 error_setg_errno(errp, errno, "Could not reopen file");
669 ret = -1;
673 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
674 * alignment with the new fd. */
675 if (raw_s->fd != -1) {
676 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
677 if (local_err) {
678 qemu_close(raw_s->fd);
679 raw_s->fd = -1;
680 error_propagate(errp, local_err);
681 ret = -EINVAL;
685 return ret;
688 static void raw_reopen_commit(BDRVReopenState *state)
690 BDRVRawReopenState *raw_s = state->opaque;
691 BDRVRawState *s = state->bs->opaque;
693 s->open_flags = raw_s->open_flags;
695 qemu_close(s->fd);
696 s->fd = raw_s->fd;
697 #ifdef CONFIG_LINUX_AIO
698 s->use_aio = raw_s->use_aio;
699 #endif
701 g_free(state->opaque);
702 state->opaque = NULL;
706 static void raw_reopen_abort(BDRVReopenState *state)
708 BDRVRawReopenState *raw_s = state->opaque;
710 /* nothing to do if NULL, we didn't get far enough */
711 if (raw_s == NULL) {
712 return;
715 if (raw_s->fd >= 0) {
716 qemu_close(raw_s->fd);
717 raw_s->fd = -1;
719 g_free(state->opaque);
720 state->opaque = NULL;
723 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
725 BDRVRawState *s = bs->opaque;
727 raw_probe_alignment(bs, s->fd, errp);
728 bs->bl.opt_mem_alignment = s->buf_align;
731 static int check_for_dasd(int fd)
733 #ifdef BIODASDINFO2
734 struct dasd_information2_t info = {0};
736 return ioctl(fd, BIODASDINFO2, &info);
737 #else
738 return -1;
739 #endif
743 * Try to get @bs's logical and physical block size.
744 * On success, store them in @bsz and return zero.
745 * On failure, return negative errno.
747 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
749 BDRVRawState *s = bs->opaque;
750 int ret;
752 /* If DASD, get blocksizes */
753 if (check_for_dasd(s->fd) < 0) {
754 return -ENOTSUP;
756 ret = probe_logical_blocksize(s->fd, &bsz->log);
757 if (ret < 0) {
758 return ret;
760 return probe_physical_blocksize(s->fd, &bsz->phys);
764 * Try to get @bs's geometry: cyls, heads, sectors.
765 * On success, store them in @geo and return 0.
766 * On failure return -errno.
767 * (Allows block driver to assign default geometry values that guest sees)
769 #ifdef __linux__
770 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
772 BDRVRawState *s = bs->opaque;
773 struct hd_geometry ioctl_geo = {0};
774 uint32_t blksize;
776 /* If DASD, get its geometry */
777 if (check_for_dasd(s->fd) < 0) {
778 return -ENOTSUP;
780 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
781 return -errno;
783 /* HDIO_GETGEO may return success even though geo contains zeros
784 (e.g. certain multipath setups) */
785 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
786 return -ENOTSUP;
788 /* Do not return a geometry for partition */
789 if (ioctl_geo.start != 0) {
790 return -ENOTSUP;
792 geo->heads = ioctl_geo.heads;
793 geo->sectors = ioctl_geo.sectors;
794 if (!probe_physical_blocksize(s->fd, &blksize)) {
795 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
796 geo->cylinders = bdrv_nb_sectors(bs) / (blksize / BDRV_SECTOR_SIZE)
797 / (geo->heads * geo->sectors);
798 return 0;
800 geo->cylinders = ioctl_geo.cylinders;
802 return 0;
804 #else /* __linux__ */
805 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
807 return -ENOTSUP;
809 #endif
811 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
813 int ret;
815 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
816 if (ret == -1) {
817 return -errno;
820 return 0;
823 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
825 int ret;
827 ret = qemu_fdatasync(aiocb->aio_fildes);
828 if (ret == -1) {
829 return -errno;
831 return 0;
834 #ifdef CONFIG_PREADV
836 static bool preadv_present = true;
838 static ssize_t
839 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
841 return preadv(fd, iov, nr_iov, offset);
844 static ssize_t
845 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
847 return pwritev(fd, iov, nr_iov, offset);
850 #else
852 static bool preadv_present = false;
854 static ssize_t
855 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
857 return -ENOSYS;
860 static ssize_t
861 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
863 return -ENOSYS;
866 #endif
868 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
870 ssize_t len;
872 do {
873 if (aiocb->aio_type & QEMU_AIO_WRITE)
874 len = qemu_pwritev(aiocb->aio_fildes,
875 aiocb->aio_iov,
876 aiocb->aio_niov,
877 aiocb->aio_offset);
878 else
879 len = qemu_preadv(aiocb->aio_fildes,
880 aiocb->aio_iov,
881 aiocb->aio_niov,
882 aiocb->aio_offset);
883 } while (len == -1 && errno == EINTR);
885 if (len == -1) {
886 return -errno;
888 return len;
892 * Read/writes the data to/from a given linear buffer.
894 * Returns the number of bytes handles or -errno in case of an error. Short
895 * reads are only returned if the end of the file is reached.
897 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
899 ssize_t offset = 0;
900 ssize_t len;
902 while (offset < aiocb->aio_nbytes) {
903 if (aiocb->aio_type & QEMU_AIO_WRITE) {
904 len = pwrite(aiocb->aio_fildes,
905 (const char *)buf + offset,
906 aiocb->aio_nbytes - offset,
907 aiocb->aio_offset + offset);
908 } else {
909 len = pread(aiocb->aio_fildes,
910 buf + offset,
911 aiocb->aio_nbytes - offset,
912 aiocb->aio_offset + offset);
914 if (len == -1 && errno == EINTR) {
915 continue;
916 } else if (len == -1 && errno == EINVAL &&
917 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
918 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
919 offset > 0) {
920 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
921 * after a short read. Assume that O_DIRECT short reads only occur
922 * at EOF. Therefore this is a short read, not an I/O error.
924 break;
925 } else if (len == -1) {
926 offset = -errno;
927 break;
928 } else if (len == 0) {
929 break;
931 offset += len;
934 return offset;
937 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
939 ssize_t nbytes;
940 char *buf;
942 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
944 * If there is just a single buffer, and it is properly aligned
945 * we can just use plain pread/pwrite without any problems.
947 if (aiocb->aio_niov == 1) {
948 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
951 * We have more than one iovec, and all are properly aligned.
953 * Try preadv/pwritev first and fall back to linearizing the
954 * buffer if it's not supported.
956 if (preadv_present) {
957 nbytes = handle_aiocb_rw_vector(aiocb);
958 if (nbytes == aiocb->aio_nbytes ||
959 (nbytes < 0 && nbytes != -ENOSYS)) {
960 return nbytes;
962 preadv_present = false;
966 * XXX(hch): short read/write. no easy way to handle the reminder
967 * using these interfaces. For now retry using plain
968 * pread/pwrite?
973 * Ok, we have to do it the hard way, copy all segments into
974 * a single aligned buffer.
976 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
977 if (buf == NULL) {
978 return -ENOMEM;
981 if (aiocb->aio_type & QEMU_AIO_WRITE) {
982 char *p = buf;
983 int i;
985 for (i = 0; i < aiocb->aio_niov; ++i) {
986 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
987 p += aiocb->aio_iov[i].iov_len;
989 assert(p - buf == aiocb->aio_nbytes);
992 nbytes = handle_aiocb_rw_linear(aiocb, buf);
993 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
994 char *p = buf;
995 size_t count = aiocb->aio_nbytes, copy;
996 int i;
998 for (i = 0; i < aiocb->aio_niov && count; ++i) {
999 copy = count;
1000 if (copy > aiocb->aio_iov[i].iov_len) {
1001 copy = aiocb->aio_iov[i].iov_len;
1003 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1004 assert(count >= copy);
1005 p += copy;
1006 count -= copy;
1008 assert(count == 0);
1010 qemu_vfree(buf);
1012 return nbytes;
1015 #ifdef CONFIG_XFS
1016 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1018 struct xfs_flock64 fl;
1020 memset(&fl, 0, sizeof(fl));
1021 fl.l_whence = SEEK_SET;
1022 fl.l_start = offset;
1023 fl.l_len = bytes;
1025 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1026 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
1027 return -errno;
1030 return 0;
1033 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1035 struct xfs_flock64 fl;
1037 memset(&fl, 0, sizeof(fl));
1038 fl.l_whence = SEEK_SET;
1039 fl.l_start = offset;
1040 fl.l_len = bytes;
1042 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1043 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
1044 return -errno;
1047 return 0;
1049 #endif
1051 static int translate_err(int err)
1053 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1054 err == -ENOTTY) {
1055 err = -ENOTSUP;
1057 return err;
1060 #ifdef CONFIG_FALLOCATE
1061 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1063 do {
1064 if (fallocate(fd, mode, offset, len) == 0) {
1065 return 0;
1067 } while (errno == EINTR);
1068 return translate_err(-errno);
1070 #endif
1072 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1074 int ret = -ENOTSUP;
1075 BDRVRawState *s = aiocb->bs->opaque;
1077 if (!s->has_write_zeroes) {
1078 return -ENOTSUP;
1081 #ifdef BLKZEROOUT
1082 do {
1083 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1084 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1085 return 0;
1087 } while (errno == EINTR);
1089 ret = translate_err(-errno);
1090 #endif
1092 if (ret == -ENOTSUP) {
1093 s->has_write_zeroes = false;
1095 return ret;
1098 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1100 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1101 BDRVRawState *s = aiocb->bs->opaque;
1102 #endif
1104 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1105 return handle_aiocb_write_zeroes_block(aiocb);
1108 #ifdef CONFIG_XFS
1109 if (s->is_xfs) {
1110 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1112 #endif
1114 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1115 if (s->has_write_zeroes) {
1116 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1117 aiocb->aio_offset, aiocb->aio_nbytes);
1118 if (ret == 0 || ret != -ENOTSUP) {
1119 return ret;
1121 s->has_write_zeroes = false;
1123 #endif
1125 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1126 if (s->has_discard && s->has_fallocate) {
1127 int ret = do_fallocate(s->fd,
1128 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1129 aiocb->aio_offset, aiocb->aio_nbytes);
1130 if (ret == 0) {
1131 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1132 if (ret == 0 || ret != -ENOTSUP) {
1133 return ret;
1135 s->has_fallocate = false;
1136 } else if (ret != -ENOTSUP) {
1137 return ret;
1138 } else {
1139 s->has_discard = false;
1142 #endif
1144 #ifdef CONFIG_FALLOCATE
1145 if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1146 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1147 if (ret == 0 || ret != -ENOTSUP) {
1148 return ret;
1150 s->has_fallocate = false;
1152 #endif
1154 return -ENOTSUP;
1157 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1159 int ret = -EOPNOTSUPP;
1160 BDRVRawState *s = aiocb->bs->opaque;
1162 if (!s->has_discard) {
1163 return -ENOTSUP;
1166 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1167 #ifdef BLKDISCARD
1168 do {
1169 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1170 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1171 return 0;
1173 } while (errno == EINTR);
1175 ret = -errno;
1176 #endif
1177 } else {
1178 #ifdef CONFIG_XFS
1179 if (s->is_xfs) {
1180 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1182 #endif
1184 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1185 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1186 aiocb->aio_offset, aiocb->aio_nbytes);
1187 #endif
1190 ret = translate_err(ret);
1191 if (ret == -ENOTSUP) {
1192 s->has_discard = false;
1194 return ret;
1197 static int aio_worker(void *arg)
1199 RawPosixAIOData *aiocb = arg;
1200 ssize_t ret = 0;
1202 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1203 case QEMU_AIO_READ:
1204 ret = handle_aiocb_rw(aiocb);
1205 if (ret >= 0 && ret < aiocb->aio_nbytes) {
1206 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1207 0, aiocb->aio_nbytes - ret);
1209 ret = aiocb->aio_nbytes;
1211 if (ret == aiocb->aio_nbytes) {
1212 ret = 0;
1213 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1214 ret = -EINVAL;
1216 break;
1217 case QEMU_AIO_WRITE:
1218 ret = handle_aiocb_rw(aiocb);
1219 if (ret == aiocb->aio_nbytes) {
1220 ret = 0;
1221 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1222 ret = -EINVAL;
1224 break;
1225 case QEMU_AIO_FLUSH:
1226 ret = handle_aiocb_flush(aiocb);
1227 break;
1228 case QEMU_AIO_IOCTL:
1229 ret = handle_aiocb_ioctl(aiocb);
1230 break;
1231 case QEMU_AIO_DISCARD:
1232 ret = handle_aiocb_discard(aiocb);
1233 break;
1234 case QEMU_AIO_WRITE_ZEROES:
1235 ret = handle_aiocb_write_zeroes(aiocb);
1236 break;
1237 default:
1238 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1239 ret = -EINVAL;
1240 break;
1243 g_slice_free(RawPosixAIOData, aiocb);
1244 return ret;
1247 static int paio_submit_co(BlockDriverState *bs, int fd,
1248 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1249 int type)
1251 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1252 ThreadPool *pool;
1254 acb->bs = bs;
1255 acb->aio_type = type;
1256 acb->aio_fildes = fd;
1258 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1259 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1261 if (qiov) {
1262 acb->aio_iov = qiov->iov;
1263 acb->aio_niov = qiov->niov;
1264 assert(qiov->size == acb->aio_nbytes);
1267 trace_paio_submit_co(sector_num, nb_sectors, type);
1268 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1269 return thread_pool_submit_co(pool, aio_worker, acb);
1272 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1273 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1274 BlockCompletionFunc *cb, void *opaque, int type)
1276 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1277 ThreadPool *pool;
1279 acb->bs = bs;
1280 acb->aio_type = type;
1281 acb->aio_fildes = fd;
1283 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1284 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1286 if (qiov) {
1287 acb->aio_iov = qiov->iov;
1288 acb->aio_niov = qiov->niov;
1289 assert(qiov->size == acb->aio_nbytes);
1292 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1293 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1294 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1297 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1298 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1299 BlockCompletionFunc *cb, void *opaque, int type)
1301 BDRVRawState *s = bs->opaque;
1303 if (fd_open(bs) < 0)
1304 return NULL;
1307 * Check if the underlying device requires requests to be aligned,
1308 * and if the request we are trying to submit is aligned or not.
1309 * If this is the case tell the low-level driver that it needs
1310 * to copy the buffer.
1312 if (s->needs_alignment) {
1313 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1314 type |= QEMU_AIO_MISALIGNED;
1315 #ifdef CONFIG_LINUX_AIO
1316 } else if (s->use_aio) {
1317 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1318 nb_sectors, cb, opaque, type);
1319 #endif
1323 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1324 cb, opaque, type);
1327 static void raw_aio_plug(BlockDriverState *bs)
1329 #ifdef CONFIG_LINUX_AIO
1330 BDRVRawState *s = bs->opaque;
1331 if (s->use_aio) {
1332 laio_io_plug(bs, s->aio_ctx);
1334 #endif
1337 static void raw_aio_unplug(BlockDriverState *bs)
1339 #ifdef CONFIG_LINUX_AIO
1340 BDRVRawState *s = bs->opaque;
1341 if (s->use_aio) {
1342 laio_io_unplug(bs, s->aio_ctx, true);
1344 #endif
1347 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1349 #ifdef CONFIG_LINUX_AIO
1350 BDRVRawState *s = bs->opaque;
1351 if (s->use_aio) {
1352 laio_io_unplug(bs, s->aio_ctx, false);
1354 #endif
1357 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1358 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1359 BlockCompletionFunc *cb, void *opaque)
1361 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1362 cb, opaque, QEMU_AIO_READ);
1365 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1366 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1367 BlockCompletionFunc *cb, void *opaque)
1369 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1370 cb, opaque, QEMU_AIO_WRITE);
1373 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1374 BlockCompletionFunc *cb, void *opaque)
1376 BDRVRawState *s = bs->opaque;
1378 if (fd_open(bs) < 0)
1379 return NULL;
1381 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1384 static void raw_close(BlockDriverState *bs)
1386 BDRVRawState *s = bs->opaque;
1388 raw_detach_aio_context(bs);
1390 #ifdef CONFIG_LINUX_AIO
1391 if (s->use_aio) {
1392 laio_cleanup(s->aio_ctx);
1394 #endif
1395 if (s->fd >= 0) {
1396 qemu_close(s->fd);
1397 s->fd = -1;
1401 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1403 BDRVRawState *s = bs->opaque;
1404 struct stat st;
1406 if (fstat(s->fd, &st)) {
1407 return -errno;
1410 if (S_ISREG(st.st_mode)) {
1411 if (ftruncate(s->fd, offset) < 0) {
1412 return -errno;
1414 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1415 if (offset > raw_getlength(bs)) {
1416 return -EINVAL;
1418 } else {
1419 return -ENOTSUP;
1422 return 0;
1425 #ifdef __OpenBSD__
1426 static int64_t raw_getlength(BlockDriverState *bs)
1428 BDRVRawState *s = bs->opaque;
1429 int fd = s->fd;
1430 struct stat st;
1432 if (fstat(fd, &st))
1433 return -errno;
1434 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1435 struct disklabel dl;
1437 if (ioctl(fd, DIOCGDINFO, &dl))
1438 return -errno;
1439 return (uint64_t)dl.d_secsize *
1440 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1441 } else
1442 return st.st_size;
1444 #elif defined(__NetBSD__)
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 dkwedge_info dkw;
1456 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1457 return dkw.dkw_size * 512;
1458 } else {
1459 struct disklabel dl;
1461 if (ioctl(fd, DIOCGDINFO, &dl))
1462 return -errno;
1463 return (uint64_t)dl.d_secsize *
1464 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1466 } else
1467 return st.st_size;
1469 #elif defined(__sun__)
1470 static int64_t raw_getlength(BlockDriverState *bs)
1472 BDRVRawState *s = bs->opaque;
1473 struct dk_minfo minfo;
1474 int ret;
1475 int64_t size;
1477 ret = fd_open(bs);
1478 if (ret < 0) {
1479 return ret;
1483 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1485 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1486 if (ret != -1) {
1487 return minfo.dki_lbsize * minfo.dki_capacity;
1491 * There are reports that lseek on some devices fails, but
1492 * irc discussion said that contingency on contingency was overkill.
1494 size = lseek(s->fd, 0, SEEK_END);
1495 if (size < 0) {
1496 return -errno;
1498 return size;
1500 #elif defined(CONFIG_BSD)
1501 static int64_t raw_getlength(BlockDriverState *bs)
1503 BDRVRawState *s = bs->opaque;
1504 int fd = s->fd;
1505 int64_t size;
1506 struct stat sb;
1507 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1508 int reopened = 0;
1509 #endif
1510 int ret;
1512 ret = fd_open(bs);
1513 if (ret < 0)
1514 return ret;
1516 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1517 again:
1518 #endif
1519 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1520 #ifdef DIOCGMEDIASIZE
1521 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1522 #elif defined(DIOCGPART)
1524 struct partinfo pi;
1525 if (ioctl(fd, DIOCGPART, &pi) == 0)
1526 size = pi.media_size;
1527 else
1528 size = 0;
1530 if (size == 0)
1531 #endif
1532 #if defined(__APPLE__) && defined(__MACH__)
1534 uint64_t sectors = 0;
1535 uint32_t sector_size = 0;
1537 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1538 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1539 size = sectors * sector_size;
1540 } else {
1541 size = lseek(fd, 0LL, SEEK_END);
1542 if (size < 0) {
1543 return -errno;
1547 #else
1548 size = lseek(fd, 0LL, SEEK_END);
1549 if (size < 0) {
1550 return -errno;
1552 #endif
1553 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1554 switch(s->type) {
1555 case FTYPE_CD:
1556 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1557 if (size == 2048LL * (unsigned)-1)
1558 size = 0;
1559 /* XXX no disc? maybe we need to reopen... */
1560 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1561 reopened = 1;
1562 goto again;
1565 #endif
1566 } else {
1567 size = lseek(fd, 0, SEEK_END);
1568 if (size < 0) {
1569 return -errno;
1572 return size;
1574 #else
1575 static int64_t raw_getlength(BlockDriverState *bs)
1577 BDRVRawState *s = bs->opaque;
1578 int ret;
1579 int64_t size;
1581 ret = fd_open(bs);
1582 if (ret < 0) {
1583 return ret;
1586 size = lseek(s->fd, 0, SEEK_END);
1587 if (size < 0) {
1588 return -errno;
1590 return size;
1592 #endif
1594 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1596 struct stat st;
1597 BDRVRawState *s = bs->opaque;
1599 if (fstat(s->fd, &st) < 0) {
1600 return -errno;
1602 return (int64_t)st.st_blocks * 512;
1605 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1607 int fd;
1608 int result = 0;
1609 int64_t total_size = 0;
1610 bool nocow = false;
1611 PreallocMode prealloc;
1612 char *buf = NULL;
1613 Error *local_err = NULL;
1615 strstart(filename, "file:", &filename);
1617 /* Read out options */
1618 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1619 BDRV_SECTOR_SIZE);
1620 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1621 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1622 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1623 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1624 &local_err);
1625 g_free(buf);
1626 if (local_err) {
1627 error_propagate(errp, local_err);
1628 result = -EINVAL;
1629 goto out;
1632 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1633 0644);
1634 if (fd < 0) {
1635 result = -errno;
1636 error_setg_errno(errp, -result, "Could not create file");
1637 goto out;
1640 if (nocow) {
1641 #ifdef __linux__
1642 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1643 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1644 * will be ignored since any failure of this operation should not
1645 * block the left work.
1647 int attr;
1648 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1649 attr |= FS_NOCOW_FL;
1650 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1652 #endif
1655 if (ftruncate(fd, total_size) != 0) {
1656 result = -errno;
1657 error_setg_errno(errp, -result, "Could not resize file");
1658 goto out_close;
1661 switch (prealloc) {
1662 #ifdef CONFIG_POSIX_FALLOCATE
1663 case PREALLOC_MODE_FALLOC:
1664 /* posix_fallocate() doesn't set errno. */
1665 result = -posix_fallocate(fd, 0, total_size);
1666 if (result != 0) {
1667 error_setg_errno(errp, -result,
1668 "Could not preallocate data for the new file");
1670 break;
1671 #endif
1672 case PREALLOC_MODE_FULL:
1674 int64_t num = 0, left = total_size;
1675 buf = g_malloc0(65536);
1677 while (left > 0) {
1678 num = MIN(left, 65536);
1679 result = write(fd, buf, num);
1680 if (result < 0) {
1681 result = -errno;
1682 error_setg_errno(errp, -result,
1683 "Could not write to the new file");
1684 break;
1686 left -= result;
1688 if (result >= 0) {
1689 result = fsync(fd);
1690 if (result < 0) {
1691 result = -errno;
1692 error_setg_errno(errp, -result,
1693 "Could not flush new file to disk");
1696 g_free(buf);
1697 break;
1699 case PREALLOC_MODE_OFF:
1700 break;
1701 default:
1702 result = -EINVAL;
1703 error_setg(errp, "Unsupported preallocation mode: %s",
1704 PreallocMode_lookup[prealloc]);
1705 break;
1708 out_close:
1709 if (qemu_close(fd) != 0 && result == 0) {
1710 result = -errno;
1711 error_setg_errno(errp, -result, "Could not close the new file");
1713 out:
1714 return result;
1718 * Find allocation range in @bs around offset @start.
1719 * May change underlying file descriptor's file offset.
1720 * If @start is not in a hole, store @start in @data, and the
1721 * beginning of the next hole in @hole, and return 0.
1722 * If @start is in a non-trailing hole, store @start in @hole and the
1723 * beginning of the next non-hole in @data, and return 0.
1724 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1725 * If we can't find out, return a negative errno other than -ENXIO.
1727 static int find_allocation(BlockDriverState *bs, off_t start,
1728 off_t *data, off_t *hole)
1730 #if defined SEEK_HOLE && defined SEEK_DATA
1731 BDRVRawState *s = bs->opaque;
1732 off_t offs;
1735 * SEEK_DATA cases:
1736 * D1. offs == start: start is in data
1737 * D2. offs > start: start is in a hole, next data at offs
1738 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1739 * or start is beyond EOF
1740 * If the latter happens, the file has been truncated behind
1741 * our back since we opened it. All bets are off then.
1742 * Treating like a trailing hole is simplest.
1743 * D4. offs < 0, errno != ENXIO: we learned nothing
1745 offs = lseek(s->fd, start, SEEK_DATA);
1746 if (offs < 0) {
1747 return -errno; /* D3 or D4 */
1749 assert(offs >= start);
1751 if (offs > start) {
1752 /* D2: in hole, next data at offs */
1753 *hole = start;
1754 *data = offs;
1755 return 0;
1758 /* D1: in data, end not yet known */
1761 * SEEK_HOLE cases:
1762 * H1. offs == start: start is in a hole
1763 * If this happens here, a hole has been dug behind our back
1764 * since the previous lseek().
1765 * H2. offs > start: either start is in data, next hole at offs,
1766 * or start is in trailing hole, EOF at offs
1767 * Linux treats trailing holes like any other hole: offs ==
1768 * start. Solaris seeks to EOF instead: offs > start (blech).
1769 * If that happens here, a hole has been dug behind our back
1770 * since the previous lseek().
1771 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1772 * If this happens, the file has been truncated behind our
1773 * back since we opened it. Treat it like a trailing hole.
1774 * H4. offs < 0, errno != ENXIO: we learned nothing
1775 * Pretend we know nothing at all, i.e. "forget" about D1.
1777 offs = lseek(s->fd, start, SEEK_HOLE);
1778 if (offs < 0) {
1779 return -errno; /* D1 and (H3 or H4) */
1781 assert(offs >= start);
1783 if (offs > start) {
1785 * D1 and H2: either in data, next hole at offs, or it was in
1786 * data but is now in a trailing hole. In the latter case,
1787 * all bets are off. Treating it as if it there was data all
1788 * the way to EOF is safe, so simply do that.
1790 *data = start;
1791 *hole = offs;
1792 return 0;
1795 /* D1 and H1 */
1796 return -EBUSY;
1797 #else
1798 return -ENOTSUP;
1799 #endif
1803 * Returns the allocation status of the specified sectors.
1805 * If 'sector_num' is beyond the end of the disk image the return value is 0
1806 * and 'pnum' is set to 0.
1808 * 'pnum' is set to the number of sectors (including and immediately following
1809 * the specified sector) that are known to be in the same
1810 * allocated/unallocated state.
1812 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1813 * beyond the end of the disk image it will be clamped.
1815 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1816 int64_t sector_num,
1817 int nb_sectors, int *pnum)
1819 off_t start, data = 0, hole = 0;
1820 int64_t total_size;
1821 int ret;
1823 ret = fd_open(bs);
1824 if (ret < 0) {
1825 return ret;
1828 start = sector_num * BDRV_SECTOR_SIZE;
1829 total_size = bdrv_getlength(bs);
1830 if (total_size < 0) {
1831 return total_size;
1832 } else if (start >= total_size) {
1833 *pnum = 0;
1834 return 0;
1835 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1836 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1839 ret = find_allocation(bs, start, &data, &hole);
1840 if (ret == -ENXIO) {
1841 /* Trailing hole */
1842 *pnum = nb_sectors;
1843 ret = BDRV_BLOCK_ZERO;
1844 } else if (ret < 0) {
1845 /* No info available, so pretend there are no holes */
1846 *pnum = nb_sectors;
1847 ret = BDRV_BLOCK_DATA;
1848 } else if (data == start) {
1849 /* On a data extent, compute sectors to the end of the extent. */
1850 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1851 ret = BDRV_BLOCK_DATA;
1852 } else {
1853 /* On a hole, compute sectors to the beginning of the next extent. */
1854 assert(hole == start);
1855 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1856 ret = BDRV_BLOCK_ZERO;
1858 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1861 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1862 int64_t sector_num, int nb_sectors,
1863 BlockCompletionFunc *cb, void *opaque)
1865 BDRVRawState *s = bs->opaque;
1867 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1868 cb, opaque, QEMU_AIO_DISCARD);
1871 static int coroutine_fn raw_co_write_zeroes(
1872 BlockDriverState *bs, int64_t sector_num,
1873 int nb_sectors, BdrvRequestFlags flags)
1875 BDRVRawState *s = bs->opaque;
1877 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1878 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1879 QEMU_AIO_WRITE_ZEROES);
1880 } else if (s->discard_zeroes) {
1881 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1882 QEMU_AIO_DISCARD);
1884 return -ENOTSUP;
1887 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1889 BDRVRawState *s = bs->opaque;
1891 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1892 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1893 return 0;
1896 static QemuOptsList raw_create_opts = {
1897 .name = "raw-create-opts",
1898 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1899 .desc = {
1901 .name = BLOCK_OPT_SIZE,
1902 .type = QEMU_OPT_SIZE,
1903 .help = "Virtual disk size"
1906 .name = BLOCK_OPT_NOCOW,
1907 .type = QEMU_OPT_BOOL,
1908 .help = "Turn off copy-on-write (valid only on btrfs)"
1911 .name = BLOCK_OPT_PREALLOC,
1912 .type = QEMU_OPT_STRING,
1913 .help = "Preallocation mode (allowed values: off, falloc, full)"
1915 { /* end of list */ }
1919 BlockDriver bdrv_file = {
1920 .format_name = "file",
1921 .protocol_name = "file",
1922 .instance_size = sizeof(BDRVRawState),
1923 .bdrv_needs_filename = true,
1924 .bdrv_probe = NULL, /* no probe for protocols */
1925 .bdrv_parse_filename = raw_parse_filename,
1926 .bdrv_file_open = raw_open,
1927 .bdrv_reopen_prepare = raw_reopen_prepare,
1928 .bdrv_reopen_commit = raw_reopen_commit,
1929 .bdrv_reopen_abort = raw_reopen_abort,
1930 .bdrv_close = raw_close,
1931 .bdrv_create = raw_create,
1932 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1933 .bdrv_co_get_block_status = raw_co_get_block_status,
1934 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1936 .bdrv_aio_readv = raw_aio_readv,
1937 .bdrv_aio_writev = raw_aio_writev,
1938 .bdrv_aio_flush = raw_aio_flush,
1939 .bdrv_aio_discard = raw_aio_discard,
1940 .bdrv_refresh_limits = raw_refresh_limits,
1941 .bdrv_io_plug = raw_aio_plug,
1942 .bdrv_io_unplug = raw_aio_unplug,
1943 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1945 .bdrv_truncate = raw_truncate,
1946 .bdrv_getlength = raw_getlength,
1947 .bdrv_get_info = raw_get_info,
1948 .bdrv_get_allocated_file_size
1949 = raw_get_allocated_file_size,
1951 .bdrv_detach_aio_context = raw_detach_aio_context,
1952 .bdrv_attach_aio_context = raw_attach_aio_context,
1954 .create_opts = &raw_create_opts,
1957 /***********************************************/
1958 /* host device */
1960 #if defined(__APPLE__) && defined(__MACH__)
1961 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1962 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1964 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1966 kern_return_t kernResult;
1967 mach_port_t masterPort;
1968 CFMutableDictionaryRef classesToMatch;
1970 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1971 if ( KERN_SUCCESS != kernResult ) {
1972 printf( "IOMasterPort returned %d\n", kernResult );
1975 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1976 if ( classesToMatch == NULL ) {
1977 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1978 } else {
1979 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1981 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1982 if ( KERN_SUCCESS != kernResult )
1984 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1987 return kernResult;
1990 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1992 io_object_t nextMedia;
1993 kern_return_t kernResult = KERN_FAILURE;
1994 *bsdPath = '\0';
1995 nextMedia = IOIteratorNext( mediaIterator );
1996 if ( nextMedia )
1998 CFTypeRef bsdPathAsCFString;
1999 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2000 if ( bsdPathAsCFString ) {
2001 size_t devPathLength;
2002 strcpy( bsdPath, _PATH_DEV );
2003 strcat( bsdPath, "r" );
2004 devPathLength = strlen( bsdPath );
2005 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2006 kernResult = KERN_SUCCESS;
2008 CFRelease( bsdPathAsCFString );
2010 IOObjectRelease( nextMedia );
2013 return kernResult;
2016 #endif
2018 static int hdev_probe_device(const char *filename)
2020 struct stat st;
2022 /* allow a dedicated CD-ROM driver to match with a higher priority */
2023 if (strstart(filename, "/dev/cdrom", NULL))
2024 return 50;
2026 if (stat(filename, &st) >= 0 &&
2027 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2028 return 100;
2031 return 0;
2034 static int check_hdev_writable(BDRVRawState *s)
2036 #if defined(BLKROGET)
2037 /* Linux block devices can be configured "read-only" using blockdev(8).
2038 * This is independent of device node permissions and therefore open(2)
2039 * with O_RDWR succeeds. Actual writes fail with EPERM.
2041 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2042 * check for read-only block devices so that Linux block devices behave
2043 * properly.
2045 struct stat st;
2046 int readonly = 0;
2048 if (fstat(s->fd, &st)) {
2049 return -errno;
2052 if (!S_ISBLK(st.st_mode)) {
2053 return 0;
2056 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2057 return -errno;
2060 if (readonly) {
2061 return -EACCES;
2063 #endif /* defined(BLKROGET) */
2064 return 0;
2067 static void hdev_parse_filename(const char *filename, QDict *options,
2068 Error **errp)
2070 /* The prefix is optional, just as for "file". */
2071 strstart(filename, "host_device:", &filename);
2073 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2076 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2077 Error **errp)
2079 BDRVRawState *s = bs->opaque;
2080 Error *local_err = NULL;
2081 int ret;
2082 const char *filename = qdict_get_str(options, "filename");
2084 #if defined(__APPLE__) && defined(__MACH__)
2085 if (strstart(filename, "/dev/cdrom", NULL)) {
2086 kern_return_t kernResult;
2087 io_iterator_t mediaIterator;
2088 char bsdPath[ MAXPATHLEN ];
2089 int fd;
2091 kernResult = FindEjectableCDMedia( &mediaIterator );
2092 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
2094 if ( bsdPath[ 0 ] != '\0' ) {
2095 strcat(bsdPath,"s0");
2096 /* some CDs don't have a partition 0 */
2097 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
2098 if (fd < 0) {
2099 bsdPath[strlen(bsdPath)-1] = '1';
2100 } else {
2101 qemu_close(fd);
2103 filename = bsdPath;
2104 qdict_put(options, "filename", qstring_from_str(filename));
2107 if ( mediaIterator )
2108 IOObjectRelease( mediaIterator );
2110 #endif
2112 s->type = FTYPE_FILE;
2113 #if defined(__linux__)
2115 char resolved_path[ MAXPATHLEN ], *temp;
2117 temp = realpath(filename, resolved_path);
2118 if (temp && strstart(temp, "/dev/sg", NULL)) {
2119 bs->sg = 1;
2122 #endif
2124 ret = raw_open_common(bs, options, flags, 0, &local_err);
2125 if (ret < 0) {
2126 if (local_err) {
2127 error_propagate(errp, local_err);
2129 return ret;
2132 if (flags & BDRV_O_RDWR) {
2133 ret = check_hdev_writable(s);
2134 if (ret < 0) {
2135 raw_close(bs);
2136 error_setg_errno(errp, -ret, "The device is not writable");
2137 return ret;
2141 return ret;
2144 #if defined(__linux__)
2145 /* Note: we do not have a reliable method to detect if the floppy is
2146 present. The current method is to try to open the floppy at every
2147 I/O and to keep it opened during a few hundreds of ms. */
2148 static int fd_open(BlockDriverState *bs)
2150 BDRVRawState *s = bs->opaque;
2151 int last_media_present;
2153 if (s->type != FTYPE_FD)
2154 return 0;
2155 last_media_present = (s->fd >= 0);
2156 if (s->fd >= 0 &&
2157 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
2158 qemu_close(s->fd);
2159 s->fd = -1;
2160 #ifdef DEBUG_FLOPPY
2161 printf("Floppy closed\n");
2162 #endif
2164 if (s->fd < 0) {
2165 if (s->fd_got_error &&
2166 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
2167 #ifdef DEBUG_FLOPPY
2168 printf("No floppy (open delayed)\n");
2169 #endif
2170 return -EIO;
2172 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
2173 if (s->fd < 0) {
2174 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2175 s->fd_got_error = 1;
2176 if (last_media_present)
2177 s->fd_media_changed = 1;
2178 #ifdef DEBUG_FLOPPY
2179 printf("No floppy\n");
2180 #endif
2181 return -EIO;
2183 #ifdef DEBUG_FLOPPY
2184 printf("Floppy opened\n");
2185 #endif
2187 if (!last_media_present)
2188 s->fd_media_changed = 1;
2189 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2190 s->fd_got_error = 0;
2191 return 0;
2194 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2196 BDRVRawState *s = bs->opaque;
2198 return ioctl(s->fd, req, buf);
2201 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2202 unsigned long int req, void *buf,
2203 BlockCompletionFunc *cb, void *opaque)
2205 BDRVRawState *s = bs->opaque;
2206 RawPosixAIOData *acb;
2207 ThreadPool *pool;
2209 if (fd_open(bs) < 0)
2210 return NULL;
2212 acb = g_slice_new(RawPosixAIOData);
2213 acb->bs = bs;
2214 acb->aio_type = QEMU_AIO_IOCTL;
2215 acb->aio_fildes = s->fd;
2216 acb->aio_offset = 0;
2217 acb->aio_ioctl_buf = buf;
2218 acb->aio_ioctl_cmd = req;
2219 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2220 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2223 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2224 static int fd_open(BlockDriverState *bs)
2226 BDRVRawState *s = bs->opaque;
2228 /* this is just to ensure s->fd is sane (its called by io ops) */
2229 if (s->fd >= 0)
2230 return 0;
2231 return -EIO;
2233 #else /* !linux && !FreeBSD */
2235 static int fd_open(BlockDriverState *bs)
2237 return 0;
2240 #endif /* !linux && !FreeBSD */
2242 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2243 int64_t sector_num, int nb_sectors,
2244 BlockCompletionFunc *cb, void *opaque)
2246 BDRVRawState *s = bs->opaque;
2248 if (fd_open(bs) < 0) {
2249 return NULL;
2251 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2252 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2255 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2256 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2258 BDRVRawState *s = bs->opaque;
2259 int rc;
2261 rc = fd_open(bs);
2262 if (rc < 0) {
2263 return rc;
2265 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2266 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2267 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2268 } else if (s->discard_zeroes) {
2269 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2270 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2272 return -ENOTSUP;
2275 static int hdev_create(const char *filename, QemuOpts *opts,
2276 Error **errp)
2278 int fd;
2279 int ret = 0;
2280 struct stat stat_buf;
2281 int64_t total_size = 0;
2282 bool has_prefix;
2284 /* This function is used by all three protocol block drivers and therefore
2285 * any of these three prefixes may be given.
2286 * The return value has to be stored somewhere, otherwise this is an error
2287 * due to -Werror=unused-value. */
2288 has_prefix =
2289 strstart(filename, "host_device:", &filename) ||
2290 strstart(filename, "host_cdrom:" , &filename) ||
2291 strstart(filename, "host_floppy:", &filename);
2293 (void)has_prefix;
2295 /* Read out options */
2296 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2297 BDRV_SECTOR_SIZE);
2299 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2300 if (fd < 0) {
2301 ret = -errno;
2302 error_setg_errno(errp, -ret, "Could not open device");
2303 return ret;
2306 if (fstat(fd, &stat_buf) < 0) {
2307 ret = -errno;
2308 error_setg_errno(errp, -ret, "Could not stat device");
2309 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2310 error_setg(errp,
2311 "The given file is neither a block nor a character device");
2312 ret = -ENODEV;
2313 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2314 error_setg(errp, "Device is too small");
2315 ret = -ENOSPC;
2318 qemu_close(fd);
2319 return ret;
2322 static BlockDriver bdrv_host_device = {
2323 .format_name = "host_device",
2324 .protocol_name = "host_device",
2325 .instance_size = sizeof(BDRVRawState),
2326 .bdrv_needs_filename = true,
2327 .bdrv_probe_device = hdev_probe_device,
2328 .bdrv_parse_filename = hdev_parse_filename,
2329 .bdrv_file_open = hdev_open,
2330 .bdrv_close = raw_close,
2331 .bdrv_reopen_prepare = raw_reopen_prepare,
2332 .bdrv_reopen_commit = raw_reopen_commit,
2333 .bdrv_reopen_abort = raw_reopen_abort,
2334 .bdrv_create = hdev_create,
2335 .create_opts = &raw_create_opts,
2336 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2338 .bdrv_aio_readv = raw_aio_readv,
2339 .bdrv_aio_writev = raw_aio_writev,
2340 .bdrv_aio_flush = raw_aio_flush,
2341 .bdrv_aio_discard = hdev_aio_discard,
2342 .bdrv_refresh_limits = raw_refresh_limits,
2343 .bdrv_io_plug = raw_aio_plug,
2344 .bdrv_io_unplug = raw_aio_unplug,
2345 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2347 .bdrv_truncate = raw_truncate,
2348 .bdrv_getlength = raw_getlength,
2349 .bdrv_get_info = raw_get_info,
2350 .bdrv_get_allocated_file_size
2351 = raw_get_allocated_file_size,
2352 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2353 .bdrv_probe_geometry = hdev_probe_geometry,
2355 .bdrv_detach_aio_context = raw_detach_aio_context,
2356 .bdrv_attach_aio_context = raw_attach_aio_context,
2358 /* generic scsi device */
2359 #ifdef __linux__
2360 .bdrv_ioctl = hdev_ioctl,
2361 .bdrv_aio_ioctl = hdev_aio_ioctl,
2362 #endif
2365 #ifdef __linux__
2366 static void floppy_parse_filename(const char *filename, QDict *options,
2367 Error **errp)
2369 /* The prefix is optional, just as for "file". */
2370 strstart(filename, "host_floppy:", &filename);
2372 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2375 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2376 Error **errp)
2378 BDRVRawState *s = bs->opaque;
2379 Error *local_err = NULL;
2380 int ret;
2382 s->type = FTYPE_FD;
2384 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2385 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2386 if (ret) {
2387 if (local_err) {
2388 error_propagate(errp, local_err);
2390 return ret;
2393 /* close fd so that we can reopen it as needed */
2394 qemu_close(s->fd);
2395 s->fd = -1;
2396 s->fd_media_changed = 1;
2398 error_report("Host floppy pass-through is deprecated");
2399 error_printf("Support for it will be removed in a future release.\n");
2400 return 0;
2403 static int floppy_probe_device(const char *filename)
2405 int fd, ret;
2406 int prio = 0;
2407 struct floppy_struct fdparam;
2408 struct stat st;
2410 if (strstart(filename, "/dev/fd", NULL) &&
2411 !strstart(filename, "/dev/fdset/", NULL)) {
2412 prio = 50;
2415 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2416 if (fd < 0) {
2417 goto out;
2419 ret = fstat(fd, &st);
2420 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2421 goto outc;
2424 /* Attempt to detect via a floppy specific ioctl */
2425 ret = ioctl(fd, FDGETPRM, &fdparam);
2426 if (ret >= 0)
2427 prio = 100;
2429 outc:
2430 qemu_close(fd);
2431 out:
2432 return prio;
2436 static int floppy_is_inserted(BlockDriverState *bs)
2438 return fd_open(bs) >= 0;
2441 static int floppy_media_changed(BlockDriverState *bs)
2443 BDRVRawState *s = bs->opaque;
2444 int ret;
2447 * XXX: we do not have a true media changed indication.
2448 * It does not work if the floppy is changed without trying to read it.
2450 fd_open(bs);
2451 ret = s->fd_media_changed;
2452 s->fd_media_changed = 0;
2453 #ifdef DEBUG_FLOPPY
2454 printf("Floppy changed=%d\n", ret);
2455 #endif
2456 return ret;
2459 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2461 BDRVRawState *s = bs->opaque;
2462 int fd;
2464 if (s->fd >= 0) {
2465 qemu_close(s->fd);
2466 s->fd = -1;
2468 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2469 if (fd >= 0) {
2470 if (ioctl(fd, FDEJECT, 0) < 0)
2471 perror("FDEJECT");
2472 qemu_close(fd);
2476 static BlockDriver bdrv_host_floppy = {
2477 .format_name = "host_floppy",
2478 .protocol_name = "host_floppy",
2479 .instance_size = sizeof(BDRVRawState),
2480 .bdrv_needs_filename = true,
2481 .bdrv_probe_device = floppy_probe_device,
2482 .bdrv_parse_filename = floppy_parse_filename,
2483 .bdrv_file_open = floppy_open,
2484 .bdrv_close = raw_close,
2485 .bdrv_reopen_prepare = raw_reopen_prepare,
2486 .bdrv_reopen_commit = raw_reopen_commit,
2487 .bdrv_reopen_abort = raw_reopen_abort,
2488 .bdrv_create = hdev_create,
2489 .create_opts = &raw_create_opts,
2491 .bdrv_aio_readv = raw_aio_readv,
2492 .bdrv_aio_writev = raw_aio_writev,
2493 .bdrv_aio_flush = raw_aio_flush,
2494 .bdrv_refresh_limits = raw_refresh_limits,
2495 .bdrv_io_plug = raw_aio_plug,
2496 .bdrv_io_unplug = raw_aio_unplug,
2497 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2499 .bdrv_truncate = raw_truncate,
2500 .bdrv_getlength = raw_getlength,
2501 .has_variable_length = true,
2502 .bdrv_get_allocated_file_size
2503 = raw_get_allocated_file_size,
2505 .bdrv_detach_aio_context = raw_detach_aio_context,
2506 .bdrv_attach_aio_context = raw_attach_aio_context,
2508 /* removable device support */
2509 .bdrv_is_inserted = floppy_is_inserted,
2510 .bdrv_media_changed = floppy_media_changed,
2511 .bdrv_eject = floppy_eject,
2513 #endif
2515 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2516 static void cdrom_parse_filename(const char *filename, QDict *options,
2517 Error **errp)
2519 /* The prefix is optional, just as for "file". */
2520 strstart(filename, "host_cdrom:", &filename);
2522 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2524 #endif
2526 #ifdef __linux__
2527 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2528 Error **errp)
2530 BDRVRawState *s = bs->opaque;
2531 Error *local_err = NULL;
2532 int ret;
2534 s->type = FTYPE_CD;
2536 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2537 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2538 if (local_err) {
2539 error_propagate(errp, local_err);
2541 return ret;
2544 static int cdrom_probe_device(const char *filename)
2546 int fd, ret;
2547 int prio = 0;
2548 struct stat st;
2550 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2551 if (fd < 0) {
2552 goto out;
2554 ret = fstat(fd, &st);
2555 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2556 goto outc;
2559 /* Attempt to detect via a CDROM specific ioctl */
2560 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2561 if (ret >= 0)
2562 prio = 100;
2564 outc:
2565 qemu_close(fd);
2566 out:
2567 return prio;
2570 static int cdrom_is_inserted(BlockDriverState *bs)
2572 BDRVRawState *s = bs->opaque;
2573 int ret;
2575 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2576 if (ret == CDS_DISC_OK)
2577 return 1;
2578 return 0;
2581 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2583 BDRVRawState *s = bs->opaque;
2585 if (eject_flag) {
2586 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2587 perror("CDROMEJECT");
2588 } else {
2589 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2590 perror("CDROMEJECT");
2594 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2596 BDRVRawState *s = bs->opaque;
2598 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2600 * Note: an error can happen if the distribution automatically
2601 * mounts the CD-ROM
2603 /* perror("CDROM_LOCKDOOR"); */
2607 static BlockDriver bdrv_host_cdrom = {
2608 .format_name = "host_cdrom",
2609 .protocol_name = "host_cdrom",
2610 .instance_size = sizeof(BDRVRawState),
2611 .bdrv_needs_filename = true,
2612 .bdrv_probe_device = cdrom_probe_device,
2613 .bdrv_parse_filename = cdrom_parse_filename,
2614 .bdrv_file_open = cdrom_open,
2615 .bdrv_close = raw_close,
2616 .bdrv_reopen_prepare = raw_reopen_prepare,
2617 .bdrv_reopen_commit = raw_reopen_commit,
2618 .bdrv_reopen_abort = raw_reopen_abort,
2619 .bdrv_create = hdev_create,
2620 .create_opts = &raw_create_opts,
2622 .bdrv_aio_readv = raw_aio_readv,
2623 .bdrv_aio_writev = raw_aio_writev,
2624 .bdrv_aio_flush = raw_aio_flush,
2625 .bdrv_refresh_limits = raw_refresh_limits,
2626 .bdrv_io_plug = raw_aio_plug,
2627 .bdrv_io_unplug = raw_aio_unplug,
2628 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2630 .bdrv_truncate = raw_truncate,
2631 .bdrv_getlength = raw_getlength,
2632 .has_variable_length = true,
2633 .bdrv_get_allocated_file_size
2634 = raw_get_allocated_file_size,
2636 .bdrv_detach_aio_context = raw_detach_aio_context,
2637 .bdrv_attach_aio_context = raw_attach_aio_context,
2639 /* removable device support */
2640 .bdrv_is_inserted = cdrom_is_inserted,
2641 .bdrv_eject = cdrom_eject,
2642 .bdrv_lock_medium = cdrom_lock_medium,
2644 /* generic scsi device */
2645 .bdrv_ioctl = hdev_ioctl,
2646 .bdrv_aio_ioctl = hdev_aio_ioctl,
2648 #endif /* __linux__ */
2650 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2651 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2652 Error **errp)
2654 BDRVRawState *s = bs->opaque;
2655 Error *local_err = NULL;
2656 int ret;
2658 s->type = FTYPE_CD;
2660 ret = raw_open_common(bs, options, flags, 0, &local_err);
2661 if (ret) {
2662 if (local_err) {
2663 error_propagate(errp, local_err);
2665 return ret;
2668 /* make sure the door isn't locked at this time */
2669 ioctl(s->fd, CDIOCALLOW);
2670 return 0;
2673 static int cdrom_probe_device(const char *filename)
2675 if (strstart(filename, "/dev/cd", NULL) ||
2676 strstart(filename, "/dev/acd", NULL))
2677 return 100;
2678 return 0;
2681 static int cdrom_reopen(BlockDriverState *bs)
2683 BDRVRawState *s = bs->opaque;
2684 int fd;
2687 * Force reread of possibly changed/newly loaded disc,
2688 * FreeBSD seems to not notice sometimes...
2690 if (s->fd >= 0)
2691 qemu_close(s->fd);
2692 fd = qemu_open(bs->filename, s->open_flags, 0644);
2693 if (fd < 0) {
2694 s->fd = -1;
2695 return -EIO;
2697 s->fd = fd;
2699 /* make sure the door isn't locked at this time */
2700 ioctl(s->fd, CDIOCALLOW);
2701 return 0;
2704 static int cdrom_is_inserted(BlockDriverState *bs)
2706 return raw_getlength(bs) > 0;
2709 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2711 BDRVRawState *s = bs->opaque;
2713 if (s->fd < 0)
2714 return;
2716 (void) ioctl(s->fd, CDIOCALLOW);
2718 if (eject_flag) {
2719 if (ioctl(s->fd, CDIOCEJECT) < 0)
2720 perror("CDIOCEJECT");
2721 } else {
2722 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2723 perror("CDIOCCLOSE");
2726 cdrom_reopen(bs);
2729 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2731 BDRVRawState *s = bs->opaque;
2733 if (s->fd < 0)
2734 return;
2735 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2737 * Note: an error can happen if the distribution automatically
2738 * mounts the CD-ROM
2740 /* perror("CDROM_LOCKDOOR"); */
2744 static BlockDriver bdrv_host_cdrom = {
2745 .format_name = "host_cdrom",
2746 .protocol_name = "host_cdrom",
2747 .instance_size = sizeof(BDRVRawState),
2748 .bdrv_needs_filename = true,
2749 .bdrv_probe_device = cdrom_probe_device,
2750 .bdrv_parse_filename = cdrom_parse_filename,
2751 .bdrv_file_open = cdrom_open,
2752 .bdrv_close = raw_close,
2753 .bdrv_reopen_prepare = raw_reopen_prepare,
2754 .bdrv_reopen_commit = raw_reopen_commit,
2755 .bdrv_reopen_abort = raw_reopen_abort,
2756 .bdrv_create = hdev_create,
2757 .create_opts = &raw_create_opts,
2759 .bdrv_aio_readv = raw_aio_readv,
2760 .bdrv_aio_writev = raw_aio_writev,
2761 .bdrv_aio_flush = raw_aio_flush,
2762 .bdrv_refresh_limits = raw_refresh_limits,
2763 .bdrv_io_plug = raw_aio_plug,
2764 .bdrv_io_unplug = raw_aio_unplug,
2765 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2767 .bdrv_truncate = raw_truncate,
2768 .bdrv_getlength = raw_getlength,
2769 .has_variable_length = true,
2770 .bdrv_get_allocated_file_size
2771 = raw_get_allocated_file_size,
2773 .bdrv_detach_aio_context = raw_detach_aio_context,
2774 .bdrv_attach_aio_context = raw_attach_aio_context,
2776 /* removable device support */
2777 .bdrv_is_inserted = cdrom_is_inserted,
2778 .bdrv_eject = cdrom_eject,
2779 .bdrv_lock_medium = cdrom_lock_medium,
2781 #endif /* __FreeBSD__ */
2783 static void bdrv_file_init(void)
2786 * Register all the drivers. Note that order is important, the driver
2787 * registered last will get probed first.
2789 bdrv_register(&bdrv_file);
2790 bdrv_register(&bdrv_host_device);
2791 #ifdef __linux__
2792 bdrv_register(&bdrv_host_floppy);
2793 bdrv_register(&bdrv_host_cdrom);
2794 #endif
2795 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2796 bdrv_register(&bdrv_host_cdrom);
2797 #endif
2800 block_init(bdrv_file_init);