Merge branch release-4-6 into release-5-0
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_cuda / nbnxn_cuda_data_mgmt.cu
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, 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 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #include <assert.h>
40 #include <stdarg.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43
44 #include <cuda.h>
45
46 #include "gmx_fatal.h"
47 #include "gromacs/utility/smalloc.h"
48 #include "tables.h"
49 #include "typedefs.h"
50 #include "types/enums.h"
51 #include "types/nb_verlet.h"
52 #include "types/interaction_const.h"
53 #include "types/force_flags.h"
54 #include "../nbnxn_consts.h"
55 #include "gmx_detect_hardware.h"
56
57 #include "nbnxn_cuda_types.h"
58 #include "../../gmxlib/cuda_tools/cudautils.cuh"
59 #include "nbnxn_cuda_data_mgmt.h"
60 #include "pmalloc_cuda.h"
61 #include "gpu_utils.h"
62
63 #include "gromacs/utility/common.h"
64
65 static bool bUseCudaEventBlockingSync = false; /* makes the CPU thread block */
66
67 /* This is a heuristically determined parameter for the Fermi architecture for
68  * the minimum size of ci lists by multiplying this constant with the # of
69  * multiprocessors on the current device.
70  */
71 static unsigned int gpu_min_ci_balanced_factor = 40;
72
73 /* Functions from nbnxn_cuda.cu */
74 extern void nbnxn_cuda_set_cacheconfig(cuda_dev_info_t *devinfo);
75 extern const struct texture<float, 1, cudaReadModeElementType> &nbnxn_cuda_get_nbfp_texref();
76 extern const struct texture<float, 1, cudaReadModeElementType> &nbnxn_cuda_get_nbfp_comb_texref();
77 extern const struct texture<float, 1, cudaReadModeElementType> &nbnxn_cuda_get_coulomb_tab_texref();
78
79 /* We should actually be using md_print_warn in md_logging.c,
80  * but we can't include mpi.h in CUDA code.
81  */
82 static void md_print_warn(FILE       *fplog,
83                           const char *fmt, ...)
84 {
85     va_list ap;
86
87     if (fplog != NULL)
88     {
89         /* We should only print to stderr on the master node,
90          * in most cases fplog is only set on the master node, so this works.
91          */
92         va_start(ap, fmt);
93         fprintf(stderr, "\n");
94         vfprintf(stderr, fmt, ap);
95         fprintf(stderr, "\n");
96         va_end(ap);
97
98         va_start(ap, fmt);
99         fprintf(fplog, "\n");
100         vfprintf(fplog, fmt, ap);
101         fprintf(fplog, "\n");
102         va_end(ap);
103     }
104 }
105
106
107 /* Fw. decl. */
108 static void nbnxn_cuda_clear_e_fshift(nbnxn_cuda_ptr_t cu_nb);
109
110
111 /*! Tabulates the Ewald Coulomb force and initializes the size/scale
112     and the table GPU array. If called with an already allocated table,
113     it just re-uploads the table.
114  */
115 static void init_ewald_coulomb_force_table(cu_nbparam_t          *nbp,
116                                            const cuda_dev_info_t *dev_info)
117 {
118     float       *ftmp, *coul_tab;
119     int          tabsize;
120     double       tabscale;
121     cudaError_t  stat;
122
123     tabsize     = GPU_EWALD_COULOMB_FORCE_TABLE_SIZE;
124     /* Subtract 2 iso 1 to avoid access out of range due to rounding */
125     tabscale    = (tabsize - 2) / sqrt(nbp->rcoulomb_sq);
126
127     pmalloc((void**)&ftmp, tabsize*sizeof(*ftmp));
128
129     table_spline3_fill_ewald_lr(ftmp, NULL, NULL, tabsize,
130                                 1/tabscale, nbp->ewald_beta, v_q_ewald_lr);
131
132     /* If the table pointer == NULL the table is generated the first time =>
133        the array pointer will be saved to nbparam and the texture is bound.
134      */
135     coul_tab = nbp->coulomb_tab;
136     if (coul_tab == NULL)
137     {
138         stat = cudaMalloc((void **)&coul_tab, tabsize*sizeof(*coul_tab));
139         CU_RET_ERR(stat, "cudaMalloc failed on coul_tab");
140
141         nbp->coulomb_tab = coul_tab;
142
143 #ifdef TEXOBJ_SUPPORTED
144         /* Only device CC >= 3.0 (Kepler and later) support texture objects */
145         if (dev_info->prop.major >= 3)
146         {
147             cudaResourceDesc rd;
148             memset(&rd, 0, sizeof(rd));
149             rd.resType                  = cudaResourceTypeLinear;
150             rd.res.linear.devPtr        = nbp->coulomb_tab;
151             rd.res.linear.desc.f        = cudaChannelFormatKindFloat;
152             rd.res.linear.desc.x        = 32;
153             rd.res.linear.sizeInBytes   = tabsize*sizeof(*coul_tab);
154
155             cudaTextureDesc td;
156             memset(&td, 0, sizeof(td));
157             td.readMode                 = cudaReadModeElementType;
158             stat = cudaCreateTextureObject(&nbp->coulomb_tab_texobj, &rd, &td, NULL);
159             CU_RET_ERR(stat, "cudaCreateTextureObject on coulomb_tab_texobj failed");
160         }
161         else
162 #endif
163         {
164             GMX_UNUSED_VALUE(dev_info);
165             cudaChannelFormatDesc cd   = cudaCreateChannelDesc<float>();
166             stat = cudaBindTexture(NULL, &nbnxn_cuda_get_coulomb_tab_texref(),
167                                    coul_tab, &cd, tabsize*sizeof(*coul_tab));
168             CU_RET_ERR(stat, "cudaBindTexture on coulomb_tab_texref failed");
169         }
170     }
171
172     cu_copy_H2D(coul_tab, ftmp, tabsize*sizeof(*coul_tab));
173
174     nbp->coulomb_tab_size     = tabsize;
175     nbp->coulomb_tab_scale    = tabscale;
176
177     pfree(ftmp);
178 }
179
180
181 /*! Initializes the atomdata structure first time, it only gets filled at
182     pair-search. */
183 static void init_atomdata_first(cu_atomdata_t *ad, int ntypes)
184 {
185     cudaError_t stat;
186
187     ad->ntypes  = ntypes;
188     stat        = cudaMalloc((void**)&ad->shift_vec, SHIFTS*sizeof(*ad->shift_vec));
189     CU_RET_ERR(stat, "cudaMalloc failed on ad->shift_vec");
190     ad->bShiftVecUploaded = false;
191
192     stat = cudaMalloc((void**)&ad->fshift, SHIFTS*sizeof(*ad->fshift));
193     CU_RET_ERR(stat, "cudaMalloc failed on ad->fshift");
194
195     stat = cudaMalloc((void**)&ad->e_lj, sizeof(*ad->e_lj));
196     CU_RET_ERR(stat, "cudaMalloc failed on ad->e_lj");
197     stat = cudaMalloc((void**)&ad->e_el, sizeof(*ad->e_el));
198     CU_RET_ERR(stat, "cudaMalloc failed on ad->e_el");
199
200     /* initialize to NULL poiters to data that is not allocated here and will
201        need reallocation in nbnxn_cuda_init_atomdata */
202     ad->xq = NULL;
203     ad->f  = NULL;
204
205     /* size -1 indicates that the respective array hasn't been initialized yet */
206     ad->natoms = -1;
207     ad->nalloc = -1;
208 }
209
210 /*! Selects the Ewald kernel type, analytical on SM 3.0 and later, tabulated on
211     earlier GPUs, single or twin cut-off. */
212 static int pick_ewald_kernel_type(bool                   bTwinCut,
213                                   const cuda_dev_info_t *dev_info)
214 {
215     bool bUseAnalyticalEwald, bForceAnalyticalEwald, bForceTabulatedEwald;
216     int  kernel_type;
217
218     /* Benchmarking/development environment variables to force the use of
219        analytical or tabulated Ewald kernel. */
220     bForceAnalyticalEwald = (getenv("GMX_CUDA_NB_ANA_EWALD") != NULL);
221     bForceTabulatedEwald  = (getenv("GMX_CUDA_NB_TAB_EWALD") != NULL);
222
223     if (bForceAnalyticalEwald && bForceTabulatedEwald)
224     {
225         gmx_incons("Both analytical and tabulated Ewald CUDA non-bonded kernels "
226                    "requested through environment variables.");
227     }
228
229     /* By default, on SM 3.0 and later use analytical Ewald, on earlier tabulated. */
230     if ((dev_info->prop.major >= 3 || bForceAnalyticalEwald) && !bForceTabulatedEwald)
231     {
232         bUseAnalyticalEwald = true;
233
234         if (debug)
235         {
236             fprintf(debug, "Using analytical Ewald CUDA kernels\n");
237         }
238     }
239     else
240     {
241         bUseAnalyticalEwald = false;
242
243         if (debug)
244         {
245             fprintf(debug, "Using tabulated Ewald CUDA kernels\n");
246         }
247     }
248
249     /* Use twin cut-off kernels if requested by bTwinCut or the env. var.
250        forces it (use it for debugging/benchmarking only). */
251     if (!bTwinCut && (getenv("GMX_CUDA_NB_EWALD_TWINCUT") == NULL))
252     {
253         kernel_type = bUseAnalyticalEwald ? eelCuEWALD_ANA : eelCuEWALD_TAB;
254     }
255     else
256     {
257         kernel_type = bUseAnalyticalEwald ? eelCuEWALD_ANA_TWIN : eelCuEWALD_TAB_TWIN;
258     }
259
260     return kernel_type;
261 }
262
263 /*! Copies all parameters related to the cut-off from ic to nbp */
264 static void set_cutoff_parameters(cu_nbparam_t              *nbp,
265                                   const interaction_const_t *ic)
266 {
267     nbp->ewald_beta       = ic->ewaldcoeff_q;
268     nbp->sh_ewald         = ic->sh_ewald;
269     nbp->epsfac           = ic->epsfac;
270     nbp->two_k_rf         = 2.0 * ic->k_rf;
271     nbp->c_rf             = ic->c_rf;
272     nbp->rvdw_sq          = ic->rvdw * ic->rvdw;
273     nbp->rcoulomb_sq      = ic->rcoulomb * ic->rcoulomb;
274     nbp->rlist_sq         = ic->rlist * ic->rlist;
275
276     nbp->sh_lj_ewald      = ic->sh_lj_ewald;
277     nbp->ewaldcoeff_lj    = ic->ewaldcoeff_lj;
278
279     nbp->rvdw_switch      = ic->rvdw_switch;
280     nbp->dispersion_shift = ic->dispersion_shift;
281     nbp->repulsion_shift  = ic->repulsion_shift;
282     nbp->vdw_switch       = ic->vdw_switch;
283 }
284
285 /*! Initializes the nonbonded parameter data structure. */
286 static void init_nbparam(cu_nbparam_t              *nbp,
287                          const interaction_const_t *ic,
288                          const nbnxn_atomdata_t    *nbat,
289                          const cuda_dev_info_t     *dev_info)
290 {
291     cudaError_t stat;
292     int         ntypes, nnbfp, nnbfp_comb;
293
294     ntypes  = nbat->ntype;
295
296     set_cutoff_parameters(nbp, ic);
297
298     if (ic->vdwtype == evdwCUT)
299     {
300         switch (ic->vdw_modifier)
301         {
302             case eintmodNONE:
303             case eintmodPOTSHIFT:
304                 nbp->vdwtype = evdwCuCUT;
305                 break;
306             case eintmodFORCESWITCH:
307                 nbp->vdwtype = evdwCuFSWITCH;
308                 break;
309             case eintmodPOTSWITCH:
310                 nbp->vdwtype = evdwCuPSWITCH;
311                 break;
312             default:
313                 gmx_incons("The requested VdW interaction modifier is not implemented in the CUDA GPU accelerated kernels!");
314                 break;
315         }
316     }
317     else if (ic->vdwtype == evdwPME)
318     {
319         if (ic->ljpme_comb_rule == ljcrGEOM)
320         {
321             assert(nbat->comb_rule == ljcrGEOM);
322             nbp->vdwtype = evdwCuEWALDGEOM;
323         }
324         else
325         {
326             assert(nbat->comb_rule == ljcrLB);
327             nbp->vdwtype = evdwCuEWALDLB;
328         }
329     }
330     else
331     {
332         gmx_incons("The requested VdW type is not implemented in the CUDA GPU accelerated kernels!");
333     }
334
335     if (ic->eeltype == eelCUT)
336     {
337         nbp->eeltype = eelCuCUT;
338     }
339     else if (EEL_RF(ic->eeltype))
340     {
341         nbp->eeltype = eelCuRF;
342     }
343     else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
344     {
345         /* Initially rcoulomb == rvdw, so it's surely not twin cut-off. */
346         nbp->eeltype = pick_ewald_kernel_type(false, dev_info);
347     }
348     else
349     {
350         /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
351         gmx_incons("The requested electrostatics type is not implemented in the CUDA GPU accelerated kernels!");
352     }
353
354     /* generate table for PME */
355     nbp->coulomb_tab = NULL;
356     if (nbp->eeltype == eelCuEWALD_TAB || nbp->eeltype == eelCuEWALD_TAB_TWIN)
357     {
358         init_ewald_coulomb_force_table(nbp, dev_info);
359     }
360
361     nnbfp      = 2*ntypes*ntypes;
362     nnbfp_comb = 2*ntypes;
363
364     stat  = cudaMalloc((void **)&nbp->nbfp, nnbfp*sizeof(*nbp->nbfp));
365     CU_RET_ERR(stat, "cudaMalloc failed on nbp->nbfp");
366     cu_copy_H2D(nbp->nbfp, nbat->nbfp, nnbfp*sizeof(*nbp->nbfp));
367
368
369     if (ic->vdwtype == evdwPME)
370     {
371         stat  = cudaMalloc((void **)&nbp->nbfp_comb, nnbfp_comb*sizeof(*nbp->nbfp_comb));
372         CU_RET_ERR(stat, "cudaMalloc failed on nbp->nbfp_comb");
373         cu_copy_H2D(nbp->nbfp_comb, nbat->nbfp_comb, nnbfp_comb*sizeof(*nbp->nbfp_comb));
374     }
375
376 #ifdef TEXOBJ_SUPPORTED
377     /* Only device CC >= 3.0 (Kepler and later) support texture objects */
378     if (dev_info->prop.major >= 3)
379     {
380         cudaResourceDesc rd;
381         cudaTextureDesc  td;
382
383         memset(&rd, 0, sizeof(rd));
384         rd.resType                  = cudaResourceTypeLinear;
385         rd.res.linear.devPtr        = nbp->nbfp;
386         rd.res.linear.desc.f        = cudaChannelFormatKindFloat;
387         rd.res.linear.desc.x        = 32;
388         rd.res.linear.sizeInBytes   = nnbfp*sizeof(*nbp->nbfp);
389
390         memset(&td, 0, sizeof(td));
391         td.readMode                 = cudaReadModeElementType;
392         stat = cudaCreateTextureObject(&nbp->nbfp_texobj, &rd, &td, NULL);
393         CU_RET_ERR(stat, "cudaCreateTextureObject on nbfp_texobj failed");
394
395         if (ic->vdwtype == evdwPME)
396         {
397             memset(&rd, 0, sizeof(rd));
398             rd.resType                  = cudaResourceTypeLinear;
399             rd.res.linear.devPtr        = nbp->nbfp_comb;
400             rd.res.linear.desc.f        = cudaChannelFormatKindFloat;
401             rd.res.linear.desc.x        = 32;
402             rd.res.linear.sizeInBytes   = nnbfp_comb*sizeof(*nbp->nbfp_comb);
403
404             memset(&td, 0, sizeof(td));
405             td.readMode = cudaReadModeElementType;
406             stat        = cudaCreateTextureObject(&nbp->nbfp_comb_texobj, &rd, &td, NULL);
407             CU_RET_ERR(stat, "cudaCreateTextureObject on nbfp_comb_texobj failed");
408         }
409     }
410     else
411 #endif
412     {
413         cudaChannelFormatDesc cd = cudaCreateChannelDesc<float>();
414         stat = cudaBindTexture(NULL, &nbnxn_cuda_get_nbfp_texref(),
415                                nbp->nbfp, &cd, nnbfp*sizeof(*nbp->nbfp));
416         CU_RET_ERR(stat, "cudaBindTexture on nbfp_texref failed");
417
418         if (ic->vdwtype == evdwPME)
419         {
420             stat = cudaBindTexture(NULL, &nbnxn_cuda_get_nbfp_comb_texref(),
421                                    nbp->nbfp_comb, &cd, nnbfp_comb*sizeof(*nbp->nbfp_comb));
422             CU_RET_ERR(stat, "cudaBindTexture on nbfp_comb_texref failed");
423         }
424     }
425 }
426
427 /*! Re-generate the GPU Ewald force table, resets rlist, and update the
428  *  electrostatic type switching to twin cut-off (or back) if needed. */
429 void nbnxn_cuda_pme_loadbal_update_param(nbnxn_cuda_ptr_t           cu_nb,
430                                          const interaction_const_t *ic)
431 {
432     cu_nbparam_t *nbp = cu_nb->nbparam;
433
434     set_cutoff_parameters(nbp, ic);
435
436     nbp->eeltype        = pick_ewald_kernel_type(ic->rcoulomb != ic->rvdw,
437                                                  cu_nb->dev_info);
438
439     init_ewald_coulomb_force_table(cu_nb->nbparam, cu_nb->dev_info);
440 }
441
442 /*! Initializes the pair list data structure. */
443 static void init_plist(cu_plist_t *pl)
444 {
445     /* initialize to NULL pointers to data that is not allocated here and will
446        need reallocation in nbnxn_cuda_init_pairlist */
447     pl->sci     = NULL;
448     pl->cj4     = NULL;
449     pl->excl    = NULL;
450
451     /* size -1 indicates that the respective array hasn't been initialized yet */
452     pl->na_c        = -1;
453     pl->nsci        = -1;
454     pl->sci_nalloc  = -1;
455     pl->ncj4        = -1;
456     pl->cj4_nalloc  = -1;
457     pl->nexcl       = -1;
458     pl->excl_nalloc = -1;
459     pl->bDoPrune    = false;
460 }
461
462 /*! Initializes the timer data structure. */
463 static void init_timers(cu_timers_t *t, bool bUseTwoStreams)
464 {
465     cudaError_t stat;
466     int         eventflags = ( bUseCudaEventBlockingSync ? cudaEventBlockingSync : cudaEventDefault );
467
468     stat = cudaEventCreateWithFlags(&(t->start_atdat), eventflags);
469     CU_RET_ERR(stat, "cudaEventCreate on start_atdat failed");
470     stat = cudaEventCreateWithFlags(&(t->stop_atdat), eventflags);
471     CU_RET_ERR(stat, "cudaEventCreate on stop_atdat failed");
472
473     /* The non-local counters/stream (second in the array) are needed only with DD. */
474     for (int i = 0; i <= (bUseTwoStreams ? 1 : 0); i++)
475     {
476         stat = cudaEventCreateWithFlags(&(t->start_nb_k[i]), eventflags);
477         CU_RET_ERR(stat, "cudaEventCreate on start_nb_k failed");
478         stat = cudaEventCreateWithFlags(&(t->stop_nb_k[i]), eventflags);
479         CU_RET_ERR(stat, "cudaEventCreate on stop_nb_k failed");
480
481
482         stat = cudaEventCreateWithFlags(&(t->start_pl_h2d[i]), eventflags);
483         CU_RET_ERR(stat, "cudaEventCreate on start_pl_h2d failed");
484         stat = cudaEventCreateWithFlags(&(t->stop_pl_h2d[i]), eventflags);
485         CU_RET_ERR(stat, "cudaEventCreate on stop_pl_h2d failed");
486
487         stat = cudaEventCreateWithFlags(&(t->start_nb_h2d[i]), eventflags);
488         CU_RET_ERR(stat, "cudaEventCreate on start_nb_h2d failed");
489         stat = cudaEventCreateWithFlags(&(t->stop_nb_h2d[i]), eventflags);
490         CU_RET_ERR(stat, "cudaEventCreate on stop_nb_h2d failed");
491
492         stat = cudaEventCreateWithFlags(&(t->start_nb_d2h[i]), eventflags);
493         CU_RET_ERR(stat, "cudaEventCreate on start_nb_d2h failed");
494         stat = cudaEventCreateWithFlags(&(t->stop_nb_d2h[i]), eventflags);
495         CU_RET_ERR(stat, "cudaEventCreate on stop_nb_d2h failed");
496     }
497 }
498
499 /*! Initializes the timings data structure. */
500 static void init_timings(wallclock_gpu_t *t)
501 {
502     int i, j;
503
504     t->nb_h2d_t = 0.0;
505     t->nb_d2h_t = 0.0;
506     t->nb_c     = 0;
507     t->pl_h2d_t = 0.0;
508     t->pl_h2d_c = 0;
509     for (i = 0; i < 2; i++)
510     {
511         for (j = 0; j < 2; j++)
512         {
513             t->ktime[i][j].t = 0.0;
514             t->ktime[i][j].c = 0;
515         }
516     }
517 }
518
519 void nbnxn_cuda_init(FILE                 *fplog,
520                      nbnxn_cuda_ptr_t     *p_cu_nb,
521                      const gmx_gpu_info_t *gpu_info,
522                      const gmx_gpu_opt_t  *gpu_opt,
523                      int                   my_gpu_index,
524                      gmx_bool              bLocalAndNonlocal)
525 {
526     cudaError_t       stat;
527     nbnxn_cuda_ptr_t  nb;
528     char              sbuf[STRLEN];
529     bool              bStreamSync, bNoStreamSync, bTMPIAtomics, bX86, bOldDriver;
530     int               cuda_drv_ver;
531
532     assert(gpu_info);
533
534     if (p_cu_nb == NULL)
535     {
536         return;
537     }
538
539     snew(nb, 1);
540     snew(nb->atdat, 1);
541     snew(nb->nbparam, 1);
542     snew(nb->plist[eintLocal], 1);
543     if (bLocalAndNonlocal)
544     {
545         snew(nb->plist[eintNonlocal], 1);
546     }
547
548     nb->bUseTwoStreams = bLocalAndNonlocal;
549
550     snew(nb->timers, 1);
551     snew(nb->timings, 1);
552
553     /* init nbst */
554     pmalloc((void**)&nb->nbst.e_lj, sizeof(*nb->nbst.e_lj));
555     pmalloc((void**)&nb->nbst.e_el, sizeof(*nb->nbst.e_el));
556     pmalloc((void**)&nb->nbst.fshift, SHIFTS * sizeof(*nb->nbst.fshift));
557
558     init_plist(nb->plist[eintLocal]);
559
560     /* set device info, just point it to the right GPU among the detected ones */
561     nb->dev_info = &gpu_info->cuda_dev[get_gpu_device_id(gpu_info, gpu_opt, my_gpu_index)];
562
563     /* local/non-local GPU streams */
564     stat = cudaStreamCreate(&nb->stream[eintLocal]);
565     CU_RET_ERR(stat, "cudaStreamCreate on stream[eintLocal] failed");
566     if (nb->bUseTwoStreams)
567     {
568         init_plist(nb->plist[eintNonlocal]);
569
570         /* CUDA stream priority available in the CUDA RT 5.5 API.
571          * Note that the device we're running on does not have to support
572          * priorities, because we are querying the priority range which in this
573          * case will be a single value.
574          */
575 #if CUDA_VERSION >= 5050
576         {
577             int highest_priority;
578             stat = cudaDeviceGetStreamPriorityRange(NULL, &highest_priority);
579             CU_RET_ERR(stat, "cudaDeviceGetStreamPriorityRange failed");
580
581             stat = cudaStreamCreateWithPriority(&nb->stream[eintNonlocal],
582                                                 cudaStreamDefault,
583                                                 highest_priority);
584             CU_RET_ERR(stat, "cudaStreamCreateWithPriority on stream[eintNonlocal] failed");
585         }
586 #else
587         stat = cudaStreamCreate(&nb->stream[eintNonlocal]);
588         CU_RET_ERR(stat, "cudaStreamCreate on stream[eintNonlocal] failed");
589 #endif
590     }
591
592     /* init events for sychronization (timing disabled for performance reasons!) */
593     stat = cudaEventCreateWithFlags(&nb->nonlocal_done, cudaEventDisableTiming);
594     CU_RET_ERR(stat, "cudaEventCreate on nonlocal_done failed");
595     stat = cudaEventCreateWithFlags(&nb->misc_ops_done, cudaEventDisableTiming);
596     CU_RET_ERR(stat, "cudaEventCreate on misc_ops_one failed");
597
598     /* On GPUs with ECC enabled, cudaStreamSynchronize shows a large overhead
599      * (which increases with shorter time/step) caused by a known CUDA driver bug.
600      * To work around the issue we'll use an (admittedly fragile) memory polling
601      * waiting to preserve performance. This requires support for atomic
602      * operations and only works on x86/x86_64.
603      * With polling wait event-timing also needs to be disabled.
604      *
605      * The overhead is greatly reduced in API v5.0 drivers and the improvement
606      * is independent of runtime version. Hence, with API v5.0 drivers and later
607      * we won't switch to polling.
608      *
609      * NOTE: Unfortunately, this is known to fail when GPUs are shared by (t)MPI,
610      * ranks so we will also disable it in that case.
611      */
612
613     bStreamSync    = getenv("GMX_CUDA_STREAMSYNC") != NULL;
614     bNoStreamSync  = getenv("GMX_NO_CUDA_STREAMSYNC") != NULL;
615
616 #ifdef TMPI_ATOMICS
617     bTMPIAtomics = true;
618 #else
619     bTMPIAtomics = false;
620 #endif
621
622 #ifdef GMX_TARGET_X86
623     bX86 = true;
624 #else
625     bX86 = false;
626 #endif
627
628     if (bStreamSync && bNoStreamSync)
629     {
630         gmx_fatal(FARGS, "Conflicting environment variables: both GMX_CUDA_STREAMSYNC and GMX_NO_CUDA_STREAMSYNC defined");
631     }
632
633     stat = cudaDriverGetVersion(&cuda_drv_ver);
634     CU_RET_ERR(stat, "cudaDriverGetVersion failed");
635
636     bOldDriver = (cuda_drv_ver < 5000);
637
638     if ((nb->dev_info->prop.ECCEnabled == 1) && bOldDriver)
639     {
640         /* Polling wait should be used instead of cudaStreamSynchronize only if:
641          *   - ECC is ON & driver is old (checked above),
642          *   - we're on x86/x86_64,
643          *   - atomics are available, and
644          *   - GPUs are not being shared.
645          */
646         bool bShouldUsePollSync = (bX86 && bTMPIAtomics &&
647                                    (gmx_count_gpu_dev_shared(gpu_opt) < 1));
648
649         if (bStreamSync)
650         {
651             nb->bUseStreamSync = true;
652
653             /* only warn if polling should be used */
654             if (bShouldUsePollSync)
655             {
656                 md_print_warn(fplog,
657                               "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0, but\n"
658                               "      cudaStreamSynchronize waiting is forced by the GMX_CUDA_STREAMSYNC env. var.\n");
659             }
660         }
661         else
662         {
663             nb->bUseStreamSync = !bShouldUsePollSync;
664
665             if (bShouldUsePollSync)
666             {
667                 md_print_warn(fplog,
668                               "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0, known to\n"
669                               "      cause performance loss. Switching to the alternative polling GPU wait.\n"
670                               "      If you encounter issues, switch back to standard GPU waiting by setting\n"
671                               "      the GMX_CUDA_STREAMSYNC environment variable.\n");
672             }
673             else
674             {
675                 /* Tell the user that the ECC+old driver combination can be bad */
676                 sprintf(sbuf,
677                         "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0.\n"
678                         "      A known bug in this driver version can cause performance loss.\n"
679                         "      However, the polling wait workaround can not be used because\n%s\n"
680                         "      Consider updating the driver or turning ECC off.",
681                         (bX86 && bTMPIAtomics) ?
682                         "      GPU(s) are being oversubscribed." :
683                         "      atomic operations are not supported by the platform/CPU+compiler.");
684                 md_print_warn(fplog, sbuf);
685             }
686         }
687     }
688     else
689     {
690         if (bNoStreamSync)
691         {
692             nb->bUseStreamSync = false;
693
694             md_print_warn(fplog,
695                           "NOTE: Polling wait for GPU synchronization requested by GMX_NO_CUDA_STREAMSYNC\n");
696         }
697         else
698         {
699             /* no/off ECC, cudaStreamSynchronize not turned off by env. var. */
700             nb->bUseStreamSync = true;
701         }
702     }
703
704     /* CUDA timing disabled as event timers don't work:
705        - with multiple streams = domain-decomposition;
706        - with the polling waiting hack (without cudaStreamSynchronize);
707        - when turned off by GMX_DISABLE_CUDA_TIMING.
708      */
709     nb->bDoTime = (!nb->bUseTwoStreams && nb->bUseStreamSync &&
710                    (getenv("GMX_DISABLE_CUDA_TIMING") == NULL));
711
712     if (nb->bDoTime)
713     {
714         init_timers(nb->timers, nb->bUseTwoStreams);
715         init_timings(nb->timings);
716     }
717
718     /* set the kernel type for the current GPU */
719     /* pick L1 cache configuration */
720     nbnxn_cuda_set_cacheconfig(nb->dev_info);
721
722     *p_cu_nb = nb;
723
724     if (debug)
725     {
726         fprintf(debug, "Initialized CUDA data structures.\n");
727     }
728 }
729
730 void nbnxn_cuda_init_const(nbnxn_cuda_ptr_t                cu_nb,
731                            const interaction_const_t      *ic,
732                            const nonbonded_verlet_group_t *nbv_group)
733 {
734     init_atomdata_first(cu_nb->atdat, nbv_group[0].nbat->ntype);
735     init_nbparam(cu_nb->nbparam, ic, nbv_group[0].nbat, cu_nb->dev_info);
736
737     /* clear energy and shift force outputs */
738     nbnxn_cuda_clear_e_fshift(cu_nb);
739 }
740
741 void nbnxn_cuda_init_pairlist(nbnxn_cuda_ptr_t        cu_nb,
742                               const nbnxn_pairlist_t *h_plist,
743                               int                     iloc)
744 {
745     char          sbuf[STRLEN];
746     cudaError_t   stat;
747     bool          bDoTime    = cu_nb->bDoTime;
748     cudaStream_t  stream     = cu_nb->stream[iloc];
749     cu_plist_t   *d_plist    = cu_nb->plist[iloc];
750
751     if (d_plist->na_c < 0)
752     {
753         d_plist->na_c = h_plist->na_ci;
754     }
755     else
756     {
757         if (d_plist->na_c != h_plist->na_ci)
758         {
759             sprintf(sbuf, "In cu_init_plist: the #atoms per cell has changed (from %d to %d)",
760                     d_plist->na_c, h_plist->na_ci);
761             gmx_incons(sbuf);
762         }
763     }
764
765     if (bDoTime)
766     {
767         stat = cudaEventRecord(cu_nb->timers->start_pl_h2d[iloc], stream);
768         CU_RET_ERR(stat, "cudaEventRecord failed");
769     }
770
771     cu_realloc_buffered((void **)&d_plist->sci, h_plist->sci, sizeof(*d_plist->sci),
772                         &d_plist->nsci, &d_plist->sci_nalloc,
773                         h_plist->nsci,
774                         stream, true);
775
776     cu_realloc_buffered((void **)&d_plist->cj4, h_plist->cj4, sizeof(*d_plist->cj4),
777                         &d_plist->ncj4, &d_plist->cj4_nalloc,
778                         h_plist->ncj4,
779                         stream, true);
780
781     cu_realloc_buffered((void **)&d_plist->excl, h_plist->excl, sizeof(*d_plist->excl),
782                         &d_plist->nexcl, &d_plist->excl_nalloc,
783                         h_plist->nexcl,
784                         stream, true);
785
786     if (bDoTime)
787     {
788         stat = cudaEventRecord(cu_nb->timers->stop_pl_h2d[iloc], stream);
789         CU_RET_ERR(stat, "cudaEventRecord failed");
790     }
791
792     /* need to prune the pair list during the next step */
793     d_plist->bDoPrune = true;
794 }
795
796 void nbnxn_cuda_upload_shiftvec(nbnxn_cuda_ptr_t        cu_nb,
797                                 const nbnxn_atomdata_t *nbatom)
798 {
799     cu_atomdata_t *adat  = cu_nb->atdat;
800     cudaStream_t   ls    = cu_nb->stream[eintLocal];
801
802     /* only if we have a dynamic box */
803     if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
804     {
805         cu_copy_H2D_async(adat->shift_vec, nbatom->shift_vec,
806                           SHIFTS * sizeof(*adat->shift_vec), ls);
807         adat->bShiftVecUploaded = true;
808     }
809 }
810
811 /*! Clears the first natoms_clear elements of the GPU nonbonded force output array. */
812 static void nbnxn_cuda_clear_f(nbnxn_cuda_ptr_t cu_nb, int natoms_clear)
813 {
814     cudaError_t    stat;
815     cu_atomdata_t *adat  = cu_nb->atdat;
816     cudaStream_t   ls    = cu_nb->stream[eintLocal];
817
818     stat = cudaMemsetAsync(adat->f, 0, natoms_clear * sizeof(*adat->f), ls);
819     CU_RET_ERR(stat, "cudaMemsetAsync on f falied");
820 }
821
822 /*! Clears nonbonded shift force output array and energy outputs on the GPU. */
823 static void nbnxn_cuda_clear_e_fshift(nbnxn_cuda_ptr_t cu_nb)
824 {
825     cudaError_t    stat;
826     cu_atomdata_t *adat  = cu_nb->atdat;
827     cudaStream_t   ls    = cu_nb->stream[eintLocal];
828
829     stat = cudaMemsetAsync(adat->fshift, 0, SHIFTS * sizeof(*adat->fshift), ls);
830     CU_RET_ERR(stat, "cudaMemsetAsync on fshift falied");
831     stat = cudaMemsetAsync(adat->e_lj, 0, sizeof(*adat->e_lj), ls);
832     CU_RET_ERR(stat, "cudaMemsetAsync on e_lj falied");
833     stat = cudaMemsetAsync(adat->e_el, 0, sizeof(*adat->e_el), ls);
834     CU_RET_ERR(stat, "cudaMemsetAsync on e_el falied");
835 }
836
837 void nbnxn_cuda_clear_outputs(nbnxn_cuda_ptr_t cu_nb, int flags)
838 {
839     nbnxn_cuda_clear_f(cu_nb, cu_nb->atdat->natoms);
840     /* clear shift force array and energies if the outputs were
841        used in the current step */
842     if (flags & GMX_FORCE_VIRIAL)
843     {
844         nbnxn_cuda_clear_e_fshift(cu_nb);
845     }
846 }
847
848 void nbnxn_cuda_init_atomdata(nbnxn_cuda_ptr_t        cu_nb,
849                               const nbnxn_atomdata_t *nbat)
850 {
851     cudaError_t    stat;
852     int            nalloc, natoms;
853     bool           realloced;
854     bool           bDoTime   = cu_nb->bDoTime;
855     cu_timers_t   *timers    = cu_nb->timers;
856     cu_atomdata_t *d_atdat   = cu_nb->atdat;
857     cudaStream_t   ls        = cu_nb->stream[eintLocal];
858
859     natoms    = nbat->natoms;
860     realloced = false;
861
862     if (bDoTime)
863     {
864         /* time async copy */
865         stat = cudaEventRecord(timers->start_atdat, ls);
866         CU_RET_ERR(stat, "cudaEventRecord failed");
867     }
868
869     /* need to reallocate if we have to copy more atoms than the amount of space
870        available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
871     if (natoms > d_atdat->nalloc)
872     {
873         nalloc = over_alloc_small(natoms);
874
875         /* free up first if the arrays have already been initialized */
876         if (d_atdat->nalloc != -1)
877         {
878             cu_free_buffered(d_atdat->f, &d_atdat->natoms, &d_atdat->nalloc);
879             cu_free_buffered(d_atdat->xq);
880             cu_free_buffered(d_atdat->atom_types);
881         }
882
883         stat = cudaMalloc((void **)&d_atdat->f, nalloc*sizeof(*d_atdat->f));
884         CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->f");
885         stat = cudaMalloc((void **)&d_atdat->xq, nalloc*sizeof(*d_atdat->xq));
886         CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->xq");
887
888         stat = cudaMalloc((void **)&d_atdat->atom_types, nalloc*sizeof(*d_atdat->atom_types));
889         CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->atom_types");
890
891         d_atdat->nalloc = nalloc;
892         realloced       = true;
893     }
894
895     d_atdat->natoms       = natoms;
896     d_atdat->natoms_local = nbat->natoms_local;
897
898     /* need to clear GPU f output if realloc happened */
899     if (realloced)
900     {
901         nbnxn_cuda_clear_f(cu_nb, nalloc);
902     }
903
904     cu_copy_H2D_async(d_atdat->atom_types, nbat->type,
905                       natoms*sizeof(*d_atdat->atom_types), ls);
906
907     if (bDoTime)
908     {
909         stat = cudaEventRecord(timers->stop_atdat, ls);
910         CU_RET_ERR(stat, "cudaEventRecord failed");
911     }
912 }
913
914 void nbnxn_cuda_free(nbnxn_cuda_ptr_t cu_nb)
915 {
916     cudaError_t      stat;
917     cu_atomdata_t   *atdat;
918     cu_nbparam_t    *nbparam;
919     cu_plist_t      *plist, *plist_nl;
920     cu_timers_t     *timers;
921
922     if (cu_nb == NULL)
923     {
924         return;
925     }
926
927     atdat       = cu_nb->atdat;
928     nbparam     = cu_nb->nbparam;
929     plist       = cu_nb->plist[eintLocal];
930     plist_nl    = cu_nb->plist[eintNonlocal];
931     timers      = cu_nb->timers;
932
933     if (nbparam->eeltype == eelCuEWALD_TAB || nbparam->eeltype == eelCuEWALD_TAB_TWIN)
934     {
935
936 #ifdef TEXOBJ_SUPPORTED
937         /* Only device CC >= 3.0 (Kepler and later) support texture objects */
938         if (cu_nb->dev_info->prop.major >= 3)
939         {
940             stat = cudaDestroyTextureObject(nbparam->coulomb_tab_texobj);
941             CU_RET_ERR(stat, "cudaDestroyTextureObject on coulomb_tab_texobj failed");
942         }
943         else
944 #endif
945         {
946             stat = cudaUnbindTexture(nbnxn_cuda_get_coulomb_tab_texref());
947             CU_RET_ERR(stat, "cudaUnbindTexture on coulomb_tab_texref failed");
948         }
949         cu_free_buffered(nbparam->coulomb_tab, &nbparam->coulomb_tab_size);
950     }
951
952     stat = cudaEventDestroy(cu_nb->nonlocal_done);
953     CU_RET_ERR(stat, "cudaEventDestroy failed on timers->nonlocal_done");
954     stat = cudaEventDestroy(cu_nb->misc_ops_done);
955     CU_RET_ERR(stat, "cudaEventDestroy failed on timers->misc_ops_done");
956
957     if (cu_nb->bDoTime)
958     {
959         stat = cudaEventDestroy(timers->start_atdat);
960         CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_atdat");
961         stat = cudaEventDestroy(timers->stop_atdat);
962         CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_atdat");
963
964         /* The non-local counters/stream (second in the array) are needed only with DD. */
965         for (int i = 0; i <= (cu_nb->bUseTwoStreams ? 1 : 0); i++)
966         {
967             stat = cudaEventDestroy(timers->start_nb_k[i]);
968             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_k");
969             stat = cudaEventDestroy(timers->stop_nb_k[i]);
970             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_k");
971
972             stat = cudaEventDestroy(timers->start_pl_h2d[i]);
973             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_pl_h2d");
974             stat = cudaEventDestroy(timers->stop_pl_h2d[i]);
975             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_pl_h2d");
976
977             stat = cudaStreamDestroy(cu_nb->stream[i]);
978             CU_RET_ERR(stat, "cudaStreamDestroy failed on stream");
979
980             stat = cudaEventDestroy(timers->start_nb_h2d[i]);
981             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_h2d");
982             stat = cudaEventDestroy(timers->stop_nb_h2d[i]);
983             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_h2d");
984
985             stat = cudaEventDestroy(timers->start_nb_d2h[i]);
986             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_d2h");
987             stat = cudaEventDestroy(timers->stop_nb_d2h[i]);
988             CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_d2h");
989         }
990     }
991
992 #ifdef TEXOBJ_SUPPORTED
993     /* Only device CC >= 3.0 (Kepler and later) support texture objects */
994     if (cu_nb->dev_info->prop.major >= 3)
995     {
996         stat = cudaDestroyTextureObject(nbparam->nbfp_texobj);
997         CU_RET_ERR(stat, "cudaDestroyTextureObject on nbfp_texobj failed");
998     }
999     else
1000 #endif
1001     {
1002         stat = cudaUnbindTexture(nbnxn_cuda_get_nbfp_texref());
1003         CU_RET_ERR(stat, "cudaUnbindTexture on nbfp_texref failed");
1004     }
1005     cu_free_buffered(nbparam->nbfp);
1006
1007     if (nbparam->vdwtype == evdwCuEWALDGEOM || nbparam->vdwtype == evdwCuEWALDLB)
1008     {
1009 #ifdef TEXOBJ_SUPPORTED
1010         /* Only device CC >= 3.0 (Kepler and later) support texture objects */
1011         if (cu_nb->dev_info->prop.major >= 3)
1012         {
1013             stat = cudaDestroyTextureObject(nbparam->nbfp_comb_texobj);
1014             CU_RET_ERR(stat, "cudaDestroyTextureObject on nbfp_comb_texobj failed");
1015         }
1016         else
1017 #endif
1018         {
1019             stat = cudaUnbindTexture(nbnxn_cuda_get_nbfp_comb_texref());
1020             CU_RET_ERR(stat, "cudaUnbindTexture on nbfp_comb_texref failed");
1021         }
1022         cu_free_buffered(nbparam->nbfp_comb);
1023     }
1024
1025     stat = cudaFree(atdat->shift_vec);
1026     CU_RET_ERR(stat, "cudaFree failed on atdat->shift_vec");
1027     stat = cudaFree(atdat->fshift);
1028     CU_RET_ERR(stat, "cudaFree failed on atdat->fshift");
1029
1030     stat = cudaFree(atdat->e_lj);
1031     CU_RET_ERR(stat, "cudaFree failed on atdat->e_lj");
1032     stat = cudaFree(atdat->e_el);
1033     CU_RET_ERR(stat, "cudaFree failed on atdat->e_el");
1034
1035     cu_free_buffered(atdat->f, &atdat->natoms, &atdat->nalloc);
1036     cu_free_buffered(atdat->xq);
1037     cu_free_buffered(atdat->atom_types, &atdat->ntypes);
1038
1039     cu_free_buffered(plist->sci, &plist->nsci, &plist->sci_nalloc);
1040     cu_free_buffered(plist->cj4, &plist->ncj4, &plist->cj4_nalloc);
1041     cu_free_buffered(plist->excl, &plist->nexcl, &plist->excl_nalloc);
1042     if (cu_nb->bUseTwoStreams)
1043     {
1044         cu_free_buffered(plist_nl->sci, &plist_nl->nsci, &plist_nl->sci_nalloc);
1045         cu_free_buffered(plist_nl->cj4, &plist_nl->ncj4, &plist_nl->cj4_nalloc);
1046         cu_free_buffered(plist_nl->excl, &plist_nl->nexcl, &plist->excl_nalloc);
1047     }
1048
1049     sfree(atdat);
1050     sfree(nbparam);
1051     sfree(plist);
1052     if (cu_nb->bUseTwoStreams)
1053     {
1054         sfree(plist_nl);
1055     }
1056     sfree(timers);
1057     sfree(cu_nb->timings);
1058     sfree(cu_nb);
1059
1060     if (debug)
1061     {
1062         fprintf(debug, "Cleaned up CUDA data structures.\n");
1063     }
1064 }
1065
1066 void cu_synchstream_atdat(nbnxn_cuda_ptr_t cu_nb, int iloc)
1067 {
1068     cudaError_t  stat;
1069     cudaStream_t stream = cu_nb->stream[iloc];
1070
1071     stat = cudaStreamWaitEvent(stream, cu_nb->timers->stop_atdat, 0);
1072     CU_RET_ERR(stat, "cudaStreamWaitEvent failed");
1073 }
1074
1075 wallclock_gpu_t * nbnxn_cuda_get_timings(nbnxn_cuda_ptr_t cu_nb)
1076 {
1077     return (cu_nb != NULL && cu_nb->bDoTime) ? cu_nb->timings : NULL;
1078 }
1079
1080 void nbnxn_cuda_reset_timings(nbnxn_cuda_ptr_t cu_nb)
1081 {
1082     if (cu_nb->bDoTime)
1083     {
1084         init_timings(cu_nb->timings);
1085     }
1086 }
1087
1088 int nbnxn_cuda_min_ci_balanced(nbnxn_cuda_ptr_t cu_nb)
1089 {
1090     return cu_nb != NULL ?
1091            gpu_min_ci_balanced_factor*cu_nb->dev_info->prop.multiProcessorCount : 0;
1092
1093 }
1094
1095 gmx_bool nbnxn_cuda_is_kernel_ewald_analytical(const nbnxn_cuda_ptr_t cu_nb)
1096 {
1097     return ((cu_nb->nbparam->eeltype == eelCuEWALD_ANA) ||
1098             (cu_nb->nbparam->eeltype == eelCuEWALD_ANA_TWIN));
1099 }