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