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