1 /* $NetBSD: pthread.c,v 1.109 2009/04/01 10:13:24 drochner Exp $ */ 2 3 /*- 4 * Copyright (c) 2001, 2002, 2003, 2006, 2007, 2008 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 and Andrew Doran. 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 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 __RCSID("$NetBSD: pthread.c,v 1.109 2009/04/01 10:13:24 drochner Exp $"); 34 35 #define __EXPOSE_STACK 1 36 37 #include <sys/param.h> 38 #include <sys/mman.h> 39 #include <sys/sysctl.h> 40 #include <sys/lwpctl.h> 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 <sched.h> 53 54 #include "pthread.h" 55 #include "pthread_int.h" 56 57 pthread_rwlock_t pthread__alltree_lock = PTHREAD_RWLOCK_INITIALIZER; 58 RB_HEAD(__pthread__alltree, __pthread_st) pthread__alltree; 59 60 #ifndef lint 61 static int pthread__cmp(struct __pthread_st *, struct __pthread_st *); 62 RB_PROTOTYPE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp) 63 #endif 64 65 static void pthread__create_tramp(pthread_t, void *(*)(void *), void *); 66 static void pthread__initthread(pthread_t); 67 static void pthread__scrubthread(pthread_t, char *, int); 68 static int pthread__stackid_setup(void *, size_t, pthread_t *); 69 static int pthread__stackalloc(pthread_t *); 70 static void pthread__initmain(pthread_t *); 71 static void pthread__fork_callback(void); 72 static void pthread__reap(pthread_t); 73 static void pthread__child_callback(void); 74 static void pthread__start(void); 75 76 void pthread__init(void); 77 78 int pthread__started; 79 pthread_mutex_t pthread__deadqueue_lock = PTHREAD_MUTEX_INITIALIZER; 80 pthread_queue_t pthread__deadqueue; 81 pthread_queue_t pthread__allqueue; 82 83 static pthread_attr_t pthread_default_attr; 84 static lwpctl_t pthread__dummy_lwpctl = { .lc_curcpu = LWPCTL_CPU_NONE }; 85 static pthread_t pthread__first; 86 87 enum { 88 DIAGASSERT_ABORT = 1<<0, 89 DIAGASSERT_STDERR = 1<<1, 90 DIAGASSERT_SYSLOG = 1<<2 91 }; 92 93 static int pthread__diagassert; 94 95 int pthread__concurrency; 96 int pthread__nspins; 97 int pthread__unpark_max = PTHREAD__UNPARK_MAX; 98 99 /* 100 * We have to initialize the pthread_stack* variables here because 101 * mutexes are used before pthread_init() and thus pthread__initmain() 102 * are called. Since mutexes only save the stack pointer and not a 103 * pointer to the thread data, it is safe to change the mapping from 104 * stack pointer to thread data afterwards. 105 */ 106 #define _STACKSIZE_LG 18 107 int pthread__stacksize_lg = _STACKSIZE_LG; 108 size_t pthread__stacksize = 1 << _STACKSIZE_LG; 109 vaddr_t pthread__stackmask = (1 << _STACKSIZE_LG) - 1; 110 vaddr_t pthread__threadmask = (vaddr_t)~((1 << _STACKSIZE_LG) - 1); 111 #undef _STACKSIZE_LG 112 113 int _sys___sigprocmask14(int, const sigset_t *, sigset_t *); 114 115 __strong_alias(__libc_thr_self,pthread_self) 116 __strong_alias(__libc_thr_create,pthread_create) 117 __strong_alias(__libc_thr_exit,pthread_exit) 118 __strong_alias(__libc_thr_errno,pthread__errno) 119 __strong_alias(__libc_thr_setcancelstate,pthread_setcancelstate) 120 __strong_alias(__libc_thr_equal,pthread_equal) 121 __strong_alias(__libc_thr_init,pthread__init) 122 123 /* 124 * Static library kludge. Place a reference to a symbol any library 125 * file which does not already have a reference here. 126 */ 127 extern int pthread__cancel_stub_binder; 128 129 void *pthread__static_lib_binder[] = { 130 &pthread__cancel_stub_binder, 131 pthread_cond_init, 132 pthread_mutex_init, 133 pthread_rwlock_init, 134 pthread_barrier_init, 135 pthread_key_create, 136 pthread_setspecific, 137 }; 138 139 #define NHASHLOCK 64 140 141 static union hashlock { 142 pthread_mutex_t mutex; 143 char pad[64]; 144 } hashlocks[NHASHLOCK] __aligned(64); 145 146 /* 147 * This needs to be started by the library loading code, before main() 148 * gets to run, for various things that use the state of the initial thread 149 * to work properly (thread-specific data is an application-visible example; 150 * spinlock counts for mutexes is an internal example). 151 */ 152 void 153 pthread__init(void) 154 { 155 pthread_t first; 156 char *p; 157 int i, mib[2]; 158 size_t len; 159 extern int __isthreaded; 160 161 mib[0] = CTL_HW; 162 mib[1] = HW_NCPU; 163 164 len = sizeof(pthread__concurrency); 165 if (sysctl(mib, 2, &pthread__concurrency, &len, NULL, 0) == -1) 166 err(1, "sysctl(hw.ncpu"); 167 168 mib[0] = CTL_KERN; 169 mib[1] = KERN_OSREV; 170 171 /* Initialize locks first; they're needed elsewhere. */ 172 pthread__lockprim_init(); 173 for (i = 0; i < NHASHLOCK; i++) { 174 pthread_mutex_init(&hashlocks[i].mutex, NULL); 175 } 176 177 /* Fetch parameters. */ 178 i = (int)_lwp_unpark_all(NULL, 0, NULL); 179 if (i == -1) 180 err(1, "_lwp_unpark_all"); 181 if (i < pthread__unpark_max) 182 pthread__unpark_max = i; 183 184 /* Basic data structure setup */ 185 pthread_attr_init(&pthread_default_attr); 186 PTQ_INIT(&pthread__allqueue); 187 PTQ_INIT(&pthread__deadqueue); 188 RB_INIT(&pthread__alltree); 189 190 /* Create the thread structure corresponding to main() */ 191 pthread__initmain(&first); 192 pthread__initthread(first); 193 pthread__scrubthread(first, NULL, 0); 194 195 first->pt_lid = _lwp_self(); 196 PTQ_INSERT_HEAD(&pthread__allqueue, first, pt_allq); 197 RB_INSERT(__pthread__alltree, &pthread__alltree, first); 198 199 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &first->pt_lwpctl) != 0) { 200 err(1, "_lwp_ctl"); 201 } 202 203 /* Start subsystems */ 204 PTHREAD_MD_INIT 205 206 for (p = pthread__getenv("PTHREAD_DIAGASSERT"); p && *p; p++) { 207 switch (*p) { 208 case 'a': 209 pthread__diagassert |= DIAGASSERT_ABORT; 210 break; 211 case 'A': 212 pthread__diagassert &= ~DIAGASSERT_ABORT; 213 break; 214 case 'e': 215 pthread__diagassert |= DIAGASSERT_STDERR; 216 break; 217 case 'E': 218 pthread__diagassert &= ~DIAGASSERT_STDERR; 219 break; 220 case 'l': 221 pthread__diagassert |= DIAGASSERT_SYSLOG; 222 break; 223 case 'L': 224 pthread__diagassert &= ~DIAGASSERT_SYSLOG; 225 break; 226 } 227 } 228 229 /* Tell libc that we're here and it should role-play accordingly. */ 230 pthread__first = first; 231 pthread_atfork(NULL, NULL, pthread__fork_callback); 232 __isthreaded = 1; 233 } 234 235 static void 236 pthread__fork_callback(void) 237 { 238 239 /* lwpctl state is not copied across fork. */ 240 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &pthread__first->pt_lwpctl)) { 241 err(1, "_lwp_ctl"); 242 } 243 } 244 245 static void 246 pthread__child_callback(void) 247 { 248 249 /* 250 * Clean up data structures that a forked child process might 251 * trip over. Note that if threads have been created (causing 252 * this handler to be registered) the standards say that the 253 * child will trigger undefined behavior if it makes any 254 * pthread_* calls (or any other calls that aren't 255 * async-signal-safe), so we don't really have to clean up 256 * much. Anything that permits some pthread_* calls to work is 257 * merely being polite. 258 */ 259 pthread__started = 0; 260 } 261 262 static void 263 pthread__start(void) 264 { 265 266 /* 267 * Per-process timers are cleared by fork(); despite the 268 * various restrictions on fork() and threads, it's legal to 269 * fork() before creating any threads. 270 */ 271 pthread_atfork(NULL, NULL, pthread__child_callback); 272 } 273 274 275 /* General-purpose thread data structure sanitization. */ 276 /* ARGSUSED */ 277 static void 278 pthread__initthread(pthread_t t) 279 { 280 281 t->pt_self = t; 282 t->pt_magic = PT_MAGIC; 283 t->pt_willpark = 0; 284 t->pt_unpark = 0; 285 t->pt_nwaiters = 0; 286 t->pt_sleepobj = NULL; 287 t->pt_signalled = 0; 288 t->pt_havespecific = 0; 289 t->pt_early = NULL; 290 t->pt_lwpctl = &pthread__dummy_lwpctl; 291 t->pt_blocking = 0; 292 t->pt_droplock = NULL; 293 294 memcpy(&t->pt_lockops, pthread__lock_ops, sizeof(t->pt_lockops)); 295 pthread_mutex_init(&t->pt_lock, NULL); 296 PTQ_INIT(&t->pt_cleanup_stack); 297 pthread_cond_init(&t->pt_joiners, NULL); 298 memset(&t->pt_specific, 0, sizeof(t->pt_specific)); 299 } 300 301 static void 302 pthread__scrubthread(pthread_t t, char *name, int flags) 303 { 304 305 t->pt_state = PT_STATE_RUNNING; 306 t->pt_exitval = NULL; 307 t->pt_flags = flags; 308 t->pt_cancel = 0; 309 t->pt_errno = 0; 310 t->pt_name = name; 311 t->pt_lid = 0; 312 } 313 314 315 int 316 pthread_create(pthread_t *thread, const pthread_attr_t *attr, 317 void *(*startfunc)(void *), void *arg) 318 { 319 pthread_t newthread; 320 pthread_attr_t nattr; 321 struct pthread_attr_private *p; 322 char * volatile name; 323 unsigned long flag; 324 int ret; 325 326 /* 327 * It's okay to check this without a lock because there can 328 * only be one thread before it becomes true. 329 */ 330 if (pthread__started == 0) { 331 pthread__start(); 332 pthread__started = 1; 333 } 334 335 if (attr == NULL) 336 nattr = pthread_default_attr; 337 else if (attr->pta_magic == PT_ATTR_MAGIC) 338 nattr = *attr; 339 else 340 return EINVAL; 341 342 /* Fetch misc. attributes from the attr structure. */ 343 name = NULL; 344 if ((p = nattr.pta_private) != NULL) 345 if (p->ptap_name[0] != '\0') 346 if ((name = strdup(p->ptap_name)) == NULL) 347 return ENOMEM; 348 349 newthread = NULL; 350 351 /* 352 * Try to reclaim a dead thread. 353 */ 354 if (!PTQ_EMPTY(&pthread__deadqueue)) { 355 pthread_mutex_lock(&pthread__deadqueue_lock); 356 newthread = PTQ_FIRST(&pthread__deadqueue); 357 if (newthread != NULL) { 358 PTQ_REMOVE(&pthread__deadqueue, newthread, pt_deadq); 359 pthread_mutex_unlock(&pthread__deadqueue_lock); 360 /* Still running? */ 361 if (newthread->pt_lwpctl->lc_curcpu != 362 LWPCTL_CPU_EXITED && 363 (_lwp_kill(newthread->pt_lid, 0) == 0 || 364 errno != ESRCH)) { 365 pthread_mutex_lock(&pthread__deadqueue_lock); 366 PTQ_INSERT_TAIL(&pthread__deadqueue, 367 newthread, pt_deadq); 368 pthread_mutex_unlock(&pthread__deadqueue_lock); 369 newthread = NULL; 370 } 371 } else 372 pthread_mutex_unlock(&pthread__deadqueue_lock); 373 } 374 375 /* 376 * If necessary set up a stack, allocate space for a pthread_st, 377 * and initialize it. 378 */ 379 if (newthread == NULL) { 380 ret = pthread__stackalloc(&newthread); 381 if (ret != 0) { 382 if (name) 383 free(name); 384 return ret; 385 } 386 387 /* This is used only when creating the thread. */ 388 _INITCONTEXT_U(&newthread->pt_uc); 389 #ifdef PTHREAD_MACHINE_HAS_ID_REGISTER 390 pthread__uc_id(&newthread->pt_uc) = newthread; 391 #endif 392 newthread->pt_uc.uc_stack = newthread->pt_stack; 393 newthread->pt_uc.uc_link = NULL; 394 395 /* Add to list of all threads. */ 396 pthread_rwlock_wrlock(&pthread__alltree_lock); 397 PTQ_INSERT_TAIL(&pthread__allqueue, newthread, pt_allq); 398 RB_INSERT(__pthread__alltree, &pthread__alltree, newthread); 399 pthread_rwlock_unlock(&pthread__alltree_lock); 400 401 /* Will be reset by the thread upon exit. */ 402 pthread__initthread(newthread); 403 } 404 405 /* 406 * Create the new LWP. 407 */ 408 pthread__scrubthread(newthread, name, nattr.pta_flags); 409 makecontext(&newthread->pt_uc, pthread__create_tramp, 3, 410 newthread, startfunc, arg); 411 412 flag = LWP_DETACHED; 413 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) != 0 || 414 (nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0) 415 flag |= LWP_SUSPENDED; 416 ret = _lwp_create(&newthread->pt_uc, flag, &newthread->pt_lid); 417 if (ret != 0) { 418 free(name); 419 newthread->pt_state = PT_STATE_DEAD; 420 pthread_mutex_lock(&pthread__deadqueue_lock); 421 PTQ_INSERT_HEAD(&pthread__deadqueue, newthread, pt_deadq); 422 pthread_mutex_unlock(&pthread__deadqueue_lock); 423 return ret; 424 } 425 426 if ((nattr.pta_flags & PT_FLAG_EXPLICIT_SCHED) != 0) { 427 if (p != NULL) { 428 (void)pthread_setschedparam(newthread, p->ptap_policy, 429 &p->ptap_sp); 430 } 431 if ((newthread->pt_flags & PT_FLAG_SUSPENDED) == 0) { 432 (void)_lwp_continue(newthread->pt_lid); 433 } 434 } 435 436 *thread = newthread; 437 438 return 0; 439 } 440 441 442 static void 443 pthread__create_tramp(pthread_t self, void *(*start)(void *), void *arg) 444 { 445 void *retval; 446 447 /* 448 * Set up identity register. 449 * XXX Race: could receive a signal before this. 450 */ 451 (void)_lwp_setprivate(self); 452 453 /* 454 * Throw away some stack in a feeble attempt to reduce cache 455 * thrash. May help for SMT processors. XXX We should not 456 * be allocating stacks on fixed 2MB boundaries. Needs a 457 * thread register or decent thread local storage. Note 458 * that pt_lid may not be set by this point, but we don't 459 * care. 460 */ 461 (void)alloca(((unsigned)self->pt_lid & 7) << 8); 462 463 if (self->pt_name != NULL) { 464 pthread_mutex_lock(&self->pt_lock); 465 if (self->pt_name != NULL) 466 (void)_lwp_setname(0, self->pt_name); 467 pthread_mutex_unlock(&self->pt_lock); 468 } 469 470 if (_lwp_ctl(LWPCTL_FEATURE_CURCPU, &self->pt_lwpctl)) { 471 err(1, "_lwp_ctl"); 472 } 473 474 retval = (*start)(arg); 475 476 pthread_exit(retval); 477 478 /*NOTREACHED*/ 479 pthread__abort(); 480 } 481 482 int 483 pthread_suspend_np(pthread_t thread) 484 { 485 pthread_t self; 486 487 self = pthread__self(); 488 if (self == thread) { 489 return EDEADLK; 490 } 491 if (pthread__find(thread) != 0) 492 return ESRCH; 493 if (_lwp_suspend(thread->pt_lid) == 0) 494 return 0; 495 return errno; 496 } 497 498 int 499 pthread_resume_np(pthread_t thread) 500 { 501 502 if (pthread__find(thread) != 0) 503 return ESRCH; 504 if (_lwp_continue(thread->pt_lid) == 0) 505 return 0; 506 return errno; 507 } 508 509 void 510 pthread_exit(void *retval) 511 { 512 pthread_t self; 513 struct pt_clean_t *cleanup; 514 char *name; 515 516 self = pthread__self(); 517 518 /* Disable cancellability. */ 519 pthread_mutex_lock(&self->pt_lock); 520 self->pt_flags |= PT_FLAG_CS_DISABLED; 521 self->pt_cancel = 0; 522 523 /* Call any cancellation cleanup handlers */ 524 if (!PTQ_EMPTY(&self->pt_cleanup_stack)) { 525 pthread_mutex_unlock(&self->pt_lock); 526 while (!PTQ_EMPTY(&self->pt_cleanup_stack)) { 527 cleanup = PTQ_FIRST(&self->pt_cleanup_stack); 528 PTQ_REMOVE(&self->pt_cleanup_stack, cleanup, ptc_next); 529 (*cleanup->ptc_cleanup)(cleanup->ptc_arg); 530 } 531 pthread_mutex_lock(&self->pt_lock); 532 } 533 534 /* Perform cleanup of thread-specific data */ 535 pthread__destroy_tsd(self); 536 537 /* Signal our exit. */ 538 self->pt_exitval = retval; 539 if (self->pt_flags & PT_FLAG_DETACHED) { 540 self->pt_state = PT_STATE_DEAD; 541 name = self->pt_name; 542 self->pt_name = NULL; 543 pthread_mutex_unlock(&self->pt_lock); 544 if (name != NULL) 545 free(name); 546 pthread_mutex_lock(&pthread__deadqueue_lock); 547 PTQ_INSERT_TAIL(&pthread__deadqueue, self, pt_deadq); 548 pthread_mutex_unlock(&pthread__deadqueue_lock); 549 _lwp_exit(); 550 } else { 551 self->pt_state = PT_STATE_ZOMBIE; 552 pthread_cond_broadcast(&self->pt_joiners); 553 pthread_mutex_unlock(&self->pt_lock); 554 /* Note: name will be freed by the joiner. */ 555 _lwp_exit(); 556 } 557 558 /*NOTREACHED*/ 559 pthread__abort(); 560 exit(1); 561 } 562 563 564 int 565 pthread_join(pthread_t thread, void **valptr) 566 { 567 pthread_t self; 568 int error; 569 570 self = pthread__self(); 571 572 if (pthread__find(thread) != 0) 573 return ESRCH; 574 575 if (thread->pt_magic != PT_MAGIC) 576 return EINVAL; 577 578 if (thread == self) 579 return EDEADLK; 580 581 self->pt_droplock = &thread->pt_lock; 582 pthread_mutex_lock(&thread->pt_lock); 583 for (;;) { 584 if (thread->pt_state == PT_STATE_ZOMBIE) 585 break; 586 if (thread->pt_state == PT_STATE_DEAD) { 587 pthread_mutex_unlock(&thread->pt_lock); 588 self->pt_droplock = NULL; 589 return ESRCH; 590 } 591 if ((thread->pt_flags & PT_FLAG_DETACHED) != 0) { 592 pthread_mutex_unlock(&thread->pt_lock); 593 self->pt_droplock = NULL; 594 return EINVAL; 595 } 596 error = pthread_cond_wait(&thread->pt_joiners, 597 &thread->pt_lock); 598 if (error != 0) { 599 pthread__errorfunc(__FILE__, __LINE__, 600 __func__, "unexpected return from cond_wait()"); 601 } 602 603 } 604 pthread__testcancel(self); 605 if (valptr != NULL) 606 *valptr = thread->pt_exitval; 607 /* pthread__reap() will drop the lock. */ 608 pthread__reap(thread); 609 self->pt_droplock = NULL; 610 611 return 0; 612 } 613 614 static void 615 pthread__reap(pthread_t thread) 616 { 617 char *name; 618 619 name = thread->pt_name; 620 thread->pt_name = NULL; 621 thread->pt_state = PT_STATE_DEAD; 622 pthread_mutex_unlock(&thread->pt_lock); 623 624 pthread_mutex_lock(&pthread__deadqueue_lock); 625 PTQ_INSERT_HEAD(&pthread__deadqueue, thread, pt_deadq); 626 pthread_mutex_unlock(&pthread__deadqueue_lock); 627 628 if (name != NULL) 629 free(name); 630 } 631 632 int 633 pthread_equal(pthread_t t1, pthread_t t2) 634 { 635 636 /* Nothing special here. */ 637 return (t1 == t2); 638 } 639 640 641 int 642 pthread_detach(pthread_t thread) 643 { 644 645 if (pthread__find(thread) != 0) 646 return ESRCH; 647 648 if (thread->pt_magic != PT_MAGIC) 649 return EINVAL; 650 651 pthread_mutex_lock(&thread->pt_lock); 652 thread->pt_flags |= PT_FLAG_DETACHED; 653 if (thread->pt_state == PT_STATE_ZOMBIE) { 654 /* pthread__reap() will drop the lock. */ 655 pthread__reap(thread); 656 } else { 657 /* 658 * Not valid for threads to be waiting in 659 * pthread_join() (there are intractable 660 * sync issues from the application 661 * perspective), but give those threads 662 * a chance anyway. 663 */ 664 pthread_cond_broadcast(&thread->pt_joiners); 665 pthread_mutex_unlock(&thread->pt_lock); 666 } 667 668 return 0; 669 } 670 671 672 int 673 pthread_getname_np(pthread_t thread, char *name, size_t len) 674 { 675 676 if (pthread__find(thread) != 0) 677 return ESRCH; 678 679 if (thread->pt_magic != PT_MAGIC) 680 return EINVAL; 681 682 pthread_mutex_lock(&thread->pt_lock); 683 if (thread->pt_name == NULL) 684 name[0] = '\0'; 685 else 686 strlcpy(name, thread->pt_name, len); 687 pthread_mutex_unlock(&thread->pt_lock); 688 689 return 0; 690 } 691 692 693 int 694 pthread_setname_np(pthread_t thread, const char *name, void *arg) 695 { 696 char *oldname, *cp, newname[PTHREAD_MAX_NAMELEN_NP]; 697 int namelen; 698 699 if (pthread__find(thread) != 0) 700 return ESRCH; 701 702 if (thread->pt_magic != PT_MAGIC) 703 return EINVAL; 704 705 namelen = snprintf(newname, sizeof(newname), name, arg); 706 if (namelen >= PTHREAD_MAX_NAMELEN_NP) 707 return EINVAL; 708 709 cp = strdup(newname); 710 if (cp == NULL) 711 return ENOMEM; 712 713 pthread_mutex_lock(&thread->pt_lock); 714 oldname = thread->pt_name; 715 thread->pt_name = cp; 716 (void)_lwp_setname(thread->pt_lid, cp); 717 pthread_mutex_unlock(&thread->pt_lock); 718 719 if (oldname != NULL) 720 free(oldname); 721 722 return 0; 723 } 724 725 726 727 /* 728 * XXX There should be a way for applications to use the efficent 729 * inline version, but there are opacity/namespace issues. 730 */ 731 pthread_t 732 pthread_self(void) 733 { 734 735 return pthread__self(); 736 } 737 738 739 int 740 pthread_cancel(pthread_t thread) 741 { 742 743 if (pthread__find(thread) != 0) 744 return ESRCH; 745 pthread_mutex_lock(&thread->pt_lock); 746 thread->pt_flags |= PT_FLAG_CS_PENDING; 747 if ((thread->pt_flags & PT_FLAG_CS_DISABLED) == 0) { 748 thread->pt_cancel = 1; 749 pthread_mutex_unlock(&thread->pt_lock); 750 _lwp_wakeup(thread->pt_lid); 751 } else 752 pthread_mutex_unlock(&thread->pt_lock); 753 754 return 0; 755 } 756 757 758 int 759 pthread_setcancelstate(int state, int *oldstate) 760 { 761 pthread_t self; 762 int retval; 763 764 self = pthread__self(); 765 retval = 0; 766 767 pthread_mutex_lock(&self->pt_lock); 768 769 if (oldstate != NULL) { 770 if (self->pt_flags & PT_FLAG_CS_DISABLED) 771 *oldstate = PTHREAD_CANCEL_DISABLE; 772 else 773 *oldstate = PTHREAD_CANCEL_ENABLE; 774 } 775 776 if (state == PTHREAD_CANCEL_DISABLE) { 777 self->pt_flags |= PT_FLAG_CS_DISABLED; 778 if (self->pt_cancel) { 779 self->pt_flags |= PT_FLAG_CS_PENDING; 780 self->pt_cancel = 0; 781 } 782 } else if (state == PTHREAD_CANCEL_ENABLE) { 783 self->pt_flags &= ~PT_FLAG_CS_DISABLED; 784 /* 785 * If a cancellation was requested while cancellation 786 * was disabled, note that fact for future 787 * cancellation tests. 788 */ 789 if (self->pt_flags & PT_FLAG_CS_PENDING) { 790 self->pt_cancel = 1; 791 /* This is not a deferred cancellation point. */ 792 if (self->pt_flags & PT_FLAG_CS_ASYNC) { 793 pthread_mutex_unlock(&self->pt_lock); 794 pthread__cancelled(); 795 } 796 } 797 } else 798 retval = EINVAL; 799 800 pthread_mutex_unlock(&self->pt_lock); 801 802 return retval; 803 } 804 805 806 int 807 pthread_setcanceltype(int type, int *oldtype) 808 { 809 pthread_t self; 810 int retval; 811 812 self = pthread__self(); 813 retval = 0; 814 815 pthread_mutex_lock(&self->pt_lock); 816 817 if (oldtype != NULL) { 818 if (self->pt_flags & PT_FLAG_CS_ASYNC) 819 *oldtype = PTHREAD_CANCEL_ASYNCHRONOUS; 820 else 821 *oldtype = PTHREAD_CANCEL_DEFERRED; 822 } 823 824 if (type == PTHREAD_CANCEL_ASYNCHRONOUS) { 825 self->pt_flags |= PT_FLAG_CS_ASYNC; 826 if (self->pt_cancel) { 827 pthread_mutex_unlock(&self->pt_lock); 828 pthread__cancelled(); 829 } 830 } else if (type == PTHREAD_CANCEL_DEFERRED) 831 self->pt_flags &= ~PT_FLAG_CS_ASYNC; 832 else 833 retval = EINVAL; 834 835 pthread_mutex_unlock(&self->pt_lock); 836 837 return retval; 838 } 839 840 841 void 842 pthread_testcancel(void) 843 { 844 pthread_t self; 845 846 self = pthread__self(); 847 if (self->pt_cancel) 848 pthread__cancelled(); 849 } 850 851 852 /* 853 * POSIX requires that certain functions return an error rather than 854 * invoking undefined behavior even when handed completely bogus 855 * pthread_t values, e.g. stack garbage or (pthread_t)666. This 856 * utility routine searches the list of threads for the pthread_t 857 * value without dereferencing it. 858 */ 859 int 860 pthread__find(pthread_t id) 861 { 862 pthread_t target; 863 864 pthread_rwlock_rdlock(&pthread__alltree_lock); 865 /* LINTED */ 866 target = RB_FIND(__pthread__alltree, &pthread__alltree, id); 867 pthread_rwlock_unlock(&pthread__alltree_lock); 868 869 if (target == NULL || target->pt_state == PT_STATE_DEAD) 870 return ESRCH; 871 872 return 0; 873 } 874 875 876 void 877 pthread__testcancel(pthread_t self) 878 { 879 880 if (self->pt_cancel) 881 pthread__cancelled(); 882 } 883 884 885 void 886 pthread__cancelled(void) 887 { 888 pthread_mutex_t *droplock; 889 pthread_t self; 890 891 self = pthread__self(); 892 droplock = self->pt_droplock; 893 self->pt_droplock = NULL; 894 895 if (droplock != NULL && pthread_mutex_held_np(droplock)) 896 pthread_mutex_unlock(droplock); 897 898 pthread_exit(PTHREAD_CANCELED); 899 } 900 901 902 void 903 pthread__cleanup_push(void (*cleanup)(void *), void *arg, void *store) 904 { 905 pthread_t self; 906 struct pt_clean_t *entry; 907 908 self = pthread__self(); 909 entry = store; 910 entry->ptc_cleanup = cleanup; 911 entry->ptc_arg = arg; 912 PTQ_INSERT_HEAD(&self->pt_cleanup_stack, entry, ptc_next); 913 } 914 915 916 void 917 pthread__cleanup_pop(int ex, void *store) 918 { 919 pthread_t self; 920 struct pt_clean_t *entry; 921 922 self = pthread__self(); 923 entry = store; 924 925 PTQ_REMOVE(&self->pt_cleanup_stack, entry, ptc_next); 926 if (ex) 927 (*entry->ptc_cleanup)(entry->ptc_arg); 928 } 929 930 931 int * 932 pthread__errno(void) 933 { 934 pthread_t self; 935 936 self = pthread__self(); 937 938 return &(self->pt_errno); 939 } 940 941 ssize_t _sys_write(int, const void *, size_t); 942 943 void 944 pthread__assertfunc(const char *file, int line, const char *function, 945 const char *expr) 946 { 947 char buf[1024]; 948 int len; 949 950 /* 951 * snprintf should not acquire any locks, or we could 952 * end up deadlocked if the assert caller held locks. 953 */ 954 len = snprintf(buf, 1024, 955 "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n", 956 expr, file, line, 957 function ? ", function \"" : "", 958 function ? function : "", 959 function ? "\"" : ""); 960 961 _sys_write(STDERR_FILENO, buf, (size_t)len); 962 (void)kill(getpid(), SIGABRT); 963 964 _exit(1); 965 } 966 967 968 void 969 pthread__errorfunc(const char *file, int line, const char *function, 970 const char *msg) 971 { 972 char buf[1024]; 973 size_t len; 974 975 if (pthread__diagassert == 0) 976 return; 977 978 /* 979 * snprintf should not acquire any locks, or we could 980 * end up deadlocked if the assert caller held locks. 981 */ 982 len = snprintf(buf, 1024, 983 "%s: Error detected by libpthread: %s.\n" 984 "Detected by file \"%s\", line %d%s%s%s.\n" 985 "See pthread(3) for information.\n", 986 getprogname(), msg, file, line, 987 function ? ", function \"" : "", 988 function ? function : "", 989 function ? "\"" : ""); 990 991 if (pthread__diagassert & DIAGASSERT_STDERR) 992 _sys_write(STDERR_FILENO, buf, len); 993 994 if (pthread__diagassert & DIAGASSERT_SYSLOG) 995 syslog(LOG_DEBUG | LOG_USER, "%s", buf); 996 997 if (pthread__diagassert & DIAGASSERT_ABORT) { 998 (void)kill(getpid(), SIGABRT); 999 _exit(1); 1000 } 1001 } 1002 1003 /* 1004 * Thread park/unpark operations. The kernel operations are 1005 * modelled after a brief description from "Multithreading in 1006 * the Solaris Operating Environment": 1007 * 1008 * http://www.sun.com/software/whitepapers/solaris9/multithread.pdf 1009 */ 1010 1011 #define OOPS(msg) \ 1012 pthread__errorfunc(__FILE__, __LINE__, __func__, msg) 1013 1014 int 1015 pthread__park(pthread_t self, pthread_mutex_t *lock, 1016 pthread_queue_t *queue, const struct timespec *abstime, 1017 int cancelpt, const void *hint) 1018 { 1019 int rv, error; 1020 void *obj; 1021 1022 /* 1023 * For non-interlocked release of mutexes we need a store 1024 * barrier before incrementing pt_blocking away from zero. 1025 * This is provided by pthread_mutex_unlock(). 1026 */ 1027 self->pt_willpark = 1; 1028 pthread_mutex_unlock(lock); 1029 self->pt_willpark = 0; 1030 self->pt_blocking++; 1031 1032 /* 1033 * Wait until we are awoken by a pending unpark operation, 1034 * a signal, an unpark posted after we have gone asleep, 1035 * or an expired timeout. 1036 * 1037 * It is fine to test the value of pt_sleepobj without 1038 * holding any locks, because: 1039 * 1040 * o Only the blocking thread (this thread) ever sets them 1041 * to a non-NULL value. 1042 * 1043 * o Other threads may set them NULL, but if they do so they 1044 * must also make this thread return from _lwp_park. 1045 * 1046 * o _lwp_park, _lwp_unpark and _lwp_unpark_all are system 1047 * calls and all make use of spinlocks in the kernel. So 1048 * these system calls act as full memory barriers, and will 1049 * ensure that the calling CPU's store buffers are drained. 1050 * In combination with the spinlock release before unpark, 1051 * this means that modification of pt_sleepobj/onq by another 1052 * thread will become globally visible before that thread 1053 * schedules an unpark operation on this thread. 1054 * 1055 * Note: the test in the while() statement dodges the park op if 1056 * we have already been awoken, unless there is another thread to 1057 * awaken. This saves a syscall - if we were already awakened, 1058 * the next call to _lwp_park() would need to return early in order 1059 * to eat the previous wakeup. 1060 */ 1061 rv = 0; 1062 do { 1063 /* 1064 * If we deferred unparking a thread, arrange to 1065 * have _lwp_park() restart it before blocking. 1066 */ 1067 error = _lwp_park(abstime, self->pt_unpark, hint, hint); 1068 self->pt_unpark = 0; 1069 if (error != 0) { 1070 switch (rv = errno) { 1071 case EINTR: 1072 case EALREADY: 1073 rv = 0; 1074 break; 1075 case ETIMEDOUT: 1076 break; 1077 default: 1078 OOPS("_lwp_park failed"); 1079 break; 1080 } 1081 } 1082 /* Check for cancellation. */ 1083 if (cancelpt && self->pt_cancel) 1084 rv = EINTR; 1085 } while (self->pt_sleepobj != NULL && rv == 0); 1086 1087 /* 1088 * If we have been awoken early but are still on the queue, 1089 * then remove ourself. Again, it's safe to do the test 1090 * without holding any locks. 1091 */ 1092 if (__predict_false(self->pt_sleepobj != NULL)) { 1093 pthread_mutex_lock(lock); 1094 if ((obj = self->pt_sleepobj) != NULL) { 1095 PTQ_REMOVE(queue, self, pt_sleep); 1096 self->pt_sleepobj = NULL; 1097 if (obj != NULL && self->pt_early != NULL) 1098 (*self->pt_early)(obj); 1099 } 1100 pthread_mutex_unlock(lock); 1101 } 1102 self->pt_early = NULL; 1103 self->pt_blocking--; 1104 membar_sync(); 1105 1106 return rv; 1107 } 1108 1109 void 1110 pthread__unpark(pthread_queue_t *queue, pthread_t self, 1111 pthread_mutex_t *interlock) 1112 { 1113 pthread_t target; 1114 u_int max; 1115 size_t nwaiters; 1116 1117 max = pthread__unpark_max; 1118 nwaiters = self->pt_nwaiters; 1119 target = PTQ_FIRST(queue); 1120 if (nwaiters == max) { 1121 /* Overflow. */ 1122 (void)_lwp_unpark_all(self->pt_waiters, nwaiters, 1123 __UNVOLATILE(&interlock->ptm_waiters)); 1124 nwaiters = 0; 1125 } 1126 target->pt_sleepobj = NULL; 1127 self->pt_waiters[nwaiters++] = target->pt_lid; 1128 PTQ_REMOVE(queue, target, pt_sleep); 1129 self->pt_nwaiters = nwaiters; 1130 pthread__mutex_deferwake(self, interlock); 1131 } 1132 1133 void 1134 pthread__unpark_all(pthread_queue_t *queue, pthread_t self, 1135 pthread_mutex_t *interlock) 1136 { 1137 pthread_t target; 1138 u_int max; 1139 size_t nwaiters; 1140 1141 max = pthread__unpark_max; 1142 nwaiters = self->pt_nwaiters; 1143 PTQ_FOREACH(target, queue, pt_sleep) { 1144 if (nwaiters == max) { 1145 /* Overflow. */ 1146 (void)_lwp_unpark_all(self->pt_waiters, nwaiters, 1147 __UNVOLATILE(&interlock->ptm_waiters)); 1148 nwaiters = 0; 1149 } 1150 target->pt_sleepobj = NULL; 1151 self->pt_waiters[nwaiters++] = target->pt_lid; 1152 } 1153 self->pt_nwaiters = nwaiters; 1154 PTQ_INIT(queue); 1155 pthread__mutex_deferwake(self, interlock); 1156 } 1157 1158 #undef OOPS 1159 1160 /* 1161 * Allocate a stack for a thread, and set it up. It needs to be aligned, so 1162 * that a thread can find itself by its stack pointer. 1163 */ 1164 static int 1165 pthread__stackalloc(pthread_t *newt) 1166 { 1167 void *addr; 1168 1169 addr = mmap(NULL, pthread__stacksize, PROT_READ|PROT_WRITE, 1170 MAP_ANON|MAP_PRIVATE | MAP_ALIGNED(pthread__stacksize_lg), 1171 -1, (off_t)0); 1172 1173 if (addr == MAP_FAILED) 1174 return ENOMEM; 1175 1176 pthread__assert(((intptr_t)addr & pthread__stackmask) == 0); 1177 1178 return pthread__stackid_setup(addr, pthread__stacksize, newt); 1179 } 1180 1181 1182 /* 1183 * Set up the slightly special stack for the "initial" thread, which 1184 * runs on the normal system stack, and thus gets slightly different 1185 * treatment. 1186 */ 1187 static void 1188 pthread__initmain(pthread_t *newt) 1189 { 1190 struct rlimit slimit; 1191 size_t pagesize; 1192 pthread_t t; 1193 void *base; 1194 size_t size; 1195 int error, ret; 1196 char *value; 1197 1198 pagesize = (size_t)sysconf(_SC_PAGESIZE); 1199 pthread__stacksize = 0; 1200 ret = getrlimit(RLIMIT_STACK, &slimit); 1201 if (ret == -1) 1202 err(1, "Couldn't get stack resource consumption limits"); 1203 1204 value = pthread__getenv("PTHREAD_STACKSIZE"); 1205 if (value != NULL) { 1206 pthread__stacksize = atoi(value) * 1024; 1207 if (pthread__stacksize > slimit.rlim_cur) 1208 pthread__stacksize = (size_t)slimit.rlim_cur; 1209 } 1210 if (pthread__stacksize == 0) 1211 pthread__stacksize = (size_t)slimit.rlim_cur; 1212 if (pthread__stacksize < 4 * pagesize) 1213 errx(1, "Stacksize limit is too low, minimum %zd kbyte.", 1214 4 * pagesize / 1024); 1215 1216 pthread__stacksize_lg = -1; 1217 while (pthread__stacksize) { 1218 pthread__stacksize >>= 1; 1219 pthread__stacksize_lg++; 1220 } 1221 1222 pthread__stacksize = (1 << pthread__stacksize_lg); 1223 pthread__stackmask = pthread__stacksize - 1; 1224 pthread__threadmask = ~pthread__stackmask; 1225 1226 base = (void *)(pthread__sp() & pthread__threadmask); 1227 size = pthread__stacksize; 1228 1229 error = pthread__stackid_setup(base, size, &t); 1230 if (error) { 1231 /* XXX */ 1232 errx(2, "failed to setup main thread: error=%d", error); 1233 } 1234 1235 *newt = t; 1236 1237 /* Set up identity register. */ 1238 (void)_lwp_setprivate(t); 1239 } 1240 1241 static int 1242 /*ARGSUSED*/ 1243 pthread__stackid_setup(void *base, size_t size, pthread_t *tp) 1244 { 1245 pthread_t t; 1246 void *redaddr; 1247 size_t pagesize; 1248 int ret; 1249 1250 t = base; 1251 pagesize = (size_t)sysconf(_SC_PAGESIZE); 1252 1253 /* 1254 * Put a pointer to the pthread in the bottom (but 1255 * redzone-protected section) of the stack. 1256 */ 1257 redaddr = STACK_SHRINK(STACK_MAX(base, size), pagesize); 1258 t->pt_stack.ss_size = size - 2 * pagesize; 1259 #ifdef __MACHINE_STACK_GROWS_UP 1260 t->pt_stack.ss_sp = (char *)(void *)base + pagesize; 1261 #else 1262 t->pt_stack.ss_sp = (char *)(void *)base + 2 * pagesize; 1263 #endif 1264 1265 /* Protect the next-to-bottom stack page as a red zone. */ 1266 ret = mprotect(redaddr, pagesize, PROT_NONE); 1267 if (ret == -1) { 1268 return errno; 1269 } 1270 *tp = t; 1271 return 0; 1272 } 1273 1274 #ifndef lint 1275 static int 1276 pthread__cmp(struct __pthread_st *a, struct __pthread_st *b) 1277 { 1278 1279 if ((uintptr_t)a < (uintptr_t)b) 1280 return (-1); 1281 else if (a == b) 1282 return 0; 1283 else 1284 return 1; 1285 } 1286 RB_GENERATE_STATIC(__pthread__alltree, __pthread_st, pt_alltree, pthread__cmp) 1287 #endif 1288 1289 /* Because getenv() wants to use locks. */ 1290 char * 1291 pthread__getenv(const char *name) 1292 { 1293 extern char *__findenv(const char *, int *); 1294 int off; 1295 1296 return __findenv(name, &off); 1297 } 1298 1299 pthread_mutex_t * 1300 pthread__hashlock(volatile const void *p) 1301 { 1302 uintptr_t v; 1303 1304 v = (uintptr_t)p; 1305 return &hashlocks[((v >> 9) ^ (v >> 3)) & (NHASHLOCK - 1)].mutex; 1306 } 1307 1308 int 1309 pthread__checkpri(int pri) 1310 { 1311 static int havepri; 1312 static long min, max; 1313 1314 if (!havepri) { 1315 min = sysconf(_SC_SCHED_PRI_MIN); 1316 max = sysconf(_SC_SCHED_PRI_MAX); 1317 havepri = 1; 1318 } 1319 return (pri < min || pri > max) ? EINVAL : 0; 1320 } 1321