block: switch posix-aio-compat to threadpool
[qemu/ar7.git] / block / raw-posix.c
blob9ae2c505a8a85fae70988753c0c2510a6eda8109
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-char.h"
27 #include "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "block/raw-posix-aio.h"
32 #if defined(__APPLE__) && (__MACH__)
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <sys/dkio.h>
47 #endif
48 #ifdef __linux__
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <linux/cdrom.h>
54 #include <linux/fd.h>
55 #include <linux/fs.h>
56 #endif
57 #ifdef CONFIG_FIEMAP
58 #include <linux/fiemap.h>
59 #endif
60 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
61 #include <sys/disk.h>
62 #include <sys/cdio.h>
63 #endif
65 #ifdef __OpenBSD__
66 #include <sys/ioctl.h>
67 #include <sys/disklabel.h>
68 #include <sys/dkio.h>
69 #endif
71 #ifdef __NetBSD__
72 #include <sys/ioctl.h>
73 #include <sys/disklabel.h>
74 #include <sys/dkio.h>
75 #include <sys/disk.h>
76 #endif
78 #ifdef __DragonFly__
79 #include <sys/ioctl.h>
80 #include <sys/diskslice.h>
81 #endif
83 #ifdef CONFIG_XFS
84 #include <xfs/xfs.h>
85 #endif
87 //#define DEBUG_FLOPPY
89 //#define DEBUG_BLOCK
90 #if defined(DEBUG_BLOCK)
91 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
92 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
93 #else
94 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
95 #endif
97 /* OS X does not have O_DSYNC */
98 #ifndef O_DSYNC
99 #ifdef O_SYNC
100 #define O_DSYNC O_SYNC
101 #elif defined(O_FSYNC)
102 #define O_DSYNC O_FSYNC
103 #endif
104 #endif
106 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
107 #ifndef O_DIRECT
108 #define O_DIRECT O_DSYNC
109 #endif
111 #define FTYPE_FILE 0
112 #define FTYPE_CD 1
113 #define FTYPE_FD 2
115 /* if the FD is not accessed during that time (in ns), we try to
116 reopen it to see if the disk has been changed */
117 #define FD_OPEN_TIMEOUT (1000000000)
119 #define MAX_BLOCKSIZE 4096
121 typedef struct BDRVRawState {
122 int fd;
123 int type;
124 int open_flags;
125 #if defined(__linux__)
126 /* linux floppy specific */
127 int64_t fd_open_time;
128 int64_t fd_error_time;
129 int fd_got_error;
130 int fd_media_changed;
131 #endif
132 #ifdef CONFIG_LINUX_AIO
133 int use_aio;
134 void *aio_ctx;
135 #endif
136 #ifdef CONFIG_XFS
137 bool is_xfs : 1;
138 #endif
139 } BDRVRawState;
141 typedef struct BDRVRawReopenState {
142 int fd;
143 int open_flags;
144 #ifdef CONFIG_LINUX_AIO
145 int use_aio;
146 #endif
147 } BDRVRawReopenState;
149 static int fd_open(BlockDriverState *bs);
150 static int64_t raw_getlength(BlockDriverState *bs);
152 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
153 static int cdrom_reopen(BlockDriverState *bs);
154 #endif
156 #if defined(__NetBSD__)
157 static int raw_normalize_devicepath(const char **filename)
159 static char namebuf[PATH_MAX];
160 const char *dp, *fname;
161 struct stat sb;
163 fname = *filename;
164 dp = strrchr(fname, '/');
165 if (lstat(fname, &sb) < 0) {
166 fprintf(stderr, "%s: stat failed: %s\n",
167 fname, strerror(errno));
168 return -errno;
171 if (!S_ISBLK(sb.st_mode)) {
172 return 0;
175 if (dp == NULL) {
176 snprintf(namebuf, PATH_MAX, "r%s", fname);
177 } else {
178 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
179 (int)(dp - fname), fname, dp + 1);
181 fprintf(stderr, "%s is a block device", fname);
182 *filename = namebuf;
183 fprintf(stderr, ", using %s\n", *filename);
185 return 0;
187 #else
188 static int raw_normalize_devicepath(const char **filename)
190 return 0;
192 #endif
194 static void raw_parse_flags(int bdrv_flags, int *open_flags)
196 assert(open_flags != NULL);
198 *open_flags |= O_BINARY;
199 *open_flags &= ~O_ACCMODE;
200 if (bdrv_flags & BDRV_O_RDWR) {
201 *open_flags |= O_RDWR;
202 } else {
203 *open_flags |= O_RDONLY;
206 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
207 * and O_DIRECT for no caching. */
208 if ((bdrv_flags & BDRV_O_NOCACHE)) {
209 *open_flags |= O_DIRECT;
213 #ifdef CONFIG_LINUX_AIO
214 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
216 int ret = -1;
217 assert(aio_ctx != NULL);
218 assert(use_aio != NULL);
220 * Currently Linux do AIO only for files opened with O_DIRECT
221 * specified so check NOCACHE flag too
223 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
224 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
226 /* if non-NULL, laio_init() has already been run */
227 if (*aio_ctx == NULL) {
228 *aio_ctx = laio_init();
229 if (!*aio_ctx) {
230 goto error;
233 *use_aio = 1;
234 } else {
235 *use_aio = 0;
238 ret = 0;
240 error:
241 return ret;
243 #endif
245 static int raw_open_common(BlockDriverState *bs, const char *filename,
246 int bdrv_flags, int open_flags)
248 BDRVRawState *s = bs->opaque;
249 int fd, ret;
251 ret = raw_normalize_devicepath(&filename);
252 if (ret != 0) {
253 return ret;
256 s->open_flags = open_flags;
257 raw_parse_flags(bdrv_flags, &s->open_flags);
259 s->fd = -1;
260 fd = qemu_open(filename, s->open_flags, 0644);
261 if (fd < 0) {
262 ret = -errno;
263 if (ret == -EROFS)
264 ret = -EACCES;
265 return ret;
267 s->fd = fd;
269 #ifdef CONFIG_LINUX_AIO
270 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
271 qemu_close(fd);
272 return -errno;
274 #endif
276 #ifdef CONFIG_XFS
277 if (platform_test_xfs_fd(s->fd)) {
278 s->is_xfs = 1;
280 #endif
282 return 0;
285 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
287 BDRVRawState *s = bs->opaque;
289 s->type = FTYPE_FILE;
290 return raw_open_common(bs, filename, flags, 0);
293 static int raw_reopen_prepare(BDRVReopenState *state,
294 BlockReopenQueue *queue, Error **errp)
296 BDRVRawState *s;
297 BDRVRawReopenState *raw_s;
298 int ret = 0;
300 assert(state != NULL);
301 assert(state->bs != NULL);
303 s = state->bs->opaque;
305 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
306 raw_s = state->opaque;
308 #ifdef CONFIG_LINUX_AIO
309 raw_s->use_aio = s->use_aio;
311 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
312 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
313 * won't override aio_ctx if aio_ctx is non-NULL */
314 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
315 return -1;
317 #endif
319 raw_parse_flags(state->flags, &raw_s->open_flags);
321 raw_s->fd = -1;
323 int fcntl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
324 #ifdef O_NOATIME
325 fcntl_flags |= O_NOATIME;
326 #endif
328 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
329 /* dup the original fd */
330 /* TODO: use qemu fcntl wrapper */
331 #ifdef F_DUPFD_CLOEXEC
332 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
333 #else
334 raw_s->fd = dup(s->fd);
335 if (raw_s->fd != -1) {
336 qemu_set_cloexec(raw_s->fd);
338 #endif
339 if (raw_s->fd >= 0) {
340 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
341 if (ret) {
342 qemu_close(raw_s->fd);
343 raw_s->fd = -1;
348 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
349 if (raw_s->fd == -1) {
350 assert(!(raw_s->open_flags & O_CREAT));
351 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
352 if (raw_s->fd == -1) {
353 ret = -1;
356 return ret;
360 static void raw_reopen_commit(BDRVReopenState *state)
362 BDRVRawReopenState *raw_s = state->opaque;
363 BDRVRawState *s = state->bs->opaque;
365 s->open_flags = raw_s->open_flags;
367 qemu_close(s->fd);
368 s->fd = raw_s->fd;
369 #ifdef CONFIG_LINUX_AIO
370 s->use_aio = raw_s->use_aio;
371 #endif
373 g_free(state->opaque);
374 state->opaque = NULL;
378 static void raw_reopen_abort(BDRVReopenState *state)
380 BDRVRawReopenState *raw_s = state->opaque;
382 /* nothing to do if NULL, we didn't get far enough */
383 if (raw_s == NULL) {
384 return;
387 if (raw_s->fd >= 0) {
388 qemu_close(raw_s->fd);
389 raw_s->fd = -1;
391 g_free(state->opaque);
392 state->opaque = NULL;
396 /* XXX: use host sector size if necessary with:
397 #ifdef DIOCGSECTORSIZE
399 unsigned int sectorsize = 512;
400 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
401 sectorsize > bufsize)
402 bufsize = sectorsize;
404 #endif
405 #ifdef CONFIG_COCOA
406 uint32_t blockSize = 512;
407 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
408 bufsize = blockSize;
410 #endif
414 * Check if all memory in this vector is sector aligned.
416 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
418 int i;
420 for (i = 0; i < qiov->niov; i++) {
421 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
422 return 0;
426 return 1;
429 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
430 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
431 BlockDriverCompletionFunc *cb, void *opaque, int type)
433 BDRVRawState *s = bs->opaque;
435 if (fd_open(bs) < 0)
436 return NULL;
439 * If O_DIRECT is used the buffer needs to be aligned on a sector
440 * boundary. Check if this is the case or tell the low-level
441 * driver that it needs to copy the buffer.
443 if ((bs->open_flags & BDRV_O_NOCACHE)) {
444 if (!qiov_is_aligned(bs, qiov)) {
445 type |= QEMU_AIO_MISALIGNED;
446 #ifdef CONFIG_LINUX_AIO
447 } else if (s->use_aio) {
448 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
449 nb_sectors, cb, opaque, type);
450 #endif
454 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
455 cb, opaque, type);
458 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
459 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
460 BlockDriverCompletionFunc *cb, void *opaque)
462 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
463 cb, opaque, QEMU_AIO_READ);
466 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
467 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
468 BlockDriverCompletionFunc *cb, void *opaque)
470 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
471 cb, opaque, QEMU_AIO_WRITE);
474 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
475 BlockDriverCompletionFunc *cb, void *opaque)
477 BDRVRawState *s = bs->opaque;
479 if (fd_open(bs) < 0)
480 return NULL;
482 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
485 static void raw_close(BlockDriverState *bs)
487 BDRVRawState *s = bs->opaque;
488 if (s->fd >= 0) {
489 qemu_close(s->fd);
490 s->fd = -1;
494 static int raw_truncate(BlockDriverState *bs, int64_t offset)
496 BDRVRawState *s = bs->opaque;
497 struct stat st;
499 if (fstat(s->fd, &st)) {
500 return -errno;
503 if (S_ISREG(st.st_mode)) {
504 if (ftruncate(s->fd, offset) < 0) {
505 return -errno;
507 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
508 if (offset > raw_getlength(bs)) {
509 return -EINVAL;
511 } else {
512 return -ENOTSUP;
515 return 0;
518 #ifdef __OpenBSD__
519 static int64_t raw_getlength(BlockDriverState *bs)
521 BDRVRawState *s = bs->opaque;
522 int fd = s->fd;
523 struct stat st;
525 if (fstat(fd, &st))
526 return -1;
527 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
528 struct disklabel dl;
530 if (ioctl(fd, DIOCGDINFO, &dl))
531 return -1;
532 return (uint64_t)dl.d_secsize *
533 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
534 } else
535 return st.st_size;
537 #elif defined(__NetBSD__)
538 static int64_t raw_getlength(BlockDriverState *bs)
540 BDRVRawState *s = bs->opaque;
541 int fd = s->fd;
542 struct stat st;
544 if (fstat(fd, &st))
545 return -1;
546 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
547 struct dkwedge_info dkw;
549 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
550 return dkw.dkw_size * 512;
551 } else {
552 struct disklabel dl;
554 if (ioctl(fd, DIOCGDINFO, &dl))
555 return -1;
556 return (uint64_t)dl.d_secsize *
557 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
559 } else
560 return st.st_size;
562 #elif defined(__sun__)
563 static int64_t raw_getlength(BlockDriverState *bs)
565 BDRVRawState *s = bs->opaque;
566 struct dk_minfo minfo;
567 int ret;
569 ret = fd_open(bs);
570 if (ret < 0) {
571 return ret;
575 * Use the DKIOCGMEDIAINFO ioctl to read the size.
577 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
578 if (ret != -1) {
579 return minfo.dki_lbsize * minfo.dki_capacity;
583 * There are reports that lseek on some devices fails, but
584 * irc discussion said that contingency on contingency was overkill.
586 return lseek(s->fd, 0, SEEK_END);
588 #elif defined(CONFIG_BSD)
589 static int64_t raw_getlength(BlockDriverState *bs)
591 BDRVRawState *s = bs->opaque;
592 int fd = s->fd;
593 int64_t size;
594 struct stat sb;
595 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
596 int reopened = 0;
597 #endif
598 int ret;
600 ret = fd_open(bs);
601 if (ret < 0)
602 return ret;
604 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
605 again:
606 #endif
607 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
608 #ifdef DIOCGMEDIASIZE
609 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
610 #elif defined(DIOCGPART)
612 struct partinfo pi;
613 if (ioctl(fd, DIOCGPART, &pi) == 0)
614 size = pi.media_size;
615 else
616 size = 0;
618 if (size == 0)
619 #endif
620 #if defined(__APPLE__) && defined(__MACH__)
621 size = LONG_LONG_MAX;
622 #else
623 size = lseek(fd, 0LL, SEEK_END);
624 #endif
625 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
626 switch(s->type) {
627 case FTYPE_CD:
628 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
629 if (size == 2048LL * (unsigned)-1)
630 size = 0;
631 /* XXX no disc? maybe we need to reopen... */
632 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
633 reopened = 1;
634 goto again;
637 #endif
638 } else {
639 size = lseek(fd, 0, SEEK_END);
641 return size;
643 #else
644 static int64_t raw_getlength(BlockDriverState *bs)
646 BDRVRawState *s = bs->opaque;
647 int ret;
649 ret = fd_open(bs);
650 if (ret < 0) {
651 return ret;
654 return lseek(s->fd, 0, SEEK_END);
656 #endif
658 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
660 struct stat st;
661 BDRVRawState *s = bs->opaque;
663 if (fstat(s->fd, &st) < 0) {
664 return -errno;
666 return (int64_t)st.st_blocks * 512;
669 static int raw_create(const char *filename, QEMUOptionParameter *options)
671 int fd;
672 int result = 0;
673 int64_t total_size = 0;
675 /* Read out options */
676 while (options && options->name) {
677 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
678 total_size = options->value.n / BDRV_SECTOR_SIZE;
680 options++;
683 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
684 0644);
685 if (fd < 0) {
686 result = -errno;
687 } else {
688 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
689 result = -errno;
691 if (qemu_close(fd) != 0) {
692 result = -errno;
695 return result;
699 * Returns true iff the specified sector is present in the disk image. Drivers
700 * not implementing the functionality are assumed to not support backing files,
701 * hence all their sectors are reported as allocated.
703 * If 'sector_num' is beyond the end of the disk image the return value is 0
704 * and 'pnum' is set to 0.
706 * 'pnum' is set to the number of sectors (including and immediately following
707 * the specified sector) that are known to be in the same
708 * allocated/unallocated state.
710 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
711 * beyond the end of the disk image it will be clamped.
713 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
714 int64_t sector_num,
715 int nb_sectors, int *pnum)
717 off_t start, data, hole;
718 int ret;
720 ret = fd_open(bs);
721 if (ret < 0) {
722 return ret;
725 start = sector_num * BDRV_SECTOR_SIZE;
727 #ifdef CONFIG_FIEMAP
729 BDRVRawState *s = bs->opaque;
730 struct {
731 struct fiemap fm;
732 struct fiemap_extent fe;
733 } f;
735 f.fm.fm_start = start;
736 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
737 f.fm.fm_flags = 0;
738 f.fm.fm_extent_count = 1;
739 f.fm.fm_reserved = 0;
740 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
741 /* Assume everything is allocated. */
742 *pnum = nb_sectors;
743 return 1;
746 if (f.fm.fm_mapped_extents == 0) {
747 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
748 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
750 off_t length = lseek(s->fd, 0, SEEK_END);
751 hole = f.fm.fm_start;
752 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
753 } else {
754 data = f.fe.fe_logical;
755 hole = f.fe.fe_logical + f.fe.fe_length;
758 #elif defined SEEK_HOLE && defined SEEK_DATA
760 BDRVRawState *s = bs->opaque;
762 hole = lseek(s->fd, start, SEEK_HOLE);
763 if (hole == -1) {
764 /* -ENXIO indicates that sector_num was past the end of the file.
765 * There is a virtual hole there. */
766 assert(errno != -ENXIO);
768 /* Most likely EINVAL. Assume everything is allocated. */
769 *pnum = nb_sectors;
770 return 1;
773 if (hole > start) {
774 data = start;
775 } else {
776 /* On a hole. We need another syscall to find its end. */
777 data = lseek(s->fd, start, SEEK_DATA);
778 if (data == -1) {
779 data = lseek(s->fd, 0, SEEK_END);
782 #else
783 *pnum = nb_sectors;
784 return 1;
785 #endif
787 if (data <= start) {
788 /* On a data extent, compute sectors to the end of the extent. */
789 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
790 return 1;
791 } else {
792 /* On a hole, compute sectors to the beginning of the next extent. */
793 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
794 return 0;
798 #ifdef CONFIG_XFS
799 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
801 struct xfs_flock64 fl;
803 memset(&fl, 0, sizeof(fl));
804 fl.l_whence = SEEK_SET;
805 fl.l_start = sector_num << 9;
806 fl.l_len = (int64_t)nb_sectors << 9;
808 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
809 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
810 return -errno;
813 return 0;
815 #endif
817 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
818 int64_t sector_num, int nb_sectors)
820 #ifdef CONFIG_XFS
821 BDRVRawState *s = bs->opaque;
823 if (s->is_xfs) {
824 return xfs_discard(s, sector_num, nb_sectors);
826 #endif
828 return 0;
831 static QEMUOptionParameter raw_create_options[] = {
833 .name = BLOCK_OPT_SIZE,
834 .type = OPT_SIZE,
835 .help = "Virtual disk size"
837 { NULL }
840 static BlockDriver bdrv_file = {
841 .format_name = "file",
842 .protocol_name = "file",
843 .instance_size = sizeof(BDRVRawState),
844 .bdrv_probe = NULL, /* no probe for protocols */
845 .bdrv_file_open = raw_open,
846 .bdrv_reopen_prepare = raw_reopen_prepare,
847 .bdrv_reopen_commit = raw_reopen_commit,
848 .bdrv_reopen_abort = raw_reopen_abort,
849 .bdrv_close = raw_close,
850 .bdrv_create = raw_create,
851 .bdrv_co_discard = raw_co_discard,
852 .bdrv_co_is_allocated = raw_co_is_allocated,
854 .bdrv_aio_readv = raw_aio_readv,
855 .bdrv_aio_writev = raw_aio_writev,
856 .bdrv_aio_flush = raw_aio_flush,
858 .bdrv_truncate = raw_truncate,
859 .bdrv_getlength = raw_getlength,
860 .bdrv_get_allocated_file_size
861 = raw_get_allocated_file_size,
863 .create_options = raw_create_options,
866 /***********************************************/
867 /* host device */
869 #if defined(__APPLE__) && defined(__MACH__)
870 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
871 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
873 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
875 kern_return_t kernResult;
876 mach_port_t masterPort;
877 CFMutableDictionaryRef classesToMatch;
879 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
880 if ( KERN_SUCCESS != kernResult ) {
881 printf( "IOMasterPort returned %d\n", kernResult );
884 classesToMatch = IOServiceMatching( kIOCDMediaClass );
885 if ( classesToMatch == NULL ) {
886 printf( "IOServiceMatching returned a NULL dictionary.\n" );
887 } else {
888 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
890 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
891 if ( KERN_SUCCESS != kernResult )
893 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
896 return kernResult;
899 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
901 io_object_t nextMedia;
902 kern_return_t kernResult = KERN_FAILURE;
903 *bsdPath = '\0';
904 nextMedia = IOIteratorNext( mediaIterator );
905 if ( nextMedia )
907 CFTypeRef bsdPathAsCFString;
908 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
909 if ( bsdPathAsCFString ) {
910 size_t devPathLength;
911 strcpy( bsdPath, _PATH_DEV );
912 strcat( bsdPath, "r" );
913 devPathLength = strlen( bsdPath );
914 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
915 kernResult = KERN_SUCCESS;
917 CFRelease( bsdPathAsCFString );
919 IOObjectRelease( nextMedia );
922 return kernResult;
925 #endif
927 static int hdev_probe_device(const char *filename)
929 struct stat st;
931 /* allow a dedicated CD-ROM driver to match with a higher priority */
932 if (strstart(filename, "/dev/cdrom", NULL))
933 return 50;
935 if (stat(filename, &st) >= 0 &&
936 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
937 return 100;
940 return 0;
943 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
945 BDRVRawState *s = bs->opaque;
947 #if defined(__APPLE__) && defined(__MACH__)
948 if (strstart(filename, "/dev/cdrom", NULL)) {
949 kern_return_t kernResult;
950 io_iterator_t mediaIterator;
951 char bsdPath[ MAXPATHLEN ];
952 int fd;
954 kernResult = FindEjectableCDMedia( &mediaIterator );
955 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
957 if ( bsdPath[ 0 ] != '\0' ) {
958 strcat(bsdPath,"s0");
959 /* some CDs don't have a partition 0 */
960 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
961 if (fd < 0) {
962 bsdPath[strlen(bsdPath)-1] = '1';
963 } else {
964 qemu_close(fd);
966 filename = bsdPath;
969 if ( mediaIterator )
970 IOObjectRelease( mediaIterator );
972 #endif
974 s->type = FTYPE_FILE;
975 #if defined(__linux__)
977 char resolved_path[ MAXPATHLEN ], *temp;
979 temp = realpath(filename, resolved_path);
980 if (temp && strstart(temp, "/dev/sg", NULL)) {
981 bs->sg = 1;
984 #endif
986 return raw_open_common(bs, filename, flags, 0);
989 #if defined(__linux__)
990 /* Note: we do not have a reliable method to detect if the floppy is
991 present. The current method is to try to open the floppy at every
992 I/O and to keep it opened during a few hundreds of ms. */
993 static int fd_open(BlockDriverState *bs)
995 BDRVRawState *s = bs->opaque;
996 int last_media_present;
998 if (s->type != FTYPE_FD)
999 return 0;
1000 last_media_present = (s->fd >= 0);
1001 if (s->fd >= 0 &&
1002 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1003 qemu_close(s->fd);
1004 s->fd = -1;
1005 #ifdef DEBUG_FLOPPY
1006 printf("Floppy closed\n");
1007 #endif
1009 if (s->fd < 0) {
1010 if (s->fd_got_error &&
1011 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1012 #ifdef DEBUG_FLOPPY
1013 printf("No floppy (open delayed)\n");
1014 #endif
1015 return -EIO;
1017 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1018 if (s->fd < 0) {
1019 s->fd_error_time = get_clock();
1020 s->fd_got_error = 1;
1021 if (last_media_present)
1022 s->fd_media_changed = 1;
1023 #ifdef DEBUG_FLOPPY
1024 printf("No floppy\n");
1025 #endif
1026 return -EIO;
1028 #ifdef DEBUG_FLOPPY
1029 printf("Floppy opened\n");
1030 #endif
1032 if (!last_media_present)
1033 s->fd_media_changed = 1;
1034 s->fd_open_time = get_clock();
1035 s->fd_got_error = 0;
1036 return 0;
1039 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1041 BDRVRawState *s = bs->opaque;
1043 return ioctl(s->fd, req, buf);
1046 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1047 unsigned long int req, void *buf,
1048 BlockDriverCompletionFunc *cb, void *opaque)
1050 BDRVRawState *s = bs->opaque;
1052 if (fd_open(bs) < 0)
1053 return NULL;
1054 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
1057 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1058 static int fd_open(BlockDriverState *bs)
1060 BDRVRawState *s = bs->opaque;
1062 /* this is just to ensure s->fd is sane (its called by io ops) */
1063 if (s->fd >= 0)
1064 return 0;
1065 return -EIO;
1067 #else /* !linux && !FreeBSD */
1069 static int fd_open(BlockDriverState *bs)
1071 return 0;
1074 #endif /* !linux && !FreeBSD */
1076 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1078 int fd;
1079 int ret = 0;
1080 struct stat stat_buf;
1081 int64_t total_size = 0;
1083 /* Read out options */
1084 while (options && options->name) {
1085 if (!strcmp(options->name, "size")) {
1086 total_size = options->value.n / BDRV_SECTOR_SIZE;
1088 options++;
1091 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1092 if (fd < 0)
1093 return -errno;
1095 if (fstat(fd, &stat_buf) < 0)
1096 ret = -errno;
1097 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1098 ret = -ENODEV;
1099 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1100 ret = -ENOSPC;
1102 qemu_close(fd);
1103 return ret;
1106 static int hdev_has_zero_init(BlockDriverState *bs)
1108 return 0;
1111 static BlockDriver bdrv_host_device = {
1112 .format_name = "host_device",
1113 .protocol_name = "host_device",
1114 .instance_size = sizeof(BDRVRawState),
1115 .bdrv_probe_device = hdev_probe_device,
1116 .bdrv_file_open = hdev_open,
1117 .bdrv_close = raw_close,
1118 .bdrv_create = hdev_create,
1119 .create_options = raw_create_options,
1120 .bdrv_has_zero_init = hdev_has_zero_init,
1122 .bdrv_aio_readv = raw_aio_readv,
1123 .bdrv_aio_writev = raw_aio_writev,
1124 .bdrv_aio_flush = raw_aio_flush,
1126 .bdrv_truncate = raw_truncate,
1127 .bdrv_getlength = raw_getlength,
1128 .bdrv_get_allocated_file_size
1129 = raw_get_allocated_file_size,
1131 /* generic scsi device */
1132 #ifdef __linux__
1133 .bdrv_ioctl = hdev_ioctl,
1134 .bdrv_aio_ioctl = hdev_aio_ioctl,
1135 #endif
1138 #ifdef __linux__
1139 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1141 BDRVRawState *s = bs->opaque;
1142 int ret;
1144 s->type = FTYPE_FD;
1146 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1147 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1148 if (ret)
1149 return ret;
1151 /* close fd so that we can reopen it as needed */
1152 qemu_close(s->fd);
1153 s->fd = -1;
1154 s->fd_media_changed = 1;
1156 return 0;
1159 static int floppy_probe_device(const char *filename)
1161 int fd, ret;
1162 int prio = 0;
1163 struct floppy_struct fdparam;
1164 struct stat st;
1166 if (strstart(filename, "/dev/fd", NULL) &&
1167 !strstart(filename, "/dev/fdset/", NULL)) {
1168 prio = 50;
1171 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1172 if (fd < 0) {
1173 goto out;
1175 ret = fstat(fd, &st);
1176 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1177 goto outc;
1180 /* Attempt to detect via a floppy specific ioctl */
1181 ret = ioctl(fd, FDGETPRM, &fdparam);
1182 if (ret >= 0)
1183 prio = 100;
1185 outc:
1186 qemu_close(fd);
1187 out:
1188 return prio;
1192 static int floppy_is_inserted(BlockDriverState *bs)
1194 return fd_open(bs) >= 0;
1197 static int floppy_media_changed(BlockDriverState *bs)
1199 BDRVRawState *s = bs->opaque;
1200 int ret;
1203 * XXX: we do not have a true media changed indication.
1204 * It does not work if the floppy is changed without trying to read it.
1206 fd_open(bs);
1207 ret = s->fd_media_changed;
1208 s->fd_media_changed = 0;
1209 #ifdef DEBUG_FLOPPY
1210 printf("Floppy changed=%d\n", ret);
1211 #endif
1212 return ret;
1215 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1217 BDRVRawState *s = bs->opaque;
1218 int fd;
1220 if (s->fd >= 0) {
1221 qemu_close(s->fd);
1222 s->fd = -1;
1224 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1225 if (fd >= 0) {
1226 if (ioctl(fd, FDEJECT, 0) < 0)
1227 perror("FDEJECT");
1228 qemu_close(fd);
1232 static BlockDriver bdrv_host_floppy = {
1233 .format_name = "host_floppy",
1234 .protocol_name = "host_floppy",
1235 .instance_size = sizeof(BDRVRawState),
1236 .bdrv_probe_device = floppy_probe_device,
1237 .bdrv_file_open = floppy_open,
1238 .bdrv_close = raw_close,
1239 .bdrv_create = hdev_create,
1240 .create_options = raw_create_options,
1241 .bdrv_has_zero_init = hdev_has_zero_init,
1243 .bdrv_aio_readv = raw_aio_readv,
1244 .bdrv_aio_writev = raw_aio_writev,
1245 .bdrv_aio_flush = raw_aio_flush,
1247 .bdrv_truncate = raw_truncate,
1248 .bdrv_getlength = raw_getlength,
1249 .bdrv_get_allocated_file_size
1250 = raw_get_allocated_file_size,
1252 /* removable device support */
1253 .bdrv_is_inserted = floppy_is_inserted,
1254 .bdrv_media_changed = floppy_media_changed,
1255 .bdrv_eject = floppy_eject,
1258 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1260 BDRVRawState *s = bs->opaque;
1262 s->type = FTYPE_CD;
1264 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1265 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1268 static int cdrom_probe_device(const char *filename)
1270 int fd, ret;
1271 int prio = 0;
1272 struct stat st;
1274 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1275 if (fd < 0) {
1276 goto out;
1278 ret = fstat(fd, &st);
1279 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1280 goto outc;
1283 /* Attempt to detect via a CDROM specific ioctl */
1284 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1285 if (ret >= 0)
1286 prio = 100;
1288 outc:
1289 qemu_close(fd);
1290 out:
1291 return prio;
1294 static int cdrom_is_inserted(BlockDriverState *bs)
1296 BDRVRawState *s = bs->opaque;
1297 int ret;
1299 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1300 if (ret == CDS_DISC_OK)
1301 return 1;
1302 return 0;
1305 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1307 BDRVRawState *s = bs->opaque;
1309 if (eject_flag) {
1310 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1311 perror("CDROMEJECT");
1312 } else {
1313 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1314 perror("CDROMEJECT");
1318 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1320 BDRVRawState *s = bs->opaque;
1322 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1324 * Note: an error can happen if the distribution automatically
1325 * mounts the CD-ROM
1327 /* perror("CDROM_LOCKDOOR"); */
1331 static BlockDriver bdrv_host_cdrom = {
1332 .format_name = "host_cdrom",
1333 .protocol_name = "host_cdrom",
1334 .instance_size = sizeof(BDRVRawState),
1335 .bdrv_probe_device = cdrom_probe_device,
1336 .bdrv_file_open = cdrom_open,
1337 .bdrv_close = raw_close,
1338 .bdrv_create = hdev_create,
1339 .create_options = raw_create_options,
1340 .bdrv_has_zero_init = hdev_has_zero_init,
1342 .bdrv_aio_readv = raw_aio_readv,
1343 .bdrv_aio_writev = raw_aio_writev,
1344 .bdrv_aio_flush = raw_aio_flush,
1346 .bdrv_truncate = raw_truncate,
1347 .bdrv_getlength = raw_getlength,
1348 .bdrv_get_allocated_file_size
1349 = raw_get_allocated_file_size,
1351 /* removable device support */
1352 .bdrv_is_inserted = cdrom_is_inserted,
1353 .bdrv_eject = cdrom_eject,
1354 .bdrv_lock_medium = cdrom_lock_medium,
1356 /* generic scsi device */
1357 .bdrv_ioctl = hdev_ioctl,
1358 .bdrv_aio_ioctl = hdev_aio_ioctl,
1360 #endif /* __linux__ */
1362 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1363 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1365 BDRVRawState *s = bs->opaque;
1366 int ret;
1368 s->type = FTYPE_CD;
1370 ret = raw_open_common(bs, filename, flags, 0);
1371 if (ret)
1372 return ret;
1374 /* make sure the door isn't locked at this time */
1375 ioctl(s->fd, CDIOCALLOW);
1376 return 0;
1379 static int cdrom_probe_device(const char *filename)
1381 if (strstart(filename, "/dev/cd", NULL) ||
1382 strstart(filename, "/dev/acd", NULL))
1383 return 100;
1384 return 0;
1387 static int cdrom_reopen(BlockDriverState *bs)
1389 BDRVRawState *s = bs->opaque;
1390 int fd;
1393 * Force reread of possibly changed/newly loaded disc,
1394 * FreeBSD seems to not notice sometimes...
1396 if (s->fd >= 0)
1397 qemu_close(s->fd);
1398 fd = qemu_open(bs->filename, s->open_flags, 0644);
1399 if (fd < 0) {
1400 s->fd = -1;
1401 return -EIO;
1403 s->fd = fd;
1405 /* make sure the door isn't locked at this time */
1406 ioctl(s->fd, CDIOCALLOW);
1407 return 0;
1410 static int cdrom_is_inserted(BlockDriverState *bs)
1412 return raw_getlength(bs) > 0;
1415 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1417 BDRVRawState *s = bs->opaque;
1419 if (s->fd < 0)
1420 return;
1422 (void) ioctl(s->fd, CDIOCALLOW);
1424 if (eject_flag) {
1425 if (ioctl(s->fd, CDIOCEJECT) < 0)
1426 perror("CDIOCEJECT");
1427 } else {
1428 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1429 perror("CDIOCCLOSE");
1432 cdrom_reopen(bs);
1435 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1437 BDRVRawState *s = bs->opaque;
1439 if (s->fd < 0)
1440 return;
1441 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1443 * Note: an error can happen if the distribution automatically
1444 * mounts the CD-ROM
1446 /* perror("CDROM_LOCKDOOR"); */
1450 static BlockDriver bdrv_host_cdrom = {
1451 .format_name = "host_cdrom",
1452 .protocol_name = "host_cdrom",
1453 .instance_size = sizeof(BDRVRawState),
1454 .bdrv_probe_device = cdrom_probe_device,
1455 .bdrv_file_open = cdrom_open,
1456 .bdrv_close = raw_close,
1457 .bdrv_create = hdev_create,
1458 .create_options = raw_create_options,
1459 .bdrv_has_zero_init = hdev_has_zero_init,
1461 .bdrv_aio_readv = raw_aio_readv,
1462 .bdrv_aio_writev = raw_aio_writev,
1463 .bdrv_aio_flush = raw_aio_flush,
1465 .bdrv_truncate = raw_truncate,
1466 .bdrv_getlength = raw_getlength,
1467 .bdrv_get_allocated_file_size
1468 = raw_get_allocated_file_size,
1470 /* removable device support */
1471 .bdrv_is_inserted = cdrom_is_inserted,
1472 .bdrv_eject = cdrom_eject,
1473 .bdrv_lock_medium = cdrom_lock_medium,
1475 #endif /* __FreeBSD__ */
1477 static void bdrv_file_init(void)
1480 * Register all the drivers. Note that order is important, the driver
1481 * registered last will get probed first.
1483 bdrv_register(&bdrv_file);
1484 bdrv_register(&bdrv_host_device);
1485 #ifdef __linux__
1486 bdrv_register(&bdrv_host_floppy);
1487 bdrv_register(&bdrv_host_cdrom);
1488 #endif
1489 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1490 bdrv_register(&bdrv_host_cdrom);
1491 #endif
1494 block_init(bdrv_file_init);