2 * Copyright 2017 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.
23 #include <type_traits>
25 #include <boost/noncopyable.hpp>
26 #include <folly/AtomicStruct.h>
27 #include <folly/Portability.h>
28 #include <folly/concurrency/CacheLocality.h>
29 #include <folly/portability/SysMman.h>
30 #include <folly/portability/Unistd.h>
32 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
34 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
39 template <typename Pool>
40 struct IndexedMemPoolRecycler;
45 bool EagerRecycleWhenTrivial = false,
46 bool EagerRecycleWhenNotTrivial = true>
47 struct IndexedMemPoolTraits {
48 static constexpr bool eagerRecycle() {
49 return std::is_trivial<T>::value ? EagerRecycleWhenTrivial
50 : EagerRecycleWhenNotTrivial;
53 /// Called when the element pointed to by ptr is allocated for the
55 static void initialize(T* ptr) {
56 if (!eagerRecycle()) {
61 /// Called when the element pointed to by ptr is freed at the pool
63 static void cleanup(T* ptr) {
64 if (!eagerRecycle()) {
69 /// Called when the element is allocated with the arguments forwarded from
70 /// IndexedMemPool::allocElem.
71 template <typename... Args>
72 static void onAllocate(T* ptr, Args&&... args) {
74 sizeof...(Args) == 0 || eagerRecycle(),
75 "emplace-style allocation requires eager recycle, "
76 "which is defaulted only for non-trivial types");
78 new (ptr) T(std::forward<Args>(args)...);
82 /// Called when the element is recycled.
83 static void onRecycle(T* ptr) {
90 /// IndexedMemPool traits that implements the lazy lifecycle strategy. In this
91 /// strategy elements are default-constructed the first time they are allocated,
92 /// and destroyed when the pool itself is destroyed.
94 using IndexedMemPoolTraitsLazyRecycle = IndexedMemPoolTraits<T, false, false>;
96 /// IndexedMemPool traits that implements the eager lifecycle strategy. In this
97 /// strategy elements are constructed when they are allocated from the pool and
98 /// destroyed when recycled.
100 using IndexedMemPoolTraitsEagerRecycle = IndexedMemPoolTraits<T, true, true>;
102 /// Instances of IndexedMemPool dynamically allocate and then pool their
103 /// element type (T), returning 4-byte integer indices that can be passed
104 /// to the pool's operator[] method to access or obtain pointers to the
105 /// actual elements. The memory backing items returned from the pool
106 /// will always be readable, even if items have been returned to the pool.
107 /// These two features are useful for lock-free algorithms. The indexing
108 /// behavior makes it easy to build tagged pointer-like-things, since
109 /// a large number of elements can be managed using fewer bits than a
110 /// full pointer. The access-after-free behavior makes it safe to read
111 /// from T-s even after they have been recycled, since it is guaranteed
112 /// that the memory won't have been returned to the OS and unmapped
113 /// (the algorithm must still use a mechanism to validate that the read
114 /// was correct, but it doesn't have to worry about page faults), and if
115 /// the elements use internal sequence numbers it can be guaranteed that
116 /// there won't be an ABA match due to the element being overwritten with
117 /// a different type that has the same bit pattern.
119 /// The object lifecycle strategy is controlled by the Traits parameter.
120 /// One strategy, implemented by IndexedMemPoolTraitsEagerRecycle, is to
121 /// construct objects when they are allocated from the pool and destroy
122 /// them when they are recycled. In this mode allocIndex and allocElem
123 /// have emplace-like semantics. In another strategy, implemented by
124 /// IndexedMemPoolTraitsLazyRecycle, objects are default-constructed the
125 /// first time they are removed from the pool, and deleted when the pool
126 /// itself is deleted. By default the first mode is used for non-trivial
127 /// T, and the second is used for trivial T. Clients can customize the
128 /// object lifecycle by providing their own Traits implementation.
129 /// See IndexedMemPoolTraits for a Traits example.
131 /// IMPORTANT: Space for extra elements is allocated to account for those
132 /// that are inaccessible because they are in other local lists, so the
133 /// actual number of items that can be allocated ranges from capacity to
134 /// capacity + (NumLocalLists_-1)*LocalListLimit_. This is important if
135 /// you are trying to maximize the capacity of the pool while constraining
136 /// the bit size of the resulting pointers, because the pointers will
137 /// actually range up to the boosted capacity. See maxIndexForCapacity
138 /// and capacityForMaxIndex.
140 /// To avoid contention, NumLocalLists_ free lists of limited (less than
141 /// or equal to LocalListLimit_) size are maintained, and each thread
142 /// retrieves and returns entries from its associated local list. If the
143 /// local list becomes too large then elements are placed in bulk in a
144 /// global free list. This allows items to be efficiently recirculated
145 /// from consumers to producers. AccessSpreader is used to access the
146 /// local lists, so there is no performance advantage to having more
147 /// local lists than L1 caches.
149 /// The pool mmap-s the entire necessary address space when the pool is
150 /// constructed, but delays element construction. This means that only
151 /// elements that are actually returned to the caller get paged into the
152 /// process's resident set (RSS).
155 uint32_t NumLocalLists_ = 32,
156 uint32_t LocalListLimit_ = 200,
157 template <typename> class Atom = std::atomic,
158 typename Traits = IndexedMemPoolTraits<T>>
159 struct IndexedMemPool : boost::noncopyable {
160 typedef T value_type;
162 typedef std::unique_ptr<T, detail::IndexedMemPoolRecycler<IndexedMemPool>>
165 static_assert(LocalListLimit_ <= 255, "LocalListLimit must fit in 8 bits");
167 NumLocalLists = NumLocalLists_,
168 LocalListLimit = LocalListLimit_
171 // these are public because clients may need to reason about the number
172 // of bits required to hold indices from a pool, given its capacity
174 static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) {
175 // index of std::numeric_limits<uint32_t>::max() is reserved for isAllocated
177 return uint32_t(std::min(
178 uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit,
179 uint64_t(std::numeric_limits<uint32_t>::max() - 1)));
182 static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) {
183 return maxIndex - (NumLocalLists - 1) * LocalListLimit;
187 /// Constructs a pool that can allocate at least _capacity_ elements,
188 /// even if all the local lists are full
189 explicit IndexedMemPool(uint32_t capacity)
190 : actualCapacity_(maxIndexForCapacity(capacity))
192 , globalHead_(TaggedPtr{})
194 const size_t needed = sizeof(Slot) * (actualCapacity_ + 1);
195 size_t pagesize = size_t(sysconf(_SC_PAGESIZE));
196 mmapLength_ = ((needed - 1) & ~(pagesize - 1)) + pagesize;
197 assert(needed <= mmapLength_ && mmapLength_ < needed + pagesize);
198 assert((mmapLength_ % pagesize) == 0);
200 slots_ = static_cast<Slot*>(mmap(nullptr, mmapLength_,
201 PROT_READ | PROT_WRITE,
202 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
203 if (slots_ == MAP_FAILED) {
204 assert(errno == ENOMEM);
205 throw std::bad_alloc();
209 /// Destroys all of the contained elements
211 for (uint32_t i = maxAllocatedIndex(); i > 0; --i) {
212 Traits::cleanup(&slots_[i].elem);
214 munmap(slots_, mmapLength_);
217 /// Returns a lower bound on the number of elements that may be
218 /// simultaneously allocated and not yet recycled. Because of the
219 /// local lists it is possible that more elements than this are returned
221 uint32_t capacity() {
222 return capacityForMaxIndex(actualCapacity_);
225 /// Returns the maximum index of elements ever allocated in this pool
226 /// including elements that have been recycled.
227 uint32_t maxAllocatedIndex() const {
228 // Take the minimum since it is possible that size_ > actualCapacity_.
229 // This can happen if there are multiple concurrent requests
230 // when size_ == actualCapacity_ - 1.
231 return std::min(uint32_t(size_), uint32_t(actualCapacity_));
234 /// Finds a slot with a non-zero index, emplaces a T there if we're
235 /// using the eager recycle lifecycle mode, and returns the index,
236 /// or returns 0 if no elements are available. Passes a pointer to
237 /// the element to Traits::onAllocate before the slot is marked as
239 template <typename ...Args>
240 uint32_t allocIndex(Args&&... args) {
241 auto idx = localPop(localHead());
244 Traits::onAllocate(&s.elem, std::forward<Args>(args)...);
250 /// If an element is available, returns a std::unique_ptr to it that will
251 /// recycle the element to the pool when it is reclaimed, otherwise returns
252 /// a null (falsy) std::unique_ptr. Passes a pointer to the element to
253 /// Traits::onAllocate before the slot is marked as allocated.
254 template <typename ...Args>
255 UniquePtr allocElem(Args&&... args) {
256 auto idx = allocIndex(std::forward<Args>(args)...);
257 T* ptr = idx == 0 ? nullptr : &slot(idx).elem;
258 return UniquePtr(ptr, typename UniquePtr::deleter_type(this));
261 /// Gives up ownership previously granted by alloc()
262 void recycleIndex(uint32_t idx) {
263 assert(isAllocated(idx));
264 localPush(localHead(), idx);
267 /// Provides access to the pooled element referenced by idx
268 T& operator[](uint32_t idx) {
269 return slot(idx).elem;
272 /// Provides access to the pooled element referenced by idx
273 const T& operator[](uint32_t idx) const {
274 return slot(idx).elem;
277 /// If elem == &pool[idx], then pool.locateElem(elem) == idx. Also,
278 /// pool.locateElem(nullptr) == 0
279 uint32_t locateElem(const T* elem) const {
284 static_assert(std::is_standard_layout<Slot>::value, "offsetof needs POD");
286 auto slot = reinterpret_cast<const Slot*>(
287 reinterpret_cast<const char*>(elem) - offsetof(Slot, elem));
288 auto rv = uint32_t(slot - slots_);
290 // this assert also tests that rv is in range
291 assert(elem == &(*this)[rv]);
295 /// Returns true iff idx has been alloc()ed and not recycleIndex()ed
296 bool isAllocated(uint32_t idx) const {
297 return slot(idx).localNext.load(std::memory_order_acquire) == uint32_t(-1);
306 Atom<uint32_t> localNext;
307 Atom<uint32_t> globalNext;
309 Slot() : localNext{}, globalNext{} {}
315 // size is bottom 8 bits, tag in top 24. g++'s code generation for
316 // bitfields seems to depend on the phase of the moon, plus we can
317 // do better because we can rely on other checks to avoid masking
322 SizeMask = (1U << SizeBits) - 1,
323 TagIncr = 1U << SizeBits,
326 uint32_t size() const {
327 return tagAndSize & SizeMask;
330 TaggedPtr withSize(uint32_t repl) const {
331 assert(repl <= LocalListLimit);
332 return TaggedPtr{ idx, (tagAndSize & ~SizeMask) | repl };
335 TaggedPtr withSizeIncr() const {
336 assert(size() < LocalListLimit);
337 return TaggedPtr{ idx, tagAndSize + 1 };
340 TaggedPtr withSizeDecr() const {
342 return TaggedPtr{ idx, tagAndSize - 1 };
345 TaggedPtr withIdx(uint32_t repl) const {
346 return TaggedPtr{ repl, tagAndSize + TagIncr };
349 TaggedPtr withEmpty() const {
350 return withIdx(0).withSize(0);
354 struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING LocalList {
355 AtomicStruct<TaggedPtr,Atom> head;
357 LocalList() : head(TaggedPtr{}) {}
362 /// the number of bytes allocated from mmap, which is a multiple of
363 /// the page size of the machine
366 /// the actual number of slots that we will allocate, to guarantee
367 /// that we will satisfy the capacity requested at construction time.
368 /// They will be numbered 1..actualCapacity_ (note the 1-based counting),
369 /// and occupy slots_[1..actualCapacity_].
370 uint32_t actualCapacity_;
372 /// this records the number of slots that have actually been constructed.
373 /// To allow use of atomic ++ instead of CAS, we let this overflow.
374 /// The actual number of constructed elements is min(actualCapacity_,
376 Atom<uint32_t> size_;
378 /// raw storage, only 1..min(size_,actualCapacity_) (inclusive) are
379 /// actually constructed. Note that slots_[0] is not constructed or used
380 FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Slot* slots_;
382 /// use AccessSpreader to find your list. We use stripes instead of
383 /// thread-local to avoid the need to grow or shrink on thread start
384 /// or join. These are heads of lists chained with localNext
385 LocalList local_[NumLocalLists];
387 /// this is the head of a list of node chained by globalNext, that are
388 /// themselves each the head of a list chained by localNext
389 FOLLY_ALIGN_TO_AVOID_FALSE_SHARING AtomicStruct<TaggedPtr,Atom> globalHead_;
391 ///////////// private methods
393 uint32_t slotIndex(uint32_t idx) const {
395 idx <= actualCapacity_ &&
396 idx <= size_.load(std::memory_order_acquire));
400 Slot& slot(uint32_t idx) {
401 return slots_[slotIndex(idx)];
404 const Slot& slot(uint32_t idx) const {
405 return slots_[slotIndex(idx)];
408 // localHead references a full list chained by localNext. s should
409 // reference slot(localHead), it is passed as a micro-optimization
410 void globalPush(Slot& s, uint32_t localHead) {
412 TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
413 s.globalNext.store(gh.idx, std::memory_order_relaxed);
414 if (globalHead_.compare_exchange_strong(gh, gh.withIdx(localHead))) {
421 // idx references a single node
422 void localPush(AtomicStruct<TaggedPtr,Atom>& head, uint32_t idx) {
424 TaggedPtr h = head.load(std::memory_order_acquire);
426 s.localNext.store(h.idx, std::memory_order_release);
427 Traits::onRecycle(&slot(idx).elem);
429 if (h.size() == LocalListLimit) {
430 // push will overflow local list, steal it instead
431 if (head.compare_exchange_strong(h, h.withEmpty())) {
432 // steal was successful, put everything in the global list
437 // local list has space
438 if (head.compare_exchange_strong(h, h.withIdx(idx).withSizeIncr())) {
443 // h was updated by failing CAS
447 // returns 0 if empty
448 uint32_t globalPop() {
450 TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
452 globalHead_.compare_exchange_strong(
455 slot(gh.idx).globalNext.load(std::memory_order_relaxed)))) {
456 // global list is empty, or pop was successful
462 // returns 0 if allocation failed
463 uint32_t localPop(AtomicStruct<TaggedPtr,Atom>& head) {
465 TaggedPtr h = head.load(std::memory_order_acquire);
467 // local list is non-empty, try to pop
468 Slot& s = slot(h.idx);
469 auto next = s.localNext.load(std::memory_order_relaxed);
470 if (head.compare_exchange_strong(h, h.withIdx(next).withSizeDecr())) {
477 uint32_t idx = globalPop();
479 // global list is empty, allocate and construct new slot
480 if (size_.load(std::memory_order_relaxed) >= actualCapacity_ ||
481 (idx = ++size_) > actualCapacity_) {
485 Traits::initialize(&slot(idx).elem);
490 auto next = s.localNext.load(std::memory_order_relaxed);
491 if (head.compare_exchange_strong(
492 h, h.withIdx(next).withSize(LocalListLimit))) {
493 // global list moved to local list, keep head for us
496 // local bulk push failed, return idx to the global list and try again
501 AtomicStruct<TaggedPtr,Atom>& localHead() {
502 auto stripe = AccessSpreader<Atom>::current(NumLocalLists);
503 return local_[stripe].head;
506 void markAllocated(Slot& slot) {
507 slot.localNext.store(uint32_t(-1), std::memory_order_release);
513 /// This is a stateful Deleter functor, which allows std::unique_ptr
514 /// to track elements allocated from an IndexedMemPool by tracking the
515 /// associated pool. See IndexedMemPool::allocElem.
516 template <typename Pool>
517 struct IndexedMemPoolRecycler {
520 explicit IndexedMemPoolRecycler(Pool* pool) : pool(pool) {}
522 IndexedMemPoolRecycler(const IndexedMemPoolRecycler<Pool>& rhs)
524 IndexedMemPoolRecycler& operator= (const IndexedMemPoolRecycler<Pool>& rhs)
527 void operator()(typename Pool::value_type* elem) const {
528 pool->recycleIndex(pool->locateElem(elem));