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