1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
4 * This source code is part of
8 * GROningen MAchine for Chemical Simulations
10 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12 * Copyright (c) 2001-2012, The GROMACS development team,
13 * check out http://www.gromacs.org for more information.
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License
17 * as published by the Free Software Foundation; either version 2
18 * of the License, or (at your option) any later version.
20 * If you want to redistribute modifications, please consider that
21 * scientific software is very special. Version control is crucial -
22 * bugs must be traceable. We will be happy to consider code for
23 * inclusion in the official distribution, but derived work must not
24 * be called official GROMACS. Details are found in the README & COPYING
25 * files - if they are missing, get the official version at www.gromacs.org.
27 * To help us fund GROMACS development, we humbly ask that you cite
28 * the papers on the package - you can find them in the top README file.
30 * For more info, check our website at http://www.gromacs.org
33 * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
45 #include "gmx_fatal.h"
49 #include "types/nb_verlet.h"
50 #include "types/interaction_const.h"
51 #include "types/force_flags.h"
52 #include "../nbnxn_consts.h"
53 #include "gmx_detect_hardware.h"
55 #include "nbnxn_cuda_types.h"
56 #include "../../gmxlib/cuda_tools/cudautils.cuh"
57 #include "nbnxn_cuda_data_mgmt.h"
58 #include "pmalloc_cuda.h"
59 #include "gpu_utils.h"
61 static bool bUseCudaEventBlockingSync = false; /* makes the CPU thread block */
63 /* This is a heuristically determined parameter for the Fermi architecture for
64 * the minimum size of ci lists by multiplying this constant with the # of
65 * multiprocessors on the current device.
67 static unsigned int gpu_min_ci_balanced_factor = 40;
69 /* Functions from nbnxn_cuda.cu */
70 extern void nbnxn_cuda_set_cacheconfig(cuda_dev_info_t *devinfo);
71 extern const struct texture<float, 1, cudaReadModeElementType>& nbnxn_cuda_get_nbfp_texref();
72 extern const struct texture<float, 1, cudaReadModeElementType>& nbnxn_cuda_get_coulomb_tab_texref();
74 /* We should actually be using md_print_warn in md_logging.c,
75 * but we can't include mpi.h in CUDA code.
77 static void md_print_warn(FILE *fplog,
84 /* We should only print to stderr on the master node,
85 * in most cases fplog is only set on the master node, so this works.
88 fprintf(stderr, "\n");
89 vfprintf(stderr, fmt, ap);
90 fprintf(stderr, "\n");
95 vfprintf(fplog, fmt, ap);
103 static void nbnxn_cuda_clear_e_fshift(nbnxn_cuda_ptr_t cu_nb);
106 /*! Tabulates the Ewald Coulomb force and initializes the size/scale
107 and the table GPU array. If called with an already allocated table,
108 it just re-uploads the table.
110 static void init_ewald_coulomb_force_table(cu_nbparam_t *nbp,
111 const cuda_dev_info_t *dev_info)
113 float *ftmp, *coul_tab;
118 tabsize = GPU_EWALD_COULOMB_FORCE_TABLE_SIZE;
119 /* Subtract 2 iso 1 to avoid access out of range due to rounding */
120 tabscale = (tabsize - 2) / sqrt(nbp->rcoulomb_sq);
122 pmalloc((void**)&ftmp, tabsize*sizeof(*ftmp));
124 table_spline3_fill_ewald_lr(ftmp, NULL, NULL, tabsize,
125 1/tabscale, nbp->ewald_beta);
127 /* If the table pointer == NULL the table is generated the first time =>
128 the array pointer will be saved to nbparam and the texture is bound.
130 coul_tab = nbp->coulomb_tab;
131 if (coul_tab == NULL)
133 stat = cudaMalloc((void **)&coul_tab, tabsize*sizeof(*coul_tab));
134 CU_RET_ERR(stat, "cudaMalloc failed on coul_tab");
136 nbp->coulomb_tab = coul_tab;
138 #ifdef TEXOBJ_SUPPORTED
139 /* Only device CC >= 3.0 (Kepler and later) support texture objects */
140 if (dev_info->prop.major >= 3)
143 memset(&rd, 0, sizeof(rd));
144 rd.resType = cudaResourceTypeLinear;
145 rd.res.linear.devPtr = nbp->coulomb_tab;
146 rd.res.linear.desc.f = cudaChannelFormatKindFloat;
147 rd.res.linear.desc.x = 32;
148 rd.res.linear.sizeInBytes = tabsize*sizeof(*coul_tab);
151 memset(&td, 0, sizeof(td));
152 td.readMode = cudaReadModeElementType;
153 stat = cudaCreateTextureObject(&nbp->coulomb_tab_texobj, &rd, &td, NULL);
154 CU_RET_ERR(stat, "cudaCreateTextureObject on coulomb_tab_texobj failed");
159 cudaChannelFormatDesc cd = cudaCreateChannelDesc<float>();
160 stat = cudaBindTexture(NULL, &nbnxn_cuda_get_coulomb_tab_texref(),
161 coul_tab, &cd, tabsize*sizeof(*coul_tab));
162 CU_RET_ERR(stat, "cudaBindTexture on coulomb_tab_texref failed");
166 cu_copy_H2D(coul_tab, ftmp, tabsize*sizeof(*coul_tab));
168 nbp->coulomb_tab_size = tabsize;
169 nbp->coulomb_tab_scale = tabscale;
175 /*! Initializes the atomdata structure first time, it only gets filled at
177 static void init_atomdata_first(cu_atomdata_t *ad, int ntypes)
182 stat = cudaMalloc((void**)&ad->shift_vec, SHIFTS*sizeof(*ad->shift_vec));
183 CU_RET_ERR(stat, "cudaMalloc failed on ad->shift_vec");
184 ad->bShiftVecUploaded = false;
186 stat = cudaMalloc((void**)&ad->fshift, SHIFTS*sizeof(*ad->fshift));
187 CU_RET_ERR(stat, "cudaMalloc failed on ad->fshift");
189 stat = cudaMalloc((void**)&ad->e_lj, sizeof(*ad->e_lj));
190 CU_RET_ERR(stat, "cudaMalloc failed on ad->e_lj");
191 stat = cudaMalloc((void**)&ad->e_el, sizeof(*ad->e_el));
192 CU_RET_ERR(stat, "cudaMalloc failed on ad->e_el");
194 /* initialize to NULL poiters to data that is not allocated here and will
195 need reallocation in nbnxn_cuda_init_atomdata */
199 /* size -1 indicates that the respective array hasn't been initialized yet */
204 /*! Selects the Ewald kernel type, analytical on SM 3.0 and later, tabulated on
205 earlier GPUs, single or twin cut-off. */
206 static int pick_ewald_kernel_type(bool bTwinCut,
207 const cuda_dev_info_t *dev_info)
209 bool bUseAnalyticalEwald, bForceAnalyticalEwald, bForceTabulatedEwald;
212 /* Benchmarking/development environment variables to force the use of
213 analytical or tabulated Ewald kernel. */
214 bForceAnalyticalEwald = (getenv("GMX_CUDA_NB_ANA_EWALD") != NULL);
215 bForceTabulatedEwald = (getenv("GMX_CUDA_NB_TAB_EWALD") != NULL);
217 if (bForceAnalyticalEwald && bForceTabulatedEwald)
219 gmx_incons("Both analytical and tabulated Ewald CUDA non-bonded kernels "
220 "requested through environment variables.");
223 /* By default, on SM 3.0 and later use analytical Ewald, on earlier tabulated. */
224 if ((dev_info->prop.major >= 3 || bForceAnalyticalEwald) && !bForceTabulatedEwald)
226 bUseAnalyticalEwald = true;
230 fprintf(debug, "Using analytical Ewald CUDA kernels\n");
235 bUseAnalyticalEwald = false;
239 fprintf(debug, "Using tabulated Ewald CUDA kernels\n");
243 /* Use twin cut-off kernels if requested by bTwinCut or the env. var.
244 forces it (use it for debugging/benchmarking only). */
245 if (!bTwinCut && (getenv("GMX_CUDA_NB_EWALD_TWINCUT") == NULL))
247 kernel_type = bUseAnalyticalEwald ? eelCuEWALD_ANA : eelCuEWALD_TAB;
251 kernel_type = bUseAnalyticalEwald ? eelCuEWALD_ANA_TWIN : eelCuEWALD_TAB_TWIN;
258 /*! Initializes the nonbonded parameter data structure. */
259 static void init_nbparam(cu_nbparam_t *nbp,
260 const interaction_const_t *ic,
261 const nbnxn_atomdata_t *nbat,
262 const cuda_dev_info_t *dev_info)
267 ntypes = nbat->ntype;
269 nbp->ewald_beta = ic->ewaldcoeff_q;
270 nbp->sh_ewald = ic->sh_ewald;
271 nbp->epsfac = ic->epsfac;
272 nbp->two_k_rf = 2.0 * ic->k_rf;
273 nbp->c_rf = ic->c_rf;
274 nbp->rvdw_sq = ic->rvdw * ic->rvdw;
275 nbp->rcoulomb_sq= ic->rcoulomb * ic->rcoulomb;
276 nbp->rlist_sq = ic->rlist * ic->rlist;
277 nbp->sh_invrc6 = ic->sh_invrc6;
279 if (ic->eeltype == eelCUT)
281 nbp->eeltype = eelCuCUT;
283 else if (EEL_RF(ic->eeltype))
285 nbp->eeltype = eelCuRF;
287 else if ((EEL_PME(ic->eeltype) || ic->eeltype==eelEWALD))
289 /* Initially rcoulomb == rvdw, so it's surely not twin cut-off. */
290 nbp->eeltype = pick_ewald_kernel_type(false, dev_info);
294 /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
295 gmx_incons("The requested electrostatics type is not implemented in the CUDA GPU accelerated kernels!");
298 /* generate table for PME */
299 nbp->coulomb_tab = NULL;
300 if (nbp->eeltype == eelCuEWALD_TAB || nbp->eeltype == eelCuEWALD_TAB_TWIN)
302 init_ewald_coulomb_force_table(nbp, dev_info);
305 nnbfp = 2*ntypes*ntypes;
306 stat = cudaMalloc((void **)&nbp->nbfp, nnbfp*sizeof(*nbp->nbfp));
307 CU_RET_ERR(stat, "cudaMalloc failed on nbp->nbfp");
308 cu_copy_H2D(nbp->nbfp, nbat->nbfp, nnbfp*sizeof(*nbp->nbfp));
310 #ifdef TEXOBJ_SUPPORTED
311 /* Only device CC >= 3.0 (Kepler and later) support texture objects */
312 if (dev_info->prop.major >= 3)
315 memset(&rd, 0, sizeof(rd));
316 rd.resType = cudaResourceTypeLinear;
317 rd.res.linear.devPtr = nbp->nbfp;
318 rd.res.linear.desc.f = cudaChannelFormatKindFloat;
319 rd.res.linear.desc.x = 32;
320 rd.res.linear.sizeInBytes = nnbfp*sizeof(*nbp->nbfp);
323 memset(&td, 0, sizeof(td));
324 td.readMode = cudaReadModeElementType;
325 stat = cudaCreateTextureObject(&nbp->nbfp_texobj, &rd, &td, NULL);
326 CU_RET_ERR(stat, "cudaCreateTextureObject on nbfp_texobj failed");
331 cudaChannelFormatDesc cd = cudaCreateChannelDesc<float>();
332 stat = cudaBindTexture(NULL, &nbnxn_cuda_get_nbfp_texref(),
333 nbp->nbfp, &cd, nnbfp*sizeof(*nbp->nbfp));
334 CU_RET_ERR(stat, "cudaBindTexture on nbfp_texref failed");
338 /*! Re-generate the GPU Ewald force table, resets rlist, and update the
339 * electrostatic type switching to twin cut-off (or back) if needed. */
340 void nbnxn_cuda_pme_loadbal_update_param(nbnxn_cuda_ptr_t cu_nb,
341 const interaction_const_t *ic)
343 cu_nbparam_t *nbp = cu_nb->nbparam;
345 nbp->rlist_sq = ic->rlist * ic->rlist;
346 nbp->rcoulomb_sq = ic->rcoulomb * ic->rcoulomb;
347 nbp->ewald_beta = ic->ewaldcoeff_q;
349 nbp->eeltype = pick_ewald_kernel_type(ic->rcoulomb != ic->rvdw,
352 init_ewald_coulomb_force_table(cu_nb->nbparam, cu_nb->dev_info);
355 /*! Initializes the pair list data structure. */
356 static void init_plist(cu_plist_t *pl)
358 /* initialize to NULL pointers to data that is not allocated here and will
359 need reallocation in nbnxn_cuda_init_pairlist */
364 /* size -1 indicates that the respective array hasn't been initialized yet */
371 pl->excl_nalloc = -1;
372 pl->bDoPrune = false;
375 /*! Initializes the timer data structure. */
376 static void init_timers(cu_timers_t *t, bool bUseTwoStreams)
379 int eventflags = ( bUseCudaEventBlockingSync ? cudaEventBlockingSync: cudaEventDefault );
381 stat = cudaEventCreateWithFlags(&(t->start_atdat), eventflags);
382 CU_RET_ERR(stat, "cudaEventCreate on start_atdat failed");
383 stat = cudaEventCreateWithFlags(&(t->stop_atdat), eventflags);
384 CU_RET_ERR(stat, "cudaEventCreate on stop_atdat failed");
386 /* The non-local counters/stream (second in the array) are needed only with DD. */
387 for (int i = 0; i <= (bUseTwoStreams ? 1 : 0); i++)
389 stat = cudaEventCreateWithFlags(&(t->start_nb_k[i]), eventflags);
390 CU_RET_ERR(stat, "cudaEventCreate on start_nb_k failed");
391 stat = cudaEventCreateWithFlags(&(t->stop_nb_k[i]), eventflags);
392 CU_RET_ERR(stat, "cudaEventCreate on stop_nb_k failed");
395 stat = cudaEventCreateWithFlags(&(t->start_pl_h2d[i]), eventflags);
396 CU_RET_ERR(stat, "cudaEventCreate on start_pl_h2d failed");
397 stat = cudaEventCreateWithFlags(&(t->stop_pl_h2d[i]), eventflags);
398 CU_RET_ERR(stat, "cudaEventCreate on stop_pl_h2d failed");
400 stat = cudaEventCreateWithFlags(&(t->start_nb_h2d[i]), eventflags);
401 CU_RET_ERR(stat, "cudaEventCreate on start_nb_h2d failed");
402 stat = cudaEventCreateWithFlags(&(t->stop_nb_h2d[i]), eventflags);
403 CU_RET_ERR(stat, "cudaEventCreate on stop_nb_h2d failed");
405 stat = cudaEventCreateWithFlags(&(t->start_nb_d2h[i]), eventflags);
406 CU_RET_ERR(stat, "cudaEventCreate on start_nb_d2h failed");
407 stat = cudaEventCreateWithFlags(&(t->stop_nb_d2h[i]), eventflags);
408 CU_RET_ERR(stat, "cudaEventCreate on stop_nb_d2h failed");
412 /*! Initializes the timings data structure. */
413 static void init_timings(wallclock_gpu_t *t)
422 for (i = 0; i < 2; i++)
424 for(j = 0; j < 2; j++)
426 t->ktime[i][j].t = 0.0;
427 t->ktime[i][j].c = 0;
432 void nbnxn_cuda_init(FILE *fplog,
433 nbnxn_cuda_ptr_t *p_cu_nb,
434 const gmx_gpu_info_t *gpu_info,
435 const gmx_gpu_opt_t *gpu_opt,
437 gmx_bool bLocalAndNonlocal)
442 bool bStreamSync, bNoStreamSync, bTMPIAtomics, bX86, bOldDriver;
447 if (p_cu_nb == NULL) return;
451 snew(nb->nbparam, 1);
452 snew(nb->plist[eintLocal], 1);
453 if (bLocalAndNonlocal)
455 snew(nb->plist[eintNonlocal], 1);
458 nb->bUseTwoStreams = bLocalAndNonlocal;
461 snew(nb->timings, 1);
464 pmalloc((void**)&nb->nbst.e_lj, sizeof(*nb->nbst.e_lj));
465 pmalloc((void**)&nb->nbst.e_el, sizeof(*nb->nbst.e_el));
466 pmalloc((void**)&nb->nbst.fshift, SHIFTS * sizeof(*nb->nbst.fshift));
468 init_plist(nb->plist[eintLocal]);
470 /* set device info, just point it to the right GPU among the detected ones */
471 nb->dev_info = &gpu_info->cuda_dev[get_gpu_device_id(gpu_info, gpu_opt, my_gpu_index)];
473 /* local/non-local GPU streams */
474 stat = cudaStreamCreate(&nb->stream[eintLocal]);
475 CU_RET_ERR(stat, "cudaStreamCreate on stream[eintLocal] failed");
476 if (nb->bUseTwoStreams)
478 init_plist(nb->plist[eintNonlocal]);
480 /* CUDA stream priority available in the CUDA RT 5.5 API.
481 * Note that the device we're running on does not have to support
482 * priorities, because we are querying the priority range which in this
483 * case will be a single value.
485 #if CUDA_VERSION >= 5500
487 int highest_priority;
488 stat = cudaDeviceGetStreamPriorityRange(NULL, &highest_priority);
489 CU_RET_ERR(stat, "cudaDeviceGetStreamPriorityRange failed");
491 stat = cudaStreamCreateWithPriority(&nb->stream[eintNonlocal],
494 CU_RET_ERR(stat, "cudaStreamCreateWithPriority on stream[eintNonlocal] failed");
497 stat = cudaStreamCreate(&nb->stream[eintNonlocal]);
498 CU_RET_ERR(stat, "cudaStreamCreate on stream[eintNonlocal] failed");
502 /* init events for sychronization (timing disabled for performance reasons!) */
503 stat = cudaEventCreateWithFlags(&nb->nonlocal_done, cudaEventDisableTiming);
504 CU_RET_ERR(stat, "cudaEventCreate on nonlocal_done failed");
505 stat = cudaEventCreateWithFlags(&nb->misc_ops_done, cudaEventDisableTiming);
506 CU_RET_ERR(stat, "cudaEventCreate on misc_ops_one failed");
508 /* On GPUs with ECC enabled, cudaStreamSynchronize shows a large overhead
509 * (which increases with shorter time/step) caused by a known CUDA driver bug.
510 * To work around the issue we'll use an (admittedly fragile) memory polling
511 * waiting to preserve performance. This requires support for atomic
512 * operations and only works on x86/x86_64.
513 * With polling wait event-timing also needs to be disabled.
515 * The overhead is greatly reduced in API v5.0 drivers and the improvement
516 $ is independent of runtime version. Hence, with API v5.0 drivers and later
517 * we won't switch to polling.
519 * NOTE: Unfortunately, this is known to fail when GPUs are shared by (t)MPI,
520 * ranks so we will also disable it in that case.
523 bStreamSync = getenv("GMX_CUDA_STREAMSYNC") != NULL;
524 bNoStreamSync = getenv("GMX_NO_CUDA_STREAMSYNC") != NULL;
529 bTMPIAtomics = false;
532 #ifdef GMX_TARGET_X86
538 if (bStreamSync && bNoStreamSync)
540 gmx_fatal(FARGS, "Conflicting environment variables: both GMX_CUDA_STREAMSYNC and GMX_NO_CUDA_STREAMSYNC defined");
543 stat = cudaDriverGetVersion(&cuda_drv_ver);
544 CU_RET_ERR(stat, "cudaDriverGetVersion failed");
546 bOldDriver = (cuda_drv_ver < 5000);
548 if ((nb->dev_info->prop.ECCEnabled == 1) && bOldDriver)
550 /* Polling wait should be used instead of cudaStreamSynchronize only if:
551 * - ECC is ON & driver is old (checked above),
552 * - we're on x86/x86_64,
553 * - atomics are available, and
554 * - GPUs are not being shared.
556 bool bShouldUsePollSync = (bX86 && bTMPIAtomics &&
557 (gmx_count_gpu_dev_shared(gpu_opt) < 1));
561 nb->bUseStreamSync = true;
563 /* only warn if polling should be used */
564 if (bShouldUsePollSync)
567 "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0, but\n"
568 " cudaStreamSynchronize waiting is forced by the GMX_CUDA_STREAMSYNC env. var.\n");
573 nb->bUseStreamSync = !bShouldUsePollSync;
575 if (bShouldUsePollSync)
578 "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0, known to\n"
579 " cause performance loss. Switching to the alternative polling GPU wait.\n"
580 " If you encounter issues, switch back to standard GPU waiting by setting\n"
581 " the GMX_CUDA_STREAMSYNC environment variable.\n");
585 /* Tell the user that the ECC+old driver combination can be bad */
587 "NOTE: Using a GPU with ECC enabled and CUDA driver API version <5.0.\n"
588 " A known bug in this driver version can cause performance loss.\n"
589 " However, the polling wait workaround can not be used because\n%s\n"
590 " Consider updating the driver or turning ECC off.",
591 (bX86 && bTMPIAtomics) ?
592 " GPU(s) are being oversubscribed." :
593 " atomic operations are not supported by the platform/CPU+compiler.");
594 md_print_warn(fplog, sbuf);
602 nb->bUseStreamSync = false;
605 "NOTE: Polling wait for GPU synchronization requested by GMX_NO_CUDA_STREAMSYNC\n");
609 /* no/off ECC, cudaStreamSynchronize not turned off by env. var. */
610 nb->bUseStreamSync = true;
614 /* CUDA timing disabled as event timers don't work:
615 - with multiple streams = domain-decomposition;
616 - with the polling waiting hack (without cudaStreamSynchronize);
617 - when turned off by GMX_DISABLE_CUDA_TIMING.
619 nb->bDoTime = (!nb->bUseTwoStreams && nb->bUseStreamSync &&
620 (getenv("GMX_DISABLE_CUDA_TIMING") == NULL));
624 init_timers(nb->timers, nb->bUseTwoStreams);
625 init_timings(nb->timings);
628 /* set the kernel type for the current GPU */
629 /* pick L1 cache configuration */
630 nbnxn_cuda_set_cacheconfig(nb->dev_info);
636 fprintf(debug, "Initialized CUDA data structures.\n");
640 void nbnxn_cuda_init_const(nbnxn_cuda_ptr_t cu_nb,
641 const interaction_const_t *ic,
642 const nonbonded_verlet_group_t *nbv_group)
644 init_atomdata_first(cu_nb->atdat, nbv_group[0].nbat->ntype);
645 init_nbparam(cu_nb->nbparam, ic, nbv_group[0].nbat, cu_nb->dev_info);
647 /* clear energy and shift force outputs */
648 nbnxn_cuda_clear_e_fshift(cu_nb);
651 void nbnxn_cuda_init_pairlist(nbnxn_cuda_ptr_t cu_nb,
652 const nbnxn_pairlist_t *h_plist,
657 bool bDoTime = cu_nb->bDoTime;
658 cudaStream_t stream = cu_nb->stream[iloc];
659 cu_plist_t *d_plist = cu_nb->plist[iloc];
661 if (d_plist->na_c < 0)
663 d_plist->na_c = h_plist->na_ci;
667 if (d_plist->na_c != h_plist->na_ci)
669 sprintf(sbuf, "In cu_init_plist: the #atoms per cell has changed (from %d to %d)",
670 d_plist->na_c, h_plist->na_ci);
677 stat = cudaEventRecord(cu_nb->timers->start_pl_h2d[iloc], stream);
678 CU_RET_ERR(stat, "cudaEventRecord failed");
681 cu_realloc_buffered((void **)&d_plist->sci, h_plist->sci, sizeof(*d_plist->sci),
682 &d_plist->nsci, &d_plist->sci_nalloc,
686 cu_realloc_buffered((void **)&d_plist->cj4, h_plist->cj4, sizeof(*d_plist->cj4),
687 &d_plist->ncj4, &d_plist->cj4_nalloc,
691 cu_realloc_buffered((void **)&d_plist->excl, h_plist->excl, sizeof(*d_plist->excl),
692 &d_plist->nexcl, &d_plist->excl_nalloc,
698 stat = cudaEventRecord(cu_nb->timers->stop_pl_h2d[iloc], stream);
699 CU_RET_ERR(stat, "cudaEventRecord failed");
702 /* need to prune the pair list during the next step */
703 d_plist->bDoPrune = true;
706 void nbnxn_cuda_upload_shiftvec(nbnxn_cuda_ptr_t cu_nb,
707 const nbnxn_atomdata_t *nbatom)
709 cu_atomdata_t *adat = cu_nb->atdat;
710 cudaStream_t ls = cu_nb->stream[eintLocal];
712 /* only if we have a dynamic box */
713 if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
715 cu_copy_H2D_async(adat->shift_vec, nbatom->shift_vec,
716 SHIFTS * sizeof(*adat->shift_vec), ls);
717 adat->bShiftVecUploaded = true;
721 /*! Clears the first natoms_clear elements of the GPU nonbonded force output array. */
722 static void nbnxn_cuda_clear_f(nbnxn_cuda_ptr_t cu_nb, int natoms_clear)
725 cu_atomdata_t *adat = cu_nb->atdat;
726 cudaStream_t ls = cu_nb->stream[eintLocal];
728 stat = cudaMemsetAsync(adat->f, 0, natoms_clear * sizeof(*adat->f), ls);
729 CU_RET_ERR(stat, "cudaMemsetAsync on f falied");
732 /*! Clears nonbonded shift force output array and energy outputs on the GPU. */
733 static void nbnxn_cuda_clear_e_fshift(nbnxn_cuda_ptr_t cu_nb)
736 cu_atomdata_t *adat = cu_nb->atdat;
737 cudaStream_t ls = cu_nb->stream[eintLocal];
739 stat = cudaMemsetAsync(adat->fshift, 0, SHIFTS * sizeof(*adat->fshift), ls);
740 CU_RET_ERR(stat, "cudaMemsetAsync on fshift falied");
741 stat = cudaMemsetAsync(adat->e_lj, 0, sizeof(*adat->e_lj), ls);
742 CU_RET_ERR(stat, "cudaMemsetAsync on e_lj falied");
743 stat = cudaMemsetAsync(adat->e_el, 0, sizeof(*adat->e_el), ls);
744 CU_RET_ERR(stat, "cudaMemsetAsync on e_el falied");
747 void nbnxn_cuda_clear_outputs(nbnxn_cuda_ptr_t cu_nb, int flags)
749 nbnxn_cuda_clear_f(cu_nb, cu_nb->atdat->natoms);
750 /* clear shift force array and energies if the outputs were
751 used in the current step */
752 if (flags & GMX_FORCE_VIRIAL)
754 nbnxn_cuda_clear_e_fshift(cu_nb);
758 void nbnxn_cuda_init_atomdata(nbnxn_cuda_ptr_t cu_nb,
759 const nbnxn_atomdata_t *nbat)
764 bool bDoTime = cu_nb->bDoTime;
765 cu_timers_t *timers = cu_nb->timers;
766 cu_atomdata_t *d_atdat = cu_nb->atdat;
767 cudaStream_t ls = cu_nb->stream[eintLocal];
769 natoms = nbat->natoms;
774 /* time async copy */
775 stat = cudaEventRecord(timers->start_atdat, ls);
776 CU_RET_ERR(stat, "cudaEventRecord failed");
779 /* need to reallocate if we have to copy more atoms than the amount of space
780 available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
781 if (natoms > d_atdat->nalloc)
783 nalloc = over_alloc_small(natoms);
785 /* free up first if the arrays have already been initialized */
786 if (d_atdat->nalloc != -1)
788 cu_free_buffered(d_atdat->f, &d_atdat->natoms, &d_atdat->nalloc);
789 cu_free_buffered(d_atdat->xq);
790 cu_free_buffered(d_atdat->atom_types);
793 stat = cudaMalloc((void **)&d_atdat->f, nalloc*sizeof(*d_atdat->f));
794 CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->f");
795 stat = cudaMalloc((void **)&d_atdat->xq, nalloc*sizeof(*d_atdat->xq));
796 CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->xq");
798 stat = cudaMalloc((void **)&d_atdat->atom_types, nalloc*sizeof(*d_atdat->atom_types));
799 CU_RET_ERR(stat, "cudaMalloc failed on d_atdat->atom_types");
801 d_atdat->nalloc = nalloc;
805 d_atdat->natoms = natoms;
806 d_atdat->natoms_local = nbat->natoms_local;
808 /* need to clear GPU f output if realloc happened */
811 nbnxn_cuda_clear_f(cu_nb, nalloc);
814 cu_copy_H2D_async(d_atdat->atom_types, nbat->type,
815 natoms*sizeof(*d_atdat->atom_types), ls);
819 stat = cudaEventRecord(timers->stop_atdat, ls);
820 CU_RET_ERR(stat, "cudaEventRecord failed");
824 void nbnxn_cuda_free(FILE *fplog, nbnxn_cuda_ptr_t cu_nb)
827 cu_atomdata_t *atdat;
828 cu_nbparam_t *nbparam;
829 cu_plist_t *plist, *plist_nl;
832 if (cu_nb == NULL) return;
834 atdat = cu_nb->atdat;
835 nbparam = cu_nb->nbparam;
836 plist = cu_nb->plist[eintLocal];
837 plist_nl = cu_nb->plist[eintNonlocal];
838 timers = cu_nb->timers;
840 if (nbparam->eeltype == eelCuEWALD_TAB || nbparam->eeltype == eelCuEWALD_TAB_TWIN)
843 #ifdef TEXOBJ_SUPPORTED
844 /* Only device CC >= 3.0 (Kepler and later) support texture objects */
845 if (cu_nb->dev_info->prop.major >= 3)
847 stat = cudaDestroyTextureObject(nbparam->coulomb_tab_texobj);
848 CU_RET_ERR(stat, "cudaDestroyTextureObject on coulomb_tab_texobj failed");
853 stat = cudaUnbindTexture(nbnxn_cuda_get_coulomb_tab_texref());
854 CU_RET_ERR(stat, "cudaUnbindTexture on coulomb_tab_texref failed");
856 cu_free_buffered(nbparam->coulomb_tab, &nbparam->coulomb_tab_size);
859 stat = cudaEventDestroy(cu_nb->nonlocal_done);
860 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->nonlocal_done");
861 stat = cudaEventDestroy(cu_nb->misc_ops_done);
862 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->misc_ops_done");
866 stat = cudaEventDestroy(timers->start_atdat);
867 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_atdat");
868 stat = cudaEventDestroy(timers->stop_atdat);
869 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_atdat");
871 /* The non-local counters/stream (second in the array) are needed only with DD. */
872 for (int i = 0; i <= (cu_nb->bUseTwoStreams ? 1 : 0); i++)
874 stat = cudaEventDestroy(timers->start_nb_k[i]);
875 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_k");
876 stat = cudaEventDestroy(timers->stop_nb_k[i]);
877 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_k");
879 stat = cudaEventDestroy(timers->start_pl_h2d[i]);
880 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_pl_h2d");
881 stat = cudaEventDestroy(timers->stop_pl_h2d[i]);
882 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_pl_h2d");
884 stat = cudaStreamDestroy(cu_nb->stream[i]);
885 CU_RET_ERR(stat, "cudaStreamDestroy failed on stream");
887 stat = cudaEventDestroy(timers->start_nb_h2d[i]);
888 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_h2d");
889 stat = cudaEventDestroy(timers->stop_nb_h2d[i]);
890 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_h2d");
892 stat = cudaEventDestroy(timers->start_nb_d2h[i]);
893 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->start_nb_d2h");
894 stat = cudaEventDestroy(timers->stop_nb_d2h[i]);
895 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->stop_nb_d2h");
899 #ifdef TEXOBJ_SUPPORTED
900 /* Only device CC >= 3.0 (Kepler and later) support texture objects */
901 if (cu_nb->dev_info->prop.major >= 3)
903 stat = cudaDestroyTextureObject(nbparam->nbfp_texobj);
904 CU_RET_ERR(stat, "cudaDestroyTextureObject on nbfp_texobj failed");
909 stat = cudaUnbindTexture(nbnxn_cuda_get_nbfp_texref());
910 CU_RET_ERR(stat, "cudaUnbindTexture on nbfp_texref failed");
912 cu_free_buffered(nbparam->nbfp);
914 stat = cudaFree(atdat->shift_vec);
915 CU_RET_ERR(stat, "cudaFree failed on atdat->shift_vec");
916 stat = cudaFree(atdat->fshift);
917 CU_RET_ERR(stat, "cudaFree failed on atdat->fshift");
919 stat = cudaFree(atdat->e_lj);
920 CU_RET_ERR(stat, "cudaFree failed on atdat->e_lj");
921 stat = cudaFree(atdat->e_el);
922 CU_RET_ERR(stat, "cudaFree failed on atdat->e_el");
924 cu_free_buffered(atdat->f, &atdat->natoms, &atdat->nalloc);
925 cu_free_buffered(atdat->xq);
926 cu_free_buffered(atdat->atom_types, &atdat->ntypes);
928 cu_free_buffered(plist->sci, &plist->nsci, &plist->sci_nalloc);
929 cu_free_buffered(plist->cj4, &plist->ncj4, &plist->cj4_nalloc);
930 cu_free_buffered(plist->excl, &plist->nexcl, &plist->excl_nalloc);
931 if (cu_nb->bUseTwoStreams)
933 cu_free_buffered(plist_nl->sci, &plist_nl->nsci, &plist_nl->sci_nalloc);
934 cu_free_buffered(plist_nl->cj4, &plist_nl->ncj4, &plist_nl->cj4_nalloc);
935 cu_free_buffered(plist_nl->excl, &plist_nl->nexcl, &plist->excl_nalloc);
941 if (cu_nb->bUseTwoStreams)
946 sfree(cu_nb->timings);
951 fprintf(debug, "Cleaned up CUDA data structures.\n");
955 void cu_synchstream_atdat(nbnxn_cuda_ptr_t cu_nb, int iloc)
958 cudaStream_t stream = cu_nb->stream[iloc];
960 stat = cudaStreamWaitEvent(stream, cu_nb->timers->stop_atdat, 0);
961 CU_RET_ERR(stat, "cudaStreamWaitEvent failed");
964 wallclock_gpu_t * nbnxn_cuda_get_timings(nbnxn_cuda_ptr_t cu_nb)
966 return (cu_nb != NULL && cu_nb->bDoTime) ? cu_nb->timings : NULL;
969 void nbnxn_cuda_reset_timings(nbnxn_cuda_ptr_t cu_nb)
973 init_timings(cu_nb->timings);
977 int nbnxn_cuda_min_ci_balanced(nbnxn_cuda_ptr_t cu_nb)
979 return cu_nb != NULL ?
980 gpu_min_ci_balanced_factor*cu_nb->dev_info->prop.multiProcessorCount : 0;
984 gmx_bool nbnxn_cuda_is_kernel_ewald_analytical(const nbnxn_cuda_ptr_t cu_nb)
986 return ((cu_nb->nbparam->eeltype == eelCuEWALD_ANA) ||
987 (cu_nb->nbparam->eeltype == eelCuEWALD_ANA_TWIN));