4f1e9fc65c75e737684dc293bdf7e3bc261a761c
[alexxy/gromacs.git] / src / gromacs / nbnxm / opencl / nbnxm_ocl_data_mgmt.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  *  \brief Define OpenCL implementation of nbnxm_gpu_data_mgmt.h
38  *
39  *  \author Anca Hamuraru <anca@streamcomputing.eu>
40  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
41  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
42  *  \author Szilárd Páll <pall.szilard@gmail.com>
43  *  \ingroup module_nbnxm
44  */
45 #include "gmxpre.h"
46
47 #include <assert.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52
53 #include <cmath>
54
55 #include "gromacs/gpu_utils/device_stream_manager.h"
56 #include "gromacs/gpu_utils/gpu_utils.h"
57 #include "gromacs/gpu_utils/oclutils.h"
58 #include "gromacs/hardware/gpu_hw_info.h"
59 #include "gromacs/math/vectypes.h"
60 #include "gromacs/mdlib/force_flags.h"
61 #include "gromacs/mdtypes/interaction_const.h"
62 #include "gromacs/mdtypes/md_enums.h"
63 #include "gromacs/nbnxm/atomdata.h"
64 #include "gromacs/nbnxm/gpu_data_mgmt.h"
65 #include "gromacs/nbnxm/gpu_jit_support.h"
66 #include "gromacs/nbnxm/nbnxm.h"
67 #include "gromacs/nbnxm/nbnxm_gpu.h"
68 #include "gromacs/nbnxm/pairlistsets.h"
69 #include "gromacs/pbcutil/ishift.h"
70 #include "gromacs/timing/gpu_timing.h"
71 #include "gromacs/utility/cstringutil.h"
72 #include "gromacs/utility/fatalerror.h"
73 #include "gromacs/utility/gmxassert.h"
74 #include "gromacs/utility/real.h"
75 #include "gromacs/utility/smalloc.h"
76
77 #include "nbnxm_ocl_internal.h"
78 #include "nbnxm_ocl_types.h"
79
80 namespace Nbnxm
81 {
82
83 /*! \brief Copies of values from cl_driver_diagnostics_intel.h,
84  * which isn't guaranteed to be available. */
85 /**@{*/
86 #define CL_CONTEXT_SHOW_DIAGNOSTICS_INTEL 0x4106
87 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_GOOD_INTEL 0x1
88 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_BAD_INTEL 0x2
89 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_NEUTRAL_INTEL 0x4
90 /**@}*/
91
92 /*! \brief This parameter should be determined heuristically from the
93  * kernel execution times
94  *
95  * This value is best for small systems on a single AMD Radeon R9 290X
96  * (and about 5% faster than 40, which is the default for CUDA
97  * devices). Larger simulation systems were quite insensitive to the
98  * value of this parameter.
99  */
100 static unsigned int gpu_min_ci_balanced_factor = 50;
101
102
103 /*! \brief Returns true if LJ combination rules are used in the non-bonded kernels.
104  *
105  * Full doc in nbnxn_ocl_internal.h */
106 bool useLjCombRule(int vdwType)
107 {
108     return (vdwType == evdwOclCUTCOMBGEOM || vdwType == evdwOclCUTCOMBLB);
109 }
110
111 /*! \brief Tabulates the Ewald Coulomb force and initializes the size/scale
112  * and the table GPU array.
113  *
114  * If called with an already allocated table, it just re-uploads the
115  * table.
116  */
117 static void init_ewald_coulomb_force_table(const EwaldCorrectionTables& tables,
118                                            cl_nbparam_t*                nbp,
119                                            const DeviceContext&         deviceContext)
120 {
121     if (nbp->coulomb_tab_climg2d != nullptr)
122     {
123         freeDeviceBuffer(&(nbp->coulomb_tab_climg2d));
124     }
125
126     DeviceBuffer<real> coulomb_tab;
127
128     initParamLookupTable(&coulomb_tab, nullptr, tables.tableF.data(), tables.tableF.size(), deviceContext);
129
130     nbp->coulomb_tab_climg2d = coulomb_tab;
131     nbp->coulomb_tab_scale   = tables.scale;
132 }
133
134
135 /*! \brief Initializes the atomdata structure first time, it only gets filled at
136     pair-search.
137  */
138 static void init_atomdata_first(cl_atomdata_t* ad, int ntypes, const DeviceContext& deviceContext)
139 {
140     cl_int cl_error;
141
142     ad->ntypes = ntypes;
143
144     ad->shift_vec = clCreateBuffer(deviceContext.context(), CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
145                                    SHIFTS * sizeof(nbnxn_atomdata_t::shift_vec[0]), nullptr, &cl_error);
146     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
147                        ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
148     ad->bShiftVecUploaded = CL_FALSE;
149
150     ad->fshift = clCreateBuffer(deviceContext.context(), CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
151                                 SHIFTS * sizeof(nb_staging_t::fshift[0]), nullptr, &cl_error);
152     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
153                        ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
154
155     ad->e_lj = clCreateBuffer(deviceContext.context(), CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
156                               sizeof(float), nullptr, &cl_error);
157     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
158                        ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
159
160     ad->e_el = clCreateBuffer(deviceContext.context(), CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
161                               sizeof(float), nullptr, &cl_error);
162     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
163                        ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
164
165     /* initialize to nullptr pointers to data that is not allocated here and will
166        need reallocation in nbnxn_gpu_init_atomdata */
167     ad->xq = nullptr;
168     ad->f  = nullptr;
169
170     /* size -1 indicates that the respective array hasn't been initialized yet */
171     ad->natoms = -1;
172     ad->nalloc = -1;
173 }
174
175 /*! \brief Copies all parameters related to the cut-off from ic to nbp
176  */
177 static void set_cutoff_parameters(cl_nbparam_t* nbp, const interaction_const_t* ic, const PairlistParams& listParams)
178 {
179     nbp->ewald_beta        = ic->ewaldcoeff_q;
180     nbp->sh_ewald          = ic->sh_ewald;
181     nbp->epsfac            = ic->epsfac;
182     nbp->two_k_rf          = 2.0 * ic->k_rf;
183     nbp->c_rf              = ic->c_rf;
184     nbp->rvdw_sq           = ic->rvdw * ic->rvdw;
185     nbp->rcoulomb_sq       = ic->rcoulomb * ic->rcoulomb;
186     nbp->rlistOuter_sq     = listParams.rlistOuter * listParams.rlistOuter;
187     nbp->rlistInner_sq     = listParams.rlistInner * listParams.rlistInner;
188     nbp->useDynamicPruning = listParams.useDynamicPruning;
189
190     nbp->sh_lj_ewald   = ic->sh_lj_ewald;
191     nbp->ewaldcoeff_lj = ic->ewaldcoeff_lj;
192
193     nbp->rvdw_switch      = ic->rvdw_switch;
194     nbp->dispersion_shift = ic->dispersion_shift;
195     nbp->repulsion_shift  = ic->repulsion_shift;
196     nbp->vdw_switch       = ic->vdw_switch;
197 }
198
199 /*! \brief Returns the kinds of electrostatics and Vdw OpenCL
200  *  kernels that will be used.
201  *
202  * Respectively, these values are from enum eelOcl and enum
203  * evdwOcl. */
204 static void map_interaction_types_to_gpu_kernel_flavors(const interaction_const_t* ic,
205                                                         int                        combRule,
206                                                         int*                       gpu_eeltype,
207                                                         int*                       gpu_vdwtype)
208 {
209     if (ic->vdwtype == evdwCUT)
210     {
211         switch (ic->vdw_modifier)
212         {
213             case eintmodNONE:
214             case eintmodPOTSHIFT:
215                 switch (combRule)
216                 {
217                     case ljcrNONE: *gpu_vdwtype = evdwOclCUT; break;
218                     case ljcrGEOM: *gpu_vdwtype = evdwOclCUTCOMBGEOM; break;
219                     case ljcrLB: *gpu_vdwtype = evdwOclCUTCOMBLB; break;
220                     default:
221                         gmx_incons(
222                                 "The requested LJ combination rule is not implemented in the "
223                                 "OpenCL GPU accelerated kernels!");
224                 }
225                 break;
226             case eintmodFORCESWITCH: *gpu_vdwtype = evdwOclFSWITCH; break;
227             case eintmodPOTSWITCH: *gpu_vdwtype = evdwOclPSWITCH; break;
228             default:
229                 gmx_incons(
230                         "The requested VdW interaction modifier is not implemented in the GPU "
231                         "accelerated kernels!");
232         }
233     }
234     else if (ic->vdwtype == evdwPME)
235     {
236         if (ic->ljpme_comb_rule == ljcrGEOM)
237         {
238             *gpu_vdwtype = evdwOclEWALDGEOM;
239         }
240         else
241         {
242             *gpu_vdwtype = evdwOclEWALDLB;
243         }
244     }
245     else
246     {
247         gmx_incons("The requested VdW type is not implemented in the GPU accelerated kernels!");
248     }
249
250     if (ic->eeltype == eelCUT)
251     {
252         *gpu_eeltype = eelOclCUT;
253     }
254     else if (EEL_RF(ic->eeltype))
255     {
256         *gpu_eeltype = eelOclRF;
257     }
258     else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
259     {
260         *gpu_eeltype = nbnxn_gpu_pick_ewald_kernel_type(*ic);
261     }
262     else
263     {
264         /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
265         gmx_incons(
266                 "The requested electrostatics type is not implemented in the GPU accelerated "
267                 "kernels!");
268     }
269 }
270
271 /*! \brief Initializes the nonbonded parameter data structure.
272  */
273 static void init_nbparam(cl_nbparam_t*                   nbp,
274                          const interaction_const_t*      ic,
275                          const PairlistParams&           listParams,
276                          const nbnxn_atomdata_t::Params& nbatParams,
277                          const DeviceContext&            deviceContext)
278 {
279     cl_int cl_error;
280
281     set_cutoff_parameters(nbp, ic, listParams);
282
283     map_interaction_types_to_gpu_kernel_flavors(ic, nbatParams.comb_rule, &(nbp->eeltype), &(nbp->vdwtype));
284
285     if (ic->vdwtype == evdwPME)
286     {
287         if (ic->ljpme_comb_rule == ljcrGEOM)
288         {
289             GMX_ASSERT(nbatParams.comb_rule == ljcrGEOM, "Combination rule mismatch!");
290         }
291         else
292         {
293             GMX_ASSERT(nbatParams.comb_rule == ljcrLB, "Combination rule mismatch!");
294         }
295     }
296     /* generate table for PME */
297     nbp->coulomb_tab_climg2d = nullptr;
298     if (nbp->eeltype == eelOclEWALD_TAB || nbp->eeltype == eelOclEWALD_TAB_TWIN)
299     {
300         GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
301         init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
302     }
303     else
304     {
305         nbp->coulomb_tab_climg2d = clCreateBuffer(deviceContext.context(), CL_MEM_READ_ONLY,
306                                                   sizeof(cl_float), nullptr, &cl_error);
307         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
308                            ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
309     }
310
311     const int nnbfp      = 2 * nbatParams.numTypes * nbatParams.numTypes;
312     const int nnbfp_comb = 2 * nbatParams.numTypes;
313
314     {
315         /* set up LJ parameter lookup table */
316         DeviceBuffer<real> nbfp;
317         initParamLookupTable(&nbfp, nullptr, nbatParams.nbfp.data(), nnbfp, deviceContext);
318         nbp->nbfp_climg2d = nbfp;
319
320         if (ic->vdwtype == evdwPME)
321         {
322             DeviceBuffer<float> nbfp_comb;
323             initParamLookupTable(&nbfp_comb, nullptr, nbatParams.nbfp_comb.data(), nnbfp_comb, deviceContext);
324             nbp->nbfp_comb_climg2d = nbfp_comb;
325         }
326     }
327 }
328
329 //! This function is documented in the header file
330 void gpu_pme_loadbal_update_param(const nonbonded_verlet_t* nbv, const interaction_const_t* ic)
331 {
332     if (!nbv || !nbv->useGpu())
333     {
334         return;
335     }
336     NbnxmGpu*     nb  = nbv->gpu_nbv;
337     cl_nbparam_t* nbp = nb->nbparam;
338
339     set_cutoff_parameters(nbp, ic, nbv->pairlistSets().params());
340
341     nbp->eeltype = nbnxn_gpu_pick_ewald_kernel_type(*ic);
342
343     GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
344     init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, *nb->deviceContext_);
345 }
346
347 /*! \brief Initializes the pair list data structure.
348  */
349 static void init_plist(cl_plist_t* pl)
350 {
351     /* initialize to nullptr pointers to data that is not allocated here and will
352        need reallocation in nbnxn_gpu_init_pairlist */
353     pl->sci   = nullptr;
354     pl->cj4   = nullptr;
355     pl->imask = nullptr;
356     pl->excl  = nullptr;
357
358     /* size -1 indicates that the respective array hasn't been initialized yet */
359     pl->na_c          = -1;
360     pl->nsci          = -1;
361     pl->sci_nalloc    = -1;
362     pl->ncj4          = -1;
363     pl->cj4_nalloc    = -1;
364     pl->nimask        = -1;
365     pl->imask_nalloc  = -1;
366     pl->nexcl         = -1;
367     pl->excl_nalloc   = -1;
368     pl->haveFreshList = false;
369 }
370
371 /*! \brief Initializes the timings data structure.
372  */
373 static void init_timings(gmx_wallclock_gpu_nbnxn_t* t)
374 {
375     int i, j;
376
377     t->nb_h2d_t = 0.0;
378     t->nb_d2h_t = 0.0;
379     t->nb_c     = 0;
380     t->pl_h2d_t = 0.0;
381     t->pl_h2d_c = 0;
382     for (i = 0; i < 2; i++)
383     {
384         for (j = 0; j < 2; j++)
385         {
386             t->ktime[i][j].t = 0.0;
387             t->ktime[i][j].c = 0;
388         }
389     }
390
391     t->pruneTime.c        = 0;
392     t->pruneTime.t        = 0.0;
393     t->dynamicPruneTime.c = 0;
394     t->dynamicPruneTime.t = 0.0;
395 }
396
397 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
398 static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name)
399 {
400     cl_kernel kernel;
401     cl_int    cl_error;
402
403     kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
404     if (CL_SUCCESS != cl_error)
405     {
406         gmx_fatal(FARGS, "Failed to create kernel '%s' for GPU #%s: OpenCL error %d", kernel_name,
407                   nb->deviceContext_->deviceInfo().device_name, cl_error);
408     }
409
410     return kernel;
411 }
412
413 /*! \brief Clears nonbonded shift force output array and energy outputs on the GPU.
414  */
415 static void nbnxn_ocl_clear_e_fshift(NbnxmGpu* nb)
416 {
417
418     cl_int           cl_error;
419     cl_atomdata_t*   adat = nb->atdat;
420     cl_command_queue ls   = nb->deviceStreams[InteractionLocality::Local]->stream();
421
422     size_t local_work_size[3]  = { 1, 1, 1 };
423     size_t global_work_size[3] = { 1, 1, 1 };
424
425     cl_int shifts = SHIFTS * 3;
426
427     cl_int arg_no;
428
429     cl_kernel zero_e_fshift = nb->kernel_zero_e_fshift;
430
431     local_work_size[0] = 64;
432     // Round the total number of threads up from the array size
433     global_work_size[0] = ((shifts + local_work_size[0] - 1) / local_work_size[0]) * local_work_size[0];
434
435     arg_no   = 0;
436     cl_error = clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->fshift));
437     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_lj));
438     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_el));
439     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_uint), &shifts);
440     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
441
442     cl_error = clEnqueueNDRangeKernel(ls, zero_e_fshift, 3, nullptr, global_work_size,
443                                       local_work_size, 0, nullptr, nullptr);
444     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
445 }
446
447 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
448 static void nbnxn_gpu_init_kernels(NbnxmGpu* nb)
449 {
450     /* Init to 0 main kernel arrays */
451     /* They will be later on initialized in select_nbnxn_kernel */
452     // TODO: consider always creating all variants of the kernels here so that there is no
453     // need for late call to clCreateKernel -- if that gives any advantage?
454     memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
455     memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
456     memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
457     memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
458
459     /* Init pruning kernels
460      *
461      * TODO: we could avoid creating kernels if dynamic pruning is turned off,
462      * but ATM that depends on force flags not passed into the initialization.
463      */
464     nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
465     nb->kernel_pruneonly[epruneRolling] =
466             nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
467
468     /* Init auxiliary kernels */
469     nb->kernel_zero_e_fshift = nbnxn_gpu_create_kernel(nb, "zero_e_fshift");
470 }
471
472 /*! \brief Initializes simulation constant data.
473  *
474  *  Initializes members of the atomdata and nbparam structs and
475  *  clears e/fshift output buffers.
476  */
477 static void nbnxn_ocl_init_const(cl_atomdata_t*                  atomData,
478                                  cl_nbparam_t*                   nbParams,
479                                  const interaction_const_t*      ic,
480                                  const PairlistParams&           listParams,
481                                  const nbnxn_atomdata_t::Params& nbatParams,
482                                  const DeviceContext&            deviceContext)
483 {
484     init_atomdata_first(atomData, nbatParams.numTypes, deviceContext);
485     init_nbparam(nbParams, ic, listParams, nbatParams, deviceContext);
486 }
487
488
489 //! This function is documented in the header file
490 NbnxmGpu* gpu_init(const gmx::DeviceStreamManager& deviceStreamManager,
491                    const interaction_const_t*      ic,
492                    const PairlistParams&           listParams,
493                    const nbnxn_atomdata_t*         nbat,
494                    const bool                      bLocalAndNonlocal)
495 {
496     GMX_ASSERT(ic, "Need a valid interaction constants object");
497
498     auto nb            = new NbnxmGpu();
499     nb->deviceContext_ = &deviceStreamManager.context();
500     snew(nb->atdat, 1);
501     snew(nb->nbparam, 1);
502     snew(nb->plist[InteractionLocality::Local], 1);
503     if (bLocalAndNonlocal)
504     {
505         snew(nb->plist[InteractionLocality::NonLocal], 1);
506     }
507
508     nb->bUseTwoStreams = bLocalAndNonlocal;
509
510     nb->timers = new cl_timers_t();
511     snew(nb->timings, 1);
512
513     /* set device info, just point it to the right GPU among the detected ones */
514     nb->dev_rundata = new gmx_device_runtime_data_t();
515
516     /* init nbst */
517     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_lj), sizeof(*nb->nbst.e_lj));
518     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_el), sizeof(*nb->nbst.e_el));
519     pmalloc(reinterpret_cast<void**>(&nb->nbst.fshift), SHIFTS * sizeof(*nb->nbst.fshift));
520
521     init_plist(nb->plist[InteractionLocality::Local]);
522
523     /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
524     nb->bDoTime = (getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
525
526     /* local/non-local GPU streams */
527     GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedLocal),
528                        "Local non-bonded stream should be initialized to use GPU for non-bonded.");
529     nb->deviceStreams[InteractionLocality::Local] =
530             &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal);
531
532     if (nb->bUseTwoStreams)
533     {
534         init_plist(nb->plist[InteractionLocality::NonLocal]);
535
536         GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedNonLocal),
537                            "Non-local non-bonded stream should be initialized to use GPU for "
538                            "non-bonded with domain decomposition.");
539         nb->deviceStreams[InteractionLocality::NonLocal] =
540                 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal);
541     }
542
543     if (nb->bDoTime)
544     {
545         init_timings(nb->timings);
546     }
547
548     nbnxn_ocl_init_const(nb->atdat, nb->nbparam, ic, listParams, nbat->params(), *nb->deviceContext_);
549
550     /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
551      * TODO: decide about NVIDIA
552      */
553     nb->bPrefetchLjParam = (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr)
554                            && ((nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Amd)
555                                || (nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Intel)
556                                || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
557
558     /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
559      * but sadly this is not supported in OpenCL (yet?). Consider adding it if
560      * it becomes supported.
561      */
562     nbnxn_gpu_compile_kernels(nb);
563     nbnxn_gpu_init_kernels(nb);
564
565     /* clear energy and shift force outputs */
566     nbnxn_ocl_clear_e_fshift(nb);
567
568     if (debug)
569     {
570         fprintf(debug, "Initialized OpenCL data structures.\n");
571     }
572
573     return nb;
574 }
575
576 /*! \brief Clears the first natoms_clear elements of the GPU nonbonded force output array.
577  */
578 static void nbnxn_ocl_clear_f(NbnxmGpu* nb, int natoms_clear)
579 {
580     if (natoms_clear == 0)
581     {
582         return;
583     }
584
585     cl_int gmx_used_in_debug cl_error;
586
587     cl_atomdata_t*   atomData = nb->atdat;
588     cl_command_queue ls       = nb->deviceStreams[InteractionLocality::Local]->stream();
589     cl_float         value    = 0.0F;
590
591     cl_error = clEnqueueFillBuffer(ls, atomData->f, &value, sizeof(cl_float), 0,
592                                    natoms_clear * sizeof(rvec), 0, nullptr, nullptr);
593     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
594                        ("clEnqueueFillBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
595 }
596
597 //! This function is documented in the header file
598 void gpu_clear_outputs(NbnxmGpu* nb, bool computeVirial)
599 {
600     nbnxn_ocl_clear_f(nb, nb->atdat->natoms);
601     /* clear shift force array and energies if the outputs were
602        used in the current step */
603     if (computeVirial)
604     {
605         nbnxn_ocl_clear_e_fshift(nb);
606     }
607
608     /* kick off buffer clearing kernel to ensure concurrency with constraints/update */
609     cl_int gmx_unused cl_error;
610     cl_error = clFlush(nb->deviceStreams[InteractionLocality::Local]->stream());
611     GMX_ASSERT(cl_error == CL_SUCCESS, ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
612 }
613
614 //! This function is documented in the header file
615 void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const InteractionLocality iloc)
616 {
617     char sbuf[STRLEN];
618     // Timing accumulation should happen only if there was work to do
619     // because getLastRangeTime() gets skipped with empty lists later
620     // which leads to the counter not being reset.
621     bool                bDoTime      = (nb->bDoTime && !h_plist->sci.empty());
622     const DeviceStream& deviceStream = *nb->deviceStreams[iloc];
623     cl_plist_t*         d_plist      = nb->plist[iloc];
624
625     if (d_plist->na_c < 0)
626     {
627         d_plist->na_c = h_plist->na_ci;
628     }
629     else
630     {
631         if (d_plist->na_c != h_plist->na_ci)
632         {
633             sprintf(sbuf, "In cu_init_plist: the #atoms per cell has changed (from %d to %d)",
634                     d_plist->na_c, h_plist->na_ci);
635             gmx_incons(sbuf);
636         }
637     }
638
639     gpu_timers_t::Interaction& iTimers = nb->timers->interaction[iloc];
640
641     if (bDoTime)
642     {
643         iTimers.pl_h2d.openTimingRegion(deviceStream);
644         iTimers.didPairlistH2D = true;
645     }
646
647     // TODO most of this function is same in CUDA and OpenCL, move into the header
648     const DeviceContext& deviceContext = *nb->deviceContext_;
649
650     reallocateDeviceBuffer(&d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc,
651                            deviceContext);
652     copyToDeviceBuffer(&d_plist->sci, h_plist->sci.data(), 0, h_plist->sci.size(), deviceStream,
653                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
654
655     reallocateDeviceBuffer(&d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc,
656                            deviceContext);
657     copyToDeviceBuffer(&d_plist->cj4, h_plist->cj4.data(), 0, h_plist->cj4.size(), deviceStream,
658                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
659
660     reallocateDeviceBuffer(&d_plist->imask, h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit,
661                            &d_plist->nimask, &d_plist->imask_nalloc, deviceContext);
662
663     reallocateDeviceBuffer(&d_plist->excl, h_plist->excl.size(), &d_plist->nexcl,
664                            &d_plist->excl_nalloc, deviceContext);
665     copyToDeviceBuffer(&d_plist->excl, h_plist->excl.data(), 0, h_plist->excl.size(), deviceStream,
666                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
667
668     if (bDoTime)
669     {
670         iTimers.pl_h2d.closeTimingRegion(deviceStream);
671     }
672
673     /* need to prune the pair list during the next step */
674     d_plist->haveFreshList = true;
675 }
676
677 //! This function is documented in the header file
678 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
679 {
680     cl_atomdata_t*   adat = nb->atdat;
681     cl_command_queue ls   = nb->deviceStreams[InteractionLocality::Local]->stream();
682
683     /* only if we have a dynamic box */
684     if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
685     {
686         ocl_copy_H2D_async(adat->shift_vec, nbatom->shift_vec.data(), 0,
687                            SHIFTS * sizeof(nbatom->shift_vec[0]), ls, nullptr);
688         adat->bShiftVecUploaded = CL_TRUE;
689     }
690 }
691
692 //! This function is documented in the header file
693 void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat)
694 {
695     cl_int              cl_error;
696     int                 nalloc, natoms;
697     bool                realloced;
698     bool                bDoTime      = nb->bDoTime;
699     cl_timers_t*        timers       = nb->timers;
700     cl_atomdata_t*      d_atdat      = nb->atdat;
701     const DeviceStream& deviceStream = *nb->deviceStreams[InteractionLocality::Local];
702
703     natoms    = nbat->numAtoms();
704     realloced = false;
705
706     if (bDoTime)
707     {
708         /* time async copy */
709         timers->atdat.openTimingRegion(deviceStream);
710     }
711
712     /* need to reallocate if we have to copy more atoms than the amount of space
713        available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
714     if (natoms > d_atdat->nalloc)
715     {
716         nalloc = over_alloc_small(natoms);
717
718         /* free up first if the arrays have already been initialized */
719         if (d_atdat->nalloc != -1)
720         {
721             freeDeviceBuffer(&d_atdat->f);
722             freeDeviceBuffer(&d_atdat->xq);
723             freeDeviceBuffer(&d_atdat->lj_comb);
724             freeDeviceBuffer(&d_atdat->atom_types);
725         }
726
727         d_atdat->f = clCreateBuffer(nb->deviceContext_->context(), CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
728                                     nalloc * DIM * sizeof(nbat->out[0].f[0]), nullptr, &cl_error);
729         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
730                            ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
731
732         d_atdat->xq = clCreateBuffer(nb->deviceContext_->context(), CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
733                                      nalloc * sizeof(cl_float4), nullptr, &cl_error);
734         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
735                            ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
736
737         if (useLjCombRule(nb->nbparam->vdwtype))
738         {
739             d_atdat->lj_comb = clCreateBuffer(nb->deviceContext_->context(),
740                                               CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
741                                               nalloc * sizeof(cl_float2), nullptr, &cl_error);
742             GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
743                                ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
744         }
745         else
746         {
747             d_atdat->atom_types = clCreateBuffer(nb->deviceContext_->context(),
748                                                  CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
749                                                  nalloc * sizeof(int), nullptr, &cl_error);
750             GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
751                                ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
752         }
753
754         d_atdat->nalloc = nalloc;
755         realloced       = true;
756     }
757
758     d_atdat->natoms       = natoms;
759     d_atdat->natoms_local = nbat->natoms_local;
760
761     /* need to clear GPU f output if realloc happened */
762     if (realloced)
763     {
764         nbnxn_ocl_clear_f(nb, nalloc);
765     }
766
767     if (useLjCombRule(nb->nbparam->vdwtype))
768     {
769         ocl_copy_H2D_async(d_atdat->lj_comb, nbat->params().lj_comb.data(), 0, natoms * sizeof(cl_float2),
770                            deviceStream.stream(), bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
771     }
772     else
773     {
774         ocl_copy_H2D_async(d_atdat->atom_types, nbat->params().type.data(), 0, natoms * sizeof(int),
775                            deviceStream.stream(), bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
776     }
777
778     if (bDoTime)
779     {
780         timers->atdat.closeTimingRegion(deviceStream);
781     }
782
783     /* kick off the tasks enqueued above to ensure concurrency with the search */
784     cl_error = clFlush(deviceStream.stream());
785     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
786                        ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
787 }
788
789 /*! \brief Releases an OpenCL kernel pointer */
790 static void free_kernel(cl_kernel* kernel_ptr)
791 {
792     cl_int gmx_unused cl_error;
793
794     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
795
796     if (*kernel_ptr)
797     {
798         cl_error = clReleaseKernel(*kernel_ptr);
799         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
800                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
801
802         *kernel_ptr = nullptr;
803     }
804 }
805
806 /*! \brief Releases a list of OpenCL kernel pointers */
807 static void free_kernels(cl_kernel* kernels, int count)
808 {
809     int i;
810
811     for (i = 0; i < count; i++)
812     {
813         free_kernel(kernels + i);
814     }
815 }
816
817 /*! \brief Free the OpenCL program.
818  *
819  *  The function releases the OpenCL program assuciated with the
820  *  device that the calling PP rank is running on.
821  *
822  *  \param program [in]  OpenCL program to release.
823  */
824 static void freeGpuProgram(cl_program program)
825 {
826     if (program)
827     {
828         cl_int cl_error = clReleaseProgram(program);
829         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
830                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
831         program = nullptr;
832     }
833 }
834
835 //! This function is documented in the header file
836 void gpu_free(NbnxmGpu* nb)
837 {
838     if (nb == nullptr)
839     {
840         return;
841     }
842
843     /* Free kernels */
844     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
845     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
846
847     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
848     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
849
850     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
851     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
852
853     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
854     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
855
856     free_kernel(&(nb->kernel_zero_e_fshift));
857
858     /* Free atdat */
859     freeDeviceBuffer(&(nb->atdat->xq));
860     freeDeviceBuffer(&(nb->atdat->f));
861     freeDeviceBuffer(&(nb->atdat->e_lj));
862     freeDeviceBuffer(&(nb->atdat->e_el));
863     freeDeviceBuffer(&(nb->atdat->fshift));
864     freeDeviceBuffer(&(nb->atdat->lj_comb));
865     freeDeviceBuffer(&(nb->atdat->atom_types));
866     freeDeviceBuffer(&(nb->atdat->shift_vec));
867     sfree(nb->atdat);
868
869     /* Free nbparam */
870     freeDeviceBuffer(&(nb->nbparam->nbfp_climg2d));
871     freeDeviceBuffer(&(nb->nbparam->nbfp_comb_climg2d));
872     freeDeviceBuffer(&(nb->nbparam->coulomb_tab_climg2d));
873     sfree(nb->nbparam);
874
875     /* Free plist */
876     auto* plist = nb->plist[InteractionLocality::Local];
877     freeDeviceBuffer(&plist->sci);
878     freeDeviceBuffer(&plist->cj4);
879     freeDeviceBuffer(&plist->imask);
880     freeDeviceBuffer(&plist->excl);
881     sfree(plist);
882     if (nb->bUseTwoStreams)
883     {
884         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
885         freeDeviceBuffer(&plist_nl->sci);
886         freeDeviceBuffer(&plist_nl->cj4);
887         freeDeviceBuffer(&plist_nl->imask);
888         freeDeviceBuffer(&plist_nl->excl);
889         sfree(plist_nl);
890     }
891
892     /* Free nbst */
893     pfree(nb->nbst.e_lj);
894     nb->nbst.e_lj = nullptr;
895
896     pfree(nb->nbst.e_el);
897     nb->nbst.e_el = nullptr;
898
899     pfree(nb->nbst.fshift);
900     nb->nbst.fshift = nullptr;
901
902     /* Free other events */
903     if (nb->nonlocal_done)
904     {
905         clReleaseEvent(nb->nonlocal_done);
906         nb->nonlocal_done = nullptr;
907     }
908     if (nb->misc_ops_and_local_H2D_done)
909     {
910         clReleaseEvent(nb->misc_ops_and_local_H2D_done);
911         nb->misc_ops_and_local_H2D_done = nullptr;
912     }
913
914     freeGpuProgram(nb->dev_rundata->program);
915     delete nb->dev_rundata;
916
917     /* Free timers and timings */
918     delete nb->timers;
919     sfree(nb->timings);
920     delete nb;
921
922     if (debug)
923     {
924         fprintf(debug, "Cleaned up OpenCL data structures.\n");
925     }
926 }
927
928 //! This function is documented in the header file
929 gmx_wallclock_gpu_nbnxn_t* gpu_get_timings(NbnxmGpu* nb)
930 {
931     return (nb != nullptr && nb->bDoTime) ? nb->timings : nullptr;
932 }
933
934 //! This function is documented in the header file
935 void gpu_reset_timings(nonbonded_verlet_t* nbv)
936 {
937     if (nbv->gpu_nbv && nbv->gpu_nbv->bDoTime)
938     {
939         init_timings(nbv->gpu_nbv->timings);
940     }
941 }
942
943 //! This function is documented in the header file
944 int gpu_min_ci_balanced(NbnxmGpu* nb)
945 {
946     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
947 }
948
949 //! This function is documented in the header file
950 gmx_bool gpu_is_kernel_ewald_analytical(const NbnxmGpu* nb)
951 {
952     return ((nb->nbparam->eeltype == eelOclEWALD_ANA) || (nb->nbparam->eeltype == eelOclEWALD_ANA_TWIN));
953 }
954
955 } // namespace Nbnxm