Unify CUDA and OpenCL lookup-table creation
[alexxy/gromacs.git] / src / gromacs / gpu_utils / devicebuffer.cuh
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2018,2019,2020, 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 #ifndef GMX_GPU_UTILS_DEVICEBUFFER_CUH
36 #define GMX_GPU_UTILS_DEVICEBUFFER_CUH
37
38 /*! \libinternal \file
39  *  \brief Implements the DeviceBuffer type and routines for CUDA.
40  *  Should only be included directly by the main DeviceBuffer file devicebuffer.h.
41  *  TODO: the intent is for DeviceBuffer to become a class.
42  *
43  *  \author Aleksei Iupinov <a.yupinov@gmail.com>
44  *
45  *  \inlibraryapi
46  */
47
48 #include "gromacs/gpu_utils/cuda_arch_utils.cuh"
49 #include "gromacs/gpu_utils/device_context.h"
50 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
51 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
52 #include "gromacs/gpu_utils/gputraits.cuh"
53 #include "gromacs/utility/gmxassert.h"
54 #include "gromacs/utility/stringutil.h"
55
56 /*! \brief
57  * Allocates a device-side buffer.
58  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
59  *
60  * \tparam        ValueType            Raw value type of the \p buffer.
61  * \param[in,out] buffer               Pointer to the device-side buffer.
62  * \param[in]     numValues            Number of values to accomodate.
63  * \param[in]     deviceContext        The buffer's dummy device  context - not managed explicitly in CUDA RT.
64  */
65 template<typename ValueType>
66 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& /* deviceContext */)
67 {
68     GMX_ASSERT(buffer, "needs a buffer pointer");
69     cudaError_t stat = cudaMalloc((void**)buffer, numValues * sizeof(ValueType));
70     GMX_RELEASE_ASSERT(stat == cudaSuccess, "cudaMalloc failure");
71 }
72
73 /*! \brief
74  * Frees a device-side buffer.
75  * This does not reset separately stored size/capacity integers,
76  * as this is planned to be a destructor of DeviceBuffer as a proper class,
77  * and no calls on \p buffer should be made afterwards.
78  *
79  * \param[in] buffer  Pointer to the buffer to free.
80  */
81 template<typename DeviceBuffer>
82 void freeDeviceBuffer(DeviceBuffer* buffer)
83 {
84     GMX_ASSERT(buffer, "needs a buffer pointer");
85     if (*buffer)
86     {
87         GMX_RELEASE_ASSERT(cudaFree(*buffer) == cudaSuccess, "cudaFree failed");
88     }
89 }
90
91 /*! \brief
92  * Performs the host-to-device data copy, synchronous or asynchronously on request.
93  *
94  * \tparam        ValueType            Raw value type of the \p buffer.
95  * \param[in,out] buffer               Pointer to the device-side buffer
96  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
97  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
98  * \param[in]     numValues            Number of values to copy.
99  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
100  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
101  * \param[out]    timingEvent          A dummy pointer to the H2D copy timing event to be filled in.
102  *                                     Not used in CUDA implementation.
103  */
104 template<typename ValueType>
105 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
106                         const ValueType*         hostBuffer,
107                         size_t                   startingOffset,
108                         size_t                   numValues,
109                         const DeviceStream&      deviceStream,
110                         GpuApiCallBehavior       transferKind,
111                         CommandEvent* /*timingEvent*/)
112 {
113     if (numValues == 0)
114     {
115         return;
116     }
117     GMX_ASSERT(buffer, "needs a buffer pointer");
118     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
119     cudaError_t  stat;
120     const size_t bytes = numValues * sizeof(ValueType);
121
122     switch (transferKind)
123     {
124         case GpuApiCallBehavior::Async:
125             GMX_ASSERT(isHostMemoryPinned(hostBuffer),
126                        "Source host buffer was not pinned for CUDA");
127             stat = cudaMemcpyAsync(*((ValueType**)buffer) + startingOffset, hostBuffer, bytes,
128                                    cudaMemcpyHostToDevice, deviceStream.stream());
129             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Asynchronous H2D copy failed");
130             break;
131
132         case GpuApiCallBehavior::Sync:
133             stat = cudaMemcpy(*((ValueType**)buffer) + startingOffset, hostBuffer, bytes,
134                               cudaMemcpyHostToDevice);
135             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Synchronous H2D copy failed");
136             break;
137
138         default: throw;
139     }
140 }
141
142 /*! \brief
143  * Performs the device-to-host data copy, synchronous or asynchronously on request.
144  *
145  * \tparam        ValueType            Raw value type of the \p buffer.
146  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
147  * \param[in]     buffer               Pointer to the device-side buffer
148  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
149  * \param[in]     numValues            Number of values to copy.
150  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
151  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
152  * \param[out]    timingEvent          A dummy pointer to the H2D copy timing event to be filled in.
153  *                                     Not used in CUDA implementation.
154  */
155 template<typename ValueType>
156 void copyFromDeviceBuffer(ValueType*               hostBuffer,
157                           DeviceBuffer<ValueType>* buffer,
158                           size_t                   startingOffset,
159                           size_t                   numValues,
160                           const DeviceStream&      deviceStream,
161                           GpuApiCallBehavior       transferKind,
162                           CommandEvent* /*timingEvent*/)
163 {
164     if (numValues == 0)
165     {
166         return;
167     }
168     GMX_ASSERT(buffer, "needs a buffer pointer");
169     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
170
171     cudaError_t  stat;
172     const size_t bytes = numValues * sizeof(ValueType);
173     switch (transferKind)
174     {
175         case GpuApiCallBehavior::Async:
176             GMX_ASSERT(isHostMemoryPinned(hostBuffer),
177                        "Destination host buffer was not pinned for CUDA");
178             stat = cudaMemcpyAsync(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes,
179                                    cudaMemcpyDeviceToHost, deviceStream.stream());
180             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Asynchronous D2H copy failed");
181             break;
182
183         case GpuApiCallBehavior::Sync:
184             stat = cudaMemcpy(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes,
185                               cudaMemcpyDeviceToHost);
186             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Synchronous D2H copy failed");
187             break;
188
189         default: throw;
190     }
191 }
192
193 /*! \brief
194  * Clears the device buffer asynchronously.
195  *
196  * \tparam        ValueType       Raw value type of the \p buffer.
197  * \param[in,out] buffer          Pointer to the device-side buffer
198  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
199  * \param[in]     numValues       Number of values to clear.
200  * \param[in]     deviceStream    GPU stream.
201  */
202 template<typename ValueType>
203 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
204                             size_t                   startingOffset,
205                             size_t                   numValues,
206                             const DeviceStream&      deviceStream)
207 {
208     GMX_ASSERT(buffer, "needs a buffer pointer");
209     const size_t bytes   = numValues * sizeof(ValueType);
210     const char   pattern = 0;
211
212     cudaError_t stat = cudaMemsetAsync(*((ValueType**)buffer) + startingOffset, pattern, bytes,
213                                        deviceStream.stream());
214     GMX_RELEASE_ASSERT(stat == cudaSuccess, "Couldn't clear the device buffer");
215 }
216
217 /*! \brief Check the validity of the device buffer.
218  *
219  * Checks if the buffer is not nullptr.
220  *
221  * \todo Add checks on the buffer size when it will be possible.
222  *
223  * \param[in] buffer        Device buffer to be checked.
224  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
225  *
226  * \returns Whether the device buffer can be set.
227  */
228 template<typename T>
229 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, gmx_unused int requiredSize)
230 {
231     GMX_ASSERT(buffer != nullptr, "The device pointer is nullptr");
232     return buffer != nullptr;
233 }
234
235 //! Device texture wrapper.
236 using DeviceTexture = cudaTextureObject_t;
237
238 /*! \brief Create a texture object for an array of type ValueType.
239  *
240  * Creates the device buffer, copies data and binds texture object for an array of type ValueType.
241  *
242  * \todo Test if using textures is still relevant on modern hardware.
243  *
244  * \tparam      ValueType      Raw data type.
245  *
246  * \param[out]  deviceBuffer   Device buffer to store data in.
247  * \param[out]  deviceTexture  Device texture object to initialize.
248  * \param[in]   hostBuffer     Host buffer to get date from
249  * \param[in]   numValues      Number of elements in the buffer.
250  * \param[in]   deviceContext  GPU device context.
251  */
252 template<typename ValueType>
253 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
254                           DeviceTexture*           deviceTexture,
255                           const ValueType*         hostBuffer,
256                           int                      numValues,
257                           const DeviceContext&     deviceContext)
258 {
259     if (numValues == 0)
260     {
261         return;
262     }
263     GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
264
265     allocateDeviceBuffer(deviceBuffer, numValues, deviceContext);
266
267     const size_t sizeInBytes = numValues * sizeof(ValueType);
268
269     cudaError_t stat =
270             cudaMemcpy(*((ValueType**)deviceBuffer), hostBuffer, sizeInBytes, cudaMemcpyHostToDevice);
271
272     GMX_RELEASE_ASSERT(
273             stat == cudaSuccess,
274             gmx::formatString("Synchronous H2D copy failed (CUDA error: %s).", cudaGetErrorName(stat))
275                     .c_str());
276
277     if (!c_disableCudaTextures)
278     {
279         cudaResourceDesc rd;
280         cudaTextureDesc  td;
281
282         memset(&rd, 0, sizeof(rd));
283         rd.resType                = cudaResourceTypeLinear;
284         rd.res.linear.devPtr      = *deviceBuffer;
285         rd.res.linear.desc        = cudaCreateChannelDesc<ValueType>();
286         rd.res.linear.sizeInBytes = sizeInBytes;
287
288         memset(&td, 0, sizeof(td));
289         td.readMode = cudaReadModeElementType;
290         stat        = cudaCreateTextureObject(deviceTexture, &rd, &td, nullptr);
291         GMX_RELEASE_ASSERT(stat == cudaSuccess,
292                            gmx::formatString("cudaCreateTextureObject failed (CUDA error: %s).",
293                                              cudaGetErrorName(stat))
294                                    .c_str());
295     }
296 }
297
298 /*! \brief Unbind the texture and release the CUDA texture object.
299  *
300  * \tparam         ValueType      Raw data type
301  *
302  * \param[in,out]  deviceBuffer   Device buffer to store data in.
303  * \param[in,out]  deviceTexture  Device texture object to unbind.
304  */
305 template<typename ValueType>
306 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& deviceTexture)
307 {
308     if (!c_disableCudaTextures && deviceTexture && deviceBuffer)
309     {
310         cudaError_t stat = cudaDestroyTextureObject(deviceTexture);
311         GMX_RELEASE_ASSERT(
312                 stat == cudaSuccess,
313                 gmx::formatString(
314                         "cudaDestroyTextureObject on texture object failed (CUDA error: %s).",
315                         cudaGetErrorName(stat))
316                         .c_str());
317     }
318     freeDeviceBuffer(deviceBuffer);
319 }
320
321 #endif