xen: move Xen PV machine files to hw/xenpv
[qemu/ar7.git] / block / raw-posix.c
blob3ce026db589a887389a43163d793943ace61f257
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 } BDRVRawState;
151 typedef struct BDRVRawReopenState {
152 int fd;
153 int open_flags;
154 #ifdef CONFIG_LINUX_AIO
155 int use_aio;
156 #endif
157 } BDRVRawReopenState;
159 static int fd_open(BlockDriverState *bs);
160 static int64_t raw_getlength(BlockDriverState *bs);
162 typedef struct RawPosixAIOData {
163 BlockDriverState *bs;
164 int aio_fildes;
165 union {
166 struct iovec *aio_iov;
167 void *aio_ioctl_buf;
169 int aio_niov;
170 uint64_t aio_nbytes;
171 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
172 off_t aio_offset;
173 int aio_type;
174 } RawPosixAIOData;
176 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
177 static int cdrom_reopen(BlockDriverState *bs);
178 #endif
180 #if defined(__NetBSD__)
181 static int raw_normalize_devicepath(const char **filename)
183 static char namebuf[PATH_MAX];
184 const char *dp, *fname;
185 struct stat sb;
187 fname = *filename;
188 dp = strrchr(fname, '/');
189 if (lstat(fname, &sb) < 0) {
190 fprintf(stderr, "%s: stat failed: %s\n",
191 fname, strerror(errno));
192 return -errno;
195 if (!S_ISBLK(sb.st_mode)) {
196 return 0;
199 if (dp == NULL) {
200 snprintf(namebuf, PATH_MAX, "r%s", fname);
201 } else {
202 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
203 (int)(dp - fname), fname, dp + 1);
205 fprintf(stderr, "%s is a block device", fname);
206 *filename = namebuf;
207 fprintf(stderr, ", using %s\n", *filename);
209 return 0;
211 #else
212 static int raw_normalize_devicepath(const char **filename)
214 return 0;
216 #endif
218 static void raw_probe_alignment(BlockDriverState *bs)
220 BDRVRawState *s = bs->opaque;
221 char *buf;
222 unsigned int sector_size;
224 /* For /dev/sg devices the alignment is not really used.
225 With buffered I/O, we don't have any restrictions. */
226 if (bs->sg || !(s->open_flags & O_DIRECT)) {
227 bs->request_alignment = 1;
228 s->buf_align = 1;
229 return;
232 /* Try a few ioctls to get the right size */
233 bs->request_alignment = 0;
234 s->buf_align = 0;
236 #ifdef BLKSSZGET
237 if (ioctl(s->fd, BLKSSZGET, &sector_size) >= 0) {
238 bs->request_alignment = sector_size;
240 #endif
241 #ifdef DKIOCGETBLOCKSIZE
242 if (ioctl(s->fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
243 bs->request_alignment = sector_size;
245 #endif
246 #ifdef DIOCGSECTORSIZE
247 if (ioctl(s->fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
248 bs->request_alignment = sector_size;
250 #endif
251 #ifdef CONFIG_XFS
252 if (s->is_xfs) {
253 struct dioattr da;
254 if (xfsctl(NULL, s->fd, XFS_IOC_DIOINFO, &da) >= 0) {
255 bs->request_alignment = da.d_miniosz;
256 /* The kernel returns wrong information for d_mem */
257 /* s->buf_align = da.d_mem; */
260 #endif
262 /* If we could not get the sizes so far, we can only guess them */
263 if (!s->buf_align) {
264 size_t align;
265 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
266 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
267 if (pread(s->fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
268 s->buf_align = align;
269 break;
272 qemu_vfree(buf);
275 if (!bs->request_alignment) {
276 size_t align;
277 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
278 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
279 if (pread(s->fd, buf, align, 0) >= 0) {
280 bs->request_alignment = align;
281 break;
284 qemu_vfree(buf);
288 static void raw_parse_flags(int bdrv_flags, int *open_flags)
290 assert(open_flags != NULL);
292 *open_flags |= O_BINARY;
293 *open_flags &= ~O_ACCMODE;
294 if (bdrv_flags & BDRV_O_RDWR) {
295 *open_flags |= O_RDWR;
296 } else {
297 *open_flags |= O_RDONLY;
300 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
301 * and O_DIRECT for no caching. */
302 if ((bdrv_flags & BDRV_O_NOCACHE)) {
303 *open_flags |= O_DIRECT;
307 #ifdef CONFIG_LINUX_AIO
308 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
310 int ret = -1;
311 assert(aio_ctx != NULL);
312 assert(use_aio != NULL);
314 * Currently Linux do AIO only for files opened with O_DIRECT
315 * specified so check NOCACHE flag too
317 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
318 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
320 /* if non-NULL, laio_init() has already been run */
321 if (*aio_ctx == NULL) {
322 *aio_ctx = laio_init();
323 if (!*aio_ctx) {
324 goto error;
327 *use_aio = 1;
328 } else {
329 *use_aio = 0;
332 ret = 0;
334 error:
335 return ret;
337 #endif
339 static void raw_parse_filename(const char *filename, QDict *options,
340 Error **errp)
342 /* The filename does not have to be prefixed by the protocol name, since
343 * "file" is the default protocol; therefore, the return value of this
344 * function call can be ignored. */
345 strstart(filename, "file:", &filename);
347 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
350 static QemuOptsList raw_runtime_opts = {
351 .name = "raw",
352 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
353 .desc = {
355 .name = "filename",
356 .type = QEMU_OPT_STRING,
357 .help = "File name of the image",
359 { /* end of list */ }
363 static int raw_open_common(BlockDriverState *bs, QDict *options,
364 int bdrv_flags, int open_flags, Error **errp)
366 BDRVRawState *s = bs->opaque;
367 QemuOpts *opts;
368 Error *local_err = NULL;
369 const char *filename = NULL;
370 int fd, ret;
371 struct stat st;
373 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
374 qemu_opts_absorb_qdict(opts, options, &local_err);
375 if (local_err) {
376 error_propagate(errp, local_err);
377 ret = -EINVAL;
378 goto fail;
381 filename = qemu_opt_get(opts, "filename");
383 ret = raw_normalize_devicepath(&filename);
384 if (ret != 0) {
385 error_setg_errno(errp, -ret, "Could not normalize device path");
386 goto fail;
389 s->open_flags = open_flags;
390 raw_parse_flags(bdrv_flags, &s->open_flags);
392 s->fd = -1;
393 fd = qemu_open(filename, s->open_flags, 0644);
394 if (fd < 0) {
395 ret = -errno;
396 if (ret == -EROFS) {
397 ret = -EACCES;
399 goto fail;
401 s->fd = fd;
403 #ifdef CONFIG_LINUX_AIO
404 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
405 qemu_close(fd);
406 ret = -errno;
407 error_setg_errno(errp, -ret, "Could not set AIO state");
408 goto fail;
410 #endif
412 s->has_discard = true;
413 s->has_write_zeroes = true;
415 if (fstat(s->fd, &st) < 0) {
416 error_setg_errno(errp, errno, "Could not stat file");
417 goto fail;
419 if (S_ISREG(st.st_mode)) {
420 s->discard_zeroes = true;
422 if (S_ISBLK(st.st_mode)) {
423 #ifdef BLKDISCARDZEROES
424 unsigned int arg;
425 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
426 s->discard_zeroes = true;
428 #endif
429 #ifdef __linux__
430 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
431 * not rely on the contents of discarded blocks unless using O_DIRECT.
432 * Same for BLKZEROOUT.
434 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
435 s->discard_zeroes = false;
436 s->has_write_zeroes = false;
438 #endif
441 #ifdef CONFIG_XFS
442 if (platform_test_xfs_fd(s->fd)) {
443 s->is_xfs = true;
445 #endif
447 ret = 0;
448 fail:
449 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
450 unlink(filename);
452 qemu_opts_del(opts);
453 return ret;
456 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
457 Error **errp)
459 BDRVRawState *s = bs->opaque;
460 Error *local_err = NULL;
461 int ret;
463 s->type = FTYPE_FILE;
464 ret = raw_open_common(bs, options, flags, 0, &local_err);
465 if (local_err) {
466 error_propagate(errp, local_err);
468 return ret;
471 static int raw_reopen_prepare(BDRVReopenState *state,
472 BlockReopenQueue *queue, Error **errp)
474 BDRVRawState *s;
475 BDRVRawReopenState *raw_s;
476 int ret = 0;
478 assert(state != NULL);
479 assert(state->bs != NULL);
481 s = state->bs->opaque;
483 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
484 raw_s = state->opaque;
486 #ifdef CONFIG_LINUX_AIO
487 raw_s->use_aio = s->use_aio;
489 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
490 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
491 * won't override aio_ctx if aio_ctx is non-NULL */
492 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
493 error_setg(errp, "Could not set AIO state");
494 return -1;
496 #endif
498 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
499 raw_s->open_flags |= O_NONBLOCK;
502 raw_parse_flags(state->flags, &raw_s->open_flags);
504 raw_s->fd = -1;
506 int fcntl_flags = O_APPEND | O_NONBLOCK;
507 #ifdef O_NOATIME
508 fcntl_flags |= O_NOATIME;
509 #endif
511 #ifdef O_ASYNC
512 /* Not all operating systems have O_ASYNC, and those that don't
513 * will not let us track the state into raw_s->open_flags (typically
514 * you achieve the same effect with an ioctl, for example I_SETSIG
515 * on Solaris). But we do not use O_ASYNC, so that's fine.
517 assert((s->open_flags & O_ASYNC) == 0);
518 #endif
520 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
521 /* dup the original fd */
522 /* TODO: use qemu fcntl wrapper */
523 #ifdef F_DUPFD_CLOEXEC
524 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
525 #else
526 raw_s->fd = dup(s->fd);
527 if (raw_s->fd != -1) {
528 qemu_set_cloexec(raw_s->fd);
530 #endif
531 if (raw_s->fd >= 0) {
532 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
533 if (ret) {
534 qemu_close(raw_s->fd);
535 raw_s->fd = -1;
540 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
541 if (raw_s->fd == -1) {
542 assert(!(raw_s->open_flags & O_CREAT));
543 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
544 if (raw_s->fd == -1) {
545 error_setg_errno(errp, errno, "Could not reopen file");
546 ret = -1;
549 return ret;
552 static void raw_reopen_commit(BDRVReopenState *state)
554 BDRVRawReopenState *raw_s = state->opaque;
555 BDRVRawState *s = state->bs->opaque;
557 s->open_flags = raw_s->open_flags;
559 qemu_close(s->fd);
560 s->fd = raw_s->fd;
561 #ifdef CONFIG_LINUX_AIO
562 s->use_aio = raw_s->use_aio;
563 #endif
565 g_free(state->opaque);
566 state->opaque = NULL;
570 static void raw_reopen_abort(BDRVReopenState *state)
572 BDRVRawReopenState *raw_s = state->opaque;
574 /* nothing to do if NULL, we didn't get far enough */
575 if (raw_s == NULL) {
576 return;
579 if (raw_s->fd >= 0) {
580 qemu_close(raw_s->fd);
581 raw_s->fd = -1;
583 g_free(state->opaque);
584 state->opaque = NULL;
587 static int raw_refresh_limits(BlockDriverState *bs)
589 BDRVRawState *s = bs->opaque;
591 raw_probe_alignment(bs);
592 bs->bl.opt_mem_alignment = s->buf_align;
594 return 0;
597 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
599 int ret;
601 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
602 if (ret == -1) {
603 return -errno;
606 return 0;
609 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
611 int ret;
613 ret = qemu_fdatasync(aiocb->aio_fildes);
614 if (ret == -1) {
615 return -errno;
617 return 0;
620 #ifdef CONFIG_PREADV
622 static bool preadv_present = true;
624 static ssize_t
625 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
627 return preadv(fd, iov, nr_iov, offset);
630 static ssize_t
631 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
633 return pwritev(fd, iov, nr_iov, offset);
636 #else
638 static bool preadv_present = false;
640 static ssize_t
641 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
643 return -ENOSYS;
646 static ssize_t
647 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
649 return -ENOSYS;
652 #endif
654 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
656 ssize_t len;
658 do {
659 if (aiocb->aio_type & QEMU_AIO_WRITE)
660 len = qemu_pwritev(aiocb->aio_fildes,
661 aiocb->aio_iov,
662 aiocb->aio_niov,
663 aiocb->aio_offset);
664 else
665 len = qemu_preadv(aiocb->aio_fildes,
666 aiocb->aio_iov,
667 aiocb->aio_niov,
668 aiocb->aio_offset);
669 } while (len == -1 && errno == EINTR);
671 if (len == -1) {
672 return -errno;
674 return len;
678 * Read/writes the data to/from a given linear buffer.
680 * Returns the number of bytes handles or -errno in case of an error. Short
681 * reads are only returned if the end of the file is reached.
683 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
685 ssize_t offset = 0;
686 ssize_t len;
688 while (offset < aiocb->aio_nbytes) {
689 if (aiocb->aio_type & QEMU_AIO_WRITE) {
690 len = pwrite(aiocb->aio_fildes,
691 (const char *)buf + offset,
692 aiocb->aio_nbytes - offset,
693 aiocb->aio_offset + offset);
694 } else {
695 len = pread(aiocb->aio_fildes,
696 buf + offset,
697 aiocb->aio_nbytes - offset,
698 aiocb->aio_offset + offset);
700 if (len == -1 && errno == EINTR) {
701 continue;
702 } else if (len == -1) {
703 offset = -errno;
704 break;
705 } else if (len == 0) {
706 break;
708 offset += len;
711 return offset;
714 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
716 ssize_t nbytes;
717 char *buf;
719 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
721 * If there is just a single buffer, and it is properly aligned
722 * we can just use plain pread/pwrite without any problems.
724 if (aiocb->aio_niov == 1) {
725 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
728 * We have more than one iovec, and all are properly aligned.
730 * Try preadv/pwritev first and fall back to linearizing the
731 * buffer if it's not supported.
733 if (preadv_present) {
734 nbytes = handle_aiocb_rw_vector(aiocb);
735 if (nbytes == aiocb->aio_nbytes ||
736 (nbytes < 0 && nbytes != -ENOSYS)) {
737 return nbytes;
739 preadv_present = false;
743 * XXX(hch): short read/write. no easy way to handle the reminder
744 * using these interfaces. For now retry using plain
745 * pread/pwrite?
750 * Ok, we have to do it the hard way, copy all segments into
751 * a single aligned buffer.
753 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
754 if (aiocb->aio_type & QEMU_AIO_WRITE) {
755 char *p = buf;
756 int i;
758 for (i = 0; i < aiocb->aio_niov; ++i) {
759 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
760 p += aiocb->aio_iov[i].iov_len;
764 nbytes = handle_aiocb_rw_linear(aiocb, buf);
765 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
766 char *p = buf;
767 size_t count = aiocb->aio_nbytes, copy;
768 int i;
770 for (i = 0; i < aiocb->aio_niov && count; ++i) {
771 copy = count;
772 if (copy > aiocb->aio_iov[i].iov_len) {
773 copy = aiocb->aio_iov[i].iov_len;
775 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
776 p += copy;
777 count -= copy;
780 qemu_vfree(buf);
782 return nbytes;
785 #ifdef CONFIG_XFS
786 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
788 struct xfs_flock64 fl;
790 memset(&fl, 0, sizeof(fl));
791 fl.l_whence = SEEK_SET;
792 fl.l_start = offset;
793 fl.l_len = bytes;
795 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
796 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
797 return -errno;
800 return 0;
803 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
805 struct xfs_flock64 fl;
807 memset(&fl, 0, sizeof(fl));
808 fl.l_whence = SEEK_SET;
809 fl.l_start = offset;
810 fl.l_len = bytes;
812 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
813 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
814 return -errno;
817 return 0;
819 #endif
821 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
823 int ret = -EOPNOTSUPP;
824 BDRVRawState *s = aiocb->bs->opaque;
826 if (s->has_write_zeroes == 0) {
827 return -ENOTSUP;
830 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
831 #ifdef BLKZEROOUT
832 do {
833 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
834 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
835 return 0;
837 } while (errno == EINTR);
839 ret = -errno;
840 #endif
841 } else {
842 #ifdef CONFIG_XFS
843 if (s->is_xfs) {
844 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
846 #endif
849 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
850 ret == -ENOTTY) {
851 s->has_write_zeroes = false;
852 ret = -ENOTSUP;
854 return ret;
857 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
859 int ret = -EOPNOTSUPP;
860 BDRVRawState *s = aiocb->bs->opaque;
862 if (!s->has_discard) {
863 return -ENOTSUP;
866 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
867 #ifdef BLKDISCARD
868 do {
869 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
870 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
871 return 0;
873 } while (errno == EINTR);
875 ret = -errno;
876 #endif
877 } else {
878 #ifdef CONFIG_XFS
879 if (s->is_xfs) {
880 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
882 #endif
884 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
885 do {
886 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
887 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
888 return 0;
890 } while (errno == EINTR);
892 ret = -errno;
893 #endif
896 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
897 ret == -ENOTTY) {
898 s->has_discard = false;
899 ret = -ENOTSUP;
901 return ret;
904 static int aio_worker(void *arg)
906 RawPosixAIOData *aiocb = arg;
907 ssize_t ret = 0;
909 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
910 case QEMU_AIO_READ:
911 ret = handle_aiocb_rw(aiocb);
912 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
913 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
914 0, aiocb->aio_nbytes - ret);
916 ret = aiocb->aio_nbytes;
918 if (ret == aiocb->aio_nbytes) {
919 ret = 0;
920 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
921 ret = -EINVAL;
923 break;
924 case QEMU_AIO_WRITE:
925 ret = handle_aiocb_rw(aiocb);
926 if (ret == aiocb->aio_nbytes) {
927 ret = 0;
928 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
929 ret = -EINVAL;
931 break;
932 case QEMU_AIO_FLUSH:
933 ret = handle_aiocb_flush(aiocb);
934 break;
935 case QEMU_AIO_IOCTL:
936 ret = handle_aiocb_ioctl(aiocb);
937 break;
938 case QEMU_AIO_DISCARD:
939 ret = handle_aiocb_discard(aiocb);
940 break;
941 case QEMU_AIO_WRITE_ZEROES:
942 ret = handle_aiocb_write_zeroes(aiocb);
943 break;
944 default:
945 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
946 ret = -EINVAL;
947 break;
950 g_slice_free(RawPosixAIOData, aiocb);
951 return ret;
954 static int paio_submit_co(BlockDriverState *bs, int fd,
955 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
956 int type)
958 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
959 ThreadPool *pool;
961 acb->bs = bs;
962 acb->aio_type = type;
963 acb->aio_fildes = fd;
965 if (qiov) {
966 acb->aio_iov = qiov->iov;
967 acb->aio_niov = qiov->niov;
969 acb->aio_nbytes = nb_sectors * 512;
970 acb->aio_offset = sector_num * 512;
972 trace_paio_submit_co(sector_num, nb_sectors, type);
973 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
974 return thread_pool_submit_co(pool, aio_worker, acb);
977 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
978 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
979 BlockDriverCompletionFunc *cb, void *opaque, int type)
981 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
982 ThreadPool *pool;
984 acb->bs = bs;
985 acb->aio_type = type;
986 acb->aio_fildes = fd;
988 if (qiov) {
989 acb->aio_iov = qiov->iov;
990 acb->aio_niov = qiov->niov;
992 acb->aio_nbytes = nb_sectors * 512;
993 acb->aio_offset = sector_num * 512;
995 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
996 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
997 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1000 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
1001 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1002 BlockDriverCompletionFunc *cb, void *opaque, int type)
1004 BDRVRawState *s = bs->opaque;
1006 if (fd_open(bs) < 0)
1007 return NULL;
1010 * If O_DIRECT is used the buffer needs to be aligned on a sector
1011 * boundary. Check if this is the case or tell the low-level
1012 * driver that it needs to copy the buffer.
1014 if ((bs->open_flags & BDRV_O_NOCACHE)) {
1015 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1016 type |= QEMU_AIO_MISALIGNED;
1017 #ifdef CONFIG_LINUX_AIO
1018 } else if (s->use_aio) {
1019 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1020 nb_sectors, cb, opaque, type);
1021 #endif
1025 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1026 cb, opaque, type);
1029 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
1030 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1031 BlockDriverCompletionFunc *cb, void *opaque)
1033 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1034 cb, opaque, QEMU_AIO_READ);
1037 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
1038 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1039 BlockDriverCompletionFunc *cb, void *opaque)
1041 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1042 cb, opaque, QEMU_AIO_WRITE);
1045 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
1046 BlockDriverCompletionFunc *cb, void *opaque)
1048 BDRVRawState *s = bs->opaque;
1050 if (fd_open(bs) < 0)
1051 return NULL;
1053 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1056 static void raw_close(BlockDriverState *bs)
1058 BDRVRawState *s = bs->opaque;
1059 if (s->fd >= 0) {
1060 qemu_close(s->fd);
1061 s->fd = -1;
1065 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1067 BDRVRawState *s = bs->opaque;
1068 struct stat st;
1070 if (fstat(s->fd, &st)) {
1071 return -errno;
1074 if (S_ISREG(st.st_mode)) {
1075 if (ftruncate(s->fd, offset) < 0) {
1076 return -errno;
1078 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1079 if (offset > raw_getlength(bs)) {
1080 return -EINVAL;
1082 } else {
1083 return -ENOTSUP;
1086 return 0;
1089 #ifdef __OpenBSD__
1090 static int64_t raw_getlength(BlockDriverState *bs)
1092 BDRVRawState *s = bs->opaque;
1093 int fd = s->fd;
1094 struct stat st;
1096 if (fstat(fd, &st))
1097 return -1;
1098 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1099 struct disklabel dl;
1101 if (ioctl(fd, DIOCGDINFO, &dl))
1102 return -1;
1103 return (uint64_t)dl.d_secsize *
1104 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1105 } else
1106 return st.st_size;
1108 #elif defined(__NetBSD__)
1109 static int64_t raw_getlength(BlockDriverState *bs)
1111 BDRVRawState *s = bs->opaque;
1112 int fd = s->fd;
1113 struct stat st;
1115 if (fstat(fd, &st))
1116 return -1;
1117 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1118 struct dkwedge_info dkw;
1120 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1121 return dkw.dkw_size * 512;
1122 } else {
1123 struct disklabel dl;
1125 if (ioctl(fd, DIOCGDINFO, &dl))
1126 return -1;
1127 return (uint64_t)dl.d_secsize *
1128 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1130 } else
1131 return st.st_size;
1133 #elif defined(__sun__)
1134 static int64_t raw_getlength(BlockDriverState *bs)
1136 BDRVRawState *s = bs->opaque;
1137 struct dk_minfo minfo;
1138 int ret;
1140 ret = fd_open(bs);
1141 if (ret < 0) {
1142 return ret;
1146 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1148 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1149 if (ret != -1) {
1150 return minfo.dki_lbsize * minfo.dki_capacity;
1154 * There are reports that lseek on some devices fails, but
1155 * irc discussion said that contingency on contingency was overkill.
1157 return lseek(s->fd, 0, SEEK_END);
1159 #elif defined(CONFIG_BSD)
1160 static int64_t raw_getlength(BlockDriverState *bs)
1162 BDRVRawState *s = bs->opaque;
1163 int fd = s->fd;
1164 int64_t size;
1165 struct stat sb;
1166 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1167 int reopened = 0;
1168 #endif
1169 int ret;
1171 ret = fd_open(bs);
1172 if (ret < 0)
1173 return ret;
1175 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1176 again:
1177 #endif
1178 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1179 #ifdef DIOCGMEDIASIZE
1180 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1181 #elif defined(DIOCGPART)
1183 struct partinfo pi;
1184 if (ioctl(fd, DIOCGPART, &pi) == 0)
1185 size = pi.media_size;
1186 else
1187 size = 0;
1189 if (size == 0)
1190 #endif
1191 #if defined(__APPLE__) && defined(__MACH__)
1192 size = LONG_LONG_MAX;
1193 #else
1194 size = lseek(fd, 0LL, SEEK_END);
1195 #endif
1196 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1197 switch(s->type) {
1198 case FTYPE_CD:
1199 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1200 if (size == 2048LL * (unsigned)-1)
1201 size = 0;
1202 /* XXX no disc? maybe we need to reopen... */
1203 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1204 reopened = 1;
1205 goto again;
1208 #endif
1209 } else {
1210 size = lseek(fd, 0, SEEK_END);
1212 return size;
1214 #else
1215 static int64_t raw_getlength(BlockDriverState *bs)
1217 BDRVRawState *s = bs->opaque;
1218 int ret;
1220 ret = fd_open(bs);
1221 if (ret < 0) {
1222 return ret;
1225 return lseek(s->fd, 0, SEEK_END);
1227 #endif
1229 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1231 struct stat st;
1232 BDRVRawState *s = bs->opaque;
1234 if (fstat(s->fd, &st) < 0) {
1235 return -errno;
1237 return (int64_t)st.st_blocks * 512;
1240 static int raw_create(const char *filename, QEMUOptionParameter *options,
1241 Error **errp)
1243 int fd;
1244 int result = 0;
1245 int64_t total_size = 0;
1247 strstart(filename, "file:", &filename);
1249 /* Read out options */
1250 while (options && options->name) {
1251 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1252 total_size = options->value.n / BDRV_SECTOR_SIZE;
1254 options++;
1257 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1258 0644);
1259 if (fd < 0) {
1260 result = -errno;
1261 error_setg_errno(errp, -result, "Could not create file");
1262 } else {
1263 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
1264 result = -errno;
1265 error_setg_errno(errp, -result, "Could not resize file");
1267 if (qemu_close(fd) != 0) {
1268 result = -errno;
1269 error_setg_errno(errp, -result, "Could not close the new file");
1272 return result;
1276 * Returns true iff the specified sector is present in the disk image. Drivers
1277 * not implementing the functionality are assumed to not support backing files,
1278 * hence all their sectors are reported as allocated.
1280 * If 'sector_num' is beyond the end of the disk image the return value is 0
1281 * and 'pnum' is set to 0.
1283 * 'pnum' is set to the number of sectors (including and immediately following
1284 * the specified sector) that are known to be in the same
1285 * allocated/unallocated state.
1287 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1288 * beyond the end of the disk image it will be clamped.
1290 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1291 int64_t sector_num,
1292 int nb_sectors, int *pnum)
1294 off_t start, data, hole;
1295 int64_t ret;
1297 ret = fd_open(bs);
1298 if (ret < 0) {
1299 return ret;
1302 start = sector_num * BDRV_SECTOR_SIZE;
1303 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1305 #ifdef CONFIG_FIEMAP
1307 BDRVRawState *s = bs->opaque;
1308 struct {
1309 struct fiemap fm;
1310 struct fiemap_extent fe;
1311 } f;
1313 f.fm.fm_start = start;
1314 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1315 f.fm.fm_flags = 0;
1316 f.fm.fm_extent_count = 1;
1317 f.fm.fm_reserved = 0;
1318 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1319 /* Assume everything is allocated. */
1320 *pnum = nb_sectors;
1321 return ret;
1324 if (f.fm.fm_mapped_extents == 0) {
1325 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1326 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1328 off_t length = lseek(s->fd, 0, SEEK_END);
1329 hole = f.fm.fm_start;
1330 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1331 } else {
1332 data = f.fe.fe_logical;
1333 hole = f.fe.fe_logical + f.fe.fe_length;
1334 if (f.fe.fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
1335 ret |= BDRV_BLOCK_ZERO;
1339 #elif defined SEEK_HOLE && defined SEEK_DATA
1341 BDRVRawState *s = bs->opaque;
1343 hole = lseek(s->fd, start, SEEK_HOLE);
1344 if (hole == -1) {
1345 /* -ENXIO indicates that sector_num was past the end of the file.
1346 * There is a virtual hole there. */
1347 assert(errno != -ENXIO);
1349 /* Most likely EINVAL. Assume everything is allocated. */
1350 *pnum = nb_sectors;
1351 return ret;
1354 if (hole > start) {
1355 data = start;
1356 } else {
1357 /* On a hole. We need another syscall to find its end. */
1358 data = lseek(s->fd, start, SEEK_DATA);
1359 if (data == -1) {
1360 data = lseek(s->fd, 0, SEEK_END);
1363 #else
1364 data = 0;
1365 hole = start + nb_sectors * BDRV_SECTOR_SIZE;
1366 #endif
1368 if (data <= start) {
1369 /* On a data extent, compute sectors to the end of the extent. */
1370 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1371 } else {
1372 /* On a hole, compute sectors to the beginning of the next extent. */
1373 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1374 ret &= ~BDRV_BLOCK_DATA;
1375 ret |= BDRV_BLOCK_ZERO;
1378 return ret;
1381 static coroutine_fn BlockDriverAIOCB *raw_aio_discard(BlockDriverState *bs,
1382 int64_t sector_num, int nb_sectors,
1383 BlockDriverCompletionFunc *cb, void *opaque)
1385 BDRVRawState *s = bs->opaque;
1387 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1388 cb, opaque, QEMU_AIO_DISCARD);
1391 static int coroutine_fn raw_co_write_zeroes(
1392 BlockDriverState *bs, int64_t sector_num,
1393 int nb_sectors, BdrvRequestFlags flags)
1395 BDRVRawState *s = bs->opaque;
1397 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1398 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1399 QEMU_AIO_WRITE_ZEROES);
1400 } else if (s->discard_zeroes) {
1401 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1402 QEMU_AIO_DISCARD);
1404 return -ENOTSUP;
1407 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1409 BDRVRawState *s = bs->opaque;
1411 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1412 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1413 return 0;
1416 static QEMUOptionParameter raw_create_options[] = {
1418 .name = BLOCK_OPT_SIZE,
1419 .type = OPT_SIZE,
1420 .help = "Virtual disk size"
1422 { NULL }
1425 static BlockDriver bdrv_file = {
1426 .format_name = "file",
1427 .protocol_name = "file",
1428 .instance_size = sizeof(BDRVRawState),
1429 .bdrv_needs_filename = true,
1430 .bdrv_probe = NULL, /* no probe for protocols */
1431 .bdrv_parse_filename = raw_parse_filename,
1432 .bdrv_file_open = raw_open,
1433 .bdrv_reopen_prepare = raw_reopen_prepare,
1434 .bdrv_reopen_commit = raw_reopen_commit,
1435 .bdrv_reopen_abort = raw_reopen_abort,
1436 .bdrv_close = raw_close,
1437 .bdrv_create = raw_create,
1438 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1439 .bdrv_co_get_block_status = raw_co_get_block_status,
1440 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1442 .bdrv_aio_readv = raw_aio_readv,
1443 .bdrv_aio_writev = raw_aio_writev,
1444 .bdrv_aio_flush = raw_aio_flush,
1445 .bdrv_aio_discard = raw_aio_discard,
1446 .bdrv_refresh_limits = raw_refresh_limits,
1448 .bdrv_truncate = raw_truncate,
1449 .bdrv_getlength = raw_getlength,
1450 .bdrv_get_info = raw_get_info,
1451 .bdrv_get_allocated_file_size
1452 = raw_get_allocated_file_size,
1454 .create_options = raw_create_options,
1457 /***********************************************/
1458 /* host device */
1460 #if defined(__APPLE__) && defined(__MACH__)
1461 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1462 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1464 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1466 kern_return_t kernResult;
1467 mach_port_t masterPort;
1468 CFMutableDictionaryRef classesToMatch;
1470 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1471 if ( KERN_SUCCESS != kernResult ) {
1472 printf( "IOMasterPort returned %d\n", kernResult );
1475 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1476 if ( classesToMatch == NULL ) {
1477 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1478 } else {
1479 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1481 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1482 if ( KERN_SUCCESS != kernResult )
1484 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1487 return kernResult;
1490 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1492 io_object_t nextMedia;
1493 kern_return_t kernResult = KERN_FAILURE;
1494 *bsdPath = '\0';
1495 nextMedia = IOIteratorNext( mediaIterator );
1496 if ( nextMedia )
1498 CFTypeRef bsdPathAsCFString;
1499 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1500 if ( bsdPathAsCFString ) {
1501 size_t devPathLength;
1502 strcpy( bsdPath, _PATH_DEV );
1503 strcat( bsdPath, "r" );
1504 devPathLength = strlen( bsdPath );
1505 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1506 kernResult = KERN_SUCCESS;
1508 CFRelease( bsdPathAsCFString );
1510 IOObjectRelease( nextMedia );
1513 return kernResult;
1516 #endif
1518 static int hdev_probe_device(const char *filename)
1520 struct stat st;
1522 /* allow a dedicated CD-ROM driver to match with a higher priority */
1523 if (strstart(filename, "/dev/cdrom", NULL))
1524 return 50;
1526 if (stat(filename, &st) >= 0 &&
1527 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1528 return 100;
1531 return 0;
1534 static int check_hdev_writable(BDRVRawState *s)
1536 #if defined(BLKROGET)
1537 /* Linux block devices can be configured "read-only" using blockdev(8).
1538 * This is independent of device node permissions and therefore open(2)
1539 * with O_RDWR succeeds. Actual writes fail with EPERM.
1541 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1542 * check for read-only block devices so that Linux block devices behave
1543 * properly.
1545 struct stat st;
1546 int readonly = 0;
1548 if (fstat(s->fd, &st)) {
1549 return -errno;
1552 if (!S_ISBLK(st.st_mode)) {
1553 return 0;
1556 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1557 return -errno;
1560 if (readonly) {
1561 return -EACCES;
1563 #endif /* defined(BLKROGET) */
1564 return 0;
1567 static void hdev_parse_filename(const char *filename, QDict *options,
1568 Error **errp)
1570 /* The prefix is optional, just as for "file". */
1571 strstart(filename, "host_device:", &filename);
1573 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1576 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1577 Error **errp)
1579 BDRVRawState *s = bs->opaque;
1580 Error *local_err = NULL;
1581 int ret;
1582 const char *filename = qdict_get_str(options, "filename");
1584 #if defined(__APPLE__) && defined(__MACH__)
1585 if (strstart(filename, "/dev/cdrom", NULL)) {
1586 kern_return_t kernResult;
1587 io_iterator_t mediaIterator;
1588 char bsdPath[ MAXPATHLEN ];
1589 int fd;
1591 kernResult = FindEjectableCDMedia( &mediaIterator );
1592 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1594 if ( bsdPath[ 0 ] != '\0' ) {
1595 strcat(bsdPath,"s0");
1596 /* some CDs don't have a partition 0 */
1597 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1598 if (fd < 0) {
1599 bsdPath[strlen(bsdPath)-1] = '1';
1600 } else {
1601 qemu_close(fd);
1603 filename = bsdPath;
1604 qdict_put(options, "filename", qstring_from_str(filename));
1607 if ( mediaIterator )
1608 IOObjectRelease( mediaIterator );
1610 #endif
1612 s->type = FTYPE_FILE;
1613 #if defined(__linux__)
1615 char resolved_path[ MAXPATHLEN ], *temp;
1617 temp = realpath(filename, resolved_path);
1618 if (temp && strstart(temp, "/dev/sg", NULL)) {
1619 bs->sg = 1;
1622 #endif
1624 ret = raw_open_common(bs, options, flags, 0, &local_err);
1625 if (ret < 0) {
1626 if (local_err) {
1627 error_propagate(errp, local_err);
1629 return ret;
1632 if (flags & BDRV_O_RDWR) {
1633 ret = check_hdev_writable(s);
1634 if (ret < 0) {
1635 raw_close(bs);
1636 error_setg_errno(errp, -ret, "The device is not writable");
1637 return ret;
1641 return ret;
1644 #if defined(__linux__)
1645 /* Note: we do not have a reliable method to detect if the floppy is
1646 present. The current method is to try to open the floppy at every
1647 I/O and to keep it opened during a few hundreds of ms. */
1648 static int fd_open(BlockDriverState *bs)
1650 BDRVRawState *s = bs->opaque;
1651 int last_media_present;
1653 if (s->type != FTYPE_FD)
1654 return 0;
1655 last_media_present = (s->fd >= 0);
1656 if (s->fd >= 0 &&
1657 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1658 qemu_close(s->fd);
1659 s->fd = -1;
1660 #ifdef DEBUG_FLOPPY
1661 printf("Floppy closed\n");
1662 #endif
1664 if (s->fd < 0) {
1665 if (s->fd_got_error &&
1666 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1667 #ifdef DEBUG_FLOPPY
1668 printf("No floppy (open delayed)\n");
1669 #endif
1670 return -EIO;
1672 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1673 if (s->fd < 0) {
1674 s->fd_error_time = get_clock();
1675 s->fd_got_error = 1;
1676 if (last_media_present)
1677 s->fd_media_changed = 1;
1678 #ifdef DEBUG_FLOPPY
1679 printf("No floppy\n");
1680 #endif
1681 return -EIO;
1683 #ifdef DEBUG_FLOPPY
1684 printf("Floppy opened\n");
1685 #endif
1687 if (!last_media_present)
1688 s->fd_media_changed = 1;
1689 s->fd_open_time = get_clock();
1690 s->fd_got_error = 0;
1691 return 0;
1694 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1696 BDRVRawState *s = bs->opaque;
1698 return ioctl(s->fd, req, buf);
1701 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1702 unsigned long int req, void *buf,
1703 BlockDriverCompletionFunc *cb, void *opaque)
1705 BDRVRawState *s = bs->opaque;
1706 RawPosixAIOData *acb;
1707 ThreadPool *pool;
1709 if (fd_open(bs) < 0)
1710 return NULL;
1712 acb = g_slice_new(RawPosixAIOData);
1713 acb->bs = bs;
1714 acb->aio_type = QEMU_AIO_IOCTL;
1715 acb->aio_fildes = s->fd;
1716 acb->aio_offset = 0;
1717 acb->aio_ioctl_buf = buf;
1718 acb->aio_ioctl_cmd = req;
1719 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1720 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1723 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1724 static int fd_open(BlockDriverState *bs)
1726 BDRVRawState *s = bs->opaque;
1728 /* this is just to ensure s->fd is sane (its called by io ops) */
1729 if (s->fd >= 0)
1730 return 0;
1731 return -EIO;
1733 #else /* !linux && !FreeBSD */
1735 static int fd_open(BlockDriverState *bs)
1737 return 0;
1740 #endif /* !linux && !FreeBSD */
1742 static coroutine_fn BlockDriverAIOCB *hdev_aio_discard(BlockDriverState *bs,
1743 int64_t sector_num, int nb_sectors,
1744 BlockDriverCompletionFunc *cb, void *opaque)
1746 BDRVRawState *s = bs->opaque;
1748 if (fd_open(bs) < 0) {
1749 return NULL;
1751 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1752 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1755 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
1756 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1758 BDRVRawState *s = bs->opaque;
1759 int rc;
1761 rc = fd_open(bs);
1762 if (rc < 0) {
1763 return rc;
1765 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1766 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1767 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
1768 } else if (s->discard_zeroes) {
1769 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1770 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1772 return -ENOTSUP;
1775 static int hdev_create(const char *filename, QEMUOptionParameter *options,
1776 Error **errp)
1778 int fd;
1779 int ret = 0;
1780 struct stat stat_buf;
1781 int64_t total_size = 0;
1782 bool has_prefix;
1784 /* This function is used by all three protocol block drivers and therefore
1785 * any of these three prefixes may be given.
1786 * The return value has to be stored somewhere, otherwise this is an error
1787 * due to -Werror=unused-value. */
1788 has_prefix =
1789 strstart(filename, "host_device:", &filename) ||
1790 strstart(filename, "host_cdrom:" , &filename) ||
1791 strstart(filename, "host_floppy:", &filename);
1793 (void)has_prefix;
1795 /* Read out options */
1796 while (options && options->name) {
1797 if (!strcmp(options->name, "size")) {
1798 total_size = options->value.n / BDRV_SECTOR_SIZE;
1800 options++;
1803 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1804 if (fd < 0) {
1805 ret = -errno;
1806 error_setg_errno(errp, -ret, "Could not open device");
1807 return ret;
1810 if (fstat(fd, &stat_buf) < 0) {
1811 ret = -errno;
1812 error_setg_errno(errp, -ret, "Could not stat device");
1813 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
1814 error_setg(errp,
1815 "The given file is neither a block nor a character device");
1816 ret = -ENODEV;
1817 } else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE) {
1818 error_setg(errp, "Device is too small");
1819 ret = -ENOSPC;
1822 qemu_close(fd);
1823 return ret;
1826 static BlockDriver bdrv_host_device = {
1827 .format_name = "host_device",
1828 .protocol_name = "host_device",
1829 .instance_size = sizeof(BDRVRawState),
1830 .bdrv_needs_filename = true,
1831 .bdrv_probe_device = hdev_probe_device,
1832 .bdrv_parse_filename = hdev_parse_filename,
1833 .bdrv_file_open = hdev_open,
1834 .bdrv_close = raw_close,
1835 .bdrv_reopen_prepare = raw_reopen_prepare,
1836 .bdrv_reopen_commit = raw_reopen_commit,
1837 .bdrv_reopen_abort = raw_reopen_abort,
1838 .bdrv_create = hdev_create,
1839 .create_options = raw_create_options,
1840 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
1842 .bdrv_aio_readv = raw_aio_readv,
1843 .bdrv_aio_writev = raw_aio_writev,
1844 .bdrv_aio_flush = raw_aio_flush,
1845 .bdrv_aio_discard = hdev_aio_discard,
1846 .bdrv_refresh_limits = raw_refresh_limits,
1848 .bdrv_truncate = raw_truncate,
1849 .bdrv_getlength = raw_getlength,
1850 .bdrv_get_info = raw_get_info,
1851 .bdrv_get_allocated_file_size
1852 = raw_get_allocated_file_size,
1854 /* generic scsi device */
1855 #ifdef __linux__
1856 .bdrv_ioctl = hdev_ioctl,
1857 .bdrv_aio_ioctl = hdev_aio_ioctl,
1858 #endif
1861 #ifdef __linux__
1862 static void floppy_parse_filename(const char *filename, QDict *options,
1863 Error **errp)
1865 /* The prefix is optional, just as for "file". */
1866 strstart(filename, "host_floppy:", &filename);
1868 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1871 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
1872 Error **errp)
1874 BDRVRawState *s = bs->opaque;
1875 Error *local_err = NULL;
1876 int ret;
1878 s->type = FTYPE_FD;
1880 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1881 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
1882 if (ret) {
1883 if (local_err) {
1884 error_propagate(errp, local_err);
1886 return ret;
1889 /* close fd so that we can reopen it as needed */
1890 qemu_close(s->fd);
1891 s->fd = -1;
1892 s->fd_media_changed = 1;
1894 return 0;
1897 static int floppy_probe_device(const char *filename)
1899 int fd, ret;
1900 int prio = 0;
1901 struct floppy_struct fdparam;
1902 struct stat st;
1904 if (strstart(filename, "/dev/fd", NULL) &&
1905 !strstart(filename, "/dev/fdset/", NULL)) {
1906 prio = 50;
1909 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1910 if (fd < 0) {
1911 goto out;
1913 ret = fstat(fd, &st);
1914 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1915 goto outc;
1918 /* Attempt to detect via a floppy specific ioctl */
1919 ret = ioctl(fd, FDGETPRM, &fdparam);
1920 if (ret >= 0)
1921 prio = 100;
1923 outc:
1924 qemu_close(fd);
1925 out:
1926 return prio;
1930 static int floppy_is_inserted(BlockDriverState *bs)
1932 return fd_open(bs) >= 0;
1935 static int floppy_media_changed(BlockDriverState *bs)
1937 BDRVRawState *s = bs->opaque;
1938 int ret;
1941 * XXX: we do not have a true media changed indication.
1942 * It does not work if the floppy is changed without trying to read it.
1944 fd_open(bs);
1945 ret = s->fd_media_changed;
1946 s->fd_media_changed = 0;
1947 #ifdef DEBUG_FLOPPY
1948 printf("Floppy changed=%d\n", ret);
1949 #endif
1950 return ret;
1953 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1955 BDRVRawState *s = bs->opaque;
1956 int fd;
1958 if (s->fd >= 0) {
1959 qemu_close(s->fd);
1960 s->fd = -1;
1962 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1963 if (fd >= 0) {
1964 if (ioctl(fd, FDEJECT, 0) < 0)
1965 perror("FDEJECT");
1966 qemu_close(fd);
1970 static BlockDriver bdrv_host_floppy = {
1971 .format_name = "host_floppy",
1972 .protocol_name = "host_floppy",
1973 .instance_size = sizeof(BDRVRawState),
1974 .bdrv_needs_filename = true,
1975 .bdrv_probe_device = floppy_probe_device,
1976 .bdrv_parse_filename = floppy_parse_filename,
1977 .bdrv_file_open = floppy_open,
1978 .bdrv_close = raw_close,
1979 .bdrv_reopen_prepare = raw_reopen_prepare,
1980 .bdrv_reopen_commit = raw_reopen_commit,
1981 .bdrv_reopen_abort = raw_reopen_abort,
1982 .bdrv_create = hdev_create,
1983 .create_options = raw_create_options,
1985 .bdrv_aio_readv = raw_aio_readv,
1986 .bdrv_aio_writev = raw_aio_writev,
1987 .bdrv_aio_flush = raw_aio_flush,
1988 .bdrv_refresh_limits = raw_refresh_limits,
1990 .bdrv_truncate = raw_truncate,
1991 .bdrv_getlength = raw_getlength,
1992 .has_variable_length = true,
1993 .bdrv_get_allocated_file_size
1994 = raw_get_allocated_file_size,
1996 /* removable device support */
1997 .bdrv_is_inserted = floppy_is_inserted,
1998 .bdrv_media_changed = floppy_media_changed,
1999 .bdrv_eject = floppy_eject,
2001 #endif
2003 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2004 static void cdrom_parse_filename(const char *filename, QDict *options,
2005 Error **errp)
2007 /* The prefix is optional, just as for "file". */
2008 strstart(filename, "host_cdrom:", &filename);
2010 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2012 #endif
2014 #ifdef __linux__
2015 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2016 Error **errp)
2018 BDRVRawState *s = bs->opaque;
2019 Error *local_err = NULL;
2020 int ret;
2022 s->type = FTYPE_CD;
2024 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2025 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2026 if (local_err) {
2027 error_propagate(errp, local_err);
2029 return ret;
2032 static int cdrom_probe_device(const char *filename)
2034 int fd, ret;
2035 int prio = 0;
2036 struct stat st;
2038 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2039 if (fd < 0) {
2040 goto out;
2042 ret = fstat(fd, &st);
2043 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2044 goto outc;
2047 /* Attempt to detect via a CDROM specific ioctl */
2048 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2049 if (ret >= 0)
2050 prio = 100;
2052 outc:
2053 qemu_close(fd);
2054 out:
2055 return prio;
2058 static int cdrom_is_inserted(BlockDriverState *bs)
2060 BDRVRawState *s = bs->opaque;
2061 int ret;
2063 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2064 if (ret == CDS_DISC_OK)
2065 return 1;
2066 return 0;
2069 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2071 BDRVRawState *s = bs->opaque;
2073 if (eject_flag) {
2074 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2075 perror("CDROMEJECT");
2076 } else {
2077 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2078 perror("CDROMEJECT");
2082 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2084 BDRVRawState *s = bs->opaque;
2086 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2088 * Note: an error can happen if the distribution automatically
2089 * mounts the CD-ROM
2091 /* perror("CDROM_LOCKDOOR"); */
2095 static BlockDriver bdrv_host_cdrom = {
2096 .format_name = "host_cdrom",
2097 .protocol_name = "host_cdrom",
2098 .instance_size = sizeof(BDRVRawState),
2099 .bdrv_needs_filename = true,
2100 .bdrv_probe_device = cdrom_probe_device,
2101 .bdrv_parse_filename = cdrom_parse_filename,
2102 .bdrv_file_open = cdrom_open,
2103 .bdrv_close = raw_close,
2104 .bdrv_reopen_prepare = raw_reopen_prepare,
2105 .bdrv_reopen_commit = raw_reopen_commit,
2106 .bdrv_reopen_abort = raw_reopen_abort,
2107 .bdrv_create = hdev_create,
2108 .create_options = raw_create_options,
2110 .bdrv_aio_readv = raw_aio_readv,
2111 .bdrv_aio_writev = raw_aio_writev,
2112 .bdrv_aio_flush = raw_aio_flush,
2113 .bdrv_refresh_limits = raw_refresh_limits,
2115 .bdrv_truncate = raw_truncate,
2116 .bdrv_getlength = raw_getlength,
2117 .has_variable_length = true,
2118 .bdrv_get_allocated_file_size
2119 = raw_get_allocated_file_size,
2121 /* removable device support */
2122 .bdrv_is_inserted = cdrom_is_inserted,
2123 .bdrv_eject = cdrom_eject,
2124 .bdrv_lock_medium = cdrom_lock_medium,
2126 /* generic scsi device */
2127 .bdrv_ioctl = hdev_ioctl,
2128 .bdrv_aio_ioctl = hdev_aio_ioctl,
2130 #endif /* __linux__ */
2132 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2133 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2134 Error **errp)
2136 BDRVRawState *s = bs->opaque;
2137 Error *local_err = NULL;
2138 int ret;
2140 s->type = FTYPE_CD;
2142 ret = raw_open_common(bs, options, flags, 0, &local_err);
2143 if (ret) {
2144 if (local_err) {
2145 error_propagate(errp, local_err);
2147 return ret;
2150 /* make sure the door isn't locked at this time */
2151 ioctl(s->fd, CDIOCALLOW);
2152 return 0;
2155 static int cdrom_probe_device(const char *filename)
2157 if (strstart(filename, "/dev/cd", NULL) ||
2158 strstart(filename, "/dev/acd", NULL))
2159 return 100;
2160 return 0;
2163 static int cdrom_reopen(BlockDriverState *bs)
2165 BDRVRawState *s = bs->opaque;
2166 int fd;
2169 * Force reread of possibly changed/newly loaded disc,
2170 * FreeBSD seems to not notice sometimes...
2172 if (s->fd >= 0)
2173 qemu_close(s->fd);
2174 fd = qemu_open(bs->filename, s->open_flags, 0644);
2175 if (fd < 0) {
2176 s->fd = -1;
2177 return -EIO;
2179 s->fd = fd;
2181 /* make sure the door isn't locked at this time */
2182 ioctl(s->fd, CDIOCALLOW);
2183 return 0;
2186 static int cdrom_is_inserted(BlockDriverState *bs)
2188 return raw_getlength(bs) > 0;
2191 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2193 BDRVRawState *s = bs->opaque;
2195 if (s->fd < 0)
2196 return;
2198 (void) ioctl(s->fd, CDIOCALLOW);
2200 if (eject_flag) {
2201 if (ioctl(s->fd, CDIOCEJECT) < 0)
2202 perror("CDIOCEJECT");
2203 } else {
2204 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2205 perror("CDIOCCLOSE");
2208 cdrom_reopen(bs);
2211 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2213 BDRVRawState *s = bs->opaque;
2215 if (s->fd < 0)
2216 return;
2217 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2219 * Note: an error can happen if the distribution automatically
2220 * mounts the CD-ROM
2222 /* perror("CDROM_LOCKDOOR"); */
2226 static BlockDriver bdrv_host_cdrom = {
2227 .format_name = "host_cdrom",
2228 .protocol_name = "host_cdrom",
2229 .instance_size = sizeof(BDRVRawState),
2230 .bdrv_needs_filename = true,
2231 .bdrv_probe_device = cdrom_probe_device,
2232 .bdrv_parse_filename = cdrom_parse_filename,
2233 .bdrv_file_open = cdrom_open,
2234 .bdrv_close = raw_close,
2235 .bdrv_reopen_prepare = raw_reopen_prepare,
2236 .bdrv_reopen_commit = raw_reopen_commit,
2237 .bdrv_reopen_abort = raw_reopen_abort,
2238 .bdrv_create = hdev_create,
2239 .create_options = raw_create_options,
2241 .bdrv_aio_readv = raw_aio_readv,
2242 .bdrv_aio_writev = raw_aio_writev,
2243 .bdrv_aio_flush = raw_aio_flush,
2244 .bdrv_refresh_limits = raw_refresh_limits,
2246 .bdrv_truncate = raw_truncate,
2247 .bdrv_getlength = raw_getlength,
2248 .has_variable_length = true,
2249 .bdrv_get_allocated_file_size
2250 = raw_get_allocated_file_size,
2252 /* removable device support */
2253 .bdrv_is_inserted = cdrom_is_inserted,
2254 .bdrv_eject = cdrom_eject,
2255 .bdrv_lock_medium = cdrom_lock_medium,
2257 #endif /* __FreeBSD__ */
2259 #ifdef CONFIG_LINUX_AIO
2261 * Return the file descriptor for Linux AIO
2263 * This function is a layering violation and should be removed when it becomes
2264 * possible to call the block layer outside the global mutex. It allows the
2265 * caller to hijack the file descriptor so I/O can be performed outside the
2266 * block layer.
2268 int raw_get_aio_fd(BlockDriverState *bs)
2270 BDRVRawState *s;
2272 if (!bs->drv) {
2273 return -ENOMEDIUM;
2276 if (bs->drv == bdrv_find_format("raw")) {
2277 bs = bs->file;
2280 /* raw-posix has several protocols so just check for raw_aio_readv */
2281 if (bs->drv->bdrv_aio_readv != raw_aio_readv) {
2282 return -ENOTSUP;
2285 s = bs->opaque;
2286 if (!s->use_aio) {
2287 return -ENOTSUP;
2289 return s->fd;
2291 #endif /* CONFIG_LINUX_AIO */
2293 static void bdrv_file_init(void)
2296 * Register all the drivers. Note that order is important, the driver
2297 * registered last will get probed first.
2299 bdrv_register(&bdrv_file);
2300 bdrv_register(&bdrv_host_device);
2301 #ifdef __linux__
2302 bdrv_register(&bdrv_host_floppy);
2303 bdrv_register(&bdrv_host_cdrom);
2304 #endif
2305 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2306 bdrv_register(&bdrv_host_cdrom);
2307 #endif
2310 block_init(bdrv_file_init);