Disable the vnc CopyRect encoding
[qemu-kvm/fedora.git] / block-raw-posix.c
blob3ec4797274f737f31d15404324d81bd04d0074a2
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 "compatfd.h"
29 #include <assert.h>
30 #ifdef CONFIG_AIO
31 #include "posix-aio-compat.h"
32 #endif
34 #ifdef CONFIG_COCOA
35 #include <paths.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>
44 #endif
46 #ifdef __sun__
47 #define _POSIX_PTHREAD_SEMANTICS 1
48 #include <signal.h>
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/ioctl.h>
53 #include <linux/cdrom.h>
54 #include <linux/fd.h>
55 #endif
56 #ifdef __FreeBSD__
57 #include <signal.h>
58 #include <sys/disk.h>
59 #endif
61 #ifdef __OpenBSD__
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
64 #include <sys/dkio.h>
65 #endif
67 //#define DEBUG_FLOPPY
69 //#define DEBUG_BLOCK
70 #if defined(DEBUG_BLOCK)
71 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (qemu_log_enabled()) \
72 { qemu_log(formatCstr, ##args); qemu_log_flush(); } } while (0)
73 #else
74 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
75 #endif
77 /* OS X does not have O_DSYNC */
78 #ifndef O_DSYNC
79 #ifdef O_SYNC
80 #define O_DSYNC O_SYNC
81 #elif defined(O_FSYNC)
82 #define O_DSYNC O_FSYNC
83 #endif
84 #endif
86 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
87 #ifndef O_DIRECT
88 #define O_DIRECT O_DSYNC
89 #endif
91 #define FTYPE_FILE 0
92 #define FTYPE_CD 1
93 #define FTYPE_FD 2
95 #define ALIGNED_BUFFER_SIZE (32 * 512)
97 /* if the FD is not accessed during that time (in ms), we try to
98 reopen it to see if the disk has been changed */
99 #define FD_OPEN_TIMEOUT 1000
101 typedef struct BDRVRawState {
102 int fd;
103 int type;
104 unsigned int lseek_err_cnt;
105 #if defined(__linux__)
106 /* linux floppy specific */
107 int fd_open_flags;
108 int64_t fd_open_time;
109 int64_t fd_error_time;
110 int fd_got_error;
111 int fd_media_changed;
112 #endif
113 uint8_t* aligned_buf;
114 } BDRVRawState;
116 static int posix_aio_init(void);
118 static int fd_open(BlockDriverState *bs);
120 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
122 BDRVRawState *s = bs->opaque;
123 int fd, open_flags, ret;
125 posix_aio_init();
127 s->lseek_err_cnt = 0;
129 open_flags = O_BINARY;
130 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
131 open_flags |= O_RDWR;
132 } else {
133 open_flags |= O_RDONLY;
134 bs->read_only = 1;
136 if (flags & BDRV_O_CREAT)
137 open_flags |= O_CREAT | O_TRUNC;
139 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
140 * and O_DIRECT for no caching. */
141 if ((flags & BDRV_O_NOCACHE))
142 open_flags |= O_DIRECT;
143 else if (!(flags & BDRV_O_CACHE_WB))
144 open_flags |= O_DSYNC;
146 s->type = FTYPE_FILE;
148 fd = open(filename, open_flags, 0644);
149 if (fd < 0) {
150 ret = -errno;
151 if (ret == -EROFS)
152 ret = -EACCES;
153 return ret;
155 s->fd = fd;
156 s->aligned_buf = NULL;
157 if ((flags & BDRV_O_NOCACHE)) {
158 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
159 if (s->aligned_buf == NULL) {
160 ret = -errno;
161 close(fd);
162 return ret;
165 return 0;
168 /* XXX: use host sector size if necessary with:
169 #ifdef DIOCGSECTORSIZE
171 unsigned int sectorsize = 512;
172 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
173 sectorsize > bufsize)
174 bufsize = sectorsize;
176 #endif
177 #ifdef CONFIG_COCOA
178 u_int32_t blockSize = 512;
179 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
180 bufsize = blockSize;
182 #endif
186 * offset and count are in bytes, but must be multiples of 512 for files
187 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
189 * This function may be called without alignment if the caller ensures
190 * that O_DIRECT is not in effect.
192 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
193 uint8_t *buf, int count)
195 BDRVRawState *s = bs->opaque;
196 int ret;
198 ret = fd_open(bs);
199 if (ret < 0)
200 return ret;
202 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
203 ++(s->lseek_err_cnt);
204 if(s->lseek_err_cnt <= 10) {
205 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
206 "] lseek failed : %d = %s\n",
207 s->fd, bs->filename, offset, buf, count,
208 bs->total_sectors, errno, strerror(errno));
210 return -1;
212 s->lseek_err_cnt=0;
214 ret = read(s->fd, buf, count);
215 if (ret == count)
216 goto label__raw_read__success;
218 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
219 "] read failed %d : %d = %s\n",
220 s->fd, bs->filename, offset, buf, count,
221 bs->total_sectors, ret, errno, strerror(errno));
223 /* Try harder for CDrom. */
224 if (bs->type == BDRV_TYPE_CDROM) {
225 lseek(s->fd, offset, SEEK_SET);
226 ret = read(s->fd, buf, count);
227 if (ret == count)
228 goto label__raw_read__success;
229 lseek(s->fd, offset, SEEK_SET);
230 ret = read(s->fd, buf, count);
231 if (ret == count)
232 goto label__raw_read__success;
234 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
235 "] retry read failed %d : %d = %s\n",
236 s->fd, bs->filename, offset, buf, count,
237 bs->total_sectors, ret, errno, strerror(errno));
240 label__raw_read__success:
242 return (ret < 0) ? -errno : ret;
246 * offset and count are in bytes, but must be multiples of 512 for files
247 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
249 * This function may be called without alignment if the caller ensures
250 * that O_DIRECT is not in effect.
252 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
253 const uint8_t *buf, int count)
255 BDRVRawState *s = bs->opaque;
256 int ret;
258 ret = fd_open(bs);
259 if (ret < 0)
260 return -errno;
262 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
263 ++(s->lseek_err_cnt);
264 if(s->lseek_err_cnt) {
265 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
266 PRId64 "] lseek failed : %d = %s\n",
267 s->fd, bs->filename, offset, buf, count,
268 bs->total_sectors, errno, strerror(errno));
270 return -EIO;
272 s->lseek_err_cnt = 0;
274 ret = write(s->fd, buf, count);
275 if (ret == count)
276 goto label__raw_write__success;
278 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
279 "] write failed %d : %d = %s\n",
280 s->fd, bs->filename, offset, buf, count,
281 bs->total_sectors, ret, errno, strerror(errno));
283 label__raw_write__success:
285 return (ret < 0) ? -errno : ret;
290 * offset and count are in bytes and possibly not aligned. For files opened
291 * with O_DIRECT, necessary alignments are ensured before calling
292 * raw_pread_aligned to do the actual read.
294 static int raw_pread(BlockDriverState *bs, int64_t offset,
295 uint8_t *buf, int count)
297 BDRVRawState *s = bs->opaque;
298 int size, ret, shift, sum;
300 sum = 0;
302 if (s->aligned_buf != NULL) {
304 if (offset & 0x1ff) {
305 /* align offset on a 512 bytes boundary */
307 shift = offset & 0x1ff;
308 size = (shift + count + 0x1ff) & ~0x1ff;
309 if (size > ALIGNED_BUFFER_SIZE)
310 size = ALIGNED_BUFFER_SIZE;
311 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
312 if (ret < 0)
313 return ret;
315 size = 512 - shift;
316 if (size > count)
317 size = count;
318 memcpy(buf, s->aligned_buf + shift, size);
320 buf += size;
321 offset += size;
322 count -= size;
323 sum += size;
325 if (count == 0)
326 return sum;
328 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
330 /* read on aligned buffer */
332 while (count) {
334 size = (count + 0x1ff) & ~0x1ff;
335 if (size > ALIGNED_BUFFER_SIZE)
336 size = ALIGNED_BUFFER_SIZE;
338 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
339 if (ret < 0)
340 return ret;
342 size = ret;
343 if (size > count)
344 size = count;
346 memcpy(buf, s->aligned_buf, size);
348 buf += size;
349 offset += size;
350 count -= size;
351 sum += size;
354 return sum;
358 return raw_pread_aligned(bs, offset, buf, count) + sum;
362 * offset and count are in bytes and possibly not aligned. For files opened
363 * with O_DIRECT, necessary alignments are ensured before calling
364 * raw_pwrite_aligned to do the actual write.
366 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
367 const uint8_t *buf, int count)
369 BDRVRawState *s = bs->opaque;
370 int size, ret, shift, sum;
372 sum = 0;
374 if (s->aligned_buf != NULL) {
376 if (offset & 0x1ff) {
377 /* align offset on a 512 bytes boundary */
378 shift = offset & 0x1ff;
379 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
380 if (ret < 0)
381 return ret;
383 size = 512 - shift;
384 if (size > count)
385 size = count;
386 memcpy(s->aligned_buf + shift, buf, size);
388 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
389 if (ret < 0)
390 return ret;
392 buf += size;
393 offset += size;
394 count -= size;
395 sum += size;
397 if (count == 0)
398 return sum;
400 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
402 while ((size = (count & ~0x1ff)) != 0) {
404 if (size > ALIGNED_BUFFER_SIZE)
405 size = ALIGNED_BUFFER_SIZE;
407 memcpy(s->aligned_buf, buf, size);
409 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
410 if (ret < 0)
411 return ret;
413 buf += ret;
414 offset += ret;
415 count -= ret;
416 sum += ret;
418 /* here, count < 512 because (count & ~0x1ff) == 0 */
419 if (count) {
420 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
421 if (ret < 0)
422 return ret;
423 memcpy(s->aligned_buf, buf, count);
425 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
426 if (ret < 0)
427 return ret;
428 if (count < ret)
429 ret = count;
431 sum += ret;
433 return sum;
436 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
439 #ifdef CONFIG_AIO
440 /***********************************************************/
441 /* Unix AIO using POSIX AIO */
443 typedef struct RawAIOCB {
444 BlockDriverAIOCB common;
445 struct qemu_paiocb aiocb;
446 struct RawAIOCB *next;
447 int ret;
448 } RawAIOCB;
450 typedef struct PosixAioState
452 int fd;
453 RawAIOCB *first_aio;
454 } PosixAioState;
456 static void posix_aio_read(void *opaque)
458 PosixAioState *s = opaque;
459 RawAIOCB *acb, **pacb;
460 int ret;
461 size_t offset;
462 union {
463 struct qemu_signalfd_siginfo siginfo;
464 char buf[128];
465 } sig;
467 /* try to read from signalfd, don't freak out if we can't read anything */
468 offset = 0;
469 while (offset < 128) {
470 ssize_t len;
472 len = read(s->fd, sig.buf + offset, 128 - offset);
473 if (len == -1 && errno == EINTR)
474 continue;
475 if (len == -1 && errno == EAGAIN) {
476 /* there is no natural reason for this to happen,
477 * so we'll spin hard until we get everything just
478 * to be on the safe side. */
479 if (offset > 0)
480 continue;
483 offset += len;
486 for(;;) {
487 pacb = &s->first_aio;
488 for(;;) {
489 acb = *pacb;
490 if (!acb)
491 goto the_end;
492 ret = qemu_paio_error(&acb->aiocb);
493 if (ret == ECANCELED) {
494 /* remove the request */
495 *pacb = acb->next;
496 qemu_aio_release(acb);
497 } else if (ret != EINPROGRESS) {
498 /* end of aio */
499 if (ret == 0) {
500 ret = qemu_paio_return(&acb->aiocb);
501 if (ret == acb->aiocb.aio_nbytes)
502 ret = 0;
503 else
504 ret = -EINVAL;
505 } else {
506 ret = -ret;
508 /* remove the request */
509 *pacb = acb->next;
510 /* call the callback */
511 acb->common.cb(acb->common.opaque, ret);
512 qemu_aio_release(acb);
513 break;
514 } else {
515 pacb = &acb->next;
519 the_end: ;
522 static int posix_aio_flush(void *opaque)
524 PosixAioState *s = opaque;
525 return !!s->first_aio;
528 static PosixAioState *posix_aio_state;
530 static int posix_aio_init(void)
532 sigset_t mask;
533 PosixAioState *s;
534 struct qemu_paioinit ai;
536 if (posix_aio_state)
537 return 0;
539 s = qemu_malloc(sizeof(PosixAioState));
541 /* Make sure to block AIO signal */
542 sigemptyset(&mask);
543 sigaddset(&mask, SIGUSR2);
544 sigprocmask(SIG_BLOCK, &mask, NULL);
546 s->first_aio = NULL;
547 s->fd = qemu_signalfd(&mask);
548 if (s->fd == -1) {
549 fprintf(stderr, "failed to create signalfd\n");
550 return -errno;
553 fcntl(s->fd, F_SETFL, O_NONBLOCK);
555 qemu_aio_set_fd_handler(s->fd, posix_aio_read, NULL, posix_aio_flush, s);
557 memset(&ai, 0, sizeof(ai));
558 ai.aio_threads = 64;
559 ai.aio_num = 64;
560 qemu_paio_init(&ai);
562 posix_aio_state = s;
564 return 0;
567 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
568 int64_t sector_num, uint8_t *buf, int nb_sectors,
569 BlockDriverCompletionFunc *cb, void *opaque)
571 BDRVRawState *s = bs->opaque;
572 RawAIOCB *acb;
574 if (fd_open(bs) < 0)
575 return NULL;
577 acb = qemu_aio_get(bs, cb, opaque);
578 if (!acb)
579 return NULL;
580 acb->aiocb.aio_fildes = s->fd;
581 acb->aiocb.ev_signo = SIGUSR2;
582 acb->aiocb.aio_buf = buf;
583 if (nb_sectors < 0)
584 acb->aiocb.aio_nbytes = -nb_sectors;
585 else
586 acb->aiocb.aio_nbytes = nb_sectors * 512;
587 acb->aiocb.aio_offset = sector_num * 512;
588 acb->next = posix_aio_state->first_aio;
589 posix_aio_state->first_aio = acb;
590 return acb;
593 static void raw_aio_em_cb(void* opaque)
595 RawAIOCB *acb = opaque;
596 acb->common.cb(acb->common.opaque, acb->ret);
597 qemu_aio_release(acb);
600 static void raw_aio_remove(RawAIOCB *acb)
602 RawAIOCB **pacb;
604 /* remove the callback from the queue */
605 pacb = &posix_aio_state->first_aio;
606 for(;;) {
607 if (*pacb == NULL) {
608 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
609 break;
610 } else if (*pacb == acb) {
611 *pacb = acb->next;
612 qemu_aio_release(acb);
613 break;
615 pacb = &(*pacb)->next;
619 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
620 int64_t sector_num, uint8_t *buf, int nb_sectors,
621 BlockDriverCompletionFunc *cb, void *opaque)
623 RawAIOCB *acb;
626 * If O_DIRECT is used and the buffer is not aligned fall back
627 * to synchronous IO.
629 BDRVRawState *s = bs->opaque;
631 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
632 QEMUBH *bh;
633 acb = qemu_aio_get(bs, cb, opaque);
634 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
635 bh = qemu_bh_new(raw_aio_em_cb, acb);
636 qemu_bh_schedule(bh);
637 return &acb->common;
640 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
641 if (!acb)
642 return NULL;
643 if (qemu_paio_read(&acb->aiocb) < 0) {
644 raw_aio_remove(acb);
645 return NULL;
647 return &acb->common;
650 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
651 int64_t sector_num, const uint8_t *buf, int nb_sectors,
652 BlockDriverCompletionFunc *cb, void *opaque)
654 RawAIOCB *acb;
657 * If O_DIRECT is used and the buffer is not aligned fall back
658 * to synchronous IO.
660 BDRVRawState *s = bs->opaque;
662 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
663 QEMUBH *bh;
664 acb = qemu_aio_get(bs, cb, opaque);
665 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
666 bh = qemu_bh_new(raw_aio_em_cb, acb);
667 qemu_bh_schedule(bh);
668 return &acb->common;
671 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
672 if (!acb)
673 return NULL;
674 if (qemu_paio_write(&acb->aiocb) < 0) {
675 raw_aio_remove(acb);
676 return NULL;
678 return &acb->common;
681 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
683 int ret;
684 RawAIOCB *acb = (RawAIOCB *)blockacb;
686 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
687 if (ret == QEMU_PAIO_NOTCANCELED) {
688 /* fail safe: if the aio could not be canceled, we wait for
689 it */
690 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
693 raw_aio_remove(acb);
695 #else /* CONFIG_AIO */
696 static int posix_aio_init(void)
698 return 0;
700 #endif /* CONFIG_AIO */
703 static void raw_close(BlockDriverState *bs)
705 BDRVRawState *s = bs->opaque;
706 if (s->fd >= 0) {
707 close(s->fd);
708 s->fd = -1;
709 if (s->aligned_buf != NULL)
710 qemu_free(s->aligned_buf);
714 static int raw_truncate(BlockDriverState *bs, int64_t offset)
716 BDRVRawState *s = bs->opaque;
717 if (s->type != FTYPE_FILE)
718 return -ENOTSUP;
719 if (ftruncate(s->fd, offset) < 0)
720 return -errno;
721 return 0;
724 #ifdef __OpenBSD__
725 static int64_t raw_getlength(BlockDriverState *bs)
727 BDRVRawState *s = bs->opaque;
728 int fd = s->fd;
729 struct stat st;
731 if (fstat(fd, &st))
732 return -1;
733 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
734 struct disklabel dl;
736 if (ioctl(fd, DIOCGDINFO, &dl))
737 return -1;
738 return (uint64_t)dl.d_secsize *
739 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
740 } else
741 return st.st_size;
743 #else /* !__OpenBSD__ */
744 static int64_t raw_getlength(BlockDriverState *bs)
746 BDRVRawState *s = bs->opaque;
747 int fd = s->fd;
748 int64_t size;
749 #ifdef _BSD
750 struct stat sb;
751 #endif
752 #ifdef __sun__
753 struct dk_minfo minfo;
754 int rv;
755 #endif
756 int ret;
758 ret = fd_open(bs);
759 if (ret < 0)
760 return ret;
762 #ifdef _BSD
763 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
764 #ifdef DIOCGMEDIASIZE
765 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
766 #endif
767 #ifdef CONFIG_COCOA
768 size = LONG_LONG_MAX;
769 #else
770 size = lseek(fd, 0LL, SEEK_END);
771 #endif
772 } else
773 #endif
774 #ifdef __sun__
776 * use the DKIOCGMEDIAINFO ioctl to read the size.
778 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
779 if ( rv != -1 ) {
780 size = minfo.dki_lbsize * minfo.dki_capacity;
781 } else /* there are reports that lseek on some devices
782 fails, but irc discussion said that contingency
783 on contingency was overkill */
784 #endif
786 size = lseek(fd, 0, SEEK_END);
788 return size;
790 #endif
792 static int raw_create(const char *filename, int64_t total_size,
793 const char *backing_file, int flags)
795 int fd;
797 if (flags || backing_file)
798 return -ENOTSUP;
800 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
801 0644);
802 if (fd < 0)
803 return -EIO;
804 ftruncate(fd, total_size * 512);
805 close(fd);
806 return 0;
809 static void raw_flush(BlockDriverState *bs)
811 BDRVRawState *s = bs->opaque;
812 fsync(s->fd);
815 BlockDriver bdrv_raw = {
816 "raw",
817 sizeof(BDRVRawState),
818 NULL, /* no probe for protocols */
819 raw_open,
820 NULL,
821 NULL,
822 raw_close,
823 raw_create,
824 raw_flush,
826 #ifdef CONFIG_AIO
827 .bdrv_aio_read = raw_aio_read,
828 .bdrv_aio_write = raw_aio_write,
829 .bdrv_aio_cancel = raw_aio_cancel,
830 .aiocb_size = sizeof(RawAIOCB),
831 #endif
833 .bdrv_pread = raw_pread,
834 .bdrv_pwrite = raw_pwrite,
835 .bdrv_truncate = raw_truncate,
836 .bdrv_getlength = raw_getlength,
839 /***********************************************/
840 /* host device */
842 #ifdef CONFIG_COCOA
843 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
844 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
846 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
848 kern_return_t kernResult;
849 mach_port_t masterPort;
850 CFMutableDictionaryRef classesToMatch;
852 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
853 if ( KERN_SUCCESS != kernResult ) {
854 printf( "IOMasterPort returned %d\n", kernResult );
857 classesToMatch = IOServiceMatching( kIOCDMediaClass );
858 if ( classesToMatch == NULL ) {
859 printf( "IOServiceMatching returned a NULL dictionary.\n" );
860 } else {
861 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
863 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
864 if ( KERN_SUCCESS != kernResult )
866 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
869 return kernResult;
872 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
874 io_object_t nextMedia;
875 kern_return_t kernResult = KERN_FAILURE;
876 *bsdPath = '\0';
877 nextMedia = IOIteratorNext( mediaIterator );
878 if ( nextMedia )
880 CFTypeRef bsdPathAsCFString;
881 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
882 if ( bsdPathAsCFString ) {
883 size_t devPathLength;
884 strcpy( bsdPath, _PATH_DEV );
885 strcat( bsdPath, "r" );
886 devPathLength = strlen( bsdPath );
887 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
888 kernResult = KERN_SUCCESS;
890 CFRelease( bsdPathAsCFString );
892 IOObjectRelease( nextMedia );
895 return kernResult;
898 #endif
900 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
902 BDRVRawState *s = bs->opaque;
903 int fd, open_flags, ret;
905 posix_aio_init();
907 #ifdef CONFIG_COCOA
908 if (strstart(filename, "/dev/cdrom", NULL)) {
909 kern_return_t kernResult;
910 io_iterator_t mediaIterator;
911 char bsdPath[ MAXPATHLEN ];
912 int fd;
914 kernResult = FindEjectableCDMedia( &mediaIterator );
915 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
917 if ( bsdPath[ 0 ] != '\0' ) {
918 strcat(bsdPath,"s0");
919 /* some CDs don't have a partition 0 */
920 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
921 if (fd < 0) {
922 bsdPath[strlen(bsdPath)-1] = '1';
923 } else {
924 close(fd);
926 filename = bsdPath;
929 if ( mediaIterator )
930 IOObjectRelease( mediaIterator );
932 #endif
933 open_flags = O_BINARY;
934 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
935 open_flags |= O_RDWR;
936 } else {
937 open_flags |= O_RDONLY;
938 bs->read_only = 1;
940 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
941 * and O_DIRECT for no caching. */
942 if ((flags & BDRV_O_NOCACHE))
943 open_flags |= O_DIRECT;
944 else if (!(flags & BDRV_O_CACHE_WB))
945 open_flags |= O_DSYNC;
947 s->type = FTYPE_FILE;
948 #if defined(__linux__)
949 if (strstart(filename, "/dev/cd", NULL)) {
950 /* open will not fail even if no CD is inserted */
951 open_flags |= O_NONBLOCK;
952 s->type = FTYPE_CD;
953 } else if (strstart(filename, "/dev/fd", NULL)) {
954 s->type = FTYPE_FD;
955 s->fd_open_flags = open_flags;
956 /* open will not fail even if no floppy is inserted */
957 open_flags |= O_NONBLOCK;
958 } else if (strstart(filename, "/dev/sg", NULL)) {
959 bs->sg = 1;
961 #endif
962 fd = open(filename, open_flags, 0644);
963 if (fd < 0) {
964 ret = -errno;
965 if (ret == -EROFS)
966 ret = -EACCES;
967 return ret;
969 s->fd = fd;
970 #if defined(__linux__)
971 /* close fd so that we can reopen it as needed */
972 if (s->type == FTYPE_FD) {
973 close(s->fd);
974 s->fd = -1;
975 s->fd_media_changed = 1;
977 #endif
978 return 0;
981 #if defined(__linux__)
982 /* Note: we do not have a reliable method to detect if the floppy is
983 present. The current method is to try to open the floppy at every
984 I/O and to keep it opened during a few hundreds of ms. */
985 static int fd_open(BlockDriverState *bs)
987 BDRVRawState *s = bs->opaque;
988 int last_media_present;
990 if (s->type != FTYPE_FD)
991 return 0;
992 last_media_present = (s->fd >= 0);
993 if (s->fd >= 0 &&
994 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
995 close(s->fd);
996 s->fd = -1;
997 #ifdef DEBUG_FLOPPY
998 printf("Floppy closed\n");
999 #endif
1001 if (s->fd < 0) {
1002 if (s->fd_got_error &&
1003 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1004 #ifdef DEBUG_FLOPPY
1005 printf("No floppy (open delayed)\n");
1006 #endif
1007 return -EIO;
1009 s->fd = open(bs->filename, s->fd_open_flags);
1010 if (s->fd < 0) {
1011 s->fd_error_time = qemu_get_clock(rt_clock);
1012 s->fd_got_error = 1;
1013 if (last_media_present)
1014 s->fd_media_changed = 1;
1015 #ifdef DEBUG_FLOPPY
1016 printf("No floppy\n");
1017 #endif
1018 return -EIO;
1020 #ifdef DEBUG_FLOPPY
1021 printf("Floppy opened\n");
1022 #endif
1024 if (!last_media_present)
1025 s->fd_media_changed = 1;
1026 s->fd_open_time = qemu_get_clock(rt_clock);
1027 s->fd_got_error = 0;
1028 return 0;
1031 static int raw_is_inserted(BlockDriverState *bs)
1033 BDRVRawState *s = bs->opaque;
1034 int ret;
1036 switch(s->type) {
1037 case FTYPE_CD:
1038 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1039 if (ret == CDS_DISC_OK)
1040 return 1;
1041 else
1042 return 0;
1043 break;
1044 case FTYPE_FD:
1045 ret = fd_open(bs);
1046 return (ret >= 0);
1047 default:
1048 return 1;
1052 /* currently only used by fdc.c, but a CD version would be good too */
1053 static int raw_media_changed(BlockDriverState *bs)
1055 BDRVRawState *s = bs->opaque;
1057 switch(s->type) {
1058 case FTYPE_FD:
1060 int ret;
1061 /* XXX: we do not have a true media changed indication. It
1062 does not work if the floppy is changed without trying
1063 to read it */
1064 fd_open(bs);
1065 ret = s->fd_media_changed;
1066 s->fd_media_changed = 0;
1067 #ifdef DEBUG_FLOPPY
1068 printf("Floppy changed=%d\n", ret);
1069 #endif
1070 return ret;
1072 default:
1073 return -ENOTSUP;
1077 static int raw_eject(BlockDriverState *bs, int eject_flag)
1079 BDRVRawState *s = bs->opaque;
1081 switch(s->type) {
1082 case FTYPE_CD:
1083 if (eject_flag) {
1084 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1085 perror("CDROMEJECT");
1086 } else {
1087 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1088 perror("CDROMEJECT");
1090 break;
1091 case FTYPE_FD:
1093 int fd;
1094 if (s->fd >= 0) {
1095 close(s->fd);
1096 s->fd = -1;
1098 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1099 if (fd >= 0) {
1100 if (ioctl(fd, FDEJECT, 0) < 0)
1101 perror("FDEJECT");
1102 close(fd);
1105 break;
1106 default:
1107 return -ENOTSUP;
1109 return 0;
1112 static int raw_set_locked(BlockDriverState *bs, int locked)
1114 BDRVRawState *s = bs->opaque;
1116 switch(s->type) {
1117 case FTYPE_CD:
1118 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1119 /* Note: an error can happen if the distribution automatically
1120 mounts the CD-ROM */
1121 // perror("CDROM_LOCKDOOR");
1123 break;
1124 default:
1125 return -ENOTSUP;
1127 return 0;
1130 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1132 BDRVRawState *s = bs->opaque;
1134 return ioctl(s->fd, req, buf);
1136 #else
1138 static int fd_open(BlockDriverState *bs)
1140 return 0;
1143 static int raw_is_inserted(BlockDriverState *bs)
1145 return 1;
1148 static int raw_media_changed(BlockDriverState *bs)
1150 return -ENOTSUP;
1153 static int raw_eject(BlockDriverState *bs, int eject_flag)
1155 return -ENOTSUP;
1158 static int raw_set_locked(BlockDriverState *bs, int locked)
1160 return -ENOTSUP;
1163 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1165 return -ENOTSUP;
1167 #endif /* !linux */
1169 BlockDriver bdrv_host_device = {
1170 "host_device",
1171 sizeof(BDRVRawState),
1172 NULL, /* no probe for protocols */
1173 hdev_open,
1174 NULL,
1175 NULL,
1176 raw_close,
1177 NULL,
1178 raw_flush,
1180 #ifdef CONFIG_AIO
1181 .bdrv_aio_read = raw_aio_read,
1182 .bdrv_aio_write = raw_aio_write,
1183 .bdrv_aio_cancel = raw_aio_cancel,
1184 .aiocb_size = sizeof(RawAIOCB),
1185 #endif
1187 .bdrv_pread = raw_pread,
1188 .bdrv_pwrite = raw_pwrite,
1189 .bdrv_getlength = raw_getlength,
1191 /* removable device support */
1192 .bdrv_is_inserted = raw_is_inserted,
1193 .bdrv_media_changed = raw_media_changed,
1194 .bdrv_eject = raw_eject,
1195 .bdrv_set_locked = raw_set_locked,
1196 /* generic scsi device */
1197 .bdrv_ioctl = raw_ioctl,