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