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