Make most implicit integer truncations and sign conversions explicit
[folly.git] / folly / IndexedMemPool.h
1 /*
2  * Copyright 2017 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 #pragma once
18
19 #include <type_traits>
20 #include <assert.h>
21 #include <errno.h>
22 #include <stdint.h>
23 #include <boost/noncopyable.hpp>
24 #include <folly/AtomicStruct.h>
25 #include <folly/detail/CacheLocality.h>
26 #include <folly/portability/SysMman.h>
27 #include <folly/portability/Unistd.h>
28
29 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
30 #pragma GCC diagnostic push
31 #pragma GCC diagnostic ignored "-Wshadow"
32
33 namespace folly {
34
35 namespace detail {
36 template <typename Pool>
37 struct IndexedMemPoolRecycler;
38 }
39
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.
56 ///
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.
64 ///
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.
73 ///
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.
82 ///
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).
87 template <typename T,
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 {
94   typedef T value_type;
95
96   typedef std::unique_ptr<T, detail::IndexedMemPoolRecycler<IndexedMemPool>>
97       UniquePtr;
98
99   static_assert(LocalListLimit_ <= 255, "LocalListLimit must fit in 8 bits");
100   enum {
101     NumLocalLists = NumLocalLists_,
102     LocalListLimit = LocalListLimit_
103   };
104
105
106   static constexpr bool eagerRecycle() {
107     return std::is_trivial<T>::value
108         ? EagerRecycleWhenTrivial : EagerRecycleWhenNotTrivial;
109   }
110
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
113
114   static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) {
115     // index of std::numeric_limits<uint32_t>::max() is reserved for isAllocated
116     // tracking
117     return uint32_t(std::min(
118         uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit,
119         uint64_t(std::numeric_limits<uint32_t>::max() - 1)));
120   }
121
122   static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) {
123     return maxIndex - (NumLocalLists - 1) * LocalListLimit;
124   }
125
126
127   /// Constructs a pool that can allocate at least _capacity_ elements,
128   /// even if all the local lists are full
129   explicit IndexedMemPool(uint32_t capacity)
130     : actualCapacity_(maxIndexForCapacity(capacity))
131     , size_(0)
132     , globalHead_(TaggedPtr{})
133   {
134     const size_t needed = sizeof(Slot) * (actualCapacity_ + 1);
135     size_t pagesize = size_t(sysconf(_SC_PAGESIZE));
136     mmapLength_ = ((needed - 1) & ~(pagesize - 1)) + pagesize;
137     assert(needed <= mmapLength_ && mmapLength_ < needed + pagesize);
138     assert((mmapLength_ % pagesize) == 0);
139
140     slots_ = static_cast<Slot*>(mmap(nullptr, mmapLength_,
141                                      PROT_READ | PROT_WRITE,
142                                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
143     if (slots_ == MAP_FAILED) {
144       assert(errno == ENOMEM);
145       throw std::bad_alloc();
146     }
147   }
148
149   /// Destroys all of the contained elements
150   ~IndexedMemPool() {
151     if (!eagerRecycle()) {
152       for (size_t i = size_; i > 0; --i) {
153         slots_[i].~Slot();
154       }
155     }
156     munmap(slots_, mmapLength_);
157   }
158
159   /// Returns a lower bound on the number of elements that may be
160   /// simultaneously allocated and not yet recycled.  Because of the
161   /// local lists it is possible that more elements than this are returned
162   /// successfully
163   size_t capacity() {
164     return capacityForMaxIndex(actualCapacity_);
165   }
166
167   /// Finds a slot with a non-zero index, emplaces a T there if we're
168   /// using the eager recycle lifecycle mode, and returns the index,
169   /// or returns 0 if no elements are available.
170   template <typename ...Args>
171   uint32_t allocIndex(Args&&... args) {
172     static_assert(sizeof...(Args) == 0 || eagerRecycle(),
173         "emplace-style allocation requires eager recycle, "
174         "which is defaulted only for non-trivial types");
175     auto idx = localPop(localHead());
176     if (idx != 0 && eagerRecycle()) {
177       T* ptr = &slot(idx).elem;
178       new (ptr) T(std::forward<Args>(args)...);
179     }
180     return idx;
181   }
182
183   /// If an element is available, returns a std::unique_ptr to it that will
184   /// recycle the element to the pool when it is reclaimed, otherwise returns
185   /// a null (falsy) std::unique_ptr
186   template <typename ...Args>
187   UniquePtr allocElem(Args&&... args) {
188     auto idx = allocIndex(std::forward<Args>(args)...);
189     T* ptr = idx == 0 ? nullptr : &slot(idx).elem;
190     return UniquePtr(ptr, typename UniquePtr::deleter_type(this));
191   }
192
193   /// Gives up ownership previously granted by alloc()
194   void recycleIndex(uint32_t idx) {
195     assert(isAllocated(idx));
196     if (eagerRecycle()) {
197       slot(idx).elem.~T();
198     }
199     localPush(localHead(), idx);
200   }
201
202   /// Provides access to the pooled element referenced by idx
203   T& operator[](uint32_t idx) {
204     return slot(idx).elem;
205   }
206
207   /// Provides access to the pooled element referenced by idx
208   const T& operator[](uint32_t idx) const {
209     return slot(idx).elem;
210   }
211
212   /// If elem == &pool[idx], then pool.locateElem(elem) == idx.  Also,
213   /// pool.locateElem(nullptr) == 0
214   uint32_t locateElem(const T* elem) const {
215     if (!elem) {
216       return 0;
217     }
218
219     static_assert(std::is_standard_layout<Slot>::value, "offsetof needs POD");
220
221     auto slot = reinterpret_cast<const Slot*>(
222         reinterpret_cast<const char*>(elem) - offsetof(Slot, elem));
223     auto rv = uint32_t(slot - slots_);
224
225     // this assert also tests that rv is in range
226     assert(elem == &(*this)[rv]);
227     return rv;
228   }
229
230   /// Returns true iff idx has been alloc()ed and not recycleIndex()ed
231   bool isAllocated(uint32_t idx) const {
232     return slot(idx).localNext == uint32_t(-1);
233   }
234
235
236  private:
237   ///////////// types
238
239   struct Slot {
240     T elem;
241     uint32_t localNext;
242     uint32_t globalNext;
243
244     Slot() : localNext{}, globalNext{} {}
245   };
246
247   struct TaggedPtr {
248     uint32_t idx;
249
250     // size is bottom 8 bits, tag in top 24.  g++'s code generation for
251     // bitfields seems to depend on the phase of the moon, plus we can
252     // do better because we can rely on other checks to avoid masking
253     uint32_t tagAndSize;
254
255     enum : uint32_t {
256         SizeBits = 8,
257         SizeMask = (1U << SizeBits) - 1,
258         TagIncr = 1U << SizeBits,
259     };
260
261     uint32_t size() const {
262       return tagAndSize & SizeMask;
263     }
264
265     TaggedPtr withSize(uint32_t repl) const {
266       assert(repl <= LocalListLimit);
267       return TaggedPtr{ idx, (tagAndSize & ~SizeMask) | repl };
268     }
269
270     TaggedPtr withSizeIncr() const {
271       assert(size() < LocalListLimit);
272       return TaggedPtr{ idx, tagAndSize + 1 };
273     }
274
275     TaggedPtr withSizeDecr() const {
276       assert(size() > 0);
277       return TaggedPtr{ idx, tagAndSize - 1 };
278     }
279
280     TaggedPtr withIdx(uint32_t repl) const {
281       return TaggedPtr{ repl, tagAndSize + TagIncr };
282     }
283
284     TaggedPtr withEmpty() const {
285       return withIdx(0).withSize(0);
286     }
287   };
288
289   struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING LocalList {
290     AtomicStruct<TaggedPtr,Atom> head;
291
292     LocalList() : head(TaggedPtr{}) {}
293   };
294
295   ////////// fields
296
297   /// the actual number of slots that we will allocate, to guarantee
298   /// that we will satisfy the capacity requested at construction time.
299   /// They will be numbered 1..actualCapacity_ (note the 1-based counting),
300   /// and occupy slots_[1..actualCapacity_].
301   size_t actualCapacity_;
302
303   /// the number of bytes allocated from mmap, which is a multiple of
304   /// the page size of the machine
305   size_t mmapLength_;
306
307   /// this records the number of slots that have actually been constructed.
308   /// To allow use of atomic ++ instead of CAS, we let this overflow.
309   /// The actual number of constructed elements is min(actualCapacity_,
310   /// size_)
311   Atom<uint32_t> size_;
312
313   /// raw storage, only 1..min(size_,actualCapacity_) (inclusive) are
314   /// actually constructed.  Note that slots_[0] is not constructed or used
315   FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Slot* slots_;
316
317   /// use AccessSpreader to find your list.  We use stripes instead of
318   /// thread-local to avoid the need to grow or shrink on thread start
319   /// or join.   These are heads of lists chained with localNext
320   LocalList local_[NumLocalLists];
321
322   /// this is the head of a list of node chained by globalNext, that are
323   /// themselves each the head of a list chained by localNext
324   FOLLY_ALIGN_TO_AVOID_FALSE_SHARING AtomicStruct<TaggedPtr,Atom> globalHead_;
325
326   ///////////// private methods
327
328   size_t slotIndex(uint32_t idx) const {
329     assert(0 < idx &&
330            idx <= actualCapacity_ &&
331            idx <= size_.load(std::memory_order_acquire));
332     return idx;
333   }
334
335   Slot& slot(uint32_t idx) {
336     return slots_[slotIndex(idx)];
337   }
338
339   const Slot& slot(uint32_t idx) const {
340     return slots_[slotIndex(idx)];
341   }
342
343   // localHead references a full list chained by localNext.  s should
344   // reference slot(localHead), it is passed as a micro-optimization
345   void globalPush(Slot& s, uint32_t localHead) {
346     while (true) {
347       TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
348       s.globalNext = gh.idx;
349       if (globalHead_.compare_exchange_strong(gh, gh.withIdx(localHead))) {
350         // success
351         return;
352       }
353     }
354   }
355
356   // idx references a single node
357   void localPush(AtomicStruct<TaggedPtr,Atom>& head, uint32_t idx) {
358     Slot& s = slot(idx);
359     TaggedPtr h = head.load(std::memory_order_acquire);
360     while (true) {
361       s.localNext = h.idx;
362
363       if (h.size() == LocalListLimit) {
364         // push will overflow local list, steal it instead
365         if (head.compare_exchange_strong(h, h.withEmpty())) {
366           // steal was successful, put everything in the global list
367           globalPush(s, idx);
368           return;
369         }
370       } else {
371         // local list has space
372         if (head.compare_exchange_strong(h, h.withIdx(idx).withSizeIncr())) {
373           // success
374           return;
375         }
376       }
377       // h was updated by failing CAS
378     }
379   }
380
381   // returns 0 if empty
382   uint32_t globalPop() {
383     while (true) {
384       TaggedPtr gh = globalHead_.load(std::memory_order_acquire);
385       if (gh.idx == 0 || globalHead_.compare_exchange_strong(
386                   gh, gh.withIdx(slot(gh.idx).globalNext))) {
387         // global list is empty, or pop was successful
388         return gh.idx;
389       }
390     }
391   }
392
393   // returns 0 if allocation failed
394   uint32_t localPop(AtomicStruct<TaggedPtr,Atom>& head) {
395     while (true) {
396       TaggedPtr h = head.load(std::memory_order_acquire);
397       if (h.idx != 0) {
398         // local list is non-empty, try to pop
399         Slot& s = slot(h.idx);
400         if (head.compare_exchange_strong(
401                     h, h.withIdx(s.localNext).withSizeDecr())) {
402           // success
403           s.localNext = uint32_t(-1);
404           return h.idx;
405         }
406         continue;
407       }
408
409       uint32_t idx = globalPop();
410       if (idx == 0) {
411         // global list is empty, allocate and construct new slot
412         if (size_.load(std::memory_order_relaxed) >= actualCapacity_ ||
413             (idx = ++size_) > actualCapacity_) {
414           // allocation failed
415           return 0;
416         }
417         // default-construct it now if we aren't going to construct and
418         // destroy on each allocation
419         if (!eagerRecycle()) {
420           T* ptr = &slot(idx).elem;
421           new (ptr) T();
422         }
423         slot(idx).localNext = uint32_t(-1);
424         return idx;
425       }
426
427       Slot& s = slot(idx);
428       if (head.compare_exchange_strong(
429                   h, h.withIdx(s.localNext).withSize(LocalListLimit))) {
430         // global list moved to local list, keep head for us
431         s.localNext = uint32_t(-1);
432         return idx;
433       }
434       // local bulk push failed, return idx to the global list and try again
435       globalPush(s, idx);
436     }
437   }
438
439   AtomicStruct<TaggedPtr,Atom>& localHead() {
440     auto stripe = detail::AccessSpreader<Atom>::current(NumLocalLists);
441     return local_[stripe].head;
442   }
443 };
444
445 namespace detail {
446
447 /// This is a stateful Deleter functor, which allows std::unique_ptr
448 /// to track elements allocated from an IndexedMemPool by tracking the
449 /// associated pool.  See IndexedMemPool::allocElem.
450 template <typename Pool>
451 struct IndexedMemPoolRecycler {
452   Pool* pool;
453
454   explicit IndexedMemPoolRecycler(Pool* pool) : pool(pool) {}
455
456   IndexedMemPoolRecycler(const IndexedMemPoolRecycler<Pool>& rhs)
457       = default;
458   IndexedMemPoolRecycler& operator= (const IndexedMemPoolRecycler<Pool>& rhs)
459       = default;
460
461   void operator()(typename Pool::value_type* elem) const {
462     pool->recycleIndex(pool->locateElem(elem));
463   }
464 };
465
466 }
467
468 } // namespace folly
469
470 # pragma GCC diagnostic pop