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 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
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;
150 bool needs_alignment;
153 typedef struct BDRVRawReopenState {
156 #ifdef CONFIG_LINUX_AIO
159 } BDRVRawReopenState;
161 static int fd_open(BlockDriverState *bs);
162 static int64_t raw_getlength(BlockDriverState *bs);
164 typedef struct RawPosixAIOData {
165 BlockDriverState *bs;
168 struct iovec *aio_iov;
173 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
178 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
179 static int cdrom_reopen(BlockDriverState *bs);
182 #if defined(__NetBSD__)
183 static int raw_normalize_devicepath(const char **filename)
185 static char namebuf[PATH_MAX];
186 const char *dp, *fname;
190 dp = strrchr(fname, '/');
191 if (lstat(fname, &sb) < 0) {
192 fprintf(stderr, "%s: stat failed: %s\n",
193 fname, strerror(errno));
197 if (!S_ISBLK(sb.st_mode)) {
202 snprintf(namebuf, PATH_MAX, "r%s", fname);
204 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
205 (int)(dp - fname), fname, dp + 1);
207 fprintf(stderr, "%s is a block device", fname);
209 fprintf(stderr, ", using %s\n", *filename);
214 static int raw_normalize_devicepath(const char **filename)
220 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
222 BDRVRawState *s = bs->opaque;
224 unsigned int sector_size;
226 /* For /dev/sg devices the alignment is not really used.
227 With buffered I/O, we don't have any restrictions. */
228 if (bs->sg || !s->needs_alignment) {
229 bs->request_alignment = 1;
234 /* Try a few ioctls to get the right size */
235 bs->request_alignment = 0;
239 if (ioctl(fd, BLKSSZGET, §or_size) >= 0) {
240 bs->request_alignment = sector_size;
243 #ifdef DKIOCGETBLOCKSIZE
244 if (ioctl(fd, DKIOCGETBLOCKSIZE, §or_size) >= 0) {
245 bs->request_alignment = sector_size;
248 #ifdef DIOCGSECTORSIZE
249 if (ioctl(fd, DIOCGSECTORSIZE, §or_size) >= 0) {
250 bs->request_alignment = sector_size;
256 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
257 bs->request_alignment = da.d_miniosz;
258 /* The kernel returns wrong information for d_mem */
259 /* s->buf_align = da.d_mem; */
264 /* If we could not get the sizes so far, we can only guess them */
267 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
268 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
269 if (pread(fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
270 s->buf_align = align;
277 if (!bs->request_alignment) {
279 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
280 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
281 if (pread(fd, buf, align, 0) >= 0) {
282 bs->request_alignment = align;
289 if (!s->buf_align || !bs->request_alignment) {
290 error_setg(errp, "Could not find working O_DIRECT alignment. "
291 "Try cache.direct=off.");
295 static void raw_parse_flags(int bdrv_flags, int *open_flags)
297 assert(open_flags != NULL);
299 *open_flags |= O_BINARY;
300 *open_flags &= ~O_ACCMODE;
301 if (bdrv_flags & BDRV_O_RDWR) {
302 *open_flags |= O_RDWR;
304 *open_flags |= O_RDONLY;
307 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
308 * and O_DIRECT for no caching. */
309 if ((bdrv_flags & BDRV_O_NOCACHE)) {
310 *open_flags |= O_DIRECT;
314 static void raw_detach_aio_context(BlockDriverState *bs)
316 #ifdef CONFIG_LINUX_AIO
317 BDRVRawState *s = bs->opaque;
320 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
325 static void raw_attach_aio_context(BlockDriverState *bs,
326 AioContext *new_context)
328 #ifdef CONFIG_LINUX_AIO
329 BDRVRawState *s = bs->opaque;
332 laio_attach_aio_context(s->aio_ctx, new_context);
337 #ifdef CONFIG_LINUX_AIO
338 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
341 assert(aio_ctx != NULL);
342 assert(use_aio != NULL);
344 * Currently Linux do AIO only for files opened with O_DIRECT
345 * specified so check NOCACHE flag too
347 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
348 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
350 /* if non-NULL, laio_init() has already been run */
351 if (*aio_ctx == NULL) {
352 *aio_ctx = laio_init();
369 static void raw_parse_filename(const char *filename, QDict *options,
372 /* The filename does not have to be prefixed by the protocol name, since
373 * "file" is the default protocol; therefore, the return value of this
374 * function call can be ignored. */
375 strstart(filename, "file:", &filename);
377 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
380 static QemuOptsList raw_runtime_opts = {
382 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
386 .type = QEMU_OPT_STRING,
387 .help = "File name of the image",
389 { /* end of list */ }
393 static int raw_open_common(BlockDriverState *bs, QDict *options,
394 int bdrv_flags, int open_flags, Error **errp)
396 BDRVRawState *s = bs->opaque;
398 Error *local_err = NULL;
399 const char *filename = NULL;
403 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
404 qemu_opts_absorb_qdict(opts, options, &local_err);
406 error_propagate(errp, local_err);
411 filename = qemu_opt_get(opts, "filename");
413 ret = raw_normalize_devicepath(&filename);
415 error_setg_errno(errp, -ret, "Could not normalize device path");
419 s->open_flags = open_flags;
420 raw_parse_flags(bdrv_flags, &s->open_flags);
423 fd = qemu_open(filename, s->open_flags, 0644);
433 #ifdef CONFIG_LINUX_AIO
434 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
437 error_setg_errno(errp, -ret, "Could not set AIO state");
442 s->has_discard = true;
443 s->has_write_zeroes = true;
444 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
445 s->needs_alignment = true;
448 if (fstat(s->fd, &st) < 0) {
449 error_setg_errno(errp, errno, "Could not stat file");
452 if (S_ISREG(st.st_mode)) {
453 s->discard_zeroes = true;
455 if (S_ISBLK(st.st_mode)) {
456 #ifdef BLKDISCARDZEROES
458 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
459 s->discard_zeroes = true;
463 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
464 * not rely on the contents of discarded blocks unless using O_DIRECT.
465 * Same for BLKZEROOUT.
467 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
468 s->discard_zeroes = false;
469 s->has_write_zeroes = false;
474 if (S_ISCHR(st.st_mode)) {
476 * The file is a char device (disk), which on FreeBSD isn't behind
477 * a pager, so force all requests to be aligned. This is needed
478 * so QEMU makes sure all IO operations on the device are aligned
479 * to sector size, or else FreeBSD will reject them with EINVAL.
481 s->needs_alignment = true;
486 if (platform_test_xfs_fd(s->fd)) {
491 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
495 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
502 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
505 BDRVRawState *s = bs->opaque;
506 Error *local_err = NULL;
509 s->type = FTYPE_FILE;
510 ret = raw_open_common(bs, options, flags, 0, &local_err);
512 error_propagate(errp, local_err);
517 static int raw_reopen_prepare(BDRVReopenState *state,
518 BlockReopenQueue *queue, Error **errp)
521 BDRVRawReopenState *raw_s;
523 Error *local_err = NULL;
525 assert(state != NULL);
526 assert(state->bs != NULL);
528 s = state->bs->opaque;
530 state->opaque = g_new0(BDRVRawReopenState, 1);
531 raw_s = state->opaque;
533 #ifdef CONFIG_LINUX_AIO
534 raw_s->use_aio = s->use_aio;
536 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
537 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
538 * won't override aio_ctx if aio_ctx is non-NULL */
539 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
540 error_setg(errp, "Could not set AIO state");
545 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
546 raw_s->open_flags |= O_NONBLOCK;
549 raw_parse_flags(state->flags, &raw_s->open_flags);
553 int fcntl_flags = O_APPEND | O_NONBLOCK;
555 fcntl_flags |= O_NOATIME;
559 /* Not all operating systems have O_ASYNC, and those that don't
560 * will not let us track the state into raw_s->open_flags (typically
561 * you achieve the same effect with an ioctl, for example I_SETSIG
562 * on Solaris). But we do not use O_ASYNC, so that's fine.
564 assert((s->open_flags & O_ASYNC) == 0);
567 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
568 /* dup the original fd */
569 /* TODO: use qemu fcntl wrapper */
570 #ifdef F_DUPFD_CLOEXEC
571 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
573 raw_s->fd = dup(s->fd);
574 if (raw_s->fd != -1) {
575 qemu_set_cloexec(raw_s->fd);
578 if (raw_s->fd >= 0) {
579 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
581 qemu_close(raw_s->fd);
587 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
588 if (raw_s->fd == -1) {
589 assert(!(raw_s->open_flags & O_CREAT));
590 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
591 if (raw_s->fd == -1) {
592 error_setg_errno(errp, errno, "Could not reopen file");
597 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
598 * alignment with the new fd. */
599 if (raw_s->fd != -1) {
600 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
602 qemu_close(raw_s->fd);
604 error_propagate(errp, local_err);
612 static void raw_reopen_commit(BDRVReopenState *state)
614 BDRVRawReopenState *raw_s = state->opaque;
615 BDRVRawState *s = state->bs->opaque;
617 s->open_flags = raw_s->open_flags;
621 #ifdef CONFIG_LINUX_AIO
622 s->use_aio = raw_s->use_aio;
625 g_free(state->opaque);
626 state->opaque = NULL;
630 static void raw_reopen_abort(BDRVReopenState *state)
632 BDRVRawReopenState *raw_s = state->opaque;
634 /* nothing to do if NULL, we didn't get far enough */
639 if (raw_s->fd >= 0) {
640 qemu_close(raw_s->fd);
643 g_free(state->opaque);
644 state->opaque = NULL;
647 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
649 BDRVRawState *s = bs->opaque;
651 raw_probe_alignment(bs, s->fd, errp);
652 bs->bl.opt_mem_alignment = s->buf_align;
655 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
659 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
667 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
671 ret = qemu_fdatasync(aiocb->aio_fildes);
680 static bool preadv_present = true;
683 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
685 return preadv(fd, iov, nr_iov, offset);
689 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
691 return pwritev(fd, iov, nr_iov, offset);
696 static bool preadv_present = false;
699 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
705 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
712 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
717 if (aiocb->aio_type & QEMU_AIO_WRITE)
718 len = qemu_pwritev(aiocb->aio_fildes,
723 len = qemu_preadv(aiocb->aio_fildes,
727 } while (len == -1 && errno == EINTR);
736 * Read/writes the data to/from a given linear buffer.
738 * Returns the number of bytes handles or -errno in case of an error. Short
739 * reads are only returned if the end of the file is reached.
741 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
746 while (offset < aiocb->aio_nbytes) {
747 if (aiocb->aio_type & QEMU_AIO_WRITE) {
748 len = pwrite(aiocb->aio_fildes,
749 (const char *)buf + offset,
750 aiocb->aio_nbytes - offset,
751 aiocb->aio_offset + offset);
753 len = pread(aiocb->aio_fildes,
755 aiocb->aio_nbytes - offset,
756 aiocb->aio_offset + offset);
758 if (len == -1 && errno == EINTR) {
760 } else if (len == -1 && errno == EINVAL &&
761 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
762 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
764 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
765 * after a short read. Assume that O_DIRECT short reads only occur
766 * at EOF. Therefore this is a short read, not an I/O error.
769 } else if (len == -1) {
772 } else if (len == 0) {
781 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
786 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
788 * If there is just a single buffer, and it is properly aligned
789 * we can just use plain pread/pwrite without any problems.
791 if (aiocb->aio_niov == 1) {
792 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
795 * We have more than one iovec, and all are properly aligned.
797 * Try preadv/pwritev first and fall back to linearizing the
798 * buffer if it's not supported.
800 if (preadv_present) {
801 nbytes = handle_aiocb_rw_vector(aiocb);
802 if (nbytes == aiocb->aio_nbytes ||
803 (nbytes < 0 && nbytes != -ENOSYS)) {
806 preadv_present = false;
810 * XXX(hch): short read/write. no easy way to handle the reminder
811 * using these interfaces. For now retry using plain
817 * Ok, we have to do it the hard way, copy all segments into
818 * a single aligned buffer.
820 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
825 if (aiocb->aio_type & QEMU_AIO_WRITE) {
829 for (i = 0; i < aiocb->aio_niov; ++i) {
830 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
831 p += aiocb->aio_iov[i].iov_len;
833 assert(p - buf == aiocb->aio_nbytes);
836 nbytes = handle_aiocb_rw_linear(aiocb, buf);
837 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
839 size_t count = aiocb->aio_nbytes, copy;
842 for (i = 0; i < aiocb->aio_niov && count; ++i) {
844 if (copy > aiocb->aio_iov[i].iov_len) {
845 copy = aiocb->aio_iov[i].iov_len;
847 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
848 assert(count >= copy);
860 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
862 struct xfs_flock64 fl;
864 memset(&fl, 0, sizeof(fl));
865 fl.l_whence = SEEK_SET;
869 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
870 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
877 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
879 struct xfs_flock64 fl;
881 memset(&fl, 0, sizeof(fl));
882 fl.l_whence = SEEK_SET;
886 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
887 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
895 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
897 int ret = -EOPNOTSUPP;
898 BDRVRawState *s = aiocb->bs->opaque;
900 if (s->has_write_zeroes == 0) {
904 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
907 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
908 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
911 } while (errno == EINTR);
918 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
923 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
925 s->has_write_zeroes = false;
931 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
933 int ret = -EOPNOTSUPP;
934 BDRVRawState *s = aiocb->bs->opaque;
936 if (!s->has_discard) {
940 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
943 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
944 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
947 } while (errno == EINTR);
954 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
958 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
960 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
961 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
964 } while (errno == EINTR);
970 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
972 s->has_discard = false;
978 static int aio_worker(void *arg)
980 RawPosixAIOData *aiocb = arg;
983 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
985 ret = handle_aiocb_rw(aiocb);
986 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
987 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
988 0, aiocb->aio_nbytes - ret);
990 ret = aiocb->aio_nbytes;
992 if (ret == aiocb->aio_nbytes) {
994 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
999 ret = handle_aiocb_rw(aiocb);
1000 if (ret == aiocb->aio_nbytes) {
1002 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1006 case QEMU_AIO_FLUSH:
1007 ret = handle_aiocb_flush(aiocb);
1009 case QEMU_AIO_IOCTL:
1010 ret = handle_aiocb_ioctl(aiocb);
1012 case QEMU_AIO_DISCARD:
1013 ret = handle_aiocb_discard(aiocb);
1015 case QEMU_AIO_WRITE_ZEROES:
1016 ret = handle_aiocb_write_zeroes(aiocb);
1019 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1024 g_slice_free(RawPosixAIOData, aiocb);
1028 static int paio_submit_co(BlockDriverState *bs, int fd,
1029 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1032 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1036 acb->aio_type = type;
1037 acb->aio_fildes = fd;
1039 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1040 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1043 acb->aio_iov = qiov->iov;
1044 acb->aio_niov = qiov->niov;
1045 assert(qiov->size == acb->aio_nbytes);
1048 trace_paio_submit_co(sector_num, nb_sectors, type);
1049 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1050 return thread_pool_submit_co(pool, aio_worker, acb);
1053 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1054 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1055 BlockCompletionFunc *cb, void *opaque, int type)
1057 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1061 acb->aio_type = type;
1062 acb->aio_fildes = fd;
1064 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1065 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1068 acb->aio_iov = qiov->iov;
1069 acb->aio_niov = qiov->niov;
1070 assert(qiov->size == acb->aio_nbytes);
1073 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1074 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1075 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1078 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1079 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1080 BlockCompletionFunc *cb, void *opaque, int type)
1082 BDRVRawState *s = bs->opaque;
1084 if (fd_open(bs) < 0)
1088 * Check if the underlying device requires requests to be aligned,
1089 * and if the request we are trying to submit is aligned or not.
1090 * If this is the case tell the low-level driver that it needs
1091 * to copy the buffer.
1093 if (s->needs_alignment) {
1094 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1095 type |= QEMU_AIO_MISALIGNED;
1096 #ifdef CONFIG_LINUX_AIO
1097 } else if (s->use_aio) {
1098 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1099 nb_sectors, cb, opaque, type);
1104 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1108 static void raw_aio_plug(BlockDriverState *bs)
1110 #ifdef CONFIG_LINUX_AIO
1111 BDRVRawState *s = bs->opaque;
1113 laio_io_plug(bs, s->aio_ctx);
1118 static void raw_aio_unplug(BlockDriverState *bs)
1120 #ifdef CONFIG_LINUX_AIO
1121 BDRVRawState *s = bs->opaque;
1123 laio_io_unplug(bs, s->aio_ctx, true);
1128 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1130 #ifdef CONFIG_LINUX_AIO
1131 BDRVRawState *s = bs->opaque;
1133 laio_io_unplug(bs, s->aio_ctx, false);
1138 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1139 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1140 BlockCompletionFunc *cb, void *opaque)
1142 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1143 cb, opaque, QEMU_AIO_READ);
1146 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1147 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1148 BlockCompletionFunc *cb, void *opaque)
1150 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1151 cb, opaque, QEMU_AIO_WRITE);
1154 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1155 BlockCompletionFunc *cb, void *opaque)
1157 BDRVRawState *s = bs->opaque;
1159 if (fd_open(bs) < 0)
1162 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1165 static void raw_close(BlockDriverState *bs)
1167 BDRVRawState *s = bs->opaque;
1169 raw_detach_aio_context(bs);
1171 #ifdef CONFIG_LINUX_AIO
1173 laio_cleanup(s->aio_ctx);
1182 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1184 BDRVRawState *s = bs->opaque;
1187 if (fstat(s->fd, &st)) {
1191 if (S_ISREG(st.st_mode)) {
1192 if (ftruncate(s->fd, offset) < 0) {
1195 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1196 if (offset > raw_getlength(bs)) {
1207 static int64_t raw_getlength(BlockDriverState *bs)
1209 BDRVRawState *s = bs->opaque;
1215 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1216 struct disklabel dl;
1218 if (ioctl(fd, DIOCGDINFO, &dl))
1220 return (uint64_t)dl.d_secsize *
1221 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1225 #elif defined(__NetBSD__)
1226 static int64_t raw_getlength(BlockDriverState *bs)
1228 BDRVRawState *s = bs->opaque;
1234 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1235 struct dkwedge_info dkw;
1237 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1238 return dkw.dkw_size * 512;
1240 struct disklabel dl;
1242 if (ioctl(fd, DIOCGDINFO, &dl))
1244 return (uint64_t)dl.d_secsize *
1245 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1250 #elif defined(__sun__)
1251 static int64_t raw_getlength(BlockDriverState *bs)
1253 BDRVRawState *s = bs->opaque;
1254 struct dk_minfo minfo;
1264 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1266 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1268 return minfo.dki_lbsize * minfo.dki_capacity;
1272 * There are reports that lseek on some devices fails, but
1273 * irc discussion said that contingency on contingency was overkill.
1275 size = lseek(s->fd, 0, SEEK_END);
1281 #elif defined(CONFIG_BSD)
1282 static int64_t raw_getlength(BlockDriverState *bs)
1284 BDRVRawState *s = bs->opaque;
1288 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1297 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1300 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1301 #ifdef DIOCGMEDIASIZE
1302 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1303 #elif defined(DIOCGPART)
1306 if (ioctl(fd, DIOCGPART, &pi) == 0)
1307 size = pi.media_size;
1313 #if defined(__APPLE__) && defined(__MACH__)
1316 size = lseek(fd, 0LL, SEEK_END);
1321 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1324 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1325 if (size == 2048LL * (unsigned)-1)
1327 /* XXX no disc? maybe we need to reopen... */
1328 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1335 size = lseek(fd, 0, SEEK_END);
1343 static int64_t raw_getlength(BlockDriverState *bs)
1345 BDRVRawState *s = bs->opaque;
1354 size = lseek(s->fd, 0, SEEK_END);
1362 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1365 BDRVRawState *s = bs->opaque;
1367 if (fstat(s->fd, &st) < 0) {
1370 return (int64_t)st.st_blocks * 512;
1373 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1377 int64_t total_size = 0;
1379 PreallocMode prealloc;
1381 Error *local_err = NULL;
1383 strstart(filename, "file:", &filename);
1385 /* Read out options */
1386 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1388 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1389 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1390 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1391 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1395 error_propagate(errp, local_err);
1400 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1404 error_setg_errno(errp, -result, "Could not create file");
1410 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1411 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1412 * will be ignored since any failure of this operation should not
1413 * block the left work.
1416 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1417 attr |= FS_NOCOW_FL;
1418 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1423 if (ftruncate(fd, total_size) != 0) {
1425 error_setg_errno(errp, -result, "Could not resize file");
1430 #ifdef CONFIG_POSIX_FALLOCATE
1431 case PREALLOC_MODE_FALLOC:
1432 /* posix_fallocate() doesn't set errno. */
1433 result = -posix_fallocate(fd, 0, total_size);
1435 error_setg_errno(errp, -result,
1436 "Could not preallocate data for the new file");
1440 case PREALLOC_MODE_FULL:
1442 int64_t num = 0, left = total_size;
1443 buf = g_malloc0(65536);
1446 num = MIN(left, 65536);
1447 result = write(fd, buf, num);
1450 error_setg_errno(errp, -result,
1451 "Could not write to the new file");
1460 error_setg_errno(errp, -result,
1461 "Could not flush new file to disk");
1467 case PREALLOC_MODE_OFF:
1471 error_setg(errp, "Unsupported preallocation mode: %s",
1472 PreallocMode_lookup[prealloc]);
1477 if (qemu_close(fd) != 0 && result == 0) {
1479 error_setg_errno(errp, -result, "Could not close the new file");
1486 * Find allocation range in @bs around offset @start.
1487 * May change underlying file descriptor's file offset.
1488 * If @start is not in a hole, store @start in @data, and the
1489 * beginning of the next hole in @hole, and return 0.
1490 * If @start is in a non-trailing hole, store @start in @hole and the
1491 * beginning of the next non-hole in @data, and return 0.
1492 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1493 * If we can't find out, return a negative errno other than -ENXIO.
1495 static int find_allocation(BlockDriverState *bs, off_t start,
1496 off_t *data, off_t *hole)
1498 #if defined SEEK_HOLE && defined SEEK_DATA
1499 BDRVRawState *s = bs->opaque;
1504 * D1. offs == start: start is in data
1505 * D2. offs > start: start is in a hole, next data at offs
1506 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1507 * or start is beyond EOF
1508 * If the latter happens, the file has been truncated behind
1509 * our back since we opened it. All bets are off then.
1510 * Treating like a trailing hole is simplest.
1511 * D4. offs < 0, errno != ENXIO: we learned nothing
1513 offs = lseek(s->fd, start, SEEK_DATA);
1515 return -errno; /* D3 or D4 */
1517 assert(offs >= start);
1520 /* D2: in hole, next data at offs */
1526 /* D1: in data, end not yet known */
1530 * H1. offs == start: start is in a hole
1531 * If this happens here, a hole has been dug behind our back
1532 * since the previous lseek().
1533 * H2. offs > start: either start is in data, next hole at offs,
1534 * or start is in trailing hole, EOF at offs
1535 * Linux treats trailing holes like any other hole: offs ==
1536 * start. Solaris seeks to EOF instead: offs > start (blech).
1537 * If that happens here, a hole has been dug behind our back
1538 * since the previous lseek().
1539 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1540 * If this happens, the file has been truncated behind our
1541 * back since we opened it. Treat it like a trailing hole.
1542 * H4. offs < 0, errno != ENXIO: we learned nothing
1543 * Pretend we know nothing at all, i.e. "forget" about D1.
1545 offs = lseek(s->fd, start, SEEK_HOLE);
1547 return -errno; /* D1 and (H3 or H4) */
1549 assert(offs >= start);
1553 * D1 and H2: either in data, next hole at offs, or it was in
1554 * data but is now in a trailing hole. In the latter case,
1555 * all bets are off. Treating it as if it there was data all
1556 * the way to EOF is safe, so simply do that.
1571 * Returns the allocation status of the specified sectors.
1573 * If 'sector_num' is beyond the end of the disk image the return value is 0
1574 * and 'pnum' is set to 0.
1576 * 'pnum' is set to the number of sectors (including and immediately following
1577 * the specified sector) that are known to be in the same
1578 * allocated/unallocated state.
1580 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1581 * beyond the end of the disk image it will be clamped.
1583 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1585 int nb_sectors, int *pnum)
1587 off_t start, data = 0, hole = 0;
1596 start = sector_num * BDRV_SECTOR_SIZE;
1597 total_size = bdrv_getlength(bs);
1598 if (total_size < 0) {
1600 } else if (start >= total_size) {
1603 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1604 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1607 ret = find_allocation(bs, start, &data, &hole);
1608 if (ret == -ENXIO) {
1611 ret = BDRV_BLOCK_ZERO;
1612 } else if (ret < 0) {
1613 /* No info available, so pretend there are no holes */
1615 ret = BDRV_BLOCK_DATA;
1616 } else if (data == start) {
1617 /* On a data extent, compute sectors to the end of the extent. */
1618 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1619 ret = BDRV_BLOCK_DATA;
1621 /* On a hole, compute sectors to the beginning of the next extent. */
1622 assert(hole == start);
1623 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1624 ret = BDRV_BLOCK_ZERO;
1626 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1629 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1630 int64_t sector_num, int nb_sectors,
1631 BlockCompletionFunc *cb, void *opaque)
1633 BDRVRawState *s = bs->opaque;
1635 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1636 cb, opaque, QEMU_AIO_DISCARD);
1639 static int coroutine_fn raw_co_write_zeroes(
1640 BlockDriverState *bs, int64_t sector_num,
1641 int nb_sectors, BdrvRequestFlags flags)
1643 BDRVRawState *s = bs->opaque;
1645 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1646 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1647 QEMU_AIO_WRITE_ZEROES);
1648 } else if (s->discard_zeroes) {
1649 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1655 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1657 BDRVRawState *s = bs->opaque;
1659 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1660 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1664 static QemuOptsList raw_create_opts = {
1665 .name = "raw-create-opts",
1666 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1669 .name = BLOCK_OPT_SIZE,
1670 .type = QEMU_OPT_SIZE,
1671 .help = "Virtual disk size"
1674 .name = BLOCK_OPT_NOCOW,
1675 .type = QEMU_OPT_BOOL,
1676 .help = "Turn off copy-on-write (valid only on btrfs)"
1679 .name = BLOCK_OPT_PREALLOC,
1680 .type = QEMU_OPT_STRING,
1681 .help = "Preallocation mode (allowed values: off, falloc, full)"
1683 { /* end of list */ }
1687 static BlockDriver bdrv_file = {
1688 .format_name = "file",
1689 .protocol_name = "file",
1690 .instance_size = sizeof(BDRVRawState),
1691 .bdrv_needs_filename = true,
1692 .bdrv_probe = NULL, /* no probe for protocols */
1693 .bdrv_parse_filename = raw_parse_filename,
1694 .bdrv_file_open = raw_open,
1695 .bdrv_reopen_prepare = raw_reopen_prepare,
1696 .bdrv_reopen_commit = raw_reopen_commit,
1697 .bdrv_reopen_abort = raw_reopen_abort,
1698 .bdrv_close = raw_close,
1699 .bdrv_create = raw_create,
1700 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1701 .bdrv_co_get_block_status = raw_co_get_block_status,
1702 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1704 .bdrv_aio_readv = raw_aio_readv,
1705 .bdrv_aio_writev = raw_aio_writev,
1706 .bdrv_aio_flush = raw_aio_flush,
1707 .bdrv_aio_discard = raw_aio_discard,
1708 .bdrv_refresh_limits = raw_refresh_limits,
1709 .bdrv_io_plug = raw_aio_plug,
1710 .bdrv_io_unplug = raw_aio_unplug,
1711 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1713 .bdrv_truncate = raw_truncate,
1714 .bdrv_getlength = raw_getlength,
1715 .bdrv_get_info = raw_get_info,
1716 .bdrv_get_allocated_file_size
1717 = raw_get_allocated_file_size,
1719 .bdrv_detach_aio_context = raw_detach_aio_context,
1720 .bdrv_attach_aio_context = raw_attach_aio_context,
1722 .create_opts = &raw_create_opts,
1725 /***********************************************/
1728 #if defined(__APPLE__) && defined(__MACH__)
1729 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1730 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1732 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1734 kern_return_t kernResult;
1735 mach_port_t masterPort;
1736 CFMutableDictionaryRef classesToMatch;
1738 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1739 if ( KERN_SUCCESS != kernResult ) {
1740 printf( "IOMasterPort returned %d\n", kernResult );
1743 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1744 if ( classesToMatch == NULL ) {
1745 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1747 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1749 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1750 if ( KERN_SUCCESS != kernResult )
1752 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1758 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1760 io_object_t nextMedia;
1761 kern_return_t kernResult = KERN_FAILURE;
1763 nextMedia = IOIteratorNext( mediaIterator );
1766 CFTypeRef bsdPathAsCFString;
1767 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1768 if ( bsdPathAsCFString ) {
1769 size_t devPathLength;
1770 strcpy( bsdPath, _PATH_DEV );
1771 strcat( bsdPath, "r" );
1772 devPathLength = strlen( bsdPath );
1773 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1774 kernResult = KERN_SUCCESS;
1776 CFRelease( bsdPathAsCFString );
1778 IOObjectRelease( nextMedia );
1786 static int hdev_probe_device(const char *filename)
1790 /* allow a dedicated CD-ROM driver to match with a higher priority */
1791 if (strstart(filename, "/dev/cdrom", NULL))
1794 if (stat(filename, &st) >= 0 &&
1795 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1802 static int check_hdev_writable(BDRVRawState *s)
1804 #if defined(BLKROGET)
1805 /* Linux block devices can be configured "read-only" using blockdev(8).
1806 * This is independent of device node permissions and therefore open(2)
1807 * with O_RDWR succeeds. Actual writes fail with EPERM.
1809 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1810 * check for read-only block devices so that Linux block devices behave
1816 if (fstat(s->fd, &st)) {
1820 if (!S_ISBLK(st.st_mode)) {
1824 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1831 #endif /* defined(BLKROGET) */
1835 static void hdev_parse_filename(const char *filename, QDict *options,
1838 /* The prefix is optional, just as for "file". */
1839 strstart(filename, "host_device:", &filename);
1841 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1844 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1847 BDRVRawState *s = bs->opaque;
1848 Error *local_err = NULL;
1850 const char *filename = qdict_get_str(options, "filename");
1852 #if defined(__APPLE__) && defined(__MACH__)
1853 if (strstart(filename, "/dev/cdrom", NULL)) {
1854 kern_return_t kernResult;
1855 io_iterator_t mediaIterator;
1856 char bsdPath[ MAXPATHLEN ];
1859 kernResult = FindEjectableCDMedia( &mediaIterator );
1860 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1862 if ( bsdPath[ 0 ] != '\0' ) {
1863 strcat(bsdPath,"s0");
1864 /* some CDs don't have a partition 0 */
1865 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1867 bsdPath[strlen(bsdPath)-1] = '1';
1872 qdict_put(options, "filename", qstring_from_str(filename));
1875 if ( mediaIterator )
1876 IOObjectRelease( mediaIterator );
1880 s->type = FTYPE_FILE;
1881 #if defined(__linux__)
1883 char resolved_path[ MAXPATHLEN ], *temp;
1885 temp = realpath(filename, resolved_path);
1886 if (temp && strstart(temp, "/dev/sg", NULL)) {
1892 ret = raw_open_common(bs, options, flags, 0, &local_err);
1895 error_propagate(errp, local_err);
1900 if (flags & BDRV_O_RDWR) {
1901 ret = check_hdev_writable(s);
1904 error_setg_errno(errp, -ret, "The device is not writable");
1912 #if defined(__linux__)
1913 /* Note: we do not have a reliable method to detect if the floppy is
1914 present. The current method is to try to open the floppy at every
1915 I/O and to keep it opened during a few hundreds of ms. */
1916 static int fd_open(BlockDriverState *bs)
1918 BDRVRawState *s = bs->opaque;
1919 int last_media_present;
1921 if (s->type != FTYPE_FD)
1923 last_media_present = (s->fd >= 0);
1925 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1929 printf("Floppy closed\n");
1933 if (s->fd_got_error &&
1934 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1936 printf("No floppy (open delayed)\n");
1940 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1942 s->fd_error_time = get_clock();
1943 s->fd_got_error = 1;
1944 if (last_media_present)
1945 s->fd_media_changed = 1;
1947 printf("No floppy\n");
1952 printf("Floppy opened\n");
1955 if (!last_media_present)
1956 s->fd_media_changed = 1;
1957 s->fd_open_time = get_clock();
1958 s->fd_got_error = 0;
1962 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1964 BDRVRawState *s = bs->opaque;
1966 return ioctl(s->fd, req, buf);
1969 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1970 unsigned long int req, void *buf,
1971 BlockCompletionFunc *cb, void *opaque)
1973 BDRVRawState *s = bs->opaque;
1974 RawPosixAIOData *acb;
1977 if (fd_open(bs) < 0)
1980 acb = g_slice_new(RawPosixAIOData);
1982 acb->aio_type = QEMU_AIO_IOCTL;
1983 acb->aio_fildes = s->fd;
1984 acb->aio_offset = 0;
1985 acb->aio_ioctl_buf = buf;
1986 acb->aio_ioctl_cmd = req;
1987 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1988 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1991 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1992 static int fd_open(BlockDriverState *bs)
1994 BDRVRawState *s = bs->opaque;
1996 /* this is just to ensure s->fd is sane (its called by io ops) */
2001 #else /* !linux && !FreeBSD */
2003 static int fd_open(BlockDriverState *bs)
2008 #endif /* !linux && !FreeBSD */
2010 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2011 int64_t sector_num, int nb_sectors,
2012 BlockCompletionFunc *cb, void *opaque)
2014 BDRVRawState *s = bs->opaque;
2016 if (fd_open(bs) < 0) {
2019 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2020 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2023 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2024 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2026 BDRVRawState *s = bs->opaque;
2033 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2034 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2035 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2036 } else if (s->discard_zeroes) {
2037 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2038 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2043 static int hdev_create(const char *filename, QemuOpts *opts,
2048 struct stat stat_buf;
2049 int64_t total_size = 0;
2052 /* This function is used by all three protocol block drivers and therefore
2053 * any of these three prefixes may be given.
2054 * The return value has to be stored somewhere, otherwise this is an error
2055 * due to -Werror=unused-value. */
2057 strstart(filename, "host_device:", &filename) ||
2058 strstart(filename, "host_cdrom:" , &filename) ||
2059 strstart(filename, "host_floppy:", &filename);
2063 /* Read out options */
2064 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2067 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2070 error_setg_errno(errp, -ret, "Could not open device");
2074 if (fstat(fd, &stat_buf) < 0) {
2076 error_setg_errno(errp, -ret, "Could not stat device");
2077 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2079 "The given file is neither a block nor a character device");
2081 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2082 error_setg(errp, "Device is too small");
2090 static BlockDriver bdrv_host_device = {
2091 .format_name = "host_device",
2092 .protocol_name = "host_device",
2093 .instance_size = sizeof(BDRVRawState),
2094 .bdrv_needs_filename = true,
2095 .bdrv_probe_device = hdev_probe_device,
2096 .bdrv_parse_filename = hdev_parse_filename,
2097 .bdrv_file_open = hdev_open,
2098 .bdrv_close = raw_close,
2099 .bdrv_reopen_prepare = raw_reopen_prepare,
2100 .bdrv_reopen_commit = raw_reopen_commit,
2101 .bdrv_reopen_abort = raw_reopen_abort,
2102 .bdrv_create = hdev_create,
2103 .create_opts = &raw_create_opts,
2104 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2106 .bdrv_aio_readv = raw_aio_readv,
2107 .bdrv_aio_writev = raw_aio_writev,
2108 .bdrv_aio_flush = raw_aio_flush,
2109 .bdrv_aio_discard = hdev_aio_discard,
2110 .bdrv_refresh_limits = raw_refresh_limits,
2111 .bdrv_io_plug = raw_aio_plug,
2112 .bdrv_io_unplug = raw_aio_unplug,
2113 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2115 .bdrv_truncate = raw_truncate,
2116 .bdrv_getlength = raw_getlength,
2117 .bdrv_get_info = raw_get_info,
2118 .bdrv_get_allocated_file_size
2119 = raw_get_allocated_file_size,
2121 .bdrv_detach_aio_context = raw_detach_aio_context,
2122 .bdrv_attach_aio_context = raw_attach_aio_context,
2124 /* generic scsi device */
2126 .bdrv_ioctl = hdev_ioctl,
2127 .bdrv_aio_ioctl = hdev_aio_ioctl,
2132 static void floppy_parse_filename(const char *filename, QDict *options,
2135 /* The prefix is optional, just as for "file". */
2136 strstart(filename, "host_floppy:", &filename);
2138 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2141 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2144 BDRVRawState *s = bs->opaque;
2145 Error *local_err = NULL;
2150 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2151 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2154 error_propagate(errp, local_err);
2159 /* close fd so that we can reopen it as needed */
2162 s->fd_media_changed = 1;
2167 static int floppy_probe_device(const char *filename)
2171 struct floppy_struct fdparam;
2174 if (strstart(filename, "/dev/fd", NULL) &&
2175 !strstart(filename, "/dev/fdset/", NULL)) {
2179 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2183 ret = fstat(fd, &st);
2184 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2188 /* Attempt to detect via a floppy specific ioctl */
2189 ret = ioctl(fd, FDGETPRM, &fdparam);
2200 static int floppy_is_inserted(BlockDriverState *bs)
2202 return fd_open(bs) >= 0;
2205 static int floppy_media_changed(BlockDriverState *bs)
2207 BDRVRawState *s = bs->opaque;
2211 * XXX: we do not have a true media changed indication.
2212 * It does not work if the floppy is changed without trying to read it.
2215 ret = s->fd_media_changed;
2216 s->fd_media_changed = 0;
2218 printf("Floppy changed=%d\n", ret);
2223 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2225 BDRVRawState *s = bs->opaque;
2232 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2234 if (ioctl(fd, FDEJECT, 0) < 0)
2240 static BlockDriver bdrv_host_floppy = {
2241 .format_name = "host_floppy",
2242 .protocol_name = "host_floppy",
2243 .instance_size = sizeof(BDRVRawState),
2244 .bdrv_needs_filename = true,
2245 .bdrv_probe_device = floppy_probe_device,
2246 .bdrv_parse_filename = floppy_parse_filename,
2247 .bdrv_file_open = floppy_open,
2248 .bdrv_close = raw_close,
2249 .bdrv_reopen_prepare = raw_reopen_prepare,
2250 .bdrv_reopen_commit = raw_reopen_commit,
2251 .bdrv_reopen_abort = raw_reopen_abort,
2252 .bdrv_create = hdev_create,
2253 .create_opts = &raw_create_opts,
2255 .bdrv_aio_readv = raw_aio_readv,
2256 .bdrv_aio_writev = raw_aio_writev,
2257 .bdrv_aio_flush = raw_aio_flush,
2258 .bdrv_refresh_limits = raw_refresh_limits,
2259 .bdrv_io_plug = raw_aio_plug,
2260 .bdrv_io_unplug = raw_aio_unplug,
2261 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2263 .bdrv_truncate = raw_truncate,
2264 .bdrv_getlength = raw_getlength,
2265 .has_variable_length = true,
2266 .bdrv_get_allocated_file_size
2267 = raw_get_allocated_file_size,
2269 .bdrv_detach_aio_context = raw_detach_aio_context,
2270 .bdrv_attach_aio_context = raw_attach_aio_context,
2272 /* removable device support */
2273 .bdrv_is_inserted = floppy_is_inserted,
2274 .bdrv_media_changed = floppy_media_changed,
2275 .bdrv_eject = floppy_eject,
2279 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2280 static void cdrom_parse_filename(const char *filename, QDict *options,
2283 /* The prefix is optional, just as for "file". */
2284 strstart(filename, "host_cdrom:", &filename);
2286 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2291 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2294 BDRVRawState *s = bs->opaque;
2295 Error *local_err = NULL;
2300 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2301 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2303 error_propagate(errp, local_err);
2308 static int cdrom_probe_device(const char *filename)
2314 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2318 ret = fstat(fd, &st);
2319 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2323 /* Attempt to detect via a CDROM specific ioctl */
2324 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2334 static int cdrom_is_inserted(BlockDriverState *bs)
2336 BDRVRawState *s = bs->opaque;
2339 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2340 if (ret == CDS_DISC_OK)
2345 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2347 BDRVRawState *s = bs->opaque;
2350 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2351 perror("CDROMEJECT");
2353 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2354 perror("CDROMEJECT");
2358 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2360 BDRVRawState *s = bs->opaque;
2362 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2364 * Note: an error can happen if the distribution automatically
2367 /* perror("CDROM_LOCKDOOR"); */
2371 static BlockDriver bdrv_host_cdrom = {
2372 .format_name = "host_cdrom",
2373 .protocol_name = "host_cdrom",
2374 .instance_size = sizeof(BDRVRawState),
2375 .bdrv_needs_filename = true,
2376 .bdrv_probe_device = cdrom_probe_device,
2377 .bdrv_parse_filename = cdrom_parse_filename,
2378 .bdrv_file_open = cdrom_open,
2379 .bdrv_close = raw_close,
2380 .bdrv_reopen_prepare = raw_reopen_prepare,
2381 .bdrv_reopen_commit = raw_reopen_commit,
2382 .bdrv_reopen_abort = raw_reopen_abort,
2383 .bdrv_create = hdev_create,
2384 .create_opts = &raw_create_opts,
2386 .bdrv_aio_readv = raw_aio_readv,
2387 .bdrv_aio_writev = raw_aio_writev,
2388 .bdrv_aio_flush = raw_aio_flush,
2389 .bdrv_refresh_limits = raw_refresh_limits,
2390 .bdrv_io_plug = raw_aio_plug,
2391 .bdrv_io_unplug = raw_aio_unplug,
2392 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2394 .bdrv_truncate = raw_truncate,
2395 .bdrv_getlength = raw_getlength,
2396 .has_variable_length = true,
2397 .bdrv_get_allocated_file_size
2398 = raw_get_allocated_file_size,
2400 .bdrv_detach_aio_context = raw_detach_aio_context,
2401 .bdrv_attach_aio_context = raw_attach_aio_context,
2403 /* removable device support */
2404 .bdrv_is_inserted = cdrom_is_inserted,
2405 .bdrv_eject = cdrom_eject,
2406 .bdrv_lock_medium = cdrom_lock_medium,
2408 /* generic scsi device */
2409 .bdrv_ioctl = hdev_ioctl,
2410 .bdrv_aio_ioctl = hdev_aio_ioctl,
2412 #endif /* __linux__ */
2414 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2415 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2418 BDRVRawState *s = bs->opaque;
2419 Error *local_err = NULL;
2424 ret = raw_open_common(bs, options, flags, 0, &local_err);
2427 error_propagate(errp, local_err);
2432 /* make sure the door isn't locked at this time */
2433 ioctl(s->fd, CDIOCALLOW);
2437 static int cdrom_probe_device(const char *filename)
2439 if (strstart(filename, "/dev/cd", NULL) ||
2440 strstart(filename, "/dev/acd", NULL))
2445 static int cdrom_reopen(BlockDriverState *bs)
2447 BDRVRawState *s = bs->opaque;
2451 * Force reread of possibly changed/newly loaded disc,
2452 * FreeBSD seems to not notice sometimes...
2456 fd = qemu_open(bs->filename, s->open_flags, 0644);
2463 /* make sure the door isn't locked at this time */
2464 ioctl(s->fd, CDIOCALLOW);
2468 static int cdrom_is_inserted(BlockDriverState *bs)
2470 return raw_getlength(bs) > 0;
2473 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2475 BDRVRawState *s = bs->opaque;
2480 (void) ioctl(s->fd, CDIOCALLOW);
2483 if (ioctl(s->fd, CDIOCEJECT) < 0)
2484 perror("CDIOCEJECT");
2486 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2487 perror("CDIOCCLOSE");
2493 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2495 BDRVRawState *s = bs->opaque;
2499 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2501 * Note: an error can happen if the distribution automatically
2504 /* perror("CDROM_LOCKDOOR"); */
2508 static BlockDriver bdrv_host_cdrom = {
2509 .format_name = "host_cdrom",
2510 .protocol_name = "host_cdrom",
2511 .instance_size = sizeof(BDRVRawState),
2512 .bdrv_needs_filename = true,
2513 .bdrv_probe_device = cdrom_probe_device,
2514 .bdrv_parse_filename = cdrom_parse_filename,
2515 .bdrv_file_open = cdrom_open,
2516 .bdrv_close = raw_close,
2517 .bdrv_reopen_prepare = raw_reopen_prepare,
2518 .bdrv_reopen_commit = raw_reopen_commit,
2519 .bdrv_reopen_abort = raw_reopen_abort,
2520 .bdrv_create = hdev_create,
2521 .create_opts = &raw_create_opts,
2523 .bdrv_aio_readv = raw_aio_readv,
2524 .bdrv_aio_writev = raw_aio_writev,
2525 .bdrv_aio_flush = raw_aio_flush,
2526 .bdrv_refresh_limits = raw_refresh_limits,
2527 .bdrv_io_plug = raw_aio_plug,
2528 .bdrv_io_unplug = raw_aio_unplug,
2529 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2531 .bdrv_truncate = raw_truncate,
2532 .bdrv_getlength = raw_getlength,
2533 .has_variable_length = true,
2534 .bdrv_get_allocated_file_size
2535 = raw_get_allocated_file_size,
2537 .bdrv_detach_aio_context = raw_detach_aio_context,
2538 .bdrv_attach_aio_context = raw_attach_aio_context,
2540 /* removable device support */
2541 .bdrv_is_inserted = cdrom_is_inserted,
2542 .bdrv_eject = cdrom_eject,
2543 .bdrv_lock_medium = cdrom_lock_medium,
2545 #endif /* __FreeBSD__ */
2547 static void bdrv_file_init(void)
2550 * Register all the drivers. Note that order is important, the driver
2551 * registered last will get probed first.
2553 bdrv_register(&bdrv_file);
2554 bdrv_register(&bdrv_host_device);
2556 bdrv_register(&bdrv_host_floppy);
2557 bdrv_register(&bdrv_host_cdrom);
2559 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2560 bdrv_register(&bdrv_host_cdrom);
2564 block_init(bdrv_file_init);