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