clean up sloppy nested inclusion from pthread_impl.h
[musl] / src / thread / synccall.c
1 #include "pthread_impl.h"
2 #include <semaphore.h>
3 #include <string.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         pthread_t self = __pthread_self();
18         int old_errno = errno;
19
20         if (chainlen == libc.threads_minus_1) return;
21
22         sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
23
24         /* Threads which have already decremented themselves from the
25          * thread count must not act. Block further receipt of signals
26          * and return. */
27         if (self->dead) {
28                 memset(&((ucontext_t *)ctx)->uc_sigmask, -1, 8);
29                 errno = old_errno;
30                 return;
31         }
32
33         sem_init(&ch.sem, 0, 0);
34         sem_init(&ch.sem2, 0, 0);
35
36         while (sem_wait(&chainlock));
37         ch.next = head;
38         head = &ch;
39         if (++chainlen == libc.threads_minus_1) sem_post(&chaindone);
40         sem_post(&chainlock);
41
42         while (sem_wait(&ch.sem));
43         callback(context);
44         sem_post(&ch.sem2);
45         while (sem_wait(&ch.sem));
46
47         errno = old_errno;
48 }
49
50 void __synccall(void (*func)(void *), void *ctx)
51 {
52         pthread_t self;
53         struct sigaction sa;
54         struct chain *next;
55         uint64_t oldmask;
56
57         if (!libc.threads_minus_1) {
58                 func(ctx);
59                 return;
60         }
61
62         __inhibit_ptc();
63
64         __syscall(SYS_rt_sigprocmask, SIG_BLOCK, SIGALL_SET,
65                 &oldmask, __SYSCALL_SSLEN);
66
67         sem_init(&chaindone, 0, 0);
68         sem_init(&chainlock, 0, 1);
69         chainlen = 0;
70         callback = func;
71         context = ctx;
72
73         sa.sa_flags = SA_SIGINFO | SA_RESTART;
74         sa.sa_sigaction = handler;
75         sigfillset(&sa.sa_mask);
76         __libc_sigaction(SIGSYNCCALL, &sa, 0);
77
78         self = __pthread_self();
79         sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
80         while (sem_wait(&chaindone));
81
82         for (cur=head; cur; cur=cur->next) {
83                 sem_post(&cur->sem);
84                 while (sem_wait(&cur->sem2));
85         }
86         func(ctx);
87
88         for (cur=head; cur; cur=next) {
89                 next = cur->next;
90                 sem_post(&cur->sem);
91         }
92
93         sa.sa_flags = 0;
94         sa.sa_handler = SIG_IGN;
95         __libc_sigaction(SIGSYNCCALL, &sa, 0);
96
97         __syscall(SYS_rt_sigprocmask, SIG_SETMASK,
98                 &oldmask, 0, __SYSCALL_SSLEN);
99
100         __release_ptc();
101 }