fbcode: __x__-protect all __attribute__ keywords, mechanically
[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
33 namespace folly {
34   using std::goodMallocSize;
35   using std::jemallocMinInPlaceExpandable;
36   using std::usingJEMalloc;
37   using std::smartRealloc;
38   using std::checkedMalloc;
39   using std::checkedCalloc;
40   using std::checkedRealloc;
41 }
42
43 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
44
45 #ifdef _LIBSTDCXX_FBSTRING
46 #pragma GCC system_header
47
48 /**
49  * Declare rallocm(), allocm(), and mallctl() as weak symbols. These will be
50  * provided by jemalloc if we are using jemalloc, or will be NULL if we are
51  * using another malloc implementation.
52  */
53 extern "C" int rallocm(void**, size_t*, size_t, size_t, int)
54 __attribute__((__weak__));
55 extern "C" int allocm(void**, size_t*, size_t, int)
56 __attribute__((__weak__));
57 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
58 __attribute__((__weak__));
59
60 #include <bits/functexcept.h>
61 #define FOLLY_HAVE_MALLOC_H 1
62 #else
63 #include <folly/detail/Malloc.h>
64 #include <folly/Portability.h>
65 #endif
66
67 // for malloc_usable_size
68 // NOTE: FreeBSD 9 doesn't have malloc.h.  It's defitions
69 // are found in stdlib.h.
70 #if FOLLY_HAVE_MALLOC_H
71 #include <malloc.h>
72 #else
73 #include <stdlib.h>
74 #endif
75
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdlib>
79 #include <cstring>
80
81 #include <new>
82
83 /**
84  * Define various ALLOCM_* macros normally provided by jemalloc.  We define
85  * them so that we don't have to include jemalloc.h, in case the program is
86  * built without jemalloc support.
87  */
88 #ifndef ALLOCM_SUCCESS
89
90 #define ALLOCM_SUCCESS 0
91 #define ALLOCM_ERR_OOM 1
92 #define ALLOCM_ERR_NOT_MOVED 2
93
94 #define ALLOCM_ZERO    64
95 #define ALLOCM_NO_MOVE 128
96
97 #define ALLOCM_LG_ALIGN(la) (la)
98
99 #if defined(JEMALLOC_MANGLE) && defined(JEMALLOC_EXPERIMENTAL)
100 #define rallocm je_rallocm
101 #define allocm je_allocm
102 #endif
103
104 #endif /* ALLOCM_SUCCESS */
105
106 #ifdef _LIBSTDCXX_FBSTRING
107 namespace std _GLIBCXX_VISIBILITY(default) {
108 _GLIBCXX_BEGIN_NAMESPACE_VERSION
109 #else
110 namespace folly {
111 #endif
112
113 bool usingJEMallocSlow();
114
115 /**
116  * Determine if we are using jemalloc or not.
117  */
118 inline bool usingJEMalloc() {
119   // Checking for rallocm != NULL is not sufficient; we may be in a dlopen()ed
120   // module that depends on libjemalloc, so rallocm is resolved, but the main
121   // program might be using a different memory allocator. Look at the
122   // implementation of usingJEMallocSlow() for the (hacky) details.
123   static bool result = usingJEMallocSlow();
124   return result;
125 }
126
127 /**
128  * For jemalloc's size classes, see
129  * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
130  */
131 inline size_t goodMallocSize(size_t minSize) {
132   if (!usingJEMalloc()) {
133     // Not using jemalloc - no smarts
134     return minSize;
135   }
136   if (minSize <= 64) {
137     // Choose smallest allocation to be 64 bytes - no tripping over
138     // cache line boundaries, and small string optimization takes care
139     // of short strings anyway.
140     return 64;
141   }
142   if (minSize <= 512) {
143     // Round up to the next multiple of 64; we don't want to trip over
144     // cache line boundaries.
145     return (minSize + 63) & ~size_t(63);
146   }
147   if (minSize <= 3840) {
148     // Round up to the next multiple of 256
149     return (minSize + 255) & ~size_t(255);
150   }
151   if (minSize <= 4072 * 1024) {
152     // Round up to the next multiple of 4KB
153     return (minSize + 4095) & ~size_t(4095);
154   }
155   // Holy Moly
156   // Round up to the next multiple of 4MB
157   return (minSize + 4194303) & ~size_t(4194303);
158 }
159
160 // We always request "good" sizes for allocation, so jemalloc can
161 // never grow in place small blocks; they're already occupied to the
162 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
163 // expanded in place, and this constant reflects that.
164 static const size_t jemallocMinInPlaceExpandable = 4096;
165
166 /**
167  * Trivial wrappers around malloc, calloc, realloc that check for allocation
168  * failure and throw std::bad_alloc in that case.
169  */
170 inline void* checkedMalloc(size_t size) {
171   void* p = malloc(size);
172   if (!p) std::__throw_bad_alloc();
173   return p;
174 }
175
176 inline void* checkedCalloc(size_t n, size_t size) {
177   void* p = calloc(n, size);
178   if (!p) std::__throw_bad_alloc();
179   return p;
180 }
181
182 inline void* checkedRealloc(void* ptr, size_t size) {
183   void* p = realloc(ptr, size);
184   if (!p) std::__throw_bad_alloc();
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, nullptr, 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_