@@ -91,6 +91,30 @@ static inline u32 get_random_u32_below(u32 ceil)
}
}
+/*
+ * Returns a random integer in the interval (floor, U32_MAX], with uniform
+ * distribution, suitable for all uses. Fastest when floor is a constant, but
+ * still fast for variable floor as well.
+ */
+static inline u32 get_random_u32_above(u32 floor)
+{
+ BUILD_BUG_ON_MSG(__builtin_constant_p(floor) && floor == U32_MAX,
+ "get_random_u32_above() must take floor < U32_MAX");
+ return floor + 1 + get_random_u32_below(U32_MAX - floor);
+}
+
+/*
+ * Returns a random integer in the interval [floor, ceil), with uniform
+ * distribution, suitable for all uses. Fastest when floor and ceil are
+ * constant, but still fast for variable floor and ceil as well.
+ */
+static inline u32 get_random_u32_between(u32 floor, u32 ceil)
+{
+ BUILD_BUG_ON_MSG(__builtin_constant_p(floor) && __builtin_constant_p(ceil) &&
+ floor >= ceil, "get_random_u32_above() must take floor < ceil");
+ return floor + get_random_u32_below(ceil - floor);
+}
+
/*
* On 64-bit architectures, protect against non-terminated C string overflows
* by zeroing out the first byte of the canary; this leaves 56 bits of entropy.
Now that we have get_random_u32_below(), it's trivial to make inline helpers to compute get_random_u32_above() and get_random_u32_between(), which will help clean up open coded loops and manual computations throughout the tree. Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com> --- include/linux/random.h | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)