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