2 * include/linux/random.h
4 * Include file for the random number generator.
6 #ifndef _LINUX_RANDOM_H
7 #define _LINUX_RANDOM_H
10 #include <sys/syscall.h>
11 #include <linux/bug.h>
12 #include <linux/log2.h>
15 static inline int getrandom(void *buf, size_t buflen, unsigned int flags)
17 return syscall(SYS_getrandom, buf, buflen, flags);
20 extern int urandom_fd;
22 static inline int getrandom(void *buf, size_t buflen, unsigned int flags)
24 return read(urandom_fd, buf, buflen);
28 static inline void get_random_bytes(void *buf, int nbytes)
30 BUG_ON(getrandom(buf, nbytes, 0) != nbytes);
33 #define get_random_type(type) \
34 static inline type get_random_##type(void) \
38 get_random_bytes(&v, sizeof(v)); \
43 get_random_type(long);
49 static inline u32 get_random_u32_below(u32 ceil)
54 if (ceil <= 1U << 8) {
55 u32 mult = ceil * get_random_u8();
56 if (likely(is_power_of_2(ceil) || (u8)mult >= (1U << 8) % ceil))
58 } else if (ceil <= 1U << 16) {
59 u32 mult = ceil * get_random_u16();
60 if (likely(is_power_of_2(ceil) || (u16)mult >= (1U << 16) % ceil))
63 u64 mult = (u64)ceil * get_random_u32();
64 if (likely(is_power_of_2(ceil) || (u32)mult >= -ceil % ceil))
70 #endif /* _LINUX_RANDOM_H */