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