2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // Functions to provide smarter use of jemalloc, if jemalloc is being used.
18 // http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
20 #ifndef FOLLY_MALLOC_H_
21 #define FOLLY_MALLOC_H_
23 // If using fbstring from libstdc++, then just define stub code
24 // here to typedef the fbstring type into the folly namespace.
25 // This provides backwards compatibility for code that explicitly
26 // includes and uses fbstring.
27 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
29 #include <folly/detail/Malloc.h>
34 using std::goodMallocSize;
35 using std::jemallocMinInPlaceExpandable;
36 using std::usingJEMalloc;
37 using std::smartRealloc;
38 using std::checkedMalloc;
39 using std::checkedCalloc;
40 using std::checkedRealloc;
43 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
45 #ifdef _LIBSTDCXX_FBSTRING
46 #pragma GCC system_header
49 * Declare rallocm(), allocm(), and mallctl() as weak symbols. These will be
50 * provided by jemalloc if we are using jemalloc, or will be NULL if we are
51 * using another malloc implementation.
53 extern "C" int rallocm(void**, size_t*, size_t, size_t, int)
54 __attribute__((__weak__));
55 extern "C" int allocm(void**, size_t*, size_t, int)
56 __attribute__((__weak__));
57 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
58 __attribute__((__weak__));
60 #include <bits/functexcept.h>
61 #define FOLLY_HAVE_MALLOC_H 1
63 #include <folly/detail/Malloc.h>
64 #include <folly/Portability.h>
67 // for malloc_usable_size
68 // NOTE: FreeBSD 9 doesn't have malloc.h. It's defitions
69 // are found in stdlib.h.
70 #if FOLLY_HAVE_MALLOC_H
84 * Define various ALLOCM_* macros normally provided by jemalloc. We define
85 * them so that we don't have to include jemalloc.h, in case the program is
86 * built without jemalloc support.
88 #ifndef ALLOCM_SUCCESS
90 #define ALLOCM_SUCCESS 0
91 #define ALLOCM_ERR_OOM 1
92 #define ALLOCM_ERR_NOT_MOVED 2
94 #define ALLOCM_ZERO 64
95 #define ALLOCM_NO_MOVE 128
97 #define ALLOCM_LG_ALIGN(la) (la)
99 #if defined(JEMALLOC_MANGLE) && defined(JEMALLOC_EXPERIMENTAL)
100 #define rallocm je_rallocm
101 #define allocm je_allocm
104 #endif /* ALLOCM_SUCCESS */
106 #ifdef _LIBSTDCXX_FBSTRING
107 namespace std _GLIBCXX_VISIBILITY(default) {
108 _GLIBCXX_BEGIN_NAMESPACE_VERSION
113 bool usingJEMallocSlow();
116 * Determine if we are using jemalloc or not.
118 inline bool usingJEMalloc() {
119 // Checking for rallocm != NULL is not sufficient; we may be in a dlopen()ed
120 // module that depends on libjemalloc, so rallocm is resolved, but the main
121 // program might be using a different memory allocator. Look at the
122 // implementation of usingJEMallocSlow() for the (hacky) details.
123 static bool result = usingJEMallocSlow();
128 * For jemalloc's size classes, see
129 * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
131 inline size_t goodMallocSize(size_t minSize) {
132 if (!usingJEMalloc()) {
133 // Not using jemalloc - no smarts
137 // Choose smallest allocation to be 64 bytes - no tripping over
138 // cache line boundaries, and small string optimization takes care
139 // of short strings anyway.
142 if (minSize <= 512) {
143 // Round up to the next multiple of 64; we don't want to trip over
144 // cache line boundaries.
145 return (minSize + 63) & ~size_t(63);
147 if (minSize <= 3840) {
148 // Round up to the next multiple of 256
149 return (minSize + 255) & ~size_t(255);
151 if (minSize <= 4072 * 1024) {
152 // Round up to the next multiple of 4KB
153 return (minSize + 4095) & ~size_t(4095);
156 // Round up to the next multiple of 4MB
157 return (minSize + 4194303) & ~size_t(4194303);
160 // We always request "good" sizes for allocation, so jemalloc can
161 // never grow in place small blocks; they're already occupied to the
162 // brim. Blocks larger than or equal to 4096 bytes can in fact be
163 // expanded in place, and this constant reflects that.
164 static const size_t jemallocMinInPlaceExpandable = 4096;
167 * Trivial wrappers around malloc, calloc, realloc that check for allocation
168 * failure and throw std::bad_alloc in that case.
170 inline void* checkedMalloc(size_t size) {
171 void* p = malloc(size);
172 if (!p) std::__throw_bad_alloc();
176 inline void* checkedCalloc(size_t n, size_t size) {
177 void* p = calloc(n, size);
178 if (!p) std::__throw_bad_alloc();
182 inline void* checkedRealloc(void* ptr, size_t size) {
183 void* p = realloc(ptr, size);
184 if (!p) std::__throw_bad_alloc();
189 * This function tries to reallocate a buffer of which only the first
190 * currentSize bytes are used. The problem with using realloc is that
191 * if currentSize is relatively small _and_ if realloc decides it
192 * needs to move the memory chunk to a new buffer, then realloc ends
193 * up copying data that is not used. It's impossible to hook into
194 * GNU's malloc to figure whether expansion will occur in-place or as
195 * a malloc-copy-free troika. (If an expand_in_place primitive would
196 * be available, smartRealloc would use it.) As things stand, this
197 * routine just tries to call realloc() (thus benefitting of potential
198 * copy-free coalescing) unless there's too much slack memory.
200 inline void* smartRealloc(void* p,
201 const size_t currentSize,
202 const size_t currentCapacity,
203 const size_t newCapacity) {
205 assert(currentSize <= currentCapacity &&
206 currentCapacity < newCapacity);
208 if (usingJEMalloc()) {
209 // using jemalloc's API. Don't forget that jemalloc can never grow
210 // in place blocks smaller than 4096 bytes.
211 if (currentCapacity >= jemallocMinInPlaceExpandable &&
212 rallocm(&p, nullptr, newCapacity, 0, ALLOCM_NO_MOVE) == ALLOCM_SUCCESS) {
213 // Managed to expand in place
216 // Cannot expand; must move
217 auto const result = checkedMalloc(newCapacity);
218 std::memcpy(result, p, currentSize);
223 // No jemalloc no honey
224 auto const slack = currentCapacity - currentSize;
225 if (slack * 2 > currentSize) {
226 // Too much slack, malloc-copy-free cycle:
227 auto const result = checkedMalloc(newCapacity);
228 std::memcpy(result, p, currentSize);
232 // If there's not too much slack, we realloc in hope of coalescing
233 return checkedRealloc(p, newCapacity);
236 #ifdef _LIBSTDCXX_FBSTRING
237 _GLIBCXX_END_NAMESPACE_VERSION
242 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
244 #endif // FOLLY_MALLOC_H_