Revert "Add support for generating a systemtap tapset static probes"
[qemu.git] / block / raw-posix.c
blobd0960b85c4fc307de7ad632197c37b22cb8e94f5
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 /* if the FD is not accessed during that time (in ns), we try to
101 reopen it to see if the disk has been changed */
102 #define FD_OPEN_TIMEOUT (1000000000)
104 #define MAX_BLOCKSIZE 4096
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 unsigned aligned_buf_size;
123 } BDRVRawState;
125 static int fd_open(BlockDriverState *bs);
126 static int64_t raw_getlength(BlockDriverState *bs);
128 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
129 static int cdrom_reopen(BlockDriverState *bs);
130 #endif
132 static int raw_open_common(BlockDriverState *bs, const char *filename,
133 int bdrv_flags, int open_flags)
135 BDRVRawState *s = bs->opaque;
136 int fd, ret;
138 s->open_flags = open_flags | O_BINARY;
139 s->open_flags &= ~O_ACCMODE;
140 if (bdrv_flags & BDRV_O_RDWR) {
141 s->open_flags |= O_RDWR;
142 } else {
143 s->open_flags |= O_RDONLY;
146 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
147 * and O_DIRECT for no caching. */
148 if ((bdrv_flags & BDRV_O_NOCACHE))
149 s->open_flags |= O_DIRECT;
150 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
151 s->open_flags |= O_DSYNC;
153 s->fd = -1;
154 fd = qemu_open(filename, s->open_flags, 0644);
155 if (fd < 0) {
156 ret = -errno;
157 if (ret == -EROFS)
158 ret = -EACCES;
159 return ret;
161 s->fd = fd;
162 s->aligned_buf = NULL;
164 if ((bdrv_flags & BDRV_O_NOCACHE)) {
166 * Allocate a buffer for read/modify/write cycles. Chose the size
167 * pessimistically as we don't know the block size yet.
169 s->aligned_buf_size = 32 * MAX_BLOCKSIZE;
170 s->aligned_buf = qemu_memalign(MAX_BLOCKSIZE, s->aligned_buf_size);
171 if (s->aligned_buf == NULL) {
172 goto out_close;
176 #ifdef CONFIG_LINUX_AIO
177 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
178 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
180 /* We're falling back to POSIX AIO in some cases */
181 paio_init();
183 s->aio_ctx = laio_init();
184 if (!s->aio_ctx) {
185 goto out_free_buf;
187 s->use_aio = 1;
188 } else
189 #endif
191 if (paio_init() < 0) {
192 goto out_free_buf;
194 #ifdef CONFIG_LINUX_AIO
195 s->use_aio = 0;
196 #endif
199 return 0;
201 out_free_buf:
202 qemu_vfree(s->aligned_buf);
203 out_close:
204 close(fd);
205 return -errno;
208 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
210 BDRVRawState *s = bs->opaque;
212 s->type = FTYPE_FILE;
213 return raw_open_common(bs, filename, flags, 0);
216 /* XXX: use host sector size if necessary with:
217 #ifdef DIOCGSECTORSIZE
219 unsigned int sectorsize = 512;
220 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
221 sectorsize > bufsize)
222 bufsize = sectorsize;
224 #endif
225 #ifdef CONFIG_COCOA
226 uint32_t blockSize = 512;
227 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
228 bufsize = blockSize;
230 #endif
234 * offset and count are in bytes, but must be multiples of 512 for files
235 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
237 * This function may be called without alignment if the caller ensures
238 * that O_DIRECT is not in effect.
240 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
241 uint8_t *buf, int count)
243 BDRVRawState *s = bs->opaque;
244 int ret;
246 ret = fd_open(bs);
247 if (ret < 0)
248 return ret;
250 ret = pread(s->fd, buf, count, offset);
251 if (ret == count)
252 return ret;
254 /* Allow reads beyond the end (needed for pwrite) */
255 if ((ret == 0) && bs->growable) {
256 int64_t size = raw_getlength(bs);
257 if (offset >= size) {
258 memset(buf, 0, count);
259 return count;
263 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
264 "] read failed %d : %d = %s\n",
265 s->fd, bs->filename, offset, buf, count,
266 bs->total_sectors, ret, errno, strerror(errno));
268 /* Try harder for CDrom. */
269 if (s->type != FTYPE_FILE) {
270 ret = pread(s->fd, buf, count, offset);
271 if (ret == count)
272 return ret;
273 ret = pread(s->fd, buf, count, offset);
274 if (ret == count)
275 return ret;
277 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
278 "] retry read failed %d : %d = %s\n",
279 s->fd, bs->filename, offset, buf, count,
280 bs->total_sectors, ret, errno, strerror(errno));
283 return (ret < 0) ? -errno : ret;
287 * offset and count are in bytes, but must be multiples of the sector size
288 * for files opened with O_DIRECT. buf must be aligned to sector size bytes
289 * then.
291 * This function may be called without alignment if the caller ensures
292 * that O_DIRECT is not in effect.
294 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
295 const uint8_t *buf, int count)
297 BDRVRawState *s = bs->opaque;
298 int ret;
300 ret = fd_open(bs);
301 if (ret < 0)
302 return -errno;
304 ret = pwrite(s->fd, buf, count, offset);
305 if (ret == count)
306 return ret;
308 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
309 "] write failed %d : %d = %s\n",
310 s->fd, bs->filename, offset, buf, count,
311 bs->total_sectors, ret, errno, strerror(errno));
313 return (ret < 0) ? -errno : ret;
318 * offset and count are in bytes and possibly not aligned. For files opened
319 * with O_DIRECT, necessary alignments are ensured before calling
320 * raw_pread_aligned to do the actual read.
322 static int raw_pread(BlockDriverState *bs, int64_t offset,
323 uint8_t *buf, int count)
325 BDRVRawState *s = bs->opaque;
326 unsigned sector_mask = bs->buffer_alignment - 1;
327 int size, ret, shift, sum;
329 sum = 0;
331 if (s->aligned_buf != NULL) {
333 if (offset & sector_mask) {
334 /* align offset on a sector size bytes boundary */
336 shift = offset & sector_mask;
337 size = (shift + count + sector_mask) & ~sector_mask;
338 if (size > s->aligned_buf_size)
339 size = s->aligned_buf_size;
340 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
341 if (ret < 0)
342 return ret;
344 size = bs->buffer_alignment - shift;
345 if (size > count)
346 size = count;
347 memcpy(buf, s->aligned_buf + shift, size);
349 buf += size;
350 offset += size;
351 count -= size;
352 sum += size;
354 if (count == 0)
355 return sum;
357 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
359 /* read on aligned buffer */
361 while (count) {
363 size = (count + sector_mask) & ~sector_mask;
364 if (size > s->aligned_buf_size)
365 size = s->aligned_buf_size;
367 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
368 if (ret < 0) {
369 return ret;
370 } else if (ret == 0) {
371 fprintf(stderr, "raw_pread: read beyond end of file\n");
372 abort();
375 size = ret;
376 if (size > count)
377 size = count;
379 memcpy(buf, s->aligned_buf, size);
381 buf += size;
382 offset += size;
383 count -= size;
384 sum += size;
387 return sum;
391 return raw_pread_aligned(bs, offset, buf, count) + sum;
394 static int raw_read(BlockDriverState *bs, int64_t sector_num,
395 uint8_t *buf, int nb_sectors)
397 int ret;
399 ret = raw_pread(bs, sector_num * BDRV_SECTOR_SIZE, buf,
400 nb_sectors * BDRV_SECTOR_SIZE);
401 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
402 ret = 0;
403 return ret;
407 * offset and count are in bytes and possibly not aligned. For files opened
408 * with O_DIRECT, necessary alignments are ensured before calling
409 * raw_pwrite_aligned to do the actual write.
411 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
412 const uint8_t *buf, int count)
414 BDRVRawState *s = bs->opaque;
415 unsigned sector_mask = bs->buffer_alignment - 1;
416 int size, ret, shift, sum;
418 sum = 0;
420 if (s->aligned_buf != NULL) {
422 if (offset & sector_mask) {
423 /* align offset on a sector size bytes boundary */
424 shift = offset & sector_mask;
425 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf,
426 bs->buffer_alignment);
427 if (ret < 0)
428 return ret;
430 size = bs->buffer_alignment - shift;
431 if (size > count)
432 size = count;
433 memcpy(s->aligned_buf + shift, buf, size);
435 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf,
436 bs->buffer_alignment);
437 if (ret < 0)
438 return ret;
440 buf += size;
441 offset += size;
442 count -= size;
443 sum += size;
445 if (count == 0)
446 return sum;
448 if (count & sector_mask || (uintptr_t) buf & sector_mask) {
450 while ((size = (count & ~sector_mask)) != 0) {
452 if (size > s->aligned_buf_size)
453 size = s->aligned_buf_size;
455 memcpy(s->aligned_buf, buf, size);
457 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
458 if (ret < 0)
459 return ret;
461 buf += ret;
462 offset += ret;
463 count -= ret;
464 sum += ret;
466 /* here, count < 512 because (count & ~sector_mask) == 0 */
467 if (count) {
468 ret = raw_pread_aligned(bs, offset, s->aligned_buf,
469 bs->buffer_alignment);
470 if (ret < 0)
471 return ret;
472 memcpy(s->aligned_buf, buf, count);
474 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf,
475 bs->buffer_alignment);
476 if (ret < 0)
477 return ret;
478 if (count < ret)
479 ret = count;
481 sum += ret;
483 return sum;
486 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
489 static int raw_write(BlockDriverState *bs, int64_t sector_num,
490 const uint8_t *buf, int nb_sectors)
492 int ret;
493 ret = raw_pwrite(bs, sector_num * BDRV_SECTOR_SIZE, buf,
494 nb_sectors * BDRV_SECTOR_SIZE);
495 if (ret == (nb_sectors * BDRV_SECTOR_SIZE))
496 ret = 0;
497 return ret;
501 * Check if all memory in this vector is sector aligned.
503 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
505 int i;
507 for (i = 0; i < qiov->niov; i++) {
508 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
509 return 0;
513 return 1;
516 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
517 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
518 BlockDriverCompletionFunc *cb, void *opaque, int type)
520 BDRVRawState *s = bs->opaque;
522 if (fd_open(bs) < 0)
523 return NULL;
526 * If O_DIRECT is used the buffer needs to be aligned on a sector
527 * boundary. Check if this is the case or telll the low-level
528 * driver that it needs to copy the buffer.
530 if (s->aligned_buf) {
531 if (!qiov_is_aligned(bs, qiov)) {
532 type |= QEMU_AIO_MISALIGNED;
533 #ifdef CONFIG_LINUX_AIO
534 } else if (s->use_aio) {
535 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
536 nb_sectors, cb, opaque, type);
537 #endif
541 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
542 cb, opaque, type);
545 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
546 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
547 BlockDriverCompletionFunc *cb, void *opaque)
549 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
550 cb, opaque, QEMU_AIO_READ);
553 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
554 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
555 BlockDriverCompletionFunc *cb, void *opaque)
557 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
558 cb, opaque, QEMU_AIO_WRITE);
561 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
562 BlockDriverCompletionFunc *cb, void *opaque)
564 BDRVRawState *s = bs->opaque;
566 if (fd_open(bs) < 0)
567 return NULL;
569 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
572 static void raw_close(BlockDriverState *bs)
574 BDRVRawState *s = bs->opaque;
575 if (s->fd >= 0) {
576 close(s->fd);
577 s->fd = -1;
578 if (s->aligned_buf != NULL)
579 qemu_vfree(s->aligned_buf);
583 static int raw_truncate(BlockDriverState *bs, int64_t offset)
585 BDRVRawState *s = bs->opaque;
586 if (s->type != FTYPE_FILE)
587 return -ENOTSUP;
588 if (ftruncate(s->fd, offset) < 0)
589 return -errno;
590 return 0;
593 #ifdef __OpenBSD__
594 static int64_t raw_getlength(BlockDriverState *bs)
596 BDRVRawState *s = bs->opaque;
597 int fd = s->fd;
598 struct stat st;
600 if (fstat(fd, &st))
601 return -1;
602 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
603 struct disklabel dl;
605 if (ioctl(fd, DIOCGDINFO, &dl))
606 return -1;
607 return (uint64_t)dl.d_secsize *
608 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
609 } else
610 return st.st_size;
612 #elif defined(__sun__)
613 static int64_t raw_getlength(BlockDriverState *bs)
615 BDRVRawState *s = bs->opaque;
616 struct dk_minfo minfo;
617 int ret;
619 ret = fd_open(bs);
620 if (ret < 0) {
621 return ret;
625 * Use the DKIOCGMEDIAINFO ioctl to read the size.
627 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
628 if (ret != -1) {
629 return minfo.dki_lbsize * minfo.dki_capacity;
633 * There are reports that lseek on some devices fails, but
634 * irc discussion said that contingency on contingency was overkill.
636 return lseek(s->fd, 0, SEEK_END);
638 #elif defined(CONFIG_BSD)
639 static int64_t raw_getlength(BlockDriverState *bs)
641 BDRVRawState *s = bs->opaque;
642 int fd = s->fd;
643 int64_t size;
644 struct stat sb;
645 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
646 int reopened = 0;
647 #endif
648 int ret;
650 ret = fd_open(bs);
651 if (ret < 0)
652 return ret;
654 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
655 again:
656 #endif
657 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
658 #ifdef DIOCGMEDIASIZE
659 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
660 #elif defined(DIOCGPART)
662 struct partinfo pi;
663 if (ioctl(fd, DIOCGPART, &pi) == 0)
664 size = pi.media_size;
665 else
666 size = 0;
668 if (size == 0)
669 #endif
670 #ifdef CONFIG_COCOA
671 size = LONG_LONG_MAX;
672 #else
673 size = lseek(fd, 0LL, SEEK_END);
674 #endif
675 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
676 switch(s->type) {
677 case FTYPE_CD:
678 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
679 if (size == 2048LL * (unsigned)-1)
680 size = 0;
681 /* XXX no disc? maybe we need to reopen... */
682 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
683 reopened = 1;
684 goto again;
687 #endif
688 } else {
689 size = lseek(fd, 0, SEEK_END);
691 return size;
693 #else
694 static int64_t raw_getlength(BlockDriverState *bs)
696 BDRVRawState *s = bs->opaque;
697 int ret;
699 ret = fd_open(bs);
700 if (ret < 0) {
701 return ret;
704 return lseek(s->fd, 0, SEEK_END);
706 #endif
708 static int raw_create(const char *filename, QEMUOptionParameter *options)
710 int fd;
711 int result = 0;
712 int64_t total_size = 0;
714 /* Read out options */
715 while (options && options->name) {
716 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
717 total_size = options->value.n / BDRV_SECTOR_SIZE;
719 options++;
722 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
723 0644);
724 if (fd < 0) {
725 result = -errno;
726 } else {
727 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
728 result = -errno;
730 if (close(fd) != 0) {
731 result = -errno;
734 return result;
737 static int raw_flush(BlockDriverState *bs)
739 BDRVRawState *s = bs->opaque;
740 return qemu_fdatasync(s->fd);
744 static QEMUOptionParameter raw_create_options[] = {
746 .name = BLOCK_OPT_SIZE,
747 .type = OPT_SIZE,
748 .help = "Virtual disk size"
750 { NULL }
753 static BlockDriver bdrv_file = {
754 .format_name = "file",
755 .protocol_name = "file",
756 .instance_size = sizeof(BDRVRawState),
757 .bdrv_probe = NULL, /* no probe for protocols */
758 .bdrv_file_open = raw_open,
759 .bdrv_read = raw_read,
760 .bdrv_write = raw_write,
761 .bdrv_close = raw_close,
762 .bdrv_create = raw_create,
763 .bdrv_flush = raw_flush,
765 .bdrv_aio_readv = raw_aio_readv,
766 .bdrv_aio_writev = raw_aio_writev,
767 .bdrv_aio_flush = raw_aio_flush,
769 .bdrv_truncate = raw_truncate,
770 .bdrv_getlength = raw_getlength,
772 .create_options = raw_create_options,
775 /***********************************************/
776 /* host device */
778 #ifdef CONFIG_COCOA
779 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
780 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
782 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
784 kern_return_t kernResult;
785 mach_port_t masterPort;
786 CFMutableDictionaryRef classesToMatch;
788 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
789 if ( KERN_SUCCESS != kernResult ) {
790 printf( "IOMasterPort returned %d\n", kernResult );
793 classesToMatch = IOServiceMatching( kIOCDMediaClass );
794 if ( classesToMatch == NULL ) {
795 printf( "IOServiceMatching returned a NULL dictionary.\n" );
796 } else {
797 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
799 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
800 if ( KERN_SUCCESS != kernResult )
802 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
805 return kernResult;
808 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
810 io_object_t nextMedia;
811 kern_return_t kernResult = KERN_FAILURE;
812 *bsdPath = '\0';
813 nextMedia = IOIteratorNext( mediaIterator );
814 if ( nextMedia )
816 CFTypeRef bsdPathAsCFString;
817 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
818 if ( bsdPathAsCFString ) {
819 size_t devPathLength;
820 strcpy( bsdPath, _PATH_DEV );
821 strcat( bsdPath, "r" );
822 devPathLength = strlen( bsdPath );
823 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
824 kernResult = KERN_SUCCESS;
826 CFRelease( bsdPathAsCFString );
828 IOObjectRelease( nextMedia );
831 return kernResult;
834 #endif
836 static int hdev_probe_device(const char *filename)
838 struct stat st;
840 /* allow a dedicated CD-ROM driver to match with a higher priority */
841 if (strstart(filename, "/dev/cdrom", NULL))
842 return 50;
844 if (stat(filename, &st) >= 0 &&
845 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
846 return 100;
849 return 0;
852 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
854 BDRVRawState *s = bs->opaque;
856 #ifdef CONFIG_COCOA
857 if (strstart(filename, "/dev/cdrom", NULL)) {
858 kern_return_t kernResult;
859 io_iterator_t mediaIterator;
860 char bsdPath[ MAXPATHLEN ];
861 int fd;
863 kernResult = FindEjectableCDMedia( &mediaIterator );
864 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
866 if ( bsdPath[ 0 ] != '\0' ) {
867 strcat(bsdPath,"s0");
868 /* some CDs don't have a partition 0 */
869 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
870 if (fd < 0) {
871 bsdPath[strlen(bsdPath)-1] = '1';
872 } else {
873 close(fd);
875 filename = bsdPath;
878 if ( mediaIterator )
879 IOObjectRelease( mediaIterator );
881 #endif
883 s->type = FTYPE_FILE;
884 #if defined(__linux__)
886 char resolved_path[ MAXPATHLEN ], *temp;
888 temp = realpath(filename, resolved_path);
889 if (temp && strstart(temp, "/dev/sg", NULL)) {
890 bs->sg = 1;
893 #endif
895 return raw_open_common(bs, filename, flags, 0);
898 #if defined(__linux__)
899 /* Note: we do not have a reliable method to detect if the floppy is
900 present. The current method is to try to open the floppy at every
901 I/O and to keep it opened during a few hundreds of ms. */
902 static int fd_open(BlockDriverState *bs)
904 BDRVRawState *s = bs->opaque;
905 int last_media_present;
907 if (s->type != FTYPE_FD)
908 return 0;
909 last_media_present = (s->fd >= 0);
910 if (s->fd >= 0 &&
911 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
912 close(s->fd);
913 s->fd = -1;
914 #ifdef DEBUG_FLOPPY
915 printf("Floppy closed\n");
916 #endif
918 if (s->fd < 0) {
919 if (s->fd_got_error &&
920 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
921 #ifdef DEBUG_FLOPPY
922 printf("No floppy (open delayed)\n");
923 #endif
924 return -EIO;
926 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
927 if (s->fd < 0) {
928 s->fd_error_time = get_clock();
929 s->fd_got_error = 1;
930 if (last_media_present)
931 s->fd_media_changed = 1;
932 #ifdef DEBUG_FLOPPY
933 printf("No floppy\n");
934 #endif
935 return -EIO;
937 #ifdef DEBUG_FLOPPY
938 printf("Floppy opened\n");
939 #endif
941 if (!last_media_present)
942 s->fd_media_changed = 1;
943 s->fd_open_time = get_clock();
944 s->fd_got_error = 0;
945 return 0;
948 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
950 BDRVRawState *s = bs->opaque;
952 return ioctl(s->fd, req, buf);
955 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
956 unsigned long int req, void *buf,
957 BlockDriverCompletionFunc *cb, void *opaque)
959 BDRVRawState *s = bs->opaque;
961 if (fd_open(bs) < 0)
962 return NULL;
963 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
966 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
967 static int fd_open(BlockDriverState *bs)
969 BDRVRawState *s = bs->opaque;
971 /* this is just to ensure s->fd is sane (its called by io ops) */
972 if (s->fd >= 0)
973 return 0;
974 return -EIO;
976 #else /* !linux && !FreeBSD */
978 static int fd_open(BlockDriverState *bs)
980 return 0;
983 #endif /* !linux && !FreeBSD */
985 static int hdev_create(const char *filename, QEMUOptionParameter *options)
987 int fd;
988 int ret = 0;
989 struct stat stat_buf;
990 int64_t total_size = 0;
992 /* Read out options */
993 while (options && options->name) {
994 if (!strcmp(options->name, "size")) {
995 total_size = options->value.n / BDRV_SECTOR_SIZE;
997 options++;
1000 fd = open(filename, O_WRONLY | O_BINARY);
1001 if (fd < 0)
1002 return -errno;
1004 if (fstat(fd, &stat_buf) < 0)
1005 ret = -errno;
1006 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1007 ret = -ENODEV;
1008 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1009 ret = -ENOSPC;
1011 close(fd);
1012 return ret;
1015 static int hdev_has_zero_init(BlockDriverState *bs)
1017 return 0;
1020 static BlockDriver bdrv_host_device = {
1021 .format_name = "host_device",
1022 .protocol_name = "host_device",
1023 .instance_size = sizeof(BDRVRawState),
1024 .bdrv_probe_device = hdev_probe_device,
1025 .bdrv_file_open = hdev_open,
1026 .bdrv_close = raw_close,
1027 .bdrv_create = hdev_create,
1028 .create_options = raw_create_options,
1029 .bdrv_has_zero_init = hdev_has_zero_init,
1030 .bdrv_flush = raw_flush,
1032 .bdrv_aio_readv = raw_aio_readv,
1033 .bdrv_aio_writev = raw_aio_writev,
1034 .bdrv_aio_flush = raw_aio_flush,
1036 .bdrv_read = raw_read,
1037 .bdrv_write = raw_write,
1038 .bdrv_getlength = raw_getlength,
1040 /* generic scsi device */
1041 #ifdef __linux__
1042 .bdrv_ioctl = hdev_ioctl,
1043 .bdrv_aio_ioctl = hdev_aio_ioctl,
1044 #endif
1047 #ifdef __linux__
1048 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1050 BDRVRawState *s = bs->opaque;
1051 int ret;
1053 s->type = FTYPE_FD;
1055 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1056 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1057 if (ret)
1058 return ret;
1060 /* close fd so that we can reopen it as needed */
1061 close(s->fd);
1062 s->fd = -1;
1063 s->fd_media_changed = 1;
1065 return 0;
1068 static int floppy_probe_device(const char *filename)
1070 int fd, ret;
1071 int prio = 0;
1072 struct floppy_struct fdparam;
1074 if (strstart(filename, "/dev/fd", NULL))
1075 prio = 50;
1077 fd = open(filename, O_RDONLY | O_NONBLOCK);
1078 if (fd < 0) {
1079 goto out;
1082 /* Attempt to detect via a floppy specific ioctl */
1083 ret = ioctl(fd, FDGETPRM, &fdparam);
1084 if (ret >= 0)
1085 prio = 100;
1087 close(fd);
1088 out:
1089 return prio;
1093 static int floppy_is_inserted(BlockDriverState *bs)
1095 return fd_open(bs) >= 0;
1098 static int floppy_media_changed(BlockDriverState *bs)
1100 BDRVRawState *s = bs->opaque;
1101 int ret;
1104 * XXX: we do not have a true media changed indication.
1105 * It does not work if the floppy is changed without trying to read it.
1107 fd_open(bs);
1108 ret = s->fd_media_changed;
1109 s->fd_media_changed = 0;
1110 #ifdef DEBUG_FLOPPY
1111 printf("Floppy changed=%d\n", ret);
1112 #endif
1113 return ret;
1116 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1118 BDRVRawState *s = bs->opaque;
1119 int fd;
1121 if (s->fd >= 0) {
1122 close(s->fd);
1123 s->fd = -1;
1125 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1126 if (fd >= 0) {
1127 if (ioctl(fd, FDEJECT, 0) < 0)
1128 perror("FDEJECT");
1129 close(fd);
1132 return 0;
1135 static BlockDriver bdrv_host_floppy = {
1136 .format_name = "host_floppy",
1137 .protocol_name = "host_floppy",
1138 .instance_size = sizeof(BDRVRawState),
1139 .bdrv_probe_device = floppy_probe_device,
1140 .bdrv_file_open = floppy_open,
1141 .bdrv_close = raw_close,
1142 .bdrv_create = hdev_create,
1143 .create_options = raw_create_options,
1144 .bdrv_has_zero_init = hdev_has_zero_init,
1145 .bdrv_flush = raw_flush,
1147 .bdrv_aio_readv = raw_aio_readv,
1148 .bdrv_aio_writev = raw_aio_writev,
1149 .bdrv_aio_flush = raw_aio_flush,
1151 .bdrv_read = raw_read,
1152 .bdrv_write = raw_write,
1153 .bdrv_getlength = raw_getlength,
1155 /* removable device support */
1156 .bdrv_is_inserted = floppy_is_inserted,
1157 .bdrv_media_changed = floppy_media_changed,
1158 .bdrv_eject = floppy_eject,
1161 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1163 BDRVRawState *s = bs->opaque;
1165 s->type = FTYPE_CD;
1167 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1168 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1171 static int cdrom_probe_device(const char *filename)
1173 int fd, ret;
1174 int prio = 0;
1176 fd = open(filename, O_RDONLY | O_NONBLOCK);
1177 if (fd < 0) {
1178 goto out;
1181 /* Attempt to detect via a CDROM specific ioctl */
1182 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1183 if (ret >= 0)
1184 prio = 100;
1186 close(fd);
1187 out:
1188 return prio;
1191 static int cdrom_is_inserted(BlockDriverState *bs)
1193 BDRVRawState *s = bs->opaque;
1194 int ret;
1196 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1197 if (ret == CDS_DISC_OK)
1198 return 1;
1199 return 0;
1202 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1204 BDRVRawState *s = bs->opaque;
1206 if (eject_flag) {
1207 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1208 perror("CDROMEJECT");
1209 } else {
1210 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1211 perror("CDROMEJECT");
1214 return 0;
1217 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1219 BDRVRawState *s = bs->opaque;
1221 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1223 * Note: an error can happen if the distribution automatically
1224 * mounts the CD-ROM
1226 /* perror("CDROM_LOCKDOOR"); */
1229 return 0;
1232 static BlockDriver bdrv_host_cdrom = {
1233 .format_name = "host_cdrom",
1234 .protocol_name = "host_cdrom",
1235 .instance_size = sizeof(BDRVRawState),
1236 .bdrv_probe_device = cdrom_probe_device,
1237 .bdrv_file_open = cdrom_open,
1238 .bdrv_close = raw_close,
1239 .bdrv_create = hdev_create,
1240 .create_options = raw_create_options,
1241 .bdrv_has_zero_init = hdev_has_zero_init,
1242 .bdrv_flush = raw_flush,
1244 .bdrv_aio_readv = raw_aio_readv,
1245 .bdrv_aio_writev = raw_aio_writev,
1246 .bdrv_aio_flush = raw_aio_flush,
1248 .bdrv_read = raw_read,
1249 .bdrv_write = raw_write,
1250 .bdrv_getlength = raw_getlength,
1252 /* removable device support */
1253 .bdrv_is_inserted = cdrom_is_inserted,
1254 .bdrv_eject = cdrom_eject,
1255 .bdrv_set_locked = cdrom_set_locked,
1257 /* generic scsi device */
1258 .bdrv_ioctl = hdev_ioctl,
1259 .bdrv_aio_ioctl = hdev_aio_ioctl,
1261 #endif /* __linux__ */
1263 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1264 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1266 BDRVRawState *s = bs->opaque;
1267 int ret;
1269 s->type = FTYPE_CD;
1271 ret = raw_open_common(bs, filename, flags, 0);
1272 if (ret)
1273 return ret;
1275 /* make sure the door isnt locked at this time */
1276 ioctl(s->fd, CDIOCALLOW);
1277 return 0;
1280 static int cdrom_probe_device(const char *filename)
1282 if (strstart(filename, "/dev/cd", NULL) ||
1283 strstart(filename, "/dev/acd", NULL))
1284 return 100;
1285 return 0;
1288 static int cdrom_reopen(BlockDriverState *bs)
1290 BDRVRawState *s = bs->opaque;
1291 int fd;
1294 * Force reread of possibly changed/newly loaded disc,
1295 * FreeBSD seems to not notice sometimes...
1297 if (s->fd >= 0)
1298 close(s->fd);
1299 fd = open(bs->filename, s->open_flags, 0644);
1300 if (fd < 0) {
1301 s->fd = -1;
1302 return -EIO;
1304 s->fd = fd;
1306 /* make sure the door isnt locked at this time */
1307 ioctl(s->fd, CDIOCALLOW);
1308 return 0;
1311 static int cdrom_is_inserted(BlockDriverState *bs)
1313 return raw_getlength(bs) > 0;
1316 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1318 BDRVRawState *s = bs->opaque;
1320 if (s->fd < 0)
1321 return -ENOTSUP;
1323 (void) ioctl(s->fd, CDIOCALLOW);
1325 if (eject_flag) {
1326 if (ioctl(s->fd, CDIOCEJECT) < 0)
1327 perror("CDIOCEJECT");
1328 } else {
1329 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1330 perror("CDIOCCLOSE");
1333 if (cdrom_reopen(bs) < 0)
1334 return -ENOTSUP;
1335 return 0;
1338 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1340 BDRVRawState *s = bs->opaque;
1342 if (s->fd < 0)
1343 return -ENOTSUP;
1344 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1346 * Note: an error can happen if the distribution automatically
1347 * mounts the CD-ROM
1349 /* perror("CDROM_LOCKDOOR"); */
1352 return 0;
1355 static BlockDriver bdrv_host_cdrom = {
1356 .format_name = "host_cdrom",
1357 .protocol_name = "host_cdrom",
1358 .instance_size = sizeof(BDRVRawState),
1359 .bdrv_probe_device = cdrom_probe_device,
1360 .bdrv_file_open = cdrom_open,
1361 .bdrv_close = raw_close,
1362 .bdrv_create = hdev_create,
1363 .create_options = raw_create_options,
1364 .bdrv_has_zero_init = hdev_has_zero_init,
1365 .bdrv_flush = raw_flush,
1367 .bdrv_aio_readv = raw_aio_readv,
1368 .bdrv_aio_writev = raw_aio_writev,
1369 .bdrv_aio_flush = raw_aio_flush,
1371 .bdrv_read = raw_read,
1372 .bdrv_write = raw_write,
1373 .bdrv_getlength = raw_getlength,
1375 /* removable device support */
1376 .bdrv_is_inserted = cdrom_is_inserted,
1377 .bdrv_eject = cdrom_eject,
1378 .bdrv_set_locked = cdrom_set_locked,
1380 #endif /* __FreeBSD__ */
1382 static void bdrv_file_init(void)
1385 * Register all the drivers. Note that order is important, the driver
1386 * registered last will get probed first.
1388 bdrv_register(&bdrv_file);
1389 bdrv_register(&bdrv_host_device);
1390 #ifdef __linux__
1391 bdrv_register(&bdrv_host_floppy);
1392 bdrv_register(&bdrv_host_cdrom);
1393 #endif
1394 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1395 bdrv_register(&bdrv_host_cdrom);
1396 #endif
1399 block_init(bdrv_file_init);