]> Git Repo - qemu.git/blame - block/raw-posix.c
block/raw-posix: Don't think /dev/fd/<NN> is a floppy drive.
[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"
d49b6836 25#include "qemu/error-report.h"
1de7afc9
PB
26#include "qemu/timer.h"
27#include "qemu/log.h"
737e150e 28#include "block/block_int.h"
1de7afc9 29#include "qemu/module.h"
de81a169 30#include "trace.h"
737e150e 31#include "block/thread-pool.h"
1de7afc9 32#include "qemu/iov.h"
9f8540ec 33#include "raw-aio.h"
06247428 34#include "qapi/util.h"
d49b6836 35#include "qapi/qmp/qstring.h"
83f64091 36
83affaa6 37#if defined(__APPLE__) && (__MACH__)
83f64091
FB
38#include <paths.h>
39#include <sys/param.h>
40#include <IOKit/IOKitLib.h>
41#include <IOKit/IOBSD.h>
42#include <IOKit/storage/IOMediaBSDClient.h>
43#include <IOKit/storage/IOMedia.h>
44#include <IOKit/storage/IOCDMedia.h>
45//#include <IOKit/storage/IOCDTypes.h>
46#include <CoreFoundation/CoreFoundation.h>
47#endif
48
49#ifdef __sun__
2e9671da 50#define _POSIX_PTHREAD_SEMANTICS 1
83f64091
FB
51#include <sys/dkio.h>
52#endif
19cb3738 53#ifdef __linux__
343f8568
JS
54#include <sys/types.h>
55#include <sys/stat.h>
19cb3738 56#include <sys/ioctl.h>
05acda4d 57#include <sys/param.h>
19cb3738
FB
58#include <linux/cdrom.h>
59#include <linux/fd.h>
5500316d 60#include <linux/fs.h>
1a9335e4 61#include <linux/hdreg.h>
3307ed7b 62#include <scsi/sg.h>
1a9335e4
ET
63#ifdef __s390__
64#include <asm/dasd.h>
65#endif
4ab15590
CL
66#ifndef FS_NOCOW_FL
67#define FS_NOCOW_FL 0x00800000 /* Do not cow file */
68#endif
5500316d 69#endif
b953f075 70#if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
3d4fa43e
KK
71#include <linux/falloc.h>
72#endif
a167ba50 73#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1cb6c3fd 74#include <sys/disk.h>
9f23011a 75#include <sys/cdio.h>
1cb6c3fd 76#endif
83f64091 77
128ab2ff
BS
78#ifdef __OpenBSD__
79#include <sys/ioctl.h>
80#include <sys/disklabel.h>
81#include <sys/dkio.h>
82#endif
83
d1f6fd8d
CE
84#ifdef __NetBSD__
85#include <sys/ioctl.h>
86#include <sys/disklabel.h>
87#include <sys/dkio.h>
88#include <sys/disk.h>
89#endif
90
c5e97233
BS
91#ifdef __DragonFly__
92#include <sys/ioctl.h>
93#include <sys/diskslice.h>
94#endif
95
dce512de
CH
96#ifdef CONFIG_XFS
97#include <xfs/xfs.h>
98#endif
99
faf07963 100//#define DEBUG_BLOCK
bcb22555
DA
101
102#ifdef DEBUG_BLOCK
103# define DEBUG_BLOCK_PRINT 1
8c05dbf9 104#else
bcb22555 105# define DEBUG_BLOCK_PRINT 0
8c05dbf9 106#endif
bcb22555
DA
107#define DPRINTF(fmt, ...) \
108do { \
109 if (DEBUG_BLOCK_PRINT) { \
110 printf(fmt, ## __VA_ARGS__); \
111 } \
112} while (0)
8c05dbf9 113
f6465578
AL
114/* OS X does not have O_DSYNC */
115#ifndef O_DSYNC
1c27a8b3 116#ifdef O_SYNC
7ab064d2 117#define O_DSYNC O_SYNC
1c27a8b3
JA
118#elif defined(O_FSYNC)
119#define O_DSYNC O_FSYNC
120#endif
f6465578
AL
121#endif
122
9f7965c7
AL
123/* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
124#ifndef O_DIRECT
125#define O_DIRECT O_DSYNC
126#endif
127
19cb3738
FB
128#define FTYPE_FILE 0
129#define FTYPE_CD 1
130#define FTYPE_FD 2
83f64091 131
c57c846a 132/* if the FD is not accessed during that time (in ns), we try to
19cb3738 133 reopen it to see if the disk has been changed */
c57c846a 134#define FD_OPEN_TIMEOUT (1000000000)
83f64091 135
581b9e29
CH
136#define MAX_BLOCKSIZE 4096
137
19cb3738
FB
138typedef struct BDRVRawState {
139 int fd;
140 int type;
0e1d8f4c 141 int open_flags;
c25f53b0
PB
142 size_t buf_align;
143
19cb3738
FB
144#if defined(__linux__)
145 /* linux floppy specific */
19cb3738
FB
146 int64_t fd_open_time;
147 int64_t fd_error_time;
148 int fd_got_error;
149 int fd_media_changed;
83f64091 150#endif
e44bd6fc 151#ifdef CONFIG_LINUX_AIO
5c6c3a6c 152 int use_aio;
1e5b9d2f 153 void *aio_ctx;
e44bd6fc 154#endif
dce512de 155#ifdef CONFIG_XFS
260a82e5 156 bool is_xfs:1;
dce512de 157#endif
260a82e5 158 bool has_discard:1;
97a2ae34 159 bool has_write_zeroes:1;
260a82e5 160 bool discard_zeroes:1;
d50d8222 161 bool has_fallocate;
3cad8307 162 bool needs_alignment;
19cb3738
FB
163} BDRVRawState;
164
eeb6b45d
JC
165typedef struct BDRVRawReopenState {
166 int fd;
167 int open_flags;
168#ifdef CONFIG_LINUX_AIO
169 int use_aio;
170#endif
171} BDRVRawReopenState;
172
19cb3738 173static int fd_open(BlockDriverState *bs);
22afa7b5 174static int64_t raw_getlength(BlockDriverState *bs);
83f64091 175
de81a169
PB
176typedef struct RawPosixAIOData {
177 BlockDriverState *bs;
178 int aio_fildes;
179 union {
180 struct iovec *aio_iov;
181 void *aio_ioctl_buf;
182 };
183 int aio_niov;
8238010b 184 uint64_t aio_nbytes;
de81a169
PB
185#define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
186 off_t aio_offset;
187 int aio_type;
188} RawPosixAIOData;
189
a167ba50 190#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8 191static int cdrom_reopen(BlockDriverState *bs);
9f23011a
BS
192#endif
193
1de1ae0a
CE
194#if defined(__NetBSD__)
195static int raw_normalize_devicepath(const char **filename)
196{
197 static char namebuf[PATH_MAX];
198 const char *dp, *fname;
199 struct stat sb;
200
201 fname = *filename;
202 dp = strrchr(fname, '/');
203 if (lstat(fname, &sb) < 0) {
204 fprintf(stderr, "%s: stat failed: %s\n",
205 fname, strerror(errno));
206 return -errno;
207 }
208
209 if (!S_ISBLK(sb.st_mode)) {
210 return 0;
211 }
212
213 if (dp == NULL) {
214 snprintf(namebuf, PATH_MAX, "r%s", fname);
215 } else {
216 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
217 (int)(dp - fname), fname, dp + 1);
218 }
219 fprintf(stderr, "%s is a block device", fname);
220 *filename = namebuf;
221 fprintf(stderr, ", using %s\n", *filename);
222
223 return 0;
224}
225#else
226static int raw_normalize_devicepath(const char **filename)
227{
228 return 0;
229}
230#endif
231
8a4ed0d1
ET
232/*
233 * Get logical block size via ioctl. On success store it in @sector_size_p.
234 */
235static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
c25f53b0 236{
c25f53b0 237 unsigned int sector_size;
8a4ed0d1 238 bool success = false;
c25f53b0 239
8a4ed0d1 240 errno = ENOTSUP;
c25f53b0
PB
241
242 /* Try a few ioctls to get the right size */
c25f53b0 243#ifdef BLKSSZGET
df26a350 244 if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
8a4ed0d1
ET
245 *sector_size_p = sector_size;
246 success = true;
c25f53b0
PB
247 }
248#endif
249#ifdef DKIOCGETBLOCKSIZE
df26a350 250 if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
8a4ed0d1
ET
251 *sector_size_p = sector_size;
252 success = true;
c25f53b0
PB
253 }
254#endif
255#ifdef DIOCGSECTORSIZE
df26a350 256 if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
8a4ed0d1
ET
257 *sector_size_p = sector_size;
258 success = true;
c25f53b0
PB
259 }
260#endif
8a4ed0d1
ET
261
262 return success ? 0 : -errno;
263}
264
1a9335e4
ET
265/**
266 * Get physical block size of @fd.
267 * On success, store it in @blk_size and return 0.
268 * On failure, return -errno.
269 */
270static int probe_physical_blocksize(int fd, unsigned int *blk_size)
271{
272#ifdef BLKPBSZGET
273 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
274 return -errno;
275 }
276 return 0;
277#else
278 return -ENOTSUP;
279#endif
280}
281
22d182e8
SH
282/* Check if read is allowed with given memory buffer and length.
283 *
284 * This function is used to check O_DIRECT memory buffer and request alignment.
285 */
286static bool raw_is_io_aligned(int fd, void *buf, size_t len)
287{
288 ssize_t ret = pread(fd, buf, len, 0);
289
290 if (ret >= 0) {
291 return true;
292 }
293
294#ifdef __linux__
295 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
296 * other errors (e.g. real I/O error), which could happen on a failed
297 * drive, since we only care about probing alignment.
298 */
299 if (errno != EINVAL) {
300 return true;
301 }
302#endif
303
304 return false;
305}
306
8a4ed0d1
ET
307static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
308{
309 BDRVRawState *s = bs->opaque;
310 char *buf;
459b4e66 311 size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
8a4ed0d1 312
b192af8a 313 /* For SCSI generic devices the alignment is not really used.
8a4ed0d1 314 With buffered I/O, we don't have any restrictions. */
b192af8a 315 if (bdrv_is_sg(bs) || !s->needs_alignment) {
8a4ed0d1
ET
316 bs->request_alignment = 1;
317 s->buf_align = 1;
318 return;
319 }
320
321 bs->request_alignment = 0;
322 s->buf_align = 0;
323 /* Let's try to use the logical blocksize for the alignment. */
324 if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {
325 bs->request_alignment = 0;
326 }
c25f53b0
PB
327#ifdef CONFIG_XFS
328 if (s->is_xfs) {
329 struct dioattr da;
df26a350 330 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
c25f53b0
PB
331 bs->request_alignment = da.d_miniosz;
332 /* The kernel returns wrong information for d_mem */
333 /* s->buf_align = da.d_mem; */
334 }
335 }
336#endif
337
338 /* If we could not get the sizes so far, we can only guess them */
339 if (!s->buf_align) {
340 size_t align;
459b4e66
DL
341 buf = qemu_memalign(max_align, 2 * max_align);
342 for (align = 512; align <= max_align; align <<= 1) {
343 if (raw_is_io_aligned(fd, buf + align, max_align)) {
c25f53b0
PB
344 s->buf_align = align;
345 break;
346 }
347 }
348 qemu_vfree(buf);
349 }
350
351 if (!bs->request_alignment) {
352 size_t align;
459b4e66
DL
353 buf = qemu_memalign(s->buf_align, max_align);
354 for (align = 512; align <= max_align; align <<= 1) {
22d182e8 355 if (raw_is_io_aligned(fd, buf, align)) {
c25f53b0
PB
356 bs->request_alignment = align;
357 break;
358 }
359 }
360 qemu_vfree(buf);
361 }
df26a350
KW
362
363 if (!s->buf_align || !bs->request_alignment) {
364 error_setg(errp, "Could not find working O_DIRECT alignment. "
365 "Try cache.direct=off.");
366 }
c25f53b0
PB
367}
368
6a8dc042
JC
369static void raw_parse_flags(int bdrv_flags, int *open_flags)
370{
371 assert(open_flags != NULL);
372
373 *open_flags |= O_BINARY;
374 *open_flags &= ~O_ACCMODE;
375 if (bdrv_flags & BDRV_O_RDWR) {
376 *open_flags |= O_RDWR;
377 } else {
378 *open_flags |= O_RDONLY;
379 }
380
381 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
382 * and O_DIRECT for no caching. */
383 if ((bdrv_flags & BDRV_O_NOCACHE)) {
384 *open_flags |= O_DIRECT;
385 }
6a8dc042
JC
386}
387
c2f3426c
SH
388static void raw_detach_aio_context(BlockDriverState *bs)
389{
390#ifdef CONFIG_LINUX_AIO
391 BDRVRawState *s = bs->opaque;
392
393 if (s->use_aio) {
394 laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
395 }
396#endif
397}
398
399static void raw_attach_aio_context(BlockDriverState *bs,
400 AioContext *new_context)
401{
402#ifdef CONFIG_LINUX_AIO
403 BDRVRawState *s = bs->opaque;
404
405 if (s->use_aio) {
406 laio_attach_aio_context(s->aio_ctx, new_context);
407 }
408#endif
409}
410
fc32a72d
JC
411#ifdef CONFIG_LINUX_AIO
412static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
413{
414 int ret = -1;
415 assert(aio_ctx != NULL);
416 assert(use_aio != NULL);
417 /*
418 * Currently Linux do AIO only for files opened with O_DIRECT
419 * specified so check NOCACHE flag too
420 */
421 if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
422 (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
423
424 /* if non-NULL, laio_init() has already been run */
425 if (*aio_ctx == NULL) {
426 *aio_ctx = laio_init();
427 if (!*aio_ctx) {
428 goto error;
429 }
430 }
431 *use_aio = 1;
432 } else {
433 *use_aio = 0;
434 }
435
436 ret = 0;
437
438error:
439 return ret;
440}
441#endif
442
078896a9
HR
443static void raw_parse_filename(const char *filename, QDict *options,
444 Error **errp)
445{
446 /* The filename does not have to be prefixed by the protocol name, since
447 * "file" is the default protocol; therefore, the return value of this
448 * function call can be ignored. */
449 strstart(filename, "file:", &filename);
450
451 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
452}
453
c66a6157
KW
454static QemuOptsList raw_runtime_opts = {
455 .name = "raw",
456 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
457 .desc = {
458 {
459 .name = "filename",
460 .type = QEMU_OPT_STRING,
461 .help = "File name of the image",
462 },
463 { /* end of list */ }
464 },
465};
466
467static int raw_open_common(BlockDriverState *bs, QDict *options,
e428e439 468 int bdrv_flags, int open_flags, Error **errp)
83f64091
FB
469{
470 BDRVRawState *s = bs->opaque;
c66a6157
KW
471 QemuOpts *opts;
472 Error *local_err = NULL;
8bfea15d 473 const char *filename = NULL;
0e1d8f4c 474 int fd, ret;
260a82e5 475 struct stat st;
83f64091 476
87ea75d5 477 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
c66a6157 478 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 479 if (local_err) {
e428e439 480 error_propagate(errp, local_err);
c66a6157
KW
481 ret = -EINVAL;
482 goto fail;
483 }
484
485 filename = qemu_opt_get(opts, "filename");
486
1de1ae0a
CE
487 ret = raw_normalize_devicepath(&filename);
488 if (ret != 0) {
e428e439 489 error_setg_errno(errp, -ret, "Could not normalize device path");
c66a6157 490 goto fail;
1de1ae0a
CE
491 }
492
6a8dc042
JC
493 s->open_flags = open_flags;
494 raw_parse_flags(bdrv_flags, &s->open_flags);
83f64091 495
90babde0 496 s->fd = -1;
40ff6d7e 497 fd = qemu_open(filename, s->open_flags, 0644);
19cb3738
FB
498 if (fd < 0) {
499 ret = -errno;
c66a6157 500 if (ret == -EROFS) {
19cb3738 501 ret = -EACCES;
c66a6157
KW
502 }
503 goto fail;
19cb3738 504 }
83f64091 505 s->fd = fd;
9ef91a67 506
5c6c3a6c 507#ifdef CONFIG_LINUX_AIO
fc32a72d 508 if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
47e6b251 509 qemu_close(fd);
c66a6157 510 ret = -errno;
e428e439 511 error_setg_errno(errp, -ret, "Could not set AIO state");
c66a6157 512 goto fail;
9ef91a67 513 }
96518254
KW
514 if (!s->use_aio && (bdrv_flags & BDRV_O_NATIVE_AIO)) {
515 error_printf("WARNING: aio=native was specified for '%s', but "
516 "it requires cache.direct=on, which was not "
517 "specified. Falling back to aio=threads.\n"
518 " This will become an error condition in "
519 "future QEMU versions.\n",
520 bs->filename);
521 }
fc32a72d 522#endif
9ef91a67 523
7ce21016 524 s->has_discard = true;
97a2ae34 525 s->has_write_zeroes = true;
3cad8307
RPM
526 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
527 s->needs_alignment = true;
528 }
260a82e5
PB
529
530 if (fstat(s->fd, &st) < 0) {
01212d4e 531 ret = -errno;
260a82e5
PB
532 error_setg_errno(errp, errno, "Could not stat file");
533 goto fail;
534 }
535 if (S_ISREG(st.st_mode)) {
536 s->discard_zeroes = true;
d50d8222 537 s->has_fallocate = true;
260a82e5 538 }
d0b4503e
PB
539 if (S_ISBLK(st.st_mode)) {
540#ifdef BLKDISCARDZEROES
541 unsigned int arg;
542 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
543 s->discard_zeroes = true;
544 }
545#endif
546#ifdef __linux__
547 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
548 * not rely on the contents of discarded blocks unless using O_DIRECT.
97a2ae34 549 * Same for BLKZEROOUT.
d0b4503e
PB
550 */
551 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
552 s->discard_zeroes = false;
97a2ae34 553 s->has_write_zeroes = false;
d0b4503e
PB
554 }
555#endif
556 }
3cad8307
RPM
557#ifdef __FreeBSD__
558 if (S_ISCHR(st.st_mode)) {
559 /*
560 * The file is a char device (disk), which on FreeBSD isn't behind
561 * a pager, so force all requests to be aligned. This is needed
562 * so QEMU makes sure all IO operations on the device are aligned
563 * to sector size, or else FreeBSD will reject them with EINVAL.
564 */
565 s->needs_alignment = true;
566 }
567#endif
260a82e5 568
dce512de
CH
569#ifdef CONFIG_XFS
570 if (platform_test_xfs_fd(s->fd)) {
7ce21016 571 s->is_xfs = true;
dce512de
CH
572 }
573#endif
574
c2f3426c
SH
575 raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
576
c66a6157
KW
577 ret = 0;
578fail:
8bfea15d
KW
579 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
580 unlink(filename);
581 }
c66a6157
KW
582 qemu_opts_del(opts);
583 return ret;
83f64091
FB
584}
585
015a1036
HR
586static int raw_open(BlockDriverState *bs, QDict *options, int flags,
587 Error **errp)
90babde0
CH
588{
589 BDRVRawState *s = bs->opaque;
e428e439
HR
590 Error *local_err = NULL;
591 int ret;
90babde0
CH
592
593 s->type = FTYPE_FILE;
e428e439 594 ret = raw_open_common(bs, options, flags, 0, &local_err);
84d18f06 595 if (local_err) {
e428e439
HR
596 error_propagate(errp, local_err);
597 }
598 return ret;
90babde0
CH
599}
600
eeb6b45d
JC
601static int raw_reopen_prepare(BDRVReopenState *state,
602 BlockReopenQueue *queue, Error **errp)
603{
604 BDRVRawState *s;
605 BDRVRawReopenState *raw_s;
606 int ret = 0;
df26a350 607 Error *local_err = NULL;
eeb6b45d
JC
608
609 assert(state != NULL);
610 assert(state->bs != NULL);
611
612 s = state->bs->opaque;
613
5839e53b 614 state->opaque = g_new0(BDRVRawReopenState, 1);
eeb6b45d
JC
615 raw_s = state->opaque;
616
617#ifdef CONFIG_LINUX_AIO
618 raw_s->use_aio = s->use_aio;
619
620 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
621 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
622 * won't override aio_ctx if aio_ctx is non-NULL */
623 if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
e428e439 624 error_setg(errp, "Could not set AIO state");
eeb6b45d
JC
625 return -1;
626 }
627#endif
628
1bc6b705
JC
629 if (s->type == FTYPE_FD || s->type == FTYPE_CD) {
630 raw_s->open_flags |= O_NONBLOCK;
631 }
632
eeb6b45d
JC
633 raw_parse_flags(state->flags, &raw_s->open_flags);
634
635 raw_s->fd = -1;
636
fdf263f6 637 int fcntl_flags = O_APPEND | O_NONBLOCK;
eeb6b45d
JC
638#ifdef O_NOATIME
639 fcntl_flags |= O_NOATIME;
640#endif
641
fdf263f6
AF
642#ifdef O_ASYNC
643 /* Not all operating systems have O_ASYNC, and those that don't
644 * will not let us track the state into raw_s->open_flags (typically
645 * you achieve the same effect with an ioctl, for example I_SETSIG
646 * on Solaris). But we do not use O_ASYNC, so that's fine.
647 */
648 assert((s->open_flags & O_ASYNC) == 0);
649#endif
650
eeb6b45d
JC
651 if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
652 /* dup the original fd */
653 /* TODO: use qemu fcntl wrapper */
654#ifdef F_DUPFD_CLOEXEC
655 raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
656#else
657 raw_s->fd = dup(s->fd);
658 if (raw_s->fd != -1) {
659 qemu_set_cloexec(raw_s->fd);
660 }
661#endif
662 if (raw_s->fd >= 0) {
663 ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
664 if (ret) {
665 qemu_close(raw_s->fd);
666 raw_s->fd = -1;
667 }
668 }
669 }
670
671 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
672 if (raw_s->fd == -1) {
673 assert(!(raw_s->open_flags & O_CREAT));
674 raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);
675 if (raw_s->fd == -1) {
e428e439 676 error_setg_errno(errp, errno, "Could not reopen file");
eeb6b45d
JC
677 ret = -1;
678 }
679 }
df26a350
KW
680
681 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
682 * alignment with the new fd. */
683 if (raw_s->fd != -1) {
684 raw_probe_alignment(state->bs, raw_s->fd, &local_err);
685 if (local_err) {
686 qemu_close(raw_s->fd);
687 raw_s->fd = -1;
688 error_propagate(errp, local_err);
689 ret = -EINVAL;
690 }
691 }
692
eeb6b45d
JC
693 return ret;
694}
695
eeb6b45d
JC
696static void raw_reopen_commit(BDRVReopenState *state)
697{
698 BDRVRawReopenState *raw_s = state->opaque;
699 BDRVRawState *s = state->bs->opaque;
700
701 s->open_flags = raw_s->open_flags;
702
703 qemu_close(s->fd);
704 s->fd = raw_s->fd;
705#ifdef CONFIG_LINUX_AIO
706 s->use_aio = raw_s->use_aio;
707#endif
708
709 g_free(state->opaque);
710 state->opaque = NULL;
711}
712
713
714static void raw_reopen_abort(BDRVReopenState *state)
715{
716 BDRVRawReopenState *raw_s = state->opaque;
717
718 /* nothing to do if NULL, we didn't get far enough */
719 if (raw_s == NULL) {
720 return;
721 }
722
723 if (raw_s->fd >= 0) {
724 qemu_close(raw_s->fd);
725 raw_s->fd = -1;
726 }
727 g_free(state->opaque);
728 state->opaque = NULL;
729}
730
3baca891 731static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
c25f53b0
PB
732{
733 BDRVRawState *s = bs->opaque;
eeb6b45d 734
df26a350 735 raw_probe_alignment(bs, s->fd, errp);
4196d2f0 736 bs->bl.min_mem_alignment = s->buf_align;
459b4e66 737 bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
c25f53b0 738}
83f64091 739
1a9335e4
ET
740static int check_for_dasd(int fd)
741{
742#ifdef BIODASDINFO2
743 struct dasd_information2_t info = {0};
744
745 return ioctl(fd, BIODASDINFO2, &info);
746#else
747 return -1;
748#endif
749}
750
751/**
752 * Try to get @bs's logical and physical block size.
753 * On success, store them in @bsz and return zero.
754 * On failure, return negative errno.
755 */
756static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
757{
758 BDRVRawState *s = bs->opaque;
759 int ret;
760
761 /* If DASD, get blocksizes */
762 if (check_for_dasd(s->fd) < 0) {
763 return -ENOTSUP;
764 }
765 ret = probe_logical_blocksize(s->fd, &bsz->log);
766 if (ret < 0) {
767 return ret;
768 }
769 return probe_physical_blocksize(s->fd, &bsz->phys);
770}
771
772/**
773 * Try to get @bs's geometry: cyls, heads, sectors.
774 * On success, store them in @geo and return 0.
775 * On failure return -errno.
776 * (Allows block driver to assign default geometry values that guest sees)
777 */
778#ifdef __linux__
779static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
780{
781 BDRVRawState *s = bs->opaque;
782 struct hd_geometry ioctl_geo = {0};
783 uint32_t blksize;
784
785 /* If DASD, get its geometry */
786 if (check_for_dasd(s->fd) < 0) {
787 return -ENOTSUP;
788 }
789 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
790 return -errno;
791 }
792 /* HDIO_GETGEO may return success even though geo contains zeros
793 (e.g. certain multipath setups) */
794 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
795 return -ENOTSUP;
796 }
797 /* Do not return a geometry for partition */
798 if (ioctl_geo.start != 0) {
799 return -ENOTSUP;
800 }
801 geo->heads = ioctl_geo.heads;
802 geo->sectors = ioctl_geo.sectors;
803 if (!probe_physical_blocksize(s->fd, &blksize)) {
804 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
805 geo->cylinders = bdrv_nb_sectors(bs) / (blksize / BDRV_SECTOR_SIZE)
806 / (geo->heads * geo->sectors);
807 return 0;
808 }
809 geo->cylinders = ioctl_geo.cylinders;
810
811 return 0;
812}
813#else /* __linux__ */
814static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
815{
816 return -ENOTSUP;
817}
818#endif
819
de81a169
PB
820static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
821{
822 int ret;
823
824 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
825 if (ret == -1) {
826 return -errno;
827 }
828
b608c8dc 829 return 0;
de81a169
PB
830}
831
832static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
833{
834 int ret;
835
836 ret = qemu_fdatasync(aiocb->aio_fildes);
837 if (ret == -1) {
838 return -errno;
839 }
840 return 0;
841}
842
843#ifdef CONFIG_PREADV
844
845static bool preadv_present = true;
846
847static ssize_t
848qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
849{
850 return preadv(fd, iov, nr_iov, offset);
851}
852
853static ssize_t
854qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
855{
856 return pwritev(fd, iov, nr_iov, offset);
857}
858
859#else
860
861static bool preadv_present = false;
862
863static ssize_t
864qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
865{
866 return -ENOSYS;
867}
868
869static ssize_t
870qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
871{
872 return -ENOSYS;
873}
874
875#endif
876
877static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
878{
879 ssize_t len;
880
881 do {
882 if (aiocb->aio_type & QEMU_AIO_WRITE)
883 len = qemu_pwritev(aiocb->aio_fildes,
884 aiocb->aio_iov,
885 aiocb->aio_niov,
886 aiocb->aio_offset);
887 else
888 len = qemu_preadv(aiocb->aio_fildes,
889 aiocb->aio_iov,
890 aiocb->aio_niov,
891 aiocb->aio_offset);
892 } while (len == -1 && errno == EINTR);
893
894 if (len == -1) {
895 return -errno;
896 }
897 return len;
898}
899
900/*
901 * Read/writes the data to/from a given linear buffer.
902 *
903 * Returns the number of bytes handles or -errno in case of an error. Short
904 * reads are only returned if the end of the file is reached.
905 */
906static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
907{
908 ssize_t offset = 0;
909 ssize_t len;
910
911 while (offset < aiocb->aio_nbytes) {
912 if (aiocb->aio_type & QEMU_AIO_WRITE) {
913 len = pwrite(aiocb->aio_fildes,
914 (const char *)buf + offset,
915 aiocb->aio_nbytes - offset,
916 aiocb->aio_offset + offset);
917 } else {
918 len = pread(aiocb->aio_fildes,
919 buf + offset,
920 aiocb->aio_nbytes - offset,
921 aiocb->aio_offset + offset);
922 }
923 if (len == -1 && errno == EINTR) {
924 continue;
61ed73cf
SH
925 } else if (len == -1 && errno == EINVAL &&
926 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
927 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
928 offset > 0) {
929 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
930 * after a short read. Assume that O_DIRECT short reads only occur
931 * at EOF. Therefore this is a short read, not an I/O error.
932 */
933 break;
de81a169
PB
934 } else if (len == -1) {
935 offset = -errno;
936 break;
937 } else if (len == 0) {
938 break;
939 }
940 offset += len;
941 }
942
943 return offset;
944}
945
946static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
947{
948 ssize_t nbytes;
949 char *buf;
950
951 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
952 /*
953 * If there is just a single buffer, and it is properly aligned
954 * we can just use plain pread/pwrite without any problems.
955 */
956 if (aiocb->aio_niov == 1) {
957 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
958 }
959 /*
960 * We have more than one iovec, and all are properly aligned.
961 *
962 * Try preadv/pwritev first and fall back to linearizing the
963 * buffer if it's not supported.
964 */
965 if (preadv_present) {
966 nbytes = handle_aiocb_rw_vector(aiocb);
967 if (nbytes == aiocb->aio_nbytes ||
968 (nbytes < 0 && nbytes != -ENOSYS)) {
969 return nbytes;
970 }
971 preadv_present = false;
972 }
973
974 /*
975 * XXX(hch): short read/write. no easy way to handle the reminder
976 * using these interfaces. For now retry using plain
977 * pread/pwrite?
978 */
979 }
980
981 /*
982 * Ok, we have to do it the hard way, copy all segments into
983 * a single aligned buffer.
984 */
50d4a858
KW
985 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
986 if (buf == NULL) {
987 return -ENOMEM;
988 }
989
de81a169
PB
990 if (aiocb->aio_type & QEMU_AIO_WRITE) {
991 char *p = buf;
992 int i;
993
994 for (i = 0; i < aiocb->aio_niov; ++i) {
995 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
996 p += aiocb->aio_iov[i].iov_len;
997 }
8eb029c2 998 assert(p - buf == aiocb->aio_nbytes);
de81a169
PB
999 }
1000
1001 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1002 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1003 char *p = buf;
1004 size_t count = aiocb->aio_nbytes, copy;
1005 int i;
1006
1007 for (i = 0; i < aiocb->aio_niov && count; ++i) {
1008 copy = count;
1009 if (copy > aiocb->aio_iov[i].iov_len) {
1010 copy = aiocb->aio_iov[i].iov_len;
1011 }
1012 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
8eb029c2 1013 assert(count >= copy);
de81a169
PB
1014 p += copy;
1015 count -= copy;
1016 }
8eb029c2 1017 assert(count == 0);
de81a169
PB
1018 }
1019 qemu_vfree(buf);
1020
1021 return nbytes;
1022}
1023
8238010b 1024#ifdef CONFIG_XFS
97a2ae34
PB
1025static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1026{
1027 struct xfs_flock64 fl;
bcb22555 1028 int err;
97a2ae34
PB
1029
1030 memset(&fl, 0, sizeof(fl));
1031 fl.l_whence = SEEK_SET;
1032 fl.l_start = offset;
1033 fl.l_len = bytes;
1034
1035 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
bcb22555
DA
1036 err = errno;
1037 DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1038 return -err;
97a2ae34
PB
1039 }
1040
1041 return 0;
1042}
1043
8238010b
PB
1044static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1045{
1046 struct xfs_flock64 fl;
bcb22555 1047 int err;
8238010b
PB
1048
1049 memset(&fl, 0, sizeof(fl));
1050 fl.l_whence = SEEK_SET;
1051 fl.l_start = offset;
1052 fl.l_len = bytes;
1053
1054 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
bcb22555
DA
1055 err = errno;
1056 DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1057 return -err;
8238010b
PB
1058 }
1059
1060 return 0;
1061}
1062#endif
1063
1486df0e
DL
1064static int translate_err(int err)
1065{
1066 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1067 err == -ENOTTY) {
1068 err = -ENOTSUP;
1069 }
1070 return err;
1071}
1072
d50d8222 1073#ifdef CONFIG_FALLOCATE
0b991712
DL
1074static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1075{
1076 do {
1077 if (fallocate(fd, mode, offset, len) == 0) {
1078 return 0;
1079 }
1080 } while (errno == EINTR);
1081 return translate_err(-errno);
1082}
1083#endif
1084
37cc9f7f 1085static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
97a2ae34 1086{
37cc9f7f 1087 int ret = -ENOTSUP;
97a2ae34
PB
1088 BDRVRawState *s = aiocb->bs->opaque;
1089
37cc9f7f 1090 if (!s->has_write_zeroes) {
97a2ae34
PB
1091 return -ENOTSUP;
1092 }
1093
97a2ae34 1094#ifdef BLKZEROOUT
37cc9f7f
DL
1095 do {
1096 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1097 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1098 return 0;
97a2ae34 1099 }
37cc9f7f
DL
1100 } while (errno == EINTR);
1101
1102 ret = translate_err(-errno);
97a2ae34 1103#endif
97a2ae34 1104
1486df0e 1105 if (ret == -ENOTSUP) {
97a2ae34 1106 s->has_write_zeroes = false;
97a2ae34
PB
1107 }
1108 return ret;
1109}
1110
37cc9f7f
DL
1111static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1112{
a6dcf097 1113#if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
37cc9f7f 1114 BDRVRawState *s = aiocb->bs->opaque;
a6dcf097 1115#endif
37cc9f7f
DL
1116
1117 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1118 return handle_aiocb_write_zeroes_block(aiocb);
1119 }
1120
1121#ifdef CONFIG_XFS
1122 if (s->is_xfs) {
1123 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1124 }
1125#endif
1126
b953f075
DL
1127#ifdef CONFIG_FALLOCATE_ZERO_RANGE
1128 if (s->has_write_zeroes) {
1129 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1130 aiocb->aio_offset, aiocb->aio_nbytes);
1131 if (ret == 0 || ret != -ENOTSUP) {
1132 return ret;
1133 }
1134 s->has_write_zeroes = false;
1135 }
1136#endif
1137
1cdc3239
DL
1138#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1139 if (s->has_discard && s->has_fallocate) {
1140 int ret = do_fallocate(s->fd,
1141 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1142 aiocb->aio_offset, aiocb->aio_nbytes);
1143 if (ret == 0) {
1144 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1145 if (ret == 0 || ret != -ENOTSUP) {
1146 return ret;
1147 }
1148 s->has_fallocate = false;
1149 } else if (ret != -ENOTSUP) {
1150 return ret;
1151 } else {
1152 s->has_discard = false;
1153 }
1154 }
1155#endif
1156
d50d8222
DL
1157#ifdef CONFIG_FALLOCATE
1158 if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1159 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1160 if (ret == 0 || ret != -ENOTSUP) {
1161 return ret;
1162 }
1163 s->has_fallocate = false;
1164 }
1165#endif
1166
37cc9f7f
DL
1167 return -ENOTSUP;
1168}
1169
8238010b
PB
1170static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1171{
1172 int ret = -EOPNOTSUPP;
1173 BDRVRawState *s = aiocb->bs->opaque;
1174
7ce21016
PB
1175 if (!s->has_discard) {
1176 return -ENOTSUP;
8238010b
PB
1177 }
1178
1179 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1180#ifdef BLKDISCARD
1181 do {
1182 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1183 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1184 return 0;
1185 }
1186 } while (errno == EINTR);
1187
1188 ret = -errno;
1189#endif
1190 } else {
1191#ifdef CONFIG_XFS
1192 if (s->is_xfs) {
1193 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1194 }
1195#endif
1196
1197#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
0b991712
DL
1198 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1199 aiocb->aio_offset, aiocb->aio_nbytes);
8238010b
PB
1200#endif
1201 }
1202
1486df0e
DL
1203 ret = translate_err(ret);
1204 if (ret == -ENOTSUP) {
7ce21016 1205 s->has_discard = false;
8238010b
PB
1206 }
1207 return ret;
1208}
1209
de81a169
PB
1210static int aio_worker(void *arg)
1211{
1212 RawPosixAIOData *aiocb = arg;
1213 ssize_t ret = 0;
1214
1215 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1216 case QEMU_AIO_READ:
1217 ret = handle_aiocb_rw(aiocb);
c0191e76 1218 if (ret >= 0 && ret < aiocb->aio_nbytes) {
de81a169
PB
1219 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1220 0, aiocb->aio_nbytes - ret);
1221
1222 ret = aiocb->aio_nbytes;
1223 }
1224 if (ret == aiocb->aio_nbytes) {
1225 ret = 0;
1226 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1227 ret = -EINVAL;
1228 }
1229 break;
1230 case QEMU_AIO_WRITE:
1231 ret = handle_aiocb_rw(aiocb);
1232 if (ret == aiocb->aio_nbytes) {
1233 ret = 0;
1234 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1235 ret = -EINVAL;
1236 }
1237 break;
1238 case QEMU_AIO_FLUSH:
1239 ret = handle_aiocb_flush(aiocb);
1240 break;
1241 case QEMU_AIO_IOCTL:
1242 ret = handle_aiocb_ioctl(aiocb);
1243 break;
8238010b
PB
1244 case QEMU_AIO_DISCARD:
1245 ret = handle_aiocb_discard(aiocb);
1246 break;
97a2ae34
PB
1247 case QEMU_AIO_WRITE_ZEROES:
1248 ret = handle_aiocb_write_zeroes(aiocb);
1249 break;
de81a169
PB
1250 default:
1251 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1252 ret = -EINVAL;
1253 break;
1254 }
1255
1256 g_slice_free(RawPosixAIOData, aiocb);
1257 return ret;
1258}
1259
260a82e5
PB
1260static int paio_submit_co(BlockDriverState *bs, int fd,
1261 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1262 int type)
1263{
1264 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
1265 ThreadPool *pool;
1266
1267 acb->bs = bs;
1268 acb->aio_type = type;
1269 acb->aio_fildes = fd;
1270
8eb029c2
KW
1271 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1272 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1273
260a82e5
PB
1274 if (qiov) {
1275 acb->aio_iov = qiov->iov;
1276 acb->aio_niov = qiov->niov;
8eb029c2 1277 assert(qiov->size == acb->aio_nbytes);
260a82e5 1278 }
260a82e5
PB
1279
1280 trace_paio_submit_co(sector_num, nb_sectors, type);
1281 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1282 return thread_pool_submit_co(pool, aio_worker, acb);
1283}
1284
7c84b1b8 1285static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
de81a169 1286 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
097310b5 1287 BlockCompletionFunc *cb, void *opaque, int type)
de81a169
PB
1288{
1289 RawPosixAIOData *acb = g_slice_new(RawPosixAIOData);
c4d9d196 1290 ThreadPool *pool;
de81a169
PB
1291
1292 acb->bs = bs;
1293 acb->aio_type = type;
1294 acb->aio_fildes = fd;
1295
8eb029c2
KW
1296 acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1297 acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1298
de81a169
PB
1299 if (qiov) {
1300 acb->aio_iov = qiov->iov;
1301 acb->aio_niov = qiov->niov;
8eb029c2 1302 assert(qiov->size == acb->aio_nbytes);
de81a169 1303 }
de81a169
PB
1304
1305 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
c4d9d196
SH
1306 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1307 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
de81a169
PB
1308}
1309
7c84b1b8 1310static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
9ef91a67 1311 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
097310b5 1312 BlockCompletionFunc *cb, void *opaque, int type)
83f64091 1313{
ce1a14dc 1314 BDRVRawState *s = bs->opaque;
ce1a14dc 1315
19cb3738
FB
1316 if (fd_open(bs) < 0)
1317 return NULL;
1318
f141eafe 1319 /*
3cad8307
RPM
1320 * Check if the underlying device requires requests to be aligned,
1321 * and if the request we are trying to submit is aligned or not.
1322 * If this is the case tell the low-level driver that it needs
1323 * to copy the buffer.
f141eafe 1324 */
3cad8307 1325 if (s->needs_alignment) {
c53b1c51 1326 if (!bdrv_qiov_is_aligned(bs, qiov)) {
5c6c3a6c 1327 type |= QEMU_AIO_MISALIGNED;
e44bd6fc 1328#ifdef CONFIG_LINUX_AIO
5c6c3a6c
CH
1329 } else if (s->use_aio) {
1330 return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
e44bd6fc
SW
1331 nb_sectors, cb, opaque, type);
1332#endif
5c6c3a6c 1333 }
9ef91a67 1334 }
f141eafe 1335
1e5b9d2f 1336 return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
9ef91a67 1337 cb, opaque, type);
83f64091
FB
1338}
1339
1b3abdcc
ML
1340static void raw_aio_plug(BlockDriverState *bs)
1341{
1342#ifdef CONFIG_LINUX_AIO
1343 BDRVRawState *s = bs->opaque;
1344 if (s->use_aio) {
1345 laio_io_plug(bs, s->aio_ctx);
1346 }
1347#endif
1348}
1349
1350static void raw_aio_unplug(BlockDriverState *bs)
1351{
1352#ifdef CONFIG_LINUX_AIO
1353 BDRVRawState *s = bs->opaque;
1354 if (s->use_aio) {
1355 laio_io_unplug(bs, s->aio_ctx, true);
1356 }
1357#endif
1358}
1359
1360static void raw_aio_flush_io_queue(BlockDriverState *bs)
1361{
1362#ifdef CONFIG_LINUX_AIO
1363 BDRVRawState *s = bs->opaque;
1364 if (s->use_aio) {
1365 laio_io_unplug(bs, s->aio_ctx, false);
1366 }
1367#endif
1368}
1369
7c84b1b8 1370static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
f141eafe 1371 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
097310b5 1372 BlockCompletionFunc *cb, void *opaque)
83f64091 1373{
9ef91a67
CH
1374 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1375 cb, opaque, QEMU_AIO_READ);
83f64091
FB
1376}
1377
7c84b1b8 1378static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
f141eafe 1379 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
097310b5 1380 BlockCompletionFunc *cb, void *opaque)
83f64091 1381{
9ef91a67
CH
1382 return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1383 cb, opaque, QEMU_AIO_WRITE);
83f64091 1384}
53538725 1385
7c84b1b8 1386static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
097310b5 1387 BlockCompletionFunc *cb, void *opaque)
b2e12bc6
CH
1388{
1389 BDRVRawState *s = bs->opaque;
1390
1391 if (fd_open(bs) < 0)
1392 return NULL;
1393
1e5b9d2f 1394 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
b2e12bc6
CH
1395}
1396
83f64091
FB
1397static void raw_close(BlockDriverState *bs)
1398{
1399 BDRVRawState *s = bs->opaque;
c2f3426c
SH
1400
1401 raw_detach_aio_context(bs);
1402
abd269b7
SH
1403#ifdef CONFIG_LINUX_AIO
1404 if (s->use_aio) {
1405 laio_cleanup(s->aio_ctx);
1406 }
1407#endif
19cb3738 1408 if (s->fd >= 0) {
2e1e79da 1409 qemu_close(s->fd);
19cb3738
FB
1410 s->fd = -1;
1411 }
83f64091
FB
1412}
1413
1414static int raw_truncate(BlockDriverState *bs, int64_t offset)
1415{
1416 BDRVRawState *s = bs->opaque;
55b949c8
CH
1417 struct stat st;
1418
1419 if (fstat(s->fd, &st)) {
83f64091 1420 return -errno;
55b949c8
CH
1421 }
1422
1423 if (S_ISREG(st.st_mode)) {
1424 if (ftruncate(s->fd, offset) < 0) {
1425 return -errno;
1426 }
1427 } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1428 if (offset > raw_getlength(bs)) {
1429 return -EINVAL;
1430 }
1431 } else {
1432 return -ENOTSUP;
1433 }
1434
83f64091
FB
1435 return 0;
1436}
1437
128ab2ff
BS
1438#ifdef __OpenBSD__
1439static int64_t raw_getlength(BlockDriverState *bs)
1440{
1441 BDRVRawState *s = bs->opaque;
1442 int fd = s->fd;
1443 struct stat st;
1444
1445 if (fstat(fd, &st))
aa729704 1446 return -errno;
128ab2ff
BS
1447 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1448 struct disklabel dl;
1449
1450 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 1451 return -errno;
128ab2ff
BS
1452 return (uint64_t)dl.d_secsize *
1453 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1454 } else
1455 return st.st_size;
1456}
d1f6fd8d
CE
1457#elif defined(__NetBSD__)
1458static int64_t raw_getlength(BlockDriverState *bs)
1459{
1460 BDRVRawState *s = bs->opaque;
1461 int fd = s->fd;
1462 struct stat st;
1463
1464 if (fstat(fd, &st))
aa729704 1465 return -errno;
d1f6fd8d
CE
1466 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1467 struct dkwedge_info dkw;
1468
1469 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1470 return dkw.dkw_size * 512;
1471 } else {
1472 struct disklabel dl;
1473
1474 if (ioctl(fd, DIOCGDINFO, &dl))
aa729704 1475 return -errno;
d1f6fd8d
CE
1476 return (uint64_t)dl.d_secsize *
1477 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1478 }
1479 } else
1480 return st.st_size;
1481}
50779cc2
CH
1482#elif defined(__sun__)
1483static int64_t raw_getlength(BlockDriverState *bs)
1484{
1485 BDRVRawState *s = bs->opaque;
1486 struct dk_minfo minfo;
1487 int ret;
aa729704 1488 int64_t size;
50779cc2
CH
1489
1490 ret = fd_open(bs);
1491 if (ret < 0) {
1492 return ret;
1493 }
1494
1495 /*
1496 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1497 */
1498 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1499 if (ret != -1) {
1500 return minfo.dki_lbsize * minfo.dki_capacity;
1501 }
1502
1503 /*
1504 * There are reports that lseek on some devices fails, but
1505 * irc discussion said that contingency on contingency was overkill.
1506 */
aa729704
MA
1507 size = lseek(s->fd, 0, SEEK_END);
1508 if (size < 0) {
1509 return -errno;
1510 }
1511 return size;
50779cc2
CH
1512}
1513#elif defined(CONFIG_BSD)
1514static int64_t raw_getlength(BlockDriverState *bs)
83f64091
FB
1515{
1516 BDRVRawState *s = bs->opaque;
1517 int fd = s->fd;
1518 int64_t size;
83f64091 1519 struct stat sb;
a167ba50 1520#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a 1521 int reopened = 0;
83f64091 1522#endif
19cb3738
FB
1523 int ret;
1524
1525 ret = fd_open(bs);
1526 if (ret < 0)
1527 return ret;
83f64091 1528
a167ba50 1529#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
1530again:
1531#endif
83f64091
FB
1532 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1533#ifdef DIOCGMEDIASIZE
1534 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
c5e97233
BS
1535#elif defined(DIOCGPART)
1536 {
1537 struct partinfo pi;
1538 if (ioctl(fd, DIOCGPART, &pi) == 0)
1539 size = pi.media_size;
1540 else
1541 size = 0;
1542 }
1543 if (size == 0)
83f64091 1544#endif
83affaa6 1545#if defined(__APPLE__) && defined(__MACH__)
728dacbd
JA
1546 {
1547 uint64_t sectors = 0;
1548 uint32_t sector_size = 0;
1549
1550 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1551 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1552 size = sectors * sector_size;
1553 } else {
1554 size = lseek(fd, 0LL, SEEK_END);
1555 if (size < 0) {
1556 return -errno;
1557 }
1558 }
1559 }
83f64091
FB
1560#else
1561 size = lseek(fd, 0LL, SEEK_END);
aa729704
MA
1562 if (size < 0) {
1563 return -errno;
1564 }
9f23011a 1565#endif
a167ba50 1566#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
1567 switch(s->type) {
1568 case FTYPE_CD:
1569 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1570 if (size == 2048LL * (unsigned)-1)
1571 size = 0;
1572 /* XXX no disc? maybe we need to reopen... */
f3a5d3f8 1573 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
9f23011a
BS
1574 reopened = 1;
1575 goto again;
1576 }
1577 }
83f64091 1578#endif
50779cc2 1579 } else {
83f64091 1580 size = lseek(fd, 0, SEEK_END);
aa729704
MA
1581 if (size < 0) {
1582 return -errno;
1583 }
83f64091 1584 }
83f64091
FB
1585 return size;
1586}
50779cc2
CH
1587#else
1588static int64_t raw_getlength(BlockDriverState *bs)
1589{
1590 BDRVRawState *s = bs->opaque;
1591 int ret;
aa729704 1592 int64_t size;
50779cc2
CH
1593
1594 ret = fd_open(bs);
1595 if (ret < 0) {
1596 return ret;
1597 }
1598
aa729704
MA
1599 size = lseek(s->fd, 0, SEEK_END);
1600 if (size < 0) {
1601 return -errno;
1602 }
1603 return size;
50779cc2 1604}
128ab2ff 1605#endif
83f64091 1606
4a1d5e1f
FZ
1607static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1608{
1609 struct stat st;
1610 BDRVRawState *s = bs->opaque;
1611
1612 if (fstat(s->fd, &st) < 0) {
1613 return -errno;
1614 }
1615 return (int64_t)st.st_blocks * 512;
1616}
1617
6f482f74 1618static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
83f64091
FB
1619{
1620 int fd;
1e37d059 1621 int result = 0;
0e7e1989 1622 int64_t total_size = 0;
4ab15590 1623 bool nocow = false;
06247428
HT
1624 PreallocMode prealloc;
1625 char *buf = NULL;
1626 Error *local_err = NULL;
83f64091 1627
464d9f64
HR
1628 strstart(filename, "file:", &filename);
1629
0e7e1989 1630 /* Read out options */
180e9526
HT
1631 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1632 BDRV_SECTOR_SIZE);
4ab15590 1633 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
06247428
HT
1634 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1635 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1636 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1637 &local_err);
1638 g_free(buf);
1639 if (local_err) {
1640 error_propagate(errp, local_err);
1641 result = -EINVAL;
1642 goto out;
1643 }
83f64091 1644
6165f4d8
CB
1645 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
1646 0644);
1e37d059
SW
1647 if (fd < 0) {
1648 result = -errno;
e428e439 1649 error_setg_errno(errp, -result, "Could not create file");
06247428
HT
1650 goto out;
1651 }
1652
1653 if (nocow) {
4ab15590 1654#ifdef __linux__
06247428
HT
1655 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1656 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1657 * will be ignored since any failure of this operation should not
1658 * block the left work.
1659 */
1660 int attr;
1661 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1662 attr |= FS_NOCOW_FL;
1663 ioctl(fd, FS_IOC_SETFLAGS, &attr);
4ab15590 1664 }
06247428
HT
1665#endif
1666 }
1667
1668 if (ftruncate(fd, total_size) != 0) {
1669 result = -errno;
1670 error_setg_errno(errp, -result, "Could not resize file");
1671 goto out_close;
1672 }
4ab15590 1673
ed911435
KW
1674 switch (prealloc) {
1675#ifdef CONFIG_POSIX_FALLOCATE
1676 case PREALLOC_MODE_FALLOC:
06247428
HT
1677 /* posix_fallocate() doesn't set errno. */
1678 result = -posix_fallocate(fd, 0, total_size);
1679 if (result != 0) {
1680 error_setg_errno(errp, -result,
1681 "Could not preallocate data for the new file");
1e37d059 1682 }
ed911435
KW
1683 break;
1684#endif
1685 case PREALLOC_MODE_FULL:
1686 {
06247428 1687 int64_t num = 0, left = total_size;
ed911435 1688 buf = g_malloc0(65536);
06247428
HT
1689
1690 while (left > 0) {
1691 num = MIN(left, 65536);
1692 result = write(fd, buf, num);
1693 if (result < 0) {
1694 result = -errno;
1695 error_setg_errno(errp, -result,
1696 "Could not write to the new file");
1697 break;
1698 }
39411cf3 1699 left -= result;
1e37d059 1700 }
731de380 1701 if (result >= 0) {
098ffa66
HR
1702 result = fsync(fd);
1703 if (result < 0) {
1704 result = -errno;
1705 error_setg_errno(errp, -result,
1706 "Could not flush new file to disk");
1707 }
731de380 1708 }
06247428 1709 g_free(buf);
ed911435
KW
1710 break;
1711 }
1712 case PREALLOC_MODE_OFF:
1713 break;
1714 default:
06247428
HT
1715 result = -EINVAL;
1716 error_setg(errp, "Unsupported preallocation mode: %s",
1717 PreallocMode_lookup[prealloc]);
ed911435 1718 break;
1e37d059 1719 }
06247428
HT
1720
1721out_close:
1722 if (qemu_close(fd) != 0 && result == 0) {
1723 result = -errno;
1724 error_setg_errno(errp, -result, "Could not close the new file");
1725 }
1726out:
1e37d059 1727 return result;
83f64091
FB
1728}
1729
d1f06fe6
MA
1730/*
1731 * Find allocation range in @bs around offset @start.
1732 * May change underlying file descriptor's file offset.
1733 * If @start is not in a hole, store @start in @data, and the
1734 * beginning of the next hole in @hole, and return 0.
1735 * If @start is in a non-trailing hole, store @start in @hole and the
1736 * beginning of the next non-hole in @data, and return 0.
1737 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1738 * If we can't find out, return a negative errno other than -ENXIO.
1739 */
1740static int find_allocation(BlockDriverState *bs, off_t start,
1741 off_t *data, off_t *hole)
4f11aa8a
HR
1742{
1743#if defined SEEK_HOLE && defined SEEK_DATA
94282e71 1744 BDRVRawState *s = bs->opaque;
d1f06fe6 1745 off_t offs;
94282e71 1746
d1f06fe6
MA
1747 /*
1748 * SEEK_DATA cases:
1749 * D1. offs == start: start is in data
1750 * D2. offs > start: start is in a hole, next data at offs
1751 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1752 * or start is beyond EOF
1753 * If the latter happens, the file has been truncated behind
1754 * our back since we opened it. All bets are off then.
1755 * Treating like a trailing hole is simplest.
1756 * D4. offs < 0, errno != ENXIO: we learned nothing
1757 */
1758 offs = lseek(s->fd, start, SEEK_DATA);
1759 if (offs < 0) {
1760 return -errno; /* D3 or D4 */
1761 }
1762 assert(offs >= start);
1763
1764 if (offs > start) {
1765 /* D2: in hole, next data at offs */
1766 *hole = start;
1767 *data = offs;
1768 return 0;
5500316d
PB
1769 }
1770
d1f06fe6
MA
1771 /* D1: in data, end not yet known */
1772
1773 /*
1774 * SEEK_HOLE cases:
1775 * H1. offs == start: start is in a hole
1776 * If this happens here, a hole has been dug behind our back
1777 * since the previous lseek().
1778 * H2. offs > start: either start is in data, next hole at offs,
1779 * or start is in trailing hole, EOF at offs
1780 * Linux treats trailing holes like any other hole: offs ==
1781 * start. Solaris seeks to EOF instead: offs > start (blech).
1782 * If that happens here, a hole has been dug behind our back
1783 * since the previous lseek().
1784 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1785 * If this happens, the file has been truncated behind our
1786 * back since we opened it. Treat it like a trailing hole.
1787 * H4. offs < 0, errno != ENXIO: we learned nothing
1788 * Pretend we know nothing at all, i.e. "forget" about D1.
1789 */
1790 offs = lseek(s->fd, start, SEEK_HOLE);
1791 if (offs < 0) {
1792 return -errno; /* D1 and (H3 or H4) */
1793 }
1794 assert(offs >= start);
1795
1796 if (offs > start) {
1797 /*
1798 * D1 and H2: either in data, next hole at offs, or it was in
1799 * data but is now in a trailing hole. In the latter case,
1800 * all bets are off. Treating it as if it there was data all
1801 * the way to EOF is safe, so simply do that.
1802 */
4f11aa8a 1803 *data = start;
d1f06fe6
MA
1804 *hole = offs;
1805 return 0;
5500316d 1806 }
4f11aa8a 1807
d1f06fe6
MA
1808 /* D1 and H1 */
1809 return -EBUSY;
5500316d 1810#else
4f11aa8a 1811 return -ENOTSUP;
5500316d 1812#endif
4f11aa8a
HR
1813}
1814
1815/*
be2ebc6d 1816 * Returns the allocation status of the specified sectors.
4f11aa8a
HR
1817 *
1818 * If 'sector_num' is beyond the end of the disk image the return value is 0
1819 * and 'pnum' is set to 0.
1820 *
1821 * 'pnum' is set to the number of sectors (including and immediately following
1822 * the specified sector) that are known to be in the same
1823 * allocated/unallocated state.
1824 *
1825 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1826 * beyond the end of the disk image it will be clamped.
1827 */
1828static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1829 int64_t sector_num,
1830 int nb_sectors, int *pnum)
1831{
1832 off_t start, data = 0, hole = 0;
e6d7ec32 1833 int64_t total_size;
d7f62751 1834 int ret;
4f11aa8a
HR
1835
1836 ret = fd_open(bs);
1837 if (ret < 0) {
1838 return ret;
1839 }
1840
1841 start = sector_num * BDRV_SECTOR_SIZE;
e6d7ec32
HR
1842 total_size = bdrv_getlength(bs);
1843 if (total_size < 0) {
1844 return total_size;
1845 } else if (start >= total_size) {
1846 *pnum = 0;
1847 return 0;
1848 } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1849 nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1850 }
4f11aa8a 1851
d1f06fe6
MA
1852 ret = find_allocation(bs, start, &data, &hole);
1853 if (ret == -ENXIO) {
1854 /* Trailing hole */
1855 *pnum = nb_sectors;
1856 ret = BDRV_BLOCK_ZERO;
1857 } else if (ret < 0) {
1858 /* No info available, so pretend there are no holes */
1859 *pnum = nb_sectors;
1860 ret = BDRV_BLOCK_DATA;
1861 } else if (data == start) {
f4a769ab
KW
1862 /* On a data extent, compute sectors to the end of the extent,
1863 * possibly including a partial sector at EOF. */
1864 *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
d1f06fe6 1865 ret = BDRV_BLOCK_DATA;
5500316d
PB
1866 } else {
1867 /* On a hole, compute sectors to the beginning of the next extent. */
d1f06fe6 1868 assert(hole == start);
5500316d 1869 *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
d1f06fe6 1870 ret = BDRV_BLOCK_ZERO;
5500316d 1871 }
d1f06fe6 1872 return ret | BDRV_BLOCK_OFFSET_VALID | start;
5500316d
PB
1873}
1874
7c84b1b8 1875static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
8238010b 1876 int64_t sector_num, int nb_sectors,
097310b5 1877 BlockCompletionFunc *cb, void *opaque)
dce512de 1878{
dce512de
CH
1879 BDRVRawState *s = bs->opaque;
1880
8238010b
PB
1881 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1882 cb, opaque, QEMU_AIO_DISCARD);
dce512de 1883}
0e7e1989 1884
260a82e5
PB
1885static int coroutine_fn raw_co_write_zeroes(
1886 BlockDriverState *bs, int64_t sector_num,
1887 int nb_sectors, BdrvRequestFlags flags)
1888{
1889 BDRVRawState *s = bs->opaque;
1890
1891 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
97a2ae34
PB
1892 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1893 QEMU_AIO_WRITE_ZEROES);
1894 } else if (s->discard_zeroes) {
1895 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1896 QEMU_AIO_DISCARD);
260a82e5 1897 }
97a2ae34 1898 return -ENOTSUP;
260a82e5
PB
1899}
1900
1901static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1902{
1903 BDRVRawState *s = bs->opaque;
1904
1905 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1906 bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1907 return 0;
1908}
1909
6f482f74
CL
1910static QemuOptsList raw_create_opts = {
1911 .name = "raw-create-opts",
1912 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1913 .desc = {
1914 {
1915 .name = BLOCK_OPT_SIZE,
1916 .type = QEMU_OPT_SIZE,
1917 .help = "Virtual disk size"
1918 },
4ab15590
CL
1919 {
1920 .name = BLOCK_OPT_NOCOW,
1921 .type = QEMU_OPT_BOOL,
1922 .help = "Turn off copy-on-write (valid only on btrfs)"
1923 },
06247428
HT
1924 {
1925 .name = BLOCK_OPT_PREALLOC,
1926 .type = QEMU_OPT_STRING,
1927 .help = "Preallocation mode (allowed values: off, falloc, full)"
1928 },
6f482f74
CL
1929 { /* end of list */ }
1930 }
0e7e1989
KW
1931};
1932
5f535a94 1933BlockDriver bdrv_file = {
84a12e66
CH
1934 .format_name = "file",
1935 .protocol_name = "file",
856ae5c3 1936 .instance_size = sizeof(BDRVRawState),
030be321 1937 .bdrv_needs_filename = true,
856ae5c3 1938 .bdrv_probe = NULL, /* no probe for protocols */
078896a9 1939 .bdrv_parse_filename = raw_parse_filename,
66f82cee 1940 .bdrv_file_open = raw_open,
eeb6b45d
JC
1941 .bdrv_reopen_prepare = raw_reopen_prepare,
1942 .bdrv_reopen_commit = raw_reopen_commit,
1943 .bdrv_reopen_abort = raw_reopen_abort,
856ae5c3 1944 .bdrv_close = raw_close,
c282e1fd 1945 .bdrv_create = raw_create,
3ac21627 1946 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 1947 .bdrv_co_get_block_status = raw_co_get_block_status,
260a82e5 1948 .bdrv_co_write_zeroes = raw_co_write_zeroes,
3b46e624 1949
f141eafe
AL
1950 .bdrv_aio_readv = raw_aio_readv,
1951 .bdrv_aio_writev = raw_aio_writev,
b2e12bc6 1952 .bdrv_aio_flush = raw_aio_flush,
8238010b 1953 .bdrv_aio_discard = raw_aio_discard,
c25f53b0 1954 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
1955 .bdrv_io_plug = raw_aio_plug,
1956 .bdrv_io_unplug = raw_aio_unplug,
1957 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
3c529d93 1958
83f64091
FB
1959 .bdrv_truncate = raw_truncate,
1960 .bdrv_getlength = raw_getlength,
260a82e5 1961 .bdrv_get_info = raw_get_info,
4a1d5e1f
FZ
1962 .bdrv_get_allocated_file_size
1963 = raw_get_allocated_file_size,
0e7e1989 1964
c2f3426c
SH
1965 .bdrv_detach_aio_context = raw_detach_aio_context,
1966 .bdrv_attach_aio_context = raw_attach_aio_context,
1967
6f482f74 1968 .create_opts = &raw_create_opts,
83f64091
FB
1969};
1970
19cb3738
FB
1971/***********************************************/
1972/* host device */
1973
83affaa6 1974#if defined(__APPLE__) && defined(__MACH__)
19cb3738
FB
1975static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1976static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
1977
1978kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1979{
5fafdf24 1980 kern_return_t kernResult;
19cb3738
FB
1981 mach_port_t masterPort;
1982 CFMutableDictionaryRef classesToMatch;
1983
1984 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1985 if ( KERN_SUCCESS != kernResult ) {
1986 printf( "IOMasterPort returned %d\n", kernResult );
1987 }
3b46e624 1988
5fafdf24 1989 classesToMatch = IOServiceMatching( kIOCDMediaClass );
19cb3738
FB
1990 if ( classesToMatch == NULL ) {
1991 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1992 } else {
1993 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1994 }
1995 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1996 if ( KERN_SUCCESS != kernResult )
1997 {
1998 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1999 }
3b46e624 2000
19cb3738
FB
2001 return kernResult;
2002}
2003
2004kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
2005{
2006 io_object_t nextMedia;
2007 kern_return_t kernResult = KERN_FAILURE;
2008 *bsdPath = '\0';
2009 nextMedia = IOIteratorNext( mediaIterator );
2010 if ( nextMedia )
2011 {
2012 CFTypeRef bsdPathAsCFString;
2013 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2014 if ( bsdPathAsCFString ) {
2015 size_t devPathLength;
2016 strcpy( bsdPath, _PATH_DEV );
2017 strcat( bsdPath, "r" );
2018 devPathLength = strlen( bsdPath );
2019 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2020 kernResult = KERN_SUCCESS;
2021 }
2022 CFRelease( bsdPathAsCFString );
2023 }
2024 IOObjectRelease( nextMedia );
2025 }
3b46e624 2026
19cb3738
FB
2027 return kernResult;
2028}
2029
2030#endif
2031
508c7cb3
CH
2032static int hdev_probe_device(const char *filename)
2033{
2034 struct stat st;
2035
2036 /* allow a dedicated CD-ROM driver to match with a higher priority */
2037 if (strstart(filename, "/dev/cdrom", NULL))
2038 return 50;
2039
2040 if (stat(filename, &st) >= 0 &&
2041 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2042 return 100;
2043 }
2044
2045 return 0;
2046}
2047
da888d37
SH
2048static int check_hdev_writable(BDRVRawState *s)
2049{
2050#if defined(BLKROGET)
2051 /* Linux block devices can be configured "read-only" using blockdev(8).
2052 * This is independent of device node permissions and therefore open(2)
2053 * with O_RDWR succeeds. Actual writes fail with EPERM.
2054 *
2055 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2056 * check for read-only block devices so that Linux block devices behave
2057 * properly.
2058 */
2059 struct stat st;
2060 int readonly = 0;
2061
2062 if (fstat(s->fd, &st)) {
2063 return -errno;
2064 }
2065
2066 if (!S_ISBLK(st.st_mode)) {
2067 return 0;
2068 }
2069
2070 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2071 return -errno;
2072 }
2073
2074 if (readonly) {
2075 return -EACCES;
2076 }
2077#endif /* defined(BLKROGET) */
2078 return 0;
2079}
2080
7af803d4
HR
2081static void hdev_parse_filename(const char *filename, QDict *options,
2082 Error **errp)
2083{
2084 /* The prefix is optional, just as for "file". */
2085 strstart(filename, "host_device:", &filename);
2086
2087 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2088}
2089
3307ed7b
DA
2090static bool hdev_is_sg(BlockDriverState *bs)
2091{
2092
2093#if defined(__linux__)
2094
2095 struct stat st;
2096 struct sg_scsi_id scsiid;
2097 int sg_version;
2098
2099 if (stat(bs->filename, &st) >= 0 && S_ISCHR(st.st_mode) &&
2100 !bdrv_ioctl(bs, SG_GET_VERSION_NUM, &sg_version) &&
2101 !bdrv_ioctl(bs, SG_GET_SCSI_ID, &scsiid)) {
2102 DPRINTF("SG device found: type=%d, version=%d\n",
2103 scsiid.scsi_type, sg_version);
2104 return true;
2105 }
2106
2107#endif
2108
2109 return false;
2110}
2111
015a1036
HR
2112static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2113 Error **errp)
19cb3738
FB
2114{
2115 BDRVRawState *s = bs->opaque;
e428e439 2116 Error *local_err = NULL;
da888d37 2117 int ret;
a76bab49 2118
83affaa6 2119#if defined(__APPLE__) && defined(__MACH__)
3307ed7b
DA
2120 const char *filename = qdict_get_str(options, "filename");
2121
19cb3738
FB
2122 if (strstart(filename, "/dev/cdrom", NULL)) {
2123 kern_return_t kernResult;
2124 io_iterator_t mediaIterator;
2125 char bsdPath[ MAXPATHLEN ];
2126 int fd;
5fafdf24 2127
19cb3738
FB
2128 kernResult = FindEjectableCDMedia( &mediaIterator );
2129 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
3b46e624 2130
19cb3738
FB
2131 if ( bsdPath[ 0 ] != '\0' ) {
2132 strcat(bsdPath,"s0");
2133 /* some CDs don't have a partition 0 */
6165f4d8 2134 fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
19cb3738
FB
2135 if (fd < 0) {
2136 bsdPath[strlen(bsdPath)-1] = '1';
2137 } else {
2e1e79da 2138 qemu_close(fd);
19cb3738
FB
2139 }
2140 filename = bsdPath;
a5c5ea3f 2141 qdict_put(options, "filename", qstring_from_str(filename));
19cb3738 2142 }
3b46e624 2143
19cb3738
FB
2144 if ( mediaIterator )
2145 IOObjectRelease( mediaIterator );
2146 }
2147#endif
19cb3738
FB
2148
2149 s->type = FTYPE_FILE;
90babde0 2150
e428e439 2151 ret = raw_open_common(bs, options, flags, 0, &local_err);
da888d37 2152 if (ret < 0) {
84d18f06 2153 if (local_err) {
e428e439
HR
2154 error_propagate(errp, local_err);
2155 }
da888d37
SH
2156 return ret;
2157 }
2158
3307ed7b
DA
2159 /* Since this does ioctl the device must be already opened */
2160 bs->sg = hdev_is_sg(bs);
2161
da888d37
SH
2162 if (flags & BDRV_O_RDWR) {
2163 ret = check_hdev_writable(s);
2164 if (ret < 0) {
2165 raw_close(bs);
e428e439 2166 error_setg_errno(errp, -ret, "The device is not writable");
da888d37
SH
2167 return ret;
2168 }
2169 }
2170
2171 return ret;
19cb3738
FB
2172}
2173
03ff3ca3 2174#if defined(__linux__)
19cb3738
FB
2175/* Note: we do not have a reliable method to detect if the floppy is
2176 present. The current method is to try to open the floppy at every
2177 I/O and to keep it opened during a few hundreds of ms. */
2178static int fd_open(BlockDriverState *bs)
2179{
2180 BDRVRawState *s = bs->opaque;
2181 int last_media_present;
2182
2183 if (s->type != FTYPE_FD)
2184 return 0;
2185 last_media_present = (s->fd >= 0);
5fafdf24 2186 if (s->fd >= 0 &&
a56ebc6b 2187 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
2e1e79da 2188 qemu_close(s->fd);
19cb3738 2189 s->fd = -1;
a93a3982 2190 DPRINTF("Floppy closed\n");
19cb3738
FB
2191 }
2192 if (s->fd < 0) {
5fafdf24 2193 if (s->fd_got_error &&
a56ebc6b 2194 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
a93a3982 2195 DPRINTF("No floppy (open delayed)\n");
19cb3738
FB
2196 return -EIO;
2197 }
6165f4d8 2198 s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
19cb3738 2199 if (s->fd < 0) {
a56ebc6b 2200 s->fd_error_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
19cb3738
FB
2201 s->fd_got_error = 1;
2202 if (last_media_present)
2203 s->fd_media_changed = 1;
a93a3982 2204 DPRINTF("No floppy\n");
19cb3738
FB
2205 return -EIO;
2206 }
a93a3982 2207 DPRINTF("Floppy opened\n");
19cb3738
FB
2208 }
2209 if (!last_media_present)
2210 s->fd_media_changed = 1;
a56ebc6b 2211 s->fd_open_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
19cb3738
FB
2212 s->fd_got_error = 0;
2213 return 0;
2214}
19cb3738 2215
63ec93db 2216static int hdev_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
985a03b0
TS
2217{
2218 BDRVRawState *s = bs->opaque;
2219
2220 return ioctl(s->fd, req, buf);
2221}
221f715d 2222
7c84b1b8 2223static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
221f715d 2224 unsigned long int req, void *buf,
097310b5 2225 BlockCompletionFunc *cb, void *opaque)
221f715d 2226{
f141eafe 2227 BDRVRawState *s = bs->opaque;
c208e8c2 2228 RawPosixAIOData *acb;
c4d9d196 2229 ThreadPool *pool;
221f715d 2230
f141eafe
AL
2231 if (fd_open(bs) < 0)
2232 return NULL;
c208e8c2
PB
2233
2234 acb = g_slice_new(RawPosixAIOData);
2235 acb->bs = bs;
2236 acb->aio_type = QEMU_AIO_IOCTL;
2237 acb->aio_fildes = s->fd;
2238 acb->aio_offset = 0;
2239 acb->aio_ioctl_buf = buf;
2240 acb->aio_ioctl_cmd = req;
c4d9d196
SH
2241 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2242 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
221f715d
AL
2243}
2244
a167ba50 2245#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9f23011a
BS
2246static int fd_open(BlockDriverState *bs)
2247{
2248 BDRVRawState *s = bs->opaque;
2249
2250 /* this is just to ensure s->fd is sane (its called by io ops) */
2251 if (s->fd >= 0)
2252 return 0;
2253 return -EIO;
2254}
9f23011a 2255#else /* !linux && !FreeBSD */
19cb3738 2256
08af02e2
AL
2257static int fd_open(BlockDriverState *bs)
2258{
2259 return 0;
2260}
2261
221f715d 2262#endif /* !linux && !FreeBSD */
04eeb8b6 2263
7c84b1b8 2264static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
c36dd8a0 2265 int64_t sector_num, int nb_sectors,
097310b5 2266 BlockCompletionFunc *cb, void *opaque)
c36dd8a0
AF
2267{
2268 BDRVRawState *s = bs->opaque;
2269
2270 if (fd_open(bs) < 0) {
2271 return NULL;
2272 }
2273 return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2274 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2275}
2276
d0b4503e
PB
2277static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2278 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2279{
2280 BDRVRawState *s = bs->opaque;
2281 int rc;
2282
2283 rc = fd_open(bs);
2284 if (rc < 0) {
2285 return rc;
2286 }
2287 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
97a2ae34
PB
2288 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2289 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2290 } else if (s->discard_zeroes) {
2291 return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2292 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
d0b4503e 2293 }
97a2ae34 2294 return -ENOTSUP;
d0b4503e
PB
2295}
2296
6f482f74 2297static int hdev_create(const char *filename, QemuOpts *opts,
d5124c00 2298 Error **errp)
93c65b47
AL
2299{
2300 int fd;
2301 int ret = 0;
2302 struct stat stat_buf;
0e7e1989 2303 int64_t total_size = 0;
cc28c6aa
HR
2304 bool has_prefix;
2305
2306 /* This function is used by all three protocol block drivers and therefore
2307 * any of these three prefixes may be given.
2308 * The return value has to be stored somewhere, otherwise this is an error
2309 * due to -Werror=unused-value. */
2310 has_prefix =
2311 strstart(filename, "host_device:", &filename) ||
2312 strstart(filename, "host_cdrom:" , &filename) ||
2313 strstart(filename, "host_floppy:", &filename);
2314
2315 (void)has_prefix;
93c65b47 2316
0e7e1989 2317 /* Read out options */
180e9526
HT
2318 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2319 BDRV_SECTOR_SIZE);
93c65b47 2320
6165f4d8 2321 fd = qemu_open(filename, O_WRONLY | O_BINARY);
e428e439
HR
2322 if (fd < 0) {
2323 ret = -errno;
2324 error_setg_errno(errp, -ret, "Could not open device");
2325 return ret;
2326 }
93c65b47 2327
e428e439 2328 if (fstat(fd, &stat_buf) < 0) {
57e69b7d 2329 ret = -errno;
e428e439
HR
2330 error_setg_errno(errp, -ret, "Could not stat device");
2331 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2332 error_setg(errp,
2333 "The given file is neither a block nor a character device");
57e69b7d 2334 ret = -ENODEV;
180e9526 2335 } else if (lseek(fd, 0, SEEK_END) < total_size) {
e428e439 2336 error_setg(errp, "Device is too small");
93c65b47 2337 ret = -ENOSPC;
e428e439 2338 }
93c65b47 2339
2e1e79da 2340 qemu_close(fd);
93c65b47
AL
2341 return ret;
2342}
2343
5efa9d5a 2344static BlockDriver bdrv_host_device = {
0b4ce02e 2345 .format_name = "host_device",
84a12e66 2346 .protocol_name = "host_device",
0b4ce02e 2347 .instance_size = sizeof(BDRVRawState),
030be321 2348 .bdrv_needs_filename = true,
0b4ce02e 2349 .bdrv_probe_device = hdev_probe_device,
7af803d4 2350 .bdrv_parse_filename = hdev_parse_filename,
66f82cee 2351 .bdrv_file_open = hdev_open,
0b4ce02e 2352 .bdrv_close = raw_close,
1bc6b705
JC
2353 .bdrv_reopen_prepare = raw_reopen_prepare,
2354 .bdrv_reopen_commit = raw_reopen_commit,
2355 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2356 .bdrv_create = hdev_create,
6f482f74 2357 .create_opts = &raw_create_opts,
d0b4503e 2358 .bdrv_co_write_zeroes = hdev_co_write_zeroes,
3b46e624 2359
f141eafe
AL
2360 .bdrv_aio_readv = raw_aio_readv,
2361 .bdrv_aio_writev = raw_aio_writev,
b2e12bc6 2362 .bdrv_aio_flush = raw_aio_flush,
8238010b 2363 .bdrv_aio_discard = hdev_aio_discard,
c25f53b0 2364 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2365 .bdrv_io_plug = raw_aio_plug,
2366 .bdrv_io_unplug = raw_aio_unplug,
2367 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
3c529d93 2368
55b949c8 2369 .bdrv_truncate = raw_truncate,
e60f469c 2370 .bdrv_getlength = raw_getlength,
260a82e5 2371 .bdrv_get_info = raw_get_info,
4a1d5e1f
FZ
2372 .bdrv_get_allocated_file_size
2373 = raw_get_allocated_file_size,
1a9335e4
ET
2374 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2375 .bdrv_probe_geometry = hdev_probe_geometry,
19cb3738 2376
c2f3426c
SH
2377 .bdrv_detach_aio_context = raw_detach_aio_context,
2378 .bdrv_attach_aio_context = raw_attach_aio_context,
2379
f3a5d3f8 2380 /* generic scsi device */
63ec93db
CH
2381#ifdef __linux__
2382 .bdrv_ioctl = hdev_ioctl,
63ec93db
CH
2383 .bdrv_aio_ioctl = hdev_aio_ioctl,
2384#endif
f3a5d3f8
CH
2385};
2386
2387#ifdef __linux__
d3f49845
HR
2388static void floppy_parse_filename(const char *filename, QDict *options,
2389 Error **errp)
2390{
2391 /* The prefix is optional, just as for "file". */
2392 strstart(filename, "host_floppy:", &filename);
2393
2394 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2395}
2396
015a1036
HR
2397static int floppy_open(BlockDriverState *bs, QDict *options, int flags,
2398 Error **errp)
f3a5d3f8
CH
2399{
2400 BDRVRawState *s = bs->opaque;
e428e439 2401 Error *local_err = NULL;
f3a5d3f8
CH
2402 int ret;
2403
f3a5d3f8 2404 s->type = FTYPE_FD;
f3a5d3f8 2405
19a3da7f 2406 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
e428e439
HR
2407 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2408 if (ret) {
84d18f06 2409 if (local_err) {
e428e439
HR
2410 error_propagate(errp, local_err);
2411 }
f3a5d3f8 2412 return ret;
e428e439 2413 }
f3a5d3f8
CH
2414
2415 /* close fd so that we can reopen it as needed */
2e1e79da 2416 qemu_close(s->fd);
f3a5d3f8
CH
2417 s->fd = -1;
2418 s->fd_media_changed = 1;
2419
92a539d2
MA
2420 error_report("Host floppy pass-through is deprecated");
2421 error_printf("Support for it will be removed in a future release.\n");
f3a5d3f8
CH
2422 return 0;
2423}
2424
508c7cb3
CH
2425static int floppy_probe_device(const char *filename)
2426{
2ebf7c4b
CR
2427 int fd, ret;
2428 int prio = 0;
2429 struct floppy_struct fdparam;
343f8568 2430 struct stat st;
2ebf7c4b 2431
e1740828 2432 if (strstart(filename, "/dev/fd", NULL) &&
25d9747b
RJ
2433 !strstart(filename, "/dev/fdset/", NULL) &&
2434 !strstart(filename, "/dev/fd/", NULL)) {
2ebf7c4b 2435 prio = 50;
e1740828 2436 }
2ebf7c4b 2437
6165f4d8 2438 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2ebf7c4b
CR
2439 if (fd < 0) {
2440 goto out;
2441 }
343f8568
JS
2442 ret = fstat(fd, &st);
2443 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2444 goto outc;
2445 }
2ebf7c4b
CR
2446
2447 /* Attempt to detect via a floppy specific ioctl */
2448 ret = ioctl(fd, FDGETPRM, &fdparam);
2449 if (ret >= 0)
2450 prio = 100;
2451
343f8568 2452outc:
2e1e79da 2453 qemu_close(fd);
2ebf7c4b
CR
2454out:
2455 return prio;
508c7cb3
CH
2456}
2457
2458
f3a5d3f8
CH
2459static int floppy_is_inserted(BlockDriverState *bs)
2460{
2461 return fd_open(bs) >= 0;
2462}
2463
2464static int floppy_media_changed(BlockDriverState *bs)
2465{
2466 BDRVRawState *s = bs->opaque;
2467 int ret;
2468
2469 /*
2470 * XXX: we do not have a true media changed indication.
2471 * It does not work if the floppy is changed without trying to read it.
2472 */
2473 fd_open(bs);
2474 ret = s->fd_media_changed;
2475 s->fd_media_changed = 0;
a93a3982 2476 DPRINTF("Floppy changed=%d\n", ret);
f3a5d3f8
CH
2477 return ret;
2478}
2479
f36f3949 2480static void floppy_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
2481{
2482 BDRVRawState *s = bs->opaque;
2483 int fd;
2484
2485 if (s->fd >= 0) {
2e1e79da 2486 qemu_close(s->fd);
f3a5d3f8
CH
2487 s->fd = -1;
2488 }
6165f4d8 2489 fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
f3a5d3f8
CH
2490 if (fd >= 0) {
2491 if (ioctl(fd, FDEJECT, 0) < 0)
2492 perror("FDEJECT");
2e1e79da 2493 qemu_close(fd);
f3a5d3f8 2494 }
f3a5d3f8
CH
2495}
2496
2497static BlockDriver bdrv_host_floppy = {
2498 .format_name = "host_floppy",
84a12e66 2499 .protocol_name = "host_floppy",
f3a5d3f8 2500 .instance_size = sizeof(BDRVRawState),
030be321 2501 .bdrv_needs_filename = true,
508c7cb3 2502 .bdrv_probe_device = floppy_probe_device,
d3f49845 2503 .bdrv_parse_filename = floppy_parse_filename,
66f82cee 2504 .bdrv_file_open = floppy_open,
f3a5d3f8 2505 .bdrv_close = raw_close,
1bc6b705
JC
2506 .bdrv_reopen_prepare = raw_reopen_prepare,
2507 .bdrv_reopen_commit = raw_reopen_commit,
2508 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2509 .bdrv_create = hdev_create,
6f482f74 2510 .create_opts = &raw_create_opts,
f3a5d3f8 2511
f3a5d3f8
CH
2512 .bdrv_aio_readv = raw_aio_readv,
2513 .bdrv_aio_writev = raw_aio_writev,
b2e12bc6 2514 .bdrv_aio_flush = raw_aio_flush,
c25f53b0 2515 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2516 .bdrv_io_plug = raw_aio_plug,
2517 .bdrv_io_unplug = raw_aio_unplug,
2518 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
f3a5d3f8 2519
55b949c8 2520 .bdrv_truncate = raw_truncate,
b94a2610
KW
2521 .bdrv_getlength = raw_getlength,
2522 .has_variable_length = true,
4a1d5e1f
FZ
2523 .bdrv_get_allocated_file_size
2524 = raw_get_allocated_file_size,
f3a5d3f8 2525
c2f3426c
SH
2526 .bdrv_detach_aio_context = raw_detach_aio_context,
2527 .bdrv_attach_aio_context = raw_attach_aio_context,
2528
f3a5d3f8
CH
2529 /* removable device support */
2530 .bdrv_is_inserted = floppy_is_inserted,
2531 .bdrv_media_changed = floppy_media_changed,
2532 .bdrv_eject = floppy_eject,
f3a5d3f8 2533};
18fa1c42 2534#endif
f3a5d3f8 2535
18fa1c42
HR
2536#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2537static void cdrom_parse_filename(const char *filename, QDict *options,
2538 Error **errp)
2539{
2540 /* The prefix is optional, just as for "file". */
2541 strstart(filename, "host_cdrom:", &filename);
2542
2543 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2544}
2545#endif
2546
2547#ifdef __linux__
015a1036
HR
2548static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2549 Error **errp)
f3a5d3f8
CH
2550{
2551 BDRVRawState *s = bs->opaque;
e428e439
HR
2552 Error *local_err = NULL;
2553 int ret;
f3a5d3f8 2554
f3a5d3f8
CH
2555 s->type = FTYPE_CD;
2556
19a3da7f 2557 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
e428e439 2558 ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
84d18f06 2559 if (local_err) {
e428e439
HR
2560 error_propagate(errp, local_err);
2561 }
2562 return ret;
f3a5d3f8
CH
2563}
2564
508c7cb3
CH
2565static int cdrom_probe_device(const char *filename)
2566{
3baf720e
CR
2567 int fd, ret;
2568 int prio = 0;
343f8568 2569 struct stat st;
3baf720e 2570
6165f4d8 2571 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
3baf720e
CR
2572 if (fd < 0) {
2573 goto out;
2574 }
343f8568
JS
2575 ret = fstat(fd, &st);
2576 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2577 goto outc;
2578 }
3baf720e
CR
2579
2580 /* Attempt to detect via a CDROM specific ioctl */
2581 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2582 if (ret >= 0)
2583 prio = 100;
2584
343f8568 2585outc:
2e1e79da 2586 qemu_close(fd);
3baf720e
CR
2587out:
2588 return prio;
508c7cb3
CH
2589}
2590
f3a5d3f8
CH
2591static int cdrom_is_inserted(BlockDriverState *bs)
2592{
2593 BDRVRawState *s = bs->opaque;
2594 int ret;
2595
2596 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2597 if (ret == CDS_DISC_OK)
2598 return 1;
2599 return 0;
2600}
2601
f36f3949 2602static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
2603{
2604 BDRVRawState *s = bs->opaque;
2605
2606 if (eject_flag) {
2607 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2608 perror("CDROMEJECT");
2609 } else {
2610 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2611 perror("CDROMEJECT");
2612 }
f3a5d3f8
CH
2613}
2614
025e849a 2615static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
2616{
2617 BDRVRawState *s = bs->opaque;
2618
2619 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2620 /*
2621 * Note: an error can happen if the distribution automatically
2622 * mounts the CD-ROM
2623 */
2624 /* perror("CDROM_LOCKDOOR"); */
2625 }
f3a5d3f8
CH
2626}
2627
2628static BlockDriver bdrv_host_cdrom = {
2629 .format_name = "host_cdrom",
84a12e66 2630 .protocol_name = "host_cdrom",
f3a5d3f8 2631 .instance_size = sizeof(BDRVRawState),
030be321 2632 .bdrv_needs_filename = true,
508c7cb3 2633 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 2634 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 2635 .bdrv_file_open = cdrom_open,
f3a5d3f8 2636 .bdrv_close = raw_close,
1bc6b705
JC
2637 .bdrv_reopen_prepare = raw_reopen_prepare,
2638 .bdrv_reopen_commit = raw_reopen_commit,
2639 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2640 .bdrv_create = hdev_create,
6f482f74 2641 .create_opts = &raw_create_opts,
f3a5d3f8 2642
f3a5d3f8
CH
2643 .bdrv_aio_readv = raw_aio_readv,
2644 .bdrv_aio_writev = raw_aio_writev,
b2e12bc6 2645 .bdrv_aio_flush = raw_aio_flush,
c25f53b0 2646 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2647 .bdrv_io_plug = raw_aio_plug,
2648 .bdrv_io_unplug = raw_aio_unplug,
2649 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
f3a5d3f8 2650
55b949c8 2651 .bdrv_truncate = raw_truncate,
b94a2610
KW
2652 .bdrv_getlength = raw_getlength,
2653 .has_variable_length = true,
4a1d5e1f
FZ
2654 .bdrv_get_allocated_file_size
2655 = raw_get_allocated_file_size,
f3a5d3f8 2656
c2f3426c
SH
2657 .bdrv_detach_aio_context = raw_detach_aio_context,
2658 .bdrv_attach_aio_context = raw_attach_aio_context,
2659
f3a5d3f8
CH
2660 /* removable device support */
2661 .bdrv_is_inserted = cdrom_is_inserted,
2662 .bdrv_eject = cdrom_eject,
025e849a 2663 .bdrv_lock_medium = cdrom_lock_medium,
f3a5d3f8
CH
2664
2665 /* generic scsi device */
63ec93db 2666 .bdrv_ioctl = hdev_ioctl,
63ec93db 2667 .bdrv_aio_ioctl = hdev_aio_ioctl,
f3a5d3f8
CH
2668};
2669#endif /* __linux__ */
2670
a167ba50 2671#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
511018e4
AT
2672static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2673 Error **errp)
f3a5d3f8
CH
2674{
2675 BDRVRawState *s = bs->opaque;
e428e439 2676 Error *local_err = NULL;
f3a5d3f8
CH
2677 int ret;
2678
2679 s->type = FTYPE_CD;
2680
e428e439
HR
2681 ret = raw_open_common(bs, options, flags, 0, &local_err);
2682 if (ret) {
84d18f06 2683 if (local_err) {
e428e439
HR
2684 error_propagate(errp, local_err);
2685 }
f3a5d3f8 2686 return ret;
e428e439 2687 }
f3a5d3f8 2688
9b2260cb 2689 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
2690 ioctl(s->fd, CDIOCALLOW);
2691 return 0;
2692}
2693
508c7cb3
CH
2694static int cdrom_probe_device(const char *filename)
2695{
2696 if (strstart(filename, "/dev/cd", NULL) ||
2697 strstart(filename, "/dev/acd", NULL))
2698 return 100;
2699 return 0;
2700}
2701
f3a5d3f8
CH
2702static int cdrom_reopen(BlockDriverState *bs)
2703{
2704 BDRVRawState *s = bs->opaque;
2705 int fd;
2706
2707 /*
2708 * Force reread of possibly changed/newly loaded disc,
2709 * FreeBSD seems to not notice sometimes...
2710 */
2711 if (s->fd >= 0)
2e1e79da 2712 qemu_close(s->fd);
6165f4d8 2713 fd = qemu_open(bs->filename, s->open_flags, 0644);
f3a5d3f8
CH
2714 if (fd < 0) {
2715 s->fd = -1;
2716 return -EIO;
2717 }
2718 s->fd = fd;
2719
9b2260cb 2720 /* make sure the door isn't locked at this time */
f3a5d3f8
CH
2721 ioctl(s->fd, CDIOCALLOW);
2722 return 0;
2723}
2724
2725static int cdrom_is_inserted(BlockDriverState *bs)
2726{
2727 return raw_getlength(bs) > 0;
2728}
2729
f36f3949 2730static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
f3a5d3f8
CH
2731{
2732 BDRVRawState *s = bs->opaque;
2733
2734 if (s->fd < 0)
822e1cd1 2735 return;
f3a5d3f8
CH
2736
2737 (void) ioctl(s->fd, CDIOCALLOW);
2738
2739 if (eject_flag) {
2740 if (ioctl(s->fd, CDIOCEJECT) < 0)
2741 perror("CDIOCEJECT");
2742 } else {
2743 if (ioctl(s->fd, CDIOCCLOSE) < 0)
2744 perror("CDIOCCLOSE");
2745 }
2746
822e1cd1 2747 cdrom_reopen(bs);
f3a5d3f8
CH
2748}
2749
025e849a 2750static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
f3a5d3f8
CH
2751{
2752 BDRVRawState *s = bs->opaque;
2753
2754 if (s->fd < 0)
7bf37fed 2755 return;
f3a5d3f8
CH
2756 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2757 /*
2758 * Note: an error can happen if the distribution automatically
2759 * mounts the CD-ROM
2760 */
2761 /* perror("CDROM_LOCKDOOR"); */
2762 }
f3a5d3f8
CH
2763}
2764
2765static BlockDriver bdrv_host_cdrom = {
2766 .format_name = "host_cdrom",
84a12e66 2767 .protocol_name = "host_cdrom",
f3a5d3f8 2768 .instance_size = sizeof(BDRVRawState),
030be321 2769 .bdrv_needs_filename = true,
508c7cb3 2770 .bdrv_probe_device = cdrom_probe_device,
18fa1c42 2771 .bdrv_parse_filename = cdrom_parse_filename,
66f82cee 2772 .bdrv_file_open = cdrom_open,
f3a5d3f8 2773 .bdrv_close = raw_close,
1bc6b705
JC
2774 .bdrv_reopen_prepare = raw_reopen_prepare,
2775 .bdrv_reopen_commit = raw_reopen_commit,
2776 .bdrv_reopen_abort = raw_reopen_abort,
c282e1fd 2777 .bdrv_create = hdev_create,
6f482f74 2778 .create_opts = &raw_create_opts,
f3a5d3f8 2779
f3a5d3f8
CH
2780 .bdrv_aio_readv = raw_aio_readv,
2781 .bdrv_aio_writev = raw_aio_writev,
b2e12bc6 2782 .bdrv_aio_flush = raw_aio_flush,
c25f53b0 2783 .bdrv_refresh_limits = raw_refresh_limits,
1b3abdcc
ML
2784 .bdrv_io_plug = raw_aio_plug,
2785 .bdrv_io_unplug = raw_aio_unplug,
2786 .bdrv_flush_io_queue = raw_aio_flush_io_queue,
f3a5d3f8 2787
55b949c8 2788 .bdrv_truncate = raw_truncate,
b94a2610
KW
2789 .bdrv_getlength = raw_getlength,
2790 .has_variable_length = true,
4a1d5e1f
FZ
2791 .bdrv_get_allocated_file_size
2792 = raw_get_allocated_file_size,
f3a5d3f8 2793
c2f3426c
SH
2794 .bdrv_detach_aio_context = raw_detach_aio_context,
2795 .bdrv_attach_aio_context = raw_attach_aio_context,
2796
19cb3738 2797 /* removable device support */
f3a5d3f8
CH
2798 .bdrv_is_inserted = cdrom_is_inserted,
2799 .bdrv_eject = cdrom_eject,
025e849a 2800 .bdrv_lock_medium = cdrom_lock_medium,
19cb3738 2801};
f3a5d3f8 2802#endif /* __FreeBSD__ */
5efa9d5a 2803
84a12e66 2804static void bdrv_file_init(void)
5efa9d5a 2805{
508c7cb3
CH
2806 /*
2807 * Register all the drivers. Note that order is important, the driver
2808 * registered last will get probed first.
2809 */
84a12e66 2810 bdrv_register(&bdrv_file);
5efa9d5a 2811 bdrv_register(&bdrv_host_device);
f3a5d3f8
CH
2812#ifdef __linux__
2813 bdrv_register(&bdrv_host_floppy);
2814 bdrv_register(&bdrv_host_cdrom);
2815#endif
a167ba50 2816#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
f3a5d3f8
CH
2817 bdrv_register(&bdrv_host_cdrom);
2818#endif
5efa9d5a
AL
2819}
2820
84a12e66 2821block_init(bdrv_file_init);
This page took 0.999561 seconds and 4 git commands to generate.