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