Merge from vendor branch NTPD:
[dragonfly.git] / lib / libc_r / uthread / uthread_init.c
1 /*
2  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by John Birrell.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $FreeBSD: src/lib/libc_r/uthread/uthread_init.c,v 1.23.2.11 2003/02/24 23:27:32 das Exp $
33  * $DragonFly: src/lib/libc_r/uthread/uthread_init.c,v 1.4 2005/03/13 15:10:03 swildner Exp $
34  */
35
36 /* Allocate space for global thread variables here: */
37 #define GLOBAL_PTHREAD_PRIVATE
38
39 #include <errno.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <poll.h>
45 #include <unistd.h>
46 #include <sys/ioctl.h>
47 #include <sys/sysctl.h>
48 #include <sys/time.h>
49 #include <sys/ttycom.h>
50 #include <sys/param.h>
51 #include <sys/user.h>
52 #include <sys/mman.h>
53 #include <machine/reg.h>
54 #include <pthread.h>
55 #include "pthread_private.h"
56
57 /*
58  * These are needed when linking statically.  All references within
59  * libgcc (and in the future libc) to these routines are weak, but
60  * if they are not (strongly) referenced by the application or other
61  * libraries, then the actual functions will not be loaded.
62  */
63 static void *thread_references[] = {
64         &_pthread_once,
65         &_pthread_key_create,
66         &_pthread_key_delete,
67         &_pthread_getspecific,
68         &_pthread_setspecific,
69         &_pthread_mutex_init,
70         &_pthread_mutex_destroy,
71         &_pthread_mutex_lock,
72         &_pthread_mutex_trylock,
73         &_pthread_mutex_unlock,
74         &_pthread_cond_init,
75         &_pthread_cond_destroy,
76         &_pthread_cond_wait,
77         &_pthread_cond_timedwait,
78         &_pthread_cond_signal,
79         &_pthread_cond_broadcast
80 };
81
82 #ifdef GCC_2_8_MADE_THREAD_AWARE
83 typedef void *** (*dynamic_handler_allocator)();
84 extern void __set_dynamic_handler_allocator(dynamic_handler_allocator);
85
86 static pthread_key_t except_head_key;
87
88 typedef struct {
89         void **__dynamic_handler_chain;
90         void *top_elt[2];
91 } except_struct;
92
93 static void ***dynamic_allocator_handler_fn()
94 {
95         except_struct *dh = (except_struct *)pthread_getspecific(except_head_key);
96
97         if(dh == NULL) {
98                 dh = (except_struct *)malloc( sizeof(except_struct) );
99                 memset(dh, '\0', sizeof(except_struct));
100                 dh->__dynamic_handler_chain= dh->top_elt;
101                 pthread_setspecific(except_head_key, (void *)dh);
102         }
103         return &dh->__dynamic_handler_chain;
104 }
105 #endif /* GCC_2_8_MADE_THREAD_AWARE */
106
107 /*
108  * Threaded process initialization
109  */
110
111 void    _thread_init(void) __attribute__((constructor));
112
113 void
114 _thread_init(void)
115 {
116         int             fd;
117         int             flags;
118         int             i;
119         size_t          len;
120         int             mib[2];
121         struct clockinfo clockinfo;
122         struct sigaction act;
123
124         /* Check if this function has already been called: */
125         if (_thread_initial)
126                 /* Only initialise the threaded application once. */
127                 return;
128
129         /*
130          * Make gcc quiescent about thread_references not being
131          * referenced:
132          */
133         if (thread_references[0] == NULL)
134                 PANIC("Mandatory pthread_* functions not loaded");
135
136         /*
137          * Check for the special case of this process running as
138          * or in place of init as pid = 1:
139          */
140         if (getpid() == 1) {
141                 /*
142                  * Setup a new session for this process which is
143                  * assumed to be running as root.
144                  */
145                 if (setsid() == -1)
146                         PANIC("Can't set session ID");
147                 if (revoke(_PATH_CONSOLE) != 0)
148                         PANIC("Can't revoke console");
149                 if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
150                         PANIC("Can't open console");
151                 if (setlogin("root") == -1)
152                         PANIC("Can't set login to root");
153                 if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
154                         PANIC("Can't set controlling terminal");
155                 if (__sys_dup2(fd, 0) == -1 ||
156                     __sys_dup2(fd, 1) == -1 ||
157                     __sys_dup2(fd, 2) == -1)
158                         PANIC("Can't dup2");
159         }
160
161         /* Get the standard I/O flags before messing with them : */
162         for (i = 0; i < 3; i++) {
163                 if (((_pthread_stdio_flags[i] =
164                     __sys_fcntl(i, F_GETFL, NULL)) == -1) &&
165                     (errno != EBADF))
166                         PANIC("Cannot get stdio flags");
167         }
168
169         /*
170          * Create a pipe that is written to by the signal handler to prevent
171          * signals being missed in calls to _select:
172          */
173         if (__sys_pipe(_thread_kern_pipe) != 0) {
174                 /* Cannot create pipe, so abort: */
175                 PANIC("Cannot create kernel pipe");
176         }
177
178         /*
179          * Make sure the pipe does not get in the way of stdio:
180          */
181         for (i = 0; i < 2; i++) {
182                 if (_thread_kern_pipe[i] < 3) {
183                         fd = __sys_fcntl(_thread_kern_pipe[i], F_DUPFD, 3);
184                         if (fd == -1)
185                             PANIC("Cannot create kernel pipe");
186                         __sys_close(_thread_kern_pipe[i]);
187                         _thread_kern_pipe[i] = fd;
188                 }
189         }
190         /* Get the flags for the read pipe: */
191         if ((flags = __sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
192                 /* Abort this application: */
193                 PANIC("Cannot get kernel read pipe flags");
194         }
195         /* Make the read pipe non-blocking: */
196         else if (__sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
197                 /* Abort this application: */
198                 PANIC("Cannot make kernel read pipe non-blocking");
199         }
200         /* Get the flags for the write pipe: */
201         else if ((flags = __sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
202                 /* Abort this application: */
203                 PANIC("Cannot get kernel write pipe flags");
204         }
205         /* Make the write pipe non-blocking: */
206         else if (__sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
207                 /* Abort this application: */
208                 PANIC("Cannot get kernel write pipe flags");
209         }
210         /* Allocate and initialize the ready queue: */
211         else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) {
212                 /* Abort this application: */
213                 PANIC("Cannot allocate priority ready queue.");
214         }
215         /* Allocate memory for the thread structure of the initial thread: */
216         else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
217                 /*
218                  * Insufficient memory to initialise this application, so
219                  * abort:
220                  */
221                 PANIC("Cannot allocate memory for initial thread");
222         }
223         /* Allocate memory for the scheduler stack: */
224         else if ((_thread_kern_sched_stack = malloc(SCHED_STACK_SIZE)) == NULL)
225                 PANIC("Failed to allocate stack for scheduler");
226         else {
227                 /* Zero the global kernel thread structure: */
228                 memset(&_thread_kern_thread, 0, sizeof(struct pthread));
229                 _thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
230                 memset(_thread_initial, 0, sizeof(struct pthread));
231
232                 /* Initialize the waiting and work queues: */
233                 TAILQ_INIT(&_waitingq);
234                 TAILQ_INIT(&_workq);
235
236                 /* Initialize the scheduling switch hook routine: */
237                 _sched_switch_hook = NULL;
238
239                 /* Give this thread default attributes: */
240                 memcpy((void *) &_thread_initial->attr, &pthread_attr_default,
241                     sizeof(struct pthread_attr));
242
243                 /* Initialize the thread stack cache: */
244                 SLIST_INIT(&_stackq);
245
246                 /* Find the stack top */
247                 mib[0] = CTL_KERN;
248                 mib[1] = KERN_USRSTACK;
249                 len = sizeof (int);
250                 if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
251                         _usrstack = (void *)USRSTACK;
252                 _next_stack = _usrstack - PTHREAD_STACK_INITIAL -
253                     PTHREAD_STACK_DEFAULT - (2 * PTHREAD_STACK_GUARD);
254                 /*
255                  * Create a red zone below the main stack.  All other stacks are
256                  * constrained to a maximum size by the paramters passed to
257                  * mmap(), but this stack is only limited by resource limits, so
258                  * this stack needs an explicitly mapped red zone to protect the
259                  * thread stack that is just beyond.
260                  */
261                 if (mmap(_usrstack - PTHREAD_STACK_INITIAL -
262                     PTHREAD_STACK_GUARD, PTHREAD_STACK_GUARD, 0, MAP_ANON,
263                     -1, 0) == MAP_FAILED)
264                         PANIC("Cannot allocate red zone for initial thread");
265
266                 /* Set the main thread stack pointer. */
267                 _thread_initial->stack = _usrstack - PTHREAD_STACK_INITIAL;
268
269                 /* Set the stack attributes: */
270                 _thread_initial->attr.stackaddr_attr = _thread_initial->stack;
271                 _thread_initial->attr.stacksize_attr = PTHREAD_STACK_INITIAL;
272
273                 /* Setup the context for the scheduler: */
274                 _setjmp(_thread_kern_sched_jb);
275                 SET_STACK_JB(_thread_kern_sched_jb, _thread_kern_sched_stack +
276                     SCHED_STACK_SIZE - sizeof(double));
277                 SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler);
278
279                 /*
280                  * Write a magic value to the thread structure
281                  * to help identify valid ones:
282                  */
283                 _thread_initial->magic = PTHREAD_MAGIC;
284
285                 /* Set the initial cancel state */
286                 _thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE |
287                     PTHREAD_CANCEL_DEFERRED;
288
289                 /* Default the priority of the initial thread: */
290                 _thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
291                 _thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
292                 _thread_initial->inherited_priority = 0;
293
294                 /* Initialise the state of the initial thread: */
295                 _thread_initial->state = PS_RUNNING;
296
297                 /* Set the name of the thread: */
298                 _thread_initial->name = strdup("_thread_initial");
299
300                 /* Initialize joiner to NULL (no joiner): */
301                 _thread_initial->joiner = NULL;
302
303                 /* Initialize the owned mutex queue and count: */
304                 TAILQ_INIT(&(_thread_initial->mutexq));
305                 _thread_initial->priority_mutex_count = 0;
306
307                 /* Initialize the global scheduling time: */
308                 _sched_ticks = 0;
309                 gettimeofday((struct timeval *) &_sched_tod, NULL);
310
311                 /* Initialize last active: */
312                 _thread_initial->last_active = (long) _sched_ticks;
313
314                 /* Initialize the initial context: */
315                 _thread_initial->curframe = NULL;
316
317                 /* Initialise the rest of the fields: */
318                 _thread_initial->poll_data.nfds = 0;
319                 _thread_initial->poll_data.fds = NULL;
320                 _thread_initial->sig_defer_count = 0;
321                 _thread_initial->yield_on_sig_undefer = 0;
322                 _thread_initial->specific_data = NULL;
323                 _thread_initial->cleanup = NULL;
324                 _thread_initial->flags = 0;
325                 _thread_initial->error = 0;
326                 TAILQ_INIT(&_thread_list);
327                 TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
328                 _set_curthread(_thread_initial);
329
330                 /* Initialise the global signal action structure: */
331                 sigfillset(&act.sa_mask);
332                 act.sa_handler = (void (*) ()) _thread_sig_handler;
333                 act.sa_flags = SA_SIGINFO | SA_RESTART;
334
335                 /* Clear pending signals for the process: */
336                 sigemptyset(&_process_sigpending);
337
338                 /* Clear the signal queue: */
339                 memset(_thread_sigq, 0, sizeof(_thread_sigq));
340
341                 /* Enter a loop to get the existing signal status: */
342                 for (i = 1; i < NSIG; i++) {
343                         /* Check for signals which cannot be trapped: */
344                         if (i == SIGKILL || i == SIGSTOP) {
345                         }
346
347                         /* Get the signal handler details: */
348                         else if (__sys_sigaction(i, NULL,
349                             &_thread_sigact[i - 1]) != 0) {
350                                 /*
351                                  * Abort this process if signal
352                                  * initialisation fails:
353                                  */
354                                 PANIC("Cannot read signal handler info");
355                         }
356
357                         /* Initialize the SIG_DFL dummy handler count. */
358                         _thread_dfl_count[i] = 0;
359                 }
360
361                 /*
362                  * Install the signal handler for the most important
363                  * signals that the user-thread kernel needs. Actually
364                  * SIGINFO isn't really needed, but it is nice to have.
365                  */
366                 if (__sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
367                     __sys_sigaction(SIGINFO,       &act, NULL) != 0 ||
368                     __sys_sigaction(SIGCHLD,       &act, NULL) != 0) {
369                         /*
370                          * Abort this process if signal initialisation fails:
371                          */
372                         PANIC("Cannot initialise signal handler");
373                 }
374                 _thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO;
375                 _thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO;
376                 _thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO;
377
378                 /* Get the process signal mask: */
379                 __sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask);
380
381                 /* Get the kernel clockrate: */
382                 mib[0] = CTL_KERN;
383                 mib[1] = KERN_CLOCKRATE;
384                 len = sizeof (struct clockinfo);
385                 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
386                         _clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
387                             clockinfo.tick : CLOCK_RES_USEC_MIN;
388
389                 /* Get the table size: */
390                 if ((_thread_dtablesize = getdtablesize()) < 0) {
391                         /*
392                          * Cannot get the system defined table size, so abort
393                          * this process.
394                          */
395                         PANIC("Cannot get dtablesize");
396                 }
397                 /* Allocate memory for the file descriptor table: */
398                 if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
399                         /* Avoid accesses to file descriptor table on exit: */
400                         _thread_dtablesize = 0;
401
402                         /*
403                          * Cannot allocate memory for the file descriptor
404                          * table, so abort this process.
405                          */
406                         PANIC("Cannot allocate memory for file descriptor table");
407                 }
408                 /* Allocate memory for the pollfd table: */
409                 if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
410                         /*
411                          * Cannot allocate memory for the file descriptor
412                          * table, so abort this process.
413                          */
414                         PANIC("Cannot allocate memory for pollfd table");
415                 } else {
416                         /*
417                          * Enter a loop to initialise the file descriptor
418                          * table:
419                          */
420                         for (i = 0; i < _thread_dtablesize; i++) {
421                                 /* Initialise the file descriptor table: */
422                                 _thread_fd_table[i] = NULL;
423                         }
424
425                         /* Initialize stdio file descriptor table entries: */
426                         for (i = 0; i < 3; i++) {
427                                 if ((_thread_fd_table_init(i) != 0) &&
428                                     (errno != EBADF))
429                                         PANIC("Cannot initialize stdio file "
430                                             "descriptor table entry");
431                         }
432                 }
433         }
434
435 #ifdef GCC_2_8_MADE_THREAD_AWARE
436         /* Create the thread-specific data for the exception linked list. */
437         if(pthread_key_create(&except_head_key, NULL) != 0)
438                 PANIC("Failed to create thread specific execption head");
439
440         /* Setup the gcc exception handler per thread. */
441         __set_dynamic_handler_allocator( dynamic_allocator_handler_fn );
442 #endif /* GCC_2_8_MADE_THREAD_AWARE */
443
444         /* Initialise the garbage collector mutex and condition variable. */
445         if (pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
446             pthread_cond_init(&_gc_cond,NULL) != 0)
447                 PANIC("Failed to initialise garbage collector mutex or condvar");
448 }
449
450 int _thread_autoinit_dummy_decl = 0;