blob: 4b78519b0739d2e242de6314b2c2b2296e0eff33 [file] [log] [blame]
Jim Cownie5e8470a2013-09-27 10:38:44 +00001/*
2 * kmp_affinity.cpp -- affinity management
Jim Cownie5e8470a2013-09-27 10:38:44 +00003 */
4
5
6//===----------------------------------------------------------------------===//
7//
8// The LLVM Compiler Infrastructure
9//
10// This file is dual licensed under the MIT and the University of Illinois Open
11// Source Licenses. See LICENSE.txt for details.
12//
13//===----------------------------------------------------------------------===//
14
15
16#include "kmp.h"
17#include "kmp_i18n.h"
18#include "kmp_io.h"
19#include "kmp_str.h"
Jim Cownie4cc4bb42014-10-07 16:25:50 +000020#include "kmp_wrapper_getpid.h"
Jonathan Peyton17078362015-09-10 19:22:07 +000021#include "kmp_affinity.h"
22
23// Store the real or imagined machine hierarchy here
24static hierarchy_info machine_hierarchy;
25
26void __kmp_cleanup_hierarchy() {
27 machine_hierarchy.fini();
28}
29
30void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar) {
31 kmp_uint32 depth;
32 // The test below is true if affinity is available, but set to "none". Need to init on first use of hierarchical barrier.
33 if (TCR_1(machine_hierarchy.uninitialized))
34 machine_hierarchy.init(NULL, nproc);
Jonathan Peyton17078362015-09-10 19:22:07 +000035
Jonathan Peyton7dee82e2015-11-09 16:24:53 +000036 // Adjust the hierarchy in case num threads exceeds original
37 if (nproc > machine_hierarchy.base_num_threads)
38 machine_hierarchy.resize(nproc);
39
Jonathan Peyton17078362015-09-10 19:22:07 +000040 depth = machine_hierarchy.depth;
41 KMP_DEBUG_ASSERT(depth > 0);
Jonathan Peyton17078362015-09-10 19:22:07 +000042
43 thr_bar->depth = depth;
44 thr_bar->base_leaf_kids = (kmp_uint8)machine_hierarchy.numPerLevel[0]-1;
45 thr_bar->skip_per_level = machine_hierarchy.skipPerLevel;
46}
Jim Cownie5e8470a2013-09-27 10:38:44 +000047
Alp Toker763b9392014-02-28 09:42:41 +000048#if KMP_AFFINITY_SUPPORTED
Jim Cownie5e8470a2013-09-27 10:38:44 +000049
50//
51// Print the affinity mask to the character array in a pretty format.
52//
Jonathan Peyton01dcf362015-11-30 20:02:59 +000053#if KMP_USE_HWLOC
54char *
55__kmp_affinity_print_mask(char *buf, int buf_len, kmp_affin_mask_t *mask)
56{
57 int num_chars_to_write, num_chars_written;
58 char* scan;
59 KMP_ASSERT(buf_len >= 40);
60
61 // bufsize of 0 just retrieves the needed buffer size.
62 num_chars_to_write = hwloc_bitmap_list_snprintf(buf, 0, (hwloc_bitmap_t)mask);
63
64 // need '{', "xxxxxxxx...xx", '}', '\0' = num_chars_to_write + 3 bytes
65 // * num_chars_to_write returned by hwloc_bitmap_list_snprintf does not
66 // take into account the '\0' character.
67 if(hwloc_bitmap_iszero((hwloc_bitmap_t)mask)) {
68 KMP_SNPRINTF(buf, buf_len, "{<empty>}");
69 } else if(num_chars_to_write < buf_len - 3) {
70 // no problem fitting the mask into buf_len number of characters
71 buf[0] = '{';
72 // use buf_len-3 because we have the three characters: '{' '}' '\0' to add to the buffer
73 num_chars_written = hwloc_bitmap_list_snprintf(buf+1, buf_len-3, (hwloc_bitmap_t)mask);
74 buf[num_chars_written+1] = '}';
75 buf[num_chars_written+2] = '\0';
76 } else {
77 // Need to truncate the affinity mask string and add ellipsis.
78 // To do this, we first write out the '{' + str(mask)
79 buf[0] = '{';
Jonathan Peyton1d5487c2016-04-25 21:08:31 +000080 hwloc_bitmap_list_snprintf(buf+1, buf_len-1, (hwloc_bitmap_t)mask);
Jonathan Peyton01dcf362015-11-30 20:02:59 +000081 // then, what we do here is go to the 7th to last character, then go backwards until we are NOT
82 // on a digit then write "...}\0". This way it is a clean ellipsis addition and we don't
83 // overwrite part of an affinity number. i.e., we avoid something like { 45, 67, 8...} and get
84 // { 45, 67,...} instead.
85 scan = buf + buf_len - 7;
86 while(*scan >= '0' && *scan <= '9' && scan >= buf)
87 scan--;
88 *(scan+1) = '.';
89 *(scan+2) = '.';
90 *(scan+3) = '.';
91 *(scan+4) = '}';
92 *(scan+5) = '\0';
93 }
94 return buf;
95}
96#else
Jim Cownie5e8470a2013-09-27 10:38:44 +000097char *
98__kmp_affinity_print_mask(char *buf, int buf_len, kmp_affin_mask_t *mask)
99{
100 KMP_ASSERT(buf_len >= 40);
101 char *scan = buf;
102 char *end = buf + buf_len - 1;
103
104 //
105 // Find first element / check for empty set.
106 //
107 size_t i;
108 for (i = 0; i < KMP_CPU_SETSIZE; i++) {
109 if (KMP_CPU_ISSET(i, mask)) {
110 break;
111 }
112 }
113 if (i == KMP_CPU_SETSIZE) {
Jonathan Peyton7edeef12015-09-25 17:23:17 +0000114 KMP_SNPRINTF(scan, end-scan+1, "{<empty>}");
Jim Cownie5e8470a2013-09-27 10:38:44 +0000115 while (*scan != '\0') scan++;
116 KMP_ASSERT(scan <= end);
117 return buf;
118 }
119
Jonathan Peyton7edeef12015-09-25 17:23:17 +0000120 KMP_SNPRINTF(scan, end-scan+1, "{%ld", (long)i);
Jim Cownie5e8470a2013-09-27 10:38:44 +0000121 while (*scan != '\0') scan++;
122 i++;
123 for (; i < KMP_CPU_SETSIZE; i++) {
124 if (! KMP_CPU_ISSET(i, mask)) {
125 continue;
126 }
127
128 //
129 // Check for buffer overflow. A string of the form ",<n>" will have
130 // at most 10 characters, plus we want to leave room to print ",...}"
131 // if the set is too large to print for a total of 15 characters.
132 // We already left room for '\0' in setting end.
133 //
134 if (end - scan < 15) {
135 break;
136 }
Jonathan Peyton7edeef12015-09-25 17:23:17 +0000137 KMP_SNPRINTF(scan, end-scan+1, ",%-ld", (long)i);
Jim Cownie5e8470a2013-09-27 10:38:44 +0000138 while (*scan != '\0') scan++;
139 }
140 if (i < KMP_CPU_SETSIZE) {
Jonathan Peyton7edeef12015-09-25 17:23:17 +0000141 KMP_SNPRINTF(scan, end-scan+1, ",...");
Jim Cownie5e8470a2013-09-27 10:38:44 +0000142 while (*scan != '\0') scan++;
143 }
Jonathan Peyton7edeef12015-09-25 17:23:17 +0000144 KMP_SNPRINTF(scan, end-scan+1, "}");
Jim Cownie5e8470a2013-09-27 10:38:44 +0000145 while (*scan != '\0') scan++;
146 KMP_ASSERT(scan <= end);
147 return buf;
148}
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000149#endif // KMP_USE_HWLOC
Jim Cownie5e8470a2013-09-27 10:38:44 +0000150
151
152void
153__kmp_affinity_entire_machine_mask(kmp_affin_mask_t *mask)
154{
155 KMP_CPU_ZERO(mask);
156
Andrey Churbanov7daf9802015-01-27 16:52:57 +0000157# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +0000158
159 if (__kmp_num_proc_groups > 1) {
160 int group;
Jim Cownie5e8470a2013-09-27 10:38:44 +0000161 KMP_DEBUG_ASSERT(__kmp_GetActiveProcessorCount != NULL);
162 for (group = 0; group < __kmp_num_proc_groups; group++) {
163 int i;
164 int num = __kmp_GetActiveProcessorCount(group);
165 for (i = 0; i < num; i++) {
166 KMP_CPU_SET(i + group * (CHAR_BIT * sizeof(DWORD_PTR)), mask);
167 }
168 }
169 }
170 else
171
Andrey Churbanov7daf9802015-01-27 16:52:57 +0000172# endif /* KMP_GROUP_AFFINITY */
Jim Cownie5e8470a2013-09-27 10:38:44 +0000173
174 {
175 int proc;
176 for (proc = 0; proc < __kmp_xproc; proc++) {
177 KMP_CPU_SET(proc, mask);
178 }
179 }
180}
181
Jim Cownie5e8470a2013-09-27 10:38:44 +0000182//
183// When sorting by labels, __kmp_affinity_assign_child_nums() must first be
184// called to renumber the labels from [0..n] and place them into the child_num
185// vector of the address object. This is done in case the labels used for
Alp Toker8f2d3f02014-02-24 10:40:15 +0000186// the children at one node of the hierarchy differ from those used for
Jim Cownie5e8470a2013-09-27 10:38:44 +0000187// another node at the same level. Example: suppose the machine has 2 nodes
188// with 2 packages each. The first node contains packages 601 and 602, and
189// second node contains packages 603 and 604. If we try to sort the table
190// for "scatter" affinity, the table will still be sorted 601, 602, 603, 604
191// because we are paying attention to the labels themselves, not the ordinal
192// child numbers. By using the child numbers in the sort, the result is
193// {0,0}=601, {0,1}=603, {1,0}=602, {1,1}=604.
194//
195static void
196__kmp_affinity_assign_child_nums(AddrUnsPair *address2os,
197 int numAddrs)
198{
199 KMP_DEBUG_ASSERT(numAddrs > 0);
200 int depth = address2os->first.depth;
201 unsigned *counts = (unsigned *)__kmp_allocate(depth * sizeof(unsigned));
202 unsigned *lastLabel = (unsigned *)__kmp_allocate(depth
203 * sizeof(unsigned));
204 int labCt;
205 for (labCt = 0; labCt < depth; labCt++) {
206 address2os[0].first.childNums[labCt] = counts[labCt] = 0;
207 lastLabel[labCt] = address2os[0].first.labels[labCt];
208 }
209 int i;
210 for (i = 1; i < numAddrs; i++) {
211 for (labCt = 0; labCt < depth; labCt++) {
212 if (address2os[i].first.labels[labCt] != lastLabel[labCt]) {
213 int labCt2;
214 for (labCt2 = labCt + 1; labCt2 < depth; labCt2++) {
215 counts[labCt2] = 0;
216 lastLabel[labCt2] = address2os[i].first.labels[labCt2];
217 }
218 counts[labCt]++;
219 lastLabel[labCt] = address2os[i].first.labels[labCt];
220 break;
221 }
222 }
223 for (labCt = 0; labCt < depth; labCt++) {
224 address2os[i].first.childNums[labCt] = counts[labCt];
225 }
226 for (; labCt < (int)Address::maxDepth; labCt++) {
227 address2os[i].first.childNums[labCt] = 0;
228 }
229 }
230}
231
232
233//
234// All of the __kmp_affinity_create_*_map() routines should set
235// __kmp_affinity_masks to a vector of affinity mask objects of length
236// __kmp_affinity_num_masks, if __kmp_affinity_type != affinity_none, and
237// return the number of levels in the machine topology tree (zero if
238// __kmp_affinity_type == affinity_none).
239//
240// All of the __kmp_affinity_create_*_map() routines should set *fullMask
241// to the affinity mask for the initialization thread. They need to save and
242// restore the mask, and it could be needed later, so saving it is just an
243// optimization to avoid calling kmp_get_system_affinity() again.
244//
245static kmp_affin_mask_t *fullMask = NULL;
246
247kmp_affin_mask_t *
248__kmp_affinity_get_fullMask() { return fullMask; }
249
250
251static int nCoresPerPkg, nPackages;
Andrey Churbanovf696c822015-01-27 16:55:43 +0000252static int __kmp_nThreadsPerCore;
253#ifndef KMP_DFLT_NTH_CORES
254static int __kmp_ncores;
255#endif
Jim Cownie5e8470a2013-09-27 10:38:44 +0000256
257//
258// __kmp_affinity_uniform_topology() doesn't work when called from
259// places which support arbitrarily many levels in the machine topology
260// map, i.e. the non-default cases in __kmp_affinity_create_cpuinfo_map()
261// __kmp_affinity_create_x2apicid_map().
262//
263inline static bool
264__kmp_affinity_uniform_topology()
265{
266 return __kmp_avail_proc == (__kmp_nThreadsPerCore * nCoresPerPkg * nPackages);
267}
268
269
270//
271// Print out the detailed machine topology map, i.e. the physical locations
272// of each OS proc.
273//
274static void
275__kmp_affinity_print_topology(AddrUnsPair *address2os, int len, int depth,
276 int pkgLevel, int coreLevel, int threadLevel)
277{
278 int proc;
279
280 KMP_INFORM(OSProcToPhysicalThreadMap, "KMP_AFFINITY");
281 for (proc = 0; proc < len; proc++) {
282 int level;
283 kmp_str_buf_t buf;
284 __kmp_str_buf_init(&buf);
285 for (level = 0; level < depth; level++) {
286 if (level == threadLevel) {
287 __kmp_str_buf_print(&buf, "%s ", KMP_I18N_STR(Thread));
288 }
289 else if (level == coreLevel) {
290 __kmp_str_buf_print(&buf, "%s ", KMP_I18N_STR(Core));
291 }
292 else if (level == pkgLevel) {
293 __kmp_str_buf_print(&buf, "%s ", KMP_I18N_STR(Package));
294 }
295 else if (level > pkgLevel) {
296 __kmp_str_buf_print(&buf, "%s_%d ", KMP_I18N_STR(Node),
297 level - pkgLevel - 1);
298 }
299 else {
300 __kmp_str_buf_print(&buf, "L%d ", level);
301 }
302 __kmp_str_buf_print(&buf, "%d ",
303 address2os[proc].first.labels[level]);
304 }
305 KMP_INFORM(OSProcMapToPack, "KMP_AFFINITY", address2os[proc].second,
306 buf.str);
307 __kmp_str_buf_free(&buf);
308 }
309}
310
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000311#if KMP_USE_HWLOC
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000312
313// This function removes the topology levels that are radix 1 and don't offer
314// further information about the topology. The most common example is when you
315// have one thread context per core, we don't want the extra thread context
316// level if it offers no unique labels. So they are removed.
317// return value: the new depth of address2os
318static int
319__kmp_affinity_remove_radix_one_levels(AddrUnsPair *address2os, int nActiveThreads, int depth, int* pkgLevel, int* coreLevel, int* threadLevel) {
320 int level;
321 int i;
322 int radix1_detected;
323
324 for (level = depth-1; level >= 0; --level) {
325 // Always keep the package level
326 if (level == *pkgLevel)
327 continue;
328 // Detect if this level is radix 1
329 radix1_detected = 1;
330 for (i = 1; i < nActiveThreads; ++i) {
331 if (address2os[0].first.labels[level] != address2os[i].first.labels[level]) {
332 // There are differing label values for this level so it stays
333 radix1_detected = 0;
334 break;
335 }
336 }
337 if (!radix1_detected)
338 continue;
339 // Radix 1 was detected
340 if (level == *threadLevel) {
341 // If only one thread per core, then just decrement
342 // the depth which removes the threadlevel from address2os
343 for (i = 0; i < nActiveThreads; ++i) {
344 address2os[i].first.depth--;
345 }
346 *threadLevel = -1;
347 } else if (level == *coreLevel) {
348 // For core level, we move the thread labels over if they are still
349 // valid (*threadLevel != -1), and also reduce the depth another level
350 for (i = 0; i < nActiveThreads; ++i) {
351 if (*threadLevel != -1) {
352 address2os[i].first.labels[*coreLevel] = address2os[i].first.labels[*threadLevel];
353 }
354 address2os[i].first.depth--;
355 }
356 *coreLevel = -1;
357 }
358 }
359 return address2os[0].first.depth;
360}
361
362// Returns the number of objects of type 'type' below 'obj' within the topology tree structure.
363// e.g., if obj is a HWLOC_OBJ_SOCKET object, and type is HWLOC_OBJ_PU, then
364// this will return the number of PU's under the SOCKET object.
365static int
366__kmp_hwloc_get_nobjs_under_obj(hwloc_obj_t obj, hwloc_obj_type_t type) {
367 int retval = 0;
368 hwloc_obj_t first;
369 for(first = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, obj->type, obj->logical_index, type, 0);
370 first != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology, obj->type, first) == obj;
371 first = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, first->type, first))
372 {
373 ++retval;
374 }
375 return retval;
376}
377
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000378static int
379__kmp_affinity_create_hwloc_map(AddrUnsPair **address2os,
380 kmp_i18n_id_t *const msg_id)
381{
382 *address2os = NULL;
383 *msg_id = kmp_i18n_null;
384
385 //
386 // Save the affinity mask for the current thread.
387 //
388 kmp_affin_mask_t *oldMask;
389 KMP_CPU_ALLOC(oldMask);
390 __kmp_get_system_affinity(oldMask, TRUE);
391
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000392 int depth = 3;
393 int pkgLevel = 0;
394 int coreLevel = 1;
395 int threadLevel = 2;
396 nPackages = __kmp_hwloc_get_nobjs_under_obj(hwloc_get_root_obj(__kmp_hwloc_topology), HWLOC_OBJ_SOCKET);
397 nCoresPerPkg = __kmp_hwloc_get_nobjs_under_obj(hwloc_get_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_SOCKET, 0), HWLOC_OBJ_CORE);
398 __kmp_nThreadsPerCore = __kmp_hwloc_get_nobjs_under_obj(hwloc_get_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_CORE, 0), HWLOC_OBJ_PU);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000399
400 if (! KMP_AFFINITY_CAPABLE())
401 {
402 //
403 // Hack to try and infer the machine topology using only the data
404 // available from cpuid on the current thread, and __kmp_xproc.
405 //
406 KMP_ASSERT(__kmp_affinity_type == affinity_none);
407
408 __kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;
409 nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
410 if (__kmp_affinity_verbose) {
411 KMP_INFORM(AffNotCapableUseLocCpuidL11, "KMP_AFFINITY");
412 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
413 if (__kmp_affinity_uniform_topology()) {
414 KMP_INFORM(Uniform, "KMP_AFFINITY");
415 } else {
416 KMP_INFORM(NonUniform, "KMP_AFFINITY");
417 }
418 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
419 __kmp_nThreadsPerCore, __kmp_ncores);
420 }
421 return 0;
422 }
423
424 //
425 // Allocate the data structure to be returned.
426 //
427 AddrUnsPair *retval = (AddrUnsPair *)__kmp_allocate(sizeof(AddrUnsPair) * __kmp_avail_proc);
428
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000429 hwloc_obj_t pu;
430 hwloc_obj_t core;
431 hwloc_obj_t socket;
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000432 int nActiveThreads = 0;
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000433 int socket_identifier = 0;
434 for(socket = hwloc_get_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_SOCKET, 0);
435 socket != NULL;
436 socket = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_SOCKET, socket),
437 socket_identifier++)
438 {
439 int core_identifier = 0;
440 for(core = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, socket->type, socket->logical_index, HWLOC_OBJ_CORE, 0);
441 core != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology, socket->type, core) == socket;
442 core = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_CORE, core),
443 core_identifier++)
444 {
445 int pu_identifier = 0;
446 for(pu = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, core->type, core->logical_index, HWLOC_OBJ_PU, 0);
447 pu != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology, core->type, pu) == core;
448 pu = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, HWLOC_OBJ_PU, pu),
449 pu_identifier++)
450 {
451 Address addr(3);
452 if(! KMP_CPU_ISSET(pu->os_index, fullMask))
453 continue;
454 KA_TRACE(20, ("Hwloc inserting %d (%d) %d (%d) %d (%d) into address2os\n",
455 socket->os_index, socket->logical_index, core->os_index, core->logical_index, pu->os_index,pu->logical_index));
456 addr.labels[0] = socket_identifier; // package
457 addr.labels[1] = core_identifier; // core
458 addr.labels[2] = pu_identifier; // pu
459 retval[nActiveThreads] = AddrUnsPair(addr, pu->os_index);
460 nActiveThreads++;
461 }
462 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000463 }
464
465 //
466 // If there's only one thread context to bind to, return now.
467 //
468 KMP_ASSERT(nActiveThreads > 0);
469 if (nActiveThreads == 1) {
470 __kmp_ncores = nPackages = 1;
471 __kmp_nThreadsPerCore = nCoresPerPkg = 1;
472 if (__kmp_affinity_verbose) {
473 char buf[KMP_AFFIN_MASK_PRINT_LEN];
474 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
475
476 KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
477 if (__kmp_affinity_respect_mask) {
478 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
479 } else {
480 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
481 }
482 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
483 KMP_INFORM(Uniform, "KMP_AFFINITY");
484 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
485 __kmp_nThreadsPerCore, __kmp_ncores);
486 }
487
488 if (__kmp_affinity_type == affinity_none) {
489 __kmp_free(retval);
490 KMP_CPU_FREE(oldMask);
491 return 0;
492 }
493
494 //
495 // Form an Address object which only includes the package level.
496 //
497 Address addr(1);
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000498 addr.labels[0] = retval[0].first.labels[pkgLevel];
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000499 retval[0].first = addr;
500
501 if (__kmp_affinity_gran_levels < 0) {
502 __kmp_affinity_gran_levels = 0;
503 }
504
505 if (__kmp_affinity_verbose) {
506 __kmp_affinity_print_topology(retval, 1, 1, 0, -1, -1);
507 }
508
509 *address2os = retval;
510 KMP_CPU_FREE(oldMask);
511 return 1;
512 }
513
514 //
515 // Sort the table by physical Id.
516 //
517 qsort(retval, nActiveThreads, sizeof(*retval), __kmp_affinity_cmp_Address_labels);
518
519 //
520 // When affinity is off, this routine will still be called to set
521 // __kmp_ncores, as well as __kmp_nThreadsPerCore,
522 // nCoresPerPkg, & nPackages. Make sure all these vars are set
523 // correctly, and return if affinity is not enabled.
524 //
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000525 __kmp_ncores = hwloc_get_nbobjs_by_type(__kmp_hwloc_topology, HWLOC_OBJ_CORE);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000526
527 //
528 // Check to see if the machine topology is uniform
529 //
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000530 unsigned npackages = hwloc_get_nbobjs_by_type(__kmp_hwloc_topology, HWLOC_OBJ_SOCKET);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000531 unsigned ncores = __kmp_ncores;
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000532 unsigned nthreads = hwloc_get_nbobjs_by_type(__kmp_hwloc_topology, HWLOC_OBJ_PU);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000533 unsigned uniform = (npackages * nCoresPerPkg * __kmp_nThreadsPerCore == nthreads);
534
535 //
536 // Print the machine topology summary.
537 //
538 if (__kmp_affinity_verbose) {
539 char mask[KMP_AFFIN_MASK_PRINT_LEN];
540 __kmp_affinity_print_mask(mask, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
541
542 KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
543 if (__kmp_affinity_respect_mask) {
544 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", mask);
545 } else {
546 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", mask);
547 }
548 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
549 if (uniform) {
550 KMP_INFORM(Uniform, "KMP_AFFINITY");
551 } else {
552 KMP_INFORM(NonUniform, "KMP_AFFINITY");
553 }
554
555 kmp_str_buf_t buf;
556 __kmp_str_buf_init(&buf);
557
558 __kmp_str_buf_print(&buf, "%d", npackages);
559 //for (level = 1; level <= pkgLevel; level++) {
560 // __kmp_str_buf_print(&buf, " x %d", maxCt[level]);
561 // }
562 KMP_INFORM(TopologyExtra, "KMP_AFFINITY", buf.str, nCoresPerPkg,
563 __kmp_nThreadsPerCore, __kmp_ncores);
564
565 __kmp_str_buf_free(&buf);
566 }
567
568 if (__kmp_affinity_type == affinity_none) {
569 KMP_CPU_FREE(oldMask);
570 return 0;
571 }
572
573 //
574 // Find any levels with radiix 1, and remove them from the map
575 // (except for the package level).
576 //
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000577 depth = __kmp_affinity_remove_radix_one_levels(retval, nActiveThreads, depth, &pkgLevel, &coreLevel, &threadLevel);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000578
579 if (__kmp_affinity_gran_levels < 0) {
580 //
581 // Set the granularity level based on what levels are modeled
582 // in the machine topology map.
583 //
584 __kmp_affinity_gran_levels = 0;
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000585 if ((threadLevel >= 0) && (__kmp_affinity_gran > affinity_gran_thread)) {
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000586 __kmp_affinity_gran_levels++;
587 }
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000588 if ((coreLevel >= 0) && (__kmp_affinity_gran > affinity_gran_core)) {
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000589 __kmp_affinity_gran_levels++;
590 }
591 if (__kmp_affinity_gran > affinity_gran_package) {
592 __kmp_affinity_gran_levels++;
593 }
594 }
595
596 if (__kmp_affinity_verbose) {
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000597 __kmp_affinity_print_topology(retval, nActiveThreads, depth, pkgLevel,
598 coreLevel, threadLevel);
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000599 }
600
601 KMP_CPU_FREE(oldMask);
602 *address2os = retval;
Jonathan Peyton202a24d2016-06-13 17:30:08 +0000603 return depth;
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000604}
605#endif // KMP_USE_HWLOC
Jim Cownie5e8470a2013-09-27 10:38:44 +0000606
607//
608// If we don't know how to retrieve the machine's processor topology, or
609// encounter an error in doing so, this routine is called to form a "flat"
610// mapping of os thread id's <-> processor id's.
611//
612static int
613__kmp_affinity_create_flat_map(AddrUnsPair **address2os,
614 kmp_i18n_id_t *const msg_id)
615{
616 *address2os = NULL;
617 *msg_id = kmp_i18n_null;
618
619 //
620 // Even if __kmp_affinity_type == affinity_none, this routine might still
Andrey Churbanovf696c822015-01-27 16:55:43 +0000621 // called to set __kmp_ncores, as well as
Jim Cownie5e8470a2013-09-27 10:38:44 +0000622 // __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
623 //
624 if (! KMP_AFFINITY_CAPABLE()) {
625 KMP_ASSERT(__kmp_affinity_type == affinity_none);
626 __kmp_ncores = nPackages = __kmp_xproc;
627 __kmp_nThreadsPerCore = nCoresPerPkg = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +0000628 if (__kmp_affinity_verbose) {
629 KMP_INFORM(AffFlatTopology, "KMP_AFFINITY");
630 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
631 KMP_INFORM(Uniform, "KMP_AFFINITY");
632 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
633 __kmp_nThreadsPerCore, __kmp_ncores);
634 }
635 return 0;
636 }
637
638 //
639 // When affinity is off, this routine will still be called to set
Andrey Churbanovf696c822015-01-27 16:55:43 +0000640 // __kmp_ncores, as well as __kmp_nThreadsPerCore,
Jim Cownie5e8470a2013-09-27 10:38:44 +0000641 // nCoresPerPkg, & nPackages. Make sure all these vars are set
642 // correctly, and return now if affinity is not enabled.
643 //
644 __kmp_ncores = nPackages = __kmp_avail_proc;
645 __kmp_nThreadsPerCore = nCoresPerPkg = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +0000646 if (__kmp_affinity_verbose) {
647 char buf[KMP_AFFIN_MASK_PRINT_LEN];
648 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, fullMask);
649
650 KMP_INFORM(AffCapableUseFlat, "KMP_AFFINITY");
651 if (__kmp_affinity_respect_mask) {
652 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
653 } else {
654 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
655 }
656 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
657 KMP_INFORM(Uniform, "KMP_AFFINITY");
658 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
659 __kmp_nThreadsPerCore, __kmp_ncores);
660 }
661 if (__kmp_affinity_type == affinity_none) {
662 return 0;
663 }
664
665 //
666 // Contruct the data structure to be returned.
667 //
668 *address2os = (AddrUnsPair*)
669 __kmp_allocate(sizeof(**address2os) * __kmp_avail_proc);
670 int avail_ct = 0;
671 unsigned int i;
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000672 KMP_CPU_SET_ITERATE(i, fullMask) {
Jim Cownie5e8470a2013-09-27 10:38:44 +0000673 //
674 // Skip this proc if it is not included in the machine model.
675 //
676 if (! KMP_CPU_ISSET(i, fullMask)) {
677 continue;
678 }
679
680 Address addr(1);
681 addr.labels[0] = i;
682 (*address2os)[avail_ct++] = AddrUnsPair(addr,i);
683 }
684 if (__kmp_affinity_verbose) {
685 KMP_INFORM(OSProcToPackage, "KMP_AFFINITY");
686 }
687
688 if (__kmp_affinity_gran_levels < 0) {
689 //
690 // Only the package level is modeled in the machine topology map,
691 // so the #levels of granularity is either 0 or 1.
692 //
693 if (__kmp_affinity_gran > affinity_gran_package) {
694 __kmp_affinity_gran_levels = 1;
695 }
696 else {
697 __kmp_affinity_gran_levels = 0;
698 }
699 }
700 return 1;
701}
702
703
Andrey Churbanov7daf9802015-01-27 16:52:57 +0000704# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +0000705
706//
707// If multiple Windows* OS processor groups exist, we can create a 2-level
708// topology map with the groups at level 0 and the individual procs at
709// level 1.
710//
711// This facilitates letting the threads float among all procs in a group,
712// if granularity=group (the default when there are multiple groups).
713//
714static int
715__kmp_affinity_create_proc_group_map(AddrUnsPair **address2os,
716 kmp_i18n_id_t *const msg_id)
717{
718 *address2os = NULL;
719 *msg_id = kmp_i18n_null;
720
721 //
722 // If we don't have multiple processor groups, return now.
723 // The flat mapping will be used.
724 //
725 if ((! KMP_AFFINITY_CAPABLE()) || (__kmp_get_proc_group(fullMask) >= 0)) {
726 // FIXME set *msg_id
727 return -1;
728 }
729
730 //
731 // Contruct the data structure to be returned.
732 //
733 *address2os = (AddrUnsPair*)
734 __kmp_allocate(sizeof(**address2os) * __kmp_avail_proc);
735 int avail_ct = 0;
736 int i;
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000737 KMP_CPU_SET_ITERATE(i, fullMask) {
Jim Cownie5e8470a2013-09-27 10:38:44 +0000738 //
739 // Skip this proc if it is not included in the machine model.
740 //
741 if (! KMP_CPU_ISSET(i, fullMask)) {
742 continue;
743 }
744
745 Address addr(2);
746 addr.labels[0] = i / (CHAR_BIT * sizeof(DWORD_PTR));
747 addr.labels[1] = i % (CHAR_BIT * sizeof(DWORD_PTR));
748 (*address2os)[avail_ct++] = AddrUnsPair(addr,i);
749
750 if (__kmp_affinity_verbose) {
751 KMP_INFORM(AffOSProcToGroup, "KMP_AFFINITY", i, addr.labels[0],
752 addr.labels[1]);
753 }
754 }
755
756 if (__kmp_affinity_gran_levels < 0) {
757 if (__kmp_affinity_gran == affinity_gran_group) {
758 __kmp_affinity_gran_levels = 1;
759 }
760 else if ((__kmp_affinity_gran == affinity_gran_fine)
761 || (__kmp_affinity_gran == affinity_gran_thread)) {
762 __kmp_affinity_gran_levels = 0;
763 }
764 else {
765 const char *gran_str = NULL;
766 if (__kmp_affinity_gran == affinity_gran_core) {
767 gran_str = "core";
768 }
769 else if (__kmp_affinity_gran == affinity_gran_package) {
770 gran_str = "package";
771 }
772 else if (__kmp_affinity_gran == affinity_gran_node) {
773 gran_str = "node";
774 }
775 else {
776 KMP_ASSERT(0);
777 }
778
779 // Warning: can't use affinity granularity \"gran\" with group topology method, using "thread"
780 __kmp_affinity_gran_levels = 0;
781 }
782 }
783 return 2;
784}
785
Andrey Churbanov7daf9802015-01-27 16:52:57 +0000786# endif /* KMP_GROUP_AFFINITY */
Jim Cownie5e8470a2013-09-27 10:38:44 +0000787
788
789# if KMP_ARCH_X86 || KMP_ARCH_X86_64
790
791static int
792__kmp_cpuid_mask_width(int count) {
793 int r = 0;
794
795 while((1<<r) < count)
796 ++r;
797 return r;
798}
799
800
801class apicThreadInfo {
802public:
803 unsigned osId; // param to __kmp_affinity_bind_thread
804 unsigned apicId; // from cpuid after binding
805 unsigned maxCoresPerPkg; // ""
806 unsigned maxThreadsPerPkg; // ""
807 unsigned pkgId; // inferred from above values
808 unsigned coreId; // ""
809 unsigned threadId; // ""
810};
811
812
813static int
814__kmp_affinity_cmp_apicThreadInfo_os_id(const void *a, const void *b)
815{
816 const apicThreadInfo *aa = (const apicThreadInfo *)a;
817 const apicThreadInfo *bb = (const apicThreadInfo *)b;
818 if (aa->osId < bb->osId) return -1;
819 if (aa->osId > bb->osId) return 1;
820 return 0;
821}
822
823
824static int
825__kmp_affinity_cmp_apicThreadInfo_phys_id(const void *a, const void *b)
826{
827 const apicThreadInfo *aa = (const apicThreadInfo *)a;
828 const apicThreadInfo *bb = (const apicThreadInfo *)b;
829 if (aa->pkgId < bb->pkgId) return -1;
830 if (aa->pkgId > bb->pkgId) return 1;
831 if (aa->coreId < bb->coreId) return -1;
832 if (aa->coreId > bb->coreId) return 1;
833 if (aa->threadId < bb->threadId) return -1;
834 if (aa->threadId > bb->threadId) return 1;
835 return 0;
836}
837
838
839//
840// On IA-32 architecture and Intel(R) 64 architecture, we attempt to use
841// an algorithm which cycles through the available os threads, setting
842// the current thread's affinity mask to that thread, and then retrieves
843// the Apic Id for each thread context using the cpuid instruction.
844//
845static int
846__kmp_affinity_create_apicid_map(AddrUnsPair **address2os,
847 kmp_i18n_id_t *const msg_id)
848{
Andrey Churbanov1c331292015-01-27 17:03:42 +0000849 kmp_cpuid buf;
Jim Cownie5e8470a2013-09-27 10:38:44 +0000850 int rc;
851 *address2os = NULL;
852 *msg_id = kmp_i18n_null;
853
Andrey Churbanov1c331292015-01-27 17:03:42 +0000854 //
855 // Check if cpuid leaf 4 is supported.
856 //
Jim Cownie5e8470a2013-09-27 10:38:44 +0000857 __kmp_x86_cpuid(0, 0, &buf);
858 if (buf.eax < 4) {
859 *msg_id = kmp_i18n_str_NoLeaf4Support;
860 return -1;
861 }
Jim Cownie5e8470a2013-09-27 10:38:44 +0000862
863 //
Jim Cownie5e8470a2013-09-27 10:38:44 +0000864 // The algorithm used starts by setting the affinity to each available
Andrey Churbanov1c331292015-01-27 17:03:42 +0000865 // thread and retrieving info from the cpuid instruction, so if we are
866 // not capable of calling __kmp_get_system_affinity() and
867 // _kmp_get_system_affinity(), then we need to do something else - use
868 // the defaults that we calculated from issuing cpuid without binding
869 // to each proc.
Jim Cownie5e8470a2013-09-27 10:38:44 +0000870 //
871 if (! KMP_AFFINITY_CAPABLE()) {
872 //
873 // Hack to try and infer the machine topology using only the data
874 // available from cpuid on the current thread, and __kmp_xproc.
875 //
876 KMP_ASSERT(__kmp_affinity_type == affinity_none);
877
878 //
879 // Get an upper bound on the number of threads per package using
880 // cpuid(1).
881 //
882 // On some OS/chps combinations where HT is supported by the chip
883 // but is disabled, this value will be 2 on a single core chip.
884 // Usually, it will be 2 if HT is enabled and 1 if HT is disabled.
885 //
Jim Cownie5e8470a2013-09-27 10:38:44 +0000886 __kmp_x86_cpuid(1, 0, &buf);
887 int maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
888 if (maxThreadsPerPkg == 0) {
889 maxThreadsPerPkg = 1;
890 }
891
892 //
893 // The num cores per pkg comes from cpuid(4).
894 // 1 must be added to the encoded value.
895 //
896 // The author of cpu_count.cpp treated this only an upper bound
897 // on the number of cores, but I haven't seen any cases where it
898 // was greater than the actual number of cores, so we will treat
899 // it as exact in this block of code.
900 //
901 // First, we need to check if cpuid(4) is supported on this chip.
902 // To see if cpuid(n) is supported, issue cpuid(0) and check if eax
903 // has the value n or greater.
904 //
905 __kmp_x86_cpuid(0, 0, &buf);
906 if (buf.eax >= 4) {
907 __kmp_x86_cpuid(4, 0, &buf);
908 nCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
909 }
910 else {
911 nCoresPerPkg = 1;
912 }
913
914 //
915 // There is no way to reliably tell if HT is enabled without issuing
916 // the cpuid instruction from every thread, can correlating the cpuid
917 // info, so if the machine is not affinity capable, we assume that HT
918 // is off. We have seen quite a few machines where maxThreadsPerPkg
919 // is 2, yet the machine does not support HT.
920 //
921 // - Older OSes are usually found on machines with older chips, which
922 // do not support HT.
923 //
924 // - The performance penalty for mistakenly identifying a machine as
925 // HT when it isn't (which results in blocktime being incorrecly set
926 // to 0) is greater than the penalty when for mistakenly identifying
927 // a machine as being 1 thread/core when it is really HT enabled
928 // (which results in blocktime being incorrectly set to a positive
929 // value).
930 //
931 __kmp_ncores = __kmp_xproc;
932 nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
933 __kmp_nThreadsPerCore = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +0000934 if (__kmp_affinity_verbose) {
935 KMP_INFORM(AffNotCapableUseLocCpuid, "KMP_AFFINITY");
936 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
937 if (__kmp_affinity_uniform_topology()) {
938 KMP_INFORM(Uniform, "KMP_AFFINITY");
939 } else {
940 KMP_INFORM(NonUniform, "KMP_AFFINITY");
941 }
942 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
943 __kmp_nThreadsPerCore, __kmp_ncores);
944 }
945 return 0;
946 }
947
948 //
949 //
950 // From here on, we can assume that it is safe to call
951 // __kmp_get_system_affinity() and __kmp_set_system_affinity(),
952 // even if __kmp_affinity_type = affinity_none.
953 //
954
955 //
956 // Save the affinity mask for the current thread.
957 //
958 kmp_affin_mask_t *oldMask;
959 KMP_CPU_ALLOC(oldMask);
960 KMP_ASSERT(oldMask != NULL);
961 __kmp_get_system_affinity(oldMask, TRUE);
962
963 //
964 // Run through each of the available contexts, binding the current thread
965 // to it, and obtaining the pertinent information using the cpuid instr.
966 //
967 // The relevant information is:
968 //
969 // Apic Id: Bits 24:31 of ebx after issuing cpuid(1) - each thread context
970 // has a uniqie Apic Id, which is of the form pkg# : core# : thread#.
971 //
972 // Max Threads Per Pkg: Bits 16:23 of ebx after issuing cpuid(1). The
973 // value of this field determines the width of the core# + thread#
974 // fields in the Apic Id. It is also an upper bound on the number
975 // of threads per package, but it has been verified that situations
976 // happen were it is not exact. In particular, on certain OS/chip
977 // combinations where Intel(R) Hyper-Threading Technology is supported
978 // by the chip but has
979 // been disabled, the value of this field will be 2 (for a single core
980 // chip). On other OS/chip combinations supporting
981 // Intel(R) Hyper-Threading Technology, the value of
982 // this field will be 1 when Intel(R) Hyper-Threading Technology is
983 // disabled and 2 when it is enabled.
984 //
985 // Max Cores Per Pkg: Bits 26:31 of eax after issuing cpuid(4). The
986 // value of this field (+1) determines the width of the core# field in
987 // the Apic Id. The comments in "cpucount.cpp" say that this value is
988 // an upper bound, but the IA-32 architecture manual says that it is
989 // exactly the number of cores per package, and I haven't seen any
990 // case where it wasn't.
991 //
992 // From this information, deduce the package Id, core Id, and thread Id,
993 // and set the corresponding fields in the apicThreadInfo struct.
994 //
995 unsigned i;
996 apicThreadInfo *threadInfo = (apicThreadInfo *)__kmp_allocate(
997 __kmp_avail_proc * sizeof(apicThreadInfo));
998 unsigned nApics = 0;
Jonathan Peyton01dcf362015-11-30 20:02:59 +0000999 KMP_CPU_SET_ITERATE(i, fullMask) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00001000 //
1001 // Skip this proc if it is not included in the machine model.
1002 //
1003 if (! KMP_CPU_ISSET(i, fullMask)) {
1004 continue;
1005 }
1006 KMP_DEBUG_ASSERT((int)nApics < __kmp_avail_proc);
1007
1008 __kmp_affinity_bind_thread(i);
1009 threadInfo[nApics].osId = i;
1010
1011 //
1012 // The apic id and max threads per pkg come from cpuid(1).
1013 //
Jim Cownie5e8470a2013-09-27 10:38:44 +00001014 __kmp_x86_cpuid(1, 0, &buf);
1015 if (! (buf.edx >> 9) & 1) {
1016 __kmp_set_system_affinity(oldMask, TRUE);
1017 __kmp_free(threadInfo);
1018 KMP_CPU_FREE(oldMask);
1019 *msg_id = kmp_i18n_str_ApicNotPresent;
1020 return -1;
1021 }
1022 threadInfo[nApics].apicId = (buf.ebx >> 24) & 0xff;
1023 threadInfo[nApics].maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
1024 if (threadInfo[nApics].maxThreadsPerPkg == 0) {
1025 threadInfo[nApics].maxThreadsPerPkg = 1;
1026 }
1027
1028 //
1029 // Max cores per pkg comes from cpuid(4).
1030 // 1 must be added to the encoded value.
1031 //
1032 // First, we need to check if cpuid(4) is supported on this chip.
1033 // To see if cpuid(n) is supported, issue cpuid(0) and check if eax
1034 // has the value n or greater.
1035 //
1036 __kmp_x86_cpuid(0, 0, &buf);
1037 if (buf.eax >= 4) {
1038 __kmp_x86_cpuid(4, 0, &buf);
1039 threadInfo[nApics].maxCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
1040 }
1041 else {
1042 threadInfo[nApics].maxCoresPerPkg = 1;
1043 }
1044
1045 //
1046 // Infer the pkgId / coreId / threadId using only the info
1047 // obtained locally.
1048 //
1049 int widthCT = __kmp_cpuid_mask_width(
1050 threadInfo[nApics].maxThreadsPerPkg);
1051 threadInfo[nApics].pkgId = threadInfo[nApics].apicId >> widthCT;
1052
1053 int widthC = __kmp_cpuid_mask_width(
1054 threadInfo[nApics].maxCoresPerPkg);
1055 int widthT = widthCT - widthC;
1056 if (widthT < 0) {
1057 //
1058 // I've never seen this one happen, but I suppose it could, if
1059 // the cpuid instruction on a chip was really screwed up.
1060 // Make sure to restore the affinity mask before the tail call.
1061 //
1062 __kmp_set_system_affinity(oldMask, TRUE);
1063 __kmp_free(threadInfo);
1064 KMP_CPU_FREE(oldMask);
1065 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1066 return -1;
1067 }
1068
1069 int maskC = (1 << widthC) - 1;
1070 threadInfo[nApics].coreId = (threadInfo[nApics].apicId >> widthT)
1071 &maskC;
1072
1073 int maskT = (1 << widthT) - 1;
1074 threadInfo[nApics].threadId = threadInfo[nApics].apicId &maskT;
1075
1076 nApics++;
1077 }
1078
1079 //
1080 // We've collected all the info we need.
1081 // Restore the old affinity mask for this thread.
1082 //
1083 __kmp_set_system_affinity(oldMask, TRUE);
1084
1085 //
1086 // If there's only one thread context to bind to, form an Address object
1087 // with depth 1 and return immediately (or, if affinity is off, set
1088 // address2os to NULL and return).
1089 //
1090 // If it is configured to omit the package level when there is only a
1091 // single package, the logic at the end of this routine won't work if
1092 // there is only a single thread - it would try to form an Address
1093 // object with depth 0.
1094 //
1095 KMP_ASSERT(nApics > 0);
1096 if (nApics == 1) {
1097 __kmp_ncores = nPackages = 1;
1098 __kmp_nThreadsPerCore = nCoresPerPkg = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001099 if (__kmp_affinity_verbose) {
1100 char buf[KMP_AFFIN_MASK_PRINT_LEN];
1101 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
1102
1103 KMP_INFORM(AffUseGlobCpuid, "KMP_AFFINITY");
1104 if (__kmp_affinity_respect_mask) {
1105 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
1106 } else {
1107 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
1108 }
1109 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
1110 KMP_INFORM(Uniform, "KMP_AFFINITY");
1111 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
1112 __kmp_nThreadsPerCore, __kmp_ncores);
1113 }
1114
1115 if (__kmp_affinity_type == affinity_none) {
1116 __kmp_free(threadInfo);
1117 KMP_CPU_FREE(oldMask);
1118 return 0;
1119 }
1120
1121 *address2os = (AddrUnsPair*)__kmp_allocate(sizeof(AddrUnsPair));
1122 Address addr(1);
1123 addr.labels[0] = threadInfo[0].pkgId;
1124 (*address2os)[0] = AddrUnsPair(addr, threadInfo[0].osId);
1125
1126 if (__kmp_affinity_gran_levels < 0) {
1127 __kmp_affinity_gran_levels = 0;
1128 }
1129
1130 if (__kmp_affinity_verbose) {
1131 __kmp_affinity_print_topology(*address2os, 1, 1, 0, -1, -1);
1132 }
1133
1134 __kmp_free(threadInfo);
1135 KMP_CPU_FREE(oldMask);
1136 return 1;
1137 }
1138
1139 //
1140 // Sort the threadInfo table by physical Id.
1141 //
1142 qsort(threadInfo, nApics, sizeof(*threadInfo),
1143 __kmp_affinity_cmp_apicThreadInfo_phys_id);
1144
1145 //
1146 // The table is now sorted by pkgId / coreId / threadId, but we really
1147 // don't know the radix of any of the fields. pkgId's may be sparsely
1148 // assigned among the chips on a system. Although coreId's are usually
1149 // assigned [0 .. coresPerPkg-1] and threadId's are usually assigned
1150 // [0..threadsPerCore-1], we don't want to make any such assumptions.
1151 //
1152 // For that matter, we don't know what coresPerPkg and threadsPerCore
1153 // (or the total # packages) are at this point - we want to determine
1154 // that now. We only have an upper bound on the first two figures.
1155 //
1156 // We also perform a consistency check at this point: the values returned
1157 // by the cpuid instruction for any thread bound to a given package had
1158 // better return the same info for maxThreadsPerPkg and maxCoresPerPkg.
1159 //
1160 nPackages = 1;
1161 nCoresPerPkg = 1;
1162 __kmp_nThreadsPerCore = 1;
1163 unsigned nCores = 1;
1164
1165 unsigned pkgCt = 1; // to determine radii
1166 unsigned lastPkgId = threadInfo[0].pkgId;
1167 unsigned coreCt = 1;
1168 unsigned lastCoreId = threadInfo[0].coreId;
1169 unsigned threadCt = 1;
1170 unsigned lastThreadId = threadInfo[0].threadId;
1171
1172 // intra-pkg consist checks
1173 unsigned prevMaxCoresPerPkg = threadInfo[0].maxCoresPerPkg;
1174 unsigned prevMaxThreadsPerPkg = threadInfo[0].maxThreadsPerPkg;
1175
1176 for (i = 1; i < nApics; i++) {
1177 if (threadInfo[i].pkgId != lastPkgId) {
1178 nCores++;
1179 pkgCt++;
1180 lastPkgId = threadInfo[i].pkgId;
1181 if ((int)coreCt > nCoresPerPkg) nCoresPerPkg = coreCt;
1182 coreCt = 1;
1183 lastCoreId = threadInfo[i].coreId;
1184 if ((int)threadCt > __kmp_nThreadsPerCore) __kmp_nThreadsPerCore = threadCt;
1185 threadCt = 1;
1186 lastThreadId = threadInfo[i].threadId;
1187
1188 //
1189 // This is a different package, so go on to the next iteration
1190 // without doing any consistency checks. Reset the consistency
1191 // check vars, though.
1192 //
1193 prevMaxCoresPerPkg = threadInfo[i].maxCoresPerPkg;
1194 prevMaxThreadsPerPkg = threadInfo[i].maxThreadsPerPkg;
1195 continue;
1196 }
1197
1198 if (threadInfo[i].coreId != lastCoreId) {
1199 nCores++;
1200 coreCt++;
1201 lastCoreId = threadInfo[i].coreId;
1202 if ((int)threadCt > __kmp_nThreadsPerCore) __kmp_nThreadsPerCore = threadCt;
1203 threadCt = 1;
1204 lastThreadId = threadInfo[i].threadId;
1205 }
1206 else if (threadInfo[i].threadId != lastThreadId) {
1207 threadCt++;
1208 lastThreadId = threadInfo[i].threadId;
1209 }
1210 else {
1211 __kmp_free(threadInfo);
1212 KMP_CPU_FREE(oldMask);
1213 *msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;
1214 return -1;
1215 }
1216
1217 //
1218 // Check to make certain that the maxCoresPerPkg and maxThreadsPerPkg
1219 // fields agree between all the threads bounds to a given package.
1220 //
1221 if ((prevMaxCoresPerPkg != threadInfo[i].maxCoresPerPkg)
1222 || (prevMaxThreadsPerPkg != threadInfo[i].maxThreadsPerPkg)) {
1223 __kmp_free(threadInfo);
1224 KMP_CPU_FREE(oldMask);
1225 *msg_id = kmp_i18n_str_InconsistentCpuidInfo;
1226 return -1;
1227 }
1228 }
1229 nPackages = pkgCt;
1230 if ((int)coreCt > nCoresPerPkg) nCoresPerPkg = coreCt;
1231 if ((int)threadCt > __kmp_nThreadsPerCore) __kmp_nThreadsPerCore = threadCt;
1232
1233 //
1234 // When affinity is off, this routine will still be called to set
Andrey Churbanovf696c822015-01-27 16:55:43 +00001235 // __kmp_ncores, as well as __kmp_nThreadsPerCore,
Jim Cownie5e8470a2013-09-27 10:38:44 +00001236 // nCoresPerPkg, & nPackages. Make sure all these vars are set
1237 // correctly, and return now if affinity is not enabled.
1238 //
Jim Cownie5e8470a2013-09-27 10:38:44 +00001239 __kmp_ncores = nCores;
1240 if (__kmp_affinity_verbose) {
1241 char buf[KMP_AFFIN_MASK_PRINT_LEN];
1242 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
1243
1244 KMP_INFORM(AffUseGlobCpuid, "KMP_AFFINITY");
1245 if (__kmp_affinity_respect_mask) {
1246 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
1247 } else {
1248 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
1249 }
1250 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
1251 if (__kmp_affinity_uniform_topology()) {
1252 KMP_INFORM(Uniform, "KMP_AFFINITY");
1253 } else {
1254 KMP_INFORM(NonUniform, "KMP_AFFINITY");
1255 }
1256 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
1257 __kmp_nThreadsPerCore, __kmp_ncores);
1258
1259 }
1260
1261 if (__kmp_affinity_type == affinity_none) {
1262 __kmp_free(threadInfo);
1263 KMP_CPU_FREE(oldMask);
1264 return 0;
1265 }
1266
1267 //
1268 // Now that we've determined the number of packages, the number of cores
1269 // per package, and the number of threads per core, we can construct the
1270 // data structure that is to be returned.
1271 //
1272 int pkgLevel = 0;
1273 int coreLevel = (nCoresPerPkg <= 1) ? -1 : 1;
1274 int threadLevel = (__kmp_nThreadsPerCore <= 1) ? -1 : ((coreLevel >= 0) ? 2 : 1);
1275 unsigned depth = (pkgLevel >= 0) + (coreLevel >= 0) + (threadLevel >= 0);
1276
1277 KMP_ASSERT(depth > 0);
1278 *address2os = (AddrUnsPair*)__kmp_allocate(sizeof(AddrUnsPair) * nApics);
1279
1280 for (i = 0; i < nApics; ++i) {
1281 Address addr(depth);
1282 unsigned os = threadInfo[i].osId;
1283 int d = 0;
1284
1285 if (pkgLevel >= 0) {
1286 addr.labels[d++] = threadInfo[i].pkgId;
1287 }
1288 if (coreLevel >= 0) {
1289 addr.labels[d++] = threadInfo[i].coreId;
1290 }
1291 if (threadLevel >= 0) {
1292 addr.labels[d++] = threadInfo[i].threadId;
1293 }
1294 (*address2os)[i] = AddrUnsPair(addr, os);
1295 }
1296
1297 if (__kmp_affinity_gran_levels < 0) {
1298 //
1299 // Set the granularity level based on what levels are modeled
1300 // in the machine topology map.
1301 //
1302 __kmp_affinity_gran_levels = 0;
1303 if ((threadLevel >= 0)
1304 && (__kmp_affinity_gran > affinity_gran_thread)) {
1305 __kmp_affinity_gran_levels++;
1306 }
1307 if ((coreLevel >= 0) && (__kmp_affinity_gran > affinity_gran_core)) {
1308 __kmp_affinity_gran_levels++;
1309 }
1310 if ((pkgLevel >= 0) && (__kmp_affinity_gran > affinity_gran_package)) {
1311 __kmp_affinity_gran_levels++;
1312 }
1313 }
1314
1315 if (__kmp_affinity_verbose) {
1316 __kmp_affinity_print_topology(*address2os, nApics, depth, pkgLevel,
1317 coreLevel, threadLevel);
1318 }
1319
1320 __kmp_free(threadInfo);
1321 KMP_CPU_FREE(oldMask);
1322 return depth;
1323}
1324
1325
1326//
1327// Intel(R) microarchitecture code name Nehalem, Dunnington and later
1328// architectures support a newer interface for specifying the x2APIC Ids,
1329// based on cpuid leaf 11.
1330//
1331static int
1332__kmp_affinity_create_x2apicid_map(AddrUnsPair **address2os,
1333 kmp_i18n_id_t *const msg_id)
1334{
1335 kmp_cpuid buf;
1336
1337 *address2os = NULL;
1338 *msg_id = kmp_i18n_null;
1339
1340 //
1341 // Check to see if cpuid leaf 11 is supported.
1342 //
1343 __kmp_x86_cpuid(0, 0, &buf);
1344 if (buf.eax < 11) {
1345 *msg_id = kmp_i18n_str_NoLeaf11Support;
1346 return -1;
1347 }
1348 __kmp_x86_cpuid(11, 0, &buf);
1349 if (buf.ebx == 0) {
1350 *msg_id = kmp_i18n_str_NoLeaf11Support;
1351 return -1;
1352 }
1353
1354 //
1355 // Find the number of levels in the machine topology. While we're at it,
1356 // get the default values for __kmp_nThreadsPerCore & nCoresPerPkg. We will
1357 // try to get more accurate values later by explicitly counting them,
1358 // but get reasonable defaults now, in case we return early.
1359 //
1360 int level;
1361 int threadLevel = -1;
1362 int coreLevel = -1;
1363 int pkgLevel = -1;
1364 __kmp_nThreadsPerCore = nCoresPerPkg = nPackages = 1;
1365
1366 for (level = 0;; level++) {
1367 if (level > 31) {
1368 //
1369 // FIXME: Hack for DPD200163180
1370 //
1371 // If level is big then something went wrong -> exiting
1372 //
1373 // There could actually be 32 valid levels in the machine topology,
1374 // but so far, the only machine we have seen which does not exit
1375 // this loop before iteration 32 has fubar x2APIC settings.
1376 //
1377 // For now, just reject this case based upon loop trip count.
1378 //
1379 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1380 return -1;
1381 }
1382 __kmp_x86_cpuid(11, level, &buf);
1383 if (buf.ebx == 0) {
1384 if (pkgLevel < 0) {
1385 //
1386 // Will infer nPackages from __kmp_xproc
1387 //
1388 pkgLevel = level;
1389 level++;
1390 }
1391 break;
1392 }
1393 int kind = (buf.ecx >> 8) & 0xff;
1394 if (kind == 1) {
1395 //
1396 // SMT level
1397 //
1398 threadLevel = level;
1399 coreLevel = -1;
1400 pkgLevel = -1;
1401 __kmp_nThreadsPerCore = buf.ebx & 0xff;
1402 if (__kmp_nThreadsPerCore == 0) {
1403 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1404 return -1;
1405 }
1406 }
1407 else if (kind == 2) {
1408 //
1409 // core level
1410 //
1411 coreLevel = level;
1412 pkgLevel = -1;
1413 nCoresPerPkg = buf.ebx & 0xff;
1414 if (nCoresPerPkg == 0) {
1415 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1416 return -1;
1417 }
1418 }
1419 else {
1420 if (level <= 0) {
1421 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1422 return -1;
1423 }
1424 if (pkgLevel >= 0) {
1425 continue;
1426 }
1427 pkgLevel = level;
1428 nPackages = buf.ebx & 0xff;
1429 if (nPackages == 0) {
1430 *msg_id = kmp_i18n_str_InvalidCpuidInfo;
1431 return -1;
1432 }
1433 }
1434 }
1435 int depth = level;
1436
1437 //
1438 // In the above loop, "level" was counted from the finest level (usually
1439 // thread) to the coarsest. The caller expects that we will place the
1440 // labels in (*address2os)[].first.labels[] in the inverse order, so
1441 // we need to invert the vars saying which level means what.
1442 //
1443 if (threadLevel >= 0) {
1444 threadLevel = depth - threadLevel - 1;
1445 }
1446 if (coreLevel >= 0) {
1447 coreLevel = depth - coreLevel - 1;
1448 }
1449 KMP_DEBUG_ASSERT(pkgLevel >= 0);
1450 pkgLevel = depth - pkgLevel - 1;
1451
1452 //
1453 // The algorithm used starts by setting the affinity to each available
Andrey Churbanov1c331292015-01-27 17:03:42 +00001454 // thread and retrieving info from the cpuid instruction, so if we are
1455 // not capable of calling __kmp_get_system_affinity() and
1456 // _kmp_get_system_affinity(), then we need to do something else - use
1457 // the defaults that we calculated from issuing cpuid without binding
1458 // to each proc.
Jim Cownie5e8470a2013-09-27 10:38:44 +00001459 //
1460 if (! KMP_AFFINITY_CAPABLE())
1461 {
1462 //
1463 // Hack to try and infer the machine topology using only the data
1464 // available from cpuid on the current thread, and __kmp_xproc.
1465 //
1466 KMP_ASSERT(__kmp_affinity_type == affinity_none);
1467
1468 __kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;
1469 nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001470 if (__kmp_affinity_verbose) {
1471 KMP_INFORM(AffNotCapableUseLocCpuidL11, "KMP_AFFINITY");
1472 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
1473 if (__kmp_affinity_uniform_topology()) {
1474 KMP_INFORM(Uniform, "KMP_AFFINITY");
1475 } else {
1476 KMP_INFORM(NonUniform, "KMP_AFFINITY");
1477 }
1478 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
1479 __kmp_nThreadsPerCore, __kmp_ncores);
1480 }
1481 return 0;
1482 }
1483
1484 //
1485 //
1486 // From here on, we can assume that it is safe to call
1487 // __kmp_get_system_affinity() and __kmp_set_system_affinity(),
1488 // even if __kmp_affinity_type = affinity_none.
1489 //
1490
1491 //
1492 // Save the affinity mask for the current thread.
1493 //
1494 kmp_affin_mask_t *oldMask;
1495 KMP_CPU_ALLOC(oldMask);
1496 __kmp_get_system_affinity(oldMask, TRUE);
1497
1498 //
1499 // Allocate the data structure to be returned.
1500 //
1501 AddrUnsPair *retval = (AddrUnsPair *)
1502 __kmp_allocate(sizeof(AddrUnsPair) * __kmp_avail_proc);
1503
1504 //
1505 // Run through each of the available contexts, binding the current thread
1506 // to it, and obtaining the pertinent information using the cpuid instr.
1507 //
1508 unsigned int proc;
1509 int nApics = 0;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00001510 KMP_CPU_SET_ITERATE(proc, fullMask) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00001511 //
1512 // Skip this proc if it is not included in the machine model.
1513 //
1514 if (! KMP_CPU_ISSET(proc, fullMask)) {
1515 continue;
1516 }
1517 KMP_DEBUG_ASSERT(nApics < __kmp_avail_proc);
1518
1519 __kmp_affinity_bind_thread(proc);
1520
1521 //
1522 // Extrach the labels for each level in the machine topology map
1523 // from the Apic ID.
1524 //
1525 Address addr(depth);
1526 int prev_shift = 0;
1527
1528 for (level = 0; level < depth; level++) {
1529 __kmp_x86_cpuid(11, level, &buf);
1530 unsigned apicId = buf.edx;
1531 if (buf.ebx == 0) {
1532 if (level != depth - 1) {
1533 KMP_CPU_FREE(oldMask);
1534 *msg_id = kmp_i18n_str_InconsistentCpuidInfo;
1535 return -1;
1536 }
1537 addr.labels[depth - level - 1] = apicId >> prev_shift;
1538 level++;
1539 break;
1540 }
1541 int shift = buf.eax & 0x1f;
1542 int mask = (1 << shift) - 1;
1543 addr.labels[depth - level - 1] = (apicId & mask) >> prev_shift;
1544 prev_shift = shift;
1545 }
1546 if (level != depth) {
1547 KMP_CPU_FREE(oldMask);
1548 *msg_id = kmp_i18n_str_InconsistentCpuidInfo;
1549 return -1;
1550 }
1551
1552 retval[nApics] = AddrUnsPair(addr, proc);
1553 nApics++;
1554 }
1555
1556 //
1557 // We've collected all the info we need.
1558 // Restore the old affinity mask for this thread.
1559 //
1560 __kmp_set_system_affinity(oldMask, TRUE);
1561
1562 //
1563 // If there's only one thread context to bind to, return now.
1564 //
1565 KMP_ASSERT(nApics > 0);
1566 if (nApics == 1) {
1567 __kmp_ncores = nPackages = 1;
1568 __kmp_nThreadsPerCore = nCoresPerPkg = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001569 if (__kmp_affinity_verbose) {
1570 char buf[KMP_AFFIN_MASK_PRINT_LEN];
1571 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
1572
1573 KMP_INFORM(AffUseGlobCpuidL11, "KMP_AFFINITY");
1574 if (__kmp_affinity_respect_mask) {
1575 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
1576 } else {
1577 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
1578 }
1579 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
1580 KMP_INFORM(Uniform, "KMP_AFFINITY");
1581 KMP_INFORM(Topology, "KMP_AFFINITY", nPackages, nCoresPerPkg,
1582 __kmp_nThreadsPerCore, __kmp_ncores);
1583 }
1584
1585 if (__kmp_affinity_type == affinity_none) {
1586 __kmp_free(retval);
1587 KMP_CPU_FREE(oldMask);
1588 return 0;
1589 }
1590
1591 //
1592 // Form an Address object which only includes the package level.
1593 //
1594 Address addr(1);
1595 addr.labels[0] = retval[0].first.labels[pkgLevel];
1596 retval[0].first = addr;
1597
1598 if (__kmp_affinity_gran_levels < 0) {
1599 __kmp_affinity_gran_levels = 0;
1600 }
1601
1602 if (__kmp_affinity_verbose) {
1603 __kmp_affinity_print_topology(retval, 1, 1, 0, -1, -1);
1604 }
1605
1606 *address2os = retval;
1607 KMP_CPU_FREE(oldMask);
1608 return 1;
1609 }
1610
1611 //
1612 // Sort the table by physical Id.
1613 //
1614 qsort(retval, nApics, sizeof(*retval), __kmp_affinity_cmp_Address_labels);
1615
1616 //
1617 // Find the radix at each of the levels.
1618 //
1619 unsigned *totals = (unsigned *)__kmp_allocate(depth * sizeof(unsigned));
1620 unsigned *counts = (unsigned *)__kmp_allocate(depth * sizeof(unsigned));
1621 unsigned *maxCt = (unsigned *)__kmp_allocate(depth * sizeof(unsigned));
1622 unsigned *last = (unsigned *)__kmp_allocate(depth * sizeof(unsigned));
1623 for (level = 0; level < depth; level++) {
1624 totals[level] = 1;
1625 maxCt[level] = 1;
1626 counts[level] = 1;
1627 last[level] = retval[0].first.labels[level];
1628 }
1629
1630 //
1631 // From here on, the iteration variable "level" runs from the finest
1632 // level to the coarsest, i.e. we iterate forward through
1633 // (*address2os)[].first.labels[] - in the previous loops, we iterated
1634 // backwards.
1635 //
1636 for (proc = 1; (int)proc < nApics; proc++) {
1637 int level;
1638 for (level = 0; level < depth; level++) {
1639 if (retval[proc].first.labels[level] != last[level]) {
1640 int j;
1641 for (j = level + 1; j < depth; j++) {
1642 totals[j]++;
1643 counts[j] = 1;
1644 // The line below causes printing incorrect topology information
1645 // in case the max value for some level (maxCt[level]) is encountered earlier than
1646 // some less value while going through the array.
1647 // For example, let pkg0 has 4 cores and pkg1 has 2 cores. Then maxCt[1] == 2
1648 // whereas it must be 4.
1649 // TODO!!! Check if it can be commented safely
1650 //maxCt[j] = 1;
1651 last[j] = retval[proc].first.labels[j];
1652 }
1653 totals[level]++;
1654 counts[level]++;
1655 if (counts[level] > maxCt[level]) {
1656 maxCt[level] = counts[level];
1657 }
1658 last[level] = retval[proc].first.labels[level];
1659 break;
1660 }
1661 else if (level == depth - 1) {
1662 __kmp_free(last);
1663 __kmp_free(maxCt);
1664 __kmp_free(counts);
1665 __kmp_free(totals);
1666 __kmp_free(retval);
1667 KMP_CPU_FREE(oldMask);
1668 *msg_id = kmp_i18n_str_x2ApicIDsNotUnique;
1669 return -1;
1670 }
1671 }
1672 }
1673
1674 //
1675 // When affinity is off, this routine will still be called to set
Andrey Churbanovf696c822015-01-27 16:55:43 +00001676 // __kmp_ncores, as well as __kmp_nThreadsPerCore,
Jim Cownie5e8470a2013-09-27 10:38:44 +00001677 // nCoresPerPkg, & nPackages. Make sure all these vars are set
1678 // correctly, and return if affinity is not enabled.
1679 //
1680 if (threadLevel >= 0) {
1681 __kmp_nThreadsPerCore = maxCt[threadLevel];
1682 }
1683 else {
1684 __kmp_nThreadsPerCore = 1;
1685 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00001686 nPackages = totals[pkgLevel];
1687
1688 if (coreLevel >= 0) {
1689 __kmp_ncores = totals[coreLevel];
1690 nCoresPerPkg = maxCt[coreLevel];
1691 }
1692 else {
1693 __kmp_ncores = nPackages;
1694 nCoresPerPkg = 1;
1695 }
1696
1697 //
1698 // Check to see if the machine topology is uniform
1699 //
1700 unsigned prod = maxCt[0];
1701 for (level = 1; level < depth; level++) {
1702 prod *= maxCt[level];
1703 }
1704 bool uniform = (prod == totals[level - 1]);
1705
1706 //
1707 // Print the machine topology summary.
1708 //
1709 if (__kmp_affinity_verbose) {
1710 char mask[KMP_AFFIN_MASK_PRINT_LEN];
1711 __kmp_affinity_print_mask(mask, KMP_AFFIN_MASK_PRINT_LEN, oldMask);
1712
1713 KMP_INFORM(AffUseGlobCpuidL11, "KMP_AFFINITY");
1714 if (__kmp_affinity_respect_mask) {
1715 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", mask);
1716 } else {
1717 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", mask);
1718 }
1719 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
1720 if (uniform) {
1721 KMP_INFORM(Uniform, "KMP_AFFINITY");
1722 } else {
1723 KMP_INFORM(NonUniform, "KMP_AFFINITY");
1724 }
1725
1726 kmp_str_buf_t buf;
1727 __kmp_str_buf_init(&buf);
1728
1729 __kmp_str_buf_print(&buf, "%d", totals[0]);
1730 for (level = 1; level <= pkgLevel; level++) {
1731 __kmp_str_buf_print(&buf, " x %d", maxCt[level]);
1732 }
1733 KMP_INFORM(TopologyExtra, "KMP_AFFINITY", buf.str, nCoresPerPkg,
1734 __kmp_nThreadsPerCore, __kmp_ncores);
1735
1736 __kmp_str_buf_free(&buf);
1737 }
1738
1739 if (__kmp_affinity_type == affinity_none) {
1740 __kmp_free(last);
1741 __kmp_free(maxCt);
1742 __kmp_free(counts);
1743 __kmp_free(totals);
1744 __kmp_free(retval);
1745 KMP_CPU_FREE(oldMask);
1746 return 0;
1747 }
1748
1749 //
1750 // Find any levels with radiix 1, and remove them from the map
1751 // (except for the package level).
1752 //
1753 int new_depth = 0;
1754 for (level = 0; level < depth; level++) {
1755 if ((maxCt[level] == 1) && (level != pkgLevel)) {
1756 continue;
1757 }
1758 new_depth++;
1759 }
1760
1761 //
1762 // If we are removing any levels, allocate a new vector to return,
1763 // and copy the relevant information to it.
1764 //
1765 if (new_depth != depth) {
1766 AddrUnsPair *new_retval = (AddrUnsPair *)__kmp_allocate(
1767 sizeof(AddrUnsPair) * nApics);
1768 for (proc = 0; (int)proc < nApics; proc++) {
1769 Address addr(new_depth);
1770 new_retval[proc] = AddrUnsPair(addr, retval[proc].second);
1771 }
1772 int new_level = 0;
Jonathan Peyton62f38402015-08-25 18:44:41 +00001773 int newPkgLevel = -1;
1774 int newCoreLevel = -1;
1775 int newThreadLevel = -1;
1776 int i;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001777 for (level = 0; level < depth; level++) {
Jonathan Peyton62f38402015-08-25 18:44:41 +00001778 if ((maxCt[level] == 1)
1779 && (level != pkgLevel)) {
1780 //
1781 // Remove this level. Never remove the package level
1782 //
1783 continue;
1784 }
1785 if (level == pkgLevel) {
1786 newPkgLevel = level;
1787 }
1788 if (level == coreLevel) {
1789 newCoreLevel = level;
1790 }
1791 if (level == threadLevel) {
1792 newThreadLevel = level;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001793 }
1794 for (proc = 0; (int)proc < nApics; proc++) {
1795 new_retval[proc].first.labels[new_level]
1796 = retval[proc].first.labels[level];
1797 }
1798 new_level++;
1799 }
1800
1801 __kmp_free(retval);
1802 retval = new_retval;
1803 depth = new_depth;
Jonathan Peyton62f38402015-08-25 18:44:41 +00001804 pkgLevel = newPkgLevel;
1805 coreLevel = newCoreLevel;
1806 threadLevel = newThreadLevel;
Jim Cownie5e8470a2013-09-27 10:38:44 +00001807 }
1808
1809 if (__kmp_affinity_gran_levels < 0) {
1810 //
1811 // Set the granularity level based on what levels are modeled
1812 // in the machine topology map.
1813 //
1814 __kmp_affinity_gran_levels = 0;
1815 if ((threadLevel >= 0) && (__kmp_affinity_gran > affinity_gran_thread)) {
1816 __kmp_affinity_gran_levels++;
1817 }
1818 if ((coreLevel >= 0) && (__kmp_affinity_gran > affinity_gran_core)) {
1819 __kmp_affinity_gran_levels++;
1820 }
1821 if (__kmp_affinity_gran > affinity_gran_package) {
1822 __kmp_affinity_gran_levels++;
1823 }
1824 }
1825
1826 if (__kmp_affinity_verbose) {
1827 __kmp_affinity_print_topology(retval, nApics, depth, pkgLevel,
1828 coreLevel, threadLevel);
1829 }
1830
1831 __kmp_free(last);
1832 __kmp_free(maxCt);
1833 __kmp_free(counts);
1834 __kmp_free(totals);
1835 KMP_CPU_FREE(oldMask);
1836 *address2os = retval;
1837 return depth;
1838}
1839
1840
1841# endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
1842
1843
1844#define osIdIndex 0
1845#define threadIdIndex 1
1846#define coreIdIndex 2
1847#define pkgIdIndex 3
1848#define nodeIdIndex 4
1849
1850typedef unsigned *ProcCpuInfo;
1851static unsigned maxIndex = pkgIdIndex;
1852
1853
1854static int
1855__kmp_affinity_cmp_ProcCpuInfo_os_id(const void *a, const void *b)
1856{
1857 const unsigned *aa = (const unsigned *)a;
1858 const unsigned *bb = (const unsigned *)b;
1859 if (aa[osIdIndex] < bb[osIdIndex]) return -1;
1860 if (aa[osIdIndex] > bb[osIdIndex]) return 1;
1861 return 0;
1862};
1863
1864
1865static int
1866__kmp_affinity_cmp_ProcCpuInfo_phys_id(const void *a, const void *b)
1867{
1868 unsigned i;
1869 const unsigned *aa = *((const unsigned **)a);
1870 const unsigned *bb = *((const unsigned **)b);
1871 for (i = maxIndex; ; i--) {
1872 if (aa[i] < bb[i]) return -1;
1873 if (aa[i] > bb[i]) return 1;
1874 if (i == osIdIndex) break;
1875 }
1876 return 0;
1877}
1878
1879
1880//
1881// Parse /proc/cpuinfo (or an alternate file in the same format) to obtain the
1882// affinity map.
1883//
1884static int
1885__kmp_affinity_create_cpuinfo_map(AddrUnsPair **address2os, int *line,
1886 kmp_i18n_id_t *const msg_id, FILE *f)
1887{
1888 *address2os = NULL;
1889 *msg_id = kmp_i18n_null;
1890
1891 //
1892 // Scan of the file, and count the number of "processor" (osId) fields,
Alp Toker8f2d3f02014-02-24 10:40:15 +00001893 // and find the highest value of <n> for a node_<n> field.
Jim Cownie5e8470a2013-09-27 10:38:44 +00001894 //
1895 char buf[256];
1896 unsigned num_records = 0;
1897 while (! feof(f)) {
1898 buf[sizeof(buf) - 1] = 1;
1899 if (! fgets(buf, sizeof(buf), f)) {
1900 //
1901 // Read errors presumably because of EOF
1902 //
1903 break;
1904 }
1905
1906 char s1[] = "processor";
1907 if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
1908 num_records++;
1909 continue;
1910 }
1911
1912 //
1913 // FIXME - this will match "node_<n> <garbage>"
1914 //
1915 unsigned level;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00001916 if (KMP_SSCANF(buf, "node_%d id", &level) == 1) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00001917 if (nodeIdIndex + level >= maxIndex) {
1918 maxIndex = nodeIdIndex + level;
1919 }
1920 continue;
1921 }
1922 }
1923
1924 //
1925 // Check for empty file / no valid processor records, or too many.
1926 // The number of records can't exceed the number of valid bits in the
1927 // affinity mask.
1928 //
1929 if (num_records == 0) {
1930 *line = 0;
1931 *msg_id = kmp_i18n_str_NoProcRecords;
1932 return -1;
1933 }
1934 if (num_records > (unsigned)__kmp_xproc) {
1935 *line = 0;
1936 *msg_id = kmp_i18n_str_TooManyProcRecords;
1937 return -1;
1938 }
1939
1940 //
1941 // Set the file pointer back to the begginning, so that we can scan the
1942 // file again, this time performing a full parse of the data.
1943 // Allocate a vector of ProcCpuInfo object, where we will place the data.
1944 // Adding an extra element at the end allows us to remove a lot of extra
1945 // checks for termination conditions.
1946 //
1947 if (fseek(f, 0, SEEK_SET) != 0) {
1948 *line = 0;
1949 *msg_id = kmp_i18n_str_CantRewindCpuinfo;
1950 return -1;
1951 }
1952
1953 //
1954 // Allocate the array of records to store the proc info in. The dummy
1955 // element at the end makes the logic in filling them out easier to code.
1956 //
1957 unsigned **threadInfo = (unsigned **)__kmp_allocate((num_records + 1)
1958 * sizeof(unsigned *));
1959 unsigned i;
1960 for (i = 0; i <= num_records; i++) {
1961 threadInfo[i] = (unsigned *)__kmp_allocate((maxIndex + 1)
1962 * sizeof(unsigned));
1963 }
1964
1965#define CLEANUP_THREAD_INFO \
1966 for (i = 0; i <= num_records; i++) { \
1967 __kmp_free(threadInfo[i]); \
1968 } \
1969 __kmp_free(threadInfo);
1970
1971 //
1972 // A value of UINT_MAX means that we didn't find the field
1973 //
1974 unsigned __index;
1975
1976#define INIT_PROC_INFO(p) \
1977 for (__index = 0; __index <= maxIndex; __index++) { \
1978 (p)[__index] = UINT_MAX; \
1979 }
1980
1981 for (i = 0; i <= num_records; i++) {
1982 INIT_PROC_INFO(threadInfo[i]);
1983 }
1984
1985 unsigned num_avail = 0;
1986 *line = 0;
1987 while (! feof(f)) {
1988 //
1989 // Create an inner scoping level, so that all the goto targets at the
1990 // end of the loop appear in an outer scoping level. This avoids
1991 // warnings about jumping past an initialization to a target in the
1992 // same block.
1993 //
1994 {
1995 buf[sizeof(buf) - 1] = 1;
1996 bool long_line = false;
1997 if (! fgets(buf, sizeof(buf), f)) {
1998 //
1999 // Read errors presumably because of EOF
2000 //
2001 // If there is valid data in threadInfo[num_avail], then fake
2002 // a blank line in ensure that the last address gets parsed.
2003 //
2004 bool valid = false;
2005 for (i = 0; i <= maxIndex; i++) {
2006 if (threadInfo[num_avail][i] != UINT_MAX) {
2007 valid = true;
2008 }
2009 }
2010 if (! valid) {
2011 break;
2012 }
2013 buf[0] = 0;
2014 } else if (!buf[sizeof(buf) - 1]) {
2015 //
2016 // The line is longer than the buffer. Set a flag and don't
2017 // emit an error if we were going to ignore the line, anyway.
2018 //
2019 long_line = true;
2020
2021#define CHECK_LINE \
2022 if (long_line) { \
2023 CLEANUP_THREAD_INFO; \
2024 *msg_id = kmp_i18n_str_LongLineCpuinfo; \
2025 return -1; \
2026 }
2027 }
2028 (*line)++;
2029
2030 char s1[] = "processor";
2031 if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
2032 CHECK_LINE;
2033 char *p = strchr(buf + sizeof(s1) - 1, ':');
2034 unsigned val;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002035 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1)) goto no_val;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002036 if (threadInfo[num_avail][osIdIndex] != UINT_MAX) goto dup_field;
2037 threadInfo[num_avail][osIdIndex] = val;
Jim Cownie181b4bb2013-12-23 17:28:57 +00002038#if KMP_OS_LINUX && USE_SYSFS_INFO
2039 char path[256];
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002040 KMP_SNPRINTF(path, sizeof(path),
Jim Cownie181b4bb2013-12-23 17:28:57 +00002041 "/sys/devices/system/cpu/cpu%u/topology/physical_package_id",
2042 threadInfo[num_avail][osIdIndex]);
2043 __kmp_read_from_file(path, "%u", &threadInfo[num_avail][pkgIdIndex]);
2044
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002045 KMP_SNPRINTF(path, sizeof(path),
Jim Cownie181b4bb2013-12-23 17:28:57 +00002046 "/sys/devices/system/cpu/cpu%u/topology/core_id",
2047 threadInfo[num_avail][osIdIndex]);
2048 __kmp_read_from_file(path, "%u", &threadInfo[num_avail][coreIdIndex]);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002049 continue;
Jim Cownie181b4bb2013-12-23 17:28:57 +00002050#else
Jim Cownie5e8470a2013-09-27 10:38:44 +00002051 }
2052 char s2[] = "physical id";
2053 if (strncmp(buf, s2, sizeof(s2) - 1) == 0) {
2054 CHECK_LINE;
2055 char *p = strchr(buf + sizeof(s2) - 1, ':');
2056 unsigned val;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002057 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1)) goto no_val;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002058 if (threadInfo[num_avail][pkgIdIndex] != UINT_MAX) goto dup_field;
2059 threadInfo[num_avail][pkgIdIndex] = val;
2060 continue;
2061 }
2062 char s3[] = "core id";
2063 if (strncmp(buf, s3, sizeof(s3) - 1) == 0) {
2064 CHECK_LINE;
2065 char *p = strchr(buf + sizeof(s3) - 1, ':');
2066 unsigned val;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002067 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1)) goto no_val;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002068 if (threadInfo[num_avail][coreIdIndex] != UINT_MAX) goto dup_field;
2069 threadInfo[num_avail][coreIdIndex] = val;
2070 continue;
Jim Cownie181b4bb2013-12-23 17:28:57 +00002071#endif // KMP_OS_LINUX && USE_SYSFS_INFO
Jim Cownie5e8470a2013-09-27 10:38:44 +00002072 }
2073 char s4[] = "thread id";
2074 if (strncmp(buf, s4, sizeof(s4) - 1) == 0) {
2075 CHECK_LINE;
2076 char *p = strchr(buf + sizeof(s4) - 1, ':');
2077 unsigned val;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002078 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1)) goto no_val;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002079 if (threadInfo[num_avail][threadIdIndex] != UINT_MAX) goto dup_field;
2080 threadInfo[num_avail][threadIdIndex] = val;
2081 continue;
2082 }
2083 unsigned level;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002084 if (KMP_SSCANF(buf, "node_%d id", &level) == 1) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00002085 CHECK_LINE;
2086 char *p = strchr(buf + sizeof(s4) - 1, ':');
2087 unsigned val;
Andrey Churbanov74bf17b2015-04-02 13:27:08 +00002088 if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1)) goto no_val;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002089 KMP_ASSERT(nodeIdIndex + level <= maxIndex);
2090 if (threadInfo[num_avail][nodeIdIndex + level] != UINT_MAX) goto dup_field;
2091 threadInfo[num_avail][nodeIdIndex + level] = val;
2092 continue;
2093 }
2094
2095 //
2096 // We didn't recognize the leading token on the line.
2097 // There are lots of leading tokens that we don't recognize -
2098 // if the line isn't empty, go on to the next line.
2099 //
2100 if ((*buf != 0) && (*buf != '\n')) {
2101 //
2102 // If the line is longer than the buffer, read characters
2103 // until we find a newline.
2104 //
2105 if (long_line) {
2106 int ch;
2107 while (((ch = fgetc(f)) != EOF) && (ch != '\n'));
2108 }
2109 continue;
2110 }
2111
2112 //
2113 // A newline has signalled the end of the processor record.
2114 // Check that there aren't too many procs specified.
2115 //
Jim Cownie4cc4bb42014-10-07 16:25:50 +00002116 if ((int)num_avail == __kmp_xproc) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00002117 CLEANUP_THREAD_INFO;
2118 *msg_id = kmp_i18n_str_TooManyEntries;
2119 return -1;
2120 }
2121
2122 //
2123 // Check for missing fields. The osId field must be there, and we
2124 // currently require that the physical id field is specified, also.
2125 //
2126 if (threadInfo[num_avail][osIdIndex] == UINT_MAX) {
2127 CLEANUP_THREAD_INFO;
2128 *msg_id = kmp_i18n_str_MissingProcField;
2129 return -1;
2130 }
2131 if (threadInfo[0][pkgIdIndex] == UINT_MAX) {
2132 CLEANUP_THREAD_INFO;
2133 *msg_id = kmp_i18n_str_MissingPhysicalIDField;
2134 return -1;
2135 }
2136
2137 //
2138 // Skip this proc if it is not included in the machine model.
2139 //
2140 if (! KMP_CPU_ISSET(threadInfo[num_avail][osIdIndex], fullMask)) {
2141 INIT_PROC_INFO(threadInfo[num_avail]);
2142 continue;
2143 }
2144
2145 //
2146 // We have a successful parse of this proc's info.
2147 // Increment the counter, and prepare for the next proc.
2148 //
2149 num_avail++;
2150 KMP_ASSERT(num_avail <= num_records);
2151 INIT_PROC_INFO(threadInfo[num_avail]);
2152 }
2153 continue;
2154
2155 no_val:
2156 CLEANUP_THREAD_INFO;
2157 *msg_id = kmp_i18n_str_MissingValCpuinfo;
2158 return -1;
2159
2160 dup_field:
2161 CLEANUP_THREAD_INFO;
2162 *msg_id = kmp_i18n_str_DuplicateFieldCpuinfo;
2163 return -1;
2164 }
2165 *line = 0;
2166
2167# if KMP_MIC && REDUCE_TEAM_SIZE
2168 unsigned teamSize = 0;
2169# endif // KMP_MIC && REDUCE_TEAM_SIZE
2170
2171 // check for num_records == __kmp_xproc ???
2172
2173 //
2174 // If there's only one thread context to bind to, form an Address object
2175 // with depth 1 and return immediately (or, if affinity is off, set
2176 // address2os to NULL and return).
2177 //
2178 // If it is configured to omit the package level when there is only a
2179 // single package, the logic at the end of this routine won't work if
2180 // there is only a single thread - it would try to form an Address
2181 // object with depth 0.
2182 //
2183 KMP_ASSERT(num_avail > 0);
2184 KMP_ASSERT(num_avail <= num_records);
2185 if (num_avail == 1) {
2186 __kmp_ncores = 1;
2187 __kmp_nThreadsPerCore = nCoresPerPkg = nPackages = 1;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002188 if (__kmp_affinity_verbose) {
2189 if (! KMP_AFFINITY_CAPABLE()) {
2190 KMP_INFORM(AffNotCapableUseCpuinfo, "KMP_AFFINITY");
2191 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
2192 KMP_INFORM(Uniform, "KMP_AFFINITY");
2193 }
2194 else {
2195 char buf[KMP_AFFIN_MASK_PRINT_LEN];
2196 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
2197 fullMask);
2198 KMP_INFORM(AffCapableUseCpuinfo, "KMP_AFFINITY");
2199 if (__kmp_affinity_respect_mask) {
2200 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
2201 } else {
2202 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
2203 }
2204 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
2205 KMP_INFORM(Uniform, "KMP_AFFINITY");
2206 }
2207 int index;
2208 kmp_str_buf_t buf;
2209 __kmp_str_buf_init(&buf);
2210 __kmp_str_buf_print(&buf, "1");
2211 for (index = maxIndex - 1; index > pkgIdIndex; index--) {
2212 __kmp_str_buf_print(&buf, " x 1");
2213 }
2214 KMP_INFORM(TopologyExtra, "KMP_AFFINITY", buf.str, 1, 1, 1);
2215 __kmp_str_buf_free(&buf);
2216 }
2217
2218 if (__kmp_affinity_type == affinity_none) {
2219 CLEANUP_THREAD_INFO;
2220 return 0;
2221 }
2222
2223 *address2os = (AddrUnsPair*)__kmp_allocate(sizeof(AddrUnsPair));
2224 Address addr(1);
2225 addr.labels[0] = threadInfo[0][pkgIdIndex];
2226 (*address2os)[0] = AddrUnsPair(addr, threadInfo[0][osIdIndex]);
2227
2228 if (__kmp_affinity_gran_levels < 0) {
2229 __kmp_affinity_gran_levels = 0;
2230 }
2231
2232 if (__kmp_affinity_verbose) {
2233 __kmp_affinity_print_topology(*address2os, 1, 1, 0, -1, -1);
2234 }
2235
2236 CLEANUP_THREAD_INFO;
2237 return 1;
2238 }
2239
2240 //
2241 // Sort the threadInfo table by physical Id.
2242 //
2243 qsort(threadInfo, num_avail, sizeof(*threadInfo),
2244 __kmp_affinity_cmp_ProcCpuInfo_phys_id);
2245
2246 //
2247 // The table is now sorted by pkgId / coreId / threadId, but we really
2248 // don't know the radix of any of the fields. pkgId's may be sparsely
2249 // assigned among the chips on a system. Although coreId's are usually
2250 // assigned [0 .. coresPerPkg-1] and threadId's are usually assigned
2251 // [0..threadsPerCore-1], we don't want to make any such assumptions.
2252 //
2253 // For that matter, we don't know what coresPerPkg and threadsPerCore
2254 // (or the total # packages) are at this point - we want to determine
2255 // that now. We only have an upper bound on the first two figures.
2256 //
2257 unsigned *counts = (unsigned *)__kmp_allocate((maxIndex + 1)
2258 * sizeof(unsigned));
2259 unsigned *maxCt = (unsigned *)__kmp_allocate((maxIndex + 1)
2260 * sizeof(unsigned));
2261 unsigned *totals = (unsigned *)__kmp_allocate((maxIndex + 1)
2262 * sizeof(unsigned));
2263 unsigned *lastId = (unsigned *)__kmp_allocate((maxIndex + 1)
2264 * sizeof(unsigned));
2265
2266 bool assign_thread_ids = false;
2267 unsigned threadIdCt;
2268 unsigned index;
2269
2270 restart_radix_check:
2271 threadIdCt = 0;
2272
2273 //
2274 // Initialize the counter arrays with data from threadInfo[0].
2275 //
2276 if (assign_thread_ids) {
2277 if (threadInfo[0][threadIdIndex] == UINT_MAX) {
2278 threadInfo[0][threadIdIndex] = threadIdCt++;
2279 }
2280 else if (threadIdCt <= threadInfo[0][threadIdIndex]) {
2281 threadIdCt = threadInfo[0][threadIdIndex] + 1;
2282 }
2283 }
2284 for (index = 0; index <= maxIndex; index++) {
2285 counts[index] = 1;
2286 maxCt[index] = 1;
2287 totals[index] = 1;
2288 lastId[index] = threadInfo[0][index];;
2289 }
2290
2291 //
2292 // Run through the rest of the OS procs.
2293 //
2294 for (i = 1; i < num_avail; i++) {
2295 //
2296 // Find the most significant index whose id differs
2297 // from the id for the previous OS proc.
2298 //
2299 for (index = maxIndex; index >= threadIdIndex; index--) {
2300 if (assign_thread_ids && (index == threadIdIndex)) {
2301 //
2302 // Auto-assign the thread id field if it wasn't specified.
2303 //
2304 if (threadInfo[i][threadIdIndex] == UINT_MAX) {
2305 threadInfo[i][threadIdIndex] = threadIdCt++;
2306 }
2307
2308 //
2309 // Aparrently the thread id field was specified for some
2310 // entries and not others. Start the thread id counter
2311 // off at the next higher thread id.
2312 //
2313 else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
2314 threadIdCt = threadInfo[i][threadIdIndex] + 1;
2315 }
2316 }
2317 if (threadInfo[i][index] != lastId[index]) {
2318 //
2319 // Run through all indices which are less significant,
2320 // and reset the counts to 1.
2321 //
2322 // At all levels up to and including index, we need to
2323 // increment the totals and record the last id.
2324 //
2325 unsigned index2;
2326 for (index2 = threadIdIndex; index2 < index; index2++) {
2327 totals[index2]++;
2328 if (counts[index2] > maxCt[index2]) {
2329 maxCt[index2] = counts[index2];
2330 }
2331 counts[index2] = 1;
2332 lastId[index2] = threadInfo[i][index2];
2333 }
2334 counts[index]++;
2335 totals[index]++;
2336 lastId[index] = threadInfo[i][index];
2337
2338 if (assign_thread_ids && (index > threadIdIndex)) {
2339
2340# if KMP_MIC && REDUCE_TEAM_SIZE
2341 //
2342 // The default team size is the total #threads in the machine
2343 // minus 1 thread for every core that has 3 or more threads.
2344 //
2345 teamSize += ( threadIdCt <= 2 ) ? ( threadIdCt ) : ( threadIdCt - 1 );
2346# endif // KMP_MIC && REDUCE_TEAM_SIZE
2347
2348 //
2349 // Restart the thread counter, as we are on a new core.
2350 //
2351 threadIdCt = 0;
2352
2353 //
2354 // Auto-assign the thread id field if it wasn't specified.
2355 //
2356 if (threadInfo[i][threadIdIndex] == UINT_MAX) {
2357 threadInfo[i][threadIdIndex] = threadIdCt++;
2358 }
2359
2360 //
2361 // Aparrently the thread id field was specified for some
2362 // entries and not others. Start the thread id counter
2363 // off at the next higher thread id.
2364 //
2365 else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
2366 threadIdCt = threadInfo[i][threadIdIndex] + 1;
2367 }
2368 }
2369 break;
2370 }
2371 }
2372 if (index < threadIdIndex) {
2373 //
2374 // If thread ids were specified, it is an error if they are not
2375 // unique. Also, check that we waven't already restarted the
2376 // loop (to be safe - shouldn't need to).
2377 //
2378 if ((threadInfo[i][threadIdIndex] != UINT_MAX)
2379 || assign_thread_ids) {
2380 __kmp_free(lastId);
2381 __kmp_free(totals);
2382 __kmp_free(maxCt);
2383 __kmp_free(counts);
2384 CLEANUP_THREAD_INFO;
2385 *msg_id = kmp_i18n_str_PhysicalIDsNotUnique;
2386 return -1;
2387 }
2388
2389 //
2390 // If the thread ids were not specified and we see entries
2391 // entries that are duplicates, start the loop over and
2392 // assign the thread ids manually.
2393 //
2394 assign_thread_ids = true;
2395 goto restart_radix_check;
2396 }
2397 }
2398
2399# if KMP_MIC && REDUCE_TEAM_SIZE
2400 //
2401 // The default team size is the total #threads in the machine
2402 // minus 1 thread for every core that has 3 or more threads.
2403 //
2404 teamSize += ( threadIdCt <= 2 ) ? ( threadIdCt ) : ( threadIdCt - 1 );
2405# endif // KMP_MIC && REDUCE_TEAM_SIZE
2406
2407 for (index = threadIdIndex; index <= maxIndex; index++) {
2408 if (counts[index] > maxCt[index]) {
2409 maxCt[index] = counts[index];
2410 }
2411 }
2412
2413 __kmp_nThreadsPerCore = maxCt[threadIdIndex];
2414 nCoresPerPkg = maxCt[coreIdIndex];
2415 nPackages = totals[pkgIdIndex];
2416
2417 //
2418 // Check to see if the machine topology is uniform
2419 //
2420 unsigned prod = totals[maxIndex];
2421 for (index = threadIdIndex; index < maxIndex; index++) {
2422 prod *= maxCt[index];
2423 }
2424 bool uniform = (prod == totals[threadIdIndex]);
2425
2426 //
2427 // When affinity is off, this routine will still be called to set
Andrey Churbanovf696c822015-01-27 16:55:43 +00002428 // __kmp_ncores, as well as __kmp_nThreadsPerCore,
Jim Cownie5e8470a2013-09-27 10:38:44 +00002429 // nCoresPerPkg, & nPackages. Make sure all these vars are set
2430 // correctly, and return now if affinity is not enabled.
2431 //
Jim Cownie5e8470a2013-09-27 10:38:44 +00002432 __kmp_ncores = totals[coreIdIndex];
2433
2434 if (__kmp_affinity_verbose) {
2435 if (! KMP_AFFINITY_CAPABLE()) {
2436 KMP_INFORM(AffNotCapableUseCpuinfo, "KMP_AFFINITY");
2437 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
2438 if (uniform) {
2439 KMP_INFORM(Uniform, "KMP_AFFINITY");
2440 } else {
2441 KMP_INFORM(NonUniform, "KMP_AFFINITY");
2442 }
2443 }
2444 else {
2445 char buf[KMP_AFFIN_MASK_PRINT_LEN];
2446 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, fullMask);
2447 KMP_INFORM(AffCapableUseCpuinfo, "KMP_AFFINITY");
2448 if (__kmp_affinity_respect_mask) {
2449 KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
2450 } else {
2451 KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
2452 }
2453 KMP_INFORM(AvailableOSProc, "KMP_AFFINITY", __kmp_avail_proc);
2454 if (uniform) {
2455 KMP_INFORM(Uniform, "KMP_AFFINITY");
2456 } else {
2457 KMP_INFORM(NonUniform, "KMP_AFFINITY");
2458 }
2459 }
2460 kmp_str_buf_t buf;
2461 __kmp_str_buf_init(&buf);
2462
2463 __kmp_str_buf_print(&buf, "%d", totals[maxIndex]);
2464 for (index = maxIndex - 1; index >= pkgIdIndex; index--) {
2465 __kmp_str_buf_print(&buf, " x %d", maxCt[index]);
2466 }
2467 KMP_INFORM(TopologyExtra, "KMP_AFFINITY", buf.str, maxCt[coreIdIndex],
2468 maxCt[threadIdIndex], __kmp_ncores);
2469
2470 __kmp_str_buf_free(&buf);
2471 }
2472
2473# if KMP_MIC && REDUCE_TEAM_SIZE
2474 //
2475 // Set the default team size.
2476 //
2477 if ((__kmp_dflt_team_nth == 0) && (teamSize > 0)) {
2478 __kmp_dflt_team_nth = teamSize;
2479 KA_TRACE(20, ("__kmp_affinity_create_cpuinfo_map: setting __kmp_dflt_team_nth = %d\n",
2480 __kmp_dflt_team_nth));
2481 }
2482# endif // KMP_MIC && REDUCE_TEAM_SIZE
2483
2484 if (__kmp_affinity_type == affinity_none) {
2485 __kmp_free(lastId);
2486 __kmp_free(totals);
2487 __kmp_free(maxCt);
2488 __kmp_free(counts);
2489 CLEANUP_THREAD_INFO;
2490 return 0;
2491 }
2492
2493 //
2494 // Count the number of levels which have more nodes at that level than
2495 // at the parent's level (with there being an implicit root node of
2496 // the top level). This is equivalent to saying that there is at least
2497 // one node at this level which has a sibling. These levels are in the
2498 // map, and the package level is always in the map.
2499 //
2500 bool *inMap = (bool *)__kmp_allocate((maxIndex + 1) * sizeof(bool));
2501 int level = 0;
2502 for (index = threadIdIndex; index < maxIndex; index++) {
2503 KMP_ASSERT(totals[index] >= totals[index + 1]);
2504 inMap[index] = (totals[index] > totals[index + 1]);
2505 }
2506 inMap[maxIndex] = (totals[maxIndex] > 1);
2507 inMap[pkgIdIndex] = true;
2508
2509 int depth = 0;
2510 for (index = threadIdIndex; index <= maxIndex; index++) {
2511 if (inMap[index]) {
2512 depth++;
2513 }
2514 }
2515 KMP_ASSERT(depth > 0);
2516
2517 //
2518 // Construct the data structure that is to be returned.
2519 //
2520 *address2os = (AddrUnsPair*)
2521 __kmp_allocate(sizeof(AddrUnsPair) * num_avail);
2522 int pkgLevel = -1;
2523 int coreLevel = -1;
2524 int threadLevel = -1;
2525
2526 for (i = 0; i < num_avail; ++i) {
2527 Address addr(depth);
2528 unsigned os = threadInfo[i][osIdIndex];
2529 int src_index;
2530 int dst_index = 0;
2531
2532 for (src_index = maxIndex; src_index >= threadIdIndex; src_index--) {
2533 if (! inMap[src_index]) {
2534 continue;
2535 }
2536 addr.labels[dst_index] = threadInfo[i][src_index];
2537 if (src_index == pkgIdIndex) {
2538 pkgLevel = dst_index;
2539 }
2540 else if (src_index == coreIdIndex) {
2541 coreLevel = dst_index;
2542 }
2543 else if (src_index == threadIdIndex) {
2544 threadLevel = dst_index;
2545 }
2546 dst_index++;
2547 }
2548 (*address2os)[i] = AddrUnsPair(addr, os);
2549 }
2550
2551 if (__kmp_affinity_gran_levels < 0) {
2552 //
2553 // Set the granularity level based on what levels are modeled
2554 // in the machine topology map.
2555 //
2556 unsigned src_index;
2557 __kmp_affinity_gran_levels = 0;
2558 for (src_index = threadIdIndex; src_index <= maxIndex; src_index++) {
2559 if (! inMap[src_index]) {
2560 continue;
2561 }
2562 switch (src_index) {
2563 case threadIdIndex:
2564 if (__kmp_affinity_gran > affinity_gran_thread) {
2565 __kmp_affinity_gran_levels++;
2566 }
2567
2568 break;
2569 case coreIdIndex:
2570 if (__kmp_affinity_gran > affinity_gran_core) {
2571 __kmp_affinity_gran_levels++;
2572 }
2573 break;
2574
2575 case pkgIdIndex:
2576 if (__kmp_affinity_gran > affinity_gran_package) {
2577 __kmp_affinity_gran_levels++;
2578 }
2579 break;
2580 }
2581 }
2582 }
2583
2584 if (__kmp_affinity_verbose) {
2585 __kmp_affinity_print_topology(*address2os, num_avail, depth, pkgLevel,
2586 coreLevel, threadLevel);
2587 }
2588
2589 __kmp_free(inMap);
2590 __kmp_free(lastId);
2591 __kmp_free(totals);
2592 __kmp_free(maxCt);
2593 __kmp_free(counts);
2594 CLEANUP_THREAD_INFO;
2595 return depth;
2596}
2597
2598
2599//
2600// Create and return a table of affinity masks, indexed by OS thread ID.
2601// This routine handles OR'ing together all the affinity masks of threads
2602// that are sufficiently close, if granularity > fine.
2603//
2604static kmp_affin_mask_t *
2605__kmp_create_masks(unsigned *maxIndex, unsigned *numUnique,
2606 AddrUnsPair *address2os, unsigned numAddrs)
2607{
2608 //
2609 // First form a table of affinity masks in order of OS thread id.
2610 //
2611 unsigned depth;
2612 unsigned maxOsId;
2613 unsigned i;
2614
2615 KMP_ASSERT(numAddrs > 0);
2616 depth = address2os[0].first.depth;
2617
2618 maxOsId = 0;
2619 for (i = 0; i < numAddrs; i++) {
2620 unsigned osId = address2os[i].second;
2621 if (osId > maxOsId) {
2622 maxOsId = osId;
2623 }
2624 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002625 kmp_affin_mask_t *osId2Mask;
2626 KMP_CPU_ALLOC_ARRAY(osId2Mask, (maxOsId+1));
Jim Cownie5e8470a2013-09-27 10:38:44 +00002627
2628 //
2629 // Sort the address2os table according to physical order. Doing so
2630 // will put all threads on the same core/package/node in consecutive
2631 // locations.
2632 //
2633 qsort(address2os, numAddrs, sizeof(*address2os),
2634 __kmp_affinity_cmp_Address_labels);
2635
2636 KMP_ASSERT(__kmp_affinity_gran_levels >= 0);
2637 if (__kmp_affinity_verbose && (__kmp_affinity_gran_levels > 0)) {
2638 KMP_INFORM(ThreadsMigrate, "KMP_AFFINITY", __kmp_affinity_gran_levels);
2639 }
2640 if (__kmp_affinity_gran_levels >= (int)depth) {
2641 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
2642 && (__kmp_affinity_type != affinity_none))) {
2643 KMP_WARNING(AffThreadsMayMigrate);
2644 }
2645 }
2646
2647 //
2648 // Run through the table, forming the masks for all threads on each
2649 // core. Threads on the same core will have identical "Address"
2650 // objects, not considering the last level, which must be the thread
2651 // id. All threads on a core will appear consecutively.
2652 //
2653 unsigned unique = 0;
2654 unsigned j = 0; // index of 1st thread on core
2655 unsigned leader = 0;
2656 Address *leaderAddr = &(address2os[0].first);
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002657 kmp_affin_mask_t *sum;
2658 KMP_CPU_ALLOC_ON_STACK(sum);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002659 KMP_CPU_ZERO(sum);
2660 KMP_CPU_SET(address2os[0].second, sum);
2661 for (i = 1; i < numAddrs; i++) {
2662 //
Alp Toker8f2d3f02014-02-24 10:40:15 +00002663 // If this thread is sufficiently close to the leader (within the
Jim Cownie5e8470a2013-09-27 10:38:44 +00002664 // granularity setting), then set the bit for this os thread in the
2665 // affinity mask for this group, and go on to the next thread.
2666 //
2667 if (leaderAddr->isClose(address2os[i].first,
2668 __kmp_affinity_gran_levels)) {
2669 KMP_CPU_SET(address2os[i].second, sum);
2670 continue;
2671 }
2672
2673 //
2674 // For every thread in this group, copy the mask to the thread's
2675 // entry in the osId2Mask table. Mark the first address as a
2676 // leader.
2677 //
2678 for (; j < i; j++) {
2679 unsigned osId = address2os[j].second;
2680 KMP_DEBUG_ASSERT(osId <= maxOsId);
2681 kmp_affin_mask_t *mask = KMP_CPU_INDEX(osId2Mask, osId);
2682 KMP_CPU_COPY(mask, sum);
2683 address2os[j].first.leader = (j == leader);
2684 }
2685 unique++;
2686
2687 //
2688 // Start a new mask.
2689 //
2690 leader = i;
2691 leaderAddr = &(address2os[i].first);
2692 KMP_CPU_ZERO(sum);
2693 KMP_CPU_SET(address2os[i].second, sum);
2694 }
2695
2696 //
2697 // For every thread in last group, copy the mask to the thread's
2698 // entry in the osId2Mask table.
2699 //
2700 for (; j < i; j++) {
2701 unsigned osId = address2os[j].second;
2702 KMP_DEBUG_ASSERT(osId <= maxOsId);
2703 kmp_affin_mask_t *mask = KMP_CPU_INDEX(osId2Mask, osId);
2704 KMP_CPU_COPY(mask, sum);
2705 address2os[j].first.leader = (j == leader);
2706 }
2707 unique++;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002708 KMP_CPU_FREE_FROM_STACK(sum);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002709
2710 *maxIndex = maxOsId;
2711 *numUnique = unique;
2712 return osId2Mask;
2713}
2714
2715
2716//
2717// Stuff for the affinity proclist parsers. It's easier to declare these vars
2718// as file-static than to try and pass them through the calling sequence of
2719// the recursive-descent OMP_PLACES parser.
2720//
2721static kmp_affin_mask_t *newMasks;
2722static int numNewMasks;
2723static int nextNewMask;
2724
2725#define ADD_MASK(_mask) \
2726 { \
2727 if (nextNewMask >= numNewMasks) { \
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002728 int i; \
Jim Cownie5e8470a2013-09-27 10:38:44 +00002729 numNewMasks *= 2; \
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002730 kmp_affin_mask_t* temp; \
2731 KMP_CPU_INTERNAL_ALLOC_ARRAY(temp, numNewMasks); \
2732 for(i=0;i<numNewMasks/2;i++) { \
2733 kmp_affin_mask_t* src = KMP_CPU_INDEX(newMasks, i); \
2734 kmp_affin_mask_t* dest = KMP_CPU_INDEX(temp, i); \
2735 KMP_CPU_COPY(dest, src); \
2736 } \
2737 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks/2); \
2738 newMasks = temp; \
Jim Cownie5e8470a2013-09-27 10:38:44 +00002739 } \
2740 KMP_CPU_COPY(KMP_CPU_INDEX(newMasks, nextNewMask), (_mask)); \
2741 nextNewMask++; \
2742 }
2743
2744#define ADD_MASK_OSID(_osId,_osId2Mask,_maxOsId) \
2745 { \
2746 if (((_osId) > _maxOsId) || \
Jim Cownie4cc4bb42014-10-07 16:25:50 +00002747 (! KMP_CPU_ISSET((_osId), KMP_CPU_INDEX((_osId2Mask), (_osId))))) { \
Jim Cownie5e8470a2013-09-27 10:38:44 +00002748 if (__kmp_affinity_verbose || (__kmp_affinity_warnings \
2749 && (__kmp_affinity_type != affinity_none))) { \
2750 KMP_WARNING(AffIgnoreInvalidProcID, _osId); \
2751 } \
2752 } \
2753 else { \
2754 ADD_MASK(KMP_CPU_INDEX(_osId2Mask, (_osId))); \
2755 } \
2756 }
2757
2758
2759//
2760// Re-parse the proclist (for the explicit affinity type), and form the list
2761// of affinity newMasks indexed by gtid.
2762//
2763static void
2764__kmp_affinity_process_proclist(kmp_affin_mask_t **out_masks,
2765 unsigned int *out_numMasks, const char *proclist,
2766 kmp_affin_mask_t *osId2Mask, int maxOsId)
2767{
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002768 int i;
Jim Cownie5e8470a2013-09-27 10:38:44 +00002769 const char *scan = proclist;
2770 const char *next = proclist;
2771
2772 //
2773 // We use malloc() for the temporary mask vector,
2774 // so that we can use realloc() to extend it.
2775 //
2776 numNewMasks = 2;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002777 KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002778 nextNewMask = 0;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002779 kmp_affin_mask_t *sumMask;
2780 KMP_CPU_ALLOC(sumMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002781 int setSize = 0;
2782
2783 for (;;) {
2784 int start, end, stride;
2785
2786 SKIP_WS(scan);
2787 next = scan;
2788 if (*next == '\0') {
2789 break;
2790 }
2791
2792 if (*next == '{') {
2793 int num;
2794 setSize = 0;
2795 next++; // skip '{'
2796 SKIP_WS(next);
2797 scan = next;
2798
2799 //
2800 // Read the first integer in the set.
2801 //
2802 KMP_ASSERT2((*next >= '0') && (*next <= '9'),
2803 "bad proclist");
2804 SKIP_DIGITS(next);
2805 num = __kmp_str_to_int(scan, *next);
2806 KMP_ASSERT2(num >= 0, "bad explicit proc list");
2807
2808 //
2809 // Copy the mask for that osId to the sum (union) mask.
2810 //
2811 if ((num > maxOsId) ||
2812 (! KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
2813 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
2814 && (__kmp_affinity_type != affinity_none))) {
2815 KMP_WARNING(AffIgnoreInvalidProcID, num);
2816 }
2817 KMP_CPU_ZERO(sumMask);
2818 }
2819 else {
2820 KMP_CPU_COPY(sumMask, KMP_CPU_INDEX(osId2Mask, num));
2821 setSize = 1;
2822 }
2823
2824 for (;;) {
2825 //
2826 // Check for end of set.
2827 //
2828 SKIP_WS(next);
2829 if (*next == '}') {
2830 next++; // skip '}'
2831 break;
2832 }
2833
2834 //
2835 // Skip optional comma.
2836 //
2837 if (*next == ',') {
2838 next++;
2839 }
2840 SKIP_WS(next);
2841
2842 //
2843 // Read the next integer in the set.
2844 //
2845 scan = next;
2846 KMP_ASSERT2((*next >= '0') && (*next <= '9'),
2847 "bad explicit proc list");
2848
2849 SKIP_DIGITS(next);
2850 num = __kmp_str_to_int(scan, *next);
2851 KMP_ASSERT2(num >= 0, "bad explicit proc list");
2852
2853 //
2854 // Add the mask for that osId to the sum mask.
2855 //
2856 if ((num > maxOsId) ||
2857 (! KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
2858 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
2859 && (__kmp_affinity_type != affinity_none))) {
2860 KMP_WARNING(AffIgnoreInvalidProcID, num);
2861 }
2862 }
2863 else {
2864 KMP_CPU_UNION(sumMask, KMP_CPU_INDEX(osId2Mask, num));
2865 setSize++;
2866 }
2867 }
2868 if (setSize > 0) {
2869 ADD_MASK(sumMask);
2870 }
2871
2872 SKIP_WS(next);
2873 if (*next == ',') {
2874 next++;
2875 }
2876 scan = next;
2877 continue;
2878 }
2879
2880 //
2881 // Read the first integer.
2882 //
2883 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
2884 SKIP_DIGITS(next);
2885 start = __kmp_str_to_int(scan, *next);
2886 KMP_ASSERT2(start >= 0, "bad explicit proc list");
2887 SKIP_WS(next);
2888
2889 //
2890 // If this isn't a range, then add a mask to the list and go on.
2891 //
2892 if (*next != '-') {
2893 ADD_MASK_OSID(start, osId2Mask, maxOsId);
2894
2895 //
2896 // Skip optional comma.
2897 //
2898 if (*next == ',') {
2899 next++;
2900 }
2901 scan = next;
2902 continue;
2903 }
2904
2905 //
2906 // This is a range. Skip over the '-' and read in the 2nd int.
2907 //
2908 next++; // skip '-'
2909 SKIP_WS(next);
2910 scan = next;
2911 KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
2912 SKIP_DIGITS(next);
2913 end = __kmp_str_to_int(scan, *next);
2914 KMP_ASSERT2(end >= 0, "bad explicit proc list");
2915
2916 //
2917 // Check for a stride parameter
2918 //
2919 stride = 1;
2920 SKIP_WS(next);
2921 if (*next == ':') {
2922 //
2923 // A stride is specified. Skip over the ':" and read the 3rd int.
2924 //
2925 int sign = +1;
2926 next++; // skip ':'
2927 SKIP_WS(next);
2928 scan = next;
2929 if (*next == '-') {
2930 sign = -1;
2931 next++;
2932 SKIP_WS(next);
2933 scan = next;
2934 }
2935 KMP_ASSERT2((*next >= '0') && (*next <= '9'),
2936 "bad explicit proc list");
2937 SKIP_DIGITS(next);
2938 stride = __kmp_str_to_int(scan, *next);
2939 KMP_ASSERT2(stride >= 0, "bad explicit proc list");
2940 stride *= sign;
2941 }
2942
2943 //
2944 // Do some range checks.
2945 //
2946 KMP_ASSERT2(stride != 0, "bad explicit proc list");
2947 if (stride > 0) {
2948 KMP_ASSERT2(start <= end, "bad explicit proc list");
2949 }
2950 else {
2951 KMP_ASSERT2(start >= end, "bad explicit proc list");
2952 }
2953 KMP_ASSERT2((end - start) / stride <= 65536, "bad explicit proc list");
2954
2955 //
2956 // Add the mask for each OS proc # to the list.
2957 //
2958 if (stride > 0) {
2959 do {
2960 ADD_MASK_OSID(start, osId2Mask, maxOsId);
2961 start += stride;
2962 } while (start <= end);
2963 }
2964 else {
2965 do {
2966 ADD_MASK_OSID(start, osId2Mask, maxOsId);
2967 start += stride;
2968 } while (start >= end);
2969 }
2970
2971 //
2972 // Skip optional comma.
2973 //
2974 SKIP_WS(next);
2975 if (*next == ',') {
2976 next++;
2977 }
2978 scan = next;
2979 }
2980
2981 *out_numMasks = nextNewMask;
2982 if (nextNewMask == 0) {
2983 *out_masks = NULL;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002984 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002985 return;
2986 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00002987 KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
2988 for(i = 0; i < nextNewMask; i++) {
2989 kmp_affin_mask_t* src = KMP_CPU_INDEX(newMasks, i);
2990 kmp_affin_mask_t* dest = KMP_CPU_INDEX((*out_masks), i);
2991 KMP_CPU_COPY(dest, src);
2992 }
2993 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
2994 KMP_CPU_FREE(sumMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00002995}
2996
2997
2998# if OMP_40_ENABLED
2999
3000/*-----------------------------------------------------------------------------
3001
3002Re-parse the OMP_PLACES proc id list, forming the newMasks for the different
3003places. Again, Here is the grammar:
3004
3005place_list := place
3006place_list := place , place_list
3007place := num
3008place := place : num
3009place := place : num : signed
3010place := { subplacelist }
3011place := ! place // (lowest priority)
3012subplace_list := subplace
3013subplace_list := subplace , subplace_list
3014subplace := num
3015subplace := num : num
3016subplace := num : num : signed
3017signed := num
3018signed := + signed
3019signed := - signed
3020
3021-----------------------------------------------------------------------------*/
3022
3023static void
3024__kmp_process_subplace_list(const char **scan, kmp_affin_mask_t *osId2Mask,
3025 int maxOsId, kmp_affin_mask_t *tempMask, int *setSize)
3026{
3027 const char *next;
3028
3029 for (;;) {
3030 int start, count, stride, i;
3031
3032 //
3033 // Read in the starting proc id
3034 //
3035 SKIP_WS(*scan);
3036 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'),
3037 "bad explicit places list");
3038 next = *scan;
3039 SKIP_DIGITS(next);
3040 start = __kmp_str_to_int(*scan, *next);
3041 KMP_ASSERT(start >= 0);
3042 *scan = next;
3043
3044 //
3045 // valid follow sets are ',' ':' and '}'
3046 //
3047 SKIP_WS(*scan);
3048 if (**scan == '}' || **scan == ',') {
3049 if ((start > maxOsId) ||
3050 (! KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
3051 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3052 && (__kmp_affinity_type != affinity_none))) {
3053 KMP_WARNING(AffIgnoreInvalidProcID, start);
3054 }
3055 }
3056 else {
3057 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
3058 (*setSize)++;
3059 }
3060 if (**scan == '}') {
3061 break;
3062 }
3063 (*scan)++; // skip ','
3064 continue;
3065 }
3066 KMP_ASSERT2(**scan == ':', "bad explicit places list");
3067 (*scan)++; // skip ':'
3068
3069 //
3070 // Read count parameter
3071 //
3072 SKIP_WS(*scan);
3073 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'),
3074 "bad explicit places list");
3075 next = *scan;
3076 SKIP_DIGITS(next);
3077 count = __kmp_str_to_int(*scan, *next);
3078 KMP_ASSERT(count >= 0);
3079 *scan = next;
3080
3081 //
3082 // valid follow sets are ',' ':' and '}'
3083 //
3084 SKIP_WS(*scan);
3085 if (**scan == '}' || **scan == ',') {
3086 for (i = 0; i < count; i++) {
3087 if ((start > maxOsId) ||
3088 (! KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
3089 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3090 && (__kmp_affinity_type != affinity_none))) {
3091 KMP_WARNING(AffIgnoreInvalidProcID, start);
3092 }
3093 break; // don't proliferate warnings for large count
3094 }
3095 else {
3096 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
3097 start++;
3098 (*setSize)++;
3099 }
3100 }
3101 if (**scan == '}') {
3102 break;
3103 }
3104 (*scan)++; // skip ','
3105 continue;
3106 }
3107 KMP_ASSERT2(**scan == ':', "bad explicit places list");
3108 (*scan)++; // skip ':'
3109
3110 //
3111 // Read stride parameter
3112 //
3113 int sign = +1;
3114 for (;;) {
3115 SKIP_WS(*scan);
3116 if (**scan == '+') {
3117 (*scan)++; // skip '+'
3118 continue;
3119 }
3120 if (**scan == '-') {
3121 sign *= -1;
3122 (*scan)++; // skip '-'
3123 continue;
3124 }
3125 break;
3126 }
3127 SKIP_WS(*scan);
3128 KMP_ASSERT2((**scan >= '0') && (**scan <= '9'),
3129 "bad explicit places list");
3130 next = *scan;
3131 SKIP_DIGITS(next);
3132 stride = __kmp_str_to_int(*scan, *next);
3133 KMP_ASSERT(stride >= 0);
3134 *scan = next;
3135 stride *= sign;
3136
3137 //
3138 // valid follow sets are ',' and '}'
3139 //
3140 SKIP_WS(*scan);
3141 if (**scan == '}' || **scan == ',') {
3142 for (i = 0; i < count; i++) {
3143 if ((start > maxOsId) ||
3144 (! KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
3145 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3146 && (__kmp_affinity_type != affinity_none))) {
3147 KMP_WARNING(AffIgnoreInvalidProcID, start);
3148 }
3149 break; // don't proliferate warnings for large count
3150 }
3151 else {
3152 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
3153 start += stride;
3154 (*setSize)++;
3155 }
3156 }
3157 if (**scan == '}') {
3158 break;
3159 }
3160 (*scan)++; // skip ','
3161 continue;
3162 }
3163
3164 KMP_ASSERT2(0, "bad explicit places list");
3165 }
3166}
3167
3168
3169static void
3170__kmp_process_place(const char **scan, kmp_affin_mask_t *osId2Mask,
3171 int maxOsId, kmp_affin_mask_t *tempMask, int *setSize)
3172{
3173 const char *next;
3174
3175 //
3176 // valid follow sets are '{' '!' and num
3177 //
3178 SKIP_WS(*scan);
3179 if (**scan == '{') {
3180 (*scan)++; // skip '{'
3181 __kmp_process_subplace_list(scan, osId2Mask, maxOsId , tempMask,
3182 setSize);
3183 KMP_ASSERT2(**scan == '}', "bad explicit places list");
3184 (*scan)++; // skip '}'
3185 }
3186 else if (**scan == '!') {
Jonathan Peyton6778c732015-10-19 19:43:01 +00003187 (*scan)++; // skip '!'
Jim Cownie5e8470a2013-09-27 10:38:44 +00003188 __kmp_process_place(scan, osId2Mask, maxOsId, tempMask, setSize);
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003189 KMP_CPU_COMPLEMENT(maxOsId, tempMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003190 }
3191 else if ((**scan >= '0') && (**scan <= '9')) {
3192 next = *scan;
3193 SKIP_DIGITS(next);
3194 int num = __kmp_str_to_int(*scan, *next);
3195 KMP_ASSERT(num >= 0);
3196 if ((num > maxOsId) ||
3197 (! KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
3198 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3199 && (__kmp_affinity_type != affinity_none))) {
3200 KMP_WARNING(AffIgnoreInvalidProcID, num);
3201 }
3202 }
3203 else {
3204 KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, num));
3205 (*setSize)++;
3206 }
3207 *scan = next; // skip num
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003208 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003209 else {
3210 KMP_ASSERT2(0, "bad explicit places list");
3211 }
3212}
3213
3214
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003215//static void
3216void
Jim Cownie5e8470a2013-09-27 10:38:44 +00003217__kmp_affinity_process_placelist(kmp_affin_mask_t **out_masks,
3218 unsigned int *out_numMasks, const char *placelist,
3219 kmp_affin_mask_t *osId2Mask, int maxOsId)
3220{
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003221 int i,j,count,stride,sign;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003222 const char *scan = placelist;
3223 const char *next = placelist;
3224
3225 numNewMasks = 2;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003226 KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003227 nextNewMask = 0;
3228
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003229 // tempMask is modified based on the previous or initial
3230 // place to form the current place
3231 // previousMask contains the previous place
3232 kmp_affin_mask_t *tempMask;
3233 kmp_affin_mask_t *previousMask;
3234 KMP_CPU_ALLOC(tempMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003235 KMP_CPU_ZERO(tempMask);
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003236 KMP_CPU_ALLOC(previousMask);
3237 KMP_CPU_ZERO(previousMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003238 int setSize = 0;
3239
3240 for (;;) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00003241 __kmp_process_place(&scan, osId2Mask, maxOsId, tempMask, &setSize);
3242
3243 //
3244 // valid follow sets are ',' ':' and EOL
3245 //
3246 SKIP_WS(scan);
3247 if (*scan == '\0' || *scan == ',') {
3248 if (setSize > 0) {
3249 ADD_MASK(tempMask);
3250 }
3251 KMP_CPU_ZERO(tempMask);
3252 setSize = 0;
3253 if (*scan == '\0') {
3254 break;
3255 }
3256 scan++; // skip ','
3257 continue;
3258 }
3259
3260 KMP_ASSERT2(*scan == ':', "bad explicit places list");
3261 scan++; // skip ':'
3262
3263 //
3264 // Read count parameter
3265 //
3266 SKIP_WS(scan);
3267 KMP_ASSERT2((*scan >= '0') && (*scan <= '9'),
3268 "bad explicit places list");
3269 next = scan;
3270 SKIP_DIGITS(next);
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003271 count = __kmp_str_to_int(scan, *next);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003272 KMP_ASSERT(count >= 0);
3273 scan = next;
3274
3275 //
3276 // valid follow sets are ',' ':' and EOL
3277 //
3278 SKIP_WS(scan);
3279 if (*scan == '\0' || *scan == ',') {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003280 stride = +1;
3281 }
3282 else {
3283 KMP_ASSERT2(*scan == ':', "bad explicit places list");
3284 scan++; // skip ':'
Jim Cownie5e8470a2013-09-27 10:38:44 +00003285
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003286 //
3287 // Read stride parameter
3288 //
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003289 sign = +1;
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003290 for (;;) {
3291 SKIP_WS(scan);
3292 if (*scan == '+') {
3293 scan++; // skip '+'
3294 continue;
3295 }
3296 if (*scan == '-') {
3297 sign *= -1;
3298 scan++; // skip '-'
3299 continue;
3300 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003301 break;
3302 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003303 SKIP_WS(scan);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003304 KMP_ASSERT2((*scan >= '0') && (*scan <= '9'),
3305 "bad explicit places list");
3306 next = scan;
3307 SKIP_DIGITS(next);
3308 stride = __kmp_str_to_int(scan, *next);
3309 KMP_DEBUG_ASSERT(stride >= 0);
3310 scan = next;
3311 stride *= sign;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003312 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003313
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003314 // Add places determined by initial_place : count : stride
3315 for (i = 0; i < count; i++) {
3316 if (setSize == 0) {
3317 break;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003318 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003319 // Add the current place, then build the next place (tempMask) from that
3320 KMP_CPU_COPY(previousMask, tempMask);
3321 ADD_MASK(previousMask);
3322 KMP_CPU_ZERO(tempMask);
3323 setSize = 0;
3324 KMP_CPU_SET_ITERATE(j, previousMask) {
3325 if (! KMP_CPU_ISSET(j, previousMask)) {
3326 continue;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003327 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003328 else if ((j+stride > maxOsId) || (j+stride < 0) ||
3329 (! KMP_CPU_ISSET(j+stride, KMP_CPU_INDEX(osId2Mask, j+stride)))) {
3330 if ((__kmp_affinity_verbose || (__kmp_affinity_warnings
3331 && (__kmp_affinity_type != affinity_none))) && i < count - 1) {
3332 KMP_WARNING(AffIgnoreInvalidProcID, j+stride);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003333 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003334 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003335 else {
3336 KMP_CPU_SET(j+stride, tempMask);
3337 setSize++;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003338 }
3339 }
3340 }
3341 KMP_CPU_ZERO(tempMask);
3342 setSize = 0;
3343
3344 //
3345 // valid follow sets are ',' and EOL
3346 //
3347 SKIP_WS(scan);
3348 if (*scan == '\0') {
3349 break;
3350 }
3351 if (*scan == ',') {
3352 scan++; // skip ','
3353 continue;
3354 }
3355
3356 KMP_ASSERT2(0, "bad explicit places list");
3357 }
3358
3359 *out_numMasks = nextNewMask;
3360 if (nextNewMask == 0) {
3361 *out_masks = NULL;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003362 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003363 return;
3364 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003365 KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
3366 KMP_CPU_FREE(tempMask);
3367 KMP_CPU_FREE(previousMask);
3368 for(i = 0; i < nextNewMask; i++) {
3369 kmp_affin_mask_t* src = KMP_CPU_INDEX(newMasks, i);
3370 kmp_affin_mask_t* dest = KMP_CPU_INDEX((*out_masks), i);
3371 KMP_CPU_COPY(dest, src);
3372 }
3373 KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003374}
3375
3376# endif /* OMP_40_ENABLED */
3377
3378#undef ADD_MASK
3379#undef ADD_MASK_OSID
3380
Jim Cownie5e8470a2013-09-27 10:38:44 +00003381static void
3382__kmp_apply_thread_places(AddrUnsPair **pAddr, int depth)
3383{
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003384 if (__kmp_place_num_sockets == 0 &&
3385 __kmp_place_num_cores == 0 &&
3386 __kmp_place_num_threads_per_core == 0 )
3387 return; // no topology limiting actions requested, exit
3388 if (__kmp_place_num_sockets == 0)
3389 __kmp_place_num_sockets = nPackages; // use all available sockets
3390 if (__kmp_place_num_cores == 0)
Jim Cownie5e8470a2013-09-27 10:38:44 +00003391 __kmp_place_num_cores = nCoresPerPkg; // use all available cores
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003392 if (__kmp_place_num_threads_per_core == 0 ||
3393 __kmp_place_num_threads_per_core > __kmp_nThreadsPerCore)
3394 __kmp_place_num_threads_per_core = __kmp_nThreadsPerCore; // use all HW contexts
3395
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003396 if ( !__kmp_affinity_uniform_topology() ) {
3397 KMP_WARNING( AffThrPlaceNonUniform );
3398 return; // don't support non-uniform topology
3399 }
3400 if ( depth != 3 ) {
3401 KMP_WARNING( AffThrPlaceNonThreeLevel );
3402 return; // don't support not-3-level topology
Jim Cownie5e8470a2013-09-27 10:38:44 +00003403 }
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003404 if (__kmp_place_socket_offset + __kmp_place_num_sockets > nPackages) {
3405 KMP_WARNING(AffThrPlaceManySockets);
3406 return;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003407 }
Andrey Churbanov12875572015-03-10 09:00:36 +00003408 if ( __kmp_place_core_offset + __kmp_place_num_cores > nCoresPerPkg ) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00003409 KMP_WARNING( AffThrPlaceManyCores );
3410 return;
3411 }
3412
3413 AddrUnsPair *newAddr = (AddrUnsPair *)__kmp_allocate( sizeof(AddrUnsPair) *
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003414 __kmp_place_num_sockets * __kmp_place_num_cores * __kmp_place_num_threads_per_core);
3415
Jim Cownie5e8470a2013-09-27 10:38:44 +00003416 int i, j, k, n_old = 0, n_new = 0;
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003417 for (i = 0; i < nPackages; ++i)
3418 if (i < __kmp_place_socket_offset ||
3419 i >= __kmp_place_socket_offset + __kmp_place_num_sockets)
3420 n_old += nCoresPerPkg * __kmp_nThreadsPerCore; // skip not-requested socket
3421 else
3422 for (j = 0; j < nCoresPerPkg; ++j) // walk through requested socket
3423 if (j < __kmp_place_core_offset ||
3424 j >= __kmp_place_core_offset + __kmp_place_num_cores)
3425 n_old += __kmp_nThreadsPerCore; // skip not-requested core
3426 else
3427 for (k = 0; k < __kmp_nThreadsPerCore; ++k) { // walk through requested core
3428 if (k < __kmp_place_num_threads_per_core) {
3429 newAddr[n_new] = (*pAddr)[n_old]; // collect requested thread's data
3430 n_new++;
3431 }
3432 n_old++;
Jim Cownie5e8470a2013-09-27 10:38:44 +00003433 }
Jonathan Peytondd4aa9b2015-10-08 17:55:54 +00003434 KMP_DEBUG_ASSERT(n_old == nPackages * nCoresPerPkg * __kmp_nThreadsPerCore);
3435 KMP_DEBUG_ASSERT(n_new == __kmp_place_num_sockets * __kmp_place_num_cores *
3436 __kmp_place_num_threads_per_core);
3437
3438 nPackages = __kmp_place_num_sockets; // correct nPackages
Jim Cownie5e8470a2013-09-27 10:38:44 +00003439 nCoresPerPkg = __kmp_place_num_cores; // correct nCoresPerPkg
3440 __kmp_nThreadsPerCore = __kmp_place_num_threads_per_core; // correct __kmp_nThreadsPerCore
3441 __kmp_avail_proc = n_new; // correct avail_proc
3442 __kmp_ncores = nPackages * __kmp_place_num_cores; // correct ncores
3443
3444 __kmp_free( *pAddr );
3445 *pAddr = newAddr; // replace old topology with new one
3446}
3447
Jim Cownie5e8470a2013-09-27 10:38:44 +00003448
3449static AddrUnsPair *address2os = NULL;
3450static int * procarr = NULL;
3451static int __kmp_aff_depth = 0;
3452
3453static void
3454__kmp_aux_affinity_initialize(void)
3455{
3456 if (__kmp_affinity_masks != NULL) {
3457 KMP_ASSERT(fullMask != NULL);
3458 return;
3459 }
3460
3461 //
3462 // Create the "full" mask - this defines all of the processors that we
3463 // consider to be in the machine model. If respect is set, then it is
3464 // the initialization thread's affinity mask. Otherwise, it is all
3465 // processors that we know about on the machine.
3466 //
3467 if (fullMask == NULL) {
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003468 KMP_CPU_ALLOC(fullMask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003469 }
3470 if (KMP_AFFINITY_CAPABLE()) {
3471 if (__kmp_affinity_respect_mask) {
3472 __kmp_get_system_affinity(fullMask, TRUE);
3473
3474 //
3475 // Count the number of available processors.
3476 //
3477 unsigned i;
3478 __kmp_avail_proc = 0;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003479 KMP_CPU_SET_ITERATE(i, fullMask) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00003480 if (! KMP_CPU_ISSET(i, fullMask)) {
3481 continue;
3482 }
3483 __kmp_avail_proc++;
3484 }
3485 if (__kmp_avail_proc > __kmp_xproc) {
3486 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3487 && (__kmp_affinity_type != affinity_none))) {
3488 KMP_WARNING(ErrorInitializeAffinity);
3489 }
3490 __kmp_affinity_type = affinity_none;
Andrey Churbanov1f037e42015-03-10 09:15:26 +00003491 KMP_AFFINITY_DISABLE();
Jim Cownie5e8470a2013-09-27 10:38:44 +00003492 return;
3493 }
3494 }
3495 else {
3496 __kmp_affinity_entire_machine_mask(fullMask);
3497 __kmp_avail_proc = __kmp_xproc;
3498 }
3499 }
3500
3501 int depth = -1;
3502 kmp_i18n_id_t msg_id = kmp_i18n_null;
3503
3504 //
Alp Toker8f2d3f02014-02-24 10:40:15 +00003505 // For backward compatibility, setting KMP_CPUINFO_FILE =>
Jim Cownie5e8470a2013-09-27 10:38:44 +00003506 // KMP_TOPOLOGY_METHOD=cpuinfo
3507 //
3508 if ((__kmp_cpuinfo_file != NULL) &&
3509 (__kmp_affinity_top_method == affinity_top_method_all)) {
3510 __kmp_affinity_top_method = affinity_top_method_cpuinfo;
3511 }
3512
3513 if (__kmp_affinity_top_method == affinity_top_method_all) {
3514 //
3515 // In the default code path, errors are not fatal - we just try using
3516 // another method. We only emit a warning message if affinity is on,
3517 // or the verbose flag is set, an the nowarnings flag was not set.
3518 //
3519 const char *file_name = NULL;
3520 int line = 0;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003521# if KMP_USE_HWLOC
3522 if (depth < 0) {
3523 if (__kmp_affinity_verbose) {
3524 KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
3525 }
3526 if(!__kmp_hwloc_error) {
3527 depth = __kmp_affinity_create_hwloc_map(&address2os, &msg_id);
3528 if (depth == 0) {
3529 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3530 KMP_ASSERT(address2os == NULL);
3531 return;
3532 } else if(depth < 0 && __kmp_affinity_verbose) {
3533 KMP_INFORM(AffIgnoringHwloc, "KMP_AFFINITY");
3534 }
3535 } else if(__kmp_affinity_verbose) {
3536 KMP_INFORM(AffIgnoringHwloc, "KMP_AFFINITY");
3537 }
3538 }
3539# endif
Jim Cownie5e8470a2013-09-27 10:38:44 +00003540
3541# if KMP_ARCH_X86 || KMP_ARCH_X86_64
3542
Jim Cownie5e8470a2013-09-27 10:38:44 +00003543 if (depth < 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003544 if (__kmp_affinity_verbose) {
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003545 KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(Decodingx2APIC));
Jim Cownie5e8470a2013-09-27 10:38:44 +00003546 }
3547
3548 file_name = NULL;
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003549 depth = __kmp_affinity_create_x2apicid_map(&address2os, &msg_id);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003550 if (depth == 0) {
3551 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3552 KMP_ASSERT(address2os == NULL);
3553 return;
3554 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003555
3556 if (depth < 0) {
3557 if (__kmp_affinity_verbose) {
3558 if (msg_id != kmp_i18n_null) {
3559 KMP_INFORM(AffInfoStrStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id),
3560 KMP_I18N_STR(DecodingLegacyAPIC));
3561 }
3562 else {
3563 KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(DecodingLegacyAPIC));
3564 }
3565 }
3566
3567 file_name = NULL;
3568 depth = __kmp_affinity_create_apicid_map(&address2os, &msg_id);
3569 if (depth == 0) {
3570 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3571 KMP_ASSERT(address2os == NULL);
3572 return;
3573 }
3574 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003575 }
3576
3577# endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
3578
3579# if KMP_OS_LINUX
3580
3581 if (depth < 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003582 if (__kmp_affinity_verbose) {
3583 if (msg_id != kmp_i18n_null) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00003584 KMP_INFORM(AffStrParseFilename, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id), "/proc/cpuinfo");
3585 }
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003586 else {
3587 KMP_INFORM(AffParseFilename, "KMP_AFFINITY", "/proc/cpuinfo");
3588 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003589 }
3590
3591 FILE *f = fopen("/proc/cpuinfo", "r");
3592 if (f == NULL) {
3593 msg_id = kmp_i18n_str_CantOpenCpuinfo;
3594 }
3595 else {
3596 file_name = "/proc/cpuinfo";
3597 depth = __kmp_affinity_create_cpuinfo_map(&address2os, &line, &msg_id, f);
3598 fclose(f);
3599 if (depth == 0) {
3600 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3601 KMP_ASSERT(address2os == NULL);
3602 return;
3603 }
3604 }
3605 }
3606
3607# endif /* KMP_OS_LINUX */
3608
Andrey Churbanov7daf9802015-01-27 16:52:57 +00003609# if KMP_GROUP_AFFINITY
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003610
3611 if ((depth < 0) && (__kmp_num_proc_groups > 1)) {
3612 if (__kmp_affinity_verbose) {
3613 KMP_INFORM(AffWindowsProcGroupMap, "KMP_AFFINITY");
3614 }
3615
3616 depth = __kmp_affinity_create_proc_group_map(&address2os, &msg_id);
3617 KMP_ASSERT(depth != 0);
3618 }
3619
Andrey Churbanov7daf9802015-01-27 16:52:57 +00003620# endif /* KMP_GROUP_AFFINITY */
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003621
Jim Cownie5e8470a2013-09-27 10:38:44 +00003622 if (depth < 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003623 if (__kmp_affinity_verbose && (msg_id != kmp_i18n_null)) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00003624 if (file_name == NULL) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003625 KMP_INFORM(UsingFlatOS, __kmp_i18n_catgets(msg_id));
Jim Cownie5e8470a2013-09-27 10:38:44 +00003626 }
3627 else if (line == 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003628 KMP_INFORM(UsingFlatOSFile, file_name, __kmp_i18n_catgets(msg_id));
Jim Cownie5e8470a2013-09-27 10:38:44 +00003629 }
3630 else {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003631 KMP_INFORM(UsingFlatOSFileLine, file_name, line, __kmp_i18n_catgets(msg_id));
Jim Cownie5e8470a2013-09-27 10:38:44 +00003632 }
3633 }
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003634 // FIXME - print msg if msg_id = kmp_i18n_null ???
Jim Cownie5e8470a2013-09-27 10:38:44 +00003635
3636 file_name = "";
3637 depth = __kmp_affinity_create_flat_map(&address2os, &msg_id);
3638 if (depth == 0) {
3639 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3640 KMP_ASSERT(address2os == NULL);
3641 return;
3642 }
3643 KMP_ASSERT(depth > 0);
3644 KMP_ASSERT(address2os != NULL);
3645 }
3646 }
3647
3648 //
3649 // If the user has specified that a paricular topology discovery method
3650 // is to be used, then we abort if that method fails. The exception is
3651 // group affinity, which might have been implicitly set.
3652 //
3653
3654# if KMP_ARCH_X86 || KMP_ARCH_X86_64
3655
3656 else if (__kmp_affinity_top_method == affinity_top_method_x2apicid) {
3657 if (__kmp_affinity_verbose) {
3658 KMP_INFORM(AffInfoStr, "KMP_AFFINITY",
3659 KMP_I18N_STR(Decodingx2APIC));
3660 }
3661
3662 depth = __kmp_affinity_create_x2apicid_map(&address2os, &msg_id);
3663 if (depth == 0) {
3664 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3665 KMP_ASSERT(address2os == NULL);
3666 return;
3667 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003668 if (depth < 0) {
3669 KMP_ASSERT(msg_id != kmp_i18n_null);
3670 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
3671 }
3672 }
3673 else if (__kmp_affinity_top_method == affinity_top_method_apicid) {
3674 if (__kmp_affinity_verbose) {
3675 KMP_INFORM(AffInfoStr, "KMP_AFFINITY",
3676 KMP_I18N_STR(DecodingLegacyAPIC));
3677 }
3678
3679 depth = __kmp_affinity_create_apicid_map(&address2os, &msg_id);
3680 if (depth == 0) {
3681 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3682 KMP_ASSERT(address2os == NULL);
3683 return;
3684 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003685 if (depth < 0) {
3686 KMP_ASSERT(msg_id != kmp_i18n_null);
3687 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
3688 }
3689 }
3690
3691# endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
3692
3693 else if (__kmp_affinity_top_method == affinity_top_method_cpuinfo) {
3694 const char *filename;
3695 if (__kmp_cpuinfo_file != NULL) {
3696 filename = __kmp_cpuinfo_file;
3697 }
3698 else {
3699 filename = "/proc/cpuinfo";
3700 }
3701
3702 if (__kmp_affinity_verbose) {
3703 KMP_INFORM(AffParseFilename, "KMP_AFFINITY", filename);
3704 }
3705
3706 FILE *f = fopen(filename, "r");
3707 if (f == NULL) {
3708 int code = errno;
3709 if (__kmp_cpuinfo_file != NULL) {
3710 __kmp_msg(
3711 kmp_ms_fatal,
3712 KMP_MSG(CantOpenFileForReading, filename),
3713 KMP_ERR(code),
3714 KMP_HNT(NameComesFrom_CPUINFO_FILE),
3715 __kmp_msg_null
3716 );
3717 }
3718 else {
3719 __kmp_msg(
3720 kmp_ms_fatal,
3721 KMP_MSG(CantOpenFileForReading, filename),
3722 KMP_ERR(code),
3723 __kmp_msg_null
3724 );
3725 }
3726 }
3727 int line = 0;
3728 depth = __kmp_affinity_create_cpuinfo_map(&address2os, &line, &msg_id, f);
3729 fclose(f);
3730 if (depth < 0) {
3731 KMP_ASSERT(msg_id != kmp_i18n_null);
3732 if (line > 0) {
3733 KMP_FATAL(FileLineMsgExiting, filename, line, __kmp_i18n_catgets(msg_id));
3734 }
3735 else {
3736 KMP_FATAL(FileMsgExiting, filename, __kmp_i18n_catgets(msg_id));
3737 }
3738 }
3739 if (__kmp_affinity_type == affinity_none) {
3740 KMP_ASSERT(depth == 0);
3741 KMP_ASSERT(address2os == NULL);
3742 return;
3743 }
3744 }
3745
Andrey Churbanov7daf9802015-01-27 16:52:57 +00003746# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +00003747
3748 else if (__kmp_affinity_top_method == affinity_top_method_group) {
3749 if (__kmp_affinity_verbose) {
3750 KMP_INFORM(AffWindowsProcGroupMap, "KMP_AFFINITY");
3751 }
3752
3753 depth = __kmp_affinity_create_proc_group_map(&address2os, &msg_id);
3754 KMP_ASSERT(depth != 0);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003755 if (depth < 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003756 KMP_ASSERT(msg_id != kmp_i18n_null);
3757 KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
Jim Cownie5e8470a2013-09-27 10:38:44 +00003758 }
3759 }
3760
Andrey Churbanov7daf9802015-01-27 16:52:57 +00003761# endif /* KMP_GROUP_AFFINITY */
Jim Cownie5e8470a2013-09-27 10:38:44 +00003762
3763 else if (__kmp_affinity_top_method == affinity_top_method_flat) {
3764 if (__kmp_affinity_verbose) {
3765 KMP_INFORM(AffUsingFlatOS, "KMP_AFFINITY");
3766 }
3767
3768 depth = __kmp_affinity_create_flat_map(&address2os, &msg_id);
3769 if (depth == 0) {
3770 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3771 KMP_ASSERT(address2os == NULL);
3772 return;
3773 }
3774 // should not fail
3775 KMP_ASSERT(depth > 0);
3776 KMP_ASSERT(address2os != NULL);
3777 }
3778
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003779# if KMP_USE_HWLOC
3780 else if (__kmp_affinity_top_method == affinity_top_method_hwloc) {
3781 if (__kmp_affinity_verbose) {
3782 KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
3783 }
3784 depth = __kmp_affinity_create_hwloc_map(&address2os, &msg_id);
3785 if (depth == 0) {
3786 KMP_ASSERT(__kmp_affinity_type == affinity_none);
3787 KMP_ASSERT(address2os == NULL);
3788 return;
3789 }
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003790 }
3791# endif // KMP_USE_HWLOC
3792
Jim Cownie5e8470a2013-09-27 10:38:44 +00003793 if (address2os == NULL) {
3794 if (KMP_AFFINITY_CAPABLE()
3795 && (__kmp_affinity_verbose || (__kmp_affinity_warnings
3796 && (__kmp_affinity_type != affinity_none)))) {
3797 KMP_WARNING(ErrorInitializeAffinity);
3798 }
3799 __kmp_affinity_type = affinity_none;
Andrey Churbanov1f037e42015-03-10 09:15:26 +00003800 KMP_AFFINITY_DISABLE();
Jim Cownie5e8470a2013-09-27 10:38:44 +00003801 return;
3802 }
3803
Jim Cownie5e8470a2013-09-27 10:38:44 +00003804 __kmp_apply_thread_places(&address2os, depth);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003805
3806 //
3807 // Create the table of masks, indexed by thread Id.
3808 //
3809 unsigned maxIndex;
3810 unsigned numUnique;
3811 kmp_affin_mask_t *osId2Mask = __kmp_create_masks(&maxIndex, &numUnique,
3812 address2os, __kmp_avail_proc);
3813 if (__kmp_affinity_gran_levels == 0) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00003814 KMP_DEBUG_ASSERT((int)numUnique == __kmp_avail_proc);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003815 }
3816
3817 //
3818 // Set the childNums vector in all Address objects. This must be done
3819 // before we can sort using __kmp_affinity_cmp_Address_child_num(),
3820 // which takes into account the setting of __kmp_affinity_compact.
3821 //
3822 __kmp_affinity_assign_child_nums(address2os, __kmp_avail_proc);
3823
3824 switch (__kmp_affinity_type) {
3825
3826 case affinity_explicit:
3827 KMP_DEBUG_ASSERT(__kmp_affinity_proclist != NULL);
3828# if OMP_40_ENABLED
3829 if (__kmp_nested_proc_bind.bind_types[0] == proc_bind_intel)
3830# endif
3831 {
3832 __kmp_affinity_process_proclist(&__kmp_affinity_masks,
3833 &__kmp_affinity_num_masks, __kmp_affinity_proclist, osId2Mask,
3834 maxIndex);
3835 }
3836# if OMP_40_ENABLED
3837 else {
3838 __kmp_affinity_process_placelist(&__kmp_affinity_masks,
3839 &__kmp_affinity_num_masks, __kmp_affinity_proclist, osId2Mask,
3840 maxIndex);
3841 }
3842# endif
3843 if (__kmp_affinity_num_masks == 0) {
3844 if (__kmp_affinity_verbose || (__kmp_affinity_warnings
3845 && (__kmp_affinity_type != affinity_none))) {
3846 KMP_WARNING(AffNoValidProcID);
3847 }
3848 __kmp_affinity_type = affinity_none;
3849 return;
3850 }
3851 break;
3852
3853 //
3854 // The other affinity types rely on sorting the Addresses according
3855 // to some permutation of the machine topology tree. Set
3856 // __kmp_affinity_compact and __kmp_affinity_offset appropriately,
3857 // then jump to a common code fragment to do the sort and create
3858 // the array of affinity masks.
3859 //
3860
3861 case affinity_logical:
3862 __kmp_affinity_compact = 0;
3863 if (__kmp_affinity_offset) {
3864 __kmp_affinity_offset = __kmp_nThreadsPerCore * __kmp_affinity_offset
3865 % __kmp_avail_proc;
3866 }
3867 goto sortAddresses;
3868
3869 case affinity_physical:
3870 if (__kmp_nThreadsPerCore > 1) {
3871 __kmp_affinity_compact = 1;
3872 if (__kmp_affinity_compact >= depth) {
3873 __kmp_affinity_compact = 0;
3874 }
3875 } else {
3876 __kmp_affinity_compact = 0;
3877 }
3878 if (__kmp_affinity_offset) {
3879 __kmp_affinity_offset = __kmp_nThreadsPerCore * __kmp_affinity_offset
3880 % __kmp_avail_proc;
3881 }
3882 goto sortAddresses;
3883
3884 case affinity_scatter:
3885 if (__kmp_affinity_compact >= depth) {
3886 __kmp_affinity_compact = 0;
3887 }
3888 else {
3889 __kmp_affinity_compact = depth - 1 - __kmp_affinity_compact;
3890 }
3891 goto sortAddresses;
3892
3893 case affinity_compact:
3894 if (__kmp_affinity_compact >= depth) {
3895 __kmp_affinity_compact = depth - 1;
3896 }
3897 goto sortAddresses;
3898
Jim Cownie5e8470a2013-09-27 10:38:44 +00003899 case affinity_balanced:
Jonathan Peytoncaf09fe2015-05-27 23:27:33 +00003900 // Balanced works only for the case of a single package
Jim Cownie5e8470a2013-09-27 10:38:44 +00003901 if( nPackages > 1 ) {
3902 if( __kmp_affinity_verbose || __kmp_affinity_warnings ) {
3903 KMP_WARNING( AffBalancedNotAvail, "KMP_AFFINITY" );
3904 }
3905 __kmp_affinity_type = affinity_none;
3906 return;
3907 } else if( __kmp_affinity_uniform_topology() ) {
3908 break;
3909 } else { // Non-uniform topology
3910
3911 // Save the depth for further usage
3912 __kmp_aff_depth = depth;
3913
3914 // Number of hyper threads per core in HT machine
3915 int nth_per_core = __kmp_nThreadsPerCore;
3916
3917 int core_level;
3918 if( nth_per_core > 1 ) {
3919 core_level = depth - 2;
3920 } else {
3921 core_level = depth - 1;
3922 }
3923 int ncores = address2os[ __kmp_avail_proc - 1 ].first.labels[ core_level ] + 1;
3924 int nproc = nth_per_core * ncores;
3925
3926 procarr = ( int * )__kmp_allocate( sizeof( int ) * nproc );
3927 for( int i = 0; i < nproc; i++ ) {
3928 procarr[ i ] = -1;
3929 }
3930
3931 for( int i = 0; i < __kmp_avail_proc; i++ ) {
3932 int proc = address2os[ i ].second;
3933 // If depth == 3 then level=0 - package, level=1 - core, level=2 - thread.
3934 // If there is only one thread per core then depth == 2: level 0 - package,
3935 // level 1 - core.
3936 int level = depth - 1;
3937
3938 // __kmp_nth_per_core == 1
3939 int thread = 0;
3940 int core = address2os[ i ].first.labels[ level ];
3941 // If the thread level exists, that is we have more than one thread context per core
3942 if( nth_per_core > 1 ) {
3943 thread = address2os[ i ].first.labels[ level ] % nth_per_core;
3944 core = address2os[ i ].first.labels[ level - 1 ];
3945 }
3946 procarr[ core * nth_per_core + thread ] = proc;
3947 }
3948
3949 break;
3950 }
Jim Cownie5e8470a2013-09-27 10:38:44 +00003951
3952 sortAddresses:
3953 //
3954 // Allocate the gtid->affinity mask table.
3955 //
3956 if (__kmp_affinity_dups) {
3957 __kmp_affinity_num_masks = __kmp_avail_proc;
3958 }
3959 else {
3960 __kmp_affinity_num_masks = numUnique;
3961 }
3962
3963# if OMP_40_ENABLED
3964 if ( ( __kmp_nested_proc_bind.bind_types[0] != proc_bind_intel )
3965 && ( __kmp_affinity_num_places > 0 )
3966 && ( (unsigned)__kmp_affinity_num_places < __kmp_affinity_num_masks ) ) {
3967 __kmp_affinity_num_masks = __kmp_affinity_num_places;
3968 }
3969# endif
3970
Jonathan Peyton01dcf362015-11-30 20:02:59 +00003971 KMP_CPU_ALLOC_ARRAY(__kmp_affinity_masks, __kmp_affinity_num_masks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00003972
3973 //
3974 // Sort the address2os table according to the current setting of
3975 // __kmp_affinity_compact, then fill out __kmp_affinity_masks.
3976 //
3977 qsort(address2os, __kmp_avail_proc, sizeof(*address2os),
3978 __kmp_affinity_cmp_Address_child_num);
3979 {
3980 int i;
3981 unsigned j;
3982 for (i = 0, j = 0; i < __kmp_avail_proc; i++) {
3983 if ((! __kmp_affinity_dups) && (! address2os[i].first.leader)) {
3984 continue;
3985 }
3986 unsigned osId = address2os[i].second;
3987 kmp_affin_mask_t *src = KMP_CPU_INDEX(osId2Mask, osId);
3988 kmp_affin_mask_t *dest
3989 = KMP_CPU_INDEX(__kmp_affinity_masks, j);
3990 KMP_ASSERT(KMP_CPU_ISSET(osId, src));
3991 KMP_CPU_COPY(dest, src);
3992 if (++j >= __kmp_affinity_num_masks) {
3993 break;
3994 }
3995 }
3996 KMP_DEBUG_ASSERT(j == __kmp_affinity_num_masks);
3997 }
3998 break;
3999
4000 default:
4001 KMP_ASSERT2(0, "Unexpected affinity setting");
4002 }
4003
4004 __kmp_free(osId2Mask);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004005 machine_hierarchy.init(address2os, __kmp_avail_proc);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004006}
4007
4008
4009void
4010__kmp_affinity_initialize(void)
4011{
4012 //
4013 // Much of the code above was written assumming that if a machine was not
4014 // affinity capable, then __kmp_affinity_type == affinity_none. We now
4015 // explicitly represent this as __kmp_affinity_type == affinity_disabled.
4016 //
4017 // There are too many checks for __kmp_affinity_type == affinity_none
4018 // in this code. Instead of trying to change them all, check if
4019 // __kmp_affinity_type == affinity_disabled, and if so, slam it with
4020 // affinity_none, call the real initialization routine, then restore
4021 // __kmp_affinity_type to affinity_disabled.
4022 //
4023 int disabled = (__kmp_affinity_type == affinity_disabled);
4024 if (! KMP_AFFINITY_CAPABLE()) {
4025 KMP_ASSERT(disabled);
4026 }
4027 if (disabled) {
4028 __kmp_affinity_type = affinity_none;
4029 }
4030 __kmp_aux_affinity_initialize();
4031 if (disabled) {
4032 __kmp_affinity_type = affinity_disabled;
4033 }
4034}
4035
4036
4037void
4038__kmp_affinity_uninitialize(void)
4039{
4040 if (__kmp_affinity_masks != NULL) {
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004041 KMP_CPU_FREE_ARRAY(__kmp_affinity_masks, __kmp_affinity_num_masks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004042 __kmp_affinity_masks = NULL;
4043 }
4044 if (fullMask != NULL) {
4045 KMP_CPU_FREE(fullMask);
4046 fullMask = NULL;
4047 }
4048 __kmp_affinity_num_masks = 0;
4049# if OMP_40_ENABLED
4050 __kmp_affinity_num_places = 0;
4051# endif
4052 if (__kmp_affinity_proclist != NULL) {
4053 __kmp_free(__kmp_affinity_proclist);
4054 __kmp_affinity_proclist = NULL;
4055 }
4056 if( address2os != NULL ) {
4057 __kmp_free( address2os );
4058 address2os = NULL;
4059 }
4060 if( procarr != NULL ) {
4061 __kmp_free( procarr );
4062 procarr = NULL;
4063 }
Jonathan Peyton202a24d2016-06-13 17:30:08 +00004064# if KMP_USE_HWLOC
4065 if (__kmp_hwloc_topology != NULL) {
4066 hwloc_topology_destroy(__kmp_hwloc_topology);
4067 __kmp_hwloc_topology = NULL;
4068 }
4069# endif
Jim Cownie5e8470a2013-09-27 10:38:44 +00004070}
4071
4072
4073void
4074__kmp_affinity_set_init_mask(int gtid, int isa_root)
4075{
4076 if (! KMP_AFFINITY_CAPABLE()) {
4077 return;
4078 }
4079
4080 kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);
4081 if (th->th.th_affin_mask == NULL) {
4082 KMP_CPU_ALLOC(th->th.th_affin_mask);
4083 }
4084 else {
4085 KMP_CPU_ZERO(th->th.th_affin_mask);
4086 }
4087
4088 //
4089 // Copy the thread mask to the kmp_info_t strucuture.
4090 // If __kmp_affinity_type == affinity_none, copy the "full" mask, i.e. one
4091 // that has all of the OS proc ids set, or if __kmp_affinity_respect_mask
4092 // is set, then the full mask is the same as the mask of the initialization
4093 // thread.
4094 //
4095 kmp_affin_mask_t *mask;
4096 int i;
4097
4098# if OMP_40_ENABLED
4099 if (__kmp_nested_proc_bind.bind_types[0] == proc_bind_intel)
4100# endif
4101 {
Andrey Churbanovf28f6132015-01-13 14:54:00 +00004102 if ((__kmp_affinity_type == affinity_none) || (__kmp_affinity_type == affinity_balanced)
Jim Cownie5e8470a2013-09-27 10:38:44 +00004103 ) {
Andrey Churbanov7daf9802015-01-27 16:52:57 +00004104# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +00004105 if (__kmp_num_proc_groups > 1) {
4106 return;
4107 }
4108# endif
4109 KMP_ASSERT(fullMask != NULL);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004110 i = KMP_PLACE_ALL;
Jim Cownie5e8470a2013-09-27 10:38:44 +00004111 mask = fullMask;
4112 }
4113 else {
4114 KMP_DEBUG_ASSERT( __kmp_affinity_num_masks > 0 );
4115 i = (gtid + __kmp_affinity_offset) % __kmp_affinity_num_masks;
4116 mask = KMP_CPU_INDEX(__kmp_affinity_masks, i);
4117 }
4118 }
4119# if OMP_40_ENABLED
4120 else {
4121 if ((! isa_root)
4122 || (__kmp_nested_proc_bind.bind_types[0] == proc_bind_false)) {
Andrey Churbanov7daf9802015-01-27 16:52:57 +00004123# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +00004124 if (__kmp_num_proc_groups > 1) {
4125 return;
4126 }
4127# endif
4128 KMP_ASSERT(fullMask != NULL);
4129 i = KMP_PLACE_ALL;
4130 mask = fullMask;
4131 }
4132 else {
4133 //
4134 // int i = some hash function or just a counter that doesn't
4135 // always start at 0. Use gtid for now.
4136 //
4137 KMP_DEBUG_ASSERT( __kmp_affinity_num_masks > 0 );
4138 i = (gtid + __kmp_affinity_offset) % __kmp_affinity_num_masks;
4139 mask = KMP_CPU_INDEX(__kmp_affinity_masks, i);
4140 }
4141 }
4142# endif
4143
4144# if OMP_40_ENABLED
4145 th->th.th_current_place = i;
4146 if (isa_root) {
4147 th->th.th_new_place = i;
4148 th->th.th_first_place = 0;
4149 th->th.th_last_place = __kmp_affinity_num_masks - 1;
4150 }
4151
4152 if (i == KMP_PLACE_ALL) {
4153 KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to all places\n",
4154 gtid));
4155 }
4156 else {
4157 KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to place %d\n",
4158 gtid, i));
4159 }
4160# else
4161 if (i == -1) {
4162 KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to fullMask\n",
4163 gtid));
4164 }
4165 else {
4166 KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to mask %d\n",
4167 gtid, i));
4168 }
4169# endif /* OMP_40_ENABLED */
4170
4171 KMP_CPU_COPY(th->th.th_affin_mask, mask);
4172
4173 if (__kmp_affinity_verbose) {
4174 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4175 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4176 th->th.th_affin_mask);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004177 KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(), gtid,
4178 buf);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004179 }
4180
4181# if KMP_OS_WINDOWS
4182 //
4183 // On Windows* OS, the process affinity mask might have changed.
4184 // If the user didn't request affinity and this call fails,
4185 // just continue silently. See CQ171393.
4186 //
4187 if ( __kmp_affinity_type == affinity_none ) {
4188 __kmp_set_system_affinity(th->th.th_affin_mask, FALSE);
4189 }
4190 else
4191# endif
4192 __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
4193}
4194
4195
4196# if OMP_40_ENABLED
4197
4198void
4199__kmp_affinity_set_place(int gtid)
4200{
4201 int retval;
4202
4203 if (! KMP_AFFINITY_CAPABLE()) {
4204 return;
4205 }
4206
4207 kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);
4208
4209 KA_TRACE(100, ("__kmp_affinity_set_place: binding T#%d to place %d (current place = %d)\n",
4210 gtid, th->th.th_new_place, th->th.th_current_place));
4211
4212 //
Alp Toker8f2d3f02014-02-24 10:40:15 +00004213 // Check that the new place is within this thread's partition.
Jim Cownie5e8470a2013-09-27 10:38:44 +00004214 //
4215 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004216 KMP_ASSERT(th->th.th_new_place >= 0);
4217 KMP_ASSERT((unsigned)th->th.th_new_place <= __kmp_affinity_num_masks);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004218 if (th->th.th_first_place <= th->th.th_last_place) {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004219 KMP_ASSERT((th->th.th_new_place >= th->th.th_first_place)
Jim Cownie5e8470a2013-09-27 10:38:44 +00004220 && (th->th.th_new_place <= th->th.th_last_place));
4221 }
4222 else {
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004223 KMP_ASSERT((th->th.th_new_place <= th->th.th_first_place)
Jim Cownie5e8470a2013-09-27 10:38:44 +00004224 || (th->th.th_new_place >= th->th.th_last_place));
4225 }
4226
4227 //
4228 // Copy the thread mask to the kmp_info_t strucuture,
4229 // and set this thread's affinity.
4230 //
4231 kmp_affin_mask_t *mask = KMP_CPU_INDEX(__kmp_affinity_masks,
4232 th->th.th_new_place);
4233 KMP_CPU_COPY(th->th.th_affin_mask, mask);
4234 th->th.th_current_place = th->th.th_new_place;
4235
4236 if (__kmp_affinity_verbose) {
4237 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4238 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4239 th->th.th_affin_mask);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004240 KMP_INFORM(BoundToOSProcSet, "OMP_PROC_BIND", (kmp_int32)getpid(),
4241 gtid, buf);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004242 }
4243 __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
4244}
4245
4246# endif /* OMP_40_ENABLED */
4247
4248
4249int
4250__kmp_aux_set_affinity(void **mask)
4251{
4252 int gtid;
4253 kmp_info_t *th;
4254 int retval;
4255
4256 if (! KMP_AFFINITY_CAPABLE()) {
4257 return -1;
4258 }
4259
4260 gtid = __kmp_entry_gtid();
4261 KA_TRACE(1000, ;{
4262 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4263 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4264 (kmp_affin_mask_t *)(*mask));
4265 __kmp_debug_printf("kmp_set_affinity: setting affinity mask for thread %d = %s\n",
4266 gtid, buf);
4267 });
4268
4269 if (__kmp_env_consistency_check) {
4270 if ((mask == NULL) || (*mask == NULL)) {
4271 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
4272 }
4273 else {
4274 unsigned proc;
4275 int num_procs = 0;
4276
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004277 KMP_CPU_SET_ITERATE(proc, ((kmp_affin_mask_t*)(*mask))) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00004278 if (! KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask))) {
4279 continue;
4280 }
4281 num_procs++;
4282 if (! KMP_CPU_ISSET(proc, fullMask)) {
4283 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
4284 break;
4285 }
4286 }
4287 if (num_procs == 0) {
4288 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
4289 }
4290
Andrey Churbanov7daf9802015-01-27 16:52:57 +00004291# if KMP_GROUP_AFFINITY
Jim Cownie5e8470a2013-09-27 10:38:44 +00004292 if (__kmp_get_proc_group((kmp_affin_mask_t *)(*mask)) < 0) {
4293 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
4294 }
Andrey Churbanov7daf9802015-01-27 16:52:57 +00004295# endif /* KMP_GROUP_AFFINITY */
Jim Cownie5e8470a2013-09-27 10:38:44 +00004296
4297 }
4298 }
4299
4300 th = __kmp_threads[gtid];
4301 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
4302 retval = __kmp_set_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
4303 if (retval == 0) {
4304 KMP_CPU_COPY(th->th.th_affin_mask, (kmp_affin_mask_t *)(*mask));
4305 }
4306
4307# if OMP_40_ENABLED
4308 th->th.th_current_place = KMP_PLACE_UNDEFINED;
4309 th->th.th_new_place = KMP_PLACE_UNDEFINED;
4310 th->th.th_first_place = 0;
4311 th->th.th_last_place = __kmp_affinity_num_masks - 1;
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004312
4313 //
4314 // Turn off 4.0 affinity for the current tread at this parallel level.
4315 //
4316 th->th.th_current_task->td_icvs.proc_bind = proc_bind_false;
Jim Cownie5e8470a2013-09-27 10:38:44 +00004317# endif
4318
4319 return retval;
4320}
4321
4322
4323int
4324__kmp_aux_get_affinity(void **mask)
4325{
4326 int gtid;
4327 int retval;
4328 kmp_info_t *th;
4329
4330 if (! KMP_AFFINITY_CAPABLE()) {
4331 return -1;
4332 }
4333
4334 gtid = __kmp_entry_gtid();
4335 th = __kmp_threads[gtid];
4336 KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
4337
4338 KA_TRACE(1000, ;{
4339 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4340 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4341 th->th.th_affin_mask);
4342 __kmp_printf("kmp_get_affinity: stored affinity mask for thread %d = %s\n", gtid, buf);
4343 });
4344
4345 if (__kmp_env_consistency_check) {
4346 if ((mask == NULL) || (*mask == NULL)) {
4347 KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity");
4348 }
4349 }
4350
4351# if !KMP_OS_WINDOWS
4352
4353 retval = __kmp_get_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
4354 KA_TRACE(1000, ;{
4355 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4356 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4357 (kmp_affin_mask_t *)(*mask));
4358 __kmp_printf("kmp_get_affinity: system affinity mask for thread %d = %s\n", gtid, buf);
4359 });
4360 return retval;
4361
4362# else
4363
4364 KMP_CPU_COPY((kmp_affin_mask_t *)(*mask), th->th.th_affin_mask);
4365 return 0;
4366
4367# endif /* KMP_OS_WINDOWS */
4368
4369}
4370
Jim Cownie5e8470a2013-09-27 10:38:44 +00004371int
4372__kmp_aux_set_affinity_mask_proc(int proc, void **mask)
4373{
4374 int retval;
4375
4376 if (! KMP_AFFINITY_CAPABLE()) {
4377 return -1;
4378 }
4379
4380 KA_TRACE(1000, ;{
4381 int gtid = __kmp_entry_gtid();
4382 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4383 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4384 (kmp_affin_mask_t *)(*mask));
4385 __kmp_debug_printf("kmp_set_affinity_mask_proc: setting proc %d in affinity mask for thread %d = %s\n",
4386 proc, gtid, buf);
4387 });
4388
4389 if (__kmp_env_consistency_check) {
4390 if ((mask == NULL) || (*mask == NULL)) {
4391 KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity_mask_proc");
4392 }
4393 }
4394
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004395 if ((proc < 0)
4396# if !KMP_USE_HWLOC
4397 || ((unsigned)proc >= KMP_CPU_SETSIZE)
4398# endif
4399 ) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00004400 return -1;
4401 }
4402 if (! KMP_CPU_ISSET(proc, fullMask)) {
4403 return -2;
4404 }
4405
4406 KMP_CPU_SET(proc, (kmp_affin_mask_t *)(*mask));
4407 return 0;
4408}
4409
4410
4411int
4412__kmp_aux_unset_affinity_mask_proc(int proc, void **mask)
4413{
4414 int retval;
4415
4416 if (! KMP_AFFINITY_CAPABLE()) {
4417 return -1;
4418 }
4419
4420 KA_TRACE(1000, ;{
4421 int gtid = __kmp_entry_gtid();
4422 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4423 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4424 (kmp_affin_mask_t *)(*mask));
4425 __kmp_debug_printf("kmp_unset_affinity_mask_proc: unsetting proc %d in affinity mask for thread %d = %s\n",
4426 proc, gtid, buf);
4427 });
4428
4429 if (__kmp_env_consistency_check) {
4430 if ((mask == NULL) || (*mask == NULL)) {
4431 KMP_FATAL(AffinityInvalidMask, "kmp_unset_affinity_mask_proc");
4432 }
4433 }
4434
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004435 if ((proc < 0)
4436# if !KMP_USE_HWLOC
4437 || ((unsigned)proc >= KMP_CPU_SETSIZE)
4438# endif
4439 ) {
Jim Cownie5e8470a2013-09-27 10:38:44 +00004440 return -1;
4441 }
4442 if (! KMP_CPU_ISSET(proc, fullMask)) {
4443 return -2;
4444 }
4445
4446 KMP_CPU_CLR(proc, (kmp_affin_mask_t *)(*mask));
4447 return 0;
4448}
4449
4450
4451int
4452__kmp_aux_get_affinity_mask_proc(int proc, void **mask)
4453{
4454 int retval;
4455
4456 if (! KMP_AFFINITY_CAPABLE()) {
4457 return -1;
4458 }
4459
4460 KA_TRACE(1000, ;{
4461 int gtid = __kmp_entry_gtid();
4462 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4463 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
4464 (kmp_affin_mask_t *)(*mask));
4465 __kmp_debug_printf("kmp_get_affinity_mask_proc: getting proc %d in affinity mask for thread %d = %s\n",
4466 proc, gtid, buf);
4467 });
4468
4469 if (__kmp_env_consistency_check) {
4470 if ((mask == NULL) || (*mask == NULL)) {
Andrey Churbanov4b2f17a2015-01-29 15:49:22 +00004471 KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity_mask_proc");
Jim Cownie5e8470a2013-09-27 10:38:44 +00004472 }
4473 }
4474
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004475 if ((proc < 0)
4476# if !KMP_USE_HWLOC
4477 || ((unsigned)proc >= KMP_CPU_SETSIZE)
4478# endif
4479 ) {
4480 return -1;
Jim Cownie5e8470a2013-09-27 10:38:44 +00004481 }
4482 if (! KMP_CPU_ISSET(proc, fullMask)) {
4483 return 0;
4484 }
4485
4486 return KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask));
4487}
4488
Jim Cownie5e8470a2013-09-27 10:38:44 +00004489
4490// Dynamic affinity settings - Affinity balanced
4491void __kmp_balanced_affinity( int tid, int nthreads )
4492{
4493 if( __kmp_affinity_uniform_topology() ) {
4494 int coreID;
4495 int threadID;
4496 // Number of hyper threads per core in HT machine
4497 int __kmp_nth_per_core = __kmp_avail_proc / __kmp_ncores;
4498 // Number of cores
4499 int ncores = __kmp_ncores;
4500 // How many threads will be bound to each core
4501 int chunk = nthreads / ncores;
4502 // How many cores will have an additional thread bound to it - "big cores"
4503 int big_cores = nthreads % ncores;
4504 // Number of threads on the big cores
4505 int big_nth = ( chunk + 1 ) * big_cores;
4506 if( tid < big_nth ) {
4507 coreID = tid / (chunk + 1 );
4508 threadID = ( tid % (chunk + 1 ) ) % __kmp_nth_per_core ;
4509 } else { //tid >= big_nth
4510 coreID = ( tid - big_cores ) / chunk;
4511 threadID = ( ( tid - big_cores ) % chunk ) % __kmp_nth_per_core ;
4512 }
4513
4514 KMP_DEBUG_ASSERT2(KMP_AFFINITY_CAPABLE(),
4515 "Illegal set affinity operation when not capable");
4516
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004517 kmp_affin_mask_t *mask;
4518 KMP_CPU_ALLOC_ON_STACK(mask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004519 KMP_CPU_ZERO(mask);
4520
4521 // Granularity == thread
4522 if( __kmp_affinity_gran == affinity_gran_fine || __kmp_affinity_gran == affinity_gran_thread) {
4523 int osID = address2os[ coreID * __kmp_nth_per_core + threadID ].second;
4524 KMP_CPU_SET( osID, mask);
4525 } else if( __kmp_affinity_gran == affinity_gran_core ) { // Granularity == core
4526 for( int i = 0; i < __kmp_nth_per_core; i++ ) {
4527 int osID;
4528 osID = address2os[ coreID * __kmp_nth_per_core + i ].second;
4529 KMP_CPU_SET( osID, mask);
4530 }
4531 }
4532 if (__kmp_affinity_verbose) {
4533 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4534 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004535 KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(),
4536 tid, buf);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004537 }
4538 __kmp_set_system_affinity( mask, TRUE );
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004539 KMP_CPU_FREE_FROM_STACK(mask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004540 } else { // Non-uniform topology
4541
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004542 kmp_affin_mask_t *mask;
4543 KMP_CPU_ALLOC_ON_STACK(mask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004544 KMP_CPU_ZERO(mask);
4545
4546 // Number of hyper threads per core in HT machine
4547 int nth_per_core = __kmp_nThreadsPerCore;
4548 int core_level;
4549 if( nth_per_core > 1 ) {
4550 core_level = __kmp_aff_depth - 2;
4551 } else {
4552 core_level = __kmp_aff_depth - 1;
4553 }
4554
4555 // Number of cores - maximum value; it does not count trail cores with 0 processors
4556 int ncores = address2os[ __kmp_avail_proc - 1 ].first.labels[ core_level ] + 1;
4557
4558 // For performance gain consider the special case nthreads == __kmp_avail_proc
4559 if( nthreads == __kmp_avail_proc ) {
4560 if( __kmp_affinity_gran == affinity_gran_fine || __kmp_affinity_gran == affinity_gran_thread) {
4561 int osID = address2os[ tid ].second;
4562 KMP_CPU_SET( osID, mask);
4563 } else if( __kmp_affinity_gran == affinity_gran_core ) { // Granularity == core
4564 int coreID = address2os[ tid ].first.labels[ core_level ];
4565 // We'll count found osIDs for the current core; they can be not more than nth_per_core;
4566 // since the address2os is sortied we can break when cnt==nth_per_core
4567 int cnt = 0;
4568 for( int i = 0; i < __kmp_avail_proc; i++ ) {
4569 int osID = address2os[ i ].second;
4570 int core = address2os[ i ].first.labels[ core_level ];
4571 if( core == coreID ) {
4572 KMP_CPU_SET( osID, mask);
4573 cnt++;
4574 if( cnt == nth_per_core ) {
4575 break;
4576 }
4577 }
4578 }
4579 }
4580 } else if( nthreads <= __kmp_ncores ) {
4581
4582 int core = 0;
4583 for( int i = 0; i < ncores; i++ ) {
4584 // Check if this core from procarr[] is in the mask
4585 int in_mask = 0;
4586 for( int j = 0; j < nth_per_core; j++ ) {
4587 if( procarr[ i * nth_per_core + j ] != - 1 ) {
4588 in_mask = 1;
4589 break;
4590 }
4591 }
4592 if( in_mask ) {
4593 if( tid == core ) {
4594 for( int j = 0; j < nth_per_core; j++ ) {
4595 int osID = procarr[ i * nth_per_core + j ];
4596 if( osID != -1 ) {
4597 KMP_CPU_SET( osID, mask );
4598 // For granularity=thread it is enough to set the first available osID for this core
4599 if( __kmp_affinity_gran == affinity_gran_fine || __kmp_affinity_gran == affinity_gran_thread) {
4600 break;
4601 }
4602 }
4603 }
4604 break;
4605 } else {
4606 core++;
4607 }
4608 }
4609 }
4610
4611 } else { // nthreads > __kmp_ncores
4612
4613 // Array to save the number of processors at each core
Jonathan Peyton7be075332015-06-22 15:53:50 +00004614 int* nproc_at_core = (int*)KMP_ALLOCA(sizeof(int)*ncores);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004615 // Array to save the number of cores with "x" available processors;
Jonathan Peyton7be075332015-06-22 15:53:50 +00004616 int* ncores_with_x_procs = (int*)KMP_ALLOCA(sizeof(int)*(nth_per_core+1));
Jim Cownie5e8470a2013-09-27 10:38:44 +00004617 // Array to save the number of cores with # procs from x to nth_per_core
Jonathan Peyton7be075332015-06-22 15:53:50 +00004618 int* ncores_with_x_to_max_procs = (int*)KMP_ALLOCA(sizeof(int)*(nth_per_core+1));
Jim Cownie5e8470a2013-09-27 10:38:44 +00004619
4620 for( int i = 0; i <= nth_per_core; i++ ) {
4621 ncores_with_x_procs[ i ] = 0;
4622 ncores_with_x_to_max_procs[ i ] = 0;
4623 }
4624
4625 for( int i = 0; i < ncores; i++ ) {
4626 int cnt = 0;
4627 for( int j = 0; j < nth_per_core; j++ ) {
4628 if( procarr[ i * nth_per_core + j ] != -1 ) {
4629 cnt++;
4630 }
4631 }
4632 nproc_at_core[ i ] = cnt;
4633 ncores_with_x_procs[ cnt ]++;
4634 }
4635
4636 for( int i = 0; i <= nth_per_core; i++ ) {
4637 for( int j = i; j <= nth_per_core; j++ ) {
4638 ncores_with_x_to_max_procs[ i ] += ncores_with_x_procs[ j ];
4639 }
4640 }
4641
4642 // Max number of processors
4643 int nproc = nth_per_core * ncores;
4644 // An array to keep number of threads per each context
4645 int * newarr = ( int * )__kmp_allocate( sizeof( int ) * nproc );
4646 for( int i = 0; i < nproc; i++ ) {
4647 newarr[ i ] = 0;
4648 }
4649
4650 int nth = nthreads;
4651 int flag = 0;
4652 while( nth > 0 ) {
4653 for( int j = 1; j <= nth_per_core; j++ ) {
4654 int cnt = ncores_with_x_to_max_procs[ j ];
4655 for( int i = 0; i < ncores; i++ ) {
4656 // Skip the core with 0 processors
4657 if( nproc_at_core[ i ] == 0 ) {
4658 continue;
4659 }
4660 for( int k = 0; k < nth_per_core; k++ ) {
4661 if( procarr[ i * nth_per_core + k ] != -1 ) {
4662 if( newarr[ i * nth_per_core + k ] == 0 ) {
4663 newarr[ i * nth_per_core + k ] = 1;
4664 cnt--;
4665 nth--;
4666 break;
4667 } else {
4668 if( flag != 0 ) {
4669 newarr[ i * nth_per_core + k ] ++;
4670 cnt--;
4671 nth--;
4672 break;
4673 }
4674 }
4675 }
4676 }
4677 if( cnt == 0 || nth == 0 ) {
4678 break;
4679 }
4680 }
4681 if( nth == 0 ) {
4682 break;
4683 }
4684 }
4685 flag = 1;
4686 }
4687 int sum = 0;
4688 for( int i = 0; i < nproc; i++ ) {
4689 sum += newarr[ i ];
4690 if( sum > tid ) {
4691 // Granularity == thread
4692 if( __kmp_affinity_gran == affinity_gran_fine || __kmp_affinity_gran == affinity_gran_thread) {
4693 int osID = procarr[ i ];
4694 KMP_CPU_SET( osID, mask);
4695 } else if( __kmp_affinity_gran == affinity_gran_core ) { // Granularity == core
4696 int coreID = i / nth_per_core;
4697 for( int ii = 0; ii < nth_per_core; ii++ ) {
4698 int osID = procarr[ coreID * nth_per_core + ii ];
4699 if( osID != -1 ) {
4700 KMP_CPU_SET( osID, mask);
4701 }
4702 }
4703 }
4704 break;
4705 }
4706 }
4707 __kmp_free( newarr );
4708 }
4709
4710 if (__kmp_affinity_verbose) {
4711 char buf[KMP_AFFIN_MASK_PRINT_LEN];
4712 __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
Jim Cownie4cc4bb42014-10-07 16:25:50 +00004713 KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(),
4714 tid, buf);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004715 }
4716 __kmp_set_system_affinity( mask, TRUE );
Jonathan Peyton01dcf362015-11-30 20:02:59 +00004717 KMP_CPU_FREE_FROM_STACK(mask);
Jim Cownie5e8470a2013-09-27 10:38:44 +00004718 }
4719}
4720
Jonathan Peyton3076fa42016-01-12 17:21:55 +00004721#if KMP_OS_LINUX
4722// We don't need this entry for Windows because
4723// there is GetProcessAffinityMask() api
4724//
4725// The intended usage is indicated by these steps:
4726// 1) The user gets the current affinity mask
4727// 2) Then sets the affinity by calling this function
4728// 3) Error check the return value
4729// 4) Use non-OpenMP parallelization
4730// 5) Reset the affinity to what was stored in step 1)
4731#ifdef __cplusplus
4732extern "C"
4733#endif
4734int
4735kmp_set_thread_affinity_mask_initial()
4736// the function returns 0 on success,
4737// -1 if we cannot bind thread
4738// >0 (errno) if an error happened during binding
4739{
4740 int gtid = __kmp_get_gtid();
4741 if (gtid < 0) {
4742 // Do not touch non-omp threads
4743 KA_TRACE(30, ( "kmp_set_thread_affinity_mask_initial: "
4744 "non-omp thread, returning\n"));
4745 return -1;
4746 }
4747 if (!KMP_AFFINITY_CAPABLE() || !__kmp_init_middle) {
4748 KA_TRACE(30, ( "kmp_set_thread_affinity_mask_initial: "
4749 "affinity not initialized, returning\n"));
4750 return -1;
4751 }
4752 KA_TRACE(30, ( "kmp_set_thread_affinity_mask_initial: "
4753 "set full mask for thread %d\n", gtid));
4754 KMP_DEBUG_ASSERT(fullMask != NULL);
4755 return __kmp_set_system_affinity(fullMask, FALSE);
4756}
4757#endif
4758
Alp Toker763b9392014-02-28 09:42:41 +00004759#endif // KMP_AFFINITY_SUPPORTED