Change default Ewald kernel to tabulated on NVIDIA CC 7.0
[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,2021, 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/oclutils.h"
57 #include "gromacs/hardware/device_information.h"
58 #include "gromacs/hardware/device_management.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/nbnxm_gpu_data_mgmt.h"
69 #include "gromacs/nbnxm/pairlistsets.h"
70 #include "gromacs/pbcutil/ishift.h"
71 #include "gromacs/timing/gpu_timing.h"
72 #include "gromacs/utility/cstringutil.h"
73 #include "gromacs/utility/fatalerror.h"
74 #include "gromacs/utility/gmxassert.h"
75 #include "gromacs/utility/real.h"
76 #include "gromacs/utility/smalloc.h"
77
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 Initializes the atomdata structure first time, it only gets filled at
104     pair-search.
105  */
106 static void init_atomdata_first(cl_atomdata_t* ad, int ntypes, const DeviceContext& deviceContext)
107 {
108     ad->ntypes = ntypes;
109
110     allocateDeviceBuffer(&ad->shift_vec, SHIFTS * DIM, deviceContext);
111     ad->bShiftVecUploaded = CL_FALSE;
112
113     allocateDeviceBuffer(&ad->fshift, SHIFTS * DIM, deviceContext);
114     allocateDeviceBuffer(&ad->e_lj, 1, deviceContext);
115     allocateDeviceBuffer(&ad->e_el, 1, deviceContext);
116
117     /* initialize to nullptr pointers to data that is not allocated here and will
118        need reallocation in nbnxn_gpu_init_atomdata */
119     ad->xq = nullptr;
120     ad->f  = nullptr;
121
122     /* size -1 indicates that the respective array hasn't been initialized yet */
123     ad->natoms = -1;
124     ad->nalloc = -1;
125 }
126
127 /*! \brief Returns the kinds of electrostatics and Vdw OpenCL
128  *  kernels that will be used.
129  *
130  * Respectively, these values are from enum eelOcl and enum
131  * evdwOcl. */
132 static void map_interaction_types_to_gpu_kernel_flavors(const interaction_const_t* ic,
133                                                         int                        combRule,
134                                                         int*                       gpu_eeltype,
135                                                         int*                       gpu_vdwtype,
136                                                         const DeviceContext&       deviceContext)
137 {
138     if (ic->vdwtype == evdwCUT)
139     {
140         switch (ic->vdw_modifier)
141         {
142             case eintmodNONE:
143             case eintmodPOTSHIFT:
144                 switch (combRule)
145                 {
146                     case ljcrNONE: *gpu_vdwtype = evdwTypeCUT; break;
147                     case ljcrGEOM: *gpu_vdwtype = evdwTypeCUTCOMBGEOM; break;
148                     case ljcrLB: *gpu_vdwtype = evdwTypeCUTCOMBLB; break;
149                     default:
150                         gmx_incons(
151                                 "The requested LJ combination rule is not implemented in the "
152                                 "OpenCL GPU accelerated kernels!");
153                 }
154                 break;
155             case eintmodFORCESWITCH: *gpu_vdwtype = evdwTypeFSWITCH; break;
156             case eintmodPOTSWITCH: *gpu_vdwtype = evdwTypePSWITCH; break;
157             default:
158                 gmx_incons(
159                         "The requested VdW interaction modifier is not implemented in the GPU "
160                         "accelerated kernels!");
161         }
162     }
163     else if (ic->vdwtype == evdwPME)
164     {
165         if (ic->ljpme_comb_rule == ljcrGEOM)
166         {
167             *gpu_vdwtype = evdwTypeEWALDGEOM;
168         }
169         else
170         {
171             *gpu_vdwtype = evdwTypeEWALDLB;
172         }
173     }
174     else
175     {
176         gmx_incons("The requested VdW type is not implemented in the GPU accelerated kernels!");
177     }
178
179     if (ic->eeltype == eelCUT)
180     {
181         *gpu_eeltype = eelTypeCUT;
182     }
183     else if (EEL_RF(ic->eeltype))
184     {
185         *gpu_eeltype = eelTypeRF;
186     }
187     else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
188     {
189         *gpu_eeltype = nbnxn_gpu_pick_ewald_kernel_type(*ic, deviceContext.deviceInfo());
190     }
191     else
192     {
193         /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
194         gmx_incons(
195                 "The requested electrostatics type is not implemented in the GPU accelerated "
196                 "kernels!");
197     }
198 }
199
200 /*! \brief Initializes the nonbonded parameter data structure.
201  */
202 static void init_nbparam(NBParamGpu*                     nbp,
203                          const interaction_const_t*      ic,
204                          const PairlistParams&           listParams,
205                          const nbnxn_atomdata_t::Params& nbatParams,
206                          const DeviceContext&            deviceContext)
207 {
208     set_cutoff_parameters(nbp, ic, listParams);
209
210     map_interaction_types_to_gpu_kernel_flavors(ic, nbatParams.comb_rule, &(nbp->eeltype),
211                                                 &(nbp->vdwtype), deviceContext);
212
213     if (ic->vdwtype == evdwPME)
214     {
215         if (ic->ljpme_comb_rule == ljcrGEOM)
216         {
217             GMX_ASSERT(nbatParams.comb_rule == ljcrGEOM, "Combination rule mismatch!");
218         }
219         else
220         {
221             GMX_ASSERT(nbatParams.comb_rule == ljcrLB, "Combination rule mismatch!");
222         }
223     }
224     /* generate table for PME */
225     nbp->coulomb_tab = nullptr;
226     if (nbp->eeltype == eelTypeEWALD_TAB || nbp->eeltype == eelTypeEWALD_TAB_TWIN)
227     {
228         GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
229         init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
230     }
231     else
232     {
233         allocateDeviceBuffer(&nbp->coulomb_tab, 1, deviceContext);
234     }
235
236     const int nnbfp      = 2 * nbatParams.numTypes * nbatParams.numTypes;
237     const int nnbfp_comb = 2 * nbatParams.numTypes;
238
239     {
240         /* set up LJ parameter lookup table */
241         DeviceBuffer<real> nbfp;
242         initParamLookupTable(&nbfp, nullptr, nbatParams.nbfp.data(), nnbfp, deviceContext);
243         nbp->nbfp = nbfp;
244
245         if (ic->vdwtype == evdwPME)
246         {
247             DeviceBuffer<float> nbfp_comb;
248             initParamLookupTable(&nbfp_comb, nullptr, nbatParams.nbfp_comb.data(), nnbfp_comb, deviceContext);
249             nbp->nbfp_comb = nbfp_comb;
250         }
251     }
252 }
253
254 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
255 static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name)
256 {
257     cl_kernel kernel;
258     cl_int    cl_error;
259
260     kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
261     if (CL_SUCCESS != cl_error)
262     {
263         gmx_fatal(FARGS, "Failed to create kernel '%s' for GPU #%s: OpenCL error %d", kernel_name,
264                   nb->deviceContext_->deviceInfo().device_name, cl_error);
265     }
266
267     return kernel;
268 }
269
270 /*! \brief Clears nonbonded shift force output array and energy outputs on the GPU.
271  */
272 static void nbnxn_ocl_clear_e_fshift(NbnxmGpu* nb)
273 {
274
275     cl_int           cl_error;
276     cl_atomdata_t*   adat = nb->atdat;
277     cl_command_queue ls   = nb->deviceStreams[InteractionLocality::Local]->stream();
278
279     size_t local_work_size[3]  = { 1, 1, 1 };
280     size_t global_work_size[3] = { 1, 1, 1 };
281
282     cl_int shifts = SHIFTS * 3;
283
284     cl_int arg_no;
285
286     cl_kernel zero_e_fshift = nb->kernel_zero_e_fshift;
287
288     local_work_size[0] = 64;
289     // Round the total number of threads up from the array size
290     global_work_size[0] = ((shifts + local_work_size[0] - 1) / local_work_size[0]) * local_work_size[0];
291
292     arg_no   = 0;
293     cl_error = clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->fshift));
294     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_lj));
295     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_el));
296     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_uint), &shifts);
297     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
298
299     cl_error = clEnqueueNDRangeKernel(ls, zero_e_fshift, 3, nullptr, global_work_size,
300                                       local_work_size, 0, nullptr, nullptr);
301     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
302 }
303
304 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
305 static void nbnxn_gpu_init_kernels(NbnxmGpu* nb)
306 {
307     /* Init to 0 main kernel arrays */
308     /* They will be later on initialized in select_nbnxn_kernel */
309     // TODO: consider always creating all variants of the kernels here so that there is no
310     // need for late call to clCreateKernel -- if that gives any advantage?
311     memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
312     memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
313     memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
314     memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
315
316     /* Init pruning kernels
317      *
318      * TODO: we could avoid creating kernels if dynamic pruning is turned off,
319      * but ATM that depends on force flags not passed into the initialization.
320      */
321     nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
322     nb->kernel_pruneonly[epruneRolling] =
323             nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
324
325     /* Init auxiliary kernels */
326     nb->kernel_zero_e_fshift = nbnxn_gpu_create_kernel(nb, "zero_e_fshift");
327 }
328
329 /*! \brief Initializes simulation constant data.
330  *
331  *  Initializes members of the atomdata and nbparam structs and
332  *  clears e/fshift output buffers.
333  */
334 static void nbnxn_ocl_init_const(cl_atomdata_t*                  atomData,
335                                  NBParamGpu*                     nbParams,
336                                  const interaction_const_t*      ic,
337                                  const PairlistParams&           listParams,
338                                  const nbnxn_atomdata_t::Params& nbatParams,
339                                  const DeviceContext&            deviceContext)
340 {
341     init_atomdata_first(atomData, nbatParams.numTypes, deviceContext);
342     init_nbparam(nbParams, ic, listParams, nbatParams, deviceContext);
343 }
344
345
346 //! This function is documented in the header file
347 NbnxmGpu* gpu_init(const gmx::DeviceStreamManager& deviceStreamManager,
348                    const interaction_const_t*      ic,
349                    const PairlistParams&           listParams,
350                    const nbnxn_atomdata_t*         nbat,
351                    const bool                      bLocalAndNonlocal)
352 {
353     GMX_ASSERT(ic, "Need a valid interaction constants object");
354
355     auto nb            = new NbnxmGpu();
356     nb->deviceContext_ = &deviceStreamManager.context();
357     snew(nb->atdat, 1);
358     snew(nb->nbparam, 1);
359     snew(nb->plist[InteractionLocality::Local], 1);
360     if (bLocalAndNonlocal)
361     {
362         snew(nb->plist[InteractionLocality::NonLocal], 1);
363     }
364
365     nb->bUseTwoStreams = bLocalAndNonlocal;
366
367     nb->timers = new cl_timers_t();
368     snew(nb->timings, 1);
369
370     /* set device info, just point it to the right GPU among the detected ones */
371     nb->dev_rundata = new gmx_device_runtime_data_t();
372
373     /* init nbst */
374     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_lj), sizeof(*nb->nbst.e_lj));
375     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_el), sizeof(*nb->nbst.e_el));
376     pmalloc(reinterpret_cast<void**>(&nb->nbst.fshift), SHIFTS * sizeof(*nb->nbst.fshift));
377
378     init_plist(nb->plist[InteractionLocality::Local]);
379
380     /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
381     nb->bDoTime = (getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
382
383     /* local/non-local GPU streams */
384     GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedLocal),
385                        "Local non-bonded stream should be initialized to use GPU for non-bonded.");
386     nb->deviceStreams[InteractionLocality::Local] =
387             &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal);
388
389     if (nb->bUseTwoStreams)
390     {
391         init_plist(nb->plist[InteractionLocality::NonLocal]);
392
393         GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedNonLocal),
394                            "Non-local non-bonded stream should be initialized to use GPU for "
395                            "non-bonded with domain decomposition.");
396         nb->deviceStreams[InteractionLocality::NonLocal] =
397                 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal);
398     }
399
400     if (nb->bDoTime)
401     {
402         init_timings(nb->timings);
403     }
404
405     nbnxn_ocl_init_const(nb->atdat, nb->nbparam, ic, listParams, nbat->params(), *nb->deviceContext_);
406
407     /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
408      * TODO: decide about NVIDIA
409      */
410     nb->bPrefetchLjParam = (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr)
411                            && ((nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Amd)
412                                || (nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Intel)
413                                || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
414
415     /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
416      * but sadly this is not supported in OpenCL (yet?). Consider adding it if
417      * it becomes supported.
418      */
419     nbnxn_gpu_compile_kernels(nb);
420     nbnxn_gpu_init_kernels(nb);
421
422     /* clear energy and shift force outputs */
423     nbnxn_ocl_clear_e_fshift(nb);
424
425     if (debug)
426     {
427         fprintf(debug, "Initialized OpenCL data structures.\n");
428     }
429
430     return nb;
431 }
432
433 /*! \brief Clears the first natoms_clear elements of the GPU nonbonded force output array.
434  */
435 static void nbnxn_ocl_clear_f(NbnxmGpu* nb, int natoms_clear)
436 {
437     if (natoms_clear == 0)
438     {
439         return;
440     }
441
442     cl_atomdata_t*      atomData    = nb->atdat;
443     const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
444
445     clearDeviceBufferAsync(&atomData->f, 0, natoms_clear * DIM, localStream);
446 }
447
448 //! This function is documented in the header file
449 void gpu_clear_outputs(NbnxmGpu* nb, bool computeVirial)
450 {
451     nbnxn_ocl_clear_f(nb, nb->atdat->natoms);
452     /* clear shift force array and energies if the outputs were
453        used in the current step */
454     if (computeVirial)
455     {
456         nbnxn_ocl_clear_e_fshift(nb);
457     }
458
459     /* kick off buffer clearing kernel to ensure concurrency with constraints/update */
460     cl_int gmx_unused cl_error;
461     cl_error = clFlush(nb->deviceStreams[InteractionLocality::Local]->stream());
462     GMX_ASSERT(cl_error == CL_SUCCESS, ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
463 }
464
465 //! This function is documented in the header file
466 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
467 {
468     cl_atomdata_t*      adat         = nb->atdat;
469     const DeviceStream& deviceStream = *nb->deviceStreams[InteractionLocality::Local];
470
471     /* only if we have a dynamic box */
472     if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
473     {
474         GMX_ASSERT(sizeof(float) * DIM == sizeof(*nbatom->shift_vec.data()),
475                    "Sizes of host- and device-side shift vectors should be the same.");
476         copyToDeviceBuffer(&adat->shift_vec, reinterpret_cast<const float*>(nbatom->shift_vec.data()),
477                            0, SHIFTS * DIM, deviceStream, GpuApiCallBehavior::Async, nullptr);
478         adat->bShiftVecUploaded = CL_TRUE;
479     }
480 }
481
482 //! This function is documented in the header file
483 void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat)
484 {
485     cl_int               cl_error;
486     int                  nalloc, natoms;
487     bool                 realloced;
488     bool                 bDoTime       = nb->bDoTime;
489     cl_timers_t*         timers        = nb->timers;
490     cl_atomdata_t*       d_atdat       = nb->atdat;
491     const DeviceContext& deviceContext = *nb->deviceContext_;
492     const DeviceStream&  deviceStream  = *nb->deviceStreams[InteractionLocality::Local];
493
494     natoms    = nbat->numAtoms();
495     realloced = false;
496
497     if (bDoTime)
498     {
499         /* time async copy */
500         timers->atdat.openTimingRegion(deviceStream);
501     }
502
503     /* need to reallocate if we have to copy more atoms than the amount of space
504        available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
505     if (natoms > d_atdat->nalloc)
506     {
507         nalloc = over_alloc_small(natoms);
508
509         /* free up first if the arrays have already been initialized */
510         if (d_atdat->nalloc != -1)
511         {
512             freeDeviceBuffer(&d_atdat->f);
513             freeDeviceBuffer(&d_atdat->xq);
514             freeDeviceBuffer(&d_atdat->lj_comb);
515             freeDeviceBuffer(&d_atdat->atom_types);
516         }
517
518
519         allocateDeviceBuffer(&d_atdat->f, nalloc * DIM, deviceContext);
520         allocateDeviceBuffer(&d_atdat->xq, nalloc * (DIM + 1), deviceContext);
521
522         if (useLjCombRule(nb->nbparam->vdwtype))
523         {
524             // Two Lennard-Jones parameters per atom
525             allocateDeviceBuffer(&d_atdat->lj_comb, nalloc * 2, deviceContext);
526         }
527         else
528         {
529             allocateDeviceBuffer(&d_atdat->atom_types, nalloc, deviceContext);
530         }
531
532         d_atdat->nalloc = nalloc;
533         realloced       = true;
534     }
535
536     d_atdat->natoms       = natoms;
537     d_atdat->natoms_local = nbat->natoms_local;
538
539     /* need to clear GPU f output if realloc happened */
540     if (realloced)
541     {
542         nbnxn_ocl_clear_f(nb, nalloc);
543     }
544
545     if (useLjCombRule(nb->nbparam->vdwtype))
546     {
547         GMX_ASSERT(sizeof(float) == sizeof(*nbat->params().lj_comb.data()),
548                    "Size of the LJ parameters element should be equal to the size of float2.");
549         copyToDeviceBuffer(&d_atdat->lj_comb, nbat->params().lj_comb.data(), 0, 2 * natoms,
550                            deviceStream, GpuApiCallBehavior::Async,
551                            bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
552     }
553     else
554     {
555         GMX_ASSERT(sizeof(int) == sizeof(*nbat->params().type.data()),
556                    "Sizes of host- and device-side atom types should be the same.");
557         copyToDeviceBuffer(&d_atdat->atom_types, nbat->params().type.data(), 0, natoms, deviceStream,
558                            GpuApiCallBehavior::Async, bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
559     }
560
561     if (bDoTime)
562     {
563         timers->atdat.closeTimingRegion(deviceStream);
564     }
565
566     /* kick off the tasks enqueued above to ensure concurrency with the search */
567     cl_error = clFlush(deviceStream.stream());
568     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
569                        ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
570 }
571
572 /*! \brief Releases an OpenCL kernel pointer */
573 static void free_kernel(cl_kernel* kernel_ptr)
574 {
575     cl_int gmx_unused cl_error;
576
577     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
578
579     if (*kernel_ptr)
580     {
581         cl_error = clReleaseKernel(*kernel_ptr);
582         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
583                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
584
585         *kernel_ptr = nullptr;
586     }
587 }
588
589 /*! \brief Releases a list of OpenCL kernel pointers */
590 static void free_kernels(cl_kernel* kernels, int count)
591 {
592     int i;
593
594     for (i = 0; i < count; i++)
595     {
596         free_kernel(kernels + i);
597     }
598 }
599
600 /*! \brief Free the OpenCL program.
601  *
602  *  The function releases the OpenCL program assuciated with the
603  *  device that the calling PP rank is running on.
604  *
605  *  \param program [in]  OpenCL program to release.
606  */
607 static void freeGpuProgram(cl_program program)
608 {
609     if (program)
610     {
611         cl_int cl_error = clReleaseProgram(program);
612         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
613                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
614         program = nullptr;
615     }
616 }
617
618 //! This function is documented in the header file
619 void gpu_free(NbnxmGpu* nb)
620 {
621     if (nb == nullptr)
622     {
623         return;
624     }
625
626     /* Free kernels */
627     // NOLINTNEXTLINE(bugprone-sizeof-expression)
628     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
629     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
630
631     // NOLINTNEXTLINE(bugprone-sizeof-expression)
632     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
633     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
634
635     // NOLINTNEXTLINE(bugprone-sizeof-expression)
636     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
637     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
638
639     // NOLINTNEXTLINE(bugprone-sizeof-expression)
640     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
641     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
642
643     free_kernel(&(nb->kernel_zero_e_fshift));
644
645     /* Free atdat */
646     freeDeviceBuffer(&(nb->atdat->xq));
647     freeDeviceBuffer(&(nb->atdat->f));
648     freeDeviceBuffer(&(nb->atdat->e_lj));
649     freeDeviceBuffer(&(nb->atdat->e_el));
650     freeDeviceBuffer(&(nb->atdat->fshift));
651     freeDeviceBuffer(&(nb->atdat->lj_comb));
652     freeDeviceBuffer(&(nb->atdat->atom_types));
653     freeDeviceBuffer(&(nb->atdat->shift_vec));
654     sfree(nb->atdat);
655
656     /* Free nbparam */
657     freeDeviceBuffer(&(nb->nbparam->nbfp));
658     freeDeviceBuffer(&(nb->nbparam->nbfp_comb));
659     freeDeviceBuffer(&(nb->nbparam->coulomb_tab));
660     sfree(nb->nbparam);
661
662     /* Free plist */
663     auto* plist = nb->plist[InteractionLocality::Local];
664     freeDeviceBuffer(&plist->sci);
665     freeDeviceBuffer(&plist->cj4);
666     freeDeviceBuffer(&plist->imask);
667     freeDeviceBuffer(&plist->excl);
668     sfree(plist);
669     if (nb->bUseTwoStreams)
670     {
671         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
672         freeDeviceBuffer(&plist_nl->sci);
673         freeDeviceBuffer(&plist_nl->cj4);
674         freeDeviceBuffer(&plist_nl->imask);
675         freeDeviceBuffer(&plist_nl->excl);
676         sfree(plist_nl);
677     }
678
679     /* Free nbst */
680     pfree(nb->nbst.e_lj);
681     nb->nbst.e_lj = nullptr;
682
683     pfree(nb->nbst.e_el);
684     nb->nbst.e_el = nullptr;
685
686     pfree(nb->nbst.fshift);
687     nb->nbst.fshift = nullptr;
688
689     /* Free other events */
690     if (nb->nonlocal_done)
691     {
692         clReleaseEvent(nb->nonlocal_done);
693         nb->nonlocal_done = nullptr;
694     }
695     if (nb->misc_ops_and_local_H2D_done)
696     {
697         clReleaseEvent(nb->misc_ops_and_local_H2D_done);
698         nb->misc_ops_and_local_H2D_done = nullptr;
699     }
700
701     freeGpuProgram(nb->dev_rundata->program);
702     delete nb->dev_rundata;
703
704     /* Free timers and timings */
705     delete nb->timers;
706     sfree(nb->timings);
707     delete nb;
708
709     if (debug)
710     {
711         fprintf(debug, "Cleaned up OpenCL data structures.\n");
712     }
713 }
714
715 //! This function is documented in the header file
716 int gpu_min_ci_balanced(NbnxmGpu* nb)
717 {
718     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
719 }
720
721 } // namespace Nbnxm