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