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