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