thr_create.c revision 113786
1/*
2 * Copyright (c) 2003 Daniel M. Eischen <deischen@gdeb.com>
3 * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 *    must display the following acknowledgement:
16 *	This product includes software developed by John Birrell.
17 * 4. Neither the name of the author nor the names of any co-contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * $FreeBSD: head/lib/libkse/thread/thr_create.c 113786 2003-04-21 04:02:56Z deischen $
34 */
35#include <errno.h>
36#include <stdlib.h>
37#include <string.h>
38#include <fcntl.h>
39#include <unistd.h>
40#include <stddef.h>
41#include <sys/time.h>
42#include <machine/reg.h>
43#include <pthread.h>
44#include "thr_private.h"
45#include "libc_private.h"
46
47static u_int64_t next_uniqueid = 1;
48
49#define OFF(f)	offsetof(struct pthread, f)
50int _thread_next_offset			= OFF(tle.tqe_next);
51int _thread_uniqueid_offset		= OFF(uniqueid);
52int _thread_state_offset		= OFF(state);
53int _thread_name_offset			= OFF(name);
54int _thread_ctx_offset			= OFF(tmbx.tm_context);
55#undef OFF
56
57int _thread_PS_RUNNING_value		= PS_RUNNING;
58int _thread_PS_DEAD_value		= PS_DEAD;
59
60static int  create_stack(struct pthread_attr *pattr);
61static void thread_start(struct pthread *curthread,
62		void *(*start_routine) (void *), void *arg);
63
64__weak_reference(_pthread_create, pthread_create);
65
66/*
67 * Some notes on new thread creation and first time initializion
68 * to enable multi-threading.
69 *
70 * There are basically two things that need to be done.
71 *
72 *   1) The internal library variables must be initialized.
73 *   2) Upcalls need to be enabled to allow multiple threads
74 *      to be run.
75 *
76 * The first may be done as a result of other pthread functions
77 * being called.  When _thr_initial is null, _libpthread_init is
78 * called to initialize the internal variables; this also creates
79 * or sets the initial thread.  It'd be nice to automatically
80 * have _libpthread_init called on program execution so we don't
81 * have to have checks throughout the library.
82 *
83 * The second part is only triggered by the creation of the first
84 * thread (other than the initial/main thread).  If the thread
85 * being created is a scope system thread, then a new KSE/KSEG
86 * pair needs to be allocated.  Also, if upcalls haven't been
87 * enabled on the initial thread's KSE, they must be now that
88 * there is more than one thread; this could be delayed until
89 * the initial KSEG has more than one thread.
90 */
91int
92_pthread_create(pthread_t * thread, const pthread_attr_t * attr,
93	       void *(*start_routine) (void *), void *arg)
94{
95	struct kse *curkse;
96	struct pthread *curthread, *new_thread;
97	struct kse *kse = NULL;
98	struct kse_group *kseg = NULL;
99	kse_critical_t crit;
100	int i;
101	int ret = 0;
102
103	if (_thr_initial == NULL)
104		_libpthread_init(NULL);
105
106	/*
107	 * Turn on threaded mode, if failed, it is unnecessary to
108	 * do further work.
109	 */
110	if (_kse_isthreaded() == 0 && _kse_setthreaded(1)) {
111		return (EAGAIN);
112	}
113	curthread = _get_curthread();
114
115	/*
116	 * Allocate memory for the thread structure.
117	 * Some functions use malloc, so don't put it
118	 * in a critical region.
119	 */
120	if ((new_thread = _thr_alloc(curthread)) == NULL) {
121		/* Insufficient memory to create a thread: */
122		ret = EAGAIN;
123	} else {
124		/* Initialize the thread structure: */
125		memset(new_thread, 0, sizeof(struct pthread));
126
127		/* Check if default thread attributes are required: */
128		if (attr == NULL || *attr == NULL)
129			/* Use the default thread attributes: */
130			new_thread->attr = _pthread_attr_default;
131		else
132			new_thread->attr = *(*attr);
133
134		if (create_stack(&new_thread->attr) != 0) {
135			/* Insufficient memory to create a stack: */
136			ret = EAGAIN;
137			_thr_free(curthread, new_thread);
138		}
139		else if (((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) != 0) &&
140		    (((kse = _kse_alloc(curthread)) == NULL)
141		    || ((kseg = _kseg_alloc(curthread)) == NULL))) {
142			/* Insufficient memory to create a new KSE/KSEG: */
143			ret = EAGAIN;
144			if (kse != NULL)
145				_kse_free(curthread, kse);
146			if ((new_thread->attr.flags & THR_STACK_USER) == 0) {
147				crit = _kse_critical_enter();
148				curkse = _get_curkse();
149				KSE_LOCK_ACQUIRE(curkse, &_thread_list_lock);
150				/* Stack routines don't use malloc/free. */
151				_thr_stack_free(&new_thread->attr);
152				KSE_LOCK_RELEASE(curkse, &_thread_list_lock);
153				_kse_critical_leave(crit);
154			}
155			_thr_free(curthread, new_thread);
156		}
157		else {
158			if (kseg != NULL) {
159				/* Add the KSE to the KSEG's list of KSEs. */
160				TAILQ_INSERT_HEAD(&kseg->kg_kseq, kse, k_qe);
161				kse->k_kseg = kseg;
162				kse->k_schedq = &kseg->kg_schedq;
163			}
164			/*
165			 * Write a magic value to the thread structure
166			 * to help identify valid ones:
167			 */
168			new_thread->magic = THR_MAGIC;
169
170			new_thread->slice_usec = -1;
171			new_thread->start_routine = start_routine;
172			new_thread->arg = arg;
173			new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
174			    PTHREAD_CANCEL_DEFERRED;
175
176			/* Initialize the thread for signals: */
177			new_thread->sigmask = curthread->sigmask;
178
179			/* No thread is wanting to join to this one: */
180			new_thread->joiner = NULL;
181
182			/* Initialize the signal frame: */
183			new_thread->curframe = NULL;
184
185			/*
186			 * Initialize the machine context.
187			 * Enter a critical region to get consistent context.
188			 */
189			crit = _kse_critical_enter();
190			THR_GETCONTEXT(&new_thread->tmbx.tm_context);
191			_kse_critical_leave(crit);
192			new_thread->tmbx.tm_udata = new_thread;
193			new_thread->tmbx.tm_context.uc_sigmask =
194			    new_thread->sigmask;
195			new_thread->tmbx.tm_context.uc_stack.ss_size =
196			    new_thread->attr.stacksize_attr;
197			new_thread->tmbx.tm_context.uc_stack.ss_sp =
198			    new_thread->attr.stackaddr_attr;
199			makecontext(&new_thread->tmbx.tm_context,
200			    (void (*)(void))thread_start, 4, new_thread,
201			    start_routine, arg);
202			/*
203			 * Check if this thread is to inherit the scheduling
204			 * attributes from its parent:
205			 */
206			if ((new_thread->attr.flags & PTHREAD_INHERIT_SCHED) != 0) {
207				/*
208				 * Copy the scheduling attributes.
209				 * Lock the scheduling lock to get consistent
210				 * scheduling parameters.
211				 */
212				THR_SCHED_LOCK(curthread, curthread);
213				new_thread->base_priority =
214				    curthread->base_priority &
215				    ~THR_SIGNAL_PRIORITY;
216				new_thread->attr.prio =
217				    curthread->base_priority &
218				    ~THR_SIGNAL_PRIORITY;
219				new_thread->attr.sched_policy =
220				    curthread->attr.sched_policy;
221				THR_SCHED_UNLOCK(curthread, curthread);
222			} else {
223				/*
224				 * Use just the thread priority, leaving the
225				 * other scheduling attributes as their
226				 * default values:
227				 */
228				new_thread->base_priority =
229				    new_thread->attr.prio;
230			}
231			new_thread->active_priority = new_thread->base_priority;
232			new_thread->inherited_priority = 0;
233
234			/* Initialize the mutex queue: */
235			TAILQ_INIT(&new_thread->mutexq);
236
237			/*
238			 * Initialize thread locking.
239			 * Lock initializing needs malloc, so don't
240			 * enter critical region before doing this!
241			 */
242			if (_lock_init(&new_thread->lock, LCK_ADAPTIVE,
243			    _thr_lock_wait, _thr_lock_wakeup) != 0)
244				PANIC("Cannot initialize thread lock");
245			for (i = 0; i < MAX_THR_LOCKLEVEL; i++) {
246				_lockuser_init(&new_thread->lockusers[i],
247				    (void *)new_thread);
248				_LCK_SET_PRIVATE2(&new_thread->lockusers[i],
249				    (void *)new_thread);
250			}
251
252			/* Initialise hooks in the thread structure: */
253			new_thread->specific = NULL;
254			new_thread->cleanup = NULL;
255			new_thread->flags = 0;
256			new_thread->continuation = NULL;
257
258			if (new_thread->attr.suspend == THR_CREATE_SUSPENDED)
259				new_thread->state = PS_SUSPENDED;
260			else
261				new_thread->state = PS_RUNNING;
262
263			/*
264			 * System scope threads have their own kse and
265			 * kseg.  Process scope threads are all hung
266			 * off the main process kseg.
267			 */
268			if ((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) == 0) {
269				new_thread->kseg = _kse_initial->k_kseg;
270				new_thread->kse = _kse_initial;
271			}
272			else {
273				kse->k_curthread = NULL;
274#ifdef NOT_YET
275				kse->k_kseg->kg_flags |= KGF_SINGLE_THREAD;
276#endif
277				new_thread->kse = kse;
278				new_thread->kseg = kse->k_kseg;
279				kse->k_mbx.km_udata = kse;
280				kse->k_mbx.km_curthread = NULL;
281			}
282
283			crit = _kse_critical_enter();
284			KSE_LOCK_ACQUIRE(curthread->kse, &_thread_list_lock);
285			/*
286			 * Initialise the unique id which GDB uses to
287			 * track threads.
288			 */
289			new_thread->uniqueid = next_uniqueid++;
290			/* Add the thread to the linked list of all threads: */
291			THR_LIST_ADD(new_thread);
292			KSE_LOCK_RELEASE(curthread->kse, &_thread_list_lock);
293
294			/*
295			 * Schedule the new thread starting a new KSEG/KSE
296			 * pair if necessary.
297			 */
298			_thr_schedule_add(curthread, new_thread);
299			_kse_critical_leave(crit);
300
301			/* Return a pointer to the thread structure: */
302			(*thread) = new_thread;
303		}
304	}
305
306	/* Return the status: */
307	return (ret);
308}
309
310static int
311create_stack(struct pthread_attr *pattr)
312{
313	int ret;
314
315	/* Check if a stack was specified in the thread attributes: */
316	if ((pattr->stackaddr_attr) != NULL) {
317		pattr->guardsize_attr = 0;
318		pattr->flags = THR_STACK_USER;
319		ret = 0;
320	}
321	else
322		ret = _thr_stack_alloc(pattr);
323	return (ret);
324}
325
326
327static void
328thread_start(struct pthread *curthread, void *(*start_routine) (void *),
329    void *arg)
330{
331	/* Run the current thread's start routine with argument: */
332	pthread_exit(start_routine(arg));
333
334	/* This point should never be reached. */
335	PANIC("Thread has resumed after exit");
336}
337