thr_create.c revision 116974
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 116974 2003-06-28 09:41:59Z davidxu $
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
47#define OFF(f)	offsetof(struct pthread, f)
48int _thread_next_offset			= OFF(tle.tqe_next);
49int _thread_uniqueid_offset		= OFF(uniqueid);
50int _thread_state_offset		= OFF(state);
51int _thread_name_offset			= OFF(name);
52int _thread_ctx_offset			= OFF(tmbx.tm_context);
53#undef OFF
54
55int _thread_PS_RUNNING_value		= PS_RUNNING;
56int _thread_PS_DEAD_value		= PS_DEAD;
57
58static void free_thread(struct pthread *curthread, struct pthread *thread);
59static int  create_stack(struct pthread_attr *pattr);
60static void thread_start(struct pthread *curthread,
61		void *(*start_routine) (void *), void *arg);
62
63__weak_reference(_pthread_create, pthread_create);
64
65/*
66 * Some notes on new thread creation and first time initializion
67 * to enable multi-threading.
68 *
69 * There are basically two things that need to be done.
70 *
71 *   1) The internal library variables must be initialized.
72 *   2) Upcalls need to be enabled to allow multiple threads
73 *      to be run.
74 *
75 * The first may be done as a result of other pthread functions
76 * being called.  When _thr_initial is null, _libpthread_init is
77 * called to initialize the internal variables; this also creates
78 * or sets the initial thread.  It'd be nice to automatically
79 * have _libpthread_init called on program execution so we don't
80 * have to have checks throughout the library.
81 *
82 * The second part is only triggered by the creation of the first
83 * thread (other than the initial/main thread).  If the thread
84 * being created is a scope system thread, then a new KSE/KSEG
85 * pair needs to be allocated.  Also, if upcalls haven't been
86 * enabled on the initial thread's KSE, they must be now that
87 * there is more than one thread; this could be delayed until
88 * the initial KSEG has more than one thread.
89 */
90int
91_pthread_create(pthread_t * thread, const pthread_attr_t * attr,
92	       void *(*start_routine) (void *), void *arg)
93{
94	struct kse *curkse;
95	struct pthread *curthread, *new_thread;
96	struct kse *kse = NULL;
97	struct kse_group *kseg = NULL;
98	void *p;
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		p = new_thread->alloc_addr;
126		memset(new_thread, 0, sizeof(struct pthread));
127		new_thread->alloc_addr = p;
128
129		/* Check if default thread attributes are required: */
130		if (attr == NULL || *attr == NULL)
131			/* Use the default thread attributes: */
132			new_thread->attr = _pthread_attr_default;
133		else
134			new_thread->attr = *(*attr);
135
136		if (create_stack(&new_thread->attr) != 0) {
137			/* Insufficient memory to create a stack: */
138			ret = EAGAIN;
139			_thr_free(curthread, new_thread);
140		}
141		else if (((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) != 0) &&
142		    (((kse = _kse_alloc(curthread)) == NULL)
143		    || ((kseg = _kseg_alloc(curthread)) == NULL))) {
144			/* Insufficient memory to create a new KSE/KSEG: */
145			ret = EAGAIN;
146			if (kse != NULL) {
147				kse->k_mbx.km_flags |= KMF_DONE;
148				_kse_free(curthread, kse);
149			}
150			if ((new_thread->attr.flags & THR_STACK_USER) == 0) {
151				crit = _kse_critical_enter();
152				curkse = _get_curkse();
153				KSE_LOCK_ACQUIRE(curkse, &_thread_list_lock);
154				/* Stack routines don't use malloc/free. */
155				_thr_stack_free(&new_thread->attr);
156				KSE_LOCK_RELEASE(curkse, &_thread_list_lock);
157				_kse_critical_leave(crit);
158			}
159			_thr_free(curthread, new_thread);
160		}
161		else {
162			if (kseg != NULL) {
163				/* Add the KSE to the KSEG's list of KSEs. */
164				TAILQ_INSERT_HEAD(&kseg->kg_kseq, kse, k_kgqe);
165				kseg->kg_ksecount = 1;
166				kse->k_kseg = kseg;
167				kse->k_schedq = &kseg->kg_schedq;
168			}
169			/*
170			 * Write a magic value to the thread structure
171			 * to help identify valid ones:
172			 */
173			new_thread->magic = THR_MAGIC;
174
175			new_thread->slice_usec = -1;
176			new_thread->start_routine = start_routine;
177			new_thread->arg = arg;
178			new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
179			    PTHREAD_CANCEL_DEFERRED;
180
181			/* Initialize the thread for signals: */
182			new_thread->sigmask = curthread->sigmask;
183
184			/* No thread is wanting to join to this one: */
185			new_thread->joiner = NULL;
186
187			/* Initialize the signal frame: */
188			new_thread->curframe = NULL;
189
190			/*
191			 * Initialize the machine context.
192			 * Enter a critical region to get consistent context.
193			 */
194			crit = _kse_critical_enter();
195			THR_GETCONTEXT(&new_thread->tmbx.tm_context);
196			_kse_critical_leave(crit);
197			new_thread->tmbx.tm_udata = new_thread;
198			new_thread->tmbx.tm_context.uc_sigmask =
199			    new_thread->sigmask;
200			new_thread->tmbx.tm_context.uc_stack.ss_size =
201			    new_thread->attr.stacksize_attr;
202			new_thread->tmbx.tm_context.uc_stack.ss_sp =
203			    new_thread->attr.stackaddr_attr;
204			makecontext(&new_thread->tmbx.tm_context,
205			    (void (*)(void))thread_start, 4, new_thread,
206			    start_routine, arg);
207			/*
208			 * Check if this thread is to inherit the scheduling
209			 * attributes from its parent:
210			 */
211			if ((new_thread->attr.flags & PTHREAD_INHERIT_SCHED) != 0) {
212				/*
213				 * Copy the scheduling attributes.
214				 * Lock the scheduling lock to get consistent
215				 * scheduling parameters.
216				 */
217				THR_SCHED_LOCK(curthread, curthread);
218				new_thread->base_priority =
219				    curthread->base_priority &
220				    ~THR_SIGNAL_PRIORITY;
221				new_thread->attr.prio =
222				    curthread->base_priority &
223				    ~THR_SIGNAL_PRIORITY;
224				new_thread->attr.sched_policy =
225				    curthread->attr.sched_policy;
226				THR_SCHED_UNLOCK(curthread, curthread);
227			} else {
228				/*
229				 * Use just the thread priority, leaving the
230				 * other scheduling attributes as their
231				 * default values:
232				 */
233				new_thread->base_priority =
234				    new_thread->attr.prio;
235			}
236			new_thread->active_priority = new_thread->base_priority;
237			new_thread->inherited_priority = 0;
238
239			/* Initialize the mutex queue: */
240			TAILQ_INIT(&new_thread->mutexq);
241
242			/*
243			 * Initialize thread locking.
244			 * Lock initializing needs malloc, so don't
245			 * enter critical region before doing this!
246			 */
247			if (_lock_init(&new_thread->lock, LCK_ADAPTIVE,
248			    _thr_lock_wait, _thr_lock_wakeup) != 0)
249				PANIC("Cannot initialize thread lock");
250			for (i = 0; i < MAX_THR_LOCKLEVEL; i++) {
251				_lockuser_init(&new_thread->lockusers[i],
252				    (void *)new_thread);
253				_LCK_SET_PRIVATE2(&new_thread->lockusers[i],
254				    (void *)new_thread);
255			}
256
257			/* Initialise hooks in the thread structure: */
258			new_thread->specific = NULL;
259			new_thread->cleanup = NULL;
260			new_thread->flags = 0;
261			new_thread->continuation = NULL;
262
263			if (new_thread->attr.suspend == THR_CREATE_SUSPENDED) {
264				new_thread->state = PS_SUSPENDED;
265				new_thread->flags = THR_FLAGS_SUSPENDED;
266			}
267			else
268				new_thread->state = PS_RUNNING;
269
270			/*
271			 * System scope threads have their own kse and
272			 * kseg.  Process scope threads are all hung
273			 * off the main process kseg.
274			 */
275			if ((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) == 0) {
276				new_thread->kseg = _kse_initial->k_kseg;
277				new_thread->kse = _kse_initial;
278			}
279			else {
280				kse->k_curthread = NULL;
281#ifdef NOT_YET
282				kse->k_kseg->kg_flags |= KGF_SINGLE_THREAD;
283#endif
284				new_thread->kse = kse;
285				new_thread->kseg = kse->k_kseg;
286				kse->k_mbx.km_udata = kse;
287				kse->k_mbx.km_curthread = NULL;
288			}
289
290			/*
291			 * Schedule the new thread starting a new KSEG/KSE
292			 * pair if necessary.
293			 */
294			ret = _thr_schedule_add(curthread, new_thread);
295			if (ret != 0)
296				free_thread(curthread, new_thread);
297			else {
298				/* Return a pointer to the thread structure: */
299				(*thread) = new_thread;
300			}
301		}
302	}
303
304	/* Return the status: */
305	return (ret);
306}
307
308static void
309free_thread(struct pthread *curthread, struct pthread *thread)
310{
311	if ((thread->attr.flags & PTHREAD_SCOPE_SYSTEM) != 0) {
312		/* Free the KSE and KSEG. */
313		_kseg_free(thread->kseg);
314		_kse_free(curthread, thread->kse);
315	}
316	_thr_free(curthread, thread);
317}
318
319static int
320create_stack(struct pthread_attr *pattr)
321{
322	int ret;
323
324	/* Check if a stack was specified in the thread attributes: */
325	if ((pattr->stackaddr_attr) != NULL) {
326		pattr->guardsize_attr = 0;
327		pattr->flags |= THR_STACK_USER;
328		ret = 0;
329	}
330	else
331		ret = _thr_stack_alloc(pattr);
332	return (ret);
333}
334
335
336static void
337thread_start(struct pthread *curthread, void *(*start_routine) (void *),
338    void *arg)
339{
340	/* Run the current thread's start routine with argument: */
341	pthread_exit(start_routine(arg));
342
343	/* This point should never be reached. */
344	PANIC("Thread has resumed after exit");
345}
346