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