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