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