Fix more clang-6 warnings in CUDA code
[alexxy/gromacs.git] / src / gromacs / gpu_utils / cudautils.cuh
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2014,2015,2016,2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 #ifndef GMX_GPU_UTILS_CUDAUTILS_CUH
36 #define GMX_GPU_UTILS_CUDAUTILS_CUH
37
38 #include <stdio.h>
39
40 #include <array>
41 #include <string>
42
43 #include "gromacs/gpu_utils/gputraits.cuh"
44 #include "gromacs/math/vec.h"
45 #include "gromacs/math/vectypes.h"
46 #include "gromacs/utility/exceptions.h"
47 #include "gromacs/utility/fatalerror.h"
48 #include "gromacs/utility/gmxassert.h"
49 #include "gromacs/utility/stringutil.h"
50
51 namespace gmx
52 {
53 namespace
54 {
55
56 /*! \brief Helper function to ensure no pending error silently
57  * disrupts error handling.
58  *
59  * Asserts in a debug build if an unhandled error is present. Issues a
60  * warning at run time otherwise.
61  *
62  * \todo This is similar to CU_CHECK_PREV_ERR, which should be
63  * consolidated.
64  */
65 static inline void ensureNoPendingCudaError(const char *errorMessage)
66 {
67     // Ensure there is no pending error that would otherwise affect
68     // the behaviour of future error handling.
69     cudaError_t stat = cudaGetLastError();
70     if (stat == cudaSuccess)
71     {
72         return;
73     }
74
75     // If we would find an error in a release build, we do not know
76     // what is appropriate to do about it, so assert only for debug
77     // builds.
78     auto fullMessage = formatString("%s An unhandled error from a previous CUDA operation was detected. %s: %s",
79                                     errorMessage, cudaGetErrorName(stat), cudaGetErrorString(stat));
80     GMX_ASSERT(stat == cudaSuccess, fullMessage.c_str());
81     // TODO When we evolve a better logging framework, use that
82     // for release-build error reporting.
83     gmx_warning("%s", fullMessage.c_str());
84 }
85
86 }   // namespace
87 }   // namespace
88
89 enum class GpuApiCallBehavior;
90
91 /* TODO error checking needs to be rewritten. We have 2 types of error checks needed
92    based on where they occur in the code:
93    - non performance-critical: these errors are unsafe to be ignored and must be
94      _always_ checked for, e.g. initializations
95    - performance critical: handling errors might hurt performance so care need to be taken
96      when/if we should check for them at all, e.g. in cu_upload_X. However, we should be
97      able to turn the check for these errors on!
98
99    Probably we'll need two sets of the macros below...
100
101  */
102 #define CHECK_CUDA_ERRORS
103
104 #ifdef CHECK_CUDA_ERRORS
105
106 /*! Check for CUDA error on the return status of a CUDA RT API call. */
107 #define CU_RET_ERR(status, msg) \
108     do { \
109         if (status != cudaSuccess) \
110         { \
111             gmx_fatal(FARGS, "%s: %s\n", msg, cudaGetErrorString(status)); \
112         } \
113     } while (0)
114
115 /*! Check for any previously occurred uncaught CUDA error. */
116 #define CU_CHECK_PREV_ERR() \
117     do { \
118         cudaError_t _CU_CHECK_PREV_ERR_status = cudaGetLastError(); \
119         if (_CU_CHECK_PREV_ERR_status != cudaSuccess) { \
120             gmx_warning("Just caught a previously occurred CUDA error (%s), will try to continue.", cudaGetErrorString(_CU_CHECK_PREV_ERR_status)); \
121         } \
122     } while (0)
123
124 #else /* CHECK_CUDA_ERRORS */
125
126 #define CU_RET_ERR(status, msg) do { } while (0)
127 #define CU_CHECK_PREV_ERR()     do { } while (0)
128
129 #endif /* CHECK_CUDA_ERRORS */
130
131 /*! \brief CUDA device information.
132  *
133  * The CUDA device information is queried and set at detection and contains
134  * both information about the device/hardware returned by the runtime as well
135  * as additional data like support status.
136  */
137 struct gmx_device_info_t
138 {
139     int                 id;                      /* id of the CUDA device */
140     cudaDeviceProp      prop;                    /* CUDA device properties */
141     int                 stat;                    /* result of the device check */
142 };
143
144 /*! Launches synchronous or asynchronous device to host memory copy.
145  *
146  *  The copy is launched in stream s or if not specified, in stream 0.
147  */
148 int cu_copy_D2H(void *h_dest, void *d_src, size_t bytes, GpuApiCallBehavior transferKind, cudaStream_t /*s = nullptr*/);
149
150 /*! Launches synchronous host to device memory copy in stream 0. */
151 int cu_copy_D2H_sync(void * /*h_dest*/, void * /*d_src*/, size_t /*bytes*/);
152
153 /*! Launches asynchronous host to device memory copy in stream s. */
154 int cu_copy_D2H_async(void * /*h_dest*/, void * /*d_src*/, size_t /*bytes*/, cudaStream_t /*s = nullptr*/);
155
156 /*! Launches synchronous or asynchronous host to device memory copy.
157  *
158  *  The copy is launched in stream s or if not specified, in stream 0.
159  */
160 int cu_copy_H2D(void *d_dest, void *h_src, size_t bytes, GpuApiCallBehavior transferKind, cudaStream_t /*s = nullptr*/);
161
162 /*! Launches synchronous host to device memory copy. */
163 int cu_copy_H2D_sync(void * /*d_dest*/, void * /*h_src*/, size_t /*bytes*/);
164
165 /*! Launches asynchronous host to device memory copy in stream s. */
166 int cu_copy_H2D_async(void * /*d_dest*/, void * /*h_src*/, size_t /*bytes*/, cudaStream_t /*s = nullptr*/);
167
168 // TODO: the 2 functions below are pretty much a constructor/destructor of a simple
169 // GPU table object. There is also almost self-contained fetchFromParamLookupTable()
170 // in cuda_kernel_utils.cuh. They could all live in a separate class/struct file.
171
172 /*! \brief Initialize parameter lookup table.
173  *
174  * Initializes device memory, copies data from host and binds
175  * a texture to allocated device memory to be used for parameter lookup.
176  *
177  * \tparam[in] T         Raw data type
178  * \param[out] d_ptr     device pointer to the memory to be allocated
179  * \param[out] texObj    texture object to be initialized
180  * \param[in]  h_ptr     pointer to the host memory to be uploaded to the device
181  * \param[in]  numElem   number of elements in the h_ptr
182  * \param[in]  devInfo   pointer to the info struct of the device in use
183  */
184 template <typename T>
185 void initParamLookupTable(T                        * &d_ptr,
186                           cudaTextureObject_t        &texObj,
187                           const T                    *h_ptr,
188                           int                         numElem,
189                           const gmx_device_info_t    *devInfo);
190
191 // Add extern declarations so each translation unit understands that
192 // there will be a definition provided.
193 extern template void initParamLookupTable<int>(int * &, cudaTextureObject_t &, const int *, int, const gmx_device_info_t *);
194 extern template void initParamLookupTable<float>(float * &, cudaTextureObject_t &, const float *, int, const gmx_device_info_t *);
195
196 /*! \brief Destroy parameter lookup table.
197  *
198  * Unbinds texture object, deallocates device memory.
199  *
200  * \tparam[in] T         Raw data type
201  * \param[in]  d_ptr     Device pointer to the memory to be deallocated
202  * \param[in]  texObj    Texture object to be deinitialized
203  * \param[in]  devInfo   Pointer to the info struct of the device in use
204  */
205 template <typename T>
206 void destroyParamLookupTable(T                       *d_ptr,
207                              cudaTextureObject_t      texObj,
208                              const gmx_device_info_t *devInfo);
209
210 // Add extern declarations so each translation unit understands that
211 // there will be a definition provided.
212 extern template void destroyParamLookupTable<int>(int *, cudaTextureObject_t, const gmx_device_info_t *);
213 extern template void destroyParamLookupTable<float>(float *, cudaTextureObject_t, const gmx_device_info_t *);
214
215 /*! \brief Add a triplets stored in a float3 to an rvec variable.
216  *
217  * \param[out]  a Rvec to increment
218  * \param[in]   b Float triplet to increment with.
219  */
220 static inline void rvec_inc(rvec a, const float3 b)
221 {
222     rvec tmp = {b.x, b.y, b.z};
223     rvec_inc(a, tmp);
224 }
225
226 /*! \brief Wait for all taks in stream \p s to complete.
227  *
228  * \param[in] s stream to synchronize with
229  */
230 static inline void gpuStreamSynchronize(cudaStream_t s)
231 {
232     cudaError_t stat = cudaStreamSynchronize(s);
233     CU_RET_ERR(stat, "cudaStreamSynchronize failed");
234 }
235
236 /*! \brief  Returns true if all tasks in \p s have completed.
237  *
238  * \param[in] s stream to check
239  *
240  *  \returns     True if all tasks enqueued in the stream \p s (at the time of this call) have completed.
241  */
242 static inline bool haveStreamTasksCompleted(cudaStream_t s)
243 {
244     cudaError_t stat = cudaStreamQuery(s);
245
246     if (stat == cudaErrorNotReady)
247     {
248         // work is still in progress in the stream
249         return false;
250     }
251
252     GMX_ASSERT(stat !=  cudaErrorInvalidResourceHandle, "Stream idnetifier not valid");
253
254     // cudaSuccess and cudaErrorNotReady are the expected return values
255     CU_RET_ERR(stat, "Unexpected cudaStreamQuery failure");
256
257     GMX_ASSERT(stat == cudaSuccess, "Values other than cudaSuccess should have been explicitly handled");
258
259     return true;
260 }
261
262 /* Kernel launch helpers */
263
264 /*! \brief
265  * A function for setting up a single CUDA kernel argument.
266  * This is the tail of the compile-time recursive function below.
267  * It has to be seen by the compiler first.
268  *
269  * \tparam        totalArgsCount  Number of the kernel arguments
270  * \tparam        KernelPtr       Kernel function handle type
271  * \param[in]     argIndex        Index of the current argument
272  */
273 template <size_t totalArgsCount, typename KernelPtr>
274 void prepareGpuKernelArgument(KernelPtr /*kernel*/,
275                               std::array<void *, totalArgsCount> */* kernelArgsPtr */,
276                               size_t gmx_used_in_debug argIndex)
277 {
278     GMX_ASSERT(argIndex == totalArgsCount, "Tail expansion");
279 }
280
281 /*! \brief
282  * Compile-time recursive function for setting up a single CUDA kernel argument.
283  * This function copies a kernel argument pointer \p argPtr into \p kernelArgsPtr,
284  * and calls itself on the next argument, eventually calling the tail function above.
285  *
286  * \tparam        CurrentArg      Type of the current argument
287  * \tparam        RemainingArgs   Types of remaining arguments after the current one
288  * \tparam        totalArgsCount  Number of the kernel arguments
289  * \tparam        KernelPtr       Kernel function handle type
290  * \param[in]     kernel          Kernel function handle
291  * \param[in,out] kernelArgsPtr   Pointer to the argument array to be filled in
292  * \param[in]     argIndex        Index of the current argument
293  * \param[in]     argPtr          Pointer to the current argument
294  * \param[in]     otherArgsPtrs   Pack of pointers to arguments remaining to process after the current one
295  */
296 template <typename CurrentArg, typename ... RemainingArgs, size_t totalArgsCount, typename KernelPtr>
297 void prepareGpuKernelArgument(KernelPtr kernel,
298                               std::array<void *, totalArgsCount> *kernelArgsPtr,
299                               size_t argIndex,
300                               const CurrentArg *argPtr,
301                               const RemainingArgs *... otherArgsPtrs)
302 {
303     (*kernelArgsPtr)[argIndex] = (void *)argPtr;
304     prepareGpuKernelArgument(kernel, kernelArgsPtr, argIndex + 1, otherArgsPtrs ...);
305 }
306
307 /*! \brief
308  * A wrapper function for setting up all the CUDA kernel arguments.
309  * Calls the recursive functions above.
310  *
311  * \tparam    Args            Types of all the kernel arguments
312  * \param[in] kernel          Kernel function handle
313  * \param[in] argsPtrs        Pointers to all the kernel arguments
314  * \returns A prepared parameter pack to be used with launchGpuKernel() as the last argument.
315  */
316 template <typename ... Args>
317 std::array<void *, sizeof ... (Args)> prepareGpuKernelArguments(void                     (*kernel)(Args...),
318                                                                 const KernelLaunchConfig & /*config */,
319                                                                 const Args *...          argsPtrs)
320 {
321     std::array<void *, sizeof ... (Args)> kernelArgs;
322     prepareGpuKernelArgument(kernel, &kernelArgs, 0, argsPtrs ...);
323     return kernelArgs;
324 }
325
326 /*! \brief Launches the CUDA kernel and handles the errors.
327  *
328  * \tparam    Args            Types of all the kernel arguments
329  * \param[in] kernel          Kernel function handle
330  * \param[in] config          Kernel configuration for launching
331  * \param[in] kernelName      Human readable kernel description, for error handling only
332  * \param[in] kernelArgs      Array of the pointers to the kernel arguments, prepared by prepareGpuKernelArguments()
333  * \throws gmx::InternalError on kernel launch failure
334  */
335 template <typename... Args>
336 void launchGpuKernel(void                                       (*kernel)(Args...),
337                      const KernelLaunchConfig                    &config,
338                      CommandEvent                                */*timingEvent */,
339                      const char                                  *kernelName,
340                      const std::array<void *, sizeof ... (Args)> &kernelArgs)
341 {
342     dim3 blockSize(config.blockSize[0], config.blockSize[1], config.blockSize[2]);
343     dim3 gridSize(config.gridSize[0], config.gridSize[1], config.gridSize[2]);
344     cudaLaunchKernel((void *)kernel, gridSize, blockSize, const_cast<void **>(kernelArgs.data()), config.sharedMemorySize, config.stream);
345
346     cudaError_t status = cudaGetLastError();
347     if (cudaSuccess != status)
348     {
349         const std::string errorMessage = "GPU kernel (" +  std::string(kernelName) +
350             ") failed to launch: " + std::string(cudaGetErrorString(status));
351         GMX_THROW(gmx::InternalError(errorMessage));
352     }
353 }
354
355 #endif