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