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