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 if (flags
& BDRV_O_DIRECT
)
111 open_flags
|= O_DIRECT
;
114 s
->type
= FTYPE_FILE
;
116 fd
= open(filename
, open_flags
, 0644);
127 /* XXX: use host sector size if necessary with:
128 #ifdef DIOCGSECTORSIZE
130 unsigned int sectorsize = 512;
131 if (!ioctl(fd, DIOCGSECTORSIZE, §orsize) &&
132 sectorsize > bufsize)
133 bufsize = sectorsize;
137 u_int32_t blockSize = 512;
138 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
144 static int raw_pread(BlockDriverState
*bs
, int64_t offset
,
145 uint8_t *buf
, int count
)
147 BDRVRawState
*s
= bs
->opaque
;
154 if (lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
155 ++(s
->lseek_err_cnt
);
156 if(s
->lseek_err_cnt
<= 10) {
157 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
158 "] lseek failed : %d = %s\n",
159 s
->fd
, bs
->filename
, offset
, buf
, count
,
160 bs
->total_sectors
, errno
, strerror(errno
));
166 ret
= read(s
->fd
, buf
, count
);
168 goto label__raw_read__success
;
170 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
171 "] read failed %d : %d = %s\n",
172 s
->fd
, bs
->filename
, offset
, buf
, count
,
173 bs
->total_sectors
, ret
, errno
, strerror(errno
));
175 /* Try harder for CDrom. */
176 if (bs
->type
== BDRV_TYPE_CDROM
) {
177 lseek(s
->fd
, offset
, SEEK_SET
);
178 ret
= read(s
->fd
, buf
, count
);
180 goto label__raw_read__success
;
181 lseek(s
->fd
, offset
, SEEK_SET
);
182 ret
= read(s
->fd
, buf
, count
);
184 goto label__raw_read__success
;
186 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
187 "] retry read failed %d : %d = %s\n",
188 s
->fd
, bs
->filename
, offset
, buf
, count
,
189 bs
->total_sectors
, ret
, errno
, strerror(errno
));
192 label__raw_read__success
:
197 static int raw_pwrite(BlockDriverState
*bs
, int64_t offset
,
198 const uint8_t *buf
, int count
)
200 BDRVRawState
*s
= bs
->opaque
;
207 if (lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
208 ++(s
->lseek_err_cnt
);
209 if(s
->lseek_err_cnt
) {
210 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%"
211 PRId64
"] lseek failed : %d = %s\n",
212 s
->fd
, bs
->filename
, offset
, buf
, count
,
213 bs
->total_sectors
, errno
, strerror(errno
));
217 s
->lseek_err_cnt
= 0;
219 ret
= write(s
->fd
, buf
, count
);
221 goto label__raw_write__success
;
223 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%" PRId64
224 "] write failed %d : %d = %s\n",
225 s
->fd
, bs
->filename
, offset
, buf
, count
,
226 bs
->total_sectors
, ret
, errno
, strerror(errno
));
228 label__raw_write__success
:
233 /***********************************************************/
234 /* Unix AIO using POSIX AIO */
236 typedef struct RawAIOCB
{
237 BlockDriverAIOCB common
;
239 struct RawAIOCB
*next
;
242 static int aio_sig_num
= SIGUSR2
;
243 static RawAIOCB
*first_aio
; /* AIO issued */
244 static int aio_initialized
= 0;
246 static void aio_signal_handler(int signum
)
249 CPUState
*env
= cpu_single_env
;
251 /* stop the currently executing cpu because a timer occured */
252 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
254 if (env
->kqemu_enabled
) {
255 kqemu_cpu_interrupt(env
);
262 void qemu_aio_init(void)
264 struct sigaction act
;
268 sigfillset(&act
.sa_mask
);
269 act
.sa_flags
= 0; /* do not restart syscalls to interrupt select() */
270 act
.sa_handler
= aio_signal_handler
;
271 sigaction(aio_sig_num
, &act
, NULL
);
273 #if defined(__GLIBC__) && defined(__linux__)
275 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
276 seems to fix the problem. */
278 memset(&ai
, 0, sizeof(ai
));
281 ai
.aio_idle_time
= 365 * 100000;
287 void qemu_aio_poll(void)
289 RawAIOCB
*acb
, **pacb
;
298 ret
= aio_error(&acb
->aiocb
);
299 if (ret
== ECANCELED
) {
300 /* remove the request */
302 qemu_aio_release(acb
);
303 } else if (ret
!= EINPROGRESS
) {
306 ret
= aio_return(&acb
->aiocb
);
307 if (ret
== acb
->aiocb
.aio_nbytes
)
314 /* remove the request */
316 /* call the callback */
317 acb
->common
.cb(acb
->common
.opaque
, ret
);
318 qemu_aio_release(acb
);
328 /* Wait for all IO requests to complete. */
329 void qemu_aio_flush(void)
331 qemu_aio_wait_start();
339 /* wait until at least one AIO was handled */
340 static sigset_t wait_oset
;
342 void qemu_aio_wait_start(void)
346 if (!aio_initialized
)
349 sigaddset(&set
, aio_sig_num
);
350 sigprocmask(SIG_BLOCK
, &set
, &wait_oset
);
353 void qemu_aio_wait(void)
363 sigaddset(&set
, aio_sig_num
);
364 sigwait(&set
, &nb_sigs
);
368 void qemu_aio_wait_end(void)
370 sigprocmask(SIG_SETMASK
, &wait_oset
, NULL
);
373 static RawAIOCB
*raw_aio_setup(BlockDriverState
*bs
,
374 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
375 BlockDriverCompletionFunc
*cb
, void *opaque
)
377 BDRVRawState
*s
= bs
->opaque
;
383 acb
= qemu_aio_get(bs
, cb
, opaque
);
386 acb
->aiocb
.aio_fildes
= s
->fd
;
387 acb
->aiocb
.aio_sigevent
.sigev_signo
= aio_sig_num
;
388 acb
->aiocb
.aio_sigevent
.sigev_notify
= SIGEV_SIGNAL
;
389 acb
->aiocb
.aio_buf
= buf
;
390 acb
->aiocb
.aio_nbytes
= nb_sectors
* 512;
391 acb
->aiocb
.aio_offset
= sector_num
* 512;
392 acb
->next
= first_aio
;
397 static BlockDriverAIOCB
*raw_aio_read(BlockDriverState
*bs
,
398 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
399 BlockDriverCompletionFunc
*cb
, void *opaque
)
403 acb
= raw_aio_setup(bs
, sector_num
, buf
, nb_sectors
, cb
, opaque
);
406 if (aio_read(&acb
->aiocb
) < 0) {
407 qemu_aio_release(acb
);
413 static BlockDriverAIOCB
*raw_aio_write(BlockDriverState
*bs
,
414 int64_t sector_num
, const uint8_t *buf
, int nb_sectors
,
415 BlockDriverCompletionFunc
*cb
, void *opaque
)
419 acb
= raw_aio_setup(bs
, sector_num
, (uint8_t*)buf
, nb_sectors
, cb
, opaque
);
422 if (aio_write(&acb
->aiocb
) < 0) {
423 qemu_aio_release(acb
);
429 static void raw_aio_cancel(BlockDriverAIOCB
*blockacb
)
432 RawAIOCB
*acb
= (RawAIOCB
*)blockacb
;
435 ret
= aio_cancel(acb
->aiocb
.aio_fildes
, &acb
->aiocb
);
436 if (ret
== AIO_NOTCANCELED
) {
437 /* fail safe: if the aio could not be canceled, we wait for
439 while (aio_error(&acb
->aiocb
) == EINPROGRESS
);
442 /* remove the callback from the queue */
447 } else if (*pacb
== acb
) {
449 qemu_aio_release(acb
);
456 static void raw_close(BlockDriverState
*bs
)
458 BDRVRawState
*s
= bs
->opaque
;
465 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
467 BDRVRawState
*s
= bs
->opaque
;
468 if (s
->type
!= FTYPE_FILE
)
470 if (ftruncate(s
->fd
, offset
) < 0)
475 static int64_t raw_getlength(BlockDriverState
*bs
)
477 BDRVRawState
*s
= bs
->opaque
;
484 struct dk_minfo minfo
;
494 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
495 #ifdef DIOCGMEDIASIZE
496 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
499 size
= LONG_LONG_MAX
;
501 size
= lseek(fd
, 0LL, SEEK_END
);
507 * use the DKIOCGMEDIAINFO ioctl to read the size.
509 rv
= ioctl ( fd
, DKIOCGMEDIAINFO
, &minfo
);
511 size
= minfo
.dki_lbsize
* minfo
.dki_capacity
;
512 } else /* there are reports that lseek on some devices
513 fails, but irc discussion said that contingency
514 on contingency was overkill */
517 size
= lseek(fd
, 0, SEEK_END
);
522 static int raw_create(const char *filename
, int64_t total_size
,
523 const char *backing_file
, int flags
)
527 if (flags
|| backing_file
)
530 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
534 ftruncate(fd
, total_size
* 512);
539 static void raw_flush(BlockDriverState
*bs
)
541 BDRVRawState
*s
= bs
->opaque
;
545 BlockDriver bdrv_raw
= {
547 sizeof(BDRVRawState
),
548 NULL
, /* no probe for protocols */
556 .bdrv_aio_read
= raw_aio_read
,
557 .bdrv_aio_write
= raw_aio_write
,
558 .bdrv_aio_cancel
= raw_aio_cancel
,
559 .aiocb_size
= sizeof(RawAIOCB
),
560 .protocol_name
= "file",
561 .bdrv_pread
= raw_pread
,
562 .bdrv_pwrite
= raw_pwrite
,
563 .bdrv_truncate
= raw_truncate
,
564 .bdrv_getlength
= raw_getlength
,
567 /***********************************************/
571 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
572 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
574 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
576 kern_return_t kernResult
;
577 mach_port_t masterPort
;
578 CFMutableDictionaryRef classesToMatch
;
580 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
581 if ( KERN_SUCCESS
!= kernResult
) {
582 printf( "IOMasterPort returned %d\n", kernResult
);
585 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
586 if ( classesToMatch
== NULL
) {
587 printf( "IOServiceMatching returned a NULL dictionary.\n" );
589 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
591 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
592 if ( KERN_SUCCESS
!= kernResult
)
594 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
600 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
602 io_object_t nextMedia
;
603 kern_return_t kernResult
= KERN_FAILURE
;
605 nextMedia
= IOIteratorNext( mediaIterator
);
608 CFTypeRef bsdPathAsCFString
;
609 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
610 if ( bsdPathAsCFString
) {
611 size_t devPathLength
;
612 strcpy( bsdPath
, _PATH_DEV
);
613 strcat( bsdPath
, "r" );
614 devPathLength
= strlen( bsdPath
);
615 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
616 kernResult
= KERN_SUCCESS
;
618 CFRelease( bsdPathAsCFString
);
620 IOObjectRelease( nextMedia
);
628 static int hdev_open(BlockDriverState
*bs
, const char *filename
, int flags
)
630 BDRVRawState
*s
= bs
->opaque
;
631 int fd
, open_flags
, ret
;
634 if (strstart(filename
, "/dev/cdrom", NULL
)) {
635 kern_return_t kernResult
;
636 io_iterator_t mediaIterator
;
637 char bsdPath
[ MAXPATHLEN
];
640 kernResult
= FindEjectableCDMedia( &mediaIterator
);
641 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
643 if ( bsdPath
[ 0 ] != '\0' ) {
644 strcat(bsdPath
,"s0");
645 /* some CDs don't have a partition 0 */
646 fd
= open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
648 bsdPath
[strlen(bsdPath
)-1] = '1';
656 IOObjectRelease( mediaIterator
);
659 open_flags
= O_BINARY
;
660 if ((flags
& BDRV_O_ACCESS
) == O_RDWR
) {
661 open_flags
|= O_RDWR
;
663 open_flags
|= O_RDONLY
;
667 if (flags
& BDRV_O_DIRECT
)
668 open_flags
|= O_DIRECT
;
671 s
->type
= FTYPE_FILE
;
672 #if defined(__linux__)
673 if (strstart(filename
, "/dev/cd", NULL
)) {
674 /* open will not fail even if no CD is inserted */
675 open_flags
|= O_NONBLOCK
;
677 } else if (strstart(filename
, "/dev/fd", NULL
)) {
679 s
->fd_open_flags
= open_flags
;
680 /* open will not fail even if no floppy is inserted */
681 open_flags
|= O_NONBLOCK
;
684 fd
= open(filename
, open_flags
, 0644);
692 #if defined(__linux__)
693 /* close fd so that we can reopen it as needed */
694 if (s
->type
== FTYPE_FD
) {
697 s
->fd_media_changed
= 1;
703 #if defined(__linux__) && !defined(QEMU_IMG)
705 /* Note: we do not have a reliable method to detect if the floppy is
706 present. The current method is to try to open the floppy at every
707 I/O and to keep it opened during a few hundreds of ms. */
708 static int fd_open(BlockDriverState
*bs
)
710 BDRVRawState
*s
= bs
->opaque
;
711 int last_media_present
;
713 if (s
->type
!= FTYPE_FD
)
715 last_media_present
= (s
->fd
>= 0);
717 (qemu_get_clock(rt_clock
) - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
721 printf("Floppy closed\n");
725 if (s
->fd_got_error
&&
726 (qemu_get_clock(rt_clock
) - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
728 printf("No floppy (open delayed)\n");
732 s
->fd
= open(bs
->filename
, s
->fd_open_flags
);
734 s
->fd_error_time
= qemu_get_clock(rt_clock
);
736 if (last_media_present
)
737 s
->fd_media_changed
= 1;
739 printf("No floppy\n");
744 printf("Floppy opened\n");
747 if (!last_media_present
)
748 s
->fd_media_changed
= 1;
749 s
->fd_open_time
= qemu_get_clock(rt_clock
);
754 static int fd_open(BlockDriverState
*bs
)
760 #if defined(__linux__)
762 static int raw_is_inserted(BlockDriverState
*bs
)
764 BDRVRawState
*s
= bs
->opaque
;
769 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
770 if (ret
== CDS_DISC_OK
)
783 /* currently only used by fdc.c, but a CD version would be good too */
784 static int raw_media_changed(BlockDriverState
*bs
)
786 BDRVRawState
*s
= bs
->opaque
;
792 /* XXX: we do not have a true media changed indication. It
793 does not work if the floppy is changed without trying
796 ret
= s
->fd_media_changed
;
797 s
->fd_media_changed
= 0;
799 printf("Floppy changed=%d\n", ret
);
808 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
810 BDRVRawState
*s
= bs
->opaque
;
815 if (ioctl (s
->fd
, CDROMEJECT
, NULL
) < 0)
816 perror("CDROMEJECT");
818 if (ioctl (s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
819 perror("CDROMEJECT");
829 fd
= open(bs
->filename
, s
->fd_open_flags
| O_NONBLOCK
);
831 if (ioctl(fd
, FDEJECT
, 0) < 0)
843 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
845 BDRVRawState
*s
= bs
->opaque
;
849 if (ioctl (s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
850 /* Note: an error can happen if the distribution automatically
852 // perror("CDROM_LOCKDOOR");
863 static int raw_is_inserted(BlockDriverState
*bs
)
868 static int raw_media_changed(BlockDriverState
*bs
)
873 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
878 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
885 BlockDriver bdrv_host_device
= {
887 sizeof(BDRVRawState
),
888 NULL
, /* no probe for protocols */
896 .bdrv_aio_read
= raw_aio_read
,
897 .bdrv_aio_write
= raw_aio_write
,
898 .bdrv_aio_cancel
= raw_aio_cancel
,
899 .aiocb_size
= sizeof(RawAIOCB
),
900 .bdrv_pread
= raw_pread
,
901 .bdrv_pwrite
= raw_pwrite
,
902 .bdrv_getlength
= raw_getlength
,
904 /* removable device support */
905 .bdrv_is_inserted
= raw_is_inserted
,
906 .bdrv_media_changed
= raw_media_changed
,
907 .bdrv_eject
= raw_eject
,
908 .bdrv_set_locked
= raw_set_locked
,