gmxlib: clean up -Wunused-parameter warnings
[alexxy/gromacs.git] / src / gromacs / gmxlib / gmx_thread_affinity.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38 #if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_GETAFFINITY)
39 #define _GNU_SOURCE
40 #include <sched.h>
41 #include <sys/syscall.h>
42 #endif
43 #include <string.h>
44 #include <errno.h>
45 #include <assert.h>
46 #include <stdio.h>
47 #include "typedefs.h"
48 #include "types/commrec.h"
49 #include "types/hw_info.h"
50 #include "gmx_cpuid.h"
51 #include "gmx_omp.h"
52 #include "gmx_omp_nthreads.h"
53 #include "mdrun.h"
54 #include "md_logging.h"
55 #include "statutil.h"
56 #include "gmx_thread_affinity.h"
57
58 #include "thread_mpi/threads.h"
59
60
61 static int
62 get_thread_affinity_layout(FILE *fplog,
63                            const t_commrec *cr,
64                            const gmx_hw_info_t * hwinfo,
65                            int nthreads,
66                            int pin_offset, int * pin_stride,
67                            const int **locality_order)
68 {
69     int         nhwthreads, npkg, ncores, nhwthreads_per_core, rc;
70     const int * pkg_id;
71     const int * core_id;
72     const int * hwthread_id;
73     gmx_bool    bPickPinStride;
74
75     if (pin_offset < 0)
76     {
77         gmx_fatal(FARGS, "Negative thread pinning offset requested");
78     }
79     if (*pin_stride < 0)
80     {
81         gmx_fatal(FARGS, "Negative thread pinning stride requested");
82     }
83
84     rc = gmx_cpuid_topology(hwinfo->cpuid_info, &nhwthreads, &npkg, &ncores,
85                             &nhwthreads_per_core,
86                             &pkg_id, &core_id, &hwthread_id, locality_order);
87
88     if (rc != 0)
89     {
90         /* topology information not available or invalid, ignore it */
91         nhwthreads      = hwinfo->nthreads_hw_avail;
92         *locality_order = NULL;
93
94         if (nhwthreads <= 0)
95         {
96             /* We don't know anything about the hardware, don't pin */
97             md_print_warn(cr, fplog,
98                           "NOTE: We don't know how many logical cores we have, will not pin threads");
99
100             return -1;
101         }
102     }
103
104     if (nthreads > nhwthreads)
105     {
106         /* We are oversubscribing, don't pin */
107         md_print_warn(NULL, fplog,
108                       "WARNING: Oversubscribing the CPU, will not pin threads");
109
110         return -1;
111     }
112
113     if (pin_offset + nthreads > nhwthreads)
114     {
115         /* We are oversubscribing, don't pin */
116         md_print_warn(NULL, fplog,
117                       "WARNING: The requested pin offset is too large for the available logical cores,\n"
118                       "         will not pin threads");
119
120         return -1;
121     }
122
123
124     /* do we need to choose the pinning stride? */
125     bPickPinStride = (*pin_stride == 0);
126
127     if (bPickPinStride)
128     {
129         if (rc == 0 && pin_offset + nthreads*nhwthreads_per_core <= nhwthreads)
130         {
131             /* Put one thread on each physical core */
132             *pin_stride = nhwthreads_per_core;
133         }
134         else
135         {
136             /* We don't know if we have SMT, and if we do, we don't know
137              * if hw threads in the same physical core are consecutive.
138              * Without SMT the pinning layout should not matter too much.
139              * so we assume a consecutive layout and maximally spread out"
140              * the threads at equal threads per core.
141              * Note that IBM is the major non-x86 case with cpuid support
142              * and probably threads are already pinned by the queuing system,
143              * so we wouldn't end up here in the first place.
144              */
145             *pin_stride = (nhwthreads - pin_offset)/nthreads;
146         }
147     }
148     else
149     {
150         /* Check the placement of the thread with the largest index to make sure
151          * that the offset & stride doesn't cause pinning beyond the last hardware thread. */
152         if (pin_offset + (nthreads-1)*(*pin_stride) >= nhwthreads)
153         {
154             /* We are oversubscribing, don't pin */
155             md_print_warn(NULL, fplog,
156                           "WARNING: The requested pinning stride is too large for the available logical cores,\n"
157                           "         will not pin threads");
158
159             return -1;
160         }
161     }
162
163     if (fplog != NULL)
164     {
165         fprintf(fplog, "Pinning threads with a%s logical core stride of %d\n",
166                 bPickPinStride ? "n auto-selected" : " user-specified",
167                 *pin_stride);
168     }
169
170     return 0;
171 }
172
173 /* Set CPU affinity. Can be important for performance.
174    On some systems (e.g. Cray) CPU Affinity is set by default.
175    But default assigning doesn't work (well) with only some ranks
176    having threads. This causes very low performance.
177    External tools have cumbersome syntax for setting affinity
178    in the case that only some ranks have threads.
179    Thus it is important that GROMACS sets the affinity internally
180    if only PME is using threads.
181  */
182 void
183 gmx_set_thread_affinity(FILE                *fplog,
184                         const t_commrec     *cr,
185                         gmx_hw_opt_t        *hw_opt,
186                         const gmx_hw_info_t *hwinfo)
187 {
188     int        nth_affinity_set, thread_id_node, thread_id,
189                nthread_local, nthread_node, nthread_hw_max, nphyscore;
190     int        offset;
191     /* these are inherently global properties that are shared among all threads
192      */
193     static const int          *locality_order;
194     static int                 rc;
195     static gmx_bool            have_locality_order = FALSE;
196     static tMPI_Thread_mutex_t locality_order_mtx  =
197         TMPI_THREAD_MUTEX_INITIALIZER;
198     static tMPI_Thread_cond_t  locality_order_cond =
199         TMPI_THREAD_COND_INITIALIZER;
200
201     if (hw_opt->thread_affinity == threadaffOFF)
202     {
203         /* Nothing to do */
204         return;
205     }
206
207     /* If the tMPI thread affinity setting is not supported encourage the user
208      * to report it as it's either a bug or an exotic platform which we might
209      * want to support. */
210     if (tMPI_Thread_setaffinity_support() != TMPI_SETAFFINITY_SUPPORT_YES)
211     {
212         /* we know Mac OS doesn't support setting thread affinity, so there's
213            no point in warning the user in that case. In any other case
214            the user might be able to do something about it. */
215 #ifndef __APPLE__
216         md_print_warn(NULL, fplog,
217                       "Can not set thread affinities on the current platform. On NUMA systems this\n"
218                       "can cause performance degradation. If you think your platform should support\n"
219                       "setting affinities, contact the GROMACS developers.");
220 #endif /* __APPLE__ */
221         return;
222     }
223
224     /* threads on this MPI process or TMPI thread */
225     if (cr->duty & DUTY_PP)
226     {
227         nthread_local = gmx_omp_nthreads_get(emntNonbonded);
228     }
229     else
230     {
231         nthread_local = gmx_omp_nthreads_get(emntPME);
232     }
233
234     /* map the current process to cores */
235     thread_id_node = 0;
236     nthread_node   = nthread_local;
237 #ifdef GMX_MPI
238     if (PAR(cr) || MULTISIM(cr))
239     {
240         /* We need to determine a scan of the thread counts in this
241          * compute node.
242          */
243         MPI_Comm comm_intra;
244
245         MPI_Comm_split(MPI_COMM_WORLD, gmx_hostname_num(), cr->rank_intranode,
246                        &comm_intra);
247         MPI_Scan(&nthread_local, &thread_id_node, 1, MPI_INT, MPI_SUM, comm_intra);
248         /* MPI_Scan is inclusive, but here we need exclusive */
249         thread_id_node -= nthread_local;
250         /* Get the total number of threads on this physical node */
251         MPI_Allreduce(&nthread_local, &nthread_node, 1, MPI_INT, MPI_SUM, comm_intra);
252         MPI_Comm_free(&comm_intra);
253     }
254 #endif
255
256     if (hw_opt->thread_affinity == threadaffAUTO &&
257         nthread_node != hwinfo->nthreads_hw_avail)
258     {
259         if (nthread_node > 1 && nthread_node < hwinfo->nthreads_hw_avail)
260         {
261             md_print_warn(cr, fplog,
262                           "NOTE: The number of threads is not equal to the number of (logical) cores\n"
263                           "      and the -pin option is set to auto: will not pin thread to cores.\n"
264                           "      This can lead to significant performance degradation.\n"
265                           "      Consider using -pin on (and -pinoffset in case you run multiple jobs).\n");
266         }
267
268         return;
269     }
270
271     offset = 0;
272     if (hw_opt->core_pinning_offset != 0)
273     {
274         offset = hw_opt->core_pinning_offset;
275         md_print_info(cr, fplog, "Applying core pinning offset %d\n", offset);
276     }
277
278     /* hw_opt is shared among tMPI threads, so for thread safety we need to do
279      * the layout detection only on master as core_pinning_stride is an in-out
280      * parameter and gets auto-set depending on its initial value.
281      * This
282      * This is not thread-safe with multi-simulations, but that's anyway not
283      * supported by tMPI. */
284     if (SIMMASTER(cr))
285     {
286         int ret;
287         int i;
288
289         ret = tMPI_Thread_mutex_lock(&locality_order_mtx);
290         if (ret != 0)
291         {
292             goto locality_order_err;
293         }
294         rc = get_thread_affinity_layout(fplog, cr, hwinfo,
295                                         nthread_node,
296                                         offset, &hw_opt->core_pinning_stride,
297                                         &locality_order);
298         have_locality_order = TRUE;
299         ret                 = tMPI_Thread_cond_broadcast(&locality_order_cond);
300         if (ret != 0)
301         {
302             tMPI_Thread_mutex_unlock(&locality_order_mtx);
303             goto locality_order_err;
304         }
305         ret = tMPI_Thread_mutex_unlock(&locality_order_mtx);
306         if (ret != 0)
307         {
308             goto locality_order_err;
309         }
310     }
311     else
312     {
313         int ret;
314         /* all other threads wait for the locality order data. */
315         ret = tMPI_Thread_mutex_lock(&locality_order_mtx);
316         if (ret != 0)
317         {
318             goto locality_order_err;
319         }
320
321         while (!have_locality_order)
322         {
323             ret = tMPI_Thread_cond_wait(&locality_order_cond,
324                                         &locality_order_mtx);
325             if (ret != 0)
326             {
327                 tMPI_Thread_mutex_unlock(&locality_order_mtx);
328                 goto locality_order_err;
329             }
330         }
331         ret = tMPI_Thread_mutex_unlock(&locality_order_mtx);
332         if (ret != 0)
333         {
334             goto locality_order_err;
335         }
336     }
337
338     if (rc != 0)
339     {
340         /* Incompatible layout, don't pin, warning was already issued */
341         return;
342     }
343
344     /* Set the per-thread affinity. In order to be able to check the success
345      * of affinity settings, we will set nth_affinity_set to 1 on threads
346      * where the affinity setting succeded and to 0 where it failed.
347      * Reducing these 0/1 values over the threads will give the total number
348      * of threads on which we succeeded.
349      */
350     nth_affinity_set = 0;
351 #pragma omp parallel firstprivate(thread_id_node) num_threads(nthread_local) \
352     reduction(+:nth_affinity_set)
353     {
354         int      index, core;
355         gmx_bool setaffinity_ret;
356
357         thread_id       = gmx_omp_get_thread_num();
358         thread_id_node += thread_id;
359         index           = offset + thread_id_node*hw_opt->core_pinning_stride;
360         if (locality_order != NULL)
361         {
362             core = locality_order[index];
363         }
364         else
365         {
366             core = index;
367         }
368
369         setaffinity_ret = tMPI_Thread_setaffinity_single(tMPI_Thread_self(), core);
370
371         /* store the per-thread success-values of the setaffinity */
372         nth_affinity_set = (setaffinity_ret == 0);
373
374         if (debug)
375         {
376             fprintf(debug, "On rank %2d, thread %2d, core %2d the affinity setting returned %d\n",
377                     cr->nodeid, gmx_omp_get_thread_num(), core, setaffinity_ret);
378         }
379     }
380
381     if (nth_affinity_set > nthread_local)
382     {
383         char msg[STRLEN];
384
385         sprintf(msg, "Looks like we have set affinity for more threads than "
386                 "we have (%d > %d)!\n", nth_affinity_set, nthread_local);
387         gmx_incons(msg);
388     }
389     else
390     {
391         /* check & warn if some threads failed to set their affinities */
392         if (nth_affinity_set != nthread_local)
393         {
394             char sbuf1[STRLEN], sbuf2[STRLEN];
395
396             /* sbuf1 contains rank info, while sbuf2 OpenMP thread info */
397             sbuf1[0] = sbuf2[0] = '\0';
398             /* Only add rank info if we have more than one rank. */
399             if (cr->nnodes > 1)
400             {
401 #ifdef GMX_MPI
402 #ifdef GMX_THREAD_MPI
403                 sprintf(sbuf1, "In tMPI thread #%d: ", cr->nodeid);
404 #else           /* GMX_LIB_MPI */
405                 sprintf(sbuf1, "In MPI process #%d: ", cr->nodeid);
406 #endif
407 #endif          /* GMX_MPI */
408             }
409
410             if (nthread_local > 1)
411             {
412                 sprintf(sbuf2, "for %d/%d thread%s ",
413                         nthread_local - nth_affinity_set, nthread_local,
414                         nthread_local > 1 ? "s" : "");
415             }
416
417             md_print_warn(NULL, fplog,
418                           "WARNING: %sAffinity setting %sfailed.\n"
419                           "         This can cause performance degradation! If you think your setting are\n"
420                           "         correct, contact the GROMACS developers.",
421                           sbuf1, sbuf2);
422         }
423     }
424     return;
425
426 locality_order_err:
427     /* any error in affinity setting shouldn't be fatal, but should generate
428        a warning */
429     md_print_warn(NULL, fplog,
430                   "WARNING: Obtaining affinity information failed due to a basic system error: %s.\n"
431                   "         This can cause performance degradation! ",
432                   strerror(errno));
433     return;
434 }
435
436 /* Check the process affinity mask and if it is found to be non-zero,
437  * will honor it and disable mdrun internal affinity setting.
438  * Note that this will only work on Linux as we use a GNU feature.
439  */
440 void
441 gmx_check_thread_affinity_set(FILE *fplog, const t_commrec *cr,
442                               gmx_hw_opt_t *hw_opt, int ncpus,
443                               gmx_bool bAfterOpenmpInit)
444 {
445 #ifdef HAVE_SCHED_GETAFFINITY
446     cpu_set_t mask_current;
447     int       i, ret, cpu_count, cpu_set;
448     gmx_bool  bAllSet;
449
450     assert(hw_opt);
451     if (hw_opt->thread_affinity == threadaffOFF)
452     {
453         /* internal affinity setting is off, don't bother checking process affinity */
454         return;
455     }
456
457     CPU_ZERO(&mask_current);
458     if ((ret = sched_getaffinity(0, sizeof(cpu_set_t), &mask_current)) != 0)
459     {
460         /* failed to query affinity mask, will just return */
461         if (debug)
462         {
463             fprintf(debug, "Failed to query affinity mask (error %d)", ret);
464         }
465         return;
466     }
467
468     /* Before proceeding with the actual check, make sure that the number of
469      * detected CPUs is >= the CPUs in the current set.
470      * We need to check for CPU_COUNT as it was added only in glibc 2.6. */
471 #ifdef CPU_COUNT
472     if (ncpus < CPU_COUNT(&mask_current))
473     {
474         if (debug)
475         {
476             fprintf(debug, "%d CPUs detected, but %d was returned by CPU_COUNT",
477                     ncpus, CPU_COUNT(&mask_current));
478         }
479         return;
480     }
481 #endif /* CPU_COUNT */
482
483     bAllSet = TRUE;
484     for (i = 0; (i < ncpus && i < CPU_SETSIZE); i++)
485     {
486         bAllSet = bAllSet && (CPU_ISSET(i, &mask_current) != 0);
487     }
488
489     if (!bAllSet)
490     {
491         if (hw_opt->thread_affinity == threadaffAUTO)
492         {
493             if (!bAfterOpenmpInit)
494             {
495                 md_print_warn(cr, fplog,
496                               "Non-default thread affinity set, disabling internal thread affinity");
497             }
498             else
499             {
500                 md_print_warn(cr, fplog,
501                               "Non-default thread affinity set probably by the OpenMP library,\n"
502                               "disabling internal thread affinity");
503             }
504             hw_opt->thread_affinity = threadaffOFF;
505         }
506         else
507         {
508             /* Only warn once, at the last check (bAfterOpenmpInit==TRUE) */
509             if (bAfterOpenmpInit)
510             {
511                 md_print_warn(cr, fplog,
512                               "Overriding thread affinity set outside %s\n",
513                               ShortProgram());
514             }
515         }
516
517         if (debug)
518         {
519             fprintf(debug, "Non-default affinity mask found\n");
520         }
521     }
522     else
523     {
524         if (debug)
525         {
526             fprintf(debug, "Default affinity mask found\n");
527         }
528     }
529 #endif /* HAVE_SCHED_GETAFFINITY */
530 }