]>
git.proxmox.com Git - mirror_qemu.git/blob - util/mmap-alloc.c
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
) {
39 /* SPARC Linux needs greater alignment than the pagesize */
40 return QEMU_VMALLOC_ALIGN
;
47 size_t qemu_mempath_getpagesize(const char *mem_path
)
55 ret
= statfs(mem_path
, &fs
);
56 } while (ret
!= 0 && errno
== EINTR
);
59 fprintf(stderr
, "Couldn't statfs() memory path: %s\n",
64 if (fs
.f_type
== HUGETLBFS_MAGIC
) {
65 /* It's hugepage, return the huge page size */
70 /* SPARC Linux needs greater alignment than the pagesize */
71 return QEMU_VMALLOC_ALIGN
;
78 void *qemu_ram_mmap(int fd
, size_t size
, size_t align
, bool shared
)
88 * Note: this always allocates at least one extra page of virtual address
89 * space, even if size is already aligned.
93 #if defined(__powerpc64__) && defined(__linux__)
94 /* On ppc64 mappings in the same segment (aka slice) must share the same
95 * page size. Since we will be re-allocating part of this segment
96 * from the supplied fd, we should make sure to use the same page size, to
97 * this end we mmap the supplied fd. In this case, set MAP_NORESERVE to
98 * avoid allocating backing store memory.
99 * We do this unless we are using the system page size, in which case
100 * anonymous memory is OK.
103 if (fd
== -1 || qemu_fd_getpagesize(fd
) == getpagesize()) {
105 flags
|= MAP_ANONYMOUS
;
108 flags
|= MAP_NORESERVE
;
112 flags
= MAP_PRIVATE
| MAP_ANONYMOUS
;
115 guardptr
= mmap(0, total
, PROT_NONE
, flags
, guardfd
, 0);
117 if (guardptr
== MAP_FAILED
) {
121 assert(is_power_of_2(align
));
122 /* Always align to host page size */
123 assert(align
>= getpagesize());
126 flags
|= fd
== -1 ? MAP_ANONYMOUS
: 0;
127 flags
|= shared
? MAP_SHARED
: MAP_PRIVATE
;
128 offset
= QEMU_ALIGN_UP((uintptr_t)guardptr
, align
) - (uintptr_t)guardptr
;
130 ptr
= mmap(guardptr
+ offset
, size
, PROT_READ
| PROT_WRITE
, flags
, fd
, 0);
132 if (ptr
== MAP_FAILED
) {
133 munmap(guardptr
, total
);
138 munmap(guardptr
, offset
);
142 * Leave a single PROT_NONE page allocated after the RAM block, to serve as
143 * a guard page guarding against potential buffer overflows.
146 if (total
> size
+ getpagesize()) {
147 munmap(ptr
+ size
+ getpagesize(), total
- size
- getpagesize());
153 void qemu_ram_munmap(void *ptr
, size_t size
)
156 /* Unmap both the RAM block and the guard page */
157 munmap(ptr
, size
+ getpagesize());