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