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