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"
27 #include "qemu-timer.h"
30 #include "block_int.h"
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
47 #define _POSIX_PTHREAD_SEMANTICS 1
52 #include <sys/ioctl.h>
53 #include <linux/cdrom.h>
60 //#define DEBUG_FLOPPY
63 #if defined(DEBUG_BLOCK) && !defined(QEMU_IMG)
64 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
65 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
67 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
74 /* if the FD is not accessed during that time (in ms), we try to
75 reopen it to see if the disk has been changed */
76 #define FD_OPEN_TIMEOUT 1000
78 typedef struct BDRVRawState
{
81 unsigned int lseek_err_cnt
;
82 #if defined(__linux__)
83 /* linux floppy specific */
86 int64_t fd_error_time
;
92 static int fd_open(BlockDriverState
*bs
);
94 static int raw_open(BlockDriverState
*bs
, const char *filename
, int flags
)
96 BDRVRawState
*s
= bs
->opaque
;
97 int fd
, open_flags
, ret
;
101 open_flags
= O_BINARY
;
102 if ((flags
& BDRV_O_ACCESS
) == O_RDWR
) {
103 open_flags
|= O_RDWR
;
105 open_flags
|= O_RDONLY
;
108 if (flags
& BDRV_O_CREAT
)
109 open_flags
|= O_CREAT
| O_TRUNC
;
111 if (flags
& BDRV_O_DIRECT
)
112 open_flags
|= O_DIRECT
;
115 s
->type
= FTYPE_FILE
;
117 fd
= open(filename
, open_flags
, 0644);
128 /* XXX: use host sector size if necessary with:
129 #ifdef DIOCGSECTORSIZE
131 unsigned int sectorsize = 512;
132 if (!ioctl(fd, DIOCGSECTORSIZE, §orsize) &&
133 sectorsize > bufsize)
134 bufsize = sectorsize;
138 u_int32_t blockSize = 512;
139 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
145 static int raw_pread(BlockDriverState
*bs
, int64_t offset
,
146 uint8_t *buf
, int count
)
148 BDRVRawState
*s
= bs
->opaque
;
155 if (offset
>= 0 && lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
156 ++(s
->lseek_err_cnt
);
157 if(s
->lseek_err_cnt
<= 10) {
158 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
159 "] lseek failed : %d = %s\n",
160 s
->fd
, bs
->filename
, offset
, buf
, count
,
161 bs
->total_sectors
, errno
, strerror(errno
));
167 ret
= read(s
->fd
, buf
, count
);
169 goto label__raw_read__success
;
171 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
172 "] read failed %d : %d = %s\n",
173 s
->fd
, bs
->filename
, offset
, buf
, count
,
174 bs
->total_sectors
, ret
, errno
, strerror(errno
));
176 /* Try harder for CDrom. */
177 if (bs
->type
== BDRV_TYPE_CDROM
) {
178 lseek(s
->fd
, offset
, SEEK_SET
);
179 ret
= read(s
->fd
, buf
, count
);
181 goto label__raw_read__success
;
182 lseek(s
->fd
, offset
, SEEK_SET
);
183 ret
= read(s
->fd
, buf
, count
);
185 goto label__raw_read__success
;
187 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64
", %p, %d) [%" PRId64
188 "] retry read failed %d : %d = %s\n",
189 s
->fd
, bs
->filename
, offset
, buf
, count
,
190 bs
->total_sectors
, ret
, errno
, strerror(errno
));
193 label__raw_read__success
:
198 static int raw_pwrite(BlockDriverState
*bs
, int64_t offset
,
199 const uint8_t *buf
, int count
)
201 BDRVRawState
*s
= bs
->opaque
;
208 if (offset
>= 0 && lseek(s
->fd
, offset
, SEEK_SET
) == (off_t
)-1) {
209 ++(s
->lseek_err_cnt
);
210 if(s
->lseek_err_cnt
) {
211 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%"
212 PRId64
"] lseek failed : %d = %s\n",
213 s
->fd
, bs
->filename
, offset
, buf
, count
,
214 bs
->total_sectors
, errno
, strerror(errno
));
218 s
->lseek_err_cnt
= 0;
220 ret
= write(s
->fd
, buf
, count
);
222 goto label__raw_write__success
;
224 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64
", %p, %d) [%" PRId64
225 "] write failed %d : %d = %s\n",
226 s
->fd
, bs
->filename
, offset
, buf
, count
,
227 bs
->total_sectors
, ret
, errno
, strerror(errno
));
229 label__raw_write__success
:
234 /***********************************************************/
235 /* Unix AIO using POSIX AIO */
237 typedef struct RawAIOCB
{
238 BlockDriverAIOCB common
;
240 struct RawAIOCB
*next
;
243 static int aio_sig_num
= SIGUSR2
;
244 static RawAIOCB
*first_aio
; /* AIO issued */
245 static int aio_initialized
= 0;
247 static void aio_signal_handler(int signum
)
250 CPUState
*env
= cpu_single_env
;
252 /* stop the currently executing cpu because a timer occured */
253 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
255 if (env
->kqemu_enabled
) {
256 kqemu_cpu_interrupt(env
);
263 void qemu_aio_init(void)
265 struct sigaction act
;
269 sigfillset(&act
.sa_mask
);
270 act
.sa_flags
= 0; /* do not restart syscalls to interrupt select() */
271 act
.sa_handler
= aio_signal_handler
;
272 sigaction(aio_sig_num
, &act
, NULL
);
274 #if defined(__GLIBC__) && defined(__linux__)
276 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
277 seems to fix the problem. */
279 memset(&ai
, 0, sizeof(ai
));
282 ai
.aio_idle_time
= 365 * 100000;
288 void qemu_aio_poll(void)
290 RawAIOCB
*acb
, **pacb
;
299 ret
= aio_error(&acb
->aiocb
);
300 if (ret
== ECANCELED
) {
301 /* remove the request */
303 qemu_aio_release(acb
);
304 } else if (ret
!= EINPROGRESS
) {
307 ret
= aio_return(&acb
->aiocb
);
308 if (ret
== acb
->aiocb
.aio_nbytes
)
315 /* remove the request */
317 /* call the callback */
318 acb
->common
.cb(acb
->common
.opaque
, ret
);
319 qemu_aio_release(acb
);
329 /* Wait for all IO requests to complete. */
330 void qemu_aio_flush(void)
332 qemu_aio_wait_start();
340 /* wait until at least one AIO was handled */
341 static sigset_t wait_oset
;
343 void qemu_aio_wait_start(void)
347 if (!aio_initialized
)
351 qemu_kvm_aio_wait_start();
356 sigaddset(&set
, aio_sig_num
);
357 sigprocmask(SIG_BLOCK
, &set
, &wait_oset
);
360 void qemu_aio_wait(void)
375 sigaddset(&set
, aio_sig_num
);
376 sigwait(&set
, &nb_sigs
);
380 void qemu_aio_wait_end(void)
384 qemu_kvm_aio_wait_end();
388 sigprocmask(SIG_SETMASK
, &wait_oset
, NULL
);
391 static RawAIOCB
*raw_aio_setup(BlockDriverState
*bs
,
392 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
393 BlockDriverCompletionFunc
*cb
, void *opaque
)
395 BDRVRawState
*s
= bs
->opaque
;
401 acb
= qemu_aio_get(bs
, cb
, opaque
);
404 acb
->aiocb
.aio_fildes
= s
->fd
;
405 acb
->aiocb
.aio_sigevent
.sigev_signo
= aio_sig_num
;
406 acb
->aiocb
.aio_sigevent
.sigev_notify
= SIGEV_SIGNAL
;
407 acb
->aiocb
.aio_buf
= buf
;
409 acb
->aiocb
.aio_nbytes
= -nb_sectors
;
411 acb
->aiocb
.aio_nbytes
= nb_sectors
* 512;
412 acb
->aiocb
.aio_offset
= sector_num
* 512;
413 acb
->next
= first_aio
;
418 static BlockDriverAIOCB
*raw_aio_read(BlockDriverState
*bs
,
419 int64_t sector_num
, uint8_t *buf
, int nb_sectors
,
420 BlockDriverCompletionFunc
*cb
, void *opaque
)
424 acb
= raw_aio_setup(bs
, sector_num
, buf
, nb_sectors
, cb
, opaque
);
427 if (aio_read(&acb
->aiocb
) < 0) {
428 qemu_aio_release(acb
);
434 static BlockDriverAIOCB
*raw_aio_write(BlockDriverState
*bs
,
435 int64_t sector_num
, const uint8_t *buf
, int nb_sectors
,
436 BlockDriverCompletionFunc
*cb
, void *opaque
)
440 acb
= raw_aio_setup(bs
, sector_num
, (uint8_t*)buf
, nb_sectors
, cb
, opaque
);
443 if (aio_write(&acb
->aiocb
) < 0) {
444 qemu_aio_release(acb
);
450 static void raw_aio_cancel(BlockDriverAIOCB
*blockacb
)
453 RawAIOCB
*acb
= (RawAIOCB
*)blockacb
;
456 ret
= aio_cancel(acb
->aiocb
.aio_fildes
, &acb
->aiocb
);
457 if (ret
== AIO_NOTCANCELED
) {
458 /* fail safe: if the aio could not be canceled, we wait for
460 while (aio_error(&acb
->aiocb
) == EINPROGRESS
);
463 /* remove the callback from the queue */
468 } else if (*pacb
== acb
) {
470 qemu_aio_release(acb
);
477 static void raw_close(BlockDriverState
*bs
)
479 BDRVRawState
*s
= bs
->opaque
;
486 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
488 BDRVRawState
*s
= bs
->opaque
;
489 if (s
->type
!= FTYPE_FILE
)
491 if (ftruncate(s
->fd
, offset
) < 0)
496 static int64_t raw_getlength(BlockDriverState
*bs
)
498 BDRVRawState
*s
= bs
->opaque
;
505 struct dk_minfo minfo
;
515 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
516 #ifdef DIOCGMEDIASIZE
517 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
520 size
= LONG_LONG_MAX
;
522 size
= lseek(fd
, 0LL, SEEK_END
);
528 * use the DKIOCGMEDIAINFO ioctl to read the size.
530 rv
= ioctl ( fd
, DKIOCGMEDIAINFO
, &minfo
);
532 size
= minfo
.dki_lbsize
* minfo
.dki_capacity
;
533 } else /* there are reports that lseek on some devices
534 fails, but irc discussion said that contingency
535 on contingency was overkill */
538 size
= lseek(fd
, 0, SEEK_END
);
543 static int raw_create(const char *filename
, int64_t total_size
,
544 const char *backing_file
, int flags
)
548 if (flags
|| backing_file
)
551 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
555 ftruncate(fd
, total_size
* 512);
560 static void raw_flush(BlockDriverState
*bs
)
562 BDRVRawState
*s
= bs
->opaque
;
566 BlockDriver bdrv_raw
= {
568 sizeof(BDRVRawState
),
569 NULL
, /* no probe for protocols */
577 .bdrv_aio_read
= raw_aio_read
,
578 .bdrv_aio_write
= raw_aio_write
,
579 .bdrv_aio_cancel
= raw_aio_cancel
,
580 .aiocb_size
= sizeof(RawAIOCB
),
581 .protocol_name
= "file",
582 .bdrv_pread
= raw_pread
,
583 .bdrv_pwrite
= raw_pwrite
,
584 .bdrv_truncate
= raw_truncate
,
585 .bdrv_getlength
= raw_getlength
,
588 /***********************************************/
592 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
593 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
595 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
597 kern_return_t kernResult
;
598 mach_port_t masterPort
;
599 CFMutableDictionaryRef classesToMatch
;
601 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
602 if ( KERN_SUCCESS
!= kernResult
) {
603 printf( "IOMasterPort returned %d\n", kernResult
);
606 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
607 if ( classesToMatch
== NULL
) {
608 printf( "IOServiceMatching returned a NULL dictionary.\n" );
610 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
612 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
613 if ( KERN_SUCCESS
!= kernResult
)
615 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
621 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
623 io_object_t nextMedia
;
624 kern_return_t kernResult
= KERN_FAILURE
;
626 nextMedia
= IOIteratorNext( mediaIterator
);
629 CFTypeRef bsdPathAsCFString
;
630 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
631 if ( bsdPathAsCFString
) {
632 size_t devPathLength
;
633 strcpy( bsdPath
, _PATH_DEV
);
634 strcat( bsdPath
, "r" );
635 devPathLength
= strlen( bsdPath
);
636 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
637 kernResult
= KERN_SUCCESS
;
639 CFRelease( bsdPathAsCFString
);
641 IOObjectRelease( nextMedia
);
649 static int hdev_open(BlockDriverState
*bs
, const char *filename
, int flags
)
651 BDRVRawState
*s
= bs
->opaque
;
652 int fd
, open_flags
, ret
;
655 if (strstart(filename
, "/dev/cdrom", NULL
)) {
656 kern_return_t kernResult
;
657 io_iterator_t mediaIterator
;
658 char bsdPath
[ MAXPATHLEN
];
661 kernResult
= FindEjectableCDMedia( &mediaIterator
);
662 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
664 if ( bsdPath
[ 0 ] != '\0' ) {
665 strcat(bsdPath
,"s0");
666 /* some CDs don't have a partition 0 */
667 fd
= open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
669 bsdPath
[strlen(bsdPath
)-1] = '1';
677 IOObjectRelease( mediaIterator
);
680 open_flags
= O_BINARY
;
681 if ((flags
& BDRV_O_ACCESS
) == O_RDWR
) {
682 open_flags
|= O_RDWR
;
684 open_flags
|= O_RDONLY
;
688 if (flags
& BDRV_O_DIRECT
)
689 open_flags
|= O_DIRECT
;
692 s
->type
= FTYPE_FILE
;
693 #if defined(__linux__)
694 if (strstart(filename
, "/dev/cd", NULL
)) {
695 /* open will not fail even if no CD is inserted */
696 open_flags
|= O_NONBLOCK
;
698 } else if (strstart(filename
, "/dev/fd", NULL
)) {
700 s
->fd_open_flags
= open_flags
;
701 /* open will not fail even if no floppy is inserted */
702 open_flags
|= O_NONBLOCK
;
703 } else if (strstart(filename
, "/dev/sg", NULL
)) {
707 fd
= open(filename
, open_flags
, 0644);
715 #if defined(__linux__)
716 /* close fd so that we can reopen it as needed */
717 if (s
->type
== FTYPE_FD
) {
720 s
->fd_media_changed
= 1;
726 #if defined(__linux__) && !defined(QEMU_IMG)
728 /* Note: we do not have a reliable method to detect if the floppy is
729 present. The current method is to try to open the floppy at every
730 I/O and to keep it opened during a few hundreds of ms. */
731 static int fd_open(BlockDriverState
*bs
)
733 BDRVRawState
*s
= bs
->opaque
;
734 int last_media_present
;
736 if (s
->type
!= FTYPE_FD
)
738 last_media_present
= (s
->fd
>= 0);
740 (qemu_get_clock(rt_clock
) - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
744 printf("Floppy closed\n");
748 if (s
->fd_got_error
&&
749 (qemu_get_clock(rt_clock
) - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
751 printf("No floppy (open delayed)\n");
755 s
->fd
= open(bs
->filename
, s
->fd_open_flags
);
757 s
->fd_error_time
= qemu_get_clock(rt_clock
);
759 if (last_media_present
)
760 s
->fd_media_changed
= 1;
762 printf("No floppy\n");
767 printf("Floppy opened\n");
770 if (!last_media_present
)
771 s
->fd_media_changed
= 1;
772 s
->fd_open_time
= qemu_get_clock(rt_clock
);
777 static int fd_open(BlockDriverState
*bs
)
783 #if defined(__linux__)
785 static int raw_is_inserted(BlockDriverState
*bs
)
787 BDRVRawState
*s
= bs
->opaque
;
792 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
793 if (ret
== CDS_DISC_OK
)
806 /* currently only used by fdc.c, but a CD version would be good too */
807 static int raw_media_changed(BlockDriverState
*bs
)
809 BDRVRawState
*s
= bs
->opaque
;
815 /* XXX: we do not have a true media changed indication. It
816 does not work if the floppy is changed without trying
819 ret
= s
->fd_media_changed
;
820 s
->fd_media_changed
= 0;
822 printf("Floppy changed=%d\n", ret
);
831 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
833 BDRVRawState
*s
= bs
->opaque
;
838 if (ioctl (s
->fd
, CDROMEJECT
, NULL
) < 0)
839 perror("CDROMEJECT");
841 if (ioctl (s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
842 perror("CDROMEJECT");
852 fd
= open(bs
->filename
, s
->fd_open_flags
| O_NONBLOCK
);
854 if (ioctl(fd
, FDEJECT
, 0) < 0)
866 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
868 BDRVRawState
*s
= bs
->opaque
;
872 if (ioctl (s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
873 /* Note: an error can happen if the distribution automatically
875 // perror("CDROM_LOCKDOOR");
884 static int raw_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
886 BDRVRawState
*s
= bs
->opaque
;
888 return ioctl(s
->fd
, req
, buf
);
892 static int raw_is_inserted(BlockDriverState
*bs
)
897 static int raw_media_changed(BlockDriverState
*bs
)
902 static int raw_eject(BlockDriverState
*bs
, int eject_flag
)
907 static int raw_set_locked(BlockDriverState
*bs
, int locked
)
912 static int raw_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
918 BlockDriver bdrv_host_device
= {
920 sizeof(BDRVRawState
),
921 NULL
, /* no probe for protocols */
929 .bdrv_aio_read
= raw_aio_read
,
930 .bdrv_aio_write
= raw_aio_write
,
931 .bdrv_aio_cancel
= raw_aio_cancel
,
932 .aiocb_size
= sizeof(RawAIOCB
),
933 .bdrv_pread
= raw_pread
,
934 .bdrv_pwrite
= raw_pwrite
,
935 .bdrv_getlength
= raw_getlength
,
937 /* removable device support */
938 .bdrv_is_inserted
= raw_is_inserted
,
939 .bdrv_media_changed
= raw_media_changed
,
940 .bdrv_eject
= raw_eject
,
941 .bdrv_set_locked
= raw_set_locked
,
942 /* generic scsi device */
943 .bdrv_ioctl
= raw_ioctl
,