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