1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // A bunch of threads repeatedly hash an array of ints protected by a
16 // spinlock. If the spinlock is working properly, all elements of the
17 // array should be equal at the end of the test.
18
19 #include <cstdint>
20 #include <limits>
21 #include <random>
22 #include <thread> // NOLINT(build/c++11)
23 #include <type_traits>
24 #include <vector>
25
26 #include "gtest/gtest.h"
27 #include "absl/base/attributes.h"
28 #include "absl/base/config.h"
29 #include "absl/base/internal/low_level_scheduling.h"
30 #include "absl/base/internal/scheduling_mode.h"
31 #include "absl/base/internal/spinlock.h"
32 #include "absl/base/internal/sysinfo.h"
33 #include "absl/base/macros.h"
34 #include "absl/synchronization/blocking_counter.h"
35 #include "absl/synchronization/notification.h"
36
37 constexpr int32_t kNumThreads = 10;
38 constexpr int32_t kIters = 1000;
39
40 namespace absl {
41 ABSL_NAMESPACE_BEGIN
42 namespace base_internal {
43
44 // This is defined outside of anonymous namespace so that it can be
45 // a friend of SpinLock to access protected methods for testing.
46 struct SpinLockTest {
EncodeWaitCyclesabsl::base_internal::SpinLockTest47 static uint32_t EncodeWaitCycles(int64_t wait_start_time,
48 int64_t wait_end_time) {
49 return SpinLock::EncodeWaitCycles(wait_start_time, wait_end_time);
50 }
DecodeWaitCyclesabsl::base_internal::SpinLockTest51 static uint64_t DecodeWaitCycles(uint32_t lock_value) {
52 return SpinLock::DecodeWaitCycles(lock_value);
53 }
54 };
55
56 namespace {
57
58 static constexpr int kArrayLength = 10;
59 static uint32_t values[kArrayLength];
60
61 ABSL_CONST_INIT static SpinLock static_cooperative_spinlock(
62 absl::kConstInit, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
63 ABSL_CONST_INIT static SpinLock static_noncooperative_spinlock(
64 absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
65
66 // Simple integer hash function based on the public domain lookup2 hash.
67 // http://burtleburtle.net/bob/c/lookup2.c
Hash32(uint32_t a,uint32_t c)68 static uint32_t Hash32(uint32_t a, uint32_t c) {
69 uint32_t b = 0x9e3779b9UL; // The golden ratio; an arbitrary value.
70 a -= b; a -= c; a ^= (c >> 13);
71 b -= c; b -= a; b ^= (a << 8);
72 c -= a; c -= b; c ^= (b >> 13);
73 a -= b; a -= c; a ^= (c >> 12);
74 b -= c; b -= a; b ^= (a << 16);
75 c -= a; c -= b; c ^= (b >> 5);
76 a -= b; a -= c; a ^= (c >> 3);
77 b -= c; b -= a; b ^= (a << 10);
78 c -= a; c -= b; c ^= (b >> 15);
79 return c;
80 }
81
TestFunction(int thread_salt,SpinLock * spinlock)82 static void TestFunction(int thread_salt, SpinLock* spinlock) {
83 for (int i = 0; i < kIters; i++) {
84 SpinLockHolder h(spinlock);
85 for (int j = 0; j < kArrayLength; j++) {
86 const int index = (j + thread_salt) % kArrayLength;
87 values[index] = Hash32(values[index], thread_salt);
88 std::this_thread::yield();
89 }
90 }
91 }
92
ThreadedTest(SpinLock * spinlock)93 static void ThreadedTest(SpinLock* spinlock) {
94 std::vector<std::thread> threads;
95 for (int i = 0; i < kNumThreads; ++i) {
96 threads.push_back(std::thread(TestFunction, i, spinlock));
97 }
98 for (auto& thread : threads) {
99 thread.join();
100 }
101
102 SpinLockHolder h(spinlock);
103 for (int i = 1; i < kArrayLength; i++) {
104 EXPECT_EQ(values[0], values[i]);
105 }
106 }
107
108 #ifndef ABSL_HAVE_THREAD_SANITIZER
109 static_assert(std::is_trivially_destructible<SpinLock>(), "");
110 #endif
111
TEST(SpinLock,StackNonCooperativeDisablesScheduling)112 TEST(SpinLock, StackNonCooperativeDisablesScheduling) {
113 SpinLock spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
114 spinlock.Lock();
115 EXPECT_FALSE(base_internal::SchedulingGuard::ReschedulingIsAllowed());
116 spinlock.Unlock();
117 }
118
TEST(SpinLock,StaticNonCooperativeDisablesScheduling)119 TEST(SpinLock, StaticNonCooperativeDisablesScheduling) {
120 static_noncooperative_spinlock.Lock();
121 EXPECT_FALSE(base_internal::SchedulingGuard::ReschedulingIsAllowed());
122 static_noncooperative_spinlock.Unlock();
123 }
124
TEST(SpinLock,WaitCyclesEncoding)125 TEST(SpinLock, WaitCyclesEncoding) {
126 // These are implementation details not exported by SpinLock.
127 const int kProfileTimestampShift = 7;
128 const int kLockwordReservedShift = 3;
129 const uint32_t kSpinLockSleeper = 8;
130
131 // We should be able to encode up to (1^kMaxCycleBits - 1) without clamping
132 // but the lower kProfileTimestampShift will be dropped.
133 const int kMaxCyclesShift =
134 32 - kLockwordReservedShift + kProfileTimestampShift;
135 const uint64_t kMaxCycles = (int64_t{1} << kMaxCyclesShift) - 1;
136
137 // These bits should be zero after encoding.
138 const uint32_t kLockwordReservedMask = (1 << kLockwordReservedShift) - 1;
139
140 // These bits are dropped when wait cycles are encoded.
141 const uint64_t kProfileTimestampMask = (1 << kProfileTimestampShift) - 1;
142
143 // Test a bunch of random values
144 std::default_random_engine generator;
145 // Shift to avoid overflow below.
146 std::uniform_int_distribution<uint64_t> time_distribution(
147 0, std::numeric_limits<uint64_t>::max() >> 4);
148 std::uniform_int_distribution<uint64_t> cycle_distribution(0, kMaxCycles);
149
150 for (int i = 0; i < 100; i++) {
151 int64_t start_time = time_distribution(generator);
152 int64_t cycles = cycle_distribution(generator);
153 int64_t end_time = start_time + cycles;
154 uint32_t lock_value = SpinLockTest::EncodeWaitCycles(start_time, end_time);
155 EXPECT_EQ(0, lock_value & kLockwordReservedMask);
156 uint64_t decoded = SpinLockTest::DecodeWaitCycles(lock_value);
157 EXPECT_EQ(0, decoded & kProfileTimestampMask);
158 EXPECT_EQ(cycles & ~kProfileTimestampMask, decoded);
159 }
160
161 // Test corner cases
162 int64_t start_time = time_distribution(generator);
163 EXPECT_EQ(kSpinLockSleeper,
164 SpinLockTest::EncodeWaitCycles(start_time, start_time));
165 EXPECT_EQ(0, SpinLockTest::DecodeWaitCycles(0));
166 EXPECT_EQ(0, SpinLockTest::DecodeWaitCycles(kLockwordReservedMask));
167 EXPECT_EQ(kMaxCycles & ~kProfileTimestampMask,
168 SpinLockTest::DecodeWaitCycles(~kLockwordReservedMask));
169
170 // Check that we cannot produce kSpinLockSleeper during encoding.
171 int64_t sleeper_cycles =
172 kSpinLockSleeper << (kProfileTimestampShift - kLockwordReservedShift);
173 uint32_t sleeper_value =
174 SpinLockTest::EncodeWaitCycles(start_time, start_time + sleeper_cycles);
175 EXPECT_NE(sleeper_value, kSpinLockSleeper);
176
177 // Test clamping
178 uint32_t max_value =
179 SpinLockTest::EncodeWaitCycles(start_time, start_time + kMaxCycles);
180 uint64_t max_value_decoded = SpinLockTest::DecodeWaitCycles(max_value);
181 uint64_t expected_max_value_decoded = kMaxCycles & ~kProfileTimestampMask;
182 EXPECT_EQ(expected_max_value_decoded, max_value_decoded);
183
184 const int64_t step = (1 << kProfileTimestampShift);
185 uint32_t after_max_value =
186 SpinLockTest::EncodeWaitCycles(start_time, start_time + kMaxCycles + step);
187 uint64_t after_max_value_decoded =
188 SpinLockTest::DecodeWaitCycles(after_max_value);
189 EXPECT_EQ(expected_max_value_decoded, after_max_value_decoded);
190
191 uint32_t before_max_value = SpinLockTest::EncodeWaitCycles(
192 start_time, start_time + kMaxCycles - step);
193 uint64_t before_max_value_decoded =
194 SpinLockTest::DecodeWaitCycles(before_max_value);
195 EXPECT_GT(expected_max_value_decoded, before_max_value_decoded);
196 }
197
TEST(SpinLockWithThreads,StackSpinLock)198 TEST(SpinLockWithThreads, StackSpinLock) {
199 SpinLock spinlock;
200 ThreadedTest(&spinlock);
201 }
202
TEST(SpinLockWithThreads,StackCooperativeSpinLock)203 TEST(SpinLockWithThreads, StackCooperativeSpinLock) {
204 SpinLock spinlock(base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
205 ThreadedTest(&spinlock);
206 }
207
TEST(SpinLockWithThreads,StackNonCooperativeSpinLock)208 TEST(SpinLockWithThreads, StackNonCooperativeSpinLock) {
209 SpinLock spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
210 ThreadedTest(&spinlock);
211 }
212
TEST(SpinLockWithThreads,StaticCooperativeSpinLock)213 TEST(SpinLockWithThreads, StaticCooperativeSpinLock) {
214 ThreadedTest(&static_cooperative_spinlock);
215 }
216
TEST(SpinLockWithThreads,StaticNonCooperativeSpinLock)217 TEST(SpinLockWithThreads, StaticNonCooperativeSpinLock) {
218 ThreadedTest(&static_noncooperative_spinlock);
219 }
220
TEST(SpinLockWithThreads,DoesNotDeadlock)221 TEST(SpinLockWithThreads, DoesNotDeadlock) {
222 struct Helper {
223 static void NotifyThenLock(Notification* locked, SpinLock* spinlock,
224 BlockingCounter* b) {
225 locked->WaitForNotification(); // Wait for LockThenWait() to hold "s".
226 b->DecrementCount();
227 SpinLockHolder l(spinlock);
228 }
229
230 static void LockThenWait(Notification* locked, SpinLock* spinlock,
231 BlockingCounter* b) {
232 SpinLockHolder l(spinlock);
233 locked->Notify();
234 b->Wait();
235 }
236
237 static void DeadlockTest(SpinLock* spinlock, int num_spinners) {
238 Notification locked;
239 BlockingCounter counter(num_spinners);
240 std::vector<std::thread> threads;
241
242 threads.push_back(
243 std::thread(Helper::LockThenWait, &locked, spinlock, &counter));
244 for (int i = 0; i < num_spinners; ++i) {
245 threads.push_back(
246 std::thread(Helper::NotifyThenLock, &locked, spinlock, &counter));
247 }
248
249 for (auto& thread : threads) {
250 thread.join();
251 }
252 }
253 };
254
255 SpinLock stack_cooperative_spinlock(
256 base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
257 SpinLock stack_noncooperative_spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
258 Helper::DeadlockTest(&stack_cooperative_spinlock,
259 base_internal::NumCPUs() * 2);
260 Helper::DeadlockTest(&stack_noncooperative_spinlock,
261 base_internal::NumCPUs() * 2);
262 Helper::DeadlockTest(&static_cooperative_spinlock,
263 base_internal::NumCPUs() * 2);
264 Helper::DeadlockTest(&static_noncooperative_spinlock,
265 base_internal::NumCPUs() * 2);
266 }
267
268 } // namespace
269 } // namespace base_internal
270 ABSL_NAMESPACE_END
271 } // namespace absl
272