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 {
81 unsigned int lseek_err_cnt;
82 #if defined(__linux__)
83 /* 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->open_flags = open_flags;
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) {
146 * offset and count are in bytes, but must be multiples of 512 for files
147 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
149 * This function may be called without alignment if the caller ensures
150 * that O_DIRECT is not in effect.
152 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
153 uint8_t *buf, int count)
155 BDRVRawState *s = bs->opaque;
162 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
163 ++(s->lseek_err_cnt);
164 if(s->lseek_err_cnt <= 10) {
165 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
166 "] lseek failed : %d = %s\n",
167 s->fd, bs->filename, offset, buf, count,
168 bs->total_sectors, errno, strerror(errno));
174 ret = read(s->fd, buf, count);
176 goto label__raw_read__success;
178 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
179 "] read failed %d : %d = %s\n",
180 s->fd, bs->filename, offset, buf, count,
181 bs->total_sectors, ret, errno, strerror(errno));
183 /* Try harder for CDrom. */
184 if (bs->type == BDRV_TYPE_CDROM) {
185 lseek(s->fd, offset, SEEK_SET);
186 ret = read(s->fd, buf, count);
188 goto label__raw_read__success;
189 lseek(s->fd, offset, SEEK_SET);
190 ret = read(s->fd, buf, count);
192 goto label__raw_read__success;
194 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
195 "] retry read failed %d : %d = %s\n",
196 s->fd, bs->filename, offset, buf, count,
197 bs->total_sectors, ret, errno, strerror(errno));
200 label__raw_read__success:
206 * offset and count are in bytes, but must be multiples of 512 for files
207 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
209 * This function may be called without alignment if the caller ensures
210 * that O_DIRECT is not in effect.
212 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
213 const uint8_t *buf, int count)
215 BDRVRawState *s = bs->opaque;
222 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
223 ++(s->lseek_err_cnt);
224 if(s->lseek_err_cnt) {
225 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
226 PRId64 "] lseek failed : %d = %s\n",
227 s->fd, bs->filename, offset, buf, count,
228 bs->total_sectors, errno, strerror(errno));
232 s->lseek_err_cnt = 0;
234 ret = write(s->fd, buf, count);
236 goto label__raw_write__success;
238 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
239 "] write failed %d : %d = %s\n",
240 s->fd, bs->filename, offset, buf, count,
241 bs->total_sectors, ret, errno, strerror(errno));
243 label__raw_write__success:
251 * offset and count are in bytes and possibly not aligned. For files opened
252 * with O_DIRECT, necessary alignments are ensured before calling
253 * raw_pread_aligned to do the actual read.
255 static int raw_pread(BlockDriverState *bs, int64_t offset,
256 uint8_t *buf, int count)
258 BDRVRawState *s = bs->opaque;
260 if (unlikely((s->open_flags & O_DIRECT) &&
261 (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
265 // Temporarily disable O_DIRECT for unaligned access
266 fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
267 ret = raw_pread_aligned(bs, offset, buf, count);
268 fcntl(s->fd, F_SETFL, s->open_flags);
273 return raw_pread_aligned(bs, offset, buf, count);
278 * offset and count are in bytes and possibly not aligned. For files opened
279 * with O_DIRECT, necessary alignments are ensured before calling
280 * raw_pwrite_aligned to do the actual write.
282 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
283 const uint8_t *buf, int count)
285 BDRVRawState *s = bs->opaque;
287 if (unlikely((s->open_flags & O_DIRECT) &&
288 (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
292 // Temporarily disable O_DIRECT for unaligned access
293 fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
294 ret = raw_pwrite_aligned(bs, offset, buf, count);
295 fcntl(s->fd, F_SETFL, s->open_flags);
299 return raw_pwrite_aligned(bs, offset, buf, count);
304 #define raw_pread raw_pread_aligned
305 #define raw_pwrite raw_pwrite_aligned
309 /***********************************************************/
310 /* Unix AIO using POSIX AIO */
312 typedef struct RawAIOCB {
313 BlockDriverAIOCB common;
315 struct RawAIOCB *next;
318 static int aio_sig_num = SIGUSR2;
319 static RawAIOCB *first_aio; /* AIO issued */
320 static int aio_initialized = 0;
322 static void aio_signal_handler(int signum)
325 CPUState *env = cpu_single_env;
327 /* stop the currently executing cpu because a timer occured */
328 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
330 if (env->kqemu_enabled) {
331 kqemu_cpu_interrupt(env);
338 void qemu_aio_init(void)
340 struct sigaction act;
344 sigfillset(&act.sa_mask);
345 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
346 act.sa_handler = aio_signal_handler;
347 sigaction(aio_sig_num, &act, NULL);
349 #if defined(__GLIBC__) && defined(__linux__)
351 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
352 seems to fix the problem. */
354 memset(&ai, 0, sizeof(ai));
357 ai.aio_idle_time = 365 * 100000;
363 void qemu_aio_poll(void)
365 RawAIOCB *acb, **pacb;
374 ret = aio_error(&acb->aiocb);
375 if (ret == ECANCELED) {
376 /* remove the request */
378 qemu_aio_release(acb);
379 } else if (ret != EINPROGRESS) {
382 ret = aio_return(&acb->aiocb);
383 if (ret == acb->aiocb.aio_nbytes)
390 /* remove the request */
392 /* call the callback */
393 acb->common.cb(acb->common.opaque, ret);
394 qemu_aio_release(acb);
404 /* Wait for all IO requests to complete. */
405 void qemu_aio_flush(void)
407 qemu_aio_wait_start();
415 /* wait until at least one AIO was handled */
416 static sigset_t wait_oset;
418 void qemu_aio_wait_start(void)
422 if (!aio_initialized)
425 sigaddset(&set, aio_sig_num);
426 sigprocmask(SIG_BLOCK, &set, &wait_oset);
429 void qemu_aio_wait(void)
439 sigaddset(&set, aio_sig_num);
440 sigwait(&set, &nb_sigs);
444 void qemu_aio_wait_end(void)
446 sigprocmask(SIG_SETMASK, &wait_oset, NULL);
449 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
450 int64_t sector_num, uint8_t *buf, int nb_sectors,
451 BlockDriverCompletionFunc *cb, void *opaque)
453 BDRVRawState *s = bs->opaque;
459 acb = qemu_aio_get(bs, cb, opaque);
462 acb->aiocb.aio_fildes = s->fd;
463 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
464 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
465 acb->aiocb.aio_buf = buf;
467 acb->aiocb.aio_nbytes = -nb_sectors;
469 acb->aiocb.aio_nbytes = nb_sectors * 512;
470 acb->aiocb.aio_offset = sector_num * 512;
471 acb->next = first_aio;
476 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
477 int64_t sector_num, uint8_t *buf, int nb_sectors,
478 BlockDriverCompletionFunc *cb, void *opaque)
481 BDRVRawState *s = bs->opaque;
484 * If O_DIRECT is used and the buffer is not aligned fall back
487 if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
490 acb = qemu_aio_get(bs, cb, opaque);
491 ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
492 acb->common.cb(acb->common.opaque, ret);
493 qemu_aio_release(acb);
497 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
501 if (aio_read(&acb->aiocb) < 0) {
502 qemu_aio_release(acb);
508 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
509 int64_t sector_num, const uint8_t *buf, int nb_sectors,
510 BlockDriverCompletionFunc *cb, void *opaque)
513 BDRVRawState *s = bs->opaque;
516 * If O_DIRECT is used and the buffer is not aligned fall back
519 if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
522 acb = qemu_aio_get(bs, cb, opaque);
523 ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
524 acb->common.cb(acb->common.opaque, ret);
525 qemu_aio_release(acb);
529 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
532 if (aio_write(&acb->aiocb) < 0) {
533 qemu_aio_release(acb);
539 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
542 RawAIOCB *acb = (RawAIOCB *)blockacb;
545 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
546 if (ret == AIO_NOTCANCELED) {
547 /* fail safe: if the aio could not be canceled, we wait for
549 while (aio_error(&acb->aiocb) == EINPROGRESS);
552 /* remove the callback from the queue */
557 } else if (*pacb == acb) {
559 qemu_aio_release(acb);
566 static void raw_close(BlockDriverState *bs)
568 BDRVRawState *s = bs->opaque;
575 static int raw_truncate(BlockDriverState *bs, int64_t offset)
577 BDRVRawState *s = bs->opaque;
578 if (s->type != FTYPE_FILE)
580 if (ftruncate(s->fd, offset) < 0)
585 static int64_t raw_getlength(BlockDriverState *bs)
587 BDRVRawState *s = bs->opaque;
594 struct dk_minfo minfo;
604 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
605 #ifdef DIOCGMEDIASIZE
606 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
609 size = LONG_LONG_MAX;
611 size = lseek(fd, 0LL, SEEK_END);
617 * use the DKIOCGMEDIAINFO ioctl to read the size.
619 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
621 size = minfo.dki_lbsize * minfo.dki_capacity;
622 } else /* there are reports that lseek on some devices
623 fails, but irc discussion said that contingency
624 on contingency was overkill */
627 size = lseek(fd, 0, SEEK_END);
632 static int raw_create(const char *filename, int64_t total_size,
633 const char *backing_file, int flags)
637 if (flags || backing_file)
640 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
644 ftruncate(fd, total_size * 512);
649 static void raw_flush(BlockDriverState *bs)
651 BDRVRawState *s = bs->opaque;
655 BlockDriver bdrv_raw = {
657 sizeof(BDRVRawState),
658 NULL, /* no probe for protocols */
666 .bdrv_aio_read = raw_aio_read,
667 .bdrv_aio_write = raw_aio_write,
668 .bdrv_aio_cancel = raw_aio_cancel,
669 .aiocb_size = sizeof(RawAIOCB),
670 .protocol_name = "file",
671 .bdrv_pread = raw_pread,
672 .bdrv_pwrite = raw_pwrite,
673 .bdrv_truncate = raw_truncate,
674 .bdrv_getlength = raw_getlength,
677 /***********************************************/
681 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
682 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
684 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
686 kern_return_t kernResult;
687 mach_port_t masterPort;
688 CFMutableDictionaryRef classesToMatch;
690 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
691 if ( KERN_SUCCESS != kernResult ) {
692 printf( "IOMasterPort returned %d\n", kernResult );
695 classesToMatch = IOServiceMatching( kIOCDMediaClass );
696 if ( classesToMatch == NULL ) {
697 printf( "IOServiceMatching returned a NULL dictionary.\n" );
699 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
701 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
702 if ( KERN_SUCCESS != kernResult )
704 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
710 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
712 io_object_t nextMedia;
713 kern_return_t kernResult = KERN_FAILURE;
715 nextMedia = IOIteratorNext( mediaIterator );
718 CFTypeRef bsdPathAsCFString;
719 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
720 if ( bsdPathAsCFString ) {
721 size_t devPathLength;
722 strcpy( bsdPath, _PATH_DEV );
723 strcat( bsdPath, "r" );
724 devPathLength = strlen( bsdPath );
725 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
726 kernResult = KERN_SUCCESS;
728 CFRelease( bsdPathAsCFString );
730 IOObjectRelease( nextMedia );
738 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
740 BDRVRawState *s = bs->opaque;
741 int fd, open_flags, ret;
744 if (strstart(filename, "/dev/cdrom", NULL)) {
745 kern_return_t kernResult;
746 io_iterator_t mediaIterator;
747 char bsdPath[ MAXPATHLEN ];
750 kernResult = FindEjectableCDMedia( &mediaIterator );
751 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
753 if ( bsdPath[ 0 ] != '\0' ) {
754 strcat(bsdPath,"s0");
755 /* some CDs don't have a partition 0 */
756 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
758 bsdPath[strlen(bsdPath)-1] = '1';
766 IOObjectRelease( mediaIterator );
769 open_flags = O_BINARY;
770 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
771 open_flags |= O_RDWR;
773 open_flags |= O_RDONLY;
777 if (flags & BDRV_O_DIRECT)
778 open_flags |= O_DIRECT;
781 s->type = FTYPE_FILE;
782 #if defined(__linux__)
783 if (strstart(filename, "/dev/cd", NULL)) {
784 /* open will not fail even if no CD is inserted */
785 open_flags |= O_NONBLOCK;
787 } else if (strstart(filename, "/dev/fd", NULL)) {
789 s->open_flags = open_flags;
790 /* open will not fail even if no floppy is inserted */
791 open_flags |= O_NONBLOCK;
792 } else if (strstart(filename, "/dev/sg", NULL)) {
796 fd = open(filename, open_flags, 0644);
804 #if defined(__linux__)
805 /* close fd so that we can reopen it as needed */
806 if (s->type == FTYPE_FD) {
809 s->fd_media_changed = 1;
815 #if defined(__linux__) && !defined(QEMU_IMG)
817 /* Note: we do not have a reliable method to detect if the floppy is
818 present. The current method is to try to open the floppy at every
819 I/O and to keep it opened during a few hundreds of ms. */
820 static int fd_open(BlockDriverState *bs)
822 BDRVRawState *s = bs->opaque;
823 int last_media_present;
825 if (s->type != FTYPE_FD)
827 last_media_present = (s->fd >= 0);
829 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
833 printf("Floppy closed\n");
837 if (s->fd_got_error &&
838 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
840 printf("No floppy (open delayed)\n");
844 s->fd = open(bs->filename, s->open_flags);
846 s->fd_error_time = qemu_get_clock(rt_clock);
848 if (last_media_present)
849 s->fd_media_changed = 1;
851 printf("No floppy\n");
856 printf("Floppy opened\n");
859 if (!last_media_present)
860 s->fd_media_changed = 1;
861 s->fd_open_time = qemu_get_clock(rt_clock);
866 static int fd_open(BlockDriverState *bs)
872 #if defined(__linux__)
874 static int raw_is_inserted(BlockDriverState *bs)
876 BDRVRawState *s = bs->opaque;
881 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
882 if (ret == CDS_DISC_OK)
895 /* currently only used by fdc.c, but a CD version would be good too */
896 static int raw_media_changed(BlockDriverState *bs)
898 BDRVRawState *s = bs->opaque;
904 /* XXX: we do not have a true media changed indication. It
905 does not work if the floppy is changed without trying
908 ret = s->fd_media_changed;
909 s->fd_media_changed = 0;
911 printf("Floppy changed=%d\n", ret);
920 static int raw_eject(BlockDriverState *bs, int eject_flag)
922 BDRVRawState *s = bs->opaque;
927 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
928 perror("CDROMEJECT");
930 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
931 perror("CDROMEJECT");
941 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
943 if (ioctl(fd, FDEJECT, 0) < 0)
955 static int raw_set_locked(BlockDriverState *bs, int locked)
957 BDRVRawState *s = bs->opaque;
961 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
962 /* Note: an error can happen if the distribution automatically
964 // perror("CDROM_LOCKDOOR");
973 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
975 BDRVRawState *s = bs->opaque;
977 return ioctl(s->fd, req, buf);
981 static int raw_is_inserted(BlockDriverState *bs)
986 static int raw_media_changed(BlockDriverState *bs)
991 static int raw_eject(BlockDriverState *bs, int eject_flag)
996 static int raw_set_locked(BlockDriverState *bs, int locked)
1001 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1007 BlockDriver bdrv_host_device = {
1009 sizeof(BDRVRawState),
1010 NULL, /* no probe for protocols */
1018 .bdrv_aio_read = raw_aio_read,
1019 .bdrv_aio_write = raw_aio_write,
1020 .bdrv_aio_cancel = raw_aio_cancel,
1021 .aiocb_size = sizeof(RawAIOCB),
1022 .bdrv_pread = raw_pread,
1023 .bdrv_pwrite = raw_pwrite,
1024 .bdrv_getlength = raw_getlength,
1026 /* removable device support */
1027 .bdrv_is_inserted = raw_is_inserted,
1028 .bdrv_media_changed = raw_media_changed,
1029 .bdrv_eject = raw_eject,
1030 .bdrv_set_locked = raw_set_locked,
1031 /* generic scsi device */
1032 .bdrv_ioctl = raw_ioctl,