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