add C11 thread creation and related thread functions
[musl] / src / thread / pthread_create.c
1 #define _GNU_SOURCE
2 #include "pthread_impl.h"
3 #include "stdio_impl.h"
4 #include "libc.h"
5 #include <sys/mman.h>
6 #include <string.h>
7
8 void *__mmap(void *, size_t, int, int, int, off_t);
9 int __munmap(void *, size_t);
10 int __mprotect(void *, size_t, int);
11
12 static void dummy_0()
13 {
14 }
15 weak_alias(dummy_0, __acquire_ptc);
16 weak_alias(dummy_0, __release_ptc);
17 weak_alias(dummy_0, __pthread_tsd_run_dtors);
18 weak_alias(dummy_0, __do_private_robust_list);
19 weak_alias(dummy_0, __do_orphaned_stdio_locks);
20
21 _Noreturn void __pthread_exit(void *result)
22 {
23         pthread_t self = __pthread_self();
24         sigset_t set;
25
26         self->result = result;
27
28         while (self->cancelbuf) {
29                 void (*f)(void *) = self->cancelbuf->__f;
30                 void *x = self->cancelbuf->__x;
31                 self->cancelbuf = self->cancelbuf->__next;
32                 f(x);
33         }
34
35         __pthread_tsd_run_dtors();
36
37         __lock(self->exitlock);
38
39         /* Mark this thread dead before decrementing count */
40         __lock(self->killlock);
41         self->dead = 1;
42
43         /* Block all signals before decrementing the live thread count.
44          * This is important to ensure that dynamically allocated TLS
45          * is not under-allocated/over-committed, and possibly for other
46          * reasons as well. */
47         __block_all_sigs(&set);
48
49         /* Wait to unlock the kill lock, which governs functions like
50          * pthread_kill which target a thread id, until signals have
51          * been blocked. This precludes observation of the thread id
52          * as a live thread (with application code running in it) after
53          * the thread was reported dead by ESRCH being returned. */
54         __unlock(self->killlock);
55
56         /* It's impossible to determine whether this is "the last thread"
57          * until performing the atomic decrement, since multiple threads
58          * could exit at the same time. For the last thread, revert the
59          * decrement and unblock signals to give the atexit handlers and
60          * stdio cleanup code a consistent state. */
61         if (a_fetch_add(&libc.threads_minus_1, -1)==0) {
62                 libc.threads_minus_1 = 0;
63                 __restore_sigs(&set);
64                 exit(0);
65         }
66
67         if (self->locale != &libc.global_locale) {
68                 a_dec(&libc.uselocale_cnt);
69                 if (self->locale->ctype_utf8)
70                         a_dec(&libc.bytelocale_cnt_minus_1);
71         }
72
73         __do_private_robust_list();
74         __do_orphaned_stdio_locks();
75
76         if (self->detached && self->map_base) {
77                 /* Detached threads must avoid the kernel clear_child_tid
78                  * feature, since the virtual address will have been
79                  * unmapped and possibly already reused by a new mapping
80                  * at the time the kernel would perform the write. In
81                  * the case of threads that started out detached, the
82                  * initial clone flags are correct, but if the thread was
83                  * detached later (== 2), we need to clear it here. */
84                 if (self->detached == 2) __syscall(SYS_set_tid_address, 0);
85
86                 /* The following call unmaps the thread's stack mapping
87                  * and then exits without touching the stack. */
88                 __unmapself(self->map_base, self->map_size);
89         }
90
91         for (;;) __syscall(SYS_exit, 0);
92 }
93
94 void __do_cleanup_push(struct __ptcb *cb)
95 {
96         if (!libc.has_thread_pointer) return;
97         struct pthread *self = __pthread_self();
98         cb->__next = self->cancelbuf;
99         self->cancelbuf = cb;
100 }
101
102 void __do_cleanup_pop(struct __ptcb *cb)
103 {
104         if (!libc.has_thread_pointer) return;
105         __pthread_self()->cancelbuf = cb->__next;
106 }
107
108 static int start(void *p)
109 {
110         pthread_t self = p;
111         if (self->startlock[0]) {
112                 __wait(self->startlock, 0, 1, 1);
113                 if (self->startlock[0]) {
114                         self->detached = 2;
115                         pthread_exit(0);
116                 }
117                 __restore_sigs(self->sigmask);
118         }
119         if (self->unblock_cancel)
120                 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK,
121                         SIGPT_SET, 0, _NSIG/8);
122         __pthread_exit(self->start(self->start_arg));
123         return 0;
124 }
125
126 static int start_c11(void *p)
127 {
128         pthread_t self = p;
129         int (*start)(void*) = (int(*)(void*)) self->start;
130         __pthread_exit((void *)(uintptr_t)start(self->start_arg));
131         return 0;
132 }
133
134 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
135
136 /* pthread_key_create.c overrides this */
137 static volatile size_t dummy = 0;
138 weak_alias(dummy, __pthread_tsd_size);
139 static void *dummy_tsd[1] = { 0 };
140 weak_alias(dummy_tsd, __pthread_tsd_main);
141
142 static FILE *volatile dummy_file = 0;
143 weak_alias(dummy_file, __stdin_used);
144 weak_alias(dummy_file, __stdout_used);
145 weak_alias(dummy_file, __stderr_used);
146
147 static void init_file_lock(FILE *f)
148 {
149         if (f && f->lock<0) f->lock = 0;
150 }
151
152 void *__copy_tls(unsigned char *);
153
154 int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
155 {
156         int ret, c11 = (attrp == __ATTRP_C11_THREAD);
157         size_t size, guard;
158         struct pthread *self, *new;
159         unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
160         unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
161                 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
162                 | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
163         int do_sched = 0;
164         pthread_attr_t attr = {0};
165
166         if (!libc.can_do_threads) return ENOSYS;
167         self = __pthread_self();
168         if (!libc.threaded) {
169                 for (FILE *f=libc.ofl_head; f; f=f->next)
170                         init_file_lock(f);
171                 init_file_lock(__stdin_used);
172                 init_file_lock(__stdout_used);
173                 init_file_lock(__stderr_used);
174                 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
175                 self->tsd = (void **)__pthread_tsd_main;
176                 libc.threaded = 1;
177         }
178         if (attrp && !c11) attr = *attrp;
179
180         __acquire_ptc();
181
182         if (attr._a_stackaddr) {
183                 size_t need = libc.tls_size + __pthread_tsd_size;
184                 size = attr._a_stacksize + DEFAULT_STACK_SIZE;
185                 stack = (void *)(attr._a_stackaddr & -16);
186                 stack_limit = (void *)(attr._a_stackaddr - size);
187                 /* Use application-provided stack for TLS only when
188                  * it does not take more than ~12% or 2k of the
189                  * application's stack space. */
190                 if (need < size/8 && need < 2048) {
191                         tsd = stack - __pthread_tsd_size;
192                         stack = tsd - libc.tls_size;
193                         memset(stack, 0, need);
194                 } else {
195                         size = ROUND(need);
196                         guard = 0;
197                 }
198         } else {
199                 guard = ROUND(DEFAULT_GUARD_SIZE + attr._a_guardsize);
200                 size = guard + ROUND(DEFAULT_STACK_SIZE + attr._a_stacksize
201                         + libc.tls_size +  __pthread_tsd_size);
202         }
203
204         if (!tsd) {
205                 if (guard) {
206                         map = __mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
207                         if (map == MAP_FAILED) goto fail;
208                         if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)) {
209                                 __munmap(map, size);
210                                 goto fail;
211                         }
212                 } else {
213                         map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
214                         if (map == MAP_FAILED) goto fail;
215                 }
216                 tsd = map + size - __pthread_tsd_size;
217                 if (!stack) {
218                         stack = tsd - libc.tls_size;
219                         stack_limit = map + guard;
220                 }
221         }
222
223         new = __copy_tls(tsd - libc.tls_size);
224         new->map_base = map;
225         new->map_size = size;
226         new->stack = stack;
227         new->stack_size = stack - stack_limit;
228         new->start = entry;
229         new->start_arg = arg;
230         new->self = new;
231         new->tsd = (void *)tsd;
232         new->locale = &libc.global_locale;
233         if (attr._a_detach) {
234                 new->detached = 1;
235                 flags -= CLONE_CHILD_CLEARTID;
236         }
237         if (attr._a_sched) {
238                 do_sched = new->startlock[0] = 1;
239                 __block_app_sigs(new->sigmask);
240         }
241         new->unblock_cancel = self->cancel;
242         new->canary = self->canary;
243
244         a_inc(&libc.threads_minus_1);
245         ret = __clone((c11 ? start_c11 : start), stack, flags, new, &new->tid, TP_ADJ(new), &new->tid);
246
247         __release_ptc();
248
249         if (do_sched) {
250                 __restore_sigs(new->sigmask);
251         }
252
253         if (ret < 0) {
254                 a_dec(&libc.threads_minus_1);
255                 if (map) __munmap(map, size);
256                 return EAGAIN;
257         }
258
259         if (do_sched) {
260                 ret = __syscall(SYS_sched_setscheduler, new->tid,
261                         attr._a_policy, &attr._a_prio);
262                 a_store(new->startlock, ret<0 ? 2 : 0);
263                 __wake(new->startlock, 1, 1);
264                 if (ret < 0) return -ret;
265         }
266
267         *res = new;
268         return 0;
269 fail:
270         __release_ptc();
271         return EAGAIN;
272 }
273
274 weak_alias(__pthread_exit, pthread_exit);
275 weak_alias(__pthread_create, pthread_create);