696128b80b66177908b19bb1c00cca1a85823ba8
[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 <assert.h>
29 #ifdef CONFIG_AIO
30 #include "posix-aio-compat.h"
31 #endif
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 <signal.h>
57 #include <sys/disk.h>
58 #endif
59
60 #ifdef __OpenBSD__
61 #include <sys/ioctl.h>
62 #include <sys/disklabel.h>
63 #include <sys/dkio.h>
64 #endif
65
66 #ifdef __DragonFly__
67 #include <sys/ioctl.h>
68 #include <sys/diskslice.h>
69 #endif
70
71 //#define DEBUG_FLOPPY
72
73 //#define DEBUG_BLOCK
74 #if defined(DEBUG_BLOCK)
75 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (qemu_log_enabled())     \
76     { qemu_log(formatCstr, ##args); qemu_log_flush(); } } while (0)
77 #else
78 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
79 #endif
80
81 /* OS X does not have O_DSYNC */
82 #ifndef O_DSYNC
83 #define O_DSYNC O_SYNC
84 #endif
85
86 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
87 #ifndef O_DIRECT
88 #define O_DIRECT O_DSYNC
89 #endif
90
91 #define FTYPE_FILE   0
92 #define FTYPE_CD     1
93 #define FTYPE_FD     2
94
95 #define ALIGNED_BUFFER_SIZE (32 * 512)
96
97 /* if the FD is not accessed during that time (in ms), we try to
98    reopen it to see if the disk has been changed */
99 #define FD_OPEN_TIMEOUT 1000
100
101 typedef struct BDRVRawState {
102     int fd;
103     int type;
104     unsigned int lseek_err_cnt;
105 #if defined(__linux__)
106     /* linux floppy specific */
107     int fd_open_flags;
108     int64_t fd_open_time;
109     int64_t fd_error_time;
110     int fd_got_error;
111     int fd_media_changed;
112 #endif
113     uint8_t* aligned_buf;
114 } BDRVRawState;
115
116 static int posix_aio_init(void);
117
118 static int fd_open(BlockDriverState *bs);
119
120 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
121 {
122     BDRVRawState *s = bs->opaque;
123     int fd, open_flags, ret;
124
125     posix_aio_init();
126
127     s->lseek_err_cnt = 0;
128
129     open_flags = O_BINARY;
130     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
131         open_flags |= O_RDWR;
132     } else {
133         open_flags |= O_RDONLY;
134         bs->read_only = 1;
135     }
136     if (flags & BDRV_O_CREAT)
137         open_flags |= O_CREAT | O_TRUNC;
138
139     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
140      * and O_DIRECT for no caching. */
141     if ((flags & BDRV_O_NOCACHE))
142         open_flags |= O_DIRECT;
143     else if (!(flags & BDRV_O_CACHE_WB))
144         open_flags |= O_DSYNC;
145
146     s->type = FTYPE_FILE;
147
148     fd = open(filename, open_flags, 0644);
149     if (fd < 0) {
150         ret = -errno;
151         if (ret == -EROFS)
152             ret = -EACCES;
153         return ret;
154     }
155     s->fd = fd;
156     s->aligned_buf = NULL;
157     if ((flags & BDRV_O_NOCACHE)) {
158         s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
159         if (s->aligned_buf == NULL) {
160             ret = -errno;
161             close(fd);
162             return ret;
163         }
164     }
165     return 0;
166 }
167
168 /* XXX: use host sector size if necessary with:
169 #ifdef DIOCGSECTORSIZE
170         {
171             unsigned int sectorsize = 512;
172             if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
173                 sectorsize > bufsize)
174                 bufsize = sectorsize;
175         }
176 #endif
177 #ifdef CONFIG_COCOA
178         u_int32_t   blockSize = 512;
179         if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
180             bufsize = blockSize;
181         }
182 #endif
183 */
184
185 /*
186  * offset and count are in bytes, but must be multiples of 512 for files
187  * opened with O_DIRECT. buf must be aligned to 512 bytes then.
188  *
189  * This function may be called without alignment if the caller ensures
190  * that O_DIRECT is not in effect.
191  */
192 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
193                      uint8_t *buf, int count)
194 {
195     BDRVRawState *s = bs->opaque;
196     int ret;
197
198     ret = fd_open(bs);
199     if (ret < 0)
200         return ret;
201
202     if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
203         ++(s->lseek_err_cnt);
204         if(s->lseek_err_cnt <= 10) {
205             DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
206                               "] lseek failed : %d = %s\n",
207                               s->fd, bs->filename, offset, buf, count,
208                               bs->total_sectors, errno, strerror(errno));
209         }
210         return -1;
211     }
212     s->lseek_err_cnt=0;
213
214     ret = read(s->fd, buf, count);
215     if (ret == count)
216         goto label__raw_read__success;
217
218     DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
219                       "] read failed %d : %d = %s\n",
220                       s->fd, bs->filename, offset, buf, count,
221                       bs->total_sectors, ret, errno, strerror(errno));
222
223     /* Try harder for CDrom. */
224     if (bs->type == BDRV_TYPE_CDROM) {
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         lseek(s->fd, offset, SEEK_SET);
230         ret = read(s->fd, buf, count);
231         if (ret == count)
232             goto label__raw_read__success;
233
234         DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
235                           "] retry read failed %d : %d = %s\n",
236                           s->fd, bs->filename, offset, buf, count,
237                           bs->total_sectors, ret, errno, strerror(errno));
238     }
239
240 label__raw_read__success:
241
242     return ret;
243 }
244
245 /*
246  * offset and count are in bytes, but must be multiples of 512 for files
247  * opened with O_DIRECT. buf must be aligned to 512 bytes then.
248  *
249  * This function may be called without alignment if the caller ensures
250  * that O_DIRECT is not in effect.
251  */
252 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
253                       const uint8_t *buf, int count)
254 {
255     BDRVRawState *s = bs->opaque;
256     int ret;
257
258     ret = fd_open(bs);
259     if (ret < 0)
260         return -errno;
261
262     if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
263         ++(s->lseek_err_cnt);
264         if(s->lseek_err_cnt) {
265             DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
266                               PRId64 "] lseek failed : %d = %s\n",
267                               s->fd, bs->filename, offset, buf, count,
268                               bs->total_sectors, errno, strerror(errno));
269         }
270         return -EIO;
271     }
272     s->lseek_err_cnt = 0;
273
274     ret = write(s->fd, buf, count);
275     if (ret == count)
276         goto label__raw_write__success;
277
278     DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
279                       "] write failed %d : %d = %s\n",
280                       s->fd, bs->filename, offset, buf, count,
281                       bs->total_sectors, ret, errno, strerror(errno));
282
283 label__raw_write__success:
284
285     return  (ret < 0) ? -errno : ret;
286 }
287
288
289 /*
290  * offset and count are in bytes and possibly not aligned. For files opened
291  * with O_DIRECT, necessary alignments are ensured before calling
292  * raw_pread_aligned to do the actual read.
293  */
294 static int raw_pread(BlockDriverState *bs, int64_t offset,
295                      uint8_t *buf, int count)
296 {
297     BDRVRawState *s = bs->opaque;
298     int size, ret, shift, sum;
299
300     sum = 0;
301
302     if (s->aligned_buf != NULL)  {
303
304         if (offset & 0x1ff) {
305             /* align offset on a 512 bytes boundary */
306
307             shift = offset & 0x1ff;
308             size = (shift + count + 0x1ff) & ~0x1ff;
309             if (size > ALIGNED_BUFFER_SIZE)
310                 size = ALIGNED_BUFFER_SIZE;
311             ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
312             if (ret < 0)
313                 return ret;
314
315             size = 512 - shift;
316             if (size > count)
317                 size = count;
318             memcpy(buf, s->aligned_buf + shift, size);
319
320             buf += size;
321             offset += size;
322             count -= size;
323             sum += size;
324
325             if (count == 0)
326                 return sum;
327         }
328         if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
329
330             /* read on aligned buffer */
331
332             while (count) {
333
334                 size = (count + 0x1ff) & ~0x1ff;
335                 if (size > ALIGNED_BUFFER_SIZE)
336                     size = ALIGNED_BUFFER_SIZE;
337
338                 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
339                 if (ret < 0)
340                     return ret;
341
342                 size = ret;
343                 if (size > count)
344                     size = count;
345
346                 memcpy(buf, s->aligned_buf, size);
347
348                 buf += size;
349                 offset += size;
350                 count -= size;
351                 sum += size;
352             }
353
354             return sum;
355         }
356     }
357
358     return raw_pread_aligned(bs, offset, buf, count) + sum;
359 }
360
361 static int raw_read(BlockDriverState *bs, int64_t sector_num,
362                     uint8_t *buf, int nb_sectors)
363 {
364     return raw_pread(bs, sector_num * 512, buf, (uint64_t)nb_sectors * 512);
365 }
366
367 /*
368  * offset and count are in bytes and possibly not aligned. For files opened
369  * with O_DIRECT, necessary alignments are ensured before calling
370  * raw_pwrite_aligned to do the actual write.
371  */
372 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
373                       const uint8_t *buf, int count)
374 {
375     BDRVRawState *s = bs->opaque;
376     int size, ret, shift, sum;
377
378     sum = 0;
379
380     if (s->aligned_buf != NULL) {
381
382         if (offset & 0x1ff) {
383             /* align offset on a 512 bytes boundary */
384             shift = offset & 0x1ff;
385             ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
386             if (ret < 0)
387                 return ret;
388
389             size = 512 - shift;
390             if (size > count)
391                 size = count;
392             memcpy(s->aligned_buf + shift, buf, size);
393
394             ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
395             if (ret < 0)
396                 return ret;
397
398             buf += size;
399             offset += size;
400             count -= size;
401             sum += size;
402
403             if (count == 0)
404                 return sum;
405         }
406         if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
407
408             while ((size = (count & ~0x1ff)) != 0) {
409
410                 if (size > ALIGNED_BUFFER_SIZE)
411                     size = ALIGNED_BUFFER_SIZE;
412
413                 memcpy(s->aligned_buf, buf, size);
414
415                 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
416                 if (ret < 0)
417                     return ret;
418
419                 buf += ret;
420                 offset += ret;
421                 count -= ret;
422                 sum += ret;
423             }
424             /* here, count < 512 because (count & ~0x1ff) == 0 */
425             if (count) {
426                 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
427                 if (ret < 0)
428                     return ret;
429                  memcpy(s->aligned_buf, buf, count);
430
431                  ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
432                  if (ret < 0)
433                      return ret;
434                  if (count < ret)
435                      ret = count;
436
437                  sum += ret;
438             }
439             return sum;
440         }
441     }
442     return raw_pwrite_aligned(bs, offset, buf, count) + sum;
443 }
444
445 static int raw_write(BlockDriverState *bs, int64_t sector_num,
446                      const uint8_t *buf, int nb_sectors)
447 {
448     return raw_pwrite(bs, sector_num * 512, buf, (uint64_t)nb_sectors * 512);
449 }
450
451 #ifdef CONFIG_AIO
452 /***********************************************************/
453 /* Unix AIO using POSIX AIO */
454
455 typedef struct RawAIOCB {
456     BlockDriverAIOCB common;
457     struct qemu_paiocb aiocb;
458     struct RawAIOCB *next;
459     int ret;
460 } RawAIOCB;
461
462 typedef struct PosixAioState
463 {
464     int rfd, wfd;
465     RawAIOCB *first_aio;
466 } PosixAioState;
467
468 static void posix_aio_read(void *opaque)
469 {
470     PosixAioState *s = opaque;
471     RawAIOCB *acb, **pacb;
472     int ret;
473     ssize_t len;
474
475     /* read all bytes from signal pipe */
476     for (;;) {
477         char bytes[16];
478
479         len = read(s->rfd, bytes, sizeof(bytes));
480         if (len == -1 && errno == EINTR)
481             continue; /* try again */
482         if (len == sizeof(bytes))
483             continue; /* more to read */
484         break;
485     }
486
487     for(;;) {
488         pacb = &s->first_aio;
489         for(;;) {
490             acb = *pacb;
491             if (!acb)
492                 goto the_end;
493             ret = qemu_paio_error(&acb->aiocb);
494             if (ret == ECANCELED) {
495                 /* remove the request */
496                 *pacb = acb->next;
497                 qemu_aio_release(acb);
498             } else if (ret != EINPROGRESS) {
499                 /* end of aio */
500                 if (ret == 0) {
501                     ret = qemu_paio_return(&acb->aiocb);
502                     if (ret == acb->aiocb.aio_nbytes)
503                         ret = 0;
504                     else
505                         ret = -EINVAL;
506                 } else {
507                     ret = -ret;
508                 }
509                 /* remove the request */
510                 *pacb = acb->next;
511                 /* call the callback */
512                 acb->common.cb(acb->common.opaque, ret);
513                 qemu_aio_release(acb);
514                 break;
515             } else {
516                 pacb = &acb->next;
517             }
518         }
519     }
520  the_end: ;
521 }
522
523 static int posix_aio_flush(void *opaque)
524 {
525     PosixAioState *s = opaque;
526     return !!s->first_aio;
527 }
528
529 static PosixAioState *posix_aio_state;
530
531 static void aio_signal_handler(int signum)
532 {
533     if (posix_aio_state) {
534         char byte = 0;
535
536         write(posix_aio_state->wfd, &byte, sizeof(byte));
537     }
538
539     qemu_service_io();
540 }
541
542 static int posix_aio_init(void)
543 {
544     struct sigaction act;
545     PosixAioState *s;
546     int fds[2];
547     struct qemu_paioinit ai;
548   
549     if (posix_aio_state)
550         return 0;
551
552     s = qemu_malloc(sizeof(PosixAioState));
553
554     sigfillset(&act.sa_mask);
555     act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
556     act.sa_handler = aio_signal_handler;
557     sigaction(SIGUSR2, &act, NULL);
558
559     s->first_aio = NULL;
560     if (pipe(fds) == -1) {
561         fprintf(stderr, "failed to create pipe\n");
562         return -errno;
563     }
564
565     s->rfd = fds[0];
566     s->wfd = fds[1];
567
568     fcntl(s->rfd, F_SETFL, O_NONBLOCK);
569     fcntl(s->wfd, F_SETFL, O_NONBLOCK);
570
571     qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
572
573     memset(&ai, 0, sizeof(ai));
574     ai.aio_threads = 64;
575     ai.aio_num = 64;
576     qemu_paio_init(&ai);
577
578     posix_aio_state = s;
579
580     return 0;
581 }
582
583 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
584         int64_t sector_num, uint8_t *buf, int nb_sectors,
585         BlockDriverCompletionFunc *cb, void *opaque)
586 {
587     BDRVRawState *s = bs->opaque;
588     RawAIOCB *acb;
589
590     if (fd_open(bs) < 0)
591         return NULL;
592
593     acb = qemu_aio_get(bs, cb, opaque);
594     if (!acb)
595         return NULL;
596     acb->aiocb.aio_fildes = s->fd;
597     acb->aiocb.ev_signo = SIGUSR2;
598     acb->aiocb.aio_buf = buf;
599     if (nb_sectors < 0)
600         acb->aiocb.aio_nbytes = -nb_sectors;
601     else
602         acb->aiocb.aio_nbytes = nb_sectors * 512;
603     acb->aiocb.aio_offset = sector_num * 512;
604     acb->next = posix_aio_state->first_aio;
605     posix_aio_state->first_aio = acb;
606     return acb;
607 }
608
609 static void raw_aio_em_cb(void* opaque)
610 {
611     RawAIOCB *acb = opaque;
612     acb->common.cb(acb->common.opaque, acb->ret);
613     qemu_aio_release(acb);
614 }
615
616 static void raw_aio_remove(RawAIOCB *acb)
617 {
618     RawAIOCB **pacb;
619
620     /* remove the callback from the queue */
621     pacb = &posix_aio_state->first_aio;
622     for(;;) {
623         if (*pacb == NULL) {
624             fprintf(stderr, "raw_aio_remove: aio request not found!\n");
625             break;
626         } else if (*pacb == acb) {
627             *pacb = acb->next;
628             qemu_aio_release(acb);
629             break;
630         }
631         pacb = &(*pacb)->next;
632     }
633 }
634
635 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
636         int64_t sector_num, uint8_t *buf, int nb_sectors,
637         BlockDriverCompletionFunc *cb, void *opaque)
638 {
639     RawAIOCB *acb;
640
641     /*
642      * If O_DIRECT is used and the buffer is not aligned fall back
643      * to synchronous IO.
644      */
645     BDRVRawState *s = bs->opaque;
646
647     if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
648         QEMUBH *bh;
649         acb = qemu_aio_get(bs, cb, opaque);
650         acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
651         bh = qemu_bh_new(raw_aio_em_cb, acb);
652         qemu_bh_schedule(bh);
653         return &acb->common;
654     }
655
656     acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
657     if (!acb)
658         return NULL;
659     if (qemu_paio_read(&acb->aiocb) < 0) {
660         raw_aio_remove(acb);
661         return NULL;
662     }
663     return &acb->common;
664 }
665
666 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
667         int64_t sector_num, const uint8_t *buf, int nb_sectors,
668         BlockDriverCompletionFunc *cb, void *opaque)
669 {
670     RawAIOCB *acb;
671
672     /*
673      * If O_DIRECT is used and the buffer is not aligned fall back
674      * to synchronous IO.
675      */
676     BDRVRawState *s = bs->opaque;
677
678     if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
679         QEMUBH *bh;
680         acb = qemu_aio_get(bs, cb, opaque);
681         acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
682         bh = qemu_bh_new(raw_aio_em_cb, acb);
683         qemu_bh_schedule(bh);
684         return &acb->common;
685     }
686
687     acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
688     if (!acb)
689         return NULL;
690     if (qemu_paio_write(&acb->aiocb) < 0) {
691         raw_aio_remove(acb);
692         return NULL;
693     }
694     return &acb->common;
695 }
696
697 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
698 {
699     int ret;
700     RawAIOCB *acb = (RawAIOCB *)blockacb;
701
702     ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
703     if (ret == QEMU_PAIO_NOTCANCELED) {
704         /* fail safe: if the aio could not be canceled, we wait for
705            it */
706         while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
707     }
708
709     raw_aio_remove(acb);
710 }
711 #else /* CONFIG_AIO */
712 static int posix_aio_init(void)
713 {
714     return 0;
715 }
716 #endif /* CONFIG_AIO */
717
718
719 static void raw_close(BlockDriverState *bs)
720 {
721     BDRVRawState *s = bs->opaque;
722     if (s->fd >= 0) {
723         close(s->fd);
724         s->fd = -1;
725         if (s->aligned_buf != NULL)
726             qemu_free(s->aligned_buf);
727     }
728 }
729
730 static int raw_truncate(BlockDriverState *bs, int64_t offset)
731 {
732     BDRVRawState *s = bs->opaque;
733     if (s->type != FTYPE_FILE)
734         return -ENOTSUP;
735     if (ftruncate(s->fd, offset) < 0)
736         return -errno;
737     return 0;
738 }
739
740 #ifdef __OpenBSD__
741 static int64_t raw_getlength(BlockDriverState *bs)
742 {
743     BDRVRawState *s = bs->opaque;
744     int fd = s->fd;
745     struct stat st;
746
747     if (fstat(fd, &st))
748         return -1;
749     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
750         struct disklabel dl;
751
752         if (ioctl(fd, DIOCGDINFO, &dl))
753             return -1;
754         return (uint64_t)dl.d_secsize *
755             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
756     } else
757         return st.st_size;
758 }
759 #else /* !__OpenBSD__ */
760 static int64_t  raw_getlength(BlockDriverState *bs)
761 {
762     BDRVRawState *s = bs->opaque;
763     int fd = s->fd;
764     int64_t size;
765 #ifdef HOST_BSD
766     struct stat sb;
767 #endif
768 #ifdef __sun__
769     struct dk_minfo minfo;
770     int rv;
771 #endif
772     int ret;
773
774     ret = fd_open(bs);
775     if (ret < 0)
776         return ret;
777
778 #ifdef HOST_BSD
779     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
780 #ifdef DIOCGMEDIASIZE
781         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
782 #elif defined(DIOCGPART)
783         {
784                 struct partinfo pi;
785                 if (ioctl(fd, DIOCGPART, &pi) == 0)
786                         size = pi.media_size;
787                 else
788                         size = 0;
789         }
790         if (size == 0)
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
858     .bdrv_read = raw_read,
859     .bdrv_write = raw_write,
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     posix_aio_init();
931
932 #ifdef CONFIG_COCOA
933     if (strstart(filename, "/dev/cdrom", NULL)) {
934         kern_return_t kernResult;
935         io_iterator_t mediaIterator;
936         char bsdPath[ MAXPATHLEN ];
937         int fd;
938
939         kernResult = FindEjectableCDMedia( &mediaIterator );
940         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
941
942         if ( bsdPath[ 0 ] != '\0' ) {
943             strcat(bsdPath,"s0");
944             /* some CDs don't have a partition 0 */
945             fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
946             if (fd < 0) {
947                 bsdPath[strlen(bsdPath)-1] = '1';
948             } else {
949                 close(fd);
950             }
951             filename = bsdPath;
952         }
953
954         if ( mediaIterator )
955             IOObjectRelease( mediaIterator );
956     }
957 #endif
958     open_flags = O_BINARY;
959     if ((flags & BDRV_O_ACCESS) == O_RDWR) {
960         open_flags |= O_RDWR;
961     } else {
962         open_flags |= O_RDONLY;
963         bs->read_only = 1;
964     }
965     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
966      * and O_DIRECT for no caching. */
967     if ((flags & BDRV_O_NOCACHE))
968         open_flags |= O_DIRECT;
969     else if (!(flags & BDRV_O_CACHE_WB))
970         open_flags |= O_DSYNC;
971
972     s->type = FTYPE_FILE;
973 #if defined(__linux__)
974     if (strstart(filename, "/dev/cd", NULL)) {
975         /* open will not fail even if no CD is inserted */
976         open_flags |= O_NONBLOCK;
977         s->type = FTYPE_CD;
978     } else if (strstart(filename, "/dev/fd", NULL)) {
979         s->type = FTYPE_FD;
980         s->fd_open_flags = open_flags;
981         /* open will not fail even if no floppy is inserted */
982         open_flags |= O_NONBLOCK;
983     } else if (strstart(filename, "/dev/sg", NULL)) {
984         bs->sg = 1;
985     }
986 #endif
987     fd = open(filename, open_flags, 0644);
988     if (fd < 0) {
989         ret = -errno;
990         if (ret == -EROFS)
991             ret = -EACCES;
992         return ret;
993     }
994     s->fd = fd;
995 #if defined(__linux__)
996     /* close fd so that we can reopen it as needed */
997     if (s->type == FTYPE_FD) {
998         close(s->fd);
999         s->fd = -1;
1000         s->fd_media_changed = 1;
1001     }
1002 #endif
1003     return 0;
1004 }
1005
1006 #if defined(__linux__)
1007 /* Note: we do not have a reliable method to detect if the floppy is
1008    present. The current method is to try to open the floppy at every
1009    I/O and to keep it opened during a few hundreds of ms. */
1010 static int fd_open(BlockDriverState *bs)
1011 {
1012     BDRVRawState *s = bs->opaque;
1013     int last_media_present;
1014
1015     if (s->type != FTYPE_FD)
1016         return 0;
1017     last_media_present = (s->fd >= 0);
1018     if (s->fd >= 0 &&
1019         (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1020         close(s->fd);
1021         s->fd = -1;
1022 #ifdef DEBUG_FLOPPY
1023         printf("Floppy closed\n");
1024 #endif
1025     }
1026     if (s->fd < 0) {
1027         if (s->fd_got_error &&
1028             (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1029 #ifdef DEBUG_FLOPPY
1030             printf("No floppy (open delayed)\n");
1031 #endif
1032             return -EIO;
1033         }
1034         s->fd = open(bs->filename, s->fd_open_flags);
1035         if (s->fd < 0) {
1036             s->fd_error_time = qemu_get_clock(rt_clock);
1037             s->fd_got_error = 1;
1038             if (last_media_present)
1039                 s->fd_media_changed = 1;
1040 #ifdef DEBUG_FLOPPY
1041             printf("No floppy\n");
1042 #endif
1043             return -EIO;
1044         }
1045 #ifdef DEBUG_FLOPPY
1046         printf("Floppy opened\n");
1047 #endif
1048     }
1049     if (!last_media_present)
1050         s->fd_media_changed = 1;
1051     s->fd_open_time = qemu_get_clock(rt_clock);
1052     s->fd_got_error = 0;
1053     return 0;
1054 }
1055
1056 static int raw_is_inserted(BlockDriverState *bs)
1057 {
1058     BDRVRawState *s = bs->opaque;
1059     int ret;
1060
1061     switch(s->type) {
1062     case FTYPE_CD:
1063         ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1064         if (ret == CDS_DISC_OK)
1065             return 1;
1066         else
1067             return 0;
1068         break;
1069     case FTYPE_FD:
1070         ret = fd_open(bs);
1071         return (ret >= 0);
1072     default:
1073         return 1;
1074     }
1075 }
1076
1077 /* currently only used by fdc.c, but a CD version would be good too */
1078 static int raw_media_changed(BlockDriverState *bs)
1079 {
1080     BDRVRawState *s = bs->opaque;
1081
1082     switch(s->type) {
1083     case FTYPE_FD:
1084         {
1085             int ret;
1086             /* XXX: we do not have a true media changed indication. It
1087                does not work if the floppy is changed without trying
1088                to read it */
1089             fd_open(bs);
1090             ret = s->fd_media_changed;
1091             s->fd_media_changed = 0;
1092 #ifdef DEBUG_FLOPPY
1093             printf("Floppy changed=%d\n", ret);
1094 #endif
1095             return ret;
1096         }
1097     default:
1098         return -ENOTSUP;
1099     }
1100 }
1101
1102 static int raw_eject(BlockDriverState *bs, int eject_flag)
1103 {
1104     BDRVRawState *s = bs->opaque;
1105
1106     switch(s->type) {
1107     case FTYPE_CD:
1108         if (eject_flag) {
1109             if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1110                 perror("CDROMEJECT");
1111         } else {
1112             if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1113                 perror("CDROMEJECT");
1114         }
1115         break;
1116     case FTYPE_FD:
1117         {
1118             int fd;
1119             if (s->fd >= 0) {
1120                 close(s->fd);
1121                 s->fd = -1;
1122             }
1123             fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1124             if (fd >= 0) {
1125                 if (ioctl(fd, FDEJECT, 0) < 0)
1126                     perror("FDEJECT");
1127                 close(fd);
1128             }
1129         }
1130         break;
1131     default:
1132         return -ENOTSUP;
1133     }
1134     return 0;
1135 }
1136
1137 static int raw_set_locked(BlockDriverState *bs, int locked)
1138 {
1139     BDRVRawState *s = bs->opaque;
1140
1141     switch(s->type) {
1142     case FTYPE_CD:
1143         if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1144             /* Note: an error can happen if the distribution automatically
1145                mounts the CD-ROM */
1146             //        perror("CDROM_LOCKDOOR");
1147         }
1148         break;
1149     default:
1150         return -ENOTSUP;
1151     }
1152     return 0;
1153 }
1154
1155 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1156 {
1157     BDRVRawState *s = bs->opaque;
1158
1159     return ioctl(s->fd, req, buf);
1160 }
1161 #else
1162
1163 static int fd_open(BlockDriverState *bs)
1164 {
1165     return 0;
1166 }
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 static int raw_sg_send_command(BlockDriverState *bs, void *buf, int count)
1195 {
1196     return raw_pwrite(bs, -1, buf, count);
1197 }
1198
1199 static int raw_sg_recv_response(BlockDriverState *bs, void *buf, int count)
1200 {
1201     return raw_pread(bs, -1, buf, count);
1202 }
1203
1204 static BlockDriverAIOCB *raw_sg_aio_read(BlockDriverState *bs,
1205                                          void *buf, int count,
1206                                          BlockDriverCompletionFunc *cb,
1207                                          void *opaque)
1208 {
1209     return raw_aio_read(bs, 0, buf, -(int64_t)count, cb, opaque);
1210 }
1211
1212 static BlockDriverAIOCB *raw_sg_aio_write(BlockDriverState *bs,
1213                                           void *buf, int count,
1214                                           BlockDriverCompletionFunc *cb,
1215                                           void *opaque)
1216 {
1217     return raw_aio_write(bs, 0, buf, -(int64_t)count, cb, opaque);
1218 }
1219
1220 BlockDriver bdrv_host_device = {
1221     .format_name        = "host_device",
1222     .instance_size      = sizeof(BDRVRawState),
1223     .bdrv_open          = hdev_open,
1224     .bdrv_close         = raw_close,
1225     .bdrv_flush         = raw_flush,
1226
1227 #ifdef CONFIG_AIO
1228     .bdrv_aio_read      = raw_aio_read,
1229     .bdrv_aio_write     = raw_aio_write,
1230     .bdrv_aio_cancel    = raw_aio_cancel,
1231     .aiocb_size         = sizeof(RawAIOCB),
1232 #endif
1233
1234     .bdrv_read          = raw_read,
1235     .bdrv_write         = raw_write,
1236     .bdrv_getlength     = raw_getlength,
1237
1238     /* removable device support */
1239     .bdrv_is_inserted   = raw_is_inserted,
1240     .bdrv_media_changed = raw_media_changed,
1241     .bdrv_eject         = raw_eject,
1242     .bdrv_set_locked    = raw_set_locked,
1243     /* generic scsi device */
1244     .bdrv_ioctl         = raw_ioctl,
1245     .bdrv_sg_send_command  = raw_sg_send_command,
1246     .bdrv_sg_recv_response = raw_sg_recv_response,
1247     .bdrv_sg_aio_read      = raw_sg_aio_read,
1248     .bdrv_sg_aio_write     = raw_sg_aio_write,
1249 };