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