rework langinfo code for ABI compat and for use by time code
[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         sem_init(&ch.sem, 0, 0);
25         sem_init(&ch.sem2, 0, 0);
26
27         while (sem_wait(&chainlock));
28         ch.next = head;
29         head = &ch;
30         if (++chainlen == libc.threads_minus_1) sem_post(&chaindone);
31         sem_post(&chainlock);
32
33         while (sem_wait(&ch.sem));
34         callback(context);
35         sem_post(&ch.sem2);
36         while (sem_wait(&ch.sem));
37
38         errno = old_errno;
39 }
40
41 void __synccall(void (*func)(void *), void *ctx)
42 {
43         pthread_t self;
44         struct sigaction sa;
45         struct chain *next;
46         uint64_t oldmask;
47
48         if (!libc.threads_minus_1) {
49                 func(ctx);
50                 return;
51         }
52
53         __inhibit_ptc();
54
55         __syscall(SYS_rt_sigprocmask, SIG_BLOCK, SIGALL_SET,
56                 &oldmask, _NSIG/8);
57
58         sem_init(&chaindone, 0, 0);
59         sem_init(&chainlock, 0, 1);
60         chainlen = 0;
61         callback = func;
62         context = ctx;
63
64         sa.sa_flags = SA_SIGINFO | SA_RESTART;
65         sa.sa_sigaction = handler;
66         sigfillset(&sa.sa_mask);
67         __libc_sigaction(SIGSYNCCALL, &sa, 0);
68
69         self = __pthread_self();
70         sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
71         while (sem_wait(&chaindone));
72
73         for (cur=head; cur; cur=cur->next) {
74                 sem_post(&cur->sem);
75                 while (sem_wait(&cur->sem2));
76         }
77         func(ctx);
78
79         for (cur=head; cur; cur=next) {
80                 next = cur->next;
81                 sem_post(&cur->sem);
82         }
83
84         sa.sa_flags = 0;
85         sa.sa_handler = SIG_IGN;
86         __libc_sigaction(SIGSYNCCALL, &sa, 0);
87
88         __syscall(SYS_rt_sigprocmask, SIG_SETMASK,
89                 &oldmask, 0, _NSIG/8);
90
91         __release_ptc();
92 }