thr_create.c revision 48749
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 REGENTS 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 * $Id: uthread_create.c,v 1.16 1999/07/11 05:56:36 jasone Exp $
33 */
34#include <errno.h>
35#include <stdlib.h>
36#include <string.h>
37#include <fcntl.h>
38#include <unistd.h>
39#include <sys/time.h>
40#include <sys/types.h>
41#include <sys/mman.h>
42#ifdef _THREAD_SAFE
43#include <machine/reg.h>
44#include <pthread.h>
45#include "pthread_private.h"
46#include "libc_private.h"
47
48int
49pthread_create(pthread_t * thread, const pthread_attr_t * attr,
50	       void *(*start_routine) (void *), void *arg)
51{
52	int		f_gc = 0;
53	int             i;
54	int             ret = 0;
55	int             status;
56	pthread_t       gc_thread;
57	pthread_t       new_thread;
58	pthread_attr_t	pattr;
59	void           *stack;
60
61	/*
62	 * Locking functions in libc are required when there are
63	 * threads other than the initial thread.
64	 */
65	__isthreaded = 1;
66
67	/* Allocate memory for the thread structure: */
68	if ((new_thread = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
69		/* Insufficient memory to create a thread: */
70		ret = EAGAIN;
71	} else {
72		/* Check if default thread attributes are required: */
73		if (attr == NULL || *attr == NULL) {
74			/* Use the default thread attributes: */
75			pattr = &pthread_attr_default;
76		} else {
77			pattr = *attr;
78		}
79		/* Check if a stack was specified in the thread attributes: */
80		if ((stack = pattr->stackaddr_attr) != NULL) {
81		}
82		/* Allocate memory for a default-size stack: */
83		else if (pattr->stacksize_attr == PTHREAD_STACK_DEFAULT) {
84			struct stack	*spare_stack;
85
86			/* Allocate or re-use a default-size stack. */
87
88			/*
89			 * Use the garbage collector mutex for synchronization
90			 * of the spare stack list.
91			 */
92			if (pthread_mutex_lock(&_gc_mutex) != 0)
93				PANIC("Cannot lock gc mutex");
94
95			if ((spare_stack = SLIST_FIRST(&_stackq)) != NULL) {
96				/* Use the spare stack. */
97				SLIST_REMOVE_HEAD(&_stackq, qe);
98
99				/* Unlock the garbage collector mutex. */
100				if (pthread_mutex_unlock(&_gc_mutex) != 0)
101					PANIC("Cannot unlock gc mutex");
102
103				stack = sizeof(struct stack)
104				    + (void *) spare_stack
105				    - PTHREAD_STACK_DEFAULT;
106			} else {
107				/* Unlock the garbage collector mutex. */
108				if (pthread_mutex_unlock(&_gc_mutex) != 0)
109					PANIC("Cannot unlock gc mutex");
110
111				/* Allocate a new stack. */
112				stack = _next_stack + PTHREAD_STACK_GUARD;
113				/*
114				 * Even if stack allocation fails, we don't want
115				 * to try to use this location again, so
116				 * unconditionally decrement _next_stack.  Under
117				 * normal operating conditions, the most likely
118				 * reason for an mmap() error is a stack
119				 * overflow of the adjacent thread stack.
120				 */
121				_next_stack -= (PTHREAD_STACK_DEFAULT
122						+ PTHREAD_STACK_GUARD);
123
124				/* Red zone: */
125				if (mmap(_next_stack, PTHREAD_STACK_GUARD, 0,
126					 MAP_ANON, -1, 0) == MAP_FAILED) {
127					ret = EAGAIN;
128					free(new_thread);
129				}
130				/* Stack: */
131				else if (mmap(stack,
132					      PTHREAD_STACK_DEFAULT,
133					      PROT_READ | PROT_WRITE,
134#ifdef __i386__
135					      MAP_STACK,
136#else
137					      MAP_ANON,
138#endif
139					      -1, 0) == MAP_FAILED) {
140					ret = EAGAIN;
141					munmap(_next_stack,
142					       PTHREAD_STACK_GUARD);
143					free(new_thread);
144				}
145			}
146		}
147		/*
148		 * The user wants a stack of a particular size.  Lets hope they
149		 * really know what they want, and simply malloc the stack.
150		 */
151		else if ((stack = (void *) malloc(pattr->stacksize_attr))
152			 == NULL) {
153			/* Insufficient memory to create a thread: */
154			ret = EAGAIN;
155			free(new_thread);
156		}
157
158		/* Check for errors: */
159		if (ret != 0) {
160		} else {
161			/* Initialise the thread structure: */
162			memset(new_thread, 0, sizeof(struct pthread));
163			new_thread->slice_usec = -1;
164			new_thread->sig_saved = 0;
165			new_thread->stack = stack;
166			new_thread->start_routine = start_routine;
167			new_thread->arg = arg;
168
169			/*
170			 * Write a magic value to the thread structure
171			 * to help identify valid ones:
172			 */
173			new_thread->magic = PTHREAD_MAGIC;
174
175			/* Initialise the thread for signals: */
176			new_thread->sigmask = _thread_run->sigmask;
177
178			/* Initialise the jump buffer: */
179			setjmp(new_thread->saved_jmp_buf);
180
181			/*
182			 * Set up new stack frame so that it looks like it
183			 * returned from a longjmp() to the beginning of
184			 * _thread_start().
185			 */
186#if	defined(__FreeBSD__)
187#if	defined(__alpha__)
188			new_thread->saved_jmp_buf[0]._jb[2] = (long) _thread_start;
189			new_thread->saved_jmp_buf[0]._jb[4 + R_RA] = 0;
190			new_thread->saved_jmp_buf[0]._jb[4 + R_T12] = (long) _thread_start;
191#else
192			new_thread->saved_jmp_buf[0]._jb[0] = (long) _thread_start;
193#endif
194#elif	defined(__NetBSD__)
195#if	defined(__alpha__)
196			new_thread->saved_jmp_buf[2] = (long) _thread_start;
197			new_thread->saved_jmp_buf[4 + R_RA] = 0;
198			new_thread->saved_jmp_buf[4 + R_T12] = (long) _thread_start;
199#else
200			new_thread->saved_jmp_buf[0] = (long) _thread_start;
201#endif
202#else
203#error	"Don't recognize this operating system!"
204#endif
205
206			/* The stack starts high and builds down: */
207#if	defined(__FreeBSD__)
208#if	defined(__alpha__)
209			new_thread->saved_jmp_buf[0]._jb[4 + R_SP] = (long) new_thread->stack + pattr->stacksize_attr - sizeof(double);
210#else
211			new_thread->saved_jmp_buf[0]._jb[2] = (int) (new_thread->stack + pattr->stacksize_attr - sizeof(double));
212#endif
213#elif	defined(__NetBSD__)
214#if	defined(__alpha__)
215			new_thread->saved_jmp_buf[4 + R_SP] = (long) new_thread->stack + pattr->stacksize_attr - sizeof(double);
216#else
217			new_thread->saved_jmp_buf[2] = (long) new_thread->stack + pattr->stacksize_attr - sizeof(double);
218#endif
219#else
220#error	"Don't recognize this operating system!"
221#endif
222
223			/* Copy the thread attributes: */
224			memcpy(&new_thread->attr, pattr, sizeof(struct pthread_attr));
225
226			/*
227			 * Check if this thread is to inherit the scheduling
228			 * attributes from its parent:
229			 */
230			if (new_thread->attr.flags & PTHREAD_INHERIT_SCHED) {
231				/* Copy the scheduling attributes: */
232				new_thread->base_priority
233				    = _thread_run->base_priority;
234				new_thread->attr.prio
235				    = _thread_run->base_priority;
236				new_thread->attr.sched_policy
237				    = _thread_run->attr.sched_policy;
238			} else {
239				/*
240				 * Use just the thread priority, leaving the
241				 * other scheduling attributes as their
242				 * default values:
243				 */
244				new_thread->base_priority
245				    = new_thread->attr.prio;
246			}
247			new_thread->active_priority = new_thread->base_priority;
248			new_thread->inherited_priority = 0;
249
250			/* Initialise the join queue for the new thread: */
251			TAILQ_INIT(&(new_thread->join_queue));
252
253			/* Initialize the mutex queue: */
254			TAILQ_INIT(&new_thread->mutexq);
255
256			/* Initialise hooks in the thread structure: */
257			new_thread->specific_data = NULL;
258			new_thread->cleanup = NULL;
259			new_thread->flags = 0;
260			new_thread->poll_data.nfds = 0;
261			new_thread->poll_data.fds = NULL;
262
263			/*
264			 * Defer signals to protect the scheduling queues
265			 * from access by the signal handler:
266			 */
267			_thread_kern_sig_defer();
268
269			/*
270			 * Check if the garbage collector thread
271			 * needs to be started.
272			 */
273			f_gc = (TAILQ_FIRST(&_thread_list) == _thread_initial);
274
275			/* Add the thread to the linked list of all threads: */
276			TAILQ_INSERT_HEAD(&_thread_list, new_thread, tle);
277
278			if (pattr->suspend == PTHREAD_CREATE_SUSPENDED) {
279				new_thread->state = PS_SUSPENDED;
280				PTHREAD_WAITQ_INSERT(new_thread);
281			} else {
282				new_thread->state = PS_RUNNING;
283				PTHREAD_PRIOQ_INSERT_TAIL(new_thread);
284			}
285
286			/*
287			 * Undefer and handle pending signals, yielding
288			 * if necessary.
289			 */
290			_thread_kern_sig_undefer();
291
292			/* Return a pointer to the thread structure: */
293			(*thread) = new_thread;
294
295			/* Schedule the new user thread: */
296			_thread_kern_sched(NULL);
297
298			/*
299			 * Start a garbage collector thread
300			 * if necessary.
301			 */
302			if (f_gc && pthread_create(&gc_thread,NULL,
303				    _thread_gc,NULL) != 0)
304				PANIC("Can't create gc thread");
305		}
306	}
307
308	/* Return the status: */
309	return (ret);
310}
311
312void
313_thread_start(void)
314{
315	/* We just left the scheduler via longjmp: */
316	_thread_kern_in_sched = 0;
317
318	/* Run the current thread's start routine with argument: */
319	pthread_exit(_thread_run->start_routine(_thread_run->arg));
320
321	/* This point should never be reached. */
322	PANIC("Thread has resumed after exit");
323}
324#endif
325