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