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