softfloat: Apply patch corresponding to rebasing to softfloat-2a
[qemu/ar7.git] / block / raw-posix.c
blobe51293a455f28a6b1e21d02c74d49f232795e29d
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"
33 #include "qapi/util.h"
35 #if defined(__APPLE__) && (__MACH__)
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
45 #endif
47 #ifdef __sun__
48 #define _POSIX_PTHREAD_SEMANTICS 1
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
57 #include <linux/fd.h>
58 #include <linux/fs.h>
59 #ifndef FS_NOCOW_FL
60 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
61 #endif
62 #endif
63 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
64 #include <linux/falloc.h>
65 #endif
66 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
67 #include <sys/disk.h>
68 #include <sys/cdio.h>
69 #endif
71 #ifdef __OpenBSD__
72 #include <sys/ioctl.h>
73 #include <sys/disklabel.h>
74 #include <sys/dkio.h>
75 #endif
77 #ifdef __NetBSD__
78 #include <sys/ioctl.h>
79 #include <sys/disklabel.h>
80 #include <sys/dkio.h>
81 #include <sys/disk.h>
82 #endif
84 #ifdef __DragonFly__
85 #include <sys/ioctl.h>
86 #include <sys/diskslice.h>
87 #endif
89 #ifdef CONFIG_XFS
90 #include <xfs/xfs.h>
91 #endif
93 //#define DEBUG_FLOPPY
95 //#define DEBUG_BLOCK
96 #if defined(DEBUG_BLOCK)
97 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
98 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
99 #else
100 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
101 #endif
103 /* OS X does not have O_DSYNC */
104 #ifndef O_DSYNC
105 #ifdef O_SYNC
106 #define O_DSYNC O_SYNC
107 #elif defined(O_FSYNC)
108 #define O_DSYNC O_FSYNC
109 #endif
110 #endif
112 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
113 #ifndef O_DIRECT
114 #define O_DIRECT O_DSYNC
115 #endif
117 #define FTYPE_FILE 0
118 #define FTYPE_CD 1
119 #define FTYPE_FD 2
121 /* if the FD is not accessed during that time (in ns), we try to
122 reopen it to see if the disk has been changed */
123 #define FD_OPEN_TIMEOUT (1000000000)
125 #define MAX_BLOCKSIZE 4096
127 typedef struct BDRVRawState {
128 int fd;
129 int type;
130 int open_flags;
131 size_t buf_align;
133 #if defined(__linux__)
134 /* linux floppy specific */
135 int64_t fd_open_time;
136 int64_t fd_error_time;
137 int fd_got_error;
138 int fd_media_changed;
139 #endif
140 #ifdef CONFIG_LINUX_AIO
141 int use_aio;
142 void *aio_ctx;
143 #endif
144 #ifdef CONFIG_XFS
145 bool is_xfs:1;
146 #endif
147 bool has_discard:1;
148 bool has_write_zeroes:1;
149 bool discard_zeroes:1;
150 bool needs_alignment;
151 } BDRVRawState;
153 typedef struct BDRVRawReopenState {
154 int fd;
155 int open_flags;
156 #ifdef CONFIG_LINUX_AIO
157 int use_aio;
158 #endif
159 } BDRVRawReopenState;
161 static int fd_open(BlockDriverState *bs);
162 static int64_t raw_getlength(BlockDriverState *bs);
164 typedef struct RawPosixAIOData {
165 BlockDriverState *bs;
166 int aio_fildes;
167 union {
168 struct iovec *aio_iov;
169 void *aio_ioctl_buf;
171 int aio_niov;
172 uint64_t aio_nbytes;
173 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
174 off_t aio_offset;
175 int aio_type;
176 } RawPosixAIOData;
178 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
179 static int cdrom_reopen(BlockDriverState *bs);
180 #endif
182 #if defined(__NetBSD__)
183 static int raw_normalize_devicepath(const char **filename)
185 static char namebuf[PATH_MAX];
186 const char *dp, *fname;
187 struct stat sb;
189 fname = *filename;
190 dp = strrchr(fname, '/');
191 if (lstat(fname, &sb) < 0) {
192 fprintf(stderr, "%s: stat failed: %s\n",
193 fname, strerror(errno));
194 return -errno;
197 if (!S_ISBLK(sb.st_mode)) {
198 return 0;
201 if (dp == NULL) {
202 snprintf(namebuf, PATH_MAX, "r%s", fname);
203 } else {
204 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
205 (int)(dp - fname), fname, dp + 1);
207 fprintf(stderr, "%s is a block device", fname);
208 *filename = namebuf;
209 fprintf(stderr, ", using %s\n", *filename);
211 return 0;
213 #else
214 static int raw_normalize_devicepath(const char **filename)
216 return 0;
218 #endif
220 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
222 BDRVRawState *s = bs->opaque;
223 char *buf;
224 unsigned int sector_size;
226 /* For /dev/sg devices the alignment is not really used.
227 With buffered I/O, we don't have any restrictions. */
228 if (bs->sg || !s->needs_alignment) {
229 bs->request_alignment = 1;
230 s->buf_align = 1;
231 return;
234 /* Try a few ioctls to get the right size */
235 bs->request_alignment = 0;
236 s->buf_align = 0;
238 #ifdef BLKSSZGET
239 if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
240 bs->request_alignment = sector_size;
242 #endif
243 #ifdef DKIOCGETBLOCKSIZE
244 if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
245 bs->request_alignment = sector_size;
247 #endif
248 #ifdef DIOCGSECTORSIZE
249 if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
250 bs->request_alignment = sector_size;
252 #endif
253 #ifdef CONFIG_XFS
254 if (s->is_xfs) {
255 struct dioattr da;
256 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
257 bs->request_alignment = da.d_miniosz;
258 /* The kernel returns wrong information for d_mem */
259 /* s->buf_align = da.d_mem; */
262 #endif
264 /* If we could not get the sizes so far, we can only guess them */
265 if (!s->buf_align) {
266 size_t align;
267 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
268 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
269 if (pread(fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
270 s->buf_align = align;
271 break;
274 qemu_vfree(buf);
277 if (!bs->request_alignment) {
278 size_t align;
279 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
280 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
281 if (pread(fd, buf, align, 0) >= 0) {
282 bs->request_alignment = align;
283 break;
286 qemu_vfree(buf);
289 if (!s->buf_align || !bs->request_alignment) {
290 error_setg(errp, "Could not find working O_DIRECT alignment. "
291 "Try cache.direct=off.");
295 static void raw_parse_flags(int bdrv_flags, int *open_flags)
297 assert(open_flags != NULL);
299 *open_flags |= O_BINARY;
300 *open_flags &= ~O_ACCMODE;
301 if (bdrv_flags & BDRV_O_RDWR) {
302 *open_flags |= O_RDWR;
303 } else {
304 *open_flags |= O_RDONLY;
307 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
308 * and O_DIRECT for no caching. */
309 if ((bdrv_flags & BDRV_O_NOCACHE)) {
310 *open_flags |= O_DIRECT;
314 static void raw_detach_aio_context(BlockDriverState *bs)
316 #ifdef CONFIG_LINUX_AIO
317 BDRVRawState *s = bs->opaque;
319 if (s->use_aio) {
320 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
322 #endif
325 static void raw_attach_aio_context(BlockDriverState *bs,
326 AioContext *new_context)
328 #ifdef CONFIG_LINUX_AIO
329 BDRVRawState *s = bs->opaque;
331 if (s->use_aio) {
332 laio_attach_aio_context(s->aio_ctx, new_context);
334 #endif
337 #ifdef CONFIG_LINUX_AIO
338 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
340 int ret = -1;
341 assert(aio_ctx != NULL);
342 assert(use_aio != NULL);
344 * Currently Linux do AIO only for files opened with O_DIRECT
345 * specified so check NOCACHE flag too
347 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
348 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
350 /* if non-NULL, laio_init() has already been run */
351 if (*aio_ctx == NULL) {
352 *aio_ctx = laio_init();
353 if (!*aio_ctx) {
354 goto error;
357 *use_aio = 1;
358 } else {
359 *use_aio = 0;
362 ret = 0;
364 error:
365 return ret;
367 #endif
369 static void raw_parse_filename(const char *filename, QDict *options,
370 Error **errp)
372 /* The filename does not have to be prefixed by the protocol name, since
373 * "file" is the default protocol; therefore, the return value of this
374 * function call can be ignored. */
375 strstart(filename, "file:", &filename);
377 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
380 static QemuOptsList raw_runtime_opts = {
381 .name = "raw",
382 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
383 .desc = {
385 .name = "filename",
386 .type = QEMU_OPT_STRING,
387 .help = "File name of the image",
389 { /* end of list */ }
393 static int raw_open_common(BlockDriverState *bs, QDict *options,
394 int bdrv_flags, int open_flags, Error **errp)
396 BDRVRawState *s = bs->opaque;
397 QemuOpts *opts;
398 Error *local_err = NULL;
399 const char *filename = NULL;
400 int fd, ret;
401 struct stat st;
403 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
404 qemu_opts_absorb_qdict(opts, options, &local_err);
405 if (local_err) {
406 error_propagate(errp, local_err);
407 ret = -EINVAL;
408 goto fail;
411 filename = qemu_opt_get(opts, "filename");
413 ret = raw_normalize_devicepath(&filename);
414 if (ret != 0) {
415 error_setg_errno(errp, -ret, "Could not normalize device path");
416 goto fail;
419 s->open_flags = open_flags;
420 raw_parse_flags(bdrv_flags, &s->open_flags);
422 s->fd = -1;
423 fd = qemu_open(filename, s->open_flags, 0644);
424 if (fd < 0) {
425 ret = -errno;
426 if (ret == -EROFS) {
427 ret = -EACCES;
429 goto fail;
431 s->fd = fd;
433 #ifdef CONFIG_LINUX_AIO
434 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
435 qemu_close(fd);
436 ret = -errno;
437 error_setg_errno(errp, -ret, "Could not set AIO state");
438 goto fail;
440 #endif
442 s->has_discard = true;
443 s->has_write_zeroes = true;
444 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
445 s->needs_alignment = true;
448 if (fstat(s->fd, &st) < 0) {
449 ret = -errno;
450 error_setg_errno(errp, errno, "Could not stat file");
451 goto fail;
453 if (S_ISREG(st.st_mode)) {
454 s->discard_zeroes = true;
456 if (S_ISBLK(st.st_mode)) {
457 #ifdef BLKDISCARDZEROES
458 unsigned int arg;
459 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
460 s->discard_zeroes = true;
462 #endif
463 #ifdef __linux__
464 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
465 * not rely on the contents of discarded blocks unless using O_DIRECT.
466 * Same for BLKZEROOUT.
468 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
469 s->discard_zeroes = false;
470 s->has_write_zeroes = false;
472 #endif
474 #ifdef __FreeBSD__
475 if (S_ISCHR(st.st_mode)) {
477 * The file is a char device (disk), which on FreeBSD isn't behind
478 * a pager, so force all requests to be aligned. This is needed
479 * so QEMU makes sure all IO operations on the device are aligned
480 * to sector size, or else FreeBSD will reject them with EINVAL.
482 s->needs_alignment = true;
484 #endif
486 #ifdef CONFIG_XFS
487 if (platform_test_xfs_fd(s->fd)) {
488 s->is_xfs = true;
490 #endif
492 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
494 ret = 0;
495 fail:
496 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
497 unlink(filename);
499 qemu_opts_del(opts);
500 return ret;
503 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
504 Error **errp)
506 BDRVRawState *s = bs->opaque;
507 Error *local_err = NULL;
508 int ret;
510 s->type = FTYPE_FILE;
511 ret = raw_open_common(bs, options, flags, 0, &local_err);
512 if (local_err) {
513 error_propagate(errp, local_err);
515 return ret;
518 static int raw_reopen_prepare(BDRVReopenState *state,
519 BlockReopenQueue *queue, Error **errp)
521 BDRVRawState *s;
522 BDRVRawReopenState *raw_s;
523 int ret = 0;
524 Error *local_err = NULL;
526 assert(state != NULL);
527 assert(state->bs != NULL);
529 s = state->bs->opaque;
531 state->opaque = g_new0(BDRVRawReopenState, 1);
532 raw_s = state->opaque;
534 #ifdef CONFIG_LINUX_AIO
535 raw_s->use_aio = s->use_aio;
537 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
538 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
539 * won't override aio_ctx if aio_ctx is non-NULL */
540 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
541 error_setg(errp, "Could not set AIO state");
542 return -1;
544 #endif
546 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
547 raw_s->open_flags |= O_NONBLOCK;
550 raw_parse_flags(state->flags, &raw_s->open_flags);
552 raw_s->fd = -1;
554 int fcntl_flags = O_APPEND | O_NONBLOCK;
555 #ifdef O_NOATIME
556 fcntl_flags |= O_NOATIME;
557 #endif
559 #ifdef O_ASYNC
560 /* Not all operating systems have O_ASYNC, and those that don't
561 * will not let us track the state into raw_s->open_flags (typically
562 * you achieve the same effect with an ioctl, for example I_SETSIG
563 * on Solaris). But we do not use O_ASYNC, so that's fine.
565 assert((s->open_flags & O_ASYNC) == 0);
566 #endif
568 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
569 /* dup the original fd */
570 /* TODO: use qemu fcntl wrapper */
571 #ifdef F_DUPFD_CLOEXEC
572 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
573 #else
574 raw_s->fd = dup(s->fd);
575 if (raw_s->fd != -1) {
576 qemu_set_cloexec(raw_s->fd);
578 #endif
579 if (raw_s->fd >= 0) {
580 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
581 if (ret) {
582 qemu_close(raw_s->fd);
583 raw_s->fd = -1;
588 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
589 if (raw_s->fd == -1) {
590 assert(!(raw_s->open_flags & O_CREAT));
591 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
592 if (raw_s->fd == -1) {
593 error_setg_errno(errp, errno, "Could not reopen file");
594 ret = -1;
598 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
599 * alignment with the new fd. */
600 if (raw_s->fd != -1) {
601 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
602 if (local_err) {
603 qemu_close(raw_s->fd);
604 raw_s->fd = -1;
605 error_propagate(errp, local_err);
606 ret = -EINVAL;
610 return ret;
613 static void raw_reopen_commit(BDRVReopenState *state)
615 BDRVRawReopenState *raw_s = state->opaque;
616 BDRVRawState *s = state->bs->opaque;
618 s->open_flags = raw_s->open_flags;
620 qemu_close(s->fd);
621 s->fd = raw_s->fd;
622 #ifdef CONFIG_LINUX_AIO
623 s->use_aio = raw_s->use_aio;
624 #endif
626 g_free(state->opaque);
627 state->opaque = NULL;
631 static void raw_reopen_abort(BDRVReopenState *state)
633 BDRVRawReopenState *raw_s = state->opaque;
635 /* nothing to do if NULL, we didn't get far enough */
636 if (raw_s == NULL) {
637 return;
640 if (raw_s->fd >= 0) {
641 qemu_close(raw_s->fd);
642 raw_s->fd = -1;
644 g_free(state->opaque);
645 state->opaque = NULL;
648 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
650 BDRVRawState *s = bs->opaque;
652 raw_probe_alignment(bs, s->fd, errp);
653 bs->bl.opt_mem_alignment = s->buf_align;
656 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
658 int ret;
660 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
661 if (ret == -1) {
662 return -errno;
665 return 0;
668 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
670 int ret;
672 ret = qemu_fdatasync(aiocb->aio_fildes);
673 if (ret == -1) {
674 return -errno;
676 return 0;
679 #ifdef CONFIG_PREADV
681 static bool preadv_present = true;
683 static ssize_t
684 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
686 return preadv(fd, iov, nr_iov, offset);
689 static ssize_t
690 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
692 return pwritev(fd, iov, nr_iov, offset);
695 #else
697 static bool preadv_present = false;
699 static ssize_t
700 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
702 return -ENOSYS;
705 static ssize_t
706 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
708 return -ENOSYS;
711 #endif
713 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
715 ssize_t len;
717 do {
718 if (aiocb->aio_type & QEMU_AIO_WRITE)
719 len = qemu_pwritev(aiocb->aio_fildes,
720 aiocb->aio_iov,
721 aiocb->aio_niov,
722 aiocb->aio_offset);
723 else
724 len = qemu_preadv(aiocb->aio_fildes,
725 aiocb->aio_iov,
726 aiocb->aio_niov,
727 aiocb->aio_offset);
728 } while (len == -1 && errno == EINTR);
730 if (len == -1) {
731 return -errno;
733 return len;
737 * Read/writes the data to/from a given linear buffer.
739 * Returns the number of bytes handles or -errno in case of an error. Short
740 * reads are only returned if the end of the file is reached.
742 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
744 ssize_t offset = 0;
745 ssize_t len;
747 while (offset < aiocb->aio_nbytes) {
748 if (aiocb->aio_type & QEMU_AIO_WRITE) {
749 len = pwrite(aiocb->aio_fildes,
750 (const char *)buf + offset,
751 aiocb->aio_nbytes - offset,
752 aiocb->aio_offset + offset);
753 } else {
754 len = pread(aiocb->aio_fildes,
755 buf + offset,
756 aiocb->aio_nbytes - offset,
757 aiocb->aio_offset + offset);
759 if (len == -1 && errno == EINTR) {
760 continue;
761 } else if (len == -1 && errno == EINVAL &&
762 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
763 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
764 offset > 0) {
765 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
766 * after a short read. Assume that O_DIRECT short reads only occur
767 * at EOF. Therefore this is a short read, not an I/O error.
769 break;
770 } else if (len == -1) {
771 offset = -errno;
772 break;
773 } else if (len == 0) {
774 break;
776 offset += len;
779 return offset;
782 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
784 ssize_t nbytes;
785 char *buf;
787 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
789 * If there is just a single buffer, and it is properly aligned
790 * we can just use plain pread/pwrite without any problems.
792 if (aiocb->aio_niov == 1) {
793 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
796 * We have more than one iovec, and all are properly aligned.
798 * Try preadv/pwritev first and fall back to linearizing the
799 * buffer if it's not supported.
801 if (preadv_present) {
802 nbytes = handle_aiocb_rw_vector(aiocb);
803 if (nbytes == aiocb->aio_nbytes ||
804 (nbytes < 0 && nbytes != -ENOSYS)) {
805 return nbytes;
807 preadv_present = false;
811 * XXX(hch): short read/write. no easy way to handle the reminder
812 * using these interfaces. For now retry using plain
813 * pread/pwrite?
818 * Ok, we have to do it the hard way, copy all segments into
819 * a single aligned buffer.
821 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
822 if (buf == NULL) {
823 return -ENOMEM;
826 if (aiocb->aio_type & QEMU_AIO_WRITE) {
827 char *p = buf;
828 int i;
830 for (i = 0; i < aiocb->aio_niov; ++i) {
831 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
832 p += aiocb->aio_iov[i].iov_len;
834 assert(p - buf == aiocb->aio_nbytes);
837 nbytes = handle_aiocb_rw_linear(aiocb, buf);
838 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
839 char *p = buf;
840 size_t count = aiocb->aio_nbytes, copy;
841 int i;
843 for (i = 0; i < aiocb->aio_niov && count; ++i) {
844 copy = count;
845 if (copy > aiocb->aio_iov[i].iov_len) {
846 copy = aiocb->aio_iov[i].iov_len;
848 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
849 assert(count >= copy);
850 p += copy;
851 count -= copy;
853 assert(count == 0);
855 qemu_vfree(buf);
857 return nbytes;
860 #ifdef CONFIG_XFS
861 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
863 struct xfs_flock64 fl;
865 memset(&fl, 0, sizeof(fl));
866 fl.l_whence = SEEK_SET;
867 fl.l_start = offset;
868 fl.l_len = bytes;
870 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
871 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
872 return -errno;
875 return 0;
878 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
880 struct xfs_flock64 fl;
882 memset(&fl, 0, sizeof(fl));
883 fl.l_whence = SEEK_SET;
884 fl.l_start = offset;
885 fl.l_len = bytes;
887 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
888 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
889 return -errno;
892 return 0;
894 #endif
896 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
898 int ret = -EOPNOTSUPP;
899 BDRVRawState *s = aiocb->bs->opaque;
901 if (s->has_write_zeroes == 0) {
902 return -ENOTSUP;
905 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
906 #ifdef BLKZEROOUT
907 do {
908 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
909 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
910 return 0;
912 } while (errno == EINTR);
914 ret = -errno;
915 #endif
916 } else {
917 #ifdef CONFIG_XFS
918 if (s->is_xfs) {
919 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
921 #endif
924 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
925 ret == -ENOTTY) {
926 s->has_write_zeroes = false;
927 ret = -ENOTSUP;
929 return ret;
932 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
934 int ret = -EOPNOTSUPP;
935 BDRVRawState *s = aiocb->bs->opaque;
937 if (!s->has_discard) {
938 return -ENOTSUP;
941 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
942 #ifdef BLKDISCARD
943 do {
944 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
945 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
946 return 0;
948 } while (errno == EINTR);
950 ret = -errno;
951 #endif
952 } else {
953 #ifdef CONFIG_XFS
954 if (s->is_xfs) {
955 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
957 #endif
959 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
960 do {
961 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
962 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
963 return 0;
965 } while (errno == EINTR);
967 ret = -errno;
968 #endif
971 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
972 ret == -ENOTTY) {
973 s->has_discard = false;
974 ret = -ENOTSUP;
976 return ret;
979 static int aio_worker(void *arg)
981 RawPosixAIOData *aiocb = arg;
982 ssize_t ret = 0;
984 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
985 case QEMU_AIO_READ:
986 ret = handle_aiocb_rw(aiocb);
987 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
988 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
989 0, aiocb->aio_nbytes - ret);
991 ret = aiocb->aio_nbytes;
993 if (ret == aiocb->aio_nbytes) {
994 ret = 0;
995 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
996 ret = -EINVAL;
998 break;
999 case QEMU_AIO_WRITE:
1000 ret = handle_aiocb_rw(aiocb);
1001 if (ret == aiocb->aio_nbytes) {
1002 ret = 0;
1003 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1004 ret = -EINVAL;
1006 break;
1007 case QEMU_AIO_FLUSH:
1008 ret = handle_aiocb_flush(aiocb);
1009 break;
1010 case QEMU_AIO_IOCTL:
1011 ret = handle_aiocb_ioctl(aiocb);
1012 break;
1013 case QEMU_AIO_DISCARD:
1014 ret = handle_aiocb_discard(aiocb);
1015 break;
1016 case QEMU_AIO_WRITE_ZEROES:
1017 ret = handle_aiocb_write_zeroes(aiocb);
1018 break;
1019 default:
1020 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1021 ret = -EINVAL;
1022 break;
1025 g_slice_free(RawPosixAIOData, aiocb);
1026 return ret;
1029 static int paio_submit_co(BlockDriverState *bs, int fd,
1030 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1031 int type)
1033 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1034 ThreadPool *pool;
1036 acb->bs = bs;
1037 acb->aio_type = type;
1038 acb->aio_fildes = fd;
1040 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1041 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1043 if (qiov) {
1044 acb->aio_iov = qiov->iov;
1045 acb->aio_niov = qiov->niov;
1046 assert(qiov->size == acb->aio_nbytes);
1049 trace_paio_submit_co(sector_num, nb_sectors, type);
1050 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1051 return thread_pool_submit_co(pool, aio_worker, acb);
1054 static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1055 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1056 BlockCompletionFunc *cb, void *opaque, int type)
1058 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1059 ThreadPool *pool;
1061 acb->bs = bs;
1062 acb->aio_type = type;
1063 acb->aio_fildes = fd;
1065 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1066 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1068 if (qiov) {
1069 acb->aio_iov = qiov->iov;
1070 acb->aio_niov = qiov->niov;
1071 assert(qiov->size == acb->aio_nbytes);
1074 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1075 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1076 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1079 static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1080 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1081 BlockCompletionFunc *cb, void *opaque, int type)
1083 BDRVRawState *s = bs->opaque;
1085 if (fd_open(bs) < 0)
1086 return NULL;
1089 * Check if the underlying device requires requests to be aligned,
1090 * and if the request we are trying to submit is aligned or not.
1091 * If this is the case tell the low-level driver that it needs
1092 * to copy the buffer.
1094 if (s->needs_alignment) {
1095 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1096 type |= QEMU_AIO_MISALIGNED;
1097 #ifdef CONFIG_LINUX_AIO
1098 } else if (s->use_aio) {
1099 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1100 nb_sectors, cb, opaque, type);
1101 #endif
1105 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1106 cb, opaque, type);
1109 static void raw_aio_plug(BlockDriverState *bs)
1111 #ifdef CONFIG_LINUX_AIO
1112 BDRVRawState *s = bs->opaque;
1113 if (s->use_aio) {
1114 laio_io_plug(bs, s->aio_ctx);
1116 #endif
1119 static void raw_aio_unplug(BlockDriverState *bs)
1121 #ifdef CONFIG_LINUX_AIO
1122 BDRVRawState *s = bs->opaque;
1123 if (s->use_aio) {
1124 laio_io_unplug(bs, s->aio_ctx, true);
1126 #endif
1129 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1131 #ifdef CONFIG_LINUX_AIO
1132 BDRVRawState *s = bs->opaque;
1133 if (s->use_aio) {
1134 laio_io_unplug(bs, s->aio_ctx, false);
1136 #endif
1139 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1140 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1141 BlockCompletionFunc *cb, void *opaque)
1143 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1144 cb, opaque, QEMU_AIO_READ);
1147 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1148 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1149 BlockCompletionFunc *cb, void *opaque)
1151 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1152 cb, opaque, QEMU_AIO_WRITE);
1155 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1156 BlockCompletionFunc *cb, void *opaque)
1158 BDRVRawState *s = bs->opaque;
1160 if (fd_open(bs) < 0)
1161 return NULL;
1163 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1166 static void raw_close(BlockDriverState *bs)
1168 BDRVRawState *s = bs->opaque;
1170 raw_detach_aio_context(bs);
1172 #ifdef CONFIG_LINUX_AIO
1173 if (s->use_aio) {
1174 laio_cleanup(s->aio_ctx);
1176 #endif
1177 if (s->fd >= 0) {
1178 qemu_close(s->fd);
1179 s->fd = -1;
1183 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1185 BDRVRawState *s = bs->opaque;
1186 struct stat st;
1188 if (fstat(s->fd, &st)) {
1189 return -errno;
1192 if (S_ISREG(st.st_mode)) {
1193 if (ftruncate(s->fd, offset) < 0) {
1194 return -errno;
1196 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1197 if (offset > raw_getlength(bs)) {
1198 return -EINVAL;
1200 } else {
1201 return -ENOTSUP;
1204 return 0;
1207 #ifdef __OpenBSD__
1208 static int64_t raw_getlength(BlockDriverState *bs)
1210 BDRVRawState *s = bs->opaque;
1211 int fd = s->fd;
1212 struct stat st;
1214 if (fstat(fd, &st))
1215 return -errno;
1216 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1217 struct disklabel dl;
1219 if (ioctl(fd, DIOCGDINFO, &dl))
1220 return -errno;
1221 return (uint64_t)dl.d_secsize *
1222 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1223 } else
1224 return st.st_size;
1226 #elif defined(__NetBSD__)
1227 static int64_t raw_getlength(BlockDriverState *bs)
1229 BDRVRawState *s = bs->opaque;
1230 int fd = s->fd;
1231 struct stat st;
1233 if (fstat(fd, &st))
1234 return -errno;
1235 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1236 struct dkwedge_info dkw;
1238 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1239 return dkw.dkw_size * 512;
1240 } else {
1241 struct disklabel dl;
1243 if (ioctl(fd, DIOCGDINFO, &dl))
1244 return -errno;
1245 return (uint64_t)dl.d_secsize *
1246 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1248 } else
1249 return st.st_size;
1251 #elif defined(__sun__)
1252 static int64_t raw_getlength(BlockDriverState *bs)
1254 BDRVRawState *s = bs->opaque;
1255 struct dk_minfo minfo;
1256 int ret;
1257 int64_t size;
1259 ret = fd_open(bs);
1260 if (ret < 0) {
1261 return ret;
1265 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1267 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1268 if (ret != -1) {
1269 return minfo.dki_lbsize * minfo.dki_capacity;
1273 * There are reports that lseek on some devices fails, but
1274 * irc discussion said that contingency on contingency was overkill.
1276 size = lseek(s->fd, 0, SEEK_END);
1277 if (size < 0) {
1278 return -errno;
1280 return size;
1282 #elif defined(CONFIG_BSD)
1283 static int64_t raw_getlength(BlockDriverState *bs)
1285 BDRVRawState *s = bs->opaque;
1286 int fd = s->fd;
1287 int64_t size;
1288 struct stat sb;
1289 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1290 int reopened = 0;
1291 #endif
1292 int ret;
1294 ret = fd_open(bs);
1295 if (ret < 0)
1296 return ret;
1298 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1299 again:
1300 #endif
1301 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1302 #ifdef DIOCGMEDIASIZE
1303 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1304 #elif defined(DIOCGPART)
1306 struct partinfo pi;
1307 if (ioctl(fd, DIOCGPART, &pi) == 0)
1308 size = pi.media_size;
1309 else
1310 size = 0;
1312 if (size == 0)
1313 #endif
1314 #if defined(__APPLE__) && defined(__MACH__)
1315 size = LLONG_MAX;
1316 #else
1317 size = lseek(fd, 0LL, SEEK_END);
1318 if (size < 0) {
1319 return -errno;
1321 #endif
1322 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1323 switch(s->type) {
1324 case FTYPE_CD:
1325 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1326 if (size == 2048LL * (unsigned)-1)
1327 size = 0;
1328 /* XXX no disc? maybe we need to reopen... */
1329 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1330 reopened = 1;
1331 goto again;
1334 #endif
1335 } else {
1336 size = lseek(fd, 0, SEEK_END);
1337 if (size < 0) {
1338 return -errno;
1341 return size;
1343 #else
1344 static int64_t raw_getlength(BlockDriverState *bs)
1346 BDRVRawState *s = bs->opaque;
1347 int ret;
1348 int64_t size;
1350 ret = fd_open(bs);
1351 if (ret < 0) {
1352 return ret;
1355 size = lseek(s->fd, 0, SEEK_END);
1356 if (size < 0) {
1357 return -errno;
1359 return size;
1361 #endif
1363 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1365 struct stat st;
1366 BDRVRawState *s = bs->opaque;
1368 if (fstat(s->fd, &st) < 0) {
1369 return -errno;
1371 return (int64_t)st.st_blocks * 512;
1374 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1376 int fd;
1377 int result = 0;
1378 int64_t total_size = 0;
1379 bool nocow = false;
1380 PreallocMode prealloc;
1381 char *buf = NULL;
1382 Error *local_err = NULL;
1384 strstart(filename, "file:", &filename);
1386 /* Read out options */
1387 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1388 BDRV_SECTOR_SIZE);
1389 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1390 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1391 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1392 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1393 &local_err);
1394 g_free(buf);
1395 if (local_err) {
1396 error_propagate(errp, local_err);
1397 result = -EINVAL;
1398 goto out;
1401 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1402 0644);
1403 if (fd < 0) {
1404 result = -errno;
1405 error_setg_errno(errp, -result, "Could not create file");
1406 goto out;
1409 if (nocow) {
1410 #ifdef __linux__
1411 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1412 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1413 * will be ignored since any failure of this operation should not
1414 * block the left work.
1416 int attr;
1417 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1418 attr |= FS_NOCOW_FL;
1419 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1421 #endif
1424 if (ftruncate(fd, total_size) != 0) {
1425 result = -errno;
1426 error_setg_errno(errp, -result, "Could not resize file");
1427 goto out_close;
1430 switch (prealloc) {
1431 #ifdef CONFIG_POSIX_FALLOCATE
1432 case PREALLOC_MODE_FALLOC:
1433 /* posix_fallocate() doesn't set errno. */
1434 result = -posix_fallocate(fd, 0, total_size);
1435 if (result != 0) {
1436 error_setg_errno(errp, -result,
1437 "Could not preallocate data for the new file");
1439 break;
1440 #endif
1441 case PREALLOC_MODE_FULL:
1443 int64_t num = 0, left = total_size;
1444 buf = g_malloc0(65536);
1446 while (left > 0) {
1447 num = MIN(left, 65536);
1448 result = write(fd, buf, num);
1449 if (result < 0) {
1450 result = -errno;
1451 error_setg_errno(errp, -result,
1452 "Could not write to the new file");
1453 break;
1455 left -= result;
1457 if (result >= 0) {
1458 result = fsync(fd);
1459 if (result < 0) {
1460 result = -errno;
1461 error_setg_errno(errp, -result,
1462 "Could not flush new file to disk");
1465 g_free(buf);
1466 break;
1468 case PREALLOC_MODE_OFF:
1469 break;
1470 default:
1471 result = -EINVAL;
1472 error_setg(errp, "Unsupported preallocation mode: %s",
1473 PreallocMode_lookup[prealloc]);
1474 break;
1477 out_close:
1478 if (qemu_close(fd) != 0 && result == 0) {
1479 result = -errno;
1480 error_setg_errno(errp, -result, "Could not close the new file");
1482 out:
1483 return result;
1487 * Find allocation range in @bs around offset @start.
1488 * May change underlying file descriptor's file offset.
1489 * If @start is not in a hole, store @start in @data, and the
1490 * beginning of the next hole in @hole, and return 0.
1491 * If @start is in a non-trailing hole, store @start in @hole and the
1492 * beginning of the next non-hole in @data, and return 0.
1493 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1494 * If we can't find out, return a negative errno other than -ENXIO.
1496 static int find_allocation(BlockDriverState *bs, off_t start,
1497 off_t *data, off_t *hole)
1499 #if defined SEEK_HOLE && defined SEEK_DATA
1500 BDRVRawState *s = bs->opaque;
1501 off_t offs;
1504 * SEEK_DATA cases:
1505 * D1. offs == start: start is in data
1506 * D2. offs > start: start is in a hole, next data at offs
1507 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1508 * or start is beyond EOF
1509 * If the latter happens, the file has been truncated behind
1510 * our back since we opened it. All bets are off then.
1511 * Treating like a trailing hole is simplest.
1512 * D4. offs < 0, errno != ENXIO: we learned nothing
1514 offs = lseek(s->fd, start, SEEK_DATA);
1515 if (offs < 0) {
1516 return -errno; /* D3 or D4 */
1518 assert(offs >= start);
1520 if (offs > start) {
1521 /* D2: in hole, next data at offs */
1522 *hole = start;
1523 *data = offs;
1524 return 0;
1527 /* D1: in data, end not yet known */
1530 * SEEK_HOLE cases:
1531 * H1. offs == start: start is in a hole
1532 * If this happens here, a hole has been dug behind our back
1533 * since the previous lseek().
1534 * H2. offs > start: either start is in data, next hole at offs,
1535 * or start is in trailing hole, EOF at offs
1536 * Linux treats trailing holes like any other hole: offs ==
1537 * start. Solaris seeks to EOF instead: offs > start (blech).
1538 * If that happens here, a hole has been dug behind our back
1539 * since the previous lseek().
1540 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1541 * If this happens, the file has been truncated behind our
1542 * back since we opened it. Treat it like a trailing hole.
1543 * H4. offs < 0, errno != ENXIO: we learned nothing
1544 * Pretend we know nothing at all, i.e. "forget" about D1.
1546 offs = lseek(s->fd, start, SEEK_HOLE);
1547 if (offs < 0) {
1548 return -errno; /* D1 and (H3 or H4) */
1550 assert(offs >= start);
1552 if (offs > start) {
1554 * D1 and H2: either in data, next hole at offs, or it was in
1555 * data but is now in a trailing hole. In the latter case,
1556 * all bets are off. Treating it as if it there was data all
1557 * the way to EOF is safe, so simply do that.
1559 *data = start;
1560 *hole = offs;
1561 return 0;
1564 /* D1 and H1 */
1565 return -EBUSY;
1566 #else
1567 return -ENOTSUP;
1568 #endif
1572 * Returns the allocation status of the specified sectors.
1574 * If 'sector_num' is beyond the end of the disk image the return value is 0
1575 * and 'pnum' is set to 0.
1577 * 'pnum' is set to the number of sectors (including and immediately following
1578 * the specified sector) that are known to be in the same
1579 * allocated/unallocated state.
1581 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1582 * beyond the end of the disk image it will be clamped.
1584 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1585 int64_t sector_num,
1586 int nb_sectors, int *pnum)
1588 off_t start, data = 0, hole = 0;
1589 int64_t total_size;
1590 int ret;
1592 ret = fd_open(bs);
1593 if (ret < 0) {
1594 return ret;
1597 start = sector_num * BDRV_SECTOR_SIZE;
1598 total_size = bdrv_getlength(bs);
1599 if (total_size < 0) {
1600 return total_size;
1601 } else if (start >= total_size) {
1602 *pnum = 0;
1603 return 0;
1604 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1605 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1608 ret = find_allocation(bs, start, &data, &hole);
1609 if (ret == -ENXIO) {
1610 /* Trailing hole */
1611 *pnum = nb_sectors;
1612 ret = BDRV_BLOCK_ZERO;
1613 } else if (ret < 0) {
1614 /* No info available, so pretend there are no holes */
1615 *pnum = nb_sectors;
1616 ret = BDRV_BLOCK_DATA;
1617 } else if (data == start) {
1618 /* On a data extent, compute sectors to the end of the extent. */
1619 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1620 ret = BDRV_BLOCK_DATA;
1621 } else {
1622 /* On a hole, compute sectors to the beginning of the next extent. */
1623 assert(hole == start);
1624 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1625 ret = BDRV_BLOCK_ZERO;
1627 return ret | BDRV_BLOCK_OFFSET_VALID | start;
1630 static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1631 int64_t sector_num, int nb_sectors,
1632 BlockCompletionFunc *cb, void *opaque)
1634 BDRVRawState *s = bs->opaque;
1636 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1637 cb, opaque, QEMU_AIO_DISCARD);
1640 static int coroutine_fn raw_co_write_zeroes(
1641 BlockDriverState *bs, int64_t sector_num,
1642 int nb_sectors, BdrvRequestFlags flags)
1644 BDRVRawState *s = bs->opaque;
1646 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1647 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1648 QEMU_AIO_WRITE_ZEROES);
1649 } else if (s->discard_zeroes) {
1650 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1651 QEMU_AIO_DISCARD);
1653 return -ENOTSUP;
1656 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1658 BDRVRawState *s = bs->opaque;
1660 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1661 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1662 return 0;
1665 static QemuOptsList raw_create_opts = {
1666 .name = "raw-create-opts",
1667 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1668 .desc = {
1670 .name = BLOCK_OPT_SIZE,
1671 .type = QEMU_OPT_SIZE,
1672 .help = "Virtual disk size"
1675 .name = BLOCK_OPT_NOCOW,
1676 .type = QEMU_OPT_BOOL,
1677 .help = "Turn off copy-on-write (valid only on btrfs)"
1680 .name = BLOCK_OPT_PREALLOC,
1681 .type = QEMU_OPT_STRING,
1682 .help = "Preallocation mode (allowed values: off, falloc, full)"
1684 { /* end of list */ }
1688 BlockDriver bdrv_file = {
1689 .format_name = "file",
1690 .protocol_name = "file",
1691 .instance_size = sizeof(BDRVRawState),
1692 .bdrv_needs_filename = true,
1693 .bdrv_probe = NULL, /* no probe for protocols */
1694 .bdrv_parse_filename = raw_parse_filename,
1695 .bdrv_file_open = raw_open,
1696 .bdrv_reopen_prepare = raw_reopen_prepare,
1697 .bdrv_reopen_commit = raw_reopen_commit,
1698 .bdrv_reopen_abort = raw_reopen_abort,
1699 .bdrv_close = raw_close,
1700 .bdrv_create = raw_create,
1701 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1702 .bdrv_co_get_block_status = raw_co_get_block_status,
1703 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1705 .bdrv_aio_readv = raw_aio_readv,
1706 .bdrv_aio_writev = raw_aio_writev,
1707 .bdrv_aio_flush = raw_aio_flush,
1708 .bdrv_aio_discard = raw_aio_discard,
1709 .bdrv_refresh_limits = raw_refresh_limits,
1710 .bdrv_io_plug = raw_aio_plug,
1711 .bdrv_io_unplug = raw_aio_unplug,
1712 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1714 .bdrv_truncate = raw_truncate,
1715 .bdrv_getlength = raw_getlength,
1716 .bdrv_get_info = raw_get_info,
1717 .bdrv_get_allocated_file_size
1718 = raw_get_allocated_file_size,
1720 .bdrv_detach_aio_context = raw_detach_aio_context,
1721 .bdrv_attach_aio_context = raw_attach_aio_context,
1723 .create_opts = &raw_create_opts,
1726 /***********************************************/
1727 /* host device */
1729 #if defined(__APPLE__) && defined(__MACH__)
1730 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1731 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1733 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1735 kern_return_t kernResult;
1736 mach_port_t masterPort;
1737 CFMutableDictionaryRef classesToMatch;
1739 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1740 if ( KERN_SUCCESS != kernResult ) {
1741 printf( "IOMasterPort returned %d\n", kernResult );
1744 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1745 if ( classesToMatch == NULL ) {
1746 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1747 } else {
1748 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1750 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1751 if ( KERN_SUCCESS != kernResult )
1753 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1756 return kernResult;
1759 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1761 io_object_t nextMedia;
1762 kern_return_t kernResult = KERN_FAILURE;
1763 *bsdPath = '\0';
1764 nextMedia = IOIteratorNext( mediaIterator );
1765 if ( nextMedia )
1767 CFTypeRef bsdPathAsCFString;
1768 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1769 if ( bsdPathAsCFString ) {
1770 size_t devPathLength;
1771 strcpy( bsdPath, _PATH_DEV );
1772 strcat( bsdPath, "r" );
1773 devPathLength = strlen( bsdPath );
1774 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1775 kernResult = KERN_SUCCESS;
1777 CFRelease( bsdPathAsCFString );
1779 IOObjectRelease( nextMedia );
1782 return kernResult;
1785 #endif
1787 static int hdev_probe_device(const char *filename)
1789 struct stat st;
1791 /* allow a dedicated CD-ROM driver to match with a higher priority */
1792 if (strstart(filename, "/dev/cdrom", NULL))
1793 return 50;
1795 if (stat(filename, &st) >= 0 &&
1796 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1797 return 100;
1800 return 0;
1803 static int check_hdev_writable(BDRVRawState *s)
1805 #if defined(BLKROGET)
1806 /* Linux block devices can be configured "read-only" using blockdev(8).
1807 * This is independent of device node permissions and therefore open(2)
1808 * with O_RDWR succeeds. Actual writes fail with EPERM.
1810 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1811 * check for read-only block devices so that Linux block devices behave
1812 * properly.
1814 struct stat st;
1815 int readonly = 0;
1817 if (fstat(s->fd, &st)) {
1818 return -errno;
1821 if (!S_ISBLK(st.st_mode)) {
1822 return 0;
1825 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1826 return -errno;
1829 if (readonly) {
1830 return -EACCES;
1832 #endif /* defined(BLKROGET) */
1833 return 0;
1836 static void hdev_parse_filename(const char *filename, QDict *options,
1837 Error **errp)
1839 /* The prefix is optional, just as for "file". */
1840 strstart(filename, "host_device:", &filename);
1842 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1845 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1846 Error **errp)
1848 BDRVRawState *s = bs->opaque;
1849 Error *local_err = NULL;
1850 int ret;
1851 const char *filename = qdict_get_str(options, "filename");
1853 #if defined(__APPLE__) && defined(__MACH__)
1854 if (strstart(filename, "/dev/cdrom", NULL)) {
1855 kern_return_t kernResult;
1856 io_iterator_t mediaIterator;
1857 char bsdPath[ MAXPATHLEN ];
1858 int fd;
1860 kernResult = FindEjectableCDMedia( &mediaIterator );
1861 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1863 if ( bsdPath[ 0 ] != '\0' ) {
1864 strcat(bsdPath,"s0");
1865 /* some CDs don't have a partition 0 */
1866 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1867 if (fd < 0) {
1868 bsdPath[strlen(bsdPath)-1] = '1';
1869 } else {
1870 qemu_close(fd);
1872 filename = bsdPath;
1873 qdict_put(options, "filename", qstring_from_str(filename));
1876 if ( mediaIterator )
1877 IOObjectRelease( mediaIterator );
1879 #endif
1881 s->type = FTYPE_FILE;
1882 #if defined(__linux__)
1884 char resolved_path[ MAXPATHLEN ], *temp;
1886 temp = realpath(filename, resolved_path);
1887 if (temp && strstart(temp, "/dev/sg", NULL)) {
1888 bs->sg = 1;
1891 #endif
1893 ret = raw_open_common(bs, options, flags, 0, &local_err);
1894 if (ret < 0) {
1895 if (local_err) {
1896 error_propagate(errp, local_err);
1898 return ret;
1901 if (flags & BDRV_O_RDWR) {
1902 ret = check_hdev_writable(s);
1903 if (ret < 0) {
1904 raw_close(bs);
1905 error_setg_errno(errp, -ret, "The device is not writable");
1906 return ret;
1910 return ret;
1913 #if defined(__linux__)
1914 /* Note: we do not have a reliable method to detect if the floppy is
1915 present. The current method is to try to open the floppy at every
1916 I/O and to keep it opened during a few hundreds of ms. */
1917 static int fd_open(BlockDriverState *bs)
1919 BDRVRawState *s = bs->opaque;
1920 int last_media_present;
1922 if (s->type != FTYPE_FD)
1923 return 0;
1924 last_media_present = (s->fd >= 0);
1925 if (s->fd >= 0 &&
1926 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1927 qemu_close(s->fd);
1928 s->fd = -1;
1929 #ifdef DEBUG_FLOPPY
1930 printf("Floppy closed\n");
1931 #endif
1933 if (s->fd < 0) {
1934 if (s->fd_got_error &&
1935 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1936 #ifdef DEBUG_FLOPPY
1937 printf("No floppy (open delayed)\n");
1938 #endif
1939 return -EIO;
1941 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1942 if (s->fd < 0) {
1943 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1944 s->fd_got_error = 1;
1945 if (last_media_present)
1946 s->fd_media_changed = 1;
1947 #ifdef DEBUG_FLOPPY
1948 printf("No floppy\n");
1949 #endif
1950 return -EIO;
1952 #ifdef DEBUG_FLOPPY
1953 printf("Floppy opened\n");
1954 #endif
1956 if (!last_media_present)
1957 s->fd_media_changed = 1;
1958 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1959 s->fd_got_error = 0;
1960 return 0;
1963 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1965 BDRVRawState *s = bs->opaque;
1967 return ioctl(s->fd, req, buf);
1970 static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1971 unsigned long int req, void *buf,
1972 BlockCompletionFunc *cb, void *opaque)
1974 BDRVRawState *s = bs->opaque;
1975 RawPosixAIOData *acb;
1976 ThreadPool *pool;
1978 if (fd_open(bs) < 0)
1979 return NULL;
1981 acb = g_slice_new(RawPosixAIOData);
1982 acb->bs = bs;
1983 acb->aio_type = QEMU_AIO_IOCTL;
1984 acb->aio_fildes = s->fd;
1985 acb->aio_offset = 0;
1986 acb->aio_ioctl_buf = buf;
1987 acb->aio_ioctl_cmd = req;
1988 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1989 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1992 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1993 static int fd_open(BlockDriverState *bs)
1995 BDRVRawState *s = bs->opaque;
1997 /* this is just to ensure s->fd is sane (its called by io ops) */
1998 if (s->fd >= 0)
1999 return 0;
2000 return -EIO;
2002 #else /* !linux && !FreeBSD */
2004 static int fd_open(BlockDriverState *bs)
2006 return 0;
2009 #endif /* !linux && !FreeBSD */
2011 static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2012 int64_t sector_num, int nb_sectors,
2013 BlockCompletionFunc *cb, void *opaque)
2015 BDRVRawState *s = bs->opaque;
2017 if (fd_open(bs) < 0) {
2018 return NULL;
2020 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2021 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2024 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2025 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2027 BDRVRawState *s = bs->opaque;
2028 int rc;
2030 rc = fd_open(bs);
2031 if (rc < 0) {
2032 return rc;
2034 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2035 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2036 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2037 } else if (s->discard_zeroes) {
2038 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2039 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2041 return -ENOTSUP;
2044 static int hdev_create(const char *filename, QemuOpts *opts,
2045 Error **errp)
2047 int fd;
2048 int ret = 0;
2049 struct stat stat_buf;
2050 int64_t total_size = 0;
2051 bool has_prefix;
2053 /* This function is used by all three protocol block drivers and therefore
2054 * any of these three prefixes may be given.
2055 * The return value has to be stored somewhere, otherwise this is an error
2056 * due to -Werror=unused-value. */
2057 has_prefix =
2058 strstart(filename, "host_device:", &filename) ||
2059 strstart(filename, "host_cdrom:" , &filename) ||
2060 strstart(filename, "host_floppy:", &filename);
2062 (void)has_prefix;
2064 /* Read out options */
2065 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2066 BDRV_SECTOR_SIZE);
2068 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2069 if (fd < 0) {
2070 ret = -errno;
2071 error_setg_errno(errp, -ret, "Could not open device");
2072 return ret;
2075 if (fstat(fd, &stat_buf) < 0) {
2076 ret = -errno;
2077 error_setg_errno(errp, -ret, "Could not stat device");
2078 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2079 error_setg(errp,
2080 "The given file is neither a block nor a character device");
2081 ret = -ENODEV;
2082 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2083 error_setg(errp, "Device is too small");
2084 ret = -ENOSPC;
2087 qemu_close(fd);
2088 return ret;
2091 static BlockDriver bdrv_host_device = {
2092 .format_name = "host_device",
2093 .protocol_name = "host_device",
2094 .instance_size = sizeof(BDRVRawState),
2095 .bdrv_needs_filename = true,
2096 .bdrv_probe_device = hdev_probe_device,
2097 .bdrv_parse_filename = hdev_parse_filename,
2098 .bdrv_file_open = hdev_open,
2099 .bdrv_close = raw_close,
2100 .bdrv_reopen_prepare = raw_reopen_prepare,
2101 .bdrv_reopen_commit = raw_reopen_commit,
2102 .bdrv_reopen_abort = raw_reopen_abort,
2103 .bdrv_create = hdev_create,
2104 .create_opts = &raw_create_opts,
2105 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2107 .bdrv_aio_readv = raw_aio_readv,
2108 .bdrv_aio_writev = raw_aio_writev,
2109 .bdrv_aio_flush = raw_aio_flush,
2110 .bdrv_aio_discard = hdev_aio_discard,
2111 .bdrv_refresh_limits = raw_refresh_limits,
2112 .bdrv_io_plug = raw_aio_plug,
2113 .bdrv_io_unplug = raw_aio_unplug,
2114 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2116 .bdrv_truncate = raw_truncate,
2117 .bdrv_getlength = raw_getlength,
2118 .bdrv_get_info = raw_get_info,
2119 .bdrv_get_allocated_file_size
2120 = raw_get_allocated_file_size,
2122 .bdrv_detach_aio_context = raw_detach_aio_context,
2123 .bdrv_attach_aio_context = raw_attach_aio_context,
2125 /* generic scsi device */
2126 #ifdef __linux__
2127 .bdrv_ioctl = hdev_ioctl,
2128 .bdrv_aio_ioctl = hdev_aio_ioctl,
2129 #endif
2132 #ifdef __linux__
2133 static void floppy_parse_filename(const char *filename, QDict *options,
2134 Error **errp)
2136 /* The prefix is optional, just as for "file". */
2137 strstart(filename, "host_floppy:", &filename);
2139 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2142 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2143 Error **errp)
2145 BDRVRawState *s = bs->opaque;
2146 Error *local_err = NULL;
2147 int ret;
2149 s->type = FTYPE_FD;
2151 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2152 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2153 if (ret) {
2154 if (local_err) {
2155 error_propagate(errp, local_err);
2157 return ret;
2160 /* close fd so that we can reopen it as needed */
2161 qemu_close(s->fd);
2162 s->fd = -1;
2163 s->fd_media_changed = 1;
2165 return 0;
2168 static int floppy_probe_device(const char *filename)
2170 int fd, ret;
2171 int prio = 0;
2172 struct floppy_struct fdparam;
2173 struct stat st;
2175 if (strstart(filename, "/dev/fd", NULL) &&
2176 !strstart(filename, "/dev/fdset/", NULL)) {
2177 prio = 50;
2180 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2181 if (fd < 0) {
2182 goto out;
2184 ret = fstat(fd, &st);
2185 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2186 goto outc;
2189 /* Attempt to detect via a floppy specific ioctl */
2190 ret = ioctl(fd, FDGETPRM, &fdparam);
2191 if (ret >= 0)
2192 prio = 100;
2194 outc:
2195 qemu_close(fd);
2196 out:
2197 return prio;
2201 static int floppy_is_inserted(BlockDriverState *bs)
2203 return fd_open(bs) >= 0;
2206 static int floppy_media_changed(BlockDriverState *bs)
2208 BDRVRawState *s = bs->opaque;
2209 int ret;
2212 * XXX: we do not have a true media changed indication.
2213 * It does not work if the floppy is changed without trying to read it.
2215 fd_open(bs);
2216 ret = s->fd_media_changed;
2217 s->fd_media_changed = 0;
2218 #ifdef DEBUG_FLOPPY
2219 printf("Floppy changed=%d\n", ret);
2220 #endif
2221 return ret;
2224 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2226 BDRVRawState *s = bs->opaque;
2227 int fd;
2229 if (s->fd >= 0) {
2230 qemu_close(s->fd);
2231 s->fd = -1;
2233 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2234 if (fd >= 0) {
2235 if (ioctl(fd, FDEJECT, 0) < 0)
2236 perror("FDEJECT");
2237 qemu_close(fd);
2241 static BlockDriver bdrv_host_floppy = {
2242 .format_name = "host_floppy",
2243 .protocol_name = "host_floppy",
2244 .instance_size = sizeof(BDRVRawState),
2245 .bdrv_needs_filename = true,
2246 .bdrv_probe_device = floppy_probe_device,
2247 .bdrv_parse_filename = floppy_parse_filename,
2248 .bdrv_file_open = floppy_open,
2249 .bdrv_close = raw_close,
2250 .bdrv_reopen_prepare = raw_reopen_prepare,
2251 .bdrv_reopen_commit = raw_reopen_commit,
2252 .bdrv_reopen_abort = raw_reopen_abort,
2253 .bdrv_create = hdev_create,
2254 .create_opts = &raw_create_opts,
2256 .bdrv_aio_readv = raw_aio_readv,
2257 .bdrv_aio_writev = raw_aio_writev,
2258 .bdrv_aio_flush = raw_aio_flush,
2259 .bdrv_refresh_limits = raw_refresh_limits,
2260 .bdrv_io_plug = raw_aio_plug,
2261 .bdrv_io_unplug = raw_aio_unplug,
2262 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2264 .bdrv_truncate = raw_truncate,
2265 .bdrv_getlength = raw_getlength,
2266 .has_variable_length = true,
2267 .bdrv_get_allocated_file_size
2268 = raw_get_allocated_file_size,
2270 .bdrv_detach_aio_context = raw_detach_aio_context,
2271 .bdrv_attach_aio_context = raw_attach_aio_context,
2273 /* removable device support */
2274 .bdrv_is_inserted = floppy_is_inserted,
2275 .bdrv_media_changed = floppy_media_changed,
2276 .bdrv_eject = floppy_eject,
2278 #endif
2280 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2281 static void cdrom_parse_filename(const char *filename, QDict *options,
2282 Error **errp)
2284 /* The prefix is optional, just as for "file". */
2285 strstart(filename, "host_cdrom:", &filename);
2287 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2289 #endif
2291 #ifdef __linux__
2292 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2293 Error **errp)
2295 BDRVRawState *s = bs->opaque;
2296 Error *local_err = NULL;
2297 int ret;
2299 s->type = FTYPE_CD;
2301 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2302 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2303 if (local_err) {
2304 error_propagate(errp, local_err);
2306 return ret;
2309 static int cdrom_probe_device(const char *filename)
2311 int fd, ret;
2312 int prio = 0;
2313 struct stat st;
2315 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2316 if (fd < 0) {
2317 goto out;
2319 ret = fstat(fd, &st);
2320 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2321 goto outc;
2324 /* Attempt to detect via a CDROM specific ioctl */
2325 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2326 if (ret >= 0)
2327 prio = 100;
2329 outc:
2330 qemu_close(fd);
2331 out:
2332 return prio;
2335 static int cdrom_is_inserted(BlockDriverState *bs)
2337 BDRVRawState *s = bs->opaque;
2338 int ret;
2340 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2341 if (ret == CDS_DISC_OK)
2342 return 1;
2343 return 0;
2346 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2348 BDRVRawState *s = bs->opaque;
2350 if (eject_flag) {
2351 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2352 perror("CDROMEJECT");
2353 } else {
2354 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2355 perror("CDROMEJECT");
2359 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2361 BDRVRawState *s = bs->opaque;
2363 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2365 * Note: an error can happen if the distribution automatically
2366 * mounts the CD-ROM
2368 /* perror("CDROM_LOCKDOOR"); */
2372 static BlockDriver bdrv_host_cdrom = {
2373 .format_name = "host_cdrom",
2374 .protocol_name = "host_cdrom",
2375 .instance_size = sizeof(BDRVRawState),
2376 .bdrv_needs_filename = true,
2377 .bdrv_probe_device = cdrom_probe_device,
2378 .bdrv_parse_filename = cdrom_parse_filename,
2379 .bdrv_file_open = cdrom_open,
2380 .bdrv_close = raw_close,
2381 .bdrv_reopen_prepare = raw_reopen_prepare,
2382 .bdrv_reopen_commit = raw_reopen_commit,
2383 .bdrv_reopen_abort = raw_reopen_abort,
2384 .bdrv_create = hdev_create,
2385 .create_opts = &raw_create_opts,
2387 .bdrv_aio_readv = raw_aio_readv,
2388 .bdrv_aio_writev = raw_aio_writev,
2389 .bdrv_aio_flush = raw_aio_flush,
2390 .bdrv_refresh_limits = raw_refresh_limits,
2391 .bdrv_io_plug = raw_aio_plug,
2392 .bdrv_io_unplug = raw_aio_unplug,
2393 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2395 .bdrv_truncate = raw_truncate,
2396 .bdrv_getlength = raw_getlength,
2397 .has_variable_length = true,
2398 .bdrv_get_allocated_file_size
2399 = raw_get_allocated_file_size,
2401 .bdrv_detach_aio_context = raw_detach_aio_context,
2402 .bdrv_attach_aio_context = raw_attach_aio_context,
2404 /* removable device support */
2405 .bdrv_is_inserted = cdrom_is_inserted,
2406 .bdrv_eject = cdrom_eject,
2407 .bdrv_lock_medium = cdrom_lock_medium,
2409 /* generic scsi device */
2410 .bdrv_ioctl = hdev_ioctl,
2411 .bdrv_aio_ioctl = hdev_aio_ioctl,
2413 #endif /* __linux__ */
2415 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2416 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2417 Error **errp)
2419 BDRVRawState *s = bs->opaque;
2420 Error *local_err = NULL;
2421 int ret;
2423 s->type = FTYPE_CD;
2425 ret = raw_open_common(bs, options, flags, 0, &local_err);
2426 if (ret) {
2427 if (local_err) {
2428 error_propagate(errp, local_err);
2430 return ret;
2433 /* make sure the door isn't locked at this time */
2434 ioctl(s->fd, CDIOCALLOW);
2435 return 0;
2438 static int cdrom_probe_device(const char *filename)
2440 if (strstart(filename, "/dev/cd", NULL) ||
2441 strstart(filename, "/dev/acd", NULL))
2442 return 100;
2443 return 0;
2446 static int cdrom_reopen(BlockDriverState *bs)
2448 BDRVRawState *s = bs->opaque;
2449 int fd;
2452 * Force reread of possibly changed/newly loaded disc,
2453 * FreeBSD seems to not notice sometimes...
2455 if (s->fd >= 0)
2456 qemu_close(s->fd);
2457 fd = qemu_open(bs->filename, s->open_flags, 0644);
2458 if (fd < 0) {
2459 s->fd = -1;
2460 return -EIO;
2462 s->fd = fd;
2464 /* make sure the door isn't locked at this time */
2465 ioctl(s->fd, CDIOCALLOW);
2466 return 0;
2469 static int cdrom_is_inserted(BlockDriverState *bs)
2471 return raw_getlength(bs) > 0;
2474 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2476 BDRVRawState *s = bs->opaque;
2478 if (s->fd < 0)
2479 return;
2481 (void) ioctl(s->fd, CDIOCALLOW);
2483 if (eject_flag) {
2484 if (ioctl(s->fd, CDIOCEJECT) < 0)
2485 perror("CDIOCEJECT");
2486 } else {
2487 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2488 perror("CDIOCCLOSE");
2491 cdrom_reopen(bs);
2494 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2496 BDRVRawState *s = bs->opaque;
2498 if (s->fd < 0)
2499 return;
2500 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2502 * Note: an error can happen if the distribution automatically
2503 * mounts the CD-ROM
2505 /* perror("CDROM_LOCKDOOR"); */
2509 static BlockDriver bdrv_host_cdrom = {
2510 .format_name = "host_cdrom",
2511 .protocol_name = "host_cdrom",
2512 .instance_size = sizeof(BDRVRawState),
2513 .bdrv_needs_filename = true,
2514 .bdrv_probe_device = cdrom_probe_device,
2515 .bdrv_parse_filename = cdrom_parse_filename,
2516 .bdrv_file_open = cdrom_open,
2517 .bdrv_close = raw_close,
2518 .bdrv_reopen_prepare = raw_reopen_prepare,
2519 .bdrv_reopen_commit = raw_reopen_commit,
2520 .bdrv_reopen_abort = raw_reopen_abort,
2521 .bdrv_create = hdev_create,
2522 .create_opts = &raw_create_opts,
2524 .bdrv_aio_readv = raw_aio_readv,
2525 .bdrv_aio_writev = raw_aio_writev,
2526 .bdrv_aio_flush = raw_aio_flush,
2527 .bdrv_refresh_limits = raw_refresh_limits,
2528 .bdrv_io_plug = raw_aio_plug,
2529 .bdrv_io_unplug = raw_aio_unplug,
2530 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2532 .bdrv_truncate = raw_truncate,
2533 .bdrv_getlength = raw_getlength,
2534 .has_variable_length = true,
2535 .bdrv_get_allocated_file_size
2536 = raw_get_allocated_file_size,
2538 .bdrv_detach_aio_context = raw_detach_aio_context,
2539 .bdrv_attach_aio_context = raw_attach_aio_context,
2541 /* removable device support */
2542 .bdrv_is_inserted = cdrom_is_inserted,
2543 .bdrv_eject = cdrom_eject,
2544 .bdrv_lock_medium = cdrom_lock_medium,
2546 #endif /* __FreeBSD__ */
2548 static void bdrv_file_init(void)
2551 * Register all the drivers. Note that order is important, the driver
2552 * registered last will get probed first.
2554 bdrv_register(&bdrv_file);
2555 bdrv_register(&bdrv_host_device);
2556 #ifdef __linux__
2557 bdrv_register(&bdrv_host_floppy);
2558 bdrv_register(&bdrv_host_cdrom);
2559 #endif
2560 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2561 bdrv_register(&bdrv_host_cdrom);
2562 #endif
2565 block_init(bdrv_file_init);