]> Git Repo - qemu.git/blob - block/raw-posix.c
Merge remote-tracking branch 'remotes/mst/tags/for_upstream' into staging
[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 #ifndef FS_NOCOW_FL
59 #define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
60 #endif
61 #endif
62 #ifdef CONFIG_FIEMAP
63 #include <linux/fiemap.h>
64 #endif
65 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
66 #include <linux/falloc.h>
67 #endif
68 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
69 #include <sys/disk.h>
70 #include <sys/cdio.h>
71 #endif
72
73 #ifdef __OpenBSD__
74 #include <sys/ioctl.h>
75 #include <sys/disklabel.h>
76 #include <sys/dkio.h>
77 #endif
78
79 #ifdef __NetBSD__
80 #include <sys/ioctl.h>
81 #include <sys/disklabel.h>
82 #include <sys/dkio.h>
83 #include <sys/disk.h>
84 #endif
85
86 #ifdef __DragonFly__
87 #include <sys/ioctl.h>
88 #include <sys/diskslice.h>
89 #endif
90
91 #ifdef CONFIG_XFS
92 #include <xfs/xfs.h>
93 #endif
94
95 //#define DEBUG_FLOPPY
96
97 //#define DEBUG_BLOCK
98 #if defined(DEBUG_BLOCK)
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
100     { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
101 #else
102 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
103 #endif
104
105 /* OS X does not have O_DSYNC */
106 #ifndef O_DSYNC
107 #ifdef O_SYNC
108 #define O_DSYNC O_SYNC
109 #elif defined(O_FSYNC)
110 #define O_DSYNC O_FSYNC
111 #endif
112 #endif
113
114 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
115 #ifndef O_DIRECT
116 #define O_DIRECT O_DSYNC
117 #endif
118
119 #define FTYPE_FILE   0
120 #define FTYPE_CD     1
121 #define FTYPE_FD     2
122
123 /* if the FD is not accessed during that time (in ns), we try to
124    reopen it to see if the disk has been changed */
125 #define FD_OPEN_TIMEOUT (1000000000)
126
127 #define MAX_BLOCKSIZE   4096
128
129 typedef struct BDRVRawState {
130     int fd;
131     int type;
132     int open_flags;
133     size_t buf_align;
134
135 #if defined(__linux__)
136     /* linux floppy specific */
137     int64_t fd_open_time;
138     int64_t fd_error_time;
139     int fd_got_error;
140     int fd_media_changed;
141 #endif
142 #ifdef CONFIG_LINUX_AIO
143     int use_aio;
144     void *aio_ctx;
145 #endif
146 #ifdef CONFIG_XFS
147     bool is_xfs:1;
148 #endif
149     bool has_discard:1;
150     bool has_write_zeroes:1;
151     bool discard_zeroes:1;
152 #ifdef CONFIG_FIEMAP
153     bool skip_fiemap;
154 #endif
155 } BDRVRawState;
156
157 typedef struct BDRVRawReopenState {
158     int fd;
159     int open_flags;
160 #ifdef CONFIG_LINUX_AIO
161     int use_aio;
162 #endif
163 } BDRVRawReopenState;
164
165 static int fd_open(BlockDriverState *bs);
166 static int64_t raw_getlength(BlockDriverState *bs);
167
168 typedef struct RawPosixAIOData {
169     BlockDriverState *bs;
170     int aio_fildes;
171     union {
172         struct iovec *aio_iov;
173         void *aio_ioctl_buf;
174     };
175     int aio_niov;
176     uint64_t aio_nbytes;
177 #define aio_ioctl_cmd   aio_nbytes /* for QEMU_AIO_IOCTL */
178     off_t aio_offset;
179     int aio_type;
180 } RawPosixAIOData;
181
182 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
183 static int cdrom_reopen(BlockDriverState *bs);
184 #endif
185
186 #if defined(__NetBSD__)
187 static int raw_normalize_devicepath(const char **filename)
188 {
189     static char namebuf[PATH_MAX];
190     const char *dp, *fname;
191     struct stat sb;
192
193     fname = *filename;
194     dp = strrchr(fname, '/');
195     if (lstat(fname, &sb) < 0) {
196         fprintf(stderr, "%s: stat failed: %s\n",
197             fname, strerror(errno));
198         return -errno;
199     }
200
201     if (!S_ISBLK(sb.st_mode)) {
202         return 0;
203     }
204
205     if (dp == NULL) {
206         snprintf(namebuf, PATH_MAX, "r%s", fname);
207     } else {
208         snprintf(namebuf, PATH_MAX, "%.*s/r%s",
209             (int)(dp - fname), fname, dp + 1);
210     }
211     fprintf(stderr, "%s is a block device", fname);
212     *filename = namebuf;
213     fprintf(stderr, ", using %s\n", *filename);
214
215     return 0;
216 }
217 #else
218 static int raw_normalize_devicepath(const char **filename)
219 {
220     return 0;
221 }
222 #endif
223
224 static void raw_probe_alignment(BlockDriverState *bs)
225 {
226     BDRVRawState *s = bs->opaque;
227     char *buf;
228     unsigned int sector_size;
229
230     /* For /dev/sg devices the alignment is not really used.
231        With buffered I/O, we don't have any restrictions. */
232     if (bs->sg || !(s->open_flags & O_DIRECT)) {
233         bs->request_alignment = 1;
234         s->buf_align = 1;
235         return;
236     }
237
238     /* Try a few ioctls to get the right size */
239     bs->request_alignment = 0;
240     s->buf_align = 0;
241
242 #ifdef BLKSSZGET
243     if (ioctl(s->fd, BLKSSZGET, &sector_size) >= 0) {
244         bs->request_alignment = sector_size;
245     }
246 #endif
247 #ifdef DKIOCGETBLOCKSIZE
248     if (ioctl(s->fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
249         bs->request_alignment = sector_size;
250     }
251 #endif
252 #ifdef DIOCGSECTORSIZE
253     if (ioctl(s->fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
254         bs->request_alignment = sector_size;
255     }
256 #endif
257 #ifdef CONFIG_XFS
258     if (s->is_xfs) {
259         struct dioattr da;
260         if (xfsctl(NULL, s->fd, XFS_IOC_DIOINFO, &da) >= 0) {
261             bs->request_alignment = da.d_miniosz;
262             /* The kernel returns wrong information for d_mem */
263             /* s->buf_align = da.d_mem; */
264         }
265     }
266 #endif
267
268     /* If we could not get the sizes so far, we can only guess them */
269     if (!s->buf_align) {
270         size_t align;
271         buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);
272         for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
273             if (pread(s->fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {
274                 s->buf_align = align;
275                 break;
276             }
277         }
278         qemu_vfree(buf);
279     }
280
281     if (!bs->request_alignment) {
282         size_t align;
283         buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);
284         for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {
285             if (pread(s->fd, buf, align, 0) >= 0) {
286                 bs->request_alignment = align;
287                 break;
288             }
289         }
290         qemu_vfree(buf);
291     }
292 }
293
294 static void raw_parse_flags(int bdrv_flags, int *open_flags)
295 {
296     assert(open_flags != NULL);
297
298     *open_flags |= O_BINARY;
299     *open_flags &= ~O_ACCMODE;
300     if (bdrv_flags & BDRV_O_RDWR) {
301         *open_flags |= O_RDWR;
302     } else {
303         *open_flags |= O_RDONLY;
304     }
305
306     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
307      * and O_DIRECT for no caching. */
308     if ((bdrv_flags & BDRV_O_NOCACHE)) {
309         *open_flags |= O_DIRECT;
310     }
311 }
312
313 static void raw_detach_aio_context(BlockDriverState *bs)
314 {
315 #ifdef CONFIG_LINUX_AIO
316     BDRVRawState *s = bs->opaque;
317
318     if (s->use_aio) {
319         laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
320     }
321 #endif
322 }
323
324 static void raw_attach_aio_context(BlockDriverState *bs,
325                                    AioContext *new_context)
326 {
327 #ifdef CONFIG_LINUX_AIO
328     BDRVRawState *s = bs->opaque;
329
330     if (s->use_aio) {
331         laio_attach_aio_context(s->aio_ctx, new_context);
332     }
333 #endif
334 }
335
336 #ifdef CONFIG_LINUX_AIO
337 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
338 {
339     int ret = -1;
340     assert(aio_ctx != NULL);
341     assert(use_aio != NULL);
342     /*
343      * Currently Linux do AIO only for files opened with O_DIRECT
344      * specified so check NOCACHE flag too
345      */
346     if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
347                       (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
348
349         /* if non-NULL, laio_init() has already been run */
350         if (*aio_ctx == NULL) {
351             *aio_ctx = laio_init();
352             if (!*aio_ctx) {
353                 goto error;
354             }
355         }
356         *use_aio = 1;
357     } else {
358         *use_aio = 0;
359     }
360
361     ret = 0;
362
363 error:
364     return ret;
365 }
366 #endif
367
368 static void raw_parse_filename(const char *filename, QDict *options,
369                                Error **errp)
370 {
371     /* The filename does not have to be prefixed by the protocol name, since
372      * "file" is the default protocol; therefore, the return value of this
373      * function call can be ignored. */
374     strstart(filename, "file:", &filename);
375
376     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
377 }
378
379 static QemuOptsList raw_runtime_opts = {
380     .name = "raw",
381     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
382     .desc = {
383         {
384             .name = "filename",
385             .type = QEMU_OPT_STRING,
386             .help = "File name of the image",
387         },
388         { /* end of list */ }
389     },
390 };
391
392 static int raw_open_common(BlockDriverState *bs, QDict *options,
393                            int bdrv_flags, int open_flags, Error **errp)
394 {
395     BDRVRawState *s = bs->opaque;
396     QemuOpts *opts;
397     Error *local_err = NULL;
398     const char *filename = NULL;
399     int fd, ret;
400     struct stat st;
401
402     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
403     qemu_opts_absorb_qdict(opts, options, &local_err);
404     if (local_err) {
405         error_propagate(errp, local_err);
406         ret = -EINVAL;
407         goto fail;
408     }
409
410     filename = qemu_opt_get(opts, "filename");
411
412     ret = raw_normalize_devicepath(&filename);
413     if (ret != 0) {
414         error_setg_errno(errp, -ret, "Could not normalize device path");
415         goto fail;
416     }
417
418     s->open_flags = open_flags;
419     raw_parse_flags(bdrv_flags, &s->open_flags);
420
421     s->fd = -1;
422     fd = qemu_open(filename, s->open_flags, 0644);
423     if (fd < 0) {
424         ret = -errno;
425         if (ret == -EROFS) {
426             ret = -EACCES;
427         }
428         goto fail;
429     }
430     s->fd = fd;
431
432 #ifdef CONFIG_LINUX_AIO
433     if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
434         qemu_close(fd);
435         ret = -errno;
436         error_setg_errno(errp, -ret, "Could not set AIO state");
437         goto fail;
438     }
439 #endif
440
441     s->has_discard = true;
442     s->has_write_zeroes = true;
443
444     if (fstat(s->fd, &st) < 0) {
445         error_setg_errno(errp, errno, "Could not stat file");
446         goto fail;
447     }
448     if (S_ISREG(st.st_mode)) {
449         s->discard_zeroes = true;
450     }
451     if (S_ISBLK(st.st_mode)) {
452 #ifdef BLKDISCARDZEROES
453         unsigned int arg;
454         if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
455             s->discard_zeroes = true;
456         }
457 #endif
458 #ifdef __linux__
459         /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
460          * not rely on the contents of discarded blocks unless using O_DIRECT.
461          * Same for BLKZEROOUT.
462          */
463         if (!(bs->open_flags & BDRV_O_NOCACHE)) {
464             s->discard_zeroes = false;
465             s->has_write_zeroes = false;
466         }
467 #endif
468     }
469
470 #ifdef CONFIG_XFS
471     if (platform_test_xfs_fd(s->fd)) {
472         s->is_xfs = true;
473     }
474 #endif
475
476     raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
477
478     ret = 0;
479 fail:
480     if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
481         unlink(filename);
482     }
483     qemu_opts_del(opts);
484     return ret;
485 }
486
487 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
488                     Error **errp)
489 {
490     BDRVRawState *s = bs->opaque;
491     Error *local_err = NULL;
492     int ret;
493
494     s->type = FTYPE_FILE;
495     ret = raw_open_common(bs, options, flags, 0, &local_err);
496     if (local_err) {
497         error_propagate(errp, local_err);
498     }
499     return ret;
500 }
501
502 static int raw_reopen_prepare(BDRVReopenState *state,
503                               BlockReopenQueue *queue, Error **errp)
504 {
505     BDRVRawState *s;
506     BDRVRawReopenState *raw_s;
507     int ret = 0;
508
509     assert(state != NULL);
510     assert(state->bs != NULL);
511
512     s = state->bs->opaque;
513
514     state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
515     raw_s = state->opaque;
516
517 #ifdef CONFIG_LINUX_AIO
518     raw_s->use_aio = s->use_aio;
519
520     /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
521      * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
522      * won't override aio_ctx if aio_ctx is non-NULL */
523     if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
524         error_setg(errp, "Could not set AIO state");
525         return -1;
526     }
527 #endif
528
529     if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
530         raw_s->open_flags |= O_NONBLOCK;
531     }
532
533     raw_parse_flags(state->flags, &raw_s->open_flags);
534
535     raw_s->fd = -1;
536
537     int fcntl_flags = O_APPEND | O_NONBLOCK;
538 #ifdef O_NOATIME
539     fcntl_flags |= O_NOATIME;
540 #endif
541
542 #ifdef O_ASYNC
543     /* Not all operating systems have O_ASYNC, and those that don't
544      * will not let us track the state into raw_s->open_flags (typically
545      * you achieve the same effect with an ioctl, for example I_SETSIG
546      * on Solaris). But we do not use O_ASYNC, so that's fine.
547      */
548     assert((s->open_flags & O_ASYNC) == 0);
549 #endif
550
551     if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
552         /* dup the original fd */
553         /* TODO: use qemu fcntl wrapper */
554 #ifdef F_DUPFD_CLOEXEC
555         raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
556 #else
557         raw_s->fd = dup(s->fd);
558         if (raw_s->fd != -1) {
559             qemu_set_cloexec(raw_s->fd);
560         }
561 #endif
562         if (raw_s->fd >= 0) {
563             ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
564             if (ret) {
565                 qemu_close(raw_s->fd);
566                 raw_s->fd = -1;
567             }
568         }
569     }
570
571     /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
572     if (raw_s->fd == -1) {
573         assert(!(raw_s->open_flags & O_CREAT));
574         raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
575         if (raw_s->fd == -1) {
576             error_setg_errno(errp, errno, "Could not reopen file");
577             ret = -1;
578         }
579     }
580     return ret;
581 }
582
583 static void raw_reopen_commit(BDRVReopenState *state)
584 {
585     BDRVRawReopenState *raw_s = state->opaque;
586     BDRVRawState *s = state->bs->opaque;
587
588     s->open_flags = raw_s->open_flags;
589
590     qemu_close(s->fd);
591     s->fd = raw_s->fd;
592 #ifdef CONFIG_LINUX_AIO
593     s->use_aio = raw_s->use_aio;
594 #endif
595
596     g_free(state->opaque);
597     state->opaque = NULL;
598 }
599
600
601 static void raw_reopen_abort(BDRVReopenState *state)
602 {
603     BDRVRawReopenState *raw_s = state->opaque;
604
605      /* nothing to do if NULL, we didn't get far enough */
606     if (raw_s == NULL) {
607         return;
608     }
609
610     if (raw_s->fd >= 0) {
611         qemu_close(raw_s->fd);
612         raw_s->fd = -1;
613     }
614     g_free(state->opaque);
615     state->opaque = NULL;
616 }
617
618 static int raw_refresh_limits(BlockDriverState *bs)
619 {
620     BDRVRawState *s = bs->opaque;
621
622     raw_probe_alignment(bs);
623     bs->bl.opt_mem_alignment = s->buf_align;
624
625     return 0;
626 }
627
628 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
629 {
630     int ret;
631
632     ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
633     if (ret == -1) {
634         return -errno;
635     }
636
637     return 0;
638 }
639
640 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
641 {
642     int ret;
643
644     ret = qemu_fdatasync(aiocb->aio_fildes);
645     if (ret == -1) {
646         return -errno;
647     }
648     return 0;
649 }
650
651 #ifdef CONFIG_PREADV
652
653 static bool preadv_present = true;
654
655 static ssize_t
656 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
657 {
658     return preadv(fd, iov, nr_iov, offset);
659 }
660
661 static ssize_t
662 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
663 {
664     return pwritev(fd, iov, nr_iov, offset);
665 }
666
667 #else
668
669 static bool preadv_present = false;
670
671 static ssize_t
672 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
673 {
674     return -ENOSYS;
675 }
676
677 static ssize_t
678 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
679 {
680     return -ENOSYS;
681 }
682
683 #endif
684
685 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
686 {
687     ssize_t len;
688
689     do {
690         if (aiocb->aio_type & QEMU_AIO_WRITE)
691             len = qemu_pwritev(aiocb->aio_fildes,
692                                aiocb->aio_iov,
693                                aiocb->aio_niov,
694                                aiocb->aio_offset);
695          else
696             len = qemu_preadv(aiocb->aio_fildes,
697                               aiocb->aio_iov,
698                               aiocb->aio_niov,
699                               aiocb->aio_offset);
700     } while (len == -1 && errno == EINTR);
701
702     if (len == -1) {
703         return -errno;
704     }
705     return len;
706 }
707
708 /*
709  * Read/writes the data to/from a given linear buffer.
710  *
711  * Returns the number of bytes handles or -errno in case of an error. Short
712  * reads are only returned if the end of the file is reached.
713  */
714 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
715 {
716     ssize_t offset = 0;
717     ssize_t len;
718
719     while (offset < aiocb->aio_nbytes) {
720         if (aiocb->aio_type & QEMU_AIO_WRITE) {
721             len = pwrite(aiocb->aio_fildes,
722                          (const char *)buf + offset,
723                          aiocb->aio_nbytes - offset,
724                          aiocb->aio_offset + offset);
725         } else {
726             len = pread(aiocb->aio_fildes,
727                         buf + offset,
728                         aiocb->aio_nbytes - offset,
729                         aiocb->aio_offset + offset);
730         }
731         if (len == -1 && errno == EINTR) {
732             continue;
733         } else if (len == -1) {
734             offset = -errno;
735             break;
736         } else if (len == 0) {
737             break;
738         }
739         offset += len;
740     }
741
742     return offset;
743 }
744
745 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
746 {
747     ssize_t nbytes;
748     char *buf;
749
750     if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
751         /*
752          * If there is just a single buffer, and it is properly aligned
753          * we can just use plain pread/pwrite without any problems.
754          */
755         if (aiocb->aio_niov == 1) {
756              return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
757         }
758         /*
759          * We have more than one iovec, and all are properly aligned.
760          *
761          * Try preadv/pwritev first and fall back to linearizing the
762          * buffer if it's not supported.
763          */
764         if (preadv_present) {
765             nbytes = handle_aiocb_rw_vector(aiocb);
766             if (nbytes == aiocb->aio_nbytes ||
767                 (nbytes < 0 && nbytes != -ENOSYS)) {
768                 return nbytes;
769             }
770             preadv_present = false;
771         }
772
773         /*
774          * XXX(hch): short read/write.  no easy way to handle the reminder
775          * using these interfaces.  For now retry using plain
776          * pread/pwrite?
777          */
778     }
779
780     /*
781      * Ok, we have to do it the hard way, copy all segments into
782      * a single aligned buffer.
783      */
784     buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
785     if (aiocb->aio_type & QEMU_AIO_WRITE) {
786         char *p = buf;
787         int i;
788
789         for (i = 0; i < aiocb->aio_niov; ++i) {
790             memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
791             p += aiocb->aio_iov[i].iov_len;
792         }
793         assert(p - buf == aiocb->aio_nbytes);
794     }
795
796     nbytes = handle_aiocb_rw_linear(aiocb, buf);
797     if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
798         char *p = buf;
799         size_t count = aiocb->aio_nbytes, copy;
800         int i;
801
802         for (i = 0; i < aiocb->aio_niov && count; ++i) {
803             copy = count;
804             if (copy > aiocb->aio_iov[i].iov_len) {
805                 copy = aiocb->aio_iov[i].iov_len;
806             }
807             memcpy(aiocb->aio_iov[i].iov_base, p, copy);
808             assert(count >= copy);
809             p     += copy;
810             count -= copy;
811         }
812         assert(count == 0);
813     }
814     qemu_vfree(buf);
815
816     return nbytes;
817 }
818
819 #ifdef CONFIG_XFS
820 static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
821 {
822     struct xfs_flock64 fl;
823
824     memset(&fl, 0, sizeof(fl));
825     fl.l_whence = SEEK_SET;
826     fl.l_start = offset;
827     fl.l_len = bytes;
828
829     if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
830         DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno));
831         return -errno;
832     }
833
834     return 0;
835 }
836
837 static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
838 {
839     struct xfs_flock64 fl;
840
841     memset(&fl, 0, sizeof(fl));
842     fl.l_whence = SEEK_SET;
843     fl.l_start = offset;
844     fl.l_len = bytes;
845
846     if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
847         DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
848         return -errno;
849     }
850
851     return 0;
852 }
853 #endif
854
855 static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
856 {
857     int ret = -EOPNOTSUPP;
858     BDRVRawState *s = aiocb->bs->opaque;
859
860     if (s->has_write_zeroes == 0) {
861         return -ENOTSUP;
862     }
863
864     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
865 #ifdef BLKZEROOUT
866         do {
867             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
868             if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
869                 return 0;
870             }
871         } while (errno == EINTR);
872
873         ret = -errno;
874 #endif
875     } else {
876 #ifdef CONFIG_XFS
877         if (s->is_xfs) {
878             return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
879         }
880 #endif
881     }
882
883     if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
884         ret == -ENOTTY) {
885         s->has_write_zeroes = false;
886         ret = -ENOTSUP;
887     }
888     return ret;
889 }
890
891 static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
892 {
893     int ret = -EOPNOTSUPP;
894     BDRVRawState *s = aiocb->bs->opaque;
895
896     if (!s->has_discard) {
897         return -ENOTSUP;
898     }
899
900     if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
901 #ifdef BLKDISCARD
902         do {
903             uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
904             if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
905                 return 0;
906             }
907         } while (errno == EINTR);
908
909         ret = -errno;
910 #endif
911     } else {
912 #ifdef CONFIG_XFS
913         if (s->is_xfs) {
914             return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
915         }
916 #endif
917
918 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
919         do {
920             if (fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
921                           aiocb->aio_offset, aiocb->aio_nbytes) == 0) {
922                 return 0;
923             }
924         } while (errno == EINTR);
925
926         ret = -errno;
927 #endif
928     }
929
930     if (ret == -ENODEV || ret == -ENOSYS || ret == -EOPNOTSUPP ||
931         ret == -ENOTTY) {
932         s->has_discard = false;
933         ret = -ENOTSUP;
934     }
935     return ret;
936 }
937
938 static int aio_worker(void *arg)
939 {
940     RawPosixAIOData *aiocb = arg;
941     ssize_t ret = 0;
942
943     switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
944     case QEMU_AIO_READ:
945         ret = handle_aiocb_rw(aiocb);
946         if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
947             iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
948                       0, aiocb->aio_nbytes - ret);
949
950             ret = aiocb->aio_nbytes;
951         }
952         if (ret == aiocb->aio_nbytes) {
953             ret = 0;
954         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
955             ret = -EINVAL;
956         }
957         break;
958     case QEMU_AIO_WRITE:
959         ret = handle_aiocb_rw(aiocb);
960         if (ret == aiocb->aio_nbytes) {
961             ret = 0;
962         } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
963             ret = -EINVAL;
964         }
965         break;
966     case QEMU_AIO_FLUSH:
967         ret = handle_aiocb_flush(aiocb);
968         break;
969     case QEMU_AIO_IOCTL:
970         ret = handle_aiocb_ioctl(aiocb);
971         break;
972     case QEMU_AIO_DISCARD:
973         ret = handle_aiocb_discard(aiocb);
974         break;
975     case QEMU_AIO_WRITE_ZEROES:
976         ret = handle_aiocb_write_zeroes(aiocb);
977         break;
978     default:
979         fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
980         ret = -EINVAL;
981         break;
982     }
983
984     g_slice_free(RawPosixAIOData, aiocb);
985     return ret;
986 }
987
988 static int paio_submit_co(BlockDriverState *bs, int fd,
989         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
990         int type)
991 {
992     RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
993     ThreadPool *pool;
994
995     acb->bs = bs;
996     acb->aio_type = type;
997     acb->aio_fildes = fd;
998
999     acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1000     acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1001
1002     if (qiov) {
1003         acb->aio_iov = qiov->iov;
1004         acb->aio_niov = qiov->niov;
1005         assert(qiov->size == acb->aio_nbytes);
1006     }
1007
1008     trace_paio_submit_co(sector_num, nb_sectors, type);
1009     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1010     return thread_pool_submit_co(pool, aio_worker, acb);
1011 }
1012
1013 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
1014         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1015         BlockDriverCompletionFunc *cb, void *opaque, int type)
1016 {
1017     RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1018     ThreadPool *pool;
1019
1020     acb->bs = bs;
1021     acb->aio_type = type;
1022     acb->aio_fildes = fd;
1023
1024     acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1025     acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1026
1027     if (qiov) {
1028         acb->aio_iov = qiov->iov;
1029         acb->aio_niov = qiov->niov;
1030         assert(qiov->size == acb->aio_nbytes);
1031     }
1032
1033     trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1034     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1035     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1036 }
1037
1038 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
1039         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1040         BlockDriverCompletionFunc *cb, void *opaque, int type)
1041 {
1042     BDRVRawState *s = bs->opaque;
1043
1044     if (fd_open(bs) < 0)
1045         return NULL;
1046
1047     /*
1048      * If O_DIRECT is used the buffer needs to be aligned on a sector
1049      * boundary.  Check if this is the case or tell the low-level
1050      * driver that it needs to copy the buffer.
1051      */
1052     if ((bs->open_flags & BDRV_O_NOCACHE)) {
1053         if (!bdrv_qiov_is_aligned(bs, qiov)) {
1054             type |= QEMU_AIO_MISALIGNED;
1055 #ifdef CONFIG_LINUX_AIO
1056         } else if (s->use_aio) {
1057             return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1058                                nb_sectors, cb, opaque, type);
1059 #endif
1060         }
1061     }
1062
1063     return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1064                        cb, opaque, type);
1065 }
1066
1067 static void raw_aio_plug(BlockDriverState *bs)
1068 {
1069 #ifdef CONFIG_LINUX_AIO
1070     BDRVRawState *s = bs->opaque;
1071     if (s->use_aio) {
1072         laio_io_plug(bs, s->aio_ctx);
1073     }
1074 #endif
1075 }
1076
1077 static void raw_aio_unplug(BlockDriverState *bs)
1078 {
1079 #ifdef CONFIG_LINUX_AIO
1080     BDRVRawState *s = bs->opaque;
1081     if (s->use_aio) {
1082         laio_io_unplug(bs, s->aio_ctx, true);
1083     }
1084 #endif
1085 }
1086
1087 static void raw_aio_flush_io_queue(BlockDriverState *bs)
1088 {
1089 #ifdef CONFIG_LINUX_AIO
1090     BDRVRawState *s = bs->opaque;
1091     if (s->use_aio) {
1092         laio_io_unplug(bs, s->aio_ctx, false);
1093     }
1094 #endif
1095 }
1096
1097 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
1098         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1099         BlockDriverCompletionFunc *cb, void *opaque)
1100 {
1101     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1102                           cb, opaque, QEMU_AIO_READ);
1103 }
1104
1105 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
1106         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1107         BlockDriverCompletionFunc *cb, void *opaque)
1108 {
1109     return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1110                           cb, opaque, QEMU_AIO_WRITE);
1111 }
1112
1113 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
1114         BlockDriverCompletionFunc *cb, void *opaque)
1115 {
1116     BDRVRawState *s = bs->opaque;
1117
1118     if (fd_open(bs) < 0)
1119         return NULL;
1120
1121     return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1122 }
1123
1124 static void raw_close(BlockDriverState *bs)
1125 {
1126     BDRVRawState *s = bs->opaque;
1127
1128     raw_detach_aio_context(bs);
1129
1130 #ifdef CONFIG_LINUX_AIO
1131     if (s->use_aio) {
1132         laio_cleanup(s->aio_ctx);
1133     }
1134 #endif
1135     if (s->fd >= 0) {
1136         qemu_close(s->fd);
1137         s->fd = -1;
1138     }
1139 }
1140
1141 static int raw_truncate(BlockDriverState *bs, int64_t offset)
1142 {
1143     BDRVRawState *s = bs->opaque;
1144     struct stat st;
1145
1146     if (fstat(s->fd, &st)) {
1147         return -errno;
1148     }
1149
1150     if (S_ISREG(st.st_mode)) {
1151         if (ftruncate(s->fd, offset) < 0) {
1152             return -errno;
1153         }
1154     } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1155        if (offset > raw_getlength(bs)) {
1156            return -EINVAL;
1157        }
1158     } else {
1159         return -ENOTSUP;
1160     }
1161
1162     return 0;
1163 }
1164
1165 #ifdef __OpenBSD__
1166 static int64_t raw_getlength(BlockDriverState *bs)
1167 {
1168     BDRVRawState *s = bs->opaque;
1169     int fd = s->fd;
1170     struct stat st;
1171
1172     if (fstat(fd, &st))
1173         return -errno;
1174     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1175         struct disklabel dl;
1176
1177         if (ioctl(fd, DIOCGDINFO, &dl))
1178             return -errno;
1179         return (uint64_t)dl.d_secsize *
1180             dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1181     } else
1182         return st.st_size;
1183 }
1184 #elif defined(__NetBSD__)
1185 static int64_t raw_getlength(BlockDriverState *bs)
1186 {
1187     BDRVRawState *s = bs->opaque;
1188     int fd = s->fd;
1189     struct stat st;
1190
1191     if (fstat(fd, &st))
1192         return -errno;
1193     if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1194         struct dkwedge_info dkw;
1195
1196         if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1197             return dkw.dkw_size * 512;
1198         } else {
1199             struct disklabel dl;
1200
1201             if (ioctl(fd, DIOCGDINFO, &dl))
1202                 return -errno;
1203             return (uint64_t)dl.d_secsize *
1204                 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1205         }
1206     } else
1207         return st.st_size;
1208 }
1209 #elif defined(__sun__)
1210 static int64_t raw_getlength(BlockDriverState *bs)
1211 {
1212     BDRVRawState *s = bs->opaque;
1213     struct dk_minfo minfo;
1214     int ret;
1215     int64_t size;
1216
1217     ret = fd_open(bs);
1218     if (ret < 0) {
1219         return ret;
1220     }
1221
1222     /*
1223      * Use the DKIOCGMEDIAINFO ioctl to read the size.
1224      */
1225     ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1226     if (ret != -1) {
1227         return minfo.dki_lbsize * minfo.dki_capacity;
1228     }
1229
1230     /*
1231      * There are reports that lseek on some devices fails, but
1232      * irc discussion said that contingency on contingency was overkill.
1233      */
1234     size = lseek(s->fd, 0, SEEK_END);
1235     if (size < 0) {
1236         return -errno;
1237     }
1238     return size;
1239 }
1240 #elif defined(CONFIG_BSD)
1241 static int64_t raw_getlength(BlockDriverState *bs)
1242 {
1243     BDRVRawState *s = bs->opaque;
1244     int fd = s->fd;
1245     int64_t size;
1246     struct stat sb;
1247 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1248     int reopened = 0;
1249 #endif
1250     int ret;
1251
1252     ret = fd_open(bs);
1253     if (ret < 0)
1254         return ret;
1255
1256 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1257 again:
1258 #endif
1259     if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1260 #ifdef DIOCGMEDIASIZE
1261         if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1262 #elif defined(DIOCGPART)
1263         {
1264                 struct partinfo pi;
1265                 if (ioctl(fd, DIOCGPART, &pi) == 0)
1266                         size = pi.media_size;
1267                 else
1268                         size = 0;
1269         }
1270         if (size == 0)
1271 #endif
1272 #if defined(__APPLE__) && defined(__MACH__)
1273         size = LLONG_MAX;
1274 #else
1275         size = lseek(fd, 0LL, SEEK_END);
1276         if (size < 0) {
1277             return -errno;
1278         }
1279 #endif
1280 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1281         switch(s->type) {
1282         case FTYPE_CD:
1283             /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1284             if (size == 2048LL * (unsigned)-1)
1285                 size = 0;
1286             /* XXX no disc?  maybe we need to reopen... */
1287             if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1288                 reopened = 1;
1289                 goto again;
1290             }
1291         }
1292 #endif
1293     } else {
1294         size = lseek(fd, 0, SEEK_END);
1295         if (size < 0) {
1296             return -errno;
1297         }
1298     }
1299     return size;
1300 }
1301 #else
1302 static int64_t raw_getlength(BlockDriverState *bs)
1303 {
1304     BDRVRawState *s = bs->opaque;
1305     int ret;
1306     int64_t size;
1307
1308     ret = fd_open(bs);
1309     if (ret < 0) {
1310         return ret;
1311     }
1312
1313     size = lseek(s->fd, 0, SEEK_END);
1314     if (size < 0) {
1315         return -errno;
1316     }
1317     return size;
1318 }
1319 #endif
1320
1321 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1322 {
1323     struct stat st;
1324     BDRVRawState *s = bs->opaque;
1325
1326     if (fstat(s->fd, &st) < 0) {
1327         return -errno;
1328     }
1329     return (int64_t)st.st_blocks * 512;
1330 }
1331
1332 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1333 {
1334     int fd;
1335     int result = 0;
1336     int64_t total_size = 0;
1337     bool nocow = false;
1338
1339     strstart(filename, "file:", &filename);
1340
1341     /* Read out options */
1342     total_size =
1343         qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;
1344     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1345
1346     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1347                    0644);
1348     if (fd < 0) {
1349         result = -errno;
1350         error_setg_errno(errp, -result, "Could not create file");
1351     } else {
1352         if (nocow) {
1353 #ifdef __linux__
1354             /* Set NOCOW flag to solve performance issue on fs like btrfs.
1355              * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1356              * will be ignored since any failure of this operation should not
1357              * block the left work.
1358              */
1359             int attr;
1360             if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1361                 attr |= FS_NOCOW_FL;
1362                 ioctl(fd, FS_IOC_SETFLAGS, &attr);
1363             }
1364 #endif
1365         }
1366
1367         if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
1368             result = -errno;
1369             error_setg_errno(errp, -result, "Could not resize file");
1370         }
1371         if (qemu_close(fd) != 0) {
1372             result = -errno;
1373             error_setg_errno(errp, -result, "Could not close the new file");
1374         }
1375     }
1376     return result;
1377 }
1378
1379 static int64_t try_fiemap(BlockDriverState *bs, off_t start, off_t *data,
1380                           off_t *hole, int nb_sectors, int *pnum)
1381 {
1382 #ifdef CONFIG_FIEMAP
1383     BDRVRawState *s = bs->opaque;
1384     int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1385     struct {
1386         struct fiemap fm;
1387         struct fiemap_extent fe;
1388     } f;
1389
1390     if (s->skip_fiemap) {
1391         return -ENOTSUP;
1392     }
1393
1394     f.fm.fm_start = start;
1395     f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1396     f.fm.fm_flags = 0;
1397     f.fm.fm_extent_count = 1;
1398     f.fm.fm_reserved = 0;
1399     if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1400         s->skip_fiemap = true;
1401         return -errno;
1402     }
1403
1404     if (f.fm.fm_mapped_extents == 0) {
1405         /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1406          * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1407          */
1408         off_t length = lseek(s->fd, 0, SEEK_END);
1409         *hole = f.fm.fm_start;
1410         *data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1411     } else {
1412         *data = f.fe.fe_logical;
1413         *hole = f.fe.fe_logical + f.fe.fe_length;
1414         if (f.fe.fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
1415             ret |= BDRV_BLOCK_ZERO;
1416         }
1417     }
1418
1419     return ret;
1420 #else
1421     return -ENOTSUP;
1422 #endif
1423 }
1424
1425 static int64_t try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,
1426                              off_t *hole, int *pnum)
1427 {
1428 #if defined SEEK_HOLE && defined SEEK_DATA
1429     BDRVRawState *s = bs->opaque;
1430
1431     *hole = lseek(s->fd, start, SEEK_HOLE);
1432     if (*hole == -1) {
1433         /* -ENXIO indicates that sector_num was past the end of the file.
1434          * There is a virtual hole there.  */
1435         assert(errno != -ENXIO);
1436
1437         return -errno;
1438     }
1439
1440     if (*hole > start) {
1441         *data = start;
1442     } else {
1443         /* On a hole.  We need another syscall to find its end.  */
1444         *data = lseek(s->fd, start, SEEK_DATA);
1445         if (*data == -1) {
1446             *data = lseek(s->fd, 0, SEEK_END);
1447         }
1448     }
1449
1450     return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1451 #else
1452     return -ENOTSUP;
1453 #endif
1454 }
1455
1456 /*
1457  * Returns true iff the specified sector is present in the disk image. Drivers
1458  * not implementing the functionality are assumed to not support backing files,
1459  * hence all their sectors are reported as allocated.
1460  *
1461  * If 'sector_num' is beyond the end of the disk image the return value is 0
1462  * and 'pnum' is set to 0.
1463  *
1464  * 'pnum' is set to the number of sectors (including and immediately following
1465  * the specified sector) that are known to be in the same
1466  * allocated/unallocated state.
1467  *
1468  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
1469  * beyond the end of the disk image it will be clamped.
1470  */
1471 static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1472                                                     int64_t sector_num,
1473                                                     int nb_sectors, int *pnum)
1474 {
1475     off_t start, data = 0, hole = 0;
1476     int64_t ret;
1477
1478     ret = fd_open(bs);
1479     if (ret < 0) {
1480         return ret;
1481     }
1482
1483     start = sector_num * BDRV_SECTOR_SIZE;
1484
1485     ret = try_fiemap(bs, start, &data, &hole, nb_sectors, pnum);
1486     if (ret < 0) {
1487         ret = try_seek_hole(bs, start, &data, &hole, pnum);
1488         if (ret < 0) {
1489             /* Assume everything is allocated. */
1490             data = 0;
1491             hole = start + nb_sectors * BDRV_SECTOR_SIZE;
1492             ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
1493         }
1494     }
1495
1496     if (data <= start) {
1497         /* On a data extent, compute sectors to the end of the extent.  */
1498         *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1499     } else {
1500         /* On a hole, compute sectors to the beginning of the next extent.  */
1501         *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1502         ret &= ~BDRV_BLOCK_DATA;
1503         ret |= BDRV_BLOCK_ZERO;
1504     }
1505
1506     return ret;
1507 }
1508
1509 static coroutine_fn BlockDriverAIOCB *raw_aio_discard(BlockDriverState *bs,
1510     int64_t sector_num, int nb_sectors,
1511     BlockDriverCompletionFunc *cb, void *opaque)
1512 {
1513     BDRVRawState *s = bs->opaque;
1514
1515     return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1516                        cb, opaque, QEMU_AIO_DISCARD);
1517 }
1518
1519 static int coroutine_fn raw_co_write_zeroes(
1520     BlockDriverState *bs, int64_t sector_num,
1521     int nb_sectors, BdrvRequestFlags flags)
1522 {
1523     BDRVRawState *s = bs->opaque;
1524
1525     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1526         return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1527                               QEMU_AIO_WRITE_ZEROES);
1528     } else if (s->discard_zeroes) {
1529         return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1530                               QEMU_AIO_DISCARD);
1531     }
1532     return -ENOTSUP;
1533 }
1534
1535 static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1536 {
1537     BDRVRawState *s = bs->opaque;
1538
1539     bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1540     bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1541     return 0;
1542 }
1543
1544 static QemuOptsList raw_create_opts = {
1545     .name = "raw-create-opts",
1546     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1547     .desc = {
1548         {
1549             .name = BLOCK_OPT_SIZE,
1550             .type = QEMU_OPT_SIZE,
1551             .help = "Virtual disk size"
1552         },
1553         {
1554             .name = BLOCK_OPT_NOCOW,
1555             .type = QEMU_OPT_BOOL,
1556             .help = "Turn off copy-on-write (valid only on btrfs)"
1557         },
1558         { /* end of list */ }
1559     }
1560 };
1561
1562 static BlockDriver bdrv_file = {
1563     .format_name = "file",
1564     .protocol_name = "file",
1565     .instance_size = sizeof(BDRVRawState),
1566     .bdrv_needs_filename = true,
1567     .bdrv_probe = NULL, /* no probe for protocols */
1568     .bdrv_parse_filename = raw_parse_filename,
1569     .bdrv_file_open = raw_open,
1570     .bdrv_reopen_prepare = raw_reopen_prepare,
1571     .bdrv_reopen_commit = raw_reopen_commit,
1572     .bdrv_reopen_abort = raw_reopen_abort,
1573     .bdrv_close = raw_close,
1574     .bdrv_create = raw_create,
1575     .bdrv_has_zero_init = bdrv_has_zero_init_1,
1576     .bdrv_co_get_block_status = raw_co_get_block_status,
1577     .bdrv_co_write_zeroes = raw_co_write_zeroes,
1578
1579     .bdrv_aio_readv = raw_aio_readv,
1580     .bdrv_aio_writev = raw_aio_writev,
1581     .bdrv_aio_flush = raw_aio_flush,
1582     .bdrv_aio_discard = raw_aio_discard,
1583     .bdrv_refresh_limits = raw_refresh_limits,
1584     .bdrv_io_plug = raw_aio_plug,
1585     .bdrv_io_unplug = raw_aio_unplug,
1586     .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1587
1588     .bdrv_truncate = raw_truncate,
1589     .bdrv_getlength = raw_getlength,
1590     .bdrv_get_info = raw_get_info,
1591     .bdrv_get_allocated_file_size
1592                         = raw_get_allocated_file_size,
1593
1594     .bdrv_detach_aio_context = raw_detach_aio_context,
1595     .bdrv_attach_aio_context = raw_attach_aio_context,
1596
1597     .create_opts = &raw_create_opts,
1598 };
1599
1600 /***********************************************/
1601 /* host device */
1602
1603 #if defined(__APPLE__) && defined(__MACH__)
1604 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1605 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1606
1607 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1608 {
1609     kern_return_t       kernResult;
1610     mach_port_t     masterPort;
1611     CFMutableDictionaryRef  classesToMatch;
1612
1613     kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1614     if ( KERN_SUCCESS != kernResult ) {
1615         printf( "IOMasterPort returned %d\n", kernResult );
1616     }
1617
1618     classesToMatch = IOServiceMatching( kIOCDMediaClass );
1619     if ( classesToMatch == NULL ) {
1620         printf( "IOServiceMatching returned a NULL dictionary.\n" );
1621     } else {
1622     CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1623     }
1624     kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1625     if ( KERN_SUCCESS != kernResult )
1626     {
1627         printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1628     }
1629
1630     return kernResult;
1631 }
1632
1633 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1634 {
1635     io_object_t     nextMedia;
1636     kern_return_t   kernResult = KERN_FAILURE;
1637     *bsdPath = '\0';
1638     nextMedia = IOIteratorNext( mediaIterator );
1639     if ( nextMedia )
1640     {
1641         CFTypeRef   bsdPathAsCFString;
1642     bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1643         if ( bsdPathAsCFString ) {
1644             size_t devPathLength;
1645             strcpy( bsdPath, _PATH_DEV );
1646             strcat( bsdPath, "r" );
1647             devPathLength = strlen( bsdPath );
1648             if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1649                 kernResult = KERN_SUCCESS;
1650             }
1651             CFRelease( bsdPathAsCFString );
1652         }
1653         IOObjectRelease( nextMedia );
1654     }
1655
1656     return kernResult;
1657 }
1658
1659 #endif
1660
1661 static int hdev_probe_device(const char *filename)
1662 {
1663     struct stat st;
1664
1665     /* allow a dedicated CD-ROM driver to match with a higher priority */
1666     if (strstart(filename, "/dev/cdrom", NULL))
1667         return 50;
1668
1669     if (stat(filename, &st) >= 0 &&
1670             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1671         return 100;
1672     }
1673
1674     return 0;
1675 }
1676
1677 static int check_hdev_writable(BDRVRawState *s)
1678 {
1679 #if defined(BLKROGET)
1680     /* Linux block devices can be configured "read-only" using blockdev(8).
1681      * This is independent of device node permissions and therefore open(2)
1682      * with O_RDWR succeeds.  Actual writes fail with EPERM.
1683      *
1684      * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
1685      * check for read-only block devices so that Linux block devices behave
1686      * properly.
1687      */
1688     struct stat st;
1689     int readonly = 0;
1690
1691     if (fstat(s->fd, &st)) {
1692         return -errno;
1693     }
1694
1695     if (!S_ISBLK(st.st_mode)) {
1696         return 0;
1697     }
1698
1699     if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
1700         return -errno;
1701     }
1702
1703     if (readonly) {
1704         return -EACCES;
1705     }
1706 #endif /* defined(BLKROGET) */
1707     return 0;
1708 }
1709
1710 static void hdev_parse_filename(const char *filename, QDict *options,
1711                                 Error **errp)
1712 {
1713     /* The prefix is optional, just as for "file". */
1714     strstart(filename, "host_device:", &filename);
1715
1716     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
1717 }
1718
1719 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
1720                      Error **errp)
1721 {
1722     BDRVRawState *s = bs->opaque;
1723     Error *local_err = NULL;
1724     int ret;
1725     const char *filename = qdict_get_str(options, "filename");
1726
1727 #if defined(__APPLE__) && defined(__MACH__)
1728     if (strstart(filename, "/dev/cdrom", NULL)) {
1729         kern_return_t kernResult;
1730         io_iterator_t mediaIterator;
1731         char bsdPath[ MAXPATHLEN ];
1732         int fd;
1733
1734         kernResult = FindEjectableCDMedia( &mediaIterator );
1735         kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1736
1737         if ( bsdPath[ 0 ] != '\0' ) {
1738             strcat(bsdPath,"s0");
1739             /* some CDs don't have a partition 0 */
1740             fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1741             if (fd < 0) {
1742                 bsdPath[strlen(bsdPath)-1] = '1';
1743             } else {
1744                 qemu_close(fd);
1745             }
1746             filename = bsdPath;
1747             qdict_put(options, "filename", qstring_from_str(filename));
1748         }
1749
1750         if ( mediaIterator )
1751             IOObjectRelease( mediaIterator );
1752     }
1753 #endif
1754
1755     s->type = FTYPE_FILE;
1756 #if defined(__linux__)
1757     {
1758         char resolved_path[ MAXPATHLEN ], *temp;
1759
1760         temp = realpath(filename, resolved_path);
1761         if (temp && strstart(temp, "/dev/sg", NULL)) {
1762             bs->sg = 1;
1763         }
1764     }
1765 #endif
1766
1767     ret = raw_open_common(bs, options, flags, 0, &local_err);
1768     if (ret < 0) {
1769         if (local_err) {
1770             error_propagate(errp, local_err);
1771         }
1772         return ret;
1773     }
1774
1775     if (flags & BDRV_O_RDWR) {
1776         ret = check_hdev_writable(s);
1777         if (ret < 0) {
1778             raw_close(bs);
1779             error_setg_errno(errp, -ret, "The device is not writable");
1780             return ret;
1781         }
1782     }
1783
1784     return ret;
1785 }
1786
1787 #if defined(__linux__)
1788 /* Note: we do not have a reliable method to detect if the floppy is
1789    present. The current method is to try to open the floppy at every
1790    I/O and to keep it opened during a few hundreds of ms. */
1791 static int fd_open(BlockDriverState *bs)
1792 {
1793     BDRVRawState *s = bs->opaque;
1794     int last_media_present;
1795
1796     if (s->type != FTYPE_FD)
1797         return 0;
1798     last_media_present = (s->fd >= 0);
1799     if (s->fd >= 0 &&
1800         (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1801         qemu_close(s->fd);
1802         s->fd = -1;
1803 #ifdef DEBUG_FLOPPY
1804         printf("Floppy closed\n");
1805 #endif
1806     }
1807     if (s->fd < 0) {
1808         if (s->fd_got_error &&
1809             (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1810 #ifdef DEBUG_FLOPPY
1811             printf("No floppy (open delayed)\n");
1812 #endif
1813             return -EIO;
1814         }
1815         s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1816         if (s->fd < 0) {
1817             s->fd_error_time = get_clock();
1818             s->fd_got_error = 1;
1819             if (last_media_present)
1820                 s->fd_media_changed = 1;
1821 #ifdef DEBUG_FLOPPY
1822             printf("No floppy\n");
1823 #endif
1824             return -EIO;
1825         }
1826 #ifdef DEBUG_FLOPPY
1827         printf("Floppy opened\n");
1828 #endif
1829     }
1830     if (!last_media_present)
1831         s->fd_media_changed = 1;
1832     s->fd_open_time = get_clock();
1833     s->fd_got_error = 0;
1834     return 0;
1835 }
1836
1837 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1838 {
1839     BDRVRawState *s = bs->opaque;
1840
1841     return ioctl(s->fd, req, buf);
1842 }
1843
1844 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1845         unsigned long int req, void *buf,
1846         BlockDriverCompletionFunc *cb, void *opaque)
1847 {
1848     BDRVRawState *s = bs->opaque;
1849     RawPosixAIOData *acb;
1850     ThreadPool *pool;
1851
1852     if (fd_open(bs) < 0)
1853         return NULL;
1854
1855     acb = g_slice_new(RawPosixAIOData);
1856     acb->bs = bs;
1857     acb->aio_type = QEMU_AIO_IOCTL;
1858     acb->aio_fildes = s->fd;
1859     acb->aio_offset = 0;
1860     acb->aio_ioctl_buf = buf;
1861     acb->aio_ioctl_cmd = req;
1862     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1863     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1864 }
1865
1866 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1867 static int fd_open(BlockDriverState *bs)
1868 {
1869     BDRVRawState *s = bs->opaque;
1870
1871     /* this is just to ensure s->fd is sane (its called by io ops) */
1872     if (s->fd >= 0)
1873         return 0;
1874     return -EIO;
1875 }
1876 #else /* !linux && !FreeBSD */
1877
1878 static int fd_open(BlockDriverState *bs)
1879 {
1880     return 0;
1881 }
1882
1883 #endif /* !linux && !FreeBSD */
1884
1885 static coroutine_fn BlockDriverAIOCB *hdev_aio_discard(BlockDriverState *bs,
1886     int64_t sector_num, int nb_sectors,
1887     BlockDriverCompletionFunc *cb, void *opaque)
1888 {
1889     BDRVRawState *s = bs->opaque;
1890
1891     if (fd_open(bs) < 0) {
1892         return NULL;
1893     }
1894     return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1895                        cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1896 }
1897
1898 static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
1899     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1900 {
1901     BDRVRawState *s = bs->opaque;
1902     int rc;
1903
1904     rc = fd_open(bs);
1905     if (rc < 0) {
1906         return rc;
1907     }
1908     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1909         return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1910                               QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
1911     } else if (s->discard_zeroes) {
1912         return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1913                               QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
1914     }
1915     return -ENOTSUP;
1916 }
1917
1918 static int hdev_create(const char *filename, QemuOpts *opts,
1919                        Error **errp)
1920 {
1921     int fd;
1922     int ret = 0;
1923     struct stat stat_buf;
1924     int64_t total_size = 0;
1925     bool has_prefix;
1926
1927     /* This function is used by all three protocol block drivers and therefore
1928      * any of these three prefixes may be given.
1929      * The return value has to be stored somewhere, otherwise this is an error
1930      * due to -Werror=unused-value. */
1931     has_prefix =
1932         strstart(filename, "host_device:", &filename) ||
1933         strstart(filename, "host_cdrom:" , &filename) ||
1934         strstart(filename, "host_floppy:", &filename);
1935
1936     (void)has_prefix;
1937
1938     /* Read out options */
1939     total_size =
1940         qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;
1941
1942     fd = qemu_open(filename, O_WRONLY | O_BINARY);
1943     if (fd < 0) {
1944         ret = -errno;
1945         error_setg_errno(errp, -ret, "Could not open device");
1946         return ret;
1947     }
1948
1949     if (fstat(fd, &stat_buf) < 0) {
1950         ret = -errno;
1951         error_setg_errno(errp, -ret, "Could not stat device");
1952     } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
1953         error_setg(errp,
1954                    "The given file is neither a block nor a character device");
1955         ret = -ENODEV;
1956     } else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE) {
1957         error_setg(errp, "Device is too small");
1958         ret = -ENOSPC;
1959     }
1960
1961     qemu_close(fd);
1962     return ret;
1963 }
1964
1965 static BlockDriver bdrv_host_device = {
1966     .format_name        = "host_device",
1967     .protocol_name        = "host_device",
1968     .instance_size      = sizeof(BDRVRawState),
1969     .bdrv_needs_filename = true,
1970     .bdrv_probe_device  = hdev_probe_device,
1971     .bdrv_parse_filename = hdev_parse_filename,
1972     .bdrv_file_open     = hdev_open,
1973     .bdrv_close         = raw_close,
1974     .bdrv_reopen_prepare = raw_reopen_prepare,
1975     .bdrv_reopen_commit  = raw_reopen_commit,
1976     .bdrv_reopen_abort   = raw_reopen_abort,
1977     .bdrv_create         = hdev_create,
1978     .create_opts         = &raw_create_opts,
1979     .bdrv_co_write_zeroes = hdev_co_write_zeroes,
1980
1981     .bdrv_aio_readv     = raw_aio_readv,
1982     .bdrv_aio_writev    = raw_aio_writev,
1983     .bdrv_aio_flush     = raw_aio_flush,
1984     .bdrv_aio_discard   = hdev_aio_discard,
1985     .bdrv_refresh_limits = raw_refresh_limits,
1986     .bdrv_io_plug = raw_aio_plug,
1987     .bdrv_io_unplug = raw_aio_unplug,
1988     .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1989
1990     .bdrv_truncate      = raw_truncate,
1991     .bdrv_getlength     = raw_getlength,
1992     .bdrv_get_info = raw_get_info,
1993     .bdrv_get_allocated_file_size
1994                         = raw_get_allocated_file_size,
1995
1996     .bdrv_detach_aio_context = raw_detach_aio_context,
1997     .bdrv_attach_aio_context = raw_attach_aio_context,
1998
1999     /* generic scsi device */
2000 #ifdef __linux__
2001     .bdrv_ioctl         = hdev_ioctl,
2002     .bdrv_aio_ioctl     = hdev_aio_ioctl,
2003 #endif
2004 };
2005
2006 #ifdef __linux__
2007 static void floppy_parse_filename(const char *filename, QDict *options,
2008                                   Error **errp)
2009 {
2010     /* The prefix is optional, just as for "file". */
2011     strstart(filename, "host_floppy:", &filename);
2012
2013     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2014 }
2015
2016 static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2017                        Error **errp)
2018 {
2019     BDRVRawState *s = bs->opaque;
2020     Error *local_err = NULL;
2021     int ret;
2022
2023     s->type = FTYPE_FD;
2024
2025     /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2026     ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2027     if (ret) {
2028         if (local_err) {
2029             error_propagate(errp, local_err);
2030         }
2031         return ret;
2032     }
2033
2034     /* close fd so that we can reopen it as needed */
2035     qemu_close(s->fd);
2036     s->fd = -1;
2037     s->fd_media_changed = 1;
2038
2039     return 0;
2040 }
2041
2042 static int floppy_probe_device(const char *filename)
2043 {
2044     int fd, ret;
2045     int prio = 0;
2046     struct floppy_struct fdparam;
2047     struct stat st;
2048
2049     if (strstart(filename, "/dev/fd", NULL) &&
2050         !strstart(filename, "/dev/fdset/", NULL)) {
2051         prio = 50;
2052     }
2053
2054     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2055     if (fd < 0) {
2056         goto out;
2057     }
2058     ret = fstat(fd, &st);
2059     if (ret == -1 || !S_ISBLK(st.st_mode)) {
2060         goto outc;
2061     }
2062
2063     /* Attempt to detect via a floppy specific ioctl */
2064     ret = ioctl(fd, FDGETPRM, &fdparam);
2065     if (ret >= 0)
2066         prio = 100;
2067
2068 outc:
2069     qemu_close(fd);
2070 out:
2071     return prio;
2072 }
2073
2074
2075 static int floppy_is_inserted(BlockDriverState *bs)
2076 {
2077     return fd_open(bs) >= 0;
2078 }
2079
2080 static int floppy_media_changed(BlockDriverState *bs)
2081 {
2082     BDRVRawState *s = bs->opaque;
2083     int ret;
2084
2085     /*
2086      * XXX: we do not have a true media changed indication.
2087      * It does not work if the floppy is changed without trying to read it.
2088      */
2089     fd_open(bs);
2090     ret = s->fd_media_changed;
2091     s->fd_media_changed = 0;
2092 #ifdef DEBUG_FLOPPY
2093     printf("Floppy changed=%d\n", ret);
2094 #endif
2095     return ret;
2096 }
2097
2098 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
2099 {
2100     BDRVRawState *s = bs->opaque;
2101     int fd;
2102
2103     if (s->fd >= 0) {
2104         qemu_close(s->fd);
2105         s->fd = -1;
2106     }
2107     fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
2108     if (fd >= 0) {
2109         if (ioctl(fd, FDEJECT, 0) < 0)
2110             perror("FDEJECT");
2111         qemu_close(fd);
2112     }
2113 }
2114
2115 static BlockDriver bdrv_host_floppy = {
2116     .format_name        = "host_floppy",
2117     .protocol_name      = "host_floppy",
2118     .instance_size      = sizeof(BDRVRawState),
2119     .bdrv_needs_filename = true,
2120     .bdrv_probe_device  = floppy_probe_device,
2121     .bdrv_parse_filename = floppy_parse_filename,
2122     .bdrv_file_open     = floppy_open,
2123     .bdrv_close         = raw_close,
2124     .bdrv_reopen_prepare = raw_reopen_prepare,
2125     .bdrv_reopen_commit  = raw_reopen_commit,
2126     .bdrv_reopen_abort   = raw_reopen_abort,
2127     .bdrv_create         = hdev_create,
2128     .create_opts         = &raw_create_opts,
2129
2130     .bdrv_aio_readv     = raw_aio_readv,
2131     .bdrv_aio_writev    = raw_aio_writev,
2132     .bdrv_aio_flush     = raw_aio_flush,
2133     .bdrv_refresh_limits = raw_refresh_limits,
2134     .bdrv_io_plug = raw_aio_plug,
2135     .bdrv_io_unplug = raw_aio_unplug,
2136     .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2137
2138     .bdrv_truncate      = raw_truncate,
2139     .bdrv_getlength      = raw_getlength,
2140     .has_variable_length = true,
2141     .bdrv_get_allocated_file_size
2142                         = raw_get_allocated_file_size,
2143
2144     .bdrv_detach_aio_context = raw_detach_aio_context,
2145     .bdrv_attach_aio_context = raw_attach_aio_context,
2146
2147     /* removable device support */
2148     .bdrv_is_inserted   = floppy_is_inserted,
2149     .bdrv_media_changed = floppy_media_changed,
2150     .bdrv_eject         = floppy_eject,
2151 };
2152 #endif
2153
2154 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2155 static void cdrom_parse_filename(const char *filename, QDict *options,
2156                                  Error **errp)
2157 {
2158     /* The prefix is optional, just as for "file". */
2159     strstart(filename, "host_cdrom:", &filename);
2160
2161     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2162 }
2163 #endif
2164
2165 #ifdef __linux__
2166 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2167                       Error **errp)
2168 {
2169     BDRVRawState *s = bs->opaque;
2170     Error *local_err = NULL;
2171     int ret;
2172
2173     s->type = FTYPE_CD;
2174
2175     /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2176     ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2177     if (local_err) {
2178         error_propagate(errp, local_err);
2179     }
2180     return ret;
2181 }
2182
2183 static int cdrom_probe_device(const char *filename)
2184 {
2185     int fd, ret;
2186     int prio = 0;
2187     struct stat st;
2188
2189     fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2190     if (fd < 0) {
2191         goto out;
2192     }
2193     ret = fstat(fd, &st);
2194     if (ret == -1 || !S_ISBLK(st.st_mode)) {
2195         goto outc;
2196     }
2197
2198     /* Attempt to detect via a CDROM specific ioctl */
2199     ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2200     if (ret >= 0)
2201         prio = 100;
2202
2203 outc:
2204     qemu_close(fd);
2205 out:
2206     return prio;
2207 }
2208
2209 static int cdrom_is_inserted(BlockDriverState *bs)
2210 {
2211     BDRVRawState *s = bs->opaque;
2212     int ret;
2213
2214     ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2215     if (ret == CDS_DISC_OK)
2216         return 1;
2217     return 0;
2218 }
2219
2220 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2221 {
2222     BDRVRawState *s = bs->opaque;
2223
2224     if (eject_flag) {
2225         if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2226             perror("CDROMEJECT");
2227     } else {
2228         if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2229             perror("CDROMEJECT");
2230     }
2231 }
2232
2233 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2234 {
2235     BDRVRawState *s = bs->opaque;
2236
2237     if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2238         /*
2239          * Note: an error can happen if the distribution automatically
2240          * mounts the CD-ROM
2241          */
2242         /* perror("CDROM_LOCKDOOR"); */
2243     }
2244 }
2245
2246 static BlockDriver bdrv_host_cdrom = {
2247     .format_name        = "host_cdrom",
2248     .protocol_name      = "host_cdrom",
2249     .instance_size      = sizeof(BDRVRawState),
2250     .bdrv_needs_filename = true,
2251     .bdrv_probe_device  = cdrom_probe_device,
2252     .bdrv_parse_filename = cdrom_parse_filename,
2253     .bdrv_file_open     = cdrom_open,
2254     .bdrv_close         = raw_close,
2255     .bdrv_reopen_prepare = raw_reopen_prepare,
2256     .bdrv_reopen_commit  = raw_reopen_commit,
2257     .bdrv_reopen_abort   = raw_reopen_abort,
2258     .bdrv_create         = hdev_create,
2259     .create_opts         = &raw_create_opts,
2260
2261     .bdrv_aio_readv     = raw_aio_readv,
2262     .bdrv_aio_writev    = raw_aio_writev,
2263     .bdrv_aio_flush     = raw_aio_flush,
2264     .bdrv_refresh_limits = raw_refresh_limits,
2265     .bdrv_io_plug = raw_aio_plug,
2266     .bdrv_io_unplug = raw_aio_unplug,
2267     .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2268
2269     .bdrv_truncate      = raw_truncate,
2270     .bdrv_getlength      = raw_getlength,
2271     .has_variable_length = true,
2272     .bdrv_get_allocated_file_size
2273                         = raw_get_allocated_file_size,
2274
2275     .bdrv_detach_aio_context = raw_detach_aio_context,
2276     .bdrv_attach_aio_context = raw_attach_aio_context,
2277
2278     /* removable device support */
2279     .bdrv_is_inserted   = cdrom_is_inserted,
2280     .bdrv_eject         = cdrom_eject,
2281     .bdrv_lock_medium   = cdrom_lock_medium,
2282
2283     /* generic scsi device */
2284     .bdrv_ioctl         = hdev_ioctl,
2285     .bdrv_aio_ioctl     = hdev_aio_ioctl,
2286 };
2287 #endif /* __linux__ */
2288
2289 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2290 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2291                       Error **errp)
2292 {
2293     BDRVRawState *s = bs->opaque;
2294     Error *local_err = NULL;
2295     int ret;
2296
2297     s->type = FTYPE_CD;
2298
2299     ret = raw_open_common(bs, options, flags, 0, &local_err);
2300     if (ret) {
2301         if (local_err) {
2302             error_propagate(errp, local_err);
2303         }
2304         return ret;
2305     }
2306
2307     /* make sure the door isn't locked at this time */
2308     ioctl(s->fd, CDIOCALLOW);
2309     return 0;
2310 }
2311
2312 static int cdrom_probe_device(const char *filename)
2313 {
2314     if (strstart(filename, "/dev/cd", NULL) ||
2315             strstart(filename, "/dev/acd", NULL))
2316         return 100;
2317     return 0;
2318 }
2319
2320 static int cdrom_reopen(BlockDriverState *bs)
2321 {
2322     BDRVRawState *s = bs->opaque;
2323     int fd;
2324
2325     /*
2326      * Force reread of possibly changed/newly loaded disc,
2327      * FreeBSD seems to not notice sometimes...
2328      */
2329     if (s->fd >= 0)
2330         qemu_close(s->fd);
2331     fd = qemu_open(bs->filename, s->open_flags, 0644);
2332     if (fd < 0) {
2333         s->fd = -1;
2334         return -EIO;
2335     }
2336     s->fd = fd;
2337
2338     /* make sure the door isn't locked at this time */
2339     ioctl(s->fd, CDIOCALLOW);
2340     return 0;
2341 }
2342
2343 static int cdrom_is_inserted(BlockDriverState *bs)
2344 {
2345     return raw_getlength(bs) > 0;
2346 }
2347
2348 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2349 {
2350     BDRVRawState *s = bs->opaque;
2351
2352     if (s->fd < 0)
2353         return;
2354
2355     (void) ioctl(s->fd, CDIOCALLOW);
2356
2357     if (eject_flag) {
2358         if (ioctl(s->fd, CDIOCEJECT) < 0)
2359             perror("CDIOCEJECT");
2360     } else {
2361         if (ioctl(s->fd, CDIOCCLOSE) < 0)
2362             perror("CDIOCCLOSE");
2363     }
2364
2365     cdrom_reopen(bs);
2366 }
2367
2368 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2369 {
2370     BDRVRawState *s = bs->opaque;
2371
2372     if (s->fd < 0)
2373         return;
2374     if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2375         /*
2376          * Note: an error can happen if the distribution automatically
2377          * mounts the CD-ROM
2378          */
2379         /* perror("CDROM_LOCKDOOR"); */
2380     }
2381 }
2382
2383 static BlockDriver bdrv_host_cdrom = {
2384     .format_name        = "host_cdrom",
2385     .protocol_name      = "host_cdrom",
2386     .instance_size      = sizeof(BDRVRawState),
2387     .bdrv_needs_filename = true,
2388     .bdrv_probe_device  = cdrom_probe_device,
2389     .bdrv_parse_filename = cdrom_parse_filename,
2390     .bdrv_file_open     = cdrom_open,
2391     .bdrv_close         = raw_close,
2392     .bdrv_reopen_prepare = raw_reopen_prepare,
2393     .bdrv_reopen_commit  = raw_reopen_commit,
2394     .bdrv_reopen_abort   = raw_reopen_abort,
2395     .bdrv_create        = hdev_create,
2396     .create_opts        = &raw_create_opts,
2397
2398     .bdrv_aio_readv     = raw_aio_readv,
2399     .bdrv_aio_writev    = raw_aio_writev,
2400     .bdrv_aio_flush     = raw_aio_flush,
2401     .bdrv_refresh_limits = raw_refresh_limits,
2402     .bdrv_io_plug = raw_aio_plug,
2403     .bdrv_io_unplug = raw_aio_unplug,
2404     .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2405
2406     .bdrv_truncate      = raw_truncate,
2407     .bdrv_getlength      = raw_getlength,
2408     .has_variable_length = true,
2409     .bdrv_get_allocated_file_size
2410                         = raw_get_allocated_file_size,
2411
2412     .bdrv_detach_aio_context = raw_detach_aio_context,
2413     .bdrv_attach_aio_context = raw_attach_aio_context,
2414
2415     /* removable device support */
2416     .bdrv_is_inserted   = cdrom_is_inserted,
2417     .bdrv_eject         = cdrom_eject,
2418     .bdrv_lock_medium   = cdrom_lock_medium,
2419 };
2420 #endif /* __FreeBSD__ */
2421
2422 static void bdrv_file_init(void)
2423 {
2424     /*
2425      * Register all the drivers.  Note that order is important, the driver
2426      * registered last will get probed first.
2427      */
2428     bdrv_register(&bdrv_file);
2429     bdrv_register(&bdrv_host_device);
2430 #ifdef __linux__
2431     bdrv_register(&bdrv_host_floppy);
2432     bdrv_register(&bdrv_host_cdrom);
2433 #endif
2434 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2435     bdrv_register(&bdrv_host_cdrom);
2436 #endif
2437 }
2438
2439 block_init(bdrv_file_init);
This page took 0.154729 seconds and 4 git commands to generate.