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