Skip to content

Commit a6cdc1c

Browse files
Daniel Borkmannlongsleep
authored andcommitted
random32: add prandom_u32_max and convert open coded users
commit f337db64af059c9a94278a8b0ab97d87259ff62f upstream. Many functions have open coded a function that returns a random number in range [0,N-1]. Under the assumption that we have a PRNG such as taus113 with being well distributed in [0, ~0U] space, we can implement such a function as uword t = (n*m')>>32, where m' is a random number obtained from PRNG, n the right open interval border and t our resulting random number, with n,m',t in u32 universe. Lets go with Joe and simply call it prandom_u32_max(), although technically we have an right open interval endpoint, but that we have documented. Other users can further be migrated to the new prandom_u32_max() function later on; for now, we need to make sure to migrate reciprocal_divide() users for the reciprocal_divide() follow-up fixup since their function signatures are going to change. Joint work with Hannes Frederic Sowa. Signed-off-by: Simon Eisenmann <simon@longsleep.org> Cc: Jakub Zawadzki <darkjames-ws@darkjames.pl> Cc: Eric Dumazet <eric.dumazet@gmail.com> Cc: linux-kernel@vger.kernel.org Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: Daniel Borkmann <dborkman@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net>
1 parent 3670ff4 commit a6cdc1c

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

include/linux/random.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,23 @@ void prandom_seed(u32 seed);
3333
u32 prandom_u32_state(struct rnd_state *);
3434
void prandom_bytes_state(struct rnd_state *state, void *buf, int nbytes);
3535

36+
/**
37+
* prandom_u32_max - returns a pseudo-random number in interval [0, ep_ro)
38+
* @ep_ro: right open interval endpoint
39+
*
40+
* Returns a pseudo-random number that is in interval [0, ep_ro). Note
41+
* that the result depends on PRNG being well distributed in [0, ~0U]
42+
* u32 space. Here we use maximally equidistributed combined Tausworthe
43+
* generator, that is, prandom_u32(). This is useful when requesting a
44+
* random index of an array containing ep_ro elements, for example.
45+
*
46+
* Returns: pseudo-random number in interval [0, ep_ro)
47+
*/
48+
static inline u32 prandom_u32_max(u32 ep_ro)
49+
{
50+
return (u32)(((u64) prandom_u32() * ep_ro) >> 32);
51+
}
52+
3653
/*
3754
* Handle minimum values for seeds
3855
*/

0 commit comments

Comments
 (0)