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