Make DeviceContext into a proper class
[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/device_context.h"
49 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
50 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
51 #include "gromacs/gpu_utils/gputraits.cuh"
52 #include "gromacs/utility/gmxassert.h"
53
54 /*! \brief
55  * Allocates a device-side buffer.
56  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
57  *
58  * \tparam        ValueType            Raw value type of the \p buffer.
59  * \param[in,out] buffer               Pointer to the device-side buffer.
60  * \param[in]     numValues            Number of values to accomodate.
61  * \param[in]     deviceContext        The buffer's dummy device  context - not managed explicitly in CUDA RT.
62  */
63 template<typename ValueType>
64 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& /* deviceContext */)
65 {
66     GMX_ASSERT(buffer, "needs a buffer pointer");
67     cudaError_t stat = cudaMalloc((void**)buffer, numValues * sizeof(ValueType));
68     GMX_RELEASE_ASSERT(stat == cudaSuccess, "cudaMalloc failure");
69 }
70
71 /*! \brief
72  * Frees a device-side buffer.
73  * This does not reset separately stored size/capacity integers,
74  * as this is planned to be a destructor of DeviceBuffer as a proper class,
75  * and no calls on \p buffer should be made afterwards.
76  *
77  * \param[in] buffer  Pointer to the buffer to free.
78  */
79 template<typename DeviceBuffer>
80 void freeDeviceBuffer(DeviceBuffer* buffer)
81 {
82     GMX_ASSERT(buffer, "needs a buffer pointer");
83     if (*buffer)
84     {
85         GMX_RELEASE_ASSERT(cudaFree(*buffer) == cudaSuccess, "cudaFree failed");
86     }
87 }
88
89 /*! \brief
90  * Performs the host-to-device data copy, synchronous or asynchronously on request.
91  *
92  * TODO: This is meant to gradually replace cu/ocl_copy_h2d.
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]     stream               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                         CommandStream            stream,
110                         GpuApiCallBehavior       transferKind,
111                         CommandEvent* /*timingEvent*/)
112 {
113     if (numValues == 0)
114     {
115         return; // such calls are actually made with empty domains
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, 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
143 /*! \brief
144  * Performs the device-to-host data copy, synchronous or asynchronously on request.
145  *
146  * TODO: This is meant to gradually replace cu/ocl_copy_d2h.
147  *
148  * \tparam        ValueType            Raw value type of the \p buffer.
149  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
150  * \param[in]     buffer               Pointer to the device-side buffer
151  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
152  * \param[in]     numValues            Number of values to copy.
153  * \param[in]     stream               GPU stream to perform asynchronous copy in.
154  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
155  * \param[out]    timingEvent          A dummy pointer to the H2D copy timing event to be filled in.
156  *                                     Not used in CUDA implementation.
157  */
158 template<typename ValueType>
159 void copyFromDeviceBuffer(ValueType*               hostBuffer,
160                           DeviceBuffer<ValueType>* buffer,
161                           size_t                   startingOffset,
162                           size_t                   numValues,
163                           CommandStream            stream,
164                           GpuApiCallBehavior       transferKind,
165                           CommandEvent* /*timingEvent*/)
166 {
167     GMX_ASSERT(buffer, "needs a buffer pointer");
168     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
169
170     cudaError_t  stat;
171     const size_t bytes = numValues * sizeof(ValueType);
172     switch (transferKind)
173     {
174         case GpuApiCallBehavior::Async:
175             GMX_ASSERT(isHostMemoryPinned(hostBuffer),
176                        "Destination host buffer was not pinned for CUDA");
177             stat = cudaMemcpyAsync(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes,
178                                    cudaMemcpyDeviceToHost, stream);
179             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Asynchronous D2H copy failed");
180             break;
181
182         case GpuApiCallBehavior::Sync:
183             stat = cudaMemcpy(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes,
184                               cudaMemcpyDeviceToHost);
185             GMX_RELEASE_ASSERT(stat == cudaSuccess, "Synchronous D2H copy failed");
186             break;
187
188         default: throw;
189     }
190 }
191
192 /*! \brief
193  * Clears the device buffer asynchronously.
194  *
195  * \tparam        ValueType       Raw value type of the \p buffer.
196  * \param[in,out] buffer          Pointer to the device-side buffer
197  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
198  * \param[in]     numValues       Number of values to clear.
199  * \param[in]     stream          GPU stream.
200  */
201 template<typename ValueType>
202 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer, size_t startingOffset, size_t numValues, CommandStream stream)
203 {
204     GMX_ASSERT(buffer, "needs a buffer pointer");
205     const size_t bytes   = numValues * sizeof(ValueType);
206     const char   pattern = 0;
207
208     cudaError_t stat = cudaMemsetAsync(*((ValueType**)buffer) + startingOffset, pattern, bytes, stream);
209     GMX_RELEASE_ASSERT(stat == cudaSuccess, "Couldn't clear the device buffer");
210 }
211
212 /*! \brief Check the validity of the device buffer.
213  *
214  * Checks if the buffer is not nullptr.
215  *
216  * \todo Add checks on the buffer size when it will be possible.
217  *
218  * \param[in] buffer        Device buffer to be checked.
219  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
220  *
221  * \returns Whether the device buffer can be set.
222  */
223 template<typename T>
224 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, gmx_unused int requiredSize)
225 {
226     GMX_ASSERT(buffer != nullptr, "The device pointer is nullptr");
227     return buffer != nullptr;
228 }
229
230 #endif