honor -S on incoming migration
[qemu-kvm/fedora.git] / block-raw-posix.c
blob49dd528d266aeb18589378d339ebfd12e3a12e77
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 <assert.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 #endif
60 #ifdef __OpenBSD__
61 #include <sys/ioctl.h>
62 #include <sys/disklabel.h>
63 #include <sys/dkio.h>
64 #endif
66 //#define DEBUG_FLOPPY
68 //#define DEBUG_BLOCK
69 #if defined(DEBUG_BLOCK)
70 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (qemu_log_enabled()) \
71 { qemu_log(formatCstr, ##args); qemu_log_flush(); } } while (0)
72 #else
73 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
74 #endif
76 /* OS X does not have O_DSYNC */
77 #ifndef O_DSYNC
78 #ifdef O_SYNC
79 #define O_DSYNC O_SYNC
80 #elif defined(O_FSYNC)
81 #define O_DSYNC O_FSYNC
82 #endif
83 #endif
85 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
86 #ifndef O_DIRECT
87 #define O_DIRECT O_DSYNC
88 #endif
90 #define FTYPE_FILE 0
91 #define FTYPE_CD 1
92 #define FTYPE_FD 2
94 #define ALIGNED_BUFFER_SIZE (32 * 512)
96 /* if the FD is not accessed during that time (in ms), we try to
97 reopen it to see if the disk has been changed */
98 #define FD_OPEN_TIMEOUT 1000
100 typedef struct BDRVRawState {
101 int fd;
102 int type;
103 unsigned int lseek_err_cnt;
104 #if defined(__linux__)
105 /* linux floppy specific */
106 int fd_open_flags;
107 int64_t fd_open_time;
108 int64_t fd_error_time;
109 int fd_got_error;
110 int fd_media_changed;
111 #endif
112 uint8_t* aligned_buf;
113 } BDRVRawState;
115 static int posix_aio_init(void);
117 static int fd_open(BlockDriverState *bs);
119 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
121 BDRVRawState *s = bs->opaque;
122 int fd, open_flags, ret;
124 posix_aio_init();
126 s->lseek_err_cnt = 0;
128 open_flags = O_BINARY;
129 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
130 open_flags |= O_RDWR;
131 } else {
132 open_flags |= O_RDONLY;
133 bs->read_only = 1;
135 if (flags & BDRV_O_CREAT)
136 open_flags |= O_CREAT | O_TRUNC;
138 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
139 * and O_DIRECT for no caching. */
140 if ((flags & BDRV_O_NOCACHE))
141 open_flags |= O_DIRECT;
142 else if (!(flags & BDRV_O_CACHE_WB))
143 open_flags |= O_DSYNC;
145 s->type = FTYPE_FILE;
147 fd = open(filename, open_flags, 0644);
148 if (fd < 0) {
149 ret = -errno;
150 if (ret == -EROFS)
151 ret = -EACCES;
152 return ret;
154 s->fd = fd;
155 s->aligned_buf = NULL;
156 if ((flags & BDRV_O_NOCACHE)) {
157 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
158 if (s->aligned_buf == NULL) {
159 ret = -errno;
160 close(fd);
161 return ret;
164 return 0;
167 /* XXX: use host sector size if necessary with:
168 #ifdef DIOCGSECTORSIZE
170 unsigned int sectorsize = 512;
171 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
172 sectorsize > bufsize)
173 bufsize = sectorsize;
175 #endif
176 #ifdef CONFIG_COCOA
177 u_int32_t blockSize = 512;
178 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
179 bufsize = blockSize;
181 #endif
185 * offset and count are in bytes, but must be multiples of 512 for files
186 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
188 * This function may be called without alignment if the caller ensures
189 * that O_DIRECT is not in effect.
191 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
192 uint8_t *buf, int count)
194 BDRVRawState *s = bs->opaque;
195 int ret;
197 ret = fd_open(bs);
198 if (ret < 0)
199 return ret;
201 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
202 ++(s->lseek_err_cnt);
203 if(s->lseek_err_cnt <= 10) {
204 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
205 "] lseek failed : %d = %s\n",
206 s->fd, bs->filename, offset, buf, count,
207 bs->total_sectors, errno, strerror(errno));
209 return -1;
211 s->lseek_err_cnt=0;
213 ret = read(s->fd, buf, count);
214 if (ret == count)
215 goto label__raw_read__success;
217 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
218 "] read failed %d : %d = %s\n",
219 s->fd, bs->filename, offset, buf, count,
220 bs->total_sectors, ret, errno, strerror(errno));
222 /* Try harder for CDrom. */
223 if (bs->type == BDRV_TYPE_CDROM) {
224 lseek(s->fd, offset, SEEK_SET);
225 ret = read(s->fd, buf, count);
226 if (ret == count)
227 goto label__raw_read__success;
228 lseek(s->fd, offset, SEEK_SET);
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 "] retry read failed %d : %d = %s\n",
235 s->fd, bs->filename, offset, buf, count,
236 bs->total_sectors, ret, errno, strerror(errno));
239 label__raw_read__success:
241 return (ret < 0) ? -errno : ret;
245 * offset and count are in bytes, but must be multiples of 512 for files
246 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
248 * This function may be called without alignment if the caller ensures
249 * that O_DIRECT is not in effect.
251 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
252 const uint8_t *buf, int count)
254 BDRVRawState *s = bs->opaque;
255 int ret;
257 ret = fd_open(bs);
258 if (ret < 0)
259 return -errno;
261 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
262 ++(s->lseek_err_cnt);
263 if(s->lseek_err_cnt) {
264 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
265 PRId64 "] lseek failed : %d = %s\n",
266 s->fd, bs->filename, offset, buf, count,
267 bs->total_sectors, errno, strerror(errno));
269 return -EIO;
271 s->lseek_err_cnt = 0;
273 ret = write(s->fd, buf, count);
274 if (ret == count)
275 goto label__raw_write__success;
277 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
278 "] write failed %d : %d = %s\n",
279 s->fd, bs->filename, offset, buf, count,
280 bs->total_sectors, ret, errno, strerror(errno));
282 label__raw_write__success:
284 return (ret < 0) ? -errno : ret;
289 * offset and count are in bytes and possibly not aligned. For files opened
290 * with O_DIRECT, necessary alignments are ensured before calling
291 * raw_pread_aligned to do the actual read.
293 static int raw_pread(BlockDriverState *bs, int64_t offset,
294 uint8_t *buf, int count)
296 BDRVRawState *s = bs->opaque;
297 int size, ret, shift, sum;
299 sum = 0;
301 if (s->aligned_buf != NULL) {
303 if (offset & 0x1ff) {
304 /* align offset on a 512 bytes boundary */
306 shift = offset & 0x1ff;
307 size = (shift + count + 0x1ff) & ~0x1ff;
308 if (size > ALIGNED_BUFFER_SIZE)
309 size = ALIGNED_BUFFER_SIZE;
310 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
311 if (ret < 0)
312 return ret;
314 size = 512 - shift;
315 if (size > count)
316 size = count;
317 memcpy(buf, s->aligned_buf + shift, size);
319 buf += size;
320 offset += size;
321 count -= size;
322 sum += size;
324 if (count == 0)
325 return sum;
327 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
329 /* read on aligned buffer */
331 while (count) {
333 size = (count + 0x1ff) & ~0x1ff;
334 if (size > ALIGNED_BUFFER_SIZE)
335 size = ALIGNED_BUFFER_SIZE;
337 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
338 if (ret < 0)
339 return ret;
341 size = ret;
342 if (size > count)
343 size = count;
345 memcpy(buf, s->aligned_buf, size);
347 buf += size;
348 offset += size;
349 count -= size;
350 sum += size;
353 return sum;
357 return raw_pread_aligned(bs, offset, buf, count) + sum;
361 * offset and count are in bytes and possibly not aligned. For files opened
362 * with O_DIRECT, necessary alignments are ensured before calling
363 * raw_pwrite_aligned to do the actual write.
365 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
366 const uint8_t *buf, int count)
368 BDRVRawState *s = bs->opaque;
369 int size, ret, shift, sum;
371 sum = 0;
373 if (s->aligned_buf != NULL) {
375 if (offset & 0x1ff) {
376 /* align offset on a 512 bytes boundary */
377 shift = offset & 0x1ff;
378 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
379 if (ret < 0)
380 return ret;
382 size = 512 - shift;
383 if (size > count)
384 size = count;
385 memcpy(s->aligned_buf + shift, buf, size);
387 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
388 if (ret < 0)
389 return ret;
391 buf += size;
392 offset += size;
393 count -= size;
394 sum += size;
396 if (count == 0)
397 return sum;
399 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
401 while ((size = (count & ~0x1ff)) != 0) {
403 if (size > ALIGNED_BUFFER_SIZE)
404 size = ALIGNED_BUFFER_SIZE;
406 memcpy(s->aligned_buf, buf, size);
408 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
409 if (ret < 0)
410 return ret;
412 buf += ret;
413 offset += ret;
414 count -= ret;
415 sum += ret;
417 /* here, count < 512 because (count & ~0x1ff) == 0 */
418 if (count) {
419 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
420 if (ret < 0)
421 return ret;
422 memcpy(s->aligned_buf, buf, count);
424 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
425 if (ret < 0)
426 return ret;
427 if (count < ret)
428 ret = count;
430 sum += ret;
432 return sum;
435 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
438 #ifdef CONFIG_AIO
439 /***********************************************************/
440 /* Unix AIO using POSIX AIO */
442 typedef struct RawAIOCB {
443 BlockDriverAIOCB common;
444 struct qemu_paiocb aiocb;
445 struct RawAIOCB *next;
446 int ret;
447 } RawAIOCB;
449 typedef struct PosixAioState
451 int rfd, wfd;
452 RawAIOCB *first_aio;
453 } PosixAioState;
455 static void posix_aio_read(void *opaque)
457 PosixAioState *s = opaque;
458 RawAIOCB *acb, **pacb;
459 int ret;
460 ssize_t len;
462 /* read all bytes from signal pipe */
463 for (;;) {
464 char bytes[16];
466 len = read(s->rfd, bytes, sizeof(bytes));
467 if (len == -1 && errno == EINTR)
468 continue; /* try again */
469 if (len == sizeof(bytes))
470 continue; /* more to read */
471 break;
474 for(;;) {
475 pacb = &s->first_aio;
476 for(;;) {
477 acb = *pacb;
478 if (!acb)
479 goto the_end;
480 ret = qemu_paio_error(&acb->aiocb);
481 if (ret == ECANCELED) {
482 /* remove the request */
483 *pacb = acb->next;
484 qemu_aio_release(acb);
485 } else if (ret != EINPROGRESS) {
486 /* end of aio */
487 if (ret == 0) {
488 ret = qemu_paio_return(&acb->aiocb);
489 if (ret == acb->aiocb.aio_nbytes)
490 ret = 0;
491 else
492 ret = -EINVAL;
493 } else {
494 ret = -ret;
496 /* remove the request */
497 *pacb = acb->next;
498 /* call the callback */
499 acb->common.cb(acb->common.opaque, ret);
500 qemu_aio_release(acb);
501 break;
502 } else {
503 pacb = &acb->next;
507 the_end: ;
510 static int posix_aio_flush(void *opaque)
512 PosixAioState *s = opaque;
513 return !!s->first_aio;
516 static PosixAioState *posix_aio_state;
518 static void aio_signal_handler(int signum)
520 if (posix_aio_state) {
521 char byte = 0;
523 write(posix_aio_state->wfd, &byte, sizeof(byte));
526 qemu_service_io();
529 static int posix_aio_init(void)
531 struct sigaction act;
532 PosixAioState *s;
533 int fds[2];
534 struct qemu_paioinit ai;
536 if (posix_aio_state)
537 return 0;
539 s = qemu_malloc(sizeof(PosixAioState));
541 sigfillset(&act.sa_mask);
542 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
543 act.sa_handler = aio_signal_handler;
544 sigaction(SIGUSR2, &act, NULL);
546 s->first_aio = NULL;
547 if (pipe(fds) == -1) {
548 fprintf(stderr, "failed to create pipe\n");
549 return -errno;
552 s->rfd = fds[0];
553 s->wfd = fds[1];
555 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
556 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
558 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
560 memset(&ai, 0, sizeof(ai));
561 ai.aio_threads = 64;
562 ai.aio_num = 64;
563 qemu_paio_init(&ai);
565 posix_aio_state = s;
567 return 0;
570 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
571 int64_t sector_num, uint8_t *buf, int nb_sectors,
572 BlockDriverCompletionFunc *cb, void *opaque)
574 BDRVRawState *s = bs->opaque;
575 RawAIOCB *acb;
577 if (fd_open(bs) < 0)
578 return NULL;
580 acb = qemu_aio_get(bs, cb, opaque);
581 if (!acb)
582 return NULL;
583 acb->aiocb.aio_fildes = s->fd;
584 acb->aiocb.ev_signo = SIGUSR2;
585 acb->aiocb.aio_buf = buf;
586 if (nb_sectors < 0)
587 acb->aiocb.aio_nbytes = -nb_sectors;
588 else
589 acb->aiocb.aio_nbytes = nb_sectors * 512;
590 acb->aiocb.aio_offset = sector_num * 512;
591 acb->next = posix_aio_state->first_aio;
592 posix_aio_state->first_aio = acb;
593 return acb;
596 static void raw_aio_em_cb(void* opaque)
598 RawAIOCB *acb = opaque;
599 acb->common.cb(acb->common.opaque, acb->ret);
600 qemu_aio_release(acb);
603 static void raw_aio_remove(RawAIOCB *acb)
605 RawAIOCB **pacb;
607 /* remove the callback from the queue */
608 pacb = &posix_aio_state->first_aio;
609 for(;;) {
610 if (*pacb == NULL) {
611 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
612 break;
613 } else if (*pacb == acb) {
614 *pacb = acb->next;
615 qemu_aio_release(acb);
616 break;
618 pacb = &(*pacb)->next;
622 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
623 int64_t sector_num, uint8_t *buf, int nb_sectors,
624 BlockDriverCompletionFunc *cb, void *opaque)
626 RawAIOCB *acb;
629 * If O_DIRECT is used and the buffer is not aligned fall back
630 * to synchronous IO.
632 BDRVRawState *s = bs->opaque;
634 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
635 QEMUBH *bh;
636 acb = qemu_aio_get(bs, cb, opaque);
637 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
638 bh = qemu_bh_new(raw_aio_em_cb, acb);
639 qemu_bh_schedule(bh);
640 return &acb->common;
643 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
644 if (!acb)
645 return NULL;
646 if (qemu_paio_read(&acb->aiocb) < 0) {
647 raw_aio_remove(acb);
648 return NULL;
650 return &acb->common;
653 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
654 int64_t sector_num, const uint8_t *buf, int nb_sectors,
655 BlockDriverCompletionFunc *cb, void *opaque)
657 RawAIOCB *acb;
660 * If O_DIRECT is used and the buffer is not aligned fall back
661 * to synchronous IO.
663 BDRVRawState *s = bs->opaque;
665 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
666 QEMUBH *bh;
667 acb = qemu_aio_get(bs, cb, opaque);
668 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
669 bh = qemu_bh_new(raw_aio_em_cb, acb);
670 qemu_bh_schedule(bh);
671 return &acb->common;
674 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
675 if (!acb)
676 return NULL;
677 if (qemu_paio_write(&acb->aiocb) < 0) {
678 raw_aio_remove(acb);
679 return NULL;
681 return &acb->common;
684 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
686 int ret;
687 RawAIOCB *acb = (RawAIOCB *)blockacb;
689 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
690 if (ret == QEMU_PAIO_NOTCANCELED) {
691 /* fail safe: if the aio could not be canceled, we wait for
692 it */
693 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
696 raw_aio_remove(acb);
698 #else /* CONFIG_AIO */
699 static int posix_aio_init(void)
701 return 0;
703 #endif /* CONFIG_AIO */
706 static void raw_close(BlockDriverState *bs)
708 BDRVRawState *s = bs->opaque;
709 if (s->fd >= 0) {
710 close(s->fd);
711 s->fd = -1;
712 if (s->aligned_buf != NULL)
713 qemu_free(s->aligned_buf);
717 static int raw_truncate(BlockDriverState *bs, int64_t offset)
719 BDRVRawState *s = bs->opaque;
720 if (s->type != FTYPE_FILE)
721 return -ENOTSUP;
722 if (ftruncate(s->fd, offset) < 0)
723 return -errno;
724 return 0;
727 #ifdef __OpenBSD__
728 static int64_t raw_getlength(BlockDriverState *bs)
730 BDRVRawState *s = bs->opaque;
731 int fd = s->fd;
732 struct stat st;
734 if (fstat(fd, &st))
735 return -1;
736 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
737 struct disklabel dl;
739 if (ioctl(fd, DIOCGDINFO, &dl))
740 return -1;
741 return (uint64_t)dl.d_secsize *
742 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
743 } else
744 return st.st_size;
746 #else /* !__OpenBSD__ */
747 static int64_t raw_getlength(BlockDriverState *bs)
749 BDRVRawState *s = bs->opaque;
750 int fd = s->fd;
751 int64_t size;
752 #ifdef _BSD
753 struct stat sb;
754 #endif
755 #ifdef __sun__
756 struct dk_minfo minfo;
757 int rv;
758 #endif
759 int ret;
761 ret = fd_open(bs);
762 if (ret < 0)
763 return ret;
765 #ifdef _BSD
766 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
767 #ifdef DIOCGMEDIASIZE
768 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
769 #endif
770 #ifdef CONFIG_COCOA
771 size = LONG_LONG_MAX;
772 #else
773 size = lseek(fd, 0LL, SEEK_END);
774 #endif
775 } else
776 #endif
777 #ifdef __sun__
779 * use the DKIOCGMEDIAINFO ioctl to read the size.
781 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
782 if ( rv != -1 ) {
783 size = minfo.dki_lbsize * minfo.dki_capacity;
784 } else /* there are reports that lseek on some devices
785 fails, but irc discussion said that contingency
786 on contingency was overkill */
787 #endif
789 size = lseek(fd, 0, SEEK_END);
791 return size;
793 #endif
795 static int raw_create(const char *filename, int64_t total_size,
796 const char *backing_file, int flags)
798 int fd;
800 if (flags || backing_file)
801 return -ENOTSUP;
803 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
804 0644);
805 if (fd < 0)
806 return -EIO;
807 ftruncate(fd, total_size * 512);
808 close(fd);
809 return 0;
812 static void raw_flush(BlockDriverState *bs)
814 BDRVRawState *s = bs->opaque;
815 fsync(s->fd);
818 BlockDriver bdrv_raw = {
819 "raw",
820 sizeof(BDRVRawState),
821 NULL, /* no probe for protocols */
822 raw_open,
823 NULL,
824 NULL,
825 raw_close,
826 raw_create,
827 raw_flush,
829 #ifdef CONFIG_AIO
830 .bdrv_aio_read = raw_aio_read,
831 .bdrv_aio_write = raw_aio_write,
832 .bdrv_aio_cancel = raw_aio_cancel,
833 .aiocb_size = sizeof(RawAIOCB),
834 #endif
836 .bdrv_pread = raw_pread,
837 .bdrv_pwrite = raw_pwrite,
838 .bdrv_truncate = raw_truncate,
839 .bdrv_getlength = raw_getlength,
842 /***********************************************/
843 /* host device */
845 #ifdef CONFIG_COCOA
846 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
847 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
849 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
851 kern_return_t kernResult;
852 mach_port_t masterPort;
853 CFMutableDictionaryRef classesToMatch;
855 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
856 if ( KERN_SUCCESS != kernResult ) {
857 printf( "IOMasterPort returned %d\n", kernResult );
860 classesToMatch = IOServiceMatching( kIOCDMediaClass );
861 if ( classesToMatch == NULL ) {
862 printf( "IOServiceMatching returned a NULL dictionary.\n" );
863 } else {
864 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
866 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
867 if ( KERN_SUCCESS != kernResult )
869 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
872 return kernResult;
875 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
877 io_object_t nextMedia;
878 kern_return_t kernResult = KERN_FAILURE;
879 *bsdPath = '\0';
880 nextMedia = IOIteratorNext( mediaIterator );
881 if ( nextMedia )
883 CFTypeRef bsdPathAsCFString;
884 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
885 if ( bsdPathAsCFString ) {
886 size_t devPathLength;
887 strcpy( bsdPath, _PATH_DEV );
888 strcat( bsdPath, "r" );
889 devPathLength = strlen( bsdPath );
890 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
891 kernResult = KERN_SUCCESS;
893 CFRelease( bsdPathAsCFString );
895 IOObjectRelease( nextMedia );
898 return kernResult;
901 #endif
903 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
905 BDRVRawState *s = bs->opaque;
906 int fd, open_flags, ret;
908 posix_aio_init();
910 #ifdef CONFIG_COCOA
911 if (strstart(filename, "/dev/cdrom", NULL)) {
912 kern_return_t kernResult;
913 io_iterator_t mediaIterator;
914 char bsdPath[ MAXPATHLEN ];
915 int fd;
917 kernResult = FindEjectableCDMedia( &mediaIterator );
918 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
920 if ( bsdPath[ 0 ] != '\0' ) {
921 strcat(bsdPath,"s0");
922 /* some CDs don't have a partition 0 */
923 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
924 if (fd < 0) {
925 bsdPath[strlen(bsdPath)-1] = '1';
926 } else {
927 close(fd);
929 filename = bsdPath;
932 if ( mediaIterator )
933 IOObjectRelease( mediaIterator );
935 #endif
936 open_flags = O_BINARY;
937 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
938 open_flags |= O_RDWR;
939 } else {
940 open_flags |= O_RDONLY;
941 bs->read_only = 1;
943 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
944 * and O_DIRECT for no caching. */
945 if ((flags & BDRV_O_NOCACHE))
946 open_flags |= O_DIRECT;
947 else if (!(flags & BDRV_O_CACHE_WB))
948 open_flags |= O_DSYNC;
950 s->type = FTYPE_FILE;
951 #if defined(__linux__)
952 if (strstart(filename, "/dev/cd", NULL)) {
953 /* open will not fail even if no CD is inserted */
954 open_flags |= O_NONBLOCK;
955 s->type = FTYPE_CD;
956 } else if (strstart(filename, "/dev/fd", NULL)) {
957 s->type = FTYPE_FD;
958 s->fd_open_flags = open_flags;
959 /* open will not fail even if no floppy is inserted */
960 open_flags |= O_NONBLOCK;
961 } else if (strstart(filename, "/dev/sg", NULL)) {
962 bs->sg = 1;
964 #endif
965 fd = open(filename, open_flags, 0644);
966 if (fd < 0) {
967 ret = -errno;
968 if (ret == -EROFS)
969 ret = -EACCES;
970 return ret;
972 s->fd = fd;
973 #if defined(__linux__)
974 /* close fd so that we can reopen it as needed */
975 if (s->type == FTYPE_FD) {
976 close(s->fd);
977 s->fd = -1;
978 s->fd_media_changed = 1;
980 #endif
981 return 0;
984 #if defined(__linux__)
985 /* Note: we do not have a reliable method to detect if the floppy is
986 present. The current method is to try to open the floppy at every
987 I/O and to keep it opened during a few hundreds of ms. */
988 static int fd_open(BlockDriverState *bs)
990 BDRVRawState *s = bs->opaque;
991 int last_media_present;
993 if (s->type != FTYPE_FD)
994 return 0;
995 last_media_present = (s->fd >= 0);
996 if (s->fd >= 0 &&
997 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
998 close(s->fd);
999 s->fd = -1;
1000 #ifdef DEBUG_FLOPPY
1001 printf("Floppy closed\n");
1002 #endif
1004 if (s->fd < 0) {
1005 if (s->fd_got_error &&
1006 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1007 #ifdef DEBUG_FLOPPY
1008 printf("No floppy (open delayed)\n");
1009 #endif
1010 return -EIO;
1012 s->fd = open(bs->filename, s->fd_open_flags);
1013 if (s->fd < 0) {
1014 s->fd_error_time = qemu_get_clock(rt_clock);
1015 s->fd_got_error = 1;
1016 if (last_media_present)
1017 s->fd_media_changed = 1;
1018 #ifdef DEBUG_FLOPPY
1019 printf("No floppy\n");
1020 #endif
1021 return -EIO;
1023 #ifdef DEBUG_FLOPPY
1024 printf("Floppy opened\n");
1025 #endif
1027 if (!last_media_present)
1028 s->fd_media_changed = 1;
1029 s->fd_open_time = qemu_get_clock(rt_clock);
1030 s->fd_got_error = 0;
1031 return 0;
1034 static int raw_is_inserted(BlockDriverState *bs)
1036 BDRVRawState *s = bs->opaque;
1037 int ret;
1039 switch(s->type) {
1040 case FTYPE_CD:
1041 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1042 if (ret == CDS_DISC_OK)
1043 return 1;
1044 else
1045 return 0;
1046 break;
1047 case FTYPE_FD:
1048 ret = fd_open(bs);
1049 return (ret >= 0);
1050 default:
1051 return 1;
1055 /* currently only used by fdc.c, but a CD version would be good too */
1056 static int raw_media_changed(BlockDriverState *bs)
1058 BDRVRawState *s = bs->opaque;
1060 switch(s->type) {
1061 case FTYPE_FD:
1063 int ret;
1064 /* XXX: we do not have a true media changed indication. It
1065 does not work if the floppy is changed without trying
1066 to read it */
1067 fd_open(bs);
1068 ret = s->fd_media_changed;
1069 s->fd_media_changed = 0;
1070 #ifdef DEBUG_FLOPPY
1071 printf("Floppy changed=%d\n", ret);
1072 #endif
1073 return ret;
1075 default:
1076 return -ENOTSUP;
1080 static int raw_eject(BlockDriverState *bs, int eject_flag)
1082 BDRVRawState *s = bs->opaque;
1084 switch(s->type) {
1085 case FTYPE_CD:
1086 if (eject_flag) {
1087 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1088 perror("CDROMEJECT");
1089 } else {
1090 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1091 perror("CDROMEJECT");
1093 break;
1094 case FTYPE_FD:
1096 int fd;
1097 if (s->fd >= 0) {
1098 close(s->fd);
1099 s->fd = -1;
1101 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1102 if (fd >= 0) {
1103 if (ioctl(fd, FDEJECT, 0) < 0)
1104 perror("FDEJECT");
1105 close(fd);
1108 break;
1109 default:
1110 return -ENOTSUP;
1112 return 0;
1115 static int raw_set_locked(BlockDriverState *bs, int locked)
1117 BDRVRawState *s = bs->opaque;
1119 switch(s->type) {
1120 case FTYPE_CD:
1121 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1122 /* Note: an error can happen if the distribution automatically
1123 mounts the CD-ROM */
1124 // perror("CDROM_LOCKDOOR");
1126 break;
1127 default:
1128 return -ENOTSUP;
1130 return 0;
1133 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1135 BDRVRawState *s = bs->opaque;
1137 return ioctl(s->fd, req, buf);
1139 #else
1141 static int fd_open(BlockDriverState *bs)
1143 return 0;
1146 static int raw_is_inserted(BlockDriverState *bs)
1148 return 1;
1151 static int raw_media_changed(BlockDriverState *bs)
1153 return -ENOTSUP;
1156 static int raw_eject(BlockDriverState *bs, int eject_flag)
1158 return -ENOTSUP;
1161 static int raw_set_locked(BlockDriverState *bs, int locked)
1163 return -ENOTSUP;
1166 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1168 return -ENOTSUP;
1170 #endif /* !linux */
1172 BlockDriver bdrv_host_device = {
1173 "host_device",
1174 sizeof(BDRVRawState),
1175 NULL, /* no probe for protocols */
1176 hdev_open,
1177 NULL,
1178 NULL,
1179 raw_close,
1180 NULL,
1181 raw_flush,
1183 #ifdef CONFIG_AIO
1184 .bdrv_aio_read = raw_aio_read,
1185 .bdrv_aio_write = raw_aio_write,
1186 .bdrv_aio_cancel = raw_aio_cancel,
1187 .aiocb_size = sizeof(RawAIOCB),
1188 #endif
1190 .bdrv_pread = raw_pread,
1191 .bdrv_pwrite = raw_pwrite,
1192 .bdrv_getlength = raw_getlength,
1194 /* removable device support */
1195 .bdrv_is_inserted = raw_is_inserted,
1196 .bdrv_media_changed = raw_media_changed,
1197 .bdrv_eject = raw_eject,
1198 .bdrv_set_locked = raw_set_locked,
1199 /* generic scsi device */
1200 .bdrv_ioctl = raw_ioctl,