Merge common nbnxn CUDA/OpenCL GPU wait code-paths
[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, 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 "config.h"
39
40 #include <stdio.h>
41 #if HAVE_NVML
42 #include <nvml.h>
43 #endif /* HAVE_NVML */
44
45 #include "gromacs/math/vec.h"
46 #include "gromacs/math/vectypes.h"
47 #include "gromacs/utility/fatalerror.h"
48
49 /* TODO error checking needs to be rewritten. We have 2 types of error checks needed
50    based on where they occur in the code:
51    - non performance-critical: these errors are unsafe to be ignored and must be
52      _always_ checked for, e.g. initializations
53    - performance critical: handling errors might hurt performance so care need to be taken
54      when/if we should check for them at all, e.g. in cu_upload_X. However, we should be
55      able to turn the check for these errors on!
56
57    Probably we'll need two sets of the macros below...
58
59  */
60 #define CHECK_CUDA_ERRORS
61
62 #ifdef CHECK_CUDA_ERRORS
63
64 /*! Check for CUDA error on the return status of a CUDA RT API call. */
65 #define CU_RET_ERR(status, msg) \
66     do { \
67         if (status != cudaSuccess) \
68         { \
69             gmx_fatal(FARGS, "%s: %s\n", msg, cudaGetErrorString(status)); \
70         } \
71     } while (0)
72
73 /*! Check for any previously occurred uncaught CUDA error. */
74 #define CU_CHECK_PREV_ERR() \
75     do { \
76         cudaError_t _CU_CHECK_PREV_ERR_status = cudaGetLastError(); \
77         if (_CU_CHECK_PREV_ERR_status != cudaSuccess) { \
78             gmx_warning("Just caught a previously occurred CUDA error (%s), will try to continue.", cudaGetErrorString(_CU_CHECK_PREV_ERR_status)); \
79         } \
80     } while (0)
81
82 /*! Check for any previously occurred uncaught CUDA error
83    -- aimed at use after kernel calls. */
84 #define CU_LAUNCH_ERR(msg) \
85     do { \
86         cudaError_t _CU_LAUNCH_ERR_status = cudaGetLastError(); \
87         if (_CU_LAUNCH_ERR_status != cudaSuccess) { \
88             gmx_fatal(FARGS, "Error while launching kernel %s: %s\n", msg, cudaGetErrorString(_CU_LAUNCH_ERR_status)); \
89         } \
90     } while (0)
91
92 /*! Synchronize with GPU and check for any previously occurred uncaught CUDA error
93    -- aimed at use after kernel calls. */
94 #define CU_LAUNCH_ERR_SYNC(msg) \
95     do { \
96         cudaError_t _CU_SYNC_LAUNCH_ERR_status = cudaThreadSynchronize(); \
97         if (_CU_SYNC_LAUNCH_ERR_status != cudaSuccess) { \
98             gmx_fatal(FARGS, "Error while launching kernel %s: %s\n", msg, cudaGetErrorString(_CU_SYNC_LAUNCH_ERR_status)); \
99         } \
100     } while (0)
101
102 #else /* CHECK_CUDA_ERRORS */
103
104 #define CU_RET_ERR(status, msg) do { } while (0)
105 #define CU_CHECK_PREV_ERR()     do { } while (0)
106 #define CU_LAUNCH_ERR(msg)      do { } while (0)
107 #define CU_LAUNCH_ERR_SYNC(msg) do { } while (0)
108 #define HANDLE_NVML_RET_ERR(status, msg) do { } while (0)
109
110 #endif /* CHECK_CUDA_ERRORS */
111
112 /*! \brief CUDA device information.
113  *
114  * The CUDA device information is queried and set at detection and contains
115  * both information about the device/hardware returned by the runtime as well
116  * as additional data like support status.
117  *
118  * \todo extract an object to manage NVML details
119  */
120 struct gmx_device_info_t
121 {
122     int                 id;                      /* id of the CUDA device */
123     cudaDeviceProp      prop;                    /* CUDA device properties */
124     int                 stat;                    /* result of the device check */
125     unsigned int        nvml_orig_app_sm_clock;  /* The original SM clock before we changed it */
126     unsigned int        nvml_orig_app_mem_clock; /* The original memory clock before we changed it */
127     gmx_bool            nvml_app_clocks_changed; /* If application clocks have been changed */
128     unsigned int        nvml_set_app_sm_clock;   /* The SM clock we set */
129     unsigned int        nvml_set_app_mem_clock;  /* The memory clock we set */
130 #if HAVE_NVML
131     nvmlDevice_t        nvml_device_id;          /* NVML device id */
132     // TODO This can become a bool with a more useful name
133     nvmlEnableState_t   nvml_is_restricted;      /* Status of application clocks permission */
134 #endif                                           /* HAVE_NVML */
135 };
136
137
138 /*! Launches asynchronous host to device memory copy in stream 0. */
139 int cu_copy_D2H(void * /*h_dest*/, void * /*d_src*/, size_t /*bytes*/);
140
141 /*! Launches asynchronous host to device memory copy in stream s. */
142 int cu_copy_D2H_async(void * /*h_dest*/, void * /*d_src*/, size_t /*bytes*/, cudaStream_t /*s = 0*/);
143
144 /*! Launches synchronous host to device memory copy. */
145 int cu_copy_H2D(void * /*d_dest*/, void * /*h_src*/, size_t /*bytes*/);
146
147 /*! Launches asynchronous host to device memory copy in stream s. */
148 int cu_copy_H2D_async(void * /*d_dest*/, void * /*h_src*/, size_t /*bytes*/, cudaStream_t /*s = 0*/);
149
150 /*! Frees device memory and resets the size and allocation size to -1. */
151 void cu_free_buffered(void *d_ptr, int *n = NULL, int *nalloc = NULL);
152
153 /*! Reallocates the device memory and copies data from the host. */
154 void cu_realloc_buffered(void **d_dest, void *h_src,
155                          size_t type_size,
156                          int *curr_size, int *curr_alloc_size,
157                          int req_size,
158                          cudaStream_t s,
159                          bool bAsync);
160
161 // TODO: the 2 functions below are pretty much a constructor/destructor of a simple
162 // GPU table object. There is also almost self-contained fetchFromParamLookupTable()
163 // in cuda_kernel_utils.cuh. They could all live in a separate class/struct file,
164 // granted storing static texture references in there does not pose problems.
165
166 /*! \brief Initialize parameter lookup table.
167  *
168  * Initializes device memory, copies data from host and binds
169  * a texture to allocated device memory to be used for parameter lookup.
170  *
171  * \tparam[in] T         Raw data type
172  * \param[out] d_ptr     device pointer to the memory to be allocated
173  * \param[out] texObj    texture object to be initialized
174  * \param[out] texRef    texture reference to be initialized
175  * \param[in]  h_ptr     pointer to the host memory to be uploaded to the device
176  * \param[in]  numElem   number of elements in the h_ptr
177  * \param[in]  devInfo   pointer to the info struct of the device in use
178  */
179 template <typename T>
180 void initParamLookupTable(T                        * &d_ptr,
181                           cudaTextureObject_t       &texObj,
182                           const struct texture<T, 1, cudaReadModeElementType> *texRef,
183                           const T                   *h_ptr,
184                           int                        numElem,
185                           const gmx_device_info_t   *devInfo);
186
187 /*! \brief Destroy parameter lookup table.
188  *
189  * Unbinds texture reference/object, deallocates device memory.
190  *
191  * \tparam[in] T         Raw data type
192  * \param[in]  d_ptr     Device pointer to the memory to be deallocated
193  * \param[in]  texObj    Texture object to be deinitialized
194  * \param[in]  texRef    Texture reference to be deinitialized
195  * \param[in]  devInfo   Pointer to the info struct of the device in use
196  */
197 template <typename T>
198 void destroyParamLookupTable(T                         *d_ptr,
199                              cudaTextureObject_t        texObj,
200                              const struct texture<T, 1, cudaReadModeElementType> *texRef,
201                              const gmx_device_info_t   *devInfo);
202
203 /*! \brief Add a triplets stored in a float3 to an rvec variable.
204  *
205  * \param[out]  a Rvec to increment
206  * \param[in]   b Float triplet to increment with.
207  */
208 static inline void rvec_inc(rvec a, const float3 b)
209 {
210     rvec tmp = {b.x, b.y, b.z};
211     rvec_inc(a, tmp);
212 }
213
214 /*! \brief Calls cudaStreamSynchronize() in the stream \p s.
215  *
216  * \param[in] s stream to synchronize with
217  */
218 static inline void gpuStreamSynchronize(cudaStream_t s)
219 {
220     cudaError_t stat = cudaStreamSynchronize(s);
221     CU_RET_ERR(stat, "cudaStreamSynchronize failed");
222 }
223
224 #endif