block: kill BDRV_O_CREAT
[qemu.git] / block / raw-posix.c
blob325d2265f5c4d470cb9c0ce7bf652e6ea9b2be93
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;
145 bs->read_only = 1;
148 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
149 * and O_DIRECT for no caching. */
150 if ((bdrv_flags & BDRV_O_NOCACHE))
151 s->open_flags |= O_DIRECT;
152 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
153 s->open_flags |= O_DSYNC;
155 s->fd = -1;
156 fd = qemu_open(filename, s->open_flags, 0644);
157 if (fd < 0) {
158 ret = -errno;
159 if (ret == -EROFS)
160 ret = -EACCES;
161 return ret;
163 s->fd = fd;
164 s->aligned_buf = NULL;
166 if ((bdrv_flags & BDRV_O_NOCACHE)) {
167 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
168 if (s->aligned_buf == NULL) {
169 goto out_close;
173 #ifdef CONFIG_LINUX_AIO
174 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
175 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
177 /* We're falling back to POSIX AIO in some cases */
178 paio_init();
180 s->aio_ctx = laio_init();
181 if (!s->aio_ctx) {
182 goto out_free_buf;
184 s->use_aio = 1;
185 } else
186 #endif
188 if (paio_init() < 0) {
189 goto out_free_buf;
191 #ifdef CONFIG_LINUX_AIO
192 s->use_aio = 0;
193 #endif
196 return 0;
198 out_free_buf:
199 qemu_vfree(s->aligned_buf);
200 out_close:
201 close(fd);
202 return -errno;
205 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
207 BDRVRawState *s = bs->opaque;
209 s->type = FTYPE_FILE;
210 return raw_open_common(bs, filename, flags, 0);
213 /* XXX: use host sector size if necessary with:
214 #ifdef DIOCGSECTORSIZE
216 unsigned int sectorsize = 512;
217 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
218 sectorsize > bufsize)
219 bufsize = sectorsize;
221 #endif
222 #ifdef CONFIG_COCOA
223 u_int32_t blockSize = 512;
224 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
225 bufsize = blockSize;
227 #endif
231 * offset and count are in bytes, but must be multiples of 512 for files
232 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
234 * This function may be called without alignment if the caller ensures
235 * that O_DIRECT is not in effect.
237 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
238 uint8_t *buf, int count)
240 BDRVRawState *s = bs->opaque;
241 int ret;
243 ret = fd_open(bs);
244 if (ret < 0)
245 return ret;
247 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
248 ++(s->lseek_err_cnt);
249 if(s->lseek_err_cnt <= 10) {
250 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
251 "] lseek failed : %d = %s\n",
252 s->fd, bs->filename, offset, buf, count,
253 bs->total_sectors, errno, strerror(errno));
255 return -1;
257 s->lseek_err_cnt=0;
259 ret = read(s->fd, buf, count);
260 if (ret == count)
261 goto label__raw_read__success;
263 /* Allow reads beyond the end (needed for pwrite) */
264 if ((ret == 0) && bs->growable) {
265 int64_t size = raw_getlength(bs);
266 if (offset >= size) {
267 memset(buf, 0, count);
268 ret = count;
269 goto label__raw_read__success;
273 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
274 "] read failed %d : %d = %s\n",
275 s->fd, bs->filename, offset, buf, count,
276 bs->total_sectors, ret, errno, strerror(errno));
278 /* Try harder for CDrom. */
279 if (bs->type == BDRV_TYPE_CDROM) {
280 lseek(s->fd, offset, SEEK_SET);
281 ret = read(s->fd, buf, count);
282 if (ret == count)
283 goto label__raw_read__success;
284 lseek(s->fd, offset, SEEK_SET);
285 ret = read(s->fd, buf, count);
286 if (ret == count)
287 goto label__raw_read__success;
289 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
290 "] retry read failed %d : %d = %s\n",
291 s->fd, bs->filename, offset, buf, count,
292 bs->total_sectors, ret, errno, strerror(errno));
295 label__raw_read__success:
297 return (ret < 0) ? -errno : ret;
301 * offset and count are in bytes, but must be multiples of 512 for files
302 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
304 * This function may be called without alignment if the caller ensures
305 * that O_DIRECT is not in effect.
307 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
308 const uint8_t *buf, int count)
310 BDRVRawState *s = bs->opaque;
311 int ret;
313 ret = fd_open(bs);
314 if (ret < 0)
315 return -errno;
317 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
318 ++(s->lseek_err_cnt);
319 if(s->lseek_err_cnt) {
320 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
321 PRId64 "] lseek failed : %d = %s\n",
322 s->fd, bs->filename, offset, buf, count,
323 bs->total_sectors, errno, strerror(errno));
325 return -EIO;
327 s->lseek_err_cnt = 0;
329 ret = write(s->fd, buf, count);
330 if (ret == count)
331 goto label__raw_write__success;
333 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
334 "] write failed %d : %d = %s\n",
335 s->fd, bs->filename, offset, buf, count,
336 bs->total_sectors, ret, errno, strerror(errno));
338 label__raw_write__success:
340 return (ret < 0) ? -errno : ret;
345 * offset and count are in bytes and possibly not aligned. For files opened
346 * with O_DIRECT, necessary alignments are ensured before calling
347 * raw_pread_aligned to do the actual read.
349 static int raw_pread(BlockDriverState *bs, int64_t offset,
350 uint8_t *buf, int count)
352 BDRVRawState *s = bs->opaque;
353 int size, ret, shift, sum;
355 sum = 0;
357 if (s->aligned_buf != NULL) {
359 if (offset & 0x1ff) {
360 /* align offset on a 512 bytes boundary */
362 shift = offset & 0x1ff;
363 size = (shift + count + 0x1ff) & ~0x1ff;
364 if (size > ALIGNED_BUFFER_SIZE)
365 size = ALIGNED_BUFFER_SIZE;
366 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
367 if (ret < 0)
368 return ret;
370 size = 512 - shift;
371 if (size > count)
372 size = count;
373 memcpy(buf, s->aligned_buf + shift, size);
375 buf += size;
376 offset += size;
377 count -= size;
378 sum += size;
380 if (count == 0)
381 return sum;
383 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
385 /* read on aligned buffer */
387 while (count) {
389 size = (count + 0x1ff) & ~0x1ff;
390 if (size > ALIGNED_BUFFER_SIZE)
391 size = ALIGNED_BUFFER_SIZE;
393 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
394 if (ret < 0)
395 return ret;
397 size = ret;
398 if (size > count)
399 size = count;
401 memcpy(buf, s->aligned_buf, size);
403 buf += size;
404 offset += size;
405 count -= size;
406 sum += size;
409 return sum;
413 return raw_pread_aligned(bs, offset, buf, count) + sum;
416 static int raw_read(BlockDriverState *bs, int64_t sector_num,
417 uint8_t *buf, int nb_sectors)
419 int ret;
421 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
422 if (ret == (nb_sectors * 512))
423 ret = 0;
424 return ret;
428 * offset and count are in bytes and possibly not aligned. For files opened
429 * with O_DIRECT, necessary alignments are ensured before calling
430 * raw_pwrite_aligned to do the actual write.
432 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
433 const uint8_t *buf, int count)
435 BDRVRawState *s = bs->opaque;
436 int size, ret, shift, sum;
438 sum = 0;
440 if (s->aligned_buf != NULL) {
442 if (offset & 0x1ff) {
443 /* align offset on a 512 bytes boundary */
444 shift = offset & 0x1ff;
445 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
446 if (ret < 0)
447 return ret;
449 size = 512 - shift;
450 if (size > count)
451 size = count;
452 memcpy(s->aligned_buf + shift, buf, size);
454 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
455 if (ret < 0)
456 return ret;
458 buf += size;
459 offset += size;
460 count -= size;
461 sum += size;
463 if (count == 0)
464 return sum;
466 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
468 while ((size = (count & ~0x1ff)) != 0) {
470 if (size > ALIGNED_BUFFER_SIZE)
471 size = ALIGNED_BUFFER_SIZE;
473 memcpy(s->aligned_buf, buf, size);
475 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
476 if (ret < 0)
477 return ret;
479 buf += ret;
480 offset += ret;
481 count -= ret;
482 sum += ret;
484 /* here, count < 512 because (count & ~0x1ff) == 0 */
485 if (count) {
486 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
487 if (ret < 0)
488 return ret;
489 memcpy(s->aligned_buf, buf, count);
491 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
492 if (ret < 0)
493 return ret;
494 if (count < ret)
495 ret = count;
497 sum += ret;
499 return sum;
502 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
505 static int raw_write(BlockDriverState *bs, int64_t sector_num,
506 const uint8_t *buf, int nb_sectors)
508 int ret;
509 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
510 if (ret == (nb_sectors * 512))
511 ret = 0;
512 return ret;
516 * Check if all memory in this vector is sector aligned.
518 static int qiov_is_aligned(QEMUIOVector *qiov)
520 int i;
522 for (i = 0; i < qiov->niov; i++) {
523 if ((uintptr_t) qiov->iov[i].iov_base % 512) {
524 return 0;
528 return 1;
531 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
532 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
533 BlockDriverCompletionFunc *cb, void *opaque, int type)
535 BDRVRawState *s = bs->opaque;
537 if (fd_open(bs) < 0)
538 return NULL;
541 * If O_DIRECT is used the buffer needs to be aligned on a sector
542 * boundary. Check if this is the case or telll the low-level
543 * driver that it needs to copy the buffer.
545 if (s->aligned_buf) {
546 if (!qiov_is_aligned(qiov)) {
547 type |= QEMU_AIO_MISALIGNED;
548 #ifdef CONFIG_LINUX_AIO
549 } else if (s->use_aio) {
550 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
551 nb_sectors, cb, opaque, type);
552 #endif
556 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
557 cb, opaque, type);
560 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
561 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
562 BlockDriverCompletionFunc *cb, void *opaque)
564 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
565 cb, opaque, QEMU_AIO_READ);
568 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
569 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
570 BlockDriverCompletionFunc *cb, void *opaque)
572 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
573 cb, opaque, QEMU_AIO_WRITE);
576 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
577 BlockDriverCompletionFunc *cb, void *opaque)
579 BDRVRawState *s = bs->opaque;
581 if (fd_open(bs) < 0)
582 return NULL;
584 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
587 static void raw_close(BlockDriverState *bs)
589 BDRVRawState *s = bs->opaque;
590 if (s->fd >= 0) {
591 close(s->fd);
592 s->fd = -1;
593 if (s->aligned_buf != NULL)
594 qemu_free(s->aligned_buf);
598 static int raw_truncate(BlockDriverState *bs, int64_t offset)
600 BDRVRawState *s = bs->opaque;
601 if (s->type != FTYPE_FILE)
602 return -ENOTSUP;
603 if (ftruncate(s->fd, offset) < 0)
604 return -errno;
605 return 0;
608 #ifdef __OpenBSD__
609 static int64_t raw_getlength(BlockDriverState *bs)
611 BDRVRawState *s = bs->opaque;
612 int fd = s->fd;
613 struct stat st;
615 if (fstat(fd, &st))
616 return -1;
617 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
618 struct disklabel dl;
620 if (ioctl(fd, DIOCGDINFO, &dl))
621 return -1;
622 return (uint64_t)dl.d_secsize *
623 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
624 } else
625 return st.st_size;
627 #else /* !__OpenBSD__ */
628 static int64_t raw_getlength(BlockDriverState *bs)
630 BDRVRawState *s = bs->opaque;
631 int fd = s->fd;
632 int64_t size;
633 #ifdef CONFIG_BSD
634 struct stat sb;
635 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
636 int reopened = 0;
637 #endif
638 #endif
639 #ifdef __sun__
640 struct dk_minfo minfo;
641 int rv;
642 #endif
643 int ret;
645 ret = fd_open(bs);
646 if (ret < 0)
647 return ret;
649 #ifdef CONFIG_BSD
650 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
651 again:
652 #endif
653 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
654 #ifdef DIOCGMEDIASIZE
655 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
656 #elif defined(DIOCGPART)
658 struct partinfo pi;
659 if (ioctl(fd, DIOCGPART, &pi) == 0)
660 size = pi.media_size;
661 else
662 size = 0;
664 if (size == 0)
665 #endif
666 #ifdef CONFIG_COCOA
667 size = LONG_LONG_MAX;
668 #else
669 size = lseek(fd, 0LL, SEEK_END);
670 #endif
671 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
672 switch(s->type) {
673 case FTYPE_CD:
674 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
675 if (size == 2048LL * (unsigned)-1)
676 size = 0;
677 /* XXX no disc? maybe we need to reopen... */
678 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
679 reopened = 1;
680 goto again;
683 #endif
684 } else
685 #endif
686 #ifdef __sun__
688 * use the DKIOCGMEDIAINFO ioctl to read the size.
690 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
691 if ( rv != -1 ) {
692 size = minfo.dki_lbsize * minfo.dki_capacity;
693 } else /* there are reports that lseek on some devices
694 fails, but irc discussion said that contingency
695 on contingency was overkill */
696 #endif
698 size = lseek(fd, 0, SEEK_END);
700 return size;
702 #endif
704 static int raw_create(const char *filename, QEMUOptionParameter *options)
706 int fd;
707 int result = 0;
708 int64_t total_size = 0;
710 /* Read out options */
711 while (options && options->name) {
712 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
713 total_size = options->value.n / 512;
715 options++;
718 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
719 0644);
720 if (fd < 0) {
721 result = -errno;
722 } else {
723 if (ftruncate(fd, total_size * 512) != 0) {
724 result = -errno;
726 if (close(fd) != 0) {
727 result = -errno;
730 return result;
733 static void raw_flush(BlockDriverState *bs)
735 BDRVRawState *s = bs->opaque;
736 qemu_fdatasync(s->fd);
740 static QEMUOptionParameter raw_create_options[] = {
742 .name = BLOCK_OPT_SIZE,
743 .type = OPT_SIZE,
744 .help = "Virtual disk size"
746 { NULL }
749 static BlockDriver bdrv_raw = {
750 .format_name = "raw",
751 .instance_size = sizeof(BDRVRawState),
752 .bdrv_probe = NULL, /* no probe for protocols */
753 .bdrv_open = raw_open,
754 .bdrv_read = raw_read,
755 .bdrv_write = raw_write,
756 .bdrv_close = raw_close,
757 .bdrv_create = raw_create,
758 .bdrv_flush = raw_flush,
760 .bdrv_aio_readv = raw_aio_readv,
761 .bdrv_aio_writev = raw_aio_writev,
762 .bdrv_aio_flush = raw_aio_flush,
764 .bdrv_truncate = raw_truncate,
765 .bdrv_getlength = raw_getlength,
767 .create_options = raw_create_options,
770 /***********************************************/
771 /* host device */
773 #ifdef CONFIG_COCOA
774 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
775 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
777 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
779 kern_return_t kernResult;
780 mach_port_t masterPort;
781 CFMutableDictionaryRef classesToMatch;
783 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
784 if ( KERN_SUCCESS != kernResult ) {
785 printf( "IOMasterPort returned %d\n", kernResult );
788 classesToMatch = IOServiceMatching( kIOCDMediaClass );
789 if ( classesToMatch == NULL ) {
790 printf( "IOServiceMatching returned a NULL dictionary.\n" );
791 } else {
792 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
794 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
795 if ( KERN_SUCCESS != kernResult )
797 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
800 return kernResult;
803 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
805 io_object_t nextMedia;
806 kern_return_t kernResult = KERN_FAILURE;
807 *bsdPath = '\0';
808 nextMedia = IOIteratorNext( mediaIterator );
809 if ( nextMedia )
811 CFTypeRef bsdPathAsCFString;
812 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
813 if ( bsdPathAsCFString ) {
814 size_t devPathLength;
815 strcpy( bsdPath, _PATH_DEV );
816 strcat( bsdPath, "r" );
817 devPathLength = strlen( bsdPath );
818 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
819 kernResult = KERN_SUCCESS;
821 CFRelease( bsdPathAsCFString );
823 IOObjectRelease( nextMedia );
826 return kernResult;
829 #endif
831 static int hdev_probe_device(const char *filename)
833 struct stat st;
835 /* allow a dedicated CD-ROM driver to match with a higher priority */
836 if (strstart(filename, "/dev/cdrom", NULL))
837 return 50;
839 if (stat(filename, &st) >= 0 &&
840 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
841 return 100;
844 return 0;
847 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
849 BDRVRawState *s = bs->opaque;
851 #ifdef CONFIG_COCOA
852 if (strstart(filename, "/dev/cdrom", NULL)) {
853 kern_return_t kernResult;
854 io_iterator_t mediaIterator;
855 char bsdPath[ MAXPATHLEN ];
856 int fd;
858 kernResult = FindEjectableCDMedia( &mediaIterator );
859 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
861 if ( bsdPath[ 0 ] != '\0' ) {
862 strcat(bsdPath,"s0");
863 /* some CDs don't have a partition 0 */
864 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
865 if (fd < 0) {
866 bsdPath[strlen(bsdPath)-1] = '1';
867 } else {
868 close(fd);
870 filename = bsdPath;
873 if ( mediaIterator )
874 IOObjectRelease( mediaIterator );
876 #endif
878 s->type = FTYPE_FILE;
879 #if defined(__linux__)
880 if (strstart(filename, "/dev/sg", NULL)) {
881 bs->sg = 1;
883 #endif
885 return raw_open_common(bs, filename, flags, 0);
888 #if defined(__linux__)
889 /* Note: we do not have a reliable method to detect if the floppy is
890 present. The current method is to try to open the floppy at every
891 I/O and to keep it opened during a few hundreds of ms. */
892 static int fd_open(BlockDriverState *bs)
894 BDRVRawState *s = bs->opaque;
895 int last_media_present;
897 if (s->type != FTYPE_FD)
898 return 0;
899 last_media_present = (s->fd >= 0);
900 if (s->fd >= 0 &&
901 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
902 close(s->fd);
903 s->fd = -1;
904 #ifdef DEBUG_FLOPPY
905 printf("Floppy closed\n");
906 #endif
908 if (s->fd < 0) {
909 if (s->fd_got_error &&
910 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
911 #ifdef DEBUG_FLOPPY
912 printf("No floppy (open delayed)\n");
913 #endif
914 return -EIO;
916 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
917 if (s->fd < 0) {
918 s->fd_error_time = qemu_get_clock(rt_clock);
919 s->fd_got_error = 1;
920 if (last_media_present)
921 s->fd_media_changed = 1;
922 #ifdef DEBUG_FLOPPY
923 printf("No floppy\n");
924 #endif
925 return -EIO;
927 #ifdef DEBUG_FLOPPY
928 printf("Floppy opened\n");
929 #endif
931 if (!last_media_present)
932 s->fd_media_changed = 1;
933 s->fd_open_time = qemu_get_clock(rt_clock);
934 s->fd_got_error = 0;
935 return 0;
938 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
940 BDRVRawState *s = bs->opaque;
942 return ioctl(s->fd, req, buf);
945 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
946 unsigned long int req, void *buf,
947 BlockDriverCompletionFunc *cb, void *opaque)
949 BDRVRawState *s = bs->opaque;
951 if (fd_open(bs) < 0)
952 return NULL;
953 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
956 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
957 static int fd_open(BlockDriverState *bs)
959 BDRVRawState *s = bs->opaque;
961 /* this is just to ensure s->fd is sane (its called by io ops) */
962 if (s->fd >= 0)
963 return 0;
964 return -EIO;
966 #else /* !linux && !FreeBSD */
968 static int fd_open(BlockDriverState *bs)
970 return 0;
973 #endif /* !linux && !FreeBSD */
975 static int hdev_create(const char *filename, QEMUOptionParameter *options)
977 int fd;
978 int ret = 0;
979 struct stat stat_buf;
980 int64_t total_size = 0;
982 /* Read out options */
983 while (options && options->name) {
984 if (!strcmp(options->name, "size")) {
985 total_size = options->value.n / 512;
987 options++;
990 fd = open(filename, O_WRONLY | O_BINARY);
991 if (fd < 0)
992 return -EIO;
994 if (fstat(fd, &stat_buf) < 0)
995 ret = -EIO;
996 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
997 ret = -EIO;
998 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
999 ret = -ENOSPC;
1001 close(fd);
1002 return ret;
1005 static BlockDriver bdrv_host_device = {
1006 .format_name = "host_device",
1007 .instance_size = sizeof(BDRVRawState),
1008 .bdrv_probe_device = hdev_probe_device,
1009 .bdrv_open = hdev_open,
1010 .bdrv_close = raw_close,
1011 .bdrv_create = hdev_create,
1012 .create_options = raw_create_options,
1013 .no_zero_init = 1,
1014 .bdrv_flush = raw_flush,
1016 .bdrv_aio_readv = raw_aio_readv,
1017 .bdrv_aio_writev = raw_aio_writev,
1018 .bdrv_aio_flush = raw_aio_flush,
1020 .bdrv_read = raw_read,
1021 .bdrv_write = raw_write,
1022 .bdrv_getlength = raw_getlength,
1024 /* generic scsi device */
1025 #ifdef __linux__
1026 .bdrv_ioctl = hdev_ioctl,
1027 .bdrv_aio_ioctl = hdev_aio_ioctl,
1028 #endif
1031 #ifdef __linux__
1032 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1034 BDRVRawState *s = bs->opaque;
1035 int ret;
1037 s->type = FTYPE_FD;
1039 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1040 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1041 if (ret)
1042 return ret;
1044 /* close fd so that we can reopen it as needed */
1045 close(s->fd);
1046 s->fd = -1;
1047 s->fd_media_changed = 1;
1049 return 0;
1052 static int floppy_probe_device(const char *filename)
1054 int fd, ret;
1055 int prio = 0;
1056 struct floppy_struct fdparam;
1058 if (strstart(filename, "/dev/fd", NULL))
1059 prio = 50;
1061 fd = open(filename, O_RDONLY | O_NONBLOCK);
1062 if (fd < 0) {
1063 goto out;
1066 /* Attempt to detect via a floppy specific ioctl */
1067 ret = ioctl(fd, FDGETPRM, &fdparam);
1068 if (ret >= 0)
1069 prio = 100;
1071 close(fd);
1072 out:
1073 return prio;
1077 static int floppy_is_inserted(BlockDriverState *bs)
1079 return fd_open(bs) >= 0;
1082 static int floppy_media_changed(BlockDriverState *bs)
1084 BDRVRawState *s = bs->opaque;
1085 int ret;
1088 * XXX: we do not have a true media changed indication.
1089 * It does not work if the floppy is changed without trying to read it.
1091 fd_open(bs);
1092 ret = s->fd_media_changed;
1093 s->fd_media_changed = 0;
1094 #ifdef DEBUG_FLOPPY
1095 printf("Floppy changed=%d\n", ret);
1096 #endif
1097 return ret;
1100 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1102 BDRVRawState *s = bs->opaque;
1103 int fd;
1105 if (s->fd >= 0) {
1106 close(s->fd);
1107 s->fd = -1;
1109 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1110 if (fd >= 0) {
1111 if (ioctl(fd, FDEJECT, 0) < 0)
1112 perror("FDEJECT");
1113 close(fd);
1116 return 0;
1119 static BlockDriver bdrv_host_floppy = {
1120 .format_name = "host_floppy",
1121 .instance_size = sizeof(BDRVRawState),
1122 .bdrv_probe_device = floppy_probe_device,
1123 .bdrv_open = floppy_open,
1124 .bdrv_close = raw_close,
1125 .bdrv_create = hdev_create,
1126 .create_options = raw_create_options,
1127 .no_zero_init = 1,
1128 .bdrv_flush = raw_flush,
1130 .bdrv_aio_readv = raw_aio_readv,
1131 .bdrv_aio_writev = raw_aio_writev,
1132 .bdrv_aio_flush = raw_aio_flush,
1134 .bdrv_read = raw_read,
1135 .bdrv_write = raw_write,
1136 .bdrv_getlength = raw_getlength,
1138 /* removable device support */
1139 .bdrv_is_inserted = floppy_is_inserted,
1140 .bdrv_media_changed = floppy_media_changed,
1141 .bdrv_eject = floppy_eject,
1144 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1146 BDRVRawState *s = bs->opaque;
1148 s->type = FTYPE_CD;
1150 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1151 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1154 static int cdrom_probe_device(const char *filename)
1156 int fd, ret;
1157 int prio = 0;
1159 if (strstart(filename, "/dev/cd", NULL))
1160 prio = 50;
1162 fd = open(filename, O_RDONLY | O_NONBLOCK);
1163 if (fd < 0) {
1164 goto out;
1167 /* Attempt to detect via a CDROM specific ioctl */
1168 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1169 if (ret >= 0)
1170 prio = 100;
1172 close(fd);
1173 out:
1174 return prio;
1177 static int cdrom_is_inserted(BlockDriverState *bs)
1179 BDRVRawState *s = bs->opaque;
1180 int ret;
1182 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1183 if (ret == CDS_DISC_OK)
1184 return 1;
1185 return 0;
1188 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1190 BDRVRawState *s = bs->opaque;
1192 if (eject_flag) {
1193 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1194 perror("CDROMEJECT");
1195 } else {
1196 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1197 perror("CDROMEJECT");
1200 return 0;
1203 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1205 BDRVRawState *s = bs->opaque;
1207 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1209 * Note: an error can happen if the distribution automatically
1210 * mounts the CD-ROM
1212 /* perror("CDROM_LOCKDOOR"); */
1215 return 0;
1218 static BlockDriver bdrv_host_cdrom = {
1219 .format_name = "host_cdrom",
1220 .instance_size = sizeof(BDRVRawState),
1221 .bdrv_probe_device = cdrom_probe_device,
1222 .bdrv_open = cdrom_open,
1223 .bdrv_close = raw_close,
1224 .bdrv_create = hdev_create,
1225 .create_options = raw_create_options,
1226 .no_zero_init = 1,
1227 .bdrv_flush = raw_flush,
1229 .bdrv_aio_readv = raw_aio_readv,
1230 .bdrv_aio_writev = raw_aio_writev,
1231 .bdrv_aio_flush = raw_aio_flush,
1233 .bdrv_read = raw_read,
1234 .bdrv_write = raw_write,
1235 .bdrv_getlength = raw_getlength,
1237 /* removable device support */
1238 .bdrv_is_inserted = cdrom_is_inserted,
1239 .bdrv_eject = cdrom_eject,
1240 .bdrv_set_locked = cdrom_set_locked,
1242 /* generic scsi device */
1243 .bdrv_ioctl = hdev_ioctl,
1244 .bdrv_aio_ioctl = hdev_aio_ioctl,
1246 #endif /* __linux__ */
1248 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1249 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1251 BDRVRawState *s = bs->opaque;
1252 int ret;
1254 s->type = FTYPE_CD;
1256 ret = raw_open_common(bs, filename, flags, 0);
1257 if (ret)
1258 return ret;
1260 /* make sure the door isnt locked at this time */
1261 ioctl(s->fd, CDIOCALLOW);
1262 return 0;
1265 static int cdrom_probe_device(const char *filename)
1267 if (strstart(filename, "/dev/cd", NULL) ||
1268 strstart(filename, "/dev/acd", NULL))
1269 return 100;
1270 return 0;
1273 static int cdrom_reopen(BlockDriverState *bs)
1275 BDRVRawState *s = bs->opaque;
1276 int fd;
1279 * Force reread of possibly changed/newly loaded disc,
1280 * FreeBSD seems to not notice sometimes...
1282 if (s->fd >= 0)
1283 close(s->fd);
1284 fd = open(bs->filename, s->open_flags, 0644);
1285 if (fd < 0) {
1286 s->fd = -1;
1287 return -EIO;
1289 s->fd = fd;
1291 /* make sure the door isnt locked at this time */
1292 ioctl(s->fd, CDIOCALLOW);
1293 return 0;
1296 static int cdrom_is_inserted(BlockDriverState *bs)
1298 return raw_getlength(bs) > 0;
1301 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1303 BDRVRawState *s = bs->opaque;
1305 if (s->fd < 0)
1306 return -ENOTSUP;
1308 (void) ioctl(s->fd, CDIOCALLOW);
1310 if (eject_flag) {
1311 if (ioctl(s->fd, CDIOCEJECT) < 0)
1312 perror("CDIOCEJECT");
1313 } else {
1314 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1315 perror("CDIOCCLOSE");
1318 if (cdrom_reopen(bs) < 0)
1319 return -ENOTSUP;
1320 return 0;
1323 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1325 BDRVRawState *s = bs->opaque;
1327 if (s->fd < 0)
1328 return -ENOTSUP;
1329 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1331 * Note: an error can happen if the distribution automatically
1332 * mounts the CD-ROM
1334 /* perror("CDROM_LOCKDOOR"); */
1337 return 0;
1340 static BlockDriver bdrv_host_cdrom = {
1341 .format_name = "host_cdrom",
1342 .instance_size = sizeof(BDRVRawState),
1343 .bdrv_probe_device = cdrom_probe_device,
1344 .bdrv_open = cdrom_open,
1345 .bdrv_close = raw_close,
1346 .bdrv_create = hdev_create,
1347 .create_options = raw_create_options,
1348 .no_zero_init = 1,
1349 .bdrv_flush = raw_flush,
1351 .bdrv_aio_readv = raw_aio_readv,
1352 .bdrv_aio_writev = raw_aio_writev,
1353 .bdrv_aio_flush = raw_aio_flush,
1355 .bdrv_read = raw_read,
1356 .bdrv_write = raw_write,
1357 .bdrv_getlength = raw_getlength,
1359 /* removable device support */
1360 .bdrv_is_inserted = cdrom_is_inserted,
1361 .bdrv_eject = cdrom_eject,
1362 .bdrv_set_locked = cdrom_set_locked,
1364 #endif /* __FreeBSD__ */
1366 static void bdrv_raw_init(void)
1369 * Register all the drivers. Note that order is important, the driver
1370 * registered last will get probed first.
1372 bdrv_register(&bdrv_raw);
1373 bdrv_register(&bdrv_host_device);
1374 #ifdef __linux__
1375 bdrv_register(&bdrv_host_floppy);
1376 bdrv_register(&bdrv_host_cdrom);
1377 #endif
1378 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1379 bdrv_register(&bdrv_host_cdrom);
1380 #endif
1383 block_init(bdrv_raw_init);