abfedbea7330a7e7f4e5908071ae8a6aba5e22d1
[sdk/emulator/qemu.git] / 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 "trace.h"
31 #include "thread-pool.h"
32 #include "iov.h"
33 #include "raw-aio.h"
34
35 #if defined(__APPLE__) && (__MACH__)
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
45 #endif
46
47 #ifdef __sun__
48 #define _POSIX_PTHREAD_SEMANTICS 1
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
57 #include <linux/fd.h>
58 #include <linux/fs.h>
59 #endif
60 #ifdef CONFIG_FIEMAP
61 #include <linux/fiemap.h>
62 #endif
63 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
64 #include <sys/disk.h>
65 #include <sys/cdio.h>
66 #endif
67
68 #ifdef __OpenBSD__
69 #include <sys/ioctl.h>
70 #include <sys/disklabel.h>
71 #include <sys/dkio.h>
72 #endif
73
74 #ifdef __NetBSD__
75 #include <sys/ioctl.h>
76 #include <sys/disklabel.h>
77 #include <sys/dkio.h>
78 #include <sys/disk.h>
79 #endif
80
81 #ifdef __DragonFly__
82 #include <sys/ioctl.h>
83 #include <sys/diskslice.h>
84 #endif
85
86 #ifdef CONFIG_XFS
87 #include <xfs/xfs.h>
88 #endif
89
90 //#define DEBUG_FLOPPY
91
92 //#define DEBUG_BLOCK
93 #if defined(DEBUG_BLOCK)
94 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
95     { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
96 #else
97 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
98 #endif
99
100 /* OS X does not have O_DSYNC */
101 #ifndef O_DSYNC
102 #ifdef O_SYNC
103 #define O_DSYNC O_SYNC
104 #elif defined(O_FSYNC)
105 #define O_DSYNC O_FSYNC
106 #endif
107 #endif
108
109 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
110 #ifndef O_DIRECT
111 #define O_DIRECT O_DSYNC
112 #endif
113
114 #define FTYPE_FILE   0
115 #define FTYPE_CD     1
116 #define FTYPE_FD     2
117
118 /* if the FD is not accessed during that time (in ns), we try to
119    reopen it to see if the disk has been changed */
120 #define FD_OPEN_TIMEOUT (1000000000)
121
122 #define MAX_BLOCKSIZE   4096
123
124 typedef struct BDRVRawState {
125     int fd;
126     int type;
127     int open_flags;
128 #if defined(__linux__)
129     /* linux floppy specific */
130     int64_t fd_open_time;
131     int64_t fd_error_time;
132     int fd_got_error;
133     int fd_media_changed;
134 #endif
135 #ifdef CONFIG_LINUX_AIO
136     int use_aio;
137     void *aio_ctx;
138 #endif
139 #ifdef CONFIG_XFS
140     bool is_xfs : 1;
141 #endif
142 } BDRVRawState;
143
144 typedef struct BDRVRawReopenState {
145     int fd;
146     int open_flags;
147 #ifdef CONFIG_LINUX_AIO
148     int use_aio;
149 #endif
150 } BDRVRawReopenState;
151
152 static int fd_open(BlockDriverState *bs);
153 static int64_t raw_getlength(BlockDriverState *bs);
154
155 typedef struct RawPosixAIOData {
156     BlockDriverState *bs;
157     int aio_fildes;
158     union {
159         struct iovec *aio_iov;
160         void *aio_ioctl_buf;
161     };
162     int aio_niov;
163     size_t aio_nbytes;
164 #define aio_ioctl_cmd   aio_nbytes /* for QEMU_AIO_IOCTL */
165     off_t aio_offset;
166     int aio_type;
167 } RawPosixAIOData;
168
169 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
170 static int cdrom_reopen(BlockDriverState *bs);
171 #endif
172
173 #if defined(__NetBSD__)
174 static int raw_normalize_devicepath(const char **filename)
175 {
176     static char namebuf[PATH_MAX];
177     const char *dp, *fname;
178     struct stat sb;
179
180     fname = *filename;
181     dp = strrchr(fname, '/');
182     if (lstat(fname, &sb) < 0) {
183         fprintf(stderr, "%s: stat failed: %s\n",
184             fname, strerror(errno));
185         return -errno;
186     }
187
188     if (!S_ISBLK(sb.st_mode)) {
189         return 0;
190     }
191
192     if (dp == NULL) {
193         snprintf(namebuf, PATH_MAX, "r%s", fname);
194     } else {
195         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
196             (int)(dp - fname), fname, dp + 1);
197     }
198     fprintf(stderr, "%s is a block device", fname);
199     *filename = namebuf;
200     fprintf(stderr, ", using %s\n", *filename);
201
202     return 0;
203 }
204 #else
205 static int raw_normalize_devicepath(const char **filename)
206 {
207     return 0;
208 }
209 #endif
210
211 static void raw_parse_flags(int bdrv_flags, int *open_flags)
212 {
213     assert(open_flags != NULL);
214
215     *open_flags |= O_BINARY;
216     *open_flags &= ~O_ACCMODE;
217     if (bdrv_flags & BDRV_O_RDWR) {
218         *open_flags |= O_RDWR;
219     } else {
220         *open_flags |= O_RDONLY;
221     }
222
223     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
224      * and O_DIRECT for no caching. */
225     if ((bdrv_flags & BDRV_O_NOCACHE)) {
226         *open_flags |= O_DIRECT;
227     }
228 }
229
230 #ifdef CONFIG_LINUX_AIO
231 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
232 {
233     int ret = -1;
234     assert(aio_ctx != NULL);
235     assert(use_aio != NULL);
236     /*
237      * Currently Linux do AIO only for files opened with O_DIRECT
238      * specified so check NOCACHE flag too
239      */
240     if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
241                       (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
242
243         /* if non-NULL, laio_init() has already been run */
244         if (*aio_ctx == NULL) {
245             *aio_ctx = laio_init();
246             if (!*aio_ctx) {
247                 goto error;
248             }
249         }
250         *use_aio = 1;
251     } else {
252         *use_aio = 0;
253     }
254
255     ret = 0;
256
257 error:
258     return ret;
259 }
260 #endif
261
262 static int raw_open_common(BlockDriverState *bs, const char *filename,
263                            int bdrv_flags, int open_flags)
264 {
265     BDRVRawState *s = bs->opaque;
266     int fd, ret;
267
268     ret = raw_normalize_devicepath(&filename);
269     if (ret != 0) {
270         return ret;
271     }
272
273     s->open_flags = open_flags;
274     raw_parse_flags(bdrv_flags, &s->open_flags);
275
276     s->fd = -1;
277     fd = qemu_open(filename, s->open_flags, 0644);
278     if (fd < 0) {
279         ret = -errno;
280         if (ret == -EROFS)
281             ret = -EACCES;
282         return ret;
283     }
284     s->fd = fd;
285
286 #ifdef CONFIG_LINUX_AIO
287     if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
288         qemu_close(fd);
289         return -errno;
290     }
291 #endif
292
293 #ifdef CONFIG_XFS
294     if (platform_test_xfs_fd(s->fd)) {
295         s->is_xfs = 1;
296     }
297 #endif
298
299     return 0;
300 }
301
302 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
303 {
304     BDRVRawState *s = bs->opaque;
305
306     s->type = FTYPE_FILE;
307     return raw_open_common(bs, filename, flags, 0);
308 }
309
310 static int raw_reopen_prepare(BDRVReopenState *state,
311                               BlockReopenQueue *queue, Error **errp)
312 {
313     BDRVRawState *s;
314     BDRVRawReopenState *raw_s;
315     int ret = 0;
316
317     assert(state != NULL);
318     assert(state->bs != NULL);
319
320     s = state->bs->opaque;
321
322     state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
323     raw_s = state->opaque;
324
325 #ifdef CONFIG_LINUX_AIO
326     raw_s->use_aio = s->use_aio;
327
328     /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
329      * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
330      * won't override aio_ctx if aio_ctx is non-NULL */
331     if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
332         return -1;
333     }
334 #endif
335
336     if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
337         raw_s->open_flags |= O_NONBLOCK;
338     }
339
340     raw_parse_flags(state->flags, &raw_s->open_flags);
341
342     raw_s->fd = -1;
343
344     int fcntl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
345 #ifdef O_NOATIME
346     fcntl_flags |= O_NOATIME;
347 #endif
348
349     if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
350         /* dup the original fd */
351         /* TODO: use qemu fcntl wrapper */
352 #ifdef F_DUPFD_CLOEXEC
353         raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
354 #else
355         raw_s->fd = dup(s->fd);
356         if (raw_s->fd != -1) {
357             qemu_set_cloexec(raw_s->fd);
358         }
359 #endif
360         if (raw_s->fd >= 0) {
361             ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
362             if (ret) {
363                 qemu_close(raw_s->fd);
364                 raw_s->fd = -1;
365             }
366         }
367     }
368
369     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
370     if (raw_s->fd == -1) {
371         assert(!(raw_s->open_flags & O_CREAT));
372         raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
373         if (raw_s->fd == -1) {
374             ret = -1;
375         }
376     }
377     return ret;
378 }
379
380
381 static void raw_reopen_commit(BDRVReopenState *state)
382 {
383     BDRVRawReopenState *raw_s = state->opaque;
384     BDRVRawState *s = state->bs->opaque;
385
386     s->open_flags = raw_s->open_flags;
387
388     qemu_close(s->fd);
389     s->fd = raw_s->fd;
390 #ifdef CONFIG_LINUX_AIO
391     s->use_aio = raw_s->use_aio;
392 #endif
393
394     g_free(state->opaque);
395     state->opaque = NULL;
396 }
397
398
399 static void raw_reopen_abort(BDRVReopenState *state)
400 {
401     BDRVRawReopenState *raw_s = state->opaque;
402
403      /* nothing to do if NULL, we didn't get far enough */
404     if (raw_s == NULL) {
405         return;
406     }
407
408     if (raw_s->fd >= 0) {
409         qemu_close(raw_s->fd);
410         raw_s->fd = -1;
411     }
412     g_free(state->opaque);
413     state->opaque = NULL;
414 }
415
416
417 /* XXX: use host sector size if necessary with:
418 #ifdef DIOCGSECTORSIZE
419         {
420             unsigned int sectorsize = 512;
421             if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
422                 sectorsize > bufsize)
423                 bufsize = sectorsize;
424         }
425 #endif
426 #ifdef CONFIG_COCOA
427         uint32_t blockSize = 512;
428         if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
429             bufsize = blockSize;
430         }
431 #endif
432 */
433
434 /*
435  * Check if all memory in this vector is sector aligned.
436  */
437 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
438 {
439     int i;
440
441     for (i = 0; i < qiov->niov; i++) {
442         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
443             return 0;
444         }
445     }
446
447     return 1;
448 }
449
450 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
451 {
452     int ret;
453
454     ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
455     if (ret == -1) {
456         return -errno;
457     }
458
459     /*
460      * This looks weird, but the aio code only considers a request
461      * successful if it has written the full number of bytes.
462      *
463      * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command,
464      * so in fact we return the ioctl command here to make posix_aio_read()
465      * happy..
466      */
467     return aiocb->aio_nbytes;
468 }
469
470 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
471 {
472     int ret;
473
474     ret = qemu_fdatasync(aiocb->aio_fildes);
475     if (ret == -1) {
476         return -errno;
477     }
478     return 0;
479 }
480
481 #ifdef CONFIG_PREADV
482
483 static bool preadv_present = true;
484
485 static ssize_t
486 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
487 {
488     return preadv(fd, iov, nr_iov, offset);
489 }
490
491 static ssize_t
492 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
493 {
494     return pwritev(fd, iov, nr_iov, offset);
495 }
496
497 #else
498
499 static bool preadv_present = false;
500
501 static ssize_t
502 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
503 {
504     return -ENOSYS;
505 }
506
507 static ssize_t
508 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
509 {
510     return -ENOSYS;
511 }
512
513 #endif
514
515 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
516 {
517     ssize_t len;
518
519     do {
520         if (aiocb->aio_type & QEMU_AIO_WRITE)
521             len = qemu_pwritev(aiocb->aio_fildes,
522                                aiocb->aio_iov,
523                                aiocb->aio_niov,
524                                aiocb->aio_offset);
525          else
526             len = qemu_preadv(aiocb->aio_fildes,
527                               aiocb->aio_iov,
528                               aiocb->aio_niov,
529                               aiocb->aio_offset);
530     } while (len == -1 && errno == EINTR);
531
532     if (len == -1) {
533         return -errno;
534     }
535     return len;
536 }
537
538 /*
539  * Read/writes the data to/from a given linear buffer.
540  *
541  * Returns the number of bytes handles or -errno in case of an error. Short
542  * reads are only returned if the end of the file is reached.
543  */
544 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
545 {
546     ssize_t offset = 0;
547     ssize_t len;
548
549     while (offset < aiocb->aio_nbytes) {
550         if (aiocb->aio_type & QEMU_AIO_WRITE) {
551             len = pwrite(aiocb->aio_fildes,
552                          (const char *)buf + offset,
553                          aiocb->aio_nbytes - offset,
554                          aiocb->aio_offset + offset);
555         } else {
556             len = pread(aiocb->aio_fildes,
557                         buf + offset,
558                         aiocb->aio_nbytes - offset,
559                         aiocb->aio_offset + offset);
560         }
561         if (len == -1 && errno == EINTR) {
562             continue;
563         } else if (len == -1) {
564             offset = -errno;
565             break;
566         } else if (len == 0) {
567             break;
568         }
569         offset += len;
570     }
571
572     return offset;
573 }
574
575 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
576 {
577     ssize_t nbytes;
578     char *buf;
579
580     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
581         /*
582          * If there is just a single buffer, and it is properly aligned
583          * we can just use plain pread/pwrite without any problems.
584          */
585         if (aiocb->aio_niov == 1) {
586              return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
587         }
588         /*
589          * We have more than one iovec, and all are properly aligned.
590          *
591          * Try preadv/pwritev first and fall back to linearizing the
592          * buffer if it's not supported.
593          */
594         if (preadv_present) {
595             nbytes = handle_aiocb_rw_vector(aiocb);
596             if (nbytes == aiocb->aio_nbytes ||
597                 (nbytes < 0 && nbytes != -ENOSYS)) {
598                 return nbytes;
599             }
600             preadv_present = false;
601         }
602
603         /*
604          * XXX(hch): short read/write.  no easy way to handle the reminder
605          * using these interfaces.  For now retry using plain
606          * pread/pwrite?
607          */
608     }
609
610     /*
611      * Ok, we have to do it the hard way, copy all segments into
612      * a single aligned buffer.
613      */
614     buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
615     if (aiocb->aio_type & QEMU_AIO_WRITE) {
616         char *p = buf;
617         int i;
618
619         for (i = 0; i < aiocb->aio_niov; ++i) {
620             memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
621             p += aiocb->aio_iov[i].iov_len;
622         }
623     }
624
625     nbytes = handle_aiocb_rw_linear(aiocb, buf);
626     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
627         char *p = buf;
628         size_t count = aiocb->aio_nbytes, copy;
629         int i;
630
631         for (i = 0; i < aiocb->aio_niov && count; ++i) {
632             copy = count;
633             if (copy > aiocb->aio_iov[i].iov_len) {
634                 copy = aiocb->aio_iov[i].iov_len;
635             }
636             memcpy(aiocb->aio_iov[i].iov_base, p, copy);
637             p     += copy;
638             count -= copy;
639         }
640     }
641     qemu_vfree(buf);
642
643     return nbytes;
644 }
645
646 static int aio_worker(void *arg)
647 {
648     RawPosixAIOData *aiocb = arg;
649     ssize_t ret = 0;
650
651     switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
652     case QEMU_AIO_READ:
653         ret = handle_aiocb_rw(aiocb);
654         if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
655             iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
656                       0, aiocb->aio_nbytes - ret);
657
658             ret = aiocb->aio_nbytes;
659         }
660         if (ret == aiocb->aio_nbytes) {
661             ret = 0;
662         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
663             ret = -EINVAL;
664         }
665         break;
666     case QEMU_AIO_WRITE:
667         ret = handle_aiocb_rw(aiocb);
668         if (ret == aiocb->aio_nbytes) {
669             ret = 0;
670         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
671             ret = -EINVAL;
672         }
673         break;
674     case QEMU_AIO_FLUSH:
675         ret = handle_aiocb_flush(aiocb);
676         break;
677     case QEMU_AIO_IOCTL:
678         ret = handle_aiocb_ioctl(aiocb);
679         break;
680     default:
681         fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
682         ret = -EINVAL;
683         break;
684     }
685
686     g_slice_free(RawPosixAIOData, aiocb);
687     return ret;
688 }
689
690 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
691         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
692         BlockDriverCompletionFunc *cb, void *opaque, int type)
693 {
694     RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
695
696     acb->bs = bs;
697     acb->aio_type = type;
698     acb->aio_fildes = fd;
699
700     if (qiov) {
701         acb->aio_iov = qiov->iov;
702         acb->aio_niov = qiov->niov;
703     }
704     acb->aio_nbytes = nb_sectors * 512;
705     acb->aio_offset = sector_num * 512;
706
707     trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
708     return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
709 }
710
711 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
712         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
713         BlockDriverCompletionFunc *cb, void *opaque, int type)
714 {
715     BDRVRawState *s = bs->opaque;
716
717     if (fd_open(bs) < 0)
718         return NULL;
719
720     /*
721      * If O_DIRECT is used the buffer needs to be aligned on a sector
722      * boundary.  Check if this is the case or tell the low-level
723      * driver that it needs to copy the buffer.
724      */
725     if ((bs->open_flags & BDRV_O_NOCACHE)) {
726         if (!qiov_is_aligned(bs, qiov)) {
727             type |= QEMU_AIO_MISALIGNED;
728 #ifdef CONFIG_LINUX_AIO
729         } else if (s->use_aio) {
730             return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
731                                nb_sectors, cb, opaque, type);
732 #endif
733         }
734     }
735
736     return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
737                        cb, opaque, type);
738 }
739
740 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
741         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
742         BlockDriverCompletionFunc *cb, void *opaque)
743 {
744     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
745                           cb, opaque, QEMU_AIO_READ);
746 }
747
748 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
749         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
750         BlockDriverCompletionFunc *cb, void *opaque)
751 {
752     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
753                           cb, opaque, QEMU_AIO_WRITE);
754 }
755
756 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
757         BlockDriverCompletionFunc *cb, void *opaque)
758 {
759     BDRVRawState *s = bs->opaque;
760
761     if (fd_open(bs) < 0)
762         return NULL;
763
764     return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
765 }
766
767 static void raw_close(BlockDriverState *bs)
768 {
769     BDRVRawState *s = bs->opaque;
770     if (s->fd >= 0) {
771         qemu_close(s->fd);
772         s->fd = -1;
773     }
774 }
775
776 static int raw_truncate(BlockDriverState *bs, int64_t offset)
777 {
778     BDRVRawState *s = bs->opaque;
779     struct stat st;
780
781     if (fstat(s->fd, &st)) {
782         return -errno;
783     }
784
785     if (S_ISREG(st.st_mode)) {
786         if (ftruncate(s->fd, offset) < 0) {
787             return -errno;
788         }
789     } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
790        if (offset > raw_getlength(bs)) {
791            return -EINVAL;
792        }
793     } else {
794         return -ENOTSUP;
795     }
796
797     return 0;
798 }
799
800 #ifdef __OpenBSD__
801 static int64_t raw_getlength(BlockDriverState *bs)
802 {
803     BDRVRawState *s = bs->opaque;
804     int fd = s->fd;
805     struct stat st;
806
807     if (fstat(fd, &st))
808         return -1;
809     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
810         struct disklabel dl;
811
812         if (ioctl(fd, DIOCGDINFO, &dl))
813             return -1;
814         return (uint64_t)dl.d_secsize *
815             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
816     } else
817         return st.st_size;
818 }
819 #elif defined(__NetBSD__)
820 static int64_t raw_getlength(BlockDriverState *bs)
821 {
822     BDRVRawState *s = bs->opaque;
823     int fd = s->fd;
824     struct stat st;
825
826     if (fstat(fd, &st))
827         return -1;
828     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
829         struct dkwedge_info dkw;
830
831         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
832             return dkw.dkw_size * 512;
833         } else {
834             struct disklabel dl;
835
836             if (ioctl(fd, DIOCGDINFO, &dl))
837                 return -1;
838             return (uint64_t)dl.d_secsize *
839                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
840         }
841     } else
842         return st.st_size;
843 }
844 #elif defined(__sun__)
845 static int64_t raw_getlength(BlockDriverState *bs)
846 {
847     BDRVRawState *s = bs->opaque;
848     struct dk_minfo minfo;
849     int ret;
850
851     ret = fd_open(bs);
852     if (ret < 0) {
853         return ret;
854     }
855
856     /*
857      * Use the DKIOCGMEDIAINFO ioctl to read the size.
858      */
859     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
860     if (ret != -1) {
861         return minfo.dki_lbsize * minfo.dki_capacity;
862     }
863
864     /*
865      * There are reports that lseek on some devices fails, but
866      * irc discussion said that contingency on contingency was overkill.
867      */
868     return lseek(s->fd, 0, SEEK_END);
869 }
870 #elif defined(CONFIG_BSD)
871 static int64_t raw_getlength(BlockDriverState *bs)
872 {
873     BDRVRawState *s = bs->opaque;
874     int fd = s->fd;
875     int64_t size;
876     struct stat sb;
877 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
878     int reopened = 0;
879 #endif
880     int ret;
881
882     ret = fd_open(bs);
883     if (ret < 0)
884         return ret;
885
886 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
887 again:
888 #endif
889     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
890 #ifdef DIOCGMEDIASIZE
891         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
892 #elif defined(DIOCGPART)
893         {
894                 struct partinfo pi;
895                 if (ioctl(fd, DIOCGPART, &pi) == 0)
896                         size = pi.media_size;
897                 else
898                         size = 0;
899         }
900         if (size == 0)
901 #endif
902 #if defined(__APPLE__) && defined(__MACH__)
903         size = LONG_LONG_MAX;
904 #else
905         size = lseek(fd, 0LL, SEEK_END);
906 #endif
907 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
908         switch(s->type) {
909         case FTYPE_CD:
910             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
911             if (size == 2048LL * (unsigned)-1)
912                 size = 0;
913             /* XXX no disc?  maybe we need to reopen... */
914             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
915                 reopened = 1;
916                 goto again;
917             }
918         }
919 #endif
920     } else {
921         size = lseek(fd, 0, SEEK_END);
922     }
923     return size;
924 }
925 #else
926 static int64_t raw_getlength(BlockDriverState *bs)
927 {
928     BDRVRawState *s = bs->opaque;
929     int ret;
930
931     ret = fd_open(bs);
932     if (ret < 0) {
933         return ret;
934     }
935
936     return lseek(s->fd, 0, SEEK_END);
937 }
938 #endif
939
940 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
941 {
942     struct stat st;
943     BDRVRawState *s = bs->opaque;
944
945     if (fstat(s->fd, &st) < 0) {
946         return -errno;
947     }
948     return (int64_t)st.st_blocks * 512;
949 }
950
951 static int raw_create(const char *filename, QEMUOptionParameter *options)
952 {
953     int fd;
954     int result = 0;
955     int64_t total_size = 0;
956
957     /* Read out options */
958     while (options && options->name) {
959         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
960             total_size = options->value.n / BDRV_SECTOR_SIZE;
961         }
962         options++;
963     }
964
965     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
966                    0644);
967     if (fd < 0) {
968         result = -errno;
969     } else {
970         if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
971             result = -errno;
972         }
973         if (qemu_close(fd) != 0) {
974             result = -errno;
975         }
976     }
977     return result;
978 }
979
980 /*
981  * Returns true iff the specified sector is present in the disk image. Drivers
982  * not implementing the functionality are assumed to not support backing files,
983  * hence all their sectors are reported as allocated.
984  *
985  * If 'sector_num' is beyond the end of the disk image the return value is 0
986  * and 'pnum' is set to 0.
987  *
988  * 'pnum' is set to the number of sectors (including and immediately following
989  * the specified sector) that are known to be in the same
990  * allocated/unallocated state.
991  *
992  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
993  * beyond the end of the disk image it will be clamped.
994  */
995 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
996                                             int64_t sector_num,
997                                             int nb_sectors, int *pnum)
998 {
999     off_t start, data, hole;
1000     int ret;
1001
1002     ret = fd_open(bs);
1003     if (ret < 0) {
1004         return ret;
1005     }
1006
1007     start = sector_num * BDRV_SECTOR_SIZE;
1008
1009 #ifdef CONFIG_FIEMAP
1010
1011     BDRVRawState *s = bs->opaque;
1012     struct {
1013         struct fiemap fm;
1014         struct fiemap_extent fe;
1015     } f;
1016
1017     f.fm.fm_start = start;
1018     f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1019     f.fm.fm_flags = 0;
1020     f.fm.fm_extent_count = 1;
1021     f.fm.fm_reserved = 0;
1022     if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1023         /* Assume everything is allocated.  */
1024         *pnum = nb_sectors;
1025         return 1;
1026     }
1027
1028     if (f.fm.fm_mapped_extents == 0) {
1029         /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1030          * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1031          */
1032         off_t length = lseek(s->fd, 0, SEEK_END);
1033         hole = f.fm.fm_start;
1034         data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1035     } else {
1036         data = f.fe.fe_logical;
1037         hole = f.fe.fe_logical + f.fe.fe_length;
1038     }
1039
1040 #elif defined SEEK_HOLE && defined SEEK_DATA
1041
1042     BDRVRawState *s = bs->opaque;
1043
1044     hole = lseek(s->fd, start, SEEK_HOLE);
1045     if (hole == -1) {
1046         /* -ENXIO indicates that sector_num was past the end of the file.
1047          * There is a virtual hole there.  */
1048         assert(errno != -ENXIO);
1049
1050         /* Most likely EINVAL.  Assume everything is allocated.  */
1051         *pnum = nb_sectors;
1052         return 1;
1053     }
1054
1055     if (hole > start) {
1056         data = start;
1057     } else {
1058         /* On a hole.  We need another syscall to find its end.  */
1059         data = lseek(s->fd, start, SEEK_DATA);
1060         if (data == -1) {
1061             data = lseek(s->fd, 0, SEEK_END);
1062         }
1063     }
1064 #else
1065     *pnum = nb_sectors;
1066     return 1;
1067 #endif
1068
1069     if (data <= start) {
1070         /* On a data extent, compute sectors to the end of the extent.  */
1071         *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1072         return 1;
1073     } else {
1074         /* On a hole, compute sectors to the beginning of the next extent.  */
1075         *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1076         return 0;
1077     }
1078 }
1079
1080 #ifdef CONFIG_XFS
1081 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
1082 {
1083     struct xfs_flock64 fl;
1084
1085     memset(&fl, 0, sizeof(fl));
1086     fl.l_whence = SEEK_SET;
1087     fl.l_start = sector_num << 9;
1088     fl.l_len = (int64_t)nb_sectors << 9;
1089
1090     if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1091         DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
1092         return -errno;
1093     }
1094
1095     return 0;
1096 }
1097 #endif
1098
1099 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
1100     int64_t sector_num, int nb_sectors)
1101 {
1102 #ifdef CONFIG_XFS
1103     BDRVRawState *s = bs->opaque;
1104
1105     if (s->is_xfs) {
1106         return xfs_discard(s, sector_num, nb_sectors);
1107     }
1108 #endif
1109
1110     return 0;
1111 }
1112
1113 static QEMUOptionParameter raw_create_options[] = {
1114     {
1115         .name = BLOCK_OPT_SIZE,
1116         .type = OPT_SIZE,
1117         .help = "Virtual disk size"
1118     },
1119     { NULL }
1120 };
1121
1122 static BlockDriver bdrv_file = {
1123     .format_name = "file",
1124     .protocol_name = "file",
1125     .instance_size = sizeof(BDRVRawState),
1126     .bdrv_probe = NULL, /* no probe for protocols */
1127     .bdrv_file_open = raw_open,
1128     .bdrv_reopen_prepare = raw_reopen_prepare,
1129     .bdrv_reopen_commit = raw_reopen_commit,
1130     .bdrv_reopen_abort = raw_reopen_abort,
1131     .bdrv_close = raw_close,
1132     .bdrv_create = raw_create,
1133     .bdrv_co_discard = raw_co_discard,
1134     .bdrv_co_is_allocated = raw_co_is_allocated,
1135
1136     .bdrv_aio_readv = raw_aio_readv,
1137     .bdrv_aio_writev = raw_aio_writev,
1138     .bdrv_aio_flush = raw_aio_flush,
1139
1140     .bdrv_truncate = raw_truncate,
1141     .bdrv_getlength = raw_getlength,
1142     .bdrv_get_allocated_file_size
1143                         = raw_get_allocated_file_size,
1144
1145     .create_options = raw_create_options,
1146 };
1147
1148 /***********************************************/
1149 /* host device */
1150
1151 #if defined(__APPLE__) && defined(__MACH__)
1152 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1153 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1154
1155 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1156 {
1157     kern_return_t       kernResult;
1158     mach_port_t     masterPort;
1159     CFMutableDictionaryRef  classesToMatch;
1160
1161     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1162     if ( KERN_SUCCESS != kernResult ) {
1163         printf( "IOMasterPort returned %d\n", kernResult );
1164     }
1165
1166     classesToMatch = IOServiceMatching( kIOCDMediaClass );
1167     if ( classesToMatch == NULL ) {
1168         printf( "IOServiceMatching returned a NULL dictionary.\n" );
1169     } else {
1170     CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1171     }
1172     kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1173     if ( KERN_SUCCESS != kernResult )
1174     {
1175         printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1176     }
1177
1178     return kernResult;
1179 }
1180
1181 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1182 {
1183     io_object_t     nextMedia;
1184     kern_return_t   kernResult = KERN_FAILURE;
1185     *bsdPath = '\0';
1186     nextMedia = IOIteratorNext( mediaIterator );
1187     if ( nextMedia )
1188     {
1189         CFTypeRef   bsdPathAsCFString;
1190     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1191         if ( bsdPathAsCFString ) {
1192             size_t devPathLength;
1193             strcpy( bsdPath, _PATH_DEV );
1194             strcat( bsdPath, "r" );
1195             devPathLength = strlen( bsdPath );
1196             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1197                 kernResult = KERN_SUCCESS;
1198             }
1199             CFRelease( bsdPathAsCFString );
1200         }
1201         IOObjectRelease( nextMedia );
1202     }
1203
1204     return kernResult;
1205 }
1206
1207 #endif
1208
1209 static int hdev_probe_device(const char *filename)
1210 {
1211     struct stat st;
1212
1213     /* allow a dedicated CD-ROM driver to match with a higher priority */
1214     if (strstart(filename, "/dev/cdrom", NULL))
1215         return 50;
1216
1217     if (stat(filename, &st) >= 0 &&
1218             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1219         return 100;
1220     }
1221
1222     return 0;
1223 }
1224
1225 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1226 {
1227     BDRVRawState *s = bs->opaque;
1228
1229 #if defined(__APPLE__) && defined(__MACH__)
1230     if (strstart(filename, "/dev/cdrom", NULL)) {
1231         kern_return_t kernResult;
1232         io_iterator_t mediaIterator;
1233         char bsdPath[ MAXPATHLEN ];
1234         int fd;
1235
1236         kernResult = FindEjectableCDMedia( &mediaIterator );
1237         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1238
1239         if ( bsdPath[ 0 ] != '\0' ) {
1240             strcat(bsdPath,"s0");
1241             /* some CDs don't have a partition 0 */
1242             fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1243             if (fd < 0) {
1244                 bsdPath[strlen(bsdPath)-1] = '1';
1245             } else {
1246                 qemu_close(fd);
1247             }
1248             filename = bsdPath;
1249         }
1250
1251         if ( mediaIterator )
1252             IOObjectRelease( mediaIterator );
1253     }
1254 #endif
1255
1256     s->type = FTYPE_FILE;
1257 #if defined(__linux__)
1258     {
1259         char resolved_path[ MAXPATHLEN ], *temp;
1260
1261         temp = realpath(filename, resolved_path);
1262         if (temp && strstart(temp, "/dev/sg", NULL)) {
1263             bs->sg = 1;
1264         }
1265     }
1266 #endif
1267
1268     return raw_open_common(bs, filename, flags, 0);
1269 }
1270
1271 #if defined(__linux__)
1272 /* Note: we do not have a reliable method to detect if the floppy is
1273    present. The current method is to try to open the floppy at every
1274    I/O and to keep it opened during a few hundreds of ms. */
1275 static int fd_open(BlockDriverState *bs)
1276 {
1277     BDRVRawState *s = bs->opaque;
1278     int last_media_present;
1279
1280     if (s->type != FTYPE_FD)
1281         return 0;
1282     last_media_present = (s->fd >= 0);
1283     if (s->fd >= 0 &&
1284         (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1285         qemu_close(s->fd);
1286         s->fd = -1;
1287 #ifdef DEBUG_FLOPPY
1288         printf("Floppy closed\n");
1289 #endif
1290     }
1291     if (s->fd < 0) {
1292         if (s->fd_got_error &&
1293             (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1294 #ifdef DEBUG_FLOPPY
1295             printf("No floppy (open delayed)\n");
1296 #endif
1297             return -EIO;
1298         }
1299         s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1300         if (s->fd < 0) {
1301             s->fd_error_time = get_clock();
1302             s->fd_got_error = 1;
1303             if (last_media_present)
1304                 s->fd_media_changed = 1;
1305 #ifdef DEBUG_FLOPPY
1306             printf("No floppy\n");
1307 #endif
1308             return -EIO;
1309         }
1310 #ifdef DEBUG_FLOPPY
1311         printf("Floppy opened\n");
1312 #endif
1313     }
1314     if (!last_media_present)
1315         s->fd_media_changed = 1;
1316     s->fd_open_time = get_clock();
1317     s->fd_got_error = 0;
1318     return 0;
1319 }
1320
1321 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1322 {
1323     BDRVRawState *s = bs->opaque;
1324
1325     return ioctl(s->fd, req, buf);
1326 }
1327
1328 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1329         unsigned long int req, void *buf,
1330         BlockDriverCompletionFunc *cb, void *opaque)
1331 {
1332     BDRVRawState *s = bs->opaque;
1333     RawPosixAIOData *acb;
1334
1335     if (fd_open(bs) < 0)
1336         return NULL;
1337
1338     acb = g_slice_new(RawPosixAIOData);
1339     acb->bs = bs;
1340     acb->aio_type = QEMU_AIO_IOCTL;
1341     acb->aio_fildes = s->fd;
1342     acb->aio_offset = 0;
1343     acb->aio_ioctl_buf = buf;
1344     acb->aio_ioctl_cmd = req;
1345     return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
1346 }
1347
1348 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1349 static int fd_open(BlockDriverState *bs)
1350 {
1351     BDRVRawState *s = bs->opaque;
1352
1353     /* this is just to ensure s->fd is sane (its called by io ops) */
1354     if (s->fd >= 0)
1355         return 0;
1356     return -EIO;
1357 }
1358 #else /* !linux && !FreeBSD */
1359
1360 static int fd_open(BlockDriverState *bs)
1361 {
1362     return 0;
1363 }
1364
1365 #endif /* !linux && !FreeBSD */
1366
1367 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1368 {
1369     int fd;
1370     int ret = 0;
1371     struct stat stat_buf;
1372     int64_t total_size = 0;
1373
1374     /* Read out options */
1375     while (options && options->name) {
1376         if (!strcmp(options->name, "size")) {
1377             total_size = options->value.n / BDRV_SECTOR_SIZE;
1378         }
1379         options++;
1380     }
1381
1382     fd = qemu_open(filename, O_WRONLY | O_BINARY);
1383     if (fd < 0)
1384         return -errno;
1385
1386     if (fstat(fd, &stat_buf) < 0)
1387         ret = -errno;
1388     else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1389         ret = -ENODEV;
1390     else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1391         ret = -ENOSPC;
1392
1393     qemu_close(fd);
1394     return ret;
1395 }
1396
1397 static int hdev_has_zero_init(BlockDriverState *bs)
1398 {
1399     return 0;
1400 }
1401
1402 static BlockDriver bdrv_host_device = {
1403     .format_name        = "host_device",
1404     .protocol_name        = "host_device",
1405     .instance_size      = sizeof(BDRVRawState),
1406     .bdrv_probe_device  = hdev_probe_device,
1407     .bdrv_file_open     = hdev_open,
1408     .bdrv_close         = raw_close,
1409     .bdrv_reopen_prepare = raw_reopen_prepare,
1410     .bdrv_reopen_commit  = raw_reopen_commit,
1411     .bdrv_reopen_abort   = raw_reopen_abort,
1412     .bdrv_create        = hdev_create,
1413     .create_options     = raw_create_options,
1414     .bdrv_has_zero_init = hdev_has_zero_init,
1415
1416     .bdrv_aio_readv     = raw_aio_readv,
1417     .bdrv_aio_writev    = raw_aio_writev,
1418     .bdrv_aio_flush     = raw_aio_flush,
1419
1420     .bdrv_truncate      = raw_truncate,
1421     .bdrv_getlength     = raw_getlength,
1422     .bdrv_get_allocated_file_size
1423                         = raw_get_allocated_file_size,
1424
1425     /* generic scsi device */
1426 #ifdef __linux__
1427     .bdrv_ioctl         = hdev_ioctl,
1428     .bdrv_aio_ioctl     = hdev_aio_ioctl,
1429 #endif
1430 };
1431
1432 #ifdef __linux__
1433 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1434 {
1435     BDRVRawState *s = bs->opaque;
1436     int ret;
1437
1438     s->type = FTYPE_FD;
1439
1440     /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1441     ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1442     if (ret)
1443         return ret;
1444
1445     /* close fd so that we can reopen it as needed */
1446     qemu_close(s->fd);
1447     s->fd = -1;
1448     s->fd_media_changed = 1;
1449
1450     return 0;
1451 }
1452
1453 static int floppy_probe_device(const char *filename)
1454 {
1455     int fd, ret;
1456     int prio = 0;
1457     struct floppy_struct fdparam;
1458     struct stat st;
1459
1460     if (strstart(filename, "/dev/fd", NULL) &&
1461         !strstart(filename, "/dev/fdset/", NULL)) {
1462         prio = 50;
1463     }
1464
1465     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1466     if (fd < 0) {
1467         goto out;
1468     }
1469     ret = fstat(fd, &st);
1470     if (ret == -1 || !S_ISBLK(st.st_mode)) {
1471         goto outc;
1472     }
1473
1474     /* Attempt to detect via a floppy specific ioctl */
1475     ret = ioctl(fd, FDGETPRM, &fdparam);
1476     if (ret >= 0)
1477         prio = 100;
1478
1479 outc:
1480     qemu_close(fd);
1481 out:
1482     return prio;
1483 }
1484
1485
1486 static int floppy_is_inserted(BlockDriverState *bs)
1487 {
1488     return fd_open(bs) >= 0;
1489 }
1490
1491 static int floppy_media_changed(BlockDriverState *bs)
1492 {
1493     BDRVRawState *s = bs->opaque;
1494     int ret;
1495
1496     /*
1497      * XXX: we do not have a true media changed indication.
1498      * It does not work if the floppy is changed without trying to read it.
1499      */
1500     fd_open(bs);
1501     ret = s->fd_media_changed;
1502     s->fd_media_changed = 0;
1503 #ifdef DEBUG_FLOPPY
1504     printf("Floppy changed=%d\n", ret);
1505 #endif
1506     return ret;
1507 }
1508
1509 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1510 {
1511     BDRVRawState *s = bs->opaque;
1512     int fd;
1513
1514     if (s->fd >= 0) {
1515         qemu_close(s->fd);
1516         s->fd = -1;
1517     }
1518     fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1519     if (fd >= 0) {
1520         if (ioctl(fd, FDEJECT, 0) < 0)
1521             perror("FDEJECT");
1522         qemu_close(fd);
1523     }
1524 }
1525
1526 static BlockDriver bdrv_host_floppy = {
1527     .format_name        = "host_floppy",
1528     .protocol_name      = "host_floppy",
1529     .instance_size      = sizeof(BDRVRawState),
1530     .bdrv_probe_device  = floppy_probe_device,
1531     .bdrv_file_open     = floppy_open,
1532     .bdrv_close         = raw_close,
1533     .bdrv_reopen_prepare = raw_reopen_prepare,
1534     .bdrv_reopen_commit  = raw_reopen_commit,
1535     .bdrv_reopen_abort   = raw_reopen_abort,
1536     .bdrv_create        = hdev_create,
1537     .create_options     = raw_create_options,
1538     .bdrv_has_zero_init = hdev_has_zero_init,
1539
1540     .bdrv_aio_readv     = raw_aio_readv,
1541     .bdrv_aio_writev    = raw_aio_writev,
1542     .bdrv_aio_flush     = raw_aio_flush,
1543
1544     .bdrv_truncate      = raw_truncate,
1545     .bdrv_getlength     = raw_getlength,
1546     .bdrv_get_allocated_file_size
1547                         = raw_get_allocated_file_size,
1548
1549     /* removable device support */
1550     .bdrv_is_inserted   = floppy_is_inserted,
1551     .bdrv_media_changed = floppy_media_changed,
1552     .bdrv_eject         = floppy_eject,
1553 };
1554
1555 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1556 {
1557     BDRVRawState *s = bs->opaque;
1558
1559     s->type = FTYPE_CD;
1560
1561     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1562     return raw_open_common(bs, filename, flags, O_NONBLOCK);
1563 }
1564
1565 static int cdrom_probe_device(const char *filename)
1566 {
1567     int fd, ret;
1568     int prio = 0;
1569     struct stat st;
1570
1571     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1572     if (fd < 0) {
1573         goto out;
1574     }
1575     ret = fstat(fd, &st);
1576     if (ret == -1 || !S_ISBLK(st.st_mode)) {
1577         goto outc;
1578     }
1579
1580     /* Attempt to detect via a CDROM specific ioctl */
1581     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1582     if (ret >= 0)
1583         prio = 100;
1584
1585 outc:
1586     qemu_close(fd);
1587 out:
1588     return prio;
1589 }
1590
1591 static int cdrom_is_inserted(BlockDriverState *bs)
1592 {
1593     BDRVRawState *s = bs->opaque;
1594     int ret;
1595
1596     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1597     if (ret == CDS_DISC_OK)
1598         return 1;
1599     return 0;
1600 }
1601
1602 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1603 {
1604     BDRVRawState *s = bs->opaque;
1605
1606     if (eject_flag) {
1607         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1608             perror("CDROMEJECT");
1609     } else {
1610         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1611             perror("CDROMEJECT");
1612     }
1613 }
1614
1615 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1616 {
1617     BDRVRawState *s = bs->opaque;
1618
1619     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1620         /*
1621          * Note: an error can happen if the distribution automatically
1622          * mounts the CD-ROM
1623          */
1624         /* perror("CDROM_LOCKDOOR"); */
1625     }
1626 }
1627
1628 static BlockDriver bdrv_host_cdrom = {
1629     .format_name        = "host_cdrom",
1630     .protocol_name      = "host_cdrom",
1631     .instance_size      = sizeof(BDRVRawState),
1632     .bdrv_probe_device  = cdrom_probe_device,
1633     .bdrv_file_open     = cdrom_open,
1634     .bdrv_close         = raw_close,
1635     .bdrv_reopen_prepare = raw_reopen_prepare,
1636     .bdrv_reopen_commit  = raw_reopen_commit,
1637     .bdrv_reopen_abort   = raw_reopen_abort,
1638     .bdrv_create        = hdev_create,
1639     .create_options     = raw_create_options,
1640     .bdrv_has_zero_init = hdev_has_zero_init,
1641
1642     .bdrv_aio_readv     = raw_aio_readv,
1643     .bdrv_aio_writev    = raw_aio_writev,
1644     .bdrv_aio_flush     = raw_aio_flush,
1645
1646     .bdrv_truncate      = raw_truncate,
1647     .bdrv_getlength     = raw_getlength,
1648     .bdrv_get_allocated_file_size
1649                         = raw_get_allocated_file_size,
1650
1651     /* removable device support */
1652     .bdrv_is_inserted   = cdrom_is_inserted,
1653     .bdrv_eject         = cdrom_eject,
1654     .bdrv_lock_medium   = cdrom_lock_medium,
1655
1656     /* generic scsi device */
1657     .bdrv_ioctl         = hdev_ioctl,
1658     .bdrv_aio_ioctl     = hdev_aio_ioctl,
1659 };
1660 #endif /* __linux__ */
1661
1662 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1663 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1664 {
1665     BDRVRawState *s = bs->opaque;
1666     int ret;
1667
1668     s->type = FTYPE_CD;
1669
1670     ret = raw_open_common(bs, filename, flags, 0);
1671     if (ret)
1672         return ret;
1673
1674     /* make sure the door isn't locked at this time */
1675     ioctl(s->fd, CDIOCALLOW);
1676     return 0;
1677 }
1678
1679 static int cdrom_probe_device(const char *filename)
1680 {
1681     if (strstart(filename, "/dev/cd", NULL) ||
1682             strstart(filename, "/dev/acd", NULL))
1683         return 100;
1684     return 0;
1685 }
1686
1687 static int cdrom_reopen(BlockDriverState *bs)
1688 {
1689     BDRVRawState *s = bs->opaque;
1690     int fd;
1691
1692     /*
1693      * Force reread of possibly changed/newly loaded disc,
1694      * FreeBSD seems to not notice sometimes...
1695      */
1696     if (s->fd >= 0)
1697         qemu_close(s->fd);
1698     fd = qemu_open(bs->filename, s->open_flags, 0644);
1699     if (fd < 0) {
1700         s->fd = -1;
1701         return -EIO;
1702     }
1703     s->fd = fd;
1704
1705     /* make sure the door isn't locked at this time */
1706     ioctl(s->fd, CDIOCALLOW);
1707     return 0;
1708 }
1709
1710 static int cdrom_is_inserted(BlockDriverState *bs)
1711 {
1712     return raw_getlength(bs) > 0;
1713 }
1714
1715 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1716 {
1717     BDRVRawState *s = bs->opaque;
1718
1719     if (s->fd < 0)
1720         return;
1721
1722     (void) ioctl(s->fd, CDIOCALLOW);
1723
1724     if (eject_flag) {
1725         if (ioctl(s->fd, CDIOCEJECT) < 0)
1726             perror("CDIOCEJECT");
1727     } else {
1728         if (ioctl(s->fd, CDIOCCLOSE) < 0)
1729             perror("CDIOCCLOSE");
1730     }
1731
1732     cdrom_reopen(bs);
1733 }
1734
1735 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1736 {
1737     BDRVRawState *s = bs->opaque;
1738
1739     if (s->fd < 0)
1740         return;
1741     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1742         /*
1743          * Note: an error can happen if the distribution automatically
1744          * mounts the CD-ROM
1745          */
1746         /* perror("CDROM_LOCKDOOR"); */
1747     }
1748 }
1749
1750 static BlockDriver bdrv_host_cdrom = {
1751     .format_name        = "host_cdrom",
1752     .protocol_name      = "host_cdrom",
1753     .instance_size      = sizeof(BDRVRawState),
1754     .bdrv_probe_device  = cdrom_probe_device,
1755     .bdrv_file_open     = cdrom_open,
1756     .bdrv_close         = raw_close,
1757     .bdrv_reopen_prepare = raw_reopen_prepare,
1758     .bdrv_reopen_commit  = raw_reopen_commit,
1759     .bdrv_reopen_abort   = raw_reopen_abort,
1760     .bdrv_create        = hdev_create,
1761     .create_options     = raw_create_options,
1762     .bdrv_has_zero_init = hdev_has_zero_init,
1763
1764     .bdrv_aio_readv     = raw_aio_readv,
1765     .bdrv_aio_writev    = raw_aio_writev,
1766     .bdrv_aio_flush     = raw_aio_flush,
1767
1768     .bdrv_truncate      = raw_truncate,
1769     .bdrv_getlength     = raw_getlength,
1770     .bdrv_get_allocated_file_size
1771                         = raw_get_allocated_file_size,
1772
1773     /* removable device support */
1774     .bdrv_is_inserted   = cdrom_is_inserted,
1775     .bdrv_eject         = cdrom_eject,
1776     .bdrv_lock_medium   = cdrom_lock_medium,
1777 };
1778 #endif /* __FreeBSD__ */
1779
1780 static void bdrv_file_init(void)
1781 {
1782     /*
1783      * Register all the drivers.  Note that order is important, the driver
1784      * registered last will get probed first.
1785      */
1786     bdrv_register(&bdrv_file);
1787     bdrv_register(&bdrv_host_device);
1788 #ifdef __linux__
1789     bdrv_register(&bdrv_host_floppy);
1790     bdrv_register(&bdrv_host_cdrom);
1791 #endif
1792 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1793     bdrv_register(&bdrv_host_cdrom);
1794 #endif
1795 }
1796
1797 block_init(bdrv_file_init);