Make --mem-path memory allocation depend on mmu notifiers
[qemu-kvm/fedora.git] / block-raw-posix.c
blob0c25787701500354639ad1af91fc108278e516c2
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 "compatfd.h"
29 #include <assert.h>
30 #ifdef CONFIG_AIO
31 #include "posix-aio-compat.h"
32 #endif
34 #ifdef CONFIG_COCOA
35 #include <paths.h>
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
44 #endif
46 #ifdef __sun__
47 #define _POSIX_PTHREAD_SEMANTICS 1
48 #include <signal.h>
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/ioctl.h>
53 #include <linux/cdrom.h>
54 #include <linux/fd.h>
55 #endif
56 #ifdef __FreeBSD__
57 #include <signal.h>
58 #include <sys/disk.h>
59 #endif
61 #ifdef __OpenBSD__
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
64 #include <sys/dkio.h>
65 #endif
67 //#define DEBUG_FLOPPY
69 //#define DEBUG_BLOCK
70 #if defined(DEBUG_BLOCK)
71 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (qemu_log_enabled()) \
72 { qemu_log(formatCstr, ##args); qemu_log_flush(); } } while (0)
73 #else
74 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
75 #endif
77 /* OS X does not have O_DSYNC */
78 #ifndef O_DSYNC
79 #define O_DSYNC O_SYNC
80 #endif
82 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
83 #ifndef O_DIRECT
84 #define O_DIRECT O_DSYNC
85 #endif
87 #define FTYPE_FILE 0
88 #define FTYPE_CD 1
89 #define FTYPE_FD 2
91 #define ALIGNED_BUFFER_SIZE (32 * 512)
93 /* if the FD is not accessed during that time (in ms), we try to
94 reopen it to see if the disk has been changed */
95 #define FD_OPEN_TIMEOUT 1000
97 typedef struct BDRVRawState {
98 int fd;
99 int type;
100 unsigned int lseek_err_cnt;
101 #if defined(__linux__)
102 /* linux floppy specific */
103 int fd_open_flags;
104 int64_t fd_open_time;
105 int64_t fd_error_time;
106 int fd_got_error;
107 int fd_media_changed;
108 #endif
109 uint8_t* aligned_buf;
110 } BDRVRawState;
112 static int posix_aio_init(void);
114 static int fd_open(BlockDriverState *bs);
116 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
118 BDRVRawState *s = bs->opaque;
119 int fd, open_flags, ret;
121 posix_aio_init();
123 s->lseek_err_cnt = 0;
125 open_flags = O_BINARY;
126 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
127 open_flags |= O_RDWR;
128 } else {
129 open_flags |= O_RDONLY;
130 bs->read_only = 1;
132 if (flags & BDRV_O_CREAT)
133 open_flags |= O_CREAT | O_TRUNC;
135 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
136 * and O_DIRECT for no caching. */
137 if ((flags & BDRV_O_NOCACHE))
138 open_flags |= O_DIRECT;
139 else if (!(flags & BDRV_O_CACHE_WB))
140 open_flags |= O_DSYNC;
142 s->type = FTYPE_FILE;
144 fd = open(filename, open_flags, 0644);
145 if (fd < 0) {
146 ret = -errno;
147 if (ret == -EROFS)
148 ret = -EACCES;
149 return ret;
151 s->fd = fd;
152 s->aligned_buf = NULL;
153 if ((flags & BDRV_O_NOCACHE)) {
154 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
155 if (s->aligned_buf == NULL) {
156 ret = -errno;
157 close(fd);
158 return ret;
161 return 0;
164 /* XXX: use host sector size if necessary with:
165 #ifdef DIOCGSECTORSIZE
167 unsigned int sectorsize = 512;
168 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
169 sectorsize > bufsize)
170 bufsize = sectorsize;
172 #endif
173 #ifdef CONFIG_COCOA
174 u_int32_t blockSize = 512;
175 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
176 bufsize = blockSize;
178 #endif
182 * offset and count are in bytes, but must be multiples of 512 for files
183 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
185 * This function may be called without alignment if the caller ensures
186 * that O_DIRECT is not in effect.
188 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
189 uint8_t *buf, int count)
191 BDRVRawState *s = bs->opaque;
192 int ret;
194 ret = fd_open(bs);
195 if (ret < 0)
196 return ret;
198 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
199 ++(s->lseek_err_cnt);
200 if(s->lseek_err_cnt <= 10) {
201 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
202 "] lseek failed : %d = %s\n",
203 s->fd, bs->filename, offset, buf, count,
204 bs->total_sectors, errno, strerror(errno));
206 return -1;
208 s->lseek_err_cnt=0;
210 ret = read(s->fd, buf, count);
211 if (ret == count)
212 goto label__raw_read__success;
214 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
215 "] read failed %d : %d = %s\n",
216 s->fd, bs->filename, offset, buf, count,
217 bs->total_sectors, ret, errno, strerror(errno));
219 /* Try harder for CDrom. */
220 if (bs->type == BDRV_TYPE_CDROM) {
221 lseek(s->fd, offset, SEEK_SET);
222 ret = read(s->fd, buf, count);
223 if (ret == count)
224 goto label__raw_read__success;
225 lseek(s->fd, offset, SEEK_SET);
226 ret = read(s->fd, buf, count);
227 if (ret == count)
228 goto label__raw_read__success;
230 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
231 "] retry read failed %d : %d = %s\n",
232 s->fd, bs->filename, offset, buf, count,
233 bs->total_sectors, ret, errno, strerror(errno));
236 label__raw_read__success:
238 return ret;
242 * offset and count are in bytes, but must be multiples of 512 for files
243 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
245 * This function may be called without alignment if the caller ensures
246 * that O_DIRECT is not in effect.
248 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
249 const uint8_t *buf, int count)
251 BDRVRawState *s = bs->opaque;
252 int ret;
254 ret = fd_open(bs);
255 if (ret < 0)
256 return -errno;
258 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
259 ++(s->lseek_err_cnt);
260 if(s->lseek_err_cnt) {
261 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
262 PRId64 "] lseek failed : %d = %s\n",
263 s->fd, bs->filename, offset, buf, count,
264 bs->total_sectors, errno, strerror(errno));
266 return -EIO;
268 s->lseek_err_cnt = 0;
270 ret = write(s->fd, buf, count);
271 if (ret == count)
272 goto label__raw_write__success;
274 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
275 "] write failed %d : %d = %s\n",
276 s->fd, bs->filename, offset, buf, count,
277 bs->total_sectors, ret, errno, strerror(errno));
279 label__raw_write__success:
281 return (ret < 0) ? -errno : ret;
286 * offset and count are in bytes and possibly not aligned. For files opened
287 * with O_DIRECT, necessary alignments are ensured before calling
288 * raw_pread_aligned to do the actual read.
290 static int raw_pread(BlockDriverState *bs, int64_t offset,
291 uint8_t *buf, int count)
293 BDRVRawState *s = bs->opaque;
294 int size, ret, shift, sum;
296 sum = 0;
298 if (s->aligned_buf != NULL) {
300 if (offset & 0x1ff) {
301 /* align offset on a 512 bytes boundary */
303 shift = offset & 0x1ff;
304 size = (shift + count + 0x1ff) & ~0x1ff;
305 if (size > ALIGNED_BUFFER_SIZE)
306 size = ALIGNED_BUFFER_SIZE;
307 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
308 if (ret < 0)
309 return ret;
311 size = 512 - shift;
312 if (size > count)
313 size = count;
314 memcpy(buf, s->aligned_buf + shift, size);
316 buf += size;
317 offset += size;
318 count -= size;
319 sum += size;
321 if (count == 0)
322 return sum;
324 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
326 /* read on aligned buffer */
328 while (count) {
330 size = (count + 0x1ff) & ~0x1ff;
331 if (size > ALIGNED_BUFFER_SIZE)
332 size = ALIGNED_BUFFER_SIZE;
334 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
335 if (ret < 0)
336 return ret;
338 size = ret;
339 if (size > count)
340 size = count;
342 memcpy(buf, s->aligned_buf, size);
344 buf += size;
345 offset += size;
346 count -= size;
347 sum += size;
350 return sum;
354 return raw_pread_aligned(bs, offset, buf, count) + sum;
358 * offset and count are in bytes and possibly not aligned. For files opened
359 * with O_DIRECT, necessary alignments are ensured before calling
360 * raw_pwrite_aligned to do the actual write.
362 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
363 const uint8_t *buf, int count)
365 BDRVRawState *s = bs->opaque;
366 int size, ret, shift, sum;
368 sum = 0;
370 if (s->aligned_buf != NULL) {
372 if (offset & 0x1ff) {
373 /* align offset on a 512 bytes boundary */
374 shift = offset & 0x1ff;
375 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
376 if (ret < 0)
377 return ret;
379 size = 512 - shift;
380 if (size > count)
381 size = count;
382 memcpy(s->aligned_buf + shift, buf, size);
384 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
385 if (ret < 0)
386 return ret;
388 buf += size;
389 offset += size;
390 count -= size;
391 sum += size;
393 if (count == 0)
394 return sum;
396 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
398 while ((size = (count & ~0x1ff)) != 0) {
400 if (size > ALIGNED_BUFFER_SIZE)
401 size = ALIGNED_BUFFER_SIZE;
403 memcpy(s->aligned_buf, buf, size);
405 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
406 if (ret < 0)
407 return ret;
409 buf += ret;
410 offset += ret;
411 count -= ret;
412 sum += ret;
414 /* here, count < 512 because (count & ~0x1ff) == 0 */
415 if (count) {
416 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
417 if (ret < 0)
418 return ret;
419 memcpy(s->aligned_buf, buf, count);
421 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
422 if (ret < 0)
423 return ret;
424 if (count < ret)
425 ret = count;
427 sum += ret;
429 return sum;
432 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
435 #ifdef CONFIG_AIO
436 /***********************************************************/
437 /* Unix AIO using POSIX AIO */
439 typedef struct RawAIOCB {
440 BlockDriverAIOCB common;
441 struct qemu_paiocb aiocb;
442 struct RawAIOCB *next;
443 int ret;
444 } RawAIOCB;
446 typedef struct PosixAioState
448 int fd;
449 RawAIOCB *first_aio;
450 } PosixAioState;
452 static void posix_aio_read(void *opaque)
454 PosixAioState *s = opaque;
455 RawAIOCB *acb, **pacb;
456 int ret;
457 size_t offset;
458 union {
459 struct qemu_signalfd_siginfo siginfo;
460 char buf[128];
461 } sig;
463 /* try to read from signalfd, don't freak out if we can't read anything */
464 offset = 0;
465 while (offset < 128) {
466 ssize_t len;
468 len = read(s->fd, sig.buf + offset, 128 - offset);
469 if (len == -1 && errno == EINTR)
470 continue;
471 if (len == -1 && errno == EAGAIN) {
472 /* there is no natural reason for this to happen,
473 * so we'll spin hard until we get everything just
474 * to be on the safe side. */
475 if (offset > 0)
476 continue;
479 offset += len;
482 for(;;) {
483 pacb = &s->first_aio;
484 for(;;) {
485 acb = *pacb;
486 if (!acb)
487 goto the_end;
488 ret = qemu_paio_error(&acb->aiocb);
489 if (ret == ECANCELED) {
490 /* remove the request */
491 *pacb = acb->next;
492 qemu_aio_release(acb);
493 } else if (ret != EINPROGRESS) {
494 /* end of aio */
495 if (ret == 0) {
496 ret = qemu_paio_return(&acb->aiocb);
497 if (ret == acb->aiocb.aio_nbytes)
498 ret = 0;
499 else
500 ret = -EINVAL;
501 } else {
502 ret = -ret;
504 /* remove the request */
505 *pacb = acb->next;
506 /* call the callback */
507 acb->common.cb(acb->common.opaque, ret);
508 qemu_aio_release(acb);
509 break;
510 } else {
511 pacb = &acb->next;
515 the_end: ;
518 static int posix_aio_flush(void *opaque)
520 PosixAioState *s = opaque;
521 return !!s->first_aio;
524 static PosixAioState *posix_aio_state;
526 static int posix_aio_init(void)
528 sigset_t mask;
529 PosixAioState *s;
530 int fds[2];
531 struct qemu_paioinit ai;
533 if (posix_aio_state)
534 return 0;
536 s = qemu_malloc(sizeof(PosixAioState));
537 if (s == NULL)
538 return -ENOMEM;
540 /* Make sure to block AIO signal */
541 sigemptyset(&mask);
542 sigaddset(&mask, SIGUSR2);
543 sigprocmask(SIG_BLOCK, &mask, NULL);
545 s->first_aio = NULL;
546 s->fd = qemu_signalfd(&mask);
547 if (s->fd == -1) {
548 fprintf(stderr, "failed to create signalfd\n");
549 return -errno;
552 fcntl(s->fd, F_SETFL, O_NONBLOCK);
554 qemu_aio_set_fd_handler(s->fd, posix_aio_read, NULL, posix_aio_flush, s);
556 memset(&ai, 0, sizeof(ai));
557 ai.aio_threads = 64;
558 ai.aio_num = 64;
559 qemu_paio_init(&ai);
561 posix_aio_state = s;
563 return 0;
566 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
567 int64_t sector_num, uint8_t *buf, int nb_sectors,
568 BlockDriverCompletionFunc *cb, void *opaque)
570 BDRVRawState *s = bs->opaque;
571 RawAIOCB *acb;
573 if (fd_open(bs) < 0)
574 return NULL;
576 acb = qemu_aio_get(bs, cb, opaque);
577 if (!acb)
578 return NULL;
579 acb->aiocb.aio_fildes = s->fd;
580 acb->aiocb.sigev_signo = SIGUSR2;
581 acb->aiocb.aio_buf = buf;
582 if (nb_sectors < 0)
583 acb->aiocb.aio_nbytes = -nb_sectors;
584 else
585 acb->aiocb.aio_nbytes = nb_sectors * 512;
586 acb->aiocb.aio_offset = sector_num * 512;
587 acb->next = posix_aio_state->first_aio;
588 posix_aio_state->first_aio = acb;
589 return acb;
592 static void raw_aio_em_cb(void* opaque)
594 RawAIOCB *acb = opaque;
595 acb->common.cb(acb->common.opaque, acb->ret);
596 qemu_aio_release(acb);
599 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
600 int64_t sector_num, uint8_t *buf, int nb_sectors,
601 BlockDriverCompletionFunc *cb, void *opaque)
603 RawAIOCB *acb;
606 * If O_DIRECT is used and the buffer is not aligned fall back
607 * to synchronous IO.
609 BDRVRawState *s = bs->opaque;
611 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
612 QEMUBH *bh;
613 acb = qemu_aio_get(bs, cb, opaque);
614 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
615 bh = qemu_bh_new(raw_aio_em_cb, acb);
616 qemu_bh_schedule(bh);
617 return &acb->common;
620 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
621 if (!acb)
622 return NULL;
623 if (qemu_paio_read(&acb->aiocb) < 0) {
624 qemu_aio_release(acb);
625 return NULL;
627 return &acb->common;
630 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
631 int64_t sector_num, const uint8_t *buf, int nb_sectors,
632 BlockDriverCompletionFunc *cb, void *opaque)
634 RawAIOCB *acb;
637 * If O_DIRECT is used and the buffer is not aligned fall back
638 * to synchronous IO.
640 BDRVRawState *s = bs->opaque;
642 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
643 QEMUBH *bh;
644 acb = qemu_aio_get(bs, cb, opaque);
645 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
646 bh = qemu_bh_new(raw_aio_em_cb, acb);
647 qemu_bh_schedule(bh);
648 return &acb->common;
651 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
652 if (!acb)
653 return NULL;
654 if (qemu_paio_write(&acb->aiocb) < 0) {
655 qemu_aio_release(acb);
656 return NULL;
658 return &acb->common;
661 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
663 int ret;
664 RawAIOCB *acb = (RawAIOCB *)blockacb;
665 RawAIOCB **pacb;
667 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
668 if (ret == QEMU_PAIO_NOTCANCELED) {
669 /* fail safe: if the aio could not be canceled, we wait for
670 it */
671 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
674 /* remove the callback from the queue */
675 pacb = &posix_aio_state->first_aio;
676 for(;;) {
677 if (*pacb == NULL) {
678 break;
679 } else if (*pacb == acb) {
680 *pacb = acb->next;
681 qemu_aio_release(acb);
682 break;
684 pacb = &acb->next;
687 #else /* CONFIG_AIO */
688 static int posix_aio_init(void)
690 return 0;
692 #endif /* CONFIG_AIO */
695 static void raw_close(BlockDriverState *bs)
697 BDRVRawState *s = bs->opaque;
698 if (s->fd >= 0) {
699 close(s->fd);
700 s->fd = -1;
701 if (s->aligned_buf != NULL)
702 qemu_free(s->aligned_buf);
706 static int raw_truncate(BlockDriverState *bs, int64_t offset)
708 BDRVRawState *s = bs->opaque;
709 if (s->type != FTYPE_FILE)
710 return -ENOTSUP;
711 if (ftruncate(s->fd, offset) < 0)
712 return -errno;
713 return 0;
716 #ifdef __OpenBSD__
717 static int64_t raw_getlength(BlockDriverState *bs)
719 BDRVRawState *s = bs->opaque;
720 int fd = s->fd;
721 struct stat st;
723 if (fstat(fd, &st))
724 return -1;
725 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
726 struct disklabel dl;
728 if (ioctl(fd, DIOCGDINFO, &dl))
729 return -1;
730 return (uint64_t)dl.d_secsize *
731 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
732 } else
733 return st.st_size;
735 #else /* !__OpenBSD__ */
736 static int64_t raw_getlength(BlockDriverState *bs)
738 BDRVRawState *s = bs->opaque;
739 int fd = s->fd;
740 int64_t size;
741 #ifdef _BSD
742 struct stat sb;
743 #endif
744 #ifdef __sun__
745 struct dk_minfo minfo;
746 int rv;
747 #endif
748 int ret;
750 ret = fd_open(bs);
751 if (ret < 0)
752 return ret;
754 #ifdef _BSD
755 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
756 #ifdef DIOCGMEDIASIZE
757 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
758 #endif
759 #ifdef CONFIG_COCOA
760 size = LONG_LONG_MAX;
761 #else
762 size = lseek(fd, 0LL, SEEK_END);
763 #endif
764 } else
765 #endif
766 #ifdef __sun__
768 * use the DKIOCGMEDIAINFO ioctl to read the size.
770 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
771 if ( rv != -1 ) {
772 size = minfo.dki_lbsize * minfo.dki_capacity;
773 } else /* there are reports that lseek on some devices
774 fails, but irc discussion said that contingency
775 on contingency was overkill */
776 #endif
778 size = lseek(fd, 0, SEEK_END);
780 return size;
782 #endif
784 static int raw_create(const char *filename, int64_t total_size,
785 const char *backing_file, int flags)
787 int fd;
789 if (flags || backing_file)
790 return -ENOTSUP;
792 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
793 0644);
794 if (fd < 0)
795 return -EIO;
796 ftruncate(fd, total_size * 512);
797 close(fd);
798 return 0;
801 static void raw_flush(BlockDriverState *bs)
803 BDRVRawState *s = bs->opaque;
804 fsync(s->fd);
807 BlockDriver bdrv_raw = {
808 "raw",
809 sizeof(BDRVRawState),
810 NULL, /* no probe for protocols */
811 raw_open,
812 NULL,
813 NULL,
814 raw_close,
815 raw_create,
816 raw_flush,
818 #ifdef CONFIG_AIO
819 .bdrv_aio_read = raw_aio_read,
820 .bdrv_aio_write = raw_aio_write,
821 .bdrv_aio_cancel = raw_aio_cancel,
822 .aiocb_size = sizeof(RawAIOCB),
823 #endif
825 .bdrv_pread = raw_pread,
826 .bdrv_pwrite = raw_pwrite,
827 .bdrv_truncate = raw_truncate,
828 .bdrv_getlength = raw_getlength,
831 /***********************************************/
832 /* host device */
834 #ifdef CONFIG_COCOA
835 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
836 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
838 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
840 kern_return_t kernResult;
841 mach_port_t masterPort;
842 CFMutableDictionaryRef classesToMatch;
844 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
845 if ( KERN_SUCCESS != kernResult ) {
846 printf( "IOMasterPort returned %d\n", kernResult );
849 classesToMatch = IOServiceMatching( kIOCDMediaClass );
850 if ( classesToMatch == NULL ) {
851 printf( "IOServiceMatching returned a NULL dictionary.\n" );
852 } else {
853 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
855 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
856 if ( KERN_SUCCESS != kernResult )
858 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
861 return kernResult;
864 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
866 io_object_t nextMedia;
867 kern_return_t kernResult = KERN_FAILURE;
868 *bsdPath = '\0';
869 nextMedia = IOIteratorNext( mediaIterator );
870 if ( nextMedia )
872 CFTypeRef bsdPathAsCFString;
873 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
874 if ( bsdPathAsCFString ) {
875 size_t devPathLength;
876 strcpy( bsdPath, _PATH_DEV );
877 strcat( bsdPath, "r" );
878 devPathLength = strlen( bsdPath );
879 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
880 kernResult = KERN_SUCCESS;
882 CFRelease( bsdPathAsCFString );
884 IOObjectRelease( nextMedia );
887 return kernResult;
890 #endif
892 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
894 BDRVRawState *s = bs->opaque;
895 int fd, open_flags, ret;
897 posix_aio_init();
899 #ifdef CONFIG_COCOA
900 if (strstart(filename, "/dev/cdrom", NULL)) {
901 kern_return_t kernResult;
902 io_iterator_t mediaIterator;
903 char bsdPath[ MAXPATHLEN ];
904 int fd;
906 kernResult = FindEjectableCDMedia( &mediaIterator );
907 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
909 if ( bsdPath[ 0 ] != '\0' ) {
910 strcat(bsdPath,"s0");
911 /* some CDs don't have a partition 0 */
912 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
913 if (fd < 0) {
914 bsdPath[strlen(bsdPath)-1] = '1';
915 } else {
916 close(fd);
918 filename = bsdPath;
921 if ( mediaIterator )
922 IOObjectRelease( mediaIterator );
924 #endif
925 open_flags = O_BINARY;
926 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
927 open_flags |= O_RDWR;
928 } else {
929 open_flags |= O_RDONLY;
930 bs->read_only = 1;
932 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
933 * and O_DIRECT for no caching. */
934 if ((flags & BDRV_O_NOCACHE))
935 open_flags |= O_DIRECT;
936 else if (!(flags & BDRV_O_CACHE_WB))
937 open_flags |= O_DSYNC;
939 s->type = FTYPE_FILE;
940 #if defined(__linux__)
941 if (strstart(filename, "/dev/cd", NULL)) {
942 /* open will not fail even if no CD is inserted */
943 open_flags |= O_NONBLOCK;
944 s->type = FTYPE_CD;
945 } else if (strstart(filename, "/dev/fd", NULL)) {
946 s->type = FTYPE_FD;
947 s->fd_open_flags = open_flags;
948 /* open will not fail even if no floppy is inserted */
949 open_flags |= O_NONBLOCK;
950 } else if (strstart(filename, "/dev/sg", NULL)) {
951 bs->sg = 1;
953 #endif
954 fd = open(filename, open_flags, 0644);
955 if (fd < 0) {
956 ret = -errno;
957 if (ret == -EROFS)
958 ret = -EACCES;
959 return ret;
961 s->fd = fd;
962 #if defined(__linux__)
963 /* close fd so that we can reopen it as needed */
964 if (s->type == FTYPE_FD) {
965 close(s->fd);
966 s->fd = -1;
967 s->fd_media_changed = 1;
969 #endif
970 return 0;
973 #if defined(__linux__)
974 /* Note: we do not have a reliable method to detect if the floppy is
975 present. The current method is to try to open the floppy at every
976 I/O and to keep it opened during a few hundreds of ms. */
977 static int fd_open(BlockDriverState *bs)
979 BDRVRawState *s = bs->opaque;
980 int last_media_present;
982 if (s->type != FTYPE_FD)
983 return 0;
984 last_media_present = (s->fd >= 0);
985 if (s->fd >= 0 &&
986 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
987 close(s->fd);
988 s->fd = -1;
989 #ifdef DEBUG_FLOPPY
990 printf("Floppy closed\n");
991 #endif
993 if (s->fd < 0) {
994 if (s->fd_got_error &&
995 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
996 #ifdef DEBUG_FLOPPY
997 printf("No floppy (open delayed)\n");
998 #endif
999 return -EIO;
1001 s->fd = open(bs->filename, s->fd_open_flags);
1002 if (s->fd < 0) {
1003 s->fd_error_time = qemu_get_clock(rt_clock);
1004 s->fd_got_error = 1;
1005 if (last_media_present)
1006 s->fd_media_changed = 1;
1007 #ifdef DEBUG_FLOPPY
1008 printf("No floppy\n");
1009 #endif
1010 return -EIO;
1012 #ifdef DEBUG_FLOPPY
1013 printf("Floppy opened\n");
1014 #endif
1016 if (!last_media_present)
1017 s->fd_media_changed = 1;
1018 s->fd_open_time = qemu_get_clock(rt_clock);
1019 s->fd_got_error = 0;
1020 return 0;
1023 static int raw_is_inserted(BlockDriverState *bs)
1025 BDRVRawState *s = bs->opaque;
1026 int ret;
1028 switch(s->type) {
1029 case FTYPE_CD:
1030 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1031 if (ret == CDS_DISC_OK)
1032 return 1;
1033 else
1034 return 0;
1035 break;
1036 case FTYPE_FD:
1037 ret = fd_open(bs);
1038 return (ret >= 0);
1039 default:
1040 return 1;
1044 /* currently only used by fdc.c, but a CD version would be good too */
1045 static int raw_media_changed(BlockDriverState *bs)
1047 BDRVRawState *s = bs->opaque;
1049 switch(s->type) {
1050 case FTYPE_FD:
1052 int ret;
1053 /* XXX: we do not have a true media changed indication. It
1054 does not work if the floppy is changed without trying
1055 to read it */
1056 fd_open(bs);
1057 ret = s->fd_media_changed;
1058 s->fd_media_changed = 0;
1059 #ifdef DEBUG_FLOPPY
1060 printf("Floppy changed=%d\n", ret);
1061 #endif
1062 return ret;
1064 default:
1065 return -ENOTSUP;
1069 static int raw_eject(BlockDriverState *bs, int eject_flag)
1071 BDRVRawState *s = bs->opaque;
1073 switch(s->type) {
1074 case FTYPE_CD:
1075 if (eject_flag) {
1076 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1077 perror("CDROMEJECT");
1078 } else {
1079 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1080 perror("CDROMEJECT");
1082 break;
1083 case FTYPE_FD:
1085 int fd;
1086 if (s->fd >= 0) {
1087 close(s->fd);
1088 s->fd = -1;
1090 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1091 if (fd >= 0) {
1092 if (ioctl(fd, FDEJECT, 0) < 0)
1093 perror("FDEJECT");
1094 close(fd);
1097 break;
1098 default:
1099 return -ENOTSUP;
1101 return 0;
1104 static int raw_set_locked(BlockDriverState *bs, int locked)
1106 BDRVRawState *s = bs->opaque;
1108 switch(s->type) {
1109 case FTYPE_CD:
1110 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1111 /* Note: an error can happen if the distribution automatically
1112 mounts the CD-ROM */
1113 // perror("CDROM_LOCKDOOR");
1115 break;
1116 default:
1117 return -ENOTSUP;
1119 return 0;
1122 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1124 BDRVRawState *s = bs->opaque;
1126 return ioctl(s->fd, req, buf);
1128 #else
1130 static int fd_open(BlockDriverState *bs)
1132 return 0;
1135 static int raw_is_inserted(BlockDriverState *bs)
1137 return 1;
1140 static int raw_media_changed(BlockDriverState *bs)
1142 return -ENOTSUP;
1145 static int raw_eject(BlockDriverState *bs, int eject_flag)
1147 return -ENOTSUP;
1150 static int raw_set_locked(BlockDriverState *bs, int locked)
1152 return -ENOTSUP;
1155 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1157 return -ENOTSUP;
1159 #endif /* !linux */
1161 BlockDriver bdrv_host_device = {
1162 "host_device",
1163 sizeof(BDRVRawState),
1164 NULL, /* no probe for protocols */
1165 hdev_open,
1166 NULL,
1167 NULL,
1168 raw_close,
1169 NULL,
1170 raw_flush,
1172 #ifdef CONFIG_AIO
1173 .bdrv_aio_read = raw_aio_read,
1174 .bdrv_aio_write = raw_aio_write,
1175 .bdrv_aio_cancel = raw_aio_cancel,
1176 .aiocb_size = sizeof(RawAIOCB),
1177 #endif
1179 .bdrv_pread = raw_pread,
1180 .bdrv_pwrite = raw_pwrite,
1181 .bdrv_getlength = raw_getlength,
1183 /* removable device support */
1184 .bdrv_is_inserted = raw_is_inserted,
1185 .bdrv_media_changed = raw_media_changed,
1186 .bdrv_eject = raw_eject,
1187 .bdrv_set_locked = raw_set_locked,
1188 /* generic scsi device */
1189 .bdrv_ioctl = raw_ioctl,