2c92c81c1be361d2cbdee1f282bbe108d7d792e0
[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/devicebuffer_datatype.h"
49 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
50 #include "gromacs/gpu_utils/gputraits_ocl.h"
51 #include "gromacs/gpu_utils/oclutils.h"
52 #include "gromacs/utility/gmxassert.h"
53 #include "gromacs/utility/stringutil.h"
54
55 /*! \libinternal \brief
56  * Allocates a device-side buffer.
57  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
58  *
59  * \tparam        ValueType            Raw value type of the \p buffer.
60  * \param[in,out] buffer               Pointer to the device-side buffer.
61  * \param[in]     numValues            Number of values to accomodate.
62  * \param[in]     deviceContext        The buffer's device context-to-be.
63  */
64 template<typename ValueType>
65 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, DeviceContext deviceContext)
66 {
67     GMX_ASSERT(buffer, "needs a buffer pointer");
68     void*  hostPtr = nullptr;
69     cl_int clError;
70     *buffer = clCreateBuffer(deviceContext, CL_MEM_READ_WRITE, numValues * sizeof(ValueType),
71                              hostPtr, &clError);
72     GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
73                        gmx::formatString("clCreateBuffer failure (OpenCL error %d: %s)", clError,
74                                          ocl_get_error_string(clError).c_str())
75                                .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         cl_int clError = clReleaseMemObject(*buffer);
93         GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
94                            gmx::formatString("clReleaseMemObject failed (OpenCL error %d: %s)",
95                                              clError, ocl_get_error_string(clError).c_str())
96                                    .c_str());
97     }
98 }
99
100 /*! \brief
101  * Performs the host-to-device data copy, synchronous or asynchronously on request.
102  *
103  * TODO: This is meant to gradually replace cu/ocl_copy_h2d.
104  *
105  * \tparam        ValueType            Raw value type of the \p buffer.
106  * \param[in,out] buffer               Pointer to the device-side buffer
107  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
108  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
109  * \param[in]     numValues            Number of values to copy.
110  * \param[in]     stream               GPU stream to perform asynchronous copy in.
111  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
112  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
113  *                                     If the pointer is not null, the event can further be used
114  *                                     to queue a wait for this operation or to query profiling information.
115  */
116 template<typename ValueType>
117 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
118                         const ValueType*         hostBuffer,
119                         size_t                   startingOffset,
120                         size_t                   numValues,
121                         CommandStream            stream,
122                         GpuApiCallBehavior       transferKind,
123                         CommandEvent*            timingEvent)
124 {
125     if (numValues == 0)
126     {
127         return; // such calls are actually made with empty domains
128     }
129     GMX_ASSERT(buffer, "needs a buffer pointer");
130     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
131     cl_int       clError;
132     const size_t offset = startingOffset * sizeof(ValueType);
133     const size_t bytes  = numValues * sizeof(ValueType);
134     switch (transferKind)
135     {
136         case GpuApiCallBehavior::Async:
137             clError = clEnqueueWriteBuffer(stream, *buffer, CL_FALSE, offset, bytes, hostBuffer, 0,
138                                            nullptr, timingEvent);
139             GMX_RELEASE_ASSERT(
140                     clError == CL_SUCCESS,
141                     gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)", clError,
142                                       ocl_get_error_string(clError).c_str())
143                             .c_str());
144             break;
145
146         case GpuApiCallBehavior::Sync:
147             clError = clEnqueueWriteBuffer(stream, *buffer, CL_TRUE, offset, bytes, hostBuffer, 0,
148                                            nullptr, timingEvent);
149             GMX_RELEASE_ASSERT(
150                     clError == CL_SUCCESS,
151                     gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)", clError,
152                                       ocl_get_error_string(clError).c_str())
153                             .c_str());
154             break;
155
156         default: throw;
157     }
158 }
159
160 /*! \brief
161  * Performs the device-to-host data copy, synchronous or asynchronously on request.
162  *
163  * TODO: This is meant to gradually replace cu/ocl_copy_d2h.
164  *
165  * \tparam        ValueType            Raw value type of the \p buffer.
166  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
167  * \param[in]     buffer               Pointer to the device-side buffer
168  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
169  * \param[in]     numValues            Number of values to copy.
170  * \param[in]     stream               GPU stream to perform asynchronous copy in.
171  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
172  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
173  *                                     If the pointer is not null, the event can further be used
174  *                                     to queue a wait for this operation or to query profiling information.
175  */
176 template<typename ValueType>
177 void copyFromDeviceBuffer(ValueType*               hostBuffer,
178                           DeviceBuffer<ValueType>* buffer,
179                           size_t                   startingOffset,
180                           size_t                   numValues,
181                           CommandStream            stream,
182                           GpuApiCallBehavior       transferKind,
183                           CommandEvent*            timingEvent)
184 {
185     GMX_ASSERT(buffer, "needs a buffer pointer");
186     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
187     cl_int       clError;
188     const size_t offset = startingOffset * sizeof(ValueType);
189     const size_t bytes  = numValues * sizeof(ValueType);
190     switch (transferKind)
191     {
192         case GpuApiCallBehavior::Async:
193             clError = clEnqueueReadBuffer(stream, *buffer, CL_FALSE, offset, bytes, hostBuffer, 0,
194                                           nullptr, timingEvent);
195             GMX_RELEASE_ASSERT(
196                     clError == CL_SUCCESS,
197                     gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)", clError,
198                                       ocl_get_error_string(clError).c_str())
199                             .c_str());
200             break;
201
202         case GpuApiCallBehavior::Sync:
203             clError = clEnqueueReadBuffer(stream, *buffer, CL_TRUE, offset, bytes, hostBuffer, 0,
204                                           nullptr, timingEvent);
205             GMX_RELEASE_ASSERT(
206                     clError == CL_SUCCESS,
207                     gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)", clError,
208                                       ocl_get_error_string(clError).c_str())
209                             .c_str());
210             break;
211
212         default: throw;
213     }
214 }
215
216 /*! \brief
217  * Clears the device buffer asynchronously.
218  *
219  * \tparam        ValueType       Raw value type of the \p buffer.
220  * \param[in,out] buffer          Pointer to the device-side buffer
221  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
222  * \param[in]     numValues       Number of values to clear.
223  * \param[in]     stream          GPU stream.
224  */
225 template<typename ValueType>
226 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer, size_t startingOffset, size_t numValues, CommandStream stream)
227 {
228     GMX_ASSERT(buffer, "needs a buffer pointer");
229     const size_t    offset        = startingOffset * sizeof(ValueType);
230     const size_t    bytes         = numValues * sizeof(ValueType);
231     const ValueType pattern       = 0;
232     const cl_uint   numWaitEvents = 0;
233     const cl_event* waitEvents    = nullptr;
234     cl_event        commandEvent;
235     cl_int clError = clEnqueueFillBuffer(stream, *buffer, &pattern, sizeof(pattern), offset, bytes,
236                                          numWaitEvents, waitEvents, &commandEvent);
237     GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
238                        gmx::formatString("Couldn't clear the device buffer (OpenCL error %d: %s)",
239                                          clError, ocl_get_error_string(clError).c_str())
240                                .c_str());
241 }
242
243 /*! \brief Check the validity of the device buffer.
244  *
245  * Checks if the buffer is not nullptr and if its allocation is big enough.
246  *
247  * \param[in] buffer        Device buffer to be checked.
248  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
249  *
250  * \returns Whether the device buffer can be set.
251  */
252 template<typename T>
253 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
254 {
255     size_t size;
256     int    retval = clGetMemObjectInfo(buffer, CL_MEM_SIZE, sizeof(size), &size, nullptr);
257     GMX_ASSERT(retval == CL_SUCCESS,
258                gmx::formatString("clGetMemObjectInfo failed with error code #%d", retval).c_str());
259     GMX_ASSERT(static_cast<int>(size) >= requiredSize,
260                "Number of atoms in device buffer is smaller then required size.");
261     return retval == CL_SUCCESS && static_cast<int>(size) >= requiredSize;
262 }
263
264 #endif