Align file accesses with cache=off (Kevin Wolf, Laurent Vivier)
[qemu] / block-raw-posix.c
1 /*
2  * Block driver for RAW files (posix)
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 "qemu-common.h"
25 #ifndef QEMU_IMG
26 #include "qemu-timer.h"
27 #include "exec-all.h"
28 #endif
29 #include "block_int.h"
30 #include <assert.h>
31 #include <aio.h>
32
33 #ifdef CONFIG_COCOA
34 #include <paths.h>
35 #include <sys/param.h>
36 #include <IOKit/IOKitLib.h>
37 #include <IOKit/IOBSD.h>
38 #include <IOKit/storage/IOMediaBSDClient.h>
39 #include <IOKit/storage/IOMedia.h>
40 #include <IOKit/storage/IOCDMedia.h>
41 //#include <IOKit/storage/IOCDTypes.h>
42 #include <CoreFoundation/CoreFoundation.h>
43 #endif
44
45 #ifdef __sun__
46 #define _POSIX_PTHREAD_SEMANTICS 1
47 #include <signal.h>
48 #include <sys/dkio.h>
49 #endif
50 #ifdef __linux__
51 #include <sys/ioctl.h>
52 #include <linux/cdrom.h>
53 #include <linux/fd.h>
54 #endif
55 #ifdef __FreeBSD__
56 #include <sys/disk.h>
57 #endif
58
59 //#define DEBUG_FLOPPY
60
61 //#define DEBUG_BLOCK
62 #if defined(DEBUG_BLOCK) && !defined(QEMU_IMG)
63 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0)  \
64     { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
65 #else
66 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
67 #endif
68
69 #define FTYPE_FILE   0
70 #define FTYPE_CD     1
71 #define FTYPE_FD     2
72
73 /* if the FD is not accessed during that time (in ms), we try to
74    reopen it to see if the disk has been changed */
75 #define FD_OPEN_TIMEOUT 1000
76
77 typedef struct BDRVRawState {
78     int fd;
79     int type;
80     int open_flags;
81     unsigned int lseek_err_cnt;
82 #if defined(__linux__)
83     /* linux floppy specific */
84     int64_t fd_open_time;
85     int64_t fd_error_time;
86     int fd_got_error;
87     int fd_media_changed;
88 #endif
89 } BDRVRawState;
90
91 static int fd_open(BlockDriverState *bs);
92
93 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
94 {
95     BDRVRawState *s = bs->opaque;
96     int fd, open_flags, ret;
97
98     s->lseek_err_cnt = 0;
99
100     open_flags = O_BINARY;
101     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
102         open_flags |= O_RDWR;
103     } else {
104         open_flags |= O_RDONLY;
105         bs->read_only = 1;
106     }
107     if (flags & BDRV_O_CREAT)
108         open_flags |= O_CREAT | O_TRUNC;
109 #ifdef O_DIRECT
110     if (flags & BDRV_O_DIRECT)
111         open_flags |= O_DIRECT;
112 #endif
113
114     s->open_flags = open_flags;
115     s->type = FTYPE_FILE;
116
117     fd = open(filename, open_flags, 0644);
118     if (fd < 0) {
119         ret = -errno;
120         if (ret == -EROFS)
121             ret = -EACCES;
122         return ret;
123     }
124     s->fd = fd;
125     return 0;
126 }
127
128 /* XXX: use host sector size if necessary with:
129 #ifdef DIOCGSECTORSIZE
130         {
131             unsigned int sectorsize = 512;
132             if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
133                 sectorsize > bufsize)
134                 bufsize = sectorsize;
135         }
136 #endif
137 #ifdef CONFIG_COCOA
138         u_int32_t   blockSize = 512;
139         if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
140             bufsize = blockSize;
141         }
142 #endif
143 */
144
145 /* 
146  * offset and count are in bytes, but must be multiples of 512 for files 
147  * opened with O_DIRECT. buf must be aligned to 512 bytes then.
148  *
149  * This function may be called without alignment if the caller ensures
150  * that O_DIRECT is not in effect.
151  */
152 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
153                      uint8_t *buf, int count)
154 {
155     BDRVRawState *s = bs->opaque;
156     int ret;
157
158     ret = fd_open(bs);
159     if (ret < 0)
160         return ret;
161
162     if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
163         ++(s->lseek_err_cnt);
164         if(s->lseek_err_cnt <= 10) {
165             DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
166                               "] lseek failed : %d = %s\n",
167                               s->fd, bs->filename, offset, buf, count,
168                               bs->total_sectors, errno, strerror(errno));
169         }
170         return -1;
171     }
172     s->lseek_err_cnt=0;
173
174     ret = read(s->fd, buf, count);
175     if (ret == count)
176         goto label__raw_read__success;
177
178     DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
179                       "] read failed %d : %d = %s\n",
180                       s->fd, bs->filename, offset, buf, count,
181                       bs->total_sectors, ret, errno, strerror(errno));
182
183     /* Try harder for CDrom. */
184     if (bs->type == BDRV_TYPE_CDROM) {
185         lseek(s->fd, offset, SEEK_SET);
186         ret = read(s->fd, buf, count);
187         if (ret == count)
188             goto label__raw_read__success;
189         lseek(s->fd, offset, SEEK_SET);
190         ret = read(s->fd, buf, count);
191         if (ret == count)
192             goto label__raw_read__success;
193
194         DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
195                           "] retry read failed %d : %d = %s\n",
196                           s->fd, bs->filename, offset, buf, count,
197                           bs->total_sectors, ret, errno, strerror(errno));
198     }
199
200 label__raw_read__success:
201
202     return ret;
203 }
204
205 /* 
206  * offset and count are in bytes, but must be multiples of 512 for files 
207  * opened with O_DIRECT. buf must be aligned to 512 bytes then.
208  *
209  * This function may be called without alignment if the caller ensures
210  * that O_DIRECT is not in effect.
211  */
212 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
213                       const uint8_t *buf, int count)
214 {
215     BDRVRawState *s = bs->opaque;
216     int ret;
217
218     ret = fd_open(bs);
219     if (ret < 0)
220         return ret;
221
222     if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
223         ++(s->lseek_err_cnt);
224         if(s->lseek_err_cnt) {
225             DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
226                               PRId64 "] lseek failed : %d = %s\n",
227                               s->fd, bs->filename, offset, buf, count,
228                               bs->total_sectors, errno, strerror(errno));
229         }
230         return -1;
231     }
232     s->lseek_err_cnt = 0;
233
234     ret = write(s->fd, buf, count);
235     if (ret == count)
236         goto label__raw_write__success;
237
238     DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
239                       "] write failed %d : %d = %s\n",
240                       s->fd, bs->filename, offset, buf, count,
241                       bs->total_sectors, ret, errno, strerror(errno));
242
243 label__raw_write__success:
244
245     return ret;
246 }
247
248
249 #ifdef O_DIRECT
250 /* 
251  * offset and count are in bytes and possibly not aligned. For files opened 
252  * with O_DIRECT, necessary alignments are ensured before calling 
253  * raw_pread_aligned to do the actual read.
254  */
255 static int raw_pread(BlockDriverState *bs, int64_t offset,
256                      uint8_t *buf, int count)
257 {
258     BDRVRawState *s = bs->opaque;
259
260     if (unlikely((s->open_flags & O_DIRECT) &&
261             (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
262
263         int ret;
264
265         // Temporarily disable O_DIRECT for unaligned access
266         fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
267         ret = raw_pread_aligned(bs, offset, buf, count);
268         fcntl(s->fd, F_SETFL, s->open_flags);
269
270         return ret;
271
272     } else {
273         return raw_pread_aligned(bs, offset, buf, count);
274     }
275 }
276
277 /* 
278  * offset and count are in bytes and possibly not aligned. For files opened 
279  * with O_DIRECT, necessary alignments are ensured before calling 
280  * raw_pwrite_aligned to do the actual write.
281  */
282 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
283                       const uint8_t *buf, int count)
284 {
285     BDRVRawState *s = bs->opaque;
286
287     if (unlikely((s->open_flags & O_DIRECT) &&
288             (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
289
290         int ret;
291
292         // Temporarily disable O_DIRECT for unaligned access
293         fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
294         ret = raw_pwrite_aligned(bs, offset, buf, count);
295         fcntl(s->fd, F_SETFL, s->open_flags);
296
297         return ret;
298     } else {
299         return raw_pwrite_aligned(bs, offset, buf, count);
300     }
301 }
302
303 #else
304 #define raw_pread raw_pread_aligned
305 #define raw_pwrite raw_pwrite_aligned
306 #endif
307
308
309 /***********************************************************/
310 /* Unix AIO using POSIX AIO */
311
312 typedef struct RawAIOCB {
313     BlockDriverAIOCB common;
314     struct aiocb aiocb;
315     struct RawAIOCB *next;
316 } RawAIOCB;
317
318 static int aio_sig_num = SIGUSR2;
319 static RawAIOCB *first_aio; /* AIO issued */
320 static int aio_initialized = 0;
321
322 static void aio_signal_handler(int signum)
323 {
324 #ifndef QEMU_IMG
325     CPUState *env = cpu_single_env;
326     if (env) {
327         /* stop the currently executing cpu because a timer occured */
328         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
329 #ifdef USE_KQEMU
330         if (env->kqemu_enabled) {
331             kqemu_cpu_interrupt(env);
332         }
333 #endif
334     }
335 #endif
336 }
337
338 void qemu_aio_init(void)
339 {
340     struct sigaction act;
341
342     aio_initialized = 1;
343
344     sigfillset(&act.sa_mask);
345     act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
346     act.sa_handler = aio_signal_handler;
347     sigaction(aio_sig_num, &act, NULL);
348
349 #if defined(__GLIBC__) && defined(__linux__)
350     {
351         /* XXX: aio thread exit seems to hang on RedHat 9 and this init
352            seems to fix the problem. */
353         struct aioinit ai;
354         memset(&ai, 0, sizeof(ai));
355         ai.aio_threads = 1;
356         ai.aio_num = 1;
357         ai.aio_idle_time = 365 * 100000;
358         aio_init(&ai);
359     }
360 #endif
361 }
362
363 void qemu_aio_poll(void)
364 {
365     RawAIOCB *acb, **pacb;
366     int ret;
367
368     for(;;) {
369         pacb = &first_aio;
370         for(;;) {
371             acb = *pacb;
372             if (!acb)
373                 goto the_end;
374             ret = aio_error(&acb->aiocb);
375             if (ret == ECANCELED) {
376                 /* remove the request */
377                 *pacb = acb->next;
378                 qemu_aio_release(acb);
379             } else if (ret != EINPROGRESS) {
380                 /* end of aio */
381                 if (ret == 0) {
382                     ret = aio_return(&acb->aiocb);
383                     if (ret == acb->aiocb.aio_nbytes)
384                         ret = 0;
385                     else
386                         ret = -EINVAL;
387                 } else {
388                     ret = -ret;
389                 }
390                 /* remove the request */
391                 *pacb = acb->next;
392                 /* call the callback */
393                 acb->common.cb(acb->common.opaque, ret);
394                 qemu_aio_release(acb);
395                 break;
396             } else {
397                 pacb = &acb->next;
398             }
399         }
400     }
401  the_end: ;
402 }
403
404 /* Wait for all IO requests to complete.  */
405 void qemu_aio_flush(void)
406 {
407     qemu_aio_wait_start();
408     qemu_aio_poll();
409     while (first_aio) {
410         qemu_aio_wait();
411     }
412     qemu_aio_wait_end();
413 }
414
415 /* wait until at least one AIO was handled */
416 static sigset_t wait_oset;
417
418 void qemu_aio_wait_start(void)
419 {
420     sigset_t set;
421
422     if (!aio_initialized)
423         qemu_aio_init();
424     sigemptyset(&set);
425     sigaddset(&set, aio_sig_num);
426     sigprocmask(SIG_BLOCK, &set, &wait_oset);
427 }
428
429 void qemu_aio_wait(void)
430 {
431     sigset_t set;
432     int nb_sigs;
433
434 #ifndef QEMU_IMG
435     if (qemu_bh_poll())
436         return;
437 #endif
438     sigemptyset(&set);
439     sigaddset(&set, aio_sig_num);
440     sigwait(&set, &nb_sigs);
441     qemu_aio_poll();
442 }
443
444 void qemu_aio_wait_end(void)
445 {
446     sigprocmask(SIG_SETMASK, &wait_oset, NULL);
447 }
448
449 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
450         int64_t sector_num, uint8_t *buf, int nb_sectors,
451         BlockDriverCompletionFunc *cb, void *opaque)
452 {
453     BDRVRawState *s = bs->opaque;
454     RawAIOCB *acb;
455
456     if (fd_open(bs) < 0)
457         return NULL;
458
459     acb = qemu_aio_get(bs, cb, opaque);
460     if (!acb)
461         return NULL;
462     acb->aiocb.aio_fildes = s->fd;
463     acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
464     acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
465     acb->aiocb.aio_buf = buf;
466     if (nb_sectors < 0)
467         acb->aiocb.aio_nbytes = -nb_sectors;
468     else
469         acb->aiocb.aio_nbytes = nb_sectors * 512;
470     acb->aiocb.aio_offset = sector_num * 512;
471     acb->next = first_aio;
472     first_aio = acb;
473     return acb;
474 }
475
476 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
477         int64_t sector_num, uint8_t *buf, int nb_sectors,
478         BlockDriverCompletionFunc *cb, void *opaque)
479 {
480     RawAIOCB *acb;
481     BDRVRawState *s = bs->opaque;
482
483     /* 
484      * If O_DIRECT is used and the buffer is not aligned fall back
485      * to synchronous IO.
486      */
487     if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
488         int ret;
489
490         acb = qemu_aio_get(bs, cb, opaque);
491         ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
492         acb->common.cb(acb->common.opaque, ret);
493         qemu_aio_release(acb);
494         return &acb->common;
495     }
496
497     acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
498     if (!acb)
499         return NULL;
500
501     if (aio_read(&acb->aiocb) < 0) {
502         qemu_aio_release(acb);
503         return NULL;
504     }
505     return &acb->common;
506 }
507
508 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
509         int64_t sector_num, const uint8_t *buf, int nb_sectors,
510         BlockDriverCompletionFunc *cb, void *opaque)
511 {
512     RawAIOCB *acb;
513     BDRVRawState *s = bs->opaque;
514
515     /* 
516      * If O_DIRECT is used and the buffer is not aligned fall back
517      * to synchronous IO.
518      */
519     if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
520         int ret;
521
522         acb = qemu_aio_get(bs, cb, opaque);
523         ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
524         acb->common.cb(acb->common.opaque, ret);
525         qemu_aio_release(acb);
526         return &acb->common;
527     }
528
529     acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
530     if (!acb)
531         return NULL;
532     if (aio_write(&acb->aiocb) < 0) {
533         qemu_aio_release(acb);
534         return NULL;
535     }
536     return &acb->common;
537 }
538
539 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
540 {
541     int ret;
542     RawAIOCB *acb = (RawAIOCB *)blockacb;
543     RawAIOCB **pacb;
544
545     ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
546     if (ret == AIO_NOTCANCELED) {
547         /* fail safe: if the aio could not be canceled, we wait for
548            it */
549         while (aio_error(&acb->aiocb) == EINPROGRESS);
550     }
551
552     /* remove the callback from the queue */
553     pacb = &first_aio;
554     for(;;) {
555         if (*pacb == NULL) {
556             break;
557         } else if (*pacb == acb) {
558             *pacb = acb->next;
559             qemu_aio_release(acb);
560             break;
561         }
562         pacb = &acb->next;
563     }
564 }
565
566 static void raw_close(BlockDriverState *bs)
567 {
568     BDRVRawState *s = bs->opaque;
569     if (s->fd >= 0) {
570         close(s->fd);
571         s->fd = -1;
572     }
573 }
574
575 static int raw_truncate(BlockDriverState *bs, int64_t offset)
576 {
577     BDRVRawState *s = bs->opaque;
578     if (s->type != FTYPE_FILE)
579         return -ENOTSUP;
580     if (ftruncate(s->fd, offset) < 0)
581         return -errno;
582     return 0;
583 }
584
585 static int64_t  raw_getlength(BlockDriverState *bs)
586 {
587     BDRVRawState *s = bs->opaque;
588     int fd = s->fd;
589     int64_t size;
590 #ifdef _BSD
591     struct stat sb;
592 #endif
593 #ifdef __sun__
594     struct dk_minfo minfo;
595     int rv;
596 #endif
597     int ret;
598
599     ret = fd_open(bs);
600     if (ret < 0)
601         return ret;
602
603 #ifdef _BSD
604     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
605 #ifdef DIOCGMEDIASIZE
606         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
607 #endif
608 #ifdef CONFIG_COCOA
609         size = LONG_LONG_MAX;
610 #else
611         size = lseek(fd, 0LL, SEEK_END);
612 #endif
613     } else
614 #endif
615 #ifdef __sun__
616     /*
617      * use the DKIOCGMEDIAINFO ioctl to read the size.
618      */
619     rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
620     if ( rv != -1 ) {
621         size = minfo.dki_lbsize * minfo.dki_capacity;
622     } else /* there are reports that lseek on some devices
623               fails, but irc discussion said that contingency
624               on contingency was overkill */
625 #endif
626     {
627         size = lseek(fd, 0, SEEK_END);
628     }
629     return size;
630 }
631
632 static int raw_create(const char *filename, int64_t total_size,
633                       const char *backing_file, int flags)
634 {
635     int fd;
636
637     if (flags || backing_file)
638         return -ENOTSUP;
639
640     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
641               0644);
642     if (fd < 0)
643         return -EIO;
644     ftruncate(fd, total_size * 512);
645     close(fd);
646     return 0;
647 }
648
649 static void raw_flush(BlockDriverState *bs)
650 {
651     BDRVRawState *s = bs->opaque;
652     fsync(s->fd);
653 }
654
655 BlockDriver bdrv_raw = {
656     "raw",
657     sizeof(BDRVRawState),
658     NULL, /* no probe for protocols */
659     raw_open,
660     NULL,
661     NULL,
662     raw_close,
663     raw_create,
664     raw_flush,
665
666     .bdrv_aio_read = raw_aio_read,
667     .bdrv_aio_write = raw_aio_write,
668     .bdrv_aio_cancel = raw_aio_cancel,
669     .aiocb_size = sizeof(RawAIOCB),
670     .protocol_name = "file",
671     .bdrv_pread = raw_pread,
672     .bdrv_pwrite = raw_pwrite,
673     .bdrv_truncate = raw_truncate,
674     .bdrv_getlength = raw_getlength,
675 };
676
677 /***********************************************/
678 /* host device */
679
680 #ifdef CONFIG_COCOA
681 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
682 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
683
684 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
685 {
686     kern_return_t       kernResult;
687     mach_port_t     masterPort;
688     CFMutableDictionaryRef  classesToMatch;
689
690     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
691     if ( KERN_SUCCESS != kernResult ) {
692         printf( "IOMasterPort returned %d\n", kernResult );
693     }
694
695     classesToMatch = IOServiceMatching( kIOCDMediaClass );
696     if ( classesToMatch == NULL ) {
697         printf( "IOServiceMatching returned a NULL dictionary.\n" );
698     } else {
699     CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
700     }
701     kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
702     if ( KERN_SUCCESS != kernResult )
703     {
704         printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
705     }
706
707     return kernResult;
708 }
709
710 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
711 {
712     io_object_t     nextMedia;
713     kern_return_t   kernResult = KERN_FAILURE;
714     *bsdPath = '\0';
715     nextMedia = IOIteratorNext( mediaIterator );
716     if ( nextMedia )
717     {
718         CFTypeRef   bsdPathAsCFString;
719     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
720         if ( bsdPathAsCFString ) {
721             size_t devPathLength;
722             strcpy( bsdPath, _PATH_DEV );
723             strcat( bsdPath, "r" );
724             devPathLength = strlen( bsdPath );
725             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
726                 kernResult = KERN_SUCCESS;
727             }
728             CFRelease( bsdPathAsCFString );
729         }
730         IOObjectRelease( nextMedia );
731     }
732
733     return kernResult;
734 }
735
736 #endif
737
738 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
739 {
740     BDRVRawState *s = bs->opaque;
741     int fd, open_flags, ret;
742
743 #ifdef CONFIG_COCOA
744     if (strstart(filename, "/dev/cdrom", NULL)) {
745         kern_return_t kernResult;
746         io_iterator_t mediaIterator;
747         char bsdPath[ MAXPATHLEN ];
748         int fd;
749
750         kernResult = FindEjectableCDMedia( &mediaIterator );
751         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
752
753         if ( bsdPath[ 0 ] != '\0' ) {
754             strcat(bsdPath,"s0");
755             /* some CDs don't have a partition 0 */
756             fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
757             if (fd < 0) {
758                 bsdPath[strlen(bsdPath)-1] = '1';
759             } else {
760                 close(fd);
761             }
762             filename = bsdPath;
763         }
764
765         if ( mediaIterator )
766             IOObjectRelease( mediaIterator );
767     }
768 #endif
769     open_flags = O_BINARY;
770     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
771         open_flags |= O_RDWR;
772     } else {
773         open_flags |= O_RDONLY;
774         bs->read_only = 1;
775     }
776 #ifdef O_DIRECT
777     if (flags & BDRV_O_DIRECT)
778         open_flags |= O_DIRECT;
779 #endif
780
781     s->type = FTYPE_FILE;
782 #if defined(__linux__)
783     if (strstart(filename, "/dev/cd", NULL)) {
784         /* open will not fail even if no CD is inserted */
785         open_flags |= O_NONBLOCK;
786         s->type = FTYPE_CD;
787     } else if (strstart(filename, "/dev/fd", NULL)) {
788         s->type = FTYPE_FD;
789         s->open_flags = open_flags;
790         /* open will not fail even if no floppy is inserted */
791         open_flags |= O_NONBLOCK;
792     } else if (strstart(filename, "/dev/sg", NULL)) {
793         bs->sg = 1;
794     }
795 #endif
796     fd = open(filename, open_flags, 0644);
797     if (fd < 0) {
798         ret = -errno;
799         if (ret == -EROFS)
800             ret = -EACCES;
801         return ret;
802     }
803     s->fd = fd;
804 #if defined(__linux__)
805     /* close fd so that we can reopen it as needed */
806     if (s->type == FTYPE_FD) {
807         close(s->fd);
808         s->fd = -1;
809         s->fd_media_changed = 1;
810     }
811 #endif
812     return 0;
813 }
814
815 #if defined(__linux__) && !defined(QEMU_IMG)
816
817 /* Note: we do not have a reliable method to detect if the floppy is
818    present. The current method is to try to open the floppy at every
819    I/O and to keep it opened during a few hundreds of ms. */
820 static int fd_open(BlockDriverState *bs)
821 {
822     BDRVRawState *s = bs->opaque;
823     int last_media_present;
824
825     if (s->type != FTYPE_FD)
826         return 0;
827     last_media_present = (s->fd >= 0);
828     if (s->fd >= 0 &&
829         (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
830         close(s->fd);
831         s->fd = -1;
832 #ifdef DEBUG_FLOPPY
833         printf("Floppy closed\n");
834 #endif
835     }
836     if (s->fd < 0) {
837         if (s->fd_got_error &&
838             (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
839 #ifdef DEBUG_FLOPPY
840             printf("No floppy (open delayed)\n");
841 #endif
842             return -EIO;
843         }
844         s->fd = open(bs->filename, s->open_flags);
845         if (s->fd < 0) {
846             s->fd_error_time = qemu_get_clock(rt_clock);
847             s->fd_got_error = 1;
848             if (last_media_present)
849                 s->fd_media_changed = 1;
850 #ifdef DEBUG_FLOPPY
851             printf("No floppy\n");
852 #endif
853             return -EIO;
854         }
855 #ifdef DEBUG_FLOPPY
856         printf("Floppy opened\n");
857 #endif
858     }
859     if (!last_media_present)
860         s->fd_media_changed = 1;
861     s->fd_open_time = qemu_get_clock(rt_clock);
862     s->fd_got_error = 0;
863     return 0;
864 }
865 #else
866 static int fd_open(BlockDriverState *bs)
867 {
868     return 0;
869 }
870 #endif
871
872 #if defined(__linux__)
873
874 static int raw_is_inserted(BlockDriverState *bs)
875 {
876     BDRVRawState *s = bs->opaque;
877     int ret;
878
879     switch(s->type) {
880     case FTYPE_CD:
881         ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
882         if (ret == CDS_DISC_OK)
883             return 1;
884         else
885             return 0;
886         break;
887     case FTYPE_FD:
888         ret = fd_open(bs);
889         return (ret >= 0);
890     default:
891         return 1;
892     }
893 }
894
895 /* currently only used by fdc.c, but a CD version would be good too */
896 static int raw_media_changed(BlockDriverState *bs)
897 {
898     BDRVRawState *s = bs->opaque;
899
900     switch(s->type) {
901     case FTYPE_FD:
902         {
903             int ret;
904             /* XXX: we do not have a true media changed indication. It
905                does not work if the floppy is changed without trying
906                to read it */
907             fd_open(bs);
908             ret = s->fd_media_changed;
909             s->fd_media_changed = 0;
910 #ifdef DEBUG_FLOPPY
911             printf("Floppy changed=%d\n", ret);
912 #endif
913             return ret;
914         }
915     default:
916         return -ENOTSUP;
917     }
918 }
919
920 static int raw_eject(BlockDriverState *bs, int eject_flag)
921 {
922     BDRVRawState *s = bs->opaque;
923
924     switch(s->type) {
925     case FTYPE_CD:
926         if (eject_flag) {
927             if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
928                 perror("CDROMEJECT");
929         } else {
930             if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
931                 perror("CDROMEJECT");
932         }
933         break;
934     case FTYPE_FD:
935         {
936             int fd;
937             if (s->fd >= 0) {
938                 close(s->fd);
939                 s->fd = -1;
940             }
941             fd = open(bs->filename, s->open_flags | O_NONBLOCK);
942             if (fd >= 0) {
943                 if (ioctl(fd, FDEJECT, 0) < 0)
944                     perror("FDEJECT");
945                 close(fd);
946             }
947         }
948         break;
949     default:
950         return -ENOTSUP;
951     }
952     return 0;
953 }
954
955 static int raw_set_locked(BlockDriverState *bs, int locked)
956 {
957     BDRVRawState *s = bs->opaque;
958
959     switch(s->type) {
960     case FTYPE_CD:
961         if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
962             /* Note: an error can happen if the distribution automatically
963                mounts the CD-ROM */
964             //        perror("CDROM_LOCKDOOR");
965         }
966         break;
967     default:
968         return -ENOTSUP;
969     }
970     return 0;
971 }
972
973 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
974 {
975     BDRVRawState *s = bs->opaque;
976
977     return ioctl(s->fd, req, buf);
978 }
979 #else
980
981 static int raw_is_inserted(BlockDriverState *bs)
982 {
983     return 1;
984 }
985
986 static int raw_media_changed(BlockDriverState *bs)
987 {
988     return -ENOTSUP;
989 }
990
991 static int raw_eject(BlockDriverState *bs, int eject_flag)
992 {
993     return -ENOTSUP;
994 }
995
996 static int raw_set_locked(BlockDriverState *bs, int locked)
997 {
998     return -ENOTSUP;
999 }
1000
1001 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1002 {
1003     return -ENOTSUP;
1004 }
1005 #endif /* !linux */
1006
1007 BlockDriver bdrv_host_device = {
1008     "host_device",
1009     sizeof(BDRVRawState),
1010     NULL, /* no probe for protocols */
1011     hdev_open,
1012     NULL,
1013     NULL,
1014     raw_close,
1015     NULL,
1016     raw_flush,
1017
1018     .bdrv_aio_read = raw_aio_read,
1019     .bdrv_aio_write = raw_aio_write,
1020     .bdrv_aio_cancel = raw_aio_cancel,
1021     .aiocb_size = sizeof(RawAIOCB),
1022     .bdrv_pread = raw_pread,
1023     .bdrv_pwrite = raw_pwrite,
1024     .bdrv_getlength = raw_getlength,
1025
1026     /* removable device support */
1027     .bdrv_is_inserted = raw_is_inserted,
1028     .bdrv_media_changed = raw_media_changed,
1029     .bdrv_eject = raw_eject,
1030     .bdrv_set_locked = raw_set_locked,
1031     /* generic scsi device */
1032     .bdrv_ioctl = raw_ioctl,
1033 };