add pflib: PixelFormat conversion library.
[qemu.git] / block / raw-posix.c
blob813372a6c72edb2e614f0d998f78bfecee20033f
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 <sys/param.h>
52 #include <linux/cdrom.h>
53 #include <linux/fd.h>
54 #endif
55 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
56 #include <signal.h>
57 #include <sys/disk.h>
58 #include <sys/cdio.h>
59 #endif
61 #ifdef __OpenBSD__
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
64 #include <sys/dkio.h>
65 #endif
67 #ifdef __DragonFly__
68 #include <sys/ioctl.h>
69 #include <sys/diskslice.h>
70 #endif
72 //#define DEBUG_FLOPPY
74 //#define DEBUG_BLOCK
75 #if defined(DEBUG_BLOCK)
76 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
77 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
78 #else
79 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
80 #endif
82 /* OS X does not have O_DSYNC */
83 #ifndef O_DSYNC
84 #ifdef O_SYNC
85 #define O_DSYNC O_SYNC
86 #elif defined(O_FSYNC)
87 #define O_DSYNC O_FSYNC
88 #endif
89 #endif
91 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
92 #ifndef O_DIRECT
93 #define O_DIRECT O_DSYNC
94 #endif
96 #define FTYPE_FILE 0
97 #define FTYPE_CD 1
98 #define FTYPE_FD 2
100 #define ALIGNED_BUFFER_SIZE (32 * 512)
102 /* if the FD is not accessed during that time (in ms), we try to
103 reopen it to see if the disk has been changed */
104 #define FD_OPEN_TIMEOUT 1000
106 typedef struct BDRVRawState {
107 int fd;
108 int type;
109 int open_flags;
110 #if defined(__linux__)
111 /* linux floppy specific */
112 int64_t fd_open_time;
113 int64_t fd_error_time;
114 int fd_got_error;
115 int fd_media_changed;
116 #endif
117 #ifdef CONFIG_LINUX_AIO
118 int use_aio;
119 void *aio_ctx;
120 #endif
121 uint8_t* aligned_buf;
122 } BDRVRawState;
124 static int fd_open(BlockDriverState *bs);
125 static int64_t raw_getlength(BlockDriverState *bs);
127 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
128 static int cdrom_reopen(BlockDriverState *bs);
129 #endif
131 static int raw_open_common(BlockDriverState *bs, const char *filename,
132 int bdrv_flags, int open_flags)
134 BDRVRawState *s = bs->opaque;
135 int fd, ret;
137 s->open_flags = open_flags | O_BINARY;
138 s->open_flags &= ~O_ACCMODE;
139 if (bdrv_flags & BDRV_O_RDWR) {
140 s->open_flags |= O_RDWR;
141 } else {
142 s->open_flags |= O_RDONLY;
145 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
146 * and O_DIRECT for no caching. */
147 if ((bdrv_flags & BDRV_O_NOCACHE))
148 s->open_flags |= O_DIRECT;
149 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
150 s->open_flags |= O_DSYNC;
152 s->fd = -1;
153 fd = qemu_open(filename, s->open_flags, 0644);
154 if (fd < 0) {
155 ret = -errno;
156 if (ret == -EROFS)
157 ret = -EACCES;
158 return ret;
160 s->fd = fd;
161 s->aligned_buf = NULL;
163 if ((bdrv_flags & BDRV_O_NOCACHE)) {
164 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
165 if (s->aligned_buf == NULL) {
166 goto out_close;
170 #ifdef CONFIG_LINUX_AIO
171 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
172 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
174 /* We're falling back to POSIX AIO in some cases */
175 paio_init();
177 s->aio_ctx = laio_init();
178 if (!s->aio_ctx) {
179 goto out_free_buf;
181 s->use_aio = 1;
182 } else
183 #endif
185 if (paio_init() < 0) {
186 goto out_free_buf;
188 #ifdef CONFIG_LINUX_AIO
189 s->use_aio = 0;
190 #endif
193 return 0;
195 out_free_buf:
196 qemu_vfree(s->aligned_buf);
197 out_close:
198 close(fd);
199 return -errno;
202 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
204 BDRVRawState *s = bs->opaque;
206 s->type = FTYPE_FILE;
207 return raw_open_common(bs, filename, flags, 0);
210 /* XXX: use host sector size if necessary with:
211 #ifdef DIOCGSECTORSIZE
213 unsigned int sectorsize = 512;
214 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
215 sectorsize > bufsize)
216 bufsize = sectorsize;
218 #endif
219 #ifdef CONFIG_COCOA
220 uint32_t blockSize = 512;
221 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
222 bufsize = blockSize;
224 #endif
228 * offset and count are in bytes, but must be multiples of 512 for files
229 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
231 * This function may be called without alignment if the caller ensures
232 * that O_DIRECT is not in effect.
234 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
235 uint8_t *buf, int count)
237 BDRVRawState *s = bs->opaque;
238 int ret;
240 ret = fd_open(bs);
241 if (ret < 0)
242 return ret;
244 ret = pread(s->fd, buf, count, offset);
245 if (ret == count)
246 return ret;
248 /* Allow reads beyond the end (needed for pwrite) */
249 if ((ret == 0) && bs->growable) {
250 int64_t size = raw_getlength(bs);
251 if (offset >= size) {
252 memset(buf, 0, count);
253 return count;
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 (s->type != FTYPE_FILE) {
264 ret = pread(s->fd, buf, count, offset);
265 if (ret == count)
266 return ret;
267 ret = pread(s->fd, buf, count, offset);
268 if (ret == count)
269 return ret;
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 return (ret < 0) ? -errno : ret;
281 * offset and count are in bytes, but must be multiples of 512 for files
282 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
284 * This function may be called without alignment if the caller ensures
285 * that O_DIRECT is not in effect.
287 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
288 const uint8_t *buf, int count)
290 BDRVRawState *s = bs->opaque;
291 int ret;
293 ret = fd_open(bs);
294 if (ret < 0)
295 return -errno;
297 ret = pwrite(s->fd, buf, count, offset);
298 if (ret == count)
299 return ret;
301 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
302 "] write failed %d : %d = %s\n",
303 s->fd, bs->filename, offset, buf, count,
304 bs->total_sectors, ret, errno, strerror(errno));
306 return (ret < 0) ? -errno : ret;
311 * offset and count are in bytes and possibly not aligned. For files opened
312 * with O_DIRECT, necessary alignments are ensured before calling
313 * raw_pread_aligned to do the actual read.
315 static int raw_pread(BlockDriverState *bs, int64_t offset,
316 uint8_t *buf, int count)
318 BDRVRawState *s = bs->opaque;
319 int size, ret, shift, sum;
321 sum = 0;
323 if (s->aligned_buf != NULL) {
325 if (offset & 0x1ff) {
326 /* align offset on a 512 bytes boundary */
328 shift = offset & 0x1ff;
329 size = (shift + count + 0x1ff) & ~0x1ff;
330 if (size > ALIGNED_BUFFER_SIZE)
331 size = ALIGNED_BUFFER_SIZE;
332 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
333 if (ret < 0)
334 return ret;
336 size = 512 - shift;
337 if (size > count)
338 size = count;
339 memcpy(buf, s->aligned_buf + shift, size);
341 buf += size;
342 offset += size;
343 count -= size;
344 sum += size;
346 if (count == 0)
347 return sum;
349 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
351 /* read on aligned buffer */
353 while (count) {
355 size = (count + 0x1ff) & ~0x1ff;
356 if (size > ALIGNED_BUFFER_SIZE)
357 size = ALIGNED_BUFFER_SIZE;
359 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
360 if (ret < 0) {
361 return ret;
362 } else if (ret == 0) {
363 fprintf(stderr, "raw_pread: read beyond end of file\n");
364 abort();
367 size = ret;
368 if (size > count)
369 size = count;
371 memcpy(buf, s->aligned_buf, size);
373 buf += size;
374 offset += size;
375 count -= size;
376 sum += size;
379 return sum;
383 return raw_pread_aligned(bs, offset, buf, count) + sum;
386 static int raw_read(BlockDriverState *bs, int64_t sector_num,
387 uint8_t *buf, int nb_sectors)
389 int ret;
391 ret = raw_pread(bs, sector_num * BDRV_SECTOR_SIZE, buf,
392 nb_sectors * BDRV_SECTOR_SIZE);
393 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
394 ret = 0;
395 return ret;
399 * offset and count are in bytes and possibly not aligned. For files opened
400 * with O_DIRECT, necessary alignments are ensured before calling
401 * raw_pwrite_aligned to do the actual write.
403 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
404 const uint8_t *buf, int count)
406 BDRVRawState *s = bs->opaque;
407 int size, ret, shift, sum;
409 sum = 0;
411 if (s->aligned_buf != NULL) {
413 if (offset & 0x1ff) {
414 /* align offset on a 512 bytes boundary */
415 shift = offset & 0x1ff;
416 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
417 if (ret < 0)
418 return ret;
420 size = 512 - shift;
421 if (size > count)
422 size = count;
423 memcpy(s->aligned_buf + shift, buf, size);
425 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
426 if (ret < 0)
427 return ret;
429 buf += size;
430 offset += size;
431 count -= size;
432 sum += size;
434 if (count == 0)
435 return sum;
437 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
439 while ((size = (count & ~0x1ff)) != 0) {
441 if (size > ALIGNED_BUFFER_SIZE)
442 size = ALIGNED_BUFFER_SIZE;
444 memcpy(s->aligned_buf, buf, size);
446 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
447 if (ret < 0)
448 return ret;
450 buf += ret;
451 offset += ret;
452 count -= ret;
453 sum += ret;
455 /* here, count < 512 because (count & ~0x1ff) == 0 */
456 if (count) {
457 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
458 if (ret < 0)
459 return ret;
460 memcpy(s->aligned_buf, buf, count);
462 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
463 if (ret < 0)
464 return ret;
465 if (count < ret)
466 ret = count;
468 sum += ret;
470 return sum;
473 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
476 static int raw_write(BlockDriverState *bs, int64_t sector_num,
477 const uint8_t *buf, int nb_sectors)
479 int ret;
480 ret = raw_pwrite(bs, sector_num * BDRV_SECTOR_SIZE, buf,
481 nb_sectors * BDRV_SECTOR_SIZE);
482 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
483 ret = 0;
484 return ret;
488 * Check if all memory in this vector is sector aligned.
490 static int qiov_is_aligned(QEMUIOVector *qiov)
492 int i;
494 for (i = 0; i < qiov->niov; i++) {
495 if ((uintptr_t) qiov->iov[i].iov_base % BDRV_SECTOR_SIZE) {
496 return 0;
500 return 1;
503 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
504 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
505 BlockDriverCompletionFunc *cb, void *opaque, int type)
507 BDRVRawState *s = bs->opaque;
509 if (fd_open(bs) < 0)
510 return NULL;
513 * If O_DIRECT is used the buffer needs to be aligned on a sector
514 * boundary. Check if this is the case or telll the low-level
515 * driver that it needs to copy the buffer.
517 if (s->aligned_buf) {
518 if (!qiov_is_aligned(qiov)) {
519 type |= QEMU_AIO_MISALIGNED;
520 #ifdef CONFIG_LINUX_AIO
521 } else if (s->use_aio) {
522 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
523 nb_sectors, cb, opaque, type);
524 #endif
528 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
529 cb, opaque, type);
532 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
533 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
534 BlockDriverCompletionFunc *cb, void *opaque)
536 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
537 cb, opaque, QEMU_AIO_READ);
540 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
541 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
542 BlockDriverCompletionFunc *cb, void *opaque)
544 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
545 cb, opaque, QEMU_AIO_WRITE);
548 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
549 BlockDriverCompletionFunc *cb, void *opaque)
551 BDRVRawState *s = bs->opaque;
553 if (fd_open(bs) < 0)
554 return NULL;
556 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
559 static void raw_close(BlockDriverState *bs)
561 BDRVRawState *s = bs->opaque;
562 if (s->fd >= 0) {
563 close(s->fd);
564 s->fd = -1;
565 if (s->aligned_buf != NULL)
566 qemu_vfree(s->aligned_buf);
570 static int raw_truncate(BlockDriverState *bs, int64_t offset)
572 BDRVRawState *s = bs->opaque;
573 if (s->type != FTYPE_FILE)
574 return -ENOTSUP;
575 if (ftruncate(s->fd, offset) < 0)
576 return -errno;
577 return 0;
580 #ifdef __OpenBSD__
581 static int64_t raw_getlength(BlockDriverState *bs)
583 BDRVRawState *s = bs->opaque;
584 int fd = s->fd;
585 struct stat st;
587 if (fstat(fd, &st))
588 return -1;
589 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
590 struct disklabel dl;
592 if (ioctl(fd, DIOCGDINFO, &dl))
593 return -1;
594 return (uint64_t)dl.d_secsize *
595 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
596 } else
597 return st.st_size;
599 #elif defined(__sun__)
600 static int64_t raw_getlength(BlockDriverState *bs)
602 BDRVRawState *s = bs->opaque;
603 struct dk_minfo minfo;
604 int ret;
606 ret = fd_open(bs);
607 if (ret < 0) {
608 return ret;
612 * Use the DKIOCGMEDIAINFO ioctl to read the size.
614 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
615 if (ret != -1) {
616 return minfo.dki_lbsize * minfo.dki_capacity;
620 * There are reports that lseek on some devices fails, but
621 * irc discussion said that contingency on contingency was overkill.
623 return lseek(s->fd, 0, SEEK_END);
625 #elif defined(CONFIG_BSD)
626 static int64_t raw_getlength(BlockDriverState *bs)
628 BDRVRawState *s = bs->opaque;
629 int fd = s->fd;
630 int64_t size;
631 struct stat sb;
632 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
633 int reopened = 0;
634 #endif
635 int ret;
637 ret = fd_open(bs);
638 if (ret < 0)
639 return ret;
641 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
642 again:
643 #endif
644 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
645 #ifdef DIOCGMEDIASIZE
646 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
647 #elif defined(DIOCGPART)
649 struct partinfo pi;
650 if (ioctl(fd, DIOCGPART, &pi) == 0)
651 size = pi.media_size;
652 else
653 size = 0;
655 if (size == 0)
656 #endif
657 #ifdef CONFIG_COCOA
658 size = LONG_LONG_MAX;
659 #else
660 size = lseek(fd, 0LL, SEEK_END);
661 #endif
662 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
663 switch(s->type) {
664 case FTYPE_CD:
665 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
666 if (size == 2048LL * (unsigned)-1)
667 size = 0;
668 /* XXX no disc? maybe we need to reopen... */
669 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
670 reopened = 1;
671 goto again;
674 #endif
675 } else {
676 size = lseek(fd, 0, SEEK_END);
678 return size;
680 #else
681 static int64_t raw_getlength(BlockDriverState *bs)
683 BDRVRawState *s = bs->opaque;
684 int ret;
686 ret = fd_open(bs);
687 if (ret < 0) {
688 return ret;
691 return lseek(s->fd, 0, SEEK_END);
693 #endif
695 static int raw_create(const char *filename, QEMUOptionParameter *options)
697 int fd;
698 int result = 0;
699 int64_t total_size = 0;
701 /* Read out options */
702 while (options && options->name) {
703 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
704 total_size = options->value.n / BDRV_SECTOR_SIZE;
706 options++;
709 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
710 0644);
711 if (fd < 0) {
712 result = -errno;
713 } else {
714 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
715 result = -errno;
717 if (close(fd) != 0) {
718 result = -errno;
721 return result;
724 static void raw_flush(BlockDriverState *bs)
726 BDRVRawState *s = bs->opaque;
727 qemu_fdatasync(s->fd);
731 static QEMUOptionParameter raw_create_options[] = {
733 .name = BLOCK_OPT_SIZE,
734 .type = OPT_SIZE,
735 .help = "Virtual disk size"
737 { NULL }
740 static BlockDriver bdrv_file = {
741 .format_name = "file",
742 .protocol_name = "file",
743 .instance_size = sizeof(BDRVRawState),
744 .bdrv_probe = NULL, /* no probe for protocols */
745 .bdrv_file_open = raw_open,
746 .bdrv_read = raw_read,
747 .bdrv_write = raw_write,
748 .bdrv_close = raw_close,
749 .bdrv_create = raw_create,
750 .bdrv_flush = raw_flush,
752 .bdrv_aio_readv = raw_aio_readv,
753 .bdrv_aio_writev = raw_aio_writev,
754 .bdrv_aio_flush = raw_aio_flush,
756 .bdrv_truncate = raw_truncate,
757 .bdrv_getlength = raw_getlength,
759 .create_options = raw_create_options,
762 /***********************************************/
763 /* host device */
765 #ifdef CONFIG_COCOA
766 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
767 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
769 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
771 kern_return_t kernResult;
772 mach_port_t masterPort;
773 CFMutableDictionaryRef classesToMatch;
775 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
776 if ( KERN_SUCCESS != kernResult ) {
777 printf( "IOMasterPort returned %d\n", kernResult );
780 classesToMatch = IOServiceMatching( kIOCDMediaClass );
781 if ( classesToMatch == NULL ) {
782 printf( "IOServiceMatching returned a NULL dictionary.\n" );
783 } else {
784 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
786 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
787 if ( KERN_SUCCESS != kernResult )
789 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
792 return kernResult;
795 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
797 io_object_t nextMedia;
798 kern_return_t kernResult = KERN_FAILURE;
799 *bsdPath = '\0';
800 nextMedia = IOIteratorNext( mediaIterator );
801 if ( nextMedia )
803 CFTypeRef bsdPathAsCFString;
804 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
805 if ( bsdPathAsCFString ) {
806 size_t devPathLength;
807 strcpy( bsdPath, _PATH_DEV );
808 strcat( bsdPath, "r" );
809 devPathLength = strlen( bsdPath );
810 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
811 kernResult = KERN_SUCCESS;
813 CFRelease( bsdPathAsCFString );
815 IOObjectRelease( nextMedia );
818 return kernResult;
821 #endif
823 static int hdev_probe_device(const char *filename)
825 struct stat st;
827 /* allow a dedicated CD-ROM driver to match with a higher priority */
828 if (strstart(filename, "/dev/cdrom", NULL))
829 return 50;
831 if (stat(filename, &st) >= 0 &&
832 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
833 return 100;
836 return 0;
839 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
841 BDRVRawState *s = bs->opaque;
843 #ifdef CONFIG_COCOA
844 if (strstart(filename, "/dev/cdrom", NULL)) {
845 kern_return_t kernResult;
846 io_iterator_t mediaIterator;
847 char bsdPath[ MAXPATHLEN ];
848 int fd;
850 kernResult = FindEjectableCDMedia( &mediaIterator );
851 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
853 if ( bsdPath[ 0 ] != '\0' ) {
854 strcat(bsdPath,"s0");
855 /* some CDs don't have a partition 0 */
856 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
857 if (fd < 0) {
858 bsdPath[strlen(bsdPath)-1] = '1';
859 } else {
860 close(fd);
862 filename = bsdPath;
865 if ( mediaIterator )
866 IOObjectRelease( mediaIterator );
868 #endif
870 s->type = FTYPE_FILE;
871 #if defined(__linux__)
873 char resolved_path[ MAXPATHLEN ], *temp;
875 temp = realpath(filename, resolved_path);
876 if (temp && strstart(temp, "/dev/sg", NULL)) {
877 bs->sg = 1;
880 #endif
882 return raw_open_common(bs, filename, flags, 0);
885 #if defined(__linux__)
886 /* Note: we do not have a reliable method to detect if the floppy is
887 present. The current method is to try to open the floppy at every
888 I/O and to keep it opened during a few hundreds of ms. */
889 static int fd_open(BlockDriverState *bs)
891 BDRVRawState *s = bs->opaque;
892 int last_media_present;
894 if (s->type != FTYPE_FD)
895 return 0;
896 last_media_present = (s->fd >= 0);
897 if (s->fd >= 0 &&
898 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
899 close(s->fd);
900 s->fd = -1;
901 #ifdef DEBUG_FLOPPY
902 printf("Floppy closed\n");
903 #endif
905 if (s->fd < 0) {
906 if (s->fd_got_error &&
907 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
908 #ifdef DEBUG_FLOPPY
909 printf("No floppy (open delayed)\n");
910 #endif
911 return -EIO;
913 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
914 if (s->fd < 0) {
915 s->fd_error_time = qemu_get_clock(rt_clock);
916 s->fd_got_error = 1;
917 if (last_media_present)
918 s->fd_media_changed = 1;
919 #ifdef DEBUG_FLOPPY
920 printf("No floppy\n");
921 #endif
922 return -EIO;
924 #ifdef DEBUG_FLOPPY
925 printf("Floppy opened\n");
926 #endif
928 if (!last_media_present)
929 s->fd_media_changed = 1;
930 s->fd_open_time = qemu_get_clock(rt_clock);
931 s->fd_got_error = 0;
932 return 0;
935 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
937 BDRVRawState *s = bs->opaque;
939 return ioctl(s->fd, req, buf);
942 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
943 unsigned long int req, void *buf,
944 BlockDriverCompletionFunc *cb, void *opaque)
946 BDRVRawState *s = bs->opaque;
948 if (fd_open(bs) < 0)
949 return NULL;
950 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
953 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
954 static int fd_open(BlockDriverState *bs)
956 BDRVRawState *s = bs->opaque;
958 /* this is just to ensure s->fd is sane (its called by io ops) */
959 if (s->fd >= 0)
960 return 0;
961 return -EIO;
963 #else /* !linux && !FreeBSD */
965 static int fd_open(BlockDriverState *bs)
967 return 0;
970 #endif /* !linux && !FreeBSD */
972 static int hdev_create(const char *filename, QEMUOptionParameter *options)
974 int fd;
975 int ret = 0;
976 struct stat stat_buf;
977 int64_t total_size = 0;
979 /* Read out options */
980 while (options && options->name) {
981 if (!strcmp(options->name, "size")) {
982 total_size = options->value.n / BDRV_SECTOR_SIZE;
984 options++;
987 fd = open(filename, O_WRONLY | O_BINARY);
988 if (fd < 0)
989 return -errno;
991 if (fstat(fd, &stat_buf) < 0)
992 ret = -errno;
993 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
994 ret = -ENODEV;
995 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
996 ret = -ENOSPC;
998 close(fd);
999 return ret;
1002 static int hdev_has_zero_init(BlockDriverState *bs)
1004 return 0;
1007 static BlockDriver bdrv_host_device = {
1008 .format_name = "host_device",
1009 .protocol_name = "host_device",
1010 .instance_size = sizeof(BDRVRawState),
1011 .bdrv_probe_device = hdev_probe_device,
1012 .bdrv_file_open = hdev_open,
1013 .bdrv_close = raw_close,
1014 .bdrv_create = hdev_create,
1015 .create_options = raw_create_options,
1016 .bdrv_has_zero_init = hdev_has_zero_init,
1017 .bdrv_flush = raw_flush,
1019 .bdrv_aio_readv = raw_aio_readv,
1020 .bdrv_aio_writev = raw_aio_writev,
1021 .bdrv_aio_flush = raw_aio_flush,
1023 .bdrv_read = raw_read,
1024 .bdrv_write = raw_write,
1025 .bdrv_getlength = raw_getlength,
1027 /* generic scsi device */
1028 #ifdef __linux__
1029 .bdrv_ioctl = hdev_ioctl,
1030 .bdrv_aio_ioctl = hdev_aio_ioctl,
1031 #endif
1034 #ifdef __linux__
1035 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1037 BDRVRawState *s = bs->opaque;
1038 int ret;
1040 s->type = FTYPE_FD;
1042 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1043 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1044 if (ret)
1045 return ret;
1047 /* close fd so that we can reopen it as needed */
1048 close(s->fd);
1049 s->fd = -1;
1050 s->fd_media_changed = 1;
1052 return 0;
1055 static int floppy_probe_device(const char *filename)
1057 int fd, ret;
1058 int prio = 0;
1059 struct floppy_struct fdparam;
1061 if (strstart(filename, "/dev/fd", NULL))
1062 prio = 50;
1064 fd = open(filename, O_RDONLY | O_NONBLOCK);
1065 if (fd < 0) {
1066 goto out;
1069 /* Attempt to detect via a floppy specific ioctl */
1070 ret = ioctl(fd, FDGETPRM, &fdparam);
1071 if (ret >= 0)
1072 prio = 100;
1074 close(fd);
1075 out:
1076 return prio;
1080 static int floppy_is_inserted(BlockDriverState *bs)
1082 return fd_open(bs) >= 0;
1085 static int floppy_media_changed(BlockDriverState *bs)
1087 BDRVRawState *s = bs->opaque;
1088 int ret;
1091 * XXX: we do not have a true media changed indication.
1092 * It does not work if the floppy is changed without trying to read it.
1094 fd_open(bs);
1095 ret = s->fd_media_changed;
1096 s->fd_media_changed = 0;
1097 #ifdef DEBUG_FLOPPY
1098 printf("Floppy changed=%d\n", ret);
1099 #endif
1100 return ret;
1103 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1105 BDRVRawState *s = bs->opaque;
1106 int fd;
1108 if (s->fd >= 0) {
1109 close(s->fd);
1110 s->fd = -1;
1112 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1113 if (fd >= 0) {
1114 if (ioctl(fd, FDEJECT, 0) < 0)
1115 perror("FDEJECT");
1116 close(fd);
1119 return 0;
1122 static BlockDriver bdrv_host_floppy = {
1123 .format_name = "host_floppy",
1124 .protocol_name = "host_floppy",
1125 .instance_size = sizeof(BDRVRawState),
1126 .bdrv_probe_device = floppy_probe_device,
1127 .bdrv_file_open = floppy_open,
1128 .bdrv_close = raw_close,
1129 .bdrv_create = hdev_create,
1130 .create_options = raw_create_options,
1131 .bdrv_has_zero_init = hdev_has_zero_init,
1132 .bdrv_flush = raw_flush,
1134 .bdrv_aio_readv = raw_aio_readv,
1135 .bdrv_aio_writev = raw_aio_writev,
1136 .bdrv_aio_flush = raw_aio_flush,
1138 .bdrv_read = raw_read,
1139 .bdrv_write = raw_write,
1140 .bdrv_getlength = raw_getlength,
1142 /* removable device support */
1143 .bdrv_is_inserted = floppy_is_inserted,
1144 .bdrv_media_changed = floppy_media_changed,
1145 .bdrv_eject = floppy_eject,
1148 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1150 BDRVRawState *s = bs->opaque;
1152 s->type = FTYPE_CD;
1154 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1155 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1158 static int cdrom_probe_device(const char *filename)
1160 int fd, ret;
1161 int prio = 0;
1163 fd = open(filename, O_RDONLY | O_NONBLOCK);
1164 if (fd < 0) {
1165 goto out;
1168 /* Attempt to detect via a CDROM specific ioctl */
1169 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1170 if (ret >= 0)
1171 prio = 100;
1173 close(fd);
1174 out:
1175 return prio;
1178 static int cdrom_is_inserted(BlockDriverState *bs)
1180 BDRVRawState *s = bs->opaque;
1181 int ret;
1183 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1184 if (ret == CDS_DISC_OK)
1185 return 1;
1186 return 0;
1189 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1191 BDRVRawState *s = bs->opaque;
1193 if (eject_flag) {
1194 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1195 perror("CDROMEJECT");
1196 } else {
1197 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1198 perror("CDROMEJECT");
1201 return 0;
1204 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1206 BDRVRawState *s = bs->opaque;
1208 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1210 * Note: an error can happen if the distribution automatically
1211 * mounts the CD-ROM
1213 /* perror("CDROM_LOCKDOOR"); */
1216 return 0;
1219 static BlockDriver bdrv_host_cdrom = {
1220 .format_name = "host_cdrom",
1221 .protocol_name = "host_cdrom",
1222 .instance_size = sizeof(BDRVRawState),
1223 .bdrv_probe_device = cdrom_probe_device,
1224 .bdrv_file_open = cdrom_open,
1225 .bdrv_close = raw_close,
1226 .bdrv_create = hdev_create,
1227 .create_options = raw_create_options,
1228 .bdrv_has_zero_init = hdev_has_zero_init,
1229 .bdrv_flush = raw_flush,
1231 .bdrv_aio_readv = raw_aio_readv,
1232 .bdrv_aio_writev = raw_aio_writev,
1233 .bdrv_aio_flush = raw_aio_flush,
1235 .bdrv_read = raw_read,
1236 .bdrv_write = raw_write,
1237 .bdrv_getlength = raw_getlength,
1239 /* removable device support */
1240 .bdrv_is_inserted = cdrom_is_inserted,
1241 .bdrv_eject = cdrom_eject,
1242 .bdrv_set_locked = cdrom_set_locked,
1244 /* generic scsi device */
1245 .bdrv_ioctl = hdev_ioctl,
1246 .bdrv_aio_ioctl = hdev_aio_ioctl,
1248 #endif /* __linux__ */
1250 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1251 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1253 BDRVRawState *s = bs->opaque;
1254 int ret;
1256 s->type = FTYPE_CD;
1258 ret = raw_open_common(bs, filename, flags, 0);
1259 if (ret)
1260 return ret;
1262 /* make sure the door isnt locked at this time */
1263 ioctl(s->fd, CDIOCALLOW);
1264 return 0;
1267 static int cdrom_probe_device(const char *filename)
1269 if (strstart(filename, "/dev/cd", NULL) ||
1270 strstart(filename, "/dev/acd", NULL))
1271 return 100;
1272 return 0;
1275 static int cdrom_reopen(BlockDriverState *bs)
1277 BDRVRawState *s = bs->opaque;
1278 int fd;
1281 * Force reread of possibly changed/newly loaded disc,
1282 * FreeBSD seems to not notice sometimes...
1284 if (s->fd >= 0)
1285 close(s->fd);
1286 fd = open(bs->filename, s->open_flags, 0644);
1287 if (fd < 0) {
1288 s->fd = -1;
1289 return -EIO;
1291 s->fd = fd;
1293 /* make sure the door isnt locked at this time */
1294 ioctl(s->fd, CDIOCALLOW);
1295 return 0;
1298 static int cdrom_is_inserted(BlockDriverState *bs)
1300 return raw_getlength(bs) > 0;
1303 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1305 BDRVRawState *s = bs->opaque;
1307 if (s->fd < 0)
1308 return -ENOTSUP;
1310 (void) ioctl(s->fd, CDIOCALLOW);
1312 if (eject_flag) {
1313 if (ioctl(s->fd, CDIOCEJECT) < 0)
1314 perror("CDIOCEJECT");
1315 } else {
1316 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1317 perror("CDIOCCLOSE");
1320 if (cdrom_reopen(bs) < 0)
1321 return -ENOTSUP;
1322 return 0;
1325 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1327 BDRVRawState *s = bs->opaque;
1329 if (s->fd < 0)
1330 return -ENOTSUP;
1331 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1333 * Note: an error can happen if the distribution automatically
1334 * mounts the CD-ROM
1336 /* perror("CDROM_LOCKDOOR"); */
1339 return 0;
1342 static BlockDriver bdrv_host_cdrom = {
1343 .format_name = "host_cdrom",
1344 .protocol_name = "host_cdrom",
1345 .instance_size = sizeof(BDRVRawState),
1346 .bdrv_probe_device = cdrom_probe_device,
1347 .bdrv_file_open = cdrom_open,
1348 .bdrv_close = raw_close,
1349 .bdrv_create = hdev_create,
1350 .create_options = raw_create_options,
1351 .bdrv_has_zero_init = hdev_has_zero_init,
1352 .bdrv_flush = raw_flush,
1354 .bdrv_aio_readv = raw_aio_readv,
1355 .bdrv_aio_writev = raw_aio_writev,
1356 .bdrv_aio_flush = raw_aio_flush,
1358 .bdrv_read = raw_read,
1359 .bdrv_write = raw_write,
1360 .bdrv_getlength = raw_getlength,
1362 /* removable device support */
1363 .bdrv_is_inserted = cdrom_is_inserted,
1364 .bdrv_eject = cdrom_eject,
1365 .bdrv_set_locked = cdrom_set_locked,
1367 #endif /* __FreeBSD__ */
1369 static void bdrv_file_init(void)
1372 * Register all the drivers. Note that order is important, the driver
1373 * registered last will get probed first.
1375 bdrv_register(&bdrv_file);
1376 bdrv_register(&bdrv_host_device);
1377 #ifdef __linux__
1378 bdrv_register(&bdrv_host_floppy);
1379 bdrv_register(&bdrv_host_cdrom);
1380 #endif
1381 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1382 bdrv_register(&bdrv_host_cdrom);
1383 #endif
1386 block_init(bdrv_file_init);