1*529f21eeSAaron LI /* $OpenBSD: arc4random_uniform.c,v 1.3 2019/01/20 02:59:07 bcook Exp $ */
2*529f21eeSAaron LI
3*529f21eeSAaron LI /*
4*529f21eeSAaron LI * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5*529f21eeSAaron LI *
6*529f21eeSAaron LI * Permission to use, copy, modify, and distribute this software for any
7*529f21eeSAaron LI * purpose with or without fee is hereby granted, provided that the above
8*529f21eeSAaron LI * copyright notice and this permission notice appear in all copies.
9*529f21eeSAaron LI *
10*529f21eeSAaron LI * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11*529f21eeSAaron LI * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12*529f21eeSAaron LI * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13*529f21eeSAaron LI * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14*529f21eeSAaron LI * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15*529f21eeSAaron LI * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16*529f21eeSAaron LI * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*529f21eeSAaron LI */
18*529f21eeSAaron LI
19*529f21eeSAaron LI #include <sys/types.h>
20*529f21eeSAaron LI #include <sys/libkern.h>
21*529f21eeSAaron LI
22*529f21eeSAaron LI /*
23*529f21eeSAaron LI * Calculate a uniformly distributed random number less than upper_bound
24*529f21eeSAaron LI * avoiding "modulo bias".
25*529f21eeSAaron LI *
26*529f21eeSAaron LI * Uniformity is achieved by generating new random numbers until the one
27*529f21eeSAaron LI * returned is outside the range [0, 2**32 % upper_bound). This
28*529f21eeSAaron LI * guarantees the selected random number will be inside
29*529f21eeSAaron LI * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
30*529f21eeSAaron LI * after reduction modulo upper_bound.
31*529f21eeSAaron LI */
32*529f21eeSAaron LI uint32_t
karc4random_uniform(uint32_t upper_bound)33*529f21eeSAaron LI karc4random_uniform(uint32_t upper_bound)
34*529f21eeSAaron LI {
35*529f21eeSAaron LI uint32_t r, min;
36*529f21eeSAaron LI
37*529f21eeSAaron LI if (upper_bound < 2)
38*529f21eeSAaron LI return 0;
39*529f21eeSAaron LI
40*529f21eeSAaron LI /* 2**32 % x == (2**32 - x) % x */
41*529f21eeSAaron LI min = -upper_bound % upper_bound;
42*529f21eeSAaron LI
43*529f21eeSAaron LI /*
44*529f21eeSAaron LI * This could theoretically loop forever but each retry has
45*529f21eeSAaron LI * p > 0.5 (worst case, usually far better) of selecting a
46*529f21eeSAaron LI * number inside the range we need, so it should rarely need
47*529f21eeSAaron LI * to re-roll.
48*529f21eeSAaron LI */
49*529f21eeSAaron LI for (;;) {
50*529f21eeSAaron LI r = karc4random();
51*529f21eeSAaron LI if (r >= min)
52*529f21eeSAaron LI break;
53*529f21eeSAaron LI }
54*529f21eeSAaron LI
55*529f21eeSAaron LI return r % upper_bound;
56*529f21eeSAaron LI }
57