Updated to fedora-glibc-20041110T0839
[glibc.git] / nptl / pthread_create.c
blob82a3c683aaaf0df6bfabf7d7553edabe1672636a
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 struct pthread *pd = (struct pthread *) arg;
227 #if HP_TIMING_AVAIL
228 /* Remember the time when the thread was started. */
229 hp_timing_t now;
230 HP_TIMING_NOW (now);
231 THREAD_SETMEM (pd, cpuclock_offset, now);
232 #endif
234 /* Initialize resolver state pointer. */
235 __resp = &pd->res;
237 /* This is where the try/finally block should be created. For
238 compilers without that support we do use setjmp. */
239 struct pthread_unwind_buf unwind_buf;
241 /* No previous handlers. */
242 unwind_buf.priv.data.prev = NULL;
243 unwind_buf.priv.data.cleanup = NULL;
245 int not_first_call;
246 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
247 if (__builtin_expect (! not_first_call, 1))
249 /* Store the new cleanup handler info. */
250 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
252 if (__builtin_expect (pd->stopped_start, 0))
254 int oldtype = CANCEL_ASYNC ();
256 /* Get the lock the parent locked to force synchronization. */
257 lll_lock (pd->lock);
258 /* And give it up right away. */
259 lll_unlock (pd->lock);
261 CANCEL_RESET (oldtype);
264 /* Run the code the user provided. */
265 #ifdef CALL_THREAD_FCT
266 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
267 #else
268 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
269 #endif
272 /* Run the destructor for the thread-local data. */
273 __nptl_deallocate_tsd ();
275 /* Clean up any state libc stored in thread-local variables. */
276 __libc_thread_freeres ();
278 /* If this is the last thread we terminate the process now. We
279 do not notify the debugger, it might just irritate it if there
280 is no thread left. */
281 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
282 /* This was the last thread. */
283 exit (0);
285 /* Report the death of the thread if this is wanted. */
286 if (__builtin_expect (pd->report_events, 0))
288 /* See whether TD_DEATH is in any of the mask. */
289 const int idx = __td_eventword (TD_DEATH);
290 const uint32_t mask = __td_eventmask (TD_DEATH);
292 if ((mask & (__nptl_threads_events.event_bits[idx]
293 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
295 /* Yep, we have to signal the death. Add the descriptor to
296 the list but only if it is not already on it. */
297 if (pd->nextevent == NULL)
299 pd->eventbuf.eventnum = TD_DEATH;
300 pd->eventbuf.eventdata = pd;
303 pd->nextevent = __nptl_last_event;
304 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
305 pd, pd->nextevent));
308 /* Now call the function to signal the event. */
309 __nptl_death_event ();
313 /* The thread is exiting now. Don't set this bit until after we've hit
314 the event-reporting breakpoint, so that td_thr_get_info on us while at
315 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
316 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
318 /* If the thread is detached free the TCB. */
319 if (IS_DETACHED (pd))
320 /* Free the TCB. */
321 __free_tcb (pd);
323 /* We cannot call '_exit' here. '_exit' will terminate the process.
325 The 'exit' implementation in the kernel will signal when the
326 process is really dead since 'clone' got passed the CLONE_CLEARTID
327 flag. The 'tid' field in the TCB will be set to zero.
329 The exit code is zero since in case all threads exit by calling
330 'pthread_exit' the exit status must be 0 (zero). */
331 __exit_thread_inline (0);
333 /* NOTREACHED */
334 return 0;
338 /* Default thread attributes for the case when the user does not
339 provide any. */
340 static const struct pthread_attr default_attr =
342 /* Just some value > 0 which gets rounded to the nearest page size. */
343 .guardsize = 1,
348 __pthread_create_2_1 (newthread, attr, start_routine, arg)
349 pthread_t *newthread;
350 const pthread_attr_t *attr;
351 void *(*start_routine) (void *);
352 void *arg;
354 STACK_VARIABLES;
355 const struct pthread_attr *iattr;
356 struct pthread *pd;
357 int err;
359 iattr = (struct pthread_attr *) attr;
360 if (iattr == NULL)
361 /* Is this the best idea? On NUMA machines this could mean
362 accessing far-away memory. */
363 iattr = &default_attr;
365 err = ALLOCATE_STACK (iattr, &pd);
366 if (__builtin_expect (err != 0, 0))
367 /* Something went wrong. Maybe a parameter of the attributes is
368 invalid or we could not allocate memory. */
369 return err;
372 /* Initialize the TCB. All initializations with zero should be
373 performed in 'get_cached_stack'. This way we avoid doing this if
374 the stack freshly allocated with 'mmap'. */
376 #ifdef TLS_TCB_AT_TP
377 /* Reference to the TCB itself. */
378 pd->header.self = pd;
380 /* Self-reference for TLS. */
381 pd->header.tcb = pd;
382 #endif
384 /* Store the address of the start routine and the parameter. Since
385 we do not start the function directly the stillborn thread will
386 get the information from its thread descriptor. */
387 pd->start_routine = start_routine;
388 pd->arg = arg;
390 /* Copy the thread attribute flags. */
391 struct pthread *self = THREAD_SELF;
392 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
393 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
395 /* Initialize the field for the ID of the thread which is waiting
396 for us. This is a self-reference in case the thread is created
397 detached. */
398 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
400 /* The debug events are inherited from the parent. */
401 pd->eventbuf = self->eventbuf;
404 /* Copy the parent's scheduling parameters. The flags will say what
405 is valid and what is not. */
406 pd->schedpolicy = self->schedpolicy;
407 pd->schedparam = self->schedparam;
409 /* Determine scheduling parameters for the thread. */
410 if (attr != NULL
411 && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
412 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
414 INTERNAL_SYSCALL_DECL (err);
416 /* Use the scheduling parameters the user provided. */
417 if (iattr->flags & ATTR_FLAG_POLICY_SET)
418 pd->schedpolicy = iattr->schedpolicy;
419 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
421 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, err, 1, 0);
422 pd->flags |= ATTR_FLAG_POLICY_SET;
425 if (iattr->flags & ATTR_FLAG_SCHED_SET)
426 memcpy (&pd->schedparam, &iattr->schedparam,
427 sizeof (struct sched_param));
428 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
430 INTERNAL_SYSCALL (sched_getparam, err, 2, 0, &pd->schedparam);
431 pd->flags |= ATTR_FLAG_SCHED_SET;
434 /* Check for valid priorities. */
435 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, err, 1,
436 iattr->schedpolicy);
437 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, err, 1,
438 iattr->schedpolicy);
439 if (pd->schedparam.sched_priority < minprio
440 || pd->schedparam.sched_priority > maxprio)
442 err = EINVAL;
443 goto errout;
447 /* Pass the descriptor to the caller. */
448 *newthread = (pthread_t) pd;
450 /* Remember whether the thread is detached or not. In case of an
451 error we have to free the stacks of non-detached stillborn
452 threads. */
453 bool is_detached = IS_DETACHED (pd);
455 /* Start the thread. */
456 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
457 if (err != 0)
459 /* Something went wrong. Free the resources. */
460 if (!is_detached)
462 errout:
463 __deallocate_stack (pd);
465 return err;
468 return 0;
470 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
473 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
475 __pthread_create_2_0 (newthread, attr, start_routine, arg)
476 pthread_t *newthread;
477 const pthread_attr_t *attr;
478 void *(*start_routine) (void *);
479 void *arg;
481 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
482 the old size and access to the new members might crash the program.
483 We convert the struct now. */
484 struct pthread_attr new_attr;
486 if (attr != NULL)
488 struct pthread_attr *iattr = (struct pthread_attr *) attr;
489 size_t ps = __getpagesize ();
491 /* Copy values from the user-provided attributes. */
492 new_attr.schedparam = iattr->schedparam;
493 new_attr.schedpolicy = iattr->schedpolicy;
494 new_attr.flags = iattr->flags;
496 /* Fill in default values for the fields not present in the old
497 implementation. */
498 new_attr.guardsize = ps;
499 new_attr.stackaddr = NULL;
500 new_attr.stacksize = 0;
501 new_attr.cpuset = NULL;
503 /* We will pass this value on to the real implementation. */
504 attr = (pthread_attr_t *) &new_attr;
507 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
509 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
510 GLIBC_2_0);
511 #endif
513 /* Information for libthread_db. */
515 #include "../nptl_db/db_info.c"