Updated to fedora-glibc-20041021T0701
[glibc.git] / nptl / pthread_create.c
blob1bab72d1e998f90d794df67179fdfef59e256aa9
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 #if HP_TIMING_AVAIL
231 /* Remember the time when the thread was started. */
232 hp_timing_t now;
233 HP_TIMING_NOW (now);
234 THREAD_SETMEM (pd, cpuclock_offset, now);
235 #endif
237 /* Initialize resolver state pointer. */
238 __resp = &pd->res;
240 /* This is where the try/finally block should be created. For
241 compilers without that support we do use setjmp. */
242 struct pthread_unwind_buf unwind_buf;
244 /* No previous handlers. */
245 unwind_buf.priv.data.prev = NULL;
246 unwind_buf.priv.data.cleanup = NULL;
248 int not_first_call;
249 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
250 if (__builtin_expect (! not_first_call, 1))
252 /* Store the new cleanup handler info. */
253 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
255 if (__builtin_expect (pd->stopped_start, 0))
257 int oldtype = CANCEL_ASYNC ();
259 /* Get the lock the parent locked to force synchronization. */
260 lll_lock (pd->lock);
261 /* And give it up right away. */
262 lll_unlock (pd->lock);
264 CANCEL_RESET (oldtype);
267 /* Run the code the user provided. */
268 #ifdef CALL_THREAD_FCT
269 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
270 #else
271 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
272 #endif
275 /* Run the destructor for the thread-local data. */
276 __nptl_deallocate_tsd ();
278 /* Clean up any state libc stored in thread-local variables. */
279 __libc_thread_freeres ();
281 /* If this is the last thread we terminate the process now. We
282 do not notify the debugger, it might just irritate it if there
283 is no thread left. */
284 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
285 /* This was the last thread. */
286 exit (0);
288 /* Report the death of the thread if this is wanted. */
289 if (__builtin_expect (pd->report_events, 0))
291 /* See whether TD_DEATH is in any of the mask. */
292 const int idx = __td_eventword (TD_DEATH);
293 const uint32_t mask = __td_eventmask (TD_DEATH);
295 if ((mask & (__nptl_threads_events.event_bits[idx]
296 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
298 /* Yep, we have to signal the death. Add the descriptor to
299 the list but only if it is not already on it. */
300 if (pd->nextevent == NULL)
302 pd->eventbuf.eventnum = TD_DEATH;
303 pd->eventbuf.eventdata = pd;
306 pd->nextevent = __nptl_last_event;
307 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
308 pd, pd->nextevent));
311 /* Now call the function to signal the event. */
312 __nptl_death_event ();
316 /* The thread is exiting now. Don't set this bit until after we've hit
317 the event-reporting breakpoint, so that td_thr_get_info on us while at
318 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
319 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
321 /* If the thread is detached free the TCB. */
322 if (IS_DETACHED (pd))
323 /* Free the TCB. */
324 __free_tcb (pd);
326 /* We cannot call '_exit' here. '_exit' will terminate the process.
328 The 'exit' implementation in the kernel will signal when the
329 process is really dead since 'clone' got passed the CLONE_CLEARTID
330 flag. The 'tid' field in the TCB will be set to zero.
332 The exit code is zero since in case all threads exit by calling
333 'pthread_exit' the exit status must be 0 (zero). */
334 __exit_thread_inline (0);
336 /* NOTREACHED */
337 return 0;
341 /* Default thread attributes for the case when the user does not
342 provide any. */
343 static const struct pthread_attr default_attr =
345 /* Just some value > 0 which gets rounded to the nearest page size. */
346 .guardsize = 1,
351 __pthread_create_2_1 (newthread, attr, start_routine, arg)
352 pthread_t *newthread;
353 const pthread_attr_t *attr;
354 void *(*start_routine) (void *);
355 void *arg;
357 STACK_VARIABLES;
358 const struct pthread_attr *iattr;
359 struct pthread *pd;
360 int err;
362 iattr = (struct pthread_attr *) attr;
363 if (iattr == NULL)
364 /* Is this the best idea? On NUMA machines this could mean
365 accessing far-away memory. */
366 iattr = &default_attr;
368 err = ALLOCATE_STACK (iattr, &pd);
369 if (__builtin_expect (err != 0, 0))
370 /* Something went wrong. Maybe a parameter of the attributes is
371 invalid or we could not allocate memory. */
372 return err;
375 /* Initialize the TCB. All initializations with zero should be
376 performed in 'get_cached_stack'. This way we avoid doing this if
377 the stack freshly allocated with 'mmap'. */
379 #ifdef TLS_TCB_AT_TP
380 /* Reference to the TCB itself. */
381 pd->header.self = pd;
383 /* Self-reference for TLS. */
384 pd->header.tcb = pd;
385 #endif
387 /* Store the address of the start routine and the parameter. Since
388 we do not start the function directly the stillborn thread will
389 get the information from its thread descriptor. */
390 pd->start_routine = start_routine;
391 pd->arg = arg;
393 /* Copy the thread attribute flags. */
394 struct pthread *self = THREAD_SELF;
395 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
396 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
398 /* Initialize the field for the ID of the thread which is waiting
399 for us. This is a self-reference in case the thread is created
400 detached. */
401 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
403 /* The debug events are inherited from the parent. */
404 pd->eventbuf = self->eventbuf;
407 /* Copy the parent's scheduling parameters. The flags will say what
408 is valid and what is not. */
409 pd->schedpolicy = self->schedpolicy;
410 pd->schedparam = self->schedparam;
412 /* Determine scheduling parameters for the thread. */
413 if (attr != NULL
414 && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
415 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
417 INTERNAL_SYSCALL_DECL (err);
419 /* Use the scheduling parameters the user provided. */
420 if (iattr->flags & ATTR_FLAG_POLICY_SET)
421 pd->schedpolicy = iattr->schedpolicy;
422 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
424 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, err, 1, 0);
425 pd->flags |= ATTR_FLAG_POLICY_SET;
428 if (iattr->flags & ATTR_FLAG_SCHED_SET)
429 memcpy (&pd->schedparam, &iattr->schedparam,
430 sizeof (struct sched_param));
431 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
433 INTERNAL_SYSCALL (sched_getparam, err, 2, 0, &pd->schedparam);
434 pd->flags |= ATTR_FLAG_SCHED_SET;
437 /* Check for valid priorities. */
438 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, err, 1,
439 iattr->schedpolicy);
440 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, err, 1,
441 iattr->schedpolicy);
442 if (pd->schedparam.sched_priority < minprio
443 || pd->schedparam.sched_priority > maxprio)
445 err = EINVAL;
446 goto errout;
450 /* Pass the descriptor to the caller. */
451 *newthread = (pthread_t) pd;
453 /* Remember whether the thread is detached or not. In case of an
454 error we have to free the stacks of non-detached stillborn
455 threads. */
456 bool is_detached = IS_DETACHED (pd);
458 /* Start the thread. */
459 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
460 if (err != 0)
462 errout:
463 /* Something went wrong. Free the resources. */
464 if (!is_detached)
465 __deallocate_stack (pd);
466 return err;
469 return 0;
471 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
474 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
476 __pthread_create_2_0 (newthread, attr, start_routine, arg)
477 pthread_t *newthread;
478 const pthread_attr_t *attr;
479 void *(*start_routine) (void *);
480 void *arg;
482 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
483 the old size and access to the new members might crash the program.
484 We convert the struct now. */
485 struct pthread_attr new_attr;
487 if (attr != NULL)
489 struct pthread_attr *iattr = (struct pthread_attr *) attr;
490 size_t ps = __getpagesize ();
492 /* Copy values from the user-provided attributes. */
493 new_attr.schedparam = iattr->schedparam;
494 new_attr.schedpolicy = iattr->schedpolicy;
495 new_attr.flags = iattr->flags;
497 /* Fill in default values for the fields not present in the old
498 implementation. */
499 new_attr.guardsize = ps;
500 new_attr.stackaddr = NULL;
501 new_attr.stacksize = 0;
502 new_attr.cpuset = NULL;
504 /* We will pass this value on to the real implementation. */
505 attr = (pthread_attr_t *) &new_attr;
508 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
510 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
511 GLIBC_2_0);
512 #endif
514 /* Information for libthread_db. */
516 #include "../nptl_db/db_info.c"