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