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