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