MPMCQueue.h: fix a bug introduced while accommodating -Wsign-compare
[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<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
362
363   /// The adaptive spin cutoff when the queue is empty on dequeue
364   Atom<uint32_t> 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 -
369                 sizeof(Atom<uint32_t>)];
370
371
372   /// We assign tickets in increasing order, but we don't want to
373   /// access neighboring elements of slots_ because that will lead to
374   /// false sharing (multiple cores accessing the same cache line even
375   /// though they aren't accessing the same bytes in that cache line).
376   /// To avoid this we advance by stride slots per ticket.
377   ///
378   /// We need gcd(capacity, stride) to be 1 so that we will use all
379   /// of the slots.  We ensure this by only considering prime strides,
380   /// which either have no common divisors with capacity or else have
381   /// a zero remainder after dividing by capacity.  That is sufficient
382   /// to guarantee correctness, but we also want to actually spread the
383   /// accesses away from each other to avoid false sharing (consider a
384   /// stride of 7 with a capacity of 8).  To that end we try a few taking
385   /// care to observe that advancing by -1 is as bad as advancing by 1
386   /// when in comes to false sharing.
387   ///
388   /// The simple way to avoid false sharing would be to pad each
389   /// SingleElementQueue, but since we have capacity_ of them that could
390   /// waste a lot of space.
391   static int computeStride(size_t capacity) noexcept {
392     static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
393
394     int bestStride = 1;
395     size_t bestSep = 1;
396     for (int stride : smallPrimes) {
397       if ((stride % capacity) == 0 || (capacity % stride) == 0) {
398         continue;
399       }
400       size_t sep = stride % capacity;
401       sep = std::min(sep, capacity - sep);
402       if (sep > bestSep) {
403         bestStride = stride;
404         bestSep = sep;
405       }
406     }
407     return bestStride;
408   }
409
410   /// Returns the index into slots_ that should be used when enqueuing or
411   /// dequeuing with the specified ticket
412   size_t idx(uint64_t ticket) noexcept {
413     return ((ticket * stride_) % capacity_) + kSlotPadding;
414   }
415
416   /// Maps an enqueue or dequeue ticket to the turn should be used at the
417   /// corresponding SingleElementQueue
418   uint32_t turn(uint64_t ticket) noexcept {
419     return ticket / capacity_;
420   }
421
422   /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
423   /// won't block.  Returns true on immediate success, false on immediate
424   /// failure.
425   bool tryObtainReadyPushTicket(uint64_t& rv) noexcept {
426     auto ticket = pushTicket_.load(std::memory_order_acquire); // A
427     while (true) {
428       if (!slots_[idx(ticket)].mayEnqueue(turn(ticket))) {
429         // if we call enqueue(ticket, ...) on the SingleElementQueue
430         // right now it would block, but this might no longer be the next
431         // ticket.  We can increase the chance of tryEnqueue success under
432         // contention (without blocking) by rechecking the ticket dispenser
433         auto prev = ticket;
434         ticket = pushTicket_.load(std::memory_order_acquire); // B
435         if (prev == ticket) {
436           // mayEnqueue was bracketed by two reads (A or prev B or prev
437           // failing CAS to B), so we are definitely unable to enqueue
438           return false;
439         }
440       } else {
441         // we will bracket the mayEnqueue check with a read (A or prev B
442         // or prev failing CAS) and the following CAS.  If the CAS fails
443         // it will effect a load of pushTicket_
444         if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
445           rv = ticket;
446           return true;
447         }
448       }
449     }
450   }
451
452   /// Tries to obtain a push ticket which can be satisfied if all
453   /// in-progress pops complete.  This function does not block, but
454   /// blocking may be required when using the returned ticket if some
455   /// other thread's pop is still in progress (ticket has been granted but
456   /// pop has not yet completed).
457   bool tryObtainPromisedPushTicket(uint64_t& rv) noexcept {
458     auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
459     while (true) {
460       auto numPops = popTicket_.load(std::memory_order_acquire); // B
461       // n will be negative if pops are pending
462       int64_t n = numPushes - numPops;
463       if (n >= static_cast<ssize_t>(capacity_)) {
464         // Full, linearize at B.  We don't need to recheck the read we
465         // performed at A, because if numPushes was stale at B then the
466         // real numPushes value is even worse
467         return false;
468       }
469       if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
470         rv = numPushes;
471         return true;
472       }
473     }
474   }
475
476   /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
477   /// won't block.  Returns true on immediate success, false on immediate
478   /// failure.
479   bool tryObtainReadyPopTicket(uint64_t& rv) noexcept {
480     auto ticket = popTicket_.load(std::memory_order_acquire);
481     while (true) {
482       if (!slots_[idx(ticket)].mayDequeue(turn(ticket))) {
483         auto prev = ticket;
484         ticket = popTicket_.load(std::memory_order_acquire);
485         if (prev == ticket) {
486           return false;
487         }
488       } else {
489         if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
490           rv = ticket;
491           return true;
492         }
493       }
494     }
495   }
496
497   /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
498   /// corresponding push ticket has already been handed out, rather than
499   /// returning one whose corresponding push ticket has already been
500   /// completed.  This means that there is a possibility that the caller
501   /// will block when using the ticket, but it allows the user to rely on
502   /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
503   /// will return true.  The "try" part of this is that we won't have
504   /// to block waiting for someone to call enqueue, although we might
505   /// have to block waiting for them to finish executing code inside the
506   /// MPMCQueue itself.
507   bool tryObtainPromisedPopTicket(uint64_t& rv) noexcept {
508     auto numPops = popTicket_.load(std::memory_order_acquire); // A
509     while (true) {
510       auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
511       if (numPops >= numPushes) {
512         // Empty, or empty with pending pops.  Linearize at B.  We don't
513         // need to recheck the read we performed at A, because if numPops
514         // is stale then the fresh value is larger and the >= is still true
515         return false;
516       }
517       if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
518         rv = numPops;
519         return true;
520       }
521     }
522   }
523
524   // Given a ticket, constructs an enqueued item using args
525   template <typename ...Args>
526   void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
527     slots_[idx(ticket)].enqueue(turn(ticket),
528                                 pushSpinCutoff_,
529                                 (ticket % kAdaptationFreq) == 0,
530                                 std::forward<Args>(args)...);
531   }
532
533   // Given a ticket, dequeues the corresponding element
534   void dequeueWithTicket(uint64_t ticket, T& elem) noexcept {
535     slots_[idx(ticket)].dequeue(turn(ticket),
536                                 popSpinCutoff_,
537                                 (ticket % kAdaptationFreq) == 0,
538                                 elem);
539   }
540 };
541
542
543 namespace detail {
544
545 /// A TurnSequencer allows threads to order their execution according to
546 /// a monotonically increasing (with wraparound) "turn" value.  The two
547 /// operations provided are to wait for turn T, and to move to the next
548 /// turn.  Every thread that is waiting for T must have arrived before
549 /// that turn is marked completed (for MPMCQueue only one thread waits
550 /// for any particular turn, so this is trivially true).
551 ///
552 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
553 /// left by 6), along with a 6 bit saturating value that records the
554 /// maximum waiter minus the current turn.  Wraparound of the turn space
555 /// is expected and handled.  This allows us to atomically adjust the
556 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
557 /// Compare this strategy to sem_t's separate num_waiters field, which
558 /// isn't decremented until after the waiting thread gets scheduled,
559 /// during which time more enqueues might have occurred and made pointless
560 /// FUTEX_WAKE calls.
561 ///
562 /// TurnSequencer uses futex() directly.  It is optimized for the
563 /// case that the highest awaited turn is 32 or less higher than the
564 /// current turn.  We use the FUTEX_WAIT_BITSET variant, which lets
565 /// us embed 32 separate wakeup channels in a single futex.  See
566 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
567 ///
568 /// We only need to keep exact track of the delta between the current
569 /// turn and the maximum waiter for the 32 turns that follow the current
570 /// one, because waiters at turn t+32 will be awoken at turn t.  At that
571 /// point they can then adjust the delta using the higher base.  Since we
572 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
573 /// We actually store waiter deltas up to 63, since that might reduce
574 /// the number of CAS operations a tiny bit.
575 ///
576 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
577 /// spin cutoff before waiting.  The overheads (and convergence rate)
578 /// of separately tracking the spin cutoff for each TurnSequencer would
579 /// be prohibitive, so the actual storage is passed in as a parameter and
580 /// updated atomically.  This also lets the caller use different adaptive
581 /// cutoffs for different operations (read versus write, for example).
582 /// To avoid contention, the spin cutoff is only updated when requested
583 /// by the caller.
584 template <template<typename> class Atom>
585 struct TurnSequencer {
586   explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
587       : state_(encode(firstTurn << kTurnShift, 0))
588   {}
589
590   /// Returns true iff a call to waitForTurn(turn, ...) won't block
591   bool isTurn(const uint32_t turn) const noexcept {
592     auto state = state_.load(std::memory_order_acquire);
593     return decodeCurrentSturn(state) == (turn << kTurnShift);
594   }
595
596   // Internally we always work with shifted turn values, which makes the
597   // truncation and wraparound work correctly.  This leaves us bits at
598   // the bottom to store the number of waiters.  We call shifted turns
599   // "sturns" inside this class.
600
601   /// Blocks the current thread until turn has arrived.  If
602   /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
603   /// before blocking and will adjust spinCutoff based on the results,
604   /// otherwise it will spin for at most spinCutoff spins.
605   void waitForTurn(const uint32_t turn,
606                    Atom<uint32_t>& spinCutoff,
607                    const bool updateSpinCutoff) noexcept {
608     uint32_t prevThresh = spinCutoff.load(std::memory_order_relaxed);
609     const uint32_t effectiveSpinCutoff =
610         updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
611
612     uint32_t tries;
613     const uint32_t sturn = turn << kTurnShift;
614     for (tries = 0; ; ++tries) {
615       uint32_t state = state_.load(std::memory_order_acquire);
616       uint32_t current_sturn = decodeCurrentSturn(state);
617       if (current_sturn == sturn) {
618         break;
619       }
620
621       // wrap-safe version of assert(current_sturn < sturn)
622       assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
623
624       // the first effectSpinCutoff tries are spins, after that we will
625       // record ourself as a waiter and block with futexWait
626       if (tries < effectiveSpinCutoff) {
627         asm volatile ("pause");
628         continue;
629       }
630
631       uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
632       uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
633       uint32_t new_state;
634       if (our_waiter_delta <= current_max_waiter_delta) {
635         // state already records us as waiters, probably because this
636         // isn't our first time around this loop
637         new_state = state;
638       } else {
639         new_state = encode(current_sturn, our_waiter_delta);
640         if (state != new_state &&
641             !state_.compare_exchange_strong(state, new_state)) {
642           continue;
643         }
644       }
645       state_.futexWait(new_state, futexChannel(turn));
646     }
647
648     if (updateSpinCutoff || prevThresh == 0) {
649       // if we hit kMaxSpins then spinning was pointless, so the right
650       // spinCutoff is kMinSpins
651       uint32_t target;
652       if (tries >= kMaxSpins) {
653         target = kMinSpins;
654       } else {
655         // to account for variations, we allow ourself to spin 2*N when
656         // we think that N is actually required in order to succeed
657         target = std::min<uint32_t>(kMaxSpins,
658                                     std::max<uint32_t>(kMinSpins, tries * 2));
659       }
660
661       if (prevThresh == 0) {
662         // bootstrap
663         spinCutoff.store(target);
664       } else {
665         // try once, keep moving if CAS fails.  Exponential moving average
666         // with alpha of 7/8
667         // Be careful that the quantity we add to prevThresh is signed.
668         spinCutoff.compare_exchange_weak(
669             prevThresh, prevThresh + int(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<uint32_t>& 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<uint32_t>& 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<uint32_t>& 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