]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/jemalloc/src/chunk_mmap.c
Update llvm, clang and lldb to release_38 branch r260756.
[FreeBSD/FreeBSD.git] / contrib / jemalloc / src / chunk_mmap.c
1 #define JEMALLOC_CHUNK_MMAP_C_
2 #include "jemalloc/internal/jemalloc_internal.h"
3
4 /******************************************************************************/
5
6 static void *
7 chunk_alloc_mmap_slow(size_t size, size_t alignment, bool *zero, bool *commit)
8 {
9         void *ret;
10         size_t alloc_size;
11
12         alloc_size = size + alignment - PAGE;
13         /* Beware size_t wrap-around. */
14         if (alloc_size < size)
15                 return (NULL);
16         do {
17                 void *pages;
18                 size_t leadsize;
19                 pages = pages_map(NULL, alloc_size);
20                 if (pages == NULL)
21                         return (NULL);
22                 leadsize = ALIGNMENT_CEILING((uintptr_t)pages, alignment) -
23                     (uintptr_t)pages;
24                 ret = pages_trim(pages, alloc_size, leadsize, size);
25         } while (ret == NULL);
26
27         assert(ret != NULL);
28         *zero = true;
29         if (!*commit)
30                 *commit = pages_decommit(ret, size);
31         return (ret);
32 }
33
34 void *
35 chunk_alloc_mmap(size_t size, size_t alignment, bool *zero, bool *commit)
36 {
37         void *ret;
38         size_t offset;
39
40         /*
41          * Ideally, there would be a way to specify alignment to mmap() (like
42          * NetBSD has), but in the absence of such a feature, we have to work
43          * hard to efficiently create aligned mappings.  The reliable, but
44          * slow method is to create a mapping that is over-sized, then trim the
45          * excess.  However, that always results in one or two calls to
46          * pages_unmap().
47          *
48          * Optimistically try mapping precisely the right amount before falling
49          * back to the slow method, with the expectation that the optimistic
50          * approach works most of the time.
51          */
52
53         assert(alignment != 0);
54         assert((alignment & chunksize_mask) == 0);
55
56         ret = pages_map(NULL, size);
57         if (ret == NULL)
58                 return (NULL);
59         offset = ALIGNMENT_ADDR2OFFSET(ret, alignment);
60         if (offset != 0) {
61                 pages_unmap(ret, size);
62                 return (chunk_alloc_mmap_slow(size, alignment, zero, commit));
63         }
64
65         assert(ret != NULL);
66         *zero = true;
67         if (!*commit)
68                 *commit = pages_decommit(ret, size);
69         return (ret);
70 }
71
72 bool
73 chunk_dalloc_mmap(void *chunk, size_t size)
74 {
75
76         if (config_munmap)
77                 pages_unmap(chunk, size);
78
79         return (!config_munmap);
80 }