2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
35 #ifndef GMX_GPU_UTILS_DEVICEBUFFER_OCL_H
36 #define GMX_GPU_UTILS_DEVICEBUFFER_OCL_H
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.
43 * \author Aleksei Iupinov <a.yupinov@gmail.com>
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"
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.
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.
66 template<typename ValueType>
67 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
69 GMX_ASSERT(buffer, "needs a buffer pointer");
70 void* hostPtr = nullptr;
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())
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.
86 * \param[in] buffer Pointer to the buffer to free.
88 template<typename DeviceBuffer>
89 void freeDeviceBuffer(DeviceBuffer* buffer)
91 GMX_ASSERT(buffer, "needs a buffer pointer");
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())
103 * Performs the host-to-device data copy, synchronous or asynchronously on request.
105 * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
106 * because of the early return.
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.
119 template<typename ValueType>
120 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
121 const ValueType* hostBuffer,
122 size_t startingOffset,
124 const DeviceStream& deviceStream,
125 GpuApiCallBehavior transferKind,
126 CommandEvent* timingEvent)
130 return; // such calls are actually made with empty domains
132 GMX_ASSERT(buffer, "needs a buffer pointer");
133 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
135 const size_t offset = startingOffset * sizeof(ValueType);
136 const size_t bytes = numValues * sizeof(ValueType);
137 switch (transferKind)
139 case GpuApiCallBehavior::Async:
140 clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes,
141 hostBuffer, 0, nullptr, timingEvent);
143 clError == CL_SUCCESS,
144 gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)", clError,
145 ocl_get_error_string(clError).c_str())
149 case GpuApiCallBehavior::Sync:
150 clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes,
151 hostBuffer, 0, nullptr, timingEvent);
153 clError == CL_SUCCESS,
154 gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)", clError,
155 ocl_get_error_string(clError).c_str())
164 * Performs the device-to-host data copy, synchronous or asynchronously on request.
166 * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
167 * because of the early return.
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.
180 template<typename ValueType>
181 void copyFromDeviceBuffer(ValueType* hostBuffer,
182 DeviceBuffer<ValueType>* buffer,
183 size_t startingOffset,
185 const DeviceStream& deviceStream,
186 GpuApiCallBehavior transferKind,
187 CommandEvent* timingEvent)
193 GMX_ASSERT(buffer, "needs a buffer pointer");
194 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
196 const size_t offset = startingOffset * sizeof(ValueType);
197 const size_t bytes = numValues * sizeof(ValueType);
198 switch (transferKind)
200 case GpuApiCallBehavior::Async:
201 clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes,
202 hostBuffer, 0, nullptr, timingEvent);
204 clError == CL_SUCCESS,
205 gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)", clError,
206 ocl_get_error_string(clError).c_str())
210 case GpuApiCallBehavior::Sync:
211 clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes,
212 hostBuffer, 0, nullptr, timingEvent);
214 clError == CL_SUCCESS,
215 gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)", clError,
216 ocl_get_error_string(clError).c_str())
225 * Clears the device buffer asynchronously.
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.
233 template<typename ValueType>
234 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
235 size_t startingOffset,
237 const DeviceStream& deviceStream)
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())
254 #if defined(__clang__)
255 # pragma clang diagnostic push
256 # pragma clang diagnostic ignored "-Wunused-template"
259 /*! \brief Check the validity of the device buffer.
261 * Checks if the buffer is not nullptr and if its allocation is big enough.
263 * \param[in] buffer Device buffer to be checked.
264 * \param[in] requiredSize Number of elements that the buffer will have to accommodate.
266 * \returns Whether the device buffer can be set.
269 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
271 const size_t requiredSizeBytes = requiredSize * sizeof(T);
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;
281 //! Device texture wrapper.
282 using DeviceTexture = void*;
284 /*! \brief Create a texture object for an array of type ValueType.
286 * Creates the device buffer and copies read-only data for an array of type ValueType.
288 * \todo Decide if using image2d is most efficient.
290 * \tparam ValueType Raw data type.
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.
297 template<typename ValueType>
298 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
299 DeviceTexture* /* deviceTexture */,
300 const ValueType* hostBuffer,
302 const DeviceContext& deviceContext)
304 GMX_ASSERT(hostBuffer, "Host buffer pointer can not be null");
305 const size_t bytes = numValues * sizeof(ValueType);
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);
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())
317 /*! \brief Release the OpenCL device buffer.
319 * \tparam ValueType Raw data type.
321 * \param[in,out] deviceBuffer Device buffer to store data in.
323 template<typename ValueType>
324 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture*/)
326 freeDeviceBuffer(deviceBuffer);
328 #if defined(__clang__)
329 # pragma clang diagnostic pop