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