2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <boost/noncopyable.hpp>
22 #include <glog/logging.h>
23 #include <semaphore.h>
28 #include <unordered_set>
31 #include <folly/ScopeGuard.h>
32 #include <folly/detail/CacheLocality.h>
33 #include <folly/detail/Futex.h>
38 // This is ugly, but better perf for DeterministicAtomic translates
39 // directly to more states explored and tested
40 #define FOLLY_TEST_DSCHED_VLOG(msg...) \
43 VLOG(2) << std::hex << std::this_thread::get_id() << ": " << msg; \
48 * DeterministicSchedule coordinates the inter-thread communication of a
49 * set of threads under test, so that despite concurrency the execution is
50 * the same every time. It works by stashing a reference to the schedule
51 * in a thread-local variable, then blocking all but one thread at a time.
53 * In order for DeterministicSchedule to work, it needs to intercept
54 * all inter-thread communication. To do this you should use
55 * DeterministicAtomic<T> instead of std::atomic<T>, create threads
56 * using DeterministicSchedule::thread() instead of the std::thread
57 * constructor, DeterministicSchedule::join(thr) instead of thr.join(),
58 * and access semaphores via the helper functions in DeterministicSchedule.
59 * Locks are not yet supported, although they would be easy to add with
60 * the same strategy as the mapping of sem_wait.
62 * The actual schedule is defined by a function from n -> [0,n). At
63 * each step, the function will be given the number of active threads
64 * (n), and it returns the index of the thread that should be run next.
65 * Invocations of the scheduler function will be serialized, but will
66 * occur from multiple threads. A good starting schedule is uniform(0).
68 class DeterministicSchedule : boost::noncopyable {
71 * Arranges for the current thread (and all threads created by
72 * DeterministicSchedule::thread on a thread participating in this
73 * schedule) to participate in a deterministic schedule.
75 explicit DeterministicSchedule(const std::function<int(int)>& scheduler);
77 /** Completes the schedule. */
78 ~DeterministicSchedule();
81 * Returns a scheduling function that randomly chooses one of the
82 * runnable threads at each step, with no history. This implements
83 * a schedule that is equivalent to one in which the steps between
84 * inter-thread communication are random variables following a poisson
87 static std::function<int(int)> uniform(long seed);
90 * Returns a scheduling function that chooses a subset of the active
91 * threads and randomly chooses a member of the subset as the next
92 * runnable thread. The subset is chosen with size n, and the choice
93 * is made every m steps.
95 static std::function<int(int)> uniformSubset(long seed,
99 /** Obtains permission for the current thread to perform inter-thread
101 static void beforeSharedAccess();
103 /** Releases permission for the current thread to perform inter-thread
105 static void afterSharedAccess();
107 /** Launches a thread that will participate in the same deterministic
108 * schedule as the current thread. */
109 template <typename Func, typename... Args>
110 static inline std::thread thread(Func&& func, Args&&... args) {
111 // TODO: maybe future versions of gcc will allow forwarding to thread
112 auto sched = tls_sched;
113 auto sem = sched ? sched->beforeThreadCreate() : nullptr;
114 auto child = std::thread([=](Args... a) {
116 sched->afterThreadCreate(sem);
117 beforeSharedAccess();
118 FOLLY_TEST_DSCHED_VLOG("running");
123 sched->beforeThreadExit();
129 beforeSharedAccess();
130 sched->active_.insert(child.get_id());
131 FOLLY_TEST_DSCHED_VLOG("forked " << std::hex << child.get_id());
137 /** Calls child.join() as part of a deterministic schedule. */
138 static void join(std::thread& child);
140 /** Calls sem_post(sem) as part of a deterministic schedule. */
141 static void post(sem_t* sem);
143 /** Calls sem_trywait(sem) as part of a deterministic schedule, returning
144 * true on success and false on transient failure. */
145 static bool tryWait(sem_t* sem);
147 /** Calls sem_wait(sem) as part of a deterministic schedule. */
148 static void wait(sem_t* sem);
150 /** Used scheduler_ to get a random number b/w [0, n). If tls_sched is
151 * not set-up it falls back to std::rand() */
152 static int getRandNumber(int n);
154 /** Deterministic implemencation of getcpu */
155 static int getcpu(unsigned* cpu, unsigned* node, void* unused);
158 static FOLLY_TLS sem_t* tls_sem;
159 static FOLLY_TLS DeterministicSchedule* tls_sched;
160 static FOLLY_TLS unsigned tls_threadId;
162 std::function<int(int)> scheduler_;
163 std::vector<sem_t*> sems_;
164 std::unordered_set<std::thread::id> active_;
165 unsigned nextThreadId_;
167 sem_t* beforeThreadCreate();
168 void afterThreadCreate(sem_t*);
169 void beforeThreadExit();
173 * DeterministicAtomic<T> is a drop-in replacement std::atomic<T> that
174 * cooperates with DeterministicSchedule.
176 template <typename T>
177 struct DeterministicAtomic {
180 DeterministicAtomic() = default;
181 ~DeterministicAtomic() = default;
182 DeterministicAtomic(DeterministicAtomic<T> const&) = delete;
183 DeterministicAtomic<T>& operator=(DeterministicAtomic<T> const&) = delete;
185 constexpr /* implicit */ DeterministicAtomic(T v) noexcept : data(v) {}
187 bool is_lock_free() const noexcept { return data.is_lock_free(); }
189 bool compare_exchange_strong(
190 T& v0, T v1, std::memory_order mo = std::memory_order_seq_cst) noexcept {
191 DeterministicSchedule::beforeSharedAccess();
193 bool rv = data.compare_exchange_strong(v0, v1, mo);
194 FOLLY_TEST_DSCHED_VLOG(this << ".compare_exchange_strong(" << std::hex
195 << orig << ", " << std::hex << v1 << ") -> "
196 << rv << "," << std::hex << v0);
197 DeterministicSchedule::afterSharedAccess();
201 bool compare_exchange_weak(
202 T& v0, T v1, std::memory_order mo = std::memory_order_seq_cst) noexcept {
203 DeterministicSchedule::beforeSharedAccess();
205 bool rv = data.compare_exchange_weak(v0, v1, mo);
206 FOLLY_TEST_DSCHED_VLOG(this << ".compare_exchange_weak(" << std::hex << orig
207 << ", " << std::hex << v1 << ") -> " << rv
208 << "," << std::hex << v0);
209 DeterministicSchedule::afterSharedAccess();
213 T exchange(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
214 DeterministicSchedule::beforeSharedAccess();
215 T rv = data.exchange(v, mo);
216 FOLLY_TEST_DSCHED_VLOG(this << ".exchange(" << std::hex << v << ") -> "
218 DeterministicSchedule::afterSharedAccess();
222 /* implicit */ operator T() const noexcept {
223 DeterministicSchedule::beforeSharedAccess();
225 FOLLY_TEST_DSCHED_VLOG(this << "() -> " << std::hex << rv);
226 DeterministicSchedule::afterSharedAccess();
230 T load(std::memory_order mo = std::memory_order_seq_cst) const noexcept {
231 DeterministicSchedule::beforeSharedAccess();
232 T rv = data.load(mo);
233 FOLLY_TEST_DSCHED_VLOG(this << ".load() -> " << std::hex << rv);
234 DeterministicSchedule::afterSharedAccess();
238 T operator=(T v) noexcept {
239 DeterministicSchedule::beforeSharedAccess();
241 FOLLY_TEST_DSCHED_VLOG(this << " = " << std::hex << v);
242 DeterministicSchedule::afterSharedAccess();
246 void store(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
247 DeterministicSchedule::beforeSharedAccess();
249 FOLLY_TEST_DSCHED_VLOG(this << ".store(" << std::hex << v << ")");
250 DeterministicSchedule::afterSharedAccess();
253 T operator++() noexcept {
254 DeterministicSchedule::beforeSharedAccess();
256 FOLLY_TEST_DSCHED_VLOG(this << " pre++ -> " << std::hex << rv);
257 DeterministicSchedule::afterSharedAccess();
261 T operator++(int /* postDummy */) noexcept {
262 DeterministicSchedule::beforeSharedAccess();
264 FOLLY_TEST_DSCHED_VLOG(this << " post++ -> " << std::hex << rv);
265 DeterministicSchedule::afterSharedAccess();
269 T operator--() noexcept {
270 DeterministicSchedule::beforeSharedAccess();
272 FOLLY_TEST_DSCHED_VLOG(this << " pre-- -> " << std::hex << rv);
273 DeterministicSchedule::afterSharedAccess();
277 T operator--(int /* postDummy */) noexcept {
278 DeterministicSchedule::beforeSharedAccess();
280 FOLLY_TEST_DSCHED_VLOG(this << " post-- -> " << std::hex << rv);
281 DeterministicSchedule::afterSharedAccess();
285 T operator+=(T v) noexcept {
286 DeterministicSchedule::beforeSharedAccess();
288 FOLLY_TEST_DSCHED_VLOG(this << " += " << std::hex << v << " -> " << std::hex
290 DeterministicSchedule::afterSharedAccess();
295 std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
296 DeterministicSchedule::beforeSharedAccess();
299 FOLLY_TEST_DSCHED_VLOG(this << ".fetch_add(" << std::hex << v << ") -> "
301 DeterministicSchedule::afterSharedAccess();
305 T operator-=(T v) noexcept {
306 DeterministicSchedule::beforeSharedAccess();
308 FOLLY_TEST_DSCHED_VLOG(this << " -= " << std::hex << v << " -> " << std::hex
310 DeterministicSchedule::afterSharedAccess();
315 std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
316 DeterministicSchedule::beforeSharedAccess();
319 FOLLY_TEST_DSCHED_VLOG(this << ".fetch_sub(" << std::hex << v << ") -> "
321 DeterministicSchedule::afterSharedAccess();
325 T operator&=(T v) noexcept {
326 DeterministicSchedule::beforeSharedAccess();
328 FOLLY_TEST_DSCHED_VLOG(this << " &= " << std::hex << v << " -> " << std::hex
330 DeterministicSchedule::afterSharedAccess();
335 std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
336 DeterministicSchedule::beforeSharedAccess();
339 FOLLY_TEST_DSCHED_VLOG(this << ".fetch_and(" << std::hex << v << ") -> "
341 DeterministicSchedule::afterSharedAccess();
345 T operator|=(T v) noexcept {
346 DeterministicSchedule::beforeSharedAccess();
348 FOLLY_TEST_DSCHED_VLOG(this << " |= " << std::hex << v << " -> " << std::hex
350 DeterministicSchedule::afterSharedAccess();
355 std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
356 DeterministicSchedule::beforeSharedAccess();
359 FOLLY_TEST_DSCHED_VLOG(this << ".fetch_or(" << std::hex << v << ") -> "
361 DeterministicSchedule::afterSharedAccess();
365 T operator^=(T v) noexcept {
366 DeterministicSchedule::beforeSharedAccess();
368 FOLLY_TEST_DSCHED_VLOG(this << " ^= " << std::hex << v << " -> " << std::hex
370 DeterministicSchedule::afterSharedAccess();
375 std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
376 DeterministicSchedule::beforeSharedAccess();
379 FOLLY_TEST_DSCHED_VLOG(this << ".fetch_xor(" << std::hex << v << ") -> "
381 DeterministicSchedule::afterSharedAccess();
387 * DeterministicMutex is a drop-in replacement of std::mutex that
388 * cooperates with DeterministicSchedule.
390 struct DeterministicMutex {
393 DeterministicMutex() = default;
394 ~DeterministicMutex() = default;
395 DeterministicMutex(DeterministicMutex const&) = delete;
396 DeterministicMutex& operator=(DeterministicMutex const&) = delete;
399 FOLLY_TEST_DSCHED_VLOG(this << ".lock()");
400 while (!try_lock()) {
401 // Not calling m.lock() in order to avoid deadlock when the
402 // mutex m is held by another thread. The deadlock would be
403 // between the call to m.lock() and the lock holder's wait on
404 // its own tls_sem scheduling semaphore.
409 DeterministicSchedule::beforeSharedAccess();
410 bool rv = m.try_lock();
411 FOLLY_TEST_DSCHED_VLOG(this << ".try_lock() -> " << rv);
412 DeterministicSchedule::afterSharedAccess();
417 FOLLY_TEST_DSCHED_VLOG(this << ".unlock()");
422 } // namespace folly::test
424 /* Specialization declarations */
430 int Futex<test::DeterministicAtomic>::futexWake(int count, uint32_t wakeMask);
433 FutexResult Futex<test::DeterministicAtomic>::futexWaitImpl(
435 std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
436 std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
440 Getcpu::Func AccessSpreader<test::DeterministicAtomic>::pickGetcpuFunc();
442 } // namespace folly::detail