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