14 #include "kmp_affinity.h"
18 #include "kmp_wait_release.h"
27 enum SYSTEM_INFORMATION_CLASS {
28 SystemProcessInformation = 5
48 SIZE_T PeakVirtualSize;
51 SIZE_T PeakWorkingSetSize;
52 SIZE_T WorkingSetSize;
53 SIZE_T QuotaPeakPagedPoolUsage;
54 SIZE_T QuotaPagedPoolUsage;
55 SIZE_T QuotaPeakNonPagedPoolUsage;
56 SIZE_T QuotaNonPagedPoolUsage;
58 SIZE_T PeakPagefileUsage;
59 SIZE_T PrivatePageCount;
62 struct SYSTEM_THREAD {
63 LARGE_INTEGER KernelTime;
64 LARGE_INTEGER UserTime;
65 LARGE_INTEGER CreateTime;
71 ULONG ContextSwitchCount;
76 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, KernelTime) == 0);
78 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 28);
79 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 52);
81 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 32);
82 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 68);
85 struct SYSTEM_PROCESS_INFORMATION {
86 ULONG NextEntryOffset;
87 ULONG NumberOfThreads;
88 LARGE_INTEGER Reserved[3];
89 LARGE_INTEGER CreateTime;
90 LARGE_INTEGER UserTime;
91 LARGE_INTEGER KernelTime;
92 UNICODE_STRING ImageName;
95 HANDLE ParentProcessId;
98 VM_COUNTERS VMCounters;
99 IO_COUNTERS IOCounters;
100 SYSTEM_THREAD Threads[1];
102 typedef SYSTEM_PROCESS_INFORMATION *PSYSTEM_PROCESS_INFORMATION;
104 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, NextEntryOffset) == 0);
105 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, CreateTime) == 32);
106 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ImageName) == 56);
108 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 68);
109 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 76);
110 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 88);
111 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 136);
112 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 184);
114 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 80);
115 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 96);
116 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 112);
117 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 208);
118 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 256);
121 typedef NTSTATUS(NTAPI *NtQuerySystemInformation_t)(SYSTEM_INFORMATION_CLASS,
122 PVOID, ULONG, PULONG);
123 NtQuerySystemInformation_t NtQuerySystemInformation = NULL;
125 HMODULE ntdll = NULL;
129 static HMODULE kernel32 = NULL;
131 #if KMP_HANDLE_SIGNALS
132 typedef void (*sig_func_t)(int);
133 static sig_func_t __kmp_sighldrs[NSIG];
134 static int __kmp_siginstalled[NSIG];
138 static HANDLE __kmp_monitor_ev;
140 static kmp_int64 __kmp_win32_time;
141 double __kmp_win32_tick;
143 int __kmp_init_runtime = FALSE;
144 CRITICAL_SECTION __kmp_win32_section;
146 void __kmp_win32_mutex_init(kmp_win32_mutex_t *mx) {
147 InitializeCriticalSection(&mx->cs);
149 __kmp_itt_system_object_created(&mx->cs,
"Critical Section");
153 void __kmp_win32_mutex_destroy(kmp_win32_mutex_t *mx) {
154 DeleteCriticalSection(&mx->cs);
157 void __kmp_win32_mutex_lock(kmp_win32_mutex_t *mx) {
158 EnterCriticalSection(&mx->cs);
161 int __kmp_win32_mutex_trylock(kmp_win32_mutex_t *mx) {
162 return TryEnterCriticalSection(&mx->cs);
165 void __kmp_win32_mutex_unlock(kmp_win32_mutex_t *mx) {
166 LeaveCriticalSection(&mx->cs);
169 void __kmp_win32_cond_init(kmp_win32_cond_t *cv) {
170 cv->waiters_count_ = 0;
171 cv->wait_generation_count_ = 0;
172 cv->release_count_ = 0;
175 __kmp_win32_mutex_init(&cv->waiters_count_lock_);
178 cv->event_ = CreateEvent(NULL,
183 __kmp_itt_system_object_created(cv->event_,
"Event");
187 void __kmp_win32_cond_destroy(kmp_win32_cond_t *cv) {
188 __kmp_win32_mutex_destroy(&cv->waiters_count_lock_);
189 __kmp_free_handle(cv->event_);
190 memset(cv,
'\0',
sizeof(*cv));
196 void __kmp_win32_cond_wait(kmp_win32_cond_t *cv, kmp_win32_mutex_t *mx,
197 kmp_info_t *th,
int need_decrease_load) {
202 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
205 cv->waiters_count_++;
208 my_generation = cv->wait_generation_count_;
210 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
211 __kmp_win32_mutex_unlock(mx);
217 WaitForSingleObject(cv->event_, INFINITE);
219 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
224 wait_done = (cv->release_count_ > 0) &&
225 (cv->wait_generation_count_ != my_generation);
227 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
235 __kmp_win32_mutex_lock(mx);
236 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
238 cv->waiters_count_--;
239 cv->release_count_--;
241 last_waiter = (cv->release_count_ == 0);
243 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
247 ResetEvent(cv->event_);
251 void __kmp_win32_cond_broadcast(kmp_win32_cond_t *cv) {
252 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
254 if (cv->waiters_count_ > 0) {
255 SetEvent(cv->event_);
258 cv->release_count_ = cv->waiters_count_;
261 cv->wait_generation_count_++;
264 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
267 void __kmp_win32_cond_signal(kmp_win32_cond_t *cv) {
268 __kmp_win32_cond_broadcast(cv);
271 void __kmp_enable(
int new_state) {
272 if (__kmp_init_runtime)
273 LeaveCriticalSection(&__kmp_win32_section);
276 void __kmp_disable(
int *old_state) {
279 if (__kmp_init_runtime)
280 EnterCriticalSection(&__kmp_win32_section);
283 void __kmp_suspend_initialize(
void) {
286 static void __kmp_suspend_initialize_thread(kmp_info_t *th) {
287 if (!TCR_4(th->th.th_suspend_init)) {
290 __kmp_win32_cond_init(&th->th.th_suspend_cv);
291 __kmp_win32_mutex_init(&th->th.th_suspend_mx);
292 TCW_4(th->th.th_suspend_init, TRUE);
296 void __kmp_suspend_uninitialize_thread(kmp_info_t *th) {
297 if (TCR_4(th->th.th_suspend_init)) {
300 __kmp_win32_cond_destroy(&th->th.th_suspend_cv);
301 __kmp_win32_mutex_destroy(&th->th.th_suspend_mx);
302 TCW_4(th->th.th_suspend_init, FALSE);
306 int __kmp_try_suspend_mx(kmp_info_t *th) {
307 return __kmp_win32_mutex_trylock(&th->th.th_suspend_mx);
310 void __kmp_lock_suspend_mx(kmp_info_t *th) {
311 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
314 void __kmp_unlock_suspend_mx(kmp_info_t *th) {
315 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
321 static inline void __kmp_suspend_template(
int th_gtid, C *flag) {
322 kmp_info_t *th = __kmp_threads[th_gtid];
324 typename C::flag_t old_spin;
326 KF_TRACE(30, (
"__kmp_suspend_template: T#%d enter for flag's loc(%p)\n",
327 th_gtid, flag->get()));
329 __kmp_suspend_initialize_thread(th);
330 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
332 KF_TRACE(10, (
"__kmp_suspend_template: T#%d setting sleep bit for flag's"
334 th_gtid, flag->get()));
338 old_spin = flag->set_sleeping();
340 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME &&
341 __kmp_pause_status != kmp_soft_paused) {
342 flag->unset_sleeping();
343 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
348 KF_TRACE(5, (
"__kmp_suspend_template: T#%d set sleep bit for flag's"
350 th_gtid, flag->get(), *(flag->get())));
352 if (flag->done_check_val(old_spin)) {
353 old_spin = flag->unset_sleeping();
354 KF_TRACE(5, (
"__kmp_suspend_template: T#%d false alarm, reset sleep bit "
355 "for flag's loc(%p)\n",
356 th_gtid, flag->get()));
359 __kmp_suspend_count++;
364 int deactivated = FALSE;
365 TCW_PTR(th->th.th_sleep_loc, (
void *)flag);
366 while (flag->is_sleeping()) {
367 KF_TRACE(15, (
"__kmp_suspend_template: T#%d about to perform "
368 "kmp_win32_cond_wait()\n",
373 th->th.th_active = FALSE;
374 if (th->th.th_active_in_pool) {
375 th->th.th_active_in_pool = FALSE;
376 KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth);
377 KMP_DEBUG_ASSERT(TCR_4(__kmp_thread_pool_active_nth) >= 0);
381 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
384 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
389 if (flag->is_sleeping()) {
391 (
"__kmp_suspend_template: T#%d spurious wakeup\n", th_gtid));
399 th->th.th_active = TRUE;
400 if (TCR_4(th->th.th_in_pool)) {
401 KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth);
402 th->th.th_active_in_pool = TRUE;
407 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
409 KF_TRACE(30, (
"__kmp_suspend_template: T#%d exit\n", th_gtid));
412 void __kmp_suspend_32(
int th_gtid, kmp_flag_32 *flag) {
413 __kmp_suspend_template(th_gtid, flag);
415 void __kmp_suspend_64(
int th_gtid, kmp_flag_64 *flag) {
416 __kmp_suspend_template(th_gtid, flag);
418 void __kmp_suspend_oncore(
int th_gtid, kmp_flag_oncore *flag) {
419 __kmp_suspend_template(th_gtid, flag);
425 static inline void __kmp_resume_template(
int target_gtid, C *flag) {
426 kmp_info_t *th = __kmp_threads[target_gtid];
430 int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1;
433 KF_TRACE(30, (
"__kmp_resume_template: T#%d wants to wakeup T#%d enter\n",
436 __kmp_suspend_initialize_thread(th);
437 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
440 flag = (C *)th->th.th_sleep_loc;
445 if (!flag || flag->get_type() != flag->get_ptr_type()) {
448 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already "
449 "awake: flag's loc(%p)\n",
450 gtid, target_gtid, NULL));
451 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
454 typename C::flag_t old_spin = flag->unset_sleeping();
455 if (!flag->is_sleeping_val(old_spin)) {
456 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already "
457 "awake: flag's loc(%p): %u => %u\n",
458 gtid, target_gtid, flag->get(), old_spin, *(flag->get())));
459 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
463 TCW_PTR(th->th.th_sleep_loc, NULL);
464 KF_TRACE(5, (
"__kmp_resume_template: T#%d about to wakeup T#%d, reset sleep "
465 "bit for flag's loc(%p)\n",
466 gtid, target_gtid, flag->get()));
468 __kmp_win32_cond_signal(&th->th.th_suspend_cv);
469 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
471 KF_TRACE(30, (
"__kmp_resume_template: T#%d exiting after signaling wake up"
476 void __kmp_resume_32(
int target_gtid, kmp_flag_32 *flag) {
477 __kmp_resume_template(target_gtid, flag);
479 void __kmp_resume_64(
int target_gtid, kmp_flag_64 *flag) {
480 __kmp_resume_template(target_gtid, flag);
482 void __kmp_resume_oncore(
int target_gtid, kmp_flag_oncore *flag) {
483 __kmp_resume_template(target_gtid, flag);
486 void __kmp_yield(
int cond) {
491 void __kmp_gtid_set_specific(
int gtid) {
492 if (__kmp_init_gtid) {
493 KA_TRACE(50, (
"__kmp_gtid_set_specific: T#%d key:%d\n", gtid,
494 __kmp_gtid_threadprivate_key));
495 if (!TlsSetValue(__kmp_gtid_threadprivate_key, (LPVOID)(gtid + 1)))
496 KMP_FATAL(TLSSetValueFailed);
498 KA_TRACE(50, (
"__kmp_gtid_set_specific: runtime shutdown, returning\n"));
502 int __kmp_gtid_get_specific() {
504 if (!__kmp_init_gtid) {
505 KA_TRACE(50, (
"__kmp_gtid_get_specific: runtime shutdown, returning "
506 "KMP_GTID_SHUTDOWN\n"));
507 return KMP_GTID_SHUTDOWN;
509 gtid = (int)(kmp_intptr_t)TlsGetValue(__kmp_gtid_threadprivate_key);
515 KA_TRACE(50, (
"__kmp_gtid_get_specific: key:%d gtid:%d\n",
516 __kmp_gtid_threadprivate_key, gtid));
520 void __kmp_affinity_bind_thread(
int proc) {
521 if (__kmp_num_proc_groups > 1) {
525 KMP_DEBUG_ASSERT((proc >= 0) && (proc < (__kmp_num_proc_groups * CHAR_BIT *
526 sizeof(DWORD_PTR))));
527 ga.Group = proc / (CHAR_BIT *
sizeof(DWORD_PTR));
528 ga.Mask = (
unsigned long long)1 << (proc % (CHAR_BIT *
sizeof(DWORD_PTR)));
529 ga.Reserved[0] = ga.Reserved[1] = ga.Reserved[2] = 0;
531 KMP_DEBUG_ASSERT(__kmp_SetThreadGroupAffinity != NULL);
532 if (__kmp_SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) == 0) {
533 DWORD error = GetLastError();
534 if (__kmp_affinity_verbose) {
535 kmp_msg_t err_code = KMP_ERR(error);
536 __kmp_msg(kmp_ms_warning, KMP_MSG(CantSetThreadAffMask), err_code,
538 if (__kmp_generate_warnings == kmp_warnings_off) {
539 __kmp_str_free(&err_code.str);
544 kmp_affin_mask_t *mask;
545 KMP_CPU_ALLOC_ON_STACK(mask);
547 KMP_CPU_SET(proc, mask);
548 __kmp_set_system_affinity(mask, TRUE);
549 KMP_CPU_FREE_FROM_STACK(mask);
553 void __kmp_affinity_determine_capable(
const char *env_var) {
556 #if KMP_GROUP_AFFINITY
557 KMP_AFFINITY_ENABLE(__kmp_num_proc_groups *
sizeof(DWORD_PTR));
559 KMP_AFFINITY_ENABLE(
sizeof(DWORD_PTR));
562 KA_TRACE(10, (
"__kmp_affinity_determine_capable: "
563 "Windows* OS affinity interface functional (mask size = "
564 "%" KMP_SIZE_T_SPEC
").\n",
565 __kmp_affin_mask_size));
568 double __kmp_read_cpu_time(
void) {
569 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
575 status = GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime,
576 &KernelTime, &UserTime);
581 sec += KernelTime.dwHighDateTime;
582 sec += UserTime.dwHighDateTime;
585 sec *= (double)(1 << 16) * (double)(1 << 16);
587 sec += KernelTime.dwLowDateTime;
588 sec += UserTime.dwLowDateTime;
590 cpu_time += (sec * 100.0) / KMP_NSEC_PER_SEC;
596 int __kmp_read_system_info(
struct kmp_sys_info *info) {
609 void __kmp_runtime_initialize(
void) {
614 if (__kmp_init_runtime) {
622 UINT err_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
624 BOOL ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
625 GET_MODULE_HANDLE_EX_FLAG_PIN,
626 (LPCTSTR)&__kmp_serial_initialize, &h);
627 KMP_DEBUG_ASSERT2(h && ret,
"OpenMP RTL cannot find itself loaded");
628 SetErrorMode(err_mode);
629 KA_TRACE(10, (
"__kmp_runtime_initialize: dynamic library pinned\n"));
633 InitializeCriticalSection(&__kmp_win32_section);
635 __kmp_itt_system_object_created(&__kmp_win32_section,
"Critical Section");
637 __kmp_initialize_system_tick();
639 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64)
640 if (!__kmp_cpuinfo.initialized) {
641 __kmp_query_cpuid(&__kmp_cpuinfo);
646 #if KMP_OS_WINDOWS && !KMP_DYNAMIC_LIB
661 __kmp_tls_gtid_min = 0;
663 __kmp_tls_gtid_min = KMP_TLS_GTID_MIN;
667 if (!__kmp_gtid_threadprivate_key) {
668 __kmp_gtid_threadprivate_key = TlsAlloc();
669 if (__kmp_gtid_threadprivate_key == TLS_OUT_OF_INDEXES) {
670 KMP_FATAL(TLSOutOfIndexes);
678 __kmp_str_buf_init(&path);
679 path_size = GetSystemDirectory(path.str, path.size);
680 KMP_DEBUG_ASSERT(path_size > 0);
681 if (path_size >= path.size) {
683 __kmp_str_buf_reserve(&path, path_size);
684 path_size = GetSystemDirectory(path.str, path.size);
685 KMP_DEBUG_ASSERT(path_size > 0);
687 if (path_size > 0 && path_size < path.size) {
690 path.used = path_size;
691 __kmp_str_buf_print(&path,
"\\%s",
"ntdll.dll");
694 ntdll = GetModuleHandle(path.str);
697 KMP_DEBUG_ASSERT(ntdll != NULL);
699 NtQuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(
700 ntdll,
"NtQuerySystemInformation");
702 KMP_DEBUG_ASSERT(NtQuerySystemInformation != NULL);
704 #if KMP_GROUP_AFFINITY
707 if (path_size > 0 && path_size < path.size) {
710 path.used = path_size;
711 __kmp_str_buf_print(&path,
"\\%s",
"kernel32.dll");
714 kernel32 = GetModuleHandle(path.str);
715 KA_TRACE(10, (
"__kmp_runtime_initialize: kernel32.dll = %s\n", path.str));
719 if (kernel32 != NULL) {
720 __kmp_GetActiveProcessorCount =
721 (kmp_GetActiveProcessorCount_t)GetProcAddress(
722 kernel32,
"GetActiveProcessorCount");
723 __kmp_GetActiveProcessorGroupCount =
724 (kmp_GetActiveProcessorGroupCount_t)GetProcAddress(
725 kernel32,
"GetActiveProcessorGroupCount");
726 __kmp_GetThreadGroupAffinity =
727 (kmp_GetThreadGroupAffinity_t)GetProcAddress(
728 kernel32,
"GetThreadGroupAffinity");
729 __kmp_SetThreadGroupAffinity =
730 (kmp_SetThreadGroupAffinity_t)GetProcAddress(
731 kernel32,
"SetThreadGroupAffinity");
733 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_GetActiveProcessorCount"
735 __kmp_GetActiveProcessorCount));
736 KA_TRACE(10, (
"__kmp_runtime_initialize: "
737 "__kmp_GetActiveProcessorGroupCount = %p\n",
738 __kmp_GetActiveProcessorGroupCount));
739 KA_TRACE(10, (
"__kmp_runtime_initialize:__kmp_GetThreadGroupAffinity"
741 __kmp_GetThreadGroupAffinity));
742 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_SetThreadGroupAffinity"
744 __kmp_SetThreadGroupAffinity));
745 KA_TRACE(10, (
"__kmp_runtime_initialize: sizeof(kmp_affin_mask_t) = %d\n",
746 sizeof(kmp_affin_mask_t)));
753 if ((__kmp_GetActiveProcessorCount != NULL) &&
754 (__kmp_GetActiveProcessorGroupCount != NULL) &&
755 (__kmp_GetThreadGroupAffinity != NULL) &&
756 (__kmp_SetThreadGroupAffinity != NULL) &&
757 ((__kmp_num_proc_groups = __kmp_GetActiveProcessorGroupCount()) >
762 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups"
764 __kmp_num_proc_groups));
768 for (i = 0; i < __kmp_num_proc_groups; i++) {
769 DWORD size = __kmp_GetActiveProcessorCount(i);
771 KA_TRACE(10, (
"__kmp_runtime_initialize: proc group %d size = %d\n",
775 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups"
777 __kmp_num_proc_groups));
781 if (__kmp_num_proc_groups <= 1) {
782 GetSystemInfo(&info);
783 __kmp_xproc = info.dwNumberOfProcessors;
786 GetSystemInfo(&info);
787 __kmp_xproc = info.dwNumberOfProcessors;
792 if (__kmp_xproc <= 0) {
797 (
"__kmp_runtime_initialize: total processors = %d\n", __kmp_xproc));
799 __kmp_str_buf_free(&path);
802 __kmp_itt_initialize();
805 __kmp_init_runtime = TRUE;
808 void __kmp_runtime_destroy(
void) {
809 if (!__kmp_init_runtime) {
819 KA_TRACE(40, (
"__kmp_runtime_destroy\n"));
821 if (__kmp_gtid_threadprivate_key) {
822 TlsFree(__kmp_gtid_threadprivate_key);
823 __kmp_gtid_threadprivate_key = 0;
826 __kmp_affinity_uninitialize();
827 DeleteCriticalSection(&__kmp_win32_section);
830 NtQuerySystemInformation = NULL;
834 __kmp_GetActiveProcessorCount = NULL;
835 __kmp_GetActiveProcessorGroupCount = NULL;
836 __kmp_GetThreadGroupAffinity = NULL;
837 __kmp_SetThreadGroupAffinity = NULL;
838 #endif // KMP_ARCH_X86_64
840 __kmp_init_runtime = FALSE;
843 void __kmp_terminate_thread(
int gtid) {
844 kmp_info_t *th = __kmp_threads[gtid];
849 KA_TRACE(10, (
"__kmp_terminate_thread: kill (%d)\n", gtid));
851 if (TerminateThread(th->th.th_info.ds.ds_thread, (DWORD)-1) == FALSE) {
854 __kmp_free_handle(th->th.th_info.ds.ds_thread);
857 void __kmp_clear_system_time(
void) {
860 status = QueryPerformanceCounter(&time);
861 __kmp_win32_time = (kmp_int64)time.QuadPart;
864 void __kmp_initialize_system_tick(
void) {
869 status = QueryPerformanceFrequency(&freq);
871 DWORD error = GetLastError();
872 __kmp_fatal(KMP_MSG(FunctionError,
"QueryPerformanceFrequency()"),
873 KMP_ERR(error), __kmp_msg_null);
876 __kmp_win32_tick = ((double)1.0) / (double)freq.QuadPart;
883 void __kmp_elapsed(
double *t) {
886 status = QueryPerformanceCounter(&now);
887 *t = ((double)now.QuadPart) * __kmp_win32_tick;
892 void __kmp_elapsed_tick(
double *t) { *t = __kmp_win32_tick; }
894 void __kmp_read_system_time(
double *delta) {
899 status = QueryPerformanceCounter(&now);
901 *delta = ((double)(((kmp_int64)now.QuadPart) - __kmp_win32_time)) *
907 kmp_uint64 __kmp_now_nsec() {
909 QueryPerformanceCounter(&now);
910 return 1e9 * __kmp_win32_tick * now.QuadPart;
914 void *__stdcall __kmp_launch_worker(
void *arg) {
915 volatile void *stack_data;
918 kmp_info_t *this_thr = (kmp_info_t *)arg;
921 gtid = this_thr->th.th_info.ds.ds_gtid;
922 __kmp_gtid_set_specific(gtid);
923 #ifdef KMP_TDATA_GTID
924 #error "This define causes problems with LoadLibrary() + declspec(thread) " \
925 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \
926 "reference: http://support.microsoft.com/kb/118816"
931 __kmp_itt_thread_name(gtid);
934 __kmp_affinity_set_init_mask(gtid, FALSE);
936 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
938 __kmp_clear_x87_fpu_status_word();
939 __kmp_load_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word);
940 __kmp_load_mxcsr(&__kmp_init_mxcsr);
943 if (__kmp_stkoffset > 0 && gtid > 0) {
944 padding = KMP_ALLOCA(gtid * __kmp_stkoffset);
947 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
948 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
949 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
951 if (TCR_4(__kmp_gtid_mode) <
953 TCW_PTR(this_thr->th.th_info.ds.ds_stackbase, &stack_data);
954 KMP_ASSERT(this_thr->th.th_info.ds.ds_stackgrow == FALSE);
955 __kmp_check_stack_overlap(this_thr);
958 exit_val = __kmp_launch_thread(this_thr);
959 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
960 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
968 void *__stdcall __kmp_launch_monitor(
void *arg) {
970 kmp_thread_t monitor;
973 kmp_info_t *this_thr = (kmp_info_t *)arg;
975 KMP_DEBUG_ASSERT(__kmp_init_monitor);
976 TCW_4(__kmp_init_monitor, 2);
978 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
979 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
982 KA_TRACE(10, (
"__kmp_launch_monitor: launched\n"));
984 monitor = GetCurrentThread();
987 status = SetThreadPriority(monitor, THREAD_PRIORITY_HIGHEST);
989 DWORD error = GetLastError();
990 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
994 __kmp_gtid_set_specific(KMP_GTID_MONITOR);
995 #ifdef KMP_TDATA_GTID
996 #error "This define causes problems with LoadLibrary() + declspec(thread) " \
997 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \
998 "reference: http://support.microsoft.com/kb/118816"
1003 __kmp_itt_thread_ignore();
1009 interval = (1000 / __kmp_monitor_wakeups);
1011 while (!TCR_4(__kmp_global.g.g_done)) {
1014 KA_TRACE(15, (
"__kmp_launch_monitor: update\n"));
1016 wait_status = WaitForSingleObject(__kmp_monitor_ev, interval);
1018 if (wait_status == WAIT_TIMEOUT) {
1019 TCW_4(__kmp_global.g.g_time.dt.t_value,
1020 TCR_4(__kmp_global.g.g_time.dt.t_value) + 1);
1026 KA_TRACE(10, (
"__kmp_launch_monitor: finished\n"));
1028 status = SetThreadPriority(monitor, THREAD_PRIORITY_NORMAL);
1030 DWORD error = GetLastError();
1031 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
1034 if (__kmp_global.g.g_abort != 0) {
1039 KA_TRACE(10, (
"__kmp_launch_monitor: terminate sig=%d\n",
1040 (__kmp_global.g.g_abort)));
1045 for (gtid = 1; gtid < __kmp_threads_capacity; ++gtid)
1046 __kmp_terminate_thread(gtid);
1053 (
"__kmp_launch_monitor: raise sig=%d\n", __kmp_global.g.g_abort));
1055 if (__kmp_global.g.g_abort > 0) {
1056 raise(__kmp_global.g.g_abort);
1060 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
1067 void __kmp_create_worker(
int gtid, kmp_info_t *th,
size_t stack_size) {
1068 kmp_thread_t handle;
1071 KA_TRACE(10, (
"__kmp_create_worker: try to create thread (%d)\n", gtid));
1073 th->th.th_info.ds.ds_gtid = gtid;
1075 if (KMP_UBER_GTID(gtid)) {
1083 rc = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1084 GetCurrentProcess(), &th->th.th_info.ds.ds_thread, 0,
1085 FALSE, DUPLICATE_SAME_ACCESS);
1087 KA_TRACE(10, (
" __kmp_create_worker: ROOT Handle duplicated, th = %p, "
1088 "handle = %" KMP_UINTPTR_SPEC
"\n",
1089 (LPVOID)th, th->th.th_info.ds.ds_thread));
1090 th->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1092 if (TCR_4(__kmp_gtid_mode) < 2) {
1094 TCW_PTR(th->th.th_info.ds.ds_stackbase, &stack_data);
1095 TCW_PTR(th->th.th_info.ds.ds_stacksize, 0);
1096 TCW_4(th->th.th_info.ds.ds_stackgrow, TRUE);
1097 __kmp_check_stack_overlap(th);
1104 (
"__kmp_create_worker: stack_size = %" KMP_SIZE_T_SPEC
" bytes\n",
1107 stack_size += gtid * __kmp_stkoffset;
1109 TCW_PTR(th->th.th_info.ds.ds_stacksize, stack_size);
1110 TCW_4(th->th.th_info.ds.ds_stackgrow, FALSE);
1113 (
"__kmp_create_worker: (before) stack_size = %" KMP_SIZE_T_SPEC
1114 " bytes, &__kmp_launch_worker = %p, th = %p, &idThread = %p\n",
1115 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1116 (LPVOID)th, &idThread));
1118 handle = CreateThread(
1119 NULL, (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)__kmp_launch_worker,
1120 (LPVOID)th, STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1123 (
"__kmp_create_worker: (after) stack_size = %" KMP_SIZE_T_SPEC
1124 " bytes, &__kmp_launch_worker = %p, th = %p, "
1125 "idThread = %u, handle = %" KMP_UINTPTR_SPEC
"\n",
1126 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1127 (LPVOID)th, idThread, handle));
1130 DWORD error = GetLastError();
1131 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1133 th->th.th_info.ds.ds_thread = handle;
1139 KA_TRACE(10, (
"__kmp_create_worker: done creating thread (%d)\n", gtid));
1142 int __kmp_still_running(kmp_info_t *th) {
1143 return (WAIT_TIMEOUT == WaitForSingleObject(th->th.th_info.ds.ds_thread, 0));
1147 void __kmp_create_monitor(kmp_info_t *th) {
1148 kmp_thread_t handle;
1150 int ideal, new_ideal;
1152 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) {
1154 KA_TRACE(10, (
"__kmp_create_monitor: skipping monitor thread because of "
1155 "MAX blocktime\n"));
1156 th->th.th_info.ds.ds_tid = 0;
1157 th->th.th_info.ds.ds_gtid = 0;
1158 TCW_4(__kmp_init_monitor, 2);
1161 KA_TRACE(10, (
"__kmp_create_monitor: try to create monitor\n"));
1165 __kmp_monitor_ev = CreateEvent(NULL, TRUE, FALSE, NULL);
1166 if (__kmp_monitor_ev == NULL) {
1167 DWORD error = GetLastError();
1168 __kmp_fatal(KMP_MSG(CantCreateEvent), KMP_ERR(error), __kmp_msg_null);
1171 __kmp_itt_system_object_created(__kmp_monitor_ev,
"Event");
1174 th->th.th_info.ds.ds_tid = KMP_GTID_MONITOR;
1175 th->th.th_info.ds.ds_gtid = KMP_GTID_MONITOR;
1179 if (__kmp_monitor_stksize == 0) {
1180 __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE;
1182 if (__kmp_monitor_stksize < __kmp_sys_min_stksize) {
1183 __kmp_monitor_stksize = __kmp_sys_min_stksize;
1186 KA_TRACE(10, (
"__kmp_create_monitor: requested stacksize = %d bytes\n",
1187 (
int)__kmp_monitor_stksize));
1189 TCW_4(__kmp_global.g.g_time.dt.t_value, 0);
1192 CreateThread(NULL, (SIZE_T)__kmp_monitor_stksize,
1193 (LPTHREAD_START_ROUTINE)__kmp_launch_monitor, (LPVOID)th,
1194 STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1196 DWORD error = GetLastError();
1197 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1199 th->th.th_info.ds.ds_thread = handle;
1203 KA_TRACE(10, (
"__kmp_create_monitor: monitor created %p\n",
1204 (
void *)th->th.th_info.ds.ds_thread));
1214 int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val) {
1216 rc = GetExitCodeThread(th->th.th_info.ds.ds_thread, exit_val);
1218 DWORD error = GetLastError();
1219 __kmp_fatal(KMP_MSG(FunctionError,
"GetExitCodeThread()"), KMP_ERR(error),
1222 return (*exit_val == STILL_ACTIVE);
1225 void __kmp_exit_thread(
int exit_status) {
1226 ExitThread(exit_status);
1230 static void __kmp_reap_common(kmp_info_t *th) {
1236 10, (
"__kmp_reap_common: try to reap (%d)\n", th->th.th_info.ds.ds_gtid));
1253 KMP_FSYNC_SPIN_INIT(obj, (
void *)&th->th.th_info.ds.ds_alive);
1255 KMP_INIT_YIELD(spins);
1258 KMP_FSYNC_SPIN_PREPARE(obj);
1260 __kmp_is_thread_alive(th, &exit_val);
1261 KMP_YIELD(TCR_4(__kmp_nth) > __kmp_avail_proc);
1262 KMP_YIELD_SPIN(spins);
1263 }
while (exit_val == STILL_ACTIVE && TCR_4(th->th.th_info.ds.ds_alive));
1265 if (exit_val == STILL_ACTIVE) {
1266 KMP_FSYNC_CANCEL(obj);
1268 KMP_FSYNC_SPIN_ACQUIRED(obj);
1273 __kmp_free_handle(th->th.th_info.ds.ds_thread);
1278 if (exit_val == STILL_ACTIVE) {
1279 KA_TRACE(1, (
"__kmp_reap_common: thread still active.\n"));
1280 }
else if ((
void *)exit_val != (
void *)th) {
1281 KA_TRACE(1, (
"__kmp_reap_common: ExitProcess / TerminateThread used?\n"));
1285 (
"__kmp_reap_common: done reaping (%d), handle = %" KMP_UINTPTR_SPEC
1287 th->th.th_info.ds.ds_gtid, th->th.th_info.ds.ds_thread));
1289 th->th.th_info.ds.ds_thread = 0;
1290 th->th.th_info.ds.ds_tid = KMP_GTID_DNE;
1291 th->th.th_info.ds.ds_gtid = KMP_GTID_DNE;
1292 th->th.th_info.ds.ds_thread_id = 0;
1298 void __kmp_reap_monitor(kmp_info_t *th) {
1301 KA_TRACE(10, (
"__kmp_reap_monitor: try to reap %p\n",
1302 (
void *)th->th.th_info.ds.ds_thread));
1307 KMP_DEBUG_ASSERT(th->th.th_info.ds.ds_tid == th->th.th_info.ds.ds_gtid);
1308 if (th->th.th_info.ds.ds_gtid != KMP_GTID_MONITOR) {
1309 KA_TRACE(10, (
"__kmp_reap_monitor: monitor did not start, returning\n"));
1315 status = SetEvent(__kmp_monitor_ev);
1316 if (status == FALSE) {
1317 DWORD error = GetLastError();
1318 __kmp_fatal(KMP_MSG(CantSetEvent), KMP_ERR(error), __kmp_msg_null);
1320 KA_TRACE(10, (
"__kmp_reap_monitor: reaping thread (%d)\n",
1321 th->th.th_info.ds.ds_gtid));
1322 __kmp_reap_common(th);
1324 __kmp_free_handle(__kmp_monitor_ev);
1330 void __kmp_reap_worker(kmp_info_t *th) {
1331 KA_TRACE(10, (
"__kmp_reap_worker: reaping thread (%d)\n",
1332 th->th.th_info.ds.ds_gtid));
1333 __kmp_reap_common(th);
1336 #if KMP_HANDLE_SIGNALS
1338 static void __kmp_team_handler(
int signo) {
1339 if (__kmp_global.g.g_abort == 0) {
1341 if (__kmp_debug_buf) {
1342 __kmp_dump_debug_buffer();
1345 TCW_4(__kmp_global.g.g_abort, signo);
1347 TCW_4(__kmp_global.g.g_done, TRUE);
1352 static sig_func_t __kmp_signal(
int signum, sig_func_t handler) {
1353 sig_func_t old = signal(signum, handler);
1354 if (old == SIG_ERR) {
1356 __kmp_fatal(KMP_MSG(FunctionError,
"signal"), KMP_ERR(error),
1362 static void __kmp_install_one_handler(
int sig, sig_func_t handler,
1363 int parallel_init) {
1366 KB_TRACE(60, (
"__kmp_install_one_handler: called: sig=%d\n", sig));
1367 if (parallel_init) {
1368 old = __kmp_signal(sig, handler);
1370 if (old == __kmp_sighldrs[sig]) {
1371 __kmp_siginstalled[sig] = 1;
1373 old = __kmp_signal(sig, old);
1379 old = __kmp_signal(sig, SIG_DFL);
1380 __kmp_sighldrs[sig] = old;
1381 __kmp_signal(sig, old);
1386 static void __kmp_remove_one_handler(
int sig) {
1387 if (__kmp_siginstalled[sig]) {
1390 KB_TRACE(60, (
"__kmp_remove_one_handler: called: sig=%d\n", sig));
1391 old = __kmp_signal(sig, __kmp_sighldrs[sig]);
1392 if (old != __kmp_team_handler) {
1393 KB_TRACE(10, (
"__kmp_remove_one_handler: oops, not our handler, "
1394 "restoring: sig=%d\n",
1396 old = __kmp_signal(sig, old);
1398 __kmp_sighldrs[sig] = NULL;
1399 __kmp_siginstalled[sig] = 0;
1404 void __kmp_install_signals(
int parallel_init) {
1405 KB_TRACE(10, (
"__kmp_install_signals: called\n"));
1406 if (!__kmp_handle_signals) {
1407 KB_TRACE(10, (
"__kmp_install_signals: KMP_HANDLE_SIGNALS is false - "
1408 "handlers not installed\n"));
1411 __kmp_install_one_handler(SIGINT, __kmp_team_handler, parallel_init);
1412 __kmp_install_one_handler(SIGILL, __kmp_team_handler, parallel_init);
1413 __kmp_install_one_handler(SIGABRT, __kmp_team_handler, parallel_init);
1414 __kmp_install_one_handler(SIGFPE, __kmp_team_handler, parallel_init);
1415 __kmp_install_one_handler(SIGSEGV, __kmp_team_handler, parallel_init);
1416 __kmp_install_one_handler(SIGTERM, __kmp_team_handler, parallel_init);
1419 void __kmp_remove_signals(
void) {
1421 KB_TRACE(10, (
"__kmp_remove_signals: called\n"));
1422 for (sig = 1; sig < NSIG; ++sig) {
1423 __kmp_remove_one_handler(sig);
1427 #endif // KMP_HANDLE_SIGNALS
1430 void __kmp_thread_sleep(
int millis) {
1433 status = SleepEx((DWORD)millis, FALSE);
1435 DWORD error = GetLastError();
1436 __kmp_fatal(KMP_MSG(FunctionError,
"SleepEx()"), KMP_ERR(error),
1442 int __kmp_is_address_mapped(
void *addr) {
1444 MEMORY_BASIC_INFORMATION lpBuffer;
1447 dwLength =
sizeof(MEMORY_BASIC_INFORMATION);
1449 status = VirtualQuery(addr, &lpBuffer, dwLength);
1451 return !(((lpBuffer.State == MEM_RESERVE) || (lpBuffer.State == MEM_FREE)) ||
1452 ((lpBuffer.Protect == PAGE_NOACCESS) ||
1453 (lpBuffer.Protect == PAGE_EXECUTE)));
1456 kmp_uint64 __kmp_hardware_timestamp(
void) {
1459 QueryPerformanceCounter((LARGE_INTEGER *)&r);
1464 void __kmp_free_handle(kmp_thread_t tHandle) {
1468 rc = CloseHandle(tHandle);
1470 DWORD error = GetLastError();
1471 __kmp_fatal(KMP_MSG(CantCloseHandle), KMP_ERR(error), __kmp_msg_null);
1475 int __kmp_get_load_balance(
int max) {
1476 static ULONG glb_buff_size = 100 * 1024;
1479 static int glb_running_threads = 0;
1480 static double glb_call_time = 0;
1482 int running_threads = 0;
1483 NTSTATUS status = 0;
1484 ULONG buff_size = 0;
1485 ULONG info_size = 0;
1486 void *buffer = NULL;
1487 PSYSTEM_PROCESS_INFORMATION spi = NULL;
1490 double call_time = 0.0;
1492 __kmp_elapsed(&call_time);
1494 if (glb_call_time &&
1495 (call_time - glb_call_time < __kmp_load_balance_interval)) {
1496 running_threads = glb_running_threads;
1499 glb_call_time = call_time;
1502 if (NtQuerySystemInformation == NULL) {
1503 running_threads = -1;
1514 buff_size = glb_buff_size;
1516 buff_size = 2 * buff_size;
1519 buffer = KMP_INTERNAL_REALLOC(buffer, buff_size);
1520 if (buffer == NULL) {
1521 running_threads = -1;
1524 status = NtQuerySystemInformation(SystemProcessInformation, buffer,
1525 buff_size, &info_size);
1528 }
while (status == STATUS_INFO_LENGTH_MISMATCH);
1529 glb_buff_size = buff_size;
1531 #define CHECK(cond) \
1533 KMP_DEBUG_ASSERT(cond); \
1535 running_threads = -1; \
1540 CHECK(buff_size >= info_size);
1541 spi = PSYSTEM_PROCESS_INFORMATION(buffer);
1543 ptrdiff_t offset = uintptr_t(spi) - uintptr_t(buffer);
1544 CHECK(0 <= offset &&
1545 offset +
sizeof(SYSTEM_PROCESS_INFORMATION) < info_size);
1546 HANDLE pid = spi->ProcessId;
1547 ULONG num = spi->NumberOfThreads;
1550 sizeof(SYSTEM_PROCESS_INFORMATION) +
sizeof(SYSTEM_THREAD) * (num - 1);
1551 CHECK(offset + spi_size <
1553 if (spi->NextEntryOffset != 0) {
1555 spi->NextEntryOffset);
1561 for (
int i = 0; i < num; ++i) {
1562 THREAD_STATE state = spi->Threads[i].State;
1565 if (state == StateRunning) {
1569 if (running_threads >= max) {
1575 if (spi->NextEntryOffset == 0) {
1578 spi = PSYSTEM_PROCESS_INFORMATION(uintptr_t(spi) + spi->NextEntryOffset);
1585 if (buffer != NULL) {
1586 KMP_INTERNAL_FREE(buffer);
1589 glb_running_threads = running_threads;
1591 return running_threads;