2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2018,2019,2020,2021, 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.
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.
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.
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.
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.
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.
35 #ifndef GMX_GPU_UTILS_DEVICEBUFFER_CUH
36 #define GMX_GPU_UTILS_DEVICEBUFFER_CUH
38 /*! \libinternal \file
39 * \brief Implements the DeviceBuffer type and routines for CUDA.
40 * Should only be included directly by the main DeviceBuffer file devicebuffer.h.
41 * TODO: the intent is for DeviceBuffer to become a class.
43 * \author Aleksei Iupinov <a.yupinov@gmail.com>
48 #include "gromacs/gpu_utils/cuda_arch_utils.cuh"
49 #include "gromacs/gpu_utils/cudautils.cuh"
50 #include "gromacs/gpu_utils/device_context.h"
51 #include "gromacs/gpu_utils/device_stream.h"
52 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
53 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
54 #include "gromacs/gpu_utils/gputraits.cuh"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
59 * Allocates a device-side buffer.
60 * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
62 * \tparam ValueType Raw value type of the \p buffer.
63 * \param[in,out] buffer Pointer to the device-side buffer.
64 * \param[in] numValues Number of values to accommodate.
65 * \param[in] deviceContext The buffer's dummy device context - not managed explicitly in CUDA RT.
67 template<typename ValueType>
68 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& /* deviceContext */)
70 GMX_ASSERT(buffer, "needs a buffer pointer");
71 cudaError_t stat = cudaMalloc((void**)buffer, numValues * sizeof(ValueType));
74 ("Allocation of the device buffer failed. " + gmx::getDeviceErrorString(stat)).c_str());
78 * Frees a device-side buffer.
79 * This does not reset separately stored size/capacity integers,
80 * as this is planned to be a destructor of DeviceBuffer as a proper class,
81 * and no calls on \p buffer should be made afterwards.
83 * \param[in] buffer Pointer to the buffer to free.
85 template<typename DeviceBuffer>
86 void freeDeviceBuffer(DeviceBuffer* buffer)
88 GMX_ASSERT(buffer, "needs a buffer pointer");
91 cudaError_t stat = cudaFree(*buffer);
94 ("Freeing of the device buffer failed. " + gmx::getDeviceErrorString(stat)).c_str());
99 * Performs the host-to-device data copy, synchronous or asynchronously on request.
101 * \tparam ValueType Raw value type of the \p buffer.
102 * \param[in,out] buffer Pointer to the device-side buffer
103 * \param[in] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType
104 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy into.
105 * \param[in] numValues Number of values to copy.
106 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
107 * \param[in] transferKind Copy type: synchronous or asynchronous.
108 * \param[out] timingEvent A dummy pointer to the H2D copy timing event to be filled in.
109 * Not used in CUDA implementation.
111 template<typename ValueType>
112 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
113 const ValueType* hostBuffer,
114 size_t startingOffset,
116 const DeviceStream& deviceStream,
117 GpuApiCallBehavior transferKind,
118 CommandEvent* /*timingEvent*/)
124 GMX_ASSERT(buffer, "needs a buffer pointer");
125 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
127 const size_t bytes = numValues * sizeof(ValueType);
129 switch (transferKind)
131 case GpuApiCallBehavior::Async:
132 GMX_ASSERT(isHostMemoryPinned(hostBuffer), "Source host buffer was not pinned for CUDA");
133 stat = cudaMemcpyAsync(*((ValueType**)buffer) + startingOffset,
136 cudaMemcpyHostToDevice,
137 deviceStream.stream());
140 ("Asynchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
143 case GpuApiCallBehavior::Sync:
145 *((ValueType**)buffer) + startingOffset, hostBuffer, bytes, cudaMemcpyHostToDevice);
148 ("Synchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
156 * Performs the device-to-host data copy, synchronous or asynchronously on request.
158 * \tparam ValueType Raw value type of the \p buffer.
159 * \param[in,out] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType
160 * \param[in] buffer Pointer to the device-side buffer
161 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy from.
162 * \param[in] numValues Number of values to copy.
163 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
164 * \param[in] transferKind Copy type: synchronous or asynchronous.
165 * \param[out] timingEvent A dummy pointer to the H2D copy timing event to be filled in.
166 * Not used in CUDA implementation.
168 template<typename ValueType>
169 void copyFromDeviceBuffer(ValueType* hostBuffer,
170 DeviceBuffer<ValueType>* buffer,
171 size_t startingOffset,
173 const DeviceStream& deviceStream,
174 GpuApiCallBehavior transferKind,
175 CommandEvent* /*timingEvent*/)
181 GMX_ASSERT(buffer, "needs a buffer pointer");
182 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
185 const size_t bytes = numValues * sizeof(ValueType);
186 switch (transferKind)
188 case GpuApiCallBehavior::Async:
189 GMX_ASSERT(isHostMemoryPinned(hostBuffer),
190 "Destination host buffer was not pinned for CUDA");
191 stat = cudaMemcpyAsync(hostBuffer,
192 *((ValueType**)buffer) + startingOffset,
194 cudaMemcpyDeviceToHost,
195 deviceStream.stream());
198 ("Asynchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
201 case GpuApiCallBehavior::Sync:
203 hostBuffer, *((ValueType**)buffer) + startingOffset, bytes, cudaMemcpyDeviceToHost);
206 ("Synchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
214 * Performs the device-to-device data copy, synchronous or asynchronously on request.
216 * \tparam ValueType Raw value type of the \p buffer.
217 * \param[in,out] destinationDeviceBuffer Device-side buffer to copy to
218 * \param[in] sourceDeviceBuffer Device-side buffer to copy from
219 * \param[in] numValues Number of values to copy.
220 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
221 * \param[in] transferKind Copy type: synchronous or asynchronous.
222 * \param[out] timingEvent A dummy pointer to the D2D copy timing event to be filled
223 * in. Not used in CUDA implementation.
225 template<typename ValueType>
226 void copyBetweenDeviceBuffers(DeviceBuffer<ValueType>* destinationDeviceBuffer,
227 DeviceBuffer<ValueType>* sourceDeviceBuffer,
229 const DeviceStream& deviceStream,
230 GpuApiCallBehavior transferKind,
231 CommandEvent* /*timingEvent*/)
237 GMX_ASSERT(destinationDeviceBuffer, "needs a destination buffer pointer");
238 GMX_ASSERT(sourceDeviceBuffer, "needs a source buffer pointer");
241 const size_t bytes = numValues * sizeof(ValueType);
242 switch (transferKind)
244 case GpuApiCallBehavior::Async:
245 stat = cudaMemcpyAsync(*destinationDeviceBuffer,
248 cudaMemcpyDeviceToDevice,
249 deviceStream.stream());
252 ("Asynchronous D2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
255 case GpuApiCallBehavior::Sync:
256 stat = cudaMemcpy(*destinationDeviceBuffer, *sourceDeviceBuffer, bytes, cudaMemcpyDeviceToDevice);
259 ("Synchronous D2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
267 * Clears the device buffer asynchronously.
269 * \tparam ValueType Raw value type of the \p buffer.
270 * \param[in,out] buffer Pointer to the device-side buffer
271 * \param[in] startingOffset Offset (in values) at the device-side buffer to start clearing at.
272 * \param[in] numValues Number of values to clear.
273 * \param[in] deviceStream GPU stream.
275 template<typename ValueType>
276 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
277 size_t startingOffset,
279 const DeviceStream& deviceStream)
285 GMX_ASSERT(buffer, "needs a buffer pointer");
286 const size_t bytes = numValues * sizeof(ValueType);
287 const char pattern = 0;
289 cudaError_t stat = cudaMemsetAsync(
290 *((ValueType**)buffer) + startingOffset, pattern, bytes, deviceStream.stream());
291 GMX_RELEASE_ASSERT(stat == cudaSuccess,
292 ("Couldn't clear the device buffer. " + gmx::getDeviceErrorString(stat)).c_str());
295 /*! \brief Check the validity of the device buffer.
297 * Checks if the buffer is not nullptr.
299 * \todo Add checks on the buffer size when it will be possible.
301 * \param[in] buffer Device buffer to be checked.
302 * \param[in] requiredSize Number of elements that the buffer will have to accommodate.
304 * \returns Whether the device buffer can be set.
307 gmx_unused static bool checkDeviceBuffer(DeviceBuffer<T> buffer, gmx_unused int requiredSize)
309 GMX_ASSERT(buffer != nullptr, "The device pointer is nullptr");
310 return buffer != nullptr;
313 //! Device texture wrapper.
314 using DeviceTexture = cudaTextureObject_t;
316 /*! \brief Create a texture object for an array of type ValueType.
318 * Creates the device buffer, copies data and binds texture object for an array of type ValueType.
320 * \todo Test if using textures is still relevant on modern hardware.
322 * \tparam ValueType Raw data type.
324 * \param[out] deviceBuffer Device buffer to store data in.
325 * \param[out] deviceTexture Device texture object to initialize.
326 * \param[in] hostBuffer Host buffer to get date from
327 * \param[in] numValues Number of elements in the buffer.
328 * \param[in] deviceContext GPU device context.
330 template<typename ValueType>
331 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
332 DeviceTexture* deviceTexture,
333 const ValueType* hostBuffer,
335 const DeviceContext& deviceContext)
341 GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
343 allocateDeviceBuffer(deviceBuffer, numValues, deviceContext);
345 const size_t sizeInBytes = numValues * sizeof(ValueType);
348 cudaMemcpy(*((ValueType**)deviceBuffer), hostBuffer, sizeInBytes, cudaMemcpyHostToDevice);
350 GMX_RELEASE_ASSERT(stat == cudaSuccess,
351 ("Synchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
353 if (!c_disableCudaTextures)
358 memset(&rd, 0, sizeof(rd));
359 rd.resType = cudaResourceTypeLinear;
360 rd.res.linear.devPtr = *deviceBuffer;
361 rd.res.linear.desc = cudaCreateChannelDesc<ValueType>();
362 rd.res.linear.sizeInBytes = sizeInBytes;
364 memset(&td, 0, sizeof(td));
365 td.readMode = cudaReadModeElementType;
366 stat = cudaCreateTextureObject(deviceTexture, &rd, &td, nullptr);
369 ("Binding of the texture object failed. " + gmx::getDeviceErrorString(stat)).c_str());
373 /*! \brief Unbind the texture and release the CUDA texture object.
375 * \tparam ValueType Raw data type
377 * \param[in,out] deviceBuffer Device buffer to store data in.
378 * \param[in,out] deviceTexture Device texture object to unbind.
380 template<typename ValueType>
381 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& deviceTexture)
383 if (!c_disableCudaTextures && deviceTexture && deviceBuffer)
385 cudaError_t stat = cudaDestroyTextureObject(deviceTexture);
388 ("Destruction of the texture object failed. " + gmx::getDeviceErrorString(stat)).c_str());
390 freeDeviceBuffer(deviceBuffer);