LLVM OpenMP* Runtime Library
z_Windows_NT_util.cpp
1 /*
2  * z_Windows_NT_util.cpp -- platform specific routines.
3  */
4 
5 //===----------------------------------------------------------------------===//
6 //
7 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
8 // See https://llvm.org/LICENSE.txt for license information.
9 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "kmp.h"
14 #include "kmp_affinity.h"
15 #include "kmp_i18n.h"
16 #include "kmp_io.h"
17 #include "kmp_itt.h"
18 #include "kmp_wait_release.h"
19 
20 /* This code is related to NtQuerySystemInformation() function. This function
21  is used in the Load balance algorithm for OMP_DYNAMIC=true to find the
22  number of running threads in the system. */
23 
24 #include <ntsecapi.h> // UNICODE_STRING
25 #include <ntstatus.h>
26 #include <psapi.h>
27 #ifdef _MSC_VER
28 #pragma comment(lib, "psapi.lib")
29 #endif
30 
31 enum SYSTEM_INFORMATION_CLASS {
32  SystemProcessInformation = 5
33 }; // SYSTEM_INFORMATION_CLASS
34 
35 struct CLIENT_ID {
36  HANDLE UniqueProcess;
37  HANDLE UniqueThread;
38 }; // struct CLIENT_ID
39 
40 enum THREAD_STATE {
41  StateInitialized,
42  StateReady,
43  StateRunning,
44  StateStandby,
45  StateTerminated,
46  StateWait,
47  StateTransition,
48  StateUnknown
49 }; // enum THREAD_STATE
50 
51 struct VM_COUNTERS {
52  SIZE_T PeakVirtualSize;
53  SIZE_T VirtualSize;
54  ULONG PageFaultCount;
55  SIZE_T PeakWorkingSetSize;
56  SIZE_T WorkingSetSize;
57  SIZE_T QuotaPeakPagedPoolUsage;
58  SIZE_T QuotaPagedPoolUsage;
59  SIZE_T QuotaPeakNonPagedPoolUsage;
60  SIZE_T QuotaNonPagedPoolUsage;
61  SIZE_T PagefileUsage;
62  SIZE_T PeakPagefileUsage;
63  SIZE_T PrivatePageCount;
64 }; // struct VM_COUNTERS
65 
66 struct SYSTEM_THREAD {
67  LARGE_INTEGER KernelTime;
68  LARGE_INTEGER UserTime;
69  LARGE_INTEGER CreateTime;
70  ULONG WaitTime;
71  LPVOID StartAddress;
72  CLIENT_ID ClientId;
73  DWORD Priority;
74  LONG BasePriority;
75  ULONG ContextSwitchCount;
76  THREAD_STATE State;
77  ULONG WaitReason;
78 }; // SYSTEM_THREAD
79 
80 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, KernelTime) == 0);
81 #if KMP_ARCH_X86
82 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 28);
83 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 52);
84 #else
85 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, StartAddress) == 32);
86 KMP_BUILD_ASSERT(offsetof(SYSTEM_THREAD, State) == 68);
87 #endif
88 
89 struct SYSTEM_PROCESS_INFORMATION {
90  ULONG NextEntryOffset;
91  ULONG NumberOfThreads;
92  LARGE_INTEGER Reserved[3];
93  LARGE_INTEGER CreateTime;
94  LARGE_INTEGER UserTime;
95  LARGE_INTEGER KernelTime;
96  UNICODE_STRING ImageName;
97  DWORD BasePriority;
98  HANDLE ProcessId;
99  HANDLE ParentProcessId;
100  ULONG HandleCount;
101  ULONG Reserved2[2];
102  VM_COUNTERS VMCounters;
103  IO_COUNTERS IOCounters;
104  SYSTEM_THREAD Threads[1];
105 }; // SYSTEM_PROCESS_INFORMATION
106 typedef SYSTEM_PROCESS_INFORMATION *PSYSTEM_PROCESS_INFORMATION;
107 
108 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, NextEntryOffset) == 0);
109 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, CreateTime) == 32);
110 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ImageName) == 56);
111 #if KMP_ARCH_X86
112 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 68);
113 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 76);
114 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 88);
115 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 136);
116 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 184);
117 #else
118 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, ProcessId) == 80);
119 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, HandleCount) == 96);
120 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, VMCounters) == 112);
121 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, IOCounters) == 208);
122 KMP_BUILD_ASSERT(offsetof(SYSTEM_PROCESS_INFORMATION, Threads) == 256);
123 #endif
124 
125 typedef NTSTATUS(NTAPI *NtQuerySystemInformation_t)(SYSTEM_INFORMATION_CLASS,
126  PVOID, ULONG, PULONG);
127 NtQuerySystemInformation_t NtQuerySystemInformation = NULL;
128 
129 HMODULE ntdll = NULL;
130 
131 /* End of NtQuerySystemInformation()-related code */
132 
133 static HMODULE kernel32 = NULL;
134 
135 #if KMP_HANDLE_SIGNALS
136 typedef void (*sig_func_t)(int);
137 static sig_func_t __kmp_sighldrs[NSIG];
138 static int __kmp_siginstalled[NSIG];
139 #endif
140 
141 #if KMP_USE_MONITOR
142 static HANDLE __kmp_monitor_ev;
143 #endif
144 static kmp_int64 __kmp_win32_time;
145 double __kmp_win32_tick;
146 
147 int __kmp_init_runtime = FALSE;
148 CRITICAL_SECTION __kmp_win32_section;
149 
150 void __kmp_win32_mutex_init(kmp_win32_mutex_t *mx) {
151  InitializeCriticalSection(&mx->cs);
152 #if USE_ITT_BUILD
153  __kmp_itt_system_object_created(&mx->cs, "Critical Section");
154 #endif /* USE_ITT_BUILD */
155 }
156 
157 void __kmp_win32_mutex_destroy(kmp_win32_mutex_t *mx) {
158  DeleteCriticalSection(&mx->cs);
159 }
160 
161 void __kmp_win32_mutex_lock(kmp_win32_mutex_t *mx) {
162  EnterCriticalSection(&mx->cs);
163 }
164 
165 int __kmp_win32_mutex_trylock(kmp_win32_mutex_t *mx) {
166  return TryEnterCriticalSection(&mx->cs);
167 }
168 
169 void __kmp_win32_mutex_unlock(kmp_win32_mutex_t *mx) {
170  LeaveCriticalSection(&mx->cs);
171 }
172 
173 void __kmp_win32_cond_init(kmp_win32_cond_t *cv) {
174  cv->waiters_count_ = 0;
175  cv->wait_generation_count_ = 0;
176  cv->release_count_ = 0;
177 
178  /* Initialize the critical section */
179  __kmp_win32_mutex_init(&cv->waiters_count_lock_);
180 
181  /* Create a manual-reset event. */
182  cv->event_ = CreateEvent(NULL, // no security
183  TRUE, // manual-reset
184  FALSE, // non-signaled initially
185  NULL); // unnamed
186 #if USE_ITT_BUILD
187  __kmp_itt_system_object_created(cv->event_, "Event");
188 #endif /* USE_ITT_BUILD */
189 }
190 
191 void __kmp_win32_cond_destroy(kmp_win32_cond_t *cv) {
192  __kmp_win32_mutex_destroy(&cv->waiters_count_lock_);
193  __kmp_free_handle(cv->event_);
194  memset(cv, '\0', sizeof(*cv));
195 }
196 
197 /* TODO associate cv with a team instead of a thread so as to optimize
198  the case where we wake up a whole team */
199 
200 template <class C>
201 static void __kmp_win32_cond_wait(kmp_win32_cond_t *cv, kmp_win32_mutex_t *mx,
202  kmp_info_t *th, C *flag) {
203  int my_generation;
204  int last_waiter;
205 
206  /* Avoid race conditions */
207  __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
208 
209  /* Increment count of waiters */
210  cv->waiters_count_++;
211 
212  /* Store current generation in our activation record. */
213  my_generation = cv->wait_generation_count_;
214 
215  __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
216  __kmp_win32_mutex_unlock(mx);
217 
218  for (;;) {
219  int wait_done = 0;
220  DWORD res, timeout = 5000; // just tried to quess an appropriate number
221  /* Wait until the event is signaled */
222  res = WaitForSingleObject(cv->event_, timeout);
223 
224  if (res == WAIT_OBJECT_0) {
225  // event signaled
226  __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
227  /* Exit the loop when the <cv->event_> is signaled and there are still
228  waiting threads from this <wait_generation> that haven't been released
229  from this wait yet. */
230  wait_done = (cv->release_count_ > 0) &&
231  (cv->wait_generation_count_ != my_generation);
232  __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
233  } else if (res == WAIT_TIMEOUT || res == WAIT_FAILED) {
234  // check if the flag and cv counters are in consistent state
235  // as MS sent us debug dump whith inconsistent state of data
236  __kmp_win32_mutex_lock(mx);
237  typename C::flag_t old_f = flag->set_sleeping();
238  if (!flag->done_check_val(old_f & ~KMP_BARRIER_SLEEP_STATE)) {
239  __kmp_win32_mutex_unlock(mx);
240  continue;
241  }
242  // condition fulfilled, exiting
243  flag->unset_sleeping();
244  TCW_PTR(th->th.th_sleep_loc, NULL);
245  th->th.th_sleep_loc_type = flag_unset;
246  KF_TRACE(50, ("__kmp_win32_cond_wait: exiting, condition "
247  "fulfilled: flag's loc(%p): %u\n",
248  flag->get(), (unsigned int)flag->load()));
249 
250  __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
251  KMP_DEBUG_ASSERT(cv->waiters_count_ > 0);
252  cv->release_count_ = cv->waiters_count_;
253  cv->wait_generation_count_++;
254  wait_done = 1;
255  __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
256 
257  __kmp_win32_mutex_unlock(mx);
258  }
259  /* there used to be a semicolon after the if statement, it looked like a
260  bug, so i removed it */
261  if (wait_done)
262  break;
263  }
264 
265  __kmp_win32_mutex_lock(mx);
266  __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
267 
268  cv->waiters_count_--;
269  cv->release_count_--;
270 
271  last_waiter = (cv->release_count_ == 0);
272 
273  __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
274 
275  if (last_waiter) {
276  /* We're the last waiter to be notified, so reset the manual event. */
277  ResetEvent(cv->event_);
278  }
279 }
280 
281 void __kmp_win32_cond_broadcast(kmp_win32_cond_t *cv) {
282  __kmp_win32_mutex_lock(&cv->waiters_count_lock_);
283 
284  if (cv->waiters_count_ > 0) {
285  SetEvent(cv->event_);
286  /* Release all the threads in this generation. */
287 
288  cv->release_count_ = cv->waiters_count_;
289 
290  /* Start a new generation. */
291  cv->wait_generation_count_++;
292  }
293 
294  __kmp_win32_mutex_unlock(&cv->waiters_count_lock_);
295 }
296 
297 void __kmp_win32_cond_signal(kmp_win32_cond_t *cv) {
298  __kmp_win32_cond_broadcast(cv);
299 }
300 
301 void __kmp_enable(int new_state) {
302  if (__kmp_init_runtime)
303  LeaveCriticalSection(&__kmp_win32_section);
304 }
305 
306 void __kmp_disable(int *old_state) {
307  *old_state = 0;
308 
309  if (__kmp_init_runtime)
310  EnterCriticalSection(&__kmp_win32_section);
311 }
312 
313 void __kmp_suspend_initialize(void) { /* do nothing */
314 }
315 
316 void __kmp_suspend_initialize_thread(kmp_info_t *th) {
317  int old_value = KMP_ATOMIC_LD_RLX(&th->th.th_suspend_init);
318  int new_value = TRUE;
319  // Return if already initialized
320  if (old_value == new_value)
321  return;
322  // Wait, then return if being initialized
323  if (old_value == -1 ||
324  !__kmp_atomic_compare_store(&th->th.th_suspend_init, old_value, -1)) {
325  while (KMP_ATOMIC_LD_ACQ(&th->th.th_suspend_init) != new_value) {
326  KMP_CPU_PAUSE();
327  }
328  } else {
329  // Claim to be the initializer and do initializations
330  __kmp_win32_cond_init(&th->th.th_suspend_cv);
331  __kmp_win32_mutex_init(&th->th.th_suspend_mx);
332  KMP_ATOMIC_ST_REL(&th->th.th_suspend_init, new_value);
333  }
334 }
335 
336 void __kmp_suspend_uninitialize_thread(kmp_info_t *th) {
337  if (KMP_ATOMIC_LD_ACQ(&th->th.th_suspend_init)) {
338  /* this means we have initialize the suspension pthread objects for this
339  thread in this instance of the process */
340  __kmp_win32_cond_destroy(&th->th.th_suspend_cv);
341  __kmp_win32_mutex_destroy(&th->th.th_suspend_mx);
342  KMP_ATOMIC_ST_REL(&th->th.th_suspend_init, FALSE);
343  }
344 }
345 
346 int __kmp_try_suspend_mx(kmp_info_t *th) {
347  return __kmp_win32_mutex_trylock(&th->th.th_suspend_mx);
348 }
349 
350 void __kmp_lock_suspend_mx(kmp_info_t *th) {
351  __kmp_win32_mutex_lock(&th->th.th_suspend_mx);
352 }
353 
354 void __kmp_unlock_suspend_mx(kmp_info_t *th) {
355  __kmp_win32_mutex_unlock(&th->th.th_suspend_mx);
356 }
357 
358 /* This routine puts the calling thread to sleep after setting the
359  sleep bit for the indicated flag variable to true. */
360 template <class C>
361 static inline void __kmp_suspend_template(int th_gtid, C *flag) {
362  kmp_info_t *th = __kmp_threads[th_gtid];
363  typename C::flag_t old_spin;
364 
365  KF_TRACE(30, ("__kmp_suspend_template: T#%d enter for flag's loc(%p)\n",
366  th_gtid, flag->get()));
367 
368  __kmp_suspend_initialize_thread(th);
369  __kmp_lock_suspend_mx(th);
370 
371  KF_TRACE(10, ("__kmp_suspend_template: T#%d setting sleep bit for flag's"
372  " loc(%p)\n",
373  th_gtid, flag->get()));
374 
375  /* TODO: shouldn't this use release semantics to ensure that
376  __kmp_suspend_initialize_thread gets called first? */
377  old_spin = flag->set_sleeping();
378  TCW_PTR(th->th.th_sleep_loc, (void *)flag);
379  th->th.th_sleep_loc_type = flag->get_type();
380  if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME &&
381  __kmp_pause_status != kmp_soft_paused) {
382  flag->unset_sleeping();
383  TCW_PTR(th->th.th_sleep_loc, NULL);
384  th->th.th_sleep_loc_type = flag_unset;
385  __kmp_unlock_suspend_mx(th);
386  return;
387  }
388 
389  KF_TRACE(5, ("__kmp_suspend_template: T#%d set sleep bit for flag's"
390  " loc(%p)==%u\n",
391  th_gtid, flag->get(), (unsigned int)flag->load()));
392 
393  if (flag->done_check_val(old_spin) || flag->done_check()) {
394  flag->unset_sleeping();
395  TCW_PTR(th->th.th_sleep_loc, NULL);
396  th->th.th_sleep_loc_type = flag_unset;
397  KF_TRACE(5, ("__kmp_suspend_template: T#%d false alarm, reset sleep bit "
398  "for flag's loc(%p)\n",
399  th_gtid, flag->get()));
400  } else {
401 #ifdef DEBUG_SUSPEND
402  __kmp_suspend_count++;
403 #endif
404  /* Encapsulate in a loop as the documentation states that this may "with
405  low probability" return when the condition variable has not been signaled
406  or broadcast */
407  int deactivated = FALSE;
408 
409  while (flag->is_sleeping()) {
410  KF_TRACE(15, ("__kmp_suspend_template: T#%d about to perform "
411  "kmp_win32_cond_wait()\n",
412  th_gtid));
413  // Mark the thread as no longer active (only in the first iteration of the
414  // loop).
415  if (!deactivated) {
416  th->th.th_active = FALSE;
417  if (th->th.th_active_in_pool) {
418  th->th.th_active_in_pool = FALSE;
419  KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth);
420  KMP_DEBUG_ASSERT(TCR_4(__kmp_thread_pool_active_nth) >= 0);
421  }
422  deactivated = TRUE;
423  }
424 
425  KMP_DEBUG_ASSERT(th->th.th_sleep_loc);
426  KMP_DEBUG_ASSERT(th->th.th_sleep_loc_type == flag->get_type());
427 
428  __kmp_win32_cond_wait(&th->th.th_suspend_cv, &th->th.th_suspend_mx, th,
429  flag);
430 
431 #ifdef KMP_DEBUG
432  if (flag->is_sleeping()) {
433  KF_TRACE(100,
434  ("__kmp_suspend_template: T#%d spurious wakeup\n", th_gtid));
435  }
436 #endif /* KMP_DEBUG */
437 
438  } // while
439 
440  // We may have had the loop variable set before entering the loop body;
441  // so we need to reset sleep_loc.
442  TCW_PTR(th->th.th_sleep_loc, NULL);
443  th->th.th_sleep_loc_type = flag_unset;
444 
445  KMP_DEBUG_ASSERT(!flag->is_sleeping());
446  KMP_DEBUG_ASSERT(!th->th.th_sleep_loc);
447 
448  // Mark the thread as active again (if it was previous marked as inactive)
449  if (deactivated) {
450  th->th.th_active = TRUE;
451  if (TCR_4(th->th.th_in_pool)) {
452  KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth);
453  th->th.th_active_in_pool = TRUE;
454  }
455  }
456  }
457 
458  __kmp_unlock_suspend_mx(th);
459  KF_TRACE(30, ("__kmp_suspend_template: T#%d exit\n", th_gtid));
460 }
461 
462 template <bool C, bool S>
463 void __kmp_suspend_32(int th_gtid, kmp_flag_32<C, S> *flag) {
464  __kmp_suspend_template(th_gtid, flag);
465 }
466 template <bool C, bool S>
467 void __kmp_suspend_64(int th_gtid, kmp_flag_64<C, S> *flag) {
468  __kmp_suspend_template(th_gtid, flag);
469 }
470 template <bool C, bool S>
471 void __kmp_atomic_suspend_64(int th_gtid, kmp_atomic_flag_64<C, S> *flag) {
472  __kmp_suspend_template(th_gtid, flag);
473 }
474 void __kmp_suspend_oncore(int th_gtid, kmp_flag_oncore *flag) {
475  __kmp_suspend_template(th_gtid, flag);
476 }
477 
478 template void __kmp_suspend_32<false, false>(int, kmp_flag_32<false, false> *);
479 template void __kmp_suspend_64<false, true>(int, kmp_flag_64<false, true> *);
480 template void __kmp_suspend_64<true, false>(int, kmp_flag_64<true, false> *);
481 template void
482 __kmp_atomic_suspend_64<false, true>(int, kmp_atomic_flag_64<false, true> *);
483 template void
484 __kmp_atomic_suspend_64<true, false>(int, kmp_atomic_flag_64<true, false> *);
485 
486 /* This routine signals the thread specified by target_gtid to wake up
487  after setting the sleep bit indicated by the flag argument to FALSE */
488 template <class C>
489 static inline void __kmp_resume_template(int target_gtid, C *flag) {
490  kmp_info_t *th = __kmp_threads[target_gtid];
491 
492 #ifdef KMP_DEBUG
493  int gtid = TCR_4(__kmp_init_gtid) ? __kmp_get_gtid() : -1;
494 #endif
495 
496  KF_TRACE(30, ("__kmp_resume_template: T#%d wants to wakeup T#%d enter\n",
497  gtid, target_gtid));
498 
499  __kmp_suspend_initialize_thread(th);
500  __kmp_lock_suspend_mx(th);
501 
502  if (!flag || flag != th->th.th_sleep_loc) {
503  // coming from __kmp_null_resume_wrapper, or thread is now sleeping on a
504  // different location; wake up at new location
505  flag = (C *)th->th.th_sleep_loc;
506  }
507 
508  // First, check if the flag is null or its type has changed. If so, someone
509  // else woke it up.
510  if (!flag || flag->get_type() != th->th.th_sleep_loc_type) {
511  // simply shows what flag was cast to
512  KF_TRACE(5, ("__kmp_resume_template: T#%d exiting, thread T#%d already "
513  "awake: flag's loc(%p)\n",
514  gtid, target_gtid, NULL));
515  __kmp_unlock_suspend_mx(th);
516  return;
517  } else {
518  if (!flag->is_sleeping()) {
519  KF_TRACE(5, ("__kmp_resume_template: T#%d exiting, thread T#%d already "
520  "awake: flag's loc(%p): %u\n",
521  gtid, target_gtid, flag->get(), (unsigned int)flag->load()));
522  __kmp_unlock_suspend_mx(th);
523  return;
524  }
525  }
526  KMP_DEBUG_ASSERT(flag);
527  flag->unset_sleeping();
528  TCW_PTR(th->th.th_sleep_loc, NULL);
529  th->th.th_sleep_loc_type = flag_unset;
530 
531  KF_TRACE(5, ("__kmp_resume_template: T#%d about to wakeup T#%d, reset sleep "
532  "bit for flag's loc(%p)\n",
533  gtid, target_gtid, flag->get()));
534 
535  __kmp_win32_cond_signal(&th->th.th_suspend_cv);
536  __kmp_unlock_suspend_mx(th);
537 
538  KF_TRACE(30, ("__kmp_resume_template: T#%d exiting after signaling wake up"
539  " for T#%d\n",
540  gtid, target_gtid));
541 }
542 
543 template <bool C, bool S>
544 void __kmp_resume_32(int target_gtid, kmp_flag_32<C, S> *flag) {
545  __kmp_resume_template(target_gtid, flag);
546 }
547 template <bool C, bool S>
548 void __kmp_resume_64(int target_gtid, kmp_flag_64<C, S> *flag) {
549  __kmp_resume_template(target_gtid, flag);
550 }
551 template <bool C, bool S>
552 void __kmp_atomic_resume_64(int target_gtid, kmp_atomic_flag_64<C, S> *flag) {
553  __kmp_resume_template(target_gtid, flag);
554 }
555 void __kmp_resume_oncore(int target_gtid, kmp_flag_oncore *flag) {
556  __kmp_resume_template(target_gtid, flag);
557 }
558 
559 template void __kmp_resume_32<false, true>(int, kmp_flag_32<false, true> *);
560 template void __kmp_resume_32<false, false>(int, kmp_flag_32<false, false> *);
561 template void __kmp_resume_64<false, true>(int, kmp_flag_64<false, true> *);
562 template void
563 __kmp_atomic_resume_64<false, true>(int, kmp_atomic_flag_64<false, true> *);
564 
565 void __kmp_yield() { Sleep(0); }
566 
567 void __kmp_gtid_set_specific(int gtid) {
568  if (__kmp_init_gtid) {
569  KA_TRACE(50, ("__kmp_gtid_set_specific: T#%d key:%d\n", gtid,
570  __kmp_gtid_threadprivate_key));
571  if (!TlsSetValue(__kmp_gtid_threadprivate_key, (LPVOID)(gtid + 1)))
572  KMP_FATAL(TLSSetValueFailed);
573  } else {
574  KA_TRACE(50, ("__kmp_gtid_set_specific: runtime shutdown, returning\n"));
575  }
576 }
577 
578 int __kmp_gtid_get_specific() {
579  int gtid;
580  if (!__kmp_init_gtid) {
581  KA_TRACE(50, ("__kmp_gtid_get_specific: runtime shutdown, returning "
582  "KMP_GTID_SHUTDOWN\n"));
583  return KMP_GTID_SHUTDOWN;
584  }
585  gtid = (int)(kmp_intptr_t)TlsGetValue(__kmp_gtid_threadprivate_key);
586  if (gtid == 0) {
587  gtid = KMP_GTID_DNE;
588  } else {
589  gtid--;
590  }
591  KA_TRACE(50, ("__kmp_gtid_get_specific: key:%d gtid:%d\n",
592  __kmp_gtid_threadprivate_key, gtid));
593  return gtid;
594 }
595 
596 void __kmp_affinity_bind_thread(int proc) {
597  if (__kmp_num_proc_groups > 1) {
598  // Form the GROUP_AFFINITY struct directly, rather than filling
599  // out a bit vector and calling __kmp_set_system_affinity().
600  GROUP_AFFINITY ga;
601  KMP_DEBUG_ASSERT((proc >= 0) && (proc < (__kmp_num_proc_groups * CHAR_BIT *
602  sizeof(DWORD_PTR))));
603  ga.Group = proc / (CHAR_BIT * sizeof(DWORD_PTR));
604  ga.Mask = (unsigned long long)1 << (proc % (CHAR_BIT * sizeof(DWORD_PTR)));
605  ga.Reserved[0] = ga.Reserved[1] = ga.Reserved[2] = 0;
606 
607  KMP_DEBUG_ASSERT(__kmp_SetThreadGroupAffinity != NULL);
608  if (__kmp_SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) == 0) {
609  DWORD error = GetLastError();
610  if (__kmp_affinity_verbose) { // AC: continue silently if not verbose
611  kmp_msg_t err_code = KMP_ERR(error);
612  __kmp_msg(kmp_ms_warning, KMP_MSG(CantSetThreadAffMask), err_code,
613  __kmp_msg_null);
614  if (__kmp_generate_warnings == kmp_warnings_off) {
615  __kmp_str_free(&err_code.str);
616  }
617  }
618  }
619  } else {
620  kmp_affin_mask_t *mask;
621  KMP_CPU_ALLOC_ON_STACK(mask);
622  KMP_CPU_ZERO(mask);
623  KMP_CPU_SET(proc, mask);
624  __kmp_set_system_affinity(mask, TRUE);
625  KMP_CPU_FREE_FROM_STACK(mask);
626  }
627 }
628 
629 void __kmp_affinity_determine_capable(const char *env_var) {
630  // All versions of Windows* OS (since Win '95) support
631  // SetThreadAffinityMask().
632 
633 #if KMP_GROUP_AFFINITY
634  KMP_AFFINITY_ENABLE(__kmp_num_proc_groups * sizeof(DWORD_PTR));
635 #else
636  KMP_AFFINITY_ENABLE(sizeof(DWORD_PTR));
637 #endif
638 
639  KA_TRACE(10, ("__kmp_affinity_determine_capable: "
640  "Windows* OS affinity interface functional (mask size = "
641  "%" KMP_SIZE_T_SPEC ").\n",
642  __kmp_affin_mask_size));
643 }
644 
645 double __kmp_read_cpu_time(void) {
646  FILETIME CreationTime, ExitTime, KernelTime, UserTime;
647  int status;
648  double cpu_time;
649 
650  cpu_time = 0;
651 
652  status = GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime,
653  &KernelTime, &UserTime);
654 
655  if (status) {
656  double sec = 0;
657 
658  sec += KernelTime.dwHighDateTime;
659  sec += UserTime.dwHighDateTime;
660 
661  /* Shift left by 32 bits */
662  sec *= (double)(1 << 16) * (double)(1 << 16);
663 
664  sec += KernelTime.dwLowDateTime;
665  sec += UserTime.dwLowDateTime;
666 
667  cpu_time += (sec * 100.0) / KMP_NSEC_PER_SEC;
668  }
669 
670  return cpu_time;
671 }
672 
673 int __kmp_read_system_info(struct kmp_sys_info *info) {
674  info->maxrss = 0; /* the maximum resident set size utilized (in kilobytes) */
675  info->minflt = 0; /* the number of page faults serviced without any I/O */
676  info->majflt = 0; /* the number of page faults serviced that required I/O */
677  info->nswap = 0; // the number of times a process was "swapped" out of memory
678  info->inblock = 0; // the number of times the file system had to perform input
679  info->oublock = 0; // number of times the file system had to perform output
680  info->nvcsw = 0; /* the number of times a context switch was voluntarily */
681  info->nivcsw = 0; /* the number of times a context switch was forced */
682 
683  return 1;
684 }
685 
686 void __kmp_runtime_initialize(void) {
687  SYSTEM_INFO info;
688  kmp_str_buf_t path;
689  UINT path_size;
690 
691  if (__kmp_init_runtime) {
692  return;
693  }
694 
695 #if KMP_DYNAMIC_LIB
696  /* Pin dynamic library for the lifetime of application */
697  {
698  // First, turn off error message boxes
699  UINT err_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
700  HMODULE h;
701  BOOL ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
702  GET_MODULE_HANDLE_EX_FLAG_PIN,
703  (LPCTSTR)&__kmp_serial_initialize, &h);
704  (void)ret;
705  KMP_DEBUG_ASSERT2(h && ret, "OpenMP RTL cannot find itself loaded");
706  SetErrorMode(err_mode); // Restore error mode
707  KA_TRACE(10, ("__kmp_runtime_initialize: dynamic library pinned\n"));
708  }
709 #endif
710 
711  InitializeCriticalSection(&__kmp_win32_section);
712 #if USE_ITT_BUILD
713  __kmp_itt_system_object_created(&__kmp_win32_section, "Critical Section");
714 #endif /* USE_ITT_BUILD */
715  __kmp_initialize_system_tick();
716 
717 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64)
718  if (!__kmp_cpuinfo.initialized) {
719  __kmp_query_cpuid(&__kmp_cpuinfo);
720  }
721 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
722 
723 /* Set up minimum number of threads to switch to TLS gtid */
724 #if KMP_OS_WINDOWS && !KMP_DYNAMIC_LIB
725  // Windows* OS, static library.
726  /* New thread may use stack space previously used by another thread,
727  currently terminated. On Windows* OS, in case of static linking, we do not
728  know the moment of thread termination, and our structures (__kmp_threads
729  and __kmp_root arrays) are still keep info about dead threads. This leads
730  to problem in __kmp_get_global_thread_id() function: it wrongly finds gtid
731  (by searching through stack addresses of all known threads) for
732  unregistered foreign tread.
733 
734  Setting __kmp_tls_gtid_min to 0 workarounds this problem:
735  __kmp_get_global_thread_id() does not search through stacks, but get gtid
736  from TLS immediately.
737  --ln
738  */
739  __kmp_tls_gtid_min = 0;
740 #else
741  __kmp_tls_gtid_min = KMP_TLS_GTID_MIN;
742 #endif
743 
744  /* for the static library */
745  if (!__kmp_gtid_threadprivate_key) {
746  __kmp_gtid_threadprivate_key = TlsAlloc();
747  if (__kmp_gtid_threadprivate_key == TLS_OUT_OF_INDEXES) {
748  KMP_FATAL(TLSOutOfIndexes);
749  }
750  }
751 
752  // Load ntdll.dll.
753  /* Simple GetModuleHandle( "ntdll.dl" ) is not suitable due to security issue
754  (see http://www.microsoft.com/technet/security/advisory/2269637.mspx). We
755  have to specify full path to the library. */
756  __kmp_str_buf_init(&path);
757  path_size = GetSystemDirectory(path.str, path.size);
758  KMP_DEBUG_ASSERT(path_size > 0);
759  if (path_size >= path.size) {
760  // Buffer is too short. Expand the buffer and try again.
761  __kmp_str_buf_reserve(&path, path_size);
762  path_size = GetSystemDirectory(path.str, path.size);
763  KMP_DEBUG_ASSERT(path_size > 0);
764  }
765  if (path_size > 0 && path_size < path.size) {
766  // Now we have system directory name in the buffer.
767  // Append backslash and name of dll to form full path,
768  path.used = path_size;
769  __kmp_str_buf_print(&path, "\\%s", "ntdll.dll");
770 
771  // Now load ntdll using full path.
772  ntdll = GetModuleHandle(path.str);
773  }
774 
775  KMP_DEBUG_ASSERT(ntdll != NULL);
776  if (ntdll != NULL) {
777  NtQuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(
778  ntdll, "NtQuerySystemInformation");
779  }
780  KMP_DEBUG_ASSERT(NtQuerySystemInformation != NULL);
781 
782 #if KMP_GROUP_AFFINITY
783  // Load kernel32.dll.
784  // Same caveat - must use full system path name.
785  if (path_size > 0 && path_size < path.size) {
786  // Truncate the buffer back to just the system path length,
787  // discarding "\\ntdll.dll", and replacing it with "kernel32.dll".
788  path.used = path_size;
789  __kmp_str_buf_print(&path, "\\%s", "kernel32.dll");
790 
791  // Load kernel32.dll using full path.
792  kernel32 = GetModuleHandle(path.str);
793  KA_TRACE(10, ("__kmp_runtime_initialize: kernel32.dll = %s\n", path.str));
794 
795  // Load the function pointers to kernel32.dll routines
796  // that may or may not exist on this system.
797  if (kernel32 != NULL) {
798  __kmp_GetActiveProcessorCount =
799  (kmp_GetActiveProcessorCount_t)GetProcAddress(
800  kernel32, "GetActiveProcessorCount");
801  __kmp_GetActiveProcessorGroupCount =
802  (kmp_GetActiveProcessorGroupCount_t)GetProcAddress(
803  kernel32, "GetActiveProcessorGroupCount");
804  __kmp_GetThreadGroupAffinity =
805  (kmp_GetThreadGroupAffinity_t)GetProcAddress(
806  kernel32, "GetThreadGroupAffinity");
807  __kmp_SetThreadGroupAffinity =
808  (kmp_SetThreadGroupAffinity_t)GetProcAddress(
809  kernel32, "SetThreadGroupAffinity");
810 
811  KA_TRACE(10, ("__kmp_runtime_initialize: __kmp_GetActiveProcessorCount"
812  " = %p\n",
813  __kmp_GetActiveProcessorCount));
814  KA_TRACE(10, ("__kmp_runtime_initialize: "
815  "__kmp_GetActiveProcessorGroupCount = %p\n",
816  __kmp_GetActiveProcessorGroupCount));
817  KA_TRACE(10, ("__kmp_runtime_initialize:__kmp_GetThreadGroupAffinity"
818  " = %p\n",
819  __kmp_GetThreadGroupAffinity));
820  KA_TRACE(10, ("__kmp_runtime_initialize: __kmp_SetThreadGroupAffinity"
821  " = %p\n",
822  __kmp_SetThreadGroupAffinity));
823  KA_TRACE(10, ("__kmp_runtime_initialize: sizeof(kmp_affin_mask_t) = %d\n",
824  sizeof(kmp_affin_mask_t)));
825 
826  // See if group affinity is supported on this system.
827  // If so, calculate the #groups and #procs.
828  //
829  // Group affinity was introduced with Windows* 7 OS and
830  // Windows* Server 2008 R2 OS.
831  if ((__kmp_GetActiveProcessorCount != NULL) &&
832  (__kmp_GetActiveProcessorGroupCount != NULL) &&
833  (__kmp_GetThreadGroupAffinity != NULL) &&
834  (__kmp_SetThreadGroupAffinity != NULL) &&
835  ((__kmp_num_proc_groups = __kmp_GetActiveProcessorGroupCount()) >
836  1)) {
837  // Calculate the total number of active OS procs.
838  int i;
839 
840  KA_TRACE(10, ("__kmp_runtime_initialize: %d processor groups"
841  " detected\n",
842  __kmp_num_proc_groups));
843 
844  __kmp_xproc = 0;
845 
846  for (i = 0; i < __kmp_num_proc_groups; i++) {
847  DWORD size = __kmp_GetActiveProcessorCount(i);
848  __kmp_xproc += size;
849  KA_TRACE(10, ("__kmp_runtime_initialize: proc group %d size = %d\n",
850  i, size));
851  }
852  } else {
853  KA_TRACE(10, ("__kmp_runtime_initialize: %d processor groups"
854  " detected\n",
855  __kmp_num_proc_groups));
856  }
857  }
858  }
859  if (__kmp_num_proc_groups <= 1) {
860  GetSystemInfo(&info);
861  __kmp_xproc = info.dwNumberOfProcessors;
862  }
863 #else
864  (void)kernel32;
865  GetSystemInfo(&info);
866  __kmp_xproc = info.dwNumberOfProcessors;
867 #endif /* KMP_GROUP_AFFINITY */
868 
869  // If the OS said there were 0 procs, take a guess and use a value of 2.
870  // This is done for Linux* OS, also. Do we need error / warning?
871  if (__kmp_xproc <= 0) {
872  __kmp_xproc = 2;
873  }
874 
875  KA_TRACE(5,
876  ("__kmp_runtime_initialize: total processors = %d\n", __kmp_xproc));
877 
878  __kmp_str_buf_free(&path);
879 
880 #if USE_ITT_BUILD
881  __kmp_itt_initialize();
882 #endif /* USE_ITT_BUILD */
883 
884  __kmp_init_runtime = TRUE;
885 } // __kmp_runtime_initialize
886 
887 void __kmp_runtime_destroy(void) {
888  if (!__kmp_init_runtime) {
889  return;
890  }
891 
892 #if USE_ITT_BUILD
893  __kmp_itt_destroy();
894 #endif /* USE_ITT_BUILD */
895 
896  /* we can't DeleteCriticalsection( & __kmp_win32_section ); */
897  /* due to the KX_TRACE() commands */
898  KA_TRACE(40, ("__kmp_runtime_destroy\n"));
899 
900  if (__kmp_gtid_threadprivate_key) {
901  TlsFree(__kmp_gtid_threadprivate_key);
902  __kmp_gtid_threadprivate_key = 0;
903  }
904 
905  __kmp_affinity_uninitialize();
906  DeleteCriticalSection(&__kmp_win32_section);
907 
908  ntdll = NULL;
909  NtQuerySystemInformation = NULL;
910 
911 #if KMP_ARCH_X86_64
912  kernel32 = NULL;
913  __kmp_GetActiveProcessorCount = NULL;
914  __kmp_GetActiveProcessorGroupCount = NULL;
915  __kmp_GetThreadGroupAffinity = NULL;
916  __kmp_SetThreadGroupAffinity = NULL;
917 #endif // KMP_ARCH_X86_64
918 
919  __kmp_init_runtime = FALSE;
920 }
921 
922 void __kmp_terminate_thread(int gtid) {
923  kmp_info_t *th = __kmp_threads[gtid];
924 
925  if (!th)
926  return;
927 
928  KA_TRACE(10, ("__kmp_terminate_thread: kill (%d)\n", gtid));
929 
930  if (TerminateThread(th->th.th_info.ds.ds_thread, (DWORD)-1) == FALSE) {
931  /* It's OK, the thread may have exited already */
932  }
933  __kmp_free_handle(th->th.th_info.ds.ds_thread);
934 }
935 
936 void __kmp_clear_system_time(void) {
937  BOOL status;
938  LARGE_INTEGER time;
939  status = QueryPerformanceCounter(&time);
940  __kmp_win32_time = (kmp_int64)time.QuadPart;
941 }
942 
943 void __kmp_initialize_system_tick(void) {
944  {
945  BOOL status;
946  LARGE_INTEGER freq;
947 
948  status = QueryPerformanceFrequency(&freq);
949  if (!status) {
950  DWORD error = GetLastError();
951  __kmp_fatal(KMP_MSG(FunctionError, "QueryPerformanceFrequency()"),
952  KMP_ERR(error), __kmp_msg_null);
953 
954  } else {
955  __kmp_win32_tick = ((double)1.0) / (double)freq.QuadPart;
956  }
957  }
958 }
959 
960 /* Calculate the elapsed wall clock time for the user */
961 
962 void __kmp_elapsed(double *t) {
963  BOOL status;
964  LARGE_INTEGER now;
965  status = QueryPerformanceCounter(&now);
966  *t = ((double)now.QuadPart) * __kmp_win32_tick;
967 }
968 
969 /* Calculate the elapsed wall clock tick for the user */
970 
971 void __kmp_elapsed_tick(double *t) { *t = __kmp_win32_tick; }
972 
973 void __kmp_read_system_time(double *delta) {
974  if (delta != NULL) {
975  BOOL status;
976  LARGE_INTEGER now;
977 
978  status = QueryPerformanceCounter(&now);
979 
980  *delta = ((double)(((kmp_int64)now.QuadPart) - __kmp_win32_time)) *
981  __kmp_win32_tick;
982  }
983 }
984 
985 /* Return the current time stamp in nsec */
986 kmp_uint64 __kmp_now_nsec() {
987  LARGE_INTEGER now;
988  QueryPerformanceCounter(&now);
989  return 1e9 * __kmp_win32_tick * now.QuadPart;
990 }
991 
992 extern "C" void *__stdcall __kmp_launch_worker(void *arg) {
993  volatile void *stack_data;
994  void *exit_val;
995  void *padding = 0;
996  kmp_info_t *this_thr = (kmp_info_t *)arg;
997  int gtid;
998 
999  gtid = this_thr->th.th_info.ds.ds_gtid;
1000  __kmp_gtid_set_specific(gtid);
1001 #ifdef KMP_TDATA_GTID
1002 #error "This define causes problems with LoadLibrary() + declspec(thread) " \
1003  "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \
1004  "reference: http://support.microsoft.com/kb/118816"
1005 //__kmp_gtid = gtid;
1006 #endif
1007 
1008 #if USE_ITT_BUILD
1009  __kmp_itt_thread_name(gtid);
1010 #endif /* USE_ITT_BUILD */
1011 
1012  __kmp_affinity_set_init_mask(gtid, FALSE);
1013 
1014 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
1015  // Set FP control regs to be a copy of the parallel initialization thread's.
1016  __kmp_clear_x87_fpu_status_word();
1017  __kmp_load_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word);
1018  __kmp_load_mxcsr(&__kmp_init_mxcsr);
1019 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
1020 
1021  if (__kmp_stkoffset > 0 && gtid > 0) {
1022  padding = KMP_ALLOCA(gtid * __kmp_stkoffset);
1023  }
1024 
1025  KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
1026  this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1027  TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
1028 
1029  if (TCR_4(__kmp_gtid_mode) <
1030  2) { // check stack only if it is used to get gtid
1031  TCW_PTR(this_thr->th.th_info.ds.ds_stackbase, &stack_data);
1032  KMP_ASSERT(this_thr->th.th_info.ds.ds_stackgrow == FALSE);
1033  __kmp_check_stack_overlap(this_thr);
1034  }
1035  KMP_MB();
1036  exit_val = __kmp_launch_thread(this_thr);
1037  KMP_FSYNC_RELEASING(&this_thr->th.th_info.ds.ds_alive);
1038  TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
1039  KMP_MB();
1040  return exit_val;
1041 }
1042 
1043 #if KMP_USE_MONITOR
1044 /* The monitor thread controls all of the threads in the complex */
1045 
1046 void *__stdcall __kmp_launch_monitor(void *arg) {
1047  DWORD wait_status;
1048  kmp_thread_t monitor;
1049  int status;
1050  int interval;
1051  kmp_info_t *this_thr = (kmp_info_t *)arg;
1052 
1053  KMP_DEBUG_ASSERT(__kmp_init_monitor);
1054  TCW_4(__kmp_init_monitor, 2); // AC: Signal library that monitor has started
1055  // TODO: hide "2" in enum (like {true,false,started})
1056  this_thr->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1057  TCW_4(this_thr->th.th_info.ds.ds_alive, TRUE);
1058 
1059  KMP_MB(); /* Flush all pending memory write invalidates. */
1060  KA_TRACE(10, ("__kmp_launch_monitor: launched\n"));
1061 
1062  monitor = GetCurrentThread();
1063 
1064  /* set thread priority */
1065  status = SetThreadPriority(monitor, THREAD_PRIORITY_HIGHEST);
1066  if (!status) {
1067  DWORD error = GetLastError();
1068  __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
1069  }
1070 
1071  /* register us as monitor */
1072  __kmp_gtid_set_specific(KMP_GTID_MONITOR);
1073 #ifdef KMP_TDATA_GTID
1074 #error "This define causes problems with LoadLibrary() + declspec(thread) " \
1075  "on Windows* OS. See CQ50564, tests kmp_load_library*.c and this MSDN " \
1076  "reference: http://support.microsoft.com/kb/118816"
1077 //__kmp_gtid = KMP_GTID_MONITOR;
1078 #endif
1079 
1080 #if USE_ITT_BUILD
1081  __kmp_itt_thread_ignore(); // Instruct Intel(R) Threading Tools to ignore
1082 // monitor thread.
1083 #endif /* USE_ITT_BUILD */
1084 
1085  KMP_MB(); /* Flush all pending memory write invalidates. */
1086 
1087  interval = (1000 / __kmp_monitor_wakeups); /* in milliseconds */
1088 
1089  while (!TCR_4(__kmp_global.g.g_done)) {
1090  /* This thread monitors the state of the system */
1091 
1092  KA_TRACE(15, ("__kmp_launch_monitor: update\n"));
1093 
1094  wait_status = WaitForSingleObject(__kmp_monitor_ev, interval);
1095 
1096  if (wait_status == WAIT_TIMEOUT) {
1097  TCW_4(__kmp_global.g.g_time.dt.t_value,
1098  TCR_4(__kmp_global.g.g_time.dt.t_value) + 1);
1099  }
1100 
1101  KMP_MB(); /* Flush all pending memory write invalidates. */
1102  }
1103 
1104  KA_TRACE(10, ("__kmp_launch_monitor: finished\n"));
1105 
1106  status = SetThreadPriority(monitor, THREAD_PRIORITY_NORMAL);
1107  if (!status) {
1108  DWORD error = GetLastError();
1109  __kmp_fatal(KMP_MSG(CantSetThreadPriority), KMP_ERR(error), __kmp_msg_null);
1110  }
1111 
1112  if (__kmp_global.g.g_abort != 0) {
1113  /* now we need to terminate the worker threads */
1114  /* the value of t_abort is the signal we caught */
1115  int gtid;
1116 
1117  KA_TRACE(10, ("__kmp_launch_monitor: terminate sig=%d\n",
1118  (__kmp_global.g.g_abort)));
1119 
1120  /* terminate the OpenMP worker threads */
1121  /* TODO this is not valid for sibling threads!!
1122  * the uber master might not be 0 anymore.. */
1123  for (gtid = 1; gtid < __kmp_threads_capacity; ++gtid)
1124  __kmp_terminate_thread(gtid);
1125 
1126  __kmp_cleanup();
1127 
1128  Sleep(0);
1129 
1130  KA_TRACE(10,
1131  ("__kmp_launch_monitor: raise sig=%d\n", __kmp_global.g.g_abort));
1132 
1133  if (__kmp_global.g.g_abort > 0) {
1134  raise(__kmp_global.g.g_abort);
1135  }
1136  }
1137 
1138  TCW_4(this_thr->th.th_info.ds.ds_alive, FALSE);
1139 
1140  KMP_MB();
1141  return arg;
1142 }
1143 #endif
1144 
1145 void __kmp_create_worker(int gtid, kmp_info_t *th, size_t stack_size) {
1146  kmp_thread_t handle;
1147  DWORD idThread;
1148 
1149  KA_TRACE(10, ("__kmp_create_worker: try to create thread (%d)\n", gtid));
1150 
1151  th->th.th_info.ds.ds_gtid = gtid;
1152 
1153  if (KMP_UBER_GTID(gtid)) {
1154  int stack_data;
1155 
1156  /* TODO: GetCurrentThread() returns a pseudo-handle that is unsuitable for
1157  other threads to use. Is it appropriate to just use GetCurrentThread?
1158  When should we close this handle? When unregistering the root? */
1159  {
1160  BOOL rc;
1161  rc = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1162  GetCurrentProcess(), &th->th.th_info.ds.ds_thread, 0,
1163  FALSE, DUPLICATE_SAME_ACCESS);
1164  KMP_ASSERT(rc);
1165  KA_TRACE(10, (" __kmp_create_worker: ROOT Handle duplicated, th = %p, "
1166  "handle = %" KMP_UINTPTR_SPEC "\n",
1167  (LPVOID)th, th->th.th_info.ds.ds_thread));
1168  th->th.th_info.ds.ds_thread_id = GetCurrentThreadId();
1169  }
1170  if (TCR_4(__kmp_gtid_mode) < 2) { // check stack only if used to get gtid
1171  /* we will dynamically update the stack range if gtid_mode == 1 */
1172  TCW_PTR(th->th.th_info.ds.ds_stackbase, &stack_data);
1173  TCW_PTR(th->th.th_info.ds.ds_stacksize, 0);
1174  TCW_4(th->th.th_info.ds.ds_stackgrow, TRUE);
1175  __kmp_check_stack_overlap(th);
1176  }
1177  } else {
1178  KMP_MB(); /* Flush all pending memory write invalidates. */
1179 
1180  /* Set stack size for this thread now. */
1181  KA_TRACE(10,
1182  ("__kmp_create_worker: stack_size = %" KMP_SIZE_T_SPEC " bytes\n",
1183  stack_size));
1184 
1185  stack_size += gtid * __kmp_stkoffset;
1186 
1187  TCW_PTR(th->th.th_info.ds.ds_stacksize, stack_size);
1188  TCW_4(th->th.th_info.ds.ds_stackgrow, FALSE);
1189 
1190  KA_TRACE(10,
1191  ("__kmp_create_worker: (before) stack_size = %" KMP_SIZE_T_SPEC
1192  " bytes, &__kmp_launch_worker = %p, th = %p, &idThread = %p\n",
1193  (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1194  (LPVOID)th, &idThread));
1195 
1196  handle = CreateThread(
1197  NULL, (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)__kmp_launch_worker,
1198  (LPVOID)th, STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1199 
1200  KA_TRACE(10,
1201  ("__kmp_create_worker: (after) stack_size = %" KMP_SIZE_T_SPEC
1202  " bytes, &__kmp_launch_worker = %p, th = %p, "
1203  "idThread = %u, handle = %" KMP_UINTPTR_SPEC "\n",
1204  (SIZE_T)stack_size, (LPTHREAD_START_ROUTINE)&__kmp_launch_worker,
1205  (LPVOID)th, idThread, handle));
1206 
1207  if (handle == 0) {
1208  DWORD error = GetLastError();
1209  __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1210  } else {
1211  th->th.th_info.ds.ds_thread = handle;
1212  }
1213 
1214  KMP_MB(); /* Flush all pending memory write invalidates. */
1215  }
1216 
1217  KA_TRACE(10, ("__kmp_create_worker: done creating thread (%d)\n", gtid));
1218 }
1219 
1220 int __kmp_still_running(kmp_info_t *th) {
1221  return (WAIT_TIMEOUT == WaitForSingleObject(th->th.th_info.ds.ds_thread, 0));
1222 }
1223 
1224 #if KMP_USE_MONITOR
1225 void __kmp_create_monitor(kmp_info_t *th) {
1226  kmp_thread_t handle;
1227  DWORD idThread;
1228  int ideal, new_ideal;
1229 
1230  if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) {
1231  // We don't need monitor thread in case of MAX_BLOCKTIME
1232  KA_TRACE(10, ("__kmp_create_monitor: skipping monitor thread because of "
1233  "MAX blocktime\n"));
1234  th->th.th_info.ds.ds_tid = 0; // this makes reap_monitor no-op
1235  th->th.th_info.ds.ds_gtid = 0;
1236  TCW_4(__kmp_init_monitor, 2); // Signal to stop waiting for monitor creation
1237  return;
1238  }
1239  KA_TRACE(10, ("__kmp_create_monitor: try to create monitor\n"));
1240 
1241  KMP_MB(); /* Flush all pending memory write invalidates. */
1242 
1243  __kmp_monitor_ev = CreateEvent(NULL, TRUE, FALSE, NULL);
1244  if (__kmp_monitor_ev == NULL) {
1245  DWORD error = GetLastError();
1246  __kmp_fatal(KMP_MSG(CantCreateEvent), KMP_ERR(error), __kmp_msg_null);
1247  }
1248 #if USE_ITT_BUILD
1249  __kmp_itt_system_object_created(__kmp_monitor_ev, "Event");
1250 #endif /* USE_ITT_BUILD */
1251 
1252  th->th.th_info.ds.ds_tid = KMP_GTID_MONITOR;
1253  th->th.th_info.ds.ds_gtid = KMP_GTID_MONITOR;
1254 
1255  // FIXME - on Windows* OS, if __kmp_monitor_stksize = 0, figure out how
1256  // to automatically expand stacksize based on CreateThread error code.
1257  if (__kmp_monitor_stksize == 0) {
1258  __kmp_monitor_stksize = KMP_DEFAULT_MONITOR_STKSIZE;
1259  }
1260  if (__kmp_monitor_stksize < __kmp_sys_min_stksize) {
1261  __kmp_monitor_stksize = __kmp_sys_min_stksize;
1262  }
1263 
1264  KA_TRACE(10, ("__kmp_create_monitor: requested stacksize = %d bytes\n",
1265  (int)__kmp_monitor_stksize));
1266 
1267  TCW_4(__kmp_global.g.g_time.dt.t_value, 0);
1268 
1269  handle =
1270  CreateThread(NULL, (SIZE_T)__kmp_monitor_stksize,
1271  (LPTHREAD_START_ROUTINE)__kmp_launch_monitor, (LPVOID)th,
1272  STACK_SIZE_PARAM_IS_A_RESERVATION, &idThread);
1273  if (handle == 0) {
1274  DWORD error = GetLastError();
1275  __kmp_fatal(KMP_MSG(CantCreateThread), KMP_ERR(error), __kmp_msg_null);
1276  } else
1277  th->th.th_info.ds.ds_thread = handle;
1278 
1279  KMP_MB(); /* Flush all pending memory write invalidates. */
1280 
1281  KA_TRACE(10, ("__kmp_create_monitor: monitor created %p\n",
1282  (void *)th->th.th_info.ds.ds_thread));
1283 }
1284 #endif
1285 
1286 /* Check to see if thread is still alive.
1287  NOTE: The ExitProcess(code) system call causes all threads to Terminate
1288  with a exit_val = code. Because of this we can not rely on exit_val having
1289  any particular value. So this routine may return STILL_ALIVE in exit_val
1290  even after the thread is dead. */
1291 
1292 int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val) {
1293  DWORD rc;
1294  rc = GetExitCodeThread(th->th.th_info.ds.ds_thread, exit_val);
1295  if (rc == 0) {
1296  DWORD error = GetLastError();
1297  __kmp_fatal(KMP_MSG(FunctionError, "GetExitCodeThread()"), KMP_ERR(error),
1298  __kmp_msg_null);
1299  }
1300  return (*exit_val == STILL_ACTIVE);
1301 }
1302 
1303 void __kmp_exit_thread(int exit_status) {
1304  ExitThread(exit_status);
1305 } // __kmp_exit_thread
1306 
1307 // This is a common part for both __kmp_reap_worker() and __kmp_reap_monitor().
1308 static void __kmp_reap_common(kmp_info_t *th) {
1309  DWORD exit_val;
1310 
1311  KMP_MB(); /* Flush all pending memory write invalidates. */
1312 
1313  KA_TRACE(
1314  10, ("__kmp_reap_common: try to reap (%d)\n", th->th.th_info.ds.ds_gtid));
1315 
1316  /* 2006-10-19:
1317  There are two opposite situations:
1318  1. Windows* OS keep thread alive after it resets ds_alive flag and
1319  exits from thread function. (For example, see C70770/Q394281 "unloading of
1320  dll based on OMP is very slow".)
1321  2. Windows* OS may kill thread before it resets ds_alive flag.
1322 
1323  Right solution seems to be waiting for *either* thread termination *or*
1324  ds_alive resetting. */
1325  {
1326  // TODO: This code is very similar to KMP_WAIT. Need to generalize
1327  // KMP_WAIT to cover this usage also.
1328  void *obj = NULL;
1329  kmp_uint32 spins;
1330  kmp_uint64 time;
1331 #if USE_ITT_BUILD
1332  KMP_FSYNC_SPIN_INIT(obj, (void *)&th->th.th_info.ds.ds_alive);
1333 #endif /* USE_ITT_BUILD */
1334  KMP_INIT_YIELD(spins);
1335  KMP_INIT_BACKOFF(time);
1336  do {
1337 #if USE_ITT_BUILD
1338  KMP_FSYNC_SPIN_PREPARE(obj);
1339 #endif /* USE_ITT_BUILD */
1340  __kmp_is_thread_alive(th, &exit_val);
1341  KMP_YIELD_OVERSUB_ELSE_SPIN(spins, time);
1342  } while (exit_val == STILL_ACTIVE && TCR_4(th->th.th_info.ds.ds_alive));
1343 #if USE_ITT_BUILD
1344  if (exit_val == STILL_ACTIVE) {
1345  KMP_FSYNC_CANCEL(obj);
1346  } else {
1347  KMP_FSYNC_SPIN_ACQUIRED(obj);
1348  }
1349 #endif /* USE_ITT_BUILD */
1350  }
1351 
1352  __kmp_free_handle(th->th.th_info.ds.ds_thread);
1353 
1354  /* NOTE: The ExitProcess(code) system call causes all threads to Terminate
1355  with a exit_val = code. Because of this we can not rely on exit_val having
1356  any particular value. */
1357  if (exit_val == STILL_ACTIVE) {
1358  KA_TRACE(1, ("__kmp_reap_common: thread still active.\n"));
1359  } else if ((void *)exit_val != (void *)th) {
1360  KA_TRACE(1, ("__kmp_reap_common: ExitProcess / TerminateThread used?\n"));
1361  }
1362 
1363  KA_TRACE(10,
1364  ("__kmp_reap_common: done reaping (%d), handle = %" KMP_UINTPTR_SPEC
1365  "\n",
1366  th->th.th_info.ds.ds_gtid, th->th.th_info.ds.ds_thread));
1367 
1368  th->th.th_info.ds.ds_thread = 0;
1369  th->th.th_info.ds.ds_tid = KMP_GTID_DNE;
1370  th->th.th_info.ds.ds_gtid = KMP_GTID_DNE;
1371  th->th.th_info.ds.ds_thread_id = 0;
1372 
1373  KMP_MB(); /* Flush all pending memory write invalidates. */
1374 }
1375 
1376 #if KMP_USE_MONITOR
1377 void __kmp_reap_monitor(kmp_info_t *th) {
1378  int status;
1379 
1380  KA_TRACE(10, ("__kmp_reap_monitor: try to reap %p\n",
1381  (void *)th->th.th_info.ds.ds_thread));
1382 
1383  // If monitor has been created, its tid and gtid should be KMP_GTID_MONITOR.
1384  // If both tid and gtid are 0, it means the monitor did not ever start.
1385  // If both tid and gtid are KMP_GTID_DNE, the monitor has been shut down.
1386  KMP_DEBUG_ASSERT(th->th.th_info.ds.ds_tid == th->th.th_info.ds.ds_gtid);
1387  if (th->th.th_info.ds.ds_gtid != KMP_GTID_MONITOR) {
1388  KA_TRACE(10, ("__kmp_reap_monitor: monitor did not start, returning\n"));
1389  return;
1390  }
1391 
1392  KMP_MB(); /* Flush all pending memory write invalidates. */
1393 
1394  status = SetEvent(__kmp_monitor_ev);
1395  if (status == FALSE) {
1396  DWORD error = GetLastError();
1397  __kmp_fatal(KMP_MSG(CantSetEvent), KMP_ERR(error), __kmp_msg_null);
1398  }
1399  KA_TRACE(10, ("__kmp_reap_monitor: reaping thread (%d)\n",
1400  th->th.th_info.ds.ds_gtid));
1401  __kmp_reap_common(th);
1402 
1403  __kmp_free_handle(__kmp_monitor_ev);
1404 
1405  KMP_MB(); /* Flush all pending memory write invalidates. */
1406 }
1407 #endif
1408 
1409 void __kmp_reap_worker(kmp_info_t *th) {
1410  KA_TRACE(10, ("__kmp_reap_worker: reaping thread (%d)\n",
1411  th->th.th_info.ds.ds_gtid));
1412  __kmp_reap_common(th);
1413 }
1414 
1415 #if KMP_HANDLE_SIGNALS
1416 
1417 static void __kmp_team_handler(int signo) {
1418  if (__kmp_global.g.g_abort == 0) {
1419  // Stage 1 signal handler, let's shut down all of the threads.
1420  if (__kmp_debug_buf) {
1421  __kmp_dump_debug_buffer();
1422  }
1423  KMP_MB(); // Flush all pending memory write invalidates.
1424  TCW_4(__kmp_global.g.g_abort, signo);
1425  KMP_MB(); // Flush all pending memory write invalidates.
1426  TCW_4(__kmp_global.g.g_done, TRUE);
1427  KMP_MB(); // Flush all pending memory write invalidates.
1428  }
1429 } // __kmp_team_handler
1430 
1431 static sig_func_t __kmp_signal(int signum, sig_func_t handler) {
1432  sig_func_t old = signal(signum, handler);
1433  if (old == SIG_ERR) {
1434  int error = errno;
1435  __kmp_fatal(KMP_MSG(FunctionError, "signal"), KMP_ERR(error),
1436  __kmp_msg_null);
1437  }
1438  return old;
1439 }
1440 
1441 static void __kmp_install_one_handler(int sig, sig_func_t handler,
1442  int parallel_init) {
1443  sig_func_t old;
1444  KMP_MB(); /* Flush all pending memory write invalidates. */
1445  KB_TRACE(60, ("__kmp_install_one_handler: called: sig=%d\n", sig));
1446  if (parallel_init) {
1447  old = __kmp_signal(sig, handler);
1448  // SIG_DFL on Windows* OS in NULL or 0.
1449  if (old == __kmp_sighldrs[sig]) {
1450  __kmp_siginstalled[sig] = 1;
1451  } else { // Restore/keep user's handler if one previously installed.
1452  old = __kmp_signal(sig, old);
1453  }
1454  } else {
1455  // Save initial/system signal handlers to see if user handlers installed.
1456  // 2009-09-23: It is a dead code. On Windows* OS __kmp_install_signals
1457  // called once with parallel_init == TRUE.
1458  old = __kmp_signal(sig, SIG_DFL);
1459  __kmp_sighldrs[sig] = old;
1460  __kmp_signal(sig, old);
1461  }
1462  KMP_MB(); /* Flush all pending memory write invalidates. */
1463 } // __kmp_install_one_handler
1464 
1465 static void __kmp_remove_one_handler(int sig) {
1466  if (__kmp_siginstalled[sig]) {
1467  sig_func_t old;
1468  KMP_MB(); // Flush all pending memory write invalidates.
1469  KB_TRACE(60, ("__kmp_remove_one_handler: called: sig=%d\n", sig));
1470  old = __kmp_signal(sig, __kmp_sighldrs[sig]);
1471  if (old != __kmp_team_handler) {
1472  KB_TRACE(10, ("__kmp_remove_one_handler: oops, not our handler, "
1473  "restoring: sig=%d\n",
1474  sig));
1475  old = __kmp_signal(sig, old);
1476  }
1477  __kmp_sighldrs[sig] = NULL;
1478  __kmp_siginstalled[sig] = 0;
1479  KMP_MB(); // Flush all pending memory write invalidates.
1480  }
1481 } // __kmp_remove_one_handler
1482 
1483 void __kmp_install_signals(int parallel_init) {
1484  KB_TRACE(10, ("__kmp_install_signals: called\n"));
1485  if (!__kmp_handle_signals) {
1486  KB_TRACE(10, ("__kmp_install_signals: KMP_HANDLE_SIGNALS is false - "
1487  "handlers not installed\n"));
1488  return;
1489  }
1490  __kmp_install_one_handler(SIGINT, __kmp_team_handler, parallel_init);
1491  __kmp_install_one_handler(SIGILL, __kmp_team_handler, parallel_init);
1492  __kmp_install_one_handler(SIGABRT, __kmp_team_handler, parallel_init);
1493  __kmp_install_one_handler(SIGFPE, __kmp_team_handler, parallel_init);
1494  __kmp_install_one_handler(SIGSEGV, __kmp_team_handler, parallel_init);
1495  __kmp_install_one_handler(SIGTERM, __kmp_team_handler, parallel_init);
1496 } // __kmp_install_signals
1497 
1498 void __kmp_remove_signals(void) {
1499  int sig;
1500  KB_TRACE(10, ("__kmp_remove_signals: called\n"));
1501  for (sig = 1; sig < NSIG; ++sig) {
1502  __kmp_remove_one_handler(sig);
1503  }
1504 } // __kmp_remove_signals
1505 
1506 #endif // KMP_HANDLE_SIGNALS
1507 
1508 /* Put the thread to sleep for a time period */
1509 void __kmp_thread_sleep(int millis) {
1510  DWORD status;
1511 
1512  status = SleepEx((DWORD)millis, FALSE);
1513  if (status) {
1514  DWORD error = GetLastError();
1515  __kmp_fatal(KMP_MSG(FunctionError, "SleepEx()"), KMP_ERR(error),
1516  __kmp_msg_null);
1517  }
1518 }
1519 
1520 // Determine whether the given address is mapped into the current address space.
1521 int __kmp_is_address_mapped(void *addr) {
1522  DWORD status;
1523  MEMORY_BASIC_INFORMATION lpBuffer;
1524  SIZE_T dwLength;
1525 
1526  dwLength = sizeof(MEMORY_BASIC_INFORMATION);
1527 
1528  status = VirtualQuery(addr, &lpBuffer, dwLength);
1529 
1530  return !(((lpBuffer.State == MEM_RESERVE) || (lpBuffer.State == MEM_FREE)) ||
1531  ((lpBuffer.Protect == PAGE_NOACCESS) ||
1532  (lpBuffer.Protect == PAGE_EXECUTE)));
1533 }
1534 
1535 kmp_uint64 __kmp_hardware_timestamp(void) {
1536  kmp_uint64 r = 0;
1537 
1538  QueryPerformanceCounter((LARGE_INTEGER *)&r);
1539  return r;
1540 }
1541 
1542 /* Free handle and check the error code */
1543 void __kmp_free_handle(kmp_thread_t tHandle) {
1544  /* called with parameter type HANDLE also, thus suppose kmp_thread_t defined
1545  * as HANDLE */
1546  BOOL rc;
1547  rc = CloseHandle(tHandle);
1548  if (!rc) {
1549  DWORD error = GetLastError();
1550  __kmp_fatal(KMP_MSG(CantCloseHandle), KMP_ERR(error), __kmp_msg_null);
1551  }
1552 }
1553 
1554 int __kmp_get_load_balance(int max) {
1555  static ULONG glb_buff_size = 100 * 1024;
1556 
1557  // Saved count of the running threads for the thread balance algorithm
1558  static int glb_running_threads = 0;
1559  static double glb_call_time = 0; /* Thread balance algorithm call time */
1560 
1561  int running_threads = 0; // Number of running threads in the system.
1562  NTSTATUS status = 0;
1563  ULONG buff_size = 0;
1564  ULONG info_size = 0;
1565  void *buffer = NULL;
1566  PSYSTEM_PROCESS_INFORMATION spi = NULL;
1567  int first_time = 1;
1568 
1569  double call_time = 0.0; // start, finish;
1570 
1571  __kmp_elapsed(&call_time);
1572 
1573  if (glb_call_time &&
1574  (call_time - glb_call_time < __kmp_load_balance_interval)) {
1575  running_threads = glb_running_threads;
1576  goto finish;
1577  }
1578  glb_call_time = call_time;
1579 
1580  // Do not spend time on running algorithm if we have a permanent error.
1581  if (NtQuerySystemInformation == NULL) {
1582  running_threads = -1;
1583  goto finish;
1584  }
1585 
1586  if (max <= 0) {
1587  max = INT_MAX;
1588  }
1589 
1590  do {
1591 
1592  if (first_time) {
1593  buff_size = glb_buff_size;
1594  } else {
1595  buff_size = 2 * buff_size;
1596  }
1597 
1598  buffer = KMP_INTERNAL_REALLOC(buffer, buff_size);
1599  if (buffer == NULL) {
1600  running_threads = -1;
1601  goto finish;
1602  }
1603  status = NtQuerySystemInformation(SystemProcessInformation, buffer,
1604  buff_size, &info_size);
1605  first_time = 0;
1606 
1607  } while (status == STATUS_INFO_LENGTH_MISMATCH);
1608  glb_buff_size = buff_size;
1609 
1610 #define CHECK(cond) \
1611  { \
1612  KMP_DEBUG_ASSERT(cond); \
1613  if (!(cond)) { \
1614  running_threads = -1; \
1615  goto finish; \
1616  } \
1617  }
1618 
1619  CHECK(buff_size >= info_size);
1620  spi = PSYSTEM_PROCESS_INFORMATION(buffer);
1621  for (;;) {
1622  ptrdiff_t offset = uintptr_t(spi) - uintptr_t(buffer);
1623  CHECK(0 <= offset &&
1624  offset + sizeof(SYSTEM_PROCESS_INFORMATION) < info_size);
1625  HANDLE pid = spi->ProcessId;
1626  ULONG num = spi->NumberOfThreads;
1627  CHECK(num >= 1);
1628  size_t spi_size =
1629  sizeof(SYSTEM_PROCESS_INFORMATION) + sizeof(SYSTEM_THREAD) * (num - 1);
1630  CHECK(offset + spi_size <
1631  info_size); // Make sure process info record fits the buffer.
1632  if (spi->NextEntryOffset != 0) {
1633  CHECK(spi_size <=
1634  spi->NextEntryOffset); // And do not overlap with the next record.
1635  }
1636  // pid == 0 corresponds to the System Idle Process. It always has running
1637  // threads on all cores. So, we don't consider the running threads of this
1638  // process.
1639  if (pid != 0) {
1640  for (int i = 0; i < num; ++i) {
1641  THREAD_STATE state = spi->Threads[i].State;
1642  // Count threads that have Ready or Running state.
1643  // !!! TODO: Why comment does not match the code???
1644  if (state == StateRunning) {
1645  ++running_threads;
1646  // Stop counting running threads if the number is already greater than
1647  // the number of available cores
1648  if (running_threads >= max) {
1649  goto finish;
1650  }
1651  }
1652  }
1653  }
1654  if (spi->NextEntryOffset == 0) {
1655  break;
1656  }
1657  spi = PSYSTEM_PROCESS_INFORMATION(uintptr_t(spi) + spi->NextEntryOffset);
1658  }
1659 
1660 #undef CHECK
1661 
1662 finish: // Clean up and exit.
1663 
1664  if (buffer != NULL) {
1665  KMP_INTERNAL_FREE(buffer);
1666  }
1667 
1668  glb_running_threads = running_threads;
1669 
1670  return running_threads;
1671 } //__kmp_get_load_balance()
1672 
1673 // Find symbol from the loaded modules
1674 void *__kmp_lookup_symbol(const char *name) {
1675  HANDLE process = GetCurrentProcess();
1676  DWORD needed;
1677  HMODULE *modules = nullptr;
1678  if (!EnumProcessModules(process, modules, 0, &needed))
1679  return nullptr;
1680  DWORD num_modules = needed / sizeof(HMODULE);
1681  modules = (HMODULE *)malloc(num_modules * sizeof(HMODULE));
1682  if (!EnumProcessModules(process, modules, needed, &needed)) {
1683  free(modules);
1684  return nullptr;
1685  }
1686  void *proc = nullptr;
1687  for (uint32_t i = 0; i < num_modules; i++) {
1688  proc = (void *)GetProcAddress(modules[i], name);
1689  if (proc)
1690  break;
1691  }
1692  free(modules);
1693  return proc;
1694 }
1695 
1696 // Functions for hidden helper task
1697 void __kmp_hidden_helper_worker_thread_wait() {
1698  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1699 }
1700 
1701 void __kmp_do_initialize_hidden_helper_threads() {
1702  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1703 }
1704 
1705 void __kmp_hidden_helper_threads_initz_wait() {
1706  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1707 }
1708 
1709 void __kmp_hidden_helper_initz_release() {
1710  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1711 }
1712 
1713 void __kmp_hidden_helper_main_thread_wait() {
1714  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1715 }
1716 
1717 void __kmp_hidden_helper_main_thread_release() {
1718  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1719 }
1720 
1721 void __kmp_hidden_helper_worker_thread_signal() {
1722  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1723 }
1724 
1725 void __kmp_hidden_helper_threads_deinitz_wait() {
1726  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1727 }
1728 
1729 void __kmp_hidden_helper_threads_deinitz_release() {
1730  KMP_ASSERT(0 && "Hidden helper task is not supported on Windows");
1731 }