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