Path: blob/main/contrib/llvm-project/openmp/runtime/src/kmp_affinity.cpp
35258 views
/*1* kmp_affinity.cpp -- affinity management2*/34//===----------------------------------------------------------------------===//5//6// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.7// See https://llvm.org/LICENSE.txt for license information.8// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception9//10//===----------------------------------------------------------------------===//1112#include "kmp.h"13#include "kmp_affinity.h"14#include "kmp_i18n.h"15#include "kmp_io.h"16#include "kmp_str.h"17#include "kmp_wrapper_getpid.h"18#if KMP_USE_HIER_SCHED19#include "kmp_dispatch_hier.h"20#endif21#if KMP_USE_HWLOC22// Copied from hwloc23#define HWLOC_GROUP_KIND_INTEL_MODULE 10224#define HWLOC_GROUP_KIND_INTEL_TILE 10325#define HWLOC_GROUP_KIND_INTEL_DIE 10426#define HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP 22027#endif28#include <ctype.h>2930// The machine topology31kmp_topology_t *__kmp_topology = nullptr;32// KMP_HW_SUBSET environment variable33kmp_hw_subset_t *__kmp_hw_subset = nullptr;3435// Store the real or imagined machine hierarchy here36static hierarchy_info machine_hierarchy;3738void __kmp_cleanup_hierarchy() { machine_hierarchy.fini(); }3940#if KMP_AFFINITY_SUPPORTED41// Helper class to see if place lists further restrict the fullMask42class kmp_full_mask_modifier_t {43kmp_affin_mask_t *mask;4445public:46kmp_full_mask_modifier_t() {47KMP_CPU_ALLOC(mask);48KMP_CPU_ZERO(mask);49}50~kmp_full_mask_modifier_t() {51KMP_CPU_FREE(mask);52mask = nullptr;53}54void include(const kmp_affin_mask_t *other) { KMP_CPU_UNION(mask, other); }55// If the new full mask is different from the current full mask,56// then switch them. Returns true if full mask was affected, false otherwise.57bool restrict_to_mask() {58// See if the new mask further restricts or changes the full mask59if (KMP_CPU_EQUAL(__kmp_affin_fullMask, mask) || KMP_CPU_ISEMPTY(mask))60return false;61return __kmp_topology->restrict_to_mask(mask);62}63};6465static inline const char *66__kmp_get_affinity_env_var(const kmp_affinity_t &affinity,67bool for_binding = false) {68if (affinity.flags.omp_places) {69if (for_binding)70return "OMP_PROC_BIND";71return "OMP_PLACES";72}73return affinity.env_var;74}75#endif // KMP_AFFINITY_SUPPORTED7677void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar) {78kmp_uint32 depth;79// The test below is true if affinity is available, but set to "none". Need to80// init on first use of hierarchical barrier.81if (TCR_1(machine_hierarchy.uninitialized))82machine_hierarchy.init(nproc);8384// Adjust the hierarchy in case num threads exceeds original85if (nproc > machine_hierarchy.base_num_threads)86machine_hierarchy.resize(nproc);8788depth = machine_hierarchy.depth;89KMP_DEBUG_ASSERT(depth > 0);9091thr_bar->depth = depth;92__kmp_type_convert(machine_hierarchy.numPerLevel[0] - 1,93&(thr_bar->base_leaf_kids));94thr_bar->skip_per_level = machine_hierarchy.skipPerLevel;95}9697static int nCoresPerPkg, nPackages;98static int __kmp_nThreadsPerCore;99#ifndef KMP_DFLT_NTH_CORES100static int __kmp_ncores;101#endif102103const char *__kmp_hw_get_catalog_string(kmp_hw_t type, bool plural) {104switch (type) {105case KMP_HW_SOCKET:106return ((plural) ? KMP_I18N_STR(Sockets) : KMP_I18N_STR(Socket));107case KMP_HW_DIE:108return ((plural) ? KMP_I18N_STR(Dice) : KMP_I18N_STR(Die));109case KMP_HW_MODULE:110return ((plural) ? KMP_I18N_STR(Modules) : KMP_I18N_STR(Module));111case KMP_HW_TILE:112return ((plural) ? KMP_I18N_STR(Tiles) : KMP_I18N_STR(Tile));113case KMP_HW_NUMA:114return ((plural) ? KMP_I18N_STR(NumaDomains) : KMP_I18N_STR(NumaDomain));115case KMP_HW_L3:116return ((plural) ? KMP_I18N_STR(L3Caches) : KMP_I18N_STR(L3Cache));117case KMP_HW_L2:118return ((plural) ? KMP_I18N_STR(L2Caches) : KMP_I18N_STR(L2Cache));119case KMP_HW_L1:120return ((plural) ? KMP_I18N_STR(L1Caches) : KMP_I18N_STR(L1Cache));121case KMP_HW_LLC:122return ((plural) ? KMP_I18N_STR(LLCaches) : KMP_I18N_STR(LLCache));123case KMP_HW_CORE:124return ((plural) ? KMP_I18N_STR(Cores) : KMP_I18N_STR(Core));125case KMP_HW_THREAD:126return ((plural) ? KMP_I18N_STR(Threads) : KMP_I18N_STR(Thread));127case KMP_HW_PROC_GROUP:128return ((plural) ? KMP_I18N_STR(ProcGroups) : KMP_I18N_STR(ProcGroup));129case KMP_HW_UNKNOWN:130case KMP_HW_LAST:131return KMP_I18N_STR(Unknown);132}133KMP_ASSERT2(false, "Unhandled kmp_hw_t enumeration");134KMP_BUILTIN_UNREACHABLE;135}136137const char *__kmp_hw_get_keyword(kmp_hw_t type, bool plural) {138switch (type) {139case KMP_HW_SOCKET:140return ((plural) ? "sockets" : "socket");141case KMP_HW_DIE:142return ((plural) ? "dice" : "die");143case KMP_HW_MODULE:144return ((plural) ? "modules" : "module");145case KMP_HW_TILE:146return ((plural) ? "tiles" : "tile");147case KMP_HW_NUMA:148return ((plural) ? "numa_domains" : "numa_domain");149case KMP_HW_L3:150return ((plural) ? "l3_caches" : "l3_cache");151case KMP_HW_L2:152return ((plural) ? "l2_caches" : "l2_cache");153case KMP_HW_L1:154return ((plural) ? "l1_caches" : "l1_cache");155case KMP_HW_LLC:156return ((plural) ? "ll_caches" : "ll_cache");157case KMP_HW_CORE:158return ((plural) ? "cores" : "core");159case KMP_HW_THREAD:160return ((plural) ? "threads" : "thread");161case KMP_HW_PROC_GROUP:162return ((plural) ? "proc_groups" : "proc_group");163case KMP_HW_UNKNOWN:164case KMP_HW_LAST:165return ((plural) ? "unknowns" : "unknown");166}167KMP_ASSERT2(false, "Unhandled kmp_hw_t enumeration");168KMP_BUILTIN_UNREACHABLE;169}170171const char *__kmp_hw_get_core_type_string(kmp_hw_core_type_t type) {172switch (type) {173case KMP_HW_CORE_TYPE_UNKNOWN:174case KMP_HW_MAX_NUM_CORE_TYPES:175return "unknown";176#if KMP_ARCH_X86 || KMP_ARCH_X86_64177case KMP_HW_CORE_TYPE_ATOM:178return "Intel Atom(R) processor";179case KMP_HW_CORE_TYPE_CORE:180return "Intel(R) Core(TM) processor";181#endif182}183KMP_ASSERT2(false, "Unhandled kmp_hw_core_type_t enumeration");184KMP_BUILTIN_UNREACHABLE;185}186187#if KMP_AFFINITY_SUPPORTED188// If affinity is supported, check the affinity189// verbose and warning flags before printing warning190#define KMP_AFF_WARNING(s, ...) \191if (s.flags.verbose || (s.flags.warnings && (s.type != affinity_none))) { \192KMP_WARNING(__VA_ARGS__); \193}194#else195#define KMP_AFF_WARNING(s, ...) KMP_WARNING(__VA_ARGS__)196#endif197198////////////////////////////////////////////////////////////////////////////////199// kmp_hw_thread_t methods200int kmp_hw_thread_t::compare_ids(const void *a, const void *b) {201const kmp_hw_thread_t *ahwthread = (const kmp_hw_thread_t *)a;202const kmp_hw_thread_t *bhwthread = (const kmp_hw_thread_t *)b;203int depth = __kmp_topology->get_depth();204for (int level = 0; level < depth; ++level) {205if (ahwthread->ids[level] < bhwthread->ids[level])206return -1;207else if (ahwthread->ids[level] > bhwthread->ids[level])208return 1;209}210if (ahwthread->os_id < bhwthread->os_id)211return -1;212else if (ahwthread->os_id > bhwthread->os_id)213return 1;214return 0;215}216217#if KMP_AFFINITY_SUPPORTED218int kmp_hw_thread_t::compare_compact(const void *a, const void *b) {219int i;220const kmp_hw_thread_t *aa = (const kmp_hw_thread_t *)a;221const kmp_hw_thread_t *bb = (const kmp_hw_thread_t *)b;222int depth = __kmp_topology->get_depth();223int compact = __kmp_topology->compact;224KMP_DEBUG_ASSERT(compact >= 0);225KMP_DEBUG_ASSERT(compact <= depth);226for (i = 0; i < compact; i++) {227int j = depth - i - 1;228if (aa->sub_ids[j] < bb->sub_ids[j])229return -1;230if (aa->sub_ids[j] > bb->sub_ids[j])231return 1;232}233for (; i < depth; i++) {234int j = i - compact;235if (aa->sub_ids[j] < bb->sub_ids[j])236return -1;237if (aa->sub_ids[j] > bb->sub_ids[j])238return 1;239}240return 0;241}242#endif243244void kmp_hw_thread_t::print() const {245int depth = __kmp_topology->get_depth();246printf("%4d ", os_id);247for (int i = 0; i < depth; ++i) {248printf("%4d ", ids[i]);249}250if (attrs) {251if (attrs.is_core_type_valid())252printf(" (%s)", __kmp_hw_get_core_type_string(attrs.get_core_type()));253if (attrs.is_core_eff_valid())254printf(" (eff=%d)", attrs.get_core_eff());255}256if (leader)257printf(" (leader)");258printf("\n");259}260261////////////////////////////////////////////////////////////////////////////////262// kmp_topology_t methods263264// Add a layer to the topology based on the ids. Assume the topology265// is perfectly nested (i.e., so no object has more than one parent)266void kmp_topology_t::_insert_layer(kmp_hw_t type, const int *ids) {267// Figure out where the layer should go by comparing the ids of the current268// layers with the new ids269int target_layer;270int previous_id = kmp_hw_thread_t::UNKNOWN_ID;271int previous_new_id = kmp_hw_thread_t::UNKNOWN_ID;272273// Start from the highest layer and work down to find target layer274// If new layer is equal to another layer then put the new layer above275for (target_layer = 0; target_layer < depth; ++target_layer) {276bool layers_equal = true;277bool strictly_above_target_layer = false;278for (int i = 0; i < num_hw_threads; ++i) {279int id = hw_threads[i].ids[target_layer];280int new_id = ids[i];281if (id != previous_id && new_id == previous_new_id) {282// Found the layer we are strictly above283strictly_above_target_layer = true;284layers_equal = false;285break;286} else if (id == previous_id && new_id != previous_new_id) {287// Found a layer we are below. Move to next layer and check.288layers_equal = false;289break;290}291previous_id = id;292previous_new_id = new_id;293}294if (strictly_above_target_layer || layers_equal)295break;296}297298// Found the layer we are above. Now move everything to accommodate the new299// layer. And put the new ids and type into the topology.300for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)301types[j] = types[i];302types[target_layer] = type;303for (int k = 0; k < num_hw_threads; ++k) {304for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)305hw_threads[k].ids[j] = hw_threads[k].ids[i];306hw_threads[k].ids[target_layer] = ids[k];307}308equivalent[type] = type;309depth++;310}311312#if KMP_GROUP_AFFINITY313// Insert the Windows Processor Group structure into the topology314void kmp_topology_t::_insert_windows_proc_groups() {315// Do not insert the processor group structure for a single group316if (__kmp_num_proc_groups == 1)317return;318kmp_affin_mask_t *mask;319int *ids = (int *)__kmp_allocate(sizeof(int) * num_hw_threads);320KMP_CPU_ALLOC(mask);321for (int i = 0; i < num_hw_threads; ++i) {322KMP_CPU_ZERO(mask);323KMP_CPU_SET(hw_threads[i].os_id, mask);324ids[i] = __kmp_get_proc_group(mask);325}326KMP_CPU_FREE(mask);327_insert_layer(KMP_HW_PROC_GROUP, ids);328__kmp_free(ids);329330// sort topology after adding proc groups331__kmp_topology->sort_ids();332}333#endif334335// Remove layers that don't add information to the topology.336// This is done by having the layer take on the id = UNKNOWN_ID (-1)337void kmp_topology_t::_remove_radix1_layers() {338int preference[KMP_HW_LAST];339int top_index1, top_index2;340// Set up preference associative array341preference[KMP_HW_SOCKET] = 110;342preference[KMP_HW_PROC_GROUP] = 100;343preference[KMP_HW_CORE] = 95;344preference[KMP_HW_THREAD] = 90;345preference[KMP_HW_NUMA] = 85;346preference[KMP_HW_DIE] = 80;347preference[KMP_HW_TILE] = 75;348preference[KMP_HW_MODULE] = 73;349preference[KMP_HW_L3] = 70;350preference[KMP_HW_L2] = 65;351preference[KMP_HW_L1] = 60;352preference[KMP_HW_LLC] = 5;353top_index1 = 0;354top_index2 = 1;355while (top_index1 < depth - 1 && top_index2 < depth) {356kmp_hw_t type1 = types[top_index1];357kmp_hw_t type2 = types[top_index2];358KMP_ASSERT_VALID_HW_TYPE(type1);359KMP_ASSERT_VALID_HW_TYPE(type2);360// Do not allow the three main topology levels (sockets, cores, threads) to361// be compacted down362if ((type1 == KMP_HW_THREAD || type1 == KMP_HW_CORE ||363type1 == KMP_HW_SOCKET) &&364(type2 == KMP_HW_THREAD || type2 == KMP_HW_CORE ||365type2 == KMP_HW_SOCKET)) {366top_index1 = top_index2++;367continue;368}369bool radix1 = true;370bool all_same = true;371int id1 = hw_threads[0].ids[top_index1];372int id2 = hw_threads[0].ids[top_index2];373int pref1 = preference[type1];374int pref2 = preference[type2];375for (int hwidx = 1; hwidx < num_hw_threads; ++hwidx) {376if (hw_threads[hwidx].ids[top_index1] == id1 &&377hw_threads[hwidx].ids[top_index2] != id2) {378radix1 = false;379break;380}381if (hw_threads[hwidx].ids[top_index2] != id2)382all_same = false;383id1 = hw_threads[hwidx].ids[top_index1];384id2 = hw_threads[hwidx].ids[top_index2];385}386if (radix1) {387// Select the layer to remove based on preference388kmp_hw_t remove_type, keep_type;389int remove_layer, remove_layer_ids;390if (pref1 > pref2) {391remove_type = type2;392remove_layer = remove_layer_ids = top_index2;393keep_type = type1;394} else {395remove_type = type1;396remove_layer = remove_layer_ids = top_index1;397keep_type = type2;398}399// If all the indexes for the second (deeper) layer are the same.400// e.g., all are zero, then make sure to keep the first layer's ids401if (all_same)402remove_layer_ids = top_index2;403// Remove radix one type by setting the equivalence, removing the id from404// the hw threads and removing the layer from types and depth405set_equivalent_type(remove_type, keep_type);406for (int idx = 0; idx < num_hw_threads; ++idx) {407kmp_hw_thread_t &hw_thread = hw_threads[idx];408for (int d = remove_layer_ids; d < depth - 1; ++d)409hw_thread.ids[d] = hw_thread.ids[d + 1];410}411for (int idx = remove_layer; idx < depth - 1; ++idx)412types[idx] = types[idx + 1];413depth--;414} else {415top_index1 = top_index2++;416}417}418KMP_ASSERT(depth > 0);419}420421void kmp_topology_t::_set_last_level_cache() {422if (get_equivalent_type(KMP_HW_L3) != KMP_HW_UNKNOWN)423set_equivalent_type(KMP_HW_LLC, KMP_HW_L3);424else if (get_equivalent_type(KMP_HW_L2) != KMP_HW_UNKNOWN)425set_equivalent_type(KMP_HW_LLC, KMP_HW_L2);426#if KMP_MIC_SUPPORTED427else if (__kmp_mic_type == mic3) {428if (get_equivalent_type(KMP_HW_L2) != KMP_HW_UNKNOWN)429set_equivalent_type(KMP_HW_LLC, KMP_HW_L2);430else if (get_equivalent_type(KMP_HW_TILE) != KMP_HW_UNKNOWN)431set_equivalent_type(KMP_HW_LLC, KMP_HW_TILE);432// L2/Tile wasn't detected so just say L1433else434set_equivalent_type(KMP_HW_LLC, KMP_HW_L1);435}436#endif437else if (get_equivalent_type(KMP_HW_L1) != KMP_HW_UNKNOWN)438set_equivalent_type(KMP_HW_LLC, KMP_HW_L1);439// Fallback is to set last level cache to socket or core440if (get_equivalent_type(KMP_HW_LLC) == KMP_HW_UNKNOWN) {441if (get_equivalent_type(KMP_HW_SOCKET) != KMP_HW_UNKNOWN)442set_equivalent_type(KMP_HW_LLC, KMP_HW_SOCKET);443else if (get_equivalent_type(KMP_HW_CORE) != KMP_HW_UNKNOWN)444set_equivalent_type(KMP_HW_LLC, KMP_HW_CORE);445}446KMP_ASSERT(get_equivalent_type(KMP_HW_LLC) != KMP_HW_UNKNOWN);447}448449// Gather the count of each topology layer and the ratio450void kmp_topology_t::_gather_enumeration_information() {451int previous_id[KMP_HW_LAST];452int max[KMP_HW_LAST];453454for (int i = 0; i < depth; ++i) {455previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;456max[i] = 0;457count[i] = 0;458ratio[i] = 0;459}460int core_level = get_level(KMP_HW_CORE);461for (int i = 0; i < num_hw_threads; ++i) {462kmp_hw_thread_t &hw_thread = hw_threads[i];463for (int layer = 0; layer < depth; ++layer) {464int id = hw_thread.ids[layer];465if (id != previous_id[layer]) {466// Add an additional increment to each count467for (int l = layer; l < depth; ++l)468count[l]++;469// Keep track of topology layer ratio statistics470max[layer]++;471for (int l = layer + 1; l < depth; ++l) {472if (max[l] > ratio[l])473ratio[l] = max[l];474max[l] = 1;475}476// Figure out the number of different core types477// and efficiencies for hybrid CPUs478if (__kmp_is_hybrid_cpu() && core_level >= 0 && layer <= core_level) {479if (hw_thread.attrs.is_core_eff_valid() &&480hw_thread.attrs.core_eff >= num_core_efficiencies) {481// Because efficiencies can range from 0 to max efficiency - 1,482// the number of efficiencies is max efficiency + 1483num_core_efficiencies = hw_thread.attrs.core_eff + 1;484}485if (hw_thread.attrs.is_core_type_valid()) {486bool found = false;487for (int j = 0; j < num_core_types; ++j) {488if (hw_thread.attrs.get_core_type() == core_types[j]) {489found = true;490break;491}492}493if (!found) {494KMP_ASSERT(num_core_types < KMP_HW_MAX_NUM_CORE_TYPES);495core_types[num_core_types++] = hw_thread.attrs.get_core_type();496}497}498}499break;500}501}502for (int layer = 0; layer < depth; ++layer) {503previous_id[layer] = hw_thread.ids[layer];504}505}506for (int layer = 0; layer < depth; ++layer) {507if (max[layer] > ratio[layer])508ratio[layer] = max[layer];509}510}511512int kmp_topology_t::_get_ncores_with_attr(const kmp_hw_attr_t &attr,513int above_level,514bool find_all) const {515int current, current_max;516int previous_id[KMP_HW_LAST];517for (int i = 0; i < depth; ++i)518previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;519int core_level = get_level(KMP_HW_CORE);520if (find_all)521above_level = -1;522KMP_ASSERT(above_level < core_level);523current_max = 0;524current = 0;525for (int i = 0; i < num_hw_threads; ++i) {526kmp_hw_thread_t &hw_thread = hw_threads[i];527if (!find_all && hw_thread.ids[above_level] != previous_id[above_level]) {528if (current > current_max)529current_max = current;530current = hw_thread.attrs.contains(attr);531} else {532for (int level = above_level + 1; level <= core_level; ++level) {533if (hw_thread.ids[level] != previous_id[level]) {534if (hw_thread.attrs.contains(attr))535current++;536break;537}538}539}540for (int level = 0; level < depth; ++level)541previous_id[level] = hw_thread.ids[level];542}543if (current > current_max)544current_max = current;545return current_max;546}547548// Find out if the topology is uniform549void kmp_topology_t::_discover_uniformity() {550int num = 1;551for (int level = 0; level < depth; ++level)552num *= ratio[level];553flags.uniform = (num == count[depth - 1]);554}555556// Set all the sub_ids for each hardware thread557void kmp_topology_t::_set_sub_ids() {558int previous_id[KMP_HW_LAST];559int sub_id[KMP_HW_LAST];560561for (int i = 0; i < depth; ++i) {562previous_id[i] = -1;563sub_id[i] = -1;564}565for (int i = 0; i < num_hw_threads; ++i) {566kmp_hw_thread_t &hw_thread = hw_threads[i];567// Setup the sub_id568for (int j = 0; j < depth; ++j) {569if (hw_thread.ids[j] != previous_id[j]) {570sub_id[j]++;571for (int k = j + 1; k < depth; ++k) {572sub_id[k] = 0;573}574break;575}576}577// Set previous_id578for (int j = 0; j < depth; ++j) {579previous_id[j] = hw_thread.ids[j];580}581// Set the sub_ids field582for (int j = 0; j < depth; ++j) {583hw_thread.sub_ids[j] = sub_id[j];584}585}586}587588void kmp_topology_t::_set_globals() {589// Set nCoresPerPkg, nPackages, __kmp_nThreadsPerCore, __kmp_ncores590int core_level, thread_level, package_level;591package_level = get_level(KMP_HW_SOCKET);592#if KMP_GROUP_AFFINITY593if (package_level == -1)594package_level = get_level(KMP_HW_PROC_GROUP);595#endif596core_level = get_level(KMP_HW_CORE);597thread_level = get_level(KMP_HW_THREAD);598599KMP_ASSERT(core_level != -1);600KMP_ASSERT(thread_level != -1);601602__kmp_nThreadsPerCore = calculate_ratio(thread_level, core_level);603if (package_level != -1) {604nCoresPerPkg = calculate_ratio(core_level, package_level);605nPackages = get_count(package_level);606} else {607// assume one socket608nCoresPerPkg = get_count(core_level);609nPackages = 1;610}611#ifndef KMP_DFLT_NTH_CORES612__kmp_ncores = get_count(core_level);613#endif614}615616kmp_topology_t *kmp_topology_t::allocate(int nproc, int ndepth,617const kmp_hw_t *types) {618kmp_topology_t *retval;619// Allocate all data in one large allocation620size_t size = sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc +621sizeof(int) * (size_t)KMP_HW_LAST * 3;622char *bytes = (char *)__kmp_allocate(size);623retval = (kmp_topology_t *)bytes;624if (nproc > 0) {625retval->hw_threads = (kmp_hw_thread_t *)(bytes + sizeof(kmp_topology_t));626} else {627retval->hw_threads = nullptr;628}629retval->num_hw_threads = nproc;630retval->depth = ndepth;631int *arr =632(int *)(bytes + sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc);633retval->types = (kmp_hw_t *)arr;634retval->ratio = arr + (size_t)KMP_HW_LAST;635retval->count = arr + 2 * (size_t)KMP_HW_LAST;636retval->num_core_efficiencies = 0;637retval->num_core_types = 0;638retval->compact = 0;639for (int i = 0; i < KMP_HW_MAX_NUM_CORE_TYPES; ++i)640retval->core_types[i] = KMP_HW_CORE_TYPE_UNKNOWN;641KMP_FOREACH_HW_TYPE(type) { retval->equivalent[type] = KMP_HW_UNKNOWN; }642for (int i = 0; i < ndepth; ++i) {643retval->types[i] = types[i];644retval->equivalent[types[i]] = types[i];645}646return retval;647}648649void kmp_topology_t::deallocate(kmp_topology_t *topology) {650if (topology)651__kmp_free(topology);652}653654bool kmp_topology_t::check_ids() const {655// Assume ids have been sorted656if (num_hw_threads == 0)657return true;658for (int i = 1; i < num_hw_threads; ++i) {659kmp_hw_thread_t ¤t_thread = hw_threads[i];660kmp_hw_thread_t &previous_thread = hw_threads[i - 1];661bool unique = false;662for (int j = 0; j < depth; ++j) {663if (previous_thread.ids[j] != current_thread.ids[j]) {664unique = true;665break;666}667}668if (unique)669continue;670return false;671}672return true;673}674675void kmp_topology_t::dump() const {676printf("***********************\n");677printf("*** __kmp_topology: ***\n");678printf("***********************\n");679printf("* depth: %d\n", depth);680681printf("* types: ");682for (int i = 0; i < depth; ++i)683printf("%15s ", __kmp_hw_get_keyword(types[i]));684printf("\n");685686printf("* ratio: ");687for (int i = 0; i < depth; ++i) {688printf("%15d ", ratio[i]);689}690printf("\n");691692printf("* count: ");693for (int i = 0; i < depth; ++i) {694printf("%15d ", count[i]);695}696printf("\n");697698printf("* num_core_eff: %d\n", num_core_efficiencies);699printf("* num_core_types: %d\n", num_core_types);700printf("* core_types: ");701for (int i = 0; i < num_core_types; ++i)702printf("%3d ", core_types[i]);703printf("\n");704705printf("* equivalent map:\n");706KMP_FOREACH_HW_TYPE(i) {707const char *key = __kmp_hw_get_keyword(i);708const char *value = __kmp_hw_get_keyword(equivalent[i]);709printf("%-15s -> %-15s\n", key, value);710}711712printf("* uniform: %s\n", (is_uniform() ? "Yes" : "No"));713714printf("* num_hw_threads: %d\n", num_hw_threads);715printf("* hw_threads:\n");716for (int i = 0; i < num_hw_threads; ++i) {717hw_threads[i].print();718}719printf("***********************\n");720}721722void kmp_topology_t::print(const char *env_var) const {723kmp_str_buf_t buf;724int print_types_depth;725__kmp_str_buf_init(&buf);726kmp_hw_t print_types[KMP_HW_LAST + 2];727728// Num Available Threads729if (num_hw_threads) {730KMP_INFORM(AvailableOSProc, env_var, num_hw_threads);731} else {732KMP_INFORM(AvailableOSProc, env_var, __kmp_xproc);733}734735// Uniform or not736if (is_uniform()) {737KMP_INFORM(Uniform, env_var);738} else {739KMP_INFORM(NonUniform, env_var);740}741742// Equivalent types743KMP_FOREACH_HW_TYPE(type) {744kmp_hw_t eq_type = equivalent[type];745if (eq_type != KMP_HW_UNKNOWN && eq_type != type) {746KMP_INFORM(AffEqualTopologyTypes, env_var,747__kmp_hw_get_catalog_string(type),748__kmp_hw_get_catalog_string(eq_type));749}750}751752// Quick topology753KMP_ASSERT(depth > 0 && depth <= (int)KMP_HW_LAST);754// Create a print types array that always guarantees printing755// the core and thread level756print_types_depth = 0;757for (int level = 0; level < depth; ++level)758print_types[print_types_depth++] = types[level];759if (equivalent[KMP_HW_CORE] != KMP_HW_CORE) {760// Force in the core level for quick topology761if (print_types[print_types_depth - 1] == KMP_HW_THREAD) {762// Force core before thread e.g., 1 socket X 2 threads/socket763// becomes 1 socket X 1 core/socket X 2 threads/socket764print_types[print_types_depth - 1] = KMP_HW_CORE;765print_types[print_types_depth++] = KMP_HW_THREAD;766} else {767print_types[print_types_depth++] = KMP_HW_CORE;768}769}770// Always put threads at very end of quick topology771if (equivalent[KMP_HW_THREAD] != KMP_HW_THREAD)772print_types[print_types_depth++] = KMP_HW_THREAD;773774__kmp_str_buf_clear(&buf);775kmp_hw_t numerator_type;776kmp_hw_t denominator_type = KMP_HW_UNKNOWN;777int core_level = get_level(KMP_HW_CORE);778int ncores = get_count(core_level);779780for (int plevel = 0, level = 0; plevel < print_types_depth; ++plevel) {781int c;782bool plural;783numerator_type = print_types[plevel];784KMP_ASSERT_VALID_HW_TYPE(numerator_type);785if (equivalent[numerator_type] != numerator_type)786c = 1;787else788c = get_ratio(level++);789plural = (c > 1);790if (plevel == 0) {791__kmp_str_buf_print(&buf, "%d %s", c,792__kmp_hw_get_catalog_string(numerator_type, plural));793} else {794__kmp_str_buf_print(&buf, " x %d %s/%s", c,795__kmp_hw_get_catalog_string(numerator_type, plural),796__kmp_hw_get_catalog_string(denominator_type));797}798denominator_type = numerator_type;799}800KMP_INFORM(TopologyGeneric, env_var, buf.str, ncores);801802// Hybrid topology information803if (__kmp_is_hybrid_cpu()) {804for (int i = 0; i < num_core_types; ++i) {805kmp_hw_core_type_t core_type = core_types[i];806kmp_hw_attr_t attr;807attr.clear();808attr.set_core_type(core_type);809int ncores = get_ncores_with_attr(attr);810if (ncores > 0) {811KMP_INFORM(TopologyHybrid, env_var, ncores,812__kmp_hw_get_core_type_string(core_type));813KMP_ASSERT(num_core_efficiencies <= KMP_HW_MAX_NUM_CORE_EFFS)814for (int eff = 0; eff < num_core_efficiencies; ++eff) {815attr.set_core_eff(eff);816int ncores_with_eff = get_ncores_with_attr(attr);817if (ncores_with_eff > 0) {818KMP_INFORM(TopologyHybridCoreEff, env_var, ncores_with_eff, eff);819}820}821}822}823}824825if (num_hw_threads <= 0) {826__kmp_str_buf_free(&buf);827return;828}829830// Full OS proc to hardware thread map831KMP_INFORM(OSProcToPhysicalThreadMap, env_var);832for (int i = 0; i < num_hw_threads; i++) {833__kmp_str_buf_clear(&buf);834for (int level = 0; level < depth; ++level) {835kmp_hw_t type = types[level];836__kmp_str_buf_print(&buf, "%s ", __kmp_hw_get_catalog_string(type));837__kmp_str_buf_print(&buf, "%d ", hw_threads[i].ids[level]);838}839if (__kmp_is_hybrid_cpu())840__kmp_str_buf_print(841&buf, "(%s)",842__kmp_hw_get_core_type_string(hw_threads[i].attrs.get_core_type()));843KMP_INFORM(OSProcMapToPack, env_var, hw_threads[i].os_id, buf.str);844}845846__kmp_str_buf_free(&buf);847}848849#if KMP_AFFINITY_SUPPORTED850void kmp_topology_t::set_granularity(kmp_affinity_t &affinity) const {851const char *env_var = __kmp_get_affinity_env_var(affinity);852// If requested hybrid CPU attributes for granularity (either OMP_PLACES or853// KMP_AFFINITY), but none exist, then reset granularity and have below method854// select a granularity and warn user.855if (!__kmp_is_hybrid_cpu()) {856if (affinity.core_attr_gran.valid) {857// OMP_PLACES with cores:<attribute> but non-hybrid arch, use cores858// instead859KMP_AFF_WARNING(860affinity, AffIgnoringNonHybrid, env_var,861__kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true));862affinity.gran = KMP_HW_CORE;863affinity.gran_levels = -1;864affinity.core_attr_gran = KMP_AFFINITY_ATTRS_UNKNOWN;865affinity.flags.core_types_gran = affinity.flags.core_effs_gran = 0;866} else if (affinity.flags.core_types_gran ||867affinity.flags.core_effs_gran) {868// OMP_PLACES=core_types|core_effs but non-hybrid, use cores instead869if (affinity.flags.omp_places) {870KMP_AFF_WARNING(871affinity, AffIgnoringNonHybrid, env_var,872__kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true));873} else {874// KMP_AFFINITY=granularity=core_type|core_eff,...875KMP_AFF_WARNING(affinity, AffGranularityBad, env_var,876"Intel(R) Hybrid Technology core attribute",877__kmp_hw_get_catalog_string(KMP_HW_CORE));878}879affinity.gran = KMP_HW_CORE;880affinity.gran_levels = -1;881affinity.core_attr_gran = KMP_AFFINITY_ATTRS_UNKNOWN;882affinity.flags.core_types_gran = affinity.flags.core_effs_gran = 0;883}884}885// Set the number of affinity granularity levels886if (affinity.gran_levels < 0) {887kmp_hw_t gran_type = get_equivalent_type(affinity.gran);888// Check if user's granularity request is valid889if (gran_type == KMP_HW_UNKNOWN) {890// First try core, then thread, then package891kmp_hw_t gran_types[3] = {KMP_HW_CORE, KMP_HW_THREAD, KMP_HW_SOCKET};892for (auto g : gran_types) {893if (get_equivalent_type(g) != KMP_HW_UNKNOWN) {894gran_type = g;895break;896}897}898KMP_ASSERT(gran_type != KMP_HW_UNKNOWN);899// Warn user what granularity setting will be used instead900KMP_AFF_WARNING(affinity, AffGranularityBad, env_var,901__kmp_hw_get_catalog_string(affinity.gran),902__kmp_hw_get_catalog_string(gran_type));903affinity.gran = gran_type;904}905#if KMP_GROUP_AFFINITY906// If more than one processor group exists, and the level of907// granularity specified by the user is too coarse, then the908// granularity must be adjusted "down" to processor group affinity909// because threads can only exist within one processor group.910// For example, if a user sets granularity=socket and there are two911// processor groups that cover a socket, then the runtime must912// restrict the granularity down to the processor group level.913if (__kmp_num_proc_groups > 1) {914int gran_depth = get_level(gran_type);915int proc_group_depth = get_level(KMP_HW_PROC_GROUP);916if (gran_depth >= 0 && proc_group_depth >= 0 &&917gran_depth < proc_group_depth) {918KMP_AFF_WARNING(affinity, AffGranTooCoarseProcGroup, env_var,919__kmp_hw_get_catalog_string(affinity.gran));920affinity.gran = gran_type = KMP_HW_PROC_GROUP;921}922}923#endif924affinity.gran_levels = 0;925for (int i = depth - 1; i >= 0 && get_type(i) != gran_type; --i)926affinity.gran_levels++;927}928}929#endif930931void kmp_topology_t::canonicalize() {932#if KMP_GROUP_AFFINITY933_insert_windows_proc_groups();934#endif935_remove_radix1_layers();936_gather_enumeration_information();937_discover_uniformity();938_set_sub_ids();939_set_globals();940_set_last_level_cache();941942#if KMP_MIC_SUPPORTED943// Manually Add L2 = Tile equivalence944if (__kmp_mic_type == mic3) {945if (get_level(KMP_HW_L2) != -1)946set_equivalent_type(KMP_HW_TILE, KMP_HW_L2);947else if (get_level(KMP_HW_TILE) != -1)948set_equivalent_type(KMP_HW_L2, KMP_HW_TILE);949}950#endif951952// Perform post canonicalization checking953KMP_ASSERT(depth > 0);954for (int level = 0; level < depth; ++level) {955// All counts, ratios, and types must be valid956KMP_ASSERT(count[level] > 0 && ratio[level] > 0);957KMP_ASSERT_VALID_HW_TYPE(types[level]);958// Detected types must point to themselves959KMP_ASSERT(equivalent[types[level]] == types[level]);960}961}962963// Canonicalize an explicit packages X cores/pkg X threads/core topology964void kmp_topology_t::canonicalize(int npackages, int ncores_per_pkg,965int nthreads_per_core, int ncores) {966int ndepth = 3;967depth = ndepth;968KMP_FOREACH_HW_TYPE(i) { equivalent[i] = KMP_HW_UNKNOWN; }969for (int level = 0; level < depth; ++level) {970count[level] = 0;971ratio[level] = 0;972}973count[0] = npackages;974count[1] = ncores;975count[2] = __kmp_xproc;976ratio[0] = npackages;977ratio[1] = ncores_per_pkg;978ratio[2] = nthreads_per_core;979equivalent[KMP_HW_SOCKET] = KMP_HW_SOCKET;980equivalent[KMP_HW_CORE] = KMP_HW_CORE;981equivalent[KMP_HW_THREAD] = KMP_HW_THREAD;982types[0] = KMP_HW_SOCKET;983types[1] = KMP_HW_CORE;984types[2] = KMP_HW_THREAD;985//__kmp_avail_proc = __kmp_xproc;986_discover_uniformity();987}988989#if KMP_AFFINITY_SUPPORTED990static kmp_str_buf_t *991__kmp_hw_get_catalog_core_string(const kmp_hw_attr_t &attr, kmp_str_buf_t *buf,992bool plural) {993__kmp_str_buf_init(buf);994if (attr.is_core_type_valid())995__kmp_str_buf_print(buf, "%s %s",996__kmp_hw_get_core_type_string(attr.get_core_type()),997__kmp_hw_get_catalog_string(KMP_HW_CORE, plural));998else999__kmp_str_buf_print(buf, "%s eff=%d",1000__kmp_hw_get_catalog_string(KMP_HW_CORE, plural),1001attr.get_core_eff());1002return buf;1003}10041005bool kmp_topology_t::restrict_to_mask(const kmp_affin_mask_t *mask) {1006// Apply the filter1007bool affected;1008int new_index = 0;1009for (int i = 0; i < num_hw_threads; ++i) {1010int os_id = hw_threads[i].os_id;1011if (KMP_CPU_ISSET(os_id, mask)) {1012if (i != new_index)1013hw_threads[new_index] = hw_threads[i];1014new_index++;1015} else {1016KMP_CPU_CLR(os_id, __kmp_affin_fullMask);1017__kmp_avail_proc--;1018}1019}10201021KMP_DEBUG_ASSERT(new_index <= num_hw_threads);1022affected = (num_hw_threads != new_index);1023num_hw_threads = new_index;10241025// Post hardware subset canonicalization1026if (affected) {1027_gather_enumeration_information();1028_discover_uniformity();1029_set_globals();1030_set_last_level_cache();1031#if KMP_OS_WINDOWS1032// Copy filtered full mask if topology has single processor group1033if (__kmp_num_proc_groups <= 1)1034#endif1035__kmp_affin_origMask->copy(__kmp_affin_fullMask);1036}1037return affected;1038}10391040// Apply the KMP_HW_SUBSET envirable to the topology1041// Returns true if KMP_HW_SUBSET filtered any processors1042// otherwise, returns false1043bool kmp_topology_t::filter_hw_subset() {1044// If KMP_HW_SUBSET wasn't requested, then do nothing.1045if (!__kmp_hw_subset)1046return false;10471048// First, sort the KMP_HW_SUBSET items by the machine topology1049__kmp_hw_subset->sort();10501051__kmp_hw_subset->canonicalize(__kmp_topology);10521053// Check to see if KMP_HW_SUBSET is a valid subset of the detected topology1054bool using_core_types = false;1055bool using_core_effs = false;1056bool is_absolute = __kmp_hw_subset->is_absolute();1057int hw_subset_depth = __kmp_hw_subset->get_depth();1058kmp_hw_t specified[KMP_HW_LAST];1059int *topology_levels = (int *)KMP_ALLOCA(sizeof(int) * hw_subset_depth);1060KMP_ASSERT(hw_subset_depth > 0);1061KMP_FOREACH_HW_TYPE(i) { specified[i] = KMP_HW_UNKNOWN; }1062int core_level = get_level(KMP_HW_CORE);1063for (int i = 0; i < hw_subset_depth; ++i) {1064int max_count;1065const kmp_hw_subset_t::item_t &item = __kmp_hw_subset->at(i);1066int num = item.num[0];1067int offset = item.offset[0];1068kmp_hw_t type = item.type;1069kmp_hw_t equivalent_type = equivalent[type];1070int level = get_level(type);1071topology_levels[i] = level;10721073// Check to see if current layer is in detected machine topology1074if (equivalent_type != KMP_HW_UNKNOWN) {1075__kmp_hw_subset->at(i).type = equivalent_type;1076} else {1077KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetNotExistGeneric,1078__kmp_hw_get_catalog_string(type));1079return false;1080}10811082// Check to see if current layer has already been1083// specified either directly or through an equivalent type1084if (specified[equivalent_type] != KMP_HW_UNKNOWN) {1085KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetEqvLayers,1086__kmp_hw_get_catalog_string(type),1087__kmp_hw_get_catalog_string(specified[equivalent_type]));1088return false;1089}1090specified[equivalent_type] = type;10911092// Check to see if each layer's num & offset parameters are valid1093max_count = get_ratio(level);1094if (!is_absolute) {1095if (max_count < 0 ||1096(num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {1097bool plural = (num > 1);1098KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetManyGeneric,1099__kmp_hw_get_catalog_string(type, plural));1100return false;1101}1102}11031104// Check to see if core attributes are consistent1105if (core_level == level) {1106// Determine which core attributes are specified1107for (int j = 0; j < item.num_attrs; ++j) {1108if (item.attr[j].is_core_type_valid())1109using_core_types = true;1110if (item.attr[j].is_core_eff_valid())1111using_core_effs = true;1112}11131114// Check if using a single core attribute on non-hybrid arch.1115// Do not ignore all of KMP_HW_SUBSET, just ignore the attribute.1116//1117// Check if using multiple core attributes on non-hyrbid arch.1118// Ignore all of KMP_HW_SUBSET if this is the case.1119if ((using_core_effs || using_core_types) && !__kmp_is_hybrid_cpu()) {1120if (item.num_attrs == 1) {1121if (using_core_effs) {1122KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIgnoringAttr,1123"efficiency");1124} else {1125KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIgnoringAttr,1126"core_type");1127}1128using_core_effs = false;1129using_core_types = false;1130} else {1131KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAttrsNonHybrid);1132return false;1133}1134}11351136// Check if using both core types and core efficiencies together1137if (using_core_types && using_core_effs) {1138KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIncompat, "core_type",1139"efficiency");1140return false;1141}11421143// Check that core efficiency values are valid1144if (using_core_effs) {1145for (int j = 0; j < item.num_attrs; ++j) {1146if (item.attr[j].is_core_eff_valid()) {1147int core_eff = item.attr[j].get_core_eff();1148if (core_eff < 0 || core_eff >= num_core_efficiencies) {1149kmp_str_buf_t buf;1150__kmp_str_buf_init(&buf);1151__kmp_str_buf_print(&buf, "%d", item.attr[j].get_core_eff());1152__kmp_msg(kmp_ms_warning,1153KMP_MSG(AffHWSubsetAttrInvalid, "efficiency", buf.str),1154KMP_HNT(ValidValuesRange, 0, num_core_efficiencies - 1),1155__kmp_msg_null);1156__kmp_str_buf_free(&buf);1157return false;1158}1159}1160}1161}11621163// Check that the number of requested cores with attributes is valid1164if ((using_core_types || using_core_effs) && !is_absolute) {1165for (int j = 0; j < item.num_attrs; ++j) {1166int num = item.num[j];1167int offset = item.offset[j];1168int level_above = core_level - 1;1169if (level_above >= 0) {1170max_count = get_ncores_with_attr_per(item.attr[j], level_above);1171if (max_count <= 0 ||1172(num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {1173kmp_str_buf_t buf;1174__kmp_hw_get_catalog_core_string(item.attr[j], &buf, num > 0);1175KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetManyGeneric, buf.str);1176__kmp_str_buf_free(&buf);1177return false;1178}1179}1180}1181}11821183if ((using_core_types || using_core_effs) && item.num_attrs > 1) {1184for (int j = 0; j < item.num_attrs; ++j) {1185// Ambiguous use of specific core attribute + generic core1186// e.g., 4c & 3c:intel_core or 4c & 3c:eff11187if (!item.attr[j]) {1188kmp_hw_attr_t other_attr;1189for (int k = 0; k < item.num_attrs; ++k) {1190if (item.attr[k] != item.attr[j]) {1191other_attr = item.attr[k];1192break;1193}1194}1195kmp_str_buf_t buf;1196__kmp_hw_get_catalog_core_string(other_attr, &buf, item.num[j] > 0);1197KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetIncompat,1198__kmp_hw_get_catalog_string(KMP_HW_CORE), buf.str);1199__kmp_str_buf_free(&buf);1200return false;1201}1202// Allow specifying a specific core type or core eff exactly once1203for (int k = 0; k < j; ++k) {1204if (!item.attr[j] || !item.attr[k])1205continue;1206if (item.attr[k] == item.attr[j]) {1207kmp_str_buf_t buf;1208__kmp_hw_get_catalog_core_string(item.attr[j], &buf,1209item.num[j] > 0);1210KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAttrRepeat, buf.str);1211__kmp_str_buf_free(&buf);1212return false;1213}1214}1215}1216}1217}1218}12191220// For keeping track of sub_ids for an absolute KMP_HW_SUBSET1221// or core attributes (core type or efficiency)1222int prev_sub_ids[KMP_HW_LAST];1223int abs_sub_ids[KMP_HW_LAST];1224int core_eff_sub_ids[KMP_HW_MAX_NUM_CORE_EFFS];1225int core_type_sub_ids[KMP_HW_MAX_NUM_CORE_TYPES];1226for (size_t i = 0; i < KMP_HW_LAST; ++i) {1227abs_sub_ids[i] = -1;1228prev_sub_ids[i] = -1;1229}1230for (size_t i = 0; i < KMP_HW_MAX_NUM_CORE_EFFS; ++i)1231core_eff_sub_ids[i] = -1;1232for (size_t i = 0; i < KMP_HW_MAX_NUM_CORE_TYPES; ++i)1233core_type_sub_ids[i] = -1;12341235// Determine which hardware threads should be filtered.12361237// Helpful to determine if a topology layer is targeted by an absolute subset1238auto is_targeted = [&](int level) {1239if (is_absolute) {1240for (int i = 0; i < hw_subset_depth; ++i)1241if (topology_levels[i] == level)1242return true;1243return false;1244}1245// If not absolute KMP_HW_SUBSET, then every layer is seen as targeted1246return true;1247};12481249// Helpful to index into core type sub Ids array1250auto get_core_type_index = [](const kmp_hw_thread_t &t) {1251switch (t.attrs.get_core_type()) {1252case KMP_HW_CORE_TYPE_UNKNOWN:1253case KMP_HW_MAX_NUM_CORE_TYPES:1254return 0;1255#if KMP_ARCH_X86 || KMP_ARCH_X86_641256case KMP_HW_CORE_TYPE_ATOM:1257return 1;1258case KMP_HW_CORE_TYPE_CORE:1259return 2;1260#endif1261}1262KMP_ASSERT2(false, "Unhandled kmp_hw_thread_t enumeration");1263KMP_BUILTIN_UNREACHABLE;1264};12651266// Helpful to index into core efficiencies sub Ids array1267auto get_core_eff_index = [](const kmp_hw_thread_t &t) {1268return t.attrs.get_core_eff();1269};12701271int num_filtered = 0;1272kmp_affin_mask_t *filtered_mask;1273KMP_CPU_ALLOC(filtered_mask);1274KMP_CPU_COPY(filtered_mask, __kmp_affin_fullMask);1275for (int i = 0; i < num_hw_threads; ++i) {1276kmp_hw_thread_t &hw_thread = hw_threads[i];12771278// Figure out the absolute sub ids and core eff/type sub ids1279if (is_absolute || using_core_effs || using_core_types) {1280for (int level = 0; level < get_depth(); ++level) {1281if (hw_thread.sub_ids[level] != prev_sub_ids[level]) {1282bool found_targeted = false;1283for (int j = level; j < get_depth(); ++j) {1284bool targeted = is_targeted(j);1285if (!found_targeted && targeted) {1286found_targeted = true;1287abs_sub_ids[j]++;1288if (j == core_level && using_core_effs)1289core_eff_sub_ids[get_core_eff_index(hw_thread)]++;1290if (j == core_level && using_core_types)1291core_type_sub_ids[get_core_type_index(hw_thread)]++;1292} else if (targeted) {1293abs_sub_ids[j] = 0;1294if (j == core_level && using_core_effs)1295core_eff_sub_ids[get_core_eff_index(hw_thread)] = 0;1296if (j == core_level && using_core_types)1297core_type_sub_ids[get_core_type_index(hw_thread)] = 0;1298}1299}1300break;1301}1302}1303for (int level = 0; level < get_depth(); ++level)1304prev_sub_ids[level] = hw_thread.sub_ids[level];1305}13061307// Check to see if this hardware thread should be filtered1308bool should_be_filtered = false;1309for (int hw_subset_index = 0; hw_subset_index < hw_subset_depth;1310++hw_subset_index) {1311const auto &hw_subset_item = __kmp_hw_subset->at(hw_subset_index);1312int level = topology_levels[hw_subset_index];1313if (level == -1)1314continue;1315if ((using_core_effs || using_core_types) && level == core_level) {1316// Look for the core attribute in KMP_HW_SUBSET which corresponds1317// to this hardware thread's core attribute. Use this num,offset plus1318// the running sub_id for the particular core attribute of this hardware1319// thread to determine if the hardware thread should be filtered or not.1320int attr_idx;1321kmp_hw_core_type_t core_type = hw_thread.attrs.get_core_type();1322int core_eff = hw_thread.attrs.get_core_eff();1323for (attr_idx = 0; attr_idx < hw_subset_item.num_attrs; ++attr_idx) {1324if (using_core_types &&1325hw_subset_item.attr[attr_idx].get_core_type() == core_type)1326break;1327if (using_core_effs &&1328hw_subset_item.attr[attr_idx].get_core_eff() == core_eff)1329break;1330}1331// This core attribute isn't in the KMP_HW_SUBSET so always filter it.1332if (attr_idx == hw_subset_item.num_attrs) {1333should_be_filtered = true;1334break;1335}1336int sub_id;1337int num = hw_subset_item.num[attr_idx];1338int offset = hw_subset_item.offset[attr_idx];1339if (using_core_types)1340sub_id = core_type_sub_ids[get_core_type_index(hw_thread)];1341else1342sub_id = core_eff_sub_ids[get_core_eff_index(hw_thread)];1343if (sub_id < offset ||1344(num != kmp_hw_subset_t::USE_ALL && sub_id >= offset + num)) {1345should_be_filtered = true;1346break;1347}1348} else {1349int sub_id;1350int num = hw_subset_item.num[0];1351int offset = hw_subset_item.offset[0];1352if (is_absolute)1353sub_id = abs_sub_ids[level];1354else1355sub_id = hw_thread.sub_ids[level];1356if (sub_id < offset ||1357(num != kmp_hw_subset_t::USE_ALL && sub_id >= offset + num)) {1358should_be_filtered = true;1359break;1360}1361}1362}1363// Collect filtering information1364if (should_be_filtered) {1365KMP_CPU_CLR(hw_thread.os_id, filtered_mask);1366num_filtered++;1367}1368}13691370// One last check that we shouldn't allow filtering entire machine1371if (num_filtered == num_hw_threads) {1372KMP_AFF_WARNING(__kmp_affinity, AffHWSubsetAllFiltered);1373return false;1374}13751376// Apply the filter1377restrict_to_mask(filtered_mask);1378return true;1379}13801381bool kmp_topology_t::is_close(int hwt1, int hwt2,1382const kmp_affinity_t &stgs) const {1383int hw_level = stgs.gran_levels;1384if (hw_level >= depth)1385return true;1386bool retval = true;1387const kmp_hw_thread_t &t1 = hw_threads[hwt1];1388const kmp_hw_thread_t &t2 = hw_threads[hwt2];1389if (stgs.flags.core_types_gran)1390return t1.attrs.get_core_type() == t2.attrs.get_core_type();1391if (stgs.flags.core_effs_gran)1392return t1.attrs.get_core_eff() == t2.attrs.get_core_eff();1393for (int i = 0; i < (depth - hw_level); ++i) {1394if (t1.ids[i] != t2.ids[i])1395return false;1396}1397return retval;1398}13991400////////////////////////////////////////////////////////////////////////////////14011402bool KMPAffinity::picked_api = false;14031404void *KMPAffinity::Mask::operator new(size_t n) { return __kmp_allocate(n); }1405void *KMPAffinity::Mask::operator new[](size_t n) { return __kmp_allocate(n); }1406void KMPAffinity::Mask::operator delete(void *p) { __kmp_free(p); }1407void KMPAffinity::Mask::operator delete[](void *p) { __kmp_free(p); }1408void *KMPAffinity::operator new(size_t n) { return __kmp_allocate(n); }1409void KMPAffinity::operator delete(void *p) { __kmp_free(p); }14101411void KMPAffinity::pick_api() {1412KMPAffinity *affinity_dispatch;1413if (picked_api)1414return;1415#if KMP_USE_HWLOC1416// Only use Hwloc if affinity isn't explicitly disabled and1417// user requests Hwloc topology method1418if (__kmp_affinity_top_method == affinity_top_method_hwloc &&1419__kmp_affinity.type != affinity_disabled) {1420affinity_dispatch = new KMPHwlocAffinity();1421} else1422#endif1423{1424affinity_dispatch = new KMPNativeAffinity();1425}1426__kmp_affinity_dispatch = affinity_dispatch;1427picked_api = true;1428}14291430void KMPAffinity::destroy_api() {1431if (__kmp_affinity_dispatch != NULL) {1432delete __kmp_affinity_dispatch;1433__kmp_affinity_dispatch = NULL;1434picked_api = false;1435}1436}14371438#define KMP_ADVANCE_SCAN(scan) \1439while (*scan != '\0') { \1440scan++; \1441}14421443// Print the affinity mask to the character array in a pretty format.1444// The format is a comma separated list of non-negative integers or integer1445// ranges: e.g., 1,2,3-5,7,9-151446// The format can also be the string "{<empty>}" if no bits are set in mask1447char *__kmp_affinity_print_mask(char *buf, int buf_len,1448kmp_affin_mask_t *mask) {1449int start = 0, finish = 0, previous = 0;1450bool first_range;1451KMP_ASSERT(buf);1452KMP_ASSERT(buf_len >= 40);1453KMP_ASSERT(mask);1454char *scan = buf;1455char *end = buf + buf_len - 1;14561457// Check for empty set.1458if (mask->begin() == mask->end()) {1459KMP_SNPRINTF(scan, end - scan + 1, "{<empty>}");1460KMP_ADVANCE_SCAN(scan);1461KMP_ASSERT(scan <= end);1462return buf;1463}14641465first_range = true;1466start = mask->begin();1467while (1) {1468// Find next range1469// [start, previous] is inclusive range of contiguous bits in mask1470for (finish = mask->next(start), previous = start;1471finish == previous + 1 && finish != mask->end();1472finish = mask->next(finish)) {1473previous = finish;1474}14751476// The first range does not need a comma printed before it, but the rest1477// of the ranges do need a comma beforehand1478if (!first_range) {1479KMP_SNPRINTF(scan, end - scan + 1, "%s", ",");1480KMP_ADVANCE_SCAN(scan);1481} else {1482first_range = false;1483}1484// Range with three or more contiguous bits in the affinity mask1485if (previous - start > 1) {1486KMP_SNPRINTF(scan, end - scan + 1, "%u-%u", start, previous);1487} else {1488// Range with one or two contiguous bits in the affinity mask1489KMP_SNPRINTF(scan, end - scan + 1, "%u", start);1490KMP_ADVANCE_SCAN(scan);1491if (previous - start > 0) {1492KMP_SNPRINTF(scan, end - scan + 1, ",%u", previous);1493}1494}1495KMP_ADVANCE_SCAN(scan);1496// Start over with new start point1497start = finish;1498if (start == mask->end())1499break;1500// Check for overflow1501if (end - scan < 2)1502break;1503}15041505// Check for overflow1506KMP_ASSERT(scan <= end);1507return buf;1508}1509#undef KMP_ADVANCE_SCAN15101511// Print the affinity mask to the string buffer object in a pretty format1512// The format is a comma separated list of non-negative integers or integer1513// ranges: e.g., 1,2,3-5,7,9-151514// The format can also be the string "{<empty>}" if no bits are set in mask1515kmp_str_buf_t *__kmp_affinity_str_buf_mask(kmp_str_buf_t *buf,1516kmp_affin_mask_t *mask) {1517int start = 0, finish = 0, previous = 0;1518bool first_range;1519KMP_ASSERT(buf);1520KMP_ASSERT(mask);15211522__kmp_str_buf_clear(buf);15231524// Check for empty set.1525if (mask->begin() == mask->end()) {1526__kmp_str_buf_print(buf, "%s", "{<empty>}");1527return buf;1528}15291530first_range = true;1531start = mask->begin();1532while (1) {1533// Find next range1534// [start, previous] is inclusive range of contiguous bits in mask1535for (finish = mask->next(start), previous = start;1536finish == previous + 1 && finish != mask->end();1537finish = mask->next(finish)) {1538previous = finish;1539}15401541// The first range does not need a comma printed before it, but the rest1542// of the ranges do need a comma beforehand1543if (!first_range) {1544__kmp_str_buf_print(buf, "%s", ",");1545} else {1546first_range = false;1547}1548// Range with three or more contiguous bits in the affinity mask1549if (previous - start > 1) {1550__kmp_str_buf_print(buf, "%u-%u", start, previous);1551} else {1552// Range with one or two contiguous bits in the affinity mask1553__kmp_str_buf_print(buf, "%u", start);1554if (previous - start > 0) {1555__kmp_str_buf_print(buf, ",%u", previous);1556}1557}1558// Start over with new start point1559start = finish;1560if (start == mask->end())1561break;1562}1563return buf;1564}15651566// Return (possibly empty) affinity mask representing the offline CPUs1567// Caller must free the mask1568kmp_affin_mask_t *__kmp_affinity_get_offline_cpus() {1569kmp_affin_mask_t *offline;1570KMP_CPU_ALLOC(offline);1571KMP_CPU_ZERO(offline);1572#if KMP_OS_LINUX1573int n, begin_cpu, end_cpu;1574kmp_safe_raii_file_t offline_file;1575auto skip_ws = [](FILE *f) {1576int c;1577do {1578c = fgetc(f);1579} while (isspace(c));1580if (c != EOF)1581ungetc(c, f);1582};1583// File contains CSV of integer ranges representing the offline CPUs1584// e.g., 1,2,4-7,9,11-151585int status = offline_file.try_open("/sys/devices/system/cpu/offline", "r");1586if (status != 0)1587return offline;1588while (!feof(offline_file)) {1589skip_ws(offline_file);1590n = fscanf(offline_file, "%d", &begin_cpu);1591if (n != 1)1592break;1593skip_ws(offline_file);1594int c = fgetc(offline_file);1595if (c == EOF || c == ',') {1596// Just single CPU1597end_cpu = begin_cpu;1598} else if (c == '-') {1599// Range of CPUs1600skip_ws(offline_file);1601n = fscanf(offline_file, "%d", &end_cpu);1602if (n != 1)1603break;1604skip_ws(offline_file);1605c = fgetc(offline_file); // skip ','1606} else {1607// Syntax problem1608break;1609}1610// Ensure a valid range of CPUs1611if (begin_cpu < 0 || begin_cpu >= __kmp_xproc || end_cpu < 0 ||1612end_cpu >= __kmp_xproc || begin_cpu > end_cpu) {1613continue;1614}1615// Insert [begin_cpu, end_cpu] into offline mask1616for (int cpu = begin_cpu; cpu <= end_cpu; ++cpu) {1617KMP_CPU_SET(cpu, offline);1618}1619}1620#endif1621return offline;1622}16231624// Return the number of available procs1625int __kmp_affinity_entire_machine_mask(kmp_affin_mask_t *mask) {1626int avail_proc = 0;1627KMP_CPU_ZERO(mask);16281629#if KMP_GROUP_AFFINITY16301631if (__kmp_num_proc_groups > 1) {1632int group;1633KMP_DEBUG_ASSERT(__kmp_GetActiveProcessorCount != NULL);1634for (group = 0; group < __kmp_num_proc_groups; group++) {1635int i;1636int num = __kmp_GetActiveProcessorCount(group);1637for (i = 0; i < num; i++) {1638KMP_CPU_SET(i + group * (CHAR_BIT * sizeof(DWORD_PTR)), mask);1639avail_proc++;1640}1641}1642} else16431644#endif /* KMP_GROUP_AFFINITY */16451646{1647int proc;1648kmp_affin_mask_t *offline_cpus = __kmp_affinity_get_offline_cpus();1649for (proc = 0; proc < __kmp_xproc; proc++) {1650// Skip offline CPUs1651if (KMP_CPU_ISSET(proc, offline_cpus))1652continue;1653KMP_CPU_SET(proc, mask);1654avail_proc++;1655}1656KMP_CPU_FREE(offline_cpus);1657}16581659return avail_proc;1660}16611662// All of the __kmp_affinity_create_*_map() routines should allocate the1663// internal topology object and set the layer ids for it. Each routine1664// returns a boolean on whether it was successful at doing so.1665kmp_affin_mask_t *__kmp_affin_fullMask = NULL;1666// Original mask is a subset of full mask in multiple processor groups topology1667kmp_affin_mask_t *__kmp_affin_origMask = NULL;16681669#if KMP_USE_HWLOC1670static inline bool __kmp_hwloc_is_cache_type(hwloc_obj_t obj) {1671#if HWLOC_API_VERSION >= 0x000200001672return hwloc_obj_type_is_cache(obj->type);1673#else1674return obj->type == HWLOC_OBJ_CACHE;1675#endif1676}16771678// Returns KMP_HW_* type derived from HWLOC_* type1679static inline kmp_hw_t __kmp_hwloc_type_2_topology_type(hwloc_obj_t obj) {16801681if (__kmp_hwloc_is_cache_type(obj)) {1682if (obj->attr->cache.type == HWLOC_OBJ_CACHE_INSTRUCTION)1683return KMP_HW_UNKNOWN;1684switch (obj->attr->cache.depth) {1685case 1:1686return KMP_HW_L1;1687case 2:1688#if KMP_MIC_SUPPORTED1689if (__kmp_mic_type == mic3) {1690return KMP_HW_TILE;1691}1692#endif1693return KMP_HW_L2;1694case 3:1695return KMP_HW_L3;1696}1697return KMP_HW_UNKNOWN;1698}16991700switch (obj->type) {1701case HWLOC_OBJ_PACKAGE:1702return KMP_HW_SOCKET;1703case HWLOC_OBJ_NUMANODE:1704return KMP_HW_NUMA;1705case HWLOC_OBJ_CORE:1706return KMP_HW_CORE;1707case HWLOC_OBJ_PU:1708return KMP_HW_THREAD;1709case HWLOC_OBJ_GROUP:1710#if HWLOC_API_VERSION >= 0x000200001711if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_DIE)1712return KMP_HW_DIE;1713else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_TILE)1714return KMP_HW_TILE;1715else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_MODULE)1716return KMP_HW_MODULE;1717else if (obj->attr->group.kind == HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP)1718return KMP_HW_PROC_GROUP;1719#endif1720return KMP_HW_UNKNOWN;1721#if HWLOC_API_VERSION >= 0x000201001722case HWLOC_OBJ_DIE:1723return KMP_HW_DIE;1724#endif1725}1726return KMP_HW_UNKNOWN;1727}17281729// Returns the number of objects of type 'type' below 'obj' within the topology1730// tree structure. e.g., if obj is a HWLOC_OBJ_PACKAGE object, and type is1731// HWLOC_OBJ_PU, then this will return the number of PU's under the SOCKET1732// object.1733static int __kmp_hwloc_get_nobjs_under_obj(hwloc_obj_t obj,1734hwloc_obj_type_t type) {1735int retval = 0;1736hwloc_obj_t first;1737for (first = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, obj->type,1738obj->logical_index, type, 0);1739first != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology,1740obj->type, first) == obj;1741first = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, first->type,1742first)) {1743++retval;1744}1745return retval;1746}17471748// This gets the sub_id for a lower object under a higher object in the1749// topology tree1750static int __kmp_hwloc_get_sub_id(hwloc_topology_t t, hwloc_obj_t higher,1751hwloc_obj_t lower) {1752hwloc_obj_t obj;1753hwloc_obj_type_t ltype = lower->type;1754int lindex = lower->logical_index - 1;1755int sub_id = 0;1756// Get the previous lower object1757obj = hwloc_get_obj_by_type(t, ltype, lindex);1758while (obj && lindex >= 0 &&1759hwloc_bitmap_isincluded(obj->cpuset, higher->cpuset)) {1760if (obj->userdata) {1761sub_id = (int)(RCAST(kmp_intptr_t, obj->userdata));1762break;1763}1764sub_id++;1765lindex--;1766obj = hwloc_get_obj_by_type(t, ltype, lindex);1767}1768// store sub_id + 1 so that 0 is differed from NULL1769lower->userdata = RCAST(void *, sub_id + 1);1770return sub_id;1771}17721773static bool __kmp_affinity_create_hwloc_map(kmp_i18n_id_t *const msg_id) {1774kmp_hw_t type;1775int hw_thread_index, sub_id;1776int depth;1777hwloc_obj_t pu, obj, root, prev;1778kmp_hw_t types[KMP_HW_LAST];1779hwloc_obj_type_t hwloc_types[KMP_HW_LAST];17801781hwloc_topology_t tp = __kmp_hwloc_topology;1782*msg_id = kmp_i18n_null;1783if (__kmp_affinity.flags.verbose) {1784KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");1785}17861787if (!KMP_AFFINITY_CAPABLE()) {1788// Hack to try and infer the machine topology using only the data1789// available from hwloc on the current thread, and __kmp_xproc.1790KMP_ASSERT(__kmp_affinity.type == affinity_none);1791// hwloc only guarantees existance of PU object, so check PACKAGE and CORE1792hwloc_obj_t o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_PACKAGE, 0);1793if (o != NULL)1794nCoresPerPkg = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_CORE);1795else1796nCoresPerPkg = 1; // no PACKAGE found1797o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_CORE, 0);1798if (o != NULL)1799__kmp_nThreadsPerCore = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_PU);1800else1801__kmp_nThreadsPerCore = 1; // no CORE found1802if (__kmp_nThreadsPerCore == 0)1803__kmp_nThreadsPerCore = 1;1804__kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;1805if (nCoresPerPkg == 0)1806nCoresPerPkg = 1; // to prevent possible division by 01807nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;1808return true;1809}18101811#if HWLOC_API_VERSION >= 0x000204001812// Handle multiple types of cores if they exist on the system1813int nr_cpu_kinds = hwloc_cpukinds_get_nr(tp, 0);18141815typedef struct kmp_hwloc_cpukinds_info_t {1816int efficiency;1817kmp_hw_core_type_t core_type;1818hwloc_bitmap_t mask;1819} kmp_hwloc_cpukinds_info_t;1820kmp_hwloc_cpukinds_info_t *cpukinds = nullptr;18211822if (nr_cpu_kinds > 0) {1823unsigned nr_infos;1824struct hwloc_info_s *infos;1825cpukinds = (kmp_hwloc_cpukinds_info_t *)__kmp_allocate(1826sizeof(kmp_hwloc_cpukinds_info_t) * nr_cpu_kinds);1827for (unsigned idx = 0; idx < (unsigned)nr_cpu_kinds; ++idx) {1828cpukinds[idx].efficiency = -1;1829cpukinds[idx].core_type = KMP_HW_CORE_TYPE_UNKNOWN;1830cpukinds[idx].mask = hwloc_bitmap_alloc();1831if (hwloc_cpukinds_get_info(tp, idx, cpukinds[idx].mask,1832&cpukinds[idx].efficiency, &nr_infos, &infos,18330) == 0) {1834for (unsigned i = 0; i < nr_infos; ++i) {1835if (__kmp_str_match("CoreType", 8, infos[i].name)) {1836#if KMP_ARCH_X86 || KMP_ARCH_X86_641837if (__kmp_str_match("IntelAtom", 9, infos[i].value)) {1838cpukinds[idx].core_type = KMP_HW_CORE_TYPE_ATOM;1839break;1840} else if (__kmp_str_match("IntelCore", 9, infos[i].value)) {1841cpukinds[idx].core_type = KMP_HW_CORE_TYPE_CORE;1842break;1843}1844#endif1845}1846}1847}1848}1849}1850#endif18511852root = hwloc_get_root_obj(tp);18531854// Figure out the depth and types in the topology1855depth = 0;1856obj = hwloc_get_pu_obj_by_os_index(tp, __kmp_affin_fullMask->begin());1857while (obj && obj != root) {1858#if HWLOC_API_VERSION >= 0x000200001859if (obj->memory_arity) {1860hwloc_obj_t memory;1861for (memory = obj->memory_first_child; memory;1862memory = hwloc_get_next_child(tp, obj, memory)) {1863if (memory->type == HWLOC_OBJ_NUMANODE)1864break;1865}1866if (memory && memory->type == HWLOC_OBJ_NUMANODE) {1867types[depth] = KMP_HW_NUMA;1868hwloc_types[depth] = memory->type;1869depth++;1870}1871}1872#endif1873type = __kmp_hwloc_type_2_topology_type(obj);1874if (type != KMP_HW_UNKNOWN) {1875types[depth] = type;1876hwloc_types[depth] = obj->type;1877depth++;1878}1879obj = obj->parent;1880}1881KMP_ASSERT(depth > 0);18821883// Get the order for the types correct1884for (int i = 0, j = depth - 1; i < j; ++i, --j) {1885hwloc_obj_type_t hwloc_temp = hwloc_types[i];1886kmp_hw_t temp = types[i];1887types[i] = types[j];1888types[j] = temp;1889hwloc_types[i] = hwloc_types[j];1890hwloc_types[j] = hwloc_temp;1891}18921893// Allocate the data structure to be returned.1894__kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);18951896hw_thread_index = 0;1897pu = NULL;1898while ((pu = hwloc_get_next_obj_by_type(tp, HWLOC_OBJ_PU, pu))) {1899int index = depth - 1;1900bool included = KMP_CPU_ISSET(pu->os_index, __kmp_affin_fullMask);1901kmp_hw_thread_t &hw_thread = __kmp_topology->at(hw_thread_index);1902if (included) {1903hw_thread.clear();1904hw_thread.ids[index] = pu->logical_index;1905hw_thread.os_id = pu->os_index;1906// If multiple core types, then set that attribute for the hardware thread1907#if HWLOC_API_VERSION >= 0x000204001908if (cpukinds) {1909int cpukind_index = -1;1910for (int i = 0; i < nr_cpu_kinds; ++i) {1911if (hwloc_bitmap_isset(cpukinds[i].mask, hw_thread.os_id)) {1912cpukind_index = i;1913break;1914}1915}1916if (cpukind_index >= 0) {1917hw_thread.attrs.set_core_type(cpukinds[cpukind_index].core_type);1918hw_thread.attrs.set_core_eff(cpukinds[cpukind_index].efficiency);1919}1920}1921#endif1922index--;1923}1924obj = pu;1925prev = obj;1926while (obj != root && obj != NULL) {1927obj = obj->parent;1928#if HWLOC_API_VERSION >= 0x000200001929// NUMA Nodes are handled differently since they are not within the1930// parent/child structure anymore. They are separate children1931// of obj (memory_first_child points to first memory child)1932if (obj->memory_arity) {1933hwloc_obj_t memory;1934for (memory = obj->memory_first_child; memory;1935memory = hwloc_get_next_child(tp, obj, memory)) {1936if (memory->type == HWLOC_OBJ_NUMANODE)1937break;1938}1939if (memory && memory->type == HWLOC_OBJ_NUMANODE) {1940sub_id = __kmp_hwloc_get_sub_id(tp, memory, prev);1941if (included) {1942hw_thread.ids[index] = memory->logical_index;1943hw_thread.ids[index + 1] = sub_id;1944index--;1945}1946prev = memory;1947}1948prev = obj;1949}1950#endif1951type = __kmp_hwloc_type_2_topology_type(obj);1952if (type != KMP_HW_UNKNOWN) {1953sub_id = __kmp_hwloc_get_sub_id(tp, obj, prev);1954if (included) {1955hw_thread.ids[index] = obj->logical_index;1956hw_thread.ids[index + 1] = sub_id;1957index--;1958}1959prev = obj;1960}1961}1962if (included)1963hw_thread_index++;1964}19651966#if HWLOC_API_VERSION >= 0x000204001967// Free the core types information1968if (cpukinds) {1969for (int idx = 0; idx < nr_cpu_kinds; ++idx)1970hwloc_bitmap_free(cpukinds[idx].mask);1971__kmp_free(cpukinds);1972}1973#endif1974__kmp_topology->sort_ids();1975return true;1976}1977#endif // KMP_USE_HWLOC19781979// If we don't know how to retrieve the machine's processor topology, or1980// encounter an error in doing so, this routine is called to form a "flat"1981// mapping of os thread id's <-> processor id's.1982static bool __kmp_affinity_create_flat_map(kmp_i18n_id_t *const msg_id) {1983*msg_id = kmp_i18n_null;1984int depth = 3;1985kmp_hw_t types[] = {KMP_HW_SOCKET, KMP_HW_CORE, KMP_HW_THREAD};19861987if (__kmp_affinity.flags.verbose) {1988KMP_INFORM(UsingFlatOS, "KMP_AFFINITY");1989}19901991// Even if __kmp_affinity.type == affinity_none, this routine might still1992// be called to set __kmp_ncores, as well as1993// __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.1994if (!KMP_AFFINITY_CAPABLE()) {1995KMP_ASSERT(__kmp_affinity.type == affinity_none);1996__kmp_ncores = nPackages = __kmp_xproc;1997__kmp_nThreadsPerCore = nCoresPerPkg = 1;1998return true;1999}20002001// When affinity is off, this routine will still be called to set2002// __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.2003// Make sure all these vars are set correctly, and return now if affinity is2004// not enabled.2005__kmp_ncores = nPackages = __kmp_avail_proc;2006__kmp_nThreadsPerCore = nCoresPerPkg = 1;20072008// Construct the data structure to be returned.2009__kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);2010int avail_ct = 0;2011int i;2012KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {2013// Skip this proc if it is not included in the machine model.2014if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {2015continue;2016}2017kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct);2018hw_thread.clear();2019hw_thread.os_id = i;2020hw_thread.ids[0] = i;2021hw_thread.ids[1] = 0;2022hw_thread.ids[2] = 0;2023avail_ct++;2024}2025if (__kmp_affinity.flags.verbose) {2026KMP_INFORM(OSProcToPackage, "KMP_AFFINITY");2027}2028return true;2029}20302031#if KMP_GROUP_AFFINITY2032// If multiple Windows* OS processor groups exist, we can create a 2-level2033// topology map with the groups at level 0 and the individual procs at level 1.2034// This facilitates letting the threads float among all procs in a group,2035// if granularity=group (the default when there are multiple groups).2036static bool __kmp_affinity_create_proc_group_map(kmp_i18n_id_t *const msg_id) {2037*msg_id = kmp_i18n_null;2038int depth = 3;2039kmp_hw_t types[] = {KMP_HW_PROC_GROUP, KMP_HW_CORE, KMP_HW_THREAD};2040const static size_t BITS_PER_GROUP = CHAR_BIT * sizeof(DWORD_PTR);20412042if (__kmp_affinity.flags.verbose) {2043KMP_INFORM(AffWindowsProcGroupMap, "KMP_AFFINITY");2044}20452046// If we aren't affinity capable, then use flat topology2047if (!KMP_AFFINITY_CAPABLE()) {2048KMP_ASSERT(__kmp_affinity.type == affinity_none);2049nPackages = __kmp_num_proc_groups;2050__kmp_nThreadsPerCore = 1;2051__kmp_ncores = __kmp_xproc;2052nCoresPerPkg = nPackages / __kmp_ncores;2053return true;2054}20552056// Construct the data structure to be returned.2057__kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);2058int avail_ct = 0;2059int i;2060KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {2061// Skip this proc if it is not included in the machine model.2062if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {2063continue;2064}2065kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct++);2066hw_thread.clear();2067hw_thread.os_id = i;2068hw_thread.ids[0] = i / BITS_PER_GROUP;2069hw_thread.ids[1] = hw_thread.ids[2] = i % BITS_PER_GROUP;2070}2071return true;2072}2073#endif /* KMP_GROUP_AFFINITY */20742075#if KMP_ARCH_X86 || KMP_ARCH_X86_6420762077template <kmp_uint32 LSB, kmp_uint32 MSB>2078static inline unsigned __kmp_extract_bits(kmp_uint32 v) {2079const kmp_uint32 SHIFT_LEFT = sizeof(kmp_uint32) * 8 - 1 - MSB;2080const kmp_uint32 SHIFT_RIGHT = LSB;2081kmp_uint32 retval = v;2082retval <<= SHIFT_LEFT;2083retval >>= (SHIFT_LEFT + SHIFT_RIGHT);2084return retval;2085}20862087static int __kmp_cpuid_mask_width(int count) {2088int r = 0;20892090while ((1 << r) < count)2091++r;2092return r;2093}20942095class apicThreadInfo {2096public:2097unsigned osId; // param to __kmp_affinity_bind_thread2098unsigned apicId; // from cpuid after binding2099unsigned maxCoresPerPkg; // ""2100unsigned maxThreadsPerPkg; // ""2101unsigned pkgId; // inferred from above values2102unsigned coreId; // ""2103unsigned threadId; // ""2104};21052106static int __kmp_affinity_cmp_apicThreadInfo_phys_id(const void *a,2107const void *b) {2108const apicThreadInfo *aa = (const apicThreadInfo *)a;2109const apicThreadInfo *bb = (const apicThreadInfo *)b;2110if (aa->pkgId < bb->pkgId)2111return -1;2112if (aa->pkgId > bb->pkgId)2113return 1;2114if (aa->coreId < bb->coreId)2115return -1;2116if (aa->coreId > bb->coreId)2117return 1;2118if (aa->threadId < bb->threadId)2119return -1;2120if (aa->threadId > bb->threadId)2121return 1;2122return 0;2123}21242125class kmp_cache_info_t {2126public:2127struct info_t {2128unsigned level, mask;2129};2130kmp_cache_info_t() : depth(0) { get_leaf4_levels(); }2131size_t get_depth() const { return depth; }2132info_t &operator[](size_t index) { return table[index]; }2133const info_t &operator[](size_t index) const { return table[index]; }21342135static kmp_hw_t get_topology_type(unsigned level) {2136KMP_DEBUG_ASSERT(level >= 1 && level <= MAX_CACHE_LEVEL);2137switch (level) {2138case 1:2139return KMP_HW_L1;2140case 2:2141return KMP_HW_L2;2142case 3:2143return KMP_HW_L3;2144}2145return KMP_HW_UNKNOWN;2146}21472148private:2149static const int MAX_CACHE_LEVEL = 3;21502151size_t depth;2152info_t table[MAX_CACHE_LEVEL];21532154void get_leaf4_levels() {2155unsigned level = 0;2156while (depth < MAX_CACHE_LEVEL) {2157unsigned cache_type, max_threads_sharing;2158unsigned cache_level, cache_mask_width;2159kmp_cpuid buf2;2160__kmp_x86_cpuid(4, level, &buf2);2161cache_type = __kmp_extract_bits<0, 4>(buf2.eax);2162if (!cache_type)2163break;2164// Skip instruction caches2165if (cache_type == 2) {2166level++;2167continue;2168}2169max_threads_sharing = __kmp_extract_bits<14, 25>(buf2.eax) + 1;2170cache_mask_width = __kmp_cpuid_mask_width(max_threads_sharing);2171cache_level = __kmp_extract_bits<5, 7>(buf2.eax);2172table[depth].level = cache_level;2173table[depth].mask = ((-1) << cache_mask_width);2174depth++;2175level++;2176}2177}2178};21792180// On IA-32 architecture and Intel(R) 64 architecture, we attempt to use2181// an algorithm which cycles through the available os threads, setting2182// the current thread's affinity mask to that thread, and then retrieves2183// the Apic Id for each thread context using the cpuid instruction.2184static bool __kmp_affinity_create_apicid_map(kmp_i18n_id_t *const msg_id) {2185kmp_cpuid buf;2186*msg_id = kmp_i18n_null;21872188if (__kmp_affinity.flags.verbose) {2189KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(DecodingLegacyAPIC));2190}21912192// Check if cpuid leaf 4 is supported.2193__kmp_x86_cpuid(0, 0, &buf);2194if (buf.eax < 4) {2195*msg_id = kmp_i18n_str_NoLeaf4Support;2196return false;2197}21982199// The algorithm used starts by setting the affinity to each available thread2200// and retrieving info from the cpuid instruction, so if we are not capable of2201// calling __kmp_get_system_affinity() and _kmp_get_system_affinity(), then we2202// need to do something else - use the defaults that we calculated from2203// issuing cpuid without binding to each proc.2204if (!KMP_AFFINITY_CAPABLE()) {2205// Hack to try and infer the machine topology using only the data2206// available from cpuid on the current thread, and __kmp_xproc.2207KMP_ASSERT(__kmp_affinity.type == affinity_none);22082209// Get an upper bound on the number of threads per package using cpuid(1).2210// On some OS/chps combinations where HT is supported by the chip but is2211// disabled, this value will be 2 on a single core chip. Usually, it will be2212// 2 if HT is enabled and 1 if HT is disabled.2213__kmp_x86_cpuid(1, 0, &buf);2214int maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;2215if (maxThreadsPerPkg == 0) {2216maxThreadsPerPkg = 1;2217}22182219// The num cores per pkg comes from cpuid(4). 1 must be added to the encoded2220// value.2221//2222// The author of cpu_count.cpp treated this only an upper bound on the2223// number of cores, but I haven't seen any cases where it was greater than2224// the actual number of cores, so we will treat it as exact in this block of2225// code.2226//2227// First, we need to check if cpuid(4) is supported on this chip. To see if2228// cpuid(n) is supported, issue cpuid(0) and check if eax has the value n or2229// greater.2230__kmp_x86_cpuid(0, 0, &buf);2231if (buf.eax >= 4) {2232__kmp_x86_cpuid(4, 0, &buf);2233nCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;2234} else {2235nCoresPerPkg = 1;2236}22372238// There is no way to reliably tell if HT is enabled without issuing the2239// cpuid instruction from every thread, can correlating the cpuid info, so2240// if the machine is not affinity capable, we assume that HT is off. We have2241// seen quite a few machines where maxThreadsPerPkg is 2, yet the machine2242// does not support HT.2243//2244// - Older OSes are usually found on machines with older chips, which do not2245// support HT.2246// - The performance penalty for mistakenly identifying a machine as HT when2247// it isn't (which results in blocktime being incorrectly set to 0) is2248// greater than the penalty when for mistakenly identifying a machine as2249// being 1 thread/core when it is really HT enabled (which results in2250// blocktime being incorrectly set to a positive value).2251__kmp_ncores = __kmp_xproc;2252nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;2253__kmp_nThreadsPerCore = 1;2254return true;2255}22562257// From here on, we can assume that it is safe to call2258// __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if2259// __kmp_affinity.type = affinity_none.22602261// Save the affinity mask for the current thread.2262kmp_affinity_raii_t previous_affinity;22632264// Run through each of the available contexts, binding the current thread2265// to it, and obtaining the pertinent information using the cpuid instr.2266//2267// The relevant information is:2268// - Apic Id: Bits 24:31 of ebx after issuing cpuid(1) - each thread context2269// has a uniqie Apic Id, which is of the form pkg# : core# : thread#.2270// - Max Threads Per Pkg: Bits 16:23 of ebx after issuing cpuid(1). The value2271// of this field determines the width of the core# + thread# fields in the2272// Apic Id. It is also an upper bound on the number of threads per2273// package, but it has been verified that situations happen were it is not2274// exact. In particular, on certain OS/chip combinations where Intel(R)2275// Hyper-Threading Technology is supported by the chip but has been2276// disabled, the value of this field will be 2 (for a single core chip).2277// On other OS/chip combinations supporting Intel(R) Hyper-Threading2278// Technology, the value of this field will be 1 when Intel(R)2279// Hyper-Threading Technology is disabled and 2 when it is enabled.2280// - Max Cores Per Pkg: Bits 26:31 of eax after issuing cpuid(4). The value2281// of this field (+1) determines the width of the core# field in the Apic2282// Id. The comments in "cpucount.cpp" say that this value is an upper2283// bound, but the IA-32 architecture manual says that it is exactly the2284// number of cores per package, and I haven't seen any case where it2285// wasn't.2286//2287// From this information, deduce the package Id, core Id, and thread Id,2288// and set the corresponding fields in the apicThreadInfo struct.2289unsigned i;2290apicThreadInfo *threadInfo = (apicThreadInfo *)__kmp_allocate(2291__kmp_avail_proc * sizeof(apicThreadInfo));2292unsigned nApics = 0;2293KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {2294// Skip this proc if it is not included in the machine model.2295if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {2296continue;2297}2298KMP_DEBUG_ASSERT((int)nApics < __kmp_avail_proc);22992300__kmp_affinity_dispatch->bind_thread(i);2301threadInfo[nApics].osId = i;23022303// The apic id and max threads per pkg come from cpuid(1).2304__kmp_x86_cpuid(1, 0, &buf);2305if (((buf.edx >> 9) & 1) == 0) {2306__kmp_free(threadInfo);2307*msg_id = kmp_i18n_str_ApicNotPresent;2308return false;2309}2310threadInfo[nApics].apicId = (buf.ebx >> 24) & 0xff;2311threadInfo[nApics].maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;2312if (threadInfo[nApics].maxThreadsPerPkg == 0) {2313threadInfo[nApics].maxThreadsPerPkg = 1;2314}23152316// Max cores per pkg comes from cpuid(4). 1 must be added to the encoded2317// value.2318//2319// First, we need to check if cpuid(4) is supported on this chip. To see if2320// cpuid(n) is supported, issue cpuid(0) and check if eax has the value n2321// or greater.2322__kmp_x86_cpuid(0, 0, &buf);2323if (buf.eax >= 4) {2324__kmp_x86_cpuid(4, 0, &buf);2325threadInfo[nApics].maxCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;2326} else {2327threadInfo[nApics].maxCoresPerPkg = 1;2328}23292330// Infer the pkgId / coreId / threadId using only the info obtained locally.2331int widthCT = __kmp_cpuid_mask_width(threadInfo[nApics].maxThreadsPerPkg);2332threadInfo[nApics].pkgId = threadInfo[nApics].apicId >> widthCT;23332334int widthC = __kmp_cpuid_mask_width(threadInfo[nApics].maxCoresPerPkg);2335int widthT = widthCT - widthC;2336if (widthT < 0) {2337// I've never seen this one happen, but I suppose it could, if the cpuid2338// instruction on a chip was really screwed up. Make sure to restore the2339// affinity mask before the tail call.2340__kmp_free(threadInfo);2341*msg_id = kmp_i18n_str_InvalidCpuidInfo;2342return false;2343}23442345int maskC = (1 << widthC) - 1;2346threadInfo[nApics].coreId = (threadInfo[nApics].apicId >> widthT) & maskC;23472348int maskT = (1 << widthT) - 1;2349threadInfo[nApics].threadId = threadInfo[nApics].apicId & maskT;23502351nApics++;2352}23532354// We've collected all the info we need.2355// Restore the old affinity mask for this thread.2356previous_affinity.restore();23572358// Sort the threadInfo table by physical Id.2359qsort(threadInfo, nApics, sizeof(*threadInfo),2360__kmp_affinity_cmp_apicThreadInfo_phys_id);23612362// The table is now sorted by pkgId / coreId / threadId, but we really don't2363// know the radix of any of the fields. pkgId's may be sparsely assigned among2364// the chips on a system. Although coreId's are usually assigned2365// [0 .. coresPerPkg-1] and threadId's are usually assigned2366// [0..threadsPerCore-1], we don't want to make any such assumptions.2367//2368// For that matter, we don't know what coresPerPkg and threadsPerCore (or the2369// total # packages) are at this point - we want to determine that now. We2370// only have an upper bound on the first two figures.2371//2372// We also perform a consistency check at this point: the values returned by2373// the cpuid instruction for any thread bound to a given package had better2374// return the same info for maxThreadsPerPkg and maxCoresPerPkg.2375nPackages = 1;2376nCoresPerPkg = 1;2377__kmp_nThreadsPerCore = 1;2378unsigned nCores = 1;23792380unsigned pkgCt = 1; // to determine radii2381unsigned lastPkgId = threadInfo[0].pkgId;2382unsigned coreCt = 1;2383unsigned lastCoreId = threadInfo[0].coreId;2384unsigned threadCt = 1;2385unsigned lastThreadId = threadInfo[0].threadId;23862387// intra-pkg consist checks2388unsigned prevMaxCoresPerPkg = threadInfo[0].maxCoresPerPkg;2389unsigned prevMaxThreadsPerPkg = threadInfo[0].maxThreadsPerPkg;23902391for (i = 1; i < nApics; i++) {2392if (threadInfo[i].pkgId != lastPkgId) {2393nCores++;2394pkgCt++;2395lastPkgId = threadInfo[i].pkgId;2396if ((int)coreCt > nCoresPerPkg)2397nCoresPerPkg = coreCt;2398coreCt = 1;2399lastCoreId = threadInfo[i].coreId;2400if ((int)threadCt > __kmp_nThreadsPerCore)2401__kmp_nThreadsPerCore = threadCt;2402threadCt = 1;2403lastThreadId = threadInfo[i].threadId;24042405// This is a different package, so go on to the next iteration without2406// doing any consistency checks. Reset the consistency check vars, though.2407prevMaxCoresPerPkg = threadInfo[i].maxCoresPerPkg;2408prevMaxThreadsPerPkg = threadInfo[i].maxThreadsPerPkg;2409continue;2410}24112412if (threadInfo[i].coreId != lastCoreId) {2413nCores++;2414coreCt++;2415lastCoreId = threadInfo[i].coreId;2416if ((int)threadCt > __kmp_nThreadsPerCore)2417__kmp_nThreadsPerCore = threadCt;2418threadCt = 1;2419lastThreadId = threadInfo[i].threadId;2420} else if (threadInfo[i].threadId != lastThreadId) {2421threadCt++;2422lastThreadId = threadInfo[i].threadId;2423} else {2424__kmp_free(threadInfo);2425*msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;2426return false;2427}24282429// Check to make certain that the maxCoresPerPkg and maxThreadsPerPkg2430// fields agree between all the threads bounds to a given package.2431if ((prevMaxCoresPerPkg != threadInfo[i].maxCoresPerPkg) ||2432(prevMaxThreadsPerPkg != threadInfo[i].maxThreadsPerPkg)) {2433__kmp_free(threadInfo);2434*msg_id = kmp_i18n_str_InconsistentCpuidInfo;2435return false;2436}2437}2438// When affinity is off, this routine will still be called to set2439// __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.2440// Make sure all these vars are set correctly2441nPackages = pkgCt;2442if ((int)coreCt > nCoresPerPkg)2443nCoresPerPkg = coreCt;2444if ((int)threadCt > __kmp_nThreadsPerCore)2445__kmp_nThreadsPerCore = threadCt;2446__kmp_ncores = nCores;2447KMP_DEBUG_ASSERT(nApics == (unsigned)__kmp_avail_proc);24482449// Now that we've determined the number of packages, the number of cores per2450// package, and the number of threads per core, we can construct the data2451// structure that is to be returned.2452int idx = 0;2453int pkgLevel = 0;2454int coreLevel = 1;2455int threadLevel = 2;2456//(__kmp_nThreadsPerCore <= 1) ? -1 : ((coreLevel >= 0) ? 2 : 1);2457int depth = (pkgLevel >= 0) + (coreLevel >= 0) + (threadLevel >= 0);2458kmp_hw_t types[3];2459if (pkgLevel >= 0)2460types[idx++] = KMP_HW_SOCKET;2461if (coreLevel >= 0)2462types[idx++] = KMP_HW_CORE;2463if (threadLevel >= 0)2464types[idx++] = KMP_HW_THREAD;24652466KMP_ASSERT(depth > 0);2467__kmp_topology = kmp_topology_t::allocate(nApics, depth, types);24682469for (i = 0; i < nApics; ++i) {2470idx = 0;2471unsigned os = threadInfo[i].osId;2472kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);2473hw_thread.clear();24742475if (pkgLevel >= 0) {2476hw_thread.ids[idx++] = threadInfo[i].pkgId;2477}2478if (coreLevel >= 0) {2479hw_thread.ids[idx++] = threadInfo[i].coreId;2480}2481if (threadLevel >= 0) {2482hw_thread.ids[idx++] = threadInfo[i].threadId;2483}2484hw_thread.os_id = os;2485}24862487__kmp_free(threadInfo);2488__kmp_topology->sort_ids();2489if (!__kmp_topology->check_ids()) {2490kmp_topology_t::deallocate(__kmp_topology);2491__kmp_topology = nullptr;2492*msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;2493return false;2494}2495return true;2496}24972498// Hybrid cpu detection using CPUID.1A2499// Thread should be pinned to processor already2500static void __kmp_get_hybrid_info(kmp_hw_core_type_t *type, int *efficiency,2501unsigned *native_model_id) {2502kmp_cpuid buf;2503__kmp_x86_cpuid(0x1a, 0, &buf);2504*type = (kmp_hw_core_type_t)__kmp_extract_bits<24, 31>(buf.eax);2505switch (*type) {2506case KMP_HW_CORE_TYPE_ATOM:2507*efficiency = 0;2508break;2509case KMP_HW_CORE_TYPE_CORE:2510*efficiency = 1;2511break;2512default:2513*efficiency = 0;2514}2515*native_model_id = __kmp_extract_bits<0, 23>(buf.eax);2516}25172518// Intel(R) microarchitecture code name Nehalem, Dunnington and later2519// architectures support a newer interface for specifying the x2APIC Ids,2520// based on CPUID.B or CPUID.1F2521/*2522* CPUID.B or 1F, Input ECX (sub leaf # aka level number)2523Bits Bits Bits Bits252431-16 15-8 7-4 4-02525---+-----------+--------------+-------------+-----------------+2526EAX| reserved | reserved | reserved | Bits to Shift |2527---+-----------|--------------+-------------+-----------------|2528EBX| reserved | Num logical processors at level (16 bits) |2529---+-----------|--------------+-------------------------------|2530ECX| reserved | Level Type | Level Number (8 bits) |2531---+-----------+--------------+-------------------------------|2532EDX| X2APIC ID (32 bits) |2533---+----------------------------------------------------------+2534*/25352536enum {2537INTEL_LEVEL_TYPE_INVALID = 0, // Package level2538INTEL_LEVEL_TYPE_SMT = 1,2539INTEL_LEVEL_TYPE_CORE = 2,2540INTEL_LEVEL_TYPE_MODULE = 3,2541INTEL_LEVEL_TYPE_TILE = 4,2542INTEL_LEVEL_TYPE_DIE = 5,2543INTEL_LEVEL_TYPE_LAST = 6,2544};25452546struct cpuid_level_info_t {2547unsigned level_type, mask, mask_width, nitems, cache_mask;2548};25492550static kmp_hw_t __kmp_intel_type_2_topology_type(int intel_type) {2551switch (intel_type) {2552case INTEL_LEVEL_TYPE_INVALID:2553return KMP_HW_SOCKET;2554case INTEL_LEVEL_TYPE_SMT:2555return KMP_HW_THREAD;2556case INTEL_LEVEL_TYPE_CORE:2557return KMP_HW_CORE;2558case INTEL_LEVEL_TYPE_TILE:2559return KMP_HW_TILE;2560case INTEL_LEVEL_TYPE_MODULE:2561return KMP_HW_MODULE;2562case INTEL_LEVEL_TYPE_DIE:2563return KMP_HW_DIE;2564}2565return KMP_HW_UNKNOWN;2566}25672568// This function takes the topology leaf, a levels array to store the levels2569// detected and a bitmap of the known levels.2570// Returns the number of levels in the topology2571static unsigned2572__kmp_x2apicid_get_levels(int leaf,2573cpuid_level_info_t levels[INTEL_LEVEL_TYPE_LAST],2574kmp_uint64 known_levels) {2575unsigned level, levels_index;2576unsigned level_type, mask_width, nitems;2577kmp_cpuid buf;25782579// New algorithm has known topology layers act as highest unknown topology2580// layers when unknown topology layers exist.2581// e.g., Suppose layers were SMT <X> CORE <Y> <Z> PACKAGE, where <X> <Y> <Z>2582// are unknown topology layers, Then SMT will take the characteristics of2583// (SMT x <X>) and CORE will take the characteristics of (CORE x <Y> x <Z>).2584// This eliminates unknown portions of the topology while still keeping the2585// correct structure.2586level = levels_index = 0;2587do {2588__kmp_x86_cpuid(leaf, level, &buf);2589level_type = __kmp_extract_bits<8, 15>(buf.ecx);2590mask_width = __kmp_extract_bits<0, 4>(buf.eax);2591nitems = __kmp_extract_bits<0, 15>(buf.ebx);2592if (level_type != INTEL_LEVEL_TYPE_INVALID && nitems == 0)2593return 0;25942595if (known_levels & (1ull << level_type)) {2596// Add a new level to the topology2597KMP_ASSERT(levels_index < INTEL_LEVEL_TYPE_LAST);2598levels[levels_index].level_type = level_type;2599levels[levels_index].mask_width = mask_width;2600levels[levels_index].nitems = nitems;2601levels_index++;2602} else {2603// If it is an unknown level, then logically move the previous layer up2604if (levels_index > 0) {2605levels[levels_index - 1].mask_width = mask_width;2606levels[levels_index - 1].nitems = nitems;2607}2608}2609level++;2610} while (level_type != INTEL_LEVEL_TYPE_INVALID);26112612// Ensure the INTEL_LEVEL_TYPE_INVALID (Socket) layer isn't first2613if (levels_index == 0 || levels[0].level_type == INTEL_LEVEL_TYPE_INVALID)2614return 0;26152616// Set the masks to & with apicid2617for (unsigned i = 0; i < levels_index; ++i) {2618if (levels[i].level_type != INTEL_LEVEL_TYPE_INVALID) {2619levels[i].mask = ~((-1) << levels[i].mask_width);2620levels[i].cache_mask = (-1) << levels[i].mask_width;2621for (unsigned j = 0; j < i; ++j)2622levels[i].mask ^= levels[j].mask;2623} else {2624KMP_DEBUG_ASSERT(i > 0);2625levels[i].mask = (-1) << levels[i - 1].mask_width;2626levels[i].cache_mask = 0;2627}2628}2629return levels_index;2630}26312632static bool __kmp_affinity_create_x2apicid_map(kmp_i18n_id_t *const msg_id) {26332634cpuid_level_info_t levels[INTEL_LEVEL_TYPE_LAST];2635kmp_hw_t types[INTEL_LEVEL_TYPE_LAST];2636unsigned levels_index;2637kmp_cpuid buf;2638kmp_uint64 known_levels;2639int topology_leaf, highest_leaf, apic_id;2640int num_leaves;2641static int leaves[] = {0, 0};26422643kmp_i18n_id_t leaf_message_id;26442645KMP_BUILD_ASSERT(sizeof(known_levels) * CHAR_BIT > KMP_HW_LAST);26462647*msg_id = kmp_i18n_null;2648if (__kmp_affinity.flags.verbose) {2649KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(Decodingx2APIC));2650}26512652// Figure out the known topology levels2653known_levels = 0ull;2654for (int i = 0; i < INTEL_LEVEL_TYPE_LAST; ++i) {2655if (__kmp_intel_type_2_topology_type(i) != KMP_HW_UNKNOWN) {2656known_levels |= (1ull << i);2657}2658}26592660// Get the highest cpuid leaf supported2661__kmp_x86_cpuid(0, 0, &buf);2662highest_leaf = buf.eax;26632664// If a specific topology method was requested, only allow that specific leaf2665// otherwise, try both leaves 31 and 11 in that order2666num_leaves = 0;2667if (__kmp_affinity_top_method == affinity_top_method_x2apicid) {2668num_leaves = 1;2669leaves[0] = 11;2670leaf_message_id = kmp_i18n_str_NoLeaf11Support;2671} else if (__kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {2672num_leaves = 1;2673leaves[0] = 31;2674leaf_message_id = kmp_i18n_str_NoLeaf31Support;2675} else {2676num_leaves = 2;2677leaves[0] = 31;2678leaves[1] = 11;2679leaf_message_id = kmp_i18n_str_NoLeaf11Support;2680}26812682// Check to see if cpuid leaf 31 or 11 is supported.2683__kmp_nThreadsPerCore = nCoresPerPkg = nPackages = 1;2684topology_leaf = -1;2685for (int i = 0; i < num_leaves; ++i) {2686int leaf = leaves[i];2687if (highest_leaf < leaf)2688continue;2689__kmp_x86_cpuid(leaf, 0, &buf);2690if (buf.ebx == 0)2691continue;2692topology_leaf = leaf;2693levels_index = __kmp_x2apicid_get_levels(leaf, levels, known_levels);2694if (levels_index == 0)2695continue;2696break;2697}2698if (topology_leaf == -1 || levels_index == 0) {2699*msg_id = leaf_message_id;2700return false;2701}2702KMP_ASSERT(levels_index <= INTEL_LEVEL_TYPE_LAST);27032704// The algorithm used starts by setting the affinity to each available thread2705// and retrieving info from the cpuid instruction, so if we are not capable of2706// calling __kmp_get_system_affinity() and __kmp_get_system_affinity(), then2707// we need to do something else - use the defaults that we calculated from2708// issuing cpuid without binding to each proc.2709if (!KMP_AFFINITY_CAPABLE()) {2710// Hack to try and infer the machine topology using only the data2711// available from cpuid on the current thread, and __kmp_xproc.2712KMP_ASSERT(__kmp_affinity.type == affinity_none);2713for (unsigned i = 0; i < levels_index; ++i) {2714if (levels[i].level_type == INTEL_LEVEL_TYPE_SMT) {2715__kmp_nThreadsPerCore = levels[i].nitems;2716} else if (levels[i].level_type == INTEL_LEVEL_TYPE_CORE) {2717nCoresPerPkg = levels[i].nitems;2718}2719}2720__kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;2721nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;2722return true;2723}27242725// Allocate the data structure to be returned.2726int depth = levels_index;2727for (int i = depth - 1, j = 0; i >= 0; --i, ++j)2728types[j] = __kmp_intel_type_2_topology_type(levels[i].level_type);2729__kmp_topology =2730kmp_topology_t::allocate(__kmp_avail_proc, levels_index, types);27312732// Insert equivalent cache types if they exist2733kmp_cache_info_t cache_info;2734for (size_t i = 0; i < cache_info.get_depth(); ++i) {2735const kmp_cache_info_t::info_t &info = cache_info[i];2736unsigned cache_mask = info.mask;2737unsigned cache_level = info.level;2738for (unsigned j = 0; j < levels_index; ++j) {2739unsigned hw_cache_mask = levels[j].cache_mask;2740kmp_hw_t cache_type = kmp_cache_info_t::get_topology_type(cache_level);2741if (hw_cache_mask == cache_mask && j < levels_index - 1) {2742kmp_hw_t type =2743__kmp_intel_type_2_topology_type(levels[j + 1].level_type);2744__kmp_topology->set_equivalent_type(cache_type, type);2745}2746}2747}27482749// From here on, we can assume that it is safe to call2750// __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if2751// __kmp_affinity.type = affinity_none.27522753// Save the affinity mask for the current thread.2754kmp_affinity_raii_t previous_affinity;27552756// Run through each of the available contexts, binding the current thread2757// to it, and obtaining the pertinent information using the cpuid instr.2758unsigned int proc;2759int hw_thread_index = 0;2760KMP_CPU_SET_ITERATE(proc, __kmp_affin_fullMask) {2761cpuid_level_info_t my_levels[INTEL_LEVEL_TYPE_LAST];2762unsigned my_levels_index;27632764// Skip this proc if it is not included in the machine model.2765if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {2766continue;2767}2768KMP_DEBUG_ASSERT(hw_thread_index < __kmp_avail_proc);27692770__kmp_affinity_dispatch->bind_thread(proc);27712772// New algorithm2773__kmp_x86_cpuid(topology_leaf, 0, &buf);2774apic_id = buf.edx;2775kmp_hw_thread_t &hw_thread = __kmp_topology->at(hw_thread_index);2776my_levels_index =2777__kmp_x2apicid_get_levels(topology_leaf, my_levels, known_levels);2778if (my_levels_index == 0 || my_levels_index != levels_index) {2779*msg_id = kmp_i18n_str_InvalidCpuidInfo;2780return false;2781}2782hw_thread.clear();2783hw_thread.os_id = proc;2784// Put in topology information2785for (unsigned j = 0, idx = depth - 1; j < my_levels_index; ++j, --idx) {2786hw_thread.ids[idx] = apic_id & my_levels[j].mask;2787if (j > 0) {2788hw_thread.ids[idx] >>= my_levels[j - 1].mask_width;2789}2790}2791// Hybrid information2792if (__kmp_is_hybrid_cpu() && highest_leaf >= 0x1a) {2793kmp_hw_core_type_t type;2794unsigned native_model_id;2795int efficiency;2796__kmp_get_hybrid_info(&type, &efficiency, &native_model_id);2797hw_thread.attrs.set_core_type(type);2798hw_thread.attrs.set_core_eff(efficiency);2799}2800hw_thread_index++;2801}2802KMP_ASSERT(hw_thread_index > 0);2803__kmp_topology->sort_ids();2804if (!__kmp_topology->check_ids()) {2805kmp_topology_t::deallocate(__kmp_topology);2806__kmp_topology = nullptr;2807*msg_id = kmp_i18n_str_x2ApicIDsNotUnique;2808return false;2809}2810return true;2811}2812#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */28132814#define osIdIndex 02815#define threadIdIndex 12816#define coreIdIndex 22817#define pkgIdIndex 32818#define nodeIdIndex 428192820typedef unsigned *ProcCpuInfo;2821static unsigned maxIndex = pkgIdIndex;28222823static int __kmp_affinity_cmp_ProcCpuInfo_phys_id(const void *a,2824const void *b) {2825unsigned i;2826const unsigned *aa = *(unsigned *const *)a;2827const unsigned *bb = *(unsigned *const *)b;2828for (i = maxIndex;; i--) {2829if (aa[i] < bb[i])2830return -1;2831if (aa[i] > bb[i])2832return 1;2833if (i == osIdIndex)2834break;2835}2836return 0;2837}28382839#if KMP_USE_HIER_SCHED2840// Set the array sizes for the hierarchy layers2841static void __kmp_dispatch_set_hierarchy_values() {2842// Set the maximum number of L1's to number of cores2843// Set the maximum number of L2's to either number of cores / 2 for2844// Intel(R) Xeon Phi(TM) coprocessor formally codenamed Knights Landing2845// Or the number of cores for Intel(R) Xeon(R) processors2846// Set the maximum number of NUMA nodes and L3's to number of packages2847__kmp_hier_max_units[kmp_hier_layer_e::LAYER_THREAD + 1] =2848nPackages * nCoresPerPkg * __kmp_nThreadsPerCore;2849__kmp_hier_max_units[kmp_hier_layer_e::LAYER_L1 + 1] = __kmp_ncores;2850#if KMP_ARCH_X86_64 && \2851(KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \2852KMP_OS_WINDOWS) && \2853KMP_MIC_SUPPORTED2854if (__kmp_mic_type >= mic3)2855__kmp_hier_max_units[kmp_hier_layer_e::LAYER_L2 + 1] = __kmp_ncores / 2;2856else2857#endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)2858__kmp_hier_max_units[kmp_hier_layer_e::LAYER_L2 + 1] = __kmp_ncores;2859__kmp_hier_max_units[kmp_hier_layer_e::LAYER_L3 + 1] = nPackages;2860__kmp_hier_max_units[kmp_hier_layer_e::LAYER_NUMA + 1] = nPackages;2861__kmp_hier_max_units[kmp_hier_layer_e::LAYER_LOOP + 1] = 1;2862// Set the number of threads per unit2863// Number of hardware threads per L1/L2/L3/NUMA/LOOP2864__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_THREAD + 1] = 1;2865__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L1 + 1] =2866__kmp_nThreadsPerCore;2867#if KMP_ARCH_X86_64 && \2868(KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \2869KMP_OS_WINDOWS) && \2870KMP_MIC_SUPPORTED2871if (__kmp_mic_type >= mic3)2872__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L2 + 1] =28732 * __kmp_nThreadsPerCore;2874else2875#endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)2876__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L2 + 1] =2877__kmp_nThreadsPerCore;2878__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L3 + 1] =2879nCoresPerPkg * __kmp_nThreadsPerCore;2880__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_NUMA + 1] =2881nCoresPerPkg * __kmp_nThreadsPerCore;2882__kmp_hier_threads_per[kmp_hier_layer_e::LAYER_LOOP + 1] =2883nPackages * nCoresPerPkg * __kmp_nThreadsPerCore;2884}28852886// Return the index into the hierarchy for this tid and layer type (L1, L2, etc)2887// i.e., this thread's L1 or this thread's L2, etc.2888int __kmp_dispatch_get_index(int tid, kmp_hier_layer_e type) {2889int index = type + 1;2890int num_hw_threads = __kmp_hier_max_units[kmp_hier_layer_e::LAYER_THREAD + 1];2891KMP_DEBUG_ASSERT(type != kmp_hier_layer_e::LAYER_LAST);2892if (type == kmp_hier_layer_e::LAYER_THREAD)2893return tid;2894else if (type == kmp_hier_layer_e::LAYER_LOOP)2895return 0;2896KMP_DEBUG_ASSERT(__kmp_hier_max_units[index] != 0);2897if (tid >= num_hw_threads)2898tid = tid % num_hw_threads;2899return (tid / __kmp_hier_threads_per[index]) % __kmp_hier_max_units[index];2900}29012902// Return the number of t1's per t22903int __kmp_dispatch_get_t1_per_t2(kmp_hier_layer_e t1, kmp_hier_layer_e t2) {2904int i1 = t1 + 1;2905int i2 = t2 + 1;2906KMP_DEBUG_ASSERT(i1 <= i2);2907KMP_DEBUG_ASSERT(t1 != kmp_hier_layer_e::LAYER_LAST);2908KMP_DEBUG_ASSERT(t2 != kmp_hier_layer_e::LAYER_LAST);2909KMP_DEBUG_ASSERT(__kmp_hier_threads_per[i1] != 0);2910// (nthreads/t2) / (nthreads/t1) = t1 / t22911return __kmp_hier_threads_per[i2] / __kmp_hier_threads_per[i1];2912}2913#endif // KMP_USE_HIER_SCHED29142915static inline const char *__kmp_cpuinfo_get_filename() {2916const char *filename;2917if (__kmp_cpuinfo_file != nullptr)2918filename = __kmp_cpuinfo_file;2919else2920filename = "/proc/cpuinfo";2921return filename;2922}29232924static inline const char *__kmp_cpuinfo_get_envvar() {2925const char *envvar = nullptr;2926if (__kmp_cpuinfo_file != nullptr)2927envvar = "KMP_CPUINFO_FILE";2928return envvar;2929}29302931// Parse /proc/cpuinfo (or an alternate file in the same format) to obtain the2932// affinity map. On AIX, the map is obtained through system SRAD (Scheduler2933// Resource Allocation Domain).2934static bool __kmp_affinity_create_cpuinfo_map(int *line,2935kmp_i18n_id_t *const msg_id) {2936*msg_id = kmp_i18n_null;29372938#if KMP_OS_AIX2939unsigned num_records = __kmp_xproc;2940#else2941const char *filename = __kmp_cpuinfo_get_filename();2942const char *envvar = __kmp_cpuinfo_get_envvar();29432944if (__kmp_affinity.flags.verbose) {2945KMP_INFORM(AffParseFilename, "KMP_AFFINITY", filename);2946}29472948kmp_safe_raii_file_t f(filename, "r", envvar);29492950// Scan of the file, and count the number of "processor" (osId) fields,2951// and find the highest value of <n> for a node_<n> field.2952char buf[256];2953unsigned num_records = 0;2954while (!feof(f)) {2955buf[sizeof(buf) - 1] = 1;2956if (!fgets(buf, sizeof(buf), f)) {2957// Read errors presumably because of EOF2958break;2959}29602961char s1[] = "processor";2962if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {2963num_records++;2964continue;2965}29662967// FIXME - this will match "node_<n> <garbage>"2968unsigned level;2969if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {2970// validate the input fisrt:2971if (level > (unsigned)__kmp_xproc) { // level is too big2972level = __kmp_xproc;2973}2974if (nodeIdIndex + level >= maxIndex) {2975maxIndex = nodeIdIndex + level;2976}2977continue;2978}2979}29802981// Check for empty file / no valid processor records, or too many. The number2982// of records can't exceed the number of valid bits in the affinity mask.2983if (num_records == 0) {2984*msg_id = kmp_i18n_str_NoProcRecords;2985return false;2986}2987if (num_records > (unsigned)__kmp_xproc) {2988*msg_id = kmp_i18n_str_TooManyProcRecords;2989return false;2990}29912992// Set the file pointer back to the beginning, so that we can scan the file2993// again, this time performing a full parse of the data. Allocate a vector of2994// ProcCpuInfo object, where we will place the data. Adding an extra element2995// at the end allows us to remove a lot of extra checks for termination2996// conditions.2997if (fseek(f, 0, SEEK_SET) != 0) {2998*msg_id = kmp_i18n_str_CantRewindCpuinfo;2999return false;3000}3001#endif // KMP_OS_AIX30023003// Allocate the array of records to store the proc info in. The dummy3004// element at the end makes the logic in filling them out easier to code.3005unsigned **threadInfo =3006(unsigned **)__kmp_allocate((num_records + 1) * sizeof(unsigned *));3007unsigned i;3008for (i = 0; i <= num_records; i++) {3009threadInfo[i] =3010(unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));3011}30123013#define CLEANUP_THREAD_INFO \3014for (i = 0; i <= num_records; i++) { \3015__kmp_free(threadInfo[i]); \3016} \3017__kmp_free(threadInfo);30183019// A value of UINT_MAX means that we didn't find the field3020unsigned __index;30213022#define INIT_PROC_INFO(p) \3023for (__index = 0; __index <= maxIndex; __index++) { \3024(p)[__index] = UINT_MAX; \3025}30263027for (i = 0; i <= num_records; i++) {3028INIT_PROC_INFO(threadInfo[i]);3029}30303031#if KMP_OS_AIX3032int smt_threads;3033lpar_info_format1_t cpuinfo;3034unsigned num_avail = __kmp_xproc;30353036if (__kmp_affinity.flags.verbose)3037KMP_INFORM(AffParseFilename, "KMP_AFFINITY", "system info for topology");30383039// Get the number of SMT threads per core.3040smt_threads = syssmt(GET_NUMBER_SMT_SETS, 0, 0, NULL);30413042// Allocate a resource set containing available system resourses.3043rsethandle_t sys_rset = rs_alloc(RS_SYSTEM);3044if (sys_rset == NULL) {3045CLEANUP_THREAD_INFO;3046*msg_id = kmp_i18n_str_UnknownTopology;3047return false;3048}3049// Allocate a resource set for the SRAD info.3050rsethandle_t srad = rs_alloc(RS_EMPTY);3051if (srad == NULL) {3052rs_free(sys_rset);3053CLEANUP_THREAD_INFO;3054*msg_id = kmp_i18n_str_UnknownTopology;3055return false;3056}30573058// Get the SRAD system detail level.3059int sradsdl = rs_getinfo(NULL, R_SRADSDL, 0);3060if (sradsdl < 0) {3061rs_free(sys_rset);3062rs_free(srad);3063CLEANUP_THREAD_INFO;3064*msg_id = kmp_i18n_str_UnknownTopology;3065return false;3066}3067// Get the number of RADs at that SRAD SDL.3068int num_rads = rs_numrads(sys_rset, sradsdl, 0);3069if (num_rads < 0) {3070rs_free(sys_rset);3071rs_free(srad);3072CLEANUP_THREAD_INFO;3073*msg_id = kmp_i18n_str_UnknownTopology;3074return false;3075}30763077// Get the maximum number of procs that may be contained in a resource set.3078int max_procs = rs_getinfo(NULL, R_MAXPROCS, 0);3079if (max_procs < 0) {3080rs_free(sys_rset);3081rs_free(srad);3082CLEANUP_THREAD_INFO;3083*msg_id = kmp_i18n_str_UnknownTopology;3084return false;3085}30863087int cur_rad = 0;3088int num_set = 0;3089for (int srad_idx = 0; cur_rad < num_rads && srad_idx < VMI_MAXRADS;3090++srad_idx) {3091// Check if the SRAD is available in the RSET.3092if (rs_getrad(sys_rset, srad, sradsdl, srad_idx, 0) < 0)3093continue;30943095for (int cpu = 0; cpu < max_procs; cpu++) {3096// Set the info for the cpu if it is in the SRAD.3097if (rs_op(RS_TESTRESOURCE, srad, NULL, R_PROCS, cpu)) {3098threadInfo[cpu][osIdIndex] = cpu;3099threadInfo[cpu][pkgIdIndex] = cur_rad;3100threadInfo[cpu][coreIdIndex] = cpu / smt_threads;3101++num_set;3102if (num_set >= num_avail) {3103// Done if all available CPUs have been set.3104break;3105}3106}3107}3108++cur_rad;3109}3110rs_free(sys_rset);3111rs_free(srad);31123113// The topology is already sorted.31143115#else // !KMP_OS_AIX3116unsigned num_avail = 0;3117*line = 0;3118#if KMP_ARCH_S390X3119bool reading_s390x_sys_info = true;3120#endif3121while (!feof(f)) {3122// Create an inner scoping level, so that all the goto targets at the end of3123// the loop appear in an outer scoping level. This avoids warnings about3124// jumping past an initialization to a target in the same block.3125{3126buf[sizeof(buf) - 1] = 1;3127bool long_line = false;3128if (!fgets(buf, sizeof(buf), f)) {3129// Read errors presumably because of EOF3130// If there is valid data in threadInfo[num_avail], then fake3131// a blank line in ensure that the last address gets parsed.3132bool valid = false;3133for (i = 0; i <= maxIndex; i++) {3134if (threadInfo[num_avail][i] != UINT_MAX) {3135valid = true;3136}3137}3138if (!valid) {3139break;3140}3141buf[0] = 0;3142} else if (!buf[sizeof(buf) - 1]) {3143// The line is longer than the buffer. Set a flag and don't3144// emit an error if we were going to ignore the line, anyway.3145long_line = true;31463147#define CHECK_LINE \3148if (long_line) { \3149CLEANUP_THREAD_INFO; \3150*msg_id = kmp_i18n_str_LongLineCpuinfo; \3151return false; \3152}3153}3154(*line)++;31553156#if KMP_ARCH_LOONGARCH643157// The parsing logic of /proc/cpuinfo in this function highly depends on3158// the blank lines between each processor info block. But on LoongArch a3159// blank line exists before the first processor info block (i.e. after the3160// "system type" line). This blank line was added because the "system3161// type" line is unrelated to any of the CPUs. We must skip this line so3162// that the original logic works on LoongArch.3163if (*buf == '\n' && *line == 2)3164continue;3165#endif3166#if KMP_ARCH_S390X3167// s390x /proc/cpuinfo starts with a variable number of lines containing3168// the overall system information. Skip them.3169if (reading_s390x_sys_info) {3170if (*buf == '\n')3171reading_s390x_sys_info = false;3172continue;3173}3174#endif31753176#if KMP_ARCH_S390X3177char s1[] = "cpu number";3178#else3179char s1[] = "processor";3180#endif3181if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {3182CHECK_LINE;3183char *p = strchr(buf + sizeof(s1) - 1, ':');3184unsigned val;3185if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))3186goto no_val;3187if (threadInfo[num_avail][osIdIndex] != UINT_MAX)3188#if KMP_ARCH_AARCH643189// Handle the old AArch64 /proc/cpuinfo layout differently,3190// it contains all of the 'processor' entries listed in a3191// single 'Processor' section, therefore the normal looking3192// for duplicates in that section will always fail.3193num_avail++;3194#else3195goto dup_field;3196#endif3197threadInfo[num_avail][osIdIndex] = val;3198#if KMP_OS_LINUX && !(KMP_ARCH_X86 || KMP_ARCH_X86_64)3199char path[256];3200KMP_SNPRINTF(3201path, sizeof(path),3202"/sys/devices/system/cpu/cpu%u/topology/physical_package_id",3203threadInfo[num_avail][osIdIndex]);3204__kmp_read_from_file(path, "%u", &threadInfo[num_avail][pkgIdIndex]);32053206#if KMP_ARCH_S390X3207// Disambiguate physical_package_id.3208unsigned book_id;3209KMP_SNPRINTF(path, sizeof(path),3210"/sys/devices/system/cpu/cpu%u/topology/book_id",3211threadInfo[num_avail][osIdIndex]);3212__kmp_read_from_file(path, "%u", &book_id);3213threadInfo[num_avail][pkgIdIndex] |= (book_id << 8);32143215unsigned drawer_id;3216KMP_SNPRINTF(path, sizeof(path),3217"/sys/devices/system/cpu/cpu%u/topology/drawer_id",3218threadInfo[num_avail][osIdIndex]);3219__kmp_read_from_file(path, "%u", &drawer_id);3220threadInfo[num_avail][pkgIdIndex] |= (drawer_id << 16);3221#endif32223223KMP_SNPRINTF(path, sizeof(path),3224"/sys/devices/system/cpu/cpu%u/topology/core_id",3225threadInfo[num_avail][osIdIndex]);3226__kmp_read_from_file(path, "%u", &threadInfo[num_avail][coreIdIndex]);3227continue;3228#else3229}3230char s2[] = "physical id";3231if (strncmp(buf, s2, sizeof(s2) - 1) == 0) {3232CHECK_LINE;3233char *p = strchr(buf + sizeof(s2) - 1, ':');3234unsigned val;3235if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))3236goto no_val;3237if (threadInfo[num_avail][pkgIdIndex] != UINT_MAX)3238goto dup_field;3239threadInfo[num_avail][pkgIdIndex] = val;3240continue;3241}3242char s3[] = "core id";3243if (strncmp(buf, s3, sizeof(s3) - 1) == 0) {3244CHECK_LINE;3245char *p = strchr(buf + sizeof(s3) - 1, ':');3246unsigned val;3247if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))3248goto no_val;3249if (threadInfo[num_avail][coreIdIndex] != UINT_MAX)3250goto dup_field;3251threadInfo[num_avail][coreIdIndex] = val;3252continue;3253#endif // KMP_OS_LINUX && USE_SYSFS_INFO3254}3255char s4[] = "thread id";3256if (strncmp(buf, s4, sizeof(s4) - 1) == 0) {3257CHECK_LINE;3258char *p = strchr(buf + sizeof(s4) - 1, ':');3259unsigned val;3260if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))3261goto no_val;3262if (threadInfo[num_avail][threadIdIndex] != UINT_MAX)3263goto dup_field;3264threadInfo[num_avail][threadIdIndex] = val;3265continue;3266}3267unsigned level;3268if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {3269CHECK_LINE;3270char *p = strchr(buf + sizeof(s4) - 1, ':');3271unsigned val;3272if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))3273goto no_val;3274// validate the input before using level:3275if (level > (unsigned)__kmp_xproc) { // level is too big3276level = __kmp_xproc;3277}3278if (threadInfo[num_avail][nodeIdIndex + level] != UINT_MAX)3279goto dup_field;3280threadInfo[num_avail][nodeIdIndex + level] = val;3281continue;3282}32833284// We didn't recognize the leading token on the line. There are lots of3285// leading tokens that we don't recognize - if the line isn't empty, go on3286// to the next line.3287if ((*buf != 0) && (*buf != '\n')) {3288// If the line is longer than the buffer, read characters3289// until we find a newline.3290if (long_line) {3291int ch;3292while (((ch = fgetc(f)) != EOF) && (ch != '\n'))3293;3294}3295continue;3296}32973298// A newline has signalled the end of the processor record.3299// Check that there aren't too many procs specified.3300if ((int)num_avail == __kmp_xproc) {3301CLEANUP_THREAD_INFO;3302*msg_id = kmp_i18n_str_TooManyEntries;3303return false;3304}33053306// Check for missing fields. The osId field must be there, and we3307// currently require that the physical id field is specified, also.3308if (threadInfo[num_avail][osIdIndex] == UINT_MAX) {3309CLEANUP_THREAD_INFO;3310*msg_id = kmp_i18n_str_MissingProcField;3311return false;3312}3313if (threadInfo[0][pkgIdIndex] == UINT_MAX) {3314CLEANUP_THREAD_INFO;3315*msg_id = kmp_i18n_str_MissingPhysicalIDField;3316return false;3317}33183319// Skip this proc if it is not included in the machine model.3320if (KMP_AFFINITY_CAPABLE() &&3321!KMP_CPU_ISSET(threadInfo[num_avail][osIdIndex],3322__kmp_affin_fullMask)) {3323INIT_PROC_INFO(threadInfo[num_avail]);3324continue;3325}33263327// We have a successful parse of this proc's info.3328// Increment the counter, and prepare for the next proc.3329num_avail++;3330KMP_ASSERT(num_avail <= num_records);3331INIT_PROC_INFO(threadInfo[num_avail]);3332}3333continue;33343335no_val:3336CLEANUP_THREAD_INFO;3337*msg_id = kmp_i18n_str_MissingValCpuinfo;3338return false;33393340dup_field:3341CLEANUP_THREAD_INFO;3342*msg_id = kmp_i18n_str_DuplicateFieldCpuinfo;3343return false;3344}3345*line = 0;33463347#if KMP_MIC && REDUCE_TEAM_SIZE3348unsigned teamSize = 0;3349#endif // KMP_MIC && REDUCE_TEAM_SIZE33503351// check for num_records == __kmp_xproc ???33523353// If it is configured to omit the package level when there is only a single3354// package, the logic at the end of this routine won't work if there is only a3355// single thread3356KMP_ASSERT(num_avail > 0);3357KMP_ASSERT(num_avail <= num_records);33583359// Sort the threadInfo table by physical Id.3360qsort(threadInfo, num_avail, sizeof(*threadInfo),3361__kmp_affinity_cmp_ProcCpuInfo_phys_id);33623363#endif // KMP_OS_AIX33643365// The table is now sorted by pkgId / coreId / threadId, but we really don't3366// know the radix of any of the fields. pkgId's may be sparsely assigned among3367// the chips on a system. Although coreId's are usually assigned3368// [0 .. coresPerPkg-1] and threadId's are usually assigned3369// [0..threadsPerCore-1], we don't want to make any such assumptions.3370//3371// For that matter, we don't know what coresPerPkg and threadsPerCore (or the3372// total # packages) are at this point - we want to determine that now. We3373// only have an upper bound on the first two figures.3374unsigned *counts =3375(unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));3376unsigned *maxCt =3377(unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));3378unsigned *totals =3379(unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));3380unsigned *lastId =3381(unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));33823383bool assign_thread_ids = false;3384unsigned threadIdCt;3385unsigned index;33863387restart_radix_check:3388threadIdCt = 0;33893390// Initialize the counter arrays with data from threadInfo[0].3391if (assign_thread_ids) {3392if (threadInfo[0][threadIdIndex] == UINT_MAX) {3393threadInfo[0][threadIdIndex] = threadIdCt++;3394} else if (threadIdCt <= threadInfo[0][threadIdIndex]) {3395threadIdCt = threadInfo[0][threadIdIndex] + 1;3396}3397}3398for (index = 0; index <= maxIndex; index++) {3399counts[index] = 1;3400maxCt[index] = 1;3401totals[index] = 1;3402lastId[index] = threadInfo[0][index];3403;3404}34053406// Run through the rest of the OS procs.3407for (i = 1; i < num_avail; i++) {3408// Find the most significant index whose id differs from the id for the3409// previous OS proc.3410for (index = maxIndex; index >= threadIdIndex; index--) {3411if (assign_thread_ids && (index == threadIdIndex)) {3412// Auto-assign the thread id field if it wasn't specified.3413if (threadInfo[i][threadIdIndex] == UINT_MAX) {3414threadInfo[i][threadIdIndex] = threadIdCt++;3415}3416// Apparently the thread id field was specified for some entries and not3417// others. Start the thread id counter off at the next higher thread id.3418else if (threadIdCt <= threadInfo[i][threadIdIndex]) {3419threadIdCt = threadInfo[i][threadIdIndex] + 1;3420}3421}3422if (threadInfo[i][index] != lastId[index]) {3423// Run through all indices which are less significant, and reset the3424// counts to 1. At all levels up to and including index, we need to3425// increment the totals and record the last id.3426unsigned index2;3427for (index2 = threadIdIndex; index2 < index; index2++) {3428totals[index2]++;3429if (counts[index2] > maxCt[index2]) {3430maxCt[index2] = counts[index2];3431}3432counts[index2] = 1;3433lastId[index2] = threadInfo[i][index2];3434}3435counts[index]++;3436totals[index]++;3437lastId[index] = threadInfo[i][index];34383439if (assign_thread_ids && (index > threadIdIndex)) {34403441#if KMP_MIC && REDUCE_TEAM_SIZE3442// The default team size is the total #threads in the machine3443// minus 1 thread for every core that has 3 or more threads.3444teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);3445#endif // KMP_MIC && REDUCE_TEAM_SIZE34463447// Restart the thread counter, as we are on a new core.3448threadIdCt = 0;34493450// Auto-assign the thread id field if it wasn't specified.3451if (threadInfo[i][threadIdIndex] == UINT_MAX) {3452threadInfo[i][threadIdIndex] = threadIdCt++;3453}34543455// Apparently the thread id field was specified for some entries and3456// not others. Start the thread id counter off at the next higher3457// thread id.3458else if (threadIdCt <= threadInfo[i][threadIdIndex]) {3459threadIdCt = threadInfo[i][threadIdIndex] + 1;3460}3461}3462break;3463}3464}3465if (index < threadIdIndex) {3466// If thread ids were specified, it is an error if they are not unique.3467// Also, check that we waven't already restarted the loop (to be safe -3468// shouldn't need to).3469if ((threadInfo[i][threadIdIndex] != UINT_MAX) || assign_thread_ids) {3470__kmp_free(lastId);3471__kmp_free(totals);3472__kmp_free(maxCt);3473__kmp_free(counts);3474CLEANUP_THREAD_INFO;3475*msg_id = kmp_i18n_str_PhysicalIDsNotUnique;3476return false;3477}34783479// If the thread ids were not specified and we see entries that3480// are duplicates, start the loop over and assign the thread ids manually.3481assign_thread_ids = true;3482goto restart_radix_check;3483}3484}34853486#if KMP_MIC && REDUCE_TEAM_SIZE3487// The default team size is the total #threads in the machine3488// minus 1 thread for every core that has 3 or more threads.3489teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);3490#endif // KMP_MIC && REDUCE_TEAM_SIZE34913492for (index = threadIdIndex; index <= maxIndex; index++) {3493if (counts[index] > maxCt[index]) {3494maxCt[index] = counts[index];3495}3496}34973498__kmp_nThreadsPerCore = maxCt[threadIdIndex];3499nCoresPerPkg = maxCt[coreIdIndex];3500nPackages = totals[pkgIdIndex];35013502// When affinity is off, this routine will still be called to set3503// __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.3504// Make sure all these vars are set correctly, and return now if affinity is3505// not enabled.3506__kmp_ncores = totals[coreIdIndex];3507if (!KMP_AFFINITY_CAPABLE()) {3508KMP_ASSERT(__kmp_affinity.type == affinity_none);3509return true;3510}35113512#if KMP_MIC && REDUCE_TEAM_SIZE3513// Set the default team size.3514if ((__kmp_dflt_team_nth == 0) && (teamSize > 0)) {3515__kmp_dflt_team_nth = teamSize;3516KA_TRACE(20, ("__kmp_affinity_create_cpuinfo_map: setting "3517"__kmp_dflt_team_nth = %d\n",3518__kmp_dflt_team_nth));3519}3520#endif // KMP_MIC && REDUCE_TEAM_SIZE35213522KMP_DEBUG_ASSERT(num_avail == (unsigned)__kmp_avail_proc);35233524// Count the number of levels which have more nodes at that level than at the3525// parent's level (with there being an implicit root node of the top level).3526// This is equivalent to saying that there is at least one node at this level3527// which has a sibling. These levels are in the map, and the package level is3528// always in the map.3529bool *inMap = (bool *)__kmp_allocate((maxIndex + 1) * sizeof(bool));3530for (index = threadIdIndex; index < maxIndex; index++) {3531KMP_ASSERT(totals[index] >= totals[index + 1]);3532inMap[index] = (totals[index] > totals[index + 1]);3533}3534inMap[maxIndex] = (totals[maxIndex] > 1);3535inMap[pkgIdIndex] = true;3536inMap[coreIdIndex] = true;3537inMap[threadIdIndex] = true;35383539int depth = 0;3540int idx = 0;3541kmp_hw_t types[KMP_HW_LAST];3542int pkgLevel = -1;3543int coreLevel = -1;3544int threadLevel = -1;3545for (index = threadIdIndex; index <= maxIndex; index++) {3546if (inMap[index]) {3547depth++;3548}3549}3550if (inMap[pkgIdIndex]) {3551pkgLevel = idx;3552types[idx++] = KMP_HW_SOCKET;3553}3554if (inMap[coreIdIndex]) {3555coreLevel = idx;3556types[idx++] = KMP_HW_CORE;3557}3558if (inMap[threadIdIndex]) {3559threadLevel = idx;3560types[idx++] = KMP_HW_THREAD;3561}3562KMP_ASSERT(depth > 0);35633564// Construct the data structure that is to be returned.3565__kmp_topology = kmp_topology_t::allocate(num_avail, depth, types);35663567for (i = 0; i < num_avail; ++i) {3568unsigned os = threadInfo[i][osIdIndex];3569int src_index;3570kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);3571hw_thread.clear();3572hw_thread.os_id = os;35733574idx = 0;3575for (src_index = maxIndex; src_index >= threadIdIndex; src_index--) {3576if (!inMap[src_index]) {3577continue;3578}3579if (src_index == pkgIdIndex) {3580hw_thread.ids[pkgLevel] = threadInfo[i][src_index];3581} else if (src_index == coreIdIndex) {3582hw_thread.ids[coreLevel] = threadInfo[i][src_index];3583} else if (src_index == threadIdIndex) {3584hw_thread.ids[threadLevel] = threadInfo[i][src_index];3585}3586}3587}35883589__kmp_free(inMap);3590__kmp_free(lastId);3591__kmp_free(totals);3592__kmp_free(maxCt);3593__kmp_free(counts);3594CLEANUP_THREAD_INFO;3595__kmp_topology->sort_ids();3596if (!__kmp_topology->check_ids()) {3597kmp_topology_t::deallocate(__kmp_topology);3598__kmp_topology = nullptr;3599*msg_id = kmp_i18n_str_PhysicalIDsNotUnique;3600return false;3601}3602return true;3603}36043605// Create and return a table of affinity masks, indexed by OS thread ID.3606// This routine handles OR'ing together all the affinity masks of threads3607// that are sufficiently close, if granularity > fine.3608template <typename FindNextFunctionType>3609static void __kmp_create_os_id_masks(unsigned *numUnique,3610kmp_affinity_t &affinity,3611FindNextFunctionType find_next) {3612// First form a table of affinity masks in order of OS thread id.3613int maxOsId;3614int i;3615int numAddrs = __kmp_topology->get_num_hw_threads();3616int depth = __kmp_topology->get_depth();3617const char *env_var = __kmp_get_affinity_env_var(affinity);3618KMP_ASSERT(numAddrs);3619KMP_ASSERT(depth);36203621i = find_next(-1);3622// If could not find HW thread location with attributes, then return and3623// fallback to increment find_next and disregard core attributes.3624if (i >= numAddrs)3625return;36263627maxOsId = 0;3628for (i = numAddrs - 1;; --i) {3629int osId = __kmp_topology->at(i).os_id;3630if (osId > maxOsId) {3631maxOsId = osId;3632}3633if (i == 0)3634break;3635}3636affinity.num_os_id_masks = maxOsId + 1;3637KMP_CPU_ALLOC_ARRAY(affinity.os_id_masks, affinity.num_os_id_masks);3638KMP_ASSERT(affinity.gran_levels >= 0);3639if (affinity.flags.verbose && (affinity.gran_levels > 0)) {3640KMP_INFORM(ThreadsMigrate, env_var, affinity.gran_levels);3641}3642if (affinity.gran_levels >= (int)depth) {3643KMP_AFF_WARNING(affinity, AffThreadsMayMigrate);3644}36453646// Run through the table, forming the masks for all threads on each core.3647// Threads on the same core will have identical kmp_hw_thread_t objects, not3648// considering the last level, which must be the thread id. All threads on a3649// core will appear consecutively.3650int unique = 0;3651int j = 0; // index of 1st thread on core3652int leader = 0;3653kmp_affin_mask_t *sum;3654KMP_CPU_ALLOC_ON_STACK(sum);3655KMP_CPU_ZERO(sum);36563657i = j = leader = find_next(-1);3658KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);3659kmp_full_mask_modifier_t full_mask;3660for (i = find_next(i); i < numAddrs; i = find_next(i)) {3661// If this thread is sufficiently close to the leader (within the3662// granularity setting), then set the bit for this os thread in the3663// affinity mask for this group, and go on to the next thread.3664if (__kmp_topology->is_close(leader, i, affinity)) {3665KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);3666continue;3667}36683669// For every thread in this group, copy the mask to the thread's entry in3670// the OS Id mask table. Mark the first address as a leader.3671for (; j < i; j = find_next(j)) {3672int osId = __kmp_topology->at(j).os_id;3673KMP_DEBUG_ASSERT(osId <= maxOsId);3674kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.os_id_masks, osId);3675KMP_CPU_COPY(mask, sum);3676__kmp_topology->at(j).leader = (j == leader);3677}3678unique++;36793680// Start a new mask.3681leader = i;3682full_mask.include(sum);3683KMP_CPU_ZERO(sum);3684KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);3685}36863687// For every thread in last group, copy the mask to the thread's3688// entry in the OS Id mask table.3689for (; j < i; j = find_next(j)) {3690int osId = __kmp_topology->at(j).os_id;3691KMP_DEBUG_ASSERT(osId <= maxOsId);3692kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.os_id_masks, osId);3693KMP_CPU_COPY(mask, sum);3694__kmp_topology->at(j).leader = (j == leader);3695}3696full_mask.include(sum);3697unique++;3698KMP_CPU_FREE_FROM_STACK(sum);36993700// See if the OS Id mask table further restricts or changes the full mask3701if (full_mask.restrict_to_mask() && affinity.flags.verbose) {3702__kmp_topology->print(env_var);3703}37043705*numUnique = unique;3706}37073708// Stuff for the affinity proclist parsers. It's easier to declare these vars3709// as file-static than to try and pass them through the calling sequence of3710// the recursive-descent OMP_PLACES parser.3711static kmp_affin_mask_t *newMasks;3712static int numNewMasks;3713static int nextNewMask;37143715#define ADD_MASK(_mask) \3716{ \3717if (nextNewMask >= numNewMasks) { \3718int i; \3719numNewMasks *= 2; \3720kmp_affin_mask_t *temp; \3721KMP_CPU_INTERNAL_ALLOC_ARRAY(temp, numNewMasks); \3722for (i = 0; i < numNewMasks / 2; i++) { \3723kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i); \3724kmp_affin_mask_t *dest = KMP_CPU_INDEX(temp, i); \3725KMP_CPU_COPY(dest, src); \3726} \3727KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks / 2); \3728newMasks = temp; \3729} \3730KMP_CPU_COPY(KMP_CPU_INDEX(newMasks, nextNewMask), (_mask)); \3731nextNewMask++; \3732}37333734#define ADD_MASK_OSID(_osId, _osId2Mask, _maxOsId) \3735{ \3736if (((_osId) > _maxOsId) || \3737(!KMP_CPU_ISSET((_osId), KMP_CPU_INDEX((_osId2Mask), (_osId))))) { \3738KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, _osId); \3739} else { \3740ADD_MASK(KMP_CPU_INDEX(_osId2Mask, (_osId))); \3741} \3742}37433744// Re-parse the proclist (for the explicit affinity type), and form the list3745// of affinity newMasks indexed by gtid.3746static void __kmp_affinity_process_proclist(kmp_affinity_t &affinity) {3747int i;3748kmp_affin_mask_t **out_masks = &affinity.masks;3749unsigned *out_numMasks = &affinity.num_masks;3750const char *proclist = affinity.proclist;3751kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;3752int maxOsId = affinity.num_os_id_masks - 1;3753const char *scan = proclist;3754const char *next = proclist;37553756// We use malloc() for the temporary mask vector, so that we can use3757// realloc() to extend it.3758numNewMasks = 2;3759KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);3760nextNewMask = 0;3761kmp_affin_mask_t *sumMask;3762KMP_CPU_ALLOC(sumMask);3763int setSize = 0;37643765for (;;) {3766int start, end, stride;37673768SKIP_WS(scan);3769next = scan;3770if (*next == '\0') {3771break;3772}37733774if (*next == '{') {3775int num;3776setSize = 0;3777next++; // skip '{'3778SKIP_WS(next);3779scan = next;37803781// Read the first integer in the set.3782KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad proclist");3783SKIP_DIGITS(next);3784num = __kmp_str_to_int(scan, *next);3785KMP_ASSERT2(num >= 0, "bad explicit proc list");37863787// Copy the mask for that osId to the sum (union) mask.3788if ((num > maxOsId) ||3789(!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {3790KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);3791KMP_CPU_ZERO(sumMask);3792} else {3793KMP_CPU_COPY(sumMask, KMP_CPU_INDEX(osId2Mask, num));3794setSize = 1;3795}37963797for (;;) {3798// Check for end of set.3799SKIP_WS(next);3800if (*next == '}') {3801next++; // skip '}'3802break;3803}38043805// Skip optional comma.3806if (*next == ',') {3807next++;3808}3809SKIP_WS(next);38103811// Read the next integer in the set.3812scan = next;3813KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");38143815SKIP_DIGITS(next);3816num = __kmp_str_to_int(scan, *next);3817KMP_ASSERT2(num >= 0, "bad explicit proc list");38183819// Add the mask for that osId to the sum mask.3820if ((num > maxOsId) ||3821(!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {3822KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);3823} else {3824KMP_CPU_UNION(sumMask, KMP_CPU_INDEX(osId2Mask, num));3825setSize++;3826}3827}3828if (setSize > 0) {3829ADD_MASK(sumMask);3830}38313832SKIP_WS(next);3833if (*next == ',') {3834next++;3835}3836scan = next;3837continue;3838}38393840// Read the first integer.3841KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");3842SKIP_DIGITS(next);3843start = __kmp_str_to_int(scan, *next);3844KMP_ASSERT2(start >= 0, "bad explicit proc list");3845SKIP_WS(next);38463847// If this isn't a range, then add a mask to the list and go on.3848if (*next != '-') {3849ADD_MASK_OSID(start, osId2Mask, maxOsId);38503851// Skip optional comma.3852if (*next == ',') {3853next++;3854}3855scan = next;3856continue;3857}38583859// This is a range. Skip over the '-' and read in the 2nd int.3860next++; // skip '-'3861SKIP_WS(next);3862scan = next;3863KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");3864SKIP_DIGITS(next);3865end = __kmp_str_to_int(scan, *next);3866KMP_ASSERT2(end >= 0, "bad explicit proc list");38673868// Check for a stride parameter3869stride = 1;3870SKIP_WS(next);3871if (*next == ':') {3872// A stride is specified. Skip over the ':" and read the 3rd int.3873int sign = +1;3874next++; // skip ':'3875SKIP_WS(next);3876scan = next;3877if (*next == '-') {3878sign = -1;3879next++;3880SKIP_WS(next);3881scan = next;3882}3883KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");3884SKIP_DIGITS(next);3885stride = __kmp_str_to_int(scan, *next);3886KMP_ASSERT2(stride >= 0, "bad explicit proc list");3887stride *= sign;3888}38893890// Do some range checks.3891KMP_ASSERT2(stride != 0, "bad explicit proc list");3892if (stride > 0) {3893KMP_ASSERT2(start <= end, "bad explicit proc list");3894} else {3895KMP_ASSERT2(start >= end, "bad explicit proc list");3896}3897KMP_ASSERT2((end - start) / stride <= 65536, "bad explicit proc list");38983899// Add the mask for each OS proc # to the list.3900if (stride > 0) {3901do {3902ADD_MASK_OSID(start, osId2Mask, maxOsId);3903start += stride;3904} while (start <= end);3905} else {3906do {3907ADD_MASK_OSID(start, osId2Mask, maxOsId);3908start += stride;3909} while (start >= end);3910}39113912// Skip optional comma.3913SKIP_WS(next);3914if (*next == ',') {3915next++;3916}3917scan = next;3918}39193920*out_numMasks = nextNewMask;3921if (nextNewMask == 0) {3922*out_masks = NULL;3923KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);3924return;3925}3926KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);3927for (i = 0; i < nextNewMask; i++) {3928kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);3929kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);3930KMP_CPU_COPY(dest, src);3931}3932KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);3933KMP_CPU_FREE(sumMask);3934}39353936/*-----------------------------------------------------------------------------3937Re-parse the OMP_PLACES proc id list, forming the newMasks for the different3938places. Again, Here is the grammar:39393940place_list := place3941place_list := place , place_list3942place := num3943place := place : num3944place := place : num : signed3945place := { subplacelist }3946place := ! place // (lowest priority)3947subplace_list := subplace3948subplace_list := subplace , subplace_list3949subplace := num3950subplace := num : num3951subplace := num : num : signed3952signed := num3953signed := + signed3954signed := - signed3955-----------------------------------------------------------------------------*/3956static void __kmp_process_subplace_list(const char **scan,3957kmp_affinity_t &affinity, int maxOsId,3958kmp_affin_mask_t *tempMask,3959int *setSize) {3960const char *next;3961kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;39623963for (;;) {3964int start, count, stride, i;39653966// Read in the starting proc id3967SKIP_WS(*scan);3968KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");3969next = *scan;3970SKIP_DIGITS(next);3971start = __kmp_str_to_int(*scan, *next);3972KMP_ASSERT(start >= 0);3973*scan = next;39743975// valid follow sets are ',' ':' and '}'3976SKIP_WS(*scan);3977if (**scan == '}' || **scan == ',') {3978if ((start > maxOsId) ||3979(!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {3980KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);3981} else {3982KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));3983(*setSize)++;3984}3985if (**scan == '}') {3986break;3987}3988(*scan)++; // skip ','3989continue;3990}3991KMP_ASSERT2(**scan == ':', "bad explicit places list");3992(*scan)++; // skip ':'39933994// Read count parameter3995SKIP_WS(*scan);3996KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");3997next = *scan;3998SKIP_DIGITS(next);3999count = __kmp_str_to_int(*scan, *next);4000KMP_ASSERT(count >= 0);4001*scan = next;40024003// valid follow sets are ',' ':' and '}'4004SKIP_WS(*scan);4005if (**scan == '}' || **scan == ',') {4006for (i = 0; i < count; i++) {4007if ((start > maxOsId) ||4008(!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {4009KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);4010break; // don't proliferate warnings for large count4011} else {4012KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));4013start++;4014(*setSize)++;4015}4016}4017if (**scan == '}') {4018break;4019}4020(*scan)++; // skip ','4021continue;4022}4023KMP_ASSERT2(**scan == ':', "bad explicit places list");4024(*scan)++; // skip ':'40254026// Read stride parameter4027int sign = +1;4028for (;;) {4029SKIP_WS(*scan);4030if (**scan == '+') {4031(*scan)++; // skip '+'4032continue;4033}4034if (**scan == '-') {4035sign *= -1;4036(*scan)++; // skip '-'4037continue;4038}4039break;4040}4041SKIP_WS(*scan);4042KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");4043next = *scan;4044SKIP_DIGITS(next);4045stride = __kmp_str_to_int(*scan, *next);4046KMP_ASSERT(stride >= 0);4047*scan = next;4048stride *= sign;40494050// valid follow sets are ',' and '}'4051SKIP_WS(*scan);4052if (**scan == '}' || **scan == ',') {4053for (i = 0; i < count; i++) {4054if ((start > maxOsId) ||4055(!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {4056KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, start);4057break; // don't proliferate warnings for large count4058} else {4059KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));4060start += stride;4061(*setSize)++;4062}4063}4064if (**scan == '}') {4065break;4066}4067(*scan)++; // skip ','4068continue;4069}40704071KMP_ASSERT2(0, "bad explicit places list");4072}4073}40744075static void __kmp_process_place(const char **scan, kmp_affinity_t &affinity,4076int maxOsId, kmp_affin_mask_t *tempMask,4077int *setSize) {4078const char *next;4079kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;40804081// valid follow sets are '{' '!' and num4082SKIP_WS(*scan);4083if (**scan == '{') {4084(*scan)++; // skip '{'4085__kmp_process_subplace_list(scan, affinity, maxOsId, tempMask, setSize);4086KMP_ASSERT2(**scan == '}', "bad explicit places list");4087(*scan)++; // skip '}'4088} else if (**scan == '!') {4089(*scan)++; // skip '!'4090__kmp_process_place(scan, affinity, maxOsId, tempMask, setSize);4091KMP_CPU_COMPLEMENT(maxOsId, tempMask);4092} else if ((**scan >= '0') && (**scan <= '9')) {4093next = *scan;4094SKIP_DIGITS(next);4095int num = __kmp_str_to_int(*scan, *next);4096KMP_ASSERT(num >= 0);4097if ((num > maxOsId) ||4098(!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {4099KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, num);4100} else {4101KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, num));4102(*setSize)++;4103}4104*scan = next; // skip num4105} else {4106KMP_ASSERT2(0, "bad explicit places list");4107}4108}41094110// static void4111void __kmp_affinity_process_placelist(kmp_affinity_t &affinity) {4112int i, j, count, stride, sign;4113kmp_affin_mask_t **out_masks = &affinity.masks;4114unsigned *out_numMasks = &affinity.num_masks;4115const char *placelist = affinity.proclist;4116kmp_affin_mask_t *osId2Mask = affinity.os_id_masks;4117int maxOsId = affinity.num_os_id_masks - 1;4118const char *scan = placelist;4119const char *next = placelist;41204121numNewMasks = 2;4122KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);4123nextNewMask = 0;41244125// tempMask is modified based on the previous or initial4126// place to form the current place4127// previousMask contains the previous place4128kmp_affin_mask_t *tempMask;4129kmp_affin_mask_t *previousMask;4130KMP_CPU_ALLOC(tempMask);4131KMP_CPU_ZERO(tempMask);4132KMP_CPU_ALLOC(previousMask);4133KMP_CPU_ZERO(previousMask);4134int setSize = 0;41354136for (;;) {4137__kmp_process_place(&scan, affinity, maxOsId, tempMask, &setSize);41384139// valid follow sets are ',' ':' and EOL4140SKIP_WS(scan);4141if (*scan == '\0' || *scan == ',') {4142if (setSize > 0) {4143ADD_MASK(tempMask);4144}4145KMP_CPU_ZERO(tempMask);4146setSize = 0;4147if (*scan == '\0') {4148break;4149}4150scan++; // skip ','4151continue;4152}41534154KMP_ASSERT2(*scan == ':', "bad explicit places list");4155scan++; // skip ':'41564157// Read count parameter4158SKIP_WS(scan);4159KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");4160next = scan;4161SKIP_DIGITS(next);4162count = __kmp_str_to_int(scan, *next);4163KMP_ASSERT(count >= 0);4164scan = next;41654166// valid follow sets are ',' ':' and EOL4167SKIP_WS(scan);4168if (*scan == '\0' || *scan == ',') {4169stride = +1;4170} else {4171KMP_ASSERT2(*scan == ':', "bad explicit places list");4172scan++; // skip ':'41734174// Read stride parameter4175sign = +1;4176for (;;) {4177SKIP_WS(scan);4178if (*scan == '+') {4179scan++; // skip '+'4180continue;4181}4182if (*scan == '-') {4183sign *= -1;4184scan++; // skip '-'4185continue;4186}4187break;4188}4189SKIP_WS(scan);4190KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");4191next = scan;4192SKIP_DIGITS(next);4193stride = __kmp_str_to_int(scan, *next);4194KMP_DEBUG_ASSERT(stride >= 0);4195scan = next;4196stride *= sign;4197}41984199// Add places determined by initial_place : count : stride4200for (i = 0; i < count; i++) {4201if (setSize == 0) {4202break;4203}4204// Add the current place, then build the next place (tempMask) from that4205KMP_CPU_COPY(previousMask, tempMask);4206ADD_MASK(previousMask);4207KMP_CPU_ZERO(tempMask);4208setSize = 0;4209KMP_CPU_SET_ITERATE(j, previousMask) {4210if (!KMP_CPU_ISSET(j, previousMask)) {4211continue;4212}4213if ((j + stride > maxOsId) || (j + stride < 0) ||4214(!KMP_CPU_ISSET(j, __kmp_affin_fullMask)) ||4215(!KMP_CPU_ISSET(j + stride,4216KMP_CPU_INDEX(osId2Mask, j + stride)))) {4217if (i < count - 1) {4218KMP_AFF_WARNING(affinity, AffIgnoreInvalidProcID, j + stride);4219}4220continue;4221}4222KMP_CPU_SET(j + stride, tempMask);4223setSize++;4224}4225}4226KMP_CPU_ZERO(tempMask);4227setSize = 0;42284229// valid follow sets are ',' and EOL4230SKIP_WS(scan);4231if (*scan == '\0') {4232break;4233}4234if (*scan == ',') {4235scan++; // skip ','4236continue;4237}42384239KMP_ASSERT2(0, "bad explicit places list");4240}42414242*out_numMasks = nextNewMask;4243if (nextNewMask == 0) {4244*out_masks = NULL;4245KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);4246return;4247}4248KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);4249KMP_CPU_FREE(tempMask);4250KMP_CPU_FREE(previousMask);4251for (i = 0; i < nextNewMask; i++) {4252kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);4253kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);4254KMP_CPU_COPY(dest, src);4255}4256KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);4257}42584259#undef ADD_MASK4260#undef ADD_MASK_OSID42614262// This function figures out the deepest level at which there is at least one4263// cluster/core with more than one processing unit bound to it.4264static int __kmp_affinity_find_core_level(int nprocs, int bottom_level) {4265int core_level = 0;42664267for (int i = 0; i < nprocs; i++) {4268const kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);4269for (int j = bottom_level; j > 0; j--) {4270if (hw_thread.ids[j] > 0) {4271if (core_level < (j - 1)) {4272core_level = j - 1;4273}4274}4275}4276}4277return core_level;4278}42794280// This function counts number of clusters/cores at given level.4281static int __kmp_affinity_compute_ncores(int nprocs, int bottom_level,4282int core_level) {4283return __kmp_topology->get_count(core_level);4284}4285// This function finds to which cluster/core given processing unit is bound.4286static int __kmp_affinity_find_core(int proc, int bottom_level,4287int core_level) {4288int core = 0;4289KMP_DEBUG_ASSERT(proc >= 0 && proc < __kmp_topology->get_num_hw_threads());4290for (int i = 0; i <= proc; ++i) {4291if (i + 1 <= proc) {4292for (int j = 0; j <= core_level; ++j) {4293if (__kmp_topology->at(i + 1).sub_ids[j] !=4294__kmp_topology->at(i).sub_ids[j]) {4295core++;4296break;4297}4298}4299}4300}4301return core;4302}43034304// This function finds maximal number of processing units bound to a4305// cluster/core at given level.4306static int __kmp_affinity_max_proc_per_core(int nprocs, int bottom_level,4307int core_level) {4308if (core_level >= bottom_level)4309return 1;4310int thread_level = __kmp_topology->get_level(KMP_HW_THREAD);4311return __kmp_topology->calculate_ratio(thread_level, core_level);4312}43134314static int *procarr = NULL;4315static int __kmp_aff_depth = 0;4316static int *__kmp_osid_to_hwthread_map = NULL;43174318static void __kmp_affinity_get_mask_topology_info(const kmp_affin_mask_t *mask,4319kmp_affinity_ids_t &ids,4320kmp_affinity_attrs_t &attrs) {4321if (!KMP_AFFINITY_CAPABLE())4322return;43234324// Initiailze ids and attrs thread data4325for (int i = 0; i < KMP_HW_LAST; ++i)4326ids.ids[i] = kmp_hw_thread_t::UNKNOWN_ID;4327attrs = KMP_AFFINITY_ATTRS_UNKNOWN;43284329// Iterate through each os id within the mask and determine4330// the topology id and attribute information4331int cpu;4332int depth = __kmp_topology->get_depth();4333KMP_CPU_SET_ITERATE(cpu, mask) {4334int osid_idx = __kmp_osid_to_hwthread_map[cpu];4335ids.os_id = cpu;4336const kmp_hw_thread_t &hw_thread = __kmp_topology->at(osid_idx);4337for (int level = 0; level < depth; ++level) {4338kmp_hw_t type = __kmp_topology->get_type(level);4339int id = hw_thread.sub_ids[level];4340if (ids.ids[type] == kmp_hw_thread_t::UNKNOWN_ID || ids.ids[type] == id) {4341ids.ids[type] = id;4342} else {4343// This mask spans across multiple topology units, set it as such4344// and mark every level below as such as well.4345ids.ids[type] = kmp_hw_thread_t::MULTIPLE_ID;4346for (; level < depth; ++level) {4347kmp_hw_t type = __kmp_topology->get_type(level);4348ids.ids[type] = kmp_hw_thread_t::MULTIPLE_ID;4349}4350}4351}4352if (!attrs.valid) {4353attrs.core_type = hw_thread.attrs.get_core_type();4354attrs.core_eff = hw_thread.attrs.get_core_eff();4355attrs.valid = 1;4356} else {4357// This mask spans across multiple attributes, set it as such4358if (attrs.core_type != hw_thread.attrs.get_core_type())4359attrs.core_type = KMP_HW_CORE_TYPE_UNKNOWN;4360if (attrs.core_eff != hw_thread.attrs.get_core_eff())4361attrs.core_eff = kmp_hw_attr_t::UNKNOWN_CORE_EFF;4362}4363}4364}43654366static void __kmp_affinity_get_thread_topology_info(kmp_info_t *th) {4367if (!KMP_AFFINITY_CAPABLE())4368return;4369const kmp_affin_mask_t *mask = th->th.th_affin_mask;4370kmp_affinity_ids_t &ids = th->th.th_topology_ids;4371kmp_affinity_attrs_t &attrs = th->th.th_topology_attrs;4372__kmp_affinity_get_mask_topology_info(mask, ids, attrs);4373}43744375// Assign the topology information to each place in the place list4376// A thread can then grab not only its affinity mask, but the topology4377// information associated with that mask. e.g., Which socket is a thread on4378static void __kmp_affinity_get_topology_info(kmp_affinity_t &affinity) {4379if (!KMP_AFFINITY_CAPABLE())4380return;4381if (affinity.type != affinity_none) {4382KMP_ASSERT(affinity.num_os_id_masks);4383KMP_ASSERT(affinity.os_id_masks);4384}4385KMP_ASSERT(affinity.num_masks);4386KMP_ASSERT(affinity.masks);4387KMP_ASSERT(__kmp_affin_fullMask);43884389int max_cpu = __kmp_affin_fullMask->get_max_cpu();4390int num_hw_threads = __kmp_topology->get_num_hw_threads();43914392// Allocate thread topology information4393if (!affinity.ids) {4394affinity.ids = (kmp_affinity_ids_t *)__kmp_allocate(4395sizeof(kmp_affinity_ids_t) * affinity.num_masks);4396}4397if (!affinity.attrs) {4398affinity.attrs = (kmp_affinity_attrs_t *)__kmp_allocate(4399sizeof(kmp_affinity_attrs_t) * affinity.num_masks);4400}4401if (!__kmp_osid_to_hwthread_map) {4402// Want the +1 because max_cpu should be valid index into map4403__kmp_osid_to_hwthread_map =4404(int *)__kmp_allocate(sizeof(int) * (max_cpu + 1));4405}44064407// Create the OS proc to hardware thread map4408for (int hw_thread = 0; hw_thread < num_hw_threads; ++hw_thread) {4409int os_id = __kmp_topology->at(hw_thread).os_id;4410if (KMP_CPU_ISSET(os_id, __kmp_affin_fullMask))4411__kmp_osid_to_hwthread_map[os_id] = hw_thread;4412}44134414for (unsigned i = 0; i < affinity.num_masks; ++i) {4415kmp_affinity_ids_t &ids = affinity.ids[i];4416kmp_affinity_attrs_t &attrs = affinity.attrs[i];4417kmp_affin_mask_t *mask = KMP_CPU_INDEX(affinity.masks, i);4418__kmp_affinity_get_mask_topology_info(mask, ids, attrs);4419}4420}44214422// Called when __kmp_topology is ready4423static void __kmp_aux_affinity_initialize_other_data(kmp_affinity_t &affinity) {4424// Initialize other data structures which depend on the topology4425if (__kmp_topology && __kmp_topology->get_num_hw_threads()) {4426machine_hierarchy.init(__kmp_topology->get_num_hw_threads());4427__kmp_affinity_get_topology_info(affinity);4428#if KMP_WEIGHTED_ITERATIONS_SUPPORTED4429__kmp_first_osid_with_ecore = __kmp_get_first_osid_with_ecore();4430#endif4431}4432}44334434// Create a one element mask array (set of places) which only contains the4435// initial process's affinity mask4436static void __kmp_create_affinity_none_places(kmp_affinity_t &affinity) {4437KMP_ASSERT(__kmp_affin_fullMask != NULL);4438KMP_ASSERT(affinity.type == affinity_none);4439KMP_ASSERT(__kmp_avail_proc == __kmp_topology->get_num_hw_threads());4440affinity.num_masks = 1;4441KMP_CPU_ALLOC_ARRAY(affinity.masks, affinity.num_masks);4442kmp_affin_mask_t *dest = KMP_CPU_INDEX(affinity.masks, 0);4443KMP_CPU_COPY(dest, __kmp_affin_fullMask);4444__kmp_aux_affinity_initialize_other_data(affinity);4445}44464447static void __kmp_aux_affinity_initialize_masks(kmp_affinity_t &affinity) {4448// Create the "full" mask - this defines all of the processors that we4449// consider to be in the machine model. If respect is set, then it is the4450// initialization thread's affinity mask. Otherwise, it is all processors that4451// we know about on the machine.4452int verbose = affinity.flags.verbose;4453const char *env_var = affinity.env_var;44544455// Already initialized4456if (__kmp_affin_fullMask && __kmp_affin_origMask)4457return;44584459if (__kmp_affin_fullMask == NULL) {4460KMP_CPU_ALLOC(__kmp_affin_fullMask);4461}4462if (__kmp_affin_origMask == NULL) {4463KMP_CPU_ALLOC(__kmp_affin_origMask);4464}4465if (KMP_AFFINITY_CAPABLE()) {4466__kmp_get_system_affinity(__kmp_affin_fullMask, TRUE);4467// Make a copy before possible expanding to the entire machine mask4468__kmp_affin_origMask->copy(__kmp_affin_fullMask);4469if (affinity.flags.respect) {4470// Count the number of available processors.4471unsigned i;4472__kmp_avail_proc = 0;4473KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {4474if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {4475continue;4476}4477__kmp_avail_proc++;4478}4479if (__kmp_avail_proc > __kmp_xproc) {4480KMP_AFF_WARNING(affinity, ErrorInitializeAffinity);4481affinity.type = affinity_none;4482KMP_AFFINITY_DISABLE();4483return;4484}44854486if (verbose) {4487char buf[KMP_AFFIN_MASK_PRINT_LEN];4488__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,4489__kmp_affin_fullMask);4490KMP_INFORM(InitOSProcSetRespect, env_var, buf);4491}4492} else {4493if (verbose) {4494char buf[KMP_AFFIN_MASK_PRINT_LEN];4495__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,4496__kmp_affin_fullMask);4497KMP_INFORM(InitOSProcSetNotRespect, env_var, buf);4498}4499__kmp_avail_proc =4500__kmp_affinity_entire_machine_mask(__kmp_affin_fullMask);4501#if KMP_OS_WINDOWS4502if (__kmp_num_proc_groups <= 1) {4503// Copy expanded full mask if topology has single processor group4504__kmp_affin_origMask->copy(__kmp_affin_fullMask);4505}4506// Set the process affinity mask since threads' affinity4507// masks must be subset of process mask in Windows* OS4508__kmp_affin_fullMask->set_process_affinity(true);4509#endif4510}4511}4512}45134514static bool __kmp_aux_affinity_initialize_topology(kmp_affinity_t &affinity) {4515bool success = false;4516const char *env_var = affinity.env_var;4517kmp_i18n_id_t msg_id = kmp_i18n_null;4518int verbose = affinity.flags.verbose;45194520// For backward compatibility, setting KMP_CPUINFO_FILE =>4521// KMP_TOPOLOGY_METHOD=cpuinfo4522if ((__kmp_cpuinfo_file != NULL) &&4523(__kmp_affinity_top_method == affinity_top_method_all)) {4524__kmp_affinity_top_method = affinity_top_method_cpuinfo;4525}45264527if (__kmp_affinity_top_method == affinity_top_method_all) {4528// In the default code path, errors are not fatal - we just try using4529// another method. We only emit a warning message if affinity is on, or the4530// verbose flag is set, an the nowarnings flag was not set.4531#if KMP_USE_HWLOC4532if (!success &&4533__kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC) {4534if (!__kmp_hwloc_error) {4535success = __kmp_affinity_create_hwloc_map(&msg_id);4536if (!success && verbose) {4537KMP_INFORM(AffIgnoringHwloc, env_var);4538}4539} else if (verbose) {4540KMP_INFORM(AffIgnoringHwloc, env_var);4541}4542}4543#endif45444545#if KMP_ARCH_X86 || KMP_ARCH_X86_644546if (!success) {4547success = __kmp_affinity_create_x2apicid_map(&msg_id);4548if (!success && verbose && msg_id != kmp_i18n_null) {4549KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));4550}4551}4552if (!success) {4553success = __kmp_affinity_create_apicid_map(&msg_id);4554if (!success && verbose && msg_id != kmp_i18n_null) {4555KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));4556}4557}4558#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */45594560#if KMP_OS_LINUX || KMP_OS_AIX4561if (!success) {4562int line = 0;4563success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);4564if (!success && verbose && msg_id != kmp_i18n_null) {4565KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));4566}4567}4568#endif /* KMP_OS_LINUX */45694570#if KMP_GROUP_AFFINITY4571if (!success && (__kmp_num_proc_groups > 1)) {4572success = __kmp_affinity_create_proc_group_map(&msg_id);4573if (!success && verbose && msg_id != kmp_i18n_null) {4574KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));4575}4576}4577#endif /* KMP_GROUP_AFFINITY */45784579if (!success) {4580success = __kmp_affinity_create_flat_map(&msg_id);4581if (!success && verbose && msg_id != kmp_i18n_null) {4582KMP_INFORM(AffInfoStr, env_var, __kmp_i18n_catgets(msg_id));4583}4584KMP_ASSERT(success);4585}4586}45874588// If the user has specified that a paricular topology discovery method is to be4589// used, then we abort if that method fails. The exception is group affinity,4590// which might have been implicitly set.4591#if KMP_USE_HWLOC4592else if (__kmp_affinity_top_method == affinity_top_method_hwloc) {4593KMP_ASSERT(__kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC);4594success = __kmp_affinity_create_hwloc_map(&msg_id);4595if (!success) {4596KMP_ASSERT(msg_id != kmp_i18n_null);4597KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));4598}4599}4600#endif // KMP_USE_HWLOC46014602#if KMP_ARCH_X86 || KMP_ARCH_X86_644603else if (__kmp_affinity_top_method == affinity_top_method_x2apicid ||4604__kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {4605success = __kmp_affinity_create_x2apicid_map(&msg_id);4606if (!success) {4607KMP_ASSERT(msg_id != kmp_i18n_null);4608KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));4609}4610} else if (__kmp_affinity_top_method == affinity_top_method_apicid) {4611success = __kmp_affinity_create_apicid_map(&msg_id);4612if (!success) {4613KMP_ASSERT(msg_id != kmp_i18n_null);4614KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));4615}4616}4617#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */46184619else if (__kmp_affinity_top_method == affinity_top_method_cpuinfo) {4620int line = 0;4621success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);4622if (!success) {4623KMP_ASSERT(msg_id != kmp_i18n_null);4624const char *filename = __kmp_cpuinfo_get_filename();4625if (line > 0) {4626KMP_FATAL(FileLineMsgExiting, filename, line,4627__kmp_i18n_catgets(msg_id));4628} else {4629KMP_FATAL(FileMsgExiting, filename, __kmp_i18n_catgets(msg_id));4630}4631}4632}46334634#if KMP_GROUP_AFFINITY4635else if (__kmp_affinity_top_method == affinity_top_method_group) {4636success = __kmp_affinity_create_proc_group_map(&msg_id);4637KMP_ASSERT(success);4638if (!success) {4639KMP_ASSERT(msg_id != kmp_i18n_null);4640KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));4641}4642}4643#endif /* KMP_GROUP_AFFINITY */46444645else if (__kmp_affinity_top_method == affinity_top_method_flat) {4646success = __kmp_affinity_create_flat_map(&msg_id);4647// should not fail4648KMP_ASSERT(success);4649}46504651// Early exit if topology could not be created4652if (!__kmp_topology) {4653if (KMP_AFFINITY_CAPABLE()) {4654KMP_AFF_WARNING(affinity, ErrorInitializeAffinity);4655}4656if (nPackages > 0 && nCoresPerPkg > 0 && __kmp_nThreadsPerCore > 0 &&4657__kmp_ncores > 0) {4658__kmp_topology = kmp_topology_t::allocate(0, 0, NULL);4659__kmp_topology->canonicalize(nPackages, nCoresPerPkg,4660__kmp_nThreadsPerCore, __kmp_ncores);4661if (verbose) {4662__kmp_topology->print(env_var);4663}4664}4665return false;4666}46674668// Canonicalize, print (if requested), apply KMP_HW_SUBSET4669__kmp_topology->canonicalize();4670if (verbose)4671__kmp_topology->print(env_var);4672bool filtered = __kmp_topology->filter_hw_subset();4673if (filtered && verbose)4674__kmp_topology->print("KMP_HW_SUBSET");4675return success;4676}46774678static void __kmp_aux_affinity_initialize(kmp_affinity_t &affinity) {4679bool is_regular_affinity = (&affinity == &__kmp_affinity);4680bool is_hidden_helper_affinity = (&affinity == &__kmp_hh_affinity);4681const char *env_var = __kmp_get_affinity_env_var(affinity);46824683if (affinity.flags.initialized) {4684KMP_ASSERT(__kmp_affin_fullMask != NULL);4685return;4686}46874688if (is_regular_affinity && (!__kmp_affin_fullMask || !__kmp_affin_origMask))4689__kmp_aux_affinity_initialize_masks(affinity);46904691if (is_regular_affinity && !__kmp_topology) {4692bool success = __kmp_aux_affinity_initialize_topology(affinity);4693if (success) {4694KMP_ASSERT(__kmp_avail_proc == __kmp_topology->get_num_hw_threads());4695} else {4696affinity.type = affinity_none;4697KMP_AFFINITY_DISABLE();4698}4699}47004701// If KMP_AFFINITY=none, then only create the single "none" place4702// which is the process's initial affinity mask or the number of4703// hardware threads depending on respect,norespect4704if (affinity.type == affinity_none) {4705__kmp_create_affinity_none_places(affinity);4706#if KMP_USE_HIER_SCHED4707__kmp_dispatch_set_hierarchy_values();4708#endif4709affinity.flags.initialized = TRUE;4710return;4711}47124713__kmp_topology->set_granularity(affinity);4714int depth = __kmp_topology->get_depth();47154716// Create the table of masks, indexed by thread Id.4717unsigned numUnique;4718int numAddrs = __kmp_topology->get_num_hw_threads();4719// If OMP_PLACES=cores:<attribute> specified, then attempt4720// to make OS Id mask table using those attributes4721if (affinity.core_attr_gran.valid) {4722__kmp_create_os_id_masks(&numUnique, affinity, [&](int idx) {4723KMP_ASSERT(idx >= -1);4724for (int i = idx + 1; i < numAddrs; ++i)4725if (__kmp_topology->at(i).attrs.contains(affinity.core_attr_gran))4726return i;4727return numAddrs;4728});4729if (!affinity.os_id_masks) {4730const char *core_attribute;4731if (affinity.core_attr_gran.core_eff != kmp_hw_attr_t::UNKNOWN_CORE_EFF)4732core_attribute = "core_efficiency";4733else4734core_attribute = "core_type";4735KMP_AFF_WARNING(affinity, AffIgnoringNotAvailable, env_var,4736core_attribute,4737__kmp_hw_get_catalog_string(KMP_HW_CORE, /*plural=*/true))4738}4739}4740// If core attributes did not work, or none were specified,4741// then make OS Id mask table using typical incremental way.4742if (!affinity.os_id_masks) {4743__kmp_create_os_id_masks(&numUnique, affinity, [](int idx) {4744KMP_ASSERT(idx >= -1);4745return idx + 1;4746});4747}4748if (affinity.gran_levels == 0) {4749KMP_DEBUG_ASSERT((int)numUnique == __kmp_avail_proc);4750}47514752switch (affinity.type) {47534754case affinity_explicit:4755KMP_DEBUG_ASSERT(affinity.proclist != NULL);4756if (is_hidden_helper_affinity ||4757__kmp_nested_proc_bind.bind_types[0] == proc_bind_intel) {4758__kmp_affinity_process_proclist(affinity);4759} else {4760__kmp_affinity_process_placelist(affinity);4761}4762if (affinity.num_masks == 0) {4763KMP_AFF_WARNING(affinity, AffNoValidProcID);4764affinity.type = affinity_none;4765__kmp_create_affinity_none_places(affinity);4766affinity.flags.initialized = TRUE;4767return;4768}4769break;47704771// The other affinity types rely on sorting the hardware threads according to4772// some permutation of the machine topology tree. Set affinity.compact4773// and affinity.offset appropriately, then jump to a common code4774// fragment to do the sort and create the array of affinity masks.4775case affinity_logical:4776affinity.compact = 0;4777if (affinity.offset) {4778affinity.offset =4779__kmp_nThreadsPerCore * affinity.offset % __kmp_avail_proc;4780}4781goto sortTopology;47824783case affinity_physical:4784if (__kmp_nThreadsPerCore > 1) {4785affinity.compact = 1;4786if (affinity.compact >= depth) {4787affinity.compact = 0;4788}4789} else {4790affinity.compact = 0;4791}4792if (affinity.offset) {4793affinity.offset =4794__kmp_nThreadsPerCore * affinity.offset % __kmp_avail_proc;4795}4796goto sortTopology;47974798case affinity_scatter:4799if (affinity.compact >= depth) {4800affinity.compact = 0;4801} else {4802affinity.compact = depth - 1 - affinity.compact;4803}4804goto sortTopology;48054806case affinity_compact:4807if (affinity.compact >= depth) {4808affinity.compact = depth - 1;4809}4810goto sortTopology;48114812case affinity_balanced:4813if (depth <= 1 || is_hidden_helper_affinity) {4814KMP_AFF_WARNING(affinity, AffBalancedNotAvail, env_var);4815affinity.type = affinity_none;4816__kmp_create_affinity_none_places(affinity);4817affinity.flags.initialized = TRUE;4818return;4819} else if (!__kmp_topology->is_uniform()) {4820// Save the depth for further usage4821__kmp_aff_depth = depth;48224823int core_level =4824__kmp_affinity_find_core_level(__kmp_avail_proc, depth - 1);4825int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc, depth - 1,4826core_level);4827int maxprocpercore = __kmp_affinity_max_proc_per_core(4828__kmp_avail_proc, depth - 1, core_level);48294830int nproc = ncores * maxprocpercore;4831if ((nproc < 2) || (nproc < __kmp_avail_proc)) {4832KMP_AFF_WARNING(affinity, AffBalancedNotAvail, env_var);4833affinity.type = affinity_none;4834__kmp_create_affinity_none_places(affinity);4835affinity.flags.initialized = TRUE;4836return;4837}48384839procarr = (int *)__kmp_allocate(sizeof(int) * nproc);4840for (int i = 0; i < nproc; i++) {4841procarr[i] = -1;4842}48434844int lastcore = -1;4845int inlastcore = 0;4846for (int i = 0; i < __kmp_avail_proc; i++) {4847int proc = __kmp_topology->at(i).os_id;4848int core = __kmp_affinity_find_core(i, depth - 1, core_level);48494850if (core == lastcore) {4851inlastcore++;4852} else {4853inlastcore = 0;4854}4855lastcore = core;48564857procarr[core * maxprocpercore + inlastcore] = proc;4858}4859}4860if (affinity.compact >= depth) {4861affinity.compact = depth - 1;4862}48634864sortTopology:4865// Allocate the gtid->affinity mask table.4866if (affinity.flags.dups) {4867affinity.num_masks = __kmp_avail_proc;4868} else {4869affinity.num_masks = numUnique;4870}48714872if ((__kmp_nested_proc_bind.bind_types[0] != proc_bind_intel) &&4873(__kmp_affinity_num_places > 0) &&4874((unsigned)__kmp_affinity_num_places < affinity.num_masks) &&4875!is_hidden_helper_affinity) {4876affinity.num_masks = __kmp_affinity_num_places;4877}48784879KMP_CPU_ALLOC_ARRAY(affinity.masks, affinity.num_masks);48804881// Sort the topology table according to the current setting of4882// affinity.compact, then fill out affinity.masks.4883__kmp_topology->sort_compact(affinity);4884{4885int i;4886unsigned j;4887int num_hw_threads = __kmp_topology->get_num_hw_threads();4888kmp_full_mask_modifier_t full_mask;4889for (i = 0, j = 0; i < num_hw_threads; i++) {4890if ((!affinity.flags.dups) && (!__kmp_topology->at(i).leader)) {4891continue;4892}4893int osId = __kmp_topology->at(i).os_id;48944895kmp_affin_mask_t *src = KMP_CPU_INDEX(affinity.os_id_masks, osId);4896kmp_affin_mask_t *dest = KMP_CPU_INDEX(affinity.masks, j);4897KMP_ASSERT(KMP_CPU_ISSET(osId, src));4898KMP_CPU_COPY(dest, src);4899full_mask.include(src);4900if (++j >= affinity.num_masks) {4901break;4902}4903}4904KMP_DEBUG_ASSERT(j == affinity.num_masks);4905// See if the places list further restricts or changes the full mask4906if (full_mask.restrict_to_mask() && affinity.flags.verbose) {4907__kmp_topology->print(env_var);4908}4909}4910// Sort the topology back using ids4911__kmp_topology->sort_ids();4912break;49134914default:4915KMP_ASSERT2(0, "Unexpected affinity setting");4916}4917__kmp_aux_affinity_initialize_other_data(affinity);4918affinity.flags.initialized = TRUE;4919}49204921void __kmp_affinity_initialize(kmp_affinity_t &affinity) {4922// Much of the code above was written assuming that if a machine was not4923// affinity capable, then affinity type == affinity_none.4924// We now explicitly represent this as affinity type == affinity_disabled.4925// There are too many checks for affinity type == affinity_none in this code.4926// Instead of trying to change them all, check if4927// affinity type == affinity_disabled, and if so, slam it with affinity_none,4928// call the real initialization routine, then restore affinity type to4929// affinity_disabled.4930int disabled = (affinity.type == affinity_disabled);4931if (!KMP_AFFINITY_CAPABLE())4932KMP_ASSERT(disabled);4933if (disabled)4934affinity.type = affinity_none;4935__kmp_aux_affinity_initialize(affinity);4936if (disabled)4937affinity.type = affinity_disabled;4938}49394940void __kmp_affinity_uninitialize(void) {4941for (kmp_affinity_t *affinity : __kmp_affinities) {4942if (affinity->masks != NULL)4943KMP_CPU_FREE_ARRAY(affinity->masks, affinity->num_masks);4944if (affinity->os_id_masks != NULL)4945KMP_CPU_FREE_ARRAY(affinity->os_id_masks, affinity->num_os_id_masks);4946if (affinity->proclist != NULL)4947__kmp_free(affinity->proclist);4948if (affinity->ids != NULL)4949__kmp_free(affinity->ids);4950if (affinity->attrs != NULL)4951__kmp_free(affinity->attrs);4952*affinity = KMP_AFFINITY_INIT(affinity->env_var);4953}4954if (__kmp_affin_origMask != NULL) {4955if (KMP_AFFINITY_CAPABLE()) {4956#if KMP_OS_AIX4957// Uninitialize by unbinding the thread.4958bindprocessor(BINDTHREAD, thread_self(), PROCESSOR_CLASS_ANY);4959#else4960__kmp_set_system_affinity(__kmp_affin_origMask, FALSE);4961#endif4962}4963KMP_CPU_FREE(__kmp_affin_origMask);4964__kmp_affin_origMask = NULL;4965}4966__kmp_affinity_num_places = 0;4967if (procarr != NULL) {4968__kmp_free(procarr);4969procarr = NULL;4970}4971if (__kmp_osid_to_hwthread_map) {4972__kmp_free(__kmp_osid_to_hwthread_map);4973__kmp_osid_to_hwthread_map = NULL;4974}4975#if KMP_USE_HWLOC4976if (__kmp_hwloc_topology != NULL) {4977hwloc_topology_destroy(__kmp_hwloc_topology);4978__kmp_hwloc_topology = NULL;4979}4980#endif4981if (__kmp_hw_subset) {4982kmp_hw_subset_t::deallocate(__kmp_hw_subset);4983__kmp_hw_subset = nullptr;4984}4985if (__kmp_topology) {4986kmp_topology_t::deallocate(__kmp_topology);4987__kmp_topology = nullptr;4988}4989KMPAffinity::destroy_api();4990}49914992static void __kmp_select_mask_by_gtid(int gtid, const kmp_affinity_t *affinity,4993int *place, kmp_affin_mask_t **mask) {4994int mask_idx;4995bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);4996if (is_hidden_helper)4997// The first gtid is the regular primary thread, the second gtid is the main4998// thread of hidden team which does not participate in task execution.4999mask_idx = gtid - 2;5000else5001mask_idx = __kmp_adjust_gtid_for_hidden_helpers(gtid);5002KMP_DEBUG_ASSERT(affinity->num_masks > 0);5003*place = (mask_idx + affinity->offset) % affinity->num_masks;5004*mask = KMP_CPU_INDEX(affinity->masks, *place);5005}50065007// This function initializes the per-thread data concerning affinity including5008// the mask and topology information5009void __kmp_affinity_set_init_mask(int gtid, int isa_root) {50105011kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);50125013// Set the thread topology information to default of unknown5014for (int id = 0; id < KMP_HW_LAST; ++id)5015th->th.th_topology_ids.ids[id] = kmp_hw_thread_t::UNKNOWN_ID;5016th->th.th_topology_attrs = KMP_AFFINITY_ATTRS_UNKNOWN;50175018if (!KMP_AFFINITY_CAPABLE()) {5019return;5020}50215022if (th->th.th_affin_mask == NULL) {5023KMP_CPU_ALLOC(th->th.th_affin_mask);5024} else {5025KMP_CPU_ZERO(th->th.th_affin_mask);5026}50275028// Copy the thread mask to the kmp_info_t structure. If5029// __kmp_affinity.type == affinity_none, copy the "full" mask, i.e.5030// one that has all of the OS proc ids set, or if5031// __kmp_affinity.flags.respect is set, then the full mask is the5032// same as the mask of the initialization thread.5033kmp_affin_mask_t *mask;5034int i;5035const kmp_affinity_t *affinity;5036bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);50375038if (is_hidden_helper)5039affinity = &__kmp_hh_affinity;5040else5041affinity = &__kmp_affinity;50425043if (KMP_AFFINITY_NON_PROC_BIND || is_hidden_helper) {5044if ((affinity->type == affinity_none) ||5045(affinity->type == affinity_balanced) ||5046KMP_HIDDEN_HELPER_MAIN_THREAD(gtid)) {5047#if KMP_GROUP_AFFINITY5048if (__kmp_num_proc_groups > 1) {5049return;5050}5051#endif5052KMP_ASSERT(__kmp_affin_fullMask != NULL);5053i = 0;5054mask = __kmp_affin_fullMask;5055} else {5056__kmp_select_mask_by_gtid(gtid, affinity, &i, &mask);5057}5058} else {5059if (!isa_root || __kmp_nested_proc_bind.bind_types[0] == proc_bind_false) {5060#if KMP_GROUP_AFFINITY5061if (__kmp_num_proc_groups > 1) {5062return;5063}5064#endif5065KMP_ASSERT(__kmp_affin_fullMask != NULL);5066i = KMP_PLACE_ALL;5067mask = __kmp_affin_fullMask;5068} else {5069__kmp_select_mask_by_gtid(gtid, affinity, &i, &mask);5070}5071}50725073th->th.th_current_place = i;5074if (isa_root && !is_hidden_helper) {5075th->th.th_new_place = i;5076th->th.th_first_place = 0;5077th->th.th_last_place = affinity->num_masks - 1;5078} else if (KMP_AFFINITY_NON_PROC_BIND) {5079// When using a Non-OMP_PROC_BIND affinity method,5080// set all threads' place-partition-var to the entire place list5081th->th.th_first_place = 0;5082th->th.th_last_place = affinity->num_masks - 1;5083}5084// Copy topology information associated with the place5085if (i >= 0) {5086th->th.th_topology_ids = __kmp_affinity.ids[i];5087th->th.th_topology_attrs = __kmp_affinity.attrs[i];5088}50895090if (i == KMP_PLACE_ALL) {5091KA_TRACE(100, ("__kmp_affinity_set_init_mask: setting T#%d to all places\n",5092gtid));5093} else {5094KA_TRACE(100, ("__kmp_affinity_set_init_mask: setting T#%d to place %d\n",5095gtid, i));5096}50975098KMP_CPU_COPY(th->th.th_affin_mask, mask);5099}51005101void __kmp_affinity_bind_init_mask(int gtid) {5102if (!KMP_AFFINITY_CAPABLE()) {5103return;5104}5105kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);5106const kmp_affinity_t *affinity;5107const char *env_var;5108bool is_hidden_helper = KMP_HIDDEN_HELPER_THREAD(gtid);51095110if (is_hidden_helper)5111affinity = &__kmp_hh_affinity;5112else5113affinity = &__kmp_affinity;5114env_var = __kmp_get_affinity_env_var(*affinity, /*for_binding=*/true);5115/* to avoid duplicate printing (will be correctly printed on barrier) */5116if (affinity->flags.verbose && (affinity->type == affinity_none ||5117(th->th.th_current_place != KMP_PLACE_ALL &&5118affinity->type != affinity_balanced)) &&5119!KMP_HIDDEN_HELPER_MAIN_THREAD(gtid)) {5120char buf[KMP_AFFIN_MASK_PRINT_LEN];5121__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5122th->th.th_affin_mask);5123KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),5124gtid, buf);5125}51265127#if KMP_OS_WINDOWS5128// On Windows* OS, the process affinity mask might have changed. If the user5129// didn't request affinity and this call fails, just continue silently.5130// See CQ171393.5131if (affinity->type == affinity_none) {5132__kmp_set_system_affinity(th->th.th_affin_mask, FALSE);5133} else5134#endif5135#ifndef KMP_OS_AIX5136// Do not set the full mask as the init mask on AIX.5137__kmp_set_system_affinity(th->th.th_affin_mask, TRUE);5138#endif5139}51405141void __kmp_affinity_bind_place(int gtid) {5142// Hidden helper threads should not be affected by OMP_PLACES/OMP_PROC_BIND5143if (!KMP_AFFINITY_CAPABLE() || KMP_HIDDEN_HELPER_THREAD(gtid)) {5144return;5145}51465147kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);51485149KA_TRACE(100, ("__kmp_affinity_bind_place: binding T#%d to place %d (current "5150"place = %d)\n",5151gtid, th->th.th_new_place, th->th.th_current_place));51525153// Check that the new place is within this thread's partition.5154KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);5155KMP_ASSERT(th->th.th_new_place >= 0);5156KMP_ASSERT((unsigned)th->th.th_new_place <= __kmp_affinity.num_masks);5157if (th->th.th_first_place <= th->th.th_last_place) {5158KMP_ASSERT((th->th.th_new_place >= th->th.th_first_place) &&5159(th->th.th_new_place <= th->th.th_last_place));5160} else {5161KMP_ASSERT((th->th.th_new_place <= th->th.th_first_place) ||5162(th->th.th_new_place >= th->th.th_last_place));5163}51645165// Copy the thread mask to the kmp_info_t structure,5166// and set this thread's affinity.5167kmp_affin_mask_t *mask =5168KMP_CPU_INDEX(__kmp_affinity.masks, th->th.th_new_place);5169KMP_CPU_COPY(th->th.th_affin_mask, mask);5170th->th.th_current_place = th->th.th_new_place;51715172if (__kmp_affinity.flags.verbose) {5173char buf[KMP_AFFIN_MASK_PRINT_LEN];5174__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5175th->th.th_affin_mask);5176KMP_INFORM(BoundToOSProcSet, "OMP_PROC_BIND", (kmp_int32)getpid(),5177__kmp_gettid(), gtid, buf);5178}5179__kmp_set_system_affinity(th->th.th_affin_mask, TRUE);5180}51815182int __kmp_aux_set_affinity(void **mask) {5183int gtid;5184kmp_info_t *th;5185int retval;51865187if (!KMP_AFFINITY_CAPABLE()) {5188return -1;5189}51905191gtid = __kmp_entry_gtid();5192KA_TRACE(51931000, (""); {5194char buf[KMP_AFFIN_MASK_PRINT_LEN];5195__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5196(kmp_affin_mask_t *)(*mask));5197__kmp_debug_printf(5198"kmp_set_affinity: setting affinity mask for thread %d = %s\n",5199gtid, buf);5200});52015202if (__kmp_env_consistency_check) {5203if ((mask == NULL) || (*mask == NULL)) {5204KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");5205} else {5206unsigned proc;5207int num_procs = 0;52085209KMP_CPU_SET_ITERATE(proc, ((kmp_affin_mask_t *)(*mask))) {5210if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {5211KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");5212}5213if (!KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask))) {5214continue;5215}5216num_procs++;5217}5218if (num_procs == 0) {5219KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");5220}52215222#if KMP_GROUP_AFFINITY5223if (__kmp_get_proc_group((kmp_affin_mask_t *)(*mask)) < 0) {5224KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");5225}5226#endif /* KMP_GROUP_AFFINITY */5227}5228}52295230th = __kmp_threads[gtid];5231KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);5232retval = __kmp_set_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);5233if (retval == 0) {5234KMP_CPU_COPY(th->th.th_affin_mask, (kmp_affin_mask_t *)(*mask));5235}52365237th->th.th_current_place = KMP_PLACE_UNDEFINED;5238th->th.th_new_place = KMP_PLACE_UNDEFINED;5239th->th.th_first_place = 0;5240th->th.th_last_place = __kmp_affinity.num_masks - 1;52415242// Turn off 4.0 affinity for the current tread at this parallel level.5243th->th.th_current_task->td_icvs.proc_bind = proc_bind_false;52445245return retval;5246}52475248int __kmp_aux_get_affinity(void **mask) {5249int gtid;5250int retval;5251#if KMP_OS_WINDOWS || KMP_OS_AIX || KMP_DEBUG5252kmp_info_t *th;5253#endif5254if (!KMP_AFFINITY_CAPABLE()) {5255return -1;5256}52575258gtid = __kmp_entry_gtid();5259#if KMP_OS_WINDOWS || KMP_OS_AIX || KMP_DEBUG5260th = __kmp_threads[gtid];5261#else5262(void)gtid; // unused variable5263#endif5264KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);52655266KA_TRACE(52671000, (""); {5268char buf[KMP_AFFIN_MASK_PRINT_LEN];5269__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5270th->th.th_affin_mask);5271__kmp_printf(5272"kmp_get_affinity: stored affinity mask for thread %d = %s\n", gtid,5273buf);5274});52755276if (__kmp_env_consistency_check) {5277if ((mask == NULL) || (*mask == NULL)) {5278KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity");5279}5280}52815282#if !KMP_OS_WINDOWS && !KMP_OS_AIX52835284retval = __kmp_get_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);5285KA_TRACE(52861000, (""); {5287char buf[KMP_AFFIN_MASK_PRINT_LEN];5288__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5289(kmp_affin_mask_t *)(*mask));5290__kmp_printf(5291"kmp_get_affinity: system affinity mask for thread %d = %s\n", gtid,5292buf);5293});5294return retval;52955296#else5297(void)retval;52985299KMP_CPU_COPY((kmp_affin_mask_t *)(*mask), th->th.th_affin_mask);5300return 0;53015302#endif /* !KMP_OS_WINDOWS && !KMP_OS_AIX */5303}53045305int __kmp_aux_get_affinity_max_proc() {5306if (!KMP_AFFINITY_CAPABLE()) {5307return 0;5308}5309#if KMP_GROUP_AFFINITY5310if (__kmp_num_proc_groups > 1) {5311return (int)(__kmp_num_proc_groups * sizeof(DWORD_PTR) * CHAR_BIT);5312}5313#endif5314return __kmp_xproc;5315}53165317int __kmp_aux_set_affinity_mask_proc(int proc, void **mask) {5318if (!KMP_AFFINITY_CAPABLE()) {5319return -1;5320}53215322KA_TRACE(53231000, (""); {5324int gtid = __kmp_entry_gtid();5325char buf[KMP_AFFIN_MASK_PRINT_LEN];5326__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5327(kmp_affin_mask_t *)(*mask));5328__kmp_debug_printf("kmp_set_affinity_mask_proc: setting proc %d in "5329"affinity mask for thread %d = %s\n",5330proc, gtid, buf);5331});53325333if (__kmp_env_consistency_check) {5334if ((mask == NULL) || (*mask == NULL)) {5335KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity_mask_proc");5336}5337}53385339if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {5340return -1;5341}5342if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {5343return -2;5344}53455346KMP_CPU_SET(proc, (kmp_affin_mask_t *)(*mask));5347return 0;5348}53495350int __kmp_aux_unset_affinity_mask_proc(int proc, void **mask) {5351if (!KMP_AFFINITY_CAPABLE()) {5352return -1;5353}53545355KA_TRACE(53561000, (""); {5357int gtid = __kmp_entry_gtid();5358char buf[KMP_AFFIN_MASK_PRINT_LEN];5359__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5360(kmp_affin_mask_t *)(*mask));5361__kmp_debug_printf("kmp_unset_affinity_mask_proc: unsetting proc %d in "5362"affinity mask for thread %d = %s\n",5363proc, gtid, buf);5364});53655366if (__kmp_env_consistency_check) {5367if ((mask == NULL) || (*mask == NULL)) {5368KMP_FATAL(AffinityInvalidMask, "kmp_unset_affinity_mask_proc");5369}5370}53715372if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {5373return -1;5374}5375if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {5376return -2;5377}53785379KMP_CPU_CLR(proc, (kmp_affin_mask_t *)(*mask));5380return 0;5381}53825383int __kmp_aux_get_affinity_mask_proc(int proc, void **mask) {5384if (!KMP_AFFINITY_CAPABLE()) {5385return -1;5386}53875388KA_TRACE(53891000, (""); {5390int gtid = __kmp_entry_gtid();5391char buf[KMP_AFFIN_MASK_PRINT_LEN];5392__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,5393(kmp_affin_mask_t *)(*mask));5394__kmp_debug_printf("kmp_get_affinity_mask_proc: getting proc %d in "5395"affinity mask for thread %d = %s\n",5396proc, gtid, buf);5397});53985399if (__kmp_env_consistency_check) {5400if ((mask == NULL) || (*mask == NULL)) {5401KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity_mask_proc");5402}5403}54045405if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {5406return -1;5407}5408if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {5409return 0;5410}54115412return KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask));5413}54145415#if KMP_WEIGHTED_ITERATIONS_SUPPORTED5416// Returns first os proc id with ATOM core5417int __kmp_get_first_osid_with_ecore(void) {5418int low = 0;5419int high = __kmp_topology->get_num_hw_threads() - 1;5420int mid = 0;5421while (high - low > 1) {5422mid = (high + low) / 2;5423if (__kmp_topology->at(mid).attrs.get_core_type() ==5424KMP_HW_CORE_TYPE_CORE) {5425low = mid + 1;5426} else {5427high = mid;5428}5429}5430if (__kmp_topology->at(mid).attrs.get_core_type() == KMP_HW_CORE_TYPE_ATOM) {5431return mid;5432}5433return -1;5434}5435#endif54365437// Dynamic affinity settings - Affinity balanced5438void __kmp_balanced_affinity(kmp_info_t *th, int nthreads) {5439KMP_DEBUG_ASSERT(th);5440bool fine_gran = true;5441int tid = th->th.th_info.ds.ds_tid;5442const char *env_var = "KMP_AFFINITY";54435444// Do not perform balanced affinity for the hidden helper threads5445if (KMP_HIDDEN_HELPER_THREAD(__kmp_gtid_from_thread(th)))5446return;54475448switch (__kmp_affinity.gran) {5449case KMP_HW_THREAD:5450break;5451case KMP_HW_CORE:5452if (__kmp_nThreadsPerCore > 1) {5453fine_gran = false;5454}5455break;5456case KMP_HW_SOCKET:5457if (nCoresPerPkg > 1) {5458fine_gran = false;5459}5460break;5461default:5462fine_gran = false;5463}54645465if (__kmp_topology->is_uniform()) {5466int coreID;5467int threadID;5468// Number of hyper threads per core in HT machine5469int __kmp_nth_per_core = __kmp_avail_proc / __kmp_ncores;5470// Number of cores5471int ncores = __kmp_ncores;5472if ((nPackages > 1) && (__kmp_nth_per_core <= 1)) {5473__kmp_nth_per_core = __kmp_avail_proc / nPackages;5474ncores = nPackages;5475}5476// How many threads will be bound to each core5477int chunk = nthreads / ncores;5478// How many cores will have an additional thread bound to it - "big cores"5479int big_cores = nthreads % ncores;5480// Number of threads on the big cores5481int big_nth = (chunk + 1) * big_cores;5482if (tid < big_nth) {5483coreID = tid / (chunk + 1);5484threadID = (tid % (chunk + 1)) % __kmp_nth_per_core;5485} else { // tid >= big_nth5486coreID = (tid - big_cores) / chunk;5487threadID = ((tid - big_cores) % chunk) % __kmp_nth_per_core;5488}5489KMP_DEBUG_ASSERT2(KMP_AFFINITY_CAPABLE(),5490"Illegal set affinity operation when not capable");54915492kmp_affin_mask_t *mask = th->th.th_affin_mask;5493KMP_CPU_ZERO(mask);54945495if (fine_gran) {5496int osID =5497__kmp_topology->at(coreID * __kmp_nth_per_core + threadID).os_id;5498KMP_CPU_SET(osID, mask);5499} else {5500for (int i = 0; i < __kmp_nth_per_core; i++) {5501int osID;5502osID = __kmp_topology->at(coreID * __kmp_nth_per_core + i).os_id;5503KMP_CPU_SET(osID, mask);5504}5505}5506if (__kmp_affinity.flags.verbose) {5507char buf[KMP_AFFIN_MASK_PRINT_LEN];5508__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);5509KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),5510tid, buf);5511}5512__kmp_affinity_get_thread_topology_info(th);5513__kmp_set_system_affinity(mask, TRUE);5514} else { // Non-uniform topology55155516kmp_affin_mask_t *mask = th->th.th_affin_mask;5517KMP_CPU_ZERO(mask);55185519int core_level =5520__kmp_affinity_find_core_level(__kmp_avail_proc, __kmp_aff_depth - 1);5521int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc,5522__kmp_aff_depth - 1, core_level);5523int nth_per_core = __kmp_affinity_max_proc_per_core(5524__kmp_avail_proc, __kmp_aff_depth - 1, core_level);55255526// For performance gain consider the special case nthreads ==5527// __kmp_avail_proc5528if (nthreads == __kmp_avail_proc) {5529if (fine_gran) {5530int osID = __kmp_topology->at(tid).os_id;5531KMP_CPU_SET(osID, mask);5532} else {5533int core =5534__kmp_affinity_find_core(tid, __kmp_aff_depth - 1, core_level);5535for (int i = 0; i < __kmp_avail_proc; i++) {5536int osID = __kmp_topology->at(i).os_id;5537if (__kmp_affinity_find_core(i, __kmp_aff_depth - 1, core_level) ==5538core) {5539KMP_CPU_SET(osID, mask);5540}5541}5542}5543} else if (nthreads <= ncores) {55445545int core = 0;5546for (int i = 0; i < ncores; i++) {5547// Check if this core from procarr[] is in the mask5548int in_mask = 0;5549for (int j = 0; j < nth_per_core; j++) {5550if (procarr[i * nth_per_core + j] != -1) {5551in_mask = 1;5552break;5553}5554}5555if (in_mask) {5556if (tid == core) {5557for (int j = 0; j < nth_per_core; j++) {5558int osID = procarr[i * nth_per_core + j];5559if (osID != -1) {5560KMP_CPU_SET(osID, mask);5561// For fine granularity it is enough to set the first available5562// osID for this core5563if (fine_gran) {5564break;5565}5566}5567}5568break;5569} else {5570core++;5571}5572}5573}5574} else { // nthreads > ncores5575// Array to save the number of processors at each core5576int *nproc_at_core = (int *)KMP_ALLOCA(sizeof(int) * ncores);5577// Array to save the number of cores with "x" available processors;5578int *ncores_with_x_procs =5579(int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));5580// Array to save the number of cores with # procs from x to nth_per_core5581int *ncores_with_x_to_max_procs =5582(int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));55835584for (int i = 0; i <= nth_per_core; i++) {5585ncores_with_x_procs[i] = 0;5586ncores_with_x_to_max_procs[i] = 0;5587}55885589for (int i = 0; i < ncores; i++) {5590int cnt = 0;5591for (int j = 0; j < nth_per_core; j++) {5592if (procarr[i * nth_per_core + j] != -1) {5593cnt++;5594}5595}5596nproc_at_core[i] = cnt;5597ncores_with_x_procs[cnt]++;5598}55995600for (int i = 0; i <= nth_per_core; i++) {5601for (int j = i; j <= nth_per_core; j++) {5602ncores_with_x_to_max_procs[i] += ncores_with_x_procs[j];5603}5604}56055606// Max number of processors5607int nproc = nth_per_core * ncores;5608// An array to keep number of threads per each context5609int *newarr = (int *)__kmp_allocate(sizeof(int) * nproc);5610for (int i = 0; i < nproc; i++) {5611newarr[i] = 0;5612}56135614int nth = nthreads;5615int flag = 0;5616while (nth > 0) {5617for (int j = 1; j <= nth_per_core; j++) {5618int cnt = ncores_with_x_to_max_procs[j];5619for (int i = 0; i < ncores; i++) {5620// Skip the core with 0 processors5621if (nproc_at_core[i] == 0) {5622continue;5623}5624for (int k = 0; k < nth_per_core; k++) {5625if (procarr[i * nth_per_core + k] != -1) {5626if (newarr[i * nth_per_core + k] == 0) {5627newarr[i * nth_per_core + k] = 1;5628cnt--;5629nth--;5630break;5631} else {5632if (flag != 0) {5633newarr[i * nth_per_core + k]++;5634cnt--;5635nth--;5636break;5637}5638}5639}5640}5641if (cnt == 0 || nth == 0) {5642break;5643}5644}5645if (nth == 0) {5646break;5647}5648}5649flag = 1;5650}5651int sum = 0;5652for (int i = 0; i < nproc; i++) {5653sum += newarr[i];5654if (sum > tid) {5655if (fine_gran) {5656int osID = procarr[i];5657KMP_CPU_SET(osID, mask);5658} else {5659int coreID = i / nth_per_core;5660for (int ii = 0; ii < nth_per_core; ii++) {5661int osID = procarr[coreID * nth_per_core + ii];5662if (osID != -1) {5663KMP_CPU_SET(osID, mask);5664}5665}5666}5667break;5668}5669}5670__kmp_free(newarr);5671}56725673if (__kmp_affinity.flags.verbose) {5674char buf[KMP_AFFIN_MASK_PRINT_LEN];5675__kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);5676KMP_INFORM(BoundToOSProcSet, env_var, (kmp_int32)getpid(), __kmp_gettid(),5677tid, buf);5678}5679__kmp_affinity_get_thread_topology_info(th);5680__kmp_set_system_affinity(mask, TRUE);5681}5682}56835684#if KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_NETBSD || KMP_OS_DRAGONFLY || \5685KMP_OS_AIX5686// We don't need this entry for Windows because5687// there is GetProcessAffinityMask() api5688//5689// The intended usage is indicated by these steps:5690// 1) The user gets the current affinity mask5691// 2) Then sets the affinity by calling this function5692// 3) Error check the return value5693// 4) Use non-OpenMP parallelization5694// 5) Reset the affinity to what was stored in step 1)5695#ifdef __cplusplus5696extern "C"5697#endif5698int5699kmp_set_thread_affinity_mask_initial()5700// the function returns 0 on success,5701// -1 if we cannot bind thread5702// >0 (errno) if an error happened during binding5703{5704int gtid = __kmp_get_gtid();5705if (gtid < 0) {5706// Do not touch non-omp threads5707KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "5708"non-omp thread, returning\n"));5709return -1;5710}5711if (!KMP_AFFINITY_CAPABLE() || !__kmp_init_middle) {5712KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "5713"affinity not initialized, returning\n"));5714return -1;5715}5716KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "5717"set full mask for thread %d\n",5718gtid));5719KMP_DEBUG_ASSERT(__kmp_affin_fullMask != NULL);5720#if KMP_OS_AIX5721return bindprocessor(BINDTHREAD, thread_self(), PROCESSOR_CLASS_ANY);5722#else5723return __kmp_set_system_affinity(__kmp_affin_fullMask, FALSE);5724#endif5725}5726#endif57275728#endif // KMP_AFFINITY_SUPPORTED572957305731