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