cautionary comment in futexWake
[folly.git] / folly / detail / Futex.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 <atomic>
20 #include <chrono>
21 #include <limits>
22 #include <assert.h>
23 #include <unistd.h>
24 #include <boost/noncopyable.hpp>
25
26 namespace folly { namespace detail {
27
28 enum class FutexResult {
29   VALUE_CHANGED, /* Futex value didn't match expected */
30   AWOKEN,        /* futex wait matched with a futex wake */
31   INTERRUPTED,   /* Spurious wake-up or signal caused futex wait failure */
32   TIMEDOUT
33 };
34
35 /**
36  * Futex is an atomic 32 bit unsigned integer that provides access to the
37  * futex() syscall on that value.  It is templated in such a way that it
38  * can interact properly with DeterministicSchedule testing.
39  *
40  * If you don't know how to use futex(), you probably shouldn't be using
41  * this class.  Even if you do know how, you should have a good reason
42  * (and benchmarks to back you up).
43  */
44 template <template <typename> class Atom = std::atomic>
45 struct Futex : Atom<uint32_t>, boost::noncopyable {
46
47   explicit Futex(uint32_t init = 0) : Atom<uint32_t>(init) {}
48
49   /** Puts the thread to sleep if this->load() == expected.  Returns true when
50    *  it is returning because it has consumed a wake() event, false for any
51    *  other return (signal, this->load() != expected, or spurious wakeup). */
52   bool futexWait(uint32_t expected, uint32_t waitMask = -1) {
53     auto rv = futexWaitImpl(expected, nullptr, nullptr, waitMask);
54     assert(rv != FutexResult::TIMEDOUT);
55     return rv == FutexResult::AWOKEN;
56   }
57
58   /** Similar to futexWait but also accepts a timeout that gives the time until
59    *  when the call can block (time is the absolute time i.e time since epoch).
60    *  Allowed clock types: std::chrono::system_clock, std::chrono::steady_clock.
61    *  Returns one of FutexResult values.
62    *
63    *  NOTE: On some systems steady_clock is just an alias for system_clock,
64    *  and is not actually steady.*/
65   template <class Clock, class Duration = typename Clock::duration>
66   FutexResult futexWaitUntil(
67           uint32_t expected,
68           const std::chrono::time_point<Clock, Duration>& absTime,
69           uint32_t waitMask = -1) {
70     using std::chrono::duration_cast;
71     using std::chrono::nanoseconds;
72     using std::chrono::seconds;
73     using std::chrono::steady_clock;
74     using std::chrono::system_clock;
75     using std::chrono::time_point;
76
77     static_assert(
78         (std::is_same<Clock, system_clock>::value ||
79          std::is_same<Clock, steady_clock>::value),
80         "futexWaitUntil only knows std::chrono::{system_clock,steady_clock}");
81     assert((std::is_same<Clock, system_clock>::value) || Clock::is_steady);
82
83     // We launder the clock type via a std::chrono::duration so that we
84     // can compile both the true and false branch.  Tricky case is when
85     // steady_clock has a higher precision than system_clock (Xcode 6,
86     // for example), for which time_point<system_clock> construction
87     // refuses to do an implicit duration conversion.  (duration is
88     // happy to implicitly convert its denominator causing overflow, but
89     // refuses conversion that might cause truncation.)  We use explicit
90     // duration_cast to work around this.  Truncation does not actually
91     // occur (unless Duration != Clock::duration) because the missing
92     // implicit conversion is in the untaken branch.
93     Duration absTimeDuration = absTime.time_since_epoch();
94     if (std::is_same<Clock, system_clock>::value) {
95       time_point<system_clock> absSystemTime(
96           duration_cast<system_clock::duration>(absTimeDuration));
97       return futexWaitImpl(expected, &absSystemTime, nullptr, waitMask);
98     } else {
99       time_point<steady_clock> absSteadyTime(
100           duration_cast<steady_clock::duration>(absTimeDuration));
101       return futexWaitImpl(expected, nullptr, &absSteadyTime, waitMask);
102     }
103   }
104
105   /** Wakens up to count waiters where (waitMask & wakeMask) !=
106    *  0, returning the number of awoken threads, or -1 if an error
107    *  occurred.  Note that when constructing a concurrency primitive
108    *  that can guard its own destruction, it is likely that you will
109    *  want to ignore EINVAL here (as well as making sure that you
110    *  never touch the object after performing the memory store that
111    *  is the linearization point for unlock or control handoff).
112    *  See https://sourceware.org/bugzilla/show_bug.cgi?id=13690 */
113   int futexWake(int count = std::numeric_limits<int>::max(),
114                 uint32_t wakeMask = -1);
115
116  private:
117
118   /** Underlying implementation of futexWait and futexWaitUntil.
119    *  At most one of absSystemTime and absSteadyTime should be non-null.
120    *  Timeouts are separated into separate parameters to allow the
121    *  implementations to be elsewhere without templating on the clock
122    *  type, which is otherwise complicated by the fact that steady_clock
123    *  is the same as system_clock on some platforms. */
124   FutexResult futexWaitImpl(
125       uint32_t expected,
126       std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
127       std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
128       uint32_t waitMask);
129 };
130
131 /** A std::atomic subclass that can be used to force Futex to emulate
132  *  the underlying futex() syscall.  This is primarily useful to test or
133  *  benchmark the emulated implementation on systems that don't need it. */
134 template <typename T>
135 struct EmulatedFutexAtomic : public std::atomic<T> {
136   EmulatedFutexAtomic() noexcept = default;
137   constexpr /* implicit */ EmulatedFutexAtomic(T init) noexcept
138       : std::atomic<T>(init) {}
139   EmulatedFutexAtomic(const EmulatedFutexAtomic& rhs) = delete;
140 };
141
142 /* Available specializations, with definitions elsewhere */
143
144 template<>
145 int Futex<std::atomic>::futexWake(int count, uint32_t wakeMask);
146
147 template<>
148 FutexResult Futex<std::atomic>::futexWaitImpl(
149       uint32_t expected,
150       std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
151       std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
152       uint32_t waitMask);
153
154 template<>
155 int Futex<EmulatedFutexAtomic>::futexWake(int count, uint32_t wakeMask);
156
157 template<>
158 FutexResult Futex<EmulatedFutexAtomic>::futexWaitImpl(
159       uint32_t expected,
160       std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
161       std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
162       uint32_t waitMask);
163
164 }}