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