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