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