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