raw-posix: Add falloc and full preallocation option
[qemu.git] / block / raw-posix.c
bloba2536974272b9bb6e3f43de2e41985bba2a1dcf8
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_FIEMAP
64 #include <linux/fiemap.h>
65 #endif
66 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
67 #include <linux/falloc.h>
68 #endif
69 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
70 #include <sys/disk.h>
71 #include <sys/cdio.h>
72 #endif
74 #ifdef __OpenBSD__
75 #include <sys/ioctl.h>
76 #include <sys/disklabel.h>
77 #include <sys/dkio.h>
78 #endif
80 #ifdef __NetBSD__
81 #include <sys/ioctl.h>
82 #include <sys/disklabel.h>
83 #include <sys/dkio.h>
84 #include <sys/disk.h>
85 #endif
87 #ifdef __DragonFly__
88 #include <sys/ioctl.h>
89 #include <sys/diskslice.h>
90 #endif
92 #ifdef CONFIG_XFS
93 #include <xfs/xfs.h>
94 #endif
96 //#define DEBUG_FLOPPY
98 //#define DEBUG_BLOCK
99 #if defined(DEBUG_BLOCK)
100 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
101 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
102 #else
103 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
104 #endif
106 /* OS X does not have O_DSYNC */
107 #ifndef O_DSYNC
108 #ifdef O_SYNC
109 #define O_DSYNC O_SYNC
110 #elif defined(O_FSYNC)
111 #define O_DSYNC O_FSYNC
112 #endif
113 #endif
115 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
116 #ifndef O_DIRECT
117 #define O_DIRECT O_DSYNC
118 #endif
120 #define FTYPE_FILE 0
121 #define FTYPE_CD 1
122 #define FTYPE_FD 2
124 /* if the FD is not accessed during that time (in ns), we try to
125 reopen it to see if the disk has been changed */
126 #define FD_OPEN_TIMEOUT (1000000000)
128 #define MAX_BLOCKSIZE 4096
130 typedef struct BDRVRawState {
131 int fd;
132 int type;
133 int open_flags;
134 size_t buf_align;
136 #if defined(__linux__)
137 /* linux floppy specific */
138 int64_t fd_open_time;
139 int64_t fd_error_time;
140 int fd_got_error;
141 int fd_media_changed;
142 #endif
143 #ifdef CONFIG_LINUX_AIO
144 int use_aio;
145 void *aio_ctx;
146 #endif
147 #ifdef CONFIG_XFS
148 bool is_xfs:1;
149 #endif
150 bool has_discard:1;
151 bool has_write_zeroes:1;
152 bool discard_zeroes:1;
153 #ifdef CONFIG_FIEMAP
154 bool skip_fiemap;
155 #endif
156 } BDRVRawState;
158 typedef struct BDRVRawReopenState {
159 int fd;
160 int open_flags;
161 #ifdef CONFIG_LINUX_AIO
162 int use_aio;
163 #endif
164 } BDRVRawReopenState;
166 static int fd_open(BlockDriverState *bs);
167 static int64_t raw_getlength(BlockDriverState *bs);
169 typedef struct RawPosixAIOData {
170 BlockDriverState *bs;
171 int aio_fildes;
172 union {
173 struct iovec *aio_iov;
174 void *aio_ioctl_buf;
176 int aio_niov;
177 uint64_t aio_nbytes;
178 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
179 off_t aio_offset;
180 int aio_type;
181 } RawPosixAIOData;
183 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184 static int cdrom_reopen(BlockDriverState *bs);
185 #endif
187 #if defined(__NetBSD__)
188 static int raw_normalize_devicepath(const char **filename)
190 static char namebuf[PATH_MAX];
191 const char *dp, *fname;
192 struct stat sb;
194 fname = *filename;
195 dp = strrchr(fname, '/');
196 if (lstat(fname, &sb) < 0) {
197 fprintf(stderr, "%s: stat failed: %s\n",
198 fname, strerror(errno));
199 return -errno;
202 if (!S_ISBLK(sb.st_mode)) {
203 return 0;
206 if (dp == NULL) {
207 snprintf(namebuf, PATH_MAX, "r%s", fname);
208 } else {
209 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
210 (int)(dp - fname), fname, dp + 1);
212 fprintf(stderr, "%s is a block device", fname);
213 *filename = namebuf;
214 fprintf(stderr, ", using %s\n", *filename);
216 return 0;
218 #else
219 static int raw_normalize_devicepath(const char **filename)
221 return 0;
223 #endif
225 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
227 BDRVRawState *s = bs->opaque;
228 char *buf;
229 unsigned int sector_size;
231 /* For /dev/sg devices the alignment is not really used.
232 With buffered I/O, we don't have any restrictions. */
233 if (bs->sg || !(s->open_flags & O_DIRECT)) {
234 bs->request_alignment = 1;
235 s->buf_align = 1;
236 return;
239 /* Try a few ioctls to get the right size */
240 bs->request_alignment = 0;
241 s->buf_align = 0;
243 #ifdef BLKSSZGET
244 if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
245 bs->request_alignment = sector_size;
247 #endif
248 #ifdef DKIOCGETBLOCKSIZE
249 if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
250 bs->request_alignment = sector_size;
252 #endif
253 #ifdef DIOCGSECTORSIZE
254 if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
255 bs->request_alignment = sector_size;
257 #endif
258 #ifdef CONFIG_XFS
259 if (s->is_xfs) {
260 struct dioattr da;
261 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
262 bs->request_alignment = da.d_miniosz;
263 /* The kernel returns wrong information for d_mem */
264 /* s->buf_align = da.d_mem; */
267 #endif
269 /* If we could not get the sizes so far, we can only guess them */
270 if (!s->buf_align) {
271 size_t align;
272 buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
273 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
274 if (pread(fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
275 s->buf_align = align;
276 break;
279 qemu_vfree(buf);
282 if (!bs->request_alignment) {
283 size_t align;
284 buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
285 for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
286 if (pread(fd, buf, align, 0) >= 0) {
287 bs->request_alignment = align;
288 break;
291 qemu_vfree(buf);
294 if (!s->buf_align || !bs->request_alignment) {
295 error_setg(errp, "Could not find working O_DIRECT alignment. "
296 "Try cache.direct=off.");
300 static void raw_parse_flags(int bdrv_flags, int *open_flags)
302 assert(open_flags != NULL);
304 *open_flags |= O_BINARY;
305 *open_flags &= ~O_ACCMODE;
306 if (bdrv_flags & BDRV_O_RDWR) {
307 *open_flags |= O_RDWR;
308 } else {
309 *open_flags |= O_RDONLY;
312 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
313 * and O_DIRECT for no caching. */
314 if ((bdrv_flags & BDRV_O_NOCACHE)) {
315 *open_flags |= O_DIRECT;
319 static void raw_detach_aio_context(BlockDriverState *bs)
321 #ifdef CONFIG_LINUX_AIO
322 BDRVRawState *s = bs->opaque;
324 if (s->use_aio) {
325 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
327 #endif
330 static void raw_attach_aio_context(BlockDriverState *bs,
331 AioContext *new_context)
333 #ifdef CONFIG_LINUX_AIO
334 BDRVRawState *s = bs->opaque;
336 if (s->use_aio) {
337 laio_attach_aio_context(s->aio_ctx, new_context);
339 #endif
342 #ifdef CONFIG_LINUX_AIO
343 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
345 int ret = -1;
346 assert(aio_ctx != NULL);
347 assert(use_aio != NULL);
349 * Currently Linux do AIO only for files opened with O_DIRECT
350 * specified so check NOCACHE flag too
352 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
353 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
355 /* if non-NULL, laio_init() has already been run */
356 if (*aio_ctx == NULL) {
357 *aio_ctx = laio_init();
358 if (!*aio_ctx) {
359 goto error;
362 *use_aio = 1;
363 } else {
364 *use_aio = 0;
367 ret = 0;
369 error:
370 return ret;
372 #endif
374 static void raw_parse_filename(const char *filename, QDict *options,
375 Error **errp)
377 /* The filename does not have to be prefixed by the protocol name, since
378 * "file" is the default protocol; therefore, the return value of this
379 * function call can be ignored. */
380 strstart(filename, "file:", &filename);
382 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
385 static QemuOptsList raw_runtime_opts = {
386 .name = "raw",
387 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
388 .desc = {
390 .name = "filename",
391 .type = QEMU_OPT_STRING,
392 .help = "File name of the image",
394 { /* end of list */ }
398 static int raw_open_common(BlockDriverState *bs, QDict *options,
399 int bdrv_flags, int open_flags, Error **errp)
401 BDRVRawState *s = bs->opaque;
402 QemuOpts *opts;
403 Error *local_err = NULL;
404 const char *filename = NULL;
405 int fd, ret;
406 struct stat st;
408 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
409 qemu_opts_absorb_qdict(opts, options, &local_err);
410 if (local_err) {
411 error_propagate(errp, local_err);
412 ret = -EINVAL;
413 goto fail;
416 filename = qemu_opt_get(opts, "filename");
418 ret = raw_normalize_devicepath(&filename);
419 if (ret != 0) {
420 error_setg_errno(errp, -ret, "Could not normalize device path");
421 goto fail;
424 s->open_flags = open_flags;
425 raw_parse_flags(bdrv_flags, &s->open_flags);
427 s->fd = -1;
428 fd = qemu_open(filename, s->open_flags, 0644);
429 if (fd < 0) {
430 ret = -errno;
431 if (ret == -EROFS) {
432 ret = -EACCES;
434 goto fail;
436 s->fd = fd;
438 #ifdef CONFIG_LINUX_AIO
439 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
440 qemu_close(fd);
441 ret = -errno;
442 error_setg_errno(errp, -ret, "Could not set AIO state");
443 goto fail;
445 #endif
447 s->has_discard = true;
448 s->has_write_zeroes = true;
450 if (fstat(s->fd, &st) < 0) {
451 error_setg_errno(errp, errno, "Could not stat file");
452 goto fail;
454 if (S_ISREG(st.st_mode)) {
455 s->discard_zeroes = true;
457 if (S_ISBLK(st.st_mode)) {
458 #ifdef BLKDISCARDZEROES
459 unsigned int arg;
460 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
461 s->discard_zeroes = true;
463 #endif
464 #ifdef __linux__
465 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
466 * not rely on the contents of discarded blocks unless using O_DIRECT.
467 * Same for BLKZEROOUT.
469 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
470 s->discard_zeroes = false;
471 s->has_write_zeroes = false;
473 #endif
476 #ifdef CONFIG_XFS
477 if (platform_test_xfs_fd(s->fd)) {
478 s->is_xfs = true;
480 #endif
482 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
484 ret = 0;
485 fail:
486 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
487 unlink(filename);
489 qemu_opts_del(opts);
490 return ret;
493 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
494 Error **errp)
496 BDRVRawState *s = bs->opaque;
497 Error *local_err = NULL;
498 int ret;
500 s->type = FTYPE_FILE;
501 ret = raw_open_common(bs, options, flags, 0, &local_err);
502 if (local_err) {
503 error_propagate(errp, local_err);
505 return ret;
508 static int raw_reopen_prepare(BDRVReopenState *state,
509 BlockReopenQueue *queue, Error **errp)
511 BDRVRawState *s;
512 BDRVRawReopenState *raw_s;
513 int ret = 0;
514 Error *local_err = NULL;
516 assert(state != NULL);
517 assert(state->bs != NULL);
519 s = state->bs->opaque;
521 state->opaque = g_new0(BDRVRawReopenState, 1);
522 raw_s = state->opaque;
524 #ifdef CONFIG_LINUX_AIO
525 raw_s->use_aio = s->use_aio;
527 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
528 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
529 * won't override aio_ctx if aio_ctx is non-NULL */
530 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
531 error_setg(errp, "Could not set AIO state");
532 return -1;
534 #endif
536 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
537 raw_s->open_flags |= O_NONBLOCK;
540 raw_parse_flags(state->flags, &raw_s->open_flags);
542 raw_s->fd = -1;
544 int fcntl_flags = O_APPEND | O_NONBLOCK;
545 #ifdef O_NOATIME
546 fcntl_flags |= O_NOATIME;
547 #endif
549 #ifdef O_ASYNC
550 /* Not all operating systems have O_ASYNC, and those that don't
551 * will not let us track the state into raw_s->open_flags (typically
552 * you achieve the same effect with an ioctl, for example I_SETSIG
553 * on Solaris). But we do not use O_ASYNC, so that's fine.
555 assert((s->open_flags & O_ASYNC) == 0);
556 #endif
558 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
559 /* dup the original fd */
560 /* TODO: use qemu fcntl wrapper */
561 #ifdef F_DUPFD_CLOEXEC
562 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
563 #else
564 raw_s->fd = dup(s->fd);
565 if (raw_s->fd != -1) {
566 qemu_set_cloexec(raw_s->fd);
568 #endif
569 if (raw_s->fd >= 0) {
570 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
571 if (ret) {
572 qemu_close(raw_s->fd);
573 raw_s->fd = -1;
578 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
579 if (raw_s->fd == -1) {
580 assert(!(raw_s->open_flags & O_CREAT));
581 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
582 if (raw_s->fd == -1) {
583 error_setg_errno(errp, errno, "Could not reopen file");
584 ret = -1;
588 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
589 * alignment with the new fd. */
590 if (raw_s->fd != -1) {
591 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
592 if (local_err) {
593 qemu_close(raw_s->fd);
594 raw_s->fd = -1;
595 error_propagate(errp, local_err);
596 ret = -EINVAL;
600 return ret;
603 static void raw_reopen_commit(BDRVReopenState *state)
605 BDRVRawReopenState *raw_s = state->opaque;
606 BDRVRawState *s = state->bs->opaque;
608 s->open_flags = raw_s->open_flags;
610 qemu_close(s->fd);
611 s->fd = raw_s->fd;
612 #ifdef CONFIG_LINUX_AIO
613 s->use_aio = raw_s->use_aio;
614 #endif
616 g_free(state->opaque);
617 state->opaque = NULL;
621 static void raw_reopen_abort(BDRVReopenState *state)
623 BDRVRawReopenState *raw_s = state->opaque;
625 /* nothing to do if NULL, we didn't get far enough */
626 if (raw_s == NULL) {
627 return;
630 if (raw_s->fd >= 0) {
631 qemu_close(raw_s->fd);
632 raw_s->fd = -1;
634 g_free(state->opaque);
635 state->opaque = NULL;
638 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
640 BDRVRawState *s = bs->opaque;
642 raw_probe_alignment(bs, s->fd, errp);
643 bs->bl.opt_mem_alignment = s->buf_align;
646 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
648 int ret;
650 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
651 if (ret == -1) {
652 return -errno;
655 return 0;
658 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
660 int ret;
662 ret = qemu_fdatasync(aiocb->aio_fildes);
663 if (ret == -1) {
664 return -errno;
666 return 0;
669 #ifdef CONFIG_PREADV
671 static bool preadv_present = true;
673 static ssize_t
674 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
676 return preadv(fd, iov, nr_iov, offset);
679 static ssize_t
680 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
682 return pwritev(fd, iov, nr_iov, offset);
685 #else
687 static bool preadv_present = false;
689 static ssize_t
690 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
692 return -ENOSYS;
695 static ssize_t
696 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
698 return -ENOSYS;
701 #endif
703 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
705 ssize_t len;
707 do {
708 if (aiocb->aio_type & QEMU_AIO_WRITE)
709 len = qemu_pwritev(aiocb->aio_fildes,
710 aiocb->aio_iov,
711 aiocb->aio_niov,
712 aiocb->aio_offset);
713 else
714 len = qemu_preadv(aiocb->aio_fildes,
715 aiocb->aio_iov,
716 aiocb->aio_niov,
717 aiocb->aio_offset);
718 } while (len == -1 && errno == EINTR);
720 if (len == -1) {
721 return -errno;
723 return len;
727 * Read/writes the data to/from a given linear buffer.
729 * Returns the number of bytes handles or -errno in case of an error. Short
730 * reads are only returned if the end of the file is reached.
732 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
734 ssize_t offset = 0;
735 ssize_t len;
737 while (offset < aiocb->aio_nbytes) {
738 if (aiocb->aio_type & QEMU_AIO_WRITE) {
739 len = pwrite(aiocb->aio_fildes,
740 (const char *)buf + offset,
741 aiocb->aio_nbytes - offset,
742 aiocb->aio_offset + offset);
743 } else {
744 len = pread(aiocb->aio_fildes,
745 buf + offset,
746 aiocb->aio_nbytes - offset,
747 aiocb->aio_offset + offset);
749 if (len == -1 && errno == EINTR) {
750 continue;
751 } else if (len == -1 && errno == EINVAL &&
752 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
753 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
754 offset > 0) {
755 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
756 * after a short read. Assume that O_DIRECT short reads only occur
757 * at EOF. Therefore this is a short read, not an I/O error.
759 break;
760 } else if (len == -1) {
761 offset = -errno;
762 break;
763 } else if (len == 0) {
764 break;
766 offset += len;
769 return offset;
772 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
774 ssize_t nbytes;
775 char *buf;
777 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
779 * If there is just a single buffer, and it is properly aligned
780 * we can just use plain pread/pwrite without any problems.
782 if (aiocb->aio_niov == 1) {
783 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
786 * We have more than one iovec, and all are properly aligned.
788 * Try preadv/pwritev first and fall back to linearizing the
789 * buffer if it's not supported.
791 if (preadv_present) {
792 nbytes = handle_aiocb_rw_vector(aiocb);
793 if (nbytes == aiocb->aio_nbytes ||
794 (nbytes < 0 && nbytes != -ENOSYS)) {
795 return nbytes;
797 preadv_present = false;
801 * XXX(hch): short read/write. no easy way to handle the reminder
802 * using these interfaces. For now retry using plain
803 * pread/pwrite?
808 * Ok, we have to do it the hard way, copy all segments into
809 * a single aligned buffer.
811 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
812 if (buf == NULL) {
813 return -ENOMEM;
816 if (aiocb->aio_type & QEMU_AIO_WRITE) {
817 char *p = buf;
818 int i;
820 for (i = 0; i < aiocb->aio_niov; ++i) {
821 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
822 p += aiocb->aio_iov[i].iov_len;
824 assert(p - buf == aiocb->aio_nbytes);
827 nbytes = handle_aiocb_rw_linear(aiocb, buf);
828 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
829 char *p = buf;
830 size_t count = aiocb->aio_nbytes, copy;
831 int i;
833 for (i = 0; i < aiocb->aio_niov && count; ++i) {
834 copy = count;
835 if (copy > aiocb->aio_iov[i].iov_len) {
836 copy = aiocb->aio_iov[i].iov_len;
838 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
839 assert(count >= copy);
840 p += copy;
841 count -= copy;
843 assert(count == 0);
845 qemu_vfree(buf);
847 return nbytes;
850 #ifdef CONFIG_XFS
851 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
853 struct xfs_flock64 fl;
855 memset(&fl, 0, sizeof(fl));
856 fl.l_whence = SEEK_SET;
857 fl.l_start = offset;
858 fl.l_len = bytes;
860 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
861 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
862 return -errno;
865 return 0;
868 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
870 struct xfs_flock64 fl;
872 memset(&fl, 0, sizeof(fl));
873 fl.l_whence = SEEK_SET;
874 fl.l_start = offset;
875 fl.l_len = bytes;
877 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
878 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
879 return -errno;
882 return 0;
884 #endif
886 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
888 int ret = -EOPNOTSUPP;
889 BDRVRawState *s = aiocb->bs->opaque;
891 if (s->has_write_zeroes == 0) {
892 return -ENOTSUP;
895 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
896 #ifdef BLKZEROOUT
897 do {
898 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
899 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
900 return 0;
902 } while (errno == EINTR);
904 ret = -errno;
905 #endif
906 } else {
907 #ifdef CONFIG_XFS
908 if (s->is_xfs) {
909 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
911 #endif
914 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
915 ret == -ENOTTY) {
916 s->has_write_zeroes = false;
917 ret = -ENOTSUP;
919 return ret;
922 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
924 int ret = -EOPNOTSUPP;
925 BDRVRawState *s = aiocb->bs->opaque;
927 if (!s->has_discard) {
928 return -ENOTSUP;
931 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
932 #ifdef BLKDISCARD
933 do {
934 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
935 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
936 return 0;
938 } while (errno == EINTR);
940 ret = -errno;
941 #endif
942 } else {
943 #ifdef CONFIG_XFS
944 if (s->is_xfs) {
945 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
947 #endif
949 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
950 do {
951 if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
952 aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
953 return 0;
955 } while (errno == EINTR);
957 ret = -errno;
958 #endif
961 if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
962 ret == -ENOTTY) {
963 s->has_discard = false;
964 ret = -ENOTSUP;
966 return ret;
969 static int aio_worker(void *arg)
971 RawPosixAIOData *aiocb = arg;
972 ssize_t ret = 0;
974 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
975 case QEMU_AIO_READ:
976 ret = handle_aiocb_rw(aiocb);
977 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
978 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
979 0, aiocb->aio_nbytes - ret);
981 ret = aiocb->aio_nbytes;
983 if (ret == aiocb->aio_nbytes) {
984 ret = 0;
985 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
986 ret = -EINVAL;
988 break;
989 case QEMU_AIO_WRITE:
990 ret = handle_aiocb_rw(aiocb);
991 if (ret == aiocb->aio_nbytes) {
992 ret = 0;
993 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
994 ret = -EINVAL;
996 break;
997 case QEMU_AIO_FLUSH:
998 ret = handle_aiocb_flush(aiocb);
999 break;
1000 case QEMU_AIO_IOCTL:
1001 ret = handle_aiocb_ioctl(aiocb);
1002 break;
1003 case QEMU_AIO_DISCARD:
1004 ret = handle_aiocb_discard(aiocb);
1005 break;
1006 case QEMU_AIO_WRITE_ZEROES:
1007 ret = handle_aiocb_write_zeroes(aiocb);
1008 break;
1009 default:
1010 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1011 ret = -EINVAL;
1012 break;
1015 g_slice_free(RawPosixAIOData, aiocb);
1016 return ret;
1019 static int paio_submit_co(BlockDriverState *bs, int fd,
1020 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1021 int type)
1023 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1024 ThreadPool *pool;
1026 acb->bs = bs;
1027 acb->aio_type = type;
1028 acb->aio_fildes = fd;
1030 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1031 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1033 if (qiov) {
1034 acb->aio_iov = qiov->iov;
1035 acb->aio_niov = qiov->niov;
1036 assert(qiov->size == acb->aio_nbytes);
1039 trace_paio_submit_co(sector_num, nb_sectors, type);
1040 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1041 return thread_pool_submit_co(pool, aio_worker, acb);
1044 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
1045 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1046 BlockDriverCompletionFunc *cb, void *opaque, int type)
1048 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1049 ThreadPool *pool;
1051 acb->bs = bs;
1052 acb->aio_type = type;
1053 acb->aio_fildes = fd;
1055 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1056 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1058 if (qiov) {
1059 acb->aio_iov = qiov->iov;
1060 acb->aio_niov = qiov->niov;
1061 assert(qiov->size == acb->aio_nbytes);
1064 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1065 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1066 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1069 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
1070 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1071 BlockDriverCompletionFunc *cb, void *opaque, int type)
1073 BDRVRawState *s = bs->opaque;
1075 if (fd_open(bs) < 0)
1076 return NULL;
1079 * If O_DIRECT is used the buffer needs to be aligned on a sector
1080 * boundary. Check if this is the case or tell the low-level
1081 * driver that it needs to copy the buffer.
1083 if ((bs->open_flags & BDRV_O_NOCACHE)) {
1084 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1085 type |= QEMU_AIO_MISALIGNED;
1086 #ifdef CONFIG_LINUX_AIO
1087 } else if (s->use_aio) {
1088 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1089 nb_sectors, cb, opaque, type);
1090 #endif
1094 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1095 cb, opaque, type);
1098 static void raw_aio_plug(BlockDriverState *bs)
1100 #ifdef CONFIG_LINUX_AIO
1101 BDRVRawState *s = bs->opaque;
1102 if (s->use_aio) {
1103 laio_io_plug(bs, s->aio_ctx);
1105 #endif
1108 static void raw_aio_unplug(BlockDriverState *bs)
1110 #ifdef CONFIG_LINUX_AIO
1111 BDRVRawState *s = bs->opaque;
1112 if (s->use_aio) {
1113 laio_io_unplug(bs, s->aio_ctx, true);
1115 #endif
1118 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1120 #ifdef CONFIG_LINUX_AIO
1121 BDRVRawState *s = bs->opaque;
1122 if (s->use_aio) {
1123 laio_io_unplug(bs, s->aio_ctx, false);
1125 #endif
1128 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
1129 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1130 BlockDriverCompletionFunc *cb, void *opaque)
1132 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1133 cb, opaque, QEMU_AIO_READ);
1136 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
1137 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1138 BlockDriverCompletionFunc *cb, void *opaque)
1140 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1141 cb, opaque, QEMU_AIO_WRITE);
1144 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
1145 BlockDriverCompletionFunc *cb, void *opaque)
1147 BDRVRawState *s = bs->opaque;
1149 if (fd_open(bs) < 0)
1150 return NULL;
1152 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1155 static void raw_close(BlockDriverState *bs)
1157 BDRVRawState *s = bs->opaque;
1159 raw_detach_aio_context(bs);
1161 #ifdef CONFIG_LINUX_AIO
1162 if (s->use_aio) {
1163 laio_cleanup(s->aio_ctx);
1165 #endif
1166 if (s->fd >= 0) {
1167 qemu_close(s->fd);
1168 s->fd = -1;
1172 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1174 BDRVRawState *s = bs->opaque;
1175 struct stat st;
1177 if (fstat(s->fd, &st)) {
1178 return -errno;
1181 if (S_ISREG(st.st_mode)) {
1182 if (ftruncate(s->fd, offset) < 0) {
1183 return -errno;
1185 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1186 if (offset > raw_getlength(bs)) {
1187 return -EINVAL;
1189 } else {
1190 return -ENOTSUP;
1193 return 0;
1196 #ifdef __OpenBSD__
1197 static int64_t raw_getlength(BlockDriverState *bs)
1199 BDRVRawState *s = bs->opaque;
1200 int fd = s->fd;
1201 struct stat st;
1203 if (fstat(fd, &st))
1204 return -errno;
1205 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1206 struct disklabel dl;
1208 if (ioctl(fd, DIOCGDINFO, &dl))
1209 return -errno;
1210 return (uint64_t)dl.d_secsize *
1211 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1212 } else
1213 return st.st_size;
1215 #elif defined(__NetBSD__)
1216 static int64_t raw_getlength(BlockDriverState *bs)
1218 BDRVRawState *s = bs->opaque;
1219 int fd = s->fd;
1220 struct stat st;
1222 if (fstat(fd, &st))
1223 return -errno;
1224 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1225 struct dkwedge_info dkw;
1227 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1228 return dkw.dkw_size * 512;
1229 } else {
1230 struct disklabel dl;
1232 if (ioctl(fd, DIOCGDINFO, &dl))
1233 return -errno;
1234 return (uint64_t)dl.d_secsize *
1235 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1237 } else
1238 return st.st_size;
1240 #elif defined(__sun__)
1241 static int64_t raw_getlength(BlockDriverState *bs)
1243 BDRVRawState *s = bs->opaque;
1244 struct dk_minfo minfo;
1245 int ret;
1246 int64_t size;
1248 ret = fd_open(bs);
1249 if (ret < 0) {
1250 return ret;
1254 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1256 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1257 if (ret != -1) {
1258 return minfo.dki_lbsize * minfo.dki_capacity;
1262 * There are reports that lseek on some devices fails, but
1263 * irc discussion said that contingency on contingency was overkill.
1265 size = lseek(s->fd, 0, SEEK_END);
1266 if (size < 0) {
1267 return -errno;
1269 return size;
1271 #elif defined(CONFIG_BSD)
1272 static int64_t raw_getlength(BlockDriverState *bs)
1274 BDRVRawState *s = bs->opaque;
1275 int fd = s->fd;
1276 int64_t size;
1277 struct stat sb;
1278 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1279 int reopened = 0;
1280 #endif
1281 int ret;
1283 ret = fd_open(bs);
1284 if (ret < 0)
1285 return ret;
1287 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1288 again:
1289 #endif
1290 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1291 #ifdef DIOCGMEDIASIZE
1292 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1293 #elif defined(DIOCGPART)
1295 struct partinfo pi;
1296 if (ioctl(fd, DIOCGPART, &pi) == 0)
1297 size = pi.media_size;
1298 else
1299 size = 0;
1301 if (size == 0)
1302 #endif
1303 #if defined(__APPLE__) && defined(__MACH__)
1304 size = LLONG_MAX;
1305 #else
1306 size = lseek(fd, 0LL, SEEK_END);
1307 if (size < 0) {
1308 return -errno;
1310 #endif
1311 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1312 switch(s->type) {
1313 case FTYPE_CD:
1314 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1315 if (size == 2048LL * (unsigned)-1)
1316 size = 0;
1317 /* XXX no disc? maybe we need to reopen... */
1318 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1319 reopened = 1;
1320 goto again;
1323 #endif
1324 } else {
1325 size = lseek(fd, 0, SEEK_END);
1326 if (size < 0) {
1327 return -errno;
1330 return size;
1332 #else
1333 static int64_t raw_getlength(BlockDriverState *bs)
1335 BDRVRawState *s = bs->opaque;
1336 int ret;
1337 int64_t size;
1339 ret = fd_open(bs);
1340 if (ret < 0) {
1341 return ret;
1344 size = lseek(s->fd, 0, SEEK_END);
1345 if (size < 0) {
1346 return -errno;
1348 return size;
1350 #endif
1352 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1354 struct stat st;
1355 BDRVRawState *s = bs->opaque;
1357 if (fstat(s->fd, &st) < 0) {
1358 return -errno;
1360 return (int64_t)st.st_blocks * 512;
1363 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1365 int fd;
1366 int result = 0;
1367 int64_t total_size = 0;
1368 bool nocow = false;
1369 PreallocMode prealloc;
1370 char *buf = NULL;
1371 Error *local_err = NULL;
1373 strstart(filename, "file:", &filename);
1375 /* Read out options */
1376 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1377 BDRV_SECTOR_SIZE);
1378 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1379 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1380 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1381 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1382 &local_err);
1383 g_free(buf);
1384 if (local_err) {
1385 error_propagate(errp, local_err);
1386 result = -EINVAL;
1387 goto out;
1390 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1391 0644);
1392 if (fd < 0) {
1393 result = -errno;
1394 error_setg_errno(errp, -result, "Could not create file");
1395 goto out;
1398 if (nocow) {
1399 #ifdef __linux__
1400 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1401 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1402 * will be ignored since any failure of this operation should not
1403 * block the left work.
1405 int attr;
1406 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1407 attr |= FS_NOCOW_FL;
1408 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1410 #endif
1413 if (ftruncate(fd, total_size) != 0) {
1414 result = -errno;
1415 error_setg_errno(errp, -result, "Could not resize file");
1416 goto out_close;
1419 if (prealloc == PREALLOC_MODE_FALLOC) {
1420 /* posix_fallocate() doesn't set errno. */
1421 result = -posix_fallocate(fd, 0, total_size);
1422 if (result != 0) {
1423 error_setg_errno(errp, -result,
1424 "Could not preallocate data for the new file");
1426 } else if (prealloc == PREALLOC_MODE_FULL) {
1427 buf = g_malloc0(65536);
1428 int64_t num = 0, left = total_size;
1430 while (left > 0) {
1431 num = MIN(left, 65536);
1432 result = write(fd, buf, num);
1433 if (result < 0) {
1434 result = -errno;
1435 error_setg_errno(errp, -result,
1436 "Could not write to the new file");
1437 break;
1439 left -= num;
1441 fsync(fd);
1442 g_free(buf);
1443 } else if (prealloc != PREALLOC_MODE_OFF) {
1444 result = -EINVAL;
1445 error_setg(errp, "Unsupported preallocation mode: %s",
1446 PreallocMode_lookup[prealloc]);
1449 out_close:
1450 if (qemu_close(fd) != 0 && result == 0) {
1451 result = -errno;
1452 error_setg_errno(errp, -result, "Could not close the new file");
1454 out:
1455 return result;
1458 static int64_t try_fiemap(BlockDriverState *bs, off_t start, off_t *data,
1459 off_t *hole, int nb_sectors, int *pnum)
1461 #ifdef CONFIG_FIEMAP
1462 BDRVRawState *s = bs->opaque;
1463 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1464 struct {
1465 struct fiemap fm;
1466 struct fiemap_extent fe;
1467 } f;
1469 if (s->skip_fiemap) {
1470 return -ENOTSUP;
1473 f.fm.fm_start = start;
1474 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1475 f.fm.fm_flags = 0;
1476 f.fm.fm_extent_count = 1;
1477 f.fm.fm_reserved = 0;
1478 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1479 s->skip_fiemap = true;
1480 return -errno;
1483 if (f.fm.fm_mapped_extents == 0) {
1484 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1485 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1487 off_t length = lseek(s->fd, 0, SEEK_END);
1488 *hole = f.fm.fm_start;
1489 *data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1490 } else {
1491 *data = f.fe.fe_logical;
1492 *hole = f.fe.fe_logical + f.fe.fe_length;
1493 if (f.fe.fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
1494 ret |= BDRV_BLOCK_ZERO;
1498 return ret;
1499 #else
1500 return -ENOTSUP;
1501 #endif
1504 static int64_t try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,
1505 off_t *hole, int *pnum)
1507 #if defined SEEK_HOLE && defined SEEK_DATA
1508 BDRVRawState *s = bs->opaque;
1510 *hole = lseek(s->fd, start, SEEK_HOLE);
1511 if (*hole == -1) {
1512 /* -ENXIO indicates that sector_num was past the end of the file.
1513 * There is a virtual hole there. */
1514 assert(errno != -ENXIO);
1516 return -errno;
1519 if (*hole > start) {
1520 *data = start;
1521 } else {
1522 /* On a hole. We need another syscall to find its end. */
1523 *data = lseek(s->fd, start, SEEK_DATA);
1524 if (*data == -1) {
1525 *data = lseek(s->fd, 0, SEEK_END);
1529 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1530 #else
1531 return -ENOTSUP;
1532 #endif
1536 * Returns true iff the specified sector is present in the disk image. Drivers
1537 * not implementing the functionality are assumed to not support backing files,
1538 * hence all their sectors are reported as allocated.
1540 * If 'sector_num' is beyond the end of the disk image the return value is 0
1541 * and 'pnum' is set to 0.
1543 * 'pnum' is set to the number of sectors (including and immediately following
1544 * the specified sector) that are known to be in the same
1545 * allocated/unallocated state.
1547 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1548 * beyond the end of the disk image it will be clamped.
1550 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1551 int64_t sector_num,
1552 int nb_sectors, int *pnum)
1554 off_t start, data = 0, hole = 0;
1555 int64_t ret;
1557 ret = fd_open(bs);
1558 if (ret < 0) {
1559 return ret;
1562 start = sector_num * BDRV_SECTOR_SIZE;
1564 ret = try_fiemap(bs, start, &data, &hole, nb_sectors, pnum);
1565 if (ret < 0) {
1566 ret = try_seek_hole(bs, start, &data, &hole, pnum);
1567 if (ret < 0) {
1568 /* Assume everything is allocated. */
1569 data = 0;
1570 hole = start + nb_sectors * BDRV_SECTOR_SIZE;
1571 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1575 if (data <= start) {
1576 /* On a data extent, compute sectors to the end of the extent. */
1577 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1578 } else {
1579 /* On a hole, compute sectors to the beginning of the next extent. */
1580 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1581 ret &= ~BDRV_BLOCK_DATA;
1582 ret |= BDRV_BLOCK_ZERO;
1585 return ret;
1588 static coroutine_fn BlockDriverAIOCB *raw_aio_discard(BlockDriverState *bs,
1589 int64_t sector_num, int nb_sectors,
1590 BlockDriverCompletionFunc *cb, void *opaque)
1592 BDRVRawState *s = bs->opaque;
1594 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1595 cb, opaque, QEMU_AIO_DISCARD);
1598 static int coroutine_fn raw_co_write_zeroes(
1599 BlockDriverState *bs, int64_t sector_num,
1600 int nb_sectors, BdrvRequestFlags flags)
1602 BDRVRawState *s = bs->opaque;
1604 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1605 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1606 QEMU_AIO_WRITE_ZEROES);
1607 } else if (s->discard_zeroes) {
1608 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1609 QEMU_AIO_DISCARD);
1611 return -ENOTSUP;
1614 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1616 BDRVRawState *s = bs->opaque;
1618 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1619 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1620 return 0;
1623 static QemuOptsList raw_create_opts = {
1624 .name = "raw-create-opts",
1625 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1626 .desc = {
1628 .name = BLOCK_OPT_SIZE,
1629 .type = QEMU_OPT_SIZE,
1630 .help = "Virtual disk size"
1633 .name = BLOCK_OPT_NOCOW,
1634 .type = QEMU_OPT_BOOL,
1635 .help = "Turn off copy-on-write (valid only on btrfs)"
1638 .name = BLOCK_OPT_PREALLOC,
1639 .type = QEMU_OPT_STRING,
1640 .help = "Preallocation mode (allowed values: off, falloc, full)"
1642 { /* end of list */ }
1646 static BlockDriver bdrv_file = {
1647 .format_name = "file",
1648 .protocol_name = "file",
1649 .instance_size = sizeof(BDRVRawState),
1650 .bdrv_needs_filename = true,
1651 .bdrv_probe = NULL, /* no probe for protocols */
1652 .bdrv_parse_filename = raw_parse_filename,
1653 .bdrv_file_open = raw_open,
1654 .bdrv_reopen_prepare = raw_reopen_prepare,
1655 .bdrv_reopen_commit = raw_reopen_commit,
1656 .bdrv_reopen_abort = raw_reopen_abort,
1657 .bdrv_close = raw_close,
1658 .bdrv_create = raw_create,
1659 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1660 .bdrv_co_get_block_status = raw_co_get_block_status,
1661 .bdrv_co_write_zeroes = raw_co_write_zeroes,
1663 .bdrv_aio_readv = raw_aio_readv,
1664 .bdrv_aio_writev = raw_aio_writev,
1665 .bdrv_aio_flush = raw_aio_flush,
1666 .bdrv_aio_discard = raw_aio_discard,
1667 .bdrv_refresh_limits = raw_refresh_limits,
1668 .bdrv_io_plug = raw_aio_plug,
1669 .bdrv_io_unplug = raw_aio_unplug,
1670 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1672 .bdrv_truncate = raw_truncate,
1673 .bdrv_getlength = raw_getlength,
1674 .bdrv_get_info = raw_get_info,
1675 .bdrv_get_allocated_file_size
1676 = raw_get_allocated_file_size,
1678 .bdrv_detach_aio_context = raw_detach_aio_context,
1679 .bdrv_attach_aio_context = raw_attach_aio_context,
1681 .create_opts = &raw_create_opts,
1684 /***********************************************/
1685 /* host device */
1687 #if defined(__APPLE__) && defined(__MACH__)
1688 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1689 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1691 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1693 kern_return_t kernResult;
1694 mach_port_t masterPort;
1695 CFMutableDictionaryRef classesToMatch;
1697 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1698 if ( KERN_SUCCESS != kernResult ) {
1699 printf( "IOMasterPort returned %d\n", kernResult );
1702 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1703 if ( classesToMatch == NULL ) {
1704 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1705 } else {
1706 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1708 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1709 if ( KERN_SUCCESS != kernResult )
1711 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1714 return kernResult;
1717 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1719 io_object_t nextMedia;
1720 kern_return_t kernResult = KERN_FAILURE;
1721 *bsdPath = '\0';
1722 nextMedia = IOIteratorNext( mediaIterator );
1723 if ( nextMedia )
1725 CFTypeRef bsdPathAsCFString;
1726 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1727 if ( bsdPathAsCFString ) {
1728 size_t devPathLength;
1729 strcpy( bsdPath, _PATH_DEV );
1730 strcat( bsdPath, "r" );
1731 devPathLength = strlen( bsdPath );
1732 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1733 kernResult = KERN_SUCCESS;
1735 CFRelease( bsdPathAsCFString );
1737 IOObjectRelease( nextMedia );
1740 return kernResult;
1743 #endif
1745 static int hdev_probe_device(const char *filename)
1747 struct stat st;
1749 /* allow a dedicated CD-ROM driver to match with a higher priority */
1750 if (strstart(filename, "/dev/cdrom", NULL))
1751 return 50;
1753 if (stat(filename, &st) >= 0 &&
1754 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1755 return 100;
1758 return 0;
1761 static int check_hdev_writable(BDRVRawState *s)
1763 #if defined(BLKROGET)
1764 /* Linux block devices can be configured "read-only" using blockdev(8).
1765 * This is independent of device node permissions and therefore open(2)
1766 * with O_RDWR succeeds. Actual writes fail with EPERM.
1768 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1769 * check for read-only block devices so that Linux block devices behave
1770 * properly.
1772 struct stat st;
1773 int readonly = 0;
1775 if (fstat(s->fd, &st)) {
1776 return -errno;
1779 if (!S_ISBLK(st.st_mode)) {
1780 return 0;
1783 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1784 return -errno;
1787 if (readonly) {
1788 return -EACCES;
1790 #endif /* defined(BLKROGET) */
1791 return 0;
1794 static void hdev_parse_filename(const char *filename, QDict *options,
1795 Error **errp)
1797 /* The prefix is optional, just as for "file". */
1798 strstart(filename, "host_device:", &filename);
1800 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1803 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1804 Error **errp)
1806 BDRVRawState *s = bs->opaque;
1807 Error *local_err = NULL;
1808 int ret;
1809 const char *filename = qdict_get_str(options, "filename");
1811 #if defined(__APPLE__) && defined(__MACH__)
1812 if (strstart(filename, "/dev/cdrom", NULL)) {
1813 kern_return_t kernResult;
1814 io_iterator_t mediaIterator;
1815 char bsdPath[ MAXPATHLEN ];
1816 int fd;
1818 kernResult = FindEjectableCDMedia( &mediaIterator );
1819 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1821 if ( bsdPath[ 0 ] != '\0' ) {
1822 strcat(bsdPath,"s0");
1823 /* some CDs don't have a partition 0 */
1824 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1825 if (fd < 0) {
1826 bsdPath[strlen(bsdPath)-1] = '1';
1827 } else {
1828 qemu_close(fd);
1830 filename = bsdPath;
1831 qdict_put(options, "filename", qstring_from_str(filename));
1834 if ( mediaIterator )
1835 IOObjectRelease( mediaIterator );
1837 #endif
1839 s->type = FTYPE_FILE;
1840 #if defined(__linux__)
1842 char resolved_path[ MAXPATHLEN ], *temp;
1844 temp = realpath(filename, resolved_path);
1845 if (temp && strstart(temp, "/dev/sg", NULL)) {
1846 bs->sg = 1;
1849 #endif
1851 ret = raw_open_common(bs, options, flags, 0, &local_err);
1852 if (ret < 0) {
1853 if (local_err) {
1854 error_propagate(errp, local_err);
1856 return ret;
1859 if (flags & BDRV_O_RDWR) {
1860 ret = check_hdev_writable(s);
1861 if (ret < 0) {
1862 raw_close(bs);
1863 error_setg_errno(errp, -ret, "The device is not writable");
1864 return ret;
1868 return ret;
1871 #if defined(__linux__)
1872 /* Note: we do not have a reliable method to detect if the floppy is
1873 present. The current method is to try to open the floppy at every
1874 I/O and to keep it opened during a few hundreds of ms. */
1875 static int fd_open(BlockDriverState *bs)
1877 BDRVRawState *s = bs->opaque;
1878 int last_media_present;
1880 if (s->type != FTYPE_FD)
1881 return 0;
1882 last_media_present = (s->fd >= 0);
1883 if (s->fd >= 0 &&
1884 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1885 qemu_close(s->fd);
1886 s->fd = -1;
1887 #ifdef DEBUG_FLOPPY
1888 printf("Floppy closed\n");
1889 #endif
1891 if (s->fd < 0) {
1892 if (s->fd_got_error &&
1893 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1894 #ifdef DEBUG_FLOPPY
1895 printf("No floppy (open delayed)\n");
1896 #endif
1897 return -EIO;
1899 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1900 if (s->fd < 0) {
1901 s->fd_error_time = get_clock();
1902 s->fd_got_error = 1;
1903 if (last_media_present)
1904 s->fd_media_changed = 1;
1905 #ifdef DEBUG_FLOPPY
1906 printf("No floppy\n");
1907 #endif
1908 return -EIO;
1910 #ifdef DEBUG_FLOPPY
1911 printf("Floppy opened\n");
1912 #endif
1914 if (!last_media_present)
1915 s->fd_media_changed = 1;
1916 s->fd_open_time = get_clock();
1917 s->fd_got_error = 0;
1918 return 0;
1921 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1923 BDRVRawState *s = bs->opaque;
1925 return ioctl(s->fd, req, buf);
1928 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1929 unsigned long int req, void *buf,
1930 BlockDriverCompletionFunc *cb, void *opaque)
1932 BDRVRawState *s = bs->opaque;
1933 RawPosixAIOData *acb;
1934 ThreadPool *pool;
1936 if (fd_open(bs) < 0)
1937 return NULL;
1939 acb = g_slice_new(RawPosixAIOData);
1940 acb->bs = bs;
1941 acb->aio_type = QEMU_AIO_IOCTL;
1942 acb->aio_fildes = s->fd;
1943 acb->aio_offset = 0;
1944 acb->aio_ioctl_buf = buf;
1945 acb->aio_ioctl_cmd = req;
1946 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1947 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1950 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1951 static int fd_open(BlockDriverState *bs)
1953 BDRVRawState *s = bs->opaque;
1955 /* this is just to ensure s->fd is sane (its called by io ops) */
1956 if (s->fd >= 0)
1957 return 0;
1958 return -EIO;
1960 #else /* !linux && !FreeBSD */
1962 static int fd_open(BlockDriverState *bs)
1964 return 0;
1967 #endif /* !linux && !FreeBSD */
1969 static coroutine_fn BlockDriverAIOCB *hdev_aio_discard(BlockDriverState *bs,
1970 int64_t sector_num, int nb_sectors,
1971 BlockDriverCompletionFunc *cb, void *opaque)
1973 BDRVRawState *s = bs->opaque;
1975 if (fd_open(bs) < 0) {
1976 return NULL;
1978 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1979 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1982 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
1983 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1985 BDRVRawState *s = bs->opaque;
1986 int rc;
1988 rc = fd_open(bs);
1989 if (rc < 0) {
1990 return rc;
1992 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1993 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1994 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
1995 } else if (s->discard_zeroes) {
1996 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1997 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1999 return -ENOTSUP;
2002 static int hdev_create(const char *filename, QemuOpts *opts,
2003 Error **errp)
2005 int fd;
2006 int ret = 0;
2007 struct stat stat_buf;
2008 int64_t total_size = 0;
2009 bool has_prefix;
2011 /* This function is used by all three protocol block drivers and therefore
2012 * any of these three prefixes may be given.
2013 * The return value has to be stored somewhere, otherwise this is an error
2014 * due to -Werror=unused-value. */
2015 has_prefix =
2016 strstart(filename, "host_device:", &filename) ||
2017 strstart(filename, "host_cdrom:" , &filename) ||
2018 strstart(filename, "host_floppy:", &filename);
2020 (void)has_prefix;
2022 /* Read out options */
2023 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2024 BDRV_SECTOR_SIZE);
2026 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2027 if (fd < 0) {
2028 ret = -errno;
2029 error_setg_errno(errp, -ret, "Could not open device");
2030 return ret;
2033 if (fstat(fd, &stat_buf) < 0) {
2034 ret = -errno;
2035 error_setg_errno(errp, -ret, "Could not stat device");
2036 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2037 error_setg(errp,
2038 "The given file is neither a block nor a character device");
2039 ret = -ENODEV;
2040 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2041 error_setg(errp, "Device is too small");
2042 ret = -ENOSPC;
2045 qemu_close(fd);
2046 return ret;
2049 static BlockDriver bdrv_host_device = {
2050 .format_name = "host_device",
2051 .protocol_name = "host_device",
2052 .instance_size = sizeof(BDRVRawState),
2053 .bdrv_needs_filename = true,
2054 .bdrv_probe_device = hdev_probe_device,
2055 .bdrv_parse_filename = hdev_parse_filename,
2056 .bdrv_file_open = hdev_open,
2057 .bdrv_close = raw_close,
2058 .bdrv_reopen_prepare = raw_reopen_prepare,
2059 .bdrv_reopen_commit = raw_reopen_commit,
2060 .bdrv_reopen_abort = raw_reopen_abort,
2061 .bdrv_create = hdev_create,
2062 .create_opts = &raw_create_opts,
2063 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2065 .bdrv_aio_readv = raw_aio_readv,
2066 .bdrv_aio_writev = raw_aio_writev,
2067 .bdrv_aio_flush = raw_aio_flush,
2068 .bdrv_aio_discard = hdev_aio_discard,
2069 .bdrv_refresh_limits = raw_refresh_limits,
2070 .bdrv_io_plug = raw_aio_plug,
2071 .bdrv_io_unplug = raw_aio_unplug,
2072 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2074 .bdrv_truncate = raw_truncate,
2075 .bdrv_getlength = raw_getlength,
2076 .bdrv_get_info = raw_get_info,
2077 .bdrv_get_allocated_file_size
2078 = raw_get_allocated_file_size,
2080 .bdrv_detach_aio_context = raw_detach_aio_context,
2081 .bdrv_attach_aio_context = raw_attach_aio_context,
2083 /* generic scsi device */
2084 #ifdef __linux__
2085 .bdrv_ioctl = hdev_ioctl,
2086 .bdrv_aio_ioctl = hdev_aio_ioctl,
2087 #endif
2090 #ifdef __linux__
2091 static void floppy_parse_filename(const char *filename, QDict *options,
2092 Error **errp)
2094 /* The prefix is optional, just as for "file". */
2095 strstart(filename, "host_floppy:", &filename);
2097 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2100 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2101 Error **errp)
2103 BDRVRawState *s = bs->opaque;
2104 Error *local_err = NULL;
2105 int ret;
2107 s->type = FTYPE_FD;
2109 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2110 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2111 if (ret) {
2112 if (local_err) {
2113 error_propagate(errp, local_err);
2115 return ret;
2118 /* close fd so that we can reopen it as needed */
2119 qemu_close(s->fd);
2120 s->fd = -1;
2121 s->fd_media_changed = 1;
2123 return 0;
2126 static int floppy_probe_device(const char *filename)
2128 int fd, ret;
2129 int prio = 0;
2130 struct floppy_struct fdparam;
2131 struct stat st;
2133 if (strstart(filename, "/dev/fd", NULL) &&
2134 !strstart(filename, "/dev/fdset/", NULL)) {
2135 prio = 50;
2138 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2139 if (fd < 0) {
2140 goto out;
2142 ret = fstat(fd, &st);
2143 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2144 goto outc;
2147 /* Attempt to detect via a floppy specific ioctl */
2148 ret = ioctl(fd, FDGETPRM, &fdparam);
2149 if (ret >= 0)
2150 prio = 100;
2152 outc:
2153 qemu_close(fd);
2154 out:
2155 return prio;
2159 static int floppy_is_inserted(BlockDriverState *bs)
2161 return fd_open(bs) >= 0;
2164 static int floppy_media_changed(BlockDriverState *bs)
2166 BDRVRawState *s = bs->opaque;
2167 int ret;
2170 * XXX: we do not have a true media changed indication.
2171 * It does not work if the floppy is changed without trying to read it.
2173 fd_open(bs);
2174 ret = s->fd_media_changed;
2175 s->fd_media_changed = 0;
2176 #ifdef DEBUG_FLOPPY
2177 printf("Floppy changed=%d\n", ret);
2178 #endif
2179 return ret;
2182 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2184 BDRVRawState *s = bs->opaque;
2185 int fd;
2187 if (s->fd >= 0) {
2188 qemu_close(s->fd);
2189 s->fd = -1;
2191 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2192 if (fd >= 0) {
2193 if (ioctl(fd, FDEJECT, 0) < 0)
2194 perror("FDEJECT");
2195 qemu_close(fd);
2199 static BlockDriver bdrv_host_floppy = {
2200 .format_name = "host_floppy",
2201 .protocol_name = "host_floppy",
2202 .instance_size = sizeof(BDRVRawState),
2203 .bdrv_needs_filename = true,
2204 .bdrv_probe_device = floppy_probe_device,
2205 .bdrv_parse_filename = floppy_parse_filename,
2206 .bdrv_file_open = floppy_open,
2207 .bdrv_close = raw_close,
2208 .bdrv_reopen_prepare = raw_reopen_prepare,
2209 .bdrv_reopen_commit = raw_reopen_commit,
2210 .bdrv_reopen_abort = raw_reopen_abort,
2211 .bdrv_create = hdev_create,
2212 .create_opts = &raw_create_opts,
2214 .bdrv_aio_readv = raw_aio_readv,
2215 .bdrv_aio_writev = raw_aio_writev,
2216 .bdrv_aio_flush = raw_aio_flush,
2217 .bdrv_refresh_limits = raw_refresh_limits,
2218 .bdrv_io_plug = raw_aio_plug,
2219 .bdrv_io_unplug = raw_aio_unplug,
2220 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2222 .bdrv_truncate = raw_truncate,
2223 .bdrv_getlength = raw_getlength,
2224 .has_variable_length = true,
2225 .bdrv_get_allocated_file_size
2226 = raw_get_allocated_file_size,
2228 .bdrv_detach_aio_context = raw_detach_aio_context,
2229 .bdrv_attach_aio_context = raw_attach_aio_context,
2231 /* removable device support */
2232 .bdrv_is_inserted = floppy_is_inserted,
2233 .bdrv_media_changed = floppy_media_changed,
2234 .bdrv_eject = floppy_eject,
2236 #endif
2238 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2239 static void cdrom_parse_filename(const char *filename, QDict *options,
2240 Error **errp)
2242 /* The prefix is optional, just as for "file". */
2243 strstart(filename, "host_cdrom:", &filename);
2245 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2247 #endif
2249 #ifdef __linux__
2250 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2251 Error **errp)
2253 BDRVRawState *s = bs->opaque;
2254 Error *local_err = NULL;
2255 int ret;
2257 s->type = FTYPE_CD;
2259 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2260 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2261 if (local_err) {
2262 error_propagate(errp, local_err);
2264 return ret;
2267 static int cdrom_probe_device(const char *filename)
2269 int fd, ret;
2270 int prio = 0;
2271 struct stat st;
2273 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2274 if (fd < 0) {
2275 goto out;
2277 ret = fstat(fd, &st);
2278 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2279 goto outc;
2282 /* Attempt to detect via a CDROM specific ioctl */
2283 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2284 if (ret >= 0)
2285 prio = 100;
2287 outc:
2288 qemu_close(fd);
2289 out:
2290 return prio;
2293 static int cdrom_is_inserted(BlockDriverState *bs)
2295 BDRVRawState *s = bs->opaque;
2296 int ret;
2298 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2299 if (ret == CDS_DISC_OK)
2300 return 1;
2301 return 0;
2304 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2306 BDRVRawState *s = bs->opaque;
2308 if (eject_flag) {
2309 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2310 perror("CDROMEJECT");
2311 } else {
2312 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2313 perror("CDROMEJECT");
2317 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2319 BDRVRawState *s = bs->opaque;
2321 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2323 * Note: an error can happen if the distribution automatically
2324 * mounts the CD-ROM
2326 /* perror("CDROM_LOCKDOOR"); */
2330 static BlockDriver bdrv_host_cdrom = {
2331 .format_name = "host_cdrom",
2332 .protocol_name = "host_cdrom",
2333 .instance_size = sizeof(BDRVRawState),
2334 .bdrv_needs_filename = true,
2335 .bdrv_probe_device = cdrom_probe_device,
2336 .bdrv_parse_filename = cdrom_parse_filename,
2337 .bdrv_file_open = cdrom_open,
2338 .bdrv_close = raw_close,
2339 .bdrv_reopen_prepare = raw_reopen_prepare,
2340 .bdrv_reopen_commit = raw_reopen_commit,
2341 .bdrv_reopen_abort = raw_reopen_abort,
2342 .bdrv_create = hdev_create,
2343 .create_opts = &raw_create_opts,
2345 .bdrv_aio_readv = raw_aio_readv,
2346 .bdrv_aio_writev = raw_aio_writev,
2347 .bdrv_aio_flush = raw_aio_flush,
2348 .bdrv_refresh_limits = raw_refresh_limits,
2349 .bdrv_io_plug = raw_aio_plug,
2350 .bdrv_io_unplug = raw_aio_unplug,
2351 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2353 .bdrv_truncate = raw_truncate,
2354 .bdrv_getlength = raw_getlength,
2355 .has_variable_length = true,
2356 .bdrv_get_allocated_file_size
2357 = raw_get_allocated_file_size,
2359 .bdrv_detach_aio_context = raw_detach_aio_context,
2360 .bdrv_attach_aio_context = raw_attach_aio_context,
2362 /* removable device support */
2363 .bdrv_is_inserted = cdrom_is_inserted,
2364 .bdrv_eject = cdrom_eject,
2365 .bdrv_lock_medium = cdrom_lock_medium,
2367 /* generic scsi device */
2368 .bdrv_ioctl = hdev_ioctl,
2369 .bdrv_aio_ioctl = hdev_aio_ioctl,
2371 #endif /* __linux__ */
2373 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2374 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2375 Error **errp)
2377 BDRVRawState *s = bs->opaque;
2378 Error *local_err = NULL;
2379 int ret;
2381 s->type = FTYPE_CD;
2383 ret = raw_open_common(bs, options, flags, 0, &local_err);
2384 if (ret) {
2385 if (local_err) {
2386 error_propagate(errp, local_err);
2388 return ret;
2391 /* make sure the door isn't locked at this time */
2392 ioctl(s->fd, CDIOCALLOW);
2393 return 0;
2396 static int cdrom_probe_device(const char *filename)
2398 if (strstart(filename, "/dev/cd", NULL) ||
2399 strstart(filename, "/dev/acd", NULL))
2400 return 100;
2401 return 0;
2404 static int cdrom_reopen(BlockDriverState *bs)
2406 BDRVRawState *s = bs->opaque;
2407 int fd;
2410 * Force reread of possibly changed/newly loaded disc,
2411 * FreeBSD seems to not notice sometimes...
2413 if (s->fd >= 0)
2414 qemu_close(s->fd);
2415 fd = qemu_open(bs->filename, s->open_flags, 0644);
2416 if (fd < 0) {
2417 s->fd = -1;
2418 return -EIO;
2420 s->fd = fd;
2422 /* make sure the door isn't locked at this time */
2423 ioctl(s->fd, CDIOCALLOW);
2424 return 0;
2427 static int cdrom_is_inserted(BlockDriverState *bs)
2429 return raw_getlength(bs) > 0;
2432 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2434 BDRVRawState *s = bs->opaque;
2436 if (s->fd < 0)
2437 return;
2439 (void) ioctl(s->fd, CDIOCALLOW);
2441 if (eject_flag) {
2442 if (ioctl(s->fd, CDIOCEJECT) < 0)
2443 perror("CDIOCEJECT");
2444 } else {
2445 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2446 perror("CDIOCCLOSE");
2449 cdrom_reopen(bs);
2452 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2454 BDRVRawState *s = bs->opaque;
2456 if (s->fd < 0)
2457 return;
2458 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2460 * Note: an error can happen if the distribution automatically
2461 * mounts the CD-ROM
2463 /* perror("CDROM_LOCKDOOR"); */
2467 static BlockDriver bdrv_host_cdrom = {
2468 .format_name = "host_cdrom",
2469 .protocol_name = "host_cdrom",
2470 .instance_size = sizeof(BDRVRawState),
2471 .bdrv_needs_filename = true,
2472 .bdrv_probe_device = cdrom_probe_device,
2473 .bdrv_parse_filename = cdrom_parse_filename,
2474 .bdrv_file_open = cdrom_open,
2475 .bdrv_close = raw_close,
2476 .bdrv_reopen_prepare = raw_reopen_prepare,
2477 .bdrv_reopen_commit = raw_reopen_commit,
2478 .bdrv_reopen_abort = raw_reopen_abort,
2479 .bdrv_create = hdev_create,
2480 .create_opts = &raw_create_opts,
2482 .bdrv_aio_readv = raw_aio_readv,
2483 .bdrv_aio_writev = raw_aio_writev,
2484 .bdrv_aio_flush = raw_aio_flush,
2485 .bdrv_refresh_limits = raw_refresh_limits,
2486 .bdrv_io_plug = raw_aio_plug,
2487 .bdrv_io_unplug = raw_aio_unplug,
2488 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2490 .bdrv_truncate = raw_truncate,
2491 .bdrv_getlength = raw_getlength,
2492 .has_variable_length = true,
2493 .bdrv_get_allocated_file_size
2494 = raw_get_allocated_file_size,
2496 .bdrv_detach_aio_context = raw_detach_aio_context,
2497 .bdrv_attach_aio_context = raw_attach_aio_context,
2499 /* removable device support */
2500 .bdrv_is_inserted = cdrom_is_inserted,
2501 .bdrv_eject = cdrom_eject,
2502 .bdrv_lock_medium = cdrom_lock_medium,
2504 #endif /* __FreeBSD__ */
2506 static void bdrv_file_init(void)
2509 * Register all the drivers. Note that order is important, the driver
2510 * registered last will get probed first.
2512 bdrv_register(&bdrv_file);
2513 bdrv_register(&bdrv_host_device);
2514 #ifdef __linux__
2515 bdrv_register(&bdrv_host_floppy);
2516 bdrv_register(&bdrv_host_cdrom);
2517 #endif
2518 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2519 bdrv_register(&bdrv_host_cdrom);
2520 #endif
2523 block_init(bdrv_file_init);