* sysdeps/unix/sysv/linux/getcwd.c (__getcwd): Use larger of PATH_MAX
[glibc.git] / nptl / pthread_create.c
blob71365a17e8840ebfb145664ea0be5372b200898a
1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006 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 struct pthread *
59 internal_function
60 __find_in_stack_list (pd)
61 struct pthread *pd;
63 list_t *entry;
64 struct pthread *result = NULL;
66 lll_lock (stack_cache_lock);
68 list_for_each (entry, &stack_used)
70 struct pthread *curp;
72 curp = list_entry (entry, struct pthread, list);
73 if (curp == pd)
75 result = curp;
76 break;
80 if (result == NULL)
81 list_for_each (entry, &__stack_user)
83 struct pthread *curp;
85 curp = list_entry (entry, struct pthread, list);
86 if (curp == pd)
88 result = curp;
89 break;
93 lll_unlock (stack_cache_lock);
95 return result;
99 /* Deallocate POSIX thread-local-storage. */
100 void
101 attribute_hidden
102 __nptl_deallocate_tsd (void)
104 struct pthread *self = THREAD_SELF;
106 /* Maybe no data was ever allocated. This happens often so we have
107 a flag for this. */
108 if (THREAD_GETMEM (self, specific_used))
110 size_t round;
111 size_t cnt;
113 round = 0;
116 size_t idx;
118 /* So far no new nonzero data entry. */
119 THREAD_SETMEM (self, specific_used, false);
121 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
123 struct pthread_key_data *level2;
125 level2 = THREAD_GETMEM_NC (self, specific, cnt);
127 if (level2 != NULL)
129 size_t inner;
131 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
132 ++inner, ++idx)
134 void *data = level2[inner].data;
136 if (data != NULL)
138 /* Always clear the data. */
139 level2[inner].data = NULL;
141 /* Make sure the data corresponds to a valid
142 key. This test fails if the key was
143 deallocated and also if it was
144 re-allocated. It is the user's
145 responsibility to free the memory in this
146 case. */
147 if (level2[inner].seq
148 == __pthread_keys[idx].seq
149 /* It is not necessary to register a destructor
150 function. */
151 && __pthread_keys[idx].destr != NULL)
152 /* Call the user-provided destructor. */
153 __pthread_keys[idx].destr (data);
157 else
158 idx += PTHREAD_KEY_1STLEVEL_SIZE;
161 if (THREAD_GETMEM (self, specific_used) == 0)
162 /* No data has been modified. */
163 goto just_free;
165 /* We only repeat the process a fixed number of times. */
166 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
168 /* Just clear the memory of the first block for reuse. */
169 memset (&THREAD_SELF->specific_1stblock, '\0',
170 sizeof (self->specific_1stblock));
172 just_free:
173 /* Free the memory for the other blocks. */
174 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
176 struct pthread_key_data *level2;
178 level2 = THREAD_GETMEM_NC (self, specific, cnt);
179 if (level2 != NULL)
181 /* The first block is allocated as part of the thread
182 descriptor. */
183 free (level2);
184 THREAD_SETMEM_NC (self, specific, cnt, NULL);
188 THREAD_SETMEM (self, specific_used, false);
193 /* Deallocate a thread's stack after optionally making sure the thread
194 descriptor is still valid. */
195 void
196 internal_function
197 __free_tcb (struct pthread *pd)
199 /* The thread is exiting now. */
200 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
201 TERMINATED_BIT) == 0, 1))
203 /* Remove the descriptor from the list. */
204 if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
205 /* Something is really wrong. The descriptor for a still
206 running thread is gone. */
207 abort ();
209 /* Queue the stack memory block for reuse and exit the process. The
210 kernel will signal via writing to the address returned by
211 QUEUE-STACK when the stack is available. */
212 __deallocate_stack (pd);
217 static int
218 start_thread (void *arg)
220 struct pthread *pd = (struct pthread *) arg;
222 #if HP_TIMING_AVAIL
223 /* Remember the time when the thread was started. */
224 hp_timing_t now;
225 HP_TIMING_NOW (now);
226 THREAD_SETMEM (pd, cpuclock_offset, now);
227 #endif
229 /* Initialize resolver state pointer. */
230 __resp = &pd->res;
232 #ifdef __NR_set_robust_list
233 # ifndef __ASSUME_SET_ROBUST_LIST
234 if (__set_robust_list_avail >= 0)
235 # endif
237 INTERNAL_SYSCALL_DECL (err);
238 /* This call should never fail because the initial call in init.c
239 succeeded. */
240 INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
241 sizeof (struct robust_list_head));
243 #endif
245 /* This is where the try/finally block should be created. For
246 compilers without that support we do use setjmp. */
247 struct pthread_unwind_buf unwind_buf;
249 /* No previous handlers. */
250 unwind_buf.priv.data.prev = NULL;
251 unwind_buf.priv.data.cleanup = NULL;
253 int not_first_call;
254 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
255 if (__builtin_expect (! not_first_call, 1))
257 /* Store the new cleanup handler info. */
258 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
260 if (__builtin_expect (pd->stopped_start, 0))
262 int oldtype = CANCEL_ASYNC ();
264 /* Get the lock the parent locked to force synchronization. */
265 lll_lock (pd->lock);
266 /* And give it up right away. */
267 lll_unlock (pd->lock);
269 CANCEL_RESET (oldtype);
272 /* Run the code the user provided. */
273 #ifdef CALL_THREAD_FCT
274 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
275 #else
276 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
277 #endif
280 /* Run the destructor for the thread-local data. */
281 __nptl_deallocate_tsd ();
283 /* Clean up any state libc stored in thread-local variables. */
284 __libc_thread_freeres ();
286 /* If this is the last thread we terminate the process now. We
287 do not notify the debugger, it might just irritate it if there
288 is no thread left. */
289 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
290 /* This was the last thread. */
291 exit (0);
293 /* Report the death of the thread if this is wanted. */
294 if (__builtin_expect (pd->report_events, 0))
296 /* See whether TD_DEATH is in any of the mask. */
297 const int idx = __td_eventword (TD_DEATH);
298 const uint32_t mask = __td_eventmask (TD_DEATH);
300 if ((mask & (__nptl_threads_events.event_bits[idx]
301 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
303 /* Yep, we have to signal the death. Add the descriptor to
304 the list but only if it is not already on it. */
305 if (pd->nextevent == NULL)
307 pd->eventbuf.eventnum = TD_DEATH;
308 pd->eventbuf.eventdata = pd;
311 pd->nextevent = __nptl_last_event;
312 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
313 pd, pd->nextevent));
316 /* Now call the function to signal the event. */
317 __nptl_death_event ();
321 /* The thread is exiting now. Don't set this bit until after we've hit
322 the event-reporting breakpoint, so that td_thr_get_info on us while at
323 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
324 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
326 #ifndef __ASSUME_SET_ROBUST_LIST
327 /* If this thread has any robust mutexes locked, handle them now. */
328 # if __WORDSIZE == 64
329 void *robust = pd->robust_head.list;
330 # else
331 __pthread_slist_t *robust = pd->robust_list.__next;
332 # endif
333 /* We let the kernel do the notification if it is able to do so. */
334 if (__set_robust_list_avail < 0
335 && __builtin_expect (robust != &pd->robust_head, 0))
339 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
340 ((char *) robust - offsetof (struct __pthread_mutex_s,
341 __list.__next));
342 robust = *((void **) robust);
344 # ifdef __PTHREAD_MUTEX_HAVE_PREV
345 this->__list.__prev = NULL;
346 # endif
347 this->__list.__next = NULL;
349 lll_robust_mutex_dead (this->__lock);
351 while (robust != &pd->robust_head);
353 #endif
355 /* If the thread is detached free the TCB. */
356 if (IS_DETACHED (pd))
357 /* Free the TCB. */
358 __free_tcb (pd);
359 else if (__builtin_expect (pd->cancelhandling & SETXID_BITMASK, 0))
361 /* Some other thread might call any of the setXid functions and expect
362 us to reply. In this case wait until we did that. */
364 lll_futex_wait (&pd->setxid_futex, 0);
365 while (pd->cancelhandling & SETXID_BITMASK);
367 /* Reset the value so that the stack can be reused. */
368 pd->setxid_futex = 0;
371 /* We cannot call '_exit' here. '_exit' will terminate the process.
373 The 'exit' implementation in the kernel will signal when the
374 process is really dead since 'clone' got passed the CLONE_CLEARTID
375 flag. The 'tid' field in the TCB will be set to zero.
377 The exit code is zero since in case all threads exit by calling
378 'pthread_exit' the exit status must be 0 (zero). */
379 __exit_thread_inline (0);
381 /* NOTREACHED */
382 return 0;
386 /* Default thread attributes for the case when the user does not
387 provide any. */
388 static const struct pthread_attr default_attr =
390 /* Just some value > 0 which gets rounded to the nearest page size. */
391 .guardsize = 1,
396 __pthread_create_2_1 (newthread, attr, start_routine, arg)
397 pthread_t *newthread;
398 const pthread_attr_t *attr;
399 void *(*start_routine) (void *);
400 void *arg;
402 STACK_VARIABLES;
404 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
405 if (iattr == NULL)
406 /* Is this the best idea? On NUMA machines this could mean
407 accessing far-away memory. */
408 iattr = &default_attr;
410 struct pthread *pd = NULL;
411 int err = ALLOCATE_STACK (iattr, &pd);
412 if (__builtin_expect (err != 0, 0))
413 /* Something went wrong. Maybe a parameter of the attributes is
414 invalid or we could not allocate memory. */
415 return err;
418 /* Initialize the TCB. All initializations with zero should be
419 performed in 'get_cached_stack'. This way we avoid doing this if
420 the stack freshly allocated with 'mmap'. */
422 #ifdef TLS_TCB_AT_TP
423 /* Reference to the TCB itself. */
424 pd->header.self = pd;
426 /* Self-reference for TLS. */
427 pd->header.tcb = pd;
428 #endif
430 /* Store the address of the start routine and the parameter. Since
431 we do not start the function directly the stillborn thread will
432 get the information from its thread descriptor. */
433 pd->start_routine = start_routine;
434 pd->arg = arg;
436 /* Copy the thread attribute flags. */
437 struct pthread *self = THREAD_SELF;
438 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
439 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
441 /* Initialize the field for the ID of the thread which is waiting
442 for us. This is a self-reference in case the thread is created
443 detached. */
444 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
446 /* The debug events are inherited from the parent. */
447 pd->eventbuf = self->eventbuf;
450 /* Copy the parent's scheduling parameters. The flags will say what
451 is valid and what is not. */
452 pd->schedpolicy = self->schedpolicy;
453 pd->schedparam = self->schedparam;
455 /* Copy the stack guard canary. */
456 #ifdef THREAD_COPY_STACK_GUARD
457 THREAD_COPY_STACK_GUARD (pd);
458 #endif
460 /* Copy the pointer guard value. */
461 #ifdef THREAD_COPY_POINTER_GUARD
462 THREAD_COPY_POINTER_GUARD (pd);
463 #endif
465 /* Determine scheduling parameters for the thread. */
466 if (attr != NULL
467 && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
468 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
470 INTERNAL_SYSCALL_DECL (scerr);
472 /* Use the scheduling parameters the user provided. */
473 if (iattr->flags & ATTR_FLAG_POLICY_SET)
474 pd->schedpolicy = iattr->schedpolicy;
475 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
477 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
478 pd->flags |= ATTR_FLAG_POLICY_SET;
481 if (iattr->flags & ATTR_FLAG_SCHED_SET)
482 memcpy (&pd->schedparam, &iattr->schedparam,
483 sizeof (struct sched_param));
484 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
486 INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
487 pd->flags |= ATTR_FLAG_SCHED_SET;
490 /* Check for valid priorities. */
491 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
492 iattr->schedpolicy);
493 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
494 iattr->schedpolicy);
495 if (pd->schedparam.sched_priority < minprio
496 || pd->schedparam.sched_priority > maxprio)
498 err = EINVAL;
499 goto errout;
503 /* Pass the descriptor to the caller. */
504 *newthread = (pthread_t) pd;
506 /* Remember whether the thread is detached or not. In case of an
507 error we have to free the stacks of non-detached stillborn
508 threads. */
509 bool is_detached = IS_DETACHED (pd);
511 /* Start the thread. */
512 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
513 if (err != 0)
515 /* Something went wrong. Free the resources. */
516 if (!is_detached)
518 errout:
519 __deallocate_stack (pd);
521 return err;
524 return 0;
526 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
529 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
531 __pthread_create_2_0 (newthread, attr, start_routine, arg)
532 pthread_t *newthread;
533 const pthread_attr_t *attr;
534 void *(*start_routine) (void *);
535 void *arg;
537 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
538 the old size and access to the new members might crash the program.
539 We convert the struct now. */
540 struct pthread_attr new_attr;
542 if (attr != NULL)
544 struct pthread_attr *iattr = (struct pthread_attr *) attr;
545 size_t ps = __getpagesize ();
547 /* Copy values from the user-provided attributes. */
548 new_attr.schedparam = iattr->schedparam;
549 new_attr.schedpolicy = iattr->schedpolicy;
550 new_attr.flags = iattr->flags;
552 /* Fill in default values for the fields not present in the old
553 implementation. */
554 new_attr.guardsize = ps;
555 new_attr.stackaddr = NULL;
556 new_attr.stacksize = 0;
557 new_attr.cpuset = NULL;
559 /* We will pass this value on to the real implementation. */
560 attr = (pthread_attr_t *) &new_attr;
563 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
565 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
566 GLIBC_2_0);
567 #endif
569 /* Information for libthread_db. */
571 #include "../nptl_db/db_info.c"
573 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
574 functions to be present as well. */
575 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
576 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
578 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
579 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
581 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
582 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
583 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)