Update
[glibc.git] / nptl / pthread_create.c
blob34edee498fa45d8051bc563f58b3a87c3cb04910
1 /* Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
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.
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.
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. */
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>
31 #include <shlib-compat.h>
34 /* Local function to start thread and handle cleanup. */
35 static int start_thread (void *arg);
38 /* Nozero if debugging mode is enabled. */
39 int __pthread_debug;
41 /* Globally enabled events. */
42 static td_thr_events_t __nptl_threads_events;
44 /* Pointer to descriptor with the last event. */
45 static struct pthread *__nptl_last_event;
47 /* Number of threads running. */
48 unsigned int __nptl_nthreads = 1;
51 /* Code to allocate and deallocate a stack. */
52 #include "allocatestack.c"
54 /* Code to create the thread. */
55 #include "createthread.c"
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)
63 struct pthread *
64 internal_function
65 __find_in_stack_list (pd)
66 struct pthread *pd;
68 list_t *entry;
69 struct pthread *result = NULL;
71 lll_lock (stack_cache_lock);
73 list_for_each (entry, &stack_used)
75 struct pthread *curp;
77 curp = list_entry (entry, struct pthread, list);
78 if (curp == pd)
80 result = curp;
81 break;
85 if (result == NULL)
86 list_for_each (entry, &__stack_user)
88 struct pthread *curp;
90 curp = list_entry (entry, struct pthread, list);
91 if (curp == pd)
93 result = curp;
94 break;
98 lll_unlock (stack_cache_lock);
100 return result;
104 /* Deallocate POSIX thread-local-storage. */
105 void
106 attribute_hidden
107 __nptl_deallocate_tsd (void)
109 struct pthread *self = THREAD_SELF;
111 /* Maybe no data was ever allocated. This happens often so we have
112 a flag for this. */
113 if (THREAD_GETMEM (self, specific_used))
115 size_t round;
116 size_t cnt;
118 round = 0;
121 size_t idx;
123 /* So far no new nonzero data entry. */
124 THREAD_SETMEM (self, specific_used, false);
126 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
128 struct pthread_key_data *level2;
130 level2 = THREAD_GETMEM_NC (self, specific, cnt);
132 if (level2 != NULL)
134 size_t inner;
136 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
137 ++inner, ++idx)
139 void *data = level2[inner].data;
141 if (data != NULL)
143 /* Always clear the data. */
144 level2[inner].data = NULL;
146 /* Make sure the data corresponds to a valid
147 key. This test fails if the key was
148 deallocated and also if it was
149 re-allocated. It is the user's
150 responsibility to free the memory in this
151 case. */
152 if (level2[inner].seq
153 == __pthread_keys[idx].seq
154 /* It is not necessary to register a destructor
155 function. */
156 && __pthread_keys[idx].destr != NULL)
157 /* Call the user-provided destructor. */
158 __pthread_keys[idx].destr (data);
162 else
163 idx += PTHREAD_KEY_1STLEVEL_SIZE;
166 if (THREAD_GETMEM (self, specific_used) == 0)
167 /* No data has been modified. */
168 goto just_free;
170 /* We only repeat the process a fixed number of times. */
171 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
173 /* Just clear the memory of the first block for reuse. */
174 memset (&THREAD_SELF->specific_1stblock, '\0',
175 sizeof (self->specific_1stblock));
177 just_free:
178 /* Free the memory for the other blocks. */
179 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
181 struct pthread_key_data *level2;
183 level2 = THREAD_GETMEM_NC (self, specific, cnt);
184 if (level2 != NULL)
186 /* The first block is allocated as part of the thread
187 descriptor. */
188 free (level2);
189 THREAD_SETMEM_NC (self, specific, cnt, NULL);
193 THREAD_SETMEM (self, specific_used, false);
198 /* Deallocate a thread's stack after optionally making sure the thread
199 descriptor is still valid. */
200 void
201 internal_function
202 __free_tcb (struct pthread *pd)
204 /* The thread is exiting now. */
205 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
206 TERMINATED_BIT) == 0, 1))
208 /* Remove the descriptor from the list. */
209 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
210 /* Something is really wrong. The descriptor for a still
211 running thread is gone. */
212 abort ();
214 /* Queue the stack memory block for reuse and exit the process. The
215 kernel will signal via writing to the address returned by
216 QUEUE-STACK when the stack is available. */
217 __deallocate_stack (pd);
222 static int
223 start_thread (void *arg)
225 /* One more thread. */
226 atomic_increment (&__nptl_nthreads);
228 struct pthread *pd = (struct pthread *) arg;
230 #ifndef __ASSUME_CLONE_STOPPED
231 /* Get the lock the parent locked to force synchronization. */
232 lll_lock (pd->lock);
233 /* And give it up right away. */
234 lll_unlock (pd->lock);
235 #endif
237 #if HP_TIMING_AVAIL
238 /* Remember the time when the thread was started. */
239 hp_timing_t now;
240 HP_TIMING_NOW (now);
241 THREAD_SETMEM (pd, cpuclock_offset, now);
242 #endif
244 /* Initialize resolver state pointer. */
245 __resp = &pd->res;
247 /* This is where the try/finally block should be created. For
248 compilers without that support we do use setjmp. */
249 struct pthread_unwind_buf unwind_buf;
251 /* No previous handlers. */
252 unwind_buf.priv.data.prev = NULL;
253 unwind_buf.priv.data.cleanup = NULL;
255 int not_first_call;
256 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
257 if (__builtin_expect (! not_first_call, 1))
259 /* Store the new cleanup handler info. */
260 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
262 /* Run the code the user provided. */
263 #ifdef CALL_THREAD_FCT
264 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
265 #else
266 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
267 #endif
270 /* Run the destructor for the thread-local data. */
271 __nptl_deallocate_tsd ();
273 /* Clean up any state libc stored in thread-local variables. */
274 __libc_thread_freeres ();
276 /* If this is the last thread we terminate the process now. We
277 do not notify the debugger, it might just irritate it if there
278 is no thread left. */
279 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
280 /* This was the last thread. */
281 exit (0);
283 /* Report the death of the thread if this is wanted. */
284 if (__builtin_expect (pd->report_events, 0))
286 /* See whether TD_DEATH is in any of the mask. */
287 const int idx = __td_eventword (TD_DEATH);
288 const uint32_t mask = __td_eventmask (TD_DEATH);
290 if ((mask & (__nptl_threads_events.event_bits[idx]
291 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
293 /* Yep, we have to signal the death. Add the descriptor to
294 the list but only if it is not already on it. */
295 if (pd->nextevent == NULL)
297 pd->eventbuf.eventnum = TD_DEATH;
298 pd->eventbuf.eventdata = pd;
301 pd->nextevent = __nptl_last_event;
302 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
303 pd, pd->nextevent));
306 /* Now call the function to signal the event. */
307 __nptl_death_event ();
311 /* The thread is exiting now. Don't set this bit until after we've hit
312 the event-reporting breakpoint, so that td_thr_get_info on us while at
313 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
314 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
316 /* If the thread is detached free the TCB. */
317 if (IS_DETACHED (pd))
318 /* Free the TCB. */
319 __free_tcb (pd);
321 /* We cannot call '_exit' here. '_exit' will terminate the process.
323 The 'exit' implementation in the kernel will signal when the
324 process is really dead since 'clone' got passed the CLONE_CLEARTID
325 flag. The 'tid' field in the TCB will be set to zero.
327 The exit code is zero since in case all threads exit by calling
328 'pthread_exit' the exit status must be 0 (zero). */
329 __exit_thread_inline (0);
331 /* NOTREACHED */
332 return 0;
336 /* Default thread attributes for the case when the user does not
337 provide any. */
338 static const struct pthread_attr default_attr =
340 /* Just some value > 0 which gets rounded to the nearest page size. */
341 .guardsize = 1,
346 __pthread_create_2_1 (newthread, attr, start_routine, arg)
347 pthread_t *newthread;
348 const pthread_attr_t *attr;
349 void *(*start_routine) (void *);
350 void *arg;
352 STACK_VARIABLES;
353 const struct pthread_attr *iattr;
354 struct pthread *pd;
355 int err;
357 iattr = (struct pthread_attr *) attr;
358 if (iattr == NULL)
359 /* Is this the best idea? On NUMA machines this could mean
360 accessing far-away memory. */
361 iattr = &default_attr;
363 err = ALLOCATE_STACK (iattr, &pd);
364 if (__builtin_expect (err != 0, 0))
365 /* Something went wrong. Maybe a parameter of the attributes is
366 invalid or we could not allocate memory. */
367 return err;
370 /* Initialize the TCB. All initializations with zero should be
371 performed in 'get_cached_stack'. This way we avoid doing this if
372 the stack freshly allocated with 'mmap'. */
374 #ifdef TLS_TCB_AT_TP
375 /* Reference to the TCB itself. */
376 pd->header.self = pd;
378 /* Self-reference for TLS. */
379 pd->header.tcb = pd;
380 #endif
382 /* Store the address of the start routine and the parameter. Since
383 we do not start the function directly the stillborn thread will
384 get the information from its thread descriptor. */
385 pd->start_routine = start_routine;
386 pd->arg = arg;
388 /* Copy the thread attribute flags. */
389 struct pthread *self = THREAD_SELF;
390 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
391 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
393 /* Initialize the field for the ID of the thread which is waiting
394 for us. This is a self-reference in case the thread is created
395 detached. */
396 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
398 /* The debug events are inherited from the parent. */
399 pd->eventbuf = self->eventbuf;
402 /* Copy the parent's scheduling parameters. The flags will say what
403 is valid and what is not. */
404 pd->schedpolicy = self->schedpolicy;
405 pd->schedparam = self->schedparam;
407 /* Determine scheduling parameters for the thread. */
408 if (attr != NULL
409 && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
410 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
412 INTERNAL_SYSCALL_DECL (err);
414 /* Use the scheduling parameters the user provided. */
415 if (iattr->flags & ATTR_FLAG_POLICY_SET)
416 pd->schedpolicy = iattr->schedpolicy;
417 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
419 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, err, 1, 0);
420 pd->flags |= ATTR_FLAG_POLICY_SET;
423 if (iattr->flags & ATTR_FLAG_SCHED_SET)
424 memcpy (&pd->schedparam, &iattr->schedparam,
425 sizeof (struct sched_param));
426 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
428 INTERNAL_SYSCALL (sched_getparam, err, 2, 0, &pd->schedparam);
429 pd->flags |= ATTR_FLAG_SCHED_SET;
432 /* Check for valid priorities. */
433 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, err, 1,
434 iattr->schedpolicy);
435 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, err, 1,
436 iattr->schedpolicy);
437 if (pd->schedparam.sched_priority < minprio
438 || pd->schedparam.sched_priority > maxprio)
440 err = EINVAL;
441 goto errout;
445 /* Pass the descriptor to the caller. */
446 *newthread = (pthread_t) pd;
448 /* Start the thread. */
449 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
450 if (err != 0)
452 errout:
453 /* Something went wrong. Free the resources. */
454 __deallocate_stack (pd);
455 return err;
458 return 0;
460 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
463 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
465 __pthread_create_2_0 (newthread, attr, start_routine, arg)
466 pthread_t *newthread;
467 const pthread_attr_t *attr;
468 void *(*start_routine) (void *);
469 void *arg;
471 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
472 the old size and access to the new members might crash the program.
473 We convert the struct now. */
474 struct pthread_attr new_attr;
476 if (attr != NULL)
478 struct pthread_attr *iattr = (struct pthread_attr *) attr;
479 size_t ps = __getpagesize ();
481 /* Copy values from the user-provided attributes. */
482 new_attr.schedparam = iattr->schedparam;
483 new_attr.schedpolicy = iattr->schedpolicy;
484 new_attr.flags = iattr->flags;
486 /* Fill in default values for the fields not present in the old
487 implementation. */
488 new_attr.guardsize = ps;
489 new_attr.stackaddr = NULL;
490 new_attr.stacksize = 0;
491 new_attr.cpuset = NULL;
493 /* We will pass this value on to the real implementation. */
494 attr = (pthread_attr_t *) &new_attr;
497 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
499 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
500 GLIBC_2_0);
501 #endif
503 /* Information for libthread_db. */
505 #include "../nptl_db/db_info.c"