thr_create.c revision 115278
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 115278 2003-05-24 02:29:25Z 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
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#ifndef	KMF_DONE
147#define	KMF_DONE	0x04
148#endif
149			if (kse != NULL) {
150				kse->k_mbx.km_flags |= KMF_DONE;
151				_kse_free(curthread, kse);
152			}
153			if ((new_thread->attr.flags & THR_STACK_USER) == 0) {
154				crit = _kse_critical_enter();
155				curkse = _get_curkse();
156				KSE_LOCK_ACQUIRE(curkse, &_thread_list_lock);
157				/* Stack routines don't use malloc/free. */
158				_thr_stack_free(&new_thread->attr);
159				KSE_LOCK_RELEASE(curkse, &_thread_list_lock);
160				_kse_critical_leave(crit);
161			}
162			_thr_free(curthread, new_thread);
163		}
164		else {
165			if (kseg != NULL) {
166				/* Add the KSE to the KSEG's list of KSEs. */
167				TAILQ_INSERT_HEAD(&kseg->kg_kseq, kse, k_kgqe);
168				kseg->kg_ksecount = 1;
169				kse->k_kseg = kseg;
170				kse->k_schedq = &kseg->kg_schedq;
171			}
172			/*
173			 * Write a magic value to the thread structure
174			 * to help identify valid ones:
175			 */
176			new_thread->magic = THR_MAGIC;
177
178			new_thread->slice_usec = -1;
179			new_thread->start_routine = start_routine;
180			new_thread->arg = arg;
181			new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
182			    PTHREAD_CANCEL_DEFERRED;
183
184			/* Initialize the thread for signals: */
185			new_thread->sigmask = curthread->sigmask;
186
187			/* No thread is wanting to join to this one: */
188			new_thread->joiner = NULL;
189
190			/* Initialize the signal frame: */
191			new_thread->curframe = NULL;
192
193			/*
194			 * Initialize the machine context.
195			 * Enter a critical region to get consistent context.
196			 */
197			crit = _kse_critical_enter();
198			THR_GETCONTEXT(&new_thread->tmbx.tm_context);
199			_kse_critical_leave(crit);
200			new_thread->tmbx.tm_udata = new_thread;
201			new_thread->tmbx.tm_context.uc_sigmask =
202			    new_thread->sigmask;
203			new_thread->tmbx.tm_context.uc_stack.ss_size =
204			    new_thread->attr.stacksize_attr;
205			new_thread->tmbx.tm_context.uc_stack.ss_sp =
206			    new_thread->attr.stackaddr_attr;
207			makecontext(&new_thread->tmbx.tm_context,
208			    (void (*)(void))thread_start, 4, new_thread,
209			    start_routine, arg);
210			/*
211			 * Check if this thread is to inherit the scheduling
212			 * attributes from its parent:
213			 */
214			if ((new_thread->attr.flags & PTHREAD_INHERIT_SCHED) != 0) {
215				/*
216				 * Copy the scheduling attributes.
217				 * Lock the scheduling lock to get consistent
218				 * scheduling parameters.
219				 */
220				THR_SCHED_LOCK(curthread, curthread);
221				new_thread->base_priority =
222				    curthread->base_priority &
223				    ~THR_SIGNAL_PRIORITY;
224				new_thread->attr.prio =
225				    curthread->base_priority &
226				    ~THR_SIGNAL_PRIORITY;
227				new_thread->attr.sched_policy =
228				    curthread->attr.sched_policy;
229				THR_SCHED_UNLOCK(curthread, curthread);
230			} else {
231				/*
232				 * Use just the thread priority, leaving the
233				 * other scheduling attributes as their
234				 * default values:
235				 */
236				new_thread->base_priority =
237				    new_thread->attr.prio;
238			}
239			new_thread->active_priority = new_thread->base_priority;
240			new_thread->inherited_priority = 0;
241
242			/* Initialize the mutex queue: */
243			TAILQ_INIT(&new_thread->mutexq);
244
245			/*
246			 * Initialize thread locking.
247			 * Lock initializing needs malloc, so don't
248			 * enter critical region before doing this!
249			 */
250			if (_lock_init(&new_thread->lock, LCK_ADAPTIVE,
251			    _thr_lock_wait, _thr_lock_wakeup) != 0)
252				PANIC("Cannot initialize thread lock");
253			for (i = 0; i < MAX_THR_LOCKLEVEL; i++) {
254				_lockuser_init(&new_thread->lockusers[i],
255				    (void *)new_thread);
256				_LCK_SET_PRIVATE2(&new_thread->lockusers[i],
257				    (void *)new_thread);
258			}
259
260			/* Initialise hooks in the thread structure: */
261			new_thread->specific = NULL;
262			new_thread->cleanup = NULL;
263			new_thread->flags = 0;
264			new_thread->continuation = NULL;
265
266			if (new_thread->attr.suspend == THR_CREATE_SUSPENDED) {
267				new_thread->state = PS_SUSPENDED;
268				new_thread->flags = THR_FLAGS_SUSPENDED;
269			}
270			else
271				new_thread->state = PS_RUNNING;
272
273			/*
274			 * System scope threads have their own kse and
275			 * kseg.  Process scope threads are all hung
276			 * off the main process kseg.
277			 */
278			if ((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) == 0) {
279				new_thread->kseg = _kse_initial->k_kseg;
280				new_thread->kse = _kse_initial;
281			}
282			else {
283				kse->k_curthread = NULL;
284#ifdef NOT_YET
285				kse->k_kseg->kg_flags |= KGF_SINGLE_THREAD;
286#endif
287				new_thread->kse = kse;
288				new_thread->kseg = kse->k_kseg;
289				kse->k_mbx.km_udata = kse;
290				kse->k_mbx.km_curthread = NULL;
291			}
292
293			/*
294			 * Schedule the new thread starting a new KSEG/KSE
295			 * pair if necessary.
296			 */
297			ret = _thr_schedule_add(curthread, new_thread);
298			if (ret != 0)
299				free_thread(curthread, new_thread);
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 void
311free_thread(struct pthread *curthread, struct pthread *thread)
312{
313	if ((thread->attr.flags & PTHREAD_SCOPE_SYSTEM) != 0) {
314		/* Free the KSE and KSEG. */
315		_kseg_free(thread->kseg);
316		_kse_free(curthread, thread->kse);
317	}
318	_thr_free(curthread, thread);
319}
320
321static int
322create_stack(struct pthread_attr *pattr)
323{
324	int ret;
325
326	/* Check if a stack was specified in the thread attributes: */
327	if ((pattr->stackaddr_attr) != NULL) {
328		pattr->guardsize_attr = 0;
329		pattr->flags |= THR_STACK_USER;
330		ret = 0;
331	}
332	else
333		ret = _thr_stack_alloc(pattr);
334	return (ret);
335}
336
337
338static void
339thread_start(struct pthread *curthread, void *(*start_routine) (void *),
340    void *arg)
341{
342	/* Run the current thread's start routine with argument: */
343	pthread_exit(start_routine(arg));
344
345	/* This point should never be reached. */
346	PANIC("Thread has resumed after exit");
347}
348