PPC: Reset qemu timers when guest reset
[qemu/ar7.git] / block / raw-posix.c
blob87d888ed01a6555e984a8a923f8611157b9b51b1
1 /*
2 * Block driver for RAW files (posix)
4 * Copyright (c) 2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
26 #include "qemu/log.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "trace.h"
30 #include "block/thread-pool.h"
31 #include "qemu/iov.h"
32 #include "raw-aio.h"
34 #if defined(__APPLE__) && (__MACH__)
35 #include <paths.h>
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
44 #endif
46 #ifdef __sun__
47 #define _POSIX_PTHREAD_SEMANTICS 1
48 #include <sys/dkio.h>
49 #endif
50 #ifdef __linux__
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <sys/ioctl.h>
54 #include <sys/param.h>
55 #include <linux/cdrom.h>
56 #include <linux/fd.h>
57 #include <linux/fs.h>
58 #endif
59 #ifdef CONFIG_FIEMAP
60 #include <linux/fiemap.h>
61 #endif
62 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
63 #include <sys/disk.h>
64 #include <sys/cdio.h>
65 #endif
67 #ifdef __OpenBSD__
68 #include <sys/ioctl.h>
69 #include <sys/disklabel.h>
70 #include <sys/dkio.h>
71 #endif
73 #ifdef __NetBSD__
74 #include <sys/ioctl.h>
75 #include <sys/disklabel.h>
76 #include <sys/dkio.h>
77 #include <sys/disk.h>
78 #endif
80 #ifdef __DragonFly__
81 #include <sys/ioctl.h>
82 #include <sys/diskslice.h>
83 #endif
85 #ifdef CONFIG_XFS
86 #include <xfs/xfs.h>
87 #endif
89 //#define DEBUG_FLOPPY
91 //#define DEBUG_BLOCK
92 #if defined(DEBUG_BLOCK)
93 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
94 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
95 #else
96 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
97 #endif
99 /* OS X does not have O_DSYNC */
100 #ifndef O_DSYNC
101 #ifdef O_SYNC
102 #define O_DSYNC O_SYNC
103 #elif defined(O_FSYNC)
104 #define O_DSYNC O_FSYNC
105 #endif
106 #endif
108 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
109 #ifndef O_DIRECT
110 #define O_DIRECT O_DSYNC
111 #endif
113 #define FTYPE_FILE 0
114 #define FTYPE_CD 1
115 #define FTYPE_FD 2
117 /* if the FD is not accessed during that time (in ns), we try to
118 reopen it to see if the disk has been changed */
119 #define FD_OPEN_TIMEOUT (1000000000)
121 #define MAX_BLOCKSIZE 4096
123 typedef struct BDRVRawState {
124 int fd;
125 int type;
126 int open_flags;
127 #if defined(__linux__)
128 /* linux floppy specific */
129 int64_t fd_open_time;
130 int64_t fd_error_time;
131 int fd_got_error;
132 int fd_media_changed;
133 #endif
134 #ifdef CONFIG_LINUX_AIO
135 int use_aio;
136 void *aio_ctx;
137 #endif
138 #ifdef CONFIG_XFS
139 bool is_xfs : 1;
140 #endif
141 } BDRVRawState;
143 typedef struct BDRVRawReopenState {
144 int fd;
145 int open_flags;
146 #ifdef CONFIG_LINUX_AIO
147 int use_aio;
148 #endif
149 } BDRVRawReopenState;
151 static int fd_open(BlockDriverState *bs);
152 static int64_t raw_getlength(BlockDriverState *bs);
154 typedef struct RawPosixAIOData {
155 BlockDriverState *bs;
156 int aio_fildes;
157 union {
158 struct iovec *aio_iov;
159 void *aio_ioctl_buf;
161 int aio_niov;
162 size_t aio_nbytes;
163 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
164 off_t aio_offset;
165 int aio_type;
166 } RawPosixAIOData;
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
169 static int cdrom_reopen(BlockDriverState *bs);
170 #endif
172 #if defined(__NetBSD__)
173 static int raw_normalize_devicepath(const char **filename)
175 static char namebuf[PATH_MAX];
176 const char *dp, *fname;
177 struct stat sb;
179 fname = *filename;
180 dp = strrchr(fname, '/');
181 if (lstat(fname, &sb) < 0) {
182 fprintf(stderr, "%s: stat failed: %s\n",
183 fname, strerror(errno));
184 return -errno;
187 if (!S_ISBLK(sb.st_mode)) {
188 return 0;
191 if (dp == NULL) {
192 snprintf(namebuf, PATH_MAX, "r%s", fname);
193 } else {
194 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
195 (int)(dp - fname), fname, dp + 1);
197 fprintf(stderr, "%s is a block device", fname);
198 *filename = namebuf;
199 fprintf(stderr, ", using %s\n", *filename);
201 return 0;
203 #else
204 static int raw_normalize_devicepath(const char **filename)
206 return 0;
208 #endif
210 static void raw_parse_flags(int bdrv_flags, int *open_flags)
212 assert(open_flags != NULL);
214 *open_flags |= O_BINARY;
215 *open_flags &= ~O_ACCMODE;
216 if (bdrv_flags & BDRV_O_RDWR) {
217 *open_flags |= O_RDWR;
218 } else {
219 *open_flags |= O_RDONLY;
222 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
223 * and O_DIRECT for no caching. */
224 if ((bdrv_flags & BDRV_O_NOCACHE)) {
225 *open_flags |= O_DIRECT;
229 #ifdef CONFIG_LINUX_AIO
230 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
232 int ret = -1;
233 assert(aio_ctx != NULL);
234 assert(use_aio != NULL);
236 * Currently Linux do AIO only for files opened with O_DIRECT
237 * specified so check NOCACHE flag too
239 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
240 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
242 /* if non-NULL, laio_init() has already been run */
243 if (*aio_ctx == NULL) {
244 *aio_ctx = laio_init();
245 if (!*aio_ctx) {
246 goto error;
249 *use_aio = 1;
250 } else {
251 *use_aio = 0;
254 ret = 0;
256 error:
257 return ret;
259 #endif
261 static int raw_open_common(BlockDriverState *bs, const char *filename,
262 int bdrv_flags, int open_flags)
264 BDRVRawState *s = bs->opaque;
265 int fd, ret;
267 ret = raw_normalize_devicepath(&filename);
268 if (ret != 0) {
269 return ret;
272 s->open_flags = open_flags;
273 raw_parse_flags(bdrv_flags, &s->open_flags);
275 s->fd = -1;
276 fd = qemu_open(filename, s->open_flags, 0644);
277 if (fd < 0) {
278 ret = -errno;
279 if (ret == -EROFS)
280 ret = -EACCES;
281 return ret;
283 s->fd = fd;
285 #ifdef CONFIG_LINUX_AIO
286 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
287 qemu_close(fd);
288 return -errno;
290 #endif
292 #ifdef CONFIG_XFS
293 if (platform_test_xfs_fd(s->fd)) {
294 s->is_xfs = 1;
296 #endif
298 return 0;
301 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
303 BDRVRawState *s = bs->opaque;
305 s->type = FTYPE_FILE;
306 return raw_open_common(bs, filename, flags, 0);
309 static int raw_reopen_prepare(BDRVReopenState *state,
310 BlockReopenQueue *queue, Error **errp)
312 BDRVRawState *s;
313 BDRVRawReopenState *raw_s;
314 int ret = 0;
316 assert(state != NULL);
317 assert(state->bs != NULL);
319 s = state->bs->opaque;
321 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
322 raw_s = state->opaque;
324 #ifdef CONFIG_LINUX_AIO
325 raw_s->use_aio = s->use_aio;
327 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
328 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
329 * won't override aio_ctx if aio_ctx is non-NULL */
330 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
331 return -1;
333 #endif
335 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
336 raw_s->open_flags |= O_NONBLOCK;
339 raw_parse_flags(state->flags, &raw_s->open_flags);
341 raw_s->fd = -1;
343 int fcntl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
344 #ifdef O_NOATIME
345 fcntl_flags |= O_NOATIME;
346 #endif
348 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
349 /* dup the original fd */
350 /* TODO: use qemu fcntl wrapper */
351 #ifdef F_DUPFD_CLOEXEC
352 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
353 #else
354 raw_s->fd = dup(s->fd);
355 if (raw_s->fd != -1) {
356 qemu_set_cloexec(raw_s->fd);
358 #endif
359 if (raw_s->fd >= 0) {
360 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
361 if (ret) {
362 qemu_close(raw_s->fd);
363 raw_s->fd = -1;
368 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
369 if (raw_s->fd == -1) {
370 assert(!(raw_s->open_flags & O_CREAT));
371 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
372 if (raw_s->fd == -1) {
373 ret = -1;
376 return ret;
380 static void raw_reopen_commit(BDRVReopenState *state)
382 BDRVRawReopenState *raw_s = state->opaque;
383 BDRVRawState *s = state->bs->opaque;
385 s->open_flags = raw_s->open_flags;
387 qemu_close(s->fd);
388 s->fd = raw_s->fd;
389 #ifdef CONFIG_LINUX_AIO
390 s->use_aio = raw_s->use_aio;
391 #endif
393 g_free(state->opaque);
394 state->opaque = NULL;
398 static void raw_reopen_abort(BDRVReopenState *state)
400 BDRVRawReopenState *raw_s = state->opaque;
402 /* nothing to do if NULL, we didn't get far enough */
403 if (raw_s == NULL) {
404 return;
407 if (raw_s->fd >= 0) {
408 qemu_close(raw_s->fd);
409 raw_s->fd = -1;
411 g_free(state->opaque);
412 state->opaque = NULL;
416 /* XXX: use host sector size if necessary with:
417 #ifdef DIOCGSECTORSIZE
419 unsigned int sectorsize = 512;
420 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
421 sectorsize > bufsize)
422 bufsize = sectorsize;
424 #endif
425 #ifdef CONFIG_COCOA
426 uint32_t blockSize = 512;
427 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
428 bufsize = blockSize;
430 #endif
434 * Check if all memory in this vector is sector aligned.
436 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
438 int i;
440 for (i = 0; i < qiov->niov; i++) {
441 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
442 return 0;
446 return 1;
449 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
451 int ret;
453 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
454 if (ret == -1) {
455 return -errno;
459 * This looks weird, but the aio code only considers a request
460 * successful if it has written the full number of bytes.
462 * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command,
463 * so in fact we return the ioctl command here to make posix_aio_read()
464 * happy..
466 return aiocb->aio_nbytes;
469 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
471 int ret;
473 ret = qemu_fdatasync(aiocb->aio_fildes);
474 if (ret == -1) {
475 return -errno;
477 return 0;
480 #ifdef CONFIG_PREADV
482 static bool preadv_present = true;
484 static ssize_t
485 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
487 return preadv(fd, iov, nr_iov, offset);
490 static ssize_t
491 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
493 return pwritev(fd, iov, nr_iov, offset);
496 #else
498 static bool preadv_present = false;
500 static ssize_t
501 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
503 return -ENOSYS;
506 static ssize_t
507 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
509 return -ENOSYS;
512 #endif
514 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
516 ssize_t len;
518 do {
519 if (aiocb->aio_type & QEMU_AIO_WRITE)
520 len = qemu_pwritev(aiocb->aio_fildes,
521 aiocb->aio_iov,
522 aiocb->aio_niov,
523 aiocb->aio_offset);
524 else
525 len = qemu_preadv(aiocb->aio_fildes,
526 aiocb->aio_iov,
527 aiocb->aio_niov,
528 aiocb->aio_offset);
529 } while (len == -1 && errno == EINTR);
531 if (len == -1) {
532 return -errno;
534 return len;
538 * Read/writes the data to/from a given linear buffer.
540 * Returns the number of bytes handles or -errno in case of an error. Short
541 * reads are only returned if the end of the file is reached.
543 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
545 ssize_t offset = 0;
546 ssize_t len;
548 while (offset < aiocb->aio_nbytes) {
549 if (aiocb->aio_type & QEMU_AIO_WRITE) {
550 len = pwrite(aiocb->aio_fildes,
551 (const char *)buf + offset,
552 aiocb->aio_nbytes - offset,
553 aiocb->aio_offset + offset);
554 } else {
555 len = pread(aiocb->aio_fildes,
556 buf + offset,
557 aiocb->aio_nbytes - offset,
558 aiocb->aio_offset + offset);
560 if (len == -1 && errno == EINTR) {
561 continue;
562 } else if (len == -1) {
563 offset = -errno;
564 break;
565 } else if (len == 0) {
566 break;
568 offset += len;
571 return offset;
574 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
576 ssize_t nbytes;
577 char *buf;
579 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
581 * If there is just a single buffer, and it is properly aligned
582 * we can just use plain pread/pwrite without any problems.
584 if (aiocb->aio_niov == 1) {
585 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
588 * We have more than one iovec, and all are properly aligned.
590 * Try preadv/pwritev first and fall back to linearizing the
591 * buffer if it's not supported.
593 if (preadv_present) {
594 nbytes = handle_aiocb_rw_vector(aiocb);
595 if (nbytes == aiocb->aio_nbytes ||
596 (nbytes < 0 && nbytes != -ENOSYS)) {
597 return nbytes;
599 preadv_present = false;
603 * XXX(hch): short read/write. no easy way to handle the reminder
604 * using these interfaces. For now retry using plain
605 * pread/pwrite?
610 * Ok, we have to do it the hard way, copy all segments into
611 * a single aligned buffer.
613 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
614 if (aiocb->aio_type & QEMU_AIO_WRITE) {
615 char *p = buf;
616 int i;
618 for (i = 0; i < aiocb->aio_niov; ++i) {
619 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
620 p += aiocb->aio_iov[i].iov_len;
624 nbytes = handle_aiocb_rw_linear(aiocb, buf);
625 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
626 char *p = buf;
627 size_t count = aiocb->aio_nbytes, copy;
628 int i;
630 for (i = 0; i < aiocb->aio_niov && count; ++i) {
631 copy = count;
632 if (copy > aiocb->aio_iov[i].iov_len) {
633 copy = aiocb->aio_iov[i].iov_len;
635 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
636 p += copy;
637 count -= copy;
640 qemu_vfree(buf);
642 return nbytes;
645 static int aio_worker(void *arg)
647 RawPosixAIOData *aiocb = arg;
648 ssize_t ret = 0;
650 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
651 case QEMU_AIO_READ:
652 ret = handle_aiocb_rw(aiocb);
653 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
654 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
655 0, aiocb->aio_nbytes - ret);
657 ret = aiocb->aio_nbytes;
659 if (ret == aiocb->aio_nbytes) {
660 ret = 0;
661 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
662 ret = -EINVAL;
664 break;
665 case QEMU_AIO_WRITE:
666 ret = handle_aiocb_rw(aiocb);
667 if (ret == aiocb->aio_nbytes) {
668 ret = 0;
669 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
670 ret = -EINVAL;
672 break;
673 case QEMU_AIO_FLUSH:
674 ret = handle_aiocb_flush(aiocb);
675 break;
676 case QEMU_AIO_IOCTL:
677 ret = handle_aiocb_ioctl(aiocb);
678 break;
679 default:
680 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
681 ret = -EINVAL;
682 break;
685 g_slice_free(RawPosixAIOData, aiocb);
686 return ret;
689 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
690 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
691 BlockDriverCompletionFunc *cb, void *opaque, int type)
693 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
695 acb->bs = bs;
696 acb->aio_type = type;
697 acb->aio_fildes = fd;
699 if (qiov) {
700 acb->aio_iov = qiov->iov;
701 acb->aio_niov = qiov->niov;
703 acb->aio_nbytes = nb_sectors * 512;
704 acb->aio_offset = sector_num * 512;
706 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
707 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
710 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
711 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
712 BlockDriverCompletionFunc *cb, void *opaque, int type)
714 BDRVRawState *s = bs->opaque;
716 if (fd_open(bs) < 0)
717 return NULL;
720 * If O_DIRECT is used the buffer needs to be aligned on a sector
721 * boundary. Check if this is the case or tell the low-level
722 * driver that it needs to copy the buffer.
724 if ((bs->open_flags & BDRV_O_NOCACHE)) {
725 if (!qiov_is_aligned(bs, qiov)) {
726 type |= QEMU_AIO_MISALIGNED;
727 #ifdef CONFIG_LINUX_AIO
728 } else if (s->use_aio) {
729 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
730 nb_sectors, cb, opaque, type);
731 #endif
735 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
736 cb, opaque, type);
739 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
740 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
741 BlockDriverCompletionFunc *cb, void *opaque)
743 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
744 cb, opaque, QEMU_AIO_READ);
747 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
748 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
749 BlockDriverCompletionFunc *cb, void *opaque)
751 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
752 cb, opaque, QEMU_AIO_WRITE);
755 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
756 BlockDriverCompletionFunc *cb, void *opaque)
758 BDRVRawState *s = bs->opaque;
760 if (fd_open(bs) < 0)
761 return NULL;
763 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
766 static void raw_close(BlockDriverState *bs)
768 BDRVRawState *s = bs->opaque;
769 if (s->fd >= 0) {
770 qemu_close(s->fd);
771 s->fd = -1;
775 static int raw_truncate(BlockDriverState *bs, int64_t offset)
777 BDRVRawState *s = bs->opaque;
778 struct stat st;
780 if (fstat(s->fd, &st)) {
781 return -errno;
784 if (S_ISREG(st.st_mode)) {
785 if (ftruncate(s->fd, offset) < 0) {
786 return -errno;
788 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
789 if (offset > raw_getlength(bs)) {
790 return -EINVAL;
792 } else {
793 return -ENOTSUP;
796 return 0;
799 #ifdef __OpenBSD__
800 static int64_t raw_getlength(BlockDriverState *bs)
802 BDRVRawState *s = bs->opaque;
803 int fd = s->fd;
804 struct stat st;
806 if (fstat(fd, &st))
807 return -1;
808 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
809 struct disklabel dl;
811 if (ioctl(fd, DIOCGDINFO, &dl))
812 return -1;
813 return (uint64_t)dl.d_secsize *
814 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
815 } else
816 return st.st_size;
818 #elif defined(__NetBSD__)
819 static int64_t raw_getlength(BlockDriverState *bs)
821 BDRVRawState *s = bs->opaque;
822 int fd = s->fd;
823 struct stat st;
825 if (fstat(fd, &st))
826 return -1;
827 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
828 struct dkwedge_info dkw;
830 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
831 return dkw.dkw_size * 512;
832 } else {
833 struct disklabel dl;
835 if (ioctl(fd, DIOCGDINFO, &dl))
836 return -1;
837 return (uint64_t)dl.d_secsize *
838 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
840 } else
841 return st.st_size;
843 #elif defined(__sun__)
844 static int64_t raw_getlength(BlockDriverState *bs)
846 BDRVRawState *s = bs->opaque;
847 struct dk_minfo minfo;
848 int ret;
850 ret = fd_open(bs);
851 if (ret < 0) {
852 return ret;
856 * Use the DKIOCGMEDIAINFO ioctl to read the size.
858 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
859 if (ret != -1) {
860 return minfo.dki_lbsize * minfo.dki_capacity;
864 * There are reports that lseek on some devices fails, but
865 * irc discussion said that contingency on contingency was overkill.
867 return lseek(s->fd, 0, SEEK_END);
869 #elif defined(CONFIG_BSD)
870 static int64_t raw_getlength(BlockDriverState *bs)
872 BDRVRawState *s = bs->opaque;
873 int fd = s->fd;
874 int64_t size;
875 struct stat sb;
876 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
877 int reopened = 0;
878 #endif
879 int ret;
881 ret = fd_open(bs);
882 if (ret < 0)
883 return ret;
885 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
886 again:
887 #endif
888 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
889 #ifdef DIOCGMEDIASIZE
890 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
891 #elif defined(DIOCGPART)
893 struct partinfo pi;
894 if (ioctl(fd, DIOCGPART, &pi) == 0)
895 size = pi.media_size;
896 else
897 size = 0;
899 if (size == 0)
900 #endif
901 #if defined(__APPLE__) && defined(__MACH__)
902 size = LONG_LONG_MAX;
903 #else
904 size = lseek(fd, 0LL, SEEK_END);
905 #endif
906 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
907 switch(s->type) {
908 case FTYPE_CD:
909 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
910 if (size == 2048LL * (unsigned)-1)
911 size = 0;
912 /* XXX no disc? maybe we need to reopen... */
913 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
914 reopened = 1;
915 goto again;
918 #endif
919 } else {
920 size = lseek(fd, 0, SEEK_END);
922 return size;
924 #else
925 static int64_t raw_getlength(BlockDriverState *bs)
927 BDRVRawState *s = bs->opaque;
928 int ret;
930 ret = fd_open(bs);
931 if (ret < 0) {
932 return ret;
935 return lseek(s->fd, 0, SEEK_END);
937 #endif
939 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
941 struct stat st;
942 BDRVRawState *s = bs->opaque;
944 if (fstat(s->fd, &st) < 0) {
945 return -errno;
947 return (int64_t)st.st_blocks * 512;
950 static int raw_create(const char *filename, QEMUOptionParameter *options)
952 int fd;
953 int result = 0;
954 int64_t total_size = 0;
956 /* Read out options */
957 while (options && options->name) {
958 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
959 total_size = options->value.n / BDRV_SECTOR_SIZE;
961 options++;
964 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
965 0644);
966 if (fd < 0) {
967 result = -errno;
968 } else {
969 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
970 result = -errno;
972 if (qemu_close(fd) != 0) {
973 result = -errno;
976 return result;
980 * Returns true iff the specified sector is present in the disk image. Drivers
981 * not implementing the functionality are assumed to not support backing files,
982 * hence all their sectors are reported as allocated.
984 * If 'sector_num' is beyond the end of the disk image the return value is 0
985 * and 'pnum' is set to 0.
987 * 'pnum' is set to the number of sectors (including and immediately following
988 * the specified sector) that are known to be in the same
989 * allocated/unallocated state.
991 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
992 * beyond the end of the disk image it will be clamped.
994 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
995 int64_t sector_num,
996 int nb_sectors, int *pnum)
998 off_t start, data, hole;
999 int ret;
1001 ret = fd_open(bs);
1002 if (ret < 0) {
1003 return ret;
1006 start = sector_num * BDRV_SECTOR_SIZE;
1008 #ifdef CONFIG_FIEMAP
1010 BDRVRawState *s = bs->opaque;
1011 struct {
1012 struct fiemap fm;
1013 struct fiemap_extent fe;
1014 } f;
1016 f.fm.fm_start = start;
1017 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1018 f.fm.fm_flags = 0;
1019 f.fm.fm_extent_count = 1;
1020 f.fm.fm_reserved = 0;
1021 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1022 /* Assume everything is allocated. */
1023 *pnum = nb_sectors;
1024 return 1;
1027 if (f.fm.fm_mapped_extents == 0) {
1028 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1029 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1031 off_t length = lseek(s->fd, 0, SEEK_END);
1032 hole = f.fm.fm_start;
1033 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1034 } else {
1035 data = f.fe.fe_logical;
1036 hole = f.fe.fe_logical + f.fe.fe_length;
1039 #elif defined SEEK_HOLE && defined SEEK_DATA
1041 BDRVRawState *s = bs->opaque;
1043 hole = lseek(s->fd, start, SEEK_HOLE);
1044 if (hole == -1) {
1045 /* -ENXIO indicates that sector_num was past the end of the file.
1046 * There is a virtual hole there. */
1047 assert(errno != -ENXIO);
1049 /* Most likely EINVAL. Assume everything is allocated. */
1050 *pnum = nb_sectors;
1051 return 1;
1054 if (hole > start) {
1055 data = start;
1056 } else {
1057 /* On a hole. We need another syscall to find its end. */
1058 data = lseek(s->fd, start, SEEK_DATA);
1059 if (data == -1) {
1060 data = lseek(s->fd, 0, SEEK_END);
1063 #else
1064 *pnum = nb_sectors;
1065 return 1;
1066 #endif
1068 if (data <= start) {
1069 /* On a data extent, compute sectors to the end of the extent. */
1070 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1071 return 1;
1072 } else {
1073 /* On a hole, compute sectors to the beginning of the next extent. */
1074 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1075 return 0;
1079 #ifdef CONFIG_XFS
1080 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
1082 struct xfs_flock64 fl;
1084 memset(&fl, 0, sizeof(fl));
1085 fl.l_whence = SEEK_SET;
1086 fl.l_start = sector_num << 9;
1087 fl.l_len = (int64_t)nb_sectors << 9;
1089 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1090 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
1091 return -errno;
1094 return 0;
1096 #endif
1098 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
1099 int64_t sector_num, int nb_sectors)
1101 #ifdef CONFIG_XFS
1102 BDRVRawState *s = bs->opaque;
1104 if (s->is_xfs) {
1105 return xfs_discard(s, sector_num, nb_sectors);
1107 #endif
1109 return 0;
1112 static QEMUOptionParameter raw_create_options[] = {
1114 .name = BLOCK_OPT_SIZE,
1115 .type = OPT_SIZE,
1116 .help = "Virtual disk size"
1118 { NULL }
1121 static BlockDriver bdrv_file = {
1122 .format_name = "file",
1123 .protocol_name = "file",
1124 .instance_size = sizeof(BDRVRawState),
1125 .bdrv_probe = NULL, /* no probe for protocols */
1126 .bdrv_file_open = raw_open,
1127 .bdrv_reopen_prepare = raw_reopen_prepare,
1128 .bdrv_reopen_commit = raw_reopen_commit,
1129 .bdrv_reopen_abort = raw_reopen_abort,
1130 .bdrv_close = raw_close,
1131 .bdrv_create = raw_create,
1132 .bdrv_co_discard = raw_co_discard,
1133 .bdrv_co_is_allocated = raw_co_is_allocated,
1135 .bdrv_aio_readv = raw_aio_readv,
1136 .bdrv_aio_writev = raw_aio_writev,
1137 .bdrv_aio_flush = raw_aio_flush,
1139 .bdrv_truncate = raw_truncate,
1140 .bdrv_getlength = raw_getlength,
1141 .bdrv_get_allocated_file_size
1142 = raw_get_allocated_file_size,
1144 .create_options = raw_create_options,
1147 /***********************************************/
1148 /* host device */
1150 #if defined(__APPLE__) && defined(__MACH__)
1151 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1152 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1154 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1156 kern_return_t kernResult;
1157 mach_port_t masterPort;
1158 CFMutableDictionaryRef classesToMatch;
1160 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1161 if ( KERN_SUCCESS != kernResult ) {
1162 printf( "IOMasterPort returned %d\n", kernResult );
1165 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1166 if ( classesToMatch == NULL ) {
1167 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1168 } else {
1169 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1171 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1172 if ( KERN_SUCCESS != kernResult )
1174 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1177 return kernResult;
1180 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1182 io_object_t nextMedia;
1183 kern_return_t kernResult = KERN_FAILURE;
1184 *bsdPath = '\0';
1185 nextMedia = IOIteratorNext( mediaIterator );
1186 if ( nextMedia )
1188 CFTypeRef bsdPathAsCFString;
1189 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1190 if ( bsdPathAsCFString ) {
1191 size_t devPathLength;
1192 strcpy( bsdPath, _PATH_DEV );
1193 strcat( bsdPath, "r" );
1194 devPathLength = strlen( bsdPath );
1195 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1196 kernResult = KERN_SUCCESS;
1198 CFRelease( bsdPathAsCFString );
1200 IOObjectRelease( nextMedia );
1203 return kernResult;
1206 #endif
1208 static int hdev_probe_device(const char *filename)
1210 struct stat st;
1212 /* allow a dedicated CD-ROM driver to match with a higher priority */
1213 if (strstart(filename, "/dev/cdrom", NULL))
1214 return 50;
1216 if (stat(filename, &st) >= 0 &&
1217 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1218 return 100;
1221 return 0;
1224 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1226 BDRVRawState *s = bs->opaque;
1228 #if defined(__APPLE__) && defined(__MACH__)
1229 if (strstart(filename, "/dev/cdrom", NULL)) {
1230 kern_return_t kernResult;
1231 io_iterator_t mediaIterator;
1232 char bsdPath[ MAXPATHLEN ];
1233 int fd;
1235 kernResult = FindEjectableCDMedia( &mediaIterator );
1236 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1238 if ( bsdPath[ 0 ] != '\0' ) {
1239 strcat(bsdPath,"s0");
1240 /* some CDs don't have a partition 0 */
1241 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1242 if (fd < 0) {
1243 bsdPath[strlen(bsdPath)-1] = '1';
1244 } else {
1245 qemu_close(fd);
1247 filename = bsdPath;
1250 if ( mediaIterator )
1251 IOObjectRelease( mediaIterator );
1253 #endif
1255 s->type = FTYPE_FILE;
1256 #if defined(__linux__)
1258 char resolved_path[ MAXPATHLEN ], *temp;
1260 temp = realpath(filename, resolved_path);
1261 if (temp && strstart(temp, "/dev/sg", NULL)) {
1262 bs->sg = 1;
1265 #endif
1267 return raw_open_common(bs, filename, flags, 0);
1270 #if defined(__linux__)
1271 /* Note: we do not have a reliable method to detect if the floppy is
1272 present. The current method is to try to open the floppy at every
1273 I/O and to keep it opened during a few hundreds of ms. */
1274 static int fd_open(BlockDriverState *bs)
1276 BDRVRawState *s = bs->opaque;
1277 int last_media_present;
1279 if (s->type != FTYPE_FD)
1280 return 0;
1281 last_media_present = (s->fd >= 0);
1282 if (s->fd >= 0 &&
1283 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1284 qemu_close(s->fd);
1285 s->fd = -1;
1286 #ifdef DEBUG_FLOPPY
1287 printf("Floppy closed\n");
1288 #endif
1290 if (s->fd < 0) {
1291 if (s->fd_got_error &&
1292 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1293 #ifdef DEBUG_FLOPPY
1294 printf("No floppy (open delayed)\n");
1295 #endif
1296 return -EIO;
1298 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1299 if (s->fd < 0) {
1300 s->fd_error_time = get_clock();
1301 s->fd_got_error = 1;
1302 if (last_media_present)
1303 s->fd_media_changed = 1;
1304 #ifdef DEBUG_FLOPPY
1305 printf("No floppy\n");
1306 #endif
1307 return -EIO;
1309 #ifdef DEBUG_FLOPPY
1310 printf("Floppy opened\n");
1311 #endif
1313 if (!last_media_present)
1314 s->fd_media_changed = 1;
1315 s->fd_open_time = get_clock();
1316 s->fd_got_error = 0;
1317 return 0;
1320 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1322 BDRVRawState *s = bs->opaque;
1324 return ioctl(s->fd, req, buf);
1327 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1328 unsigned long int req, void *buf,
1329 BlockDriverCompletionFunc *cb, void *opaque)
1331 BDRVRawState *s = bs->opaque;
1332 RawPosixAIOData *acb;
1334 if (fd_open(bs) < 0)
1335 return NULL;
1337 acb = g_slice_new(RawPosixAIOData);
1338 acb->bs = bs;
1339 acb->aio_type = QEMU_AIO_IOCTL;
1340 acb->aio_fildes = s->fd;
1341 acb->aio_offset = 0;
1342 acb->aio_ioctl_buf = buf;
1343 acb->aio_ioctl_cmd = req;
1344 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
1347 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1348 static int fd_open(BlockDriverState *bs)
1350 BDRVRawState *s = bs->opaque;
1352 /* this is just to ensure s->fd is sane (its called by io ops) */
1353 if (s->fd >= 0)
1354 return 0;
1355 return -EIO;
1357 #else /* !linux && !FreeBSD */
1359 static int fd_open(BlockDriverState *bs)
1361 return 0;
1364 #endif /* !linux && !FreeBSD */
1366 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1368 int fd;
1369 int ret = 0;
1370 struct stat stat_buf;
1371 int64_t total_size = 0;
1373 /* Read out options */
1374 while (options && options->name) {
1375 if (!strcmp(options->name, "size")) {
1376 total_size = options->value.n / BDRV_SECTOR_SIZE;
1378 options++;
1381 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1382 if (fd < 0)
1383 return -errno;
1385 if (fstat(fd, &stat_buf) < 0)
1386 ret = -errno;
1387 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1388 ret = -ENODEV;
1389 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1390 ret = -ENOSPC;
1392 qemu_close(fd);
1393 return ret;
1396 static int hdev_has_zero_init(BlockDriverState *bs)
1398 return 0;
1401 static BlockDriver bdrv_host_device = {
1402 .format_name = "host_device",
1403 .protocol_name = "host_device",
1404 .instance_size = sizeof(BDRVRawState),
1405 .bdrv_probe_device = hdev_probe_device,
1406 .bdrv_file_open = hdev_open,
1407 .bdrv_close = raw_close,
1408 .bdrv_reopen_prepare = raw_reopen_prepare,
1409 .bdrv_reopen_commit = raw_reopen_commit,
1410 .bdrv_reopen_abort = raw_reopen_abort,
1411 .bdrv_create = hdev_create,
1412 .create_options = raw_create_options,
1413 .bdrv_has_zero_init = hdev_has_zero_init,
1415 .bdrv_aio_readv = raw_aio_readv,
1416 .bdrv_aio_writev = raw_aio_writev,
1417 .bdrv_aio_flush = raw_aio_flush,
1419 .bdrv_truncate = raw_truncate,
1420 .bdrv_getlength = raw_getlength,
1421 .bdrv_get_allocated_file_size
1422 = raw_get_allocated_file_size,
1424 /* generic scsi device */
1425 #ifdef __linux__
1426 .bdrv_ioctl = hdev_ioctl,
1427 .bdrv_aio_ioctl = hdev_aio_ioctl,
1428 #endif
1431 #ifdef __linux__
1432 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1434 BDRVRawState *s = bs->opaque;
1435 int ret;
1437 s->type = FTYPE_FD;
1439 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1440 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1441 if (ret)
1442 return ret;
1444 /* close fd so that we can reopen it as needed */
1445 qemu_close(s->fd);
1446 s->fd = -1;
1447 s->fd_media_changed = 1;
1449 return 0;
1452 static int floppy_probe_device(const char *filename)
1454 int fd, ret;
1455 int prio = 0;
1456 struct floppy_struct fdparam;
1457 struct stat st;
1459 if (strstart(filename, "/dev/fd", NULL) &&
1460 !strstart(filename, "/dev/fdset/", NULL)) {
1461 prio = 50;
1464 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1465 if (fd < 0) {
1466 goto out;
1468 ret = fstat(fd, &st);
1469 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1470 goto outc;
1473 /* Attempt to detect via a floppy specific ioctl */
1474 ret = ioctl(fd, FDGETPRM, &fdparam);
1475 if (ret >= 0)
1476 prio = 100;
1478 outc:
1479 qemu_close(fd);
1480 out:
1481 return prio;
1485 static int floppy_is_inserted(BlockDriverState *bs)
1487 return fd_open(bs) >= 0;
1490 static int floppy_media_changed(BlockDriverState *bs)
1492 BDRVRawState *s = bs->opaque;
1493 int ret;
1496 * XXX: we do not have a true media changed indication.
1497 * It does not work if the floppy is changed without trying to read it.
1499 fd_open(bs);
1500 ret = s->fd_media_changed;
1501 s->fd_media_changed = 0;
1502 #ifdef DEBUG_FLOPPY
1503 printf("Floppy changed=%d\n", ret);
1504 #endif
1505 return ret;
1508 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1510 BDRVRawState *s = bs->opaque;
1511 int fd;
1513 if (s->fd >= 0) {
1514 qemu_close(s->fd);
1515 s->fd = -1;
1517 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1518 if (fd >= 0) {
1519 if (ioctl(fd, FDEJECT, 0) < 0)
1520 perror("FDEJECT");
1521 qemu_close(fd);
1525 static BlockDriver bdrv_host_floppy = {
1526 .format_name = "host_floppy",
1527 .protocol_name = "host_floppy",
1528 .instance_size = sizeof(BDRVRawState),
1529 .bdrv_probe_device = floppy_probe_device,
1530 .bdrv_file_open = floppy_open,
1531 .bdrv_close = raw_close,
1532 .bdrv_reopen_prepare = raw_reopen_prepare,
1533 .bdrv_reopen_commit = raw_reopen_commit,
1534 .bdrv_reopen_abort = raw_reopen_abort,
1535 .bdrv_create = hdev_create,
1536 .create_options = raw_create_options,
1537 .bdrv_has_zero_init = hdev_has_zero_init,
1539 .bdrv_aio_readv = raw_aio_readv,
1540 .bdrv_aio_writev = raw_aio_writev,
1541 .bdrv_aio_flush = raw_aio_flush,
1543 .bdrv_truncate = raw_truncate,
1544 .bdrv_getlength = raw_getlength,
1545 .bdrv_get_allocated_file_size
1546 = raw_get_allocated_file_size,
1548 /* removable device support */
1549 .bdrv_is_inserted = floppy_is_inserted,
1550 .bdrv_media_changed = floppy_media_changed,
1551 .bdrv_eject = floppy_eject,
1554 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1556 BDRVRawState *s = bs->opaque;
1558 s->type = FTYPE_CD;
1560 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1561 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1564 static int cdrom_probe_device(const char *filename)
1566 int fd, ret;
1567 int prio = 0;
1568 struct stat st;
1570 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1571 if (fd < 0) {
1572 goto out;
1574 ret = fstat(fd, &st);
1575 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1576 goto outc;
1579 /* Attempt to detect via a CDROM specific ioctl */
1580 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1581 if (ret >= 0)
1582 prio = 100;
1584 outc:
1585 qemu_close(fd);
1586 out:
1587 return prio;
1590 static int cdrom_is_inserted(BlockDriverState *bs)
1592 BDRVRawState *s = bs->opaque;
1593 int ret;
1595 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1596 if (ret == CDS_DISC_OK)
1597 return 1;
1598 return 0;
1601 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1603 BDRVRawState *s = bs->opaque;
1605 if (eject_flag) {
1606 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1607 perror("CDROMEJECT");
1608 } else {
1609 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1610 perror("CDROMEJECT");
1614 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1616 BDRVRawState *s = bs->opaque;
1618 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1620 * Note: an error can happen if the distribution automatically
1621 * mounts the CD-ROM
1623 /* perror("CDROM_LOCKDOOR"); */
1627 static BlockDriver bdrv_host_cdrom = {
1628 .format_name = "host_cdrom",
1629 .protocol_name = "host_cdrom",
1630 .instance_size = sizeof(BDRVRawState),
1631 .bdrv_probe_device = cdrom_probe_device,
1632 .bdrv_file_open = cdrom_open,
1633 .bdrv_close = raw_close,
1634 .bdrv_reopen_prepare = raw_reopen_prepare,
1635 .bdrv_reopen_commit = raw_reopen_commit,
1636 .bdrv_reopen_abort = raw_reopen_abort,
1637 .bdrv_create = hdev_create,
1638 .create_options = raw_create_options,
1639 .bdrv_has_zero_init = hdev_has_zero_init,
1641 .bdrv_aio_readv = raw_aio_readv,
1642 .bdrv_aio_writev = raw_aio_writev,
1643 .bdrv_aio_flush = raw_aio_flush,
1645 .bdrv_truncate = raw_truncate,
1646 .bdrv_getlength = raw_getlength,
1647 .bdrv_get_allocated_file_size
1648 = raw_get_allocated_file_size,
1650 /* removable device support */
1651 .bdrv_is_inserted = cdrom_is_inserted,
1652 .bdrv_eject = cdrom_eject,
1653 .bdrv_lock_medium = cdrom_lock_medium,
1655 /* generic scsi device */
1656 .bdrv_ioctl = hdev_ioctl,
1657 .bdrv_aio_ioctl = hdev_aio_ioctl,
1659 #endif /* __linux__ */
1661 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1662 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1664 BDRVRawState *s = bs->opaque;
1665 int ret;
1667 s->type = FTYPE_CD;
1669 ret = raw_open_common(bs, filename, flags, 0);
1670 if (ret)
1671 return ret;
1673 /* make sure the door isn't locked at this time */
1674 ioctl(s->fd, CDIOCALLOW);
1675 return 0;
1678 static int cdrom_probe_device(const char *filename)
1680 if (strstart(filename, "/dev/cd", NULL) ||
1681 strstart(filename, "/dev/acd", NULL))
1682 return 100;
1683 return 0;
1686 static int cdrom_reopen(BlockDriverState *bs)
1688 BDRVRawState *s = bs->opaque;
1689 int fd;
1692 * Force reread of possibly changed/newly loaded disc,
1693 * FreeBSD seems to not notice sometimes...
1695 if (s->fd >= 0)
1696 qemu_close(s->fd);
1697 fd = qemu_open(bs->filename, s->open_flags, 0644);
1698 if (fd < 0) {
1699 s->fd = -1;
1700 return -EIO;
1702 s->fd = fd;
1704 /* make sure the door isn't locked at this time */
1705 ioctl(s->fd, CDIOCALLOW);
1706 return 0;
1709 static int cdrom_is_inserted(BlockDriverState *bs)
1711 return raw_getlength(bs) > 0;
1714 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1716 BDRVRawState *s = bs->opaque;
1718 if (s->fd < 0)
1719 return;
1721 (void) ioctl(s->fd, CDIOCALLOW);
1723 if (eject_flag) {
1724 if (ioctl(s->fd, CDIOCEJECT) < 0)
1725 perror("CDIOCEJECT");
1726 } else {
1727 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1728 perror("CDIOCCLOSE");
1731 cdrom_reopen(bs);
1734 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1736 BDRVRawState *s = bs->opaque;
1738 if (s->fd < 0)
1739 return;
1740 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1742 * Note: an error can happen if the distribution automatically
1743 * mounts the CD-ROM
1745 /* perror("CDROM_LOCKDOOR"); */
1749 static BlockDriver bdrv_host_cdrom = {
1750 .format_name = "host_cdrom",
1751 .protocol_name = "host_cdrom",
1752 .instance_size = sizeof(BDRVRawState),
1753 .bdrv_probe_device = cdrom_probe_device,
1754 .bdrv_file_open = cdrom_open,
1755 .bdrv_close = raw_close,
1756 .bdrv_reopen_prepare = raw_reopen_prepare,
1757 .bdrv_reopen_commit = raw_reopen_commit,
1758 .bdrv_reopen_abort = raw_reopen_abort,
1759 .bdrv_create = hdev_create,
1760 .create_options = raw_create_options,
1761 .bdrv_has_zero_init = hdev_has_zero_init,
1763 .bdrv_aio_readv = raw_aio_readv,
1764 .bdrv_aio_writev = raw_aio_writev,
1765 .bdrv_aio_flush = raw_aio_flush,
1767 .bdrv_truncate = raw_truncate,
1768 .bdrv_getlength = raw_getlength,
1769 .bdrv_get_allocated_file_size
1770 = raw_get_allocated_file_size,
1772 /* removable device support */
1773 .bdrv_is_inserted = cdrom_is_inserted,
1774 .bdrv_eject = cdrom_eject,
1775 .bdrv_lock_medium = cdrom_lock_medium,
1777 #endif /* __FreeBSD__ */
1779 #ifdef CONFIG_LINUX_AIO
1781 * Return the file descriptor for Linux AIO
1783 * This function is a layering violation and should be removed when it becomes
1784 * possible to call the block layer outside the global mutex. It allows the
1785 * caller to hijack the file descriptor so I/O can be performed outside the
1786 * block layer.
1788 int raw_get_aio_fd(BlockDriverState *bs)
1790 BDRVRawState *s;
1792 if (!bs->drv) {
1793 return -ENOMEDIUM;
1796 if (bs->drv == bdrv_find_format("raw")) {
1797 bs = bs->file;
1800 /* raw-posix has several protocols so just check for raw_aio_readv */
1801 if (bs->drv->bdrv_aio_readv != raw_aio_readv) {
1802 return -ENOTSUP;
1805 s = bs->opaque;
1806 if (!s->use_aio) {
1807 return -ENOTSUP;
1809 return s->fd;
1811 #endif /* CONFIG_LINUX_AIO */
1813 static void bdrv_file_init(void)
1816 * Register all the drivers. Note that order is important, the driver
1817 * registered last will get probed first.
1819 bdrv_register(&bdrv_file);
1820 bdrv_register(&bdrv_host_device);
1821 #ifdef __linux__
1822 bdrv_register(&bdrv_host_floppy);
1823 bdrv_register(&bdrv_host_cdrom);
1824 #endif
1825 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1826 bdrv_register(&bdrv_host_cdrom);
1827 #endif
1830 block_init(bdrv_file_init);