Fix random doxygen warnings and typos
[alexxy/gromacs.git] / src / gromacs / gpu_utils / devicebuffer_ocl.h
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_OCL_H
36 #define GMX_GPU_UTILS_DEVICEBUFFER_OCL_H
37
38 /*! \libinternal \file
39  *  \brief Implements the DeviceBuffer type and routines for OpenCL.
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/device_stream.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_ocl.h"
53 #include "gromacs/gpu_utils/oclutils.h"
54 #include "gromacs/utility/gmxassert.h"
55 #include "gromacs/utility/stringutil.h"
56
57 /*! \libinternal \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 device context-to-be.
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     void*  hostPtr = nullptr;
71     cl_int clError;
72     *buffer = clCreateBuffer(deviceContext.context(), CL_MEM_READ_WRITE,
73                              numValues * sizeof(ValueType), hostPtr, &clError);
74     GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
75                        gmx::formatString("clCreateBuffer failure (OpenCL error %d: %s)", clError,
76                                          ocl_get_error_string(clError).c_str())
77                                .c_str());
78 }
79
80 /*! \brief
81  * Frees a device-side buffer.
82  * This does not reset separately stored size/capacity integers,
83  * as this is planned to be a destructor of DeviceBuffer as a proper class,
84  * and no calls on \p buffer should be made afterwards.
85  *
86  * \param[in] buffer  Pointer to the buffer to free.
87  */
88 template<typename DeviceBuffer>
89 void freeDeviceBuffer(DeviceBuffer* buffer)
90 {
91     GMX_ASSERT(buffer, "needs a buffer pointer");
92     if (*buffer)
93     {
94         cl_int clError = clReleaseMemObject(*buffer);
95         GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
96                            gmx::formatString("clReleaseMemObject failed (OpenCL error %d: %s)",
97                                              clError, ocl_get_error_string(clError).c_str())
98                                    .c_str());
99     }
100 }
101
102 /*! \brief
103  * Performs the host-to-device data copy, synchronous or asynchronously on request.
104  *
105  * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
106  * because of the early return.
107  *
108  * \tparam        ValueType            Raw value type of the \p buffer.
109  * \param[in,out] buffer               Pointer to the device-side buffer
110  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
111  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
112  * \param[in]     numValues            Number of values to copy.
113  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
114  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
115  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
116  *                                     If the pointer is not null, the event can further be used
117  *                                     to queue a wait for this operation or to query profiling information.
118  */
119 template<typename ValueType>
120 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
121                         const ValueType*         hostBuffer,
122                         size_t                   startingOffset,
123                         size_t                   numValues,
124                         const DeviceStream&      deviceStream,
125                         GpuApiCallBehavior       transferKind,
126                         CommandEvent*            timingEvent)
127 {
128     if (numValues == 0)
129     {
130         return; // such calls are actually made with empty domains
131     }
132     GMX_ASSERT(buffer, "needs a buffer pointer");
133     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
134     cl_int       clError;
135     const size_t offset = startingOffset * sizeof(ValueType);
136     const size_t bytes  = numValues * sizeof(ValueType);
137     switch (transferKind)
138     {
139         case GpuApiCallBehavior::Async:
140             clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes,
141                                            hostBuffer, 0, nullptr, timingEvent);
142             GMX_RELEASE_ASSERT(
143                     clError == CL_SUCCESS,
144                     gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)", clError,
145                                       ocl_get_error_string(clError).c_str())
146                             .c_str());
147             break;
148
149         case GpuApiCallBehavior::Sync:
150             clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes,
151                                            hostBuffer, 0, nullptr, timingEvent);
152             GMX_RELEASE_ASSERT(
153                     clError == CL_SUCCESS,
154                     gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)", clError,
155                                       ocl_get_error_string(clError).c_str())
156                             .c_str());
157             break;
158
159         default: throw;
160     }
161 }
162
163 /*! \brief
164  * Performs the device-to-host data copy, synchronous or asynchronously on request.
165  *
166  * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
167  * because of the early return.
168  *
169  * \tparam        ValueType            Raw value type of the \p buffer.
170  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
171  * \param[in]     buffer               Pointer to the device-side buffer
172  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
173  * \param[in]     numValues            Number of values to copy.
174  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
175  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
176  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
177  *                                     If the pointer is not null, the event can further be used
178  *                                     to queue a wait for this operation or to query profiling information.
179  */
180 template<typename ValueType>
181 void copyFromDeviceBuffer(ValueType*               hostBuffer,
182                           DeviceBuffer<ValueType>* buffer,
183                           size_t                   startingOffset,
184                           size_t                   numValues,
185                           const DeviceStream&      deviceStream,
186                           GpuApiCallBehavior       transferKind,
187                           CommandEvent*            timingEvent)
188 {
189     if (numValues == 0)
190     {
191         return;
192     }
193     GMX_ASSERT(buffer, "needs a buffer pointer");
194     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
195     cl_int       clError;
196     const size_t offset = startingOffset * sizeof(ValueType);
197     const size_t bytes  = numValues * sizeof(ValueType);
198     switch (transferKind)
199     {
200         case GpuApiCallBehavior::Async:
201             clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes,
202                                           hostBuffer, 0, nullptr, timingEvent);
203             GMX_RELEASE_ASSERT(
204                     clError == CL_SUCCESS,
205                     gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)", clError,
206                                       ocl_get_error_string(clError).c_str())
207                             .c_str());
208             break;
209
210         case GpuApiCallBehavior::Sync:
211             clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes,
212                                           hostBuffer, 0, nullptr, timingEvent);
213             GMX_RELEASE_ASSERT(
214                     clError == CL_SUCCESS,
215                     gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)", clError,
216                                       ocl_get_error_string(clError).c_str())
217                             .c_str());
218             break;
219
220         default: throw;
221     }
222 }
223
224 /*! \brief
225  * Clears the device buffer asynchronously.
226  *
227  * \tparam        ValueType       Raw value type of the \p buffer.
228  * \param[in,out] buffer          Pointer to the device-side buffer
229  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
230  * \param[in]     numValues       Number of values to clear.
231  * \param[in]     deviceStream    GPU stream.
232  */
233 template<typename ValueType>
234 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
235                             size_t                   startingOffset,
236                             size_t                   numValues,
237                             const DeviceStream&      deviceStream)
238 {
239     GMX_ASSERT(buffer, "needs a buffer pointer");
240     const size_t    offset        = startingOffset * sizeof(ValueType);
241     const size_t    bytes         = numValues * sizeof(ValueType);
242     const int       pattern       = 0;
243     const cl_uint   numWaitEvents = 0;
244     const cl_event* waitEvents    = nullptr;
245     cl_event        commandEvent;
246     cl_int clError = clEnqueueFillBuffer(deviceStream.stream(), *buffer, &pattern, sizeof(pattern),
247                                          offset, bytes, numWaitEvents, waitEvents, &commandEvent);
248     GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
249                        gmx::formatString("Couldn't clear the device buffer (OpenCL error %d: %s)",
250                                          clError, ocl_get_error_string(clError).c_str())
251                                .c_str());
252 }
253
254 #if defined(__clang__)
255 #    pragma clang diagnostic push
256 #    pragma clang diagnostic ignored "-Wunused-template"
257 #endif
258
259 /*! \brief Check the validity of the device buffer.
260  *
261  * Checks if the buffer is not nullptr and if its allocation is big enough.
262  *
263  * \param[in] buffer        Device buffer to be checked.
264  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
265  *
266  * \returns Whether the device buffer can be set.
267  */
268 template<typename T>
269 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
270 {
271     const size_t requiredSizeBytes = requiredSize * sizeof(T);
272     size_t       sizeBytes;
273     cl_int retval = clGetMemObjectInfo(buffer, CL_MEM_SIZE, sizeof(sizeBytes), &sizeBytes, nullptr);
274     GMX_ASSERT(retval == CL_SUCCESS,
275                gmx::formatString("clGetMemObjectInfo failed with error code #%d", retval).c_str());
276     GMX_ASSERT(sizeBytes >= requiredSizeBytes,
277                "Number of atoms in device buffer is smaller then required size.");
278     return retval == CL_SUCCESS && sizeBytes >= requiredSizeBytes;
279 }
280
281 //! Device texture wrapper.
282 using DeviceTexture = void*;
283
284 /*! \brief Create a texture object for an array of type ValueType.
285  *
286  * Creates the device buffer and copies read-only data for an array of type ValueType.
287  *
288  * \todo Decide if using image2d is most efficient.
289  *
290  * \tparam      ValueType      Raw data type.
291  *
292  * \param[out]  deviceBuffer   Device buffer to store data in.
293  * \param[in]   hostBuffer     Host buffer to get date from.
294  * \param[in]   numValues      Number of elements in the buffer.
295  * \param[in]   deviceContext  GPU device context.
296  */
297 template<typename ValueType>
298 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
299                           DeviceTexture* /* deviceTexture */,
300                           const ValueType*     hostBuffer,
301                           int                  numValues,
302                           const DeviceContext& deviceContext)
303 {
304     GMX_ASSERT(hostBuffer, "Host buffer pointer can not be null");
305     const size_t bytes = numValues * sizeof(ValueType);
306     cl_int       clError;
307     *deviceBuffer = clCreateBuffer(deviceContext.context(),
308                                    CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,
309                                    bytes, const_cast<ValueType*>(hostBuffer), &clError);
310
311     GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
312                        gmx::formatString("Constant memory allocation failed (OpenCL error %d: %s)",
313                                          clError, ocl_get_error_string(clError).c_str())
314                                .c_str());
315 }
316
317 /*! \brief Release the OpenCL device buffer.
318  *
319  * \tparam        ValueType     Raw data type.
320  *
321  * \param[in,out] deviceBuffer  Device buffer to store data in.
322  */
323 template<typename ValueType>
324 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture*/)
325 {
326     freeDeviceBuffer(deviceBuffer);
327 }
328 #if defined(__clang__)
329 #    pragma clang diagnostic pop
330 #endif
331
332 #endif