Debian Codegraph @

src/kj/mutex.c++

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #if _WIN32 || __CYGWIN__
23 #include "win32-api-version.h"
24 #endif
25
26 #include "mutex.h"
27 #include "debug.h"
28
29 #if !_WIN32 && !__CYGWIN__
30 #include <time.h>
31 #include <errno.h>
32 #endif
33
34 #if KJ_USE_FUTEX
35 #include <unistd.h>
36 #include <sys/syscall.h>
37 #include <linux/futex.h>
38 #include <limits.h>
39
•40 // see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1067916
41 #if defined(__USE_TIME_BITS64) && (__BITS_PER_LONG == 32)
42 #define MY_FUTEX __NR_futex_time64
43 #else
•44 #define MY_FUTEX __NR_futex
45 #endif
46
47 #ifndef FUTEX_WAIT_PRIVATE
48 // Missing on Android/Bionic.
49 #define FUTEX_WAIT_PRIVATE FUTEX_WAIT
50 #define FUTEX_WAKE_PRIVATE FUTEX_WAKE
51 #endif
52
53 #elif _WIN32 || __CYGWIN__
54 #include <windows.h>
55 #endif
56
57 namespace kj {
58 #if KJ_TRACK_LOCK_BLOCKING
59 static thread_local const BlockedOnReason* tlsBlockReason __attribute((tls_model("initial-exec")));
60 // The initial-exec model ensures that even if this code is part of a shared library built PIC, then
61 // we still place this variable in the appropriate ELF section so that __tls_get_addr is avoided.
62 // It's unclear if __tls_get_addr is still not async signal safe in glibc. The only negative
63 // downside of this approach is that a shared library built with kj & lock tracking will fail if
64 // dlopen'ed which isn't an intended use-case for the initial implementation.
65
66 Maybe<const BlockedOnReason&> blockedReason() noexcept {
67 if (tlsBlockReason == nullptr) {
68 return nullptr;
69 }
70 return *tlsBlockReason;
71 }
72
73 static void setCurrentThreadIsWaitingFor(const BlockedOnReason* meta) {
74 tlsBlockReason = meta;
75 }
76
77 static void setCurrentThreadIsNoLongerWaiting() {
78 tlsBlockReason = nullptr;
79 }
80 #elif KJ_USE_FUTEX
81 struct BlockedOnMutexAcquisition {
82 constexpr BlockedOnMutexAcquisition(const _::Mutex& mutex, LockSourceLocationArg) {}
83 };
84
85 struct BlockedOnCondVarWait {
86 constexpr BlockedOnCondVarWait(const _::Mutex& mutex, const void *waiter,
87 LockSourceLocationArg) {}
88 };
89
90 struct BlockedOnOnceInit {
91 constexpr BlockedOnOnceInit(const _::Once& once, LockSourceLocationArg) {}
92 };
93
94 struct BlockedOnReason {
95 constexpr BlockedOnReason(const BlockedOnMutexAcquisition&) {}
96 constexpr BlockedOnReason(const BlockedOnCondVarWait&) {}
97 constexpr BlockedOnReason(const BlockedOnOnceInit&) {}
98 };
99
100 static void setCurrentThreadIsWaitingFor(const BlockedOnReason* meta) {}
101 static void setCurrentThreadIsNoLongerWaiting() {}
102 #endif
103
104 namespace _ { // private
105
106 #if KJ_USE_FUTEX
107 constexpr uint Mutex::EXCLUSIVE_HELD;
108 constexpr uint Mutex::EXCLUSIVE_REQUESTED;
109 constexpr uint Mutex::SHARED_COUNT_MASK;
110 #endif
111
112 inline void Mutex::addWaiter(Waiter& waiter) {
113 #ifdef KJ_DEBUG
114 assertLockedByCaller(EXCLUSIVE);
115 #endif
116 *waitersTail = waiter;
117 waitersTail = &waiter.next;
118 }
119 inline void Mutex::removeWaiter(Waiter& waiter) {
120 #ifdef KJ_DEBUG
121 assertLockedByCaller(EXCLUSIVE);
122 #endif
123 *waiter.prev = waiter.next;
124 KJ_IF_MAYBE(next, waiter.next) {
125 next->prev = waiter.prev;
126 } else {
127 KJ_DASSERT(waitersTail == &waiter.next);
128 waitersTail = waiter.prev;
129 }
130 }
131
132 bool Mutex::checkPredicate(Waiter& waiter) {
133 // Run the predicate from a thread other than the waiting thread, returning true if it's time to
134 // signal the waiting thread. This is not only when the predicate passes, but also when it
135 // throws, in which case we want to propagate the exception to the waiting thread.
136
137 if (waiter.exception != nullptr) return true; // don't run again after an exception
138
139 bool result = false;
140 KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
141 result = waiter.predicate.check();
142 })) {
143 // Exception thrown.
144 result = true;
145 waiter.exception = kj::heap(kj::mv(*exception));
146 };
147 return result;
148 }
149
150 #if !_WIN32 && !__CYGWIN__
151 namespace {
152
153 TimePoint toTimePoint(struct timespec ts) {
154 return kj::origin<TimePoint>() + ts.tv_sec * kj::SECONDS + ts.tv_nsec * kj::NANOSECONDS;
155 }
156 TimePoint now() {
157 struct timespec now;
158 KJ_SYSCALL(clock_gettime(CLOCK_MONOTONIC, &now));
159 return toTimePoint(now);
160 }
161 struct timespec toRelativeTimespec(Duration timeout) {
162 struct timespec ts;
163 ts.tv_sec = timeout / kj::SECONDS;
164 ts.tv_nsec = timeout % kj::SECONDS / kj::NANOSECONDS;
165 return ts;
166 }
167 struct timespec toAbsoluteTimespec(TimePoint time) {
168 return toRelativeTimespec(time - kj::origin<TimePoint>());
169 }
170
171 } // namespace
172 #endif
173
174 #if KJ_USE_FUTEX
175 // =======================================================================================
176 // Futex-based implementation (Linux-only)
177
178 #if KJ_SAVE_ACQUIRED_LOCK_INFO
179 #if !__GLIBC_PREREQ(2, 30)
180 #ifndef SYS_gettid
181 #error SYS_gettid is unavailable on this system
182 #endif
183
184 #define gettid() ((pid_t)syscall(SYS_gettid))
185 #endif
186
187 static thread_local pid_t tlsTid = gettid();
188 #define TRACK_ACQUIRED_TID() tlsTid
189
190 Mutex::AcquiredMetadata Mutex::lockedInfo() const {
191 auto state = __atomic_load_n(&futex, __ATOMIC_RELAXED);
192 auto tid = lockedExclusivelyByThread;
193 auto location = lockAcquiredLocation;
194
195 if (state & EXCLUSIVE_HELD) {
196 return HoldingExclusively{tid, location};
197 } else {
198 return HoldingShared{location};
199 }
200 }
201
202 #else
203 #define TRACK_ACQUIRED_TID() 0
204 #endif
205
206 Mutex::Mutex(): futex(0) {}
207 Mutex::~Mutex() {
208 // This will crash anyway, might as well crash with a nice error message.
209 KJ_ASSERT(futex == 0, "Mutex destroyed while locked.") { break; }
210 }
211
212 bool Mutex::lock(Exclusivity exclusivity, Maybe<Duration> timeout, LockSourceLocationArg location) {
213 BlockedOnReason blockReason = BlockedOnMutexAcquisition{*this, location};
214 KJ_DEFER(setCurrentThreadIsNoLongerWaiting());
215
216 auto spec = timeout.map([](Duration d) { return toRelativeTimespec(d); });
217 struct timespec* specp = nullptr;
218 KJ_IF_MAYBE(s, spec) {
219 specp = s;
220 }
221
222 switch (exclusivity) {
223 case EXCLUSIVE:
224 for (;;) {
225 uint state = 0;
226 if (KJ_LIKELY(__atomic_compare_exchange_n(&futex, &state, EXCLUSIVE_HELD, false,
227 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))) {
228
229 // Acquired.
230 break;
231 }
232
233 // The mutex is contended. Set the exclusive-requested bit and wait.
234 if ((state & EXCLUSIVE_REQUESTED) == 0) {
235 if (!__atomic_compare_exchange_n(&futex, &state, state | EXCLUSIVE_REQUESTED, false,
236 __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
237 // Oops, the state changed before we could set the request bit. Start over.
238 continue;
239 }
240
241 state |= EXCLUSIVE_REQUESTED;
242 }
243
244 setCurrentThreadIsWaitingFor(&blockReason);
245
•246 auto result = syscall(MY_FUTEX, &futex, FUTEX_WAIT_PRIVATE, state, specp, nullptr, 0);
247 if (result < 0) {
248 if (errno == ETIMEDOUT) {
249 setCurrentThreadIsNoLongerWaiting();
250 // We timed out, we can't remove the exclusive request flag (since others might be waiting)
251 // so we just return false.
252 return false;
253 }
254 }
255 }
256 acquiredExclusive(TRACK_ACQUIRED_TID(), location);
257 #if KJ_CONTENTION_WARNING_THRESHOLD
258 printContendedReader = false;
259 #endif
260 break;
261 case SHARED: {
262 #if KJ_CONTENTION_WARNING_THRESHOLD
263 kj::Maybe<kj::TimePoint> contentionWaitStart;
264 #endif
265
266 uint state = __atomic_add_fetch(&futex, 1, __ATOMIC_ACQUIRE);
267
268 for (;;) {
269 if (KJ_LIKELY((state & EXCLUSIVE_HELD) == 0)) {
270 // Acquired.
271 break;
272 }
273
274 #if KJ_CONTENTION_WARNING_THRESHOLD
275 if (contentionWaitStart == nullptr) {
276 // We could have the exclusive mutex tell us how long it was holding the lock. That would
277 // be the nicest. However, I'm hesitant to bloat the structure. I suspect having a reader
278 // tell us how long it was waiting for is probably a good proxy.
279 contentionWaitStart = kj::systemPreciseMonotonicClock().now();
280 }
281 #endif
282
283 setCurrentThreadIsWaitingFor(&blockReason);
284
285 // The mutex is exclusively locked by another thread. Since we incremented the counter
286 // already, we just have to wait for it to be unlocked.
•287 auto result = syscall(MY_FUTEX, &futex, FUTEX_WAIT_PRIVATE, state, specp, nullptr, 0);
288 if (result < 0) {
289 // If we timeout though, we need to signal that we're not waiting anymore.
290 if (errno == ETIMEDOUT) {
291 setCurrentThreadIsNoLongerWaiting();
292 state = __atomic_sub_fetch(&futex, 1, __ATOMIC_RELAXED);
293
294 // We may have unlocked since we timed out. So act like we just unlocked the mutex
295 // and maybe send a wait signal if needed. See Mutex::unlock SHARED case.
296 if (KJ_UNLIKELY(state == EXCLUSIVE_REQUESTED)) {
297 if (__atomic_compare_exchange_n(
298 &futex, &state, 0, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
299 // Wake all exclusive waiters. We have to wake all of them because one of them will
300 // grab the lock while the others will re-establish the exclusive-requested bit.
•301 syscall(MY_FUTEX, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
302 }
303 }
304 return false;
305 }
306 }
307 state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
308 }
309
310 #ifdef KJ_CONTENTION_WARNING_THRESHOLD
311 KJ_IF_MAYBE(start, contentionWaitStart) {
312 if (__atomic_load_n(&printContendedReader, __ATOMIC_RELAXED)) {
313 // Double-checked lock avoids the CPU needing to acquire the lock in most cases.
314 if (__atomic_exchange_n(&printContendedReader, false, __ATOMIC_RELAXED)) {
315 auto contentionDuration = kj::systemPreciseMonotonicClock().now() - *start;
316 KJ_LOG(WARNING, "Acquired contended lock", location, contentionDuration,
317 kj::getStackTrace());
318 }
319 }
320 }
321 #endif
322
323 // We just want to record the lock being acquired somewhere but the specific location doesn't
324 // matter. This does mean that race conditions could occur where a thread might read this
325 // inconsistently (e.g. filename from 1 lock & function from another). This currently is just
326 // meant to be a debugging aid for manual analysis so it's OK for that purpose. If it's ever
327 // required for this to be used for anything else, then this should probably be changed to
328 // use an additional atomic variable that can ensure only one writer updates this. Or use the
329 // futex variable to ensure that this is only done for the first one to acquire the lock,
330 // although there may be thundering herd problems with that whereby there's a long wallclock
331 // time between when the lock is acquired and when the location is updated (since the first
332 // locker isn't really guaranteed to be the first one unlocked).
333 acquiredShared(location);
334
335 break;
336 }
337 }
338 return true;
339 }
340
341 void Mutex::unlock(Exclusivity exclusivity, Waiter* waiterToSkip) {
342 switch (exclusivity) {
343 case EXCLUSIVE: {
344 KJ_DASSERT(futex & EXCLUSIVE_HELD, "Unlocked a mutex that wasn't locked.");
345
346 #ifdef KJ_CONTENTION_WARNING_THRESHOLD
347 auto acquiredLocation = releasingExclusive();
348 #endif
349
350 // First check if there are any conditional waiters. Note we only do this when unlocking an
351 // exclusive lock since under a shared lock the state couldn't have changed.
352 auto nextWaiter = waitersHead;
353 for (;;) {
354 KJ_IF_MAYBE(waiter, nextWaiter) {
355 nextWaiter = waiter->next;
356
357 if (waiter != waiterToSkip && checkPredicate(*waiter)) {
358 // This waiter's predicate now evaluates true, so wake it up.
359 if (waiter->hasTimeout) {
360 // In this case we need to be careful to make sure the target thread isn't already
361 // processing a timeout, so we need to do an atomic CAS rather than just a store.
362 uint expected = 0;
363 if (__atomic_compare_exchange_n(&waiter->futex, &expected, 1, false,
364 __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
365 // Good, we set it to 1, transferring ownership of the mutex. Continue on below.
366 } else {
367 // Looks like the thread already timed out and set its own futex to 1. In that
368 // case it is going to try to lock the mutex itself, so we should NOT attempt an
369 // ownership transfer as this will deadlock.
370 //
371 // We have two options here: We can continue along the waiter list looking for
372 // another waiter that's ready to be signaled, or we could drop out of the list
373 // immediately since we know that another thread is already waiting for the lock
374 // and will re-evaluate the waiter queue itself when it is done. It feels cleaner
375 // to me to continue.
376 continue;
377 }
378 } else {
379 __atomic_store_n(&waiter->futex, 1, __ATOMIC_RELEASE);
380 }
•381 syscall(MY_FUTEX, &waiter->futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
382
383 // We transferred ownership of the lock to this waiter, so we're done now.
384 return;
385 }
386 } else {
387 // No more waiters.
388 break;
389 }
390 }
391
392 #ifdef KJ_CONTENTION_WARNING_THRESHOLD
393 uint readerCount;
394 {
395 uint oldState = __atomic_load_n(&futex, __ATOMIC_RELAXED);
396 readerCount = oldState & SHARED_COUNT_MASK;
397 if (readerCount >= KJ_CONTENTION_WARNING_THRESHOLD) {
398 // Atomic not needed because we're still holding the exclusive lock.
399 printContendedReader = true;
400 }
401 }
402 #endif
403
404 // Didn't wake any waiters, so wake normally.
405 uint oldState = __atomic_fetch_and(
406 &futex, ~(EXCLUSIVE_HELD | EXCLUSIVE_REQUESTED), __ATOMIC_RELEASE);
407
408 if (KJ_UNLIKELY(oldState & ~EXCLUSIVE_HELD)) {
409 // Other threads are waiting. If there are any shared waiters, they now collectively hold
410 // the lock, and we must wake them up. If there are any exclusive waiters, we must wake
411 // them up even if readers are waiting so that at the very least they may re-establish the
412 // EXCLUSIVE_REQUESTED bit that we just removed.
•413 syscall(MY_FUTEX, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
414
415 #ifdef KJ_CONTENTION_WARNING_THRESHOLD
416 if (readerCount >= KJ_CONTENTION_WARNING_THRESHOLD) {
417 KJ_LOG(WARNING, "excessively many readers were waiting on this lock", readerCount,
418 acquiredLocation, kj::getStackTrace());
419 }
420 #endif
421 }
422 break;
423 }
424
425 case SHARED: {
426 KJ_DASSERT(futex & SHARED_COUNT_MASK, "Unshared a mutex that wasn't shared.");
427 uint state = __atomic_sub_fetch(&futex, 1, __ATOMIC_RELEASE);
428
429 // The only case where anyone is waiting is if EXCLUSIVE_REQUESTED is set, and the only time
430 // it makes sense to wake up that waiter is if the shared count has reached zero.
431 if (KJ_UNLIKELY(state == EXCLUSIVE_REQUESTED)) {
432 if (__atomic_compare_exchange_n(
433 &futex, &state, 0, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
434 // Wake all exclusive waiters. We have to wake all of them because one of them will
435 // grab the lock while the others will re-establish the exclusive-requested bit.
•436 syscall(MY_FUTEX, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
437 }
438 }
439 break;
440 }
441 }
442 }
443
444 void Mutex::assertLockedByCaller(Exclusivity exclusivity) const {
445 switch (exclusivity) {
446 case EXCLUSIVE:
447 KJ_ASSERT(futex & EXCLUSIVE_HELD,
448 "Tried to call getAlreadyLocked*() but lock is not held.");
449 break;
450 case SHARED:
451 KJ_ASSERT(futex & SHARED_COUNT_MASK,
452 "Tried to call getAlreadyLocked*() but lock is not held.");
453 break;
454 }
455 }
456
457 void Mutex::wait(Predicate& predicate, Maybe<Duration> timeout, LockSourceLocationArg location) {
458 // Add waiter to list.
459 Waiter waiter { nullptr, waitersTail, predicate, nullptr, 0, timeout != nullptr };
460 addWaiter(waiter);
461
462 BlockedOnReason blockReason = BlockedOnCondVarWait{*this, &waiter, location};
463 KJ_DEFER(setCurrentThreadIsNoLongerWaiting());
464
465 // To guarantee that we've re-locked the mutex before scope exit, keep track of whether it is
466 // currently.
467 bool currentlyLocked = true;
468 KJ_DEFER({
469 // Infinite timeout for re-obtaining the lock is on purpose because the post-condition for this
470 // function has to be that the lock state hasn't changed (& we have to be locked when we enter
471 // since that's how condvars work).
472 if (!currentlyLocked) lock(EXCLUSIVE, nullptr, location);
473 removeWaiter(waiter);
474 });
475
476 if (!predicate.check()) {
477 unlock(EXCLUSIVE, &waiter);
478 currentlyLocked = false;
479
480 struct timespec ts;
481 struct timespec* tsp = nullptr;
482 KJ_IF_MAYBE(t, timeout) {
483 ts = toAbsoluteTimespec(now() + *t);
484 tsp = &ts;
485 }
486
487 setCurrentThreadIsWaitingFor(&blockReason);
488
489 // Wait for someone to set our futex to 1.
490 for (;;) {
491 // Note we use FUTEX_WAIT_BITSET_PRIVATE + FUTEX_BITSET_MATCH_ANY to get the same effect as
492 // FUTEX_WAIT_PRIVATE except that the timeout is specified as an absolute time based on
493 // CLOCK_MONOTONIC. Otherwise, FUTEX_WAIT_PRIVATE interprets it as a relative time, forcing
494 // us to recompute the time after every iteration.
•495 KJ_SYSCALL_HANDLE_ERRORS(syscall(MY_FUTEX,
496 &waiter.futex, FUTEX_WAIT_BITSET_PRIVATE, 0, tsp, nullptr, FUTEX_BITSET_MATCH_ANY)) {
497 case EAGAIN:
498 // Indicates that the futex was already non-zero by the time the kernel looked at it.
499 // Not an error.
500 break;
501 case ETIMEDOUT: {
502 // Wait timed out. This leaves us in a bit of a pickle: Ownership of the mutex was not
503 // transferred to us from another thread. So, we need to lock it ourselves. But, another
504 // thread might be in the process of signaling us and transferring ownership. So, we
505 // first must atomically take control of our destiny.
506 KJ_ASSERT(timeout != nullptr);
507 uint expected = 0;
508 if (__atomic_compare_exchange_n(&waiter.futex, &expected, 1, false,
509 __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) {
510 // OK, we set our own futex to 1. That means no other thread will, and so we won't be
511 // receiving a mutex ownership transfer. We have to lock the mutex ourselves.
512 setCurrentThreadIsNoLongerWaiting();
513 lock(EXCLUSIVE, nullptr, location);
514 currentlyLocked = true;
515 return;
516 } else {
517 // Oh, someone else actually did signal us, apparently. Let's move on as if the futex
518 // call told us so.
519 break;
520 }
521 }
522 default:
523 KJ_FAIL_SYSCALL("futex(FUTEX_WAIT_PRIVATE)", error);
524 }
525
526 setCurrentThreadIsNoLongerWaiting();
527
528 if (__atomic_load_n(&waiter.futex, __ATOMIC_ACQUIRE)) {
529 // We received a lock ownership transfer from another thread.
530 currentlyLocked = true;
531
532 // The other thread checked the predicate before the transfer.
533 #ifdef KJ_DEBUG
534 assertLockedByCaller(EXCLUSIVE);
535 #endif
536
537 KJ_IF_MAYBE(exception, waiter.exception) {
538 // The predicate threw an exception, apparently. Propagate it.
539 // TODO(someday): Could we somehow have this be a recoverable exception? Presumably we'd
540 // then want MutexGuarded::when() to skip calling the callback, but then what should it
541 // return, since it normally returns the callback's result? Or maybe people who disable
542 // exceptions just really should not write predicates that can throw.
543 kj::throwFatalException(kj::mv(**exception));
544 }
545
546 return;
547 }
548 }
549 }
550 }
551
552 void Mutex::induceSpuriousWakeupForTest() {
553 auto nextWaiter = waitersHead;
554 for (;;) {
555 KJ_IF_MAYBE(waiter, nextWaiter) {
556 nextWaiter = waiter->next;
•557 syscall(MY_FUTEX, &waiter->futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
558 } else {
559 // No more waiters.
560 break;
561 }
562 }
563 }
564
565 uint Mutex::numReadersWaitingForTest() const {
566 assertLockedByCaller(EXCLUSIVE);
567 return futex & SHARED_COUNT_MASK;
568 }
569
570 void Once::runOnce(Initializer& init, LockSourceLocationArg location) {
571 startOver:
572 uint state = UNINITIALIZED;
573 if (__atomic_compare_exchange_n(&futex, &state, INITIALIZING, false,
574 __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
575 // It's our job to initialize!
576 {
577 KJ_ON_SCOPE_FAILURE({
578 // An exception was thrown by the initializer. We have to revert.
579 if (__atomic_exchange_n(&futex, UNINITIALIZED, __ATOMIC_RELEASE) ==
580 INITIALIZING_WITH_WAITERS) {
581 // Someone was waiting for us to finish.
•582 syscall(MY_FUTEX, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
583 }
584 });
585
586 init.run();
587 }
588 if (__atomic_exchange_n(&futex, INITIALIZED, __ATOMIC_RELEASE) ==
589 INITIALIZING_WITH_WAITERS) {
590 // Someone was waiting for us to finish.
•591 syscall(MY_FUTEX, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
592 }
593 } else {
594 BlockedOnReason blockReason = BlockedOnOnceInit{*this, location};
595 KJ_DEFER(setCurrentThreadIsNoLongerWaiting());
596
597 for (;;) {
598 if (state == INITIALIZED) {
599 break;
600 } else if (state == INITIALIZING) {
601 // Initialization is taking place in another thread. Indicate that we're waiting.
602 if (!__atomic_compare_exchange_n(&futex, &state, INITIALIZING_WITH_WAITERS, true,
603 __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) {
604 // State changed, retry.
605 continue;
606 }
607 } else {
608 KJ_DASSERT(state == INITIALIZING_WITH_WAITERS);
609 }
610
611 // Wait for initialization.
612 setCurrentThreadIsWaitingFor(&blockReason);
•613 syscall(MY_FUTEX, &futex, FUTEX_WAIT_PRIVATE, INITIALIZING_WITH_WAITERS,
614 nullptr, nullptr, 0);
615 state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
616
617 if (state == UNINITIALIZED) {
618 // Oh hey, apparently whoever was trying to initialize gave up. Let's take it from the
619 // top.
620 goto startOver;
621 }
622 }
623 }
624 }
625
626 void Once::reset() {
627 uint state = INITIALIZED;
628 if (!__atomic_compare_exchange_n(&futex, &state, UNINITIALIZED,
629 false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
630 KJ_FAIL_REQUIRE("reset() called while not initialized.");
631 }
632 }
633
634 #elif _WIN32 || __CYGWIN__
635 // =======================================================================================
636 // Win32 implementation
637
638 #define coercedSrwLock (*reinterpret_cast<SRWLOCK*>(&srwLock))
639 #define coercedInitOnce (*reinterpret_cast<INIT_ONCE*>(&initOnce))
640 #define coercedCondvar(var) (*reinterpret_cast<CONDITION_VARIABLE*>(&var))
641
642 Mutex::Mutex() {
643 static_assert(sizeof(SRWLOCK) == sizeof(srwLock), "SRWLOCK is not a pointer?");
644 InitializeSRWLock(&coercedSrwLock);
645 }
646 Mutex::~Mutex() {}
647
648 bool Mutex::lock(Exclusivity exclusivity, Maybe<Duration> timeout, NoopSourceLocation) {
649 if (timeout != nullptr) {
650 KJ_UNIMPLEMENTED("Locking a mutex with a timeout is only supported on Linux.");
651 }
652 switch (exclusivity) {
653 case EXCLUSIVE:
654 AcquireSRWLockExclusive(&coercedSrwLock);
655 break;
656 case SHARED:
657 AcquireSRWLockShared(&coercedSrwLock);
658 break;
659 }
660 return true;
661 }
662
663 void Mutex::wakeReadyWaiter(Waiter* waiterToSkip) {
664 // Look for a waiter whose predicate is now evaluating true, and wake it. We wake no more than
665 // one waiter because only one waiter could get the lock anyway, and once it releases that lock
666 // it will awake the next waiter if necessary.
667
668 auto nextWaiter = waitersHead;
669 for (;;) {
670 KJ_IF_MAYBE(waiter, nextWaiter) {
671 nextWaiter = waiter->next;
672
673 if (waiter != waiterToSkip && checkPredicate(*waiter)) {
674 // This waiter's predicate now evaluates true, so wake it up. It doesn't matter if we
675 // use Wake vs. WakeAll here since there's always only one thread waiting.
676 WakeConditionVariable(&coercedCondvar(waiter->condvar));
677
678 // We only need to wake one waiter. Note that unlike the futex-based implementation, we
679 // cannot "transfer ownership" of the lock to the waiter, therefore we cannot guarantee
680 // that the condition is still true when that waiter finally awakes. However, if the
681 // condition is no longer true at that point, the waiter will re-check all other
682 // waiters' conditions and possibly wake up any other waiter who is now ready, hence we
683 // still only need to wake one waiter here.
684 return;
685 }
686 } else {
687 // No more waiters.
688 break;
689 }
690 }
691 }
692
693 void Mutex::unlock(Exclusivity exclusivity, Waiter* waiterToSkip) {
694 switch (exclusivity) {
695 case EXCLUSIVE: {
696 KJ_DEFER(ReleaseSRWLockExclusive(&coercedSrwLock));
697
698 // Check if there are any conditional waiters. Note we only do this when unlocking an
699 // exclusive lock since under a shared lock the state couldn't have changed.
700 wakeReadyWaiter(waiterToSkip);
701 break;
702 }
703
704 case SHARED:
705 ReleaseSRWLockShared(&coercedSrwLock);
706 break;
707 }
708 }
709
710 void Mutex::assertLockedByCaller(Exclusivity exclusivity) const {
711 // We could use TryAcquireSRWLock*() here like we do with the pthread version. However, as of
712 // this writing, my version of Wine (1.6.2) doesn't implement these functions and will abort if
713 // they are called. Since we were only going to use them as a hacky way to check if the lock is
714 // held for debug purposes anyway, we just don't bother.
715 }
716
717 void Mutex::wait(Predicate& predicate, Maybe<Duration> timeout, NoopSourceLocation) {
718 // Add waiter to list.
719 Waiter waiter { nullptr, waitersTail, predicate, nullptr, 0 };
720 static_assert(sizeof(waiter.condvar) == sizeof(CONDITION_VARIABLE),
721 "CONDITION_VARIABLE is not a pointer?");
722 InitializeConditionVariable(&coercedCondvar(waiter.condvar));
723
724 addWaiter(waiter);
725 KJ_DEFER(removeWaiter(waiter));
726
727 DWORD sleepMs;
728
729 // Only initialized if `timeout` is non-null.
730 const MonotonicClock* clock = nullptr;
731 kj::Maybe<kj::TimePoint> endTime;
732
733 KJ_IF_MAYBE(t, timeout) {
734 // Windows sleeps are inaccurate -- they can be longer *or shorter* than the requested amount.
735 // For many use cases of our API, a too-short sleep would be unacceptable. Experimentally, it
736 // seems like sleeps can be up to half a millisecond short, so we'll add half a millisecond
737 // (and then we round up, below).
738 *t += 500 * kj::MICROSECONDS;
739
740 // Compute initial sleep time.
741 sleepMs = *t / kj::MILLISECONDS;
742 if (*t % kj::MILLISECONDS > 0 * kj::SECONDS) {
743 // We guarantee we won't wake up too early.
744 ++sleepMs;
745 }
746
747 clock = &systemPreciseMonotonicClock();
748 endTime = clock->now() + *t;
749 } else {
750 sleepMs = INFINITE;
751 }
752
753 while (!predicate.check()) {
754 // SleepConditionVariableSRW() will temporarily release the lock, so we need to signal other
755 // waiters that are now ready.
756 wakeReadyWaiter(&waiter);
757
758 if (SleepConditionVariableSRW(&coercedCondvar(waiter.condvar), &coercedSrwLock, sleepMs, 0)) {
759 // Normal result. Continue loop to check predicate.
760 } else {
761 DWORD error = GetLastError();
762 if (error == ERROR_TIMEOUT) {
763 // Windows may have woken us up too early, so don't return yet. Instead, proceed through the
764 // loop and rely on our sleep time recalculation to detect if we timed out.
765 } else {
766 KJ_FAIL_WIN32("SleepConditionVariableSRW()", error);
767 }
768 }
769
770 KJ_IF_MAYBE(exception, waiter.exception) {
771 // The predicate threw an exception, apparently. Propagate it.
772 // TODO(someday): Could we somehow have this be a recoverable exception? Presumably we'd
773 // then want MutexGuarded::when() to skip calling the callback, but then what should it
774 // return, since it normally returns the callback's result? Or maybe people who disable
775 // exceptions just really should not write predicates that can throw.
776 kj::throwFatalException(kj::mv(**exception));
777 }
778
779 // Recompute sleep time.
780 KJ_IF_MAYBE(e, endTime) {
781 auto now = clock->now();
782
783 if (*e > now) {
784 auto sleepTime = *e - now;
785 sleepMs = sleepTime / kj::MILLISECONDS;
786 if (sleepTime % kj::MILLISECONDS > 0 * kj::SECONDS) {
787 // We guarantee we won't wake up too early.
788 ++sleepMs;
789 }
790 } else {
791 // Oops, already timed out.
792 return;
793 }
794 }
795 }
796 }
797
798 void Mutex::induceSpuriousWakeupForTest() {
799 auto nextWaiter = waitersHead;
800 for (;;) {
801 KJ_IF_MAYBE(waiter, nextWaiter) {
802 nextWaiter = waiter->next;
803 WakeConditionVariable(&coercedCondvar(waiter->condvar));
804 } else {
805 // No more waiters.
806 break;
807 }
808 }
809 }
810
811 static BOOL WINAPI nullInitializer(PINIT_ONCE initOnce, PVOID parameter, PVOID* context) {
812 return true;
813 }
814
815 Once::Once(bool startInitialized) {
816 static_assert(sizeof(INIT_ONCE) == sizeof(initOnce), "INIT_ONCE is not a pointer?");
817 InitOnceInitialize(&coercedInitOnce);
818 if (startInitialized) {
819 InitOnceExecuteOnce(&coercedInitOnce, &nullInitializer, nullptr, nullptr);
820 }
821 }
822 Once::~Once() {}
823
824 void Once::runOnce(Initializer& init, NoopSourceLocation) {
825 BOOL needInit;
826 while (!InitOnceBeginInitialize(&coercedInitOnce, 0, &needInit, nullptr)) {
827 // Init was occurring in another thread, but then failed with an exception. Retry.
828 }
829
830 if (needInit) {
831 {
832 KJ_ON_SCOPE_FAILURE(InitOnceComplete(&coercedInitOnce, INIT_ONCE_INIT_FAILED, nullptr));
833 init.run();
834 }
835
836 KJ_ASSERT(InitOnceComplete(&coercedInitOnce, 0, nullptr));
837 }
838 }
839
840 bool Once::isInitialized() noexcept {
841 BOOL junk;
842 return InitOnceBeginInitialize(&coercedInitOnce, INIT_ONCE_CHECK_ONLY, &junk, nullptr);
843 }
844
845 void Once::reset() {
846 InitOnceInitialize(&coercedInitOnce);
847 }
848
849 #else
850 // =======================================================================================
851 // Generic pthreads-based implementation
852
853 #define KJ_PTHREAD_CALL(code) \
854 { \
855 int pthreadError = code; \
856 if (pthreadError != 0) { \
857 KJ_FAIL_SYSCALL(#code, pthreadError); \
858 } \
859 }
860
861 #define KJ_PTHREAD_CLEANUP(code) \
862 { \
863 int pthreadError = code; \
864 if (pthreadError != 0) { \
865 KJ_LOG(ERROR, #code, strerror(pthreadError)); \
866 } \
867 }
868
869 Mutex::Mutex(): mutex(PTHREAD_RWLOCK_INITIALIZER) {
870 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070
871 // In older versions of MacOS, mutexes initialized statically cannot be destroyed,
872 // so we must call the init function.
873 KJ_PTHREAD_CALL(pthread_rwlock_init(&mutex, NULL));
874 #endif
875 }
876 Mutex::~Mutex() {
877 KJ_PTHREAD_CLEANUP(pthread_rwlock_destroy(&mutex));
878 }
879
880 bool Mutex::lock(Exclusivity exclusivity, Maybe<Duration> timeout, NoopSourceLocation) {
881 if (timeout != nullptr) {
882 KJ_UNIMPLEMENTED("Locking a mutex with a timeout is only supported on Linux.");
883 }
884 switch (exclusivity) {
885 case EXCLUSIVE:
886 KJ_PTHREAD_CALL(pthread_rwlock_wrlock(&mutex));
887 break;
888 case SHARED:
889 KJ_PTHREAD_CALL(pthread_rwlock_rdlock(&mutex));
890 break;
891 }
892 return true;
893 }
894
895 void Mutex::unlock(Exclusivity exclusivity, Waiter* waiterToSkip) {
896 KJ_DEFER(KJ_PTHREAD_CALL(pthread_rwlock_unlock(&mutex)));
897
898 if (exclusivity == EXCLUSIVE) {
899 // Check if there are any conditional waiters. Note we only do this when unlocking an
900 // exclusive lock since under a shared lock the state couldn't have changed.
901 auto nextWaiter = waitersHead;
902 for (;;) {
903 KJ_IF_MAYBE(waiter, nextWaiter) {
904 nextWaiter = waiter->next;
905
906 if (waiter != waiterToSkip && checkPredicate(*waiter)) {
907 // This waiter's predicate now evaluates true, so wake it up. It doesn't matter if we
908 // use _signal() vs. _broadcast() here since there's always only one thread waiting.
909 KJ_PTHREAD_CALL(pthread_mutex_lock(&waiter->stupidMutex));
910 KJ_PTHREAD_CALL(pthread_cond_signal(&waiter->condvar));
911 KJ_PTHREAD_CALL(pthread_mutex_unlock(&waiter->stupidMutex));
912
913 // We only need to wake one waiter. Note that unlike the futex-based implementation, we
914 // cannot "transfer ownership" of the lock to the waiter, therefore we cannot guarantee
915 // that the condition is still true when that waiter finally awakes. However, if the
916 // condition is no longer true at that point, the waiter will re-check all other waiters'
917 // conditions and possibly wake up any other waiter who is now ready, hence we still only
918 // need to wake one waiter here.
919 break;
920 }
921 } else {
922 // No more waiters.
923 break;
924 }
925 }
926 }
927 }
928
929 void Mutex::assertLockedByCaller(Exclusivity exclusivity) const {
930 switch (exclusivity) {
931 case EXCLUSIVE:
932 // A read lock should fail if the mutex is already held for writing.
933 if (pthread_rwlock_tryrdlock(&mutex) == 0) {
934 pthread_rwlock_unlock(&mutex);
935 KJ_FAIL_ASSERT("Tried to call getAlreadyLocked*() but lock is not held.");
936 }
937 break;
938 case SHARED:
939 // A write lock should fail if the mutex is already held for reading or writing. We don't
940 // have any way to prove that the lock is held only for reading.
941 if (pthread_rwlock_trywrlock(&mutex) == 0) {
942 pthread_rwlock_unlock(&mutex);
943 KJ_FAIL_ASSERT("Tried to call getAlreadyLocked*() but lock is not held.");
944 }
945 break;
946 }
947 }
948
949 void Mutex::wait(Predicate& predicate, Maybe<Duration> timeout, NoopSourceLocation) {
950 // Add waiter to list.
951 Waiter waiter {
952 nullptr, waitersTail, predicate, nullptr,
953 PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER
954 };
955
956 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070
957 // In older versions of MacOS, mutexes initialized statically cannot be destroyed,
958 // so we must call the init function.
959 KJ_PTHREAD_CALL(pthread_cond_init(&waiter.condvar, NULL));
960 KJ_PTHREAD_CALL(pthread_mutex_init(&waiter.stupidMutex, NULL));
961 #endif
962
963 addWaiter(waiter);
964
965 // To guarantee that we've re-locked the mutex before scope exit, keep track of whether it is
966 // currently.
967 bool currentlyLocked = true;
968 KJ_DEFER({
969 if (!currentlyLocked) lock(EXCLUSIVE, nullptr, NoopSourceLocation{});
970 removeWaiter(waiter);
971
972 // Destroy pthread objects.
973 KJ_PTHREAD_CLEANUP(pthread_mutex_destroy(&waiter.stupidMutex));
974 KJ_PTHREAD_CLEANUP(pthread_cond_destroy(&waiter.condvar));
975 });
976
977 #if !__APPLE__
978 if (timeout != nullptr) {
979 // Oops, the default condvar uses the wall clock, which is dumb... fix it to use the monotonic
980 // clock. (Except not on macOS, where pthread_condattr_setclock() is unimplemented, but there's
981 // a bizarre pthread_cond_timedwait_relative_np() method we can use instead...)
982 pthread_condattr_t attr;
983 KJ_PTHREAD_CALL(pthread_condattr_init(&attr));
984 KJ_PTHREAD_CALL(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
985 pthread_cond_init(&waiter.condvar, &attr);
986 KJ_PTHREAD_CALL(pthread_condattr_destroy(&attr));
987 }
988 #endif
989
990 Maybe<struct timespec> endTime = timeout.map([](Duration d) {
991 return toAbsoluteTimespec(now() + d);
992 });
993
994 while (!predicate.check()) {
995 // pthread condvars only work with basic mutexes, not rwlocks. So, we need to lock a basic
996 // mutex before we unlock the real mutex, and the signaling thread also needs to lock this
997 // mutex, in order to ensure that this thread is actually waiting on the condvar before it is
998 // signaled.
999 KJ_PTHREAD_CALL(pthread_mutex_lock(&waiter.stupidMutex));
1000
1001 // OK, now we can unlock the main mutex.
1002 unlock(EXCLUSIVE, &waiter);
1003 currentlyLocked = false;
1004
1005 bool timedOut = false;
1006
1007 // Wait for someone to signal the condvar.
1008 KJ_IF_MAYBE(t, endTime) {
1009 #if __APPLE__
1010 // On macOS, the absolute timeout can only be specified in wall time, not monotonic time,
1011 // which means modifying the system clock will break the wait. However, macOS happens to
1012 // provide an alternative relative-time wait function, so I guess we'll use that. It does
1013 // require recomputing the time every iteration...
1014 struct timespec ts = toRelativeTimespec(kj::max(toTimePoint(*t) - now(), 0 * kj::SECONDS));
1015 int error = pthread_cond_timedwait_relative_np(&waiter.condvar, &waiter.stupidMutex, &ts);
1016 #else
1017 int error = pthread_cond_timedwait(&waiter.condvar, &waiter.stupidMutex, t);
1018 #endif
1019 if (error != 0) {
1020 if (error == ETIMEDOUT) {
1021 timedOut = true;
1022 } else {
1023 KJ_FAIL_SYSCALL("pthread_cond_timedwait", error);
1024 }
1025 }
1026 } else {
1027 KJ_PTHREAD_CALL(pthread_cond_wait(&waiter.condvar, &waiter.stupidMutex));
1028 }
1029
1030 // We have to be very careful about lock ordering here. We need to unlock stupidMutex before
1031 // re-locking the main mutex, because another thread may have a lock on the main mutex already
1032 // and be waiting for a lock on stupidMutex. Note that other thread may signal the condvar
1033 // right after we unlock stupidMutex but before we re-lock the main mutex. That is fine,
1034 // because we've already been signaled.
1035 KJ_PTHREAD_CALL(pthread_mutex_unlock(&waiter.stupidMutex));
1036
1037 lock(EXCLUSIVE, nullptr, NoopSourceLocation{});
1038 currentlyLocked = true;
1039
1040 KJ_IF_MAYBE(exception, waiter.exception) {
1041 // The predicate threw an exception, apparently. Propagate it.
1042 // TODO(someday): Could we somehow have this be a recoverable exception? Presumably we'd
1043 // then want MutexGuarded::when() to skip calling the callback, but then what should it
1044 // return, since it normally returns the callback's result? Or maybe people who disable
1045 // exceptions just really should not write predicates that can throw.
1046 kj::throwFatalException(kj::mv(**exception));
1047 }
1048
1049 if (timedOut) {
1050 return;
1051 }
1052 }
1053 }
1054
1055 void Mutex::induceSpuriousWakeupForTest() {
1056 auto nextWaiter = waitersHead;
1057 for (;;) {
1058 KJ_IF_MAYBE(waiter, nextWaiter) {
1059 nextWaiter = waiter->next;
1060 KJ_PTHREAD_CALL(pthread_mutex_lock(&waiter->stupidMutex));
1061 KJ_PTHREAD_CALL(pthread_cond_signal(&waiter->condvar));
1062 KJ_PTHREAD_CALL(pthread_mutex_unlock(&waiter->stupidMutex));
1063 } else {
1064 // No more waiters.
1065 break;
1066 }
1067 }
1068 }
1069
1070 Once::Once(bool startInitialized)
1071 : state(startInitialized ? INITIALIZED : UNINITIALIZED),
1072 mutex(PTHREAD_MUTEX_INITIALIZER) {
1073 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070
1074 // In older versions of MacOS, mutexes initialized statically cannot be destroyed,
1075 // so we must call the init function.
1076 KJ_PTHREAD_CALL(pthread_mutex_init(&mutex, NULL));
1077 #endif
1078 }
1079 Once::~Once() {
1080 KJ_PTHREAD_CLEANUP(pthread_mutex_destroy(&mutex));
1081 }
1082
1083 void Once::runOnce(Initializer& init, NoopSourceLocation) {
1084 KJ_PTHREAD_CALL(pthread_mutex_lock(&mutex));
1085 KJ_DEFER(KJ_PTHREAD_CALL(pthread_mutex_unlock(&mutex)));
1086
1087 if (state != UNINITIALIZED) {
1088 return;
1089 }
1090
1091 init.run();
1092
1093 __atomic_store_n(&state, INITIALIZED, __ATOMIC_RELEASE);
1094 }
1095
1096 void Once::reset() {
1097 State oldState = INITIALIZED;
1098 if (!__atomic_compare_exchange_n(&state, &oldState, UNINITIALIZED,
1099 false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
1100 KJ_FAIL_REQUIRE("reset() called while not initialized.");
1101 }
1102 }
1103
1104 #endif
1105
1106 } // namespace _ (private)
1107 } // namespace kj