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"
26 #include "qemu-timer.h"
29 #include "block_int.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>
59 //#define DEBUG_FLOPPY
62 #if defined(DEBUG_BLOCK) && !defined(QEMU_IMG)
63 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
64 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
66 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
73 /* if the FD is not accessed during that time (in ms), we try to
74 reopen it to see if the disk has been changed */
75 #define FD_OPEN_TIMEOUT 1000
77 typedef struct BDRVRawState
{
80 unsigned int lseek_err_cnt
;
81 #if defined(__linux__)
82 /* linux floppy specific */
85 int64_t fd_error_time
;
91 static int fd_open(BlockDriverState
*bs
);
93 static int raw_open(BlockDriverState
*bs
, const char *filename
, int flags
)
95 BDRVRawState
*s
= bs
->opaque
;
96 int fd
, open_flags
, ret
;
100 open_flags
= O_BINARY
;
101 if ((flags
& BDRV_O_ACCESS
) == O_RDWR
) {
102 open_flags
|= O_RDWR
;
104 open_flags
|= O_RDONLY
;
107 if (flags
& BDRV_O_CREAT
)
108 open_flags
|= O_CREAT
| O_TRUNC
;
110 s
->type
= FTYPE_FILE
;
112 fd
= open(filename
, open_flags
, 0644);
123 /* XXX: use host sector size if necessary with:
124 #ifdef DIOCGSECTORSIZE
126 unsigned int sectorsize = 512;
127 if (!ioctl(fd, DIOCGSECTORSIZE, §orsize) &&
128 sectorsize > bufsize)
129 bufsize = sectorsize;
133 u_int32_t blockSize = 512;
134 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
140 static int raw_pread(BlockDriverState
*bs
, int64_t offset
,
141 uint8_t *buf
, int count
)
143 BDRVRawState
*s
= bs
->opaque
;
150 if (lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
151 ++(s
->lseek_err_cnt
);
152 if(s
->lseek_err_cnt
<= 10) {
153 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
154 "] lseek failed : %d = %s\n",
155 s
->fd
, bs
->filename
, offset
, buf
, count
,
156 bs
->total_sectors
, errno
, strerror(errno
));
162 ret
= read(s
->fd
, buf
, count
);
164 goto label__raw_read__success
;
166 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
167 "] read failed %d : %d = %s\n",
168 s
->fd
, bs
->filename
, offset
, buf
, count
,
169 bs
->total_sectors
, ret
, errno
, strerror(errno
));
171 /* Try harder for CDrom. */
172 if (bs
->type
== BDRV_TYPE_CDROM
) {
173 lseek(s
->fd
, offset
, SEEK_SET
);
174 ret
= read(s
->fd
, buf
, count
);
176 goto label__raw_read__success
;
177 lseek(s
->fd
, offset
, SEEK_SET
);
178 ret
= read(s
->fd
, buf
, count
);
180 goto label__raw_read__success
;
182 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
183 "] retry read failed %d : %d = %s\n",
184 s
->fd
, bs
->filename
, offset
, buf
, count
,
185 bs
->total_sectors
, ret
, errno
, strerror(errno
));
188 label__raw_read__success
:
193 static int raw_pwrite(BlockDriverState
*bs
, int64_t offset
,
194 const uint8_t *buf
, int count
)
196 BDRVRawState
*s
= bs
->opaque
;
203 if (lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
204 ++(s
->lseek_err_cnt
);
205 if(s
->lseek_err_cnt
) {
206 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%"
207 PRId64
"] lseek failed : %d = %s\n",
208 s
->fd
, bs
->filename
, offset
, buf
, count
,
209 bs
->total_sectors
, errno
, strerror(errno
));
213 s
->lseek_err_cnt
= 0;
215 ret
= write(s
->fd
, buf
, count
);
217 goto label__raw_write__success
;
219 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%" PRId64
220 "] write failed %d : %d = %s\n",
221 s
->fd
, bs
->filename
, offset
, buf
, count
,
222 bs
->total_sectors
, ret
, errno
, strerror(errno
));
224 label__raw_write__success
:
229 /***********************************************************/
230 /* Unix AIO using POSIX AIO */
232 typedef struct RawAIOCB
{
233 BlockDriverAIOCB common
;
235 struct RawAIOCB
*next
;
238 static int aio_sig_num
= SIGUSR2
;
239 static RawAIOCB
*first_aio
; /* AIO issued */
240 static int aio_initialized
= 0;
242 static void aio_signal_handler(int signum
)
245 CPUState
*env
= cpu_single_env
;
247 /* stop the currently executing cpu because a timer occured */
248 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
250 if (env
->kqemu_enabled
) {
251 kqemu_cpu_interrupt(env
);
258 void qemu_aio_init(void)
260 struct sigaction act
;
264 sigfillset(&act
.sa_mask
);
265 act
.sa_flags
= 0; /* do not restart syscalls to interrupt select() */
266 act
.sa_handler
= aio_signal_handler
;
267 sigaction(aio_sig_num
, &act
, NULL
);
269 #if defined(__GLIBC__) && defined(__linux__)
271 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
272 seems to fix the problem. */
274 memset(&ai
, 0, sizeof(ai
));
277 ai
.aio_idle_time
= 365 * 100000;
283 void qemu_aio_poll(void)
285 RawAIOCB
*acb
, **pacb
;
294 ret
= aio_error(&acb
->aiocb
);
295 if (ret
== ECANCELED
) {
296 /* remove the request */
298 qemu_aio_release(acb
);
299 } else if (ret
!= EINPROGRESS
) {
302 ret
= aio_return(&acb
->aiocb
);
303 if (ret
== acb
->aiocb
.aio_nbytes
)
310 /* remove the request */
312 /* call the callback */
313 acb
->common
.cb(acb
->common
.opaque
, ret
);
314 qemu_aio_release(acb
);
324 /* Wait for all IO requests to complete. */
325 void qemu_aio_flush(void)
327 qemu_aio_wait_start();
335 /* wait until at least one AIO was handled */
336 static sigset_t wait_oset
;
338 void qemu_aio_wait_start(void)
342 if (!aio_initialized
)
345 sigaddset(&set
, aio_sig_num
);
346 sigprocmask(SIG_BLOCK
, &set
, &wait_oset
);
349 void qemu_aio_wait(void)
359 sigaddset(&set
, aio_sig_num
);
360 sigwait(&set
, &nb_sigs
);
364 void qemu_aio_wait_end(void)
366 sigprocmask(SIG_SETMASK
, &wait_oset
, NULL
);
369 static RawAIOCB
*raw_aio_setup(BlockDriverState
*bs
,
370 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
371 BlockDriverCompletionFunc
*cb
, void *opaque
)
373 BDRVRawState
*s
= bs
->opaque
;
379 acb
= qemu_aio_get(bs
, cb
, opaque
);
382 acb
->aiocb
.aio_fildes
= s
->fd
;
383 acb
->aiocb
.aio_sigevent
.sigev_signo
= aio_sig_num
;
384 acb
->aiocb
.aio_sigevent
.sigev_notify
= SIGEV_SIGNAL
;
385 acb
->aiocb
.aio_buf
= buf
;
386 acb
->aiocb
.aio_nbytes
= nb_sectors
* 512;
387 acb
->aiocb
.aio_offset
= sector_num
* 512;
388 acb
->next
= first_aio
;
393 static BlockDriverAIOCB
*raw_aio_read(BlockDriverState
*bs
,
394 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
395 BlockDriverCompletionFunc
*cb
, void *opaque
)
399 acb
= raw_aio_setup(bs
, sector_num
, buf
, nb_sectors
, cb
, opaque
);
402 if (aio_read(&acb
->aiocb
) < 0) {
403 qemu_aio_release(acb
);
409 static BlockDriverAIOCB
*raw_aio_write(BlockDriverState
*bs
,
410 int64_t sector_num
, const uint8_t *buf
, int nb_sectors
,
411 BlockDriverCompletionFunc
*cb
, void *opaque
)
415 acb
= raw_aio_setup(bs
, sector_num
, (uint8_t*)buf
, nb_sectors
, cb
, opaque
);
418 if (aio_write(&acb
->aiocb
) < 0) {
419 qemu_aio_release(acb
);
425 static void raw_aio_cancel(BlockDriverAIOCB
*blockacb
)
428 RawAIOCB
*acb
= (RawAIOCB
*)blockacb
;
431 ret
= aio_cancel(acb
->aiocb
.aio_fildes
, &acb
->aiocb
);
432 if (ret
== AIO_NOTCANCELED
) {
433 /* fail safe: if the aio could not be canceled, we wait for
435 while (aio_error(&acb
->aiocb
) == EINPROGRESS
);
438 /* remove the callback from the queue */
443 } else if (*pacb
== acb
) {
445 qemu_aio_release(acb
);
452 static void raw_close(BlockDriverState
*bs
)
454 BDRVRawState
*s
= bs
->opaque
;
461 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
463 BDRVRawState
*s
= bs
->opaque
;
464 if (s
->type
!= FTYPE_FILE
)
466 if (ftruncate(s
->fd
, offset
) < 0)
471 static int64_t raw_getlength(BlockDriverState
*bs
)
473 BDRVRawState
*s
= bs
->opaque
;
480 struct dk_minfo minfo
;
490 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
491 #ifdef DIOCGMEDIASIZE
492 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
495 size
= LONG_LONG_MAX
;
497 size
= lseek(fd
, 0LL, SEEK_END
);
503 * use the DKIOCGMEDIAINFO ioctl to read the size.
505 rv
= ioctl ( fd
, DKIOCGMEDIAINFO
, &minfo
);
507 size
= minfo
.dki_lbsize
* minfo
.dki_capacity
;
508 } else /* there are reports that lseek on some devices
509 fails, but irc discussion said that contingency
510 on contingency was overkill */
513 size
= lseek(fd
, 0, SEEK_END
);
518 static int raw_create(const char *filename
, int64_t total_size
,
519 const char *backing_file
, int flags
)
523 if (flags
|| backing_file
)
526 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
530 ftruncate(fd
, total_size
* 512);
535 static void raw_flush(BlockDriverState
*bs
)
537 BDRVRawState
*s
= bs
->opaque
;
541 BlockDriver bdrv_raw
= {
543 sizeof(BDRVRawState
),
544 NULL
, /* no probe for protocols */
552 .bdrv_aio_read
= raw_aio_read
,
553 .bdrv_aio_write
= raw_aio_write
,
554 .bdrv_aio_cancel
= raw_aio_cancel
,
555 .aiocb_size
= sizeof(RawAIOCB
),
556 .protocol_name
= "file",
557 .bdrv_pread
= raw_pread
,
558 .bdrv_pwrite
= raw_pwrite
,
559 .bdrv_truncate
= raw_truncate
,
560 .bdrv_getlength
= raw_getlength
,
563 /***********************************************/
567 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
568 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
570 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
572 kern_return_t kernResult
;
573 mach_port_t masterPort
;
574 CFMutableDictionaryRef classesToMatch
;
576 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
577 if ( KERN_SUCCESS
!= kernResult
) {
578 printf( "IOMasterPort returned %d\n", kernResult
);
581 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
582 if ( classesToMatch
== NULL
) {
583 printf( "IOServiceMatching returned a NULL dictionary.\n" );
585 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
587 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
588 if ( KERN_SUCCESS
!= kernResult
)
590 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
596 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
598 io_object_t nextMedia
;
599 kern_return_t kernResult
= KERN_FAILURE
;
601 nextMedia
= IOIteratorNext( mediaIterator
);
604 CFTypeRef bsdPathAsCFString
;
605 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
606 if ( bsdPathAsCFString
) {
607 size_t devPathLength
;
608 strcpy( bsdPath
, _PATH_DEV
);
609 strcat( bsdPath
, "r" );
610 devPathLength
= strlen( bsdPath
);
611 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
612 kernResult
= KERN_SUCCESS
;
614 CFRelease( bsdPathAsCFString
);
616 IOObjectRelease( nextMedia
);
624 static int hdev_open(BlockDriverState
*bs
, const char *filename
, int flags
)
626 BDRVRawState
*s
= bs
->opaque
;
627 int fd
, open_flags
, ret
;
630 if (strstart(filename
, "/dev/cdrom", NULL
)) {
631 kern_return_t kernResult
;
632 io_iterator_t mediaIterator
;
633 char bsdPath
[ MAXPATHLEN
];
636 kernResult
= FindEjectableCDMedia( &mediaIterator
);
637 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
639 if ( bsdPath
[ 0 ] != '\0' ) {
640 strcat(bsdPath
,"s0");
641 /* some CDs don't have a partition 0 */
642 fd
= open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
644 bsdPath
[strlen(bsdPath
)-1] = '1';
652 IOObjectRelease( mediaIterator
);
655 open_flags
= O_BINARY
;
656 if ((flags
& BDRV_O_ACCESS
) == O_RDWR
) {
657 open_flags
|= O_RDWR
;
659 open_flags
|= O_RDONLY
;
663 s
->type
= FTYPE_FILE
;
664 #if defined(__linux__)
665 if (strstart(filename
, "/dev/cd", NULL
)) {
666 /* open will not fail even if no CD is inserted */
667 open_flags
|= O_NONBLOCK
;
669 } else if (strstart(filename
, "/dev/fd", NULL
)) {
671 s
->fd_open_flags
= open_flags
;
672 /* open will not fail even if no floppy is inserted */
673 open_flags
|= O_NONBLOCK
;
676 fd
= open(filename
, open_flags
, 0644);
684 #if defined(__linux__)
685 /* close fd so that we can reopen it as needed */
686 if (s
->type
== FTYPE_FD
) {
689 s
->fd_media_changed
= 1;
695 #if defined(__linux__) && !defined(QEMU_IMG)
697 /* Note: we do not have a reliable method to detect if the floppy is
698 present. The current method is to try to open the floppy at every
699 I/O and to keep it opened during a few hundreds of ms. */
700 static int fd_open(BlockDriverState
*bs
)
702 BDRVRawState
*s
= bs
->opaque
;
703 int last_media_present
;
705 if (s
->type
!= FTYPE_FD
)
707 last_media_present
= (s
->fd
>= 0);
709 (qemu_get_clock(rt_clock
) - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
713 printf("Floppy closed\n");
717 if (s
->fd_got_error
&&
718 (qemu_get_clock(rt_clock
) - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
720 printf("No floppy (open delayed)\n");
724 s
->fd
= open(bs
->filename
, s
->fd_open_flags
);
726 s
->fd_error_time
= qemu_get_clock(rt_clock
);
728 if (last_media_present
)
729 s
->fd_media_changed
= 1;
731 printf("No floppy\n");
736 printf("Floppy opened\n");
739 if (!last_media_present
)
740 s
->fd_media_changed
= 1;
741 s
->fd_open_time
= qemu_get_clock(rt_clock
);
746 static int fd_open(BlockDriverState
*bs
)
752 #if defined(__linux__)
754 static int raw_is_inserted(BlockDriverState
*bs
)
756 BDRVRawState
*s
= bs
->opaque
;
761 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
762 if (ret
== CDS_DISC_OK
)
775 /* currently only used by fdc.c, but a CD version would be good too */
776 static int raw_media_changed(BlockDriverState
*bs
)
778 BDRVRawState
*s
= bs
->opaque
;
784 /* XXX: we do not have a true media changed indication. It
785 does not work if the floppy is changed without trying
788 ret
= s
->fd_media_changed
;
789 s
->fd_media_changed
= 0;
791 printf("Floppy changed=%d\n", ret
);
800 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
802 BDRVRawState
*s
= bs
->opaque
;
807 if (ioctl (s
->fd
, CDROMEJECT
, NULL
) < 0)
808 perror("CDROMEJECT");
810 if (ioctl (s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
811 perror("CDROMEJECT");
821 fd
= open(bs
->filename
, s
->fd_open_flags
| O_NONBLOCK
);
823 if (ioctl(fd
, FDEJECT
, 0) < 0)
835 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
837 BDRVRawState
*s
= bs
->opaque
;
841 if (ioctl (s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
842 /* Note: an error can happen if the distribution automatically
844 // perror("CDROM_LOCKDOOR");
855 static int raw_is_inserted(BlockDriverState
*bs
)
860 static int raw_media_changed(BlockDriverState
*bs
)
865 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
870 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
877 BlockDriver bdrv_host_device
= {
879 sizeof(BDRVRawState
),
880 NULL
, /* no probe for protocols */
888 .bdrv_aio_read
= raw_aio_read
,
889 .bdrv_aio_write
= raw_aio_write
,
890 .bdrv_aio_cancel
= raw_aio_cancel
,
891 .aiocb_size
= sizeof(RawAIOCB
),
892 .bdrv_pread
= raw_pread
,
893 .bdrv_pwrite
= raw_pwrite
,
894 .bdrv_getlength
= raw_getlength
,
896 /* removable device support */
897 .bdrv_is_inserted
= raw_is_inserted
,
898 .bdrv_media_changed
= raw_media_changed
,
899 .bdrv_eject
= raw_eject
,
900 .bdrv_set_locked
= raw_set_locked
,