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