vfio: Rework to have error paths
[qemu/ar7.git] / block / raw-posix.c
blob6586a0c9e1a602715ff526d65dac791af411fc5b
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 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
63 #include <linux/falloc.h>
64 #endif
65 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
66 #include <sys/disk.h>
67 #include <sys/cdio.h>
68 #endif
70 #ifdef __OpenBSD__
71 #include <sys/ioctl.h>
72 #include <sys/disklabel.h>
73 #include <sys/dkio.h>
74 #endif
76 #ifdef __NetBSD__
77 #include <sys/ioctl.h>
78 #include <sys/disklabel.h>
79 #include <sys/dkio.h>
80 #include <sys/disk.h>
81 #endif
83 #ifdef __DragonFly__
84 #include <sys/ioctl.h>
85 #include <sys/diskslice.h>
86 #endif
88 #ifdef CONFIG_XFS
89 #include <xfs/xfs.h>
90 #endif
92 //#define DEBUG_FLOPPY
94 //#define DEBUG_BLOCK
95 #if defined(DEBUG_BLOCK)
96 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
97 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
98 #else
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
100 #endif
102 /* OS X does not have O_DSYNC */
103 #ifndef O_DSYNC
104 #ifdef O_SYNC
105 #define O_DSYNC O_SYNC
106 #elif defined(O_FSYNC)
107 #define O_DSYNC O_FSYNC
108 #endif
109 #endif
111 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
112 #ifndef O_DIRECT
113 #define O_DIRECT O_DSYNC
114 #endif
116 #define FTYPE_FILE 0
117 #define FTYPE_CD 1
118 #define FTYPE_FD 2
120 /* if the FD is not accessed during that time (in ns), we try to
121 reopen it to see if the disk has been changed */
122 #define FD_OPEN_TIMEOUT (1000000000)
124 #define MAX_BLOCKSIZE 4096
126 typedef struct BDRVRawState {
127 int fd;
128 int type;
129 int open_flags;
130 size_t buf_align;
132 #if defined(__linux__)
133 /* linux floppy specific */
134 int64_t fd_open_time;
135 int64_t fd_error_time;
136 int fd_got_error;
137 int fd_media_changed;
138 #endif
139 #ifdef CONFIG_LINUX_AIO
140 int use_aio;
141 void *aio_ctx;
142 #endif
143 #ifdef CONFIG_XFS
144 bool is_xfs:1;
145 #endif
146 bool has_discard:1;
147 bool has_write_zeroes:1;
148 bool discard_zeroes:1;
149 #ifdef CONFIG_FIEMAP
150 bool skip_fiemap;
151 #endif
152 } BDRVRawState;
154 typedef struct BDRVRawReopenState {
155 int fd;
156 int open_flags;
157 #ifdef CONFIG_LINUX_AIO
158 int use_aio;
159 #endif
160 } BDRVRawReopenState;
162 static int fd_open(BlockDriverState *bs);
163 static int64_t raw_getlength(BlockDriverState *bs);
165 typedef struct RawPosixAIOData {
166 BlockDriverState *bs;
167 int aio_fildes;
168 union {
169 struct iovec *aio_iov;
170 void *aio_ioctl_buf;
172 int aio_niov;
173 uint64_t aio_nbytes;
174 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
175 off_t aio_offset;
176 int aio_type;
177 } RawPosixAIOData;
179 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
180 static int cdrom_reopen(BlockDriverState *bs);
181 #endif
183 #if defined(__NetBSD__)
184 static int raw_normalize_devicepath(const char **filename)
186 static char namebuf[PATH_MAX];
187 const char *dp, *fname;
188 struct stat sb;
190 fname = *filename;
191 dp = strrchr(fname, '/');
192 if (lstat(fname, &sb) < 0) {
193 fprintf(stderr, "%s: stat failed: %s\n",
194 fname, strerror(errno));
195 return -errno;
198 if (!S_ISBLK(sb.st_mode)) {
199 return 0;
202 if (dp == NULL) {
203 snprintf(namebuf, PATH_MAX, "r%s", fname);
204 } else {
205 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
206 (int)(dp - fname), fname, dp + 1);
208 fprintf(stderr, "%s is a block device", fname);
209 *filename = namebuf;
210 fprintf(stderr, ", using %s\n", *filename);
212 return 0;
214 #else
215 static int raw_normalize_devicepath(const char **filename)
217 return 0;
219 #endif
221 static void raw_probe_alignment(BlockDriverState *bs)
223 BDRVRawState *s = bs->opaque;
224 char *buf;
225 unsigned int sector_size;
227 /* For /dev/sg devices the alignment is not really used.
228 With buffered I/O, we don't have any restrictions. */
229 if (bs->sg || !(s->open_flags & O_DIRECT)) {
230 bs->request_alignment = 1;
231 s->buf_align = 1;
232 return;
235 /* Try a few ioctls to get the right size */
236 bs->request_alignment = 0;
237 s->buf_align = 0;
239 #ifdef BLKSSZGET
240 if (ioctl(s->fd, BLKSSZGET, &sector_size) >= 0) {
241 bs->request_alignment = sector_size;
243 #endif
244 #ifdef DKIOCGETBLOCKSIZE
245 if (ioctl(s->fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
246 bs->request_alignment = sector_size;
248 #endif
249 #ifdef DIOCGSECTORSIZE
250 if (ioctl(s->fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
251 bs->request_alignment = sector_size;
253 #endif
254 #ifdef CONFIG_XFS
255 if (s->is_xfs) {
256 struct dioattr da;
257 if (xfsctl(NULL, s->fd, XFS_IOC_DIOINFO, &da) >= 0) {
258 bs->request_alignment = da.d_miniosz;
259 /* The kernel returns wrong information for d_mem */
260 /* s->buf_align = da.d_mem; */
263 #endif
265 /* If we could not get the sizes so far, we can only guess them */
266 if (!s->buf_align) {
267 size_t align;
268 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
269 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
270 if (pread(s->fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
271 s->buf_align = align;
272 break;
275 qemu_vfree(buf);
278 if (!bs->request_alignment) {
279 size_t align;
280 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
281 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
282 if (pread(s->fd, buf, align, 0) >= 0) {
283 bs->request_alignment = align;
284 break;
287 qemu_vfree(buf);
291 static void raw_parse_flags(int bdrv_flags, int *open_flags)
293 assert(open_flags != NULL);
295 *open_flags |= O_BINARY;
296 *open_flags &= ~O_ACCMODE;
297 if (bdrv_flags & BDRV_O_RDWR) {
298 *open_flags |= O_RDWR;
299 } else {
300 *open_flags |= O_RDONLY;
303 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
304 * and O_DIRECT for no caching. */
305 if ((bdrv_flags & BDRV_O_NOCACHE)) {
306 *open_flags |= O_DIRECT;
310 #ifdef CONFIG_LINUX_AIO
311 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
313 int ret = -1;
314 assert(aio_ctx != NULL);
315 assert(use_aio != NULL);
317 * Currently Linux do AIO only for files opened with O_DIRECT
318 * specified so check NOCACHE flag too
320 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
321 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
323 /* if non-NULL, laio_init() has already been run */
324 if (*aio_ctx == NULL) {
325 *aio_ctx = laio_init();
326 if (!*aio_ctx) {
327 goto error;
330 *use_aio = 1;
331 } else {
332 *use_aio = 0;
335 ret = 0;
337 error:
338 return ret;
340 #endif
342 static void raw_parse_filename(const char *filename, QDict *options,
343 Error **errp)
345 /* The filename does not have to be prefixed by the protocol name, since
346 * "file" is the default protocol; therefore, the return value of this
347 * function call can be ignored. */
348 strstart(filename, "file:", &filename);
350 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
353 static QemuOptsList raw_runtime_opts = {
354 .name = "raw",
355 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
356 .desc = {
358 .name = "filename",
359 .type = QEMU_OPT_STRING,
360 .help = "File name of the image",
362 { /* end of list */ }
366 static int raw_open_common(BlockDriverState *bs, QDict *options,
367 int bdrv_flags, int open_flags, Error **errp)
369 BDRVRawState *s = bs->opaque;
370 QemuOpts *opts;
371 Error *local_err = NULL;
372 const char *filename = NULL;
373 int fd, ret;
374 struct stat st;
376 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
377 qemu_opts_absorb_qdict(opts, options, &local_err);
378 if (local_err) {
379 error_propagate(errp, local_err);
380 ret = -EINVAL;
381 goto fail;
384 filename = qemu_opt_get(opts, "filename");
386 ret = raw_normalize_devicepath(&filename);
387 if (ret != 0) {
388 error_setg_errno(errp, -ret, "Could not normalize device path");
389 goto fail;
392 s->open_flags = open_flags;
393 raw_parse_flags(bdrv_flags, &s->open_flags);
395 s->fd = -1;
396 fd = qemu_open(filename, s->open_flags, 0644);
397 if (fd < 0) {
398 ret = -errno;
399 if (ret == -EROFS) {
400 ret = -EACCES;
402 goto fail;
404 s->fd = fd;
406 #ifdef CONFIG_LINUX_AIO
407 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
408 qemu_close(fd);
409 ret = -errno;
410 error_setg_errno(errp, -ret, "Could not set AIO state");
411 goto fail;
413 #endif
415 s->has_discard = true;
416 s->has_write_zeroes = true;
418 if (fstat(s->fd, &st) < 0) {
419 error_setg_errno(errp, errno, "Could not stat file");
420 goto fail;
422 if (S_ISREG(st.st_mode)) {
423 s->discard_zeroes = true;
425 if (S_ISBLK(st.st_mode)) {
426 #ifdef BLKDISCARDZEROES
427 unsigned int arg;
428 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
429 s->discard_zeroes = true;
431 #endif
432 #ifdef __linux__
433 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
434 * not rely on the contents of discarded blocks unless using O_DIRECT.
435 * Same for BLKZEROOUT.
437 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
438 s->discard_zeroes = false;
439 s->has_write_zeroes = false;
441 #endif
444 #ifdef CONFIG_XFS
445 if (platform_test_xfs_fd(s->fd)) {
446 s->is_xfs = true;
448 #endif
450 ret = 0;
451 fail:
452 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
453 unlink(filename);
455 qemu_opts_del(opts);
456 return ret;
459 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
460 Error **errp)
462 BDRVRawState *s = bs->opaque;
463 Error *local_err = NULL;
464 int ret;
466 s->type = FTYPE_FILE;
467 ret = raw_open_common(bs, options, flags, 0, &local_err);
468 if (local_err) {
469 error_propagate(errp, local_err);
471 return ret;
474 static int raw_reopen_prepare(BDRVReopenState *state,
475 BlockReopenQueue *queue, Error **errp)
477 BDRVRawState *s;
478 BDRVRawReopenState *raw_s;
479 int ret = 0;
481 assert(state != NULL);
482 assert(state->bs != NULL);
484 s = state->bs->opaque;
486 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
487 raw_s = state->opaque;
489 #ifdef CONFIG_LINUX_AIO
490 raw_s->use_aio = s->use_aio;
492 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
493 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
494 * won't override aio_ctx if aio_ctx is non-NULL */
495 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
496 error_setg(errp, "Could not set AIO state");
497 return -1;
499 #endif
501 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
502 raw_s->open_flags |= O_NONBLOCK;
505 raw_parse_flags(state->flags, &raw_s->open_flags);
507 raw_s->fd = -1;
509 int fcntl_flags = O_APPEND | O_NONBLOCK;
510 #ifdef O_NOATIME
511 fcntl_flags |= O_NOATIME;
512 #endif
514 #ifdef O_ASYNC
515 /* Not all operating systems have O_ASYNC, and those that don't
516 * will not let us track the state into raw_s->open_flags (typically
517 * you achieve the same effect with an ioctl, for example I_SETSIG
518 * on Solaris). But we do not use O_ASYNC, so that's fine.
520 assert((s->open_flags & O_ASYNC) == 0);
521 #endif
523 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
524 /* dup the original fd */
525 /* TODO: use qemu fcntl wrapper */
526 #ifdef F_DUPFD_CLOEXEC
527 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
528 #else
529 raw_s->fd = dup(s->fd);
530 if (raw_s->fd != -1) {
531 qemu_set_cloexec(raw_s->fd);
533 #endif
534 if (raw_s->fd >= 0) {
535 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
536 if (ret) {
537 qemu_close(raw_s->fd);
538 raw_s->fd = -1;
543 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
544 if (raw_s->fd == -1) {
545 assert(!(raw_s->open_flags & O_CREAT));
546 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
547 if (raw_s->fd == -1) {
548 error_setg_errno(errp, errno, "Could not reopen file");
549 ret = -1;
552 return ret;
555 static void raw_reopen_commit(BDRVReopenState *state)
557 BDRVRawReopenState *raw_s = state->opaque;
558 BDRVRawState *s = state->bs->opaque;
560 s->open_flags = raw_s->open_flags;
562 qemu_close(s->fd);
563 s->fd = raw_s->fd;
564 #ifdef CONFIG_LINUX_AIO
565 s->use_aio = raw_s->use_aio;
566 #endif
568 g_free(state->opaque);
569 state->opaque = NULL;
573 static void raw_reopen_abort(BDRVReopenState *state)
575 BDRVRawReopenState *raw_s = state->opaque;
577 /* nothing to do if NULL, we didn't get far enough */
578 if (raw_s == NULL) {
579 return;
582 if (raw_s->fd >= 0) {
583 qemu_close(raw_s->fd);
584 raw_s->fd = -1;
586 g_free(state->opaque);
587 state->opaque = NULL;
590 static int raw_refresh_limits(BlockDriverState *bs)
592 BDRVRawState *s = bs->opaque;
594 raw_probe_alignment(bs);
595 bs->bl.opt_mem_alignment = s->buf_align;
597 return 0;
600 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
602 int ret;
604 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
605 if (ret == -1) {
606 return -errno;
609 return 0;
612 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
614 int ret;
616 ret = qemu_fdatasync(aiocb->aio_fildes);
617 if (ret == -1) {
618 return -errno;
620 return 0;
623 #ifdef CONFIG_PREADV
625 static bool preadv_present = true;
627 static ssize_t
628 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
630 return preadv(fd, iov, nr_iov, offset);
633 static ssize_t
634 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
636 return pwritev(fd, iov, nr_iov, offset);
639 #else
641 static bool preadv_present = false;
643 static ssize_t
644 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
646 return -ENOSYS;
649 static ssize_t
650 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
652 return -ENOSYS;
655 #endif
657 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
659 ssize_t len;
661 do {
662 if (aiocb->aio_type & QEMU_AIO_WRITE)
663 len = qemu_pwritev(aiocb->aio_fildes,
664 aiocb->aio_iov,
665 aiocb->aio_niov,
666 aiocb->aio_offset);
667 else
668 len = qemu_preadv(aiocb->aio_fildes,
669 aiocb->aio_iov,
670 aiocb->aio_niov,
671 aiocb->aio_offset);
672 } while (len == -1 && errno == EINTR);
674 if (len == -1) {
675 return -errno;
677 return len;
681 * Read/writes the data to/from a given linear buffer.
683 * Returns the number of bytes handles or -errno in case of an error. Short
684 * reads are only returned if the end of the file is reached.
686 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
688 ssize_t offset = 0;
689 ssize_t len;
691 while (offset < aiocb->aio_nbytes) {
692 if (aiocb->aio_type & QEMU_AIO_WRITE) {
693 len = pwrite(aiocb->aio_fildes,
694 (const char *)buf + offset,
695 aiocb->aio_nbytes - offset,
696 aiocb->aio_offset + offset);
697 } else {
698 len = pread(aiocb->aio_fildes,
699 buf + offset,
700 aiocb->aio_nbytes - offset,
701 aiocb->aio_offset + offset);
703 if (len == -1 && errno == EINTR) {
704 continue;
705 } else if (len == -1) {
706 offset = -errno;
707 break;
708 } else if (len == 0) {
709 break;
711 offset += len;
714 return offset;
717 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
719 ssize_t nbytes;
720 char *buf;
722 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
724 * If there is just a single buffer, and it is properly aligned
725 * we can just use plain pread/pwrite without any problems.
727 if (aiocb->aio_niov == 1) {
728 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
731 * We have more than one iovec, and all are properly aligned.
733 * Try preadv/pwritev first and fall back to linearizing the
734 * buffer if it's not supported.
736 if (preadv_present) {
737 nbytes = handle_aiocb_rw_vector(aiocb);
738 if (nbytes == aiocb->aio_nbytes ||
739 (nbytes < 0 && nbytes != -ENOSYS)) {
740 return nbytes;
742 preadv_present = false;
746 * XXX(hch): short read/write. no easy way to handle the reminder
747 * using these interfaces. For now retry using plain
748 * pread/pwrite?
753 * Ok, we have to do it the hard way, copy all segments into
754 * a single aligned buffer.
756 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
757 if (aiocb->aio_type & QEMU_AIO_WRITE) {
758 char *p = buf;
759 int i;
761 for (i = 0; i < aiocb->aio_niov; ++i) {
762 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
763 p += aiocb->aio_iov[i].iov_len;
767 nbytes = handle_aiocb_rw_linear(aiocb, buf);
768 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
769 char *p = buf;
770 size_t count = aiocb->aio_nbytes, copy;
771 int i;
773 for (i = 0; i < aiocb->aio_niov && count; ++i) {
774 copy = count;
775 if (copy > aiocb->aio_iov[i].iov_len) {
776 copy = aiocb->aio_iov[i].iov_len;
778 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
779 p += copy;
780 count -= copy;
783 qemu_vfree(buf);
785 return nbytes;
788 #ifdef CONFIG_XFS
789 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
791 struct xfs_flock64 fl;
793 memset(&fl, 0, sizeof(fl));
794 fl.l_whence = SEEK_SET;
795 fl.l_start = offset;
796 fl.l_len = bytes;
798 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
799 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
800 return -errno;
803 return 0;
806 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
808 struct xfs_flock64 fl;
810 memset(&fl, 0, sizeof(fl));
811 fl.l_whence = SEEK_SET;
812 fl.l_start = offset;
813 fl.l_len = bytes;
815 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
816 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
817 return -errno;
820 return 0;
822 #endif
824 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
826 int ret = -EOPNOTSUPP;
827 BDRVRawState *s = aiocb->bs->opaque;
829 if (s->has_write_zeroes == 0) {
830 return -ENOTSUP;
833 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
834 #ifdef BLKZEROOUT
835 do {
836 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
837 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
838 return 0;
840 } while (errno == EINTR);
842 ret = -errno;
843 #endif
844 } else {
845 #ifdef CONFIG_XFS
846 if (s->is_xfs) {
847 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
849 #endif
852 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
853 ret == -ENOTTY) {
854 s->has_write_zeroes = false;
855 ret = -ENOTSUP;
857 return ret;
860 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
862 int ret = -EOPNOTSUPP;
863 BDRVRawState *s = aiocb->bs->opaque;
865 if (!s->has_discard) {
866 return -ENOTSUP;
869 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
870 #ifdef BLKDISCARD
871 do {
872 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
873 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
874 return 0;
876 } while (errno == EINTR);
878 ret = -errno;
879 #endif
880 } else {
881 #ifdef CONFIG_XFS
882 if (s->is_xfs) {
883 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
885 #endif
887 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
888 do {
889 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
890 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
891 return 0;
893 } while (errno == EINTR);
895 ret = -errno;
896 #endif
899 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
900 ret == -ENOTTY) {
901 s->has_discard = false;
902 ret = -ENOTSUP;
904 return ret;
907 static int aio_worker(void *arg)
909 RawPosixAIOData *aiocb = arg;
910 ssize_t ret = 0;
912 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
913 case QEMU_AIO_READ:
914 ret = handle_aiocb_rw(aiocb);
915 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
916 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
917 0, aiocb->aio_nbytes - ret);
919 ret = aiocb->aio_nbytes;
921 if (ret == aiocb->aio_nbytes) {
922 ret = 0;
923 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
924 ret = -EINVAL;
926 break;
927 case QEMU_AIO_WRITE:
928 ret = handle_aiocb_rw(aiocb);
929 if (ret == aiocb->aio_nbytes) {
930 ret = 0;
931 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
932 ret = -EINVAL;
934 break;
935 case QEMU_AIO_FLUSH:
936 ret = handle_aiocb_flush(aiocb);
937 break;
938 case QEMU_AIO_IOCTL:
939 ret = handle_aiocb_ioctl(aiocb);
940 break;
941 case QEMU_AIO_DISCARD:
942 ret = handle_aiocb_discard(aiocb);
943 break;
944 case QEMU_AIO_WRITE_ZEROES:
945 ret = handle_aiocb_write_zeroes(aiocb);
946 break;
947 default:
948 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
949 ret = -EINVAL;
950 break;
953 g_slice_free(RawPosixAIOData, aiocb);
954 return ret;
957 static int paio_submit_co(BlockDriverState *bs, int fd,
958 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
959 int type)
961 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
962 ThreadPool *pool;
964 acb->bs = bs;
965 acb->aio_type = type;
966 acb->aio_fildes = fd;
968 if (qiov) {
969 acb->aio_iov = qiov->iov;
970 acb->aio_niov = qiov->niov;
972 acb->aio_nbytes = nb_sectors * 512;
973 acb->aio_offset = sector_num * 512;
975 trace_paio_submit_co(sector_num, nb_sectors, type);
976 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
977 return thread_pool_submit_co(pool, aio_worker, acb);
980 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
981 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
982 BlockDriverCompletionFunc *cb, void *opaque, int type)
984 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
985 ThreadPool *pool;
987 acb->bs = bs;
988 acb->aio_type = type;
989 acb->aio_fildes = fd;
991 if (qiov) {
992 acb->aio_iov = qiov->iov;
993 acb->aio_niov = qiov->niov;
995 acb->aio_nbytes = nb_sectors * 512;
996 acb->aio_offset = sector_num * 512;
998 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
999 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1000 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1003 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
1004 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1005 BlockDriverCompletionFunc *cb, void *opaque, int type)
1007 BDRVRawState *s = bs->opaque;
1009 if (fd_open(bs) < 0)
1010 return NULL;
1013 * If O_DIRECT is used the buffer needs to be aligned on a sector
1014 * boundary. Check if this is the case or tell the low-level
1015 * driver that it needs to copy the buffer.
1017 if ((bs->open_flags & BDRV_O_NOCACHE)) {
1018 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1019 type |= QEMU_AIO_MISALIGNED;
1020 #ifdef CONFIG_LINUX_AIO
1021 } else if (s->use_aio) {
1022 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1023 nb_sectors, cb, opaque, type);
1024 #endif
1028 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1029 cb, opaque, type);
1032 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
1033 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1034 BlockDriverCompletionFunc *cb, void *opaque)
1036 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1037 cb, opaque, QEMU_AIO_READ);
1040 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
1041 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1042 BlockDriverCompletionFunc *cb, void *opaque)
1044 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1045 cb, opaque, QEMU_AIO_WRITE);
1048 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
1049 BlockDriverCompletionFunc *cb, void *opaque)
1051 BDRVRawState *s = bs->opaque;
1053 if (fd_open(bs) < 0)
1054 return NULL;
1056 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1059 static void raw_close(BlockDriverState *bs)
1061 BDRVRawState *s = bs->opaque;
1062 if (s->fd >= 0) {
1063 qemu_close(s->fd);
1064 s->fd = -1;
1068 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1070 BDRVRawState *s = bs->opaque;
1071 struct stat st;
1073 if (fstat(s->fd, &st)) {
1074 return -errno;
1077 if (S_ISREG(st.st_mode)) {
1078 if (ftruncate(s->fd, offset) < 0) {
1079 return -errno;
1081 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1082 if (offset > raw_getlength(bs)) {
1083 return -EINVAL;
1085 } else {
1086 return -ENOTSUP;
1089 return 0;
1092 #ifdef __OpenBSD__
1093 static int64_t raw_getlength(BlockDriverState *bs)
1095 BDRVRawState *s = bs->opaque;
1096 int fd = s->fd;
1097 struct stat st;
1099 if (fstat(fd, &st))
1100 return -1;
1101 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1102 struct disklabel dl;
1104 if (ioctl(fd, DIOCGDINFO, &dl))
1105 return -1;
1106 return (uint64_t)dl.d_secsize *
1107 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1108 } else
1109 return st.st_size;
1111 #elif defined(__NetBSD__)
1112 static int64_t raw_getlength(BlockDriverState *bs)
1114 BDRVRawState *s = bs->opaque;
1115 int fd = s->fd;
1116 struct stat st;
1118 if (fstat(fd, &st))
1119 return -1;
1120 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1121 struct dkwedge_info dkw;
1123 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1124 return dkw.dkw_size * 512;
1125 } else {
1126 struct disklabel dl;
1128 if (ioctl(fd, DIOCGDINFO, &dl))
1129 return -1;
1130 return (uint64_t)dl.d_secsize *
1131 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1133 } else
1134 return st.st_size;
1136 #elif defined(__sun__)
1137 static int64_t raw_getlength(BlockDriverState *bs)
1139 BDRVRawState *s = bs->opaque;
1140 struct dk_minfo minfo;
1141 int ret;
1143 ret = fd_open(bs);
1144 if (ret < 0) {
1145 return ret;
1149 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1151 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1152 if (ret != -1) {
1153 return minfo.dki_lbsize * minfo.dki_capacity;
1157 * There are reports that lseek on some devices fails, but
1158 * irc discussion said that contingency on contingency was overkill.
1160 return lseek(s->fd, 0, SEEK_END);
1162 #elif defined(CONFIG_BSD)
1163 static int64_t raw_getlength(BlockDriverState *bs)
1165 BDRVRawState *s = bs->opaque;
1166 int fd = s->fd;
1167 int64_t size;
1168 struct stat sb;
1169 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1170 int reopened = 0;
1171 #endif
1172 int ret;
1174 ret = fd_open(bs);
1175 if (ret < 0)
1176 return ret;
1178 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1179 again:
1180 #endif
1181 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1182 #ifdef DIOCGMEDIASIZE
1183 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1184 #elif defined(DIOCGPART)
1186 struct partinfo pi;
1187 if (ioctl(fd, DIOCGPART, &pi) == 0)
1188 size = pi.media_size;
1189 else
1190 size = 0;
1192 if (size == 0)
1193 #endif
1194 #if defined(__APPLE__) && defined(__MACH__)
1195 size = LONG_LONG_MAX;
1196 #else
1197 size = lseek(fd, 0LL, SEEK_END);
1198 #endif
1199 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1200 switch(s->type) {
1201 case FTYPE_CD:
1202 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1203 if (size == 2048LL * (unsigned)-1)
1204 size = 0;
1205 /* XXX no disc? maybe we need to reopen... */
1206 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1207 reopened = 1;
1208 goto again;
1211 #endif
1212 } else {
1213 size = lseek(fd, 0, SEEK_END);
1215 return size;
1217 #else
1218 static int64_t raw_getlength(BlockDriverState *bs)
1220 BDRVRawState *s = bs->opaque;
1221 int ret;
1223 ret = fd_open(bs);
1224 if (ret < 0) {
1225 return ret;
1228 return lseek(s->fd, 0, SEEK_END);
1230 #endif
1232 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1234 struct stat st;
1235 BDRVRawState *s = bs->opaque;
1237 if (fstat(s->fd, &st) < 0) {
1238 return -errno;
1240 return (int64_t)st.st_blocks * 512;
1243 static int raw_create(const char *filename, QEMUOptionParameter *options,
1244 Error **errp)
1246 int fd;
1247 int result = 0;
1248 int64_t total_size = 0;
1250 strstart(filename, "file:", &filename);
1252 /* Read out options */
1253 while (options && options->name) {
1254 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1255 total_size = options->value.n / BDRV_SECTOR_SIZE;
1257 options++;
1260 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1261 0644);
1262 if (fd < 0) {
1263 result = -errno;
1264 error_setg_errno(errp, -result, "Could not create file");
1265 } else {
1266 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
1267 result = -errno;
1268 error_setg_errno(errp, -result, "Could not resize file");
1270 if (qemu_close(fd) != 0) {
1271 result = -errno;
1272 error_setg_errno(errp, -result, "Could not close the new file");
1275 return result;
1278 static int64_t try_fiemap(BlockDriverState *bs, off_t start, off_t *data,
1279 off_t *hole, int nb_sectors, int *pnum)
1281 #ifdef CONFIG_FIEMAP
1282 BDRVRawState *s = bs->opaque;
1283 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1284 struct {
1285 struct fiemap fm;
1286 struct fiemap_extent fe;
1287 } f;
1289 if (s->skip_fiemap) {
1290 return -ENOTSUP;
1293 f.fm.fm_start = start;
1294 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1295 f.fm.fm_flags = 0;
1296 f.fm.fm_extent_count = 1;
1297 f.fm.fm_reserved = 0;
1298 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1299 s->skip_fiemap = true;
1300 return -errno;
1303 if (f.fm.fm_mapped_extents == 0) {
1304 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1305 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1307 off_t length = lseek(s->fd, 0, SEEK_END);
1308 *hole = f.fm.fm_start;
1309 *data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1310 } else {
1311 *data = f.fe.fe_logical;
1312 *hole = f.fe.fe_logical + f.fe.fe_length;
1313 if (f.fe.fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
1314 ret |= BDRV_BLOCK_ZERO;
1318 return ret;
1319 #else
1320 return -ENOTSUP;
1321 #endif
1324 static int64_t try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,
1325 off_t *hole, int *pnum)
1327 #if defined SEEK_HOLE && defined SEEK_DATA
1328 BDRVRawState *s = bs->opaque;
1330 *hole = lseek(s->fd, start, SEEK_HOLE);
1331 if (*hole == -1) {
1332 /* -ENXIO indicates that sector_num was past the end of the file.
1333 * There is a virtual hole there. */
1334 assert(errno != -ENXIO);
1336 return -errno;
1339 if (*hole > start) {
1340 *data = start;
1341 } else {
1342 /* On a hole. We need another syscall to find its end. */
1343 *data = lseek(s->fd, start, SEEK_DATA);
1344 if (*data == -1) {
1345 *data = lseek(s->fd, 0, SEEK_END);
1349 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1350 #else
1351 return -ENOTSUP;
1352 #endif
1356 * Returns true iff the specified sector is present in the disk image. Drivers
1357 * not implementing the functionality are assumed to not support backing files,
1358 * hence all their sectors are reported as allocated.
1360 * If 'sector_num' is beyond the end of the disk image the return value is 0
1361 * and 'pnum' is set to 0.
1363 * 'pnum' is set to the number of sectors (including and immediately following
1364 * the specified sector) that are known to be in the same
1365 * allocated/unallocated state.
1367 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1368 * beyond the end of the disk image it will be clamped.
1370 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1371 int64_t sector_num,
1372 int nb_sectors, int *pnum)
1374 off_t start, data = 0, hole = 0;
1375 int64_t ret;
1377 ret = fd_open(bs);
1378 if (ret < 0) {
1379 return ret;
1382 start = sector_num * BDRV_SECTOR_SIZE;
1384 ret = try_fiemap(bs, start, &data, &hole, nb_sectors, pnum);
1385 if (ret < 0) {
1386 ret = try_seek_hole(bs, start, &data, &hole, pnum);
1387 if (ret < 0) {
1388 /* Assume everything is allocated. */
1389 data = 0;
1390 hole = start + nb_sectors * BDRV_SECTOR_SIZE;
1391 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1395 if (data <= start) {
1396 /* On a data extent, compute sectors to the end of the extent. */
1397 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1398 } else {
1399 /* On a hole, compute sectors to the beginning of the next extent. */
1400 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1401 ret &= ~BDRV_BLOCK_DATA;
1402 ret |= BDRV_BLOCK_ZERO;
1405 return ret;
1408 static coroutine_fn BlockDriverAIOCB *raw_aio_discard(BlockDriverState *bs,
1409 int64_t sector_num, int nb_sectors,
1410 BlockDriverCompletionFunc *cb, void *opaque)
1412 BDRVRawState *s = bs->opaque;
1414 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1415 cb, opaque, QEMU_AIO_DISCARD);
1418 static int coroutine_fn raw_co_write_zeroes(
1419 BlockDriverState *bs, int64_t sector_num,
1420 int nb_sectors, BdrvRequestFlags flags)
1422 BDRVRawState *s = bs->opaque;
1424 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1425 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1426 QEMU_AIO_WRITE_ZEROES);
1427 } else if (s->discard_zeroes) {
1428 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1429 QEMU_AIO_DISCARD);
1431 return -ENOTSUP;
1434 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1436 BDRVRawState *s = bs->opaque;
1438 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1439 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1440 return 0;
1443 static QEMUOptionParameter raw_create_options[] = {
1445 .name = BLOCK_OPT_SIZE,
1446 .type = OPT_SIZE,
1447 .help = "Virtual disk size"
1449 { NULL }
1452 static BlockDriver bdrv_file = {
1453 .format_name = "file",
1454 .protocol_name = "file",
1455 .instance_size = sizeof(BDRVRawState),
1456 .bdrv_needs_filename = true,
1457 .bdrv_probe = NULL, /* no probe for protocols */
1458 .bdrv_parse_filename = raw_parse_filename,
1459 .bdrv_file_open = raw_open,
1460 .bdrv_reopen_prepare = raw_reopen_prepare,
1461 .bdrv_reopen_commit = raw_reopen_commit,
1462 .bdrv_reopen_abort = raw_reopen_abort,
1463 .bdrv_close = raw_close,
1464 .bdrv_create = raw_create,
1465 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1466 .bdrv_co_get_block_status = raw_co_get_block_status,
1467 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1469 .bdrv_aio_readv = raw_aio_readv,
1470 .bdrv_aio_writev = raw_aio_writev,
1471 .bdrv_aio_flush = raw_aio_flush,
1472 .bdrv_aio_discard = raw_aio_discard,
1473 .bdrv_refresh_limits = raw_refresh_limits,
1475 .bdrv_truncate = raw_truncate,
1476 .bdrv_getlength = raw_getlength,
1477 .bdrv_get_info = raw_get_info,
1478 .bdrv_get_allocated_file_size
1479 = raw_get_allocated_file_size,
1481 .create_options = raw_create_options,
1484 /***********************************************/
1485 /* host device */
1487 #if defined(__APPLE__) && defined(__MACH__)
1488 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1489 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1491 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1493 kern_return_t kernResult;
1494 mach_port_t masterPort;
1495 CFMutableDictionaryRef classesToMatch;
1497 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1498 if ( KERN_SUCCESS != kernResult ) {
1499 printf( "IOMasterPort returned %d\n", kernResult );
1502 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1503 if ( classesToMatch == NULL ) {
1504 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1505 } else {
1506 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1508 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1509 if ( KERN_SUCCESS != kernResult )
1511 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1514 return kernResult;
1517 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1519 io_object_t nextMedia;
1520 kern_return_t kernResult = KERN_FAILURE;
1521 *bsdPath = '\0';
1522 nextMedia = IOIteratorNext( mediaIterator );
1523 if ( nextMedia )
1525 CFTypeRef bsdPathAsCFString;
1526 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1527 if ( bsdPathAsCFString ) {
1528 size_t devPathLength;
1529 strcpy( bsdPath, _PATH_DEV );
1530 strcat( bsdPath, "r" );
1531 devPathLength = strlen( bsdPath );
1532 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1533 kernResult = KERN_SUCCESS;
1535 CFRelease( bsdPathAsCFString );
1537 IOObjectRelease( nextMedia );
1540 return kernResult;
1543 #endif
1545 static int hdev_probe_device(const char *filename)
1547 struct stat st;
1549 /* allow a dedicated CD-ROM driver to match with a higher priority */
1550 if (strstart(filename, "/dev/cdrom", NULL))
1551 return 50;
1553 if (stat(filename, &st) >= 0 &&
1554 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1555 return 100;
1558 return 0;
1561 static int check_hdev_writable(BDRVRawState *s)
1563 #if defined(BLKROGET)
1564 /* Linux block devices can be configured "read-only" using blockdev(8).
1565 * This is independent of device node permissions and therefore open(2)
1566 * with O_RDWR succeeds. Actual writes fail with EPERM.
1568 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1569 * check for read-only block devices so that Linux block devices behave
1570 * properly.
1572 struct stat st;
1573 int readonly = 0;
1575 if (fstat(s->fd, &st)) {
1576 return -errno;
1579 if (!S_ISBLK(st.st_mode)) {
1580 return 0;
1583 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1584 return -errno;
1587 if (readonly) {
1588 return -EACCES;
1590 #endif /* defined(BLKROGET) */
1591 return 0;
1594 static void hdev_parse_filename(const char *filename, QDict *options,
1595 Error **errp)
1597 /* The prefix is optional, just as for "file". */
1598 strstart(filename, "host_device:", &filename);
1600 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1603 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1604 Error **errp)
1606 BDRVRawState *s = bs->opaque;
1607 Error *local_err = NULL;
1608 int ret;
1609 const char *filename = qdict_get_str(options, "filename");
1611 #if defined(__APPLE__) && defined(__MACH__)
1612 if (strstart(filename, "/dev/cdrom", NULL)) {
1613 kern_return_t kernResult;
1614 io_iterator_t mediaIterator;
1615 char bsdPath[ MAXPATHLEN ];
1616 int fd;
1618 kernResult = FindEjectableCDMedia( &mediaIterator );
1619 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1621 if ( bsdPath[ 0 ] != '\0' ) {
1622 strcat(bsdPath,"s0");
1623 /* some CDs don't have a partition 0 */
1624 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1625 if (fd < 0) {
1626 bsdPath[strlen(bsdPath)-1] = '1';
1627 } else {
1628 qemu_close(fd);
1630 filename = bsdPath;
1631 qdict_put(options, "filename", qstring_from_str(filename));
1634 if ( mediaIterator )
1635 IOObjectRelease( mediaIterator );
1637 #endif
1639 s->type = FTYPE_FILE;
1640 #if defined(__linux__)
1642 char resolved_path[ MAXPATHLEN ], *temp;
1644 temp = realpath(filename, resolved_path);
1645 if (temp && strstart(temp, "/dev/sg", NULL)) {
1646 bs->sg = 1;
1649 #endif
1651 ret = raw_open_common(bs, options, flags, 0, &local_err);
1652 if (ret < 0) {
1653 if (local_err) {
1654 error_propagate(errp, local_err);
1656 return ret;
1659 if (flags & BDRV_O_RDWR) {
1660 ret = check_hdev_writable(s);
1661 if (ret < 0) {
1662 raw_close(bs);
1663 error_setg_errno(errp, -ret, "The device is not writable");
1664 return ret;
1668 return ret;
1671 #if defined(__linux__)
1672 /* Note: we do not have a reliable method to detect if the floppy is
1673 present. The current method is to try to open the floppy at every
1674 I/O and to keep it opened during a few hundreds of ms. */
1675 static int fd_open(BlockDriverState *bs)
1677 BDRVRawState *s = bs->opaque;
1678 int last_media_present;
1680 if (s->type != FTYPE_FD)
1681 return 0;
1682 last_media_present = (s->fd >= 0);
1683 if (s->fd >= 0 &&
1684 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1685 qemu_close(s->fd);
1686 s->fd = -1;
1687 #ifdef DEBUG_FLOPPY
1688 printf("Floppy closed\n");
1689 #endif
1691 if (s->fd < 0) {
1692 if (s->fd_got_error &&
1693 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1694 #ifdef DEBUG_FLOPPY
1695 printf("No floppy (open delayed)\n");
1696 #endif
1697 return -EIO;
1699 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1700 if (s->fd < 0) {
1701 s->fd_error_time = get_clock();
1702 s->fd_got_error = 1;
1703 if (last_media_present)
1704 s->fd_media_changed = 1;
1705 #ifdef DEBUG_FLOPPY
1706 printf("No floppy\n");
1707 #endif
1708 return -EIO;
1710 #ifdef DEBUG_FLOPPY
1711 printf("Floppy opened\n");
1712 #endif
1714 if (!last_media_present)
1715 s->fd_media_changed = 1;
1716 s->fd_open_time = get_clock();
1717 s->fd_got_error = 0;
1718 return 0;
1721 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1723 BDRVRawState *s = bs->opaque;
1725 return ioctl(s->fd, req, buf);
1728 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1729 unsigned long int req, void *buf,
1730 BlockDriverCompletionFunc *cb, void *opaque)
1732 BDRVRawState *s = bs->opaque;
1733 RawPosixAIOData *acb;
1734 ThreadPool *pool;
1736 if (fd_open(bs) < 0)
1737 return NULL;
1739 acb = g_slice_new(RawPosixAIOData);
1740 acb->bs = bs;
1741 acb->aio_type = QEMU_AIO_IOCTL;
1742 acb->aio_fildes = s->fd;
1743 acb->aio_offset = 0;
1744 acb->aio_ioctl_buf = buf;
1745 acb->aio_ioctl_cmd = req;
1746 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1747 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1750 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1751 static int fd_open(BlockDriverState *bs)
1753 BDRVRawState *s = bs->opaque;
1755 /* this is just to ensure s->fd is sane (its called by io ops) */
1756 if (s->fd >= 0)
1757 return 0;
1758 return -EIO;
1760 #else /* !linux && !FreeBSD */
1762 static int fd_open(BlockDriverState *bs)
1764 return 0;
1767 #endif /* !linux && !FreeBSD */
1769 static coroutine_fn BlockDriverAIOCB *hdev_aio_discard(BlockDriverState *bs,
1770 int64_t sector_num, int nb_sectors,
1771 BlockDriverCompletionFunc *cb, void *opaque)
1773 BDRVRawState *s = bs->opaque;
1775 if (fd_open(bs) < 0) {
1776 return NULL;
1778 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1779 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1782 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
1783 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1785 BDRVRawState *s = bs->opaque;
1786 int rc;
1788 rc = fd_open(bs);
1789 if (rc < 0) {
1790 return rc;
1792 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1793 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1794 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
1795 } else if (s->discard_zeroes) {
1796 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1797 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1799 return -ENOTSUP;
1802 static int hdev_create(const char *filename, QEMUOptionParameter *options,
1803 Error **errp)
1805 int fd;
1806 int ret = 0;
1807 struct stat stat_buf;
1808 int64_t total_size = 0;
1809 bool has_prefix;
1811 /* This function is used by all three protocol block drivers and therefore
1812 * any of these three prefixes may be given.
1813 * The return value has to be stored somewhere, otherwise this is an error
1814 * due to -Werror=unused-value. */
1815 has_prefix =
1816 strstart(filename, "host_device:", &filename) ||
1817 strstart(filename, "host_cdrom:" , &filename) ||
1818 strstart(filename, "host_floppy:", &filename);
1820 (void)has_prefix;
1822 /* Read out options */
1823 while (options && options->name) {
1824 if (!strcmp(options->name, "size")) {
1825 total_size = options->value.n / BDRV_SECTOR_SIZE;
1827 options++;
1830 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1831 if (fd < 0) {
1832 ret = -errno;
1833 error_setg_errno(errp, -ret, "Could not open device");
1834 return ret;
1837 if (fstat(fd, &stat_buf) < 0) {
1838 ret = -errno;
1839 error_setg_errno(errp, -ret, "Could not stat device");
1840 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
1841 error_setg(errp,
1842 "The given file is neither a block nor a character device");
1843 ret = -ENODEV;
1844 } else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE) {
1845 error_setg(errp, "Device is too small");
1846 ret = -ENOSPC;
1849 qemu_close(fd);
1850 return ret;
1853 static BlockDriver bdrv_host_device = {
1854 .format_name = "host_device",
1855 .protocol_name = "host_device",
1856 .instance_size = sizeof(BDRVRawState),
1857 .bdrv_needs_filename = true,
1858 .bdrv_probe_device = hdev_probe_device,
1859 .bdrv_parse_filename = hdev_parse_filename,
1860 .bdrv_file_open = hdev_open,
1861 .bdrv_close = raw_close,
1862 .bdrv_reopen_prepare = raw_reopen_prepare,
1863 .bdrv_reopen_commit = raw_reopen_commit,
1864 .bdrv_reopen_abort = raw_reopen_abort,
1865 .bdrv_create = hdev_create,
1866 .create_options = raw_create_options,
1867 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
1869 .bdrv_aio_readv = raw_aio_readv,
1870 .bdrv_aio_writev = raw_aio_writev,
1871 .bdrv_aio_flush = raw_aio_flush,
1872 .bdrv_aio_discard = hdev_aio_discard,
1873 .bdrv_refresh_limits = raw_refresh_limits,
1875 .bdrv_truncate = raw_truncate,
1876 .bdrv_getlength = raw_getlength,
1877 .bdrv_get_info = raw_get_info,
1878 .bdrv_get_allocated_file_size
1879 = raw_get_allocated_file_size,
1881 /* generic scsi device */
1882 #ifdef __linux__
1883 .bdrv_ioctl = hdev_ioctl,
1884 .bdrv_aio_ioctl = hdev_aio_ioctl,
1885 #endif
1888 #ifdef __linux__
1889 static void floppy_parse_filename(const char *filename, QDict *options,
1890 Error **errp)
1892 /* The prefix is optional, just as for "file". */
1893 strstart(filename, "host_floppy:", &filename);
1895 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1898 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
1899 Error **errp)
1901 BDRVRawState *s = bs->opaque;
1902 Error *local_err = NULL;
1903 int ret;
1905 s->type = FTYPE_FD;
1907 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1908 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
1909 if (ret) {
1910 if (local_err) {
1911 error_propagate(errp, local_err);
1913 return ret;
1916 /* close fd so that we can reopen it as needed */
1917 qemu_close(s->fd);
1918 s->fd = -1;
1919 s->fd_media_changed = 1;
1921 return 0;
1924 static int floppy_probe_device(const char *filename)
1926 int fd, ret;
1927 int prio = 0;
1928 struct floppy_struct fdparam;
1929 struct stat st;
1931 if (strstart(filename, "/dev/fd", NULL) &&
1932 !strstart(filename, "/dev/fdset/", NULL)) {
1933 prio = 50;
1936 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1937 if (fd < 0) {
1938 goto out;
1940 ret = fstat(fd, &st);
1941 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1942 goto outc;
1945 /* Attempt to detect via a floppy specific ioctl */
1946 ret = ioctl(fd, FDGETPRM, &fdparam);
1947 if (ret >= 0)
1948 prio = 100;
1950 outc:
1951 qemu_close(fd);
1952 out:
1953 return prio;
1957 static int floppy_is_inserted(BlockDriverState *bs)
1959 return fd_open(bs) >= 0;
1962 static int floppy_media_changed(BlockDriverState *bs)
1964 BDRVRawState *s = bs->opaque;
1965 int ret;
1968 * XXX: we do not have a true media changed indication.
1969 * It does not work if the floppy is changed without trying to read it.
1971 fd_open(bs);
1972 ret = s->fd_media_changed;
1973 s->fd_media_changed = 0;
1974 #ifdef DEBUG_FLOPPY
1975 printf("Floppy changed=%d\n", ret);
1976 #endif
1977 return ret;
1980 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1982 BDRVRawState *s = bs->opaque;
1983 int fd;
1985 if (s->fd >= 0) {
1986 qemu_close(s->fd);
1987 s->fd = -1;
1989 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1990 if (fd >= 0) {
1991 if (ioctl(fd, FDEJECT, 0) < 0)
1992 perror("FDEJECT");
1993 qemu_close(fd);
1997 static BlockDriver bdrv_host_floppy = {
1998 .format_name = "host_floppy",
1999 .protocol_name = "host_floppy",
2000 .instance_size = sizeof(BDRVRawState),
2001 .bdrv_needs_filename = true,
2002 .bdrv_probe_device = floppy_probe_device,
2003 .bdrv_parse_filename = floppy_parse_filename,
2004 .bdrv_file_open = floppy_open,
2005 .bdrv_close = raw_close,
2006 .bdrv_reopen_prepare = raw_reopen_prepare,
2007 .bdrv_reopen_commit = raw_reopen_commit,
2008 .bdrv_reopen_abort = raw_reopen_abort,
2009 .bdrv_create = hdev_create,
2010 .create_options = raw_create_options,
2012 .bdrv_aio_readv = raw_aio_readv,
2013 .bdrv_aio_writev = raw_aio_writev,
2014 .bdrv_aio_flush = raw_aio_flush,
2015 .bdrv_refresh_limits = raw_refresh_limits,
2017 .bdrv_truncate = raw_truncate,
2018 .bdrv_getlength = raw_getlength,
2019 .has_variable_length = true,
2020 .bdrv_get_allocated_file_size
2021 = raw_get_allocated_file_size,
2023 /* removable device support */
2024 .bdrv_is_inserted = floppy_is_inserted,
2025 .bdrv_media_changed = floppy_media_changed,
2026 .bdrv_eject = floppy_eject,
2028 #endif
2030 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2031 static void cdrom_parse_filename(const char *filename, QDict *options,
2032 Error **errp)
2034 /* The prefix is optional, just as for "file". */
2035 strstart(filename, "host_cdrom:", &filename);
2037 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2039 #endif
2041 #ifdef __linux__
2042 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2043 Error **errp)
2045 BDRVRawState *s = bs->opaque;
2046 Error *local_err = NULL;
2047 int ret;
2049 s->type = FTYPE_CD;
2051 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2052 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2053 if (local_err) {
2054 error_propagate(errp, local_err);
2056 return ret;
2059 static int cdrom_probe_device(const char *filename)
2061 int fd, ret;
2062 int prio = 0;
2063 struct stat st;
2065 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2066 if (fd < 0) {
2067 goto out;
2069 ret = fstat(fd, &st);
2070 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2071 goto outc;
2074 /* Attempt to detect via a CDROM specific ioctl */
2075 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2076 if (ret >= 0)
2077 prio = 100;
2079 outc:
2080 qemu_close(fd);
2081 out:
2082 return prio;
2085 static int cdrom_is_inserted(BlockDriverState *bs)
2087 BDRVRawState *s = bs->opaque;
2088 int ret;
2090 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2091 if (ret == CDS_DISC_OK)
2092 return 1;
2093 return 0;
2096 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2098 BDRVRawState *s = bs->opaque;
2100 if (eject_flag) {
2101 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2102 perror("CDROMEJECT");
2103 } else {
2104 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2105 perror("CDROMEJECT");
2109 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2111 BDRVRawState *s = bs->opaque;
2113 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2115 * Note: an error can happen if the distribution automatically
2116 * mounts the CD-ROM
2118 /* perror("CDROM_LOCKDOOR"); */
2122 static BlockDriver bdrv_host_cdrom = {
2123 .format_name = "host_cdrom",
2124 .protocol_name = "host_cdrom",
2125 .instance_size = sizeof(BDRVRawState),
2126 .bdrv_needs_filename = true,
2127 .bdrv_probe_device = cdrom_probe_device,
2128 .bdrv_parse_filename = cdrom_parse_filename,
2129 .bdrv_file_open = cdrom_open,
2130 .bdrv_close = raw_close,
2131 .bdrv_reopen_prepare = raw_reopen_prepare,
2132 .bdrv_reopen_commit = raw_reopen_commit,
2133 .bdrv_reopen_abort = raw_reopen_abort,
2134 .bdrv_create = hdev_create,
2135 .create_options = raw_create_options,
2137 .bdrv_aio_readv = raw_aio_readv,
2138 .bdrv_aio_writev = raw_aio_writev,
2139 .bdrv_aio_flush = raw_aio_flush,
2140 .bdrv_refresh_limits = raw_refresh_limits,
2142 .bdrv_truncate = raw_truncate,
2143 .bdrv_getlength = raw_getlength,
2144 .has_variable_length = true,
2145 .bdrv_get_allocated_file_size
2146 = raw_get_allocated_file_size,
2148 /* removable device support */
2149 .bdrv_is_inserted = cdrom_is_inserted,
2150 .bdrv_eject = cdrom_eject,
2151 .bdrv_lock_medium = cdrom_lock_medium,
2153 /* generic scsi device */
2154 .bdrv_ioctl = hdev_ioctl,
2155 .bdrv_aio_ioctl = hdev_aio_ioctl,
2157 #endif /* __linux__ */
2159 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2160 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2161 Error **errp)
2163 BDRVRawState *s = bs->opaque;
2164 Error *local_err = NULL;
2165 int ret;
2167 s->type = FTYPE_CD;
2169 ret = raw_open_common(bs, options, flags, 0, &local_err);
2170 if (ret) {
2171 if (local_err) {
2172 error_propagate(errp, local_err);
2174 return ret;
2177 /* make sure the door isn't locked at this time */
2178 ioctl(s->fd, CDIOCALLOW);
2179 return 0;
2182 static int cdrom_probe_device(const char *filename)
2184 if (strstart(filename, "/dev/cd", NULL) ||
2185 strstart(filename, "/dev/acd", NULL))
2186 return 100;
2187 return 0;
2190 static int cdrom_reopen(BlockDriverState *bs)
2192 BDRVRawState *s = bs->opaque;
2193 int fd;
2196 * Force reread of possibly changed/newly loaded disc,
2197 * FreeBSD seems to not notice sometimes...
2199 if (s->fd >= 0)
2200 qemu_close(s->fd);
2201 fd = qemu_open(bs->filename, s->open_flags, 0644);
2202 if (fd < 0) {
2203 s->fd = -1;
2204 return -EIO;
2206 s->fd = fd;
2208 /* make sure the door isn't locked at this time */
2209 ioctl(s->fd, CDIOCALLOW);
2210 return 0;
2213 static int cdrom_is_inserted(BlockDriverState *bs)
2215 return raw_getlength(bs) > 0;
2218 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2220 BDRVRawState *s = bs->opaque;
2222 if (s->fd < 0)
2223 return;
2225 (void) ioctl(s->fd, CDIOCALLOW);
2227 if (eject_flag) {
2228 if (ioctl(s->fd, CDIOCEJECT) < 0)
2229 perror("CDIOCEJECT");
2230 } else {
2231 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2232 perror("CDIOCCLOSE");
2235 cdrom_reopen(bs);
2238 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2240 BDRVRawState *s = bs->opaque;
2242 if (s->fd < 0)
2243 return;
2244 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2246 * Note: an error can happen if the distribution automatically
2247 * mounts the CD-ROM
2249 /* perror("CDROM_LOCKDOOR"); */
2253 static BlockDriver bdrv_host_cdrom = {
2254 .format_name = "host_cdrom",
2255 .protocol_name = "host_cdrom",
2256 .instance_size = sizeof(BDRVRawState),
2257 .bdrv_needs_filename = true,
2258 .bdrv_probe_device = cdrom_probe_device,
2259 .bdrv_parse_filename = cdrom_parse_filename,
2260 .bdrv_file_open = cdrom_open,
2261 .bdrv_close = raw_close,
2262 .bdrv_reopen_prepare = raw_reopen_prepare,
2263 .bdrv_reopen_commit = raw_reopen_commit,
2264 .bdrv_reopen_abort = raw_reopen_abort,
2265 .bdrv_create = hdev_create,
2266 .create_options = raw_create_options,
2268 .bdrv_aio_readv = raw_aio_readv,
2269 .bdrv_aio_writev = raw_aio_writev,
2270 .bdrv_aio_flush = raw_aio_flush,
2271 .bdrv_refresh_limits = raw_refresh_limits,
2273 .bdrv_truncate = raw_truncate,
2274 .bdrv_getlength = raw_getlength,
2275 .has_variable_length = true,
2276 .bdrv_get_allocated_file_size
2277 = raw_get_allocated_file_size,
2279 /* removable device support */
2280 .bdrv_is_inserted = cdrom_is_inserted,
2281 .bdrv_eject = cdrom_eject,
2282 .bdrv_lock_medium = cdrom_lock_medium,
2284 #endif /* __FreeBSD__ */
2286 #ifdef CONFIG_LINUX_AIO
2288 * Return the file descriptor for Linux AIO
2290 * This function is a layering violation and should be removed when it becomes
2291 * possible to call the block layer outside the global mutex. It allows the
2292 * caller to hijack the file descriptor so I/O can be performed outside the
2293 * block layer.
2295 int raw_get_aio_fd(BlockDriverState *bs)
2297 BDRVRawState *s;
2299 if (!bs->drv) {
2300 return -ENOMEDIUM;
2303 if (bs->drv == bdrv_find_format("raw")) {
2304 bs = bs->file;
2307 /* raw-posix has several protocols so just check for raw_aio_readv */
2308 if (bs->drv->bdrv_aio_readv != raw_aio_readv) {
2309 return -ENOTSUP;
2312 s = bs->opaque;
2313 if (!s->use_aio) {
2314 return -ENOTSUP;
2316 return s->fd;
2318 #endif /* CONFIG_LINUX_AIO */
2320 static void bdrv_file_init(void)
2323 * Register all the drivers. Note that order is important, the driver
2324 * registered last will get probed first.
2326 bdrv_register(&bdrv_file);
2327 bdrv_register(&bdrv_host_device);
2328 #ifdef __linux__
2329 bdrv_register(&bdrv_host_floppy);
2330 bdrv_register(&bdrv_host_cdrom);
2331 #endif
2332 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2333 bdrv_register(&bdrv_host_cdrom);
2334 #endif
2337 block_init(bdrv_file_init);