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
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
30 #include "block/thread-pool.h"
33 #include "qapi/util.h"
35 #if defined(__APPLE__) && (__MACH__)
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>
48 #define _POSIX_PTHREAD_SEMANTICS 1
52 #include <sys/types.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
60 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
63 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
64 #include <linux/falloc.h>
66 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
72 #include <sys/ioctl.h>
73 #include <sys/disklabel.h>
78 #include <sys/ioctl.h>
79 #include <sys/disklabel.h>
85 #include <sys/ioctl.h>
86 #include <sys/diskslice.h>
93 //#define DEBUG_FLOPPY
96 #if defined(DEBUG_BLOCK)
97 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
98 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
100 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
103 /* OS X does not have O_DSYNC */
106 #define O_DSYNC O_SYNC
107 #elif defined(O_FSYNC)
108 #define O_DSYNC O_FSYNC
112 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
114 #define O_DIRECT O_DSYNC
121 /* if the FD is not accessed during that time (in ns), we try to
122 reopen it to see if the disk has been changed */
123 #define FD_OPEN_TIMEOUT (1000000000)
125 #define MAX_BLOCKSIZE 4096
127 typedef struct BDRVRawState {
133 #if defined(__linux__)
134 /* linux floppy specific */
135 int64_t fd_open_time;
136 int64_t fd_error_time;
138 int fd_media_changed;
140 #ifdef CONFIG_LINUX_AIO
148 bool has_write_zeroes:1;
149 bool discard_zeroes:1;
151 bool needs_alignment;
154 typedef struct BDRVRawReopenState {
157 #ifdef CONFIG_LINUX_AIO
160 } BDRVRawReopenState;
162 static int fd_open(BlockDriverState *bs);
163 static int64_t raw_getlength(BlockDriverState *bs);
165 typedef struct RawPosixAIOData {
166 BlockDriverState *bs;
169 struct iovec *aio_iov;
174 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
179 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
180 static int cdrom_reopen(BlockDriverState *bs);
183 #if defined(__NetBSD__)
184 static int raw_normalize_devicepath(const char **filename)
186 static char namebuf[PATH_MAX];
187 const char *dp, *fname;
191 dp = strrchr(fname, '/');
192 if (lstat(fname, &sb) < 0) {
193 fprintf(stderr, "%s: stat failed: %s\n",
194 fname, strerror(errno));
198 if (!S_ISBLK(sb.st_mode)) {
203 snprintf(namebuf, PATH_MAX, "r%s", fname);
205 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
206 (int)(dp - fname), fname, dp + 1);
208 fprintf(stderr, "%s is a block device", fname);
210 fprintf(stderr, ", using %s\n", *filename);
215 static int raw_normalize_devicepath(const char **filename)
221 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
223 BDRVRawState *s = bs->opaque;
225 unsigned int sector_size;
227 /* For /dev/sg devices the alignment is not really used.
228 With buffered I/O, we don't have any restrictions. */
229 if (bs->sg || !s->needs_alignment) {
230 bs->request_alignment = 1;
235 /* Try a few ioctls to get the right size */
236 bs->request_alignment = 0;
240 if (ioctl(fd, BLKSSZGET, §or_size) >= 0) {
241 bs->request_alignment = sector_size;
244 #ifdef DKIOCGETBLOCKSIZE
245 if (ioctl(fd, DKIOCGETBLOCKSIZE, §or_size) >= 0) {
246 bs->request_alignment = sector_size;
249 #ifdef DIOCGSECTORSIZE
250 if (ioctl(fd, DIOCGSECTORSIZE, §or_size) >= 0) {
251 bs->request_alignment = sector_size;
257 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
258 bs->request_alignment = da.d_miniosz;
259 /* The kernel returns wrong information for d_mem */
260 /* s->buf_align = da.d_mem; */
265 /* If we could not get the sizes so far, we can only guess them */
268 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
269 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
270 if (pread(fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
271 s->buf_align = align;
278 if (!bs->request_alignment) {
280 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
281 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
282 if (pread(fd, buf, align, 0) >= 0) {
283 bs->request_alignment = align;
290 if (!s->buf_align || !bs->request_alignment) {
291 error_setg(errp, "Could not find working O_DIRECT alignment. "
292 "Try cache.direct=off.");
296 static void raw_parse_flags(int bdrv_flags, int *open_flags)
298 assert(open_flags != NULL);
300 *open_flags |= O_BINARY;
301 *open_flags &= ~O_ACCMODE;
302 if (bdrv_flags & BDRV_O_RDWR) {
303 *open_flags |= O_RDWR;
305 *open_flags |= O_RDONLY;
308 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
309 * and O_DIRECT for no caching. */
310 if ((bdrv_flags & BDRV_O_NOCACHE)) {
311 *open_flags |= O_DIRECT;
315 static void raw_detach_aio_context(BlockDriverState *bs)
317 #ifdef CONFIG_LINUX_AIO
318 BDRVRawState *s = bs->opaque;
321 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
326 static void raw_attach_aio_context(BlockDriverState *bs,
327 AioContext *new_context)
329 #ifdef CONFIG_LINUX_AIO
330 BDRVRawState *s = bs->opaque;
333 laio_attach_aio_context(s->aio_ctx, new_context);
338 #ifdef CONFIG_LINUX_AIO
339 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
342 assert(aio_ctx != NULL);
343 assert(use_aio != NULL);
345 * Currently Linux do AIO only for files opened with O_DIRECT
346 * specified so check NOCACHE flag too
348 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
349 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
351 /* if non-NULL, laio_init() has already been run */
352 if (*aio_ctx == NULL) {
353 *aio_ctx = laio_init();
370 static void raw_parse_filename(const char *filename, QDict *options,
373 /* The filename does not have to be prefixed by the protocol name, since
374 * "file" is the default protocol; therefore, the return value of this
375 * function call can be ignored. */
376 strstart(filename, "file:", &filename);
378 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
381 static QemuOptsList raw_runtime_opts = {
383 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
387 .type = QEMU_OPT_STRING,
388 .help = "File name of the image",
390 { /* end of list */ }
394 static int raw_open_common(BlockDriverState *bs, QDict *options,
395 int bdrv_flags, int open_flags, Error **errp)
397 BDRVRawState *s = bs->opaque;
399 Error *local_err = NULL;
400 const char *filename = NULL;
404 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
405 qemu_opts_absorb_qdict(opts, options, &local_err);
407 error_propagate(errp, local_err);
412 filename = qemu_opt_get(opts, "filename");
414 ret = raw_normalize_devicepath(&filename);
416 error_setg_errno(errp, -ret, "Could not normalize device path");
420 s->open_flags = open_flags;
421 raw_parse_flags(bdrv_flags, &s->open_flags);
424 fd = qemu_open(filename, s->open_flags, 0644);
434 #ifdef CONFIG_LINUX_AIO
435 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
438 error_setg_errno(errp, -ret, "Could not set AIO state");
443 s->has_discard = true;
444 s->has_write_zeroes = true;
445 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
446 s->needs_alignment = true;
449 if (fstat(s->fd, &st) < 0) {
451 error_setg_errno(errp, errno, "Could not stat file");
454 if (S_ISREG(st.st_mode)) {
455 s->discard_zeroes = true;
456 s->has_fallocate = true;
458 if (S_ISBLK(st.st_mode)) {
459 #ifdef BLKDISCARDZEROES
461 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
462 s->discard_zeroes = true;
466 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
467 * not rely on the contents of discarded blocks unless using O_DIRECT.
468 * Same for BLKZEROOUT.
470 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
471 s->discard_zeroes = false;
472 s->has_write_zeroes = false;
477 if (S_ISCHR(st.st_mode)) {
479 * The file is a char device (disk), which on FreeBSD isn't behind
480 * a pager, so force all requests to be aligned. This is needed
481 * so QEMU makes sure all IO operations on the device are aligned
482 * to sector size, or else FreeBSD will reject them with EINVAL.
484 s->needs_alignment = true;
489 if (platform_test_xfs_fd(s->fd)) {
494 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
498 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
505 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
508 BDRVRawState *s = bs->opaque;
509 Error *local_err = NULL;
512 s->type = FTYPE_FILE;
513 ret = raw_open_common(bs, options, flags, 0, &local_err);
515 error_propagate(errp, local_err);
520 static int raw_reopen_prepare(BDRVReopenState *state,
521 BlockReopenQueue *queue, Error **errp)
524 BDRVRawReopenState *raw_s;
526 Error *local_err = NULL;
528 assert(state != NULL);
529 assert(state->bs != NULL);
531 s = state->bs->opaque;
533 state->opaque = g_new0(BDRVRawReopenState, 1);
534 raw_s = state->opaque;
536 #ifdef CONFIG_LINUX_AIO
537 raw_s->use_aio = s->use_aio;
539 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
540 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
541 * won't override aio_ctx if aio_ctx is non-NULL */
542 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
543 error_setg(errp, "Could not set AIO state");
548 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
549 raw_s->open_flags |= O_NONBLOCK;
552 raw_parse_flags(state->flags, &raw_s->open_flags);
556 int fcntl_flags = O_APPEND | O_NONBLOCK;
558 fcntl_flags |= O_NOATIME;
562 /* Not all operating systems have O_ASYNC, and those that don't
563 * will not let us track the state into raw_s->open_flags (typically
564 * you achieve the same effect with an ioctl, for example I_SETSIG
565 * on Solaris). But we do not use O_ASYNC, so that's fine.
567 assert((s->open_flags & O_ASYNC) == 0);
570 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
571 /* dup the original fd */
572 /* TODO: use qemu fcntl wrapper */
573 #ifdef F_DUPFD_CLOEXEC
574 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
576 raw_s->fd = dup(s->fd);
577 if (raw_s->fd != -1) {
578 qemu_set_cloexec(raw_s->fd);
581 if (raw_s->fd >= 0) {
582 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
584 qemu_close(raw_s->fd);
590 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
591 if (raw_s->fd == -1) {
592 assert(!(raw_s->open_flags & O_CREAT));
593 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
594 if (raw_s->fd == -1) {
595 error_setg_errno(errp, errno, "Could not reopen file");
600 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
601 * alignment with the new fd. */
602 if (raw_s->fd != -1) {
603 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
605 qemu_close(raw_s->fd);
607 error_propagate(errp, local_err);
615 static void raw_reopen_commit(BDRVReopenState *state)
617 BDRVRawReopenState *raw_s = state->opaque;
618 BDRVRawState *s = state->bs->opaque;
620 s->open_flags = raw_s->open_flags;
624 #ifdef CONFIG_LINUX_AIO
625 s->use_aio = raw_s->use_aio;
628 g_free(state->opaque);
629 state->opaque = NULL;
633 static void raw_reopen_abort(BDRVReopenState *state)
635 BDRVRawReopenState *raw_s = state->opaque;
637 /* nothing to do if NULL, we didn't get far enough */
642 if (raw_s->fd >= 0) {
643 qemu_close(raw_s->fd);
646 g_free(state->opaque);
647 state->opaque = NULL;
650 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
652 BDRVRawState *s = bs->opaque;
654 raw_probe_alignment(bs, s->fd, errp);
655 bs->bl.opt_mem_alignment = s->buf_align;
658 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
662 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
670 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
674 ret = qemu_fdatasync(aiocb->aio_fildes);
683 static bool preadv_present = true;
686 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
688 return preadv(fd, iov, nr_iov, offset);
692 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
694 return pwritev(fd, iov, nr_iov, offset);
699 static bool preadv_present = false;
702 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
708 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
715 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
720 if (aiocb->aio_type & QEMU_AIO_WRITE)
721 len = qemu_pwritev(aiocb->aio_fildes,
726 len = qemu_preadv(aiocb->aio_fildes,
730 } while (len == -1 && errno == EINTR);
739 * Read/writes the data to/from a given linear buffer.
741 * Returns the number of bytes handles or -errno in case of an error. Short
742 * reads are only returned if the end of the file is reached.
744 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
749 while (offset < aiocb->aio_nbytes) {
750 if (aiocb->aio_type & QEMU_AIO_WRITE) {
751 len = pwrite(aiocb->aio_fildes,
752 (const char *)buf + offset,
753 aiocb->aio_nbytes - offset,
754 aiocb->aio_offset + offset);
756 len = pread(aiocb->aio_fildes,
758 aiocb->aio_nbytes - offset,
759 aiocb->aio_offset + offset);
761 if (len == -1 && errno == EINTR) {
763 } else if (len == -1 && errno == EINVAL &&
764 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
765 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
767 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
768 * after a short read. Assume that O_DIRECT short reads only occur
769 * at EOF. Therefore this is a short read, not an I/O error.
772 } else if (len == -1) {
775 } else if (len == 0) {
784 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
789 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
791 * If there is just a single buffer, and it is properly aligned
792 * we can just use plain pread/pwrite without any problems.
794 if (aiocb->aio_niov == 1) {
795 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
798 * We have more than one iovec, and all are properly aligned.
800 * Try preadv/pwritev first and fall back to linearizing the
801 * buffer if it's not supported.
803 if (preadv_present) {
804 nbytes = handle_aiocb_rw_vector(aiocb);
805 if (nbytes == aiocb->aio_nbytes ||
806 (nbytes < 0 && nbytes != -ENOSYS)) {
809 preadv_present = false;
813 * XXX(hch): short read/write. no easy way to handle the reminder
814 * using these interfaces. For now retry using plain
820 * Ok, we have to do it the hard way, copy all segments into
821 * a single aligned buffer.
823 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
828 if (aiocb->aio_type & QEMU_AIO_WRITE) {
832 for (i = 0; i < aiocb->aio_niov; ++i) {
833 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
834 p += aiocb->aio_iov[i].iov_len;
836 assert(p - buf == aiocb->aio_nbytes);
839 nbytes = handle_aiocb_rw_linear(aiocb, buf);
840 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
842 size_t count = aiocb->aio_nbytes, copy;
845 for (i = 0; i < aiocb->aio_niov && count; ++i) {
847 if (copy > aiocb->aio_iov[i].iov_len) {
848 copy = aiocb->aio_iov[i].iov_len;
850 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
851 assert(count >= copy);
863 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
865 struct xfs_flock64 fl;
867 memset(&fl, 0, sizeof(fl));
868 fl.l_whence = SEEK_SET;
872 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
873 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
880 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
882 struct xfs_flock64 fl;
884 memset(&fl, 0, sizeof(fl));
885 fl.l_whence = SEEK_SET;
889 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
890 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
898 static int translate_err(int err)
900 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
907 #ifdef CONFIG_FALLOCATE
908 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
911 if (fallocate(fd, mode, offset, len) == 0) {
914 } while (errno == EINTR);
915 return translate_err(-errno);
919 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
922 BDRVRawState *s = aiocb->bs->opaque;
924 if (!s->has_write_zeroes) {
930 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
931 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
934 } while (errno == EINTR);
936 ret = translate_err(-errno);
939 if (ret == -ENOTSUP) {
940 s->has_write_zeroes = false;
945 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
947 BDRVRawState *s = aiocb->bs->opaque;
949 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
950 return handle_aiocb_write_zeroes_block(aiocb);
955 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
959 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
960 if (s->has_write_zeroes) {
961 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
962 aiocb->aio_offset, aiocb->aio_nbytes);
963 if (ret == 0 || ret != -ENOTSUP) {
966 s->has_write_zeroes = false;
970 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
971 if (s->has_discard && s->has_fallocate) {
972 int ret = do_fallocate(s->fd,
973 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
974 aiocb->aio_offset, aiocb->aio_nbytes);
976 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
977 if (ret == 0 || ret != -ENOTSUP) {
980 s->has_fallocate = false;
981 } else if (ret != -ENOTSUP) {
984 s->has_discard = false;
989 #ifdef CONFIG_FALLOCATE
990 if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
991 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
992 if (ret == 0 || ret != -ENOTSUP) {
995 s->has_fallocate = false;
1002 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1004 int ret = -EOPNOTSUPP;
1005 BDRVRawState *s = aiocb->bs->opaque;
1007 if (!s->has_discard) {
1011 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1014 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1015 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1018 } while (errno == EINTR);
1025 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1029 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1030 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1031 aiocb->aio_offset, aiocb->aio_nbytes);
1035 ret = translate_err(ret);
1036 if (ret == -ENOTSUP) {
1037 s->has_discard = false;
1042 static int aio_worker(void *arg)
1044 RawPosixAIOData *aiocb = arg;
1047 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1049 ret = handle_aiocb_rw(aiocb);
1050 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
1051 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1052 0, aiocb->aio_nbytes - ret);
1054 ret = aiocb->aio_nbytes;
1056 if (ret == aiocb->aio_nbytes) {
1058 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1062 case QEMU_AIO_WRITE:
1063 ret = handle_aiocb_rw(aiocb);
1064 if (ret == aiocb->aio_nbytes) {
1066 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1070 case QEMU_AIO_FLUSH:
1071 ret = handle_aiocb_flush(aiocb);
1073 case QEMU_AIO_IOCTL:
1074 ret = handle_aiocb_ioctl(aiocb);
1076 case QEMU_AIO_DISCARD:
1077 ret = handle_aiocb_discard(aiocb);
1079 case QEMU_AIO_WRITE_ZEROES:
1080 ret = handle_aiocb_write_zeroes(aiocb);
1083 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1088 g_slice_free(RawPosixAIOData, aiocb);
1092 static int paio_submit_co(BlockDriverState *bs, int fd,
1093 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1096 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1100 acb->aio_type = type;
1101 acb->aio_fildes = fd;
1103 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1104 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1107 acb->aio_iov = qiov->iov;
1108 acb->aio_niov = qiov->niov;
1109 assert(qiov->size == acb->aio_nbytes);
1112 trace_paio_submit_co(sector_num, nb_sectors, type);
1113 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1114 return thread_pool_submit_co(pool, aio_worker, acb);
1117 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1118 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1119 BlockCompletionFunc *cb, void *opaque, int type)
1121 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1125 acb->aio_type = type;
1126 acb->aio_fildes = fd;
1128 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1129 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1132 acb->aio_iov = qiov->iov;
1133 acb->aio_niov = qiov->niov;
1134 assert(qiov->size == acb->aio_nbytes);
1137 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1138 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1139 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1142 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1143 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1144 BlockCompletionFunc *cb, void *opaque, int type)
1146 BDRVRawState *s = bs->opaque;
1148 if (fd_open(bs) < 0)
1152 * Check if the underlying device requires requests to be aligned,
1153 * and if the request we are trying to submit is aligned or not.
1154 * If this is the case tell the low-level driver that it needs
1155 * to copy the buffer.
1157 if (s->needs_alignment) {
1158 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1159 type |= QEMU_AIO_MISALIGNED;
1160 #ifdef CONFIG_LINUX_AIO
1161 } else if (s->use_aio) {
1162 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1163 nb_sectors, cb, opaque, type);
1168 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1172 static void raw_aio_plug(BlockDriverState *bs)
1174 #ifdef CONFIG_LINUX_AIO
1175 BDRVRawState *s = bs->opaque;
1177 laio_io_plug(bs, s->aio_ctx);
1182 static void raw_aio_unplug(BlockDriverState *bs)
1184 #ifdef CONFIG_LINUX_AIO
1185 BDRVRawState *s = bs->opaque;
1187 laio_io_unplug(bs, s->aio_ctx, true);
1192 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1194 #ifdef CONFIG_LINUX_AIO
1195 BDRVRawState *s = bs->opaque;
1197 laio_io_unplug(bs, s->aio_ctx, false);
1202 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1203 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1204 BlockCompletionFunc *cb, void *opaque)
1206 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1207 cb, opaque, QEMU_AIO_READ);
1210 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1211 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1212 BlockCompletionFunc *cb, void *opaque)
1214 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1215 cb, opaque, QEMU_AIO_WRITE);
1218 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1219 BlockCompletionFunc *cb, void *opaque)
1221 BDRVRawState *s = bs->opaque;
1223 if (fd_open(bs) < 0)
1226 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1229 static void raw_close(BlockDriverState *bs)
1231 BDRVRawState *s = bs->opaque;
1233 raw_detach_aio_context(bs);
1235 #ifdef CONFIG_LINUX_AIO
1237 laio_cleanup(s->aio_ctx);
1246 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1248 BDRVRawState *s = bs->opaque;
1251 if (fstat(s->fd, &st)) {
1255 if (S_ISREG(st.st_mode)) {
1256 if (ftruncate(s->fd, offset) < 0) {
1259 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1260 if (offset > raw_getlength(bs)) {
1271 static int64_t raw_getlength(BlockDriverState *bs)
1273 BDRVRawState *s = bs->opaque;
1279 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1280 struct disklabel dl;
1282 if (ioctl(fd, DIOCGDINFO, &dl))
1284 return (uint64_t)dl.d_secsize *
1285 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1289 #elif defined(__NetBSD__)
1290 static int64_t raw_getlength(BlockDriverState *bs)
1292 BDRVRawState *s = bs->opaque;
1298 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1299 struct dkwedge_info dkw;
1301 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1302 return dkw.dkw_size * 512;
1304 struct disklabel dl;
1306 if (ioctl(fd, DIOCGDINFO, &dl))
1308 return (uint64_t)dl.d_secsize *
1309 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1314 #elif defined(__sun__)
1315 static int64_t raw_getlength(BlockDriverState *bs)
1317 BDRVRawState *s = bs->opaque;
1318 struct dk_minfo minfo;
1328 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1330 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1332 return minfo.dki_lbsize * minfo.dki_capacity;
1336 * There are reports that lseek on some devices fails, but
1337 * irc discussion said that contingency on contingency was overkill.
1339 size = lseek(s->fd, 0, SEEK_END);
1345 #elif defined(CONFIG_BSD)
1346 static int64_t raw_getlength(BlockDriverState *bs)
1348 BDRVRawState *s = bs->opaque;
1352 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1361 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1364 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1365 #ifdef DIOCGMEDIASIZE
1366 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1367 #elif defined(DIOCGPART)
1370 if (ioctl(fd, DIOCGPART, &pi) == 0)
1371 size = pi.media_size;
1377 #if defined(__APPLE__) && defined(__MACH__)
1379 uint64_t sectors = 0;
1380 uint32_t sector_size = 0;
1382 if (ioctl(fd, DKIOCGETBLOCKCOUNT, §ors) == 0
1383 && ioctl(fd, DKIOCGETBLOCKSIZE, §or_size) == 0) {
1384 size = sectors * sector_size;
1386 size = lseek(fd, 0LL, SEEK_END);
1393 size = lseek(fd, 0LL, SEEK_END);
1398 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1401 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1402 if (size == 2048LL * (unsigned)-1)
1404 /* XXX no disc? maybe we need to reopen... */
1405 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1412 size = lseek(fd, 0, SEEK_END);
1420 static int64_t raw_getlength(BlockDriverState *bs)
1422 BDRVRawState *s = bs->opaque;
1431 size = lseek(s->fd, 0, SEEK_END);
1439 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1442 BDRVRawState *s = bs->opaque;
1444 if (fstat(s->fd, &st) < 0) {
1447 return (int64_t)st.st_blocks * 512;
1450 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1454 int64_t total_size = 0;
1456 PreallocMode prealloc;
1458 Error *local_err = NULL;
1460 strstart(filename, "file:", &filename);
1462 /* Read out options */
1463 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1465 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1466 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1467 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1468 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1472 error_propagate(errp, local_err);
1477 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1481 error_setg_errno(errp, -result, "Could not create file");
1487 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1488 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1489 * will be ignored since any failure of this operation should not
1490 * block the left work.
1493 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1494 attr |= FS_NOCOW_FL;
1495 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1500 if (ftruncate(fd, total_size) != 0) {
1502 error_setg_errno(errp, -result, "Could not resize file");
1507 #ifdef CONFIG_POSIX_FALLOCATE
1508 case PREALLOC_MODE_FALLOC:
1509 /* posix_fallocate() doesn't set errno. */
1510 result = -posix_fallocate(fd, 0, total_size);
1512 error_setg_errno(errp, -result,
1513 "Could not preallocate data for the new file");
1517 case PREALLOC_MODE_FULL:
1519 int64_t num = 0, left = total_size;
1520 buf = g_malloc0(65536);
1523 num = MIN(left, 65536);
1524 result = write(fd, buf, num);
1527 error_setg_errno(errp, -result,
1528 "Could not write to the new file");
1537 error_setg_errno(errp, -result,
1538 "Could not flush new file to disk");
1544 case PREALLOC_MODE_OFF:
1548 error_setg(errp, "Unsupported preallocation mode: %s",
1549 PreallocMode_lookup[prealloc]);
1554 if (qemu_close(fd) != 0 && result == 0) {
1556 error_setg_errno(errp, -result, "Could not close the new file");
1563 * Find allocation range in @bs around offset @start.
1564 * May change underlying file descriptor's file offset.
1565 * If @start is not in a hole, store @start in @data, and the
1566 * beginning of the next hole in @hole, and return 0.
1567 * If @start is in a non-trailing hole, store @start in @hole and the
1568 * beginning of the next non-hole in @data, and return 0.
1569 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1570 * If we can't find out, return a negative errno other than -ENXIO.
1572 static int find_allocation(BlockDriverState *bs, off_t start,
1573 off_t *data, off_t *hole)
1575 #if defined SEEK_HOLE && defined SEEK_DATA
1576 BDRVRawState *s = bs->opaque;
1581 * D1. offs == start: start is in data
1582 * D2. offs > start: start is in a hole, next data at offs
1583 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1584 * or start is beyond EOF
1585 * If the latter happens, the file has been truncated behind
1586 * our back since we opened it. All bets are off then.
1587 * Treating like a trailing hole is simplest.
1588 * D4. offs < 0, errno != ENXIO: we learned nothing
1590 offs = lseek(s->fd, start, SEEK_DATA);
1592 return -errno; /* D3 or D4 */
1594 assert(offs >= start);
1597 /* D2: in hole, next data at offs */
1603 /* D1: in data, end not yet known */
1607 * H1. offs == start: start is in a hole
1608 * If this happens here, a hole has been dug behind our back
1609 * since the previous lseek().
1610 * H2. offs > start: either start is in data, next hole at offs,
1611 * or start is in trailing hole, EOF at offs
1612 * Linux treats trailing holes like any other hole: offs ==
1613 * start. Solaris seeks to EOF instead: offs > start (blech).
1614 * If that happens here, a hole has been dug behind our back
1615 * since the previous lseek().
1616 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1617 * If this happens, the file has been truncated behind our
1618 * back since we opened it. Treat it like a trailing hole.
1619 * H4. offs < 0, errno != ENXIO: we learned nothing
1620 * Pretend we know nothing at all, i.e. "forget" about D1.
1622 offs = lseek(s->fd, start, SEEK_HOLE);
1624 return -errno; /* D1 and (H3 or H4) */
1626 assert(offs >= start);
1630 * D1 and H2: either in data, next hole at offs, or it was in
1631 * data but is now in a trailing hole. In the latter case,
1632 * all bets are off. Treating it as if it there was data all
1633 * the way to EOF is safe, so simply do that.
1648 * Returns the allocation status of the specified sectors.
1650 * If 'sector_num' is beyond the end of the disk image the return value is 0
1651 * and 'pnum' is set to 0.
1653 * 'pnum' is set to the number of sectors (including and immediately following
1654 * the specified sector) that are known to be in the same
1655 * allocated/unallocated state.
1657 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1658 * beyond the end of the disk image it will be clamped.
1660 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1662 int nb_sectors, int *pnum)
1664 off_t start, data = 0, hole = 0;
1673 start = sector_num * BDRV_SECTOR_SIZE;
1674 total_size = bdrv_getlength(bs);
1675 if (total_size < 0) {
1677 } else if (start >= total_size) {
1680 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1681 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1684 ret = find_allocation(bs, start, &data, &hole);
1685 if (ret == -ENXIO) {
1688 ret = BDRV_BLOCK_ZERO;
1689 } else if (ret < 0) {
1690 /* No info available, so pretend there are no holes */
1692 ret = BDRV_BLOCK_DATA;
1693 } else if (data == start) {
1694 /* On a data extent, compute sectors to the end of the extent. */
1695 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1696 ret = BDRV_BLOCK_DATA;
1698 /* On a hole, compute sectors to the beginning of the next extent. */
1699 assert(hole == start);
1700 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1701 ret = BDRV_BLOCK_ZERO;
1703 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1706 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1707 int64_t sector_num, int nb_sectors,
1708 BlockCompletionFunc *cb, void *opaque)
1710 BDRVRawState *s = bs->opaque;
1712 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1713 cb, opaque, QEMU_AIO_DISCARD);
1716 static int coroutine_fn raw_co_write_zeroes(
1717 BlockDriverState *bs, int64_t sector_num,
1718 int nb_sectors, BdrvRequestFlags flags)
1720 BDRVRawState *s = bs->opaque;
1722 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1723 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1724 QEMU_AIO_WRITE_ZEROES);
1725 } else if (s->discard_zeroes) {
1726 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1732 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1734 BDRVRawState *s = bs->opaque;
1736 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1737 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1741 static QemuOptsList raw_create_opts = {
1742 .name = "raw-create-opts",
1743 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1746 .name = BLOCK_OPT_SIZE,
1747 .type = QEMU_OPT_SIZE,
1748 .help = "Virtual disk size"
1751 .name = BLOCK_OPT_NOCOW,
1752 .type = QEMU_OPT_BOOL,
1753 .help = "Turn off copy-on-write (valid only on btrfs)"
1756 .name = BLOCK_OPT_PREALLOC,
1757 .type = QEMU_OPT_STRING,
1758 .help = "Preallocation mode (allowed values: off, falloc, full)"
1760 { /* end of list */ }
1764 BlockDriver bdrv_file = {
1765 .format_name = "file",
1766 .protocol_name = "file",
1767 .instance_size = sizeof(BDRVRawState),
1768 .bdrv_needs_filename = true,
1769 .bdrv_probe = NULL, /* no probe for protocols */
1770 .bdrv_parse_filename = raw_parse_filename,
1771 .bdrv_file_open = raw_open,
1772 .bdrv_reopen_prepare = raw_reopen_prepare,
1773 .bdrv_reopen_commit = raw_reopen_commit,
1774 .bdrv_reopen_abort = raw_reopen_abort,
1775 .bdrv_close = raw_close,
1776 .bdrv_create = raw_create,
1777 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1778 .bdrv_co_get_block_status = raw_co_get_block_status,
1779 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1781 .bdrv_aio_readv = raw_aio_readv,
1782 .bdrv_aio_writev = raw_aio_writev,
1783 .bdrv_aio_flush = raw_aio_flush,
1784 .bdrv_aio_discard = raw_aio_discard,
1785 .bdrv_refresh_limits = raw_refresh_limits,
1786 .bdrv_io_plug = raw_aio_plug,
1787 .bdrv_io_unplug = raw_aio_unplug,
1788 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1790 .bdrv_truncate = raw_truncate,
1791 .bdrv_getlength = raw_getlength,
1792 .bdrv_get_info = raw_get_info,
1793 .bdrv_get_allocated_file_size
1794 = raw_get_allocated_file_size,
1796 .bdrv_detach_aio_context = raw_detach_aio_context,
1797 .bdrv_attach_aio_context = raw_attach_aio_context,
1799 .create_opts = &raw_create_opts,
1802 /***********************************************/
1805 #if defined(__APPLE__) && defined(__MACH__)
1806 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1807 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1809 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1811 kern_return_t kernResult;
1812 mach_port_t masterPort;
1813 CFMutableDictionaryRef classesToMatch;
1815 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1816 if ( KERN_SUCCESS != kernResult ) {
1817 printf( "IOMasterPort returned %d\n", kernResult );
1820 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1821 if ( classesToMatch == NULL ) {
1822 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1824 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1826 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1827 if ( KERN_SUCCESS != kernResult )
1829 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1835 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1837 io_object_t nextMedia;
1838 kern_return_t kernResult = KERN_FAILURE;
1840 nextMedia = IOIteratorNext( mediaIterator );
1843 CFTypeRef bsdPathAsCFString;
1844 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1845 if ( bsdPathAsCFString ) {
1846 size_t devPathLength;
1847 strcpy( bsdPath, _PATH_DEV );
1848 strcat( bsdPath, "r" );
1849 devPathLength = strlen( bsdPath );
1850 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1851 kernResult = KERN_SUCCESS;
1853 CFRelease( bsdPathAsCFString );
1855 IOObjectRelease( nextMedia );
1863 static int hdev_probe_device(const char *filename)
1867 /* allow a dedicated CD-ROM driver to match with a higher priority */
1868 if (strstart(filename, "/dev/cdrom", NULL))
1871 if (stat(filename, &st) >= 0 &&
1872 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1879 static int check_hdev_writable(BDRVRawState *s)
1881 #if defined(BLKROGET)
1882 /* Linux block devices can be configured "read-only" using blockdev(8).
1883 * This is independent of device node permissions and therefore open(2)
1884 * with O_RDWR succeeds. Actual writes fail with EPERM.
1886 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1887 * check for read-only block devices so that Linux block devices behave
1893 if (fstat(s->fd, &st)) {
1897 if (!S_ISBLK(st.st_mode)) {
1901 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1908 #endif /* defined(BLKROGET) */
1912 static void hdev_parse_filename(const char *filename, QDict *options,
1915 /* The prefix is optional, just as for "file". */
1916 strstart(filename, "host_device:", &filename);
1918 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1921 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1924 BDRVRawState *s = bs->opaque;
1925 Error *local_err = NULL;
1927 const char *filename = qdict_get_str(options, "filename");
1929 #if defined(__APPLE__) && defined(__MACH__)
1930 if (strstart(filename, "/dev/cdrom", NULL)) {
1931 kern_return_t kernResult;
1932 io_iterator_t mediaIterator;
1933 char bsdPath[ MAXPATHLEN ];
1936 kernResult = FindEjectableCDMedia( &mediaIterator );
1937 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1939 if ( bsdPath[ 0 ] != '\0' ) {
1940 strcat(bsdPath,"s0");
1941 /* some CDs don't have a partition 0 */
1942 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1944 bsdPath[strlen(bsdPath)-1] = '1';
1949 qdict_put(options, "filename", qstring_from_str(filename));
1952 if ( mediaIterator )
1953 IOObjectRelease( mediaIterator );
1957 s->type = FTYPE_FILE;
1958 #if defined(__linux__)
1960 char resolved_path[ MAXPATHLEN ], *temp;
1962 temp = realpath(filename, resolved_path);
1963 if (temp && strstart(temp, "/dev/sg", NULL)) {
1969 ret = raw_open_common(bs, options, flags, 0, &local_err);
1972 error_propagate(errp, local_err);
1977 if (flags & BDRV_O_RDWR) {
1978 ret = check_hdev_writable(s);
1981 error_setg_errno(errp, -ret, "The device is not writable");
1989 #if defined(__linux__)
1990 /* Note: we do not have a reliable method to detect if the floppy is
1991 present. The current method is to try to open the floppy at every
1992 I/O and to keep it opened during a few hundreds of ms. */
1993 static int fd_open(BlockDriverState *bs)
1995 BDRVRawState *s = bs->opaque;
1996 int last_media_present;
1998 if (s->type != FTYPE_FD)
2000 last_media_present = (s->fd >= 0);
2002 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
2006 printf("Floppy closed\n");
2010 if (s->fd_got_error &&
2011 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
2013 printf("No floppy (open delayed)\n");
2017 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
2019 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2020 s->fd_got_error = 1;
2021 if (last_media_present)
2022 s->fd_media_changed = 1;
2024 printf("No floppy\n");
2029 printf("Floppy opened\n");
2032 if (!last_media_present)
2033 s->fd_media_changed = 1;
2034 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2035 s->fd_got_error = 0;
2039 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2041 BDRVRawState *s = bs->opaque;
2043 return ioctl(s->fd, req, buf);
2046 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2047 unsigned long int req, void *buf,
2048 BlockCompletionFunc *cb, void *opaque)
2050 BDRVRawState *s = bs->opaque;
2051 RawPosixAIOData *acb;
2054 if (fd_open(bs) < 0)
2057 acb = g_slice_new(RawPosixAIOData);
2059 acb->aio_type = QEMU_AIO_IOCTL;
2060 acb->aio_fildes = s->fd;
2061 acb->aio_offset = 0;
2062 acb->aio_ioctl_buf = buf;
2063 acb->aio_ioctl_cmd = req;
2064 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2065 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2068 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2069 static int fd_open(BlockDriverState *bs)
2071 BDRVRawState *s = bs->opaque;
2073 /* this is just to ensure s->fd is sane (its called by io ops) */
2078 #else /* !linux && !FreeBSD */
2080 static int fd_open(BlockDriverState *bs)
2085 #endif /* !linux && !FreeBSD */
2087 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2088 int64_t sector_num, int nb_sectors,
2089 BlockCompletionFunc *cb, void *opaque)
2091 BDRVRawState *s = bs->opaque;
2093 if (fd_open(bs) < 0) {
2096 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2097 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2100 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2101 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2103 BDRVRawState *s = bs->opaque;
2110 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2111 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2112 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2113 } else if (s->discard_zeroes) {
2114 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2115 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2120 static int hdev_create(const char *filename, QemuOpts *opts,
2125 struct stat stat_buf;
2126 int64_t total_size = 0;
2129 /* This function is used by all three protocol block drivers and therefore
2130 * any of these three prefixes may be given.
2131 * The return value has to be stored somewhere, otherwise this is an error
2132 * due to -Werror=unused-value. */
2134 strstart(filename, "host_device:", &filename) ||
2135 strstart(filename, "host_cdrom:" , &filename) ||
2136 strstart(filename, "host_floppy:", &filename);
2140 /* Read out options */
2141 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2144 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2147 error_setg_errno(errp, -ret, "Could not open device");
2151 if (fstat(fd, &stat_buf) < 0) {
2153 error_setg_errno(errp, -ret, "Could not stat device");
2154 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2156 "The given file is neither a block nor a character device");
2158 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2159 error_setg(errp, "Device is too small");
2167 static BlockDriver bdrv_host_device = {
2168 .format_name = "host_device",
2169 .protocol_name = "host_device",
2170 .instance_size = sizeof(BDRVRawState),
2171 .bdrv_needs_filename = true,
2172 .bdrv_probe_device = hdev_probe_device,
2173 .bdrv_parse_filename = hdev_parse_filename,
2174 .bdrv_file_open = hdev_open,
2175 .bdrv_close = raw_close,
2176 .bdrv_reopen_prepare = raw_reopen_prepare,
2177 .bdrv_reopen_commit = raw_reopen_commit,
2178 .bdrv_reopen_abort = raw_reopen_abort,
2179 .bdrv_create = hdev_create,
2180 .create_opts = &raw_create_opts,
2181 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2183 .bdrv_aio_readv = raw_aio_readv,
2184 .bdrv_aio_writev = raw_aio_writev,
2185 .bdrv_aio_flush = raw_aio_flush,
2186 .bdrv_aio_discard = hdev_aio_discard,
2187 .bdrv_refresh_limits = raw_refresh_limits,
2188 .bdrv_io_plug = raw_aio_plug,
2189 .bdrv_io_unplug = raw_aio_unplug,
2190 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2192 .bdrv_truncate = raw_truncate,
2193 .bdrv_getlength = raw_getlength,
2194 .bdrv_get_info = raw_get_info,
2195 .bdrv_get_allocated_file_size
2196 = raw_get_allocated_file_size,
2198 .bdrv_detach_aio_context = raw_detach_aio_context,
2199 .bdrv_attach_aio_context = raw_attach_aio_context,
2201 /* generic scsi device */
2203 .bdrv_ioctl = hdev_ioctl,
2204 .bdrv_aio_ioctl = hdev_aio_ioctl,
2209 static void floppy_parse_filename(const char *filename, QDict *options,
2212 /* The prefix is optional, just as for "file". */
2213 strstart(filename, "host_floppy:", &filename);
2215 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2218 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2221 BDRVRawState *s = bs->opaque;
2222 Error *local_err = NULL;
2227 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2228 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2231 error_propagate(errp, local_err);
2236 /* close fd so that we can reopen it as needed */
2239 s->fd_media_changed = 1;
2244 static int floppy_probe_device(const char *filename)
2248 struct floppy_struct fdparam;
2251 if (strstart(filename, "/dev/fd", NULL) &&
2252 !strstart(filename, "/dev/fdset/", NULL)) {
2256 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2260 ret = fstat(fd, &st);
2261 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2265 /* Attempt to detect via a floppy specific ioctl */
2266 ret = ioctl(fd, FDGETPRM, &fdparam);
2277 static int floppy_is_inserted(BlockDriverState *bs)
2279 return fd_open(bs) >= 0;
2282 static int floppy_media_changed(BlockDriverState *bs)
2284 BDRVRawState *s = bs->opaque;
2288 * XXX: we do not have a true media changed indication.
2289 * It does not work if the floppy is changed without trying to read it.
2292 ret = s->fd_media_changed;
2293 s->fd_media_changed = 0;
2295 printf("Floppy changed=%d\n", ret);
2300 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2302 BDRVRawState *s = bs->opaque;
2309 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2311 if (ioctl(fd, FDEJECT, 0) < 0)
2317 static BlockDriver bdrv_host_floppy = {
2318 .format_name = "host_floppy",
2319 .protocol_name = "host_floppy",
2320 .instance_size = sizeof(BDRVRawState),
2321 .bdrv_needs_filename = true,
2322 .bdrv_probe_device = floppy_probe_device,
2323 .bdrv_parse_filename = floppy_parse_filename,
2324 .bdrv_file_open = floppy_open,
2325 .bdrv_close = raw_close,
2326 .bdrv_reopen_prepare = raw_reopen_prepare,
2327 .bdrv_reopen_commit = raw_reopen_commit,
2328 .bdrv_reopen_abort = raw_reopen_abort,
2329 .bdrv_create = hdev_create,
2330 .create_opts = &raw_create_opts,
2332 .bdrv_aio_readv = raw_aio_readv,
2333 .bdrv_aio_writev = raw_aio_writev,
2334 .bdrv_aio_flush = raw_aio_flush,
2335 .bdrv_refresh_limits = raw_refresh_limits,
2336 .bdrv_io_plug = raw_aio_plug,
2337 .bdrv_io_unplug = raw_aio_unplug,
2338 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2340 .bdrv_truncate = raw_truncate,
2341 .bdrv_getlength = raw_getlength,
2342 .has_variable_length = true,
2343 .bdrv_get_allocated_file_size
2344 = raw_get_allocated_file_size,
2346 .bdrv_detach_aio_context = raw_detach_aio_context,
2347 .bdrv_attach_aio_context = raw_attach_aio_context,
2349 /* removable device support */
2350 .bdrv_is_inserted = floppy_is_inserted,
2351 .bdrv_media_changed = floppy_media_changed,
2352 .bdrv_eject = floppy_eject,
2356 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2357 static void cdrom_parse_filename(const char *filename, QDict *options,
2360 /* The prefix is optional, just as for "file". */
2361 strstart(filename, "host_cdrom:", &filename);
2363 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2368 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2371 BDRVRawState *s = bs->opaque;
2372 Error *local_err = NULL;
2377 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2378 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2380 error_propagate(errp, local_err);
2385 static int cdrom_probe_device(const char *filename)
2391 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2395 ret = fstat(fd, &st);
2396 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2400 /* Attempt to detect via a CDROM specific ioctl */
2401 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2411 static int cdrom_is_inserted(BlockDriverState *bs)
2413 BDRVRawState *s = bs->opaque;
2416 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2417 if (ret == CDS_DISC_OK)
2422 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2424 BDRVRawState *s = bs->opaque;
2427 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2428 perror("CDROMEJECT");
2430 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2431 perror("CDROMEJECT");
2435 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2437 BDRVRawState *s = bs->opaque;
2439 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2441 * Note: an error can happen if the distribution automatically
2444 /* perror("CDROM_LOCKDOOR"); */
2448 static BlockDriver bdrv_host_cdrom = {
2449 .format_name = "host_cdrom",
2450 .protocol_name = "host_cdrom",
2451 .instance_size = sizeof(BDRVRawState),
2452 .bdrv_needs_filename = true,
2453 .bdrv_probe_device = cdrom_probe_device,
2454 .bdrv_parse_filename = cdrom_parse_filename,
2455 .bdrv_file_open = cdrom_open,
2456 .bdrv_close = raw_close,
2457 .bdrv_reopen_prepare = raw_reopen_prepare,
2458 .bdrv_reopen_commit = raw_reopen_commit,
2459 .bdrv_reopen_abort = raw_reopen_abort,
2460 .bdrv_create = hdev_create,
2461 .create_opts = &raw_create_opts,
2463 .bdrv_aio_readv = raw_aio_readv,
2464 .bdrv_aio_writev = raw_aio_writev,
2465 .bdrv_aio_flush = raw_aio_flush,
2466 .bdrv_refresh_limits = raw_refresh_limits,
2467 .bdrv_io_plug = raw_aio_plug,
2468 .bdrv_io_unplug = raw_aio_unplug,
2469 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2471 .bdrv_truncate = raw_truncate,
2472 .bdrv_getlength = raw_getlength,
2473 .has_variable_length = true,
2474 .bdrv_get_allocated_file_size
2475 = raw_get_allocated_file_size,
2477 .bdrv_detach_aio_context = raw_detach_aio_context,
2478 .bdrv_attach_aio_context = raw_attach_aio_context,
2480 /* removable device support */
2481 .bdrv_is_inserted = cdrom_is_inserted,
2482 .bdrv_eject = cdrom_eject,
2483 .bdrv_lock_medium = cdrom_lock_medium,
2485 /* generic scsi device */
2486 .bdrv_ioctl = hdev_ioctl,
2487 .bdrv_aio_ioctl = hdev_aio_ioctl,
2489 #endif /* __linux__ */
2491 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2492 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2495 BDRVRawState *s = bs->opaque;
2496 Error *local_err = NULL;
2501 ret = raw_open_common(bs, options, flags, 0, &local_err);
2504 error_propagate(errp, local_err);
2509 /* make sure the door isn't locked at this time */
2510 ioctl(s->fd, CDIOCALLOW);
2514 static int cdrom_probe_device(const char *filename)
2516 if (strstart(filename, "/dev/cd", NULL) ||
2517 strstart(filename, "/dev/acd", NULL))
2522 static int cdrom_reopen(BlockDriverState *bs)
2524 BDRVRawState *s = bs->opaque;
2528 * Force reread of possibly changed/newly loaded disc,
2529 * FreeBSD seems to not notice sometimes...
2533 fd = qemu_open(bs->filename, s->open_flags, 0644);
2540 /* make sure the door isn't locked at this time */
2541 ioctl(s->fd, CDIOCALLOW);
2545 static int cdrom_is_inserted(BlockDriverState *bs)
2547 return raw_getlength(bs) > 0;
2550 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2552 BDRVRawState *s = bs->opaque;
2557 (void) ioctl(s->fd, CDIOCALLOW);
2560 if (ioctl(s->fd, CDIOCEJECT) < 0)
2561 perror("CDIOCEJECT");
2563 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2564 perror("CDIOCCLOSE");
2570 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2572 BDRVRawState *s = bs->opaque;
2576 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2578 * Note: an error can happen if the distribution automatically
2581 /* perror("CDROM_LOCKDOOR"); */
2585 static BlockDriver bdrv_host_cdrom = {
2586 .format_name = "host_cdrom",
2587 .protocol_name = "host_cdrom",
2588 .instance_size = sizeof(BDRVRawState),
2589 .bdrv_needs_filename = true,
2590 .bdrv_probe_device = cdrom_probe_device,
2591 .bdrv_parse_filename = cdrom_parse_filename,
2592 .bdrv_file_open = cdrom_open,
2593 .bdrv_close = raw_close,
2594 .bdrv_reopen_prepare = raw_reopen_prepare,
2595 .bdrv_reopen_commit = raw_reopen_commit,
2596 .bdrv_reopen_abort = raw_reopen_abort,
2597 .bdrv_create = hdev_create,
2598 .create_opts = &raw_create_opts,
2600 .bdrv_aio_readv = raw_aio_readv,
2601 .bdrv_aio_writev = raw_aio_writev,
2602 .bdrv_aio_flush = raw_aio_flush,
2603 .bdrv_refresh_limits = raw_refresh_limits,
2604 .bdrv_io_plug = raw_aio_plug,
2605 .bdrv_io_unplug = raw_aio_unplug,
2606 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2608 .bdrv_truncate = raw_truncate,
2609 .bdrv_getlength = raw_getlength,
2610 .has_variable_length = true,
2611 .bdrv_get_allocated_file_size
2612 = raw_get_allocated_file_size,
2614 .bdrv_detach_aio_context = raw_detach_aio_context,
2615 .bdrv_attach_aio_context = raw_attach_aio_context,
2617 /* removable device support */
2618 .bdrv_is_inserted = cdrom_is_inserted,
2619 .bdrv_eject = cdrom_eject,
2620 .bdrv_lock_medium = cdrom_lock_medium,
2622 #endif /* __FreeBSD__ */
2624 static void bdrv_file_init(void)
2627 * Register all the drivers. Note that order is important, the driver
2628 * registered last will get probed first.
2630 bdrv_register(&bdrv_file);
2631 bdrv_register(&bdrv_host_device);
2633 bdrv_register(&bdrv_host_floppy);
2634 bdrv_register(&bdrv_host_cdrom);
2636 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2637 bdrv_register(&bdrv_host_cdrom);
2641 block_init(bdrv_file_init);