musl: fix locking synchronization bug
[oweals/openwrt.git] / toolchain / musl / patches / 500-0002-don-t-use-libc.threads_minus_1-as-relaxed-atomic-for.patch
1 From e01b5939b38aea5ecbe41670643199825874b26c Mon Sep 17 00:00:00 2001
2 From: Rich Felker <dalias@aerifal.cx>
3 Date: Thu, 21 May 2020 23:32:45 -0400
4 Subject: [PATCH 2/4] don't use libc.threads_minus_1 as relaxed atomic for
5  skipping locks
6
7 after all but the last thread exits, the next thread to observe
8 libc.threads_minus_1==0 and conclude that it can skip locking fails to
9 synchronize with any changes to memory that were made by the
10 last-exiting thread. this can produce data races.
11
12 on some archs, at least x86, memory synchronization is unlikely to be
13 a problem; however, with the inline locks in malloc, skipping the lock
14 also eliminated the compiler barrier, and caused code that needed to
15 re-check chunk in-use bits after obtaining the lock to reuse a stale
16 value, possibly from before the process became single-threaded. this
17 in turn produced corruption of the heap state.
18
19 some uses of libc.threads_minus_1 remain, especially for allocation of
20 new TLS in the dynamic linker; otherwise, it could be removed
21 entirely. it's made non-volatile to reflect that the remaining
22 accesses are only made under lock on the thread list.
23
24 instead of libc.threads_minus_1, libc.threaded is now used for
25 skipping locks. the difference is that libc.threaded is permanently
26 true once an additional thread has been created. this will produce
27 some performance regression in processes that are mostly
28 single-threaded but occasionally creating threads. in the future it
29 may be possible to bring back the full lock-skipping, but more care
30 needs to be taken to produce a safe design.
31 ---
32  src/internal/libc.h | 2 +-
33  src/malloc/malloc.c | 2 +-
34  src/thread/__lock.c | 2 +-
35  3 files changed, 3 insertions(+), 3 deletions(-)
36
37 --- a/src/internal/libc.h
38 +++ b/src/internal/libc.h
39 @@ -21,7 +21,7 @@ struct __libc {
40         int can_do_threads;
41         int threaded;
42         int secure;
43 -       volatile int threads_minus_1;
44 +       int threads_minus_1;
45         size_t *auxv;
46         struct tls_module *tls_head;
47         size_t tls_size, tls_align, tls_cnt;
48 --- a/src/malloc/malloc.c
49 +++ b/src/malloc/malloc.c
50 @@ -26,7 +26,7 @@ int __malloc_replaced;
51  
52  static inline void lock(volatile int *lk)
53  {
54 -       if (libc.threads_minus_1)
55 +       if (libc.threaded)
56                 while(a_swap(lk, 1)) __wait(lk, lk+1, 1, 1);
57  }
58  
59 --- a/src/thread/__lock.c
60 +++ b/src/thread/__lock.c
61 @@ -18,7 +18,7 @@
62  
63  void __lock(volatile int *l)
64  {
65 -       if (!libc.threads_minus_1) return;
66 +       if (!libc.threaded) return;
67         /* fast path: INT_MIN for the lock, +1 for the congestion */
68         int current = a_cas(l, 0, INT_MIN + 1);
69         if (!current) return;