xref: /netbsd-src/lib/libpthread/pthread.c (revision 9c1da17e908379b8a470f1117a6395bd6a0ca559)
1 /*	$NetBSD: pthread.c,v 1.42 2005/07/01 12:35:18 yamt Exp $	*/
2 
3 /*-
4  * Copyright (c) 2001,2002,2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Nathan J. Williams.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 __RCSID("$NetBSD: pthread.c,v 1.42 2005/07/01 12:35:18 yamt Exp $");
41 
42 #include <err.h>
43 #include <errno.h>
44 #include <lwp.h>
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <syslog.h>
50 #include <ucontext.h>
51 #include <unistd.h>
52 #include <sys/param.h>
53 #include <sys/sysctl.h>
54 #ifdef PTHREAD_MLOCK_KLUDGE
55 #include <sys/mman.h>
56 #endif
57 
58 #include <sched.h>
59 #include "pthread.h"
60 #include "pthread_int.h"
61 
62 #ifdef PTHREAD_MAIN_DEBUG
63 #define SDPRINTF(x) DPRINTF(x)
64 #else
65 #define SDPRINTF(x)
66 #endif
67 
68 static void	pthread__create_tramp(void *(*start)(void *), void *arg);
69 static void	pthread__dead(pthread_t, pthread_t);
70 
71 int pthread__started;
72 
73 pthread_spin_t pthread__allqueue_lock = __SIMPLELOCK_UNLOCKED;
74 struct pthread_queue_t pthread__allqueue;
75 
76 pthread_spin_t pthread__deadqueue_lock = __SIMPLELOCK_UNLOCKED;
77 struct pthread_queue_t pthread__deadqueue;
78 struct pthread_queue_t *pthread__reidlequeue;
79 
80 static int nthreads;
81 static int nextthread;
82 static pthread_spin_t nextthread_lock = __SIMPLELOCK_UNLOCKED;
83 static pthread_attr_t pthread_default_attr;
84 
85 enum {
86 	DIAGASSERT_ABORT =	1<<0,
87 	DIAGASSERT_STDERR =	1<<1,
88 	DIAGASSERT_SYSLOG =	1<<2
89 };
90 
91 static int pthread__diagassert = DIAGASSERT_ABORT | DIAGASSERT_STDERR;
92 
93 pthread_spin_t pthread__runqueue_lock = __SIMPLELOCK_UNLOCKED;
94 struct pthread_queue_t pthread__runqueue;
95 struct pthread_queue_t pthread__idlequeue;
96 struct pthread_queue_t pthread__suspqueue;
97 
98 int pthread__concurrency, pthread__maxconcurrency;
99 
100 __strong_alias(__libc_thr_self,pthread_self)
101 __strong_alias(__libc_thr_create,pthread_create)
102 __strong_alias(__libc_thr_exit,pthread_exit)
103 __strong_alias(__libc_thr_errno,pthread__errno)
104 __strong_alias(__libc_thr_setcancelstate,pthread_setcancelstate)
105 
106 /*
107  * Static library kludge.  Place a reference to a symbol any library
108  * file which does not already have a reference here.
109  */
110 extern int pthread__cancel_stub_binder;
111 extern int pthread__sched_binder;
112 extern struct pthread_queue_t pthread__nanosleeping;
113 
114 void *pthread__static_lib_binder[] = {
115 	&pthread__cancel_stub_binder,
116 	pthread_cond_init,
117 	pthread_mutex_init,
118 	pthread_rwlock_init,
119 	pthread_barrier_init,
120 	pthread_key_create,
121 	pthread_setspecific,
122 	&pthread__sched_binder,
123 	&pthread__nanosleeping
124 };
125 
126 /*
127  * This needs to be started by the library loading code, before main()
128  * gets to run, for various things that use the state of the initial thread
129  * to work properly (thread-specific data is an application-visible example;
130  * spinlock counts for mutexes is an internal example).
131  */
132 void
133 pthread_init(void)
134 {
135 	pthread_t first;
136 	char *p;
137 	int i, mib[2], ncpu;
138 	size_t len;
139 	extern int __isthreaded;
140 #ifdef PTHREAD_MLOCK_KLUDGE
141 	int ret;
142 #endif
143 
144 	mib[0] = CTL_HW;
145 	mib[1] = HW_NCPU;
146 
147 	len = sizeof(ncpu);
148 	sysctl(mib, 2, &ncpu, &len, NULL, 0);
149 
150 	/* Initialize locks first; they're needed elsewhere. */
151 	pthread__lockprim_init(ncpu);
152 
153 	/* Find out requested/possible concurrency */
154 	p = getenv("PTHREAD_CONCURRENCY");
155 	pthread__maxconcurrency = p ? atoi(p) : 1;
156 
157 	if (pthread__maxconcurrency < 1)
158 		pthread__maxconcurrency = 1;
159 	if (pthread__maxconcurrency > ncpu)
160 		pthread__maxconcurrency = ncpu;
161 
162 	/* Allocate data structures */
163 	pthread__reidlequeue = (struct pthread_queue_t *)malloc
164 		(pthread__maxconcurrency * sizeof(struct pthread_queue_t));
165 	if (pthread__reidlequeue == NULL)
166 		err(1, "Couldn't allocate memory for pthread__reidlequeue");
167 
168 	/* Basic data structure setup */
169 	pthread_attr_init(&pthread_default_attr);
170 	PTQ_INIT(&pthread__allqueue);
171 	PTQ_INIT(&pthread__deadqueue);
172 #ifdef PTHREAD_MLOCK_KLUDGE
173 	ret = mlock(&pthread__deadqueue, sizeof(pthread__deadqueue));
174 	pthread__assert(ret == 0);
175 #endif
176 	PTQ_INIT(&pthread__runqueue);
177 	PTQ_INIT(&pthread__idlequeue);
178 	for (i = 0; i < pthread__maxconcurrency; i++)
179 		PTQ_INIT(&pthread__reidlequeue[i]);
180 	nthreads = 1;
181 
182 	/* Create the thread structure corresponding to main() */
183 	pthread__initmain(&first);
184 	pthread__initthread(first, first);
185 	first->pt_state = PT_STATE_RUNNING;
186 	sigprocmask(0, NULL, &first->pt_sigmask);
187 	PTQ_INSERT_HEAD(&pthread__allqueue, first, pt_allq);
188 
189 	/* Start subsystems */
190 	pthread__signal_init();
191 	PTHREAD_MD_INIT
192 #ifdef PTHREAD__DEBUG
193 	pthread__debug_init(ncpu);
194 #endif
195 
196 	for (p = getenv("PTHREAD_DIAGASSERT"); p && *p; p++) {
197 		switch (*p) {
198 		case 'a':
199 			pthread__diagassert |= DIAGASSERT_ABORT;
200 			break;
201 		case 'A':
202 			pthread__diagassert &= ~DIAGASSERT_ABORT;
203 			break;
204 		case 'e':
205 			pthread__diagassert |= DIAGASSERT_STDERR;
206 			break;
207 		case 'E':
208 			pthread__diagassert &= ~DIAGASSERT_STDERR;
209 			break;
210 		case 'l':
211 			pthread__diagassert |= DIAGASSERT_SYSLOG;
212 			break;
213 		case 'L':
214 			pthread__diagassert &= ~DIAGASSERT_SYSLOG;
215 			break;
216 		}
217 	}
218 
219 
220 	/* Tell libc that we're here and it should role-play accordingly. */
221 	__isthreaded = 1;
222 }
223 
224 static void
225 pthread__child_callback(void)
226 {
227 	/*
228 	 * Clean up data structures that a forked child process might
229 	 * trip over. Note that if threads have been created (causing
230 	 * this handler to be registered) the standards say that the
231 	 * child will trigger undefined behavior if it makes any
232 	 * pthread_* calls (or any other calls that aren't
233 	 * async-signal-safe), so we don't really have to clean up
234 	 * much. Anything that permits some pthread_* calls to work is
235 	 * merely being polite.
236 	 */
237 	pthread__started = 0;
238 }
239 
240 static void
241 pthread__start(void)
242 {
243 	pthread_t self, idle;
244 	int i, ret;
245 
246 	self = pthread__self(); /* should be the "main()" thread */
247 
248 	/*
249 	 * Per-process timers are cleared by fork(); despite the
250 	 * various restrictions on fork() and threads, it's legal to
251 	 * fork() before creating any threads.
252 	 */
253 	pthread__alarm_init();
254 
255 	pthread__signal_start();
256 
257 	pthread_atfork(NULL, NULL, pthread__child_callback);
258 
259 	/*
260 	 * Create idle threads
261 	 * XXX need to create more idle threads if concurrency > 3
262 	 */
263 	for (i = 0; i < NIDLETHREADS; i++) {
264 		ret = pthread__stackalloc(&idle);
265 		if (ret != 0)
266 			err(1, "Couldn't allocate stack for idle thread!");
267 		pthread__initthread(self, idle);
268 		sigfillset(&idle->pt_sigmask);
269 		idle->pt_type = PT_THREAD_IDLE;
270 		PTQ_INSERT_HEAD(&pthread__allqueue, idle, pt_allq);
271 		pthread__sched_idle(self, idle);
272 	}
273 
274 	/* Start up the SA subsystem */
275 	pthread__sa_start();
276 	SDPRINTF(("(pthread__start %p) Started.\n", self));
277 }
278 
279 
280 /* General-purpose thread data structure sanitization. */
281 void
282 pthread__initthread(pthread_t self, pthread_t t)
283 {
284 	int id;
285 
286 	pthread_spinlock(self, &nextthread_lock);
287 	id = nextthread;
288 	nextthread++;
289 	pthread_spinunlock(self, &nextthread_lock);
290 	t->pt_num = id;
291 
292 	t->pt_magic = PT_MAGIC;
293 	t->pt_type = PT_THREAD_NORMAL;
294 	t->pt_state = PT_STATE_RUNNABLE;
295 	pthread_lockinit(&t->pt_statelock);
296 	pthread_lockinit(&t->pt_flaglock);
297 	t->pt_spinlocks = 0;
298 	t->pt_next = NULL;
299 	t->pt_exitval = NULL;
300 	t->pt_flags = 0;
301 	t->pt_cancel = 0;
302 	t->pt_errno = 0;
303 	t->pt_parent = NULL;
304 	t->pt_heldlock = NULL;
305 	t->pt_switchto = NULL;
306 	t->pt_trapuc = NULL;
307 	sigemptyset(&t->pt_siglist);
308 	sigemptyset(&t->pt_sigmask);
309 	pthread_lockinit(&t->pt_siglock);
310 	PTQ_INIT(&t->pt_joiners);
311 	pthread_lockinit(&t->pt_join_lock);
312 	PTQ_INIT(&t->pt_cleanup_stack);
313 	memset(&t->pt_specific, 0, sizeof(int) * PTHREAD_KEYS_MAX);
314 	t->pt_name = NULL;
315 #ifdef PTHREAD__DEBUG
316 	t->blocks = 0;
317 	t->preempts = 0;
318 	t->rescheds = 0;
319 #endif
320 }
321 
322 
323 int
324 pthread_create(pthread_t *thread, const pthread_attr_t *attr,
325 	    void *(*startfunc)(void *), void *arg)
326 {
327 	pthread_t self, newthread;
328 	pthread_attr_t nattr;
329 	struct pthread_attr_private *p;
330 	char *name;
331 	int ret;
332 
333 	PTHREADD_ADD(PTHREADD_CREATE);
334 
335 	/*
336 	 * It's okay to check this without a lock because there can
337 	 * only be one thread before it becomes true.
338 	 */
339 	if (pthread__started == 0) {
340 		pthread__start();
341 		pthread__started = 1;
342 	}
343 
344 	if (attr == NULL)
345 		nattr = pthread_default_attr;
346 	else if (attr->pta_magic == PT_ATTR_MAGIC)
347 		nattr = *attr;
348 	else
349 		return EINVAL;
350 
351 	/* Fetch misc. attributes from the attr structure. */
352 	name = NULL;
353 	if ((p = nattr.pta_private) != NULL)
354 		if (p->ptap_name[0] != '\0')
355 			if ((name = strdup(p->ptap_name)) == NULL)
356 				return ENOMEM;
357 
358 	self = pthread__self();
359 
360 	pthread_spinlock(self, &pthread__deadqueue_lock);
361 	if (!PTQ_EMPTY(&pthread__deadqueue)) {
362 		newthread = PTQ_FIRST(&pthread__deadqueue);
363 		PTQ_REMOVE(&pthread__deadqueue, newthread, pt_allq);
364 		pthread_spinunlock(self, &pthread__deadqueue_lock);
365 	} else {
366 		pthread_spinunlock(self, &pthread__deadqueue_lock);
367 		/* Set up a stack and allocate space for a pthread_st. */
368 		ret = pthread__stackalloc(&newthread);
369 		if (ret != 0) {
370 			if (name)
371 				free(name);
372 			return ret;
373 		}
374 #ifdef PTHREAD_MLOCK_KLUDGE
375 		ret = mlock(newthread, sizeof(struct __pthread_st));
376 		pthread__assert(ret == 0);
377 #endif
378 	}
379 
380 	/* 2. Set up state. */
381 	pthread__initthread(self, newthread);
382 	newthread->pt_flags = nattr.pta_flags;
383 	newthread->pt_sigmask = self->pt_sigmask;
384 
385 	/* 3. Set up misc. attributes. */
386 	newthread->pt_name = name;
387 
388 	/*
389 	 * 4. Set up context.
390 	 *
391 	 * The pt_uc pointer points to a location safely below the
392 	 * stack start; this is arranged by pthread__stackalloc().
393 	 */
394 	_INITCONTEXT_U(newthread->pt_uc);
395 #ifdef PTHREAD_MACHINE_HAS_ID_REGISTER
396 	pthread__uc_id(newthread->pt_uc) = newthread;
397 #endif
398 	newthread->pt_uc->uc_stack = newthread->pt_stack;
399 	newthread->pt_uc->uc_link = NULL;
400 	makecontext(newthread->pt_uc, pthread__create_tramp, 2,
401 	    startfunc, arg);
402 
403 	/* 5. Add to list of all threads. */
404 	pthread_spinlock(self, &pthread__allqueue_lock);
405 	PTQ_INSERT_HEAD(&pthread__allqueue, newthread, pt_allq);
406 	nthreads++;
407 	pthread_spinunlock(self, &pthread__allqueue_lock);
408 
409 	SDPRINTF(("(pthread_create %p) Created new thread %p (name pointer %p).\n", self, newthread, newthread->pt_name));
410 	/* 6. Put on appropriate queue. */
411 	if (newthread->pt_flags & PT_FLAG_SUSPENDED) {
412 		pthread_spinlock(self, &newthread->pt_statelock);
413 		pthread__suspend(self, newthread);
414 		pthread_spinunlock(self, &newthread->pt_statelock);
415 	} else
416 		pthread__sched(self, newthread);
417 
418 	*thread = newthread;
419 
420 	return 0;
421 }
422 
423 
424 static void
425 pthread__create_tramp(void *(*start)(void *), void *arg)
426 {
427 	void *retval;
428 
429 	retval = (*start)(arg);
430 
431 	pthread_exit(retval);
432 
433 	/*NOTREACHED*/
434 	pthread__abort();
435 }
436 
437 int
438 pthread_suspend_np(pthread_t thread)
439 {
440 	pthread_t self = pthread__self();
441 	if (self == thread) {
442 		fprintf(stderr, "suspend_np: can't suspend self\n");
443 		return EDEADLK;
444 	}
445 	SDPRINTF(("(pthread_suspend_np %p) Suspend thread %p (state %d).\n",
446 		     self, thread, thread->pt_state));
447 	pthread_spinlock(self, &thread->pt_statelock);
448 	if (thread->pt_blockgen != thread->pt_unblockgen) {
449 		/* XXX flaglock? */
450 		thread->pt_flags |= PT_FLAG_SUSPENDED;
451 		pthread_spinunlock(self, &thread->pt_statelock);
452 		return 0;
453 	}
454 	switch (thread->pt_state) {
455 	case PT_STATE_RUNNING:
456 		pthread__abort();	/* XXX */
457 		break;
458 	case PT_STATE_SUSPENDED:
459 		pthread_spinunlock(self, &thread->pt_statelock);
460 		return 0;
461 	case PT_STATE_RUNNABLE:
462 		pthread_spinlock(self, &pthread__runqueue_lock);
463 		PTQ_REMOVE(&pthread__runqueue, thread, pt_runq);
464 		pthread_spinunlock(self, &pthread__runqueue_lock);
465 		break;
466 	case PT_STATE_BLOCKED_QUEUE:
467 		pthread_spinlock(self, thread->pt_sleeplock);
468 		PTQ_REMOVE(thread->pt_sleepq, thread, pt_sleep);
469 		pthread_spinunlock(self, thread->pt_sleeplock);
470 		break;
471 	default:
472 		break;			/* XXX */
473 	}
474 	pthread__suspend(self, thread);
475 	pthread_spinunlock(self, &thread->pt_statelock);
476 	return 0;
477 }
478 
479 int
480 pthread_resume_np(pthread_t thread)
481 {
482 
483 	pthread_t self = pthread__self();
484 	SDPRINTF(("(pthread_resume_np %p) Resume thread %p (state %d).\n",
485 		     self, thread, thread->pt_state));
486 	pthread_spinlock(self, &thread->pt_statelock);
487 	/* XXX flaglock? */
488 	thread->pt_flags &= ~PT_FLAG_SUSPENDED;
489 	if (thread->pt_state == PT_STATE_SUSPENDED) {
490 		pthread_spinlock(self, &pthread__runqueue_lock);
491 		PTQ_REMOVE(&pthread__suspqueue, thread, pt_runq);
492 		pthread_spinunlock(self, &pthread__runqueue_lock);
493 		pthread__sched(self, thread);
494 	}
495 	pthread_spinunlock(self, &thread->pt_statelock);
496 	return 0;
497 }
498 
499 
500 /*
501  * Other threads will switch to the idle thread so that they
502  * can dispose of any awkward locks or recycle upcall state.
503  */
504 void
505 pthread__idle(void)
506 {
507 	pthread_t self;
508 
509 	PTHREADD_ADD(PTHREADD_IDLE);
510 	self = pthread__self();
511 	SDPRINTF(("(pthread__idle %p).\n", self));
512 
513 	/*
514 	 * The drill here is that we want to yield the processor,
515 	 * but for the thread itself to be recovered, we need to be on
516 	 * a list somewhere for the thread system to know about us.
517 	 */
518 	pthread_spinlock(self, &pthread__deadqueue_lock);
519 	PTQ_INSERT_TAIL(&pthread__reidlequeue[self->pt_vpid], self, pt_runq);
520 	pthread__concurrency--;
521 	SDPRINTF(("(yield %p concurrency) now %d\n", self,
522 		     pthread__concurrency));
523 	/* Don't need a flag lock; nothing else has a handle on this thread */
524 	self->pt_flags |= PT_FLAG_IDLED;
525 	pthread_spinunlock(self, &pthread__deadqueue_lock);
526 
527 	/*
528 	 * If we get to run this, then no preemption has happened
529 	 * (because the upcall handler will not continue an idle thread with
530 	 * PT_FLAG_IDLED set), and so we can yield the processor safely.
531 	 */
532 	SDPRINTF(("(pthread__idle %p) yielding.\n", self));
533 	sa_yield();
534 
535 	/* NOTREACHED */
536 	self->pt_spinlocks++; /* XXX make sure we get to finish the assert! */
537 	SDPRINTF(("(pthread__idle %p) Returned! Error.\n", self));
538 	pthread__abort();
539 }
540 
541 
542 void
543 pthread_exit(void *retval)
544 {
545 	pthread_t self;
546 	struct pt_clean_t *cleanup;
547 	char *name;
548 	int nt;
549 
550 	self = pthread__self();
551 	SDPRINTF(("(pthread_exit %p) Exiting (status %p, flags %x, cancel %d).\n", self, retval, self->pt_flags, self->pt_cancel));
552 
553 	/* Disable cancellability. */
554 	pthread_spinlock(self, &self->pt_flaglock);
555 	self->pt_flags |= PT_FLAG_CS_DISABLED;
556 	self->pt_cancel = 0;
557 	pthread_spinunlock(self, &self->pt_flaglock);
558 
559 	/* Call any cancellation cleanup handlers */
560 	while (!PTQ_EMPTY(&self->pt_cleanup_stack)) {
561 		cleanup = PTQ_FIRST(&self->pt_cleanup_stack);
562 		PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next);
563 		(*cleanup->ptc_cleanup)(cleanup->ptc_arg);
564 	}
565 
566 	/* Perform cleanup of thread-specific data */
567 	pthread__destroy_tsd(self);
568 
569 	self->pt_exitval = retval;
570 
571 	/*
572 	 * it's safe to check PT_FLAG_DETACHED without pt_flaglock
573 	 * because it's only set by pthread_detach with pt_join_lock held.
574 	 */
575 	pthread_spinlock(self, &self->pt_join_lock);
576 	if (self->pt_flags & PT_FLAG_DETACHED) {
577 		self->pt_state = PT_STATE_DEAD;
578 		pthread_spinunlock(self, &self->pt_join_lock);
579 		name = self->pt_name;
580 		self->pt_name = NULL;
581 
582 		if (name != NULL)
583 			free(name);
584 
585 		pthread_spinlock(self, &pthread__allqueue_lock);
586 		PTQ_REMOVE(&pthread__allqueue, self, pt_allq);
587 		nthreads--;
588 		nt = nthreads;
589 		pthread_spinunlock(self, &pthread__allqueue_lock);
590 
591 		if (nt == 0) {
592 			/* Whoah, we're the last one. Time to go. */
593 			exit(0);
594 		}
595 
596 		/* Yeah, yeah, doing work while we're dead is tacky. */
597 		pthread_spinlock(self, &pthread__deadqueue_lock);
598 		PTQ_INSERT_HEAD(&pthread__deadqueue, self, pt_allq);
599 		pthread__block(self, &pthread__deadqueue_lock);
600 	} else {
601 		self->pt_state = PT_STATE_ZOMBIE;
602 		/* Note: name will be freed by the joiner. */
603 		pthread_spinlock(self, &pthread__allqueue_lock);
604 		nthreads--;
605 		nt = nthreads;
606 		pthread_spinunlock(self, &pthread__allqueue_lock);
607 		if (nt == 0) {
608 			/* Whoah, we're the last one. Time to go. */
609 			exit(0);
610 		}
611 		/*
612 		 * Wake up all the potential joiners. Only one can win.
613 		 * (Can you say "Thundering Herd"? I knew you could.)
614 		 */
615 		pthread__sched_sleepers(self, &self->pt_joiners);
616 		pthread__block(self, &self->pt_join_lock);
617 	}
618 
619 	/*NOTREACHED*/
620 	pthread__abort();
621 	exit(1);
622 }
623 
624 
625 int
626 pthread_join(pthread_t thread, void **valptr)
627 {
628 	pthread_t self;
629 	char *name;
630 	int num;
631 
632 	self = pthread__self();
633 	SDPRINTF(("(pthread_join %p) Joining %p.\n", self, thread));
634 
635 	if (pthread__find(self, thread) != 0)
636 		return ESRCH;
637 
638 	if (thread->pt_magic != PT_MAGIC)
639 		return EINVAL;
640 
641 	if (thread == self)
642 		return EDEADLK;
643 
644 	pthread_spinlock(self, &thread->pt_flaglock);
645 
646 	if (thread->pt_flags & PT_FLAG_DETACHED) {
647 		pthread_spinunlock(self, &thread->pt_flaglock);
648 		return EINVAL;
649 	}
650 
651 	num = thread->pt_num;
652 	pthread_spinlock(self, &thread->pt_join_lock);
653 	while (thread->pt_state != PT_STATE_ZOMBIE) {
654 		if ((thread->pt_state == PT_STATE_DEAD) ||
655 		    (thread->pt_flags & PT_FLAG_DETACHED) ||
656 		    (thread->pt_num != num)) {
657 			/*
658 			 * Another thread beat us to the join, or called
659 			 * pthread_detach(). If num didn't match, the
660 			 * thread died and was recycled before we got
661 			 * another chance to run.
662 			 */
663 			pthread_spinunlock(self, &thread->pt_join_lock);
664 			pthread_spinunlock(self, &thread->pt_flaglock);
665 			return ESRCH;
666 		}
667 		/*
668 		 * "I'm not dead yet!"
669 		 * "You will be soon enough."
670 		 */
671 		pthread_spinunlock(self, &thread->pt_flaglock);
672 		pthread_spinlock(self, &self->pt_statelock);
673 		if (self->pt_cancel) {
674 			pthread_spinunlock(self, &self->pt_statelock);
675 			pthread_spinunlock(self, &thread->pt_join_lock);
676 			pthread_exit(PTHREAD_CANCELED);
677 		}
678 		self->pt_state = PT_STATE_BLOCKED_QUEUE;
679 		self->pt_sleepobj = thread;
680 		self->pt_sleepq = &thread->pt_joiners;
681 		self->pt_sleeplock = &thread->pt_join_lock;
682 		pthread_spinunlock(self, &self->pt_statelock);
683 
684 		PTQ_INSERT_TAIL(&thread->pt_joiners, self, pt_sleep);
685 		pthread__block(self, &thread->pt_join_lock);
686 		pthread_spinlock(self, &thread->pt_flaglock);
687 		pthread_spinlock(self, &thread->pt_join_lock);
688 	}
689 
690 	/* All ours. */
691 	thread->pt_state = PT_STATE_DEAD;
692 	name = thread->pt_name;
693 	thread->pt_name = NULL;
694 	pthread_spinunlock(self, &thread->pt_join_lock);
695 	pthread_spinunlock(self, &thread->pt_flaglock);
696 
697 	if (valptr != NULL)
698 		*valptr = thread->pt_exitval;
699 
700 	SDPRINTF(("(pthread_join %p) Joined %p.\n", self, thread));
701 
702 	pthread__dead(self, thread);
703 
704 	if (name != NULL)
705 		free(name);
706 
707 	return 0;
708 }
709 
710 
711 int
712 pthread_equal(pthread_t t1, pthread_t t2)
713 {
714 
715 	/* Nothing special here. */
716 	return (t1 == t2);
717 }
718 
719 
720 int
721 pthread_detach(pthread_t thread)
722 {
723 	pthread_t self;
724 	int doreclaim = 0;
725 	char *name = NULL;
726 
727 	self = pthread__self();
728 
729 	if (pthread__find(self, thread) != 0)
730 		return ESRCH;
731 
732 	if (thread->pt_magic != PT_MAGIC)
733 		return EINVAL;
734 
735 	pthread_spinlock(self, &thread->pt_flaglock);
736 	pthread_spinlock(self, &thread->pt_join_lock);
737 
738 	if (thread->pt_flags & PT_FLAG_DETACHED) {
739 		pthread_spinunlock(self, &thread->pt_join_lock);
740 		pthread_spinunlock(self, &thread->pt_flaglock);
741 		return EINVAL;
742 	}
743 
744 	thread->pt_flags |= PT_FLAG_DETACHED;
745 
746 	/* Any joiners have to be punted now. */
747 	pthread__sched_sleepers(self, &thread->pt_joiners);
748 
749 	if (thread->pt_state == PT_STATE_ZOMBIE) {
750 		thread->pt_state = PT_STATE_DEAD;
751 		name = thread->pt_name;
752 		thread->pt_name = NULL;
753 		doreclaim = 1;
754 	}
755 
756 	pthread_spinunlock(self, &thread->pt_join_lock);
757 	pthread_spinunlock(self, &thread->pt_flaglock);
758 
759 	if (doreclaim) {
760 		pthread__dead(self, thread);
761 		if (name != NULL)
762 			free(name);
763 	}
764 
765 	return 0;
766 }
767 
768 
769 static void
770 pthread__dead(pthread_t self, pthread_t thread)
771 {
772 
773 	SDPRINTF(("(pthread__dead %p) Reclaimed %p.\n", self, thread));
774 	pthread__assert(thread != self);
775 	pthread__assert(thread->pt_state == PT_STATE_DEAD);
776 	pthread__assert(thread->pt_name == NULL);
777 
778 	/* Cleanup time. Move the dead thread from allqueue to the deadqueue */
779 	pthread_spinlock(self, &pthread__allqueue_lock);
780 	PTQ_REMOVE(&pthread__allqueue, thread, pt_allq);
781 	pthread_spinunlock(self, &pthread__allqueue_lock);
782 
783 	pthread_spinlock(self, &pthread__deadqueue_lock);
784 	PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_allq);
785 	pthread_spinunlock(self, &pthread__deadqueue_lock);
786 }
787 
788 
789 int
790 pthread_getname_np(pthread_t thread, char *name, size_t len)
791 {
792 	pthread_t self;
793 
794 	self = pthread__self();
795 
796 	if (pthread__find(self, thread) != 0)
797 		return ESRCH;
798 
799 	if (thread->pt_magic != PT_MAGIC)
800 		return EINVAL;
801 
802 	pthread_spinlock(self, &thread->pt_join_lock);
803 	if (thread->pt_name == NULL)
804 		name[0] = '\0';
805 	else
806 		strlcpy(name, thread->pt_name, len);
807 	pthread_spinunlock(self, &thread->pt_join_lock);
808 
809 	return 0;
810 }
811 
812 
813 int
814 pthread_setname_np(pthread_t thread, const char *name, void *arg)
815 {
816 	pthread_t self = pthread_self();
817 	char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP];
818 	int namelen;
819 
820 	if (pthread__find(self, thread) != 0)
821 		return ESRCH;
822 
823 	if (thread->pt_magic != PT_MAGIC)
824 		return EINVAL;
825 
826 	namelen = snprintf(newname, sizeof(newname), name, arg);
827 	if (namelen >= PTHREAD_MAX_NAMELEN_NP)
828 		return EINVAL;
829 
830 	cp = strdup(newname);
831 	if (cp == NULL)
832 		return ENOMEM;
833 
834 	pthread_spinlock(self, &thread->pt_join_lock);
835 
836 	if (thread->pt_state == PT_STATE_DEAD) {
837 		pthread_spinunlock(self, &thread->pt_join_lock);
838 		free(cp);
839 		return EINVAL;
840 	}
841 
842 	oldname = thread->pt_name;
843 	thread->pt_name = cp;
844 
845 	pthread_spinunlock(self, &thread->pt_join_lock);
846 
847 	if (oldname != NULL)
848 		free(oldname);
849 
850 	return 0;
851 }
852 
853 
854 
855 /*
856  * XXX There should be a way for applications to use the efficent
857  *  inline version, but there are opacity/namespace issues.
858  */
859 pthread_t
860 pthread_self(void)
861 {
862 
863 	return pthread__self();
864 }
865 
866 
867 int
868 pthread_cancel(pthread_t thread)
869 {
870 	pthread_t self;
871 
872 	if (!(thread->pt_state == PT_STATE_RUNNING ||
873 	    thread->pt_state == PT_STATE_RUNNABLE ||
874 	    thread->pt_state == PT_STATE_BLOCKED_QUEUE))
875 		return ESRCH;
876 
877 	self = pthread__self();
878 
879 	pthread_spinlock(self, &thread->pt_flaglock);
880 	thread->pt_flags |= PT_FLAG_CS_PENDING;
881 	if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) {
882 		thread->pt_cancel = 1;
883 		pthread_spinunlock(self, &thread->pt_flaglock);
884 		pthread_spinlock(self, &thread->pt_statelock);
885 		if (thread->pt_blockgen != thread->pt_unblockgen) {
886 			/*
887 			 * It's sleeping in the kernel. If we can wake
888 			 * it up, it will notice the cancellation when
889 			 * it returns. If it doesn't wake up when we
890 			 * make this call, then it's blocked
891 			 * uninterruptably in the kernel, and there's
892 			 * not much to be done about it.
893 			 */
894 			_lwp_wakeup(thread->pt_blockedlwp);
895 		} else if (thread->pt_state == PT_STATE_BLOCKED_QUEUE) {
896 			/*
897 			 * We're blocked somewhere (pthread__block()
898 			 * was called). Cause it to wake up; it will
899 			 * check for the cancellation if the routine
900 			 * is a cancellation point, and loop and reblock
901 			 * otherwise.
902 			 */
903 			pthread_spinlock(self, thread->pt_sleeplock);
904 			PTQ_REMOVE(thread->pt_sleepq, thread,
905 			    pt_sleep);
906 			pthread_spinunlock(self, thread->pt_sleeplock);
907 			pthread__sched(self, thread);
908 		} else {
909 			/*
910 			 * Nothing. The target thread is running and will
911 			 * notice at the next deferred cancellation point.
912 			 */
913 		}
914 		pthread_spinunlock(self, &thread->pt_statelock);
915 	} else
916 		pthread_spinunlock(self, &thread->pt_flaglock);
917 
918 	return 0;
919 }
920 
921 
922 int
923 pthread_setcancelstate(int state, int *oldstate)
924 {
925 	pthread_t self;
926 	int retval;
927 
928 	self = pthread__self();
929 	retval = 0;
930 
931 	pthread_spinlock(self, &self->pt_flaglock);
932 	if (oldstate != NULL) {
933 		if (self->pt_flags & PT_FLAG_CS_DISABLED)
934 			*oldstate = PTHREAD_CANCEL_DISABLE;
935 		else
936 			*oldstate = PTHREAD_CANCEL_ENABLE;
937 	}
938 
939 	if (state == PTHREAD_CANCEL_DISABLE) {
940 		self->pt_flags |= PT_FLAG_CS_DISABLED;
941 		if (self->pt_cancel) {
942 			self->pt_flags |= PT_FLAG_CS_PENDING;
943 			self->pt_cancel = 0;
944 		}
945 	} else if (state == PTHREAD_CANCEL_ENABLE) {
946 		self->pt_flags &= ~PT_FLAG_CS_DISABLED;
947 		/*
948 		 * If a cancellation was requested while cancellation
949 		 * was disabled, note that fact for future
950 		 * cancellation tests.
951 		 */
952 		if (self->pt_flags & PT_FLAG_CS_PENDING) {
953 			self->pt_cancel = 1;
954 			/* This is not a deferred cancellation point. */
955 			if (self->pt_flags & PT_FLAG_CS_ASYNC) {
956 				pthread_spinunlock(self, &self->pt_flaglock);
957 				pthread_exit(PTHREAD_CANCELED);
958 			}
959 		}
960 	} else
961 		retval = EINVAL;
962 
963 	pthread_spinunlock(self, &self->pt_flaglock);
964 	return retval;
965 }
966 
967 
968 int
969 pthread_setcanceltype(int type, int *oldtype)
970 {
971 	pthread_t self;
972 	int retval;
973 
974 	self = pthread__self();
975 	retval = 0;
976 
977 	pthread_spinlock(self, &self->pt_flaglock);
978 
979 	if (oldtype != NULL) {
980 		if (self->pt_flags & PT_FLAG_CS_ASYNC)
981 			*oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
982 		else
983 			*oldtype = PTHREAD_CANCEL_DEFERRED;
984 	}
985 
986 	if (type == PTHREAD_CANCEL_ASYNCHRONOUS) {
987 		self->pt_flags |= PT_FLAG_CS_ASYNC;
988 		if (self->pt_cancel) {
989 			pthread_spinunlock(self, &self->pt_flaglock);
990 			pthread_exit(PTHREAD_CANCELED);
991 		}
992 	} else if (type == PTHREAD_CANCEL_DEFERRED)
993 		self->pt_flags &= ~PT_FLAG_CS_ASYNC;
994 	else
995 		retval = EINVAL;
996 
997 	pthread_spinunlock(self, &self->pt_flaglock);
998 	return retval;
999 }
1000 
1001 
1002 void
1003 pthread_testcancel()
1004 {
1005 	pthread_t self;
1006 
1007 	self = pthread__self();
1008 	if (self->pt_cancel)
1009 		pthread_exit(PTHREAD_CANCELED);
1010 }
1011 
1012 
1013 /*
1014  * POSIX requires that certain functions return an error rather than
1015  * invoking undefined behavior even when handed completely bogus
1016  * pthread_t values, e.g. stack garbage or (pthread_t)666. This
1017  * utility routine searches the list of threads for the pthread_t
1018  * value without dereferencing it.
1019  */
1020 int
1021 pthread__find(pthread_t self, pthread_t id)
1022 {
1023 	pthread_t target;
1024 
1025 	pthread_spinlock(self, &pthread__allqueue_lock);
1026 	PTQ_FOREACH(target, &pthread__allqueue, pt_allq)
1027 	    if (target == id)
1028 		    break;
1029 	pthread_spinunlock(self, &pthread__allqueue_lock);
1030 
1031 	if (target == NULL)
1032 		return ESRCH;
1033 
1034 	return 0;
1035 }
1036 
1037 
1038 void
1039 pthread__testcancel(pthread_t self)
1040 {
1041 
1042 	if (self->pt_cancel)
1043 		pthread_exit(PTHREAD_CANCELED);
1044 }
1045 
1046 
1047 void
1048 pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store)
1049 {
1050 	pthread_t self;
1051 	struct pt_clean_t *entry;
1052 
1053 	self = pthread__self();
1054 	entry = store;
1055 	entry->ptc_cleanup = cleanup;
1056 	entry->ptc_arg = arg;
1057 	PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next);
1058 }
1059 
1060 
1061 void
1062 pthread__cleanup_pop(int ex, void *store)
1063 {
1064 	pthread_t self;
1065 	struct pt_clean_t *entry;
1066 
1067 	self = pthread__self();
1068 	entry = store;
1069 
1070 	PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next);
1071 	if (ex)
1072 		(*entry->ptc_cleanup)(entry->ptc_arg);
1073 }
1074 
1075 
1076 int *
1077 pthread__errno(void)
1078 {
1079 	pthread_t self;
1080 
1081 	self = pthread__self();
1082 
1083 	return &(self->pt_errno);
1084 }
1085 
1086 ssize_t	_sys_write(int, const void *, size_t);
1087 
1088 void
1089 pthread__assertfunc(const char *file, int line, const char *function,
1090 		    const char *expr)
1091 {
1092 	char buf[1024];
1093 	int len;
1094 
1095 	SDPRINTF(("(af)\n"));
1096 
1097 	/*
1098 	 * snprintf should not acquire any locks, or we could
1099 	 * end up deadlocked if the assert caller held locks.
1100 	 */
1101 	len = snprintf(buf, 1024,
1102 	    "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
1103 	    expr, file, line,
1104 	    function ? ", function \"" : "",
1105 	    function ? function : "",
1106 	    function ? "\"" : "");
1107 
1108 	_sys_write(STDERR_FILENO, buf, (size_t)len);
1109 	(void)kill(getpid(), SIGABRT);
1110 
1111 	_exit(1);
1112 }
1113 
1114 
1115 void
1116 pthread__errorfunc(const char *file, int line, const char *function,
1117 		   const char *msg)
1118 {
1119 	char buf[1024];
1120 	size_t len;
1121 
1122 	if (pthread__diagassert == 0)
1123 		return;
1124 
1125 	/*
1126 	 * snprintf should not acquire any locks, or we could
1127 	 * end up deadlocked if the assert caller held locks.
1128 	 */
1129 	len = snprintf(buf, 1024,
1130 	    "%s: Error detected by libpthread: %s.\n"
1131 	    "Detected by file \"%s\", line %d%s%s%s.\n"
1132 	    "See pthread(3) for information.\n",
1133 	    getprogname(), msg, file, line,
1134 	    function ? ", function \"" : "",
1135 	    function ? function : "",
1136 	    function ? "\"" : "");
1137 
1138 	if (pthread__diagassert & DIAGASSERT_STDERR)
1139 		_sys_write(STDERR_FILENO, buf, len);
1140 
1141 	if (pthread__diagassert & DIAGASSERT_SYSLOG)
1142 		syslog(LOG_DEBUG | LOG_USER, "%s", buf);
1143 
1144 	if (pthread__diagassert & DIAGASSERT_ABORT) {
1145 		(void)kill(getpid(), SIGABRT);
1146 		_exit(1);
1147 	}
1148 }
1149