OSDN Git Service

Merge remote branch 'origin/master' into nptl
[uclinux-h8/uClibc.git] / libpthread / nptl / init.c
1 /* Copyright (C) 2002-2007, 2008, 2009 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 <assert.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/param.h>
27 #include <sys/resource.h>
28 #include <pthreadP.h>
29 #include <atomic.h>
30 #include <ldsodefs.h>
31 #include <tls.h>
32 #include <fork.h>
33 #include <version.h>
34 #include <smp.h>
35 #include <lowlevellock.h>
36 #include <bits/kernel-features.h>
37
38
39 /* Size and alignment of static TLS block.  */
40 size_t __static_tls_size;
41 size_t __static_tls_align_m1;
42
43 #ifndef __ASSUME_SET_ROBUST_LIST
44 /* Negative if we do not have the system call and we can use it.  */
45 int __set_robust_list_avail;
46 # define set_robust_list_not_avail() \
47   __set_robust_list_avail = -1
48 #else
49 # define set_robust_list_not_avail() do { } while (0)
50 #endif
51
52 #ifndef __ASSUME_FUTEX_CLOCK_REALTIME
53 /* Nonzero if we do not have FUTEX_CLOCK_REALTIME.  */
54 int __have_futex_clock_realtime;
55 # define __set_futex_clock_realtime() \
56   __have_futex_clock_realtime = 1
57 #else
58 #define __set_futex_clock_realtime() do { } while (0)
59 #endif
60
61 /* Version of the library, used in libthread_db to detect mismatches.  */
62 static const char nptl_version[] __attribute_used__ = VERSION;
63
64
65 #ifndef SHARED
66 extern void __libc_setup_tls (size_t tcbsize, size_t tcbalign);
67 #endif
68
69 #ifdef SHARED
70 static void nptl_freeres (void);
71
72
73 static const struct pthread_functions pthread_functions =
74   {
75     .ptr_pthread_attr_destroy = __pthread_attr_destroy,
76     .ptr___pthread_attr_init_2_1 = __pthread_attr_init_2_1,
77     .ptr_pthread_attr_getdetachstate = __pthread_attr_getdetachstate,
78     .ptr_pthread_attr_setdetachstate = __pthread_attr_setdetachstate,
79     .ptr_pthread_attr_getinheritsched = __pthread_attr_getinheritsched,
80     .ptr_pthread_attr_setinheritsched = __pthread_attr_setinheritsched,
81     .ptr_pthread_attr_getschedparam = __pthread_attr_getschedparam,
82     .ptr_pthread_attr_setschedparam = __pthread_attr_setschedparam,
83     .ptr_pthread_attr_getschedpolicy = __pthread_attr_getschedpolicy,
84     .ptr_pthread_attr_setschedpolicy = __pthread_attr_setschedpolicy,
85     .ptr_pthread_attr_getscope = __pthread_attr_getscope,
86     .ptr_pthread_attr_setscope = __pthread_attr_setscope,
87     .ptr_pthread_condattr_destroy = __pthread_condattr_destroy,
88     .ptr_pthread_condattr_init = __pthread_condattr_init,
89     .ptr___pthread_cond_broadcast = __pthread_cond_broadcast,
90     .ptr___pthread_cond_destroy = __pthread_cond_destroy,
91     .ptr___pthread_cond_init = __pthread_cond_init,
92     .ptr___pthread_cond_signal = __pthread_cond_signal,
93     .ptr___pthread_cond_wait = __pthread_cond_wait,
94     .ptr___pthread_cond_timedwait = __pthread_cond_timedwait,
95     .ptr_pthread_equal = __pthread_equal,
96     .ptr___pthread_exit = __pthread_exit,
97     .ptr_pthread_getschedparam = __pthread_getschedparam,
98     .ptr_pthread_setschedparam = __pthread_setschedparam,
99     .ptr_pthread_mutex_destroy = INTUSE(__pthread_mutex_destroy),
100     .ptr_pthread_mutex_init = INTUSE(__pthread_mutex_init),
101     .ptr_pthread_mutex_lock = INTUSE(__pthread_mutex_lock),
102     .ptr_pthread_mutex_unlock = INTUSE(__pthread_mutex_unlock),
103     .ptr_pthread_self = __pthread_self,
104     .ptr_pthread_setcancelstate = __pthread_setcancelstate,
105     .ptr_pthread_setcanceltype = __pthread_setcanceltype,
106     .ptr___pthread_cleanup_upto = __pthread_cleanup_upto,
107     .ptr___pthread_once = __pthread_once_internal,
108     .ptr___pthread_rwlock_rdlock = __pthread_rwlock_rdlock_internal,
109     .ptr___pthread_rwlock_wrlock = __pthread_rwlock_wrlock_internal,
110     .ptr___pthread_rwlock_unlock = __pthread_rwlock_unlock_internal,
111     .ptr___pthread_key_create = __pthread_key_create_internal,
112     .ptr___pthread_getspecific = __pthread_getspecific_internal,
113     .ptr___pthread_setspecific = __pthread_setspecific_internal,
114     .ptr__pthread_cleanup_push_defer = __pthread_cleanup_push_defer,
115     .ptr__pthread_cleanup_pop_restore = __pthread_cleanup_pop_restore,
116     .ptr_nthreads = &__nptl_nthreads,
117     .ptr___pthread_unwind = &__pthread_unwind,
118     .ptr__nptl_deallocate_tsd = __nptl_deallocate_tsd,
119     .ptr__nptl_setxid = __nptl_setxid,
120     /* For now only the stack cache needs to be freed.  */
121     .ptr_freeres = nptl_freeres
122   };
123 # define ptr_pthread_functions &pthread_functions
124 #else
125 # define ptr_pthread_functions NULL
126 #endif
127
128
129 #ifdef SHARED
130 /* This function is called indirectly from the freeres code in libc.  */
131 static void
132 __libc_freeres_fn_section
133 nptl_freeres (void)
134 {
135   __unwind_freeres ();
136   __free_stacks (0);
137 }
138 #endif
139
140
141 /* For asynchronous cancellation we use a signal.  This is the handler.  */
142 static void
143 sigcancel_handler (int sig, siginfo_t *si, void *ctx)
144 {
145 #ifdef __ASSUME_CORRECT_SI_PID
146   /* Determine the process ID.  It might be negative if the thread is
147      in the middle of a fork() call.  */
148   pid_t pid = THREAD_GETMEM (THREAD_SELF, pid);
149   if (__builtin_expect (pid < 0, 0))
150     pid = -pid;
151 #endif
152
153   /* Safety check.  It would be possible to call this function for
154      other signals and send a signal from another process.  This is not
155      correct and might even be a security problem.  Try to catch as
156      many incorrect invocations as possible.  */
157   if (sig != SIGCANCEL
158 #ifdef __ASSUME_CORRECT_SI_PID
159       /* Kernels before 2.5.75 stored the thread ID and not the process
160          ID in si_pid so we skip this test.  */
161       || si->si_pid != pid
162 #endif
163       || si->si_code != SI_TKILL)
164     return;
165
166   struct pthread *self = THREAD_SELF;
167
168   int oldval = THREAD_GETMEM (self, cancelhandling);
169   while (1)
170     {
171       /* We are canceled now.  When canceled by another thread this flag
172          is already set but if the signal is directly send (internally or
173          from another process) is has to be done here.  */
174       int newval = oldval | CANCELING_BITMASK | CANCELED_BITMASK;
175
176       if (oldval == newval || (oldval & EXITING_BITMASK) != 0)
177         /* Already canceled or exiting.  */
178         break;
179
180       int curval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling, newval,
181                                               oldval);
182       if (curval == oldval)
183         {
184           /* Set the return value.  */
185           THREAD_SETMEM (self, result, PTHREAD_CANCELED);
186
187           /* Make sure asynchronous cancellation is still enabled.  */
188           if ((newval & CANCELTYPE_BITMASK) != 0)
189             /* Run the registered destructors and terminate the thread.  */
190             __do_cancel ();
191
192           break;
193         }
194
195       oldval = curval;
196     }
197 }
198
199
200 struct xid_command *__xidcmd attribute_hidden;
201
202 /* For asynchronous cancellation we use a signal.  This is the handler.  */
203 static void
204 sighandler_setxid (int sig, siginfo_t *si, void *ctx)
205 {
206 #ifdef __ASSUME_CORRECT_SI_PID
207   /* Determine the process ID.  It might be negative if the thread is
208      in the middle of a fork() call.  */
209   pid_t pid = THREAD_GETMEM (THREAD_SELF, pid);
210   if (__builtin_expect (pid < 0, 0))
211     pid = -pid;
212 #endif
213
214   /* Safety check.  It would be possible to call this function for
215      other signals and send a signal from another process.  This is not
216      correct and might even be a security problem.  Try to catch as
217      many incorrect invocations as possible.  */
218   if (sig != SIGSETXID
219 #ifdef __ASSUME_CORRECT_SI_PID
220       /* Kernels before 2.5.75 stored the thread ID and not the process
221          ID in si_pid so we skip this test.  */
222       || si->si_pid != pid
223 #endif
224       || si->si_code != SI_TKILL)
225     return;
226
227   INTERNAL_SYSCALL_DECL (err);
228   INTERNAL_SYSCALL_NCS (__xidcmd->syscall_no, err, 3, __xidcmd->id[0],
229                         __xidcmd->id[1], __xidcmd->id[2]);
230
231   /* Reset the SETXID flag.  */
232   struct pthread *self = THREAD_SELF;
233   int flags, newval;
234   do
235     {
236       flags = THREAD_GETMEM (self, cancelhandling);
237       newval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling,
238                                           flags & ~SETXID_BITMASK, flags);
239     }
240   while (flags != newval);
241
242   /* And release the futex.  */
243   self->setxid_futex = 1;
244   lll_futex_wake (&self->setxid_futex, 1, LLL_PRIVATE);
245
246   if (atomic_decrement_val (&__xidcmd->cntr) == 0)
247     lll_futex_wake (&__xidcmd->cntr, 1, LLL_PRIVATE);
248 }
249
250
251 /* When using __thread for this, we do it in libc so as not
252    to give libpthread its own TLS segment just for this.  */
253 extern void **__libc_dl_error_tsd (void) __attribute__ ((const));
254
255
256 /* This can be set by the debugger before initialization is complete.  */
257 static bool __nptl_initial_report_events __attribute_used__;
258
259 void
260 __pthread_initialize_minimal_internal (void)
261 {
262 #ifndef SHARED
263   /* Unlike in the dynamically linked case the dynamic linker has not
264      taken care of initializing the TLS data structures.  */
265   __libc_setup_tls (TLS_TCB_SIZE, TLS_TCB_ALIGN);
266
267   /* We must prevent gcc from being clever and move any of the
268      following code ahead of the __libc_setup_tls call.  This function
269      will initialize the thread register which is subsequently
270      used.  */
271   __asm __volatile ("");
272 #endif
273
274   /* Minimal initialization of the thread descriptor.  */
275   struct pthread *pd = THREAD_SELF;
276   INTERNAL_SYSCALL_DECL (err);
277   pd->pid = pd->tid = INTERNAL_SYSCALL (set_tid_address, err, 1, &pd->tid);
278   THREAD_SETMEM (pd, specific[0], &pd->specific_1stblock[0]);
279   THREAD_SETMEM (pd, user_stack, true);
280   if (LLL_LOCK_INITIALIZER != 0)
281     THREAD_SETMEM (pd, lock, LLL_LOCK_INITIALIZER);
282 #if HP_TIMING_AVAIL
283   THREAD_SETMEM (pd, cpuclock_offset, GL(dl_cpuclock_offset));
284 #endif
285
286   /* Initialize the robust mutex data.  */
287 #ifdef __PTHREAD_MUTEX_HAVE_PREV
288   pd->robust_prev = &pd->robust_head;
289 #endif
290   pd->robust_head.list = &pd->robust_head;
291 #ifdef __NR_set_robust_list
292   pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
293                                   - offsetof (pthread_mutex_t,
294                                               __data.__list.__next));
295   int res = INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
296                               sizeof (struct robust_list_head));
297   if (INTERNAL_SYSCALL_ERROR_P (res, err))
298 #endif
299     set_robust_list_not_avail ();
300
301 #ifndef __ASSUME_PRIVATE_FUTEX
302   /* Private futexes are always used (at least internally) so that
303      doing the test once this early is beneficial.  */
304   {
305     int word = 0;
306     word = INTERNAL_SYSCALL (futex, err, 3, &word,
307                             FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1);
308     if (!INTERNAL_SYSCALL_ERROR_P (word, err))
309       THREAD_SETMEM (pd, header.private_futex, FUTEX_PRIVATE_FLAG);
310   }
311
312   /* Private futexes have been introduced earlier than the
313      FUTEX_CLOCK_REALTIME flag.  We don't have to run the test if we
314      know the former are not supported.  This also means we know the
315      kernel will return ENOSYS for unknown operations.  */
316   if (THREAD_GETMEM (pd, header.private_futex) != 0)
317 #endif
318 #ifndef __ASSUME_FUTEX_CLOCK_REALTIME
319     {
320       int word = 0;
321       /* NB: the syscall actually takes six parameters.  The last is the
322          bit mask.  But since we will not actually wait at all the value
323          is irrelevant.  Given that passing six parameters is difficult
324          on some architectures we just pass whatever random value the
325          calling convention calls for to the kernel.  It causes no harm.  */
326       word = INTERNAL_SYSCALL (futex, err, 5, &word,
327                                FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME
328                                | FUTEX_PRIVATE_FLAG, 1, NULL, 0);
329       assert (INTERNAL_SYSCALL_ERROR_P (word, err));
330       if (INTERNAL_SYSCALL_ERRNO (word, err) != ENOSYS)
331         __set_futex_clock_realtime ();
332     }
333 #endif
334
335   /* Set initial thread's stack block from 0 up to __libc_stack_end.
336      It will be bigger than it actually is, but for unwind.c/pt-longjmp.c
337      purposes this is good enough.  */
338   THREAD_SETMEM (pd, stackblock_size, (size_t) __libc_stack_end);
339
340   /* Initialize the list of all running threads with the main thread.  */
341   INIT_LIST_HEAD (&__stack_user);
342   list_add (&pd->list, &__stack_user);
343
344   /* Before initializing __stack_user, the debugger could not find us and
345      had to set __nptl_initial_report_events.  Propagate its setting.  */
346   THREAD_SETMEM (pd, report_events, __nptl_initial_report_events);
347
348   /* Install the cancellation signal handler.  If for some reason we
349      cannot install the handler we do not abort.  Maybe we should, but
350      it is only asynchronous cancellation which is affected.  */
351   struct sigaction sa;
352   sa.sa_sigaction = sigcancel_handler;
353   sa.sa_flags = SA_SIGINFO;
354   __sigemptyset (&sa.sa_mask);
355
356   (void) __libc_sigaction (SIGCANCEL, &sa, NULL);
357
358   /* Install the handle to change the threads' uid/gid.  */
359   sa.sa_sigaction = sighandler_setxid;
360   sa.sa_flags = SA_SIGINFO | SA_RESTART;
361
362   (void) __libc_sigaction (SIGSETXID, &sa, NULL);
363
364   /* The parent process might have left the signals blocked.  Just in
365      case, unblock it.  We reuse the signal mask in the sigaction
366      structure.  It is already cleared.  */
367   __sigaddset (&sa.sa_mask, SIGCANCEL);
368   __sigaddset (&sa.sa_mask, SIGSETXID);
369   (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &sa.sa_mask,
370                            NULL, _NSIG / 8);
371
372   /* Get the size of the static and alignment requirements for the TLS
373      block.  */
374   size_t static_tls_align;
375   _dl_get_tls_static_info (&__static_tls_size, &static_tls_align);
376
377   /* Make sure the size takes all the alignments into account.  */
378   if (STACK_ALIGN > static_tls_align)
379     static_tls_align = STACK_ALIGN;
380   __static_tls_align_m1 = static_tls_align - 1;
381
382   __static_tls_size = roundup (__static_tls_size, static_tls_align);
383
384   /* Determine the default allowed stack size.  This is the size used
385      in case the user does not specify one.  */
386   struct rlimit limit;
387   if (getrlimit (RLIMIT_STACK, &limit) != 0
388       || limit.rlim_cur == RLIM_INFINITY)
389     /* The system limit is not usable.  Use an architecture-specific
390        default.  */
391     limit.rlim_cur = ARCH_STACK_DEFAULT_SIZE;
392   else if (limit.rlim_cur < PTHREAD_STACK_MIN)
393     /* The system limit is unusably small.
394        Use the minimal size acceptable.  */
395     limit.rlim_cur = PTHREAD_STACK_MIN;
396
397   /* Make sure it meets the minimum size that allocate_stack
398      (allocatestack.c) will demand, which depends on the page size.  */
399   const uintptr_t pagesz = sysconf (_SC_PAGESIZE);
400   const size_t minstack = pagesz + __static_tls_size + MINIMAL_REST_STACK;
401   if (limit.rlim_cur < minstack)
402     limit.rlim_cur = minstack;
403
404   /* Round the resource limit up to page size.  */
405   limit.rlim_cur = (limit.rlim_cur + pagesz - 1) & -pagesz;
406   __default_stacksize = limit.rlim_cur;
407
408 #ifdef SHARED
409   /* Transfer the old value from the dynamic linker's internal location.  */
410   *__libc_dl_error_tsd () = *(*GL(dl_error_catch_tsd)) ();
411   GL(dl_error_catch_tsd) = &__libc_dl_error_tsd;
412
413 #endif
414
415   GL(dl_init_static_tls) = &__pthread_init_static_tls;
416
417   /* Register the fork generation counter with the libc.  */
418 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
419   __libc_multiple_threads_ptr =
420 #endif
421     __libc_pthread_init (&__fork_generation, __reclaim_stacks,
422                          ptr_pthread_functions);
423
424   /* Determine whether the machine is SMP or not.  */
425   __is_smp = is_smp_system ();
426 }
427 strong_alias (__pthread_initialize_minimal_internal,
428               __pthread_initialize_minimal)