Merge branch 'upstream-merge'
[qemu-kvm/markmc.git] / block / raw-posix.c
blob121412bc85ca77b885193080f71a620cfd2352a7
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 "compatfd.h"
31 #include <assert.h>
32 #include "block/raw-posix-aio.h"
34 #ifdef CONFIG_COCOA
35 #include <paths.h>
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
44 #endif
46 #ifdef __sun__
47 #define _POSIX_PTHREAD_SEMANTICS 1
48 #include <signal.h>
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/ioctl.h>
53 #include <linux/cdrom.h>
54 #include <linux/fd.h>
55 #endif
56 #ifdef __FreeBSD__
57 #include <signal.h>
58 #include <sys/disk.h>
59 #include <sys/cdio.h>
60 #endif
62 #ifdef __OpenBSD__
63 #include <sys/ioctl.h>
64 #include <sys/disklabel.h>
65 #include <sys/dkio.h>
66 #endif
68 #ifdef __DragonFly__
69 #include <sys/ioctl.h>
70 #include <sys/diskslice.h>
71 #endif
73 //#define DEBUG_FLOPPY
75 //#define DEBUG_BLOCK
76 #if defined(DEBUG_BLOCK)
77 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
78 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
79 #else
80 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
81 #endif
83 /* OS X does not have O_DSYNC */
84 #ifndef O_DSYNC
85 #ifdef O_SYNC
86 #define O_DSYNC O_SYNC
87 #elif defined(O_FSYNC)
88 #define O_DSYNC O_FSYNC
89 #endif
90 #endif
92 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
93 #ifndef O_DIRECT
94 #define O_DIRECT O_DSYNC
95 #endif
97 #define FTYPE_FILE 0
98 #define FTYPE_CD 1
99 #define FTYPE_FD 2
101 #define ALIGNED_BUFFER_SIZE (32 * 512)
103 /* if the FD is not accessed during that time (in ms), we try to
104 reopen it to see if the disk has been changed */
105 #define FD_OPEN_TIMEOUT 1000
107 typedef struct BDRVRawState {
108 int fd;
109 int type;
110 unsigned int lseek_err_cnt;
111 int open_flags;
112 void *aio_ctx;
113 #if defined(__linux__)
114 /* linux floppy specific */
115 int64_t fd_open_time;
116 int64_t fd_error_time;
117 int fd_got_error;
118 int fd_media_changed;
119 #endif
120 #ifdef CONFIG_LINUX_AIO
121 int use_aio;
122 #endif
123 uint8_t* aligned_buf;
124 } BDRVRawState;
126 static int fd_open(BlockDriverState *bs);
127 static int64_t raw_getlength(BlockDriverState *bs);
129 #if defined(__FreeBSD__)
130 static int cdrom_reopen(BlockDriverState *bs);
131 #endif
133 static int raw_open_common(BlockDriverState *bs, const char *filename,
134 int bdrv_flags, int open_flags)
136 BDRVRawState *s = bs->opaque;
137 int fd, ret;
139 s->lseek_err_cnt = 0;
141 s->open_flags = open_flags | O_BINARY;
142 s->open_flags &= ~O_ACCMODE;
143 if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
144 s->open_flags |= O_RDWR;
145 } else {
146 s->open_flags |= O_RDONLY;
147 bs->read_only = 1;
150 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
151 * and O_DIRECT for no caching. */
152 if ((bdrv_flags & BDRV_O_NOCACHE))
153 s->open_flags |= O_DIRECT;
154 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
155 s->open_flags |= O_DSYNC;
157 s->fd = -1;
158 fd = open(filename, s->open_flags, 0644);
159 if (fd < 0) {
160 ret = -errno;
161 if (ret == -EROFS)
162 ret = -EACCES;
163 return ret;
165 s->fd = fd;
166 s->aligned_buf = NULL;
168 if ((bdrv_flags & BDRV_O_NOCACHE)) {
169 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
170 if (s->aligned_buf == NULL) {
171 goto out_close;
175 #ifdef CONFIG_LINUX_AIO
176 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
177 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
179 /* We're falling back to POSIX AIO in some cases */
180 paio_init();
182 s->aio_ctx = laio_init();
183 if (!s->aio_ctx) {
184 goto out_free_buf;
186 s->use_aio = 1;
187 } else
188 #endif
190 s->aio_ctx = paio_init();
191 if (!s->aio_ctx) {
192 goto out_free_buf;
194 #ifdef CONFIG_LINUX_AIO
195 s->use_aio = 0;
196 #endif
199 return 0;
201 out_free_buf:
202 qemu_vfree(s->aligned_buf);
203 out_close:
204 close(fd);
205 return -errno;
208 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
210 BDRVRawState *s = bs->opaque;
211 int open_flags = 0;
213 s->type = FTYPE_FILE;
214 if (flags & BDRV_O_CREAT)
215 open_flags = O_CREAT | O_TRUNC;
217 return raw_open_common(bs, filename, flags, open_flags);
220 /* XXX: use host sector size if necessary with:
221 #ifdef DIOCGSECTORSIZE
223 unsigned int sectorsize = 512;
224 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
225 sectorsize > bufsize)
226 bufsize = sectorsize;
228 #endif
229 #ifdef CONFIG_COCOA
230 u_int32_t blockSize = 512;
231 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
232 bufsize = blockSize;
234 #endif
238 * offset and count are in bytes, but must be multiples of 512 for files
239 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
241 * This function may be called without alignment if the caller ensures
242 * that O_DIRECT is not in effect.
244 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
245 uint8_t *buf, int count)
247 BDRVRawState *s = bs->opaque;
248 int ret;
250 ret = fd_open(bs);
251 if (ret < 0)
252 return ret;
254 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
255 ++(s->lseek_err_cnt);
256 if(s->lseek_err_cnt <= 10) {
257 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
258 "] lseek failed : %d = %s\n",
259 s->fd, bs->filename, offset, buf, count,
260 bs->total_sectors, errno, strerror(errno));
262 return -1;
264 s->lseek_err_cnt=0;
266 ret = read(s->fd, buf, count);
267 if (ret == count)
268 goto label__raw_read__success;
270 /* Allow reads beyond the end (needed for pwrite) */
271 if ((ret == 0) && bs->growable) {
272 int64_t size = raw_getlength(bs);
273 if (offset >= size) {
274 memset(buf, 0, count);
275 ret = count;
276 goto label__raw_read__success;
280 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
281 "] read failed %d : %d = %s\n",
282 s->fd, bs->filename, offset, buf, count,
283 bs->total_sectors, ret, errno, strerror(errno));
285 /* Try harder for CDrom. */
286 if (bs->type == BDRV_TYPE_CDROM) {
287 lseek(s->fd, offset, SEEK_SET);
288 ret = read(s->fd, buf, count);
289 if (ret == count)
290 goto label__raw_read__success;
291 lseek(s->fd, offset, SEEK_SET);
292 ret = read(s->fd, buf, count);
293 if (ret == count)
294 goto label__raw_read__success;
296 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
297 "] retry read failed %d : %d = %s\n",
298 s->fd, bs->filename, offset, buf, count,
299 bs->total_sectors, ret, errno, strerror(errno));
302 label__raw_read__success:
304 return (ret < 0) ? -errno : ret;
308 * offset and count are in bytes, but must be multiples of 512 for files
309 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
311 * This function may be called without alignment if the caller ensures
312 * that O_DIRECT is not in effect.
314 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
315 const uint8_t *buf, int count)
317 BDRVRawState *s = bs->opaque;
318 int ret;
320 ret = fd_open(bs);
321 if (ret < 0)
322 return -errno;
324 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
325 ++(s->lseek_err_cnt);
326 if(s->lseek_err_cnt) {
327 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
328 PRId64 "] lseek failed : %d = %s\n",
329 s->fd, bs->filename, offset, buf, count,
330 bs->total_sectors, errno, strerror(errno));
332 return -EIO;
334 s->lseek_err_cnt = 0;
336 ret = write(s->fd, buf, count);
337 if (ret == count)
338 goto label__raw_write__success;
340 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
341 "] write failed %d : %d = %s\n",
342 s->fd, bs->filename, offset, buf, count,
343 bs->total_sectors, ret, errno, strerror(errno));
345 label__raw_write__success:
347 return (ret < 0) ? -errno : ret;
352 * offset and count are in bytes and possibly not aligned. For files opened
353 * with O_DIRECT, necessary alignments are ensured before calling
354 * raw_pread_aligned to do the actual read.
356 static int raw_pread(BlockDriverState *bs, int64_t offset,
357 uint8_t *buf, int count)
359 BDRVRawState *s = bs->opaque;
360 int size, ret, shift, sum;
362 sum = 0;
364 if (s->aligned_buf != NULL) {
366 if (offset & 0x1ff) {
367 /* align offset on a 512 bytes boundary */
369 shift = offset & 0x1ff;
370 size = (shift + count + 0x1ff) & ~0x1ff;
371 if (size > ALIGNED_BUFFER_SIZE)
372 size = ALIGNED_BUFFER_SIZE;
373 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
374 if (ret < 0)
375 return ret;
377 size = 512 - shift;
378 if (size > count)
379 size = count;
380 memcpy(buf, s->aligned_buf + shift, size);
382 buf += size;
383 offset += size;
384 count -= size;
385 sum += size;
387 if (count == 0)
388 return sum;
390 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
392 /* read on aligned buffer */
394 while (count) {
396 size = (count + 0x1ff) & ~0x1ff;
397 if (size > ALIGNED_BUFFER_SIZE)
398 size = ALIGNED_BUFFER_SIZE;
400 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
401 if (ret < 0)
402 return ret;
404 size = ret;
405 if (size > count)
406 size = count;
408 memcpy(buf, s->aligned_buf, size);
410 buf += size;
411 offset += size;
412 count -= size;
413 sum += size;
416 return sum;
420 return raw_pread_aligned(bs, offset, buf, count) + sum;
423 static int raw_read(BlockDriverState *bs, int64_t sector_num,
424 uint8_t *buf, int nb_sectors)
426 int ret;
428 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
429 if (ret == (nb_sectors * 512))
430 ret = 0;
431 return ret;
435 * offset and count are in bytes and possibly not aligned. For files opened
436 * with O_DIRECT, necessary alignments are ensured before calling
437 * raw_pwrite_aligned to do the actual write.
439 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
440 const uint8_t *buf, int count)
442 BDRVRawState *s = bs->opaque;
443 int size, ret, shift, sum;
445 sum = 0;
447 if (s->aligned_buf != NULL) {
449 if (offset & 0x1ff) {
450 /* align offset on a 512 bytes boundary */
451 shift = offset & 0x1ff;
452 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
453 if (ret < 0)
454 return ret;
456 size = 512 - shift;
457 if (size > count)
458 size = count;
459 memcpy(s->aligned_buf + shift, buf, size);
461 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
462 if (ret < 0)
463 return ret;
465 buf += size;
466 offset += size;
467 count -= size;
468 sum += size;
470 if (count == 0)
471 return sum;
473 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
475 while ((size = (count & ~0x1ff)) != 0) {
477 if (size > ALIGNED_BUFFER_SIZE)
478 size = ALIGNED_BUFFER_SIZE;
480 memcpy(s->aligned_buf, buf, size);
482 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
483 if (ret < 0)
484 return ret;
486 buf += ret;
487 offset += ret;
488 count -= ret;
489 sum += ret;
491 /* here, count < 512 because (count & ~0x1ff) == 0 */
492 if (count) {
493 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
494 if (ret < 0)
495 return ret;
496 memcpy(s->aligned_buf, buf, count);
498 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
499 if (ret < 0)
500 return ret;
501 if (count < ret)
502 ret = count;
504 sum += ret;
506 return sum;
509 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
512 static int raw_write(BlockDriverState *bs, int64_t sector_num,
513 const uint8_t *buf, int nb_sectors)
515 int ret;
516 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
517 if (ret == (nb_sectors * 512))
518 ret = 0;
519 return ret;
523 * Check if all memory in this vector is sector aligned.
525 static int qiov_is_aligned(QEMUIOVector *qiov)
527 int i;
529 for (i = 0; i < qiov->niov; i++) {
530 if ((uintptr_t) qiov->iov[i].iov_base % 512) {
531 return 0;
535 return 1;
538 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
539 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
540 BlockDriverCompletionFunc *cb, void *opaque, int type)
542 BDRVRawState *s = bs->opaque;
544 if (fd_open(bs) < 0)
545 return NULL;
548 * If O_DIRECT is used the buffer needs to be aligned on a sector
549 * boundary. Check if this is the case or telll the low-level
550 * driver that it needs to copy the buffer.
552 if (s->aligned_buf) {
553 if (!qiov_is_aligned(qiov)) {
554 type |= QEMU_AIO_MISALIGNED;
555 #ifdef CONFIG_LINUX_AIO
556 } else if (s->use_aio) {
557 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
558 nb_sectors, cb, opaque, type);
559 #endif
563 return paio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov, nb_sectors,
564 cb, opaque, type);
567 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
568 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
569 BlockDriverCompletionFunc *cb, void *opaque)
571 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
572 cb, opaque, QEMU_AIO_READ);
575 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
576 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
577 BlockDriverCompletionFunc *cb, void *opaque)
579 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
580 cb, opaque, QEMU_AIO_WRITE);
583 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
584 BlockDriverCompletionFunc *cb, void *opaque)
586 BDRVRawState *s = bs->opaque;
588 if (fd_open(bs) < 0)
589 return NULL;
591 return paio_submit(bs, s->aio_ctx, s->fd, 0, NULL, 0,
592 cb, opaque, QEMU_AIO_FLUSH);
595 static void raw_close(BlockDriverState *bs)
597 BDRVRawState *s = bs->opaque;
598 if (s->fd >= 0) {
599 close(s->fd);
600 s->fd = -1;
601 if (s->aligned_buf != NULL)
602 qemu_free(s->aligned_buf);
606 static int raw_truncate(BlockDriverState *bs, int64_t offset)
608 BDRVRawState *s = bs->opaque;
609 if (s->type != FTYPE_FILE)
610 return -ENOTSUP;
611 if (ftruncate(s->fd, offset) < 0)
612 return -errno;
613 return 0;
616 #ifdef __OpenBSD__
617 static int64_t raw_getlength(BlockDriverState *bs)
619 BDRVRawState *s = bs->opaque;
620 int fd = s->fd;
621 struct stat st;
623 if (fstat(fd, &st))
624 return -1;
625 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
626 struct disklabel dl;
628 if (ioctl(fd, DIOCGDINFO, &dl))
629 return -1;
630 return (uint64_t)dl.d_secsize *
631 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
632 } else
633 return st.st_size;
635 #else /* !__OpenBSD__ */
636 static int64_t raw_getlength(BlockDriverState *bs)
638 BDRVRawState *s = bs->opaque;
639 int fd = s->fd;
640 int64_t size;
641 #ifdef CONFIG_BSD
642 struct stat sb;
643 #ifdef __FreeBSD__
644 int reopened = 0;
645 #endif
646 #endif
647 #ifdef __sun__
648 struct dk_minfo minfo;
649 int rv;
650 #endif
651 int ret;
653 ret = fd_open(bs);
654 if (ret < 0)
655 return ret;
657 #ifdef CONFIG_BSD
658 #ifdef __FreeBSD__
659 again:
660 #endif
661 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
662 #ifdef DIOCGMEDIASIZE
663 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
664 #elif defined(DIOCGPART)
666 struct partinfo pi;
667 if (ioctl(fd, DIOCGPART, &pi) == 0)
668 size = pi.media_size;
669 else
670 size = 0;
672 if (size == 0)
673 #endif
674 #ifdef CONFIG_COCOA
675 size = LONG_LONG_MAX;
676 #else
677 size = lseek(fd, 0LL, SEEK_END);
678 #endif
679 #ifdef __FreeBSD__
680 switch(s->type) {
681 case FTYPE_CD:
682 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
683 if (size == 2048LL * (unsigned)-1)
684 size = 0;
685 /* XXX no disc? maybe we need to reopen... */
686 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
687 reopened = 1;
688 goto again;
691 #endif
692 } else
693 #endif
694 #ifdef __sun__
696 * use the DKIOCGMEDIAINFO ioctl to read the size.
698 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
699 if ( rv != -1 ) {
700 size = minfo.dki_lbsize * minfo.dki_capacity;
701 } else /* there are reports that lseek on some devices
702 fails, but irc discussion said that contingency
703 on contingency was overkill */
704 #endif
706 size = lseek(fd, 0, SEEK_END);
708 return size;
710 #endif
712 static int raw_create(const char *filename, QEMUOptionParameter *options)
714 int fd;
715 int result = 0;
716 int64_t total_size = 0;
718 /* Read out options */
719 while (options && options->name) {
720 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
721 total_size = options->value.n / 512;
723 options++;
726 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
727 0644);
728 if (fd < 0) {
729 result = -errno;
730 } else {
731 if (ftruncate(fd, total_size * 512) != 0) {
732 result = -errno;
734 if (close(fd) != 0) {
735 result = -errno;
738 return result;
741 static void raw_flush(BlockDriverState *bs)
743 BDRVRawState *s = bs->opaque;
744 qemu_fdatasync(s->fd);
748 static QEMUOptionParameter raw_create_options[] = {
750 .name = BLOCK_OPT_SIZE,
751 .type = OPT_SIZE,
752 .help = "Virtual disk size"
754 { NULL }
757 static BlockDriver bdrv_raw = {
758 .format_name = "raw",
759 .instance_size = sizeof(BDRVRawState),
760 .bdrv_probe = NULL, /* no probe for protocols */
761 .bdrv_open = raw_open,
762 .bdrv_read = raw_read,
763 .bdrv_write = raw_write,
764 .bdrv_close = raw_close,
765 .bdrv_create = raw_create,
766 .bdrv_flush = raw_flush,
768 .bdrv_aio_readv = raw_aio_readv,
769 .bdrv_aio_writev = raw_aio_writev,
770 .bdrv_aio_flush = raw_aio_flush,
772 .bdrv_truncate = raw_truncate,
773 .bdrv_getlength = raw_getlength,
775 .create_options = raw_create_options,
778 /***********************************************/
779 /* host device */
781 #ifdef CONFIG_COCOA
782 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
783 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
785 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
787 kern_return_t kernResult;
788 mach_port_t masterPort;
789 CFMutableDictionaryRef classesToMatch;
791 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
792 if ( KERN_SUCCESS != kernResult ) {
793 printf( "IOMasterPort returned %d\n", kernResult );
796 classesToMatch = IOServiceMatching( kIOCDMediaClass );
797 if ( classesToMatch == NULL ) {
798 printf( "IOServiceMatching returned a NULL dictionary.\n" );
799 } else {
800 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
802 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
803 if ( KERN_SUCCESS != kernResult )
805 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
808 return kernResult;
811 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
813 io_object_t nextMedia;
814 kern_return_t kernResult = KERN_FAILURE;
815 *bsdPath = '\0';
816 nextMedia = IOIteratorNext( mediaIterator );
817 if ( nextMedia )
819 CFTypeRef bsdPathAsCFString;
820 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
821 if ( bsdPathAsCFString ) {
822 size_t devPathLength;
823 strcpy( bsdPath, _PATH_DEV );
824 strcat( bsdPath, "r" );
825 devPathLength = strlen( bsdPath );
826 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
827 kernResult = KERN_SUCCESS;
829 CFRelease( bsdPathAsCFString );
831 IOObjectRelease( nextMedia );
834 return kernResult;
837 #endif
839 static int hdev_probe_device(const char *filename)
841 struct stat st;
843 /* allow a dedicated CD-ROM driver to match with a higher priority */
844 if (strstart(filename, "/dev/cdrom", NULL))
845 return 50;
847 if (stat(filename, &st) >= 0 &&
848 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
849 return 100;
852 return 0;
855 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
857 BDRVRawState *s = bs->opaque;
859 #ifdef CONFIG_COCOA
860 if (strstart(filename, "/dev/cdrom", NULL)) {
861 kern_return_t kernResult;
862 io_iterator_t mediaIterator;
863 char bsdPath[ MAXPATHLEN ];
864 int fd;
866 kernResult = FindEjectableCDMedia( &mediaIterator );
867 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
869 if ( bsdPath[ 0 ] != '\0' ) {
870 strcat(bsdPath,"s0");
871 /* some CDs don't have a partition 0 */
872 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
873 if (fd < 0) {
874 bsdPath[strlen(bsdPath)-1] = '1';
875 } else {
876 close(fd);
878 filename = bsdPath;
881 if ( mediaIterator )
882 IOObjectRelease( mediaIterator );
884 #endif
886 s->type = FTYPE_FILE;
887 #if defined(__linux__)
888 if (strstart(filename, "/dev/sg", NULL)) {
889 bs->sg = 1;
891 #endif
893 return raw_open_common(bs, filename, flags, 0);
896 #if defined(__linux__)
897 /* Note: we do not have a reliable method to detect if the floppy is
898 present. The current method is to try to open the floppy at every
899 I/O and to keep it opened during a few hundreds of ms. */
900 static int fd_open(BlockDriverState *bs)
902 BDRVRawState *s = bs->opaque;
903 int last_media_present;
905 if (s->type != FTYPE_FD)
906 return 0;
907 last_media_present = (s->fd >= 0);
908 if (s->fd >= 0 &&
909 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
910 close(s->fd);
911 s->fd = -1;
912 #ifdef DEBUG_FLOPPY
913 printf("Floppy closed\n");
914 #endif
916 if (s->fd < 0) {
917 if (s->fd_got_error &&
918 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
919 #ifdef DEBUG_FLOPPY
920 printf("No floppy (open delayed)\n");
921 #endif
922 return -EIO;
924 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
925 if (s->fd < 0) {
926 s->fd_error_time = qemu_get_clock(rt_clock);
927 s->fd_got_error = 1;
928 if (last_media_present)
929 s->fd_media_changed = 1;
930 #ifdef DEBUG_FLOPPY
931 printf("No floppy\n");
932 #endif
933 return -EIO;
935 #ifdef DEBUG_FLOPPY
936 printf("Floppy opened\n");
937 #endif
939 if (!last_media_present)
940 s->fd_media_changed = 1;
941 s->fd_open_time = qemu_get_clock(rt_clock);
942 s->fd_got_error = 0;
943 return 0;
946 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
948 BDRVRawState *s = bs->opaque;
950 return ioctl(s->fd, req, buf);
953 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
954 unsigned long int req, void *buf,
955 BlockDriverCompletionFunc *cb, void *opaque)
957 BDRVRawState *s = bs->opaque;
959 if (fd_open(bs) < 0)
960 return NULL;
961 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
964 #elif defined(__FreeBSD__)
965 static int fd_open(BlockDriverState *bs)
967 BDRVRawState *s = bs->opaque;
969 /* this is just to ensure s->fd is sane (its called by io ops) */
970 if (s->fd >= 0)
971 return 0;
972 return -EIO;
974 #else /* !linux && !FreeBSD */
976 static int fd_open(BlockDriverState *bs)
978 return 0;
981 #endif /* !linux && !FreeBSD */
983 static int hdev_create(const char *filename, QEMUOptionParameter *options)
985 int fd;
986 int ret = 0;
987 struct stat stat_buf;
988 int64_t total_size = 0;
990 /* Read out options */
991 while (options && options->name) {
992 if (!strcmp(options->name, "size")) {
993 total_size = options->value.n / 512;
995 options++;
998 fd = open(filename, O_WRONLY | O_BINARY);
999 if (fd < 0)
1000 return -EIO;
1002 if (fstat(fd, &stat_buf) < 0)
1003 ret = -EIO;
1004 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1005 ret = -EIO;
1006 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1007 ret = -ENOSPC;
1009 close(fd);
1010 return ret;
1013 static BlockDriver bdrv_host_device = {
1014 .format_name = "host_device",
1015 .instance_size = sizeof(BDRVRawState),
1016 .bdrv_probe_device = hdev_probe_device,
1017 .bdrv_open = hdev_open,
1018 .bdrv_close = raw_close,
1019 .bdrv_create = hdev_create,
1020 .create_options = raw_create_options,
1021 .bdrv_flush = raw_flush,
1023 .bdrv_aio_readv = raw_aio_readv,
1024 .bdrv_aio_writev = raw_aio_writev,
1025 .bdrv_aio_flush = raw_aio_flush,
1027 .bdrv_read = raw_read,
1028 .bdrv_write = raw_write,
1029 .bdrv_getlength = raw_getlength,
1031 /* generic scsi device */
1032 #ifdef __linux__
1033 .bdrv_ioctl = hdev_ioctl,
1034 .bdrv_aio_ioctl = hdev_aio_ioctl,
1035 #endif
1038 #ifdef __linux__
1039 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1041 BDRVRawState *s = bs->opaque;
1042 int ret;
1044 s->type = FTYPE_FD;
1046 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1047 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1048 if (ret)
1049 return ret;
1051 /* close fd so that we can reopen it as needed */
1052 close(s->fd);
1053 s->fd = -1;
1054 s->fd_media_changed = 1;
1056 return 0;
1059 static int floppy_probe_device(const char *filename)
1061 if (strstart(filename, "/dev/fd", NULL))
1062 return 100;
1063 return 0;
1067 static int floppy_is_inserted(BlockDriverState *bs)
1069 return fd_open(bs) >= 0;
1072 static int floppy_media_changed(BlockDriverState *bs)
1074 BDRVRawState *s = bs->opaque;
1075 int ret;
1078 * XXX: we do not have a true media changed indication.
1079 * It does not work if the floppy is changed without trying to read it.
1081 fd_open(bs);
1082 ret = s->fd_media_changed;
1083 s->fd_media_changed = 0;
1084 #ifdef DEBUG_FLOPPY
1085 printf("Floppy changed=%d\n", ret);
1086 #endif
1087 return ret;
1090 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1092 BDRVRawState *s = bs->opaque;
1093 int fd;
1095 if (s->fd >= 0) {
1096 close(s->fd);
1097 s->fd = -1;
1099 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1100 if (fd >= 0) {
1101 if (ioctl(fd, FDEJECT, 0) < 0)
1102 perror("FDEJECT");
1103 close(fd);
1106 return 0;
1109 static BlockDriver bdrv_host_floppy = {
1110 .format_name = "host_floppy",
1111 .instance_size = sizeof(BDRVRawState),
1112 .bdrv_probe_device = floppy_probe_device,
1113 .bdrv_open = floppy_open,
1114 .bdrv_close = raw_close,
1115 .bdrv_create = hdev_create,
1116 .create_options = raw_create_options,
1117 .bdrv_flush = raw_flush,
1119 .bdrv_aio_readv = raw_aio_readv,
1120 .bdrv_aio_writev = raw_aio_writev,
1121 .bdrv_aio_flush = raw_aio_flush,
1123 .bdrv_read = raw_read,
1124 .bdrv_write = raw_write,
1125 .bdrv_getlength = raw_getlength,
1127 /* removable device support */
1128 .bdrv_is_inserted = floppy_is_inserted,
1129 .bdrv_media_changed = floppy_media_changed,
1130 .bdrv_eject = floppy_eject,
1133 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1135 BDRVRawState *s = bs->opaque;
1137 s->type = FTYPE_CD;
1139 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1140 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1143 static int cdrom_probe_device(const char *filename)
1145 if (strstart(filename, "/dev/cd", NULL))
1146 return 100;
1147 return 0;
1150 static int cdrom_is_inserted(BlockDriverState *bs)
1152 BDRVRawState *s = bs->opaque;
1153 int ret;
1155 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1156 if (ret == CDS_DISC_OK)
1157 return 1;
1158 return 0;
1161 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1163 BDRVRawState *s = bs->opaque;
1165 if (eject_flag) {
1166 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1167 perror("CDROMEJECT");
1168 } else {
1169 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1170 perror("CDROMEJECT");
1173 return 0;
1176 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1178 BDRVRawState *s = bs->opaque;
1180 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1182 * Note: an error can happen if the distribution automatically
1183 * mounts the CD-ROM
1185 /* perror("CDROM_LOCKDOOR"); */
1188 return 0;
1191 static BlockDriver bdrv_host_cdrom = {
1192 .format_name = "host_cdrom",
1193 .instance_size = sizeof(BDRVRawState),
1194 .bdrv_probe_device = cdrom_probe_device,
1195 .bdrv_open = cdrom_open,
1196 .bdrv_close = raw_close,
1197 .bdrv_create = hdev_create,
1198 .create_options = raw_create_options,
1199 .bdrv_flush = raw_flush,
1201 .bdrv_aio_readv = raw_aio_readv,
1202 .bdrv_aio_writev = raw_aio_writev,
1203 .bdrv_aio_flush = raw_aio_flush,
1205 .bdrv_read = raw_read,
1206 .bdrv_write = raw_write,
1207 .bdrv_getlength = raw_getlength,
1209 /* removable device support */
1210 .bdrv_is_inserted = cdrom_is_inserted,
1211 .bdrv_eject = cdrom_eject,
1212 .bdrv_set_locked = cdrom_set_locked,
1214 /* generic scsi device */
1215 .bdrv_ioctl = hdev_ioctl,
1216 .bdrv_aio_ioctl = hdev_aio_ioctl,
1218 #endif /* __linux__ */
1220 #ifdef __FreeBSD__
1221 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1223 BDRVRawState *s = bs->opaque;
1224 int ret;
1226 s->type = FTYPE_CD;
1228 ret = raw_open_common(bs, filename, flags, 0);
1229 if (ret)
1230 return ret;
1232 /* make sure the door isnt locked at this time */
1233 ioctl(s->fd, CDIOCALLOW);
1234 return 0;
1237 static int cdrom_probe_device(const char *filename)
1239 if (strstart(filename, "/dev/cd", NULL) ||
1240 strstart(filename, "/dev/acd", NULL))
1241 return 100;
1242 return 0;
1245 static int cdrom_reopen(BlockDriverState *bs)
1247 BDRVRawState *s = bs->opaque;
1248 int fd;
1251 * Force reread of possibly changed/newly loaded disc,
1252 * FreeBSD seems to not notice sometimes...
1254 if (s->fd >= 0)
1255 close(s->fd);
1256 fd = open(bs->filename, s->open_flags, 0644);
1257 if (fd < 0) {
1258 s->fd = -1;
1259 return -EIO;
1261 s->fd = fd;
1263 /* make sure the door isnt locked at this time */
1264 ioctl(s->fd, CDIOCALLOW);
1265 return 0;
1268 static int cdrom_is_inserted(BlockDriverState *bs)
1270 return raw_getlength(bs) > 0;
1273 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1275 BDRVRawState *s = bs->opaque;
1277 if (s->fd < 0)
1278 return -ENOTSUP;
1280 (void) ioctl(s->fd, CDIOCALLOW);
1282 if (eject_flag) {
1283 if (ioctl(s->fd, CDIOCEJECT) < 0)
1284 perror("CDIOCEJECT");
1285 } else {
1286 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1287 perror("CDIOCCLOSE");
1290 if (cdrom_reopen(bs) < 0)
1291 return -ENOTSUP;
1292 return 0;
1295 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1297 BDRVRawState *s = bs->opaque;
1299 if (s->fd < 0)
1300 return -ENOTSUP;
1301 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1303 * Note: an error can happen if the distribution automatically
1304 * mounts the CD-ROM
1306 /* perror("CDROM_LOCKDOOR"); */
1309 return 0;
1312 static BlockDriver bdrv_host_cdrom = {
1313 .format_name = "host_cdrom",
1314 .instance_size = sizeof(BDRVRawState),
1315 .bdrv_probe_device = cdrom_probe_device,
1316 .bdrv_open = cdrom_open,
1317 .bdrv_close = raw_close,
1318 .bdrv_create = hdev_create,
1319 .create_options = raw_create_options,
1320 .bdrv_flush = raw_flush,
1322 .bdrv_aio_readv = raw_aio_readv,
1323 .bdrv_aio_writev = raw_aio_writev,
1324 .bdrv_aio_flush = raw_aio_flush,
1326 .bdrv_read = raw_read,
1327 .bdrv_write = raw_write,
1328 .bdrv_getlength = raw_getlength,
1330 /* removable device support */
1331 .bdrv_is_inserted = cdrom_is_inserted,
1332 .bdrv_eject = cdrom_eject,
1333 .bdrv_set_locked = cdrom_set_locked,
1335 #endif /* __FreeBSD__ */
1337 static void bdrv_raw_init(void)
1340 * Register all the drivers. Note that order is important, the driver
1341 * registered last will get probed first.
1343 bdrv_register(&bdrv_raw);
1344 bdrv_register(&bdrv_host_device);
1345 #ifdef __linux__
1346 bdrv_register(&bdrv_host_floppy);
1347 bdrv_register(&bdrv_host_cdrom);
1348 #endif
1349 #ifdef __FreeBSD__
1350 bdrv_register(&bdrv_host_cdrom);
1351 #endif
1354 block_init(bdrv_raw_init);