1 /* 2 * z_Linux_util.cpp -- platform specific routines. 3 */ 4 5 //===----------------------------------------------------------------------===// 6 // 7 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 8 // See https://llvm.org/LICENSE.txt for license information. 9 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "kmp.h" 14 #include "kmp_affinity.h" 15 #include "kmp_i18n.h" 16 #include "kmp_io.h" 17 #include "kmp_itt.h" 18 #include "kmp_lock.h" 19 #include "kmp_stats.h" 20 #include "kmp_str.h" 21 #include "kmp_wait_release.h" 22 #include "kmp_wrapper_getpid.h" 23 24 #if !KMP_OS_DRAGONFLY && !KMP_OS_FREEBSD && !KMP_OS_NETBSD && !KMP_OS_OPENBSD 25 #include <alloca.h> 26 #endif 27 #include <math.h> // HUGE_VAL. 28 #if KMP_OS_LINUX 29 #include <semaphore.h> 30 #endif // KMP_OS_LINUX 31 #include <sys/resource.h> 32 #include <sys/syscall.h> 33 #include <sys/time.h> 34 #include <sys/times.h> 35 #include <unistd.h> 36 37 #if KMP_OS_LINUX 38 #include <sys/sysinfo.h> 39 #if KMP_USE_FUTEX 40 // We should really include <futex.h>, but that causes compatibility problems on 41 // different Linux* OS distributions that either require that you include (or 42 // break when you try to include) <pci/types.h>. Since all we need is the two 43 // macros below (which are part of the kernel ABI, so can't change) we just 44 // define the constants here and don't include <futex.h> 45 #ifndef FUTEX_WAIT 46 #define FUTEX_WAIT 0 47 #endif 48 #ifndef FUTEX_WAKE 49 #define FUTEX_WAKE 1 50 #endif 51 #endif 52 #elif KMP_OS_DARWIN 53 #include <mach/mach.h> 54 #include <sys/sysctl.h> 55 #elif KMP_OS_DRAGONFLY || KMP_OS_FREEBSD 56 #include <sys/types.h> 57 #include <sys/sysctl.h> 58 #include <sys/user.h> 59 #include <pthread_np.h> 60 #elif KMP_OS_NETBSD || KMP_OS_OPENBSD 61 #include <sys/types.h> 62 #include <sys/sysctl.h> 63 #endif 64 65 #include <ctype.h> 66 #include <dirent.h> 67 #include <fcntl.h> 68 69 #include "tsan_annotations.h" 70 71 struct kmp_sys_timer { 72 struct timespec start; 73 }; 74 75 // Convert timespec to nanoseconds. 76 #define TS2NS(timespec) \ 77 (((timespec).tv_sec * (long int)1e9) + (timespec).tv_nsec) 78 79 static struct kmp_sys_timer __kmp_sys_timer_data; 80 81 #if KMP_HANDLE_SIGNALS 82 typedef void (*sig_func_t)(int); 83 STATIC_EFI2_WORKAROUND struct sigaction __kmp_sighldrs[NSIG]; 84 static sigset_t __kmp_sigset; 85 #endif 86 87 static int __kmp_init_runtime = FALSE; 88 89 static int __kmp_fork_count = 0; 90 91 static pthread_condattr_t __kmp_suspend_cond_attr; 92 static pthread_mutexattr_t __kmp_suspend_mutex_attr; 93 94 static kmp_cond_align_t __kmp_wait_cv; 95 static kmp_mutex_align_t __kmp_wait_mx; 96 97 kmp_uint64 __kmp_ticks_per_msec = 1000000; 98 99 #ifdef DEBUG_SUSPEND 100 static void __kmp_print_cond(char *buffer, kmp_cond_align_t *cond) { 101 KMP_SNPRINTF(buffer, 128, "(cond (lock (%ld, %d)), (descr (%p)))", 102 cond->c_cond.__c_lock.__status, cond->c_cond.__c_lock.__spinlock, 103 cond->c_cond.__c_waiting); 104 } 105 #endif 106 107 #if ((KMP_OS_LINUX || KMP_OS_FREEBSD) && KMP_AFFINITY_SUPPORTED) 108 109 /* Affinity support */ 110 111 void __kmp_affinity_bind_thread(int which) { 112 KMP_ASSERT2(KMP_AFFINITY_CAPABLE(), 113 "Illegal set affinity operation when not capable"); 114 115 kmp_affin_mask_t *mask; 116 KMP_CPU_ALLOC_ON_STACK(mask); 117 KMP_CPU_ZERO(mask); 118 KMP_CPU_SET(which, mask); 119 __kmp_set_system_affinity(mask, TRUE); 120 KMP_CPU_FREE_FROM_STACK(mask); 121 } 122 123 /* Determine if we can access affinity functionality on this version of 124 * Linux* OS by checking __NR_sched_{get,set}affinity system calls, and set 125 * __kmp_affin_mask_size to the appropriate value (0 means not capable). */ 126 void __kmp_affinity_determine_capable(const char *env_var) { 127 // Check and see if the OS supports thread affinity. 128 129 #if KMP_OS_LINUX 130 #define KMP_CPU_SET_SIZE_LIMIT (1024 * 1024) 131 #define KMP_CPU_SET_TRY_SIZE CACHE_LINE 132 #elif KMP_OS_FREEBSD 133 #define KMP_CPU_SET_SIZE_LIMIT (sizeof(cpuset_t)) 134 #endif 135 136 #if KMP_OS_LINUX 137 long gCode; 138 unsigned char *buf; 139 buf = (unsigned char *)KMP_INTERNAL_MALLOC(KMP_CPU_SET_SIZE_LIMIT); 140 141 // If the syscall returns a suggestion for the size, 142 // then we don't have to search for an appropriate size. 143 gCode = syscall(__NR_sched_getaffinity, 0, KMP_CPU_SET_TRY_SIZE, buf); 144 KA_TRACE(30, ("__kmp_affinity_determine_capable: " 145 "initial getaffinity call returned %ld errno = %d\n", 146 gCode, errno)); 147 148 if (gCode < 0 && errno != EINVAL) { 149 // System call not supported 150 if (__kmp_affinity_verbose || 151 (__kmp_affinity_warnings && (__kmp_affinity_type != affinity_none) && 152 (__kmp_affinity_type != affinity_default) && 153 (__kmp_affinity_type != affinity_disabled))) { 154 int error = errno; 155 kmp_msg_t err_code = KMP_ERR(error); 156 __kmp_msg(kmp_ms_warning, KMP_MSG(GetAffSysCallNotSupported, env_var), 157 err_code, __kmp_msg_null); 158 if (__kmp_generate_warnings == kmp_warnings_off) { 159 __kmp_str_free(&err_code.str); 160 } 161 } 162 KMP_AFFINITY_DISABLE(); 163 KMP_INTERNAL_FREE(buf); 164 return; 165 } else if (gCode > 0) { 166 // The optimal situation: the OS returns the size of the buffer it expects. 167 KMP_AFFINITY_ENABLE(gCode); 168 KA_TRACE(10, ("__kmp_affinity_determine_capable: " 169 "affinity supported (mask size %d)\n", 170 (int)__kmp_affin_mask_size)); 171 KMP_INTERNAL_FREE(buf); 172 return; 173 } 174 175 // Call the getaffinity system call repeatedly with increasing set sizes 176 // until we succeed, or reach an upper bound on the search. 177 KA_TRACE(30, ("__kmp_affinity_determine_capable: " 178 "searching for proper set size\n")); 179 int size; 180 for (size = 1; size <= KMP_CPU_SET_SIZE_LIMIT; size *= 2) { 181 gCode = syscall(__NR_sched_getaffinity, 0, size, buf); 182 KA_TRACE(30, ("__kmp_affinity_determine_capable: " 183 "getaffinity for mask size %ld returned %ld errno = %d\n", 184 size, gCode, errno)); 185 186 if (gCode < 0) { 187 if (errno == ENOSYS) { 188 // We shouldn't get here 189 KA_TRACE(30, ("__kmp_affinity_determine_capable: " 190 "inconsistent OS call behavior: errno == ENOSYS for mask " 191 "size %d\n", 192 size)); 193 if (__kmp_affinity_verbose || 194 (__kmp_affinity_warnings && 195 (__kmp_affinity_type != affinity_none) && 196 (__kmp_affinity_type != affinity_default) && 197 (__kmp_affinity_type != affinity_disabled))) { 198 int error = errno; 199 kmp_msg_t err_code = KMP_ERR(error); 200 __kmp_msg(kmp_ms_warning, KMP_MSG(GetAffSysCallNotSupported, env_var), 201 err_code, __kmp_msg_null); 202 if (__kmp_generate_warnings == kmp_warnings_off) { 203 __kmp_str_free(&err_code.str); 204 } 205 } 206 KMP_AFFINITY_DISABLE(); 207 KMP_INTERNAL_FREE(buf); 208 return; 209 } 210 continue; 211 } 212 213 KMP_AFFINITY_ENABLE(gCode); 214 KA_TRACE(10, ("__kmp_affinity_determine_capable: " 215 "affinity supported (mask size %d)\n", 216 (int)__kmp_affin_mask_size)); 217 KMP_INTERNAL_FREE(buf); 218 return; 219 } 220 #elif KMP_OS_FREEBSD 221 long gCode; 222 unsigned char *buf; 223 buf = (unsigned char *)KMP_INTERNAL_MALLOC(KMP_CPU_SET_SIZE_LIMIT); 224 gCode = pthread_getaffinity_np(pthread_self(), KMP_CPU_SET_SIZE_LIMIT, 225 reinterpret_cast<cpuset_t *>(buf)); 226 KA_TRACE(30, ("__kmp_affinity_determine_capable: " 227 "initial getaffinity call returned %d errno = %d\n", 228 gCode, errno)); 229 if (gCode == 0) { 230 KMP_AFFINITY_ENABLE(KMP_CPU_SET_SIZE_LIMIT); 231 KA_TRACE(10, ("__kmp_affinity_determine_capable: " 232 "affinity supported (mask size %d)\n", 233 (int)__kmp_affin_mask_size)); 234 KMP_INTERNAL_FREE(buf); 235 return; 236 } 237 #endif 238 KMP_INTERNAL_FREE(buf); 239 240 // Affinity is not supported 241 KMP_AFFINITY_DISABLE(); 242 KA_TRACE(10, ("__kmp_affinity_determine_capable: " 243 "cannot determine mask size - affinity not supported\n")); 244 if (__kmp_affinity_verbose || 245 (__kmp_affinity_warnings && (__kmp_affinity_type != affinity_none) && 246 (__kmp_affinity_type != affinity_default) && 247 (__kmp_affinity_type != affinity_disabled))) { 248 KMP_WARNING(AffCantGetMaskSize, env_var); 249 } 250 } 251 252 #endif // KMP_OS_LINUX && KMP_AFFINITY_SUPPORTED 253 254 #if KMP_USE_FUTEX 255 256 int __kmp_futex_determine_capable() { 257 int loc = 0; 258 long rc = syscall(__NR_futex, &loc, FUTEX_WAKE, 1, NULL, NULL, 0); 259 int retval = (rc == 0) || (errno != ENOSYS); 260 261 KA_TRACE(10, 262 ("__kmp_futex_determine_capable: rc = %d errno = %d\n", rc, errno)); 263 KA_TRACE(10, ("__kmp_futex_determine_capable: futex syscall%s supported\n", 264 retval ? "" : " not")); 265 266 return retval; 267 } 268 269 #endif // KMP_USE_FUTEX 270 271 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) && (!KMP_ASM_INTRINS) 272 /* Only 32-bit "add-exchange" instruction on IA-32 architecture causes us to 273 use compare_and_store for these routines */ 274 275 kmp_int8 __kmp_test_then_or8(volatile kmp_int8 *p, kmp_int8 d) { 276 kmp_int8 old_value, new_value; 277 278 old_value = TCR_1(*p); 279 new_value = old_value | d; 280 281 while (!KMP_COMPARE_AND_STORE_REL8(p, old_value, new_value)) { 282 KMP_CPU_PAUSE(); 283 old_value = TCR_1(*p); 284 new_value = old_value | d; 285 } 286 return old_value; 287 } 288 289 kmp_int8 __kmp_test_then_and8(volatile kmp_int8 *p, kmp_int8 d) { 290 kmp_int8 old_value, new_value; 291 292 old_value = TCR_1(*p); 293 new_value = old_value & d; 294 295 while (!KMP_COMPARE_AND_STORE_REL8(p, old_value, new_value)) { 296 KMP_CPU_PAUSE(); 297 old_value = TCR_1(*p); 298 new_value = old_value & d; 299 } 300 return old_value; 301 } 302 303 kmp_uint32 __kmp_test_then_or32(volatile kmp_uint32 *p, kmp_uint32 d) { 304 kmp_uint32 old_value, new_value; 305 306 old_value = TCR_4(*p); 307 new_value = old_value | d; 308 309 while (!KMP_COMPARE_AND_STORE_REL32(p, old_value, new_value)) { 310 KMP_CPU_PAUSE(); 311 old_value = TCR_4(*p); 312 new_value = old_value | d; 313 } 314 return old_value; 315 } 316 317 kmp_uint32 __kmp_test_then_and32(volatile kmp_uint32 *p, kmp_uint32 d) { 318 kmp_uint32 old_value, new_value; 319 320 old_value = TCR_4(*p); 321 new_value = old_value & d; 322 323 while (!KMP_COMPARE_AND_STORE_REL32(p, old_value, new_value)) { 324 KMP_CPU_PAUSE(); 325 old_value = TCR_4(*p); 326 new_value = old_value & d; 327 } 328 return old_value; 329 } 330 331 #if KMP_ARCH_X86 332 kmp_int8 __kmp_test_then_add8(volatile kmp_int8 *p, kmp_int8 d) { 333 kmp_int8 old_value, new_value; 334 335 old_value = TCR_1(*p); 336 new_value = old_value + d; 337 338 while (!KMP_COMPARE_AND_STORE_REL8(p, old_value, new_value)) { 339 KMP_CPU_PAUSE(); 340 old_value = TCR_1(*p); 341 new_value = old_value + d; 342 } 343 return old_value; 344 } 345 346 kmp_int64 __kmp_test_then_add64(volatile kmp_int64 *p, kmp_int64 d) { 347 kmp_int64 old_value, new_value; 348 349 old_value = TCR_8(*p); 350 new_value = old_value + d; 351 352 while (!KMP_COMPARE_AND_STORE_REL64(p, old_value, new_value)) { 353 KMP_CPU_PAUSE(); 354 old_value = TCR_8(*p); 355 new_value = old_value + d; 356 } 357 return old_value; 358 } 359 #endif /* KMP_ARCH_X86 */ 360 361 kmp_uint64 __kmp_test_then_or64(volatile kmp_uint64 *p, kmp_uint64 d) { 362 kmp_uint64 old_value, new_value; 363 364 old_value = TCR_8(*p); 365 new_value = old_value | d; 366 while (!KMP_COMPARE_AND_STORE_REL64(p, old_value, new_value)) { 367 KMP_CPU_PAUSE(); 368 old_value = TCR_8(*p); 369 new_value = old_value | d; 370 } 371 return old_value; 372 } 373 374 kmp_uint64 __kmp_test_then_and64(volatile kmp_uint64 *p, kmp_uint64 d) { 375 kmp_uint64 old_value, new_value; 376 377 old_value = TCR_8(*p); 378 new_value = old_value & d; 379 while (!KMP_COMPARE_AND_STORE_REL64(p, old_value, new_value)) { 380 KMP_CPU_PAUSE(); 381 old_value = TCR_8(*p); 382 new_value = old_value & d; 383 } 384 return old_value; 385 } 386 387 #endif /* (KMP_ARCH_X86 || KMP_ARCH_X86_64) && (! KMP_ASM_INTRINS) */ 388 389 void __kmp_terminate_thread(int gtid) { 390 int status; 391 kmp_info_t *th = __kmp_threads[gtid]; 392 393 if (!th) 394 return; 395 396 #ifdef KMP_CANCEL_THREADS 397 KA_TRACE(10, ("__kmp_terminate_thread: kill (%d)\n", gtid)); 398 status = pthread_cancel(th->th.th_info.ds.ds_thread); 399 if (status != 0 && status != ESRCH) { 400 __kmp_fatal(KMP_MSG(CantTerminateWorkerThread), KMP_ERR(status), 401 __kmp_msg_null); 402 } 403 #endif 404 KMP_YIELD(TRUE); 405 } // 406 407 /* Set thread stack info according to values returned by pthread_getattr_np(). 408 If values are unreasonable, assume call failed and use incremental stack 409 refinement method instead. Returns TRUE if the stack parameters could be 410 determined exactly, FALSE if incremental refinement is necessary. */ 411 static kmp_int32 __kmp_set_stack_info(int gtid, kmp_info_t *th) { 412 int stack_data; 413 #if KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || \ 414 KMP_OS_HURD 415 pthread_attr_t attr; 416 int status; 417 size_t size = 0; 418 void *addr = 0; 419 420 /* Always do incremental stack refinement for ubermaster threads since the 421 initial thread stack range can be reduced by sibling thread creation so 422 pthread_attr_getstack may cause thread gtid aliasing */ 423 if (!KMP_UBER_GTID(gtid)) { 424 425 /* Fetch the real thread attributes */ 426 status = pthread_attr_init(&attr); 427 KMP_CHECK_SYSFAIL("pthread_attr_init", status); 428 #if KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD 429 status = pthread_attr_get_np(pthread_self(), &attr); 430 KMP_CHECK_SYSFAIL("pthread_attr_get_np", status); 431 #else 432 status = pthread_getattr_np(pthread_self(), &attr); 433 KMP_CHECK_SYSFAIL("pthread_getattr_np", status); 434 #endif 435 status = pthread_attr_getstack(&attr, &addr, &size); 436 KMP_CHECK_SYSFAIL("pthread_attr_getstack", status); 437 KA_TRACE(60, 438 ("__kmp_set_stack_info: T#%d pthread_attr_getstack returned size:" 439 " %lu, low addr: %p\n", 440 gtid, size, addr)); 441 status = pthread_attr_destroy(&attr); 442 KMP_CHECK_SYSFAIL("pthread_attr_destroy", status); 443 } 444 445 if (size != 0 && addr != 0) { // was stack parameter determination successful? 446 /* Store the correct base and size */ 447 TCW_PTR(th->th.th_info.ds.ds_stackbase, (((char *)addr) + size)); 448 TCW_PTR(th->th.th_info.ds.ds_stacksize, size); 449 TCW_4(th->th.th_info.ds.ds_stackgrow, FALSE); 450 return TRUE; 451 } 452 #endif /* KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD \ 453 || KMP_OS_HURD */ 454 /* Use incremental refinement starting from initial conservative estimate */ 455 TCW_PTR(th->th.th_info.ds.ds_stacksize, 0); 456 TCW_PTR(th->th.th_info.ds.ds_stackbase, &stack_data); 457 TCW_4(th->th.th_info.ds.ds_stackgrow, TRUE); 458 return FALSE; 459 } 460 461 static void *__kmp_launch_worker(void *thr) { 462 int status, old_type, old_state; 463 #ifdef KMP_BLOCK_SIGNALS 464 sigset_t new_set, old_set; 465 #endif /* KMP_BLOCK_SIGNALS */ 466 void *exit_val; 467 #if KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || \ 468 KMP_OS_OPENBSD || KMP_OS_HURD 469 void *volatile padding = 0; 470 #endif 471 int gtid; 472 473 gtid = ((kmp_info_t *)thr)->th.th_info.ds.ds_gtid; 474 __kmp_gtid_set_specific(gtid); 475 #ifdef KMP_TDATA_GTID 476 __kmp_gtid = gtid; 477 #endif 478 #if KMP_STATS_ENABLED 479 // set thread local index to point to thread-specific stats 480 __kmp_stats_thread_ptr = ((kmp_info_t *)thr)->th.th_stats; 481 __kmp_stats_thread_ptr->startLife(); 482 KMP_SET_THREAD_STATE(IDLE); 483 KMP_INIT_PARTITIONED_TIMERS(OMP_idle); 484 #endif 485 486 #if USE_ITT_BUILD 487 __kmp_itt_thread_name(gtid); 488 #endif /* USE_ITT_BUILD */ 489 490 #if KMP_AFFINITY_SUPPORTED 491 __kmp_affinity_set_init_mask(gtid, FALSE); 492 #endif 493 494 #ifdef KMP_CANCEL_THREADS 495 status = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type); 496 KMP_CHECK_SYSFAIL("pthread_setcanceltype", status); 497 // josh todo: isn't PTHREAD_CANCEL_ENABLE default for newly-created threads? 498 status = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state); 499 KMP_CHECK_SYSFAIL("pthread_setcancelstate", status); 500 #endif 501 502 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 503 // Set FP control regs to be a copy of the parallel initialization thread's. 504 __kmp_clear_x87_fpu_status_word(); 505 __kmp_load_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word); 506 __kmp_load_mxcsr(&__kmp_init_mxcsr); 507 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ 508 509 #ifdef KMP_BLOCK_SIGNALS 510 status = sigfillset(&new_set); 511 KMP_CHECK_SYSFAIL_ERRNO("sigfillset", status); 512 status = pthread_sigmask(SIG_BLOCK, &new_set, &old_set); 513 KMP_CHECK_SYSFAIL("pthread_sigmask", status); 514 #endif /* KMP_BLOCK_SIGNALS */ 515 516 #if KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || \ 517 KMP_OS_OPENBSD 518 if (__kmp_stkoffset > 0 && gtid > 0) { 519 padding = KMP_ALLOCA(gtid * __kmp_stkoffset); 520 (void)padding; 521 } 522 #endif 523 524 KMP_MB(); 525 __kmp_set_stack_info(gtid, (kmp_info_t *)thr); 526 527 __kmp_check_stack_overlap((kmp_info_t *)thr); 528 529 exit_val = __kmp_launch_thread((kmp_info_t *)thr); 530 531 #ifdef KMP_BLOCK_SIGNALS 532 status = pthread_sigmask(SIG_SETMASK, &old_set, NULL); 533 KMP_CHECK_SYSFAIL("pthread_sigmask", status); 534 #endif /* KMP_BLOCK_SIGNALS */ 535 536 return exit_val; 537 } 538 539 #if KMP_USE_MONITOR 540 /* The monitor thread controls all of the threads in the complex */ 541 542 static void *__kmp_launch_monitor(void *thr) { 543 int status, old_type, old_state; 544 #ifdef KMP_BLOCK_SIGNALS 545 sigset_t new_set; 546 #endif /* KMP_BLOCK_SIGNALS */ 547 struct timespec interval; 548 549 KMP_MB(); /* Flush all pending memory write invalidates. */ 550 551 KA_TRACE(10, ("__kmp_launch_monitor: #1 launched\n")); 552 553 /* register us as the monitor thread */ 554 __kmp_gtid_set_specific(KMP_GTID_MONITOR); 555 #ifdef KMP_TDATA_GTID 556 __kmp_gtid = KMP_GTID_MONITOR; 557 #endif 558 559 KMP_MB(); 560 561 #if USE_ITT_BUILD 562 // Instruct Intel(R) Threading Tools to ignore monitor thread. 563 __kmp_itt_thread_ignore(); 564 #endif /* USE_ITT_BUILD */ 565 566 __kmp_set_stack_info(((kmp_info_t *)thr)->th.th_info.ds.ds_gtid, 567 (kmp_info_t *)thr); 568 569 __kmp_check_stack_overlap((kmp_info_t *)thr); 570 571 #ifdef KMP_CANCEL_THREADS 572 status = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type); 573 KMP_CHECK_SYSFAIL("pthread_setcanceltype", status); 574 // josh todo: isn't PTHREAD_CANCEL_ENABLE default for newly-created threads? 575 status = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state); 576 KMP_CHECK_SYSFAIL("pthread_setcancelstate", status); 577 #endif 578 579 #if KMP_REAL_TIME_FIX 580 // This is a potential fix which allows application with real-time scheduling 581 // policy work. However, decision about the fix is not made yet, so it is 582 // disabled by default. 583 { // Are program started with real-time scheduling policy? 584 int sched = sched_getscheduler(0); 585 if (sched == SCHED_FIFO || sched == SCHED_RR) { 586 // Yes, we are a part of real-time application. Try to increase the 587 // priority of the monitor. 588 struct sched_param param; 589 int max_priority = sched_get_priority_max(sched); 590 int rc; 591 KMP_WARNING(RealTimeSchedNotSupported); 592 sched_getparam(0, ¶m); 593 if (param.sched_priority < max_priority) { 594 param.sched_priority += 1; 595 rc = sched_setscheduler(0, sched, ¶m); 596 if (rc != 0) { 597 int error = errno; 598 kmp_msg_t err_code = KMP_ERR(error); 599 __kmp_msg(kmp_ms_warning, KMP_MSG(CantChangeMonitorPriority), 600 err_code, KMP_MSG(MonitorWillStarve), __kmp_msg_null); 601 if (__kmp_generate_warnings == kmp_warnings_off) { 602 __kmp_str_free(&err_code.str); 603 } 604 } 605 } else { 606 // We cannot abort here, because number of CPUs may be enough for all 607 // the threads, including the monitor thread, so application could 608 // potentially work... 609 __kmp_msg(kmp_ms_warning, KMP_MSG(RunningAtMaxPriority), 610 KMP_MSG(MonitorWillStarve), KMP_HNT(RunningAtMaxPriority), 611 __kmp_msg_null); 612 } 613 } 614 // AC: free thread that waits for monitor started 615 TCW_4(__kmp_global.g.g_time.dt.t_value, 0); 616 } 617 #endif // KMP_REAL_TIME_FIX 618 619 KMP_MB(); /* Flush all pending memory write invalidates. */ 620 621 if (__kmp_monitor_wakeups == 1) { 622 interval.tv_sec = 1; 623 interval.tv_nsec = 0; 624 } else { 625 interval.tv_sec = 0; 626 interval.tv_nsec = (KMP_NSEC_PER_SEC / __kmp_monitor_wakeups); 627 } 628 629 KA_TRACE(10, ("__kmp_launch_monitor: #2 monitor\n")); 630 631 while (!TCR_4(__kmp_global.g.g_done)) { 632 struct timespec now; 633 struct timeval tval; 634 635 /* This thread monitors the state of the system */ 636 637 KA_TRACE(15, ("__kmp_launch_monitor: update\n")); 638 639 status = gettimeofday(&tval, NULL); 640 KMP_CHECK_SYSFAIL_ERRNO("gettimeofday", status); 641 TIMEVAL_TO_TIMESPEC(&tval, &now); 642 643 now.tv_sec += interval.tv_sec; 644 now.tv_nsec += interval.tv_nsec; 645 646 if (now.tv_nsec >= KMP_NSEC_PER_SEC) { 647 now.tv_sec += 1; 648 now.tv_nsec -= KMP_NSEC_PER_SEC; 649 } 650 651 status = pthread_mutex_lock(&__kmp_wait_mx.m_mutex); 652 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 653 // AC: the monitor should not fall asleep if g_done has been set 654 if (!TCR_4(__kmp_global.g.g_done)) { // check once more under mutex 655 status = pthread_cond_timedwait(&__kmp_wait_cv.c_cond, 656 &__kmp_wait_mx.m_mutex, &now); 657 if (status != 0) { 658 if (status != ETIMEDOUT && status != EINTR) { 659 KMP_SYSFAIL("pthread_cond_timedwait", status); 660 } 661 } 662 } 663 status = pthread_mutex_unlock(&__kmp_wait_mx.m_mutex); 664 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 665 666 TCW_4(__kmp_global.g.g_time.dt.t_value, 667 TCR_4(__kmp_global.g.g_time.dt.t_value) + 1); 668 669 KMP_MB(); /* Flush all pending memory write invalidates. */ 670 } 671 672 KA_TRACE(10, ("__kmp_launch_monitor: #3 cleanup\n")); 673 674 #ifdef KMP_BLOCK_SIGNALS 675 status = sigfillset(&new_set); 676 KMP_CHECK_SYSFAIL_ERRNO("sigfillset", status); 677 status = pthread_sigmask(SIG_UNBLOCK, &new_set, NULL); 678 KMP_CHECK_SYSFAIL("pthread_sigmask", status); 679 #endif /* KMP_BLOCK_SIGNALS */ 680 681 KA_TRACE(10, ("__kmp_launch_monitor: #4 finished\n")); 682 683 if (__kmp_global.g.g_abort != 0) { 684 /* now we need to terminate the worker threads */ 685 /* the value of t_abort is the signal we caught */ 686 687 int gtid; 688 689 KA_TRACE(10, ("__kmp_launch_monitor: #5 terminate sig=%d\n", 690 __kmp_global.g.g_abort)); 691 692 /* terminate the OpenMP worker threads */ 693 /* TODO this is not valid for sibling threads!! 694 * the uber master might not be 0 anymore.. */ 695 for (gtid = 1; gtid < __kmp_threads_capacity; ++gtid) 696 __kmp_terminate_thread(gtid); 697 698 __kmp_cleanup(); 699 700 KA_TRACE(10, ("__kmp_launch_monitor: #6 raise sig=%d\n", 701 __kmp_global.g.g_abort)); 702 703 if (__kmp_global.g.g_abort > 0) 704 raise(__kmp_global.g.g_abort); 705 } 706 707 KA_TRACE(10, ("__kmp_launch_monitor: #7 exit\n")); 708 709 return thr; 710 } 711 #endif // KMP_USE_MONITOR 712 713 void __kmp_create_worker(int gtid, kmp_info_t *th, size_t stack_size) { 714 pthread_t handle; 715 pthread_attr_t thread_attr; 716 int status; 717 718 th->th.th_info.ds.ds_gtid = gtid; 719 720 #if KMP_STATS_ENABLED 721 // sets up worker thread stats 722 __kmp_acquire_tas_lock(&__kmp_stats_lock, gtid); 723 724 // th->th.th_stats is used to transfer thread-specific stats-pointer to 725 // __kmp_launch_worker. So when thread is created (goes into 726 // __kmp_launch_worker) it will set its thread local pointer to 727 // th->th.th_stats 728 if (!KMP_UBER_GTID(gtid)) { 729 th->th.th_stats = __kmp_stats_list->push_back(gtid); 730 } else { 731 // For root threads, __kmp_stats_thread_ptr is set in __kmp_register_root(), 732 // so set the th->th.th_stats field to it. 733 th->th.th_stats = __kmp_stats_thread_ptr; 734 } 735 __kmp_release_tas_lock(&__kmp_stats_lock, gtid); 736 737 #endif // KMP_STATS_ENABLED 738 739 if (KMP_UBER_GTID(gtid)) { 740 KA_TRACE(10, ("__kmp_create_worker: uber thread (%d)\n", gtid)); 741 th->th.th_info.ds.ds_thread = pthread_self(); 742 __kmp_set_stack_info(gtid, th); 743 __kmp_check_stack_overlap(th); 744 return; 745 } 746 747 KA_TRACE(10, ("__kmp_create_worker: try to create thread (%d)\n", gtid)); 748 749 KMP_MB(); /* Flush all pending memory write invalidates. */ 750 751 #ifdef KMP_THREAD_ATTR 752 status = pthread_attr_init(&thread_attr); 753 if (status != 0) { 754 __kmp_fatal(KMP_MSG(CantInitThreadAttrs), KMP_ERR(status), __kmp_msg_null); 755 } 756 status = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); 757 if (status != 0) { 758 __kmp_fatal(KMP_MSG(CantSetWorkerState), KMP_ERR(status), __kmp_msg_null); 759 } 760 761 /* Set stack size for this thread now. 762 The multiple of 2 is there because on some machines, requesting an unusual 763 stacksize causes the thread to have an offset before the dummy alloca() 764 takes place to create the offset. Since we want the user to have a 765 sufficient stacksize AND support a stack offset, we alloca() twice the 766 offset so that the upcoming alloca() does not eliminate any premade offset, 767 and also gives the user the stack space they requested for all threads */ 768 stack_size += gtid * __kmp_stkoffset * 2; 769 770 #if defined(__ANDROID__) && __ANDROID_API__ < 19 771 // Round the stack size to a multiple of the page size. Older versions of 772 // Android (until KitKat) would fail pthread_attr_setstacksize with EINVAL 773 // if the stack size was not a multiple of the page size. 774 stack_size = (stack_size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); 775 #endif 776 777 KA_TRACE(10, ("__kmp_create_worker: T#%d, default stacksize = %lu bytes, " 778 "__kmp_stksize = %lu bytes, final stacksize = %lu bytes\n", 779 gtid, KMP_DEFAULT_STKSIZE, __kmp_stksize, stack_size)); 780 781 #ifdef _POSIX_THREAD_ATTR_STACKSIZE 782 status = pthread_attr_setstacksize(&thread_attr, stack_size); 783 #ifdef KMP_BACKUP_STKSIZE 784 if (status != 0) { 785 if (!__kmp_env_stksize) { 786 stack_size = KMP_BACKUP_STKSIZE + gtid * __kmp_stkoffset; 787 __kmp_stksize = KMP_BACKUP_STKSIZE; 788 KA_TRACE(10, ("__kmp_create_worker: T#%d, default stacksize = %lu bytes, " 789 "__kmp_stksize = %lu bytes, (backup) final stacksize = %lu " 790 "bytes\n", 791 gtid, KMP_DEFAULT_STKSIZE, __kmp_stksize, stack_size)); 792 status = pthread_attr_setstacksize(&thread_attr, stack_size); 793 } 794 } 795 #endif /* KMP_BACKUP_STKSIZE */ 796 if (status != 0) { 797 __kmp_fatal(KMP_MSG(CantSetWorkerStackSize, stack_size), KMP_ERR(status), 798 KMP_HNT(ChangeWorkerStackSize), __kmp_msg_null); 799 } 800 #endif /* _POSIX_THREAD_ATTR_STACKSIZE */ 801 802 #endif /* KMP_THREAD_ATTR */ 803 804 status = 805 pthread_create(&handle, &thread_attr, __kmp_launch_worker, (void *)th); 806 if (status != 0 || !handle) { // ??? Why do we check handle?? 807 #ifdef _POSIX_THREAD_ATTR_STACKSIZE 808 if (status == EINVAL) { 809 __kmp_fatal(KMP_MSG(CantSetWorkerStackSize, stack_size), KMP_ERR(status), 810 KMP_HNT(IncreaseWorkerStackSize), __kmp_msg_null); 811 } 812 if (status == ENOMEM) { 813 __kmp_fatal(KMP_MSG(CantSetWorkerStackSize, stack_size), KMP_ERR(status), 814 KMP_HNT(DecreaseWorkerStackSize), __kmp_msg_null); 815 } 816 #endif /* _POSIX_THREAD_ATTR_STACKSIZE */ 817 if (status == EAGAIN) { 818 __kmp_fatal(KMP_MSG(NoResourcesForWorkerThread), KMP_ERR(status), 819 KMP_HNT(Decrease_NUM_THREADS), __kmp_msg_null); 820 } 821 KMP_SYSFAIL("pthread_create", status); 822 } 823 824 th->th.th_info.ds.ds_thread = handle; 825 826 #ifdef KMP_THREAD_ATTR 827 status = pthread_attr_destroy(&thread_attr); 828 if (status) { 829 kmp_msg_t err_code = KMP_ERR(status); 830 __kmp_msg(kmp_ms_warning, KMP_MSG(CantDestroyThreadAttrs), err_code, 831 __kmp_msg_null); 832 if (__kmp_generate_warnings == kmp_warnings_off) { 833 __kmp_str_free(&err_code.str); 834 } 835 } 836 #endif /* KMP_THREAD_ATTR */ 837 838 KMP_MB(); /* Flush all pending memory write invalidates. */ 839 840 KA_TRACE(10, ("__kmp_create_worker: done creating thread (%d)\n", gtid)); 841 842 } // __kmp_create_worker 843 844 #if KMP_USE_MONITOR 845 void __kmp_create_monitor(kmp_info_t *th) { 846 pthread_t handle; 847 pthread_attr_t thread_attr; 848 size_t size; 849 int status; 850 int auto_adj_size = FALSE; 851 852 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) { 853 // We don't need monitor thread in case of MAX_BLOCKTIME 854 KA_TRACE(10, ("__kmp_create_monitor: skipping monitor thread because of " 855 "MAX blocktime\n")); 856 th->th.th_info.ds.ds_tid = 0; // this makes reap_monitor no-op 857 th->th.th_info.ds.ds_gtid = 0; 858 return; 859 } 860 KA_TRACE(10, ("__kmp_create_monitor: try to create monitor\n")); 861 862 KMP_MB(); /* Flush all pending memory write invalidates. */ 863 864 th->th.th_info.ds.ds_tid = KMP_GTID_MONITOR; 865 th->th.th_info.ds.ds_gtid = KMP_GTID_MONITOR; 866 #if KMP_REAL_TIME_FIX 867 TCW_4(__kmp_global.g.g_time.dt.t_value, 868 -1); // Will use it for synchronization a bit later. 869 #else 870 TCW_4(__kmp_global.g.g_time.dt.t_value, 0); 871 #endif // KMP_REAL_TIME_FIX 872 873 #ifdef KMP_THREAD_ATTR 874 if (__kmp_monitor_stksize == 0) { 875 __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE; 876 auto_adj_size = TRUE; 877 } 878 status = pthread_attr_init(&thread_attr); 879 if (status != 0) { 880 __kmp_fatal(KMP_MSG(CantInitThreadAttrs), KMP_ERR(status), __kmp_msg_null); 881 } 882 status = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); 883 if (status != 0) { 884 __kmp_fatal(KMP_MSG(CantSetMonitorState), KMP_ERR(status), __kmp_msg_null); 885 } 886 887 #ifdef _POSIX_THREAD_ATTR_STACKSIZE 888 status = pthread_attr_getstacksize(&thread_attr, &size); 889 KMP_CHECK_SYSFAIL("pthread_attr_getstacksize", status); 890 #else 891 size = __kmp_sys_min_stksize; 892 #endif /* _POSIX_THREAD_ATTR_STACKSIZE */ 893 #endif /* KMP_THREAD_ATTR */ 894 895 if (__kmp_monitor_stksize == 0) { 896 __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE; 897 } 898 if (__kmp_monitor_stksize < __kmp_sys_min_stksize) { 899 __kmp_monitor_stksize = __kmp_sys_min_stksize; 900 } 901 902 KA_TRACE(10, ("__kmp_create_monitor: default stacksize = %lu bytes," 903 "requested stacksize = %lu bytes\n", 904 size, __kmp_monitor_stksize)); 905 906 retry: 907 908 /* Set stack size for this thread now. */ 909 #ifdef _POSIX_THREAD_ATTR_STACKSIZE 910 KA_TRACE(10, ("__kmp_create_monitor: setting stacksize = %lu bytes,", 911 __kmp_monitor_stksize)); 912 status = pthread_attr_setstacksize(&thread_attr, __kmp_monitor_stksize); 913 if (status != 0) { 914 if (auto_adj_size) { 915 __kmp_monitor_stksize *= 2; 916 goto retry; 917 } 918 kmp_msg_t err_code = KMP_ERR(status); 919 __kmp_msg(kmp_ms_warning, // should this be fatal? BB 920 KMP_MSG(CantSetMonitorStackSize, (long int)__kmp_monitor_stksize), 921 err_code, KMP_HNT(ChangeMonitorStackSize), __kmp_msg_null); 922 if (__kmp_generate_warnings == kmp_warnings_off) { 923 __kmp_str_free(&err_code.str); 924 } 925 } 926 #endif /* _POSIX_THREAD_ATTR_STACKSIZE */ 927 928 status = 929 pthread_create(&handle, &thread_attr, __kmp_launch_monitor, (void *)th); 930 931 if (status != 0) { 932 #ifdef _POSIX_THREAD_ATTR_STACKSIZE 933 if (status == EINVAL) { 934 if (auto_adj_size && (__kmp_monitor_stksize < (size_t)0x40000000)) { 935 __kmp_monitor_stksize *= 2; 936 goto retry; 937 } 938 __kmp_fatal(KMP_MSG(CantSetMonitorStackSize, __kmp_monitor_stksize), 939 KMP_ERR(status), KMP_HNT(IncreaseMonitorStackSize), 940 __kmp_msg_null); 941 } 942 if (status == ENOMEM) { 943 __kmp_fatal(KMP_MSG(CantSetMonitorStackSize, __kmp_monitor_stksize), 944 KMP_ERR(status), KMP_HNT(DecreaseMonitorStackSize), 945 __kmp_msg_null); 946 } 947 #endif /* _POSIX_THREAD_ATTR_STACKSIZE */ 948 if (status == EAGAIN) { 949 __kmp_fatal(KMP_MSG(NoResourcesForMonitorThread), KMP_ERR(status), 950 KMP_HNT(DecreaseNumberOfThreadsInUse), __kmp_msg_null); 951 } 952 KMP_SYSFAIL("pthread_create", status); 953 } 954 955 th->th.th_info.ds.ds_thread = handle; 956 957 #if KMP_REAL_TIME_FIX 958 // Wait for the monitor thread is really started and set its *priority*. 959 KMP_DEBUG_ASSERT(sizeof(kmp_uint32) == 960 sizeof(__kmp_global.g.g_time.dt.t_value)); 961 __kmp_wait_4((kmp_uint32 volatile *)&__kmp_global.g.g_time.dt.t_value, -1, 962 &__kmp_neq_4, NULL); 963 #endif // KMP_REAL_TIME_FIX 964 965 #ifdef KMP_THREAD_ATTR 966 status = pthread_attr_destroy(&thread_attr); 967 if (status != 0) { 968 kmp_msg_t err_code = KMP_ERR(status); 969 __kmp_msg(kmp_ms_warning, KMP_MSG(CantDestroyThreadAttrs), err_code, 970 __kmp_msg_null); 971 if (__kmp_generate_warnings == kmp_warnings_off) { 972 __kmp_str_free(&err_code.str); 973 } 974 } 975 #endif 976 977 KMP_MB(); /* Flush all pending memory write invalidates. */ 978 979 KA_TRACE(10, ("__kmp_create_monitor: monitor created %#.8lx\n", 980 th->th.th_info.ds.ds_thread)); 981 982 } // __kmp_create_monitor 983 #endif // KMP_USE_MONITOR 984 985 void __kmp_exit_thread(int exit_status) { 986 pthread_exit((void *)(intptr_t)exit_status); 987 } // __kmp_exit_thread 988 989 #if KMP_USE_MONITOR 990 void __kmp_resume_monitor(); 991 992 void __kmp_reap_monitor(kmp_info_t *th) { 993 int status; 994 void *exit_val; 995 996 KA_TRACE(10, ("__kmp_reap_monitor: try to reap monitor thread with handle" 997 " %#.8lx\n", 998 th->th.th_info.ds.ds_thread)); 999 1000 // If monitor has been created, its tid and gtid should be KMP_GTID_MONITOR. 1001 // If both tid and gtid are 0, it means the monitor did not ever start. 1002 // If both tid and gtid are KMP_GTID_DNE, the monitor has been shut down. 1003 KMP_DEBUG_ASSERT(th->th.th_info.ds.ds_tid == th->th.th_info.ds.ds_gtid); 1004 if (th->th.th_info.ds.ds_gtid != KMP_GTID_MONITOR) { 1005 KA_TRACE(10, ("__kmp_reap_monitor: monitor did not start, returning\n")); 1006 return; 1007 } 1008 1009 KMP_MB(); /* Flush all pending memory write invalidates. */ 1010 1011 /* First, check to see whether the monitor thread exists to wake it up. This 1012 is to avoid performance problem when the monitor sleeps during 1013 blocktime-size interval */ 1014 1015 status = pthread_kill(th->th.th_info.ds.ds_thread, 0); 1016 if (status != ESRCH) { 1017 __kmp_resume_monitor(); // Wake up the monitor thread 1018 } 1019 KA_TRACE(10, ("__kmp_reap_monitor: try to join with monitor\n")); 1020 status = pthread_join(th->th.th_info.ds.ds_thread, &exit_val); 1021 if (exit_val != th) { 1022 __kmp_fatal(KMP_MSG(ReapMonitorError), KMP_ERR(status), __kmp_msg_null); 1023 } 1024 1025 th->th.th_info.ds.ds_tid = KMP_GTID_DNE; 1026 th->th.th_info.ds.ds_gtid = KMP_GTID_DNE; 1027 1028 KA_TRACE(10, ("__kmp_reap_monitor: done reaping monitor thread with handle" 1029 " %#.8lx\n", 1030 th->th.th_info.ds.ds_thread)); 1031 1032 KMP_MB(); /* Flush all pending memory write invalidates. */ 1033 } 1034 #endif // KMP_USE_MONITOR 1035 1036 void __kmp_reap_worker(kmp_info_t *th) { 1037 int status; 1038 void *exit_val; 1039 1040 KMP_MB(); /* Flush all pending memory write invalidates. */ 1041 1042 KA_TRACE( 1043 10, ("__kmp_reap_worker: try to reap T#%d\n", th->th.th_info.ds.ds_gtid)); 1044 1045 status = pthread_join(th->th.th_info.ds.ds_thread, &exit_val); 1046 #ifdef KMP_DEBUG 1047 /* Don't expose these to the user until we understand when they trigger */ 1048 if (status != 0) { 1049 __kmp_fatal(KMP_MSG(ReapWorkerError), KMP_ERR(status), __kmp_msg_null); 1050 } 1051 if (exit_val != th) { 1052 KA_TRACE(10, ("__kmp_reap_worker: worker T#%d did not reap properly, " 1053 "exit_val = %p\n", 1054 th->th.th_info.ds.ds_gtid, exit_val)); 1055 } 1056 #endif /* KMP_DEBUG */ 1057 1058 KA_TRACE(10, ("__kmp_reap_worker: done reaping T#%d\n", 1059 th->th.th_info.ds.ds_gtid)); 1060 1061 KMP_MB(); /* Flush all pending memory write invalidates. */ 1062 } 1063 1064 #if KMP_HANDLE_SIGNALS 1065 1066 static void __kmp_null_handler(int signo) { 1067 // Do nothing, for doing SIG_IGN-type actions. 1068 } // __kmp_null_handler 1069 1070 static void __kmp_team_handler(int signo) { 1071 if (__kmp_global.g.g_abort == 0) { 1072 /* Stage 1 signal handler, let's shut down all of the threads */ 1073 #ifdef KMP_DEBUG 1074 __kmp_debug_printf("__kmp_team_handler: caught signal = %d\n", signo); 1075 #endif 1076 switch (signo) { 1077 case SIGHUP: 1078 case SIGINT: 1079 case SIGQUIT: 1080 case SIGILL: 1081 case SIGABRT: 1082 case SIGFPE: 1083 case SIGBUS: 1084 case SIGSEGV: 1085 #ifdef SIGSYS 1086 case SIGSYS: 1087 #endif 1088 case SIGTERM: 1089 if (__kmp_debug_buf) { 1090 __kmp_dump_debug_buffer(); 1091 } 1092 __kmp_unregister_library(); // cleanup shared memory 1093 KMP_MB(); // Flush all pending memory write invalidates. 1094 TCW_4(__kmp_global.g.g_abort, signo); 1095 KMP_MB(); // Flush all pending memory write invalidates. 1096 TCW_4(__kmp_global.g.g_done, TRUE); 1097 KMP_MB(); // Flush all pending memory write invalidates. 1098 break; 1099 default: 1100 #ifdef KMP_DEBUG 1101 __kmp_debug_printf("__kmp_team_handler: unknown signal type"); 1102 #endif 1103 break; 1104 } 1105 } 1106 } // __kmp_team_handler 1107 1108 static void __kmp_sigaction(int signum, const struct sigaction *act, 1109 struct sigaction *oldact) { 1110 int rc = sigaction(signum, act, oldact); 1111 KMP_CHECK_SYSFAIL_ERRNO("sigaction", rc); 1112 } 1113 1114 static void __kmp_install_one_handler(int sig, sig_func_t handler_func, 1115 int parallel_init) { 1116 KMP_MB(); // Flush all pending memory write invalidates. 1117 KB_TRACE(60, 1118 ("__kmp_install_one_handler( %d, ..., %d )\n", sig, parallel_init)); 1119 if (parallel_init) { 1120 struct sigaction new_action; 1121 struct sigaction old_action; 1122 new_action.sa_handler = handler_func; 1123 new_action.sa_flags = 0; 1124 sigfillset(&new_action.sa_mask); 1125 __kmp_sigaction(sig, &new_action, &old_action); 1126 if (old_action.sa_handler == __kmp_sighldrs[sig].sa_handler) { 1127 sigaddset(&__kmp_sigset, sig); 1128 } else { 1129 // Restore/keep user's handler if one previously installed. 1130 __kmp_sigaction(sig, &old_action, NULL); 1131 } 1132 } else { 1133 // Save initial/system signal handlers to see if user handlers installed. 1134 __kmp_sigaction(sig, NULL, &__kmp_sighldrs[sig]); 1135 } 1136 KMP_MB(); // Flush all pending memory write invalidates. 1137 } // __kmp_install_one_handler 1138 1139 static void __kmp_remove_one_handler(int sig) { 1140 KB_TRACE(60, ("__kmp_remove_one_handler( %d )\n", sig)); 1141 if (sigismember(&__kmp_sigset, sig)) { 1142 struct sigaction old; 1143 KMP_MB(); // Flush all pending memory write invalidates. 1144 __kmp_sigaction(sig, &__kmp_sighldrs[sig], &old); 1145 if ((old.sa_handler != __kmp_team_handler) && 1146 (old.sa_handler != __kmp_null_handler)) { 1147 // Restore the users signal handler. 1148 KB_TRACE(10, ("__kmp_remove_one_handler: oops, not our handler, " 1149 "restoring: sig=%d\n", 1150 sig)); 1151 __kmp_sigaction(sig, &old, NULL); 1152 } 1153 sigdelset(&__kmp_sigset, sig); 1154 KMP_MB(); // Flush all pending memory write invalidates. 1155 } 1156 } // __kmp_remove_one_handler 1157 1158 void __kmp_install_signals(int parallel_init) { 1159 KB_TRACE(10, ("__kmp_install_signals( %d )\n", parallel_init)); 1160 if (__kmp_handle_signals || !parallel_init) { 1161 // If ! parallel_init, we do not install handlers, just save original 1162 // handlers. Let us do it even __handle_signals is 0. 1163 sigemptyset(&__kmp_sigset); 1164 __kmp_install_one_handler(SIGHUP, __kmp_team_handler, parallel_init); 1165 __kmp_install_one_handler(SIGINT, __kmp_team_handler, parallel_init); 1166 __kmp_install_one_handler(SIGQUIT, __kmp_team_handler, parallel_init); 1167 __kmp_install_one_handler(SIGILL, __kmp_team_handler, parallel_init); 1168 __kmp_install_one_handler(SIGABRT, __kmp_team_handler, parallel_init); 1169 __kmp_install_one_handler(SIGFPE, __kmp_team_handler, parallel_init); 1170 __kmp_install_one_handler(SIGBUS, __kmp_team_handler, parallel_init); 1171 __kmp_install_one_handler(SIGSEGV, __kmp_team_handler, parallel_init); 1172 #ifdef SIGSYS 1173 __kmp_install_one_handler(SIGSYS, __kmp_team_handler, parallel_init); 1174 #endif // SIGSYS 1175 __kmp_install_one_handler(SIGTERM, __kmp_team_handler, parallel_init); 1176 #ifdef SIGPIPE 1177 __kmp_install_one_handler(SIGPIPE, __kmp_team_handler, parallel_init); 1178 #endif // SIGPIPE 1179 } 1180 } // __kmp_install_signals 1181 1182 void __kmp_remove_signals(void) { 1183 int sig; 1184 KB_TRACE(10, ("__kmp_remove_signals()\n")); 1185 for (sig = 1; sig < NSIG; ++sig) { 1186 __kmp_remove_one_handler(sig); 1187 } 1188 } // __kmp_remove_signals 1189 1190 #endif // KMP_HANDLE_SIGNALS 1191 1192 void __kmp_enable(int new_state) { 1193 #ifdef KMP_CANCEL_THREADS 1194 int status, old_state; 1195 status = pthread_setcancelstate(new_state, &old_state); 1196 KMP_CHECK_SYSFAIL("pthread_setcancelstate", status); 1197 KMP_DEBUG_ASSERT(old_state == PTHREAD_CANCEL_DISABLE); 1198 #endif 1199 } 1200 1201 void __kmp_disable(int *old_state) { 1202 #ifdef KMP_CANCEL_THREADS 1203 int status; 1204 status = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, old_state); 1205 KMP_CHECK_SYSFAIL("pthread_setcancelstate", status); 1206 #endif 1207 } 1208 1209 static void __kmp_atfork_prepare(void) { 1210 __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); 1211 __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); 1212 } 1213 1214 static void __kmp_atfork_parent(void) { 1215 __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); 1216 __kmp_release_bootstrap_lock(&__kmp_initz_lock); 1217 } 1218 1219 /* Reset the library so execution in the child starts "all over again" with 1220 clean data structures in initial states. Don't worry about freeing memory 1221 allocated by parent, just abandon it to be safe. */ 1222 static void __kmp_atfork_child(void) { 1223 __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); 1224 __kmp_release_bootstrap_lock(&__kmp_initz_lock); 1225 /* TODO make sure this is done right for nested/sibling */ 1226 // ATT: Memory leaks are here? TODO: Check it and fix. 1227 /* KMP_ASSERT( 0 ); */ 1228 1229 ++__kmp_fork_count; 1230 1231 #if KMP_AFFINITY_SUPPORTED 1232 #if KMP_OS_LINUX || KMP_OS_FREEBSD 1233 // reset the affinity in the child to the initial thread 1234 // affinity in the parent 1235 kmp_set_thread_affinity_mask_initial(); 1236 #endif 1237 // Set default not to bind threads tightly in the child (we’re expecting 1238 // over-subscription after the fork and this can improve things for 1239 // scripting languages that use OpenMP inside process-parallel code). 1240 __kmp_affinity_type = affinity_none; 1241 if (__kmp_nested_proc_bind.bind_types != NULL) { 1242 __kmp_nested_proc_bind.bind_types[0] = proc_bind_false; 1243 } 1244 __kmp_affinity_masks = NULL; 1245 __kmp_affinity_num_masks = 0; 1246 #endif // KMP_AFFINITY_SUPPORTED 1247 1248 #if KMP_USE_MONITOR 1249 __kmp_init_monitor = 0; 1250 #endif 1251 __kmp_init_parallel = FALSE; 1252 __kmp_init_middle = FALSE; 1253 __kmp_init_serial = FALSE; 1254 TCW_4(__kmp_init_gtid, FALSE); 1255 __kmp_init_common = FALSE; 1256 1257 TCW_4(__kmp_init_user_locks, FALSE); 1258 #if !KMP_USE_DYNAMIC_LOCK 1259 __kmp_user_lock_table.used = 1; 1260 __kmp_user_lock_table.allocated = 0; 1261 __kmp_user_lock_table.table = NULL; 1262 __kmp_lock_blocks = NULL; 1263 #endif 1264 1265 __kmp_all_nth = 0; 1266 TCW_4(__kmp_nth, 0); 1267 1268 __kmp_thread_pool = NULL; 1269 __kmp_thread_pool_insert_pt = NULL; 1270 __kmp_team_pool = NULL; 1271 1272 /* Must actually zero all the *cache arguments passed to __kmpc_threadprivate 1273 here so threadprivate doesn't use stale data */ 1274 KA_TRACE(10, ("__kmp_atfork_child: checking cache address list %p\n", 1275 __kmp_threadpriv_cache_list)); 1276 1277 while (__kmp_threadpriv_cache_list != NULL) { 1278 1279 if (*__kmp_threadpriv_cache_list->addr != NULL) { 1280 KC_TRACE(50, ("__kmp_atfork_child: zeroing cache at address %p\n", 1281 &(*__kmp_threadpriv_cache_list->addr))); 1282 1283 *__kmp_threadpriv_cache_list->addr = NULL; 1284 } 1285 __kmp_threadpriv_cache_list = __kmp_threadpriv_cache_list->next; 1286 } 1287 1288 __kmp_init_runtime = FALSE; 1289 1290 /* reset statically initialized locks */ 1291 __kmp_init_bootstrap_lock(&__kmp_initz_lock); 1292 __kmp_init_bootstrap_lock(&__kmp_stdio_lock); 1293 __kmp_init_bootstrap_lock(&__kmp_console_lock); 1294 __kmp_init_bootstrap_lock(&__kmp_task_team_lock); 1295 1296 #if USE_ITT_BUILD 1297 __kmp_itt_reset(); // reset ITT's global state 1298 #endif /* USE_ITT_BUILD */ 1299 1300 __kmp_serial_initialize(); 1301 1302 /* This is necessary to make sure no stale data is left around */ 1303 /* AC: customers complain that we use unsafe routines in the atfork 1304 handler. Mathworks: dlsym() is unsafe. We call dlsym and dlopen 1305 in dynamic_link when check the presence of shared tbbmalloc library. 1306 Suggestion is to make the library initialization lazier, similar 1307 to what done for __kmpc_begin(). */ 1308 // TODO: synchronize all static initializations with regular library 1309 // startup; look at kmp_global.cpp and etc. 1310 //__kmp_internal_begin (); 1311 } 1312 1313 void __kmp_register_atfork(void) { 1314 if (__kmp_need_register_atfork) { 1315 int status = pthread_atfork(__kmp_atfork_prepare, __kmp_atfork_parent, 1316 __kmp_atfork_child); 1317 KMP_CHECK_SYSFAIL("pthread_atfork", status); 1318 __kmp_need_register_atfork = FALSE; 1319 } 1320 } 1321 1322 void __kmp_suspend_initialize(void) { 1323 int status; 1324 status = pthread_mutexattr_init(&__kmp_suspend_mutex_attr); 1325 KMP_CHECK_SYSFAIL("pthread_mutexattr_init", status); 1326 status = pthread_condattr_init(&__kmp_suspend_cond_attr); 1327 KMP_CHECK_SYSFAIL("pthread_condattr_init", status); 1328 } 1329 1330 void __kmp_suspend_initialize_thread(kmp_info_t *th) { 1331 ANNOTATE_HAPPENS_AFTER(&th->th.th_suspend_init_count); 1332 int old_value = KMP_ATOMIC_LD_RLX(&th->th.th_suspend_init_count); 1333 int new_value = __kmp_fork_count + 1; 1334 // Return if already initialized 1335 if (old_value == new_value) 1336 return; 1337 // Wait, then return if being initialized 1338 if (old_value == -1 || !__kmp_atomic_compare_store( 1339 &th->th.th_suspend_init_count, old_value, -1)) { 1340 while (KMP_ATOMIC_LD_ACQ(&th->th.th_suspend_init_count) != new_value) { 1341 KMP_CPU_PAUSE(); 1342 } 1343 } else { 1344 // Claim to be the initializer and do initializations 1345 int status; 1346 status = pthread_cond_init(&th->th.th_suspend_cv.c_cond, 1347 &__kmp_suspend_cond_attr); 1348 KMP_CHECK_SYSFAIL("pthread_cond_init", status); 1349 status = pthread_mutex_init(&th->th.th_suspend_mx.m_mutex, 1350 &__kmp_suspend_mutex_attr); 1351 KMP_CHECK_SYSFAIL("pthread_mutex_init", status); 1352 KMP_ATOMIC_ST_REL(&th->th.th_suspend_init_count, new_value); 1353 ANNOTATE_HAPPENS_BEFORE(&th->th.th_suspend_init_count); 1354 } 1355 } 1356 1357 void __kmp_suspend_uninitialize_thread(kmp_info_t *th) { 1358 if (KMP_ATOMIC_LD_ACQ(&th->th.th_suspend_init_count) > __kmp_fork_count) { 1359 /* this means we have initialize the suspension pthread objects for this 1360 thread in this instance of the process */ 1361 int status; 1362 1363 status = pthread_cond_destroy(&th->th.th_suspend_cv.c_cond); 1364 if (status != 0 && status != EBUSY) { 1365 KMP_SYSFAIL("pthread_cond_destroy", status); 1366 } 1367 status = pthread_mutex_destroy(&th->th.th_suspend_mx.m_mutex); 1368 if (status != 0 && status != EBUSY) { 1369 KMP_SYSFAIL("pthread_mutex_destroy", status); 1370 } 1371 --th->th.th_suspend_init_count; 1372 KMP_DEBUG_ASSERT(KMP_ATOMIC_LD_RLX(&th->th.th_suspend_init_count) == 1373 __kmp_fork_count); 1374 } 1375 } 1376 1377 // return true if lock obtained, false otherwise 1378 int __kmp_try_suspend_mx(kmp_info_t *th) { 1379 return (pthread_mutex_trylock(&th->th.th_suspend_mx.m_mutex) == 0); 1380 } 1381 1382 void __kmp_lock_suspend_mx(kmp_info_t *th) { 1383 int status = pthread_mutex_lock(&th->th.th_suspend_mx.m_mutex); 1384 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 1385 } 1386 1387 void __kmp_unlock_suspend_mx(kmp_info_t *th) { 1388 int status = pthread_mutex_unlock(&th->th.th_suspend_mx.m_mutex); 1389 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 1390 } 1391 1392 /* This routine puts the calling thread to sleep after setting the 1393 sleep bit for the indicated flag variable to true. */ 1394 template <class C> 1395 static inline void __kmp_suspend_template(int th_gtid, C *flag) { 1396 KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(USER_suspend); 1397 kmp_info_t *th = __kmp_threads[th_gtid]; 1398 int status; 1399 typename C::flag_t old_spin; 1400 1401 KF_TRACE(30, ("__kmp_suspend_template: T#%d enter for flag = %p\n", th_gtid, 1402 flag->get())); 1403 1404 __kmp_suspend_initialize_thread(th); 1405 1406 __kmp_lock_suspend_mx(th); 1407 1408 KF_TRACE(10, ("__kmp_suspend_template: T#%d setting sleep bit for spin(%p)\n", 1409 th_gtid, flag->get())); 1410 1411 /* TODO: shouldn't this use release semantics to ensure that 1412 __kmp_suspend_initialize_thread gets called first? */ 1413 old_spin = flag->set_sleeping(); 1414 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME && 1415 __kmp_pause_status != kmp_soft_paused) { 1416 flag->unset_sleeping(); 1417 __kmp_unlock_suspend_mx(th); 1418 return; 1419 } 1420 KF_TRACE(5, ("__kmp_suspend_template: T#%d set sleep bit for spin(%p)==%x," 1421 " was %x\n", 1422 th_gtid, flag->get(), flag->load(), old_spin)); 1423 1424 if (flag->done_check_val(old_spin)) { 1425 old_spin = flag->unset_sleeping(); 1426 KF_TRACE(5, ("__kmp_suspend_template: T#%d false alarm, reset sleep bit " 1427 "for spin(%p)\n", 1428 th_gtid, flag->get())); 1429 } else { 1430 /* Encapsulate in a loop as the documentation states that this may 1431 "with low probability" return when the condition variable has 1432 not been signaled or broadcast */ 1433 int deactivated = FALSE; 1434 TCW_PTR(th->th.th_sleep_loc, (void *)flag); 1435 1436 while (flag->is_sleeping()) { 1437 #ifdef DEBUG_SUSPEND 1438 char buffer[128]; 1439 __kmp_suspend_count++; 1440 __kmp_print_cond(buffer, &th->th.th_suspend_cv); 1441 __kmp_printf("__kmp_suspend_template: suspending T#%d: %s\n", th_gtid, 1442 buffer); 1443 #endif 1444 // Mark the thread as no longer active (only in the first iteration of the 1445 // loop). 1446 if (!deactivated) { 1447 th->th.th_active = FALSE; 1448 if (th->th.th_active_in_pool) { 1449 th->th.th_active_in_pool = FALSE; 1450 KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth); 1451 KMP_DEBUG_ASSERT(TCR_4(__kmp_thread_pool_active_nth) >= 0); 1452 } 1453 deactivated = TRUE; 1454 } 1455 1456 #if USE_SUSPEND_TIMEOUT 1457 struct timespec now; 1458 struct timeval tval; 1459 int msecs; 1460 1461 status = gettimeofday(&tval, NULL); 1462 KMP_CHECK_SYSFAIL_ERRNO("gettimeofday", status); 1463 TIMEVAL_TO_TIMESPEC(&tval, &now); 1464 1465 msecs = (4 * __kmp_dflt_blocktime) + 200; 1466 now.tv_sec += msecs / 1000; 1467 now.tv_nsec += (msecs % 1000) * 1000; 1468 1469 KF_TRACE(15, ("__kmp_suspend_template: T#%d about to perform " 1470 "pthread_cond_timedwait\n", 1471 th_gtid)); 1472 status = pthread_cond_timedwait(&th->th.th_suspend_cv.c_cond, 1473 &th->th.th_suspend_mx.m_mutex, &now); 1474 #else 1475 KF_TRACE(15, ("__kmp_suspend_template: T#%d about to perform" 1476 " pthread_cond_wait\n", 1477 th_gtid)); 1478 status = pthread_cond_wait(&th->th.th_suspend_cv.c_cond, 1479 &th->th.th_suspend_mx.m_mutex); 1480 #endif // USE_SUSPEND_TIMEOUT 1481 1482 if ((status != 0) && (status != EINTR) && (status != ETIMEDOUT)) { 1483 KMP_SYSFAIL("pthread_cond_wait", status); 1484 } 1485 #ifdef KMP_DEBUG 1486 if (status == ETIMEDOUT) { 1487 if (flag->is_sleeping()) { 1488 KF_TRACE(100, 1489 ("__kmp_suspend_template: T#%d timeout wakeup\n", th_gtid)); 1490 } else { 1491 KF_TRACE(2, ("__kmp_suspend_template: T#%d timeout wakeup, sleep bit " 1492 "not set!\n", 1493 th_gtid)); 1494 } 1495 } else if (flag->is_sleeping()) { 1496 KF_TRACE(100, 1497 ("__kmp_suspend_template: T#%d spurious wakeup\n", th_gtid)); 1498 } 1499 #endif 1500 } // while 1501 1502 // Mark the thread as active again (if it was previous marked as inactive) 1503 if (deactivated) { 1504 th->th.th_active = TRUE; 1505 if (TCR_4(th->th.th_in_pool)) { 1506 KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth); 1507 th->th.th_active_in_pool = TRUE; 1508 } 1509 } 1510 } 1511 #ifdef DEBUG_SUSPEND 1512 { 1513 char buffer[128]; 1514 __kmp_print_cond(buffer, &th->th.th_suspend_cv); 1515 __kmp_printf("__kmp_suspend_template: T#%d has awakened: %s\n", th_gtid, 1516 buffer); 1517 } 1518 #endif 1519 1520 __kmp_unlock_suspend_mx(th); 1521 KF_TRACE(30, ("__kmp_suspend_template: T#%d exit\n", th_gtid)); 1522 } 1523 1524 template <bool C, bool S> 1525 void __kmp_suspend_32(int th_gtid, kmp_flag_32<C, S> *flag) { 1526 __kmp_suspend_template(th_gtid, flag); 1527 } 1528 template <bool C, bool S> 1529 void __kmp_suspend_64(int th_gtid, kmp_flag_64<C, S> *flag) { 1530 __kmp_suspend_template(th_gtid, flag); 1531 } 1532 void __kmp_suspend_oncore(int th_gtid, kmp_flag_oncore *flag) { 1533 __kmp_suspend_template(th_gtid, flag); 1534 } 1535 1536 template void __kmp_suspend_32<false, false>(int, kmp_flag_32<false, false> *); 1537 template void __kmp_suspend_64<false, true>(int, kmp_flag_64<false, true> *); 1538 template void __kmp_suspend_64<true, false>(int, kmp_flag_64<true, false> *); 1539 1540 /* This routine signals the thread specified by target_gtid to wake up 1541 after setting the sleep bit indicated by the flag argument to FALSE. 1542 The target thread must already have called __kmp_suspend_template() */ 1543 template <class C> 1544 static inline void __kmp_resume_template(int target_gtid, C *flag) { 1545 KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(USER_resume); 1546 kmp_info_t *th = __kmp_threads[target_gtid]; 1547 int status; 1548 1549 #ifdef KMP_DEBUG 1550 int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1; 1551 #endif 1552 1553 KF_TRACE(30, ("__kmp_resume_template: T#%d wants to wakeup T#%d enter\n", 1554 gtid, target_gtid)); 1555 KMP_DEBUG_ASSERT(gtid != target_gtid); 1556 1557 __kmp_suspend_initialize_thread(th); 1558 1559 __kmp_lock_suspend_mx(th); 1560 1561 if (!flag) { // coming from __kmp_null_resume_wrapper 1562 flag = (C *)CCAST(void *, th->th.th_sleep_loc); 1563 } 1564 1565 // First, check if the flag is null or its type has changed. If so, someone 1566 // else woke it up. 1567 if (!flag || flag->get_type() != flag->get_ptr_type()) { // get_ptr_type 1568 // simply shows what flag was cast to 1569 KF_TRACE(5, ("__kmp_resume_template: T#%d exiting, thread T#%d already " 1570 "awake: flag(%p)\n", 1571 gtid, target_gtid, NULL)); 1572 __kmp_unlock_suspend_mx(th); 1573 return; 1574 } else { // if multiple threads are sleeping, flag should be internally 1575 // referring to a specific thread here 1576 typename C::flag_t old_spin = flag->unset_sleeping(); 1577 if (!flag->is_sleeping_val(old_spin)) { 1578 KF_TRACE(5, ("__kmp_resume_template: T#%d exiting, thread T#%d already " 1579 "awake: flag(%p): " 1580 "%u => %u\n", 1581 gtid, target_gtid, flag->get(), old_spin, flag->load())); 1582 __kmp_unlock_suspend_mx(th); 1583 return; 1584 } 1585 KF_TRACE(5, ("__kmp_resume_template: T#%d about to wakeup T#%d, reset " 1586 "sleep bit for flag's loc(%p): " 1587 "%u => %u\n", 1588 gtid, target_gtid, flag->get(), old_spin, flag->load())); 1589 } 1590 TCW_PTR(th->th.th_sleep_loc, NULL); 1591 1592 #ifdef DEBUG_SUSPEND 1593 { 1594 char buffer[128]; 1595 __kmp_print_cond(buffer, &th->th.th_suspend_cv); 1596 __kmp_printf("__kmp_resume_template: T#%d resuming T#%d: %s\n", gtid, 1597 target_gtid, buffer); 1598 } 1599 #endif 1600 status = pthread_cond_signal(&th->th.th_suspend_cv.c_cond); 1601 KMP_CHECK_SYSFAIL("pthread_cond_signal", status); 1602 __kmp_unlock_suspend_mx(th); 1603 KF_TRACE(30, ("__kmp_resume_template: T#%d exiting after signaling wake up" 1604 " for T#%d\n", 1605 gtid, target_gtid)); 1606 } 1607 1608 template <bool C, bool S> 1609 void __kmp_resume_32(int target_gtid, kmp_flag_32<C, S> *flag) { 1610 __kmp_resume_template(target_gtid, flag); 1611 } 1612 template <bool C, bool S> 1613 void __kmp_resume_64(int target_gtid, kmp_flag_64<C, S> *flag) { 1614 __kmp_resume_template(target_gtid, flag); 1615 } 1616 void __kmp_resume_oncore(int target_gtid, kmp_flag_oncore *flag) { 1617 __kmp_resume_template(target_gtid, flag); 1618 } 1619 1620 template void __kmp_resume_32<false, true>(int, kmp_flag_32<false, true> *); 1621 template void __kmp_resume_64<false, true>(int, kmp_flag_64<false, true> *); 1622 1623 #if KMP_USE_MONITOR 1624 void __kmp_resume_monitor() { 1625 KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(USER_resume); 1626 int status; 1627 #ifdef KMP_DEBUG 1628 int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1; 1629 KF_TRACE(30, ("__kmp_resume_monitor: T#%d wants to wakeup T#%d enter\n", gtid, 1630 KMP_GTID_MONITOR)); 1631 KMP_DEBUG_ASSERT(gtid != KMP_GTID_MONITOR); 1632 #endif 1633 status = pthread_mutex_lock(&__kmp_wait_mx.m_mutex); 1634 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 1635 #ifdef DEBUG_SUSPEND 1636 { 1637 char buffer[128]; 1638 __kmp_print_cond(buffer, &__kmp_wait_cv.c_cond); 1639 __kmp_printf("__kmp_resume_monitor: T#%d resuming T#%d: %s\n", gtid, 1640 KMP_GTID_MONITOR, buffer); 1641 } 1642 #endif 1643 status = pthread_cond_signal(&__kmp_wait_cv.c_cond); 1644 KMP_CHECK_SYSFAIL("pthread_cond_signal", status); 1645 status = pthread_mutex_unlock(&__kmp_wait_mx.m_mutex); 1646 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 1647 KF_TRACE(30, ("__kmp_resume_monitor: T#%d exiting after signaling wake up" 1648 " for T#%d\n", 1649 gtid, KMP_GTID_MONITOR)); 1650 } 1651 #endif // KMP_USE_MONITOR 1652 1653 void __kmp_yield() { sched_yield(); } 1654 1655 void __kmp_gtid_set_specific(int gtid) { 1656 if (__kmp_init_gtid) { 1657 int status; 1658 status = pthread_setspecific(__kmp_gtid_threadprivate_key, 1659 (void *)(intptr_t)(gtid + 1)); 1660 KMP_CHECK_SYSFAIL("pthread_setspecific", status); 1661 } else { 1662 KA_TRACE(50, ("__kmp_gtid_set_specific: runtime shutdown, returning\n")); 1663 } 1664 } 1665 1666 int __kmp_gtid_get_specific() { 1667 int gtid; 1668 if (!__kmp_init_gtid) { 1669 KA_TRACE(50, ("__kmp_gtid_get_specific: runtime shutdown, returning " 1670 "KMP_GTID_SHUTDOWN\n")); 1671 return KMP_GTID_SHUTDOWN; 1672 } 1673 gtid = (int)(size_t)pthread_getspecific(__kmp_gtid_threadprivate_key); 1674 if (gtid == 0) { 1675 gtid = KMP_GTID_DNE; 1676 } else { 1677 gtid--; 1678 } 1679 KA_TRACE(50, ("__kmp_gtid_get_specific: key:%d gtid:%d\n", 1680 __kmp_gtid_threadprivate_key, gtid)); 1681 return gtid; 1682 } 1683 1684 double __kmp_read_cpu_time(void) { 1685 /*clock_t t;*/ 1686 struct tms buffer; 1687 1688 /*t =*/times(&buffer); 1689 1690 return (double)(buffer.tms_utime + buffer.tms_cutime) / 1691 (double)CLOCKS_PER_SEC; 1692 } 1693 1694 int __kmp_read_system_info(struct kmp_sys_info *info) { 1695 int status; 1696 struct rusage r_usage; 1697 1698 memset(info, 0, sizeof(*info)); 1699 1700 status = getrusage(RUSAGE_SELF, &r_usage); 1701 KMP_CHECK_SYSFAIL_ERRNO("getrusage", status); 1702 1703 // The maximum resident set size utilized (in kilobytes) 1704 info->maxrss = r_usage.ru_maxrss; 1705 // The number of page faults serviced without any I/O 1706 info->minflt = r_usage.ru_minflt; 1707 // The number of page faults serviced that required I/O 1708 info->majflt = r_usage.ru_majflt; 1709 // The number of times a process was "swapped" out of memory 1710 info->nswap = r_usage.ru_nswap; 1711 // The number of times the file system had to perform input 1712 info->inblock = r_usage.ru_inblock; 1713 // The number of times the file system had to perform output 1714 info->oublock = r_usage.ru_oublock; 1715 // The number of times a context switch was voluntarily 1716 info->nvcsw = r_usage.ru_nvcsw; 1717 // The number of times a context switch was forced 1718 info->nivcsw = r_usage.ru_nivcsw; 1719 1720 return (status != 0); 1721 } 1722 1723 void __kmp_read_system_time(double *delta) { 1724 double t_ns; 1725 struct timeval tval; 1726 struct timespec stop; 1727 int status; 1728 1729 status = gettimeofday(&tval, NULL); 1730 KMP_CHECK_SYSFAIL_ERRNO("gettimeofday", status); 1731 TIMEVAL_TO_TIMESPEC(&tval, &stop); 1732 t_ns = (double)(TS2NS(stop) - TS2NS(__kmp_sys_timer_data.start)); 1733 *delta = (t_ns * 1e-9); 1734 } 1735 1736 void __kmp_clear_system_time(void) { 1737 struct timeval tval; 1738 int status; 1739 status = gettimeofday(&tval, NULL); 1740 KMP_CHECK_SYSFAIL_ERRNO("gettimeofday", status); 1741 TIMEVAL_TO_TIMESPEC(&tval, &__kmp_sys_timer_data.start); 1742 } 1743 1744 static int __kmp_get_xproc(void) { 1745 1746 int r = 0; 1747 1748 #if KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || \ 1749 KMP_OS_OPENBSD || KMP_OS_HURD 1750 1751 __kmp_type_convert(sysconf(_SC_NPROCESSORS_ONLN), &(r)); 1752 1753 #elif KMP_OS_DARWIN 1754 1755 // Bug C77011 High "OpenMP Threads and number of active cores". 1756 1757 // Find the number of available CPUs. 1758 kern_return_t rc; 1759 host_basic_info_data_t info; 1760 mach_msg_type_number_t num = HOST_BASIC_INFO_COUNT; 1761 rc = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&info, &num); 1762 if (rc == 0 && num == HOST_BASIC_INFO_COUNT) { 1763 // Cannot use KA_TRACE() here because this code works before trace support 1764 // is initialized. 1765 r = info.avail_cpus; 1766 } else { 1767 KMP_WARNING(CantGetNumAvailCPU); 1768 KMP_INFORM(AssumedNumCPU); 1769 } 1770 1771 #else 1772 1773 #error "Unknown or unsupported OS." 1774 1775 #endif 1776 1777 return r > 0 ? r : 2; /* guess value of 2 if OS told us 0 */ 1778 1779 } // __kmp_get_xproc 1780 1781 int __kmp_read_from_file(char const *path, char const *format, ...) { 1782 int result; 1783 va_list args; 1784 1785 va_start(args, format); 1786 FILE *f = fopen(path, "rb"); 1787 if (f == NULL) 1788 return 0; 1789 result = vfscanf(f, format, args); 1790 fclose(f); 1791 1792 return result; 1793 } 1794 1795 void __kmp_runtime_initialize(void) { 1796 int status; 1797 pthread_mutexattr_t mutex_attr; 1798 pthread_condattr_t cond_attr; 1799 1800 if (__kmp_init_runtime) { 1801 return; 1802 } 1803 1804 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) 1805 if (!__kmp_cpuinfo.initialized) { 1806 __kmp_query_cpuid(&__kmp_cpuinfo); 1807 } 1808 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ 1809 1810 __kmp_xproc = __kmp_get_xproc(); 1811 1812 #if !KMP_32_BIT_ARCH 1813 struct rlimit rlim; 1814 // read stack size of calling thread, save it as default for worker threads; 1815 // this should be done before reading environment variables 1816 status = getrlimit(RLIMIT_STACK, &rlim); 1817 if (status == 0) { // success? 1818 __kmp_stksize = rlim.rlim_cur; 1819 __kmp_check_stksize(&__kmp_stksize); // check value and adjust if needed 1820 } 1821 #endif /* KMP_32_BIT_ARCH */ 1822 1823 if (sysconf(_SC_THREADS)) { 1824 1825 /* Query the maximum number of threads */ 1826 __kmp_type_convert(sysconf(_SC_THREAD_THREADS_MAX), &(__kmp_sys_max_nth)); 1827 if (__kmp_sys_max_nth == -1) { 1828 /* Unlimited threads for NPTL */ 1829 __kmp_sys_max_nth = INT_MAX; 1830 } else if (__kmp_sys_max_nth <= 1) { 1831 /* Can't tell, just use PTHREAD_THREADS_MAX */ 1832 __kmp_sys_max_nth = KMP_MAX_NTH; 1833 } 1834 1835 /* Query the minimum stack size */ 1836 __kmp_sys_min_stksize = sysconf(_SC_THREAD_STACK_MIN); 1837 if (__kmp_sys_min_stksize <= 1) { 1838 __kmp_sys_min_stksize = KMP_MIN_STKSIZE; 1839 } 1840 } 1841 1842 /* Set up minimum number of threads to switch to TLS gtid */ 1843 __kmp_tls_gtid_min = KMP_TLS_GTID_MIN; 1844 1845 status = pthread_key_create(&__kmp_gtid_threadprivate_key, 1846 __kmp_internal_end_dest); 1847 KMP_CHECK_SYSFAIL("pthread_key_create", status); 1848 status = pthread_mutexattr_init(&mutex_attr); 1849 KMP_CHECK_SYSFAIL("pthread_mutexattr_init", status); 1850 status = pthread_mutex_init(&__kmp_wait_mx.m_mutex, &mutex_attr); 1851 KMP_CHECK_SYSFAIL("pthread_mutex_init", status); 1852 status = pthread_mutexattr_destroy(&mutex_attr); 1853 KMP_CHECK_SYSFAIL("pthread_mutexattr_destroy", status); 1854 status = pthread_condattr_init(&cond_attr); 1855 KMP_CHECK_SYSFAIL("pthread_condattr_init", status); 1856 status = pthread_cond_init(&__kmp_wait_cv.c_cond, &cond_attr); 1857 KMP_CHECK_SYSFAIL("pthread_cond_init", status); 1858 status = pthread_condattr_destroy(&cond_attr); 1859 KMP_CHECK_SYSFAIL("pthread_condattr_destroy", status); 1860 #if USE_ITT_BUILD 1861 __kmp_itt_initialize(); 1862 #endif /* USE_ITT_BUILD */ 1863 1864 __kmp_init_runtime = TRUE; 1865 } 1866 1867 void __kmp_runtime_destroy(void) { 1868 int status; 1869 1870 if (!__kmp_init_runtime) { 1871 return; // Nothing to do. 1872 } 1873 1874 #if USE_ITT_BUILD 1875 __kmp_itt_destroy(); 1876 #endif /* USE_ITT_BUILD */ 1877 1878 status = pthread_key_delete(__kmp_gtid_threadprivate_key); 1879 KMP_CHECK_SYSFAIL("pthread_key_delete", status); 1880 1881 status = pthread_mutex_destroy(&__kmp_wait_mx.m_mutex); 1882 if (status != 0 && status != EBUSY) { 1883 KMP_SYSFAIL("pthread_mutex_destroy", status); 1884 } 1885 status = pthread_cond_destroy(&__kmp_wait_cv.c_cond); 1886 if (status != 0 && status != EBUSY) { 1887 KMP_SYSFAIL("pthread_cond_destroy", status); 1888 } 1889 #if KMP_AFFINITY_SUPPORTED 1890 __kmp_affinity_uninitialize(); 1891 #endif 1892 1893 __kmp_init_runtime = FALSE; 1894 } 1895 1896 /* Put the thread to sleep for a time period */ 1897 /* NOTE: not currently used anywhere */ 1898 void __kmp_thread_sleep(int millis) { sleep((millis + 500) / 1000); } 1899 1900 /* Calculate the elapsed wall clock time for the user */ 1901 void __kmp_elapsed(double *t) { 1902 int status; 1903 #ifdef FIX_SGI_CLOCK 1904 struct timespec ts; 1905 1906 status = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); 1907 KMP_CHECK_SYSFAIL_ERRNO("clock_gettime", status); 1908 *t = 1909 (double)ts.tv_nsec * (1.0 / (double)KMP_NSEC_PER_SEC) + (double)ts.tv_sec; 1910 #else 1911 struct timeval tv; 1912 1913 status = gettimeofday(&tv, NULL); 1914 KMP_CHECK_SYSFAIL_ERRNO("gettimeofday", status); 1915 *t = 1916 (double)tv.tv_usec * (1.0 / (double)KMP_USEC_PER_SEC) + (double)tv.tv_sec; 1917 #endif 1918 } 1919 1920 /* Calculate the elapsed wall clock tick for the user */ 1921 void __kmp_elapsed_tick(double *t) { *t = 1 / (double)CLOCKS_PER_SEC; } 1922 1923 /* Return the current time stamp in nsec */ 1924 kmp_uint64 __kmp_now_nsec() { 1925 struct timeval t; 1926 gettimeofday(&t, NULL); 1927 kmp_uint64 nsec = (kmp_uint64)KMP_NSEC_PER_SEC * (kmp_uint64)t.tv_sec + 1928 (kmp_uint64)1000 * (kmp_uint64)t.tv_usec; 1929 return nsec; 1930 } 1931 1932 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 1933 /* Measure clock ticks per millisecond */ 1934 void __kmp_initialize_system_tick() { 1935 kmp_uint64 now, nsec2, diff; 1936 kmp_uint64 delay = 100000; // 50~100 usec on most machines. 1937 kmp_uint64 nsec = __kmp_now_nsec(); 1938 kmp_uint64 goal = __kmp_hardware_timestamp() + delay; 1939 while ((now = __kmp_hardware_timestamp()) < goal) 1940 ; 1941 nsec2 = __kmp_now_nsec(); 1942 diff = nsec2 - nsec; 1943 if (diff > 0) { 1944 kmp_uint64 tpms = ((kmp_uint64)1e6 * (delay + (now - goal)) / diff); 1945 if (tpms > 0) 1946 __kmp_ticks_per_msec = tpms; 1947 } 1948 } 1949 #endif 1950 1951 /* Determine whether the given address is mapped into the current address 1952 space. */ 1953 1954 int __kmp_is_address_mapped(void *addr) { 1955 1956 int found = 0; 1957 int rc; 1958 1959 #if KMP_OS_LINUX || KMP_OS_HURD 1960 1961 /* On GNUish OSes, read the /proc/<pid>/maps pseudo-file to get all the 1962 address ranges mapped into the address space. */ 1963 1964 char *name = __kmp_str_format("/proc/%d/maps", getpid()); 1965 FILE *file = NULL; 1966 1967 file = fopen(name, "r"); 1968 KMP_ASSERT(file != NULL); 1969 1970 for (;;) { 1971 1972 void *beginning = NULL; 1973 void *ending = NULL; 1974 char perms[5]; 1975 1976 rc = fscanf(file, "%p-%p %4s %*[^\n]\n", &beginning, &ending, perms); 1977 if (rc == EOF) { 1978 break; 1979 } 1980 KMP_ASSERT(rc == 3 && 1981 KMP_STRLEN(perms) == 4); // Make sure all fields are read. 1982 1983 // Ending address is not included in the region, but beginning is. 1984 if ((addr >= beginning) && (addr < ending)) { 1985 perms[2] = 0; // 3th and 4th character does not matter. 1986 if (strcmp(perms, "rw") == 0) { 1987 // Memory we are looking for should be readable and writable. 1988 found = 1; 1989 } 1990 break; 1991 } 1992 } 1993 1994 // Free resources. 1995 fclose(file); 1996 KMP_INTERNAL_FREE(name); 1997 #elif KMP_OS_FREEBSD 1998 char *buf; 1999 size_t lstsz; 2000 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, getpid()}; 2001 rc = sysctl(mib, 4, NULL, &lstsz, NULL, 0); 2002 if (rc < 0) 2003 return 0; 2004 // We pass from number of vm entry's semantic 2005 // to size of whole entry map list. 2006 lstsz = lstsz * 4 / 3; 2007 buf = reinterpret_cast<char *>(kmpc_malloc(lstsz)); 2008 rc = sysctl(mib, 4, buf, &lstsz, NULL, 0); 2009 if (rc < 0) { 2010 kmpc_free(buf); 2011 return 0; 2012 } 2013 2014 char *lw = buf; 2015 char *up = buf + lstsz; 2016 2017 while (lw < up) { 2018 struct kinfo_vmentry *cur = reinterpret_cast<struct kinfo_vmentry *>(lw); 2019 size_t cursz = cur->kve_structsize; 2020 if (cursz == 0) 2021 break; 2022 void *start = reinterpret_cast<void *>(cur->kve_start); 2023 void *end = reinterpret_cast<void *>(cur->kve_end); 2024 // Readable/Writable addresses within current map entry 2025 if ((addr >= start) && (addr < end)) { 2026 if ((cur->kve_protection & KVME_PROT_READ) != 0 && 2027 (cur->kve_protection & KVME_PROT_WRITE) != 0) { 2028 found = 1; 2029 break; 2030 } 2031 } 2032 lw += cursz; 2033 } 2034 kmpc_free(buf); 2035 2036 #elif KMP_OS_DARWIN 2037 2038 /* On OS X*, /proc pseudo filesystem is not available. Try to read memory 2039 using vm interface. */ 2040 2041 int buffer; 2042 vm_size_t count; 2043 rc = vm_read_overwrite( 2044 mach_task_self(), // Task to read memory of. 2045 (vm_address_t)(addr), // Address to read from. 2046 1, // Number of bytes to be read. 2047 (vm_address_t)(&buffer), // Address of buffer to save read bytes in. 2048 &count // Address of var to save number of read bytes in. 2049 ); 2050 if (rc == 0) { 2051 // Memory successfully read. 2052 found = 1; 2053 } 2054 2055 #elif KMP_OS_NETBSD 2056 2057 int mib[5]; 2058 mib[0] = CTL_VM; 2059 mib[1] = VM_PROC; 2060 mib[2] = VM_PROC_MAP; 2061 mib[3] = getpid(); 2062 mib[4] = sizeof(struct kinfo_vmentry); 2063 2064 size_t size; 2065 rc = sysctl(mib, __arraycount(mib), NULL, &size, NULL, 0); 2066 KMP_ASSERT(!rc); 2067 KMP_ASSERT(size); 2068 2069 size = size * 4 / 3; 2070 struct kinfo_vmentry *kiv = (struct kinfo_vmentry *)KMP_INTERNAL_MALLOC(size); 2071 KMP_ASSERT(kiv); 2072 2073 rc = sysctl(mib, __arraycount(mib), kiv, &size, NULL, 0); 2074 KMP_ASSERT(!rc); 2075 KMP_ASSERT(size); 2076 2077 for (size_t i = 0; i < size; i++) { 2078 if (kiv[i].kve_start >= (uint64_t)addr && 2079 kiv[i].kve_end <= (uint64_t)addr) { 2080 found = 1; 2081 break; 2082 } 2083 } 2084 KMP_INTERNAL_FREE(kiv); 2085 #elif KMP_OS_OPENBSD 2086 2087 int mib[3]; 2088 mib[0] = CTL_KERN; 2089 mib[1] = KERN_PROC_VMMAP; 2090 mib[2] = getpid(); 2091 2092 size_t size; 2093 uint64_t end; 2094 rc = sysctl(mib, 3, NULL, &size, NULL, 0); 2095 KMP_ASSERT(!rc); 2096 KMP_ASSERT(size); 2097 end = size; 2098 2099 struct kinfo_vmentry kiv = {.kve_start = 0}; 2100 2101 while ((rc = sysctl(mib, 3, &kiv, &size, NULL, 0)) == 0) { 2102 KMP_ASSERT(size); 2103 if (kiv.kve_end == end) 2104 break; 2105 2106 if (kiv.kve_start >= (uint64_t)addr && kiv.kve_end <= (uint64_t)addr) { 2107 found = 1; 2108 break; 2109 } 2110 kiv.kve_start += 1; 2111 } 2112 #elif KMP_OS_DRAGONFLY 2113 2114 // FIXME(DragonFly): Implement this 2115 found = 1; 2116 2117 #else 2118 2119 #error "Unknown or unsupported OS" 2120 2121 #endif 2122 2123 return found; 2124 2125 } // __kmp_is_address_mapped 2126 2127 #ifdef USE_LOAD_BALANCE 2128 2129 #if KMP_OS_DARWIN || KMP_OS_NETBSD 2130 2131 // The function returns the rounded value of the system load average 2132 // during given time interval which depends on the value of 2133 // __kmp_load_balance_interval variable (default is 60 sec, other values 2134 // may be 300 sec or 900 sec). 2135 // It returns -1 in case of error. 2136 int __kmp_get_load_balance(int max) { 2137 double averages[3]; 2138 int ret_avg = 0; 2139 2140 int res = getloadavg(averages, 3); 2141 2142 // Check __kmp_load_balance_interval to determine which of averages to use. 2143 // getloadavg() may return the number of samples less than requested that is 2144 // less than 3. 2145 if (__kmp_load_balance_interval < 180 && (res >= 1)) { 2146 ret_avg = (int)averages[0]; // 1 min 2147 } else if ((__kmp_load_balance_interval >= 180 && 2148 __kmp_load_balance_interval < 600) && 2149 (res >= 2)) { 2150 ret_avg = (int)averages[1]; // 5 min 2151 } else if ((__kmp_load_balance_interval >= 600) && (res == 3)) { 2152 ret_avg = (int)averages[2]; // 15 min 2153 } else { // Error occurred 2154 return -1; 2155 } 2156 2157 return ret_avg; 2158 } 2159 2160 #else // Linux* OS 2161 2162 // The function returns number of running (not sleeping) threads, or -1 in case 2163 // of error. Error could be reported if Linux* OS kernel too old (without 2164 // "/proc" support). Counting running threads stops if max running threads 2165 // encountered. 2166 int __kmp_get_load_balance(int max) { 2167 static int permanent_error = 0; 2168 static int glb_running_threads = 0; // Saved count of the running threads for 2169 // the thread balance algorithm 2170 static double glb_call_time = 0; /* Thread balance algorithm call time */ 2171 2172 int running_threads = 0; // Number of running threads in the system. 2173 2174 DIR *proc_dir = NULL; // Handle of "/proc/" directory. 2175 struct dirent *proc_entry = NULL; 2176 2177 kmp_str_buf_t task_path; // "/proc/<pid>/task/<tid>/" path. 2178 DIR *task_dir = NULL; // Handle of "/proc/<pid>/task/<tid>/" directory. 2179 struct dirent *task_entry = NULL; 2180 int task_path_fixed_len; 2181 2182 kmp_str_buf_t stat_path; // "/proc/<pid>/task/<tid>/stat" path. 2183 int stat_file = -1; 2184 int stat_path_fixed_len; 2185 2186 int total_processes = 0; // Total number of processes in system. 2187 int total_threads = 0; // Total number of threads in system. 2188 2189 double call_time = 0.0; 2190 2191 __kmp_str_buf_init(&task_path); 2192 __kmp_str_buf_init(&stat_path); 2193 2194 __kmp_elapsed(&call_time); 2195 2196 if (glb_call_time && 2197 (call_time - glb_call_time < __kmp_load_balance_interval)) { 2198 running_threads = glb_running_threads; 2199 goto finish; 2200 } 2201 2202 glb_call_time = call_time; 2203 2204 // Do not spend time on scanning "/proc/" if we have a permanent error. 2205 if (permanent_error) { 2206 running_threads = -1; 2207 goto finish; 2208 } 2209 2210 if (max <= 0) { 2211 max = INT_MAX; 2212 } 2213 2214 // Open "/proc/" directory. 2215 proc_dir = opendir("/proc"); 2216 if (proc_dir == NULL) { 2217 // Cannot open "/prroc/". Probably the kernel does not support it. Return an 2218 // error now and in subsequent calls. 2219 running_threads = -1; 2220 permanent_error = 1; 2221 goto finish; 2222 } 2223 2224 // Initialize fixed part of task_path. This part will not change. 2225 __kmp_str_buf_cat(&task_path, "/proc/", 6); 2226 task_path_fixed_len = task_path.used; // Remember number of used characters. 2227 2228 proc_entry = readdir(proc_dir); 2229 while (proc_entry != NULL) { 2230 // Proc entry is a directory and name starts with a digit. Assume it is a 2231 // process' directory. 2232 if (proc_entry->d_type == DT_DIR && isdigit(proc_entry->d_name[0])) { 2233 2234 ++total_processes; 2235 // Make sure init process is the very first in "/proc", so we can replace 2236 // strcmp( proc_entry->d_name, "1" ) == 0 with simpler total_processes == 2237 // 1. We are going to check that total_processes == 1 => d_name == "1" is 2238 // true (where "=>" is implication). Since C++ does not have => operator, 2239 // let us replace it with its equivalent: a => b == ! a || b. 2240 KMP_DEBUG_ASSERT(total_processes != 1 || 2241 strcmp(proc_entry->d_name, "1") == 0); 2242 2243 // Construct task_path. 2244 task_path.used = task_path_fixed_len; // Reset task_path to "/proc/". 2245 __kmp_str_buf_cat(&task_path, proc_entry->d_name, 2246 KMP_STRLEN(proc_entry->d_name)); 2247 __kmp_str_buf_cat(&task_path, "/task", 5); 2248 2249 task_dir = opendir(task_path.str); 2250 if (task_dir == NULL) { 2251 // Process can finish between reading "/proc/" directory entry and 2252 // opening process' "task/" directory. So, in general case we should not 2253 // complain, but have to skip this process and read the next one. But on 2254 // systems with no "task/" support we will spend lot of time to scan 2255 // "/proc/" tree again and again without any benefit. "init" process 2256 // (its pid is 1) should exist always, so, if we cannot open 2257 // "/proc/1/task/" directory, it means "task/" is not supported by 2258 // kernel. Report an error now and in the future. 2259 if (strcmp(proc_entry->d_name, "1") == 0) { 2260 running_threads = -1; 2261 permanent_error = 1; 2262 goto finish; 2263 } 2264 } else { 2265 // Construct fixed part of stat file path. 2266 __kmp_str_buf_clear(&stat_path); 2267 __kmp_str_buf_cat(&stat_path, task_path.str, task_path.used); 2268 __kmp_str_buf_cat(&stat_path, "/", 1); 2269 stat_path_fixed_len = stat_path.used; 2270 2271 task_entry = readdir(task_dir); 2272 while (task_entry != NULL) { 2273 // It is a directory and name starts with a digit. 2274 if (proc_entry->d_type == DT_DIR && isdigit(task_entry->d_name[0])) { 2275 ++total_threads; 2276 2277 // Construct complete stat file path. Easiest way would be: 2278 // __kmp_str_buf_print( & stat_path, "%s/%s/stat", task_path.str, 2279 // task_entry->d_name ); 2280 // but seriae of __kmp_str_buf_cat works a bit faster. 2281 stat_path.used = 2282 stat_path_fixed_len; // Reset stat path to its fixed part. 2283 __kmp_str_buf_cat(&stat_path, task_entry->d_name, 2284 KMP_STRLEN(task_entry->d_name)); 2285 __kmp_str_buf_cat(&stat_path, "/stat", 5); 2286 2287 // Note: Low-level API (open/read/close) is used. High-level API 2288 // (fopen/fclose) works ~ 30 % slower. 2289 stat_file = open(stat_path.str, O_RDONLY); 2290 if (stat_file == -1) { 2291 // We cannot report an error because task (thread) can terminate 2292 // just before reading this file. 2293 } else { 2294 /* Content of "stat" file looks like: 2295 24285 (program) S ... 2296 2297 It is a single line (if program name does not include funny 2298 symbols). First number is a thread id, then name of executable 2299 file name in paretheses, then state of the thread. We need just 2300 thread state. 2301 2302 Good news: Length of program name is 15 characters max. Longer 2303 names are truncated. 2304 2305 Thus, we need rather short buffer: 15 chars for program name + 2306 2 parenthesis, + 3 spaces + ~7 digits of pid = 37. 2307 2308 Bad news: Program name may contain special symbols like space, 2309 closing parenthesis, or even new line. This makes parsing 2310 "stat" file not 100 % reliable. In case of fanny program names 2311 parsing may fail (report incorrect thread state). 2312 2313 Parsing "status" file looks more promissing (due to different 2314 file structure and escaping special symbols) but reading and 2315 parsing of "status" file works slower. 2316 -- ln 2317 */ 2318 char buffer[65]; 2319 ssize_t len; 2320 len = read(stat_file, buffer, sizeof(buffer) - 1); 2321 if (len >= 0) { 2322 buffer[len] = 0; 2323 // Using scanf: 2324 // sscanf( buffer, "%*d (%*s) %c ", & state ); 2325 // looks very nice, but searching for a closing parenthesis 2326 // works a bit faster. 2327 char *close_parent = strstr(buffer, ") "); 2328 if (close_parent != NULL) { 2329 char state = *(close_parent + 2); 2330 if (state == 'R') { 2331 ++running_threads; 2332 if (running_threads >= max) { 2333 goto finish; 2334 } 2335 } 2336 } 2337 } 2338 close(stat_file); 2339 stat_file = -1; 2340 } 2341 } 2342 task_entry = readdir(task_dir); 2343 } 2344 closedir(task_dir); 2345 task_dir = NULL; 2346 } 2347 } 2348 proc_entry = readdir(proc_dir); 2349 } 2350 2351 // There _might_ be a timing hole where the thread executing this 2352 // code get skipped in the load balance, and running_threads is 0. 2353 // Assert in the debug builds only!!! 2354 KMP_DEBUG_ASSERT(running_threads > 0); 2355 if (running_threads <= 0) { 2356 running_threads = 1; 2357 } 2358 2359 finish: // Clean up and exit. 2360 if (proc_dir != NULL) { 2361 closedir(proc_dir); 2362 } 2363 __kmp_str_buf_free(&task_path); 2364 if (task_dir != NULL) { 2365 closedir(task_dir); 2366 } 2367 __kmp_str_buf_free(&stat_path); 2368 if (stat_file != -1) { 2369 close(stat_file); 2370 } 2371 2372 glb_running_threads = running_threads; 2373 2374 return running_threads; 2375 2376 } // __kmp_get_load_balance 2377 2378 #endif // KMP_OS_DARWIN 2379 2380 #endif // USE_LOAD_BALANCE 2381 2382 #if !(KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_MIC || \ 2383 ((KMP_OS_LINUX || KMP_OS_DARWIN) && KMP_ARCH_AARCH64) || \ 2384 KMP_ARCH_PPC64 || KMP_ARCH_RISCV64) 2385 2386 // we really only need the case with 1 argument, because CLANG always build 2387 // a struct of pointers to shared variables referenced in the outlined function 2388 int __kmp_invoke_microtask(microtask_t pkfn, int gtid, int tid, int argc, 2389 void *p_argv[] 2390 #if OMPT_SUPPORT 2391 , 2392 void **exit_frame_ptr 2393 #endif 2394 ) { 2395 #if OMPT_SUPPORT 2396 *exit_frame_ptr = OMPT_GET_FRAME_ADDRESS(0); 2397 #endif 2398 2399 switch (argc) { 2400 default: 2401 fprintf(stderr, "Too many args to microtask: %d!\n", argc); 2402 fflush(stderr); 2403 exit(-1); 2404 case 0: 2405 (*pkfn)(>id, &tid); 2406 break; 2407 case 1: 2408 (*pkfn)(>id, &tid, p_argv[0]); 2409 break; 2410 case 2: 2411 (*pkfn)(>id, &tid, p_argv[0], p_argv[1]); 2412 break; 2413 case 3: 2414 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2]); 2415 break; 2416 case 4: 2417 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3]); 2418 break; 2419 case 5: 2420 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4]); 2421 break; 2422 case 6: 2423 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2424 p_argv[5]); 2425 break; 2426 case 7: 2427 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2428 p_argv[5], p_argv[6]); 2429 break; 2430 case 8: 2431 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2432 p_argv[5], p_argv[6], p_argv[7]); 2433 break; 2434 case 9: 2435 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2436 p_argv[5], p_argv[6], p_argv[7], p_argv[8]); 2437 break; 2438 case 10: 2439 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2440 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9]); 2441 break; 2442 case 11: 2443 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2444 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9], p_argv[10]); 2445 break; 2446 case 12: 2447 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2448 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9], p_argv[10], 2449 p_argv[11]); 2450 break; 2451 case 13: 2452 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2453 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9], p_argv[10], 2454 p_argv[11], p_argv[12]); 2455 break; 2456 case 14: 2457 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2458 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9], p_argv[10], 2459 p_argv[11], p_argv[12], p_argv[13]); 2460 break; 2461 case 15: 2462 (*pkfn)(>id, &tid, p_argv[0], p_argv[1], p_argv[2], p_argv[3], p_argv[4], 2463 p_argv[5], p_argv[6], p_argv[7], p_argv[8], p_argv[9], p_argv[10], 2464 p_argv[11], p_argv[12], p_argv[13], p_argv[14]); 2465 break; 2466 } 2467 2468 return 1; 2469 } 2470 2471 #endif 2472 2473 #if KMP_OS_LINUX 2474 // Functions for hidden helper task 2475 namespace { 2476 // Condition variable for initializing hidden helper team 2477 pthread_cond_t hidden_helper_threads_initz_cond_var; 2478 pthread_mutex_t hidden_helper_threads_initz_lock; 2479 volatile int hidden_helper_initz_signaled = FALSE; 2480 2481 // Condition variable for deinitializing hidden helper team 2482 pthread_cond_t hidden_helper_threads_deinitz_cond_var; 2483 pthread_mutex_t hidden_helper_threads_deinitz_lock; 2484 volatile int hidden_helper_deinitz_signaled = FALSE; 2485 2486 // Condition variable for the wrapper function of main thread 2487 pthread_cond_t hidden_helper_main_thread_cond_var; 2488 pthread_mutex_t hidden_helper_main_thread_lock; 2489 volatile int hidden_helper_main_thread_signaled = FALSE; 2490 2491 // Semaphore for worker threads. We don't use condition variable here in case 2492 // that when multiple signals are sent at the same time, only one thread might 2493 // be waken. 2494 sem_t hidden_helper_task_sem; 2495 } // namespace 2496 2497 void __kmp_hidden_helper_worker_thread_wait() { 2498 int status = sem_wait(&hidden_helper_task_sem); 2499 KMP_CHECK_SYSFAIL("sem_wait", status); 2500 } 2501 2502 void __kmp_do_initialize_hidden_helper_threads() { 2503 // Initialize condition variable 2504 int status = 2505 pthread_cond_init(&hidden_helper_threads_initz_cond_var, nullptr); 2506 KMP_CHECK_SYSFAIL("pthread_cond_init", status); 2507 2508 status = pthread_cond_init(&hidden_helper_threads_deinitz_cond_var, nullptr); 2509 KMP_CHECK_SYSFAIL("pthread_cond_init", status); 2510 2511 status = pthread_cond_init(&hidden_helper_main_thread_cond_var, nullptr); 2512 KMP_CHECK_SYSFAIL("pthread_cond_init", status); 2513 2514 status = pthread_mutex_init(&hidden_helper_threads_initz_lock, nullptr); 2515 KMP_CHECK_SYSFAIL("pthread_mutex_init", status); 2516 2517 status = pthread_mutex_init(&hidden_helper_threads_deinitz_lock, nullptr); 2518 KMP_CHECK_SYSFAIL("pthread_mutex_init", status); 2519 2520 status = pthread_mutex_init(&hidden_helper_main_thread_lock, nullptr); 2521 KMP_CHECK_SYSFAIL("pthread_mutex_init", status); 2522 2523 // Initialize the semaphore 2524 status = sem_init(&hidden_helper_task_sem, 0, 0); 2525 KMP_CHECK_SYSFAIL("sem_init", status); 2526 2527 // Create a new thread to finish initialization 2528 pthread_t handle; 2529 status = pthread_create( 2530 &handle, nullptr, 2531 [](void *) -> void * { 2532 __kmp_hidden_helper_threads_initz_routine(); 2533 return nullptr; 2534 }, 2535 nullptr); 2536 KMP_CHECK_SYSFAIL("pthread_create", status); 2537 } 2538 2539 void __kmp_hidden_helper_threads_initz_wait() { 2540 // Initial thread waits here for the completion of the initialization. The 2541 // condition variable will be notified by main thread of hidden helper teams. 2542 int status = pthread_mutex_lock(&hidden_helper_threads_initz_lock); 2543 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2544 2545 if (!TCR_4(hidden_helper_initz_signaled)) { 2546 status = pthread_cond_wait(&hidden_helper_threads_initz_cond_var, 2547 &hidden_helper_threads_initz_lock); 2548 KMP_CHECK_SYSFAIL("pthread_cond_wait", status); 2549 } 2550 2551 status = pthread_mutex_unlock(&hidden_helper_threads_initz_lock); 2552 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2553 } 2554 2555 void __kmp_hidden_helper_initz_release() { 2556 // After all initialization, reset __kmp_init_hidden_helper_threads to false. 2557 int status = pthread_mutex_lock(&hidden_helper_threads_initz_lock); 2558 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2559 2560 status = pthread_cond_signal(&hidden_helper_threads_initz_cond_var); 2561 KMP_CHECK_SYSFAIL("pthread_cond_wait", status); 2562 2563 TCW_SYNC_4(hidden_helper_initz_signaled, TRUE); 2564 2565 status = pthread_mutex_unlock(&hidden_helper_threads_initz_lock); 2566 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2567 } 2568 2569 void __kmp_hidden_helper_main_thread_wait() { 2570 // The main thread of hidden helper team will be blocked here. The 2571 // condition variable can only be signal in the destructor of RTL. 2572 int status = pthread_mutex_lock(&hidden_helper_main_thread_lock); 2573 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2574 2575 if (!TCR_4(hidden_helper_main_thread_signaled)) { 2576 status = pthread_cond_wait(&hidden_helper_main_thread_cond_var, 2577 &hidden_helper_main_thread_lock); 2578 KMP_CHECK_SYSFAIL("pthread_cond_wait", status); 2579 } 2580 2581 status = pthread_mutex_unlock(&hidden_helper_main_thread_lock); 2582 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2583 } 2584 2585 void __kmp_hidden_helper_main_thread_release() { 2586 // The initial thread of OpenMP RTL should call this function to wake up the 2587 // main thread of hidden helper team. 2588 int status = pthread_mutex_lock(&hidden_helper_main_thread_lock); 2589 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2590 2591 status = pthread_cond_signal(&hidden_helper_main_thread_cond_var); 2592 KMP_CHECK_SYSFAIL("pthread_cond_signal", status); 2593 2594 // The hidden helper team is done here 2595 TCW_SYNC_4(hidden_helper_main_thread_signaled, TRUE); 2596 2597 status = pthread_mutex_unlock(&hidden_helper_main_thread_lock); 2598 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2599 } 2600 2601 void __kmp_hidden_helper_worker_thread_signal() { 2602 int status = sem_post(&hidden_helper_task_sem); 2603 KMP_CHECK_SYSFAIL("sem_post", status); 2604 } 2605 2606 void __kmp_hidden_helper_threads_deinitz_wait() { 2607 // Initial thread waits here for the completion of the deinitialization. The 2608 // condition variable will be notified by main thread of hidden helper teams. 2609 int status = pthread_mutex_lock(&hidden_helper_threads_deinitz_lock); 2610 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2611 2612 if (!TCR_4(hidden_helper_deinitz_signaled)) { 2613 status = pthread_cond_wait(&hidden_helper_threads_deinitz_cond_var, 2614 &hidden_helper_threads_deinitz_lock); 2615 KMP_CHECK_SYSFAIL("pthread_cond_wait", status); 2616 } 2617 2618 status = pthread_mutex_unlock(&hidden_helper_threads_deinitz_lock); 2619 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2620 } 2621 2622 void __kmp_hidden_helper_threads_deinitz_release() { 2623 int status = pthread_mutex_lock(&hidden_helper_threads_deinitz_lock); 2624 KMP_CHECK_SYSFAIL("pthread_mutex_lock", status); 2625 2626 status = pthread_cond_signal(&hidden_helper_threads_deinitz_cond_var); 2627 KMP_CHECK_SYSFAIL("pthread_cond_wait", status); 2628 2629 TCW_SYNC_4(hidden_helper_deinitz_signaled, TRUE); 2630 2631 status = pthread_mutex_unlock(&hidden_helper_threads_deinitz_lock); 2632 KMP_CHECK_SYSFAIL("pthread_mutex_unlock", status); 2633 } 2634 #else // KMP_OS_LINUX 2635 void __kmp_hidden_helper_worker_thread_wait() { 2636 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2637 } 2638 2639 void __kmp_do_initialize_hidden_helper_threads() { 2640 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2641 } 2642 2643 void __kmp_hidden_helper_threads_initz_wait() { 2644 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2645 } 2646 2647 void __kmp_hidden_helper_initz_release() { 2648 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2649 } 2650 2651 void __kmp_hidden_helper_main_thread_wait() { 2652 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2653 } 2654 2655 void __kmp_hidden_helper_main_thread_release() { 2656 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2657 } 2658 2659 void __kmp_hidden_helper_worker_thread_signal() { 2660 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2661 } 2662 2663 void __kmp_hidden_helper_threads_deinitz_wait() { 2664 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2665 } 2666 2667 void __kmp_hidden_helper_threads_deinitz_release() { 2668 KMP_ASSERT(0 && "Hidden helper task is not supported on this OS"); 2669 } 2670 #endif // KMP_OS_LINUX 2671 2672 // end of file // 2673