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