LLVM OpenMP
kmp_affinity.cpp
Go to the documentation of this file.
1/*
2 * kmp_affinity.cpp -- affinity management
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_str.h"
18#include "kmp_wrapper_getpid.h"
19#if KMP_USE_HIER_SCHED
20#include "kmp_dispatch_hier.h"
21#endif
22#if KMP_HWLOC_ENABLED
23// Copied from hwloc
24#define HWLOC_GROUP_KIND_INTEL_MODULE 102
25#define HWLOC_GROUP_KIND_INTEL_TILE 103
26#define HWLOC_GROUP_KIND_INTEL_DIE 104
27#define HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP 220
28#endif // KMP_HWLOC_ENABLED
29#include <ctype.h>
30
31// The machine topology
33// KMP_HW_SUBSET environment variable
35
36// Store the real or imagined machine hierarchy here
38
40
41#if KMP_AFFINITY_SUPPORTED
42// Helper class to see if place lists further restrict the fullMask
43class kmp_full_mask_modifier_t {
44 kmp_affin_mask_t *mask;
45
46public:
47 kmp_full_mask_modifier_t() {
48 KMP_CPU_ALLOC(mask);
49 KMP_CPU_ZERO(mask);
50 }
51 ~kmp_full_mask_modifier_t() {
52 KMP_CPU_FREE(mask);
53 mask = nullptr;
54 }
55 void include(const kmp_affin_mask_t *other) { KMP_CPU_UNION(mask, other); }
56 // If the new full mask is different from the current full mask,
57 // then switch them. Returns true if full mask was affected, false otherwise.
58 bool restrict_to_mask() {
59 // See if the new mask further restricts or changes the full mask
60 if (KMP_CPU_EQUAL(__kmp_affin_fullMask, mask) || KMP_CPU_ISEMPTY(mask))
61 return false;
62 return __kmp_topology->restrict_to_mask(mask);
63 }
64};
65
66static inline const char *
67__kmp_get_affinity_env_var(const kmp_affinity_t &affinity,
68 bool for_binding = false) {
69 if (affinity.flags.omp_places) {
70 if (for_binding)
71 return "OMP_PROC_BIND";
72 return "OMP_PLACES";
73 }
74 return affinity.env_var;
75}
76#endif // KMP_AFFINITY_SUPPORTED
77
79 kmp_uint32 depth;
80 // The test below is true if affinity is available, but set to "none". Need to
81 // init on first use of hierarchical barrier.
82 if (TCR_1(machine_hierarchy.uninitialized))
83 machine_hierarchy.init(nproc);
84
85 // Adjust the hierarchy in case num threads exceeds original
86 if (nproc > machine_hierarchy.base_num_threads)
87 machine_hierarchy.resize(nproc);
88
89 depth = machine_hierarchy.depth;
90 KMP_DEBUG_ASSERT(depth > 0);
91
92 thr_bar->depth = depth;
93 __kmp_type_convert(machine_hierarchy.numPerLevel[0] - 1,
94 &(thr_bar->base_leaf_kids));
95 thr_bar->skip_per_level = machine_hierarchy.skipPerLevel;
96}
97
100#ifndef KMP_DFLT_NTH_CORES
101static int __kmp_ncores;
102#endif
103
104const char *__kmp_hw_get_catalog_string(kmp_hw_t type, bool plural) {
105 switch (type) {
106 case KMP_HW_SOCKET:
107 return ((plural) ? KMP_I18N_STR(Sockets) : KMP_I18N_STR(Socket));
108 case KMP_HW_DIE:
109 return ((plural) ? KMP_I18N_STR(Dice) : KMP_I18N_STR(Die));
110 case KMP_HW_MODULE:
111 return ((plural) ? KMP_I18N_STR(Modules) : KMP_I18N_STR(Module));
112 case KMP_HW_TILE:
113 return ((plural) ? KMP_I18N_STR(Tiles) : KMP_I18N_STR(Tile));
114 case KMP_HW_NUMA:
115 return ((plural) ? KMP_I18N_STR(NumaDomains) : KMP_I18N_STR(NumaDomain));
116 case KMP_HW_L3:
117 return ((plural) ? KMP_I18N_STR(L3Caches) : KMP_I18N_STR(L3Cache));
118 case KMP_HW_L2:
119 return ((plural) ? KMP_I18N_STR(L2Caches) : KMP_I18N_STR(L2Cache));
120 case KMP_HW_L1:
121 return ((plural) ? KMP_I18N_STR(L1Caches) : KMP_I18N_STR(L1Cache));
122 case KMP_HW_LLC:
123 return ((plural) ? KMP_I18N_STR(LLCaches) : KMP_I18N_STR(LLCache));
124 case KMP_HW_CORE:
125 return ((plural) ? KMP_I18N_STR(Cores) : KMP_I18N_STR(Core));
126 case KMP_HW_THREAD:
127 return ((plural) ? KMP_I18N_STR(Threads) : KMP_I18N_STR(Thread));
129 return ((plural) ? KMP_I18N_STR(ProcGroups) : KMP_I18N_STR(ProcGroup));
130 case KMP_HW_UNKNOWN:
131 case KMP_HW_LAST:
132 return KMP_I18N_STR(Unknown);
133 }
134 KMP_ASSERT2(false, "Unhandled kmp_hw_t enumeration");
136}
137
138const char *__kmp_hw_get_keyword(kmp_hw_t type, bool plural) {
139 switch (type) {
140 case KMP_HW_SOCKET:
141 return ((plural) ? "sockets" : "socket");
142 case KMP_HW_DIE:
143 return ((plural) ? "dice" : "die");
144 case KMP_HW_MODULE:
145 return ((plural) ? "modules" : "module");
146 case KMP_HW_TILE:
147 return ((plural) ? "tiles" : "tile");
148 case KMP_HW_NUMA:
149 return ((plural) ? "numa_domains" : "numa_domain");
150 case KMP_HW_L3:
151 return ((plural) ? "l3_caches" : "l3_cache");
152 case KMP_HW_L2:
153 return ((plural) ? "l2_caches" : "l2_cache");
154 case KMP_HW_L1:
155 return ((plural) ? "l1_caches" : "l1_cache");
156 case KMP_HW_LLC:
157 return ((plural) ? "ll_caches" : "ll_cache");
158 case KMP_HW_CORE:
159 return ((plural) ? "cores" : "core");
160 case KMP_HW_THREAD:
161 return ((plural) ? "threads" : "thread");
163 return ((plural) ? "proc_groups" : "proc_group");
164 case KMP_HW_UNKNOWN:
165 case KMP_HW_LAST:
166 return ((plural) ? "unknowns" : "unknown");
167 }
168 KMP_ASSERT2(false, "Unhandled kmp_hw_t enumeration");
170}
171
173 switch (type) {
176 return "unknown";
177#if KMP_ARCH_X86 || KMP_ARCH_X86_64
178 case KMP_HW_CORE_TYPE_ATOM:
179 return "Intel Atom(R) processor";
180 case KMP_HW_CORE_TYPE_CORE:
181 return "Intel(R) Core(TM) processor";
182#endif
183 }
184 KMP_ASSERT2(false, "Unhandled kmp_hw_core_type_t enumeration");
186}
187
188#if KMP_AFFINITY_SUPPORTED
189// If affinity is supported, check the affinity
190// verbose and warning flags before printing warning
191#define KMP_AFF_WARNING(s, ...) \
192 if (s.flags.verbose || (s.flags.warnings && (s.type != affinity_none))) { \
193 KMP_WARNING(__VA_ARGS__); \
194 }
195#else
196#define KMP_AFF_WARNING(s, ...) KMP_WARNING(__VA_ARGS__)
197#endif
198
199////////////////////////////////////////////////////////////////////////////////
200// kmp_hw_thread_t methods
201int kmp_hw_thread_t::compare_ids(const void *a, const void *b) {
202 const kmp_hw_thread_t *ahwthread = (const kmp_hw_thread_t *)a;
203 const kmp_hw_thread_t *bhwthread = (const kmp_hw_thread_t *)b;
204 int depth = __kmp_topology->get_depth();
205 for (int level = 0; level < depth; ++level) {
206 // Reverse sort (higher efficiencies earlier in list) cores by core
207 // efficiency if available.
208 if (__kmp_is_hybrid_cpu() &&
209 __kmp_topology->get_type(level) == KMP_HW_CORE &&
210 ahwthread->attrs.is_core_eff_valid() &&
211 bhwthread->attrs.is_core_eff_valid()) {
212 if (ahwthread->attrs.get_core_eff() < bhwthread->attrs.get_core_eff())
213 return 1;
214 if (ahwthread->attrs.get_core_eff() > bhwthread->attrs.get_core_eff())
215 return -1;
216 }
217 if (ahwthread->ids[level] == bhwthread->ids[level])
218 continue;
219 // If the hardware id is unknown for this level, then place hardware thread
220 // further down in the sorted list as it should take last priority
221 if (ahwthread->ids[level] == UNKNOWN_ID)
222 return 1;
223 else if (bhwthread->ids[level] == UNKNOWN_ID)
224 return -1;
225 else if (ahwthread->ids[level] < bhwthread->ids[level])
226 return -1;
227 else if (ahwthread->ids[level] > bhwthread->ids[level])
228 return 1;
229 }
230 if (ahwthread->os_id < bhwthread->os_id)
231 return -1;
232 else if (ahwthread->os_id > bhwthread->os_id)
233 return 1;
234 return 0;
235}
236
237#if KMP_AFFINITY_SUPPORTED
238int kmp_hw_thread_t::compare_compact(const void *a, const void *b) {
239 int i;
240 const kmp_hw_thread_t *aa = (const kmp_hw_thread_t *)a;
241 const kmp_hw_thread_t *bb = (const kmp_hw_thread_t *)b;
242 int depth = __kmp_topology->get_depth();
243 int compact = __kmp_topology->compact;
244 KMP_DEBUG_ASSERT(compact >= 0);
245 KMP_DEBUG_ASSERT(compact <= depth);
246 for (i = 0; i < compact; i++) {
247 int j = depth - i - 1;
248 if (aa->sub_ids[j] < bb->sub_ids[j])
249 return -1;
250 if (aa->sub_ids[j] > bb->sub_ids[j])
251 return 1;
252 }
253 for (; i < depth; i++) {
254 int j = i - compact;
255 if (aa->sub_ids[j] < bb->sub_ids[j])
256 return -1;
257 if (aa->sub_ids[j] > bb->sub_ids[j])
258 return 1;
259 }
260 return 0;
261}
262#endif
263
265 int depth = __kmp_topology->get_depth();
266 printf("%4d ", os_id);
267 for (int i = 0; i < depth; ++i) {
268 printf("%4d (%d) ", ids[i], sub_ids[i]);
269 }
270 if (attrs) {
271 if (attrs.is_core_type_valid())
272 printf(" (%s)", __kmp_hw_get_core_type_string(attrs.get_core_type()));
273 if (attrs.is_core_eff_valid())
274 printf(" (eff=%d)", attrs.get_core_eff());
275 }
276 if (leader)
277 printf(" (leader)");
278 printf("\n");
279}
280
281////////////////////////////////////////////////////////////////////////////////
282// kmp_topology_t methods
283
284// Add a layer to the topology based on the ids. Assume the topology
285// is perfectly nested (i.e., so no object has more than one parent)
287 // Figure out where the layer should go by comparing the ids of the current
288 // layers with the new ids
289 int target_layer;
290 int previous_id = kmp_hw_thread_t::UNKNOWN_ID;
291 int previous_new_id = kmp_hw_thread_t::UNKNOWN_ID;
292
293 // Start from the highest layer and work down to find target layer
294 // If new layer is equal to another layer then put the new layer above
295 for (target_layer = 0; target_layer < depth; ++target_layer) {
296 bool layers_equal = true;
297 bool strictly_above_target_layer = false;
298 for (int i = 0; i < num_hw_threads; ++i) {
299 int id = hw_threads[i].ids[target_layer];
300 int new_id = ids[i];
301 if (id != previous_id && new_id == previous_new_id) {
302 // Found the layer we are strictly above
303 strictly_above_target_layer = true;
304 layers_equal = false;
305 break;
306 } else if (id == previous_id && new_id != previous_new_id) {
307 // Found a layer we are below. Move to next layer and check.
308 layers_equal = false;
309 break;
310 }
311 previous_id = id;
312 previous_new_id = new_id;
313 }
314 if (strictly_above_target_layer || layers_equal)
315 break;
316 }
317
318 // Found the layer we are above. Now move everything to accommodate the new
319 // layer. And put the new ids and type into the topology.
320 for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)
321 types[j] = types[i];
322 types[target_layer] = type;
323 for (int k = 0; k < num_hw_threads; ++k) {
324 for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)
325 hw_threads[k].ids[j] = hw_threads[k].ids[i];
326 hw_threads[k].ids[target_layer] = ids[k];
327 }
328 equivalent[type] = type;
329 depth++;
330}
331
332#if KMP_GROUP_AFFINITY
333// Insert the Windows Processor Group structure into the topology
334void kmp_topology_t::_insert_windows_proc_groups() {
335 // Do not insert the processor group structure for a single group
336 if (__kmp_num_proc_groups == 1)
337 return;
338 kmp_affin_mask_t *mask;
339 int *ids = (int *)__kmp_allocate(sizeof(int) * num_hw_threads);
340 KMP_CPU_ALLOC(mask);
341 for (int i = 0; i < num_hw_threads; ++i) {
342 KMP_CPU_ZERO(mask);
343 KMP_CPU_SET(hw_threads[i].os_id, mask);
344 ids[i] = __kmp_get_proc_group(mask);
345 }
346 KMP_CPU_FREE(mask);
348 __kmp_free(ids);
349
350 // sort topology after adding proc groups
352}
353#endif
354
355// Remove layers that don't add information to the topology.
356// This is done by having the layer take on the id = UNKNOWN_ID (-1)
357void kmp_topology_t::_remove_radix1_layers() {
358 int preference[KMP_HW_LAST];
359 int top_index1, top_index2;
360 // Set up preference associative array
361 preference[KMP_HW_SOCKET] = 110;
362 preference[KMP_HW_PROC_GROUP] = 100;
363 preference[KMP_HW_CORE] = 95;
364 preference[KMP_HW_THREAD] = 90;
365 preference[KMP_HW_NUMA] = 85;
366 preference[KMP_HW_DIE] = 80;
367 preference[KMP_HW_TILE] = 75;
368 preference[KMP_HW_MODULE] = 73;
369 preference[KMP_HW_L3] = 70;
370 preference[KMP_HW_L2] = 65;
371 preference[KMP_HW_L1] = 60;
372 preference[KMP_HW_LLC] = 5;
373 top_index1 = 0;
374 top_index2 = 1;
375 while (top_index1 < depth - 1 && top_index2 < depth) {
376 kmp_hw_t type1 = types[top_index1];
377 kmp_hw_t type2 = types[top_index2];
380 // Do not allow the three main topology levels (sockets, cores, threads) to
381 // be compacted down
382 if ((type1 == KMP_HW_THREAD || type1 == KMP_HW_CORE ||
383 type1 == KMP_HW_SOCKET) &&
384 (type2 == KMP_HW_THREAD || type2 == KMP_HW_CORE ||
385 type2 == KMP_HW_SOCKET)) {
386 top_index1 = top_index2++;
387 continue;
388 }
389 bool radix1 = true;
390 bool all_same = true;
391 int id1 = hw_threads[0].ids[top_index1];
392 int id2 = hw_threads[0].ids[top_index2];
393 int pref1 = preference[type1];
394 int pref2 = preference[type2];
395 for (int hwidx = 1; hwidx < num_hw_threads; ++hwidx) {
396 if (hw_threads[hwidx].ids[top_index1] == id1 &&
397 hw_threads[hwidx].ids[top_index2] != id2) {
398 radix1 = false;
399 break;
400 }
401 if (hw_threads[hwidx].ids[top_index2] != id2)
402 all_same = false;
403 id1 = hw_threads[hwidx].ids[top_index1];
404 id2 = hw_threads[hwidx].ids[top_index2];
405 }
406 if (radix1) {
407 // Select the layer to remove based on preference
408 kmp_hw_t remove_type, keep_type;
409 int remove_layer, remove_layer_ids;
410 if (pref1 > pref2) {
411 remove_type = type2;
412 remove_layer = remove_layer_ids = top_index2;
413 keep_type = type1;
414 } else {
415 remove_type = type1;
416 remove_layer = remove_layer_ids = top_index1;
417 keep_type = type2;
418 }
419 // If all the indexes for the second (deeper) layer are the same.
420 // e.g., all are zero, then make sure to keep the first layer's ids
421 if (all_same)
422 remove_layer_ids = top_index2;
423 // Remove radix one type by setting the equivalence, removing the id from
424 // the hw threads and removing the layer from types and depth
425 set_equivalent_type(remove_type, keep_type);
426 for (int idx = 0; idx < num_hw_threads; ++idx) {
427 kmp_hw_thread_t &hw_thread = hw_threads[idx];
428 for (int d = remove_layer_ids; d < depth - 1; ++d)
429 hw_thread.ids[d] = hw_thread.ids[d + 1];
430 }
431 for (int idx = remove_layer; idx < depth - 1; ++idx)
432 types[idx] = types[idx + 1];
433 depth--;
434 } else {
435 top_index1 = top_index2++;
436 }
437 }
438 KMP_ASSERT(depth > 0);
439}
440
441void kmp_topology_t::_set_last_level_cache() {
446#if KMP_MIC_SUPPORTED
447 else if (__kmp_mic_type == mic3) {
452 // L2/Tile wasn't detected so just say L1
453 else
455 }
456#endif
459 // Fallback is to set last level cache to socket or core
465 }
467}
468
469// Gather the count of each topology layer and the ratio
470void kmp_topology_t::_gather_enumeration_information() {
471 int previous_id[KMP_HW_LAST];
472 int max[KMP_HW_LAST];
473
474 for (int i = 0; i < depth; ++i) {
475 previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;
476 max[i] = 0;
477 count[i] = 0;
478 ratio[i] = 0;
479 }
480 int core_level = get_level(KMP_HW_CORE);
481 for (int i = 0; i < num_hw_threads; ++i) {
482 kmp_hw_thread_t &hw_thread = hw_threads[i];
483 for (int layer = 0; layer < depth; ++layer) {
484 int id = hw_thread.ids[layer];
485 if (id != previous_id[layer]) {
486 // Add an additional increment to each count
487 for (int l = layer; l < depth; ++l) {
488 if (hw_thread.ids[l] != kmp_hw_thread_t::UNKNOWN_ID)
489 count[l]++;
490 }
491 // Keep track of topology layer ratio statistics
492 if (hw_thread.ids[layer] != kmp_hw_thread_t::UNKNOWN_ID)
493 max[layer]++;
494 for (int l = layer + 1; l < depth; ++l) {
495 if (max[l] > ratio[l])
496 ratio[l] = max[l];
497 max[l] = 1;
498 }
499 // Figure out the number of different core types
500 // and efficiencies for hybrid CPUs
501 if (__kmp_is_hybrid_cpu() && core_level >= 0 && layer <= core_level) {
502 if (hw_thread.attrs.is_core_eff_valid() &&
503 hw_thread.attrs.core_eff >= num_core_efficiencies) {
504 // Because efficiencies can range from 0 to max efficiency - 1,
505 // the number of efficiencies is max efficiency + 1
506 num_core_efficiencies = hw_thread.attrs.core_eff + 1;
507 }
508 if (hw_thread.attrs.is_core_type_valid()) {
509 bool found = false;
510 for (int j = 0; j < num_core_types; ++j) {
511 if (hw_thread.attrs.get_core_type() == core_types[j]) {
512 found = true;
513 break;
514 }
515 }
516 if (!found) {
517 KMP_ASSERT(num_core_types < KMP_HW_MAX_NUM_CORE_TYPES);
518 core_types[num_core_types++] = hw_thread.attrs.get_core_type();
519 }
520 }
521 }
522 break;
523 }
524 }
525 for (int layer = 0; layer < depth; ++layer) {
526 previous_id[layer] = hw_thread.ids[layer];
527 }
528 }
529 for (int layer = 0; layer < depth; ++layer) {
530 if (max[layer] > ratio[layer])
531 ratio[layer] = max[layer];
532 }
533}
534
535int kmp_topology_t::_get_ncores_with_attr(const kmp_hw_attr_t &attr,
536 int above_level,
537 bool find_all) const {
538 int current, current_max;
539 int previous_id[KMP_HW_LAST];
540 for (int i = 0; i < depth; ++i)
541 previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;
542 int core_level = get_level(KMP_HW_CORE);
543 if (find_all)
544 above_level = -1;
545 KMP_ASSERT(above_level < core_level);
546 current_max = 0;
547 current = 0;
548 for (int i = 0; i < num_hw_threads; ++i) {
549 kmp_hw_thread_t &hw_thread = hw_threads[i];
550 if (!find_all && hw_thread.ids[above_level] != previous_id[above_level]) {
551 if (current > current_max)
552 current_max = current;
553 current = hw_thread.attrs.contains(attr);
554 } else {
555 for (int level = above_level + 1; level <= core_level; ++level) {
556 if (hw_thread.ids[level] != previous_id[level]) {
557 if (hw_thread.attrs.contains(attr))
558 current++;
559 break;
560 }
561 }
562 }
563 for (int level = 0; level < depth; ++level)
564 previous_id[level] = hw_thread.ids[level];
565 }
566 if (current > current_max)
567 current_max = current;
568 return current_max;
569}
570
571// Find out if the topology is uniform
572void kmp_topology_t::_discover_uniformity() {
573 int num = 1;
574 for (int level = 0; level < depth; ++level)
575 num *= ratio[level];
576 flags.uniform = (num == count[depth - 1]);
577}
578
579// Set all the sub_ids for each hardware thread
580void kmp_topology_t::_set_sub_ids() {
581 int previous_id[KMP_HW_LAST];
582 int sub_id[KMP_HW_LAST];
583
584 for (int i = 0; i < depth; ++i) {
585 previous_id[i] = -1;
586 sub_id[i] = -1;
587 }
588 for (int i = 0; i < num_hw_threads; ++i) {
589 kmp_hw_thread_t &hw_thread = hw_threads[i];
590 // Setup the sub_id
591 for (int j = 0; j < depth; ++j) {
592 if (hw_thread.ids[j] != previous_id[j]) {
593 sub_id[j]++;
594 for (int k = j + 1; k < depth; ++k) {
595 sub_id[k] = 0;
596 }
597 break;
598 }
599 }
600 // Set previous_id
601 for (int j = 0; j < depth; ++j) {
602 previous_id[j] = hw_thread.ids[j];
603 }
604 // Set the sub_ids field
605 for (int j = 0; j < depth; ++j) {
606 hw_thread.sub_ids[j] = sub_id[j];
607 }
608 }
609}
610
611void kmp_topology_t::_set_globals() {
612 // Set nCoresPerPkg, nPackages, __kmp_nThreadsPerCore, __kmp_ncores
613 int core_level, thread_level, package_level;
614 package_level = get_level(KMP_HW_SOCKET);
615#if KMP_GROUP_AFFINITY
616 if (package_level == -1)
617 package_level = get_level(KMP_HW_PROC_GROUP);
618#endif
619 core_level = get_level(KMP_HW_CORE);
620 thread_level = get_level(KMP_HW_THREAD);
621
622 KMP_ASSERT(core_level != -1);
623 KMP_ASSERT(thread_level != -1);
624
625 __kmp_nThreadsPerCore = calculate_ratio(thread_level, core_level);
626 if (package_level != -1) {
627 nCoresPerPkg = calculate_ratio(core_level, package_level);
628 nPackages = get_count(package_level);
629 } else {
630 // assume one socket
631 nCoresPerPkg = get_count(core_level);
632 nPackages = 1;
633 }
634#ifndef KMP_DFLT_NTH_CORES
635 __kmp_ncores = get_count(core_level);
636#endif
637}
638
640 const kmp_hw_t *types) {
641 kmp_topology_t *retval;
642 // Allocate all data in one large allocation
643 size_t size = sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc +
644 sizeof(int) * (size_t)KMP_HW_LAST * 3;
645 char *bytes = (char *)__kmp_allocate(size);
646 retval = (kmp_topology_t *)bytes;
647 if (nproc > 0) {
648 retval->hw_threads = (kmp_hw_thread_t *)(bytes + sizeof(kmp_topology_t));
649 } else {
650 retval->hw_threads = nullptr;
651 }
652 retval->num_hw_threads = nproc;
653 retval->depth = ndepth;
654 int *arr =
655 (int *)(bytes + sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc);
656 retval->types = (kmp_hw_t *)arr;
657 retval->ratio = arr + (size_t)KMP_HW_LAST;
658 retval->count = arr + 2 * (size_t)KMP_HW_LAST;
659 retval->num_core_efficiencies = 0;
660 retval->num_core_types = 0;
661 retval->compact = 0;
662 for (int i = 0; i < KMP_HW_MAX_NUM_CORE_TYPES; ++i)
663 retval->core_types[i] = KMP_HW_CORE_TYPE_UNKNOWN;
664 KMP_FOREACH_HW_TYPE(type) { retval->equivalent[type] = KMP_HW_UNKNOWN; }
665 for (int i = 0; i < ndepth; ++i) {
666 retval->types[i] = types[i];
667 retval->equivalent[types[i]] = types[i];
668 }
669 return retval;
670}
671
673 if (topology)
674 __kmp_free(topology);
675}
676
678 // Assume ids have been sorted
679 if (num_hw_threads == 0)
680 return true;
681 for (int i = 1; i < num_hw_threads; ++i) {
682 kmp_hw_thread_t &current_thread = hw_threads[i];
683 kmp_hw_thread_t &previous_thread = hw_threads[i - 1];
684 bool unique = false;
685 for (int j = 0; j < depth; ++j) {
686 if (previous_thread.ids[j] != current_thread.ids[j]) {
687 unique = true;
688 break;
689 }
690 }
691 if (unique)
692 continue;
693 return false;
694 }
695 return true;
696}
697
699 printf("***********************\n");
700 printf("*** __kmp_topology: ***\n");
701 printf("***********************\n");
702 printf("* depth: %d\n", depth);
703
704 printf("* types: ");
705 for (int i = 0; i < depth; ++i)
706 printf("%15s ", __kmp_hw_get_keyword(types[i]));
707 printf("\n");
708
709 printf("* ratio: ");
710 for (int i = 0; i < depth; ++i) {
711 printf("%15d ", ratio[i]);
712 }
713 printf("\n");
714
715 printf("* count: ");
716 for (int i = 0; i < depth; ++i) {
717 printf("%15d ", count[i]);
718 }
719 printf("\n");
720
721 printf("* num_core_eff: %d\n", num_core_efficiencies);
722 printf("* num_core_types: %d\n", num_core_types);
723 printf("* core_types: ");
724 for (int i = 0; i < num_core_types; ++i)
725 printf("%3d ", core_types[i]);
726 printf("\n");
727
728 printf("* equivalent map:\n");
730 const char *key = __kmp_hw_get_keyword(i);
731 const char *value = __kmp_hw_get_keyword(equivalent[i]);
732 printf("%-15s -> %-15s\n", key, value);
733 }
734
735 printf("* uniform: %s\n", (is_uniform() ? "Yes" : "No"));
736
737 printf("* num_hw_threads: %d\n", num_hw_threads);
738 printf("* hw_threads:\n");
739 for (int i = 0; i < num_hw_threads; ++i) {
740 hw_threads[i].print();
741 }
742 printf("***********************\n");
743}
744
745void kmp_topology_t::print(const char *env_var) const {
747 int print_types_depth;
749 kmp_hw_t print_types[KMP_HW_LAST + 2];
750
751 // Num Available Threads
752 if (num_hw_threads) {
753 KMP_INFORM(AvailableOSProc, env_var, num_hw_threads);
754 } else {
755 KMP_INFORM(AvailableOSProc, env_var, __kmp_xproc);
756 }
757
758 // Uniform or not
759 if (is_uniform()) {
760 KMP_INFORM(Uniform, env_var);
761 } else {
762 KMP_INFORM(NonUniform, env_var);
763 }
764
765 // Equivalent types
767 kmp_hw_t eq_type = equivalent[type];
768 if (eq_type != KMP_HW_UNKNOWN && eq_type != type) {
769 KMP_INFORM(AffEqualTopologyTypes, env_var,
772 }
773 }
774
775 // Quick topology
776 KMP_ASSERT(depth > 0 && depth <= (int)KMP_HW_LAST);
777 // Create a print types array that always guarantees printing
778 // the core and thread level
779 print_types_depth = 0;
780 for (int level = 0; level < depth; ++level)
781 print_types[print_types_depth++] = types[level];
782 if (equivalent[KMP_HW_CORE] != KMP_HW_CORE) {
783 // Force in the core level for quick topology
784 if (print_types[print_types_depth - 1] == KMP_HW_THREAD) {
785 // Force core before thread e.g., 1 socket X 2 threads/socket
786 // becomes 1 socket X 1 core/socket X 2 threads/socket
787 print_types[print_types_depth - 1] = KMP_HW_CORE;
788 print_types[print_types_depth++] = KMP_HW_THREAD;
789 } else {
790 print_types[print_types_depth++] = KMP_HW_CORE;
791 }
792 }
793 // Always put threads at very end of quick topology
794 if (equivalent[KMP_HW_THREAD] != KMP_HW_THREAD)
795 print_types[print_types_depth++] = KMP_HW_THREAD;
796
798 kmp_hw_t numerator_type;
799 kmp_hw_t denominator_type = KMP_HW_UNKNOWN;
800 int core_level = get_level(KMP_HW_CORE);
801 int ncores = get_count(core_level);
802
803 for (int plevel = 0, level = 0; plevel < print_types_depth; ++plevel) {
804 int c;
805 bool plural;
806 numerator_type = print_types[plevel];
807 KMP_ASSERT_VALID_HW_TYPE(numerator_type);
808 if (equivalent[numerator_type] != numerator_type)
809 c = 1;
810 else
811 c = get_ratio(level++);
812 plural = (c > 1);
813 if (plevel == 0) {
814 __kmp_str_buf_print(&buf, "%d %s", c,
815 __kmp_hw_get_catalog_string(numerator_type, plural));
816 } else {
817 __kmp_str_buf_print(&buf, " x %d %s/%s", c,
818 __kmp_hw_get_catalog_string(numerator_type, plural),
819 __kmp_hw_get_catalog_string(denominator_type));
820 }
821 denominator_type = numerator_type;
822 }
823 KMP_INFORM(TopologyGeneric, env_var, buf.str, ncores);
824
825 // Hybrid topology information
826 if (__kmp_is_hybrid_cpu()) {
827 for (int i = 0; i < num_core_types; ++i) {
828 kmp_hw_core_type_t core_type = core_types[i];
829 kmp_hw_attr_t attr;
830 attr.clear();
831 attr.set_core_type(core_type);
832 int ncores = get_ncores_with_attr(attr);
833 if (ncores > 0) {
834 KMP_INFORM(TopologyHybrid, env_var, ncores,
836 KMP_ASSERT(num_core_efficiencies <= KMP_HW_MAX_NUM_CORE_EFFS)
837 for (int eff = 0; eff < num_core_efficiencies; ++eff) {
838 attr.set_core_eff(eff);
839 int ncores_with_eff = get_ncores_with_attr(attr);
840 if (ncores_with_eff > 0) {
841 KMP_INFORM(TopologyHybridCoreEff, env_var, ncores_with_eff, eff);
842 }
843 }
844 }
845 }
846 }
847
848 if (num_hw_threads <= 0) {
850 return;
851 }
852
853 // Full OS proc to hardware thread map
854 KMP_INFORM(OSProcToPhysicalThreadMap, env_var);
855 for (int i = 0; i < num_hw_threads; i++) {
857 for (int level = 0; level < depth; ++level) {
858 if (hw_threads[i].ids[level] == kmp_hw_thread_t::UNKNOWN_ID)
859 continue;
860 kmp_hw_t type = types[level];
862 __kmp_str_buf_print(&buf, "%d ", hw_threads[i].ids[level]);
863 }
866 &buf, "(%s)",
867 __kmp_hw_get_core_type_string(hw_threads[i].attrs.get_core_type()));
868 KMP_INFORM(OSProcMapToPack, env_var, hw_threads[i].os_id, buf.str);
869 }
870
872}
873
874#if KMP_AFFINITY_SUPPORTED
875void kmp_topology_t::set_granularity(kmp_affinity_t &affinity) const {
876 const char *env_var = __kmp_get_affinity_env_var(affinity);
877 // If requested hybrid CPU attributes for granularity (either OMP_PLACES or
878 // KMP_AFFINITY), but none exist, then reset granularity and have below method
879 // select a granularity and warn user.
880 if (!__kmp_is_hybrid_cpu()) {
881 if (affinity.core_attr_gran.valid) {
882 // OMP_PLACES with cores:<attribute> but non-hybrid arch, use cores
883 // instead
885 affinity, AffIgnoringNonHybrid, env_var,
886 __kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true));
887 affinity.gran = KMP_HW_CORE;
888 affinity.gran_levels = -1;
889 affinity.core_attr_gran = KMP_AFFINITY_ATTRS_UNKNOWN;
890 affinity.flags.core_types_gran = affinity.flags.core_effs_gran = 0;
891 } else if (affinity.flags.core_types_gran ||
892 affinity.flags.core_effs_gran) {
893 // OMP_PLACES=core_types|core_effs but non-hybrid, use cores instead
894 if (affinity.flags.omp_places) {
896 affinity, AffIgnoringNonHybrid, env_var,
897 __kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true));
898 } else {
899 // KMP_AFFINITY=granularity=core_type|core_eff,...
900 KMP_AFF_WARNING(affinity, AffGranularityBad, env_var,
901 "Intel(R) Hybrid Technology core attribute",
903 }
904 affinity.gran = KMP_HW_CORE;
905 affinity.gran_levels = -1;
906 affinity.core_attr_gran = KMP_AFFINITY_ATTRS_UNKNOWN;
907 affinity.flags.core_types_gran = affinity.flags.core_effs_gran = 0;
908 }
909 }
910 // Set the number of affinity granularity levels
911 if (affinity.gran_levels < 0) {
912 kmp_hw_t gran_type = get_equivalent_type(affinity.gran);
913 // Check if user's granularity request is valid
914 if (gran_type == KMP_HW_UNKNOWN) {
915 // First try core, then thread, then package
917 for (auto g : gran_types) {
919 gran_type = g;
920 break;
921 }
922 }
923 KMP_ASSERT(gran_type != KMP_HW_UNKNOWN);
924 // Warn user what granularity setting will be used instead
925 KMP_AFF_WARNING(affinity, AffGranularityBad, env_var,
926 __kmp_hw_get_catalog_string(affinity.gran),
927 __kmp_hw_get_catalog_string(gran_type));
928 affinity.gran = gran_type;
929 }
930#if KMP_GROUP_AFFINITY
931 // If more than one processor group exists, and the level of
932 // granularity specified by the user is too coarse, then the
933 // granularity must be adjusted "down" to processor group affinity
934 // because threads can only exist within one processor group.
935 // For example, if a user sets granularity=socket and there are two
936 // processor groups that cover a socket, then the runtime must
937 // restrict the granularity down to the processor group level.
938 if (__kmp_num_proc_groups > 1) {
939 int gran_depth = get_level(gran_type);
940 int proc_group_depth = get_level(KMP_HW_PROC_GROUP);
941 if (gran_depth >= 0 && proc_group_depth >= 0 &&
942 gran_depth < proc_group_depth) {
943 KMP_AFF_WARNING(affinity, AffGranTooCoarseProcGroup, env_var,
944 __kmp_hw_get_catalog_string(affinity.gran));
945 affinity.gran = gran_type = KMP_HW_PROC_GROUP;
946 }
947 }
948#endif
949 affinity.gran_levels = 0;
950 for (int i = depth - 1; i >= 0 && get_type(i) != gran_type; --i)
951 affinity.gran_levels++;
952 }
953}
954#endif
955
957#if KMP_GROUP_AFFINITY
958 _insert_windows_proc_groups();
959#endif
960 _remove_radix1_layers();
961 _gather_enumeration_information();
962 _discover_uniformity();
963 _set_sub_ids();
964 _set_globals();
965 _set_last_level_cache();
966
967#if KMP_MIC_SUPPORTED
968 // Manually Add L2 = Tile equivalence
969 if (__kmp_mic_type == mic3) {
970 if (get_level(KMP_HW_L2) != -1)
972 else if (get_level(KMP_HW_TILE) != -1)
974 }
975#endif
976
977 // Perform post canonicalization checking
978 KMP_ASSERT(depth > 0);
979 for (int level = 0; level < depth; ++level) {
980 // All counts, ratios, and types must be valid
981 KMP_ASSERT(count[level] > 0 && ratio[level] > 0);
983 // Detected types must point to themselves
984 KMP_ASSERT(equivalent[types[level]] == types[level]);
985 }
986}
987
988// Canonicalize an explicit packages X cores/pkg X threads/core topology
989void kmp_topology_t::canonicalize(int npackages, int ncores_per_pkg,
990 int nthreads_per_core, int ncores) {
991 int ndepth = 3;
992 depth = ndepth;
993 KMP_FOREACH_HW_TYPE(i) { equivalent[i] = KMP_HW_UNKNOWN; }
994 for (int level = 0; level < depth; ++level) {
995 count[level] = 0;
996 ratio[level] = 0;
997 }
998 count[0] = npackages;
999 count[1] = ncores;
1000 count[2] = __kmp_xproc;
1001 ratio[0] = npackages;
1002 ratio[1] = ncores_per_pkg;
1003 ratio[2] = nthreads_per_core;
1004 equivalent[KMP_HW_SOCKET] = KMP_HW_SOCKET;
1005 equivalent[KMP_HW_CORE] = KMP_HW_CORE;
1006 equivalent[KMP_HW_THREAD] = KMP_HW_THREAD;
1007 types[0] = KMP_HW_SOCKET;
1008 types[1] = KMP_HW_CORE;
1009 types[2] = KMP_HW_THREAD;
1010 //__kmp_avail_proc = __kmp_xproc;
1011 _discover_uniformity();
1012}
1013
1014#if KMP_AFFINITY_SUPPORTED
1015static kmp_str_buf_t *
1016__kmp_hw_get_catalog_core_string(const kmp_hw_attr_t &attr, kmp_str_buf_t *buf,
1017 bool plural) {
1019 if (attr.is_core_type_valid())
1020 __kmp_str_buf_print(buf, "%s %s",
1023 else
1024 __kmp_str_buf_print(buf, "%s eff=%d",
1026 attr.get_core_eff());
1027 return buf;
1028}
1029
1030bool kmp_topology_t::restrict_to_mask(const kmp_affin_mask_t *mask) {
1031 // Apply the filter
1032 bool affected;
1033 int new_index = 0;
1034 for (int i = 0; i < num_hw_threads; ++i) {
1035 int os_id = hw_threads[i].os_id;
1036 if (KMP_CPU_ISSET(os_id, mask)) {
1037 if (i != new_index)
1038 hw_threads[new_index] = hw_threads[i];
1039 new_index++;
1040 } else {
1041 KMP_CPU_CLR(os_id, __kmp_affin_fullMask);
1043 }
1044 }
1045
1046 KMP_DEBUG_ASSERT(new_index <= num_hw_threads);
1047 affected = (num_hw_threads != new_index);
1048 num_hw_threads = new_index;
1049
1050 // Post hardware subset canonicalization
1051 if (affected) {
1052 _gather_enumeration_information();
1053 _discover_uniformity();
1054 _set_globals();
1055 _set_last_level_cache();
1056#if KMP_OS_WINDOWS
1057 // Copy filtered full mask if topology has single processor group
1058 if (__kmp_num_proc_groups <= 1)
1059#endif
1060 __kmp_affin_origMask->copy(__kmp_affin_fullMask);
1061 }
1062 return affected;
1063}
1064
1065// Apply the KMP_HW_SUBSET envirable to the topology
1066// Returns true if KMP_HW_SUBSET filtered any processors
1067// otherwise, returns false
1068bool kmp_topology_t::filter_hw_subset() {
1069 // If KMP_HW_SUBSET wasn't requested, then do nothing.
1070 if (!__kmp_hw_subset)
1071 return false;
1072
1073 // First, sort the KMP_HW_SUBSET items by the machine topology
1075
1077
1078 // Check to see if KMP_HW_SUBSET is a valid subset of the detected topology
1079 bool using_core_types = false;
1080 bool using_core_effs = false;
1081 bool is_absolute = __kmp_hw_subset->is_absolute();
1082 int hw_subset_depth = __kmp_hw_subset->get_depth();
1083 kmp_hw_t specified[KMP_HW_LAST];
1084 int *topology_levels = (int *)KMP_ALLOCA(sizeof(int) * hw_subset_depth);
1085 KMP_ASSERT(hw_subset_depth > 0);
1086 KMP_FOREACH_HW_TYPE(i) { specified[i] = KMP_HW_UNKNOWN; }
1087 int core_level = get_level(KMP_HW_CORE);
1088 for (int i = 0; i < hw_subset_depth; ++i) {
1089 int max_count;
1090 const kmp_hw_subset_t::item_t &item = __kmp_hw_subset->at(i);
1091 int num = item.num[0];
1092 int offset = item.offset[0];
1093 kmp_hw_t type = item.type;
1094 kmp_hw_t equivalent_type = equivalent[type];
1095 int level = get_level(type);
1096 topology_levels[i] = level;
1097
1098 // Check to see if current layer is in detected machine topology
1099 if (equivalent_type != KMP_HW_UNKNOWN) {
1100 __kmp_hw_subset->at(i).type = equivalent_type;
1101 } else {
1102 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetNotExistGeneric,
1104 return false;
1105 }
1106
1107 // Check to see if current layer has already been
1108 // specified either directly or through an equivalent type
1109 if (specified[equivalent_type] != KMP_HW_UNKNOWN) {
1110 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetEqvLayers,
1112 __kmp_hw_get_catalog_string(specified[equivalent_type]));
1113 return false;
1114 }
1115 specified[equivalent_type] = type;
1116
1117 // Check to see if each layer's num & offset parameters are valid
1118 max_count = get_ratio(level);
1119 if (!is_absolute) {
1120 if (max_count < 0 ||
1121 (num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {
1122 bool plural = (num > 1);
1123 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetManyGeneric,
1125 return false;
1126 }
1127 }
1128
1129 // Check to see if core attributes are consistent
1130 if (core_level == level) {
1131 // Determine which core attributes are specified
1132 for (int j = 0; j < item.num_attrs; ++j) {
1133 if (item.attr[j].is_core_type_valid())
1134 using_core_types = true;
1135 if (item.attr[j].is_core_eff_valid())
1136 using_core_effs = true;
1137 }
1138
1139 // Check if using a single core attribute on non-hybrid arch.
1140 // Do not ignore all of KMP_HW_SUBSET, just ignore the attribute.
1141 //
1142 // Check if using multiple core attributes on non-hyrbid arch.
1143 // Ignore all of KMP_HW_SUBSET if this is the case.
1144 if ((using_core_effs || using_core_types) && !__kmp_is_hybrid_cpu()) {
1145 if (item.num_attrs == 1) {
1146 if (using_core_effs) {
1147 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIgnoringAttr,
1148 "efficiency");
1149 } else {
1150 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIgnoringAttr,
1151 "core_type");
1152 }
1153 using_core_effs = false;
1154 using_core_types = false;
1155 } else {
1156 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAttrsNonHybrid);
1157 return false;
1158 }
1159 }
1160
1161 // Check if using both core types and core efficiencies together
1162 if (using_core_types && using_core_effs) {
1163 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIncompat, "core_type",
1164 "efficiency");
1165 return false;
1166 }
1167
1168 // Check that core efficiency values are valid
1169 if (using_core_effs) {
1170 for (int j = 0; j < item.num_attrs; ++j) {
1171 if (item.attr[j].is_core_eff_valid()) {
1172 int core_eff = item.attr[j].get_core_eff();
1173 if (core_eff < 0 || core_eff >= num_core_efficiencies) {
1176 __kmp_str_buf_print(&buf, "%d", item.attr[j].get_core_eff());
1178 KMP_MSG(AffHWSubsetAttrInvalid, "efficiency", buf.str),
1179 KMP_HNT(ValidValuesRange, 0, num_core_efficiencies - 1),
1182 return false;
1183 }
1184 }
1185 }
1186 }
1187
1188 // Check that the number of requested cores with attributes is valid
1189 if ((using_core_types || using_core_effs) && !is_absolute) {
1190 for (int j = 0; j < item.num_attrs; ++j) {
1191 int num = item.num[j];
1192 int offset = item.offset[j];
1193 int level_above = core_level - 1;
1194 if (level_above >= 0) {
1195 max_count = get_ncores_with_attr_per(item.attr[j], level_above);
1196 if (max_count <= 0 ||
1197 (num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {
1199 __kmp_hw_get_catalog_core_string(item.attr[j], &buf, num > 0);
1200 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetManyGeneric, buf.str);
1202 return false;
1203 }
1204 }
1205 }
1206 }
1207
1208 if ((using_core_types || using_core_effs) && item.num_attrs > 1) {
1209 for (int j = 0; j < item.num_attrs; ++j) {
1210 // Ambiguous use of specific core attribute + generic core
1211 // e.g., 4c & 3c:intel_core or 4c & 3c:eff1
1212 if (!item.attr[j]) {
1213 kmp_hw_attr_t other_attr;
1214 for (int k = 0; k < item.num_attrs; ++k) {
1215 if (item.attr[k] != item.attr[j]) {
1216 other_attr = item.attr[k];
1217 break;
1218 }
1219 }
1221 __kmp_hw_get_catalog_core_string(other_attr, &buf, item.num[j] > 0);
1222 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIncompat,
1225 return false;
1226 }
1227 // Allow specifying a specific core type or core eff exactly once
1228 for (int k = 0; k < j; ++k) {
1229 if (!item.attr[j] || !item.attr[k])
1230 continue;
1231 if (item.attr[k] == item.attr[j]) {
1233 __kmp_hw_get_catalog_core_string(item.attr[j], &buf,
1234 item.num[j] > 0);
1235 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAttrRepeat, buf.str);
1237 return false;
1238 }
1239 }
1240 }
1241 }
1242 }
1243 }
1244
1245 // For keeping track of sub_ids for an absolute KMP_HW_SUBSET
1246 // or core attributes (core type or efficiency)
1247 int prev_sub_ids[KMP_HW_LAST];
1248 int abs_sub_ids[KMP_HW_LAST];
1249 int core_eff_sub_ids[KMP_HW_MAX_NUM_CORE_EFFS];
1250 int core_type_sub_ids[KMP_HW_MAX_NUM_CORE_TYPES];
1251 for (size_t i = 0; i < KMP_HW_LAST; ++i) {
1252 abs_sub_ids[i] = -1;
1253 prev_sub_ids[i] = -1;
1254 }
1255 for (size_t i = 0; i < KMP_HW_MAX_NUM_CORE_EFFS; ++i)
1256 core_eff_sub_ids[i] = -1;
1257 for (size_t i = 0; i < KMP_HW_MAX_NUM_CORE_TYPES; ++i)
1258 core_type_sub_ids[i] = -1;
1259
1260 // Determine which hardware threads should be filtered.
1261
1262 // Helpful to determine if a topology layer is targeted by an absolute subset
1263 auto is_targeted = [&](int level) {
1264 if (is_absolute) {
1265 for (int i = 0; i < hw_subset_depth; ++i)
1266 if (topology_levels[i] == level)
1267 return true;
1268 return false;
1269 }
1270 // If not absolute KMP_HW_SUBSET, then every layer is seen as targeted
1271 return true;
1272 };
1273
1274 // Helpful to index into core type sub Ids array
1275 auto get_core_type_index = [](const kmp_hw_thread_t &t) {
1276 switch (t.attrs.get_core_type()) {
1279 return 0;
1280#if KMP_ARCH_X86 || KMP_ARCH_X86_64
1281 case KMP_HW_CORE_TYPE_ATOM:
1282 return 1;
1283 case KMP_HW_CORE_TYPE_CORE:
1284 return 2;
1285#endif
1286 }
1287 KMP_ASSERT2(false, "Unhandled kmp_hw_thread_t enumeration");
1289 };
1290
1291 // Helpful to index into core efficiencies sub Ids array
1292 auto get_core_eff_index = [](const kmp_hw_thread_t &t) {
1293 return t.attrs.get_core_eff();
1294 };
1295
1296 int num_filtered = 0;
1297 kmp_affin_mask_t *filtered_mask;
1298 KMP_CPU_ALLOC(filtered_mask);
1299 KMP_CPU_COPY(filtered_mask, __kmp_affin_fullMask);
1300 for (int i = 0; i < num_hw_threads; ++i) {
1301 kmp_hw_thread_t &hw_thread = hw_threads[i];
1302
1303 // Figure out the absolute sub ids and core eff/type sub ids
1304 if (is_absolute || using_core_effs || using_core_types) {
1305 for (int level = 0; level < get_depth(); ++level) {
1306 if (hw_thread.sub_ids[level] != prev_sub_ids[level]) {
1307 bool found_targeted = false;
1308 for (int j = level; j < get_depth(); ++j) {
1309 bool targeted = is_targeted(j);
1310 if (!found_targeted && targeted) {
1311 found_targeted = true;
1312 abs_sub_ids[j]++;
1313 if (j == core_level && using_core_effs)
1314 core_eff_sub_ids[get_core_eff_index(hw_thread)]++;
1315 if (j == core_level && using_core_types)
1316 core_type_sub_ids[get_core_type_index(hw_thread)]++;
1317 } else if (targeted) {
1318 abs_sub_ids[j] = 0;
1319 if (j == core_level && using_core_effs)
1320 core_eff_sub_ids[get_core_eff_index(hw_thread)] = 0;
1321 if (j == core_level && using_core_types)
1322 core_type_sub_ids[get_core_type_index(hw_thread)] = 0;
1323 }
1324 }
1325 break;
1326 }
1327 }
1328 for (int level = 0; level < get_depth(); ++level)
1329 prev_sub_ids[level] = hw_thread.sub_ids[level];
1330 }
1331
1332 // Check to see if this hardware thread should be filtered
1333 bool should_be_filtered = false;
1334 for (int hw_subset_index = 0; hw_subset_index < hw_subset_depth;
1335 ++hw_subset_index) {
1336 const auto &hw_subset_item = __kmp_hw_subset->at(hw_subset_index);
1337 int level = topology_levels[hw_subset_index];
1338 if (level == -1)
1339 continue;
1340 if ((using_core_effs || using_core_types) && level == core_level) {
1341 // Look for the core attribute in KMP_HW_SUBSET which corresponds
1342 // to this hardware thread's core attribute. Use this num,offset plus
1343 // the running sub_id for the particular core attribute of this hardware
1344 // thread to determine if the hardware thread should be filtered or not.
1345 int attr_idx;
1346 kmp_hw_core_type_t core_type = hw_thread.attrs.get_core_type();
1347 int core_eff = hw_thread.attrs.get_core_eff();
1348 for (attr_idx = 0; attr_idx < hw_subset_item.num_attrs; ++attr_idx) {
1349 if (using_core_types &&
1350 hw_subset_item.attr[attr_idx].get_core_type() == core_type)
1351 break;
1352 if (using_core_effs &&
1353 hw_subset_item.attr[attr_idx].get_core_eff() == core_eff)
1354 break;
1355 }
1356 // This core attribute isn't in the KMP_HW_SUBSET so always filter it.
1357 if (attr_idx == hw_subset_item.num_attrs) {
1358 should_be_filtered = true;
1359 break;
1360 }
1361 int sub_id;
1362 int num = hw_subset_item.num[attr_idx];
1363 int offset = hw_subset_item.offset[attr_idx];
1364 if (using_core_types)
1365 sub_id = core_type_sub_ids[get_core_type_index(hw_thread)];
1366 else
1367 sub_id = core_eff_sub_ids[get_core_eff_index(hw_thread)];
1368 if (sub_id < offset ||
1369 (num != kmp_hw_subset_t::USE_ALL && sub_id >= offset + num)) {
1370 should_be_filtered = true;
1371 break;
1372 }
1373 } else {
1374 int sub_id;
1375 int num = hw_subset_item.num[0];
1376 int offset = hw_subset_item.offset[0];
1377 if (is_absolute)
1378 sub_id = abs_sub_ids[level];
1379 else
1380 sub_id = hw_thread.sub_ids[level];
1381 if (hw_thread.ids[level] == kmp_hw_thread_t::UNKNOWN_ID ||
1382 sub_id < offset ||
1383 (num != kmp_hw_subset_t::USE_ALL && sub_id >= offset + num)) {
1384 should_be_filtered = true;
1385 break;
1386 }
1387 }
1388 }
1389 // Collect filtering information
1390 if (should_be_filtered) {
1391 KMP_CPU_CLR(hw_thread.os_id, filtered_mask);
1392 num_filtered++;
1393 }
1394 }
1395
1396 // One last check that we shouldn't allow filtering entire machine
1397 if (num_filtered == num_hw_threads) {
1398 KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAllFiltered);
1399 KMP_CPU_FREE(filtered_mask);
1400 return false;
1401 }
1402
1403 // Apply the filter
1404 restrict_to_mask(filtered_mask);
1405 KMP_CPU_FREE(filtered_mask);
1406 return true;
1407}
1408
1409bool kmp_topology_t::is_close(int hwt1, int hwt2,
1410 const kmp_affinity_t &stgs) const {
1411 int hw_level = stgs.gran_levels;
1412 if (hw_level >= depth)
1413 return true;
1414 bool retval = true;
1415 const kmp_hw_thread_t &t1 = hw_threads[hwt1];
1416 const kmp_hw_thread_t &t2 = hw_threads[hwt2];
1417 if (stgs.flags.core_types_gran)
1418 return t1.attrs.get_core_type() == t2.attrs.get_core_type();
1419 if (stgs.flags.core_effs_gran)
1420 return t1.attrs.get_core_eff() == t2.attrs.get_core_eff();
1421 for (int i = 0; i < (depth - hw_level); ++i) {
1422 if (t1.ids[i] != t2.ids[i])
1423 return false;
1424 }
1425 return retval;
1426}
1427
1428////////////////////////////////////////////////////////////////////////////////
1429
1430bool KMPAffinity::picked_api = false;
1431
1432void *KMPAffinity::Mask::operator new(size_t n) { return __kmp_allocate(n); }
1433void *KMPAffinity::Mask::operator new[](size_t n) { return __kmp_allocate(n); }
1434void KMPAffinity::Mask::operator delete(void *p) { __kmp_free(p); }
1435void KMPAffinity::Mask::operator delete[](void *p) { __kmp_free(p); }
1436void *KMPAffinity::operator new(size_t n) { return __kmp_allocate(n); }
1437void KMPAffinity::operator delete(void *p) { __kmp_free(p); }
1438
1439void KMPAffinity::pick_api() {
1440 KMPAffinity *affinity_dispatch;
1441 if (picked_api)
1442 return;
1443#if KMP_HWLOC_ENABLED
1444 // Only use Hwloc if affinity isn't explicitly disabled and
1445 // user requests Hwloc topology method
1446 if (__kmp_affinity_top_method == affinity_top_method_hwloc &&
1447 __kmp_affinity.type != affinity_disabled) {
1448 affinity_dispatch = new KMPHwlocAffinity();
1449 __kmp_hwloc_available = true;
1450 } else
1451#endif // KMP_HWLOC_ENABLED
1452 {
1453 affinity_dispatch = new KMPNativeAffinity();
1454 }
1455 __kmp_affinity_dispatch = affinity_dispatch;
1456 picked_api = true;
1457}
1458
1459void KMPAffinity::destroy_api() {
1460 if (__kmp_affinity_dispatch != NULL) {
1461 delete __kmp_affinity_dispatch;
1462 __kmp_affinity_dispatch = NULL;
1463 picked_api = false;
1464 }
1465}
1466
1467#define KMP_ADVANCE_SCAN(scan) \
1468 while (*scan != '\0') { \
1469 scan++; \
1470 }
1471
1472// Print the affinity mask to the character array in a pretty format.
1473// The format is a comma separated list of non-negative integers or integer
1474// ranges: e.g., 1,2,3-5,7,9-15
1475// The format can also be the string "{<empty>}" if no bits are set in mask
1476char *__kmp_affinity_print_mask(char *buf, int buf_len,
1477 kmp_affin_mask_t *mask) {
1478 int start = 0, finish = 0, previous = 0;
1479 bool first_range;
1480 KMP_ASSERT(buf);
1481 KMP_ASSERT(buf_len >= 40);
1483 char *scan = buf;
1484 char *end = buf + buf_len - 1;
1485
1486 // Check for empty set.
1487 if (mask->begin() == mask->end()) {
1488 KMP_SNPRINTF(scan, end - scan + 1, "{<empty>}");
1489 KMP_ADVANCE_SCAN(scan);
1490 KMP_ASSERT(scan <= end);
1491 return buf;
1492 }
1493
1494 first_range = true;
1495 start = mask->begin();
1496 while (1) {
1497 // Find next range
1498 // [start, previous] is inclusive range of contiguous bits in mask
1499 for (finish = mask->next(start), previous = start;
1500 finish == previous + 1 && finish != mask->end();
1501 finish = mask->next(finish)) {
1502 previous = finish;
1503 }
1504
1505 // The first range does not need a comma printed before it, but the rest
1506 // of the ranges do need a comma beforehand
1507 if (!first_range) {
1508 KMP_SNPRINTF(scan, end - scan + 1, "%s", ",");
1509 KMP_ADVANCE_SCAN(scan);
1510 } else {
1511 first_range = false;
1512 }
1513 // Range with three or more contiguous bits in the affinity mask
1514 if (previous - start > 1) {
1515 KMP_SNPRINTF(scan, end - scan + 1, "%u-%u", start, previous);
1516 } else {
1517 // Range with one or two contiguous bits in the affinity mask
1518 KMP_SNPRINTF(scan, end - scan + 1, "%u", start);
1519 KMP_ADVANCE_SCAN(scan);
1520 if (previous - start > 0) {
1521 KMP_SNPRINTF(scan, end - scan + 1, ",%u", previous);
1522 }
1523 }
1524 KMP_ADVANCE_SCAN(scan);
1525 // Start over with new start point
1526 start = finish;
1527 if (start == mask->end())
1528 break;
1529 // Check for overflow
1530 if (end - scan < 2)
1531 break;
1532 }
1533
1534 // Check for overflow
1535 KMP_ASSERT(scan <= end);
1536 return buf;
1537}
1538#undef KMP_ADVANCE_SCAN
1539
1540// Print the affinity mask to the string buffer object in a pretty format
1541// The format is a comma separated list of non-negative integers or integer
1542// ranges: e.g., 1,2,3-5,7,9-15
1543// The format can also be the string "{<empty>}" if no bits are set in mask
1544kmp_str_buf_t *__kmp_affinity_str_buf_mask(kmp_str_buf_t *buf,
1545 kmp_affin_mask_t *mask) {
1546 int start = 0, finish = 0, previous = 0;
1547 bool first_range;
1548 KMP_ASSERT(buf);
1550
1552
1553 // Check for empty set.
1554 if (mask->begin() == mask->end()) {
1555 __kmp_str_buf_print(buf, "%s", "{<empty>}");
1556 return buf;
1557 }
1558
1559 first_range = true;
1560 start = mask->begin();
1561 while (1) {
1562 // Find next range
1563 // [start, previous] is inclusive range of contiguous bits in mask
1564 for (finish = mask->next(start), previous = start;
1565 finish == previous + 1 && finish != mask->end();
1566 finish = mask->next(finish)) {
1567 previous = finish;
1568 }
1569
1570 // The first range does not need a comma printed before it, but the rest
1571 // of the ranges do need a comma beforehand
1572 if (!first_range) {
1573 __kmp_str_buf_print(buf, "%s", ",");
1574 } else {
1575 first_range = false;
1576 }
1577 // Range with three or more contiguous bits in the affinity mask
1578 if (previous - start > 1) {
1579 __kmp_str_buf_print(buf, "%u-%u", start, previous);
1580 } else {
1581 // Range with one or two contiguous bits in the affinity mask
1582 __kmp_str_buf_print(buf, "%u", start);
1583 if (previous - start > 0) {
1584 __kmp_str_buf_print(buf, ",%u", previous);
1585 }
1586 }
1587 // Start over with new start point
1588 start = finish;
1589 if (start == mask->end())
1590 break;
1591 }
1592 return buf;
1593}
1594
1595static kmp_affin_mask_t *__kmp_parse_cpu_list(const char *path) {
1596 kmp_affin_mask_t *mask;
1597 KMP_CPU_ALLOC(mask);
1598 KMP_CPU_ZERO(mask);
1599#if KMP_OS_LINUX
1600 int n, begin_cpu, end_cpu;
1602 auto skip_ws = [](FILE *f) {
1603 int c;
1604 do {
1605 c = fgetc(f);
1606 } while (isspace(c));
1607 if (c != EOF)
1608 ungetc(c, f);
1609 };
1610 // File contains CSV of integer ranges representing the CPUs
1611 // e.g., 1,2,4-7,9,11-15
1612 int status = file.try_open(path, "r");
1613 if (status != 0)
1614 return mask;
1615 while (!feof(file)) {
1616 skip_ws(file);
1617 n = fscanf(file, "%d", &begin_cpu);
1618 if (n != 1)
1619 break;
1620 skip_ws(file);
1621 int c = fgetc(file);
1622 if (c == EOF || c == ',') {
1623 // Just single CPU
1624 end_cpu = begin_cpu;
1625 } else if (c == '-') {
1626 // Range of CPUs
1627 skip_ws(file);
1628 n = fscanf(file, "%d", &end_cpu);
1629 if (n != 1)
1630 break;
1631 skip_ws(file);
1632 c = fgetc(file); // skip ','
1633 } else {
1634 // Syntax problem
1635 break;
1636 }
1637 // Ensure a valid range of CPUs
1638 if (begin_cpu < 0 || begin_cpu >= __kmp_xproc || end_cpu < 0 ||
1639 end_cpu >= __kmp_xproc || begin_cpu > end_cpu) {
1640 continue;
1641 }
1642 // Insert [begin_cpu, end_cpu] into mask
1643 for (int cpu = begin_cpu; cpu <= end_cpu; ++cpu) {
1644 KMP_CPU_SET(cpu, mask);
1645 }
1646 }
1647#endif
1648 return mask;
1649}
1650
1651// Return (possibly empty) affinity mask representing the offline CPUs
1652// Caller must free the mask
1653kmp_affin_mask_t *__kmp_affinity_get_offline_cpus() {
1654 return __kmp_parse_cpu_list("/sys/devices/system/cpu/offline");
1655}
1656
1657// Return the number of available procs
1658int __kmp_affinity_entire_machine_mask(kmp_affin_mask_t *mask) {
1659 int avail_proc = 0;
1660 KMP_CPU_ZERO(mask);
1661
1662#if KMP_GROUP_AFFINITY
1663
1664 if (__kmp_num_proc_groups > 1) {
1665 int group;
1666 KMP_DEBUG_ASSERT(__kmp_GetActiveProcessorCount != NULL);
1667 for (group = 0; group < __kmp_num_proc_groups; group++) {
1668 int i;
1669 int num = __kmp_GetActiveProcessorCount(group);
1670 for (i = 0; i < num; i++) {
1671 KMP_CPU_SET(i + group * (CHAR_BIT * sizeof(DWORD_PTR)), mask);
1672 avail_proc++;
1673 }
1674 }
1675 } else
1676
1677#endif /* KMP_GROUP_AFFINITY */
1678
1679 {
1680 int proc;
1681 kmp_affin_mask_t *offline_cpus = __kmp_affinity_get_offline_cpus();
1682 for (proc = 0; proc < __kmp_xproc; proc++) {
1683 // Skip offline CPUs
1684 if (KMP_CPU_ISSET(proc, offline_cpus))
1685 continue;
1686 KMP_CPU_SET(proc, mask);
1687 avail_proc++;
1688 }
1689 KMP_CPU_FREE(offline_cpus);
1690 }
1691
1692 return avail_proc;
1693}
1694
1695// All of the __kmp_affinity_create_*_map() routines should allocate the
1696// internal topology object and set the layer ids for it. Each routine
1697// returns a boolean on whether it was successful at doing so.
1698kmp_affin_mask_t *__kmp_affin_fullMask = NULL;
1699// Original mask is a subset of full mask in multiple processor groups topology
1700kmp_affin_mask_t *__kmp_affin_origMask = NULL;
1701
1702#if KMP_HWLOC_ENABLED
1703static inline bool __kmp_hwloc_is_cache_type(hwloc_obj_t obj) {
1704#if HWLOC_API_VERSION >= 0x00020000
1705 return hwloc_obj_type_is_cache(obj->type);
1706#else
1707 return obj->type == HWLOC_OBJ_CACHE;
1708#endif
1709}
1710
1711// Returns KMP_HW_* type derived from HWLOC_* type
1712static inline kmp_hw_t __kmp_hwloc_type_2_topology_type(hwloc_obj_t obj) {
1713
1714 if (__kmp_hwloc_is_cache_type(obj)) {
1715 if (obj->attr->cache.type == HWLOC_OBJ_CACHE_INSTRUCTION)
1716 return KMP_HW_UNKNOWN;
1717 switch (obj->attr->cache.depth) {
1718 case 1:
1719 return KMP_HW_L1;
1720 case 2:
1721#if KMP_MIC_SUPPORTED
1722 if (__kmp_mic_type == mic3) {
1723 return KMP_HW_TILE;
1724 }
1725#endif
1726 return KMP_HW_L2;
1727 case 3:
1728 return KMP_HW_L3;
1729 }
1730 return KMP_HW_UNKNOWN;
1731 }
1732
1733 switch (obj->type) {
1734 case HWLOC_OBJ_PACKAGE:
1735 return KMP_HW_SOCKET;
1736 case HWLOC_OBJ_NUMANODE:
1737 return KMP_HW_NUMA;
1738 case HWLOC_OBJ_CORE:
1739 return KMP_HW_CORE;
1740 case HWLOC_OBJ_PU:
1741 return KMP_HW_THREAD;
1742 case HWLOC_OBJ_GROUP:
1743#if HWLOC_API_VERSION >= 0x00020000
1744 if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_DIE)
1745 return KMP_HW_DIE;
1746 else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_TILE)
1747 return KMP_HW_TILE;
1748 else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_MODULE)
1749 return KMP_HW_MODULE;
1750 else if (obj->attr->group.kind == HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP)
1751 return KMP_HW_PROC_GROUP;
1752#endif
1753 return KMP_HW_UNKNOWN;
1754#if HWLOC_API_VERSION >= 0x00020100
1755 case HWLOC_OBJ_DIE:
1756 return KMP_HW_DIE;
1757#endif
1758 }
1759 return KMP_HW_UNKNOWN;
1760}
1761
1762// Returns the number of objects of type 'type' below 'obj' within the topology
1763// tree structure. e.g., if obj is a HWLOC_OBJ_PACKAGE object, and type is
1764// HWLOC_OBJ_PU, then this will return the number of PU's under the SOCKET
1765// object.
1766static int __kmp_hwloc_get_nobjs_under_obj(hwloc_obj_t obj,
1767 hwloc_obj_type_t type) {
1768 int retval = 0;
1769 hwloc_obj_t first;
1770 for (first = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, obj->type,
1771 obj->logical_index, type, 0);
1772 first != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology,
1773 obj->type, first) == obj;
1774 first = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, first->type,
1775 first)) {
1776 ++retval;
1777 }
1778 return retval;
1779}
1780
1781// This gets the sub_id for a lower object under a higher object in the
1782// topology tree
1783static int __kmp_hwloc_get_sub_id(hwloc_topology_t t, hwloc_obj_t higher,
1784 hwloc_obj_t lower) {
1785 hwloc_obj_t obj;
1786 hwloc_obj_type_t ltype = lower->type;
1787 int lindex = lower->logical_index - 1;
1788 int sub_id = 0;
1789 // Get the previous lower object
1790 obj = hwloc_get_obj_by_type(t, ltype, lindex);
1791 while (obj && lindex >= 0 &&
1792 hwloc_bitmap_isincluded(obj->cpuset, higher->cpuset)) {
1793 if (obj->userdata) {
1794 sub_id = (int)(RCAST(kmp_intptr_t, obj->userdata));
1795 break;
1796 }
1797 sub_id++;
1798 lindex--;
1799 obj = hwloc_get_obj_by_type(t, ltype, lindex);
1800 }
1801 // store sub_id + 1 so that 0 is differed from NULL
1802 lower->userdata = RCAST(void *, sub_id + 1);
1803 return sub_id;
1804}
1805
1806static bool __kmp_affinity_create_hwloc_map(kmp_i18n_id_t *const msg_id) {
1807 kmp_hw_t type;
1808 int hw_thread_index, sub_id;
1809 int depth;
1810 hwloc_obj_t pu, obj, root, prev;
1811 kmp_hw_t types[KMP_HW_LAST];
1812 hwloc_obj_type_t hwloc_types[KMP_HW_LAST];
1813
1814 hwloc_topology_t tp = __kmp_hwloc_topology;
1815 *msg_id = kmp_i18n_null;
1816 if (__kmp_affinity.flags.verbose) {
1817 KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
1818 }
1819
1820 if (!KMP_AFFINITY_CAPABLE()) {
1821 // Hack to try and infer the machine topology using only the data
1822 // available from hwloc on the current thread, and __kmp_xproc.
1823 KMP_ASSERT(__kmp_affinity.type == affinity_none);
1824 // hwloc only guarantees existance of PU object, so check PACKAGE and CORE
1825 hwloc_obj_t o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_PACKAGE, 0);
1826 if (o != NULL)
1827 nCoresPerPkg = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_CORE);
1828 else
1829 nCoresPerPkg = 1; // no PACKAGE found
1830 o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_CORE, 0);
1831 if (o != NULL)
1832 __kmp_nThreadsPerCore = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_PU);
1833 else
1834 __kmp_nThreadsPerCore = 1; // no CORE found
1835 if (__kmp_nThreadsPerCore == 0)
1838 if (nCoresPerPkg == 0)
1839 nCoresPerPkg = 1; // to prevent possible division by 0
1841 return true;
1842 }
1843
1844#if HWLOC_API_VERSION >= 0x00020400
1845 // Handle multiple types of cores if they exist on the system
1846 int nr_cpu_kinds = hwloc_cpukinds_get_nr(tp, 0);
1847
1848 typedef struct kmp_hwloc_cpukinds_info_t {
1849 int efficiency;
1850 kmp_hw_core_type_t core_type;
1851 hwloc_bitmap_t mask;
1852 } kmp_hwloc_cpukinds_info_t;
1853 kmp_hwloc_cpukinds_info_t *cpukinds = nullptr;
1854
1855 if (nr_cpu_kinds > 0) {
1856 unsigned nr_infos;
1857 struct hwloc_info_s *infos;
1858 cpukinds = (kmp_hwloc_cpukinds_info_t *)__kmp_allocate(
1859 sizeof(kmp_hwloc_cpukinds_info_t) * nr_cpu_kinds);
1860 for (unsigned idx = 0; idx < (unsigned)nr_cpu_kinds; ++idx) {
1861 cpukinds[idx].efficiency = -1;
1862 cpukinds[idx].core_type = KMP_HW_CORE_TYPE_UNKNOWN;
1863 cpukinds[idx].mask = hwloc_bitmap_alloc();
1864 if (hwloc_cpukinds_get_info(tp, idx, cpukinds[idx].mask,
1865 &cpukinds[idx].efficiency, &nr_infos, &infos,
1866 0) == 0) {
1867 for (unsigned i = 0; i < nr_infos; ++i) {
1868 if (__kmp_str_match("CoreType", 8, infos[i].name)) {
1869#if KMP_ARCH_X86 || KMP_ARCH_X86_64
1870 if (__kmp_str_match("IntelAtom", 9, infos[i].value)) {
1871 cpukinds[idx].core_type = KMP_HW_CORE_TYPE_ATOM;
1872 break;
1873 } else if (__kmp_str_match("IntelCore", 9, infos[i].value)) {
1874 cpukinds[idx].core_type = KMP_HW_CORE_TYPE_CORE;
1875 break;
1876 }
1877#endif
1878 }
1879 }
1880 }
1881 }
1882 }
1883#endif
1884
1885 root = hwloc_get_root_obj(tp);
1886
1887 // Figure out the depth and types in the topology
1888 depth = 0;
1889 obj = hwloc_get_pu_obj_by_os_index(tp, __kmp_affin_fullMask->begin());
1890 while (obj && obj != root) {
1891#if HWLOC_API_VERSION >= 0x00020000
1892 if (obj->memory_arity) {
1893 hwloc_obj_t memory;
1894 for (memory = obj->memory_first_child; memory;
1895 memory = hwloc_get_next_child(tp, obj, memory)) {
1896 if (memory->type == HWLOC_OBJ_NUMANODE)
1897 break;
1898 }
1899 if (memory && memory->type == HWLOC_OBJ_NUMANODE) {
1900 types[depth] = KMP_HW_NUMA;
1901 hwloc_types[depth] = memory->type;
1902 depth++;
1903 }
1904 }
1905#endif
1906 type = __kmp_hwloc_type_2_topology_type(obj);
1907 if (type != KMP_HW_UNKNOWN) {
1908 types[depth] = type;
1909 hwloc_types[depth] = obj->type;
1910 depth++;
1911 }
1912 obj = obj->parent;
1913 }
1914 KMP_ASSERT(depth > 0);
1915
1916 // Get the order for the types correct
1917 for (int i = 0, j = depth - 1; i < j; ++i, --j) {
1918 hwloc_obj_type_t hwloc_temp = hwloc_types[i];
1919 kmp_hw_t temp = types[i];
1920 types[i] = types[j];
1921 types[j] = temp;
1922 hwloc_types[i] = hwloc_types[j];
1923 hwloc_types[j] = hwloc_temp;
1924 }
1925
1926 // Allocate the data structure to be returned.
1928
1929 hw_thread_index = 0;
1930 pu = NULL;
1931 while ((pu = hwloc_get_next_obj_by_type(tp, HWLOC_OBJ_PU, pu))) {
1932 int index = depth - 1;
1933 bool included = KMP_CPU_ISSET(pu->os_index, __kmp_affin_fullMask);
1934 kmp_hw_thread_t &hw_thread = __kmp_topology->at(hw_thread_index);
1935 if (included) {
1936 hw_thread.clear();
1937 hw_thread.ids[index] = pu->logical_index;
1938 hw_thread.os_id = pu->os_index;
1939 hw_thread.original_idx = hw_thread_index;
1940 // If multiple core types, then set that attribute for the hardware thread
1941#if HWLOC_API_VERSION >= 0x00020400
1942 if (cpukinds) {
1943 int cpukind_index = -1;
1944 for (int i = 0; i < nr_cpu_kinds; ++i) {
1945 if (hwloc_bitmap_isset(cpukinds[i].mask, hw_thread.os_id)) {
1946 cpukind_index = i;
1947 break;
1948 }
1949 }
1950 if (cpukind_index >= 0) {
1951 hw_thread.attrs.set_core_type(cpukinds[cpukind_index].core_type);
1952 hw_thread.attrs.set_core_eff(cpukinds[cpukind_index].efficiency);
1953 }
1954 }
1955#endif
1956 index--;
1957 }
1958 obj = pu;
1959 prev = obj;
1960 while (obj != root && obj != NULL) {
1961 obj = obj->parent;
1962#if HWLOC_API_VERSION >= 0x00020000
1963 // NUMA Nodes are handled differently since they are not within the
1964 // parent/child structure anymore. They are separate children
1965 // of obj (memory_first_child points to first memory child)
1966 if (obj->memory_arity) {
1967 hwloc_obj_t memory;
1968 for (memory = obj->memory_first_child; memory;
1969 memory = hwloc_get_next_child(tp, obj, memory)) {
1970 if (memory->type == HWLOC_OBJ_NUMANODE)
1971 break;
1972 }
1973 if (memory && memory->type == HWLOC_OBJ_NUMANODE) {
1974 sub_id = __kmp_hwloc_get_sub_id(tp, memory, prev);
1975 if (included) {
1976 hw_thread.ids[index] = memory->logical_index;
1977 hw_thread.ids[index + 1] = sub_id;
1978 index--;
1979 }
1980 }
1981 prev = obj;
1982 }
1983#endif
1984 type = __kmp_hwloc_type_2_topology_type(obj);
1985 if (type != KMP_HW_UNKNOWN) {
1986 sub_id = __kmp_hwloc_get_sub_id(tp, obj, prev);
1987 if (included) {
1988 hw_thread.ids[index] = obj->logical_index;
1989 hw_thread.ids[index + 1] = sub_id;
1990 index--;
1991 }
1992 prev = obj;
1993 }
1994 }
1995 if (included)
1996 hw_thread_index++;
1997 }
1998
1999#if HWLOC_API_VERSION >= 0x00020400
2000 // Free the core types information
2001 if (cpukinds) {
2002 for (int idx = 0; idx < nr_cpu_kinds; ++idx)
2003 hwloc_bitmap_free(cpukinds[idx].mask);
2004 __kmp_free(cpukinds);
2005 }
2006#endif
2007 __kmp_topology->sort_ids();
2008 return true;
2009}
2010#endif // KMP_HWLOC_ENABLED
2011
2012// If we don't know how to retrieve the machine's processor topology, or
2013// encounter an error in doing so, this routine is called to form a "flat"
2014// mapping of os thread id's <-> processor id's.
2015static bool __kmp_affinity_create_flat_map(kmp_i18n_id_t *const msg_id) {
2016 *msg_id = kmp_i18n_null;
2017 int depth = 3;
2019
2020 if (__kmp_affinity.flags.verbose) {
2021 KMP_INFORM(UsingFlatOS, "KMP_AFFINITY");
2022 }
2023
2024 // Even if __kmp_affinity.type == affinity_none, this routine might still
2025 // be called to set __kmp_ncores, as well as
2026 // __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
2027 if (!KMP_AFFINITY_CAPABLE()) {
2028 KMP_ASSERT(__kmp_affinity.type == affinity_none);
2031 return true;
2032 }
2033
2034 // When affinity is off, this routine will still be called to set
2035 // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
2036 // Make sure all these vars are set correctly, and return now if affinity is
2037 // not enabled.
2040
2041 // Construct the data structure to be returned.
2043 int avail_ct = 0;
2044 int i;
2045 KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
2046 // Skip this proc if it is not included in the machine model.
2047 if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
2048 continue;
2049 }
2050 kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct);
2051 hw_thread.clear();
2052 hw_thread.os_id = i;
2053 hw_thread.original_idx = avail_ct;
2054 hw_thread.ids[0] = i;
2055 hw_thread.ids[1] = 0;
2056 hw_thread.ids[2] = 0;
2057 avail_ct++;
2058 }
2059 if (__kmp_affinity.flags.verbose) {
2060 KMP_INFORM(OSProcToPackage, "KMP_AFFINITY");
2061 }
2062 return true;
2063}
2064
2065#if KMP_GROUP_AFFINITY
2066// If multiple Windows* OS processor groups exist, we can create a 2-level
2067// topology map with the groups at level 0 and the individual procs at level 1.
2068// This facilitates letting the threads float among all procs in a group,
2069// if granularity=group (the default when there are multiple groups).
2070static bool __kmp_affinity_create_proc_group_map(kmp_i18n_id_t *const msg_id) {
2071 *msg_id = kmp_i18n_null;
2072 int depth = 3;
2074 const static size_t BITS_PER_GROUP = CHAR_BIT * sizeof(DWORD_PTR);
2075
2076 if (__kmp_affinity.flags.verbose) {
2077 KMP_INFORM(AffWindowsProcGroupMap, "KMP_AFFINITY");
2078 }
2079
2080 // If we aren't affinity capable, then use flat topology
2081 if (!KMP_AFFINITY_CAPABLE()) {
2082 KMP_ASSERT(__kmp_affinity.type == affinity_none);
2083 nPackages = __kmp_num_proc_groups;
2087 return true;
2088 }
2089
2090 // Construct the data structure to be returned.
2092 int avail_ct = 0;
2093 int i;
2094 KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
2095 // Skip this proc if it is not included in the machine model.
2096 if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
2097 continue;
2098 }
2099 kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct);
2100 hw_thread.clear();
2101 hw_thread.os_id = i;
2102 hw_thread.original_idx = avail_ct;
2103 hw_thread.ids[0] = i / BITS_PER_GROUP;
2104 hw_thread.ids[1] = hw_thread.ids[2] = i % BITS_PER_GROUP;
2105 avail_ct++;
2106 }
2107 return true;
2108}
2109#endif /* KMP_GROUP_AFFINITY */
2110
2111#if KMP_ARCH_X86 || KMP_ARCH_X86_64
2112
2113template <kmp_uint32 LSB, kmp_uint32 MSB>
2114static inline unsigned __kmp_extract_bits(kmp_uint32 v) {
2115 const kmp_uint32 SHIFT_LEFT = sizeof(kmp_uint32) * 8 - 1 - MSB;
2116 const kmp_uint32 SHIFT_RIGHT = LSB;
2117 kmp_uint32 retval = v;
2118 retval <<= SHIFT_LEFT;
2119 retval >>= (SHIFT_LEFT + SHIFT_RIGHT);
2120 return retval;
2121}
2122
2123static int __kmp_cpuid_mask_width(int count) {
2124 int r = 0;
2125
2126 while ((1 << r) < count)
2127 ++r;
2128 return r;
2129}
2130
2131class apicThreadInfo {
2132public:
2133 unsigned osId; // param to __kmp_affinity_bind_thread
2134 unsigned apicId; // from cpuid after binding
2135 unsigned maxCoresPerPkg; // ""
2136 unsigned maxThreadsPerPkg; // ""
2137 unsigned pkgId; // inferred from above values
2138 unsigned coreId; // ""
2139 unsigned threadId; // ""
2140};
2141
2142static int __kmp_affinity_cmp_apicThreadInfo_phys_id(const void *a,
2143 const void *b) {
2144 const apicThreadInfo *aa = (const apicThreadInfo *)a;
2145 const apicThreadInfo *bb = (const apicThreadInfo *)b;
2146 if (aa->pkgId < bb->pkgId)
2147 return -1;
2148 if (aa->pkgId > bb->pkgId)
2149 return 1;
2150 if (aa->coreId < bb->coreId)
2151 return -1;
2152 if (aa->coreId > bb->coreId)
2153 return 1;
2154 if (aa->threadId < bb->threadId)
2155 return -1;
2156 if (aa->threadId > bb->threadId)
2157 return 1;
2158 return 0;
2159}
2160
2161class cpuid_cache_info_t {
2162public:
2163 struct info_t {
2164 unsigned level = 0;
2165 unsigned mask = 0;
2166 bool operator==(const info_t &rhs) const {
2167 return level == rhs.level && mask == rhs.mask;
2168 }
2169 bool operator!=(const info_t &rhs) const { return !operator==(rhs); }
2170 };
2171 cpuid_cache_info_t() : depth(0) {
2172 table[MAX_CACHE_LEVEL].level = 0;
2173 table[MAX_CACHE_LEVEL].mask = 0;
2174 }
2175 size_t get_depth() const { return depth; }
2176 info_t &operator[](size_t index) { return table[index]; }
2177 const info_t &operator[](size_t index) const { return table[index]; }
2178 bool operator==(const cpuid_cache_info_t &rhs) const {
2179 if (rhs.depth != depth)
2180 return false;
2181 for (size_t i = 0; i < depth; ++i)
2182 if (table[i] != rhs.table[i])
2183 return false;
2184 return true;
2185 }
2186 bool operator!=(const cpuid_cache_info_t &rhs) const {
2187 return !operator==(rhs);
2188 }
2189 // Get cache information assocaited with L1, L2, L3 cache, etc.
2190 // If level does not exist, then return the "NULL" level (level 0)
2191 const info_t &get_level(unsigned level) const {
2192 for (size_t i = 0; i < depth; ++i) {
2193 if (table[i].level == level)
2194 return table[i];
2195 }
2196 return table[MAX_CACHE_LEVEL];
2197 }
2198
2199 static kmp_hw_t get_topology_type(unsigned level) {
2200 KMP_DEBUG_ASSERT(level >= 1 && level <= MAX_CACHE_LEVEL);
2201 switch (level) {
2202 case 1:
2203 return KMP_HW_L1;
2204 case 2:
2205 return KMP_HW_L2;
2206 case 3:
2207 return KMP_HW_L3;
2208 }
2209 return KMP_HW_UNKNOWN;
2210 }
2211 void get_leaf4_levels() {
2212 unsigned level = 0;
2213 while (depth < MAX_CACHE_LEVEL) {
2214 unsigned cache_type, max_threads_sharing;
2215 unsigned cache_level, cache_mask_width;
2216 kmp_cpuid buf2;
2217 __kmp_x86_cpuid(4, level, &buf2);
2218 cache_type = __kmp_extract_bits<0, 4>(buf2.eax);
2219 if (!cache_type)
2220 break;
2221 // Skip instruction caches
2222 if (cache_type == 2) {
2223 level++;
2224 continue;
2225 }
2226 max_threads_sharing = __kmp_extract_bits<14, 25>(buf2.eax) + 1;
2227 cache_mask_width = __kmp_cpuid_mask_width(max_threads_sharing);
2228 cache_level = __kmp_extract_bits<5, 7>(buf2.eax);
2229 table[depth].level = cache_level;
2230 table[depth].mask = ((0xffffffffu) << cache_mask_width);
2231 depth++;
2232 level++;
2233 }
2234 }
2235 static const int MAX_CACHE_LEVEL = 3;
2236
2237private:
2238 size_t depth;
2239 info_t table[MAX_CACHE_LEVEL + 1];
2240};
2241
2242// On IA-32 architecture and Intel(R) 64 architecture, we attempt to use
2243// an algorithm which cycles through the available os threads, setting
2244// the current thread's affinity mask to that thread, and then retrieves
2245// the Apic Id for each thread context using the cpuid instruction.
2246static bool __kmp_affinity_create_apicid_map(kmp_i18n_id_t *const msg_id) {
2247 kmp_cpuid buf;
2248 *msg_id = kmp_i18n_null;
2249
2250 if (__kmp_affinity.flags.verbose) {
2251 KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(DecodingLegacyAPIC));
2252 }
2253
2254 // Check if cpuid leaf 4 is supported.
2255 __kmp_x86_cpuid(0, 0, &buf);
2256 if (buf.eax < 4) {
2257 *msg_id = kmp_i18n_str_NoLeaf4Support;
2258 return false;
2259 }
2260
2261 // The algorithm used starts by setting the affinity to each available thread
2262 // and retrieving info from the cpuid instruction, so if we are not capable of
2263 // calling __kmp_get_system_affinity() and _kmp_get_system_affinity(), then we
2264 // need to do something else - use the defaults that we calculated from
2265 // issuing cpuid without binding to each proc.
2266 if (!KMP_AFFINITY_CAPABLE()) {
2267 // Hack to try and infer the machine topology using only the data
2268 // available from cpuid on the current thread, and __kmp_xproc.
2269 KMP_ASSERT(__kmp_affinity.type == affinity_none);
2270
2271 // Get an upper bound on the number of threads per package using cpuid(1).
2272 // On some OS/chps combinations where HT is supported by the chip but is
2273 // disabled, this value will be 2 on a single core chip. Usually, it will be
2274 // 2 if HT is enabled and 1 if HT is disabled.
2275 __kmp_x86_cpuid(1, 0, &buf);
2276 int maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
2277 if (maxThreadsPerPkg == 0) {
2278 maxThreadsPerPkg = 1;
2279 }
2280
2281 // The num cores per pkg comes from cpuid(4). 1 must be added to the encoded
2282 // value.
2283 //
2284 // The author of cpu_count.cpp treated this only an upper bound on the
2285 // number of cores, but I haven't seen any cases where it was greater than
2286 // the actual number of cores, so we will treat it as exact in this block of
2287 // code.
2288 //
2289 // First, we need to check if cpuid(4) is supported on this chip. To see if
2290 // cpuid(n) is supported, issue cpuid(0) and check if eax has the value n or
2291 // greater.
2292 __kmp_x86_cpuid(0, 0, &buf);
2293 if (buf.eax >= 4) {
2294 __kmp_x86_cpuid(4, 0, &buf);
2295 nCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
2296 } else {
2297 nCoresPerPkg = 1;
2298 }
2299
2300 // There is no way to reliably tell if HT is enabled without issuing the
2301 // cpuid instruction from every thread, can correlating the cpuid info, so
2302 // if the machine is not affinity capable, we assume that HT is off. We have
2303 // seen quite a few machines where maxThreadsPerPkg is 2, yet the machine
2304 // does not support HT.
2305 //
2306 // - Older OSes are usually found on machines with older chips, which do not
2307 // support HT.
2308 // - The performance penalty for mistakenly identifying a machine as HT when
2309 // it isn't (which results in blocktime being incorrectly set to 0) is
2310 // greater than the penalty when for mistakenly identifying a machine as
2311 // being 1 thread/core when it is really HT enabled (which results in
2312 // blocktime being incorrectly set to a positive value).
2316 return true;
2317 }
2318
2319 // From here on, we can assume that it is safe to call
2320 // __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if
2321 // __kmp_affinity.type = affinity_none.
2322
2323 // Save the affinity mask for the current thread.
2324 kmp_affinity_raii_t previous_affinity;
2325
2326 // Run through each of the available contexts, binding the current thread
2327 // to it, and obtaining the pertinent information using the cpuid instr.
2328 //
2329 // The relevant information is:
2330 // - Apic Id: Bits 24:31 of ebx after issuing cpuid(1) - each thread context
2331 // has a uniqie Apic Id, which is of the form pkg# : core# : thread#.
2332 // - Max Threads Per Pkg: Bits 16:23 of ebx after issuing cpuid(1). The value
2333 // of this field determines the width of the core# + thread# fields in the
2334 // Apic Id. It is also an upper bound on the number of threads per
2335 // package, but it has been verified that situations happen were it is not
2336 // exact. In particular, on certain OS/chip combinations where Intel(R)
2337 // Hyper-Threading Technology is supported by the chip but has been
2338 // disabled, the value of this field will be 2 (for a single core chip).
2339 // On other OS/chip combinations supporting Intel(R) Hyper-Threading
2340 // Technology, the value of this field will be 1 when Intel(R)
2341 // Hyper-Threading Technology is disabled and 2 when it is enabled.
2342 // - Max Cores Per Pkg: Bits 26:31 of eax after issuing cpuid(4). The value
2343 // of this field (+1) determines the width of the core# field in the Apic
2344 // Id. The comments in "cpucount.cpp" say that this value is an upper
2345 // bound, but the IA-32 architecture manual says that it is exactly the
2346 // number of cores per package, and I haven't seen any case where it
2347 // wasn't.
2348 //
2349 // From this information, deduce the package Id, core Id, and thread Id,
2350 // and set the corresponding fields in the apicThreadInfo struct.
2351 unsigned i;
2352 apicThreadInfo *threadInfo = (apicThreadInfo *)__kmp_allocate(
2353 __kmp_avail_proc * sizeof(apicThreadInfo));
2354 unsigned nApics = 0;
2355 KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
2356 // Skip this proc if it is not included in the machine model.
2357 if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
2358 continue;
2359 }
2360 KMP_DEBUG_ASSERT((int)nApics < __kmp_avail_proc);
2361
2362 __kmp_affinity_dispatch->bind_thread(i);
2363 threadInfo[nApics].osId = i;
2364
2365 // The apic id and max threads per pkg come from cpuid(1).
2366 __kmp_x86_cpuid(1, 0, &buf);
2367 if (((buf.edx >> 9) & 1) == 0) {
2368 __kmp_free(threadInfo);
2369 *msg_id = kmp_i18n_str_ApicNotPresent;
2370 return false;
2371 }
2372 threadInfo[nApics].apicId = (buf.ebx >> 24) & 0xff;
2373 threadInfo[nApics].maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
2374 if (threadInfo[nApics].maxThreadsPerPkg == 0) {
2375 threadInfo[nApics].maxThreadsPerPkg = 1;
2376 }
2377
2378 // Max cores per pkg comes from cpuid(4). 1 must be added to the encoded
2379 // value.
2380 //
2381 // First, we need to check if cpuid(4) is supported on this chip. To see if
2382 // cpuid(n) is supported, issue cpuid(0) and check if eax has the value n
2383 // or greater.
2384 __kmp_x86_cpuid(0, 0, &buf);
2385 if (buf.eax >= 4) {
2386 __kmp_x86_cpuid(4, 0, &buf);
2387 threadInfo[nApics].maxCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
2388 } else {
2389 threadInfo[nApics].maxCoresPerPkg = 1;
2390 }
2391
2392 // Infer the pkgId / coreId / threadId using only the info obtained locally.
2393 int widthCT = __kmp_cpuid_mask_width(threadInfo[nApics].maxThreadsPerPkg);
2394 threadInfo[nApics].pkgId = threadInfo[nApics].apicId >> widthCT;
2395
2396 int widthC = __kmp_cpuid_mask_width(threadInfo[nApics].maxCoresPerPkg);
2397 int widthT = widthCT - widthC;
2398 if (widthT < 0) {
2399 // I've never seen this one happen, but I suppose it could, if the cpuid
2400 // instruction on a chip was really screwed up. Make sure to restore the
2401 // affinity mask before the tail call.
2402 __kmp_free(threadInfo);
2403 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
2404 return false;
2405 }
2406
2407 int maskC = (1 << widthC) - 1;
2408 threadInfo[nApics].coreId = (threadInfo[nApics].apicId >> widthT) & maskC;
2409
2410 int maskT = (1 << widthT) - 1;
2411 threadInfo[nApics].threadId = threadInfo[nApics].apicId & maskT;
2412
2413 nApics++;
2414 }
2415
2416 // We've collected all the info we need.
2417 // Restore the old affinity mask for this thread.
2418 previous_affinity.restore();
2419
2420 // Sort the threadInfo table by physical Id.
2421 qsort(threadInfo, nApics, sizeof(*threadInfo),
2422 __kmp_affinity_cmp_apicThreadInfo_phys_id);
2423
2424 // The table is now sorted by pkgId / coreId / threadId, but we really don't
2425 // know the radix of any of the fields. pkgId's may be sparsely assigned among
2426 // the chips on a system. Although coreId's are usually assigned
2427 // [0 .. coresPerPkg-1] and threadId's are usually assigned
2428 // [0..threadsPerCore-1], we don't want to make any such assumptions.
2429 //
2430 // For that matter, we don't know what coresPerPkg and threadsPerCore (or the
2431 // total # packages) are at this point - we want to determine that now. We
2432 // only have an upper bound on the first two figures.
2433 //
2434 // We also perform a consistency check at this point: the values returned by
2435 // the cpuid instruction for any thread bound to a given package had better
2436 // return the same info for maxThreadsPerPkg and maxCoresPerPkg.
2437 nPackages = 1;
2438 nCoresPerPkg = 1;
2440 unsigned nCores = 1;
2441
2442 unsigned pkgCt = 1; // to determine radii
2443 unsigned lastPkgId = threadInfo[0].pkgId;
2444 unsigned coreCt = 1;
2445 unsigned lastCoreId = threadInfo[0].coreId;
2446 unsigned threadCt = 1;
2447 unsigned lastThreadId = threadInfo[0].threadId;
2448
2449 // intra-pkg consist checks
2450 unsigned prevMaxCoresPerPkg = threadInfo[0].maxCoresPerPkg;
2451 unsigned prevMaxThreadsPerPkg = threadInfo[0].maxThreadsPerPkg;
2452
2453 for (i = 1; i < nApics; i++) {
2454 if (threadInfo[i].pkgId != lastPkgId) {
2455 nCores++;
2456 pkgCt++;
2457 lastPkgId = threadInfo[i].pkgId;
2458 if ((int)coreCt > nCoresPerPkg)
2459 nCoresPerPkg = coreCt;
2460 coreCt = 1;
2461 lastCoreId = threadInfo[i].coreId;
2462 if ((int)threadCt > __kmp_nThreadsPerCore)
2463 __kmp_nThreadsPerCore = threadCt;
2464 threadCt = 1;
2465 lastThreadId = threadInfo[i].threadId;
2466
2467 // This is a different package, so go on to the next iteration without
2468 // doing any consistency checks. Reset the consistency check vars, though.
2469 prevMaxCoresPerPkg = threadInfo[i].maxCoresPerPkg;
2470 prevMaxThreadsPerPkg = threadInfo[i].maxThreadsPerPkg;
2471 continue;
2472 }
2473
2474 if (threadInfo[i].coreId != lastCoreId) {
2475 nCores++;
2476 coreCt++;
2477 lastCoreId = threadInfo[i].coreId;
2478 if ((int)threadCt > __kmp_nThreadsPerCore)
2479 __kmp_nThreadsPerCore = threadCt;
2480 threadCt = 1;
2481 lastThreadId = threadInfo[i].threadId;
2482 } else if (threadInfo[i].threadId != lastThreadId) {
2483 threadCt++;
2484 lastThreadId = threadInfo[i].threadId;
2485 } else {
2486 __kmp_free(threadInfo);
2487 *msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;
2488 return false;
2489 }
2490
2491 // Check to make certain that the maxCoresPerPkg and maxThreadsPerPkg
2492 // fields agree between all the threads bounds to a given package.
2493 if ((prevMaxCoresPerPkg != threadInfo[i].maxCoresPerPkg) ||
2494 (prevMaxThreadsPerPkg != threadInfo[i].maxThreadsPerPkg)) {
2495 __kmp_free(threadInfo);
2496 *msg_id = kmp_i18n_str_InconsistentCpuidInfo;
2497 return false;
2498 }
2499 }
2500 // When affinity is off, this routine will still be called to set
2501 // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
2502 // Make sure all these vars are set correctly
2503 nPackages = pkgCt;
2504 if ((int)coreCt > nCoresPerPkg)
2505 nCoresPerPkg = coreCt;
2506 if ((int)threadCt > __kmp_nThreadsPerCore)
2507 __kmp_nThreadsPerCore = threadCt;
2508 __kmp_ncores = nCores;
2509 KMP_DEBUG_ASSERT(nApics == (unsigned)__kmp_avail_proc);
2510
2511 // Now that we've determined the number of packages, the number of cores per
2512 // package, and the number of threads per core, we can construct the data
2513 // structure that is to be returned.
2514 int idx = 0;
2515 int pkgLevel = 0;
2516 int coreLevel = 1;
2517 int threadLevel = 2;
2518 //(__kmp_nThreadsPerCore <= 1) ? -1 : ((coreLevel >= 0) ? 2 : 1);
2519 int depth = (pkgLevel >= 0) + (coreLevel >= 0) + (threadLevel >= 0);
2520 kmp_hw_t types[3];
2521 if (pkgLevel >= 0)
2522 types[idx++] = KMP_HW_SOCKET;
2523 if (coreLevel >= 0)
2524 types[idx++] = KMP_HW_CORE;
2525 if (threadLevel >= 0)
2526 types[idx++] = KMP_HW_THREAD;
2527
2528 KMP_ASSERT(depth > 0);
2529 __kmp_topology = kmp_topology_t::allocate(nApics, depth, types);
2530
2531 for (i = 0; i < nApics; ++i) {
2532 idx = 0;
2533 unsigned os = threadInfo[i].osId;
2534 kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
2535 hw_thread.clear();
2536
2537 if (pkgLevel >= 0) {
2538 hw_thread.ids[idx++] = threadInfo[i].pkgId;
2539 }
2540 if (coreLevel >= 0) {
2541 hw_thread.ids[idx++] = threadInfo[i].coreId;
2542 }
2543 if (threadLevel >= 0) {
2544 hw_thread.ids[idx++] = threadInfo[i].threadId;
2545 }
2546 hw_thread.os_id = os;
2547 hw_thread.original_idx = i;
2548 }
2549
2550 __kmp_free(threadInfo);
2551 __kmp_topology->sort_ids();
2552 if (!__kmp_topology->check_ids()) {
2554 __kmp_topology = nullptr;
2555 *msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;
2556 return false;
2557 }
2558 return true;
2559}
2560
2561// Hybrid cpu detection using CPUID.1A
2562// Thread should be pinned to processor already
2563static void __kmp_get_hybrid_info(kmp_hw_core_type_t *type, int *efficiency,
2564 unsigned *native_model_id) {
2565 kmp_cpuid buf;
2566 __kmp_x86_cpuid(0x1a, 0, &buf);
2567 *type = (kmp_hw_core_type_t)__kmp_extract_bits<24, 31>(buf.eax);
2568 switch (*type) {
2569 case KMP_HW_CORE_TYPE_ATOM:
2570 *efficiency = 0;
2571 break;
2572 case KMP_HW_CORE_TYPE_CORE:
2573 *efficiency = 1;
2574 break;
2575 default:
2576 *efficiency = 0;
2577 }
2578 *native_model_id = __kmp_extract_bits<0, 23>(buf.eax);
2579}
2580
2581// Intel(R) microarchitecture code name Nehalem, Dunnington and later
2582// architectures support a newer interface for specifying the x2APIC Ids,
2583// based on CPUID.B or CPUID.1F
2584/*
2585 * CPUID.B or 1F, Input ECX (sub leaf # aka level number)
2586 Bits Bits Bits Bits
2587 31-16 15-8 7-4 4-0
2588---+-----------+--------------+-------------+-----------------+
2589EAX| reserved | reserved | reserved | Bits to Shift |
2590---+-----------|--------------+-------------+-----------------|
2591EBX| reserved | Num logical processors at level (16 bits) |
2592---+-----------|--------------+-------------------------------|
2593ECX| reserved | Level Type | Level Number (8 bits) |
2594---+-----------+--------------+-------------------------------|
2595EDX| X2APIC ID (32 bits) |
2596---+----------------------------------------------------------+
2597*/
2598
2599enum {
2600 INTEL_LEVEL_TYPE_INVALID = 0, // Package level
2601 INTEL_LEVEL_TYPE_SMT = 1,
2602 INTEL_LEVEL_TYPE_CORE = 2,
2603 INTEL_LEVEL_TYPE_MODULE = 3,
2604 INTEL_LEVEL_TYPE_TILE = 4,
2605 INTEL_LEVEL_TYPE_DIE = 5,
2606 INTEL_LEVEL_TYPE_LAST = 6,
2607};
2608KMP_BUILD_ASSERT(INTEL_LEVEL_TYPE_LAST < sizeof(unsigned) * CHAR_BIT);
2609#define KMP_LEAF_1F_KNOWN_LEVELS ((1u << INTEL_LEVEL_TYPE_LAST) - 1u)
2610
2611static kmp_hw_t __kmp_intel_type_2_topology_type(int intel_type) {
2612 switch (intel_type) {
2613 case INTEL_LEVEL_TYPE_INVALID:
2614 return KMP_HW_SOCKET;
2615 case INTEL_LEVEL_TYPE_SMT:
2616 return KMP_HW_THREAD;
2617 case INTEL_LEVEL_TYPE_CORE:
2618 return KMP_HW_CORE;
2619 case INTEL_LEVEL_TYPE_TILE:
2620 return KMP_HW_TILE;
2621 case INTEL_LEVEL_TYPE_MODULE:
2622 return KMP_HW_MODULE;
2623 case INTEL_LEVEL_TYPE_DIE:
2624 return KMP_HW_DIE;
2625 }
2626 return KMP_HW_UNKNOWN;
2627}
2628
2629static int __kmp_topology_type_2_intel_type(kmp_hw_t type) {
2630 switch (type) {
2631 case KMP_HW_SOCKET:
2632 return INTEL_LEVEL_TYPE_INVALID;
2633 case KMP_HW_THREAD:
2634 return INTEL_LEVEL_TYPE_SMT;
2635 case KMP_HW_CORE:
2636 return INTEL_LEVEL_TYPE_CORE;
2637 case KMP_HW_TILE:
2638 return INTEL_LEVEL_TYPE_TILE;
2639 case KMP_HW_MODULE:
2640 return INTEL_LEVEL_TYPE_MODULE;
2641 case KMP_HW_DIE:
2642 return INTEL_LEVEL_TYPE_DIE;
2643 default:
2644 return INTEL_LEVEL_TYPE_INVALID;
2645 }
2646}
2647
2648struct cpuid_level_info_t {
2649 unsigned level_type, mask, mask_width, nitems, cache_mask;
2650};
2651
2652class cpuid_topo_desc_t {
2653 unsigned desc = 0;
2654
2655public:
2656 void clear() { desc = 0; }
2657 bool contains(int intel_type) const {
2658 KMP_DEBUG_ASSERT(intel_type >= 0 && intel_type < INTEL_LEVEL_TYPE_LAST);
2659 if ((1u << intel_type) & desc)
2660 return true;
2661 return false;
2662 }
2663 bool contains_topology_type(kmp_hw_t type) const {
2665 int intel_type = __kmp_topology_type_2_intel_type(type);
2666 return contains(intel_type);
2667 }
2668 bool contains(cpuid_topo_desc_t rhs) const {
2669 return ((desc | rhs.desc) == desc);
2670 }
2671 void add(int intel_type) { desc |= (1u << intel_type); }
2672 void add(cpuid_topo_desc_t rhs) { desc |= rhs.desc; }
2673};
2674
2675struct cpuid_proc_info_t {
2676 // Topology info
2677 int os_id;
2678 unsigned apic_id;
2679 unsigned depth;
2680 // Hybrid info
2681 unsigned native_model_id;
2682 int efficiency;
2684 cpuid_topo_desc_t description;
2685
2686 cpuid_level_info_t levels[INTEL_LEVEL_TYPE_LAST];
2687};
2688
2689// This function takes the topology leaf, an info pointer to store the levels
2690// detected, and writable descriptors for the total topology.
2691// Returns whether total types, depth, or description were modified.
2692static bool __kmp_x2apicid_get_levels(int leaf, cpuid_proc_info_t *info,
2693 kmp_hw_t total_types[KMP_HW_LAST],
2694 int *total_depth,
2695 cpuid_topo_desc_t *total_description) {
2696 unsigned level, levels_index;
2697 unsigned level_type, mask_width, nitems;
2698 kmp_cpuid buf;
2699 cpuid_level_info_t(&levels)[INTEL_LEVEL_TYPE_LAST] = info->levels;
2700 bool retval = false;
2701
2702 // New algorithm has known topology layers act as highest unknown topology
2703 // layers when unknown topology layers exist.
2704 // e.g., Suppose layers were SMT <X> CORE <Y> <Z> PACKAGE, where <X> <Y> <Z>
2705 // are unknown topology layers, Then SMT will take the characteristics of
2706 // (SMT x <X>) and CORE will take the characteristics of (CORE x <Y> x <Z>).
2707 // This eliminates unknown portions of the topology while still keeping the
2708 // correct structure.
2709 level = levels_index = 0;
2710 do {
2711 __kmp_x86_cpuid(leaf, level, &buf);
2712 level_type = __kmp_extract_bits<8, 15>(buf.ecx);
2713 mask_width = __kmp_extract_bits<0, 4>(buf.eax);
2714 nitems = __kmp_extract_bits<0, 15>(buf.ebx);
2715 if (level_type != INTEL_LEVEL_TYPE_INVALID && nitems == 0) {
2716 info->depth = 0;
2717 return retval;
2718 }
2719
2720 if (KMP_LEAF_1F_KNOWN_LEVELS & (1u << level_type)) {
2721 // Add a new level to the topology
2722 KMP_ASSERT(levels_index < INTEL_LEVEL_TYPE_LAST);
2723 levels[levels_index].level_type = level_type;
2724 levels[levels_index].mask_width = mask_width;
2725 levels[levels_index].nitems = nitems;
2726 levels_index++;
2727 } else {
2728 // If it is an unknown level, then logically move the previous layer up
2729 if (levels_index > 0) {
2730 levels[levels_index - 1].mask_width = mask_width;
2731 levels[levels_index - 1].nitems = nitems;
2732 }
2733 }
2734 level++;
2735 } while (level_type != INTEL_LEVEL_TYPE_INVALID);
2736 KMP_ASSERT(levels_index <= INTEL_LEVEL_TYPE_LAST);
2737 info->description.clear();
2738 info->depth = levels_index;
2739
2740 // If types, depth, and total_description are uninitialized,
2741 // then initialize them now
2742 if (*total_depth == 0) {
2743 *total_depth = info->depth;
2744 total_description->clear();
2745 for (int i = *total_depth - 1, j = 0; i >= 0; --i, ++j) {
2746 total_types[j] =
2747 __kmp_intel_type_2_topology_type(info->levels[i].level_type);
2748 total_description->add(info->levels[i].level_type);
2749 }
2750 retval = true;
2751 }
2752
2753 // Ensure the INTEL_LEVEL_TYPE_INVALID (Socket) layer isn't first
2754 if (levels_index == 0 || levels[0].level_type == INTEL_LEVEL_TYPE_INVALID)
2755 return 0;
2756
2757 // Set the masks to & with apicid
2758 for (unsigned i = 0; i < levels_index; ++i) {
2759 if (levels[i].level_type != INTEL_LEVEL_TYPE_INVALID) {
2760 levels[i].mask = ~((0xffffffffu) << levels[i].mask_width);
2761 levels[i].cache_mask = (0xffffffffu) << levels[i].mask_width;
2762 for (unsigned j = 0; j < i; ++j)
2763 levels[i].mask ^= levels[j].mask;
2764 } else {
2765 KMP_DEBUG_ASSERT(i > 0);
2766 levels[i].mask = (0xffffffffu) << levels[i - 1].mask_width;
2767 levels[i].cache_mask = 0;
2768 }
2769 info->description.add(info->levels[i].level_type);
2770 }
2771
2772 // If this processor has level type not on other processors, then make
2773 // sure to include it in total types, depth, and description.
2774 // One assumption here is that the first type, i.e. socket, is known.
2775 // Another assumption is that types array is always large enough to fit any
2776 // new layers since its length is KMP_HW_LAST.
2777 if (!total_description->contains(info->description)) {
2778 for (int i = info->depth - 1, j = 0; i >= 0; --i, ++j) {
2779 // If this level is known already, then skip it.
2780 if (total_description->contains(levels[i].level_type))
2781 continue;
2782 // Unknown level, insert before last known level
2783 kmp_hw_t curr_type =
2784 __kmp_intel_type_2_topology_type(levels[i].level_type);
2785 KMP_ASSERT(j != 0 && "Bad APIC Id information");
2786 // Move over all known levels to make room for new level
2787 for (int k = info->depth - 1; k >= j; --k) {
2789 total_types[k + 1] = total_types[k];
2790 }
2791 // Insert new level
2792 total_types[j] = curr_type;
2793 (*total_depth)++;
2794 }
2795 total_description->add(info->description);
2796 retval = true;
2797 }
2798 return retval;
2799}
2800
2801static bool __kmp_affinity_create_x2apicid_map(kmp_i18n_id_t *const msg_id) {
2802
2803 kmp_hw_t types[INTEL_LEVEL_TYPE_LAST];
2804 kmp_cpuid buf;
2805 int topology_leaf, highest_leaf;
2806 int num_leaves;
2807 int depth = 0;
2808 cpuid_topo_desc_t total_description;
2809 static int leaves[] = {0, 0};
2810
2811 // If affinity is disabled, __kmp_avail_proc may be zero
2812 int ninfos = (__kmp_avail_proc > 0 ? __kmp_avail_proc : 1);
2813 cpuid_proc_info_t *proc_info = (cpuid_proc_info_t *)__kmp_allocate(
2814 (sizeof(cpuid_proc_info_t) + sizeof(cpuid_cache_info_t)) * ninfos);
2815 cpuid_cache_info_t *cache_info = (cpuid_cache_info_t *)(proc_info + ninfos);
2816
2817 kmp_i18n_id_t leaf_message_id;
2818
2819 *msg_id = kmp_i18n_null;
2820 if (__kmp_affinity.flags.verbose) {
2821 KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(Decodingx2APIC));
2822 }
2823
2824 // Get the highest cpuid leaf supported
2825 __kmp_x86_cpuid(0, 0, &buf);
2826 highest_leaf = buf.eax;
2827
2828 // If a specific topology method was requested, only allow that specific leaf
2829 // otherwise, try both leaves 31 and 11 in that order
2830 num_leaves = 0;
2831 if (__kmp_affinity_top_method == affinity_top_method_x2apicid) {
2832 num_leaves = 1;
2833 leaves[0] = 11;
2834 leaf_message_id = kmp_i18n_str_NoLeaf11Support;
2835 } else if (__kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {
2836 num_leaves = 1;
2837 leaves[0] = 31;
2838 leaf_message_id = kmp_i18n_str_NoLeaf31Support;
2839 } else {
2840 num_leaves = 2;
2841 leaves[0] = 31;
2842 leaves[1] = 11;
2843 leaf_message_id = kmp_i18n_str_NoLeaf11Support;
2844 }
2845
2846 // Check to see if cpuid leaf 31 or 11 is supported.
2848 topology_leaf = -1;
2849 for (int i = 0; i < num_leaves; ++i) {
2850 int leaf = leaves[i];
2851 if (highest_leaf < leaf)
2852 continue;
2853 __kmp_x86_cpuid(leaf, 0, &buf);
2854 if (buf.ebx == 0)
2855 continue;
2856 topology_leaf = leaf;
2857 __kmp_x2apicid_get_levels(leaf, &proc_info[0], types, &depth,
2858 &total_description);
2859 if (depth == 0)
2860 continue;
2861 break;
2862 }
2863 if (topology_leaf == -1 || depth == 0) {
2864 *msg_id = leaf_message_id;
2865 __kmp_free(proc_info);
2866 return false;
2867 }
2868 KMP_ASSERT(depth <= INTEL_LEVEL_TYPE_LAST);
2869
2870 // The algorithm used starts by setting the affinity to each available thread
2871 // and retrieving info from the cpuid instruction, so if we are not capable of
2872 // calling __kmp_get_system_affinity() and __kmp_get_system_affinity(), then
2873 // we need to do something else - use the defaults that we calculated from
2874 // issuing cpuid without binding to each proc.
2875 if (!KMP_AFFINITY_CAPABLE()) {
2876 // Hack to try and infer the machine topology using only the data
2877 // available from cpuid on the current thread, and __kmp_xproc.
2878 KMP_ASSERT(__kmp_affinity.type == affinity_none);
2879 for (int i = 0; i < depth; ++i) {
2880 if (proc_info[0].levels[i].level_type == INTEL_LEVEL_TYPE_SMT) {
2881 __kmp_nThreadsPerCore = proc_info[0].levels[i].nitems;
2882 } else if (proc_info[0].levels[i].level_type == INTEL_LEVEL_TYPE_CORE) {
2883 nCoresPerPkg = proc_info[0].levels[i].nitems;
2884 }
2885 }
2888 __kmp_free(proc_info);
2889 return true;
2890 }
2891
2892 // From here on, we can assume that it is safe to call
2893 // __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if
2894 // __kmp_affinity.type = affinity_none.
2895
2896 // Save the affinity mask for the current thread.
2897 kmp_affinity_raii_t previous_affinity;
2898
2899 // Run through each of the available contexts, binding the current thread
2900 // to it, and obtaining the pertinent information using the cpuid instr.
2901 unsigned int proc;
2902 int hw_thread_index = 0;
2903 bool uniform_caches = true;
2904
2905 KMP_CPU_SET_ITERATE(proc, __kmp_affin_fullMask) {
2906 // Skip this proc if it is not included in the machine model.
2907 if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
2908 continue;
2909 }
2910 KMP_DEBUG_ASSERT(hw_thread_index < __kmp_avail_proc);
2911
2912 // Gather topology information
2913 __kmp_affinity_dispatch->bind_thread(proc);
2914 __kmp_x86_cpuid(topology_leaf, 0, &buf);
2915 proc_info[hw_thread_index].os_id = proc;
2916 proc_info[hw_thread_index].apic_id = buf.edx;
2917 __kmp_x2apicid_get_levels(topology_leaf, &proc_info[hw_thread_index], types,
2918 &depth, &total_description);
2919 if (proc_info[hw_thread_index].depth == 0) {
2920 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
2921 __kmp_free(proc_info);
2922 return false;
2923 }
2924 // Gather cache information and insert afterwards
2925 cache_info[hw_thread_index].get_leaf4_levels();
2926 if (uniform_caches && hw_thread_index > 0)
2927 if (cache_info[0] != cache_info[hw_thread_index])
2928 uniform_caches = false;
2929 // Hybrid information
2930 if (__kmp_is_hybrid_cpu() && highest_leaf >= 0x1a) {
2931 __kmp_get_hybrid_info(&proc_info[hw_thread_index].type,
2932 &proc_info[hw_thread_index].efficiency,
2933 &proc_info[hw_thread_index].native_model_id);
2934 }
2935 hw_thread_index++;
2936 }
2937 KMP_ASSERT(hw_thread_index > 0);
2938 previous_affinity.restore();
2939
2940 // Allocate the data structure to be returned.
2942
2943 // Create topology Ids and hybrid types in __kmp_topology
2944 for (int i = 0; i < __kmp_topology->get_num_hw_threads(); ++i) {
2945 kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
2946 hw_thread.clear();
2947 hw_thread.os_id = proc_info[i].os_id;
2948 hw_thread.original_idx = i;
2949 unsigned apic_id = proc_info[i].apic_id;
2950 // Put in topology information
2951 for (int j = 0, idx = depth - 1; j < depth; ++j, --idx) {
2952 if (!(proc_info[i].description.contains_topology_type(
2953 __kmp_topology->get_type(j)))) {
2954 hw_thread.ids[idx] = kmp_hw_thread_t::UNKNOWN_ID;
2955 } else {
2956 hw_thread.ids[idx] = apic_id & proc_info[i].levels[j].mask;
2957 if (j > 0) {
2958 hw_thread.ids[idx] >>= proc_info[i].levels[j - 1].mask_width;
2959 }
2960 }
2961 }
2962 hw_thread.attrs.set_core_type(proc_info[i].type);
2963 hw_thread.attrs.set_core_eff(proc_info[i].efficiency);
2964 }
2965
2966 __kmp_topology->sort_ids();
2967
2968 // Change Ids to logical Ids
2969 for (int j = 0; j < depth - 1; ++j) {
2970 int new_id = 0;
2971 int prev_id = __kmp_topology->at(0).ids[j];
2972 int curr_id = __kmp_topology->at(0).ids[j + 1];
2973 __kmp_topology->at(0).ids[j + 1] = new_id;
2974 for (int i = 1; i < __kmp_topology->get_num_hw_threads(); ++i) {
2975 kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
2976 if (hw_thread.ids[j] == prev_id && hw_thread.ids[j + 1] == curr_id) {
2977 hw_thread.ids[j + 1] = new_id;
2978 } else if (hw_thread.ids[j] == prev_id &&
2979 hw_thread.ids[j + 1] != curr_id) {
2980 curr_id = hw_thread.ids[j + 1];
2981 hw_thread.ids[j + 1] = ++new_id;
2982 } else {
2983 prev_id = hw_thread.ids[j];
2984 curr_id = hw_thread.ids[j + 1];
2985 hw_thread.ids[j + 1] = ++new_id;
2986 }
2987 }
2988 }
2989
2990 // First check for easy cache placement. This occurs when caches are
2991 // equivalent to a layer in the CPUID leaf 0xb or 0x1f topology.
2992 if (uniform_caches) {
2993 for (size_t i = 0; i < cache_info[0].get_depth(); ++i) {
2994 unsigned cache_mask = cache_info[0][i].mask;
2995 unsigned cache_level = cache_info[0][i].level;
2996 KMP_ASSERT(cache_level <= cpuid_cache_info_t::MAX_CACHE_LEVEL);
2997 kmp_hw_t cache_type = cpuid_cache_info_t::get_topology_type(cache_level);
2998 __kmp_topology->set_equivalent_type(cache_type, cache_type);
2999 for (int j = 0; j < depth; ++j) {
3000 unsigned hw_cache_mask = proc_info[0].levels[j].cache_mask;
3001 if (hw_cache_mask == cache_mask && j < depth - 1) {
3002 kmp_hw_t type = __kmp_intel_type_2_topology_type(
3003 proc_info[0].levels[j + 1].level_type);
3004 __kmp_topology->set_equivalent_type(cache_type, type);
3005 }
3006 }
3007 }
3008 } else {
3009 // If caches are non-uniform, then record which caches exist.
3010 for (int i = 0; i < __kmp_topology->get_num_hw_threads(); ++i) {
3011 for (size_t j = 0; j < cache_info[i].get_depth(); ++j) {
3012 unsigned cache_level = cache_info[i][j].level;
3013 kmp_hw_t cache_type =
3014 cpuid_cache_info_t::get_topology_type(cache_level);
3015 if (__kmp_topology->get_equivalent_type(cache_type) == KMP_HW_UNKNOWN)
3016 __kmp_topology->set_equivalent_type(cache_type, cache_type);
3017 }
3018 }
3019 }
3020
3021 // See if any cache level needs to be added manually through cache Ids
3022 bool unresolved_cache_levels = false;
3023 for (unsigned level = 1; level <= cpuid_cache_info_t::MAX_CACHE_LEVEL;
3024 ++level) {
3025 kmp_hw_t cache_type = cpuid_cache_info_t::get_topology_type(level);
3026 // This also filters out caches which may not be in the topology
3027 // since the equivalent type might be KMP_HW_UNKNOWN.
3028 if (__kmp_topology->get_equivalent_type(cache_type) == cache_type) {
3029 unresolved_cache_levels = true;
3030 break;
3031 }
3032 }
3033
3034 // Insert unresolved cache layers into machine topology using cache Ids
3035 if (unresolved_cache_levels) {
3036 int num_hw_threads = __kmp_topology->get_num_hw_threads();
3037 int *ids = (int *)__kmp_allocate(sizeof(int) * num_hw_threads);
3038 for (unsigned l = 1; l <= cpuid_cache_info_t::MAX_CACHE_LEVEL; ++l) {
3039 kmp_hw_t cache_type = cpuid_cache_info_t::get_topology_type(l);
3040 if (__kmp_topology->get_equivalent_type(cache_type) != cache_type)
3041 continue;
3042 for (int i = 0; i < num_hw_threads; ++i) {
3043 int original_idx = __kmp_topology->at(i).original_idx;
3045 const cpuid_cache_info_t::info_t &info =
3046 cache_info[original_idx].get_level(l);
3047 // if cache level not in topology for this processor, then skip
3048 if (info.level == 0)
3049 continue;
3050 ids[i] = info.mask & proc_info[original_idx].apic_id;
3051 }
3052 __kmp_topology->insert_layer(cache_type, ids);
3053 }
3054 }
3055
3056 if (!__kmp_topology->check_ids()) {
3058 __kmp_topology = nullptr;
3059 *msg_id = kmp_i18n_str_x2ApicIDsNotUnique;
3060 __kmp_free(proc_info);
3061 return false;
3062 }
3063 __kmp_free(proc_info);
3064 return true;
3065}
3066#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
3067
3068#define osIdIndex 0
3069#define threadIdIndex 1
3070#define coreIdIndex 2
3071#define pkgIdIndex 3
3072#define nodeIdIndex 4
3073
3074typedef unsigned *ProcCpuInfo;
3075static unsigned maxIndex = pkgIdIndex;
3076
3077static int __kmp_affinity_cmp_ProcCpuInfo_phys_id(const void *a,
3078 const void *b) {
3079 unsigned i;
3080 const unsigned *aa = *(unsigned *const *)a;
3081 const unsigned *bb = *(unsigned *const *)b;
3082 for (i = maxIndex;; i--) {
3083 if (aa[i] < bb[i])
3084 return -1;
3085 if (aa[i] > bb[i])
3086 return 1;
3087 if (i == osIdIndex)
3088 break;
3089 }
3090 return 0;
3091}
3092
3093#if KMP_USE_HIER_SCHED
3094// Set the array sizes for the hierarchy layers
3095static void __kmp_dispatch_set_hierarchy_values() {
3096 // Set the maximum number of L1's to number of cores
3097 // Set the maximum number of L2's to either number of cores / 2 for
3098 // Intel(R) Xeon Phi(TM) coprocessor formally codenamed Knights Landing
3099 // Or the number of cores for Intel(R) Xeon(R) processors
3100 // Set the maximum number of NUMA nodes and L3's to number of packages
3104#if KMP_ARCH_X86_64 && \
3105 (KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \
3106 KMP_OS_WINDOWS) && \
3107 KMP_MIC_SUPPORTED
3108 if (__kmp_mic_type >= mic3)
3110 else
3111#endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)
3116 // Set the number of threads per unit
3117 // Number of hardware threads per L1/L2/L3/NUMA/LOOP
3121#if KMP_ARCH_X86_64 && \
3122 (KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \
3123 KMP_OS_WINDOWS) && \
3124 KMP_MIC_SUPPORTED
3125 if (__kmp_mic_type >= mic3)
3128 else
3129#endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)
3138}
3139
3140// Return the index into the hierarchy for this tid and layer type (L1, L2, etc)
3141// i.e., this thread's L1 or this thread's L2, etc.
3143 int index = type + 1;
3144 int num_hw_threads = __kmp_hier_max_units[kmp_hier_layer_e::LAYER_THREAD + 1];
3147 return tid;
3149 return 0;
3151 if (tid >= num_hw_threads)
3152 tid = tid % num_hw_threads;
3153 return (tid / __kmp_hier_threads_per[index]) % __kmp_hier_max_units[index];
3154}
3155
3156// Return the number of t1's per t2
3158 int i1 = t1 + 1;
3159 int i2 = t2 + 1;
3160 KMP_DEBUG_ASSERT(i1 <= i2);
3164 // (nthreads/t2) / (nthreads/t1) = t1 / t2
3166}
3167#endif // KMP_USE_HIER_SCHED
3168
3169static inline const char *__kmp_cpuinfo_get_filename() {
3170 const char *filename;
3171 if (__kmp_cpuinfo_file != nullptr)
3172 filename = __kmp_cpuinfo_file;
3173 else
3174 filename = "/proc/cpuinfo";
3175 return filename;
3176}
3177
3178static inline const char *__kmp_cpuinfo_get_envvar() {
3179 const char *envvar = nullptr;
3180 if (__kmp_cpuinfo_file != nullptr)
3181 envvar = "KMP_CPUINFO_FILE";
3182 return envvar;
3183}
3184
3185static bool __kmp_package_id_from_core_siblings_list(unsigned **threadInfo,
3186 unsigned num_avail,
3187 unsigned idx) {
3188 if (!KMP_AFFINITY_CAPABLE())
3189 return false;
3190
3191 char path[256];
3192 KMP_SNPRINTF(path, sizeof(path),
3193 "/sys/devices/system/cpu/cpu%u/topology/core_siblings_list",
3194 threadInfo[idx][osIdIndex]);
3195 kmp_affin_mask_t *siblings = __kmp_parse_cpu_list(path);
3196 for (unsigned i = 0; i < num_avail; ++i) {
3197 unsigned cpu_id = threadInfo[i][osIdIndex];
3198 KMP_ASSERT(cpu_id < __kmp_affin_mask_size * CHAR_BIT);
3199 if (!KMP_CPU_ISSET(cpu_id, siblings))
3200 continue;
3201 if (threadInfo[i][pkgIdIndex] == UINT_MAX) {
3202 // Arbitrarily pick the first index we encounter, it only matters that
3203 // the value is the same for all siblings.
3204 threadInfo[i][pkgIdIndex] = idx;
3205 } else if (threadInfo[i][pkgIdIndex] != idx) {
3206 // Contradictory sibling lists.
3207 KMP_CPU_FREE(siblings);
3208 return false;
3209 }
3210 }
3211 KMP_ASSERT(threadInfo[idx][pkgIdIndex] != UINT_MAX);
3212 KMP_CPU_FREE(siblings);
3213 return true;
3214}
3215
3216// Parse /proc/cpuinfo (or an alternate file in the same format) to obtain the
3217// affinity map. On AIX, the map is obtained through system SRAD (Scheduler
3218// Resource Allocation Domain).
3219static bool __kmp_affinity_create_cpuinfo_map(int *line,
3220 kmp_i18n_id_t *const msg_id) {
3221 *msg_id = kmp_i18n_null;
3222
3223#if KMP_OS_AIX
3224 unsigned num_records = __kmp_xproc;
3225#else
3226 const char *filename = __kmp_cpuinfo_get_filename();
3227 const char *envvar = __kmp_cpuinfo_get_envvar();
3228
3229 if (__kmp_affinity.flags.verbose) {
3230 KMP_INFORM(AffParseFilename, "KMP_AFFINITY", filename);
3231 }
3232
3233 kmp_safe_raii_file_t f(filename, "r", envvar);
3234
3235 // Scan of the file, and count the number of "processor" (osId) fields,
3236 // and find the highest value of <n> for a node_<n> field.
3237 char buf[256];
3238 unsigned num_records = 0;
3239 while (!feof(f)) {
3240 buf[sizeof(buf) - 1] = 1;
3241 if (!fgets(buf, sizeof(buf), f)) {
3242 // Read errors presumably because of EOF
3243 break;
3244 }
3245
3246 char s1[] = "processor";
3247 if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
3248 num_records++;
3249 continue;
3250 }
3251
3252 // FIXME - this will match "node_<n> <garbage>"
3253 unsigned level;
3254 if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {
3255 // validate the input fisrt:
3256 if (level > (unsigned)__kmp_xproc) { // level is too big
3258 }
3259 if (nodeIdIndex + level >= maxIndex) {
3260 maxIndex = nodeIdIndex + level;
3261 }
3262 continue;
3263 }
3264 }
3265
3266 // Check for empty file / no valid processor records, or too many. The number
3267 // of records can't exceed the number of valid bits in the affinity mask.
3268 if (num_records == 0) {
3269 *msg_id = kmp_i18n_str_NoProcRecords;
3270 return false;
3271 }
3272 if (num_records > (unsigned)__kmp_xproc) {
3273 *msg_id = kmp_i18n_str_TooManyProcRecords;
3274 return false;
3275 }
3276
3277 // Set the file pointer back to the beginning, so that we can scan the file
3278 // again, this time performing a full parse of the data. Allocate a vector of
3279 // ProcCpuInfo object, where we will place the data. Adding an extra element
3280 // at the end allows us to remove a lot of extra checks for termination
3281 // conditions.
3282 if (fseek(f, 0, SEEK_SET) != 0) {
3283 *msg_id = kmp_i18n_str_CantRewindCpuinfo;
3284 return false;
3285 }
3286#endif // KMP_OS_AIX
3287
3288 // Allocate the array of records to store the proc info in. The dummy
3289 // element at the end makes the logic in filling them out easier to code.
3290 unsigned **threadInfo =
3291 (unsigned **)__kmp_allocate((num_records + 1) * sizeof(unsigned *));
3292 unsigned i;
3293 for (i = 0; i <= num_records; i++) {
3294 threadInfo[i] =
3295 (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
3296 }
3297
3298#define CLEANUP_THREAD_INFO \
3299 for (i = 0; i <= num_records; i++) { \
3300 __kmp_free(threadInfo[i]); \
3301 } \
3302 __kmp_free(threadInfo);
3303
3304 // A value of UINT_MAX means that we didn't find the field
3305 unsigned __index;
3306
3307#define INIT_PROC_INFO(p) \
3308 for (__index = 0; __index <= maxIndex; __index++) { \
3309 (p)[__index] = UINT_MAX; \
3310 }
3311
3312 for (i = 0; i <= num_records; i++) {
3313 INIT_PROC_INFO(threadInfo[i]);
3314 }
3315
3316#if KMP_OS_AIX
3317 int smt_threads;
3318 lpar_info_format1_t cpuinfo;
3319 unsigned num_avail = __kmp_xproc;
3320
3321 if (__kmp_affinity.flags.verbose)
3322 KMP_INFORM(AffParseFilename, "KMP_AFFINITY", "system info for topology");
3323
3324 // Get the number of SMT threads per core.
3325 smt_threads = syssmt(GET_NUMBER_SMT_SETS, 0, 0, NULL);
3326
3327 // Allocate a resource set containing available system resourses.
3328 rsethandle_t sys_rset = rs_alloc(RS_SYSTEM);
3329 if (sys_rset == NULL) {
3330 CLEANUP_THREAD_INFO;
3331 *msg_id = kmp_i18n_str_UnknownTopology;
3332 return false;
3333 }
3334 // Allocate a resource set for the SRAD info.
3335 rsethandle_t srad = rs_alloc(RS_EMPTY);
3336 if (srad == NULL) {
3337 rs_free(sys_rset);
3338 CLEANUP_THREAD_INFO;
3339 *msg_id = kmp_i18n_str_UnknownTopology;
3340 return false;
3341 }
3342
3343 // Get the SRAD system detail level.
3344 int sradsdl = rs_getinfo(NULL, R_SRADSDL, 0);
3345 if (sradsdl < 0) {
3346 rs_free(sys_rset);
3347 rs_free(srad);
3348 CLEANUP_THREAD_INFO;
3349 *msg_id = kmp_i18n_str_UnknownTopology;
3350 return false;
3351 }
3352 // Get the number of RADs at that SRAD SDL.
3353 int num_rads = rs_numrads(sys_rset, sradsdl, 0);
3354 if (num_rads < 0) {
3355 rs_free(sys_rset);
3356 rs_free(srad);
3357 CLEANUP_THREAD_INFO;
3358 *msg_id = kmp_i18n_str_UnknownTopology;
3359 return false;
3360 }
3361
3362 // Get the maximum number of procs that may be contained in a resource set.
3363 int max_procs = rs_getinfo(NULL, R_MAXPROCS, 0);
3364 if (max_procs < 0) {
3365 rs_free(sys_rset);
3366 rs_free(srad);
3367 CLEANUP_THREAD_INFO;
3368 *msg_id = kmp_i18n_str_UnknownTopology;
3369 return false;
3370 }
3371
3372 int cur_rad = 0;
3373 int num_set = 0;
3374 for (int srad_idx = 0; cur_rad < num_rads && srad_idx < VMI_MAXRADS;
3375 ++srad_idx) {
3376 // Check if the SRAD is available in the RSET.
3377 if (rs_getrad(sys_rset, srad, sradsdl, srad_idx, 0) < 0)
3378 continue;
3379
3380 for (int cpu = 0; cpu < max_procs; cpu++) {
3381 // Set the info for the cpu if it is in the SRAD.
3382 if (rs_op(RS_TESTRESOURCE, srad, NULL, R_PROCS, cpu)) {
3383 threadInfo[cpu][osIdIndex] = cpu;
3384 threadInfo[cpu][pkgIdIndex] = cur_rad;
3385 threadInfo[cpu][coreIdIndex] = cpu / smt_threads;
3386 ++num_set;
3387 if (num_set >= num_avail) {
3388 // Done if all available CPUs have been set.
3389 break;
3390 }
3391 }
3392 }
3393 ++cur_rad;
3394 }
3395 rs_free(sys_rset);
3396 rs_free(srad);
3397
3398 // The topology is already sorted.
3399
3400#else // !KMP_OS_AIX
3401 unsigned num_avail = 0;
3402 *line = 0;
3403#if KMP_ARCH_S390X
3404 bool reading_s390x_sys_info = true;
3405#endif
3406 while (!feof(f)) {
3407 // Create an inner scoping level, so that all the goto targets at the end of
3408 // the loop appear in an outer scoping level. This avoids warnings about
3409 // jumping past an initialization to a target in the same block.
3410 {
3411 buf[sizeof(buf) - 1] = 1;
3412 bool long_line = false;
3413 if (!fgets(buf, sizeof(buf), f)) {
3414 // Read errors presumably because of EOF
3415 // If there is valid data in threadInfo[num_avail], then fake
3416 // a blank line in ensure that the last address gets parsed.
3417 bool valid = false;
3418 for (i = 0; i <= maxIndex; i++) {
3419 if (threadInfo[num_avail][i] != UINT_MAX) {
3420 valid = true;
3421 }
3422 }
3423 if (!valid) {
3424 break;
3425 }
3426 buf[0] = 0;
3427 } else if (!buf[sizeof(buf) - 1]) {
3428 // The line is longer than the buffer. Set a flag and don't
3429 // emit an error if we were going to ignore the line, anyway.
3430 long_line = true;
3431
3432#define CHECK_LINE \
3433 if (long_line) { \
3434 CLEANUP_THREAD_INFO; \
3435 *msg_id = kmp_i18n_str_LongLineCpuinfo; \
3436 return false; \
3437 }
3438 }
3439 (*line)++;
3440
3441#if KMP_ARCH_LOONGARCH64
3442 // The parsing logic of /proc/cpuinfo in this function highly depends on
3443 // the blank lines between each processor info block. But on LoongArch a
3444 // blank line exists before the first processor info block (i.e. after the
3445 // "system type" line). This blank line was added because the "system
3446 // type" line is unrelated to any of the CPUs. We must skip this line so
3447 // that the original logic works on LoongArch.
3448 if (*buf == '\n' && *line == 2)
3449 continue;
3450#endif
3451#if KMP_ARCH_S390X
3452 // s390x /proc/cpuinfo starts with a variable number of lines containing
3453 // the overall system information. Skip them.
3454 if (reading_s390x_sys_info) {
3455 if (*buf == '\n')
3456 reading_s390x_sys_info = false;
3457 continue;
3458 }
3459#endif
3460
3461#if KMP_ARCH_S390X
3462 char s1[] = "cpu number";
3463#else
3464 char s1[] = "processor";
3465#endif
3466 if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
3467 CHECK_LINE;
3468 char *p = strchr(buf + sizeof(s1) - 1, ':');
3469 unsigned val;
3470 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
3471 goto no_val;
3472 if (threadInfo[num_avail][osIdIndex] != UINT_MAX)
3473#if KMP_ARCH_AARCH64
3474 // Handle the old AArch64 /proc/cpuinfo layout differently,
3475 // it contains all of the 'processor' entries listed in a
3476 // single 'Processor' section, therefore the normal looking
3477 // for duplicates in that section will always fail.
3478 num_avail++;
3479#else
3480 goto dup_field;
3481#endif
3482 threadInfo[num_avail][osIdIndex] = val;
3483#if KMP_OS_LINUX && !(KMP_ARCH_X86 || KMP_ARCH_X86_64)
3484 char path[256];
3486 path, sizeof(path),
3487 "/sys/devices/system/cpu/cpu%u/topology/physical_package_id",
3488 threadInfo[num_avail][osIdIndex]);
3489 __kmp_read_from_file(path, "%u", &threadInfo[num_avail][pkgIdIndex]);
3490
3491#if KMP_ARCH_S390X
3492 // Disambiguate physical_package_id.
3493 unsigned book_id;
3494 KMP_SNPRINTF(path, sizeof(path),
3495 "/sys/devices/system/cpu/cpu%u/topology/book_id",
3496 threadInfo[num_avail][osIdIndex]);
3497 __kmp_read_from_file(path, "%u", &book_id);
3498 threadInfo[num_avail][pkgIdIndex] |= (book_id << 8);
3499
3500 unsigned drawer_id;
3501 KMP_SNPRINTF(path, sizeof(path),
3502 "/sys/devices/system/cpu/cpu%u/topology/drawer_id",
3503 threadInfo[num_avail][osIdIndex]);
3504 __kmp_read_from_file(path, "%u", &drawer_id);
3505 threadInfo[num_avail][pkgIdIndex] |= (drawer_id << 16);
3506#endif
3507
3508 KMP_SNPRINTF(path, sizeof(path),
3509 "/sys/devices/system/cpu/cpu%u/topology/core_id",
3510 threadInfo[num_avail][osIdIndex]);
3511 __kmp_read_from_file(path, "%u", &threadInfo[num_avail][coreIdIndex]);
3512 continue;
3513#else
3514 }
3515 char s2[] = "physical id";
3516 if (strncmp(buf, s2, sizeof(s2) - 1) == 0) {
3517 CHECK_LINE;
3518 char *p = strchr(buf + sizeof(s2) - 1, ':');
3519 unsigned val;
3520 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
3521 goto no_val;
3522 if (threadInfo[num_avail][pkgIdIndex] != UINT_MAX)
3523 goto dup_field;
3524 threadInfo[num_avail][pkgIdIndex] = val;
3525 continue;
3526 }
3527 char s3[] = "core id";
3528 if (strncmp(buf, s3, sizeof(s3) - 1) == 0) {
3529 CHECK_LINE;
3530 char *p = strchr(buf + sizeof(s3) - 1, ':');
3531 unsigned val;
3532 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
3533 goto no_val;
3534 if (threadInfo[num_avail][coreIdIndex] != UINT_MAX)
3535 goto dup_field;
3536 threadInfo[num_avail][coreIdIndex] = val;
3537 continue;
3538#endif // KMP_OS_LINUX && USE_SYSFS_INFO
3539 }
3540 char s4[] = "thread id";
3541 if (strncmp(buf, s4, sizeof(s4) - 1) == 0) {
3542 CHECK_LINE;
3543 char *p = strchr(buf + sizeof(s4) - 1, ':');
3544 unsigned val;
3545 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
3546 goto no_val;
3547 if (threadInfo[num_avail][threadIdIndex] != UINT_MAX)
3548 goto dup_field;
3549 threadInfo[num_avail][threadIdIndex] = val;
3550 continue;
3551 }
3552 unsigned level;
3553 if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {
3554 CHECK_LINE;
3555 char *p = strchr(buf + sizeof(s4) - 1, ':');
3556 unsigned val;
3557 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
3558 goto no_val;
3559 // validate the input before using level:
3560 if (level > (unsigned)__kmp_xproc) { // level is too big
3562 }
3563 if (threadInfo[num_avail][nodeIdIndex + level] != UINT_MAX)
3564 goto dup_field;
3565 threadInfo[num_avail][nodeIdIndex + level] = val;
3566 continue;
3567 }
3568
3569 // We didn't recognize the leading token on the line. There are lots of
3570 // leading tokens that we don't recognize - if the line isn't empty, go on
3571 // to the next line.
3572 if ((*buf != 0) && (*buf != '\n')) {
3573 // If the line is longer than the buffer, read characters
3574 // until we find a newline.
3575 if (long_line) {
3576 int ch;
3577 while (((ch = fgetc(f)) != EOF) && (ch != '\n'))
3578 ;
3579 }
3580 continue;
3581 }
3582
3583 // A newline has signalled the end of the processor record.
3584 // Check that there aren't too many procs specified.
3585 if ((int)num_avail == __kmp_xproc) {
3586 CLEANUP_THREAD_INFO;
3587 *msg_id = kmp_i18n_str_TooManyEntries;
3588 return false;
3589 }
3590
3591 // Check for missing fields. The osId field must be there. The physical
3592 // id field will be checked later.
3593 if (threadInfo[num_avail][osIdIndex] == UINT_MAX) {
3594 CLEANUP_THREAD_INFO;
3595 *msg_id = kmp_i18n_str_MissingProcField;
3596 return false;
3597 }
3598
3599 // Skip this proc if it is not included in the machine model.
3600 if (KMP_AFFINITY_CAPABLE() &&
3601 !KMP_CPU_ISSET(threadInfo[num_avail][osIdIndex],
3602 __kmp_affin_fullMask)) {
3603 INIT_PROC_INFO(threadInfo[num_avail]);
3604 continue;
3605 }
3606
3607 // We have a successful parse of this proc's info.
3608 // Increment the counter, and prepare for the next proc.
3609 num_avail++;
3610 KMP_ASSERT(num_avail <= num_records);
3611 INIT_PROC_INFO(threadInfo[num_avail]);
3612 }
3613 continue;
3614
3615 no_val:
3616 CLEANUP_THREAD_INFO;
3617 *msg_id = kmp_i18n_str_MissingValCpuinfo;
3618 return false;
3619
3620 dup_field:
3621 CLEANUP_THREAD_INFO;
3622 *msg_id = kmp_i18n_str_DuplicateFieldCpuinfo;
3623 return false;
3624 }
3625 *line = 0;
3626
3627 // At least on powerpc, Linux may return -1 for physical_package_id. Try
3628 // to reconstruct topology from core_siblings_list in that case.
3629 for (i = 0; i < num_avail; ++i) {
3630 if (threadInfo[i][pkgIdIndex] == UINT_MAX) {
3631 if (!__kmp_package_id_from_core_siblings_list(threadInfo, num_avail, i)) {
3632 CLEANUP_THREAD_INFO;
3633 *msg_id = kmp_i18n_str_MissingPhysicalIDField;
3634 return false;
3635 }
3636 }
3637 }
3638
3639#if KMP_MIC && REDUCE_TEAM_SIZE
3640 unsigned teamSize = 0;
3641#endif // KMP_MIC && REDUCE_TEAM_SIZE
3642
3643 // check for num_records == __kmp_xproc ???
3644
3645 // If it is configured to omit the package level when there is only a single
3646 // package, the logic at the end of this routine won't work if there is only a
3647 // single thread
3648 KMP_ASSERT(num_avail > 0);
3649 KMP_ASSERT(num_avail <= num_records);
3650
3651 // Sort the threadInfo table by physical Id.
3652 qsort(threadInfo, num_avail, sizeof(*threadInfo),
3653 __kmp_affinity_cmp_ProcCpuInfo_phys_id);
3654
3655#endif // KMP_OS_AIX
3656
3657 // The table is now sorted by pkgId / coreId / threadId, but we really don't
3658 // know the radix of any of the fields. pkgId's may be sparsely assigned among
3659 // the chips on a system. Although coreId's are usually assigned
3660 // [0 .. coresPerPkg-1] and threadId's are usually assigned
3661 // [0..threadsPerCore-1], we don't want to make any such assumptions.
3662 //
3663 // For that matter, we don't know what coresPerPkg and threadsPerCore (or the
3664 // total # packages) are at this point - we want to determine that now. We
3665 // only have an upper bound on the first two figures.
3666 unsigned *counts =
3667 (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
3668 unsigned *maxCt =
3669 (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
3670 unsigned *totals =
3671 (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
3672 unsigned *lastId =
3673 (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
3674
3675 bool assign_thread_ids = false;
3676 unsigned threadIdCt;
3677 unsigned index;
3678
3679restart_radix_check:
3680 threadIdCt = 0;
3681
3682 // Initialize the counter arrays with data from threadInfo[0].
3683 if (assign_thread_ids) {
3684 if (threadInfo[0][threadIdIndex] == UINT_MAX) {
3685 threadInfo[0][threadIdIndex] = threadIdCt++;
3686 } else if (threadIdCt <= threadInfo[0][threadIdIndex]) {
3687 threadIdCt = threadInfo[0][threadIdIndex] + 1;
3688 }
3689 }
3690 for (index = 0; index <= maxIndex; index++) {
3691 counts[index] = 1;
3692 maxCt[index] = 1;
3693 totals[index] = 1;
3694 lastId[index] = threadInfo[0][index];
3695 ;
3696 }
3697
3698 // Run through the rest of the OS procs.
3699 for (i = 1; i < num_avail; i++) {
3700 // Find the most significant index whose id differs from the id for the
3701 // previous OS proc.
3702 for (index = maxIndex; index >= threadIdIndex; index--) {
3703 if (assign_thread_ids && (index == threadIdIndex)) {
3704 // Auto-assign the thread id field if it wasn't specified.
3705 if (threadInfo[i][threadIdIndex] == UINT_MAX) {
3706 threadInfo[i][threadIdIndex] = threadIdCt++;
3707 }
3708 // Apparently the thread id field was specified for some entries and not
3709 // others. Start the thread id counter off at the next higher thread id.
3710 else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
3711 threadIdCt = threadInfo[i][threadIdIndex] + 1;
3712 }
3713 }
3714 if (threadInfo[i][index] != lastId[index]) {
3715 // Run through all indices which are less significant, and reset the
3716 // counts to 1. At all levels up to and including index, we need to
3717 // increment the totals and record the last id.
3718 unsigned index2;
3719 for (index2 = threadIdIndex; index2 < index; index2++) {
3720 totals[index2]++;
3721 if (counts[index2] > maxCt[index2]) {
3722 maxCt[index2] = counts[index2];
3723 }
3724 counts[index2] = 1;
3725 lastId[index2] = threadInfo[i][index2];
3726 }
3727 counts[index]++;
3728 totals[index]++;
3729 lastId[index] = threadInfo[i][index];
3730
3731 if (assign_thread_ids && (index > threadIdIndex)) {
3732
3733#if KMP_MIC && REDUCE_TEAM_SIZE
3734 // The default team size is the total #threads in the machine
3735 // minus 1 thread for every core that has 3 or more threads.
3736 teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);
3737#endif // KMP_MIC && REDUCE_TEAM_SIZE
3738
3739 // Restart the thread counter, as we are on a new core.
3740 threadIdCt = 0;
3741
3742 // Auto-assign the thread id field if it wasn't specified.
3743 if (threadInfo[i][threadIdIndex] == UINT_MAX) {
3744 threadInfo[i][threadIdIndex] = threadIdCt++;
3745 }
3746
3747 // Apparently the thread id field was specified for some entries and
3748 // not others. Start the thread id counter off at the next higher
3749 // thread id.
3750 else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
3751 threadIdCt = threadInfo[i][threadIdIndex] + 1;
3752 }
3753 }
3754 break;
3755 }
3756 }
3757 if (index < threadIdIndex) {
3758 // If thread ids were specified, it is an error if they are not unique.
3759 // Also, check that we waven't already restarted the loop (to be safe -
3760 // shouldn't need to).
3761 if ((threadInfo[i][threadIdIndex] != UINT_MAX) || assign_thread_ids) {
3762 __kmp_free(lastId);
3763 __kmp_free(totals);
3764 __kmp_free(maxCt);
3765 __kmp_free(counts);
3766 CLEANUP_THREAD_INFO;
3767 *msg_id = kmp_i18n_str_PhysicalIDsNotUnique;
3768 return false;
3769 }
3770
3771 // If the thread ids were not specified and we see entries that
3772 // are duplicates, start the loop over and assign the thread ids manually.
3773 assign_thread_ids = true;
3774 goto restart_radix_check;
3775 }
3776 }
3777
3778#if KMP_MIC && REDUCE_TEAM_SIZE
3779 // The default team size is the total #threads in the machine
3780 // minus 1 thread for every core that has 3 or more threads.
3781 teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);
3782#endif // KMP_MIC && REDUCE_TEAM_SIZE
3783
3784 for (index = threadIdIndex; index <= maxIndex; index++) {
3785 if (counts[index] > maxCt[index]) {
3786 maxCt[index] = counts[index];
3787 }
3788 }
3789
3790 __kmp_nThreadsPerCore = maxCt[threadIdIndex];
3791 nCoresPerPkg = maxCt[coreIdIndex];
3792 nPackages = totals[pkgIdIndex];
3793
3794 // When affinity is off, this routine will still be called to set
3795 // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
3796 // Make sure all these vars are set correctly, and return now if affinity is
3797 // not enabled.
3798 __kmp_ncores = totals[coreIdIndex];
3799 if (!KMP_AFFINITY_CAPABLE()) {
3800 KMP_ASSERT(__kmp_affinity.type == affinity_none);
3801 __kmp_free(lastId);
3802 __kmp_free(totals);
3803 __kmp_free(maxCt);
3804 __kmp_free(counts);
3805 CLEANUP_THREAD_INFO;
3806 return true;
3807 }
3808
3809#if KMP_MIC && REDUCE_TEAM_SIZE
3810 // Set the default team size.
3811 if ((__kmp_dflt_team_nth == 0) && (teamSize > 0)) {
3812 __kmp_dflt_team_nth = teamSize;
3813 KA_TRACE(20, ("__kmp_affinity_create_cpuinfo_map: setting "
3814 "__kmp_dflt_team_nth = %d\n",
3816 }
3817#endif // KMP_MIC && REDUCE_TEAM_SIZE
3818
3819 KMP_DEBUG_ASSERT(num_avail == (unsigned)__kmp_avail_proc);
3820
3821 // Count the number of levels which have more nodes at that level than at the
3822 // parent's level (with there being an implicit root node of the top level).
3823 // This is equivalent to saying that there is at least one node at this level
3824 // which has a sibling. These levels are in the map, and the package level is
3825 // always in the map.
3826 bool *inMap = (bool *)__kmp_allocate((maxIndex + 1) * sizeof(bool));
3827 for (index = threadIdIndex; index < maxIndex; index++) {
3828 KMP_ASSERT(totals[index] >= totals[index + 1]);
3829 inMap[index] = (totals[index] > totals[index + 1]);
3830 }
3831 inMap[maxIndex] = (totals[maxIndex] > 1);
3832 inMap[pkgIdIndex] = true;
3833 inMap[coreIdIndex] = true;
3834 inMap[threadIdIndex] = true;
3835
3836 int depth = 0;
3837 int idx = 0;
3838 kmp_hw_t types[KMP_HW_LAST];
3839 int pkgLevel = -1;
3840 int coreLevel = -1;
3841 int threadLevel = -1;
3842 for (index = threadIdIndex; index <= maxIndex; index++) {
3843 if (inMap[index]) {
3844 depth++;
3845 }
3846 }
3847 if (inMap[pkgIdIndex]) {
3848 pkgLevel = idx;
3849 types[idx++] = KMP_HW_SOCKET;
3850 }
3851 if (inMap[coreIdIndex]) {
3852 coreLevel = idx;
3853 types[idx++] = KMP_HW_CORE;
3854 }
3855 if (inMap[threadIdIndex]) {
3856 threadLevel = idx;
3857 types[idx++] = KMP_HW_THREAD;
3858 }
3859 KMP_ASSERT(depth > 0);
3860
3861 // Construct the data structure that is to be returned.
3862 __kmp_topology = kmp_topology_t::allocate(num_avail, depth, types);
3863
3864 for (i = 0; i < num_avail; ++i) {
3865 unsigned os = threadInfo[i][osIdIndex];
3866 int src_index;
3867 kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
3868 hw_thread.clear();
3869 hw_thread.os_id = os;
3870 hw_thread.original_idx = i;
3871
3872 idx = 0;
3873 for (src_index = maxIndex; src_index >= threadIdIndex; src_index--) {
3874 if (!inMap[src_index]) {
3875 continue;
3876 }
3877 if (src_index == pkgIdIndex) {
3878 hw_thread.ids[pkgLevel] = threadInfo[i][src_index];
3879 } else if (src_index == coreIdIndex) {
3880 hw_thread.ids[coreLevel] = threadInfo[i][src_index];
3881 } else if (src_index == threadIdIndex) {
3882 hw_thread.ids[threadLevel] = threadInfo[i][src_index];
3883 }
3884 }
3885 }
3886
3887 __kmp_free(inMap);
3888 __kmp_free(lastId);
3889 __kmp_free(totals);
3890 __kmp_free(maxCt);
3891 __kmp_free(counts);
3892 CLEANUP_THREAD_INFO;
3893 __kmp_topology->sort_ids();
3894
3895 int tlevel = __kmp_topology->get_level(KMP_HW_THREAD);
3896 if (tlevel > 0) {
3897 // If the thread level does not have ids, then put them in.
3898 if (__kmp_topology->at(0).ids[tlevel] == kmp_hw_thread_t::UNKNOWN_ID) {
3899 __kmp_topology->at(0).ids[tlevel] = 0;
3900 }
3901 for (int i = 1; i < __kmp_topology->get_num_hw_threads(); ++i) {
3902 kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
3903 if (hw_thread.ids[tlevel] != kmp_hw_thread_t::UNKNOWN_ID)
3904 continue;
3905 kmp_hw_thread_t &prev_hw_thread = __kmp_topology->at(i - 1);
3906 // Check if socket, core, anything above thread level changed.
3907 // If the ids did change, then restart thread id at 0
3908 // Otherwise, set thread id to prev thread's id + 1
3909 for (int j = 0; j < tlevel; ++j) {
3910 if (hw_thread.ids[j] != prev_hw_thread.ids[j]) {
3911 hw_thread.ids[tlevel] = 0;
3912 break;
3913 }
3914 }
3915 if (hw_thread.ids[tlevel] == kmp_hw_thread_t::UNKNOWN_ID)
3916 hw_thread.ids[tlevel] = prev_hw_thread.ids[tlevel] + 1;
3917 }
3918 }
3919
3920 if (!__kmp_topology->check_ids()) {
3922 __kmp_topology = nullptr;
3923 *msg_id = kmp_i18n_str_PhysicalIDsNotUnique;
3924 return false;
3925 }
3926 return true;
3927}
3928
3929// Create and return a table of affinity masks, indexed by OS thread ID.
3930// This routine handles OR'ing together all the affinity masks of threads
3931// that are sufficiently close, if granularity > fine.
3932template <typename FindNextFunctionType>
3933static void __kmp_create_os_id_masks(unsigned *numUnique,
3934 kmp_affinity_t &affinity,
3935 FindNextFunctionType find_next) {
3936 // First form a table of affinity masks in order of OS thread id.
3937 int maxOsId;
3938 int i;
3939 int numAddrs = __kmp_topology->get_num_hw_threads();
3940 int depth = __kmp_topology->get_depth();
3941 const char *env_var = __kmp_get_affinity_env_var(affinity);
3942 KMP_ASSERT(numAddrs);
3943 KMP_ASSERT(depth);
3944
3945 i = find_next(-1);
3946 // If could not find HW thread location that satisfies find_next conditions,
3947 // then return and fallback to increment find_next.
3948 if (i >= numAddrs)
3949 return;
3950
3951 maxOsId = 0;
3952 for (i = numAddrs - 1;; --i) {
3953 int osId = __kmp_topology->at(i).os_id;
3954 if (osId > maxOsId) {
3955 maxOsId = osId;
3956 }
3957 if (i == 0)
3958 break;
3959 }
3960 affinity.num_os_id_masks = maxOsId + 1;
3961 KMP_CPU_ALLOC_ARRAY(affinity.os_id_masks, affinity.num_os_id_masks);
3962 KMP_ASSERT(affinity.gran_levels >= 0);
3963 if (affinity.flags.verbose && (affinity.gran_levels > 0)) {
3964 KMP_INFORM(ThreadsMigrate, env_var, affinity.gran_levels);
3965 }
3966 if (affinity.gran_levels >= (int)depth) {
3967 KMP_AFF_WARNING(affinity, AffThreadsMayMigrate);
3968 }
3969
3970 // Run through the table, forming the masks for all threads on each core.
3971 // Threads on the same core will have identical kmp_hw_thread_t objects, not
3972 // considering the last level, which must be the thread id. All threads on a
3973 // core will appear consecutively.
3974 int unique = 0;
3975 int j = 0; // index of 1st thread on core
3976 int leader = 0;
3977 kmp_affin_mask_t *sum;
3978 KMP_CPU_ALLOC_ON_STACK(sum);
3979 KMP_CPU_ZERO(sum);
3980
3981 i = j = leader = find_next(-1);
3982 KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);
3983 kmp_full_mask_modifier_t full_mask;
3984 for (i = find_next(i); i < numAddrs; i = find_next(i)) {
3985 // If this thread is sufficiently close to the leader (within the
3986 // granularity setting), then set the bit for this os thread in the
3987 // affinity mask for this group, and go on to the next thread.
3988 if (__kmp_topology->is_close(leader, i, affinity)) {
3989 KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);
3990 continue;
3991 }
3992
3993 // For every thread in this group, copy the mask to the thread's entry in
3994 // the OS Id mask table. Mark the first address as a leader.
3995 for (; j < i; j = find_next(j)) {
3996 int osId = __kmp_topology->at(j).os_id;
3997 KMP_DEBUG_ASSERT(osId <= maxOsId);
3998 kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.os_id_masks, osId);
3999 KMP_CPU_COPY(mask, sum);
4000 __kmp_topology->at(j).leader = (j == leader);
4001 }
4002 unique++;
4003
4004 // Start a new mask.
4005 leader = i;
4006 full_mask.include(sum);
4007 KMP_CPU_ZERO(sum);
4008 KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);
4009 }
4010
4011 // For every thread in last group, copy the mask to the thread's
4012 // entry in the OS Id mask table.
4013 for (; j < i; j = find_next(j)) {
4014 int osId = __kmp_topology->at(j).os_id;
4015 KMP_DEBUG_ASSERT(osId <= maxOsId);
4016 kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.os_id_masks, osId);
4017 KMP_CPU_COPY(mask, sum);
4018 __kmp_topology->at(j).leader = (j == leader);
4019 }
4020 full_mask.include(sum);
4021 unique++;
4022 KMP_CPU_FREE_FROM_STACK(sum);
4023
4024 // See if the OS Id mask table further restricts or changes the full mask
4025 if (full_mask.restrict_to_mask() && affinity.flags.verbose) {
4026 __kmp_topology->print(env_var);
4027 }
4028
4029 *numUnique = unique;
4030}
4031
4032// Stuff for the affinity proclist parsers. It's easier to declare these vars
4033// as file-static than to try and pass them through the calling sequence of
4034// the recursive-descent OMP_PLACES parser.
4035static kmp_affin_mask_t *newMasks;
4036static int numNewMasks;
4037static int nextNewMask;
4038
4039#define ADD_MASK(_mask) \
4040 { \
4041 if (nextNewMask >= numNewMasks) { \
4042 int i; \
4043 numNewMasks *= 2; \
4044 kmp_affin_mask_t *temp; \
4045 KMP_CPU_INTERNAL_ALLOC_ARRAY(temp, numNewMasks); \
4046 for (i = 0; i < numNewMasks / 2; i++) { \
4047 kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i); \
4048 kmp_affin_mask_t *dest = KMP_CPU_INDEX(temp, i); \
4049 KMP_CPU_COPY(dest, src); \
4050 } \
4051 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks / 2); \
4052 newMasks = temp; \
4053 } \
4054 KMP_CPU_COPY(KMP_CPU_INDEX(newMasks, nextNewMask), (_mask)); \
4055 nextNewMask++; \
4056 }
4057
4058#define ADD_MASK_OSID(_osId, _osId2Mask, _maxOsId) \
4059 { \
4060 if (((_osId) > _maxOsId) || \
4061 (!KMP_CPU_ISSET((_osId), KMP_CPU_INDEX((_osId2Mask), (_osId))))) { \
4062 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, _osId); \
4063 } else { \
4064 ADD_MASK(KMP_CPU_INDEX(_osId2Mask, (_osId))); \
4065 } \
4066 }
4067
4068// Re-parse the proclist (for the explicit affinity type), and form the list
4069// of affinity newMasks indexed by gtid.
4070static void __kmp_affinity_process_proclist(kmp_affinity_t &affinity) {
4071 int i;
4072 kmp_affin_mask_t **out_masks = &affinity.masks;
4073 unsigned *out_numMasks = &affinity.num_masks;
4074 const char *proclist = affinity.proclist;
4075 kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;
4076 int maxOsId = affinity.num_os_id_masks - 1;
4077 const char *scan = proclist;
4078 const char *next = proclist;
4079
4080 // We use malloc() for the temporary mask vector, so that we can use
4081 // realloc() to extend it.
4082 numNewMasks = 2;
4083 KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
4084 nextNewMask = 0;
4085 kmp_affin_mask_t *sumMask;
4086 KMP_CPU_ALLOC(sumMask);
4087 int setSize = 0;
4088
4089 for (;;) {
4090 int start, end, stride;
4091
4092 SKIP_WS(scan);
4093 next = scan;
4094 if (*next == '\0') {
4095 break;
4096 }
4097
4098 if (*next == '{') {
4099 int num;
4100 setSize = 0;
4101 next++; // skip '{'
4102 SKIP_WS(next);
4103 scan = next;
4104
4105 // Read the first integer in the set.
4106 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad proclist");
4107 SKIP_DIGITS(next);
4108 num = __kmp_str_to_int(scan, *next);
4109 KMP_ASSERT2(num >= 0, "bad explicit proc list");
4110
4111 // Copy the mask for that osId to the sum (union) mask.
4112 if ((num > maxOsId) ||
4113 (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
4114 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);
4115 KMP_CPU_ZERO(sumMask);
4116 } else {
4117 KMP_CPU_COPY(sumMask, KMP_CPU_INDEX(osId2Mask, num));
4118 setSize = 1;
4119 }
4120
4121 for (;;) {
4122 // Check for end of set.
4123 SKIP_WS(next);
4124 if (*next == '}') {
4125 next++; // skip '}'
4126 break;
4127 }
4128
4129 // Skip optional comma.
4130 if (*next == ',') {
4131 next++;
4132 }
4133 SKIP_WS(next);
4134
4135 // Read the next integer in the set.
4136 scan = next;
4137 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
4138
4139 SKIP_DIGITS(next);
4140 num = __kmp_str_to_int(scan, *next);
4141 KMP_ASSERT2(num >= 0, "bad explicit proc list");
4142
4143 // Add the mask for that osId to the sum mask.
4144 if ((num > maxOsId) ||
4145 (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
4146 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);
4147 } else {
4148 KMP_CPU_UNION(sumMask, KMP_CPU_INDEX(osId2Mask, num));
4149 setSize++;
4150 }
4151 }
4152 if (setSize > 0) {
4153 ADD_MASK(sumMask);
4154 }
4155
4156 SKIP_WS(next);
4157 if (*next == ',') {
4158 next++;
4159 }
4160 scan = next;
4161 continue;
4162 }
4163
4164 // Read the first integer.
4165 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
4166 SKIP_DIGITS(next);
4167 start = __kmp_str_to_int(scan, *next);
4168 KMP_ASSERT2(start >= 0, "bad explicit proc list");
4169 SKIP_WS(next);
4170
4171 // If this isn't a range, then add a mask to the list and go on.
4172 if (*next != '-') {
4173 ADD_MASK_OSID(start, osId2Mask, maxOsId);
4174
4175 // Skip optional comma.
4176 if (*next == ',') {
4177 next++;
4178 }
4179 scan = next;
4180 continue;
4181 }
4182
4183 // This is a range. Skip over the '-' and read in the 2nd int.
4184 next++; // skip '-'
4185 SKIP_WS(next);
4186 scan = next;
4187 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
4188 SKIP_DIGITS(next);
4189 end = __kmp_str_to_int(scan, *next);
4190 KMP_ASSERT2(end >= 0, "bad explicit proc list");
4191
4192 // Check for a stride parameter
4193 stride = 1;
4194 SKIP_WS(next);
4195 if (*next == ':') {
4196 // A stride is specified. Skip over the ':" and read the 3rd int.
4197 int sign = +1;
4198 next++; // skip ':'
4199 SKIP_WS(next);
4200 scan = next;
4201 if (*next == '-') {
4202 sign = -1;
4203 next++;
4204 SKIP_WS(next);
4205 scan = next;
4206 }
4207 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
4208 SKIP_DIGITS(next);
4209 stride = __kmp_str_to_int(scan, *next);
4210 KMP_ASSERT2(stride >= 0, "bad explicit proc list");
4211 stride *= sign;
4212 }
4213
4214 // Do some range checks.
4215 KMP_ASSERT2(stride != 0, "bad explicit proc list");
4216 if (stride > 0) {
4217 KMP_ASSERT2(start <= end, "bad explicit proc list");
4218 } else {
4219 KMP_ASSERT2(start >= end, "bad explicit proc list");
4220 }
4221 KMP_ASSERT2((end - start) / stride <= 65536, "bad explicit proc list");
4222
4223 // Add the mask for each OS proc # to the list.
4224 if (stride > 0) {
4225 do {
4226 ADD_MASK_OSID(start, osId2Mask, maxOsId);
4227 // Prevent possible overflow calculation
4228 if (end - start < stride)
4229 break;
4230 start += stride;
4231 } while (start <= end);
4232 } else {
4233 do {
4234 ADD_MASK_OSID(start, osId2Mask, maxOsId);
4235 start += stride;
4236 } while (start >= end);
4237 }
4238
4239 // Skip optional comma.
4240 SKIP_WS(next);
4241 if (*next == ',') {
4242 next++;
4243 }
4244 scan = next;
4245 }
4246
4247 *out_numMasks = nextNewMask;
4248 if (nextNewMask == 0) {
4249 *out_masks = NULL;
4250 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
4251 KMP_CPU_FREE(sumMask);
4252 return;
4253 }
4254 KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
4255 for (i = 0; i < nextNewMask; i++) {
4256 kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);
4257 kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);
4258 KMP_CPU_COPY(dest, src);
4259 }
4260 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
4261 KMP_CPU_FREE(sumMask);
4262}
4263
4264/*-----------------------------------------------------------------------------
4265Re-parse the OMP_PLACES proc id list, forming the newMasks for the different
4266places. Again, Here is the grammar:
4267
4268place_list := place
4269place_list := place , place_list
4270place := num
4271place := place : num
4272place := place : num : signed
4273place := { subplacelist }
4274place := ! place // (lowest priority)
4275subplace_list := subplace
4276subplace_list := subplace , subplace_list
4277subplace := num
4278subplace := num : num
4279subplace := num : num : signed
4280signed := num
4281signed := + signed
4282signed := - signed
4283-----------------------------------------------------------------------------*/
4284static void __kmp_process_subplace_list(const char **scan,
4285 kmp_affinity_t &affinity, int maxOsId,
4286 kmp_affin_mask_t *tempMask,
4287 int *setSize) {
4288 const char *next;
4289 kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;
4290
4291 for (;;) {
4292 int start, count, stride, i;
4293
4294 // Read in the starting proc id
4295 SKIP_WS(*scan);
4296 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
4297 next = *scan;
4298 SKIP_DIGITS(next);
4299 start = __kmp_str_to_int(*scan, *next);
4300 KMP_ASSERT(start >= 0);
4301 *scan = next;
4302
4303 // valid follow sets are ',' ':' and '}'
4304 SKIP_WS(*scan);
4305 if (**scan == '}' || **scan == ',') {
4306 if ((start > maxOsId) ||
4307 (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
4308 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);
4309 } else {
4310 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
4311 (*setSize)++;
4312 }
4313 if (**scan == '}') {
4314 break;
4315 }
4316 (*scan)++; // skip ','
4317 continue;
4318 }
4319 KMP_ASSERT2(**scan == ':', "bad explicit places list");
4320 (*scan)++; // skip ':'
4321
4322 // Read count parameter
4323 SKIP_WS(*scan);
4324 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
4325 next = *scan;
4326 SKIP_DIGITS(next);
4327 count = __kmp_str_to_int(*scan, *next);
4328 KMP_ASSERT(count >= 0);
4329 *scan = next;
4330
4331 // valid follow sets are ',' ':' and '}'
4332 SKIP_WS(*scan);
4333 if (**scan == '}' || **scan == ',') {
4334 for (i = 0; i < count; i++) {
4335 if ((start > maxOsId) ||
4336 (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
4337 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);
4338 break; // don't proliferate warnings for large count
4339 } else {
4340 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
4341 start++;
4342 (*setSize)++;
4343 }
4344 }
4345 if (**scan == '}') {
4346 break;
4347 }
4348 (*scan)++; // skip ','
4349 continue;
4350 }
4351 KMP_ASSERT2(**scan == ':', "bad explicit places list");
4352 (*scan)++; // skip ':'
4353
4354 // Read stride parameter
4355 int sign = +1;
4356 for (;;) {
4357 SKIP_WS(*scan);
4358 if (**scan == '+') {
4359 (*scan)++; // skip '+'
4360 continue;
4361 }
4362 if (**scan == '-') {
4363 sign *= -1;
4364 (*scan)++; // skip '-'
4365 continue;
4366 }
4367 break;
4368 }
4369 SKIP_WS(*scan);
4370 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
4371 next = *scan;
4372 SKIP_DIGITS(next);
4373 stride = __kmp_str_to_int(*scan, *next);
4374 KMP_ASSERT(stride >= 0);
4375 *scan = next;
4376 stride *= sign;
4377
4378 // valid follow sets are ',' and '}'
4379 SKIP_WS(*scan);
4380 if (**scan == '}' || **scan == ',') {
4381 for (i = 0; i < count; i++) {
4382 if ((start > maxOsId) ||
4383 (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
4384 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);
4385 break; // don't proliferate warnings for large count
4386 } else {
4387 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
4388 start += stride;
4389 (*setSize)++;
4390 }
4391 }
4392 if (**scan == '}') {
4393 break;
4394 }
4395 (*scan)++; // skip ','
4396 continue;
4397 }
4398
4399 KMP_ASSERT2(0, "bad explicit places list");
4400 }
4401}
4402
4403static void __kmp_process_place(const char **scan, kmp_affinity_t &affinity,
4404 int maxOsId, kmp_affin_mask_t *tempMask,
4405 int *setSize) {
4406 const char *next;
4407 kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;
4408
4409 // valid follow sets are '{' '!' and num
4410 SKIP_WS(*scan);
4411 if (**scan == '{') {
4412 (*scan)++; // skip '{'
4413 __kmp_process_subplace_list(scan, affinity, maxOsId, tempMask, setSize);
4414 KMP_ASSERT2(**scan == '}', "bad explicit places list");
4415 (*scan)++; // skip '}'
4416 } else if (**scan == '!') {
4417 (*scan)++; // skip '!'
4418 __kmp_process_place(scan, affinity, maxOsId, tempMask, setSize);
4419 KMP_CPU_COMPLEMENT(maxOsId, tempMask);
4420 KMP_CPU_AND(tempMask, __kmp_affin_fullMask);
4421 } else if ((**scan >= '0') && (**scan <= '9')) {
4422 next = *scan;
4423 SKIP_DIGITS(next);
4424 int num = __kmp_str_to_int(*scan, *next);
4425 KMP_ASSERT(num >= 0);
4426 if ((num > maxOsId) ||
4427 (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
4428 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);
4429 } else {
4430 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, num));
4431 (*setSize)++;
4432 }
4433 *scan = next; // skip num
4434 } else {
4435 KMP_ASSERT2(0, "bad explicit places list");
4436 }
4437}
4438
4439// static void
4440void __kmp_affinity_process_placelist(kmp_affinity_t &affinity) {
4441 int i, j, count, stride, sign;
4442 kmp_affin_mask_t **out_masks = &affinity.masks;
4443 unsigned *out_numMasks = &affinity.num_masks;
4444 const char *placelist = affinity.proclist;
4445 kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;
4446 int maxOsId = affinity.num_os_id_masks - 1;
4447 const char *scan = placelist;
4448 const char *next = placelist;
4449
4450 numNewMasks = 2;
4451 KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
4452 nextNewMask = 0;
4453
4454 // tempMask is modified based on the previous or initial
4455 // place to form the current place
4456 // previousMask contains the previous place
4457 kmp_affin_mask_t *tempMask;
4458 kmp_affin_mask_t *previousMask;
4459 KMP_CPU_ALLOC(tempMask);
4460 KMP_CPU_ZERO(tempMask);
4461 KMP_CPU_ALLOC(previousMask);
4462 KMP_CPU_ZERO(previousMask);
4463 int setSize = 0;
4464
4465 for (;;) {
4466 __kmp_process_place(&scan, affinity, maxOsId, tempMask, &setSize);
4467
4468 // valid follow sets are ',' ':' and EOL
4469 SKIP_WS(scan);
4470 if (*scan == '\0' || *scan == ',') {
4471 if (setSize > 0) {
4472 ADD_MASK(tempMask);
4473 }
4474 KMP_CPU_ZERO(tempMask);
4475 setSize = 0;
4476 if (*scan == '\0') {
4477 break;
4478 }
4479 scan++; // skip ','
4480 continue;
4481 }
4482
4483 KMP_ASSERT2(*scan == ':', "bad explicit places list");
4484 scan++; // skip ':'
4485
4486 // Read count parameter
4487 SKIP_WS(scan);
4488 KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");
4489 next = scan;
4490 SKIP_DIGITS(next);
4491 count = __kmp_str_to_int(scan, *next);
4492 KMP_ASSERT(count >= 0);
4493 scan = next;
4494
4495 // valid follow sets are ',' ':' and EOL
4496 SKIP_WS(scan);
4497 if (*scan == '\0' || *scan == ',') {
4498 stride = +1;
4499 } else {
4500 KMP_ASSERT2(*scan == ':', "bad explicit places list");
4501 scan++; // skip ':'
4502
4503 // Read stride parameter
4504 sign = +1;
4505 for (;;) {
4506 SKIP_WS(scan);
4507 if (*scan == '+') {
4508 scan++; // skip '+'
4509 continue;
4510 }
4511 if (*scan == '-') {
4512 sign *= -1;
4513 scan++; // skip '-'
4514 continue;
4515 }
4516 break;
4517 }
4518 SKIP_WS(scan);
4519 KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");
4520 next = scan;
4521 SKIP_DIGITS(next);
4522 stride = __kmp_str_to_int(scan, *next);
4523 KMP_DEBUG_ASSERT(stride >= 0);
4524 scan = next;
4525 stride *= sign;
4526 }
4527
4528 // Add places determined by initial_place : count : stride
4529 for (i = 0; i < count; i++) {
4530 if (setSize == 0) {
4531 break;
4532 }
4533 // Add the current place, then build the next place (tempMask) from that
4534 KMP_CPU_COPY(previousMask, tempMask);
4535 ADD_MASK(previousMask);
4536 KMP_CPU_ZERO(tempMask);
4537 setSize = 0;
4538 KMP_CPU_SET_ITERATE(j, previousMask) {
4539 if (!KMP_CPU_ISSET(j, previousMask)) {
4540 continue;
4541 }
4542 if ((j + stride > maxOsId) || (j + stride < 0) ||
4543 (!KMP_CPU_ISSET(j, __kmp_affin_fullMask)) ||
4544 (!KMP_CPU_ISSET(j + stride,
4545 KMP_CPU_INDEX(osId2Mask, j + stride)))) {
4546 if (i < count - 1) {
4547 KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, j + stride);
4548 }
4549 continue;
4550 }
4551 KMP_CPU_SET(j + stride, tempMask);
4552 setSize++;
4553 }
4554 }
4555 KMP_CPU_ZERO(tempMask);
4556 setSize = 0;
4557
4558 // valid follow sets are ',' and EOL
4559 SKIP_WS(scan);
4560 if (*scan == '\0') {
4561 break;
4562 }
4563 if (*scan == ',') {
4564 scan++; // skip ','
4565 continue;
4566 }
4567
4568 KMP_ASSERT2(0, "bad explicit places list");
4569 }
4570
4571 *out_numMasks = nextNewMask;
4572 if (nextNewMask == 0) {
4573 *out_masks = NULL;
4574 KMP_CPU_FREE(tempMask);
4575 KMP_CPU_FREE(previousMask);
4576 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
4577 return;
4578 }
4579 KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
4580 KMP_CPU_FREE(tempMask);
4581 KMP_CPU_FREE(previousMask);
4582 for (i = 0; i < nextNewMask; i++) {
4583 kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);
4584 kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);
4585 KMP_CPU_COPY(dest, src);
4586 }
4587 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
4588}
4589
4590#undef ADD_MASK
4591#undef ADD_MASK_OSID
4592
4593// This function figures out the deepest level at which there is at least one
4594// cluster/core with more than one processing unit bound to it.
4595static int __kmp_affinity_find_core_level(int nprocs, int bottom_level) {
4596 int core_level = 0;
4597
4598 for (int i = 0; i < nprocs; i++) {
4599 const kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
4600 for (int j = bottom_level; j > 0; j--) {
4601 if (hw_thread.ids[j] > 0) {
4602 if (core_level < (j - 1)) {
4603 core_level = j - 1;
4604 }
4605 }
4606 }
4607 }
4608 return core_level;
4609}
4610
4611// This function counts number of clusters/cores at given level.
4612static int __kmp_affinity_compute_ncores(int nprocs, int bottom_level,
4613 int core_level) {
4614 return __kmp_topology->get_count(core_level);
4615}
4616// This function finds to which cluster/core given processing unit is bound.
4617static int __kmp_affinity_find_core(int proc, int bottom_level,
4618 int core_level) {
4619 int core = 0;
4620 KMP_DEBUG_ASSERT(proc >= 0 && proc < __kmp_topology->get_num_hw_threads());
4621 for (int i = 0; i <= proc; ++i) {
4622 if (i + 1 <= proc) {
4623 for (int j = 0; j <= core_level; ++j) {
4624 if (__kmp_topology->at(i + 1).sub_ids[j] !=
4625 __kmp_topology->at(i).sub_ids[j]) {
4626 core++;
4627 break;
4628 }
4629 }
4630 }
4631 }
4632 return core;
4633}
4634
4635// This function finds maximal number of processing units bound to a
4636// cluster/core at given level.
4637static int __kmp_affinity_max_proc_per_core(int nprocs, int bottom_level,
4638 int core_level) {
4639 if (core_level >= bottom_level)
4640 return 1;
4641 int thread_level = __kmp_topology->get_level(KMP_HW_THREAD);
4642 return __kmp_topology->calculate_ratio(thread_level, core_level);
4643}
4644
4645static int *procarr = NULL;
4646static int __kmp_aff_depth = 0;
4647static int *__kmp_osid_to_hwthread_map = NULL;
4648
4649static void __kmp_affinity_get_mask_topology_info(const kmp_affin_mask_t *mask,
4650 kmp_affinity_ids_t &ids,
4651 kmp_affinity_attrs_t &attrs) {
4652 if (!KMP_AFFINITY_CAPABLE())
4653 return;
4654
4655 // Initiailze ids and attrs thread data
4656 for (int i = 0; i < KMP_HW_LAST; ++i)
4657 ids.ids[i] = kmp_hw_thread_t::UNKNOWN_ID;
4658 attrs = KMP_AFFINITY_ATTRS_UNKNOWN;
4659
4660 // Iterate through each os id within the mask and determine
4661 // the topology id and attribute information
4662 int cpu;
4663 int depth = __kmp_topology->get_depth();
4664 KMP_CPU_SET_ITERATE(cpu, mask) {
4665 int osid_idx = __kmp_osid_to_hwthread_map[cpu];
4666 ids.os_id = cpu;
4667 const kmp_hw_thread_t &hw_thread = __kmp_topology->at(osid_idx);
4668 for (int level = 0; level < depth; ++level) {
4669 kmp_hw_t type = __kmp_topology->get_type(level);
4670 int id = hw_thread.sub_ids[level];
4671 if (ids.ids[type] == kmp_hw_thread_t::UNKNOWN_ID || ids.ids[type] == id) {
4672 ids.ids[type] = id;
4673 } else {
4674 // This mask spans across multiple topology units, set it as such
4675 // and mark every level below as such as well.
4677 for (; level < depth; ++level) {
4678 kmp_hw_t type = __kmp_topology->get_type(level);
4680 }
4681 }
4682 }
4683 if (!attrs.valid) {
4684 attrs.core_type = hw_thread.attrs.get_core_type();
4685 attrs.core_eff = hw_thread.attrs.get_core_eff();
4686 attrs.valid = 1;
4687 } else {
4688 // This mask spans across multiple attributes, set it as such
4689 if (attrs.core_type != hw_thread.attrs.get_core_type())
4690 attrs.core_type = KMP_HW_CORE_TYPE_UNKNOWN;
4691 if (attrs.core_eff != hw_thread.attrs.get_core_eff())
4692 attrs.core_eff = kmp_hw_attr_t::UNKNOWN_CORE_EFF;
4693 }
4694 }
4695}
4696
4697static void __kmp_affinity_get_thread_topology_info(kmp_info_t *th) {
4698 if (!KMP_AFFINITY_CAPABLE())
4699 return;
4700 const kmp_affin_mask_t *mask = th->th.th_affin_mask;
4701 kmp_affinity_ids_t &ids = th->th.th_topology_ids;
4702 kmp_affinity_attrs_t &attrs = th->th.th_topology_attrs;
4703 __kmp_affinity_get_mask_topology_info(mask, ids, attrs);
4704}
4705
4706// Assign the topology information to each place in the place list
4707// A thread can then grab not only its affinity mask, but the topology
4708// information associated with that mask. e.g., Which socket is a thread on
4709static void __kmp_affinity_get_topology_info(kmp_affinity_t &affinity) {
4710 if (!KMP_AFFINITY_CAPABLE())
4711 return;
4712 if (affinity.type != affinity_none) {
4713 KMP_ASSERT(affinity.num_os_id_masks);
4714 KMP_ASSERT(affinity.os_id_masks);
4715 }
4716 KMP_ASSERT(affinity.num_masks);
4717 KMP_ASSERT(affinity.masks);
4718 KMP_ASSERT(__kmp_affin_fullMask);
4719
4720 int max_cpu = __kmp_affin_fullMask->get_max_cpu();
4721 int num_hw_threads = __kmp_topology->get_num_hw_threads();
4722
4723 // Allocate thread topology information
4724 if (!affinity.ids) {
4725 affinity.ids = (kmp_affinity_ids_t *)__kmp_allocate(
4726 sizeof(kmp_affinity_ids_t) * affinity.num_masks);
4727 }
4728 if (!affinity.attrs) {
4729 affinity.attrs = (kmp_affinity_attrs_t *)__kmp_allocate(
4730 sizeof(kmp_affinity_attrs_t) * affinity.num_masks);
4731 }
4732 if (!__kmp_osid_to_hwthread_map) {
4733 // Want the +1 because max_cpu should be valid index into map
4734 __kmp_osid_to_hwthread_map =
4735 (int *)__kmp_allocate(sizeof(int) * (max_cpu + 1));
4736 }
4737
4738 // Create the OS proc to hardware thread map
4739 for (int hw_thread = 0; hw_thread < num_hw_threads; ++hw_thread) {
4740 int os_id = __kmp_topology->at(hw_thread).os_id;
4741 if (KMP_CPU_ISSET(os_id, __kmp_affin_fullMask))
4742 __kmp_osid_to_hwthread_map[os_id] = hw_thread;
4743 }
4744
4745 for (unsigned i = 0; i < affinity.num_masks; ++i) {
4746 kmp_affinity_ids_t &ids = affinity.ids[i];
4747 kmp_affinity_attrs_t &attrs = affinity.attrs[i];
4748 kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.masks, i);
4749 __kmp_affinity_get_mask_topology_info(mask, ids, attrs);
4750 }
4751}
4752
4753// Called when __kmp_topology is ready
4754static void __kmp_aux_affinity_initialize_other_data(kmp_affinity_t &affinity) {
4755 // Initialize other data structures which depend on the topology
4756 if (__kmp_topology && __kmp_topology->get_num_hw_threads()) {
4757 machine_hierarchy.init(__kmp_topology->get_num_hw_threads());
4758 __kmp_affinity_get_topology_info(affinity);
4759#if KMP_WEIGHTED_ITERATIONS_SUPPORTED
4760 __kmp_first_osid_with_ecore = __kmp_get_first_osid_with_ecore();
4761#endif
4762 }
4763}
4764
4765// Create a one element mask array (set of places) which only contains the
4766// initial process's affinity mask
4767static void __kmp_create_affinity_none_places(kmp_affinity_t &affinity) {
4768 KMP_ASSERT(__kmp_affin_fullMask != NULL);
4769 KMP_ASSERT(affinity.type == affinity_none);
4770 KMP_ASSERT(__kmp_avail_proc == __kmp_topology->get_num_hw_threads());
4771 affinity.num_masks = 1;
4772 KMP_CPU_ALLOC_ARRAY(affinity.masks, affinity.num_masks);
4773 kmp_affin_mask_t *dest = KMP_CPU_INDEX(affinity.masks, 0);
4774 KMP_CPU_COPY(dest, __kmp_affin_fullMask);
4775 __kmp_aux_affinity_initialize_other_data(affinity);
4776}
4777
4778static void __kmp_aux_affinity_initialize_masks(kmp_affinity_t &affinity) {
4779 // Create the "full" mask - this defines all of the processors that we
4780 // consider to be in the machine model. If respect is set, then it is the
4781 // initialization thread's affinity mask. Otherwise, it is all processors that
4782 // we know about on the machine.
4783 int verbose = affinity.flags.verbose;
4784 const char *env_var = affinity.env_var;
4785
4786 // Already initialized
4787 if (__kmp_affin_fullMask && __kmp_affin_origMask)
4788 return;
4789
4790 if (__kmp_affin_fullMask == NULL) {
4791 KMP_CPU_ALLOC(__kmp_affin_fullMask);
4792 }
4793 if (__kmp_affin_origMask == NULL) {
4794 KMP_CPU_ALLOC(__kmp_affin_origMask);
4795 }
4796 if (KMP_AFFINITY_CAPABLE()) {
4797 __kmp_get_system_affinity(__kmp_affin_fullMask, TRUE);
4798 // Make a copy before possible expanding to the entire machine mask
4799 __kmp_affin_origMask->copy(__kmp_affin_fullMask);
4800 if (affinity.flags.respect) {
4801 // Count the number of available processors.
4802 unsigned i;
4803 __kmp_avail_proc = 0;
4804 KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
4805 if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
4806 continue;
4807 }
4809 }
4811 KMP_AFF_WARNING(affinity, ErrorInitializeAffinity);
4812 affinity.type = affinity_none;
4813 KMP_AFFINITY_DISABLE();
4814 return;
4815 }
4816
4817 if (verbose) {
4818 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4819 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4820 __kmp_affin_fullMask);
4821 KMP_INFORM(InitOSProcSetRespect, env_var, buf);
4822 }
4823 } else {
4824 if (verbose) {
4825 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4826 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4827 __kmp_affin_fullMask);
4828 KMP_INFORM(InitOSProcSetNotRespect, env_var, buf);
4829 }
4831 __kmp_affinity_entire_machine_mask(__kmp_affin_fullMask);
4832#if KMP_OS_WINDOWS
4833 if (__kmp_num_proc_groups <= 1) {
4834 // Copy expanded full mask if topology has single processor group
4835 __kmp_affin_origMask->copy(__kmp_affin_fullMask);
4836 }
4837 // Set the process affinity mask since threads' affinity
4838 // masks must be subset of process mask in Windows* OS
4839 __kmp_affin_fullMask->set_process_affinity(true);
4840#endif
4841 }
4842 }
4843}
4844
4845static bool __kmp_aux_affinity_initialize_topology(kmp_affinity_t &affinity) {
4846 bool success = false;
4847 const char *env_var = affinity.env_var;
4848 kmp_i18n_id_t msg_id = kmp_i18n_null;
4849 int verbose = affinity.flags.verbose;
4850
4851 // For backward compatibility, setting KMP_CPUINFO_FILE =>
4852 // KMP_TOPOLOGY_METHOD=cpuinfo
4853 if ((__kmp_cpuinfo_file != NULL) &&
4854 (__kmp_affinity_top_method == affinity_top_method_all)) {
4855 __kmp_affinity_top_method = affinity_top_method_cpuinfo;
4856 }
4857
4858 if (__kmp_affinity_top_method == affinity_top_method_all) {
4859// In the default code path, errors are not fatal - we just try using
4860// another method. We only emit a warning message if affinity is on, or the
4861// verbose flag is set, an the nowarnings flag was not set.
4862#if KMP_HWLOC_ENABLED
4863 if (!success &&
4864 __kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC) {
4865 if (!__kmp_hwloc_error) {
4866 success = __kmp_affinity_create_hwloc_map(&msg_id);
4867 if (!success && verbose) {
4868 KMP_INFORM(AffIgnoringHwloc, env_var);
4869 }
4870 } else if (verbose) {
4871 KMP_INFORM(AffIgnoringHwloc, env_var);
4872 }
4873 }
4874#endif // KMP_HWLOC_ENABLED
4875
4876#if KMP_ARCH_X86 || KMP_ARCH_X86_64
4877 if (!success) {
4878 success = __kmp_affinity_create_x2apicid_map(&msg_id);
4879 if (!success && verbose && msg_id != kmp_i18n_null) {
4880 KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));
4881 }
4882 }
4883 if (!success) {
4884 success = __kmp_affinity_create_apicid_map(&msg_id);
4885 if (!success && verbose && msg_id != kmp_i18n_null) {
4886 KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));
4887 }
4888 }
4889#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
4890
4891#if KMP_OS_LINUX || KMP_OS_AIX
4892 if (!success) {
4893 int line = 0;
4894 success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);
4895 if (!success && verbose && msg_id != kmp_i18n_null) {
4896 KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));
4897 }
4898 }
4899#endif /* KMP_OS_LINUX */
4900
4901#if KMP_GROUP_AFFINITY
4902 if (!success && (__kmp_num_proc_groups > 1)) {
4903 success = __kmp_affinity_create_proc_group_map(&msg_id);
4904 if (!success && verbose && msg_id != kmp_i18n_null) {
4905 KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));
4906 }
4907 }
4908#endif /* KMP_GROUP_AFFINITY */
4909
4910 if (!success) {
4911 success = __kmp_affinity_create_flat_map(&msg_id);
4912 if (!success && verbose && msg_id != kmp_i18n_null) {
4913 KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));
4914 }
4915 KMP_ASSERT(success);
4916 }
4917 }
4918
4919// If the user has specified that a paricular topology discovery method is to be
4920// used, then we abort if that method fails. The exception is group affinity,
4921// which might have been implicitly set.
4922#if KMP_HWLOC_ENABLED
4923 else if (__kmp_affinity_top_method == affinity_top_method_hwloc) {
4924 KMP_ASSERT(__kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC);
4925 success = __kmp_affinity_create_hwloc_map(&msg_id);
4926 if (!success) {
4927 KMP_ASSERT(msg_id != kmp_i18n_null);
4928 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
4929 }
4930 }
4931#endif // KMP_HWLOC_ENABLED
4932
4933#if KMP_ARCH_X86 || KMP_ARCH_X86_64
4934 else if (__kmp_affinity_top_method == affinity_top_method_x2apicid ||
4935 __kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {
4936 success = __kmp_affinity_create_x2apicid_map(&msg_id);
4937 if (!success) {
4938 KMP_ASSERT(msg_id != kmp_i18n_null);
4939 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
4940 }
4941 } else if (__kmp_affinity_top_method == affinity_top_method_apicid) {
4942 success = __kmp_affinity_create_apicid_map(&msg_id);
4943 if (!success) {
4944 KMP_ASSERT(msg_id != kmp_i18n_null);
4945 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
4946 }
4947 }
4948#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
4949
4950 else if (__kmp_affinity_top_method == affinity_top_method_cpuinfo) {
4951 int line = 0;
4952 success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);
4953 if (!success) {
4954 KMP_ASSERT(msg_id != kmp_i18n_null);
4955 const char *filename = __kmp_cpuinfo_get_filename();
4956 if (line > 0) {
4957 KMP_FATAL(FileLineMsgExiting, filename, line,
4958 __kmp_i18n_catgets(msg_id));
4959 } else {
4960 KMP_FATAL(FileMsgExiting, filename, __kmp_i18n_catgets(msg_id));
4961 }
4962 }
4963 }
4964
4965#if KMP_GROUP_AFFINITY
4966 else if (__kmp_affinity_top_method == affinity_top_method_group) {
4967 success = __kmp_affinity_create_proc_group_map(&msg_id);
4968 KMP_ASSERT(success);
4969 if (!success) {
4970 KMP_ASSERT(msg_id != kmp_i18n_null);
4971 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
4972 }
4973 }
4974#endif /* KMP_GROUP_AFFINITY */
4975
4976 else if (__kmp_affinity_top_method == affinity_top_method_flat) {
4977 success = __kmp_affinity_create_flat_map(&msg_id);
4978 // should not fail
4979 KMP_ASSERT(success);
4980 }
4981
4982 // Early exit if topology could not be created
4983 if (!__kmp_topology) {
4984 if (KMP_AFFINITY_CAPABLE()) {
4985 KMP_AFF_WARNING(affinity, ErrorInitializeAffinity);
4986 }
4987 if (nPackages > 0 && nCoresPerPkg > 0 && __kmp_nThreadsPerCore > 0 &&
4988 __kmp_ncores > 0) {
4990 __kmp_topology->canonicalize(nPackages, nCoresPerPkg,
4992 if (verbose) {
4993 __kmp_topology->print(env_var);
4994 }
4995 }
4996 return false;
4997 }
4998
4999 // Canonicalize, print (if requested), apply KMP_HW_SUBSET
5000 __kmp_topology->canonicalize();
5001 if (verbose)
5002 __kmp_topology->print(env_var);
5003 bool filtered = __kmp_topology->filter_hw_subset();
5004 if (filtered && verbose)
5005 __kmp_topology->print("KMP_HW_SUBSET");
5006 return success;
5007}
5008
5009static void __kmp_aux_affinity_initialize(kmp_affinity_t &affinity) {
5010 bool is_regular_affinity = (&affinity == &__kmp_affinity);
5011 bool is_hidden_helper_affinity = (&affinity == &__kmp_hh_affinity);
5012 const char *env_var = __kmp_get_affinity_env_var(affinity);
5013
5014 if (affinity.flags.initialized) {
5015 KMP_ASSERT(__kmp_affin_fullMask != NULL);
5016 return;
5017 }
5018
5019 if (is_regular_affinity && (!__kmp_affin_fullMask || !__kmp_affin_origMask))
5020 __kmp_aux_affinity_initialize_masks(affinity);
5021
5022 if (is_regular_affinity && !__kmp_topology) {
5023 bool success = __kmp_aux_affinity_initialize_topology(affinity);
5024 if (success) {
5025 KMP_ASSERT(__kmp_avail_proc == __kmp_topology->get_num_hw_threads());
5026 } else {
5027 affinity.type = affinity_none;
5028 KMP_AFFINITY_DISABLE();
5029 }
5030 }
5031
5032 // If KMP_AFFINITY=none, then only create the single "none" place
5033 // which is the process's initial affinity mask or the number of
5034 // hardware threads depending on respect,norespect
5035 if (affinity.type == affinity_none) {
5036 __kmp_create_affinity_none_places(affinity);
5037#if KMP_USE_HIER_SCHED
5038 __kmp_dispatch_set_hierarchy_values();
5039#endif
5040 affinity.flags.initialized = TRUE;
5041 return;
5042 }
5043
5044 __kmp_topology->set_granularity(affinity);
5045 int depth = __kmp_topology->get_depth();
5046
5047 // Create the table of masks, indexed by thread Id.
5048 unsigned numUnique = 0;
5049 int numAddrs = __kmp_topology->get_num_hw_threads();
5050 // If OMP_PLACES=cores:<attribute> specified, then attempt
5051 // to make OS Id mask table using those attributes
5052 if (affinity.core_attr_gran.valid) {
5053 __kmp_create_os_id_masks(&numUnique, affinity, [&](int idx) {
5054 KMP_ASSERT(idx >= -1);
5055 for (int i = idx + 1; i < numAddrs; ++i)
5056 if (__kmp_topology->at(i).attrs.contains(affinity.core_attr_gran))
5057 return i;
5058 return numAddrs;
5059 });
5060 if (!affinity.os_id_masks) {
5061 const char *core_attribute;
5062 if (affinity.core_attr_gran.core_eff != kmp_hw_attr_t::UNKNOWN_CORE_EFF)
5063 core_attribute = "core_efficiency";
5064 else
5065 core_attribute = "core_type";
5066 KMP_AFF_WARNING(affinity, AffIgnoringNotAvailable, env_var,
5067 core_attribute,
5068 __kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true))
5069 }
5070 }
5071 // If core attributes did not work, or none were specified,
5072 // then make OS Id mask table using typical incremental way with
5073 // checking for validity of each id at granularity level specified.
5074 if (!affinity.os_id_masks) {
5075 int gran = affinity.gran_levels;
5076 int gran_level = depth - 1 - affinity.gran_levels;
5077 if (gran >= 0 && gran_level >= 0 && gran_level < depth) {
5078 __kmp_create_os_id_masks(
5079 &numUnique, affinity, [depth, numAddrs, &affinity](int idx) {
5080 KMP_ASSERT(idx >= -1);
5081 int gran = affinity.gran_levels;
5082 int gran_level = depth - 1 - affinity.gran_levels;
5083 for (int i = idx + 1; i < numAddrs; ++i)
5084 if ((gran >= depth) ||
5085 (gran < depth && __kmp_topology->at(i).ids[gran_level] !=
5087 return i;
5088 return numAddrs;
5089 });
5090 }
5091 }
5092 // Final attempt to make OS Id mask table using typical incremental way.
5093 if (!affinity.os_id_masks) {
5094 __kmp_create_os_id_masks(&numUnique, affinity, [](int idx) {
5095 KMP_ASSERT(idx >= -1);
5096 return idx + 1;
5097 });
5098 }
5099
5100 switch (affinity.type) {
5101
5102 case affinity_explicit:
5103 KMP_DEBUG_ASSERT(affinity.proclist != NULL);
5104 if (is_hidden_helper_affinity ||
5105 __kmp_nested_proc_bind.bind_types[0] == proc_bind_intel) {
5106 __kmp_affinity_process_proclist(affinity);
5107 } else {
5108 __kmp_affinity_process_placelist(affinity);
5109 }
5110 if (affinity.num_masks == 0) {
5111 KMP_AFF_WARNING(affinity, AffNoValidProcID);
5112 affinity.type = affinity_none;
5113 __kmp_create_affinity_none_places(affinity);
5114 affinity.flags.initialized = TRUE;
5115 return;
5116 }
5117 break;
5118
5119 // The other affinity types rely on sorting the hardware threads according to
5120 // some permutation of the machine topology tree. Set affinity.compact
5121 // and affinity.offset appropriately, then jump to a common code
5122 // fragment to do the sort and create the array of affinity masks.
5123 case affinity_logical:
5124 affinity.compact = 0;
5125 if (affinity.offset) {
5126 affinity.offset =
5127 __kmp_nThreadsPerCore * affinity.offset % __kmp_avail_proc;
5128 }
5129 goto sortTopology;
5130
5131 case affinity_physical:
5132 if (__kmp_nThreadsPerCore > 1) {
5133 affinity.compact = 1;
5134 if (affinity.compact >= depth) {
5135 affinity.compact = 0;
5136 }
5137 } else {
5138 affinity.compact = 0;
5139 }
5140 if (affinity.offset) {
5141 affinity.offset =
5142 __kmp_nThreadsPerCore * affinity.offset % __kmp_avail_proc;
5143 }
5144 goto sortTopology;
5145
5146 case affinity_scatter:
5147 if (affinity.compact >= depth) {
5148 affinity.compact = 0;
5149 } else {
5150 affinity.compact = depth - 1 - affinity.compact;
5151 }
5152 goto sortTopology;
5153
5154 case affinity_compact:
5155 if (affinity.compact >= depth) {
5156 affinity.compact = depth - 1;
5157 }
5158 goto sortTopology;
5159
5160 case affinity_balanced:
5161 if (depth <= 1 || is_hidden_helper_affinity) {
5162 KMP_AFF_WARNING(affinity, AffBalancedNotAvail, env_var);
5163 affinity.type = affinity_none;
5164 __kmp_create_affinity_none_places(affinity);
5165 affinity.flags.initialized = TRUE;
5166 return;
5167 } else if (!__kmp_topology->is_uniform()) {
5168 // Save the depth for further usage
5169 __kmp_aff_depth = depth;
5170
5171 int core_level =
5172 __kmp_affinity_find_core_level(__kmp_avail_proc, depth - 1);
5173 int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc, depth - 1,
5174 core_level);
5175 int maxprocpercore = __kmp_affinity_max_proc_per_core(
5176 __kmp_avail_proc, depth - 1, core_level);
5177
5178 int nproc = ncores * maxprocpercore;
5179 if ((nproc < 2) || (nproc < __kmp_avail_proc)) {
5180 KMP_AFF_WARNING(affinity, AffBalancedNotAvail, env_var);
5181 affinity.type = affinity_none;
5182 __kmp_create_affinity_none_places(affinity);
5183 affinity.flags.initialized = TRUE;
5184 return;
5185 }
5186
5187 procarr = (int *)__kmp_allocate(sizeof(int) * nproc);
5188 for (int i = 0; i < nproc; i++) {
5189 procarr[i] = -1;
5190 }
5191
5192 int lastcore = -1;
5193 int inlastcore = 0;
5194 for (int i = 0; i < __kmp_avail_proc; i++) {
5195 int proc = __kmp_topology->at(i).os_id;
5196 int core = __kmp_affinity_find_core(i, depth - 1, core_level);
5197
5198 if (core == lastcore) {
5199 inlastcore++;
5200 } else {
5201 inlastcore = 0;
5202 }
5203 lastcore = core;
5204
5205 procarr[core * maxprocpercore + inlastcore] = proc;
5206 }
5207 }
5208 if (affinity.compact >= depth) {
5209 affinity.compact = depth - 1;
5210 }
5211
5212 sortTopology:
5213 // Allocate the gtid->affinity mask table.
5214 if (affinity.flags.dups) {
5215 affinity.num_masks = __kmp_avail_proc;
5216 } else {
5217 affinity.num_masks = numUnique;
5218 }
5219
5220 if ((__kmp_nested_proc_bind.bind_types[0] != proc_bind_intel) &&
5222 ((unsigned)__kmp_affinity_num_places < affinity.num_masks) &&
5223 !is_hidden_helper_affinity) {
5224 affinity.num_masks = __kmp_affinity_num_places;
5225 }
5226
5227 KMP_CPU_ALLOC_ARRAY(affinity.masks, affinity.num_masks);
5228
5229 // Sort the topology table according to the current setting of
5230 // affinity.compact, then fill out affinity.masks.
5231 __kmp_topology->sort_compact(affinity);
5232 {
5233 int i;
5234 unsigned j;
5235 int num_hw_threads = __kmp_topology->get_num_hw_threads();
5236 kmp_full_mask_modifier_t full_mask;
5237 for (i = 0, j = 0; i < num_hw_threads; i++) {
5238 if ((!affinity.flags.dups) && (!__kmp_topology->at(i).leader)) {
5239 continue;
5240 }
5241 int osId = __kmp_topology->at(i).os_id;
5242
5243 kmp_affin_mask_t *src = KMP_CPU_INDEX(affinity.os_id_masks, osId);
5244 if (KMP_CPU_ISEMPTY(src))
5245 continue;
5246 kmp_affin_mask_t *dest = KMP_CPU_INDEX(affinity.masks, j);
5247 KMP_ASSERT(KMP_CPU_ISSET(osId, src));
5248 KMP_CPU_COPY(dest, src);
5249 full_mask.include(src);
5250 if (++j >= affinity.num_masks) {
5251 break;
5252 }
5253 }
5254 KMP_DEBUG_ASSERT(j == affinity.num_masks);
5255 // See if the places list further restricts or changes the full mask
5256 if (full_mask.restrict_to_mask() && affinity.flags.verbose) {
5257 __kmp_topology->print(env_var);
5258 }
5259 }
5260 // Sort the topology back using ids
5261 __kmp_topology->sort_ids();
5262 break;
5263
5264 default:
5265 KMP_ASSERT2(0, "Unexpected affinity setting");
5266 }
5267 __kmp_aux_affinity_initialize_other_data(affinity);
5268 affinity.flags.initialized = TRUE;
5269}
5270
5271void __kmp_affinity_initialize(kmp_affinity_t &affinity) {
5272 // Much of the code above was written assuming that if a machine was not
5273 // affinity capable, then affinity type == affinity_none.
5274 // We now explicitly represent this as affinity type == affinity_disabled.
5275 // There are too many checks for affinity type == affinity_none in this code.
5276 // Instead of trying to change them all, check if
5277 // affinity type == affinity_disabled, and if so, slam it with affinity_none,
5278 // call the real initialization routine, then restore affinity type to
5279 // affinity_disabled.
5280 int disabled = (affinity.type == affinity_disabled);
5281 if (!KMP_AFFINITY_CAPABLE())
5282 KMP_ASSERT(disabled);
5283 if (disabled)
5284 affinity.type = affinity_none;
5285 __kmp_aux_affinity_initialize(affinity);
5286 if (disabled)
5287 affinity.type = affinity_disabled;
5288}
5289
5290void __kmp_affinity_uninitialize(void) {
5291 for (kmp_affinity_t *affinity : __kmp_affinities) {
5292 if (affinity->masks != NULL)
5293 KMP_CPU_FREE_ARRAY(affinity->masks, affinity->num_masks);
5294 if (affinity->os_id_masks != NULL)
5295 KMP_CPU_FREE_ARRAY(affinity->os_id_masks, affinity->num_os_id_masks);
5296 if (affinity->proclist != NULL)
5297 KMP_INTERNAL_FREE(affinity->proclist);
5298 if (affinity->ids != NULL)
5299 __kmp_free(affinity->ids);
5300 if (affinity->attrs != NULL)
5301 __kmp_free(affinity->attrs);
5302 *affinity = KMP_AFFINITY_INIT(affinity->env_var);
5303 }
5304 if (__kmp_affin_fullMask != NULL) {
5305 KMP_CPU_FREE(__kmp_affin_fullMask);
5306 __kmp_affin_fullMask = NULL;
5307 }
5308 __kmp_avail_proc = 0;
5309 if (__kmp_affin_origMask != NULL) {
5310 if (KMP_AFFINITY_CAPABLE()) {
5311#if KMP_OS_AIX
5312 // Uninitialize by unbinding the thread.
5313 bindprocessor(BINDTHREAD, thread_self(), PROCESSOR_CLASS_ANY);
5314#else
5315 __kmp_set_system_affinity(__kmp_affin_origMask, FALSE);
5316#endif
5317 }
5318 KMP_CPU_FREE(__kmp_affin_origMask);
5319 __kmp_affin_origMask = NULL;
5320 }
5322 if (procarr != NULL) {
5323 __kmp_free(procarr);
5324 procarr = NULL;
5325 }
5326 if (__kmp_osid_to_hwthread_map) {
5327 __kmp_free(__kmp_osid_to_hwthread_map);
5328 __kmp_osid_to_hwthread_map = NULL;
5329 }
5330#if KMP_HWLOC_ENABLED
5331 if (__kmp_hwloc_topology != NULL) {
5332 hwloc_topology_destroy(__kmp_hwloc_topology);
5333 __kmp_hwloc_topology = NULL;
5334 }
5335#endif // KMP_HWLOC_ENABLED
5336 if (__kmp_hw_subset) {
5338 __kmp_hw_subset = nullptr;
5339 }
5340 if (__kmp_topology) {
5342 __kmp_topology = nullptr;
5343 }
5344 KMPAffinity::destroy_api();
5345}
5346
5347static void __kmp_select_mask_by_gtid(int gtid, const kmp_affinity_t *affinity,
5348 int *place, kmp_affin_mask_t **mask) {
5349 int mask_idx;
5350 bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);
5351 if (is_hidden_helper)
5352 // The first gtid is the regular primary thread, the second gtid is the main
5353 // thread of hidden team which does not participate in task execution.
5354 mask_idx = gtid - 2;
5355 else
5356 mask_idx = __kmp_adjust_gtid_for_hidden_helpers(gtid);
5357 KMP_DEBUG_ASSERT(affinity->num_masks > 0);
5358 *place = (mask_idx + affinity->offset) % affinity->num_masks;
5359 *mask = KMP_CPU_INDEX(affinity->masks, *place);
5360}
5361
5362// This function initializes the per-thread data concerning affinity including
5363// the mask and topology information
5364void __kmp_affinity_set_init_mask(int gtid, int isa_root) {
5365
5367
5368 // Set the thread topology information to default of unknown
5369 for (int id = 0; id < KMP_HW_LAST; ++id)
5370 th->th.th_topology_ids.ids[id] = kmp_hw_thread_t::UNKNOWN_ID;
5371 th->th.th_topology_attrs = KMP_AFFINITY_ATTRS_UNKNOWN;
5372
5373 if (!KMP_AFFINITY_CAPABLE()) {
5374 return;
5375 }
5376
5377 if (th->th.th_affin_mask == NULL) {
5378 KMP_CPU_ALLOC(th->th.th_affin_mask);
5379 } else {
5380 KMP_CPU_ZERO(th->th.th_affin_mask);
5381 }
5382
5383 // Copy the thread mask to the kmp_info_t structure. If
5384 // __kmp_affinity.type == affinity_none, copy the "full" mask, i.e.
5385 // one that has all of the OS proc ids set, or if
5386 // __kmp_affinity.flags.respect is set, then the full mask is the
5387 // same as the mask of the initialization thread.
5388 kmp_affin_mask_t *mask;
5389 int i;
5390 const kmp_affinity_t *affinity;
5391 bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);
5392
5393 if (is_hidden_helper)
5394 affinity = &__kmp_hh_affinity;
5395 else
5396 affinity = &__kmp_affinity;
5397
5398 if (KMP_AFFINITY_NON_PROC_BIND || is_hidden_helper) {
5399 if ((affinity->type == affinity_none) ||
5400 (affinity->type == affinity_balanced) ||
5402#if KMP_GROUP_AFFINITY
5403 if (__kmp_num_proc_groups > 1) {
5404 return;
5405 }
5406#endif
5407 KMP_ASSERT(__kmp_affin_fullMask != NULL);
5408 i = 0;
5409 mask = __kmp_affin_fullMask;
5410 } else {
5411 __kmp_select_mask_by_gtid(gtid, affinity, &i, &mask);
5412 }
5413 } else {
5414 if (!isa_root || __kmp_nested_proc_bind.bind_types[0] == proc_bind_false) {
5415#if KMP_GROUP_AFFINITY
5416 if (__kmp_num_proc_groups > 1) {
5417 return;
5418 }
5419#endif
5420 KMP_ASSERT(__kmp_affin_fullMask != NULL);
5421 i = KMP_PLACE_ALL;
5422 mask = __kmp_affin_fullMask;
5423 } else {
5424 __kmp_select_mask_by_gtid(gtid, affinity, &i, &mask);
5425 }
5426 }
5427
5428 th->th.th_current_place = i;
5429 if (isa_root && !is_hidden_helper) {
5430 th->th.th_new_place = i;
5431 th->th.th_first_place = 0;
5432 th->th.th_last_place = affinity->num_masks - 1;
5433 } else if (KMP_AFFINITY_NON_PROC_BIND) {
5434 // When using a Non-OMP_PROC_BIND affinity method,
5435 // set all threads' place-partition-var to the entire place list
5436 th->th.th_first_place = 0;
5437 th->th.th_last_place = affinity->num_masks - 1;
5438 }
5439 // Copy topology information associated with the place
5440 if (i >= 0) {
5441 th->th.th_topology_ids = __kmp_affinity.ids[i];
5442 th->th.th_topology_attrs = __kmp_affinity.attrs[i];
5443 }
5444
5445 if (i == KMP_PLACE_ALL) {
5446 KA_TRACE(100, ("__kmp_affinity_set_init_mask: setting T#%d to all places\n",
5447 gtid));
5448 } else {
5449 KA_TRACE(100, ("__kmp_affinity_set_init_mask: setting T#%d to place %d\n",
5450 gtid, i));
5451 }
5452
5453 KMP_CPU_COPY(th->th.th_affin_mask, mask);
5454}
5455
5456void __kmp_affinity_bind_init_mask(int gtid) {
5457 if (!KMP_AFFINITY_CAPABLE()) {
5458 return;
5459 }
5461 const kmp_affinity_t *affinity;
5462 const char *env_var;
5463 bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);
5464
5465 if (is_hidden_helper)
5466 affinity = &__kmp_hh_affinity;
5467 else
5468 affinity = &__kmp_affinity;
5469 env_var = __kmp_get_affinity_env_var(*affinity, /*for_binding=*/true);
5470 /* to avoid duplicate printing (will be correctly printed on barrier) */
5471 if (affinity->flags.verbose && (affinity->type == affinity_none ||
5472 (th->th.th_current_place != KMP_PLACE_ALL &&
5473 affinity->type != affinity_balanced)) &&
5475 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5476 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5477 th->th.th_affin_mask);
5478 KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),
5479 gtid, buf);
5480 }
5481
5482#if KMP_OS_WINDOWS
5483 // On Windows* OS, the process affinity mask might have changed. If the user
5484 // didn't request affinity and this call fails, just continue silently.
5485 // See CQ171393.
5486 if (affinity->type == affinity_none) {
5487 __kmp_set_system_affinity(th->th.th_affin_mask, FALSE);
5488 } else
5489#endif
5490#if !KMP_OS_AIX
5491 // Do not set the full mask as the init mask on AIX.
5492 __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
5493#endif
5494}
5495
5496void __kmp_affinity_bind_place(int gtid) {
5497 // Hidden helper threads should not be affected by OMP_PLACES/OMP_PROC_BIND
5498 if (!KMP_AFFINITY_CAPABLE() || KMP_HIDDEN_HELPER_THREAD(gtid)) {
5499 return;
5500 }
5501
5503
5504 KA_TRACE(100, ("__kmp_affinity_bind_place: binding T#%d to place %d (current "
5505 "place = %d)\n",
5506 gtid, th->th.th_new_place, th->th.th_current_place));
5507
5508 // Check that the new place is within this thread's partition.
5509 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
5510 KMP_ASSERT(th->th.th_new_place >= 0);
5511 KMP_ASSERT((unsigned)th->th.th_new_place <= __kmp_affinity.num_masks);
5512 if (th->th.th_first_place <= th->th.th_last_place) {
5513 KMP_ASSERT((th->th.th_new_place >= th->th.th_first_place) &&
5514 (th->th.th_new_place <= th->th.th_last_place));
5515 } else {
5516 KMP_ASSERT((th->th.th_new_place <= th->th.th_first_place) ||
5517 (th->th.th_new_place >= th->th.th_last_place));
5518 }
5519
5520 // Copy the thread mask to the kmp_info_t structure,
5521 // and set this thread's affinity.
5522 kmp_affin_mask_t *mask =
5523 KMP_CPU_INDEX(__kmp_affinity.masks, th->th.th_new_place);
5524 KMP_CPU_COPY(th->th.th_affin_mask, mask);
5525 th->th.th_current_place = th->th.th_new_place;
5526
5527 if (__kmp_affinity.flags.verbose) {
5528 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5529 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5530 th->th.th_affin_mask);
5531 KMP_INFORM(BoundToOSProcSet, "OMP_PROC_BIND", (kmp_int32)getpid(),
5532 __kmp_gettid(), gtid, buf);
5533 }
5534 __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
5535}
5536
5537int __kmp_aux_set_affinity(void **mask) {
5538 int gtid;
5539 kmp_info_t *th;
5540 int retval;
5541
5542 if (!KMP_AFFINITY_CAPABLE()) {
5543 return -1;
5544 }
5545
5546 gtid = __kmp_entry_gtid();
5547 KA_TRACE(
5548 1000, (""); {
5549 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5550 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5551 (kmp_affin_mask_t *)(*mask));
5553 "kmp_set_affinity: setting affinity mask for thread %d = %s\n",
5554 gtid, buf);
5555 });
5556
5558 if ((mask == NULL) || (*mask == NULL)) {
5559 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
5560 } else {
5561 unsigned proc;
5562 int num_procs = 0;
5563
5564 KMP_CPU_SET_ITERATE(proc, ((kmp_affin_mask_t *)(*mask))) {
5565 if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
5566 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
5567 }
5568 if (!KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask))) {
5569 continue;
5570 }
5571 num_procs++;
5572 }
5573 if (num_procs == 0) {
5574 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
5575 }
5576
5577#if KMP_GROUP_AFFINITY
5578 if (__kmp_get_proc_group((kmp_affin_mask_t *)(*mask)) < 0) {
5579 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
5580 }
5581#endif /* KMP_GROUP_AFFINITY */
5582 }
5583 }
5584
5585 th = __kmp_threads[gtid];
5586 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
5587 retval = __kmp_set_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
5588 if (retval == 0) {
5589 KMP_CPU_COPY(th->th.th_affin_mask, (kmp_affin_mask_t *)(*mask));
5590 }
5591
5592 th->th.th_current_place = KMP_PLACE_UNDEFINED;
5593 th->th.th_new_place = KMP_PLACE_UNDEFINED;
5594 th->th.th_first_place = 0;
5595 th->th.th_last_place = __kmp_affinity.num_masks - 1;
5596
5597 // Turn off 4.0 affinity for the current tread at this parallel level.
5598 th->th.th_current_task->td_icvs.proc_bind = proc_bind_false;
5599
5600 return retval;
5601}
5602
5603int __kmp_aux_get_affinity(void **mask) {
5604 int gtid;
5605 int retval;
5606#if KMP_OS_WINDOWS || KMP_OS_AIX || KMP_DEBUG
5607 kmp_info_t *th;
5608#endif
5609 if (!KMP_AFFINITY_CAPABLE()) {
5610 return -1;
5611 }
5612
5613 gtid = __kmp_entry_gtid();
5614#if KMP_OS_WINDOWS || KMP_OS_AIX || KMP_DEBUG
5615 th = __kmp_threads[gtid];
5616#else
5617 (void)gtid; // unused variable
5618#endif
5619 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
5620
5621 KA_TRACE(
5622 1000, (""); {
5623 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5624 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5625 th->th.th_affin_mask);
5627 "kmp_get_affinity: stored affinity mask for thread %d = %s\n", gtid,
5628 buf);
5629 });
5630
5632 if ((mask == NULL) || (*mask == NULL)) {
5633 KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity");
5634 }
5635 }
5636
5637#if !KMP_OS_WINDOWS && !KMP_OS_AIX
5638
5639 retval = __kmp_get_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
5640 KA_TRACE(
5641 1000, (""); {
5642 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5643 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5644 (kmp_affin_mask_t *)(*mask));
5646 "kmp_get_affinity: system affinity mask for thread %d = %s\n", gtid,
5647 buf);
5648 });
5649 return retval;
5650
5651#else
5652 (void)retval;
5653
5654 KMP_CPU_COPY((kmp_affin_mask_t *)(*mask), th->th.th_affin_mask);
5655 return 0;
5656
5657#endif /* !KMP_OS_WINDOWS && !KMP_OS_AIX */
5658}
5659
5660int __kmp_aux_get_affinity_max_proc() {
5661 if (!KMP_AFFINITY_CAPABLE()) {
5662 return 0;
5663 }
5664#if KMP_GROUP_AFFINITY
5665 if (__kmp_num_proc_groups > 1) {
5666 return (int)(__kmp_num_proc_groups * sizeof(DWORD_PTR) * CHAR_BIT);
5667 }
5668#endif
5669 return __kmp_xproc;
5670}
5671
5672int __kmp_aux_set_affinity_mask_proc(int proc, void **mask) {
5673 if (!KMP_AFFINITY_CAPABLE()) {
5674 return -1;
5675 }
5676
5677 KA_TRACE(
5678 1000, (""); {
5679 int gtid = __kmp_entry_gtid();
5680 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5681 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5682 (kmp_affin_mask_t *)(*mask));
5683 __kmp_debug_printf("kmp_set_affinity_mask_proc: setting proc %d in "
5684 "affinity mask for thread %d = %s\n",
5685 proc, gtid, buf);
5686 });
5687
5689 if ((mask == NULL) || (*mask == NULL)) {
5690 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity_mask_proc");
5691 }
5692 }
5693
5694 if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
5695 return -1;
5696 }
5697 if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
5698 return -2;
5699 }
5700
5701 KMP_CPU_SET(proc, (kmp_affin_mask_t *)(*mask));
5702 return 0;
5703}
5704
5705int __kmp_aux_unset_affinity_mask_proc(int proc, void **mask) {
5706 if (!KMP_AFFINITY_CAPABLE()) {
5707 return -1;
5708 }
5709
5710 KA_TRACE(
5711 1000, (""); {
5712 int gtid = __kmp_entry_gtid();
5713 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5714 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5715 (kmp_affin_mask_t *)(*mask));
5716 __kmp_debug_printf("kmp_unset_affinity_mask_proc: unsetting proc %d in "
5717 "affinity mask for thread %d = %s\n",
5718 proc, gtid, buf);
5719 });
5720
5722 if ((mask == NULL) || (*mask == NULL)) {
5723 KMP_FATAL(AffinityInvalidMask, "kmp_unset_affinity_mask_proc");
5724 }
5725 }
5726
5727 if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
5728 return -1;
5729 }
5730 if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
5731 return -2;
5732 }
5733
5734 KMP_CPU_CLR(proc, (kmp_affin_mask_t *)(*mask));
5735 return 0;
5736}
5737
5738int __kmp_aux_get_affinity_mask_proc(int proc, void **mask) {
5739 if (!KMP_AFFINITY_CAPABLE()) {
5740 return -1;
5741 }
5742
5743 KA_TRACE(
5744 1000, (""); {
5745 int gtid = __kmp_entry_gtid();
5746 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5747 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
5748 (kmp_affin_mask_t *)(*mask));
5749 __kmp_debug_printf("kmp_get_affinity_mask_proc: getting proc %d in "
5750 "affinity mask for thread %d = %s\n",
5751 proc, gtid, buf);
5752 });
5753
5755 if ((mask == NULL) || (*mask == NULL)) {
5756 KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity_mask_proc");
5757 }
5758 }
5759
5760 if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
5761 return -1;
5762 }
5763 if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
5764 return 0;
5765 }
5766
5767 return KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask));
5768}
5769
5770#if KMP_WEIGHTED_ITERATIONS_SUPPORTED
5771// Returns first os proc id with ATOM core
5772int __kmp_get_first_osid_with_ecore(void) {
5773 int low = 0;
5774 int high = __kmp_topology->get_num_hw_threads() - 1;
5775 int mid = 0;
5776 while (high - low > 1) {
5777 mid = (high + low) / 2;
5778 if (__kmp_topology->at(mid).attrs.get_core_type() ==
5779 KMP_HW_CORE_TYPE_CORE) {
5780 low = mid + 1;
5781 } else {
5782 high = mid;
5783 }
5784 }
5785 if (__kmp_topology->at(mid).attrs.get_core_type() == KMP_HW_CORE_TYPE_ATOM) {
5786 return mid;
5787 }
5788 return -1;
5789}
5790#endif
5791
5792// Dynamic affinity settings - Affinity balanced
5793void __kmp_balanced_affinity(kmp_info_t *th, int nthreads) {
5794 KMP_DEBUG_ASSERT(th);
5795 bool fine_gran = true;
5796 int tid = th->th.th_info.ds.ds_tid;
5797 const char *env_var = "KMP_AFFINITY";
5798
5799 // Do not perform balanced affinity for the hidden helper threads
5801 return;
5802
5803 switch (__kmp_affinity.gran) {
5804 case KMP_HW_THREAD:
5805 break;
5806 case KMP_HW_CORE:
5807 if (__kmp_nThreadsPerCore > 1) {
5808 fine_gran = false;
5809 }
5810 break;
5811 case KMP_HW_SOCKET:
5812 if (nCoresPerPkg > 1) {
5813 fine_gran = false;
5814 }
5815 break;
5816 default:
5817 fine_gran = false;
5818 }
5819
5820 if (__kmp_topology->is_uniform()) {
5821 int coreID;
5822 int threadID;
5823 // Number of hyper threads per core in HT machine
5824 int __kmp_nth_per_core = __kmp_avail_proc / __kmp_ncores;
5825 // Number of cores
5826 int ncores = __kmp_ncores;
5827 if ((nPackages > 1) && (__kmp_nth_per_core <= 1)) {
5828 __kmp_nth_per_core = __kmp_avail_proc / nPackages;
5829 ncores = nPackages;
5830 }
5831 // How many threads will be bound to each core
5832 int chunk = nthreads / ncores;
5833 // How many cores will have an additional thread bound to it - "big cores"
5834 int big_cores = nthreads % ncores;
5835 // Number of threads on the big cores
5836 int big_nth = (chunk + 1) * big_cores;
5837 if (tid < big_nth) {
5838 coreID = tid / (chunk + 1);
5839 threadID = (tid % (chunk + 1)) % __kmp_nth_per_core;
5840 } else { // tid >= big_nth
5841 coreID = (tid - big_cores) / chunk;
5842 threadID = ((tid - big_cores) % chunk) % __kmp_nth_per_core;
5843 }
5844 KMP_DEBUG_ASSERT2(KMP_AFFINITY_CAPABLE(),
5845 "Illegal set affinity operation when not capable");
5846
5847 kmp_affin_mask_t *mask = th->th.th_affin_mask;
5848 KMP_CPU_ZERO(mask);
5849
5850 if (fine_gran) {
5851 int osID =
5852 __kmp_topology->at(coreID * __kmp_nth_per_core + threadID).os_id;
5853 KMP_CPU_SET(osID, mask);
5854 } else {
5855 for (int i = 0; i < __kmp_nth_per_core; i++) {
5856 int osID;
5857 osID = __kmp_topology->at(coreID * __kmp_nth_per_core + i).os_id;
5858 KMP_CPU_SET(osID, mask);
5859 }
5860 }
5861 if (__kmp_affinity.flags.verbose) {
5862 char buf[KMP_AFFIN_MASK_PRINT_LEN];
5863 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
5864 KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),
5865 tid, buf);
5866 }
5867 __kmp_affinity_get_thread_topology_info(th);
5868 __kmp_set_system_affinity(mask, TRUE);
5869 } else { // Non-uniform topology
5870
5871 kmp_affin_mask_t *mask = th->th.th_affin_mask;
5872 KMP_CPU_ZERO(mask);
5873
5874 int core_level =
5875 __kmp_affinity_find_core_level(__kmp_avail_proc, __kmp_aff_depth - 1);
5876 int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc,
5877 __kmp_aff_depth - 1, core_level);
5878 int nth_per_core = __kmp_affinity_max_proc_per_core(
5879 __kmp_avail_proc, __kmp_aff_depth - 1, core_level);
5880
5881 // For performance gain consider the special case nthreads ==
5882 // __kmp_avail_proc
5883 if (nthreads == __kmp_avail_proc) {
5884 if (fine_gran) {
5885 int osID = __kmp_topology->at(tid).os_id;
5886 KMP_CPU_SET(osID, mask);
5887 } else {
5888 int core =
5889 __kmp_affinity_find_core(tid, __kmp_aff_depth - 1, core_level);
5890 for (int i = 0; i < __kmp_avail_proc; i++) {
5891 int osID = __kmp_topology->at(i).os_id;
5892 if (__kmp_affinity_find_core(i, __kmp_aff_depth - 1, core_level) ==
5893 core) {
5894 KMP_CPU_SET(osID, mask);
5895 }
5896 }
5897 }
5898 } else if (nthreads <= ncores) {
5899
5900 int core = 0;
5901 for (int i = 0; i < ncores; i++) {
5902 // Check if this core from procarr[] is in the mask
5903 int in_mask = 0;
5904 for (int j = 0; j < nth_per_core; j++) {
5905 if (procarr[i * nth_per_core + j] != -1) {
5906 in_mask = 1;
5907 break;
5908 }
5909 }
5910 if (in_mask) {
5911 if (tid == core) {
5912 for (int j = 0; j < nth_per_core; j++) {
5913 int osID = procarr[i * nth_per_core + j];
5914 if (osID != -1) {
5915 KMP_CPU_SET(osID, mask);
5916 // For fine granularity it is enough to set the first available
5917 // osID for this core
5918 if (fine_gran) {
5919 break;
5920 }
5921 }
5922 }
5923 break;
5924 } else {
5925 core++;
5926 }
5927 }
5928 }
5929 } else { // nthreads > ncores
5930 // Array to save the number of processors at each core
5931 int *nproc_at_core = (int *)KMP_ALLOCA(sizeof(int) * ncores);
5932 // Array to save the number of cores with "x" available processors;
5933 int *ncores_with_x_procs =
5934 (int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));
5935 // Array to save the number of cores with # procs from x to nth_per_core
5936 int *ncores_with_x_to_max_procs =
5937 (int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));
5938
5939 for (int i = 0; i <= nth_per_core; i++) {
5940 ncores_with_x_procs[i] = 0;
5941 ncores_with_x_to_max_procs[i] = 0;
5942 }
5943
5944 for (int i = 0; i < ncores; i++) {
5945 int cnt = 0;
5946 for (int j = 0; j < nth_per_core; j++) {
5947 if (procarr[i * nth_per_core + j] != -1) {
5948 cnt++;
5949 }
5950 }
5951 nproc_at_core[i] = cnt;
5952 ncores_with_x_procs[cnt]++;
5953 }
5954
5955 for (int i = 0; i <= nth_per_core; i++) {
5956 for (int j = i; j <= nth_per_core; j++) {
5957 ncores_with_x_to_max_procs[i] += ncores_with_x_procs[j];
5958 }
5959 }
5960
5961 // Max number of processors
5962 int nproc = nth_per_core * ncores;
5963 // An array to keep number of threads per each context
5964 int *newarr = (int *)__kmp_allocate(sizeof(int) * nproc);
5965 for (int i = 0; i < nproc; i++) {
5966 newarr[i] = 0;
5967 }
5968
5969 int nth = nthreads;
5970 int flag = 0;
5971 while (nth > 0) {
5972 for (int j = 1; j <= nth_per_core; j++) {
5973 int cnt = ncores_with_x_to_max_procs[j];
5974 for (int i = 0; i < ncores; i++) {
5975 // Skip the core with 0 processors
5976 if (nproc_at_core[i] == 0) {
5977 continue;
5978 }
5979 for (int k = 0; k < nth_per_core; k++) {
5980 if (procarr[i * nth_per_core + k] != -1) {
5981 if (newarr[i * nth_per_core + k] == 0) {
5982 newarr[i * nth_per_core + k] = 1;
5983 cnt--;
5984 nth--;
5985 break;
5986 } else {
5987 if (flag != 0) {
5988 newarr[i * nth_per_core + k]++;
5989 cnt--;
5990 nth--;
5991 break;
5992 }
5993 }
5994 }
5995 }
5996 if (cnt == 0 || nth == 0) {
5997 break;
5998 }
5999 }
6000 if (nth == 0) {
6001 break;
6002 }
6003 }
6004 flag = 1;
6005 }
6006 int sum = 0;
6007 for (int i = 0; i < nproc; i++) {
6008 sum += newarr[i];
6009 if (sum > tid) {
6010 if (fine_gran) {
6011 int osID = procarr[i];
6012 KMP_CPU_SET(osID, mask);
6013 } else {
6014 int coreID = i / nth_per_core;
6015 for (int ii = 0; ii < nth_per_core; ii++) {
6016 int osID = procarr[coreID * nth_per_core + ii];
6017 if (osID != -1) {
6018 KMP_CPU_SET(osID, mask);
6019 }
6020 }
6021 }
6022 break;
6023 }
6024 }
6025 __kmp_free(newarr);
6026 }
6027
6028 if (__kmp_affinity.flags.verbose) {
6029 char buf[KMP_AFFIN_MASK_PRINT_LEN];
6030 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
6031 KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),
6032 tid, buf);
6033 }
6034 __kmp_affinity_get_thread_topology_info(th);
6035 __kmp_set_system_affinity(mask, TRUE);
6036 }
6037}
6038
6039#if KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \
6040 KMP_OS_AIX
6041// We don't need this entry for Windows because
6042// there is GetProcessAffinityMask() api
6043//
6044// The intended usage is indicated by these steps:
6045// 1) The user gets the current affinity mask
6046// 2) Then sets the affinity by calling this function
6047// 3) Error check the return value
6048// 4) Use non-OpenMP parallelization
6049// 5) Reset the affinity to what was stored in step 1)
6050#ifdef __cplusplus
6051extern "C"
6052#endif
6053 int
6054 kmp_set_thread_affinity_mask_initial()
6055// the function returns 0 on success,
6056// -1 if we cannot bind thread
6057// >0 (errno) if an error happened during binding
6058{
6059 int gtid = __kmp_get_gtid();
6060 if (gtid < 0) {
6061 // Do not touch non-omp threads
6062 KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
6063 "non-omp thread, returning\n"));
6064 return -1;
6065 }
6066 if (!KMP_AFFINITY_CAPABLE() || !__kmp_init_middle) {
6067 KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
6068 "affinity not initialized, returning\n"));
6069 return -1;
6070 }
6071 KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
6072 "set full mask for thread %d\n",
6073 gtid));
6074 KMP_DEBUG_ASSERT(__kmp_affin_fullMask != NULL);
6075#if KMP_OS_AIX
6076 return bindprocessor(BINDTHREAD, thread_self(), PROCESSOR_CLASS_ANY);
6077#else
6078 return __kmp_set_system_affinity(__kmp_affin_fullMask, FALSE);
6079#endif
6080}
6081#endif
6082
6083#endif // KMP_AFFINITY_SUPPORTED
char buf[BUFFER_SIZE]
bool is_absolute() const
void canonicalize(const kmp_topology_t *top)
static void deallocate(kmp_hw_subset_t *subset)
int get_depth() const
static const int USE_ALL
const item_t & at(int index) const
kmp_hw_attr_t attrs
static const int UNKNOWN_ID
int sub_ids[KMP_HW_LAST]
static int compare_compact(const void *a, const void *b)
void print() const
static int compare_ids(const void *a, const void *b)
static const int MULTIPLE_ID
int ids[KMP_HW_LAST]
This class safely opens and closes a C-style FILE* object using RAII semantics.
Definition kmp.h:4711
int try_open(const char *filename, const char *mode)
Instead of erroring out, return non-zero when unsuccessful fopen() for any reason.
Definition kmp.h:4752
void dump() const
int get_level(kmp_hw_t type) const
int get_count(int level) const
int get_ratio(int level) const
static void deallocate(kmp_topology_t *)
kmp_hw_t get_equivalent_type(kmp_hw_t type) const
void set_equivalent_type(kmp_hw_t type1, kmp_hw_t type2)
int get_ncores_with_attr_per(const kmp_hw_attr_t &attr, int above) const
int get_depth() const
void insert_layer(kmp_hw_t type, const int *ids)
int calculate_ratio(int level1, int level2) const
bool is_uniform() const
static kmp_topology_t * allocate(int nproc, int ndepth, const kmp_hw_t *types)
void print(const char *env_var="KMP_AFFINITY") const
kmp_hw_t get_type(int level) const
kmp_topology_t()=delete
bool check_ids() const
int get_ncores_with_attr(const kmp_hw_attr_t &attr) const
__itt_string_handle * name
Definition ittnotify.h:3305
void
Definition ittnotify.h:3324
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int mask
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp end
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_id __itt_string_handle __itt_metadata_type size_t void ITT_FORMAT p const __itt_domain __itt_id __itt_string_handle const wchar_t size_t ITT_FORMAT lu const __itt_domain __itt_id __itt_relation __itt_id ITT_FORMAT p const wchar_t int ITT_FORMAT __itt_group_mark d __itt_event ITT_FORMAT __itt_group_mark d void const wchar_t const wchar_t int ITT_FORMAT __itt_group_sync __itt_group_fsync x void const wchar_t int const wchar_t int int ITT_FORMAT __itt_group_sync __itt_group_fsync x void ITT_FORMAT __itt_group_sync __itt_group_fsync p void ITT_FORMAT __itt_group_sync __itt_group_fsync p void size_t ITT_FORMAT lu no args __itt_obj_prop_t __itt_obj_state_t ITT_FORMAT d const char ITT_FORMAT s const char ITT_FORMAT s __itt_frame ITT_FORMAT p __itt_counter ITT_FORMAT p __itt_counter unsigned long long ITT_FORMAT lu __itt_counter unsigned long long ITT_FORMAT lu __itt_counter __itt_clock_domain unsigned long long void ITT_FORMAT p const wchar_t ITT_FORMAT S __itt_mark_type const wchar_t ITT_FORMAT S __itt_mark_type const char ITT_FORMAT s __itt_mark_type ITT_FORMAT d __itt_caller ITT_FORMAT p __itt_caller ITT_FORMAT p no args const __itt_domain __itt_clock_domain unsigned long long __itt_id ITT_FORMAT lu const __itt_domain __itt_clock_domain unsigned long long __itt_id __itt_id void ITT_FORMAT p const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_clock_domain unsigned long long __itt_id __itt_string_handle __itt_scope ITT_FORMAT d const __itt_domain __itt_scope __itt_string_handle const char size_t ITT_FORMAT lu const __itt_domain __itt_clock_domain unsigned long long __itt_relation __itt_id ITT_FORMAT lu __itt_track_group __itt_string_handle __itt_track_group_type ITT_FORMAT d __itt_track ITT_FORMAT p void int const int int const char int ITT_FORMAT d void void const char * path
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t count
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long value
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t size
void const char const char int ITT_FORMAT __itt_group_sync p
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_id __itt_string_handle __itt_metadata_type size_t void ITT_FORMAT p const __itt_domain __itt_id __itt_string_handle const wchar_t size_t ITT_FORMAT lu const __itt_domain __itt_id __itt_relation __itt_id ITT_FORMAT p const wchar_t int ITT_FORMAT __itt_group_mark d int
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_id __itt_string_handle __itt_metadata_type type
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_id __itt_string_handle * key
#define __kmp_free(ptr)
Definition kmp.h:3749
#define KMP_HW_MAX_NUM_CORE_EFFS
Definition kmp.h:619
int __kmp_xproc
#define KMP_FOREACH_HW_TYPE(type)
Definition kmp.h:626
kmp_nested_proc_bind_t __kmp_nested_proc_bind
#define KMP_HIDDEN_HELPER_MAIN_THREAD(gtid)
Definition kmp.h:4596
#define __kmp_entry_gtid()
Definition kmp.h:3594
#define KMP_ASSERT_VALID_HW_TYPE(type)
Definition kmp.h:623
const char * __kmp_hw_get_catalog_string(kmp_hw_t type, bool plural=false)
volatile int __kmp_init_middle
const char * __kmp_hw_get_keyword(kmp_hw_t type, bool plural=false)
int __kmp_affinity_num_places
kmp_info_t ** __kmp_threads
#define KMP_HIDDEN_HELPER_THREAD(gtid)
Definition kmp.h:4590
#define __kmp_allocate(size)
Definition kmp.h:3747
#define TRUE
Definition kmp.h:1341
#define FALSE
Definition kmp.h:1340
static bool __kmp_is_hybrid_cpu()
Definition kmp.h:3361
int __kmp_env_consistency_check
#define KMP_INTERNAL_FREE(p)
Definition kmp.h:104
static int __kmp_adjust_gtid_for_hidden_helpers(int gtid)
Definition kmp.h:4610
#define SKIP_WS(_x)
Definition kmp.h:265
const char * __kmp_hw_get_core_type_string(kmp_hw_core_type_t type)
#define __kmp_get_gtid()
Definition kmp.h:3593
int __kmp_avail_proc
#define SKIP_DIGITS(_x)
Definition kmp.h:270
int __kmp_dflt_team_nth
@ proc_bind_false
Definition kmp.h:931
@ proc_bind_intel
Definition kmp.h:936
kmp_hw_t
Definition kmp.h:591
@ KMP_HW_UNKNOWN
Definition kmp.h:592
@ KMP_HW_NUMA
Definition kmp.h:595
@ KMP_HW_SOCKET
Definition kmp.h:593
@ KMP_HW_CORE
Definition kmp.h:603
@ KMP_HW_L2
Definition kmp.h:601
@ KMP_HW_PROC_GROUP
Definition kmp.h:594
@ KMP_HW_L1
Definition kmp.h:602
@ KMP_HW_L3
Definition kmp.h:598
@ KMP_HW_MODULE
Definition kmp.h:600
@ KMP_HW_DIE
Definition kmp.h:596
@ KMP_HW_TILE
Definition kmp.h:599
@ KMP_HW_THREAD
Definition kmp.h:604
@ KMP_HW_LAST
Definition kmp.h:605
@ KMP_HW_LLC
Definition kmp.h:597
static int __kmp_gtid_from_thread(const kmp_info_t *thr)
Definition kmp.h:3622
kmp_hw_core_type_t
Definition kmp.h:608
@ KMP_HW_MAX_NUM_CORE_TYPES
Definition kmp.h:615
@ KMP_HW_CORE_TYPE_UNKNOWN
Definition kmp.h:609
static void __kmp_type_convert(T1 src, T2 *dest)
Definition kmp.h:4879
struct KMP_ALIGN_CACHE kmp_bstate kmp_bstate_t
bool __kmp_hwloc_available
union KMP_ALIGN_CACHE kmp_info kmp_info_t
kmp_hw_subset_t * __kmp_hw_subset
static hierarchy_info machine_hierarchy
kmp_topology_t * __kmp_topology
void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar)
#define KMP_AFF_WARNING(s,...)
static int __kmp_nThreadsPerCore
static int nPackages
const char * __kmp_hw_get_catalog_string(kmp_hw_t type, bool plural)
static int nCoresPerPkg
const char * __kmp_hw_get_core_type_string(kmp_hw_core_type_t type)
static int __kmp_ncores
void __kmp_cleanup_hierarchy()
const char * __kmp_hw_get_keyword(kmp_hw_t type, bool plural)
kmp_hw_subset_t * __kmp_hw_subset
kmp_topology_t * __kmp_topology
KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 add
KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86 KMP_ARCH_X86<<, 2i, 1, KMP_ARCH_X86) ATOMIC_CMPXCHG(fixed2, shr, kmp_int16, 16, > KMP_ARCH_X86 KMP_ARCH_X86 kmp_uint32
void __kmp_debug_printf(char const *format,...)
Definition kmp_debug.cpp:29
#define KA_TRACE(d, x)
Definition kmp_debug.h:157
#define KMP_ASSERT(cond)
Definition kmp_debug.h:59
#define KMP_BUILD_ASSERT(expr)
Definition kmp_debug.h:26
#define KMP_DEBUG_ASSERT2(cond, msg)
Definition kmp_debug.h:62
#define KMP_DEBUG_ASSERT(cond)
Definition kmp_debug.h:61
#define KMP_ASSERT2(cond, msg)
Definition kmp_debug.h:60
int __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_LAST+1]
kmp_hier_layer_e
@ LAYER_THREAD
@ LAYER_NUMA
@ LAYER_L1
@ LAYER_LOOP
@ LAYER_L2
@ LAYER_LAST
@ LAYER_L3
int __kmp_dispatch_get_index(int tid, kmp_hier_layer_e type)
int __kmp_hier_max_units[kmp_hier_layer_e::LAYER_LAST+1]
int __kmp_dispatch_get_t1_per_t2(kmp_hier_layer_e t1, kmp_hier_layer_e t2)
static volatile kmp_i18n_cat_status_t status
Definition kmp_i18n.cpp:48
kmp_msg_t __kmp_msg_null
Definition kmp_i18n.cpp:36
static void __kmp_msg(kmp_msg_severity_t severity, kmp_msg_t message, va_list ap)
Definition kmp_i18n.cpp:787
#define KMP_INFORM(...)
Definition kmp_i18n.h:142
#define KMP_MSG(...)
Definition kmp_i18n.h:121
@ kmp_ms_warning
Definition kmp_i18n.h:130
#define KMP_I18N_STR(id)
Definition kmp_i18n.h:46
char const * __kmp_i18n_catgets(kmp_i18n_id_t id)
#define KMP_FATAL(...)
Definition kmp_i18n.h:146
#define KMP_HNT(...)
Definition kmp_i18n.h:122
void __kmp_printf(char const *format,...)
Definition kmp_io.cpp:186
#define KMP_BUILTIN_UNREACHABLE
Definition kmp_os.h:1321
#define TCR_1(a)
Definition kmp_os.h:1139
long kmp_intptr_t
Definition kmp_os.h:205
#define TCR_SYNC_PTR(a)
Definition kmp_os.h:1172
#define RCAST(type, var)
Definition kmp_os.h:294
#define KMP_ALLOCA
#define KMP_SNPRINTF
#define KMP_SSCANF
int __kmp_str_to_int(char const *str, char sentinel)
Definition kmp_str.cpp:642
void __kmp_str_buf_clear(kmp_str_buf_t *buffer)
Definition kmp_str.cpp:71
int __kmp_str_match(char const *target, int len, char const *data)
Definition kmp_str.cpp:505
void __kmp_str_buf_free(kmp_str_buf_t *buffer)
Definition kmp_str.cpp:123
int __kmp_str_buf_print(kmp_str_buf_t *buffer, char const *format,...)
Definition kmp_str.cpp:221
struct kmp_str_buf kmp_str_buf_t
Definition kmp_str.h:39
#define __kmp_str_buf_init(b)
Definition kmp_str.h:41
#define i
Definition kmp_stub.cpp:88
int a
dest
Definition check.py:82
bool operator==(const ParallelBegin &, const ParallelBegin &)
int32_t kmp_int32
int arr[N][N][N]
static int ii
affinity_mask_t * full_mask
volatile int flag
bool contains(const kmp_hw_attr_t &other) const
int get_core_eff() const
bool is_core_type_valid() const
kmp_hw_core_type_t get_core_type() const
void set_core_type(kmp_hw_core_type_t type)
static const int UNKNOWN_CORE_EFF
void set_core_eff(int eff)
bool is_core_eff_valid() const
kmp_hw_attr_t attr[MAX_ATTRS]
int __kmp_read_from_file(char const *path, char const *format,...)