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