OSDN Git Service

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