PPC: Fix booke206 TLB with phys addrs > 32bit
[qemu.git] / block / raw-posix.c
bloba857def671c5e90b73dd1c94fb8e6eb0b711c4d2
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 #ifndef FS_NOCOW_FL
59 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
60 #endif
61 #endif
62 #ifdef CONFIG_FIEMAP
63 #include <linux/fiemap.h>
64 #endif
65 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
66 #include <linux/falloc.h>
67 #endif
68 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
69 #include <sys/disk.h>
70 #include <sys/cdio.h>
71 #endif
73 #ifdef __OpenBSD__
74 #include <sys/ioctl.h>
75 #include <sys/disklabel.h>
76 #include <sys/dkio.h>
77 #endif
79 #ifdef __NetBSD__
80 #include <sys/ioctl.h>
81 #include <sys/disklabel.h>
82 #include <sys/dkio.h>
83 #include <sys/disk.h>
84 #endif
86 #ifdef __DragonFly__
87 #include <sys/ioctl.h>
88 #include <sys/diskslice.h>
89 #endif
91 #ifdef CONFIG_XFS
92 #include <xfs/xfs.h>
93 #endif
95 //#define DEBUG_FLOPPY
97 //#define DEBUG_BLOCK
98 #if defined(DEBUG_BLOCK)
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
100 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
101 #else
102 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
103 #endif
105 /* OS X does not have O_DSYNC */
106 #ifndef O_DSYNC
107 #ifdef O_SYNC
108 #define O_DSYNC O_SYNC
109 #elif defined(O_FSYNC)
110 #define O_DSYNC O_FSYNC
111 #endif
112 #endif
114 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
115 #ifndef O_DIRECT
116 #define O_DIRECT O_DSYNC
117 #endif
119 #define FTYPE_FILE 0
120 #define FTYPE_CD 1
121 #define FTYPE_FD 2
123 /* if the FD is not accessed during that time (in ns), we try to
124 reopen it to see if the disk has been changed */
125 #define FD_OPEN_TIMEOUT (1000000000)
127 #define MAX_BLOCKSIZE 4096
129 typedef struct BDRVRawState {
130 int fd;
131 int type;
132 int open_flags;
133 size_t buf_align;
135 #if defined(__linux__)
136 /* linux floppy specific */
137 int64_t fd_open_time;
138 int64_t fd_error_time;
139 int fd_got_error;
140 int fd_media_changed;
141 #endif
142 #ifdef CONFIG_LINUX_AIO
143 int use_aio;
144 void *aio_ctx;
145 #endif
146 #ifdef CONFIG_XFS
147 bool is_xfs:1;
148 #endif
149 bool has_discard:1;
150 bool has_write_zeroes:1;
151 bool discard_zeroes:1;
152 #ifdef CONFIG_FIEMAP
153 bool skip_fiemap;
154 #endif
155 } BDRVRawState;
157 typedef struct BDRVRawReopenState {
158 int fd;
159 int open_flags;
160 #ifdef CONFIG_LINUX_AIO
161 int use_aio;
162 #endif
163 } BDRVRawReopenState;
165 static int fd_open(BlockDriverState *bs);
166 static int64_t raw_getlength(BlockDriverState *bs);
168 typedef struct RawPosixAIOData {
169 BlockDriverState *bs;
170 int aio_fildes;
171 union {
172 struct iovec *aio_iov;
173 void *aio_ioctl_buf;
175 int aio_niov;
176 uint64_t aio_nbytes;
177 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
178 off_t aio_offset;
179 int aio_type;
180 } RawPosixAIOData;
182 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
183 static int cdrom_reopen(BlockDriverState *bs);
184 #endif
186 #if defined(__NetBSD__)
187 static int raw_normalize_devicepath(const char **filename)
189 static char namebuf[PATH_MAX];
190 const char *dp, *fname;
191 struct stat sb;
193 fname = *filename;
194 dp = strrchr(fname, '/');
195 if (lstat(fname, &sb) < 0) {
196 fprintf(stderr, "%s: stat failed: %s\n",
197 fname, strerror(errno));
198 return -errno;
201 if (!S_ISBLK(sb.st_mode)) {
202 return 0;
205 if (dp == NULL) {
206 snprintf(namebuf, PATH_MAX, "r%s", fname);
207 } else {
208 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
209 (int)(dp - fname), fname, dp + 1);
211 fprintf(stderr, "%s is a block device", fname);
212 *filename = namebuf;
213 fprintf(stderr, ", using %s\n", *filename);
215 return 0;
217 #else
218 static int raw_normalize_devicepath(const char **filename)
220 return 0;
222 #endif
224 static void raw_probe_alignment(BlockDriverState *bs)
226 BDRVRawState *s = bs->opaque;
227 char *buf;
228 unsigned int sector_size;
230 /* For /dev/sg devices the alignment is not really used.
231 With buffered I/O, we don't have any restrictions. */
232 if (bs->sg || !(s->open_flags & O_DIRECT)) {
233 bs->request_alignment = 1;
234 s->buf_align = 1;
235 return;
238 /* Try a few ioctls to get the right size */
239 bs->request_alignment = 0;
240 s->buf_align = 0;
242 #ifdef BLKSSZGET
243 if (ioctl(s->fd, BLKSSZGET, &sector_size) >= 0) {
244 bs->request_alignment = sector_size;
246 #endif
247 #ifdef DKIOCGETBLOCKSIZE
248 if (ioctl(s->fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
249 bs->request_alignment = sector_size;
251 #endif
252 #ifdef DIOCGSECTORSIZE
253 if (ioctl(s->fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
254 bs->request_alignment = sector_size;
256 #endif
257 #ifdef CONFIG_XFS
258 if (s->is_xfs) {
259 struct dioattr da;
260 if (xfsctl(NULL, s->fd, XFS_IOC_DIOINFO, &da) >= 0) {
261 bs->request_alignment = da.d_miniosz;
262 /* The kernel returns wrong information for d_mem */
263 /* s->buf_align = da.d_mem; */
266 #endif
268 /* If we could not get the sizes so far, we can only guess them */
269 if (!s->buf_align) {
270 size_t align;
271 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
272 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
273 if (pread(s->fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
274 s->buf_align = align;
275 break;
278 qemu_vfree(buf);
281 if (!bs->request_alignment) {
282 size_t align;
283 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
284 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
285 if (pread(s->fd, buf, align, 0) >= 0) {
286 bs->request_alignment = align;
287 break;
290 qemu_vfree(buf);
294 static void raw_parse_flags(int bdrv_flags, int *open_flags)
296 assert(open_flags != NULL);
298 *open_flags |= O_BINARY;
299 *open_flags &= ~O_ACCMODE;
300 if (bdrv_flags & BDRV_O_RDWR) {
301 *open_flags |= O_RDWR;
302 } else {
303 *open_flags |= O_RDONLY;
306 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
307 * and O_DIRECT for no caching. */
308 if ((bdrv_flags & BDRV_O_NOCACHE)) {
309 *open_flags |= O_DIRECT;
313 static void raw_detach_aio_context(BlockDriverState *bs)
315 #ifdef CONFIG_LINUX_AIO
316 BDRVRawState *s = bs->opaque;
318 if (s->use_aio) {
319 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
321 #endif
324 static void raw_attach_aio_context(BlockDriverState *bs,
325 AioContext *new_context)
327 #ifdef CONFIG_LINUX_AIO
328 BDRVRawState *s = bs->opaque;
330 if (s->use_aio) {
331 laio_attach_aio_context(s->aio_ctx, new_context);
333 #endif
336 #ifdef CONFIG_LINUX_AIO
337 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
339 int ret = -1;
340 assert(aio_ctx != NULL);
341 assert(use_aio != NULL);
343 * Currently Linux do AIO only for files opened with O_DIRECT
344 * specified so check NOCACHE flag too
346 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
347 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
349 /* if non-NULL, laio_init() has already been run */
350 if (*aio_ctx == NULL) {
351 *aio_ctx = laio_init();
352 if (!*aio_ctx) {
353 goto error;
356 *use_aio = 1;
357 } else {
358 *use_aio = 0;
361 ret = 0;
363 error:
364 return ret;
366 #endif
368 static void raw_parse_filename(const char *filename, QDict *options,
369 Error **errp)
371 /* The filename does not have to be prefixed by the protocol name, since
372 * "file" is the default protocol; therefore, the return value of this
373 * function call can be ignored. */
374 strstart(filename, "file:", &filename);
376 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
379 static QemuOptsList raw_runtime_opts = {
380 .name = "raw",
381 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
382 .desc = {
384 .name = "filename",
385 .type = QEMU_OPT_STRING,
386 .help = "File name of the image",
388 { /* end of list */ }
392 static int raw_open_common(BlockDriverState *bs, QDict *options,
393 int bdrv_flags, int open_flags, Error **errp)
395 BDRVRawState *s = bs->opaque;
396 QemuOpts *opts;
397 Error *local_err = NULL;
398 const char *filename = NULL;
399 int fd, ret;
400 struct stat st;
402 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
403 qemu_opts_absorb_qdict(opts, options, &local_err);
404 if (local_err) {
405 error_propagate(errp, local_err);
406 ret = -EINVAL;
407 goto fail;
410 filename = qemu_opt_get(opts, "filename");
412 ret = raw_normalize_devicepath(&filename);
413 if (ret != 0) {
414 error_setg_errno(errp, -ret, "Could not normalize device path");
415 goto fail;
418 s->open_flags = open_flags;
419 raw_parse_flags(bdrv_flags, &s->open_flags);
421 s->fd = -1;
422 fd = qemu_open(filename, s->open_flags, 0644);
423 if (fd < 0) {
424 ret = -errno;
425 if (ret == -EROFS) {
426 ret = -EACCES;
428 goto fail;
430 s->fd = fd;
432 #ifdef CONFIG_LINUX_AIO
433 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
434 qemu_close(fd);
435 ret = -errno;
436 error_setg_errno(errp, -ret, "Could not set AIO state");
437 goto fail;
439 #endif
441 s->has_discard = true;
442 s->has_write_zeroes = true;
444 if (fstat(s->fd, &st) < 0) {
445 error_setg_errno(errp, errno, "Could not stat file");
446 goto fail;
448 if (S_ISREG(st.st_mode)) {
449 s->discard_zeroes = true;
451 if (S_ISBLK(st.st_mode)) {
452 #ifdef BLKDISCARDZEROES
453 unsigned int arg;
454 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
455 s->discard_zeroes = true;
457 #endif
458 #ifdef __linux__
459 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
460 * not rely on the contents of discarded blocks unless using O_DIRECT.
461 * Same for BLKZEROOUT.
463 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
464 s->discard_zeroes = false;
465 s->has_write_zeroes = false;
467 #endif
470 #ifdef CONFIG_XFS
471 if (platform_test_xfs_fd(s->fd)) {
472 s->is_xfs = true;
474 #endif
476 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
478 ret = 0;
479 fail:
480 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
481 unlink(filename);
483 qemu_opts_del(opts);
484 return ret;
487 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
488 Error **errp)
490 BDRVRawState *s = bs->opaque;
491 Error *local_err = NULL;
492 int ret;
494 s->type = FTYPE_FILE;
495 ret = raw_open_common(bs, options, flags, 0, &local_err);
496 if (local_err) {
497 error_propagate(errp, local_err);
499 return ret;
502 static int raw_reopen_prepare(BDRVReopenState *state,
503 BlockReopenQueue *queue, Error **errp)
505 BDRVRawState *s;
506 BDRVRawReopenState *raw_s;
507 int ret = 0;
509 assert(state != NULL);
510 assert(state->bs != NULL);
512 s = state->bs->opaque;
514 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
515 raw_s = state->opaque;
517 #ifdef CONFIG_LINUX_AIO
518 raw_s->use_aio = s->use_aio;
520 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
521 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
522 * won't override aio_ctx if aio_ctx is non-NULL */
523 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
524 error_setg(errp, "Could not set AIO state");
525 return -1;
527 #endif
529 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
530 raw_s->open_flags |= O_NONBLOCK;
533 raw_parse_flags(state->flags, &raw_s->open_flags);
535 raw_s->fd = -1;
537 int fcntl_flags = O_APPEND | O_NONBLOCK;
538 #ifdef O_NOATIME
539 fcntl_flags |= O_NOATIME;
540 #endif
542 #ifdef O_ASYNC
543 /* Not all operating systems have O_ASYNC, and those that don't
544 * will not let us track the state into raw_s->open_flags (typically
545 * you achieve the same effect with an ioctl, for example I_SETSIG
546 * on Solaris). But we do not use O_ASYNC, so that's fine.
548 assert((s->open_flags & O_ASYNC) == 0);
549 #endif
551 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
552 /* dup the original fd */
553 /* TODO: use qemu fcntl wrapper */
554 #ifdef F_DUPFD_CLOEXEC
555 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
556 #else
557 raw_s->fd = dup(s->fd);
558 if (raw_s->fd != -1) {
559 qemu_set_cloexec(raw_s->fd);
561 #endif
562 if (raw_s->fd >= 0) {
563 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
564 if (ret) {
565 qemu_close(raw_s->fd);
566 raw_s->fd = -1;
571 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
572 if (raw_s->fd == -1) {
573 assert(!(raw_s->open_flags & O_CREAT));
574 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
575 if (raw_s->fd == -1) {
576 error_setg_errno(errp, errno, "Could not reopen file");
577 ret = -1;
580 return ret;
583 static void raw_reopen_commit(BDRVReopenState *state)
585 BDRVRawReopenState *raw_s = state->opaque;
586 BDRVRawState *s = state->bs->opaque;
588 s->open_flags = raw_s->open_flags;
590 qemu_close(s->fd);
591 s->fd = raw_s->fd;
592 #ifdef CONFIG_LINUX_AIO
593 s->use_aio = raw_s->use_aio;
594 #endif
596 g_free(state->opaque);
597 state->opaque = NULL;
601 static void raw_reopen_abort(BDRVReopenState *state)
603 BDRVRawReopenState *raw_s = state->opaque;
605 /* nothing to do if NULL, we didn't get far enough */
606 if (raw_s == NULL) {
607 return;
610 if (raw_s->fd >= 0) {
611 qemu_close(raw_s->fd);
612 raw_s->fd = -1;
614 g_free(state->opaque);
615 state->opaque = NULL;
618 static int raw_refresh_limits(BlockDriverState *bs)
620 BDRVRawState *s = bs->opaque;
622 raw_probe_alignment(bs);
623 bs->bl.opt_mem_alignment = s->buf_align;
625 return 0;
628 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
630 int ret;
632 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
633 if (ret == -1) {
634 return -errno;
637 return 0;
640 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
642 int ret;
644 ret = qemu_fdatasync(aiocb->aio_fildes);
645 if (ret == -1) {
646 return -errno;
648 return 0;
651 #ifdef CONFIG_PREADV
653 static bool preadv_present = true;
655 static ssize_t
656 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
658 return preadv(fd, iov, nr_iov, offset);
661 static ssize_t
662 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
664 return pwritev(fd, iov, nr_iov, offset);
667 #else
669 static bool preadv_present = false;
671 static ssize_t
672 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
674 return -ENOSYS;
677 static ssize_t
678 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
680 return -ENOSYS;
683 #endif
685 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
687 ssize_t len;
689 do {
690 if (aiocb->aio_type & QEMU_AIO_WRITE)
691 len = qemu_pwritev(aiocb->aio_fildes,
692 aiocb->aio_iov,
693 aiocb->aio_niov,
694 aiocb->aio_offset);
695 else
696 len = qemu_preadv(aiocb->aio_fildes,
697 aiocb->aio_iov,
698 aiocb->aio_niov,
699 aiocb->aio_offset);
700 } while (len == -1 && errno == EINTR);
702 if (len == -1) {
703 return -errno;
705 return len;
709 * Read/writes the data to/from a given linear buffer.
711 * Returns the number of bytes handles or -errno in case of an error. Short
712 * reads are only returned if the end of the file is reached.
714 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
716 ssize_t offset = 0;
717 ssize_t len;
719 while (offset < aiocb->aio_nbytes) {
720 if (aiocb->aio_type & QEMU_AIO_WRITE) {
721 len = pwrite(aiocb->aio_fildes,
722 (const char *)buf + offset,
723 aiocb->aio_nbytes - offset,
724 aiocb->aio_offset + offset);
725 } else {
726 len = pread(aiocb->aio_fildes,
727 buf + offset,
728 aiocb->aio_nbytes - offset,
729 aiocb->aio_offset + offset);
731 if (len == -1 && errno == EINTR) {
732 continue;
733 } else if (len == -1) {
734 offset = -errno;
735 break;
736 } else if (len == 0) {
737 break;
739 offset += len;
742 return offset;
745 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
747 ssize_t nbytes;
748 char *buf;
750 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
752 * If there is just a single buffer, and it is properly aligned
753 * we can just use plain pread/pwrite without any problems.
755 if (aiocb->aio_niov == 1) {
756 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
759 * We have more than one iovec, and all are properly aligned.
761 * Try preadv/pwritev first and fall back to linearizing the
762 * buffer if it's not supported.
764 if (preadv_present) {
765 nbytes = handle_aiocb_rw_vector(aiocb);
766 if (nbytes == aiocb->aio_nbytes ||
767 (nbytes < 0 && nbytes != -ENOSYS)) {
768 return nbytes;
770 preadv_present = false;
774 * XXX(hch): short read/write. no easy way to handle the reminder
775 * using these interfaces. For now retry using plain
776 * pread/pwrite?
781 * Ok, we have to do it the hard way, copy all segments into
782 * a single aligned buffer.
784 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
785 if (aiocb->aio_type & QEMU_AIO_WRITE) {
786 char *p = buf;
787 int i;
789 for (i = 0; i < aiocb->aio_niov; ++i) {
790 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
791 p += aiocb->aio_iov[i].iov_len;
795 nbytes = handle_aiocb_rw_linear(aiocb, buf);
796 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
797 char *p = buf;
798 size_t count = aiocb->aio_nbytes, copy;
799 int i;
801 for (i = 0; i < aiocb->aio_niov && count; ++i) {
802 copy = count;
803 if (copy > aiocb->aio_iov[i].iov_len) {
804 copy = aiocb->aio_iov[i].iov_len;
806 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
807 p += copy;
808 count -= copy;
811 qemu_vfree(buf);
813 return nbytes;
816 #ifdef CONFIG_XFS
817 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
819 struct xfs_flock64 fl;
821 memset(&fl, 0, sizeof(fl));
822 fl.l_whence = SEEK_SET;
823 fl.l_start = offset;
824 fl.l_len = bytes;
826 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
827 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
828 return -errno;
831 return 0;
834 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
836 struct xfs_flock64 fl;
838 memset(&fl, 0, sizeof(fl));
839 fl.l_whence = SEEK_SET;
840 fl.l_start = offset;
841 fl.l_len = bytes;
843 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
844 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
845 return -errno;
848 return 0;
850 #endif
852 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
854 int ret = -EOPNOTSUPP;
855 BDRVRawState *s = aiocb->bs->opaque;
857 if (s->has_write_zeroes == 0) {
858 return -ENOTSUP;
861 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
862 #ifdef BLKZEROOUT
863 do {
864 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
865 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
866 return 0;
868 } while (errno == EINTR);
870 ret = -errno;
871 #endif
872 } else {
873 #ifdef CONFIG_XFS
874 if (s->is_xfs) {
875 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
877 #endif
880 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
881 ret == -ENOTTY) {
882 s->has_write_zeroes = false;
883 ret = -ENOTSUP;
885 return ret;
888 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
890 int ret = -EOPNOTSUPP;
891 BDRVRawState *s = aiocb->bs->opaque;
893 if (!s->has_discard) {
894 return -ENOTSUP;
897 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
898 #ifdef BLKDISCARD
899 do {
900 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
901 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
902 return 0;
904 } while (errno == EINTR);
906 ret = -errno;
907 #endif
908 } else {
909 #ifdef CONFIG_XFS
910 if (s->is_xfs) {
911 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
913 #endif
915 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
916 do {
917 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
918 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
919 return 0;
921 } while (errno == EINTR);
923 ret = -errno;
924 #endif
927 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
928 ret == -ENOTTY) {
929 s->has_discard = false;
930 ret = -ENOTSUP;
932 return ret;
935 static int aio_worker(void *arg)
937 RawPosixAIOData *aiocb = arg;
938 ssize_t ret = 0;
940 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
941 case QEMU_AIO_READ:
942 ret = handle_aiocb_rw(aiocb);
943 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
944 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
945 0, aiocb->aio_nbytes - ret);
947 ret = aiocb->aio_nbytes;
949 if (ret == aiocb->aio_nbytes) {
950 ret = 0;
951 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
952 ret = -EINVAL;
954 break;
955 case QEMU_AIO_WRITE:
956 ret = handle_aiocb_rw(aiocb);
957 if (ret == aiocb->aio_nbytes) {
958 ret = 0;
959 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
960 ret = -EINVAL;
962 break;
963 case QEMU_AIO_FLUSH:
964 ret = handle_aiocb_flush(aiocb);
965 break;
966 case QEMU_AIO_IOCTL:
967 ret = handle_aiocb_ioctl(aiocb);
968 break;
969 case QEMU_AIO_DISCARD:
970 ret = handle_aiocb_discard(aiocb);
971 break;
972 case QEMU_AIO_WRITE_ZEROES:
973 ret = handle_aiocb_write_zeroes(aiocb);
974 break;
975 default:
976 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
977 ret = -EINVAL;
978 break;
981 g_slice_free(RawPosixAIOData, aiocb);
982 return ret;
985 static int paio_submit_co(BlockDriverState *bs, int fd,
986 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
987 int type)
989 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
990 ThreadPool *pool;
992 acb->bs = bs;
993 acb->aio_type = type;
994 acb->aio_fildes = fd;
996 if (qiov) {
997 acb->aio_iov = qiov->iov;
998 acb->aio_niov = qiov->niov;
1000 acb->aio_nbytes = nb_sectors * 512;
1001 acb->aio_offset = sector_num * 512;
1003 trace_paio_submit_co(sector_num, nb_sectors, type);
1004 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1005 return thread_pool_submit_co(pool, aio_worker, acb);
1008 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
1009 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1010 BlockDriverCompletionFunc *cb, void *opaque, int type)
1012 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1013 ThreadPool *pool;
1015 acb->bs = bs;
1016 acb->aio_type = type;
1017 acb->aio_fildes = fd;
1019 if (qiov) {
1020 acb->aio_iov = qiov->iov;
1021 acb->aio_niov = qiov->niov;
1023 acb->aio_nbytes = nb_sectors * 512;
1024 acb->aio_offset = sector_num * 512;
1026 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1027 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1028 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1031 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
1032 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1033 BlockDriverCompletionFunc *cb, void *opaque, int type)
1035 BDRVRawState *s = bs->opaque;
1037 if (fd_open(bs) < 0)
1038 return NULL;
1041 * If O_DIRECT is used the buffer needs to be aligned on a sector
1042 * boundary. Check if this is the case or tell the low-level
1043 * driver that it needs to copy the buffer.
1045 if ((bs->open_flags & BDRV_O_NOCACHE)) {
1046 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1047 type |= QEMU_AIO_MISALIGNED;
1048 #ifdef CONFIG_LINUX_AIO
1049 } else if (s->use_aio) {
1050 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1051 nb_sectors, cb, opaque, type);
1052 #endif
1056 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1057 cb, opaque, type);
1060 static void raw_aio_plug(BlockDriverState *bs)
1062 #ifdef CONFIG_LINUX_AIO
1063 BDRVRawState *s = bs->opaque;
1064 if (s->use_aio) {
1065 laio_io_plug(bs, s->aio_ctx);
1067 #endif
1070 static void raw_aio_unplug(BlockDriverState *bs)
1072 #ifdef CONFIG_LINUX_AIO
1073 BDRVRawState *s = bs->opaque;
1074 if (s->use_aio) {
1075 laio_io_unplug(bs, s->aio_ctx, true);
1077 #endif
1080 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1082 #ifdef CONFIG_LINUX_AIO
1083 BDRVRawState *s = bs->opaque;
1084 if (s->use_aio) {
1085 laio_io_unplug(bs, s->aio_ctx, false);
1087 #endif
1090 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
1091 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1092 BlockDriverCompletionFunc *cb, void *opaque)
1094 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1095 cb, opaque, QEMU_AIO_READ);
1098 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
1099 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1100 BlockDriverCompletionFunc *cb, void *opaque)
1102 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1103 cb, opaque, QEMU_AIO_WRITE);
1106 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
1107 BlockDriverCompletionFunc *cb, void *opaque)
1109 BDRVRawState *s = bs->opaque;
1111 if (fd_open(bs) < 0)
1112 return NULL;
1114 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1117 static void raw_close(BlockDriverState *bs)
1119 BDRVRawState *s = bs->opaque;
1121 raw_detach_aio_context(bs);
1123 #ifdef CONFIG_LINUX_AIO
1124 if (s->use_aio) {
1125 laio_cleanup(s->aio_ctx);
1127 #endif
1128 if (s->fd >= 0) {
1129 qemu_close(s->fd);
1130 s->fd = -1;
1134 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1136 BDRVRawState *s = bs->opaque;
1137 struct stat st;
1139 if (fstat(s->fd, &st)) {
1140 return -errno;
1143 if (S_ISREG(st.st_mode)) {
1144 if (ftruncate(s->fd, offset) < 0) {
1145 return -errno;
1147 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1148 if (offset > raw_getlength(bs)) {
1149 return -EINVAL;
1151 } else {
1152 return -ENOTSUP;
1155 return 0;
1158 #ifdef __OpenBSD__
1159 static int64_t raw_getlength(BlockDriverState *bs)
1161 BDRVRawState *s = bs->opaque;
1162 int fd = s->fd;
1163 struct stat st;
1165 if (fstat(fd, &st))
1166 return -errno;
1167 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1168 struct disklabel dl;
1170 if (ioctl(fd, DIOCGDINFO, &dl))
1171 return -errno;
1172 return (uint64_t)dl.d_secsize *
1173 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1174 } else
1175 return st.st_size;
1177 #elif defined(__NetBSD__)
1178 static int64_t raw_getlength(BlockDriverState *bs)
1180 BDRVRawState *s = bs->opaque;
1181 int fd = s->fd;
1182 struct stat st;
1184 if (fstat(fd, &st))
1185 return -errno;
1186 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1187 struct dkwedge_info dkw;
1189 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1190 return dkw.dkw_size * 512;
1191 } else {
1192 struct disklabel dl;
1194 if (ioctl(fd, DIOCGDINFO, &dl))
1195 return -errno;
1196 return (uint64_t)dl.d_secsize *
1197 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1199 } else
1200 return st.st_size;
1202 #elif defined(__sun__)
1203 static int64_t raw_getlength(BlockDriverState *bs)
1205 BDRVRawState *s = bs->opaque;
1206 struct dk_minfo minfo;
1207 int ret;
1208 int64_t size;
1210 ret = fd_open(bs);
1211 if (ret < 0) {
1212 return ret;
1216 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1218 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1219 if (ret != -1) {
1220 return minfo.dki_lbsize * minfo.dki_capacity;
1224 * There are reports that lseek on some devices fails, but
1225 * irc discussion said that contingency on contingency was overkill.
1227 size = lseek(s->fd, 0, SEEK_END);
1228 if (size < 0) {
1229 return -errno;
1231 return size;
1233 #elif defined(CONFIG_BSD)
1234 static int64_t raw_getlength(BlockDriverState *bs)
1236 BDRVRawState *s = bs->opaque;
1237 int fd = s->fd;
1238 int64_t size;
1239 struct stat sb;
1240 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1241 int reopened = 0;
1242 #endif
1243 int ret;
1245 ret = fd_open(bs);
1246 if (ret < 0)
1247 return ret;
1249 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1250 again:
1251 #endif
1252 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1253 #ifdef DIOCGMEDIASIZE
1254 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1255 #elif defined(DIOCGPART)
1257 struct partinfo pi;
1258 if (ioctl(fd, DIOCGPART, &pi) == 0)
1259 size = pi.media_size;
1260 else
1261 size = 0;
1263 if (size == 0)
1264 #endif
1265 #if defined(__APPLE__) && defined(__MACH__)
1266 size = LLONG_MAX;
1267 #else
1268 size = lseek(fd, 0LL, SEEK_END);
1269 if (size < 0) {
1270 return -errno;
1272 #endif
1273 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1274 switch(s->type) {
1275 case FTYPE_CD:
1276 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1277 if (size == 2048LL * (unsigned)-1)
1278 size = 0;
1279 /* XXX no disc? maybe we need to reopen... */
1280 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1281 reopened = 1;
1282 goto again;
1285 #endif
1286 } else {
1287 size = lseek(fd, 0, SEEK_END);
1288 if (size < 0) {
1289 return -errno;
1292 return size;
1294 #else
1295 static int64_t raw_getlength(BlockDriverState *bs)
1297 BDRVRawState *s = bs->opaque;
1298 int ret;
1299 int64_t size;
1301 ret = fd_open(bs);
1302 if (ret < 0) {
1303 return ret;
1306 size = lseek(s->fd, 0, SEEK_END);
1307 if (size < 0) {
1308 return -errno;
1310 return size;
1312 #endif
1314 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1316 struct stat st;
1317 BDRVRawState *s = bs->opaque;
1319 if (fstat(s->fd, &st) < 0) {
1320 return -errno;
1322 return (int64_t)st.st_blocks * 512;
1325 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1327 int fd;
1328 int result = 0;
1329 int64_t total_size = 0;
1330 bool nocow = false;
1332 strstart(filename, "file:", &filename);
1334 /* Read out options */
1335 total_size =
1336 qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;
1337 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1339 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1340 0644);
1341 if (fd < 0) {
1342 result = -errno;
1343 error_setg_errno(errp, -result, "Could not create file");
1344 } else {
1345 if (nocow) {
1346 #ifdef __linux__
1347 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1348 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1349 * will be ignored since any failure of this operation should not
1350 * block the left work.
1352 int attr;
1353 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1354 attr |= FS_NOCOW_FL;
1355 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1357 #endif
1360 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
1361 result = -errno;
1362 error_setg_errno(errp, -result, "Could not resize file");
1364 if (qemu_close(fd) != 0) {
1365 result = -errno;
1366 error_setg_errno(errp, -result, "Could not close the new file");
1369 return result;
1372 static int64_t try_fiemap(BlockDriverState *bs, off_t start, off_t *data,
1373 off_t *hole, int nb_sectors, int *pnum)
1375 #ifdef CONFIG_FIEMAP
1376 BDRVRawState *s = bs->opaque;
1377 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1378 struct {
1379 struct fiemap fm;
1380 struct fiemap_extent fe;
1381 } f;
1383 if (s->skip_fiemap) {
1384 return -ENOTSUP;
1387 f.fm.fm_start = start;
1388 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1389 f.fm.fm_flags = 0;
1390 f.fm.fm_extent_count = 1;
1391 f.fm.fm_reserved = 0;
1392 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1393 s->skip_fiemap = true;
1394 return -errno;
1397 if (f.fm.fm_mapped_extents == 0) {
1398 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1399 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1401 off_t length = lseek(s->fd, 0, SEEK_END);
1402 *hole = f.fm.fm_start;
1403 *data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1404 } else {
1405 *data = f.fe.fe_logical;
1406 *hole = f.fe.fe_logical + f.fe.fe_length;
1407 if (f.fe.fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
1408 ret |= BDRV_BLOCK_ZERO;
1412 return ret;
1413 #else
1414 return -ENOTSUP;
1415 #endif
1418 static int64_t try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,
1419 off_t *hole, int *pnum)
1421 #if defined SEEK_HOLE && defined SEEK_DATA
1422 BDRVRawState *s = bs->opaque;
1424 *hole = lseek(s->fd, start, SEEK_HOLE);
1425 if (*hole == -1) {
1426 /* -ENXIO indicates that sector_num was past the end of the file.
1427 * There is a virtual hole there. */
1428 assert(errno != -ENXIO);
1430 return -errno;
1433 if (*hole > start) {
1434 *data = start;
1435 } else {
1436 /* On a hole. We need another syscall to find its end. */
1437 *data = lseek(s->fd, start, SEEK_DATA);
1438 if (*data == -1) {
1439 *data = lseek(s->fd, 0, SEEK_END);
1443 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1444 #else
1445 return -ENOTSUP;
1446 #endif
1450 * Returns true iff the specified sector is present in the disk image. Drivers
1451 * not implementing the functionality are assumed to not support backing files,
1452 * hence all their sectors are reported as allocated.
1454 * If 'sector_num' is beyond the end of the disk image the return value is 0
1455 * and 'pnum' is set to 0.
1457 * 'pnum' is set to the number of sectors (including and immediately following
1458 * the specified sector) that are known to be in the same
1459 * allocated/unallocated state.
1461 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1462 * beyond the end of the disk image it will be clamped.
1464 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1465 int64_t sector_num,
1466 int nb_sectors, int *pnum)
1468 off_t start, data = 0, hole = 0;
1469 int64_t ret;
1471 ret = fd_open(bs);
1472 if (ret < 0) {
1473 return ret;
1476 start = sector_num * BDRV_SECTOR_SIZE;
1478 ret = try_fiemap(bs, start, &data, &hole, nb_sectors, pnum);
1479 if (ret < 0) {
1480 ret = try_seek_hole(bs, start, &data, &hole, pnum);
1481 if (ret < 0) {
1482 /* Assume everything is allocated. */
1483 data = 0;
1484 hole = start + nb_sectors * BDRV_SECTOR_SIZE;
1485 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1489 if (data <= start) {
1490 /* On a data extent, compute sectors to the end of the extent. */
1491 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1492 } else {
1493 /* On a hole, compute sectors to the beginning of the next extent. */
1494 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1495 ret &= ~BDRV_BLOCK_DATA;
1496 ret |= BDRV_BLOCK_ZERO;
1499 return ret;
1502 static coroutine_fn BlockDriverAIOCB *raw_aio_discard(BlockDriverState *bs,
1503 int64_t sector_num, int nb_sectors,
1504 BlockDriverCompletionFunc *cb, void *opaque)
1506 BDRVRawState *s = bs->opaque;
1508 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1509 cb, opaque, QEMU_AIO_DISCARD);
1512 static int coroutine_fn raw_co_write_zeroes(
1513 BlockDriverState *bs, int64_t sector_num,
1514 int nb_sectors, BdrvRequestFlags flags)
1516 BDRVRawState *s = bs->opaque;
1518 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1519 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1520 QEMU_AIO_WRITE_ZEROES);
1521 } else if (s->discard_zeroes) {
1522 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1523 QEMU_AIO_DISCARD);
1525 return -ENOTSUP;
1528 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1530 BDRVRawState *s = bs->opaque;
1532 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1533 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1534 return 0;
1537 static QemuOptsList raw_create_opts = {
1538 .name = "raw-create-opts",
1539 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1540 .desc = {
1542 .name = BLOCK_OPT_SIZE,
1543 .type = QEMU_OPT_SIZE,
1544 .help = "Virtual disk size"
1547 .name = BLOCK_OPT_NOCOW,
1548 .type = QEMU_OPT_BOOL,
1549 .help = "Turn off copy-on-write (valid only on btrfs)"
1551 { /* end of list */ }
1555 static BlockDriver bdrv_file = {
1556 .format_name = "file",
1557 .protocol_name = "file",
1558 .instance_size = sizeof(BDRVRawState),
1559 .bdrv_needs_filename = true,
1560 .bdrv_probe = NULL, /* no probe for protocols */
1561 .bdrv_parse_filename = raw_parse_filename,
1562 .bdrv_file_open = raw_open,
1563 .bdrv_reopen_prepare = raw_reopen_prepare,
1564 .bdrv_reopen_commit = raw_reopen_commit,
1565 .bdrv_reopen_abort = raw_reopen_abort,
1566 .bdrv_close = raw_close,
1567 .bdrv_create = raw_create,
1568 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1569 .bdrv_co_get_block_status = raw_co_get_block_status,
1570 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1572 .bdrv_aio_readv = raw_aio_readv,
1573 .bdrv_aio_writev = raw_aio_writev,
1574 .bdrv_aio_flush = raw_aio_flush,
1575 .bdrv_aio_discard = raw_aio_discard,
1576 .bdrv_refresh_limits = raw_refresh_limits,
1577 .bdrv_io_plug = raw_aio_plug,
1578 .bdrv_io_unplug = raw_aio_unplug,
1579 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1581 .bdrv_truncate = raw_truncate,
1582 .bdrv_getlength = raw_getlength,
1583 .bdrv_get_info = raw_get_info,
1584 .bdrv_get_allocated_file_size
1585 = raw_get_allocated_file_size,
1587 .bdrv_detach_aio_context = raw_detach_aio_context,
1588 .bdrv_attach_aio_context = raw_attach_aio_context,
1590 .create_opts = &raw_create_opts,
1593 /***********************************************/
1594 /* host device */
1596 #if defined(__APPLE__) && defined(__MACH__)
1597 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1598 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1600 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1602 kern_return_t kernResult;
1603 mach_port_t masterPort;
1604 CFMutableDictionaryRef classesToMatch;
1606 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1607 if ( KERN_SUCCESS != kernResult ) {
1608 printf( "IOMasterPort returned %d\n", kernResult );
1611 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1612 if ( classesToMatch == NULL ) {
1613 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1614 } else {
1615 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1617 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1618 if ( KERN_SUCCESS != kernResult )
1620 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1623 return kernResult;
1626 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1628 io_object_t nextMedia;
1629 kern_return_t kernResult = KERN_FAILURE;
1630 *bsdPath = '\0';
1631 nextMedia = IOIteratorNext( mediaIterator );
1632 if ( nextMedia )
1634 CFTypeRef bsdPathAsCFString;
1635 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1636 if ( bsdPathAsCFString ) {
1637 size_t devPathLength;
1638 strcpy( bsdPath, _PATH_DEV );
1639 strcat( bsdPath, "r" );
1640 devPathLength = strlen( bsdPath );
1641 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1642 kernResult = KERN_SUCCESS;
1644 CFRelease( bsdPathAsCFString );
1646 IOObjectRelease( nextMedia );
1649 return kernResult;
1652 #endif
1654 static int hdev_probe_device(const char *filename)
1656 struct stat st;
1658 /* allow a dedicated CD-ROM driver to match with a higher priority */
1659 if (strstart(filename, "/dev/cdrom", NULL))
1660 return 50;
1662 if (stat(filename, &st) >= 0 &&
1663 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1664 return 100;
1667 return 0;
1670 static int check_hdev_writable(BDRVRawState *s)
1672 #if defined(BLKROGET)
1673 /* Linux block devices can be configured "read-only" using blockdev(8).
1674 * This is independent of device node permissions and therefore open(2)
1675 * with O_RDWR succeeds. Actual writes fail with EPERM.
1677 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1678 * check for read-only block devices so that Linux block devices behave
1679 * properly.
1681 struct stat st;
1682 int readonly = 0;
1684 if (fstat(s->fd, &st)) {
1685 return -errno;
1688 if (!S_ISBLK(st.st_mode)) {
1689 return 0;
1692 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1693 return -errno;
1696 if (readonly) {
1697 return -EACCES;
1699 #endif /* defined(BLKROGET) */
1700 return 0;
1703 static void hdev_parse_filename(const char *filename, QDict *options,
1704 Error **errp)
1706 /* The prefix is optional, just as for "file". */
1707 strstart(filename, "host_device:", &filename);
1709 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1712 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1713 Error **errp)
1715 BDRVRawState *s = bs->opaque;
1716 Error *local_err = NULL;
1717 int ret;
1718 const char *filename = qdict_get_str(options, "filename");
1720 #if defined(__APPLE__) && defined(__MACH__)
1721 if (strstart(filename, "/dev/cdrom", NULL)) {
1722 kern_return_t kernResult;
1723 io_iterator_t mediaIterator;
1724 char bsdPath[ MAXPATHLEN ];
1725 int fd;
1727 kernResult = FindEjectableCDMedia( &mediaIterator );
1728 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1730 if ( bsdPath[ 0 ] != '\0' ) {
1731 strcat(bsdPath,"s0");
1732 /* some CDs don't have a partition 0 */
1733 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1734 if (fd < 0) {
1735 bsdPath[strlen(bsdPath)-1] = '1';
1736 } else {
1737 qemu_close(fd);
1739 filename = bsdPath;
1740 qdict_put(options, "filename", qstring_from_str(filename));
1743 if ( mediaIterator )
1744 IOObjectRelease( mediaIterator );
1746 #endif
1748 s->type = FTYPE_FILE;
1749 #if defined(__linux__)
1751 char resolved_path[ MAXPATHLEN ], *temp;
1753 temp = realpath(filename, resolved_path);
1754 if (temp && strstart(temp, "/dev/sg", NULL)) {
1755 bs->sg = 1;
1758 #endif
1760 ret = raw_open_common(bs, options, flags, 0, &local_err);
1761 if (ret < 0) {
1762 if (local_err) {
1763 error_propagate(errp, local_err);
1765 return ret;
1768 if (flags & BDRV_O_RDWR) {
1769 ret = check_hdev_writable(s);
1770 if (ret < 0) {
1771 raw_close(bs);
1772 error_setg_errno(errp, -ret, "The device is not writable");
1773 return ret;
1777 return ret;
1780 #if defined(__linux__)
1781 /* Note: we do not have a reliable method to detect if the floppy is
1782 present. The current method is to try to open the floppy at every
1783 I/O and to keep it opened during a few hundreds of ms. */
1784 static int fd_open(BlockDriverState *bs)
1786 BDRVRawState *s = bs->opaque;
1787 int last_media_present;
1789 if (s->type != FTYPE_FD)
1790 return 0;
1791 last_media_present = (s->fd >= 0);
1792 if (s->fd >= 0 &&
1793 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1794 qemu_close(s->fd);
1795 s->fd = -1;
1796 #ifdef DEBUG_FLOPPY
1797 printf("Floppy closed\n");
1798 #endif
1800 if (s->fd < 0) {
1801 if (s->fd_got_error &&
1802 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1803 #ifdef DEBUG_FLOPPY
1804 printf("No floppy (open delayed)\n");
1805 #endif
1806 return -EIO;
1808 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1809 if (s->fd < 0) {
1810 s->fd_error_time = get_clock();
1811 s->fd_got_error = 1;
1812 if (last_media_present)
1813 s->fd_media_changed = 1;
1814 #ifdef DEBUG_FLOPPY
1815 printf("No floppy\n");
1816 #endif
1817 return -EIO;
1819 #ifdef DEBUG_FLOPPY
1820 printf("Floppy opened\n");
1821 #endif
1823 if (!last_media_present)
1824 s->fd_media_changed = 1;
1825 s->fd_open_time = get_clock();
1826 s->fd_got_error = 0;
1827 return 0;
1830 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1832 BDRVRawState *s = bs->opaque;
1834 return ioctl(s->fd, req, buf);
1837 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1838 unsigned long int req, void *buf,
1839 BlockDriverCompletionFunc *cb, void *opaque)
1841 BDRVRawState *s = bs->opaque;
1842 RawPosixAIOData *acb;
1843 ThreadPool *pool;
1845 if (fd_open(bs) < 0)
1846 return NULL;
1848 acb = g_slice_new(RawPosixAIOData);
1849 acb->bs = bs;
1850 acb->aio_type = QEMU_AIO_IOCTL;
1851 acb->aio_fildes = s->fd;
1852 acb->aio_offset = 0;
1853 acb->aio_ioctl_buf = buf;
1854 acb->aio_ioctl_cmd = req;
1855 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1856 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1859 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1860 static int fd_open(BlockDriverState *bs)
1862 BDRVRawState *s = bs->opaque;
1864 /* this is just to ensure s->fd is sane (its called by io ops) */
1865 if (s->fd >= 0)
1866 return 0;
1867 return -EIO;
1869 #else /* !linux && !FreeBSD */
1871 static int fd_open(BlockDriverState *bs)
1873 return 0;
1876 #endif /* !linux && !FreeBSD */
1878 static coroutine_fn BlockDriverAIOCB *hdev_aio_discard(BlockDriverState *bs,
1879 int64_t sector_num, int nb_sectors,
1880 BlockDriverCompletionFunc *cb, void *opaque)
1882 BDRVRawState *s = bs->opaque;
1884 if (fd_open(bs) < 0) {
1885 return NULL;
1887 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1888 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1891 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
1892 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1894 BDRVRawState *s = bs->opaque;
1895 int rc;
1897 rc = fd_open(bs);
1898 if (rc < 0) {
1899 return rc;
1901 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1902 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1903 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
1904 } else if (s->discard_zeroes) {
1905 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1906 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1908 return -ENOTSUP;
1911 static int hdev_create(const char *filename, QemuOpts *opts,
1912 Error **errp)
1914 int fd;
1915 int ret = 0;
1916 struct stat stat_buf;
1917 int64_t total_size = 0;
1918 bool has_prefix;
1920 /* This function is used by all three protocol block drivers and therefore
1921 * any of these three prefixes may be given.
1922 * The return value has to be stored somewhere, otherwise this is an error
1923 * due to -Werror=unused-value. */
1924 has_prefix =
1925 strstart(filename, "host_device:", &filename) ||
1926 strstart(filename, "host_cdrom:" , &filename) ||
1927 strstart(filename, "host_floppy:", &filename);
1929 (void)has_prefix;
1931 /* Read out options */
1932 total_size =
1933 qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;
1935 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1936 if (fd < 0) {
1937 ret = -errno;
1938 error_setg_errno(errp, -ret, "Could not open device");
1939 return ret;
1942 if (fstat(fd, &stat_buf) < 0) {
1943 ret = -errno;
1944 error_setg_errno(errp, -ret, "Could not stat device");
1945 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
1946 error_setg(errp,
1947 "The given file is neither a block nor a character device");
1948 ret = -ENODEV;
1949 } else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE) {
1950 error_setg(errp, "Device is too small");
1951 ret = -ENOSPC;
1954 qemu_close(fd);
1955 return ret;
1958 static BlockDriver bdrv_host_device = {
1959 .format_name = "host_device",
1960 .protocol_name = "host_device",
1961 .instance_size = sizeof(BDRVRawState),
1962 .bdrv_needs_filename = true,
1963 .bdrv_probe_device = hdev_probe_device,
1964 .bdrv_parse_filename = hdev_parse_filename,
1965 .bdrv_file_open = hdev_open,
1966 .bdrv_close = raw_close,
1967 .bdrv_reopen_prepare = raw_reopen_prepare,
1968 .bdrv_reopen_commit = raw_reopen_commit,
1969 .bdrv_reopen_abort = raw_reopen_abort,
1970 .bdrv_create = hdev_create,
1971 .create_opts = &raw_create_opts,
1972 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
1974 .bdrv_aio_readv = raw_aio_readv,
1975 .bdrv_aio_writev = raw_aio_writev,
1976 .bdrv_aio_flush = raw_aio_flush,
1977 .bdrv_aio_discard = hdev_aio_discard,
1978 .bdrv_refresh_limits = raw_refresh_limits,
1979 .bdrv_io_plug = raw_aio_plug,
1980 .bdrv_io_unplug = raw_aio_unplug,
1981 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1983 .bdrv_truncate = raw_truncate,
1984 .bdrv_getlength = raw_getlength,
1985 .bdrv_get_info = raw_get_info,
1986 .bdrv_get_allocated_file_size
1987 = raw_get_allocated_file_size,
1989 .bdrv_detach_aio_context = raw_detach_aio_context,
1990 .bdrv_attach_aio_context = raw_attach_aio_context,
1992 /* generic scsi device */
1993 #ifdef __linux__
1994 .bdrv_ioctl = hdev_ioctl,
1995 .bdrv_aio_ioctl = hdev_aio_ioctl,
1996 #endif
1999 #ifdef __linux__
2000 static void floppy_parse_filename(const char *filename, QDict *options,
2001 Error **errp)
2003 /* The prefix is optional, just as for "file". */
2004 strstart(filename, "host_floppy:", &filename);
2006 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2009 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2010 Error **errp)
2012 BDRVRawState *s = bs->opaque;
2013 Error *local_err = NULL;
2014 int ret;
2016 s->type = FTYPE_FD;
2018 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2019 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2020 if (ret) {
2021 if (local_err) {
2022 error_propagate(errp, local_err);
2024 return ret;
2027 /* close fd so that we can reopen it as needed */
2028 qemu_close(s->fd);
2029 s->fd = -1;
2030 s->fd_media_changed = 1;
2032 return 0;
2035 static int floppy_probe_device(const char *filename)
2037 int fd, ret;
2038 int prio = 0;
2039 struct floppy_struct fdparam;
2040 struct stat st;
2042 if (strstart(filename, "/dev/fd", NULL) &&
2043 !strstart(filename, "/dev/fdset/", NULL)) {
2044 prio = 50;
2047 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2048 if (fd < 0) {
2049 goto out;
2051 ret = fstat(fd, &st);
2052 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2053 goto outc;
2056 /* Attempt to detect via a floppy specific ioctl */
2057 ret = ioctl(fd, FDGETPRM, &fdparam);
2058 if (ret >= 0)
2059 prio = 100;
2061 outc:
2062 qemu_close(fd);
2063 out:
2064 return prio;
2068 static int floppy_is_inserted(BlockDriverState *bs)
2070 return fd_open(bs) >= 0;
2073 static int floppy_media_changed(BlockDriverState *bs)
2075 BDRVRawState *s = bs->opaque;
2076 int ret;
2079 * XXX: we do not have a true media changed indication.
2080 * It does not work if the floppy is changed without trying to read it.
2082 fd_open(bs);
2083 ret = s->fd_media_changed;
2084 s->fd_media_changed = 0;
2085 #ifdef DEBUG_FLOPPY
2086 printf("Floppy changed=%d\n", ret);
2087 #endif
2088 return ret;
2091 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2093 BDRVRawState *s = bs->opaque;
2094 int fd;
2096 if (s->fd >= 0) {
2097 qemu_close(s->fd);
2098 s->fd = -1;
2100 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2101 if (fd >= 0) {
2102 if (ioctl(fd, FDEJECT, 0) < 0)
2103 perror("FDEJECT");
2104 qemu_close(fd);
2108 static BlockDriver bdrv_host_floppy = {
2109 .format_name = "host_floppy",
2110 .protocol_name = "host_floppy",
2111 .instance_size = sizeof(BDRVRawState),
2112 .bdrv_needs_filename = true,
2113 .bdrv_probe_device = floppy_probe_device,
2114 .bdrv_parse_filename = floppy_parse_filename,
2115 .bdrv_file_open = floppy_open,
2116 .bdrv_close = raw_close,
2117 .bdrv_reopen_prepare = raw_reopen_prepare,
2118 .bdrv_reopen_commit = raw_reopen_commit,
2119 .bdrv_reopen_abort = raw_reopen_abort,
2120 .bdrv_create = hdev_create,
2121 .create_opts = &raw_create_opts,
2123 .bdrv_aio_readv = raw_aio_readv,
2124 .bdrv_aio_writev = raw_aio_writev,
2125 .bdrv_aio_flush = raw_aio_flush,
2126 .bdrv_refresh_limits = raw_refresh_limits,
2127 .bdrv_io_plug = raw_aio_plug,
2128 .bdrv_io_unplug = raw_aio_unplug,
2129 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2131 .bdrv_truncate = raw_truncate,
2132 .bdrv_getlength = raw_getlength,
2133 .has_variable_length = true,
2134 .bdrv_get_allocated_file_size
2135 = raw_get_allocated_file_size,
2137 .bdrv_detach_aio_context = raw_detach_aio_context,
2138 .bdrv_attach_aio_context = raw_attach_aio_context,
2140 /* removable device support */
2141 .bdrv_is_inserted = floppy_is_inserted,
2142 .bdrv_media_changed = floppy_media_changed,
2143 .bdrv_eject = floppy_eject,
2145 #endif
2147 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2148 static void cdrom_parse_filename(const char *filename, QDict *options,
2149 Error **errp)
2151 /* The prefix is optional, just as for "file". */
2152 strstart(filename, "host_cdrom:", &filename);
2154 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2156 #endif
2158 #ifdef __linux__
2159 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2160 Error **errp)
2162 BDRVRawState *s = bs->opaque;
2163 Error *local_err = NULL;
2164 int ret;
2166 s->type = FTYPE_CD;
2168 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2169 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2170 if (local_err) {
2171 error_propagate(errp, local_err);
2173 return ret;
2176 static int cdrom_probe_device(const char *filename)
2178 int fd, ret;
2179 int prio = 0;
2180 struct stat st;
2182 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2183 if (fd < 0) {
2184 goto out;
2186 ret = fstat(fd, &st);
2187 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2188 goto outc;
2191 /* Attempt to detect via a CDROM specific ioctl */
2192 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2193 if (ret >= 0)
2194 prio = 100;
2196 outc:
2197 qemu_close(fd);
2198 out:
2199 return prio;
2202 static int cdrom_is_inserted(BlockDriverState *bs)
2204 BDRVRawState *s = bs->opaque;
2205 int ret;
2207 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2208 if (ret == CDS_DISC_OK)
2209 return 1;
2210 return 0;
2213 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2215 BDRVRawState *s = bs->opaque;
2217 if (eject_flag) {
2218 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2219 perror("CDROMEJECT");
2220 } else {
2221 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2222 perror("CDROMEJECT");
2226 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2228 BDRVRawState *s = bs->opaque;
2230 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2232 * Note: an error can happen if the distribution automatically
2233 * mounts the CD-ROM
2235 /* perror("CDROM_LOCKDOOR"); */
2239 static BlockDriver bdrv_host_cdrom = {
2240 .format_name = "host_cdrom",
2241 .protocol_name = "host_cdrom",
2242 .instance_size = sizeof(BDRVRawState),
2243 .bdrv_needs_filename = true,
2244 .bdrv_probe_device = cdrom_probe_device,
2245 .bdrv_parse_filename = cdrom_parse_filename,
2246 .bdrv_file_open = cdrom_open,
2247 .bdrv_close = raw_close,
2248 .bdrv_reopen_prepare = raw_reopen_prepare,
2249 .bdrv_reopen_commit = raw_reopen_commit,
2250 .bdrv_reopen_abort = raw_reopen_abort,
2251 .bdrv_create = hdev_create,
2252 .create_opts = &raw_create_opts,
2254 .bdrv_aio_readv = raw_aio_readv,
2255 .bdrv_aio_writev = raw_aio_writev,
2256 .bdrv_aio_flush = raw_aio_flush,
2257 .bdrv_refresh_limits = raw_refresh_limits,
2258 .bdrv_io_plug = raw_aio_plug,
2259 .bdrv_io_unplug = raw_aio_unplug,
2260 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2262 .bdrv_truncate = raw_truncate,
2263 .bdrv_getlength = raw_getlength,
2264 .has_variable_length = true,
2265 .bdrv_get_allocated_file_size
2266 = raw_get_allocated_file_size,
2268 .bdrv_detach_aio_context = raw_detach_aio_context,
2269 .bdrv_attach_aio_context = raw_attach_aio_context,
2271 /* removable device support */
2272 .bdrv_is_inserted = cdrom_is_inserted,
2273 .bdrv_eject = cdrom_eject,
2274 .bdrv_lock_medium = cdrom_lock_medium,
2276 /* generic scsi device */
2277 .bdrv_ioctl = hdev_ioctl,
2278 .bdrv_aio_ioctl = hdev_aio_ioctl,
2280 #endif /* __linux__ */
2282 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2283 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2284 Error **errp)
2286 BDRVRawState *s = bs->opaque;
2287 Error *local_err = NULL;
2288 int ret;
2290 s->type = FTYPE_CD;
2292 ret = raw_open_common(bs, options, flags, 0, &local_err);
2293 if (ret) {
2294 if (local_err) {
2295 error_propagate(errp, local_err);
2297 return ret;
2300 /* make sure the door isn't locked at this time */
2301 ioctl(s->fd, CDIOCALLOW);
2302 return 0;
2305 static int cdrom_probe_device(const char *filename)
2307 if (strstart(filename, "/dev/cd", NULL) ||
2308 strstart(filename, "/dev/acd", NULL))
2309 return 100;
2310 return 0;
2313 static int cdrom_reopen(BlockDriverState *bs)
2315 BDRVRawState *s = bs->opaque;
2316 int fd;
2319 * Force reread of possibly changed/newly loaded disc,
2320 * FreeBSD seems to not notice sometimes...
2322 if (s->fd >= 0)
2323 qemu_close(s->fd);
2324 fd = qemu_open(bs->filename, s->open_flags, 0644);
2325 if (fd < 0) {
2326 s->fd = -1;
2327 return -EIO;
2329 s->fd = fd;
2331 /* make sure the door isn't locked at this time */
2332 ioctl(s->fd, CDIOCALLOW);
2333 return 0;
2336 static int cdrom_is_inserted(BlockDriverState *bs)
2338 return raw_getlength(bs) > 0;
2341 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2343 BDRVRawState *s = bs->opaque;
2345 if (s->fd < 0)
2346 return;
2348 (void) ioctl(s->fd, CDIOCALLOW);
2350 if (eject_flag) {
2351 if (ioctl(s->fd, CDIOCEJECT) < 0)
2352 perror("CDIOCEJECT");
2353 } else {
2354 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2355 perror("CDIOCCLOSE");
2358 cdrom_reopen(bs);
2361 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2363 BDRVRawState *s = bs->opaque;
2365 if (s->fd < 0)
2366 return;
2367 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2369 * Note: an error can happen if the distribution automatically
2370 * mounts the CD-ROM
2372 /* perror("CDROM_LOCKDOOR"); */
2376 static BlockDriver bdrv_host_cdrom = {
2377 .format_name = "host_cdrom",
2378 .protocol_name = "host_cdrom",
2379 .instance_size = sizeof(BDRVRawState),
2380 .bdrv_needs_filename = true,
2381 .bdrv_probe_device = cdrom_probe_device,
2382 .bdrv_parse_filename = cdrom_parse_filename,
2383 .bdrv_file_open = cdrom_open,
2384 .bdrv_close = raw_close,
2385 .bdrv_reopen_prepare = raw_reopen_prepare,
2386 .bdrv_reopen_commit = raw_reopen_commit,
2387 .bdrv_reopen_abort = raw_reopen_abort,
2388 .bdrv_create = hdev_create,
2389 .create_opts = &raw_create_opts,
2391 .bdrv_aio_readv = raw_aio_readv,
2392 .bdrv_aio_writev = raw_aio_writev,
2393 .bdrv_aio_flush = raw_aio_flush,
2394 .bdrv_refresh_limits = raw_refresh_limits,
2395 .bdrv_io_plug = raw_aio_plug,
2396 .bdrv_io_unplug = raw_aio_unplug,
2397 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2399 .bdrv_truncate = raw_truncate,
2400 .bdrv_getlength = raw_getlength,
2401 .has_variable_length = true,
2402 .bdrv_get_allocated_file_size
2403 = raw_get_allocated_file_size,
2405 .bdrv_detach_aio_context = raw_detach_aio_context,
2406 .bdrv_attach_aio_context = raw_attach_aio_context,
2408 /* removable device support */
2409 .bdrv_is_inserted = cdrom_is_inserted,
2410 .bdrv_eject = cdrom_eject,
2411 .bdrv_lock_medium = cdrom_lock_medium,
2413 #endif /* __FreeBSD__ */
2415 static void bdrv_file_init(void)
2418 * Register all the drivers. Note that order is important, the driver
2419 * registered last will get probed first.
2421 bdrv_register(&bdrv_file);
2422 bdrv_register(&bdrv_host_device);
2423 #ifdef __linux__
2424 bdrv_register(&bdrv_host_floppy);
2425 bdrv_register(&bdrv_host_cdrom);
2426 #endif
2427 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2428 bdrv_register(&bdrv_host_cdrom);
2429 #endif
2432 block_init(bdrv_file_init);