thr_create.c revision 67097
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 67097 2000-10-13 22:12:32Z 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)
52#define SIGFRAME_OFF(f)	offsetof(struct pthread_signal_frame, f)
53int _thread_next_offset			= OFF(tle.tqe_next);
54int _thread_uniqueid_offset		= OFF(uniqueid);
55int _thread_state_offset		= OFF(state);
56int _thread_name_offset			= OFF(name);
57int _thread_curframe_offset		= OFF(curframe);
58int _thread_sigframe_ctx_offset		= SIGFRAME_OFF(ctx);
59int _thread_sigframe_ctxtype_offset	= SIGFRAME_OFF(ctxtype);
60#undef OFF
61#undef SIGFRAME_OFF
62
63int _thread_PS_RUNNING_value		= PS_RUNNING;
64int _thread_PS_DEAD_value		= PS_DEAD;
65int _thread_CTX_JB_NOSIG_value		= CTX_JB_NOSIG;
66int _thread_CTX_JB_value		= CTX_JB;
67int _thread_CTX_SJB_value		= CTX_SJB;
68int _thread_CTX_UC_value		= CTX_UC;
69int _thread_sigframe_size_value		= sizeof(struct pthread_signal_frame);
70
71int
72pthread_create(pthread_t * thread, const pthread_attr_t * attr,
73	       void *(*start_routine) (void *), void *arg)
74{
75	int		f_gc = 0;
76	int             ret = 0;
77	pthread_t       gc_thread;
78	pthread_t       new_thread;
79	pthread_attr_t	pattr;
80	void           *stack;
81
82	/*
83	 * Locking functions in libc are required when there are
84	 * threads other than the initial thread.
85	 */
86	__isthreaded = 1;
87
88	/* Allocate memory for the thread structure: */
89	if ((new_thread = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
90		/* Insufficient memory to create a thread: */
91		ret = EAGAIN;
92	} else {
93		/* Check if default thread attributes are required: */
94		if (attr == NULL || *attr == NULL) {
95			/* Use the default thread attributes: */
96			pattr = &pthread_attr_default;
97		} else {
98			pattr = *attr;
99		}
100		/* Check if a stack was specified in the thread attributes: */
101		if ((stack = pattr->stackaddr_attr) != NULL) {
102		}
103		/* Allocate memory for a default-size stack: */
104		else if (pattr->stacksize_attr == PTHREAD_STACK_DEFAULT) {
105			struct stack	*spare_stack;
106
107			/* Allocate or re-use a default-size stack. */
108
109			/*
110			 * Use the garbage collector mutex for synchronization
111			 * of the spare stack list.
112			 */
113			if (pthread_mutex_lock(&_gc_mutex) != 0)
114				PANIC("Cannot lock gc mutex");
115
116			if ((spare_stack = SLIST_FIRST(&_stackq)) != NULL) {
117				/* Use the spare stack. */
118				SLIST_REMOVE_HEAD(&_stackq, qe);
119
120				/* Unlock the garbage collector mutex. */
121				if (pthread_mutex_unlock(&_gc_mutex) != 0)
122					PANIC("Cannot unlock gc mutex");
123
124				stack = sizeof(struct stack)
125				    + (void *) spare_stack
126				    - PTHREAD_STACK_DEFAULT;
127			} else {
128				/* Allocate a new stack. */
129				stack = _next_stack + PTHREAD_STACK_GUARD;
130
131				/*
132				 * Even if stack allocation fails, we don't want
133				 * to try to use this location again, so
134				 * unconditionally decrement _next_stack.  Under
135				 * normal operating conditions, the most likely
136				 * reason for an mmap() error is a stack
137				 * overflow of the adjacent thread stack.
138				 */
139				_next_stack -= (PTHREAD_STACK_DEFAULT
140				    + PTHREAD_STACK_GUARD);
141
142				/* Unlock the garbage collector mutex. */
143				if (pthread_mutex_unlock(&_gc_mutex) != 0)
144					PANIC("Cannot unlock gc mutex");
145
146				/* Stack: */
147				if (mmap(stack, PTHREAD_STACK_DEFAULT,
148				    PROT_READ | PROT_WRITE, MAP_STACK,
149				    -1, 0) == MAP_FAILED) {
150					ret = EAGAIN;
151					free(new_thread);
152				}
153			}
154		}
155		/*
156		 * The user wants a stack of a particular size.  Lets hope they
157		 * really know what they want, and simply malloc the stack.
158		 */
159		else if ((stack = (void *) malloc(pattr->stacksize_attr))
160		    == NULL) {
161			/* Insufficient memory to create a thread: */
162			ret = EAGAIN;
163			free(new_thread);
164		}
165
166		/* Check for errors: */
167		if (ret != 0) {
168		} else {
169			/* Initialise the thread structure: */
170			memset(new_thread, 0, sizeof(struct pthread));
171			new_thread->slice_usec = -1;
172			new_thread->stack = stack;
173			new_thread->start_routine = start_routine;
174			new_thread->arg = arg;
175
176			new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
177			    PTHREAD_CANCEL_DEFERRED;
178
179			/*
180			 * Write a magic value to the thread structure
181			 * to help identify valid ones:
182			 */
183			new_thread->magic = PTHREAD_MAGIC;
184
185			/* Initialise the thread for signals: */
186			new_thread->sigmask = _thread_run->sigmask;
187
188			/* Initialize the first signal frame: */
189			new_thread->sigframes[0] = &new_thread->sigframe0;
190			new_thread->curframe = &new_thread->sigframe0;
191
192			/* Initialise the jump buffer: */
193			_setjmp(new_thread->curframe->ctx.jb);
194
195			/*
196			 * Set up new stack frame so that it looks like it
197			 * returned from a longjmp() to the beginning of
198			 * _thread_start().
199			 */
200			SET_RETURN_ADDR_JB(new_thread->curframe->ctx.jb,
201			    _thread_start);
202
203			/* The stack starts high and builds down: */
204			SET_STACK_JB(new_thread->curframe->ctx.jb,
205			    (long)new_thread->stack + pattr->stacksize_attr
206			    - sizeof(double));
207
208			/* Initialize the rest of the frame: */
209			new_thread->curframe->ctxtype = CTX_JB_NOSIG;
210			/* Set the base of the stack: */
211			new_thread->curframe->stackp =
212			    GET_STACK_JB(new_thread->curframe->ctx.jb);
213			new_thread->sigframe_count = 0;
214
215			/* Copy the thread attributes: */
216			memcpy(&new_thread->attr, pattr, sizeof(struct pthread_attr));
217
218			/*
219			 * Check if this thread is to inherit the scheduling
220			 * attributes from its parent:
221			 */
222			if (new_thread->attr.flags & PTHREAD_INHERIT_SCHED) {
223				/* Copy the scheduling attributes: */
224				new_thread->base_priority =
225				    _thread_run->base_priority &
226				    ~PTHREAD_SIGNAL_PRIORITY;
227				new_thread->attr.prio =
228				    _thread_run->base_priority &
229				    ~PTHREAD_SIGNAL_PRIORITY;
230				new_thread->attr.sched_policy =
231				    _thread_run->attr.sched_policy;
232			} else {
233				/*
234				 * Use just the thread priority, leaving the
235				 * other scheduling attributes as their
236				 * default values:
237				 */
238				new_thread->base_priority =
239				    new_thread->attr.prio;
240			}
241			new_thread->active_priority = new_thread->base_priority;
242			new_thread->inherited_priority = 0;
243
244			/* Initialise the join queue for the new thread: */
245			TAILQ_INIT(&(new_thread->join_queue));
246
247			/* Initialize the mutex queue: */
248			TAILQ_INIT(&new_thread->mutexq);
249
250			/* Initialise hooks in the thread structure: */
251			new_thread->specific_data = NULL;
252			new_thread->cleanup = NULL;
253			new_thread->flags = 0;
254			new_thread->poll_data.nfds = 0;
255			new_thread->poll_data.fds = NULL;
256			new_thread->continuation = NULL;
257
258			/*
259			 * Defer signals to protect the scheduling queues
260			 * from access by the signal handler:
261			 */
262			_thread_kern_sig_defer();
263
264			/*
265			 * Initialise the unique id which GDB uses to
266			 * track threads.
267			 */
268			new_thread->uniqueid = next_uniqueid++;
269
270			/*
271			 * Check if the garbage collector thread
272			 * needs to be started.
273			 */
274			f_gc = (TAILQ_FIRST(&_thread_list) == _thread_initial);
275
276			/* Add the thread to the linked list of all threads: */
277			TAILQ_INSERT_HEAD(&_thread_list, new_thread, tle);
278
279			if (pattr->suspend == PTHREAD_CREATE_SUSPENDED)
280				new_thread->state = PS_SUSPENDED;
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			 * Start a garbage collector thread
299			 * if necessary.
300			 */
301			if (f_gc && pthread_create(&gc_thread,NULL,
302				    _thread_gc,NULL) != 0)
303				PANIC("Can't create gc thread");
304
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