2 * Support for RAM backed by mmaped host memory.
4 * Copyright (c) 2015 Red Hat, Inc.
7 * Michael S. Tsirkin <mst@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or
10 * later. See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
14 #include "qemu/mmap-alloc.h"
15 #include "qemu/host-utils.h"
17 #define HUGETLBFS_MAGIC 0x958458f6
23 size_t qemu_fd_getpagesize(int fd
)
31 ret
= fstatfs(fd
, &fs
);
32 } while (ret
!= 0 && errno
== EINTR
);
34 if (ret
== 0 && fs
.f_type
== HUGETLBFS_MAGIC
) {
43 size_t qemu_mempath_getpagesize(const char *mem_path
)
50 ret
= statfs(mem_path
, &fs
);
51 } while (ret
!= 0 && errno
== EINTR
);
54 fprintf(stderr
, "Couldn't statfs() memory path: %s\n",
59 if (fs
.f_type
== HUGETLBFS_MAGIC
) {
60 /* It's hugepage, return the huge page size */
68 void *qemu_ram_mmap(int fd
, size_t size
, size_t align
, bool shared
)
71 * Note: this always allocates at least one extra page of virtual address
72 * space, even if size is already aligned.
74 size_t total
= size
+ align
;
75 #if defined(__powerpc64__) && defined(__linux__)
76 /* On ppc64 mappings in the same segment (aka slice) must share the same
77 * page size. Since we will be re-allocating part of this segment
78 * from the supplied fd, we should make sure to use the same page size, to
79 * this end we mmap the supplied fd. In this case, set MAP_NORESERVE to
80 * avoid allocating backing store memory.
81 * We do this unless we are using the system page size, in which case
82 * anonymous memory is OK.
84 int anonfd
= fd
== -1 || qemu_fd_getpagesize(fd
) == getpagesize() ? -1 : fd
;
85 int flags
= anonfd
== -1 ? MAP_ANONYMOUS
: MAP_NORESERVE
;
86 void *ptr
= mmap(0, total
, PROT_NONE
, flags
| MAP_PRIVATE
, anonfd
, 0);
88 void *ptr
= mmap(0, total
, PROT_NONE
, MAP_ANONYMOUS
| MAP_PRIVATE
, -1, 0);
93 if (ptr
== MAP_FAILED
) {
97 assert(is_power_of_2(align
));
98 /* Always align to host page size */
99 assert(align
>= getpagesize());
101 offset
= QEMU_ALIGN_UP((uintptr_t)ptr
, align
) - (uintptr_t)ptr
;
102 ptr1
= mmap(ptr
+ offset
, size
, PROT_READ
| PROT_WRITE
,
104 (fd
== -1 ? MAP_ANONYMOUS
: 0) |
105 (shared
? MAP_SHARED
: MAP_PRIVATE
),
107 if (ptr1
== MAP_FAILED
) {
117 * Leave a single PROT_NONE page allocated after the RAM block, to serve as
118 * a guard page guarding against potential buffer overflows.
121 if (total
> size
+ getpagesize()) {
122 munmap(ptr1
+ size
+ getpagesize(), total
- size
- getpagesize());
128 void qemu_ram_munmap(void *ptr
, size_t size
)
131 /* Unmap both the RAM block and the guard page */
132 munmap(ptr
, size
+ getpagesize());