add legacy getloadavg api
[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         sigset_t oldmask;
47
48         if (!libc.threads_minus_1) {
49                 func(ctx);
50                 return;
51         }
52
53         __inhibit_ptc();
54
55         __block_all_sigs(&oldmask);
56
57         sem_init(&chaindone, 0, 0);
58         sem_init(&chainlock, 0, 1);
59         chainlen = 0;
60         head = 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         sa.sa_flags = 0;
74         sa.sa_handler = SIG_IGN;
75         __libc_sigaction(SIGSYNCCALL, &sa, 0);
76
77         for (cur=head; cur; cur=cur->next) {
78                 sem_post(&cur->sem);
79                 while (sem_wait(&cur->sem2));
80         }
81         func(ctx);
82
83         for (cur=head; cur; cur=next) {
84                 next = cur->next;
85                 sem_post(&cur->sem);
86         }
87
88         __restore_sigs(&oldmask);
89
90         __release_ptc();
91 }