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