]> git.proxmox.com Git - qemu.git/blob - block/raw-posix.c
Merge remote-tracking branch 'stefanha/block' 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 "trace.h"
31 #include "thread-pool.h"
32 #include "iov.h"
33 #include "raw-aio.h"
34
35 #if defined(__APPLE__) && (__MACH__)
36 #include <paths.h>
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
45 #endif
46
47 #ifdef __sun__
48 #define _POSIX_PTHREAD_SEMANTICS 1
49 #include <sys/dkio.h>
50 #endif
51 #ifdef __linux__
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
57 #include <linux/fd.h>
58 #include <linux/fs.h>
59 #endif
60 #ifdef CONFIG_FIEMAP
61 #include <linux/fiemap.h>
62 #endif
63 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
64 #include <sys/disk.h>
65 #include <sys/cdio.h>
66 #endif
67
68 #ifdef __OpenBSD__
69 #include <sys/ioctl.h>
70 #include <sys/disklabel.h>
71 #include <sys/dkio.h>
72 #endif
73
74 #ifdef __NetBSD__
75 #include <sys/ioctl.h>
76 #include <sys/disklabel.h>
77 #include <sys/dkio.h>
78 #include <sys/disk.h>
79 #endif
80
81 #ifdef __DragonFly__
82 #include <sys/ioctl.h>
83 #include <sys/diskslice.h>
84 #endif
85
86 #ifdef CONFIG_XFS
87 #include <xfs/xfs.h>
88 #endif
89
90 //#define DEBUG_FLOPPY
91
92 //#define DEBUG_BLOCK
93 #if defined(DEBUG_BLOCK)
94 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
95 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
96 #else
97 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
98 #endif
99
100 /* OS X does not have O_DSYNC */
101 #ifndef O_DSYNC
102 #ifdef O_SYNC
103 #define O_DSYNC O_SYNC
104 #elif defined(O_FSYNC)
105 #define O_DSYNC O_FSYNC
106 #endif
107 #endif
108
109 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
110 #ifndef O_DIRECT
111 #define O_DIRECT O_DSYNC
112 #endif
113
114 #define FTYPE_FILE 0
115 #define FTYPE_CD 1
116 #define FTYPE_FD 2
117
118 /* if the FD is not accessed during that time (in ns), we try to
119 reopen it to see if the disk has been changed */
120 #define FD_OPEN_TIMEOUT (1000000000)
121
122 #define MAX_BLOCKSIZE 4096
123
124 typedef struct BDRVRawState {
125 int fd;
126 int type;
127 int open_flags;
128 #if defined(__linux__)
129 /* linux floppy specific */
130 int64_t fd_open_time;
131 int64_t fd_error_time;
132 int fd_got_error;
133 int fd_media_changed;
134 #endif
135 #ifdef CONFIG_LINUX_AIO
136 int use_aio;
137 void *aio_ctx;
138 #endif
139 #ifdef CONFIG_XFS
140 bool is_xfs : 1;
141 #endif
142 } BDRVRawState;
143
144 typedef struct BDRVRawReopenState {
145 int fd;
146 int open_flags;
147 #ifdef CONFIG_LINUX_AIO
148 int use_aio;
149 #endif
150 } BDRVRawReopenState;
151
152 static int fd_open(BlockDriverState *bs);
153 static int64_t raw_getlength(BlockDriverState *bs);
154
155 typedef struct RawPosixAIOData {
156 BlockDriverState *bs;
157 int aio_fildes;
158 union {
159 struct iovec *aio_iov;
160 void *aio_ioctl_buf;
161 };
162 int aio_niov;
163 size_t aio_nbytes;
164 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
165 off_t aio_offset;
166 int aio_type;
167 } RawPosixAIOData;
168
169 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
170 static int cdrom_reopen(BlockDriverState *bs);
171 #endif
172
173 #if defined(__NetBSD__)
174 static int raw_normalize_devicepath(const char **filename)
175 {
176 static char namebuf[PATH_MAX];
177 const char *dp, *fname;
178 struct stat sb;
179
180 fname = *filename;
181 dp = strrchr(fname, '/');
182 if (lstat(fname, &sb) < 0) {
183 fprintf(stderr, "%s: stat failed: %s\n",
184 fname, strerror(errno));
185 return -errno;
186 }
187
188 if (!S_ISBLK(sb.st_mode)) {
189 return 0;
190 }
191
192 if (dp == NULL) {
193 snprintf(namebuf, PATH_MAX, "r%s", fname);
194 } else {
195 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
196 (int)(dp - fname), fname, dp + 1);
197 }
198 fprintf(stderr, "%s is a block device", fname);
199 *filename = namebuf;
200 fprintf(stderr, ", using %s\n", *filename);
201
202 return 0;
203 }
204 #else
205 static int raw_normalize_devicepath(const char **filename)
206 {
207 return 0;
208 }
209 #endif
210
211 static void raw_parse_flags(int bdrv_flags, int *open_flags)
212 {
213 assert(open_flags != NULL);
214
215 *open_flags |= O_BINARY;
216 *open_flags &= ~O_ACCMODE;
217 if (bdrv_flags & BDRV_O_RDWR) {
218 *open_flags |= O_RDWR;
219 } else {
220 *open_flags |= O_RDONLY;
221 }
222
223 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
224 * and O_DIRECT for no caching. */
225 if ((bdrv_flags & BDRV_O_NOCACHE)) {
226 *open_flags |= O_DIRECT;
227 }
228 }
229
230 #ifdef CONFIG_LINUX_AIO
231 static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
232 {
233 int ret = -1;
234 assert(aio_ctx != NULL);
235 assert(use_aio != NULL);
236 /*
237 * Currently Linux do AIO only for files opened with O_DIRECT
238 * specified so check NOCACHE flag too
239 */
240 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
241 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
242
243 /* if non-NULL, laio_init() has already been run */
244 if (*aio_ctx == NULL) {
245 *aio_ctx = laio_init();
246 if (!*aio_ctx) {
247 goto error;
248 }
249 }
250 *use_aio = 1;
251 } else {
252 *use_aio = 0;
253 }
254
255 ret = 0;
256
257 error:
258 return ret;
259 }
260 #endif
261
262 static int raw_open_common(BlockDriverState *bs, const char *filename,
263 int bdrv_flags, int open_flags)
264 {
265 BDRVRawState *s = bs->opaque;
266 int fd, ret;
267
268 ret = raw_normalize_devicepath(&filename);
269 if (ret != 0) {
270 return ret;
271 }
272
273 s->open_flags = open_flags;
274 raw_parse_flags(bdrv_flags, &s->open_flags);
275
276 s->fd = -1;
277 fd = qemu_open(filename, s->open_flags, 0644);
278 if (fd < 0) {
279 ret = -errno;
280 if (ret == -EROFS)
281 ret = -EACCES;
282 return ret;
283 }
284 s->fd = fd;
285
286 #ifdef CONFIG_LINUX_AIO
287 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
288 qemu_close(fd);
289 return -errno;
290 }
291 #endif
292
293 #ifdef CONFIG_XFS
294 if (platform_test_xfs_fd(s->fd)) {
295 s->is_xfs = 1;
296 }
297 #endif
298
299 return 0;
300 }
301
302 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
303 {
304 BDRVRawState *s = bs->opaque;
305
306 s->type = FTYPE_FILE;
307 return raw_open_common(bs, filename, flags, 0);
308 }
309
310 static int raw_reopen_prepare(BDRVReopenState *state,
311 BlockReopenQueue *queue, Error **errp)
312 {
313 BDRVRawState *s;
314 BDRVRawReopenState *raw_s;
315 int ret = 0;
316
317 assert(state != NULL);
318 assert(state->bs != NULL);
319
320 s = state->bs->opaque;
321
322 state->opaque = g_malloc0(sizeof(BDRVRawReopenState));
323 raw_s = state->opaque;
324
325 #ifdef CONFIG_LINUX_AIO
326 raw_s->use_aio = s->use_aio;
327
328 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
329 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
330 * won't override aio_ctx if aio_ctx is non-NULL */
331 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
332 return -1;
333 }
334 #endif
335
336 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
337 raw_s->open_flags |= O_NONBLOCK;
338 }
339
340 raw_parse_flags(state->flags, &raw_s->open_flags);
341
342 raw_s->fd = -1;
343
344 int fcntl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
345 #ifdef O_NOATIME
346 fcntl_flags |= O_NOATIME;
347 #endif
348
349 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
350 /* dup the original fd */
351 /* TODO: use qemu fcntl wrapper */
352 #ifdef F_DUPFD_CLOEXEC
353 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
354 #else
355 raw_s->fd = dup(s->fd);
356 if (raw_s->fd != -1) {
357 qemu_set_cloexec(raw_s->fd);
358 }
359 #endif
360 if (raw_s->fd >= 0) {
361 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
362 if (ret) {
363 qemu_close(raw_s->fd);
364 raw_s->fd = -1;
365 }
366 }
367 }
368
369 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
370 if (raw_s->fd == -1) {
371 assert(!(raw_s->open_flags & O_CREAT));
372 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
373 if (raw_s->fd == -1) {
374 ret = -1;
375 }
376 }
377 return ret;
378 }
379
380
381 static void raw_reopen_commit(BDRVReopenState *state)
382 {
383 BDRVRawReopenState *raw_s = state->opaque;
384 BDRVRawState *s = state->bs->opaque;
385
386 s->open_flags = raw_s->open_flags;
387
388 qemu_close(s->fd);
389 s->fd = raw_s->fd;
390 #ifdef CONFIG_LINUX_AIO
391 s->use_aio = raw_s->use_aio;
392 #endif
393
394 g_free(state->opaque);
395 state->opaque = NULL;
396 }
397
398
399 static void raw_reopen_abort(BDRVReopenState *state)
400 {
401 BDRVRawReopenState *raw_s = state->opaque;
402
403 /* nothing to do if NULL, we didn't get far enough */
404 if (raw_s == NULL) {
405 return;
406 }
407
408 if (raw_s->fd >= 0) {
409 qemu_close(raw_s->fd);
410 raw_s->fd = -1;
411 }
412 g_free(state->opaque);
413 state->opaque = NULL;
414 }
415
416
417 /* XXX: use host sector size if necessary with:
418 #ifdef DIOCGSECTORSIZE
419 {
420 unsigned int sectorsize = 512;
421 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
422 sectorsize > bufsize)
423 bufsize = sectorsize;
424 }
425 #endif
426 #ifdef CONFIG_COCOA
427 uint32_t blockSize = 512;
428 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
429 bufsize = blockSize;
430 }
431 #endif
432 */
433
434 /*
435 * Check if all memory in this vector is sector aligned.
436 */
437 static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
438 {
439 int i;
440
441 for (i = 0; i < qiov->niov; i++) {
442 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
443 return 0;
444 }
445 }
446
447 return 1;
448 }
449
450 static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
451 {
452 int ret;
453
454 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
455 if (ret == -1) {
456 return -errno;
457 }
458
459 /*
460 * This looks weird, but the aio code only considers a request
461 * successful if it has written the full number of bytes.
462 *
463 * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command,
464 * so in fact we return the ioctl command here to make posix_aio_read()
465 * happy..
466 */
467 return aiocb->aio_nbytes;
468 }
469
470 static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
471 {
472 int ret;
473
474 ret = qemu_fdatasync(aiocb->aio_fildes);
475 if (ret == -1) {
476 return -errno;
477 }
478 return 0;
479 }
480
481 #ifdef CONFIG_PREADV
482
483 static bool preadv_present = true;
484
485 static ssize_t
486 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
487 {
488 return preadv(fd, iov, nr_iov, offset);
489 }
490
491 static ssize_t
492 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
493 {
494 return pwritev(fd, iov, nr_iov, offset);
495 }
496
497 #else
498
499 static bool preadv_present = false;
500
501 static ssize_t
502 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
503 {
504 return -ENOSYS;
505 }
506
507 static ssize_t
508 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
509 {
510 return -ENOSYS;
511 }
512
513 #endif
514
515 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
516 {
517 ssize_t len;
518
519 do {
520 if (aiocb->aio_type & QEMU_AIO_WRITE)
521 len = qemu_pwritev(aiocb->aio_fildes,
522 aiocb->aio_iov,
523 aiocb->aio_niov,
524 aiocb->aio_offset);
525 else
526 len = qemu_preadv(aiocb->aio_fildes,
527 aiocb->aio_iov,
528 aiocb->aio_niov,
529 aiocb->aio_offset);
530 } while (len == -1 && errno == EINTR);
531
532 if (len == -1) {
533 return -errno;
534 }
535 return len;
536 }
537
538 /*
539 * Read/writes the data to/from a given linear buffer.
540 *
541 * Returns the number of bytes handles or -errno in case of an error. Short
542 * reads are only returned if the end of the file is reached.
543 */
544 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
545 {
546 ssize_t offset = 0;
547 ssize_t len;
548
549 while (offset < aiocb->aio_nbytes) {
550 if (aiocb->aio_type & QEMU_AIO_WRITE) {
551 len = pwrite(aiocb->aio_fildes,
552 (const char *)buf + offset,
553 aiocb->aio_nbytes - offset,
554 aiocb->aio_offset + offset);
555 } else {
556 len = pread(aiocb->aio_fildes,
557 buf + offset,
558 aiocb->aio_nbytes - offset,
559 aiocb->aio_offset + offset);
560 }
561 if (len == -1 && errno == EINTR) {
562 continue;
563 } else if (len == -1) {
564 offset = -errno;
565 break;
566 } else if (len == 0) {
567 break;
568 }
569 offset += len;
570 }
571
572 return offset;
573 }
574
575 static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
576 {
577 ssize_t nbytes;
578 char *buf;
579
580 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
581 /*
582 * If there is just a single buffer, and it is properly aligned
583 * we can just use plain pread/pwrite without any problems.
584 */
585 if (aiocb->aio_niov == 1) {
586 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
587 }
588 /*
589 * We have more than one iovec, and all are properly aligned.
590 *
591 * Try preadv/pwritev first and fall back to linearizing the
592 * buffer if it's not supported.
593 */
594 if (preadv_present) {
595 nbytes = handle_aiocb_rw_vector(aiocb);
596 if (nbytes == aiocb->aio_nbytes ||
597 (nbytes < 0 && nbytes != -ENOSYS)) {
598 return nbytes;
599 }
600 preadv_present = false;
601 }
602
603 /*
604 * XXX(hch): short read/write. no easy way to handle the reminder
605 * using these interfaces. For now retry using plain
606 * pread/pwrite?
607 */
608 }
609
610 /*
611 * Ok, we have to do it the hard way, copy all segments into
612 * a single aligned buffer.
613 */
614 buf = qemu_blockalign(aiocb->bs, aiocb->aio_nbytes);
615 if (aiocb->aio_type & QEMU_AIO_WRITE) {
616 char *p = buf;
617 int i;
618
619 for (i = 0; i < aiocb->aio_niov; ++i) {
620 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
621 p += aiocb->aio_iov[i].iov_len;
622 }
623 }
624
625 nbytes = handle_aiocb_rw_linear(aiocb, buf);
626 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
627 char *p = buf;
628 size_t count = aiocb->aio_nbytes, copy;
629 int i;
630
631 for (i = 0; i < aiocb->aio_niov && count; ++i) {
632 copy = count;
633 if (copy > aiocb->aio_iov[i].iov_len) {
634 copy = aiocb->aio_iov[i].iov_len;
635 }
636 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
637 p += copy;
638 count -= copy;
639 }
640 }
641 qemu_vfree(buf);
642
643 return nbytes;
644 }
645
646 static int aio_worker(void *arg)
647 {
648 RawPosixAIOData *aiocb = arg;
649 ssize_t ret = 0;
650
651 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
652 case QEMU_AIO_READ:
653 ret = handle_aiocb_rw(aiocb);
654 if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->bs->growable) {
655 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
656 0, aiocb->aio_nbytes - ret);
657
658 ret = aiocb->aio_nbytes;
659 }
660 if (ret == aiocb->aio_nbytes) {
661 ret = 0;
662 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
663 ret = -EINVAL;
664 }
665 break;
666 case QEMU_AIO_WRITE:
667 ret = handle_aiocb_rw(aiocb);
668 if (ret == aiocb->aio_nbytes) {
669 ret = 0;
670 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
671 ret = -EINVAL;
672 }
673 break;
674 case QEMU_AIO_FLUSH:
675 ret = handle_aiocb_flush(aiocb);
676 break;
677 case QEMU_AIO_IOCTL:
678 ret = handle_aiocb_ioctl(aiocb);
679 break;
680 default:
681 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
682 ret = -EINVAL;
683 break;
684 }
685
686 g_slice_free(RawPosixAIOData, aiocb);
687 return ret;
688 }
689
690 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,
691 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
692 BlockDriverCompletionFunc *cb, void *opaque, int type)
693 {
694 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
695
696 acb->bs = bs;
697 acb->aio_type = type;
698 acb->aio_fildes = fd;
699
700 if (qiov) {
701 acb->aio_iov = qiov->iov;
702 acb->aio_niov = qiov->niov;
703 }
704 acb->aio_nbytes = nb_sectors * 512;
705 acb->aio_offset = sector_num * 512;
706
707 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
708 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
709 }
710
711 static BlockDriverAIOCB *paio_ioctl(BlockDriverState *bs, int fd,
712 unsigned long int req, void *buf,
713 BlockDriverCompletionFunc *cb, void *opaque)
714 {
715 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
716
717 acb->bs = bs;
718 acb->aio_type = QEMU_AIO_IOCTL;
719 acb->aio_fildes = fd;
720 acb->aio_offset = 0;
721 acb->aio_ioctl_buf = buf;
722 acb->aio_ioctl_cmd = req;
723
724 return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
725 }
726
727 static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
728 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
729 BlockDriverCompletionFunc *cb, void *opaque, int type)
730 {
731 BDRVRawState *s = bs->opaque;
732
733 if (fd_open(bs) < 0)
734 return NULL;
735
736 /*
737 * If O_DIRECT is used the buffer needs to be aligned on a sector
738 * boundary. Check if this is the case or tell the low-level
739 * driver that it needs to copy the buffer.
740 */
741 if ((bs->open_flags & BDRV_O_NOCACHE)) {
742 if (!qiov_is_aligned(bs, qiov)) {
743 type |= QEMU_AIO_MISALIGNED;
744 #ifdef CONFIG_LINUX_AIO
745 } else if (s->use_aio) {
746 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
747 nb_sectors, cb, opaque, type);
748 #endif
749 }
750 }
751
752 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
753 cb, opaque, type);
754 }
755
756 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
757 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
758 BlockDriverCompletionFunc *cb, void *opaque)
759 {
760 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
761 cb, opaque, QEMU_AIO_READ);
762 }
763
764 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
765 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
766 BlockDriverCompletionFunc *cb, void *opaque)
767 {
768 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
769 cb, opaque, QEMU_AIO_WRITE);
770 }
771
772 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
773 BlockDriverCompletionFunc *cb, void *opaque)
774 {
775 BDRVRawState *s = bs->opaque;
776
777 if (fd_open(bs) < 0)
778 return NULL;
779
780 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
781 }
782
783 static void raw_close(BlockDriverState *bs)
784 {
785 BDRVRawState *s = bs->opaque;
786 if (s->fd >= 0) {
787 qemu_close(s->fd);
788 s->fd = -1;
789 }
790 }
791
792 static int raw_truncate(BlockDriverState *bs, int64_t offset)
793 {
794 BDRVRawState *s = bs->opaque;
795 struct stat st;
796
797 if (fstat(s->fd, &st)) {
798 return -errno;
799 }
800
801 if (S_ISREG(st.st_mode)) {
802 if (ftruncate(s->fd, offset) < 0) {
803 return -errno;
804 }
805 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
806 if (offset > raw_getlength(bs)) {
807 return -EINVAL;
808 }
809 } else {
810 return -ENOTSUP;
811 }
812
813 return 0;
814 }
815
816 #ifdef __OpenBSD__
817 static int64_t raw_getlength(BlockDriverState *bs)
818 {
819 BDRVRawState *s = bs->opaque;
820 int fd = s->fd;
821 struct stat st;
822
823 if (fstat(fd, &st))
824 return -1;
825 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
826 struct disklabel dl;
827
828 if (ioctl(fd, DIOCGDINFO, &dl))
829 return -1;
830 return (uint64_t)dl.d_secsize *
831 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
832 } else
833 return st.st_size;
834 }
835 #elif defined(__NetBSD__)
836 static int64_t raw_getlength(BlockDriverState *bs)
837 {
838 BDRVRawState *s = bs->opaque;
839 int fd = s->fd;
840 struct stat st;
841
842 if (fstat(fd, &st))
843 return -1;
844 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
845 struct dkwedge_info dkw;
846
847 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
848 return dkw.dkw_size * 512;
849 } else {
850 struct disklabel dl;
851
852 if (ioctl(fd, DIOCGDINFO, &dl))
853 return -1;
854 return (uint64_t)dl.d_secsize *
855 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
856 }
857 } else
858 return st.st_size;
859 }
860 #elif defined(__sun__)
861 static int64_t raw_getlength(BlockDriverState *bs)
862 {
863 BDRVRawState *s = bs->opaque;
864 struct dk_minfo minfo;
865 int ret;
866
867 ret = fd_open(bs);
868 if (ret < 0) {
869 return ret;
870 }
871
872 /*
873 * Use the DKIOCGMEDIAINFO ioctl to read the size.
874 */
875 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
876 if (ret != -1) {
877 return minfo.dki_lbsize * minfo.dki_capacity;
878 }
879
880 /*
881 * There are reports that lseek on some devices fails, but
882 * irc discussion said that contingency on contingency was overkill.
883 */
884 return lseek(s->fd, 0, SEEK_END);
885 }
886 #elif defined(CONFIG_BSD)
887 static int64_t raw_getlength(BlockDriverState *bs)
888 {
889 BDRVRawState *s = bs->opaque;
890 int fd = s->fd;
891 int64_t size;
892 struct stat sb;
893 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
894 int reopened = 0;
895 #endif
896 int ret;
897
898 ret = fd_open(bs);
899 if (ret < 0)
900 return ret;
901
902 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
903 again:
904 #endif
905 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
906 #ifdef DIOCGMEDIASIZE
907 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
908 #elif defined(DIOCGPART)
909 {
910 struct partinfo pi;
911 if (ioctl(fd, DIOCGPART, &pi) == 0)
912 size = pi.media_size;
913 else
914 size = 0;
915 }
916 if (size == 0)
917 #endif
918 #if defined(__APPLE__) && defined(__MACH__)
919 size = LONG_LONG_MAX;
920 #else
921 size = lseek(fd, 0LL, SEEK_END);
922 #endif
923 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
924 switch(s->type) {
925 case FTYPE_CD:
926 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
927 if (size == 2048LL * (unsigned)-1)
928 size = 0;
929 /* XXX no disc? maybe we need to reopen... */
930 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
931 reopened = 1;
932 goto again;
933 }
934 }
935 #endif
936 } else {
937 size = lseek(fd, 0, SEEK_END);
938 }
939 return size;
940 }
941 #else
942 static int64_t raw_getlength(BlockDriverState *bs)
943 {
944 BDRVRawState *s = bs->opaque;
945 int ret;
946
947 ret = fd_open(bs);
948 if (ret < 0) {
949 return ret;
950 }
951
952 return lseek(s->fd, 0, SEEK_END);
953 }
954 #endif
955
956 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
957 {
958 struct stat st;
959 BDRVRawState *s = bs->opaque;
960
961 if (fstat(s->fd, &st) < 0) {
962 return -errno;
963 }
964 return (int64_t)st.st_blocks * 512;
965 }
966
967 static int raw_create(const char *filename, QEMUOptionParameter *options)
968 {
969 int fd;
970 int result = 0;
971 int64_t total_size = 0;
972
973 /* Read out options */
974 while (options && options->name) {
975 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
976 total_size = options->value.n / BDRV_SECTOR_SIZE;
977 }
978 options++;
979 }
980
981 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
982 0644);
983 if (fd < 0) {
984 result = -errno;
985 } else {
986 if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
987 result = -errno;
988 }
989 if (qemu_close(fd) != 0) {
990 result = -errno;
991 }
992 }
993 return result;
994 }
995
996 /*
997 * Returns true iff the specified sector is present in the disk image. Drivers
998 * not implementing the functionality are assumed to not support backing files,
999 * hence all their sectors are reported as allocated.
1000 *
1001 * If 'sector_num' is beyond the end of the disk image the return value is 0
1002 * and 'pnum' is set to 0.
1003 *
1004 * 'pnum' is set to the number of sectors (including and immediately following
1005 * the specified sector) that are known to be in the same
1006 * allocated/unallocated state.
1007 *
1008 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1009 * beyond the end of the disk image it will be clamped.
1010 */
1011 static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
1012 int64_t sector_num,
1013 int nb_sectors, int *pnum)
1014 {
1015 off_t start, data, hole;
1016 int ret;
1017
1018 ret = fd_open(bs);
1019 if (ret < 0) {
1020 return ret;
1021 }
1022
1023 start = sector_num * BDRV_SECTOR_SIZE;
1024
1025 #ifdef CONFIG_FIEMAP
1026
1027 BDRVRawState *s = bs->opaque;
1028 struct {
1029 struct fiemap fm;
1030 struct fiemap_extent fe;
1031 } f;
1032
1033 f.fm.fm_start = start;
1034 f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
1035 f.fm.fm_flags = 0;
1036 f.fm.fm_extent_count = 1;
1037 f.fm.fm_reserved = 0;
1038 if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
1039 /* Assume everything is allocated. */
1040 *pnum = nb_sectors;
1041 return 1;
1042 }
1043
1044 if (f.fm.fm_mapped_extents == 0) {
1045 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1046 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1047 */
1048 off_t length = lseek(s->fd, 0, SEEK_END);
1049 hole = f.fm.fm_start;
1050 data = MIN(f.fm.fm_start + f.fm.fm_length, length);
1051 } else {
1052 data = f.fe.fe_logical;
1053 hole = f.fe.fe_logical + f.fe.fe_length;
1054 }
1055
1056 #elif defined SEEK_HOLE && defined SEEK_DATA
1057
1058 BDRVRawState *s = bs->opaque;
1059
1060 hole = lseek(s->fd, start, SEEK_HOLE);
1061 if (hole == -1) {
1062 /* -ENXIO indicates that sector_num was past the end of the file.
1063 * There is a virtual hole there. */
1064 assert(errno != -ENXIO);
1065
1066 /* Most likely EINVAL. Assume everything is allocated. */
1067 *pnum = nb_sectors;
1068 return 1;
1069 }
1070
1071 if (hole > start) {
1072 data = start;
1073 } else {
1074 /* On a hole. We need another syscall to find its end. */
1075 data = lseek(s->fd, start, SEEK_DATA);
1076 if (data == -1) {
1077 data = lseek(s->fd, 0, SEEK_END);
1078 }
1079 }
1080 #else
1081 *pnum = nb_sectors;
1082 return 1;
1083 #endif
1084
1085 if (data <= start) {
1086 /* On a data extent, compute sectors to the end of the extent. */
1087 *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
1088 return 1;
1089 } else {
1090 /* On a hole, compute sectors to the beginning of the next extent. */
1091 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1092 return 0;
1093 }
1094 }
1095
1096 #ifdef CONFIG_XFS
1097 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
1098 {
1099 struct xfs_flock64 fl;
1100
1101 memset(&fl, 0, sizeof(fl));
1102 fl.l_whence = SEEK_SET;
1103 fl.l_start = sector_num << 9;
1104 fl.l_len = (int64_t)nb_sectors << 9;
1105
1106 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1107 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno));
1108 return -errno;
1109 }
1110
1111 return 0;
1112 }
1113 #endif
1114
1115 static coroutine_fn int raw_co_discard(BlockDriverState *bs,
1116 int64_t sector_num, int nb_sectors)
1117 {
1118 #ifdef CONFIG_XFS
1119 BDRVRawState *s = bs->opaque;
1120
1121 if (s->is_xfs) {
1122 return xfs_discard(s, sector_num, nb_sectors);
1123 }
1124 #endif
1125
1126 return 0;
1127 }
1128
1129 static QEMUOptionParameter raw_create_options[] = {
1130 {
1131 .name = BLOCK_OPT_SIZE,
1132 .type = OPT_SIZE,
1133 .help = "Virtual disk size"
1134 },
1135 { NULL }
1136 };
1137
1138 static BlockDriver bdrv_file = {
1139 .format_name = "file",
1140 .protocol_name = "file",
1141 .instance_size = sizeof(BDRVRawState),
1142 .bdrv_probe = NULL, /* no probe for protocols */
1143 .bdrv_file_open = raw_open,
1144 .bdrv_reopen_prepare = raw_reopen_prepare,
1145 .bdrv_reopen_commit = raw_reopen_commit,
1146 .bdrv_reopen_abort = raw_reopen_abort,
1147 .bdrv_close = raw_close,
1148 .bdrv_create = raw_create,
1149 .bdrv_co_discard = raw_co_discard,
1150 .bdrv_co_is_allocated = raw_co_is_allocated,
1151
1152 .bdrv_aio_readv = raw_aio_readv,
1153 .bdrv_aio_writev = raw_aio_writev,
1154 .bdrv_aio_flush = raw_aio_flush,
1155
1156 .bdrv_truncate = raw_truncate,
1157 .bdrv_getlength = raw_getlength,
1158 .bdrv_get_allocated_file_size
1159 = raw_get_allocated_file_size,
1160
1161 .create_options = raw_create_options,
1162 };
1163
1164 /***********************************************/
1165 /* host device */
1166
1167 #if defined(__APPLE__) && defined(__MACH__)
1168 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1169 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1170
1171 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1172 {
1173 kern_return_t kernResult;
1174 mach_port_t masterPort;
1175 CFMutableDictionaryRef classesToMatch;
1176
1177 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1178 if ( KERN_SUCCESS != kernResult ) {
1179 printf( "IOMasterPort returned %d\n", kernResult );
1180 }
1181
1182 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1183 if ( classesToMatch == NULL ) {
1184 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1185 } else {
1186 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1187 }
1188 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1189 if ( KERN_SUCCESS != kernResult )
1190 {
1191 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1192 }
1193
1194 return kernResult;
1195 }
1196
1197 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1198 {
1199 io_object_t nextMedia;
1200 kern_return_t kernResult = KERN_FAILURE;
1201 *bsdPath = '\0';
1202 nextMedia = IOIteratorNext( mediaIterator );
1203 if ( nextMedia )
1204 {
1205 CFTypeRef bsdPathAsCFString;
1206 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
1207 if ( bsdPathAsCFString ) {
1208 size_t devPathLength;
1209 strcpy( bsdPath, _PATH_DEV );
1210 strcat( bsdPath, "r" );
1211 devPathLength = strlen( bsdPath );
1212 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
1213 kernResult = KERN_SUCCESS;
1214 }
1215 CFRelease( bsdPathAsCFString );
1216 }
1217 IOObjectRelease( nextMedia );
1218 }
1219
1220 return kernResult;
1221 }
1222
1223 #endif
1224
1225 static int hdev_probe_device(const char *filename)
1226 {
1227 struct stat st;
1228
1229 /* allow a dedicated CD-ROM driver to match with a higher priority */
1230 if (strstart(filename, "/dev/cdrom", NULL))
1231 return 50;
1232
1233 if (stat(filename, &st) >= 0 &&
1234 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
1235 return 100;
1236 }
1237
1238 return 0;
1239 }
1240
1241 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
1242 {
1243 BDRVRawState *s = bs->opaque;
1244
1245 #if defined(__APPLE__) && defined(__MACH__)
1246 if (strstart(filename, "/dev/cdrom", NULL)) {
1247 kern_return_t kernResult;
1248 io_iterator_t mediaIterator;
1249 char bsdPath[ MAXPATHLEN ];
1250 int fd;
1251
1252 kernResult = FindEjectableCDMedia( &mediaIterator );
1253 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1254
1255 if ( bsdPath[ 0 ] != '\0' ) {
1256 strcat(bsdPath,"s0");
1257 /* some CDs don't have a partition 0 */
1258 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
1259 if (fd < 0) {
1260 bsdPath[strlen(bsdPath)-1] = '1';
1261 } else {
1262 qemu_close(fd);
1263 }
1264 filename = bsdPath;
1265 }
1266
1267 if ( mediaIterator )
1268 IOObjectRelease( mediaIterator );
1269 }
1270 #endif
1271
1272 s->type = FTYPE_FILE;
1273 #if defined(__linux__)
1274 {
1275 char resolved_path[ MAXPATHLEN ], *temp;
1276
1277 temp = realpath(filename, resolved_path);
1278 if (temp && strstart(temp, "/dev/sg", NULL)) {
1279 bs->sg = 1;
1280 }
1281 }
1282 #endif
1283
1284 return raw_open_common(bs, filename, flags, 0);
1285 }
1286
1287 #if defined(__linux__)
1288 /* Note: we do not have a reliable method to detect if the floppy is
1289 present. The current method is to try to open the floppy at every
1290 I/O and to keep it opened during a few hundreds of ms. */
1291 static int fd_open(BlockDriverState *bs)
1292 {
1293 BDRVRawState *s = bs->opaque;
1294 int last_media_present;
1295
1296 if (s->type != FTYPE_FD)
1297 return 0;
1298 last_media_present = (s->fd >= 0);
1299 if (s->fd >= 0 &&
1300 (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1301 qemu_close(s->fd);
1302 s->fd = -1;
1303 #ifdef DEBUG_FLOPPY
1304 printf("Floppy closed\n");
1305 #endif
1306 }
1307 if (s->fd < 0) {
1308 if (s->fd_got_error &&
1309 (get_clock() - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1310 #ifdef DEBUG_FLOPPY
1311 printf("No floppy (open delayed)\n");
1312 #endif
1313 return -EIO;
1314 }
1315 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
1316 if (s->fd < 0) {
1317 s->fd_error_time = get_clock();
1318 s->fd_got_error = 1;
1319 if (last_media_present)
1320 s->fd_media_changed = 1;
1321 #ifdef DEBUG_FLOPPY
1322 printf("No floppy\n");
1323 #endif
1324 return -EIO;
1325 }
1326 #ifdef DEBUG_FLOPPY
1327 printf("Floppy opened\n");
1328 #endif
1329 }
1330 if (!last_media_present)
1331 s->fd_media_changed = 1;
1332 s->fd_open_time = get_clock();
1333 s->fd_got_error = 0;
1334 return 0;
1335 }
1336
1337 static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1338 {
1339 BDRVRawState *s = bs->opaque;
1340
1341 return ioctl(s->fd, req, buf);
1342 }
1343
1344 static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
1345 unsigned long int req, void *buf,
1346 BlockDriverCompletionFunc *cb, void *opaque)
1347 {
1348 BDRVRawState *s = bs->opaque;
1349
1350 if (fd_open(bs) < 0)
1351 return NULL;
1352 return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
1353 }
1354
1355 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1356 static int fd_open(BlockDriverState *bs)
1357 {
1358 BDRVRawState *s = bs->opaque;
1359
1360 /* this is just to ensure s->fd is sane (its called by io ops) */
1361 if (s->fd >= 0)
1362 return 0;
1363 return -EIO;
1364 }
1365 #else /* !linux && !FreeBSD */
1366
1367 static int fd_open(BlockDriverState *bs)
1368 {
1369 return 0;
1370 }
1371
1372 #endif /* !linux && !FreeBSD */
1373
1374 static int hdev_create(const char *filename, QEMUOptionParameter *options)
1375 {
1376 int fd;
1377 int ret = 0;
1378 struct stat stat_buf;
1379 int64_t total_size = 0;
1380
1381 /* Read out options */
1382 while (options && options->name) {
1383 if (!strcmp(options->name, "size")) {
1384 total_size = options->value.n / BDRV_SECTOR_SIZE;
1385 }
1386 options++;
1387 }
1388
1389 fd = qemu_open(filename, O_WRONLY | O_BINARY);
1390 if (fd < 0)
1391 return -errno;
1392
1393 if (fstat(fd, &stat_buf) < 0)
1394 ret = -errno;
1395 else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode))
1396 ret = -ENODEV;
1397 else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
1398 ret = -ENOSPC;
1399
1400 qemu_close(fd);
1401 return ret;
1402 }
1403
1404 static int hdev_has_zero_init(BlockDriverState *bs)
1405 {
1406 return 0;
1407 }
1408
1409 static BlockDriver bdrv_host_device = {
1410 .format_name = "host_device",
1411 .protocol_name = "host_device",
1412 .instance_size = sizeof(BDRVRawState),
1413 .bdrv_probe_device = hdev_probe_device,
1414 .bdrv_file_open = hdev_open,
1415 .bdrv_close = raw_close,
1416 .bdrv_reopen_prepare = raw_reopen_prepare,
1417 .bdrv_reopen_commit = raw_reopen_commit,
1418 .bdrv_reopen_abort = raw_reopen_abort,
1419 .bdrv_create = hdev_create,
1420 .create_options = raw_create_options,
1421 .bdrv_has_zero_init = hdev_has_zero_init,
1422
1423 .bdrv_aio_readv = raw_aio_readv,
1424 .bdrv_aio_writev = raw_aio_writev,
1425 .bdrv_aio_flush = raw_aio_flush,
1426
1427 .bdrv_truncate = raw_truncate,
1428 .bdrv_getlength = raw_getlength,
1429 .bdrv_get_allocated_file_size
1430 = raw_get_allocated_file_size,
1431
1432 /* generic scsi device */
1433 #ifdef __linux__
1434 .bdrv_ioctl = hdev_ioctl,
1435 .bdrv_aio_ioctl = hdev_aio_ioctl,
1436 #endif
1437 };
1438
1439 #ifdef __linux__
1440 static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
1441 {
1442 BDRVRawState *s = bs->opaque;
1443 int ret;
1444
1445 s->type = FTYPE_FD;
1446
1447 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1448 ret = raw_open_common(bs, filename, flags, O_NONBLOCK);
1449 if (ret)
1450 return ret;
1451
1452 /* close fd so that we can reopen it as needed */
1453 qemu_close(s->fd);
1454 s->fd = -1;
1455 s->fd_media_changed = 1;
1456
1457 return 0;
1458 }
1459
1460 static int floppy_probe_device(const char *filename)
1461 {
1462 int fd, ret;
1463 int prio = 0;
1464 struct floppy_struct fdparam;
1465 struct stat st;
1466
1467 if (strstart(filename, "/dev/fd", NULL) &&
1468 !strstart(filename, "/dev/fdset/", NULL)) {
1469 prio = 50;
1470 }
1471
1472 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1473 if (fd < 0) {
1474 goto out;
1475 }
1476 ret = fstat(fd, &st);
1477 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1478 goto outc;
1479 }
1480
1481 /* Attempt to detect via a floppy specific ioctl */
1482 ret = ioctl(fd, FDGETPRM, &fdparam);
1483 if (ret >= 0)
1484 prio = 100;
1485
1486 outc:
1487 qemu_close(fd);
1488 out:
1489 return prio;
1490 }
1491
1492
1493 static int floppy_is_inserted(BlockDriverState *bs)
1494 {
1495 return fd_open(bs) >= 0;
1496 }
1497
1498 static int floppy_media_changed(BlockDriverState *bs)
1499 {
1500 BDRVRawState *s = bs->opaque;
1501 int ret;
1502
1503 /*
1504 * XXX: we do not have a true media changed indication.
1505 * It does not work if the floppy is changed without trying to read it.
1506 */
1507 fd_open(bs);
1508 ret = s->fd_media_changed;
1509 s->fd_media_changed = 0;
1510 #ifdef DEBUG_FLOPPY
1511 printf("Floppy changed=%d\n", ret);
1512 #endif
1513 return ret;
1514 }
1515
1516 static void floppy_eject(BlockDriverState *bs, bool eject_flag)
1517 {
1518 BDRVRawState *s = bs->opaque;
1519 int fd;
1520
1521 if (s->fd >= 0) {
1522 qemu_close(s->fd);
1523 s->fd = -1;
1524 }
1525 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
1526 if (fd >= 0) {
1527 if (ioctl(fd, FDEJECT, 0) < 0)
1528 perror("FDEJECT");
1529 qemu_close(fd);
1530 }
1531 }
1532
1533 static BlockDriver bdrv_host_floppy = {
1534 .format_name = "host_floppy",
1535 .protocol_name = "host_floppy",
1536 .instance_size = sizeof(BDRVRawState),
1537 .bdrv_probe_device = floppy_probe_device,
1538 .bdrv_file_open = floppy_open,
1539 .bdrv_close = raw_close,
1540 .bdrv_reopen_prepare = raw_reopen_prepare,
1541 .bdrv_reopen_commit = raw_reopen_commit,
1542 .bdrv_reopen_abort = raw_reopen_abort,
1543 .bdrv_create = hdev_create,
1544 .create_options = raw_create_options,
1545 .bdrv_has_zero_init = hdev_has_zero_init,
1546
1547 .bdrv_aio_readv = raw_aio_readv,
1548 .bdrv_aio_writev = raw_aio_writev,
1549 .bdrv_aio_flush = raw_aio_flush,
1550
1551 .bdrv_truncate = raw_truncate,
1552 .bdrv_getlength = raw_getlength,
1553 .bdrv_get_allocated_file_size
1554 = raw_get_allocated_file_size,
1555
1556 /* removable device support */
1557 .bdrv_is_inserted = floppy_is_inserted,
1558 .bdrv_media_changed = floppy_media_changed,
1559 .bdrv_eject = floppy_eject,
1560 };
1561
1562 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1563 {
1564 BDRVRawState *s = bs->opaque;
1565
1566 s->type = FTYPE_CD;
1567
1568 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1569 return raw_open_common(bs, filename, flags, O_NONBLOCK);
1570 }
1571
1572 static int cdrom_probe_device(const char *filename)
1573 {
1574 int fd, ret;
1575 int prio = 0;
1576 struct stat st;
1577
1578 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
1579 if (fd < 0) {
1580 goto out;
1581 }
1582 ret = fstat(fd, &st);
1583 if (ret == -1 || !S_ISBLK(st.st_mode)) {
1584 goto outc;
1585 }
1586
1587 /* Attempt to detect via a CDROM specific ioctl */
1588 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1589 if (ret >= 0)
1590 prio = 100;
1591
1592 outc:
1593 qemu_close(fd);
1594 out:
1595 return prio;
1596 }
1597
1598 static int cdrom_is_inserted(BlockDriverState *bs)
1599 {
1600 BDRVRawState *s = bs->opaque;
1601 int ret;
1602
1603 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1604 if (ret == CDS_DISC_OK)
1605 return 1;
1606 return 0;
1607 }
1608
1609 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1610 {
1611 BDRVRawState *s = bs->opaque;
1612
1613 if (eject_flag) {
1614 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
1615 perror("CDROMEJECT");
1616 } else {
1617 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
1618 perror("CDROMEJECT");
1619 }
1620 }
1621
1622 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1623 {
1624 BDRVRawState *s = bs->opaque;
1625
1626 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
1627 /*
1628 * Note: an error can happen if the distribution automatically
1629 * mounts the CD-ROM
1630 */
1631 /* perror("CDROM_LOCKDOOR"); */
1632 }
1633 }
1634
1635 static BlockDriver bdrv_host_cdrom = {
1636 .format_name = "host_cdrom",
1637 .protocol_name = "host_cdrom",
1638 .instance_size = sizeof(BDRVRawState),
1639 .bdrv_probe_device = cdrom_probe_device,
1640 .bdrv_file_open = cdrom_open,
1641 .bdrv_close = raw_close,
1642 .bdrv_reopen_prepare = raw_reopen_prepare,
1643 .bdrv_reopen_commit = raw_reopen_commit,
1644 .bdrv_reopen_abort = raw_reopen_abort,
1645 .bdrv_create = hdev_create,
1646 .create_options = raw_create_options,
1647 .bdrv_has_zero_init = hdev_has_zero_init,
1648
1649 .bdrv_aio_readv = raw_aio_readv,
1650 .bdrv_aio_writev = raw_aio_writev,
1651 .bdrv_aio_flush = raw_aio_flush,
1652
1653 .bdrv_truncate = raw_truncate,
1654 .bdrv_getlength = raw_getlength,
1655 .bdrv_get_allocated_file_size
1656 = raw_get_allocated_file_size,
1657
1658 /* removable device support */
1659 .bdrv_is_inserted = cdrom_is_inserted,
1660 .bdrv_eject = cdrom_eject,
1661 .bdrv_lock_medium = cdrom_lock_medium,
1662
1663 /* generic scsi device */
1664 .bdrv_ioctl = hdev_ioctl,
1665 .bdrv_aio_ioctl = hdev_aio_ioctl,
1666 };
1667 #endif /* __linux__ */
1668
1669 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1670 static int cdrom_open(BlockDriverState *bs, const char *filename, int flags)
1671 {
1672 BDRVRawState *s = bs->opaque;
1673 int ret;
1674
1675 s->type = FTYPE_CD;
1676
1677 ret = raw_open_common(bs, filename, flags, 0);
1678 if (ret)
1679 return ret;
1680
1681 /* make sure the door isn't locked at this time */
1682 ioctl(s->fd, CDIOCALLOW);
1683 return 0;
1684 }
1685
1686 static int cdrom_probe_device(const char *filename)
1687 {
1688 if (strstart(filename, "/dev/cd", NULL) ||
1689 strstart(filename, "/dev/acd", NULL))
1690 return 100;
1691 return 0;
1692 }
1693
1694 static int cdrom_reopen(BlockDriverState *bs)
1695 {
1696 BDRVRawState *s = bs->opaque;
1697 int fd;
1698
1699 /*
1700 * Force reread of possibly changed/newly loaded disc,
1701 * FreeBSD seems to not notice sometimes...
1702 */
1703 if (s->fd >= 0)
1704 qemu_close(s->fd);
1705 fd = qemu_open(bs->filename, s->open_flags, 0644);
1706 if (fd < 0) {
1707 s->fd = -1;
1708 return -EIO;
1709 }
1710 s->fd = fd;
1711
1712 /* make sure the door isn't locked at this time */
1713 ioctl(s->fd, CDIOCALLOW);
1714 return 0;
1715 }
1716
1717 static int cdrom_is_inserted(BlockDriverState *bs)
1718 {
1719 return raw_getlength(bs) > 0;
1720 }
1721
1722 static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
1723 {
1724 BDRVRawState *s = bs->opaque;
1725
1726 if (s->fd < 0)
1727 return;
1728
1729 (void) ioctl(s->fd, CDIOCALLOW);
1730
1731 if (eject_flag) {
1732 if (ioctl(s->fd, CDIOCEJECT) < 0)
1733 perror("CDIOCEJECT");
1734 } else {
1735 if (ioctl(s->fd, CDIOCCLOSE) < 0)
1736 perror("CDIOCCLOSE");
1737 }
1738
1739 cdrom_reopen(bs);
1740 }
1741
1742 static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
1743 {
1744 BDRVRawState *s = bs->opaque;
1745
1746 if (s->fd < 0)
1747 return;
1748 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1749 /*
1750 * Note: an error can happen if the distribution automatically
1751 * mounts the CD-ROM
1752 */
1753 /* perror("CDROM_LOCKDOOR"); */
1754 }
1755 }
1756
1757 static BlockDriver bdrv_host_cdrom = {
1758 .format_name = "host_cdrom",
1759 .protocol_name = "host_cdrom",
1760 .instance_size = sizeof(BDRVRawState),
1761 .bdrv_probe_device = cdrom_probe_device,
1762 .bdrv_file_open = cdrom_open,
1763 .bdrv_close = raw_close,
1764 .bdrv_reopen_prepare = raw_reopen_prepare,
1765 .bdrv_reopen_commit = raw_reopen_commit,
1766 .bdrv_reopen_abort = raw_reopen_abort,
1767 .bdrv_create = hdev_create,
1768 .create_options = raw_create_options,
1769 .bdrv_has_zero_init = hdev_has_zero_init,
1770
1771 .bdrv_aio_readv = raw_aio_readv,
1772 .bdrv_aio_writev = raw_aio_writev,
1773 .bdrv_aio_flush = raw_aio_flush,
1774
1775 .bdrv_truncate = raw_truncate,
1776 .bdrv_getlength = raw_getlength,
1777 .bdrv_get_allocated_file_size
1778 = raw_get_allocated_file_size,
1779
1780 /* removable device support */
1781 .bdrv_is_inserted = cdrom_is_inserted,
1782 .bdrv_eject = cdrom_eject,
1783 .bdrv_lock_medium = cdrom_lock_medium,
1784 };
1785 #endif /* __FreeBSD__ */
1786
1787 static void bdrv_file_init(void)
1788 {
1789 /*
1790 * Register all the drivers. Note that order is important, the driver
1791 * registered last will get probed first.
1792 */
1793 bdrv_register(&bdrv_file);
1794 bdrv_register(&bdrv_host_device);
1795 #ifdef __linux__
1796 bdrv_register(&bdrv_host_floppy);
1797 bdrv_register(&bdrv_host_cdrom);
1798 #endif
1799 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1800 bdrv_register(&bdrv_host_cdrom);
1801 #endif
1802 }
1803
1804 block_init(bdrv_file_init);