Merge from vendor branch OPENSSH:
[dragonfly.git] / lib / libthread_xu / thread / thr_create.c
1 /*
2  * Copyright (c) 2005 David Xu <davidxu@freebsd.org>
3  * Copyright (c) 2003 Daniel M. Eischen <deischen@gdeb.com>
4  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by John Birrell.
18  * 4. Neither the name of the author nor the names of any co-contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $FreeBSD: src/lib/libpthread/thread/thr_create.c,v 1.58 2004/10/23 23:28:36 davidxu Exp $
35  * $DragonFly: src/lib/libthread_xu/thread/thr_create.c,v 1.10 2006/04/06 13:03:09 davidxu Exp $
36  */
37
38 #include "namespace.h"
39 #include <errno.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <fcntl.h>
43 #include <unistd.h>
44 #include <stddef.h>
45 #include <sys/time.h>
46 #include <machine/reg.h>
47 #include <machine/tls.h>
48
49 #include <pthread.h>
50 #include <sys/signalvar.h>
51 #include "un-namespace.h"
52
53 #include "thr_private.h"
54 #include "libc_private.h"
55
56 struct start_arg {
57         struct pthread  *thread;
58         volatile umtx_t started;
59 };
60
61 static int  create_stack(struct pthread_attr *pattr);
62 static void thread_start(void *);
63
64 int
65 _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
66        void *(*start_routine) (void *), void *arg)
67 {
68         struct start_arg start_arg;
69         void *stack;
70         sigset_t sigmask, oldsigmask;
71         struct pthread *curthread, *new_thread;
72         int ret = 0, locked;
73
74         _thr_check_init();
75
76         /*
77          * Tell libc and others now they need lock to protect their data.
78          */
79         if (_thr_isthreaded() == 0 && _thr_setthreaded(1))
80                 return (EAGAIN);
81
82         curthread = tls_get_curthread();
83         if ((new_thread = _thr_alloc(curthread)) == NULL)
84                 return (EAGAIN);
85
86         if (attr == NULL || *attr == NULL)
87                 /* Use the default thread attributes: */
88                 new_thread->attr = _pthread_attr_default;
89         else
90                 new_thread->attr = *(*attr);
91         if (new_thread->attr.sched_inherit == PTHREAD_INHERIT_SCHED) {
92                 /* inherit scheduling contention scope */
93                 if (curthread->attr.flags & PTHREAD_SCOPE_SYSTEM)
94                         new_thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
95                 else
96                         new_thread->attr.flags &= ~PTHREAD_SCOPE_SYSTEM;
97                 /*
98                  * scheduling policy and scheduling parameters will be
99                  * inherited in following code.
100                  */
101         }
102
103         if (_thread_scope_system > 0)
104                 new_thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
105         else if (_thread_scope_system < 0)
106                 new_thread->attr.flags &= ~PTHREAD_SCOPE_SYSTEM;
107
108         if (create_stack(&new_thread->attr) != 0) {
109                 /* Insufficient memory to create a stack: */
110                 new_thread->terminated = 1;
111                 _thr_free(curthread, new_thread);
112                 return (EAGAIN);
113         }
114         /*
115          * Write a magic value to the thread structure
116          * to help identify valid ones:
117          */
118         new_thread->magic = THR_MAGIC;
119         new_thread->start_routine = start_routine;
120         new_thread->arg = arg;
121         new_thread->cancelflags = PTHREAD_CANCEL_ENABLE |
122             PTHREAD_CANCEL_DEFERRED;
123         /*
124          * Check if this thread is to inherit the scheduling
125          * attributes from its parent:
126          */
127         if (new_thread->attr.sched_inherit == PTHREAD_INHERIT_SCHED) {
128                 /*
129                  * Copy the scheduling attributes. Lock the scheduling
130                  * lock to get consistent scheduling parameters.
131                  */
132                 THR_LOCK(curthread);
133                 new_thread->base_priority = curthread->base_priority;
134                 new_thread->attr.prio = curthread->base_priority;
135                 new_thread->attr.sched_policy = curthread->attr.sched_policy;
136                 THR_UNLOCK(curthread);
137         } else {
138                 /*
139                  * Use just the thread priority, leaving the
140                  * other scheduling attributes as their
141                  * default values:
142                  */
143                 new_thread->base_priority = new_thread->attr.prio;
144         }
145         new_thread->active_priority = new_thread->base_priority;
146
147         /* Initialize the mutex queue: */
148         TAILQ_INIT(&new_thread->mutexq);
149
150         /* Initialise hooks in the thread structure: */
151         if (new_thread->attr.suspend == THR_CREATE_SUSPENDED)
152                 new_thread->flags = THR_FLAGS_NEED_SUSPEND;
153
154         new_thread->state = PS_RUNNING;
155
156         if (new_thread->attr.flags & PTHREAD_CREATE_DETACHED)
157                 new_thread->tlflags |= TLFLAGS_DETACHED;
158
159         /*
160          * Thread created by thr_create() inherits currrent thread
161          * sigmask, however, before new thread setup itself correctly,
162          * it can not handle signal, so we should masks all signals here.
163          */
164         SIGFILLSET(sigmask);
165         __sys_sigprocmask(SIG_SETMASK, &sigmask, &oldsigmask);
166         new_thread->sigmask = oldsigmask;
167         /* Add the new thread. */
168         new_thread->refcount = 1;
169         _thr_link(curthread, new_thread);
170         /* Return thread pointer eariler so that new thread can use it. */
171         (*thread) = new_thread;
172         if (SHOULD_REPORT_EVENT(curthread, TD_CREATE)) {
173                 THR_THREAD_LOCK(curthread, new_thread);
174                 locked = 1;
175         } else
176                 locked = 0;
177         /* Schedule the new thread. */
178         stack = (char *)new_thread->attr.stackaddr_attr +
179                         new_thread->attr.stacksize_attr;
180         start_arg.thread  = new_thread;
181         start_arg.started = 0;
182         ret = rfork_thread(RFPROC | RFNOWAIT | RFMEM | RFSIGSHARE, stack,
183                            (int (*)(void *))thread_start, &start_arg);
184         __sys_sigprocmask(SIG_SETMASK, &oldsigmask, NULL);
185         if (ret >= 0) {
186                 /*
187                  * Wait until new thread get its thread id, so we can
188                  * send signal to it immediately after we return.
189                  */
190                 while (start_arg.started == 0)
191                         _thr_umtx_wait(&start_arg.started, 0, NULL, 0);
192                 ret = 0;
193         } else {
194                 ret = EAGAIN;
195         }
196         if (ret != 0) {
197                 if (!locked)
198                         THR_THREAD_LOCK(curthread, new_thread);
199                 new_thread->state = PS_DEAD;
200                 new_thread->terminated = 1;
201                 if (new_thread->flags & THR_FLAGS_NEED_SUSPEND) {
202                         new_thread->cycle++;
203                         _thr_umtx_wake(&new_thread->cycle, INT_MAX);
204                 }
205                 THR_THREAD_UNLOCK(curthread, new_thread);
206                 THREAD_LIST_LOCK(curthread);
207                 _thread_active_threads--;
208                 new_thread->tlflags |= TLFLAGS_DETACHED;
209                 _thr_ref_delete_unlocked(curthread, new_thread);
210                 THREAD_LIST_UNLOCK(curthread);
211                 (*thread) = 0;
212                 ret = EAGAIN;
213         } else if (locked) {
214                 _thr_report_creation(curthread, new_thread);
215                 THR_THREAD_UNLOCK(curthread, new_thread);
216         }
217         return (ret);
218 }
219
220 static int
221 create_stack(struct pthread_attr *pattr)
222 {
223         int ret;
224
225         /* Check if a stack was specified in the thread attributes: */
226         if ((pattr->stackaddr_attr) != NULL) {
227                 pattr->guardsize_attr = 0;
228                 pattr->flags |= THR_STACK_USER;
229                 ret = 0;
230         }
231         else
232                 ret = _thr_stack_alloc(pattr);
233         return (ret);
234 }
235
236 static void
237 thread_start(void *arg)
238 {
239         struct pthread *curthread;
240         struct start_arg *start_arg = arg;
241
242         curthread = start_arg->thread;
243         curthread->tid = _thr_get_tid();
244         tls_set_tcb(curthread->tcb);
245         start_arg->started = 1;
246         _thr_umtx_wake(&start_arg->started, 1);
247
248         /* Thread was created with all signals blocked, unblock them. */
249         __sys_sigprocmask(SIG_SETMASK, &curthread->sigmask, NULL);
250
251         THR_LOCK(curthread);
252         THR_UNLOCK(curthread);
253
254         if (curthread->flags & THR_FLAGS_NEED_SUSPEND)
255                 _thr_suspend_check(curthread);
256
257         /* Run the current thread's start routine with argument: */
258         _pthread_exit(curthread->start_routine(curthread->arg));
259
260         /* This point should never be reached. */
261         PANIC("Thread has resumed after exit");
262 }
263
264 __strong_reference(_pthread_create, pthread_create);