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