15 #include "kmp_affinity.h" 19 #include "kmp_wait_release.h" 28 enum SYSTEM_INFORMATION_CLASS {
29 SystemProcessInformation = 5
49 SIZE_T PeakVirtualSize;
52 SIZE_T PeakWorkingSetSize;
53 SIZE_T WorkingSetSize;
54 SIZE_T QuotaPeakPagedPoolUsage;
55 SIZE_T QuotaPagedPoolUsage;
56 SIZE_T QuotaPeakNonPagedPoolUsage;
57 SIZE_T QuotaNonPagedPoolUsage;
59 SIZE_T PeakPagefileUsage;
60 SIZE_T PrivatePageCount;
63 struct SYSTEM_THREAD {
64 LARGE_INTEGER KernelTime;
65 LARGE_INTEGER UserTime;
66 LARGE_INTEGER CreateTime;
72 ULONG ContextSwitchCount;
77 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, KernelTime) == 0);
79 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 28);
80 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 52);
82 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 32);
83 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 68);
86 struct SYSTEM_PROCESS_INFORMATION {
87 ULONG NextEntryOffset;
88 ULONG NumberOfThreads;
89 LARGE_INTEGER Reserved[3];
90 LARGE_INTEGER CreateTime;
91 LARGE_INTEGER UserTime;
92 LARGE_INTEGER KernelTime;
93 UNICODE_STRING ImageName;
96 HANDLE ParentProcessId;
99 VM_COUNTERS VMCounters;
100 IO_COUNTERS IOCounters;
101 SYSTEM_THREAD Threads[1];
103 typedef SYSTEM_PROCESS_INFORMATION *PSYSTEM_PROCESS_INFORMATION;
105 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, NextEntryOffset) == 0);
106 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, CreateTime) == 32);
107 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ImageName) == 56);
109 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 68);
110 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 76);
111 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 88);
112 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 136);
113 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 184);
115 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 80);
116 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 96);
117 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 112);
118 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 208);
119 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 256);
122 typedef NTSTATUS(NTAPI *NtQuerySystemInformation_t)(SYSTEM_INFORMATION_CLASS,
123 PVOID, ULONG, PULONG);
124 NtQuerySystemInformation_t NtQuerySystemInformation = NULL;
126 HMODULE ntdll = NULL;
130 static HMODULE kernel32 = NULL;
132 #if KMP_HANDLE_SIGNALS 133 typedef void (*sig_func_t)(int);
134 static sig_func_t __kmp_sighldrs[NSIG];
135 static int __kmp_siginstalled[NSIG];
139 static HANDLE __kmp_monitor_ev;
141 static kmp_int64 __kmp_win32_time;
142 double __kmp_win32_tick;
144 int __kmp_init_runtime = FALSE;
145 CRITICAL_SECTION __kmp_win32_section;
147 void __kmp_win32_mutex_init(kmp_win32_mutex_t *mx) {
148 InitializeCriticalSection(&mx->cs);
150 __kmp_itt_system_object_created(&mx->cs,
"Critical Section");
154 void __kmp_win32_mutex_destroy(kmp_win32_mutex_t *mx) {
155 DeleteCriticalSection(&mx->cs);
158 void __kmp_win32_mutex_lock(kmp_win32_mutex_t *mx) {
159 EnterCriticalSection(&mx->cs);
162 int __kmp_win32_mutex_trylock(kmp_win32_mutex_t *mx) {
163 return TryEnterCriticalSection(&mx->cs);
166 void __kmp_win32_mutex_unlock(kmp_win32_mutex_t *mx) {
167 LeaveCriticalSection(&mx->cs);
170 void __kmp_win32_cond_init(kmp_win32_cond_t *cv) {
171 cv->waiters_count_ = 0;
172 cv->wait_generation_count_ = 0;
173 cv->release_count_ = 0;
176 __kmp_win32_mutex_init(&cv->waiters_count_lock_);
179 cv->event_ = CreateEvent(NULL,
184 __kmp_itt_system_object_created(cv->event_,
"Event");
188 void __kmp_win32_cond_destroy(kmp_win32_cond_t *cv) {
189 __kmp_win32_mutex_destroy(&cv->waiters_count_lock_);
190 __kmp_free_handle(cv->event_);
191 memset(cv,
'\0',
sizeof(*cv));
197 void __kmp_win32_cond_wait(kmp_win32_cond_t *cv, kmp_win32_mutex_t *mx,
198 kmp_info_t *th,
int need_decrease_load) {
203 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
206 cv->waiters_count_++;
209 my_generation = cv->wait_generation_count_;
211 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
212 __kmp_win32_mutex_unlock(mx);
218 WaitForSingleObject(cv->event_, INFINITE);
220 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
225 wait_done = (cv->release_count_ > 0) &&
226 (cv->wait_generation_count_ != my_generation);
228 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
236 __kmp_win32_mutex_lock(mx);
237 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
239 cv->waiters_count_--;
240 cv->release_count_--;
242 last_waiter = (cv->release_count_ == 0);
244 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
248 ResetEvent(cv->event_);
252 void __kmp_win32_cond_broadcast(kmp_win32_cond_t *cv) {
253 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
255 if (cv->waiters_count_ > 0) {
256 SetEvent(cv->event_);
259 cv->release_count_ = cv->waiters_count_;
262 cv->wait_generation_count_++;
265 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
268 void __kmp_win32_cond_signal(kmp_win32_cond_t *cv) {
269 __kmp_win32_cond_broadcast(cv);
272 void __kmp_enable(
int new_state) {
273 if (__kmp_init_runtime)
274 LeaveCriticalSection(&__kmp_win32_section);
277 void __kmp_disable(
int *old_state) {
280 if (__kmp_init_runtime)
281 EnterCriticalSection(&__kmp_win32_section);
284 void __kmp_suspend_initialize(
void) {
287 static void __kmp_suspend_initialize_thread(kmp_info_t *th) {
288 if (!TCR_4(th->th.th_suspend_init)) {
291 __kmp_win32_cond_init(&th->th.th_suspend_cv);
292 __kmp_win32_mutex_init(&th->th.th_suspend_mx);
293 TCW_4(th->th.th_suspend_init, TRUE);
297 void __kmp_suspend_uninitialize_thread(kmp_info_t *th) {
298 if (TCR_4(th->th.th_suspend_init)) {
301 __kmp_win32_cond_destroy(&th->th.th_suspend_cv);
302 __kmp_win32_mutex_destroy(&th->th.th_suspend_mx);
303 TCW_4(th->th.th_suspend_init, FALSE);
307 int __kmp_try_suspend_mx(kmp_info_t *th) {
308 return __kmp_win32_mutex_trylock(&th->th.th_suspend_mx);
311 void __kmp_lock_suspend_mx(kmp_info_t *th) {
312 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
315 void __kmp_unlock_suspend_mx(kmp_info_t *th) {
316 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
322 static inline void __kmp_suspend_template(
int th_gtid, C *flag) {
323 kmp_info_t *th = __kmp_threads[th_gtid];
325 typename C::flag_t old_spin;
327 KF_TRACE(30, (
"__kmp_suspend_template: T#%d enter for flag's loc(%p)\n",
328 th_gtid, flag->get()));
330 __kmp_suspend_initialize_thread(th);
331 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
333 KF_TRACE(10, (
"__kmp_suspend_template: T#%d setting sleep bit for flag's" 335 th_gtid, flag->get()));
339 old_spin = flag->set_sleeping();
341 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME &&
342 __kmp_pause_status != kmp_soft_paused) {
343 flag->unset_sleeping();
344 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
349 KF_TRACE(5, (
"__kmp_suspend_template: T#%d set sleep bit for flag's" 351 th_gtid, flag->get(), *(flag->get())));
353 if (flag->done_check_val(old_spin)) {
354 old_spin = flag->unset_sleeping();
355 KF_TRACE(5, (
"__kmp_suspend_template: T#%d false alarm, reset sleep bit " 356 "for flag's loc(%p)\n",
357 th_gtid, flag->get()));
360 __kmp_suspend_count++;
365 int deactivated = FALSE;
366 TCW_PTR(th->th.th_sleep_loc, (
void *)flag);
367 while (flag->is_sleeping()) {
368 KF_TRACE(15, (
"__kmp_suspend_template: T#%d about to perform " 369 "kmp_win32_cond_wait()\n",
374 th->th.th_active = FALSE;
375 if (th->th.th_active_in_pool) {
376 th->th.th_active_in_pool = FALSE;
377 KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth);
378 KMP_DEBUG_ASSERT(TCR_4(__kmp_thread_pool_active_nth) >= 0);
382 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
385 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
390 if (flag->is_sleeping()) {
392 (
"__kmp_suspend_template: T#%d spurious wakeup\n", th_gtid));
400 th->th.th_active = TRUE;
401 if (TCR_4(th->th.th_in_pool)) {
402 KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth);
403 th->th.th_active_in_pool = TRUE;
408 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
410 KF_TRACE(30, (
"__kmp_suspend_template: T#%d exit\n", th_gtid));
413 void __kmp_suspend_32(
int th_gtid, kmp_flag_32 *flag) {
414 __kmp_suspend_template(th_gtid, flag);
416 void __kmp_suspend_64(
int th_gtid, kmp_flag_64 *flag) {
417 __kmp_suspend_template(th_gtid, flag);
419 void __kmp_suspend_oncore(
int th_gtid, kmp_flag_oncore *flag) {
420 __kmp_suspend_template(th_gtid, flag);
426 static inline void __kmp_resume_template(
int target_gtid, C *flag) {
427 kmp_info_t *th = __kmp_threads[target_gtid];
431 int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1;
434 KF_TRACE(30, (
"__kmp_resume_template: T#%d wants to wakeup T#%d enter\n",
437 __kmp_suspend_initialize_thread(th);
438 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
441 flag = (C *)th->th.th_sleep_loc;
446 if (!flag || flag->get_type() != flag->get_ptr_type()) {
449 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already " 450 "awake: flag's loc(%p)\n",
451 gtid, target_gtid, NULL));
452 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
455 typename C::flag_t old_spin = flag->unset_sleeping();
456 if (!flag->is_sleeping_val(old_spin)) {
457 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already " 458 "awake: flag's loc(%p): %u => %u\n",
459 gtid, target_gtid, flag->get(), old_spin, *(flag->get())));
460 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
464 TCW_PTR(th->th.th_sleep_loc, NULL);
465 KF_TRACE(5, (
"__kmp_resume_template: T#%d about to wakeup T#%d, reset sleep " 466 "bit for flag's loc(%p)\n",
467 gtid, target_gtid, flag->get()));
469 __kmp_win32_cond_signal(&th->th.th_suspend_cv);
470 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
472 KF_TRACE(30, (
"__kmp_resume_template: T#%d exiting after signaling wake up" 477 void __kmp_resume_32(
int target_gtid, kmp_flag_32 *flag) {
478 __kmp_resume_template(target_gtid, flag);
480 void __kmp_resume_64(
int target_gtid, kmp_flag_64 *flag) {
481 __kmp_resume_template(target_gtid, flag);
483 void __kmp_resume_oncore(
int target_gtid, kmp_flag_oncore *flag) {
484 __kmp_resume_template(target_gtid, flag);
487 void __kmp_yield(
int cond) {
492 void __kmp_gtid_set_specific(
int gtid) {
493 if (__kmp_init_gtid) {
494 KA_TRACE(50, (
"__kmp_gtid_set_specific: T#%d key:%d\n", gtid,
495 __kmp_gtid_threadprivate_key));
496 if (!TlsSetValue(__kmp_gtid_threadprivate_key, (LPVOID)(gtid + 1)))
497 KMP_FATAL(TLSSetValueFailed);
499 KA_TRACE(50, (
"__kmp_gtid_set_specific: runtime shutdown, returning\n"));
503 int __kmp_gtid_get_specific() {
505 if (!__kmp_init_gtid) {
506 KA_TRACE(50, (
"__kmp_gtid_get_specific: runtime shutdown, returning " 507 "KMP_GTID_SHUTDOWN\n"));
508 return KMP_GTID_SHUTDOWN;
510 gtid = (int)(kmp_intptr_t)TlsGetValue(__kmp_gtid_threadprivate_key);
516 KA_TRACE(50, (
"__kmp_gtid_get_specific: key:%d gtid:%d\n",
517 __kmp_gtid_threadprivate_key, gtid));
521 void __kmp_affinity_bind_thread(
int proc) {
522 if (__kmp_num_proc_groups > 1) {
526 KMP_DEBUG_ASSERT((proc >= 0) && (proc < (__kmp_num_proc_groups * CHAR_BIT *
527 sizeof(DWORD_PTR))));
528 ga.Group = proc / (CHAR_BIT *
sizeof(DWORD_PTR));
529 ga.Mask = (
unsigned long long)1 << (proc % (CHAR_BIT *
sizeof(DWORD_PTR)));
530 ga.Reserved[0] = ga.Reserved[1] = ga.Reserved[2] = 0;
532 KMP_DEBUG_ASSERT(__kmp_SetThreadGroupAffinity != NULL);
533 if (__kmp_SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) == 0) {
534 DWORD error = GetLastError();
535 if (__kmp_affinity_verbose) {
536 kmp_msg_t err_code = KMP_ERR(error);
537 __kmp_msg(kmp_ms_warning, KMP_MSG(CantSetThreadAffMask), err_code,
539 if (__kmp_generate_warnings == kmp_warnings_off) {
540 __kmp_str_free(&err_code.str);
545 kmp_affin_mask_t *mask;
546 KMP_CPU_ALLOC_ON_STACK(mask);
548 KMP_CPU_SET(proc, mask);
549 __kmp_set_system_affinity(mask, TRUE);
550 KMP_CPU_FREE_FROM_STACK(mask);
554 void __kmp_affinity_determine_capable(
const char *env_var) {
557 #if KMP_GROUP_AFFINITY 558 KMP_AFFINITY_ENABLE(__kmp_num_proc_groups *
sizeof(DWORD_PTR));
560 KMP_AFFINITY_ENABLE(
sizeof(DWORD_PTR));
563 KA_TRACE(10, (
"__kmp_affinity_determine_capable: " 564 "Windows* OS affinity interface functional (mask size = " 565 "%" KMP_SIZE_T_SPEC
").\n",
566 __kmp_affin_mask_size));
569 double __kmp_read_cpu_time(
void) {
570 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
576 status = GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime,
577 &KernelTime, &UserTime);
582 sec += KernelTime.dwHighDateTime;
583 sec += UserTime.dwHighDateTime;
586 sec *= (double)(1 << 16) * (double)(1 << 16);
588 sec += KernelTime.dwLowDateTime;
589 sec += UserTime.dwLowDateTime;
591 cpu_time += (sec * 100.0) / KMP_NSEC_PER_SEC;
597 int __kmp_read_system_info(
struct kmp_sys_info *info) {
610 void __kmp_runtime_initialize(
void) {
615 if (__kmp_init_runtime) {
623 UINT err_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
625 BOOL ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
626 GET_MODULE_HANDLE_EX_FLAG_PIN,
627 (LPCTSTR)&__kmp_serial_initialize, &h);
628 KMP_DEBUG_ASSERT2(h && ret,
"OpenMP RTL cannot find itself loaded");
629 SetErrorMode(err_mode);
630 KA_TRACE(10, (
"__kmp_runtime_initialize: dynamic library pinned\n"));
634 InitializeCriticalSection(&__kmp_win32_section);
636 __kmp_itt_system_object_created(&__kmp_win32_section,
"Critical Section");
638 __kmp_initialize_system_tick();
640 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) 641 if (!__kmp_cpuinfo.initialized) {
642 __kmp_query_cpuid(&__kmp_cpuinfo);
647 #if KMP_OS_WINDOWS && !KMP_DYNAMIC_LIB 662 __kmp_tls_gtid_min = 0;
664 __kmp_tls_gtid_min = KMP_TLS_GTID_MIN;
668 if (!__kmp_gtid_threadprivate_key) {
669 __kmp_gtid_threadprivate_key = TlsAlloc();
670 if (__kmp_gtid_threadprivate_key == TLS_OUT_OF_INDEXES) {
671 KMP_FATAL(TLSOutOfIndexes);
679 __kmp_str_buf_init(&path);
680 path_size = GetSystemDirectory(path.str, path.size);
681 KMP_DEBUG_ASSERT(path_size > 0);
682 if (path_size >= path.size) {
684 __kmp_str_buf_reserve(&path, path_size);
685 path_size = GetSystemDirectory(path.str, path.size);
686 KMP_DEBUG_ASSERT(path_size > 0);
688 if (path_size > 0 && path_size < path.size) {
691 path.used = path_size;
692 __kmp_str_buf_print(&path,
"\\%s",
"ntdll.dll");
695 ntdll = GetModuleHandle(path.str);
698 KMP_DEBUG_ASSERT(ntdll != NULL);
700 NtQuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(
701 ntdll,
"NtQuerySystemInformation");
703 KMP_DEBUG_ASSERT(NtQuerySystemInformation != NULL);
705 #if KMP_GROUP_AFFINITY 708 if (path_size > 0 && path_size < path.size) {
711 path.used = path_size;
712 __kmp_str_buf_print(&path,
"\\%s",
"kernel32.dll");
715 kernel32 = GetModuleHandle(path.str);
716 KA_TRACE(10, (
"__kmp_runtime_initialize: kernel32.dll = %s\n", path.str));
720 if (kernel32 != NULL) {
721 __kmp_GetActiveProcessorCount =
722 (kmp_GetActiveProcessorCount_t)GetProcAddress(
723 kernel32,
"GetActiveProcessorCount");
724 __kmp_GetActiveProcessorGroupCount =
725 (kmp_GetActiveProcessorGroupCount_t)GetProcAddress(
726 kernel32,
"GetActiveProcessorGroupCount");
727 __kmp_GetThreadGroupAffinity =
728 (kmp_GetThreadGroupAffinity_t)GetProcAddress(
729 kernel32,
"GetThreadGroupAffinity");
730 __kmp_SetThreadGroupAffinity =
731 (kmp_SetThreadGroupAffinity_t)GetProcAddress(
732 kernel32,
"SetThreadGroupAffinity");
734 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_GetActiveProcessorCount" 736 __kmp_GetActiveProcessorCount));
737 KA_TRACE(10, (
"__kmp_runtime_initialize: " 738 "__kmp_GetActiveProcessorGroupCount = %p\n",
739 __kmp_GetActiveProcessorGroupCount));
740 KA_TRACE(10, (
"__kmp_runtime_initialize:__kmp_GetThreadGroupAffinity" 742 __kmp_GetThreadGroupAffinity));
743 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_SetThreadGroupAffinity" 745 __kmp_SetThreadGroupAffinity));
746 KA_TRACE(10, (
"__kmp_runtime_initialize: sizeof(kmp_affin_mask_t) = %d\n",
747 sizeof(kmp_affin_mask_t)));
754 if ((__kmp_GetActiveProcessorCount != NULL) &&
755 (__kmp_GetActiveProcessorGroupCount != NULL) &&
756 (__kmp_GetThreadGroupAffinity != NULL) &&
757 (__kmp_SetThreadGroupAffinity != NULL) &&
758 ((__kmp_num_proc_groups = __kmp_GetActiveProcessorGroupCount()) >
763 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups" 765 __kmp_num_proc_groups));
769 for (i = 0; i < __kmp_num_proc_groups; i++) {
770 DWORD size = __kmp_GetActiveProcessorCount(i);
772 KA_TRACE(10, (
"__kmp_runtime_initialize: proc group %d size = %d\n",
776 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups" 778 __kmp_num_proc_groups));
782 if (__kmp_num_proc_groups <= 1) {
783 GetSystemInfo(&info);
784 __kmp_xproc = info.dwNumberOfProcessors;
787 GetSystemInfo(&info);
788 __kmp_xproc = info.dwNumberOfProcessors;
793 if (__kmp_xproc <= 0) {
798 (
"__kmp_runtime_initialize: total processors = %d\n", __kmp_xproc));
800 __kmp_str_buf_free(&path);
803 __kmp_itt_initialize();
806 __kmp_init_runtime = TRUE;
809 void __kmp_runtime_destroy(
void) {
810 if (!__kmp_init_runtime) {
820 KA_TRACE(40, (
"__kmp_runtime_destroy\n"));
822 if (__kmp_gtid_threadprivate_key) {
823 TlsFree(__kmp_gtid_threadprivate_key);
824 __kmp_gtid_threadprivate_key = 0;
827 __kmp_affinity_uninitialize();
828 DeleteCriticalSection(&__kmp_win32_section);
831 NtQuerySystemInformation = NULL;
835 __kmp_GetActiveProcessorCount = NULL;
836 __kmp_GetActiveProcessorGroupCount = NULL;
837 __kmp_GetThreadGroupAffinity = NULL;
838 __kmp_SetThreadGroupAffinity = NULL;
839 #endif // KMP_ARCH_X86_64 841 __kmp_init_runtime = FALSE;
844 void __kmp_terminate_thread(
int gtid) {
845 kmp_info_t *th = __kmp_threads[gtid];
850 KA_TRACE(10, (
"__kmp_terminate_thread: kill (%d)\n", gtid));
852 if (TerminateThread(th->th.th_info.ds.ds_thread, (DWORD)-1) == FALSE) {
855 __kmp_free_handle(th->th.th_info.ds.ds_thread);
858 void __kmp_clear_system_time(
void) {
861 status = QueryPerformanceCounter(&time);
862 __kmp_win32_time = (kmp_int64)time.QuadPart;
865 void __kmp_initialize_system_tick(
void) {
870 status = QueryPerformanceFrequency(&freq);
872 DWORD error = GetLastError();
873 __kmp_fatal(KMP_MSG(FunctionError,
"QueryPerformanceFrequency()"),
874 KMP_ERR(error), __kmp_msg_null);
877 __kmp_win32_tick = ((double)1.0) / (double)freq.QuadPart;
884 void __kmp_elapsed(
double *t) {
887 status = QueryPerformanceCounter(&now);
888 *t = ((double)now.QuadPart) * __kmp_win32_tick;
893 void __kmp_elapsed_tick(
double *t) { *t = __kmp_win32_tick; }
895 void __kmp_read_system_time(
double *delta) {
900 status = QueryPerformanceCounter(&now);
902 *delta = ((double)(((kmp_int64)now.QuadPart) - __kmp_win32_time)) *
908 kmp_uint64 __kmp_now_nsec() {
910 QueryPerformanceCounter(&now);
911 return 1e9 * __kmp_win32_tick * now.QuadPart;
915 void *__stdcall __kmp_launch_worker(
void *arg) {
916 volatile void *stack_data;
919 kmp_info_t *this_thr = (kmp_info_t *)arg;
922 gtid = this_thr->th.th_info.ds.ds_gtid;
923 __kmp_gtid_set_specific(gtid);
924 #ifdef KMP_TDATA_GTID 925 #error "This define causes problems with LoadLibrary() + declspec(thread) " \ 926 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \ 927 "reference: http://support.microsoft.com/kb/118816" 932 __kmp_itt_thread_name(gtid);
935 __kmp_affinity_set_init_mask(gtid, FALSE);
937 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 939 __kmp_clear_x87_fpu_status_word();
940 __kmp_load_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word);
941 __kmp_load_mxcsr(&__kmp_init_mxcsr);
944 if (__kmp_stkoffset > 0 && gtid > 0) {
945 padding = KMP_ALLOCA(gtid * __kmp_stkoffset);
948 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
949 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
950 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
952 if (TCR_4(__kmp_gtid_mode) <
954 TCW_PTR(this_thr->th.th_info.ds.ds_stackbase, &stack_data);
955 KMP_ASSERT(this_thr->th.th_info.ds.ds_stackgrow == FALSE);
956 __kmp_check_stack_overlap(this_thr);
959 exit_val = __kmp_launch_thread(this_thr);
960 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
961 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
969 void *__stdcall __kmp_launch_monitor(
void *arg) {
971 kmp_thread_t monitor;
974 kmp_info_t *this_thr = (kmp_info_t *)arg;
976 KMP_DEBUG_ASSERT(__kmp_init_monitor);
977 TCW_4(__kmp_init_monitor, 2);
979 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
980 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
983 KA_TRACE(10, (
"__kmp_launch_monitor: launched\n"));
985 monitor = GetCurrentThread();
988 status = SetThreadPriority(monitor, THREAD_PRIORITY_HIGHEST);
990 DWORD error = GetLastError();
991 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
995 __kmp_gtid_set_specific(KMP_GTID_MONITOR);
996 #ifdef KMP_TDATA_GTID 997 #error "This define causes problems with LoadLibrary() + declspec(thread) " \ 998 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \ 999 "reference: http://support.microsoft.com/kb/118816" 1004 __kmp_itt_thread_ignore();
1010 interval = (1000 / __kmp_monitor_wakeups);
1012 while (!TCR_4(__kmp_global.g.g_done)) {
1015 KA_TRACE(15, (
"__kmp_launch_monitor: update\n"));
1017 wait_status = WaitForSingleObject(__kmp_monitor_ev, interval);
1019 if (wait_status == WAIT_TIMEOUT) {
1020 TCW_4(__kmp_global.g.g_time.dt.t_value,
1021 TCR_4(__kmp_global.g.g_time.dt.t_value) + 1);
1027 KA_TRACE(10, (
"__kmp_launch_monitor: finished\n"));
1029 status = SetThreadPriority(monitor, THREAD_PRIORITY_NORMAL);
1031 DWORD error = GetLastError();
1032 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
1035 if (__kmp_global.g.g_abort != 0) {
1040 KA_TRACE(10, (
"__kmp_launch_monitor: terminate sig=%d\n",
1041 (__kmp_global.g.g_abort)));
1046 for (gtid = 1; gtid < __kmp_threads_capacity; ++gtid)
1047 __kmp_terminate_thread(gtid);
1054 (
"__kmp_launch_monitor: raise sig=%d\n", __kmp_global.g.g_abort));
1056 if (__kmp_global.g.g_abort > 0) {
1057 raise(__kmp_global.g.g_abort);
1061 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
1068 void __kmp_create_worker(
int gtid, kmp_info_t *th,
size_t stack_size) {
1069 kmp_thread_t handle;
1072 KA_TRACE(10, (
"__kmp_create_worker: try to create thread (%d)\n", gtid));
1074 th->th.th_info.ds.ds_gtid = gtid;
1076 if (KMP_UBER_GTID(gtid)) {
1084 rc = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1085 GetCurrentProcess(), &th->th.th_info.ds.ds_thread, 0,
1086 FALSE, DUPLICATE_SAME_ACCESS);
1088 KA_TRACE(10, (
" __kmp_create_worker: ROOT Handle duplicated, th = %p, " 1089 "handle = %" KMP_UINTPTR_SPEC
"\n",
1090 (LPVOID)th, th->th.th_info.ds.ds_thread));
1091 th->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1093 if (TCR_4(__kmp_gtid_mode) < 2) {
1095 TCW_PTR(th->th.th_info.ds.ds_stackbase, &stack_data);
1096 TCW_PTR(th->th.th_info.ds.ds_stacksize, 0);
1097 TCW_4(th->th.th_info.ds.ds_stackgrow, TRUE);
1098 __kmp_check_stack_overlap(th);
1105 (
"__kmp_create_worker: stack_size = %" KMP_SIZE_T_SPEC
" bytes\n",
1108 stack_size += gtid * __kmp_stkoffset;
1110 TCW_PTR(th->th.th_info.ds.ds_stacksize, stack_size);
1111 TCW_4(th->th.th_info.ds.ds_stackgrow, FALSE);
1114 (
"__kmp_create_worker: (before) stack_size = %" KMP_SIZE_T_SPEC
1115 " bytes, &__kmp_launch_worker = %p, th = %p, &idThread = %p\n",
1116 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1117 (LPVOID)th, &idThread));
1119 handle = CreateThread(
1120 NULL, (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)__kmp_launch_worker,
1121 (LPVOID)th, STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1124 (
"__kmp_create_worker: (after) stack_size = %" KMP_SIZE_T_SPEC
1125 " bytes, &__kmp_launch_worker = %p, th = %p, " 1126 "idThread = %u, handle = %" KMP_UINTPTR_SPEC
"\n",
1127 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1128 (LPVOID)th, idThread, handle));
1131 DWORD error = GetLastError();
1132 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1134 th->th.th_info.ds.ds_thread = handle;
1140 KA_TRACE(10, (
"__kmp_create_worker: done creating thread (%d)\n", gtid));
1143 int __kmp_still_running(kmp_info_t *th) {
1144 return (WAIT_TIMEOUT == WaitForSingleObject(th->th.th_info.ds.ds_thread, 0));
1148 void __kmp_create_monitor(kmp_info_t *th) {
1149 kmp_thread_t handle;
1151 int ideal, new_ideal;
1153 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) {
1155 KA_TRACE(10, (
"__kmp_create_monitor: skipping monitor thread because of " 1156 "MAX blocktime\n"));
1157 th->th.th_info.ds.ds_tid = 0;
1158 th->th.th_info.ds.ds_gtid = 0;
1159 TCW_4(__kmp_init_monitor, 2);
1162 KA_TRACE(10, (
"__kmp_create_monitor: try to create monitor\n"));
1166 __kmp_monitor_ev = CreateEvent(NULL, TRUE, FALSE, NULL);
1167 if (__kmp_monitor_ev == NULL) {
1168 DWORD error = GetLastError();
1169 __kmp_fatal(KMP_MSG(CantCreateEvent), KMP_ERR(error), __kmp_msg_null);
1172 __kmp_itt_system_object_created(__kmp_monitor_ev,
"Event");
1175 th->th.th_info.ds.ds_tid = KMP_GTID_MONITOR;
1176 th->th.th_info.ds.ds_gtid = KMP_GTID_MONITOR;
1180 if (__kmp_monitor_stksize == 0) {
1181 __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE;
1183 if (__kmp_monitor_stksize < __kmp_sys_min_stksize) {
1184 __kmp_monitor_stksize = __kmp_sys_min_stksize;
1187 KA_TRACE(10, (
"__kmp_create_monitor: requested stacksize = %d bytes\n",
1188 (
int)__kmp_monitor_stksize));
1190 TCW_4(__kmp_global.g.g_time.dt.t_value, 0);
1193 CreateThread(NULL, (SIZE_T)__kmp_monitor_stksize,
1194 (LPTHREAD_START_ROUTINE)__kmp_launch_monitor, (LPVOID)th,
1195 STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1197 DWORD error = GetLastError();
1198 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1200 th->th.th_info.ds.ds_thread = handle;
1204 KA_TRACE(10, (
"__kmp_create_monitor: monitor created %p\n",
1205 (
void *)th->th.th_info.ds.ds_thread));
1215 int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val) {
1217 rc = GetExitCodeThread(th->th.th_info.ds.ds_thread, exit_val);
1219 DWORD error = GetLastError();
1220 __kmp_fatal(KMP_MSG(FunctionError,
"GetExitCodeThread()"), KMP_ERR(error),
1223 return (*exit_val == STILL_ACTIVE);
1226 void __kmp_exit_thread(
int exit_status) {
1227 ExitThread(exit_status);
1231 static void __kmp_reap_common(kmp_info_t *th) {
1237 10, (
"__kmp_reap_common: try to reap (%d)\n", th->th.th_info.ds.ds_gtid));
1254 KMP_FSYNC_SPIN_INIT(obj, (
void *)&th->th.th_info.ds.ds_alive);
1256 KMP_INIT_YIELD(spins);
1259 KMP_FSYNC_SPIN_PREPARE(obj);
1261 __kmp_is_thread_alive(th, &exit_val);
1262 KMP_YIELD(TCR_4(__kmp_nth) > __kmp_avail_proc);
1263 KMP_YIELD_SPIN(spins);
1264 }
while (exit_val == STILL_ACTIVE && TCR_4(th->th.th_info.ds.ds_alive));
1266 if (exit_val == STILL_ACTIVE) {
1267 KMP_FSYNC_CANCEL(obj);
1269 KMP_FSYNC_SPIN_ACQUIRED(obj);
1274 __kmp_free_handle(th->th.th_info.ds.ds_thread);
1279 if (exit_val == STILL_ACTIVE) {
1280 KA_TRACE(1, (
"__kmp_reap_common: thread still active.\n"));
1281 }
else if ((
void *)exit_val != (
void *)th) {
1282 KA_TRACE(1, (
"__kmp_reap_common: ExitProcess / TerminateThread used?\n"));
1286 (
"__kmp_reap_common: done reaping (%d), handle = %" KMP_UINTPTR_SPEC
1288 th->th.th_info.ds.ds_gtid, th->th.th_info.ds.ds_thread));
1290 th->th.th_info.ds.ds_thread = 0;
1291 th->th.th_info.ds.ds_tid = KMP_GTID_DNE;
1292 th->th.th_info.ds.ds_gtid = KMP_GTID_DNE;
1293 th->th.th_info.ds.ds_thread_id = 0;
1299 void __kmp_reap_monitor(kmp_info_t *th) {
1302 KA_TRACE(10, (
"__kmp_reap_monitor: try to reap %p\n",
1303 (
void *)th->th.th_info.ds.ds_thread));
1308 KMP_DEBUG_ASSERT(th->th.th_info.ds.ds_tid == th->th.th_info.ds.ds_gtid);
1309 if (th->th.th_info.ds.ds_gtid != KMP_GTID_MONITOR) {
1310 KA_TRACE(10, (
"__kmp_reap_monitor: monitor did not start, returning\n"));
1316 status = SetEvent(__kmp_monitor_ev);
1317 if (status == FALSE) {
1318 DWORD error = GetLastError();
1319 __kmp_fatal(KMP_MSG(CantSetEvent), KMP_ERR(error), __kmp_msg_null);
1321 KA_TRACE(10, (
"__kmp_reap_monitor: reaping thread (%d)\n",
1322 th->th.th_info.ds.ds_gtid));
1323 __kmp_reap_common(th);
1325 __kmp_free_handle(__kmp_monitor_ev);
1331 void __kmp_reap_worker(kmp_info_t *th) {
1332 KA_TRACE(10, (
"__kmp_reap_worker: reaping thread (%d)\n",
1333 th->th.th_info.ds.ds_gtid));
1334 __kmp_reap_common(th);
1337 #if KMP_HANDLE_SIGNALS 1339 static void __kmp_team_handler(
int signo) {
1340 if (__kmp_global.g.g_abort == 0) {
1342 if (__kmp_debug_buf) {
1343 __kmp_dump_debug_buffer();
1346 TCW_4(__kmp_global.g.g_abort, signo);
1348 TCW_4(__kmp_global.g.g_done, TRUE);
1353 static sig_func_t __kmp_signal(
int signum, sig_func_t handler) {
1354 sig_func_t old = signal(signum, handler);
1355 if (old == SIG_ERR) {
1357 __kmp_fatal(KMP_MSG(FunctionError,
"signal"), KMP_ERR(error),
1363 static void __kmp_install_one_handler(
int sig, sig_func_t handler,
1364 int parallel_init) {
1367 KB_TRACE(60, (
"__kmp_install_one_handler: called: sig=%d\n", sig));
1368 if (parallel_init) {
1369 old = __kmp_signal(sig, handler);
1371 if (old == __kmp_sighldrs[sig]) {
1372 __kmp_siginstalled[sig] = 1;
1374 old = __kmp_signal(sig, old);
1380 old = __kmp_signal(sig, SIG_DFL);
1381 __kmp_sighldrs[sig] = old;
1382 __kmp_signal(sig, old);
1387 static void __kmp_remove_one_handler(
int sig) {
1388 if (__kmp_siginstalled[sig]) {
1391 KB_TRACE(60, (
"__kmp_remove_one_handler: called: sig=%d\n", sig));
1392 old = __kmp_signal(sig, __kmp_sighldrs[sig]);
1393 if (old != __kmp_team_handler) {
1394 KB_TRACE(10, (
"__kmp_remove_one_handler: oops, not our handler, " 1395 "restoring: sig=%d\n",
1397 old = __kmp_signal(sig, old);
1399 __kmp_sighldrs[sig] = NULL;
1400 __kmp_siginstalled[sig] = 0;
1405 void __kmp_install_signals(
int parallel_init) {
1406 KB_TRACE(10, (
"__kmp_install_signals: called\n"));
1407 if (!__kmp_handle_signals) {
1408 KB_TRACE(10, (
"__kmp_install_signals: KMP_HANDLE_SIGNALS is false - " 1409 "handlers not installed\n"));
1412 __kmp_install_one_handler(SIGINT, __kmp_team_handler, parallel_init);
1413 __kmp_install_one_handler(SIGILL, __kmp_team_handler, parallel_init);
1414 __kmp_install_one_handler(SIGABRT, __kmp_team_handler, parallel_init);
1415 __kmp_install_one_handler(SIGFPE, __kmp_team_handler, parallel_init);
1416 __kmp_install_one_handler(SIGSEGV, __kmp_team_handler, parallel_init);
1417 __kmp_install_one_handler(SIGTERM, __kmp_team_handler, parallel_init);
1420 void __kmp_remove_signals(
void) {
1422 KB_TRACE(10, (
"__kmp_remove_signals: called\n"));
1423 for (sig = 1; sig < NSIG; ++sig) {
1424 __kmp_remove_one_handler(sig);
1428 #endif // KMP_HANDLE_SIGNALS 1431 void __kmp_thread_sleep(
int millis) {
1434 status = SleepEx((DWORD)millis, FALSE);
1436 DWORD error = GetLastError();
1437 __kmp_fatal(KMP_MSG(FunctionError,
"SleepEx()"), KMP_ERR(error),
1443 int __kmp_is_address_mapped(
void *addr) {
1445 MEMORY_BASIC_INFORMATION lpBuffer;
1448 dwLength =
sizeof(MEMORY_BASIC_INFORMATION);
1450 status = VirtualQuery(addr, &lpBuffer, dwLength);
1452 return !(((lpBuffer.State == MEM_RESERVE) || (lpBuffer.State == MEM_FREE)) ||
1453 ((lpBuffer.Protect == PAGE_NOACCESS) ||
1454 (lpBuffer.Protect == PAGE_EXECUTE)));
1457 kmp_uint64 __kmp_hardware_timestamp(
void) {
1460 QueryPerformanceCounter((LARGE_INTEGER *)&r);
1465 void __kmp_free_handle(kmp_thread_t tHandle) {
1469 rc = CloseHandle(tHandle);
1471 DWORD error = GetLastError();
1472 __kmp_fatal(KMP_MSG(CantCloseHandle), KMP_ERR(error), __kmp_msg_null);
1476 int __kmp_get_load_balance(
int max) {
1477 static ULONG glb_buff_size = 100 * 1024;
1480 static int glb_running_threads = 0;
1481 static double glb_call_time = 0;
1483 int running_threads = 0;
1484 NTSTATUS status = 0;
1485 ULONG buff_size = 0;
1486 ULONG info_size = 0;
1487 void *buffer = NULL;
1488 PSYSTEM_PROCESS_INFORMATION spi = NULL;
1491 double call_time = 0.0;
1493 __kmp_elapsed(&call_time);
1495 if (glb_call_time &&
1496 (call_time - glb_call_time < __kmp_load_balance_interval)) {
1497 running_threads = glb_running_threads;
1500 glb_call_time = call_time;
1503 if (NtQuerySystemInformation == NULL) {
1504 running_threads = -1;
1515 buff_size = glb_buff_size;
1517 buff_size = 2 * buff_size;
1520 buffer = KMP_INTERNAL_REALLOC(buffer, buff_size);
1521 if (buffer == NULL) {
1522 running_threads = -1;
1525 status = NtQuerySystemInformation(SystemProcessInformation, buffer,
1526 buff_size, &info_size);
1529 }
while (status == STATUS_INFO_LENGTH_MISMATCH);
1530 glb_buff_size = buff_size;
1532 #define CHECK(cond) \ 1534 KMP_DEBUG_ASSERT(cond); \ 1536 running_threads = -1; \ 1541 CHECK(buff_size >= info_size);
1542 spi = PSYSTEM_PROCESS_INFORMATION(buffer);
1544 ptrdiff_t offset = uintptr_t(spi) - uintptr_t(buffer);
1545 CHECK(0 <= offset &&
1546 offset +
sizeof(SYSTEM_PROCESS_INFORMATION) < info_size);
1547 HANDLE pid = spi->ProcessId;
1548 ULONG num = spi->NumberOfThreads;
1551 sizeof(SYSTEM_PROCESS_INFORMATION) +
sizeof(SYSTEM_THREAD) * (num - 1);
1552 CHECK(offset + spi_size <
1554 if (spi->NextEntryOffset != 0) {
1556 spi->NextEntryOffset);
1562 for (
int i = 0; i < num; ++i) {
1563 THREAD_STATE state = spi->Threads[i].State;
1566 if (state == StateRunning) {
1570 if (running_threads >= max) {
1576 if (spi->NextEntryOffset == 0) {
1579 spi = PSYSTEM_PROCESS_INFORMATION(uintptr_t(spi) + spi->NextEntryOffset);
1586 if (buffer != NULL) {
1587 KMP_INTERNAL_FREE(buffer);
1590 glb_running_threads = running_threads;
1592 return running_threads;