kvm: libkvm: export init for coalesced MMIO support
[qemu-kvm/markmc.git] / block-raw-posix.c
blob7fd85bccb4481b70be3c3d8ebb658df991948f72
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 #ifndef QEMU_IMG
26 #include "qemu-kvm.h"
27 #include "qemu-timer.h"
28 #include "exec-all.h"
29 #endif
30 #include "block_int.h"
31 #include <assert.h>
32 #include <aio.h>
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 <sys/disk.h>
58 #endif
60 //#define DEBUG_FLOPPY
62 //#define DEBUG_BLOCK
63 #if defined(DEBUG_BLOCK) && !defined(QEMU_IMG)
64 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
65 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
66 #else
67 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
68 #endif
70 #define FTYPE_FILE 0
71 #define FTYPE_CD 1
72 #define FTYPE_FD 2
74 #define ALIGNED_BUFFER_SIZE (32 * 512)
76 /* if the FD is not accessed during that time (in ms), we try to
77 reopen it to see if the disk has been changed */
78 #define FD_OPEN_TIMEOUT 1000
80 typedef struct BDRVRawState {
81 int fd;
82 int type;
83 unsigned int lseek_err_cnt;
84 #if defined(__linux__)
85 /* linux floppy specific */
86 int fd_open_flags;
87 int64_t fd_open_time;
88 int64_t fd_error_time;
89 int fd_got_error;
90 int fd_media_changed;
91 #endif
92 #if defined(O_DIRECT) && !defined(QEMU_IMG)
93 uint8_t* aligned_buf;
94 #endif
95 } BDRVRawState;
97 static int fd_open(BlockDriverState *bs);
99 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
101 BDRVRawState *s = bs->opaque;
102 int fd, open_flags, ret;
104 s->lseek_err_cnt = 0;
106 open_flags = O_BINARY;
107 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
108 open_flags |= O_RDWR;
109 } else {
110 open_flags |= O_RDONLY;
111 bs->read_only = 1;
113 if (flags & BDRV_O_CREAT)
114 open_flags |= O_CREAT | O_TRUNC;
115 #ifdef O_DIRECT
116 if (flags & BDRV_O_DIRECT)
117 open_flags |= O_DIRECT;
118 #endif
120 s->type = FTYPE_FILE;
122 fd = open(filename, open_flags, 0644);
123 if (fd < 0) {
124 ret = -errno;
125 if (ret == -EROFS)
126 ret = -EACCES;
127 return ret;
129 s->fd = fd;
130 #if defined(O_DIRECT) && !defined(QEMU_IMG)
131 s->aligned_buf = NULL;
132 if (flags & BDRV_O_DIRECT) {
133 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
134 if (s->aligned_buf == NULL) {
135 ret = -errno;
136 close(fd);
137 return ret;
140 #endif
141 return 0;
144 /* XXX: use host sector size if necessary with:
145 #ifdef DIOCGSECTORSIZE
147 unsigned int sectorsize = 512;
148 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
149 sectorsize > bufsize)
150 bufsize = sectorsize;
152 #endif
153 #ifdef CONFIG_COCOA
154 u_int32_t blockSize = 512;
155 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
156 bufsize = blockSize;
158 #endif
162 * offset and count are in bytes, but must be multiples of 512 for files
163 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
165 * This function may be called without alignment if the caller ensures
166 * that O_DIRECT is not in effect.
168 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
169 uint8_t *buf, int count)
171 BDRVRawState *s = bs->opaque;
172 int ret;
174 ret = fd_open(bs);
175 if (ret < 0)
176 return ret;
178 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
179 ++(s->lseek_err_cnt);
180 if(s->lseek_err_cnt <= 10) {
181 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
182 "] lseek failed : %d = %s\n",
183 s->fd, bs->filename, offset, buf, count,
184 bs->total_sectors, errno, strerror(errno));
186 return -1;
188 s->lseek_err_cnt=0;
190 ret = read(s->fd, buf, count);
191 if (ret == count)
192 goto label__raw_read__success;
194 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
195 "] read failed %d : %d = %s\n",
196 s->fd, bs->filename, offset, buf, count,
197 bs->total_sectors, ret, errno, strerror(errno));
199 /* Try harder for CDrom. */
200 if (bs->type == BDRV_TYPE_CDROM) {
201 lseek(s->fd, offset, SEEK_SET);
202 ret = read(s->fd, buf, count);
203 if (ret == count)
204 goto label__raw_read__success;
205 lseek(s->fd, offset, SEEK_SET);
206 ret = read(s->fd, buf, count);
207 if (ret == count)
208 goto label__raw_read__success;
210 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
211 "] retry read failed %d : %d = %s\n",
212 s->fd, bs->filename, offset, buf, count,
213 bs->total_sectors, ret, errno, strerror(errno));
216 label__raw_read__success:
218 return ret;
222 * offset and count are in bytes, but must be multiples of 512 for files
223 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
225 * This function may be called without alignment if the caller ensures
226 * that O_DIRECT is not in effect.
228 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
229 const uint8_t *buf, int count)
231 BDRVRawState *s = bs->opaque;
232 int ret;
234 ret = fd_open(bs);
235 if (ret < 0)
236 return ret;
238 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
239 ++(s->lseek_err_cnt);
240 if(s->lseek_err_cnt) {
241 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
242 PRId64 "] lseek failed : %d = %s\n",
243 s->fd, bs->filename, offset, buf, count,
244 bs->total_sectors, errno, strerror(errno));
246 return -1;
248 s->lseek_err_cnt = 0;
250 ret = write(s->fd, buf, count);
251 if (ret == count)
252 goto label__raw_write__success;
254 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
255 "] write failed %d : %d = %s\n",
256 s->fd, bs->filename, offset, buf, count,
257 bs->total_sectors, ret, errno, strerror(errno));
259 label__raw_write__success:
261 return ret;
265 #if defined(O_DIRECT) && !defined(QEMU_IMG)
267 * offset and count are in bytes and possibly not aligned. For files opened
268 * with O_DIRECT, necessary alignments are ensured before calling
269 * raw_pread_aligned to do the actual read.
271 static int raw_pread(BlockDriverState *bs, int64_t offset,
272 uint8_t *buf, int count)
274 BDRVRawState *s = bs->opaque;
275 int size, ret, shift, sum;
277 sum = 0;
279 if (s->aligned_buf != NULL) {
281 if (offset & 0x1ff) {
282 /* align offset on a 512 bytes boundary */
284 shift = offset & 0x1ff;
285 size = (shift + count + 0x1ff) & ~0x1ff;
286 if (size > ALIGNED_BUFFER_SIZE)
287 size = ALIGNED_BUFFER_SIZE;
288 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
289 if (ret < 0)
290 return ret;
292 size = 512 - shift;
293 if (size > count)
294 size = count;
295 memcpy(buf, s->aligned_buf + shift, size);
297 buf += size;
298 offset += size;
299 count -= size;
300 sum += size;
302 if (count == 0)
303 return sum;
305 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
307 /* read on aligned buffer */
309 while (count) {
311 size = (count + 0x1ff) & ~0x1ff;
312 if (size > ALIGNED_BUFFER_SIZE)
313 size = ALIGNED_BUFFER_SIZE;
315 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
316 if (ret < 0)
317 return ret;
319 size = ret;
320 if (size > count)
321 size = count;
323 memcpy(buf, s->aligned_buf, size);
325 buf += size;
326 offset += size;
327 count -= size;
328 sum += size;
331 return sum;
335 return raw_pread_aligned(bs, offset, buf, count) + sum;
339 * offset and count are in bytes and possibly not aligned. For files opened
340 * with O_DIRECT, necessary alignments are ensured before calling
341 * raw_pwrite_aligned to do the actual write.
343 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
344 const uint8_t *buf, int count)
346 BDRVRawState *s = bs->opaque;
347 int size, ret, shift, sum;
349 sum = 0;
351 if (s->aligned_buf != NULL) {
353 if (offset & 0x1ff) {
354 /* align offset on a 512 bytes boundary */
355 shift = offset & 0x1ff;
356 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
357 if (ret < 0)
358 return ret;
360 size = 512 - shift;
361 if (size > count)
362 size = count;
363 memcpy(s->aligned_buf + shift, buf, size);
365 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
366 if (ret < 0)
367 return ret;
369 buf += size;
370 offset += size;
371 count -= size;
372 sum += size;
374 if (count == 0)
375 return sum;
377 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
379 while ((size = (count & ~0x1ff)) != 0) {
381 if (size > ALIGNED_BUFFER_SIZE)
382 size = ALIGNED_BUFFER_SIZE;
384 memcpy(s->aligned_buf, buf, size);
386 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
387 if (ret < 0)
388 return ret;
390 buf += ret;
391 offset += ret;
392 count -= ret;
393 sum += ret;
395 /* here, count < 512 because (count & ~0x1ff) == 0 */
396 if (count) {
397 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
398 if (ret < 0)
399 return ret;
400 memcpy(s->aligned_buf, buf, count);
402 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
403 if (ret < 0)
404 return ret;
405 if (count < ret)
406 ret = count;
408 sum += ret;
410 return sum;
413 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
416 #else
417 #define raw_pread raw_pread_aligned
418 #define raw_pwrite raw_pwrite_aligned
419 #endif
422 /***********************************************************/
423 /* Unix AIO using POSIX AIO */
425 typedef struct RawAIOCB {
426 BlockDriverAIOCB common;
427 struct aiocb aiocb;
428 struct RawAIOCB *next;
429 int ret;
430 } RawAIOCB;
432 static int aio_sig_num = SIGUSR2;
433 static RawAIOCB *first_aio; /* AIO issued */
434 static int aio_initialized = 0;
436 static void aio_signal_handler(int signum)
438 #ifndef QEMU_IMG
439 CPUState *env = cpu_single_env;
440 if (env) {
441 /* stop the currently executing cpu because a timer occured */
442 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
443 #ifdef USE_KQEMU
444 if (env->kqemu_enabled) {
445 kqemu_cpu_interrupt(env);
447 #endif
449 #endif
452 void qemu_aio_init(void)
454 struct sigaction act;
456 aio_initialized = 1;
458 sigfillset(&act.sa_mask);
459 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
460 act.sa_handler = aio_signal_handler;
461 sigaction(aio_sig_num, &act, NULL);
463 #if defined(__GLIBC__) && defined(__linux__)
465 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
466 seems to fix the problem. */
467 struct aioinit ai;
468 memset(&ai, 0, sizeof(ai));
469 ai.aio_threads = 1;
470 ai.aio_num = 1;
471 ai.aio_idle_time = 365 * 100000;
472 aio_init(&ai);
474 #endif
477 void qemu_aio_poll(void)
479 RawAIOCB *acb, **pacb;
480 int ret;
482 for(;;) {
483 pacb = &first_aio;
484 for(;;) {
485 acb = *pacb;
486 if (!acb)
487 goto the_end;
488 ret = aio_error(&acb->aiocb);
489 if (ret == ECANCELED) {
490 /* remove the request */
491 *pacb = acb->next;
492 qemu_aio_release(acb);
493 } else if (ret != EINPROGRESS) {
494 /* end of aio */
495 if (ret == 0) {
496 ret = aio_return(&acb->aiocb);
497 if (ret == acb->aiocb.aio_nbytes)
498 ret = 0;
499 else
500 ret = -EINVAL;
501 } else {
502 ret = -ret;
504 /* remove the request */
505 *pacb = acb->next;
506 /* call the callback */
507 acb->common.cb(acb->common.opaque, ret);
508 qemu_aio_release(acb);
509 break;
510 } else {
511 pacb = &acb->next;
515 the_end: ;
518 /* Wait for all IO requests to complete. */
519 void qemu_aio_flush(void)
521 qemu_aio_wait_start();
522 qemu_aio_poll();
523 while (first_aio) {
524 qemu_aio_wait();
526 qemu_aio_wait_end();
529 /* wait until at least one AIO was handled */
530 static sigset_t wait_oset;
532 void qemu_aio_wait_start(void)
534 sigset_t set;
536 if (!aio_initialized)
537 qemu_aio_init();
538 #ifndef QEMU_IMG
539 if (kvm_enabled()) {
540 qemu_kvm_aio_wait_start();
541 return;
543 #endif
544 sigemptyset(&set);
545 sigaddset(&set, aio_sig_num);
546 sigprocmask(SIG_BLOCK, &set, &wait_oset);
549 void qemu_aio_wait(void)
551 sigset_t set;
552 int nb_sigs;
554 #ifndef QEMU_IMG
555 if (qemu_bh_poll())
556 return;
557 if (kvm_enabled()) {
558 qemu_kvm_aio_wait();
559 qemu_aio_poll();
560 return;
562 #endif
563 sigemptyset(&set);
564 sigaddset(&set, aio_sig_num);
565 sigwait(&set, &nb_sigs);
566 qemu_aio_poll();
569 void qemu_aio_wait_end(void)
571 #ifndef QEMU_IMG
572 if (kvm_enabled()) {
573 qemu_kvm_aio_wait_end();
574 return;
576 #endif
577 sigprocmask(SIG_SETMASK, &wait_oset, NULL);
580 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
581 int64_t sector_num, uint8_t *buf, int nb_sectors,
582 BlockDriverCompletionFunc *cb, void *opaque)
584 BDRVRawState *s = bs->opaque;
585 RawAIOCB *acb;
587 if (fd_open(bs) < 0)
588 return NULL;
590 acb = qemu_aio_get(bs, cb, opaque);
591 if (!acb)
592 return NULL;
593 acb->aiocb.aio_fildes = s->fd;
594 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
595 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
596 acb->aiocb.aio_buf = buf;
597 if (nb_sectors < 0)
598 acb->aiocb.aio_nbytes = -nb_sectors;
599 else
600 acb->aiocb.aio_nbytes = nb_sectors * 512;
601 acb->aiocb.aio_offset = sector_num * 512;
602 acb->next = first_aio;
603 first_aio = acb;
604 return acb;
607 #ifndef QEMU_IMG
608 static void raw_aio_em_cb(void* opaque)
610 RawAIOCB *acb = opaque;
611 acb->common.cb(acb->common.opaque, acb->ret);
612 qemu_aio_release(acb);
614 #endif
616 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
617 int64_t sector_num, uint8_t *buf, int nb_sectors,
618 BlockDriverCompletionFunc *cb, void *opaque)
620 RawAIOCB *acb;
623 * If O_DIRECT is used and the buffer is not aligned fall back
624 * to synchronous IO.
626 #if defined(O_DIRECT) && !defined(QEMU_IMG)
627 BDRVRawState *s = bs->opaque;
629 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
630 QEMUBH *bh;
631 acb = qemu_aio_get(bs, cb, opaque);
632 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
633 bh = qemu_bh_new(raw_aio_em_cb, acb);
634 qemu_bh_schedule(bh);
635 return &acb->common;
637 #endif
639 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
640 if (!acb)
641 return NULL;
642 if (aio_read(&acb->aiocb) < 0) {
643 qemu_aio_release(acb);
644 return NULL;
646 return &acb->common;
649 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
650 int64_t sector_num, const uint8_t *buf, int nb_sectors,
651 BlockDriverCompletionFunc *cb, void *opaque)
653 RawAIOCB *acb;
656 * If O_DIRECT is used and the buffer is not aligned fall back
657 * to synchronous IO.
659 #if defined(O_DIRECT) && !defined(QEMU_IMG)
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;
670 #endif
672 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
673 if (!acb)
674 return NULL;
675 if (aio_write(&acb->aiocb) < 0) {
676 qemu_aio_release(acb);
677 return NULL;
679 return &acb->common;
682 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
684 int ret;
685 RawAIOCB *acb = (RawAIOCB *)blockacb;
686 RawAIOCB **pacb;
688 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
689 if (ret == AIO_NOTCANCELED) {
690 /* fail safe: if the aio could not be canceled, we wait for
691 it */
692 while (aio_error(&acb->aiocb) == EINPROGRESS);
695 /* remove the callback from the queue */
696 pacb = &first_aio;
697 for(;;) {
698 if (*pacb == NULL) {
699 break;
700 } else if (*pacb == acb) {
701 *pacb = acb->next;
702 qemu_aio_release(acb);
703 break;
705 pacb = &acb->next;
709 static void raw_close(BlockDriverState *bs)
711 BDRVRawState *s = bs->opaque;
712 if (s->fd >= 0) {
713 close(s->fd);
714 s->fd = -1;
715 #if defined(O_DIRECT) && !defined(QEMU_IMG)
716 if (s->aligned_buf != NULL)
717 qemu_free(s->aligned_buf);
718 #endif
722 static int raw_truncate(BlockDriverState *bs, int64_t offset)
724 BDRVRawState *s = bs->opaque;
725 if (s->type != FTYPE_FILE)
726 return -ENOTSUP;
727 if (ftruncate(s->fd, offset) < 0)
728 return -errno;
729 return 0;
732 static int64_t raw_getlength(BlockDriverState *bs)
734 BDRVRawState *s = bs->opaque;
735 int fd = s->fd;
736 int64_t size;
737 #ifdef _BSD
738 struct stat sb;
739 #endif
740 #ifdef __sun__
741 struct dk_minfo minfo;
742 int rv;
743 #endif
744 int ret;
746 ret = fd_open(bs);
747 if (ret < 0)
748 return ret;
750 #ifdef _BSD
751 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
752 #ifdef DIOCGMEDIASIZE
753 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
754 #endif
755 #ifdef CONFIG_COCOA
756 size = LONG_LONG_MAX;
757 #else
758 size = lseek(fd, 0LL, SEEK_END);
759 #endif
760 } else
761 #endif
762 #ifdef __sun__
764 * use the DKIOCGMEDIAINFO ioctl to read the size.
766 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
767 if ( rv != -1 ) {
768 size = minfo.dki_lbsize * minfo.dki_capacity;
769 } else /* there are reports that lseek on some devices
770 fails, but irc discussion said that contingency
771 on contingency was overkill */
772 #endif
774 size = lseek(fd, 0, SEEK_END);
776 return size;
779 static int raw_create(const char *filename, int64_t total_size,
780 const char *backing_file, int flags)
782 int fd;
784 if (flags || backing_file)
785 return -ENOTSUP;
787 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
788 0644);
789 if (fd < 0)
790 return -EIO;
791 ftruncate(fd, total_size * 512);
792 close(fd);
793 return 0;
796 static void raw_flush(BlockDriverState *bs)
798 BDRVRawState *s = bs->opaque;
799 fsync(s->fd);
802 BlockDriver bdrv_raw = {
803 "raw",
804 sizeof(BDRVRawState),
805 NULL, /* no probe for protocols */
806 raw_open,
807 NULL,
808 NULL,
809 raw_close,
810 raw_create,
811 raw_flush,
813 .bdrv_aio_read = raw_aio_read,
814 .bdrv_aio_write = raw_aio_write,
815 .bdrv_aio_cancel = raw_aio_cancel,
816 .aiocb_size = sizeof(RawAIOCB),
817 .protocol_name = "file",
818 .bdrv_pread = raw_pread,
819 .bdrv_pwrite = raw_pwrite,
820 .bdrv_truncate = raw_truncate,
821 .bdrv_getlength = raw_getlength,
824 /***********************************************/
825 /* host device */
827 #ifdef CONFIG_COCOA
828 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
829 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
831 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
833 kern_return_t kernResult;
834 mach_port_t masterPort;
835 CFMutableDictionaryRef classesToMatch;
837 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
838 if ( KERN_SUCCESS != kernResult ) {
839 printf( "IOMasterPort returned %d\n", kernResult );
842 classesToMatch = IOServiceMatching( kIOCDMediaClass );
843 if ( classesToMatch == NULL ) {
844 printf( "IOServiceMatching returned a NULL dictionary.\n" );
845 } else {
846 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
848 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
849 if ( KERN_SUCCESS != kernResult )
851 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
854 return kernResult;
857 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
859 io_object_t nextMedia;
860 kern_return_t kernResult = KERN_FAILURE;
861 *bsdPath = '\0';
862 nextMedia = IOIteratorNext( mediaIterator );
863 if ( nextMedia )
865 CFTypeRef bsdPathAsCFString;
866 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
867 if ( bsdPathAsCFString ) {
868 size_t devPathLength;
869 strcpy( bsdPath, _PATH_DEV );
870 strcat( bsdPath, "r" );
871 devPathLength = strlen( bsdPath );
872 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
873 kernResult = KERN_SUCCESS;
875 CFRelease( bsdPathAsCFString );
877 IOObjectRelease( nextMedia );
880 return kernResult;
883 #endif
885 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
887 BDRVRawState *s = bs->opaque;
888 int fd, open_flags, ret;
890 #ifdef CONFIG_COCOA
891 if (strstart(filename, "/dev/cdrom", NULL)) {
892 kern_return_t kernResult;
893 io_iterator_t mediaIterator;
894 char bsdPath[ MAXPATHLEN ];
895 int fd;
897 kernResult = FindEjectableCDMedia( &mediaIterator );
898 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
900 if ( bsdPath[ 0 ] != '\0' ) {
901 strcat(bsdPath,"s0");
902 /* some CDs don't have a partition 0 */
903 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
904 if (fd < 0) {
905 bsdPath[strlen(bsdPath)-1] = '1';
906 } else {
907 close(fd);
909 filename = bsdPath;
912 if ( mediaIterator )
913 IOObjectRelease( mediaIterator );
915 #endif
916 open_flags = O_BINARY;
917 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
918 open_flags |= O_RDWR;
919 } else {
920 open_flags |= O_RDONLY;
921 bs->read_only = 1;
923 #ifdef O_DIRECT
924 if (flags & BDRV_O_DIRECT)
925 open_flags |= O_DIRECT;
926 #endif
928 s->type = FTYPE_FILE;
929 #if defined(__linux__)
930 if (strstart(filename, "/dev/cd", NULL)) {
931 /* open will not fail even if no CD is inserted */
932 open_flags |= O_NONBLOCK;
933 s->type = FTYPE_CD;
934 } else if (strstart(filename, "/dev/fd", NULL)) {
935 s->type = FTYPE_FD;
936 s->fd_open_flags = open_flags;
937 /* open will not fail even if no floppy is inserted */
938 open_flags |= O_NONBLOCK;
939 } else if (strstart(filename, "/dev/sg", NULL)) {
940 bs->sg = 1;
942 #endif
943 fd = open(filename, open_flags, 0644);
944 if (fd < 0) {
945 ret = -errno;
946 if (ret == -EROFS)
947 ret = -EACCES;
948 return ret;
950 s->fd = fd;
951 #if defined(__linux__)
952 /* close fd so that we can reopen it as needed */
953 if (s->type == FTYPE_FD) {
954 close(s->fd);
955 s->fd = -1;
956 s->fd_media_changed = 1;
958 #endif
959 return 0;
962 #if defined(__linux__) && !defined(QEMU_IMG)
964 /* Note: we do not have a reliable method to detect if the floppy is
965 present. The current method is to try to open the floppy at every
966 I/O and to keep it opened during a few hundreds of ms. */
967 static int fd_open(BlockDriverState *bs)
969 BDRVRawState *s = bs->opaque;
970 int last_media_present;
972 if (s->type != FTYPE_FD)
973 return 0;
974 last_media_present = (s->fd >= 0);
975 if (s->fd >= 0 &&
976 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
977 close(s->fd);
978 s->fd = -1;
979 #ifdef DEBUG_FLOPPY
980 printf("Floppy closed\n");
981 #endif
983 if (s->fd < 0) {
984 if (s->fd_got_error &&
985 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
986 #ifdef DEBUG_FLOPPY
987 printf("No floppy (open delayed)\n");
988 #endif
989 return -EIO;
991 s->fd = open(bs->filename, s->fd_open_flags);
992 if (s->fd < 0) {
993 s->fd_error_time = qemu_get_clock(rt_clock);
994 s->fd_got_error = 1;
995 if (last_media_present)
996 s->fd_media_changed = 1;
997 #ifdef DEBUG_FLOPPY
998 printf("No floppy\n");
999 #endif
1000 return -EIO;
1002 #ifdef DEBUG_FLOPPY
1003 printf("Floppy opened\n");
1004 #endif
1006 if (!last_media_present)
1007 s->fd_media_changed = 1;
1008 s->fd_open_time = qemu_get_clock(rt_clock);
1009 s->fd_got_error = 0;
1010 return 0;
1012 #else
1013 static int fd_open(BlockDriverState *bs)
1015 return 0;
1017 #endif
1019 #if defined(__linux__)
1021 static int raw_is_inserted(BlockDriverState *bs)
1023 BDRVRawState *s = bs->opaque;
1024 int ret;
1026 switch(s->type) {
1027 case FTYPE_CD:
1028 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1029 if (ret == CDS_DISC_OK)
1030 return 1;
1031 else
1032 return 0;
1033 break;
1034 case FTYPE_FD:
1035 ret = fd_open(bs);
1036 return (ret >= 0);
1037 default:
1038 return 1;
1042 /* currently only used by fdc.c, but a CD version would be good too */
1043 static int raw_media_changed(BlockDriverState *bs)
1045 BDRVRawState *s = bs->opaque;
1047 switch(s->type) {
1048 case FTYPE_FD:
1050 int ret;
1051 /* XXX: we do not have a true media changed indication. It
1052 does not work if the floppy is changed without trying
1053 to read it */
1054 fd_open(bs);
1055 ret = s->fd_media_changed;
1056 s->fd_media_changed = 0;
1057 #ifdef DEBUG_FLOPPY
1058 printf("Floppy changed=%d\n", ret);
1059 #endif
1060 return ret;
1062 default:
1063 return -ENOTSUP;
1067 static int raw_eject(BlockDriverState *bs, int eject_flag)
1069 BDRVRawState *s = bs->opaque;
1071 switch(s->type) {
1072 case FTYPE_CD:
1073 if (eject_flag) {
1074 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1075 perror("CDROMEJECT");
1076 } else {
1077 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1078 perror("CDROMEJECT");
1080 break;
1081 case FTYPE_FD:
1083 int fd;
1084 if (s->fd >= 0) {
1085 close(s->fd);
1086 s->fd = -1;
1088 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1089 if (fd >= 0) {
1090 if (ioctl(fd, FDEJECT, 0) < 0)
1091 perror("FDEJECT");
1092 close(fd);
1095 break;
1096 default:
1097 return -ENOTSUP;
1099 return 0;
1102 static int raw_set_locked(BlockDriverState *bs, int locked)
1104 BDRVRawState *s = bs->opaque;
1106 switch(s->type) {
1107 case FTYPE_CD:
1108 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1109 /* Note: an error can happen if the distribution automatically
1110 mounts the CD-ROM */
1111 // perror("CDROM_LOCKDOOR");
1113 break;
1114 default:
1115 return -ENOTSUP;
1117 return 0;
1120 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1122 BDRVRawState *s = bs->opaque;
1124 return ioctl(s->fd, req, buf);
1126 #else
1128 static int raw_is_inserted(BlockDriverState *bs)
1130 return 1;
1133 static int raw_media_changed(BlockDriverState *bs)
1135 return -ENOTSUP;
1138 static int raw_eject(BlockDriverState *bs, int eject_flag)
1140 return -ENOTSUP;
1143 static int raw_set_locked(BlockDriverState *bs, int locked)
1145 return -ENOTSUP;
1148 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1150 return -ENOTSUP;
1152 #endif /* !linux */
1154 BlockDriver bdrv_host_device = {
1155 "host_device",
1156 sizeof(BDRVRawState),
1157 NULL, /* no probe for protocols */
1158 hdev_open,
1159 NULL,
1160 NULL,
1161 raw_close,
1162 NULL,
1163 raw_flush,
1165 .bdrv_aio_read = raw_aio_read,
1166 .bdrv_aio_write = raw_aio_write,
1167 .bdrv_aio_cancel = raw_aio_cancel,
1168 .aiocb_size = sizeof(RawAIOCB),
1169 .bdrv_pread = raw_pread,
1170 .bdrv_pwrite = raw_pwrite,
1171 .bdrv_getlength = raw_getlength,
1173 /* removable device support */
1174 .bdrv_is_inserted = raw_is_inserted,
1175 .bdrv_media_changed = raw_media_changed,
1176 .bdrv_eject = raw_eject,
1177 .bdrv_set_locked = raw_set_locked,
1178 /* generic scsi device */
1179 .bdrv_ioctl = raw_ioctl,