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