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