2 * Copyright 2015 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_
24 * Define various MALLOCX_* macros normally provided by jemalloc. We define
25 * them so that we don't have to include jemalloc.h, in case the program is
26 * built without jemalloc support.
28 #ifndef MALLOCX_LG_ALIGN
29 #define MALLOCX_LG_ALIGN(la) (la)
32 #define MALLOCX_ZERO (static_cast<int>(0x40))
35 // If using fbstring from libstdc++, then just define stub code
36 // here to typedef the fbstring type into the folly namespace.
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>
46 using std::goodMallocSize;
47 using std::jemallocMinInPlaceExpandable;
48 using std::usingJEMalloc;
49 using std::smartRealloc;
50 using std::checkedMalloc;
51 using std::checkedCalloc;
52 using std::checkedRealloc;
55 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
57 #ifdef _LIBSTDCXX_FBSTRING
58 #pragma GCC system_header
61 * Declare *allocx() and mallctl*() as weak symbols. These will be provided by
62 * jemalloc if we are using jemalloc, or will be NULL if we are using another
63 * malloc implementation.
65 extern "C" void* mallocx(size_t, int)
66 __attribute__((__weak__));
67 extern "C" void* rallocx(void*, size_t, int)
68 __attribute__((__weak__));
69 extern "C" size_t xallocx(void*, size_t, size_t, int)
70 __attribute__((__weak__));
71 extern "C" size_t sallocx(const void*, int)
72 __attribute__((__weak__));
73 extern "C" void dallocx(void*, int)
74 __attribute__((__weak__));
75 extern "C" size_t nallocx(size_t, int)
76 __attribute__((__weak__));
77 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
78 __attribute__((__weak__));
79 extern "C" int mallctlnametomib(const char*, size_t*, size_t*)
80 __attribute__((__weak__));
81 extern "C" int mallctlbymib(const size_t*, size_t, void*, size_t*, void*,
83 __attribute__((__weak__));
85 #include <bits/functexcept.h>
86 #define FOLLY_HAVE_MALLOC_H 1
88 #include <folly/detail/Malloc.h> /* nolint */
89 #include <folly/Portability.h>
92 // for malloc_usable_size
93 // NOTE: FreeBSD 9 doesn't have malloc.h. It's defitions
94 // are found in stdlib.h.
95 #if FOLLY_HAVE_MALLOC_H
108 #ifdef _LIBSTDCXX_FBSTRING
109 namespace std _GLIBCXX_VISIBILITY(default) {
110 _GLIBCXX_BEGIN_NAMESPACE_VERSION
115 bool usingJEMallocSlow();
118 * Determine if we are using jemalloc or not.
120 inline bool usingJEMalloc() {
121 // Checking for rallocx != NULL is not sufficient; we may be in a dlopen()ed
122 // module that depends on libjemalloc, so rallocx is resolved, but the main
123 // program might be using a different memory allocator. Look at the
124 // implementation of usingJEMallocSlow() for the (hacky) details.
125 static const bool result = usingJEMallocSlow();
130 * For jemalloc's size classes, see
131 * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
133 inline size_t goodMallocSize(size_t minSize) noexcept {
134 if (!usingJEMalloc()) {
135 // Not using jemalloc - no smarts
140 // Choose smallest allocation to be 64 bytes - no tripping over
141 // cache line boundaries, and small string optimization takes care
142 // of short strings anyway.
144 } else if (minSize <= 512) {
145 // Round up to the next multiple of 64; we don't want to trip over
146 // cache line boundaries.
147 goodSize = (minSize + 63) & ~size_t(63);
149 // Boundaries between size classes depend on numerious factors, some of
150 // which can even be modified at run-time. Determine the good allocation
151 // size by calling nallocx() directly.
152 goodSize = nallocx(minSize, 0);
154 assert(nallocx(goodSize, 0) == goodSize);
158 // We always request "good" sizes for allocation, so jemalloc can
159 // never grow in place small blocks; they're already occupied to the
160 // brim. Blocks larger than or equal to 4096 bytes can in fact be
161 // expanded in place, and this constant reflects that.
162 static const size_t jemallocMinInPlaceExpandable = 4096;
165 * Trivial wrappers around malloc, calloc, realloc that check for allocation
166 * failure and throw std::bad_alloc in that case.
168 inline void* checkedMalloc(size_t size) {
169 void* p = malloc(size);
170 if (!p) std::__throw_bad_alloc();
174 inline void* checkedCalloc(size_t n, size_t size) {
175 void* p = calloc(n, size);
176 if (!p) std::__throw_bad_alloc();
180 inline void* checkedRealloc(void* ptr, size_t size) {
181 void* p = realloc(ptr, size);
182 if (!p) std::__throw_bad_alloc();
187 * This function tries to reallocate a buffer of which only the first
188 * currentSize bytes are used. The problem with using realloc is that
189 * if currentSize is relatively small _and_ if realloc decides it
190 * needs to move the memory chunk to a new buffer, then realloc ends
191 * up copying data that is not used. It's impossible to hook into
192 * GNU's malloc to figure whether expansion will occur in-place or as
193 * a malloc-copy-free troika. (If an expand_in_place primitive would
194 * be available, smartRealloc would use it.) As things stand, this
195 * routine just tries to call realloc() (thus benefitting of potential
196 * copy-free coalescing) unless there's too much slack memory.
198 inline void* smartRealloc(void* p,
199 const size_t currentSize,
200 const size_t currentCapacity,
201 const size_t newCapacity) {
203 assert(currentSize <= currentCapacity &&
204 currentCapacity < newCapacity);
206 if (usingJEMalloc()) {
207 // using jemalloc's API. Don't forget that jemalloc can never grow
208 // in place blocks smaller than 4096 bytes.
210 // NB: newCapacity may not be precisely equal to a jemalloc size class,
211 // i.e. newCapacity is not guaranteed to be the result of a
212 // goodMallocSize() call, therefore xallocx() may return more than
213 // newCapacity bytes of space. Use >= rather than == to check whether
214 // xallocx() successfully expanded in place.
215 if (currentCapacity >= jemallocMinInPlaceExpandable &&
216 xallocx(p, newCapacity, 0, 0) >= newCapacity) {
217 // Managed to expand in place
220 // Cannot expand; must move
221 auto const result = checkedMalloc(newCapacity);
222 std::memcpy(result, p, currentSize);
227 // No jemalloc no honey
228 auto const slack = currentCapacity - currentSize;
229 if (slack * 2 > currentSize) {
230 // Too much slack, malloc-copy-free cycle:
231 auto const result = checkedMalloc(newCapacity);
232 std::memcpy(result, p, currentSize);
236 // If there's not too much slack, we realloc in hope of coalescing
237 return checkedRealloc(p, newCapacity);
240 #ifdef _LIBSTDCXX_FBSTRING
241 _GLIBCXX_END_NAMESPACE_VERSION
246 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
248 #endif // FOLLY_MALLOC_H_