b8b2e2048bd3b7018c7d323b004954b6e3e533ce
[folly.git] / folly / Malloc.h
1 /*
2  * Copyright 2014 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 // If using fbstring from libstdc++, then just define stub code
24 // here to typedef the fbstring type into the folly namespace.
25 // This provides backwards compatibility for code that explicitly
26 // includes and uses fbstring.
27 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
28
29 #include "folly/detail/Malloc.h"
30
31 #include <string>
32 namespace folly {
33   using std::goodMallocSize;
34   using std::jemallocMinInPlaceExpandable;
35   using std::usingJEMalloc;
36   using std::smartRealloc;
37   using std::checkedMalloc;
38   using std::checkedCalloc;
39   using std::checkedRealloc;
40 }
41
42 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
43
44 #ifdef _LIBSTDCXX_FBSTRING
45 #pragma GCC system_header
46
47 /**
48  * Declare rallocm(), allocm(), and mallctl() as weak symbols. These will be
49  * provided by jemalloc if we are using jemalloc, or will be NULL if we are
50  * using another malloc implementation.
51  */
52 extern "C" int rallocm(void**, size_t*, size_t, size_t, int)
53 __attribute__((weak));
54 extern "C" int allocm(void**, size_t*, size_t, int)
55 __attribute__((weak));
56 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
57 __attribute__((weak));
58
59 #include <bits/functexcept.h>
60 #define FOLLY_HAVE_MALLOC_H 1
61 #else
62 #include "folly/detail/Malloc.h"
63 #include "folly/Portability.h"
64 #endif
65
66 // for malloc_usable_size
67 // NOTE: FreeBSD 9 doesn't have malloc.h.  It's defitions
68 // are found in stdlib.h.
69 #if FOLLY_HAVE_MALLOC_H
70 #include <malloc.h>
71 #else
72 #include <stdlib.h>
73 #endif
74
75 #include <cassert>
76 #include <cstddef>
77 #include <cstdlib>
78 #include <cstring>
79
80 #include <new>
81
82 /**
83  * Define various ALLOCM_* macros normally provided by jemalloc.  We define
84  * them so that we don't have to include jemalloc.h, in case the program is
85  * built without jemalloc support.
86  */
87 #ifndef ALLOCM_SUCCESS
88
89 #define ALLOCM_SUCCESS 0
90 #define ALLOCM_ERR_OOM 1
91 #define ALLOCM_ERR_NOT_MOVED 2
92
93 #define ALLOCM_ZERO    64
94 #define ALLOCM_NO_MOVE 128
95
96 #define ALLOCM_LG_ALIGN(la) (la)
97
98 #if defined(JEMALLOC_MANGLE) && defined(JEMALLOC_EXPERIMENTAL)
99 #define rallocm je_rallocm
100 #define allocm je_allocm
101 #endif
102
103 #endif /* ALLOCM_SUCCESS */
104
105 #ifdef _LIBSTDCXX_FBSTRING
106 namespace std _GLIBCXX_VISIBILITY(default) {
107 _GLIBCXX_BEGIN_NAMESPACE_VERSION
108 #else
109 namespace folly {
110 #endif
111
112 bool usingJEMallocSlow();
113
114 /**
115  * Determine if we are using jemalloc or not.
116  */
117 inline bool usingJEMalloc() {
118   // Checking for rallocm != NULL is not sufficient; we may be in a dlopen()ed
119   // module that depends on libjemalloc, so rallocm is resolved, but the main
120   // program might be using a different memory allocator. Look at the
121   // implementation of usingJEMallocSlow() for the (hacky) details.
122   static bool result = usingJEMallocSlow();
123   return result;
124 }
125
126 /**
127  * For jemalloc's size classes, see
128  * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
129  */
130 inline size_t goodMallocSize(size_t minSize) {
131   if (!usingJEMalloc()) {
132     // Not using jemalloc - no smarts
133     return minSize;
134   }
135   if (minSize <= 64) {
136     // Choose smallest allocation to be 64 bytes - no tripping over
137     // cache line boundaries, and small string optimization takes care
138     // of short strings anyway.
139     return 64;
140   }
141   if (minSize <= 512) {
142     // Round up to the next multiple of 64; we don't want to trip over
143     // cache line boundaries.
144     return (minSize + 63) & ~size_t(63);
145   }
146   if (minSize <= 3840) {
147     // Round up to the next multiple of 256
148     return (minSize + 255) & ~size_t(255);
149   }
150   if (minSize <= 4072 * 1024) {
151     // Round up to the next multiple of 4KB
152     return (minSize + 4095) & ~size_t(4095);
153   }
154   // Holy Moly
155   // Round up to the next multiple of 4MB
156   return (minSize + 4194303) & ~size_t(4194303);
157 }
158
159 // We always request "good" sizes for allocation, so jemalloc can
160 // never grow in place small blocks; they're already occupied to the
161 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
162 // expanded in place, and this constant reflects that.
163 static const size_t jemallocMinInPlaceExpandable = 4096;
164
165 /**
166  * Trivial wrappers around malloc, calloc, realloc that check for allocation
167  * failure and throw std::bad_alloc in that case.
168  */
169 inline void* checkedMalloc(size_t size) {
170   void* p = malloc(size);
171   if (!p) std::__throw_bad_alloc();
172   return p;
173 }
174
175 inline void* checkedCalloc(size_t n, size_t size) {
176   void* p = calloc(n, size);
177   if (!p) std::__throw_bad_alloc();
178   return p;
179 }
180
181 inline void* checkedRealloc(void* ptr, size_t size) {
182   void* p = realloc(ptr, size);
183   if (!p) std::__throw_bad_alloc();
184   return p;
185 }
186
187 /**
188  * This function tries to reallocate a buffer of which only the first
189  * currentSize bytes are used. The problem with using realloc is that
190  * if currentSize is relatively small _and_ if realloc decides it
191  * needs to move the memory chunk to a new buffer, then realloc ends
192  * up copying data that is not used. It's impossible to hook into
193  * GNU's malloc to figure whether expansion will occur in-place or as
194  * a malloc-copy-free troika. (If an expand_in_place primitive would
195  * be available, smartRealloc would use it.) As things stand, this
196  * routine just tries to call realloc() (thus benefitting of potential
197  * copy-free coalescing) unless there's too much slack memory.
198  */
199 inline void* smartRealloc(void* p,
200                           const size_t currentSize,
201                           const size_t currentCapacity,
202                           const size_t newCapacity) {
203   assert(p);
204   assert(currentSize <= currentCapacity &&
205          currentCapacity < newCapacity);
206
207   if (usingJEMalloc()) {
208     // using jemalloc's API. Don't forget that jemalloc can never grow
209     // in place blocks smaller than 4096 bytes.
210     if (currentCapacity >= jemallocMinInPlaceExpandable &&
211         rallocm(&p, nullptr, newCapacity, 0, ALLOCM_NO_MOVE) == ALLOCM_SUCCESS) {
212       // Managed to expand in place
213       return p;
214     }
215     // Cannot expand; must move
216     auto const result = checkedMalloc(newCapacity);
217     std::memcpy(result, p, currentSize);
218     free(p);
219     return result;
220   }
221
222   // No jemalloc no honey
223   auto const slack = currentCapacity - currentSize;
224   if (slack * 2 > currentSize) {
225     // Too much slack, malloc-copy-free cycle:
226     auto const result = checkedMalloc(newCapacity);
227     std::memcpy(result, p, currentSize);
228     free(p);
229     return result;
230   }
231   // If there's not too much slack, we realloc in hope of coalescing
232   return checkedRealloc(p, newCapacity);
233 }
234
235 #ifdef _LIBSTDCXX_FBSTRING
236 _GLIBCXX_END_NAMESPACE_VERSION
237 #endif
238
239 } // folly
240
241 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
242
243 #endif // FOLLY_MALLOC_H_