raw-posix: don't assign bs->read_only
[qemu-kvm.git] / block / raw-posix.c
blob6521ca442a9bfd8cf67fc0311805cf45f3a90e92
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 unsigned int lseek_err_cnt;
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->lseek_err_cnt = 0;
139 s->open_flags = open_flags | O_BINARY;
140 s->open_flags &= ~O_ACCMODE;
141 if (bdrv_flags & BDRV_O_RDWR) {
142 s->open_flags |= O_RDWR;
143 } else {
144 s->open_flags |= O_RDONLY;
147 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
148 * and O_DIRECT for no caching. */
149 if ((bdrv_flags & BDRV_O_NOCACHE))
150 s->open_flags |= O_DIRECT;
151 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
152 s->open_flags |= O_DSYNC;
154 s->fd = -1;
155 fd = qemu_open(filename, s->open_flags, 0644);
156 if (fd < 0) {
157 ret = -errno;
158 if (ret == -EROFS)
159 ret = -EACCES;
160 return ret;
162 s->fd = fd;
163 s->aligned_buf = NULL;
165 if ((bdrv_flags & BDRV_O_NOCACHE)) {
166 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
167 if (s->aligned_buf == NULL) {
168 goto out_close;
172 #ifdef CONFIG_LINUX_AIO
173 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
174 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
176 /* We're falling back to POSIX AIO in some cases */
177 paio_init();
179 s->aio_ctx = laio_init();
180 if (!s->aio_ctx) {
181 goto out_free_buf;
183 s->use_aio = 1;
184 } else
185 #endif
187 if (paio_init() < 0) {
188 goto out_free_buf;
190 #ifdef CONFIG_LINUX_AIO
191 s->use_aio = 0;
192 #endif
195 return 0;
197 out_free_buf:
198 qemu_vfree(s->aligned_buf);
199 out_close:
200 close(fd);
201 return -errno;
204 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
206 BDRVRawState *s = bs->opaque;
208 s->type = FTYPE_FILE;
209 return raw_open_common(bs, filename, flags, 0);
212 /* XXX: use host sector size if necessary with:
213 #ifdef DIOCGSECTORSIZE
215 unsigned int sectorsize = 512;
216 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
217 sectorsize > bufsize)
218 bufsize = sectorsize;
220 #endif
221 #ifdef CONFIG_COCOA
222 u_int32_t blockSize = 512;
223 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
224 bufsize = blockSize;
226 #endif
230 * offset and count are in bytes, but must be multiples of 512 for files
231 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
233 * This function may be called without alignment if the caller ensures
234 * that O_DIRECT is not in effect.
236 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
237 uint8_t *buf, int count)
239 BDRVRawState *s = bs->opaque;
240 int ret;
242 ret = fd_open(bs);
243 if (ret < 0)
244 return ret;
246 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
247 ++(s->lseek_err_cnt);
248 if(s->lseek_err_cnt <= 10) {
249 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
250 "] lseek failed : %d = %s\n",
251 s->fd, bs->filename, offset, buf, count,
252 bs->total_sectors, errno, strerror(errno));
254 return -1;
256 s->lseek_err_cnt=0;
258 ret = read(s->fd, buf, count);
259 if (ret == count)
260 goto label__raw_read__success;
262 /* Allow reads beyond the end (needed for pwrite) */
263 if ((ret == 0) && bs->growable) {
264 int64_t size = raw_getlength(bs);
265 if (offset >= size) {
266 memset(buf, 0, count);
267 ret = count;
268 goto label__raw_read__success;
272 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
273 "] read failed %d : %d = %s\n",
274 s->fd, bs->filename, offset, buf, count,
275 bs->total_sectors, ret, errno, strerror(errno));
277 /* Try harder for CDrom. */
278 if (bs->type == BDRV_TYPE_CDROM) {
279 lseek(s->fd, offset, SEEK_SET);
280 ret = read(s->fd, buf, count);
281 if (ret == count)
282 goto label__raw_read__success;
283 lseek(s->fd, offset, SEEK_SET);
284 ret = read(s->fd, buf, count);
285 if (ret == count)
286 goto label__raw_read__success;
288 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
289 "] retry read failed %d : %d = %s\n",
290 s->fd, bs->filename, offset, buf, count,
291 bs->total_sectors, ret, errno, strerror(errno));
294 label__raw_read__success:
296 return (ret < 0) ? -errno : ret;
300 * offset and count are in bytes, but must be multiples of 512 for files
301 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
303 * This function may be called without alignment if the caller ensures
304 * that O_DIRECT is not in effect.
306 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
307 const uint8_t *buf, int count)
309 BDRVRawState *s = bs->opaque;
310 int ret;
312 ret = fd_open(bs);
313 if (ret < 0)
314 return -errno;
316 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
317 ++(s->lseek_err_cnt);
318 if(s->lseek_err_cnt) {
319 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
320 PRId64 "] lseek failed : %d = %s\n",
321 s->fd, bs->filename, offset, buf, count,
322 bs->total_sectors, errno, strerror(errno));
324 return -EIO;
326 s->lseek_err_cnt = 0;
328 ret = write(s->fd, buf, count);
329 if (ret == count)
330 goto label__raw_write__success;
332 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
333 "] write failed %d : %d = %s\n",
334 s->fd, bs->filename, offset, buf, count,
335 bs->total_sectors, ret, errno, strerror(errno));
337 label__raw_write__success:
339 return (ret < 0) ? -errno : ret;
344 * offset and count are in bytes and possibly not aligned. For files opened
345 * with O_DIRECT, necessary alignments are ensured before calling
346 * raw_pread_aligned to do the actual read.
348 static int raw_pread(BlockDriverState *bs, int64_t offset,
349 uint8_t *buf, int count)
351 BDRVRawState *s = bs->opaque;
352 int size, ret, shift, sum;
354 sum = 0;
356 if (s->aligned_buf != NULL) {
358 if (offset & 0x1ff) {
359 /* align offset on a 512 bytes boundary */
361 shift = offset & 0x1ff;
362 size = (shift + count + 0x1ff) & ~0x1ff;
363 if (size > ALIGNED_BUFFER_SIZE)
364 size = ALIGNED_BUFFER_SIZE;
365 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
366 if (ret < 0)
367 return ret;
369 size = 512 - shift;
370 if (size > count)
371 size = count;
372 memcpy(buf, s->aligned_buf + shift, size);
374 buf += size;
375 offset += size;
376 count -= size;
377 sum += size;
379 if (count == 0)
380 return sum;
382 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
384 /* read on aligned buffer */
386 while (count) {
388 size = (count + 0x1ff) & ~0x1ff;
389 if (size > ALIGNED_BUFFER_SIZE)
390 size = ALIGNED_BUFFER_SIZE;
392 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
393 if (ret < 0) {
394 return ret;
395 } else if (ret == 0) {
396 fprintf(stderr, "raw_pread: read beyond end of file\n");
397 abort();
400 size = ret;
401 if (size > count)
402 size = count;
404 memcpy(buf, s->aligned_buf, size);
406 buf += size;
407 offset += size;
408 count -= size;
409 sum += size;
412 return sum;
416 return raw_pread_aligned(bs, offset, buf, count) + sum;
419 static int raw_read(BlockDriverState *bs, int64_t sector_num,
420 uint8_t *buf, int nb_sectors)
422 int ret;
424 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
425 if (ret == (nb_sectors * 512))
426 ret = 0;
427 return ret;
431 * offset and count are in bytes and possibly not aligned. For files opened
432 * with O_DIRECT, necessary alignments are ensured before calling
433 * raw_pwrite_aligned to do the actual write.
435 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
436 const uint8_t *buf, int count)
438 BDRVRawState *s = bs->opaque;
439 int size, ret, shift, sum;
441 sum = 0;
443 if (s->aligned_buf != NULL) {
445 if (offset & 0x1ff) {
446 /* align offset on a 512 bytes boundary */
447 shift = offset & 0x1ff;
448 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
449 if (ret < 0)
450 return ret;
452 size = 512 - shift;
453 if (size > count)
454 size = count;
455 memcpy(s->aligned_buf + shift, buf, size);
457 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
458 if (ret < 0)
459 return ret;
461 buf += size;
462 offset += size;
463 count -= size;
464 sum += size;
466 if (count == 0)
467 return sum;
469 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
471 while ((size = (count & ~0x1ff)) != 0) {
473 if (size > ALIGNED_BUFFER_SIZE)
474 size = ALIGNED_BUFFER_SIZE;
476 memcpy(s->aligned_buf, buf, size);
478 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
479 if (ret < 0)
480 return ret;
482 buf += ret;
483 offset += ret;
484 count -= ret;
485 sum += ret;
487 /* here, count < 512 because (count & ~0x1ff) == 0 */
488 if (count) {
489 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
490 if (ret < 0)
491 return ret;
492 memcpy(s->aligned_buf, buf, count);
494 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
495 if (ret < 0)
496 return ret;
497 if (count < ret)
498 ret = count;
500 sum += ret;
502 return sum;
505 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
508 static int raw_write(BlockDriverState *bs, int64_t sector_num,
509 const uint8_t *buf, int nb_sectors)
511 int ret;
512 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
513 if (ret == (nb_sectors * 512))
514 ret = 0;
515 return ret;
519 * Check if all memory in this vector is sector aligned.
521 static int qiov_is_aligned(QEMUIOVector *qiov)
523 int i;
525 for (i = 0; i < qiov->niov; i++) {
526 if ((uintptr_t) qiov->iov[i].iov_base % 512) {
527 return 0;
531 return 1;
534 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
535 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
536 BlockDriverCompletionFunc *cb, void *opaque, int type)
538 BDRVRawState *s = bs->opaque;
540 if (fd_open(bs) < 0)
541 return NULL;
544 * If O_DIRECT is used the buffer needs to be aligned on a sector
545 * boundary. Check if this is the case or telll the low-level
546 * driver that it needs to copy the buffer.
548 if (s->aligned_buf) {
549 if (!qiov_is_aligned(qiov)) {
550 type |= QEMU_AIO_MISALIGNED;
551 #ifdef CONFIG_LINUX_AIO
552 } else if (s->use_aio) {
553 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
554 nb_sectors, cb, opaque, type);
555 #endif
559 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
560 cb, opaque, type);
563 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
564 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
565 BlockDriverCompletionFunc *cb, void *opaque)
567 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
568 cb, opaque, QEMU_AIO_READ);
571 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
572 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
573 BlockDriverCompletionFunc *cb, void *opaque)
575 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
576 cb, opaque, QEMU_AIO_WRITE);
579 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
580 BlockDriverCompletionFunc *cb, void *opaque)
582 BDRVRawState *s = bs->opaque;
584 if (fd_open(bs) < 0)
585 return NULL;
587 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
590 static void raw_close(BlockDriverState *bs)
592 BDRVRawState *s = bs->opaque;
593 if (s->fd >= 0) {
594 close(s->fd);
595 s->fd = -1;
596 if (s->aligned_buf != NULL)
597 qemu_vfree(s->aligned_buf);
601 static int raw_truncate(BlockDriverState *bs, int64_t offset)
603 BDRVRawState *s = bs->opaque;
604 if (s->type != FTYPE_FILE)
605 return -ENOTSUP;
606 if (ftruncate(s->fd, offset) < 0)
607 return -errno;
608 return 0;
611 #ifdef __OpenBSD__
612 static int64_t raw_getlength(BlockDriverState *bs)
614 BDRVRawState *s = bs->opaque;
615 int fd = s->fd;
616 struct stat st;
618 if (fstat(fd, &st))
619 return -1;
620 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
621 struct disklabel dl;
623 if (ioctl(fd, DIOCGDINFO, &dl))
624 return -1;
625 return (uint64_t)dl.d_secsize *
626 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
627 } else
628 return st.st_size;
630 #else /* !__OpenBSD__ */
631 static int64_t raw_getlength(BlockDriverState *bs)
633 BDRVRawState *s = bs->opaque;
634 int fd = s->fd;
635 int64_t size;
636 #ifdef CONFIG_BSD
637 struct stat sb;
638 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
639 int reopened = 0;
640 #endif
641 #endif
642 #ifdef __sun__
643 struct dk_minfo minfo;
644 int rv;
645 #endif
646 int ret;
648 ret = fd_open(bs);
649 if (ret < 0)
650 return ret;
652 #ifdef CONFIG_BSD
653 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
654 again:
655 #endif
656 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
657 #ifdef DIOCGMEDIASIZE
658 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
659 #elif defined(DIOCGPART)
661 struct partinfo pi;
662 if (ioctl(fd, DIOCGPART, &pi) == 0)
663 size = pi.media_size;
664 else
665 size = 0;
667 if (size == 0)
668 #endif
669 #ifdef CONFIG_COCOA
670 size = LONG_LONG_MAX;
671 #else
672 size = lseek(fd, 0LL, SEEK_END);
673 #endif
674 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
675 switch(s->type) {
676 case FTYPE_CD:
677 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
678 if (size == 2048LL * (unsigned)-1)
679 size = 0;
680 /* XXX no disc? maybe we need to reopen... */
681 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
682 reopened = 1;
683 goto again;
686 #endif
687 } else
688 #endif
689 #ifdef __sun__
691 * use the DKIOCGMEDIAINFO ioctl to read the size.
693 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
694 if ( rv != -1 ) {
695 size = minfo.dki_lbsize * minfo.dki_capacity;
696 } else /* there are reports that lseek on some devices
697 fails, but irc discussion said that contingency
698 on contingency was overkill */
699 #endif
701 size = lseek(fd, 0, SEEK_END);
703 return size;
705 #endif
707 static int raw_create(const char *filename, QEMUOptionParameter *options)
709 int fd;
710 int result = 0;
711 int64_t total_size = 0;
713 /* Read out options */
714 while (options && options->name) {
715 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
716 total_size = options->value.n / 512;
718 options++;
721 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
722 0644);
723 if (fd < 0) {
724 result = -errno;
725 } else {
726 if (ftruncate(fd, total_size * 512) != 0) {
727 result = -errno;
729 if (close(fd) != 0) {
730 result = -errno;
733 return result;
736 static void raw_flush(BlockDriverState *bs)
738 BDRVRawState *s = bs->opaque;
739 qemu_fdatasync(s->fd);
743 static QEMUOptionParameter raw_create_options[] = {
745 .name = BLOCK_OPT_SIZE,
746 .type = OPT_SIZE,
747 .help = "Virtual disk size"
749 { NULL }
752 static BlockDriver bdrv_raw = {
753 .format_name = "raw",
754 .instance_size = sizeof(BDRVRawState),
755 .bdrv_probe = NULL, /* no probe for protocols */
756 .bdrv_open = raw_open,
757 .bdrv_read = raw_read,
758 .bdrv_write = raw_write,
759 .bdrv_close = raw_close,
760 .bdrv_create = raw_create,
761 .bdrv_flush = raw_flush,
763 .bdrv_aio_readv = raw_aio_readv,
764 .bdrv_aio_writev = raw_aio_writev,
765 .bdrv_aio_flush = raw_aio_flush,
767 .bdrv_truncate = raw_truncate,
768 .bdrv_getlength = raw_getlength,
770 .create_options = raw_create_options,
773 /***********************************************/
774 /* host device */
776 #ifdef CONFIG_COCOA
777 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
778 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
780 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
782 kern_return_t kernResult;
783 mach_port_t masterPort;
784 CFMutableDictionaryRef classesToMatch;
786 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
787 if ( KERN_SUCCESS != kernResult ) {
788 printf( "IOMasterPort returned %d\n", kernResult );
791 classesToMatch = IOServiceMatching( kIOCDMediaClass );
792 if ( classesToMatch == NULL ) {
793 printf( "IOServiceMatching returned a NULL dictionary.\n" );
794 } else {
795 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
797 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
798 if ( KERN_SUCCESS != kernResult )
800 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
803 return kernResult;
806 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
808 io_object_t nextMedia;
809 kern_return_t kernResult = KERN_FAILURE;
810 *bsdPath = '\0';
811 nextMedia = IOIteratorNext( mediaIterator );
812 if ( nextMedia )
814 CFTypeRef bsdPathAsCFString;
815 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
816 if ( bsdPathAsCFString ) {
817 size_t devPathLength;
818 strcpy( bsdPath, _PATH_DEV );
819 strcat( bsdPath, "r" );
820 devPathLength = strlen( bsdPath );
821 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
822 kernResult = KERN_SUCCESS;
824 CFRelease( bsdPathAsCFString );
826 IOObjectRelease( nextMedia );
829 return kernResult;
832 #endif
834 static int hdev_probe_device(const char *filename)
836 struct stat st;
838 /* allow a dedicated CD-ROM driver to match with a higher priority */
839 if (strstart(filename, "/dev/cdrom", NULL))
840 return 50;
842 if (stat(filename, &st) >= 0 &&
843 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
844 return 100;
847 return 0;
850 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
852 BDRVRawState *s = bs->opaque;
854 #ifdef CONFIG_COCOA
855 if (strstart(filename, "/dev/cdrom", NULL)) {
856 kern_return_t kernResult;
857 io_iterator_t mediaIterator;
858 char bsdPath[ MAXPATHLEN ];
859 int fd;
861 kernResult = FindEjectableCDMedia( &mediaIterator );
862 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
864 if ( bsdPath[ 0 ] != '\0' ) {
865 strcat(bsdPath,"s0");
866 /* some CDs don't have a partition 0 */
867 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
868 if (fd < 0) {
869 bsdPath[strlen(bsdPath)-1] = '1';
870 } else {
871 close(fd);
873 filename = bsdPath;
876 if ( mediaIterator )
877 IOObjectRelease( mediaIterator );
879 #endif
881 s->type = FTYPE_FILE;
882 #if defined(__linux__)
883 if (strstart(filename, "/dev/sg", NULL)) {
884 bs->sg = 1;
886 #endif
888 return raw_open_common(bs, filename, flags, 0);
891 #if defined(__linux__)
892 /* Note: we do not have a reliable method to detect if the floppy is
893 present. The current method is to try to open the floppy at every
894 I/O and to keep it opened during a few hundreds of ms. */
895 static int fd_open(BlockDriverState *bs)
897 BDRVRawState *s = bs->opaque;
898 int last_media_present;
900 if (s->type != FTYPE_FD)
901 return 0;
902 last_media_present = (s->fd >= 0);
903 if (s->fd >= 0 &&
904 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
905 close(s->fd);
906 s->fd = -1;
907 #ifdef DEBUG_FLOPPY
908 printf("Floppy closed\n");
909 #endif
911 if (s->fd < 0) {
912 if (s->fd_got_error &&
913 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
914 #ifdef DEBUG_FLOPPY
915 printf("No floppy (open delayed)\n");
916 #endif
917 return -EIO;
919 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
920 if (s->fd < 0) {
921 s->fd_error_time = qemu_get_clock(rt_clock);
922 s->fd_got_error = 1;
923 if (last_media_present)
924 s->fd_media_changed = 1;
925 #ifdef DEBUG_FLOPPY
926 printf("No floppy\n");
927 #endif
928 return -EIO;
930 #ifdef DEBUG_FLOPPY
931 printf("Floppy opened\n");
932 #endif
934 if (!last_media_present)
935 s->fd_media_changed = 1;
936 s->fd_open_time = qemu_get_clock(rt_clock);
937 s->fd_got_error = 0;
938 return 0;
941 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
943 BDRVRawState *s = bs->opaque;
945 return ioctl(s->fd, req, buf);
948 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
949 unsigned long int req, void *buf,
950 BlockDriverCompletionFunc *cb, void *opaque)
952 BDRVRawState *s = bs->opaque;
954 if (fd_open(bs) < 0)
955 return NULL;
956 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
959 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
960 static int fd_open(BlockDriverState *bs)
962 BDRVRawState *s = bs->opaque;
964 /* this is just to ensure s->fd is sane (its called by io ops) */
965 if (s->fd >= 0)
966 return 0;
967 return -EIO;
969 #else /* !linux && !FreeBSD */
971 static int fd_open(BlockDriverState *bs)
973 return 0;
976 #endif /* !linux && !FreeBSD */
978 static int hdev_create(const char *filename, QEMUOptionParameter *options)
980 int fd;
981 int ret = 0;
982 struct stat stat_buf;
983 int64_t total_size = 0;
985 /* Read out options */
986 while (options && options->name) {
987 if (!strcmp(options->name, "size")) {
988 total_size = options->value.n / 512;
990 options++;
993 fd = open(filename, O_WRONLY | O_BINARY);
994 if (fd < 0)
995 return -errno;
997 if (fstat(fd, &stat_buf) < 0)
998 ret = -errno;
999 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1000 ret = -ENODEV;
1001 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1002 ret = -ENOSPC;
1004 close(fd);
1005 return ret;
1008 static BlockDriver bdrv_host_device = {
1009 .format_name = "host_device",
1010 .instance_size = sizeof(BDRVRawState),
1011 .bdrv_probe_device = hdev_probe_device,
1012 .bdrv_open = hdev_open,
1013 .bdrv_close = raw_close,
1014 .bdrv_create = hdev_create,
1015 .create_options = raw_create_options,
1016 .no_zero_init = 1,
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 .instance_size = sizeof(BDRVRawState),
1125 .bdrv_probe_device = floppy_probe_device,
1126 .bdrv_open = floppy_open,
1127 .bdrv_close = raw_close,
1128 .bdrv_create = hdev_create,
1129 .create_options = raw_create_options,
1130 .no_zero_init = 1,
1131 .bdrv_flush = raw_flush,
1133 .bdrv_aio_readv = raw_aio_readv,
1134 .bdrv_aio_writev = raw_aio_writev,
1135 .bdrv_aio_flush = raw_aio_flush,
1137 .bdrv_read = raw_read,
1138 .bdrv_write = raw_write,
1139 .bdrv_getlength = raw_getlength,
1141 /* removable device support */
1142 .bdrv_is_inserted = floppy_is_inserted,
1143 .bdrv_media_changed = floppy_media_changed,
1144 .bdrv_eject = floppy_eject,
1147 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1149 BDRVRawState *s = bs->opaque;
1151 s->type = FTYPE_CD;
1153 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1154 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1157 static int cdrom_probe_device(const char *filename)
1159 int fd, ret;
1160 int prio = 0;
1162 if (strstart(filename, "/dev/cd", NULL))
1163 prio = 50;
1165 fd = open(filename, O_RDONLY | O_NONBLOCK);
1166 if (fd < 0) {
1167 goto out;
1170 /* Attempt to detect via a CDROM specific ioctl */
1171 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1172 if (ret >= 0)
1173 prio = 100;
1175 close(fd);
1176 out:
1177 return prio;
1180 static int cdrom_is_inserted(BlockDriverState *bs)
1182 BDRVRawState *s = bs->opaque;
1183 int ret;
1185 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1186 if (ret == CDS_DISC_OK)
1187 return 1;
1188 return 0;
1191 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1193 BDRVRawState *s = bs->opaque;
1195 if (eject_flag) {
1196 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1197 perror("CDROMEJECT");
1198 } else {
1199 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1200 perror("CDROMEJECT");
1203 return 0;
1206 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1208 BDRVRawState *s = bs->opaque;
1210 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1212 * Note: an error can happen if the distribution automatically
1213 * mounts the CD-ROM
1215 /* perror("CDROM_LOCKDOOR"); */
1218 return 0;
1221 static BlockDriver bdrv_host_cdrom = {
1222 .format_name = "host_cdrom",
1223 .instance_size = sizeof(BDRVRawState),
1224 .bdrv_probe_device = cdrom_probe_device,
1225 .bdrv_open = cdrom_open,
1226 .bdrv_close = raw_close,
1227 .bdrv_create = hdev_create,
1228 .create_options = raw_create_options,
1229 .no_zero_init = 1,
1230 .bdrv_flush = raw_flush,
1232 .bdrv_aio_readv = raw_aio_readv,
1233 .bdrv_aio_writev = raw_aio_writev,
1234 .bdrv_aio_flush = raw_aio_flush,
1236 .bdrv_read = raw_read,
1237 .bdrv_write = raw_write,
1238 .bdrv_getlength = raw_getlength,
1240 /* removable device support */
1241 .bdrv_is_inserted = cdrom_is_inserted,
1242 .bdrv_eject = cdrom_eject,
1243 .bdrv_set_locked = cdrom_set_locked,
1245 /* generic scsi device */
1246 .bdrv_ioctl = hdev_ioctl,
1247 .bdrv_aio_ioctl = hdev_aio_ioctl,
1249 #endif /* __linux__ */
1251 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1252 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1254 BDRVRawState *s = bs->opaque;
1255 int ret;
1257 s->type = FTYPE_CD;
1259 ret = raw_open_common(bs, filename, flags, 0);
1260 if (ret)
1261 return ret;
1263 /* make sure the door isnt locked at this time */
1264 ioctl(s->fd, CDIOCALLOW);
1265 return 0;
1268 static int cdrom_probe_device(const char *filename)
1270 if (strstart(filename, "/dev/cd", NULL) ||
1271 strstart(filename, "/dev/acd", NULL))
1272 return 100;
1273 return 0;
1276 static int cdrom_reopen(BlockDriverState *bs)
1278 BDRVRawState *s = bs->opaque;
1279 int fd;
1282 * Force reread of possibly changed/newly loaded disc,
1283 * FreeBSD seems to not notice sometimes...
1285 if (s->fd >= 0)
1286 close(s->fd);
1287 fd = open(bs->filename, s->open_flags, 0644);
1288 if (fd < 0) {
1289 s->fd = -1;
1290 return -EIO;
1292 s->fd = fd;
1294 /* make sure the door isnt locked at this time */
1295 ioctl(s->fd, CDIOCALLOW);
1296 return 0;
1299 static int cdrom_is_inserted(BlockDriverState *bs)
1301 return raw_getlength(bs) > 0;
1304 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1306 BDRVRawState *s = bs->opaque;
1308 if (s->fd < 0)
1309 return -ENOTSUP;
1311 (void) ioctl(s->fd, CDIOCALLOW);
1313 if (eject_flag) {
1314 if (ioctl(s->fd, CDIOCEJECT) < 0)
1315 perror("CDIOCEJECT");
1316 } else {
1317 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1318 perror("CDIOCCLOSE");
1321 if (cdrom_reopen(bs) < 0)
1322 return -ENOTSUP;
1323 return 0;
1326 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1328 BDRVRawState *s = bs->opaque;
1330 if (s->fd < 0)
1331 return -ENOTSUP;
1332 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1334 * Note: an error can happen if the distribution automatically
1335 * mounts the CD-ROM
1337 /* perror("CDROM_LOCKDOOR"); */
1340 return 0;
1343 static BlockDriver bdrv_host_cdrom = {
1344 .format_name = "host_cdrom",
1345 .instance_size = sizeof(BDRVRawState),
1346 .bdrv_probe_device = cdrom_probe_device,
1347 .bdrv_open = cdrom_open,
1348 .bdrv_close = raw_close,
1349 .bdrv_create = hdev_create,
1350 .create_options = raw_create_options,
1351 .no_zero_init = 1,
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_raw_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_raw);
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_raw_init);