xref: /linux/drivers/char/random.c (revision b240bab51888d5c8e389dc179d7c67a869587148)
1a07fdae3SJason A. Donenfeld // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
21da177e4SLinus Torvalds /*
39f9eff85SJason A. Donenfeld  * Copyright (C) 2017-2022 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
49e95ce27SMatt Mackall  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
55f75d9f3SJason A. Donenfeld  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved.
61da177e4SLinus Torvalds  *
75f75d9f3SJason A. Donenfeld  * This driver produces cryptographically secure pseudorandom data. It is divided
85f75d9f3SJason A. Donenfeld  * into roughly six sections, each with a section header:
91da177e4SLinus Torvalds  *
105f75d9f3SJason A. Donenfeld  *   - Initialization and readiness waiting.
115f75d9f3SJason A. Donenfeld  *   - Fast key erasure RNG, the "crng".
125f75d9f3SJason A. Donenfeld  *   - Entropy accumulation and extraction routines.
135f75d9f3SJason A. Donenfeld  *   - Entropy collection routines.
145f75d9f3SJason A. Donenfeld  *   - Userspace reader/writer interfaces.
155f75d9f3SJason A. Donenfeld  *   - Sysctl interface.
161da177e4SLinus Torvalds  *
175f75d9f3SJason A. Donenfeld  * The high level overview is that there is one input pool, into which
18e85c0fc1SJason A. Donenfeld  * various pieces of data are hashed. Prior to initialization, some of that
19e85c0fc1SJason A. Donenfeld  * data is then "credited" as having a certain number of bits of entropy.
20e85c0fc1SJason A. Donenfeld  * When enough bits of entropy are available, the hash is finalized and
21e85c0fc1SJason A. Donenfeld  * handed as a key to a stream cipher that expands it indefinitely for
22e85c0fc1SJason A. Donenfeld  * various consumers. This key is periodically refreshed as the various
23e85c0fc1SJason A. Donenfeld  * entropy collectors, described below, add data to the input pool.
241da177e4SLinus Torvalds  */
251da177e4SLinus Torvalds 
2612cd53afSYangtao Li #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2712cd53afSYangtao Li 
281da177e4SLinus Torvalds #include <linux/utsname.h>
291da177e4SLinus Torvalds #include <linux/module.h>
301da177e4SLinus Torvalds #include <linux/kernel.h>
311da177e4SLinus Torvalds #include <linux/major.h>
321da177e4SLinus Torvalds #include <linux/string.h>
331da177e4SLinus Torvalds #include <linux/fcntl.h>
341da177e4SLinus Torvalds #include <linux/slab.h>
351da177e4SLinus Torvalds #include <linux/random.h>
361da177e4SLinus Torvalds #include <linux/poll.h>
371da177e4SLinus Torvalds #include <linux/init.h>
381da177e4SLinus Torvalds #include <linux/fs.h>
39322cbb50SChristoph Hellwig #include <linux/blkdev.h>
401da177e4SLinus Torvalds #include <linux/interrupt.h>
4127ac792cSAndrea Righi #include <linux/mm.h>
42dd0f0cf5SMichael Ellerman #include <linux/nodemask.h>
431da177e4SLinus Torvalds #include <linux/spinlock.h>
44c84dbf61STorsten Duwe #include <linux/kthread.h>
451da177e4SLinus Torvalds #include <linux/percpu.h>
46775f4b29STheodore Ts'o #include <linux/ptrace.h>
476265e169STheodore Ts'o #include <linux/workqueue.h>
48d178a1ebSYinghai Lu #include <linux/irq.h>
494e00b339STheodore Ts'o #include <linux/ratelimit.h>
50c6e9d6f3STheodore Ts'o #include <linux/syscalls.h>
51c6e9d6f3STheodore Ts'o #include <linux/completion.h>
528da4b8c4SAndy Shevchenko #include <linux/uuid.h>
5387e7d5abSJason A. Donenfeld #include <linux/uaccess.h>
54b7b67d13SJason A. Donenfeld #include <linux/suspend.h>
55e73aaae2SJason A. Donenfeld #include <linux/siphash.h>
561ca1b917SEric Biggers #include <crypto/chacha.h>
579f9eff85SJason A. Donenfeld #include <crypto/blake2s.h>
581da177e4SLinus Torvalds #include <asm/processor.h>
591da177e4SLinus Torvalds #include <asm/irq.h>
60775f4b29STheodore Ts'o #include <asm/irq_regs.h>
611da177e4SLinus Torvalds #include <asm/io.h>
621da177e4SLinus Torvalds 
635f1bb112SJason A. Donenfeld /*********************************************************************
645f1bb112SJason A. Donenfeld  *
655f1bb112SJason A. Donenfeld  * Initialization and readiness waiting.
665f1bb112SJason A. Donenfeld  *
675f1bb112SJason A. Donenfeld  * Much of the RNG infrastructure is devoted to various dependencies
685f1bb112SJason A. Donenfeld  * being able to wait until the RNG has collected enough entropy and
695f1bb112SJason A. Donenfeld  * is ready for safe consumption.
705f1bb112SJason A. Donenfeld  *
715f1bb112SJason A. Donenfeld  *********************************************************************/
725f1bb112SJason A. Donenfeld 
735f1bb112SJason A. Donenfeld /*
745f1bb112SJason A. Donenfeld  * crng_init is protected by base_crng->lock, and only increases
75e3d2c5e7SJason A. Donenfeld  * its value (from empty->early->ready).
765f1bb112SJason A. Donenfeld  */
77e3d2c5e7SJason A. Donenfeld static enum {
78e3d2c5e7SJason A. Donenfeld 	CRNG_EMPTY = 0, /* Little to no entropy collected */
79e3d2c5e7SJason A. Donenfeld 	CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */
80e3d2c5e7SJason A. Donenfeld 	CRNG_READY = 2  /* Fully initialized with POOL_READY_BITS collected */
81f5bda35fSJason A. Donenfeld } crng_init __read_mostly = CRNG_EMPTY;
82f5bda35fSJason A. Donenfeld static DEFINE_STATIC_KEY_FALSE(crng_is_ready);
83f5bda35fSJason A. Donenfeld #define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)
84e3d2c5e7SJason A. Donenfeld /* Various types of waiters for crng_init->CRNG_READY transition. */
855f1bb112SJason A. Donenfeld static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
865f1bb112SJason A. Donenfeld static struct fasync_struct *fasync;
875f1bb112SJason A. Donenfeld 
885f1bb112SJason A. Donenfeld /* Control how we warn userspace. */
890313bc27SLinus Torvalds static struct ratelimit_state urandom_warning =
90c01d4d0aSJason A. Donenfeld 	RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);
91cc1e127bSJason A. Donenfeld static int ratelimit_disable __read_mostly =
92cc1e127bSJason A. Donenfeld 	IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
935f1bb112SJason A. Donenfeld module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
945f1bb112SJason A. Donenfeld MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
955f1bb112SJason A. Donenfeld 
965f1bb112SJason A. Donenfeld /*
975f1bb112SJason A. Donenfeld  * Returns whether or not the input pool has been seeded and thus guaranteed
980313bc27SLinus Torvalds  * to supply cryptographically secure random numbers. This applies to: the
99a890d1c6SJason A. Donenfeld  * /dev/urandom device, the get_random_bytes function, and the get_random_{u8,
100de492c83SJason A. Donenfeld  * u16,u32,u64,long} family of functions.
1015f1bb112SJason A. Donenfeld  *
1025f1bb112SJason A. Donenfeld  * Returns: true if the input pool has been seeded.
1035f1bb112SJason A. Donenfeld  *          false if the input pool has not been seeded.
1045f1bb112SJason A. Donenfeld  */
1055f1bb112SJason A. Donenfeld bool rng_is_initialized(void)
1065f1bb112SJason A. Donenfeld {
1075f1bb112SJason A. Donenfeld 	return crng_ready();
1085f1bb112SJason A. Donenfeld }
1095f1bb112SJason A. Donenfeld EXPORT_SYMBOL(rng_is_initialized);
1105f1bb112SJason A. Donenfeld 
111560181c2SJason A. Donenfeld static void __cold crng_set_ready(struct work_struct *work)
112f5bda35fSJason A. Donenfeld {
113f5bda35fSJason A. Donenfeld 	static_branch_enable(&crng_is_ready);
114f5bda35fSJason A. Donenfeld }
115f5bda35fSJason A. Donenfeld 
1165f1bb112SJason A. Donenfeld /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
1175f1bb112SJason A. Donenfeld static void try_to_generate_entropy(void);
1185f1bb112SJason A. Donenfeld 
1195f1bb112SJason A. Donenfeld /*
1205f1bb112SJason A. Donenfeld  * Wait for the input pool to be seeded and thus guaranteed to supply
1210313bc27SLinus Torvalds  * cryptographically secure random numbers. This applies to: the /dev/urandom
122a890d1c6SJason A. Donenfeld  * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64,
123*b240bab5SJason A. Donenfeld  * long} family of functions. Using any of these functions without first
124a890d1c6SJason A. Donenfeld  * calling this function forfeits the guarantee of security.
1255f1bb112SJason A. Donenfeld  *
1265f1bb112SJason A. Donenfeld  * Returns: 0 if the input pool has been seeded.
1275f1bb112SJason A. Donenfeld  *          -ERESTARTSYS if the function was interrupted by a signal.
1285f1bb112SJason A. Donenfeld  */
1295f1bb112SJason A. Donenfeld int wait_for_random_bytes(void)
1305f1bb112SJason A. Donenfeld {
131a96cfe2dSJason A. Donenfeld 	while (!crng_ready()) {
1325f1bb112SJason A. Donenfeld 		int ret;
1333e504d20SJason A. Donenfeld 
1343e504d20SJason A. Donenfeld 		try_to_generate_entropy();
1355f1bb112SJason A. Donenfeld 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
1365f1bb112SJason A. Donenfeld 		if (ret)
1375f1bb112SJason A. Donenfeld 			return ret > 0 ? 0 : ret;
138a96cfe2dSJason A. Donenfeld 	}
1395f1bb112SJason A. Donenfeld 	return 0;
1405f1bb112SJason A. Donenfeld }
1415f1bb112SJason A. Donenfeld EXPORT_SYMBOL(wait_for_random_bytes);
1425f1bb112SJason A. Donenfeld 
143cc1e127bSJason A. Donenfeld #define warn_unseeded_randomness() \
144560181c2SJason A. Donenfeld 	if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \
145560181c2SJason A. Donenfeld 		printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n", \
146560181c2SJason A. Donenfeld 				__func__, (void *)_RET_IP_, crng_init)
1475f1bb112SJason A. Donenfeld 
1485f1bb112SJason A. Donenfeld 
1493655adc7SJason A. Donenfeld /*********************************************************************
1503655adc7SJason A. Donenfeld  *
1513655adc7SJason A. Donenfeld  * Fast key erasure RNG, the "crng".
1523655adc7SJason A. Donenfeld  *
1533655adc7SJason A. Donenfeld  * These functions expand entropy from the entropy extractor into
1543655adc7SJason A. Donenfeld  * long streams for external consumption using the "fast key erasure"
1553655adc7SJason A. Donenfeld  * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
1563655adc7SJason A. Donenfeld  *
1573655adc7SJason A. Donenfeld  * There are a few exported interfaces for use by other drivers:
1583655adc7SJason A. Donenfeld  *
159a1940263SJason A. Donenfeld  *	void get_random_bytes(void *buf, size_t len)
160a890d1c6SJason A. Donenfeld  *	u8 get_random_u8()
161a890d1c6SJason A. Donenfeld  *	u16 get_random_u16()
1623655adc7SJason A. Donenfeld  *	u32 get_random_u32()
163e9a688bcSJason A. Donenfeld  *	u32 get_random_u32_below(u32 ceil)
1647f576b25SJason A. Donenfeld  *	u32 get_random_u32_above(u32 floor)
1657f576b25SJason A. Donenfeld  *	u32 get_random_u32_inclusive(u32 floor, u32 ceil)
1663655adc7SJason A. Donenfeld  *	u64 get_random_u64()
1673655adc7SJason A. Donenfeld  *	unsigned long get_random_long()
1683655adc7SJason A. Donenfeld  *
1693655adc7SJason A. Donenfeld  * These interfaces will return the requested number of random bytes
1700313bc27SLinus Torvalds  * into the given buffer or as a return value. This is equivalent to
171de492c83SJason A. Donenfeld  * a read from /dev/urandom. The u8, u16, u32, u64, long family of
172de492c83SJason A. Donenfeld  * functions may be higher performance for one-off random integers,
173de492c83SJason A. Donenfeld  * because they do a bit of buffering and do not invoke reseeding
174de492c83SJason A. Donenfeld  * until the buffer is emptied.
1753655adc7SJason A. Donenfeld  *
1763655adc7SJason A. Donenfeld  *********************************************************************/
1773655adc7SJason A. Donenfeld 
178e85c0fc1SJason A. Donenfeld enum {
179e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_START_INTERVAL = HZ,
180e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_INTERVAL = 60 * HZ
181e85c0fc1SJason A. Donenfeld };
1823655adc7SJason A. Donenfeld 
1833655adc7SJason A. Donenfeld static struct {
1843655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
1853655adc7SJason A. Donenfeld 	unsigned long birth;
1863655adc7SJason A. Donenfeld 	unsigned long generation;
1873655adc7SJason A. Donenfeld 	spinlock_t lock;
1883655adc7SJason A. Donenfeld } base_crng = {
1893655adc7SJason A. Donenfeld 	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
1903655adc7SJason A. Donenfeld };
1913655adc7SJason A. Donenfeld 
1923655adc7SJason A. Donenfeld struct crng {
1933655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
1943655adc7SJason A. Donenfeld 	unsigned long generation;
1953655adc7SJason A. Donenfeld 	local_lock_t lock;
1963655adc7SJason A. Donenfeld };
1973655adc7SJason A. Donenfeld 
1983655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct crng, crngs) = {
1993655adc7SJason A. Donenfeld 	.generation = ULONG_MAX,
2003655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(crngs.lock),
2013655adc7SJason A. Donenfeld };
2023655adc7SJason A. Donenfeld 
203e85c0fc1SJason A. Donenfeld /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
204a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len);
2053655adc7SJason A. Donenfeld 
206e85c0fc1SJason A. Donenfeld /* This extracts a new crng key from the input pool. */
207e85c0fc1SJason A. Donenfeld static void crng_reseed(void)
2083655adc7SJason A. Donenfeld {
2093655adc7SJason A. Donenfeld 	unsigned long flags;
2103655adc7SJason A. Donenfeld 	unsigned long next_gen;
2113655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2123655adc7SJason A. Donenfeld 
213e85c0fc1SJason A. Donenfeld 	extract_entropy(key, sizeof(key));
2143655adc7SJason A. Donenfeld 
2153655adc7SJason A. Donenfeld 	/*
2163655adc7SJason A. Donenfeld 	 * We copy the new key into the base_crng, overwriting the old one,
2173655adc7SJason A. Donenfeld 	 * and update the generation counter. We avoid hitting ULONG_MAX,
2183655adc7SJason A. Donenfeld 	 * because the per-cpu crngs are initialized to ULONG_MAX, so this
2193655adc7SJason A. Donenfeld 	 * forces new CPUs that come online to always initialize.
2203655adc7SJason A. Donenfeld 	 */
2213655adc7SJason A. Donenfeld 	spin_lock_irqsave(&base_crng.lock, flags);
2223655adc7SJason A. Donenfeld 	memcpy(base_crng.key, key, sizeof(base_crng.key));
2233655adc7SJason A. Donenfeld 	next_gen = base_crng.generation + 1;
2243655adc7SJason A. Donenfeld 	if (next_gen == ULONG_MAX)
2253655adc7SJason A. Donenfeld 		++next_gen;
2263655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.generation, next_gen);
2273655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.birth, jiffies);
228f5bda35fSJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready))
229e3d2c5e7SJason A. Donenfeld 		crng_init = CRNG_READY;
2303655adc7SJason A. Donenfeld 	spin_unlock_irqrestore(&base_crng.lock, flags);
2313655adc7SJason A. Donenfeld 	memzero_explicit(key, sizeof(key));
2323655adc7SJason A. Donenfeld }
2333655adc7SJason A. Donenfeld 
2343655adc7SJason A. Donenfeld /*
2353655adc7SJason A. Donenfeld  * This generates a ChaCha block using the provided key, and then
2367f637be4SJason A. Donenfeld  * immediately overwrites that key with half the block. It returns
2373655adc7SJason A. Donenfeld  * the resultant ChaCha state to the user, along with the second
2383655adc7SJason A. Donenfeld  * half of the block containing 32 bytes of random data that may
2393655adc7SJason A. Donenfeld  * be used; random_data_len may not be greater than 32.
2408717627dSJason A. Donenfeld  *
2418717627dSJason A. Donenfeld  * The returned ChaCha state contains within it a copy of the old
2428717627dSJason A. Donenfeld  * key value, at index 4, so the state should always be zeroed out
2438717627dSJason A. Donenfeld  * immediately after using in order to maintain forward secrecy.
2448717627dSJason A. Donenfeld  * If the state cannot be erased in a timely manner, then it is
2458717627dSJason A. Donenfeld  * safer to set the random_data parameter to &chacha_state[4] so
2468717627dSJason A. Donenfeld  * that this function overwrites it before returning.
2473655adc7SJason A. Donenfeld  */
2483655adc7SJason A. Donenfeld static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
2493655adc7SJason A. Donenfeld 				  u32 chacha_state[CHACHA_STATE_WORDS],
2503655adc7SJason A. Donenfeld 				  u8 *random_data, size_t random_data_len)
2513655adc7SJason A. Donenfeld {
2523655adc7SJason A. Donenfeld 	u8 first_block[CHACHA_BLOCK_SIZE];
2533655adc7SJason A. Donenfeld 
2543655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
2553655adc7SJason A. Donenfeld 
2563655adc7SJason A. Donenfeld 	chacha_init_consts(chacha_state);
2573655adc7SJason A. Donenfeld 	memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
2583655adc7SJason A. Donenfeld 	memset(&chacha_state[12], 0, sizeof(u32) * 4);
2593655adc7SJason A. Donenfeld 	chacha20_block(chacha_state, first_block);
2603655adc7SJason A. Donenfeld 
2613655adc7SJason A. Donenfeld 	memcpy(key, first_block, CHACHA_KEY_SIZE);
2628717627dSJason A. Donenfeld 	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
2633655adc7SJason A. Donenfeld 	memzero_explicit(first_block, sizeof(first_block));
2643655adc7SJason A. Donenfeld }
2653655adc7SJason A. Donenfeld 
2663655adc7SJason A. Donenfeld /*
267745558f9SDominik Brodowski  * Return the interval until the next reseeding, which is normally
268745558f9SDominik Brodowski  * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval
269e85c0fc1SJason A. Donenfeld  * proportional to the uptime.
2707a7ff644SJason A. Donenfeld  */
271745558f9SDominik Brodowski static unsigned int crng_reseed_interval(void)
2727a7ff644SJason A. Donenfeld {
2737a7ff644SJason A. Donenfeld 	static bool early_boot = true;
2747a7ff644SJason A. Donenfeld 
2757a7ff644SJason A. Donenfeld 	if (unlikely(READ_ONCE(early_boot))) {
2767a7ff644SJason A. Donenfeld 		time64_t uptime = ktime_get_seconds();
2777a7ff644SJason A. Donenfeld 		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
2787a7ff644SJason A. Donenfeld 			WRITE_ONCE(early_boot, false);
2797a7ff644SJason A. Donenfeld 		else
280745558f9SDominik Brodowski 			return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
2817a7ff644SJason A. Donenfeld 				     (unsigned int)uptime / 2 * HZ);
2827a7ff644SJason A. Donenfeld 	}
283745558f9SDominik Brodowski 	return CRNG_RESEED_INTERVAL;
2847a7ff644SJason A. Donenfeld }
2857a7ff644SJason A. Donenfeld 
2867a7ff644SJason A. Donenfeld /*
2873655adc7SJason A. Donenfeld  * This function returns a ChaCha state that you may use for generating
2883655adc7SJason A. Donenfeld  * random data. It also returns up to 32 bytes on its own of random data
2893655adc7SJason A. Donenfeld  * that may be used; random_data_len may not be greater than 32.
2903655adc7SJason A. Donenfeld  */
2913655adc7SJason A. Donenfeld static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
2923655adc7SJason A. Donenfeld 			    u8 *random_data, size_t random_data_len)
2933655adc7SJason A. Donenfeld {
2943655adc7SJason A. Donenfeld 	unsigned long flags;
2953655adc7SJason A. Donenfeld 	struct crng *crng;
2963655adc7SJason A. Donenfeld 
2973655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
2983655adc7SJason A. Donenfeld 
2993655adc7SJason A. Donenfeld 	/*
3003655adc7SJason A. Donenfeld 	 * For the fast path, we check whether we're ready, unlocked first, and
3013655adc7SJason A. Donenfeld 	 * then re-check once locked later. In the case where we're really not
3025c3b747eSJason A. Donenfeld 	 * ready, we do fast key erasure with the base_crng directly, extracting
303e3d2c5e7SJason A. Donenfeld 	 * when crng_init is CRNG_EMPTY.
3043655adc7SJason A. Donenfeld 	 */
305a96cfe2dSJason A. Donenfeld 	if (!crng_ready()) {
3063655adc7SJason A. Donenfeld 		bool ready;
3073655adc7SJason A. Donenfeld 
3083655adc7SJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
3093655adc7SJason A. Donenfeld 		ready = crng_ready();
3105c3b747eSJason A. Donenfeld 		if (!ready) {
311e3d2c5e7SJason A. Donenfeld 			if (crng_init == CRNG_EMPTY)
3125c3b747eSJason A. Donenfeld 				extract_entropy(base_crng.key, sizeof(base_crng.key));
3133655adc7SJason A. Donenfeld 			crng_fast_key_erasure(base_crng.key, chacha_state,
3143655adc7SJason A. Donenfeld 					      random_data, random_data_len);
3155c3b747eSJason A. Donenfeld 		}
3163655adc7SJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
3173655adc7SJason A. Donenfeld 		if (!ready)
3183655adc7SJason A. Donenfeld 			return;
3193655adc7SJason A. Donenfeld 	}
3203655adc7SJason A. Donenfeld 
3213655adc7SJason A. Donenfeld 	/*
322e85c0fc1SJason A. Donenfeld 	 * If the base_crng is old enough, we reseed, which in turn bumps the
323e85c0fc1SJason A. Donenfeld 	 * generation counter that we check below.
3243655adc7SJason A. Donenfeld 	 */
325745558f9SDominik Brodowski 	if (unlikely(time_is_before_jiffies(READ_ONCE(base_crng.birth) + crng_reseed_interval())))
326e85c0fc1SJason A. Donenfeld 		crng_reseed();
3273655adc7SJason A. Donenfeld 
3283655adc7SJason A. Donenfeld 	local_lock_irqsave(&crngs.lock, flags);
3293655adc7SJason A. Donenfeld 	crng = raw_cpu_ptr(&crngs);
3303655adc7SJason A. Donenfeld 
3313655adc7SJason A. Donenfeld 	/*
3323655adc7SJason A. Donenfeld 	 * If our per-cpu crng is older than the base_crng, then it means
3333655adc7SJason A. Donenfeld 	 * somebody reseeded the base_crng. In that case, we do fast key
3343655adc7SJason A. Donenfeld 	 * erasure on the base_crng, and use its output as the new key
3353655adc7SJason A. Donenfeld 	 * for our per-cpu crng. This brings us up to date with base_crng.
3363655adc7SJason A. Donenfeld 	 */
3373655adc7SJason A. Donenfeld 	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
3383655adc7SJason A. Donenfeld 		spin_lock(&base_crng.lock);
3393655adc7SJason A. Donenfeld 		crng_fast_key_erasure(base_crng.key, chacha_state,
3403655adc7SJason A. Donenfeld 				      crng->key, sizeof(crng->key));
3413655adc7SJason A. Donenfeld 		crng->generation = base_crng.generation;
3423655adc7SJason A. Donenfeld 		spin_unlock(&base_crng.lock);
3433655adc7SJason A. Donenfeld 	}
3443655adc7SJason A. Donenfeld 
3453655adc7SJason A. Donenfeld 	/*
3463655adc7SJason A. Donenfeld 	 * Finally, when we've made it this far, our per-cpu crng has an up
3473655adc7SJason A. Donenfeld 	 * to date key, and we can do fast key erasure with it to produce
3483655adc7SJason A. Donenfeld 	 * some random data and a ChaCha state for the caller. All other
3493655adc7SJason A. Donenfeld 	 * branches of this function are "unlikely", so most of the time we
3503655adc7SJason A. Donenfeld 	 * should wind up here immediately.
3513655adc7SJason A. Donenfeld 	 */
3523655adc7SJason A. Donenfeld 	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
3533655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&crngs.lock, flags);
3543655adc7SJason A. Donenfeld }
3553655adc7SJason A. Donenfeld 
356a1940263SJason A. Donenfeld static void _get_random_bytes(void *buf, size_t len)
3573655adc7SJason A. Donenfeld {
3583655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
3593655adc7SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE];
360a1940263SJason A. Donenfeld 	size_t first_block_len;
3613655adc7SJason A. Donenfeld 
362a1940263SJason A. Donenfeld 	if (!len)
3633655adc7SJason A. Donenfeld 		return;
3643655adc7SJason A. Donenfeld 
365a1940263SJason A. Donenfeld 	first_block_len = min_t(size_t, 32, len);
366a1940263SJason A. Donenfeld 	crng_make_state(chacha_state, buf, first_block_len);
367a1940263SJason A. Donenfeld 	len -= first_block_len;
368a1940263SJason A. Donenfeld 	buf += first_block_len;
3693655adc7SJason A. Donenfeld 
370a1940263SJason A. Donenfeld 	while (len) {
371a1940263SJason A. Donenfeld 		if (len < CHACHA_BLOCK_SIZE) {
3723655adc7SJason A. Donenfeld 			chacha20_block(chacha_state, tmp);
373a1940263SJason A. Donenfeld 			memcpy(buf, tmp, len);
3743655adc7SJason A. Donenfeld 			memzero_explicit(tmp, sizeof(tmp));
3753655adc7SJason A. Donenfeld 			break;
3763655adc7SJason A. Donenfeld 		}
3773655adc7SJason A. Donenfeld 
3783655adc7SJason A. Donenfeld 		chacha20_block(chacha_state, buf);
3793655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
3803655adc7SJason A. Donenfeld 			++chacha_state[13];
381a1940263SJason A. Donenfeld 		len -= CHACHA_BLOCK_SIZE;
3823655adc7SJason A. Donenfeld 		buf += CHACHA_BLOCK_SIZE;
3833655adc7SJason A. Donenfeld 	}
3843655adc7SJason A. Donenfeld 
3853655adc7SJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
3863655adc7SJason A. Donenfeld }
3873655adc7SJason A. Donenfeld 
3883655adc7SJason A. Donenfeld /*
389d687772eSWilliam Zijl  * This function is the exported kernel interface. It returns some number of
390d687772eSWilliam Zijl  * good random numbers, suitable for key generation, seeding TCP sequence
391d687772eSWilliam Zijl  * numbers, etc. In order to ensure that the randomness returned by this
392d687772eSWilliam Zijl  * function is okay, the function wait_for_random_bytes() should be called and
393d687772eSWilliam Zijl  * return 0 at least once at any point prior.
3943655adc7SJason A. Donenfeld  */
395a1940263SJason A. Donenfeld void get_random_bytes(void *buf, size_t len)
3963655adc7SJason A. Donenfeld {
397cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
398a1940263SJason A. Donenfeld 	_get_random_bytes(buf, len);
3993655adc7SJason A. Donenfeld }
4003655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_bytes);
4013655adc7SJason A. Donenfeld 
4021b388e77SJens Axboe static ssize_t get_random_bytes_user(struct iov_iter *iter)
4033655adc7SJason A. Donenfeld {
4043655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
4051b388e77SJens Axboe 	u8 block[CHACHA_BLOCK_SIZE];
4061b388e77SJens Axboe 	size_t ret = 0, copied;
4073655adc7SJason A. Donenfeld 
4081b388e77SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
4093655adc7SJason A. Donenfeld 		return 0;
4103655adc7SJason A. Donenfeld 
411aba120ccSJason A. Donenfeld 	/*
412aba120ccSJason A. Donenfeld 	 * Immediately overwrite the ChaCha key at index 4 with random
41363b8ea5eSJason A. Donenfeld 	 * bytes, in case userspace causes copy_to_iter() below to sleep
414aba120ccSJason A. Donenfeld 	 * forever, so that we still retain forward secrecy in that case.
415aba120ccSJason A. Donenfeld 	 */
416aba120ccSJason A. Donenfeld 	crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
417aba120ccSJason A. Donenfeld 	/*
418aba120ccSJason A. Donenfeld 	 * However, if we're doing a read of len <= 32, we don't need to
419aba120ccSJason A. Donenfeld 	 * use chacha_state after, so we can simply return those bytes to
420aba120ccSJason A. Donenfeld 	 * the user directly.
421aba120ccSJason A. Donenfeld 	 */
4221b388e77SJens Axboe 	if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
4231b388e77SJens Axboe 		ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
424aba120ccSJason A. Donenfeld 		goto out_zero_chacha;
425aba120ccSJason A. Donenfeld 	}
4263655adc7SJason A. Donenfeld 
4275209aed5SJason A. Donenfeld 	for (;;) {
4281b388e77SJens Axboe 		chacha20_block(chacha_state, block);
4293655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4303655adc7SJason A. Donenfeld 			++chacha_state[13];
4313655adc7SJason A. Donenfeld 
4321b388e77SJens Axboe 		copied = copy_to_iter(block, sizeof(block), iter);
4331b388e77SJens Axboe 		ret += copied;
4341b388e77SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
4355209aed5SJason A. Donenfeld 			break;
436e3c1c4fdSJason A. Donenfeld 
4371b388e77SJens Axboe 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
4385209aed5SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
439e3c1c4fdSJason A. Donenfeld 			if (signal_pending(current))
440e3c1c4fdSJason A. Donenfeld 				break;
441e3c1c4fdSJason A. Donenfeld 			cond_resched();
442e3c1c4fdSJason A. Donenfeld 		}
4435209aed5SJason A. Donenfeld 	}
4443655adc7SJason A. Donenfeld 
4451b388e77SJens Axboe 	memzero_explicit(block, sizeof(block));
446aba120ccSJason A. Donenfeld out_zero_chacha:
447aba120ccSJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
4485209aed5SJason A. Donenfeld 	return ret ? ret : -EFAULT;
4493655adc7SJason A. Donenfeld }
4503655adc7SJason A. Donenfeld 
4513655adc7SJason A. Donenfeld /*
4523655adc7SJason A. Donenfeld  * Batched entropy returns random integers. The quality of the random
4533655adc7SJason A. Donenfeld  * number is good as /dev/urandom. In order to ensure that the randomness
4543655adc7SJason A. Donenfeld  * provided by this function is okay, the function wait_for_random_bytes()
4553655adc7SJason A. Donenfeld  * should be called and return 0 at least once at any point prior.
4563655adc7SJason A. Donenfeld  */
4573655adc7SJason A. Donenfeld 
4583092adceSJason A. Donenfeld #define DEFINE_BATCHED_ENTROPY(type)						\
4593092adceSJason A. Donenfeld struct batch_ ##type {								\
4603092adceSJason A. Donenfeld 	/*									\
4613092adceSJason A. Donenfeld 	 * We make this 1.5x a ChaCha block, so that we get the			\
4623092adceSJason A. Donenfeld 	 * remaining 32 bytes from fast key erasure, plus one full		\
4633092adceSJason A. Donenfeld 	 * block from the detached ChaCha state. We can increase		\
4643092adceSJason A. Donenfeld 	 * the size of this later if needed so long as we keep the		\
4653092adceSJason A. Donenfeld 	 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.		\
4663092adceSJason A. Donenfeld 	 */									\
4673092adceSJason A. Donenfeld 	type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))];		\
4683092adceSJason A. Donenfeld 	local_lock_t lock;							\
4693092adceSJason A. Donenfeld 	unsigned long generation;						\
4703092adceSJason A. Donenfeld 	unsigned int position;							\
4713092adceSJason A. Donenfeld };										\
4723092adceSJason A. Donenfeld 										\
4733092adceSJason A. Donenfeld static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = {	\
4743092adceSJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock),			\
4753092adceSJason A. Donenfeld 	.position = UINT_MAX							\
4763092adceSJason A. Donenfeld };										\
4773092adceSJason A. Donenfeld 										\
4783092adceSJason A. Donenfeld type get_random_ ##type(void)							\
4793092adceSJason A. Donenfeld {										\
4803092adceSJason A. Donenfeld 	type ret;								\
4813092adceSJason A. Donenfeld 	unsigned long flags;							\
4823092adceSJason A. Donenfeld 	struct batch_ ##type *batch;						\
4833092adceSJason A. Donenfeld 	unsigned long next_gen;							\
4843092adceSJason A. Donenfeld 										\
4853092adceSJason A. Donenfeld 	warn_unseeded_randomness();						\
4863092adceSJason A. Donenfeld 										\
4873092adceSJason A. Donenfeld 	if  (!crng_ready()) {							\
4883092adceSJason A. Donenfeld 		_get_random_bytes(&ret, sizeof(ret));				\
4893092adceSJason A. Donenfeld 		return ret;							\
4903092adceSJason A. Donenfeld 	}									\
4913092adceSJason A. Donenfeld 										\
4923092adceSJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_ ##type.lock, flags);		\
4933092adceSJason A. Donenfeld 	batch = raw_cpu_ptr(&batched_entropy_##type);				\
4943092adceSJason A. Donenfeld 										\
4953092adceSJason A. Donenfeld 	next_gen = READ_ONCE(base_crng.generation);				\
4963092adceSJason A. Donenfeld 	if (batch->position >= ARRAY_SIZE(batch->entropy) ||			\
4973092adceSJason A. Donenfeld 	    next_gen != batch->generation) {					\
4983092adceSJason A. Donenfeld 		_get_random_bytes(batch->entropy, sizeof(batch->entropy));	\
4993092adceSJason A. Donenfeld 		batch->position = 0;						\
5003092adceSJason A. Donenfeld 		batch->generation = next_gen;					\
5013092adceSJason A. Donenfeld 	}									\
5023092adceSJason A. Donenfeld 										\
5033092adceSJason A. Donenfeld 	ret = batch->entropy[batch->position];					\
5043092adceSJason A. Donenfeld 	batch->entropy[batch->position] = 0;					\
5053092adceSJason A. Donenfeld 	++batch->position;							\
5063092adceSJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags);		\
5073092adceSJason A. Donenfeld 	return ret;								\
5083092adceSJason A. Donenfeld }										\
5093092adceSJason A. Donenfeld EXPORT_SYMBOL(get_random_ ##type);
5103655adc7SJason A. Donenfeld 
511585cd5feSJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u8)
512a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u16)
513a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u32)
514a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u64)
5153655adc7SJason A. Donenfeld 
516e9a688bcSJason A. Donenfeld u32 __get_random_u32_below(u32 ceil)
517e9a688bcSJason A. Donenfeld {
518e9a688bcSJason A. Donenfeld 	/*
519e9a688bcSJason A. Donenfeld 	 * This is the slow path for variable ceil. It is still fast, most of
520e9a688bcSJason A. Donenfeld 	 * the time, by doing traditional reciprocal multiplication and
521e9a688bcSJason A. Donenfeld 	 * opportunistically comparing the lower half to ceil itself, before
522e9a688bcSJason A. Donenfeld 	 * falling back to computing a larger bound, and then rejecting samples
523e9a688bcSJason A. Donenfeld 	 * whose lower half would indicate a range indivisible by ceil. The use
524e9a688bcSJason A. Donenfeld 	 * of `-ceil % ceil` is analogous to `2^32 % ceil`, but is computable
525e9a688bcSJason A. Donenfeld 	 * in 32-bits.
526e9a688bcSJason A. Donenfeld 	 */
5277f576b25SJason A. Donenfeld 	u32 rand = get_random_u32();
5287f576b25SJason A. Donenfeld 	u64 mult;
5297f576b25SJason A. Donenfeld 
5307f576b25SJason A. Donenfeld 	/*
5317f576b25SJason A. Donenfeld 	 * This function is technically undefined for ceil == 0, and in fact
5327f576b25SJason A. Donenfeld 	 * for the non-underscored constant version in the header, we build bug
5337f576b25SJason A. Donenfeld 	 * on that. But for the non-constant case, it's convenient to have that
5347f576b25SJason A. Donenfeld 	 * evaluate to being a straight call to get_random_u32(), so that
5357f576b25SJason A. Donenfeld 	 * get_random_u32_inclusive() can work over its whole range without
5367f576b25SJason A. Donenfeld 	 * undefined behavior.
5377f576b25SJason A. Donenfeld 	 */
5387f576b25SJason A. Donenfeld 	if (unlikely(!ceil))
5397f576b25SJason A. Donenfeld 		return rand;
5407f576b25SJason A. Donenfeld 
5417f576b25SJason A. Donenfeld 	mult = (u64)ceil * rand;
542e9a688bcSJason A. Donenfeld 	if (unlikely((u32)mult < ceil)) {
543e9a688bcSJason A. Donenfeld 		u32 bound = -ceil % ceil;
544e9a688bcSJason A. Donenfeld 		while (unlikely((u32)mult < bound))
545e9a688bcSJason A. Donenfeld 			mult = (u64)ceil * get_random_u32();
546e9a688bcSJason A. Donenfeld 	}
547e9a688bcSJason A. Donenfeld 	return mult >> 32;
548e9a688bcSJason A. Donenfeld }
549e9a688bcSJason A. Donenfeld EXPORT_SYMBOL(__get_random_u32_below);
550e9a688bcSJason A. Donenfeld 
5513191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
5523191dd5aSJason A. Donenfeld /*
5533191dd5aSJason A. Donenfeld  * This function is called when the CPU is coming up, with entry
5543191dd5aSJason A. Donenfeld  * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
5553191dd5aSJason A. Donenfeld  */
556560181c2SJason A. Donenfeld int __cold random_prepare_cpu(unsigned int cpu)
5573191dd5aSJason A. Donenfeld {
5583191dd5aSJason A. Donenfeld 	/*
5593191dd5aSJason A. Donenfeld 	 * When the cpu comes back online, immediately invalidate both
5603191dd5aSJason A. Donenfeld 	 * the per-cpu crng and all batches, so that we serve fresh
5613191dd5aSJason A. Donenfeld 	 * randomness.
5623191dd5aSJason A. Donenfeld 	 */
5633191dd5aSJason A. Donenfeld 	per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
564a890d1c6SJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u8, cpu)->position = UINT_MAX;
565a890d1c6SJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u16, cpu)->position = UINT_MAX;
5663191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
5673191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
5683191dd5aSJason A. Donenfeld 	return 0;
5693191dd5aSJason A. Donenfeld }
5703191dd5aSJason A. Donenfeld #endif
5713191dd5aSJason A. Donenfeld 
572a5ed7cb1SJason A. Donenfeld 
573a5ed7cb1SJason A. Donenfeld /**********************************************************************
574a5ed7cb1SJason A. Donenfeld  *
575a5ed7cb1SJason A. Donenfeld  * Entropy accumulation and extraction routines.
576a5ed7cb1SJason A. Donenfeld  *
577a5ed7cb1SJason A. Donenfeld  * Callers may add entropy via:
578a5ed7cb1SJason A. Donenfeld  *
579a1940263SJason A. Donenfeld  *     static void mix_pool_bytes(const void *buf, size_t len)
580a5ed7cb1SJason A. Donenfeld  *
581a5ed7cb1SJason A. Donenfeld  * After which, if added entropy should be credited:
582a5ed7cb1SJason A. Donenfeld  *
583a1940263SJason A. Donenfeld  *     static void credit_init_bits(size_t bits)
584a5ed7cb1SJason A. Donenfeld  *
585e85c0fc1SJason A. Donenfeld  * Finally, extract entropy via:
586a5ed7cb1SJason A. Donenfeld  *
587a1940263SJason A. Donenfeld  *     static void extract_entropy(void *buf, size_t len)
588a5ed7cb1SJason A. Donenfeld  *
589a5ed7cb1SJason A. Donenfeld  **********************************************************************/
590a5ed7cb1SJason A. Donenfeld 
591c5704490SJason A. Donenfeld enum {
5926e8ec255SJason A. Donenfeld 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
593e3d2c5e7SJason A. Donenfeld 	POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
594e3d2c5e7SJason A. Donenfeld 	POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
5951da177e4SLinus Torvalds };
5961da177e4SLinus Torvalds 
59790ed1e67SJason A. Donenfeld static struct {
5986e8ec255SJason A. Donenfeld 	struct blake2s_state hash;
59943358209SMatt Mackall 	spinlock_t lock;
600e85c0fc1SJason A. Donenfeld 	unsigned int init_bits;
60190ed1e67SJason A. Donenfeld } input_pool = {
6026e8ec255SJason A. Donenfeld 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
6036e8ec255SJason A. Donenfeld 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
6046e8ec255SJason A. Donenfeld 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
6056e8ec255SJason A. Donenfeld 	.hash.outlen = BLAKE2S_HASH_SIZE,
606eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
6071da177e4SLinus Torvalds };
6081da177e4SLinus Torvalds 
609a1940263SJason A. Donenfeld static void _mix_pool_bytes(const void *buf, size_t len)
610a5ed7cb1SJason A. Donenfeld {
611a1940263SJason A. Donenfeld 	blake2s_update(&input_pool.hash, buf, len);
612a5ed7cb1SJason A. Donenfeld }
61390ed1e67SJason A. Donenfeld 
6141da177e4SLinus Torvalds /*
615e85c0fc1SJason A. Donenfeld  * This function adds bytes into the input pool. It does not
616e85c0fc1SJason A. Donenfeld  * update the initialization bit counter; the caller should call
617e85c0fc1SJason A. Donenfeld  * credit_init_bits if this is appropriate.
6181da177e4SLinus Torvalds  */
619a1940263SJason A. Donenfeld static void mix_pool_bytes(const void *buf, size_t len)
6201da177e4SLinus Torvalds {
621902c098aSTheodore Ts'o 	unsigned long flags;
622902c098aSTheodore Ts'o 
62390ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
624a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
62590ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
6261da177e4SLinus Torvalds }
6271da177e4SLinus Torvalds 
628a5ed7cb1SJason A. Donenfeld /*
629a5ed7cb1SJason A. Donenfeld  * This is an HKDF-like construction for using the hashed collected entropy
630a5ed7cb1SJason A. Donenfeld  * as a PRF key, that's then expanded block-by-block.
631a5ed7cb1SJason A. Donenfeld  */
632a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len)
633a5ed7cb1SJason A. Donenfeld {
634a5ed7cb1SJason A. Donenfeld 	unsigned long flags;
635a5ed7cb1SJason A. Donenfeld 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
636a5ed7cb1SJason A. Donenfeld 	struct {
637a5ed7cb1SJason A. Donenfeld 		unsigned long rdseed[32 / sizeof(long)];
638a5ed7cb1SJason A. Donenfeld 		size_t counter;
639a5ed7cb1SJason A. Donenfeld 	} block;
640d349ab99SJason A. Donenfeld 	size_t i, longs;
641a5ed7cb1SJason A. Donenfeld 
642d349ab99SJason A. Donenfeld 	for (i = 0; i < ARRAY_SIZE(block.rdseed);) {
643d349ab99SJason A. Donenfeld 		longs = arch_get_random_seed_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
644d349ab99SJason A. Donenfeld 		if (longs) {
645d349ab99SJason A. Donenfeld 			i += longs;
646d349ab99SJason A. Donenfeld 			continue;
647d349ab99SJason A. Donenfeld 		}
648d349ab99SJason A. Donenfeld 		longs = arch_get_random_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
649d349ab99SJason A. Donenfeld 		if (longs) {
650d349ab99SJason A. Donenfeld 			i += longs;
651d349ab99SJason A. Donenfeld 			continue;
652d349ab99SJason A. Donenfeld 		}
653d349ab99SJason A. Donenfeld 		block.rdseed[i++] = random_get_entropy();
654a5ed7cb1SJason A. Donenfeld 	}
655a5ed7cb1SJason A. Donenfeld 
656a5ed7cb1SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
657a5ed7cb1SJason A. Donenfeld 
658a5ed7cb1SJason A. Donenfeld 	/* seed = HASHPRF(last_key, entropy_input) */
659a5ed7cb1SJason A. Donenfeld 	blake2s_final(&input_pool.hash, seed);
660a5ed7cb1SJason A. Donenfeld 
661a5ed7cb1SJason A. Donenfeld 	/* next_key = HASHPRF(seed, RDSEED || 0) */
662a5ed7cb1SJason A. Donenfeld 	block.counter = 0;
663a5ed7cb1SJason A. Donenfeld 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
664a5ed7cb1SJason A. Donenfeld 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
665a5ed7cb1SJason A. Donenfeld 
666a5ed7cb1SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
667a5ed7cb1SJason A. Donenfeld 	memzero_explicit(next_key, sizeof(next_key));
668a5ed7cb1SJason A. Donenfeld 
669a1940263SJason A. Donenfeld 	while (len) {
670a1940263SJason A. Donenfeld 		i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
671a5ed7cb1SJason A. Donenfeld 		/* output = HASHPRF(seed, RDSEED || ++counter) */
672a5ed7cb1SJason A. Donenfeld 		++block.counter;
673a5ed7cb1SJason A. Donenfeld 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
674a1940263SJason A. Donenfeld 		len -= i;
675a5ed7cb1SJason A. Donenfeld 		buf += i;
676a5ed7cb1SJason A. Donenfeld 	}
677a5ed7cb1SJason A. Donenfeld 
678a5ed7cb1SJason A. Donenfeld 	memzero_explicit(seed, sizeof(seed));
679a5ed7cb1SJason A. Donenfeld 	memzero_explicit(&block, sizeof(block));
680a5ed7cb1SJason A. Donenfeld }
681a5ed7cb1SJason A. Donenfeld 
682560181c2SJason A. Donenfeld #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
683560181c2SJason A. Donenfeld 
684560181c2SJason A. Donenfeld static void __cold _credit_init_bits(size_t bits)
685a5ed7cb1SJason A. Donenfeld {
686f5bda35fSJason A. Donenfeld 	static struct execute_work set_ready;
687fed7ef06SJason A. Donenfeld 	unsigned int new, orig, add;
6885c3b747eSJason A. Donenfeld 	unsigned long flags;
6895c3b747eSJason A. Donenfeld 
690560181c2SJason A. Donenfeld 	if (!bits)
6915c3b747eSJason A. Donenfeld 		return;
6925c3b747eSJason A. Donenfeld 
693a1940263SJason A. Donenfeld 	add = min_t(size_t, bits, POOL_BITS);
6945c3b747eSJason A. Donenfeld 
695e85c0fc1SJason A. Donenfeld 	orig = READ_ONCE(input_pool.init_bits);
696b7a68f67SUros Bizjak 	do {
697fed7ef06SJason A. Donenfeld 		new = min_t(unsigned int, POOL_BITS, orig + add);
698b7a68f67SUros Bizjak 	} while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
6995c3b747eSJason A. Donenfeld 
70068c9c8b1SJason A. Donenfeld 	if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
70168c9c8b1SJason A. Donenfeld 		crng_reseed(); /* Sets crng_init to CRNG_READY under base_crng.lock. */
70260e5b288SJason A. Donenfeld 		if (static_key_initialized)
703f5bda35fSJason A. Donenfeld 			execute_in_process_context(crng_set_ready, &set_ready);
70468c9c8b1SJason A. Donenfeld 		wake_up_interruptible(&crng_init_wait);
70568c9c8b1SJason A. Donenfeld 		kill_fasync(&fasync, SIGIO, POLL_IN);
70668c9c8b1SJason A. Donenfeld 		pr_notice("crng init done\n");
707cc1e127bSJason A. Donenfeld 		if (urandom_warning.missed)
70868c9c8b1SJason A. Donenfeld 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
70968c9c8b1SJason A. Donenfeld 				  urandom_warning.missed);
71068c9c8b1SJason A. Donenfeld 	} else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
7115c3b747eSJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
71268c9c8b1SJason A. Donenfeld 		/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
713e3d2c5e7SJason A. Donenfeld 		if (crng_init == CRNG_EMPTY) {
7145c3b747eSJason A. Donenfeld 			extract_entropy(base_crng.key, sizeof(base_crng.key));
715e3d2c5e7SJason A. Donenfeld 			crng_init = CRNG_EARLY;
7165c3b747eSJason A. Donenfeld 		}
7175c3b747eSJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
7185c3b747eSJason A. Donenfeld 	}
7195c3b747eSJason A. Donenfeld }
7205c3b747eSJason A. Donenfeld 
72192c653cfSJason A. Donenfeld 
72292c653cfSJason A. Donenfeld /**********************************************************************
72392c653cfSJason A. Donenfeld  *
72492c653cfSJason A. Donenfeld  * Entropy collection routines.
72592c653cfSJason A. Donenfeld  *
72692c653cfSJason A. Donenfeld  * The following exported functions are used for pushing entropy into
72792c653cfSJason A. Donenfeld  * the above entropy accumulation routines:
72892c653cfSJason A. Donenfeld  *
729a1940263SJason A. Donenfeld  *	void add_device_randomness(const void *buf, size_t len);
730a1940263SJason A. Donenfeld  *	void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy);
731a1940263SJason A. Donenfeld  *	void add_bootloader_randomness(const void *buf, size_t len);
732a1940263SJason A. Donenfeld  *	void add_vmfork_randomness(const void *unique_vm_id, size_t len);
73392c653cfSJason A. Donenfeld  *	void add_interrupt_randomness(int irq);
734a1940263SJason A. Donenfeld  *	void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
735a4b5c26bSJason A. Donenfeld  *	void add_disk_randomness(struct gendisk *disk);
73692c653cfSJason A. Donenfeld  *
73792c653cfSJason A. Donenfeld  * add_device_randomness() adds data to the input pool that
73892c653cfSJason A. Donenfeld  * is likely to differ between two devices (or possibly even per boot).
73992c653cfSJason A. Donenfeld  * This would be things like MAC addresses or serial numbers, or the
74092c653cfSJason A. Donenfeld  * read-out of the RTC. This does *not* credit any actual entropy to
74192c653cfSJason A. Donenfeld  * the pool, but it initializes the pool to different values for devices
74292c653cfSJason A. Donenfeld  * that might otherwise be identical and have very little entropy
74392c653cfSJason A. Donenfeld  * available to them (particularly common in the embedded world).
74492c653cfSJason A. Donenfeld  *
74592c653cfSJason A. Donenfeld  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
74692c653cfSJason A. Donenfeld  * entropy as specified by the caller. If the entropy pool is full it will
74792c653cfSJason A. Donenfeld  * block until more entropy is needed.
74892c653cfSJason A. Donenfeld  *
7495c3b747eSJason A. Donenfeld  * add_bootloader_randomness() is called by bootloader drivers, such as EFI
7505c3b747eSJason A. Donenfeld  * and device tree, and credits its input depending on whether or not the
751b9b01a56SJason A. Donenfeld  * command line option 'random.trust_bootloader'.
75292c653cfSJason A. Donenfeld  *
753ae099e8eSJason A. Donenfeld  * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
754ae099e8eSJason A. Donenfeld  * representing the current instance of a VM to the pool, without crediting,
755ae099e8eSJason A. Donenfeld  * and then force-reseeds the crng so that it takes effect immediately.
756ae099e8eSJason A. Donenfeld  *
75792c653cfSJason A. Donenfeld  * add_interrupt_randomness() uses the interrupt timing as random
75892c653cfSJason A. Donenfeld  * inputs to the entropy pool. Using the cycle counters and the irq source
75992c653cfSJason A. Donenfeld  * as inputs, it feeds the input pool roughly once a second or after 64
76092c653cfSJason A. Donenfeld  * interrupts, crediting 1 bit of entropy for whichever comes first.
76192c653cfSJason A. Donenfeld  *
762a4b5c26bSJason A. Donenfeld  * add_input_randomness() uses the input layer interrupt timing, as well
763a4b5c26bSJason A. Donenfeld  * as the event type information from the hardware.
764a4b5c26bSJason A. Donenfeld  *
765a4b5c26bSJason A. Donenfeld  * add_disk_randomness() uses what amounts to the seek time of block
766a4b5c26bSJason A. Donenfeld  * layer request events, on a per-disk_devt basis, as input to the
767a4b5c26bSJason A. Donenfeld  * entropy pool. Note that high-speed solid state drives with very low
768a4b5c26bSJason A. Donenfeld  * seek times do not make for good sources of entropy, as their seek
769a4b5c26bSJason A. Donenfeld  * times are usually fairly consistent.
770a4b5c26bSJason A. Donenfeld  *
771a4b5c26bSJason A. Donenfeld  * The last two routines try to estimate how many bits of entropy
772a4b5c26bSJason A. Donenfeld  * to credit. They do this by keeping track of the first and second
773a4b5c26bSJason A. Donenfeld  * order deltas of the event timings.
774a4b5c26bSJason A. Donenfeld  *
77592c653cfSJason A. Donenfeld  **********************************************************************/
77692c653cfSJason A. Donenfeld 
777b9b01a56SJason A. Donenfeld static bool trust_cpu __initdata = true;
778b9b01a56SJason A. Donenfeld static bool trust_bootloader __initdata = true;
77992c653cfSJason A. Donenfeld static int __init parse_trust_cpu(char *arg)
78092c653cfSJason A. Donenfeld {
78192c653cfSJason A. Donenfeld 	return kstrtobool(arg, &trust_cpu);
78292c653cfSJason A. Donenfeld }
783d97c68d1SJason A. Donenfeld static int __init parse_trust_bootloader(char *arg)
784d97c68d1SJason A. Donenfeld {
785d97c68d1SJason A. Donenfeld 	return kstrtobool(arg, &trust_bootloader);
786d97c68d1SJason A. Donenfeld }
78792c653cfSJason A. Donenfeld early_param("random.trust_cpu", parse_trust_cpu);
788d97c68d1SJason A. Donenfeld early_param("random.trust_bootloader", parse_trust_bootloader);
789775f4b29STheodore Ts'o 
790b7b67d13SJason A. Donenfeld static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
791b7b67d13SJason A. Donenfeld {
792b7b67d13SJason A. Donenfeld 	unsigned long flags, entropy = random_get_entropy();
793b7b67d13SJason A. Donenfeld 
794b7b67d13SJason A. Donenfeld 	/*
795b7b67d13SJason A. Donenfeld 	 * Encode a representation of how long the system has been suspended,
796b7b67d13SJason A. Donenfeld 	 * in a way that is distinct from prior system suspends.
797b7b67d13SJason A. Donenfeld 	 */
798b7b67d13SJason A. Donenfeld 	ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
799b7b67d13SJason A. Donenfeld 
800b7b67d13SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
801b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&action, sizeof(action));
802b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(stamps, sizeof(stamps));
803b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
804b7b67d13SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
805b7b67d13SJason A. Donenfeld 
806b7b67d13SJason A. Donenfeld 	if (crng_ready() && (action == PM_RESTORE_PREPARE ||
807261e224dSKalesh Singh 	    (action == PM_POST_SUSPEND && !IS_ENABLED(CONFIG_PM_AUTOSLEEP) &&
808261e224dSKalesh Singh 	     !IS_ENABLED(CONFIG_PM_USERSPACE_AUTOSLEEP)))) {
809e85c0fc1SJason A. Donenfeld 		crng_reseed();
810b7b67d13SJason A. Donenfeld 		pr_notice("crng reseeded on system resumption\n");
811b7b67d13SJason A. Donenfeld 	}
812b7b67d13SJason A. Donenfeld 	return 0;
813b7b67d13SJason A. Donenfeld }
814b7b67d13SJason A. Donenfeld 
815b7b67d13SJason A. Donenfeld static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
816b7b67d13SJason A. Donenfeld 
817775f4b29STheodore Ts'o /*
818f6238499SJason A. Donenfeld  * This is called extremely early, before time keeping functionality is
819f6238499SJason A. Donenfeld  * available, but arch randomness is. Interrupts are not yet enabled.
820775f4b29STheodore Ts'o  */
821f6238499SJason A. Donenfeld void __init random_init_early(const char *command_line)
822775f4b29STheodore Ts'o {
823d349ab99SJason A. Donenfeld 	unsigned long entropy[BLAKE2S_BLOCK_SIZE / sizeof(long)];
824f6238499SJason A. Donenfeld 	size_t i, longs, arch_bits;
825775f4b29STheodore Ts'o 
8261754abb3SJason A. Donenfeld #if defined(LATENT_ENTROPY_PLUGIN)
8271754abb3SJason A. Donenfeld 	static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
8281754abb3SJason A. Donenfeld 	_mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
8291754abb3SJason A. Donenfeld #endif
8301754abb3SJason A. Donenfeld 
831d349ab99SJason A. Donenfeld 	for (i = 0, arch_bits = sizeof(entropy) * 8; i < ARRAY_SIZE(entropy);) {
8322c03e16fSJason A. Donenfeld 		longs = arch_get_random_seed_longs(entropy, ARRAY_SIZE(entropy) - i);
833d349ab99SJason A. Donenfeld 		if (longs) {
834d349ab99SJason A. Donenfeld 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
835d349ab99SJason A. Donenfeld 			i += longs;
836d349ab99SJason A. Donenfeld 			continue;
83792c653cfSJason A. Donenfeld 		}
8382c03e16fSJason A. Donenfeld 		longs = arch_get_random_longs(entropy, ARRAY_SIZE(entropy) - i);
839d349ab99SJason A. Donenfeld 		if (longs) {
840d349ab99SJason A. Donenfeld 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
841d349ab99SJason A. Donenfeld 			i += longs;
842d349ab99SJason A. Donenfeld 			continue;
843d349ab99SJason A. Donenfeld 		}
844d349ab99SJason A. Donenfeld 		arch_bits -= sizeof(*entropy) * 8;
845d349ab99SJason A. Donenfeld 		++i;
84692c653cfSJason A. Donenfeld 	}
847f6238499SJason A. Donenfeld 
848dd54fd7dSJason A. Donenfeld 	_mix_pool_bytes(init_utsname(), sizeof(*(init_utsname())));
8492f14062bSJason A. Donenfeld 	_mix_pool_bytes(command_line, strlen(command_line));
850f6238499SJason A. Donenfeld 
851f6238499SJason A. Donenfeld 	/* Reseed if already seeded by earlier phases. */
852f6238499SJason A. Donenfeld 	if (crng_ready())
853f6238499SJason A. Donenfeld 		crng_reseed();
854f6238499SJason A. Donenfeld 	else if (trust_cpu)
855f6238499SJason A. Donenfeld 		_credit_init_bits(arch_bits);
856f6238499SJason A. Donenfeld }
857f6238499SJason A. Donenfeld 
858f6238499SJason A. Donenfeld /*
859f6238499SJason A. Donenfeld  * This is called a little bit after the prior function, and now there is
860f6238499SJason A. Donenfeld  * access to timestamps counters. Interrupts are not yet enabled.
861f6238499SJason A. Donenfeld  */
862f6238499SJason A. Donenfeld void __init random_init(void)
863f6238499SJason A. Donenfeld {
864f6238499SJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
865f6238499SJason A. Donenfeld 	ktime_t now = ktime_get_real();
866f6238499SJason A. Donenfeld 
867f6238499SJason A. Donenfeld 	_mix_pool_bytes(&now, sizeof(now));
868f6238499SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
8692f14062bSJason A. Donenfeld 	add_latent_entropy();
870655b2264STheodore Ts'o 
87160e5b288SJason A. Donenfeld 	/*
872f6238499SJason A. Donenfeld 	 * If we were initialized by the cpu or bootloader before jump labels
873f6238499SJason A. Donenfeld 	 * are initialized, then we should enable the static branch here, where
87460e5b288SJason A. Donenfeld 	 * it's guaranteed that jump labels have been initialized.
87560e5b288SJason A. Donenfeld 	 */
87660e5b288SJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
87760e5b288SJason A. Donenfeld 		crng_set_ready(NULL);
87860e5b288SJason A. Donenfeld 
879f6238499SJason A. Donenfeld 	/* Reseed if already seeded by earlier phases. */
880e85c0fc1SJason A. Donenfeld 	if (crng_ready())
881e85c0fc1SJason A. Donenfeld 		crng_reseed();
882775f4b29STheodore Ts'o 
883b7b67d13SJason A. Donenfeld 	WARN_ON(register_pm_notifier(&pm_notifier));
884b7b67d13SJason A. Donenfeld 
885f6238499SJason A. Donenfeld 	WARN(!entropy, "Missing cycle counter and fallback timer; RNG "
8864b758edaSJason A. Donenfeld 		       "entropy collection will consequently suffer.");
88792c653cfSJason A. Donenfeld }
8881da177e4SLinus Torvalds 
889a2080a67SLinus Torvalds /*
890e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
891e192be9dSTheodore Ts'o  * initialize it.
892a2080a67SLinus Torvalds  *
893e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
894e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
895e192be9dSTheodore Ts'o  * identical devices.
896a2080a67SLinus Torvalds  */
897a1940263SJason A. Donenfeld void add_device_randomness(const void *buf, size_t len)
898a2080a67SLinus Torvalds {
8994b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
9004b758edaSJason A. Donenfeld 	unsigned long flags;
901a2080a67SLinus Torvalds 
9023ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
9034b758edaSJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
904a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
9053ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
906a2080a67SLinus Torvalds }
907a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
908a2080a67SLinus Torvalds 
90992c653cfSJason A. Donenfeld /*
91092c653cfSJason A. Donenfeld  * Interface for in-kernel drivers of true hardware RNGs.
91192c653cfSJason A. Donenfeld  * Those devices may produce endless random bits and will be throttled
91292c653cfSJason A. Donenfeld  * when our pool is full.
91392c653cfSJason A. Donenfeld  */
914a1940263SJason A. Donenfeld void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy)
91592c653cfSJason A. Donenfeld {
916a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
917e85c0fc1SJason A. Donenfeld 	credit_init_bits(entropy);
918e85c0fc1SJason A. Donenfeld 
919e85c0fc1SJason A. Donenfeld 	/*
920745558f9SDominik Brodowski 	 * Throttle writing to once every reseed interval, unless we're not yet
921d775335eSJason A. Donenfeld 	 * initialized or no entropy is credited.
922e85c0fc1SJason A. Donenfeld 	 */
923d775335eSJason A. Donenfeld 	if (!kthread_should_stop() && (crng_ready() || !entropy))
924745558f9SDominik Brodowski 		schedule_timeout_interruptible(crng_reseed_interval());
92592c653cfSJason A. Donenfeld }
92692c653cfSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
92792c653cfSJason A. Donenfeld 
92892c653cfSJason A. Donenfeld /*
929b9b01a56SJason A. Donenfeld  * Handle random seed passed by bootloader, and credit it depending
930b9b01a56SJason A. Donenfeld  * on the command line option 'random.trust_bootloader'.
93192c653cfSJason A. Donenfeld  */
93239e0f991SJason A. Donenfeld void __init add_bootloader_randomness(const void *buf, size_t len)
93392c653cfSJason A. Donenfeld {
934a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
935d97c68d1SJason A. Donenfeld 	if (trust_bootloader)
936a1940263SJason A. Donenfeld 		credit_init_bits(len * 8);
93792c653cfSJason A. Donenfeld }
93892c653cfSJason A. Donenfeld 
939a4107d34SJason A. Donenfeld #if IS_ENABLED(CONFIG_VMGENID)
940f3c2682bSJason A. Donenfeld static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
941f3c2682bSJason A. Donenfeld 
942ae099e8eSJason A. Donenfeld /*
943ae099e8eSJason A. Donenfeld  * Handle a new unique VM ID, which is unique, not secret, so we
944ae099e8eSJason A. Donenfeld  * don't credit it, but we do immediately force a reseed after so
945ae099e8eSJason A. Donenfeld  * that it's used by the crng posthaste.
946ae099e8eSJason A. Donenfeld  */
947560181c2SJason A. Donenfeld void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
948ae099e8eSJason A. Donenfeld {
949a1940263SJason A. Donenfeld 	add_device_randomness(unique_vm_id, len);
950ae099e8eSJason A. Donenfeld 	if (crng_ready()) {
951e85c0fc1SJason A. Donenfeld 		crng_reseed();
952ae099e8eSJason A. Donenfeld 		pr_notice("crng reseeded due to virtual machine fork\n");
953ae099e8eSJason A. Donenfeld 	}
954f3c2682bSJason A. Donenfeld 	blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
955ae099e8eSJason A. Donenfeld }
956a4107d34SJason A. Donenfeld #if IS_MODULE(CONFIG_VMGENID)
957ae099e8eSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_vmfork_randomness);
958a4107d34SJason A. Donenfeld #endif
959f3c2682bSJason A. Donenfeld 
960560181c2SJason A. Donenfeld int __cold register_random_vmfork_notifier(struct notifier_block *nb)
961f3c2682bSJason A. Donenfeld {
962f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_register(&vmfork_chain, nb);
963f3c2682bSJason A. Donenfeld }
964f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
965f3c2682bSJason A. Donenfeld 
966560181c2SJason A. Donenfeld int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
967f3c2682bSJason A. Donenfeld {
968f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_unregister(&vmfork_chain, nb);
969f3c2682bSJason A. Donenfeld }
970f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
971a4107d34SJason A. Donenfeld #endif
972ae099e8eSJason A. Donenfeld 
97392c653cfSJason A. Donenfeld struct fast_pool {
974f5eab0e2SJason A. Donenfeld 	unsigned long pool[4];
97592c653cfSJason A. Donenfeld 	unsigned long last;
9763191dd5aSJason A. Donenfeld 	unsigned int count;
977748bc4ddSJason A. Donenfeld 	struct timer_list mix;
97892c653cfSJason A. Donenfeld };
97992c653cfSJason A. Donenfeld 
980748bc4ddSJason A. Donenfeld static void mix_interrupt_randomness(struct timer_list *work);
981748bc4ddSJason A. Donenfeld 
982f5eab0e2SJason A. Donenfeld static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
983f5eab0e2SJason A. Donenfeld #ifdef CONFIG_64BIT
984e73aaae2SJason A. Donenfeld #define FASTMIX_PERM SIPHASH_PERMUTATION
985748bc4ddSJason A. Donenfeld 	.pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 },
986f5eab0e2SJason A. Donenfeld #else
987e73aaae2SJason A. Donenfeld #define FASTMIX_PERM HSIPHASH_PERMUTATION
988748bc4ddSJason A. Donenfeld 	.pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 },
989f5eab0e2SJason A. Donenfeld #endif
990748bc4ddSJason A. Donenfeld 	.mix = __TIMER_INITIALIZER(mix_interrupt_randomness, 0)
991f5eab0e2SJason A. Donenfeld };
992f5eab0e2SJason A. Donenfeld 
99392c653cfSJason A. Donenfeld /*
994f5eab0e2SJason A. Donenfeld  * This is [Half]SipHash-1-x, starting from an empty key. Because
995f5eab0e2SJason A. Donenfeld  * the key is fixed, it assumes that its inputs are non-malicious,
996f5eab0e2SJason A. Donenfeld  * and therefore this has no security on its own. s represents the
9974b758edaSJason A. Donenfeld  * four-word SipHash state, while v represents a two-word input.
99892c653cfSJason A. Donenfeld  */
999791332b3SJason A. Donenfeld static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
100092c653cfSJason A. Donenfeld {
1001791332b3SJason A. Donenfeld 	s[3] ^= v1;
1002e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1003791332b3SJason A. Donenfeld 	s[0] ^= v1;
1004791332b3SJason A. Donenfeld 	s[3] ^= v2;
1005e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1006791332b3SJason A. Donenfeld 	s[0] ^= v2;
1007f5eab0e2SJason A. Donenfeld }
1008775f4b29STheodore Ts'o 
10093191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
10103191dd5aSJason A. Donenfeld /*
10113191dd5aSJason A. Donenfeld  * This function is called when the CPU has just come online, with
10123191dd5aSJason A. Donenfeld  * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
10133191dd5aSJason A. Donenfeld  */
1014560181c2SJason A. Donenfeld int __cold random_online_cpu(unsigned int cpu)
10153191dd5aSJason A. Donenfeld {
10163191dd5aSJason A. Donenfeld 	/*
10173191dd5aSJason A. Donenfeld 	 * During CPU shutdown and before CPU onlining, add_interrupt_
10183191dd5aSJason A. Donenfeld 	 * randomness() may schedule mix_interrupt_randomness(), and
10193191dd5aSJason A. Donenfeld 	 * set the MIX_INFLIGHT flag. However, because the worker can
10203191dd5aSJason A. Donenfeld 	 * be scheduled on a different CPU during this period, that
10213191dd5aSJason A. Donenfeld 	 * flag will never be cleared. For that reason, we zero out
10223191dd5aSJason A. Donenfeld 	 * the flag here, which runs just after workqueues are onlined
10233191dd5aSJason A. Donenfeld 	 * for the CPU again. This also has the effect of setting the
10243191dd5aSJason A. Donenfeld 	 * irq randomness count to zero so that new accumulated irqs
10253191dd5aSJason A. Donenfeld 	 * are fresh.
10263191dd5aSJason A. Donenfeld 	 */
10273191dd5aSJason A. Donenfeld 	per_cpu_ptr(&irq_randomness, cpu)->count = 0;
10283191dd5aSJason A. Donenfeld 	return 0;
10293191dd5aSJason A. Donenfeld }
10303191dd5aSJason A. Donenfeld #endif
10313191dd5aSJason A. Donenfeld 
1032748bc4ddSJason A. Donenfeld static void mix_interrupt_randomness(struct timer_list *work)
103358340f8eSJason A. Donenfeld {
103458340f8eSJason A. Donenfeld 	struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
1035f5eab0e2SJason A. Donenfeld 	/*
10364b758edaSJason A. Donenfeld 	 * The size of the copied stack pool is explicitly 2 longs so that we
10374b758edaSJason A. Donenfeld 	 * only ever ingest half of the siphash output each time, retaining
10384b758edaSJason A. Donenfeld 	 * the other half as the next "key" that carries over. The entropy is
10394b758edaSJason A. Donenfeld 	 * supposed to be sufficiently dispersed between bits so on average
10404b758edaSJason A. Donenfeld 	 * we don't wind up "losing" some.
1041f5eab0e2SJason A. Donenfeld 	 */
10424b758edaSJason A. Donenfeld 	unsigned long pool[2];
1043e3e33fc2SJason A. Donenfeld 	unsigned int count;
104458340f8eSJason A. Donenfeld 
104558340f8eSJason A. Donenfeld 	/* Check to see if we're running on the wrong CPU due to hotplug. */
104658340f8eSJason A. Donenfeld 	local_irq_disable();
104758340f8eSJason A. Donenfeld 	if (fast_pool != this_cpu_ptr(&irq_randomness)) {
104858340f8eSJason A. Donenfeld 		local_irq_enable();
104958340f8eSJason A. Donenfeld 		return;
105058340f8eSJason A. Donenfeld 	}
105158340f8eSJason A. Donenfeld 
105258340f8eSJason A. Donenfeld 	/*
105358340f8eSJason A. Donenfeld 	 * Copy the pool to the stack so that the mixer always has a
105458340f8eSJason A. Donenfeld 	 * consistent view, before we reenable irqs again.
105558340f8eSJason A. Donenfeld 	 */
1056f5eab0e2SJason A. Donenfeld 	memcpy(pool, fast_pool->pool, sizeof(pool));
1057e3e33fc2SJason A. Donenfeld 	count = fast_pool->count;
10583191dd5aSJason A. Donenfeld 	fast_pool->count = 0;
105958340f8eSJason A. Donenfeld 	fast_pool->last = jiffies;
106058340f8eSJason A. Donenfeld 	local_irq_enable();
106158340f8eSJason A. Donenfeld 
106258340f8eSJason A. Donenfeld 	mix_pool_bytes(pool, sizeof(pool));
1063e78a802aSJason A. Donenfeld 	credit_init_bits(clamp_t(unsigned int, (count & U16_MAX) / 64, 1, sizeof(pool) * 8));
1064c2a7de4fSJason A. Donenfeld 
106558340f8eSJason A. Donenfeld 	memzero_explicit(pool, sizeof(pool));
106658340f8eSJason A. Donenfeld }
106758340f8eSJason A. Donenfeld 
1068703f7066SSebastian Andrzej Siewior void add_interrupt_randomness(int irq)
10691da177e4SLinus Torvalds {
107058340f8eSJason A. Donenfeld 	enum { MIX_INFLIGHT = 1U << 31 };
10714b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
10721b2a1a7eSChristoph Lameter 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
1073775f4b29STheodore Ts'o 	struct pt_regs *regs = get_irq_regs();
107458340f8eSJason A. Donenfeld 	unsigned int new_count;
10753060d6feSYinghai Lu 
1076791332b3SJason A. Donenfeld 	fast_mix(fast_pool->pool, entropy,
1077791332b3SJason A. Donenfeld 		 (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
10783191dd5aSJason A. Donenfeld 	new_count = ++fast_pool->count;
1079775f4b29STheodore Ts'o 
108058340f8eSJason A. Donenfeld 	if (new_count & MIX_INFLIGHT)
10811da177e4SLinus Torvalds 		return;
1082840f9507STheodore Ts'o 
1083534d2eafSJason A. Donenfeld 	if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
10841da177e4SLinus Torvalds 		return;
10851da177e4SLinus Torvalds 
10863191dd5aSJason A. Donenfeld 	fast_pool->count |= MIX_INFLIGHT;
1087748bc4ddSJason A. Donenfeld 	if (!timer_pending(&fast_pool->mix)) {
1088748bc4ddSJason A. Donenfeld 		fast_pool->mix.expires = jiffies;
1089748bc4ddSJason A. Donenfeld 		add_timer_on(&fast_pool->mix, raw_smp_processor_id());
1090748bc4ddSJason A. Donenfeld 	}
10911da177e4SLinus Torvalds }
10924b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
10931da177e4SLinus Torvalds 
1094a4b5c26bSJason A. Donenfeld /* There is one of these per entropy source */
1095a4b5c26bSJason A. Donenfeld struct timer_rand_state {
1096a4b5c26bSJason A. Donenfeld 	unsigned long last_time;
1097a4b5c26bSJason A. Donenfeld 	long last_delta, last_delta2;
1098a4b5c26bSJason A. Donenfeld };
1099a4b5c26bSJason A. Donenfeld 
1100a4b5c26bSJason A. Donenfeld /*
1101a4b5c26bSJason A. Donenfeld  * This function adds entropy to the entropy "pool" by using timing
1102a4b5c26bSJason A. Donenfeld  * delays. It uses the timer_rand_state structure to make an estimate
1103e3e33fc2SJason A. Donenfeld  * of how many bits of entropy this call has added to the pool. The
1104e3e33fc2SJason A. Donenfeld  * value "num" is also added to the pool; it should somehow describe
1105e3e33fc2SJason A. Donenfeld  * the type of event that just happened.
1106a4b5c26bSJason A. Donenfeld  */
1107a4b5c26bSJason A. Donenfeld static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1108a4b5c26bSJason A. Donenfeld {
1109a4b5c26bSJason A. Donenfeld 	unsigned long entropy = random_get_entropy(), now = jiffies, flags;
1110a4b5c26bSJason A. Donenfeld 	long delta, delta2, delta3;
1111e3e33fc2SJason A. Donenfeld 	unsigned int bits;
1112a4b5c26bSJason A. Donenfeld 
1113e3e33fc2SJason A. Donenfeld 	/*
1114e3e33fc2SJason A. Donenfeld 	 * If we're in a hard IRQ, add_interrupt_randomness() will be called
1115e3e33fc2SJason A. Donenfeld 	 * sometime after, so mix into the fast pool.
1116e3e33fc2SJason A. Donenfeld 	 */
1117e3e33fc2SJason A. Donenfeld 	if (in_hardirq()) {
1118791332b3SJason A. Donenfeld 		fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
1119e3e33fc2SJason A. Donenfeld 	} else {
1120a4b5c26bSJason A. Donenfeld 		spin_lock_irqsave(&input_pool.lock, flags);
1121a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&entropy, sizeof(entropy));
1122a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&num, sizeof(num));
1123a4b5c26bSJason A. Donenfeld 		spin_unlock_irqrestore(&input_pool.lock, flags);
1124e3e33fc2SJason A. Donenfeld 	}
1125a4b5c26bSJason A. Donenfeld 
1126a4b5c26bSJason A. Donenfeld 	if (crng_ready())
1127a4b5c26bSJason A. Donenfeld 		return;
1128a4b5c26bSJason A. Donenfeld 
1129a4b5c26bSJason A. Donenfeld 	/*
1130a4b5c26bSJason A. Donenfeld 	 * Calculate number of bits of randomness we probably added.
1131a4b5c26bSJason A. Donenfeld 	 * We take into account the first, second and third-order deltas
1132a4b5c26bSJason A. Donenfeld 	 * in order to make our estimate.
1133a4b5c26bSJason A. Donenfeld 	 */
1134a4b5c26bSJason A. Donenfeld 	delta = now - READ_ONCE(state->last_time);
1135a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_time, now);
1136a4b5c26bSJason A. Donenfeld 
1137a4b5c26bSJason A. Donenfeld 	delta2 = delta - READ_ONCE(state->last_delta);
1138a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta, delta);
1139a4b5c26bSJason A. Donenfeld 
1140a4b5c26bSJason A. Donenfeld 	delta3 = delta2 - READ_ONCE(state->last_delta2);
1141a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta2, delta2);
1142a4b5c26bSJason A. Donenfeld 
1143a4b5c26bSJason A. Donenfeld 	if (delta < 0)
1144a4b5c26bSJason A. Donenfeld 		delta = -delta;
1145a4b5c26bSJason A. Donenfeld 	if (delta2 < 0)
1146a4b5c26bSJason A. Donenfeld 		delta2 = -delta2;
1147a4b5c26bSJason A. Donenfeld 	if (delta3 < 0)
1148a4b5c26bSJason A. Donenfeld 		delta3 = -delta3;
1149a4b5c26bSJason A. Donenfeld 	if (delta > delta2)
1150a4b5c26bSJason A. Donenfeld 		delta = delta2;
1151a4b5c26bSJason A. Donenfeld 	if (delta > delta3)
1152a4b5c26bSJason A. Donenfeld 		delta = delta3;
1153a4b5c26bSJason A. Donenfeld 
1154a4b5c26bSJason A. Donenfeld 	/*
1155e3e33fc2SJason A. Donenfeld 	 * delta is now minimum absolute delta. Round down by 1 bit
1156e3e33fc2SJason A. Donenfeld 	 * on general principles, and limit entropy estimate to 11 bits.
1157a4b5c26bSJason A. Donenfeld 	 */
1158e3e33fc2SJason A. Donenfeld 	bits = min(fls(delta >> 1), 11);
1159e3e33fc2SJason A. Donenfeld 
1160e3e33fc2SJason A. Donenfeld 	/*
1161e3e33fc2SJason A. Donenfeld 	 * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
1162e3e33fc2SJason A. Donenfeld 	 * will run after this, which uses a different crediting scheme of 1 bit
1163e3e33fc2SJason A. Donenfeld 	 * per every 64 interrupts. In order to let that function do accounting
1164e3e33fc2SJason A. Donenfeld 	 * close to the one in this function, we credit a full 64/64 bit per bit,
1165e3e33fc2SJason A. Donenfeld 	 * and then subtract one to account for the extra one added.
1166e3e33fc2SJason A. Donenfeld 	 */
1167e3e33fc2SJason A. Donenfeld 	if (in_hardirq())
1168e3e33fc2SJason A. Donenfeld 		this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
1169e3e33fc2SJason A. Donenfeld 	else
1170560181c2SJason A. Donenfeld 		_credit_init_bits(bits);
1171a4b5c26bSJason A. Donenfeld }
1172a4b5c26bSJason A. Donenfeld 
1173a1940263SJason A. Donenfeld void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
1174a4b5c26bSJason A. Donenfeld {
1175a4b5c26bSJason A. Donenfeld 	static unsigned char last_value;
1176a4b5c26bSJason A. Donenfeld 	static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
1177a4b5c26bSJason A. Donenfeld 
1178a4b5c26bSJason A. Donenfeld 	/* Ignore autorepeat and the like. */
1179a4b5c26bSJason A. Donenfeld 	if (value == last_value)
1180a4b5c26bSJason A. Donenfeld 		return;
1181a4b5c26bSJason A. Donenfeld 
1182a4b5c26bSJason A. Donenfeld 	last_value = value;
1183a4b5c26bSJason A. Donenfeld 	add_timer_randomness(&input_timer_state,
1184a4b5c26bSJason A. Donenfeld 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1185a4b5c26bSJason A. Donenfeld }
1186a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_input_randomness);
1187a4b5c26bSJason A. Donenfeld 
1188a4b5c26bSJason A. Donenfeld #ifdef CONFIG_BLOCK
1189a4b5c26bSJason A. Donenfeld void add_disk_randomness(struct gendisk *disk)
1190a4b5c26bSJason A. Donenfeld {
1191a4b5c26bSJason A. Donenfeld 	if (!disk || !disk->random)
1192a4b5c26bSJason A. Donenfeld 		return;
1193a4b5c26bSJason A. Donenfeld 	/* First major is 1, so we get >= 0x200 here. */
1194a4b5c26bSJason A. Donenfeld 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1195a4b5c26bSJason A. Donenfeld }
1196a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_disk_randomness);
1197a4b5c26bSJason A. Donenfeld 
1198560181c2SJason A. Donenfeld void __cold rand_initialize_disk(struct gendisk *disk)
1199a4b5c26bSJason A. Donenfeld {
1200a4b5c26bSJason A. Donenfeld 	struct timer_rand_state *state;
1201a4b5c26bSJason A. Donenfeld 
1202a4b5c26bSJason A. Donenfeld 	/*
1203a4b5c26bSJason A. Donenfeld 	 * If kzalloc returns null, we just won't use that entropy
1204a4b5c26bSJason A. Donenfeld 	 * source.
1205a4b5c26bSJason A. Donenfeld 	 */
1206a4b5c26bSJason A. Donenfeld 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1207a4b5c26bSJason A. Donenfeld 	if (state) {
1208a4b5c26bSJason A. Donenfeld 		state->last_time = INITIAL_JIFFIES;
1209a4b5c26bSJason A. Donenfeld 		disk->random = state;
1210a4b5c26bSJason A. Donenfeld 	}
1211a4b5c26bSJason A. Donenfeld }
1212a4b5c26bSJason A. Donenfeld #endif
1213a4b5c26bSJason A. Donenfeld 
121478c768e6SJason A. Donenfeld struct entropy_timer_state {
121578c768e6SJason A. Donenfeld 	unsigned long entropy;
121678c768e6SJason A. Donenfeld 	struct timer_list timer;
121778c768e6SJason A. Donenfeld 	unsigned int samples, samples_per_bit;
121878c768e6SJason A. Donenfeld };
121978c768e6SJason A. Donenfeld 
12201da177e4SLinus Torvalds /*
122150ee7529SLinus Torvalds  * Each time the timer fires, we expect that we got an unpredictable
122250ee7529SLinus Torvalds  * jump in the cycle counter. Even if the timer is running on another
122350ee7529SLinus Torvalds  * CPU, the timer activity will be touching the stack of the CPU that is
122450ee7529SLinus Torvalds  * generating entropy..
122550ee7529SLinus Torvalds  *
122650ee7529SLinus Torvalds  * Note that we don't re-arm the timer in the timer itself - we are
122750ee7529SLinus Torvalds  * happy to be scheduled away, since that just makes the load more
122850ee7529SLinus Torvalds  * complex, but we do not want the timer to keep ticking unless the
122950ee7529SLinus Torvalds  * entropy loop is running.
123050ee7529SLinus Torvalds  *
123150ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
123250ee7529SLinus Torvalds  */
1233560181c2SJason A. Donenfeld static void __cold entropy_timer(struct timer_list *timer)
123450ee7529SLinus Torvalds {
123578c768e6SJason A. Donenfeld 	struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
123678c768e6SJason A. Donenfeld 
123778c768e6SJason A. Donenfeld 	if (++state->samples == state->samples_per_bit) {
1238e85c0fc1SJason A. Donenfeld 		credit_init_bits(1);
123978c768e6SJason A. Donenfeld 		state->samples = 0;
124078c768e6SJason A. Donenfeld 	}
124150ee7529SLinus Torvalds }
124250ee7529SLinus Torvalds 
124350ee7529SLinus Torvalds /*
124450ee7529SLinus Torvalds  * If we have an actual cycle counter, see if we can
124550ee7529SLinus Torvalds  * generate enough entropy with timing noise
124650ee7529SLinus Torvalds  */
1247560181c2SJason A. Donenfeld static void __cold try_to_generate_entropy(void)
124850ee7529SLinus Torvalds {
124912273347SJason A. Donenfeld 	enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 15 };
125078c768e6SJason A. Donenfeld 	struct entropy_timer_state stack;
125178c768e6SJason A. Donenfeld 	unsigned int i, num_different = 0;
125278c768e6SJason A. Donenfeld 	unsigned long last = random_get_entropy();
125350ee7529SLinus Torvalds 
125478c768e6SJason A. Donenfeld 	for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
12554b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
125678c768e6SJason A. Donenfeld 		if (stack.entropy != last)
125778c768e6SJason A. Donenfeld 			++num_different;
125878c768e6SJason A. Donenfeld 		last = stack.entropy;
125978c768e6SJason A. Donenfeld 	}
126078c768e6SJason A. Donenfeld 	stack.samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
126178c768e6SJason A. Donenfeld 	if (stack.samples_per_bit > MAX_SAMPLES_PER_BIT)
126250ee7529SLinus Torvalds 		return;
126350ee7529SLinus Torvalds 
126478c768e6SJason A. Donenfeld 	stack.samples = 0;
126550ee7529SLinus Torvalds 	timer_setup_on_stack(&stack.timer, entropy_timer, 0);
12663e504d20SJason A. Donenfeld 	while (!crng_ready() && !signal_pending(current)) {
126750ee7529SLinus Torvalds 		if (!timer_pending(&stack.timer))
126812273347SJason A. Donenfeld 			mod_timer(&stack.timer, jiffies);
12694b758edaSJason A. Donenfeld 		mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
127050ee7529SLinus Torvalds 		schedule();
12714b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
127250ee7529SLinus Torvalds 	}
127350ee7529SLinus Torvalds 
127450ee7529SLinus Torvalds 	del_timer_sync(&stack.timer);
127550ee7529SLinus Torvalds 	destroy_timer_on_stack(&stack.timer);
12764b758edaSJason A. Donenfeld 	mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
127750ee7529SLinus Torvalds }
127850ee7529SLinus Torvalds 
1279a6adf8e7SJason A. Donenfeld 
1280a6adf8e7SJason A. Donenfeld /**********************************************************************
1281a6adf8e7SJason A. Donenfeld  *
1282a6adf8e7SJason A. Donenfeld  * Userspace reader/writer interfaces.
1283a6adf8e7SJason A. Donenfeld  *
1284a6adf8e7SJason A. Donenfeld  * getrandom(2) is the primary modern interface into the RNG and should
1285a6adf8e7SJason A. Donenfeld  * be used in preference to anything else.
1286a6adf8e7SJason A. Donenfeld  *
12870313bc27SLinus Torvalds  * Reading from /dev/random has the same functionality as calling
12880313bc27SLinus Torvalds  * getrandom(2) with flags=0. In earlier versions, however, it had
12890313bc27SLinus Torvalds  * vastly different semantics and should therefore be avoided, to
12900313bc27SLinus Torvalds  * prevent backwards compatibility issues.
12910313bc27SLinus Torvalds  *
12920313bc27SLinus Torvalds  * Reading from /dev/urandom has the same functionality as calling
12930313bc27SLinus Torvalds  * getrandom(2) with flags=GRND_INSECURE. Because it does not block
12940313bc27SLinus Torvalds  * waiting for the RNG to be ready, it should not be used.
1295a6adf8e7SJason A. Donenfeld  *
1296a6adf8e7SJason A. Donenfeld  * Writing to either /dev/random or /dev/urandom adds entropy to
1297a6adf8e7SJason A. Donenfeld  * the input pool but does not credit it.
1298a6adf8e7SJason A. Donenfeld  *
12990313bc27SLinus Torvalds  * Polling on /dev/random indicates when the RNG is initialized, on
13000313bc27SLinus Torvalds  * the read side, and when it wants new entropy, on the write side.
1301a6adf8e7SJason A. Donenfeld  *
1302a6adf8e7SJason A. Donenfeld  * Both /dev/random and /dev/urandom have the same set of ioctls for
1303a6adf8e7SJason A. Donenfeld  * adding entropy, getting the entropy count, zeroing the count, and
1304a6adf8e7SJason A. Donenfeld  * reseeding the crng.
1305a6adf8e7SJason A. Donenfeld  *
1306a6adf8e7SJason A. Donenfeld  **********************************************************************/
1307a6adf8e7SJason A. Donenfeld 
1308a1940263SJason A. Donenfeld SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
13091da177e4SLinus Torvalds {
13101b388e77SJens Axboe 	struct iov_iter iter;
13111b388e77SJens Axboe 	struct iovec iov;
13121b388e77SJens Axboe 	int ret;
13131b388e77SJens Axboe 
1314a6adf8e7SJason A. Donenfeld 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
1315a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1316301f0595STheodore Ts'o 
1317a6adf8e7SJason A. Donenfeld 	/*
1318a6adf8e7SJason A. Donenfeld 	 * Requesting insecure and blocking randomness at the same time makes
1319a6adf8e7SJason A. Donenfeld 	 * no sense.
1320a6adf8e7SJason A. Donenfeld 	 */
1321a6adf8e7SJason A. Donenfeld 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1322a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1323c6f1deb1SAndy Lutomirski 
1324f5bda35fSJason A. Donenfeld 	if (!crng_ready() && !(flags & GRND_INSECURE)) {
1325a6adf8e7SJason A. Donenfeld 		if (flags & GRND_NONBLOCK)
1326a6adf8e7SJason A. Donenfeld 			return -EAGAIN;
132730c08efeSAndy Lutomirski 		ret = wait_for_random_bytes();
1328a6adf8e7SJason A. Donenfeld 		if (unlikely(ret))
132930c08efeSAndy Lutomirski 			return ret;
1330a6adf8e7SJason A. Donenfeld 	}
13311b388e77SJens Axboe 
13321b388e77SJens Axboe 	ret = import_single_range(READ, ubuf, len, &iov, &iter);
13331b388e77SJens Axboe 	if (unlikely(ret))
13341b388e77SJens Axboe 		return ret;
13351b388e77SJens Axboe 	return get_random_bytes_user(&iter);
133630c08efeSAndy Lutomirski }
133730c08efeSAndy Lutomirski 
1338248045b8SJason A. Donenfeld static __poll_t random_poll(struct file *file, poll_table *wait)
133989b310a2SChristoph Hellwig {
134030c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1341e85c0fc1SJason A. Donenfeld 	return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
13421da177e4SLinus Torvalds }
13431da177e4SLinus Torvalds 
13441ce6c8d6SJason A. Donenfeld static ssize_t write_pool_user(struct iov_iter *iter)
13457f397dcdSMatt Mackall {
134604ec96b7SJason A. Donenfeld 	u8 block[BLAKE2S_BLOCK_SIZE];
134722b0a222SJens Axboe 	ssize_t ret = 0;
134822b0a222SJens Axboe 	size_t copied;
13497f397dcdSMatt Mackall 
135022b0a222SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
135122b0a222SJens Axboe 		return 0;
135222b0a222SJens Axboe 
135322b0a222SJens Axboe 	for (;;) {
135422b0a222SJens Axboe 		copied = copy_from_iter(block, sizeof(block), iter);
135522b0a222SJens Axboe 		ret += copied;
135622b0a222SJens Axboe 		mix_pool_bytes(block, copied);
135722b0a222SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
135822b0a222SJens Axboe 			break;
13591ce6c8d6SJason A. Donenfeld 
13601ce6c8d6SJason A. Donenfeld 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
13611ce6c8d6SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
13621ce6c8d6SJason A. Donenfeld 			if (signal_pending(current))
13631ce6c8d6SJason A. Donenfeld 				break;
136491f3f1e3SMatt Mackall 			cond_resched();
13657f397dcdSMatt Mackall 		}
13661ce6c8d6SJason A. Donenfeld 	}
13677f397dcdSMatt Mackall 
13687b5164fbSJason A. Donenfeld 	memzero_explicit(block, sizeof(block));
136922b0a222SJens Axboe 	return ret ? ret : -EFAULT;
13707f397dcdSMatt Mackall }
13717f397dcdSMatt Mackall 
137222b0a222SJens Axboe static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
13731da177e4SLinus Torvalds {
13741ce6c8d6SJason A. Donenfeld 	return write_pool_user(iter);
13751da177e4SLinus Torvalds }
13761da177e4SLinus Torvalds 
13771b388e77SJens Axboe static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
13780313bc27SLinus Torvalds {
13790313bc27SLinus Torvalds 	static int maxwarn = 10;
13800313bc27SLinus Torvalds 
138148bff105SJason A. Donenfeld 	/*
138248bff105SJason A. Donenfeld 	 * Opportunistically attempt to initialize the RNG on platforms that
138348bff105SJason A. Donenfeld 	 * have fast cycle counters, but don't (for now) require it to succeed.
138448bff105SJason A. Donenfeld 	 */
138548bff105SJason A. Donenfeld 	if (!crng_ready())
138648bff105SJason A. Donenfeld 		try_to_generate_entropy();
138748bff105SJason A. Donenfeld 
1388cc1e127bSJason A. Donenfeld 	if (!crng_ready()) {
1389cc1e127bSJason A. Donenfeld 		if (!ratelimit_disable && maxwarn <= 0)
1390cc1e127bSJason A. Donenfeld 			++urandom_warning.missed;
1391cc1e127bSJason A. Donenfeld 		else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
1392cc1e127bSJason A. Donenfeld 			--maxwarn;
13931b388e77SJens Axboe 			pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
13941b388e77SJens Axboe 				  current->comm, iov_iter_count(iter));
13950313bc27SLinus Torvalds 		}
1396cc1e127bSJason A. Donenfeld 	}
13970313bc27SLinus Torvalds 
13981b388e77SJens Axboe 	return get_random_bytes_user(iter);
13990313bc27SLinus Torvalds }
14000313bc27SLinus Torvalds 
14011b388e77SJens Axboe static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
1402a6adf8e7SJason A. Donenfeld {
1403a6adf8e7SJason A. Donenfeld 	int ret;
1404a6adf8e7SJason A. Donenfeld 
1405cd4f24aeSJason A. Donenfeld 	if (!crng_ready() &&
1406cd4f24aeSJason A. Donenfeld 	    ((kiocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) ||
1407cd4f24aeSJason A. Donenfeld 	     (kiocb->ki_filp->f_flags & O_NONBLOCK)))
1408cd4f24aeSJason A. Donenfeld 		return -EAGAIN;
1409cd4f24aeSJason A. Donenfeld 
1410a6adf8e7SJason A. Donenfeld 	ret = wait_for_random_bytes();
1411a6adf8e7SJason A. Donenfeld 	if (ret != 0)
1412a6adf8e7SJason A. Donenfeld 		return ret;
14131b388e77SJens Axboe 	return get_random_bytes_user(iter);
1414a6adf8e7SJason A. Donenfeld }
1415a6adf8e7SJason A. Donenfeld 
141643ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
14171da177e4SLinus Torvalds {
14181da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
141922b0a222SJens Axboe 	int ent_count;
14201da177e4SLinus Torvalds 
14211da177e4SLinus Torvalds 	switch (cmd) {
14221da177e4SLinus Torvalds 	case RNDGETENTCNT:
1423a6adf8e7SJason A. Donenfeld 		/* Inherently racy, no point locking. */
1424e85c0fc1SJason A. Donenfeld 		if (put_user(input_pool.init_bits, p))
14251da177e4SLinus Torvalds 			return -EFAULT;
14261da177e4SLinus Torvalds 		return 0;
14271da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
14281da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14291da177e4SLinus Torvalds 			return -EPERM;
14301da177e4SLinus Torvalds 		if (get_user(ent_count, p))
14311da177e4SLinus Torvalds 			return -EFAULT;
1432a49c010eSJason A. Donenfeld 		if (ent_count < 0)
1433a49c010eSJason A. Donenfeld 			return -EINVAL;
1434e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1435a49c010eSJason A. Donenfeld 		return 0;
143622b0a222SJens Axboe 	case RNDADDENTROPY: {
143722b0a222SJens Axboe 		struct iov_iter iter;
143822b0a222SJens Axboe 		struct iovec iov;
143922b0a222SJens Axboe 		ssize_t ret;
144022b0a222SJens Axboe 		int len;
144122b0a222SJens Axboe 
14421da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14431da177e4SLinus Torvalds 			return -EPERM;
14441da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
14451da177e4SLinus Torvalds 			return -EFAULT;
14461da177e4SLinus Torvalds 		if (ent_count < 0)
14471da177e4SLinus Torvalds 			return -EINVAL;
144822b0a222SJens Axboe 		if (get_user(len, p++))
14491da177e4SLinus Torvalds 			return -EFAULT;
145022b0a222SJens Axboe 		ret = import_single_range(WRITE, p, len, &iov, &iter);
145122b0a222SJens Axboe 		if (unlikely(ret))
145222b0a222SJens Axboe 			return ret;
14531ce6c8d6SJason A. Donenfeld 		ret = write_pool_user(&iter);
145422b0a222SJens Axboe 		if (unlikely(ret < 0))
145522b0a222SJens Axboe 			return ret;
145622b0a222SJens Axboe 		/* Since we're crediting, enforce that it was all written into the pool. */
145722b0a222SJens Axboe 		if (unlikely(ret != len))
145822b0a222SJens Axboe 			return -EFAULT;
1459e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1460a49c010eSJason A. Donenfeld 		return 0;
146122b0a222SJens Axboe 	}
14621da177e4SLinus Torvalds 	case RNDZAPENTCNT:
14631da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1464e85c0fc1SJason A. Donenfeld 		/* No longer has any effect. */
14651da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14661da177e4SLinus Torvalds 			return -EPERM;
14671da177e4SLinus Torvalds 		return 0;
1468d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1469d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1470d848e5f8STheodore Ts'o 			return -EPERM;
1471a96cfe2dSJason A. Donenfeld 		if (!crng_ready())
1472d848e5f8STheodore Ts'o 			return -ENODATA;
1473e85c0fc1SJason A. Donenfeld 		crng_reseed();
1474d848e5f8STheodore Ts'o 		return 0;
14751da177e4SLinus Torvalds 	default:
14761da177e4SLinus Torvalds 		return -EINVAL;
14771da177e4SLinus Torvalds 	}
14781da177e4SLinus Torvalds }
14791da177e4SLinus Torvalds 
14809a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
14819a6f70bbSJeff Dike {
14829a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
14839a6f70bbSJeff Dike }
14849a6f70bbSJeff Dike 
14852b8693c0SArjan van de Ven const struct file_operations random_fops = {
14861b388e77SJens Axboe 	.read_iter = random_read_iter,
148722b0a222SJens Axboe 	.write_iter = random_write_iter,
1488a11e1d43SLinus Torvalds 	.poll = random_poll,
148943ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1490507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
14919a6f70bbSJeff Dike 	.fasync = random_fasync,
14926038f373SArnd Bergmann 	.llseek = noop_llseek,
149379025e72SJens Axboe 	.splice_read = generic_file_splice_read,
149479025e72SJens Axboe 	.splice_write = iter_file_splice_write,
14951da177e4SLinus Torvalds };
14961da177e4SLinus Torvalds 
14970313bc27SLinus Torvalds const struct file_operations urandom_fops = {
14981b388e77SJens Axboe 	.read_iter = urandom_read_iter,
149922b0a222SJens Axboe 	.write_iter = random_write_iter,
15000313bc27SLinus Torvalds 	.unlocked_ioctl = random_ioctl,
15010313bc27SLinus Torvalds 	.compat_ioctl = compat_ptr_ioctl,
15020313bc27SLinus Torvalds 	.fasync = random_fasync,
15030313bc27SLinus Torvalds 	.llseek = noop_llseek,
150479025e72SJens Axboe 	.splice_read = generic_file_splice_read,
150579025e72SJens Axboe 	.splice_write = iter_file_splice_write,
15060313bc27SLinus Torvalds };
15070313bc27SLinus Torvalds 
15080deff3c4SJason A. Donenfeld 
15091da177e4SLinus Torvalds /********************************************************************
15101da177e4SLinus Torvalds  *
15110deff3c4SJason A. Donenfeld  * Sysctl interface.
15120deff3c4SJason A. Donenfeld  *
15130deff3c4SJason A. Donenfeld  * These are partly unused legacy knobs with dummy values to not break
15140deff3c4SJason A. Donenfeld  * userspace and partly still useful things. They are usually accessible
15150deff3c4SJason A. Donenfeld  * in /proc/sys/kernel/random/ and are as follows:
15160deff3c4SJason A. Donenfeld  *
15170deff3c4SJason A. Donenfeld  * - boot_id - a UUID representing the current boot.
15180deff3c4SJason A. Donenfeld  *
15190deff3c4SJason A. Donenfeld  * - uuid - a random UUID, different each time the file is read.
15200deff3c4SJason A. Donenfeld  *
15210deff3c4SJason A. Donenfeld  * - poolsize - the number of bits of entropy that the input pool can
15220deff3c4SJason A. Donenfeld  *   hold, tied to the POOL_BITS constant.
15230deff3c4SJason A. Donenfeld  *
15240deff3c4SJason A. Donenfeld  * - entropy_avail - the number of bits of entropy currently in the
15250deff3c4SJason A. Donenfeld  *   input pool. Always <= poolsize.
15260deff3c4SJason A. Donenfeld  *
15270deff3c4SJason A. Donenfeld  * - write_wakeup_threshold - the amount of entropy in the input pool
15280deff3c4SJason A. Donenfeld  *   below which write polls to /dev/random will unblock, requesting
1529e3d2c5e7SJason A. Donenfeld  *   more entropy, tied to the POOL_READY_BITS constant. It is writable
15300deff3c4SJason A. Donenfeld  *   to avoid breaking old userspaces, but writing to it does not
15310deff3c4SJason A. Donenfeld  *   change any behavior of the RNG.
15320deff3c4SJason A. Donenfeld  *
1533d0efdf35SJason A. Donenfeld  * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
15340deff3c4SJason A. Donenfeld  *   It is writable to avoid breaking old userspaces, but writing
15350deff3c4SJason A. Donenfeld  *   to it does not change any behavior of the RNG.
15361da177e4SLinus Torvalds  *
15371da177e4SLinus Torvalds  ********************************************************************/
15381da177e4SLinus Torvalds 
15391da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
15401da177e4SLinus Torvalds 
15411da177e4SLinus Torvalds #include <linux/sysctl.h>
15421da177e4SLinus Torvalds 
1543d0efdf35SJason A. Donenfeld static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
1544e3d2c5e7SJason A. Donenfeld static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
1545489c7fc4SJason A. Donenfeld static int sysctl_poolsize = POOL_BITS;
154664276a99SJason A. Donenfeld static u8 sysctl_bootid[UUID_SIZE];
15471da177e4SLinus Torvalds 
15481da177e4SLinus Torvalds /*
1549f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
15501da177e4SLinus Torvalds  * UUID. The difference is in whether table->data is NULL; if it is,
15511da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
15521da177e4SLinus Torvalds  */
1553a1940263SJason A. Donenfeld static int proc_do_uuid(struct ctl_table *table, int write, void *buf,
1554248045b8SJason A. Donenfeld 			size_t *lenp, loff_t *ppos)
15551da177e4SLinus Torvalds {
155664276a99SJason A. Donenfeld 	u8 tmp_uuid[UUID_SIZE], *uuid;
155764276a99SJason A. Donenfeld 	char uuid_string[UUID_STRING_LEN + 1];
155864276a99SJason A. Donenfeld 	struct ctl_table fake_table = {
155964276a99SJason A. Donenfeld 		.data = uuid_string,
156064276a99SJason A. Donenfeld 		.maxlen = UUID_STRING_LEN
156164276a99SJason A. Donenfeld 	};
156264276a99SJason A. Donenfeld 
156364276a99SJason A. Donenfeld 	if (write)
156464276a99SJason A. Donenfeld 		return -EPERM;
15651da177e4SLinus Torvalds 
15661da177e4SLinus Torvalds 	uuid = table->data;
15671da177e4SLinus Torvalds 	if (!uuid) {
15681da177e4SLinus Torvalds 		uuid = tmp_uuid;
15691da177e4SLinus Torvalds 		generate_random_uuid(uuid);
157044e4360fSMathieu Desnoyers 	} else {
157144e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
157244e4360fSMathieu Desnoyers 
157344e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
157444e4360fSMathieu Desnoyers 		if (!uuid[8])
157544e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
157644e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
157744e4360fSMathieu Desnoyers 	}
15781da177e4SLinus Torvalds 
157964276a99SJason A. Donenfeld 	snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
1580a1940263SJason A. Donenfeld 	return proc_dostring(&fake_table, 0, buf, lenp, ppos);
15811da177e4SLinus Torvalds }
15821da177e4SLinus Torvalds 
158377553cf8SJason A. Donenfeld /* The same as proc_dointvec, but writes don't change anything. */
1584a1940263SJason A. Donenfeld static int proc_do_rointvec(struct ctl_table *table, int write, void *buf,
158577553cf8SJason A. Donenfeld 			    size_t *lenp, loff_t *ppos)
158677553cf8SJason A. Donenfeld {
1587a1940263SJason A. Donenfeld 	return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
158877553cf8SJason A. Donenfeld }
158977553cf8SJason A. Donenfeld 
15905475e8f0SXiaoming Ni static struct ctl_table random_table[] = {
15911da177e4SLinus Torvalds 	{
15921da177e4SLinus Torvalds 		.procname	= "poolsize",
15931da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
15941da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15951da177e4SLinus Torvalds 		.mode		= 0444,
15966d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
15971da177e4SLinus Torvalds 	},
15981da177e4SLinus Torvalds 	{
15991da177e4SLinus Torvalds 		.procname	= "entropy_avail",
1600e85c0fc1SJason A. Donenfeld 		.data		= &input_pool.init_bits,
16011da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16021da177e4SLinus Torvalds 		.mode		= 0444,
1603c5704490SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
16041da177e4SLinus Torvalds 	},
16051da177e4SLinus Torvalds 	{
16061da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
16070deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_write_wakeup_bits,
16081da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16091da177e4SLinus Torvalds 		.mode		= 0644,
161077553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
16111da177e4SLinus Torvalds 	},
16121da177e4SLinus Torvalds 	{
1613f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
16140deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_min_urandom_seed,
1615f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1616f5c2742cSTheodore Ts'o 		.mode		= 0644,
161777553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
1618f5c2742cSTheodore Ts'o 	},
1619f5c2742cSTheodore Ts'o 	{
16201da177e4SLinus Torvalds 		.procname	= "boot_id",
16211da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
16221da177e4SLinus Torvalds 		.mode		= 0444,
16236d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16241da177e4SLinus Torvalds 	},
16251da177e4SLinus Torvalds 	{
16261da177e4SLinus Torvalds 		.procname	= "uuid",
16271da177e4SLinus Torvalds 		.mode		= 0444,
16286d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16291da177e4SLinus Torvalds 	},
1630894d2491SEric W. Biederman 	{ }
16311da177e4SLinus Torvalds };
16325475e8f0SXiaoming Ni 
16335475e8f0SXiaoming Ni /*
16342f14062bSJason A. Donenfeld  * random_init() is called before sysctl_init(),
16352f14062bSJason A. Donenfeld  * so we cannot call register_sysctl_init() in random_init()
16365475e8f0SXiaoming Ni  */
16375475e8f0SXiaoming Ni static int __init random_sysctls_init(void)
16385475e8f0SXiaoming Ni {
16395475e8f0SXiaoming Ni 	register_sysctl_init("kernel/random", random_table);
16405475e8f0SXiaoming Ni 	return 0;
16415475e8f0SXiaoming Ni }
16425475e8f0SXiaoming Ni device_initcall(random_sysctls_init);
16430deff3c4SJason A. Donenfeld #endif
1644