aafeaa16879e7950cb10450b86ed0e3d8623d9eb
[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   // Internally we always work with shifted turn values, which makes the
82   // truncation and wraparound work correctly.  This leaves us bits at
83   // the bottom to store the number of waiters.  We call shifted turns
84   // "sturns" inside this class.
85
86   /// Blocks the current thread until turn has arrived.  If
87   /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
88   /// before blocking and will adjust spinCutoff based on the results,
89   /// otherwise it will spin for at most spinCutoff spins.
90   void waitForTurn(const uint32_t turn,
91                    Atom<uint32_t>& spinCutoff,
92                    const bool updateSpinCutoff) noexcept {
93     uint32_t prevThresh = spinCutoff.load(std::memory_order_relaxed);
94     const uint32_t effectiveSpinCutoff =
95         updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
96
97     uint32_t tries;
98     const uint32_t sturn = turn << kTurnShift;
99     for (tries = 0; ; ++tries) {
100       uint32_t state = state_.load(std::memory_order_acquire);
101       uint32_t current_sturn = decodeCurrentSturn(state);
102       if (current_sturn == sturn) {
103         break;
104       }
105
106       // wrap-safe version of assert(current_sturn < sturn)
107       assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
108
109       // the first effectSpinCutoff tries are spins, after that we will
110       // record ourself as a waiter and block with futexWait
111       if (tries < effectiveSpinCutoff) {
112         asm volatile ("pause");
113         continue;
114       }
115
116       uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
117       uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
118       uint32_t new_state;
119       if (our_waiter_delta <= current_max_waiter_delta) {
120         // state already records us as waiters, probably because this
121         // isn't our first time around this loop
122         new_state = state;
123       } else {
124         new_state = encode(current_sturn, our_waiter_delta);
125         if (state != new_state &&
126             !state_.compare_exchange_strong(state, new_state)) {
127           continue;
128         }
129       }
130       state_.futexWait(new_state, futexChannel(turn));
131     }
132
133     if (updateSpinCutoff || prevThresh == 0) {
134       // if we hit kMaxSpins then spinning was pointless, so the right
135       // spinCutoff is kMinSpins
136       uint32_t target;
137       if (tries >= kMaxSpins) {
138         target = kMinSpins;
139       } else {
140         // to account for variations, we allow ourself to spin 2*N when
141         // we think that N is actually required in order to succeed
142         target = std::min<uint32_t>(kMaxSpins,
143                                     std::max<uint32_t>(kMinSpins, tries * 2));
144       }
145
146       if (prevThresh == 0) {
147         // bootstrap
148         spinCutoff.store(target);
149       } else {
150         // try once, keep moving if CAS fails.  Exponential moving average
151         // with alpha of 7/8
152         // Be careful that the quantity we add to prevThresh is signed.
153         spinCutoff.compare_exchange_weak(
154             prevThresh, prevThresh + int(target - prevThresh) / 8);
155       }
156     }
157   }
158
159   /// Unblocks a thread running waitForTurn(turn + 1)
160   void completeTurn(const uint32_t turn) noexcept {
161     uint32_t state = state_.load(std::memory_order_acquire);
162     while (true) {
163       assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
164       uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
165       uint32_t new_state = encode(
166               (turn + 1) << kTurnShift,
167               max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
168       if (state_.compare_exchange_strong(state, new_state)) {
169         if (max_waiter_delta != 0) {
170           state_.futexWake(std::numeric_limits<int>::max(),
171                            futexChannel(turn + 1));
172         }
173         break;
174       }
175       // failing compare_exchange_strong updates first arg to the value
176       // that caused the failure, so no need to reread state_
177     }
178   }
179
180   /// Returns the least-most significant byte of the current uncompleted
181   /// turn.  The full 32 bit turn cannot be recovered.
182   uint8_t uncompletedTurnLSB() const noexcept {
183     return state_.load(std::memory_order_acquire) >> kTurnShift;
184   }
185
186  private:
187   enum : uint32_t {
188     /// kTurnShift counts the bits that are stolen to record the delta
189     /// between the current turn and the maximum waiter. It needs to be big
190     /// enough to record wait deltas of 0 to 32 inclusive.  Waiters more
191     /// than 32 in the future will be woken up 32*n turns early (since
192     /// their BITSET will hit) and will adjust the waiter count again.
193     /// We go a bit beyond and let the waiter count go up to 63, which
194     /// is free and might save us a few CAS
195     kTurnShift = 6,
196     kWaitersMask = (1 << kTurnShift) - 1,
197
198     /// The minimum spin count that we will adaptively select
199     kMinSpins = 20,
200
201     /// The maximum spin count that we will adaptively select, and the
202     /// spin count that will be used when probing to get a new data point
203     /// for the adaptation
204     kMaxSpins = 2000,
205   };
206
207   /// This holds both the current turn, and the highest waiting turn,
208   /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
209   Futex<Atom> state_;
210
211   /// Returns the bitmask to pass futexWait or futexWake when communicating
212   /// about the specified turn
213   int futexChannel(uint32_t turn) const noexcept {
214     return 1 << (turn & 31);
215   }
216
217   uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
218     return state & ~kWaitersMask;
219   }
220
221   uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
222     return state & kWaitersMask;
223   }
224
225   uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
226     return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
227   }
228 };
229
230 } // namespace detail
231 } // namespace folly