push CPUID level to 4 to allow Intel multicore decoding
[qemu.git] / block / raw-posix.c
blobab43589402c7d7f14ef6293c69b01ecbbb5ec9ed
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 "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "posix-aio-compat.h"
32 #ifdef CONFIG_COCOA
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <signal.h>
47 #include <sys/dkio.h>
48 #endif
49 #ifdef __linux__
50 #include <sys/ioctl.h>
51 #include <linux/cdrom.h>
52 #include <linux/fd.h>
53 #endif
54 #ifdef __FreeBSD__
55 #include <signal.h>
56 #include <sys/disk.h>
57 #include <sys/cdio.h>
58 #endif
60 #ifdef __OpenBSD__
61 #include <sys/ioctl.h>
62 #include <sys/disklabel.h>
63 #include <sys/dkio.h>
64 #endif
66 #ifdef __DragonFly__
67 #include <sys/ioctl.h>
68 #include <sys/diskslice.h>
69 #endif
71 //#define DEBUG_FLOPPY
73 //#define DEBUG_BLOCK
74 #if defined(DEBUG_BLOCK)
75 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
76 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
77 #else
78 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
79 #endif
81 /* OS X does not have O_DSYNC */
82 #ifndef O_DSYNC
83 #ifdef O_SYNC
84 #define O_DSYNC O_SYNC
85 #elif defined(O_FSYNC)
86 #define O_DSYNC O_FSYNC
87 #endif
88 #endif
90 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
91 #ifndef O_DIRECT
92 #define O_DIRECT O_DSYNC
93 #endif
95 #define FTYPE_FILE 0
96 #define FTYPE_CD 1
97 #define FTYPE_FD 2
99 #define ALIGNED_BUFFER_SIZE (32 * 512)
101 /* if the FD is not accessed during that time (in ms), we try to
102 reopen it to see if the disk has been changed */
103 #define FD_OPEN_TIMEOUT 1000
105 typedef struct BDRVRawState {
106 int fd;
107 int type;
108 unsigned int lseek_err_cnt;
109 int open_flags;
110 #if defined(__linux__)
111 /* linux floppy specific */
112 int64_t fd_open_time;
113 int64_t fd_error_time;
114 int fd_got_error;
115 int fd_media_changed;
116 #endif
117 uint8_t* aligned_buf;
118 } BDRVRawState;
120 static int posix_aio_init(void);
122 static int fd_open(BlockDriverState *bs);
123 static int64_t raw_getlength(BlockDriverState *bs);
125 #if defined(__FreeBSD__)
126 static int cdrom_reopen(BlockDriverState *bs);
127 #endif
129 static int raw_open_common(BlockDriverState *bs, const char *filename,
130 int bdrv_flags, int open_flags)
132 BDRVRawState *s = bs->opaque;
133 int fd, ret;
135 posix_aio_init();
137 s->lseek_err_cnt = 0;
139 s->open_flags = open_flags | O_BINARY;
140 s->open_flags &= ~O_ACCMODE;
141 if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
142 s->open_flags |= O_RDWR;
143 } else {
144 s->open_flags |= O_RDONLY;
145 bs->read_only = 1;
148 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
149 * and O_DIRECT for no caching. */
150 if ((bdrv_flags & BDRV_O_NOCACHE))
151 s->open_flags |= O_DIRECT;
152 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
153 s->open_flags |= O_DSYNC;
155 s->fd = -1;
156 fd = open(filename, s->open_flags, 0644);
157 if (fd < 0) {
158 ret = -errno;
159 if (ret == -EROFS)
160 ret = -EACCES;
161 return ret;
163 s->fd = fd;
164 s->aligned_buf = NULL;
165 if ((bdrv_flags & BDRV_O_NOCACHE)) {
166 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
167 if (s->aligned_buf == NULL) {
168 ret = -errno;
169 close(fd);
170 return ret;
173 return 0;
176 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
178 BDRVRawState *s = bs->opaque;
179 int open_flags = 0;
181 s->type = FTYPE_FILE;
182 if (flags & BDRV_O_CREAT)
183 open_flags = O_CREAT | O_TRUNC;
185 return raw_open_common(bs, filename, flags, open_flags);
188 /* XXX: use host sector size if necessary with:
189 #ifdef DIOCGSECTORSIZE
191 unsigned int sectorsize = 512;
192 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
193 sectorsize > bufsize)
194 bufsize = sectorsize;
196 #endif
197 #ifdef CONFIG_COCOA
198 u_int32_t blockSize = 512;
199 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
200 bufsize = blockSize;
202 #endif
206 * offset and count are in bytes, but must be multiples of 512 for files
207 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
209 * This function may be called without alignment if the caller ensures
210 * that O_DIRECT is not in effect.
212 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
213 uint8_t *buf, int count)
215 BDRVRawState *s = bs->opaque;
216 int ret;
218 ret = fd_open(bs);
219 if (ret < 0)
220 return ret;
222 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
223 ++(s->lseek_err_cnt);
224 if(s->lseek_err_cnt <= 10) {
225 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
226 "] lseek failed : %d = %s\n",
227 s->fd, bs->filename, offset, buf, count,
228 bs->total_sectors, errno, strerror(errno));
230 return -1;
232 s->lseek_err_cnt=0;
234 ret = read(s->fd, buf, count);
235 if (ret == count)
236 goto label__raw_read__success;
238 /* Allow reads beyond the end (needed for pwrite) */
239 if ((ret == 0) && bs->growable) {
240 int64_t size = raw_getlength(bs);
241 if (offset >= size) {
242 memset(buf, 0, count);
243 ret = count;
244 goto label__raw_read__success;
248 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
249 "] read failed %d : %d = %s\n",
250 s->fd, bs->filename, offset, buf, count,
251 bs->total_sectors, ret, errno, strerror(errno));
253 /* Try harder for CDrom. */
254 if (bs->type == BDRV_TYPE_CDROM) {
255 lseek(s->fd, offset, SEEK_SET);
256 ret = read(s->fd, buf, count);
257 if (ret == count)
258 goto label__raw_read__success;
259 lseek(s->fd, offset, SEEK_SET);
260 ret = read(s->fd, buf, count);
261 if (ret == count)
262 goto label__raw_read__success;
264 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
265 "] retry read failed %d : %d = %s\n",
266 s->fd, bs->filename, offset, buf, count,
267 bs->total_sectors, ret, errno, strerror(errno));
270 label__raw_read__success:
272 return (ret < 0) ? -errno : ret;
276 * offset and count are in bytes, but must be multiples of 512 for files
277 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
279 * This function may be called without alignment if the caller ensures
280 * that O_DIRECT is not in effect.
282 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
283 const uint8_t *buf, int count)
285 BDRVRawState *s = bs->opaque;
286 int ret;
288 ret = fd_open(bs);
289 if (ret < 0)
290 return -errno;
292 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
293 ++(s->lseek_err_cnt);
294 if(s->lseek_err_cnt) {
295 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
296 PRId64 "] lseek failed : %d = %s\n",
297 s->fd, bs->filename, offset, buf, count,
298 bs->total_sectors, errno, strerror(errno));
300 return -EIO;
302 s->lseek_err_cnt = 0;
304 ret = write(s->fd, buf, count);
305 if (ret == count)
306 goto label__raw_write__success;
308 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
309 "] write failed %d : %d = %s\n",
310 s->fd, bs->filename, offset, buf, count,
311 bs->total_sectors, ret, errno, strerror(errno));
313 label__raw_write__success:
315 return (ret < 0) ? -errno : ret;
320 * offset and count are in bytes and possibly not aligned. For files opened
321 * with O_DIRECT, necessary alignments are ensured before calling
322 * raw_pread_aligned to do the actual read.
324 static int raw_pread(BlockDriverState *bs, int64_t offset,
325 uint8_t *buf, int count)
327 BDRVRawState *s = bs->opaque;
328 int size, ret, shift, sum;
330 sum = 0;
332 if (s->aligned_buf != NULL) {
334 if (offset & 0x1ff) {
335 /* align offset on a 512 bytes boundary */
337 shift = offset & 0x1ff;
338 size = (shift + count + 0x1ff) & ~0x1ff;
339 if (size > ALIGNED_BUFFER_SIZE)
340 size = ALIGNED_BUFFER_SIZE;
341 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
342 if (ret < 0)
343 return ret;
345 size = 512 - shift;
346 if (size > count)
347 size = count;
348 memcpy(buf, s->aligned_buf + shift, size);
350 buf += size;
351 offset += size;
352 count -= size;
353 sum += size;
355 if (count == 0)
356 return sum;
358 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
360 /* read on aligned buffer */
362 while (count) {
364 size = (count + 0x1ff) & ~0x1ff;
365 if (size > ALIGNED_BUFFER_SIZE)
366 size = ALIGNED_BUFFER_SIZE;
368 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
369 if (ret < 0)
370 return ret;
372 size = ret;
373 if (size > count)
374 size = count;
376 memcpy(buf, s->aligned_buf, size);
378 buf += size;
379 offset += size;
380 count -= size;
381 sum += size;
384 return sum;
388 return raw_pread_aligned(bs, offset, buf, count) + sum;
391 static int raw_read(BlockDriverState *bs, int64_t sector_num,
392 uint8_t *buf, int nb_sectors)
394 int ret;
396 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
397 if (ret == (nb_sectors * 512))
398 ret = 0;
399 return ret;
403 * offset and count are in bytes and possibly not aligned. For files opened
404 * with O_DIRECT, necessary alignments are ensured before calling
405 * raw_pwrite_aligned to do the actual write.
407 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
408 const uint8_t *buf, int count)
410 BDRVRawState *s = bs->opaque;
411 int size, ret, shift, sum;
413 sum = 0;
415 if (s->aligned_buf != NULL) {
417 if (offset & 0x1ff) {
418 /* align offset on a 512 bytes boundary */
419 shift = offset & 0x1ff;
420 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
421 if (ret < 0)
422 return ret;
424 size = 512 - shift;
425 if (size > count)
426 size = count;
427 memcpy(s->aligned_buf + shift, buf, size);
429 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
430 if (ret < 0)
431 return ret;
433 buf += size;
434 offset += size;
435 count -= size;
436 sum += size;
438 if (count == 0)
439 return sum;
441 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
443 while ((size = (count & ~0x1ff)) != 0) {
445 if (size > ALIGNED_BUFFER_SIZE)
446 size = ALIGNED_BUFFER_SIZE;
448 memcpy(s->aligned_buf, buf, size);
450 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
451 if (ret < 0)
452 return ret;
454 buf += ret;
455 offset += ret;
456 count -= ret;
457 sum += ret;
459 /* here, count < 512 because (count & ~0x1ff) == 0 */
460 if (count) {
461 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
462 if (ret < 0)
463 return ret;
464 memcpy(s->aligned_buf, buf, count);
466 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
467 if (ret < 0)
468 return ret;
469 if (count < ret)
470 ret = count;
472 sum += ret;
474 return sum;
477 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
480 static int raw_write(BlockDriverState *bs, int64_t sector_num,
481 const uint8_t *buf, int nb_sectors)
483 int ret;
484 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
485 if (ret == (nb_sectors * 512))
486 ret = 0;
487 return ret;
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 rfd, wfd;
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 ssize_t len;
513 /* read all bytes from signal pipe */
514 for (;;) {
515 char bytes[16];
517 len = read(s->rfd, bytes, sizeof(bytes));
518 if (len == -1 && errno == EINTR)
519 continue; /* try again */
520 if (len == sizeof(bytes))
521 continue; /* more to read */
522 break;
525 for(;;) {
526 pacb = &s->first_aio;
527 for(;;) {
528 acb = *pacb;
529 if (!acb)
530 goto the_end;
531 ret = qemu_paio_error(&acb->aiocb);
532 if (ret == ECANCELED) {
533 /* remove the request */
534 *pacb = acb->next;
535 qemu_aio_release(acb);
536 } else if (ret != EINPROGRESS) {
537 /* end of aio */
538 if (ret == 0) {
539 ret = qemu_paio_return(&acb->aiocb);
540 if (ret == acb->aiocb.aio_nbytes)
541 ret = 0;
542 else
543 ret = -EINVAL;
544 } else {
545 ret = -ret;
547 /* remove the request */
548 *pacb = acb->next;
549 /* call the callback */
550 acb->common.cb(acb->common.opaque, ret);
551 qemu_aio_release(acb);
552 break;
553 } else {
554 pacb = &acb->next;
558 the_end: ;
561 static int posix_aio_flush(void *opaque)
563 PosixAioState *s = opaque;
564 return !!s->first_aio;
567 static PosixAioState *posix_aio_state;
569 static void aio_signal_handler(int signum)
571 if (posix_aio_state) {
572 char byte = 0;
574 write(posix_aio_state->wfd, &byte, sizeof(byte));
577 qemu_service_io();
580 static int posix_aio_init(void)
582 struct sigaction act;
583 PosixAioState *s;
584 int fds[2];
585 struct qemu_paioinit ai;
587 if (posix_aio_state)
588 return 0;
590 s = qemu_malloc(sizeof(PosixAioState));
592 sigfillset(&act.sa_mask);
593 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
594 act.sa_handler = aio_signal_handler;
595 sigaction(SIGUSR2, &act, NULL);
597 s->first_aio = NULL;
598 if (pipe(fds) == -1) {
599 fprintf(stderr, "failed to create pipe\n");
600 return -errno;
603 s->rfd = fds[0];
604 s->wfd = fds[1];
606 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
607 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
609 qemu_aio_set_fd_handler(s->rfd, 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;
726 static void raw_close(BlockDriverState *bs)
728 BDRVRawState *s = bs->opaque;
729 if (s->fd >= 0) {
730 close(s->fd);
731 s->fd = -1;
732 if (s->aligned_buf != NULL)
733 qemu_free(s->aligned_buf);
737 static int raw_truncate(BlockDriverState *bs, int64_t offset)
739 BDRVRawState *s = bs->opaque;
740 if (s->type != FTYPE_FILE)
741 return -ENOTSUP;
742 if (ftruncate(s->fd, offset) < 0)
743 return -errno;
744 return 0;
747 #ifdef __OpenBSD__
748 static int64_t raw_getlength(BlockDriverState *bs)
750 BDRVRawState *s = bs->opaque;
751 int fd = s->fd;
752 struct stat st;
754 if (fstat(fd, &st))
755 return -1;
756 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
757 struct disklabel dl;
759 if (ioctl(fd, DIOCGDINFO, &dl))
760 return -1;
761 return (uint64_t)dl.d_secsize *
762 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
763 } else
764 return st.st_size;
766 #else /* !__OpenBSD__ */
767 static int64_t raw_getlength(BlockDriverState *bs)
769 BDRVRawState *s = bs->opaque;
770 int fd = s->fd;
771 int64_t size;
772 #ifdef CONFIG_BSD
773 struct stat sb;
774 #ifdef __FreeBSD__
775 int reopened = 0;
776 #endif
777 #endif
778 #ifdef __sun__
779 struct dk_minfo minfo;
780 int rv;
781 #endif
782 int ret;
784 ret = fd_open(bs);
785 if (ret < 0)
786 return ret;
788 #ifdef CONFIG_BSD
789 #ifdef __FreeBSD__
790 again:
791 #endif
792 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
793 #ifdef DIOCGMEDIASIZE
794 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
795 #elif defined(DIOCGPART)
797 struct partinfo pi;
798 if (ioctl(fd, DIOCGPART, &pi) == 0)
799 size = pi.media_size;
800 else
801 size = 0;
803 if (size == 0)
804 #endif
805 #ifdef CONFIG_COCOA
806 size = LONG_LONG_MAX;
807 #else
808 size = lseek(fd, 0LL, SEEK_END);
809 #endif
810 #ifdef __FreeBSD__
811 switch(s->type) {
812 case FTYPE_CD:
813 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
814 if (size == 2048LL * (unsigned)-1)
815 size = 0;
816 /* XXX no disc? maybe we need to reopen... */
817 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
818 reopened = 1;
819 goto again;
822 #endif
823 } else
824 #endif
825 #ifdef __sun__
827 * use the DKIOCGMEDIAINFO ioctl to read the size.
829 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
830 if ( rv != -1 ) {
831 size = minfo.dki_lbsize * minfo.dki_capacity;
832 } else /* there are reports that lseek on some devices
833 fails, but irc discussion said that contingency
834 on contingency was overkill */
835 #endif
837 size = lseek(fd, 0, SEEK_END);
839 return size;
841 #endif
843 static int raw_create(const char *filename, QEMUOptionParameter *options)
845 int fd;
846 int result = 0;
847 int64_t total_size = 0;
849 /* Read out options */
850 while (options && options->name) {
851 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
852 total_size = options->value.n / 512;
854 options++;
857 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
858 0644);
859 if (fd < 0) {
860 result = -errno;
861 } else {
862 if (ftruncate(fd, total_size * 512) != 0) {
863 result = -errno;
865 if (close(fd) != 0) {
866 result = -errno;
869 return result;
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 .bdrv_aio_readv = raw_aio_readv,
900 .bdrv_aio_writev = raw_aio_writev,
902 .bdrv_truncate = raw_truncate,
903 .bdrv_getlength = raw_getlength,
905 .create_options = raw_create_options,
908 /***********************************************/
909 /* host device */
911 #ifdef CONFIG_COCOA
912 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
913 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
915 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
917 kern_return_t kernResult;
918 mach_port_t masterPort;
919 CFMutableDictionaryRef classesToMatch;
921 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
922 if ( KERN_SUCCESS != kernResult ) {
923 printf( "IOMasterPort returned %d\n", kernResult );
926 classesToMatch = IOServiceMatching( kIOCDMediaClass );
927 if ( classesToMatch == NULL ) {
928 printf( "IOServiceMatching returned a NULL dictionary.\n" );
929 } else {
930 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
932 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
933 if ( KERN_SUCCESS != kernResult )
935 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
938 return kernResult;
941 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
943 io_object_t nextMedia;
944 kern_return_t kernResult = KERN_FAILURE;
945 *bsdPath = '\0';
946 nextMedia = IOIteratorNext( mediaIterator );
947 if ( nextMedia )
949 CFTypeRef bsdPathAsCFString;
950 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
951 if ( bsdPathAsCFString ) {
952 size_t devPathLength;
953 strcpy( bsdPath, _PATH_DEV );
954 strcat( bsdPath, "r" );
955 devPathLength = strlen( bsdPath );
956 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
957 kernResult = KERN_SUCCESS;
959 CFRelease( bsdPathAsCFString );
961 IOObjectRelease( nextMedia );
964 return kernResult;
967 #endif
969 static int hdev_probe_device(const char *filename)
971 struct stat st;
973 /* allow a dedicated CD-ROM driver to match with a higher priority */
974 if (strstart(filename, "/dev/cdrom", NULL))
975 return 50;
977 if (stat(filename, &st) >= 0 &&
978 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
979 return 100;
982 return 0;
985 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
987 BDRVRawState *s = bs->opaque;
989 #ifdef CONFIG_COCOA
990 if (strstart(filename, "/dev/cdrom", NULL)) {
991 kern_return_t kernResult;
992 io_iterator_t mediaIterator;
993 char bsdPath[ MAXPATHLEN ];
994 int fd;
996 kernResult = FindEjectableCDMedia( &mediaIterator );
997 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
999 if ( bsdPath[ 0 ] != '\0' ) {
1000 strcat(bsdPath,"s0");
1001 /* some CDs don't have a partition 0 */
1002 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1003 if (fd < 0) {
1004 bsdPath[strlen(bsdPath)-1] = '1';
1005 } else {
1006 close(fd);
1008 filename = bsdPath;
1011 if ( mediaIterator )
1012 IOObjectRelease( mediaIterator );
1014 #endif
1016 s->type = FTYPE_FILE;
1017 #if defined(__linux__)
1018 if (strstart(filename, "/dev/sg", NULL)) {
1019 bs->sg = 1;
1021 #endif
1023 return raw_open_common(bs, filename, flags, 0);
1026 #if defined(__linux__)
1027 /* Note: we do not have a reliable method to detect if the floppy is
1028 present. The current method is to try to open the floppy at every
1029 I/O and to keep it opened during a few hundreds of ms. */
1030 static int fd_open(BlockDriverState *bs)
1032 BDRVRawState *s = bs->opaque;
1033 int last_media_present;
1035 if (s->type != FTYPE_FD)
1036 return 0;
1037 last_media_present = (s->fd >= 0);
1038 if (s->fd >= 0 &&
1039 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1040 close(s->fd);
1041 s->fd = -1;
1042 #ifdef DEBUG_FLOPPY
1043 printf("Floppy closed\n");
1044 #endif
1046 if (s->fd < 0) {
1047 if (s->fd_got_error &&
1048 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1049 #ifdef DEBUG_FLOPPY
1050 printf("No floppy (open delayed)\n");
1051 #endif
1052 return -EIO;
1054 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1055 if (s->fd < 0) {
1056 s->fd_error_time = qemu_get_clock(rt_clock);
1057 s->fd_got_error = 1;
1058 if (last_media_present)
1059 s->fd_media_changed = 1;
1060 #ifdef DEBUG_FLOPPY
1061 printf("No floppy\n");
1062 #endif
1063 return -EIO;
1065 #ifdef DEBUG_FLOPPY
1066 printf("Floppy opened\n");
1067 #endif
1069 if (!last_media_present)
1070 s->fd_media_changed = 1;
1071 s->fd_open_time = qemu_get_clock(rt_clock);
1072 s->fd_got_error = 0;
1073 return 0;
1076 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1078 BDRVRawState *s = bs->opaque;
1080 return ioctl(s->fd, req, buf);
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;
1114 #elif defined(__FreeBSD__)
1115 static int fd_open(BlockDriverState *bs)
1117 BDRVRawState *s = bs->opaque;
1119 /* this is just to ensure s->fd is sane (its called by io ops) */
1120 if (s->fd >= 0)
1121 return 0;
1122 return -EIO;
1124 #else /* !linux && !FreeBSD */
1126 static int fd_open(BlockDriverState *bs)
1128 return 0;
1131 #endif /* !linux && !FreeBSD */
1133 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1135 int fd;
1136 int ret = 0;
1137 struct stat stat_buf;
1138 int64_t total_size = 0;
1140 /* Read out options */
1141 while (options && options->name) {
1142 if (!strcmp(options->name, "size")) {
1143 total_size = options->value.n / 512;
1145 options++;
1148 fd = open(filename, O_WRONLY | O_BINARY);
1149 if (fd < 0)
1150 return -EIO;
1152 if (fstat(fd, &stat_buf) < 0)
1153 ret = -EIO;
1154 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1155 ret = -EIO;
1156 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1157 ret = -ENOSPC;
1159 close(fd);
1160 return ret;
1163 static BlockDriver bdrv_host_device = {
1164 .format_name = "host_device",
1165 .instance_size = sizeof(BDRVRawState),
1166 .bdrv_probe_device = hdev_probe_device,
1167 .bdrv_open = hdev_open,
1168 .bdrv_close = raw_close,
1169 .bdrv_create = hdev_create,
1170 .bdrv_flush = raw_flush,
1172 .bdrv_aio_readv = raw_aio_readv,
1173 .bdrv_aio_writev = raw_aio_writev,
1175 .bdrv_read = raw_read,
1176 .bdrv_write = raw_write,
1177 .bdrv_getlength = raw_getlength,
1179 /* generic scsi device */
1180 #ifdef __linux__
1181 .bdrv_ioctl = hdev_ioctl,
1182 .bdrv_aio_ioctl = hdev_aio_ioctl,
1183 #endif
1186 #ifdef __linux__
1187 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1189 BDRVRawState *s = bs->opaque;
1190 int ret;
1192 posix_aio_init();
1194 s->type = FTYPE_FD;
1196 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1197 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1198 if (ret)
1199 return ret;
1201 /* close fd so that we can reopen it as needed */
1202 close(s->fd);
1203 s->fd = -1;
1204 s->fd_media_changed = 1;
1206 return 0;
1209 static int floppy_probe_device(const char *filename)
1211 if (strstart(filename, "/dev/fd", NULL))
1212 return 100;
1213 return 0;
1217 static int floppy_is_inserted(BlockDriverState *bs)
1219 return fd_open(bs) >= 0;
1222 static int floppy_media_changed(BlockDriverState *bs)
1224 BDRVRawState *s = bs->opaque;
1225 int ret;
1228 * XXX: we do not have a true media changed indication.
1229 * It does not work if the floppy is changed without trying to read it.
1231 fd_open(bs);
1232 ret = s->fd_media_changed;
1233 s->fd_media_changed = 0;
1234 #ifdef DEBUG_FLOPPY
1235 printf("Floppy changed=%d\n", ret);
1236 #endif
1237 return ret;
1240 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1242 BDRVRawState *s = bs->opaque;
1243 int fd;
1245 if (s->fd >= 0) {
1246 close(s->fd);
1247 s->fd = -1;
1249 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1250 if (fd >= 0) {
1251 if (ioctl(fd, FDEJECT, 0) < 0)
1252 perror("FDEJECT");
1253 close(fd);
1256 return 0;
1259 static BlockDriver bdrv_host_floppy = {
1260 .format_name = "host_floppy",
1261 .instance_size = sizeof(BDRVRawState),
1262 .bdrv_probe_device = floppy_probe_device,
1263 .bdrv_open = floppy_open,
1264 .bdrv_close = raw_close,
1265 .bdrv_create = hdev_create,
1266 .bdrv_flush = raw_flush,
1268 .bdrv_aio_readv = raw_aio_readv,
1269 .bdrv_aio_writev = raw_aio_writev,
1271 .bdrv_read = raw_read,
1272 .bdrv_write = raw_write,
1273 .bdrv_getlength = raw_getlength,
1275 /* removable device support */
1276 .bdrv_is_inserted = floppy_is_inserted,
1277 .bdrv_media_changed = floppy_media_changed,
1278 .bdrv_eject = floppy_eject,
1281 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1283 BDRVRawState *s = bs->opaque;
1285 s->type = FTYPE_CD;
1287 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1288 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1291 static int cdrom_probe_device(const char *filename)
1293 if (strstart(filename, "/dev/cd", NULL))
1294 return 100;
1295 return 0;
1298 static int cdrom_is_inserted(BlockDriverState *bs)
1300 BDRVRawState *s = bs->opaque;
1301 int ret;
1303 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1304 if (ret == CDS_DISC_OK)
1305 return 1;
1306 return 0;
1309 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1311 BDRVRawState *s = bs->opaque;
1313 if (eject_flag) {
1314 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1315 perror("CDROMEJECT");
1316 } else {
1317 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1318 perror("CDROMEJECT");
1321 return 0;
1324 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1326 BDRVRawState *s = bs->opaque;
1328 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1330 * Note: an error can happen if the distribution automatically
1331 * mounts the CD-ROM
1333 /* perror("CDROM_LOCKDOOR"); */
1336 return 0;
1339 static BlockDriver bdrv_host_cdrom = {
1340 .format_name = "host_cdrom",
1341 .instance_size = sizeof(BDRVRawState),
1342 .bdrv_probe_device = cdrom_probe_device,
1343 .bdrv_open = cdrom_open,
1344 .bdrv_close = raw_close,
1345 .bdrv_create = hdev_create,
1346 .bdrv_flush = raw_flush,
1348 .bdrv_aio_readv = raw_aio_readv,
1349 .bdrv_aio_writev = raw_aio_writev,
1351 .bdrv_read = raw_read,
1352 .bdrv_write = raw_write,
1353 .bdrv_getlength = raw_getlength,
1355 /* removable device support */
1356 .bdrv_is_inserted = cdrom_is_inserted,
1357 .bdrv_eject = cdrom_eject,
1358 .bdrv_set_locked = cdrom_set_locked,
1360 /* generic scsi device */
1361 .bdrv_ioctl = hdev_ioctl,
1362 .bdrv_aio_ioctl = hdev_aio_ioctl,
1364 #endif /* __linux__ */
1366 #ifdef __FreeBSD__
1367 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1369 BDRVRawState *s = bs->opaque;
1370 int ret;
1372 s->type = FTYPE_CD;
1374 ret = raw_open_common(bs, filename, flags, 0);
1375 if (ret)
1376 return ret;
1378 /* make sure the door isnt locked at this time */
1379 ioctl(s->fd, CDIOCALLOW);
1380 return 0;
1383 static int cdrom_probe_device(const char *filename)
1385 if (strstart(filename, "/dev/cd", NULL) ||
1386 strstart(filename, "/dev/acd", NULL))
1387 return 100;
1388 return 0;
1391 static int cdrom_reopen(BlockDriverState *bs)
1393 BDRVRawState *s = bs->opaque;
1394 int fd;
1397 * Force reread of possibly changed/newly loaded disc,
1398 * FreeBSD seems to not notice sometimes...
1400 if (s->fd >= 0)
1401 close(s->fd);
1402 fd = open(bs->filename, s->open_flags, 0644);
1403 if (fd < 0) {
1404 s->fd = -1;
1405 return -EIO;
1407 s->fd = fd;
1409 /* make sure the door isnt locked at this time */
1410 ioctl(s->fd, CDIOCALLOW);
1411 return 0;
1414 static int cdrom_is_inserted(BlockDriverState *bs)
1416 return raw_getlength(bs) > 0;
1419 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1421 BDRVRawState *s = bs->opaque;
1423 if (s->fd < 0)
1424 return -ENOTSUP;
1426 (void) ioctl(s->fd, CDIOCALLOW);
1428 if (eject_flag) {
1429 if (ioctl(s->fd, CDIOCEJECT) < 0)
1430 perror("CDIOCEJECT");
1431 } else {
1432 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1433 perror("CDIOCCLOSE");
1436 if (cdrom_reopen(bs) < 0)
1437 return -ENOTSUP;
1438 return 0;
1441 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1443 BDRVRawState *s = bs->opaque;
1445 if (s->fd < 0)
1446 return -ENOTSUP;
1447 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1449 * Note: an error can happen if the distribution automatically
1450 * mounts the CD-ROM
1452 /* perror("CDROM_LOCKDOOR"); */
1455 return 0;
1458 static BlockDriver bdrv_host_cdrom = {
1459 .format_name = "host_cdrom",
1460 .instance_size = sizeof(BDRVRawState),
1461 .bdrv_probe_device = cdrom_probe_device,
1462 .bdrv_open = cdrom_open,
1463 .bdrv_close = raw_close,
1464 .bdrv_create = hdev_create,
1465 .bdrv_flush = raw_flush,
1467 .bdrv_aio_readv = raw_aio_readv,
1468 .bdrv_aio_writev = raw_aio_writev,
1470 .bdrv_read = raw_read,
1471 .bdrv_write = raw_write,
1472 .bdrv_getlength = raw_getlength,
1474 /* removable device support */
1475 .bdrv_is_inserted = cdrom_is_inserted,
1476 .bdrv_eject = cdrom_eject,
1477 .bdrv_set_locked = cdrom_set_locked,
1479 #endif /* __FreeBSD__ */
1481 static void bdrv_raw_init(void)
1484 * Register all the drivers. Note that order is important, the driver
1485 * registered last will get probed first.
1487 bdrv_register(&bdrv_raw);
1488 bdrv_register(&bdrv_host_device);
1489 #ifdef __linux__
1490 bdrv_register(&bdrv_host_floppy);
1491 bdrv_register(&bdrv_host_cdrom);
1492 #endif
1493 #ifdef __FreeBSD__
1494 bdrv_register(&bdrv_host_cdrom);
1495 #endif
1498 block_init(bdrv_raw_init);