Fix broken random seed generation.
[alexxy/gromacs.git] / src / gromacs / random / seed.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016,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.
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
36 #include "gmxpre.h"
37
38 #include "seed.h"
39
40 #include <chrono>
41
42 #include "gromacs/utility/basedefinitions.h"
43 #include "gromacs/utility/fatalerror.h"
44
45 namespace gmx
46 {
47
48
49 /*! \brief Check if the RDRAND random device functioning correctly
50  *
51  * Due to a bug in AMD Ryzen microcode, RDRAND may always return -1 (0xFFFFFFFF).
52  * To avoid that, fall back to using PRNG instead of RDRAND if this happens.
53  *
54  * \returns The result of the checks.
55  */
56 static bool checkIfRandomDeviceIsFunctional()
57 {
58     std::random_device rd;
59
60     uint64_t randomNumber1 = static_cast<uint64_t>(rd());
61     uint64_t randomNumber2 = static_cast<uint64_t>(rd());
62
63     // Due to a bug in AMD Ryzen microcode, RDRAND may always return -1 (0xFFFFFFFF).
64     // To avoid that, fall back to using PRNG instead of RDRAND if this happens.
65     if (randomNumber1 == 0xFFFFFFFF && randomNumber2 == 0xFFFFFFFF)
66     {
67         if (debug)
68         {
69             fprintf(debug,
70                     "Hardware random number generator (RDRAND) returned -1 (0xFFFFFFFF) twice in\n"
71                     "a row. This may be due to a known bug in AMD Ryzen microcode.");
72         }
73         return false;
74     }
75     return true;
76 }
77
78 /*! \brief Get the next pure or pseudo-random number
79  *
80  * Returns the next random number taken from the hardware generator or from PRNG.
81  *
82  * \param[in] gen  Pseudo-random/random numbers generator/device to use.
83  *
84  * \return Random or pseudo-random number.
85  */
86 template<typename GeneratorType>
87 static uint64_t makeRandomSeedInternal(GeneratorType& gen)
88 {
89     constexpr std::size_t resultBits = std::numeric_limits<uint64_t>::digits;
90     constexpr std::size_t numBitsInRandomNumber =
91             std::numeric_limits<typename GeneratorType::result_type>::digits;
92
93     uint64_t result = static_cast<uint64_t>(gen());
94     // This is needed so that compiler understands that what follows is a dead branch
95     // and not complains about shift count larger than number of bits in the result.
96     constexpr std::size_t shiftCount = (resultBits < numBitsInRandomNumber) ? numBitsInRandomNumber : 0;
97     for (std::size_t bits = numBitsInRandomNumber; bits < resultBits; bits += numBitsInRandomNumber)
98     {
99         result = (result << shiftCount) | static_cast<uint64_t>(gen());
100     }
101     return result;
102 }
103
104 uint64_t makeRandomSeed()
105 {
106     bool useRdrand = checkIfRandomDeviceIsFunctional();
107     if (useRdrand)
108     {
109         std::random_device rd;
110         return makeRandomSeedInternal(rd);
111     }
112     else
113     {
114         int64_t microsecondsSinceEpoch = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
115         std::mt19937_64 prng(microsecondsSinceEpoch);
116         return makeRandomSeedInternal(prng);
117     }
118 }
119
120
121 } // namespace gmx