Merge remote-tracking branch 'amit/for-anthony' into staging
[qemu.git] / block / raw-posix.c
blob4cd7d7afbb2cbfef03eb5cb57335e2a109d749ab
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-char.h"
27 #include "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "block/raw-posix-aio.h"
32 #ifdef CONFIG_COCOA
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <sys/dkio.h>
47 #endif
48 #ifdef __linux__
49 #include <sys/ioctl.h>
50 #include <sys/param.h>
51 #include <linux/cdrom.h>
52 #include <linux/fd.h>
53 #endif
54 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
55 #include <sys/disk.h>
56 #include <sys/cdio.h>
57 #endif
59 #ifdef __OpenBSD__
60 #include <sys/ioctl.h>
61 #include <sys/disklabel.h>
62 #include <sys/dkio.h>
63 #endif
65 #ifdef __NetBSD__
66 #include <sys/ioctl.h>
67 #include <sys/disklabel.h>
68 #include <sys/dkio.h>
69 #include <sys/disk.h>
70 #endif
72 #ifdef __DragonFly__
73 #include <sys/ioctl.h>
74 #include <sys/diskslice.h>
75 #endif
77 #ifdef CONFIG_XFS
78 #include <xfs/xfs.h>
79 #endif
81 //#define DEBUG_FLOPPY
83 //#define DEBUG_BLOCK
84 #if defined(DEBUG_BLOCK)
85 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
86 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
87 #else
88 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
89 #endif
91 /* OS X does not have O_DSYNC */
92 #ifndef O_DSYNC
93 #ifdef O_SYNC
94 #define O_DSYNC O_SYNC
95 #elif defined(O_FSYNC)
96 #define O_DSYNC O_FSYNC
97 #endif
98 #endif
100 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
101 #ifndef O_DIRECT
102 #define O_DIRECT O_DSYNC
103 #endif
105 #define FTYPE_FILE 0
106 #define FTYPE_CD 1
107 #define FTYPE_FD 2
109 /* if the FD is not accessed during that time (in ns), we try to
110 reopen it to see if the disk has been changed */
111 #define FD_OPEN_TIMEOUT (1000000000)
113 #define MAX_BLOCKSIZE 4096
115 typedef struct BDRVRawState {
116 int fd;
117 int type;
118 int open_flags;
119 #if defined(__linux__)
120 /* linux floppy specific */
121 int64_t fd_open_time;
122 int64_t fd_error_time;
123 int fd_got_error;
124 int fd_media_changed;
125 #endif
126 #ifdef CONFIG_LINUX_AIO
127 int use_aio;
128 void *aio_ctx;
129 #endif
130 uint8_t *aligned_buf;
131 unsigned aligned_buf_size;
132 #ifdef CONFIG_XFS
133 bool is_xfs : 1;
134 #endif
135 } BDRVRawState;
137 static int fd_open(BlockDriverState *bs);
138 static int64_t raw_getlength(BlockDriverState *bs);
140 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
141 static int cdrom_reopen(BlockDriverState *bs);
142 #endif
144 #if defined(__NetBSD__)
145 static int raw_normalize_devicepath(const char **filename)
147 static char namebuf[PATH_MAX];
148 const char *dp, *fname;
149 struct stat sb;
151 fname = *filename;
152 dp = strrchr(fname, '/');
153 if (lstat(fname, &sb) < 0) {
154 fprintf(stderr, "%s: stat failed: %s\n",
155 fname, strerror(errno));
156 return -errno;
159 if (!S_ISBLK(sb.st_mode)) {
160 return 0;
163 if (dp == NULL) {
164 snprintf(namebuf, PATH_MAX, "r%s", fname);
165 } else {
166 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
167 (int)(dp - fname), fname, dp + 1);
169 fprintf(stderr, "%s is a block device", fname);
170 *filename = namebuf;
171 fprintf(stderr, ", using %s\n", *filename);
173 return 0;
175 #else
176 static int raw_normalize_devicepath(const char **filename)
178 return 0;
180 #endif
182 static int raw_open_common(BlockDriverState *bs, const char *filename,
183 int bdrv_flags, int open_flags)
185 BDRVRawState *s = bs->opaque;
186 int fd, ret;
188 ret = raw_normalize_devicepath(&filename);
189 if (ret != 0) {
190 return ret;
193 s->open_flags = open_flags | O_BINARY;
194 s->open_flags &= ~O_ACCMODE;
195 if (bdrv_flags & BDRV_O_RDWR) {
196 s->open_flags |= O_RDWR;
197 } else {
198 s->open_flags |= O_RDONLY;
201 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
202 * and O_DIRECT for no caching. */
203 if ((bdrv_flags & BDRV_O_NOCACHE))
204 s->open_flags |= O_DIRECT;
205 if (!(bdrv_flags & BDRV_O_CACHE_WB))
206 s->open_flags |= O_DSYNC;
208 s->fd = -1;
209 fd = qemu_open(filename, s->open_flags, 0644);
210 if (fd < 0) {
211 ret = -errno;
212 if (ret == -EROFS)
213 ret = -EACCES;
214 return ret;
216 s->fd = fd;
217 s->aligned_buf = NULL;
219 if ((bdrv_flags & BDRV_O_NOCACHE)) {
221 * Allocate a buffer for read/modify/write cycles. Chose the size
222 * pessimistically as we don't know the block size yet.
224 s->aligned_buf_size = 32 * MAX_BLOCKSIZE;
225 s->aligned_buf = qemu_memalign(MAX_BLOCKSIZE, s->aligned_buf_size);
226 if (s->aligned_buf == NULL) {
227 goto out_close;
231 #ifdef CONFIG_LINUX_AIO
232 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
233 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
235 /* We're falling back to POSIX AIO in some cases */
236 paio_init();
238 s->aio_ctx = laio_init();
239 if (!s->aio_ctx) {
240 goto out_free_buf;
242 s->use_aio = 1;
243 } else
244 #endif
246 if (paio_init() < 0) {
247 goto out_free_buf;
249 #ifdef CONFIG_LINUX_AIO
250 s->use_aio = 0;
251 #endif
254 #ifdef CONFIG_XFS
255 if (platform_test_xfs_fd(s->fd)) {
256 s->is_xfs = 1;
258 #endif
260 return 0;
262 out_free_buf:
263 qemu_vfree(s->aligned_buf);
264 out_close:
265 close(fd);
266 return -errno;
269 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
271 BDRVRawState *s = bs->opaque;
273 s->type = FTYPE_FILE;
274 return raw_open_common(bs, filename, flags, 0);
277 /* XXX: use host sector size if necessary with:
278 #ifdef DIOCGSECTORSIZE
280 unsigned int sectorsize = 512;
281 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
282 sectorsize > bufsize)
283 bufsize = sectorsize;
285 #endif
286 #ifdef CONFIG_COCOA
287 uint32_t blockSize = 512;
288 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
289 bufsize = blockSize;
291 #endif
295 * offset and count are in bytes, but must be multiples of 512 for files
296 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
298 * This function may be called without alignment if the caller ensures
299 * that O_DIRECT is not in effect.
301 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
302 uint8_t *buf, int count)
304 BDRVRawState *s = bs->opaque;
305 int ret;
307 ret = fd_open(bs);
308 if (ret < 0)
309 return ret;
311 ret = pread(s->fd, buf, count, offset);
312 if (ret == count)
313 return ret;
315 /* Allow reads beyond the end (needed for pwrite) */
316 if ((ret == 0) && bs->growable) {
317 int64_t size = raw_getlength(bs);
318 if (offset >= size) {
319 memset(buf, 0, count);
320 return count;
324 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
325 "] read failed %d : %d = %s\n",
326 s->fd, bs->filename, offset, buf, count,
327 bs->total_sectors, ret, errno, strerror(errno));
329 /* Try harder for CDrom. */
330 if (s->type != FTYPE_FILE) {
331 ret = pread(s->fd, buf, count, offset);
332 if (ret == count)
333 return ret;
334 ret = pread(s->fd, buf, count, offset);
335 if (ret == count)
336 return ret;
338 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
339 "] retry read failed %d : %d = %s\n",
340 s->fd, bs->filename, offset, buf, count,
341 bs->total_sectors, ret, errno, strerror(errno));
344 return (ret < 0) ? -errno : ret;
348 * offset and count are in bytes, but must be multiples of the sector size
349 * for files opened with O_DIRECT. buf must be aligned to sector size bytes
350 * then.
352 * This function may be called without alignment if the caller ensures
353 * that O_DIRECT is not in effect.
355 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
356 const uint8_t *buf, int count)
358 BDRVRawState *s = bs->opaque;
359 int ret;
361 ret = fd_open(bs);
362 if (ret < 0)
363 return -errno;
365 ret = pwrite(s->fd, buf, count, offset);
366 if (ret == count)
367 return ret;
369 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
370 "] write failed %d : %d = %s\n",
371 s->fd, bs->filename, offset, buf, count,
372 bs->total_sectors, ret, errno, strerror(errno));
374 return (ret < 0) ? -errno : ret;
379 * offset and count are in bytes and possibly not aligned. For files opened
380 * with O_DIRECT, necessary alignments are ensured before calling
381 * raw_pread_aligned to do the actual read.
383 static int raw_pread(BlockDriverState *bs, int64_t offset,
384 uint8_t *buf, int count)
386 BDRVRawState *s = bs->opaque;
387 unsigned sector_mask = bs->buffer_alignment - 1;
388 int size, ret, shift, sum;
390 sum = 0;
392 if (s->aligned_buf != NULL) {
394 if (offset & sector_mask) {
395 /* align offset on a sector size bytes boundary */
397 shift = offset & sector_mask;
398 size = (shift + count + sector_mask) & ~sector_mask;
399 if (size > s->aligned_buf_size)
400 size = s->aligned_buf_size;
401 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
402 if (ret < 0)
403 return ret;
405 size = bs->buffer_alignment - shift;
406 if (size > count)
407 size = count;
408 memcpy(buf, s->aligned_buf + shift, size);
410 buf += size;
411 offset += size;
412 count -= size;
413 sum += size;
415 if (count == 0)
416 return sum;
418 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
420 /* read on aligned buffer */
422 while (count) {
424 size = (count + sector_mask) & ~sector_mask;
425 if (size > s->aligned_buf_size)
426 size = s->aligned_buf_size;
428 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
429 if (ret < 0) {
430 return ret;
431 } else if (ret == 0) {
432 fprintf(stderr, "raw_pread: read beyond end of file\n");
433 abort();
436 size = ret;
437 if (size > count)
438 size = count;
440 memcpy(buf, s->aligned_buf, size);
442 buf += size;
443 offset += size;
444 count -= size;
445 sum += size;
448 return sum;
452 return raw_pread_aligned(bs, offset, buf, count) + sum;
455 static int raw_read(BlockDriverState *bs, int64_t sector_num,
456 uint8_t *buf, int nb_sectors)
458 int ret;
460 ret = raw_pread(bs, sector_num * BDRV_SECTOR_SIZE, buf,
461 nb_sectors * BDRV_SECTOR_SIZE);
462 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
463 ret = 0;
464 return ret;
468 * offset and count are in bytes and possibly not aligned. For files opened
469 * with O_DIRECT, necessary alignments are ensured before calling
470 * raw_pwrite_aligned to do the actual write.
472 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
473 const uint8_t *buf, int count)
475 BDRVRawState *s = bs->opaque;
476 unsigned sector_mask = bs->buffer_alignment - 1;
477 int size, ret, shift, sum;
479 sum = 0;
481 if (s->aligned_buf != NULL) {
483 if (offset & sector_mask) {
484 /* align offset on a sector size bytes boundary */
485 shift = offset & sector_mask;
486 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf,
487 bs->buffer_alignment);
488 if (ret < 0)
489 return ret;
491 size = bs->buffer_alignment - shift;
492 if (size > count)
493 size = count;
494 memcpy(s->aligned_buf + shift, buf, size);
496 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf,
497 bs->buffer_alignment);
498 if (ret < 0)
499 return ret;
501 buf += size;
502 offset += size;
503 count -= size;
504 sum += size;
506 if (count == 0)
507 return sum;
509 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
511 while ((size = (count & ~sector_mask)) != 0) {
513 if (size > s->aligned_buf_size)
514 size = s->aligned_buf_size;
516 memcpy(s->aligned_buf, buf, size);
518 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
519 if (ret < 0)
520 return ret;
522 buf += ret;
523 offset += ret;
524 count -= ret;
525 sum += ret;
527 /* here, count < sector_size because (count & ~sector_mask) == 0 */
528 if (count) {
529 ret = raw_pread_aligned(bs, offset, s->aligned_buf,
530 bs->buffer_alignment);
531 if (ret < 0)
532 return ret;
533 memcpy(s->aligned_buf, buf, count);
535 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf,
536 bs->buffer_alignment);
537 if (ret < 0)
538 return ret;
539 if (count < ret)
540 ret = count;
542 sum += ret;
544 return sum;
547 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
550 static int raw_write(BlockDriverState *bs, int64_t sector_num,
551 const uint8_t *buf, int nb_sectors)
553 int ret;
554 ret = raw_pwrite(bs, sector_num * BDRV_SECTOR_SIZE, buf,
555 nb_sectors * BDRV_SECTOR_SIZE);
556 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
557 ret = 0;
558 return ret;
562 * Check if all memory in this vector is sector aligned.
564 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
566 int i;
568 for (i = 0; i < qiov->niov; i++) {
569 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
570 return 0;
574 return 1;
577 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
578 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
579 BlockDriverCompletionFunc *cb, void *opaque, int type)
581 BDRVRawState *s = bs->opaque;
583 if (fd_open(bs) < 0)
584 return NULL;
587 * If O_DIRECT is used the buffer needs to be aligned on a sector
588 * boundary. Check if this is the case or telll the low-level
589 * driver that it needs to copy the buffer.
591 if (s->aligned_buf) {
592 if (!qiov_is_aligned(bs, qiov)) {
593 type |= QEMU_AIO_MISALIGNED;
594 #ifdef CONFIG_LINUX_AIO
595 } else if (s->use_aio) {
596 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
597 nb_sectors, cb, opaque, type);
598 #endif
602 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
603 cb, opaque, type);
606 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
607 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
608 BlockDriverCompletionFunc *cb, void *opaque)
610 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
611 cb, opaque, QEMU_AIO_READ);
614 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
615 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
616 BlockDriverCompletionFunc *cb, void *opaque)
618 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
619 cb, opaque, QEMU_AIO_WRITE);
622 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
623 BlockDriverCompletionFunc *cb, void *opaque)
625 BDRVRawState *s = bs->opaque;
627 if (fd_open(bs) < 0)
628 return NULL;
630 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
633 static void raw_close(BlockDriverState *bs)
635 BDRVRawState *s = bs->opaque;
636 if (s->fd >= 0) {
637 close(s->fd);
638 s->fd = -1;
639 if (s->aligned_buf != NULL)
640 qemu_vfree(s->aligned_buf);
644 static int raw_truncate(BlockDriverState *bs, int64_t offset)
646 BDRVRawState *s = bs->opaque;
647 if (s->type != FTYPE_FILE)
648 return -ENOTSUP;
649 if (ftruncate(s->fd, offset) < 0)
650 return -errno;
651 return 0;
654 #ifdef __OpenBSD__
655 static int64_t raw_getlength(BlockDriverState *bs)
657 BDRVRawState *s = bs->opaque;
658 int fd = s->fd;
659 struct stat st;
661 if (fstat(fd, &st))
662 return -1;
663 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
664 struct disklabel dl;
666 if (ioctl(fd, DIOCGDINFO, &dl))
667 return -1;
668 return (uint64_t)dl.d_secsize *
669 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
670 } else
671 return st.st_size;
673 #elif defined(__NetBSD__)
674 static int64_t raw_getlength(BlockDriverState *bs)
676 BDRVRawState *s = bs->opaque;
677 int fd = s->fd;
678 struct stat st;
680 if (fstat(fd, &st))
681 return -1;
682 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
683 struct dkwedge_info dkw;
685 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
686 return dkw.dkw_size * 512;
687 } else {
688 struct disklabel dl;
690 if (ioctl(fd, DIOCGDINFO, &dl))
691 return -1;
692 return (uint64_t)dl.d_secsize *
693 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
695 } else
696 return st.st_size;
698 #elif defined(__sun__)
699 static int64_t raw_getlength(BlockDriverState *bs)
701 BDRVRawState *s = bs->opaque;
702 struct dk_minfo minfo;
703 int ret;
705 ret = fd_open(bs);
706 if (ret < 0) {
707 return ret;
711 * Use the DKIOCGMEDIAINFO ioctl to read the size.
713 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
714 if (ret != -1) {
715 return minfo.dki_lbsize * minfo.dki_capacity;
719 * There are reports that lseek on some devices fails, but
720 * irc discussion said that contingency on contingency was overkill.
722 return lseek(s->fd, 0, SEEK_END);
724 #elif defined(CONFIG_BSD)
725 static int64_t raw_getlength(BlockDriverState *bs)
727 BDRVRawState *s = bs->opaque;
728 int fd = s->fd;
729 int64_t size;
730 struct stat sb;
731 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
732 int reopened = 0;
733 #endif
734 int ret;
736 ret = fd_open(bs);
737 if (ret < 0)
738 return ret;
740 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
741 again:
742 #endif
743 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
744 #ifdef DIOCGMEDIASIZE
745 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
746 #elif defined(DIOCGPART)
748 struct partinfo pi;
749 if (ioctl(fd, DIOCGPART, &pi) == 0)
750 size = pi.media_size;
751 else
752 size = 0;
754 if (size == 0)
755 #endif
756 #ifdef CONFIG_COCOA
757 size = LONG_LONG_MAX;
758 #else
759 size = lseek(fd, 0LL, SEEK_END);
760 #endif
761 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
762 switch(s->type) {
763 case FTYPE_CD:
764 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
765 if (size == 2048LL * (unsigned)-1)
766 size = 0;
767 /* XXX no disc? maybe we need to reopen... */
768 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
769 reopened = 1;
770 goto again;
773 #endif
774 } else {
775 size = lseek(fd, 0, SEEK_END);
777 return size;
779 #else
780 static int64_t raw_getlength(BlockDriverState *bs)
782 BDRVRawState *s = bs->opaque;
783 int ret;
785 ret = fd_open(bs);
786 if (ret < 0) {
787 return ret;
790 return lseek(s->fd, 0, SEEK_END);
792 #endif
794 static int raw_create(const char *filename, QEMUOptionParameter *options)
796 int fd;
797 int result = 0;
798 int64_t total_size = 0;
800 /* Read out options */
801 while (options && options->name) {
802 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
803 total_size = options->value.n / BDRV_SECTOR_SIZE;
805 options++;
808 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
809 0644);
810 if (fd < 0) {
811 result = -errno;
812 } else {
813 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
814 result = -errno;
816 if (close(fd) != 0) {
817 result = -errno;
820 return result;
823 static int raw_flush(BlockDriverState *bs)
825 BDRVRawState *s = bs->opaque;
826 return qemu_fdatasync(s->fd);
829 #ifdef CONFIG_XFS
830 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
832 struct xfs_flock64 fl;
834 memset(&fl, 0, sizeof(fl));
835 fl.l_whence = SEEK_SET;
836 fl.l_start = sector_num << 9;
837 fl.l_len = (int64_t)nb_sectors << 9;
839 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
840 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
841 return -errno;
844 return 0;
846 #endif
848 static int raw_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
850 #ifdef CONFIG_XFS
851 BDRVRawState *s = bs->opaque;
853 if (s->is_xfs) {
854 return xfs_discard(s, sector_num, nb_sectors);
856 #endif
858 return 0;
861 static QEMUOptionParameter raw_create_options[] = {
863 .name = BLOCK_OPT_SIZE,
864 .type = OPT_SIZE,
865 .help = "Virtual disk size"
867 { NULL }
870 static BlockDriver bdrv_file = {
871 .format_name = "file",
872 .protocol_name = "file",
873 .instance_size = sizeof(BDRVRawState),
874 .bdrv_probe = NULL, /* no probe for protocols */
875 .bdrv_file_open = raw_open,
876 .bdrv_read = raw_read,
877 .bdrv_write = raw_write,
878 .bdrv_close = raw_close,
879 .bdrv_create = raw_create,
880 .bdrv_flush = raw_flush,
881 .bdrv_discard = raw_discard,
883 .bdrv_aio_readv = raw_aio_readv,
884 .bdrv_aio_writev = raw_aio_writev,
885 .bdrv_aio_flush = raw_aio_flush,
887 .bdrv_truncate = raw_truncate,
888 .bdrv_getlength = raw_getlength,
890 .create_options = raw_create_options,
893 /***********************************************/
894 /* host device */
896 #ifdef CONFIG_COCOA
897 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
898 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
900 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
902 kern_return_t kernResult;
903 mach_port_t masterPort;
904 CFMutableDictionaryRef classesToMatch;
906 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
907 if ( KERN_SUCCESS != kernResult ) {
908 printf( "IOMasterPort returned %d\n", kernResult );
911 classesToMatch = IOServiceMatching( kIOCDMediaClass );
912 if ( classesToMatch == NULL ) {
913 printf( "IOServiceMatching returned a NULL dictionary.\n" );
914 } else {
915 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
917 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
918 if ( KERN_SUCCESS != kernResult )
920 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
923 return kernResult;
926 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
928 io_object_t nextMedia;
929 kern_return_t kernResult = KERN_FAILURE;
930 *bsdPath = '\0';
931 nextMedia = IOIteratorNext( mediaIterator );
932 if ( nextMedia )
934 CFTypeRef bsdPathAsCFString;
935 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
936 if ( bsdPathAsCFString ) {
937 size_t devPathLength;
938 strcpy( bsdPath, _PATH_DEV );
939 strcat( bsdPath, "r" );
940 devPathLength = strlen( bsdPath );
941 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
942 kernResult = KERN_SUCCESS;
944 CFRelease( bsdPathAsCFString );
946 IOObjectRelease( nextMedia );
949 return kernResult;
952 #endif
954 static int hdev_probe_device(const char *filename)
956 struct stat st;
958 /* allow a dedicated CD-ROM driver to match with a higher priority */
959 if (strstart(filename, "/dev/cdrom", NULL))
960 return 50;
962 if (stat(filename, &st) >= 0 &&
963 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
964 return 100;
967 return 0;
970 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
972 BDRVRawState *s = bs->opaque;
974 #ifdef CONFIG_COCOA
975 if (strstart(filename, "/dev/cdrom", NULL)) {
976 kern_return_t kernResult;
977 io_iterator_t mediaIterator;
978 char bsdPath[ MAXPATHLEN ];
979 int fd;
981 kernResult = FindEjectableCDMedia( &mediaIterator );
982 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
984 if ( bsdPath[ 0 ] != '\0' ) {
985 strcat(bsdPath,"s0");
986 /* some CDs don't have a partition 0 */
987 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
988 if (fd < 0) {
989 bsdPath[strlen(bsdPath)-1] = '1';
990 } else {
991 close(fd);
993 filename = bsdPath;
996 if ( mediaIterator )
997 IOObjectRelease( mediaIterator );
999 #endif
1001 s->type = FTYPE_FILE;
1002 #if defined(__linux__)
1004 char resolved_path[ MAXPATHLEN ], *temp;
1006 temp = realpath(filename, resolved_path);
1007 if (temp && strstart(temp, "/dev/sg", NULL)) {
1008 bs->sg = 1;
1011 #endif
1013 return raw_open_common(bs, filename, flags, 0);
1016 #if defined(__linux__)
1017 /* Note: we do not have a reliable method to detect if the floppy is
1018 present. The current method is to try to open the floppy at every
1019 I/O and to keep it opened during a few hundreds of ms. */
1020 static int fd_open(BlockDriverState *bs)
1022 BDRVRawState *s = bs->opaque;
1023 int last_media_present;
1025 if (s->type != FTYPE_FD)
1026 return 0;
1027 last_media_present = (s->fd >= 0);
1028 if (s->fd >= 0 &&
1029 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1030 close(s->fd);
1031 s->fd = -1;
1032 #ifdef DEBUG_FLOPPY
1033 printf("Floppy closed\n");
1034 #endif
1036 if (s->fd < 0) {
1037 if (s->fd_got_error &&
1038 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1039 #ifdef DEBUG_FLOPPY
1040 printf("No floppy (open delayed)\n");
1041 #endif
1042 return -EIO;
1044 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1045 if (s->fd < 0) {
1046 s->fd_error_time = get_clock();
1047 s->fd_got_error = 1;
1048 if (last_media_present)
1049 s->fd_media_changed = 1;
1050 #ifdef DEBUG_FLOPPY
1051 printf("No floppy\n");
1052 #endif
1053 return -EIO;
1055 #ifdef DEBUG_FLOPPY
1056 printf("Floppy opened\n");
1057 #endif
1059 if (!last_media_present)
1060 s->fd_media_changed = 1;
1061 s->fd_open_time = get_clock();
1062 s->fd_got_error = 0;
1063 return 0;
1066 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1068 BDRVRawState *s = bs->opaque;
1070 return ioctl(s->fd, req, buf);
1073 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1074 unsigned long int req, void *buf,
1075 BlockDriverCompletionFunc *cb, void *opaque)
1077 BDRVRawState *s = bs->opaque;
1079 if (fd_open(bs) < 0)
1080 return NULL;
1081 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
1084 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1085 static int fd_open(BlockDriverState *bs)
1087 BDRVRawState *s = bs->opaque;
1089 /* this is just to ensure s->fd is sane (its called by io ops) */
1090 if (s->fd >= 0)
1091 return 0;
1092 return -EIO;
1094 #else /* !linux && !FreeBSD */
1096 static int fd_open(BlockDriverState *bs)
1098 return 0;
1101 #endif /* !linux && !FreeBSD */
1103 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1105 int fd;
1106 int ret = 0;
1107 struct stat stat_buf;
1108 int64_t total_size = 0;
1110 /* Read out options */
1111 while (options && options->name) {
1112 if (!strcmp(options->name, "size")) {
1113 total_size = options->value.n / BDRV_SECTOR_SIZE;
1115 options++;
1118 fd = open(filename, O_WRONLY | O_BINARY);
1119 if (fd < 0)
1120 return -errno;
1122 if (fstat(fd, &stat_buf) < 0)
1123 ret = -errno;
1124 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1125 ret = -ENODEV;
1126 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1127 ret = -ENOSPC;
1129 close(fd);
1130 return ret;
1133 static int hdev_has_zero_init(BlockDriverState *bs)
1135 return 0;
1138 static BlockDriver bdrv_host_device = {
1139 .format_name = "host_device",
1140 .protocol_name = "host_device",
1141 .instance_size = sizeof(BDRVRawState),
1142 .bdrv_probe_device = hdev_probe_device,
1143 .bdrv_file_open = hdev_open,
1144 .bdrv_close = raw_close,
1145 .bdrv_create = hdev_create,
1146 .create_options = raw_create_options,
1147 .bdrv_has_zero_init = hdev_has_zero_init,
1148 .bdrv_flush = raw_flush,
1150 .bdrv_aio_readv = raw_aio_readv,
1151 .bdrv_aio_writev = raw_aio_writev,
1152 .bdrv_aio_flush = raw_aio_flush,
1154 .bdrv_read = raw_read,
1155 .bdrv_write = raw_write,
1156 .bdrv_getlength = raw_getlength,
1158 /* generic scsi device */
1159 #ifdef __linux__
1160 .bdrv_ioctl = hdev_ioctl,
1161 .bdrv_aio_ioctl = hdev_aio_ioctl,
1162 #endif
1165 #ifdef __linux__
1166 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1168 BDRVRawState *s = bs->opaque;
1169 int ret;
1171 s->type = FTYPE_FD;
1173 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1174 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1175 if (ret)
1176 return ret;
1178 /* close fd so that we can reopen it as needed */
1179 close(s->fd);
1180 s->fd = -1;
1181 s->fd_media_changed = 1;
1183 return 0;
1186 static int floppy_probe_device(const char *filename)
1188 int fd, ret;
1189 int prio = 0;
1190 struct floppy_struct fdparam;
1192 if (strstart(filename, "/dev/fd", NULL))
1193 prio = 50;
1195 fd = open(filename, O_RDONLY | O_NONBLOCK);
1196 if (fd < 0) {
1197 goto out;
1200 /* Attempt to detect via a floppy specific ioctl */
1201 ret = ioctl(fd, FDGETPRM, &fdparam);
1202 if (ret >= 0)
1203 prio = 100;
1205 close(fd);
1206 out:
1207 return prio;
1211 static int floppy_is_inserted(BlockDriverState *bs)
1213 return fd_open(bs) >= 0;
1216 static int floppy_media_changed(BlockDriverState *bs)
1218 BDRVRawState *s = bs->opaque;
1219 int ret;
1222 * XXX: we do not have a true media changed indication.
1223 * It does not work if the floppy is changed without trying to read it.
1225 fd_open(bs);
1226 ret = s->fd_media_changed;
1227 s->fd_media_changed = 0;
1228 #ifdef DEBUG_FLOPPY
1229 printf("Floppy changed=%d\n", ret);
1230 #endif
1231 return ret;
1234 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1236 BDRVRawState *s = bs->opaque;
1237 int fd;
1239 if (s->fd >= 0) {
1240 close(s->fd);
1241 s->fd = -1;
1243 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1244 if (fd >= 0) {
1245 if (ioctl(fd, FDEJECT, 0) < 0)
1246 perror("FDEJECT");
1247 close(fd);
1250 return 0;
1253 static BlockDriver bdrv_host_floppy = {
1254 .format_name = "host_floppy",
1255 .protocol_name = "host_floppy",
1256 .instance_size = sizeof(BDRVRawState),
1257 .bdrv_probe_device = floppy_probe_device,
1258 .bdrv_file_open = floppy_open,
1259 .bdrv_close = raw_close,
1260 .bdrv_create = hdev_create,
1261 .create_options = raw_create_options,
1262 .bdrv_has_zero_init = hdev_has_zero_init,
1263 .bdrv_flush = raw_flush,
1265 .bdrv_aio_readv = raw_aio_readv,
1266 .bdrv_aio_writev = raw_aio_writev,
1267 .bdrv_aio_flush = raw_aio_flush,
1269 .bdrv_read = raw_read,
1270 .bdrv_write = raw_write,
1271 .bdrv_getlength = raw_getlength,
1273 /* removable device support */
1274 .bdrv_is_inserted = floppy_is_inserted,
1275 .bdrv_media_changed = floppy_media_changed,
1276 .bdrv_eject = floppy_eject,
1279 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1281 BDRVRawState *s = bs->opaque;
1283 s->type = FTYPE_CD;
1285 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1286 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1289 static int cdrom_probe_device(const char *filename)
1291 int fd, ret;
1292 int prio = 0;
1294 fd = open(filename, O_RDONLY | O_NONBLOCK);
1295 if (fd < 0) {
1296 goto out;
1299 /* Attempt to detect via a CDROM specific ioctl */
1300 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1301 if (ret >= 0)
1302 prio = 100;
1304 close(fd);
1305 out:
1306 return prio;
1309 static int cdrom_is_inserted(BlockDriverState *bs)
1311 BDRVRawState *s = bs->opaque;
1312 int ret;
1314 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1315 if (ret == CDS_DISC_OK)
1316 return 1;
1317 return 0;
1320 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1322 BDRVRawState *s = bs->opaque;
1324 if (eject_flag) {
1325 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1326 perror("CDROMEJECT");
1327 } else {
1328 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1329 perror("CDROMEJECT");
1332 return 0;
1335 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1337 BDRVRawState *s = bs->opaque;
1339 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1341 * Note: an error can happen if the distribution automatically
1342 * mounts the CD-ROM
1344 /* perror("CDROM_LOCKDOOR"); */
1347 return 0;
1350 static BlockDriver bdrv_host_cdrom = {
1351 .format_name = "host_cdrom",
1352 .protocol_name = "host_cdrom",
1353 .instance_size = sizeof(BDRVRawState),
1354 .bdrv_probe_device = cdrom_probe_device,
1355 .bdrv_file_open = cdrom_open,
1356 .bdrv_close = raw_close,
1357 .bdrv_create = hdev_create,
1358 .create_options = raw_create_options,
1359 .bdrv_has_zero_init = hdev_has_zero_init,
1360 .bdrv_flush = raw_flush,
1362 .bdrv_aio_readv = raw_aio_readv,
1363 .bdrv_aio_writev = raw_aio_writev,
1364 .bdrv_aio_flush = raw_aio_flush,
1366 .bdrv_read = raw_read,
1367 .bdrv_write = raw_write,
1368 .bdrv_getlength = raw_getlength,
1370 /* removable device support */
1371 .bdrv_is_inserted = cdrom_is_inserted,
1372 .bdrv_eject = cdrom_eject,
1373 .bdrv_set_locked = cdrom_set_locked,
1375 /* generic scsi device */
1376 .bdrv_ioctl = hdev_ioctl,
1377 .bdrv_aio_ioctl = hdev_aio_ioctl,
1379 #endif /* __linux__ */
1381 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1382 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1384 BDRVRawState *s = bs->opaque;
1385 int ret;
1387 s->type = FTYPE_CD;
1389 ret = raw_open_common(bs, filename, flags, 0);
1390 if (ret)
1391 return ret;
1393 /* make sure the door isnt locked at this time */
1394 ioctl(s->fd, CDIOCALLOW);
1395 return 0;
1398 static int cdrom_probe_device(const char *filename)
1400 if (strstart(filename, "/dev/cd", NULL) ||
1401 strstart(filename, "/dev/acd", NULL))
1402 return 100;
1403 return 0;
1406 static int cdrom_reopen(BlockDriverState *bs)
1408 BDRVRawState *s = bs->opaque;
1409 int fd;
1412 * Force reread of possibly changed/newly loaded disc,
1413 * FreeBSD seems to not notice sometimes...
1415 if (s->fd >= 0)
1416 close(s->fd);
1417 fd = open(bs->filename, s->open_flags, 0644);
1418 if (fd < 0) {
1419 s->fd = -1;
1420 return -EIO;
1422 s->fd = fd;
1424 /* make sure the door isnt locked at this time */
1425 ioctl(s->fd, CDIOCALLOW);
1426 return 0;
1429 static int cdrom_is_inserted(BlockDriverState *bs)
1431 return raw_getlength(bs) > 0;
1434 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1436 BDRVRawState *s = bs->opaque;
1438 if (s->fd < 0)
1439 return -ENOTSUP;
1441 (void) ioctl(s->fd, CDIOCALLOW);
1443 if (eject_flag) {
1444 if (ioctl(s->fd, CDIOCEJECT) < 0)
1445 perror("CDIOCEJECT");
1446 } else {
1447 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1448 perror("CDIOCCLOSE");
1451 if (cdrom_reopen(bs) < 0)
1452 return -ENOTSUP;
1453 return 0;
1456 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1458 BDRVRawState *s = bs->opaque;
1460 if (s->fd < 0)
1461 return -ENOTSUP;
1462 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1464 * Note: an error can happen if the distribution automatically
1465 * mounts the CD-ROM
1467 /* perror("CDROM_LOCKDOOR"); */
1470 return 0;
1473 static BlockDriver bdrv_host_cdrom = {
1474 .format_name = "host_cdrom",
1475 .protocol_name = "host_cdrom",
1476 .instance_size = sizeof(BDRVRawState),
1477 .bdrv_probe_device = cdrom_probe_device,
1478 .bdrv_file_open = cdrom_open,
1479 .bdrv_close = raw_close,
1480 .bdrv_create = hdev_create,
1481 .create_options = raw_create_options,
1482 .bdrv_has_zero_init = hdev_has_zero_init,
1483 .bdrv_flush = raw_flush,
1485 .bdrv_aio_readv = raw_aio_readv,
1486 .bdrv_aio_writev = raw_aio_writev,
1487 .bdrv_aio_flush = raw_aio_flush,
1489 .bdrv_read = raw_read,
1490 .bdrv_write = raw_write,
1491 .bdrv_getlength = raw_getlength,
1493 /* removable device support */
1494 .bdrv_is_inserted = cdrom_is_inserted,
1495 .bdrv_eject = cdrom_eject,
1496 .bdrv_set_locked = cdrom_set_locked,
1498 #endif /* __FreeBSD__ */
1500 static void bdrv_file_init(void)
1503 * Register all the drivers. Note that order is important, the driver
1504 * registered last will get probed first.
1506 bdrv_register(&bdrv_file);
1507 bdrv_register(&bdrv_host_device);
1508 #ifdef __linux__
1509 bdrv_register(&bdrv_host_floppy);
1510 bdrv_register(&bdrv_host_cdrom);
1511 #endif
1512 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1513 bdrv_register(&bdrv_host_cdrom);
1514 #endif
1517 block_init(bdrv_file_init);