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