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