Replace *_free_buffered calls by freeDeviceBuffer
[alexxy/gromacs.git] / src / gromacs / ewald / pme.cu
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \internal \file
37  * \brief This file contains internal CUDA function implementations
38  * for performing the PME calculations on GPU.
39  *
40  * \author Aleksei Iupinov <a.yupinov@gmail.com>
41  */
42
43 #include "gmxpre.h"
44
45 #include <cmath>
46
47 /* The rest */
48 #include "pme.h"
49
50 #include "gromacs/gpu_utils/cudautils.cuh"
51 #include "gromacs/gpu_utils/pmalloc_cuda.h"
52 #include "gromacs/utility/gmxassert.h"
53 #include "gromacs/utility/smalloc.h"
54
55 #include "pme.cuh"
56 #include "pme-3dfft.cuh"
57 #include "pme-grid.h"
58
59 int pme_gpu_get_atom_data_alignment(const PmeGpu *pmeGpu)
60 {
61     const int order = pmeGpu->common->pme_order;
62     GMX_ASSERT(order > 0, "Invalid PME order");
63     return PME_ATOM_DATA_ALIGNMENT;
64 }
65
66 int pme_gpu_get_atoms_per_warp(const PmeGpu *pmeGpu)
67 {
68     const int order = pmeGpu->common->pme_order;
69     GMX_ASSERT(order > 0, "Invalid PME order");
70     return PME_SPREADGATHER_ATOMS_PER_WARP;
71 }
72
73 void pme_gpu_synchronize(const PmeGpu *pmeGpu)
74 {
75     cudaError_t stat = cudaStreamSynchronize(pmeGpu->archSpecific->pmeStream);
76     CU_RET_ERR(stat, "Failed to synchronize the PME GPU stream!");
77 }
78
79 void pme_gpu_alloc_energy_virial(const PmeGpu *pmeGpu)
80 {
81     const size_t energyAndVirialSize = c_virialAndEnergyCount * sizeof(float);
82     cudaError_t  stat                = cudaMalloc((void **)&pmeGpu->kernelParams->constants.d_virialAndEnergy, energyAndVirialSize);
83     CU_RET_ERR(stat, "cudaMalloc failed on PME energy and virial");
84     pmalloc((void **)&pmeGpu->staging.h_virialAndEnergy, energyAndVirialSize);
85 }
86
87 void pme_gpu_free_energy_virial(PmeGpu *pmeGpu)
88 {
89     cudaError_t stat = cudaFree(pmeGpu->kernelParams->constants.d_virialAndEnergy);
90     CU_RET_ERR(stat, "cudaFree failed on PME energy and virial");
91     pmeGpu->kernelParams->constants.d_virialAndEnergy = nullptr;
92     pfree(pmeGpu->staging.h_virialAndEnergy);
93     pmeGpu->staging.h_virialAndEnergy = nullptr;
94 }
95
96 void pme_gpu_clear_energy_virial(const PmeGpu *pmeGpu)
97 {
98     cudaError_t stat = cudaMemsetAsync(pmeGpu->kernelParams->constants.d_virialAndEnergy, 0,
99                                        c_virialAndEnergyCount * sizeof(float), pmeGpu->archSpecific->pmeStream);
100     CU_RET_ERR(stat, "PME energy/virial cudaMemsetAsync error");
101 }
102
103 void pme_gpu_realloc_and_copy_bspline_values(const PmeGpu *pmeGpu)
104 {
105     const int splineValuesOffset[DIM] = {
106         0,
107         pmeGpu->kernelParams->grid.realGridSize[XX],
108         pmeGpu->kernelParams->grid.realGridSize[XX] + pmeGpu->kernelParams->grid.realGridSize[YY]
109     };
110     memcpy((void *)&pmeGpu->kernelParams->grid.splineValuesOffset, &splineValuesOffset, sizeof(splineValuesOffset));
111
112     const int newSplineValuesSize = pmeGpu->kernelParams->grid.realGridSize[XX] +
113         pmeGpu->kernelParams->grid.realGridSize[YY] +
114         pmeGpu->kernelParams->grid.realGridSize[ZZ];
115     const bool shouldRealloc = (newSplineValuesSize > pmeGpu->archSpecific->splineValuesSize);
116     cu_realloc_buffered((void **)&pmeGpu->kernelParams->grid.d_splineModuli, nullptr, sizeof(float),
117                         &pmeGpu->archSpecific->splineValuesSize, &pmeGpu->archSpecific->splineValuesSizeAlloc, newSplineValuesSize, pmeGpu->archSpecific->pmeStream, true);
118     if (shouldRealloc)
119     {
120         /* Reallocate the host buffer */
121         pfree(pmeGpu->staging.h_splineModuli);
122         pmalloc((void **)&pmeGpu->staging.h_splineModuli, newSplineValuesSize * sizeof(float));
123     }
124     for (int i = 0; i < DIM; i++)
125     {
126         memcpy(pmeGpu->staging.h_splineModuli + splineValuesOffset[i], pmeGpu->common->bsp_mod[i].data(), pmeGpu->common->bsp_mod[i].size() * sizeof(float));
127     }
128     /* TODO: pin original buffer instead! */
129     cu_copy_H2D(pmeGpu->kernelParams->grid.d_splineModuli, pmeGpu->staging.h_splineModuli,
130                 newSplineValuesSize * sizeof(float), pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
131 }
132
133 void pme_gpu_free_bspline_values(const PmeGpu *pmeGpu)
134 {
135     pfree(pmeGpu->staging.h_splineModuli);
136     freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli);
137 }
138
139 void pme_gpu_realloc_forces(PmeGpu *pmeGpu)
140 {
141     const size_t newForcesSize = pmeGpu->nAtomsAlloc * DIM;
142     GMX_ASSERT(newForcesSize > 0, "Bad number of atoms in PME GPU");
143     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_forces, nullptr, sizeof(float),
144                         &pmeGpu->archSpecific->forcesSize, &pmeGpu->archSpecific->forcesSizeAlloc, newForcesSize, pmeGpu->archSpecific->pmeStream, true);
145     pmeGpu->staging.h_forces.reserve(pmeGpu->nAtomsAlloc);
146     pmeGpu->staging.h_forces.resize(pmeGpu->kernelParams->atoms.nAtoms);
147 }
148
149 void pme_gpu_free_forces(const PmeGpu *pmeGpu)
150 {
151     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces);
152 }
153
154 void pme_gpu_copy_input_forces(PmeGpu *pmeGpu)
155 {
156     const size_t forcesSize = DIM * pmeGpu->kernelParams->atoms.nAtoms * sizeof(float);
157     GMX_ASSERT(forcesSize > 0, "Bad number of atoms in PME GPU");
158     cu_copy_H2D(pmeGpu->kernelParams->atoms.d_forces, pmeGpu->staging.h_forces.data(), forcesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
159 }
160
161 void pme_gpu_copy_output_forces(PmeGpu *pmeGpu)
162 {
163     const size_t forcesSize   = DIM * pmeGpu->kernelParams->atoms.nAtoms * sizeof(float);
164     GMX_ASSERT(forcesSize > 0, "Bad number of atoms in PME GPU");
165     cu_copy_D2H(pmeGpu->staging.h_forces.data(), pmeGpu->kernelParams->atoms.d_forces, forcesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
166 }
167
168 void pme_gpu_realloc_coordinates(const PmeGpu *pmeGpu)
169 {
170     const size_t newCoordinatesSize = pmeGpu->nAtomsAlloc * DIM;
171     GMX_ASSERT(newCoordinatesSize > 0, "Bad number of atoms in PME GPU");
172     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_coordinates, nullptr, sizeof(float),
173                         &pmeGpu->archSpecific->coordinatesSize, &pmeGpu->archSpecific->coordinatesSizeAlloc, newCoordinatesSize, pmeGpu->archSpecific->pmeStream, true);
174     if (c_usePadding)
175     {
176         const size_t paddingIndex = DIM * pmeGpu->kernelParams->atoms.nAtoms;
177         const size_t paddingCount = DIM * pmeGpu->nAtomsAlloc - paddingIndex;
178         if (paddingCount > 0)
179         {
180             cudaError_t stat = cudaMemsetAsync(pmeGpu->kernelParams->atoms.d_coordinates + paddingIndex, 0, paddingCount * sizeof(float), pmeGpu->archSpecific->pmeStream);
181             CU_RET_ERR(stat, "PME failed to clear the padded coordinates");
182         }
183     }
184 }
185
186 void pme_gpu_copy_input_coordinates(const PmeGpu *pmeGpu, const rvec *h_coordinates)
187 {
188     GMX_ASSERT(h_coordinates, "Bad host-side coordinate buffer in PME GPU");
189 #if GMX_DOUBLE
190     GMX_RELEASE_ASSERT(false, "Only single precision is supported");
191     GMX_UNUSED_VALUE(h_coordinates);
192 #else
193     cu_copy_H2D(pmeGpu->kernelParams->atoms.d_coordinates, const_cast<rvec *>(h_coordinates),
194                 pmeGpu->kernelParams->atoms.nAtoms * sizeof(rvec), pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
195 #endif
196 }
197
198 void pme_gpu_free_coordinates(const PmeGpu *pmeGpu)
199 {
200     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coordinates);
201 }
202
203 void pme_gpu_realloc_and_copy_input_coefficients(const PmeGpu *pmeGpu, const float *h_coefficients)
204 {
205     GMX_ASSERT(h_coefficients, "Bad host-side charge buffer in PME GPU");
206     const size_t newCoefficientsSize = pmeGpu->nAtomsAlloc;
207     GMX_ASSERT(newCoefficientsSize > 0, "Bad number of atoms in PME GPU");
208     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_coefficients, nullptr, sizeof(float),
209                         &pmeGpu->archSpecific->coefficientsSize, &pmeGpu->archSpecific->coefficientsSizeAlloc,
210                         newCoefficientsSize, pmeGpu->archSpecific->pmeStream, true);
211     cu_copy_H2D(pmeGpu->kernelParams->atoms.d_coefficients, const_cast<float *>(h_coefficients),
212                 pmeGpu->kernelParams->atoms.nAtoms * sizeof(float), pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
213     if (c_usePadding)
214     {
215         const size_t paddingIndex = pmeGpu->kernelParams->atoms.nAtoms;
216         const size_t paddingCount = pmeGpu->nAtomsAlloc - paddingIndex;
217         if (paddingCount > 0)
218         {
219             cudaError_t stat = cudaMemsetAsync(pmeGpu->kernelParams->atoms.d_coefficients + paddingIndex, 0, paddingCount * sizeof(float), pmeGpu->archSpecific->pmeStream);
220             CU_RET_ERR(stat, "PME failed to clear the padded charges");
221         }
222     }
223 }
224
225 void pme_gpu_free_coefficients(const PmeGpu *pmeGpu)
226 {
227     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients);
228 }
229
230 void pme_gpu_realloc_spline_data(const PmeGpu *pmeGpu)
231 {
232     const int    order             = pmeGpu->common->pme_order;
233     const int    alignment         = pme_gpu_get_atoms_per_warp(pmeGpu);
234     const size_t nAtomsPadded      = ((pmeGpu->nAtomsAlloc + alignment - 1) / alignment) * alignment;
235     const int    newSplineDataSize = DIM * order * nAtomsPadded;
236     GMX_ASSERT(newSplineDataSize > 0, "Bad number of atoms in PME GPU");
237     /* Two arrays of the same size */
238     const bool shouldRealloc        = (newSplineDataSize > pmeGpu->archSpecific->splineDataSize);
239     int        currentSizeTemp      = pmeGpu->archSpecific->splineDataSize;
240     int        currentSizeTempAlloc = pmeGpu->archSpecific->splineDataSizeAlloc;
241     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_theta, nullptr, sizeof(float),
242                         &currentSizeTemp, &currentSizeTempAlloc, newSplineDataSize, pmeGpu->archSpecific->pmeStream, true);
243     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_dtheta, nullptr, sizeof(float),
244                         &pmeGpu->archSpecific->splineDataSize, &pmeGpu->archSpecific->splineDataSizeAlloc, newSplineDataSize, pmeGpu->archSpecific->pmeStream, true);
245     // the host side reallocation
246     if (shouldRealloc)
247     {
248         pfree(pmeGpu->staging.h_theta);
249         pmalloc((void **)&pmeGpu->staging.h_theta, newSplineDataSize * sizeof(float));
250         pfree(pmeGpu->staging.h_dtheta);
251         pmalloc((void **)&pmeGpu->staging.h_dtheta, newSplineDataSize * sizeof(float));
252     }
253 }
254
255 void pme_gpu_free_spline_data(const PmeGpu *pmeGpu)
256 {
257     /* Two arrays of the same size */
258     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_theta);
259     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_dtheta);
260     pfree(pmeGpu->staging.h_theta);
261     pfree(pmeGpu->staging.h_dtheta);
262 }
263
264 void pme_gpu_realloc_grid_indices(const PmeGpu *pmeGpu)
265 {
266     const size_t newIndicesSize = DIM * pmeGpu->nAtomsAlloc;
267     GMX_ASSERT(newIndicesSize > 0, "Bad number of atoms in PME GPU");
268     cu_realloc_buffered((void **)&pmeGpu->kernelParams->atoms.d_gridlineIndices, nullptr, sizeof(int),
269                         &pmeGpu->archSpecific->gridlineIndicesSize, &pmeGpu->archSpecific->gridlineIndicesSizeAlloc, newIndicesSize, pmeGpu->archSpecific->pmeStream, true);
270     pfree(pmeGpu->staging.h_gridlineIndices);
271     pmalloc((void **)&pmeGpu->staging.h_gridlineIndices, newIndicesSize * sizeof(int));
272 }
273
274 void pme_gpu_free_grid_indices(const PmeGpu *pmeGpu)
275 {
276     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_gridlineIndices);
277     pfree(pmeGpu->staging.h_gridlineIndices);
278 }
279
280 void pme_gpu_realloc_grids(PmeGpu *pmeGpu)
281 {
282     auto     *kernelParamsPtr = pmeGpu->kernelParams.get();
283     const int newRealGridSize = kernelParamsPtr->grid.realGridSizePadded[XX] *
284         kernelParamsPtr->grid.realGridSizePadded[YY] *
285         kernelParamsPtr->grid.realGridSizePadded[ZZ];
286     const int newComplexGridSize = kernelParamsPtr->grid.complexGridSizePadded[XX] *
287         kernelParamsPtr->grid.complexGridSizePadded[YY] *
288         kernelParamsPtr->grid.complexGridSizePadded[ZZ] * 2;
289     // Multiplied by 2 because we count complex grid size for complex numbers, but all allocations/pointers are float
290     if (pmeGpu->archSpecific->performOutOfPlaceFFT)
291     {
292         /* 2 separate grids */
293         cu_realloc_buffered((void **)&kernelParamsPtr->grid.d_fourierGrid, nullptr, sizeof(float),
294                             &pmeGpu->archSpecific->complexGridSize, &pmeGpu->archSpecific->complexGridSizeAlloc,
295                             newComplexGridSize, pmeGpu->archSpecific->pmeStream, true);
296         cu_realloc_buffered((void **)&kernelParamsPtr->grid.d_realGrid, nullptr, sizeof(float),
297                             &pmeGpu->archSpecific->realGridSize, &pmeGpu->archSpecific->realGridSizeAlloc,
298                             newRealGridSize, pmeGpu->archSpecific->pmeStream, true);
299     }
300     else
301     {
302         /* A single buffer so that any grid will fit */
303         const int newGridsSize = std::max(newRealGridSize, newComplexGridSize);
304         cu_realloc_buffered((void **)&kernelParamsPtr->grid.d_realGrid, nullptr, sizeof(float),
305                             &pmeGpu->archSpecific->realGridSize, &pmeGpu->archSpecific->realGridSizeAlloc,
306                             newGridsSize, pmeGpu->archSpecific->pmeStream, true);
307         kernelParamsPtr->grid.d_fourierGrid   = kernelParamsPtr->grid.d_realGrid;
308         pmeGpu->archSpecific->complexGridSize = pmeGpu->archSpecific->realGridSize;
309         // the size might get used later for copying the grid
310     }
311 }
312
313 void pme_gpu_free_grids(const PmeGpu *pmeGpu)
314 {
315     if (pmeGpu->archSpecific->performOutOfPlaceFFT)
316     {
317         freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_fourierGrid);
318     }
319     freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_realGrid);
320 }
321
322 void pme_gpu_clear_grids(const PmeGpu *pmeGpu)
323 {
324     cudaError_t stat = cudaMemsetAsync(pmeGpu->kernelParams->grid.d_realGrid, 0,
325                                        pmeGpu->archSpecific->realGridSize * sizeof(float), pmeGpu->archSpecific->pmeStream);
326     /* Should the complex grid be cleared in some weird case? */
327     CU_RET_ERR(stat, "cudaMemsetAsync on the PME grid error");
328 }
329
330 void pme_gpu_realloc_and_copy_fract_shifts(PmeGpu *pmeGpu)
331 {
332     pme_gpu_free_fract_shifts(pmeGpu);
333
334     auto        *kernelParamsPtr = pmeGpu->kernelParams.get();
335
336     const int    nx                  = kernelParamsPtr->grid.realGridSize[XX];
337     const int    ny                  = kernelParamsPtr->grid.realGridSize[YY];
338     const int    nz                  = kernelParamsPtr->grid.realGridSize[ZZ];
339     const int    cellCount           = c_pmeNeighborUnitcellCount;
340     const int    gridDataOffset[DIM] = {0, cellCount * nx, cellCount * (nx + ny)};
341
342     memcpy(kernelParamsPtr->grid.tablesOffsets, &gridDataOffset, sizeof(gridDataOffset));
343
344     const int    newFractShiftsSize  = cellCount * (nx + ny + nz);
345
346     initParamLookupTable(kernelParamsPtr->grid.d_fractShiftsTable,
347                          kernelParamsPtr->fractShiftsTableTexture,
348                          pmeGpu->common->fsh.data(),
349                          newFractShiftsSize,
350                          pmeGpu->deviceInfo);
351
352     initParamLookupTable(kernelParamsPtr->grid.d_gridlineIndicesTable,
353                          kernelParamsPtr->gridlineIndicesTableTexture,
354                          pmeGpu->common->nn.data(),
355                          newFractShiftsSize,
356                          pmeGpu->deviceInfo);
357 }
358
359 void pme_gpu_free_fract_shifts(const PmeGpu *pmeGpu)
360 {
361     auto *kernelParamsPtr = pmeGpu->kernelParams.get();
362     destroyParamLookupTable(kernelParamsPtr->grid.d_fractShiftsTable,
363                             kernelParamsPtr->fractShiftsTableTexture,
364                             pmeGpu->deviceInfo);
365     destroyParamLookupTable(kernelParamsPtr->grid.d_gridlineIndicesTable,
366                             kernelParamsPtr->gridlineIndicesTableTexture,
367                             pmeGpu->deviceInfo);
368 }
369
370 bool pme_gpu_stream_query(const PmeGpu *pmeGpu)
371 {
372     return haveStreamTasksCompleted(pmeGpu->archSpecific->pmeStream);
373 }
374
375 void pme_gpu_copy_input_gather_grid(const PmeGpu *pmeGpu, float *h_grid)
376 {
377     const size_t gridSize = pmeGpu->archSpecific->realGridSize * sizeof(float);
378     cu_copy_H2D(pmeGpu->kernelParams->grid.d_realGrid, h_grid, gridSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
379 }
380
381 void pme_gpu_copy_output_spread_grid(const PmeGpu *pmeGpu, float *h_grid)
382 {
383     const size_t gridSize = pmeGpu->archSpecific->realGridSize * sizeof(float);
384     cu_copy_D2H(h_grid, pmeGpu->kernelParams->grid.d_realGrid, gridSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
385     cudaError_t  stat = cudaEventRecord(pmeGpu->archSpecific->syncSpreadGridD2H, pmeGpu->archSpecific->pmeStream);
386     CU_RET_ERR(stat, "PME spread grid sync event record failure");
387 }
388
389 void pme_gpu_copy_output_spread_atom_data(const PmeGpu *pmeGpu)
390 {
391     const int    alignment       = pme_gpu_get_atoms_per_warp(pmeGpu);
392     const size_t nAtomsPadded    = ((pmeGpu->nAtomsAlloc + alignment - 1) / alignment) * alignment;
393     const size_t splinesSize     = DIM * nAtomsPadded * pmeGpu->common->pme_order * sizeof(float);
394     auto        *kernelParamsPtr = pmeGpu->kernelParams.get();
395     cu_copy_D2H(pmeGpu->staging.h_dtheta, kernelParamsPtr->atoms.d_dtheta, splinesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
396     cu_copy_D2H(pmeGpu->staging.h_theta, kernelParamsPtr->atoms.d_theta, splinesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
397     cu_copy_D2H(pmeGpu->staging.h_gridlineIndices, kernelParamsPtr->atoms.d_gridlineIndices,
398                 kernelParamsPtr->atoms.nAtoms * DIM * sizeof(int), pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
399 }
400
401 void pme_gpu_copy_input_gather_atom_data(const PmeGpu *pmeGpu)
402 {
403     const int    alignment       = pme_gpu_get_atoms_per_warp(pmeGpu);
404     const size_t nAtomsPadded    = ((pmeGpu->nAtomsAlloc + alignment - 1) / alignment) * alignment;
405     const size_t splinesSize     = DIM * nAtomsPadded * pmeGpu->common->pme_order * sizeof(float);
406     auto        *kernelParamsPtr = pmeGpu->kernelParams.get();
407     if (c_usePadding)
408     {
409         const size_t gridlineIndicesSizePerAtom = DIM * sizeof(int);
410         const size_t splineDataSizePerAtom      = pmeGpu->common->pme_order * DIM * sizeof(float);
411         // TODO: could clear only the padding and not the whole thing, but this is a test-exclusive code anyway
412         CU_RET_ERR(cudaMemsetAsync(kernelParamsPtr->atoms.d_gridlineIndices, 0, pmeGpu->nAtomsAlloc * gridlineIndicesSizePerAtom, pmeGpu->archSpecific->pmeStream),
413                    "PME failed to clear the gridline indices");
414         CU_RET_ERR(cudaMemsetAsync(kernelParamsPtr->atoms.d_dtheta, 0, pmeGpu->nAtomsAlloc * splineDataSizePerAtom, pmeGpu->archSpecific->pmeStream),
415                    "PME failed to clear the spline derivatives");
416         CU_RET_ERR(cudaMemsetAsync(kernelParamsPtr->atoms.d_theta, 0, pmeGpu->nAtomsAlloc * splineDataSizePerAtom, pmeGpu->archSpecific->pmeStream),
417                    "PME failed to clear the spline values");
418     }
419     cu_copy_H2D(kernelParamsPtr->atoms.d_dtheta, pmeGpu->staging.h_dtheta, splinesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
420     cu_copy_H2D(kernelParamsPtr->atoms.d_theta, pmeGpu->staging.h_theta, splinesSize, pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
421     cu_copy_H2D(kernelParamsPtr->atoms.d_gridlineIndices, pmeGpu->staging.h_gridlineIndices,
422                 kernelParamsPtr->atoms.nAtoms * DIM * sizeof(int), pmeGpu->settings.transferKind, pmeGpu->archSpecific->pmeStream);
423 }
424
425 void pme_gpu_sync_spread_grid(const PmeGpu *pmeGpu)
426 {
427     cudaError_t stat = cudaEventSynchronize(pmeGpu->archSpecific->syncSpreadGridD2H);
428     CU_RET_ERR(stat, "Error while waiting for the PME GPU spread grid to be copied to the host");
429 }
430
431 void pme_gpu_init_internal(PmeGpu *pmeGpu)
432 {
433     /* Allocate the target-specific structures */
434     pmeGpu->archSpecific.reset(new PmeGpuSpecific());
435     pmeGpu->kernelParams.reset(new PmeGpuKernelParams());
436
437     pmeGpu->archSpecific->performOutOfPlaceFFT = true;
438     /* This should give better performance, according to the cuFFT documentation.
439      * The performance seems to be the same though.
440      * TODO: PME could also try to pick up nice grid sizes (with factors of 2, 3, 5, 7).
441      */
442
443     /* WARNING: CUDA timings are incorrect with multiple streams.
444      *          This is the main reason why they are disabled by default.
445      */
446     // TODO: Consider turning on by default when we can detect nr of streams.
447     pmeGpu->archSpecific->useTiming = (getenv("GMX_ENABLE_GPU_TIMING") != nullptr);
448
449     pmeGpu->maxGridWidthX = pmeGpu->deviceInfo->prop.maxGridSize[0];
450
451     /* Creating a PME CUDA stream */
452     cudaError_t stat;
453     int         highest_priority, lowest_priority;
454     stat = cudaDeviceGetStreamPriorityRange(&lowest_priority, &highest_priority);
455     CU_RET_ERR(stat, "PME cudaDeviceGetStreamPriorityRange failed");
456     stat = cudaStreamCreateWithPriority(&pmeGpu->archSpecific->pmeStream,
457                                         cudaStreamDefault, //cudaStreamNonBlocking,
458                                         highest_priority);
459     CU_RET_ERR(stat, "cudaStreamCreateWithPriority on the PME stream failed");
460 }
461
462 void pme_gpu_destroy_specific(const PmeGpu *pmeGpu)
463 {
464     /* Destroy the CUDA stream */
465     cudaError_t stat = cudaStreamDestroy(pmeGpu->archSpecific->pmeStream);
466     CU_RET_ERR(stat, "PME cudaStreamDestroy error");
467 }
468
469 void pme_gpu_init_sync_events(const PmeGpu *pmeGpu)
470 {
471     const auto  eventFlags = cudaEventDisableTiming;
472     CU_RET_ERR(cudaEventCreateWithFlags(&pmeGpu->archSpecific->syncSpreadGridD2H, eventFlags), "cudaEventCreate on syncSpreadGridD2H failed");
473 }
474
475 void pme_gpu_destroy_sync_events(const PmeGpu *pmeGpu)
476 {
477     CU_RET_ERR(cudaEventDestroy(pmeGpu->archSpecific->syncSpreadGridD2H), "cudaEventDestroy failed on syncSpreadGridD2H");
478 }
479
480 void pme_gpu_reinit_3dfft(const PmeGpu *pmeGpu)
481 {
482     if (pme_gpu_performs_FFT(pmeGpu))
483     {
484         pmeGpu->archSpecific->fftSetup.resize(0);
485         for (int i = 0; i < pmeGpu->common->ngrids; i++)
486         {
487             pmeGpu->archSpecific->fftSetup.push_back(std::unique_ptr<GpuParallel3dFft>(new GpuParallel3dFft(pmeGpu)));
488         }
489     }
490 }
491
492 void pme_gpu_destroy_3dfft(const PmeGpu *pmeGpu)
493 {
494     pmeGpu->archSpecific->fftSetup.resize(0);
495 }