2 * This file is part of the GROMACS molecular simulation package.
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.
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(
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)",
77 ocl_get_error_string(clError).c_str())
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.
87 * \param[in] buffer Pointer to the buffer to free.
89 template<typename DeviceBuffer>
90 void freeDeviceBuffer(DeviceBuffer* buffer)
92 GMX_ASSERT(buffer, "needs a buffer pointer");
95 cl_int clError = clReleaseMemObject(*buffer);
96 GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
97 gmx::formatString("clReleaseMemObject failed (OpenCL error %d: %s)",
99 ocl_get_error_string(clError).c_str())
105 * Performs the host-to-device data copy, synchronous or asynchronously on request.
107 * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
108 * because of the early return.
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.
121 template<typename ValueType>
122 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
123 const ValueType* hostBuffer,
124 size_t startingOffset,
126 const DeviceStream& deviceStream,
127 GpuApiCallBehavior transferKind,
128 CommandEvent* timingEvent)
132 return; // such calls are actually made with empty domains
134 GMX_ASSERT(buffer, "needs a buffer pointer");
135 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
137 const size_t offset = startingOffset * sizeof(ValueType);
138 const size_t bytes = numValues * sizeof(ValueType);
139 switch (transferKind)
141 case GpuApiCallBehavior::Async:
142 clError = clEnqueueWriteBuffer(
143 deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, hostBuffer, 0, nullptr, timingEvent);
145 clError == CL_SUCCESS,
146 gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)",
148 ocl_get_error_string(clError).c_str())
152 case GpuApiCallBehavior::Sync:
153 clError = clEnqueueWriteBuffer(
154 deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, hostBuffer, 0, nullptr, timingEvent);
156 clError == CL_SUCCESS,
157 gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)",
159 ocl_get_error_string(clError).c_str())
168 * Performs the device-to-host data copy, synchronous or asynchronously on request.
170 * Note that synchronous copy will not synchronize the stream in case of zero \p numValues
171 * because of the early return.
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.
184 template<typename ValueType>
185 void copyFromDeviceBuffer(ValueType* hostBuffer,
186 DeviceBuffer<ValueType>* buffer,
187 size_t startingOffset,
189 const DeviceStream& deviceStream,
190 GpuApiCallBehavior transferKind,
191 CommandEvent* timingEvent)
197 GMX_ASSERT(buffer, "needs a buffer pointer");
198 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
200 const size_t offset = startingOffset * sizeof(ValueType);
201 const size_t bytes = numValues * sizeof(ValueType);
202 switch (transferKind)
204 case GpuApiCallBehavior::Async:
205 clError = clEnqueueReadBuffer(
206 deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, hostBuffer, 0, nullptr, timingEvent);
208 clError == CL_SUCCESS,
209 gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)",
211 ocl_get_error_string(clError).c_str())
215 case GpuApiCallBehavior::Sync:
216 clError = clEnqueueReadBuffer(
217 deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, hostBuffer, 0, nullptr, timingEvent);
219 clError == CL_SUCCESS,
220 gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)",
222 ocl_get_error_string(clError).c_str())
231 * Performs the device-to-device data copy, synchronous or asynchronously on request.
233 * \tparam ValueType Raw value type of the \p buffer.
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*/)
244 gmx_fatal(FARGS, "D2D copy stub was called. Not yet implemented in OpenCL.");
248 * Clears the device buffer asynchronously.
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.
256 template<typename ValueType>
257 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
258 size_t startingOffset,
260 const DeviceStream& deviceStream)
262 GMX_ASSERT(buffer, "needs a buffer pointer");
263 const size_t offset = startingOffset * sizeof(ValueType);
264 const size_t bytes = numValues * sizeof(ValueType);
265 const int pattern = 0;
266 const cl_uint numWaitEvents = 0;
267 const cl_event* waitEvents = nullptr;
268 cl_event commandEvent;
269 cl_int clError = clEnqueueFillBuffer(
270 deviceStream.stream(), *buffer, &pattern, sizeof(pattern), offset, bytes, numWaitEvents, waitEvents, &commandEvent);
271 GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
272 gmx::formatString("Couldn't clear the device buffer (OpenCL error %d: %s)",
274 ocl_get_error_string(clError).c_str())
278 #if defined(__clang__)
279 # pragma clang diagnostic push
280 # pragma clang diagnostic ignored "-Wunused-template"
283 /*! \brief Check the validity of the device buffer.
285 * Checks if the buffer is not nullptr and if its allocation is big enough.
287 * \param[in] buffer Device buffer to be checked.
288 * \param[in] requiredSize Number of elements that the buffer will have to accommodate.
290 * \returns Whether the device buffer can be set.
293 static bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
295 const size_t requiredSizeBytes = requiredSize * sizeof(T);
297 cl_int retval = clGetMemObjectInfo(buffer, CL_MEM_SIZE, sizeof(sizeBytes), &sizeBytes, nullptr);
298 GMX_ASSERT(retval == CL_SUCCESS,
299 gmx::formatString("clGetMemObjectInfo failed with error code #%d", retval).c_str());
300 GMX_ASSERT(sizeBytes >= requiredSizeBytes,
301 "Number of atoms in device buffer is smaller then required size.");
302 return retval == CL_SUCCESS && sizeBytes >= requiredSizeBytes;
305 //! Device texture wrapper.
306 using DeviceTexture = void*;
308 /*! \brief Create a texture object for an array of type ValueType.
310 * Creates the device buffer and copies read-only data for an array of type ValueType.
312 * \todo Decide if using image2d is most efficient.
314 * \tparam ValueType Raw data type.
316 * \param[out] deviceBuffer Device buffer to store data in.
317 * \param[in] hostBuffer Host buffer to get date from.
318 * \param[in] numValues Number of elements in the buffer.
319 * \param[in] deviceContext GPU device context.
321 template<typename ValueType>
322 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
323 DeviceTexture* /* deviceTexture */,
324 const ValueType* hostBuffer,
326 const DeviceContext& deviceContext)
328 GMX_ASSERT(hostBuffer, "Host buffer pointer can not be null");
329 const size_t bytes = numValues * sizeof(ValueType);
331 *deviceBuffer = clCreateBuffer(deviceContext.context(),
332 CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,
334 const_cast<ValueType*>(hostBuffer),
337 GMX_RELEASE_ASSERT(clError == CL_SUCCESS,
338 gmx::formatString("Constant memory allocation failed (OpenCL error %d: %s)",
340 ocl_get_error_string(clError).c_str())
344 /*! \brief Release the OpenCL device buffer.
346 * \tparam ValueType Raw data type.
348 * \param[in,out] deviceBuffer Device buffer to store data in.
350 template<typename ValueType>
351 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, const DeviceTexture& /* deviceTexture*/)
353 freeDeviceBuffer(deviceBuffer);
355 #if defined(__clang__)
356 # pragma clang diagnostic pop