blob: 39ea4c690c2c9cb812e14f52788f4c84f26a05ec [file] [log] [blame]
Brian Silvermandc1eb272014-08-19 14:25:59 -04001#if !AOS_DEBUG
Austin Schuh7a41be62015-10-31 13:06:55 -07002#undef NDEBUG
Brian Silvermandc1eb272014-08-19 14:25:59 -04003#define NDEBUG
4#endif
5
John Park398c74a2018-10-20 21:17:39 -07006#include "aos/ipc_lib/aos_sync.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04007
8#include <linux/futex.h>
Brian Silvermandc1eb272014-08-19 14:25:59 -04009#include <pthread.h>
10#include <sched.h>
Tyler Chatowbf0609c2021-07-31 16:13:27 -070011#include <sys/syscall.h>
12#include <sys/types.h>
13#include <unistd.h>
14
15#include <cassert>
16#include <cerrno>
17#include <cinttypes>
18#include <climits>
19#include <cstddef>
20#include <cstdint>
21#include <cstring>
Brian Silvermandc1eb272014-08-19 14:25:59 -040022
Brian Silverman71c55c52014-08-19 14:31:59 -040023#ifdef AOS_SANITIZER_thread
24#include <sanitizer/tsan_interface_atomic.h>
25#endif
26
Brian Silvermandc1eb272014-08-19 14:25:59 -040027#include <algorithm>
Brian Silverman71c55c52014-08-19 14:31:59 -040028#include <type_traits>
Brian Silvermandc1eb272014-08-19 14:25:59 -040029
Alex Perrycb7da4b2019-08-28 19:35:56 -070030#include "absl/base/call_once.h"
Brian Silvermanb47f5552020-10-01 15:08:14 -070031#include "aos/macros.h"
32#include "aos/thread_local.h"
33#include "aos/util/compiler_memory_barrier.h"
Tyler Chatowbf0609c2021-07-31 16:13:27 -070034#include "glog/logging.h"
Brian Silvermanb47f5552020-10-01 15:08:14 -070035
Brian Silverman71c55c52014-08-19 14:31:59 -040036using ::aos::linux_code::ipc_lib::FutexAccessorObserver;
Brian Silvermandc1eb272014-08-19 14:25:59 -040037
Tyler Chatowbf0609c2021-07-31 16:13:27 -070038// This code was originally based on
39// <https://www.akkadia.org/drepper/futex.pdf>, but is has since evolved a lot.
40// However, that still has useful information.
Brian Silvermandc1eb272014-08-19 14:25:59 -040041//
42// Finding information about actually using futexes is really REALLY hard, so
43// here's a list of the stuff that I've used:
44// futex(7) has a really high-level overview.
45// <http://locklessinc.com/articles/futex_cheat_sheet/> describes some of the
46// operations in a bit more detail than most places.
47// <http://locklessinc.com/articles/mutex_cv_futex/> is the basis of our
48// implementations (before PI).
49// <http://lwn.net/Articles/360699/> has a nice overview of futexes in late 2009
50// (fairly recent compared to everything else...).
51// <https://www.kernel.org/doc/Documentation/pi-futex.txt>,
52// <https://www.kernel.org/doc/Documentation/futex-requeue-pi.txt>,
53// <https://www.kernel.org/doc/Documentation/robust-futexes.txt>,
54// and <https://www.kernel.org/doc/Documentation/robust-futex-ABI.txt> are all
55// useful references.
56// The kernel source (kernel/futex.c) has some useful comments about what the
57// various operations do (except figuring out which argument goes where in the
58// syscall is still confusing).
59// futex(2) is basically useless except for describing the order of the
60// arguments (it only has high-level descriptions of what some of the
61// operations do, and some of them are wrong in Wheezy).
62// glibc's nptl pthreads implementation is the intended user of most of these
63// things, so it is also a good place to look for examples. However, it is all
64// very hard to read because it supports ~20 different kinds of mutexes and
65// several variations of condition variables, and some of the pieces of code
66// are only written in assembly.
67// set_robust_list(2) is wrong in Wheezy (it doesn't actually take a TID
68// argument).
69//
70// Can't use PRIVATE futex operations because they use the pid (or something) as
71// part of the hash.
72//
73// ThreadSanitizer understands how these mutexes etc work. It appears to be able
74// to figure out the happens-before relationship from the __ATOMIC_SEQ_CST
75// atomic primitives.
76//
77// Remember that EAGAIN and EWOUDBLOCK are the same! (ie if you get EAGAIN from
78// FUTEX_WAIT, the docs call it EWOULDBLOCK...)
79
80// Values for an aos_mutex.futex (kernel-mandated):
81// 0 = unlocked
82// TID = locked, not contended
83// |FUTEX_WAITERS = there are waiters (aka contended)
Brian Silverman71c55c52014-08-19 14:31:59 -040084// |FUTEX_OWNER_DIED = old owner died
Brian Silvermandc1eb272014-08-19 14:25:59 -040085//
86// Values for an aos_futex being used directly:
87// 0 = unset
88// 1 = set
89//
90// The value of an aos_condition is just a generation counter.
91
Brian Silverman71c55c52014-08-19 14:31:59 -040092#ifdef AOS_SANITIZER_thread
93extern "C" void AnnotateHappensBefore(const char *file, int line,
94 uintptr_t addr);
95extern "C" void AnnotateHappensAfter(const char *file, int line,
96 uintptr_t addr);
97#define ANNOTATE_HAPPENS_BEFORE(address) \
98 AnnotateHappensBefore(__FILE__, __LINE__, \
99 reinterpret_cast<uintptr_t>(address))
100#define ANNOTATE_HAPPENS_AFTER(address) \
101 AnnotateHappensAfter(__FILE__, __LINE__, reinterpret_cast<uintptr_t>(address))
102#else
103#define ANNOTATE_HAPPENS_BEFORE(address)
104#define ANNOTATE_HAPPENS_AFTER(address)
105#endif
106
Brian Silvermandc1eb272014-08-19 14:25:59 -0400107namespace {
108
Brian Silverman71c55c52014-08-19 14:31:59 -0400109const bool kRobustListDebug = false;
110const bool kLockDebug = false;
111const bool kPrintOperations = false;
112
Brian Silvermandc1eb272014-08-19 14:25:59 -0400113// These sys_futex_* functions are wrappers around syscall(SYS_futex). They each
114// take a specific set of arguments for a given futex operation. They return the
115// result or a negated errno value. -1..-4095 mean errors and not successful
116// results, which is guaranteed by the kernel.
117//
118// They each have optimized versions for ARM EABI (the syscall interface is
119// different for non-EABI ARM, so that is the right thing to test for) that
120// don't go through syscall(2) or errno.
121// These use register variables to get the values in the right registers to
122// actually make the syscall.
123
124// The actual macro that we key off of to use the inline versions or not.
Brian Silverman17426d92018-08-09 11:38:49 -0700125#if defined(__ARM_EABI__)
126#define ARM_EABI_INLINE_SYSCALL 1
127#else
128#define ARM_EABI_INLINE_SYSCALL 0
129#endif
Brian Silvermandc1eb272014-08-19 14:25:59 -0400130
131// Used for FUTEX_WAIT, FUTEX_LOCK_PI, and FUTEX_TRYLOCK_PI.
132inline int sys_futex_wait(int op, aos_futex *addr1, int val1,
133 const struct timespec *timeout) {
134#if ARM_EABI_INLINE_SYSCALL
135 register aos_futex *addr1_reg __asm__("r0") = addr1;
136 register int op_reg __asm__("r1") = op;
137 register int val1_reg __asm__("r2") = val1;
138 register const struct timespec *timeout_reg __asm__("r3") = timeout;
139 register int syscall_number __asm__("r7") = SYS_futex;
140 register int result __asm__("r0");
141 __asm__ volatile("swi #0"
142 : "=r"(result)
143 : "r"(addr1_reg), "r"(op_reg), "r"(val1_reg),
144 "r"(timeout_reg), "r"(syscall_number)
145 : "memory");
146 return result;
147#else
148 const int r = syscall(SYS_futex, addr1, op, val1, timeout);
149 if (r == -1) return -errno;
150 return r;
151#endif
152}
153
154inline int sys_futex_wake(aos_futex *addr1, int val1) {
155#if ARM_EABI_INLINE_SYSCALL
156 register aos_futex *addr1_reg __asm__("r0") = addr1;
157 register int op_reg __asm__("r1") = FUTEX_WAKE;
158 register int val1_reg __asm__("r2") = val1;
159 register int syscall_number __asm__("r7") = SYS_futex;
160 register int result __asm__("r0");
161 __asm__ volatile("swi #0"
162 : "=r"(result)
163 : "r"(addr1_reg), "r"(op_reg), "r"(val1_reg),
164 "r"(syscall_number)
165 : "memory");
166 return result;
167#else
168 const int r = syscall(SYS_futex, addr1, FUTEX_WAKE, val1);
169 if (r == -1) return -errno;
170 return r;
171#endif
172}
173
Brian Silverman71c55c52014-08-19 14:31:59 -0400174inline int sys_futex_cmp_requeue_pi(aos_futex *addr1, int num_wake,
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700175 int num_requeue, aos_futex *m,
176 uint32_t val) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400177#if ARM_EABI_INLINE_SYSCALL
178 register aos_futex *addr1_reg __asm__("r0") = addr1;
179 register int op_reg __asm__("r1") = FUTEX_CMP_REQUEUE_PI;
180 register int num_wake_reg __asm__("r2") = num_wake;
181 register int num_requeue_reg __asm__("r3") = num_requeue;
182 register aos_futex *m_reg __asm__("r4") = m;
183 register uint32_t val_reg __asm__("r5") = val;
184 register int syscall_number __asm__("r7") = SYS_futex;
185 register int result __asm__("r0");
186 __asm__ volatile("swi #0"
187 : "=r"(result)
188 : "r"(addr1_reg), "r"(op_reg), "r"(num_wake_reg),
189 "r"(num_requeue_reg), "r"(m_reg), "r"(val_reg),
190 "r"(syscall_number)
191 : "memory");
192 return result;
193#else
194 const int r = syscall(SYS_futex, addr1, FUTEX_CMP_REQUEUE_PI, num_wake,
195 num_requeue, m, val);
196 if (r == -1) return -errno;
197 return r;
198#endif
199}
200
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700201inline int sys_futex_wait_requeue_pi(aos_condition *addr1, uint32_t start_val,
Brian Silverman71c55c52014-08-19 14:31:59 -0400202 const struct timespec *timeout,
203 aos_futex *m) {
204#if ARM_EABI_INLINE_SYSCALL
205 register aos_condition *addr1_reg __asm__("r0") = addr1;
206 register int op_reg __asm__("r1") = FUTEX_WAIT_REQUEUE_PI;
207 register uint32_t start_val_reg __asm__("r2") = start_val;
208 register const struct timespec *timeout_reg __asm__("r3") = timeout;
209 register aos_futex *m_reg __asm__("r4") = m;
210 register int syscall_number __asm__("r7") = SYS_futex;
211 register int result __asm__("r0");
212 __asm__ volatile("swi #0"
213 : "=r"(result)
214 : "r"(addr1_reg), "r"(op_reg), "r"(start_val_reg),
215 "r"(timeout_reg), "r"(m_reg), "r"(syscall_number)
216 : "memory");
217 return result;
218#else
219 const int r =
220 syscall(SYS_futex, addr1, FUTEX_WAIT_REQUEUE_PI, start_val, timeout, m);
221 if (r == -1) return -errno;
222 return r;
223#endif
224}
225
Brian Silvermandc1eb272014-08-19 14:25:59 -0400226inline int sys_futex_unlock_pi(aos_futex *addr1) {
227#if ARM_EABI_INLINE_SYSCALL
228 register aos_futex *addr1_reg __asm__("r0") = addr1;
229 register int op_reg __asm__("r1") = FUTEX_UNLOCK_PI;
230 register int syscall_number __asm__("r7") = SYS_futex;
231 register int result __asm__("r0");
232 __asm__ volatile("swi #0"
233 : "=r"(result)
234 : "r"(addr1_reg), "r"(op_reg), "r"(syscall_number)
235 : "memory");
236 return result;
237#else
238 const int r = syscall(SYS_futex, addr1, FUTEX_UNLOCK_PI);
239 if (r == -1) return -errno;
240 return r;
241#endif
242}
243
Brian Silverman71c55c52014-08-19 14:31:59 -0400244// Returns the previous value of f.
245inline uint32_t compare_and_swap_val(aos_futex *f, uint32_t before,
246 uint32_t after) {
247#ifdef AOS_SANITIZER_thread
248 // This is a workaround for <https://llvm.org/bugs/show_bug.cgi?id=23176>.
249 // Basically, most of the atomic operations are broken under tsan, but this
250 // particular one isn't.
251 // TODO(Brian): Remove this #ifdef (and the one in compare_and_swap) once we
252 // don't have to worry about tsan with this bug any more.
253 uint32_t before_value = before;
254 __tsan_atomic32_compare_exchange_strong(
255 reinterpret_cast<int32_t *>(f),
256 reinterpret_cast<int32_t *>(&before_value), after,
257 __tsan_memory_order_seq_cst, __tsan_memory_order_seq_cst);
258 return before_value;
259#else
260 return __sync_val_compare_and_swap(f, before, after);
261#endif
Brian Silvermandc1eb272014-08-19 14:25:59 -0400262}
263
Brian Silverman71c55c52014-08-19 14:31:59 -0400264// Returns true if it succeeds and false if it fails.
265inline bool compare_and_swap(aos_futex *f, uint32_t before, uint32_t after) {
266#ifdef AOS_SANITIZER_thread
267 return compare_and_swap_val(f, before, after) == before;
268#else
269 return __sync_bool_compare_and_swap(f, before, after);
270#endif
271}
272
273#ifdef AOS_SANITIZER_thread
274
275// Simple macro for checking something which should always be true.
276// Using the standard CHECK macro isn't safe because failures often result in
277// reentering the mutex locking code, which doesn't work.
278#define SIMPLE_CHECK(expr) \
279 do { \
280 if (!(expr)) { \
281 fprintf(stderr, "%s: %d: SIMPLE_CHECK(" #expr ") failed!\n", __FILE__, \
282 __LINE__); \
283 abort(); \
284 } \
285 } while (false)
286
287// Forcibly initializes the pthread mutex for *m.
288// This sequence of operations is only safe for the simpler kinds of mutexes in
289// glibc's pthreads implementation on Linux.
290void init_pthread_mutex(aos_mutex *m) {
291 // Re-initialize the mutex so the destroy won't fail if it's locked.
292 // tsan ignores this.
293 SIMPLE_CHECK(0 == pthread_mutex_init(&m->pthread_mutex, nullptr));
294 // Destroy the mutex so tsan will forget about it if some now-dead thread
295 // locked it.
296 SIMPLE_CHECK(0 == pthread_mutex_destroy(&m->pthread_mutex));
297
298 // Now actually initialize it, making sure it's process-shareable so it works
299 // correctly across shared memory.
300 pthread_mutexattr_t attr;
301 SIMPLE_CHECK(0 == pthread_mutexattr_init(&attr));
302 SIMPLE_CHECK(0 == pthread_mutexattr_setpshared(&attr, true));
303 SIMPLE_CHECK(0 == pthread_mutex_init(&m->pthread_mutex, &attr));
304 SIMPLE_CHECK(0 == pthread_mutexattr_destroy(&attr));
305}
306
307// Locks the pthread mutex for *m.
308// If a stack trace ever reveals the pthread_mutex_lock call in here blocking,
309// there is a bug in our mutex code or the way somebody is calling it.
310void lock_pthread_mutex(aos_mutex *m) {
311 if (!m->pthread_mutex_init) {
312 init_pthread_mutex(m);
313 m->pthread_mutex_init = true;
314 }
315 SIMPLE_CHECK(0 == pthread_mutex_lock(&m->pthread_mutex));
316}
317
318// Forcibly locks the pthread mutex for *m.
319// This will (somewhat hackily) rip the lock out from underneath somebody else
320// who is already holding it.
321void force_lock_pthread_mutex(aos_mutex *m) {
322 if (!m->pthread_mutex_init) {
323 init_pthread_mutex(m);
324 m->pthread_mutex_init = true;
325 }
326 const int trylock_result = pthread_mutex_trylock(&m->pthread_mutex);
327 SIMPLE_CHECK(trylock_result == 0 || trylock_result == EBUSY);
328 if (trylock_result == 0) {
329 // We're good, so unlock it and then go for a real lock down below.
330 SIMPLE_CHECK(0 == pthread_mutex_unlock(&m->pthread_mutex));
331 } else {
332 // Somebody (should always be somebody else who died with it held) already
333 // has it, so make tsan forget about that.
334 init_pthread_mutex(m);
335 }
336 lock_pthread_mutex(m);
337}
338
339// Unlocks the pthread mutex for *m.
340void unlock_pthread_mutex(aos_mutex *m) {
341 assert(m->pthread_mutex_init);
342 SIMPLE_CHECK(0 == pthread_mutex_unlock(&m->pthread_mutex));
343}
344
345#else
346
347// Empty implementations of all these so the code below doesn't need #ifdefs.
348static inline void lock_pthread_mutex(aos_mutex *) {}
349static inline void force_lock_pthread_mutex(aos_mutex *) {}
350static inline void unlock_pthread_mutex(aos_mutex *) {}
351
352#endif
353
Brian Silvermandc1eb272014-08-19 14:25:59 -0400354pid_t do_get_tid() {
355 pid_t r = syscall(SYS_gettid);
356 assert(r > 0);
357 return r;
358}
359
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360// This gets called by functions before LOG(FATAL)ing with error messages
Austin Schuhf257f3c2019-10-27 21:00:43 -0700361// that would be incorrect if the error was caused by a process forking without
Brian Silvermandc1eb272014-08-19 14:25:59 -0400362// initialize_in_new_thread getting called in the fork.
363void check_cached_tid(pid_t tid) {
364 pid_t actual = do_get_tid();
365 if (tid != actual) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 LOG(FATAL) << "task " << static_cast<intmax_t>(tid) << " forked into "
367 << static_cast<intmax_t>(actual)
368 << " without letting aos_sync know so we're not really sure "
369 "what's going on";
Brian Silvermandc1eb272014-08-19 14:25:59 -0400370 }
371}
372
373// Starts off at 0 in each new thread (because that's what it gets initialized
374// to in most of them or it gets to reset to 0 after a fork by atfork_child()).
Brian Silvermanb47f5552020-10-01 15:08:14 -0700375AOS_THREAD_LOCAL pid_t my_tid = 0;
Brian Silvermandc1eb272014-08-19 14:25:59 -0400376
377// Gets called before the fork(2) wrapper function returns in the child.
378void atfork_child() {
379 // The next time get_tid() is called, it will set everything up again.
380 my_tid = 0;
381}
382
John Park0e699502019-11-20 19:36:05 -0800383void InstallAtforkHook() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700384 PCHECK(pthread_atfork(NULL, NULL, &atfork_child) == 0)
385 << ": pthread_atfork(NULL, NULL, "
386 << reinterpret_cast<void *>(&atfork_child) << ") failed";
Brian Silvermandc1eb272014-08-19 14:25:59 -0400387}
388
389// This gets called to set everything up in a new thread by get_tid().
390void initialize_in_new_thread();
391
392// Gets the current thread's TID and does all of the 1-time initialization the
393// first time it's called in a given thread.
394inline uint32_t get_tid() {
Brian Silverman71c55c52014-08-19 14:31:59 -0400395 if (__builtin_expect(my_tid == 0, false)) {
Brian Silvermandc1eb272014-08-19 14:25:59 -0400396 initialize_in_new_thread();
397 }
398 static_assert(sizeof(my_tid) <= sizeof(uint32_t), "pid_t is too big");
399 return static_cast<uint32_t>(my_tid);
400}
401
Brian Silverman71c55c52014-08-19 14:31:59 -0400402// Contains all of the stuff for dealing with the robust list. Nothing outside
403// this namespace should touch anything inside it except Init, Adder, and
404// Remover.
405namespace my_robust_list {
406
407static_assert(offsetof(aos_mutex, next) == 0,
408 "Our math all assumes that the beginning of a mutex and its next "
409 "pointer are at the same place in memory.");
410
411// Our version of robust_list_head.
412// This is copied from the kernel header because that's a pretty stable ABI (and
413// any changes will be backwards compatible anyways) and we want ours to have
414// different types.
415// The uintptr_ts are &next of the elements in the list (with stuff |ed in).
416struct aos_robust_list_head {
417 uintptr_t next;
418 long futex_offset;
419 uintptr_t pending_next;
420};
421
422static_assert(offsetof(aos_robust_list_head, next) ==
423 offsetof(robust_list_head, list),
424 "Our aos_robust_list_head doesn't match the kernel's");
425static_assert(offsetof(aos_robust_list_head, futex_offset) ==
426 offsetof(robust_list_head, futex_offset),
427 "Our aos_robust_list_head doesn't match the kernel's");
428static_assert(offsetof(aos_robust_list_head, pending_next) ==
429 offsetof(robust_list_head, list_op_pending),
430 "Our aos_robust_list_head doesn't match the kernel's");
431static_assert(sizeof(aos_robust_list_head) == sizeof(robust_list_head),
432 "Our aos_robust_list_head doesn't match the kernel's");
433
Brian Silvermanb47f5552020-10-01 15:08:14 -0700434AOS_THREAD_LOCAL aos_robust_list_head robust_head;
Brian Silverman71c55c52014-08-19 14:31:59 -0400435
436// Extra offset between mutex values and where we point to for their robust list
437// entries (from SetRobustListOffset).
438uintptr_t robust_list_offset = 0;
439
440// The value to OR each pointer's value with whenever putting it into the robust
441// list (technically only if it's PI, but all of ours are, so...).
442static const uintptr_t kRobustListOr = 1;
443
444// Returns the value which goes into a next variable to represent the head.
445inline uintptr_t robust_head_next_value() {
446 return reinterpret_cast<uintptr_t>(&robust_head.next);
447}
448// Returns true iff next represents the head.
449inline bool next_is_head(uintptr_t next) {
450 return next == robust_head_next_value();
451}
452// Returns the (psuedo-)mutex corresponding to the head.
453// This does NOT have a previous pointer, so be careful with the return value.
454inline aos_mutex *robust_head_mutex() {
455 return reinterpret_cast<aos_mutex *>(robust_head_next_value());
456}
457
458inline uintptr_t mutex_to_next(aos_mutex *m) {
459 return (reinterpret_cast<uintptr_t>(&m->next) + robust_list_offset) |
460 kRobustListOr;
461}
462inline aos_mutex *next_to_mutex(uintptr_t next) {
463 if (__builtin_expect(robust_list_offset != 0, false) && next_is_head(next)) {
464 // We don't offset the head pointer, so be careful.
465 return reinterpret_cast<aos_mutex *>(next);
466 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700467 return reinterpret_cast<aos_mutex *>((next & ~kRobustListOr) -
468 robust_list_offset);
Brian Silverman71c55c52014-08-19 14:31:59 -0400469}
470
471// Sets up the robust list for each thread.
472void Init() {
473 // It starts out just pointing back to itself.
474 robust_head.next = robust_head_next_value();
475 robust_head.futex_offset = static_cast<ssize_t>(offsetof(aos_mutex, futex)) -
476 static_cast<ssize_t>(offsetof(aos_mutex, next));
477 robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478 PCHECK(syscall(SYS_set_robust_list, robust_head_next_value(),
479 sizeof(robust_head)) == 0)
480 << ": set_robust_list(" << reinterpret_cast<void *>(robust_head.next)
481 << ", " << sizeof(robust_head) << ") failed";
Brian Silverman71c55c52014-08-19 14:31:59 -0400482 if (kRobustListDebug) {
483 printf("%" PRId32 ": init done\n", get_tid());
484 }
485}
486
487// Updating the offset with locked mutexes is important during robustness
488// testing, because there are mutexes which are locked before this is set to a
489// non-0 value and then unlocked after it is changed back. However, to make sure
490// the code works correctly when manipulating the next pointer of the last of
491// those mutexes, all of their next values have to be adjusted appropriately.
492void SetRobustListOffset(uintptr_t offset) {
493 const uintptr_t offset_change = offset - robust_list_offset;
494 robust_list_offset = offset;
495 aos_mutex *m = robust_head_mutex();
496 // Update the offset contained in each of the mutexes which is already locked.
497 while (!next_is_head(m->next)) {
498 m->next += offset_change;
499 m = next_to_mutex(m->next);
500 }
501}
502
503bool HaveLockedMutexes() {
504 return robust_head.next != robust_head_next_value();
505}
506
507// Handles adding a mutex to the robust list.
508// The idea is to create one of these at the beginning of a function that needs
509// to do this and then call Add() iff it should actually be added.
510class Adder {
511 public:
512 Adder(aos_mutex *m) : m_(m) {
513 assert(robust_head.pending_next == 0);
514 if (kRobustListDebug) {
515 printf("%" PRId32 ": maybe add %p\n", get_tid(), m_);
516 }
517 robust_head.pending_next = mutex_to_next(m);
518 aos_compiler_memory_barrier();
519 }
520 ~Adder() {
521 assert(robust_head.pending_next == mutex_to_next(m_));
522 if (kRobustListDebug) {
523 printf("%" PRId32 ": done maybe add %p, n=%p p=%p\n", get_tid(), m_,
524 next_to_mutex(m_->next), m_->previous);
525 }
526 aos_compiler_memory_barrier();
527 robust_head.pending_next = 0;
528 }
529
530 void Add() {
531 assert(robust_head.pending_next == mutex_to_next(m_));
532 if (kRobustListDebug) {
533 printf("%" PRId32 ": adding %p\n", get_tid(), m_);
534 }
535 const uintptr_t old_head_next_value = robust_head.next;
536
537 m_->next = old_head_next_value;
538 aos_compiler_memory_barrier();
539 robust_head.next = mutex_to_next(m_);
540
541 m_->previous = robust_head_mutex();
542 if (!next_is_head(old_head_next_value)) {
543 // robust_head's psuedo-mutex doesn't have a previous pointer to update.
544 next_to_mutex(old_head_next_value)->previous = m_;
545 }
546 aos_compiler_memory_barrier();
547 if (kRobustListDebug) {
548 printf("%" PRId32 ": done adding %p\n", get_tid(), m_);
549 }
550 }
551
552 private:
553 aos_mutex *const m_;
554
555 DISALLOW_COPY_AND_ASSIGN(Adder);
556};
557
558// Handles removing a mutex from the robust list.
559// The idea is to create one of these at the beginning of a function that needs
560// to do this.
561class Remover {
562 public:
563 Remover(aos_mutex *m) {
564 assert(robust_head.pending_next == 0);
565 if (kRobustListDebug) {
566 printf("%" PRId32 ": beginning to remove %p, n=%p p=%p\n", get_tid(), m,
567 next_to_mutex(m->next), m->previous);
568 }
569 robust_head.pending_next = mutex_to_next(m);
570 aos_compiler_memory_barrier();
571
572 aos_mutex *const previous = m->previous;
573 const uintptr_t next_value = m->next;
574
575 previous->next = m->next;
576 if (!next_is_head(next_value)) {
577 // robust_head's psuedo-mutex doesn't have a previous pointer to update.
578 next_to_mutex(next_value)->previous = previous;
579 }
580
581 if (kRobustListDebug) {
582 printf("%" PRId32 ": done removing %p\n", get_tid(), m);
583 }
584 }
585 ~Remover() {
586 assert(robust_head.pending_next != 0);
587 aos_compiler_memory_barrier();
588 robust_head.pending_next = 0;
589 if (kRobustListDebug) {
590 printf("%" PRId32 ": done with removal\n", get_tid());
591 }
592 }
593
594 private:
595 DISALLOW_COPY_AND_ASSIGN(Remover);
596};
597
598} // namespace my_robust_list
599
Brian Silvermandc1eb272014-08-19 14:25:59 -0400600void initialize_in_new_thread() {
601 // No synchronization necessary in most of this because it's all thread-local!
602
603 my_tid = do_get_tid();
604
John Park9372a682019-11-27 18:07:48 -0800605 static absl::once_flag once;
606 absl::call_once(once, InstallAtforkHook);
Brian Silverman71c55c52014-08-19 14:31:59 -0400607
608 my_robust_list::Init();
Brian Silvermandc1eb272014-08-19 14:25:59 -0400609}
610
Brian Silverman71c55c52014-08-19 14:31:59 -0400611FutexAccessorObserver before_observer = nullptr, after_observer = nullptr;
612
613// RAII class which runs before_observer during construction and after_observer
614// during destruction.
615class RunObservers {
616 public:
617 template <class T>
618 RunObservers(T *address, bool write)
619 : address_(static_cast<void *>(
620 const_cast<typename ::std::remove_cv<T>::type *>(address))),
621 write_(write) {
622 if (__builtin_expect(before_observer != nullptr, false)) {
623 before_observer(address_, write_);
624 }
625 }
626 ~RunObservers() {
627 if (__builtin_expect(after_observer != nullptr, false)) {
628 after_observer(address_, write_);
629 }
630 }
631
632 private:
633 void *const address_;
634 const bool write_;
635
636 DISALLOW_COPY_AND_ASSIGN(RunObservers);
637};
638
639// Finishes the locking of a mutex by potentially clearing FUTEX_OWNER_DIED in
640// the futex and returning the correct value.
641inline int mutex_finish_lock(aos_mutex *m) {
642 const uint32_t value = __atomic_load_n(&m->futex, __ATOMIC_ACQUIRE);
643 if (__builtin_expect((value & FUTEX_OWNER_DIED) != 0, false)) {
644 __atomic_and_fetch(&m->futex, ~FUTEX_OWNER_DIED, __ATOMIC_RELAXED);
645 force_lock_pthread_mutex(m);
646 return 1;
647 } else {
648 lock_pthread_mutex(m);
649 return 0;
650 }
651}
652
653// Split out separately from mutex_get so condition_wait can call it and use its
654// own my_robust_list::Adder.
Brian Silvermandc1eb272014-08-19 14:25:59 -0400655inline int mutex_do_get(aos_mutex *m, bool signals_fail,
Brian Silverman71c55c52014-08-19 14:31:59 -0400656 const struct timespec *timeout, uint32_t tid) {
657 RunObservers run_observers(m, true);
658 if (kPrintOperations) {
659 printf("%" PRId32 ": %p do_get\n", tid, m);
660 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400661
662 while (true) {
663 // If the atomic 0->TID transition fails.
664 if (!compare_and_swap(&m->futex, 0, tid)) {
665 // Wait in the kernel, which handles atomically ORing in FUTEX_WAITERS
666 // before actually sleeping.
667 const int ret = sys_futex_wait(FUTEX_LOCK_PI, &m->futex, 1, timeout);
668 if (ret != 0) {
669 if (timeout != NULL && ret == -ETIMEDOUT) {
670 return 3;
671 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400672 if (__builtin_expect(ret == -EINTR, true)) {
Brian Silvermandc1eb272014-08-19 14:25:59 -0400673 if (signals_fail) {
674 return 2;
675 } else {
676 continue;
677 }
678 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400679 my_robust_list::robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700680 CHECK_NE(ret, -EDEADLK) << ": multiple lock of " << m << " by " << tid;
681
682 errno = -ret;
683 PLOG(FATAL) << "FUTEX_LOCK_PI(" << &m->futex
684 << "(=" << __atomic_load_n(&m->futex, __ATOMIC_SEQ_CST)
685 << "), 1, " << timeout << ") failed";
Brian Silvermandc1eb272014-08-19 14:25:59 -0400686 } else {
Brian Silverman71c55c52014-08-19 14:31:59 -0400687 if (kLockDebug) {
688 printf("%" PRId32 ": %p kernel lock done\n", tid, m);
689 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400690 // The kernel already handled setting the value to our TID (ish).
691 break;
692 }
693 } else {
Brian Silverman71c55c52014-08-19 14:31:59 -0400694 if (kLockDebug) {
695 printf("%" PRId32 ": %p fast lock done\n", tid, m);
696 }
697 lock_pthread_mutex(m);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400698 // Fastpath succeeded, so no need to call into the kernel.
Brian Silverman71c55c52014-08-19 14:31:59 -0400699 // Because this is the fastpath, it's a good idea to avoid even having to
700 // load the value again down below.
701 return 0;
Brian Silvermandc1eb272014-08-19 14:25:59 -0400702 }
703 }
704
Brian Silverman71c55c52014-08-19 14:31:59 -0400705 return mutex_finish_lock(m);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400706}
707
708// The common implementation for everything that wants to lock a mutex.
709// If signals_fail is false, the function will try again if the wait syscall is
710// interrupted by a signal.
711// timeout can be NULL for no timeout.
712inline int mutex_get(aos_mutex *m, bool signals_fail,
713 const struct timespec *timeout) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400714 const uint32_t tid = get_tid();
715 my_robust_list::Adder adder(m);
716 const int r = mutex_do_get(m, signals_fail, timeout, tid);
717 if (r == 0 || r == 1) adder.Add();
Brian Silvermandc1eb272014-08-19 14:25:59 -0400718 return r;
719}
720
721// The common implementation for broadcast and signal.
722// number_requeue is the number of waiters to requeue (probably INT_MAX or 0). 1
723// will always be woken.
Brian Silverman71c55c52014-08-19 14:31:59 -0400724void condition_wake(aos_condition *c, aos_mutex *m, int number_requeue) {
725 RunObservers run_observers(c, true);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400726 // Make it so that anybody just going to sleep won't.
727 // This is where we might accidentally wake more than just 1 waiter with 1
728 // signal():
729 // 1 already sleeping will be woken but n might never actually make it to
730 // sleep in the kernel because of this.
Brian Silverman71c55c52014-08-19 14:31:59 -0400731 uint32_t new_value = __atomic_add_fetch(c, 1, __ATOMIC_SEQ_CST);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400732
Brian2a4294f2019-06-12 20:23:32 -0700733 while (true) {
734 // This really wants to be FUTEX_REQUEUE_PI, but the kernel doesn't have
735 // that... However, the code to support that is in the kernel, so it might
736 // be a good idea to patch it to support that and use it iff it's there.
737 const int ret =
738 sys_futex_cmp_requeue_pi(c, 1, number_requeue, &m->futex, new_value);
739 if (ret < 0) {
740 // If the value got changed out from under us (aka somebody else did a
741 // condition_wake).
742 if (__builtin_expect(ret == -EAGAIN, true)) {
743 // If we're doing a broadcast, the other guy might have done a signal
744 // instead, so we have to try again.
745 // If we're doing a signal, we have to go again to make sure that 2
746 // signals wake 2 processes.
747 new_value = __atomic_load_n(c, __ATOMIC_RELAXED);
748 continue;
Brian Silverman71c55c52014-08-19 14:31:59 -0400749 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400750 my_robust_list::robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700751 errno = -ret;
752 PLOG(FATAL) << "FUTEX_CMP_REQUEUE_PI(" << c << ", 1, " << number_requeue
753 << ", " << &m->futex << ", *" << c << ") failed";
Brian2a4294f2019-06-12 20:23:32 -0700754 } else {
755 return;
Brian Silverman71c55c52014-08-19 14:31:59 -0400756 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400757 }
758}
759
760} // namespace
761
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700762int mutex_lock(aos_mutex *m) { return mutex_get(m, true, NULL); }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400763int mutex_lock_timeout(aos_mutex *m, const struct timespec *timeout) {
764 return mutex_get(m, true, timeout);
765}
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700766int mutex_grab(aos_mutex *m) { return mutex_get(m, false, NULL); }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400767
768void mutex_unlock(aos_mutex *m) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400769 RunObservers run_observers(m, true);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400770 const uint32_t tid = get_tid();
Brian Silverman71c55c52014-08-19 14:31:59 -0400771 if (kPrintOperations) {
772 printf("%" PRId32 ": %p unlock\n", tid, m);
773 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400774
775 const uint32_t value = __atomic_load_n(&m->futex, __ATOMIC_SEQ_CST);
Brian Silverman71c55c52014-08-19 14:31:59 -0400776 if (__builtin_expect((value & FUTEX_TID_MASK) != tid, false)) {
777 my_robust_list::robust_head.pending_next = 0;
Brian Silvermandc1eb272014-08-19 14:25:59 -0400778 check_cached_tid(tid);
779 if ((value & FUTEX_TID_MASK) == 0) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780 LOG(FATAL) << "multiple unlock of aos_mutex " << m << " by " << tid;
Brian Silvermandc1eb272014-08-19 14:25:59 -0400781 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700782 LOG(FATAL) << "aos_mutex " << m << " is locked by "
783 << (value & FUTEX_TID_MASK) << ", not " << tid;
Brian Silvermandc1eb272014-08-19 14:25:59 -0400784 }
785 }
786
Brian Silverman71c55c52014-08-19 14:31:59 -0400787 my_robust_list::Remover remover(m);
788 unlock_pthread_mutex(m);
789
Brian Silvermandc1eb272014-08-19 14:25:59 -0400790 // If the atomic TID->0 transition fails (ie FUTEX_WAITERS is set),
791 if (!compare_and_swap(&m->futex, tid, 0)) {
792 // The kernel handles everything else.
793 const int ret = sys_futex_unlock_pi(&m->futex);
794 if (ret != 0) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400795 my_robust_list::robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700796 errno = -ret;
797 PLOG(FATAL) << "FUTEX_UNLOCK_PI(" << (&m->futex) << ") failed";
Brian Silvermandc1eb272014-08-19 14:25:59 -0400798 }
799 } else {
800 // There aren't any waiters, so no need to call into the kernel.
801 }
802}
803
804int mutex_trylock(aos_mutex *m) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400805 RunObservers run_observers(m, true);
806 const uint32_t tid = get_tid();
807 if (kPrintOperations) {
808 printf("%" PRId32 ": %p trylock\n", tid, m);
809 }
810 my_robust_list::Adder adder(m);
811
Brian Silvermandc1eb272014-08-19 14:25:59 -0400812 // Try an atomic 0->TID transition.
Brian Silverman71c55c52014-08-19 14:31:59 -0400813 uint32_t c = compare_and_swap_val(&m->futex, 0, tid);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400814
815 if (c != 0) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400816 if (__builtin_expect((c & FUTEX_OWNER_DIED) == 0, true)) {
817 // Somebody else had it locked; we failed.
818 return 4;
819 } else {
820 // FUTEX_OWNER_DIED was set, so we have to call into the kernel to deal
821 // with resetting it.
822 const int ret = sys_futex_wait(FUTEX_TRYLOCK_PI, &m->futex, 0, NULL);
823 if (ret == 0) {
824 adder.Add();
825 // Only clear the owner died if somebody else didn't do the recovery
826 // and then unlock before our TRYLOCK happened.
827 return mutex_finish_lock(m);
828 } else {
829 // EWOULDBLOCK means that somebody else beat us to it.
830 if (__builtin_expect(ret == -EWOULDBLOCK, true)) {
831 return 4;
832 }
833 my_robust_list::robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700834 errno = -ret;
835 PLOG(FATAL) << "FUTEX_TRYLOCK_PI(" << (&m->futex)
836 << ", 0, NULL) failed";
Brian Silverman71c55c52014-08-19 14:31:59 -0400837 }
838 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400839 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400840
841 lock_pthread_mutex(m);
842 adder.Add();
Brian Silvermandc1eb272014-08-19 14:25:59 -0400843 return 0;
844}
845
846bool mutex_islocked(const aos_mutex *m) {
847 const uint32_t tid = get_tid();
848
849 const uint32_t value = __atomic_load_n(&m->futex, __ATOMIC_RELAXED);
850 return (value & FUTEX_TID_MASK) == tid;
851}
852
Brian Silverman27af1f62019-11-18 12:04:48 -0800853void death_notification_init(aos_mutex *m) {
854 const uint32_t tid = get_tid();
855 if (kPrintOperations) {
856 printf("%" PRId32 ": %p death_notification start\n", tid, m);
857 }
858 my_robust_list::Adder adder(m);
859 {
860 RunObservers run_observers(m, true);
861 CHECK(compare_and_swap(&m->futex, 0, tid));
862 }
863 adder.Add();
864}
865
866void death_notification_release(aos_mutex *m) {
867 RunObservers run_observers(m, true);
868
869#ifndef NDEBUG
870 // Verify it's "locked", like it should be.
871 {
872 const uint32_t tid = get_tid();
873 if (kPrintOperations) {
874 printf("%" PRId32 ": %p death_notification release\n", tid, m);
875 }
876 const uint32_t value = __atomic_load_n(&m->futex, __ATOMIC_SEQ_CST);
877 assert((value & ~FUTEX_WAITERS) == tid);
878 }
879#endif
880
881 my_robust_list::Remover remover(m);
882 ANNOTATE_HAPPENS_BEFORE(m);
883 const int ret = sys_futex_unlock_pi(&m->futex);
884 if (ret != 0) {
885 my_robust_list::robust_head.pending_next = 0;
886 errno = -ret;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700887 PLOG(FATAL) << "FUTEX_UNLOCK_PI(" << &m->futex << ") failed";
Brian Silverman27af1f62019-11-18 12:04:48 -0800888 }
889}
890
Austin Schuh0ad2b6f2019-06-09 21:27:07 -0700891int condition_wait(aos_condition *c, aos_mutex *m, struct timespec *end_time) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400892 RunObservers run_observers(c, false);
893 const uint32_t tid = get_tid();
Brian Silvermandc1eb272014-08-19 14:25:59 -0400894 const uint32_t wait_start = __atomic_load_n(c, __ATOMIC_SEQ_CST);
895
896 mutex_unlock(m);
897
Brian Silverman71c55c52014-08-19 14:31:59 -0400898 my_robust_list::Adder adder(m);
899
Brian Silvermandc1eb272014-08-19 14:25:59 -0400900 while (true) {
901 // Wait in the kernel iff the value of it doesn't change (ie somebody else
902 // does a wake) from before we unlocked the mutex.
Austin Schuh0ad2b6f2019-06-09 21:27:07 -0700903 int ret = sys_futex_wait_requeue_pi(c, wait_start, end_time, &m->futex);
904
Brian Silvermandc1eb272014-08-19 14:25:59 -0400905 if (ret != 0) {
Austin Schuh0ad2b6f2019-06-09 21:27:07 -0700906 // Timed out waiting. Signal that back up to the user.
907 if (__builtin_expect(ret == -ETIMEDOUT, true)) {
908 // We have to relock it ourself because the kernel didn't do it.
909 const int r = mutex_do_get(m, false, nullptr, tid);
910 assert(__builtin_expect(r == 0 || r == 1, true));
911 adder.Add();
912
913 // OWNER_DIED takes priority. Pass it on if we found it.
914 if (r == 1) return r;
915 // Otherwise communicate that we were interrupted.
916 return -1;
917 }
918
Brian Silvermandc1eb272014-08-19 14:25:59 -0400919 // If it failed because somebody else did a wake and changed the value
920 // before we actually made it to sleep.
Brian Silverman71c55c52014-08-19 14:31:59 -0400921 if (__builtin_expect(ret == -EAGAIN, true)) {
922 // There's no need to unconditionally set FUTEX_WAITERS here if we're
923 // using REQUEUE_PI because the kernel automatically does that in the
924 // REQUEUE_PI iff it requeued anybody.
925 // If we're not using REQUEUE_PI, then everything is just normal locks
926 // etc, so there's no need to do anything special there either.
Brian Silvermandc1eb272014-08-19 14:25:59 -0400927
928 // We have to relock it ourself because the kernel didn't do it.
Brian Silverman71c55c52014-08-19 14:31:59 -0400929 const int r = mutex_do_get(m, false, nullptr, tid);
930 assert(__builtin_expect(r == 0 || r == 1, true));
931 adder.Add();
Brian Silvermandc1eb272014-08-19 14:25:59 -0400932 return r;
933 }
934 // Try again if it was because of a signal.
Austin Schuh0ad2b6f2019-06-09 21:27:07 -0700935 if (__builtin_expect((ret == -EINTR), true)) {
936 continue;
937 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400938 my_robust_list::robust_head.pending_next = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700939 errno = -ret;
940 PLOG(FATAL) << "FUTEX_WAIT_REQUEUE_PI(" << c << ", " << wait_start << ", "
941 << (&m->futex) << ") failed";
Brian Silvermandc1eb272014-08-19 14:25:59 -0400942 } else {
Brian2a4294f2019-06-12 20:23:32 -0700943 // Record that the kernel relocked it for us.
944 lock_pthread_mutex(m);
Brian Silverman71c55c52014-08-19 14:31:59 -0400945
Austin Schuh0ad2b6f2019-06-09 21:27:07 -0700946 // We succeeded in waiting, and the kernel took care of locking the
947 // mutex
Brian Silverman71c55c52014-08-19 14:31:59 -0400948 // for us and setting FUTEX_WAITERS iff it needed to (for REQUEUE_PI).
949
950 adder.Add();
951
952 const uint32_t value = __atomic_load_n(&m->futex, __ATOMIC_RELAXED);
953 if (__builtin_expect((value & FUTEX_OWNER_DIED) != 0, false)) {
954 __atomic_and_fetch(&m->futex, ~FUTEX_OWNER_DIED, __ATOMIC_RELAXED);
955 return 1;
956 } else {
957 return 0;
958 }
Brian Silvermandc1eb272014-08-19 14:25:59 -0400959 }
960 }
961}
962
963void condition_signal(aos_condition *c, aos_mutex *m) {
964 condition_wake(c, m, 0);
965}
966
967void condition_broadcast(aos_condition *c, aos_mutex *m) {
968 condition_wake(c, m, INT_MAX);
969}
970
971int futex_wait_timeout(aos_futex *m, const struct timespec *timeout) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400972 RunObservers run_observers(m, false);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400973 const int ret = sys_futex_wait(FUTEX_WAIT, m, 0, timeout);
974 if (ret != 0) {
975 if (ret == -EINTR) {
976 return 1;
977 } else if (ret == -ETIMEDOUT) {
978 return 2;
979 } else if (ret != -EWOULDBLOCK) {
980 errno = -ret;
981 return -1;
982 }
983 }
Brian Silverman71c55c52014-08-19 14:31:59 -0400984 ANNOTATE_HAPPENS_AFTER(m);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400985 return 0;
986}
987
988int futex_wait(aos_futex *m) { return futex_wait_timeout(m, NULL); }
989
990int futex_set_value(aos_futex *m, uint32_t value) {
Brian Silverman71c55c52014-08-19 14:31:59 -0400991 RunObservers run_observers(m, false);
992 ANNOTATE_HAPPENS_BEFORE(m);
Brian Silvermandc1eb272014-08-19 14:25:59 -0400993 __atomic_store_n(m, value, __ATOMIC_SEQ_CST);
994 const int r = sys_futex_wake(m, INT_MAX - 4096);
995 if (__builtin_expect(
Brian Silverman71c55c52014-08-19 14:31:59 -0400996 static_cast<unsigned int>(r) > static_cast<unsigned int>(-4096),
997 false)) {
Brian Silvermandc1eb272014-08-19 14:25:59 -0400998 errno = -r;
999 return -1;
1000 } else {
1001 return r;
1002 }
1003}
1004
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001005int futex_set(aos_futex *m) { return futex_set_value(m, 1); }
Brian Silvermandc1eb272014-08-19 14:25:59 -04001006
1007int futex_unset(aos_futex *m) {
1008 return !__atomic_exchange_n(m, 0, __ATOMIC_SEQ_CST);
1009}
Brian Silverman71c55c52014-08-19 14:31:59 -04001010
1011namespace aos {
1012namespace linux_code {
1013namespace ipc_lib {
1014
1015// Sets functions to run befor eand after all futex operations.
1016// This is important when doing robustness testing because the memory has to be
1017// made writable for the whole futex operation, otherwise it never succeeds.
1018void SetFutexAccessorObservers(FutexAccessorObserver before,
1019 FutexAccessorObserver after) {
1020 before_observer = before;
1021 after_observer = after;
1022}
1023
1024// Sets an extra offset between mutexes and the value we use for them in the
1025// robust list (only the forward pointers). This is used to work around a kernel
1026// bug by keeping a second set of mutexes which is always writable so the kernel
1027// won't go into an infinite loop when trying to unlock them.
1028void SetRobustListOffset(ptrdiff_t offset) {
1029 my_robust_list::SetRobustListOffset(offset);
1030}
1031
1032// Returns true iff there are any mutexes locked by the current thread.
1033// This is mainly useful for testing.
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001034bool HaveLockedMutexes() { return my_robust_list::HaveLockedMutexes(); }
Brian Silverman71c55c52014-08-19 14:31:59 -04001035
1036} // namespace ipc_lib
1037} // namespace linux_code
1038} // namespace aos