Fix usingJEMalloc with Clang
[folly.git] / folly / Malloc.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
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
19
20 #ifndef FOLLY_MALLOC_H_
21 #define FOLLY_MALLOC_H_
22
23 /**
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.
27  */
28 #ifndef MALLOCX_LG_ALIGN
29 #define MALLOCX_LG_ALIGN(la) (la)
30 #endif
31 #ifndef MALLOCX_ZERO
32 #define MALLOCX_ZERO (static_cast<int>(0x40))
33 #endif
34
35 // If using fbstring from libstdc++ (see comment in FBString.h), then
36 // just define stub code here to typedef the fbstring type into the
37 // folly namespace.
38 // This provides backwards compatibility for code that explicitly
39 // includes and uses fbstring.
40 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
41
42 #include <folly/detail/Malloc.h>
43
44 #include <string>
45
46 namespace folly {
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;
54 }
55
56 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
57
58 #ifdef _LIBSTDCXX_FBSTRING
59 #pragma GCC system_header
60
61 /**
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.
65  */
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" size_t nallocx(size_t, int)
77 __attribute__((__weak__));
78 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
79 __attribute__((__weak__));
80 extern "C" int mallctlnametomib(const char*, size_t*, size_t*)
81 __attribute__((__weak__));
82 extern "C" int mallctlbymib(const size_t*, size_t, void*, size_t*, void*,
83                             size_t)
84 __attribute__((__weak__));
85
86 #include <bits/functexcept.h>
87 #define FOLLY_HAVE_MALLOC_H 1
88 #else
89 #include <folly/detail/Malloc.h> /* nolint */
90 #endif
91
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
96 #include <malloc.h>
97 #else
98 #include <stdlib.h>
99 #endif
100
101 #include <cassert>
102 #include <cstddef>
103 #include <cstdint>
104 #include <cstdlib>
105 #include <cstring>
106
107 #include <new>
108
109 #ifdef _LIBSTDCXX_FBSTRING
110 namespace std _GLIBCXX_VISIBILITY(default) {
111 _GLIBCXX_BEGIN_NAMESPACE_VERSION
112 #else
113 namespace folly {
114 #endif
115
116 // Cannot depend on Portability.h when _LIBSTDCXX_FBSTRING.
117 #ifdef __GNUC__
118 #define FOLLY_MALLOC_NOINLINE __attribute__((__noinline__))
119 #else
120 #define FOLLY_MALLOC_NOINLINE
121 #endif
122
123 /**
124  * Determine if we are using jemalloc or not.
125  */
126 inline bool usingJEMalloc() noexcept {
127   // Checking for rallocx != NULL is not sufficient; we may be in a dlopen()ed
128   // module that depends on libjemalloc, so rallocx is resolved, but the main
129   // program might be using a different memory allocator.
130   // How do we determine that we're using jemalloc? In the hackiest
131   // way possible. We allocate memory using malloc() and see if the
132   // per-thread counter of allocated memory increases. This makes me
133   // feel dirty inside. Also note that this requires jemalloc to have
134   // been compiled with --enable-stats.
135   static const bool result = [] () FOLLY_MALLOC_NOINLINE noexcept {
136     // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
137     // in the form if (mallctl != nullptr). Not if (mallctl) or if (!mallctl)
138     // (!!). http://goo.gl/xpmctm
139     if (mallocx == nullptr || rallocx == nullptr || xallocx == nullptr
140         || sallocx == nullptr || dallocx == nullptr || nallocx == nullptr
141         || mallctl == nullptr || mallctlnametomib == nullptr
142         || mallctlbymib == nullptr) {
143       return false;
144     }
145
146     // "volatile" because gcc optimizes out the reads from *counter, because
147     // it "knows" malloc doesn't modify global state...
148     /* nolint */ volatile uint64_t* counter;
149     size_t counterLen = sizeof(uint64_t*);
150
151     if (mallctl("thread.allocatedp", static_cast<void*>(&counter), &counterLen,
152                 nullptr, 0) != 0) {
153       return false;
154     }
155
156     if (counterLen != sizeof(uint64_t*)) {
157       return false;
158     }
159
160     uint64_t origAllocated = *counter;
161
162     // Static because otherwise clever compilers will find out that
163     // the ptr is not used and does not escape the scope, so they will
164     // just optimize away the malloc.
165     static void* ptr = malloc(1);
166     if (!ptr) {
167       // wtf, failing to allocate 1 byte
168       return false;
169     }
170
171     return (origAllocated != *counter);
172   }();
173
174   return result;
175 }
176
177 /**
178  * For jemalloc's size classes, see
179  * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
180  */
181 inline size_t goodMallocSize(size_t minSize) noexcept {
182   if (!usingJEMalloc()) {
183     // Not using jemalloc - no smarts
184     return minSize;
185   }
186   size_t goodSize;
187   if (minSize <= 64) {
188     // Choose smallest allocation to be 64 bytes - no tripping over
189     // cache line boundaries, and small string optimization takes care
190     // of short strings anyway.
191     goodSize = 64;
192   } else if (minSize <= 512) {
193     // Round up to the next multiple of 64; we don't want to trip over
194     // cache line boundaries.
195     goodSize = (minSize + 63) & ~size_t(63);
196   } else {
197     // Boundaries between size classes depend on numerious factors, some of
198     // which can even be modified at run-time. Determine the good allocation
199     // size by calling nallocx() directly.
200     goodSize = nallocx(minSize, 0);
201   }
202   assert(nallocx(goodSize, 0) == goodSize);
203   return goodSize;
204 }
205
206 // We always request "good" sizes for allocation, so jemalloc can
207 // never grow in place small blocks; they're already occupied to the
208 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
209 // expanded in place, and this constant reflects that.
210 static const size_t jemallocMinInPlaceExpandable = 4096;
211
212 /**
213  * Trivial wrappers around malloc, calloc, realloc that check for allocation
214  * failure and throw std::bad_alloc in that case.
215  */
216 inline void* checkedMalloc(size_t size) {
217   void* p = malloc(size);
218   if (!p) std::__throw_bad_alloc();
219   return p;
220 }
221
222 inline void* checkedCalloc(size_t n, size_t size) {
223   void* p = calloc(n, size);
224   if (!p) std::__throw_bad_alloc();
225   return p;
226 }
227
228 inline void* checkedRealloc(void* ptr, size_t size) {
229   void* p = realloc(ptr, size);
230   if (!p) std::__throw_bad_alloc();
231   return p;
232 }
233
234 /**
235  * This function tries to reallocate a buffer of which only the first
236  * currentSize bytes are used. The problem with using realloc is that
237  * if currentSize is relatively small _and_ if realloc decides it
238  * needs to move the memory chunk to a new buffer, then realloc ends
239  * up copying data that is not used. It's impossible to hook into
240  * GNU's malloc to figure whether expansion will occur in-place or as
241  * a malloc-copy-free troika. (If an expand_in_place primitive would
242  * be available, smartRealloc would use it.) As things stand, this
243  * routine just tries to call realloc() (thus benefitting of potential
244  * copy-free coalescing) unless there's too much slack memory.
245  */
246 inline void* smartRealloc(void* p,
247                           const size_t currentSize,
248                           const size_t currentCapacity,
249                           const size_t newCapacity) {
250   assert(p);
251   assert(currentSize <= currentCapacity &&
252          currentCapacity < newCapacity);
253
254   if (usingJEMalloc()) {
255     // using jemalloc's API. Don't forget that jemalloc can never grow
256     // in place blocks smaller than 4096 bytes.
257     //
258     // NB: newCapacity may not be precisely equal to a jemalloc size class,
259     // i.e. newCapacity is not guaranteed to be the result of a
260     // goodMallocSize() call, therefore xallocx() may return more than
261     // newCapacity bytes of space.  Use >= rather than == to check whether
262     // xallocx() successfully expanded in place.
263     if (currentCapacity >= jemallocMinInPlaceExpandable &&
264         xallocx(p, newCapacity, 0, 0) >= newCapacity) {
265       // Managed to expand in place
266       return p;
267     }
268     // Cannot expand; must move
269     auto const result = checkedMalloc(newCapacity);
270     std::memcpy(result, p, currentSize);
271     free(p);
272     return result;
273   }
274
275   // No jemalloc no honey
276   auto const slack = currentCapacity - currentSize;
277   if (slack * 2 > currentSize) {
278     // Too much slack, malloc-copy-free cycle:
279     auto const result = checkedMalloc(newCapacity);
280     std::memcpy(result, p, currentSize);
281     free(p);
282     return result;
283   }
284   // If there's not too much slack, we realloc in hope of coalescing
285   return checkedRealloc(p, newCapacity);
286 }
287
288 #ifdef _LIBSTDCXX_FBSTRING
289 _GLIBCXX_END_NAMESPACE_VERSION
290 #endif
291
292 } // folly
293
294 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
295
296 #endif // FOLLY_MALLOC_H_