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