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"
26 #include "qemu-char.h"
28 #include "block_int.h"
31 #include "thread-pool.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>
61 #include <linux/fiemap.h>
63 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
69 #include <sys/ioctl.h>
70 #include <sys/disklabel.h>
75 #include <sys/ioctl.h>
76 #include <sys/disklabel.h>
82 #include <sys/ioctl.h>
83 #include <sys/diskslice.h>
90 //#define DEBUG_FLOPPY
93 #if defined(DEBUG_BLOCK)
94 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
95 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
97 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
100 /* OS X does not have O_DSYNC */
103 #define O_DSYNC O_SYNC
104 #elif defined(O_FSYNC)
105 #define O_DSYNC O_FSYNC
109 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
111 #define O_DIRECT O_DSYNC
118 /* if the FD is not accessed during that time (in ns), we try to
119 reopen it to see if the disk has been changed */
120 #define FD_OPEN_TIMEOUT (1000000000)
122 #define MAX_BLOCKSIZE 4096
124 typedef struct BDRVRawState {
128 #if defined(__linux__)
129 /* linux floppy specific */
130 int64_t fd_open_time;
131 int64_t fd_error_time;
133 int fd_media_changed;
135 #ifdef CONFIG_LINUX_AIO
144 typedef struct BDRVRawReopenState {
147 #ifdef CONFIG_LINUX_AIO
150 } BDRVRawReopenState;
152 static int fd_open(BlockDriverState *bs);
153 static int64_t raw_getlength(BlockDriverState *bs);
155 typedef struct RawPosixAIOData {
156 BlockDriverState *bs;
159 struct iovec *aio_iov;
164 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
169 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
170 static int cdrom_reopen(BlockDriverState *bs);
173 #if defined(__NetBSD__)
174 static int raw_normalize_devicepath(const char **filename)
176 static char namebuf[PATH_MAX];
177 const char *dp, *fname;
181 dp = strrchr(fname, '/');
182 if (lstat(fname, &sb) < 0) {
183 fprintf(stderr, "%s: stat failed: %s\n",
184 fname, strerror(errno));
188 if (!S_ISBLK(sb.st_mode)) {
193 snprintf(namebuf, PATH_MAX, "r%s", fname);
195 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
196 (int)(dp - fname), fname, dp + 1);
198 fprintf(stderr, "%s is a block device", fname);
200 fprintf(stderr, ", using %s\n", *filename);
205 static int raw_normalize_devicepath(const char **filename)
211 static void raw_parse_flags(int bdrv_flags, int *open_flags)
213 assert(open_flags != NULL);
215 *open_flags |= O_BINARY;
216 *open_flags &= ~O_ACCMODE;
217 if (bdrv_flags & BDRV_O_RDWR) {
218 *open_flags |= O_RDWR;
220 *open_flags |= O_RDONLY;
223 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
224 * and O_DIRECT for no caching. */
225 if ((bdrv_flags & BDRV_O_NOCACHE)) {
226 *open_flags |= O_DIRECT;
230 #ifdef CONFIG_LINUX_AIO
231 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
234 assert(aio_ctx != NULL);
235 assert(use_aio != NULL);
237 * Currently Linux do AIO only for files opened with O_DIRECT
238 * specified so check NOCACHE flag too
240 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
241 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
243 /* if non-NULL, laio_init() has already been run */
244 if (*aio_ctx == NULL) {
245 *aio_ctx = laio_init();
262 static int raw_open_common(BlockDriverState *bs, const char *filename,
263 int bdrv_flags, int open_flags)
265 BDRVRawState *s = bs->opaque;
268 ret = raw_normalize_devicepath(&filename);
273 s->open_flags = open_flags;
274 raw_parse_flags(bdrv_flags, &s->open_flags);
277 fd = qemu_open(filename, s->open_flags, 0644);
286 #ifdef CONFIG_LINUX_AIO
287 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
294 if (platform_test_xfs_fd(s->fd)) {
302 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
304 BDRVRawState *s = bs->opaque;
306 s->type = FTYPE_FILE;
307 return raw_open_common(bs, filename, flags, 0);
310 static int raw_reopen_prepare(BDRVReopenState *state,
311 BlockReopenQueue *queue, Error **errp)
314 BDRVRawReopenState *raw_s;
317 assert(state != NULL);
318 assert(state->bs != NULL);
320 s = state->bs->opaque;
322 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
323 raw_s = state->opaque;
325 #ifdef CONFIG_LINUX_AIO
326 raw_s->use_aio = s->use_aio;
328 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
329 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
330 * won't override aio_ctx if aio_ctx is non-NULL */
331 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
336 raw_parse_flags(state->flags, &raw_s->open_flags);
340 int fcntl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
342 fcntl_flags |= O_NOATIME;
345 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
346 /* dup the original fd */
347 /* TODO: use qemu fcntl wrapper */
348 #ifdef F_DUPFD_CLOEXEC
349 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
351 raw_s->fd = dup(s->fd);
352 if (raw_s->fd != -1) {
353 qemu_set_cloexec(raw_s->fd);
356 if (raw_s->fd >= 0) {
357 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
359 qemu_close(raw_s->fd);
365 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
366 if (raw_s->fd == -1) {
367 assert(!(raw_s->open_flags & O_CREAT));
368 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
369 if (raw_s->fd == -1) {
377 static void raw_reopen_commit(BDRVReopenState *state)
379 BDRVRawReopenState *raw_s = state->opaque;
380 BDRVRawState *s = state->bs->opaque;
382 s->open_flags = raw_s->open_flags;
386 #ifdef CONFIG_LINUX_AIO
387 s->use_aio = raw_s->use_aio;
390 g_free(state->opaque);
391 state->opaque = NULL;
395 static void raw_reopen_abort(BDRVReopenState *state)
397 BDRVRawReopenState *raw_s = state->opaque;
399 /* nothing to do if NULL, we didn't get far enough */
404 if (raw_s->fd >= 0) {
405 qemu_close(raw_s->fd);
408 g_free(state->opaque);
409 state->opaque = NULL;
413 /* XXX: use host sector size if necessary with:
414 #ifdef DIOCGSECTORSIZE
416 unsigned int sectorsize = 512;
417 if (!ioctl(fd, DIOCGSECTORSIZE, §orsize) &&
418 sectorsize > bufsize)
419 bufsize = sectorsize;
423 uint32_t blockSize = 512;
424 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
431 * Check if all memory in this vector is sector aligned.
433 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
437 for (i = 0; i < qiov->niov; i++) {
438 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
446 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
450 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
456 * This looks weird, but the aio code only considers a request
457 * successful if it has written the full number of bytes.
459 * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command,
460 * so in fact we return the ioctl command here to make posix_aio_read()
463 return aiocb->aio_nbytes;
466 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
470 ret = qemu_fdatasync(aiocb->aio_fildes);
479 static bool preadv_present = true;
482 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
484 return preadv(fd, iov, nr_iov, offset);
488 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
490 return pwritev(fd, iov, nr_iov, offset);
495 static bool preadv_present = false;
498 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
504 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
511 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
516 if (aiocb->aio_type & QEMU_AIO_WRITE)
517 len = qemu_pwritev(aiocb->aio_fildes,
522 len = qemu_preadv(aiocb->aio_fildes,
526 } while (len == -1 && errno == EINTR);
535 * Read/writes the data to/from a given linear buffer.
537 * Returns the number of bytes handles or -errno in case of an error. Short
538 * reads are only returned if the end of the file is reached.
540 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
545 while (offset < aiocb->aio_nbytes) {
546 if (aiocb->aio_type & QEMU_AIO_WRITE) {
547 len = pwrite(aiocb->aio_fildes,
548 (const char *)buf + offset,
549 aiocb->aio_nbytes - offset,
550 aiocb->aio_offset + offset);
552 len = pread(aiocb->aio_fildes,
554 aiocb->aio_nbytes - offset,
555 aiocb->aio_offset + offset);
557 if (len == -1 && errno == EINTR) {
559 } else if (len == -1) {
562 } else if (len == 0) {
571 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
576 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
578 * If there is just a single buffer, and it is properly aligned
579 * we can just use plain pread/pwrite without any problems.
581 if (aiocb->aio_niov == 1) {
582 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
585 * We have more than one iovec, and all are properly aligned.
587 * Try preadv/pwritev first and fall back to linearizing the
588 * buffer if it's not supported.
590 if (preadv_present) {
591 nbytes = handle_aiocb_rw_vector(aiocb);
592 if (nbytes == aiocb->aio_nbytes ||
593 (nbytes < 0 && nbytes != -ENOSYS)) {
596 preadv_present = false;
600 * XXX(hch): short read/write. no easy way to handle the reminder
601 * using these interfaces. For now retry using plain
607 * Ok, we have to do it the hard way, copy all segments into
608 * a single aligned buffer.
610 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
611 if (aiocb->aio_type & QEMU_AIO_WRITE) {
615 for (i = 0; i < aiocb->aio_niov; ++i) {
616 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
617 p += aiocb->aio_iov[i].iov_len;
621 nbytes = handle_aiocb_rw_linear(aiocb, buf);
622 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
624 size_t count = aiocb->aio_nbytes, copy;
627 for (i = 0; i < aiocb->aio_niov && count; ++i) {
629 if (copy > aiocb->aio_iov[i].iov_len) {
630 copy = aiocb->aio_iov[i].iov_len;
632 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
642 static int aio_worker(void *arg)
644 RawPosixAIOData *aiocb = arg;
647 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
649 ret = handle_aiocb_rw(aiocb);
650 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
651 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
652 0, aiocb->aio_nbytes - ret);
654 ret = aiocb->aio_nbytes;
656 if (ret == aiocb->aio_nbytes) {
658 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
663 ret = handle_aiocb_rw(aiocb);
664 if (ret == aiocb->aio_nbytes) {
666 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
671 ret = handle_aiocb_flush(aiocb);
674 ret = handle_aiocb_ioctl(aiocb);
677 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
682 g_slice_free(RawPosixAIOData, aiocb);
686 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
687 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
688 BlockDriverCompletionFunc *cb, void *opaque, int type)
690 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
693 acb->aio_type = type;
694 acb->aio_fildes = fd;
697 acb->aio_iov = qiov->iov;
698 acb->aio_niov = qiov->niov;
700 acb->aio_nbytes = nb_sectors * 512;
701 acb->aio_offset = sector_num * 512;
703 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
704 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
707 static BlockDriverAIOCB *paio_ioctl(BlockDriverState *bs, int fd,
708 unsigned long int req, void *buf,
709 BlockDriverCompletionFunc *cb, void *opaque)
711 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
714 acb->aio_type = QEMU_AIO_IOCTL;
715 acb->aio_fildes = fd;
717 acb->aio_ioctl_buf = buf;
718 acb->aio_ioctl_cmd = req;
720 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
723 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
724 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
725 BlockDriverCompletionFunc *cb, void *opaque, int type)
727 BDRVRawState *s = bs->opaque;
733 * If O_DIRECT is used the buffer needs to be aligned on a sector
734 * boundary. Check if this is the case or tell the low-level
735 * driver that it needs to copy the buffer.
737 if ((bs->open_flags & BDRV_O_NOCACHE)) {
738 if (!qiov_is_aligned(bs, qiov)) {
739 type |= QEMU_AIO_MISALIGNED;
740 #ifdef CONFIG_LINUX_AIO
741 } else if (s->use_aio) {
742 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
743 nb_sectors, cb, opaque, type);
748 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
752 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
753 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
754 BlockDriverCompletionFunc *cb, void *opaque)
756 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
757 cb, opaque, QEMU_AIO_READ);
760 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
761 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
762 BlockDriverCompletionFunc *cb, void *opaque)
764 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
765 cb, opaque, QEMU_AIO_WRITE);
768 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
769 BlockDriverCompletionFunc *cb, void *opaque)
771 BDRVRawState *s = bs->opaque;
776 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
779 static void raw_close(BlockDriverState *bs)
781 BDRVRawState *s = bs->opaque;
788 static int raw_truncate(BlockDriverState *bs, int64_t offset)
790 BDRVRawState *s = bs->opaque;
793 if (fstat(s->fd, &st)) {
797 if (S_ISREG(st.st_mode)) {
798 if (ftruncate(s->fd, offset) < 0) {
801 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
802 if (offset > raw_getlength(bs)) {
813 static int64_t raw_getlength(BlockDriverState *bs)
815 BDRVRawState *s = bs->opaque;
821 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
824 if (ioctl(fd, DIOCGDINFO, &dl))
826 return (uint64_t)dl.d_secsize *
827 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
831 #elif defined(__NetBSD__)
832 static int64_t raw_getlength(BlockDriverState *bs)
834 BDRVRawState *s = bs->opaque;
840 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
841 struct dkwedge_info dkw;
843 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
844 return dkw.dkw_size * 512;
848 if (ioctl(fd, DIOCGDINFO, &dl))
850 return (uint64_t)dl.d_secsize *
851 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
856 #elif defined(__sun__)
857 static int64_t raw_getlength(BlockDriverState *bs)
859 BDRVRawState *s = bs->opaque;
860 struct dk_minfo minfo;
869 * Use the DKIOCGMEDIAINFO ioctl to read the size.
871 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
873 return minfo.dki_lbsize * minfo.dki_capacity;
877 * There are reports that lseek on some devices fails, but
878 * irc discussion said that contingency on contingency was overkill.
880 return lseek(s->fd, 0, SEEK_END);
882 #elif defined(CONFIG_BSD)
883 static int64_t raw_getlength(BlockDriverState *bs)
885 BDRVRawState *s = bs->opaque;
889 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
898 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
901 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
902 #ifdef DIOCGMEDIASIZE
903 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
904 #elif defined(DIOCGPART)
907 if (ioctl(fd, DIOCGPART, &pi) == 0)
908 size = pi.media_size;
914 #if defined(__APPLE__) && defined(__MACH__)
915 size = LONG_LONG_MAX;
917 size = lseek(fd, 0LL, SEEK_END);
919 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
922 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
923 if (size == 2048LL * (unsigned)-1)
925 /* XXX no disc? maybe we need to reopen... */
926 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
933 size = lseek(fd, 0, SEEK_END);
938 static int64_t raw_getlength(BlockDriverState *bs)
940 BDRVRawState *s = bs->opaque;
948 return lseek(s->fd, 0, SEEK_END);
952 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
955 BDRVRawState *s = bs->opaque;
957 if (fstat(s->fd, &st) < 0) {
960 return (int64_t)st.st_blocks * 512;
963 static int raw_create(const char *filename, QEMUOptionParameter *options)
967 int64_t total_size = 0;
969 /* Read out options */
970 while (options && options->name) {
971 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
972 total_size = options->value.n / BDRV_SECTOR_SIZE;
977 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
982 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
985 if (qemu_close(fd) != 0) {
993 * Returns true iff the specified sector is present in the disk image. Drivers
994 * not implementing the functionality are assumed to not support backing files,
995 * hence all their sectors are reported as allocated.
997 * If 'sector_num' is beyond the end of the disk image the return value is 0
998 * and 'pnum' is set to 0.
1000 * 'pnum' is set to the number of sectors (including and immediately following
1001 * the specified sector) that are known to be in the same
1002 * allocated/unallocated state.
1004 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1005 * beyond the end of the disk image it will be clamped.
1007 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
1009 int nb_sectors, int *pnum)
1011 off_t start, data, hole;
1019 start = sector_num * BDRV_SECTOR_SIZE;
1021 #ifdef CONFIG_FIEMAP
1023 BDRVRawState *s = bs->opaque;
1026 struct fiemap_extent fe;
1029 f.fm.fm_start = start;
1030 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1032 f.fm.fm_extent_count = 1;
1033 f.fm.fm_reserved = 0;
1034 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1035 /* Assume everything is allocated. */
1040 if (f.fm.fm_mapped_extents == 0) {
1041 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1042 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1044 off_t length = lseek(s->fd, 0, SEEK_END);
1045 hole = f.fm.fm_start;
1046 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1048 data = f.fe.fe_logical;
1049 hole = f.fe.fe_logical + f.fe.fe_length;
1052 #elif defined SEEK_HOLE && defined SEEK_DATA
1054 BDRVRawState *s = bs->opaque;
1056 hole = lseek(s->fd, start, SEEK_HOLE);
1058 /* -ENXIO indicates that sector_num was past the end of the file.
1059 * There is a virtual hole there. */
1060 assert(errno != -ENXIO);
1062 /* Most likely EINVAL. Assume everything is allocated. */
1070 /* On a hole. We need another syscall to find its end. */
1071 data = lseek(s->fd, start, SEEK_DATA);
1073 data = lseek(s->fd, 0, SEEK_END);
1081 if (data <= start) {
1082 /* On a data extent, compute sectors to the end of the extent. */
1083 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1086 /* On a hole, compute sectors to the beginning of the next extent. */
1087 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1093 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
1095 struct xfs_flock64 fl;
1097 memset(&fl, 0, sizeof(fl));
1098 fl.l_whence = SEEK_SET;
1099 fl.l_start = sector_num << 9;
1100 fl.l_len = (int64_t)nb_sectors << 9;
1102 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1103 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
1111 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
1112 int64_t sector_num, int nb_sectors)
1115 BDRVRawState *s = bs->opaque;
1118 return xfs_discard(s, sector_num, nb_sectors);
1125 static QEMUOptionParameter raw_create_options[] = {
1127 .name = BLOCK_OPT_SIZE,
1129 .help = "Virtual disk size"
1134 static BlockDriver bdrv_file = {
1135 .format_name = "file",
1136 .protocol_name = "file",
1137 .instance_size = sizeof(BDRVRawState),
1138 .bdrv_probe = NULL, /* no probe for protocols */
1139 .bdrv_file_open = raw_open,
1140 .bdrv_reopen_prepare = raw_reopen_prepare,
1141 .bdrv_reopen_commit = raw_reopen_commit,
1142 .bdrv_reopen_abort = raw_reopen_abort,
1143 .bdrv_close = raw_close,
1144 .bdrv_create = raw_create,
1145 .bdrv_co_discard = raw_co_discard,
1146 .bdrv_co_is_allocated = raw_co_is_allocated,
1148 .bdrv_aio_readv = raw_aio_readv,
1149 .bdrv_aio_writev = raw_aio_writev,
1150 .bdrv_aio_flush = raw_aio_flush,
1152 .bdrv_truncate = raw_truncate,
1153 .bdrv_getlength = raw_getlength,
1154 .bdrv_get_allocated_file_size
1155 = raw_get_allocated_file_size,
1157 .create_options = raw_create_options,
1160 /***********************************************/
1163 #if defined(__APPLE__) && defined(__MACH__)
1164 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1165 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1167 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1169 kern_return_t kernResult;
1170 mach_port_t masterPort;
1171 CFMutableDictionaryRef classesToMatch;
1173 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1174 if ( KERN_SUCCESS != kernResult ) {
1175 printf( "IOMasterPort returned %d\n", kernResult );
1178 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1179 if ( classesToMatch == NULL ) {
1180 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1182 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1184 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1185 if ( KERN_SUCCESS != kernResult )
1187 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1193 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1195 io_object_t nextMedia;
1196 kern_return_t kernResult = KERN_FAILURE;
1198 nextMedia = IOIteratorNext( mediaIterator );
1201 CFTypeRef bsdPathAsCFString;
1202 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1203 if ( bsdPathAsCFString ) {
1204 size_t devPathLength;
1205 strcpy( bsdPath, _PATH_DEV );
1206 strcat( bsdPath, "r" );
1207 devPathLength = strlen( bsdPath );
1208 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1209 kernResult = KERN_SUCCESS;
1211 CFRelease( bsdPathAsCFString );
1213 IOObjectRelease( nextMedia );
1221 static int hdev_probe_device(const char *filename)
1225 /* allow a dedicated CD-ROM driver to match with a higher priority */
1226 if (strstart(filename, "/dev/cdrom", NULL))
1229 if (stat(filename, &st) >= 0 &&
1230 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1237 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1239 BDRVRawState *s = bs->opaque;
1241 #if defined(__APPLE__) && defined(__MACH__)
1242 if (strstart(filename, "/dev/cdrom", NULL)) {
1243 kern_return_t kernResult;
1244 io_iterator_t mediaIterator;
1245 char bsdPath[ MAXPATHLEN ];
1248 kernResult = FindEjectableCDMedia( &mediaIterator );
1249 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1251 if ( bsdPath[ 0 ] != '\0' ) {
1252 strcat(bsdPath,"s0");
1253 /* some CDs don't have a partition 0 */
1254 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1256 bsdPath[strlen(bsdPath)-1] = '1';
1263 if ( mediaIterator )
1264 IOObjectRelease( mediaIterator );
1268 s->type = FTYPE_FILE;
1269 #if defined(__linux__)
1271 char resolved_path[ MAXPATHLEN ], *temp;
1273 temp = realpath(filename, resolved_path);
1274 if (temp && strstart(temp, "/dev/sg", NULL)) {
1280 return raw_open_common(bs, filename, flags, 0);
1283 #if defined(__linux__)
1284 /* Note: we do not have a reliable method to detect if the floppy is
1285 present. The current method is to try to open the floppy at every
1286 I/O and to keep it opened during a few hundreds of ms. */
1287 static int fd_open(BlockDriverState *bs)
1289 BDRVRawState *s = bs->opaque;
1290 int last_media_present;
1292 if (s->type != FTYPE_FD)
1294 last_media_present = (s->fd >= 0);
1296 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1300 printf("Floppy closed\n");
1304 if (s->fd_got_error &&
1305 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1307 printf("No floppy (open delayed)\n");
1311 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1313 s->fd_error_time = get_clock();
1314 s->fd_got_error = 1;
1315 if (last_media_present)
1316 s->fd_media_changed = 1;
1318 printf("No floppy\n");
1323 printf("Floppy opened\n");
1326 if (!last_media_present)
1327 s->fd_media_changed = 1;
1328 s->fd_open_time = get_clock();
1329 s->fd_got_error = 0;
1333 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1335 BDRVRawState *s = bs->opaque;
1337 return ioctl(s->fd, req, buf);
1340 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1341 unsigned long int req, void *buf,
1342 BlockDriverCompletionFunc *cb, void *opaque)
1344 BDRVRawState *s = bs->opaque;
1346 if (fd_open(bs) < 0)
1348 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
1351 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1352 static int fd_open(BlockDriverState *bs)
1354 BDRVRawState *s = bs->opaque;
1356 /* this is just to ensure s->fd is sane (its called by io ops) */
1361 #else /* !linux && !FreeBSD */
1363 static int fd_open(BlockDriverState *bs)
1368 #endif /* !linux && !FreeBSD */
1370 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1374 struct stat stat_buf;
1375 int64_t total_size = 0;
1377 /* Read out options */
1378 while (options && options->name) {
1379 if (!strcmp(options->name, "size")) {
1380 total_size = options->value.n / BDRV_SECTOR_SIZE;
1385 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1389 if (fstat(fd, &stat_buf) < 0)
1391 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1393 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1400 static int hdev_has_zero_init(BlockDriverState *bs)
1405 static BlockDriver bdrv_host_device = {
1406 .format_name = "host_device",
1407 .protocol_name = "host_device",
1408 .instance_size = sizeof(BDRVRawState),
1409 .bdrv_probe_device = hdev_probe_device,
1410 .bdrv_file_open = hdev_open,
1411 .bdrv_close = raw_close,
1412 .bdrv_create = hdev_create,
1413 .create_options = raw_create_options,
1414 .bdrv_has_zero_init = hdev_has_zero_init,
1416 .bdrv_aio_readv = raw_aio_readv,
1417 .bdrv_aio_writev = raw_aio_writev,
1418 .bdrv_aio_flush = raw_aio_flush,
1420 .bdrv_truncate = raw_truncate,
1421 .bdrv_getlength = raw_getlength,
1422 .bdrv_get_allocated_file_size
1423 = raw_get_allocated_file_size,
1425 /* generic scsi device */
1427 .bdrv_ioctl = hdev_ioctl,
1428 .bdrv_aio_ioctl = hdev_aio_ioctl,
1433 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1435 BDRVRawState *s = bs->opaque;
1440 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1441 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1445 /* close fd so that we can reopen it as needed */
1448 s->fd_media_changed = 1;
1453 static int floppy_probe_device(const char *filename)
1457 struct floppy_struct fdparam;
1460 if (strstart(filename, "/dev/fd", NULL) &&
1461 !strstart(filename, "/dev/fdset/", NULL)) {
1465 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1469 ret = fstat(fd, &st);
1470 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1474 /* Attempt to detect via a floppy specific ioctl */
1475 ret = ioctl(fd, FDGETPRM, &fdparam);
1486 static int floppy_is_inserted(BlockDriverState *bs)
1488 return fd_open(bs) >= 0;
1491 static int floppy_media_changed(BlockDriverState *bs)
1493 BDRVRawState *s = bs->opaque;
1497 * XXX: we do not have a true media changed indication.
1498 * It does not work if the floppy is changed without trying to read it.
1501 ret = s->fd_media_changed;
1502 s->fd_media_changed = 0;
1504 printf("Floppy changed=%d\n", ret);
1509 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1511 BDRVRawState *s = bs->opaque;
1518 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1520 if (ioctl(fd, FDEJECT, 0) < 0)
1526 static BlockDriver bdrv_host_floppy = {
1527 .format_name = "host_floppy",
1528 .protocol_name = "host_floppy",
1529 .instance_size = sizeof(BDRVRawState),
1530 .bdrv_probe_device = floppy_probe_device,
1531 .bdrv_file_open = floppy_open,
1532 .bdrv_close = raw_close,
1533 .bdrv_create = hdev_create,
1534 .create_options = raw_create_options,
1535 .bdrv_has_zero_init = hdev_has_zero_init,
1537 .bdrv_aio_readv = raw_aio_readv,
1538 .bdrv_aio_writev = raw_aio_writev,
1539 .bdrv_aio_flush = raw_aio_flush,
1541 .bdrv_truncate = raw_truncate,
1542 .bdrv_getlength = raw_getlength,
1543 .bdrv_get_allocated_file_size
1544 = raw_get_allocated_file_size,
1546 /* removable device support */
1547 .bdrv_is_inserted = floppy_is_inserted,
1548 .bdrv_media_changed = floppy_media_changed,
1549 .bdrv_eject = floppy_eject,
1552 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1554 BDRVRawState *s = bs->opaque;
1558 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1559 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1562 static int cdrom_probe_device(const char *filename)
1568 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1572 ret = fstat(fd, &st);
1573 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1577 /* Attempt to detect via a CDROM specific ioctl */
1578 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1588 static int cdrom_is_inserted(BlockDriverState *bs)
1590 BDRVRawState *s = bs->opaque;
1593 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1594 if (ret == CDS_DISC_OK)
1599 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1601 BDRVRawState *s = bs->opaque;
1604 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1605 perror("CDROMEJECT");
1607 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1608 perror("CDROMEJECT");
1612 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1614 BDRVRawState *s = bs->opaque;
1616 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1618 * Note: an error can happen if the distribution automatically
1621 /* perror("CDROM_LOCKDOOR"); */
1625 static BlockDriver bdrv_host_cdrom = {
1626 .format_name = "host_cdrom",
1627 .protocol_name = "host_cdrom",
1628 .instance_size = sizeof(BDRVRawState),
1629 .bdrv_probe_device = cdrom_probe_device,
1630 .bdrv_file_open = cdrom_open,
1631 .bdrv_close = raw_close,
1632 .bdrv_create = hdev_create,
1633 .create_options = raw_create_options,
1634 .bdrv_has_zero_init = hdev_has_zero_init,
1636 .bdrv_aio_readv = raw_aio_readv,
1637 .bdrv_aio_writev = raw_aio_writev,
1638 .bdrv_aio_flush = raw_aio_flush,
1640 .bdrv_truncate = raw_truncate,
1641 .bdrv_getlength = raw_getlength,
1642 .bdrv_get_allocated_file_size
1643 = raw_get_allocated_file_size,
1645 /* removable device support */
1646 .bdrv_is_inserted = cdrom_is_inserted,
1647 .bdrv_eject = cdrom_eject,
1648 .bdrv_lock_medium = cdrom_lock_medium,
1650 /* generic scsi device */
1651 .bdrv_ioctl = hdev_ioctl,
1652 .bdrv_aio_ioctl = hdev_aio_ioctl,
1654 #endif /* __linux__ */
1656 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1657 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1659 BDRVRawState *s = bs->opaque;
1664 ret = raw_open_common(bs, filename, flags, 0);
1668 /* make sure the door isn't locked at this time */
1669 ioctl(s->fd, CDIOCALLOW);
1673 static int cdrom_probe_device(const char *filename)
1675 if (strstart(filename, "/dev/cd", NULL) ||
1676 strstart(filename, "/dev/acd", NULL))
1681 static int cdrom_reopen(BlockDriverState *bs)
1683 BDRVRawState *s = bs->opaque;
1687 * Force reread of possibly changed/newly loaded disc,
1688 * FreeBSD seems to not notice sometimes...
1692 fd = qemu_open(bs->filename, s->open_flags, 0644);
1699 /* make sure the door isn't locked at this time */
1700 ioctl(s->fd, CDIOCALLOW);
1704 static int cdrom_is_inserted(BlockDriverState *bs)
1706 return raw_getlength(bs) > 0;
1709 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1711 BDRVRawState *s = bs->opaque;
1716 (void) ioctl(s->fd, CDIOCALLOW);
1719 if (ioctl(s->fd, CDIOCEJECT) < 0)
1720 perror("CDIOCEJECT");
1722 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1723 perror("CDIOCCLOSE");
1729 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1731 BDRVRawState *s = bs->opaque;
1735 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1737 * Note: an error can happen if the distribution automatically
1740 /* perror("CDROM_LOCKDOOR"); */
1744 static BlockDriver bdrv_host_cdrom = {
1745 .format_name = "host_cdrom",
1746 .protocol_name = "host_cdrom",
1747 .instance_size = sizeof(BDRVRawState),
1748 .bdrv_probe_device = cdrom_probe_device,
1749 .bdrv_file_open = cdrom_open,
1750 .bdrv_close = raw_close,
1751 .bdrv_create = hdev_create,
1752 .create_options = raw_create_options,
1753 .bdrv_has_zero_init = hdev_has_zero_init,
1755 .bdrv_aio_readv = raw_aio_readv,
1756 .bdrv_aio_writev = raw_aio_writev,
1757 .bdrv_aio_flush = raw_aio_flush,
1759 .bdrv_truncate = raw_truncate,
1760 .bdrv_getlength = raw_getlength,
1761 .bdrv_get_allocated_file_size
1762 = raw_get_allocated_file_size,
1764 /* removable device support */
1765 .bdrv_is_inserted = cdrom_is_inserted,
1766 .bdrv_eject = cdrom_eject,
1767 .bdrv_lock_medium = cdrom_lock_medium,
1769 #endif /* __FreeBSD__ */
1771 static void bdrv_file_init(void)
1774 * Register all the drivers. Note that order is important, the driver
1775 * registered last will get probed first.
1777 bdrv_register(&bdrv_file);
1778 bdrv_register(&bdrv_host_device);
1780 bdrv_register(&bdrv_host_floppy);
1781 bdrv_register(&bdrv_host_cdrom);
1783 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1784 bdrv_register(&bdrv_host_cdrom);
1788 block_init(bdrv_file_init);