]> sourceware.org Git - glibc.git/blob - nptl/pthread_create.c
* sysdeps/powerpc/powerpc32/dl-trampoline.S (_dl_runtime_resolve):
[glibc.git] / nptl / pthread_create.c
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.
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 struct pthread *
59 internal_function
60 __find_in_stack_list (pd)
61 struct pthread *pd;
62 {
63 list_t *entry;
64 struct pthread *result = NULL;
65
66 lll_lock (stack_cache_lock);
67
68 list_for_each (entry, &stack_used)
69 {
70 struct pthread *curp;
71
72 curp = list_entry (entry, struct pthread, list);
73 if (curp == pd)
74 {
75 result = curp;
76 break;
77 }
78 }
79
80 if (result == NULL)
81 list_for_each (entry, &__stack_user)
82 {
83 struct pthread *curp;
84
85 curp = list_entry (entry, struct pthread, list);
86 if (curp == pd)
87 {
88 result = curp;
89 break;
90 }
91 }
92
93 lll_unlock (stack_cache_lock);
94
95 return result;
96 }
97
98
99 /* Deallocate POSIX thread-local-storage. */
100 void
101 attribute_hidden
102 __nptl_deallocate_tsd (void)
103 {
104 struct pthread *self = THREAD_SELF;
105
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))
109 {
110 size_t round;
111 size_t cnt;
112
113 round = 0;
114 do
115 {
116 size_t idx;
117
118 /* So far no new nonzero data entry. */
119 THREAD_SETMEM (self, specific_used, false);
120
121 for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
122 {
123 struct pthread_key_data *level2;
124
125 level2 = THREAD_GETMEM_NC (self, specific, cnt);
126
127 if (level2 != NULL)
128 {
129 size_t inner;
130
131 for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
132 ++inner, ++idx)
133 {
134 void *data = level2[inner].data;
135
136 if (data != NULL)
137 {
138 /* Always clear the data. */
139 level2[inner].data = NULL;
140
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);
154 }
155 }
156 }
157 else
158 idx += PTHREAD_KEY_1STLEVEL_SIZE;
159 }
160
161 if (THREAD_GETMEM (self, specific_used) == 0)
162 /* No data has been modified. */
163 goto just_free;
164 }
165 /* We only repeat the process a fixed number of times. */
166 while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
167
168 /* Just clear the memory of the first block for reuse. */
169 memset (&THREAD_SELF->specific_1stblock, '\0',
170 sizeof (self->specific_1stblock));
171
172 just_free:
173 /* Free the memory for the other blocks. */
174 for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
175 {
176 struct pthread_key_data *level2;
177
178 level2 = THREAD_GETMEM_NC (self, specific, cnt);
179 if (level2 != NULL)
180 {
181 /* The first block is allocated as part of the thread
182 descriptor. */
183 free (level2);
184 THREAD_SETMEM_NC (self, specific, cnt, NULL);
185 }
186 }
187
188 THREAD_SETMEM (self, specific_used, false);
189 }
190 }
191
192
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)
198 {
199 /* The thread is exiting now. */
200 if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
201 TERMINATED_BIT) == 0, 1))
202 {
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 ();
208
209 /* Free TPP data. */
210 if (__builtin_expect (pd->tpp != NULL, 0))
211 {
212 struct priority_protection_data *tpp = pd->tpp;
213
214 pd->tpp = NULL;
215 free (tpp);
216 }
217
218 /* Queue the stack memory block for reuse and exit the process. The
219 kernel will signal via writing to the address returned by
220 QUEUE-STACK when the stack is available. */
221 __deallocate_stack (pd);
222 }
223 }
224
225
226 static int
227 start_thread (void *arg)
228 {
229 struct pthread *pd = (struct pthread *) arg;
230
231 #if HP_TIMING_AVAIL
232 /* Remember the time when the thread was started. */
233 hp_timing_t now;
234 HP_TIMING_NOW (now);
235 THREAD_SETMEM (pd, cpuclock_offset, now);
236 #endif
237
238 /* Initialize resolver state pointer. */
239 __resp = &pd->res;
240
241 #ifdef __NR_set_robust_list
242 # ifndef __ASSUME_SET_ROBUST_LIST
243 if (__set_robust_list_avail >= 0)
244 # endif
245 {
246 INTERNAL_SYSCALL_DECL (err);
247 /* This call should never fail because the initial call in init.c
248 succeeded. */
249 INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
250 sizeof (struct robust_list_head));
251 }
252 #endif
253
254 /* This is where the try/finally block should be created. For
255 compilers without that support we do use setjmp. */
256 struct pthread_unwind_buf unwind_buf;
257
258 /* No previous handlers. */
259 unwind_buf.priv.data.prev = NULL;
260 unwind_buf.priv.data.cleanup = NULL;
261
262 int not_first_call;
263 not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
264 if (__builtin_expect (! not_first_call, 1))
265 {
266 /* Store the new cleanup handler info. */
267 THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
268
269 if (__builtin_expect (pd->stopped_start, 0))
270 {
271 int oldtype = CANCEL_ASYNC ();
272
273 /* Get the lock the parent locked to force synchronization. */
274 lll_lock (pd->lock);
275 /* And give it up right away. */
276 lll_unlock (pd->lock);
277
278 CANCEL_RESET (oldtype);
279 }
280
281 /* Run the code the user provided. */
282 #ifdef CALL_THREAD_FCT
283 THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
284 #else
285 THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
286 #endif
287 }
288
289 /* Run the destructor for the thread-local data. */
290 __nptl_deallocate_tsd ();
291
292 /* Clean up any state libc stored in thread-local variables. */
293 __libc_thread_freeres ();
294
295 /* If this is the last thread we terminate the process now. We
296 do not notify the debugger, it might just irritate it if there
297 is no thread left. */
298 if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
299 /* This was the last thread. */
300 exit (0);
301
302 /* Report the death of the thread if this is wanted. */
303 if (__builtin_expect (pd->report_events, 0))
304 {
305 /* See whether TD_DEATH is in any of the mask. */
306 const int idx = __td_eventword (TD_DEATH);
307 const uint32_t mask = __td_eventmask (TD_DEATH);
308
309 if ((mask & (__nptl_threads_events.event_bits[idx]
310 | pd->eventbuf.eventmask.event_bits[idx])) != 0)
311 {
312 /* Yep, we have to signal the death. Add the descriptor to
313 the list but only if it is not already on it. */
314 if (pd->nextevent == NULL)
315 {
316 pd->eventbuf.eventnum = TD_DEATH;
317 pd->eventbuf.eventdata = pd;
318
319 do
320 pd->nextevent = __nptl_last_event;
321 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
322 pd, pd->nextevent));
323 }
324
325 /* Now call the function to signal the event. */
326 __nptl_death_event ();
327 }
328 }
329
330 /* The thread is exiting now. Don't set this bit until after we've hit
331 the event-reporting breakpoint, so that td_thr_get_info on us while at
332 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
333 atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
334
335 #ifndef __ASSUME_SET_ROBUST_LIST
336 /* If this thread has any robust mutexes locked, handle them now. */
337 # if __WORDSIZE == 64
338 void *robust = pd->robust_head.list;
339 # else
340 __pthread_slist_t *robust = pd->robust_list.__next;
341 # endif
342 /* We let the kernel do the notification if it is able to do so.
343 If we have to do it here there for sure are no PI mutexes involved
344 since the kernel support for them is even more recent. */
345 if (__set_robust_list_avail < 0
346 && __builtin_expect (robust != (void *) &pd->robust_head, 0))
347 {
348 do
349 {
350 struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
351 ((char *) robust - offsetof (struct __pthread_mutex_s,
352 __list.__next));
353 robust = *((void **) robust);
354
355 # ifdef __PTHREAD_MUTEX_HAVE_PREV
356 this->__list.__prev = NULL;
357 # endif
358 this->__list.__next = NULL;
359
360 lll_robust_mutex_dead (this->__lock);
361 }
362 while (robust != (void *) &pd->robust_head);
363 }
364 #endif
365
366 /* If the thread is detached free the TCB. */
367 if (IS_DETACHED (pd))
368 /* Free the TCB. */
369 __free_tcb (pd);
370 else if (__builtin_expect (pd->cancelhandling & SETXID_BITMASK, 0))
371 {
372 /* Some other thread might call any of the setXid functions and expect
373 us to reply. In this case wait until we did that. */
374 do
375 lll_futex_wait (&pd->setxid_futex, 0);
376 while (pd->cancelhandling & SETXID_BITMASK);
377
378 /* Reset the value so that the stack can be reused. */
379 pd->setxid_futex = 0;
380 }
381
382 /* We cannot call '_exit' here. '_exit' will terminate the process.
383
384 The 'exit' implementation in the kernel will signal when the
385 process is really dead since 'clone' got passed the CLONE_CLEARTID
386 flag. The 'tid' field in the TCB will be set to zero.
387
388 The exit code is zero since in case all threads exit by calling
389 'pthread_exit' the exit status must be 0 (zero). */
390 __exit_thread_inline (0);
391
392 /* NOTREACHED */
393 return 0;
394 }
395
396
397 /* Default thread attributes for the case when the user does not
398 provide any. */
399 static const struct pthread_attr default_attr =
400 {
401 /* Just some value > 0 which gets rounded to the nearest page size. */
402 .guardsize = 1,
403 };
404
405
406 int
407 __pthread_create_2_1 (newthread, attr, start_routine, arg)
408 pthread_t *newthread;
409 const pthread_attr_t *attr;
410 void *(*start_routine) (void *);
411 void *arg;
412 {
413 STACK_VARIABLES;
414
415 const struct pthread_attr *iattr = (struct pthread_attr *) attr;
416 if (iattr == NULL)
417 /* Is this the best idea? On NUMA machines this could mean
418 accessing far-away memory. */
419 iattr = &default_attr;
420
421 struct pthread *pd = NULL;
422 int err = ALLOCATE_STACK (iattr, &pd);
423 if (__builtin_expect (err != 0, 0))
424 /* Something went wrong. Maybe a parameter of the attributes is
425 invalid or we could not allocate memory. */
426 return err;
427
428
429 /* Initialize the TCB. All initializations with zero should be
430 performed in 'get_cached_stack'. This way we avoid doing this if
431 the stack freshly allocated with 'mmap'. */
432
433 #ifdef TLS_TCB_AT_TP
434 /* Reference to the TCB itself. */
435 pd->header.self = pd;
436
437 /* Self-reference for TLS. */
438 pd->header.tcb = pd;
439 #endif
440
441 /* Store the address of the start routine and the parameter. Since
442 we do not start the function directly the stillborn thread will
443 get the information from its thread descriptor. */
444 pd->start_routine = start_routine;
445 pd->arg = arg;
446
447 /* Copy the thread attribute flags. */
448 struct pthread *self = THREAD_SELF;
449 pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
450 | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
451
452 /* Initialize the field for the ID of the thread which is waiting
453 for us. This is a self-reference in case the thread is created
454 detached. */
455 pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
456
457 /* The debug events are inherited from the parent. */
458 pd->eventbuf = self->eventbuf;
459
460
461 /* Copy the parent's scheduling parameters. The flags will say what
462 is valid and what is not. */
463 pd->schedpolicy = self->schedpolicy;
464 pd->schedparam = self->schedparam;
465
466 /* Copy the stack guard canary. */
467 #ifdef THREAD_COPY_STACK_GUARD
468 THREAD_COPY_STACK_GUARD (pd);
469 #endif
470
471 /* Copy the pointer guard value. */
472 #ifdef THREAD_COPY_POINTER_GUARD
473 THREAD_COPY_POINTER_GUARD (pd);
474 #endif
475
476 /* Determine scheduling parameters for the thread. */
477 if (attr != NULL
478 && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
479 && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
480 {
481 INTERNAL_SYSCALL_DECL (scerr);
482
483 /* Use the scheduling parameters the user provided. */
484 if (iattr->flags & ATTR_FLAG_POLICY_SET)
485 pd->schedpolicy = iattr->schedpolicy;
486 else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
487 {
488 pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
489 pd->flags |= ATTR_FLAG_POLICY_SET;
490 }
491
492 if (iattr->flags & ATTR_FLAG_SCHED_SET)
493 memcpy (&pd->schedparam, &iattr->schedparam,
494 sizeof (struct sched_param));
495 else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
496 {
497 INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
498 pd->flags |= ATTR_FLAG_SCHED_SET;
499 }
500
501 /* Check for valid priorities. */
502 int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
503 iattr->schedpolicy);
504 int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
505 iattr->schedpolicy);
506 if (pd->schedparam.sched_priority < minprio
507 || pd->schedparam.sched_priority > maxprio)
508 {
509 err = EINVAL;
510 goto errout;
511 }
512 }
513
514 /* Pass the descriptor to the caller. */
515 *newthread = (pthread_t) pd;
516
517 /* Remember whether the thread is detached or not. In case of an
518 error we have to free the stacks of non-detached stillborn
519 threads. */
520 bool is_detached = IS_DETACHED (pd);
521
522 /* Start the thread. */
523 err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
524 if (err != 0)
525 {
526 /* Something went wrong. Free the resources. */
527 if (!is_detached)
528 {
529 errout:
530 __deallocate_stack (pd);
531 }
532 return err;
533 }
534
535 return 0;
536 }
537 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
538
539
540 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
541 int
542 __pthread_create_2_0 (newthread, attr, start_routine, arg)
543 pthread_t *newthread;
544 const pthread_attr_t *attr;
545 void *(*start_routine) (void *);
546 void *arg;
547 {
548 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
549 the old size and access to the new members might crash the program.
550 We convert the struct now. */
551 struct pthread_attr new_attr;
552
553 if (attr != NULL)
554 {
555 struct pthread_attr *iattr = (struct pthread_attr *) attr;
556 size_t ps = __getpagesize ();
557
558 /* Copy values from the user-provided attributes. */
559 new_attr.schedparam = iattr->schedparam;
560 new_attr.schedpolicy = iattr->schedpolicy;
561 new_attr.flags = iattr->flags;
562
563 /* Fill in default values for the fields not present in the old
564 implementation. */
565 new_attr.guardsize = ps;
566 new_attr.stackaddr = NULL;
567 new_attr.stacksize = 0;
568 new_attr.cpuset = NULL;
569
570 /* We will pass this value on to the real implementation. */
571 attr = (pthread_attr_t *) &new_attr;
572 }
573
574 return __pthread_create_2_1 (newthread, attr, start_routine, arg);
575 }
576 compat_symbol (libpthread, __pthread_create_2_0, pthread_create,
577 GLIBC_2_0);
578 #endif
579 \f
580 /* Information for libthread_db. */
581
582 #include "../nptl_db/db_info.c"
583 \f
584 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
585 functions to be present as well. */
586 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
587 PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
588
589 PTHREAD_STATIC_FN_REQUIRE (pthread_once)
590 PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
591
592 PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
593 PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
594 PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)
This page took 0.064611 seconds and 5 git commands to generate.