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