2 * Copyright 2016 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
23 * Define various MALLOCX_* macros normally provided by jemalloc. We define
24 * them so that we don't have to include jemalloc.h, in case the program is
25 * built without jemalloc support.
27 #ifndef MALLOCX_LG_ALIGN
28 #define MALLOCX_LG_ALIGN(la) (la)
31 #define MALLOCX_ZERO (static_cast<int>(0x40))
34 // If using fbstring from libstdc++ (see comment in FBString.h), then
35 // just define stub code here to typedef the fbstring type into the
37 // This provides backwards compatibility for code that explicitly
38 // includes and uses fbstring.
39 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
41 #include <folly/detail/Malloc.h>
42 #include <folly/portability/BitsFunctexcept.h>
47 using std::goodMallocSize;
48 using std::jemallocMinInPlaceExpandable;
49 using std::usingJEMalloc;
50 using std::smartRealloc;
51 using std::checkedMalloc;
52 using std::checkedCalloc;
53 using std::checkedRealloc;
56 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
58 #ifdef _LIBSTDCXX_FBSTRING
59 #pragma GCC system_header
62 * Declare *allocx() and mallctl*() as weak symbols. These will be provided by
63 * jemalloc if we are using jemalloc, or will be NULL if we are using another
64 * malloc implementation.
66 extern "C" void* mallocx(size_t, int)
67 __attribute__((__weak__));
68 extern "C" void* rallocx(void*, size_t, int)
69 __attribute__((__weak__));
70 extern "C" size_t xallocx(void*, size_t, size_t, int)
71 __attribute__((__weak__));
72 extern "C" size_t sallocx(const void*, int)
73 __attribute__((__weak__));
74 extern "C" void dallocx(void*, int)
75 __attribute__((__weak__));
76 extern "C" void sdallocx(void*, size_t, int)
77 __attribute__((__weak__));
78 extern "C" size_t nallocx(size_t, int)
79 __attribute__((__weak__));
80 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
81 __attribute__((__weak__));
82 extern "C" int mallctlnametomib(const char*, size_t*, size_t*)
83 __attribute__((__weak__));
84 extern "C" int mallctlbymib(const size_t*, size_t, void*, size_t*, void*,
86 __attribute__((__weak__));
88 #include <bits/functexcept.h>
90 #define FOLLY_HAVE_MALLOC_H 1
92 #else // !defined(_LIBSTDCXX_FBSTRING)
94 #include <folly/detail/Malloc.h> /* nolint */
95 #include <folly/portability/BitsFunctexcept.h> /* nolint */
99 // for malloc_usable_size
100 // NOTE: FreeBSD 9 doesn't have malloc.h. Its definitions
101 // are found in stdlib.h.
102 #if FOLLY_HAVE_MALLOC_H
117 #ifdef _LIBSTDCXX_FBSTRING
118 namespace std _GLIBCXX_VISIBILITY(default) {
119 _GLIBCXX_BEGIN_NAMESPACE_VERSION
124 // Cannot depend on Portability.h when _LIBSTDCXX_FBSTRING.
125 #if defined(__GNUC__)
126 #define FOLLY_MALLOC_NOINLINE __attribute__((__noinline__))
127 // This is for checked malloc-like functions (returns non-null pointer
128 // which cannot alias any outstanding pointer).
129 #define FOLLY_MALLOC_CHECKED_MALLOC \
130 __attribute__((__returns_nonnull__, __malloc__))
132 #define FOLLY_MALLOC_NOINLINE
133 #define FOLLY_MALLOC_CHECKED_MALLOC
137 * Determine if we are using jemalloc or not.
139 FOLLY_MALLOC_NOINLINE inline bool usingJEMalloc() noexcept {
140 // Checking for rallocx != NULL is not sufficient; we may be in a dlopen()ed
141 // module that depends on libjemalloc, so rallocx is resolved, but the main
142 // program might be using a different memory allocator.
143 // How do we determine that we're using jemalloc? In the hackiest
144 // way possible. We allocate memory using malloc() and see if the
145 // per-thread counter of allocated memory increases. This makes me
146 // feel dirty inside. Also note that this requires jemalloc to have
147 // been compiled with --enable-stats.
148 static const bool result = [] () noexcept {
149 // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
150 // in the form if (mallctl != nullptr). Not if (mallctl) or if (!mallctl)
151 // (!!). http://goo.gl/xpmctm
152 if (mallocx == nullptr || rallocx == nullptr || xallocx == nullptr
153 || sallocx == nullptr || dallocx == nullptr || sdallocx == nullptr
154 || nallocx == nullptr || mallctl == nullptr
155 || mallctlnametomib == nullptr || mallctlbymib == nullptr) {
159 // "volatile" because gcc optimizes out the reads from *counter, because
160 // it "knows" malloc doesn't modify global state...
161 /* nolint */ volatile uint64_t* counter;
162 size_t counterLen = sizeof(uint64_t*);
164 if (mallctl("thread.allocatedp", static_cast<void*>(&counter), &counterLen,
169 if (counterLen != sizeof(uint64_t*)) {
173 uint64_t origAllocated = *counter;
175 // Static because otherwise clever compilers will find out that
176 // the ptr is not used and does not escape the scope, so they will
177 // just optimize away the malloc.
178 static void* ptr = malloc(1);
180 // wtf, failing to allocate 1 byte
184 return (origAllocated != *counter);
190 inline size_t goodMallocSize(size_t minSize) noexcept {
195 if (!usingJEMalloc()) {
196 // Not using jemalloc - no smarts
200 return nallocx(minSize, 0);
203 // We always request "good" sizes for allocation, so jemalloc can
204 // never grow in place small blocks; they're already occupied to the
205 // brim. Blocks larger than or equal to 4096 bytes can in fact be
206 // expanded in place, and this constant reflects that.
207 static const size_t jemallocMinInPlaceExpandable = 4096;
210 * Trivial wrappers around malloc, calloc, realloc that check for allocation
211 * failure and throw std::bad_alloc in that case.
213 inline void* checkedMalloc(size_t size) {
214 void* p = malloc(size);
215 if (!p) std::__throw_bad_alloc();
219 inline void* checkedCalloc(size_t n, size_t size) {
220 void* p = calloc(n, size);
221 if (!p) std::__throw_bad_alloc();
225 inline void* checkedRealloc(void* ptr, size_t size) {
226 void* p = realloc(ptr, size);
227 if (!p) std::__throw_bad_alloc();
232 * This function tries to reallocate a buffer of which only the first
233 * currentSize bytes are used. The problem with using realloc is that
234 * if currentSize is relatively small _and_ if realloc decides it
235 * needs to move the memory chunk to a new buffer, then realloc ends
236 * up copying data that is not used. It's impossible to hook into
237 * GNU's malloc to figure whether expansion will occur in-place or as
238 * a malloc-copy-free troika. (If an expand_in_place primitive would
239 * be available, smartRealloc would use it.) As things stand, this
240 * routine just tries to call realloc() (thus benefitting of potential
241 * copy-free coalescing) unless there's too much slack memory.
243 FOLLY_MALLOC_CHECKED_MALLOC FOLLY_MALLOC_NOINLINE inline void* smartRealloc(
245 const size_t currentSize,
246 const size_t currentCapacity,
247 const size_t newCapacity) {
249 assert(currentSize <= currentCapacity &&
250 currentCapacity < newCapacity);
252 if (usingJEMalloc()) {
253 // using jemalloc's API. Don't forget that jemalloc can never grow
254 // in place blocks smaller than 4096 bytes.
256 // NB: newCapacity may not be precisely equal to a jemalloc size class,
257 // i.e. newCapacity is not guaranteed to be the result of a
258 // goodMallocSize() call, therefore xallocx() may return more than
259 // newCapacity bytes of space. Use >= rather than == to check whether
260 // xallocx() successfully expanded in place.
261 if (currentCapacity >= jemallocMinInPlaceExpandable &&
262 xallocx(p, newCapacity, 0, 0) >= newCapacity) {
263 // Managed to expand in place
266 // Cannot expand; must move
267 auto const result = checkedMalloc(newCapacity);
268 std::memcpy(result, p, currentSize);
273 // No jemalloc no honey
274 auto const slack = currentCapacity - currentSize;
275 if (slack * 2 > currentSize) {
276 // Too much slack, malloc-copy-free cycle:
277 auto const result = checkedMalloc(newCapacity);
278 std::memcpy(result, p, currentSize);
282 // If there's not too much slack, we realloc in hope of coalescing
283 return checkedRealloc(p, newCapacity);
286 #ifdef _LIBSTDCXX_FBSTRING
287 _GLIBCXX_END_NAMESPACE_VERSION
292 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)