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