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