device-assignment: Move PCI capabilities to match physical hardware
[qemu-kvm/stefanha.git] / block / raw-posix.c
blobbf8971780e3747efd9a4e40f82b62a7ba10b9e5b
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 <sys/param.h>
54 #include <linux/cdrom.h>
55 #include <linux/fd.h>
56 #endif
57 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
58 #include <signal.h>
59 #include <sys/disk.h>
60 #include <sys/cdio.h>
61 #endif
63 #ifdef __OpenBSD__
64 #include <sys/ioctl.h>
65 #include <sys/disklabel.h>
66 #include <sys/dkio.h>
67 #endif
69 #ifdef __DragonFly__
70 #include <sys/ioctl.h>
71 #include <sys/diskslice.h>
72 #endif
74 //#define DEBUG_FLOPPY
76 //#define DEBUG_BLOCK
77 #if defined(DEBUG_BLOCK)
78 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
79 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
80 #else
81 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
82 #endif
84 /* OS X does not have O_DSYNC */
85 #ifndef O_DSYNC
86 #ifdef O_SYNC
87 #define O_DSYNC O_SYNC
88 #elif defined(O_FSYNC)
89 #define O_DSYNC O_FSYNC
90 #endif
91 #endif
93 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
94 #ifndef O_DIRECT
95 #define O_DIRECT O_DSYNC
96 #endif
98 #define FTYPE_FILE 0
99 #define FTYPE_CD 1
100 #define FTYPE_FD 2
102 /* if the FD is not accessed during that time (in ns), we try to
103 reopen it to see if the disk has been changed */
104 #define FD_OPEN_TIMEOUT (1000000000)
106 #define MAX_BLOCKSIZE 4096
108 typedef struct BDRVRawState {
109 int fd;
110 int type;
111 int open_flags;
112 #if defined(__linux__)
113 /* linux floppy specific */
114 int64_t fd_open_time;
115 int64_t fd_error_time;
116 int fd_got_error;
117 int fd_media_changed;
118 #endif
119 #ifdef CONFIG_LINUX_AIO
120 int use_aio;
121 void *aio_ctx;
122 #endif
123 uint8_t *aligned_buf;
124 unsigned aligned_buf_size;
125 } BDRVRawState;
127 static int fd_open(BlockDriverState *bs);
128 static int64_t raw_getlength(BlockDriverState *bs);
130 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
131 static int cdrom_reopen(BlockDriverState *bs);
132 #endif
134 static int raw_open_common(BlockDriverState *bs, const char *filename,
135 int bdrv_flags, int open_flags)
137 BDRVRawState *s = bs->opaque;
138 int fd, ret;
140 s->open_flags = open_flags | O_BINARY;
141 s->open_flags &= ~O_ACCMODE;
142 if (bdrv_flags & BDRV_O_RDWR) {
143 s->open_flags |= O_RDWR;
144 } else {
145 s->open_flags |= O_RDONLY;
148 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
149 * and O_DIRECT for no caching. */
150 if ((bdrv_flags & BDRV_O_NOCACHE))
151 s->open_flags |= O_DIRECT;
152 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
153 s->open_flags |= O_DSYNC;
155 s->fd = -1;
156 fd = qemu_open(filename, s->open_flags, 0644);
157 if (fd < 0) {
158 ret = -errno;
159 if (ret == -EROFS)
160 ret = -EACCES;
161 return ret;
163 s->fd = fd;
164 s->aligned_buf = NULL;
166 if ((bdrv_flags & BDRV_O_NOCACHE)) {
168 * Allocate a buffer for read/modify/write cycles. Chose the size
169 * pessimistically as we don't know the block size yet.
171 s->aligned_buf_size = 32 * MAX_BLOCKSIZE;
172 s->aligned_buf = qemu_memalign(MAX_BLOCKSIZE, s->aligned_buf_size);
173 if (s->aligned_buf == NULL) {
174 goto out_close;
178 #ifdef CONFIG_LINUX_AIO
179 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
180 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
182 /* We're falling back to POSIX AIO in some cases */
183 paio_init();
185 s->aio_ctx = laio_init();
186 if (!s->aio_ctx) {
187 goto out_free_buf;
189 s->use_aio = 1;
190 } else
191 #endif
193 if (paio_init() < 0) {
194 goto out_free_buf;
196 #ifdef CONFIG_LINUX_AIO
197 s->use_aio = 0;
198 #endif
201 return 0;
203 out_free_buf:
204 qemu_vfree(s->aligned_buf);
205 out_close:
206 close(fd);
207 return -errno;
210 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
212 BDRVRawState *s = bs->opaque;
214 s->type = FTYPE_FILE;
215 return raw_open_common(bs, filename, flags, 0);
218 /* XXX: use host sector size if necessary with:
219 #ifdef DIOCGSECTORSIZE
221 unsigned int sectorsize = 512;
222 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
223 sectorsize > bufsize)
224 bufsize = sectorsize;
226 #endif
227 #ifdef CONFIG_COCOA
228 uint32_t blockSize = 512;
229 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
230 bufsize = blockSize;
232 #endif
236 * offset and count are in bytes, but must be multiples of 512 for files
237 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
239 * This function may be called without alignment if the caller ensures
240 * that O_DIRECT is not in effect.
242 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
243 uint8_t *buf, int count)
245 BDRVRawState *s = bs->opaque;
246 int ret;
248 ret = fd_open(bs);
249 if (ret < 0)
250 return ret;
252 ret = pread(s->fd, buf, count, offset);
253 if (ret == count)
254 return ret;
256 /* Allow reads beyond the end (needed for pwrite) */
257 if ((ret == 0) && bs->growable) {
258 int64_t size = raw_getlength(bs);
259 if (offset >= size) {
260 memset(buf, 0, count);
261 return count;
265 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
266 "] read failed %d : %d = %s\n",
267 s->fd, bs->filename, offset, buf, count,
268 bs->total_sectors, ret, errno, strerror(errno));
270 /* Try harder for CDrom. */
271 if (s->type != FTYPE_FILE) {
272 ret = pread(s->fd, buf, count, offset);
273 if (ret == count)
274 return ret;
275 ret = pread(s->fd, buf, count, offset);
276 if (ret == count)
277 return ret;
279 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
280 "] retry read failed %d : %d = %s\n",
281 s->fd, bs->filename, offset, buf, count,
282 bs->total_sectors, ret, errno, strerror(errno));
285 return (ret < 0) ? -errno : ret;
289 * offset and count are in bytes, but must be multiples of the sector size
290 * for files opened with O_DIRECT. buf must be aligned to sector size bytes
291 * then.
293 * This function may be called without alignment if the caller ensures
294 * that O_DIRECT is not in effect.
296 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
297 const uint8_t *buf, int count)
299 BDRVRawState *s = bs->opaque;
300 int ret;
302 ret = fd_open(bs);
303 if (ret < 0)
304 return -errno;
306 ret = pwrite(s->fd, buf, count, offset);
307 if (ret == count)
308 return ret;
310 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
311 "] write failed %d : %d = %s\n",
312 s->fd, bs->filename, offset, buf, count,
313 bs->total_sectors, ret, errno, strerror(errno));
315 return (ret < 0) ? -errno : ret;
320 * offset and count are in bytes and possibly not aligned. For files opened
321 * with O_DIRECT, necessary alignments are ensured before calling
322 * raw_pread_aligned to do the actual read.
324 static int raw_pread(BlockDriverState *bs, int64_t offset,
325 uint8_t *buf, int count)
327 BDRVRawState *s = bs->opaque;
328 unsigned sector_mask = bs->buffer_alignment - 1;
329 int size, ret, shift, sum;
331 sum = 0;
333 if (s->aligned_buf != NULL) {
335 if (offset & sector_mask) {
336 /* align offset on a sector size bytes boundary */
338 shift = offset & sector_mask;
339 size = (shift + count + sector_mask) & ~sector_mask;
340 if (size > s->aligned_buf_size)
341 size = s->aligned_buf_size;
342 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
343 if (ret < 0)
344 return ret;
346 size = bs->buffer_alignment - shift;
347 if (size > count)
348 size = count;
349 memcpy(buf, s->aligned_buf + shift, size);
351 buf += size;
352 offset += size;
353 count -= size;
354 sum += size;
356 if (count == 0)
357 return sum;
359 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
361 /* read on aligned buffer */
363 while (count) {
365 size = (count + sector_mask) & ~sector_mask;
366 if (size > s->aligned_buf_size)
367 size = s->aligned_buf_size;
369 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
370 if (ret < 0) {
371 return ret;
372 } else if (ret == 0) {
373 fprintf(stderr, "raw_pread: read beyond end of file\n");
374 abort();
377 size = ret;
378 if (size > count)
379 size = count;
381 memcpy(buf, s->aligned_buf, size);
383 buf += size;
384 offset += size;
385 count -= size;
386 sum += size;
389 return sum;
393 return raw_pread_aligned(bs, offset, buf, count) + sum;
396 static int raw_read(BlockDriverState *bs, int64_t sector_num,
397 uint8_t *buf, int nb_sectors)
399 int ret;
401 ret = raw_pread(bs, sector_num * BDRV_SECTOR_SIZE, buf,
402 nb_sectors * BDRV_SECTOR_SIZE);
403 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
404 ret = 0;
405 return ret;
409 * offset and count are in bytes and possibly not aligned. For files opened
410 * with O_DIRECT, necessary alignments are ensured before calling
411 * raw_pwrite_aligned to do the actual write.
413 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
414 const uint8_t *buf, int count)
416 BDRVRawState *s = bs->opaque;
417 unsigned sector_mask = bs->buffer_alignment - 1;
418 int size, ret, shift, sum;
420 sum = 0;
422 if (s->aligned_buf != NULL) {
424 if (offset & sector_mask) {
425 /* align offset on a sector size bytes boundary */
426 shift = offset & sector_mask;
427 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf,
428 bs->buffer_alignment);
429 if (ret < 0)
430 return ret;
432 size = bs->buffer_alignment - shift;
433 if (size > count)
434 size = count;
435 memcpy(s->aligned_buf + shift, buf, size);
437 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf,
438 bs->buffer_alignment);
439 if (ret < 0)
440 return ret;
442 buf += size;
443 offset += size;
444 count -= size;
445 sum += size;
447 if (count == 0)
448 return sum;
450 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
452 while ((size = (count & ~sector_mask)) != 0) {
454 if (size > s->aligned_buf_size)
455 size = s->aligned_buf_size;
457 memcpy(s->aligned_buf, buf, size);
459 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
460 if (ret < 0)
461 return ret;
463 buf += ret;
464 offset += ret;
465 count -= ret;
466 sum += ret;
468 /* here, count < 512 because (count & ~sector_mask) == 0 */
469 if (count) {
470 ret = raw_pread_aligned(bs, offset, s->aligned_buf,
471 bs->buffer_alignment);
472 if (ret < 0)
473 return ret;
474 memcpy(s->aligned_buf, buf, count);
476 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf,
477 bs->buffer_alignment);
478 if (ret < 0)
479 return ret;
480 if (count < ret)
481 ret = count;
483 sum += ret;
485 return sum;
488 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
491 static int raw_write(BlockDriverState *bs, int64_t sector_num,
492 const uint8_t *buf, int nb_sectors)
494 int ret;
495 ret = raw_pwrite(bs, sector_num * BDRV_SECTOR_SIZE, buf,
496 nb_sectors * BDRV_SECTOR_SIZE);
497 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
498 ret = 0;
499 return ret;
503 * Check if all memory in this vector is sector aligned.
505 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
507 int i;
509 for (i = 0; i < qiov->niov; i++) {
510 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
511 return 0;
515 return 1;
518 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
519 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
520 BlockDriverCompletionFunc *cb, void *opaque, int type)
522 BDRVRawState *s = bs->opaque;
524 if (fd_open(bs) < 0)
525 return NULL;
528 * If O_DIRECT is used the buffer needs to be aligned on a sector
529 * boundary. Check if this is the case or telll the low-level
530 * driver that it needs to copy the buffer.
532 if (s->aligned_buf) {
533 if (!qiov_is_aligned(bs, qiov)) {
534 type |= QEMU_AIO_MISALIGNED;
535 #ifdef CONFIG_LINUX_AIO
536 } else if (s->use_aio) {
537 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
538 nb_sectors, cb, opaque, type);
539 #endif
543 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
544 cb, opaque, type);
547 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
548 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
549 BlockDriverCompletionFunc *cb, void *opaque)
551 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
552 cb, opaque, QEMU_AIO_READ);
555 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
556 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
557 BlockDriverCompletionFunc *cb, void *opaque)
559 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
560 cb, opaque, QEMU_AIO_WRITE);
563 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
564 BlockDriverCompletionFunc *cb, void *opaque)
566 BDRVRawState *s = bs->opaque;
568 if (fd_open(bs) < 0)
569 return NULL;
571 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
574 static void raw_close(BlockDriverState *bs)
576 BDRVRawState *s = bs->opaque;
577 if (s->fd >= 0) {
578 close(s->fd);
579 s->fd = -1;
580 if (s->aligned_buf != NULL)
581 qemu_vfree(s->aligned_buf);
585 static int raw_truncate(BlockDriverState *bs, int64_t offset)
587 BDRVRawState *s = bs->opaque;
588 if (s->type != FTYPE_FILE)
589 return -ENOTSUP;
590 if (ftruncate(s->fd, offset) < 0)
591 return -errno;
592 return 0;
595 #ifdef __OpenBSD__
596 static int64_t raw_getlength(BlockDriverState *bs)
598 BDRVRawState *s = bs->opaque;
599 int fd = s->fd;
600 struct stat st;
602 if (fstat(fd, &st))
603 return -1;
604 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
605 struct disklabel dl;
607 if (ioctl(fd, DIOCGDINFO, &dl))
608 return -1;
609 return (uint64_t)dl.d_secsize *
610 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
611 } else
612 return st.st_size;
614 #elif defined(__sun__)
615 static int64_t raw_getlength(BlockDriverState *bs)
617 BDRVRawState *s = bs->opaque;
618 struct dk_minfo minfo;
619 int ret;
621 ret = fd_open(bs);
622 if (ret < 0) {
623 return ret;
627 * Use the DKIOCGMEDIAINFO ioctl to read the size.
629 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
630 if (ret != -1) {
631 return minfo.dki_lbsize * minfo.dki_capacity;
635 * There are reports that lseek on some devices fails, but
636 * irc discussion said that contingency on contingency was overkill.
638 return lseek(s->fd, 0, SEEK_END);
640 #elif defined(CONFIG_BSD)
641 static int64_t raw_getlength(BlockDriverState *bs)
643 BDRVRawState *s = bs->opaque;
644 int fd = s->fd;
645 int64_t size;
646 struct stat sb;
647 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
648 int reopened = 0;
649 #endif
650 int ret;
652 ret = fd_open(bs);
653 if (ret < 0)
654 return ret;
656 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
657 again:
658 #endif
659 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
660 #ifdef DIOCGMEDIASIZE
661 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
662 #elif defined(DIOCGPART)
664 struct partinfo pi;
665 if (ioctl(fd, DIOCGPART, &pi) == 0)
666 size = pi.media_size;
667 else
668 size = 0;
670 if (size == 0)
671 #endif
672 #ifdef CONFIG_COCOA
673 size = LONG_LONG_MAX;
674 #else
675 size = lseek(fd, 0LL, SEEK_END);
676 #endif
677 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
678 switch(s->type) {
679 case FTYPE_CD:
680 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
681 if (size == 2048LL * (unsigned)-1)
682 size = 0;
683 /* XXX no disc? maybe we need to reopen... */
684 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
685 reopened = 1;
686 goto again;
689 #endif
690 } else {
691 size = lseek(fd, 0, SEEK_END);
693 return size;
695 #else
696 static int64_t raw_getlength(BlockDriverState *bs)
698 BDRVRawState *s = bs->opaque;
699 int ret;
701 ret = fd_open(bs);
702 if (ret < 0) {
703 return ret;
706 return lseek(s->fd, 0, SEEK_END);
708 #endif
710 static int raw_create(const char *filename, QEMUOptionParameter *options)
712 int fd;
713 int result = 0;
714 int64_t total_size = 0;
716 /* Read out options */
717 while (options && options->name) {
718 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
719 total_size = options->value.n / BDRV_SECTOR_SIZE;
721 options++;
724 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
725 0644);
726 if (fd < 0) {
727 result = -errno;
728 } else {
729 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
730 result = -errno;
732 if (close(fd) != 0) {
733 result = -errno;
736 return result;
739 static int raw_flush(BlockDriverState *bs)
741 BDRVRawState *s = bs->opaque;
742 return qemu_fdatasync(s->fd);
746 static QEMUOptionParameter raw_create_options[] = {
748 .name = BLOCK_OPT_SIZE,
749 .type = OPT_SIZE,
750 .help = "Virtual disk size"
752 { NULL }
755 static BlockDriver bdrv_file = {
756 .format_name = "file",
757 .protocol_name = "file",
758 .instance_size = sizeof(BDRVRawState),
759 .bdrv_probe = NULL, /* no probe for protocols */
760 .bdrv_file_open = raw_open,
761 .bdrv_read = raw_read,
762 .bdrv_write = raw_write,
763 .bdrv_close = raw_close,
764 .bdrv_create = raw_create,
765 .bdrv_flush = raw_flush,
767 .bdrv_aio_readv = raw_aio_readv,
768 .bdrv_aio_writev = raw_aio_writev,
769 .bdrv_aio_flush = raw_aio_flush,
771 .bdrv_truncate = raw_truncate,
772 .bdrv_getlength = raw_getlength,
774 .create_options = raw_create_options,
777 /***********************************************/
778 /* host device */
780 #ifdef CONFIG_COCOA
781 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
782 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
784 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
786 kern_return_t kernResult;
787 mach_port_t masterPort;
788 CFMutableDictionaryRef classesToMatch;
790 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
791 if ( KERN_SUCCESS != kernResult ) {
792 printf( "IOMasterPort returned %d\n", kernResult );
795 classesToMatch = IOServiceMatching( kIOCDMediaClass );
796 if ( classesToMatch == NULL ) {
797 printf( "IOServiceMatching returned a NULL dictionary.\n" );
798 } else {
799 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
801 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
802 if ( KERN_SUCCESS != kernResult )
804 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
807 return kernResult;
810 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
812 io_object_t nextMedia;
813 kern_return_t kernResult = KERN_FAILURE;
814 *bsdPath = '\0';
815 nextMedia = IOIteratorNext( mediaIterator );
816 if ( nextMedia )
818 CFTypeRef bsdPathAsCFString;
819 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
820 if ( bsdPathAsCFString ) {
821 size_t devPathLength;
822 strcpy( bsdPath, _PATH_DEV );
823 strcat( bsdPath, "r" );
824 devPathLength = strlen( bsdPath );
825 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
826 kernResult = KERN_SUCCESS;
828 CFRelease( bsdPathAsCFString );
830 IOObjectRelease( nextMedia );
833 return kernResult;
836 #endif
838 static int hdev_probe_device(const char *filename)
840 struct stat st;
842 /* allow a dedicated CD-ROM driver to match with a higher priority */
843 if (strstart(filename, "/dev/cdrom", NULL))
844 return 50;
846 if (stat(filename, &st) >= 0 &&
847 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
848 return 100;
851 return 0;
854 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
856 BDRVRawState *s = bs->opaque;
858 #ifdef CONFIG_COCOA
859 if (strstart(filename, "/dev/cdrom", NULL)) {
860 kern_return_t kernResult;
861 io_iterator_t mediaIterator;
862 char bsdPath[ MAXPATHLEN ];
863 int fd;
865 kernResult = FindEjectableCDMedia( &mediaIterator );
866 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
868 if ( bsdPath[ 0 ] != '\0' ) {
869 strcat(bsdPath,"s0");
870 /* some CDs don't have a partition 0 */
871 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
872 if (fd < 0) {
873 bsdPath[strlen(bsdPath)-1] = '1';
874 } else {
875 close(fd);
877 filename = bsdPath;
880 if ( mediaIterator )
881 IOObjectRelease( mediaIterator );
883 #endif
885 s->type = FTYPE_FILE;
886 #if defined(__linux__)
888 char resolved_path[ MAXPATHLEN ], *temp;
890 temp = realpath(filename, resolved_path);
891 if (temp && strstart(temp, "/dev/sg", NULL)) {
892 bs->sg = 1;
895 #endif
897 return raw_open_common(bs, filename, flags, 0);
900 #if defined(__linux__)
901 /* Note: we do not have a reliable method to detect if the floppy is
902 present. The current method is to try to open the floppy at every
903 I/O and to keep it opened during a few hundreds of ms. */
904 static int fd_open(BlockDriverState *bs)
906 BDRVRawState *s = bs->opaque;
907 int last_media_present;
909 if (s->type != FTYPE_FD)
910 return 0;
911 last_media_present = (s->fd >= 0);
912 if (s->fd >= 0 &&
913 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
914 close(s->fd);
915 s->fd = -1;
916 #ifdef DEBUG_FLOPPY
917 printf("Floppy closed\n");
918 #endif
920 if (s->fd < 0) {
921 if (s->fd_got_error &&
922 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
923 #ifdef DEBUG_FLOPPY
924 printf("No floppy (open delayed)\n");
925 #endif
926 return -EIO;
928 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
929 if (s->fd < 0) {
930 s->fd_error_time = get_clock();
931 s->fd_got_error = 1;
932 if (last_media_present)
933 s->fd_media_changed = 1;
934 #ifdef DEBUG_FLOPPY
935 printf("No floppy\n");
936 #endif
937 return -EIO;
939 #ifdef DEBUG_FLOPPY
940 printf("Floppy opened\n");
941 #endif
943 if (!last_media_present)
944 s->fd_media_changed = 1;
945 s->fd_open_time = get_clock();
946 s->fd_got_error = 0;
947 return 0;
950 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
952 BDRVRawState *s = bs->opaque;
954 return ioctl(s->fd, req, buf);
957 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
958 unsigned long int req, void *buf,
959 BlockDriverCompletionFunc *cb, void *opaque)
961 BDRVRawState *s = bs->opaque;
963 if (fd_open(bs) < 0)
964 return NULL;
965 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
968 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
969 static int fd_open(BlockDriverState *bs)
971 BDRVRawState *s = bs->opaque;
973 /* this is just to ensure s->fd is sane (its called by io ops) */
974 if (s->fd >= 0)
975 return 0;
976 return -EIO;
978 #else /* !linux && !FreeBSD */
980 static int fd_open(BlockDriverState *bs)
982 return 0;
985 #endif /* !linux && !FreeBSD */
987 static int hdev_create(const char *filename, QEMUOptionParameter *options)
989 int fd;
990 int ret = 0;
991 struct stat stat_buf;
992 int64_t total_size = 0;
994 /* Read out options */
995 while (options && options->name) {
996 if (!strcmp(options->name, "size")) {
997 total_size = options->value.n / BDRV_SECTOR_SIZE;
999 options++;
1002 fd = open(filename, O_WRONLY | O_BINARY);
1003 if (fd < 0)
1004 return -errno;
1006 if (fstat(fd, &stat_buf) < 0)
1007 ret = -errno;
1008 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1009 ret = -ENODEV;
1010 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1011 ret = -ENOSPC;
1013 close(fd);
1014 return ret;
1017 static int hdev_has_zero_init(BlockDriverState *bs)
1019 return 0;
1022 static BlockDriver bdrv_host_device = {
1023 .format_name = "host_device",
1024 .protocol_name = "host_device",
1025 .instance_size = sizeof(BDRVRawState),
1026 .bdrv_probe_device = hdev_probe_device,
1027 .bdrv_file_open = hdev_open,
1028 .bdrv_close = raw_close,
1029 .bdrv_create = hdev_create,
1030 .create_options = raw_create_options,
1031 .bdrv_has_zero_init = hdev_has_zero_init,
1032 .bdrv_flush = raw_flush,
1034 .bdrv_aio_readv = raw_aio_readv,
1035 .bdrv_aio_writev = raw_aio_writev,
1036 .bdrv_aio_flush = raw_aio_flush,
1038 .bdrv_read = raw_read,
1039 .bdrv_write = raw_write,
1040 .bdrv_getlength = raw_getlength,
1042 /* generic scsi device */
1043 #ifdef __linux__
1044 .bdrv_ioctl = hdev_ioctl,
1045 .bdrv_aio_ioctl = hdev_aio_ioctl,
1046 #endif
1049 #ifdef __linux__
1050 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1052 BDRVRawState *s = bs->opaque;
1053 int ret;
1055 s->type = FTYPE_FD;
1057 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1058 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1059 if (ret)
1060 return ret;
1062 /* close fd so that we can reopen it as needed */
1063 close(s->fd);
1064 s->fd = -1;
1065 s->fd_media_changed = 1;
1067 return 0;
1070 static int floppy_probe_device(const char *filename)
1072 int fd, ret;
1073 int prio = 0;
1074 struct floppy_struct fdparam;
1076 if (strstart(filename, "/dev/fd", NULL))
1077 prio = 50;
1079 fd = open(filename, O_RDONLY | O_NONBLOCK);
1080 if (fd < 0) {
1081 goto out;
1084 /* Attempt to detect via a floppy specific ioctl */
1085 ret = ioctl(fd, FDGETPRM, &fdparam);
1086 if (ret >= 0)
1087 prio = 100;
1089 close(fd);
1090 out:
1091 return prio;
1095 static int floppy_is_inserted(BlockDriverState *bs)
1097 return fd_open(bs) >= 0;
1100 static int floppy_media_changed(BlockDriverState *bs)
1102 BDRVRawState *s = bs->opaque;
1103 int ret;
1106 * XXX: we do not have a true media changed indication.
1107 * It does not work if the floppy is changed without trying to read it.
1109 fd_open(bs);
1110 ret = s->fd_media_changed;
1111 s->fd_media_changed = 0;
1112 #ifdef DEBUG_FLOPPY
1113 printf("Floppy changed=%d\n", ret);
1114 #endif
1115 return ret;
1118 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1120 BDRVRawState *s = bs->opaque;
1121 int fd;
1123 if (s->fd >= 0) {
1124 close(s->fd);
1125 s->fd = -1;
1127 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1128 if (fd >= 0) {
1129 if (ioctl(fd, FDEJECT, 0) < 0)
1130 perror("FDEJECT");
1131 close(fd);
1134 return 0;
1137 static BlockDriver bdrv_host_floppy = {
1138 .format_name = "host_floppy",
1139 .protocol_name = "host_floppy",
1140 .instance_size = sizeof(BDRVRawState),
1141 .bdrv_probe_device = floppy_probe_device,
1142 .bdrv_file_open = floppy_open,
1143 .bdrv_close = raw_close,
1144 .bdrv_create = hdev_create,
1145 .create_options = raw_create_options,
1146 .bdrv_has_zero_init = hdev_has_zero_init,
1147 .bdrv_flush = raw_flush,
1149 .bdrv_aio_readv = raw_aio_readv,
1150 .bdrv_aio_writev = raw_aio_writev,
1151 .bdrv_aio_flush = raw_aio_flush,
1153 .bdrv_read = raw_read,
1154 .bdrv_write = raw_write,
1155 .bdrv_getlength = raw_getlength,
1157 /* removable device support */
1158 .bdrv_is_inserted = floppy_is_inserted,
1159 .bdrv_media_changed = floppy_media_changed,
1160 .bdrv_eject = floppy_eject,
1163 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1165 BDRVRawState *s = bs->opaque;
1167 s->type = FTYPE_CD;
1169 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1170 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1173 static int cdrom_probe_device(const char *filename)
1175 int fd, ret;
1176 int prio = 0;
1178 fd = open(filename, O_RDONLY | O_NONBLOCK);
1179 if (fd < 0) {
1180 goto out;
1183 /* Attempt to detect via a CDROM specific ioctl */
1184 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1185 if (ret >= 0)
1186 prio = 100;
1188 close(fd);
1189 out:
1190 return prio;
1193 static int cdrom_is_inserted(BlockDriverState *bs)
1195 BDRVRawState *s = bs->opaque;
1196 int ret;
1198 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1199 if (ret == CDS_DISC_OK)
1200 return 1;
1201 return 0;
1204 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1206 BDRVRawState *s = bs->opaque;
1208 if (eject_flag) {
1209 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1210 perror("CDROMEJECT");
1211 } else {
1212 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1213 perror("CDROMEJECT");
1216 return 0;
1219 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1221 BDRVRawState *s = bs->opaque;
1223 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1225 * Note: an error can happen if the distribution automatically
1226 * mounts the CD-ROM
1228 /* perror("CDROM_LOCKDOOR"); */
1231 return 0;
1234 static BlockDriver bdrv_host_cdrom = {
1235 .format_name = "host_cdrom",
1236 .protocol_name = "host_cdrom",
1237 .instance_size = sizeof(BDRVRawState),
1238 .bdrv_probe_device = cdrom_probe_device,
1239 .bdrv_file_open = cdrom_open,
1240 .bdrv_close = raw_close,
1241 .bdrv_create = hdev_create,
1242 .create_options = raw_create_options,
1243 .bdrv_has_zero_init = hdev_has_zero_init,
1244 .bdrv_flush = raw_flush,
1246 .bdrv_aio_readv = raw_aio_readv,
1247 .bdrv_aio_writev = raw_aio_writev,
1248 .bdrv_aio_flush = raw_aio_flush,
1250 .bdrv_read = raw_read,
1251 .bdrv_write = raw_write,
1252 .bdrv_getlength = raw_getlength,
1254 /* removable device support */
1255 .bdrv_is_inserted = cdrom_is_inserted,
1256 .bdrv_eject = cdrom_eject,
1257 .bdrv_set_locked = cdrom_set_locked,
1259 /* generic scsi device */
1260 .bdrv_ioctl = hdev_ioctl,
1261 .bdrv_aio_ioctl = hdev_aio_ioctl,
1263 #endif /* __linux__ */
1265 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1266 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1268 BDRVRawState *s = bs->opaque;
1269 int ret;
1271 s->type = FTYPE_CD;
1273 ret = raw_open_common(bs, filename, flags, 0);
1274 if (ret)
1275 return ret;
1277 /* make sure the door isnt locked at this time */
1278 ioctl(s->fd, CDIOCALLOW);
1279 return 0;
1282 static int cdrom_probe_device(const char *filename)
1284 if (strstart(filename, "/dev/cd", NULL) ||
1285 strstart(filename, "/dev/acd", NULL))
1286 return 100;
1287 return 0;
1290 static int cdrom_reopen(BlockDriverState *bs)
1292 BDRVRawState *s = bs->opaque;
1293 int fd;
1296 * Force reread of possibly changed/newly loaded disc,
1297 * FreeBSD seems to not notice sometimes...
1299 if (s->fd >= 0)
1300 close(s->fd);
1301 fd = open(bs->filename, s->open_flags, 0644);
1302 if (fd < 0) {
1303 s->fd = -1;
1304 return -EIO;
1306 s->fd = fd;
1308 /* make sure the door isnt locked at this time */
1309 ioctl(s->fd, CDIOCALLOW);
1310 return 0;
1313 static int cdrom_is_inserted(BlockDriverState *bs)
1315 return raw_getlength(bs) > 0;
1318 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1320 BDRVRawState *s = bs->opaque;
1322 if (s->fd < 0)
1323 return -ENOTSUP;
1325 (void) ioctl(s->fd, CDIOCALLOW);
1327 if (eject_flag) {
1328 if (ioctl(s->fd, CDIOCEJECT) < 0)
1329 perror("CDIOCEJECT");
1330 } else {
1331 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1332 perror("CDIOCCLOSE");
1335 if (cdrom_reopen(bs) < 0)
1336 return -ENOTSUP;
1337 return 0;
1340 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1342 BDRVRawState *s = bs->opaque;
1344 if (s->fd < 0)
1345 return -ENOTSUP;
1346 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1348 * Note: an error can happen if the distribution automatically
1349 * mounts the CD-ROM
1351 /* perror("CDROM_LOCKDOOR"); */
1354 return 0;
1357 static BlockDriver bdrv_host_cdrom = {
1358 .format_name = "host_cdrom",
1359 .protocol_name = "host_cdrom",
1360 .instance_size = sizeof(BDRVRawState),
1361 .bdrv_probe_device = cdrom_probe_device,
1362 .bdrv_file_open = cdrom_open,
1363 .bdrv_close = raw_close,
1364 .bdrv_create = hdev_create,
1365 .create_options = raw_create_options,
1366 .bdrv_has_zero_init = hdev_has_zero_init,
1367 .bdrv_flush = raw_flush,
1369 .bdrv_aio_readv = raw_aio_readv,
1370 .bdrv_aio_writev = raw_aio_writev,
1371 .bdrv_aio_flush = raw_aio_flush,
1373 .bdrv_read = raw_read,
1374 .bdrv_write = raw_write,
1375 .bdrv_getlength = raw_getlength,
1377 /* removable device support */
1378 .bdrv_is_inserted = cdrom_is_inserted,
1379 .bdrv_eject = cdrom_eject,
1380 .bdrv_set_locked = cdrom_set_locked,
1382 #endif /* __FreeBSD__ */
1384 static void bdrv_file_init(void)
1387 * Register all the drivers. Note that order is important, the driver
1388 * registered last will get probed first.
1390 bdrv_register(&bdrv_file);
1391 bdrv_register(&bdrv_host_device);
1392 #ifdef __linux__
1393 bdrv_register(&bdrv_host_floppy);
1394 bdrv_register(&bdrv_host_cdrom);
1395 #endif
1396 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1397 bdrv_register(&bdrv_host_cdrom);
1398 #endif
1401 block_init(bdrv_file_init);