Do not allow AIO to be inited multiple times
[qemu-kvm/fedora.git] / block-raw-posix.c
blobdcd42fe7d533da4f406a666f3f99304151f52496
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 <aio.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 (loglevel != 0) \
72 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
73 #else
74 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
75 #endif
77 #define FTYPE_FILE 0
78 #define FTYPE_CD 1
79 #define FTYPE_FD 2
81 #define ALIGNED_BUFFER_SIZE (32 * 512)
83 /* if the FD is not accessed during that time (in ms), we try to
84 reopen it to see if the disk has been changed */
85 #define FD_OPEN_TIMEOUT 1000
87 typedef struct BDRVRawState {
88 int fd;
89 int type;
90 unsigned int lseek_err_cnt;
91 #if defined(__linux__)
92 /* linux floppy specific */
93 int fd_open_flags;
94 int64_t fd_open_time;
95 int64_t fd_error_time;
96 int fd_got_error;
97 int fd_media_changed;
98 #endif
99 #if defined(O_DIRECT)
100 uint8_t* aligned_buf;
101 #endif
102 } BDRVRawState;
104 static int fd_open(BlockDriverState *bs);
106 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
108 BDRVRawState *s = bs->opaque;
109 int fd, open_flags, ret;
111 s->lseek_err_cnt = 0;
113 open_flags = O_BINARY;
114 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
115 open_flags |= O_RDWR;
116 } else {
117 open_flags |= O_RDONLY;
118 bs->read_only = 1;
120 if (flags & BDRV_O_CREAT)
121 open_flags |= O_CREAT | O_TRUNC;
122 #ifdef O_DIRECT
123 if (flags & BDRV_O_DIRECT)
124 open_flags |= O_DIRECT;
125 #endif
127 s->type = FTYPE_FILE;
129 fd = open(filename, open_flags, 0644);
130 if (fd < 0) {
131 ret = -errno;
132 if (ret == -EROFS)
133 ret = -EACCES;
134 return ret;
136 s->fd = fd;
137 #if defined(O_DIRECT)
138 s->aligned_buf = NULL;
139 if (flags & BDRV_O_DIRECT) {
140 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
141 if (s->aligned_buf == NULL) {
142 ret = -errno;
143 close(fd);
144 return ret;
147 #endif
148 return 0;
151 /* XXX: use host sector size if necessary with:
152 #ifdef DIOCGSECTORSIZE
154 unsigned int sectorsize = 512;
155 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
156 sectorsize > bufsize)
157 bufsize = sectorsize;
159 #endif
160 #ifdef CONFIG_COCOA
161 u_int32_t blockSize = 512;
162 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
163 bufsize = blockSize;
165 #endif
169 * offset and count are in bytes, but must be multiples of 512 for files
170 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
172 * This function may be called without alignment if the caller ensures
173 * that O_DIRECT is not in effect.
175 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
176 uint8_t *buf, int count)
178 BDRVRawState *s = bs->opaque;
179 int ret;
181 ret = fd_open(bs);
182 if (ret < 0)
183 return ret;
185 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
186 ++(s->lseek_err_cnt);
187 if(s->lseek_err_cnt <= 10) {
188 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
189 "] lseek failed : %d = %s\n",
190 s->fd, bs->filename, offset, buf, count,
191 bs->total_sectors, errno, strerror(errno));
193 return -1;
195 s->lseek_err_cnt=0;
197 ret = read(s->fd, buf, count);
198 if (ret == count)
199 goto label__raw_read__success;
201 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
202 "] read failed %d : %d = %s\n",
203 s->fd, bs->filename, offset, buf, count,
204 bs->total_sectors, ret, errno, strerror(errno));
206 /* Try harder for CDrom. */
207 if (bs->type == BDRV_TYPE_CDROM) {
208 lseek(s->fd, offset, SEEK_SET);
209 ret = read(s->fd, buf, count);
210 if (ret == count)
211 goto label__raw_read__success;
212 lseek(s->fd, offset, SEEK_SET);
213 ret = read(s->fd, buf, count);
214 if (ret == count)
215 goto label__raw_read__success;
217 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
218 "] retry read failed %d : %d = %s\n",
219 s->fd, bs->filename, offset, buf, count,
220 bs->total_sectors, ret, errno, strerror(errno));
223 label__raw_read__success:
225 return ret;
229 * offset and count are in bytes, but must be multiples of 512 for files
230 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
232 * This function may be called without alignment if the caller ensures
233 * that O_DIRECT is not in effect.
235 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
236 const uint8_t *buf, int count)
238 BDRVRawState *s = bs->opaque;
239 int ret;
241 ret = fd_open(bs);
242 if (ret < 0)
243 return ret;
245 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
246 ++(s->lseek_err_cnt);
247 if(s->lseek_err_cnt) {
248 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
249 PRId64 "] lseek failed : %d = %s\n",
250 s->fd, bs->filename, offset, buf, count,
251 bs->total_sectors, errno, strerror(errno));
253 return -1;
255 s->lseek_err_cnt = 0;
257 ret = write(s->fd, buf, count);
258 if (ret == count)
259 goto label__raw_write__success;
261 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
262 "] write failed %d : %d = %s\n",
263 s->fd, bs->filename, offset, buf, count,
264 bs->total_sectors, ret, errno, strerror(errno));
266 label__raw_write__success:
268 return ret;
272 #if defined(O_DIRECT)
274 * offset and count are in bytes and possibly not aligned. For files opened
275 * with O_DIRECT, necessary alignments are ensured before calling
276 * raw_pread_aligned to do the actual read.
278 static int raw_pread(BlockDriverState *bs, int64_t offset,
279 uint8_t *buf, int count)
281 BDRVRawState *s = bs->opaque;
282 int size, ret, shift, sum;
284 sum = 0;
286 if (s->aligned_buf != NULL) {
288 if (offset & 0x1ff) {
289 /* align offset on a 512 bytes boundary */
291 shift = offset & 0x1ff;
292 size = (shift + count + 0x1ff) & ~0x1ff;
293 if (size > ALIGNED_BUFFER_SIZE)
294 size = ALIGNED_BUFFER_SIZE;
295 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
296 if (ret < 0)
297 return ret;
299 size = 512 - shift;
300 if (size > count)
301 size = count;
302 memcpy(buf, s->aligned_buf + shift, size);
304 buf += size;
305 offset += size;
306 count -= size;
307 sum += size;
309 if (count == 0)
310 return sum;
312 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
314 /* read on aligned buffer */
316 while (count) {
318 size = (count + 0x1ff) & ~0x1ff;
319 if (size > ALIGNED_BUFFER_SIZE)
320 size = ALIGNED_BUFFER_SIZE;
322 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
323 if (ret < 0)
324 return ret;
326 size = ret;
327 if (size > count)
328 size = count;
330 memcpy(buf, s->aligned_buf, size);
332 buf += size;
333 offset += size;
334 count -= size;
335 sum += size;
338 return sum;
342 return raw_pread_aligned(bs, offset, buf, count) + sum;
346 * offset and count are in bytes and possibly not aligned. For files opened
347 * with O_DIRECT, necessary alignments are ensured before calling
348 * raw_pwrite_aligned to do the actual write.
350 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
351 const uint8_t *buf, int count)
353 BDRVRawState *s = bs->opaque;
354 int size, ret, shift, sum;
356 sum = 0;
358 if (s->aligned_buf != NULL) {
360 if (offset & 0x1ff) {
361 /* align offset on a 512 bytes boundary */
362 shift = offset & 0x1ff;
363 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
364 if (ret < 0)
365 return ret;
367 size = 512 - shift;
368 if (size > count)
369 size = count;
370 memcpy(s->aligned_buf + shift, buf, size);
372 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
373 if (ret < 0)
374 return ret;
376 buf += size;
377 offset += size;
378 count -= size;
379 sum += size;
381 if (count == 0)
382 return sum;
384 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
386 while ((size = (count & ~0x1ff)) != 0) {
388 if (size > ALIGNED_BUFFER_SIZE)
389 size = ALIGNED_BUFFER_SIZE;
391 memcpy(s->aligned_buf, buf, size);
393 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
394 if (ret < 0)
395 return ret;
397 buf += ret;
398 offset += ret;
399 count -= ret;
400 sum += ret;
402 /* here, count < 512 because (count & ~0x1ff) == 0 */
403 if (count) {
404 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
405 if (ret < 0)
406 return ret;
407 memcpy(s->aligned_buf, buf, count);
409 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
410 if (ret < 0)
411 return ret;
412 if (count < ret)
413 ret = count;
415 sum += ret;
417 return sum;
420 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
423 #else
424 #define raw_pread raw_pread_aligned
425 #define raw_pwrite raw_pwrite_aligned
426 #endif
429 #ifdef CONFIG_AIO
430 /***********************************************************/
431 /* Unix AIO using POSIX AIO */
433 typedef struct RawAIOCB {
434 BlockDriverAIOCB common;
435 struct aiocb aiocb;
436 struct RawAIOCB *next;
437 int ret;
438 } RawAIOCB;
440 static int aio_sig_fd = -1;
441 static int aio_sig_num = SIGUSR2;
442 static RawAIOCB *first_aio; /* AIO issued */
443 static int aio_initialized = 0;
445 void qemu_aio_poll(void *opaque)
447 RawAIOCB *acb, **pacb;
448 int ret;
449 size_t offset;
450 union {
451 struct qemu_signalfd_siginfo siginfo;
452 char buf[128];
453 } sig;
455 /* try to read from signalfd, don't freak out if we can't read anything */
456 offset = 0;
457 while (offset < 128) {
458 ssize_t len;
460 len = read(aio_sig_fd, sig.buf + offset, 128 - offset);
461 if (len == -1 && errno == EINTR)
462 continue;
463 if (len == -1 && errno == EAGAIN) {
464 /* there is no natural reason for this to happen,
465 * so we'll spin hard until we get everything just
466 * to be on the safe side. */
467 if (offset > 0)
468 continue;
471 offset += len;
474 for(;;) {
475 pacb = &first_aio;
476 for(;;) {
477 acb = *pacb;
478 if (!acb)
479 goto the_end;
480 ret = aio_error(&acb->aiocb);
481 if (ret == ECANCELED) {
482 /* remove the request */
483 *pacb = acb->next;
484 qemu_aio_release(acb);
485 } else if (ret != EINPROGRESS) {
486 /* end of aio */
487 if (ret == 0) {
488 ret = aio_return(&acb->aiocb);
489 if (ret == acb->aiocb.aio_nbytes)
490 ret = 0;
491 else
492 ret = -EINVAL;
493 } else {
494 ret = -ret;
496 /* remove the request */
497 *pacb = acb->next;
498 /* call the callback */
499 acb->common.cb(acb->common.opaque, ret);
500 qemu_aio_release(acb);
501 break;
502 } else {
503 pacb = &acb->next;
507 the_end: ;
510 void qemu_aio_init(void)
512 sigset_t mask;
514 if (aio_initialized)
515 return;
517 aio_initialized = 1;
519 /* Make sure to block AIO signal */
520 sigemptyset(&mask);
521 sigaddset(&mask, aio_sig_num);
522 sigprocmask(SIG_BLOCK, &mask, NULL);
524 aio_sig_fd = qemu_signalfd(&mask);
526 fcntl(aio_sig_fd, F_SETFL, O_NONBLOCK);
528 qemu_set_fd_handler2(aio_sig_fd, NULL, qemu_aio_poll, NULL, NULL);
530 #if defined(__GLIBC__) && defined(__linux__)
532 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
533 seems to fix the problem. */
534 struct aioinit ai;
535 memset(&ai, 0, sizeof(ai));
536 ai.aio_threads = 1;
537 ai.aio_num = 1;
538 ai.aio_idle_time = 365 * 100000;
539 aio_init(&ai);
541 #endif
544 /* Wait for all IO requests to complete. */
545 void qemu_aio_flush(void)
547 qemu_aio_poll(NULL);
548 while (first_aio) {
549 qemu_aio_wait();
553 void qemu_aio_wait(void)
555 int ret;
557 if (qemu_bh_poll())
558 return;
560 if (!first_aio)
561 return;
563 do {
564 fd_set rdfds;
566 FD_ZERO(&rdfds);
567 FD_SET(aio_sig_fd, &rdfds);
569 ret = select(aio_sig_fd + 1, &rdfds, NULL, NULL, NULL);
570 if (ret == -1 && errno == EINTR)
571 continue;
572 } while (ret == 0);
574 qemu_aio_poll(NULL);
577 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
578 int64_t sector_num, uint8_t *buf, int nb_sectors,
579 BlockDriverCompletionFunc *cb, void *opaque)
581 BDRVRawState *s = bs->opaque;
582 RawAIOCB *acb;
584 if (fd_open(bs) < 0)
585 return NULL;
587 acb = qemu_aio_get(bs, cb, opaque);
588 if (!acb)
589 return NULL;
590 acb->aiocb.aio_fildes = s->fd;
591 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
592 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
593 acb->aiocb.aio_buf = buf;
594 if (nb_sectors < 0)
595 acb->aiocb.aio_nbytes = -nb_sectors;
596 else
597 acb->aiocb.aio_nbytes = nb_sectors * 512;
598 acb->aiocb.aio_offset = sector_num * 512;
599 acb->next = first_aio;
600 first_aio = acb;
601 return acb;
604 static void raw_aio_em_cb(void* opaque)
606 RawAIOCB *acb = opaque;
607 acb->common.cb(acb->common.opaque, acb->ret);
608 qemu_aio_release(acb);
611 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
612 int64_t sector_num, uint8_t *buf, int nb_sectors,
613 BlockDriverCompletionFunc *cb, void *opaque)
615 RawAIOCB *acb;
618 * If O_DIRECT is used and the buffer is not aligned fall back
619 * to synchronous IO.
621 #if defined(O_DIRECT)
622 BDRVRawState *s = bs->opaque;
624 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
625 QEMUBH *bh;
626 acb = qemu_aio_get(bs, cb, opaque);
627 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
628 bh = qemu_bh_new(raw_aio_em_cb, acb);
629 qemu_bh_schedule(bh);
630 return &acb->common;
632 #endif
634 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
635 if (!acb)
636 return NULL;
637 if (aio_read(&acb->aiocb) < 0) {
638 qemu_aio_release(acb);
639 return NULL;
641 return &acb->common;
644 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
645 int64_t sector_num, const uint8_t *buf, int nb_sectors,
646 BlockDriverCompletionFunc *cb, void *opaque)
648 RawAIOCB *acb;
651 * If O_DIRECT is used and the buffer is not aligned fall back
652 * to synchronous IO.
654 #if defined(O_DIRECT)
655 BDRVRawState *s = bs->opaque;
657 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
658 QEMUBH *bh;
659 acb = qemu_aio_get(bs, cb, opaque);
660 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
661 bh = qemu_bh_new(raw_aio_em_cb, acb);
662 qemu_bh_schedule(bh);
663 return &acb->common;
665 #endif
667 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
668 if (!acb)
669 return NULL;
670 if (aio_write(&acb->aiocb) < 0) {
671 qemu_aio_release(acb);
672 return NULL;
674 return &acb->common;
677 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
679 int ret;
680 RawAIOCB *acb = (RawAIOCB *)blockacb;
681 RawAIOCB **pacb;
683 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
684 if (ret == AIO_NOTCANCELED) {
685 /* fail safe: if the aio could not be canceled, we wait for
686 it */
687 while (aio_error(&acb->aiocb) == EINPROGRESS);
690 /* remove the callback from the queue */
691 pacb = &first_aio;
692 for(;;) {
693 if (*pacb == NULL) {
694 break;
695 } else if (*pacb == acb) {
696 *pacb = acb->next;
697 qemu_aio_release(acb);
698 break;
700 pacb = &acb->next;
704 # else /* CONFIG_AIO */
706 void qemu_aio_init(void)
710 void qemu_aio_flush(void)
714 void qemu_aio_wait(void)
716 qemu_bh_poll();
719 #endif /* CONFIG_AIO */
721 static void raw_close(BlockDriverState *bs)
723 BDRVRawState *s = bs->opaque;
724 if (s->fd >= 0) {
725 close(s->fd);
726 s->fd = -1;
727 #if defined(O_DIRECT)
728 if (s->aligned_buf != NULL)
729 qemu_free(s->aligned_buf);
730 #endif
734 static int raw_truncate(BlockDriverState *bs, int64_t offset)
736 BDRVRawState *s = bs->opaque;
737 if (s->type != FTYPE_FILE)
738 return -ENOTSUP;
739 if (ftruncate(s->fd, offset) < 0)
740 return -errno;
741 return 0;
744 #ifdef __OpenBSD__
745 static int64_t raw_getlength(BlockDriverState *bs)
747 BDRVRawState *s = bs->opaque;
748 int fd = s->fd;
749 struct stat st;
751 if (fstat(fd, &st))
752 return -1;
753 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
754 struct disklabel dl;
756 if (ioctl(fd, DIOCGDINFO, &dl))
757 return -1;
758 return (uint64_t)dl.d_secsize *
759 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
760 } else
761 return st.st_size;
763 #else /* !__OpenBSD__ */
764 static int64_t raw_getlength(BlockDriverState *bs)
766 BDRVRawState *s = bs->opaque;
767 int fd = s->fd;
768 int64_t size;
769 #ifdef _BSD
770 struct stat sb;
771 #endif
772 #ifdef __sun__
773 struct dk_minfo minfo;
774 int rv;
775 #endif
776 int ret;
778 ret = fd_open(bs);
779 if (ret < 0)
780 return ret;
782 #ifdef _BSD
783 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
784 #ifdef DIOCGMEDIASIZE
785 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
786 #endif
787 #ifdef CONFIG_COCOA
788 size = LONG_LONG_MAX;
789 #else
790 size = lseek(fd, 0LL, SEEK_END);
791 #endif
792 } else
793 #endif
794 #ifdef __sun__
796 * use the DKIOCGMEDIAINFO ioctl to read the size.
798 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
799 if ( rv != -1 ) {
800 size = minfo.dki_lbsize * minfo.dki_capacity;
801 } else /* there are reports that lseek on some devices
802 fails, but irc discussion said that contingency
803 on contingency was overkill */
804 #endif
806 size = lseek(fd, 0, SEEK_END);
808 return size;
810 #endif
812 static int raw_create(const char *filename, int64_t total_size,
813 const char *backing_file, int flags)
815 int fd;
817 if (flags || backing_file)
818 return -ENOTSUP;
820 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
821 0644);
822 if (fd < 0)
823 return -EIO;
824 ftruncate(fd, total_size * 512);
825 close(fd);
826 return 0;
829 static void raw_flush(BlockDriverState *bs)
831 BDRVRawState *s = bs->opaque;
832 fsync(s->fd);
835 BlockDriver bdrv_raw = {
836 "raw",
837 sizeof(BDRVRawState),
838 NULL, /* no probe for protocols */
839 raw_open,
840 NULL,
841 NULL,
842 raw_close,
843 raw_create,
844 raw_flush,
846 #ifdef CONFIG_AIO
847 .bdrv_aio_read = raw_aio_read,
848 .bdrv_aio_write = raw_aio_write,
849 .bdrv_aio_cancel = raw_aio_cancel,
850 .aiocb_size = sizeof(RawAIOCB),
851 #endif
852 .bdrv_pread = raw_pread,
853 .bdrv_pwrite = raw_pwrite,
854 .bdrv_truncate = raw_truncate,
855 .bdrv_getlength = raw_getlength,
858 /***********************************************/
859 /* host device */
861 #ifdef CONFIG_COCOA
862 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
863 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
865 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
867 kern_return_t kernResult;
868 mach_port_t masterPort;
869 CFMutableDictionaryRef classesToMatch;
871 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
872 if ( KERN_SUCCESS != kernResult ) {
873 printf( "IOMasterPort returned %d\n", kernResult );
876 classesToMatch = IOServiceMatching( kIOCDMediaClass );
877 if ( classesToMatch == NULL ) {
878 printf( "IOServiceMatching returned a NULL dictionary.\n" );
879 } else {
880 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
882 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
883 if ( KERN_SUCCESS != kernResult )
885 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
888 return kernResult;
891 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
893 io_object_t nextMedia;
894 kern_return_t kernResult = KERN_FAILURE;
895 *bsdPath = '\0';
896 nextMedia = IOIteratorNext( mediaIterator );
897 if ( nextMedia )
899 CFTypeRef bsdPathAsCFString;
900 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
901 if ( bsdPathAsCFString ) {
902 size_t devPathLength;
903 strcpy( bsdPath, _PATH_DEV );
904 strcat( bsdPath, "r" );
905 devPathLength = strlen( bsdPath );
906 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
907 kernResult = KERN_SUCCESS;
909 CFRelease( bsdPathAsCFString );
911 IOObjectRelease( nextMedia );
914 return kernResult;
917 #endif
919 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
921 BDRVRawState *s = bs->opaque;
922 int fd, open_flags, ret;
924 #ifdef CONFIG_COCOA
925 if (strstart(filename, "/dev/cdrom", NULL)) {
926 kern_return_t kernResult;
927 io_iterator_t mediaIterator;
928 char bsdPath[ MAXPATHLEN ];
929 int fd;
931 kernResult = FindEjectableCDMedia( &mediaIterator );
932 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
934 if ( bsdPath[ 0 ] != '\0' ) {
935 strcat(bsdPath,"s0");
936 /* some CDs don't have a partition 0 */
937 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
938 if (fd < 0) {
939 bsdPath[strlen(bsdPath)-1] = '1';
940 } else {
941 close(fd);
943 filename = bsdPath;
946 if ( mediaIterator )
947 IOObjectRelease( mediaIterator );
949 #endif
950 open_flags = O_BINARY;
951 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
952 open_flags |= O_RDWR;
953 } else {
954 open_flags |= O_RDONLY;
955 bs->read_only = 1;
957 #ifdef O_DIRECT
958 if (flags & BDRV_O_DIRECT)
959 open_flags |= O_DIRECT;
960 #endif
962 s->type = FTYPE_FILE;
963 #if defined(__linux__)
964 if (strstart(filename, "/dev/cd", NULL)) {
965 /* open will not fail even if no CD is inserted */
966 open_flags |= O_NONBLOCK;
967 s->type = FTYPE_CD;
968 } else if (strstart(filename, "/dev/fd", NULL)) {
969 s->type = FTYPE_FD;
970 s->fd_open_flags = open_flags;
971 /* open will not fail even if no floppy is inserted */
972 open_flags |= O_NONBLOCK;
973 } else if (strstart(filename, "/dev/sg", NULL)) {
974 bs->sg = 1;
976 #endif
977 fd = open(filename, open_flags, 0644);
978 if (fd < 0) {
979 ret = -errno;
980 if (ret == -EROFS)
981 ret = -EACCES;
982 return ret;
984 s->fd = fd;
985 #if defined(__linux__)
986 /* close fd so that we can reopen it as needed */
987 if (s->type == FTYPE_FD) {
988 close(s->fd);
989 s->fd = -1;
990 s->fd_media_changed = 1;
992 #endif
993 return 0;
996 #if defined(__linux__)
998 /* Note: we do not have a reliable method to detect if the floppy is
999 present. The current method is to try to open the floppy at every
1000 I/O and to keep it opened during a few hundreds of ms. */
1001 static int fd_open(BlockDriverState *bs)
1003 BDRVRawState *s = bs->opaque;
1004 int last_media_present;
1006 if (s->type != FTYPE_FD)
1007 return 0;
1008 last_media_present = (s->fd >= 0);
1009 if (s->fd >= 0 &&
1010 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1011 close(s->fd);
1012 s->fd = -1;
1013 #ifdef DEBUG_FLOPPY
1014 printf("Floppy closed\n");
1015 #endif
1017 if (s->fd < 0) {
1018 if (s->fd_got_error &&
1019 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1020 #ifdef DEBUG_FLOPPY
1021 printf("No floppy (open delayed)\n");
1022 #endif
1023 return -EIO;
1025 s->fd = open(bs->filename, s->fd_open_flags);
1026 if (s->fd < 0) {
1027 s->fd_error_time = qemu_get_clock(rt_clock);
1028 s->fd_got_error = 1;
1029 if (last_media_present)
1030 s->fd_media_changed = 1;
1031 #ifdef DEBUG_FLOPPY
1032 printf("No floppy\n");
1033 #endif
1034 return -EIO;
1036 #ifdef DEBUG_FLOPPY
1037 printf("Floppy opened\n");
1038 #endif
1040 if (!last_media_present)
1041 s->fd_media_changed = 1;
1042 s->fd_open_time = qemu_get_clock(rt_clock);
1043 s->fd_got_error = 0;
1044 return 0;
1047 static int raw_is_inserted(BlockDriverState *bs)
1049 BDRVRawState *s = bs->opaque;
1050 int ret;
1052 switch(s->type) {
1053 case FTYPE_CD:
1054 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1055 if (ret == CDS_DISC_OK)
1056 return 1;
1057 else
1058 return 0;
1059 break;
1060 case FTYPE_FD:
1061 ret = fd_open(bs);
1062 return (ret >= 0);
1063 default:
1064 return 1;
1068 /* currently only used by fdc.c, but a CD version would be good too */
1069 static int raw_media_changed(BlockDriverState *bs)
1071 BDRVRawState *s = bs->opaque;
1073 switch(s->type) {
1074 case FTYPE_FD:
1076 int ret;
1077 /* XXX: we do not have a true media changed indication. It
1078 does not work if the floppy is changed without trying
1079 to read it */
1080 fd_open(bs);
1081 ret = s->fd_media_changed;
1082 s->fd_media_changed = 0;
1083 #ifdef DEBUG_FLOPPY
1084 printf("Floppy changed=%d\n", ret);
1085 #endif
1086 return ret;
1088 default:
1089 return -ENOTSUP;
1093 static int raw_eject(BlockDriverState *bs, int eject_flag)
1095 BDRVRawState *s = bs->opaque;
1097 switch(s->type) {
1098 case FTYPE_CD:
1099 if (eject_flag) {
1100 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1101 perror("CDROMEJECT");
1102 } else {
1103 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1104 perror("CDROMEJECT");
1106 break;
1107 case FTYPE_FD:
1109 int fd;
1110 if (s->fd >= 0) {
1111 close(s->fd);
1112 s->fd = -1;
1114 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1115 if (fd >= 0) {
1116 if (ioctl(fd, FDEJECT, 0) < 0)
1117 perror("FDEJECT");
1118 close(fd);
1121 break;
1122 default:
1123 return -ENOTSUP;
1125 return 0;
1128 static int raw_set_locked(BlockDriverState *bs, int locked)
1130 BDRVRawState *s = bs->opaque;
1132 switch(s->type) {
1133 case FTYPE_CD:
1134 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1135 /* Note: an error can happen if the distribution automatically
1136 mounts the CD-ROM */
1137 // perror("CDROM_LOCKDOOR");
1139 break;
1140 default:
1141 return -ENOTSUP;
1143 return 0;
1146 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1148 BDRVRawState *s = bs->opaque;
1150 return ioctl(s->fd, req, buf);
1152 #else
1154 static int fd_open(BlockDriverState *bs)
1156 return 0;
1159 static int raw_is_inserted(BlockDriverState *bs)
1161 return 1;
1164 static int raw_media_changed(BlockDriverState *bs)
1166 return -ENOTSUP;
1169 static int raw_eject(BlockDriverState *bs, int eject_flag)
1171 return -ENOTSUP;
1174 static int raw_set_locked(BlockDriverState *bs, int locked)
1176 return -ENOTSUP;
1179 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1181 return -ENOTSUP;
1183 #endif /* !linux */
1185 BlockDriver bdrv_host_device = {
1186 "host_device",
1187 sizeof(BDRVRawState),
1188 NULL, /* no probe for protocols */
1189 hdev_open,
1190 NULL,
1191 NULL,
1192 raw_close,
1193 NULL,
1194 raw_flush,
1196 #ifdef CONFIG_AIO
1197 .bdrv_aio_read = raw_aio_read,
1198 .bdrv_aio_write = raw_aio_write,
1199 .bdrv_aio_cancel = raw_aio_cancel,
1200 .aiocb_size = sizeof(RawAIOCB),
1201 #endif
1202 .bdrv_pread = raw_pread,
1203 .bdrv_pwrite = raw_pwrite,
1204 .bdrv_getlength = raw_getlength,
1206 /* removable device support */
1207 .bdrv_is_inserted = raw_is_inserted,
1208 .bdrv_media_changed = raw_media_changed,
1209 .bdrv_eject = raw_eject,
1210 .bdrv_set_locked = raw_set_locked,
1211 /* generic scsi device */
1212 .bdrv_ioctl = raw_ioctl,