]> git.ipfire.org Git - thirdparty/glibc.git/blob - nptl/pthread_create.c
Update.
[thirdparty/glibc.git] / nptl / pthread_create.c
1 /* Copyright (C) 2002, 2003 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
19
20 #include <errno.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "pthreadP.h"
25 #include <hp-timing.h>
26 #include <ldsodefs.h>
27 #include <atomic.h>
28 #include <libc-internal.h>
29 #include <resolv.h>
30
31 #include <shlib-compat.h>
32
33
34 /* Local function to start thread and handle cleanup. */
35 static int start_thread (void *arg);
36
37
38 /* Nozero if debugging mode is enabled. */
39 int __pthread_debug;
40
41 /* Globally enabled events. */
42 static td_thr_events_t __nptl_threads_events;
43
44 /* Pointer to descriptor with the last event. */
45 static struct pthread *__nptl_last_event;
46
47 /* Number of threads running. */
48 unsigned int __nptl_nthreads = 1;
49
50
51 /* Code to allocate and deallocate a stack. */
52 #include "allocatestack.c"
53
54 /* Code to create the thread. */
55 #include "createthread.c"
56
57
58 /* Table of the key information. */
59 struct pthread_key_struct __pthread_keys[PTHREAD_KEYS_MAX]
60 __attribute__ ((nocommon));
61 hidden_data_def (__pthread_keys)
62
63 /* This is for libthread_db only. */
64 const int __pthread_pthread_sizeof_descr = sizeof (struct pthread);
65
66 struct pthread *
67 internal_function
68 __find_in_stack_list (pd)
69 struct pthread *pd;
70 {
71 list_t *entry;
72 struct pthread *result = NULL;
73
74 lll_lock (stack_cache_lock);
75
76 list_for_each (entry, &stack_used)
77 {
78 struct pthread *curp;
79
80 curp = list_entry (entry, struct pthread, list);
81 if (curp == pd)
82 {
83 result = curp;
84 break;
85 }
86 }
87
88 if (result == NULL)
89 list_for_each (entry, &__stack_user)
90 {
91 struct pthread *curp;
92
93 curp = list_entry (entry, struct pthread, list);
94 if (curp == pd)
95 {
96 result = curp;
97 break;
98 }
99 }
100
101 lll_unlock (stack_cache_lock);
102
103 return result;
104 }
105
106
107 /* Deallocate POSIX thread-local-storage. */
108 static void
109 internal_function
110 deallocate_tsd (void)
111 {
112 struct pthread *self = THREAD_SELF;
113
114 /* Maybe no data was ever allocated. This happens often so we have
115 a flag for this. */
116 if (THREAD_GETMEM (self, specific_used))
117 {
118 size_t round;
119 size_t cnt;
120
121 round = 0;
122 do
123 {
124 size_t idx;
125
126 /* So far no new nonzero data entry. */
127 THREAD_SETMEM (self, specific_used, false);
128
129 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
130 {
131 struct pthread_key_data *level2;
132
133 level2 = THREAD_GETMEM_NC (self, specific, cnt);
134
135 if (level2 != NULL)
136 {
137 size_t inner;
138
139 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
140 ++inner, ++idx)
141 {
142 void *data = level2[inner].data;
143
144 if (data != NULL)
145 {
146 /* Always clear the data. */
147 level2[inner].data = NULL;
148
149 /* Make sure the data corresponds to a valid
150 key. This test fails if the key was
151 deallocated and also if it was
152 re-allocated. It is the user's
153 responsibility to free the memory in this
154 case. */
155 if (level2[inner].seq
156 == __pthread_keys[idx].seq
157 /* It is not necessary to register a destructor
158 function. */
159 && __pthread_keys[idx].destr != NULL)
160 /* Call the user-provided destructor. */
161 __pthread_keys[idx].destr (data);
162 }
163 }
164 }
165 else
166 idx += PTHREAD_KEY_1STLEVEL_SIZE;
167 }
168
169 if (THREAD_GETMEM (self, specific_used) == 0)
170 /* No data has been modified. */
171 goto just_free;
172 }
173 /* We only repeat the process a fixed number of times. */
174 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
175
176 /* Just clear the memory of the first block for reuse. */
177 memset (&THREAD_SELF->specific_1stblock, '\0',
178 sizeof (self->specific_1stblock));
179
180 just_free:
181 /* Free the memory for the other blocks. */
182 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
183 {
184 struct pthread_key_data *level2;
185
186 level2 = THREAD_GETMEM_NC (self, specific, cnt);
187 if (level2 != NULL)
188 {
189 /* The first block is allocated as part of the thread
190 descriptor. */
191 free (level2);
192 THREAD_SETMEM_NC (self, specific, cnt, NULL);
193 }
194 }
195
196 THREAD_SETMEM (self, specific_used, false);
197 }
198 }
199
200
201 /* Deallocate a thread's stack after optionally making sure the thread
202 descriptor is still valid. */
203 void
204 internal_function
205 __free_tcb (struct pthread *pd)
206 {
207 /* The thread is exiting now. */
208 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
209 TERMINATED_BIT) == 0, 1))
210 {
211 /* Remove the descriptor from the list. */
212 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
213 /* Something is really wrong. The descriptor for a still
214 running thread is gone. */
215 abort ();
216
217 /* Queue the stack memory block for reuse and exit the process. The
218 kernel will signal via writing to the address returned by
219 QUEUE-STACK when the stack is available. */
220 __deallocate_stack (pd);
221 }
222 }
223
224
225 static int
226 start_thread (void *arg)
227 {
228 /* One more thread. */
229 atomic_increment (&__nptl_nthreads);
230
231 struct pthread *pd = (struct pthread *) arg;
232
233 #ifndef __ASSUME_CLONE_STOPPED
234 /* Get the lock the parent locked to force synchronization. */
235 lll_lock (pd->lock);
236 /* And give it up right away. */
237 lll_unlock (pd->lock);
238 #endif
239
240 #if HP_TIMING_AVAIL
241 /* Remember the time when the thread was started. */
242 hp_timing_t now;
243 HP_TIMING_NOW (now);
244 THREAD_SETMEM (pd, cpuclock_offset, now);
245 #endif
246
247 /* Initialize resolver state pointer. */
248 __resp = &pd->res;
249
250 /* This is where the try/finally block should be created. For
251 compilers without that support we do use setjmp. */
252 struct pthread_unwind_buf unwind_buf;
253
254 /* No previous handlers. */
255 unwind_buf.priv.data.prev = NULL;
256 unwind_buf.priv.data.cleanup = NULL;
257
258 int not_first_call;
259 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
260 if (__builtin_expect (! not_first_call, 1))
261 {
262 /* Store the new cleanup handler info. */
263 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
264
265 /* Run the code the user provided. */
266 #ifdef CALL_THREAD_FCT
267 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
268 #else
269 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
270 #endif
271 }
272
273 /* Run the destructor for the thread-local data. */
274 deallocate_tsd ();
275
276 /* Clean up any state libc stored in thread-local variables. */
277 __libc_thread_freeres ();
278
279 /* If this is the last thread we terminate the process now. We
280 do not notify the debugger, it might just irritate it if there
281 is no thread left. */
282 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
283 /* This was the last thread. */
284 exit (0);
285
286 /* Report the death of the thread if this is wanted. */
287 if (__builtin_expect (pd->report_events, 0))
288 {
289 /* See whether TD_DEATH is in any of the mask. */
290 const int idx = __td_eventword (TD_DEATH);
291 const uint32_t mask = __td_eventmask (TD_DEATH);
292
293 if ((mask & (__nptl_threads_events.event_bits[idx]
294 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
295 {
296 /* Yep, we have to signal the death. Add the descriptor to
297 the list but only if it is not already on it. */
298 if (pd->nextevent == NULL)
299 {
300 pd->eventbuf.eventnum = TD_DEATH;
301 pd->eventbuf.eventdata = pd;
302
303 do
304 pd->nextevent = __nptl_last_event;
305 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
306 pd, pd->nextevent));
307 }
308
309 /* Now call the function to signal the event. */
310 __nptl_death_event ();
311 }
312 }
313
314 /* The thread is exiting now. Don't set this bit until after we've hit
315 the event-reporting breakpoint, so that td_thr_get_info on us while at
316 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
317 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
318
319 /* If the thread is detached free the TCB. */
320 if (IS_DETACHED (pd))
321 /* Free the TCB. */
322 __free_tcb (pd);
323
324 /* We cannot call '_exit' here. '_exit' will terminate the process.
325
326 The 'exit' implementation in the kernel will signal when the
327 process is really dead since 'clone' got passed the CLONE_CLEARTID
328 flag. The 'tid' field in the TCB will be set to zero.
329
330 The exit code is zero since in case all threads exit by calling
331 'pthread_exit' the exit status must be 0 (zero). */
332 __exit_thread_inline (0);
333
334 /* NOTREACHED */
335 return 0;
336 }
337
338
339 /* Default thread attributes for the case when the user does not
340 provide any. */
341 static const struct pthread_attr default_attr =
342 {
343 /* Just some value > 0 which gets rounded to the nearest page size. */
344 .guardsize = 1,
345 };
346
347
348 int
349 __pthread_create_2_1 (newthread, attr, start_routine, arg)
350 pthread_t *newthread;
351 const pthread_attr_t *attr;
352 void *(*start_routine) (void *);
353 void *arg;
354 {
355 STACK_VARIABLES;
356 const struct pthread_attr *iattr;
357 struct pthread *pd;
358 int err;
359
360 iattr = (struct pthread_attr *) attr;
361 if (iattr == NULL)
362 /* Is this the best idea? On NUMA machines this could mean
363 accessing far-away memory. */
364 iattr = &default_attr;
365
366 err = ALLOCATE_STACK (iattr, &pd);
367 if (__builtin_expect (err != 0, 0))
368 /* Something went wrong. Maybe a parameter of the attributes is
369 invalid or we could not allocate memory. */
370 return err;
371
372
373 /* Initialize the TCB. All initializations with zero should be
374 performed in 'get_cached_stack'. This way we avoid doing this if
375 the stack freshly allocated with 'mmap'. */
376
377 #ifdef TLS_TCB_AT_TP
378 /* Reference to the TCB itself. */
379 pd->header.self = pd;
380
381 /* Self-reference for TLS. */
382 pd->header.tcb = pd;
383 #endif
384
385 /* Store the address of the start routine and the parameter. Since
386 we do not start the function directly the stillborn thread will
387 get the information from its thread descriptor. */
388 pd->start_routine = start_routine;
389 pd->arg = arg;
390
391 /* Copy the thread attribute flags. */
392 pd->flags = iattr->flags;
393
394 /* Initialize the field for the ID of the thread which is waiting
395 for us. This is a self-reference in case the thread is created
396 detached. */
397 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
398
399 /* The debug events are inherited from the parent. */
400 pd->eventbuf = THREAD_SELF->eventbuf;
401
402
403 /* Determine scheduling parameters for the thread.
404 XXX How to determine whether scheduling handling is needed? */
405 if (0 && attr != NULL)
406 {
407 if (iattr->flags & ATTR_FLAG_NOTINHERITSCHED)
408 {
409 /* Use the scheduling parameters the user provided. */
410 pd->schedpolicy = iattr->schedpolicy;
411 memcpy (&pd->schedparam, &iattr->schedparam,
412 sizeof (struct sched_param));
413 }
414 else
415 {
416 /* Just store the scheduling attributes of the parent. */
417 pd->schedpolicy = __sched_getscheduler (0);
418 __sched_getparam (0, &pd->schedparam);
419 }
420 }
421
422 /* Pass the descriptor to the caller. */
423 *newthread = (pthread_t) pd;
424
425 /* Start the thread. */
426 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
427 if (err != 0)
428 {
429 /* Something went wrong. Free the resources. */
430 __deallocate_stack (pd);
431 return err;
432 }
433
434 return 0;
435 }
436 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
437
438
439 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
440 int
441 __pthread_create_2_0 (newthread, attr, start_routine, arg)
442 pthread_t *newthread;
443 const pthread_attr_t *attr;
444 void *(*start_routine) (void *);
445 void *arg;
446 {
447 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
448 the old size and access to the new members might crash the program.
449 We convert the struct now. */
450 struct pthread_attr new_attr;
451
452 if (attr != NULL)
453 {
454 struct pthread_attr *iattr = (struct pthread_attr *) attr;
455 size_t ps = __getpagesize ();
456
457 /* Copy values from the user-provided attributes. */
458 new_attr.schedparam = iattr->schedparam;
459 new_attr.schedpolicy = iattr->schedpolicy;
460 new_attr.flags = iattr->flags;
461
462 /* Fill in default values for the fields not present in the old
463 implementation. */
464 new_attr.guardsize = ps;
465 new_attr.stackaddr = NULL;
466 new_attr.stacksize = 0;
467
468 /* We will pass this value on to the real implementation. */
469 attr = (pthread_attr_t *) &new_attr;
470 }
471
472 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
473 }
474 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
475 GLIBC_2_0);
476 #endif