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