SYCL: Avoid using no_init read accessor in rocFFT
[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,2021, 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/fatalerror.h"
53 #include "gromacs/utility/gmxassert.h"
54 #include "gromacs/utility/stringutil.h"
55
56 enum class GpuApiCallBehavior;
57
58 /*! \internal
59  * \brief OpenCL GPU runtime data
60  *
61  * The device runtime data is meant to hold objects associated with a GROMACS rank's
62  * (thread or process) use of a single device (multiple devices per rank is not
63  * implemented). These objects should be constructed at ther point where a device
64  * dets assigned to a rank and released at when this assignment is no longer valid
65  * (i.e. at cleanup in the current implementation).
66  *
67  */
68 struct gmx_device_runtime_data_t
69 {
70     //! OpenCL program
71     cl_program program;
72 };
73
74 /*! \brief Convert error code to diagnostic string */
75 std::string ocl_get_error_string(cl_int error);
76
77 /*! \brief Pretend to synchronize an OpenCL stream (dummy implementation).
78  *
79  *  \returns  Not implemented in OpenCL.
80  */
81 static inline bool haveStreamTasksCompleted(const DeviceStream& /* deviceStream */)
82 {
83     GMX_RELEASE_ASSERT(false, "haveStreamTasksCompleted is not implemented for OpenCL");
84     return false;
85 }
86
87 /* Kernel launch helpers */
88
89 /*! \brief
90  * A function for setting up a single OpenCL kernel argument.
91  * This is the tail of the compile-time recursive function below.
92  * It has to be seen by the compiler first.
93  * As NB kernels might be using dynamic local memory as the last argument,
94  * this function also manages that, using sharedMemorySize from \p config.
95  *
96  * \param[in]     kernel          Kernel function handle
97  * \param[in]     config          Kernel configuration for launching
98  * \param[in]     argIndex        Index of the current argument
99  */
100 void inline prepareGpuKernelArgument(cl_kernel kernel, const KernelLaunchConfig& config, size_t argIndex)
101 {
102     if (config.sharedMemorySize > 0)
103     {
104         cl_int gmx_used_in_debug clError =
105                 clSetKernelArg(kernel, argIndex, config.sharedMemorySize, nullptr);
106         GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
107     }
108 }
109
110 /*! \brief
111  * Compile-time recursive function for setting up a single OpenCL kernel argument.
112  * This function uses one kernel argument pointer \p argPtr to call clSetKernelArg(),
113  * and calls itself on the next argument, eventually calling the tail function above.
114  *
115  * \tparam        CurrentArg      Type of the current argument
116  * \tparam        RemainingArgs   Types of remaining arguments after the current one
117  * \param[in]     kernel          Kernel function handle
118  * \param[in]     config          Kernel configuration for launching
119  * \param[in]     argIndex        Index of the current argument
120  * \param[in]     argPtr          Pointer to the current argument
121  * \param[in]     otherArgsPtrs   Pack of pointers to arguments remaining to process after the current one
122  */
123 template<typename CurrentArg, typename... RemainingArgs>
124 void prepareGpuKernelArgument(cl_kernel                 kernel,
125                               const KernelLaunchConfig& config,
126                               size_t                    argIndex,
127                               const CurrentArg*         argPtr,
128                               const RemainingArgs*... otherArgsPtrs)
129 {
130     cl_int gmx_used_in_debug clError = clSetKernelArg(kernel, argIndex, sizeof(CurrentArg), argPtr);
131     GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
132
133     // Assert on types not allowed to be passed to a kernel
134     // (as per section 6.9 of the OpenCL spec).
135     static_assert(
136             !std::is_same_v<CurrentArg,
137                             bool> && !std::is_same_v<CurrentArg, size_t> && !std::is_same_v<CurrentArg, ptrdiff_t> && !std::is_same_v<CurrentArg, intptr_t> && !std::is_same_v<CurrentArg, uintptr_t>,
138             "Invalid type passed to OpenCL kernel functions (see OpenCL spec section 6.9).");
139
140     prepareGpuKernelArgument(kernel, config, argIndex + 1, otherArgsPtrs...);
141 }
142
143 /*! \brief
144  * A wrapper function for setting up all the OpenCL kernel arguments.
145  * Calls the recursive functions above.
146  *
147  * \tparam    Args            Types of all the kernel arguments
148  * \param[in] kernel          Kernel function handle
149  * \param[in] config          Kernel configuration for launching
150  * \param[in] argsPtrs        Pointers to all the kernel arguments
151  * \returns A handle for the prepared parameter pack to be used with launchGpuKernel() as the last argument
152  * - currently always nullptr for OpenCL, as it manages kernel/arguments association by itself.
153  */
154 template<typename... Args>
155 void* prepareGpuKernelArguments(cl_kernel kernel, const KernelLaunchConfig& config, const Args*... argsPtrs)
156 {
157     prepareGpuKernelArgument(kernel, config, 0, argsPtrs...);
158     return nullptr;
159 }
160
161 /*! \brief Launches the OpenCL kernel and handles the errors.
162  *
163  * \param[in] kernel          Kernel function handle
164  * \param[in] config          Kernel configuration for launching
165  * \param[in] deviceStream    GPU stream to launch kernel in
166  * \param[in] timingEvent     Timing event, fetched from GpuRegionTimer
167  * \param[in] kernelName      Human readable kernel description, for error handling only
168  * \throws gmx::InternalError on kernel launch failure
169  */
170 inline void launchGpuKernel(cl_kernel                 kernel,
171                             const KernelLaunchConfig& config,
172                             const DeviceStream&       deviceStream,
173                             CommandEvent*             timingEvent,
174                             const char*               kernelName,
175                             const void* /*kernelArgs*/)
176 {
177     const int       workDimensions   = 3;
178     const size_t*   globalWorkOffset = nullptr;
179     const size_t    waitListSize     = 0;
180     const cl_event* waitList         = nullptr;
181     size_t          globalWorkSize[3];
182     for (int i = 0; i < workDimensions; i++)
183     {
184         globalWorkSize[i] = config.gridSize[i] * config.blockSize[i];
185     }
186     cl_int clError = clEnqueueNDRangeKernel(deviceStream.stream(),
187                                             kernel,
188                                             workDimensions,
189                                             globalWorkOffset,
190                                             globalWorkSize,
191                                             config.blockSize,
192                                             waitListSize,
193                                             waitList,
194                                             timingEvent);
195     if (CL_SUCCESS != clError)
196     {
197         const std::string errorMessage = "GPU kernel (" + std::string(kernelName)
198                                          + ") failed to launch: " + ocl_get_error_string(clError);
199         GMX_THROW(gmx::InternalError(errorMessage));
200     }
201 }
202
203 #endif