linux-user: check some parameters for some socket syscalls.
[qemu.git] / block / raw-posix.c
blob8b1e67c0634176a073e8e17916184c4cec4ff835
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 #ifdef CONFIG_AIO
30 #include "posix-aio-compat.h"
31 #endif
33 #ifdef CONFIG_COCOA
34 #include <paths.h>
35 #include <sys/param.h>
36 #include <IOKit/IOKitLib.h>
37 #include <IOKit/IOBSD.h>
38 #include <IOKit/storage/IOMediaBSDClient.h>
39 #include <IOKit/storage/IOMedia.h>
40 #include <IOKit/storage/IOCDMedia.h>
41 //#include <IOKit/storage/IOCDTypes.h>
42 #include <CoreFoundation/CoreFoundation.h>
43 #endif
45 #ifdef __sun__
46 #define _POSIX_PTHREAD_SEMANTICS 1
47 #include <signal.h>
48 #include <sys/dkio.h>
49 #endif
50 #ifdef __linux__
51 #include <sys/ioctl.h>
52 #include <linux/cdrom.h>
53 #include <linux/fd.h>
54 #endif
55 #ifdef __FreeBSD__
56 #include <signal.h>
57 #include <sys/disk.h>
58 #include <sys/cdio.h>
59 #endif
61 #ifdef __OpenBSD__
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
64 #include <sys/dkio.h>
65 #endif
67 #ifdef __DragonFly__
68 #include <sys/ioctl.h>
69 #include <sys/diskslice.h>
70 #endif
72 //#define DEBUG_FLOPPY
74 //#define DEBUG_BLOCK
75 #if defined(DEBUG_BLOCK)
76 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
77 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
78 #else
79 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
80 #endif
82 /* OS X does not have O_DSYNC */
83 #ifndef O_DSYNC
84 #define O_DSYNC O_SYNC
85 #endif
87 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
88 #ifndef O_DIRECT
89 #define O_DIRECT O_DSYNC
90 #endif
92 #define FTYPE_FILE 0
93 #define FTYPE_CD 1
94 #define FTYPE_FD 2
96 #define ALIGNED_BUFFER_SIZE (32 * 512)
98 /* if the FD is not accessed during that time (in ms), we try to
99 reopen it to see if the disk has been changed */
100 #define FD_OPEN_TIMEOUT 1000
102 typedef struct BDRVRawState {
103 int fd;
104 int type;
105 unsigned int lseek_err_cnt;
106 int open_flags;
107 #if defined(__linux__)
108 /* linux floppy specific */
109 int64_t fd_open_time;
110 int64_t fd_error_time;
111 int fd_got_error;
112 int fd_media_changed;
113 #endif
114 uint8_t* aligned_buf;
115 } BDRVRawState;
117 static int posix_aio_init(void);
119 static int fd_open(BlockDriverState *bs);
120 static int64_t raw_getlength(BlockDriverState *bs);
122 #if defined(__FreeBSD__)
123 static int cdrom_reopen(BlockDriverState *bs);
124 #endif
126 static int raw_open_common(BlockDriverState *bs, const char *filename,
127 int bdrv_flags, int open_flags)
129 BDRVRawState *s = bs->opaque;
130 int fd, ret;
132 posix_aio_init();
134 s->lseek_err_cnt = 0;
136 s->open_flags = open_flags | O_BINARY;
137 s->open_flags &= ~O_ACCMODE;
138 if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
139 s->open_flags |= O_RDWR;
140 } else {
141 s->open_flags |= O_RDONLY;
142 bs->read_only = 1;
145 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
146 * and O_DIRECT for no caching. */
147 if ((bdrv_flags & BDRV_O_NOCACHE))
148 s->open_flags |= O_DIRECT;
149 else if (!(bdrv_flags & BDRV_O_CACHE_WB))
150 s->open_flags |= O_DSYNC;
152 s->fd = -1;
153 fd = open(filename, s->open_flags, 0644);
154 if (fd < 0) {
155 ret = -errno;
156 if (ret == -EROFS)
157 ret = -EACCES;
158 return ret;
160 s->fd = fd;
161 s->aligned_buf = NULL;
162 if ((bdrv_flags & BDRV_O_NOCACHE)) {
163 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
164 if (s->aligned_buf == NULL) {
165 ret = -errno;
166 close(fd);
167 return ret;
170 return 0;
173 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
175 BDRVRawState *s = bs->opaque;
176 int open_flags = 0;
178 s->type = FTYPE_FILE;
179 if (flags & BDRV_O_CREAT)
180 open_flags = O_CREAT | O_TRUNC;
182 return raw_open_common(bs, filename, flags, open_flags);
185 /* XXX: use host sector size if necessary with:
186 #ifdef DIOCGSECTORSIZE
188 unsigned int sectorsize = 512;
189 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
190 sectorsize > bufsize)
191 bufsize = sectorsize;
193 #endif
194 #ifdef CONFIG_COCOA
195 u_int32_t blockSize = 512;
196 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
197 bufsize = blockSize;
199 #endif
203 * offset and count are in bytes, but must be multiples of 512 for files
204 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
206 * This function may be called without alignment if the caller ensures
207 * that O_DIRECT is not in effect.
209 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
210 uint8_t *buf, int count)
212 BDRVRawState *s = bs->opaque;
213 int ret;
215 ret = fd_open(bs);
216 if (ret < 0)
217 return ret;
219 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
220 ++(s->lseek_err_cnt);
221 if(s->lseek_err_cnt <= 10) {
222 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
223 "] lseek failed : %d = %s\n",
224 s->fd, bs->filename, offset, buf, count,
225 bs->total_sectors, errno, strerror(errno));
227 return -1;
229 s->lseek_err_cnt=0;
231 ret = read(s->fd, buf, count);
232 if (ret == count)
233 goto label__raw_read__success;
235 /* Allow reads beyond the end (needed for pwrite) */
236 if ((ret == 0) && bs->growable) {
237 int64_t size = raw_getlength(bs);
238 if (offset >= size) {
239 memset(buf, 0, count);
240 ret = count;
241 goto label__raw_read__success;
245 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
246 "] read failed %d : %d = %s\n",
247 s->fd, bs->filename, offset, buf, count,
248 bs->total_sectors, ret, errno, strerror(errno));
250 /* Try harder for CDrom. */
251 if (bs->type == BDRV_TYPE_CDROM) {
252 lseek(s->fd, offset, SEEK_SET);
253 ret = read(s->fd, buf, count);
254 if (ret == count)
255 goto label__raw_read__success;
256 lseek(s->fd, offset, SEEK_SET);
257 ret = read(s->fd, buf, count);
258 if (ret == count)
259 goto label__raw_read__success;
261 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
262 "] retry read failed %d : %d = %s\n",
263 s->fd, bs->filename, offset, buf, count,
264 bs->total_sectors, ret, errno, strerror(errno));
267 label__raw_read__success:
269 return (ret < 0) ? -errno : ret;
273 * offset and count are in bytes, but must be multiples of 512 for files
274 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
276 * This function may be called without alignment if the caller ensures
277 * that O_DIRECT is not in effect.
279 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
280 const uint8_t *buf, int count)
282 BDRVRawState *s = bs->opaque;
283 int ret;
285 ret = fd_open(bs);
286 if (ret < 0)
287 return -errno;
289 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
290 ++(s->lseek_err_cnt);
291 if(s->lseek_err_cnt) {
292 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
293 PRId64 "] lseek failed : %d = %s\n",
294 s->fd, bs->filename, offset, buf, count,
295 bs->total_sectors, errno, strerror(errno));
297 return -EIO;
299 s->lseek_err_cnt = 0;
301 ret = write(s->fd, buf, count);
302 if (ret == count)
303 goto label__raw_write__success;
305 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
306 "] write failed %d : %d = %s\n",
307 s->fd, bs->filename, offset, buf, count,
308 bs->total_sectors, ret, errno, strerror(errno));
310 label__raw_write__success:
312 return (ret < 0) ? -errno : ret;
317 * offset and count are in bytes and possibly not aligned. For files opened
318 * with O_DIRECT, necessary alignments are ensured before calling
319 * raw_pread_aligned to do the actual read.
321 static int raw_pread(BlockDriverState *bs, int64_t offset,
322 uint8_t *buf, int count)
324 BDRVRawState *s = bs->opaque;
325 int size, ret, shift, sum;
327 sum = 0;
329 if (s->aligned_buf != NULL) {
331 if (offset & 0x1ff) {
332 /* align offset on a 512 bytes boundary */
334 shift = offset & 0x1ff;
335 size = (shift + count + 0x1ff) & ~0x1ff;
336 if (size > ALIGNED_BUFFER_SIZE)
337 size = ALIGNED_BUFFER_SIZE;
338 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
339 if (ret < 0)
340 return ret;
342 size = 512 - shift;
343 if (size > count)
344 size = count;
345 memcpy(buf, s->aligned_buf + shift, size);
347 buf += size;
348 offset += size;
349 count -= size;
350 sum += size;
352 if (count == 0)
353 return sum;
355 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
357 /* read on aligned buffer */
359 while (count) {
361 size = (count + 0x1ff) & ~0x1ff;
362 if (size > ALIGNED_BUFFER_SIZE)
363 size = ALIGNED_BUFFER_SIZE;
365 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
366 if (ret < 0)
367 return ret;
369 size = ret;
370 if (size > count)
371 size = count;
373 memcpy(buf, s->aligned_buf, size);
375 buf += size;
376 offset += size;
377 count -= size;
378 sum += size;
381 return sum;
385 return raw_pread_aligned(bs, offset, buf, count) + sum;
388 static int raw_read(BlockDriverState *bs, int64_t sector_num,
389 uint8_t *buf, int nb_sectors)
391 int ret;
393 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
394 if (ret == (nb_sectors * 512))
395 ret = 0;
396 return ret;
400 * offset and count are in bytes and possibly not aligned. For files opened
401 * with O_DIRECT, necessary alignments are ensured before calling
402 * raw_pwrite_aligned to do the actual write.
404 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
405 const uint8_t *buf, int count)
407 BDRVRawState *s = bs->opaque;
408 int size, ret, shift, sum;
410 sum = 0;
412 if (s->aligned_buf != NULL) {
414 if (offset & 0x1ff) {
415 /* align offset on a 512 bytes boundary */
416 shift = offset & 0x1ff;
417 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
418 if (ret < 0)
419 return ret;
421 size = 512 - shift;
422 if (size > count)
423 size = count;
424 memcpy(s->aligned_buf + shift, buf, size);
426 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
427 if (ret < 0)
428 return ret;
430 buf += size;
431 offset += size;
432 count -= size;
433 sum += size;
435 if (count == 0)
436 return sum;
438 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
440 while ((size = (count & ~0x1ff)) != 0) {
442 if (size > ALIGNED_BUFFER_SIZE)
443 size = ALIGNED_BUFFER_SIZE;
445 memcpy(s->aligned_buf, buf, size);
447 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
448 if (ret < 0)
449 return ret;
451 buf += ret;
452 offset += ret;
453 count -= ret;
454 sum += ret;
456 /* here, count < 512 because (count & ~0x1ff) == 0 */
457 if (count) {
458 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
459 if (ret < 0)
460 return ret;
461 memcpy(s->aligned_buf, buf, count);
463 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
464 if (ret < 0)
465 return ret;
466 if (count < ret)
467 ret = count;
469 sum += ret;
471 return sum;
474 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
477 static int raw_write(BlockDriverState *bs, int64_t sector_num,
478 const uint8_t *buf, int nb_sectors)
480 int ret;
481 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
482 if (ret == (nb_sectors * 512))
483 ret = 0;
484 return ret;
487 #ifdef CONFIG_AIO
488 /***********************************************************/
489 /* Unix AIO using POSIX AIO */
491 typedef struct RawAIOCB {
492 BlockDriverAIOCB common;
493 struct qemu_paiocb aiocb;
494 struct RawAIOCB *next;
495 int ret;
496 } RawAIOCB;
498 typedef struct PosixAioState
500 int rfd, wfd;
501 RawAIOCB *first_aio;
502 } PosixAioState;
504 static void posix_aio_read(void *opaque)
506 PosixAioState *s = opaque;
507 RawAIOCB *acb, **pacb;
508 int ret;
509 ssize_t len;
511 /* read all bytes from signal pipe */
512 for (;;) {
513 char bytes[16];
515 len = read(s->rfd, bytes, sizeof(bytes));
516 if (len == -1 && errno == EINTR)
517 continue; /* try again */
518 if (len == sizeof(bytes))
519 continue; /* more to read */
520 break;
523 for(;;) {
524 pacb = &s->first_aio;
525 for(;;) {
526 acb = *pacb;
527 if (!acb)
528 goto the_end;
529 ret = qemu_paio_error(&acb->aiocb);
530 if (ret == ECANCELED) {
531 /* remove the request */
532 *pacb = acb->next;
533 qemu_aio_release(acb);
534 } else if (ret != EINPROGRESS) {
535 /* end of aio */
536 if (ret == 0) {
537 ret = qemu_paio_return(&acb->aiocb);
538 if (ret == acb->aiocb.aio_nbytes)
539 ret = 0;
540 else
541 ret = -EINVAL;
542 } else {
543 ret = -ret;
545 /* remove the request */
546 *pacb = acb->next;
547 /* call the callback */
548 acb->common.cb(acb->common.opaque, ret);
549 qemu_aio_release(acb);
550 break;
551 } else {
552 pacb = &acb->next;
556 the_end: ;
559 static int posix_aio_flush(void *opaque)
561 PosixAioState *s = opaque;
562 return !!s->first_aio;
565 static PosixAioState *posix_aio_state;
567 static void aio_signal_handler(int signum)
569 if (posix_aio_state) {
570 char byte = 0;
572 write(posix_aio_state->wfd, &byte, sizeof(byte));
575 qemu_service_io();
578 static int posix_aio_init(void)
580 struct sigaction act;
581 PosixAioState *s;
582 int fds[2];
583 struct qemu_paioinit ai;
585 if (posix_aio_state)
586 return 0;
588 s = qemu_malloc(sizeof(PosixAioState));
590 sigfillset(&act.sa_mask);
591 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
592 act.sa_handler = aio_signal_handler;
593 sigaction(SIGUSR2, &act, NULL);
595 s->first_aio = NULL;
596 if (pipe(fds) == -1) {
597 fprintf(stderr, "failed to create pipe\n");
598 return -errno;
601 s->rfd = fds[0];
602 s->wfd = fds[1];
604 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
605 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
607 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
609 memset(&ai, 0, sizeof(ai));
610 ai.aio_threads = 64;
611 ai.aio_num = 64;
612 qemu_paio_init(&ai);
614 posix_aio_state = s;
616 return 0;
619 static void raw_aio_remove(RawAIOCB *acb)
621 RawAIOCB **pacb;
623 /* remove the callback from the queue */
624 pacb = &posix_aio_state->first_aio;
625 for(;;) {
626 if (*pacb == NULL) {
627 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
628 break;
629 } else if (*pacb == acb) {
630 *pacb = acb->next;
631 qemu_aio_release(acb);
632 break;
634 pacb = &(*pacb)->next;
638 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
640 int ret;
641 RawAIOCB *acb = (RawAIOCB *)blockacb;
643 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
644 if (ret == QEMU_PAIO_NOTCANCELED) {
645 /* fail safe: if the aio could not be canceled, we wait for
646 it */
647 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
650 raw_aio_remove(acb);
653 static AIOPool raw_aio_pool = {
654 .aiocb_size = sizeof(RawAIOCB),
655 .cancel = raw_aio_cancel,
658 static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,
659 QEMUIOVector *qiov, int nb_sectors,
660 BlockDriverCompletionFunc *cb, void *opaque)
662 BDRVRawState *s = bs->opaque;
663 RawAIOCB *acb;
665 if (fd_open(bs) < 0)
666 return NULL;
668 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
669 if (!acb)
670 return NULL;
671 acb->aiocb.aio_fildes = s->fd;
672 acb->aiocb.ev_signo = SIGUSR2;
673 acb->aiocb.aio_iov = qiov->iov;
674 acb->aiocb.aio_niov = qiov->niov;
675 acb->aiocb.aio_nbytes = nb_sectors * 512;
676 acb->aiocb.aio_offset = sector_num * 512;
677 acb->aiocb.aio_flags = 0;
680 * If O_DIRECT is used the buffer needs to be aligned on a sector
681 * boundary. Tell the low level code to ensure that in case it's
682 * not done yet.
684 if (s->aligned_buf)
685 acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;
687 acb->next = posix_aio_state->first_aio;
688 posix_aio_state->first_aio = acb;
689 return acb;
692 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
693 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
694 BlockDriverCompletionFunc *cb, void *opaque)
696 RawAIOCB *acb;
698 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
699 if (!acb)
700 return NULL;
701 if (qemu_paio_read(&acb->aiocb) < 0) {
702 raw_aio_remove(acb);
703 return NULL;
705 return &acb->common;
708 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
709 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
710 BlockDriverCompletionFunc *cb, void *opaque)
712 RawAIOCB *acb;
714 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
715 if (!acb)
716 return NULL;
717 if (qemu_paio_write(&acb->aiocb) < 0) {
718 raw_aio_remove(acb);
719 return NULL;
721 return &acb->common;
723 #else /* CONFIG_AIO */
724 static int posix_aio_init(void)
726 return 0;
728 #endif /* CONFIG_AIO */
731 static void raw_close(BlockDriverState *bs)
733 BDRVRawState *s = bs->opaque;
734 if (s->fd >= 0) {
735 close(s->fd);
736 s->fd = -1;
737 if (s->aligned_buf != NULL)
738 qemu_free(s->aligned_buf);
742 static int raw_truncate(BlockDriverState *bs, int64_t offset)
744 BDRVRawState *s = bs->opaque;
745 if (s->type != FTYPE_FILE)
746 return -ENOTSUP;
747 if (ftruncate(s->fd, offset) < 0)
748 return -errno;
749 return 0;
752 #ifdef __OpenBSD__
753 static int64_t raw_getlength(BlockDriverState *bs)
755 BDRVRawState *s = bs->opaque;
756 int fd = s->fd;
757 struct stat st;
759 if (fstat(fd, &st))
760 return -1;
761 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
762 struct disklabel dl;
764 if (ioctl(fd, DIOCGDINFO, &dl))
765 return -1;
766 return (uint64_t)dl.d_secsize *
767 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
768 } else
769 return st.st_size;
771 #else /* !__OpenBSD__ */
772 static int64_t raw_getlength(BlockDriverState *bs)
774 BDRVRawState *s = bs->opaque;
775 int fd = s->fd;
776 int64_t size;
777 #ifdef HOST_BSD
778 struct stat sb;
779 #ifdef __FreeBSD__
780 int reopened = 0;
781 #endif
782 #endif
783 #ifdef __sun__
784 struct dk_minfo minfo;
785 int rv;
786 #endif
787 int ret;
789 ret = fd_open(bs);
790 if (ret < 0)
791 return ret;
793 #ifdef HOST_BSD
794 #ifdef __FreeBSD__
795 again:
796 #endif
797 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
798 #ifdef DIOCGMEDIASIZE
799 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
800 #elif defined(DIOCGPART)
802 struct partinfo pi;
803 if (ioctl(fd, DIOCGPART, &pi) == 0)
804 size = pi.media_size;
805 else
806 size = 0;
808 if (size == 0)
809 #endif
810 #ifdef CONFIG_COCOA
811 size = LONG_LONG_MAX;
812 #else
813 size = lseek(fd, 0LL, SEEK_END);
814 #endif
815 #ifdef __FreeBSD__
816 switch(s->type) {
817 case FTYPE_CD:
818 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
819 if (size == 2048LL * (unsigned)-1)
820 size = 0;
821 /* XXX no disc? maybe we need to reopen... */
822 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
823 reopened = 1;
824 goto again;
827 #endif
828 } else
829 #endif
830 #ifdef __sun__
832 * use the DKIOCGMEDIAINFO ioctl to read the size.
834 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
835 if ( rv != -1 ) {
836 size = minfo.dki_lbsize * minfo.dki_capacity;
837 } else /* there are reports that lseek on some devices
838 fails, but irc discussion said that contingency
839 on contingency was overkill */
840 #endif
842 size = lseek(fd, 0, SEEK_END);
844 return size;
846 #endif
848 static int raw_create(const char *filename, QEMUOptionParameter *options)
850 int fd;
851 int64_t total_size = 0;
853 /* Read out options */
854 while (options && options->name) {
855 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
856 total_size = options->value.n / 512;
858 options++;
861 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
862 0644);
863 if (fd < 0)
864 return -EIO;
865 ftruncate(fd, total_size * 512);
866 close(fd);
867 return 0;
870 static void raw_flush(BlockDriverState *bs)
872 BDRVRawState *s = bs->opaque;
873 fsync(s->fd);
877 static QEMUOptionParameter raw_create_options[] = {
879 .name = BLOCK_OPT_SIZE,
880 .type = OPT_SIZE,
881 .help = "Virtual disk size"
883 { NULL }
886 static BlockDriver bdrv_raw = {
887 .format_name = "raw",
888 .instance_size = sizeof(BDRVRawState),
889 .bdrv_probe = NULL, /* no probe for protocols */
890 .bdrv_open = raw_open,
891 .bdrv_read = raw_read,
892 .bdrv_write = raw_write,
893 .bdrv_close = raw_close,
894 .bdrv_create = raw_create,
895 .bdrv_flush = raw_flush,
897 #ifdef CONFIG_AIO
898 .bdrv_aio_readv = raw_aio_readv,
899 .bdrv_aio_writev = raw_aio_writev,
900 #endif
902 .bdrv_truncate = raw_truncate,
903 .bdrv_getlength = raw_getlength,
905 .create_options = raw_create_options,
906 .protocol_name = "file",
909 /***********************************************/
910 /* host device */
912 #ifdef CONFIG_COCOA
913 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
914 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
916 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
918 kern_return_t kernResult;
919 mach_port_t masterPort;
920 CFMutableDictionaryRef classesToMatch;
922 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
923 if ( KERN_SUCCESS != kernResult ) {
924 printf( "IOMasterPort returned %d\n", kernResult );
927 classesToMatch = IOServiceMatching( kIOCDMediaClass );
928 if ( classesToMatch == NULL ) {
929 printf( "IOServiceMatching returned a NULL dictionary.\n" );
930 } else {
931 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
933 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
934 if ( KERN_SUCCESS != kernResult )
936 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
939 return kernResult;
942 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
944 io_object_t nextMedia;
945 kern_return_t kernResult = KERN_FAILURE;
946 *bsdPath = '\0';
947 nextMedia = IOIteratorNext( mediaIterator );
948 if ( nextMedia )
950 CFTypeRef bsdPathAsCFString;
951 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
952 if ( bsdPathAsCFString ) {
953 size_t devPathLength;
954 strcpy( bsdPath, _PATH_DEV );
955 strcat( bsdPath, "r" );
956 devPathLength = strlen( bsdPath );
957 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
958 kernResult = KERN_SUCCESS;
960 CFRelease( bsdPathAsCFString );
962 IOObjectRelease( nextMedia );
965 return kernResult;
968 #endif
970 static int hdev_probe_device(const char *filename)
972 struct stat st;
974 /* allow a dedicated CD-ROM driver to match with a higher priority */
975 if (strstart(filename, "/dev/cdrom", NULL))
976 return 50;
978 if (stat(filename, &st) >= 0 &&
979 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
980 return 100;
983 return 0;
986 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
988 BDRVRawState *s = bs->opaque;
990 #ifdef CONFIG_COCOA
991 if (strstart(filename, "/dev/cdrom", NULL)) {
992 kern_return_t kernResult;
993 io_iterator_t mediaIterator;
994 char bsdPath[ MAXPATHLEN ];
995 int fd;
997 kernResult = FindEjectableCDMedia( &mediaIterator );
998 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1000 if ( bsdPath[ 0 ] != '\0' ) {
1001 strcat(bsdPath,"s0");
1002 /* some CDs don't have a partition 0 */
1003 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1004 if (fd < 0) {
1005 bsdPath[strlen(bsdPath)-1] = '1';
1006 } else {
1007 close(fd);
1009 filename = bsdPath;
1012 if ( mediaIterator )
1013 IOObjectRelease( mediaIterator );
1015 #endif
1017 s->type = FTYPE_FILE;
1018 #if defined(__linux__) && defined(CONFIG_AIO)
1019 if (strstart(filename, "/dev/sg", NULL)) {
1020 bs->sg = 1;
1022 #endif
1024 return raw_open_common(bs, filename, flags, 0);
1027 #if defined(__linux__)
1028 /* Note: we do not have a reliable method to detect if the floppy is
1029 present. The current method is to try to open the floppy at every
1030 I/O and to keep it opened during a few hundreds of ms. */
1031 static int fd_open(BlockDriverState *bs)
1033 BDRVRawState *s = bs->opaque;
1034 int last_media_present;
1036 if (s->type != FTYPE_FD)
1037 return 0;
1038 last_media_present = (s->fd >= 0);
1039 if (s->fd >= 0 &&
1040 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1041 close(s->fd);
1042 s->fd = -1;
1043 #ifdef DEBUG_FLOPPY
1044 printf("Floppy closed\n");
1045 #endif
1047 if (s->fd < 0) {
1048 if (s->fd_got_error &&
1049 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1050 #ifdef DEBUG_FLOPPY
1051 printf("No floppy (open delayed)\n");
1052 #endif
1053 return -EIO;
1055 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1056 if (s->fd < 0) {
1057 s->fd_error_time = qemu_get_clock(rt_clock);
1058 s->fd_got_error = 1;
1059 if (last_media_present)
1060 s->fd_media_changed = 1;
1061 #ifdef DEBUG_FLOPPY
1062 printf("No floppy\n");
1063 #endif
1064 return -EIO;
1066 #ifdef DEBUG_FLOPPY
1067 printf("Floppy opened\n");
1068 #endif
1070 if (!last_media_present)
1071 s->fd_media_changed = 1;
1072 s->fd_open_time = qemu_get_clock(rt_clock);
1073 s->fd_got_error = 0;
1074 return 0;
1077 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1079 BDRVRawState *s = bs->opaque;
1081 return ioctl(s->fd, req, buf);
1084 #ifdef CONFIG_AIO
1085 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1086 unsigned long int req, void *buf,
1087 BlockDriverCompletionFunc *cb, void *opaque)
1089 BDRVRawState *s = bs->opaque;
1090 RawAIOCB *acb;
1092 if (fd_open(bs) < 0)
1093 return NULL;
1095 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
1096 if (!acb)
1097 return NULL;
1098 acb->aiocb.aio_fildes = s->fd;
1099 acb->aiocb.ev_signo = SIGUSR2;
1100 acb->aiocb.aio_offset = 0;
1101 acb->aiocb.aio_flags = 0;
1103 acb->next = posix_aio_state->first_aio;
1104 posix_aio_state->first_aio = acb;
1106 acb->aiocb.aio_ioctl_buf = buf;
1107 acb->aiocb.aio_ioctl_cmd = req;
1108 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1109 raw_aio_remove(acb);
1110 return NULL;
1113 return &acb->common;
1115 #endif
1117 #elif defined(__FreeBSD__)
1118 static int fd_open(BlockDriverState *bs)
1120 BDRVRawState *s = bs->opaque;
1122 /* this is just to ensure s->fd is sane (its called by io ops) */
1123 if (s->fd >= 0)
1124 return 0;
1125 return -EIO;
1127 #else /* !linux && !FreeBSD */
1129 static int fd_open(BlockDriverState *bs)
1131 return 0;
1134 #endif /* !linux && !FreeBSD */
1136 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1138 int fd;
1139 int ret = 0;
1140 struct stat stat_buf;
1141 int64_t total_size = 0;
1143 /* Read out options */
1144 while (options && options->name) {
1145 if (!strcmp(options->name, "size")) {
1146 total_size = options->value.n / 512;
1148 options++;
1151 fd = open(filename, O_WRONLY | O_BINARY);
1152 if (fd < 0)
1153 return -EIO;
1155 if (fstat(fd, &stat_buf) < 0)
1156 ret = -EIO;
1157 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1158 ret = -EIO;
1159 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1160 ret = -ENOSPC;
1162 close(fd);
1163 return ret;
1166 static BlockDriver bdrv_host_device = {
1167 .format_name = "host_device",
1168 .instance_size = sizeof(BDRVRawState),
1169 .bdrv_probe_device = hdev_probe_device,
1170 .bdrv_open = hdev_open,
1171 .bdrv_close = raw_close,
1172 .bdrv_create = hdev_create,
1173 .bdrv_flush = raw_flush,
1175 #ifdef CONFIG_AIO
1176 .bdrv_aio_readv = raw_aio_readv,
1177 .bdrv_aio_writev = raw_aio_writev,
1178 #endif
1180 .bdrv_read = raw_read,
1181 .bdrv_write = raw_write,
1182 .bdrv_getlength = raw_getlength,
1184 /* generic scsi device */
1185 #ifdef __linux__
1186 .bdrv_ioctl = hdev_ioctl,
1187 #ifdef CONFIG_AIO
1188 .bdrv_aio_ioctl = hdev_aio_ioctl,
1189 #endif
1190 #endif
1193 #ifdef __linux__
1194 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1196 BDRVRawState *s = bs->opaque;
1197 int ret;
1199 posix_aio_init();
1201 s->type = FTYPE_FD;
1203 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1204 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1205 if (ret)
1206 return ret;
1208 /* close fd so that we can reopen it as needed */
1209 close(s->fd);
1210 s->fd = -1;
1211 s->fd_media_changed = 1;
1213 return 0;
1216 static int floppy_probe_device(const char *filename)
1218 if (strstart(filename, "/dev/fd", NULL))
1219 return 100;
1220 return 0;
1224 static int floppy_is_inserted(BlockDriverState *bs)
1226 return fd_open(bs) >= 0;
1229 static int floppy_media_changed(BlockDriverState *bs)
1231 BDRVRawState *s = bs->opaque;
1232 int ret;
1235 * XXX: we do not have a true media changed indication.
1236 * It does not work if the floppy is changed without trying to read it.
1238 fd_open(bs);
1239 ret = s->fd_media_changed;
1240 s->fd_media_changed = 0;
1241 #ifdef DEBUG_FLOPPY
1242 printf("Floppy changed=%d\n", ret);
1243 #endif
1244 return ret;
1247 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1249 BDRVRawState *s = bs->opaque;
1250 int fd;
1252 if (s->fd >= 0) {
1253 close(s->fd);
1254 s->fd = -1;
1256 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1257 if (fd >= 0) {
1258 if (ioctl(fd, FDEJECT, 0) < 0)
1259 perror("FDEJECT");
1260 close(fd);
1263 return 0;
1266 static BlockDriver bdrv_host_floppy = {
1267 .format_name = "host_floppy",
1268 .instance_size = sizeof(BDRVRawState),
1269 .bdrv_probe_device = floppy_probe_device,
1270 .bdrv_open = floppy_open,
1271 .bdrv_close = raw_close,
1272 .bdrv_create = hdev_create,
1273 .bdrv_flush = raw_flush,
1275 #ifdef CONFIG_AIO
1276 .bdrv_aio_readv = raw_aio_readv,
1277 .bdrv_aio_writev = raw_aio_writev,
1278 #endif
1280 .bdrv_read = raw_read,
1281 .bdrv_write = raw_write,
1282 .bdrv_getlength = raw_getlength,
1284 /* removable device support */
1285 .bdrv_is_inserted = floppy_is_inserted,
1286 .bdrv_media_changed = floppy_media_changed,
1287 .bdrv_eject = floppy_eject,
1290 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1292 BDRVRawState *s = bs->opaque;
1294 s->type = FTYPE_CD;
1296 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1297 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1300 static int cdrom_probe_device(const char *filename)
1302 if (strstart(filename, "/dev/cd", NULL))
1303 return 100;
1304 return 0;
1307 static int cdrom_is_inserted(BlockDriverState *bs)
1309 BDRVRawState *s = bs->opaque;
1310 int ret;
1312 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1313 if (ret == CDS_DISC_OK)
1314 return 1;
1315 return 0;
1318 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1320 BDRVRawState *s = bs->opaque;
1322 if (eject_flag) {
1323 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1324 perror("CDROMEJECT");
1325 } else {
1326 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1327 perror("CDROMEJECT");
1330 return 0;
1333 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1335 BDRVRawState *s = bs->opaque;
1337 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1339 * Note: an error can happen if the distribution automatically
1340 * mounts the CD-ROM
1342 /* perror("CDROM_LOCKDOOR"); */
1345 return 0;
1348 static BlockDriver bdrv_host_cdrom = {
1349 .format_name = "host_cdrom",
1350 .instance_size = sizeof(BDRVRawState),
1351 .bdrv_probe_device = cdrom_probe_device,
1352 .bdrv_open = cdrom_open,
1353 .bdrv_close = raw_close,
1354 .bdrv_create = hdev_create,
1355 .bdrv_flush = raw_flush,
1357 #ifdef CONFIG_AIO
1358 .bdrv_aio_readv = raw_aio_readv,
1359 .bdrv_aio_writev = raw_aio_writev,
1360 #endif
1362 .bdrv_read = raw_read,
1363 .bdrv_write = raw_write,
1364 .bdrv_getlength = raw_getlength,
1366 /* removable device support */
1367 .bdrv_is_inserted = cdrom_is_inserted,
1368 .bdrv_eject = cdrom_eject,
1369 .bdrv_set_locked = cdrom_set_locked,
1371 /* generic scsi device */
1372 .bdrv_ioctl = hdev_ioctl,
1373 #ifdef CONFIG_AIO
1374 .bdrv_aio_ioctl = hdev_aio_ioctl,
1375 #endif
1377 #endif /* __linux__ */
1379 #ifdef __FreeBSD__
1380 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1382 BDRVRawState *s = bs->opaque;
1383 int ret;
1385 s->type = FTYPE_CD;
1387 ret = raw_open_common(bs, filename, flags, 0);
1388 if (ret)
1389 return ret;
1391 /* make sure the door isnt locked at this time */
1392 ioctl(s->fd, CDIOCALLOW);
1393 return 0;
1396 static int cdrom_probe_device(const char *filename)
1398 if (strstart(filename, "/dev/cd", NULL) ||
1399 strstart(filename, "/dev/acd", NULL))
1400 return 100;
1401 return 0;
1404 static int cdrom_reopen(BlockDriverState *bs)
1406 BDRVRawState *s = bs->opaque;
1407 int fd;
1410 * Force reread of possibly changed/newly loaded disc,
1411 * FreeBSD seems to not notice sometimes...
1413 if (s->fd >= 0)
1414 close(s->fd);
1415 fd = open(bs->filename, s->open_flags, 0644);
1416 if (fd < 0) {
1417 s->fd = -1;
1418 return -EIO;
1420 s->fd = fd;
1422 /* make sure the door isnt locked at this time */
1423 ioctl(s->fd, CDIOCALLOW);
1424 return 0;
1427 static int cdrom_is_inserted(BlockDriverState *bs)
1429 return raw_getlength(bs) > 0;
1432 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1434 BDRVRawState *s = bs->opaque;
1436 if (s->fd < 0)
1437 return -ENOTSUP;
1439 (void) ioctl(s->fd, CDIOCALLOW);
1441 if (eject_flag) {
1442 if (ioctl(s->fd, CDIOCEJECT) < 0)
1443 perror("CDIOCEJECT");
1444 } else {
1445 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1446 perror("CDIOCCLOSE");
1449 if (cdrom_reopen(bs) < 0)
1450 return -ENOTSUP;
1451 return 0;
1454 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1456 BDRVRawState *s = bs->opaque;
1458 if (s->fd < 0)
1459 return -ENOTSUP;
1460 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1462 * Note: an error can happen if the distribution automatically
1463 * mounts the CD-ROM
1465 /* perror("CDROM_LOCKDOOR"); */
1468 return 0;
1471 static BlockDriver bdrv_host_cdrom = {
1472 .format_name = "host_cdrom",
1473 .instance_size = sizeof(BDRVRawState),
1474 .bdrv_probe_device = cdrom_probe_device,
1475 .bdrv_open = cdrom_open,
1476 .bdrv_close = raw_close,
1477 .bdrv_create = hdev_create,
1478 .bdrv_flush = raw_flush,
1480 #ifdef CONFIG_AIO
1481 .bdrv_aio_readv = raw_aio_readv,
1482 .bdrv_aio_writev = raw_aio_writev,
1483 #endif
1485 .bdrv_read = raw_read,
1486 .bdrv_write = raw_write,
1487 .bdrv_getlength = raw_getlength,
1489 /* removable device support */
1490 .bdrv_is_inserted = cdrom_is_inserted,
1491 .bdrv_eject = cdrom_eject,
1492 .bdrv_set_locked = cdrom_set_locked,
1494 #endif /* __FreeBSD__ */
1496 static void bdrv_raw_init(void)
1499 * Register all the drivers. Note that order is important, the driver
1500 * registered last will get probed first.
1502 bdrv_register(&bdrv_raw);
1503 bdrv_register(&bdrv_host_device);
1504 #ifdef __linux__
1505 bdrv_register(&bdrv_host_floppy);
1506 bdrv_register(&bdrv_host_cdrom);
1507 #endif
1508 #ifdef __FreeBSD__
1509 bdrv_register(&bdrv_host_cdrom);
1510 #endif
1513 block_init(bdrv_raw_init);