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