Merge commit '9538749118d47dfcd3ed45804736027d87ec054e' into upstream-merge
[qemu-kvm/fedora.git] / block / raw-posix.c
blob55ac4f1df63fc5a8fa5f0a5378a5fe07dcf33a4c
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 #ifdef O_SYNC
87 #define O_DSYNC O_SYNC
88 #elif defined(O_FSYNC)
89 #define O_DSYNC O_FSYNC
90 #endif
91 #endif
93 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
94 #ifndef O_DIRECT
95 #define O_DIRECT O_DSYNC
96 #endif
98 #define FTYPE_FILE 0
99 #define FTYPE_CD 1
100 #define FTYPE_FD 2
102 #define ALIGNED_BUFFER_SIZE (32 * 512)
104 /* if the FD is not accessed during that time (in ms), we try to
105 reopen it to see if the disk has been changed */
106 #define FD_OPEN_TIMEOUT 1000
108 typedef struct BDRVRawState {
109 int fd;
110 int type;
111 unsigned int lseek_err_cnt;
112 int open_flags;
113 #if defined(__linux__)
114 /* linux floppy specific */
115 int64_t fd_open_time;
116 int64_t fd_error_time;
117 int fd_got_error;
118 int fd_media_changed;
119 #endif
120 uint8_t* aligned_buf;
121 } BDRVRawState;
123 static int posix_aio_init(void);
125 static int fd_open(BlockDriverState *bs);
126 static int64_t raw_getlength(BlockDriverState *bs);
128 #if defined(__FreeBSD__)
129 static int cdrom_reopen(BlockDriverState *bs);
130 #endif
132 static int raw_open_common(BlockDriverState *bs, const char *filename,
133 int bdrv_flags, int open_flags)
135 BDRVRawState *s = bs->opaque;
136 int fd, ret;
138 posix_aio_init();
140 s->lseek_err_cnt = 0;
142 s->open_flags = open_flags | O_BINARY;
143 s->open_flags &= ~O_ACCMODE;
144 if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
145 s->open_flags |= O_RDWR;
146 } else {
147 s->open_flags |= O_RDONLY;
148 bs->read_only = 1;
151 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
152 * and O_DIRECT for no caching. */
153 if ((bdrv_flags & BDRV_O_NOCACHE))
154 s->open_flags |= O_DIRECT;
155 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
156 s->open_flags |= O_DSYNC;
158 s->fd = -1;
159 fd = open(filename, s->open_flags, 0644);
160 if (fd < 0) {
161 ret = -errno;
162 if (ret == -EROFS)
163 ret = -EACCES;
164 return ret;
166 s->fd = fd;
167 s->aligned_buf = NULL;
168 if ((bdrv_flags & BDRV_O_NOCACHE)) {
169 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
170 if (s->aligned_buf == NULL) {
171 ret = -errno;
172 close(fd);
173 return ret;
176 return 0;
179 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
181 BDRVRawState *s = bs->opaque;
182 int open_flags = 0;
184 s->type = FTYPE_FILE;
185 if (flags & BDRV_O_CREAT)
186 open_flags = O_CREAT | O_TRUNC;
188 return raw_open_common(bs, filename, flags, open_flags);
191 /* XXX: use host sector size if necessary with:
192 #ifdef DIOCGSECTORSIZE
194 unsigned int sectorsize = 512;
195 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
196 sectorsize > bufsize)
197 bufsize = sectorsize;
199 #endif
200 #ifdef CONFIG_COCOA
201 u_int32_t blockSize = 512;
202 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
203 bufsize = blockSize;
205 #endif
209 * offset and count are in bytes, but must be multiples of 512 for files
210 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
212 * This function may be called without alignment if the caller ensures
213 * that O_DIRECT is not in effect.
215 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
216 uint8_t *buf, int count)
218 BDRVRawState *s = bs->opaque;
219 int ret;
221 ret = fd_open(bs);
222 if (ret < 0)
223 return ret;
225 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
226 ++(s->lseek_err_cnt);
227 if(s->lseek_err_cnt <= 10) {
228 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
229 "] lseek failed : %d = %s\n",
230 s->fd, bs->filename, offset, buf, count,
231 bs->total_sectors, errno, strerror(errno));
233 return -1;
235 s->lseek_err_cnt=0;
237 ret = read(s->fd, buf, count);
238 if (ret == count)
239 goto label__raw_read__success;
241 /* Allow reads beyond the end (needed for pwrite) */
242 if ((ret == 0) && bs->growable) {
243 int64_t size = raw_getlength(bs);
244 if (offset >= size) {
245 memset(buf, 0, count);
246 ret = count;
247 goto label__raw_read__success;
251 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
252 "] read failed %d : %d = %s\n",
253 s->fd, bs->filename, offset, buf, count,
254 bs->total_sectors, ret, errno, strerror(errno));
256 /* Try harder for CDrom. */
257 if (bs->type == BDRV_TYPE_CDROM) {
258 lseek(s->fd, offset, SEEK_SET);
259 ret = read(s->fd, buf, count);
260 if (ret == count)
261 goto label__raw_read__success;
262 lseek(s->fd, offset, SEEK_SET);
263 ret = read(s->fd, buf, count);
264 if (ret == count)
265 goto label__raw_read__success;
267 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
268 "] retry read failed %d : %d = %s\n",
269 s->fd, bs->filename, offset, buf, count,
270 bs->total_sectors, ret, errno, strerror(errno));
273 label__raw_read__success:
275 return (ret < 0) ? -errno : ret;
279 * offset and count are in bytes, but must be multiples of 512 for files
280 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
282 * This function may be called without alignment if the caller ensures
283 * that O_DIRECT is not in effect.
285 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
286 const uint8_t *buf, int count)
288 BDRVRawState *s = bs->opaque;
289 int ret;
291 ret = fd_open(bs);
292 if (ret < 0)
293 return -errno;
295 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
296 ++(s->lseek_err_cnt);
297 if(s->lseek_err_cnt) {
298 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
299 PRId64 "] lseek failed : %d = %s\n",
300 s->fd, bs->filename, offset, buf, count,
301 bs->total_sectors, errno, strerror(errno));
303 return -EIO;
305 s->lseek_err_cnt = 0;
307 ret = write(s->fd, buf, count);
308 if (ret == count)
309 goto label__raw_write__success;
311 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
312 "] write failed %d : %d = %s\n",
313 s->fd, bs->filename, offset, buf, count,
314 bs->total_sectors, ret, errno, strerror(errno));
316 label__raw_write__success:
318 return (ret < 0) ? -errno : ret;
323 * offset and count are in bytes and possibly not aligned. For files opened
324 * with O_DIRECT, necessary alignments are ensured before calling
325 * raw_pread_aligned to do the actual read.
327 static int raw_pread(BlockDriverState *bs, int64_t offset,
328 uint8_t *buf, int count)
330 BDRVRawState *s = bs->opaque;
331 int size, ret, shift, sum;
333 sum = 0;
335 if (s->aligned_buf != NULL) {
337 if (offset & 0x1ff) {
338 /* align offset on a 512 bytes boundary */
340 shift = offset & 0x1ff;
341 size = (shift + count + 0x1ff) & ~0x1ff;
342 if (size > ALIGNED_BUFFER_SIZE)
343 size = ALIGNED_BUFFER_SIZE;
344 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
345 if (ret < 0)
346 return ret;
348 size = 512 - shift;
349 if (size > count)
350 size = count;
351 memcpy(buf, s->aligned_buf + shift, size);
353 buf += size;
354 offset += size;
355 count -= size;
356 sum += size;
358 if (count == 0)
359 return sum;
361 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
363 /* read on aligned buffer */
365 while (count) {
367 size = (count + 0x1ff) & ~0x1ff;
368 if (size > ALIGNED_BUFFER_SIZE)
369 size = ALIGNED_BUFFER_SIZE;
371 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
372 if (ret < 0)
373 return ret;
375 size = ret;
376 if (size > count)
377 size = count;
379 memcpy(buf, s->aligned_buf, size);
381 buf += size;
382 offset += size;
383 count -= size;
384 sum += size;
387 return sum;
391 return raw_pread_aligned(bs, offset, buf, count) + sum;
394 static int raw_read(BlockDriverState *bs, int64_t sector_num,
395 uint8_t *buf, int nb_sectors)
397 int ret;
399 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
400 if (ret == (nb_sectors * 512))
401 ret = 0;
402 return ret;
406 * offset and count are in bytes and possibly not aligned. For files opened
407 * with O_DIRECT, necessary alignments are ensured before calling
408 * raw_pwrite_aligned to do the actual write.
410 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
411 const uint8_t *buf, int count)
413 BDRVRawState *s = bs->opaque;
414 int size, ret, shift, sum;
416 sum = 0;
418 if (s->aligned_buf != NULL) {
420 if (offset & 0x1ff) {
421 /* align offset on a 512 bytes boundary */
422 shift = offset & 0x1ff;
423 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
424 if (ret < 0)
425 return ret;
427 size = 512 - shift;
428 if (size > count)
429 size = count;
430 memcpy(s->aligned_buf + shift, buf, size);
432 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
433 if (ret < 0)
434 return ret;
436 buf += size;
437 offset += size;
438 count -= size;
439 sum += size;
441 if (count == 0)
442 return sum;
444 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
446 while ((size = (count & ~0x1ff)) != 0) {
448 if (size > ALIGNED_BUFFER_SIZE)
449 size = ALIGNED_BUFFER_SIZE;
451 memcpy(s->aligned_buf, buf, size);
453 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
454 if (ret < 0)
455 return ret;
457 buf += ret;
458 offset += ret;
459 count -= ret;
460 sum += ret;
462 /* here, count < 512 because (count & ~0x1ff) == 0 */
463 if (count) {
464 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
465 if (ret < 0)
466 return ret;
467 memcpy(s->aligned_buf, buf, count);
469 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
470 if (ret < 0)
471 return ret;
472 if (count < ret)
473 ret = count;
475 sum += ret;
477 return sum;
480 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
483 static int raw_write(BlockDriverState *bs, int64_t sector_num,
484 const uint8_t *buf, int nb_sectors)
486 int ret;
487 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
488 if (ret == (nb_sectors * 512))
489 ret = 0;
490 return ret;
493 #ifdef CONFIG_AIO
494 /***********************************************************/
495 /* Unix AIO using POSIX AIO */
497 typedef struct RawAIOCB {
498 BlockDriverAIOCB common;
499 struct qemu_paiocb aiocb;
500 struct RawAIOCB *next;
501 int ret;
502 } RawAIOCB;
504 typedef struct PosixAioState
506 int fd;
507 RawAIOCB *first_aio;
508 } PosixAioState;
510 static void posix_aio_read(void *opaque)
512 PosixAioState *s = opaque;
513 RawAIOCB *acb, **pacb;
514 int ret;
515 size_t offset;
516 union {
517 struct qemu_signalfd_siginfo siginfo;
518 char buf[128];
519 } sig;
521 /* try to read from signalfd, don't freak out if we can't read anything */
522 offset = 0;
523 while (offset < 128) {
524 ssize_t len;
526 len = read(s->fd, sig.buf + offset, 128 - offset);
527 if (len == -1 && errno == EINTR)
528 continue;
529 if (len == -1 && errno == EAGAIN) {
530 /* there is no natural reason for this to happen,
531 * so we'll spin hard until we get everything just
532 * to be on the safe side. */
533 if (offset > 0)
534 continue;
537 offset += len;
540 for(;;) {
541 pacb = &s->first_aio;
542 for(;;) {
543 acb = *pacb;
544 if (!acb)
545 goto the_end;
546 ret = qemu_paio_error(&acb->aiocb);
547 if (ret == ECANCELED) {
548 /* remove the request */
549 *pacb = acb->next;
550 qemu_aio_release(acb);
551 } else if (ret != EINPROGRESS) {
552 /* end of aio */
553 if (ret == 0) {
554 ret = qemu_paio_return(&acb->aiocb);
555 if (ret == acb->aiocb.aio_nbytes)
556 ret = 0;
557 else
558 ret = -EINVAL;
559 } else {
560 ret = -ret;
562 /* remove the request */
563 *pacb = acb->next;
564 /* call the callback */
565 acb->common.cb(acb->common.opaque, ret);
566 qemu_aio_release(acb);
567 break;
568 } else {
569 pacb = &acb->next;
573 the_end: ;
576 static int posix_aio_flush(void *opaque)
578 PosixAioState *s = opaque;
579 return !!s->first_aio;
582 static PosixAioState *posix_aio_state;
584 static int posix_aio_init(void)
586 sigset_t mask;
587 PosixAioState *s;
588 struct qemu_paioinit ai;
590 if (posix_aio_state)
591 return 0;
593 s = qemu_malloc(sizeof(PosixAioState));
595 /* Make sure to block AIO signal */
596 sigemptyset(&mask);
597 sigaddset(&mask, SIGUSR2);
598 sigprocmask(SIG_BLOCK, &mask, NULL);
600 s->first_aio = NULL;
601 s->fd = qemu_signalfd(&mask);
602 if (s->fd == -1) {
603 fprintf(stderr, "failed to create signalfd\n");
604 return -errno;
607 fcntl(s->fd, F_SETFL, O_NONBLOCK);
609 qemu_aio_set_fd_handler(s->fd, posix_aio_read, NULL, posix_aio_flush, s);
611 memset(&ai, 0, sizeof(ai));
612 ai.aio_threads = 64;
613 ai.aio_num = 64;
614 qemu_paio_init(&ai);
616 posix_aio_state = s;
618 return 0;
621 static void raw_aio_remove(RawAIOCB *acb)
623 RawAIOCB **pacb;
625 /* remove the callback from the queue */
626 pacb = &posix_aio_state->first_aio;
627 for(;;) {
628 if (*pacb == NULL) {
629 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
630 break;
631 } else if (*pacb == acb) {
632 *pacb = acb->next;
633 qemu_aio_release(acb);
634 break;
636 pacb = &(*pacb)->next;
640 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
642 int ret;
643 RawAIOCB *acb = (RawAIOCB *)blockacb;
645 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
646 if (ret == QEMU_PAIO_NOTCANCELED) {
647 /* fail safe: if the aio could not be canceled, we wait for
648 it */
649 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
652 raw_aio_remove(acb);
655 static AIOPool raw_aio_pool = {
656 .aiocb_size = sizeof(RawAIOCB),
657 .cancel = raw_aio_cancel,
660 static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,
661 QEMUIOVector *qiov, int nb_sectors,
662 BlockDriverCompletionFunc *cb, void *opaque)
664 BDRVRawState *s = bs->opaque;
665 RawAIOCB *acb;
667 if (fd_open(bs) < 0)
668 return NULL;
670 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
671 if (!acb)
672 return NULL;
673 acb->aiocb.aio_fildes = s->fd;
674 acb->aiocb.ev_signo = SIGUSR2;
675 acb->aiocb.aio_iov = qiov->iov;
676 acb->aiocb.aio_niov = qiov->niov;
677 acb->aiocb.aio_nbytes = nb_sectors * 512;
678 acb->aiocb.aio_offset = sector_num * 512;
679 acb->aiocb.aio_flags = 0;
682 * If O_DIRECT is used the buffer needs to be aligned on a sector
683 * boundary. Tell the low level code to ensure that in case it's
684 * not done yet.
686 if (s->aligned_buf)
687 acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;
689 acb->next = posix_aio_state->first_aio;
690 posix_aio_state->first_aio = acb;
691 return acb;
694 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
695 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
696 BlockDriverCompletionFunc *cb, void *opaque)
698 RawAIOCB *acb;
700 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
701 if (!acb)
702 return NULL;
703 if (qemu_paio_read(&acb->aiocb) < 0) {
704 raw_aio_remove(acb);
705 return NULL;
707 return &acb->common;
710 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
711 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
712 BlockDriverCompletionFunc *cb, void *opaque)
714 RawAIOCB *acb;
716 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
717 if (!acb)
718 return NULL;
719 if (qemu_paio_write(&acb->aiocb) < 0) {
720 raw_aio_remove(acb);
721 return NULL;
723 return &acb->common;
725 #else /* CONFIG_AIO */
726 static int posix_aio_init(void)
728 return 0;
730 #endif /* CONFIG_AIO */
733 static void raw_close(BlockDriverState *bs)
735 BDRVRawState *s = bs->opaque;
736 if (s->fd >= 0) {
737 close(s->fd);
738 s->fd = -1;
739 if (s->aligned_buf != NULL)
740 qemu_free(s->aligned_buf);
744 static int raw_truncate(BlockDriverState *bs, int64_t offset)
746 BDRVRawState *s = bs->opaque;
747 if (s->type != FTYPE_FILE)
748 return -ENOTSUP;
749 if (ftruncate(s->fd, offset) < 0)
750 return -errno;
751 return 0;
754 #ifdef __OpenBSD__
755 static int64_t raw_getlength(BlockDriverState *bs)
757 BDRVRawState *s = bs->opaque;
758 int fd = s->fd;
759 struct stat st;
761 if (fstat(fd, &st))
762 return -1;
763 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
764 struct disklabel dl;
766 if (ioctl(fd, DIOCGDINFO, &dl))
767 return -1;
768 return (uint64_t)dl.d_secsize *
769 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
770 } else
771 return st.st_size;
773 #else /* !__OpenBSD__ */
774 static int64_t raw_getlength(BlockDriverState *bs)
776 BDRVRawState *s = bs->opaque;
777 int fd = s->fd;
778 int64_t size;
779 #ifdef HOST_BSD
780 struct stat sb;
781 #ifdef __FreeBSD__
782 int reopened = 0;
783 #endif
784 #endif
785 #ifdef __sun__
786 struct dk_minfo minfo;
787 int rv;
788 #endif
789 int ret;
791 ret = fd_open(bs);
792 if (ret < 0)
793 return ret;
795 #ifdef HOST_BSD
796 #ifdef __FreeBSD__
797 again:
798 #endif
799 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
800 #ifdef DIOCGMEDIASIZE
801 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
802 #elif defined(DIOCGPART)
804 struct partinfo pi;
805 if (ioctl(fd, DIOCGPART, &pi) == 0)
806 size = pi.media_size;
807 else
808 size = 0;
810 if (size == 0)
811 #endif
812 #ifdef CONFIG_COCOA
813 size = LONG_LONG_MAX;
814 #else
815 size = lseek(fd, 0LL, SEEK_END);
816 #endif
817 #ifdef __FreeBSD__
818 switch(s->type) {
819 case FTYPE_CD:
820 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
821 if (size == 2048LL * (unsigned)-1)
822 size = 0;
823 /* XXX no disc? maybe we need to reopen... */
824 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
825 reopened = 1;
826 goto again;
829 #endif
830 } else
831 #endif
832 #ifdef __sun__
834 * use the DKIOCGMEDIAINFO ioctl to read the size.
836 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
837 if ( rv != -1 ) {
838 size = minfo.dki_lbsize * minfo.dki_capacity;
839 } else /* there are reports that lseek on some devices
840 fails, but irc discussion said that contingency
841 on contingency was overkill */
842 #endif
844 size = lseek(fd, 0, SEEK_END);
846 return size;
848 #endif
850 static int raw_create(const char *filename, QEMUOptionParameter *options)
852 int fd;
853 int64_t total_size = 0;
855 /* Read out options */
856 while (options && options->name) {
857 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
858 total_size = options->value.n / 512;
860 options++;
863 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
864 0644);
865 if (fd < 0)
866 return -EIO;
867 ftruncate(fd, total_size * 512);
868 close(fd);
869 return 0;
872 static void raw_flush(BlockDriverState *bs)
874 BDRVRawState *s = bs->opaque;
875 fsync(s->fd);
879 static QEMUOptionParameter raw_create_options[] = {
881 .name = BLOCK_OPT_SIZE,
882 .type = OPT_SIZE,
883 .help = "Virtual disk size"
885 { NULL }
888 static BlockDriver bdrv_raw = {
889 .format_name = "raw",
890 .instance_size = sizeof(BDRVRawState),
891 .bdrv_probe = NULL, /* no probe for protocols */
892 .bdrv_open = raw_open,
893 .bdrv_read = raw_read,
894 .bdrv_write = raw_write,
895 .bdrv_close = raw_close,
896 .bdrv_create = raw_create,
897 .bdrv_flush = raw_flush,
899 #ifdef CONFIG_AIO
900 .bdrv_aio_readv = raw_aio_readv,
901 .bdrv_aio_writev = raw_aio_writev,
902 #endif
904 .bdrv_truncate = raw_truncate,
905 .bdrv_getlength = raw_getlength,
907 .create_options = raw_create_options,
910 /***********************************************/
911 /* host device */
913 #ifdef CONFIG_COCOA
914 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
915 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
917 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
919 kern_return_t kernResult;
920 mach_port_t masterPort;
921 CFMutableDictionaryRef classesToMatch;
923 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
924 if ( KERN_SUCCESS != kernResult ) {
925 printf( "IOMasterPort returned %d\n", kernResult );
928 classesToMatch = IOServiceMatching( kIOCDMediaClass );
929 if ( classesToMatch == NULL ) {
930 printf( "IOServiceMatching returned a NULL dictionary.\n" );
931 } else {
932 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
934 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
935 if ( KERN_SUCCESS != kernResult )
937 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
940 return kernResult;
943 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
945 io_object_t nextMedia;
946 kern_return_t kernResult = KERN_FAILURE;
947 *bsdPath = '\0';
948 nextMedia = IOIteratorNext( mediaIterator );
949 if ( nextMedia )
951 CFTypeRef bsdPathAsCFString;
952 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
953 if ( bsdPathAsCFString ) {
954 size_t devPathLength;
955 strcpy( bsdPath, _PATH_DEV );
956 strcat( bsdPath, "r" );
957 devPathLength = strlen( bsdPath );
958 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
959 kernResult = KERN_SUCCESS;
961 CFRelease( bsdPathAsCFString );
963 IOObjectRelease( nextMedia );
966 return kernResult;
969 #endif
971 static int hdev_probe_device(const char *filename)
973 struct stat st;
975 /* allow a dedicated CD-ROM driver to match with a higher priority */
976 if (strstart(filename, "/dev/cdrom", NULL))
977 return 50;
979 if (stat(filename, &st) >= 0 &&
980 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
981 return 100;
984 return 0;
987 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
989 BDRVRawState *s = bs->opaque;
991 #ifdef CONFIG_COCOA
992 if (strstart(filename, "/dev/cdrom", NULL)) {
993 kern_return_t kernResult;
994 io_iterator_t mediaIterator;
995 char bsdPath[ MAXPATHLEN ];
996 int fd;
998 kernResult = FindEjectableCDMedia( &mediaIterator );
999 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1001 if ( bsdPath[ 0 ] != '\0' ) {
1002 strcat(bsdPath,"s0");
1003 /* some CDs don't have a partition 0 */
1004 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1005 if (fd < 0) {
1006 bsdPath[strlen(bsdPath)-1] = '1';
1007 } else {
1008 close(fd);
1010 filename = bsdPath;
1013 if ( mediaIterator )
1014 IOObjectRelease( mediaIterator );
1016 #endif
1018 s->type = FTYPE_FILE;
1019 #if defined(__linux__) && defined(CONFIG_AIO)
1020 if (strstart(filename, "/dev/sg", NULL)) {
1021 bs->sg = 1;
1023 #endif
1025 return raw_open_common(bs, filename, flags, 0);
1028 #if defined(__linux__)
1029 /* Note: we do not have a reliable method to detect if the floppy is
1030 present. The current method is to try to open the floppy at every
1031 I/O and to keep it opened during a few hundreds of ms. */
1032 static int fd_open(BlockDriverState *bs)
1034 BDRVRawState *s = bs->opaque;
1035 int last_media_present;
1037 if (s->type != FTYPE_FD)
1038 return 0;
1039 last_media_present = (s->fd >= 0);
1040 if (s->fd >= 0 &&
1041 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1042 close(s->fd);
1043 s->fd = -1;
1044 #ifdef DEBUG_FLOPPY
1045 printf("Floppy closed\n");
1046 #endif
1048 if (s->fd < 0) {
1049 if (s->fd_got_error &&
1050 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1051 #ifdef DEBUG_FLOPPY
1052 printf("No floppy (open delayed)\n");
1053 #endif
1054 return -EIO;
1056 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1057 if (s->fd < 0) {
1058 s->fd_error_time = qemu_get_clock(rt_clock);
1059 s->fd_got_error = 1;
1060 if (last_media_present)
1061 s->fd_media_changed = 1;
1062 #ifdef DEBUG_FLOPPY
1063 printf("No floppy\n");
1064 #endif
1065 return -EIO;
1067 #ifdef DEBUG_FLOPPY
1068 printf("Floppy opened\n");
1069 #endif
1071 if (!last_media_present)
1072 s->fd_media_changed = 1;
1073 s->fd_open_time = qemu_get_clock(rt_clock);
1074 s->fd_got_error = 0;
1075 return 0;
1078 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1080 BDRVRawState *s = bs->opaque;
1082 return ioctl(s->fd, req, buf);
1085 #ifdef CONFIG_AIO
1086 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1087 unsigned long int req, void *buf,
1088 BlockDriverCompletionFunc *cb, void *opaque)
1090 BDRVRawState *s = bs->opaque;
1091 RawAIOCB *acb;
1093 if (fd_open(bs) < 0)
1094 return NULL;
1096 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
1097 if (!acb)
1098 return NULL;
1099 acb->aiocb.aio_fildes = s->fd;
1100 acb->aiocb.ev_signo = SIGUSR2;
1101 acb->aiocb.aio_offset = 0;
1102 acb->aiocb.aio_flags = 0;
1104 acb->next = posix_aio_state->first_aio;
1105 posix_aio_state->first_aio = acb;
1107 acb->aiocb.aio_ioctl_buf = buf;
1108 acb->aiocb.aio_ioctl_cmd = req;
1109 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1110 raw_aio_remove(acb);
1111 return NULL;
1114 return &acb->common;
1116 #endif
1118 #elif defined(__FreeBSD__)
1119 static int fd_open(BlockDriverState *bs)
1121 BDRVRawState *s = bs->opaque;
1123 /* this is just to ensure s->fd is sane (its called by io ops) */
1124 if (s->fd >= 0)
1125 return 0;
1126 return -EIO;
1128 #else /* !linux && !FreeBSD */
1130 static int fd_open(BlockDriverState *bs)
1132 return 0;
1135 #endif /* !linux && !FreeBSD */
1137 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1139 int fd;
1140 int ret = 0;
1141 struct stat stat_buf;
1142 int64_t total_size = 0;
1144 /* Read out options */
1145 while (options && options->name) {
1146 if (!strcmp(options->name, "size")) {
1147 total_size = options->value.n / 512;
1149 options++;
1152 fd = open(filename, O_WRONLY | O_BINARY);
1153 if (fd < 0)
1154 return -EIO;
1156 if (fstat(fd, &stat_buf) < 0)
1157 ret = -EIO;
1158 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1159 ret = -EIO;
1160 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1161 ret = -ENOSPC;
1163 close(fd);
1164 return ret;
1167 static BlockDriver bdrv_host_device = {
1168 .format_name = "host_device",
1169 .instance_size = sizeof(BDRVRawState),
1170 .bdrv_probe_device = hdev_probe_device,
1171 .bdrv_open = hdev_open,
1172 .bdrv_close = raw_close,
1173 .bdrv_create = hdev_create,
1174 .bdrv_flush = raw_flush,
1176 #ifdef CONFIG_AIO
1177 .bdrv_aio_readv = raw_aio_readv,
1178 .bdrv_aio_writev = raw_aio_writev,
1179 #endif
1181 .bdrv_read = raw_read,
1182 .bdrv_write = raw_write,
1183 .bdrv_getlength = raw_getlength,
1185 /* generic scsi device */
1186 #ifdef __linux__
1187 .bdrv_ioctl = hdev_ioctl,
1188 #ifdef CONFIG_AIO
1189 .bdrv_aio_ioctl = hdev_aio_ioctl,
1190 #endif
1191 #endif
1194 #ifdef __linux__
1195 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1197 BDRVRawState *s = bs->opaque;
1198 int ret;
1200 posix_aio_init();
1202 s->type = FTYPE_FD;
1204 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1205 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1206 if (ret)
1207 return ret;
1209 /* close fd so that we can reopen it as needed */
1210 close(s->fd);
1211 s->fd = -1;
1212 s->fd_media_changed = 1;
1214 return 0;
1217 static int floppy_probe_device(const char *filename)
1219 if (strstart(filename, "/dev/fd", NULL))
1220 return 100;
1221 return 0;
1225 static int floppy_is_inserted(BlockDriverState *bs)
1227 return fd_open(bs) >= 0;
1230 static int floppy_media_changed(BlockDriverState *bs)
1232 BDRVRawState *s = bs->opaque;
1233 int ret;
1236 * XXX: we do not have a true media changed indication.
1237 * It does not work if the floppy is changed without trying to read it.
1239 fd_open(bs);
1240 ret = s->fd_media_changed;
1241 s->fd_media_changed = 0;
1242 #ifdef DEBUG_FLOPPY
1243 printf("Floppy changed=%d\n", ret);
1244 #endif
1245 return ret;
1248 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1250 BDRVRawState *s = bs->opaque;
1251 int fd;
1253 if (s->fd >= 0) {
1254 close(s->fd);
1255 s->fd = -1;
1257 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1258 if (fd >= 0) {
1259 if (ioctl(fd, FDEJECT, 0) < 0)
1260 perror("FDEJECT");
1261 close(fd);
1264 return 0;
1267 static BlockDriver bdrv_host_floppy = {
1268 .format_name = "host_floppy",
1269 .instance_size = sizeof(BDRVRawState),
1270 .bdrv_probe_device = floppy_probe_device,
1271 .bdrv_open = floppy_open,
1272 .bdrv_close = raw_close,
1273 .bdrv_create = hdev_create,
1274 .bdrv_flush = raw_flush,
1276 #ifdef CONFIG_AIO
1277 .bdrv_aio_readv = raw_aio_readv,
1278 .bdrv_aio_writev = raw_aio_writev,
1279 #endif
1281 .bdrv_read = raw_read,
1282 .bdrv_write = raw_write,
1283 .bdrv_getlength = raw_getlength,
1285 /* removable device support */
1286 .bdrv_is_inserted = floppy_is_inserted,
1287 .bdrv_media_changed = floppy_media_changed,
1288 .bdrv_eject = floppy_eject,
1291 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1293 BDRVRawState *s = bs->opaque;
1295 s->type = FTYPE_CD;
1297 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1298 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1301 static int cdrom_probe_device(const char *filename)
1303 if (strstart(filename, "/dev/cd", NULL))
1304 return 100;
1305 return 0;
1308 static int cdrom_is_inserted(BlockDriverState *bs)
1310 BDRVRawState *s = bs->opaque;
1311 int ret;
1313 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1314 if (ret == CDS_DISC_OK)
1315 return 1;
1316 return 0;
1319 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1321 BDRVRawState *s = bs->opaque;
1323 if (eject_flag) {
1324 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1325 perror("CDROMEJECT");
1326 } else {
1327 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1328 perror("CDROMEJECT");
1331 return 0;
1334 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1336 BDRVRawState *s = bs->opaque;
1338 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1340 * Note: an error can happen if the distribution automatically
1341 * mounts the CD-ROM
1343 /* perror("CDROM_LOCKDOOR"); */
1346 return 0;
1349 static BlockDriver bdrv_host_cdrom = {
1350 .format_name = "host_cdrom",
1351 .instance_size = sizeof(BDRVRawState),
1352 .bdrv_probe_device = cdrom_probe_device,
1353 .bdrv_open = cdrom_open,
1354 .bdrv_close = raw_close,
1355 .bdrv_create = hdev_create,
1356 .bdrv_flush = raw_flush,
1358 #ifdef CONFIG_AIO
1359 .bdrv_aio_readv = raw_aio_readv,
1360 .bdrv_aio_writev = raw_aio_writev,
1361 #endif
1363 .bdrv_read = raw_read,
1364 .bdrv_write = raw_write,
1365 .bdrv_getlength = raw_getlength,
1367 /* removable device support */
1368 .bdrv_is_inserted = cdrom_is_inserted,
1369 .bdrv_eject = cdrom_eject,
1370 .bdrv_set_locked = cdrom_set_locked,
1372 /* generic scsi device */
1373 .bdrv_ioctl = hdev_ioctl,
1374 #ifdef CONFIG_AIO
1375 .bdrv_aio_ioctl = hdev_aio_ioctl,
1376 #endif
1378 #endif /* __linux__ */
1380 #ifdef __FreeBSD__
1381 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1383 BDRVRawState *s = bs->opaque;
1384 int ret;
1386 s->type = FTYPE_CD;
1388 ret = raw_open_common(bs, filename, flags, 0);
1389 if (ret)
1390 return ret;
1392 /* make sure the door isnt locked at this time */
1393 ioctl(s->fd, CDIOCALLOW);
1394 return 0;
1397 static int cdrom_probe_device(const char *filename)
1399 if (strstart(filename, "/dev/cd", NULL) ||
1400 strstart(filename, "/dev/acd", NULL))
1401 return 100;
1402 return 0;
1405 static int cdrom_reopen(BlockDriverState *bs)
1407 BDRVRawState *s = bs->opaque;
1408 int fd;
1411 * Force reread of possibly changed/newly loaded disc,
1412 * FreeBSD seems to not notice sometimes...
1414 if (s->fd >= 0)
1415 close(s->fd);
1416 fd = open(bs->filename, s->open_flags, 0644);
1417 if (fd < 0) {
1418 s->fd = -1;
1419 return -EIO;
1421 s->fd = fd;
1423 /* make sure the door isnt locked at this time */
1424 ioctl(s->fd, CDIOCALLOW);
1425 return 0;
1428 static int cdrom_is_inserted(BlockDriverState *bs)
1430 return raw_getlength(bs) > 0;
1433 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1435 BDRVRawState *s = bs->opaque;
1437 if (s->fd < 0)
1438 return -ENOTSUP;
1440 (void) ioctl(s->fd, CDIOCALLOW);
1442 if (eject_flag) {
1443 if (ioctl(s->fd, CDIOCEJECT) < 0)
1444 perror("CDIOCEJECT");
1445 } else {
1446 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1447 perror("CDIOCCLOSE");
1450 if (cdrom_reopen(bs) < 0)
1451 return -ENOTSUP;
1452 return 0;
1455 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1457 BDRVRawState *s = bs->opaque;
1459 if (s->fd < 0)
1460 return -ENOTSUP;
1461 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1463 * Note: an error can happen if the distribution automatically
1464 * mounts the CD-ROM
1466 /* perror("CDROM_LOCKDOOR"); */
1469 return 0;
1472 static BlockDriver bdrv_host_cdrom = {
1473 .format_name = "host_cdrom",
1474 .instance_size = sizeof(BDRVRawState),
1475 .bdrv_probe_device = cdrom_probe_device,
1476 .bdrv_open = cdrom_open,
1477 .bdrv_close = raw_close,
1478 .bdrv_create = hdev_create,
1479 .bdrv_flush = raw_flush,
1481 #ifdef CONFIG_AIO
1482 .bdrv_aio_readv = raw_aio_readv,
1483 .bdrv_aio_writev = raw_aio_writev,
1484 #endif
1486 .bdrv_read = raw_read,
1487 .bdrv_write = raw_write,
1488 .bdrv_getlength = raw_getlength,
1490 /* removable device support */
1491 .bdrv_is_inserted = cdrom_is_inserted,
1492 .bdrv_eject = cdrom_eject,
1493 .bdrv_set_locked = cdrom_set_locked,
1495 #endif /* __FreeBSD__ */
1497 static void bdrv_raw_init(void)
1500 * Register all the drivers. Note that order is important, the driver
1501 * registered last will get probed first.
1503 bdrv_register(&bdrv_raw);
1504 bdrv_register(&bdrv_host_device);
1505 #ifdef __linux__
1506 bdrv_register(&bdrv_host_floppy);
1507 bdrv_register(&bdrv_host_cdrom);
1508 #endif
1509 #ifdef __FreeBSD__
1510 bdrv_register(&bdrv_host_cdrom);
1511 #endif
1514 block_init(bdrv_raw_init);