Merge commit 'e9283f8b88eb6054ac032f3d9b773e80d842c0cf' into upstream-merge
[qemu-kvm/fedora.git] / block / raw-posix.c
blobc578814d8e017447202751630d37df9387fb28de
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 "module.h"
29 #include "compatfd.h"
30 #include <assert.h>
31 #ifdef CONFIG_AIO
32 #include "posix-aio-compat.h"
33 #endif
35 #ifdef CONFIG_COCOA
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
45 #endif
47 #ifdef __sun__
48 #define _POSIX_PTHREAD_SEMANTICS 1
49 #include <signal.h>
50 #include <sys/dkio.h>
51 #endif
52 #ifdef __linux__
53 #include <sys/ioctl.h>
54 #include <linux/cdrom.h>
55 #include <linux/fd.h>
56 #endif
57 #ifdef __FreeBSD__
58 #include <signal.h>
59 #include <sys/disk.h>
60 #include <sys/cdio.h>
61 #endif
63 #ifdef __OpenBSD__
64 #include <sys/ioctl.h>
65 #include <sys/disklabel.h>
66 #include <sys/dkio.h>
67 #endif
69 #ifdef __DragonFly__
70 #include <sys/ioctl.h>
71 #include <sys/diskslice.h>
72 #endif
74 //#define DEBUG_FLOPPY
76 //#define DEBUG_BLOCK
77 #if defined(DEBUG_BLOCK)
78 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
79 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
80 #else
81 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
82 #endif
84 /* OS X does not have O_DSYNC */
85 #ifndef O_DSYNC
86 #define O_DSYNC O_SYNC
87 #endif
89 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
90 #ifndef O_DIRECT
91 #define O_DIRECT O_DSYNC
92 #endif
94 #define FTYPE_FILE 0
95 #define FTYPE_CD 1
96 #define FTYPE_FD 2
98 #define ALIGNED_BUFFER_SIZE (32 * 512)
100 /* if the FD is not accessed during that time (in ms), we try to
101 reopen it to see if the disk has been changed */
102 #define FD_OPEN_TIMEOUT 1000
104 typedef struct BDRVRawState {
105 int fd;
106 int type;
107 unsigned int lseek_err_cnt;
108 int open_flags;
109 #if defined(__linux__)
110 /* linux floppy specific */
111 int64_t fd_open_time;
112 int64_t fd_error_time;
113 int fd_got_error;
114 int fd_media_changed;
115 #endif
116 uint8_t* aligned_buf;
117 } BDRVRawState;
119 static int posix_aio_init(void);
121 static int fd_open(BlockDriverState *bs);
122 static int64_t raw_getlength(BlockDriverState *bs);
124 #if defined(__FreeBSD__)
125 static int cdrom_reopen(BlockDriverState *bs);
126 #endif
128 static int raw_open_common(BlockDriverState *bs, const char *filename,
129 int bdrv_flags, int open_flags)
131 BDRVRawState *s = bs->opaque;
132 int fd, ret;
134 posix_aio_init();
136 s->lseek_err_cnt = 0;
138 s->open_flags = open_flags | O_BINARY;
139 s->open_flags &= ~O_ACCMODE;
140 if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
141 s->open_flags |= O_RDWR;
142 } else {
143 s->open_flags |= O_RDONLY;
144 bs->read_only = 1;
147 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
148 * and O_DIRECT for no caching. */
149 if ((bdrv_flags & BDRV_O_NOCACHE))
150 s->open_flags |= O_DIRECT;
151 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
152 s->open_flags |= O_DSYNC;
154 s->fd = -1;
155 fd = open(filename, s->open_flags, 0644);
156 if (fd < 0) {
157 ret = -errno;
158 if (ret == -EROFS)
159 ret = -EACCES;
160 return ret;
162 s->fd = fd;
163 s->aligned_buf = NULL;
164 if ((bdrv_flags & BDRV_O_NOCACHE)) {
165 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
166 if (s->aligned_buf == NULL) {
167 ret = -errno;
168 close(fd);
169 return ret;
172 return 0;
175 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
177 BDRVRawState *s = bs->opaque;
178 int open_flags = 0;
180 s->type = FTYPE_FILE;
181 if (flags & BDRV_O_CREAT)
182 open_flags = O_CREAT | O_TRUNC;
184 return raw_open_common(bs, filename, flags, open_flags);
187 /* XXX: use host sector size if necessary with:
188 #ifdef DIOCGSECTORSIZE
190 unsigned int sectorsize = 512;
191 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
192 sectorsize > bufsize)
193 bufsize = sectorsize;
195 #endif
196 #ifdef CONFIG_COCOA
197 u_int32_t blockSize = 512;
198 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
199 bufsize = blockSize;
201 #endif
205 * offset and count are in bytes, but must be multiples of 512 for files
206 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
208 * This function may be called without alignment if the caller ensures
209 * that O_DIRECT is not in effect.
211 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
212 uint8_t *buf, int count)
214 BDRVRawState *s = bs->opaque;
215 int ret;
217 ret = fd_open(bs);
218 if (ret < 0)
219 return ret;
221 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
222 ++(s->lseek_err_cnt);
223 if(s->lseek_err_cnt <= 10) {
224 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
225 "] lseek failed : %d = %s\n",
226 s->fd, bs->filename, offset, buf, count,
227 bs->total_sectors, errno, strerror(errno));
229 return -1;
231 s->lseek_err_cnt=0;
233 ret = read(s->fd, buf, count);
234 if (ret == count)
235 goto label__raw_read__success;
237 /* Allow reads beyond the end (needed for pwrite) */
238 if ((ret == 0) && bs->growable) {
239 int64_t size = raw_getlength(bs);
240 if (offset >= size) {
241 memset(buf, 0, count);
242 ret = count;
243 goto label__raw_read__success;
247 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
248 "] read failed %d : %d = %s\n",
249 s->fd, bs->filename, offset, buf, count,
250 bs->total_sectors, ret, errno, strerror(errno));
252 /* Try harder for CDrom. */
253 if (bs->type == BDRV_TYPE_CDROM) {
254 lseek(s->fd, offset, SEEK_SET);
255 ret = read(s->fd, buf, count);
256 if (ret == count)
257 goto label__raw_read__success;
258 lseek(s->fd, offset, SEEK_SET);
259 ret = read(s->fd, buf, count);
260 if (ret == count)
261 goto label__raw_read__success;
263 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
264 "] retry read failed %d : %d = %s\n",
265 s->fd, bs->filename, offset, buf, count,
266 bs->total_sectors, ret, errno, strerror(errno));
269 label__raw_read__success:
271 return (ret < 0) ? -errno : ret;
275 * offset and count are in bytes, but must be multiples of 512 for files
276 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
278 * This function may be called without alignment if the caller ensures
279 * that O_DIRECT is not in effect.
281 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
282 const uint8_t *buf, int count)
284 BDRVRawState *s = bs->opaque;
285 int ret;
287 ret = fd_open(bs);
288 if (ret < 0)
289 return -errno;
291 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
292 ++(s->lseek_err_cnt);
293 if(s->lseek_err_cnt) {
294 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
295 PRId64 "] lseek failed : %d = %s\n",
296 s->fd, bs->filename, offset, buf, count,
297 bs->total_sectors, errno, strerror(errno));
299 return -EIO;
301 s->lseek_err_cnt = 0;
303 ret = write(s->fd, buf, count);
304 if (ret == count)
305 goto label__raw_write__success;
307 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
308 "] write failed %d : %d = %s\n",
309 s->fd, bs->filename, offset, buf, count,
310 bs->total_sectors, ret, errno, strerror(errno));
312 label__raw_write__success:
314 return (ret < 0) ? -errno : ret;
319 * offset and count are in bytes and possibly not aligned. For files opened
320 * with O_DIRECT, necessary alignments are ensured before calling
321 * raw_pread_aligned to do the actual read.
323 static int raw_pread(BlockDriverState *bs, int64_t offset,
324 uint8_t *buf, int count)
326 BDRVRawState *s = bs->opaque;
327 int size, ret, shift, sum;
329 sum = 0;
331 if (s->aligned_buf != NULL) {
333 if (offset & 0x1ff) {
334 /* align offset on a 512 bytes boundary */
336 shift = offset & 0x1ff;
337 size = (shift + count + 0x1ff) & ~0x1ff;
338 if (size > ALIGNED_BUFFER_SIZE)
339 size = ALIGNED_BUFFER_SIZE;
340 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
341 if (ret < 0)
342 return ret;
344 size = 512 - shift;
345 if (size > count)
346 size = count;
347 memcpy(buf, s->aligned_buf + shift, size);
349 buf += size;
350 offset += size;
351 count -= size;
352 sum += size;
354 if (count == 0)
355 return sum;
357 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
359 /* read on aligned buffer */
361 while (count) {
363 size = (count + 0x1ff) & ~0x1ff;
364 if (size > ALIGNED_BUFFER_SIZE)
365 size = ALIGNED_BUFFER_SIZE;
367 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
368 if (ret < 0)
369 return ret;
371 size = ret;
372 if (size > count)
373 size = count;
375 memcpy(buf, s->aligned_buf, size);
377 buf += size;
378 offset += size;
379 count -= size;
380 sum += size;
383 return sum;
387 return raw_pread_aligned(bs, offset, buf, count) + sum;
390 static int raw_read(BlockDriverState *bs, int64_t sector_num,
391 uint8_t *buf, int nb_sectors)
393 int ret;
395 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
396 if (ret == (nb_sectors * 512))
397 ret = 0;
398 return ret;
402 * offset and count are in bytes and possibly not aligned. For files opened
403 * with O_DIRECT, necessary alignments are ensured before calling
404 * raw_pwrite_aligned to do the actual write.
406 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
407 const uint8_t *buf, int count)
409 BDRVRawState *s = bs->opaque;
410 int size, ret, shift, sum;
412 sum = 0;
414 if (s->aligned_buf != NULL) {
416 if (offset & 0x1ff) {
417 /* align offset on a 512 bytes boundary */
418 shift = offset & 0x1ff;
419 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
420 if (ret < 0)
421 return ret;
423 size = 512 - shift;
424 if (size > count)
425 size = count;
426 memcpy(s->aligned_buf + shift, buf, size);
428 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
429 if (ret < 0)
430 return ret;
432 buf += size;
433 offset += size;
434 count -= size;
435 sum += size;
437 if (count == 0)
438 return sum;
440 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
442 while ((size = (count & ~0x1ff)) != 0) {
444 if (size > ALIGNED_BUFFER_SIZE)
445 size = ALIGNED_BUFFER_SIZE;
447 memcpy(s->aligned_buf, buf, size);
449 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
450 if (ret < 0)
451 return ret;
453 buf += ret;
454 offset += ret;
455 count -= ret;
456 sum += ret;
458 /* here, count < 512 because (count & ~0x1ff) == 0 */
459 if (count) {
460 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
461 if (ret < 0)
462 return ret;
463 memcpy(s->aligned_buf, buf, count);
465 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
466 if (ret < 0)
467 return ret;
468 if (count < ret)
469 ret = count;
471 sum += ret;
473 return sum;
476 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
479 static int raw_write(BlockDriverState *bs, int64_t sector_num,
480 const uint8_t *buf, int nb_sectors)
482 int ret;
483 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
484 if (ret == (nb_sectors * 512))
485 ret = 0;
486 return ret;
489 #ifdef CONFIG_AIO
490 /***********************************************************/
491 /* Unix AIO using POSIX AIO */
493 typedef struct RawAIOCB {
494 BlockDriverAIOCB common;
495 struct qemu_paiocb aiocb;
496 struct RawAIOCB *next;
497 int ret;
498 } RawAIOCB;
500 typedef struct PosixAioState
502 int fd;
503 RawAIOCB *first_aio;
504 } PosixAioState;
506 static void posix_aio_read(void *opaque)
508 PosixAioState *s = opaque;
509 RawAIOCB *acb, **pacb;
510 int ret;
511 size_t offset;
512 union {
513 struct qemu_signalfd_siginfo siginfo;
514 char buf[128];
515 } sig;
517 /* try to read from signalfd, don't freak out if we can't read anything */
518 offset = 0;
519 while (offset < 128) {
520 ssize_t len;
522 len = read(s->fd, sig.buf + offset, 128 - offset);
523 if (len == -1 && errno == EINTR)
524 continue;
525 if (len == -1 && errno == EAGAIN) {
526 /* there is no natural reason for this to happen,
527 * so we'll spin hard until we get everything just
528 * to be on the safe side. */
529 if (offset > 0)
530 continue;
533 offset += len;
536 for(;;) {
537 pacb = &s->first_aio;
538 for(;;) {
539 acb = *pacb;
540 if (!acb)
541 goto the_end;
542 ret = qemu_paio_error(&acb->aiocb);
543 if (ret == ECANCELED) {
544 /* remove the request */
545 *pacb = acb->next;
546 qemu_aio_release(acb);
547 } else if (ret != EINPROGRESS) {
548 /* end of aio */
549 if (ret == 0) {
550 ret = qemu_paio_return(&acb->aiocb);
551 if (ret == acb->aiocb.aio_nbytes)
552 ret = 0;
553 else
554 ret = -EINVAL;
555 } else {
556 ret = -ret;
558 /* remove the request */
559 *pacb = acb->next;
560 /* call the callback */
561 acb->common.cb(acb->common.opaque, ret);
562 qemu_aio_release(acb);
563 break;
564 } else {
565 pacb = &acb->next;
569 the_end: ;
572 static int posix_aio_flush(void *opaque)
574 PosixAioState *s = opaque;
575 return !!s->first_aio;
578 static PosixAioState *posix_aio_state;
580 static int posix_aio_init(void)
582 sigset_t mask;
583 PosixAioState *s;
584 struct qemu_paioinit ai;
586 if (posix_aio_state)
587 return 0;
589 s = qemu_malloc(sizeof(PosixAioState));
591 /* Make sure to block AIO signal */
592 sigemptyset(&mask);
593 sigaddset(&mask, SIGUSR2);
594 sigprocmask(SIG_BLOCK, &mask, NULL);
596 s->first_aio = NULL;
597 s->fd = qemu_signalfd(&mask);
598 if (s->fd == -1) {
599 fprintf(stderr, "failed to create signalfd\n");
600 return -errno;
603 fcntl(s->fd, F_SETFL, O_NONBLOCK);
605 qemu_aio_set_fd_handler(s->fd, posix_aio_read, NULL, posix_aio_flush, s);
607 memset(&ai, 0, sizeof(ai));
608 ai.aio_threads = 64;
609 ai.aio_num = 64;
610 qemu_paio_init(&ai);
612 posix_aio_state = s;
614 return 0;
617 static void raw_aio_remove(RawAIOCB *acb)
619 RawAIOCB **pacb;
621 /* remove the callback from the queue */
622 pacb = &posix_aio_state->first_aio;
623 for(;;) {
624 if (*pacb == NULL) {
625 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
626 break;
627 } else if (*pacb == acb) {
628 *pacb = acb->next;
629 qemu_aio_release(acb);
630 break;
632 pacb = &(*pacb)->next;
636 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
638 int ret;
639 RawAIOCB *acb = (RawAIOCB *)blockacb;
641 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
642 if (ret == QEMU_PAIO_NOTCANCELED) {
643 /* fail safe: if the aio could not be canceled, we wait for
644 it */
645 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
648 raw_aio_remove(acb);
651 static AIOPool raw_aio_pool = {
652 .aiocb_size = sizeof(RawAIOCB),
653 .cancel = raw_aio_cancel,
656 static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,
657 QEMUIOVector *qiov, int nb_sectors,
658 BlockDriverCompletionFunc *cb, void *opaque)
660 BDRVRawState *s = bs->opaque;
661 RawAIOCB *acb;
663 if (fd_open(bs) < 0)
664 return NULL;
666 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
667 if (!acb)
668 return NULL;
669 acb->aiocb.aio_fildes = s->fd;
670 acb->aiocb.ev_signo = SIGUSR2;
671 acb->aiocb.aio_iov = qiov->iov;
672 acb->aiocb.aio_niov = qiov->niov;
673 acb->aiocb.aio_nbytes = nb_sectors * 512;
674 acb->aiocb.aio_offset = sector_num * 512;
675 acb->aiocb.aio_flags = 0;
678 * If O_DIRECT is used the buffer needs to be aligned on a sector
679 * boundary. Tell the low level code to ensure that in case it's
680 * not done yet.
682 if (s->aligned_buf)
683 acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;
685 acb->next = posix_aio_state->first_aio;
686 posix_aio_state->first_aio = acb;
687 return acb;
690 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
691 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
692 BlockDriverCompletionFunc *cb, void *opaque)
694 RawAIOCB *acb;
696 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
697 if (!acb)
698 return NULL;
699 if (qemu_paio_read(&acb->aiocb) < 0) {
700 raw_aio_remove(acb);
701 return NULL;
703 return &acb->common;
706 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
707 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
708 BlockDriverCompletionFunc *cb, void *opaque)
710 RawAIOCB *acb;
712 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
713 if (!acb)
714 return NULL;
715 if (qemu_paio_write(&acb->aiocb) < 0) {
716 raw_aio_remove(acb);
717 return NULL;
719 return &acb->common;
721 #else /* CONFIG_AIO */
722 static int posix_aio_init(void)
724 return 0;
726 #endif /* CONFIG_AIO */
729 static void raw_close(BlockDriverState *bs)
731 BDRVRawState *s = bs->opaque;
732 if (s->fd >= 0) {
733 close(s->fd);
734 s->fd = -1;
735 if (s->aligned_buf != NULL)
736 qemu_free(s->aligned_buf);
740 static int raw_truncate(BlockDriverState *bs, int64_t offset)
742 BDRVRawState *s = bs->opaque;
743 if (s->type != FTYPE_FILE)
744 return -ENOTSUP;
745 if (ftruncate(s->fd, offset) < 0)
746 return -errno;
747 return 0;
750 #ifdef __OpenBSD__
751 static int64_t raw_getlength(BlockDriverState *bs)
753 BDRVRawState *s = bs->opaque;
754 int fd = s->fd;
755 struct stat st;
757 if (fstat(fd, &st))
758 return -1;
759 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
760 struct disklabel dl;
762 if (ioctl(fd, DIOCGDINFO, &dl))
763 return -1;
764 return (uint64_t)dl.d_secsize *
765 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
766 } else
767 return st.st_size;
769 #else /* !__OpenBSD__ */
770 static int64_t raw_getlength(BlockDriverState *bs)
772 BDRVRawState *s = bs->opaque;
773 int fd = s->fd;
774 int64_t size;
775 #ifdef HOST_BSD
776 struct stat sb;
777 #ifdef __FreeBSD__
778 int reopened = 0;
779 #endif
780 #endif
781 #ifdef __sun__
782 struct dk_minfo minfo;
783 int rv;
784 #endif
785 int ret;
787 ret = fd_open(bs);
788 if (ret < 0)
789 return ret;
791 #ifdef HOST_BSD
792 #ifdef __FreeBSD__
793 again:
794 #endif
795 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
796 #ifdef DIOCGMEDIASIZE
797 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
798 #elif defined(DIOCGPART)
800 struct partinfo pi;
801 if (ioctl(fd, DIOCGPART, &pi) == 0)
802 size = pi.media_size;
803 else
804 size = 0;
806 if (size == 0)
807 #endif
808 #ifdef CONFIG_COCOA
809 size = LONG_LONG_MAX;
810 #else
811 size = lseek(fd, 0LL, SEEK_END);
812 #endif
813 #ifdef __FreeBSD__
814 switch(s->type) {
815 case FTYPE_CD:
816 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
817 if (size == 2048LL * (unsigned)-1)
818 size = 0;
819 /* XXX no disc? maybe we need to reopen... */
820 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
821 reopened = 1;
822 goto again;
825 #endif
826 } else
827 #endif
828 #ifdef __sun__
830 * use the DKIOCGMEDIAINFO ioctl to read the size.
832 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
833 if ( rv != -1 ) {
834 size = minfo.dki_lbsize * minfo.dki_capacity;
835 } else /* there are reports that lseek on some devices
836 fails, but irc discussion said that contingency
837 on contingency was overkill */
838 #endif
840 size = lseek(fd, 0, SEEK_END);
842 return size;
844 #endif
846 static int raw_create(const char *filename, QEMUOptionParameter *options)
848 int fd;
849 int64_t total_size = 0;
851 /* Read out options */
852 while (options && options->name) {
853 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
854 total_size = options->value.n / 512;
856 options++;
859 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
860 0644);
861 if (fd < 0)
862 return -EIO;
863 ftruncate(fd, total_size * 512);
864 close(fd);
865 return 0;
868 static void raw_flush(BlockDriverState *bs)
870 BDRVRawState *s = bs->opaque;
871 fsync(s->fd);
875 static QEMUOptionParameter raw_create_options[] = {
877 .name = BLOCK_OPT_SIZE,
878 .type = OPT_SIZE,
879 .help = "Virtual disk size"
881 { NULL }
884 static BlockDriver bdrv_raw = {
885 .format_name = "raw",
886 .instance_size = sizeof(BDRVRawState),
887 .bdrv_probe = NULL, /* no probe for protocols */
888 .bdrv_open = raw_open,
889 .bdrv_read = raw_read,
890 .bdrv_write = raw_write,
891 .bdrv_close = raw_close,
892 .bdrv_create = raw_create,
893 .bdrv_flush = raw_flush,
895 #ifdef CONFIG_AIO
896 .bdrv_aio_readv = raw_aio_readv,
897 .bdrv_aio_writev = raw_aio_writev,
898 #endif
900 .bdrv_truncate = raw_truncate,
901 .bdrv_getlength = raw_getlength,
903 .create_options = raw_create_options,
904 .protocol_name = "file",
907 /***********************************************/
908 /* host device */
910 #ifdef CONFIG_COCOA
911 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
912 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
914 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
916 kern_return_t kernResult;
917 mach_port_t masterPort;
918 CFMutableDictionaryRef classesToMatch;
920 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
921 if ( KERN_SUCCESS != kernResult ) {
922 printf( "IOMasterPort returned %d\n", kernResult );
925 classesToMatch = IOServiceMatching( kIOCDMediaClass );
926 if ( classesToMatch == NULL ) {
927 printf( "IOServiceMatching returned a NULL dictionary.\n" );
928 } else {
929 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
931 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
932 if ( KERN_SUCCESS != kernResult )
934 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
937 return kernResult;
940 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
942 io_object_t nextMedia;
943 kern_return_t kernResult = KERN_FAILURE;
944 *bsdPath = '\0';
945 nextMedia = IOIteratorNext( mediaIterator );
946 if ( nextMedia )
948 CFTypeRef bsdPathAsCFString;
949 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
950 if ( bsdPathAsCFString ) {
951 size_t devPathLength;
952 strcpy( bsdPath, _PATH_DEV );
953 strcat( bsdPath, "r" );
954 devPathLength = strlen( bsdPath );
955 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
956 kernResult = KERN_SUCCESS;
958 CFRelease( bsdPathAsCFString );
960 IOObjectRelease( nextMedia );
963 return kernResult;
966 #endif
968 static int hdev_probe_device(const char *filename)
970 struct stat st;
972 /* allow a dedicated CD-ROM driver to match with a higher priority */
973 if (strstart(filename, "/dev/cdrom", NULL))
974 return 50;
976 if (stat(filename, &st) >= 0 &&
977 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
978 return 100;
981 return 0;
984 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
986 BDRVRawState *s = bs->opaque;
988 #ifdef CONFIG_COCOA
989 if (strstart(filename, "/dev/cdrom", NULL)) {
990 kern_return_t kernResult;
991 io_iterator_t mediaIterator;
992 char bsdPath[ MAXPATHLEN ];
993 int fd;
995 kernResult = FindEjectableCDMedia( &mediaIterator );
996 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
998 if ( bsdPath[ 0 ] != '\0' ) {
999 strcat(bsdPath,"s0");
1000 /* some CDs don't have a partition 0 */
1001 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1002 if (fd < 0) {
1003 bsdPath[strlen(bsdPath)-1] = '1';
1004 } else {
1005 close(fd);
1007 filename = bsdPath;
1010 if ( mediaIterator )
1011 IOObjectRelease( mediaIterator );
1013 #endif
1015 s->type = FTYPE_FILE;
1016 #if defined(__linux__) && defined(CONFIG_AIO)
1017 if (strstart(filename, "/dev/sg", NULL)) {
1018 bs->sg = 1;
1020 #endif
1022 return raw_open_common(bs, filename, flags, 0);
1025 #if defined(__linux__)
1026 /* Note: we do not have a reliable method to detect if the floppy is
1027 present. The current method is to try to open the floppy at every
1028 I/O and to keep it opened during a few hundreds of ms. */
1029 static int fd_open(BlockDriverState *bs)
1031 BDRVRawState *s = bs->opaque;
1032 int last_media_present;
1034 if (s->type != FTYPE_FD)
1035 return 0;
1036 last_media_present = (s->fd >= 0);
1037 if (s->fd >= 0 &&
1038 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1039 close(s->fd);
1040 s->fd = -1;
1041 #ifdef DEBUG_FLOPPY
1042 printf("Floppy closed\n");
1043 #endif
1045 if (s->fd < 0) {
1046 if (s->fd_got_error &&
1047 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1048 #ifdef DEBUG_FLOPPY
1049 printf("No floppy (open delayed)\n");
1050 #endif
1051 return -EIO;
1053 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1054 if (s->fd < 0) {
1055 s->fd_error_time = qemu_get_clock(rt_clock);
1056 s->fd_got_error = 1;
1057 if (last_media_present)
1058 s->fd_media_changed = 1;
1059 #ifdef DEBUG_FLOPPY
1060 printf("No floppy\n");
1061 #endif
1062 return -EIO;
1064 #ifdef DEBUG_FLOPPY
1065 printf("Floppy opened\n");
1066 #endif
1068 if (!last_media_present)
1069 s->fd_media_changed = 1;
1070 s->fd_open_time = qemu_get_clock(rt_clock);
1071 s->fd_got_error = 0;
1072 return 0;
1075 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1077 BDRVRawState *s = bs->opaque;
1079 return ioctl(s->fd, req, buf);
1082 #ifdef CONFIG_AIO
1083 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1084 unsigned long int req, void *buf,
1085 BlockDriverCompletionFunc *cb, void *opaque)
1087 BDRVRawState *s = bs->opaque;
1088 RawAIOCB *acb;
1090 if (fd_open(bs) < 0)
1091 return NULL;
1093 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
1094 if (!acb)
1095 return NULL;
1096 acb->aiocb.aio_fildes = s->fd;
1097 acb->aiocb.ev_signo = SIGUSR2;
1098 acb->aiocb.aio_offset = 0;
1099 acb->aiocb.aio_flags = 0;
1101 acb->next = posix_aio_state->first_aio;
1102 posix_aio_state->first_aio = acb;
1104 acb->aiocb.aio_ioctl_buf = buf;
1105 acb->aiocb.aio_ioctl_cmd = req;
1106 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1107 raw_aio_remove(acb);
1108 return NULL;
1111 return &acb->common;
1113 #endif
1115 #elif defined(__FreeBSD__)
1116 static int fd_open(BlockDriverState *bs)
1118 BDRVRawState *s = bs->opaque;
1120 /* this is just to ensure s->fd is sane (its called by io ops) */
1121 if (s->fd >= 0)
1122 return 0;
1123 return -EIO;
1125 #else /* !linux && !FreeBSD */
1127 static int fd_open(BlockDriverState *bs)
1129 return 0;
1132 #endif /* !linux && !FreeBSD */
1134 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1136 int fd;
1137 int ret = 0;
1138 struct stat stat_buf;
1139 int64_t total_size = 0;
1141 /* Read out options */
1142 while (options && options->name) {
1143 if (!strcmp(options->name, "size")) {
1144 total_size = options->value.n / 512;
1146 options++;
1149 fd = open(filename, O_WRONLY | O_BINARY);
1150 if (fd < 0)
1151 return -EIO;
1153 if (fstat(fd, &stat_buf) < 0)
1154 ret = -EIO;
1155 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1156 ret = -EIO;
1157 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1158 ret = -ENOSPC;
1160 close(fd);
1161 return ret;
1164 static BlockDriver bdrv_host_device = {
1165 .format_name = "host_device",
1166 .instance_size = sizeof(BDRVRawState),
1167 .bdrv_probe_device = hdev_probe_device,
1168 .bdrv_open = hdev_open,
1169 .bdrv_close = raw_close,
1170 .bdrv_create = hdev_create,
1171 .bdrv_flush = raw_flush,
1173 #ifdef CONFIG_AIO
1174 .bdrv_aio_readv = raw_aio_readv,
1175 .bdrv_aio_writev = raw_aio_writev,
1176 #endif
1178 .bdrv_read = raw_read,
1179 .bdrv_write = raw_write,
1180 .bdrv_getlength = raw_getlength,
1182 /* generic scsi device */
1183 #ifdef __linux__
1184 .bdrv_ioctl = hdev_ioctl,
1185 #ifdef CONFIG_AIO
1186 .bdrv_aio_ioctl = hdev_aio_ioctl,
1187 #endif
1188 #endif
1191 #ifdef __linux__
1192 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1194 BDRVRawState *s = bs->opaque;
1195 int ret;
1197 posix_aio_init();
1199 s->type = FTYPE_FD;
1201 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1202 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1203 if (ret)
1204 return ret;
1206 /* close fd so that we can reopen it as needed */
1207 close(s->fd);
1208 s->fd = -1;
1209 s->fd_media_changed = 1;
1211 return 0;
1214 static int floppy_probe_device(const char *filename)
1216 if (strstart(filename, "/dev/fd", NULL))
1217 return 100;
1218 return 0;
1222 static int floppy_is_inserted(BlockDriverState *bs)
1224 return fd_open(bs) >= 0;
1227 static int floppy_media_changed(BlockDriverState *bs)
1229 BDRVRawState *s = bs->opaque;
1230 int ret;
1233 * XXX: we do not have a true media changed indication.
1234 * It does not work if the floppy is changed without trying to read it.
1236 fd_open(bs);
1237 ret = s->fd_media_changed;
1238 s->fd_media_changed = 0;
1239 #ifdef DEBUG_FLOPPY
1240 printf("Floppy changed=%d\n", ret);
1241 #endif
1242 return ret;
1245 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1247 BDRVRawState *s = bs->opaque;
1248 int fd;
1250 if (s->fd >= 0) {
1251 close(s->fd);
1252 s->fd = -1;
1254 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1255 if (fd >= 0) {
1256 if (ioctl(fd, FDEJECT, 0) < 0)
1257 perror("FDEJECT");
1258 close(fd);
1261 return 0;
1264 static BlockDriver bdrv_host_floppy = {
1265 .format_name = "host_floppy",
1266 .instance_size = sizeof(BDRVRawState),
1267 .bdrv_probe_device = floppy_probe_device,
1268 .bdrv_open = floppy_open,
1269 .bdrv_close = raw_close,
1270 .bdrv_create = hdev_create,
1271 .bdrv_flush = raw_flush,
1273 #ifdef CONFIG_AIO
1274 .bdrv_aio_readv = raw_aio_readv,
1275 .bdrv_aio_writev = raw_aio_writev,
1276 #endif
1278 .bdrv_read = raw_read,
1279 .bdrv_write = raw_write,
1280 .bdrv_getlength = raw_getlength,
1282 /* removable device support */
1283 .bdrv_is_inserted = floppy_is_inserted,
1284 .bdrv_media_changed = floppy_media_changed,
1285 .bdrv_eject = floppy_eject,
1288 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1290 BDRVRawState *s = bs->opaque;
1292 s->type = FTYPE_CD;
1294 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1295 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1298 static int cdrom_probe_device(const char *filename)
1300 if (strstart(filename, "/dev/cd", NULL))
1301 return 100;
1302 return 0;
1305 static int cdrom_is_inserted(BlockDriverState *bs)
1307 BDRVRawState *s = bs->opaque;
1308 int ret;
1310 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1311 if (ret == CDS_DISC_OK)
1312 return 1;
1313 return 0;
1316 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1318 BDRVRawState *s = bs->opaque;
1320 if (eject_flag) {
1321 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1322 perror("CDROMEJECT");
1323 } else {
1324 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1325 perror("CDROMEJECT");
1328 return 0;
1331 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1333 BDRVRawState *s = bs->opaque;
1335 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1337 * Note: an error can happen if the distribution automatically
1338 * mounts the CD-ROM
1340 /* perror("CDROM_LOCKDOOR"); */
1343 return 0;
1346 static BlockDriver bdrv_host_cdrom = {
1347 .format_name = "host_cdrom",
1348 .instance_size = sizeof(BDRVRawState),
1349 .bdrv_probe_device = cdrom_probe_device,
1350 .bdrv_open = cdrom_open,
1351 .bdrv_close = raw_close,
1352 .bdrv_create = hdev_create,
1353 .bdrv_flush = raw_flush,
1355 #ifdef CONFIG_AIO
1356 .bdrv_aio_readv = raw_aio_readv,
1357 .bdrv_aio_writev = raw_aio_writev,
1358 #endif
1360 .bdrv_read = raw_read,
1361 .bdrv_write = raw_write,
1362 .bdrv_getlength = raw_getlength,
1364 /* removable device support */
1365 .bdrv_is_inserted = cdrom_is_inserted,
1366 .bdrv_eject = cdrom_eject,
1367 .bdrv_set_locked = cdrom_set_locked,
1369 /* generic scsi device */
1370 .bdrv_ioctl = hdev_ioctl,
1371 #ifdef CONFIG_AIO
1372 .bdrv_aio_ioctl = hdev_aio_ioctl,
1373 #endif
1375 #endif /* __linux__ */
1377 #ifdef __FreeBSD__
1378 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1380 BDRVRawState *s = bs->opaque;
1381 int ret;
1383 s->type = FTYPE_CD;
1385 ret = raw_open_common(bs, filename, flags, 0);
1386 if (ret)
1387 return ret;
1389 /* make sure the door isnt locked at this time */
1390 ioctl(s->fd, CDIOCALLOW);
1391 return 0;
1394 static int cdrom_probe_device(const char *filename)
1396 if (strstart(filename, "/dev/cd", NULL) ||
1397 strstart(filename, "/dev/acd", NULL))
1398 return 100;
1399 return 0;
1402 static int cdrom_reopen(BlockDriverState *bs)
1404 BDRVRawState *s = bs->opaque;
1405 int fd;
1408 * Force reread of possibly changed/newly loaded disc,
1409 * FreeBSD seems to not notice sometimes...
1411 if (s->fd >= 0)
1412 close(s->fd);
1413 fd = open(bs->filename, s->open_flags, 0644);
1414 if (fd < 0) {
1415 s->fd = -1;
1416 return -EIO;
1418 s->fd = fd;
1420 /* make sure the door isnt locked at this time */
1421 ioctl(s->fd, CDIOCALLOW);
1422 return 0;
1425 static int cdrom_is_inserted(BlockDriverState *bs)
1427 return raw_getlength(bs) > 0;
1430 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1432 BDRVRawState *s = bs->opaque;
1434 if (s->fd < 0)
1435 return -ENOTSUP;
1437 (void) ioctl(s->fd, CDIOCALLOW);
1439 if (eject_flag) {
1440 if (ioctl(s->fd, CDIOCEJECT) < 0)
1441 perror("CDIOCEJECT");
1442 } else {
1443 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1444 perror("CDIOCCLOSE");
1447 if (cdrom_reopen(bs) < 0)
1448 return -ENOTSUP;
1449 return 0;
1452 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1454 BDRVRawState *s = bs->opaque;
1456 if (s->fd < 0)
1457 return -ENOTSUP;
1458 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1460 * Note: an error can happen if the distribution automatically
1461 * mounts the CD-ROM
1463 /* perror("CDROM_LOCKDOOR"); */
1466 return 0;
1469 static BlockDriver bdrv_host_cdrom = {
1470 .format_name = "host_cdrom",
1471 .instance_size = sizeof(BDRVRawState),
1472 .bdrv_probe_device = cdrom_probe_device,
1473 .bdrv_open = cdrom_open,
1474 .bdrv_close = raw_close,
1475 .bdrv_create = hdev_create,
1476 .bdrv_flush = raw_flush,
1478 #ifdef CONFIG_AIO
1479 .bdrv_aio_readv = raw_aio_readv,
1480 .bdrv_aio_writev = raw_aio_writev,
1481 #endif
1483 .bdrv_read = raw_read,
1484 .bdrv_write = raw_write,
1485 .bdrv_getlength = raw_getlength,
1487 /* removable device support */
1488 .bdrv_is_inserted = cdrom_is_inserted,
1489 .bdrv_eject = cdrom_eject,
1490 .bdrv_set_locked = cdrom_set_locked,
1492 #endif /* __FreeBSD__ */
1494 static void bdrv_raw_init(void)
1497 * Register all the drivers. Note that order is important, the driver
1498 * registered last will get probed first.
1500 bdrv_register(&bdrv_raw);
1501 bdrv_register(&bdrv_host_device);
1502 #ifdef __linux__
1503 bdrv_register(&bdrv_host_floppy);
1504 bdrv_register(&bdrv_host_cdrom);
1505 #endif
1506 #ifdef __FreeBSD__
1507 bdrv_register(&bdrv_host_cdrom);
1508 #endif
1511 block_init(bdrv_raw_init);