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