qemu-kvm: Process exit requests in kvm loop
[qemu-kvm/amd-iommu.git] / block / raw-posix.c
blob1515ca90203d053d692171500e5584202cb3777c
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 u_int32_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 goto label__raw_read__success;
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 ret = count;
255 goto label__raw_read__success;
259 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
260 "] read failed %d : %d = %s\n",
261 s->fd, bs->filename, offset, buf, count,
262 bs->total_sectors, ret, errno, strerror(errno));
264 /* Try harder for CDrom. */
265 if (bs->type == BDRV_TYPE_CDROM) {
266 ret = pread(s->fd, buf, count, offset);
267 if (ret == count)
268 goto label__raw_read__success;
269 ret = pread(s->fd, buf, count, offset);
270 if (ret == count)
271 goto label__raw_read__success;
273 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
274 "] retry read failed %d : %d = %s\n",
275 s->fd, bs->filename, offset, buf, count,
276 bs->total_sectors, ret, errno, strerror(errno));
279 label__raw_read__success:
281 return (ret < 0) ? -errno : ret;
285 * offset and count are in bytes, but must be multiples of 512 for files
286 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
288 * This function may be called without alignment if the caller ensures
289 * that O_DIRECT is not in effect.
291 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
292 const uint8_t *buf, int count)
294 BDRVRawState *s = bs->opaque;
295 int ret;
297 ret = fd_open(bs);
298 if (ret < 0)
299 return -errno;
301 ret = pwrite(s->fd, buf, count, offset);
302 if (ret == count)
303 goto label__raw_write__success;
305 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
306 "] write failed %d : %d = %s\n",
307 s->fd, bs->filename, offset, buf, count,
308 bs->total_sectors, ret, errno, strerror(errno));
310 label__raw_write__success:
312 return (ret < 0) ? -errno : ret;
317 * offset and count are in bytes and possibly not aligned. For files opened
318 * with O_DIRECT, necessary alignments are ensured before calling
319 * raw_pread_aligned to do the actual read.
321 static int raw_pread(BlockDriverState *bs, int64_t offset,
322 uint8_t *buf, int count)
324 BDRVRawState *s = bs->opaque;
325 int size, ret, shift, sum;
327 sum = 0;
329 if (s->aligned_buf != NULL) {
331 if (offset & 0x1ff) {
332 /* align offset on a 512 bytes boundary */
334 shift = offset & 0x1ff;
335 size = (shift + count + 0x1ff) & ~0x1ff;
336 if (size > ALIGNED_BUFFER_SIZE)
337 size = ALIGNED_BUFFER_SIZE;
338 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
339 if (ret < 0)
340 return ret;
342 size = 512 - shift;
343 if (size > count)
344 size = count;
345 memcpy(buf, s->aligned_buf + shift, size);
347 buf += size;
348 offset += size;
349 count -= size;
350 sum += size;
352 if (count == 0)
353 return sum;
355 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
357 /* read on aligned buffer */
359 while (count) {
361 size = (count + 0x1ff) & ~0x1ff;
362 if (size > ALIGNED_BUFFER_SIZE)
363 size = ALIGNED_BUFFER_SIZE;
365 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
366 if (ret < 0) {
367 return ret;
368 } else if (ret == 0) {
369 fprintf(stderr, "raw_pread: read beyond end of file\n");
370 abort();
373 size = ret;
374 if (size > count)
375 size = count;
377 memcpy(buf, s->aligned_buf, size);
379 buf += size;
380 offset += size;
381 count -= size;
382 sum += size;
385 return sum;
389 return raw_pread_aligned(bs, offset, buf, count) + sum;
392 static int raw_read(BlockDriverState *bs, int64_t sector_num,
393 uint8_t *buf, int nb_sectors)
395 int ret;
397 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
398 if (ret == (nb_sectors * 512))
399 ret = 0;
400 return ret;
404 * offset and count are in bytes and possibly not aligned. For files opened
405 * with O_DIRECT, necessary alignments are ensured before calling
406 * raw_pwrite_aligned to do the actual write.
408 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
409 const uint8_t *buf, int count)
411 BDRVRawState *s = bs->opaque;
412 int size, ret, shift, sum;
414 sum = 0;
416 if (s->aligned_buf != NULL) {
418 if (offset & 0x1ff) {
419 /* align offset on a 512 bytes boundary */
420 shift = offset & 0x1ff;
421 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
422 if (ret < 0)
423 return ret;
425 size = 512 - shift;
426 if (size > count)
427 size = count;
428 memcpy(s->aligned_buf + shift, buf, size);
430 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
431 if (ret < 0)
432 return ret;
434 buf += size;
435 offset += size;
436 count -= size;
437 sum += size;
439 if (count == 0)
440 return sum;
442 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
444 while ((size = (count & ~0x1ff)) != 0) {
446 if (size > ALIGNED_BUFFER_SIZE)
447 size = ALIGNED_BUFFER_SIZE;
449 memcpy(s->aligned_buf, buf, size);
451 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
452 if (ret < 0)
453 return ret;
455 buf += ret;
456 offset += ret;
457 count -= ret;
458 sum += ret;
460 /* here, count < 512 because (count & ~0x1ff) == 0 */
461 if (count) {
462 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
463 if (ret < 0)
464 return ret;
465 memcpy(s->aligned_buf, buf, count);
467 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
468 if (ret < 0)
469 return ret;
470 if (count < ret)
471 ret = count;
473 sum += ret;
475 return sum;
478 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
481 static int raw_write(BlockDriverState *bs, int64_t sector_num,
482 const uint8_t *buf, int nb_sectors)
484 int ret;
485 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
486 if (ret == (nb_sectors * 512))
487 ret = 0;
488 return ret;
492 * Check if all memory in this vector is sector aligned.
494 static int qiov_is_aligned(QEMUIOVector *qiov)
496 int i;
498 for (i = 0; i < qiov->niov; i++) {
499 if ((uintptr_t) qiov->iov[i].iov_base % 512) {
500 return 0;
504 return 1;
507 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
508 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
509 BlockDriverCompletionFunc *cb, void *opaque, int type)
511 BDRVRawState *s = bs->opaque;
513 if (fd_open(bs) < 0)
514 return NULL;
517 * If O_DIRECT is used the buffer needs to be aligned on a sector
518 * boundary. Check if this is the case or telll the low-level
519 * driver that it needs to copy the buffer.
521 if (s->aligned_buf) {
522 if (!qiov_is_aligned(qiov)) {
523 type |= QEMU_AIO_MISALIGNED;
524 #ifdef CONFIG_LINUX_AIO
525 } else if (s->use_aio) {
526 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
527 nb_sectors, cb, opaque, type);
528 #endif
532 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
533 cb, opaque, type);
536 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
537 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
538 BlockDriverCompletionFunc *cb, void *opaque)
540 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
541 cb, opaque, QEMU_AIO_READ);
544 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
545 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
546 BlockDriverCompletionFunc *cb, void *opaque)
548 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
549 cb, opaque, QEMU_AIO_WRITE);
552 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
553 BlockDriverCompletionFunc *cb, void *opaque)
555 BDRVRawState *s = bs->opaque;
557 if (fd_open(bs) < 0)
558 return NULL;
560 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
563 static void raw_close(BlockDriverState *bs)
565 BDRVRawState *s = bs->opaque;
566 if (s->fd >= 0) {
567 close(s->fd);
568 s->fd = -1;
569 if (s->aligned_buf != NULL)
570 qemu_vfree(s->aligned_buf);
574 static int raw_truncate(BlockDriverState *bs, int64_t offset)
576 BDRVRawState *s = bs->opaque;
577 if (s->type != FTYPE_FILE)
578 return -ENOTSUP;
579 if (ftruncate(s->fd, offset) < 0)
580 return -errno;
581 return 0;
584 #ifdef __OpenBSD__
585 static int64_t raw_getlength(BlockDriverState *bs)
587 BDRVRawState *s = bs->opaque;
588 int fd = s->fd;
589 struct stat st;
591 if (fstat(fd, &st))
592 return -1;
593 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
594 struct disklabel dl;
596 if (ioctl(fd, DIOCGDINFO, &dl))
597 return -1;
598 return (uint64_t)dl.d_secsize *
599 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
600 } else
601 return st.st_size;
603 #elif defined(__sun__)
604 static int64_t raw_getlength(BlockDriverState *bs)
606 BDRVRawState *s = bs->opaque;
607 struct dk_minfo minfo;
608 int ret;
610 ret = fd_open(bs);
611 if (ret < 0) {
612 return ret;
616 * Use the DKIOCGMEDIAINFO ioctl to read the size.
618 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
619 if (ret != -1) {
620 return minfo.dki_lbsize * minfo.dki_capacity;
624 * There are reports that lseek on some devices fails, but
625 * irc discussion said that contingency on contingency was overkill.
627 return lseek(s->fd, 0, SEEK_END);
629 #elif defined(CONFIG_BSD)
630 static int64_t raw_getlength(BlockDriverState *bs)
632 BDRVRawState *s = bs->opaque;
633 int fd = s->fd;
634 int64_t size;
635 struct stat sb;
636 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
637 int reopened = 0;
638 #endif
639 int ret;
641 ret = fd_open(bs);
642 if (ret < 0)
643 return ret;
645 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
646 again:
647 #endif
648 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
649 #ifdef DIOCGMEDIASIZE
650 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
651 #elif defined(DIOCGPART)
653 struct partinfo pi;
654 if (ioctl(fd, DIOCGPART, &pi) == 0)
655 size = pi.media_size;
656 else
657 size = 0;
659 if (size == 0)
660 #endif
661 #ifdef CONFIG_COCOA
662 size = LONG_LONG_MAX;
663 #else
664 size = lseek(fd, 0LL, SEEK_END);
665 #endif
666 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
667 switch(s->type) {
668 case FTYPE_CD:
669 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
670 if (size == 2048LL * (unsigned)-1)
671 size = 0;
672 /* XXX no disc? maybe we need to reopen... */
673 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
674 reopened = 1;
675 goto again;
678 #endif
679 } else {
680 size = lseek(fd, 0, SEEK_END);
682 return size;
684 #else
685 static int64_t raw_getlength(BlockDriverState *bs)
687 BDRVRawState *s = bs->opaque;
688 int ret;
690 ret = fd_open(bs);
691 if (ret < 0) {
692 return ret;
695 return lseek(s->fd, 0, SEEK_END);
697 #endif
699 static int raw_create(const char *filename, QEMUOptionParameter *options)
701 int fd;
702 int result = 0;
703 int64_t total_size = 0;
705 /* Read out options */
706 while (options && options->name) {
707 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
708 total_size = options->value.n / 512;
710 options++;
713 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
714 0644);
715 if (fd < 0) {
716 result = -errno;
717 } else {
718 if (ftruncate(fd, total_size * 512) != 0) {
719 result = -errno;
721 if (close(fd) != 0) {
722 result = -errno;
725 return result;
728 static void raw_flush(BlockDriverState *bs)
730 BDRVRawState *s = bs->opaque;
731 qemu_fdatasync(s->fd);
735 static QEMUOptionParameter raw_create_options[] = {
737 .name = BLOCK_OPT_SIZE,
738 .type = OPT_SIZE,
739 .help = "Virtual disk size"
741 { NULL }
744 static BlockDriver bdrv_file = {
745 .format_name = "file",
746 .protocol_name = "file",
747 .instance_size = sizeof(BDRVRawState),
748 .bdrv_probe = NULL, /* no probe for protocols */
749 .bdrv_file_open = raw_open,
750 .bdrv_read = raw_read,
751 .bdrv_write = raw_write,
752 .bdrv_close = raw_close,
753 .bdrv_create = raw_create,
754 .bdrv_flush = raw_flush,
756 .bdrv_aio_readv = raw_aio_readv,
757 .bdrv_aio_writev = raw_aio_writev,
758 .bdrv_aio_flush = raw_aio_flush,
760 .bdrv_truncate = raw_truncate,
761 .bdrv_getlength = raw_getlength,
763 .create_options = raw_create_options,
766 /***********************************************/
767 /* host device */
769 #ifdef CONFIG_COCOA
770 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
771 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
773 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
775 kern_return_t kernResult;
776 mach_port_t masterPort;
777 CFMutableDictionaryRef classesToMatch;
779 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
780 if ( KERN_SUCCESS != kernResult ) {
781 printf( "IOMasterPort returned %d\n", kernResult );
784 classesToMatch = IOServiceMatching( kIOCDMediaClass );
785 if ( classesToMatch == NULL ) {
786 printf( "IOServiceMatching returned a NULL dictionary.\n" );
787 } else {
788 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
790 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
791 if ( KERN_SUCCESS != kernResult )
793 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
796 return kernResult;
799 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
801 io_object_t nextMedia;
802 kern_return_t kernResult = KERN_FAILURE;
803 *bsdPath = '\0';
804 nextMedia = IOIteratorNext( mediaIterator );
805 if ( nextMedia )
807 CFTypeRef bsdPathAsCFString;
808 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
809 if ( bsdPathAsCFString ) {
810 size_t devPathLength;
811 strcpy( bsdPath, _PATH_DEV );
812 strcat( bsdPath, "r" );
813 devPathLength = strlen( bsdPath );
814 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
815 kernResult = KERN_SUCCESS;
817 CFRelease( bsdPathAsCFString );
819 IOObjectRelease( nextMedia );
822 return kernResult;
825 #endif
827 static int hdev_probe_device(const char *filename)
829 struct stat st;
831 /* allow a dedicated CD-ROM driver to match with a higher priority */
832 if (strstart(filename, "/dev/cdrom", NULL))
833 return 50;
835 if (stat(filename, &st) >= 0 &&
836 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
837 return 100;
840 return 0;
843 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
845 BDRVRawState *s = bs->opaque;
847 #ifdef CONFIG_COCOA
848 if (strstart(filename, "/dev/cdrom", NULL)) {
849 kern_return_t kernResult;
850 io_iterator_t mediaIterator;
851 char bsdPath[ MAXPATHLEN ];
852 int fd;
854 kernResult = FindEjectableCDMedia( &mediaIterator );
855 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
857 if ( bsdPath[ 0 ] != '\0' ) {
858 strcat(bsdPath,"s0");
859 /* some CDs don't have a partition 0 */
860 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
861 if (fd < 0) {
862 bsdPath[strlen(bsdPath)-1] = '1';
863 } else {
864 close(fd);
866 filename = bsdPath;
869 if ( mediaIterator )
870 IOObjectRelease( mediaIterator );
872 #endif
874 s->type = FTYPE_FILE;
875 #if defined(__linux__)
876 if (strstart(filename, "/dev/sg", NULL)) {
877 bs->sg = 1;
879 #endif
881 return raw_open_common(bs, filename, flags, 0);
884 #if defined(__linux__)
885 /* Note: we do not have a reliable method to detect if the floppy is
886 present. The current method is to try to open the floppy at every
887 I/O and to keep it opened during a few hundreds of ms. */
888 static int fd_open(BlockDriverState *bs)
890 BDRVRawState *s = bs->opaque;
891 int last_media_present;
893 if (s->type != FTYPE_FD)
894 return 0;
895 last_media_present = (s->fd >= 0);
896 if (s->fd >= 0 &&
897 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
898 close(s->fd);
899 s->fd = -1;
900 #ifdef DEBUG_FLOPPY
901 printf("Floppy closed\n");
902 #endif
904 if (s->fd < 0) {
905 if (s->fd_got_error &&
906 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
907 #ifdef DEBUG_FLOPPY
908 printf("No floppy (open delayed)\n");
909 #endif
910 return -EIO;
912 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
913 if (s->fd < 0) {
914 s->fd_error_time = qemu_get_clock(rt_clock);
915 s->fd_got_error = 1;
916 if (last_media_present)
917 s->fd_media_changed = 1;
918 #ifdef DEBUG_FLOPPY
919 printf("No floppy\n");
920 #endif
921 return -EIO;
923 #ifdef DEBUG_FLOPPY
924 printf("Floppy opened\n");
925 #endif
927 if (!last_media_present)
928 s->fd_media_changed = 1;
929 s->fd_open_time = qemu_get_clock(rt_clock);
930 s->fd_got_error = 0;
931 return 0;
934 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
936 BDRVRawState *s = bs->opaque;
938 return ioctl(s->fd, req, buf);
941 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
942 unsigned long int req, void *buf,
943 BlockDriverCompletionFunc *cb, void *opaque)
945 BDRVRawState *s = bs->opaque;
947 if (fd_open(bs) < 0)
948 return NULL;
949 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
952 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
953 static int fd_open(BlockDriverState *bs)
955 BDRVRawState *s = bs->opaque;
957 /* this is just to ensure s->fd is sane (its called by io ops) */
958 if (s->fd >= 0)
959 return 0;
960 return -EIO;
962 #else /* !linux && !FreeBSD */
964 static int fd_open(BlockDriverState *bs)
966 return 0;
969 #endif /* !linux && !FreeBSD */
971 static int hdev_create(const char *filename, QEMUOptionParameter *options)
973 int fd;
974 int ret = 0;
975 struct stat stat_buf;
976 int64_t total_size = 0;
978 /* Read out options */
979 while (options && options->name) {
980 if (!strcmp(options->name, "size")) {
981 total_size = options->value.n / 512;
983 options++;
986 fd = open(filename, O_WRONLY | O_BINARY);
987 if (fd < 0)
988 return -errno;
990 if (fstat(fd, &stat_buf) < 0)
991 ret = -errno;
992 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
993 ret = -ENODEV;
994 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
995 ret = -ENOSPC;
997 close(fd);
998 return ret;
1001 static BlockDriver bdrv_host_device = {
1002 .format_name = "host_device",
1003 .protocol_name = "host_device",
1004 .instance_size = sizeof(BDRVRawState),
1005 .bdrv_probe_device = hdev_probe_device,
1006 .bdrv_file_open = hdev_open,
1007 .bdrv_close = raw_close,
1008 .bdrv_create = hdev_create,
1009 .create_options = raw_create_options,
1010 .no_zero_init = 1,
1011 .bdrv_flush = raw_flush,
1013 .bdrv_aio_readv = raw_aio_readv,
1014 .bdrv_aio_writev = raw_aio_writev,
1015 .bdrv_aio_flush = raw_aio_flush,
1017 .bdrv_read = raw_read,
1018 .bdrv_write = raw_write,
1019 .bdrv_getlength = raw_getlength,
1021 /* generic scsi device */
1022 #ifdef __linux__
1023 .bdrv_ioctl = hdev_ioctl,
1024 .bdrv_aio_ioctl = hdev_aio_ioctl,
1025 #endif
1028 #ifdef __linux__
1029 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1031 BDRVRawState *s = bs->opaque;
1032 int ret;
1034 s->type = FTYPE_FD;
1036 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1037 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1038 if (ret)
1039 return ret;
1041 /* close fd so that we can reopen it as needed */
1042 close(s->fd);
1043 s->fd = -1;
1044 s->fd_media_changed = 1;
1046 return 0;
1049 static int floppy_probe_device(const char *filename)
1051 int fd, ret;
1052 int prio = 0;
1053 struct floppy_struct fdparam;
1055 if (strstart(filename, "/dev/fd", NULL))
1056 prio = 50;
1058 fd = open(filename, O_RDONLY | O_NONBLOCK);
1059 if (fd < 0) {
1060 goto out;
1063 /* Attempt to detect via a floppy specific ioctl */
1064 ret = ioctl(fd, FDGETPRM, &fdparam);
1065 if (ret >= 0)
1066 prio = 100;
1068 close(fd);
1069 out:
1070 return prio;
1074 static int floppy_is_inserted(BlockDriverState *bs)
1076 return fd_open(bs) >= 0;
1079 static int floppy_media_changed(BlockDriverState *bs)
1081 BDRVRawState *s = bs->opaque;
1082 int ret;
1085 * XXX: we do not have a true media changed indication.
1086 * It does not work if the floppy is changed without trying to read it.
1088 fd_open(bs);
1089 ret = s->fd_media_changed;
1090 s->fd_media_changed = 0;
1091 #ifdef DEBUG_FLOPPY
1092 printf("Floppy changed=%d\n", ret);
1093 #endif
1094 return ret;
1097 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1099 BDRVRawState *s = bs->opaque;
1100 int fd;
1102 if (s->fd >= 0) {
1103 close(s->fd);
1104 s->fd = -1;
1106 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1107 if (fd >= 0) {
1108 if (ioctl(fd, FDEJECT, 0) < 0)
1109 perror("FDEJECT");
1110 close(fd);
1113 return 0;
1116 static BlockDriver bdrv_host_floppy = {
1117 .format_name = "host_floppy",
1118 .protocol_name = "host_floppy",
1119 .instance_size = sizeof(BDRVRawState),
1120 .bdrv_probe_device = floppy_probe_device,
1121 .bdrv_file_open = floppy_open,
1122 .bdrv_close = raw_close,
1123 .bdrv_create = hdev_create,
1124 .create_options = raw_create_options,
1125 .no_zero_init = 1,
1126 .bdrv_flush = raw_flush,
1128 .bdrv_aio_readv = raw_aio_readv,
1129 .bdrv_aio_writev = raw_aio_writev,
1130 .bdrv_aio_flush = raw_aio_flush,
1132 .bdrv_read = raw_read,
1133 .bdrv_write = raw_write,
1134 .bdrv_getlength = raw_getlength,
1136 /* removable device support */
1137 .bdrv_is_inserted = floppy_is_inserted,
1138 .bdrv_media_changed = floppy_media_changed,
1139 .bdrv_eject = floppy_eject,
1142 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1144 BDRVRawState *s = bs->opaque;
1146 s->type = FTYPE_CD;
1148 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1149 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1152 static int cdrom_probe_device(const char *filename)
1154 int fd, ret;
1155 int prio = 0;
1157 if (strstart(filename, "/dev/cd", NULL))
1158 prio = 50;
1160 fd = open(filename, O_RDONLY | O_NONBLOCK);
1161 if (fd < 0) {
1162 goto out;
1165 /* Attempt to detect via a CDROM specific ioctl */
1166 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1167 if (ret >= 0)
1168 prio = 100;
1170 close(fd);
1171 out:
1172 return prio;
1175 static int cdrom_is_inserted(BlockDriverState *bs)
1177 BDRVRawState *s = bs->opaque;
1178 int ret;
1180 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1181 if (ret == CDS_DISC_OK)
1182 return 1;
1183 return 0;
1186 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1188 BDRVRawState *s = bs->opaque;
1190 if (eject_flag) {
1191 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1192 perror("CDROMEJECT");
1193 } else {
1194 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1195 perror("CDROMEJECT");
1198 return 0;
1201 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1203 BDRVRawState *s = bs->opaque;
1205 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1207 * Note: an error can happen if the distribution automatically
1208 * mounts the CD-ROM
1210 /* perror("CDROM_LOCKDOOR"); */
1213 return 0;
1216 static BlockDriver bdrv_host_cdrom = {
1217 .format_name = "host_cdrom",
1218 .protocol_name = "host_cdrom",
1219 .instance_size = sizeof(BDRVRawState),
1220 .bdrv_probe_device = cdrom_probe_device,
1221 .bdrv_file_open = cdrom_open,
1222 .bdrv_close = raw_close,
1223 .bdrv_create = hdev_create,
1224 .create_options = raw_create_options,
1225 .no_zero_init = 1,
1226 .bdrv_flush = raw_flush,
1228 .bdrv_aio_readv = raw_aio_readv,
1229 .bdrv_aio_writev = raw_aio_writev,
1230 .bdrv_aio_flush = raw_aio_flush,
1232 .bdrv_read = raw_read,
1233 .bdrv_write = raw_write,
1234 .bdrv_getlength = raw_getlength,
1236 /* removable device support */
1237 .bdrv_is_inserted = cdrom_is_inserted,
1238 .bdrv_eject = cdrom_eject,
1239 .bdrv_set_locked = cdrom_set_locked,
1241 /* generic scsi device */
1242 .bdrv_ioctl = hdev_ioctl,
1243 .bdrv_aio_ioctl = hdev_aio_ioctl,
1245 #endif /* __linux__ */
1247 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1248 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1250 BDRVRawState *s = bs->opaque;
1251 int ret;
1253 s->type = FTYPE_CD;
1255 ret = raw_open_common(bs, filename, flags, 0);
1256 if (ret)
1257 return ret;
1259 /* make sure the door isnt locked at this time */
1260 ioctl(s->fd, CDIOCALLOW);
1261 return 0;
1264 static int cdrom_probe_device(const char *filename)
1266 if (strstart(filename, "/dev/cd", NULL) ||
1267 strstart(filename, "/dev/acd", NULL))
1268 return 100;
1269 return 0;
1272 static int cdrom_reopen(BlockDriverState *bs)
1274 BDRVRawState *s = bs->opaque;
1275 int fd;
1278 * Force reread of possibly changed/newly loaded disc,
1279 * FreeBSD seems to not notice sometimes...
1281 if (s->fd >= 0)
1282 close(s->fd);
1283 fd = open(bs->filename, s->open_flags, 0644);
1284 if (fd < 0) {
1285 s->fd = -1;
1286 return -EIO;
1288 s->fd = fd;
1290 /* make sure the door isnt locked at this time */
1291 ioctl(s->fd, CDIOCALLOW);
1292 return 0;
1295 static int cdrom_is_inserted(BlockDriverState *bs)
1297 return raw_getlength(bs) > 0;
1300 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1302 BDRVRawState *s = bs->opaque;
1304 if (s->fd < 0)
1305 return -ENOTSUP;
1307 (void) ioctl(s->fd, CDIOCALLOW);
1309 if (eject_flag) {
1310 if (ioctl(s->fd, CDIOCEJECT) < 0)
1311 perror("CDIOCEJECT");
1312 } else {
1313 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1314 perror("CDIOCCLOSE");
1317 if (cdrom_reopen(bs) < 0)
1318 return -ENOTSUP;
1319 return 0;
1322 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1324 BDRVRawState *s = bs->opaque;
1326 if (s->fd < 0)
1327 return -ENOTSUP;
1328 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1330 * Note: an error can happen if the distribution automatically
1331 * mounts the CD-ROM
1333 /* perror("CDROM_LOCKDOOR"); */
1336 return 0;
1339 static BlockDriver bdrv_host_cdrom = {
1340 .format_name = "host_cdrom",
1341 .protocol_name = "host_cdrom",
1342 .instance_size = sizeof(BDRVRawState),
1343 .bdrv_probe_device = cdrom_probe_device,
1344 .bdrv_file_open = cdrom_open,
1345 .bdrv_close = raw_close,
1346 .bdrv_create = hdev_create,
1347 .create_options = raw_create_options,
1348 .no_zero_init = 1,
1349 .bdrv_flush = raw_flush,
1351 .bdrv_aio_readv = raw_aio_readv,
1352 .bdrv_aio_writev = raw_aio_writev,
1353 .bdrv_aio_flush = raw_aio_flush,
1355 .bdrv_read = raw_read,
1356 .bdrv_write = raw_write,
1357 .bdrv_getlength = raw_getlength,
1359 /* removable device support */
1360 .bdrv_is_inserted = cdrom_is_inserted,
1361 .bdrv_eject = cdrom_eject,
1362 .bdrv_set_locked = cdrom_set_locked,
1364 #endif /* __FreeBSD__ */
1366 static void bdrv_file_init(void)
1369 * Register all the drivers. Note that order is important, the driver
1370 * registered last will get probed first.
1372 bdrv_register(&bdrv_file);
1373 bdrv_register(&bdrv_host_device);
1374 #ifdef __linux__
1375 bdrv_register(&bdrv_host_floppy);
1376 bdrv_register(&bdrv_host_cdrom);
1377 #endif
1378 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1379 bdrv_register(&bdrv_host_cdrom);
1380 #endif
1383 block_init(bdrv_file_init);