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