c8a15545c8c1753901604947cde2ae397ecc4f6c
[alexxy/gromacs.git] / src / gromacs / hardware / hardwaretopology.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \internal \file
37  * \brief
38  * Implements gmx::HardwareTopology.
39  *
40  * \author Erik Lindahl <erik.lindahl@gmail.com>
41  * \ingroup module_hardware
42  */
43
44 #include "gmxpre.h"
45
46 #include "hardwaretopology.h"
47
48 #include "config.h"
49
50 #include <cstdio>
51
52 #include <algorithm>
53 #include <functional>
54 #include <limits>
55 #include <utility>
56 #include <vector>
57
58 #if GMX_USE_HWLOC
59 #    include <hwloc.h>
60 #endif
61
62 #include "gromacs/hardware/cpuinfo.h"
63 #include "gromacs/utility/gmxassert.h"
64
65 #ifdef HAVE_UNISTD_H
66 #    include <unistd.h>       // sysconf()
67 #endif
68 #if GMX_NATIVE_WINDOWS
69 #    include <windows.h>      // GetSystemInfo()
70 #endif
71
72 //! Convenience macro to help us avoid ifdefs each time we use sysconf
73 #if !defined(_SC_NPROCESSORS_ONLN) && defined(_SC_NPROC_ONLN)
74 #    define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
75 #endif
76
77 namespace gmx
78 {
79
80 namespace
81 {
82
83 /*****************************************************************************
84  *                                                                           *
85  *   Utility functions for extracting hardware topology from CpuInfo object  *
86  *                                                                           *
87  *****************************************************************************/
88
89 /*! \brief Initialize machine data from basic information in cpuinfo
90  *
91  *  \param  machine      Machine tree structure where information will be assigned
92  *                       if the cpuinfo object contains topology information.
93  *  \param  supportLevel If topology information is available in CpuInfo,
94  *                       this will be updated to reflect the amount of
95  *                       information written to the machine structure.
96  */
97 void
98 parseCpuInfo(HardwareTopology::Machine *        machine,
99              HardwareTopology::SupportLevel *   supportLevel)
100 {
101     CpuInfo cpuInfo(CpuInfo::detect());
102
103     if (!cpuInfo.logicalProcessors().empty())
104     {
105         int nSockets   = 0;
106         int nCores     = 0;
107         int nHwThreads = 0;
108
109         // Copy the logical processor information from cpuinfo
110         for (auto &l : cpuInfo.logicalProcessors())
111         {
112             machine->logicalProcessors.push_back( { l.socketRankInMachine, l.coreRankInSocket, l.hwThreadRankInCore, -1 } );
113             nSockets   = std::max(nSockets, l.socketRankInMachine);
114             nCores     = std::max(nCores, l.coreRankInSocket);
115             nHwThreads = std::max(nHwThreads, l.hwThreadRankInCore);
116         }
117
118         // Fill info form sockets/cores/hwthreads
119         int socketId   = 0;
120         int coreId     = 0;
121         int hwThreadId = 0;
122
123         machine->sockets.resize(nSockets + 1);
124         for (auto &s : machine->sockets)
125         {
126             s.id = socketId++;
127             s.cores.resize(nCores + 1);
128             for (auto &c : s.cores)
129             {
130                 c.id         = coreId++;
131                 c.numaNodeId = -1; // No numa information
132                 c.hwThreads.resize(nHwThreads + 1);
133                 for (auto &t : c.hwThreads)
134                 {
135                     t.id                 = hwThreadId++;
136                     t.logicalProcessorId = -1; // set as unassigned for now
137                 }
138             }
139         }
140
141         // Fill the logical processor id in the right place
142         for (std::size_t i = 0; i < machine->logicalProcessors.size(); i++)
143         {
144             const HardwareTopology::LogicalProcessor &l = machine->logicalProcessors[i];
145             machine->sockets[l.socketRankInMachine].cores[l.coreRankInSocket].hwThreads[l.hwThreadRankInCore].logicalProcessorId = static_cast<int>(i);
146         }
147         machine->logicalProcessorCount = machine->logicalProcessors.size();
148         *supportLevel                  = HardwareTopology::SupportLevel::Basic;
149     }
150     else
151     {
152         *supportLevel = HardwareTopology::SupportLevel::None;
153     }
154 }
155
156 #if GMX_USE_HWLOC
157
158 #if HWLOC_API_VERSION < 0x00010b00
159 #    define HWLOC_OBJ_PACKAGE  HWLOC_OBJ_SOCKET
160 #    define HWLOC_OBJ_NUMANODE HWLOC_OBJ_NODE
161 #endif
162
163 // Preprocessor variable for if hwloc api is version 1.x.x or 2.x.x
164 #if HWLOC_API_VERSION >= 0x00020000
165 #    define GMX_HWLOC_API_VERSION_IS_2XX 1
166 #else
167 #    define GMX_HWLOC_API_VERSION_IS_2XX 0
168 #endif
169
170 /*****************************************************************************
171  *                                                                           *
172  *   Utility functions for extracting hardware topology from hwloc library   *
173  *                                                                           *
174  *****************************************************************************/
175
176 // Compatibility function for accessing hwloc_obj_t object memory with different API versions of hwloc
177 std::size_t
178 getHwLocObjectMemory(const hwloc_obj* obj)
179 {
180 #if GMX_HWLOC_API_VERSION_IS_2XX
181     return obj->total_memory;
182 #else
183     return obj->memory.total_memory;
184 #endif
185 }
186
187 /*! \brief Return vector of all descendants of a given type in hwloc topology
188  *
189  *  \param topo  hwloc topology handle that has been initialized and loaded
190  *  \param obj   Non-null hwloc object.
191  *  \param type  hwloc object type to find. The routine will only search
192  *               on levels below obj.
193  *
194  *  \return vector containing all the objects of given type that are
195  *          descendants of the provided object. If no objects of this type
196  *          were found, the vector will be empty.
197  */
198 const std::vector<const hwloc_obj*>
199 getHwLocDescendantsByType(const hwloc_topology* topo, const hwloc_obj* obj, const hwloc_obj_type_t type)
200 {
201     GMX_RELEASE_ASSERT(obj, "NULL hwloc object provided to getHwLocDescendantsByType()");
202
203     std::vector<const hwloc_obj*> v;
204
205     if (obj->type == type)
206     {
207         v.push_back(obj);
208     }
209     // Go through children; if this object has no children obj->arity is 0,
210     // and we'll return an empty vector.
211     hwloc_obj_t tempNode = nullptr;
212     while ((tempNode = hwloc_get_next_child(const_cast<hwloc_topology_t>(topo),
213                                             const_cast<hwloc_obj_t>(obj),
214                                             tempNode)) != nullptr)
215     {
216         std::vector<const hwloc_obj*> v2 = getHwLocDescendantsByType(topo, tempNode, type);
217         v.insert(v.end(), v2.begin(), v2.end());
218     }
219     return v;
220 }
221
222 /*! \brief Read information about sockets, cores and threads from hwloc topology
223  *
224  *  \param topo    hwloc topology handle that has been initialized and loaded
225  *  \param machine Pointer to the machine structure in the HardwareTopology
226  *                 class, where the tree of sockets/cores/threads will be written.
227  *
228  *  \return If all the data is found
229  */
230 bool
231 parseHwLocSocketsCoresThreads(hwloc_topology_t                   topo,
232                               HardwareTopology::Machine *        machine)
233 {
234     const hwloc_obj*                      root         = hwloc_get_root_obj(topo);
235     std::vector<const hwloc_obj*>         hwlocSockets = getHwLocDescendantsByType(topo, root, HWLOC_OBJ_PACKAGE);
236
237     machine->logicalProcessorCount = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_PU);
238     machine->logicalProcessors.resize(machine->logicalProcessorCount);
239     machine->sockets.resize(hwlocSockets.size());
240
241     bool topologyOk = !hwlocSockets.empty(); // Fail if we have no sockets in machine
242
243     for (std::size_t i = 0; i < hwlocSockets.size() && topologyOk; i++)
244     {
245         // Assign information about this socket
246         machine->sockets[i].id = hwlocSockets[i]->logical_index;
247
248         // Get children (cores)
249         std::vector<const hwloc_obj*> hwlocCores = getHwLocDescendantsByType(topo, hwlocSockets[i], HWLOC_OBJ_CORE);
250         machine->sockets[i].cores.resize(hwlocCores.size());
251
252         topologyOk = topologyOk && !hwlocCores.empty(); // Fail if we have no cores in socket
253
254         // Loop over child cores
255         for (std::size_t j = 0; j < hwlocCores.size() && topologyOk; j++)
256         {
257             // Assign information about this core
258             machine->sockets[i].cores[j].id         = hwlocCores[j]->logical_index;
259             machine->sockets[i].cores[j].numaNodeId = -1;
260
261             // Get children (hwthreads)
262             std::vector<const hwloc_obj*> hwlocPUs = getHwLocDescendantsByType(topo, hwlocCores[j], HWLOC_OBJ_PU);
263             machine->sockets[i].cores[j].hwThreads.resize(hwlocPUs.size());
264
265             topologyOk = topologyOk && !hwlocPUs.empty(); // Fail if we have no hwthreads in core
266
267             // Loop over child hwthreads
268             for (std::size_t k = 0; k < hwlocPUs.size() && topologyOk; k++)
269             {
270                 // Assign information about this hwthread
271                 std::size_t logicalProcessorId                               = hwlocPUs[k]->os_index;
272                 machine->sockets[i].cores[j].hwThreads[k].id                 = hwlocPUs[k]->logical_index;
273                 machine->sockets[i].cores[j].hwThreads[k].logicalProcessorId = logicalProcessorId;
274
275                 if (logicalProcessorId < machine->logicalProcessors.size())
276                 {
277                     // Cross-assign data for this hwthread to the logicalprocess vector
278                     machine->logicalProcessors[logicalProcessorId].socketRankInMachine = static_cast<int>(i);
279                     machine->logicalProcessors[logicalProcessorId].coreRankInSocket    = static_cast<int>(j);
280                     machine->logicalProcessors[logicalProcessorId].hwThreadRankInCore  = static_cast<int>(k);
281                     machine->logicalProcessors[logicalProcessorId].numaNodeId          = -1;
282                 }
283                 else
284                 {
285                     topologyOk = false;
286                 }
287             }
288         }
289     }
290
291     if (!topologyOk)
292     {
293         machine->logicalProcessors.clear();
294         machine->sockets.clear();
295     }
296     return topologyOk;
297 }
298
299 /*! \brief Read cache information from hwloc topology
300  *
301  *  \param topo    hwloc topology handle that has been initialized and loaded
302  *  \param machine Pointer to the machine structure in the HardwareTopology
303  *                 class, where cache data will be filled.
304  *
305  *  \return If any cache data is found
306  */
307 bool
308 parseHwLocCache(hwloc_topology_t                   topo,
309                 HardwareTopology::Machine *        machine)
310 {
311     // Parse caches up to L5
312     for (int cachelevel : { 1, 2, 3, 4, 5})
313     {
314         int depth = hwloc_get_cache_type_depth(topo, cachelevel, HWLOC_OBJ_CACHE_DATA);
315
316         if (depth >= 0)
317         {
318             hwloc_obj_t cache = hwloc_get_next_obj_by_depth(topo, depth, nullptr);
319             if (cache != nullptr)
320             {
321                 std::vector<const hwloc_obj*> hwThreads = getHwLocDescendantsByType(topo, cache, HWLOC_OBJ_PU);
322
323                 machine->caches.push_back( {
324                                                static_cast<int>(cache->attr->cache.depth),
325                                                static_cast<std::size_t>(cache->attr->cache.size),
326                                                static_cast<int>(cache->attr->cache.linesize),
327                                                static_cast<int>(cache->attr->cache.associativity),
328                                                std::max<int>(hwThreads.size(), 1)
329                                            } );
330             }
331         }
332     }
333     return !machine->caches.empty();
334 }
335
336
337 /*! \brief Read numa information from hwloc topology
338  *
339  *  \param topo    hwloc topology handle that has been initialized and loaded
340  *  \param machine Pointer to the machine structure in the HardwareTopology
341  *                 class, where numa information will be filled.
342  *
343  *  Hwloc should virtually always be able to detect numa information, but if
344  *  there is only a single numa node in the system it is not reported at all.
345  *  In this case we create a single numa node covering all cores.
346  *
347  *  This function uses the basic socket/core/thread information detected by
348  *  parseHwLocSocketsCoresThreads(), which means that routine must have
349  *  completed successfully before calling this one. If this is not the case,
350  *  you will get an error return code.
351  *
352  *  \return If the data found makes sense (either in the numa node or the
353  *          entire machine)
354  */
355 bool
356 parseHwLocNuma(hwloc_topology_t                   topo,
357                HardwareTopology::Machine *        machine)
358 {
359     const hwloc_obj*                  root           = hwloc_get_root_obj(topo);
360     std::vector<const hwloc_obj*>     hwlocNumaNodes = getHwLocDescendantsByType(topo, root, HWLOC_OBJ_NUMANODE);
361     bool                              topologyOk     = true;
362
363     if (!hwlocNumaNodes.empty())
364     {
365         machine->numa.nodes.resize(hwlocNumaNodes.size());
366
367         for (std::size_t i = 0; i < hwlocNumaNodes.size(); i++)
368         {
369             machine->numa.nodes[i].id     = hwlocNumaNodes[i]->logical_index;
370             machine->numa.nodes[i].memory = getHwLocObjectMemory(hwlocNumaNodes[i]);;
371             machine->numa.nodes[i].logicalProcessorId.clear();
372
373             // Get list of PUs in this numa node. Get from numa node if v1.x.x, get from numa node's parent if 2.x.x
374 #if GMX_HWLOC_API_VERSION_IS_2XX
375             std::vector<const hwloc_obj*> hwlocPUs = getHwLocDescendantsByType(topo, hwlocNumaNodes[i]->parent, HWLOC_OBJ_PU);
376 #else
377             std::vector<const hwloc_obj*> hwlocPUs = getHwLocDescendantsByType(topo, hwlocNumaNodes[i], HWLOC_OBJ_PU);
378 #endif
379             for (auto &p : hwlocPUs)
380             {
381                 machine->numa.nodes[i].logicalProcessorId.push_back(p->os_index);
382
383                 GMX_RELEASE_ASSERT(p->os_index < machine->logicalProcessors.size(), "OS index of PU in hwloc larger than processor count");
384
385                 machine->logicalProcessors[p->os_index].numaNodeId = static_cast<int>(i);
386                 std::size_t s = machine->logicalProcessors[p->os_index].socketRankInMachine;
387                 std::size_t c = machine->logicalProcessors[p->os_index].coreRankInSocket;
388
389                 GMX_RELEASE_ASSERT(s < machine->sockets.size(), "Socket index in logicalProcessors larger than socket count");
390                 GMX_RELEASE_ASSERT(c < machine->sockets[s].cores.size(), "Core index in logicalProcessors larger than core count");
391                 // Set numaNodeId in core too
392                 machine->sockets[s].cores[c].numaNodeId = i;
393             }
394         }
395         // Getting the distance matrix
396 #if GMX_HWLOC_API_VERSION_IS_2XX
397         // with hwloc api v. 2.x.x, distances are no longer directly accessible. Need to retrieve and release hwloc_distances_s object
398         // In addition, there can now be multiple types of distances, ie latency, bandwidth. We look only for latency, but have to check
399         // if multiple distance matrices are returned.
400
401         // If only 1 numa node exists, the v2.x.x hwloc api won't have a distances matrix, set manually
402         if (hwlocNumaNodes.size() == 1)
403         {
404             machine->numa.relativeLatency       = { { 1.0 } };
405         }
406         else
407         {
408             hwloc_distances_s* dist;
409             // Set the number of distance matrices to return (1 in our case, but hwloc 2.x.x allows
410             // for multiple distances types and therefore multiple distance matrices)
411             unsigned nr = 1;
412             hwloc_distances_get(topo, &nr, &dist, HWLOC_DISTANCES_KIND_MEANS_LATENCY, 0);
413             // If no distances were found, nr will be 0, otherwise distances will be populated with 1
414             // hwloc_distances_s object
415             if (nr > 0 && dist->nbobjs == hwlocNumaNodes.size())
416             {
417
418                 machine->numa.relativeLatency.resize(dist->nbobjs);
419                 for (std::size_t i = 0; i < dist->nbobjs; i++)
420                 {
421                     machine->numa.relativeLatency[i].resize(dist->nbobjs);
422                     for (std::size_t j = 0; j < dist->nbobjs; j++)
423                     {
424                         machine->numa.relativeLatency[i][j] = dist->values[i*dist->nbobjs+j];
425                     }
426                 }
427             }
428             else
429             {
430                 topologyOk = false;
431             }
432             hwloc_distances_release(topo, dist);
433         }
434
435         // hwloc-2.x provides latencies as integers, but to make things more similar to the case of a single
436         // numa node as well as hwloc-1.x, we rescale to relative floating-point values and also set the
437         // largest relative latency value.
438
439         // find smallest value in matrix
440         float minLatency = std::numeric_limits<float>::max(); // large number
441         float maxLatency = std::numeric_limits<float>::min(); // 0.0
442         for (const auto &v : machine->numa.relativeLatency)
443         {
444             auto result = std::minmax_element(v.begin(), v.end());
445             minLatency = std::min(minLatency, *result.first);
446             maxLatency = std::max(maxLatency, *result.second);
447         }
448
449         // assign stuff
450         for (auto &v : machine->numa.relativeLatency)
451         {
452             std::transform(v.begin(), v.end(), v.begin(), std::bind(std::multiplies<float>(), std::placeholders::_1, 1.0/minLatency));
453         }
454         machine->numa.baseLatency        = 1.0; // latencies still do not have any units in hwloc-2.x
455         machine->numa.maxRelativeLatency = maxLatency/minLatency;
456
457 #else           // GMX_HWLOC_API_VERSION_IS_2XX == false, hwloc api is 1.x.x
458         int depth = hwloc_get_type_depth(topo, HWLOC_OBJ_NUMANODE);
459         const struct hwloc_distances_s * dist = hwloc_get_whole_distance_matrix_by_depth(topo, depth);
460         if (dist != nullptr && dist->nbobjs == hwlocNumaNodes.size())
461         {
462             machine->numa.baseLatency        = dist->latency_base;
463             machine->numa.maxRelativeLatency = dist->latency_max;
464             machine->numa.relativeLatency.resize(dist->nbobjs);
465             for (std::size_t i = 0; i < dist->nbobjs; i++)
466             {
467                 machine->numa.relativeLatency[i].resize(dist->nbobjs);
468                 for (std::size_t j = 0; j < dist->nbobjs; j++)
469                 {
470                     machine->numa.relativeLatency[i][j] = dist->latency[i*dist->nbobjs+j];
471                 }
472             }
473         }
474         else
475         {
476             topologyOk = false;
477         }
478 #endif          // end GMX_HWLOC_API_VERSION_IS_2XX == false
479     }
480     else
481     // Deals with the case of no numa nodes found.
482 #if GMX_HWLOC_API_VERSION_IS_2XX
483     // If the hwloc version is 2.x.x, and there is no numa node, something went wrong
484     {
485         topologyOk = false;
486     }
487 #else
488     {
489         // No numa nodes found. Use the entire machine as a numa node.
490         // Note that this should only be the case with hwloc api v 1.x.x,
491         // a numa node is assigned to the machine by default in v 2.x.x
492         const hwloc_obj*const hwlocMachine = hwloc_get_next_obj_by_type(topo, HWLOC_OBJ_MACHINE, nullptr);
493
494         if (hwlocMachine != nullptr)
495         {
496             machine->numa.nodes.resize(1);
497             machine->numa.nodes[0].id           = 0;
498             machine->numa.nodes[0].memory       = hwlocMachine->memory.total_memory;
499             machine->numa.baseLatency           = 10;
500             machine->numa.maxRelativeLatency    = 1;
501             machine->numa.relativeLatency       = { { 1.0 } };
502
503             for (int i = 0; i < machine->logicalProcessorCount; i++)
504             {
505                 machine->numa.nodes[0].logicalProcessorId.push_back(i);
506             }
507             for (auto &l : machine->logicalProcessors)
508             {
509                 l.numaNodeId = 0;
510             }
511             for (auto &s : machine->sockets)
512             {
513                 for (auto &c : s.cores)
514                 {
515                     c.numaNodeId = 0;
516                 }
517             }
518         }
519         else
520         {
521             topologyOk = false;
522         }
523     }
524 #endif      // end if not GMX_HWLOC_API_VERSION_IS_2XX
525     if (!topologyOk)
526     {
527         machine->numa.nodes.clear();
528     }
529     return topologyOk;
530 }
531
532 /*! \brief Read PCI device information from hwloc topology
533  *
534  *  \param topo    hwloc topology handle that has been initialized and loaded
535  *  \param machine Pointer to the machine structure in the HardwareTopology
536  *                 class, where PCI device information will be filled.
537  * *
538  *  \return If any devices were found
539  */
540 bool
541 parseHwLocDevices(hwloc_topology_t                   topo,
542                   HardwareTopology::Machine *        machine)
543 {
544     const hwloc_obj *             root    = hwloc_get_root_obj(topo);
545     std::vector<const hwloc_obj*> pcidevs = getHwLocDescendantsByType(topo, root, HWLOC_OBJ_PCI_DEVICE);
546
547     for (auto &p : pcidevs)
548     {
549 #if GMX_HWLOC_API_VERSION_IS_2XX
550         const hwloc_obj * ancestor = nullptr;
551         // Numa nodes not directly part of tree. Walk up the tree until we find an ancestor with a numa node
552         hwloc_obj_t       parent = p->parent;
553         while (parent && !parent->memory_arity)
554         {
555             parent = parent->parent;
556         }
557         if (parent)
558         {
559             ancestor = parent->memory_first_child;
560         }
561 #else           // GMX_HWLOC_API_VERSION_IS_2XX = false, api v 1.x.x
562         // numa nodes are normal part of tree, can use hwloc ancestor function
563         const hwloc_obj * const ancestor = hwloc_get_ancestor_obj_by_type(topo, HWLOC_OBJ_NUMANODE,
564                                                                           const_cast<hwloc_obj_t>(p));
565 #endif          // end if GMX_HWLOC_API_VERSION_IS_2XX
566         int                     numaId;
567         if (ancestor != nullptr)
568         {
569             numaId = ancestor->logical_index;
570         }
571         else
572         {
573             // If we only have a single numa node we belong to it, otherwise set it to -1 (unknown)
574             numaId = (machine->numa.nodes.size() == 1) ?  0 : -1;
575         }
576
577         GMX_RELEASE_ASSERT(p->attr, "Attributes should not be NULL for hwloc PCI object");
578
579         machine->devices.push_back( {
580                                         p->attr->pcidev.vendor_id,
581                                         p->attr->pcidev.device_id,
582                                         p->attr->pcidev.class_id,
583                                         p->attr->pcidev.domain,
584                                         p->attr->pcidev.bus,
585                                         p->attr->pcidev.dev,
586                                         p->attr->pcidev.func,
587                                         numaId
588                                     } );
589     }
590     return !pcidevs.empty();
591 }
592
593 void
594 parseHwLoc(HardwareTopology::Machine *        machine,
595            HardwareTopology::SupportLevel *   supportLevel,
596            bool *                             isThisSystem)
597 {
598     hwloc_topology_t    topo;
599
600     // Initialize a hwloc object, set flags to request IO device information too,
601     // try to load the topology, and get the root object. If either step fails,
602     // return that we do not have any support at all from hwloc.
603     if (hwloc_topology_init(&topo) != 0)
604     {
605         hwloc_topology_destroy(topo);
606         return; // SupportLevel::None.
607     }
608
609     // Flags to look for io devices
610 #if GMX_HWLOC_API_VERSION_IS_2XX
611     hwloc_topology_set_io_types_filter(topo, HWLOC_TYPE_FILTER_KEEP_IMPORTANT);
612 #else
613     hwloc_topology_set_flags(topo, HWLOC_TOPOLOGY_FLAG_IO_DEVICES);
614 #endif
615
616     if (hwloc_topology_load(topo) != 0 || hwloc_get_root_obj(topo) == nullptr)
617     {
618         hwloc_topology_destroy(topo);
619         return; // SupportLevel::None.
620     }
621
622     // If we get here, we can get a valid root object for the topology
623     *isThisSystem = hwloc_topology_is_thissystem(topo) != 0;
624
625     // Parse basic information about sockets, cores, and hardware threads
626     if (parseHwLocSocketsCoresThreads(topo, machine))
627     {
628         *supportLevel = HardwareTopology::SupportLevel::Basic;
629     }
630     else
631     {
632         hwloc_topology_destroy(topo);
633         return; // SupportLevel::None.
634     }
635
636     // Get information about cache and numa nodes
637     if (parseHwLocCache(topo, machine) && parseHwLocNuma(topo, machine))
638     {
639         *supportLevel = HardwareTopology::SupportLevel::Full;
640     }
641     else
642     {
643         hwloc_topology_destroy(topo);
644         return; // SupportLevel::Basic.
645     }
646
647     // PCI devices
648     if (parseHwLocDevices(topo, machine))
649     {
650         *supportLevel = HardwareTopology::SupportLevel::FullWithDevices;
651     }
652
653     hwloc_topology_destroy(topo);
654 // SupportLevel::Full or SupportLevel::FullWithDevices.
655 }
656
657 #endif
658
659 /*! \brief Try to detect the number of logical processors.
660  *
661  *  \return The number of hardware processing units, or 0 if it fails.
662  */
663 int
664 detectLogicalProcessorCount()
665 {
666     int count = 0;
667
668     {
669 #if GMX_NATIVE_WINDOWS
670         // Windows
671         SYSTEM_INFO sysinfo;
672         GetSystemInfo( &sysinfo );
673         count = sysinfo.dwNumberOfProcessors;
674 #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
675         // We are probably on Unix. Check if we have the argument to use before executing any calls
676         count = sysconf(_SC_NPROCESSORS_ONLN);
677 #else
678         count = 0; // Neither windows nor Unix.
679 #endif
680     }
681
682     return count;
683 }
684
685 }   // namespace
686
687 // static
688 HardwareTopology HardwareTopology::detect()
689 {
690     HardwareTopology result;
691
692 #if GMX_USE_HWLOC
693     parseHwLoc(&result.machine_, &result.supportLevel_, &result.isThisSystem_);
694 #endif
695
696     // If something went wrong in hwloc (or if it was not present) we might
697     // have more information in cpuInfo
698     if (result.supportLevel_ < SupportLevel::Basic)
699     {
700         // There might be topology information in cpuInfo
701         parseCpuInfo(&result.machine_, &result.supportLevel_);
702     }
703     // If we did not manage to get anything from either hwloc or cpuInfo, find the cpu count at least
704     if (result.supportLevel_ == SupportLevel::None)
705     {
706         // No topology information; try to detect the number of logical processors at least
707         result.machine_.logicalProcessorCount = detectLogicalProcessorCount();
708         if (result.machine_.logicalProcessorCount > 0)
709         {
710             result.supportLevel_ = SupportLevel::LogicalProcessorCount;
711         }
712     }
713     return result;
714 }
715
716 HardwareTopology::Machine::Machine()
717 {
718     logicalProcessorCount   = 0;
719     numa.baseLatency        = 0.0;
720     numa.maxRelativeLatency = 0.0;
721 }
722
723
724 HardwareTopology::HardwareTopology()
725     : supportLevel_(SupportLevel::None),
726       machine_(),
727       isThisSystem_(true)
728 {
729 }
730
731 HardwareTopology::HardwareTopology(int logicalProcessorCount)
732     : supportLevel_(SupportLevel::None),
733       machine_(),
734       isThisSystem_(true)
735 {
736     if (logicalProcessorCount > 0)
737     {
738         machine_.logicalProcessorCount = logicalProcessorCount;
739         supportLevel_                  = SupportLevel::LogicalProcessorCount;
740     }
741 }
742
743 int HardwareTopology::numberOfCores() const
744 {
745     if (supportLevel() >= SupportLevel::Basic)
746     {
747         // We assume all sockets have the same number of cores as socket 0.
748         // Since topology information is present, we can assume there is at least one socket.
749         return machine().sockets.size() * machine().sockets[0].cores.size();
750     }
751     else if (supportLevel() >= SupportLevel::LogicalProcessorCount)
752     {
753         return machine().logicalProcessorCount;
754     }
755     else
756     {
757         return 0;
758     }
759 }
760
761 } // namespace gmx