Add new command line option for controlling shadow cache size
[qemu-kvm/fedora.git] / block-raw.c
blob2f2e19f9bbbe0f3a1a007959cb85f04de9f414b7
1 /*
2 * Block driver for RAW files
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 "vl.h"
25 #include "block_int.h"
26 #include <assert.h>
27 #ifndef _WIN32
28 #include <aio.h>
30 #ifndef QEMU_TOOL
31 #include "exec-all.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 <sys/disk.h>
58 #endif
60 //#define DEBUG_FLOPPY
62 #define DEBUG_BLOCK
63 #if defined(DEBUG_BLOCK) && !defined(QEMU_TOOL)
64 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
65 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
66 #else
67 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
68 #endif
70 #define FTYPE_FILE 0
71 #define FTYPE_CD 1
72 #define FTYPE_FD 2
74 /* if the FD is not accessed during that time (in ms), we try to
75 reopen it to see if the disk has been changed */
76 #define FD_OPEN_TIMEOUT 1000
78 typedef struct BDRVRawState {
79 int fd;
80 int type;
81 unsigned int lseek_err_cnt;
82 #if defined(__linux__)
83 /* linux floppy specific */
84 int fd_open_flags;
85 int64_t fd_open_time;
86 int64_t fd_error_time;
87 int fd_got_error;
88 int fd_media_changed;
89 #endif
90 } BDRVRawState;
92 static int fd_open(BlockDriverState *bs);
94 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
96 BDRVRawState *s = bs->opaque;
97 int fd, open_flags, ret;
99 s->lseek_err_cnt = 0;
101 open_flags = O_BINARY;
102 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
103 open_flags |= O_RDWR;
104 } else {
105 open_flags |= O_RDONLY;
106 bs->read_only = 1;
108 if (flags & BDRV_O_CREAT)
109 open_flags |= O_CREAT | O_TRUNC;
111 s->type = FTYPE_FILE;
113 fd = open(filename, open_flags, 0644);
114 if (fd < 0) {
115 ret = -errno;
116 if (ret == -EROFS)
117 ret = -EACCES;
118 return ret;
120 s->fd = fd;
121 return 0;
124 /* XXX: use host sector size if necessary with:
125 #ifdef DIOCGSECTORSIZE
127 unsigned int sectorsize = 512;
128 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
129 sectorsize > bufsize)
130 bufsize = sectorsize;
132 #endif
133 #ifdef CONFIG_COCOA
134 u_int32_t blockSize = 512;
135 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
136 bufsize = blockSize;
138 #endif
141 static int raw_pread(BlockDriverState *bs, int64_t offset,
142 uint8_t *buf, int count)
144 BDRVRawState *s = bs->opaque;
145 int ret;
147 ret = fd_open(bs);
148 if (ret < 0)
149 return ret;
151 if (lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
152 ++(s->lseek_err_cnt);
153 if(s->lseek_err_cnt <= 10) {
154 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
155 "] lseek failed : %d = %s\n",
156 s->fd, bs->filename, offset, buf, count,
157 bs->total_sectors, errno, strerror(errno));
159 return -1;
161 s->lseek_err_cnt=0;
163 ret = read(s->fd, buf, count);
164 if (ret == count)
165 goto label__raw_read__success;
167 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
168 "] read failed %d : %d = %s\n",
169 s->fd, bs->filename, offset, buf, count,
170 bs->total_sectors, ret, errno, strerror(errno));
172 /* Try harder for CDrom. */
173 if (bs->type == BDRV_TYPE_CDROM) {
174 lseek(s->fd, offset, SEEK_SET);
175 ret = read(s->fd, buf, count);
176 if (ret == count)
177 goto label__raw_read__success;
178 lseek(s->fd, offset, SEEK_SET);
179 ret = read(s->fd, buf, count);
180 if (ret == count)
181 goto label__raw_read__success;
183 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
184 "] retry read failed %d : %d = %s\n",
185 s->fd, bs->filename, offset, buf, count,
186 bs->total_sectors, ret, errno, strerror(errno));
189 label__raw_read__success:
191 return ret;
194 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
195 const uint8_t *buf, int count)
197 BDRVRawState *s = bs->opaque;
198 int ret;
200 ret = fd_open(bs);
201 if (ret < 0)
202 return ret;
204 if (lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
205 ++(s->lseek_err_cnt);
206 if(s->lseek_err_cnt) {
207 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
208 PRId64 "] lseek failed : %d = %s\n",
209 s->fd, bs->filename, offset, buf, count,
210 bs->total_sectors, errno, strerror(errno));
212 return -1;
214 s->lseek_err_cnt = 0;
216 ret = write(s->fd, buf, count);
217 if (ret == count)
218 goto label__raw_write__success;
220 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
221 "] write failed %d : %d = %s\n",
222 s->fd, bs->filename, offset, buf, count,
223 bs->total_sectors, ret, errno, strerror(errno));
225 label__raw_write__success:
227 return ret;
230 /***********************************************************/
231 /* Unix AIO using POSIX AIO */
233 typedef struct RawAIOCB {
234 BlockDriverAIOCB common;
235 struct aiocb aiocb;
236 struct RawAIOCB *next;
237 } RawAIOCB;
239 static int aio_sig_num = SIGUSR2;
240 static RawAIOCB *first_aio; /* AIO issued */
241 static int aio_initialized = 0;
243 static void aio_signal_handler(int signum)
245 #ifndef QEMU_TOOL
246 CPUState *env = cpu_single_env;
247 if (env) {
248 /* stop the currently executing cpu because a timer occured */
249 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
250 #ifdef USE_KQEMU
251 if (env->kqemu_enabled) {
252 kqemu_cpu_interrupt(env);
254 #endif
256 #endif
259 void qemu_aio_init(void)
261 struct sigaction act;
263 aio_initialized = 1;
265 sigfillset(&act.sa_mask);
266 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
267 act.sa_handler = aio_signal_handler;
268 sigaction(aio_sig_num, &act, NULL);
270 #if defined(__GLIBC__) && defined(__linux__)
272 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
273 seems to fix the problem. */
274 struct aioinit ai;
275 memset(&ai, 0, sizeof(ai));
276 ai.aio_threads = 1;
277 ai.aio_num = 1;
278 ai.aio_idle_time = 365 * 100000;
279 aio_init(&ai);
281 #endif
284 void qemu_aio_poll(void)
286 RawAIOCB *acb, **pacb;
287 int ret;
289 for(;;) {
290 pacb = &first_aio;
291 for(;;) {
292 acb = *pacb;
293 if (!acb)
294 goto the_end;
295 ret = aio_error(&acb->aiocb);
296 if (ret == ECANCELED) {
297 /* remove the request */
298 *pacb = acb->next;
299 qemu_aio_release(acb);
300 } else if (ret != EINPROGRESS) {
301 /* end of aio */
302 if (ret == 0) {
303 ret = aio_return(&acb->aiocb);
304 if (ret == acb->aiocb.aio_nbytes)
305 ret = 0;
306 else
307 ret = -EINVAL;
308 } else {
309 ret = -ret;
311 /* remove the request */
312 *pacb = acb->next;
313 /* call the callback */
314 acb->common.cb(acb->common.opaque, ret);
315 qemu_aio_release(acb);
316 break;
317 } else {
318 pacb = &acb->next;
322 the_end: ;
325 /* Wait for all IO requests to complete. */
326 void qemu_aio_flush(void)
328 qemu_aio_wait_start();
329 qemu_aio_poll();
330 while (first_aio) {
331 qemu_aio_wait();
333 qemu_aio_wait_end();
336 /* wait until at least one AIO was handled */
337 static sigset_t wait_oset;
339 void qemu_aio_wait_start(void)
341 sigset_t set;
343 if (!aio_initialized)
344 qemu_aio_init();
345 sigemptyset(&set);
346 sigaddset(&set, aio_sig_num);
347 sigprocmask(SIG_BLOCK, &set, &wait_oset);
350 void qemu_aio_wait(void)
352 sigset_t set;
353 int nb_sigs;
355 #ifndef QEMU_TOOL
356 if (qemu_bh_poll())
357 return;
358 #endif
359 sigemptyset(&set);
360 sigaddset(&set, aio_sig_num);
361 sigwait(&set, &nb_sigs);
362 qemu_aio_poll();
365 void qemu_aio_wait_end(void)
367 sigprocmask(SIG_SETMASK, &wait_oset, NULL);
370 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
371 int64_t sector_num, uint8_t *buf, int nb_sectors,
372 BlockDriverCompletionFunc *cb, void *opaque)
374 BDRVRawState *s = bs->opaque;
375 RawAIOCB *acb;
377 if (fd_open(bs) < 0)
378 return NULL;
380 acb = qemu_aio_get(bs, cb, opaque);
381 if (!acb)
382 return NULL;
383 acb->aiocb.aio_fildes = s->fd;
384 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
385 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
386 acb->aiocb.aio_buf = buf;
387 acb->aiocb.aio_nbytes = nb_sectors * 512;
388 acb->aiocb.aio_offset = sector_num * 512;
389 acb->next = first_aio;
390 first_aio = acb;
391 return acb;
394 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
395 int64_t sector_num, uint8_t *buf, int nb_sectors,
396 BlockDriverCompletionFunc *cb, void *opaque)
398 RawAIOCB *acb;
400 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
401 if (!acb)
402 return NULL;
403 if (aio_read(&acb->aiocb) < 0) {
404 qemu_aio_release(acb);
405 return NULL;
407 return &acb->common;
410 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
411 int64_t sector_num, const uint8_t *buf, int nb_sectors,
412 BlockDriverCompletionFunc *cb, void *opaque)
414 RawAIOCB *acb;
416 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
417 if (!acb)
418 return NULL;
419 if (aio_write(&acb->aiocb) < 0) {
420 qemu_aio_release(acb);
421 return NULL;
423 return &acb->common;
426 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
428 int ret;
429 RawAIOCB *acb = (RawAIOCB *)blockacb;
430 RawAIOCB **pacb;
432 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
433 if (ret == AIO_NOTCANCELED) {
434 /* fail safe: if the aio could not be canceled, we wait for
435 it */
436 while (aio_error(&acb->aiocb) == EINPROGRESS);
439 /* remove the callback from the queue */
440 pacb = &first_aio;
441 for(;;) {
442 if (*pacb == NULL) {
443 break;
444 } else if (*pacb == acb) {
445 *pacb = acb->next;
446 qemu_aio_release(acb);
447 break;
449 pacb = &acb->next;
453 static void raw_close(BlockDriverState *bs)
455 BDRVRawState *s = bs->opaque;
456 if (s->fd >= 0) {
457 close(s->fd);
458 s->fd = -1;
462 static int raw_truncate(BlockDriverState *bs, int64_t offset)
464 BDRVRawState *s = bs->opaque;
465 if (s->type != FTYPE_FILE)
466 return -ENOTSUP;
467 if (ftruncate(s->fd, offset) < 0)
468 return -errno;
469 return 0;
472 static int64_t raw_getlength(BlockDriverState *bs)
474 BDRVRawState *s = bs->opaque;
475 int fd = s->fd;
476 int64_t size;
477 #ifdef _BSD
478 struct stat sb;
479 #endif
480 #ifdef __sun__
481 struct dk_minfo minfo;
482 int rv;
483 #endif
484 int ret;
486 ret = fd_open(bs);
487 if (ret < 0)
488 return ret;
490 #ifdef _BSD
491 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
492 #ifdef DIOCGMEDIASIZE
493 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
494 #endif
495 #ifdef CONFIG_COCOA
496 size = LONG_LONG_MAX;
497 #else
498 size = lseek(fd, 0LL, SEEK_END);
499 #endif
500 } else
501 #endif
502 #ifdef __sun__
504 * use the DKIOCGMEDIAINFO ioctl to read the size.
506 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
507 if ( rv != -1 ) {
508 size = minfo.dki_lbsize * minfo.dki_capacity;
509 } else /* there are reports that lseek on some devices
510 fails, but irc discussion said that contingency
511 on contingency was overkill */
512 #endif
514 size = lseek(fd, 0, SEEK_END);
516 return size;
519 static int raw_create(const char *filename, int64_t total_size,
520 const char *backing_file, int flags)
522 int fd;
524 if (flags || backing_file)
525 return -ENOTSUP;
527 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
528 0644);
529 if (fd < 0)
530 return -EIO;
531 ftruncate(fd, total_size * 512);
532 close(fd);
533 return 0;
536 static void raw_flush(BlockDriverState *bs)
538 BDRVRawState *s = bs->opaque;
539 fsync(s->fd);
542 BlockDriver bdrv_raw = {
543 "raw",
544 sizeof(BDRVRawState),
545 NULL, /* no probe for protocols */
546 raw_open,
547 NULL,
548 NULL,
549 raw_close,
550 raw_create,
551 raw_flush,
553 .bdrv_aio_read = raw_aio_read,
554 .bdrv_aio_write = raw_aio_write,
555 .bdrv_aio_cancel = raw_aio_cancel,
556 .aiocb_size = sizeof(RawAIOCB),
557 .protocol_name = "file",
558 .bdrv_pread = raw_pread,
559 .bdrv_pwrite = raw_pwrite,
560 .bdrv_truncate = raw_truncate,
561 .bdrv_getlength = raw_getlength,
564 /***********************************************/
565 /* host device */
567 #ifdef CONFIG_COCOA
568 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
569 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
571 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
573 kern_return_t kernResult;
574 mach_port_t masterPort;
575 CFMutableDictionaryRef classesToMatch;
577 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
578 if ( KERN_SUCCESS != kernResult ) {
579 printf( "IOMasterPort returned %d\n", kernResult );
582 classesToMatch = IOServiceMatching( kIOCDMediaClass );
583 if ( classesToMatch == NULL ) {
584 printf( "IOServiceMatching returned a NULL dictionary.\n" );
585 } else {
586 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
588 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
589 if ( KERN_SUCCESS != kernResult )
591 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
594 return kernResult;
597 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
599 io_object_t nextMedia;
600 kern_return_t kernResult = KERN_FAILURE;
601 *bsdPath = '\0';
602 nextMedia = IOIteratorNext( mediaIterator );
603 if ( nextMedia )
605 CFTypeRef bsdPathAsCFString;
606 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
607 if ( bsdPathAsCFString ) {
608 size_t devPathLength;
609 strcpy( bsdPath, _PATH_DEV );
610 strcat( bsdPath, "r" );
611 devPathLength = strlen( bsdPath );
612 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
613 kernResult = KERN_SUCCESS;
615 CFRelease( bsdPathAsCFString );
617 IOObjectRelease( nextMedia );
620 return kernResult;
623 #endif
625 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
627 BDRVRawState *s = bs->opaque;
628 int fd, open_flags, ret;
630 #ifdef CONFIG_COCOA
631 if (strstart(filename, "/dev/cdrom", NULL)) {
632 kern_return_t kernResult;
633 io_iterator_t mediaIterator;
634 char bsdPath[ MAXPATHLEN ];
635 int fd;
637 kernResult = FindEjectableCDMedia( &mediaIterator );
638 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
640 if ( bsdPath[ 0 ] != '\0' ) {
641 strcat(bsdPath,"s0");
642 /* some CDs don't have a partition 0 */
643 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
644 if (fd < 0) {
645 bsdPath[strlen(bsdPath)-1] = '1';
646 } else {
647 close(fd);
649 filename = bsdPath;
652 if ( mediaIterator )
653 IOObjectRelease( mediaIterator );
655 #endif
656 open_flags = O_BINARY;
657 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
658 open_flags |= O_RDWR;
659 } else {
660 open_flags |= O_RDONLY;
661 bs->read_only = 1;
664 s->type = FTYPE_FILE;
665 #if defined(__linux__)
666 if (strstart(filename, "/dev/cd", NULL)) {
667 /* open will not fail even if no CD is inserted */
668 open_flags |= O_NONBLOCK;
669 s->type = FTYPE_CD;
670 } else if (strstart(filename, "/dev/fd", NULL)) {
671 s->type = FTYPE_FD;
672 s->fd_open_flags = open_flags;
673 /* open will not fail even if no floppy is inserted */
674 open_flags |= O_NONBLOCK;
676 #endif
677 fd = open(filename, open_flags, 0644);
678 if (fd < 0) {
679 ret = -errno;
680 if (ret == -EROFS)
681 ret = -EACCES;
682 return ret;
684 s->fd = fd;
685 #if defined(__linux__)
686 /* close fd so that we can reopen it as needed */
687 if (s->type == FTYPE_FD) {
688 close(s->fd);
689 s->fd = -1;
690 s->fd_media_changed = 1;
692 #endif
693 return 0;
696 #if defined(__linux__) && !defined(QEMU_TOOL)
698 /* Note: we do not have a reliable method to detect if the floppy is
699 present. The current method is to try to open the floppy at every
700 I/O and to keep it opened during a few hundreds of ms. */
701 static int fd_open(BlockDriverState *bs)
703 BDRVRawState *s = bs->opaque;
704 int last_media_present;
706 if (s->type != FTYPE_FD)
707 return 0;
708 last_media_present = (s->fd >= 0);
709 if (s->fd >= 0 &&
710 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
711 close(s->fd);
712 s->fd = -1;
713 #ifdef DEBUG_FLOPPY
714 printf("Floppy closed\n");
715 #endif
717 if (s->fd < 0) {
718 if (s->fd_got_error &&
719 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
720 #ifdef DEBUG_FLOPPY
721 printf("No floppy (open delayed)\n");
722 #endif
723 return -EIO;
725 s->fd = open(bs->filename, s->fd_open_flags);
726 if (s->fd < 0) {
727 s->fd_error_time = qemu_get_clock(rt_clock);
728 s->fd_got_error = 1;
729 if (last_media_present)
730 s->fd_media_changed = 1;
731 #ifdef DEBUG_FLOPPY
732 printf("No floppy\n");
733 #endif
734 return -EIO;
736 #ifdef DEBUG_FLOPPY
737 printf("Floppy opened\n");
738 #endif
740 if (!last_media_present)
741 s->fd_media_changed = 1;
742 s->fd_open_time = qemu_get_clock(rt_clock);
743 s->fd_got_error = 0;
744 return 0;
746 #else
747 static int fd_open(BlockDriverState *bs)
749 return 0;
751 #endif
753 #if defined(__linux__)
755 static int raw_is_inserted(BlockDriverState *bs)
757 BDRVRawState *s = bs->opaque;
758 int ret;
760 switch(s->type) {
761 case FTYPE_CD:
762 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
763 if (ret == CDS_DISC_OK)
764 return 1;
765 else
766 return 0;
767 break;
768 case FTYPE_FD:
769 ret = fd_open(bs);
770 return (ret >= 0);
771 default:
772 return 1;
776 /* currently only used by fdc.c, but a CD version would be good too */
777 static int raw_media_changed(BlockDriverState *bs)
779 BDRVRawState *s = bs->opaque;
781 switch(s->type) {
782 case FTYPE_FD:
784 int ret;
785 /* XXX: we do not have a true media changed indication. It
786 does not work if the floppy is changed without trying
787 to read it */
788 fd_open(bs);
789 ret = s->fd_media_changed;
790 s->fd_media_changed = 0;
791 #ifdef DEBUG_FLOPPY
792 printf("Floppy changed=%d\n", ret);
793 #endif
794 return ret;
796 default:
797 return -ENOTSUP;
801 static int raw_eject(BlockDriverState *bs, int eject_flag)
803 BDRVRawState *s = bs->opaque;
805 switch(s->type) {
806 case FTYPE_CD:
807 if (eject_flag) {
808 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
809 perror("CDROMEJECT");
810 } else {
811 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
812 perror("CDROMEJECT");
814 break;
815 case FTYPE_FD:
817 int fd;
818 if (s->fd >= 0) {
819 close(s->fd);
820 s->fd = -1;
822 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
823 if (fd >= 0) {
824 if (ioctl(fd, FDEJECT, 0) < 0)
825 perror("FDEJECT");
826 close(fd);
829 break;
830 default:
831 return -ENOTSUP;
833 return 0;
836 static int raw_set_locked(BlockDriverState *bs, int locked)
838 BDRVRawState *s = bs->opaque;
840 switch(s->type) {
841 case FTYPE_CD:
842 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
843 /* Note: an error can happen if the distribution automatically
844 mounts the CD-ROM */
845 // perror("CDROM_LOCKDOOR");
847 break;
848 default:
849 return -ENOTSUP;
851 return 0;
854 #else
856 static int raw_is_inserted(BlockDriverState *bs)
858 return 1;
861 static int raw_media_changed(BlockDriverState *bs)
863 return -ENOTSUP;
866 static int raw_eject(BlockDriverState *bs, int eject_flag)
868 return -ENOTSUP;
871 static int raw_set_locked(BlockDriverState *bs, int locked)
873 return -ENOTSUP;
876 #endif /* !linux */
878 BlockDriver bdrv_host_device = {
879 "host_device",
880 sizeof(BDRVRawState),
881 NULL, /* no probe for protocols */
882 hdev_open,
883 NULL,
884 NULL,
885 raw_close,
886 NULL,
887 raw_flush,
889 .bdrv_aio_read = raw_aio_read,
890 .bdrv_aio_write = raw_aio_write,
891 .bdrv_aio_cancel = raw_aio_cancel,
892 .aiocb_size = sizeof(RawAIOCB),
893 .bdrv_pread = raw_pread,
894 .bdrv_pwrite = raw_pwrite,
895 .bdrv_getlength = raw_getlength,
897 /* removable device support */
898 .bdrv_is_inserted = raw_is_inserted,
899 .bdrv_media_changed = raw_media_changed,
900 .bdrv_eject = raw_eject,
901 .bdrv_set_locked = raw_set_locked,
904 #else /* _WIN32 */
906 /* XXX: use another file ? */
907 #include <winioctl.h>
909 #define FTYPE_FILE 0
910 #define FTYPE_CD 1
911 #define FTYPE_HARDDISK 2
913 typedef struct BDRVRawState {
914 HANDLE hfile;
915 int type;
916 char drive_path[16]; /* format: "d:\" */
917 } BDRVRawState;
919 typedef struct RawAIOCB {
920 BlockDriverAIOCB common;
921 HANDLE hEvent;
922 OVERLAPPED ov;
923 int count;
924 } RawAIOCB;
926 int qemu_ftruncate64(int fd, int64_t length)
928 LARGE_INTEGER li;
929 LONG high;
930 HANDLE h;
931 BOOL res;
933 if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
934 return -1;
936 h = (HANDLE)_get_osfhandle(fd);
938 /* get current position, ftruncate do not change position */
939 li.HighPart = 0;
940 li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
941 if (li.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
942 return -1;
944 high = length >> 32;
945 if (!SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN))
946 return -1;
947 res = SetEndOfFile(h);
949 /* back to old position */
950 SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
951 return res ? 0 : -1;
954 static int set_sparse(int fd)
956 DWORD returned;
957 return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
958 NULL, 0, NULL, 0, &returned, NULL);
961 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
963 BDRVRawState *s = bs->opaque;
964 int access_flags, create_flags;
965 DWORD overlapped;
967 s->type = FTYPE_FILE;
969 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
970 access_flags = GENERIC_READ | GENERIC_WRITE;
971 } else {
972 access_flags = GENERIC_READ;
974 if (flags & BDRV_O_CREAT) {
975 create_flags = CREATE_ALWAYS;
976 } else {
977 create_flags = OPEN_EXISTING;
979 #ifdef QEMU_TOOL
980 overlapped = FILE_ATTRIBUTE_NORMAL;
981 #else
982 overlapped = FILE_FLAG_OVERLAPPED;
983 #endif
984 s->hfile = CreateFile(filename, access_flags,
985 FILE_SHARE_READ, NULL,
986 create_flags, overlapped, NULL);
987 if (s->hfile == INVALID_HANDLE_VALUE) {
988 int err = GetLastError();
990 if (err == ERROR_ACCESS_DENIED)
991 return -EACCES;
992 return -1;
994 return 0;
997 static int raw_pread(BlockDriverState *bs, int64_t offset,
998 uint8_t *buf, int count)
1000 BDRVRawState *s = bs->opaque;
1001 OVERLAPPED ov;
1002 DWORD ret_count;
1003 int ret;
1005 memset(&ov, 0, sizeof(ov));
1006 ov.Offset = offset;
1007 ov.OffsetHigh = offset >> 32;
1008 ret = ReadFile(s->hfile, buf, count, &ret_count, &ov);
1009 if (!ret) {
1010 ret = GetOverlappedResult(s->hfile, &ov, &ret_count, TRUE);
1011 if (!ret)
1012 return -EIO;
1013 else
1014 return ret_count;
1016 return ret_count;
1019 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
1020 const uint8_t *buf, int count)
1022 BDRVRawState *s = bs->opaque;
1023 OVERLAPPED ov;
1024 DWORD ret_count;
1025 int ret;
1027 memset(&ov, 0, sizeof(ov));
1028 ov.Offset = offset;
1029 ov.OffsetHigh = offset >> 32;
1030 ret = WriteFile(s->hfile, buf, count, &ret_count, &ov);
1031 if (!ret) {
1032 ret = GetOverlappedResult(s->hfile, &ov, &ret_count, TRUE);
1033 if (!ret)
1034 return -EIO;
1035 else
1036 return ret_count;
1038 return ret_count;
1041 #if 0
1042 #ifndef QEMU_TOOL
1043 static void raw_aio_cb(void *opaque)
1045 RawAIOCB *acb = opaque;
1046 BlockDriverState *bs = acb->common.bs;
1047 BDRVRawState *s = bs->opaque;
1048 DWORD ret_count;
1049 int ret;
1051 ret = GetOverlappedResult(s->hfile, &acb->ov, &ret_count, TRUE);
1052 if (!ret || ret_count != acb->count) {
1053 acb->common.cb(acb->common.opaque, -EIO);
1054 } else {
1055 acb->common.cb(acb->common.opaque, 0);
1058 #endif
1060 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
1061 int64_t sector_num, uint8_t *buf, int nb_sectors,
1062 BlockDriverCompletionFunc *cb, void *opaque)
1064 RawAIOCB *acb;
1065 int64_t offset;
1067 acb = qemu_aio_get(bs, cb, opaque);
1068 if (acb->hEvent) {
1069 acb->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1070 if (!acb->hEvent) {
1071 qemu_aio_release(acb);
1072 return NULL;
1075 memset(&acb->ov, 0, sizeof(acb->ov));
1076 offset = sector_num * 512;
1077 acb->ov.Offset = offset;
1078 acb->ov.OffsetHigh = offset >> 32;
1079 acb->ov.hEvent = acb->hEvent;
1080 acb->count = nb_sectors * 512;
1081 #ifndef QEMU_TOOL
1082 qemu_add_wait_object(acb->ov.hEvent, raw_aio_cb, acb);
1083 #endif
1084 return acb;
1087 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
1088 int64_t sector_num, uint8_t *buf, int nb_sectors,
1089 BlockDriverCompletionFunc *cb, void *opaque)
1091 BDRVRawState *s = bs->opaque;
1092 RawAIOCB *acb;
1093 int ret;
1095 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1096 if (!acb)
1097 return NULL;
1098 ret = ReadFile(s->hfile, buf, acb->count, NULL, &acb->ov);
1099 if (!ret) {
1100 qemu_aio_release(acb);
1101 return NULL;
1103 #ifdef QEMU_TOOL
1104 qemu_aio_release(acb);
1105 #endif
1106 return (BlockDriverAIOCB *)acb;
1109 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
1110 int64_t sector_num, uint8_t *buf, int nb_sectors,
1111 BlockDriverCompletionFunc *cb, void *opaque)
1113 BDRVRawState *s = bs->opaque;
1114 RawAIOCB *acb;
1115 int ret;
1117 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1118 if (!acb)
1119 return NULL;
1120 ret = WriteFile(s->hfile, buf, acb->count, NULL, &acb->ov);
1121 if (!ret) {
1122 qemu_aio_release(acb);
1123 return NULL;
1125 #ifdef QEMU_TOOL
1126 qemu_aio_release(acb);
1127 #endif
1128 return (BlockDriverAIOCB *)acb;
1131 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
1133 #ifndef QEMU_TOOL
1134 RawAIOCB *acb = (RawAIOCB *)blockacb;
1135 BlockDriverState *bs = acb->common.bs;
1136 BDRVRawState *s = bs->opaque;
1138 qemu_del_wait_object(acb->ov.hEvent, raw_aio_cb, acb);
1139 /* XXX: if more than one async I/O it is not correct */
1140 CancelIo(s->hfile);
1141 qemu_aio_release(acb);
1142 #endif
1144 #endif /* #if 0 */
1146 static void raw_flush(BlockDriverState *bs)
1148 BDRVRawState *s = bs->opaque;
1149 FlushFileBuffers(s->hfile);
1152 static void raw_close(BlockDriverState *bs)
1154 BDRVRawState *s = bs->opaque;
1155 CloseHandle(s->hfile);
1158 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1160 BDRVRawState *s = bs->opaque;
1161 DWORD low, high;
1163 low = offset;
1164 high = offset >> 32;
1165 if (!SetFilePointer(s->hfile, low, &high, FILE_BEGIN))
1166 return -EIO;
1167 if (!SetEndOfFile(s->hfile))
1168 return -EIO;
1169 return 0;
1172 static int64_t raw_getlength(BlockDriverState *bs)
1174 BDRVRawState *s = bs->opaque;
1175 LARGE_INTEGER l;
1176 ULARGE_INTEGER available, total, total_free;
1177 DISK_GEOMETRY dg;
1178 DWORD count;
1179 BOOL status;
1181 switch(s->type) {
1182 case FTYPE_FILE:
1183 l.LowPart = GetFileSize(s->hfile, &l.HighPart);
1184 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
1185 return -EIO;
1186 break;
1187 case FTYPE_CD:
1188 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
1189 return -EIO;
1190 l.QuadPart = total.QuadPart;
1191 break;
1192 case FTYPE_HARDDISK:
1193 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY,
1194 NULL, 0, &dg, sizeof(dg), &count, NULL);
1195 if (status != FALSE) {
1196 l.QuadPart = dg.Cylinders.QuadPart * dg.TracksPerCylinder
1197 * dg.SectorsPerTrack * dg.BytesPerSector;
1199 break;
1200 default:
1201 return -EIO;
1203 return l.QuadPart;
1206 static int raw_create(const char *filename, int64_t total_size,
1207 const char *backing_file, int flags)
1209 int fd;
1211 if (flags || backing_file)
1212 return -ENOTSUP;
1214 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1215 0644);
1216 if (fd < 0)
1217 return -EIO;
1218 set_sparse(fd);
1219 ftruncate(fd, total_size * 512);
1220 close(fd);
1221 return 0;
1224 void qemu_aio_init(void)
1228 void qemu_aio_poll(void)
1232 void qemu_aio_flush(void)
1236 void qemu_aio_wait_start(void)
1240 void qemu_aio_wait(void)
1242 #ifndef QEMU_TOOL
1243 qemu_bh_poll();
1244 #endif
1247 void qemu_aio_wait_end(void)
1251 BlockDriver bdrv_raw = {
1252 "raw",
1253 sizeof(BDRVRawState),
1254 NULL, /* no probe for protocols */
1255 raw_open,
1256 NULL,
1257 NULL,
1258 raw_close,
1259 raw_create,
1260 raw_flush,
1262 #if 0
1263 .bdrv_aio_read = raw_aio_read,
1264 .bdrv_aio_write = raw_aio_write,
1265 .bdrv_aio_cancel = raw_aio_cancel,
1266 .aiocb_size = sizeof(RawAIOCB);
1267 #endif
1268 .protocol_name = "file",
1269 .bdrv_pread = raw_pread,
1270 .bdrv_pwrite = raw_pwrite,
1271 .bdrv_truncate = raw_truncate,
1272 .bdrv_getlength = raw_getlength,
1275 /***********************************************/
1276 /* host device */
1278 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
1280 char drives[256], *pdrv = drives;
1281 UINT type;
1283 memset(drives, 0, sizeof(drives));
1284 GetLogicalDriveStrings(sizeof(drives), drives);
1285 while(pdrv[0] != '\0') {
1286 type = GetDriveType(pdrv);
1287 switch(type) {
1288 case DRIVE_CDROM:
1289 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
1290 return 0;
1291 break;
1293 pdrv += lstrlen(pdrv) + 1;
1295 return -1;
1298 static int find_device_type(BlockDriverState *bs, const char *filename)
1300 BDRVRawState *s = bs->opaque;
1301 UINT type;
1302 const char *p;
1304 if (strstart(filename, "\\\\.\\", &p) ||
1305 strstart(filename, "//./", &p)) {
1306 if (stristart(p, "PhysicalDrive", NULL))
1307 return FTYPE_HARDDISK;
1308 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
1309 type = GetDriveType(s->drive_path);
1310 if (type == DRIVE_CDROM)
1311 return FTYPE_CD;
1312 else
1313 return FTYPE_FILE;
1314 } else {
1315 return FTYPE_FILE;
1319 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1321 BDRVRawState *s = bs->opaque;
1322 int access_flags, create_flags;
1323 DWORD overlapped;
1324 char device_name[64];
1326 if (strstart(filename, "/dev/cdrom", NULL)) {
1327 if (find_cdrom(device_name, sizeof(device_name)) < 0)
1328 return -ENOENT;
1329 filename = device_name;
1330 } else {
1331 /* transform drive letters into device name */
1332 if (((filename[0] >= 'a' && filename[0] <= 'z') ||
1333 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1334 filename[1] == ':' && filename[2] == '\0') {
1335 snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
1336 filename = device_name;
1339 s->type = find_device_type(bs, filename);
1341 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
1342 access_flags = GENERIC_READ | GENERIC_WRITE;
1343 } else {
1344 access_flags = GENERIC_READ;
1346 create_flags = OPEN_EXISTING;
1348 #ifdef QEMU_TOOL
1349 overlapped = FILE_ATTRIBUTE_NORMAL;
1350 #else
1351 overlapped = FILE_FLAG_OVERLAPPED;
1352 #endif
1353 s->hfile = CreateFile(filename, access_flags,
1354 FILE_SHARE_READ, NULL,
1355 create_flags, overlapped, NULL);
1356 if (s->hfile == INVALID_HANDLE_VALUE) {
1357 int err = GetLastError();
1359 if (err == ERROR_ACCESS_DENIED)
1360 return -EACCES;
1361 return -1;
1363 return 0;
1366 #if 0
1367 /***********************************************/
1368 /* removable device additional commands */
1370 static int raw_is_inserted(BlockDriverState *bs)
1372 return 1;
1375 static int raw_media_changed(BlockDriverState *bs)
1377 return -ENOTSUP;
1380 static int raw_eject(BlockDriverState *bs, int eject_flag)
1382 DWORD ret_count;
1384 if (s->type == FTYPE_FILE)
1385 return -ENOTSUP;
1386 if (eject_flag) {
1387 DeviceIoControl(s->hfile, IOCTL_STORAGE_EJECT_MEDIA,
1388 NULL, 0, NULL, 0, &lpBytesReturned, NULL);
1389 } else {
1390 DeviceIoControl(s->hfile, IOCTL_STORAGE_LOAD_MEDIA,
1391 NULL, 0, NULL, 0, &lpBytesReturned, NULL);
1395 static int raw_set_locked(BlockDriverState *bs, int locked)
1397 return -ENOTSUP;
1399 #endif
1401 BlockDriver bdrv_host_device = {
1402 "host_device",
1403 sizeof(BDRVRawState),
1404 NULL, /* no probe for protocols */
1405 hdev_open,
1406 NULL,
1407 NULL,
1408 raw_close,
1409 NULL,
1410 raw_flush,
1412 #if 0
1413 .bdrv_aio_read = raw_aio_read,
1414 .bdrv_aio_write = raw_aio_write,
1415 .bdrv_aio_cancel = raw_aio_cancel,
1416 .aiocb_size = sizeof(RawAIOCB);
1417 #endif
1418 .bdrv_pread = raw_pread,
1419 .bdrv_pwrite = raw_pwrite,
1420 .bdrv_getlength = raw_getlength,
1422 #endif /* _WIN32 */