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