Multi-Producer, Multi-Consumer pipeline
[folly.git] / folly / MPMCQueue.h
1 /*
2  * Copyright 2013 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 <algorithm>
20 #include <atomic>
21 #include <assert.h>
22 #include <boost/noncopyable.hpp>
23 #include <errno.h>
24 #include <limits>
25 #include <linux/futex.h>
26 #include <string.h>
27 #include <sys/syscall.h>
28 #include <unistd.h>
29
30 #include <folly/Traits.h>
31 #include <folly/detail/Futex.h>
32
33 namespace folly {
34
35 namespace detail {
36
37 template<typename T, template<typename> class Atom>
38 class SingleElementQueue;
39
40 template <typename T> class MPMCPipelineStageImpl;
41
42 } // namespace detail
43
44 /// MPMCQueue<T> is a high-performance bounded concurrent queue that
45 /// supports multiple producers, multiple consumers, and optional blocking.
46 /// The queue has a fixed capacity, for which all memory will be allocated
47 /// up front.  The bulk of the work of enqueuing and dequeuing can be
48 /// performed in parallel.
49 ///
50 /// The underlying implementation uses a ticket dispenser for the head and
51 /// the tail, spreading accesses across N single-element queues to produce
52 /// a queue with capacity N.  The ticket dispensers use atomic increment,
53 /// which is more robust to contention than a CAS loop.  Each of the
54 /// single-element queues uses its own CAS to serialize access, with an
55 /// adaptive spin cutoff.  When spinning fails on a single-element queue
56 /// it uses futex()'s _BITSET operations to reduce unnecessary wakeups
57 /// even if multiple waiters are present on an individual queue (such as
58 /// when the MPMCQueue's capacity is smaller than the number of enqueuers
59 /// or dequeuers).
60 ///
61 /// NOEXCEPT INTERACTION: Ticket-based queues separate the assignment
62 /// of In benchmarks (contained in tao/queues/ConcurrentQueueTests)
63 /// it handles 1 to 1, 1 to N, N to 1, and N to M thread counts better
64 /// than any of the alternatives present in fbcode, for both small (~10)
65 /// and large capacities.  In these benchmarks it is also faster than
66 /// tbb::concurrent_bounded_queue for all configurations.  When there are
67 /// many more threads than cores, MPMCQueue is _much_ faster than the tbb
68 /// queue because it uses futex() to block and unblock waiting threads,
69 /// rather than spinning with sched_yield.
70 ///
71 /// queue positions from the actual construction of the in-queue elements,
72 /// which means that the T constructor used during enqueue must not throw
73 /// an exception.  This is enforced at compile time using type traits,
74 /// which requires that T be adorned with accurate noexcept information.
75 /// If your type does not use noexcept, you will have to wrap it in
76 /// something that provides the guarantee.  We provide an alternate
77 /// safe implementation for types that don't use noexcept but that are
78 /// marked folly::IsRelocatable and boost::has_nothrow_constructor,
79 /// which is common for folly types.  In particular, if you can declare
80 /// FOLLY_ASSUME_FBVECTOR_COMPATIBLE then your type can be put in
81 /// MPMCQueue.
82 template<typename T,
83          template<typename> class Atom = std::atomic,
84          typename = typename std::enable_if<
85              std::is_nothrow_constructible<T,T&&>::value ||
86              folly::IsRelocatable<T>::value>::type>
87 class MPMCQueue : boost::noncopyable {
88   friend class detail::MPMCPipelineStageImpl<T>;
89  public:
90   typedef T value_type;
91
92   explicit MPMCQueue(size_t capacity)
93     : capacity_(capacity)
94     , slots_(new detail::SingleElementQueue<T,Atom>[capacity +
95                                                     2 * kSlotPadding])
96     , stride_(computeStride(capacity))
97     , pushTicket_(0)
98     , popTicket_(0)
99     , pushSpinCutoff_(0)
100     , popSpinCutoff_(0)
101   {
102     // ideally this would be a static assert, but g++ doesn't allow it
103     assert(alignof(MPMCQueue<T,Atom>) >= kFalseSharingRange);
104   }
105
106   /// A default-constructed queue is useful because a usable (non-zero
107   /// capacity) queue can be moved onto it or swapped with it
108   MPMCQueue() noexcept
109     : capacity_(0)
110     , slots_(nullptr)
111     , stride_(0)
112     , pushTicket_(0)
113     , popTicket_(0)
114     , pushSpinCutoff_(0)
115     , popSpinCutoff_(0)
116   {}
117
118   /// IMPORTANT: The move constructor is here to make it easier to perform
119   /// the initialization phase, it is not safe to use when there are any
120   /// concurrent accesses (this is not checked).
121   MPMCQueue(MPMCQueue<T,Atom>&& rhs) noexcept
122     : capacity_(rhs.capacity_)
123     , slots_(rhs.slots_)
124     , stride_(rhs.stride_)
125     , pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed))
126     , popTicket_(rhs.popTicket_.load(std::memory_order_relaxed))
127     , pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed))
128     , popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed))
129   {
130     // relaxed ops are okay for the previous reads, since rhs queue can't
131     // be in concurrent use
132
133     // zero out rhs
134     rhs.capacity_ = 0;
135     rhs.slots_ = nullptr;
136     rhs.stride_ = 0;
137     rhs.pushTicket_.store(0, std::memory_order_relaxed);
138     rhs.popTicket_.store(0, std::memory_order_relaxed);
139     rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
140     rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
141   }
142
143   /// IMPORTANT: The move operator is here to make it easier to perform
144   /// the initialization phase, it is not safe to use when there are any
145   /// concurrent accesses (this is not checked).
146   MPMCQueue<T,Atom> const& operator= (MPMCQueue<T,Atom>&& rhs) {
147     if (this != &rhs) {
148       this->~MPMCQueue();
149       new (this) MPMCQueue(std::move(rhs));
150     }
151     return *this;
152   }
153
154   /// MPMCQueue can only be safely destroyed when there are no
155   /// pending enqueuers or dequeuers (this is not checked).
156   ~MPMCQueue() {
157     delete[] slots_;
158   }
159
160   /// Returns the number of successful reads minus the number of successful
161   /// writes.  Waiting blockingRead and blockingWrite calls are included,
162   /// so this value can be negative.
163   ssize_t size() const noexcept {
164     // since both pushes and pops increase monotonically, we can get a
165     // consistent snapshot either by bracketing a read of popTicket_ with
166     // two reads of pushTicket_ that return the same value, or the other
167     // way around.  We maximize our chances by alternately attempting
168     // both bracketings.
169     uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
170     uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
171     while (true) {
172       uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
173       if (pushes == nextPushes) {
174         // pushTicket_ didn't change from A (or the previous C) to C,
175         // so we can linearize at B (or D)
176         return pushes - pops;
177       }
178       pushes = nextPushes;
179       uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
180       if (pops == nextPops) {
181         // popTicket_ didn't chance from B (or the previous D), so we
182         // can linearize at C
183         return pushes - pops;
184       }
185       pops = nextPops;
186     }
187   }
188
189   /// Returns true if there are no items available for dequeue
190   bool isEmpty() const noexcept {
191     return size() <= 0;
192   }
193
194   /// Returns true if there is currently no empty space to enqueue
195   bool isFull() const noexcept {
196     // careful with signed -> unsigned promotion, since size can be negative
197     return size() >= static_cast<ssize_t>(capacity_);
198   }
199
200   /// Returns is a guess at size() for contexts that don't need a precise
201   /// value, such as stats.
202   ssize_t sizeGuess() const noexcept {
203     return writeCount() - readCount();
204   }
205
206   /// Doesn't change
207   size_t capacity() const noexcept {
208     return capacity_;
209   }
210
211   /// Returns the total number of calls to blockingWrite or successful
212   /// calls to write, including those blockingWrite calls that are
213   /// currently blocking
214   uint64_t writeCount() const noexcept {
215     return pushTicket_.load(std::memory_order_acquire);
216   }
217
218   /// Returns the total number of calls to blockingRead or successful
219   /// calls to read, including those blockingRead calls that are currently
220   /// blocking
221   uint64_t readCount() const noexcept {
222     return popTicket_.load(std::memory_order_acquire);
223   }
224
225   /// Enqueues a T constructed from args, blocking until space is
226   /// available.  Note that this method signature allows enqueue via
227   /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
228   /// via emplacement if args is an initializer list that can be passed
229   /// to a T constructor.
230   template <typename ...Args>
231   void blockingWrite(Args&&... args) noexcept {
232     enqueueWithTicket(pushTicket_++, std::forward<Args>(args)...);
233   }
234
235   /// If an item can be enqueued with no blocking, does so and returns
236   /// true, otherwise returns false.  This method is similar to
237   /// writeIfNotFull, but if you don't have a specific need for that
238   /// method you should use this one.
239   ///
240   /// One of the common usages of this method is to enqueue via the
241   /// move constructor, something like q.write(std::move(x)).  If write
242   /// returns false because the queue is full then x has not actually been
243   /// consumed, which looks strange.  To understand why it is actually okay
244   /// to use x afterward, remember that std::move is just a typecast that
245   /// provides an rvalue reference that enables use of a move constructor
246   /// or operator.  std::move doesn't actually move anything.  It could
247   /// more accurately be called std::rvalue_cast or std::move_permission.
248   template <typename ...Args>
249   bool write(Args&&... args) noexcept {
250     uint64_t ticket;
251     if (tryObtainReadyPushTicket(ticket)) {
252       // we have pre-validated that the ticket won't block
253       enqueueWithTicket(ticket, std::forward<Args>(args)...);
254       return true;
255     } else {
256       return false;
257     }
258   }
259
260   /// If the queue is not full, enqueues and returns true, otherwise
261   /// returns false.  Unlike write this method can be blocked by another
262   /// thread, specifically a read that has linearized (been assigned
263   /// a ticket) but not yet completed.  If you don't really need this
264   /// function you should probably use write.
265   ///
266   /// MPMCQueue isn't lock-free, so just because a read operation has
267   /// linearized (and isFull is false) doesn't mean that space has been
268   /// made available for another write.  In this situation write will
269   /// return false, but writeIfNotFull will wait for the dequeue to finish.
270   /// This method is required if you are composing queues and managing
271   /// your own wakeup, because it guarantees that after every successful
272   /// write a readIfNotFull will succeed.
273   template <typename ...Args>
274   bool writeIfNotFull(Args&&... args) noexcept {
275     uint64_t ticket;
276     if (tryObtainPromisedPushTicket(ticket)) {
277       // some other thread is already dequeuing the slot into which we
278       // are going to enqueue, but we might have to wait for them to finish
279       enqueueWithTicket(ticket, std::forward<Args>(args)...);
280       return true;
281     } else {
282       return false;
283     }
284   }
285
286   /// Moves a dequeued element onto elem, blocking until an element
287   /// is available
288   void blockingRead(T& elem) noexcept {
289     dequeueWithTicket(popTicket_++, elem);
290   }
291
292   /// If an item can be dequeued with no blocking, does so and returns
293   /// true, otherwise returns false.
294   bool read(T& elem) noexcept {
295     uint64_t ticket;
296     if (tryObtainReadyPopTicket(ticket)) {
297       // the ticket has been pre-validated to not block
298       dequeueWithTicket(ticket, elem);
299       return true;
300     } else {
301       return false;
302     }
303   }
304
305   /// If the queue is not empty, dequeues and returns true, otherwise
306   /// returns false.  If the matching write is still in progress then this
307   /// method may block waiting for it.  If you don't rely on being able
308   /// to dequeue (such as by counting completed write) then you should
309   /// prefer read.
310   bool readIfNotEmpty(T& elem) noexcept {
311     uint64_t ticket;
312     if (tryObtainPromisedPopTicket(ticket)) {
313       // the matching enqueue already has a ticket, but might not be done
314       dequeueWithTicket(ticket, elem);
315       return true;
316     } else {
317       return false;
318     }
319   }
320
321  private:
322   enum {
323     /// Once every kAdaptationFreq we will spin longer, to try to estimate
324     /// the proper spin backoff
325     kAdaptationFreq = 128,
326
327     /// Memory locations on the same cache line are subject to false
328     /// sharing, which is very bad for performance
329     kFalseSharingRange = 64,
330
331     /// To avoid false sharing in slots_ with neighboring memory
332     /// allocations, we pad it with this many SingleElementQueue-s at
333     /// each end
334     kSlotPadding = 1 +
335         (kFalseSharingRange - 1) / sizeof(detail::SingleElementQueue<T,Atom>)
336   };
337
338 #define FOLLY_ON_NEXT_CACHE_LINE __attribute__((aligned(kFalseSharingRange)))
339
340   /// The maximum number of items in the queue at once
341   size_t capacity_ FOLLY_ON_NEXT_CACHE_LINE;
342
343   /// An array of capacity_ SingleElementQueue-s, each of which holds
344   /// either 0 or 1 item.  We over-allocate by 2 * kSlotPadding and don't
345   /// touch the slots at either end, to avoid false sharing
346   detail::SingleElementQueue<T,Atom>* slots_;
347
348   /// The number of slots_ indices that we advance for each ticket, to
349   /// avoid false sharing.  Ideally slots_[i] and slots_[i + stride_]
350   /// aren't on the same cache line
351   int stride_;
352
353   /// Enqueuers get tickets from here
354   Atom<uint64_t> pushTicket_ FOLLY_ON_NEXT_CACHE_LINE;
355
356   /// Dequeuers get tickets from here
357   Atom<uint64_t> popTicket_ FOLLY_ON_NEXT_CACHE_LINE;
358
359   /// This is how many times we will spin before using FUTEX_WAIT when
360   /// the queue is full on enqueue, adaptively computed by occasionally
361   /// spinning for longer and smoothing with an exponential moving average
362   Atom<int> pushSpinCutoff_ FOLLY_ON_NEXT_CACHE_LINE;
363
364   /// The adaptive spin cutoff when the queue is empty on dequeue
365   Atom<int> popSpinCutoff_ FOLLY_ON_NEXT_CACHE_LINE;
366
367   /// Alignment doesn't avoid false sharing at the end of the struct,
368   /// so fill out the last cache line
369   char padding_[kFalseSharingRange - sizeof(Atom<int>)];
370
371 #undef FOLLY_ON_NEXT_CACHE_LINE
372
373   /// We assign tickets in increasing order, but we don't want to
374   /// access neighboring elements of slots_ because that will lead to
375   /// false sharing (multiple cores accessing the same cache line even
376   /// though they aren't accessing the same bytes in that cache line).
377   /// To avoid this we advance by stride slots per ticket.
378   ///
379   /// We need gcd(capacity, stride) to be 1 so that we will use all
380   /// of the slots.  We ensure this by only considering prime strides,
381   /// which either have no common divisors with capacity or else have
382   /// a zero remainder after dividing by capacity.  That is sufficient
383   /// to guarantee correctness, but we also want to actually spread the
384   /// accesses away from each other to avoid false sharing (consider a
385   /// stride of 7 with a capacity of 8).  To that end we try a few taking
386   /// care to observe that advancing by -1 is as bad as advancing by 1
387   /// when in comes to false sharing.
388   ///
389   /// The simple way to avoid false sharing would be to pad each
390   /// SingleElementQueue, but since we have capacity_ of them that could
391   /// waste a lot of space.
392   static int computeStride(size_t capacity) noexcept {
393     static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
394
395     int bestStride = 1;
396     size_t bestSep = 1;
397     for (int stride : smallPrimes) {
398       if ((stride % capacity) == 0 || (capacity % stride) == 0) {
399         continue;
400       }
401       size_t sep = stride % capacity;
402       sep = std::min(sep, capacity - sep);
403       if (sep > bestSep) {
404         bestStride = stride;
405         bestSep = sep;
406       }
407     }
408     return bestStride;
409   }
410
411   /// Returns the index into slots_ that should be used when enqueuing or
412   /// dequeuing with the specified ticket
413   size_t idx(uint64_t ticket) noexcept {
414     return ((ticket * stride_) % capacity_) + kSlotPadding;
415   }
416
417   /// Maps an enqueue or dequeue ticket to the turn should be used at the
418   /// corresponding SingleElementQueue
419   uint32_t turn(uint64_t ticket) noexcept {
420     return ticket / capacity_;
421   }
422
423   /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
424   /// won't block.  Returns true on immediate success, false on immediate
425   /// failure.
426   bool tryObtainReadyPushTicket(uint64_t& rv) noexcept {
427     auto ticket = pushTicket_.load(std::memory_order_acquire); // A
428     while (true) {
429       if (!slots_[idx(ticket)].mayEnqueue(turn(ticket))) {
430         // if we call enqueue(ticket, ...) on the SingleElementQueue
431         // right now it would block, but this might no longer be the next
432         // ticket.  We can increase the chance of tryEnqueue success under
433         // contention (without blocking) by rechecking the ticket dispenser
434         auto prev = ticket;
435         ticket = pushTicket_.load(std::memory_order_acquire); // B
436         if (prev == ticket) {
437           // mayEnqueue was bracketed by two reads (A or prev B or prev
438           // failing CAS to B), so we are definitely unable to enqueue
439           return false;
440         }
441       } else {
442         // we will bracket the mayEnqueue check with a read (A or prev B
443         // or prev failing CAS) and the following CAS.  If the CAS fails
444         // it will effect a load of pushTicket_
445         if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
446           rv = ticket;
447           return true;
448         }
449       }
450     }
451   }
452
453   /// Tries to obtain a push ticket which can be satisfied if all
454   /// in-progress pops complete.  This function does not block, but
455   /// blocking may be required when using the returned ticket if some
456   /// other thread's pop is still in progress (ticket has been granted but
457   /// pop has not yet completed).
458   bool tryObtainPromisedPushTicket(uint64_t& rv) noexcept {
459     auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
460     while (true) {
461       auto numPops = popTicket_.load(std::memory_order_acquire); // B
462       // n will be negative if pops are pending
463       int64_t n = numPushes - numPops;
464       if (n >= static_cast<ssize_t>(capacity_)) {
465         // Full, linearize at B.  We don't need to recheck the read we
466         // performed at A, because if numPushes was stale at B then the
467         // real numPushes value is even worse
468         return false;
469       }
470       if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
471         rv = numPushes;
472         return true;
473       }
474     }
475   }
476
477   /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
478   /// won't block.  Returns true on immediate success, false on immediate
479   /// failure.
480   bool tryObtainReadyPopTicket(uint64_t& rv) noexcept {
481     auto ticket = popTicket_.load(std::memory_order_acquire);
482     while (true) {
483       if (!slots_[idx(ticket)].mayDequeue(turn(ticket))) {
484         auto prev = ticket;
485         ticket = popTicket_.load(std::memory_order_acquire);
486         if (prev == ticket) {
487           return false;
488         }
489       } else {
490         if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
491           rv = ticket;
492           return true;
493         }
494       }
495     }
496   }
497
498   /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
499   /// corresponding push ticket has already been handed out, rather than
500   /// returning one whose corresponding push ticket has already been
501   /// completed.  This means that there is a possibility that the caller
502   /// will block when using the ticket, but it allows the user to rely on
503   /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
504   /// will return true.  The "try" part of this is that we won't have
505   /// to block waiting for someone to call enqueue, although we might
506   /// have to block waiting for them to finish executing code inside the
507   /// MPMCQueue itself.
508   bool tryObtainPromisedPopTicket(uint64_t& rv) noexcept {
509     auto numPops = popTicket_.load(std::memory_order_acquire); // A
510     while (true) {
511       auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
512       if (numPops >= numPushes) {
513         // Empty, or empty with pending pops.  Linearize at B.  We don't
514         // need to recheck the read we performed at A, because if numPops
515         // is stale then the fresh value is larger and the >= is still true
516         return false;
517       }
518       if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
519         rv = numPops;
520         return true;
521       }
522     }
523   }
524
525   // Given a ticket, constructs an enqueued item using args
526   template <typename ...Args>
527   void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
528     slots_[idx(ticket)].enqueue(turn(ticket),
529                                 pushSpinCutoff_,
530                                 (ticket % kAdaptationFreq) == 0,
531                                 std::forward<Args>(args)...);
532   }
533
534   // Given a ticket, dequeues the corresponding element
535   void dequeueWithTicket(uint64_t ticket, T& elem) noexcept {
536     slots_[idx(ticket)].dequeue(turn(ticket),
537                                 popSpinCutoff_,
538                                 (ticket % kAdaptationFreq) == 0,
539                                 elem);
540   }
541 };
542
543
544 namespace detail {
545
546 /// A TurnSequencer allows threads to order their execution according to
547 /// a monotonically increasing (with wraparound) "turn" value.  The two
548 /// operations provided are to wait for turn T, and to move to the next
549 /// turn.  Every thread that is waiting for T must have arrived before
550 /// that turn is marked completed (for MPMCQueue only one thread waits
551 /// for any particular turn, so this is trivially true).
552 ///
553 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
554 /// left by 6), along with a 6 bit saturating value that records the
555 /// maximum waiter minus the current turn.  Wraparound of the turn space
556 /// is expected and handled.  This allows us to atomically adjust the
557 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
558 /// Compare this strategy to sem_t's separate num_waiters field, which
559 /// isn't decremented until after the waiting thread gets scheduled,
560 /// during which time more enqueues might have occurred and made pointless
561 /// FUTEX_WAKE calls.
562 ///
563 /// TurnSequencer uses futex() directly.  It is optimized for the
564 /// case that the highest awaited turn is 32 or less higher than the
565 /// current turn.  We use the FUTEX_WAIT_BITSET variant, which lets
566 /// us embed 32 separate wakeup channels in a single futex.  See
567 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
568 ///
569 /// We only need to keep exact track of the delta between the current
570 /// turn and the maximum waiter for the 32 turns that follow the current
571 /// one, because waiters at turn t+32 will be awoken at turn t.  At that
572 /// point they can then adjust the delta using the higher base.  Since we
573 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
574 /// We actually store waiter deltas up to 63, since that might reduce
575 /// the number of CAS operations a tiny bit.
576 ///
577 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
578 /// spin cutoff before waiting.  The overheads (and convergence rate)
579 /// of separately tracking the spin cutoff for each TurnSequencer would
580 /// be prohibitive, so the actual storage is passed in as a parameter and
581 /// updated atomically.  This also lets the caller use different adaptive
582 /// cutoffs for different operations (read versus write, for example).
583 /// To avoid contention, the spin cutoff is only updated when requested
584 /// by the caller.
585 template <template<typename> class Atom>
586 struct TurnSequencer {
587   explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
588       : state_(encode(firstTurn << kTurnShift, 0))
589   {}
590
591   /// Returns true iff a call to waitForTurn(turn, ...) won't block
592   bool isTurn(const uint32_t turn) const noexcept {
593     auto state = state_.load(std::memory_order_acquire);
594     return decodeCurrentSturn(state) == (turn << kTurnShift);
595   }
596
597   // Internally we always work with shifted turn values, which makes the
598   // truncation and wraparound work correctly.  This leaves us bits at
599   // the bottom to store the number of waiters.  We call shifted turns
600   // "sturns" inside this class.
601
602   /// Blocks the current thread until turn has arrived.  If
603   /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
604   /// before blocking and will adjust spinCutoff based on the results,
605   /// otherwise it will spin for at most spinCutoff spins.
606   void waitForTurn(const uint32_t turn,
607                    Atom<int>& spinCutoff,
608                    const bool updateSpinCutoff) noexcept {
609     int prevThresh = spinCutoff.load(std::memory_order_relaxed);
610     const int effectiveSpinCutoff =
611         updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
612     int tries;
613
614     const uint32_t sturn = turn << kTurnShift;
615     for (tries = 0; ; ++tries) {
616       uint32_t state = state_.load(std::memory_order_acquire);
617       uint32_t current_sturn = decodeCurrentSturn(state);
618       if (current_sturn == sturn) {
619         break;
620       }
621
622       // wrap-safe version of assert(current_sturn < sturn)
623       assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
624
625       // the first effectSpinCutoff tries are spins, after that we will
626       // record ourself as a waiter and block with futexWait
627       if (tries < effectiveSpinCutoff) {
628         asm volatile ("pause");
629         continue;
630       }
631
632       uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
633       uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
634       uint32_t new_state;
635       if (our_waiter_delta <= current_max_waiter_delta) {
636         // state already records us as waiters, probably because this
637         // isn't our first time around this loop
638         new_state = state;
639       } else {
640         new_state = encode(current_sturn, our_waiter_delta);
641         if (state != new_state &&
642             !state_.compare_exchange_strong(state, new_state)) {
643           continue;
644         }
645       }
646       state_.futexWait(new_state, futexChannel(turn));
647     }
648
649     if (updateSpinCutoff || prevThresh == 0) {
650       // if we hit kMaxSpins then spinning was pointless, so the right
651       // spinCutoff is kMinSpins
652       int target;
653       if (tries >= kMaxSpins) {
654         target = kMinSpins;
655       } else {
656         // to account for variations, we allow ourself to spin 2*N when
657         // we think that N is actually required in order to succeed
658         target = std::min(int{kMaxSpins}, std::max(int{kMinSpins}, tries * 2));
659       }
660
661       if (prevThresh == 0) {
662         // bootstrap
663         spinCutoff = target;
664       } else {
665         // try once, keep moving if CAS fails.  Exponential moving average
666         // with alpha of 7/8
667         spinCutoff.compare_exchange_weak(
668             prevThresh, prevThresh + (target - prevThresh) / 8);
669       }
670     }
671   }
672
673   /// Unblocks a thread running waitForTurn(turn + 1)
674   void completeTurn(const uint32_t turn) noexcept {
675     uint32_t state = state_.load(std::memory_order_acquire);
676     while (true) {
677       assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
678       uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
679       uint32_t new_state = encode(
680               (turn + 1) << kTurnShift,
681               max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
682       if (state_.compare_exchange_strong(state, new_state)) {
683         if (max_waiter_delta != 0) {
684           state_.futexWake(std::numeric_limits<int>::max(),
685                            futexChannel(turn + 1));
686         }
687         break;
688       }
689       // failing compare_exchange_strong updates first arg to the value
690       // that caused the failure, so no need to reread state_
691     }
692   }
693
694   /// Returns the least-most significant byte of the current uncompleted
695   /// turn.  The full 32 bit turn cannot be recovered.
696   uint8_t uncompletedTurnLSB() const noexcept {
697     return state_.load(std::memory_order_acquire) >> kTurnShift;
698   }
699
700  private:
701   enum : uint32_t {
702     /// kTurnShift counts the bits that are stolen to record the delta
703     /// between the current turn and the maximum waiter. It needs to be big
704     /// enough to record wait deltas of 0 to 32 inclusive.  Waiters more
705     /// than 32 in the future will be woken up 32*n turns early (since
706     /// their BITSET will hit) and will adjust the waiter count again.
707     /// We go a bit beyond and let the waiter count go up to 63, which
708     /// is free and might save us a few CAS
709     kTurnShift = 6,
710     kWaitersMask = (1 << kTurnShift) - 1,
711
712     /// The minimum spin count that we will adaptively select
713     kMinSpins = 20,
714
715     /// The maximum spin count that we will adaptively select, and the
716     /// spin count that will be used when probing to get a new data point
717     /// for the adaptation
718     kMaxSpins = 2000,
719   };
720
721   /// This holds both the current turn, and the highest waiting turn,
722   /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
723   Futex<Atom> state_;
724
725   /// Returns the bitmask to pass futexWait or futexWake when communicating
726   /// about the specified turn
727   int futexChannel(uint32_t turn) const noexcept {
728     return 1 << (turn & 31);
729   }
730
731   uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
732     return state & ~kWaitersMask;
733   }
734
735   uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
736     return state & kWaitersMask;
737   }
738
739   uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
740     return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
741   }
742 };
743
744
745 /// SingleElementQueue implements a blocking queue that holds at most one
746 /// item, and that requires its users to assign incrementing identifiers
747 /// (turns) to each enqueue and dequeue operation.  Note that the turns
748 /// used by SingleElementQueue are doubled inside the TurnSequencer
749 template <typename T, template <typename> class Atom>
750 struct SingleElementQueue {
751
752   ~SingleElementQueue() noexcept {
753     if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
754       // we are pending a dequeue, so we have a constructed item
755       destroyContents();
756     }
757   }
758
759   /// enqueue using in-place noexcept construction
760   template <typename ...Args,
761             typename = typename std::enable_if<
762                 std::is_nothrow_constructible<T,Args...>::value>::type>
763   void enqueue(const uint32_t turn,
764                Atom<int>& spinCutoff,
765                const bool updateSpinCutoff,
766                Args&&... args) noexcept {
767     sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
768     new (contents_) T(std::forward<Args>(args)...);
769     sequencer_.completeTurn(turn * 2);
770   }
771
772   /// enqueue using move construction, either real (if
773   /// is_nothrow_move_constructible) or simulated using relocation and
774   /// default construction (if IsRelocatable and has_nothrow_constructor)
775   template <typename = typename std::enable_if<
776                 (folly::IsRelocatable<T>::value &&
777                  boost::has_nothrow_constructor<T>::value) ||
778                 std::is_nothrow_constructible<T,T&&>::value>::type>
779   void enqueue(const uint32_t turn,
780                Atom<int>& spinCutoff,
781                const bool updateSpinCutoff,
782                T&& goner) noexcept {
783     if (std::is_nothrow_constructible<T,T&&>::value) {
784       // this is preferred
785       sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
786       new (contents_) T(std::move(goner));
787       sequencer_.completeTurn(turn * 2);
788     } else {
789       // simulate nothrow move with relocation, followed by default
790       // construction to fill the gap we created
791       sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
792       memcpy(contents_, &goner, sizeof(T));
793       sequencer_.completeTurn(turn * 2);
794       new (&goner) T();
795     }
796   }
797
798   bool mayEnqueue(const uint32_t turn) const noexcept {
799     return sequencer_.isTurn(turn * 2);
800   }
801
802   void dequeue(uint32_t turn,
803                Atom<int>& spinCutoff,
804                const bool updateSpinCutoff,
805                T& elem) noexcept {
806     if (folly::IsRelocatable<T>::value) {
807       // this version is preferred, because we do as much work as possible
808       // before waiting
809       try {
810         elem.~T();
811       } catch (...) {
812         // unlikely, but if we don't complete our turn the queue will die
813       }
814       sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
815       memcpy(&elem, contents_, sizeof(T));
816       sequencer_.completeTurn(turn * 2 + 1);
817     } else {
818       // use nothrow move assignment
819       sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
820       elem = std::move(*ptr());
821       destroyContents();
822       sequencer_.completeTurn(turn * 2 + 1);
823     }
824   }
825
826   bool mayDequeue(const uint32_t turn) const noexcept {
827     return sequencer_.isTurn(turn * 2 + 1);
828   }
829
830  private:
831   /// Storage for a T constructed with placement new
832   char contents_[sizeof(T)] __attribute__((aligned(alignof(T))));
833
834   /// Even turns are pushes, odd turns are pops
835   TurnSequencer<Atom> sequencer_;
836
837   T* ptr() noexcept {
838     return static_cast<T*>(static_cast<void*>(contents_));
839   }
840
841   void destroyContents() noexcept {
842     try {
843       ptr()->~T();
844     } catch (...) {
845       // g++ doesn't seem to have std::is_nothrow_destructible yet
846     }
847 #ifndef NDEBUG
848     memset(contents_, 'Q', sizeof(T));
849 #endif
850   }
851 };
852
853 } // namespace detail
854
855 } // namespace folly