xref: /netbsd-src/lib/libpthread/pthread.c (revision f81322cf185a4db50f71fcf7701f20198272620e)
1 /*	$NetBSD: pthread.c,v 1.47 2006/02/12 11:41:53 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.47 2006/02/12 11:41:53 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 	}
375 
376 	/* 2. Set up state. */
377 	pthread__initthread(self, newthread);
378 	newthread->pt_flags = nattr.pta_flags;
379 	newthread->pt_sigmask = self->pt_sigmask;
380 
381 	/* 3. Set up misc. attributes. */
382 	newthread->pt_name = name;
383 
384 	/*
385 	 * 4. Set up context.
386 	 *
387 	 * The pt_uc pointer points to a location safely below the
388 	 * stack start; this is arranged by pthread__stackalloc().
389 	 */
390 	_INITCONTEXT_U(newthread->pt_uc);
391 #ifdef PTHREAD_MACHINE_HAS_ID_REGISTER
392 	pthread__uc_id(newthread->pt_uc) = newthread;
393 #endif
394 	newthread->pt_uc->uc_stack = newthread->pt_stack;
395 	newthread->pt_uc->uc_link = NULL;
396 	makecontext(newthread->pt_uc, pthread__create_tramp, 2,
397 	    startfunc, arg);
398 
399 	/* 5. Add to list of all threads. */
400 	pthread_spinlock(self, &pthread__allqueue_lock);
401 	PTQ_INSERT_HEAD(&pthread__allqueue, newthread, pt_allq);
402 	nthreads++;
403 	pthread_spinunlock(self, &pthread__allqueue_lock);
404 
405 	SDPRINTF(("(pthread_create %p) new thread %p (name pointer %p).\n",
406 		  self, newthread, newthread->pt_name));
407 	/* 6. Put on appropriate queue. */
408 	if (newthread->pt_flags & PT_FLAG_SUSPENDED) {
409 		pthread_spinlock(self, &newthread->pt_statelock);
410 		pthread__suspend(self, newthread);
411 		pthread_spinunlock(self, &newthread->pt_statelock);
412 	} else
413 		pthread__sched(self, newthread);
414 
415 	*thread = newthread;
416 
417 	return 0;
418 }
419 
420 
421 static void
422 pthread__create_tramp(void *(*start)(void *), void *arg)
423 {
424 	void *retval;
425 
426 	retval = (*start)(arg);
427 
428 	pthread_exit(retval);
429 
430 	/*NOTREACHED*/
431 	pthread__abort();
432 }
433 
434 int
435 pthread_suspend_np(pthread_t thread)
436 {
437 	pthread_t self;
438 
439 	self = pthread__self();
440 	if (self == thread) {
441 		return EDEADLK;
442 	}
443 #ifdef ERRORCHECK
444 	if (pthread__find(self, thread) != 0)
445 		return ESRCH;
446 #endif
447 	SDPRINTF(("(pthread_suspend_np %p) Suspend thread %p (state %d).\n",
448 		     self, thread, thread->pt_state));
449 	pthread_spinlock(self, &thread->pt_statelock);
450 	if (thread->pt_blockgen != thread->pt_unblockgen) {
451 		/* XXX flaglock? */
452 		thread->pt_flags |= PT_FLAG_SUSPENDED;
453 		pthread_spinunlock(self, &thread->pt_statelock);
454 		return 0;
455 	}
456 	switch (thread->pt_state) {
457 	case PT_STATE_RUNNING:
458 		pthread__abort();	/* XXX */
459 		break;
460 	case PT_STATE_SUSPENDED:
461 		pthread_spinunlock(self, &thread->pt_statelock);
462 		return 0;
463 	case PT_STATE_RUNNABLE:
464 		pthread_spinlock(self, &pthread__runqueue_lock);
465 		PTQ_REMOVE(&pthread__runqueue, thread, pt_runq);
466 		pthread_spinunlock(self, &pthread__runqueue_lock);
467 		break;
468 	case PT_STATE_BLOCKED_QUEUE:
469 		pthread_spinlock(self, thread->pt_sleeplock);
470 		PTQ_REMOVE(thread->pt_sleepq, thread, pt_sleep);
471 		pthread_spinunlock(self, thread->pt_sleeplock);
472 		break;
473 	case PT_STATE_ZOMBIE:
474 		goto out;
475 	default:
476 		break;			/* XXX */
477 	}
478 	pthread__suspend(self, thread);
479 
480 out:
481 	pthread_spinunlock(self, &thread->pt_statelock);
482 	return 0;
483 }
484 
485 int
486 pthread_resume_np(pthread_t thread)
487 {
488 	pthread_t self;
489 
490 	self = pthread__self();
491 #ifdef ERRORCHECK
492 	if (pthread__find(self, thread) != 0)
493 		return ESRCH;
494 #endif
495 	SDPRINTF(("(pthread_resume_np %p) Resume thread %p (state %d).\n",
496 		     self, thread, thread->pt_state));
497 	pthread_spinlock(self, &thread->pt_statelock);
498 	/* XXX flaglock? */
499 	thread->pt_flags &= ~PT_FLAG_SUSPENDED;
500 	if (thread->pt_state == PT_STATE_SUSPENDED) {
501 		pthread_spinlock(self, &pthread__runqueue_lock);
502 		PTQ_REMOVE(&pthread__suspqueue, thread, pt_runq);
503 		pthread_spinunlock(self, &pthread__runqueue_lock);
504 		pthread__sched(self, thread);
505 	}
506 	pthread_spinunlock(self, &thread->pt_statelock);
507 	return 0;
508 }
509 
510 
511 /*
512  * Other threads will switch to the idle thread so that they
513  * can dispose of any awkward locks or recycle upcall state.
514  */
515 void
516 pthread__idle(void)
517 {
518 	pthread_t self;
519 
520 	PTHREADD_ADD(PTHREADD_IDLE);
521 	self = pthread__self();
522 	SDPRINTF(("(pthread__idle %p).\n", self));
523 
524 	/*
525 	 * The drill here is that we want to yield the processor,
526 	 * but for the thread itself to be recovered, we need to be on
527 	 * a list somewhere for the thread system to know about us.
528 	 */
529 	pthread_spinlock(self, &pthread__deadqueue_lock);
530 	PTQ_INSERT_TAIL(&pthread__reidlequeue[self->pt_vpid], self, pt_runq);
531 	pthread__concurrency--;
532 	SDPRINTF(("(yield %p concurrency) now %d\n", self,
533 		     pthread__concurrency));
534 	/* Don't need a flag lock; nothing else has a handle on this thread */
535 	self->pt_flags |= PT_FLAG_IDLED;
536 	pthread_spinunlock(self, &pthread__deadqueue_lock);
537 
538 	/*
539 	 * If we get to run this, then no preemption has happened
540 	 * (because the upcall handler will not continue an idle thread with
541 	 * PT_FLAG_IDLED set), and so we can yield the processor safely.
542 	 */
543 	SDPRINTF(("(pthread__idle %p) yielding.\n", self));
544 	sa_yield();
545 
546 	/* NOTREACHED */
547 	self->pt_spinlocks++; /* XXX make sure we get to finish the assert! */
548 	SDPRINTF(("(pthread__idle %p) Returned! Error.\n", self));
549 	pthread__abort();
550 }
551 
552 
553 void
554 pthread_exit(void *retval)
555 {
556 	pthread_t self;
557 	struct pt_clean_t *cleanup;
558 	char *name;
559 	int nt;
560 
561 	self = pthread__self();
562 	SDPRINTF(("(pthread_exit %p) status %p, flags %x, cancel %d\n",
563 		  self, retval, self->pt_flags, self->pt_cancel));
564 
565 	/* Disable cancellability. */
566 	pthread_spinlock(self, &self->pt_flaglock);
567 	self->pt_flags |= PT_FLAG_CS_DISABLED;
568 	self->pt_cancel = 0;
569 	pthread_spinunlock(self, &self->pt_flaglock);
570 
571 	/* Call any cancellation cleanup handlers */
572 	while (!PTQ_EMPTY(&self->pt_cleanup_stack)) {
573 		cleanup = PTQ_FIRST(&self->pt_cleanup_stack);
574 		PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next);
575 		(*cleanup->ptc_cleanup)(cleanup->ptc_arg);
576 	}
577 
578 	/* Perform cleanup of thread-specific data */
579 	pthread__destroy_tsd(self);
580 
581 	self->pt_exitval = retval;
582 
583 	/*
584 	 * it's safe to check PT_FLAG_DETACHED without pt_flaglock
585 	 * because it's only set by pthread_detach with pt_join_lock held.
586 	 */
587 	pthread_spinlock(self, &self->pt_join_lock);
588 	if (self->pt_flags & PT_FLAG_DETACHED) {
589 		self->pt_state = PT_STATE_DEAD;
590 		pthread_spinunlock(self, &self->pt_join_lock);
591 		name = self->pt_name;
592 		self->pt_name = NULL;
593 
594 		if (name != NULL)
595 			free(name);
596 
597 		pthread_spinlock(self, &pthread__allqueue_lock);
598 		PTQ_REMOVE(&pthread__allqueue, self, pt_allq);
599 		nthreads--;
600 		nt = nthreads;
601 		pthread_spinunlock(self, &pthread__allqueue_lock);
602 
603 		if (nt == 0) {
604 			/* Whoah, we're the last one. Time to go. */
605 			exit(0);
606 		}
607 
608 		/* Yeah, yeah, doing work while we're dead is tacky. */
609 		pthread_spinlock(self, &pthread__deadqueue_lock);
610 		PTQ_INSERT_HEAD(&pthread__deadqueue, self, pt_allq);
611 		pthread__block(self, &pthread__deadqueue_lock);
612 		SDPRINTF(("(pthread_exit %p) walking dead\n", self));
613 	} else {
614 		self->pt_state = PT_STATE_ZOMBIE;
615 		/* Note: name will be freed by the joiner. */
616 		pthread_spinlock(self, &pthread__allqueue_lock);
617 		nthreads--;
618 		nt = nthreads;
619 		pthread_spinunlock(self, &pthread__allqueue_lock);
620 		if (nt == 0) {
621 			/* Whoah, we're the last one. Time to go. */
622 			exit(0);
623 		}
624 		/*
625 		 * Wake up all the potential joiners. Only one can win.
626 		 * (Can you say "Thundering Herd"? I knew you could.)
627 		 */
628 		pthread__sched_sleepers(self, &self->pt_joiners);
629 		pthread__block(self, &self->pt_join_lock);
630 		SDPRINTF(("(pthread_exit %p) walking zombie\n", self));
631 	}
632 
633 	/*NOTREACHED*/
634 	pthread__abort();
635 	exit(1);
636 }
637 
638 
639 int
640 pthread_join(pthread_t thread, void **valptr)
641 {
642 	pthread_t self;
643 	char *name;
644 	int num;
645 
646 	self = pthread__self();
647 	SDPRINTF(("(pthread_join %p) Joining %p.\n", self, thread));
648 
649 	if (pthread__find(self, thread) != 0)
650 		return ESRCH;
651 
652 	if (thread->pt_magic != PT_MAGIC)
653 		return EINVAL;
654 
655 	if (thread == self)
656 		return EDEADLK;
657 
658 	pthread_spinlock(self, &thread->pt_flaglock);
659 
660 	if (thread->pt_flags & PT_FLAG_DETACHED) {
661 		pthread_spinunlock(self, &thread->pt_flaglock);
662 		return EINVAL;
663 	}
664 
665 	num = thread->pt_num;
666 	pthread_spinlock(self, &thread->pt_join_lock);
667 	while (thread->pt_state != PT_STATE_ZOMBIE) {
668 		if ((thread->pt_state == PT_STATE_DEAD) ||
669 		    (thread->pt_flags & PT_FLAG_DETACHED) ||
670 		    (thread->pt_num != num)) {
671 			/*
672 			 * Another thread beat us to the join, or called
673 			 * pthread_detach(). If num didn't match, the
674 			 * thread died and was recycled before we got
675 			 * another chance to run.
676 			 */
677 			pthread_spinunlock(self, &thread->pt_join_lock);
678 			pthread_spinunlock(self, &thread->pt_flaglock);
679 			return ESRCH;
680 		}
681 		/*
682 		 * "I'm not dead yet!"
683 		 * "You will be soon enough."
684 		 */
685 		pthread_spinunlock(self, &thread->pt_flaglock);
686 		pthread_spinlock(self, &self->pt_statelock);
687 		if (self->pt_cancel) {
688 			pthread_spinunlock(self, &self->pt_statelock);
689 			pthread_spinunlock(self, &thread->pt_join_lock);
690 			pthread_exit(PTHREAD_CANCELED);
691 		}
692 		self->pt_state = PT_STATE_BLOCKED_QUEUE;
693 		self->pt_sleepobj = thread;
694 		self->pt_sleepq = &thread->pt_joiners;
695 		self->pt_sleeplock = &thread->pt_join_lock;
696 		pthread_spinunlock(self, &self->pt_statelock);
697 
698 		PTQ_INSERT_TAIL(&thread->pt_joiners, self, pt_sleep);
699 		pthread__block(self, &thread->pt_join_lock);
700 		pthread_spinlock(self, &thread->pt_flaglock);
701 		pthread_spinlock(self, &thread->pt_join_lock);
702 	}
703 
704 	/* All ours. */
705 	thread->pt_state = PT_STATE_DEAD;
706 	name = thread->pt_name;
707 	thread->pt_name = NULL;
708 	pthread_spinunlock(self, &thread->pt_join_lock);
709 	pthread_spinunlock(self, &thread->pt_flaglock);
710 
711 	if (valptr != NULL)
712 		*valptr = thread->pt_exitval;
713 
714 	SDPRINTF(("(pthread_join %p) Joined %p.\n", self, thread));
715 
716 	pthread__dead(self, thread);
717 
718 	if (name != NULL)
719 		free(name);
720 
721 	return 0;
722 }
723 
724 
725 int
726 pthread_equal(pthread_t t1, pthread_t t2)
727 {
728 
729 	/* Nothing special here. */
730 	return (t1 == t2);
731 }
732 
733 
734 int
735 pthread_detach(pthread_t thread)
736 {
737 	pthread_t self;
738 	int doreclaim = 0;
739 	char *name = NULL;
740 
741 	self = pthread__self();
742 
743 	if (pthread__find(self, thread) != 0)
744 		return ESRCH;
745 
746 	if (thread->pt_magic != PT_MAGIC)
747 		return EINVAL;
748 
749 	pthread_spinlock(self, &thread->pt_flaglock);
750 	pthread_spinlock(self, &thread->pt_join_lock);
751 
752 	if (thread->pt_flags & PT_FLAG_DETACHED) {
753 		pthread_spinunlock(self, &thread->pt_join_lock);
754 		pthread_spinunlock(self, &thread->pt_flaglock);
755 		return EINVAL;
756 	}
757 
758 	thread->pt_flags |= PT_FLAG_DETACHED;
759 
760 	/* Any joiners have to be punted now. */
761 	pthread__sched_sleepers(self, &thread->pt_joiners);
762 
763 	if (thread->pt_state == PT_STATE_ZOMBIE) {
764 		thread->pt_state = PT_STATE_DEAD;
765 		name = thread->pt_name;
766 		thread->pt_name = NULL;
767 		doreclaim = 1;
768 	}
769 
770 	pthread_spinunlock(self, &thread->pt_join_lock);
771 	pthread_spinunlock(self, &thread->pt_flaglock);
772 
773 	if (doreclaim) {
774 		pthread__dead(self, thread);
775 		if (name != NULL)
776 			free(name);
777 	}
778 
779 	return 0;
780 }
781 
782 
783 static void
784 pthread__dead(pthread_t self, pthread_t thread)
785 {
786 
787 	SDPRINTF(("(pthread__dead %p) Reclaimed %p.\n", self, thread));
788 	pthread__assert(thread != self);
789 	pthread__assert(thread->pt_state == PT_STATE_DEAD);
790 	pthread__assert(thread->pt_name == NULL);
791 
792 	/* Cleanup time. Move the dead thread from allqueue to the deadqueue */
793 	pthread_spinlock(self, &pthread__allqueue_lock);
794 	PTQ_REMOVE(&pthread__allqueue, thread, pt_allq);
795 	pthread_spinunlock(self, &pthread__allqueue_lock);
796 
797 	pthread_spinlock(self, &pthread__deadqueue_lock);
798 	PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_allq);
799 	pthread_spinunlock(self, &pthread__deadqueue_lock);
800 }
801 
802 
803 int
804 pthread_getname_np(pthread_t thread, char *name, size_t len)
805 {
806 	pthread_t self;
807 
808 	self = pthread__self();
809 
810 	if (pthread__find(self, thread) != 0)
811 		return ESRCH;
812 
813 	if (thread->pt_magic != PT_MAGIC)
814 		return EINVAL;
815 
816 	pthread_spinlock(self, &thread->pt_join_lock);
817 	if (thread->pt_name == NULL)
818 		name[0] = '\0';
819 	else
820 		strlcpy(name, thread->pt_name, len);
821 	pthread_spinunlock(self, &thread->pt_join_lock);
822 
823 	return 0;
824 }
825 
826 
827 int
828 pthread_setname_np(pthread_t thread, const char *name, void *arg)
829 {
830 	pthread_t self;
831 	char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP];
832 	int namelen;
833 
834 	self = pthread__self();
835 	if (pthread__find(self, thread) != 0)
836 		return ESRCH;
837 
838 	if (thread->pt_magic != PT_MAGIC)
839 		return EINVAL;
840 
841 	namelen = snprintf(newname, sizeof(newname), name, arg);
842 	if (namelen >= PTHREAD_MAX_NAMELEN_NP)
843 		return EINVAL;
844 
845 	cp = strdup(newname);
846 	if (cp == NULL)
847 		return ENOMEM;
848 
849 	pthread_spinlock(self, &thread->pt_join_lock);
850 
851 	if (thread->pt_state == PT_STATE_DEAD) {
852 		pthread_spinunlock(self, &thread->pt_join_lock);
853 		free(cp);
854 		return EINVAL;
855 	}
856 
857 	oldname = thread->pt_name;
858 	thread->pt_name = cp;
859 
860 	pthread_spinunlock(self, &thread->pt_join_lock);
861 
862 	if (oldname != NULL)
863 		free(oldname);
864 
865 	return 0;
866 }
867 
868 
869 
870 /*
871  * XXX There should be a way for applications to use the efficent
872  *  inline version, but there are opacity/namespace issues.
873  */
874 pthread_t
875 pthread_self(void)
876 {
877 
878 	return pthread__self();
879 }
880 
881 
882 int
883 pthread_cancel(pthread_t thread)
884 {
885 	pthread_t self;
886 
887 	self = pthread__self();
888 #ifdef ERRORCHECK
889 	if (pthread__find(self, thread) != 0)
890 		return ESRCH;
891 #endif
892 	if (!(thread->pt_state == PT_STATE_RUNNING ||
893 	    thread->pt_state == PT_STATE_RUNNABLE ||
894 	    thread->pt_state == PT_STATE_BLOCKED_QUEUE))
895 		return ESRCH;
896 
897 	pthread_spinlock(self, &thread->pt_flaglock);
898 	thread->pt_flags |= PT_FLAG_CS_PENDING;
899 	if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) {
900 		thread->pt_cancel = 1;
901 		pthread_spinunlock(self, &thread->pt_flaglock);
902 		pthread_spinlock(self, &thread->pt_statelock);
903 		if (thread->pt_blockgen != thread->pt_unblockgen) {
904 			/*
905 			 * It's sleeping in the kernel. If we can wake
906 			 * it up, it will notice the cancellation when
907 			 * it returns. If it doesn't wake up when we
908 			 * make this call, then it's blocked
909 			 * uninterruptably in the kernel, and there's
910 			 * not much to be done about it.
911 			 */
912 			_lwp_wakeup(thread->pt_blockedlwp);
913 		} else if (thread->pt_state == PT_STATE_BLOCKED_QUEUE) {
914 			/*
915 			 * We're blocked somewhere (pthread__block()
916 			 * was called). Cause it to wake up; it will
917 			 * check for the cancellation if the routine
918 			 * is a cancellation point, and loop and reblock
919 			 * otherwise.
920 			 */
921 			pthread_spinlock(self, thread->pt_sleeplock);
922 			PTQ_REMOVE(thread->pt_sleepq, thread,
923 			    pt_sleep);
924 			pthread_spinunlock(self, thread->pt_sleeplock);
925 			pthread__sched(self, thread);
926 		} else {
927 			/*
928 			 * Nothing. The target thread is running and will
929 			 * notice at the next deferred cancellation point.
930 			 */
931 		}
932 		pthread_spinunlock(self, &thread->pt_statelock);
933 	} else
934 		pthread_spinunlock(self, &thread->pt_flaglock);
935 
936 	return 0;
937 }
938 
939 
940 int
941 pthread_setcancelstate(int state, int *oldstate)
942 {
943 	pthread_t self;
944 	int retval;
945 
946 	self = pthread__self();
947 	retval = 0;
948 
949 	pthread_spinlock(self, &self->pt_flaglock);
950 	if (oldstate != NULL) {
951 		if (self->pt_flags & PT_FLAG_CS_DISABLED)
952 			*oldstate = PTHREAD_CANCEL_DISABLE;
953 		else
954 			*oldstate = PTHREAD_CANCEL_ENABLE;
955 	}
956 
957 	if (state == PTHREAD_CANCEL_DISABLE) {
958 		self->pt_flags |= PT_FLAG_CS_DISABLED;
959 		if (self->pt_cancel) {
960 			self->pt_flags |= PT_FLAG_CS_PENDING;
961 			self->pt_cancel = 0;
962 		}
963 	} else if (state == PTHREAD_CANCEL_ENABLE) {
964 		self->pt_flags &= ~PT_FLAG_CS_DISABLED;
965 		/*
966 		 * If a cancellation was requested while cancellation
967 		 * was disabled, note that fact for future
968 		 * cancellation tests.
969 		 */
970 		if (self->pt_flags & PT_FLAG_CS_PENDING) {
971 			self->pt_cancel = 1;
972 			/* This is not a deferred cancellation point. */
973 			if (self->pt_flags & PT_FLAG_CS_ASYNC) {
974 				pthread_spinunlock(self, &self->pt_flaglock);
975 				pthread_exit(PTHREAD_CANCELED);
976 			}
977 		}
978 	} else
979 		retval = EINVAL;
980 
981 	pthread_spinunlock(self, &self->pt_flaglock);
982 	return retval;
983 }
984 
985 
986 int
987 pthread_setcanceltype(int type, int *oldtype)
988 {
989 	pthread_t self;
990 	int retval;
991 
992 	self = pthread__self();
993 	retval = 0;
994 
995 	pthread_spinlock(self, &self->pt_flaglock);
996 
997 	if (oldtype != NULL) {
998 		if (self->pt_flags & PT_FLAG_CS_ASYNC)
999 			*oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
1000 		else
1001 			*oldtype = PTHREAD_CANCEL_DEFERRED;
1002 	}
1003 
1004 	if (type == PTHREAD_CANCEL_ASYNCHRONOUS) {
1005 		self->pt_flags |= PT_FLAG_CS_ASYNC;
1006 		if (self->pt_cancel) {
1007 			pthread_spinunlock(self, &self->pt_flaglock);
1008 			pthread_exit(PTHREAD_CANCELED);
1009 		}
1010 	} else if (type == PTHREAD_CANCEL_DEFERRED)
1011 		self->pt_flags &= ~PT_FLAG_CS_ASYNC;
1012 	else
1013 		retval = EINVAL;
1014 
1015 	pthread_spinunlock(self, &self->pt_flaglock);
1016 	return retval;
1017 }
1018 
1019 
1020 void
1021 pthread_testcancel()
1022 {
1023 	pthread_t self;
1024 
1025 	self = pthread__self();
1026 	if (self->pt_cancel)
1027 		pthread_exit(PTHREAD_CANCELED);
1028 }
1029 
1030 
1031 /*
1032  * POSIX requires that certain functions return an error rather than
1033  * invoking undefined behavior even when handed completely bogus
1034  * pthread_t values, e.g. stack garbage or (pthread_t)666. This
1035  * utility routine searches the list of threads for the pthread_t
1036  * value without dereferencing it.
1037  */
1038 int
1039 pthread__find(pthread_t self, pthread_t id)
1040 {
1041 	pthread_t target;
1042 
1043 	pthread_spinlock(self, &pthread__allqueue_lock);
1044 	PTQ_FOREACH(target, &pthread__allqueue, pt_allq)
1045 	    if (target == id)
1046 		    break;
1047 	pthread_spinunlock(self, &pthread__allqueue_lock);
1048 
1049 	if (target == NULL)
1050 		return ESRCH;
1051 
1052 	return 0;
1053 }
1054 
1055 
1056 void
1057 pthread__testcancel(pthread_t self)
1058 {
1059 
1060 	if (self->pt_cancel)
1061 		pthread_exit(PTHREAD_CANCELED);
1062 }
1063 
1064 
1065 void
1066 pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store)
1067 {
1068 	pthread_t self;
1069 	struct pt_clean_t *entry;
1070 
1071 	self = pthread__self();
1072 	entry = store;
1073 	entry->ptc_cleanup = cleanup;
1074 	entry->ptc_arg = arg;
1075 	PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next);
1076 }
1077 
1078 
1079 void
1080 pthread__cleanup_pop(int ex, void *store)
1081 {
1082 	pthread_t self;
1083 	struct pt_clean_t *entry;
1084 
1085 	self = pthread__self();
1086 	entry = store;
1087 
1088 	PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next);
1089 	if (ex)
1090 		(*entry->ptc_cleanup)(entry->ptc_arg);
1091 }
1092 
1093 
1094 int *
1095 pthread__errno(void)
1096 {
1097 	pthread_t self;
1098 
1099 	self = pthread__self();
1100 
1101 	return &(self->pt_errno);
1102 }
1103 
1104 ssize_t	_sys_write(int, const void *, size_t);
1105 
1106 void
1107 pthread__assertfunc(const char *file, int line, const char *function,
1108 		    const char *expr)
1109 {
1110 	char buf[1024];
1111 	int len;
1112 
1113 	SDPRINTF(("(af)\n"));
1114 
1115 	/*
1116 	 * snprintf should not acquire any locks, or we could
1117 	 * end up deadlocked if the assert caller held locks.
1118 	 */
1119 	len = snprintf(buf, 1024,
1120 	    "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
1121 	    expr, file, line,
1122 	    function ? ", function \"" : "",
1123 	    function ? function : "",
1124 	    function ? "\"" : "");
1125 
1126 	_sys_write(STDERR_FILENO, buf, (size_t)len);
1127 	(void)kill(getpid(), SIGABRT);
1128 
1129 	_exit(1);
1130 }
1131 
1132 
1133 void
1134 pthread__errorfunc(const char *file, int line, const char *function,
1135 		   const char *msg)
1136 {
1137 	char buf[1024];
1138 	size_t len;
1139 
1140 	if (pthread__diagassert == 0)
1141 		return;
1142 
1143 	/*
1144 	 * snprintf should not acquire any locks, or we could
1145 	 * end up deadlocked if the assert caller held locks.
1146 	 */
1147 	len = snprintf(buf, 1024,
1148 	    "%s: Error detected by libpthread: %s.\n"
1149 	    "Detected by file \"%s\", line %d%s%s%s.\n"
1150 	    "See pthread(3) for information.\n",
1151 	    getprogname(), msg, file, line,
1152 	    function ? ", function \"" : "",
1153 	    function ? function : "",
1154 	    function ? "\"" : "");
1155 
1156 	if (pthread__diagassert & DIAGASSERT_STDERR)
1157 		_sys_write(STDERR_FILENO, buf, len);
1158 
1159 	if (pthread__diagassert & DIAGASSERT_SYSLOG)
1160 		syslog(LOG_DEBUG | LOG_USER, "%s", buf);
1161 
1162 	if (pthread__diagassert & DIAGASSERT_ABORT) {
1163 		(void)kill(getpid(), SIGABRT);
1164 		_exit(1);
1165 	}
1166 }
1167