Don't launch guest if -no-kvm when tcg is not configured in
[qemu/qemu-dev-zwu.git] / block / raw-posix.c
blobaf47e82d55e7e62ff42e3b7134e0738491d2071a
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 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
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 int open_flags;
111 #if defined(__linux__)
112 /* linux floppy specific */
113 int64_t fd_open_time;
114 int64_t fd_error_time;
115 int fd_got_error;
116 int fd_media_changed;
117 #endif
118 #ifdef CONFIG_LINUX_AIO
119 int use_aio;
120 void *aio_ctx;
121 #endif
122 uint8_t* aligned_buf;
123 } BDRVRawState;
125 static int fd_open(BlockDriverState *bs);
126 static int64_t raw_getlength(BlockDriverState *bs);
128 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
129 static int cdrom_reopen(BlockDriverState *bs);
130 #endif
132 static int raw_open_common(BlockDriverState *bs, const char *filename,
133 int bdrv_flags, int open_flags)
135 BDRVRawState *s = bs->opaque;
136 int fd, ret;
138 s->open_flags = open_flags | O_BINARY;
139 s->open_flags &= ~O_ACCMODE;
140 if (bdrv_flags & BDRV_O_RDWR) {
141 s->open_flags |= O_RDWR;
142 } else {
143 s->open_flags |= O_RDONLY;
146 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
147 * and O_DIRECT for no caching. */
148 if ((bdrv_flags & BDRV_O_NOCACHE))
149 s->open_flags |= O_DIRECT;
150 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
151 s->open_flags |= O_DSYNC;
153 s->fd = -1;
154 fd = qemu_open(filename, s->open_flags, 0644);
155 if (fd < 0) {
156 ret = -errno;
157 if (ret == -EROFS)
158 ret = -EACCES;
159 return ret;
161 s->fd = fd;
162 s->aligned_buf = NULL;
164 if ((bdrv_flags & BDRV_O_NOCACHE)) {
165 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
166 if (s->aligned_buf == NULL) {
167 goto out_close;
171 #ifdef CONFIG_LINUX_AIO
172 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
173 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
175 /* We're falling back to POSIX AIO in some cases */
176 paio_init();
178 s->aio_ctx = laio_init();
179 if (!s->aio_ctx) {
180 goto out_free_buf;
182 s->use_aio = 1;
183 } else
184 #endif
186 if (paio_init() < 0) {
187 goto out_free_buf;
189 #ifdef CONFIG_LINUX_AIO
190 s->use_aio = 0;
191 #endif
194 return 0;
196 out_free_buf:
197 qemu_vfree(s->aligned_buf);
198 out_close:
199 close(fd);
200 return -errno;
203 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
205 BDRVRawState *s = bs->opaque;
207 s->type = FTYPE_FILE;
208 return raw_open_common(bs, filename, flags, 0);
211 /* XXX: use host sector size if necessary with:
212 #ifdef DIOCGSECTORSIZE
214 unsigned int sectorsize = 512;
215 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
216 sectorsize > bufsize)
217 bufsize = sectorsize;
219 #endif
220 #ifdef CONFIG_COCOA
221 uint32_t blockSize = 512;
222 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
223 bufsize = blockSize;
225 #endif
229 * offset and count are in bytes, but must be multiples of 512 for files
230 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
232 * This function may be called without alignment if the caller ensures
233 * that O_DIRECT is not in effect.
235 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
236 uint8_t *buf, int count)
238 BDRVRawState *s = bs->opaque;
239 int ret;
241 ret = fd_open(bs);
242 if (ret < 0)
243 return ret;
245 ret = pread(s->fd, buf, count, offset);
246 if (ret == count)
247 return ret;
249 /* Allow reads beyond the end (needed for pwrite) */
250 if ((ret == 0) && bs->growable) {
251 int64_t size = raw_getlength(bs);
252 if (offset >= size) {
253 memset(buf, 0, count);
254 return count;
258 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
259 "] read failed %d : %d = %s\n",
260 s->fd, bs->filename, offset, buf, count,
261 bs->total_sectors, ret, errno, strerror(errno));
263 /* Try harder for CDrom. */
264 if (s->type != FTYPE_FILE) {
265 ret = pread(s->fd, buf, count, offset);
266 if (ret == count)
267 return ret;
268 ret = pread(s->fd, buf, count, offset);
269 if (ret == count)
270 return ret;
272 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
273 "] retry read failed %d : %d = %s\n",
274 s->fd, bs->filename, offset, buf, count,
275 bs->total_sectors, ret, errno, strerror(errno));
278 return (ret < 0) ? -errno : ret;
282 * offset and count are in bytes, but must be multiples of 512 for files
283 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
285 * This function may be called without alignment if the caller ensures
286 * that O_DIRECT is not in effect.
288 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
289 const uint8_t *buf, int count)
291 BDRVRawState *s = bs->opaque;
292 int ret;
294 ret = fd_open(bs);
295 if (ret < 0)
296 return -errno;
298 ret = pwrite(s->fd, buf, count, offset);
299 if (ret == count)
300 return ret;
302 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
303 "] write failed %d : %d = %s\n",
304 s->fd, bs->filename, offset, buf, count,
305 bs->total_sectors, ret, errno, strerror(errno));
307 return (ret < 0) ? -errno : ret;
312 * offset and count are in bytes and possibly not aligned. For files opened
313 * with O_DIRECT, necessary alignments are ensured before calling
314 * raw_pread_aligned to do the actual read.
316 static int raw_pread(BlockDriverState *bs, int64_t offset,
317 uint8_t *buf, int count)
319 BDRVRawState *s = bs->opaque;
320 int size, ret, shift, sum;
322 sum = 0;
324 if (s->aligned_buf != NULL) {
326 if (offset & 0x1ff) {
327 /* align offset on a 512 bytes boundary */
329 shift = offset & 0x1ff;
330 size = (shift + count + 0x1ff) & ~0x1ff;
331 if (size > ALIGNED_BUFFER_SIZE)
332 size = ALIGNED_BUFFER_SIZE;
333 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
334 if (ret < 0)
335 return ret;
337 size = 512 - shift;
338 if (size > count)
339 size = count;
340 memcpy(buf, s->aligned_buf + shift, size);
342 buf += size;
343 offset += size;
344 count -= size;
345 sum += size;
347 if (count == 0)
348 return sum;
350 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
352 /* read on aligned buffer */
354 while (count) {
356 size = (count + 0x1ff) & ~0x1ff;
357 if (size > ALIGNED_BUFFER_SIZE)
358 size = ALIGNED_BUFFER_SIZE;
360 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
361 if (ret < 0) {
362 return ret;
363 } else if (ret == 0) {
364 fprintf(stderr, "raw_pread: read beyond end of file\n");
365 abort();
368 size = ret;
369 if (size > count)
370 size = count;
372 memcpy(buf, s->aligned_buf, size);
374 buf += size;
375 offset += size;
376 count -= size;
377 sum += size;
380 return sum;
384 return raw_pread_aligned(bs, offset, buf, count) + sum;
387 static int raw_read(BlockDriverState *bs, int64_t sector_num,
388 uint8_t *buf, int nb_sectors)
390 int ret;
392 ret = raw_pread(bs, sector_num * BDRV_SECTOR_SIZE, buf,
393 nb_sectors * BDRV_SECTOR_SIZE);
394 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
395 ret = 0;
396 return ret;
400 * offset and count are in bytes and possibly not aligned. For files opened
401 * with O_DIRECT, necessary alignments are ensured before calling
402 * raw_pwrite_aligned to do the actual write.
404 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
405 const uint8_t *buf, int count)
407 BDRVRawState *s = bs->opaque;
408 int size, ret, shift, sum;
410 sum = 0;
412 if (s->aligned_buf != NULL) {
414 if (offset & 0x1ff) {
415 /* align offset on a 512 bytes boundary */
416 shift = offset & 0x1ff;
417 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
418 if (ret < 0)
419 return ret;
421 size = 512 - shift;
422 if (size > count)
423 size = count;
424 memcpy(s->aligned_buf + shift, buf, size);
426 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
427 if (ret < 0)
428 return ret;
430 buf += size;
431 offset += size;
432 count -= size;
433 sum += size;
435 if (count == 0)
436 return sum;
438 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
440 while ((size = (count & ~0x1ff)) != 0) {
442 if (size > ALIGNED_BUFFER_SIZE)
443 size = ALIGNED_BUFFER_SIZE;
445 memcpy(s->aligned_buf, buf, size);
447 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
448 if (ret < 0)
449 return ret;
451 buf += ret;
452 offset += ret;
453 count -= ret;
454 sum += ret;
456 /* here, count < 512 because (count & ~0x1ff) == 0 */
457 if (count) {
458 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
459 if (ret < 0)
460 return ret;
461 memcpy(s->aligned_buf, buf, count);
463 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
464 if (ret < 0)
465 return ret;
466 if (count < ret)
467 ret = count;
469 sum += ret;
471 return sum;
474 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
477 static int raw_write(BlockDriverState *bs, int64_t sector_num,
478 const uint8_t *buf, int nb_sectors)
480 int ret;
481 ret = raw_pwrite(bs, sector_num * BDRV_SECTOR_SIZE, buf,
482 nb_sectors * BDRV_SECTOR_SIZE);
483 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
484 ret = 0;
485 return ret;
489 * Check if all memory in this vector is sector aligned.
491 static int qiov_is_aligned(QEMUIOVector *qiov)
493 int i;
495 for (i = 0; i < qiov->niov; i++) {
496 if ((uintptr_t) qiov->iov[i].iov_base % BDRV_SECTOR_SIZE) {
497 return 0;
501 return 1;
504 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
505 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
506 BlockDriverCompletionFunc *cb, void *opaque, int type)
508 BDRVRawState *s = bs->opaque;
510 if (fd_open(bs) < 0)
511 return NULL;
514 * If O_DIRECT is used the buffer needs to be aligned on a sector
515 * boundary. Check if this is the case or telll the low-level
516 * driver that it needs to copy the buffer.
518 if (s->aligned_buf) {
519 if (!qiov_is_aligned(qiov)) {
520 type |= QEMU_AIO_MISALIGNED;
521 #ifdef CONFIG_LINUX_AIO
522 } else if (s->use_aio) {
523 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
524 nb_sectors, cb, opaque, type);
525 #endif
529 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
530 cb, opaque, type);
533 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
534 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
535 BlockDriverCompletionFunc *cb, void *opaque)
537 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
538 cb, opaque, QEMU_AIO_READ);
541 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
542 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
543 BlockDriverCompletionFunc *cb, void *opaque)
545 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
546 cb, opaque, QEMU_AIO_WRITE);
549 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
550 BlockDriverCompletionFunc *cb, void *opaque)
552 BDRVRawState *s = bs->opaque;
554 if (fd_open(bs) < 0)
555 return NULL;
557 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
560 static void raw_close(BlockDriverState *bs)
562 BDRVRawState *s = bs->opaque;
563 if (s->fd >= 0) {
564 close(s->fd);
565 s->fd = -1;
566 if (s->aligned_buf != NULL)
567 qemu_vfree(s->aligned_buf);
571 static int raw_truncate(BlockDriverState *bs, int64_t offset)
573 BDRVRawState *s = bs->opaque;
574 if (s->type != FTYPE_FILE)
575 return -ENOTSUP;
576 if (ftruncate(s->fd, offset) < 0)
577 return -errno;
578 return 0;
581 #ifdef __OpenBSD__
582 static int64_t raw_getlength(BlockDriverState *bs)
584 BDRVRawState *s = bs->opaque;
585 int fd = s->fd;
586 struct stat st;
588 if (fstat(fd, &st))
589 return -1;
590 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
591 struct disklabel dl;
593 if (ioctl(fd, DIOCGDINFO, &dl))
594 return -1;
595 return (uint64_t)dl.d_secsize *
596 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
597 } else
598 return st.st_size;
600 #elif defined(__sun__)
601 static int64_t raw_getlength(BlockDriverState *bs)
603 BDRVRawState *s = bs->opaque;
604 struct dk_minfo minfo;
605 int ret;
607 ret = fd_open(bs);
608 if (ret < 0) {
609 return ret;
613 * Use the DKIOCGMEDIAINFO ioctl to read the size.
615 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
616 if (ret != -1) {
617 return minfo.dki_lbsize * minfo.dki_capacity;
621 * There are reports that lseek on some devices fails, but
622 * irc discussion said that contingency on contingency was overkill.
624 return lseek(s->fd, 0, SEEK_END);
626 #elif defined(CONFIG_BSD)
627 static int64_t raw_getlength(BlockDriverState *bs)
629 BDRVRawState *s = bs->opaque;
630 int fd = s->fd;
631 int64_t size;
632 struct stat sb;
633 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
634 int reopened = 0;
635 #endif
636 int ret;
638 ret = fd_open(bs);
639 if (ret < 0)
640 return ret;
642 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
643 again:
644 #endif
645 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
646 #ifdef DIOCGMEDIASIZE
647 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
648 #elif defined(DIOCGPART)
650 struct partinfo pi;
651 if (ioctl(fd, DIOCGPART, &pi) == 0)
652 size = pi.media_size;
653 else
654 size = 0;
656 if (size == 0)
657 #endif
658 #ifdef CONFIG_COCOA
659 size = LONG_LONG_MAX;
660 #else
661 size = lseek(fd, 0LL, SEEK_END);
662 #endif
663 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
664 switch(s->type) {
665 case FTYPE_CD:
666 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
667 if (size == 2048LL * (unsigned)-1)
668 size = 0;
669 /* XXX no disc? maybe we need to reopen... */
670 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
671 reopened = 1;
672 goto again;
675 #endif
676 } else {
677 size = lseek(fd, 0, SEEK_END);
679 return size;
681 #else
682 static int64_t raw_getlength(BlockDriverState *bs)
684 BDRVRawState *s = bs->opaque;
685 int ret;
687 ret = fd_open(bs);
688 if (ret < 0) {
689 return ret;
692 return lseek(s->fd, 0, SEEK_END);
694 #endif
696 static int raw_create(const char *filename, QEMUOptionParameter *options)
698 int fd;
699 int result = 0;
700 int64_t total_size = 0;
702 /* Read out options */
703 while (options && options->name) {
704 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
705 total_size = options->value.n / BDRV_SECTOR_SIZE;
707 options++;
710 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
711 0644);
712 if (fd < 0) {
713 result = -errno;
714 } else {
715 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
716 result = -errno;
718 if (close(fd) != 0) {
719 result = -errno;
722 return result;
725 static void raw_flush(BlockDriverState *bs)
727 BDRVRawState *s = bs->opaque;
728 qemu_fdatasync(s->fd);
732 static QEMUOptionParameter raw_create_options[] = {
734 .name = BLOCK_OPT_SIZE,
735 .type = OPT_SIZE,
736 .help = "Virtual disk size"
738 { NULL }
741 static BlockDriver bdrv_file = {
742 .format_name = "file",
743 .protocol_name = "file",
744 .instance_size = sizeof(BDRVRawState),
745 .bdrv_probe = NULL, /* no probe for protocols */
746 .bdrv_file_open = raw_open,
747 .bdrv_read = raw_read,
748 .bdrv_write = raw_write,
749 .bdrv_close = raw_close,
750 .bdrv_create = raw_create,
751 .bdrv_flush = raw_flush,
753 .bdrv_aio_readv = raw_aio_readv,
754 .bdrv_aio_writev = raw_aio_writev,
755 .bdrv_aio_flush = raw_aio_flush,
757 .bdrv_truncate = raw_truncate,
758 .bdrv_getlength = raw_getlength,
760 .create_options = raw_create_options,
763 /***********************************************/
764 /* host device */
766 #ifdef CONFIG_COCOA
767 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
768 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
770 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
772 kern_return_t kernResult;
773 mach_port_t masterPort;
774 CFMutableDictionaryRef classesToMatch;
776 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
777 if ( KERN_SUCCESS != kernResult ) {
778 printf( "IOMasterPort returned %d\n", kernResult );
781 classesToMatch = IOServiceMatching( kIOCDMediaClass );
782 if ( classesToMatch == NULL ) {
783 printf( "IOServiceMatching returned a NULL dictionary.\n" );
784 } else {
785 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
787 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
788 if ( KERN_SUCCESS != kernResult )
790 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
793 return kernResult;
796 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
798 io_object_t nextMedia;
799 kern_return_t kernResult = KERN_FAILURE;
800 *bsdPath = '\0';
801 nextMedia = IOIteratorNext( mediaIterator );
802 if ( nextMedia )
804 CFTypeRef bsdPathAsCFString;
805 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
806 if ( bsdPathAsCFString ) {
807 size_t devPathLength;
808 strcpy( bsdPath, _PATH_DEV );
809 strcat( bsdPath, "r" );
810 devPathLength = strlen( bsdPath );
811 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
812 kernResult = KERN_SUCCESS;
814 CFRelease( bsdPathAsCFString );
816 IOObjectRelease( nextMedia );
819 return kernResult;
822 #endif
824 static int hdev_probe_device(const char *filename)
826 struct stat st;
828 /* allow a dedicated CD-ROM driver to match with a higher priority */
829 if (strstart(filename, "/dev/cdrom", NULL))
830 return 50;
832 if (stat(filename, &st) >= 0 &&
833 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
834 return 100;
837 return 0;
840 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
842 BDRVRawState *s = bs->opaque;
844 #ifdef CONFIG_COCOA
845 if (strstart(filename, "/dev/cdrom", NULL)) {
846 kern_return_t kernResult;
847 io_iterator_t mediaIterator;
848 char bsdPath[ MAXPATHLEN ];
849 int fd;
851 kernResult = FindEjectableCDMedia( &mediaIterator );
852 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
854 if ( bsdPath[ 0 ] != '\0' ) {
855 strcat(bsdPath,"s0");
856 /* some CDs don't have a partition 0 */
857 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
858 if (fd < 0) {
859 bsdPath[strlen(bsdPath)-1] = '1';
860 } else {
861 close(fd);
863 filename = bsdPath;
866 if ( mediaIterator )
867 IOObjectRelease( mediaIterator );
869 #endif
871 s->type = FTYPE_FILE;
872 #if defined(__linux__)
873 if (strstart(filename, "/dev/sg", NULL)) {
874 bs->sg = 1;
876 #endif
878 return raw_open_common(bs, filename, flags, 0);
881 #if defined(__linux__)
882 /* Note: we do not have a reliable method to detect if the floppy is
883 present. The current method is to try to open the floppy at every
884 I/O and to keep it opened during a few hundreds of ms. */
885 static int fd_open(BlockDriverState *bs)
887 BDRVRawState *s = bs->opaque;
888 int last_media_present;
890 if (s->type != FTYPE_FD)
891 return 0;
892 last_media_present = (s->fd >= 0);
893 if (s->fd >= 0 &&
894 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
895 close(s->fd);
896 s->fd = -1;
897 #ifdef DEBUG_FLOPPY
898 printf("Floppy closed\n");
899 #endif
901 if (s->fd < 0) {
902 if (s->fd_got_error &&
903 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
904 #ifdef DEBUG_FLOPPY
905 printf("No floppy (open delayed)\n");
906 #endif
907 return -EIO;
909 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
910 if (s->fd < 0) {
911 s->fd_error_time = qemu_get_clock(rt_clock);
912 s->fd_got_error = 1;
913 if (last_media_present)
914 s->fd_media_changed = 1;
915 #ifdef DEBUG_FLOPPY
916 printf("No floppy\n");
917 #endif
918 return -EIO;
920 #ifdef DEBUG_FLOPPY
921 printf("Floppy opened\n");
922 #endif
924 if (!last_media_present)
925 s->fd_media_changed = 1;
926 s->fd_open_time = qemu_get_clock(rt_clock);
927 s->fd_got_error = 0;
928 return 0;
931 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
933 BDRVRawState *s = bs->opaque;
935 return ioctl(s->fd, req, buf);
938 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
939 unsigned long int req, void *buf,
940 BlockDriverCompletionFunc *cb, void *opaque)
942 BDRVRawState *s = bs->opaque;
944 if (fd_open(bs) < 0)
945 return NULL;
946 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
949 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
950 static int fd_open(BlockDriverState *bs)
952 BDRVRawState *s = bs->opaque;
954 /* this is just to ensure s->fd is sane (its called by io ops) */
955 if (s->fd >= 0)
956 return 0;
957 return -EIO;
959 #else /* !linux && !FreeBSD */
961 static int fd_open(BlockDriverState *bs)
963 return 0;
966 #endif /* !linux && !FreeBSD */
968 static int hdev_create(const char *filename, QEMUOptionParameter *options)
970 int fd;
971 int ret = 0;
972 struct stat stat_buf;
973 int64_t total_size = 0;
975 /* Read out options */
976 while (options && options->name) {
977 if (!strcmp(options->name, "size")) {
978 total_size = options->value.n / BDRV_SECTOR_SIZE;
980 options++;
983 fd = open(filename, O_WRONLY | O_BINARY);
984 if (fd < 0)
985 return -errno;
987 if (fstat(fd, &stat_buf) < 0)
988 ret = -errno;
989 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
990 ret = -ENODEV;
991 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
992 ret = -ENOSPC;
994 close(fd);
995 return ret;
998 static int hdev_has_zero_init(BlockDriverState *bs)
1000 return 0;
1003 static BlockDriver bdrv_host_device = {
1004 .format_name = "host_device",
1005 .protocol_name = "host_device",
1006 .instance_size = sizeof(BDRVRawState),
1007 .bdrv_probe_device = hdev_probe_device,
1008 .bdrv_file_open = hdev_open,
1009 .bdrv_close = raw_close,
1010 .bdrv_create = hdev_create,
1011 .create_options = raw_create_options,
1012 .bdrv_has_zero_init = hdev_has_zero_init,
1013 .bdrv_flush = raw_flush,
1015 .bdrv_aio_readv = raw_aio_readv,
1016 .bdrv_aio_writev = raw_aio_writev,
1017 .bdrv_aio_flush = raw_aio_flush,
1019 .bdrv_read = raw_read,
1020 .bdrv_write = raw_write,
1021 .bdrv_getlength = raw_getlength,
1023 /* generic scsi device */
1024 #ifdef __linux__
1025 .bdrv_ioctl = hdev_ioctl,
1026 .bdrv_aio_ioctl = hdev_aio_ioctl,
1027 #endif
1030 #ifdef __linux__
1031 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1033 BDRVRawState *s = bs->opaque;
1034 int ret;
1036 s->type = FTYPE_FD;
1038 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1039 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1040 if (ret)
1041 return ret;
1043 /* close fd so that we can reopen it as needed */
1044 close(s->fd);
1045 s->fd = -1;
1046 s->fd_media_changed = 1;
1048 return 0;
1051 static int floppy_probe_device(const char *filename)
1053 int fd, ret;
1054 int prio = 0;
1055 struct floppy_struct fdparam;
1057 if (strstart(filename, "/dev/fd", NULL))
1058 prio = 50;
1060 fd = open(filename, O_RDONLY | O_NONBLOCK);
1061 if (fd < 0) {
1062 goto out;
1065 /* Attempt to detect via a floppy specific ioctl */
1066 ret = ioctl(fd, FDGETPRM, &fdparam);
1067 if (ret >= 0)
1068 prio = 100;
1070 close(fd);
1071 out:
1072 return prio;
1076 static int floppy_is_inserted(BlockDriverState *bs)
1078 return fd_open(bs) >= 0;
1081 static int floppy_media_changed(BlockDriverState *bs)
1083 BDRVRawState *s = bs->opaque;
1084 int ret;
1087 * XXX: we do not have a true media changed indication.
1088 * It does not work if the floppy is changed without trying to read it.
1090 fd_open(bs);
1091 ret = s->fd_media_changed;
1092 s->fd_media_changed = 0;
1093 #ifdef DEBUG_FLOPPY
1094 printf("Floppy changed=%d\n", ret);
1095 #endif
1096 return ret;
1099 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1101 BDRVRawState *s = bs->opaque;
1102 int fd;
1104 if (s->fd >= 0) {
1105 close(s->fd);
1106 s->fd = -1;
1108 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1109 if (fd >= 0) {
1110 if (ioctl(fd, FDEJECT, 0) < 0)
1111 perror("FDEJECT");
1112 close(fd);
1115 return 0;
1118 static BlockDriver bdrv_host_floppy = {
1119 .format_name = "host_floppy",
1120 .protocol_name = "host_floppy",
1121 .instance_size = sizeof(BDRVRawState),
1122 .bdrv_probe_device = floppy_probe_device,
1123 .bdrv_file_open = floppy_open,
1124 .bdrv_close = raw_close,
1125 .bdrv_create = hdev_create,
1126 .create_options = raw_create_options,
1127 .bdrv_has_zero_init = hdev_has_zero_init,
1128 .bdrv_flush = raw_flush,
1130 .bdrv_aio_readv = raw_aio_readv,
1131 .bdrv_aio_writev = raw_aio_writev,
1132 .bdrv_aio_flush = raw_aio_flush,
1134 .bdrv_read = raw_read,
1135 .bdrv_write = raw_write,
1136 .bdrv_getlength = raw_getlength,
1138 /* removable device support */
1139 .bdrv_is_inserted = floppy_is_inserted,
1140 .bdrv_media_changed = floppy_media_changed,
1141 .bdrv_eject = floppy_eject,
1144 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1146 BDRVRawState *s = bs->opaque;
1148 s->type = FTYPE_CD;
1150 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1151 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1154 static int cdrom_probe_device(const char *filename)
1156 int fd, ret;
1157 int prio = 0;
1159 if (strstart(filename, "/dev/cd", NULL))
1160 prio = 50;
1162 fd = open(filename, O_RDONLY | O_NONBLOCK);
1163 if (fd < 0) {
1164 goto out;
1167 /* Attempt to detect via a CDROM specific ioctl */
1168 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1169 if (ret >= 0)
1170 prio = 100;
1172 close(fd);
1173 out:
1174 return prio;
1177 static int cdrom_is_inserted(BlockDriverState *bs)
1179 BDRVRawState *s = bs->opaque;
1180 int ret;
1182 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1183 if (ret == CDS_DISC_OK)
1184 return 1;
1185 return 0;
1188 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1190 BDRVRawState *s = bs->opaque;
1192 if (eject_flag) {
1193 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1194 perror("CDROMEJECT");
1195 } else {
1196 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1197 perror("CDROMEJECT");
1200 return 0;
1203 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1205 BDRVRawState *s = bs->opaque;
1207 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1209 * Note: an error can happen if the distribution automatically
1210 * mounts the CD-ROM
1212 /* perror("CDROM_LOCKDOOR"); */
1215 return 0;
1218 static BlockDriver bdrv_host_cdrom = {
1219 .format_name = "host_cdrom",
1220 .protocol_name = "host_cdrom",
1221 .instance_size = sizeof(BDRVRawState),
1222 .bdrv_probe_device = cdrom_probe_device,
1223 .bdrv_file_open = cdrom_open,
1224 .bdrv_close = raw_close,
1225 .bdrv_create = hdev_create,
1226 .create_options = raw_create_options,
1227 .bdrv_has_zero_init = hdev_has_zero_init,
1228 .bdrv_flush = raw_flush,
1230 .bdrv_aio_readv = raw_aio_readv,
1231 .bdrv_aio_writev = raw_aio_writev,
1232 .bdrv_aio_flush = raw_aio_flush,
1234 .bdrv_read = raw_read,
1235 .bdrv_write = raw_write,
1236 .bdrv_getlength = raw_getlength,
1238 /* removable device support */
1239 .bdrv_is_inserted = cdrom_is_inserted,
1240 .bdrv_eject = cdrom_eject,
1241 .bdrv_set_locked = cdrom_set_locked,
1243 /* generic scsi device */
1244 .bdrv_ioctl = hdev_ioctl,
1245 .bdrv_aio_ioctl = hdev_aio_ioctl,
1247 #endif /* __linux__ */
1249 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1250 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1252 BDRVRawState *s = bs->opaque;
1253 int ret;
1255 s->type = FTYPE_CD;
1257 ret = raw_open_common(bs, filename, flags, 0);
1258 if (ret)
1259 return ret;
1261 /* make sure the door isnt locked at this time */
1262 ioctl(s->fd, CDIOCALLOW);
1263 return 0;
1266 static int cdrom_probe_device(const char *filename)
1268 if (strstart(filename, "/dev/cd", NULL) ||
1269 strstart(filename, "/dev/acd", NULL))
1270 return 100;
1271 return 0;
1274 static int cdrom_reopen(BlockDriverState *bs)
1276 BDRVRawState *s = bs->opaque;
1277 int fd;
1280 * Force reread of possibly changed/newly loaded disc,
1281 * FreeBSD seems to not notice sometimes...
1283 if (s->fd >= 0)
1284 close(s->fd);
1285 fd = open(bs->filename, s->open_flags, 0644);
1286 if (fd < 0) {
1287 s->fd = -1;
1288 return -EIO;
1290 s->fd = fd;
1292 /* make sure the door isnt locked at this time */
1293 ioctl(s->fd, CDIOCALLOW);
1294 return 0;
1297 static int cdrom_is_inserted(BlockDriverState *bs)
1299 return raw_getlength(bs) > 0;
1302 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1304 BDRVRawState *s = bs->opaque;
1306 if (s->fd < 0)
1307 return -ENOTSUP;
1309 (void) ioctl(s->fd, CDIOCALLOW);
1311 if (eject_flag) {
1312 if (ioctl(s->fd, CDIOCEJECT) < 0)
1313 perror("CDIOCEJECT");
1314 } else {
1315 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1316 perror("CDIOCCLOSE");
1319 if (cdrom_reopen(bs) < 0)
1320 return -ENOTSUP;
1321 return 0;
1324 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1326 BDRVRawState *s = bs->opaque;
1328 if (s->fd < 0)
1329 return -ENOTSUP;
1330 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1332 * Note: an error can happen if the distribution automatically
1333 * mounts the CD-ROM
1335 /* perror("CDROM_LOCKDOOR"); */
1338 return 0;
1341 static BlockDriver bdrv_host_cdrom = {
1342 .format_name = "host_cdrom",
1343 .protocol_name = "host_cdrom",
1344 .instance_size = sizeof(BDRVRawState),
1345 .bdrv_probe_device = cdrom_probe_device,
1346 .bdrv_file_open = cdrom_open,
1347 .bdrv_close = raw_close,
1348 .bdrv_create = hdev_create,
1349 .create_options = raw_create_options,
1350 .bdrv_has_zero_init = hdev_has_zero_init,
1351 .bdrv_flush = raw_flush,
1353 .bdrv_aio_readv = raw_aio_readv,
1354 .bdrv_aio_writev = raw_aio_writev,
1355 .bdrv_aio_flush = raw_aio_flush,
1357 .bdrv_read = raw_read,
1358 .bdrv_write = raw_write,
1359 .bdrv_getlength = raw_getlength,
1361 /* removable device support */
1362 .bdrv_is_inserted = cdrom_is_inserted,
1363 .bdrv_eject = cdrom_eject,
1364 .bdrv_set_locked = cdrom_set_locked,
1366 #endif /* __FreeBSD__ */
1368 static void bdrv_file_init(void)
1371 * Register all the drivers. Note that order is important, the driver
1372 * registered last will get probed first.
1374 bdrv_register(&bdrv_file);
1375 bdrv_register(&bdrv_host_device);
1376 #ifdef __linux__
1377 bdrv_register(&bdrv_host_floppy);
1378 bdrv_register(&bdrv_host_cdrom);
1379 #endif
1380 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1381 bdrv_register(&bdrv_host_cdrom);
1382 #endif
1385 block_init(bdrv_file_init);