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