Debian Codegraph @

alloc.c

raw symbols SCIP
1 /*
2 * libhugetlbfs - Easy use of Linux hugepages
3 * alloc.c - Simple allocator of regions backed by hugepages
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public License
7 * as published by the Free Software Foundation; either version 2.1 of
8 * the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #define _GNU_SOURCE
21 #include <fcntl.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <time.h>
28 #include <sys/mman.h>
29 #include <sys/types.h>
30
31 #include "hugetlbfs.h"
32 #include "libhugetlbfs_internal.h"
33
34 /* Allocate base pages if huge page allocation fails */
35 static void *fallback_base_pages(size_t len, ghp_t flags)
36 {
37 int fd;
38 void *buf;
39 INFO("get_huge_pages: Falling back to base pages\n");
40
41 /*
42 * Map /dev/zero instead of MAP_ANONYMOUS avoid VMA mergings. Freeing
43 * pages depends on /proc/pid/maps to find lengths of allocations.
44 * This is a bit lazy and if found to be costly due to either the
45 * extra open() or virtual address space usage, we could track active
46 * mappings in a lock-protected list instead.
47 */
48 fd = open("/dev/zero", O_RDWR);
49 if (fd == -1) {
50 ERROR("get_huge_pages: Failed to open /dev/zero for fallback");
51 return NULL;
52 }
53
54 buf = mmap(NULL, len,
55 PROT_READ|PROT_WRITE,
56 MAP_PRIVATE,
57 fd, 0);
58 if (buf == MAP_FAILED) {
59 WARNING("Base page fallback failed: %s\n", strerror(errno));
60 buf = NULL;
61 }
62 close(fd);
63
64 return buf;
65 }
66
67 /**
68 * get_huge_pages - Allocate an amount of memory backed by huge pages
69 * len: Size of the region to allocate, must be hugepage-aligned
70 * flags: Flags specifying the behaviour of the function
71 *
72 * This function allocates a region of memory that is backed by huge pages
73 * and hugepage-aligned. This is not a suitable drop-in for malloc() but a
74 * a malloc library could use this function to create a new fixed-size heap
75 * similar in principal to what morecore does for glibc malloc.
76 */
77 void *get_huge_pages(size_t len, ghp_t flags)
78 {
79 void *buf;
80 int buf_fd = -1;
81 int mmap_reserve = __hugetlb_opts.no_reserve ? MAP_NORESERVE : 0;
82 int mmap_hugetlb = 0;
83 int ret;
84
85 /* Catch an altogether-too easy typo */
86 if (flags & GHR_MASK)
87 ERROR("Improper use of GHR_* in get_huge_pages()\n");
88
89 #ifdef MAP_HUGETLB
90 mmap_hugetlb = MAP_HUGETLB;
91 #endif
92
93 if (__hugetlb_opts.map_hugetlb &&
94 gethugepagesize() == kernel_default_hugepage_size()) {
95 /* Because we can use MAP_HUGETLB, we simply mmap the region */
96 buf = mmap(NULL, len, PROT_READ|PROT_WRITE,
97 MAP_PRIVATE|MAP_ANONYMOUS|mmap_hugetlb|mmap_reserve,
98 0, 0);
99 } else {
100 /* Create a file descriptor for the new region */
101 buf_fd = hugetlbfs_unlinked_fd();
102 if (buf_fd < 0) {
103 WARNING("Couldn't open hugetlbfs file for %zd-sized buffer\n",
104 len);
105 return NULL;
106 }
107
108 /* Map the requested region */
109 buf = mmap(NULL, len, PROT_READ|PROT_WRITE,
110 MAP_PRIVATE|mmap_reserve, buf_fd, 0);
111 }
112
113 if (buf == MAP_FAILED) {
114 if (buf_fd >= 0)
115 close(buf_fd);
116
117 WARNING("get_huge_pages: New region mapping failed (flags: 0x%lX): %s\n",
118 flags, strerror(errno));
119 return NULL;
120 }
121
122 /* Fault the region to ensure accesses succeed */
123 ret = hugetlbfs_prefault(buf, len);
124 if (ret != 0) {
125 munmap(buf, len);
126 if (buf_fd >= 0)
127 close(buf_fd);
128
129 WARNING("get_huge_pages: Prefaulting failed (flags: 0x%lX): %s\n",
130 flags, strerror(ret));
131 return NULL;
132 }
133
134 /* Close the file so we do not have to track the descriptor */
135 if (buf_fd >= 0 && close(buf_fd) != 0) {
136 WARNING("Failed to close new buffer fd: %s\n", strerror(errno));
137 munmap(buf, len);
138 return NULL;
139 }
140
141 /* woo, new buffer of shiny */
142 return buf;
143 }
144
145 #define MAPS_BUF_SZ 4096
146 static void __free_huge_pages(void *ptr, int aligned)
147 {
148 FILE *fd;
149 char line[MAPS_BUF_SZ];
150 unsigned long start = 0, end = 0;
151 unsigned long palign = 0, hpalign = 0;
152 unsigned long hpalign_end = 0;
153
154 /*
155 * /proc/self/maps is used to determine the length of the original
156 * allocation. As mappings are based on different files, we can
157 * assume that maps will not merge. If the hugepages were truly
158 * anonymous, this assumption would be broken.
159 */
160 fd = fopen("/proc/self/maps", "r");
161 if (!fd) {
162 ERROR("Failed to open /proc/self/maps\n");
163 return;
164 }
165
166 /*
167 * An unaligned address allocated by get_hugepage_region()
168 * could be either page or hugepage aligned
169 */
170 if (!aligned) {
171 palign = ALIGN_DOWN((unsigned long)ptr, getpagesize());
172 hpalign = ALIGN_DOWN((unsigned long)ptr, gethugepagesize());
173 }
174
175 /* Parse /proc/maps for address ranges line by line */
176 while (!feof(fd)) {
177 char *bufptr;
178 char *saveptr = NULL;
179
180 /* Read a line of input */
181 if (fgets(line, MAPS_BUF_SZ, fd) == NULL)
182 break;
183
184 /* Parse the line to get the start and end of each mapping */
185 bufptr = strtok_r(line, " ", &saveptr);
186 bufptr = strtok_r(bufptr, "-", &saveptr);
187 start = strtoull(bufptr, NULL, 16);
188 bufptr = strtok_r(NULL, "-", &saveptr);
189
190 /* If the correct mapping is found, remove it */
191 if (start == (unsigned long)ptr) {
192 end = strtoull(bufptr, NULL, 16);
193 munmap(ptr, end - start);
194 break;
195 }
196
197 /* If the passed address is aligned, just move along */
198 if (aligned)
199 continue;
200
201 /*
202 * If an address is hpage-aligned, record it but keep looking.
203 * We might find a page-aligned or exact address later
204 */
205 if (start == hpalign) {
206 hpalign_end = strtoull(bufptr, NULL, 16);
207 continue;
208 }
209
210 /* If an address is page-aligned, free it */
211 if (start == palign) {
212 end = strtoull(bufptr, NULL, 16);
213 munmap((void *)start, end - start);
214 break;
215 }
216
217 }
218
219 /*
220 * If no exact or page-aligned address was found, check for a
221 * hpage-aligned address. If found, free it, otherwise warn that
222 * the ptr pointed nowhere
223 */
224 if (end == 0) {
225 if (hpalign_end == 0)
226 ERROR("hugepages_free using invalid or double free\n");
227 else
228 munmap((void *)hpalign, hpalign_end - hpalign);
229 }
230
231 fclose(fd);
232 }
233
234 /**
235 * free_huge_pages - Free a region allocated that was backed by large pages
236 * ptr - The pointer to the buffer returned by get_huge_pages()
237 *
238 * This function finds a region to free based on the contents of
239 * /proc/pid/maps. The assumption is made that the ptr is the start of
240 * a hugepage region allocated with free_huge_pages. No checking is made
241 * that the pointer is to a hugepage backed region.
242 */
243 void free_huge_pages(void *ptr)
244 {
245 __free_huge_pages(ptr, 1);
246 }
247
248 /*
249 * Offset the buffer using bytes wasted due to alignment to avoid using the
250 * same cache lines for the start of every buffer returned by
251 * get_huge_pages(). A small effort is made to select a random cacheline
252 * rather than sequential lines to give decent behaviour on average.
253 */
254 void *cachecolor(void *buf, size_t len, size_t color_bytes)
255 {
256 static long cacheline_size = 0;
257 static int linemod = 0;
258 char *bytebuf = (char *)buf;
259 int numlines;
260 int line = 0;
261
262 /* Lookup our cacheline size once */
263 if (cacheline_size == 0) {
264 cacheline_size = sysconf(_SC_LEVEL2_CACHE_LINESIZE);
265 linemod = time(NULL);
266 }
267
268 numlines = color_bytes / cacheline_size;
269 DEBUG("%d lines of cacheline size %ld due to %zd wastage\n",
270 numlines, cacheline_size, color_bytes);
271 if (numlines) {
272 line = linemod % numlines;
273 bytebuf += cacheline_size * line;
274
275 /* Pseudo-ish random line selection */
276 linemod += len % numlines;
277 }
278 DEBUG("Using line offset %d from start\n", line);
279
280 return bytebuf;
281 }
282
283 /**
284 * get_hugepage_region - Allocate an amount of memory backed by huge pages
285 *
286 * len: Size of the region to allocate
287 * flags: Flags specifying the behaviour of the function
288 *
289 * This function allocates a region of memory backed by huge pages. Care should
290 * be taken when using this function as a drop-in replacement for malloc() as
291 * memory can be wasted if the length is not hugepage-aligned. This function
292 * is more relaxed than get_huge_pages() in that it allows fallback to small
293 * pages when requested.
294 */
295 void *get_hugepage_region(size_t len, ghr_t flags)
296 {
297 size_t aligned_len, wastage;
298 void *buf;
299
300 /* Catch an altogether-too easy typo */
301 if (flags & GHP_MASK)
302 ERROR("Improper use of GHP_* in get_hugepage_region()\n");
303
304 /* Align the len parameter to a hugepage boundary and allocate */
305 aligned_len = ALIGN(len, gethugepagesize());
306 buf = get_huge_pages(aligned_len, GHP_DEFAULT);
307 if (buf == NULL) {
308 if (flags & GHR_FALLBACK) {
309 aligned_len = ALIGN(len, getpagesize());
310 buf = fallback_base_pages(len, flags);
311 } else {
312 return buf;
313 }
314 }
315
316 /* Calculate wastage for coloring */
317 wastage = aligned_len - len;
318 if (wastage != 0 && !(flags & GHR_COLOR))
319 DEBUG("get_hugepage_region: Wasted %zd bytes due to alignment\n",
320 wastage);
321
322 /* Only colour if requested */
323 if (flags & GHR_COLOR)
324 buf = cachecolor(buf, len, wastage);
325
326 return buf;
327 }
328
329 /**
330 * free_hugepage_region - Free a region allocated by get_hugepage_region
331 * ptr - The pointer to the buffer returned by get_hugepage_region
332 *
333 * This function finds a region to free based on the contents of
334 * /proc/pid/maps. The assumption is made that the ptr is the start of
335 * a hugepage region allocated with get_hugepage_region. No checking is made
336 * that the pointer is to a hugepage backed region.
337 */
338 void free_hugepage_region(void *ptr)
339 {
340 __free_huge_pages(ptr, 0);
341 }