timers: Createt TimersState and put all timers state there
[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 "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "block/raw-posix-aio.h"
31
32 #ifdef CONFIG_COCOA
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
43
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <signal.h>
47 #include <sys/dkio.h>
48 #endif
49 #ifdef __linux__
50 #include <sys/ioctl.h>
51 #include <linux/cdrom.h>
52 #include <linux/fd.h>
53 #endif
54 #ifdef __FreeBSD__
55 #include <signal.h>
56 #include <sys/disk.h>
57 #include <sys/cdio.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, ...) do { if (qemu_log_enabled()) \
76     { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
77 #else
78 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
79 #endif
80
81 /* OS X does not have O_DSYNC */
82 #ifndef O_DSYNC
83 #ifdef O_SYNC
84 #define O_DSYNC O_SYNC
85 #elif defined(O_FSYNC)
86 #define O_DSYNC O_FSYNC
87 #endif
88 #endif
89
90 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
91 #ifndef O_DIRECT
92 #define O_DIRECT O_DSYNC
93 #endif
94
95 #define FTYPE_FILE   0
96 #define FTYPE_CD     1
97 #define FTYPE_FD     2
98
99 #define ALIGNED_BUFFER_SIZE (32 * 512)
100
101 /* if the FD is not accessed during that time (in ms), we try to
102    reopen it to see if the disk has been changed */
103 #define FD_OPEN_TIMEOUT 1000
104
105 typedef struct BDRVRawState {
106     int fd;
107     int type;
108     unsigned int lseek_err_cnt;
109     int open_flags;
110     void *aio_ctx;
111 #if defined(__linux__)
112     /* linux floppy specific */
113     int64_t fd_open_time;
114     int64_t fd_error_time;
115     int fd_got_error;
116     int fd_media_changed;
117 #endif
118 #ifdef CONFIG_LINUX_AIO
119     int use_aio;
120 #endif
121     uint8_t* aligned_buf;
122 } BDRVRawState;
123
124 static int fd_open(BlockDriverState *bs);
125 static int64_t raw_getlength(BlockDriverState *bs);
126
127 #if defined(__FreeBSD__)
128 static int cdrom_reopen(BlockDriverState *bs);
129 #endif
130
131 static int raw_open_common(BlockDriverState *bs, const char *filename,
132                            int bdrv_flags, int open_flags)
133 {
134     BDRVRawState *s = bs->opaque;
135     int fd, ret;
136
137     s->lseek_err_cnt = 0;
138
139     s->open_flags = open_flags | O_BINARY;
140     s->open_flags &= ~O_ACCMODE;
141     if ((bdrv_flags & BDRV_O_ACCESS) == BDRV_O_RDWR) {
142         s->open_flags |= O_RDWR;
143     } else {
144         s->open_flags |= O_RDONLY;
145         bs->read_only = 1;
146     }
147
148     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
149      * and O_DIRECT for no caching. */
150     if ((bdrv_flags & BDRV_O_NOCACHE))
151         s->open_flags |= O_DIRECT;
152     else if (!(bdrv_flags & BDRV_O_CACHE_WB))
153         s->open_flags |= O_DSYNC;
154
155     s->fd = -1;
156     fd = open(filename, s->open_flags, 0644);
157     if (fd < 0) {
158         ret = -errno;
159         if (ret == -EROFS)
160             ret = -EACCES;
161         return ret;
162     }
163     s->fd = fd;
164     s->aligned_buf = NULL;
165
166     if ((bdrv_flags & BDRV_O_NOCACHE)) {
167         s->aligned_buf = qemu_blockalign(bs, ALIGNED_BUFFER_SIZE);
168         if (s->aligned_buf == NULL) {
169             goto out_close;
170         }
171     }
172
173 #ifdef CONFIG_LINUX_AIO
174     if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
175                       (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
176         s->aio_ctx = laio_init();
177         if (!s->aio_ctx) {
178             goto out_free_buf;
179         }
180         s->use_aio = 1;
181     } else
182 #endif
183     {
184         s->aio_ctx = paio_init();
185         if (!s->aio_ctx) {
186             goto out_free_buf;
187         }
188 #ifdef CONFIG_LINUX_AIO
189         s->use_aio = 0;
190 #endif
191     }
192
193     return 0;
194
195 out_free_buf:
196     qemu_vfree(s->aligned_buf);
197 out_close:
198     close(fd);
199     return -errno;
200 }
201
202 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
203 {
204     BDRVRawState *s = bs->opaque;
205     int open_flags = 0;
206
207     s->type = FTYPE_FILE;
208     if (flags & BDRV_O_CREAT)
209         open_flags = O_CREAT | O_TRUNC;
210
211     return raw_open_common(bs, filename, flags, open_flags);
212 }
213
214 /* XXX: use host sector size if necessary with:
215 #ifdef DIOCGSECTORSIZE
216         {
217             unsigned int sectorsize = 512;
218             if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
219                 sectorsize > bufsize)
220                 bufsize = sectorsize;
221         }
222 #endif
223 #ifdef CONFIG_COCOA
224         u_int32_t   blockSize = 512;
225         if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
226             bufsize = blockSize;
227         }
228 #endif
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_pread_aligned(BlockDriverState *bs, int64_t offset,
239                      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 <= 10) {
251             DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
252                               "] 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 = read(s->fd, buf, count);
261     if (ret == count)
262         goto label__raw_read__success;
263
264     /* Allow reads beyond the end (needed for pwrite) */
265     if ((ret == 0) && bs->growable) {
266         int64_t size = raw_getlength(bs);
267         if (offset >= size) {
268             memset(buf, 0, count);
269             ret = count;
270             goto label__raw_read__success;
271         }
272     }
273
274     DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
275                       "] read failed %d : %d = %s\n",
276                       s->fd, bs->filename, offset, buf, count,
277                       bs->total_sectors, ret, errno, strerror(errno));
278
279     /* Try harder for CDrom. */
280     if (bs->type == BDRV_TYPE_CDROM) {
281         lseek(s->fd, offset, SEEK_SET);
282         ret = read(s->fd, buf, count);
283         if (ret == count)
284             goto label__raw_read__success;
285         lseek(s->fd, offset, SEEK_SET);
286         ret = read(s->fd, buf, count);
287         if (ret == count)
288             goto label__raw_read__success;
289
290         DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
291                           "] retry read failed %d : %d = %s\n",
292                           s->fd, bs->filename, offset, buf, count,
293                           bs->total_sectors, ret, errno, strerror(errno));
294     }
295
296 label__raw_read__success:
297
298     return  (ret < 0) ? -errno : ret;
299 }
300
301 /*
302  * offset and count are in bytes, but must be multiples of 512 for files
303  * opened with O_DIRECT. buf must be aligned to 512 bytes then.
304  *
305  * This function may be called without alignment if the caller ensures
306  * that O_DIRECT is not in effect.
307  */
308 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
309                       const uint8_t *buf, int count)
310 {
311     BDRVRawState *s = bs->opaque;
312     int ret;
313
314     ret = fd_open(bs);
315     if (ret < 0)
316         return -errno;
317
318     if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
319         ++(s->lseek_err_cnt);
320         if(s->lseek_err_cnt) {
321             DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
322                               PRId64 "] lseek failed : %d = %s\n",
323                               s->fd, bs->filename, offset, buf, count,
324                               bs->total_sectors, errno, strerror(errno));
325         }
326         return -EIO;
327     }
328     s->lseek_err_cnt = 0;
329
330     ret = write(s->fd, buf, count);
331     if (ret == count)
332         goto label__raw_write__success;
333
334     DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
335                       "] write failed %d : %d = %s\n",
336                       s->fd, bs->filename, offset, buf, count,
337                       bs->total_sectors, ret, errno, strerror(errno));
338
339 label__raw_write__success:
340
341     return  (ret < 0) ? -errno : ret;
342 }
343
344
345 /*
346  * offset and count are in bytes and possibly not aligned. For files opened
347  * with O_DIRECT, necessary alignments are ensured before calling
348  * raw_pread_aligned to do the actual read.
349  */
350 static int raw_pread(BlockDriverState *bs, int64_t offset,
351                      uint8_t *buf, int count)
352 {
353     BDRVRawState *s = bs->opaque;
354     int size, ret, shift, sum;
355
356     sum = 0;
357
358     if (s->aligned_buf != NULL)  {
359
360         if (offset & 0x1ff) {
361             /* align offset on a 512 bytes boundary */
362
363             shift = offset & 0x1ff;
364             size = (shift + count + 0x1ff) & ~0x1ff;
365             if (size > ALIGNED_BUFFER_SIZE)
366                 size = ALIGNED_BUFFER_SIZE;
367             ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
368             if (ret < 0)
369                 return ret;
370
371             size = 512 - shift;
372             if (size > count)
373                 size = count;
374             memcpy(buf, s->aligned_buf + shift, size);
375
376             buf += size;
377             offset += size;
378             count -= size;
379             sum += size;
380
381             if (count == 0)
382                 return sum;
383         }
384         if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
385
386             /* read on aligned buffer */
387
388             while (count) {
389
390                 size = (count + 0x1ff) & ~0x1ff;
391                 if (size > ALIGNED_BUFFER_SIZE)
392                     size = ALIGNED_BUFFER_SIZE;
393
394                 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
395                 if (ret < 0)
396                     return ret;
397
398                 size = ret;
399                 if (size > count)
400                     size = count;
401
402                 memcpy(buf, s->aligned_buf, size);
403
404                 buf += size;
405                 offset += size;
406                 count -= size;
407                 sum += size;
408             }
409
410             return sum;
411         }
412     }
413
414     return raw_pread_aligned(bs, offset, buf, count) + sum;
415 }
416
417 static int raw_read(BlockDriverState *bs, int64_t sector_num,
418                     uint8_t *buf, int nb_sectors)
419 {
420     int ret;
421
422     ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
423     if (ret == (nb_sectors * 512))
424         ret = 0;
425     return ret;
426 }
427
428 /*
429  * offset and count are in bytes and possibly not aligned. For files opened
430  * with O_DIRECT, necessary alignments are ensured before calling
431  * raw_pwrite_aligned to do the actual write.
432  */
433 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
434                       const uint8_t *buf, int count)
435 {
436     BDRVRawState *s = bs->opaque;
437     int size, ret, shift, sum;
438
439     sum = 0;
440
441     if (s->aligned_buf != NULL) {
442
443         if (offset & 0x1ff) {
444             /* align offset on a 512 bytes boundary */
445             shift = offset & 0x1ff;
446             ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
447             if (ret < 0)
448                 return ret;
449
450             size = 512 - shift;
451             if (size > count)
452                 size = count;
453             memcpy(s->aligned_buf + shift, buf, size);
454
455             ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
456             if (ret < 0)
457                 return ret;
458
459             buf += size;
460             offset += size;
461             count -= size;
462             sum += size;
463
464             if (count == 0)
465                 return sum;
466         }
467         if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
468
469             while ((size = (count & ~0x1ff)) != 0) {
470
471                 if (size > ALIGNED_BUFFER_SIZE)
472                     size = ALIGNED_BUFFER_SIZE;
473
474                 memcpy(s->aligned_buf, buf, size);
475
476                 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
477                 if (ret < 0)
478                     return ret;
479
480                 buf += ret;
481                 offset += ret;
482                 count -= ret;
483                 sum += ret;
484             }
485             /* here, count < 512 because (count & ~0x1ff) == 0 */
486             if (count) {
487                 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
488                 if (ret < 0)
489                     return ret;
490                  memcpy(s->aligned_buf, buf, count);
491
492                  ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
493                  if (ret < 0)
494                      return ret;
495                  if (count < ret)
496                      ret = count;
497
498                  sum += ret;
499             }
500             return sum;
501         }
502     }
503     return raw_pwrite_aligned(bs, offset, buf, count) + sum;
504 }
505
506 static int raw_write(BlockDriverState *bs, int64_t sector_num,
507                      const uint8_t *buf, int nb_sectors)
508 {
509     int ret;
510     ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
511     if (ret == (nb_sectors * 512))
512         ret = 0;
513     return ret;
514 }
515
516 /*
517  * Check if all memory in this vector is sector aligned.
518  */
519 static int qiov_is_aligned(QEMUIOVector *qiov)
520 {
521     int i;
522
523     for (i = 0; i < qiov->niov; i++) {
524         if ((uintptr_t) qiov->iov[i].iov_base % 512) {
525             return 0;
526         }
527     }
528
529     return 1;
530 }
531
532 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
533         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
534         BlockDriverCompletionFunc *cb, void *opaque, int type)
535 {
536     BDRVRawState *s = bs->opaque;
537
538     if (fd_open(bs) < 0)
539         return NULL;
540
541     /*
542      * If O_DIRECT is used the buffer needs to be aligned on a sector
543      * boundary.  Check if this is the case or telll the low-level
544      * driver that it needs to copy the buffer.
545      */
546     if (s->aligned_buf) {
547         if (!qiov_is_aligned(qiov)) {
548             type |= QEMU_AIO_MISALIGNED;
549 #ifdef CONFIG_LINUX_AIO
550         } else if (s->use_aio) {
551             return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
552                                nb_sectors, cb, opaque, type);
553 #endif
554         }
555     }
556
557     return paio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov, nb_sectors,
558                        cb, opaque, type);
559 }
560
561 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
562         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
563         BlockDriverCompletionFunc *cb, void *opaque)
564 {
565     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
566                           cb, opaque, QEMU_AIO_READ);
567 }
568
569 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
570         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
571         BlockDriverCompletionFunc *cb, void *opaque)
572 {
573     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
574                           cb, opaque, QEMU_AIO_WRITE);
575 }
576
577 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
578         BlockDriverCompletionFunc *cb, void *opaque)
579 {
580     BDRVRawState *s = bs->opaque;
581
582     if (fd_open(bs) < 0)
583         return NULL;
584
585     return paio_submit(bs, s->aio_ctx, s->fd, 0, NULL, 0,
586                        cb, opaque, QEMU_AIO_FLUSH);
587 }
588
589 static void raw_close(BlockDriverState *bs)
590 {
591     BDRVRawState *s = bs->opaque;
592     if (s->fd >= 0) {
593         close(s->fd);
594         s->fd = -1;
595         if (s->aligned_buf != NULL)
596             qemu_free(s->aligned_buf);
597     }
598 }
599
600 static int raw_truncate(BlockDriverState *bs, int64_t offset)
601 {
602     BDRVRawState *s = bs->opaque;
603     if (s->type != FTYPE_FILE)
604         return -ENOTSUP;
605     if (ftruncate(s->fd, offset) < 0)
606         return -errno;
607     return 0;
608 }
609
610 #ifdef __OpenBSD__
611 static int64_t raw_getlength(BlockDriverState *bs)
612 {
613     BDRVRawState *s = bs->opaque;
614     int fd = s->fd;
615     struct stat st;
616
617     if (fstat(fd, &st))
618         return -1;
619     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
620         struct disklabel dl;
621
622         if (ioctl(fd, DIOCGDINFO, &dl))
623             return -1;
624         return (uint64_t)dl.d_secsize *
625             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
626     } else
627         return st.st_size;
628 }
629 #else /* !__OpenBSD__ */
630 static int64_t  raw_getlength(BlockDriverState *bs)
631 {
632     BDRVRawState *s = bs->opaque;
633     int fd = s->fd;
634     int64_t size;
635 #ifdef CONFIG_BSD
636     struct stat sb;
637 #ifdef __FreeBSD__
638     int reopened = 0;
639 #endif
640 #endif
641 #ifdef __sun__
642     struct dk_minfo minfo;
643     int rv;
644 #endif
645     int ret;
646
647     ret = fd_open(bs);
648     if (ret < 0)
649         return ret;
650
651 #ifdef CONFIG_BSD
652 #ifdef __FreeBSD__
653 again:
654 #endif
655     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
656 #ifdef DIOCGMEDIASIZE
657         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
658 #elif defined(DIOCGPART)
659         {
660                 struct partinfo pi;
661                 if (ioctl(fd, DIOCGPART, &pi) == 0)
662                         size = pi.media_size;
663                 else
664                         size = 0;
665         }
666         if (size == 0)
667 #endif
668 #ifdef CONFIG_COCOA
669         size = LONG_LONG_MAX;
670 #else
671         size = lseek(fd, 0LL, SEEK_END);
672 #endif
673 #ifdef __FreeBSD__
674         switch(s->type) {
675         case FTYPE_CD:
676             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
677             if (size == 2048LL * (unsigned)-1)
678                 size = 0;
679             /* XXX no disc?  maybe we need to reopen... */
680             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
681                 reopened = 1;
682                 goto again;
683             }
684         }
685 #endif
686     } else
687 #endif
688 #ifdef __sun__
689     /*
690      * use the DKIOCGMEDIAINFO ioctl to read the size.
691      */
692     rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
693     if ( rv != -1 ) {
694         size = minfo.dki_lbsize * minfo.dki_capacity;
695     } else /* there are reports that lseek on some devices
696               fails, but irc discussion said that contingency
697               on contingency was overkill */
698 #endif
699     {
700         size = lseek(fd, 0, SEEK_END);
701     }
702     return size;
703 }
704 #endif
705
706 static int raw_create(const char *filename, QEMUOptionParameter *options)
707 {
708     int fd;
709     int result = 0;
710     int64_t total_size = 0;
711
712     /* Read out options */
713     while (options && options->name) {
714         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
715             total_size = options->value.n / 512;
716         }
717         options++;
718     }
719
720     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
721               0644);
722     if (fd < 0) {
723         result = -errno;
724     } else {
725         if (ftruncate(fd, total_size * 512) != 0) {
726             result = -errno;
727         }
728         if (close(fd) != 0) {
729             result = -errno;
730         }
731     }
732     return result;
733 }
734
735 static void raw_flush(BlockDriverState *bs)
736 {
737     BDRVRawState *s = bs->opaque;
738     qemu_fdatasync(s->fd);
739 }
740
741
742 static QEMUOptionParameter raw_create_options[] = {
743     {
744         .name = BLOCK_OPT_SIZE,
745         .type = OPT_SIZE,
746         .help = "Virtual disk size"
747     },
748     { NULL }
749 };
750
751 static BlockDriver bdrv_raw = {
752     .format_name = "raw",
753     .instance_size = sizeof(BDRVRawState),
754     .bdrv_probe = NULL, /* no probe for protocols */
755     .bdrv_open = raw_open,
756     .bdrv_read = raw_read,
757     .bdrv_write = raw_write,
758     .bdrv_close = raw_close,
759     .bdrv_create = raw_create,
760     .bdrv_flush = raw_flush,
761
762     .bdrv_aio_readv = raw_aio_readv,
763     .bdrv_aio_writev = raw_aio_writev,
764     .bdrv_aio_flush = raw_aio_flush,
765
766     .bdrv_truncate = raw_truncate,
767     .bdrv_getlength = raw_getlength,
768
769     .create_options = raw_create_options,
770 };
771
772 /***********************************************/
773 /* host device */
774
775 #ifdef CONFIG_COCOA
776 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
777 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
778
779 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
780 {
781     kern_return_t       kernResult;
782     mach_port_t     masterPort;
783     CFMutableDictionaryRef  classesToMatch;
784
785     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
786     if ( KERN_SUCCESS != kernResult ) {
787         printf( "IOMasterPort returned %d\n", kernResult );
788     }
789
790     classesToMatch = IOServiceMatching( kIOCDMediaClass );
791     if ( classesToMatch == NULL ) {
792         printf( "IOServiceMatching returned a NULL dictionary.\n" );
793     } else {
794     CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
795     }
796     kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
797     if ( KERN_SUCCESS != kernResult )
798     {
799         printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
800     }
801
802     return kernResult;
803 }
804
805 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
806 {
807     io_object_t     nextMedia;
808     kern_return_t   kernResult = KERN_FAILURE;
809     *bsdPath = '\0';
810     nextMedia = IOIteratorNext( mediaIterator );
811     if ( nextMedia )
812     {
813         CFTypeRef   bsdPathAsCFString;
814     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
815         if ( bsdPathAsCFString ) {
816             size_t devPathLength;
817             strcpy( bsdPath, _PATH_DEV );
818             strcat( bsdPath, "r" );
819             devPathLength = strlen( bsdPath );
820             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
821                 kernResult = KERN_SUCCESS;
822             }
823             CFRelease( bsdPathAsCFString );
824         }
825         IOObjectRelease( nextMedia );
826     }
827
828     return kernResult;
829 }
830
831 #endif
832
833 static int hdev_probe_device(const char *filename)
834 {
835     struct stat st;
836
837     /* allow a dedicated CD-ROM driver to match with a higher priority */
838     if (strstart(filename, "/dev/cdrom", NULL))
839         return 50;
840
841     if (stat(filename, &st) >= 0 &&
842             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
843         return 100;
844     }
845
846     return 0;
847 }
848
849 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
850 {
851     BDRVRawState *s = bs->opaque;
852
853 #ifdef CONFIG_COCOA
854     if (strstart(filename, "/dev/cdrom", NULL)) {
855         kern_return_t kernResult;
856         io_iterator_t mediaIterator;
857         char bsdPath[ MAXPATHLEN ];
858         int fd;
859
860         kernResult = FindEjectableCDMedia( &mediaIterator );
861         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
862
863         if ( bsdPath[ 0 ] != '\0' ) {
864             strcat(bsdPath,"s0");
865             /* some CDs don't have a partition 0 */
866             fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
867             if (fd < 0) {
868                 bsdPath[strlen(bsdPath)-1] = '1';
869             } else {
870                 close(fd);
871             }
872             filename = bsdPath;
873         }
874
875         if ( mediaIterator )
876             IOObjectRelease( mediaIterator );
877     }
878 #endif
879
880     s->type = FTYPE_FILE;
881 #if defined(__linux__)
882     if (strstart(filename, "/dev/sg", NULL)) {
883         bs->sg = 1;
884     }
885 #endif
886
887     return raw_open_common(bs, filename, flags, 0);
888 }
889
890 #if defined(__linux__)
891 /* Note: we do not have a reliable method to detect if the floppy is
892    present. The current method is to try to open the floppy at every
893    I/O and to keep it opened during a few hundreds of ms. */
894 static int fd_open(BlockDriverState *bs)
895 {
896     BDRVRawState *s = bs->opaque;
897     int last_media_present;
898
899     if (s->type != FTYPE_FD)
900         return 0;
901     last_media_present = (s->fd >= 0);
902     if (s->fd >= 0 &&
903         (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
904         close(s->fd);
905         s->fd = -1;
906 #ifdef DEBUG_FLOPPY
907         printf("Floppy closed\n");
908 #endif
909     }
910     if (s->fd < 0) {
911         if (s->fd_got_error &&
912             (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
913 #ifdef DEBUG_FLOPPY
914             printf("No floppy (open delayed)\n");
915 #endif
916             return -EIO;
917         }
918         s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
919         if (s->fd < 0) {
920             s->fd_error_time = qemu_get_clock(rt_clock);
921             s->fd_got_error = 1;
922             if (last_media_present)
923                 s->fd_media_changed = 1;
924 #ifdef DEBUG_FLOPPY
925             printf("No floppy\n");
926 #endif
927             return -EIO;
928         }
929 #ifdef DEBUG_FLOPPY
930         printf("Floppy opened\n");
931 #endif
932     }
933     if (!last_media_present)
934         s->fd_media_changed = 1;
935     s->fd_open_time = qemu_get_clock(rt_clock);
936     s->fd_got_error = 0;
937     return 0;
938 }
939
940 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
941 {
942     BDRVRawState *s = bs->opaque;
943
944     return ioctl(s->fd, req, buf);
945 }
946
947 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
948         unsigned long int req, void *buf,
949         BlockDriverCompletionFunc *cb, void *opaque)
950 {
951     BDRVRawState *s = bs->opaque;
952
953     if (fd_open(bs) < 0)
954         return NULL;
955     return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
956 }
957
958 #elif defined(__FreeBSD__)
959 static int fd_open(BlockDriverState *bs)
960 {
961     BDRVRawState *s = bs->opaque;
962
963     /* this is just to ensure s->fd is sane (its called by io ops) */
964     if (s->fd >= 0)
965         return 0;
966     return -EIO;
967 }
968 #else /* !linux && !FreeBSD */
969
970 static int fd_open(BlockDriverState *bs)
971 {
972     return 0;
973 }
974
975 #endif /* !linux && !FreeBSD */
976
977 static int hdev_create(const char *filename, QEMUOptionParameter *options)
978 {
979     int fd;
980     int ret = 0;
981     struct stat stat_buf;
982     int64_t total_size = 0;
983
984     /* Read out options */
985     while (options && options->name) {
986         if (!strcmp(options->name, "size")) {
987             total_size = options->value.n / 512;
988         }
989         options++;
990     }
991
992     fd = open(filename, O_WRONLY | O_BINARY);
993     if (fd < 0)
994         return -EIO;
995
996     if (fstat(fd, &stat_buf) < 0)
997         ret = -EIO;
998     else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
999         ret = -EIO;
1000     else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1001         ret = -ENOSPC;
1002
1003     close(fd);
1004     return ret;
1005 }
1006
1007 static BlockDriver bdrv_host_device = {
1008     .format_name        = "host_device",
1009     .instance_size      = sizeof(BDRVRawState),
1010     .bdrv_probe_device  = hdev_probe_device,
1011     .bdrv_open          = hdev_open,
1012     .bdrv_close         = raw_close,
1013     .bdrv_create        = hdev_create,
1014     .bdrv_flush         = raw_flush,
1015
1016     .bdrv_aio_readv     = raw_aio_readv,
1017     .bdrv_aio_writev    = raw_aio_writev,
1018     .bdrv_aio_flush     = raw_aio_flush,
1019
1020     .bdrv_read          = raw_read,
1021     .bdrv_write         = raw_write,
1022     .bdrv_getlength     = raw_getlength,
1023
1024     /* generic scsi device */
1025 #ifdef __linux__
1026     .bdrv_ioctl         = hdev_ioctl,
1027     .bdrv_aio_ioctl     = hdev_aio_ioctl,
1028 #endif
1029 };
1030
1031 #ifdef __linux__
1032 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1033 {
1034     BDRVRawState *s = bs->opaque;
1035     int ret;
1036
1037     s->type = FTYPE_FD;
1038
1039     /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1040     ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1041     if (ret)
1042         return ret;
1043
1044     /* close fd so that we can reopen it as needed */
1045     close(s->fd);
1046     s->fd = -1;
1047     s->fd_media_changed = 1;
1048
1049     return 0;
1050 }
1051
1052 static int floppy_probe_device(const char *filename)
1053 {
1054     if (strstart(filename, "/dev/fd", NULL))
1055         return 100;
1056     return 0;
1057 }
1058
1059
1060 static int floppy_is_inserted(BlockDriverState *bs)
1061 {
1062     return fd_open(bs) >= 0;
1063 }
1064
1065 static int floppy_media_changed(BlockDriverState *bs)
1066 {
1067     BDRVRawState *s = bs->opaque;
1068     int ret;
1069
1070     /*
1071      * XXX: we do not have a true media changed indication.
1072      * It does not work if the floppy is changed without trying to read it.
1073      */
1074     fd_open(bs);
1075     ret = s->fd_media_changed;
1076     s->fd_media_changed = 0;
1077 #ifdef DEBUG_FLOPPY
1078     printf("Floppy changed=%d\n", ret);
1079 #endif
1080     return ret;
1081 }
1082
1083 static int floppy_eject(BlockDriverState *bs, int eject_flag)
1084 {
1085     BDRVRawState *s = bs->opaque;
1086     int fd;
1087
1088     if (s->fd >= 0) {
1089         close(s->fd);
1090         s->fd = -1;
1091     }
1092     fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1093     if (fd >= 0) {
1094         if (ioctl(fd, FDEJECT, 0) < 0)
1095             perror("FDEJECT");
1096         close(fd);
1097     }
1098
1099     return 0;
1100 }
1101
1102 static BlockDriver bdrv_host_floppy = {
1103     .format_name        = "host_floppy",
1104     .instance_size      = sizeof(BDRVRawState),
1105     .bdrv_probe_device  = floppy_probe_device,
1106     .bdrv_open          = floppy_open,
1107     .bdrv_close         = raw_close,
1108     .bdrv_create        = hdev_create,
1109     .bdrv_flush         = raw_flush,
1110
1111     .bdrv_aio_readv     = raw_aio_readv,
1112     .bdrv_aio_writev    = raw_aio_writev,
1113     .bdrv_aio_flush     = raw_aio_flush,
1114
1115     .bdrv_read          = raw_read,
1116     .bdrv_write         = raw_write,
1117     .bdrv_getlength     = raw_getlength,
1118
1119     /* removable device support */
1120     .bdrv_is_inserted   = floppy_is_inserted,
1121     .bdrv_media_changed = floppy_media_changed,
1122     .bdrv_eject         = floppy_eject,
1123 };
1124
1125 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1126 {
1127     BDRVRawState *s = bs->opaque;
1128
1129     s->type = FTYPE_CD;
1130
1131     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1132     return raw_open_common(bs, filename, flags, O_NONBLOCK);
1133 }
1134
1135 static int cdrom_probe_device(const char *filename)
1136 {
1137     if (strstart(filename, "/dev/cd", NULL))
1138         return 100;
1139     return 0;
1140 }
1141
1142 static int cdrom_is_inserted(BlockDriverState *bs)
1143 {
1144     BDRVRawState *s = bs->opaque;
1145     int ret;
1146
1147     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1148     if (ret == CDS_DISC_OK)
1149         return 1;
1150     return 0;
1151 }
1152
1153 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1154 {
1155     BDRVRawState *s = bs->opaque;
1156
1157     if (eject_flag) {
1158         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1159             perror("CDROMEJECT");
1160     } else {
1161         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1162             perror("CDROMEJECT");
1163     }
1164
1165     return 0;
1166 }
1167
1168 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1169 {
1170     BDRVRawState *s = bs->opaque;
1171
1172     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1173         /*
1174          * Note: an error can happen if the distribution automatically
1175          * mounts the CD-ROM
1176          */
1177         /* perror("CDROM_LOCKDOOR"); */
1178     }
1179
1180     return 0;
1181 }
1182
1183 static BlockDriver bdrv_host_cdrom = {
1184     .format_name        = "host_cdrom",
1185     .instance_size      = sizeof(BDRVRawState),
1186     .bdrv_probe_device  = cdrom_probe_device,
1187     .bdrv_open          = cdrom_open,
1188     .bdrv_close         = raw_close,
1189     .bdrv_create        = hdev_create,
1190     .bdrv_flush         = raw_flush,
1191
1192     .bdrv_aio_readv     = raw_aio_readv,
1193     .bdrv_aio_writev    = raw_aio_writev,
1194     .bdrv_aio_flush     = raw_aio_flush,
1195
1196     .bdrv_read          = raw_read,
1197     .bdrv_write         = raw_write,
1198     .bdrv_getlength     = raw_getlength,
1199
1200     /* removable device support */
1201     .bdrv_is_inserted   = cdrom_is_inserted,
1202     .bdrv_eject         = cdrom_eject,
1203     .bdrv_set_locked    = cdrom_set_locked,
1204
1205     /* generic scsi device */
1206     .bdrv_ioctl         = hdev_ioctl,
1207     .bdrv_aio_ioctl     = hdev_aio_ioctl,
1208 };
1209 #endif /* __linux__ */
1210
1211 #ifdef __FreeBSD__
1212 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1213 {
1214     BDRVRawState *s = bs->opaque;
1215     int ret;
1216
1217     s->type = FTYPE_CD;
1218
1219     ret = raw_open_common(bs, filename, flags, 0);
1220     if (ret)
1221         return ret;
1222
1223     /* make sure the door isnt locked at this time */
1224     ioctl(s->fd, CDIOCALLOW);
1225     return 0;
1226 }
1227
1228 static int cdrom_probe_device(const char *filename)
1229 {
1230     if (strstart(filename, "/dev/cd", NULL) ||
1231             strstart(filename, "/dev/acd", NULL))
1232         return 100;
1233     return 0;
1234 }
1235
1236 static int cdrom_reopen(BlockDriverState *bs)
1237 {
1238     BDRVRawState *s = bs->opaque;
1239     int fd;
1240
1241     /*
1242      * Force reread of possibly changed/newly loaded disc,
1243      * FreeBSD seems to not notice sometimes...
1244      */
1245     if (s->fd >= 0)
1246         close(s->fd);
1247     fd = open(bs->filename, s->open_flags, 0644);
1248     if (fd < 0) {
1249         s->fd = -1;
1250         return -EIO;
1251     }
1252     s->fd = fd;
1253
1254     /* make sure the door isnt locked at this time */
1255     ioctl(s->fd, CDIOCALLOW);
1256     return 0;
1257 }
1258
1259 static int cdrom_is_inserted(BlockDriverState *bs)
1260 {
1261     return raw_getlength(bs) > 0;
1262 }
1263
1264 static int cdrom_eject(BlockDriverState *bs, int eject_flag)
1265 {
1266     BDRVRawState *s = bs->opaque;
1267
1268     if (s->fd < 0)
1269         return -ENOTSUP;
1270
1271     (void) ioctl(s->fd, CDIOCALLOW);
1272
1273     if (eject_flag) {
1274         if (ioctl(s->fd, CDIOCEJECT) < 0)
1275             perror("CDIOCEJECT");
1276     } else {
1277         if (ioctl(s->fd, CDIOCCLOSE) < 0)
1278             perror("CDIOCCLOSE");
1279     }
1280
1281     if (cdrom_reopen(bs) < 0)
1282         return -ENOTSUP;
1283     return 0;
1284 }
1285
1286 static int cdrom_set_locked(BlockDriverState *bs, int locked)
1287 {
1288     BDRVRawState *s = bs->opaque;
1289
1290     if (s->fd < 0)
1291         return -ENOTSUP;
1292     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1293         /*
1294          * Note: an error can happen if the distribution automatically
1295          * mounts the CD-ROM
1296          */
1297         /* perror("CDROM_LOCKDOOR"); */
1298     }
1299
1300     return 0;
1301 }
1302
1303 static BlockDriver bdrv_host_cdrom = {
1304     .format_name        = "host_cdrom",
1305     .instance_size      = sizeof(BDRVRawState),
1306     .bdrv_probe_device  = cdrom_probe_device,
1307     .bdrv_open          = cdrom_open,
1308     .bdrv_close         = raw_close,
1309     .bdrv_create        = hdev_create,
1310     .bdrv_flush         = raw_flush,
1311
1312     .bdrv_aio_readv     = raw_aio_readv,
1313     .bdrv_aio_writev    = raw_aio_writev,
1314     .bdrv_aio_flush     = raw_aio_flush,
1315
1316     .bdrv_read          = raw_read,
1317     .bdrv_write         = raw_write,
1318     .bdrv_getlength     = raw_getlength,
1319
1320     /* removable device support */
1321     .bdrv_is_inserted   = cdrom_is_inserted,
1322     .bdrv_eject         = cdrom_eject,
1323     .bdrv_set_locked    = cdrom_set_locked,
1324 };
1325 #endif /* __FreeBSD__ */
1326
1327 static void bdrv_raw_init(void)
1328 {
1329     /*
1330      * Register all the drivers.  Note that order is important, the driver
1331      * registered last will get probed first.
1332      */
1333     bdrv_register(&bdrv_raw);
1334     bdrv_register(&bdrv_host_device);
1335 #ifdef __linux__
1336     bdrv_register(&bdrv_host_floppy);
1337     bdrv_register(&bdrv_host_cdrom);
1338 #endif
1339 #ifdef __FreeBSD__
1340     bdrv_register(&bdrv_host_cdrom);
1341 #endif
1342 }
1343
1344 block_init(bdrv_raw_init);