Skip to content

Commit 4c95236

Browse files
committed
prandom: make use of smaller types in prandom_u32_max
When possible at compile-time, make use of smaller types in prandom_u32_max(), so that we can use smaller batches from random.c, which in turn leads to a 2x or 4x performance boost. This makes a difference, for example, in kfence, which needs a fast stream of small numbers (booleans). At the same time, we use the occasion to update the old documentation on these functions. prandom_u32() and prandom_bytes() have direct replacements now in random.h, while prandom_u32_max() remains useful as a prandom.h function, since it's not cryptographically secure by virtue of not being evenly distributed. Cc: Dominik Brodowski <[email protected]> Acked-by: Marco Elver <[email protected]> Signed-off-by: Jason A. Donenfeld <[email protected]>
1 parent 585cd5f commit 4c95236

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

include/linux/prandom.h

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212
#include <linux/percpu.h>
1313
#include <linux/random.h>
1414

15+
/* Deprecated: use get_random_u32 instead. */
1516
static inline u32 prandom_u32(void)
1617
{
1718
return get_random_u32();
1819
}
1920

21+
/* Deprecated: use get_random_bytes instead. */
2022
static inline void prandom_bytes(void *buf, size_t nbytes)
2123
{
2224
return get_random_bytes(buf, nbytes);
@@ -37,17 +39,20 @@ void prandom_seed_full_state(struct rnd_state __percpu *pcpu_state);
3739
* prandom_u32_max - returns a pseudo-random number in interval [0, ep_ro)
3840
* @ep_ro: right open interval endpoint
3941
*
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.
42+
* Returns a pseudo-random number that is in interval [0, ep_ro). This is
43+
* useful when requesting a random index of an array containing ep_ro elements,
44+
* for example. The result is somewhat biased when ep_ro is not a power of 2,
45+
* so do not use this for cryptographic purposes.
4546
*
4647
* Returns: pseudo-random number in interval [0, ep_ro)
4748
*/
4849
static inline u32 prandom_u32_max(u32 ep_ro)
4950
{
50-
return (u32)(((u64) prandom_u32() * ep_ro) >> 32);
51+
if (__builtin_constant_p(ep_ro <= 1U << 8) && ep_ro <= 1U << 8)
52+
return (get_random_u8() * ep_ro) >> 8;
53+
if (__builtin_constant_p(ep_ro <= 1U << 16) && ep_ro <= 1U << 16)
54+
return (get_random_u16() * ep_ro) >> 16;
55+
return ((u64)get_random_u32() * ep_ro) >> 32;
5156
}
5257

5358
/*

0 commit comments

Comments
 (0)