f5ec03353b5e3d2bfd5e051946ba7a966789f965
[alexxy/gromacs.git] / src / gromacs / gpu_utils / oclutils.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36 /*! \libinternal \file
37  *  \brief Declare utility routines for OpenCL
38  *
39  *  \author Anca Hamuraru <anca@streamcomputing.eu>
40  *  \inlibraryapi
41  */
42 #ifndef GMX_GPU_UTILS_OCLUTILS_H
43 #define GMX_GPU_UTILS_OCLUTILS_H
44
45 #include <string>
46
47 #include "gromacs/gpu_utils/gmxopencl.h"
48 #include "gromacs/gpu_utils/gputraits_ocl.h"
49 #include "gromacs/utility/exceptions.h"
50 #include "gromacs/utility/gmxassert.h"
51
52 enum class GpuApiCallBehavior;
53
54 /*! \brief OpenCL vendor IDs */
55 typedef enum
56 {
57     OCL_VENDOR_NVIDIA = 0,
58     OCL_VENDOR_AMD,
59     OCL_VENDOR_INTEL,
60     OCL_VENDOR_UNKNOWN
61 } ocl_vendor_id_t;
62
63 /*! \internal
64  * \brief OpenCL GPU device identificator
65  *
66  * An OpenCL device is identified by its ID.
67  * The platform ID is also included for caching reasons.
68  */
69 typedef struct
70 {
71     cl_platform_id ocl_platform_id; /**< Platform ID */
72     cl_device_id   ocl_device_id;   /**< Device ID */
73 } ocl_gpu_id_t;
74
75 /*! \internal
76  * \brief OpenCL device information.
77  *
78  * The OpenCL device information is queried and set at detection and contains
79  * both information about the device/hardware returned by the runtime as well
80  * as additional data like support status.
81  */
82 struct gmx_device_info_t
83 {
84     ocl_gpu_id_t    ocl_gpu_id;          /**< device ID assigned at detection   */
85     char            device_name[256];    /**< device name */
86     char            device_version[256]; /**< device version */
87     char            device_vendor[256];  /**< device vendor */
88     int             compute_units;       /**< number of compute units */
89     int             adress_bits;         /**< number of adress bits the device is capable of */
90     int             stat;                /**< device status takes values of e_gpu_detect_res_t */
91     ocl_vendor_id_t vendor_e;            /**< device vendor as defined by ocl_vendor_id_t */
92     size_t maxWorkItemSizes[3]; /**< workgroup size limits (CL_DEVICE_MAX_WORK_ITEM_SIZES) */
93     size_t maxWorkGroupSize;    /**< workgroup total size limit (CL_DEVICE_MAX_WORK_GROUP_SIZE) */
94 };
95
96 /*! \internal
97  * \brief OpenCL GPU runtime data
98  *
99  * The device runtime data is meant to hold objects associated with a GROMACS rank's
100  * (thread or process) use of a single device (multiple devices per rank is not
101  * implemented). These objects should be constructed at ther point where a device
102  * dets assigned to a rank and released at when this assignment is no longer valid
103  * (i.e. at cleanup in the current implementation).
104  *
105  */
106 struct gmx_device_runtime_data_t
107 {
108     cl_context context; /**< OpenCL context */
109     cl_program program; /**< OpenCL program */
110 };
111
112 /*! \brief Launches synchronous or asynchronous device to host memory copy.
113  *
114  *  If copy_event is not NULL, on return it will contain an event object
115  *  identifying this particular device to host operation. The event can further
116  *  be used to queue a wait for this operation or to query profiling information.
117  */
118 int ocl_copy_D2H(void*              h_dest,
119                  cl_mem             d_src,
120                  size_t             offset,
121                  size_t             bytes,
122                  GpuApiCallBehavior transferKind,
123                  cl_command_queue   command_queue,
124                  cl_event*          copy_event);
125
126
127 /*! \brief Launches asynchronous device to host memory copy. */
128 int ocl_copy_D2H_async(void*            h_dest,
129                        cl_mem           d_src,
130                        size_t           offset,
131                        size_t           bytes,
132                        cl_command_queue command_queue,
133                        cl_event*        copy_event);
134
135 /*! \brief Launches synchronous or asynchronous host to device memory copy.
136  *
137  *  If copy_event is not NULL, on return it will contain an event object
138  *  identifying this particular host to device operation. The event can further
139  *  be used to queue a wait for this operation or to query profiling information.
140  */
141 int ocl_copy_H2D(cl_mem             d_dest,
142                  const void*        h_src,
143                  size_t             offset,
144                  size_t             bytes,
145                  GpuApiCallBehavior transferKind,
146                  cl_command_queue   command_queue,
147                  cl_event*          copy_event);
148
149 /*! \brief Launches asynchronous host to device memory copy. */
150 int ocl_copy_H2D_async(cl_mem           d_dest,
151                        const void*      h_src,
152                        size_t           offset,
153                        size_t           bytes,
154                        cl_command_queue command_queue,
155                        cl_event*        copy_event);
156
157 /*! \brief Launches synchronous host to device memory copy. */
158 int ocl_copy_H2D_sync(cl_mem d_dest, const void* h_src, size_t offset, size_t bytes, cl_command_queue command_queue);
159
160 /*! \brief Allocate host memory in malloc style */
161 void pmalloc(void** h_ptr, size_t nbytes);
162
163 /*! \brief Free host memory in malloc style */
164 void pfree(void* h_ptr);
165
166 /*! \brief Convert error code to diagnostic string */
167 std::string ocl_get_error_string(cl_int error);
168
169 /*! \brief Calls clFinish() in the stream \p s.
170  *
171  * \param[in] s stream to synchronize with
172  */
173 static inline void gpuStreamSynchronize(cl_command_queue s)
174 {
175     cl_int cl_error = clFinish(s);
176     GMX_RELEASE_ASSERT(CL_SUCCESS == cl_error,
177                        ("Error caught during clFinish:" + ocl_get_error_string(cl_error)).c_str());
178 }
179
180 //! A debug checker to track cl_events being released correctly
181 inline void ensureReferenceCount(const cl_event& event, unsigned int refCount)
182 {
183 #ifndef NDEBUG
184     cl_int clError = clGetEventInfo(event, CL_EVENT_REFERENCE_COUNT, sizeof(refCount), &refCount, nullptr);
185     GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
186     GMX_ASSERT(refCount == refCount, "Unexpected reference count");
187 #else
188     GMX_UNUSED_VALUE(event);
189     GMX_UNUSED_VALUE(refCount);
190 #endif
191 }
192
193 /*! \brief Pretend to synchronize an OpenCL stream (dummy implementation).
194  *
195  * \param[in] s queue to check
196  *
197  *  \returns     True if all tasks enqueued in the stream \p s (at the time of this call) have completed.
198  */
199 static inline bool haveStreamTasksCompleted(cl_command_queue gmx_unused s)
200 {
201     GMX_RELEASE_ASSERT(false, "haveStreamTasksCompleted is not implemented for OpenCL");
202     return false;
203 }
204
205 /* Kernel launch helpers */
206
207 /*! \brief
208  * A function for setting up a single OpenCL kernel argument.
209  * This is the tail of the compile-time recursive function below.
210  * It has to be seen by the compiler first.
211  * As NB kernels might be using dynamic local memory as the last argument,
212  * this function also manages that, using sharedMemorySize from \p config.
213  *
214  * \param[in]     kernel          Kernel function handle
215  * \param[in]     config          Kernel configuration for launching
216  * \param[in]     argIndex        Index of the current argument
217  */
218 void inline prepareGpuKernelArgument(cl_kernel kernel, const KernelLaunchConfig& config, size_t argIndex)
219 {
220     if (config.sharedMemorySize > 0)
221     {
222         cl_int gmx_used_in_debug clError =
223                 clSetKernelArg(kernel, argIndex, config.sharedMemorySize, nullptr);
224         GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
225     }
226 }
227
228 /*! \brief
229  * Compile-time recursive function for setting up a single OpenCL kernel argument.
230  * This function uses one kernel argument pointer \p argPtr to call clSetKernelArg(),
231  * and calls itself on the next argument, eventually calling the tail function above.
232  *
233  * \tparam        CurrentArg      Type of the current argument
234  * \tparam        RemainingArgs   Types of remaining arguments after the current one
235  * \param[in]     kernel          Kernel function handle
236  * \param[in]     config          Kernel configuration for launching
237  * \param[in]     argIndex        Index of the current argument
238  * \param[in]     argPtr          Pointer to the current argument
239  * \param[in]     otherArgsPtrs   Pack of pointers to arguments remaining to process after the current one
240  */
241 template<typename CurrentArg, typename... RemainingArgs>
242 void prepareGpuKernelArgument(cl_kernel                 kernel,
243                               const KernelLaunchConfig& config,
244                               size_t                    argIndex,
245                               const CurrentArg*         argPtr,
246                               const RemainingArgs*... otherArgsPtrs)
247 {
248     cl_int gmx_used_in_debug clError = clSetKernelArg(kernel, argIndex, sizeof(CurrentArg), argPtr);
249     GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
250
251     // Assert on types not allowed to be passed to a kernel
252     // (as per section 6.9 of the OpenCL spec).
253     static_assert(!std::is_same<CurrentArg, bool>::value && !std::is_same<CurrentArg, size_t>::value
254                           && !std::is_same<CurrentArg, ptrdiff_t>::value
255                           && !std::is_same<CurrentArg, intptr_t>::value
256                           && !std::is_same<CurrentArg, uintptr_t>::value,
257                   "Invalid type passed to OpenCL kernel functions (see OpenCL spec section 6.9).");
258
259     prepareGpuKernelArgument(kernel, config, argIndex + 1, otherArgsPtrs...);
260 }
261
262 /*! \brief
263  * A wrapper function for setting up all the OpenCL kernel arguments.
264  * Calls the recursive functions above.
265  *
266  * \tparam    Args            Types of all the kernel arguments
267  * \param[in] kernel          Kernel function handle
268  * \param[in] config          Kernel configuration for launching
269  * \param[in] argsPtrs        Pointers to all the kernel arguments
270  * \returns A handle for the prepared parameter pack to be used with launchGpuKernel() as the last argument
271  * - currently always nullptr for OpenCL, as it manages kernel/arguments association by itself.
272  */
273 template<typename... Args>
274 void* prepareGpuKernelArguments(cl_kernel kernel, const KernelLaunchConfig& config, const Args*... argsPtrs)
275 {
276     prepareGpuKernelArgument(kernel, config, 0, argsPtrs...);
277     return nullptr;
278 }
279
280 /*! \brief Launches the OpenCL kernel and handles the errors.
281  *
282  * \param[in] kernel          Kernel function handle
283  * \param[in] config          Kernel configuration for launching
284  * \param[in] timingEvent     Timing event, fetched from GpuRegionTimer
285  * \param[in] kernelName      Human readable kernel description, for error handling only
286  * \throws gmx::InternalError on kernel launch failure
287  */
288 inline void launchGpuKernel(cl_kernel                 kernel,
289                             const KernelLaunchConfig& config,
290                             CommandEvent*             timingEvent,
291                             const char*               kernelName,
292                             const void* /*kernelArgs*/)
293 {
294     const int       workDimensions   = 3;
295     const size_t*   globalWorkOffset = nullptr;
296     const size_t    waitListSize     = 0;
297     const cl_event* waitList         = nullptr;
298     size_t          globalWorkSize[3];
299     for (int i = 0; i < workDimensions; i++)
300     {
301         globalWorkSize[i] = config.gridSize[i] * config.blockSize[i];
302     }
303     cl_int clError = clEnqueueNDRangeKernel(config.stream, kernel, workDimensions, globalWorkOffset,
304                                             globalWorkSize, config.blockSize, waitListSize,
305                                             waitList, timingEvent);
306     if (CL_SUCCESS != clError)
307     {
308         const std::string errorMessage = "GPU kernel (" + std::string(kernelName)
309                                          + ") failed to launch: " + ocl_get_error_string(clError);
310         GMX_THROW(gmx::InternalError(errorMessage));
311     }
312 }
313
314 #endif