1 /*
2  * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package jdk.random;
27 
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.random.RandomGenerator;
30 import jdk.internal.util.random.RandomSupport;
31 import jdk.internal.util.random.RandomSupport.AbstractSplittableWithBrineGenerator;
32 import jdk.internal.util.random.RandomSupport.RandomGeneratorProperties;
33 
34 /**
35  * A "splittable" pseudorandom number generator (PRNG) whose period
36  * is roughly 2<sup>256</sup>.  Class {@link L128X128MixRandom} implements
37  * interfaces {@link RandomGenerator} and {@link SplittableGenerator},
38  * and therefore supports methods for producing pseudorandomly chosen
39  * values of type {@code int}, {@code long}, {@code float}, {@code double},
40  * and {@code boolean} (and for producing streams of pseudorandomly chosen
41  * numbers of type {@code int}, {@code long}, and {@code double}),
42  * as well as methods for creating new split-off {@link L128X128MixRandom}
43  * objects or streams of such objects.
44  *
45  * <p>The {@link L128X128MixRandom} algorithm is a specific member of
46  * the LXM family of algorithms for pseudorandom number generators;
47  * for more information, see the documentation for package
48  * {@link jdk.random}.  Each instance of {@link L128X128MixRandom}
49  * has 256 bits of state plus one 128-bit instance-specific parameter.
50  *
51  * <p>If two instances of {@link L128X128MixRandom} are created with
52  * the same seed within the same program execution, and the same
53  * sequence of method calls is made for each, they will generate and
54  * return identical sequences of values.
55  *
56  * <p>As with {@link java.util.SplittableRandom}, instances of
57  * {@link L128X128MixRandom} are <em>not</em> thread-safe.  They are
58  * designed to be split, not shared, across threads (see the {@link #split}
59  * method). For example, a {@link java.util.concurrent.ForkJoinTask}
60  * fork/join-style computation using random numbers might include a
61  * construction of the form
62  * {@code new Subtask(someL128X128MixRandom.split()).fork()}.
63  *
64  * <p>This class provides additional methods for generating random
65  * streams, that employ the above techniques when used in
66  * {@code stream.parallel()} mode.
67  *
68  * <p>Instances of {@link L128X128MixRandom} are not cryptographically
69  * secure.  Consider instead using {@link java.security.SecureRandom}
70  * in security-sensitive applications. Additionally,
71  * default-constructed instances do not use a cryptographically random
72  * seed unless the {@linkplain System#getProperty system property}
73  * {@code java.util.secureRandomSeed} is set to {@code true}.
74  *
75  * @since   17
76  *
77  */
78 @RandomGeneratorProperties(
79         name = "L128X128MixRandom",
80         group = "LXM",
81         i = 128, j = 1, k = 128,
82         equidistribution = 1
83 )
84 public final class L128X128MixRandom extends AbstractSplittableWithBrineGenerator {
85 
86     /*
87      * Implementation Overview.
88      *
89      * The split operation uses the current generator to choose four new 64-bit
90      * long values that are then used to initialize the parameter `a` and the
91      * state variables `s`, `x0`, and `x1` for a newly constructed generator.
92      *
93      * With extremely high probability, no two generators so chosen
94      * will have the same `a` parameter, and testing has indicated
95      * that the values generated by two instances of {@link L128X128MixRandom}
96      * will be (approximately) independent if have different values for `a`.
97      *
98      * The default (no-argument) constructor, in essence, uses
99      * "defaultGen" to generate four new 64-bit values for the same
100      * purpose.  Multiple generators created in this way will certainly
101      * differ in their `a` parameters.  The defaultGen state must be accessed
102      * in a thread-safe manner, so we use an AtomicLong to represent
103      * this state.  To bootstrap the defaultGen, we start off using a
104      * seed based on current time unless the
105      * java.util.secureRandomSeed property is set. This serves as a
106      * slimmed-down (and insecure) variant of SecureRandom that also
107      * avoids stalls that may occur when using /dev/random.
108      *
109      * File organization: First static fields, then instance
110      * fields, then constructors, then instance methods.
111      */
112 
113     /* ---------------- static fields ---------------- */
114 
115     /**
116      * The seed generator for default constructors.
117      */
118     private static final AtomicLong defaultGen = new AtomicLong(RandomSupport.initialSeed());
119 
120     /*
121      * Low half of multiplier used in the LCG portion of the algorithm;
122      * the overall multiplier is (2**64 + ML).
123      * Chosen based on research by Sebastiano Vigna and Guy Steele (2019).
124      * The spectral scores for dimensions 2 through 8 for the multiplier 0x1d605bbb58c8abbfdLL
125      * are [0.991889, 0.907938, 0.830964, 0.837980, 0.780378, 0.797464, 0.761493].
126      */
127 
128     private static final long ML = 0xd605bbb58c8abbfdL;
129 
130     /* ---------------- instance fields ---------------- */
131 
132     /**
133      * The parameter that is used as an additive constant for the LCG.
134      * Must be odd (therefore al must be odd).
135      */
136     private final long ah, al;
137 
138     /**
139      * The per-instance state: sh and sl for the LCG; x0 and x1 for the XBG.
140      * At least one of x0 and x1 must be nonzero.
141      */
142     private long sh, sl, x0, x1;
143 
144     /* ---------------- constructors ---------------- */
145 
146     /**
147      * Basic constructor that initializes all fields from parameters.
148      * It then adjusts the field values if necessary to ensure that
149      * all constraints on the values of fields are met.
150      *
151      * @param ah high half of the additive parameter for the LCG
152      * @param al low half of the additive parameter for the LCG
153      * @param sh high half of the initial state for the LCG
154      * @param sl low half of the initial state for the LCG
155      * @param x0 first word of the initial state for the XBG
156      * @param x1 second word of the initial state for the XBG
157      */
L128X128MixRandom(long ah, long al, long sh, long sl, long x0, long x1)158     public L128X128MixRandom(long ah, long al, long sh, long sl, long x0, long x1) {
159         // Force a to be odd.
160         this.ah = ah;
161         this.al = al | 1;
162         this.sh = sh;
163         this.sl = sl;
164         this.x0 = x0;
165         this.x1 = x1;
166         // If x0 and x1 are both zero, we must choose nonzero values.
167         if ((x0 | x1) == 0) {
168        long v = sh;
169             // At least one of the two values generated here will be nonzero.
170             this.x0 = RandomSupport.mixStafford13(v += RandomSupport.GOLDEN_RATIO_64);
171             this.x1 = RandomSupport.mixStafford13(v + RandomSupport.GOLDEN_RATIO_64);
172         }
173     }
174 
175     /**
176      * Creates a new instance of {@link L128X128MixRandom} using the
177      * specified {@code long} value as the initial seed. Instances of
178      * {@link L128X128MixRandom} created with the same seed in the same
179      * program generate identical sequences of values.
180      *
181      * @param seed the initial seed
182      */
L128X128MixRandom(long seed)183     public L128X128MixRandom(long seed) {
184         // Using a value with irregularly spaced 1-bits to xor the seed
185         // argument tends to improve "pedestrian" seeds such as 0 or
186         // other small integers.  We may as well use SILVER_RATIO_64.
187         //
188         // The seed is hashed by mixMurmur64 to produce the `a` parameter.
189         // The seed is hashed by mixStafford13 to produce the initial `x0`,
190         // which will then be used to produce the first generated value.
191         // Then x1 is filled in as if by a SplitMix PRNG with
192         // GOLDEN_RATIO_64 as the gamma value and mixStafford13 as the mixer.
193         this(RandomSupport.mixMurmur64(seed ^= RandomSupport.SILVER_RATIO_64),
194              RandomSupport.mixMurmur64(seed += RandomSupport.GOLDEN_RATIO_64),
195              0,
196              1,
197              RandomSupport.mixStafford13(seed),
198              RandomSupport.mixStafford13(seed + RandomSupport.GOLDEN_RATIO_64));
199     }
200 
201     /**
202      * Creates a new instance of {@link L128X128MixRandom} that is likely to
203      * generate sequences of values that are statistically independent
204      * of those of any other instances in the current program execution,
205      * but may, and typically does, vary across program invocations.
206      */
L128X128MixRandom()207     public L128X128MixRandom() {
208         // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
209         this(defaultGen.getAndAdd(RandomSupport.GOLDEN_RATIO_64));
210     }
211 
212     /**
213      * Creates a new instance of {@link L128X128MixRandom} using the specified array of
214      * initial seed bytes. Instances of {@link L128X128MixRandom} created with the same
215      * seed array in the same program execution generate identical sequences of values.
216      *
217      * @param seed the initial seed
218      */
L128X128MixRandom(byte[] seed)219     public L128X128MixRandom(byte[] seed) {
220         // Convert the seed to 6 long values, of which the last 2 are not all zero.
221         long[] data = RandomSupport.convertSeedBytesToLongs(seed, 6, 2);
222         long ah = data[0], al = data[1], sh = data[2], sl = data[3], x0 = data[4], x1 = data[5];
223         // Force a to be odd.
224         this.ah = ah;
225         this.al = al | 1;
226         this.sh = sh;
227         this.sl = sl;
228         this.x0 = x0;
229         this.x1 = x1;
230     }
231 
232     /* ---------------- public methods ---------------- */
233 
234     @Override
split(SplittableGenerator source, long brine)235     public SplittableGenerator split(SplittableGenerator source, long brine) {
236        // Pick a new instance "at random", but use the brine for (the low half of) `a`.
237         return new L128X128MixRandom(source.nextLong(), brine << 1,
238                     source.nextLong(), source.nextLong(),
239                     source.nextLong(), source.nextLong());
240     }
241 
242     @Override
nextLong()243     public long nextLong() {
244        // Compute the result based on current state information
245        // (this allows the computation to be overlapped with state update).
246         final long result = RandomSupport.mixLea64(sh + x0);
247 
248        // Update the LCG subgenerator
249         // The LCG is, in effect, s = ((1LL << 64) + ML) * s + a, if only we had 128-bit arithmetic.
250         final long u = ML * sl;
251        // Note that Math.multiplyHigh computes the high half of the product of signed values,
252        // but what we need is the high half of the product of unsigned values; for this we use the
253        // formula "unsignedMultiplyHigh(a, b) = multiplyHigh(a, b) + ((a >> 63) & b) + ((b >> 63) & a)";
254        // in effect, each operand is added to the result iff the sign bit of the other operand is 1.
255        // (See Henry S. Warren, Jr., _Hacker's Delight_ (Second Edition), Addison-Wesley (2013),
256        // Section 8-3, p. 175; or see the First Edition, Addison-Wesley (2003), Section 8-3, p. 133.)
257        // If Math.unsignedMultiplyHigh(long, long) is ever implemented, the following line can become:
258        //         sh = (ML * sh) + Math.unsignedMultiplyHigh(ML, sl) + sl + ah;
259        // and this entire comment can be deleted.
260         sh = (ML * sh) + (Math.multiplyHigh(ML, sl) + ((ML >> 63) & sl) + ((sl >> 63) & ML)) + sl + ah;
261         sl = u + al;
262         if (Long.compareUnsigned(sl, u) < 0) ++sh;  // Handle the carry propagation from low half to high half.
263 
264         long q0 = x0, q1 = x1;
265        // Update the XBG subgenerator
266         {   // xoroshiro128v1_0
267             q1 ^= q0;
268             q0 = Long.rotateLeft(q0, 24);
269             q0 = q0 ^ q1 ^ (q1 << 16);
270             q1 = Long.rotateLeft(q1, 37);
271         }
272         x0 = q0; x1 = q1;
273 
274         return result;
275     }
276 
277 }
278