LockFreeRingBuffer
[folly.git] / folly / detail / TurnSequencer.h
1 /*
2  * Copyright 2015 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 <assert.h>
21 #include <limits>
22 #include <unistd.h>
23
24 #include <folly/detail/Futex.h>
25
26 namespace folly {
27
28 namespace detail {
29
30 /// A TurnSequencer allows threads to order their execution according to
31 /// a monotonically increasing (with wraparound) "turn" value.  The two
32 /// operations provided are to wait for turn T, and to move to the next
33 /// turn.  Every thread that is waiting for T must have arrived before
34 /// that turn is marked completed (for MPMCQueue only one thread waits
35 /// for any particular turn, so this is trivially true).
36 ///
37 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
38 /// left by 6), along with a 6 bit saturating value that records the
39 /// maximum waiter minus the current turn.  Wraparound of the turn space
40 /// is expected and handled.  This allows us to atomically adjust the
41 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
42 /// Compare this strategy to sem_t's separate num_waiters field, which
43 /// isn't decremented until after the waiting thread gets scheduled,
44 /// during which time more enqueues might have occurred and made pointless
45 /// FUTEX_WAKE calls.
46 ///
47 /// TurnSequencer uses futex() directly.  It is optimized for the
48 /// case that the highest awaited turn is 32 or less higher than the
49 /// current turn.  We use the FUTEX_WAIT_BITSET variant, which lets
50 /// us embed 32 separate wakeup channels in a single futex.  See
51 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
52 ///
53 /// We only need to keep exact track of the delta between the current
54 /// turn and the maximum waiter for the 32 turns that follow the current
55 /// one, because waiters at turn t+32 will be awoken at turn t.  At that
56 /// point they can then adjust the delta using the higher base.  Since we
57 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
58 /// We actually store waiter deltas up to 63, since that might reduce
59 /// the number of CAS operations a tiny bit.
60 ///
61 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
62 /// spin cutoff before waiting.  The overheads (and convergence rate)
63 /// of separately tracking the spin cutoff for each TurnSequencer would
64 /// be prohibitive, so the actual storage is passed in as a parameter and
65 /// updated atomically.  This also lets the caller use different adaptive
66 /// cutoffs for different operations (read versus write, for example).
67 /// To avoid contention, the spin cutoff is only updated when requested
68 /// by the caller.
69 template <template<typename> class Atom>
70 struct TurnSequencer {
71   explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
72       : state_(encode(firstTurn << kTurnShift, 0))
73   {}
74
75   /// Returns true iff a call to waitForTurn(turn, ...) won't block
76   bool isTurn(const uint32_t turn) const noexcept {
77     auto state = state_.load(std::memory_order_acquire);
78     return decodeCurrentSturn(state) == (turn << kTurnShift);
79   }
80
81   /// See tryWaitForTurn
82   /// Requires that `turn` is not a turn in the past.
83   void waitForTurn(const uint32_t turn,
84                 Atom<uint32_t>& spinCutoff,
85                 const bool updateSpinCutoff) noexcept {
86     bool success = tryWaitForTurn(turn, spinCutoff, updateSpinCutoff);
87     (void) success;
88     assert(success);
89   }
90
91   // Internally we always work with shifted turn values, which makes the
92   // truncation and wraparound work correctly.  This leaves us bits at
93   // the bottom to store the number of waiters.  We call shifted turns
94   // "sturns" inside this class.
95
96   /// Blocks the current thread until turn has arrived.  If
97   /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
98   /// before blocking and will adjust spinCutoff based on the results,
99   /// otherwise it will spin for at most spinCutoff spins.
100   /// Returns true if the wait succeeded, false if the turn is in the past
101   bool tryWaitForTurn(const uint32_t turn,
102                    Atom<uint32_t>& spinCutoff,
103                    const bool updateSpinCutoff) noexcept {
104     uint32_t prevThresh = spinCutoff.load(std::memory_order_relaxed);
105     const uint32_t effectiveSpinCutoff =
106         updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
107
108     uint32_t tries;
109     const uint32_t sturn = turn << kTurnShift;
110     for (tries = 0; ; ++tries) {
111       uint32_t state = state_.load(std::memory_order_acquire);
112       uint32_t current_sturn = decodeCurrentSturn(state);
113       if (current_sturn == sturn) {
114         break;
115       }
116
117       // wrap-safe version of (current_sturn >= sturn)
118       if(sturn - current_sturn >= std::numeric_limits<uint32_t>::max() / 2) {
119         // turn is in the past
120         return false;
121       }
122
123       // the first effectSpinCutoff tries are spins, after that we will
124       // record ourself as a waiter and block with futexWait
125       if (tries < effectiveSpinCutoff) {
126         asm volatile ("pause");
127         continue;
128       }
129
130       uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
131       uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
132       uint32_t new_state;
133       if (our_waiter_delta <= current_max_waiter_delta) {
134         // state already records us as waiters, probably because this
135         // isn't our first time around this loop
136         new_state = state;
137       } else {
138         new_state = encode(current_sturn, our_waiter_delta);
139         if (state != new_state &&
140             !state_.compare_exchange_strong(state, new_state)) {
141           continue;
142         }
143       }
144       state_.futexWait(new_state, futexChannel(turn));
145     }
146
147     if (updateSpinCutoff || prevThresh == 0) {
148       // if we hit kMaxSpins then spinning was pointless, so the right
149       // spinCutoff is kMinSpins
150       uint32_t target;
151       if (tries >= kMaxSpins) {
152         target = kMinSpins;
153       } else {
154         // to account for variations, we allow ourself to spin 2*N when
155         // we think that N is actually required in order to succeed
156         target = std::min<uint32_t>(kMaxSpins,
157                                     std::max<uint32_t>(kMinSpins, tries * 2));
158       }
159
160       if (prevThresh == 0) {
161         // bootstrap
162         spinCutoff.store(target);
163       } else {
164         // try once, keep moving if CAS fails.  Exponential moving average
165         // with alpha of 7/8
166         // Be careful that the quantity we add to prevThresh is signed.
167         spinCutoff.compare_exchange_weak(
168             prevThresh, prevThresh + int(target - prevThresh) / 8);
169       }
170     }
171
172     return true;
173   }
174
175   /// Unblocks a thread running waitForTurn(turn + 1)
176   void completeTurn(const uint32_t turn) noexcept {
177     uint32_t state = state_.load(std::memory_order_acquire);
178     while (true) {
179       assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
180       uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
181       uint32_t new_state = encode(
182               (turn + 1) << kTurnShift,
183               max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
184       if (state_.compare_exchange_strong(state, new_state)) {
185         if (max_waiter_delta != 0) {
186           state_.futexWake(std::numeric_limits<int>::max(),
187                            futexChannel(turn + 1));
188         }
189         break;
190       }
191       // failing compare_exchange_strong updates first arg to the value
192       // that caused the failure, so no need to reread state_
193     }
194   }
195
196   /// Returns the least-most significant byte of the current uncompleted
197   /// turn.  The full 32 bit turn cannot be recovered.
198   uint8_t uncompletedTurnLSB() const noexcept {
199     return state_.load(std::memory_order_acquire) >> kTurnShift;
200   }
201
202  private:
203   enum : uint32_t {
204     /// kTurnShift counts the bits that are stolen to record the delta
205     /// between the current turn and the maximum waiter. It needs to be big
206     /// enough to record wait deltas of 0 to 32 inclusive.  Waiters more
207     /// than 32 in the future will be woken up 32*n turns early (since
208     /// their BITSET will hit) and will adjust the waiter count again.
209     /// We go a bit beyond and let the waiter count go up to 63, which
210     /// is free and might save us a few CAS
211     kTurnShift = 6,
212     kWaitersMask = (1 << kTurnShift) - 1,
213
214     /// The minimum spin count that we will adaptively select
215     kMinSpins = 20,
216
217     /// The maximum spin count that we will adaptively select, and the
218     /// spin count that will be used when probing to get a new data point
219     /// for the adaptation
220     kMaxSpins = 2000,
221   };
222
223   /// This holds both the current turn, and the highest waiting turn,
224   /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
225   Futex<Atom> state_;
226
227   /// Returns the bitmask to pass futexWait or futexWake when communicating
228   /// about the specified turn
229   int futexChannel(uint32_t turn) const noexcept {
230     return 1 << (turn & 31);
231   }
232
233   uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
234     return state & ~kWaitersMask;
235   }
236
237   uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
238     return state & kWaitersMask;
239   }
240
241   uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
242     return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
243   }
244 };
245
246 } // namespace detail
247 } // namespace folly