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
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "qemu-char.h"
27 #include "block_int.h"
30 #include "posix-aio-compat.h"
35 #include <sys/param.h>
36 #include <IOKit/IOKitLib.h>
37 #include <IOKit/IOBSD.h>
38 #include <IOKit/storage/IOMediaBSDClient.h>
39 #include <IOKit/storage/IOMedia.h>
40 #include <IOKit/storage/IOCDMedia.h>
41 //#include <IOKit/storage/IOCDTypes.h>
42 #include <CoreFoundation/CoreFoundation.h>
46 #define _POSIX_PTHREAD_SEMANTICS 1
51 #include <sys/ioctl.h>
52 #include <linux/cdrom.h>
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
68 #include <sys/ioctl.h>
69 #include <sys/diskslice.h>
72 //#define DEBUG_FLOPPY
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)
79 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
82 /* OS X does not have O_DSYNC */
84 #define O_DSYNC O_SYNC
87 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
89 #define O_DIRECT O_DSYNC
96 #define ALIGNED_BUFFER_SIZE (32 * 512)
98 /* if the FD is not accessed during that time (in ms), we try to
99 reopen it to see if the disk has been changed */
100 #define FD_OPEN_TIMEOUT 1000
102 typedef struct BDRVRawState {
105 unsigned int lseek_err_cnt;
106 #if defined(__linux__)
107 /* linux floppy specific */
109 int64_t fd_open_time;
110 int64_t fd_error_time;
112 int fd_media_changed;
114 #if defined(__FreeBSD__)
117 uint8_t* aligned_buf;
120 static int posix_aio_init(void);
122 static int fd_open(BlockDriverState *bs);
124 #if defined(__FreeBSD__)
125 static int cd_open(BlockDriverState *bs);
128 static int raw_is_inserted(BlockDriverState *bs);
130 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
132 BDRVRawState *s = bs->opaque;
133 int fd, open_flags, ret;
137 s->lseek_err_cnt = 0;
139 open_flags = O_BINARY;
140 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
141 open_flags |= O_RDWR;
143 open_flags |= O_RDONLY;
146 if (flags & BDRV_O_CREAT)
147 open_flags |= O_CREAT | O_TRUNC;
149 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
150 * and O_DIRECT for no caching. */
151 if ((flags & BDRV_O_NOCACHE))
152 open_flags |= O_DIRECT;
153 else if (!(flags & BDRV_O_CACHE_WB))
154 open_flags |= O_DSYNC;
156 s->type = FTYPE_FILE;
158 fd = open(filename, open_flags, 0644);
166 s->aligned_buf = NULL;
167 if ((flags & BDRV_O_NOCACHE)) {
168 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
169 if (s->aligned_buf == NULL) {
178 /* XXX: use host sector size if necessary with:
179 #ifdef DIOCGSECTORSIZE
181 unsigned int sectorsize = 512;
182 if (!ioctl(fd, DIOCGSECTORSIZE, §orsize) &&
183 sectorsize > bufsize)
184 bufsize = sectorsize;
188 u_int32_t blockSize = 512;
189 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
196 * offset and count are in bytes, but must be multiples of 512 for files
197 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
199 * This function may be called without alignment if the caller ensures
200 * that O_DIRECT is not in effect.
202 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
203 uint8_t *buf, int count)
205 BDRVRawState *s = bs->opaque;
212 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
213 ++(s->lseek_err_cnt);
214 if(s->lseek_err_cnt <= 10) {
215 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
216 "] lseek failed : %d = %s\n",
217 s->fd, bs->filename, offset, buf, count,
218 bs->total_sectors, errno, strerror(errno));
224 ret = read(s->fd, buf, count);
226 goto label__raw_read__success;
228 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
229 "] read failed %d : %d = %s\n",
230 s->fd, bs->filename, offset, buf, count,
231 bs->total_sectors, ret, errno, strerror(errno));
233 /* Try harder for CDrom. */
234 if (bs->type == BDRV_TYPE_CDROM) {
235 lseek(s->fd, offset, SEEK_SET);
236 ret = read(s->fd, buf, count);
238 goto label__raw_read__success;
239 lseek(s->fd, offset, SEEK_SET);
240 ret = read(s->fd, buf, count);
242 goto label__raw_read__success;
244 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
245 "] retry read failed %d : %d = %s\n",
246 s->fd, bs->filename, offset, buf, count,
247 bs->total_sectors, ret, errno, strerror(errno));
250 label__raw_read__success:
252 return (ret < 0) ? -errno : ret;
256 * offset and count are in bytes, but must be multiples of 512 for files
257 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
259 * This function may be called without alignment if the caller ensures
260 * that O_DIRECT is not in effect.
262 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
263 const uint8_t *buf, int count)
265 BDRVRawState *s = bs->opaque;
272 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
273 ++(s->lseek_err_cnt);
274 if(s->lseek_err_cnt) {
275 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
276 PRId64 "] lseek failed : %d = %s\n",
277 s->fd, bs->filename, offset, buf, count,
278 bs->total_sectors, errno, strerror(errno));
282 s->lseek_err_cnt = 0;
284 ret = write(s->fd, buf, count);
286 goto label__raw_write__success;
288 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
289 "] write failed %d : %d = %s\n",
290 s->fd, bs->filename, offset, buf, count,
291 bs->total_sectors, ret, errno, strerror(errno));
293 label__raw_write__success:
295 return (ret < 0) ? -errno : ret;
300 * offset and count are in bytes and possibly not aligned. For files opened
301 * with O_DIRECT, necessary alignments are ensured before calling
302 * raw_pread_aligned to do the actual read.
304 static int raw_pread(BlockDriverState *bs, int64_t offset,
305 uint8_t *buf, int count)
307 BDRVRawState *s = bs->opaque;
308 int size, ret, shift, sum;
312 if (s->aligned_buf != NULL) {
314 if (offset & 0x1ff) {
315 /* align offset on a 512 bytes boundary */
317 shift = offset & 0x1ff;
318 size = (shift + count + 0x1ff) & ~0x1ff;
319 if (size > ALIGNED_BUFFER_SIZE)
320 size = ALIGNED_BUFFER_SIZE;
321 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
328 memcpy(buf, s->aligned_buf + shift, size);
338 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
340 /* read on aligned buffer */
344 size = (count + 0x1ff) & ~0x1ff;
345 if (size > ALIGNED_BUFFER_SIZE)
346 size = ALIGNED_BUFFER_SIZE;
348 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
356 memcpy(buf, s->aligned_buf, size);
368 return raw_pread_aligned(bs, offset, buf, count) + sum;
371 static int raw_read(BlockDriverState *bs, int64_t sector_num,
372 uint8_t *buf, int nb_sectors)
376 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
377 if (ret == (nb_sectors * 512))
383 * offset and count are in bytes and possibly not aligned. For files opened
384 * with O_DIRECT, necessary alignments are ensured before calling
385 * raw_pwrite_aligned to do the actual write.
387 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
388 const uint8_t *buf, int count)
390 BDRVRawState *s = bs->opaque;
391 int size, ret, shift, sum;
395 if (s->aligned_buf != NULL) {
397 if (offset & 0x1ff) {
398 /* align offset on a 512 bytes boundary */
399 shift = offset & 0x1ff;
400 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
407 memcpy(s->aligned_buf + shift, buf, size);
409 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
421 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
423 while ((size = (count & ~0x1ff)) != 0) {
425 if (size > ALIGNED_BUFFER_SIZE)
426 size = ALIGNED_BUFFER_SIZE;
428 memcpy(s->aligned_buf, buf, size);
430 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
439 /* here, count < 512 because (count & ~0x1ff) == 0 */
441 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
444 memcpy(s->aligned_buf, buf, count);
446 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
457 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
460 static int raw_write(BlockDriverState *bs, int64_t sector_num,
461 const uint8_t *buf, int nb_sectors)
464 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
465 if (ret == (nb_sectors * 512))
471 /***********************************************************/
472 /* Unix AIO using POSIX AIO */
474 typedef struct RawAIOCB {
475 BlockDriverAIOCB common;
476 struct qemu_paiocb aiocb;
477 struct RawAIOCB *next;
481 typedef struct PosixAioState
487 static void posix_aio_read(void *opaque)
489 PosixAioState *s = opaque;
490 RawAIOCB *acb, **pacb;
494 /* read all bytes from signal pipe */
498 len = read(s->rfd, bytes, sizeof(bytes));
499 if (len == -1 && errno == EINTR)
500 continue; /* try again */
501 if (len == sizeof(bytes))
502 continue; /* more to read */
507 pacb = &s->first_aio;
512 ret = qemu_paio_error(&acb->aiocb);
513 if (ret == ECANCELED) {
514 /* remove the request */
516 qemu_aio_release(acb);
517 } else if (ret != EINPROGRESS) {
520 ret = qemu_paio_return(&acb->aiocb);
521 if (ret == acb->aiocb.aio_nbytes)
528 /* remove the request */
530 /* call the callback */
531 acb->common.cb(acb->common.opaque, ret);
532 qemu_aio_release(acb);
542 static int posix_aio_flush(void *opaque)
544 PosixAioState *s = opaque;
545 return !!s->first_aio;
548 static PosixAioState *posix_aio_state;
550 static void aio_signal_handler(int signum)
552 if (posix_aio_state) {
555 write(posix_aio_state->wfd, &byte, sizeof(byte));
561 static int posix_aio_init(void)
563 struct sigaction act;
566 struct qemu_paioinit ai;
571 s = qemu_malloc(sizeof(PosixAioState));
573 sigfillset(&act.sa_mask);
574 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
575 act.sa_handler = aio_signal_handler;
576 sigaction(SIGUSR2, &act, NULL);
579 if (pipe(fds) == -1) {
580 fprintf(stderr, "failed to create pipe\n");
587 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
588 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
590 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
592 memset(&ai, 0, sizeof(ai));
602 static void raw_aio_remove(RawAIOCB *acb)
606 /* remove the callback from the queue */
607 pacb = &posix_aio_state->first_aio;
610 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
612 } else if (*pacb == acb) {
614 qemu_aio_release(acb);
617 pacb = &(*pacb)->next;
621 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
624 RawAIOCB *acb = (RawAIOCB *)blockacb;
626 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
627 if (ret == QEMU_PAIO_NOTCANCELED) {
628 /* fail safe: if the aio could not be canceled, we wait for
630 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
636 static AIOPool raw_aio_pool = {
637 .aiocb_size = sizeof(RawAIOCB),
638 .cancel = raw_aio_cancel,
641 static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,
642 QEMUIOVector *qiov, int nb_sectors,
643 BlockDriverCompletionFunc *cb, void *opaque)
645 BDRVRawState *s = bs->opaque;
651 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
654 acb->aiocb.aio_fildes = s->fd;
655 acb->aiocb.ev_signo = SIGUSR2;
656 acb->aiocb.aio_iov = qiov->iov;
657 acb->aiocb.aio_niov = qiov->niov;
658 acb->aiocb.aio_nbytes = nb_sectors * 512;
659 acb->aiocb.aio_offset = sector_num * 512;
660 acb->aiocb.aio_flags = 0;
663 * If O_DIRECT is used the buffer needs to be aligned on a sector
664 * boundary. Tell the low level code to ensure that in case it's
668 acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;
670 acb->next = posix_aio_state->first_aio;
671 posix_aio_state->first_aio = acb;
675 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
676 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
677 BlockDriverCompletionFunc *cb, void *opaque)
681 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
684 if (qemu_paio_read(&acb->aiocb) < 0) {
691 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
692 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
693 BlockDriverCompletionFunc *cb, void *opaque)
697 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
700 if (qemu_paio_write(&acb->aiocb) < 0) {
706 #else /* CONFIG_AIO */
707 static int posix_aio_init(void)
711 #endif /* CONFIG_AIO */
714 static void raw_close(BlockDriverState *bs)
716 BDRVRawState *s = bs->opaque;
720 if (s->aligned_buf != NULL)
721 qemu_free(s->aligned_buf);
725 static int raw_truncate(BlockDriverState *bs, int64_t offset)
727 BDRVRawState *s = bs->opaque;
728 if (s->type != FTYPE_FILE)
730 if (ftruncate(s->fd, offset) < 0)
736 static int64_t raw_getlength(BlockDriverState *bs)
738 BDRVRawState *s = bs->opaque;
744 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
747 if (ioctl(fd, DIOCGDINFO, &dl))
749 return (uint64_t)dl.d_secsize *
750 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
754 #else /* !__OpenBSD__ */
755 static int64_t raw_getlength(BlockDriverState *bs)
757 BDRVRawState *s = bs->opaque;
767 struct dk_minfo minfo;
780 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
781 #ifdef DIOCGMEDIASIZE
782 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
783 #elif defined(DIOCGPART)
786 if (ioctl(fd, DIOCGPART, &pi) == 0)
787 size = pi.media_size;
794 size = LONG_LONG_MAX;
796 size = lseek(fd, 0LL, SEEK_END);
801 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
802 if (size == 2048LL * (unsigned)-1)
804 /* XXX no disc? maybe we need to reopen... */
805 if (size <= 0 && !reopened && cd_open(bs) >= 0) {
815 * use the DKIOCGMEDIAINFO ioctl to read the size.
817 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
819 size = minfo.dki_lbsize * minfo.dki_capacity;
820 } else /* there are reports that lseek on some devices
821 fails, but irc discussion said that contingency
822 on contingency was overkill */
825 size = lseek(fd, 0, SEEK_END);
831 static int raw_create(const char *filename, QEMUOptionParameter *options)
834 int64_t total_size = 0;
836 /* Read out options */
837 while (options && options->name) {
838 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
839 total_size = options->value.n / 512;
844 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
848 ftruncate(fd, total_size * 512);
853 static void raw_flush(BlockDriverState *bs)
855 BDRVRawState *s = bs->opaque;
860 static QEMUOptionParameter raw_create_options[] = {
861 { BLOCK_OPT_SIZE, OPT_SIZE },
865 static BlockDriver bdrv_raw = {
866 .format_name = "raw",
867 .instance_size = sizeof(BDRVRawState),
868 .bdrv_probe = NULL, /* no probe for protocols */
869 .bdrv_open = raw_open,
870 .bdrv_read = raw_read,
871 .bdrv_write = raw_write,
872 .bdrv_close = raw_close,
873 .bdrv_create = raw_create,
874 .bdrv_flush = raw_flush,
877 .bdrv_aio_readv = raw_aio_readv,
878 .bdrv_aio_writev = raw_aio_writev,
881 .bdrv_truncate = raw_truncate,
882 .bdrv_getlength = raw_getlength,
884 .create_options = raw_create_options,
887 /***********************************************/
891 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
892 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
894 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
896 kern_return_t kernResult;
897 mach_port_t masterPort;
898 CFMutableDictionaryRef classesToMatch;
900 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
901 if ( KERN_SUCCESS != kernResult ) {
902 printf( "IOMasterPort returned %d\n", kernResult );
905 classesToMatch = IOServiceMatching( kIOCDMediaClass );
906 if ( classesToMatch == NULL ) {
907 printf( "IOServiceMatching returned a NULL dictionary.\n" );
909 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
911 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
912 if ( KERN_SUCCESS != kernResult )
914 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
920 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
922 io_object_t nextMedia;
923 kern_return_t kernResult = KERN_FAILURE;
925 nextMedia = IOIteratorNext( mediaIterator );
928 CFTypeRef bsdPathAsCFString;
929 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
930 if ( bsdPathAsCFString ) {
931 size_t devPathLength;
932 strcpy( bsdPath, _PATH_DEV );
933 strcat( bsdPath, "r" );
934 devPathLength = strlen( bsdPath );
935 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
936 kernResult = KERN_SUCCESS;
938 CFRelease( bsdPathAsCFString );
940 IOObjectRelease( nextMedia );
948 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
950 BDRVRawState *s = bs->opaque;
951 int fd, open_flags, ret;
956 if (strstart(filename, "/dev/cdrom", NULL)) {
957 kern_return_t kernResult;
958 io_iterator_t mediaIterator;
959 char bsdPath[ MAXPATHLEN ];
962 kernResult = FindEjectableCDMedia( &mediaIterator );
963 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
965 if ( bsdPath[ 0 ] != '\0' ) {
966 strcat(bsdPath,"s0");
967 /* some CDs don't have a partition 0 */
968 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
970 bsdPath[strlen(bsdPath)-1] = '1';
978 IOObjectRelease( mediaIterator );
981 open_flags = O_BINARY;
982 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
983 open_flags |= O_RDWR;
985 open_flags |= O_RDONLY;
988 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
989 * and O_DIRECT for no caching. */
990 if ((flags & BDRV_O_NOCACHE))
991 open_flags |= O_DIRECT;
992 else if (!(flags & BDRV_O_CACHE_WB))
993 open_flags |= O_DSYNC;
995 s->type = FTYPE_FILE;
996 #if defined(__linux__)
997 if (strstart(filename, "/dev/cd", NULL)) {
998 /* open will not fail even if no CD is inserted */
999 open_flags |= O_NONBLOCK;
1001 } else if (strstart(filename, "/dev/fd", NULL)) {
1003 s->fd_open_flags = open_flags;
1004 /* open will not fail even if no floppy is inserted */
1005 open_flags |= O_NONBLOCK;
1007 } else if (strstart(filename, "/dev/sg", NULL)) {
1012 #if defined(__FreeBSD__)
1013 if (strstart(filename, "/dev/cd", NULL) ||
1014 strstart(filename, "/dev/acd", NULL)) {
1016 s->cd_open_flags = open_flags;
1020 fd = open(filename, open_flags, 0644);
1028 #if defined(__FreeBSD__)
1029 /* make sure the door isnt locked at this time */
1030 if (s->type == FTYPE_CD)
1031 ioctl (s->fd, CDIOCALLOW);
1033 #if defined(__linux__)
1034 /* close fd so that we can reopen it as needed */
1035 if (s->type == FTYPE_FD) {
1038 s->fd_media_changed = 1;
1044 #if defined(__linux__)
1045 /* Note: we do not have a reliable method to detect if the floppy is
1046 present. The current method is to try to open the floppy at every
1047 I/O and to keep it opened during a few hundreds of ms. */
1048 static int fd_open(BlockDriverState *bs)
1050 BDRVRawState *s = bs->opaque;
1051 int last_media_present;
1053 if (s->type != FTYPE_FD)
1055 last_media_present = (s->fd >= 0);
1057 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1061 printf("Floppy closed\n");
1065 if (s->fd_got_error &&
1066 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1068 printf("No floppy (open delayed)\n");
1072 s->fd = open(bs->filename, s->fd_open_flags);
1074 s->fd_error_time = qemu_get_clock(rt_clock);
1075 s->fd_got_error = 1;
1076 if (last_media_present)
1077 s->fd_media_changed = 1;
1079 printf("No floppy\n");
1084 printf("Floppy opened\n");
1087 if (!last_media_present)
1088 s->fd_media_changed = 1;
1089 s->fd_open_time = qemu_get_clock(rt_clock);
1090 s->fd_got_error = 0;
1094 static int raw_is_inserted(BlockDriverState *bs)
1096 BDRVRawState *s = bs->opaque;
1101 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1102 if (ret == CDS_DISC_OK)
1115 /* currently only used by fdc.c, but a CD version would be good too */
1116 static int raw_media_changed(BlockDriverState *bs)
1118 BDRVRawState *s = bs->opaque;
1124 /* XXX: we do not have a true media changed indication. It
1125 does not work if the floppy is changed without trying
1128 ret = s->fd_media_changed;
1129 s->fd_media_changed = 0;
1131 printf("Floppy changed=%d\n", ret);
1140 static int raw_eject(BlockDriverState *bs, int eject_flag)
1142 BDRVRawState *s = bs->opaque;
1147 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1148 perror("CDROMEJECT");
1150 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1151 perror("CDROMEJECT");
1161 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1163 if (ioctl(fd, FDEJECT, 0) < 0)
1175 static int raw_set_locked(BlockDriverState *bs, int locked)
1177 BDRVRawState *s = bs->opaque;
1181 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1182 /* Note: an error can happen if the distribution automatically
1183 mounts the CD-ROM */
1184 // perror("CDROM_LOCKDOOR");
1193 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1195 BDRVRawState *s = bs->opaque;
1197 return ioctl(s->fd, req, buf);
1201 static BlockDriverAIOCB *raw_aio_ioctl(BlockDriverState *bs,
1202 unsigned long int req, void *buf,
1203 BlockDriverCompletionFunc *cb, void *opaque)
1205 BDRVRawState *s = bs->opaque;
1208 if (fd_open(bs) < 0)
1211 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
1214 acb->aiocb.aio_fildes = s->fd;
1215 acb->aiocb.ev_signo = SIGUSR2;
1216 acb->aiocb.aio_offset = 0;
1217 acb->aiocb.aio_flags = 0;
1219 acb->next = posix_aio_state->first_aio;
1220 posix_aio_state->first_aio = acb;
1222 acb->aiocb.aio_ioctl_buf = buf;
1223 acb->aiocb.aio_ioctl_cmd = req;
1224 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1225 raw_aio_remove(acb);
1229 return &acb->common;
1233 #elif defined(__FreeBSD__)
1235 static int fd_open(BlockDriverState *bs)
1237 BDRVRawState *s = bs->opaque;
1239 /* this is just to ensure s->fd is sane (its called by io ops) */
1245 static int cd_open(BlockDriverState *bs)
1247 #if defined(__FreeBSD__)
1248 BDRVRawState *s = bs->opaque;
1253 /* XXX force reread of possibly changed/newly loaded disc,
1254 * FreeBSD seems to not notice sometimes... */
1257 fd = open(bs->filename, s->cd_open_flags, 0644);
1263 /* make sure the door isnt locked at this time */
1264 ioctl (s->fd, CDIOCALLOW);
1270 static int raw_is_inserted(BlockDriverState *bs)
1272 BDRVRawState *s = bs->opaque;
1276 return (raw_getlength(bs) > 0);
1278 /* XXX handle this */
1285 static int raw_media_changed(BlockDriverState *bs)
1290 static int raw_eject(BlockDriverState *bs, int eject_flag)
1292 BDRVRawState *s = bs->opaque;
1298 (void) ioctl (s->fd, CDIOCALLOW);
1300 if (ioctl (s->fd, CDIOCEJECT) < 0)
1301 perror("CDIOCEJECT");
1303 if (ioctl (s->fd, CDIOCCLOSE) < 0)
1304 perror("CDIOCCLOSE");
1306 if (cd_open(bs) < 0)
1310 /* XXX handle this */
1318 static int raw_set_locked(BlockDriverState *bs, int locked)
1320 BDRVRawState *s = bs->opaque;
1326 if (ioctl (s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1327 /* Note: an error can happen if the distribution automatically
1328 mounts the CD-ROM */
1329 // perror("CDROM_LOCKDOOR");
1338 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1342 #else /* !linux && !FreeBSD */
1344 static int fd_open(BlockDriverState *bs)
1349 static int raw_is_inserted(BlockDriverState *bs)
1354 static int raw_media_changed(BlockDriverState *bs)
1359 static int raw_eject(BlockDriverState *bs, int eject_flag)
1364 static int raw_set_locked(BlockDriverState *bs, int locked)
1369 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1374 static BlockDriverAIOCB *raw_aio_ioctl(BlockDriverState *bs,
1375 unsigned long int req, void *buf,
1376 BlockDriverCompletionFunc *cb, void *opaque)
1380 #endif /* !linux && !FreeBSD */
1382 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1386 struct stat stat_buf;
1387 int64_t total_size = 0;
1389 /* Read out options */
1390 while (options && options->name) {
1391 if (!strcmp(options->name, "size")) {
1392 total_size = options->value.n / 512;
1397 fd = open(filename, O_WRONLY | O_BINARY);
1401 if (fstat(fd, &stat_buf) < 0)
1403 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1405 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1412 static BlockDriver bdrv_host_device = {
1413 .format_name = "host_device",
1414 .instance_size = sizeof(BDRVRawState),
1415 .bdrv_open = hdev_open,
1416 .bdrv_close = raw_close,
1417 .bdrv_create = hdev_create,
1418 .bdrv_flush = raw_flush,
1421 .bdrv_aio_readv = raw_aio_readv,
1422 .bdrv_aio_writev = raw_aio_writev,
1425 .bdrv_read = raw_read,
1426 .bdrv_write = raw_write,
1427 .bdrv_getlength = raw_getlength,
1429 /* removable device support */
1430 .bdrv_is_inserted = raw_is_inserted,
1431 .bdrv_media_changed = raw_media_changed,
1432 .bdrv_eject = raw_eject,
1433 .bdrv_set_locked = raw_set_locked,
1434 /* generic scsi device */
1435 .bdrv_ioctl = raw_ioctl,
1437 .bdrv_aio_ioctl = raw_aio_ioctl,
1441 static void bdrv_raw_init(void)
1443 bdrv_register(&bdrv_raw);
1444 bdrv_register(&bdrv_host_device);
1447 block_init(bdrv_raw_init);