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