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