2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2014,2015,2016,2017,2018 by the GROMACS development team.
5 * Copyright (c) 2019,2020, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
36 /*! \libinternal \file
37 * \brief Declare utility routines for OpenCL
39 * \author Anca Hamuraru <anca@streamcomputing.eu>
42 #ifndef GMX_GPU_UTILS_OCLUTILS_H
43 #define GMX_GPU_UTILS_OCLUTILS_H
47 #include "gromacs/gpu_utils/device_context.h"
48 #include "gromacs/gpu_utils/gmxopencl.h"
49 #include "gromacs/gpu_utils/gputraits_ocl.h"
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/gmxassert.h"
53 enum class GpuApiCallBehavior;
56 * \brief OpenCL GPU runtime data
58 * The device runtime data is meant to hold objects associated with a GROMACS rank's
59 * (thread or process) use of a single device (multiple devices per rank is not
60 * implemented). These objects should be constructed at ther point where a device
61 * dets assigned to a rank and released at when this assignment is no longer valid
62 * (i.e. at cleanup in the current implementation).
65 struct gmx_device_runtime_data_t
68 DeviceContext deviceContext;
73 /*! \brief Launches synchronous or asynchronous device to host memory copy.
75 * If copy_event is not NULL, on return it will contain an event object
76 * identifying this particular device to host operation. The event can further
77 * be used to queue a wait for this operation or to query profiling information.
79 int ocl_copy_D2H(void* h_dest,
83 GpuApiCallBehavior transferKind,
84 cl_command_queue command_queue,
85 cl_event* copy_event);
88 /*! \brief Launches asynchronous device to host memory copy. */
89 int ocl_copy_D2H_async(void* h_dest,
93 cl_command_queue command_queue,
94 cl_event* copy_event);
96 /*! \brief Launches synchronous or asynchronous host to device memory copy.
98 * If copy_event is not NULL, on return it will contain an event object
99 * identifying this particular host to device operation. The event can further
100 * be used to queue a wait for this operation or to query profiling information.
102 int ocl_copy_H2D(cl_mem d_dest,
106 GpuApiCallBehavior transferKind,
107 cl_command_queue command_queue,
108 cl_event* copy_event);
110 /*! \brief Launches asynchronous host to device memory copy. */
111 int ocl_copy_H2D_async(cl_mem d_dest,
115 cl_command_queue command_queue,
116 cl_event* copy_event);
118 /*! \brief Launches synchronous host to device memory copy. */
119 int ocl_copy_H2D_sync(cl_mem d_dest, const void* h_src, size_t offset, size_t bytes, cl_command_queue command_queue);
121 /*! \brief Allocate host memory in malloc style */
122 void pmalloc(void** h_ptr, size_t nbytes);
124 /*! \brief Free host memory in malloc style */
125 void pfree(void* h_ptr);
127 /*! \brief Convert error code to diagnostic string */
128 std::string ocl_get_error_string(cl_int error);
130 /*! \brief Calls clFinish() in the stream \p s.
132 * \param[in] s stream to synchronize with
134 static inline void gpuStreamSynchronize(cl_command_queue s)
136 cl_int cl_error = clFinish(s);
137 GMX_RELEASE_ASSERT(CL_SUCCESS == cl_error,
138 ("Error caught during clFinish:" + ocl_get_error_string(cl_error)).c_str());
141 //! A debug checker to track cl_events being released correctly
142 inline void ensureReferenceCount(const cl_event& event, unsigned int refCount)
145 cl_int clError = clGetEventInfo(event, CL_EVENT_REFERENCE_COUNT, sizeof(refCount), &refCount, nullptr);
146 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
147 GMX_ASSERT(refCount == refCount, "Unexpected reference count");
149 GMX_UNUSED_VALUE(event);
150 GMX_UNUSED_VALUE(refCount);
154 /*! \brief Pretend to synchronize an OpenCL stream (dummy implementation).
156 * \param[in] s queue to check
158 * \returns True if all tasks enqueued in the stream \p s (at the time of this call) have completed.
160 static inline bool haveStreamTasksCompleted(cl_command_queue gmx_unused s)
162 GMX_RELEASE_ASSERT(false, "haveStreamTasksCompleted is not implemented for OpenCL");
166 /* Kernel launch helpers */
169 * A function for setting up a single OpenCL kernel argument.
170 * This is the tail of the compile-time recursive function below.
171 * It has to be seen by the compiler first.
172 * As NB kernels might be using dynamic local memory as the last argument,
173 * this function also manages that, using sharedMemorySize from \p config.
175 * \param[in] kernel Kernel function handle
176 * \param[in] config Kernel configuration for launching
177 * \param[in] argIndex Index of the current argument
179 void inline prepareGpuKernelArgument(cl_kernel kernel, const KernelLaunchConfig& config, size_t argIndex)
181 if (config.sharedMemorySize > 0)
183 cl_int gmx_used_in_debug clError =
184 clSetKernelArg(kernel, argIndex, config.sharedMemorySize, nullptr);
185 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
190 * Compile-time recursive function for setting up a single OpenCL kernel argument.
191 * This function uses one kernel argument pointer \p argPtr to call clSetKernelArg(),
192 * and calls itself on the next argument, eventually calling the tail function above.
194 * \tparam CurrentArg Type of the current argument
195 * \tparam RemainingArgs Types of remaining arguments after the current one
196 * \param[in] kernel Kernel function handle
197 * \param[in] config Kernel configuration for launching
198 * \param[in] argIndex Index of the current argument
199 * \param[in] argPtr Pointer to the current argument
200 * \param[in] otherArgsPtrs Pack of pointers to arguments remaining to process after the current one
202 template<typename CurrentArg, typename... RemainingArgs>
203 void prepareGpuKernelArgument(cl_kernel kernel,
204 const KernelLaunchConfig& config,
206 const CurrentArg* argPtr,
207 const RemainingArgs*... otherArgsPtrs)
209 cl_int gmx_used_in_debug clError = clSetKernelArg(kernel, argIndex, sizeof(CurrentArg), argPtr);
210 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
212 // Assert on types not allowed to be passed to a kernel
213 // (as per section 6.9 of the OpenCL spec).
214 static_assert(!std::is_same<CurrentArg, bool>::value && !std::is_same<CurrentArg, size_t>::value
215 && !std::is_same<CurrentArg, ptrdiff_t>::value
216 && !std::is_same<CurrentArg, intptr_t>::value
217 && !std::is_same<CurrentArg, uintptr_t>::value,
218 "Invalid type passed to OpenCL kernel functions (see OpenCL spec section 6.9).");
220 prepareGpuKernelArgument(kernel, config, argIndex + 1, otherArgsPtrs...);
224 * A wrapper function for setting up all the OpenCL kernel arguments.
225 * Calls the recursive functions above.
227 * \tparam Args Types of all the kernel arguments
228 * \param[in] kernel Kernel function handle
229 * \param[in] config Kernel configuration for launching
230 * \param[in] argsPtrs Pointers to all the kernel arguments
231 * \returns A handle for the prepared parameter pack to be used with launchGpuKernel() as the last argument
232 * - currently always nullptr for OpenCL, as it manages kernel/arguments association by itself.
234 template<typename... Args>
235 void* prepareGpuKernelArguments(cl_kernel kernel, const KernelLaunchConfig& config, const Args*... argsPtrs)
237 prepareGpuKernelArgument(kernel, config, 0, argsPtrs...);
241 /*! \brief Launches the OpenCL kernel and handles the errors.
243 * \param[in] kernel Kernel function handle
244 * \param[in] config Kernel configuration for launching
245 * \param[in] timingEvent Timing event, fetched from GpuRegionTimer
246 * \param[in] kernelName Human readable kernel description, for error handling only
247 * \throws gmx::InternalError on kernel launch failure
249 inline void launchGpuKernel(cl_kernel kernel,
250 const KernelLaunchConfig& config,
251 CommandEvent* timingEvent,
252 const char* kernelName,
253 const void* /*kernelArgs*/)
255 const int workDimensions = 3;
256 const size_t* globalWorkOffset = nullptr;
257 const size_t waitListSize = 0;
258 const cl_event* waitList = nullptr;
259 size_t globalWorkSize[3];
260 for (int i = 0; i < workDimensions; i++)
262 globalWorkSize[i] = config.gridSize[i] * config.blockSize[i];
264 cl_int clError = clEnqueueNDRangeKernel(config.stream, kernel, workDimensions, globalWorkOffset,
265 globalWorkSize, config.blockSize, waitListSize,
266 waitList, timingEvent);
267 if (CL_SUCCESS != clError)
269 const std::string errorMessage = "GPU kernel (" + std::string(kernelName)
270 + ") failed to launch: " + ocl_get_error_string(clError);
271 GMX_THROW(gmx::InternalError(errorMessage));