Use calloc in qemu_mallocz.
[qemu/mdroth.git] / block / raw-posix.c
blob7541ed2abe6e6c81ebd2ed317c3ad3af770a57e4
1 /*
2 * Block driver for RAW files (posix)
4 * Copyright (c) 2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "qemu-char.h"
27 #include "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "block/raw-posix-aio.h"
32 #ifdef CONFIG_COCOA
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <signal.h>
47 #include <sys/dkio.h>
48 #endif
49 #ifdef __linux__
50 #include <sys/ioctl.h>
51 #include <linux/cdrom.h>
52 #include <linux/fd.h>
53 #endif
54 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
55 #include <signal.h>
56 #include <sys/disk.h>
57 #include <sys/cdio.h>
58 #endif
60 #ifdef __OpenBSD__
61 #include <sys/ioctl.h>
62 #include <sys/disklabel.h>
63 #include <sys/dkio.h>
64 #endif
66 #ifdef __DragonFly__
67 #include <sys/ioctl.h>
68 #include <sys/diskslice.h>
69 #endif
71 //#define DEBUG_FLOPPY
73 //#define DEBUG_BLOCK
74 #if defined(DEBUG_BLOCK)
75 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
76 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
77 #else
78 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
79 #endif
81 /* OS X does not have O_DSYNC */
82 #ifndef O_DSYNC
83 #ifdef O_SYNC
84 #define O_DSYNC O_SYNC
85 #elif defined(O_FSYNC)
86 #define O_DSYNC O_FSYNC
87 #endif
88 #endif
90 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
91 #ifndef O_DIRECT
92 #define O_DIRECT O_DSYNC
93 #endif
95 #define FTYPE_FILE 0
96 #define FTYPE_CD 1
97 #define FTYPE_FD 2
99 #define ALIGNED_BUFFER_SIZE (32 * 512)
101 /* if the FD is not accessed during that time (in ms), we try to
102 reopen it to see if the disk has been changed */
103 #define FD_OPEN_TIMEOUT 1000
105 typedef struct BDRVRawState {
106 int fd;
107 int type;
108 int open_flags;
109 #if defined(__linux__)
110 /* linux floppy specific */
111 int64_t fd_open_time;
112 int64_t fd_error_time;
113 int fd_got_error;
114 int fd_media_changed;
115 #endif
116 #ifdef CONFIG_LINUX_AIO
117 int use_aio;
118 void *aio_ctx;
119 #endif
120 uint8_t* aligned_buf;
121 } BDRVRawState;
123 static int fd_open(BlockDriverState *bs);
124 static int64_t raw_getlength(BlockDriverState *bs);
126 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
127 static int cdrom_reopen(BlockDriverState *bs);
128 #endif
130 static int raw_open_common(BlockDriverState *bs, const char *filename,
131 int bdrv_flags, int open_flags)
133 BDRVRawState *s = bs->opaque;
134 int fd, ret;
136 s->open_flags = open_flags | O_BINARY;
137 s->open_flags &= ~O_ACCMODE;
138 if (bdrv_flags & BDRV_O_RDWR) {
139 s->open_flags |= O_RDWR;
140 } else {
141 s->open_flags |= O_RDONLY;
144 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
145 * and O_DIRECT for no caching. */
146 if ((bdrv_flags & BDRV_O_NOCACHE))
147 s->open_flags |= O_DIRECT;
148 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
149 s->open_flags |= O_DSYNC;
151 s->fd = -1;
152 fd = qemu_open(filename, s->open_flags, 0644);
153 if (fd < 0) {
154 ret = -errno;
155 if (ret == -EROFS)
156 ret = -EACCES;
157 return ret;
159 s->fd = fd;
160 s->aligned_buf = NULL;
162 if ((bdrv_flags & BDRV_O_NOCACHE)) {
163 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
164 if (s->aligned_buf == NULL) {
165 goto out_close;
169 #ifdef CONFIG_LINUX_AIO
170 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
171 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
173 /* We're falling back to POSIX AIO in some cases */
174 paio_init();
176 s->aio_ctx = laio_init();
177 if (!s->aio_ctx) {
178 goto out_free_buf;
180 s->use_aio = 1;
181 } else
182 #endif
184 if (paio_init() < 0) {
185 goto out_free_buf;
187 #ifdef CONFIG_LINUX_AIO
188 s->use_aio = 0;
189 #endif
192 return 0;
194 out_free_buf:
195 qemu_vfree(s->aligned_buf);
196 out_close:
197 close(fd);
198 return -errno;
201 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
203 BDRVRawState *s = bs->opaque;
205 s->type = FTYPE_FILE;
206 return raw_open_common(bs, filename, flags, 0);
209 /* XXX: use host sector size if necessary with:
210 #ifdef DIOCGSECTORSIZE
212 unsigned int sectorsize = 512;
213 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
214 sectorsize > bufsize)
215 bufsize = sectorsize;
217 #endif
218 #ifdef CONFIG_COCOA
219 u_int32_t blockSize = 512;
220 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
221 bufsize = blockSize;
223 #endif
227 * offset and count are in bytes, but must be multiples of 512 for files
228 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
230 * This function may be called without alignment if the caller ensures
231 * that O_DIRECT is not in effect.
233 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
234 uint8_t *buf, int count)
236 BDRVRawState *s = bs->opaque;
237 int ret;
239 ret = fd_open(bs);
240 if (ret < 0)
241 return ret;
243 ret = pread(s->fd, buf, count, offset);
244 if (ret == count)
245 goto label__raw_read__success;
247 /* Allow reads beyond the end (needed for pwrite) */
248 if ((ret == 0) && bs->growable) {
249 int64_t size = raw_getlength(bs);
250 if (offset >= size) {
251 memset(buf, 0, count);
252 ret = count;
253 goto label__raw_read__success;
257 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
258 "] read failed %d : %d = %s\n",
259 s->fd, bs->filename, offset, buf, count,
260 bs->total_sectors, ret, errno, strerror(errno));
262 /* Try harder for CDrom. */
263 if (bs->type == BDRV_TYPE_CDROM) {
264 ret = pread(s->fd, buf, count, offset);
265 if (ret == count)
266 goto label__raw_read__success;
267 ret = pread(s->fd, buf, count, offset);
268 if (ret == count)
269 goto label__raw_read__success;
271 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
272 "] retry read failed %d : %d = %s\n",
273 s->fd, bs->filename, offset, buf, count,
274 bs->total_sectors, ret, errno, strerror(errno));
277 label__raw_read__success:
279 return (ret < 0) ? -errno : ret;
283 * offset and count are in bytes, but must be multiples of 512 for files
284 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
286 * This function may be called without alignment if the caller ensures
287 * that O_DIRECT is not in effect.
289 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
290 const uint8_t *buf, int count)
292 BDRVRawState *s = bs->opaque;
293 int ret;
295 ret = fd_open(bs);
296 if (ret < 0)
297 return -errno;
299 ret = pwrite(s->fd, buf, count, offset);
300 if (ret == count)
301 goto label__raw_write__success;
303 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
304 "] write failed %d : %d = %s\n",
305 s->fd, bs->filename, offset, buf, count,
306 bs->total_sectors, ret, errno, strerror(errno));
308 label__raw_write__success:
310 return (ret < 0) ? -errno : ret;
315 * offset and count are in bytes and possibly not aligned. For files opened
316 * with O_DIRECT, necessary alignments are ensured before calling
317 * raw_pread_aligned to do the actual read.
319 static int raw_pread(BlockDriverState *bs, int64_t offset,
320 uint8_t *buf, int count)
322 BDRVRawState *s = bs->opaque;
323 int size, ret, shift, sum;
325 sum = 0;
327 if (s->aligned_buf != NULL) {
329 if (offset & 0x1ff) {
330 /* align offset on a 512 bytes boundary */
332 shift = offset & 0x1ff;
333 size = (shift + count + 0x1ff) & ~0x1ff;
334 if (size > ALIGNED_BUFFER_SIZE)
335 size = ALIGNED_BUFFER_SIZE;
336 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
337 if (ret < 0)
338 return ret;
340 size = 512 - shift;
341 if (size > count)
342 size = count;
343 memcpy(buf, s->aligned_buf + shift, size);
345 buf += size;
346 offset += size;
347 count -= size;
348 sum += size;
350 if (count == 0)
351 return sum;
353 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
355 /* read on aligned buffer */
357 while (count) {
359 size = (count + 0x1ff) & ~0x1ff;
360 if (size > ALIGNED_BUFFER_SIZE)
361 size = ALIGNED_BUFFER_SIZE;
363 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
364 if (ret < 0) {
365 return ret;
366 } else if (ret == 0) {
367 fprintf(stderr, "raw_pread: read beyond end of file\n");
368 abort();
371 size = ret;
372 if (size > count)
373 size = count;
375 memcpy(buf, s->aligned_buf, size);
377 buf += size;
378 offset += size;
379 count -= size;
380 sum += size;
383 return sum;
387 return raw_pread_aligned(bs, offset, buf, count) + sum;
390 static int raw_read(BlockDriverState *bs, int64_t sector_num,
391 uint8_t *buf, int nb_sectors)
393 int ret;
395 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
396 if (ret == (nb_sectors * 512))
397 ret = 0;
398 return ret;
402 * offset and count are in bytes and possibly not aligned. For files opened
403 * with O_DIRECT, necessary alignments are ensured before calling
404 * raw_pwrite_aligned to do the actual write.
406 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
407 const uint8_t *buf, int count)
409 BDRVRawState *s = bs->opaque;
410 int size, ret, shift, sum;
412 sum = 0;
414 if (s->aligned_buf != NULL) {
416 if (offset & 0x1ff) {
417 /* align offset on a 512 bytes boundary */
418 shift = offset & 0x1ff;
419 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
420 if (ret < 0)
421 return ret;
423 size = 512 - shift;
424 if (size > count)
425 size = count;
426 memcpy(s->aligned_buf + shift, buf, size);
428 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
429 if (ret < 0)
430 return ret;
432 buf += size;
433 offset += size;
434 count -= size;
435 sum += size;
437 if (count == 0)
438 return sum;
440 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
442 while ((size = (count & ~0x1ff)) != 0) {
444 if (size > ALIGNED_BUFFER_SIZE)
445 size = ALIGNED_BUFFER_SIZE;
447 memcpy(s->aligned_buf, buf, size);
449 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
450 if (ret < 0)
451 return ret;
453 buf += ret;
454 offset += ret;
455 count -= ret;
456 sum += ret;
458 /* here, count < 512 because (count & ~0x1ff) == 0 */
459 if (count) {
460 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
461 if (ret < 0)
462 return ret;
463 memcpy(s->aligned_buf, buf, count);
465 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
466 if (ret < 0)
467 return ret;
468 if (count < ret)
469 ret = count;
471 sum += ret;
473 return sum;
476 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
479 static int raw_write(BlockDriverState *bs, int64_t sector_num,
480 const uint8_t *buf, int nb_sectors)
482 int ret;
483 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
484 if (ret == (nb_sectors * 512))
485 ret = 0;
486 return ret;
490 * Check if all memory in this vector is sector aligned.
492 static int qiov_is_aligned(QEMUIOVector *qiov)
494 int i;
496 for (i = 0; i < qiov->niov; i++) {
497 if ((uintptr_t) qiov->iov[i].iov_base % 512) {
498 return 0;
502 return 1;
505 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
506 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
507 BlockDriverCompletionFunc *cb, void *opaque, int type)
509 BDRVRawState *s = bs->opaque;
511 if (fd_open(bs) < 0)
512 return NULL;
515 * If O_DIRECT is used the buffer needs to be aligned on a sector
516 * boundary. Check if this is the case or telll the low-level
517 * driver that it needs to copy the buffer.
519 if (s->aligned_buf) {
520 if (!qiov_is_aligned(qiov)) {
521 type |= QEMU_AIO_MISALIGNED;
522 #ifdef CONFIG_LINUX_AIO
523 } else if (s->use_aio) {
524 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
525 nb_sectors, cb, opaque, type);
526 #endif
530 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
531 cb, opaque, type);
534 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
535 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
536 BlockDriverCompletionFunc *cb, void *opaque)
538 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
539 cb, opaque, QEMU_AIO_READ);
542 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
543 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
544 BlockDriverCompletionFunc *cb, void *opaque)
546 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
547 cb, opaque, QEMU_AIO_WRITE);
550 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
551 BlockDriverCompletionFunc *cb, void *opaque)
553 BDRVRawState *s = bs->opaque;
555 if (fd_open(bs) < 0)
556 return NULL;
558 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
561 static void raw_close(BlockDriverState *bs)
563 BDRVRawState *s = bs->opaque;
564 if (s->fd >= 0) {
565 close(s->fd);
566 s->fd = -1;
567 if (s->aligned_buf != NULL)
568 qemu_vfree(s->aligned_buf);
572 static int raw_truncate(BlockDriverState *bs, int64_t offset)
574 BDRVRawState *s = bs->opaque;
575 if (s->type != FTYPE_FILE)
576 return -ENOTSUP;
577 if (ftruncate(s->fd, offset) < 0)
578 return -errno;
579 return 0;
582 #ifdef __OpenBSD__
583 static int64_t raw_getlength(BlockDriverState *bs)
585 BDRVRawState *s = bs->opaque;
586 int fd = s->fd;
587 struct stat st;
589 if (fstat(fd, &st))
590 return -1;
591 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
592 struct disklabel dl;
594 if (ioctl(fd, DIOCGDINFO, &dl))
595 return -1;
596 return (uint64_t)dl.d_secsize *
597 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
598 } else
599 return st.st_size;
601 #elif defined(__sun__)
602 static int64_t raw_getlength(BlockDriverState *bs)
604 BDRVRawState *s = bs->opaque;
605 struct dk_minfo minfo;
606 int ret;
608 ret = fd_open(bs);
609 if (ret < 0) {
610 return ret;
614 * Use the DKIOCGMEDIAINFO ioctl to read the size.
616 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
617 if (ret != -1) {
618 return minfo.dki_lbsize * minfo.dki_capacity;
622 * There are reports that lseek on some devices fails, but
623 * irc discussion said that contingency on contingency was overkill.
625 return lseek(s->fd, 0, SEEK_END);
627 #elif defined(CONFIG_BSD)
628 static int64_t raw_getlength(BlockDriverState *bs)
630 BDRVRawState *s = bs->opaque;
631 int fd = s->fd;
632 int64_t size;
633 struct stat sb;
634 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
635 int reopened = 0;
636 #endif
637 int ret;
639 ret = fd_open(bs);
640 if (ret < 0)
641 return ret;
643 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
644 again:
645 #endif
646 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
647 #ifdef DIOCGMEDIASIZE
648 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
649 #elif defined(DIOCGPART)
651 struct partinfo pi;
652 if (ioctl(fd, DIOCGPART, &pi) == 0)
653 size = pi.media_size;
654 else
655 size = 0;
657 if (size == 0)
658 #endif
659 #ifdef CONFIG_COCOA
660 size = LONG_LONG_MAX;
661 #else
662 size = lseek(fd, 0LL, SEEK_END);
663 #endif
664 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
665 switch(s->type) {
666 case FTYPE_CD:
667 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
668 if (size == 2048LL * (unsigned)-1)
669 size = 0;
670 /* XXX no disc? maybe we need to reopen... */
671 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
672 reopened = 1;
673 goto again;
676 #endif
677 } else {
678 size = lseek(fd, 0, SEEK_END);
680 return size;
682 #else
683 static int64_t raw_getlength(BlockDriverState *bs)
685 BDRVRawState *s = bs->opaque;
686 int ret;
688 ret = fd_open(bs);
689 if (ret < 0) {
690 return ret;
693 return lseek(s->fd, 0, SEEK_END);
695 #endif
697 static int raw_create(const char *filename, QEMUOptionParameter *options)
699 int fd;
700 int result = 0;
701 int64_t total_size = 0;
703 /* Read out options */
704 while (options && options->name) {
705 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
706 total_size = options->value.n / 512;
708 options++;
711 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
712 0644);
713 if (fd < 0) {
714 result = -errno;
715 } else {
716 if (ftruncate(fd, total_size * 512) != 0) {
717 result = -errno;
719 if (close(fd) != 0) {
720 result = -errno;
723 return result;
726 static void raw_flush(BlockDriverState *bs)
728 BDRVRawState *s = bs->opaque;
729 qemu_fdatasync(s->fd);
733 static QEMUOptionParameter raw_create_options[] = {
735 .name = BLOCK_OPT_SIZE,
736 .type = OPT_SIZE,
737 .help = "Virtual disk size"
739 { NULL }
742 static BlockDriver bdrv_file = {
743 .format_name = "file",
744 .protocol_name = "file",
745 .instance_size = sizeof(BDRVRawState),
746 .bdrv_probe = NULL, /* no probe for protocols */
747 .bdrv_file_open = raw_open,
748 .bdrv_read = raw_read,
749 .bdrv_write = raw_write,
750 .bdrv_close = raw_close,
751 .bdrv_create = raw_create,
752 .bdrv_flush = raw_flush,
754 .bdrv_aio_readv = raw_aio_readv,
755 .bdrv_aio_writev = raw_aio_writev,
756 .bdrv_aio_flush = raw_aio_flush,
758 .bdrv_truncate = raw_truncate,
759 .bdrv_getlength = raw_getlength,
761 .create_options = raw_create_options,
764 /***********************************************/
765 /* host device */
767 #ifdef CONFIG_COCOA
768 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
769 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
771 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
773 kern_return_t kernResult;
774 mach_port_t masterPort;
775 CFMutableDictionaryRef classesToMatch;
777 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
778 if ( KERN_SUCCESS != kernResult ) {
779 printf( "IOMasterPort returned %d\n", kernResult );
782 classesToMatch = IOServiceMatching( kIOCDMediaClass );
783 if ( classesToMatch == NULL ) {
784 printf( "IOServiceMatching returned a NULL dictionary.\n" );
785 } else {
786 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
788 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
789 if ( KERN_SUCCESS != kernResult )
791 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
794 return kernResult;
797 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
799 io_object_t nextMedia;
800 kern_return_t kernResult = KERN_FAILURE;
801 *bsdPath = '\0';
802 nextMedia = IOIteratorNext( mediaIterator );
803 if ( nextMedia )
805 CFTypeRef bsdPathAsCFString;
806 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
807 if ( bsdPathAsCFString ) {
808 size_t devPathLength;
809 strcpy( bsdPath, _PATH_DEV );
810 strcat( bsdPath, "r" );
811 devPathLength = strlen( bsdPath );
812 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
813 kernResult = KERN_SUCCESS;
815 CFRelease( bsdPathAsCFString );
817 IOObjectRelease( nextMedia );
820 return kernResult;
823 #endif
825 static int hdev_probe_device(const char *filename)
827 struct stat st;
829 /* allow a dedicated CD-ROM driver to match with a higher priority */
830 if (strstart(filename, "/dev/cdrom", NULL))
831 return 50;
833 if (stat(filename, &st) >= 0 &&
834 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
835 return 100;
838 return 0;
841 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
843 BDRVRawState *s = bs->opaque;
845 #ifdef CONFIG_COCOA
846 if (strstart(filename, "/dev/cdrom", NULL)) {
847 kern_return_t kernResult;
848 io_iterator_t mediaIterator;
849 char bsdPath[ MAXPATHLEN ];
850 int fd;
852 kernResult = FindEjectableCDMedia( &mediaIterator );
853 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
855 if ( bsdPath[ 0 ] != '\0' ) {
856 strcat(bsdPath,"s0");
857 /* some CDs don't have a partition 0 */
858 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
859 if (fd < 0) {
860 bsdPath[strlen(bsdPath)-1] = '1';
861 } else {
862 close(fd);
864 filename = bsdPath;
867 if ( mediaIterator )
868 IOObjectRelease( mediaIterator );
870 #endif
872 s->type = FTYPE_FILE;
873 #if defined(__linux__)
874 if (strstart(filename, "/dev/sg", NULL)) {
875 bs->sg = 1;
877 #endif
879 return raw_open_common(bs, filename, flags, 0);
882 #if defined(__linux__)
883 /* Note: we do not have a reliable method to detect if the floppy is
884 present. The current method is to try to open the floppy at every
885 I/O and to keep it opened during a few hundreds of ms. */
886 static int fd_open(BlockDriverState *bs)
888 BDRVRawState *s = bs->opaque;
889 int last_media_present;
891 if (s->type != FTYPE_FD)
892 return 0;
893 last_media_present = (s->fd >= 0);
894 if (s->fd >= 0 &&
895 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
896 close(s->fd);
897 s->fd = -1;
898 #ifdef DEBUG_FLOPPY
899 printf("Floppy closed\n");
900 #endif
902 if (s->fd < 0) {
903 if (s->fd_got_error &&
904 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
905 #ifdef DEBUG_FLOPPY
906 printf("No floppy (open delayed)\n");
907 #endif
908 return -EIO;
910 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
911 if (s->fd < 0) {
912 s->fd_error_time = qemu_get_clock(rt_clock);
913 s->fd_got_error = 1;
914 if (last_media_present)
915 s->fd_media_changed = 1;
916 #ifdef DEBUG_FLOPPY
917 printf("No floppy\n");
918 #endif
919 return -EIO;
921 #ifdef DEBUG_FLOPPY
922 printf("Floppy opened\n");
923 #endif
925 if (!last_media_present)
926 s->fd_media_changed = 1;
927 s->fd_open_time = qemu_get_clock(rt_clock);
928 s->fd_got_error = 0;
929 return 0;
932 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
934 BDRVRawState *s = bs->opaque;
936 return ioctl(s->fd, req, buf);
939 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
940 unsigned long int req, void *buf,
941 BlockDriverCompletionFunc *cb, void *opaque)
943 BDRVRawState *s = bs->opaque;
945 if (fd_open(bs) < 0)
946 return NULL;
947 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
950 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
951 static int fd_open(BlockDriverState *bs)
953 BDRVRawState *s = bs->opaque;
955 /* this is just to ensure s->fd is sane (its called by io ops) */
956 if (s->fd >= 0)
957 return 0;
958 return -EIO;
960 #else /* !linux && !FreeBSD */
962 static int fd_open(BlockDriverState *bs)
964 return 0;
967 #endif /* !linux && !FreeBSD */
969 static int hdev_create(const char *filename, QEMUOptionParameter *options)
971 int fd;
972 int ret = 0;
973 struct stat stat_buf;
974 int64_t total_size = 0;
976 /* Read out options */
977 while (options && options->name) {
978 if (!strcmp(options->name, "size")) {
979 total_size = options->value.n / 512;
981 options++;
984 fd = open(filename, O_WRONLY | O_BINARY);
985 if (fd < 0)
986 return -errno;
988 if (fstat(fd, &stat_buf) < 0)
989 ret = -errno;
990 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
991 ret = -ENODEV;
992 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
993 ret = -ENOSPC;
995 close(fd);
996 return ret;
999 static BlockDriver bdrv_host_device = {
1000 .format_name = "host_device",
1001 .protocol_name = "host_device",
1002 .instance_size = sizeof(BDRVRawState),
1003 .bdrv_probe_device = hdev_probe_device,
1004 .bdrv_file_open = hdev_open,
1005 .bdrv_close = raw_close,
1006 .bdrv_create = hdev_create,
1007 .create_options = raw_create_options,
1008 .no_zero_init = 1,
1009 .bdrv_flush = raw_flush,
1011 .bdrv_aio_readv = raw_aio_readv,
1012 .bdrv_aio_writev = raw_aio_writev,
1013 .bdrv_aio_flush = raw_aio_flush,
1015 .bdrv_read = raw_read,
1016 .bdrv_write = raw_write,
1017 .bdrv_getlength = raw_getlength,
1019 /* generic scsi device */
1020 #ifdef __linux__
1021 .bdrv_ioctl = hdev_ioctl,
1022 .bdrv_aio_ioctl = hdev_aio_ioctl,
1023 #endif
1026 #ifdef __linux__
1027 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1029 BDRVRawState *s = bs->opaque;
1030 int ret;
1032 s->type = FTYPE_FD;
1034 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1035 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1036 if (ret)
1037 return ret;
1039 /* close fd so that we can reopen it as needed */
1040 close(s->fd);
1041 s->fd = -1;
1042 s->fd_media_changed = 1;
1044 return 0;
1047 static int floppy_probe_device(const char *filename)
1049 int fd, ret;
1050 int prio = 0;
1051 struct floppy_struct fdparam;
1053 if (strstart(filename, "/dev/fd", NULL))
1054 prio = 50;
1056 fd = open(filename, O_RDONLY | O_NONBLOCK);
1057 if (fd < 0) {
1058 goto out;
1061 /* Attempt to detect via a floppy specific ioctl */
1062 ret = ioctl(fd, FDGETPRM, &fdparam);
1063 if (ret >= 0)
1064 prio = 100;
1066 close(fd);
1067 out:
1068 return prio;
1072 static int floppy_is_inserted(BlockDriverState *bs)
1074 return fd_open(bs) >= 0;
1077 static int floppy_media_changed(BlockDriverState *bs)
1079 BDRVRawState *s = bs->opaque;
1080 int ret;
1083 * XXX: we do not have a true media changed indication.
1084 * It does not work if the floppy is changed without trying to read it.
1086 fd_open(bs);
1087 ret = s->fd_media_changed;
1088 s->fd_media_changed = 0;
1089 #ifdef DEBUG_FLOPPY
1090 printf("Floppy changed=%d\n", ret);
1091 #endif
1092 return ret;
1095 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1097 BDRVRawState *s = bs->opaque;
1098 int fd;
1100 if (s->fd >= 0) {
1101 close(s->fd);
1102 s->fd = -1;
1104 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1105 if (fd >= 0) {
1106 if (ioctl(fd, FDEJECT, 0) < 0)
1107 perror("FDEJECT");
1108 close(fd);
1111 return 0;
1114 static BlockDriver bdrv_host_floppy = {
1115 .format_name = "host_floppy",
1116 .protocol_name = "host_floppy",
1117 .instance_size = sizeof(BDRVRawState),
1118 .bdrv_probe_device = floppy_probe_device,
1119 .bdrv_file_open = floppy_open,
1120 .bdrv_close = raw_close,
1121 .bdrv_create = hdev_create,
1122 .create_options = raw_create_options,
1123 .no_zero_init = 1,
1124 .bdrv_flush = raw_flush,
1126 .bdrv_aio_readv = raw_aio_readv,
1127 .bdrv_aio_writev = raw_aio_writev,
1128 .bdrv_aio_flush = raw_aio_flush,
1130 .bdrv_read = raw_read,
1131 .bdrv_write = raw_write,
1132 .bdrv_getlength = raw_getlength,
1134 /* removable device support */
1135 .bdrv_is_inserted = floppy_is_inserted,
1136 .bdrv_media_changed = floppy_media_changed,
1137 .bdrv_eject = floppy_eject,
1140 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1142 BDRVRawState *s = bs->opaque;
1144 s->type = FTYPE_CD;
1146 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1147 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1150 static int cdrom_probe_device(const char *filename)
1152 int fd, ret;
1153 int prio = 0;
1155 if (strstart(filename, "/dev/cd", NULL))
1156 prio = 50;
1158 fd = open(filename, O_RDONLY | O_NONBLOCK);
1159 if (fd < 0) {
1160 goto out;
1163 /* Attempt to detect via a CDROM specific ioctl */
1164 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1165 if (ret >= 0)
1166 prio = 100;
1168 close(fd);
1169 out:
1170 return prio;
1173 static int cdrom_is_inserted(BlockDriverState *bs)
1175 BDRVRawState *s = bs->opaque;
1176 int ret;
1178 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1179 if (ret == CDS_DISC_OK)
1180 return 1;
1181 return 0;
1184 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1186 BDRVRawState *s = bs->opaque;
1188 if (eject_flag) {
1189 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1190 perror("CDROMEJECT");
1191 } else {
1192 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1193 perror("CDROMEJECT");
1196 return 0;
1199 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1201 BDRVRawState *s = bs->opaque;
1203 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1205 * Note: an error can happen if the distribution automatically
1206 * mounts the CD-ROM
1208 /* perror("CDROM_LOCKDOOR"); */
1211 return 0;
1214 static BlockDriver bdrv_host_cdrom = {
1215 .format_name = "host_cdrom",
1216 .protocol_name = "host_cdrom",
1217 .instance_size = sizeof(BDRVRawState),
1218 .bdrv_probe_device = cdrom_probe_device,
1219 .bdrv_file_open = cdrom_open,
1220 .bdrv_close = raw_close,
1221 .bdrv_create = hdev_create,
1222 .create_options = raw_create_options,
1223 .no_zero_init = 1,
1224 .bdrv_flush = raw_flush,
1226 .bdrv_aio_readv = raw_aio_readv,
1227 .bdrv_aio_writev = raw_aio_writev,
1228 .bdrv_aio_flush = raw_aio_flush,
1230 .bdrv_read = raw_read,
1231 .bdrv_write = raw_write,
1232 .bdrv_getlength = raw_getlength,
1234 /* removable device support */
1235 .bdrv_is_inserted = cdrom_is_inserted,
1236 .bdrv_eject = cdrom_eject,
1237 .bdrv_set_locked = cdrom_set_locked,
1239 /* generic scsi device */
1240 .bdrv_ioctl = hdev_ioctl,
1241 .bdrv_aio_ioctl = hdev_aio_ioctl,
1243 #endif /* __linux__ */
1245 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1246 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1248 BDRVRawState *s = bs->opaque;
1249 int ret;
1251 s->type = FTYPE_CD;
1253 ret = raw_open_common(bs, filename, flags, 0);
1254 if (ret)
1255 return ret;
1257 /* make sure the door isnt locked at this time */
1258 ioctl(s->fd, CDIOCALLOW);
1259 return 0;
1262 static int cdrom_probe_device(const char *filename)
1264 if (strstart(filename, "/dev/cd", NULL) ||
1265 strstart(filename, "/dev/acd", NULL))
1266 return 100;
1267 return 0;
1270 static int cdrom_reopen(BlockDriverState *bs)
1272 BDRVRawState *s = bs->opaque;
1273 int fd;
1276 * Force reread of possibly changed/newly loaded disc,
1277 * FreeBSD seems to not notice sometimes...
1279 if (s->fd >= 0)
1280 close(s->fd);
1281 fd = open(bs->filename, s->open_flags, 0644);
1282 if (fd < 0) {
1283 s->fd = -1;
1284 return -EIO;
1286 s->fd = fd;
1288 /* make sure the door isnt locked at this time */
1289 ioctl(s->fd, CDIOCALLOW);
1290 return 0;
1293 static int cdrom_is_inserted(BlockDriverState *bs)
1295 return raw_getlength(bs) > 0;
1298 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1300 BDRVRawState *s = bs->opaque;
1302 if (s->fd < 0)
1303 return -ENOTSUP;
1305 (void) ioctl(s->fd, CDIOCALLOW);
1307 if (eject_flag) {
1308 if (ioctl(s->fd, CDIOCEJECT) < 0)
1309 perror("CDIOCEJECT");
1310 } else {
1311 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1312 perror("CDIOCCLOSE");
1315 if (cdrom_reopen(bs) < 0)
1316 return -ENOTSUP;
1317 return 0;
1320 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1322 BDRVRawState *s = bs->opaque;
1324 if (s->fd < 0)
1325 return -ENOTSUP;
1326 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1328 * Note: an error can happen if the distribution automatically
1329 * mounts the CD-ROM
1331 /* perror("CDROM_LOCKDOOR"); */
1334 return 0;
1337 static BlockDriver bdrv_host_cdrom = {
1338 .format_name = "host_cdrom",
1339 .protocol_name = "host_cdrom",
1340 .instance_size = sizeof(BDRVRawState),
1341 .bdrv_probe_device = cdrom_probe_device,
1342 .bdrv_file_open = cdrom_open,
1343 .bdrv_close = raw_close,
1344 .bdrv_create = hdev_create,
1345 .create_options = raw_create_options,
1346 .no_zero_init = 1,
1347 .bdrv_flush = raw_flush,
1349 .bdrv_aio_readv = raw_aio_readv,
1350 .bdrv_aio_writev = raw_aio_writev,
1351 .bdrv_aio_flush = raw_aio_flush,
1353 .bdrv_read = raw_read,
1354 .bdrv_write = raw_write,
1355 .bdrv_getlength = raw_getlength,
1357 /* removable device support */
1358 .bdrv_is_inserted = cdrom_is_inserted,
1359 .bdrv_eject = cdrom_eject,
1360 .bdrv_set_locked = cdrom_set_locked,
1362 #endif /* __FreeBSD__ */
1364 static void bdrv_file_init(void)
1367 * Register all the drivers. Note that order is important, the driver
1368 * registered last will get probed first.
1370 bdrv_register(&bdrv_file);
1371 bdrv_register(&bdrv_host_device);
1372 #ifdef __linux__
1373 bdrv_register(&bdrv_host_floppy);
1374 bdrv_register(&bdrv_host_cdrom);
1375 #endif
1376 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1377 bdrv_register(&bdrv_host_cdrom);
1378 #endif
1381 block_init(bdrv_file_init);