l2_allocate: Write complete sectors
[armpft.git] / block / raw-posix.c
blobccb014a4d123c1d09ee670303cff4b9cbd8e29bf
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);
121 #if defined(__FreeBSD__)
122 static int cdrom_reopen(BlockDriverState *bs);
123 #endif
125 static int raw_open_common(BlockDriverState *bs, const char *filename,
126 int flags)
128 BDRVRawState *s = bs->opaque;
129 int fd, ret;
131 posix_aio_init();
133 s->lseek_err_cnt = 0;
135 s->open_flags |= O_BINARY;
136 s->open_flags &= ~O_ACCMODE;
137 if ((flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
138 s->open_flags |= O_RDWR;
139 } else {
140 s->open_flags |= O_RDONLY;
141 bs->read_only = 1;
144 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
145 * and O_DIRECT for no caching. */
146 if ((flags & BDRV_O_NOCACHE))
147 s->open_flags |= O_DIRECT;
148 else if (!(flags & BDRV_O_CACHE_WB))
149 s->open_flags |= O_DSYNC;
151 s->fd = -1;
152 fd = open(filename, s->open_flags, 0644);
153 if (fd < 0) {
154 ret = -errno;
155 if (ret == -EROFS)
156 ret = -EACCES;
157 return ret;
159 s->fd = fd;
160 s->aligned_buf = NULL;
161 if ((flags & BDRV_O_NOCACHE)) {
162 s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
163 if (s->aligned_buf == NULL) {
164 ret = -errno;
165 close(fd);
166 return ret;
169 return 0;
172 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
174 BDRVRawState *s = bs->opaque;
176 s->type = FTYPE_FILE;
177 if (flags & BDRV_O_CREAT)
178 s->open_flags |= O_CREAT | O_TRUNC;
180 return raw_open_common(bs, filename, flags);
183 /* XXX: use host sector size if necessary with:
184 #ifdef DIOCGSECTORSIZE
186 unsigned int sectorsize = 512;
187 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
188 sectorsize > bufsize)
189 bufsize = sectorsize;
191 #endif
192 #ifdef CONFIG_COCOA
193 u_int32_t blockSize = 512;
194 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
195 bufsize = blockSize;
197 #endif
201 * offset and count are in bytes, but must be multiples of 512 for files
202 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
204 * This function may be called without alignment if the caller ensures
205 * that O_DIRECT is not in effect.
207 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
208 uint8_t *buf, int count)
210 BDRVRawState *s = bs->opaque;
211 int ret;
213 ret = fd_open(bs);
214 if (ret < 0)
215 return ret;
217 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
218 ++(s->lseek_err_cnt);
219 if(s->lseek_err_cnt <= 10) {
220 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
221 "] lseek failed : %d = %s\n",
222 s->fd, bs->filename, offset, buf, count,
223 bs->total_sectors, errno, strerror(errno));
225 return -1;
227 s->lseek_err_cnt=0;
229 ret = read(s->fd, buf, count);
230 if (ret == count)
231 goto label__raw_read__success;
233 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
234 "] read failed %d : %d = %s\n",
235 s->fd, bs->filename, offset, buf, count,
236 bs->total_sectors, ret, errno, strerror(errno));
238 /* Try harder for CDrom. */
239 if (bs->type == BDRV_TYPE_CDROM) {
240 lseek(s->fd, offset, SEEK_SET);
241 ret = read(s->fd, buf, count);
242 if (ret == count)
243 goto label__raw_read__success;
244 lseek(s->fd, offset, SEEK_SET);
245 ret = read(s->fd, buf, count);
246 if (ret == count)
247 goto label__raw_read__success;
249 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
250 "] retry read failed %d : %d = %s\n",
251 s->fd, bs->filename, offset, buf, count,
252 bs->total_sectors, ret, errno, strerror(errno));
255 label__raw_read__success:
257 return (ret < 0) ? -errno : ret;
261 * offset and count are in bytes, but must be multiples of 512 for files
262 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
264 * This function may be called without alignment if the caller ensures
265 * that O_DIRECT is not in effect.
267 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
268 const uint8_t *buf, int count)
270 BDRVRawState *s = bs->opaque;
271 int ret;
273 ret = fd_open(bs);
274 if (ret < 0)
275 return -errno;
277 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
278 ++(s->lseek_err_cnt);
279 if(s->lseek_err_cnt) {
280 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
281 PRId64 "] lseek failed : %d = %s\n",
282 s->fd, bs->filename, offset, buf, count,
283 bs->total_sectors, errno, strerror(errno));
285 return -EIO;
287 s->lseek_err_cnt = 0;
289 ret = write(s->fd, buf, count);
290 if (ret == count)
291 goto label__raw_write__success;
293 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
294 "] write failed %d : %d = %s\n",
295 s->fd, bs->filename, offset, buf, count,
296 bs->total_sectors, ret, errno, strerror(errno));
298 label__raw_write__success:
300 return (ret < 0) ? -errno : ret;
305 * offset and count are in bytes and possibly not aligned. For files opened
306 * with O_DIRECT, necessary alignments are ensured before calling
307 * raw_pread_aligned to do the actual read.
309 static int raw_pread(BlockDriverState *bs, int64_t offset,
310 uint8_t *buf, int count)
312 BDRVRawState *s = bs->opaque;
313 int size, ret, shift, sum;
315 sum = 0;
317 if (s->aligned_buf != NULL) {
319 if (offset & 0x1ff) {
320 /* align offset on a 512 bytes boundary */
322 shift = offset & 0x1ff;
323 size = (shift + count + 0x1ff) & ~0x1ff;
324 if (size > ALIGNED_BUFFER_SIZE)
325 size = ALIGNED_BUFFER_SIZE;
326 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
327 if (ret < 0)
328 return ret;
330 size = 512 - shift;
331 if (size > count)
332 size = count;
333 memcpy(buf, s->aligned_buf + shift, size);
335 buf += size;
336 offset += size;
337 count -= size;
338 sum += size;
340 if (count == 0)
341 return sum;
343 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
345 /* read on aligned buffer */
347 while (count) {
349 size = (count + 0x1ff) & ~0x1ff;
350 if (size > ALIGNED_BUFFER_SIZE)
351 size = ALIGNED_BUFFER_SIZE;
353 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
354 if (ret < 0)
355 return ret;
357 size = ret;
358 if (size > count)
359 size = count;
361 memcpy(buf, s->aligned_buf, size);
363 buf += size;
364 offset += size;
365 count -= size;
366 sum += size;
369 return sum;
373 return raw_pread_aligned(bs, offset, buf, count) + sum;
376 static int raw_read(BlockDriverState *bs, int64_t sector_num,
377 uint8_t *buf, int nb_sectors)
379 int ret;
381 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
382 if (ret == (nb_sectors * 512))
383 ret = 0;
384 return ret;
388 * offset and count are in bytes and possibly not aligned. For files opened
389 * with O_DIRECT, necessary alignments are ensured before calling
390 * raw_pwrite_aligned to do the actual write.
392 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
393 const uint8_t *buf, int count)
395 BDRVRawState *s = bs->opaque;
396 int size, ret, shift, sum;
398 sum = 0;
400 if (s->aligned_buf != NULL) {
402 if (offset & 0x1ff) {
403 /* align offset on a 512 bytes boundary */
404 shift = offset & 0x1ff;
405 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
406 if (ret < 0)
407 return ret;
409 size = 512 - shift;
410 if (size > count)
411 size = count;
412 memcpy(s->aligned_buf + shift, buf, size);
414 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
415 if (ret < 0)
416 return ret;
418 buf += size;
419 offset += size;
420 count -= size;
421 sum += size;
423 if (count == 0)
424 return sum;
426 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
428 while ((size = (count & ~0x1ff)) != 0) {
430 if (size > ALIGNED_BUFFER_SIZE)
431 size = ALIGNED_BUFFER_SIZE;
433 memcpy(s->aligned_buf, buf, size);
435 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
436 if (ret < 0)
437 return ret;
439 buf += ret;
440 offset += ret;
441 count -= ret;
442 sum += ret;
444 /* here, count < 512 because (count & ~0x1ff) == 0 */
445 if (count) {
446 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
447 if (ret < 0)
448 return ret;
449 memcpy(s->aligned_buf, buf, count);
451 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
452 if (ret < 0)
453 return ret;
454 if (count < ret)
455 ret = count;
457 sum += ret;
459 return sum;
462 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
465 static int raw_write(BlockDriverState *bs, int64_t sector_num,
466 const uint8_t *buf, int nb_sectors)
468 int ret;
469 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
470 if (ret == (nb_sectors * 512))
471 ret = 0;
472 return ret;
475 #ifdef CONFIG_AIO
476 /***********************************************************/
477 /* Unix AIO using POSIX AIO */
479 typedef struct RawAIOCB {
480 BlockDriverAIOCB common;
481 struct qemu_paiocb aiocb;
482 struct RawAIOCB *next;
483 int ret;
484 } RawAIOCB;
486 typedef struct PosixAioState
488 int rfd, wfd;
489 RawAIOCB *first_aio;
490 } PosixAioState;
492 static void posix_aio_read(void *opaque)
494 PosixAioState *s = opaque;
495 RawAIOCB *acb, **pacb;
496 int ret;
497 ssize_t len;
499 /* read all bytes from signal pipe */
500 for (;;) {
501 char bytes[16];
503 len = read(s->rfd, bytes, sizeof(bytes));
504 if (len == -1 && errno == EINTR)
505 continue; /* try again */
506 if (len == sizeof(bytes))
507 continue; /* more to read */
508 break;
511 for(;;) {
512 pacb = &s->first_aio;
513 for(;;) {
514 acb = *pacb;
515 if (!acb)
516 goto the_end;
517 ret = qemu_paio_error(&acb->aiocb);
518 if (ret == ECANCELED) {
519 /* remove the request */
520 *pacb = acb->next;
521 qemu_aio_release(acb);
522 } else if (ret != EINPROGRESS) {
523 /* end of aio */
524 if (ret == 0) {
525 ret = qemu_paio_return(&acb->aiocb);
526 if (ret == acb->aiocb.aio_nbytes)
527 ret = 0;
528 else
529 ret = -EINVAL;
530 } else {
531 ret = -ret;
533 /* remove the request */
534 *pacb = acb->next;
535 /* call the callback */
536 acb->common.cb(acb->common.opaque, ret);
537 qemu_aio_release(acb);
538 break;
539 } else {
540 pacb = &acb->next;
544 the_end: ;
547 static int posix_aio_flush(void *opaque)
549 PosixAioState *s = opaque;
550 return !!s->first_aio;
553 static PosixAioState *posix_aio_state;
555 static void aio_signal_handler(int signum)
557 if (posix_aio_state) {
558 char byte = 0;
560 write(posix_aio_state->wfd, &byte, sizeof(byte));
563 qemu_service_io();
566 static int posix_aio_init(void)
568 struct sigaction act;
569 PosixAioState *s;
570 int fds[2];
571 struct qemu_paioinit ai;
573 if (posix_aio_state)
574 return 0;
576 s = qemu_malloc(sizeof(PosixAioState));
578 sigfillset(&act.sa_mask);
579 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
580 act.sa_handler = aio_signal_handler;
581 sigaction(SIGUSR2, &act, NULL);
583 s->first_aio = NULL;
584 if (pipe(fds) == -1) {
585 fprintf(stderr, "failed to create pipe\n");
586 return -errno;
589 s->rfd = fds[0];
590 s->wfd = fds[1];
592 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
593 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
595 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
597 memset(&ai, 0, sizeof(ai));
598 ai.aio_threads = 64;
599 ai.aio_num = 64;
600 qemu_paio_init(&ai);
602 posix_aio_state = s;
604 return 0;
607 static void raw_aio_remove(RawAIOCB *acb)
609 RawAIOCB **pacb;
611 /* remove the callback from the queue */
612 pacb = &posix_aio_state->first_aio;
613 for(;;) {
614 if (*pacb == NULL) {
615 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
616 break;
617 } else if (*pacb == acb) {
618 *pacb = acb->next;
619 qemu_aio_release(acb);
620 break;
622 pacb = &(*pacb)->next;
626 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
628 int ret;
629 RawAIOCB *acb = (RawAIOCB *)blockacb;
631 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
632 if (ret == QEMU_PAIO_NOTCANCELED) {
633 /* fail safe: if the aio could not be canceled, we wait for
634 it */
635 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
638 raw_aio_remove(acb);
641 static AIOPool raw_aio_pool = {
642 .aiocb_size = sizeof(RawAIOCB),
643 .cancel = raw_aio_cancel,
646 static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,
647 QEMUIOVector *qiov, int nb_sectors,
648 BlockDriverCompletionFunc *cb, void *opaque)
650 BDRVRawState *s = bs->opaque;
651 RawAIOCB *acb;
653 if (fd_open(bs) < 0)
654 return NULL;
656 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
657 if (!acb)
658 return NULL;
659 acb->aiocb.aio_fildes = s->fd;
660 acb->aiocb.ev_signo = SIGUSR2;
661 acb->aiocb.aio_iov = qiov->iov;
662 acb->aiocb.aio_niov = qiov->niov;
663 acb->aiocb.aio_nbytes = nb_sectors * 512;
664 acb->aiocb.aio_offset = sector_num * 512;
665 acb->aiocb.aio_flags = 0;
668 * If O_DIRECT is used the buffer needs to be aligned on a sector
669 * boundary. Tell the low level code to ensure that in case it's
670 * not done yet.
672 if (s->aligned_buf)
673 acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;
675 acb->next = posix_aio_state->first_aio;
676 posix_aio_state->first_aio = acb;
677 return acb;
680 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
681 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
682 BlockDriverCompletionFunc *cb, void *opaque)
684 RawAIOCB *acb;
686 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
687 if (!acb)
688 return NULL;
689 if (qemu_paio_read(&acb->aiocb) < 0) {
690 raw_aio_remove(acb);
691 return NULL;
693 return &acb->common;
696 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
697 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
698 BlockDriverCompletionFunc *cb, void *opaque)
700 RawAIOCB *acb;
702 acb = raw_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque);
703 if (!acb)
704 return NULL;
705 if (qemu_paio_write(&acb->aiocb) < 0) {
706 raw_aio_remove(acb);
707 return NULL;
709 return &acb->common;
711 #else /* CONFIG_AIO */
712 static int posix_aio_init(void)
714 return 0;
716 #endif /* CONFIG_AIO */
719 static void raw_close(BlockDriverState *bs)
721 BDRVRawState *s = bs->opaque;
722 if (s->fd >= 0) {
723 close(s->fd);
724 s->fd = -1;
725 if (s->aligned_buf != NULL)
726 qemu_free(s->aligned_buf);
730 static int raw_truncate(BlockDriverState *bs, int64_t offset)
732 BDRVRawState *s = bs->opaque;
733 if (s->type != FTYPE_FILE)
734 return -ENOTSUP;
735 if (ftruncate(s->fd, offset) < 0)
736 return -errno;
737 return 0;
740 #ifdef __OpenBSD__
741 static int64_t raw_getlength(BlockDriverState *bs)
743 BDRVRawState *s = bs->opaque;
744 int fd = s->fd;
745 struct stat st;
747 if (fstat(fd, &st))
748 return -1;
749 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
750 struct disklabel dl;
752 if (ioctl(fd, DIOCGDINFO, &dl))
753 return -1;
754 return (uint64_t)dl.d_secsize *
755 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
756 } else
757 return st.st_size;
759 #else /* !__OpenBSD__ */
760 static int64_t raw_getlength(BlockDriverState *bs)
762 BDRVRawState *s = bs->opaque;
763 int fd = s->fd;
764 int64_t size;
765 #ifdef HOST_BSD
766 struct stat sb;
767 #ifdef __FreeBSD__
768 int reopened = 0;
769 #endif
770 #endif
771 #ifdef __sun__
772 struct dk_minfo minfo;
773 int rv;
774 #endif
775 int ret;
777 ret = fd_open(bs);
778 if (ret < 0)
779 return ret;
781 #ifdef HOST_BSD
782 #ifdef __FreeBSD__
783 again:
784 #endif
785 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
786 #ifdef DIOCGMEDIASIZE
787 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
788 #elif defined(DIOCGPART)
790 struct partinfo pi;
791 if (ioctl(fd, DIOCGPART, &pi) == 0)
792 size = pi.media_size;
793 else
794 size = 0;
796 if (size == 0)
797 #endif
798 #ifdef CONFIG_COCOA
799 size = LONG_LONG_MAX;
800 #else
801 size = lseek(fd, 0LL, SEEK_END);
802 #endif
803 #ifdef __FreeBSD__
804 switch(s->type) {
805 case FTYPE_CD:
806 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
807 if (size == 2048LL * (unsigned)-1)
808 size = 0;
809 /* XXX no disc? maybe we need to reopen... */
810 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
811 reopened = 1;
812 goto again;
815 #endif
816 } else
817 #endif
818 #ifdef __sun__
820 * use the DKIOCGMEDIAINFO ioctl to read the size.
822 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
823 if ( rv != -1 ) {
824 size = minfo.dki_lbsize * minfo.dki_capacity;
825 } else /* there are reports that lseek on some devices
826 fails, but irc discussion said that contingency
827 on contingency was overkill */
828 #endif
830 size = lseek(fd, 0, SEEK_END);
832 return size;
834 #endif
836 static int raw_create(const char *filename, QEMUOptionParameter *options)
838 int fd;
839 int64_t total_size = 0;
841 /* Read out options */
842 while (options && options->name) {
843 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
844 total_size = options->value.n / 512;
846 options++;
849 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
850 0644);
851 if (fd < 0)
852 return -EIO;
853 ftruncate(fd, total_size * 512);
854 close(fd);
855 return 0;
858 static void raw_flush(BlockDriverState *bs)
860 BDRVRawState *s = bs->opaque;
861 fsync(s->fd);
865 static QEMUOptionParameter raw_create_options[] = {
867 .name = BLOCK_OPT_SIZE,
868 .type = OPT_SIZE,
869 .help = "Virtual disk size"
871 { NULL }
874 static BlockDriver bdrv_raw = {
875 .format_name = "raw",
876 .instance_size = sizeof(BDRVRawState),
877 .bdrv_probe = NULL, /* no probe for protocols */
878 .bdrv_open = raw_open,
879 .bdrv_read = raw_read,
880 .bdrv_write = raw_write,
881 .bdrv_close = raw_close,
882 .bdrv_create = raw_create,
883 .bdrv_flush = raw_flush,
885 #ifdef CONFIG_AIO
886 .bdrv_aio_readv = raw_aio_readv,
887 .bdrv_aio_writev = raw_aio_writev,
888 #endif
890 .bdrv_truncate = raw_truncate,
891 .bdrv_getlength = raw_getlength,
893 .create_options = raw_create_options,
896 /***********************************************/
897 /* host device */
899 #ifdef CONFIG_COCOA
900 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
901 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
903 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
905 kern_return_t kernResult;
906 mach_port_t masterPort;
907 CFMutableDictionaryRef classesToMatch;
909 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
910 if ( KERN_SUCCESS != kernResult ) {
911 printf( "IOMasterPort returned %d\n", kernResult );
914 classesToMatch = IOServiceMatching( kIOCDMediaClass );
915 if ( classesToMatch == NULL ) {
916 printf( "IOServiceMatching returned a NULL dictionary.\n" );
917 } else {
918 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
920 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
921 if ( KERN_SUCCESS != kernResult )
923 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
926 return kernResult;
929 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
931 io_object_t nextMedia;
932 kern_return_t kernResult = KERN_FAILURE;
933 *bsdPath = '\0';
934 nextMedia = IOIteratorNext( mediaIterator );
935 if ( nextMedia )
937 CFTypeRef bsdPathAsCFString;
938 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
939 if ( bsdPathAsCFString ) {
940 size_t devPathLength;
941 strcpy( bsdPath, _PATH_DEV );
942 strcat( bsdPath, "r" );
943 devPathLength = strlen( bsdPath );
944 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
945 kernResult = KERN_SUCCESS;
947 CFRelease( bsdPathAsCFString );
949 IOObjectRelease( nextMedia );
952 return kernResult;
955 #endif
957 static int hdev_probe_device(const char *filename)
959 struct stat st;
961 /* allow a dedicated CD-ROM driver to match with a higher priority */
962 if (strstart(filename, "/dev/cdrom", NULL))
963 return 50;
965 if (stat(filename, &st) >= 0 &&
966 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
967 return 100;
970 return 0;
973 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
975 BDRVRawState *s = bs->opaque;
977 #ifdef CONFIG_COCOA
978 if (strstart(filename, "/dev/cdrom", NULL)) {
979 kern_return_t kernResult;
980 io_iterator_t mediaIterator;
981 char bsdPath[ MAXPATHLEN ];
982 int fd;
984 kernResult = FindEjectableCDMedia( &mediaIterator );
985 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
987 if ( bsdPath[ 0 ] != '\0' ) {
988 strcat(bsdPath,"s0");
989 /* some CDs don't have a partition 0 */
990 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
991 if (fd < 0) {
992 bsdPath[strlen(bsdPath)-1] = '1';
993 } else {
994 close(fd);
996 filename = bsdPath;
999 if ( mediaIterator )
1000 IOObjectRelease( mediaIterator );
1002 #endif
1004 s->type = FTYPE_FILE;
1005 #if defined(__linux__) && defined(CONFIG_AIO)
1006 if (strstart(filename, "/dev/sg", NULL)) {
1007 bs->sg = 1;
1009 #endif
1011 return raw_open_common(bs, filename, flags);
1014 #if defined(__linux__)
1015 /* Note: we do not have a reliable method to detect if the floppy is
1016 present. The current method is to try to open the floppy at every
1017 I/O and to keep it opened during a few hundreds of ms. */
1018 static int fd_open(BlockDriverState *bs)
1020 BDRVRawState *s = bs->opaque;
1021 int last_media_present;
1023 if (s->type != FTYPE_FD)
1024 return 0;
1025 last_media_present = (s->fd >= 0);
1026 if (s->fd >= 0 &&
1027 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1028 close(s->fd);
1029 s->fd = -1;
1030 #ifdef DEBUG_FLOPPY
1031 printf("Floppy closed\n");
1032 #endif
1034 if (s->fd < 0) {
1035 if (s->fd_got_error &&
1036 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1037 #ifdef DEBUG_FLOPPY
1038 printf("No floppy (open delayed)\n");
1039 #endif
1040 return -EIO;
1042 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
1043 if (s->fd < 0) {
1044 s->fd_error_time = qemu_get_clock(rt_clock);
1045 s->fd_got_error = 1;
1046 if (last_media_present)
1047 s->fd_media_changed = 1;
1048 #ifdef DEBUG_FLOPPY
1049 printf("No floppy\n");
1050 #endif
1051 return -EIO;
1053 #ifdef DEBUG_FLOPPY
1054 printf("Floppy opened\n");
1055 #endif
1057 if (!last_media_present)
1058 s->fd_media_changed = 1;
1059 s->fd_open_time = qemu_get_clock(rt_clock);
1060 s->fd_got_error = 0;
1061 return 0;
1064 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1066 BDRVRawState *s = bs->opaque;
1068 return ioctl(s->fd, req, buf);
1071 #ifdef CONFIG_AIO
1072 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1073 unsigned long int req, void *buf,
1074 BlockDriverCompletionFunc *cb, void *opaque)
1076 BDRVRawState *s = bs->opaque;
1077 RawAIOCB *acb;
1079 if (fd_open(bs) < 0)
1080 return NULL;
1082 acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
1083 if (!acb)
1084 return NULL;
1085 acb->aiocb.aio_fildes = s->fd;
1086 acb->aiocb.ev_signo = SIGUSR2;
1087 acb->aiocb.aio_offset = 0;
1088 acb->aiocb.aio_flags = 0;
1090 acb->next = posix_aio_state->first_aio;
1091 posix_aio_state->first_aio = acb;
1093 acb->aiocb.aio_ioctl_buf = buf;
1094 acb->aiocb.aio_ioctl_cmd = req;
1095 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1096 raw_aio_remove(acb);
1097 return NULL;
1100 return &acb->common;
1102 #endif
1104 #elif defined(__FreeBSD__)
1105 static int fd_open(BlockDriverState *bs)
1107 BDRVRawState *s = bs->opaque;
1109 /* this is just to ensure s->fd is sane (its called by io ops) */
1110 if (s->fd >= 0)
1111 return 0;
1112 return -EIO;
1114 #else /* !linux && !FreeBSD */
1116 static int fd_open(BlockDriverState *bs)
1118 return 0;
1121 #endif /* !linux && !FreeBSD */
1123 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1125 int fd;
1126 int ret = 0;
1127 struct stat stat_buf;
1128 int64_t total_size = 0;
1130 /* Read out options */
1131 while (options && options->name) {
1132 if (!strcmp(options->name, "size")) {
1133 total_size = options->value.n / 512;
1135 options++;
1138 fd = open(filename, O_WRONLY | O_BINARY);
1139 if (fd < 0)
1140 return -EIO;
1142 if (fstat(fd, &stat_buf) < 0)
1143 ret = -EIO;
1144 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1145 ret = -EIO;
1146 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1147 ret = -ENOSPC;
1149 close(fd);
1150 return ret;
1153 static BlockDriver bdrv_host_device = {
1154 .format_name = "host_device",
1155 .instance_size = sizeof(BDRVRawState),
1156 .bdrv_probe_device = hdev_probe_device,
1157 .bdrv_open = hdev_open,
1158 .bdrv_close = raw_close,
1159 .bdrv_create = hdev_create,
1160 .bdrv_flush = raw_flush,
1162 #ifdef CONFIG_AIO
1163 .bdrv_aio_readv = raw_aio_readv,
1164 .bdrv_aio_writev = raw_aio_writev,
1165 #endif
1167 .bdrv_read = raw_read,
1168 .bdrv_write = raw_write,
1169 .bdrv_getlength = raw_getlength,
1171 /* generic scsi device */
1172 #ifdef __linux__
1173 .bdrv_ioctl = hdev_ioctl,
1174 #ifdef CONFIG_AIO
1175 .bdrv_aio_ioctl = hdev_aio_ioctl,
1176 #endif
1177 #endif
1180 #ifdef __linux__
1181 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1183 BDRVRawState *s = bs->opaque;
1184 int ret;
1186 posix_aio_init();
1188 s->type = FTYPE_FD;
1189 /* open will not fail even if no floppy is inserted */
1190 s->open_flags |= O_NONBLOCK;
1192 ret = raw_open_common(bs, filename, flags);
1193 if (ret)
1194 return ret;
1196 /* close fd so that we can reopen it as needed */
1197 close(s->fd);
1198 s->fd = -1;
1199 s->fd_media_changed = 1;
1201 return 0;
1204 static int floppy_probe_device(const char *filename)
1206 if (strstart(filename, "/dev/fd", NULL))
1207 return 100;
1208 return 0;
1212 static int floppy_is_inserted(BlockDriverState *bs)
1214 return fd_open(bs) >= 0;
1217 static int floppy_media_changed(BlockDriverState *bs)
1219 BDRVRawState *s = bs->opaque;
1220 int ret;
1223 * XXX: we do not have a true media changed indication.
1224 * It does not work if the floppy is changed without trying to read it.
1226 fd_open(bs);
1227 ret = s->fd_media_changed;
1228 s->fd_media_changed = 0;
1229 #ifdef DEBUG_FLOPPY
1230 printf("Floppy changed=%d\n", ret);
1231 #endif
1232 return ret;
1235 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1237 BDRVRawState *s = bs->opaque;
1238 int fd;
1240 if (s->fd >= 0) {
1241 close(s->fd);
1242 s->fd = -1;
1244 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1245 if (fd >= 0) {
1246 if (ioctl(fd, FDEJECT, 0) < 0)
1247 perror("FDEJECT");
1248 close(fd);
1251 return 0;
1254 static BlockDriver bdrv_host_floppy = {
1255 .format_name = "host_floppy",
1256 .instance_size = sizeof(BDRVRawState),
1257 .bdrv_probe_device = floppy_probe_device,
1258 .bdrv_open = floppy_open,
1259 .bdrv_close = raw_close,
1260 .bdrv_create = hdev_create,
1261 .bdrv_flush = raw_flush,
1263 #ifdef CONFIG_AIO
1264 .bdrv_aio_readv = raw_aio_readv,
1265 .bdrv_aio_writev = raw_aio_writev,
1266 #endif
1268 .bdrv_read = raw_read,
1269 .bdrv_write = raw_write,
1270 .bdrv_getlength = raw_getlength,
1272 /* removable device support */
1273 .bdrv_is_inserted = floppy_is_inserted,
1274 .bdrv_media_changed = floppy_media_changed,
1275 .bdrv_eject = floppy_eject,
1278 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1280 BDRVRawState *s = bs->opaque;
1282 /* open will not fail even if no CD is inserted */
1283 s->open_flags |= O_NONBLOCK;
1284 s->type = FTYPE_CD;
1286 return raw_open_common(bs, filename, flags);
1289 static int cdrom_probe_device(const char *filename)
1291 if (strstart(filename, "/dev/cd", NULL))
1292 return 100;
1293 return 0;
1296 static int cdrom_is_inserted(BlockDriverState *bs)
1298 BDRVRawState *s = bs->opaque;
1299 int ret;
1301 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1302 if (ret == CDS_DISC_OK)
1303 return 1;
1304 return 0;
1307 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1309 BDRVRawState *s = bs->opaque;
1311 if (eject_flag) {
1312 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1313 perror("CDROMEJECT");
1314 } else {
1315 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1316 perror("CDROMEJECT");
1319 return 0;
1322 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1324 BDRVRawState *s = bs->opaque;
1326 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1328 * Note: an error can happen if the distribution automatically
1329 * mounts the CD-ROM
1331 /* perror("CDROM_LOCKDOOR"); */
1334 return 0;
1337 static BlockDriver bdrv_host_cdrom = {
1338 .format_name = "host_cdrom",
1339 .instance_size = sizeof(BDRVRawState),
1340 .bdrv_probe_device = cdrom_probe_device,
1341 .bdrv_open = cdrom_open,
1342 .bdrv_close = raw_close,
1343 .bdrv_create = hdev_create,
1344 .bdrv_flush = raw_flush,
1346 #ifdef CONFIG_AIO
1347 .bdrv_aio_readv = raw_aio_readv,
1348 .bdrv_aio_writev = raw_aio_writev,
1349 #endif
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 #ifdef CONFIG_AIO
1363 .bdrv_aio_ioctl = hdev_aio_ioctl,
1364 #endif
1366 #endif /* __linux__ */
1368 #ifdef __FreeBSD__
1369 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1371 BDRVRawState *s = bs->opaque;
1372 int ret;
1374 s->type = FTYPE_CD;
1376 ret = raw_open_common(bs, filename, flags);
1377 if (ret)
1378 return ret;
1380 /* make sure the door isnt locked at this time */
1381 ioctl(s->fd, CDIOCALLOW);
1382 return 0;
1385 static int cdrom_probe_device(const char *filename)
1387 if (strstart(filename, "/dev/cd", NULL) ||
1388 strstart(filename, "/dev/acd", NULL))
1389 return 100;
1390 return 0;
1393 static int cdrom_reopen(BlockDriverState *bs)
1395 BDRVRawState *s = bs->opaque;
1396 int fd;
1399 * Force reread of possibly changed/newly loaded disc,
1400 * FreeBSD seems to not notice sometimes...
1402 if (s->fd >= 0)
1403 close(s->fd);
1404 fd = open(bs->filename, s->open_flags, 0644);
1405 if (fd < 0) {
1406 s->fd = -1;
1407 return -EIO;
1409 s->fd = fd;
1411 /* make sure the door isnt locked at this time */
1412 ioctl(s->fd, CDIOCALLOW);
1413 return 0;
1416 static int cdrom_is_inserted(BlockDriverState *bs)
1418 return raw_getlength(bs) > 0;
1421 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1423 BDRVRawState *s = bs->opaque;
1425 if (s->fd < 0)
1426 return -ENOTSUP;
1428 (void) ioctl(s->fd, CDIOCALLOW);
1430 if (eject_flag) {
1431 if (ioctl(s->fd, CDIOCEJECT) < 0)
1432 perror("CDIOCEJECT");
1433 } else {
1434 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1435 perror("CDIOCCLOSE");
1438 if (cdrom_reopen(bs) < 0)
1439 return -ENOTSUP;
1440 return 0;
1443 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1445 BDRVRawState *s = bs->opaque;
1447 if (s->fd < 0)
1448 return -ENOTSUP;
1449 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1451 * Note: an error can happen if the distribution automatically
1452 * mounts the CD-ROM
1454 /* perror("CDROM_LOCKDOOR"); */
1457 return 0;
1460 static BlockDriver bdrv_host_cdrom = {
1461 .format_name = "host_cdrom",
1462 .instance_size = sizeof(BDRVRawState),
1463 .bdrv_probe_device = cdrom_probe_device,
1464 .bdrv_open = cdrom_open,
1465 .bdrv_close = raw_close,
1466 .bdrv_create = hdev_create,
1467 .bdrv_flush = raw_flush,
1469 #ifdef CONFIG_AIO
1470 .bdrv_aio_readv = raw_aio_readv,
1471 .bdrv_aio_writev = raw_aio_writev,
1472 #endif
1474 .bdrv_read = raw_read,
1475 .bdrv_write = raw_write,
1476 .bdrv_getlength = raw_getlength,
1478 /* removable device support */
1479 .bdrv_is_inserted = cdrom_is_inserted,
1480 .bdrv_eject = cdrom_eject,
1481 .bdrv_set_locked = cdrom_set_locked,
1483 #endif /* __FreeBSD__ */
1485 static void bdrv_raw_init(void)
1488 * Register all the drivers. Note that order is important, the driver
1489 * registered last will get probed first.
1491 bdrv_register(&bdrv_raw);
1492 bdrv_register(&bdrv_host_device);
1493 #ifdef __linux__
1494 bdrv_register(&bdrv_host_floppy);
1495 bdrv_register(&bdrv_host_cdrom);
1496 #endif
1497 #ifdef __FreeBSD__
1498 bdrv_register(&bdrv_host_cdrom);
1499 #endif
1502 block_init(bdrv_raw_init);