Apply clang-format to source tree
[alexxy/gromacs.git] / src / gromacs / gpu_utils / pinning.cu
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018,2019, 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 /*! \internal \file
36  * \brief Implements functions for pinning memory to be suitable for
37  * efficient GPU transfers on CUDA.
38  *
39  * \author Mark Abraham <mark.j.abraham@gmail.com>
40  */
41 #include "gmxpre.h"
42
43 #include "pinning.h"
44
45 #include <cstddef>
46
47 #include <algorithm>
48
49 #include "gromacs/gpu_utils/cudautils.cuh"
50 #include "gromacs/utility/alignedallocator.h"
51 #include "gromacs/utility/exceptions.h"
52 #include "gromacs/utility/gmxassert.h"
53 #include "gromacs/utility/stringutil.h"
54
55 namespace gmx
56 {
57
58 #if !defined(NDEBUG) || defined(DOXYGEN)
59
60 //! Is \c ptr aligned on a boundary that is a multiple of \c bytes.
61 gmx_unused static inline bool isAligned(const void* ptr, size_t bytes)
62 {
63     return (reinterpret_cast<intptr_t>(ptr) % bytes) == 0;
64 }
65
66 #endif
67
68 void pinBuffer(void* pointer, std::size_t numBytes) noexcept
69 {
70     const char* errorMessage =
71             "Could not register the host memory for page locking for GPU transfers.";
72
73     GMX_ASSERT(isAligned(pointer, PageAlignedAllocationPolicy::alignment()),
74                formatString("%s Host memory needs to be page aligned.", errorMessage).c_str());
75
76     numBytes = std::max<size_t>(
77             1, numBytes); // C++11 3.7.4.1 gurantees that every pointer is different thus at least 1 byte
78
79     ensureNoPendingCudaError(errorMessage);
80     cudaError_t stat = cudaHostRegister(pointer, numBytes, cudaHostRegisterDefault);
81
82     // These errors can only arise from a coding error somewhere.
83     GMX_RELEASE_ASSERT(
84             stat != cudaErrorInvalidValue && stat != cudaErrorNotSupported
85                     && stat != cudaErrorHostMemoryAlreadyRegistered,
86             formatString("%s %s: %s", errorMessage, cudaGetErrorName(stat), cudaGetErrorString(stat))
87                     .c_str());
88
89     // We always handle the error, but if it's a type we didn't expect
90     // (e.g. because CUDA changes the set of errors it returns) then
91     // we should get a descriptive assertion in Debug mode so we know
92     // to fix our expectations.
93     GMX_ASSERT(stat != cudaErrorMemoryAllocation,
94                formatString("%s %s: %s which was an unexpected error", errorMessage,
95                             cudaGetErrorName(stat), cudaGetErrorString(stat))
96                        .c_str());
97
98     // It might be preferable to throw InternalError here, because the
99     // failing condition can only happen when GROMACS is used with a
100     // CUDA API that can return some other error code. But we can't
101     // engineer GROMACS to be forward-compatible with future CUDA
102     // versions, so if this proves to be a problem in practice, then
103     // GROMACS must be patched, or a supported CUDA version used.
104     GMX_RELEASE_ASSERT(stat == cudaSuccess, formatString("%s %s: %s", errorMessage,
105                                                          cudaGetErrorName(stat), cudaGetErrorString(stat))
106                                                     .c_str());
107 }
108
109 void unpinBuffer(void* pointer) noexcept
110 {
111     const char* errorMessage = "Could not unregister pinned host memory used for GPU transfers.";
112
113     GMX_ASSERT(pointer != nullptr,
114                formatString("%s pointer should not be nullptr when pinned.", errorMessage).c_str());
115
116     ensureNoPendingCudaError(errorMessage);
117     cudaError_t stat = cudaHostUnregister(pointer);
118     // These errors can only arise from a coding error somewhere.
119     GMX_RELEASE_ASSERT(
120             stat != cudaErrorInvalidValue && stat != cudaErrorHostMemoryNotRegistered,
121             formatString("%s %s: %s", errorMessage, cudaGetErrorName(stat), cudaGetErrorString(stat))
122                     .c_str());
123     // If there's an error whose type we didn't expect (e.g. because a
124     // future CUDA changes the set of errors it returns) then we
125     // should assert, because our code is wrong.
126     //
127     // The approach differs from that in pin() because we might
128     // unpin() from a destructor, in which case any attempt to throw
129     // an uncaught exception would anyway terminate the program. A
130     // release assertion is a better behaviour than that.
131     GMX_RELEASE_ASSERT(stat == cudaSuccess,
132                        formatString("%s %s: %s which was an unexpected error", errorMessage,
133                                     cudaGetErrorName(stat), cudaGetErrorString(stat))
134                                .c_str());
135 }
136
137 } // namespace gmx