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 void __kmp_win32_mutex_unlock(kmp_win32_mutex_t *mx) {
163 LeaveCriticalSection(&mx->cs);
166 void __kmp_win32_cond_init(kmp_win32_cond_t *cv) {
167 cv->waiters_count_ = 0;
168 cv->wait_generation_count_ = 0;
169 cv->release_count_ = 0;
172 __kmp_win32_mutex_init(&cv->waiters_count_lock_);
175 cv->event_ = CreateEvent(NULL,
180 __kmp_itt_system_object_created(cv->event_,
"Event");
184 void __kmp_win32_cond_destroy(kmp_win32_cond_t *cv) {
185 __kmp_win32_mutex_destroy(&cv->waiters_count_lock_);
186 __kmp_free_handle(cv->event_);
187 memset(cv,
'\0',
sizeof(*cv));
193 void __kmp_win32_cond_wait(kmp_win32_cond_t *cv, kmp_win32_mutex_t *mx,
194 kmp_info_t *th,
int need_decrease_load) {
199 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
202 cv->waiters_count_++;
205 my_generation = cv->wait_generation_count_;
207 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
208 __kmp_win32_mutex_unlock(mx);
214 WaitForSingleObject(cv->event_, INFINITE);
216 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
221 wait_done = (cv->release_count_ > 0) &&
222 (cv->wait_generation_count_ != my_generation);
224 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
232 __kmp_win32_mutex_lock(mx);
233 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
235 cv->waiters_count_--;
236 cv->release_count_--;
238 last_waiter = (cv->release_count_ == 0);
240 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
244 ResetEvent(cv->event_);
248 void __kmp_win32_cond_broadcast(kmp_win32_cond_t *cv) {
249 __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
251 if (cv->waiters_count_ > 0) {
252 SetEvent(cv->event_);
255 cv->release_count_ = cv->waiters_count_;
258 cv->wait_generation_count_++;
261 __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
264 void __kmp_win32_cond_signal(kmp_win32_cond_t *cv) {
265 __kmp_win32_cond_broadcast(cv);
268 void __kmp_enable(
int new_state) {
269 if (__kmp_init_runtime)
270 LeaveCriticalSection(&__kmp_win32_section);
273 void __kmp_disable(
int *old_state) {
276 if (__kmp_init_runtime)
277 EnterCriticalSection(&__kmp_win32_section);
280 void __kmp_suspend_initialize(
void) {
283 static void __kmp_suspend_initialize_thread(kmp_info_t *th) {
284 if (!TCR_4(th->th.th_suspend_init)) {
287 __kmp_win32_cond_init(&th->th.th_suspend_cv);
288 __kmp_win32_mutex_init(&th->th.th_suspend_mx);
289 TCW_4(th->th.th_suspend_init, TRUE);
293 void __kmp_suspend_uninitialize_thread(kmp_info_t *th) {
294 if (TCR_4(th->th.th_suspend_init)) {
297 __kmp_win32_cond_destroy(&th->th.th_suspend_cv);
298 __kmp_win32_mutex_destroy(&th->th.th_suspend_mx);
299 TCW_4(th->th.th_suspend_init, FALSE);
306 static inline void __kmp_suspend_template(
int th_gtid, C *flag) {
307 kmp_info_t *th = __kmp_threads[th_gtid];
309 typename C::flag_t old_spin;
311 KF_TRACE(30, (
"__kmp_suspend_template: T#%d enter for flag's loc(%p)\n",
312 th_gtid, flag->get()));
314 __kmp_suspend_initialize_thread(th);
315 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
317 KF_TRACE(10, (
"__kmp_suspend_template: T#%d setting sleep bit for flag's" 319 th_gtid, flag->get()));
323 old_spin = flag->set_sleeping();
325 KF_TRACE(5, (
"__kmp_suspend_template: T#%d set sleep bit for flag's" 327 th_gtid, flag->get(), *(flag->get())));
329 if (flag->done_check_val(old_spin)) {
330 old_spin = flag->unset_sleeping();
331 KF_TRACE(5, (
"__kmp_suspend_template: T#%d false alarm, reset sleep bit " 332 "for flag's loc(%p)\n",
333 th_gtid, flag->get()));
336 __kmp_suspend_count++;
341 int deactivated = FALSE;
342 TCW_PTR(th->th.th_sleep_loc, (
void *)flag);
343 while (flag->is_sleeping()) {
344 KF_TRACE(15, (
"__kmp_suspend_template: T#%d about to perform " 345 "kmp_win32_cond_wait()\n",
350 th->th.th_active = FALSE;
351 if (th->th.th_active_in_pool) {
352 th->th.th_active_in_pool = FALSE;
353 KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth);
354 KMP_DEBUG_ASSERT(TCR_4(__kmp_thread_pool_active_nth) >= 0);
358 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
361 __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, 0,
366 if (flag->is_sleeping()) {
368 (
"__kmp_suspend_template: T#%d spurious wakeup\n", th_gtid));
376 th->th.th_active = TRUE;
377 if (TCR_4(th->th.th_in_pool)) {
378 KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth);
379 th->th.th_active_in_pool = TRUE;
384 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
386 KF_TRACE(30, (
"__kmp_suspend_template: T#%d exit\n", th_gtid));
389 void __kmp_suspend_32(
int th_gtid, kmp_flag_32 *flag) {
390 __kmp_suspend_template(th_gtid, flag);
392 void __kmp_suspend_64(
int th_gtid, kmp_flag_64 *flag) {
393 __kmp_suspend_template(th_gtid, flag);
395 void __kmp_suspend_oncore(
int th_gtid, kmp_flag_oncore *flag) {
396 __kmp_suspend_template(th_gtid, flag);
402 static inline void __kmp_resume_template(
int target_gtid, C *flag) {
403 kmp_info_t *th = __kmp_threads[target_gtid];
407 int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1;
410 KF_TRACE(30, (
"__kmp_resume_template: T#%d wants to wakeup T#%d enter\n",
413 __kmp_suspend_initialize_thread(th);
414 __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
417 flag = (C *)th->th.th_sleep_loc;
422 if (!flag || flag->get_type() != flag->get_ptr_type()) {
425 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already " 426 "awake: flag's loc(%p)\n",
427 gtid, target_gtid, NULL));
428 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
431 typename C::flag_t old_spin = flag->unset_sleeping();
432 if (!flag->is_sleeping_val(old_spin)) {
433 KF_TRACE(5, (
"__kmp_resume_template: T#%d exiting, thread T#%d already " 434 "awake: flag's loc(%p): %u => %u\n",
435 gtid, target_gtid, flag->get(), old_spin, *(flag->get())));
436 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
440 TCW_PTR(th->th.th_sleep_loc, NULL);
441 KF_TRACE(5, (
"__kmp_resume_template: T#%d about to wakeup T#%d, reset sleep " 442 "bit for flag's loc(%p)\n",
443 gtid, target_gtid, flag->get()));
445 __kmp_win32_cond_signal(&th->th.th_suspend_cv);
446 __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
448 KF_TRACE(30, (
"__kmp_resume_template: T#%d exiting after signaling wake up" 453 void __kmp_resume_32(
int target_gtid, kmp_flag_32 *flag) {
454 __kmp_resume_template(target_gtid, flag);
456 void __kmp_resume_64(
int target_gtid, kmp_flag_64 *flag) {
457 __kmp_resume_template(target_gtid, flag);
459 void __kmp_resume_oncore(
int target_gtid, kmp_flag_oncore *flag) {
460 __kmp_resume_template(target_gtid, flag);
463 void __kmp_yield(
int cond) {
468 void __kmp_gtid_set_specific(
int gtid) {
469 if (__kmp_init_gtid) {
470 KA_TRACE(50, (
"__kmp_gtid_set_specific: T#%d key:%d\n", gtid,
471 __kmp_gtid_threadprivate_key));
472 if (!TlsSetValue(__kmp_gtid_threadprivate_key, (LPVOID)(gtid + 1)))
473 KMP_FATAL(TLSSetValueFailed);
475 KA_TRACE(50, (
"__kmp_gtid_set_specific: runtime shutdown, returning\n"));
479 int __kmp_gtid_get_specific() {
481 if (!__kmp_init_gtid) {
482 KA_TRACE(50, (
"__kmp_gtid_get_specific: runtime shutdown, returning " 483 "KMP_GTID_SHUTDOWN\n"));
484 return KMP_GTID_SHUTDOWN;
486 gtid = (int)(kmp_intptr_t)TlsGetValue(__kmp_gtid_threadprivate_key);
492 KA_TRACE(50, (
"__kmp_gtid_get_specific: key:%d gtid:%d\n",
493 __kmp_gtid_threadprivate_key, gtid));
497 void __kmp_affinity_bind_thread(
int proc) {
498 if (__kmp_num_proc_groups > 1) {
502 KMP_DEBUG_ASSERT((proc >= 0) && (proc < (__kmp_num_proc_groups * CHAR_BIT *
503 sizeof(DWORD_PTR))));
504 ga.Group = proc / (CHAR_BIT *
sizeof(DWORD_PTR));
505 ga.Mask = (
unsigned long long)1 << (proc % (CHAR_BIT *
sizeof(DWORD_PTR)));
506 ga.Reserved[0] = ga.Reserved[1] = ga.Reserved[2] = 0;
508 KMP_DEBUG_ASSERT(__kmp_SetThreadGroupAffinity != NULL);
509 if (__kmp_SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) == 0) {
510 DWORD error = GetLastError();
511 if (__kmp_affinity_verbose) {
512 kmp_msg_t err_code = KMP_ERR(error);
513 __kmp_msg(kmp_ms_warning, KMP_MSG(CantSetThreadAffMask), err_code,
515 if (__kmp_generate_warnings == kmp_warnings_off) {
516 __kmp_str_free(&err_code.str);
521 kmp_affin_mask_t *mask;
522 KMP_CPU_ALLOC_ON_STACK(mask);
524 KMP_CPU_SET(proc, mask);
525 __kmp_set_system_affinity(mask, TRUE);
526 KMP_CPU_FREE_FROM_STACK(mask);
530 void __kmp_affinity_determine_capable(
const char *env_var) {
533 #if KMP_GROUP_AFFINITY 534 KMP_AFFINITY_ENABLE(__kmp_num_proc_groups *
sizeof(DWORD_PTR));
536 KMP_AFFINITY_ENABLE(
sizeof(DWORD_PTR));
539 KA_TRACE(10, (
"__kmp_affinity_determine_capable: " 540 "Windows* OS affinity interface functional (mask size = " 541 "%" KMP_SIZE_T_SPEC
").\n",
542 __kmp_affin_mask_size));
545 double __kmp_read_cpu_time(
void) {
546 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
552 status = GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime,
553 &KernelTime, &UserTime);
558 sec += KernelTime.dwHighDateTime;
559 sec += UserTime.dwHighDateTime;
562 sec *= (double)(1 << 16) * (double)(1 << 16);
564 sec += KernelTime.dwLowDateTime;
565 sec += UserTime.dwLowDateTime;
567 cpu_time += (sec * 100.0) / KMP_NSEC_PER_SEC;
573 int __kmp_read_system_info(
struct kmp_sys_info *info) {
586 void __kmp_runtime_initialize(
void) {
591 if (__kmp_init_runtime) {
599 UINT err_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
601 BOOL ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
602 GET_MODULE_HANDLE_EX_FLAG_PIN,
603 (LPCTSTR)&__kmp_serial_initialize, &h);
604 KMP_DEBUG_ASSERT2(h && ret,
"OpenMP RTL cannot find itself loaded");
605 SetErrorMode(err_mode);
606 KA_TRACE(10, (
"__kmp_runtime_initialize: dynamic library pinned\n"));
610 InitializeCriticalSection(&__kmp_win32_section);
612 __kmp_itt_system_object_created(&__kmp_win32_section,
"Critical Section");
614 __kmp_initialize_system_tick();
616 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) 617 if (!__kmp_cpuinfo.initialized) {
618 __kmp_query_cpuid(&__kmp_cpuinfo);
623 #if KMP_OS_WINDOWS && !KMP_DYNAMIC_LIB 638 __kmp_tls_gtid_min = 0;
640 __kmp_tls_gtid_min = KMP_TLS_GTID_MIN;
644 if (!__kmp_gtid_threadprivate_key) {
645 __kmp_gtid_threadprivate_key = TlsAlloc();
646 if (__kmp_gtid_threadprivate_key == TLS_OUT_OF_INDEXES) {
647 KMP_FATAL(TLSOutOfIndexes);
655 __kmp_str_buf_init(&path);
656 path_size = GetSystemDirectory(path.str, path.size);
657 KMP_DEBUG_ASSERT(path_size > 0);
658 if (path_size >= path.size) {
660 __kmp_str_buf_reserve(&path, path_size);
661 path_size = GetSystemDirectory(path.str, path.size);
662 KMP_DEBUG_ASSERT(path_size > 0);
664 if (path_size > 0 && path_size < path.size) {
667 path.used = path_size;
668 __kmp_str_buf_print(&path,
"\\%s",
"ntdll.dll");
671 ntdll = GetModuleHandle(path.str);
674 KMP_DEBUG_ASSERT(ntdll != NULL);
676 NtQuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(
677 ntdll,
"NtQuerySystemInformation");
679 KMP_DEBUG_ASSERT(NtQuerySystemInformation != NULL);
681 #if KMP_GROUP_AFFINITY 684 if (path_size > 0 && path_size < path.size) {
687 path.used = path_size;
688 __kmp_str_buf_print(&path,
"\\%s",
"kernel32.dll");
691 kernel32 = GetModuleHandle(path.str);
692 KA_TRACE(10, (
"__kmp_runtime_initialize: kernel32.dll = %s\n", path.str));
696 if (kernel32 != NULL) {
697 __kmp_GetActiveProcessorCount =
698 (kmp_GetActiveProcessorCount_t)GetProcAddress(
699 kernel32,
"GetActiveProcessorCount");
700 __kmp_GetActiveProcessorGroupCount =
701 (kmp_GetActiveProcessorGroupCount_t)GetProcAddress(
702 kernel32,
"GetActiveProcessorGroupCount");
703 __kmp_GetThreadGroupAffinity =
704 (kmp_GetThreadGroupAffinity_t)GetProcAddress(
705 kernel32,
"GetThreadGroupAffinity");
706 __kmp_SetThreadGroupAffinity =
707 (kmp_SetThreadGroupAffinity_t)GetProcAddress(
708 kernel32,
"SetThreadGroupAffinity");
710 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_GetActiveProcessorCount" 712 __kmp_GetActiveProcessorCount));
713 KA_TRACE(10, (
"__kmp_runtime_initialize: " 714 "__kmp_GetActiveProcessorGroupCount = %p\n",
715 __kmp_GetActiveProcessorGroupCount));
716 KA_TRACE(10, (
"__kmp_runtime_initialize:__kmp_GetThreadGroupAffinity" 718 __kmp_GetThreadGroupAffinity));
719 KA_TRACE(10, (
"__kmp_runtime_initialize: __kmp_SetThreadGroupAffinity" 721 __kmp_SetThreadGroupAffinity));
722 KA_TRACE(10, (
"__kmp_runtime_initialize: sizeof(kmp_affin_mask_t) = %d\n",
723 sizeof(kmp_affin_mask_t)));
730 if ((__kmp_GetActiveProcessorCount != NULL) &&
731 (__kmp_GetActiveProcessorGroupCount != NULL) &&
732 (__kmp_GetThreadGroupAffinity != NULL) &&
733 (__kmp_SetThreadGroupAffinity != NULL) &&
734 ((__kmp_num_proc_groups = __kmp_GetActiveProcessorGroupCount()) >
739 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups" 741 __kmp_num_proc_groups));
745 for (i = 0; i < __kmp_num_proc_groups; i++) {
746 DWORD size = __kmp_GetActiveProcessorCount(i);
748 KA_TRACE(10, (
"__kmp_runtime_initialize: proc group %d size = %d\n",
752 KA_TRACE(10, (
"__kmp_runtime_initialize: %d processor groups" 754 __kmp_num_proc_groups));
758 if (__kmp_num_proc_groups <= 1) {
759 GetSystemInfo(&info);
760 __kmp_xproc = info.dwNumberOfProcessors;
763 GetSystemInfo(&info);
764 __kmp_xproc = info.dwNumberOfProcessors;
769 if (__kmp_xproc <= 0) {
774 (
"__kmp_runtime_initialize: total processors = %d\n", __kmp_xproc));
776 __kmp_str_buf_free(&path);
779 __kmp_itt_initialize();
782 __kmp_init_runtime = TRUE;
785 void __kmp_runtime_destroy(
void) {
786 if (!__kmp_init_runtime) {
796 KA_TRACE(40, (
"__kmp_runtime_destroy\n"));
798 if (__kmp_gtid_threadprivate_key) {
799 TlsFree(__kmp_gtid_threadprivate_key);
800 __kmp_gtid_threadprivate_key = 0;
803 __kmp_affinity_uninitialize();
804 DeleteCriticalSection(&__kmp_win32_section);
807 NtQuerySystemInformation = NULL;
811 __kmp_GetActiveProcessorCount = NULL;
812 __kmp_GetActiveProcessorGroupCount = NULL;
813 __kmp_GetThreadGroupAffinity = NULL;
814 __kmp_SetThreadGroupAffinity = NULL;
815 #endif // KMP_ARCH_X86_64 817 __kmp_init_runtime = FALSE;
820 void __kmp_terminate_thread(
int gtid) {
821 kmp_info_t *th = __kmp_threads[gtid];
826 KA_TRACE(10, (
"__kmp_terminate_thread: kill (%d)\n", gtid));
828 if (TerminateThread(th->th.th_info.ds.ds_thread, (DWORD)-1) == FALSE) {
831 __kmp_free_handle(th->th.th_info.ds.ds_thread);
834 void __kmp_clear_system_time(
void) {
837 status = QueryPerformanceCounter(&time);
838 __kmp_win32_time = (kmp_int64)time.QuadPart;
841 void __kmp_initialize_system_tick(
void) {
846 status = QueryPerformanceFrequency(&freq);
848 DWORD error = GetLastError();
849 __kmp_fatal(KMP_MSG(FunctionError,
"QueryPerformanceFrequency()"),
850 KMP_ERR(error), __kmp_msg_null);
853 __kmp_win32_tick = ((double)1.0) / (double)freq.QuadPart;
860 void __kmp_elapsed(
double *t) {
863 status = QueryPerformanceCounter(&now);
864 *t = ((double)now.QuadPart) * __kmp_win32_tick;
869 void __kmp_elapsed_tick(
double *t) { *t = __kmp_win32_tick; }
871 void __kmp_read_system_time(
double *delta) {
876 status = QueryPerformanceCounter(&now);
878 *delta = ((double)(((kmp_int64)now.QuadPart) - __kmp_win32_time)) *
884 kmp_uint64 __kmp_now_nsec() {
886 QueryPerformanceCounter(&now);
887 return 1e9 * __kmp_win32_tick * now.QuadPart;
891 void *__stdcall __kmp_launch_worker(
void *arg) {
892 volatile void *stack_data;
895 kmp_info_t *this_thr = (kmp_info_t *)arg;
898 gtid = this_thr->th.th_info.ds.ds_gtid;
899 __kmp_gtid_set_specific(gtid);
900 #ifdef KMP_TDATA_GTID 901 #error "This define causes problems with LoadLibrary() + declspec(thread) " \ 902 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \ 903 "reference: http://support.microsoft.com/kb/118816" 908 __kmp_itt_thread_name(gtid);
911 __kmp_affinity_set_init_mask(gtid, FALSE);
913 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 915 __kmp_clear_x87_fpu_status_word();
916 __kmp_load_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word);
917 __kmp_load_mxcsr(&__kmp_init_mxcsr);
920 if (__kmp_stkoffset > 0 && gtid > 0) {
921 padding = KMP_ALLOCA(gtid * __kmp_stkoffset);
924 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
925 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
926 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
928 if (TCR_4(__kmp_gtid_mode) <
930 TCW_PTR(this_thr->th.th_info.ds.ds_stackbase, &stack_data);
931 KMP_ASSERT(this_thr->th.th_info.ds.ds_stackgrow == FALSE);
932 __kmp_check_stack_overlap(this_thr);
935 exit_val = __kmp_launch_thread(this_thr);
936 KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
937 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
945 void *__stdcall __kmp_launch_monitor(
void *arg) {
947 kmp_thread_t monitor;
950 kmp_info_t *this_thr = (kmp_info_t *)arg;
952 KMP_DEBUG_ASSERT(__kmp_init_monitor);
953 TCW_4(__kmp_init_monitor, 2);
955 this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
956 TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
959 KA_TRACE(10, (
"__kmp_launch_monitor: launched\n"));
961 monitor = GetCurrentThread();
964 status = SetThreadPriority(monitor, THREAD_PRIORITY_HIGHEST);
966 DWORD error = GetLastError();
967 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
971 __kmp_gtid_set_specific(KMP_GTID_MONITOR);
972 #ifdef KMP_TDATA_GTID 973 #error "This define causes problems with LoadLibrary() + declspec(thread) " \ 974 "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \ 975 "reference: http://support.microsoft.com/kb/118816" 980 __kmp_itt_thread_ignore();
986 interval = (1000 / __kmp_monitor_wakeups);
988 while (!TCR_4(__kmp_global.g.g_done)) {
991 KA_TRACE(15, (
"__kmp_launch_monitor: update\n"));
993 wait_status = WaitForSingleObject(__kmp_monitor_ev, interval);
995 if (wait_status == WAIT_TIMEOUT) {
996 TCW_4(__kmp_global.g.g_time.dt.t_value,
997 TCR_4(__kmp_global.g.g_time.dt.t_value) + 1);
1003 KA_TRACE(10, (
"__kmp_launch_monitor: finished\n"));
1005 status = SetThreadPriority(monitor, THREAD_PRIORITY_NORMAL);
1007 DWORD error = GetLastError();
1008 __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
1011 if (__kmp_global.g.g_abort != 0) {
1016 KA_TRACE(10, (
"__kmp_launch_monitor: terminate sig=%d\n",
1017 (__kmp_global.g.g_abort)));
1022 for (gtid = 1; gtid < __kmp_threads_capacity; ++gtid)
1023 __kmp_terminate_thread(gtid);
1030 (
"__kmp_launch_monitor: raise sig=%d\n", __kmp_global.g.g_abort));
1032 if (__kmp_global.g.g_abort > 0) {
1033 raise(__kmp_global.g.g_abort);
1037 TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
1044 void __kmp_create_worker(
int gtid, kmp_info_t *th,
size_t stack_size) {
1045 kmp_thread_t handle;
1048 KA_TRACE(10, (
"__kmp_create_worker: try to create thread (%d)\n", gtid));
1050 th->th.th_info.ds.ds_gtid = gtid;
1052 if (KMP_UBER_GTID(gtid)) {
1060 rc = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1061 GetCurrentProcess(), &th->th.th_info.ds.ds_thread, 0,
1062 FALSE, DUPLICATE_SAME_ACCESS);
1064 KA_TRACE(10, (
" __kmp_create_worker: ROOT Handle duplicated, th = %p, " 1065 "handle = %" KMP_UINTPTR_SPEC
"\n",
1066 (LPVOID)th, th->th.th_info.ds.ds_thread));
1067 th->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1069 if (TCR_4(__kmp_gtid_mode) < 2) {
1071 TCW_PTR(th->th.th_info.ds.ds_stackbase, &stack_data);
1072 TCW_PTR(th->th.th_info.ds.ds_stacksize, 0);
1073 TCW_4(th->th.th_info.ds.ds_stackgrow, TRUE);
1074 __kmp_check_stack_overlap(th);
1081 (
"__kmp_create_worker: stack_size = %" KMP_SIZE_T_SPEC
" bytes\n",
1084 stack_size += gtid * __kmp_stkoffset;
1086 TCW_PTR(th->th.th_info.ds.ds_stacksize, stack_size);
1087 TCW_4(th->th.th_info.ds.ds_stackgrow, FALSE);
1090 (
"__kmp_create_worker: (before) stack_size = %" KMP_SIZE_T_SPEC
1091 " bytes, &__kmp_launch_worker = %p, th = %p, &idThread = %p\n",
1092 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1093 (LPVOID)th, &idThread));
1095 handle = CreateThread(
1096 NULL, (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)__kmp_launch_worker,
1097 (LPVOID)th, STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1100 (
"__kmp_create_worker: (after) stack_size = %" KMP_SIZE_T_SPEC
1101 " bytes, &__kmp_launch_worker = %p, th = %p, " 1102 "idThread = %u, handle = %" KMP_UINTPTR_SPEC
"\n",
1103 (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1104 (LPVOID)th, idThread, handle));
1107 DWORD error = GetLastError();
1108 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1110 th->th.th_info.ds.ds_thread = handle;
1116 KA_TRACE(10, (
"__kmp_create_worker: done creating thread (%d)\n", gtid));
1119 int __kmp_still_running(kmp_info_t *th) {
1120 return (WAIT_TIMEOUT == WaitForSingleObject(th->th.th_info.ds.ds_thread, 0));
1124 void __kmp_create_monitor(kmp_info_t *th) {
1125 kmp_thread_t handle;
1127 int ideal, new_ideal;
1129 if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) {
1131 KA_TRACE(10, (
"__kmp_create_monitor: skipping monitor thread because of " 1132 "MAX blocktime\n"));
1133 th->th.th_info.ds.ds_tid = 0;
1134 th->th.th_info.ds.ds_gtid = 0;
1135 TCW_4(__kmp_init_monitor, 2);
1138 KA_TRACE(10, (
"__kmp_create_monitor: try to create monitor\n"));
1142 __kmp_monitor_ev = CreateEvent(NULL, TRUE, FALSE, NULL);
1143 if (__kmp_monitor_ev == NULL) {
1144 DWORD error = GetLastError();
1145 __kmp_fatal(KMP_MSG(CantCreateEvent), KMP_ERR(error), __kmp_msg_null);
1148 __kmp_itt_system_object_created(__kmp_monitor_ev,
"Event");
1151 th->th.th_info.ds.ds_tid = KMP_GTID_MONITOR;
1152 th->th.th_info.ds.ds_gtid = KMP_GTID_MONITOR;
1156 if (__kmp_monitor_stksize == 0) {
1157 __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE;
1159 if (__kmp_monitor_stksize < __kmp_sys_min_stksize) {
1160 __kmp_monitor_stksize = __kmp_sys_min_stksize;
1163 KA_TRACE(10, (
"__kmp_create_monitor: requested stacksize = %d bytes\n",
1164 (
int)__kmp_monitor_stksize));
1166 TCW_4(__kmp_global.g.g_time.dt.t_value, 0);
1169 CreateThread(NULL, (SIZE_T)__kmp_monitor_stksize,
1170 (LPTHREAD_START_ROUTINE)__kmp_launch_monitor, (LPVOID)th,
1171 STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1173 DWORD error = GetLastError();
1174 __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1176 th->th.th_info.ds.ds_thread = handle;
1180 KA_TRACE(10, (
"__kmp_create_monitor: monitor created %p\n",
1181 (
void *)th->th.th_info.ds.ds_thread));
1191 int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val) {
1193 rc = GetExitCodeThread(th->th.th_info.ds.ds_thread, exit_val);
1195 DWORD error = GetLastError();
1196 __kmp_fatal(KMP_MSG(FunctionError,
"GetExitCodeThread()"), KMP_ERR(error),
1199 return (*exit_val == STILL_ACTIVE);
1202 void __kmp_exit_thread(
int exit_status) {
1203 ExitThread(exit_status);
1207 static void __kmp_reap_common(kmp_info_t *th) {
1213 10, (
"__kmp_reap_common: try to reap (%d)\n", th->th.th_info.ds.ds_gtid));
1230 KMP_FSYNC_SPIN_INIT(obj, (
void *)&th->th.th_info.ds.ds_alive);
1232 KMP_INIT_YIELD(spins);
1235 KMP_FSYNC_SPIN_PREPARE(obj);
1237 __kmp_is_thread_alive(th, &exit_val);
1238 KMP_YIELD(TCR_4(__kmp_nth) > __kmp_avail_proc);
1239 KMP_YIELD_SPIN(spins);
1240 }
while (exit_val == STILL_ACTIVE && TCR_4(th->th.th_info.ds.ds_alive));
1242 if (exit_val == STILL_ACTIVE) {
1243 KMP_FSYNC_CANCEL(obj);
1245 KMP_FSYNC_SPIN_ACQUIRED(obj);
1250 __kmp_free_handle(th->th.th_info.ds.ds_thread);
1255 if (exit_val == STILL_ACTIVE) {
1256 KA_TRACE(1, (
"__kmp_reap_common: thread still active.\n"));
1257 }
else if ((
void *)exit_val != (
void *)th) {
1258 KA_TRACE(1, (
"__kmp_reap_common: ExitProcess / TerminateThread used?\n"));
1262 (
"__kmp_reap_common: done reaping (%d), handle = %" KMP_UINTPTR_SPEC
1264 th->th.th_info.ds.ds_gtid, th->th.th_info.ds.ds_thread));
1266 th->th.th_info.ds.ds_thread = 0;
1267 th->th.th_info.ds.ds_tid = KMP_GTID_DNE;
1268 th->th.th_info.ds.ds_gtid = KMP_GTID_DNE;
1269 th->th.th_info.ds.ds_thread_id = 0;
1275 void __kmp_reap_monitor(kmp_info_t *th) {
1278 KA_TRACE(10, (
"__kmp_reap_monitor: try to reap %p\n",
1279 (
void *)th->th.th_info.ds.ds_thread));
1284 KMP_DEBUG_ASSERT(th->th.th_info.ds.ds_tid == th->th.th_info.ds.ds_gtid);
1285 if (th->th.th_info.ds.ds_gtid != KMP_GTID_MONITOR) {
1286 KA_TRACE(10, (
"__kmp_reap_monitor: monitor did not start, returning\n"));
1292 status = SetEvent(__kmp_monitor_ev);
1293 if (status == FALSE) {
1294 DWORD error = GetLastError();
1295 __kmp_fatal(KMP_MSG(CantSetEvent), KMP_ERR(error), __kmp_msg_null);
1297 KA_TRACE(10, (
"__kmp_reap_monitor: reaping thread (%d)\n",
1298 th->th.th_info.ds.ds_gtid));
1299 __kmp_reap_common(th);
1301 __kmp_free_handle(__kmp_monitor_ev);
1307 void __kmp_reap_worker(kmp_info_t *th) {
1308 KA_TRACE(10, (
"__kmp_reap_worker: reaping thread (%d)\n",
1309 th->th.th_info.ds.ds_gtid));
1310 __kmp_reap_common(th);
1313 #if KMP_HANDLE_SIGNALS 1315 static void __kmp_team_handler(
int signo) {
1316 if (__kmp_global.g.g_abort == 0) {
1318 if (__kmp_debug_buf) {
1319 __kmp_dump_debug_buffer();
1322 TCW_4(__kmp_global.g.g_abort, signo);
1324 TCW_4(__kmp_global.g.g_done, TRUE);
1329 static sig_func_t __kmp_signal(
int signum, sig_func_t handler) {
1330 sig_func_t old = signal(signum, handler);
1331 if (old == SIG_ERR) {
1333 __kmp_fatal(KMP_MSG(FunctionError,
"signal"), KMP_ERR(error),
1339 static void __kmp_install_one_handler(
int sig, sig_func_t handler,
1340 int parallel_init) {
1343 KB_TRACE(60, (
"__kmp_install_one_handler: called: sig=%d\n", sig));
1344 if (parallel_init) {
1345 old = __kmp_signal(sig, handler);
1347 if (old == __kmp_sighldrs[sig]) {
1348 __kmp_siginstalled[sig] = 1;
1350 old = __kmp_signal(sig, old);
1356 old = __kmp_signal(sig, SIG_DFL);
1357 __kmp_sighldrs[sig] = old;
1358 __kmp_signal(sig, old);
1363 static void __kmp_remove_one_handler(
int sig) {
1364 if (__kmp_siginstalled[sig]) {
1367 KB_TRACE(60, (
"__kmp_remove_one_handler: called: sig=%d\n", sig));
1368 old = __kmp_signal(sig, __kmp_sighldrs[sig]);
1369 if (old != __kmp_team_handler) {
1370 KB_TRACE(10, (
"__kmp_remove_one_handler: oops, not our handler, " 1371 "restoring: sig=%d\n",
1373 old = __kmp_signal(sig, old);
1375 __kmp_sighldrs[sig] = NULL;
1376 __kmp_siginstalled[sig] = 0;
1381 void __kmp_install_signals(
int parallel_init) {
1382 KB_TRACE(10, (
"__kmp_install_signals: called\n"));
1383 if (!__kmp_handle_signals) {
1384 KB_TRACE(10, (
"__kmp_install_signals: KMP_HANDLE_SIGNALS is false - " 1385 "handlers not installed\n"));
1388 __kmp_install_one_handler(SIGINT, __kmp_team_handler, parallel_init);
1389 __kmp_install_one_handler(SIGILL, __kmp_team_handler, parallel_init);
1390 __kmp_install_one_handler(SIGABRT, __kmp_team_handler, parallel_init);
1391 __kmp_install_one_handler(SIGFPE, __kmp_team_handler, parallel_init);
1392 __kmp_install_one_handler(SIGSEGV, __kmp_team_handler, parallel_init);
1393 __kmp_install_one_handler(SIGTERM, __kmp_team_handler, parallel_init);
1396 void __kmp_remove_signals(
void) {
1398 KB_TRACE(10, (
"__kmp_remove_signals: called\n"));
1399 for (sig = 1; sig < NSIG; ++sig) {
1400 __kmp_remove_one_handler(sig);
1404 #endif // KMP_HANDLE_SIGNALS 1407 void __kmp_thread_sleep(
int millis) {
1410 status = SleepEx((DWORD)millis, FALSE);
1412 DWORD error = GetLastError();
1413 __kmp_fatal(KMP_MSG(FunctionError,
"SleepEx()"), KMP_ERR(error),
1419 int __kmp_is_address_mapped(
void *addr) {
1421 MEMORY_BASIC_INFORMATION lpBuffer;
1424 dwLength =
sizeof(MEMORY_BASIC_INFORMATION);
1426 status = VirtualQuery(addr, &lpBuffer, dwLength);
1428 return !(((lpBuffer.State == MEM_RESERVE) || (lpBuffer.State == MEM_FREE)) ||
1429 ((lpBuffer.Protect == PAGE_NOACCESS) ||
1430 (lpBuffer.Protect == PAGE_EXECUTE)));
1433 kmp_uint64 __kmp_hardware_timestamp(
void) {
1436 QueryPerformanceCounter((LARGE_INTEGER *)&r);
1441 void __kmp_free_handle(kmp_thread_t tHandle) {
1445 rc = CloseHandle(tHandle);
1447 DWORD error = GetLastError();
1448 __kmp_fatal(KMP_MSG(CantCloseHandle), KMP_ERR(error), __kmp_msg_null);
1452 int __kmp_get_load_balance(
int max) {
1453 static ULONG glb_buff_size = 100 * 1024;
1456 static int glb_running_threads = 0;
1457 static double glb_call_time = 0;
1459 int running_threads = 0;
1460 NTSTATUS status = 0;
1461 ULONG buff_size = 0;
1462 ULONG info_size = 0;
1463 void *buffer = NULL;
1464 PSYSTEM_PROCESS_INFORMATION spi = NULL;
1467 double call_time = 0.0;
1469 __kmp_elapsed(&call_time);
1471 if (glb_call_time &&
1472 (call_time - glb_call_time < __kmp_load_balance_interval)) {
1473 running_threads = glb_running_threads;
1476 glb_call_time = call_time;
1479 if (NtQuerySystemInformation == NULL) {
1480 running_threads = -1;
1491 buff_size = glb_buff_size;
1493 buff_size = 2 * buff_size;
1496 buffer = KMP_INTERNAL_REALLOC(buffer, buff_size);
1497 if (buffer == NULL) {
1498 running_threads = -1;
1501 status = NtQuerySystemInformation(SystemProcessInformation, buffer,
1502 buff_size, &info_size);
1505 }
while (status == STATUS_INFO_LENGTH_MISMATCH);
1506 glb_buff_size = buff_size;
1508 #define CHECK(cond) \ 1510 KMP_DEBUG_ASSERT(cond); \ 1512 running_threads = -1; \ 1517 CHECK(buff_size >= info_size);
1518 spi = PSYSTEM_PROCESS_INFORMATION(buffer);
1520 ptrdiff_t offset = uintptr_t(spi) - uintptr_t(buffer);
1521 CHECK(0 <= offset &&
1522 offset +
sizeof(SYSTEM_PROCESS_INFORMATION) < info_size);
1523 HANDLE pid = spi->ProcessId;
1524 ULONG num = spi->NumberOfThreads;
1527 sizeof(SYSTEM_PROCESS_INFORMATION) +
sizeof(SYSTEM_THREAD) * (num - 1);
1528 CHECK(offset + spi_size <
1530 if (spi->NextEntryOffset != 0) {
1532 spi->NextEntryOffset);
1538 for (
int i = 0; i < num; ++i) {
1539 THREAD_STATE state = spi->Threads[i].State;
1542 if (state == StateRunning) {
1546 if (running_threads >= max) {
1552 if (spi->NextEntryOffset == 0) {
1555 spi = PSYSTEM_PROCESS_INFORMATION(uintptr_t(spi) + spi->NextEntryOffset);
1562 if (buffer != NULL) {
1563 KMP_INTERNAL_FREE(buffer);
1566 glb_running_threads = running_threads;
1568 return running_threads;