folly: attribute-aligned-arg must now be constant (not enum)
[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   static_assert(kFalseSharingRange == 64,
339                 "FOLLY_ON_NEXT_CACHE_LINE must track kFalseSharingRange");
340
341 // This literal "64' should be kFalseSharingRange,
342 // but gcc-4.8.0 and 4.8.1 reject it.
343 // FIXME: s/64/kFalseSharingRange/ if that ever changes.
344 #define FOLLY_ON_NEXT_CACHE_LINE __attribute__((aligned(64)))
345
346   /// The maximum number of items in the queue at once
347   size_t capacity_ FOLLY_ON_NEXT_CACHE_LINE;
348
349   /// An array of capacity_ SingleElementQueue-s, each of which holds
350   /// either 0 or 1 item.  We over-allocate by 2 * kSlotPadding and don't
351   /// touch the slots at either end, to avoid false sharing
352   detail::SingleElementQueue<T,Atom>* slots_;
353
354   /// The number of slots_ indices that we advance for each ticket, to
355   /// avoid false sharing.  Ideally slots_[i] and slots_[i + stride_]
356   /// aren't on the same cache line
357   int stride_;
358
359   /// Enqueuers get tickets from here
360   Atom<uint64_t> pushTicket_ FOLLY_ON_NEXT_CACHE_LINE;
361
362   /// Dequeuers get tickets from here
363   Atom<uint64_t> popTicket_ FOLLY_ON_NEXT_CACHE_LINE;
364
365   /// This is how many times we will spin before using FUTEX_WAIT when
366   /// the queue is full on enqueue, adaptively computed by occasionally
367   /// spinning for longer and smoothing with an exponential moving average
368   Atom<int> pushSpinCutoff_ FOLLY_ON_NEXT_CACHE_LINE;
369
370   /// The adaptive spin cutoff when the queue is empty on dequeue
371   Atom<int> popSpinCutoff_ FOLLY_ON_NEXT_CACHE_LINE;
372
373   /// Alignment doesn't avoid false sharing at the end of the struct,
374   /// so fill out the last cache line
375   char padding_[kFalseSharingRange - sizeof(Atom<int>)];
376
377 #undef FOLLY_ON_NEXT_CACHE_LINE
378
379   /// We assign tickets in increasing order, but we don't want to
380   /// access neighboring elements of slots_ because that will lead to
381   /// false sharing (multiple cores accessing the same cache line even
382   /// though they aren't accessing the same bytes in that cache line).
383   /// To avoid this we advance by stride slots per ticket.
384   ///
385   /// We need gcd(capacity, stride) to be 1 so that we will use all
386   /// of the slots.  We ensure this by only considering prime strides,
387   /// which either have no common divisors with capacity or else have
388   /// a zero remainder after dividing by capacity.  That is sufficient
389   /// to guarantee correctness, but we also want to actually spread the
390   /// accesses away from each other to avoid false sharing (consider a
391   /// stride of 7 with a capacity of 8).  To that end we try a few taking
392   /// care to observe that advancing by -1 is as bad as advancing by 1
393   /// when in comes to false sharing.
394   ///
395   /// The simple way to avoid false sharing would be to pad each
396   /// SingleElementQueue, but since we have capacity_ of them that could
397   /// waste a lot of space.
398   static int computeStride(size_t capacity) noexcept {
399     static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
400
401     int bestStride = 1;
402     size_t bestSep = 1;
403     for (int stride : smallPrimes) {
404       if ((stride % capacity) == 0 || (capacity % stride) == 0) {
405         continue;
406       }
407       size_t sep = stride % capacity;
408       sep = std::min(sep, capacity - sep);
409       if (sep > bestSep) {
410         bestStride = stride;
411         bestSep = sep;
412       }
413     }
414     return bestStride;
415   }
416
417   /// Returns the index into slots_ that should be used when enqueuing or
418   /// dequeuing with the specified ticket
419   size_t idx(uint64_t ticket) noexcept {
420     return ((ticket * stride_) % capacity_) + kSlotPadding;
421   }
422
423   /// Maps an enqueue or dequeue ticket to the turn should be used at the
424   /// corresponding SingleElementQueue
425   uint32_t turn(uint64_t ticket) noexcept {
426     return ticket / capacity_;
427   }
428
429   /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
430   /// won't block.  Returns true on immediate success, false on immediate
431   /// failure.
432   bool tryObtainReadyPushTicket(uint64_t& rv) noexcept {
433     auto ticket = pushTicket_.load(std::memory_order_acquire); // A
434     while (true) {
435       if (!slots_[idx(ticket)].mayEnqueue(turn(ticket))) {
436         // if we call enqueue(ticket, ...) on the SingleElementQueue
437         // right now it would block, but this might no longer be the next
438         // ticket.  We can increase the chance of tryEnqueue success under
439         // contention (without blocking) by rechecking the ticket dispenser
440         auto prev = ticket;
441         ticket = pushTicket_.load(std::memory_order_acquire); // B
442         if (prev == ticket) {
443           // mayEnqueue was bracketed by two reads (A or prev B or prev
444           // failing CAS to B), so we are definitely unable to enqueue
445           return false;
446         }
447       } else {
448         // we will bracket the mayEnqueue check with a read (A or prev B
449         // or prev failing CAS) and the following CAS.  If the CAS fails
450         // it will effect a load of pushTicket_
451         if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
452           rv = ticket;
453           return true;
454         }
455       }
456     }
457   }
458
459   /// Tries to obtain a push ticket which can be satisfied if all
460   /// in-progress pops complete.  This function does not block, but
461   /// blocking may be required when using the returned ticket if some
462   /// other thread's pop is still in progress (ticket has been granted but
463   /// pop has not yet completed).
464   bool tryObtainPromisedPushTicket(uint64_t& rv) noexcept {
465     auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
466     while (true) {
467       auto numPops = popTicket_.load(std::memory_order_acquire); // B
468       // n will be negative if pops are pending
469       int64_t n = numPushes - numPops;
470       if (n >= static_cast<ssize_t>(capacity_)) {
471         // Full, linearize at B.  We don't need to recheck the read we
472         // performed at A, because if numPushes was stale at B then the
473         // real numPushes value is even worse
474         return false;
475       }
476       if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
477         rv = numPushes;
478         return true;
479       }
480     }
481   }
482
483   /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
484   /// won't block.  Returns true on immediate success, false on immediate
485   /// failure.
486   bool tryObtainReadyPopTicket(uint64_t& rv) noexcept {
487     auto ticket = popTicket_.load(std::memory_order_acquire);
488     while (true) {
489       if (!slots_[idx(ticket)].mayDequeue(turn(ticket))) {
490         auto prev = ticket;
491         ticket = popTicket_.load(std::memory_order_acquire);
492         if (prev == ticket) {
493           return false;
494         }
495       } else {
496         if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
497           rv = ticket;
498           return true;
499         }
500       }
501     }
502   }
503
504   /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
505   /// corresponding push ticket has already been handed out, rather than
506   /// returning one whose corresponding push ticket has already been
507   /// completed.  This means that there is a possibility that the caller
508   /// will block when using the ticket, but it allows the user to rely on
509   /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
510   /// will return true.  The "try" part of this is that we won't have
511   /// to block waiting for someone to call enqueue, although we might
512   /// have to block waiting for them to finish executing code inside the
513   /// MPMCQueue itself.
514   bool tryObtainPromisedPopTicket(uint64_t& rv) noexcept {
515     auto numPops = popTicket_.load(std::memory_order_acquire); // A
516     while (true) {
517       auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
518       if (numPops >= numPushes) {
519         // Empty, or empty with pending pops.  Linearize at B.  We don't
520         // need to recheck the read we performed at A, because if numPops
521         // is stale then the fresh value is larger and the >= is still true
522         return false;
523       }
524       if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
525         rv = numPops;
526         return true;
527       }
528     }
529   }
530
531   // Given a ticket, constructs an enqueued item using args
532   template <typename ...Args>
533   void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
534     slots_[idx(ticket)].enqueue(turn(ticket),
535                                 pushSpinCutoff_,
536                                 (ticket % kAdaptationFreq) == 0,
537                                 std::forward<Args>(args)...);
538   }
539
540   // Given a ticket, dequeues the corresponding element
541   void dequeueWithTicket(uint64_t ticket, T& elem) noexcept {
542     slots_[idx(ticket)].dequeue(turn(ticket),
543                                 popSpinCutoff_,
544                                 (ticket % kAdaptationFreq) == 0,
545                                 elem);
546   }
547 };
548
549
550 namespace detail {
551
552 /// A TurnSequencer allows threads to order their execution according to
553 /// a monotonically increasing (with wraparound) "turn" value.  The two
554 /// operations provided are to wait for turn T, and to move to the next
555 /// turn.  Every thread that is waiting for T must have arrived before
556 /// that turn is marked completed (for MPMCQueue only one thread waits
557 /// for any particular turn, so this is trivially true).
558 ///
559 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
560 /// left by 6), along with a 6 bit saturating value that records the
561 /// maximum waiter minus the current turn.  Wraparound of the turn space
562 /// is expected and handled.  This allows us to atomically adjust the
563 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
564 /// Compare this strategy to sem_t's separate num_waiters field, which
565 /// isn't decremented until after the waiting thread gets scheduled,
566 /// during which time more enqueues might have occurred and made pointless
567 /// FUTEX_WAKE calls.
568 ///
569 /// TurnSequencer uses futex() directly.  It is optimized for the
570 /// case that the highest awaited turn is 32 or less higher than the
571 /// current turn.  We use the FUTEX_WAIT_BITSET variant, which lets
572 /// us embed 32 separate wakeup channels in a single futex.  See
573 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
574 ///
575 /// We only need to keep exact track of the delta between the current
576 /// turn and the maximum waiter for the 32 turns that follow the current
577 /// one, because waiters at turn t+32 will be awoken at turn t.  At that
578 /// point they can then adjust the delta using the higher base.  Since we
579 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
580 /// We actually store waiter deltas up to 63, since that might reduce
581 /// the number of CAS operations a tiny bit.
582 ///
583 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
584 /// spin cutoff before waiting.  The overheads (and convergence rate)
585 /// of separately tracking the spin cutoff for each TurnSequencer would
586 /// be prohibitive, so the actual storage is passed in as a parameter and
587 /// updated atomically.  This also lets the caller use different adaptive
588 /// cutoffs for different operations (read versus write, for example).
589 /// To avoid contention, the spin cutoff is only updated when requested
590 /// by the caller.
591 template <template<typename> class Atom>
592 struct TurnSequencer {
593   explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
594       : state_(encode(firstTurn << kTurnShift, 0))
595   {}
596
597   /// Returns true iff a call to waitForTurn(turn, ...) won't block
598   bool isTurn(const uint32_t turn) const noexcept {
599     auto state = state_.load(std::memory_order_acquire);
600     return decodeCurrentSturn(state) == (turn << kTurnShift);
601   }
602
603   // Internally we always work with shifted turn values, which makes the
604   // truncation and wraparound work correctly.  This leaves us bits at
605   // the bottom to store the number of waiters.  We call shifted turns
606   // "sturns" inside this class.
607
608   /// Blocks the current thread until turn has arrived.  If
609   /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
610   /// before blocking and will adjust spinCutoff based on the results,
611   /// otherwise it will spin for at most spinCutoff spins.
612   void waitForTurn(const uint32_t turn,
613                    Atom<int>& spinCutoff,
614                    const bool updateSpinCutoff) noexcept {
615     int prevThresh = spinCutoff.load(std::memory_order_relaxed);
616     const int effectiveSpinCutoff =
617         updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
618     int tries;
619
620     const uint32_t sturn = turn << kTurnShift;
621     for (tries = 0; ; ++tries) {
622       uint32_t state = state_.load(std::memory_order_acquire);
623       uint32_t current_sturn = decodeCurrentSturn(state);
624       if (current_sturn == sturn) {
625         break;
626       }
627
628       // wrap-safe version of assert(current_sturn < sturn)
629       assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
630
631       // the first effectSpinCutoff tries are spins, after that we will
632       // record ourself as a waiter and block with futexWait
633       if (tries < effectiveSpinCutoff) {
634         asm volatile ("pause");
635         continue;
636       }
637
638       uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
639       uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
640       uint32_t new_state;
641       if (our_waiter_delta <= current_max_waiter_delta) {
642         // state already records us as waiters, probably because this
643         // isn't our first time around this loop
644         new_state = state;
645       } else {
646         new_state = encode(current_sturn, our_waiter_delta);
647         if (state != new_state &&
648             !state_.compare_exchange_strong(state, new_state)) {
649           continue;
650         }
651       }
652       state_.futexWait(new_state, futexChannel(turn));
653     }
654
655     if (updateSpinCutoff || prevThresh == 0) {
656       // if we hit kMaxSpins then spinning was pointless, so the right
657       // spinCutoff is kMinSpins
658       int target;
659       if (tries >= kMaxSpins) {
660         target = kMinSpins;
661       } else {
662         // to account for variations, we allow ourself to spin 2*N when
663         // we think that N is actually required in order to succeed
664         target = std::min(int{kMaxSpins}, std::max(int{kMinSpins}, tries * 2));
665       }
666
667       if (prevThresh == 0) {
668         // bootstrap
669         spinCutoff = target;
670       } else {
671         // try once, keep moving if CAS fails.  Exponential moving average
672         // with alpha of 7/8
673         spinCutoff.compare_exchange_weak(
674             prevThresh, prevThresh + (target - prevThresh) / 8);
675       }
676     }
677   }
678
679   /// Unblocks a thread running waitForTurn(turn + 1)
680   void completeTurn(const uint32_t turn) noexcept {
681     uint32_t state = state_.load(std::memory_order_acquire);
682     while (true) {
683       assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
684       uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
685       uint32_t new_state = encode(
686               (turn + 1) << kTurnShift,
687               max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
688       if (state_.compare_exchange_strong(state, new_state)) {
689         if (max_waiter_delta != 0) {
690           state_.futexWake(std::numeric_limits<int>::max(),
691                            futexChannel(turn + 1));
692         }
693         break;
694       }
695       // failing compare_exchange_strong updates first arg to the value
696       // that caused the failure, so no need to reread state_
697     }
698   }
699
700   /// Returns the least-most significant byte of the current uncompleted
701   /// turn.  The full 32 bit turn cannot be recovered.
702   uint8_t uncompletedTurnLSB() const noexcept {
703     return state_.load(std::memory_order_acquire) >> kTurnShift;
704   }
705
706  private:
707   enum : uint32_t {
708     /// kTurnShift counts the bits that are stolen to record the delta
709     /// between the current turn and the maximum waiter. It needs to be big
710     /// enough to record wait deltas of 0 to 32 inclusive.  Waiters more
711     /// than 32 in the future will be woken up 32*n turns early (since
712     /// their BITSET will hit) and will adjust the waiter count again.
713     /// We go a bit beyond and let the waiter count go up to 63, which
714     /// is free and might save us a few CAS
715     kTurnShift = 6,
716     kWaitersMask = (1 << kTurnShift) - 1,
717
718     /// The minimum spin count that we will adaptively select
719     kMinSpins = 20,
720
721     /// The maximum spin count that we will adaptively select, and the
722     /// spin count that will be used when probing to get a new data point
723     /// for the adaptation
724     kMaxSpins = 2000,
725   };
726
727   /// This holds both the current turn, and the highest waiting turn,
728   /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
729   Futex<Atom> state_;
730
731   /// Returns the bitmask to pass futexWait or futexWake when communicating
732   /// about the specified turn
733   int futexChannel(uint32_t turn) const noexcept {
734     return 1 << (turn & 31);
735   }
736
737   uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
738     return state & ~kWaitersMask;
739   }
740
741   uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
742     return state & kWaitersMask;
743   }
744
745   uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
746     return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
747   }
748 };
749
750
751 /// SingleElementQueue implements a blocking queue that holds at most one
752 /// item, and that requires its users to assign incrementing identifiers
753 /// (turns) to each enqueue and dequeue operation.  Note that the turns
754 /// used by SingleElementQueue are doubled inside the TurnSequencer
755 template <typename T, template <typename> class Atom>
756 struct SingleElementQueue {
757
758   ~SingleElementQueue() noexcept {
759     if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
760       // we are pending a dequeue, so we have a constructed item
761       destroyContents();
762     }
763   }
764
765   /// enqueue using in-place noexcept construction
766   template <typename ...Args,
767             typename = typename std::enable_if<
768                 std::is_nothrow_constructible<T,Args...>::value>::type>
769   void enqueue(const uint32_t turn,
770                Atom<int>& spinCutoff,
771                const bool updateSpinCutoff,
772                Args&&... args) noexcept {
773     sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
774     new (contents_) T(std::forward<Args>(args)...);
775     sequencer_.completeTurn(turn * 2);
776   }
777
778   /// enqueue using move construction, either real (if
779   /// is_nothrow_move_constructible) or simulated using relocation and
780   /// default construction (if IsRelocatable and has_nothrow_constructor)
781   template <typename = typename std::enable_if<
782                 (folly::IsRelocatable<T>::value &&
783                  boost::has_nothrow_constructor<T>::value) ||
784                 std::is_nothrow_constructible<T,T&&>::value>::type>
785   void enqueue(const uint32_t turn,
786                Atom<int>& spinCutoff,
787                const bool updateSpinCutoff,
788                T&& goner) noexcept {
789     if (std::is_nothrow_constructible<T,T&&>::value) {
790       // this is preferred
791       sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
792       new (contents_) T(std::move(goner));
793       sequencer_.completeTurn(turn * 2);
794     } else {
795       // simulate nothrow move with relocation, followed by default
796       // construction to fill the gap we created
797       sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
798       memcpy(contents_, &goner, sizeof(T));
799       sequencer_.completeTurn(turn * 2);
800       new (&goner) T();
801     }
802   }
803
804   bool mayEnqueue(const uint32_t turn) const noexcept {
805     return sequencer_.isTurn(turn * 2);
806   }
807
808   void dequeue(uint32_t turn,
809                Atom<int>& spinCutoff,
810                const bool updateSpinCutoff,
811                T& elem) noexcept {
812     if (folly::IsRelocatable<T>::value) {
813       // this version is preferred, because we do as much work as possible
814       // before waiting
815       try {
816         elem.~T();
817       } catch (...) {
818         // unlikely, but if we don't complete our turn the queue will die
819       }
820       sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
821       memcpy(&elem, contents_, sizeof(T));
822       sequencer_.completeTurn(turn * 2 + 1);
823     } else {
824       // use nothrow move assignment
825       sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
826       elem = std::move(*ptr());
827       destroyContents();
828       sequencer_.completeTurn(turn * 2 + 1);
829     }
830   }
831
832   bool mayDequeue(const uint32_t turn) const noexcept {
833     return sequencer_.isTurn(turn * 2 + 1);
834   }
835
836  private:
837   /// Storage for a T constructed with placement new
838   char contents_[sizeof(T)] __attribute__((aligned(alignof(T))));
839
840   /// Even turns are pushes, odd turns are pops
841   TurnSequencer<Atom> sequencer_;
842
843   T* ptr() noexcept {
844     return static_cast<T*>(static_cast<void*>(contents_));
845   }
846
847   void destroyContents() noexcept {
848     try {
849       ptr()->~T();
850     } catch (...) {
851       // g++ doesn't seem to have std::is_nothrow_destructible yet
852     }
853 #ifndef NDEBUG
854     memset(contents_, 'Q', sizeof(T));
855 #endif
856   }
857 };
858
859 } // namespace detail
860
861 } // namespace folly