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