Add EBUS bridge
[qemu/mini2440.git] / block-raw-posix.c
blob2fbb714d01ba278e92344810fc349d80271acd65
1 /*
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
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "qemu-char.h"
27 #include "block_int.h"
28 #include <assert.h>
29 #ifdef CONFIG_AIO
30 #include "posix-aio-compat.h"
31 #endif
33 #ifdef CONFIG_COCOA
34 #include <paths.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>
43 #endif
45 #ifdef __sun__
46 #define _POSIX_PTHREAD_SEMANTICS 1
47 #include <signal.h>
48 #include <sys/dkio.h>
49 #endif
50 #ifdef __linux__
51 #include <sys/ioctl.h>
52 #include <linux/cdrom.h>
53 #include <linux/fd.h>
54 #endif
55 #ifdef __FreeBSD__
56 #include <signal.h>
57 #include <sys/disk.h>
58 #endif
60 #ifdef __OpenBSD__
61 #include <sys/ioctl.h>
62 #include <sys/disklabel.h>
63 #include <sys/dkio.h>
64 #endif
66 //#define DEBUG_FLOPPY
68 //#define DEBUG_BLOCK
69 #if defined(DEBUG_BLOCK)
70 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
71 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
72 #else
73 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
74 #endif
76 /* OS X does not have O_DSYNC */
77 #ifndef O_DSYNC
78 #define O_DSYNC O_SYNC
79 #endif
81 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
82 #ifndef O_DIRECT
83 #define O_DIRECT O_DSYNC
84 #endif
86 #define FTYPE_FILE 0
87 #define FTYPE_CD 1
88 #define FTYPE_FD 2
90 #define ALIGNED_BUFFER_SIZE (32 * 512)
92 /* if the FD is not accessed during that time (in ms), we try to
93 reopen it to see if the disk has been changed */
94 #define FD_OPEN_TIMEOUT 1000
96 typedef struct BDRVRawState {
97 int fd;
98 int type;
99 unsigned int lseek_err_cnt;
100 #if defined(__linux__)
101 /* linux floppy specific */
102 int fd_open_flags;
103 int64_t fd_open_time;
104 int64_t fd_error_time;
105 int fd_got_error;
106 int fd_media_changed;
107 #endif
108 uint8_t* aligned_buf;
109 } BDRVRawState;
111 static int posix_aio_init(void);
113 static int fd_open(BlockDriverState *bs);
115 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
117 BDRVRawState *s = bs->opaque;
118 int fd, open_flags, ret;
120 posix_aio_init();
122 s->lseek_err_cnt = 0;
124 open_flags = O_BINARY;
125 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
126 open_flags |= O_RDWR;
127 } else {
128 open_flags |= O_RDONLY;
129 bs->read_only = 1;
131 if (flags & BDRV_O_CREAT)
132 open_flags |= O_CREAT | O_TRUNC;
134 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
135 * and O_DIRECT for no caching. */
136 if ((flags & BDRV_O_NOCACHE))
137 open_flags |= O_DIRECT;
138 else if (!(flags & BDRV_O_CACHE_WB))
139 open_flags |= O_DSYNC;
141 s->type = FTYPE_FILE;
143 fd = open(filename, open_flags, 0644);
144 if (fd < 0) {
145 ret = -errno;
146 if (ret == -EROFS)
147 ret = -EACCES;
148 return ret;
150 s->fd = fd;
151 s->aligned_buf = NULL;
152 if ((flags & BDRV_O_NOCACHE)) {
153 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
154 if (s->aligned_buf == NULL) {
155 ret = -errno;
156 close(fd);
157 return ret;
160 return 0;
163 /* XXX: use host sector size if necessary with:
164 #ifdef DIOCGSECTORSIZE
166 unsigned int sectorsize = 512;
167 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
168 sectorsize > bufsize)
169 bufsize = sectorsize;
171 #endif
172 #ifdef CONFIG_COCOA
173 u_int32_t blockSize = 512;
174 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
175 bufsize = blockSize;
177 #endif
181 * offset and count are in bytes, but must be multiples of 512 for files
182 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
184 * This function may be called without alignment if the caller ensures
185 * that O_DIRECT is not in effect.
187 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
188 uint8_t *buf, int count)
190 BDRVRawState *s = bs->opaque;
191 int ret;
193 ret = fd_open(bs);
194 if (ret < 0)
195 return ret;
197 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
198 ++(s->lseek_err_cnt);
199 if(s->lseek_err_cnt <= 10) {
200 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
201 "] lseek failed : %d = %s\n",
202 s->fd, bs->filename, offset, buf, count,
203 bs->total_sectors, errno, strerror(errno));
205 return -1;
207 s->lseek_err_cnt=0;
209 ret = read(s->fd, buf, count);
210 if (ret == count)
211 goto label__raw_read__success;
213 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
214 "] read failed %d : %d = %s\n",
215 s->fd, bs->filename, offset, buf, count,
216 bs->total_sectors, ret, errno, strerror(errno));
218 /* Try harder for CDrom. */
219 if (bs->type == BDRV_TYPE_CDROM) {
220 lseek(s->fd, offset, SEEK_SET);
221 ret = read(s->fd, buf, count);
222 if (ret == count)
223 goto label__raw_read__success;
224 lseek(s->fd, offset, SEEK_SET);
225 ret = read(s->fd, buf, count);
226 if (ret == count)
227 goto label__raw_read__success;
229 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
230 "] retry read failed %d : %d = %s\n",
231 s->fd, bs->filename, offset, buf, count,
232 bs->total_sectors, ret, errno, strerror(errno));
235 label__raw_read__success:
237 return ret;
241 * offset and count are in bytes, but must be multiples of 512 for files
242 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
244 * This function may be called without alignment if the caller ensures
245 * that O_DIRECT is not in effect.
247 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
248 const uint8_t *buf, int count)
250 BDRVRawState *s = bs->opaque;
251 int ret;
253 ret = fd_open(bs);
254 if (ret < 0)
255 return ret;
257 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
258 ++(s->lseek_err_cnt);
259 if(s->lseek_err_cnt) {
260 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
261 PRId64 "] lseek failed : %d = %s\n",
262 s->fd, bs->filename, offset, buf, count,
263 bs->total_sectors, errno, strerror(errno));
265 return -1;
267 s->lseek_err_cnt = 0;
269 ret = write(s->fd, buf, count);
270 if (ret == count)
271 goto label__raw_write__success;
273 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
274 "] write failed %d : %d = %s\n",
275 s->fd, bs->filename, offset, buf, count,
276 bs->total_sectors, ret, errno, strerror(errno));
278 label__raw_write__success:
280 return ret;
285 * offset and count are in bytes and possibly not aligned. For files opened
286 * with O_DIRECT, necessary alignments are ensured before calling
287 * raw_pread_aligned to do the actual read.
289 static int raw_pread(BlockDriverState *bs, int64_t offset,
290 uint8_t *buf, int count)
292 BDRVRawState *s = bs->opaque;
293 int size, ret, shift, sum;
295 sum = 0;
297 if (s->aligned_buf != NULL) {
299 if (offset & 0x1ff) {
300 /* align offset on a 512 bytes boundary */
302 shift = offset & 0x1ff;
303 size = (shift + count + 0x1ff) & ~0x1ff;
304 if (size > ALIGNED_BUFFER_SIZE)
305 size = ALIGNED_BUFFER_SIZE;
306 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
307 if (ret < 0)
308 return ret;
310 size = 512 - shift;
311 if (size > count)
312 size = count;
313 memcpy(buf, s->aligned_buf + shift, size);
315 buf += size;
316 offset += size;
317 count -= size;
318 sum += size;
320 if (count == 0)
321 return sum;
323 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
325 /* read on aligned buffer */
327 while (count) {
329 size = (count + 0x1ff) & ~0x1ff;
330 if (size > ALIGNED_BUFFER_SIZE)
331 size = ALIGNED_BUFFER_SIZE;
333 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
334 if (ret < 0)
335 return ret;
337 size = ret;
338 if (size > count)
339 size = count;
341 memcpy(buf, s->aligned_buf, size);
343 buf += size;
344 offset += size;
345 count -= size;
346 sum += size;
349 return sum;
353 return raw_pread_aligned(bs, offset, buf, count) + sum;
357 * offset and count are in bytes and possibly not aligned. For files opened
358 * with O_DIRECT, necessary alignments are ensured before calling
359 * raw_pwrite_aligned to do the actual write.
361 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
362 const uint8_t *buf, int count)
364 BDRVRawState *s = bs->opaque;
365 int size, ret, shift, sum;
367 sum = 0;
369 if (s->aligned_buf != NULL) {
371 if (offset & 0x1ff) {
372 /* align offset on a 512 bytes boundary */
373 shift = offset & 0x1ff;
374 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
375 if (ret < 0)
376 return ret;
378 size = 512 - shift;
379 if (size > count)
380 size = count;
381 memcpy(s->aligned_buf + shift, buf, size);
383 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
384 if (ret < 0)
385 return ret;
387 buf += size;
388 offset += size;
389 count -= size;
390 sum += size;
392 if (count == 0)
393 return sum;
395 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
397 while ((size = (count & ~0x1ff)) != 0) {
399 if (size > ALIGNED_BUFFER_SIZE)
400 size = ALIGNED_BUFFER_SIZE;
402 memcpy(s->aligned_buf, buf, size);
404 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
405 if (ret < 0)
406 return ret;
408 buf += ret;
409 offset += ret;
410 count -= ret;
411 sum += ret;
413 /* here, count < 512 because (count & ~0x1ff) == 0 */
414 if (count) {
415 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
416 if (ret < 0)
417 return ret;
418 memcpy(s->aligned_buf, buf, count);
420 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
421 if (ret < 0)
422 return ret;
423 if (count < ret)
424 ret = count;
426 sum += ret;
428 return sum;
431 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
434 #ifdef CONFIG_AIO
435 /***********************************************************/
436 /* Unix AIO using POSIX AIO */
438 typedef struct RawAIOCB {
439 BlockDriverAIOCB common;
440 struct qemu_paiocb aiocb;
441 struct RawAIOCB *next;
442 int ret;
443 } RawAIOCB;
445 typedef struct PosixAioState
447 int rfd, wfd;
448 RawAIOCB *first_aio;
449 } PosixAioState;
451 static void posix_aio_read(void *opaque)
453 PosixAioState *s = opaque;
454 RawAIOCB *acb, **pacb;
455 int ret;
456 ssize_t len;
458 /* read all bytes from signal pipe */
459 for (;;) {
460 char bytes[16];
462 len = read(s->rfd, bytes, sizeof(bytes));
463 if (len == -1 && errno == EINTR)
464 continue; /* try again */
465 if (len == sizeof(bytes))
466 continue; /* more to read */
467 break;
470 for(;;) {
471 pacb = &s->first_aio;
472 for(;;) {
473 acb = *pacb;
474 if (!acb)
475 goto the_end;
476 ret = qemu_paio_error(&acb->aiocb);
477 if (ret == ECANCELED) {
478 /* remove the request */
479 *pacb = acb->next;
480 qemu_aio_release(acb);
481 } else if (ret != EINPROGRESS) {
482 /* end of aio */
483 if (ret == 0) {
484 ret = qemu_paio_return(&acb->aiocb);
485 if (ret == acb->aiocb.aio_nbytes)
486 ret = 0;
487 else
488 ret = -EINVAL;
489 } else {
490 ret = -ret;
492 /* remove the request */
493 *pacb = acb->next;
494 /* call the callback */
495 acb->common.cb(acb->common.opaque, ret);
496 qemu_aio_release(acb);
497 break;
498 } else {
499 pacb = &acb->next;
503 the_end: ;
506 static int posix_aio_flush(void *opaque)
508 PosixAioState *s = opaque;
509 return !!s->first_aio;
512 static PosixAioState *posix_aio_state;
514 static void aio_signal_handler(int signum)
516 if (posix_aio_state) {
517 char byte = 0;
519 write(posix_aio_state->wfd, &byte, sizeof(byte));
522 qemu_service_io();
525 static int posix_aio_init(void)
527 struct sigaction act;
528 PosixAioState *s;
529 int fds[2];
530 struct qemu_paioinit ai;
532 if (posix_aio_state)
533 return 0;
535 s = qemu_malloc(sizeof(PosixAioState));
536 if (s == NULL)
537 return -ENOMEM;
539 sigfillset(&act.sa_mask);
540 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
541 act.sa_handler = aio_signal_handler;
542 sigaction(SIGUSR2, &act, NULL);
544 s->first_aio = NULL;
545 if (pipe(fds) == -1) {
546 fprintf(stderr, "failed to create pipe\n");
547 return -errno;
550 s->rfd = fds[0];
551 s->wfd = fds[1];
553 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
554 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
556 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
558 memset(&ai, 0, sizeof(ai));
559 ai.aio_threads = 64;
560 ai.aio_num = 64;
561 qemu_paio_init(&ai);
563 posix_aio_state = s;
565 return 0;
568 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
569 int64_t sector_num, uint8_t *buf, int nb_sectors,
570 BlockDriverCompletionFunc *cb, void *opaque)
572 BDRVRawState *s = bs->opaque;
573 RawAIOCB *acb;
575 if (fd_open(bs) < 0)
576 return NULL;
578 acb = qemu_aio_get(bs, cb, opaque);
579 if (!acb)
580 return NULL;
581 acb->aiocb.aio_fildes = s->fd;
582 acb->aiocb.aio_sigevent.sigev_signo = SIGUSR2;
583 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
584 acb->aiocb.aio_buf = buf;
585 if (nb_sectors < 0)
586 acb->aiocb.aio_nbytes = -nb_sectors;
587 else
588 acb->aiocb.aio_nbytes = nb_sectors * 512;
589 acb->aiocb.aio_offset = sector_num * 512;
590 acb->next = posix_aio_state->first_aio;
591 posix_aio_state->first_aio = acb;
592 return acb;
595 static void raw_aio_em_cb(void* opaque)
597 RawAIOCB *acb = opaque;
598 acb->common.cb(acb->common.opaque, acb->ret);
599 qemu_aio_release(acb);
602 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
603 int64_t sector_num, uint8_t *buf, int nb_sectors,
604 BlockDriverCompletionFunc *cb, void *opaque)
606 RawAIOCB *acb;
609 * If O_DIRECT is used and the buffer is not aligned fall back
610 * to synchronous IO.
612 BDRVRawState *s = bs->opaque;
614 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
615 QEMUBH *bh;
616 acb = qemu_aio_get(bs, cb, opaque);
617 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
618 bh = qemu_bh_new(raw_aio_em_cb, acb);
619 qemu_bh_schedule(bh);
620 return &acb->common;
623 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
624 if (!acb)
625 return NULL;
626 if (qemu_paio_read(&acb->aiocb) < 0) {
627 qemu_aio_release(acb);
628 return NULL;
630 return &acb->common;
633 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
634 int64_t sector_num, const uint8_t *buf, int nb_sectors,
635 BlockDriverCompletionFunc *cb, void *opaque)
637 RawAIOCB *acb;
640 * If O_DIRECT is used and the buffer is not aligned fall back
641 * to synchronous IO.
643 BDRVRawState *s = bs->opaque;
645 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
646 QEMUBH *bh;
647 acb = qemu_aio_get(bs, cb, opaque);
648 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
649 bh = qemu_bh_new(raw_aio_em_cb, acb);
650 qemu_bh_schedule(bh);
651 return &acb->common;
654 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
655 if (!acb)
656 return NULL;
657 if (qemu_paio_write(&acb->aiocb) < 0) {
658 qemu_aio_release(acb);
659 return NULL;
661 return &acb->common;
664 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
666 int ret;
667 RawAIOCB *acb = (RawAIOCB *)blockacb;
668 RawAIOCB **pacb;
670 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
671 if (ret == QEMU_PAIO_NOTCANCELED) {
672 /* fail safe: if the aio could not be canceled, we wait for
673 it */
674 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
677 /* remove the callback from the queue */
678 pacb = &posix_aio_state->first_aio;
679 for(;;) {
680 if (*pacb == NULL) {
681 break;
682 } else if (*pacb == acb) {
683 *pacb = acb->next;
684 qemu_aio_release(acb);
685 break;
687 pacb = &acb->next;
690 #else /* CONFIG_AIO */
691 static int posix_aio_init(void)
693 return 0;
695 #endif /* CONFIG_AIO */
698 static void raw_close(BlockDriverState *bs)
700 BDRVRawState *s = bs->opaque;
701 if (s->fd >= 0) {
702 close(s->fd);
703 s->fd = -1;
704 if (s->aligned_buf != NULL)
705 qemu_free(s->aligned_buf);
709 static int raw_truncate(BlockDriverState *bs, int64_t offset)
711 BDRVRawState *s = bs->opaque;
712 if (s->type != FTYPE_FILE)
713 return -ENOTSUP;
714 if (ftruncate(s->fd, offset) < 0)
715 return -errno;
716 return 0;
719 #ifdef __OpenBSD__
720 static int64_t raw_getlength(BlockDriverState *bs)
722 BDRVRawState *s = bs->opaque;
723 int fd = s->fd;
724 struct stat st;
726 if (fstat(fd, &st))
727 return -1;
728 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
729 struct disklabel dl;
731 if (ioctl(fd, DIOCGDINFO, &dl))
732 return -1;
733 return (uint64_t)dl.d_secsize *
734 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
735 } else
736 return st.st_size;
738 #else /* !__OpenBSD__ */
739 static int64_t raw_getlength(BlockDriverState *bs)
741 BDRVRawState *s = bs->opaque;
742 int fd = s->fd;
743 int64_t size;
744 #ifdef _BSD
745 struct stat sb;
746 #endif
747 #ifdef __sun__
748 struct dk_minfo minfo;
749 int rv;
750 #endif
751 int ret;
753 ret = fd_open(bs);
754 if (ret < 0)
755 return ret;
757 #ifdef _BSD
758 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
759 #ifdef DIOCGMEDIASIZE
760 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
761 #endif
762 #ifdef CONFIG_COCOA
763 size = LONG_LONG_MAX;
764 #else
765 size = lseek(fd, 0LL, SEEK_END);
766 #endif
767 } else
768 #endif
769 #ifdef __sun__
771 * use the DKIOCGMEDIAINFO ioctl to read the size.
773 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
774 if ( rv != -1 ) {
775 size = minfo.dki_lbsize * minfo.dki_capacity;
776 } else /* there are reports that lseek on some devices
777 fails, but irc discussion said that contingency
778 on contingency was overkill */
779 #endif
781 size = lseek(fd, 0, SEEK_END);
783 return size;
785 #endif
787 static int raw_create(const char *filename, int64_t total_size,
788 const char *backing_file, int flags)
790 int fd;
792 if (flags || backing_file)
793 return -ENOTSUP;
795 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
796 0644);
797 if (fd < 0)
798 return -EIO;
799 ftruncate(fd, total_size * 512);
800 close(fd);
801 return 0;
804 static void raw_flush(BlockDriverState *bs)
806 BDRVRawState *s = bs->opaque;
807 fsync(s->fd);
810 BlockDriver bdrv_raw = {
811 "raw",
812 sizeof(BDRVRawState),
813 NULL, /* no probe for protocols */
814 raw_open,
815 NULL,
816 NULL,
817 raw_close,
818 raw_create,
819 raw_flush,
821 #ifdef CONFIG_AIO
822 .bdrv_aio_read = raw_aio_read,
823 .bdrv_aio_write = raw_aio_write,
824 .bdrv_aio_cancel = raw_aio_cancel,
825 .aiocb_size = sizeof(RawAIOCB),
826 #endif
828 .bdrv_pread = raw_pread,
829 .bdrv_pwrite = raw_pwrite,
830 .bdrv_truncate = raw_truncate,
831 .bdrv_getlength = raw_getlength,
834 /***********************************************/
835 /* host device */
837 #ifdef CONFIG_COCOA
838 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
839 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
841 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
843 kern_return_t kernResult;
844 mach_port_t masterPort;
845 CFMutableDictionaryRef classesToMatch;
847 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
848 if ( KERN_SUCCESS != kernResult ) {
849 printf( "IOMasterPort returned %d\n", kernResult );
852 classesToMatch = IOServiceMatching( kIOCDMediaClass );
853 if ( classesToMatch == NULL ) {
854 printf( "IOServiceMatching returned a NULL dictionary.\n" );
855 } else {
856 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
858 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
859 if ( KERN_SUCCESS != kernResult )
861 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
864 return kernResult;
867 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
869 io_object_t nextMedia;
870 kern_return_t kernResult = KERN_FAILURE;
871 *bsdPath = '\0';
872 nextMedia = IOIteratorNext( mediaIterator );
873 if ( nextMedia )
875 CFTypeRef bsdPathAsCFString;
876 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
877 if ( bsdPathAsCFString ) {
878 size_t devPathLength;
879 strcpy( bsdPath, _PATH_DEV );
880 strcat( bsdPath, "r" );
881 devPathLength = strlen( bsdPath );
882 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
883 kernResult = KERN_SUCCESS;
885 CFRelease( bsdPathAsCFString );
887 IOObjectRelease( nextMedia );
890 return kernResult;
893 #endif
895 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
897 BDRVRawState *s = bs->opaque;
898 int fd, open_flags, ret;
900 posix_aio_init();
902 #ifdef CONFIG_COCOA
903 if (strstart(filename, "/dev/cdrom", NULL)) {
904 kern_return_t kernResult;
905 io_iterator_t mediaIterator;
906 char bsdPath[ MAXPATHLEN ];
907 int fd;
909 kernResult = FindEjectableCDMedia( &mediaIterator );
910 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
912 if ( bsdPath[ 0 ] != '\0' ) {
913 strcat(bsdPath,"s0");
914 /* some CDs don't have a partition 0 */
915 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
916 if (fd < 0) {
917 bsdPath[strlen(bsdPath)-1] = '1';
918 } else {
919 close(fd);
921 filename = bsdPath;
924 if ( mediaIterator )
925 IOObjectRelease( mediaIterator );
927 #endif
928 open_flags = O_BINARY;
929 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
930 open_flags |= O_RDWR;
931 } else {
932 open_flags |= O_RDONLY;
933 bs->read_only = 1;
935 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
936 * and O_DIRECT for no caching. */
937 if ((flags & BDRV_O_NOCACHE))
938 open_flags |= O_DIRECT;
939 else if (!(flags & BDRV_O_CACHE_WB))
940 open_flags |= O_DSYNC;
942 s->type = FTYPE_FILE;
943 #if defined(__linux__)
944 if (strstart(filename, "/dev/cd", NULL)) {
945 /* open will not fail even if no CD is inserted */
946 open_flags |= O_NONBLOCK;
947 s->type = FTYPE_CD;
948 } else if (strstart(filename, "/dev/fd", NULL)) {
949 s->type = FTYPE_FD;
950 s->fd_open_flags = open_flags;
951 /* open will not fail even if no floppy is inserted */
952 open_flags |= O_NONBLOCK;
953 } else if (strstart(filename, "/dev/sg", NULL)) {
954 bs->sg = 1;
956 #endif
957 fd = open(filename, open_flags, 0644);
958 if (fd < 0) {
959 ret = -errno;
960 if (ret == -EROFS)
961 ret = -EACCES;
962 return ret;
964 s->fd = fd;
965 #if defined(__linux__)
966 /* close fd so that we can reopen it as needed */
967 if (s->type == FTYPE_FD) {
968 close(s->fd);
969 s->fd = -1;
970 s->fd_media_changed = 1;
972 #endif
973 return 0;
976 #if defined(__linux__)
977 /* Note: we do not have a reliable method to detect if the floppy is
978 present. The current method is to try to open the floppy at every
979 I/O and to keep it opened during a few hundreds of ms. */
980 static int fd_open(BlockDriverState *bs)
982 BDRVRawState *s = bs->opaque;
983 int last_media_present;
985 if (s->type != FTYPE_FD)
986 return 0;
987 last_media_present = (s->fd >= 0);
988 if (s->fd >= 0 &&
989 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
990 close(s->fd);
991 s->fd = -1;
992 #ifdef DEBUG_FLOPPY
993 printf("Floppy closed\n");
994 #endif
996 if (s->fd < 0) {
997 if (s->fd_got_error &&
998 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
999 #ifdef DEBUG_FLOPPY
1000 printf("No floppy (open delayed)\n");
1001 #endif
1002 return -EIO;
1004 s->fd = open(bs->filename, s->fd_open_flags);
1005 if (s->fd < 0) {
1006 s->fd_error_time = qemu_get_clock(rt_clock);
1007 s->fd_got_error = 1;
1008 if (last_media_present)
1009 s->fd_media_changed = 1;
1010 #ifdef DEBUG_FLOPPY
1011 printf("No floppy\n");
1012 #endif
1013 return -EIO;
1015 #ifdef DEBUG_FLOPPY
1016 printf("Floppy opened\n");
1017 #endif
1019 if (!last_media_present)
1020 s->fd_media_changed = 1;
1021 s->fd_open_time = qemu_get_clock(rt_clock);
1022 s->fd_got_error = 0;
1023 return 0;
1026 static int raw_is_inserted(BlockDriverState *bs)
1028 BDRVRawState *s = bs->opaque;
1029 int ret;
1031 switch(s->type) {
1032 case FTYPE_CD:
1033 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1034 if (ret == CDS_DISC_OK)
1035 return 1;
1036 else
1037 return 0;
1038 break;
1039 case FTYPE_FD:
1040 ret = fd_open(bs);
1041 return (ret >= 0);
1042 default:
1043 return 1;
1047 /* currently only used by fdc.c, but a CD version would be good too */
1048 static int raw_media_changed(BlockDriverState *bs)
1050 BDRVRawState *s = bs->opaque;
1052 switch(s->type) {
1053 case FTYPE_FD:
1055 int ret;
1056 /* XXX: we do not have a true media changed indication. It
1057 does not work if the floppy is changed without trying
1058 to read it */
1059 fd_open(bs);
1060 ret = s->fd_media_changed;
1061 s->fd_media_changed = 0;
1062 #ifdef DEBUG_FLOPPY
1063 printf("Floppy changed=%d\n", ret);
1064 #endif
1065 return ret;
1067 default:
1068 return -ENOTSUP;
1072 static int raw_eject(BlockDriverState *bs, int eject_flag)
1074 BDRVRawState *s = bs->opaque;
1076 switch(s->type) {
1077 case FTYPE_CD:
1078 if (eject_flag) {
1079 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1080 perror("CDROMEJECT");
1081 } else {
1082 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1083 perror("CDROMEJECT");
1085 break;
1086 case FTYPE_FD:
1088 int fd;
1089 if (s->fd >= 0) {
1090 close(s->fd);
1091 s->fd = -1;
1093 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1094 if (fd >= 0) {
1095 if (ioctl(fd, FDEJECT, 0) < 0)
1096 perror("FDEJECT");
1097 close(fd);
1100 break;
1101 default:
1102 return -ENOTSUP;
1104 return 0;
1107 static int raw_set_locked(BlockDriverState *bs, int locked)
1109 BDRVRawState *s = bs->opaque;
1111 switch(s->type) {
1112 case FTYPE_CD:
1113 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1114 /* Note: an error can happen if the distribution automatically
1115 mounts the CD-ROM */
1116 // perror("CDROM_LOCKDOOR");
1118 break;
1119 default:
1120 return -ENOTSUP;
1122 return 0;
1125 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1127 BDRVRawState *s = bs->opaque;
1129 return ioctl(s->fd, req, buf);
1131 #else
1133 static int fd_open(BlockDriverState *bs)
1135 return 0;
1138 static int raw_is_inserted(BlockDriverState *bs)
1140 return 1;
1143 static int raw_media_changed(BlockDriverState *bs)
1145 return -ENOTSUP;
1148 static int raw_eject(BlockDriverState *bs, int eject_flag)
1150 return -ENOTSUP;
1153 static int raw_set_locked(BlockDriverState *bs, int locked)
1155 return -ENOTSUP;
1158 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1160 return -ENOTSUP;
1162 #endif /* !linux */
1164 BlockDriver bdrv_host_device = {
1165 "host_device",
1166 sizeof(BDRVRawState),
1167 NULL, /* no probe for protocols */
1168 hdev_open,
1169 NULL,
1170 NULL,
1171 raw_close,
1172 NULL,
1173 raw_flush,
1175 #ifdef CONFIG_AIO
1176 .bdrv_aio_read = raw_aio_read,
1177 .bdrv_aio_write = raw_aio_write,
1178 .bdrv_aio_cancel = raw_aio_cancel,
1179 .aiocb_size = sizeof(RawAIOCB),
1180 #endif
1182 .bdrv_pread = raw_pread,
1183 .bdrv_pwrite = raw_pwrite,
1184 .bdrv_getlength = raw_getlength,
1186 /* removable device support */
1187 .bdrv_is_inserted = raw_is_inserted,
1188 .bdrv_media_changed = raw_media_changed,
1189 .bdrv_eject = raw_eject,
1190 .bdrv_set_locked = raw_set_locked,
1191 /* generic scsi device */
1192 .bdrv_ioctl = raw_ioctl,