c14e57f32081210e87b09b5bc3e65f47752ae5e9
[folly.git] / folly / Baton.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 #ifndef FOLLY_BATON_H
18 #define FOLLY_BATON_H
19
20 #include <stdint.h>
21 #include <atomic>
22 #include <errno.h>
23 #include <assert.h>
24
25 #include <folly/detail/Futex.h>
26 #include <folly/detail/MemoryIdler.h>
27 #include <folly/portability/Asm.h>
28
29 namespace folly {
30
31 /// A Baton allows a thread to block once and be awoken: it captures
32 /// a single handoff.  During its lifecycle (from construction/reset to
33 /// destruction/reset) a baton must either be post()ed and wait()ed exactly
34 /// once each, or not at all.
35 ///
36 /// Baton includes no internal padding, and is only 4 bytes in size.
37 /// Any alignment or padding to avoid false sharing is up to the user.
38 ///
39 /// This is basically a stripped-down semaphore that supports only a
40 /// single call to sem_post and a single call to sem_wait.  The current
41 /// posix semaphore sem_t isn't too bad, but this provides more a bit more
42 /// speed, inlining, smaller size, a guarantee that the implementation
43 /// won't change, and compatibility with DeterministicSchedule.  By having
44 /// a much more restrictive lifecycle we can also add a bunch of assertions
45 /// that can help to catch race conditions ahead of time.
46 template <template<typename> class Atom = std::atomic>
47 struct Baton {
48   constexpr Baton() : state_(INIT) {}
49
50   Baton(Baton const&) = delete;
51   Baton& operator=(Baton const&) = delete;
52
53   /// It is an error to destroy a Baton on which a thread is currently
54   /// wait()ing.  In practice this means that the waiter usually takes
55   /// responsibility for destroying the Baton.
56   ~Baton() {
57     // The docblock for this function says that it can't be called when
58     // there is a concurrent waiter.  We assume a strong version of this
59     // requirement in which the caller must _know_ that this is true, they
60     // are not allowed to be merely lucky.  If two threads are involved,
61     // the destroying thread must actually have synchronized with the
62     // waiting thread after wait() returned.  To convey causality the the
63     // waiting thread must have used release semantics and the destroying
64     // thread must have used acquire semantics for that communication,
65     // so we are guaranteed to see the post-wait() value of state_,
66     // which cannot be WAITING.
67     //
68     // Note that since we only care about a single memory location,
69     // the only two plausible memory orders here are relaxed and seq_cst.
70     assert(state_.load(std::memory_order_relaxed) != WAITING);
71   }
72
73   /// Equivalent to destroying the Baton and creating a new one.  It is
74   /// a bug to call this while there is a waiting thread, so in practice
75   /// the waiter will be the one that resets the baton.
76   void reset() {
77     // See ~Baton for a discussion about why relaxed is okay here
78     assert(state_.load(std::memory_order_relaxed) != WAITING);
79
80     // We use a similar argument to justify the use of a relaxed store
81     // here.  Since both wait() and post() are required to be called
82     // only once per lifetime, no thread can actually call those methods
83     // correctly after a reset() unless it synchronizes with the thread
84     // that performed the reset().  If a post() or wait() on another thread
85     // didn't synchronize, then regardless of what operation we performed
86     // here there would be a race on proper use of the Baton's spec
87     // (although not on any particular load and store).  Put another way,
88     // we don't need to synchronize here because anybody that might rely
89     // on such synchronization is required by the baton rules to perform
90     // an additional synchronization that has the desired effect anyway.
91     //
92     // There is actually a similar argument to be made about the
93     // constructor, in which the fenceless constructor initialization
94     // of state_ is piggybacked on whatever synchronization mechanism
95     // distributes knowledge of the Baton's existence
96     state_.store(INIT, std::memory_order_relaxed);
97   }
98
99   /// Causes wait() to wake up.  For each lifetime of a Baton (where a
100   /// lifetime starts at construction or reset() and ends at destruction
101   /// or reset()) there can be at most one call to post().  Any thread
102   /// may call post().
103   ///
104   /// Although we could implement a more generic semaphore semantics
105   /// without any extra size or CPU overhead, the single-call limitation
106   /// allows us to have better assert-ions during debug builds.
107   void post() {
108     uint32_t before = state_.load(std::memory_order_acquire);
109
110     assert(before == INIT || before == WAITING || before == TIMED_OUT);
111
112     if (before == INIT &&
113         state_.compare_exchange_strong(before, EARLY_DELIVERY)) {
114       return;
115     }
116
117     assert(before == WAITING || before == TIMED_OUT);
118
119     if (before == TIMED_OUT) {
120       return;
121     }
122
123     assert(before == WAITING);
124     state_.store(LATE_DELIVERY, std::memory_order_release);
125     state_.futexWake(1);
126   }
127
128   /// Waits until post() has been called in the current Baton lifetime.
129   /// May be called at most once during a Baton lifetime (construction
130   /// |reset until destruction|reset).  If post is called before wait in
131   /// the current lifetime then this method returns immediately.
132   ///
133   /// The restriction that there can be at most one wait() per lifetime
134   /// could be relaxed somewhat without any perf or size regressions,
135   /// but by making this condition very restrictive we can provide better
136   /// checking in debug builds.
137   void wait() {
138     if (spinWaitForEarlyDelivery()) {
139       assert(state_.load(std::memory_order_acquire) == EARLY_DELIVERY);
140       return;
141     }
142
143     // guess we have to block :(
144     uint32_t expected = INIT;
145     if (!state_.compare_exchange_strong(expected, WAITING)) {
146       // CAS failed, last minute reprieve
147       assert(expected == EARLY_DELIVERY);
148       return;
149     }
150
151     while (true) {
152       detail::MemoryIdler::futexWait(state_, WAITING);
153
154       // state_ is the truth even if FUTEX_WAIT reported a matching
155       // FUTEX_WAKE, since we aren't using type-stable storage and we
156       // don't guarantee reuse.  The scenario goes like this: thread
157       // A's last touch of a Baton is a call to wake(), which stores
158       // LATE_DELIVERY and gets an unlucky context switch before delivering
159       // the corresponding futexWake.  Thread B sees LATE_DELIVERY
160       // without consuming a futex event, because it calls futexWait
161       // with an expected value of WAITING and hence doesn't go to sleep.
162       // B returns, so the Baton's memory is reused and becomes another
163       // Baton (or a reuse of this one).  B calls futexWait on the new
164       // Baton lifetime, then A wakes up and delivers a spurious futexWake
165       // to the same memory location.  B's futexWait will then report a
166       // consumed wake event even though state_ is still WAITING.
167       //
168       // It would be possible to add an extra state_ dance to communicate
169       // that the futexWake has been sent so that we can be sure to consume
170       // it before returning, but that would be a perf and complexity hit.
171       uint32_t s = state_.load(std::memory_order_acquire);
172       assert(s == WAITING || s == LATE_DELIVERY);
173
174       if (s == LATE_DELIVERY) {
175         return;
176       }
177       // retry
178     }
179   }
180
181   /// Similar to wait, but with a timeout. The thread is unblocked if the
182   /// timeout expires.
183   /// Note: Only a single call to timed_wait/wait is allowed during a baton's
184   /// life-cycle (from construction/reset to destruction/reset). In other
185   /// words, after timed_wait the caller can't invoke wait/timed_wait/try_wait
186   /// again on the same baton without resetting it.
187   ///
188   /// @param  deadline      Time until which the thread can block
189   /// @return               true if the baton was posted to before timeout,
190   ///                       false otherwise
191   template <typename Clock, typename Duration = typename Clock::duration>
192   bool timed_wait(const std::chrono::time_point<Clock,Duration>& deadline) {
193     if (spinWaitForEarlyDelivery()) {
194       assert(state_.load(std::memory_order_acquire) == EARLY_DELIVERY);
195       return true;
196     }
197
198     // guess we have to block :(
199     uint32_t expected = INIT;
200     if (!state_.compare_exchange_strong(expected, WAITING)) {
201       // CAS failed, last minute reprieve
202       assert(expected == EARLY_DELIVERY);
203       return true;
204     }
205
206     while (true) {
207       auto rv = state_.futexWaitUntil(WAITING, deadline);
208       if (rv == folly::detail::FutexResult::TIMEDOUT) {
209         state_.store(TIMED_OUT, std::memory_order_release);
210         return false;
211       }
212
213       uint32_t s = state_.load(std::memory_order_acquire);
214       assert(s == WAITING || s == LATE_DELIVERY);
215       if (s == LATE_DELIVERY) {
216         return true;
217       }
218     }
219   }
220
221   /// Similar to timed_wait, but with a duration.
222   template <typename Clock = std::chrono::steady_clock, typename Duration>
223   bool timed_wait(const Duration& duration) {
224     auto deadline = Clock::now() + duration;
225     return timed_wait(deadline);
226   }
227
228   /// Similar to wait, but doesn't block the thread if it hasn't been posted.
229   ///
230   /// try_wait has the following semantics:
231   /// - It is ok to call try_wait any number times on the same baton until
232   ///   try_wait reports that the baton has been posted.
233   /// - It is ok to call timed_wait or wait on the same baton if try_wait
234   ///   reports that baton hasn't been posted.
235   /// - If try_wait indicates that the baton has been posted, it is invalid to
236   ///   call wait, try_wait or timed_wait on the same baton without resetting
237   ///
238   /// @return       true if baton has been posted, false othewise
239   bool try_wait() {
240     auto s = state_.load(std::memory_order_acquire);
241     assert(s == INIT || s == EARLY_DELIVERY);
242     return s == EARLY_DELIVERY;
243   }
244
245  private:
246   enum State : uint32_t {
247     INIT = 0,
248     EARLY_DELIVERY = 1,
249     WAITING = 2,
250     LATE_DELIVERY = 3,
251     TIMED_OUT = 4
252   };
253
254   enum {
255     // Must be positive.  If multiple threads are actively using a
256     // higher-level data structure that uses batons internally, it is
257     // likely that the post() and wait() calls happen almost at the same
258     // time.  In this state, we lose big 50% of the time if the wait goes
259     // to sleep immediately.  On circa-2013 devbox hardware it costs about
260     // 7 usec to FUTEX_WAIT and then be awoken (half the t/iter as the
261     // posix_sem_pingpong test in BatonTests).  We can improve our chances
262     // of EARLY_DELIVERY by spinning for a bit, although we have to balance
263     // this against the loss if we end up sleeping any way.  Spins on this
264     // hw take about 7 nanos (all but 0.5 nanos is the pause instruction).
265     // We give ourself 300 spins, which is about 2 usec of waiting.  As a
266     // partial consolation, since we are using the pause instruction we
267     // are giving a speed boost to the colocated hyperthread.
268     PreBlockAttempts = 300,
269   };
270
271   // Spin for "some time" (see discussion on PreBlockAttempts) waiting
272   // for a post.
273   //
274   // @return       true if we received an early delivery during the wait,
275   //               false otherwise. If the function returns true then
276   //               state_ is guaranteed to be EARLY_DELIVERY
277   bool spinWaitForEarlyDelivery() {
278
279     static_assert(PreBlockAttempts > 0,
280         "isn't this assert clearer than an uninitialized variable warning?");
281     for (int i = 0; i < PreBlockAttempts; ++i) {
282       if (try_wait()) {
283         // hooray!
284         return true;
285       }
286       // The pause instruction is the polite way to spin, but it doesn't
287       // actually affect correctness to omit it if we don't have it.
288       // Pausing donates the full capabilities of the current core to
289       // its other hyperthreads for a dozen cycles or so
290       asm_volatile_pause();
291     }
292
293     return false;
294   }
295
296   detail::Futex<Atom> state_;
297 };
298
299 } // namespace folly
300
301 #endif