block: implement is_allocated for raw
[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-char.h"
27 #include "qemu-log.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "block/raw-posix-aio.h"
31
32 #if defined(__APPLE__) && (__MACH__)
33 #include <paths.h>
34 #include <sys/param.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOBSD.h>
37 #include <IOKit/storage/IOMediaBSDClient.h>
38 #include <IOKit/storage/IOMedia.h>
39 #include <IOKit/storage/IOCDMedia.h>
40 //#include <IOKit/storage/IOCDTypes.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #endif
43
44 #ifdef __sun__
45 #define _POSIX_PTHREAD_SEMANTICS 1
46 #include <sys/dkio.h>
47 #endif
48 #ifdef __linux__
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <linux/cdrom.h>
54 #include <linux/fd.h>
55 #include <linux/fs.h>
56 #endif
57 #ifdef CONFIG_FIEMAP
58 #include <linux/fiemap.h>
59 #endif
60 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
61 #include <sys/disk.h>
62 #include <sys/cdio.h>
63 #endif
64
65 #ifdef __OpenBSD__
66 #include <sys/ioctl.h>
67 #include <sys/disklabel.h>
68 #include <sys/dkio.h>
69 #endif
70
71 #ifdef __NetBSD__
72 #include <sys/ioctl.h>
73 #include <sys/disklabel.h>
74 #include <sys/dkio.h>
75 #include <sys/disk.h>
76 #endif
77
78 #ifdef __DragonFly__
79 #include <sys/ioctl.h>
80 #include <sys/diskslice.h>
81 #endif
82
83 #ifdef CONFIG_XFS
84 #include <xfs/xfs.h>
85 #endif
86
87 //#define DEBUG_FLOPPY
88
89 //#define DEBUG_BLOCK
90 #if defined(DEBUG_BLOCK)
91 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
92 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
93 #else
94 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
95 #endif
96
97 /* OS X does not have O_DSYNC */
98 #ifndef O_DSYNC
99 #ifdef O_SYNC
100 #define O_DSYNC O_SYNC
101 #elif defined(O_FSYNC)
102 #define O_DSYNC O_FSYNC
103 #endif
104 #endif
105
106 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
107 #ifndef O_DIRECT
108 #define O_DIRECT O_DSYNC
109 #endif
110
111 #define FTYPE_FILE 0
112 #define FTYPE_CD 1
113 #define FTYPE_FD 2
114
115 /* if the FD is not accessed during that time (in ns), we try to
116 reopen it to see if the disk has been changed */
117 #define FD_OPEN_TIMEOUT (1000000000)
118
119 #define MAX_BLOCKSIZE 4096
120
121 typedef struct BDRVRawState {
122 int fd;
123 int type;
124 int open_flags;
125 #if defined(__linux__)
126 /* linux floppy specific */
127 int64_t fd_open_time;
128 int64_t fd_error_time;
129 int fd_got_error;
130 int fd_media_changed;
131 #endif
132 #ifdef CONFIG_LINUX_AIO
133 int use_aio;
134 void *aio_ctx;
135 #endif
136 uint8_t *aligned_buf;
137 unsigned aligned_buf_size;
138 #ifdef CONFIG_XFS
139 bool is_xfs : 1;
140 #endif
141 } BDRVRawState;
142
143 static int fd_open(BlockDriverState *bs);
144 static int64_t raw_getlength(BlockDriverState *bs);
145
146 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
147 static int cdrom_reopen(BlockDriverState *bs);
148 #endif
149
150 #if defined(__NetBSD__)
151 static int raw_normalize_devicepath(const char **filename)
152 {
153 static char namebuf[PATH_MAX];
154 const char *dp, *fname;
155 struct stat sb;
156
157 fname = *filename;
158 dp = strrchr(fname, '/');
159 if (lstat(fname, &sb) < 0) {
160 fprintf(stderr, "%s: stat failed: %s\n",
161 fname, strerror(errno));
162 return -errno;
163 }
164
165 if (!S_ISBLK(sb.st_mode)) {
166 return 0;
167 }
168
169 if (dp == NULL) {
170 snprintf(namebuf, PATH_MAX, "r%s", fname);
171 } else {
172 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
173 (int)(dp - fname), fname, dp + 1);
174 }
175 fprintf(stderr, "%s is a block device", fname);
176 *filename = namebuf;
177 fprintf(stderr, ", using %s\n", *filename);
178
179 return 0;
180 }
181 #else
182 static int raw_normalize_devicepath(const char **filename)
183 {
184 return 0;
185 }
186 #endif
187
188 static int raw_open_common(BlockDriverState *bs, const char *filename,
189 int bdrv_flags, int open_flags)
190 {
191 BDRVRawState *s = bs->opaque;
192 int fd, ret;
193
194 ret = raw_normalize_devicepath(&filename);
195 if (ret != 0) {
196 return ret;
197 }
198
199 s->open_flags = open_flags | O_BINARY;
200 s->open_flags &= ~O_ACCMODE;
201 if (bdrv_flags & BDRV_O_RDWR) {
202 s->open_flags |= O_RDWR;
203 } else {
204 s->open_flags |= O_RDONLY;
205 }
206
207 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
208 * and O_DIRECT for no caching. */
209 if ((bdrv_flags & BDRV_O_NOCACHE))
210 s->open_flags |= O_DIRECT;
211 if (!(bdrv_flags & BDRV_O_CACHE_WB))
212 s->open_flags |= O_DSYNC;
213
214 s->fd = -1;
215 fd = qemu_open(filename, s->open_flags, 0644);
216 if (fd < 0) {
217 ret = -errno;
218 if (ret == -EROFS)
219 ret = -EACCES;
220 return ret;
221 }
222 s->fd = fd;
223 s->aligned_buf = NULL;
224
225 if ((bdrv_flags & BDRV_O_NOCACHE)) {
226 /*
227 * Allocate a buffer for read/modify/write cycles. Chose the size
228 * pessimistically as we don't know the block size yet.
229 */
230 s->aligned_buf_size = 32 * MAX_BLOCKSIZE;
231 s->aligned_buf = qemu_memalign(MAX_BLOCKSIZE, s->aligned_buf_size);
232 if (s->aligned_buf == NULL) {
233 goto out_close;
234 }
235 }
236
237 /* We're falling back to POSIX AIO in some cases so init always */
238 if (paio_init() < 0) {
239 goto out_free_buf;
240 }
241
242 #ifdef CONFIG_LINUX_AIO
243 /*
244 * Currently Linux do AIO only for files opened with O_DIRECT
245 * specified so check NOCACHE flag too
246 */
247 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
248 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
249
250 s->aio_ctx = laio_init();
251 if (!s->aio_ctx) {
252 goto out_free_buf;
253 }
254 s->use_aio = 1;
255 } else
256 #endif
257 {
258 #ifdef CONFIG_LINUX_AIO
259 s->use_aio = 0;
260 #endif
261 }
262
263 #ifdef CONFIG_XFS
264 if (platform_test_xfs_fd(s->fd)) {
265 s->is_xfs = 1;
266 }
267 #endif
268
269 return 0;
270
271 out_free_buf:
272 qemu_vfree(s->aligned_buf);
273 out_close:
274 close(fd);
275 return -errno;
276 }
277
278 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
279 {
280 BDRVRawState *s = bs->opaque;
281
282 s->type = FTYPE_FILE;
283 return raw_open_common(bs, filename, flags, 0);
284 }
285
286 /* XXX: use host sector size if necessary with:
287 #ifdef DIOCGSECTORSIZE
288 {
289 unsigned int sectorsize = 512;
290 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
291 sectorsize > bufsize)
292 bufsize = sectorsize;
293 }
294 #endif
295 #ifdef CONFIG_COCOA
296 uint32_t blockSize = 512;
297 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
298 bufsize = blockSize;
299 }
300 #endif
301 */
302
303 /*
304 * Check if all memory in this vector is sector aligned.
305 */
306 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
307 {
308 int i;
309
310 for (i = 0; i < qiov->niov; i++) {
311 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
312 return 0;
313 }
314 }
315
316 return 1;
317 }
318
319 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
320 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
321 BlockDriverCompletionFunc *cb, void *opaque, int type)
322 {
323 BDRVRawState *s = bs->opaque;
324
325 if (fd_open(bs) < 0)
326 return NULL;
327
328 /*
329 * If O_DIRECT is used the buffer needs to be aligned on a sector
330 * boundary. Check if this is the case or tell the low-level
331 * driver that it needs to copy the buffer.
332 */
333 if (s->aligned_buf) {
334 if (!qiov_is_aligned(bs, qiov)) {
335 type |= QEMU_AIO_MISALIGNED;
336 #ifdef CONFIG_LINUX_AIO
337 } else if (s->use_aio) {
338 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
339 nb_sectors, cb, opaque, type);
340 #endif
341 }
342 }
343
344 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
345 cb, opaque, type);
346 }
347
348 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
349 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
350 BlockDriverCompletionFunc *cb, void *opaque)
351 {
352 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
353 cb, opaque, QEMU_AIO_READ);
354 }
355
356 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
357 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
358 BlockDriverCompletionFunc *cb, void *opaque)
359 {
360 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
361 cb, opaque, QEMU_AIO_WRITE);
362 }
363
364 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
365 BlockDriverCompletionFunc *cb, void *opaque)
366 {
367 BDRVRawState *s = bs->opaque;
368
369 if (fd_open(bs) < 0)
370 return NULL;
371
372 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
373 }
374
375 static void raw_close(BlockDriverState *bs)
376 {
377 BDRVRawState *s = bs->opaque;
378 if (s->fd >= 0) {
379 close(s->fd);
380 s->fd = -1;
381 if (s->aligned_buf != NULL)
382 qemu_vfree(s->aligned_buf);
383 }
384 }
385
386 static int raw_truncate(BlockDriverState *bs, int64_t offset)
387 {
388 BDRVRawState *s = bs->opaque;
389 struct stat st;
390
391 if (fstat(s->fd, &st)) {
392 return -errno;
393 }
394
395 if (S_ISREG(st.st_mode)) {
396 if (ftruncate(s->fd, offset) < 0) {
397 return -errno;
398 }
399 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
400 if (offset > raw_getlength(bs)) {
401 return -EINVAL;
402 }
403 } else {
404 return -ENOTSUP;
405 }
406
407 return 0;
408 }
409
410 #ifdef __OpenBSD__
411 static int64_t raw_getlength(BlockDriverState *bs)
412 {
413 BDRVRawState *s = bs->opaque;
414 int fd = s->fd;
415 struct stat st;
416
417 if (fstat(fd, &st))
418 return -1;
419 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
420 struct disklabel dl;
421
422 if (ioctl(fd, DIOCGDINFO, &dl))
423 return -1;
424 return (uint64_t)dl.d_secsize *
425 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
426 } else
427 return st.st_size;
428 }
429 #elif defined(__NetBSD__)
430 static int64_t raw_getlength(BlockDriverState *bs)
431 {
432 BDRVRawState *s = bs->opaque;
433 int fd = s->fd;
434 struct stat st;
435
436 if (fstat(fd, &st))
437 return -1;
438 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
439 struct dkwedge_info dkw;
440
441 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
442 return dkw.dkw_size * 512;
443 } else {
444 struct disklabel dl;
445
446 if (ioctl(fd, DIOCGDINFO, &dl))
447 return -1;
448 return (uint64_t)dl.d_secsize *
449 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
450 }
451 } else
452 return st.st_size;
453 }
454 #elif defined(__sun__)
455 static int64_t raw_getlength(BlockDriverState *bs)
456 {
457 BDRVRawState *s = bs->opaque;
458 struct dk_minfo minfo;
459 int ret;
460
461 ret = fd_open(bs);
462 if (ret < 0) {
463 return ret;
464 }
465
466 /*
467 * Use the DKIOCGMEDIAINFO ioctl to read the size.
468 */
469 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
470 if (ret != -1) {
471 return minfo.dki_lbsize * minfo.dki_capacity;
472 }
473
474 /*
475 * There are reports that lseek on some devices fails, but
476 * irc discussion said that contingency on contingency was overkill.
477 */
478 return lseek(s->fd, 0, SEEK_END);
479 }
480 #elif defined(CONFIG_BSD)
481 static int64_t raw_getlength(BlockDriverState *bs)
482 {
483 BDRVRawState *s = bs->opaque;
484 int fd = s->fd;
485 int64_t size;
486 struct stat sb;
487 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
488 int reopened = 0;
489 #endif
490 int ret;
491
492 ret = fd_open(bs);
493 if (ret < 0)
494 return ret;
495
496 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
497 again:
498 #endif
499 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
500 #ifdef DIOCGMEDIASIZE
501 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
502 #elif defined(DIOCGPART)
503 {
504 struct partinfo pi;
505 if (ioctl(fd, DIOCGPART, &pi) == 0)
506 size = pi.media_size;
507 else
508 size = 0;
509 }
510 if (size == 0)
511 #endif
512 #if defined(__APPLE__) && defined(__MACH__)
513 size = LONG_LONG_MAX;
514 #else
515 size = lseek(fd, 0LL, SEEK_END);
516 #endif
517 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
518 switch(s->type) {
519 case FTYPE_CD:
520 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
521 if (size == 2048LL * (unsigned)-1)
522 size = 0;
523 /* XXX no disc? maybe we need to reopen... */
524 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
525 reopened = 1;
526 goto again;
527 }
528 }
529 #endif
530 } else {
531 size = lseek(fd, 0, SEEK_END);
532 }
533 return size;
534 }
535 #else
536 static int64_t raw_getlength(BlockDriverState *bs)
537 {
538 BDRVRawState *s = bs->opaque;
539 int ret;
540
541 ret = fd_open(bs);
542 if (ret < 0) {
543 return ret;
544 }
545
546 return lseek(s->fd, 0, SEEK_END);
547 }
548 #endif
549
550 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
551 {
552 struct stat st;
553 BDRVRawState *s = bs->opaque;
554
555 if (fstat(s->fd, &st) < 0) {
556 return -errno;
557 }
558 return (int64_t)st.st_blocks * 512;
559 }
560
561 static int raw_create(const char *filename, QEMUOptionParameter *options)
562 {
563 int fd;
564 int result = 0;
565 int64_t total_size = 0;
566
567 /* Read out options */
568 while (options && options->name) {
569 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
570 total_size = options->value.n / BDRV_SECTOR_SIZE;
571 }
572 options++;
573 }
574
575 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
576 0644);
577 if (fd < 0) {
578 result = -errno;
579 } else {
580 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
581 result = -errno;
582 }
583 if (close(fd) != 0) {
584 result = -errno;
585 }
586 }
587 return result;
588 }
589
590 /*
591 * Returns true iff the specified sector is present in the disk image. Drivers
592 * not implementing the functionality are assumed to not support backing files,
593 * hence all their sectors are reported as allocated.
594 *
595 * If 'sector_num' is beyond the end of the disk image the return value is 0
596 * and 'pnum' is set to 0.
597 *
598 * 'pnum' is set to the number of sectors (including and immediately following
599 * the specified sector) that are known to be in the same
600 * allocated/unallocated state.
601 *
602 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
603 * beyond the end of the disk image it will be clamped.
604 */
605 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
606 int64_t sector_num,
607 int nb_sectors, int *pnum)
608 {
609 BDRVRawState *s = bs->opaque;
610 off_t start, data, hole;
611 int ret;
612
613 ret = fd_open(bs);
614 if (ret < 0) {
615 return ret;
616 }
617
618 start = sector_num * BDRV_SECTOR_SIZE;
619 #ifdef CONFIG_FIEMAP
620 struct {
621 struct fiemap fm;
622 struct fiemap_extent fe;
623 } f;
624 f.fm.fm_start = start;
625 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
626 f.fm.fm_flags = 0;
627 f.fm.fm_extent_count = 1;
628 f.fm.fm_reserved = 0;
629 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
630 /* Assume everything is allocated. */
631 *pnum = nb_sectors;
632 return 1;
633 }
634
635 if (f.fm.fm_mapped_extents == 0) {
636 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
637 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
638 */
639 off_t length = lseek(s->fd, 0, SEEK_END);
640 hole = f.fm.fm_start;
641 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
642 } else {
643 data = f.fe.fe_logical;
644 hole = f.fe.fe_logical + f.fe.fe_length;
645 }
646 #elif defined SEEK_HOLE && defined SEEK_DATA
647 hole = lseek(s->fd, start, SEEK_HOLE);
648 if (hole == -1) {
649 /* -ENXIO indicates that sector_num was past the end of the file.
650 * There is a virtual hole there. */
651 assert(errno != -ENXIO);
652
653 /* Most likely EINVAL. Assume everything is allocated. */
654 *pnum = nb_sectors;
655 return 1;
656 }
657
658 if (hole > start) {
659 data = start;
660 } else {
661 /* On a hole. We need another syscall to find its end. */
662 data = lseek(s->fd, start, SEEK_DATA);
663 if (data == -1) {
664 data = lseek(s->fd, 0, SEEK_END);
665 }
666 }
667 #else
668 *pnum = nb_sectors;
669 return 1;
670 #endif
671
672 if (data <= start) {
673 /* On a data extent, compute sectors to the end of the extent. */
674 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
675 return 1;
676 } else {
677 /* On a hole, compute sectors to the beginning of the next extent. */
678 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
679 return 0;
680 }
681 }
682
683 #ifdef CONFIG_XFS
684 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
685 {
686 struct xfs_flock64 fl;
687
688 memset(&fl, 0, sizeof(fl));
689 fl.l_whence = SEEK_SET;
690 fl.l_start = sector_num << 9;
691 fl.l_len = (int64_t)nb_sectors << 9;
692
693 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
694 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
695 return -errno;
696 }
697
698 return 0;
699 }
700 #endif
701
702 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
703 int64_t sector_num, int nb_sectors)
704 {
705 #ifdef CONFIG_XFS
706 BDRVRawState *s = bs->opaque;
707
708 if (s->is_xfs) {
709 return xfs_discard(s, sector_num, nb_sectors);
710 }
711 #endif
712
713 return 0;
714 }
715
716 static QEMUOptionParameter raw_create_options[] = {
717 {
718 .name = BLOCK_OPT_SIZE,
719 .type = OPT_SIZE,
720 .help = "Virtual disk size"
721 },
722 { NULL }
723 };
724
725 static BlockDriver bdrv_file = {
726 .format_name = "file",
727 .protocol_name = "file",
728 .instance_size = sizeof(BDRVRawState),
729 .bdrv_probe = NULL, /* no probe for protocols */
730 .bdrv_file_open = raw_open,
731 .bdrv_close = raw_close,
732 .bdrv_create = raw_create,
733 .bdrv_co_discard = raw_co_discard,
734 .bdrv_co_is_allocated = raw_co_is_allocated,
735
736 .bdrv_aio_readv = raw_aio_readv,
737 .bdrv_aio_writev = raw_aio_writev,
738 .bdrv_aio_flush = raw_aio_flush,
739
740 .bdrv_truncate = raw_truncate,
741 .bdrv_getlength = raw_getlength,
742 .bdrv_get_allocated_file_size
743 = raw_get_allocated_file_size,
744
745 .create_options = raw_create_options,
746 };
747
748 /***********************************************/
749 /* host device */
750
751 #if defined(__APPLE__) && defined(__MACH__)
752 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
753 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
754
755 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
756 {
757 kern_return_t kernResult;
758 mach_port_t masterPort;
759 CFMutableDictionaryRef classesToMatch;
760
761 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
762 if ( KERN_SUCCESS != kernResult ) {
763 printf( "IOMasterPort returned %d\n", kernResult );
764 }
765
766 classesToMatch = IOServiceMatching( kIOCDMediaClass );
767 if ( classesToMatch == NULL ) {
768 printf( "IOServiceMatching returned a NULL dictionary.\n" );
769 } else {
770 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
771 }
772 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
773 if ( KERN_SUCCESS != kernResult )
774 {
775 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
776 }
777
778 return kernResult;
779 }
780
781 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
782 {
783 io_object_t nextMedia;
784 kern_return_t kernResult = KERN_FAILURE;
785 *bsdPath = '\0';
786 nextMedia = IOIteratorNext( mediaIterator );
787 if ( nextMedia )
788 {
789 CFTypeRef bsdPathAsCFString;
790 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
791 if ( bsdPathAsCFString ) {
792 size_t devPathLength;
793 strcpy( bsdPath, _PATH_DEV );
794 strcat( bsdPath, "r" );
795 devPathLength = strlen( bsdPath );
796 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
797 kernResult = KERN_SUCCESS;
798 }
799 CFRelease( bsdPathAsCFString );
800 }
801 IOObjectRelease( nextMedia );
802 }
803
804 return kernResult;
805 }
806
807 #endif
808
809 static int hdev_probe_device(const char *filename)
810 {
811 struct stat st;
812
813 /* allow a dedicated CD-ROM driver to match with a higher priority */
814 if (strstart(filename, "/dev/cdrom", NULL))
815 return 50;
816
817 if (stat(filename, &st) >= 0 &&
818 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
819 return 100;
820 }
821
822 return 0;
823 }
824
825 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
826 {
827 BDRVRawState *s = bs->opaque;
828
829 #if defined(__APPLE__) && defined(__MACH__)
830 if (strstart(filename, "/dev/cdrom", NULL)) {
831 kern_return_t kernResult;
832 io_iterator_t mediaIterator;
833 char bsdPath[ MAXPATHLEN ];
834 int fd;
835
836 kernResult = FindEjectableCDMedia( &mediaIterator );
837 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
838
839 if ( bsdPath[ 0 ] != '\0' ) {
840 strcat(bsdPath,"s0");
841 /* some CDs don't have a partition 0 */
842 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
843 if (fd < 0) {
844 bsdPath[strlen(bsdPath)-1] = '1';
845 } else {
846 close(fd);
847 }
848 filename = bsdPath;
849 }
850
851 if ( mediaIterator )
852 IOObjectRelease( mediaIterator );
853 }
854 #endif
855
856 s->type = FTYPE_FILE;
857 #if defined(__linux__)
858 {
859 char resolved_path[ MAXPATHLEN ], *temp;
860
861 temp = realpath(filename, resolved_path);
862 if (temp && strstart(temp, "/dev/sg", NULL)) {
863 bs->sg = 1;
864 }
865 }
866 #endif
867
868 return raw_open_common(bs, filename, flags, 0);
869 }
870
871 #if defined(__linux__)
872 /* Note: we do not have a reliable method to detect if the floppy is
873 present. The current method is to try to open the floppy at every
874 I/O and to keep it opened during a few hundreds of ms. */
875 static int fd_open(BlockDriverState *bs)
876 {
877 BDRVRawState *s = bs->opaque;
878 int last_media_present;
879
880 if (s->type != FTYPE_FD)
881 return 0;
882 last_media_present = (s->fd >= 0);
883 if (s->fd >= 0 &&
884 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
885 close(s->fd);
886 s->fd = -1;
887 #ifdef DEBUG_FLOPPY
888 printf("Floppy closed\n");
889 #endif
890 }
891 if (s->fd < 0) {
892 if (s->fd_got_error &&
893 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
894 #ifdef DEBUG_FLOPPY
895 printf("No floppy (open delayed)\n");
896 #endif
897 return -EIO;
898 }
899 s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
900 if (s->fd < 0) {
901 s->fd_error_time = get_clock();
902 s->fd_got_error = 1;
903 if (last_media_present)
904 s->fd_media_changed = 1;
905 #ifdef DEBUG_FLOPPY
906 printf("No floppy\n");
907 #endif
908 return -EIO;
909 }
910 #ifdef DEBUG_FLOPPY
911 printf("Floppy opened\n");
912 #endif
913 }
914 if (!last_media_present)
915 s->fd_media_changed = 1;
916 s->fd_open_time = get_clock();
917 s->fd_got_error = 0;
918 return 0;
919 }
920
921 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
922 {
923 BDRVRawState *s = bs->opaque;
924
925 return ioctl(s->fd, req, buf);
926 }
927
928 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
929 unsigned long int req, void *buf,
930 BlockDriverCompletionFunc *cb, void *opaque)
931 {
932 BDRVRawState *s = bs->opaque;
933
934 if (fd_open(bs) < 0)
935 return NULL;
936 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
937 }
938
939 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
940 static int fd_open(BlockDriverState *bs)
941 {
942 BDRVRawState *s = bs->opaque;
943
944 /* this is just to ensure s->fd is sane (its called by io ops) */
945 if (s->fd >= 0)
946 return 0;
947 return -EIO;
948 }
949 #else /* !linux && !FreeBSD */
950
951 static int fd_open(BlockDriverState *bs)
952 {
953 return 0;
954 }
955
956 #endif /* !linux && !FreeBSD */
957
958 static int hdev_create(const char *filename, QEMUOptionParameter *options)
959 {
960 int fd;
961 int ret = 0;
962 struct stat stat_buf;
963 int64_t total_size = 0;
964
965 /* Read out options */
966 while (options && options->name) {
967 if (!strcmp(options->name, "size")) {
968 total_size = options->value.n / BDRV_SECTOR_SIZE;
969 }
970 options++;
971 }
972
973 fd = open(filename, O_WRONLY | O_BINARY);
974 if (fd < 0)
975 return -errno;
976
977 if (fstat(fd, &stat_buf) < 0)
978 ret = -errno;
979 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
980 ret = -ENODEV;
981 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
982 ret = -ENOSPC;
983
984 close(fd);
985 return ret;
986 }
987
988 static int hdev_has_zero_init(BlockDriverState *bs)
989 {
990 return 0;
991 }
992
993 static BlockDriver bdrv_host_device = {
994 .format_name = "host_device",
995 .protocol_name = "host_device",
996 .instance_size = sizeof(BDRVRawState),
997 .bdrv_probe_device = hdev_probe_device,
998 .bdrv_file_open = hdev_open,
999 .bdrv_close = raw_close,
1000 .bdrv_create = hdev_create,
1001 .create_options = raw_create_options,
1002 .bdrv_has_zero_init = hdev_has_zero_init,
1003
1004 .bdrv_aio_readv = raw_aio_readv,
1005 .bdrv_aio_writev = raw_aio_writev,
1006 .bdrv_aio_flush = raw_aio_flush,
1007
1008 .bdrv_truncate = raw_truncate,
1009 .bdrv_getlength = raw_getlength,
1010 .bdrv_get_allocated_file_size
1011 = raw_get_allocated_file_size,
1012
1013 /* generic scsi device */
1014 #ifdef __linux__
1015 .bdrv_ioctl = hdev_ioctl,
1016 .bdrv_aio_ioctl = hdev_aio_ioctl,
1017 #endif
1018 };
1019
1020 #ifdef __linux__
1021 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1022 {
1023 BDRVRawState *s = bs->opaque;
1024 int ret;
1025
1026 s->type = FTYPE_FD;
1027
1028 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1029 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1030 if (ret)
1031 return ret;
1032
1033 /* close fd so that we can reopen it as needed */
1034 close(s->fd);
1035 s->fd = -1;
1036 s->fd_media_changed = 1;
1037
1038 return 0;
1039 }
1040
1041 static int floppy_probe_device(const char *filename)
1042 {
1043 int fd, ret;
1044 int prio = 0;
1045 struct floppy_struct fdparam;
1046 struct stat st;
1047
1048 if (strstart(filename, "/dev/fd", NULL))
1049 prio = 50;
1050
1051 fd = open(filename, O_RDONLY | O_NONBLOCK);
1052 if (fd < 0) {
1053 goto out;
1054 }
1055 ret = fstat(fd, &st);
1056 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1057 goto outc;
1058 }
1059
1060 /* Attempt to detect via a floppy specific ioctl */
1061 ret = ioctl(fd, FDGETPRM, &fdparam);
1062 if (ret >= 0)
1063 prio = 100;
1064
1065 outc:
1066 close(fd);
1067 out:
1068 return prio;
1069 }
1070
1071
1072 static int floppy_is_inserted(BlockDriverState *bs)
1073 {
1074 return fd_open(bs) >= 0;
1075 }
1076
1077 static int floppy_media_changed(BlockDriverState *bs)
1078 {
1079 BDRVRawState *s = bs->opaque;
1080 int ret;
1081
1082 /*
1083 * XXX: we do not have a true media changed indication.
1084 * It does not work if the floppy is changed without trying to read it.
1085 */
1086 fd_open(bs);
1087 ret = s->fd_media_changed;
1088 s->fd_media_changed = 0;
1089 #ifdef DEBUG_FLOPPY
1090 printf("Floppy changed=%d\n", ret);
1091 #endif
1092 return ret;
1093 }
1094
1095 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1096 {
1097 BDRVRawState *s = bs->opaque;
1098 int fd;
1099
1100 if (s->fd >= 0) {
1101 close(s->fd);
1102 s->fd = -1;
1103 }
1104 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
1105 if (fd >= 0) {
1106 if (ioctl(fd, FDEJECT, 0) < 0)
1107 perror("FDEJECT");
1108 close(fd);
1109 }
1110 }
1111
1112 static BlockDriver bdrv_host_floppy = {
1113 .format_name = "host_floppy",
1114 .protocol_name = "host_floppy",
1115 .instance_size = sizeof(BDRVRawState),
1116 .bdrv_probe_device = floppy_probe_device,
1117 .bdrv_file_open = floppy_open,
1118 .bdrv_close = raw_close,
1119 .bdrv_create = hdev_create,
1120 .create_options = raw_create_options,
1121 .bdrv_has_zero_init = hdev_has_zero_init,
1122
1123 .bdrv_aio_readv = raw_aio_readv,
1124 .bdrv_aio_writev = raw_aio_writev,
1125 .bdrv_aio_flush = raw_aio_flush,
1126
1127 .bdrv_truncate = raw_truncate,
1128 .bdrv_getlength = raw_getlength,
1129 .bdrv_get_allocated_file_size
1130 = raw_get_allocated_file_size,
1131
1132 /* removable device support */
1133 .bdrv_is_inserted = floppy_is_inserted,
1134 .bdrv_media_changed = floppy_media_changed,
1135 .bdrv_eject = floppy_eject,
1136 };
1137
1138 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1139 {
1140 BDRVRawState *s = bs->opaque;
1141
1142 s->type = FTYPE_CD;
1143
1144 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1145 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1146 }
1147
1148 static int cdrom_probe_device(const char *filename)
1149 {
1150 int fd, ret;
1151 int prio = 0;
1152 struct stat st;
1153
1154 fd = open(filename, O_RDONLY | O_NONBLOCK);
1155 if (fd < 0) {
1156 goto out;
1157 }
1158 ret = fstat(fd, &st);
1159 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1160 goto outc;
1161 }
1162
1163 /* Attempt to detect via a CDROM specific ioctl */
1164 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1165 if (ret >= 0)
1166 prio = 100;
1167
1168 outc:
1169 close(fd);
1170 out:
1171 return prio;
1172 }
1173
1174 static int cdrom_is_inserted(BlockDriverState *bs)
1175 {
1176 BDRVRawState *s = bs->opaque;
1177 int ret;
1178
1179 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1180 if (ret == CDS_DISC_OK)
1181 return 1;
1182 return 0;
1183 }
1184
1185 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1186 {
1187 BDRVRawState *s = bs->opaque;
1188
1189 if (eject_flag) {
1190 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1191 perror("CDROMEJECT");
1192 } else {
1193 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1194 perror("CDROMEJECT");
1195 }
1196 }
1197
1198 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1199 {
1200 BDRVRawState *s = bs->opaque;
1201
1202 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1203 /*
1204 * Note: an error can happen if the distribution automatically
1205 * mounts the CD-ROM
1206 */
1207 /* perror("CDROM_LOCKDOOR"); */
1208 }
1209 }
1210
1211 static BlockDriver bdrv_host_cdrom = {
1212 .format_name = "host_cdrom",
1213 .protocol_name = "host_cdrom",
1214 .instance_size = sizeof(BDRVRawState),
1215 .bdrv_probe_device = cdrom_probe_device,
1216 .bdrv_file_open = cdrom_open,
1217 .bdrv_close = raw_close,
1218 .bdrv_create = hdev_create,
1219 .create_options = raw_create_options,
1220 .bdrv_has_zero_init = hdev_has_zero_init,
1221
1222 .bdrv_aio_readv = raw_aio_readv,
1223 .bdrv_aio_writev = raw_aio_writev,
1224 .bdrv_aio_flush = raw_aio_flush,
1225
1226 .bdrv_truncate = raw_truncate,
1227 .bdrv_getlength = raw_getlength,
1228 .bdrv_get_allocated_file_size
1229 = raw_get_allocated_file_size,
1230
1231 /* removable device support */
1232 .bdrv_is_inserted = cdrom_is_inserted,
1233 .bdrv_eject = cdrom_eject,
1234 .bdrv_lock_medium = cdrom_lock_medium,
1235
1236 /* generic scsi device */
1237 .bdrv_ioctl = hdev_ioctl,
1238 .bdrv_aio_ioctl = hdev_aio_ioctl,
1239 };
1240 #endif /* __linux__ */
1241
1242 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1243 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1244 {
1245 BDRVRawState *s = bs->opaque;
1246 int ret;
1247
1248 s->type = FTYPE_CD;
1249
1250 ret = raw_open_common(bs, filename, flags, 0);
1251 if (ret)
1252 return ret;
1253
1254 /* make sure the door isn't locked at this time */
1255 ioctl(s->fd, CDIOCALLOW);
1256 return 0;
1257 }
1258
1259 static int cdrom_probe_device(const char *filename)
1260 {
1261 if (strstart(filename, "/dev/cd", NULL) ||
1262 strstart(filename, "/dev/acd", NULL))
1263 return 100;
1264 return 0;
1265 }
1266
1267 static int cdrom_reopen(BlockDriverState *bs)
1268 {
1269 BDRVRawState *s = bs->opaque;
1270 int fd;
1271
1272 /*
1273 * Force reread of possibly changed/newly loaded disc,
1274 * FreeBSD seems to not notice sometimes...
1275 */
1276 if (s->fd >= 0)
1277 close(s->fd);
1278 fd = open(bs->filename, s->open_flags, 0644);
1279 if (fd < 0) {
1280 s->fd = -1;
1281 return -EIO;
1282 }
1283 s->fd = fd;
1284
1285 /* make sure the door isn't locked at this time */
1286 ioctl(s->fd, CDIOCALLOW);
1287 return 0;
1288 }
1289
1290 static int cdrom_is_inserted(BlockDriverState *bs)
1291 {
1292 return raw_getlength(bs) > 0;
1293 }
1294
1295 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1296 {
1297 BDRVRawState *s = bs->opaque;
1298
1299 if (s->fd < 0)
1300 return;
1301
1302 (void) ioctl(s->fd, CDIOCALLOW);
1303
1304 if (eject_flag) {
1305 if (ioctl(s->fd, CDIOCEJECT) < 0)
1306 perror("CDIOCEJECT");
1307 } else {
1308 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1309 perror("CDIOCCLOSE");
1310 }
1311
1312 cdrom_reopen(bs);
1313 }
1314
1315 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1316 {
1317 BDRVRawState *s = bs->opaque;
1318
1319 if (s->fd < 0)
1320 return;
1321 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1322 /*
1323 * Note: an error can happen if the distribution automatically
1324 * mounts the CD-ROM
1325 */
1326 /* perror("CDROM_LOCKDOOR"); */
1327 }
1328 }
1329
1330 static BlockDriver bdrv_host_cdrom = {
1331 .format_name = "host_cdrom",
1332 .protocol_name = "host_cdrom",
1333 .instance_size = sizeof(BDRVRawState),
1334 .bdrv_probe_device = cdrom_probe_device,
1335 .bdrv_file_open = cdrom_open,
1336 .bdrv_close = raw_close,
1337 .bdrv_create = hdev_create,
1338 .create_options = raw_create_options,
1339 .bdrv_has_zero_init = hdev_has_zero_init,
1340
1341 .bdrv_aio_readv = raw_aio_readv,
1342 .bdrv_aio_writev = raw_aio_writev,
1343 .bdrv_aio_flush = raw_aio_flush,
1344
1345 .bdrv_truncate = raw_truncate,
1346 .bdrv_getlength = raw_getlength,
1347 .bdrv_get_allocated_file_size
1348 = raw_get_allocated_file_size,
1349
1350 /* removable device support */
1351 .bdrv_is_inserted = cdrom_is_inserted,
1352 .bdrv_eject = cdrom_eject,
1353 .bdrv_lock_medium = cdrom_lock_medium,
1354 };
1355 #endif /* __FreeBSD__ */
1356
1357 static void bdrv_file_init(void)
1358 {
1359 /*
1360 * Register all the drivers. Note that order is important, the driver
1361 * registered last will get probed first.
1362 */
1363 bdrv_register(&bdrv_file);
1364 bdrv_register(&bdrv_host_device);
1365 #ifdef __linux__
1366 bdrv_register(&bdrv_host_floppy);
1367 bdrv_register(&bdrv_host_cdrom);
1368 #endif
1369 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1370 bdrv_register(&bdrv_host_cdrom);
1371 #endif
1372 }
1373
1374 block_init(bdrv_file_init);