kvm: external module: DEBUGCTLMSR compatibility
[qemu-kvm/fedora.git] / block-raw-posix.c
blob47fd21ebf83eafc9a0ef7ea1f66245c058fc8f4d
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 #if !defined(QEMU_IMG) && !defined(QEMU_NBD)
26 #include "qemu-kvm.h"
27 #include "qemu-timer.h"
28 #include "exec-all.h"
29 #else
30 #define kvm_enabled() 0
31 #define qemu_kvm_aio_start() ((void)0)
32 #define qemu_kvm_aio_end() ((void)0)
33 #define qemu_kvm_aio_wait() ((void)0)
34 #define qemu_kvm_aio_poll() ((void)0)
35 #endif
36 #include "block_int.h"
37 #include <assert.h>
38 #include <aio.h>
40 #ifdef CONFIG_COCOA
41 #include <paths.h>
42 #include <sys/param.h>
43 #include <IOKit/IOKitLib.h>
44 #include <IOKit/IOBSD.h>
45 #include <IOKit/storage/IOMediaBSDClient.h>
46 #include <IOKit/storage/IOMedia.h>
47 #include <IOKit/storage/IOCDMedia.h>
48 //#include <IOKit/storage/IOCDTypes.h>
49 #include <CoreFoundation/CoreFoundation.h>
50 #endif
52 #ifdef __sun__
53 #define _POSIX_PTHREAD_SEMANTICS 1
54 #include <signal.h>
55 #include <sys/dkio.h>
56 #endif
57 #ifdef __linux__
58 #include <sys/ioctl.h>
59 #include <linux/cdrom.h>
60 #include <linux/fd.h>
61 #endif
62 #ifdef __FreeBSD__
63 #include <sys/disk.h>
64 #endif
66 //#define DEBUG_FLOPPY
68 //#define DEBUG_BLOCK
69 #if defined(DEBUG_BLOCK) && !defined(QEMU_IMG) && !defined(QEMU_NBD)
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 #define FTYPE_FILE 0
77 #define FTYPE_CD 1
78 #define FTYPE_FD 2
80 #define ALIGNED_BUFFER_SIZE (32 * 512)
82 /* if the FD is not accessed during that time (in ms), we try to
83 reopen it to see if the disk has been changed */
84 #define FD_OPEN_TIMEOUT 1000
86 typedef struct BDRVRawState {
87 int fd;
88 int type;
89 unsigned int lseek_err_cnt;
90 #if defined(__linux__)
91 /* linux floppy specific */
92 int fd_open_flags;
93 int64_t fd_open_time;
94 int64_t fd_error_time;
95 int fd_got_error;
96 int fd_media_changed;
97 #endif
98 #if defined(O_DIRECT) && !defined(QEMU_IMG)
99 uint8_t* aligned_buf;
100 #endif
101 } BDRVRawState;
103 static int fd_open(BlockDriverState *bs);
105 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
107 BDRVRawState *s = bs->opaque;
108 int fd, open_flags, ret;
110 s->lseek_err_cnt = 0;
112 open_flags = O_BINARY;
113 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
114 open_flags |= O_RDWR;
115 } else {
116 open_flags |= O_RDONLY;
117 bs->read_only = 1;
119 if (flags & BDRV_O_CREAT)
120 open_flags |= O_CREAT | O_TRUNC;
121 #ifdef O_DIRECT
122 if (flags & BDRV_O_DIRECT)
123 open_flags |= O_DIRECT;
124 #endif
126 s->type = FTYPE_FILE;
128 fd = open(filename, open_flags, 0644);
129 if (fd < 0) {
130 ret = -errno;
131 if (ret == -EROFS)
132 ret = -EACCES;
133 return ret;
135 s->fd = fd;
136 #if defined(O_DIRECT) && !defined(QEMU_IMG)
137 s->aligned_buf = NULL;
138 if (flags & BDRV_O_DIRECT) {
139 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
140 if (s->aligned_buf == NULL) {
141 ret = -errno;
142 close(fd);
143 return ret;
146 #endif
147 return 0;
150 /* XXX: use host sector size if necessary with:
151 #ifdef DIOCGSECTORSIZE
153 unsigned int sectorsize = 512;
154 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
155 sectorsize > bufsize)
156 bufsize = sectorsize;
158 #endif
159 #ifdef CONFIG_COCOA
160 u_int32_t blockSize = 512;
161 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
162 bufsize = blockSize;
164 #endif
168 * offset and count are in bytes, but must be multiples of 512 for files
169 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
171 * This function may be called without alignment if the caller ensures
172 * that O_DIRECT is not in effect.
174 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
175 uint8_t *buf, int count)
177 BDRVRawState *s = bs->opaque;
178 int ret;
180 ret = fd_open(bs);
181 if (ret < 0)
182 return ret;
184 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
185 ++(s->lseek_err_cnt);
186 if(s->lseek_err_cnt <= 10) {
187 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
188 "] lseek failed : %d = %s\n",
189 s->fd, bs->filename, offset, buf, count,
190 bs->total_sectors, errno, strerror(errno));
192 return -1;
194 s->lseek_err_cnt=0;
196 ret = read(s->fd, buf, count);
197 if (ret == count)
198 goto label__raw_read__success;
200 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
201 "] read failed %d : %d = %s\n",
202 s->fd, bs->filename, offset, buf, count,
203 bs->total_sectors, ret, errno, strerror(errno));
205 /* Try harder for CDrom. */
206 if (bs->type == BDRV_TYPE_CDROM) {
207 lseek(s->fd, offset, SEEK_SET);
208 ret = read(s->fd, buf, count);
209 if (ret == count)
210 goto label__raw_read__success;
211 lseek(s->fd, offset, SEEK_SET);
212 ret = read(s->fd, buf, count);
213 if (ret == count)
214 goto label__raw_read__success;
216 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
217 "] retry read failed %d : %d = %s\n",
218 s->fd, bs->filename, offset, buf, count,
219 bs->total_sectors, ret, errno, strerror(errno));
222 label__raw_read__success:
224 return ret;
228 * offset and count are in bytes, but must be multiples of 512 for files
229 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
231 * This function may be called without alignment if the caller ensures
232 * that O_DIRECT is not in effect.
234 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
235 const uint8_t *buf, int count)
237 BDRVRawState *s = bs->opaque;
238 int ret;
240 ret = fd_open(bs);
241 if (ret < 0)
242 return ret;
244 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
245 ++(s->lseek_err_cnt);
246 if(s->lseek_err_cnt) {
247 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
248 PRId64 "] lseek failed : %d = %s\n",
249 s->fd, bs->filename, offset, buf, count,
250 bs->total_sectors, errno, strerror(errno));
252 return -1;
254 s->lseek_err_cnt = 0;
256 ret = write(s->fd, buf, count);
257 if (ret == count)
258 goto label__raw_write__success;
260 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
261 "] write failed %d : %d = %s\n",
262 s->fd, bs->filename, offset, buf, count,
263 bs->total_sectors, ret, errno, strerror(errno));
265 label__raw_write__success:
267 return ret;
271 #if defined(O_DIRECT) && !defined(QEMU_IMG)
273 * offset and count are in bytes and possibly not aligned. For files opened
274 * with O_DIRECT, necessary alignments are ensured before calling
275 * raw_pread_aligned to do the actual read.
277 static int raw_pread(BlockDriverState *bs, int64_t offset,
278 uint8_t *buf, int count)
280 BDRVRawState *s = bs->opaque;
281 int size, ret, shift, sum;
283 sum = 0;
285 if (s->aligned_buf != NULL) {
287 if (offset & 0x1ff) {
288 /* align offset on a 512 bytes boundary */
290 shift = offset & 0x1ff;
291 size = (shift + count + 0x1ff) & ~0x1ff;
292 if (size > ALIGNED_BUFFER_SIZE)
293 size = ALIGNED_BUFFER_SIZE;
294 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
295 if (ret < 0)
296 return ret;
298 size = 512 - shift;
299 if (size > count)
300 size = count;
301 memcpy(buf, s->aligned_buf + shift, size);
303 buf += size;
304 offset += size;
305 count -= size;
306 sum += size;
308 if (count == 0)
309 return sum;
311 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
313 /* read on aligned buffer */
315 while (count) {
317 size = (count + 0x1ff) & ~0x1ff;
318 if (size > ALIGNED_BUFFER_SIZE)
319 size = ALIGNED_BUFFER_SIZE;
321 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
322 if (ret < 0)
323 return ret;
325 size = ret;
326 if (size > count)
327 size = count;
329 memcpy(buf, s->aligned_buf, size);
331 buf += size;
332 offset += size;
333 count -= size;
334 sum += size;
337 return sum;
341 return raw_pread_aligned(bs, offset, buf, count) + sum;
345 * offset and count are in bytes and possibly not aligned. For files opened
346 * with O_DIRECT, necessary alignments are ensured before calling
347 * raw_pwrite_aligned to do the actual write.
349 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
350 const uint8_t *buf, int count)
352 BDRVRawState *s = bs->opaque;
353 int size, ret, shift, sum;
355 sum = 0;
357 if (s->aligned_buf != NULL) {
359 if (offset & 0x1ff) {
360 /* align offset on a 512 bytes boundary */
361 shift = offset & 0x1ff;
362 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
363 if (ret < 0)
364 return ret;
366 size = 512 - shift;
367 if (size > count)
368 size = count;
369 memcpy(s->aligned_buf + shift, buf, size);
371 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
372 if (ret < 0)
373 return ret;
375 buf += size;
376 offset += size;
377 count -= size;
378 sum += size;
380 if (count == 0)
381 return sum;
383 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
385 while ((size = (count & ~0x1ff)) != 0) {
387 if (size > ALIGNED_BUFFER_SIZE)
388 size = ALIGNED_BUFFER_SIZE;
390 memcpy(s->aligned_buf, buf, size);
392 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
393 if (ret < 0)
394 return ret;
396 buf += ret;
397 offset += ret;
398 count -= ret;
399 sum += ret;
401 /* here, count < 512 because (count & ~0x1ff) == 0 */
402 if (count) {
403 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
404 if (ret < 0)
405 return ret;
406 memcpy(s->aligned_buf, buf, count);
408 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
409 if (ret < 0)
410 return ret;
411 if (count < ret)
412 ret = count;
414 sum += ret;
416 return sum;
419 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
422 #else
423 #define raw_pread raw_pread_aligned
424 #define raw_pwrite raw_pwrite_aligned
425 #endif
428 /***********************************************************/
429 /* Unix AIO using POSIX AIO */
431 typedef struct RawAIOCB {
432 BlockDriverAIOCB common;
433 struct aiocb aiocb;
434 struct RawAIOCB *next;
435 int ret;
436 } RawAIOCB;
438 static int aio_sig_num = SIGUSR2;
439 static RawAIOCB *first_aio; /* AIO issued */
440 static int aio_initialized = 0;
442 static void aio_signal_handler(int signum)
444 #if !defined(QEMU_IMG) && !defined(QEMU_NBD)
445 CPUState *env = cpu_single_env;
446 if (env) {
447 /* stop the currently executing cpu because a timer occured */
448 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
449 #ifdef USE_KQEMU
450 if (env->kqemu_enabled) {
451 kqemu_cpu_interrupt(env);
453 #endif
455 #endif
458 void qemu_aio_init(void)
460 struct sigaction act;
462 aio_initialized = 1;
464 sigfillset(&act.sa_mask);
465 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
466 act.sa_handler = aio_signal_handler;
467 sigaction(aio_sig_num, &act, NULL);
469 #if defined(__GLIBC__) && defined(__linux__)
471 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
472 seems to fix the problem. */
473 struct aioinit ai;
474 memset(&ai, 0, sizeof(ai));
475 ai.aio_threads = 1;
476 ai.aio_num = 1;
477 ai.aio_idle_time = 365 * 100000;
478 aio_init(&ai);
480 #endif
483 void qemu_aio_poll(void)
485 RawAIOCB *acb, **pacb;
486 int ret;
488 for(;;) {
489 pacb = &first_aio;
490 for(;;) {
491 acb = *pacb;
492 if (!acb)
493 goto the_end;
494 ret = aio_error(&acb->aiocb);
495 if (ret == ECANCELED) {
496 /* remove the request */
497 *pacb = acb->next;
498 qemu_aio_release(acb);
499 } else if (ret != EINPROGRESS) {
500 /* end of aio */
501 if (ret == 0) {
502 ret = aio_return(&acb->aiocb);
503 if (ret == acb->aiocb.aio_nbytes)
504 ret = 0;
505 else
506 ret = -EINVAL;
507 } else {
508 ret = -ret;
510 /* remove the request */
511 *pacb = acb->next;
512 /* call the callback */
513 acb->common.cb(acb->common.opaque, ret);
514 qemu_aio_release(acb);
515 break;
516 } else {
517 pacb = &acb->next;
521 the_end: ;
524 /* Wait for all IO requests to complete. */
525 void qemu_aio_flush(void)
527 qemu_aio_wait_start();
528 qemu_aio_poll();
529 while (first_aio) {
530 qemu_aio_wait();
532 qemu_aio_wait_end();
535 /* wait until at least one AIO was handled */
536 static sigset_t wait_oset;
538 void qemu_aio_wait_start(void)
540 sigset_t set;
542 if (!aio_initialized)
543 qemu_aio_init();
544 #ifndef QEMU_IMG
545 if (kvm_enabled()) {
546 qemu_kvm_aio_wait_start();
547 return;
549 #endif
550 sigemptyset(&set);
551 sigaddset(&set, aio_sig_num);
552 sigprocmask(SIG_BLOCK, &set, &wait_oset);
555 void qemu_aio_wait(void)
557 sigset_t set;
558 int nb_sigs;
560 #if !defined(QEMU_IMG) && !defined(QEMU_NBD)
561 if (qemu_bh_poll())
562 return;
563 if (kvm_enabled()) {
564 qemu_kvm_aio_wait();
565 qemu_aio_poll();
566 return;
568 #endif
569 sigemptyset(&set);
570 sigaddset(&set, aio_sig_num);
571 sigwait(&set, &nb_sigs);
572 qemu_aio_poll();
575 void qemu_aio_wait_end(void)
577 #ifndef QEMU_IMG
578 if (kvm_enabled()) {
579 qemu_kvm_aio_wait_end();
580 return;
582 #endif
583 sigprocmask(SIG_SETMASK, &wait_oset, NULL);
586 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
587 int64_t sector_num, uint8_t *buf, int nb_sectors,
588 BlockDriverCompletionFunc *cb, void *opaque)
590 BDRVRawState *s = bs->opaque;
591 RawAIOCB *acb;
593 if (fd_open(bs) < 0)
594 return NULL;
596 acb = qemu_aio_get(bs, cb, opaque);
597 if (!acb)
598 return NULL;
599 acb->aiocb.aio_fildes = s->fd;
600 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
601 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
602 acb->aiocb.aio_buf = buf;
603 if (nb_sectors < 0)
604 acb->aiocb.aio_nbytes = -nb_sectors;
605 else
606 acb->aiocb.aio_nbytes = nb_sectors * 512;
607 acb->aiocb.aio_offset = sector_num * 512;
608 acb->next = first_aio;
609 first_aio = acb;
610 return acb;
613 #if !defined(QEMU_IMG) && !defined(QEMU_NBD)
614 static void raw_aio_em_cb(void* opaque)
616 RawAIOCB *acb = opaque;
617 acb->common.cb(acb->common.opaque, acb->ret);
618 qemu_aio_release(acb);
620 #endif
622 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
623 int64_t sector_num, uint8_t *buf, int nb_sectors,
624 BlockDriverCompletionFunc *cb, void *opaque)
626 RawAIOCB *acb;
629 * If O_DIRECT is used and the buffer is not aligned fall back
630 * to synchronous IO.
632 #if defined(O_DIRECT) && !defined(QEMU_IMG) && !defined(QEMU_NBD)
633 BDRVRawState *s = bs->opaque;
635 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
636 QEMUBH *bh;
637 acb = qemu_aio_get(bs, cb, opaque);
638 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
639 bh = qemu_bh_new(raw_aio_em_cb, acb);
640 qemu_bh_schedule(bh);
641 return &acb->common;
643 #endif
645 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
646 if (!acb)
647 return NULL;
648 if (aio_read(&acb->aiocb) < 0) {
649 qemu_aio_release(acb);
650 return NULL;
652 return &acb->common;
655 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
656 int64_t sector_num, const uint8_t *buf, int nb_sectors,
657 BlockDriverCompletionFunc *cb, void *opaque)
659 RawAIOCB *acb;
662 * If O_DIRECT is used and the buffer is not aligned fall back
663 * to synchronous IO.
665 #if defined(O_DIRECT) && !defined(QEMU_IMG) && !defined(QEMU_NBD)
666 BDRVRawState *s = bs->opaque;
668 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
669 QEMUBH *bh;
670 acb = qemu_aio_get(bs, cb, opaque);
671 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
672 bh = qemu_bh_new(raw_aio_em_cb, acb);
673 qemu_bh_schedule(bh);
674 return &acb->common;
676 #endif
678 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
679 if (!acb)
680 return NULL;
681 if (aio_write(&acb->aiocb) < 0) {
682 qemu_aio_release(acb);
683 return NULL;
685 return &acb->common;
688 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
690 int ret;
691 RawAIOCB *acb = (RawAIOCB *)blockacb;
692 RawAIOCB **pacb;
694 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
695 if (ret == AIO_NOTCANCELED) {
696 /* fail safe: if the aio could not be canceled, we wait for
697 it */
698 while (aio_error(&acb->aiocb) == EINPROGRESS);
701 /* remove the callback from the queue */
702 pacb = &first_aio;
703 for(;;) {
704 if (*pacb == NULL) {
705 break;
706 } else if (*pacb == acb) {
707 *pacb = acb->next;
708 qemu_aio_release(acb);
709 break;
711 pacb = &acb->next;
715 static void raw_close(BlockDriverState *bs)
717 BDRVRawState *s = bs->opaque;
718 if (s->fd >= 0) {
719 close(s->fd);
720 s->fd = -1;
721 #if defined(O_DIRECT) && !defined(QEMU_IMG)
722 if (s->aligned_buf != NULL)
723 qemu_free(s->aligned_buf);
724 #endif
728 static int raw_truncate(BlockDriverState *bs, int64_t offset)
730 BDRVRawState *s = bs->opaque;
731 if (s->type != FTYPE_FILE)
732 return -ENOTSUP;
733 if (ftruncate(s->fd, offset) < 0)
734 return -errno;
735 return 0;
738 static int64_t raw_getlength(BlockDriverState *bs)
740 BDRVRawState *s = bs->opaque;
741 int fd = s->fd;
742 int64_t size;
743 #ifdef _BSD
744 struct stat sb;
745 #endif
746 #ifdef __sun__
747 struct dk_minfo minfo;
748 int rv;
749 #endif
750 int ret;
752 ret = fd_open(bs);
753 if (ret < 0)
754 return ret;
756 #ifdef _BSD
757 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
758 #ifdef DIOCGMEDIASIZE
759 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
760 #endif
761 #ifdef CONFIG_COCOA
762 size = LONG_LONG_MAX;
763 #else
764 size = lseek(fd, 0LL, SEEK_END);
765 #endif
766 } else
767 #endif
768 #ifdef __sun__
770 * use the DKIOCGMEDIAINFO ioctl to read the size.
772 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
773 if ( rv != -1 ) {
774 size = minfo.dki_lbsize * minfo.dki_capacity;
775 } else /* there are reports that lseek on some devices
776 fails, but irc discussion said that contingency
777 on contingency was overkill */
778 #endif
780 size = lseek(fd, 0, SEEK_END);
782 return size;
785 static int raw_create(const char *filename, int64_t total_size,
786 const char *backing_file, int flags)
788 int fd;
790 if (flags || backing_file)
791 return -ENOTSUP;
793 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
794 0644);
795 if (fd < 0)
796 return -EIO;
797 ftruncate(fd, total_size * 512);
798 close(fd);
799 return 0;
802 static void raw_flush(BlockDriverState *bs)
804 BDRVRawState *s = bs->opaque;
805 fsync(s->fd);
808 BlockDriver bdrv_raw = {
809 "raw",
810 sizeof(BDRVRawState),
811 NULL, /* no probe for protocols */
812 raw_open,
813 NULL,
814 NULL,
815 raw_close,
816 raw_create,
817 raw_flush,
819 .bdrv_aio_read = raw_aio_read,
820 .bdrv_aio_write = raw_aio_write,
821 .bdrv_aio_cancel = raw_aio_cancel,
822 .aiocb_size = sizeof(RawAIOCB),
823 .protocol_name = "file",
824 .bdrv_pread = raw_pread,
825 .bdrv_pwrite = raw_pwrite,
826 .bdrv_truncate = raw_truncate,
827 .bdrv_getlength = raw_getlength,
830 /***********************************************/
831 /* host device */
833 #ifdef CONFIG_COCOA
834 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
835 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
837 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
839 kern_return_t kernResult;
840 mach_port_t masterPort;
841 CFMutableDictionaryRef classesToMatch;
843 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
844 if ( KERN_SUCCESS != kernResult ) {
845 printf( "IOMasterPort returned %d\n", kernResult );
848 classesToMatch = IOServiceMatching( kIOCDMediaClass );
849 if ( classesToMatch == NULL ) {
850 printf( "IOServiceMatching returned a NULL dictionary.\n" );
851 } else {
852 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
854 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
855 if ( KERN_SUCCESS != kernResult )
857 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
860 return kernResult;
863 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
865 io_object_t nextMedia;
866 kern_return_t kernResult = KERN_FAILURE;
867 *bsdPath = '\0';
868 nextMedia = IOIteratorNext( mediaIterator );
869 if ( nextMedia )
871 CFTypeRef bsdPathAsCFString;
872 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
873 if ( bsdPathAsCFString ) {
874 size_t devPathLength;
875 strcpy( bsdPath, _PATH_DEV );
876 strcat( bsdPath, "r" );
877 devPathLength = strlen( bsdPath );
878 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
879 kernResult = KERN_SUCCESS;
881 CFRelease( bsdPathAsCFString );
883 IOObjectRelease( nextMedia );
886 return kernResult;
889 #endif
891 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
893 BDRVRawState *s = bs->opaque;
894 int fd, open_flags, ret;
896 #ifdef CONFIG_COCOA
897 if (strstart(filename, "/dev/cdrom", NULL)) {
898 kern_return_t kernResult;
899 io_iterator_t mediaIterator;
900 char bsdPath[ MAXPATHLEN ];
901 int fd;
903 kernResult = FindEjectableCDMedia( &mediaIterator );
904 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
906 if ( bsdPath[ 0 ] != '\0' ) {
907 strcat(bsdPath,"s0");
908 /* some CDs don't have a partition 0 */
909 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
910 if (fd < 0) {
911 bsdPath[strlen(bsdPath)-1] = '1';
912 } else {
913 close(fd);
915 filename = bsdPath;
918 if ( mediaIterator )
919 IOObjectRelease( mediaIterator );
921 #endif
922 open_flags = O_BINARY;
923 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
924 open_flags |= O_RDWR;
925 } else {
926 open_flags |= O_RDONLY;
927 bs->read_only = 1;
929 #ifdef O_DIRECT
930 if (flags & BDRV_O_DIRECT)
931 open_flags |= O_DIRECT;
932 #endif
934 s->type = FTYPE_FILE;
935 #if defined(__linux__)
936 if (strstart(filename, "/dev/cd", NULL)) {
937 /* open will not fail even if no CD is inserted */
938 open_flags |= O_NONBLOCK;
939 s->type = FTYPE_CD;
940 } else if (strstart(filename, "/dev/fd", NULL)) {
941 s->type = FTYPE_FD;
942 s->fd_open_flags = open_flags;
943 /* open will not fail even if no floppy is inserted */
944 open_flags |= O_NONBLOCK;
945 } else if (strstart(filename, "/dev/sg", NULL)) {
946 bs->sg = 1;
948 #endif
949 fd = open(filename, open_flags, 0644);
950 if (fd < 0) {
951 ret = -errno;
952 if (ret == -EROFS)
953 ret = -EACCES;
954 return ret;
956 s->fd = fd;
957 #if defined(__linux__)
958 /* close fd so that we can reopen it as needed */
959 if (s->type == FTYPE_FD) {
960 close(s->fd);
961 s->fd = -1;
962 s->fd_media_changed = 1;
964 #endif
965 return 0;
968 #if defined(__linux__) && !defined(QEMU_IMG) && !defined(QEMU_NBD)
970 /* Note: we do not have a reliable method to detect if the floppy is
971 present. The current method is to try to open the floppy at every
972 I/O and to keep it opened during a few hundreds of ms. */
973 static int fd_open(BlockDriverState *bs)
975 BDRVRawState *s = bs->opaque;
976 int last_media_present;
978 if (s->type != FTYPE_FD)
979 return 0;
980 last_media_present = (s->fd >= 0);
981 if (s->fd >= 0 &&
982 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
983 close(s->fd);
984 s->fd = -1;
985 #ifdef DEBUG_FLOPPY
986 printf("Floppy closed\n");
987 #endif
989 if (s->fd < 0) {
990 if (s->fd_got_error &&
991 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
992 #ifdef DEBUG_FLOPPY
993 printf("No floppy (open delayed)\n");
994 #endif
995 return -EIO;
997 s->fd = open(bs->filename, s->fd_open_flags);
998 if (s->fd < 0) {
999 s->fd_error_time = qemu_get_clock(rt_clock);
1000 s->fd_got_error = 1;
1001 if (last_media_present)
1002 s->fd_media_changed = 1;
1003 #ifdef DEBUG_FLOPPY
1004 printf("No floppy\n");
1005 #endif
1006 return -EIO;
1008 #ifdef DEBUG_FLOPPY
1009 printf("Floppy opened\n");
1010 #endif
1012 if (!last_media_present)
1013 s->fd_media_changed = 1;
1014 s->fd_open_time = qemu_get_clock(rt_clock);
1015 s->fd_got_error = 0;
1016 return 0;
1018 #else
1019 static int fd_open(BlockDriverState *bs)
1021 return 0;
1023 #endif
1025 #if defined(__linux__)
1027 static int raw_is_inserted(BlockDriverState *bs)
1029 BDRVRawState *s = bs->opaque;
1030 int ret;
1032 switch(s->type) {
1033 case FTYPE_CD:
1034 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1035 if (ret == CDS_DISC_OK)
1036 return 1;
1037 else
1038 return 0;
1039 break;
1040 case FTYPE_FD:
1041 ret = fd_open(bs);
1042 return (ret >= 0);
1043 default:
1044 return 1;
1048 /* currently only used by fdc.c, but a CD version would be good too */
1049 static int raw_media_changed(BlockDriverState *bs)
1051 BDRVRawState *s = bs->opaque;
1053 switch(s->type) {
1054 case FTYPE_FD:
1056 int ret;
1057 /* XXX: we do not have a true media changed indication. It
1058 does not work if the floppy is changed without trying
1059 to read it */
1060 fd_open(bs);
1061 ret = s->fd_media_changed;
1062 s->fd_media_changed = 0;
1063 #ifdef DEBUG_FLOPPY
1064 printf("Floppy changed=%d\n", ret);
1065 #endif
1066 return ret;
1068 default:
1069 return -ENOTSUP;
1073 static int raw_eject(BlockDriverState *bs, int eject_flag)
1075 BDRVRawState *s = bs->opaque;
1077 switch(s->type) {
1078 case FTYPE_CD:
1079 if (eject_flag) {
1080 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1081 perror("CDROMEJECT");
1082 } else {
1083 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1084 perror("CDROMEJECT");
1086 break;
1087 case FTYPE_FD:
1089 int fd;
1090 if (s->fd >= 0) {
1091 close(s->fd);
1092 s->fd = -1;
1094 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1095 if (fd >= 0) {
1096 if (ioctl(fd, FDEJECT, 0) < 0)
1097 perror("FDEJECT");
1098 close(fd);
1101 break;
1102 default:
1103 return -ENOTSUP;
1105 return 0;
1108 static int raw_set_locked(BlockDriverState *bs, int locked)
1110 BDRVRawState *s = bs->opaque;
1112 switch(s->type) {
1113 case FTYPE_CD:
1114 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1115 /* Note: an error can happen if the distribution automatically
1116 mounts the CD-ROM */
1117 // perror("CDROM_LOCKDOOR");
1119 break;
1120 default:
1121 return -ENOTSUP;
1123 return 0;
1126 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1128 BDRVRawState *s = bs->opaque;
1130 return ioctl(s->fd, req, buf);
1132 #else
1134 static int raw_is_inserted(BlockDriverState *bs)
1136 return 1;
1139 static int raw_media_changed(BlockDriverState *bs)
1141 return -ENOTSUP;
1144 static int raw_eject(BlockDriverState *bs, int eject_flag)
1146 return -ENOTSUP;
1149 static int raw_set_locked(BlockDriverState *bs, int locked)
1151 return -ENOTSUP;
1154 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1156 return -ENOTSUP;
1158 #endif /* !linux */
1160 BlockDriver bdrv_host_device = {
1161 "host_device",
1162 sizeof(BDRVRawState),
1163 NULL, /* no probe for protocols */
1164 hdev_open,
1165 NULL,
1166 NULL,
1167 raw_close,
1168 NULL,
1169 raw_flush,
1171 .bdrv_aio_read = raw_aio_read,
1172 .bdrv_aio_write = raw_aio_write,
1173 .bdrv_aio_cancel = raw_aio_cancel,
1174 .aiocb_size = sizeof(RawAIOCB),
1175 .bdrv_pread = raw_pread,
1176 .bdrv_pwrite = raw_pwrite,
1177 .bdrv_getlength = raw_getlength,
1179 /* removable device support */
1180 .bdrv_is_inserted = raw_is_inserted,
1181 .bdrv_media_changed = raw_media_changed,
1182 .bdrv_eject = raw_eject,
1183 .bdrv_set_locked = raw_set_locked,
1184 /* generic scsi device */
1185 .bdrv_ioctl = raw_ioctl,