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