no need for bdrv_close()
[qemu] / block-raw.c
1 /*
2  * Block driver for RAW files
3  * 
4  * Copyright (c) 2006 Fabrice Bellard
5  * 
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 #include "vl.h"
25 #include "block_int.h"
26 #include <assert.h>
27 #ifndef _WIN32
28 #include <aio.h>
29
30 #ifndef QEMU_TOOL
31 #include "exec-all.h"
32 #endif
33
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
45
46 #ifdef __sun__
47 #include <sys/dkio.h>
48 #endif
49 #ifdef __linux__
50 #include <sys/ioctl.h>
51 #include <linux/cdrom.h>
52 #include <linux/fd.h>
53 #endif
54
55 //#define DEBUG_FLOPPY
56
57 #define FTYPE_FILE   0
58 #define FTYPE_CD     1
59 #define FTYPE_FD     2
60
61 /* if the FD is not accessed during that time (in ms), we try to
62    reopen it to see if the disk has been changed */
63 #define FD_OPEN_TIMEOUT 1000
64
65 typedef struct BDRVRawState {
66     int fd;
67     int type;
68 #if defined(__linux__)
69     /* linux floppy specific */
70     int fd_open_flags;
71     int64_t fd_open_time;
72     int64_t fd_error_time;
73     int fd_got_error;
74     int fd_media_changed;
75 #endif
76 } BDRVRawState;
77
78 static int fd_open(BlockDriverState *bs);
79
80 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
81 {
82     BDRVRawState *s = bs->opaque;
83     int fd, open_flags, ret;
84
85     open_flags = O_BINARY;
86     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
87         open_flags |= O_RDWR;
88     } else {
89         open_flags |= O_RDONLY;
90         bs->read_only = 1;
91     }
92     if (flags & BDRV_O_CREAT)
93         open_flags |= O_CREAT | O_TRUNC;
94
95     s->type = FTYPE_FILE;
96
97     fd = open(filename, open_flags, 0644);
98     if (fd < 0) {
99         ret = -errno;
100         if (ret == -EROFS)
101             ret = -EACCES;
102         return ret;
103     }
104     s->fd = fd;
105     return 0;
106 }
107
108 /* XXX: use host sector size if necessary with:
109 #ifdef DIOCGSECTORSIZE
110         {
111             unsigned int sectorsize = 512;
112             if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
113                 sectorsize > bufsize)
114                 bufsize = sectorsize;
115         }
116 #endif
117 #ifdef CONFIG_COCOA
118         u_int32_t   blockSize = 512;
119         if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
120             bufsize = blockSize;
121         }
122 #endif
123 */
124
125 static int raw_pread(BlockDriverState *bs, int64_t offset, 
126                      uint8_t *buf, int count)
127 {
128     BDRVRawState *s = bs->opaque;
129     int ret;
130     
131     ret = fd_open(bs);
132     if (ret < 0)
133         return ret;
134
135     lseek(s->fd, offset, SEEK_SET);
136     ret = read(s->fd, buf, count);
137     return ret;
138 }
139
140 static int raw_pwrite(BlockDriverState *bs, int64_t offset, 
141                       const uint8_t *buf, int count)
142 {
143     BDRVRawState *s = bs->opaque;
144     int ret;
145     
146     ret = fd_open(bs);
147     if (ret < 0)
148         return ret;
149
150     lseek(s->fd, offset, SEEK_SET);
151     ret = write(s->fd, buf, count);
152     return ret;
153 }
154
155 /***********************************************************/
156 /* Unix AIO using POSIX AIO */
157
158 typedef struct RawAIOCB {
159     BlockDriverAIOCB common;
160     struct aiocb aiocb;
161     struct RawAIOCB *next;
162 } RawAIOCB;
163
164 static int aio_sig_num = SIGUSR2;
165 static RawAIOCB *first_aio; /* AIO issued */
166 static int aio_initialized = 0;
167
168 static void aio_signal_handler(int signum)
169 {
170 #ifndef QEMU_TOOL
171     CPUState *env = cpu_single_env;
172     if (env) {
173         /* stop the currently executing cpu because a timer occured */
174         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
175 #ifdef USE_KQEMU
176         if (env->kqemu_enabled) {
177             kqemu_cpu_interrupt(env);
178         }
179 #endif
180     }
181 #endif
182 }
183
184 void qemu_aio_init(void)
185 {
186     struct sigaction act;
187
188     aio_initialized = 1;
189     
190     sigfillset(&act.sa_mask);
191     act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
192     act.sa_handler = aio_signal_handler;
193     sigaction(aio_sig_num, &act, NULL);
194
195 #if defined(__GLIBC__) && defined(__linux__)
196     {
197         /* XXX: aio thread exit seems to hang on RedHat 9 and this init
198            seems to fix the problem. */
199         struct aioinit ai;
200         memset(&ai, 0, sizeof(ai));
201         ai.aio_threads = 1;
202         ai.aio_num = 1;
203         ai.aio_idle_time = 365 * 100000;
204         aio_init(&ai);
205     }
206 #endif
207 }
208
209 void qemu_aio_poll(void)
210 {
211     RawAIOCB *acb, **pacb;
212     int ret;
213
214     for(;;) {
215         pacb = &first_aio;
216         for(;;) {
217             acb = *pacb;
218             if (!acb)
219                 goto the_end;
220             ret = aio_error(&acb->aiocb);
221             if (ret == ECANCELED) {
222                 /* remove the request */
223                 *pacb = acb->next;
224                 qemu_aio_release(acb);
225             } else if (ret != EINPROGRESS) {
226                 /* end of aio */
227                 if (ret == 0) {
228                     ret = aio_return(&acb->aiocb);
229                     if (ret == acb->aiocb.aio_nbytes)
230                         ret = 0;
231                     else
232                         ret = -EINVAL;
233                 } else {
234                     ret = -ret;
235                 }
236                 /* remove the request */
237                 *pacb = acb->next;
238                 /* call the callback */
239                 acb->common.cb(acb->common.opaque, ret);
240                 qemu_aio_release(acb);
241                 break;
242             } else {
243                 pacb = &acb->next;
244             }
245         }
246     }
247  the_end: ;
248 }
249
250 /* wait until at least one AIO was handled */
251 static sigset_t wait_oset;
252
253 void qemu_aio_wait_start(void)
254 {
255     sigset_t set;
256
257     if (!aio_initialized)
258         qemu_aio_init();
259     sigemptyset(&set);
260     sigaddset(&set, aio_sig_num);
261     sigprocmask(SIG_BLOCK, &set, &wait_oset);
262 }
263
264 void qemu_aio_wait(void)
265 {
266     sigset_t set;
267     int nb_sigs;
268
269 #ifndef QEMU_TOOL
270     if (qemu_bh_poll())
271         return;
272 #endif
273     sigemptyset(&set);
274     sigaddset(&set, aio_sig_num);
275     sigwait(&set, &nb_sigs);
276     qemu_aio_poll();
277 }
278
279 void qemu_aio_wait_end(void)
280 {
281     sigprocmask(SIG_SETMASK, &wait_oset, NULL);
282 }
283
284 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
285         int64_t sector_num, uint8_t *buf, int nb_sectors,
286         BlockDriverCompletionFunc *cb, void *opaque)
287 {
288     BDRVRawState *s = bs->opaque;
289     RawAIOCB *acb;
290
291     if (fd_open(bs) < 0)
292         return NULL;
293
294     acb = qemu_aio_get(bs, cb, opaque);
295     if (!acb)
296         return NULL;
297     acb->aiocb.aio_fildes = s->fd;
298     acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
299     acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
300     acb->aiocb.aio_buf = buf;
301     acb->aiocb.aio_nbytes = nb_sectors * 512;
302     acb->aiocb.aio_offset = sector_num * 512;
303     acb->next = first_aio;
304     first_aio = acb;
305     return acb;
306 }
307
308 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
309         int64_t sector_num, uint8_t *buf, int nb_sectors,
310         BlockDriverCompletionFunc *cb, void *opaque)
311 {
312     RawAIOCB *acb;
313
314     acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
315     if (!acb)
316         return NULL;
317     if (aio_read(&acb->aiocb) < 0) {
318         qemu_aio_release(acb);
319         return NULL;
320     } 
321     return &acb->common;
322 }
323
324 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
325         int64_t sector_num, const uint8_t *buf, int nb_sectors,
326         BlockDriverCompletionFunc *cb, void *opaque)
327 {
328     RawAIOCB *acb;
329
330     acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
331     if (!acb)
332         return NULL;
333     if (aio_write(&acb->aiocb) < 0) {
334         qemu_aio_release(acb);
335         return NULL;
336     } 
337     return &acb->common;
338 }
339
340 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
341 {
342     int ret;
343     RawAIOCB *acb = (RawAIOCB *)blockacb;
344     RawAIOCB **pacb;
345
346     ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
347     if (ret == AIO_NOTCANCELED) {
348         /* fail safe: if the aio could not be canceled, we wait for
349            it */
350         while (aio_error(&acb->aiocb) == EINPROGRESS);
351     }
352
353     /* remove the callback from the queue */
354     pacb = &first_aio;
355     for(;;) {
356         if (*pacb == NULL) {
357             break;
358         } else if (*pacb == acb) {
359             *pacb = acb->next;
360             qemu_aio_release(acb);
361             break;
362         }
363         pacb = &acb->next;
364     }
365 }
366
367 static void raw_close(BlockDriverState *bs)
368 {
369     BDRVRawState *s = bs->opaque;
370     if (s->fd >= 0) {
371         close(s->fd);
372         s->fd = -1;
373     }
374 }
375
376 static int raw_truncate(BlockDriverState *bs, int64_t offset)
377 {
378     BDRVRawState *s = bs->opaque;
379     if (s->type != FTYPE_FILE)
380         return -ENOTSUP;
381     if (ftruncate(s->fd, offset) < 0)
382         return -errno;
383     return 0;
384 }
385
386 static int64_t  raw_getlength(BlockDriverState *bs)
387 {
388     BDRVRawState *s = bs->opaque;
389     int fd = s->fd;
390     int64_t size;
391 #ifdef _BSD
392     struct stat sb;
393 #endif
394 #ifdef __sun__
395     struct dk_minfo minfo;
396     int rv;
397 #endif
398     int ret;
399
400     ret = fd_open(bs);
401     if (ret < 0)
402         return ret;
403
404 #ifdef _BSD
405     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
406 #ifdef DIOCGMEDIASIZE
407         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
408 #endif
409 #ifdef CONFIG_COCOA
410         size = LONG_LONG_MAX;
411 #else
412         size = lseek(fd, 0LL, SEEK_END);
413 #endif
414     } else
415 #endif
416 #ifdef __sun__
417     /*
418      * use the DKIOCGMEDIAINFO ioctl to read the size.
419      */
420     rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
421     if ( rv != -1 ) {
422         size = minfo.dki_lbsize * minfo.dki_capacity;
423     } else /* there are reports that lseek on some devices
424               fails, but irc discussion said that contingency
425               on contingency was overkill */
426 #endif
427     {
428         size = lseek(fd, 0, SEEK_END);
429     }
430     return size;
431 }
432
433 static int raw_create(const char *filename, int64_t total_size,
434                       const char *backing_file, int flags)
435 {
436     int fd;
437
438     if (flags || backing_file)
439         return -ENOTSUP;
440
441     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 
442               0644);
443     if (fd < 0)
444         return -EIO;
445     ftruncate(fd, total_size * 512);
446     close(fd);
447     return 0;
448 }
449
450 static void raw_flush(BlockDriverState *bs)
451 {
452     BDRVRawState *s = bs->opaque;
453     fsync(s->fd);
454 }
455
456 BlockDriver bdrv_raw = {
457     "raw",
458     sizeof(BDRVRawState),
459     NULL, /* no probe for protocols */
460     raw_open,
461     NULL,
462     NULL,
463     raw_close,
464     raw_create,
465     raw_flush,
466     
467     .bdrv_aio_read = raw_aio_read,
468     .bdrv_aio_write = raw_aio_write,
469     .bdrv_aio_cancel = raw_aio_cancel,
470     .aiocb_size = sizeof(RawAIOCB),
471     .protocol_name = "file",
472     .bdrv_pread = raw_pread,
473     .bdrv_pwrite = raw_pwrite,
474     .bdrv_truncate = raw_truncate,
475     .bdrv_getlength = raw_getlength,
476 };
477
478 /***********************************************/
479 /* host device */
480
481 #ifdef CONFIG_COCOA
482 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
483 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
484
485 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
486 {
487     kern_return_t       kernResult; 
488     mach_port_t     masterPort;
489     CFMutableDictionaryRef  classesToMatch;
490
491     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
492     if ( KERN_SUCCESS != kernResult ) {
493         printf( "IOMasterPort returned %d\n", kernResult );
494     }
495     
496     classesToMatch = IOServiceMatching( kIOCDMediaClass ); 
497     if ( classesToMatch == NULL ) {
498         printf( "IOServiceMatching returned a NULL dictionary.\n" );
499     } else {
500     CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
501     }
502     kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
503     if ( KERN_SUCCESS != kernResult )
504     {
505         printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
506     }
507     
508     return kernResult;
509 }
510
511 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
512 {
513     io_object_t     nextMedia;
514     kern_return_t   kernResult = KERN_FAILURE;
515     *bsdPath = '\0';
516     nextMedia = IOIteratorNext( mediaIterator );
517     if ( nextMedia )
518     {
519         CFTypeRef   bsdPathAsCFString;
520     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
521         if ( bsdPathAsCFString ) {
522             size_t devPathLength;
523             strcpy( bsdPath, _PATH_DEV );
524             strcat( bsdPath, "r" );
525             devPathLength = strlen( bsdPath );
526             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
527                 kernResult = KERN_SUCCESS;
528             }
529             CFRelease( bsdPathAsCFString );
530         }
531         IOObjectRelease( nextMedia );
532     }
533     
534     return kernResult;
535 }
536
537 #endif
538
539 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
540 {
541     BDRVRawState *s = bs->opaque;
542     int fd, open_flags, ret;
543
544 #ifdef CONFIG_COCOA
545     if (strstart(filename, "/dev/cdrom", NULL)) {
546         kern_return_t kernResult;
547         io_iterator_t mediaIterator;
548         char bsdPath[ MAXPATHLEN ];
549         int fd;
550  
551         kernResult = FindEjectableCDMedia( &mediaIterator );
552         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
553     
554         if ( bsdPath[ 0 ] != '\0' ) {
555             strcat(bsdPath,"s0");
556             /* some CDs don't have a partition 0 */
557             fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
558             if (fd < 0) {
559                 bsdPath[strlen(bsdPath)-1] = '1';
560             } else {
561                 close(fd);
562             }
563             filename = bsdPath;
564         }
565         
566         if ( mediaIterator )
567             IOObjectRelease( mediaIterator );
568     }
569 #endif
570     open_flags = O_BINARY;
571     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
572         open_flags |= O_RDWR;
573     } else {
574         open_flags |= O_RDONLY;
575         bs->read_only = 1;
576     }
577
578     s->type = FTYPE_FILE;
579 #if defined(__linux__)
580     if (strstart(filename, "/dev/cd", NULL)) {
581         /* open will not fail even if no CD is inserted */
582         open_flags |= O_NONBLOCK;
583         s->type = FTYPE_CD;
584     } else if (strstart(filename, "/dev/fd", NULL)) {
585         s->type = FTYPE_FD;
586         s->fd_open_flags = open_flags;
587         /* open will not fail even if no floppy is inserted */
588         open_flags |= O_NONBLOCK;
589     }
590 #endif
591     fd = open(filename, open_flags, 0644);
592     if (fd < 0) {
593         ret = -errno;
594         if (ret == -EROFS)
595             ret = -EACCES;
596         return ret;
597     }
598     s->fd = fd;
599 #if defined(__linux__)
600     /* close fd so that we can reopen it as needed */
601     if (s->type == FTYPE_FD) {
602         close(s->fd);
603         s->fd = -1;
604         s->fd_media_changed = 1;
605     }
606 #endif
607     return 0;
608 }
609
610 #if defined(__linux__) && !defined(QEMU_TOOL)
611
612 /* Note: we do not have a reliable method to detect if the floppy is
613    present. The current method is to try to open the floppy at every
614    I/O and to keep it opened during a few hundreds of ms. */
615 static int fd_open(BlockDriverState *bs)
616 {
617     BDRVRawState *s = bs->opaque;
618     int last_media_present;
619
620     if (s->type != FTYPE_FD)
621         return 0;
622     last_media_present = (s->fd >= 0);
623     if (s->fd >= 0 && 
624         (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
625         close(s->fd);
626         s->fd = -1;
627 #ifdef DEBUG_FLOPPY
628         printf("Floppy closed\n");
629 #endif
630     }
631     if (s->fd < 0) {
632         if (s->fd_got_error && 
633             (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
634 #ifdef DEBUG_FLOPPY
635             printf("No floppy (open delayed)\n");
636 #endif
637             return -EIO;
638         }
639         s->fd = open(bs->filename, s->fd_open_flags);
640         if (s->fd < 0) {
641             s->fd_error_time = qemu_get_clock(rt_clock);
642             s->fd_got_error = 1;
643             if (last_media_present)
644                 s->fd_media_changed = 1;
645 #ifdef DEBUG_FLOPPY
646             printf("No floppy\n");
647 #endif
648             return -EIO;
649         }
650 #ifdef DEBUG_FLOPPY
651         printf("Floppy opened\n");
652 #endif
653     }
654     if (!last_media_present)
655         s->fd_media_changed = 1;
656     s->fd_open_time = qemu_get_clock(rt_clock);
657     s->fd_got_error = 0;
658     return 0;
659 }
660 #else
661 static int fd_open(BlockDriverState *bs)
662 {
663     return 0;
664 }
665 #endif
666
667 #if defined(__linux__)
668
669 static int raw_is_inserted(BlockDriverState *bs)
670 {
671     BDRVRawState *s = bs->opaque;
672     int ret;
673
674     switch(s->type) {
675     case FTYPE_CD:
676         ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
677         if (ret == CDS_DISC_OK)
678             return 1;
679         else
680             return 0;
681         break;
682     case FTYPE_FD:
683         ret = fd_open(bs);
684         return (ret >= 0);
685     default:
686         return 1;
687     }
688 }
689
690 /* currently only used by fdc.c, but a CD version would be good too */
691 static int raw_media_changed(BlockDriverState *bs)
692 {
693     BDRVRawState *s = bs->opaque;
694
695     switch(s->type) {
696     case FTYPE_FD:
697         {
698             int ret;
699             /* XXX: we do not have a true media changed indication. It
700                does not work if the floppy is changed without trying
701                to read it */
702             fd_open(bs);
703             ret = s->fd_media_changed;
704             s->fd_media_changed = 0;
705 #ifdef DEBUG_FLOPPY
706             printf("Floppy changed=%d\n", ret);
707 #endif
708             return ret;
709         }
710     default:
711         return -ENOTSUP;
712     }
713 }
714
715 static int raw_eject(BlockDriverState *bs, int eject_flag)
716 {
717     BDRVRawState *s = bs->opaque;
718
719     switch(s->type) {
720     case FTYPE_CD:
721         if (eject_flag) {
722             if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
723                 perror("CDROMEJECT");
724         } else {
725             if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
726                 perror("CDROMEJECT");
727         }
728         break;
729     case FTYPE_FD:
730         {
731             int fd;
732             if (s->fd >= 0) {
733                 close(s->fd);
734                 s->fd = -1;
735             }
736             fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
737             if (fd >= 0) {
738                 if (ioctl(fd, FDEJECT, 0) < 0)
739                     perror("FDEJECT");
740                 close(fd);
741             }
742         }
743         break;
744     default:
745         return -ENOTSUP;
746     }
747     return 0;
748 }
749
750 static int raw_set_locked(BlockDriverState *bs, int locked)
751 {
752     BDRVRawState *s = bs->opaque;
753
754     switch(s->type) {
755     case FTYPE_CD:
756         if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
757             /* Note: an error can happen if the distribution automatically
758                mounts the CD-ROM */
759             //        perror("CDROM_LOCKDOOR");
760         }
761         break;
762     default:
763         return -ENOTSUP;
764     }
765     return 0;
766 }
767
768 #else
769
770 static int raw_is_inserted(BlockDriverState *bs)
771 {
772     return 1;
773 }
774
775 static int raw_media_changed(BlockDriverState *bs)
776 {
777     return -ENOTSUP;
778 }
779
780 static int raw_eject(BlockDriverState *bs, int eject_flag)
781 {
782     return -ENOTSUP;
783 }
784
785 static int raw_set_locked(BlockDriverState *bs, int locked)
786 {
787     return -ENOTSUP;
788 }
789
790 #endif /* !linux */
791
792 BlockDriver bdrv_host_device = {
793     "host_device",
794     sizeof(BDRVRawState),
795     NULL, /* no probe for protocols */
796     hdev_open,
797     NULL,
798     NULL,
799     raw_close,
800     NULL,
801     raw_flush,
802     
803     .bdrv_aio_read = raw_aio_read,
804     .bdrv_aio_write = raw_aio_write,
805     .bdrv_aio_cancel = raw_aio_cancel,
806     .aiocb_size = sizeof(RawAIOCB),
807     .bdrv_pread = raw_pread,
808     .bdrv_pwrite = raw_pwrite,
809     .bdrv_getlength = raw_getlength,
810
811     /* removable device support */
812     .bdrv_is_inserted = raw_is_inserted,
813     .bdrv_media_changed = raw_media_changed,
814     .bdrv_eject = raw_eject,
815     .bdrv_set_locked = raw_set_locked,
816 };
817
818 #else /* _WIN32 */
819
820 /* XXX: use another file ? */
821 #include <winioctl.h>
822
823 #define FTYPE_FILE 0
824 #define FTYPE_CD     1
825
826 typedef struct BDRVRawState {
827     HANDLE hfile;
828     int type;
829     char drive_letter[2];
830 } BDRVRawState;
831
832 typedef struct RawAIOCB {
833     BlockDriverAIOCB common;
834     HANDLE hEvent;
835     OVERLAPPED ov;
836     int count;
837 } RawAIOCB;
838
839 int qemu_ftruncate64(int fd, int64_t length)
840 {
841     LARGE_INTEGER li;
842     LONG high;
843     HANDLE h;
844     BOOL res;
845
846     if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
847         return -1;
848
849     h = (HANDLE)_get_osfhandle(fd);
850
851     /* get current position, ftruncate do not change position */
852     li.HighPart = 0;
853     li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
854     if (li.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
855         return -1;
856
857     high = length >> 32;
858     if (!SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN))
859         return -1;
860     res = SetEndOfFile(h);
861
862     /* back to old position */
863     SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
864     return res ? 0 : -1;
865 }
866
867 static int set_sparse(int fd)
868 {
869     DWORD returned;
870     return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
871                                  NULL, 0, NULL, 0, &returned, NULL);
872 }
873
874 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
875 {
876     BDRVRawState *s = bs->opaque;
877     int access_flags, create_flags;
878     DWORD overlapped;
879     char device_name[64];
880     const char *p;
881
882     if (strstart(filename, "/dev/cdrom", NULL)) {
883         if (find_cdrom(device_name, sizeof(device_name)) < 0)
884             return -ENOENT;
885         filename = device_name;
886     } else {
887         /* transform drive letters into device name */
888         if (((filename[0] >= 'a' && filename[0] <= 'z') ||
889              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
890             filename[1] == ':' && filename[2] == '\0') {
891             snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
892             filename = device_name;
893         }
894     }
895     s->type = find_device_type(filename);
896
897     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
898         access_flags = GENERIC_READ | GENERIC_WRITE;
899     } else {
900         access_flags = GENERIC_READ;
901     }
902     if (flags & BDRV_O_CREAT) {
903         create_flags = CREATE_ALWAYS;
904     } else {
905         create_flags = OPEN_EXISTING;
906     }
907 #ifdef QEMU_TOOL
908     overlapped = 0;
909 #else
910     overlapped = FILE_FLAG_OVERLAPPED;
911 #endif
912     s->hfile = CreateFile(filename, access_flags, 
913                           FILE_SHARE_READ, NULL,
914                           create_flags, overlapped, 0);
915     if (s->hfile == INVALID_HANDLE_VALUE) 
916         return -1;
917     return 0;
918 }
919
920 static int raw_pread(BlockDriverState *bs, int64_t offset, 
921                      uint8_t *buf, int count)
922 {
923     BDRVRawState *s = bs->opaque;
924     OVERLAPPED ov;
925     DWORD ret_count;
926     int ret;
927     
928     memset(&ov, 0, sizeof(ov));
929     ov.Offset = offset;
930     ov.OffsetHigh = offset >> 32;
931     ret = ReadFile(s->hfile, buf, count, &ret_count, &ov);
932     if (!ret) {
933         ret = GetOverlappedResult(s->hfile, &ov, &ret_count, TRUE);
934         if (!ret)
935             return -EIO;
936         else
937             return ret_count;
938     }
939     return ret_count;
940 }
941
942 static int raw_pwrite(BlockDriverState *bs, int64_t offset, 
943                       const uint8_t *buf, int count)
944 {
945     BDRVRawState *s = bs->opaque;
946     OVERLAPPED ov;
947     DWORD ret_count;
948     int ret;
949     
950     memset(&ov, 0, sizeof(ov));
951     ov.Offset = offset;
952     ov.OffsetHigh = offset >> 32;
953     ret = WriteFile(s->hfile, buf, count, &ret_count, &ov);
954     if (!ret) {
955         ret = GetOverlappedResult(s->hfile, &ov, &ret_count, TRUE);
956         if (!ret)
957             return -EIO;
958         else
959             return ret_count;
960     }
961     return ret_count;
962 }
963
964 #ifndef QEMU_TOOL
965 static void raw_aio_cb(void *opaque)
966 {
967     RawAIOCB *acb = opaque;
968     BlockDriverState *bs = acb->common.bs;
969     BDRVRawState *s = bs->opaque;
970     DWORD ret_count;
971     int ret;
972
973     ret = GetOverlappedResult(s->hfile, &acb->ov, &ret_count, TRUE);
974     if (!ret || ret_count != acb->count) {
975         acb->common.cb(acb->common.opaque, -EIO);
976     } else {
977         acb->common.cb(acb->common.opaque, 0);
978     }
979 }
980 #endif
981
982 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
983         int64_t sector_num, uint8_t *buf, int nb_sectors,
984         BlockDriverCompletionFunc *cb, void *opaque)
985 {
986     RawAIOCB *acb;
987     int64_t offset;
988
989     acb = qemu_aio_get(bs, cb, opaque);
990     if (acb->hEvent) {
991         acb->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
992         if (!acb->hEvent) {
993             qemu_aio_release(acb);
994             return NULL;
995         }
996     }
997     memset(&acb->ov, 0, sizeof(acb->ov));
998     offset = sector_num * 512;
999     acb->ov.Offset = offset;
1000     acb->ov.OffsetHigh = offset >> 32;
1001     acb->ov.hEvent = acb->hEvent;
1002     acb->count = nb_sectors * 512;
1003 #ifndef QEMU_TOOL
1004     qemu_add_wait_object(acb->ov.hEvent, raw_aio_cb, acb);
1005 #endif
1006     return acb;
1007 }
1008
1009 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
1010         int64_t sector_num, uint8_t *buf, int nb_sectors,
1011         BlockDriverCompletionFunc *cb, void *opaque)
1012 {
1013     BDRVRawState *s = bs->opaque;
1014     RawAIOCB *acb;
1015     int ret;
1016
1017     acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1018     if (!acb)
1019         return NULL;
1020     ret = ReadFile(s->hfile, buf, acb->count, NULL, &acb->ov);
1021     if (!ret) {
1022         qemu_aio_release(acb);
1023         return NULL;
1024     }
1025 #ifdef QEMU_TOOL
1026     qemu_aio_release(acb);
1027 #endif
1028     return (BlockDriverAIOCB *)acb;
1029 }
1030
1031 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
1032         int64_t sector_num, uint8_t *buf, int nb_sectors,
1033         BlockDriverCompletionFunc *cb, void *opaque)
1034 {
1035     BDRVRawState *s = bs->opaque;
1036     RawAIOCB *acb;
1037     int ret;
1038
1039     acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1040     if (!acb)
1041         return NULL;
1042     ret = WriteFile(s->hfile, buf, acb->count, NULL, &acb->ov);
1043     if (!ret) {
1044         qemu_aio_release(acb);
1045         return NULL;
1046     }
1047 #ifdef QEMU_TOOL
1048     qemu_aio_release(acb);
1049 #endif
1050     return (BlockDriverAIOCB *)acb;
1051 }
1052
1053 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
1054 {
1055 #ifndef QEMU_TOOL
1056     RawAIOCB *acb = (RawAIOCB *)blockacb;
1057     BlockDriverState *bs = acb->common.bs;
1058     BDRVRawState *s = bs->opaque;
1059
1060     qemu_del_wait_object(acb->ov.hEvent, raw_aio_cb, acb);
1061     /* XXX: if more than one async I/O it is not correct */
1062     CancelIo(s->hfile);
1063     qemu_aio_release(acb);
1064 #endif
1065 }
1066
1067 static void raw_flush(BlockDriverState *bs)
1068 {
1069     /* XXX: add it */
1070 }
1071
1072 static void raw_close(BlockDriverState *bs)
1073 {
1074     BDRVRawState *s = bs->opaque;
1075     CloseHandle(s->hfile);
1076 }
1077
1078 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1079 {
1080     BDRVRawState *s = bs->opaque;
1081     DWORD low, high;
1082
1083     low = offset;
1084     high = offset >> 32;
1085     if (!SetFilePointer(s->hfile, low, &high, FILE_BEGIN))
1086         return -EIO;
1087     if (!SetEndOfFile(s->hfile))
1088         return -EIO;
1089     return 0;
1090 }
1091
1092 static int64_t  raw_getlength(BlockDriverState *bs)
1093 {
1094     BDRVRawState *s = bs->opaque;
1095     LARGE_INTEGER l;
1096     ULARGE_INTEGER available, total, total_free; 
1097
1098     switch(s->ftype) {
1099     case FTYPE_FILE:
1100         l.LowPart = GetFileSize(s->hfile, &l.HighPart);
1101         if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
1102             return -EIO;
1103         break;
1104     case FTYPE_CD:
1105         if (!GetDiskFreeSpaceEx(s->drive_letter, &available, &total, &total_free))
1106             return -EIO;
1107         l = total;
1108         break;
1109     default:
1110         return -EIO;
1111     }
1112     return l.QuadPart;
1113 }
1114
1115 static int raw_create(const char *filename, int64_t total_size,
1116                       const char *backing_file, int flags)
1117 {
1118     int fd;
1119
1120     if (flags || backing_file)
1121         return -ENOTSUP;
1122
1123     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 
1124               0644);
1125     if (fd < 0)
1126         return -EIO;
1127     set_sparse(fd);
1128     ftruncate(fd, total_size * 512);
1129     close(fd);
1130     return 0;
1131 }
1132
1133 void qemu_aio_init(void)
1134 {
1135 }
1136
1137 void qemu_aio_poll(void)
1138 {
1139 }
1140
1141 void qemu_aio_wait_start(void)
1142 {
1143 }
1144
1145 void qemu_aio_wait(void)
1146 {
1147 }
1148
1149 void qemu_aio_wait_end(void)
1150 {
1151 }
1152
1153 BlockDriver bdrv_raw = {
1154     "raw",
1155     sizeof(BDRVRawState),
1156     NULL, /* no probe for protocols */
1157     raw_open,
1158     NULL,
1159     NULL,
1160     raw_close,
1161     raw_create,
1162     raw_flush,
1163     
1164 #if 0
1165     .bdrv_aio_read = raw_aio_read,
1166     .bdrv_aio_write = raw_aio_write,
1167     .bdrv_aio_cancel = raw_aio_cancel,
1168     .aiocb_size = sizeof(RawAIOCB);
1169 #endif
1170     .protocol_name = "file",
1171     .bdrv_pread = raw_pread,
1172     .bdrv_pwrite = raw_pwrite,
1173     .bdrv_truncate = raw_truncate,
1174     .bdrv_getlength = raw_getlength,
1175 };
1176
1177 /***********************************************/
1178 /* host device */
1179
1180 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
1181 {
1182     char drives[256], *pdrv = drives;
1183     UINT type;
1184
1185     memset(drives, 0, sizeof(drivers));
1186     GetLogicalDriveStrings(sizeof(drives), drives);
1187     while(pdrv[0] != '\0') {
1188         type = GetDriveType(pdrv);
1189         switch(type) {
1190         case DRIVE_CDROM:
1191             snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
1192             return 0;
1193             break;
1194         }
1195         pdrv += lstrlen(pdrv) + 1;
1196     }
1197     return -1;
1198 }
1199
1200 static int find_device_type(const char *filename)
1201 {
1202     UINT type;
1203     const char *p;
1204
1205     if (strstart(filename, "\\\\.\\", &p) ||
1206         strstart(filename, "//./", &p)) {
1207         s->drive_letter[0] = p[0];
1208         s->drive_letter[1] = '\0';
1209         type = GetDriveType(s->drive_letter);
1210         if (type == DRIVE_CDROM)
1211             return FTYPE_CD;
1212         else
1213             return FTYPE_FILE;
1214     } else {
1215         return FTYPE_FILE;
1216     }
1217 }
1218
1219 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1220 {
1221     BDRVRawState *s = bs->opaque;
1222     int access_flags, create_flags;
1223     DWORD overlapped;
1224     char device_name[64];
1225     const char *p;
1226
1227     if (strstart(filename, "/dev/cdrom", NULL)) {
1228         if (find_cdrom(device_name, sizeof(device_name)) < 0)
1229             return -ENOENT;
1230         filename = device_name;
1231     } else {
1232         /* transform drive letters into device name */
1233         if (((filename[0] >= 'a' && filename[0] <= 'z') ||
1234              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1235             filename[1] == ':' && filename[2] == '\0') {
1236             snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
1237             filename = device_name;
1238         }
1239     }
1240     s->type = find_device_type(filename);
1241
1242     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
1243         access_flags = GENERIC_READ | GENERIC_WRITE;
1244     } else {
1245         access_flags = GENERIC_READ;
1246     }
1247     create_flags = OPEN_EXISTING;
1248
1249 #ifdef QEMU_TOOL
1250     overlapped = 0;
1251 #else
1252     overlapped = FILE_FLAG_OVERLAPPED;
1253 #endif
1254     s->hfile = CreateFile(filename, access_flags, 
1255                           FILE_SHARE_READ, NULL,
1256                           create_flags, overlapped, 0);
1257     if (s->hfile == INVALID_HANDLE_VALUE) 
1258         return -1;
1259     return 0;
1260 }
1261
1262 #if 0
1263 /***********************************************/
1264 /* removable device additionnal commands */
1265
1266 static int raw_is_inserted(BlockDriverState *bs)
1267 {
1268     return 1;
1269 }
1270
1271 static int raw_media_changed(BlockDriverState *bs)
1272 {
1273     return -ENOTSUP;
1274 }
1275
1276 static int raw_eject(BlockDriverState *bs, int eject_flag)
1277 {
1278     DWORD ret_count;
1279
1280     if (s->type == FTYPE_FILE)
1281         return -ENOTSUP;
1282     if (eject_flag) {
1283         DeviceIoControl(s->hfile, IOCTL_STORAGE_EJECT_MEDIA, 
1284                         NULL, 0, NULL, 0, &lpBytesReturned, NULL);
1285     } else {
1286         DeviceIoControl(s->hfile, IOCTL_STORAGE_LOAD_MEDIA, 
1287                         NULL, 0, NULL, 0, &lpBytesReturned, NULL);
1288     }
1289 }
1290
1291 static int raw_set_locked(BlockDriverState *bs, int locked)
1292 {
1293     return -ENOTSUP;
1294 }
1295 #endif
1296
1297 BlockDriver bdrv_host_device = {
1298     "host_device",
1299     sizeof(BDRVRawState),
1300     NULL, /* no probe for protocols */
1301     hdev_open,
1302     NULL,
1303     NULL,
1304     raw_close,
1305     NULL,
1306     raw_flush,
1307     
1308 #if 0
1309     .bdrv_aio_read = raw_aio_read,
1310     .bdrv_aio_write = raw_aio_write,
1311     .bdrv_aio_cancel = raw_aio_cancel,
1312     .aiocb_size = sizeof(RawAIOCB);
1313 #endif
1314     .bdrv_pread = raw_pread,
1315     .bdrv_pwrite = raw_pwrite,
1316     .bdrv_getlength = raw_getlength,
1317 };
1318 #endif /* _WIN32 */