1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include "qemu/osdep.h"
26#include "qapi/error.h"
27#include "qemu/cutils.h"
28#include "qemu/error-report.h"
29#include "block/block_int.h"
30#include "qemu/module.h"
31#include "qemu/option.h"
32#include "trace.h"
33#include "block/thread-pool.h"
34#include "qemu/iov.h"
35#include "block/raw-aio.h"
36#include "qapi/qmp/qdict.h"
37#include "qapi/qmp/qstring.h"
38
39#include "scsi/pr-manager.h"
40#include "scsi/constants.h"
41
42#if defined(__APPLE__) && (__MACH__)
43#include <paths.h>
44#include <sys/param.h>
45#include <IOKit/IOKitLib.h>
46#include <IOKit/IOBSD.h>
47#include <IOKit/storage/IOMediaBSDClient.h>
48#include <IOKit/storage/IOMedia.h>
49#include <IOKit/storage/IOCDMedia.h>
50
51#include <IOKit/storage/IODVDMedia.h>
52#include <CoreFoundation/CoreFoundation.h>
53#endif
54
55#ifdef __sun__
56#define _POSIX_PTHREAD_SEMANTICS 1
57#include <sys/dkio.h>
58#endif
59#ifdef __linux__
60#include <sys/ioctl.h>
61#include <sys/param.h>
62#include <linux/cdrom.h>
63#include <linux/fd.h>
64#include <linux/fs.h>
65#include <linux/hdreg.h>
66#include <scsi/sg.h>
67#ifdef __s390__
68#include <asm/dasd.h>
69#endif
70#ifndef FS_NOCOW_FL
71#define FS_NOCOW_FL 0x00800000
72#endif
73#endif
74#if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
75#include <linux/falloc.h>
76#endif
77#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
78#include <sys/disk.h>
79#include <sys/cdio.h>
80#endif
81
82#ifdef __OpenBSD__
83#include <sys/ioctl.h>
84#include <sys/disklabel.h>
85#include <sys/dkio.h>
86#endif
87
88#ifdef __NetBSD__
89#include <sys/ioctl.h>
90#include <sys/disklabel.h>
91#include <sys/dkio.h>
92#include <sys/disk.h>
93#endif
94
95#ifdef __DragonFly__
96#include <sys/ioctl.h>
97#include <sys/diskslice.h>
98#endif
99
100#ifdef CONFIG_XFS
101#include <xfs/xfs.h>
102#endif
103
104
105
106#ifdef DEBUG_BLOCK
107# define DEBUG_BLOCK_PRINT 1
108#else
109# define DEBUG_BLOCK_PRINT 0
110#endif
111#define DPRINTF(fmt, ...) \
112do { \
113 if (DEBUG_BLOCK_PRINT) { \
114 printf(fmt, ## __VA_ARGS__); \
115 } \
116} while (0)
117
118
119#ifndef O_DSYNC
120#ifdef O_SYNC
121#define O_DSYNC O_SYNC
122#elif defined(O_FSYNC)
123#define O_DSYNC O_FSYNC
124#endif
125#endif
126
127
128#ifndef O_DIRECT
129#define O_DIRECT O_DSYNC
130#endif
131
132#define FTYPE_FILE 0
133#define FTYPE_CD 1
134
135#define MAX_BLOCKSIZE 4096
136
137
138
139#define RAW_LOCK_PERM_BASE 100
140#define RAW_LOCK_SHARED_BASE 200
141
142typedef struct BDRVRawState {
143 int fd;
144 int lock_fd;
145 bool use_lock;
146 int type;
147 int open_flags;
148 size_t buf_align;
149
150
151 uint64_t perm;
152 uint64_t shared_perm;
153
154#ifdef CONFIG_XFS
155 bool is_xfs:1;
156#endif
157 bool has_discard:1;
158 bool has_write_zeroes:1;
159 bool discard_zeroes:1;
160 bool use_linux_aio:1;
161 bool page_cache_inconsistent:1;
162 bool has_fallocate;
163 bool needs_alignment;
164
165 PRManager *pr_mgr;
166} BDRVRawState;
167
168typedef struct BDRVRawReopenState {
169 int fd;
170 int open_flags;
171} BDRVRawReopenState;
172
173static int fd_open(BlockDriverState *bs);
174static int64_t raw_getlength(BlockDriverState *bs);
175
176typedef struct RawPosixAIOData {
177 BlockDriverState *bs;
178 int aio_fildes;
179 union {
180 struct iovec *aio_iov;
181 void *aio_ioctl_buf;
182 };
183 int aio_niov;
184 uint64_t aio_nbytes;
185#define aio_ioctl_cmd aio_nbytes
186 off_t aio_offset;
187 int aio_type;
188} RawPosixAIOData;
189
190#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
191static int cdrom_reopen(BlockDriverState *bs);
192#endif
193
194#if defined(__NetBSD__)
195static int raw_normalize_devicepath(const char **filename)
196{
197 static char namebuf[PATH_MAX];
198 const char *dp, *fname;
199 struct stat sb;
200
201 fname = *filename;
202 dp = strrchr(fname, '/');
203 if (lstat(fname, &sb) < 0) {
204 fprintf(stderr, "%s: stat failed: %s\n",
205 fname, strerror(errno));
206 return -errno;
207 }
208
209 if (!S_ISBLK(sb.st_mode)) {
210 return 0;
211 }
212
213 if (dp == NULL) {
214 snprintf(namebuf, PATH_MAX, "r%s", fname);
215 } else {
216 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
217 (int)(dp - fname), fname, dp + 1);
218 }
219 fprintf(stderr, "%s is a block device", fname);
220 *filename = namebuf;
221 fprintf(stderr, ", using %s\n", *filename);
222
223 return 0;
224}
225#else
226static int raw_normalize_devicepath(const char **filename)
227{
228 return 0;
229}
230#endif
231
232
233
234
235static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
236{
237 unsigned int sector_size;
238 bool success = false;
239 int i;
240
241 errno = ENOTSUP;
242 static const unsigned long ioctl_list[] = {
243#ifdef BLKSSZGET
244 BLKSSZGET,
245#endif
246#ifdef DKIOCGETBLOCKSIZE
247 DKIOCGETBLOCKSIZE,
248#endif
249#ifdef DIOCGSECTORSIZE
250 DIOCGSECTORSIZE,
251#endif
252 };
253
254
255 for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
256 if (ioctl(fd, ioctl_list[i], §or_size) >= 0) {
257 *sector_size_p = sector_size;
258 success = true;
259 }
260 }
261
262 return success ? 0 : -errno;
263}
264
265
266
267
268
269
270static int probe_physical_blocksize(int fd, unsigned int *blk_size)
271{
272#ifdef BLKPBSZGET
273 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
274 return -errno;
275 }
276 return 0;
277#else
278 return -ENOTSUP;
279#endif
280}
281
282
283
284
285
286static bool raw_is_io_aligned(int fd, void *buf, size_t len)
287{
288 ssize_t ret = pread(fd, buf, len, 0);
289
290 if (ret >= 0) {
291 return true;
292 }
293
294#ifdef __linux__
295
296
297
298
299 if (errno != EINVAL) {
300 return true;
301 }
302#endif
303
304 return false;
305}
306
307static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
308{
309 BDRVRawState *s = bs->opaque;
310 char *buf;
311 size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
312
313
314
315 if (bdrv_is_sg(bs) || !s->needs_alignment) {
316 bs->bl.request_alignment = 1;
317 s->buf_align = 1;
318 return;
319 }
320
321 bs->bl.request_alignment = 0;
322 s->buf_align = 0;
323
324 if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
325 bs->bl.request_alignment = 0;
326 }
327#ifdef CONFIG_XFS
328 if (s->is_xfs) {
329 struct dioattr da;
330 if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
331 bs->bl.request_alignment = da.d_miniosz;
332
333
334 }
335 }
336#endif
337
338
339 if (!s->buf_align) {
340 size_t align;
341 buf = qemu_memalign(max_align, 2 * max_align);
342 for (align = 512; align <= max_align; align <<= 1) {
343 if (raw_is_io_aligned(fd, buf + align, max_align)) {
344 s->buf_align = align;
345 break;
346 }
347 }
348 qemu_vfree(buf);
349 }
350
351 if (!bs->bl.request_alignment) {
352 size_t align;
353 buf = qemu_memalign(s->buf_align, max_align);
354 for (align = 512; align <= max_align; align <<= 1) {
355 if (raw_is_io_aligned(fd, buf, align)) {
356 bs->bl.request_alignment = align;
357 break;
358 }
359 }
360 qemu_vfree(buf);
361 }
362
363 if (!s->buf_align || !bs->bl.request_alignment) {
364 error_setg(errp, "Could not find working O_DIRECT alignment");
365 error_append_hint(errp, "Try cache.direct=off\n");
366 }
367}
368
369static void raw_parse_flags(int bdrv_flags, int *open_flags)
370{
371 assert(open_flags != NULL);
372
373 *open_flags |= O_BINARY;
374 *open_flags &= ~O_ACCMODE;
375 if (bdrv_flags & BDRV_O_RDWR) {
376 *open_flags |= O_RDWR;
377 } else {
378 *open_flags |= O_RDONLY;
379 }
380
381
382
383 if ((bdrv_flags & BDRV_O_NOCACHE)) {
384 *open_flags |= O_DIRECT;
385 }
386}
387
388static void raw_parse_filename(const char *filename, QDict *options,
389 Error **errp)
390{
391 bdrv_parse_filename_strip_prefix(filename, "file:", options);
392}
393
394static QemuOptsList raw_runtime_opts = {
395 .name = "raw",
396 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
397 .desc = {
398 {
399 .name = "filename",
400 .type = QEMU_OPT_STRING,
401 .help = "File name of the image",
402 },
403 {
404 .name = "aio",
405 .type = QEMU_OPT_STRING,
406 .help = "host AIO implementation (threads, native)",
407 },
408 {
409 .name = "locking",
410 .type = QEMU_OPT_STRING,
411 .help = "file locking mode (on/off/auto, default: auto)",
412 },
413 {
414 .name = "pr-manager",
415 .type = QEMU_OPT_STRING,
416 .help = "id of persistent reservation manager object (default: none)",
417 },
418 { }
419 },
420};
421
422static int raw_open_common(BlockDriverState *bs, QDict *options,
423 int bdrv_flags, int open_flags, Error **errp)
424{
425 BDRVRawState *s = bs->opaque;
426 QemuOpts *opts;
427 Error *local_err = NULL;
428 const char *filename = NULL;
429 const char *str;
430 BlockdevAioOptions aio, aio_default;
431 int fd, ret;
432 struct stat st;
433 OnOffAuto locking;
434
435 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
436 qemu_opts_absorb_qdict(opts, options, &local_err);
437 if (local_err) {
438 error_propagate(errp, local_err);
439 ret = -EINVAL;
440 goto fail;
441 }
442
443 filename = qemu_opt_get(opts, "filename");
444
445 ret = raw_normalize_devicepath(&filename);
446 if (ret != 0) {
447 error_setg_errno(errp, -ret, "Could not normalize device path");
448 goto fail;
449 }
450
451 aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
452 ? BLOCKDEV_AIO_OPTIONS_NATIVE
453 : BLOCKDEV_AIO_OPTIONS_THREADS;
454 aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
455 qemu_opt_get(opts, "aio"),
456 aio_default, &local_err);
457 if (local_err) {
458 error_propagate(errp, local_err);
459 ret = -EINVAL;
460 goto fail;
461 }
462 s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
463
464 locking = qapi_enum_parse(&OnOffAuto_lookup,
465 qemu_opt_get(opts, "locking"),
466 ON_OFF_AUTO_AUTO, &local_err);
467 if (local_err) {
468 error_propagate(errp, local_err);
469 ret = -EINVAL;
470 goto fail;
471 }
472 switch (locking) {
473 case ON_OFF_AUTO_ON:
474 s->use_lock = true;
475 if (!qemu_has_ofd_lock()) {
476 fprintf(stderr,
477 "File lock requested but OFD locking syscall is "
478 "unavailable, falling back to POSIX file locks.\n"
479 "Due to the implementation, locks can be lost "
480 "unexpectedly.\n");
481 }
482 break;
483 case ON_OFF_AUTO_OFF:
484 s->use_lock = false;
485 break;
486 case ON_OFF_AUTO_AUTO:
487 s->use_lock = qemu_has_ofd_lock();
488 break;
489 default:
490 abort();
491 }
492
493 str = qemu_opt_get(opts, "pr-manager");
494 if (str) {
495 s->pr_mgr = pr_manager_lookup(str, &local_err);
496 if (local_err) {
497 error_propagate(errp, local_err);
498 ret = -EINVAL;
499 goto fail;
500 }
501 }
502
503 s->open_flags = open_flags;
504 raw_parse_flags(bdrv_flags, &s->open_flags);
505
506 s->fd = -1;
507 fd = qemu_open(filename, s->open_flags, 0644);
508 if (fd < 0) {
509 ret = -errno;
510 error_setg_errno(errp, errno, "Could not open '%s'", filename);
511 if (ret == -EROFS) {
512 ret = -EACCES;
513 }
514 goto fail;
515 }
516 s->fd = fd;
517
518 s->lock_fd = -1;
519 if (s->use_lock) {
520 fd = qemu_open(filename, s->open_flags);
521 if (fd < 0) {
522 ret = -errno;
523 error_setg_errno(errp, errno, "Could not open '%s' for locking",
524 filename);
525 qemu_close(s->fd);
526 goto fail;
527 }
528 s->lock_fd = fd;
529 }
530 s->perm = 0;
531 s->shared_perm = BLK_PERM_ALL;
532
533#ifdef CONFIG_LINUX_AIO
534
535 if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {
536 error_setg(errp, "aio=native was specified, but it requires "
537 "cache.direct=on, which was not specified.");
538 ret = -EINVAL;
539 goto fail;
540 }
541#else
542 if (s->use_linux_aio) {
543 error_setg(errp, "aio=native was specified, but is not supported "
544 "in this build.");
545 ret = -EINVAL;
546 goto fail;
547 }
548#endif
549
550 s->has_discard = true;
551 s->has_write_zeroes = true;
552 if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
553 s->needs_alignment = true;
554 }
555
556 if (fstat(s->fd, &st) < 0) {
557 ret = -errno;
558 error_setg_errno(errp, errno, "Could not stat file");
559 goto fail;
560 }
561 if (S_ISREG(st.st_mode)) {
562 s->discard_zeroes = true;
563 s->has_fallocate = true;
564 }
565 if (S_ISBLK(st.st_mode)) {
566#ifdef BLKDISCARDZEROES
567 unsigned int arg;
568 if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
569 s->discard_zeroes = true;
570 }
571#endif
572#ifdef __linux__
573
574
575
576
577 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
578 s->discard_zeroes = false;
579 s->has_write_zeroes = false;
580 }
581#endif
582 }
583#ifdef __FreeBSD__
584 if (S_ISCHR(st.st_mode)) {
585
586
587
588
589
590
591 s->needs_alignment = true;
592 }
593#endif
594
595#ifdef CONFIG_XFS
596 if (platform_test_xfs_fd(s->fd)) {
597 s->is_xfs = true;
598 }
599#endif
600
601 bs->supported_zero_flags = s->discard_zeroes ? BDRV_REQ_MAY_UNMAP : 0;
602 ret = 0;
603fail:
604 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
605 unlink(filename);
606 }
607 qemu_opts_del(opts);
608 return ret;
609}
610
611static int raw_open(BlockDriverState *bs, QDict *options, int flags,
612 Error **errp)
613{
614 BDRVRawState *s = bs->opaque;
615
616 s->type = FTYPE_FILE;
617 return raw_open_common(bs, options, flags, 0, errp);
618}
619
620typedef enum {
621 RAW_PL_PREPARE,
622 RAW_PL_COMMIT,
623 RAW_PL_ABORT,
624} RawPermLockOp;
625
626#define PERM_FOREACH(i) \
627 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
628
629
630
631
632
633static int raw_apply_lock_bytes(BDRVRawState *s,
634 uint64_t perm_lock_bits,
635 uint64_t shared_perm_lock_bits,
636 bool unlock, Error **errp)
637{
638 int ret;
639 int i;
640
641 PERM_FOREACH(i) {
642 int off = RAW_LOCK_PERM_BASE + i;
643 if (perm_lock_bits & (1ULL << i)) {
644 ret = qemu_lock_fd(s->lock_fd, off, 1, false);
645 if (ret) {
646 error_setg(errp, "Failed to lock byte %d", off);
647 return ret;
648 }
649 } else if (unlock) {
650 ret = qemu_unlock_fd(s->lock_fd, off, 1);
651 if (ret) {
652 error_setg(errp, "Failed to unlock byte %d", off);
653 return ret;
654 }
655 }
656 }
657 PERM_FOREACH(i) {
658 int off = RAW_LOCK_SHARED_BASE + i;
659 if (shared_perm_lock_bits & (1ULL << i)) {
660 ret = qemu_lock_fd(s->lock_fd, off, 1, false);
661 if (ret) {
662 error_setg(errp, "Failed to lock byte %d", off);
663 return ret;
664 }
665 } else if (unlock) {
666 ret = qemu_unlock_fd(s->lock_fd, off, 1);
667 if (ret) {
668 error_setg(errp, "Failed to unlock byte %d", off);
669 return ret;
670 }
671 }
672 }
673 return 0;
674}
675
676
677static int raw_check_lock_bytes(BDRVRawState *s,
678 uint64_t perm, uint64_t shared_perm,
679 Error **errp)
680{
681 int ret;
682 int i;
683
684 PERM_FOREACH(i) {
685 int off = RAW_LOCK_SHARED_BASE + i;
686 uint64_t p = 1ULL << i;
687 if (perm & p) {
688 ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
689 if (ret) {
690 char *perm_name = bdrv_perm_names(p);
691 error_setg(errp,
692 "Failed to get \"%s\" lock",
693 perm_name);
694 g_free(perm_name);
695 error_append_hint(errp,
696 "Is another process using the image?\n");
697 return ret;
698 }
699 }
700 }
701 PERM_FOREACH(i) {
702 int off = RAW_LOCK_PERM_BASE + i;
703 uint64_t p = 1ULL << i;
704 if (!(shared_perm & p)) {
705 ret = qemu_lock_fd_test(s->lock_fd, off, 1, true);
706 if (ret) {
707 char *perm_name = bdrv_perm_names(p);
708 error_setg(errp,
709 "Failed to get shared \"%s\" lock",
710 perm_name);
711 g_free(perm_name);
712 error_append_hint(errp,
713 "Is another process using the image?\n");
714 return ret;
715 }
716 }
717 }
718 return 0;
719}
720
721static int raw_handle_perm_lock(BlockDriverState *bs,
722 RawPermLockOp op,
723 uint64_t new_perm, uint64_t new_shared,
724 Error **errp)
725{
726 BDRVRawState *s = bs->opaque;
727 int ret = 0;
728 Error *local_err = NULL;
729
730 if (!s->use_lock) {
731 return 0;
732 }
733
734 if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
735 return 0;
736 }
737
738 assert(s->lock_fd > 0);
739
740 switch (op) {
741 case RAW_PL_PREPARE:
742 ret = raw_apply_lock_bytes(s, s->perm | new_perm,
743 ~s->shared_perm | ~new_shared,
744 false, errp);
745 if (!ret) {
746 ret = raw_check_lock_bytes(s, new_perm, new_shared, errp);
747 if (!ret) {
748 return 0;
749 }
750 }
751 op = RAW_PL_ABORT;
752
753 case RAW_PL_ABORT:
754 raw_apply_lock_bytes(s, s->perm, ~s->shared_perm, true, &local_err);
755 if (local_err) {
756
757
758
759 error_report_err(local_err);
760 }
761 break;
762 case RAW_PL_COMMIT:
763 raw_apply_lock_bytes(s, new_perm, ~new_shared, true, &local_err);
764 if (local_err) {
765
766
767
768 error_report_err(local_err);
769 }
770 break;
771 }
772 return ret;
773}
774
775static int raw_reopen_prepare(BDRVReopenState *state,
776 BlockReopenQueue *queue, Error **errp)
777{
778 BDRVRawState *s;
779 BDRVRawReopenState *rs;
780 int ret = 0;
781 Error *local_err = NULL;
782
783 assert(state != NULL);
784 assert(state->bs != NULL);
785
786 s = state->bs->opaque;
787
788 state->opaque = g_new0(BDRVRawReopenState, 1);
789 rs = state->opaque;
790
791 if (s->type == FTYPE_CD) {
792 rs->open_flags |= O_NONBLOCK;
793 }
794
795 raw_parse_flags(state->flags, &rs->open_flags);
796
797 rs->fd = -1;
798
799 int fcntl_flags = O_APPEND | O_NONBLOCK;
800#ifdef O_NOATIME
801 fcntl_flags |= O_NOATIME;
802#endif
803
804#ifdef O_ASYNC
805
806
807
808
809
810 assert((s->open_flags & O_ASYNC) == 0);
811#endif
812
813 if ((rs->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
814
815 rs->fd = qemu_dup(s->fd);
816 if (rs->fd >= 0) {
817 ret = fcntl_setfl(rs->fd, rs->open_flags);
818 if (ret) {
819 qemu_close(rs->fd);
820 rs->fd = -1;
821 }
822 }
823 }
824
825
826 if (rs->fd == -1) {
827 const char *normalized_filename = state->bs->filename;
828 ret = raw_normalize_devicepath(&normalized_filename);
829 if (ret < 0) {
830 error_setg_errno(errp, -ret, "Could not normalize device path");
831 } else {
832 assert(!(rs->open_flags & O_CREAT));
833 rs->fd = qemu_open(normalized_filename, rs->open_flags);
834 if (rs->fd == -1) {
835 error_setg_errno(errp, errno, "Could not reopen file");
836 ret = -1;
837 }
838 }
839 }
840
841
842
843 if (rs->fd != -1) {
844 raw_probe_alignment(state->bs, rs->fd, &local_err);
845 if (local_err) {
846 qemu_close(rs->fd);
847 rs->fd = -1;
848 error_propagate(errp, local_err);
849 ret = -EINVAL;
850 }
851 }
852
853 return ret;
854}
855
856static void raw_reopen_commit(BDRVReopenState *state)
857{
858 BDRVRawReopenState *rs = state->opaque;
859 BDRVRawState *s = state->bs->opaque;
860
861 s->open_flags = rs->open_flags;
862
863 qemu_close(s->fd);
864 s->fd = rs->fd;
865
866 g_free(state->opaque);
867 state->opaque = NULL;
868}
869
870
871static void raw_reopen_abort(BDRVReopenState *state)
872{
873 BDRVRawReopenState *rs = state->opaque;
874
875
876 if (rs == NULL) {
877 return;
878 }
879
880 if (rs->fd >= 0) {
881 qemu_close(rs->fd);
882 rs->fd = -1;
883 }
884 g_free(state->opaque);
885 state->opaque = NULL;
886}
887
888static int hdev_get_max_transfer_length(BlockDriverState *bs, int fd)
889{
890#ifdef BLKSECTGET
891 int max_bytes = 0;
892 short max_sectors = 0;
893 if (bs->sg && ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
894 return max_bytes;
895 } else if (!bs->sg && ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
896 return max_sectors << BDRV_SECTOR_BITS;
897 } else {
898 return -errno;
899 }
900#else
901 return -ENOSYS;
902#endif
903}
904
905static int hdev_get_max_segments(const struct stat *st)
906{
907#ifdef CONFIG_LINUX
908 char buf[32];
909 const char *end;
910 char *sysfspath;
911 int ret;
912 int fd = -1;
913 long max_segments;
914
915 sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
916 major(st->st_rdev), minor(st->st_rdev));
917 fd = open(sysfspath, O_RDONLY);
918 if (fd == -1) {
919 ret = -errno;
920 goto out;
921 }
922 do {
923 ret = read(fd, buf, sizeof(buf) - 1);
924 } while (ret == -1 && errno == EINTR);
925 if (ret < 0) {
926 ret = -errno;
927 goto out;
928 } else if (ret == 0) {
929 ret = -EIO;
930 goto out;
931 }
932 buf[ret] = 0;
933
934 ret = qemu_strtol(buf, &end, 10, &max_segments);
935 if (ret == 0 && end && *end == '\n') {
936 ret = max_segments;
937 }
938
939out:
940 if (fd != -1) {
941 close(fd);
942 }
943 g_free(sysfspath);
944 return ret;
945#else
946 return -ENOTSUP;
947#endif
948}
949
950static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
951{
952 BDRVRawState *s = bs->opaque;
953 struct stat st;
954
955 if (!fstat(s->fd, &st)) {
956 if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
957 int ret = hdev_get_max_transfer_length(bs, s->fd);
958 if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
959 bs->bl.max_transfer = pow2floor(ret);
960 }
961 ret = hdev_get_max_segments(&st);
962 if (ret > 0) {
963 bs->bl.max_transfer = MIN(bs->bl.max_transfer,
964 ret * getpagesize());
965 }
966 }
967 }
968
969 raw_probe_alignment(bs, s->fd, errp);
970 bs->bl.min_mem_alignment = s->buf_align;
971 bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
972}
973
974static int check_for_dasd(int fd)
975{
976#ifdef BIODASDINFO2
977 struct dasd_information2_t info = {0};
978
979 return ioctl(fd, BIODASDINFO2, &info);
980#else
981 return -1;
982#endif
983}
984
985
986
987
988
989
990static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
991{
992 BDRVRawState *s = bs->opaque;
993 int ret;
994
995
996 if (check_for_dasd(s->fd) < 0) {
997 return -ENOTSUP;
998 }
999 ret = probe_logical_blocksize(s->fd, &bsz->log);
1000 if (ret < 0) {
1001 return ret;
1002 }
1003 return probe_physical_blocksize(s->fd, &bsz->phys);
1004}
1005
1006
1007
1008
1009
1010
1011
1012#ifdef __linux__
1013static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1014{
1015 BDRVRawState *s = bs->opaque;
1016 struct hd_geometry ioctl_geo = {0};
1017
1018
1019 if (check_for_dasd(s->fd) < 0) {
1020 return -ENOTSUP;
1021 }
1022 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1023 return -errno;
1024 }
1025
1026
1027 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1028 return -ENOTSUP;
1029 }
1030
1031 if (ioctl_geo.start != 0) {
1032 return -ENOTSUP;
1033 }
1034 geo->heads = ioctl_geo.heads;
1035 geo->sectors = ioctl_geo.sectors;
1036 geo->cylinders = ioctl_geo.cylinders;
1037
1038 return 0;
1039}
1040#else
1041static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1042{
1043 return -ENOTSUP;
1044}
1045#endif
1046
1047static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
1048{
1049 int ret;
1050
1051 ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
1052 if (ret == -1) {
1053 return -errno;
1054 }
1055
1056 return 0;
1057}
1058
1059static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
1060{
1061 BDRVRawState *s = aiocb->bs->opaque;
1062 int ret;
1063
1064 if (s->page_cache_inconsistent) {
1065 return -EIO;
1066 }
1067
1068 ret = qemu_fdatasync(aiocb->aio_fildes);
1069 if (ret == -1) {
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083 if ((s->open_flags & O_DIRECT) == 0) {
1084 s->page_cache_inconsistent = true;
1085 }
1086 return -errno;
1087 }
1088 return 0;
1089}
1090
1091#ifdef CONFIG_PREADV
1092
1093static bool preadv_present = true;
1094
1095static ssize_t
1096qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1097{
1098 return preadv(fd, iov, nr_iov, offset);
1099}
1100
1101static ssize_t
1102qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1103{
1104 return pwritev(fd, iov, nr_iov, offset);
1105}
1106
1107#else
1108
1109static bool preadv_present = false;
1110
1111static ssize_t
1112qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1113{
1114 return -ENOSYS;
1115}
1116
1117static ssize_t
1118qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1119{
1120 return -ENOSYS;
1121}
1122
1123#endif
1124
1125static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1126{
1127 ssize_t len;
1128
1129 do {
1130 if (aiocb->aio_type & QEMU_AIO_WRITE)
1131 len = qemu_pwritev(aiocb->aio_fildes,
1132 aiocb->aio_iov,
1133 aiocb->aio_niov,
1134 aiocb->aio_offset);
1135 else
1136 len = qemu_preadv(aiocb->aio_fildes,
1137 aiocb->aio_iov,
1138 aiocb->aio_niov,
1139 aiocb->aio_offset);
1140 } while (len == -1 && errno == EINTR);
1141
1142 if (len == -1) {
1143 return -errno;
1144 }
1145 return len;
1146}
1147
1148
1149
1150
1151
1152
1153
1154static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1155{
1156 ssize_t offset = 0;
1157 ssize_t len;
1158
1159 while (offset < aiocb->aio_nbytes) {
1160 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1161 len = pwrite(aiocb->aio_fildes,
1162 (const char *)buf + offset,
1163 aiocb->aio_nbytes - offset,
1164 aiocb->aio_offset + offset);
1165 } else {
1166 len = pread(aiocb->aio_fildes,
1167 buf + offset,
1168 aiocb->aio_nbytes - offset,
1169 aiocb->aio_offset + offset);
1170 }
1171 if (len == -1 && errno == EINTR) {
1172 continue;
1173 } else if (len == -1 && errno == EINVAL &&
1174 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1175 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1176 offset > 0) {
1177
1178
1179
1180
1181 break;
1182 } else if (len == -1) {
1183 offset = -errno;
1184 break;
1185 } else if (len == 0) {
1186 break;
1187 }
1188 offset += len;
1189 }
1190
1191 return offset;
1192}
1193
1194static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
1195{
1196 ssize_t nbytes;
1197 char *buf;
1198
1199 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1200
1201
1202
1203
1204 if (aiocb->aio_niov == 1) {
1205 return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
1206 }
1207
1208
1209
1210
1211
1212
1213 if (preadv_present) {
1214 nbytes = handle_aiocb_rw_vector(aiocb);
1215 if (nbytes == aiocb->aio_nbytes ||
1216 (nbytes < 0 && nbytes != -ENOSYS)) {
1217 return nbytes;
1218 }
1219 preadv_present = false;
1220 }
1221
1222
1223
1224
1225
1226
1227 }
1228
1229
1230
1231
1232
1233 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1234 if (buf == NULL) {
1235 return -ENOMEM;
1236 }
1237
1238 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1239 char *p = buf;
1240 int i;
1241
1242 for (i = 0; i < aiocb->aio_niov; ++i) {
1243 memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
1244 p += aiocb->aio_iov[i].iov_len;
1245 }
1246 assert(p - buf == aiocb->aio_nbytes);
1247 }
1248
1249 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1250 if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
1251 char *p = buf;
1252 size_t count = aiocb->aio_nbytes, copy;
1253 int i;
1254
1255 for (i = 0; i < aiocb->aio_niov && count; ++i) {
1256 copy = count;
1257 if (copy > aiocb->aio_iov[i].iov_len) {
1258 copy = aiocb->aio_iov[i].iov_len;
1259 }
1260 memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1261 assert(count >= copy);
1262 p += copy;
1263 count -= copy;
1264 }
1265 assert(count == 0);
1266 }
1267 qemu_vfree(buf);
1268
1269 return nbytes;
1270}
1271
1272#ifdef CONFIG_XFS
1273static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1274{
1275 struct xfs_flock64 fl;
1276 int err;
1277
1278 memset(&fl, 0, sizeof(fl));
1279 fl.l_whence = SEEK_SET;
1280 fl.l_start = offset;
1281 fl.l_len = bytes;
1282
1283 if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1284 err = errno;
1285 DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1286 return -err;
1287 }
1288
1289 return 0;
1290}
1291
1292static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1293{
1294 struct xfs_flock64 fl;
1295 int err;
1296
1297 memset(&fl, 0, sizeof(fl));
1298 fl.l_whence = SEEK_SET;
1299 fl.l_start = offset;
1300 fl.l_len = bytes;
1301
1302 if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1303 err = errno;
1304 DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1305 return -err;
1306 }
1307
1308 return 0;
1309}
1310#endif
1311
1312static int translate_err(int err)
1313{
1314 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1315 err == -ENOTTY) {
1316 err = -ENOTSUP;
1317 }
1318 return err;
1319}
1320
1321#ifdef CONFIG_FALLOCATE
1322static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1323{
1324 do {
1325 if (fallocate(fd, mode, offset, len) == 0) {
1326 return 0;
1327 }
1328 } while (errno == EINTR);
1329 return translate_err(-errno);
1330}
1331#endif
1332
1333static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1334{
1335 int ret = -ENOTSUP;
1336 BDRVRawState *s = aiocb->bs->opaque;
1337
1338 if (!s->has_write_zeroes) {
1339 return -ENOTSUP;
1340 }
1341
1342#ifdef BLKZEROOUT
1343 do {
1344 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1345 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1346 return 0;
1347 }
1348 } while (errno == EINTR);
1349
1350 ret = translate_err(-errno);
1351#endif
1352
1353 if (ret == -ENOTSUP) {
1354 s->has_write_zeroes = false;
1355 }
1356 return ret;
1357}
1358
1359static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1360{
1361#if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1362 BDRVRawState *s = aiocb->bs->opaque;
1363#endif
1364#ifdef CONFIG_FALLOCATE
1365 int64_t len;
1366#endif
1367
1368 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1369 return handle_aiocb_write_zeroes_block(aiocb);
1370 }
1371
1372#ifdef CONFIG_XFS
1373 if (s->is_xfs) {
1374 return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1375 }
1376#endif
1377
1378#ifdef CONFIG_FALLOCATE_ZERO_RANGE
1379 if (s->has_write_zeroes) {
1380 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1381 aiocb->aio_offset, aiocb->aio_nbytes);
1382 if (ret == 0 || ret != -ENOTSUP) {
1383 return ret;
1384 }
1385 s->has_write_zeroes = false;
1386 }
1387#endif
1388
1389#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1390 if (s->has_discard && s->has_fallocate) {
1391 int ret = do_fallocate(s->fd,
1392 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1393 aiocb->aio_offset, aiocb->aio_nbytes);
1394 if (ret == 0) {
1395 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1396 if (ret == 0 || ret != -ENOTSUP) {
1397 return ret;
1398 }
1399 s->has_fallocate = false;
1400 } else if (ret != -ENOTSUP) {
1401 return ret;
1402 } else {
1403 s->has_discard = false;
1404 }
1405 }
1406#endif
1407
1408#ifdef CONFIG_FALLOCATE
1409
1410
1411 len = bdrv_getlength(aiocb->bs);
1412 if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1413 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1414 if (ret == 0 || ret != -ENOTSUP) {
1415 return ret;
1416 }
1417 s->has_fallocate = false;
1418 }
1419#endif
1420
1421 return -ENOTSUP;
1422}
1423
1424static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1425{
1426 int ret = -EOPNOTSUPP;
1427 BDRVRawState *s = aiocb->bs->opaque;
1428
1429 if (!s->has_discard) {
1430 return -ENOTSUP;
1431 }
1432
1433 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1434#ifdef BLKDISCARD
1435 do {
1436 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1437 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1438 return 0;
1439 }
1440 } while (errno == EINTR);
1441
1442 ret = -errno;
1443#endif
1444 } else {
1445#ifdef CONFIG_XFS
1446 if (s->is_xfs) {
1447 return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1448 }
1449#endif
1450
1451#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1452 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1453 aiocb->aio_offset, aiocb->aio_nbytes);
1454#endif
1455 }
1456
1457 ret = translate_err(ret);
1458 if (ret == -ENOTSUP) {
1459 s->has_discard = false;
1460 }
1461 return ret;
1462}
1463
1464static int aio_worker(void *arg)
1465{
1466 RawPosixAIOData *aiocb = arg;
1467 ssize_t ret = 0;
1468
1469 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1470 case QEMU_AIO_READ:
1471 ret = handle_aiocb_rw(aiocb);
1472 if (ret >= 0 && ret < aiocb->aio_nbytes) {
1473 iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1474 0, aiocb->aio_nbytes - ret);
1475
1476 ret = aiocb->aio_nbytes;
1477 }
1478 if (ret == aiocb->aio_nbytes) {
1479 ret = 0;
1480 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1481 ret = -EINVAL;
1482 }
1483 break;
1484 case QEMU_AIO_WRITE:
1485 ret = handle_aiocb_rw(aiocb);
1486 if (ret == aiocb->aio_nbytes) {
1487 ret = 0;
1488 } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1489 ret = -EINVAL;
1490 }
1491 break;
1492 case QEMU_AIO_FLUSH:
1493 ret = handle_aiocb_flush(aiocb);
1494 break;
1495 case QEMU_AIO_IOCTL:
1496 ret = handle_aiocb_ioctl(aiocb);
1497 break;
1498 case QEMU_AIO_DISCARD:
1499 ret = handle_aiocb_discard(aiocb);
1500 break;
1501 case QEMU_AIO_WRITE_ZEROES:
1502 ret = handle_aiocb_write_zeroes(aiocb);
1503 break;
1504 default:
1505 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1506 ret = -EINVAL;
1507 break;
1508 }
1509
1510 g_free(aiocb);
1511 return ret;
1512}
1513
1514static int paio_submit_co(BlockDriverState *bs, int fd,
1515 int64_t offset, QEMUIOVector *qiov,
1516 int bytes, int type)
1517{
1518 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1519 ThreadPool *pool;
1520
1521 acb->bs = bs;
1522 acb->aio_type = type;
1523 acb->aio_fildes = fd;
1524
1525 acb->aio_nbytes = bytes;
1526 acb->aio_offset = offset;
1527
1528 if (qiov) {
1529 acb->aio_iov = qiov->iov;
1530 acb->aio_niov = qiov->niov;
1531 assert(qiov->size == bytes);
1532 }
1533
1534 trace_paio_submit_co(offset, bytes, type);
1535 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1536 return thread_pool_submit_co(pool, aio_worker, acb);
1537}
1538
1539static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1540 int64_t offset, QEMUIOVector *qiov, int bytes,
1541 BlockCompletionFunc *cb, void *opaque, int type)
1542{
1543 RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1544 ThreadPool *pool;
1545
1546 acb->bs = bs;
1547 acb->aio_type = type;
1548 acb->aio_fildes = fd;
1549
1550 acb->aio_nbytes = bytes;
1551 acb->aio_offset = offset;
1552
1553 if (qiov) {
1554 acb->aio_iov = qiov->iov;
1555 acb->aio_niov = qiov->niov;
1556 assert(qiov->size == acb->aio_nbytes);
1557 }
1558
1559 trace_paio_submit(acb, opaque, offset, bytes, type);
1560 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1561 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1562}
1563
1564static int coroutine_fn raw_co_prw(BlockDriverState *bs, uint64_t offset,
1565 uint64_t bytes, QEMUIOVector *qiov, int type)
1566{
1567 BDRVRawState *s = bs->opaque;
1568
1569 if (fd_open(bs) < 0)
1570 return -EIO;
1571
1572
1573
1574
1575
1576
1577
1578 if (s->needs_alignment) {
1579 if (!bdrv_qiov_is_aligned(bs, qiov)) {
1580 type |= QEMU_AIO_MISALIGNED;
1581#ifdef CONFIG_LINUX_AIO
1582 } else if (s->use_linux_aio) {
1583 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1584 assert(qiov->size == bytes);
1585 return laio_co_submit(bs, aio, s->fd, offset, qiov, type);
1586#endif
1587 }
1588 }
1589
1590 return paio_submit_co(bs, s->fd, offset, qiov, bytes, type);
1591}
1592
1593static int coroutine_fn raw_co_preadv(BlockDriverState *bs, uint64_t offset,
1594 uint64_t bytes, QEMUIOVector *qiov,
1595 int flags)
1596{
1597 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_READ);
1598}
1599
1600static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, uint64_t offset,
1601 uint64_t bytes, QEMUIOVector *qiov,
1602 int flags)
1603{
1604 assert(flags == 0);
1605 return raw_co_prw(bs, offset, bytes, qiov, QEMU_AIO_WRITE);
1606}
1607
1608static void raw_aio_plug(BlockDriverState *bs)
1609{
1610#ifdef CONFIG_LINUX_AIO
1611 BDRVRawState *s = bs->opaque;
1612 if (s->use_linux_aio) {
1613 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1614 laio_io_plug(bs, aio);
1615 }
1616#endif
1617}
1618
1619static void raw_aio_unplug(BlockDriverState *bs)
1620{
1621#ifdef CONFIG_LINUX_AIO
1622 BDRVRawState *s = bs->opaque;
1623 if (s->use_linux_aio) {
1624 LinuxAioState *aio = aio_get_linux_aio(bdrv_get_aio_context(bs));
1625 laio_io_unplug(bs, aio);
1626 }
1627#endif
1628}
1629
1630static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1631 BlockCompletionFunc *cb, void *opaque)
1632{
1633 BDRVRawState *s = bs->opaque;
1634
1635 if (fd_open(bs) < 0)
1636 return NULL;
1637
1638 return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1639}
1640
1641static void raw_close(BlockDriverState *bs)
1642{
1643 BDRVRawState *s = bs->opaque;
1644
1645 if (s->fd >= 0) {
1646 qemu_close(s->fd);
1647 s->fd = -1;
1648 }
1649 if (s->lock_fd >= 0) {
1650 qemu_close(s->lock_fd);
1651 s->lock_fd = -1;
1652 }
1653}
1654
1655
1656
1657
1658
1659
1660
1661static int raw_regular_truncate(int fd, int64_t offset, PreallocMode prealloc,
1662 Error **errp)
1663{
1664 int result = 0;
1665 int64_t current_length = 0;
1666 char *buf = NULL;
1667 struct stat st;
1668
1669 if (fstat(fd, &st) < 0) {
1670 result = -errno;
1671 error_setg_errno(errp, -result, "Could not stat file");
1672 return result;
1673 }
1674
1675 current_length = st.st_size;
1676 if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
1677 error_setg(errp, "Cannot use preallocation for shrinking files");
1678 return -ENOTSUP;
1679 }
1680
1681 switch (prealloc) {
1682#ifdef CONFIG_POSIX_FALLOCATE
1683 case PREALLOC_MODE_FALLOC:
1684
1685
1686
1687
1688
1689 if (offset != current_length) {
1690 result = -posix_fallocate(fd, current_length, offset - current_length);
1691 if (result != 0) {
1692
1693 error_setg_errno(errp, -result,
1694 "Could not preallocate new data");
1695 }
1696 } else {
1697 result = 0;
1698 }
1699 goto out;
1700#endif
1701 case PREALLOC_MODE_FULL:
1702 {
1703 int64_t num = 0, left = offset - current_length;
1704 off_t seek_result;
1705
1706
1707
1708
1709
1710
1711 if (ftruncate(fd, offset) != 0) {
1712 result = -errno;
1713 error_setg_errno(errp, -result, "Could not resize file");
1714 goto out;
1715 }
1716
1717 buf = g_malloc0(65536);
1718
1719 seek_result = lseek(fd, current_length, SEEK_SET);
1720 if (seek_result < 0) {
1721 result = -errno;
1722 error_setg_errno(errp, -result,
1723 "Failed to seek to the old end of file");
1724 goto out;
1725 }
1726
1727 while (left > 0) {
1728 num = MIN(left, 65536);
1729 result = write(fd, buf, num);
1730 if (result < 0) {
1731 if (errno == EINTR) {
1732 continue;
1733 }
1734 result = -errno;
1735 error_setg_errno(errp, -result,
1736 "Could not write zeros for preallocation");
1737 goto out;
1738 }
1739 left -= result;
1740 }
1741 if (result >= 0) {
1742 result = fsync(fd);
1743 if (result < 0) {
1744 result = -errno;
1745 error_setg_errno(errp, -result,
1746 "Could not flush file to disk");
1747 goto out;
1748 }
1749 }
1750 goto out;
1751 }
1752 case PREALLOC_MODE_OFF:
1753 if (ftruncate(fd, offset) != 0) {
1754 result = -errno;
1755 error_setg_errno(errp, -result, "Could not resize file");
1756 }
1757 return result;
1758 default:
1759 result = -ENOTSUP;
1760 error_setg(errp, "Unsupported preallocation mode: %s",
1761 PreallocMode_str(prealloc));
1762 return result;
1763 }
1764
1765out:
1766 if (result < 0) {
1767 if (ftruncate(fd, current_length) < 0) {
1768 error_report("Failed to restore old file length: %s",
1769 strerror(errno));
1770 }
1771 }
1772
1773 g_free(buf);
1774 return result;
1775}
1776
1777static int raw_truncate(BlockDriverState *bs, int64_t offset,
1778 PreallocMode prealloc, Error **errp)
1779{
1780 BDRVRawState *s = bs->opaque;
1781 struct stat st;
1782 int ret;
1783
1784 if (fstat(s->fd, &st)) {
1785 ret = -errno;
1786 error_setg_errno(errp, -ret, "Failed to fstat() the file");
1787 return ret;
1788 }
1789
1790 if (S_ISREG(st.st_mode)) {
1791 return raw_regular_truncate(s->fd, offset, prealloc, errp);
1792 }
1793
1794 if (prealloc != PREALLOC_MODE_OFF) {
1795 error_setg(errp, "Preallocation mode '%s' unsupported for this "
1796 "non-regular file", PreallocMode_str(prealloc));
1797 return -ENOTSUP;
1798 }
1799
1800 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1801 if (offset > raw_getlength(bs)) {
1802 error_setg(errp, "Cannot grow device files");
1803 return -EINVAL;
1804 }
1805 } else {
1806 error_setg(errp, "Resizing this file is not supported");
1807 return -ENOTSUP;
1808 }
1809
1810 return 0;
1811}
1812
1813#ifdef __OpenBSD__
1814static int64_t raw_getlength(BlockDriverState *bs)
1815{
1816 BDRVRawState *s = bs->opaque;
1817 int fd = s->fd;
1818 struct stat st;
1819
1820 if (fstat(fd, &st))
1821 return -errno;
1822 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1823 struct disklabel dl;
1824
1825 if (ioctl(fd, DIOCGDINFO, &dl))
1826 return -errno;
1827 return (uint64_t)dl.d_secsize *
1828 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1829 } else
1830 return st.st_size;
1831}
1832#elif defined(__NetBSD__)
1833static int64_t raw_getlength(BlockDriverState *bs)
1834{
1835 BDRVRawState *s = bs->opaque;
1836 int fd = s->fd;
1837 struct stat st;
1838
1839 if (fstat(fd, &st))
1840 return -errno;
1841 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1842 struct dkwedge_info dkw;
1843
1844 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1845 return dkw.dkw_size * 512;
1846 } else {
1847 struct disklabel dl;
1848
1849 if (ioctl(fd, DIOCGDINFO, &dl))
1850 return -errno;
1851 return (uint64_t)dl.d_secsize *
1852 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1853 }
1854 } else
1855 return st.st_size;
1856}
1857#elif defined(__sun__)
1858static int64_t raw_getlength(BlockDriverState *bs)
1859{
1860 BDRVRawState *s = bs->opaque;
1861 struct dk_minfo minfo;
1862 int ret;
1863 int64_t size;
1864
1865 ret = fd_open(bs);
1866 if (ret < 0) {
1867 return ret;
1868 }
1869
1870
1871
1872
1873 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1874 if (ret != -1) {
1875 return minfo.dki_lbsize * minfo.dki_capacity;
1876 }
1877
1878
1879
1880
1881
1882 size = lseek(s->fd, 0, SEEK_END);
1883 if (size < 0) {
1884 return -errno;
1885 }
1886 return size;
1887}
1888#elif defined(CONFIG_BSD)
1889static int64_t raw_getlength(BlockDriverState *bs)
1890{
1891 BDRVRawState *s = bs->opaque;
1892 int fd = s->fd;
1893 int64_t size;
1894 struct stat sb;
1895#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1896 int reopened = 0;
1897#endif
1898 int ret;
1899
1900 ret = fd_open(bs);
1901 if (ret < 0)
1902 return ret;
1903
1904#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1905again:
1906#endif
1907 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1908#ifdef DIOCGMEDIASIZE
1909 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1910#elif defined(DIOCGPART)
1911 {
1912 struct partinfo pi;
1913 if (ioctl(fd, DIOCGPART, &pi) == 0)
1914 size = pi.media_size;
1915 else
1916 size = 0;
1917 }
1918 if (size == 0)
1919#endif
1920#if defined(__APPLE__) && defined(__MACH__)
1921 {
1922 uint64_t sectors = 0;
1923 uint32_t sector_size = 0;
1924
1925 if (ioctl(fd, DKIOCGETBLOCKCOUNT, §ors) == 0
1926 && ioctl(fd, DKIOCGETBLOCKSIZE, §or_size) == 0) {
1927 size = sectors * sector_size;
1928 } else {
1929 size = lseek(fd, 0LL, SEEK_END);
1930 if (size < 0) {
1931 return -errno;
1932 }
1933 }
1934 }
1935#else
1936 size = lseek(fd, 0LL, SEEK_END);
1937 if (size < 0) {
1938 return -errno;
1939 }
1940#endif
1941#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1942 switch(s->type) {
1943 case FTYPE_CD:
1944
1945 if (size == 2048LL * (unsigned)-1)
1946 size = 0;
1947
1948 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1949 reopened = 1;
1950 goto again;
1951 }
1952 }
1953#endif
1954 } else {
1955 size = lseek(fd, 0, SEEK_END);
1956 if (size < 0) {
1957 return -errno;
1958 }
1959 }
1960 return size;
1961}
1962#else
1963static int64_t raw_getlength(BlockDriverState *bs)
1964{
1965 BDRVRawState *s = bs->opaque;
1966 int ret;
1967 int64_t size;
1968
1969 ret = fd_open(bs);
1970 if (ret < 0) {
1971 return ret;
1972 }
1973
1974 size = lseek(s->fd, 0, SEEK_END);
1975 if (size < 0) {
1976 return -errno;
1977 }
1978 return size;
1979}
1980#endif
1981
1982static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1983{
1984 struct stat st;
1985 BDRVRawState *s = bs->opaque;
1986
1987 if (fstat(s->fd, &st) < 0) {
1988 return -errno;
1989 }
1990 return (int64_t)st.st_blocks * 512;
1991}
1992
1993static int raw_co_create(BlockdevCreateOptions *options, Error **errp)
1994{
1995 BlockdevCreateOptionsFile *file_opts;
1996 int fd;
1997 int result = 0;
1998
1999
2000 assert(options->driver == BLOCKDEV_DRIVER_FILE);
2001 file_opts = &options->u.file;
2002
2003 if (!file_opts->has_nocow) {
2004 file_opts->nocow = false;
2005 }
2006 if (!file_opts->has_preallocation) {
2007 file_opts->preallocation = PREALLOC_MODE_OFF;
2008 }
2009
2010
2011 fd = qemu_open(file_opts->filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
2012 0644);
2013 if (fd < 0) {
2014 result = -errno;
2015 error_setg_errno(errp, -result, "Could not create file");
2016 goto out;
2017 }
2018
2019 if (file_opts->nocow) {
2020#ifdef __linux__
2021
2022
2023
2024
2025
2026 int attr;
2027 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2028 attr |= FS_NOCOW_FL;
2029 ioctl(fd, FS_IOC_SETFLAGS, &attr);
2030 }
2031#endif
2032 }
2033
2034 result = raw_regular_truncate(fd, file_opts->size, file_opts->preallocation,
2035 errp);
2036 if (result < 0) {
2037 goto out_close;
2038 }
2039
2040out_close:
2041 if (qemu_close(fd) != 0 && result == 0) {
2042 result = -errno;
2043 error_setg_errno(errp, -result, "Could not close the new file");
2044 }
2045out:
2046 return result;
2047}
2048
2049static int coroutine_fn raw_co_create_opts(const char *filename, QemuOpts *opts,
2050 Error **errp)
2051{
2052 BlockdevCreateOptions options;
2053 int64_t total_size = 0;
2054 bool nocow = false;
2055 PreallocMode prealloc;
2056 char *buf = NULL;
2057 Error *local_err = NULL;
2058
2059
2060 strstart(filename, "file:", &filename);
2061
2062
2063 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2064 BDRV_SECTOR_SIZE);
2065 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
2066 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2067 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2068 PREALLOC_MODE_OFF, &local_err);
2069 g_free(buf);
2070 if (local_err) {
2071 error_propagate(errp, local_err);
2072 return -EINVAL;
2073 }
2074
2075 options = (BlockdevCreateOptions) {
2076 .driver = BLOCKDEV_DRIVER_FILE,
2077 .u.file = {
2078 .filename = (char *) filename,
2079 .size = total_size,
2080 .has_preallocation = true,
2081 .preallocation = prealloc,
2082 .has_nocow = true,
2083 .nocow = nocow,
2084 },
2085 };
2086 return raw_co_create(&options, errp);
2087}
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099static int find_allocation(BlockDriverState *bs, off_t start,
2100 off_t *data, off_t *hole)
2101{
2102#if defined SEEK_HOLE && defined SEEK_DATA
2103 BDRVRawState *s = bs->opaque;
2104 off_t offs;
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117 offs = lseek(s->fd, start, SEEK_DATA);
2118 if (offs < 0) {
2119 return -errno;
2120 }
2121
2122 if (offs < start) {
2123
2124
2125 return -EIO;
2126 }
2127
2128 if (offs > start) {
2129
2130 *hole = start;
2131 *data = offs;
2132 return 0;
2133 }
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154 offs = lseek(s->fd, start, SEEK_HOLE);
2155 if (offs < 0) {
2156 return -errno;
2157 }
2158
2159 if (offs < start) {
2160
2161
2162 return -EIO;
2163 }
2164
2165 if (offs > start) {
2166
2167
2168
2169
2170
2171
2172 *data = start;
2173 *hole = offs;
2174 return 0;
2175 }
2176
2177
2178 return -EBUSY;
2179#else
2180 return -ENOTSUP;
2181#endif
2182}
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
2196 bool want_zero,
2197 int64_t offset,
2198 int64_t bytes, int64_t *pnum,
2199 int64_t *map,
2200 BlockDriverState **file)
2201{
2202 off_t data = 0, hole = 0;
2203 int ret;
2204
2205 ret = fd_open(bs);
2206 if (ret < 0) {
2207 return ret;
2208 }
2209
2210 if (!want_zero) {
2211 *pnum = bytes;
2212 *map = offset;
2213 *file = bs;
2214 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2215 }
2216
2217 ret = find_allocation(bs, offset, &data, &hole);
2218 if (ret == -ENXIO) {
2219
2220 *pnum = bytes;
2221 ret = BDRV_BLOCK_ZERO;
2222 } else if (ret < 0) {
2223
2224 *pnum = bytes;
2225 ret = BDRV_BLOCK_DATA;
2226 } else if (data == offset) {
2227
2228
2229 *pnum = MIN(bytes, hole - offset);
2230 ret = BDRV_BLOCK_DATA;
2231 } else {
2232
2233 assert(hole == offset);
2234 *pnum = MIN(bytes, data - offset);
2235 ret = BDRV_BLOCK_ZERO;
2236 }
2237 *map = offset;
2238 *file = bs;
2239 return ret | BDRV_BLOCK_OFFSET_VALID;
2240}
2241
2242static coroutine_fn BlockAIOCB *raw_aio_pdiscard(BlockDriverState *bs,
2243 int64_t offset, int bytes,
2244 BlockCompletionFunc *cb, void *opaque)
2245{
2246 BDRVRawState *s = bs->opaque;
2247
2248 return paio_submit(bs, s->fd, offset, NULL, bytes,
2249 cb, opaque, QEMU_AIO_DISCARD);
2250}
2251
2252static int coroutine_fn raw_co_pwrite_zeroes(
2253 BlockDriverState *bs, int64_t offset,
2254 int bytes, BdrvRequestFlags flags)
2255{
2256 BDRVRawState *s = bs->opaque;
2257
2258 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2259 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
2260 QEMU_AIO_WRITE_ZEROES);
2261 } else if (s->discard_zeroes) {
2262 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
2263 QEMU_AIO_DISCARD);
2264 }
2265 return -ENOTSUP;
2266}
2267
2268static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2269{
2270 BDRVRawState *s = bs->opaque;
2271
2272 bdi->unallocated_blocks_are_zero = s->discard_zeroes;
2273 return 0;
2274}
2275
2276static QemuOptsList raw_create_opts = {
2277 .name = "raw-create-opts",
2278 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
2279 .desc = {
2280 {
2281 .name = BLOCK_OPT_SIZE,
2282 .type = QEMU_OPT_SIZE,
2283 .help = "Virtual disk size"
2284 },
2285 {
2286 .name = BLOCK_OPT_NOCOW,
2287 .type = QEMU_OPT_BOOL,
2288 .help = "Turn off copy-on-write (valid only on btrfs)"
2289 },
2290 {
2291 .name = BLOCK_OPT_PREALLOC,
2292 .type = QEMU_OPT_STRING,
2293 .help = "Preallocation mode (allowed values: off, falloc, full)"
2294 },
2295 { }
2296 }
2297};
2298
2299static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
2300 Error **errp)
2301{
2302 return raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
2303}
2304
2305static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
2306{
2307 BDRVRawState *s = bs->opaque;
2308 raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
2309 s->perm = perm;
2310 s->shared_perm = shared;
2311}
2312
2313static void raw_abort_perm_update(BlockDriverState *bs)
2314{
2315 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
2316}
2317
2318BlockDriver bdrv_file = {
2319 .format_name = "file",
2320 .protocol_name = "file",
2321 .instance_size = sizeof(BDRVRawState),
2322 .bdrv_needs_filename = true,
2323 .bdrv_probe = NULL,
2324 .bdrv_parse_filename = raw_parse_filename,
2325 .bdrv_file_open = raw_open,
2326 .bdrv_reopen_prepare = raw_reopen_prepare,
2327 .bdrv_reopen_commit = raw_reopen_commit,
2328 .bdrv_reopen_abort = raw_reopen_abort,
2329 .bdrv_close = raw_close,
2330 .bdrv_co_create = raw_co_create,
2331 .bdrv_co_create_opts = raw_co_create_opts,
2332 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2333 .bdrv_co_block_status = raw_co_block_status,
2334 .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
2335
2336 .bdrv_co_preadv = raw_co_preadv,
2337 .bdrv_co_pwritev = raw_co_pwritev,
2338 .bdrv_aio_flush = raw_aio_flush,
2339 .bdrv_aio_pdiscard = raw_aio_pdiscard,
2340 .bdrv_refresh_limits = raw_refresh_limits,
2341 .bdrv_io_plug = raw_aio_plug,
2342 .bdrv_io_unplug = raw_aio_unplug,
2343
2344 .bdrv_truncate = raw_truncate,
2345 .bdrv_getlength = raw_getlength,
2346 .bdrv_get_info = raw_get_info,
2347 .bdrv_get_allocated_file_size
2348 = raw_get_allocated_file_size,
2349 .bdrv_check_perm = raw_check_perm,
2350 .bdrv_set_perm = raw_set_perm,
2351 .bdrv_abort_perm_update = raw_abort_perm_update,
2352 .create_opts = &raw_create_opts,
2353};
2354
2355
2356
2357
2358#if defined(__APPLE__) && defined(__MACH__)
2359static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2360 CFIndex maxPathSize, int flags);
2361static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
2362{
2363 kern_return_t kernResult = KERN_FAILURE;
2364 mach_port_t masterPort;
2365 CFMutableDictionaryRef classesToMatch;
2366 const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
2367 char *mediaType = NULL;
2368
2369 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
2370 if ( KERN_SUCCESS != kernResult ) {
2371 printf( "IOMasterPort returned %d\n", kernResult );
2372 }
2373
2374 int index;
2375 for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
2376 classesToMatch = IOServiceMatching(matching_array[index]);
2377 if (classesToMatch == NULL) {
2378 error_report("IOServiceMatching returned NULL for %s",
2379 matching_array[index]);
2380 continue;
2381 }
2382 CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
2383 kCFBooleanTrue);
2384 kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch,
2385 mediaIterator);
2386 if (kernResult != KERN_SUCCESS) {
2387 error_report("Note: IOServiceGetMatchingServices returned %d",
2388 kernResult);
2389 continue;
2390 }
2391
2392
2393 if (*mediaIterator != 0) {
2394 DPRINTF("Matching using %s\n", matching_array[index]);
2395 mediaType = g_strdup(matching_array[index]);
2396 break;
2397 }
2398 }
2399 return mediaType;
2400}
2401
2402kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2403 CFIndex maxPathSize, int flags)
2404{
2405 io_object_t nextMedia;
2406 kern_return_t kernResult = KERN_FAILURE;
2407 *bsdPath = '\0';
2408 nextMedia = IOIteratorNext( mediaIterator );
2409 if ( nextMedia )
2410 {
2411 CFTypeRef bsdPathAsCFString;
2412 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2413 if ( bsdPathAsCFString ) {
2414 size_t devPathLength;
2415 strcpy( bsdPath, _PATH_DEV );
2416 if (flags & BDRV_O_NOCACHE) {
2417 strcat(bsdPath, "r");
2418 }
2419 devPathLength = strlen( bsdPath );
2420 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2421 kernResult = KERN_SUCCESS;
2422 }
2423 CFRelease( bsdPathAsCFString );
2424 }
2425 IOObjectRelease( nextMedia );
2426 }
2427
2428 return kernResult;
2429}
2430
2431
2432static bool setup_cdrom(char *bsd_path, Error **errp)
2433{
2434 int index, num_of_test_partitions = 2, fd;
2435 char test_partition[MAXPATHLEN];
2436 bool partition_found = false;
2437
2438
2439 for (index = 0; index < num_of_test_partitions; index++) {
2440 snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
2441 index);
2442 fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE);
2443 if (fd >= 0) {
2444 partition_found = true;
2445 qemu_close(fd);
2446 break;
2447 }
2448 }
2449
2450
2451 if (partition_found == false) {
2452 error_setg(errp, "Failed to find a working partition on disc");
2453 } else {
2454 DPRINTF("Using %s as optical disc\n", test_partition);
2455 pstrcpy(bsd_path, MAXPATHLEN, test_partition);
2456 }
2457 return partition_found;
2458}
2459
2460
2461static void print_unmounting_directions(const char *file_name)
2462{
2463 error_report("If device %s is mounted on the desktop, unmount"
2464 " it first before using it in QEMU", file_name);
2465 error_report("Command to unmount device: diskutil unmountDisk %s",
2466 file_name);
2467 error_report("Command to mount device: diskutil mountDisk %s", file_name);
2468}
2469
2470#endif
2471
2472static int hdev_probe_device(const char *filename)
2473{
2474 struct stat st;
2475
2476
2477 if (strstart(filename, "/dev/cdrom", NULL))
2478 return 50;
2479
2480 if (stat(filename, &st) >= 0 &&
2481 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2482 return 100;
2483 }
2484
2485 return 0;
2486}
2487
2488static int check_hdev_writable(BDRVRawState *s)
2489{
2490#if defined(BLKROGET)
2491
2492
2493
2494
2495
2496
2497
2498
2499 struct stat st;
2500 int readonly = 0;
2501
2502 if (fstat(s->fd, &st)) {
2503 return -errno;
2504 }
2505
2506 if (!S_ISBLK(st.st_mode)) {
2507 return 0;
2508 }
2509
2510 if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2511 return -errno;
2512 }
2513
2514 if (readonly) {
2515 return -EACCES;
2516 }
2517#endif
2518 return 0;
2519}
2520
2521static void hdev_parse_filename(const char *filename, QDict *options,
2522 Error **errp)
2523{
2524 bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
2525}
2526
2527static bool hdev_is_sg(BlockDriverState *bs)
2528{
2529
2530#if defined(__linux__)
2531
2532 BDRVRawState *s = bs->opaque;
2533 struct stat st;
2534 struct sg_scsi_id scsiid;
2535 int sg_version;
2536 int ret;
2537
2538 if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
2539 return false;
2540 }
2541
2542 ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
2543 if (ret < 0) {
2544 return false;
2545 }
2546
2547 ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
2548 if (ret >= 0) {
2549 DPRINTF("SG device found: type=%d, version=%d\n",
2550 scsiid.scsi_type, sg_version);
2551 return true;
2552 }
2553
2554#endif
2555
2556 return false;
2557}
2558
2559static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2560 Error **errp)
2561{
2562 BDRVRawState *s = bs->opaque;
2563 Error *local_err = NULL;
2564 int ret;
2565
2566#if defined(__APPLE__) && defined(__MACH__)
2567
2568
2569
2570
2571
2572
2573 const char *filename = qdict_get_str(options, "filename");
2574 char bsd_path[MAXPATHLEN] = "";
2575 bool error_occurred = false;
2576
2577
2578 if (strcmp(filename, "/dev/cdrom") == 0) {
2579 char *mediaType = NULL;
2580 kern_return_t ret_val;
2581 io_iterator_t mediaIterator = 0;
2582
2583 mediaType = FindEjectableOpticalMedia(&mediaIterator);
2584 if (mediaType == NULL) {
2585 error_setg(errp, "Please make sure your CD/DVD is in the optical"
2586 " drive");
2587 error_occurred = true;
2588 goto hdev_open_Mac_error;
2589 }
2590
2591 ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
2592 if (ret_val != KERN_SUCCESS) {
2593 error_setg(errp, "Could not get BSD path for optical drive");
2594 error_occurred = true;
2595 goto hdev_open_Mac_error;
2596 }
2597
2598
2599 if (bsd_path[0] == '\0') {
2600 error_setg(errp, "Failed to obtain bsd path for optical drive");
2601 error_occurred = true;
2602 goto hdev_open_Mac_error;
2603 }
2604
2605
2606 if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
2607 setup_cdrom(bsd_path, errp) == false) {
2608 print_unmounting_directions(bsd_path);
2609 error_occurred = true;
2610 goto hdev_open_Mac_error;
2611 }
2612
2613 qdict_put_str(options, "filename", bsd_path);
2614
2615hdev_open_Mac_error:
2616 g_free(mediaType);
2617 if (mediaIterator) {
2618 IOObjectRelease(mediaIterator);
2619 }
2620 if (error_occurred) {
2621 return -ENOENT;
2622 }
2623 }
2624#endif
2625
2626 s->type = FTYPE_FILE;
2627
2628 ret = raw_open_common(bs, options, flags, 0, &local_err);
2629 if (ret < 0) {
2630 error_propagate(errp, local_err);
2631#if defined(__APPLE__) && defined(__MACH__)
2632 if (*bsd_path) {
2633 filename = bsd_path;
2634 }
2635
2636 if (strncmp(filename, "/dev/", 5) == 0) {
2637 print_unmounting_directions(filename);
2638 }
2639#endif
2640 return ret;
2641 }
2642
2643
2644 bs->sg = hdev_is_sg(bs);
2645
2646 if (flags & BDRV_O_RDWR) {
2647 ret = check_hdev_writable(s);
2648 if (ret < 0) {
2649 raw_close(bs);
2650 error_setg_errno(errp, -ret, "The device is not writable");
2651 return ret;
2652 }
2653 }
2654
2655 return ret;
2656}
2657
2658#if defined(__linux__)
2659
2660static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2661 unsigned long int req, void *buf,
2662 BlockCompletionFunc *cb, void *opaque)
2663{
2664 BDRVRawState *s = bs->opaque;
2665 RawPosixAIOData *acb;
2666 ThreadPool *pool;
2667
2668 if (fd_open(bs) < 0)
2669 return NULL;
2670
2671 if (req == SG_IO && s->pr_mgr) {
2672 struct sg_io_hdr *io_hdr = buf;
2673 if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
2674 io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
2675 return pr_manager_execute(s->pr_mgr, bdrv_get_aio_context(bs),
2676 s->fd, io_hdr, cb, opaque);
2677 }
2678 }
2679
2680 acb = g_new(RawPosixAIOData, 1);
2681 acb->bs = bs;
2682 acb->aio_type = QEMU_AIO_IOCTL;
2683 acb->aio_fildes = s->fd;
2684 acb->aio_offset = 0;
2685 acb->aio_ioctl_buf = buf;
2686 acb->aio_ioctl_cmd = req;
2687 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2688 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2689}
2690#endif
2691
2692static int fd_open(BlockDriverState *bs)
2693{
2694 BDRVRawState *s = bs->opaque;
2695
2696
2697 if (s->fd >= 0)
2698 return 0;
2699 return -EIO;
2700}
2701
2702static coroutine_fn BlockAIOCB *hdev_aio_pdiscard(BlockDriverState *bs,
2703 int64_t offset, int bytes,
2704 BlockCompletionFunc *cb, void *opaque)
2705{
2706 BDRVRawState *s = bs->opaque;
2707
2708 if (fd_open(bs) < 0) {
2709 return NULL;
2710 }
2711 return paio_submit(bs, s->fd, offset, NULL, bytes,
2712 cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2713}
2714
2715static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
2716 int64_t offset, int bytes, BdrvRequestFlags flags)
2717{
2718 BDRVRawState *s = bs->opaque;
2719 int rc;
2720
2721 rc = fd_open(bs);
2722 if (rc < 0) {
2723 return rc;
2724 }
2725 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2726 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
2727 QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2728 } else if (s->discard_zeroes) {
2729 return paio_submit_co(bs, s->fd, offset, NULL, bytes,
2730 QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2731 }
2732 return -ENOTSUP;
2733}
2734
2735static int coroutine_fn hdev_co_create_opts(const char *filename, QemuOpts *opts,
2736 Error **errp)
2737{
2738 int fd;
2739 int ret = 0;
2740 struct stat stat_buf;
2741 int64_t total_size = 0;
2742 bool has_prefix;
2743
2744
2745
2746
2747
2748 has_prefix =
2749 strstart(filename, "host_device:", &filename) ||
2750 strstart(filename, "host_cdrom:" , &filename);
2751
2752 (void)has_prefix;
2753
2754 ret = raw_normalize_devicepath(&filename);
2755 if (ret < 0) {
2756 error_setg_errno(errp, -ret, "Could not normalize device path");
2757 return ret;
2758 }
2759
2760
2761 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2762 BDRV_SECTOR_SIZE);
2763
2764 fd = qemu_open(filename, O_WRONLY | O_BINARY);
2765 if (fd < 0) {
2766 ret = -errno;
2767 error_setg_errno(errp, -ret, "Could not open device");
2768 return ret;
2769 }
2770
2771 if (fstat(fd, &stat_buf) < 0) {
2772 ret = -errno;
2773 error_setg_errno(errp, -ret, "Could not stat device");
2774 } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2775 error_setg(errp,
2776 "The given file is neither a block nor a character device");
2777 ret = -ENODEV;
2778 } else if (lseek(fd, 0, SEEK_END) < total_size) {
2779 error_setg(errp, "Device is too small");
2780 ret = -ENOSPC;
2781 }
2782
2783 if (!ret && total_size) {
2784 uint8_t buf[BDRV_SECTOR_SIZE] = { 0 };
2785 int64_t zero_size = MIN(BDRV_SECTOR_SIZE, total_size);
2786 if (lseek(fd, 0, SEEK_SET) == -1) {
2787 ret = -errno;
2788 } else {
2789 ret = qemu_write_full(fd, buf, zero_size);
2790 ret = ret == zero_size ? 0 : -errno;
2791 }
2792 }
2793 qemu_close(fd);
2794 return ret;
2795}
2796
2797static BlockDriver bdrv_host_device = {
2798 .format_name = "host_device",
2799 .protocol_name = "host_device",
2800 .instance_size = sizeof(BDRVRawState),
2801 .bdrv_needs_filename = true,
2802 .bdrv_probe_device = hdev_probe_device,
2803 .bdrv_parse_filename = hdev_parse_filename,
2804 .bdrv_file_open = hdev_open,
2805 .bdrv_close = raw_close,
2806 .bdrv_reopen_prepare = raw_reopen_prepare,
2807 .bdrv_reopen_commit = raw_reopen_commit,
2808 .bdrv_reopen_abort = raw_reopen_abort,
2809 .bdrv_co_create_opts = hdev_co_create_opts,
2810 .create_opts = &raw_create_opts,
2811 .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
2812
2813 .bdrv_co_preadv = raw_co_preadv,
2814 .bdrv_co_pwritev = raw_co_pwritev,
2815 .bdrv_aio_flush = raw_aio_flush,
2816 .bdrv_aio_pdiscard = hdev_aio_pdiscard,
2817 .bdrv_refresh_limits = raw_refresh_limits,
2818 .bdrv_io_plug = raw_aio_plug,
2819 .bdrv_io_unplug = raw_aio_unplug,
2820
2821 .bdrv_truncate = raw_truncate,
2822 .bdrv_getlength = raw_getlength,
2823 .bdrv_get_info = raw_get_info,
2824 .bdrv_get_allocated_file_size
2825 = raw_get_allocated_file_size,
2826 .bdrv_check_perm = raw_check_perm,
2827 .bdrv_set_perm = raw_set_perm,
2828 .bdrv_abort_perm_update = raw_abort_perm_update,
2829 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2830 .bdrv_probe_geometry = hdev_probe_geometry,
2831
2832
2833#ifdef __linux__
2834 .bdrv_aio_ioctl = hdev_aio_ioctl,
2835#endif
2836};
2837
2838#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2839static void cdrom_parse_filename(const char *filename, QDict *options,
2840 Error **errp)
2841{
2842 bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
2843}
2844#endif
2845
2846#ifdef __linux__
2847static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2848 Error **errp)
2849{
2850 BDRVRawState *s = bs->opaque;
2851
2852 s->type = FTYPE_CD;
2853
2854
2855 return raw_open_common(bs, options, flags, O_NONBLOCK, errp);
2856}
2857
2858static int cdrom_probe_device(const char *filename)
2859{
2860 int fd, ret;
2861 int prio = 0;
2862 struct stat st;
2863
2864 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2865 if (fd < 0) {
2866 goto out;
2867 }
2868 ret = fstat(fd, &st);
2869 if (ret == -1 || !S_ISBLK(st.st_mode)) {
2870 goto outc;
2871 }
2872
2873
2874 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2875 if (ret >= 0)
2876 prio = 100;
2877
2878outc:
2879 qemu_close(fd);
2880out:
2881 return prio;
2882}
2883
2884static bool cdrom_is_inserted(BlockDriverState *bs)
2885{
2886 BDRVRawState *s = bs->opaque;
2887 int ret;
2888
2889 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2890 return ret == CDS_DISC_OK;
2891}
2892
2893static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2894{
2895 BDRVRawState *s = bs->opaque;
2896
2897 if (eject_flag) {
2898 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2899 perror("CDROMEJECT");
2900 } else {
2901 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2902 perror("CDROMEJECT");
2903 }
2904}
2905
2906static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2907{
2908 BDRVRawState *s = bs->opaque;
2909
2910 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2911
2912
2913
2914
2915
2916 }
2917}
2918
2919static BlockDriver bdrv_host_cdrom = {
2920 .format_name = "host_cdrom",
2921 .protocol_name = "host_cdrom",
2922 .instance_size = sizeof(BDRVRawState),
2923 .bdrv_needs_filename = true,
2924 .bdrv_probe_device = cdrom_probe_device,
2925 .bdrv_parse_filename = cdrom_parse_filename,
2926 .bdrv_file_open = cdrom_open,
2927 .bdrv_close = raw_close,
2928 .bdrv_reopen_prepare = raw_reopen_prepare,
2929 .bdrv_reopen_commit = raw_reopen_commit,
2930 .bdrv_reopen_abort = raw_reopen_abort,
2931 .bdrv_co_create_opts = hdev_co_create_opts,
2932 .create_opts = &raw_create_opts,
2933
2934
2935 .bdrv_co_preadv = raw_co_preadv,
2936 .bdrv_co_pwritev = raw_co_pwritev,
2937 .bdrv_aio_flush = raw_aio_flush,
2938 .bdrv_refresh_limits = raw_refresh_limits,
2939 .bdrv_io_plug = raw_aio_plug,
2940 .bdrv_io_unplug = raw_aio_unplug,
2941
2942 .bdrv_truncate = raw_truncate,
2943 .bdrv_getlength = raw_getlength,
2944 .has_variable_length = true,
2945 .bdrv_get_allocated_file_size
2946 = raw_get_allocated_file_size,
2947
2948
2949 .bdrv_is_inserted = cdrom_is_inserted,
2950 .bdrv_eject = cdrom_eject,
2951 .bdrv_lock_medium = cdrom_lock_medium,
2952
2953
2954 .bdrv_aio_ioctl = hdev_aio_ioctl,
2955};
2956#endif
2957
2958#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2959static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2960 Error **errp)
2961{
2962 BDRVRawState *s = bs->opaque;
2963 Error *local_err = NULL;
2964 int ret;
2965
2966 s->type = FTYPE_CD;
2967
2968 ret = raw_open_common(bs, options, flags, 0, &local_err);
2969 if (ret) {
2970 error_propagate(errp, local_err);
2971 return ret;
2972 }
2973
2974
2975 ioctl(s->fd, CDIOCALLOW);
2976 return 0;
2977}
2978
2979static int cdrom_probe_device(const char *filename)
2980{
2981 if (strstart(filename, "/dev/cd", NULL) ||
2982 strstart(filename, "/dev/acd", NULL))
2983 return 100;
2984 return 0;
2985}
2986
2987static int cdrom_reopen(BlockDriverState *bs)
2988{
2989 BDRVRawState *s = bs->opaque;
2990 int fd;
2991
2992
2993
2994
2995
2996 if (s->fd >= 0)
2997 qemu_close(s->fd);
2998 fd = qemu_open(bs->filename, s->open_flags, 0644);
2999 if (fd < 0) {
3000 s->fd = -1;
3001 return -EIO;
3002 }
3003 s->fd = fd;
3004
3005
3006 ioctl(s->fd, CDIOCALLOW);
3007 return 0;
3008}
3009
3010static bool cdrom_is_inserted(BlockDriverState *bs)
3011{
3012 return raw_getlength(bs) > 0;
3013}
3014
3015static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
3016{
3017 BDRVRawState *s = bs->opaque;
3018
3019 if (s->fd < 0)
3020 return;
3021
3022 (void) ioctl(s->fd, CDIOCALLOW);
3023
3024 if (eject_flag) {
3025 if (ioctl(s->fd, CDIOCEJECT) < 0)
3026 perror("CDIOCEJECT");
3027 } else {
3028 if (ioctl(s->fd, CDIOCCLOSE) < 0)
3029 perror("CDIOCCLOSE");
3030 }
3031
3032 cdrom_reopen(bs);
3033}
3034
3035static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
3036{
3037 BDRVRawState *s = bs->opaque;
3038
3039 if (s->fd < 0)
3040 return;
3041 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
3042
3043
3044
3045
3046
3047 }
3048}
3049
3050static BlockDriver bdrv_host_cdrom = {
3051 .format_name = "host_cdrom",
3052 .protocol_name = "host_cdrom",
3053 .instance_size = sizeof(BDRVRawState),
3054 .bdrv_needs_filename = true,
3055 .bdrv_probe_device = cdrom_probe_device,
3056 .bdrv_parse_filename = cdrom_parse_filename,
3057 .bdrv_file_open = cdrom_open,
3058 .bdrv_close = raw_close,
3059 .bdrv_reopen_prepare = raw_reopen_prepare,
3060 .bdrv_reopen_commit = raw_reopen_commit,
3061 .bdrv_reopen_abort = raw_reopen_abort,
3062 .bdrv_co_create_opts = hdev_co_create_opts,
3063 .create_opts = &raw_create_opts,
3064
3065 .bdrv_co_preadv = raw_co_preadv,
3066 .bdrv_co_pwritev = raw_co_pwritev,
3067 .bdrv_aio_flush = raw_aio_flush,
3068 .bdrv_refresh_limits = raw_refresh_limits,
3069 .bdrv_io_plug = raw_aio_plug,
3070 .bdrv_io_unplug = raw_aio_unplug,
3071
3072 .bdrv_truncate = raw_truncate,
3073 .bdrv_getlength = raw_getlength,
3074 .has_variable_length = true,
3075 .bdrv_get_allocated_file_size
3076 = raw_get_allocated_file_size,
3077
3078
3079 .bdrv_is_inserted = cdrom_is_inserted,
3080 .bdrv_eject = cdrom_eject,
3081 .bdrv_lock_medium = cdrom_lock_medium,
3082};
3083#endif
3084
3085static void bdrv_file_init(void)
3086{
3087
3088
3089
3090
3091 bdrv_register(&bdrv_file);
3092 bdrv_register(&bdrv_host_device);
3093#ifdef __linux__
3094 bdrv_register(&bdrv_host_cdrom);
3095#endif
3096#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3097 bdrv_register(&bdrv_host_cdrom);
3098#endif
3099}
3100
3101block_init(bdrv_file_init);
3102