thr_create.c revision 133563
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 133563 2004-08-12 12:12:12Z 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 void free_thread(struct pthread *curthread, struct pthread *thread);
48static int  create_stack(struct pthread_attr *pattr);
49static void free_stack(struct pthread_attr *pattr);
50static void thread_start(struct pthread *curthread,
51		void *(*start_routine) (void *), void *arg);
52
53__weak_reference(_pthread_create, pthread_create);
54
55/*
56 * Some notes on new thread creation and first time initializion
57 * to enable multi-threading.
58 *
59 * There are basically two things that need to be done.
60 *
61 *   1) The internal library variables must be initialized.
62 *   2) Upcalls need to be enabled to allow multiple threads
63 *      to be run.
64 *
65 * The first may be done as a result of other pthread functions
66 * being called.  When _thr_initial is null, _libpthread_init is
67 * called to initialize the internal variables; this also creates
68 * or sets the initial thread.  It'd be nice to automatically
69 * have _libpthread_init called on program execution so we don't
70 * have to have checks throughout the library.
71 *
72 * The second part is only triggered by the creation of the first
73 * thread (other than the initial/main thread).  If the thread
74 * being created is a scope system thread, then a new KSE/KSEG
75 * pair needs to be allocated.  Also, if upcalls haven't been
76 * enabled on the initial thread's KSE, they must be now that
77 * there is more than one thread; this could be delayed until
78 * the initial KSEG has more than one thread.
79 */
80int
81_pthread_create(pthread_t * thread, const pthread_attr_t * attr,
82	       void *(*start_routine) (void *), void *arg)
83{
84	struct pthread *curthread, *new_thread;
85	struct kse *kse = NULL;
86	struct kse_group *kseg = NULL;
87	kse_critical_t crit;
88	int ret = 0;
89
90	if (_thr_initial == NULL)
91		_libpthread_init(NULL);
92
93	/*
94	 * Turn on threaded mode, if failed, it is unnecessary to
95	 * do further work.
96	 */
97	if (_kse_isthreaded() == 0 && _kse_setthreaded(1)) {
98		return (EAGAIN);
99	}
100	curthread = _get_curthread();
101
102	/*
103	 * Allocate memory for the thread structure.
104	 * Some functions use malloc, so don't put it
105	 * in a critical region.
106	 */
107	if ((new_thread = _thr_alloc(curthread)) == NULL) {
108		/* Insufficient memory to create a thread: */
109		ret = EAGAIN;
110	} else {
111		/* Check if default thread attributes are required: */
112		if (attr == NULL || *attr == NULL)
113			/* Use the default thread attributes: */
114			new_thread->attr = _pthread_attr_default;
115		else {
116			new_thread->attr = *(*attr);
117			if ((*attr)->sched_inherit == PTHREAD_INHERIT_SCHED) {
118				/* inherit scheduling contention scop */
119				if (curthread->attr.flags & PTHREAD_SCOPE_SYSTEM)
120					new_thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
121				else
122					new_thread->attr.flags &= ~PTHREAD_SCOPE_SYSTEM;
123				/*
124				 * scheduling policy and scheduling parameters will be
125				 * inherited in following code.
126				 */
127			}
128		}
129		if (_thread_scope_system > 0)
130			new_thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
131		else if ((_thread_scope_system < 0)
132		    && (thread != &_thr_sig_daemon))
133			new_thread->attr.flags &= ~PTHREAD_SCOPE_SYSTEM;
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, 1)) == 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->k_kcb->kcb_kmbx.km_flags |= KMF_DONE;
146				_kse_free(curthread, kse);
147			}
148			free_stack(&new_thread->attr);
149			_thr_free(curthread, new_thread);
150		}
151		else {
152			if (kseg != NULL) {
153				/* Add the KSE to the KSEG's list of KSEs. */
154				TAILQ_INSERT_HEAD(&kseg->kg_kseq, kse, k_kgqe);
155				kseg->kg_ksecount = 1;
156				kse->k_kseg = kseg;
157				kse->k_schedq = &kseg->kg_schedq;
158			}
159			/*
160			 * Write a magic value to the thread structure
161			 * to help identify valid ones:
162			 */
163			new_thread->magic = THR_MAGIC;
164
165			new_thread->slice_usec = -1;
166			new_thread->start_routine = start_routine;
167			new_thread->arg = arg;
168			new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
169			    PTHREAD_CANCEL_DEFERRED;
170
171			/* No thread is wanting to join to this one: */
172			new_thread->joiner = NULL;
173
174			/* Initialize the signal frame: */
175			new_thread->curframe = 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->continuation = NULL;
238			new_thread->wakeup_time.tv_sec = -1;
239			new_thread->lock_switch = 0;
240			sigemptyset(&new_thread->sigpend);
241			new_thread->check_pending = 0;
242			new_thread->locklevel = 0;
243			new_thread->rdlock_count = 0;
244			new_thread->sigstk.ss_sp = 0;
245			new_thread->sigstk.ss_size = 0;
246			new_thread->sigstk.ss_flags = SS_DISABLE;
247			new_thread->oldsigmask = NULL;
248
249			if (new_thread->attr.suspend == THR_CREATE_SUSPENDED) {
250				new_thread->state = PS_SUSPENDED;
251				new_thread->flags = THR_FLAGS_SUSPENDED;
252			}
253			else
254				new_thread->state = PS_RUNNING;
255
256			/*
257			 * System scope threads have their own kse and
258			 * kseg.  Process scope threads are all hung
259			 * off the main process kseg.
260			 */
261			if ((new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM) == 0) {
262				new_thread->kseg = _kse_initial->k_kseg;
263				new_thread->kse = _kse_initial;
264			}
265			else {
266				kse->k_curthread = NULL;
267				kse->k_kseg->kg_flags |= KGF_SINGLE_THREAD;
268				new_thread->kse = kse;
269				new_thread->kseg = kse->k_kseg;
270				kse->k_kcb->kcb_kmbx.km_udata = kse;
271				kse->k_kcb->kcb_kmbx.km_curthread = NULL;
272			}
273
274			/*
275			 * Schedule the new thread starting a new KSEG/KSE
276			 * pair if necessary.
277			 */
278			ret = _thr_schedule_add(curthread, new_thread);
279			if (ret != 0)
280				free_thread(curthread, new_thread);
281			else {
282				/* Return a pointer to the thread structure: */
283				(*thread) = new_thread;
284			}
285		}
286	}
287
288	/* Return the status: */
289	return (ret);
290}
291
292static void
293free_thread(struct pthread *curthread, struct pthread *thread)
294{
295	free_stack(&thread->attr);
296	if ((thread->attr.flags & PTHREAD_SCOPE_SYSTEM) != 0) {
297		/* Free the KSE and KSEG. */
298		_kseg_free(thread->kseg);
299		_kse_free(curthread, thread->kse);
300	}
301	_thr_free(curthread, thread);
302}
303
304static int
305create_stack(struct pthread_attr *pattr)
306{
307	int ret;
308
309	/* Check if a stack was specified in the thread attributes: */
310	if ((pattr->stackaddr_attr) != NULL) {
311		pattr->guardsize_attr = 0;
312		pattr->flags |= THR_STACK_USER;
313		ret = 0;
314	}
315	else
316		ret = _thr_stack_alloc(pattr);
317	return (ret);
318}
319
320static void
321free_stack(struct pthread_attr *pattr)
322{
323	struct kse *curkse;
324	kse_critical_t crit;
325
326	if ((pattr->flags & THR_STACK_USER) == 0) {
327		crit = _kse_critical_enter();
328		curkse = _get_curkse();
329		KSE_LOCK_ACQUIRE(curkse, &_thread_list_lock);
330		/* Stack routines don't use malloc/free. */
331		_thr_stack_free(pattr);
332		KSE_LOCK_RELEASE(curkse, &_thread_list_lock);
333		_kse_critical_leave(crit);
334	}
335}
336
337static void
338thread_start(struct pthread *curthread, void *(*start_routine) (void *),
339    void *arg)
340{
341	/* Run the current thread's start routine with argument: */
342	pthread_exit(start_routine(arg));
343
344	/* This point should never be reached. */
345	PANIC("Thread has resumed after exit");
346}
347