2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_INDEXEDMEMPOOL_H
18 #define FOLLY_INDEXEDMEMPOOL_H
20 #include <type_traits>
25 #include <boost/noncopyable.hpp>
26 #include <folly/AtomicStruct.h>
27 #include <folly/detail/CacheLocality.h>
29 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
30 #pragma GCC diagnostic push
31 #pragma GCC diagnostic ignored "-Wshadow"
36 template <typename Pool>
37 struct IndexedMemPoolRecycler;
40 /// Instances of IndexedMemPool dynamically allocate and then pool their
41 /// element type (T), returning 4-byte integer indices that can be passed
42 /// to the pool's operator[] method to access or obtain pointers to the
43 /// actual elements. The memory backing items returned from the pool
44 /// will always be readable, even if items have been returned to the pool.
45 /// These two features are useful for lock-free algorithms. The indexing
46 /// behavior makes it easy to build tagged pointer-like-things, since
47 /// a large number of elements can be managed using fewer bits than a
48 /// full pointer. The access-after-free behavior makes it safe to read
49 /// from T-s even after they have been recycled, since it is guaranteed
50 /// that the memory won't have been returned to the OS and unmapped
51 /// (the algorithm must still use a mechanism to validate that the read
52 /// was correct, but it doesn't have to worry about page faults), and if
53 /// the elements use internal sequence numbers it can be guaranteed that
54 /// there won't be an ABA match due to the element being overwritten with
55 /// a different type that has the same bit pattern.
57 /// IndexedMemPool has two object lifecycle strategies. The first
58 /// is to construct objects when they are allocated from the pool and
59 /// destroy them when they are recycled. In this mode allocIndex and
60 /// allocElem have emplace-like semantics. In the second mode, objects
61 /// are default-constructed the first time they are removed from the pool,
62 /// and deleted when the pool itself is deleted. By default the first
63 /// mode is used for non-trivial T, and the second is used for trivial T.
65 /// IMPORTANT: Space for extra elements is allocated to account for those
66 /// that are inaccessible because they are in other local lists, so the
67 /// actual number of items that can be allocated ranges from capacity to
68 /// capacity + (NumLocalLists_-1)*LocalListLimit_. This is important if
69 /// you are trying to maximize the capacity of the pool while constraining
70 /// the bit size of the resulting pointers, because the pointers will
71 /// actually range up to the boosted capacity. See maxIndexForCapacity
72 /// and capacityForMaxIndex.
74 /// To avoid contention, NumLocalLists_ free lists of limited (less than
75 /// or equal to LocalListLimit_) size are maintained, and each thread
76 /// retrieves and returns entries from its associated local list. If the
77 /// local list becomes too large then elements are placed in bulk in a
78 /// global free list. This allows items to be efficiently recirculated
79 /// from consumers to producers. AccessSpreader is used to access the
80 /// local lists, so there is no performance advantage to having more
81 /// local lists than L1 caches.
83 /// The pool mmap-s the entire necessary address space when the pool is
84 /// constructed, but delays element construction. This means that only
85 /// elements that are actually returned to the caller get paged into the
86 /// process's resident set (RSS).
88 int NumLocalLists_ = 32,
89 int LocalListLimit_ = 200,
90 template<typename> class Atom = std::atomic,
91 bool EagerRecycleWhenTrivial = false,
92 bool EagerRecycleWhenNotTrivial = true>
93 struct IndexedMemPool : boost::noncopyable {
96 typedef std::unique_ptr<T, detail::IndexedMemPoolRecycler<IndexedMemPool>>
99 static_assert(LocalListLimit_ <= 255, "LocalListLimit must fit in 8 bits");
101 NumLocalLists = NumLocalLists_,
102 LocalListLimit = LocalListLimit_
106 static constexpr bool eagerRecycle() {
107 return std::is_trivial<T>::value
108 ? EagerRecycleWhenTrivial : EagerRecycleWhenNotTrivial;
111 // these are public because clients may need to reason about the number
112 // of bits required to hold indices from a pool, given its capacity
114 static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) {
115 // index of uint32_t(-1) == UINT32_MAX is reserved for isAllocated tracking
116 return std::min(uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit,
117 uint64_t(uint32_t(-1) - 1));
120 static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) {
121 return maxIndex - (NumLocalLists - 1) * LocalListLimit;
125 /// Constructs a pool that can allocate at least _capacity_ elements,
126 /// even if all the local lists are full
127 explicit IndexedMemPool(uint32_t capacity)
128 : actualCapacity_(maxIndexForCapacity(capacity))
130 , globalHead_(TaggedPtr{})
132 const size_t needed = sizeof(Slot) * (actualCapacity_ + 1);
133 size_t pagesize = sysconf(_SC_PAGESIZE);
134 mmapLength_ = ((needed - 1) & ~(pagesize - 1)) + pagesize;
135 assert(needed <= mmapLength_ && mmapLength_ < needed + pagesize);
136 assert((mmapLength_ % pagesize) == 0);
138 slots_ = static_cast<Slot*>(mmap(nullptr, mmapLength_,
139 PROT_READ | PROT_WRITE,
140 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
141 if (slots_ == MAP_FAILED) {
142 assert(errno == ENOMEM);
143 throw std::bad_alloc();
147 /// Destroys all of the contained elements
149 if (!eagerRecycle()) {
150 for (size_t i = size_; i > 0; --i) {
154 munmap(slots_, mmapLength_);
157 /// Returns a lower bound on the number of elements that may be
158 /// simultaneously allocated and not yet recycled. Because of the
159 /// local lists it is possible that more elements than this are returned
162 return capacityForMaxIndex(actualCapacity_);
165 /// Finds a slot with a non-zero index, emplaces a T there if we're
166 /// using the eager recycle lifecycle mode, and returns the index,
167 /// or returns 0 if no elements are available.
168 template <typename ...Args>
169 uint32_t allocIndex(Args&&... args) {
170 static_assert(sizeof...(Args) == 0 || eagerRecycle(),
171 "emplace-style allocation requires eager recycle, "
172 "which is defaulted only for non-trivial types");
173 auto idx = localPop(localHead());
174 if (idx != 0 && eagerRecycle()) {
175 T* ptr = &slot(idx).elem;
176 new (ptr) T(std::forward<Args>(args)...);
181 /// If an element is available, returns a std::unique_ptr to it that will
182 /// recycle the element to the pool when it is reclaimed, otherwise returns
183 /// a null (falsy) std::unique_ptr
184 template <typename ...Args>
185 UniquePtr allocElem(Args&&... args) {
186 auto idx = allocIndex(std::forward<Args>(args)...);
187 T* ptr = idx == 0 ? nullptr : &slot(idx).elem;
188 return UniquePtr(ptr, typename UniquePtr::deleter_type(this));
191 /// Gives up ownership previously granted by alloc()
192 void recycleIndex(uint32_t idx) {
193 assert(isAllocated(idx));
194 if (eagerRecycle()) {
197 localPush(localHead(), idx);
200 /// Provides access to the pooled element referenced by idx
201 T& operator[](uint32_t idx) {
202 return slot(idx).elem;
205 /// Provides access to the pooled element referenced by idx
206 const T& operator[](uint32_t idx) const {
207 return slot(idx).elem;
210 /// If elem == &pool[idx], then pool.locateElem(elem) == idx. Also,
211 /// pool.locateElem(nullptr) == 0
212 uint32_t locateElem(const T* elem) const {
217 static_assert(std::is_standard_layout<Slot>::value, "offsetof needs POD");
219 auto slot = reinterpret_cast<const Slot*>(
220 reinterpret_cast<const char*>(elem) - offsetof(Slot, elem));
221 auto rv = slot - slots_;
223 // this assert also tests that rv is in range
224 assert(elem == &(*this)[rv]);
228 /// Returns true iff idx has been alloc()ed and not recycleIndex()ed
229 bool isAllocated(uint32_t idx) const {
230 return slot(idx).localNext == uint32_t(-1);
242 Slot() : localNext{}, globalNext{} {}
248 // size is bottom 8 bits, tag in top 24. g++'s code generation for
249 // bitfields seems to depend on the phase of the moon, plus we can
250 // do better because we can rely on other checks to avoid masking
255 SizeMask = (1U << SizeBits) - 1,
256 TagIncr = 1U << SizeBits,
259 uint32_t size() const {
260 return tagAndSize & SizeMask;
263 TaggedPtr withSize(uint32_t repl) const {
264 assert(repl <= LocalListLimit);
265 return TaggedPtr{ idx, (tagAndSize & ~SizeMask) | repl };
268 TaggedPtr withSizeIncr() const {
269 assert(size() < LocalListLimit);
270 return TaggedPtr{ idx, tagAndSize + 1 };
273 TaggedPtr withSizeDecr() const {
275 return TaggedPtr{ idx, tagAndSize - 1 };
278 TaggedPtr withIdx(uint32_t repl) const {
279 return TaggedPtr{ repl, tagAndSize + TagIncr };
282 TaggedPtr withEmpty() const {
283 return withIdx(0).withSize(0);
287 struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING LocalList {
288 AtomicStruct<TaggedPtr,Atom> head;
290 LocalList() : head(TaggedPtr{}) {}
295 /// the actual number of slots that we will allocate, to guarantee
296 /// that we will satisfy the capacity requested at construction time.
297 /// They will be numbered 1..actualCapacity_ (note the 1-based counting),
298 /// and occupy slots_[1..actualCapacity_].
299 size_t actualCapacity_;
301 /// the number of bytes allocated from mmap, which is a multiple of
302 /// the page size of the machine
305 /// this records the number of slots that have actually been constructed.
306 /// To allow use of atomic ++ instead of CAS, we let this overflow.
307 /// The actual number of constructed elements is min(actualCapacity_,
309 Atom<uint32_t> size_;
311 /// raw storage, only 1..min(size_,actualCapacity_) (inclusive) are
312 /// actually constructed. Note that slots_[0] is not constructed or used
313 FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Slot* slots_;
315 /// use AccessSpreader to find your list. We use stripes instead of
316 /// thread-local to avoid the need to grow or shrink on thread start
317 /// or join. These are heads of lists chained with localNext
318 LocalList local_[NumLocalLists];
320 /// this is the head of a list of node chained by globalNext, that are
321 /// themselves each the head of a list chained by localNext
322 FOLLY_ALIGN_TO_AVOID_FALSE_SHARING AtomicStruct<TaggedPtr,Atom> globalHead_;
324 ///////////// private methods
326 size_t slotIndex(uint32_t idx) const {
328 idx <= actualCapacity_ &&
329 idx <= size_.load(std::memory_order_acquire));
333 Slot& slot(uint32_t idx) {
334 return slots_[slotIndex(idx)];
337 const Slot& slot(uint32_t idx) const {
338 return slots_[slotIndex(idx)];
341 // localHead references a full list chained by localNext. s should
342 // reference slot(localHead), it is passed as a micro-optimization
343 void globalPush(Slot& s, uint32_t localHead) {
345 TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
346 s.globalNext = gh.idx;
347 if (globalHead_.compare_exchange_strong(gh, gh.withIdx(localHead))) {
354 // idx references a single node
355 void localPush(AtomicStruct<TaggedPtr,Atom>& head, uint32_t idx) {
357 TaggedPtr h = head.load(std::memory_order_acquire);
361 if (h.size() == LocalListLimit) {
362 // push will overflow local list, steal it instead
363 if (head.compare_exchange_strong(h, h.withEmpty())) {
364 // steal was successful, put everything in the global list
369 // local list has space
370 if (head.compare_exchange_strong(h, h.withIdx(idx).withSizeIncr())) {
375 // h was updated by failing CAS
379 // returns 0 if empty
380 uint32_t globalPop() {
382 TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
383 if (gh.idx == 0 || globalHead_.compare_exchange_strong(
384 gh, gh.withIdx(slot(gh.idx).globalNext))) {
385 // global list is empty, or pop was successful
391 // returns 0 if allocation failed
392 uint32_t localPop(AtomicStruct<TaggedPtr,Atom>& head) {
394 TaggedPtr h = head.load(std::memory_order_acquire);
396 // local list is non-empty, try to pop
397 Slot& s = slot(h.idx);
398 if (head.compare_exchange_strong(
399 h, h.withIdx(s.localNext).withSizeDecr())) {
401 s.localNext = uint32_t(-1);
407 uint32_t idx = globalPop();
409 // global list is empty, allocate and construct new slot
410 if (size_.load(std::memory_order_relaxed) >= actualCapacity_ ||
411 (idx = ++size_) > actualCapacity_) {
415 // default-construct it now if we aren't going to construct and
416 // destroy on each allocation
417 if (!eagerRecycle()) {
418 T* ptr = &slot(idx).elem;
421 slot(idx).localNext = uint32_t(-1);
426 if (head.compare_exchange_strong(
427 h, h.withIdx(s.localNext).withSize(LocalListLimit))) {
428 // global list moved to local list, keep head for us
429 s.localNext = uint32_t(-1);
432 // local bulk push failed, return idx to the global list and try again
437 AtomicStruct<TaggedPtr,Atom>& localHead() {
438 auto stripe = detail::AccessSpreader<Atom>::current(NumLocalLists);
439 return local_[stripe].head;
445 /// This is a stateful Deleter functor, which allows std::unique_ptr
446 /// to track elements allocated from an IndexedMemPool by tracking the
447 /// associated pool. See IndexedMemPool::allocElem.
448 template <typename Pool>
449 struct IndexedMemPoolRecycler {
452 explicit IndexedMemPoolRecycler(Pool* pool) : pool(pool) {}
454 IndexedMemPoolRecycler(const IndexedMemPoolRecycler<Pool>& rhs)
456 IndexedMemPoolRecycler& operator= (const IndexedMemPoolRecycler<Pool>& rhs)
459 void operator()(typename Pool::value_type* elem) const {
460 pool->recycleIndex(pool->locateElem(elem));
468 # pragma GCC diagnostic pop