fix fallback checks for kernels without private futex support
[musl] / src / thread / synccall.c
1 #include "pthread_impl.h"
2 #include <semaphore.h>
3 #include <unistd.h>
4
5 static struct chain {
6         struct chain *next;
7         sem_t sem, sem2;
8 } *head, *cur;
9
10 static void (*callback)(void *), *context;
11 static int chainlen;
12 static sem_t chainlock, chaindone;
13
14 static void handler(int sig, siginfo_t *si, void *ctx)
15 {
16         struct chain ch;
17         int old_errno = errno;
18
19         if (chainlen == libc.threads_minus_1) return;
20
21         sigqueue(getpid(), SIGSYNCCALL, (union sigval){0});
22
23         sem_init(&ch.sem, 0, 0);
24         sem_init(&ch.sem2, 0, 0);
25
26         while (sem_wait(&chainlock));
27         ch.next = head;
28         head = &ch;
29         if (++chainlen == libc.threads_minus_1) sem_post(&chaindone);
30         sem_post(&chainlock);
31
32         while (sem_wait(&ch.sem));
33         callback(context);
34         sem_post(&ch.sem2);
35         while (sem_wait(&ch.sem));
36
37         errno = old_errno;
38 }
39
40 void __synccall(void (*func)(void *), void *ctx)
41 {
42         struct sigaction sa;
43         struct chain *next;
44         sigset_t oldmask;
45
46         if (!libc.threads_minus_1) {
47                 func(ctx);
48                 return;
49         }
50
51         __inhibit_ptc();
52
53         __block_all_sigs(&oldmask);
54
55         sem_init(&chaindone, 0, 0);
56         sem_init(&chainlock, 0, 1);
57         chainlen = 0;
58         head = 0;
59         callback = func;
60         context = ctx;
61
62         sa.sa_flags = SA_SIGINFO | SA_RESTART;
63         sa.sa_sigaction = handler;
64         sigfillset(&sa.sa_mask);
65         __libc_sigaction(SIGSYNCCALL, &sa, 0);
66
67         sigqueue(getpid(), SIGSYNCCALL, (union sigval){0});
68         while (sem_wait(&chaindone));
69
70         sa.sa_flags = 0;
71         sa.sa_handler = SIG_IGN;
72         __libc_sigaction(SIGSYNCCALL, &sa, 0);
73
74         for (cur=head; cur; cur=cur->next) {
75                 sem_post(&cur->sem);
76                 while (sem_wait(&cur->sem2));
77         }
78         func(ctx);
79
80         for (cur=head; cur; cur=next) {
81                 next = cur->next;
82                 sem_post(&cur->sem);
83         }
84
85         __restore_sigs(&oldmask);
86
87         __release_ptc();
88 }