xref: /linux/drivers/char/random.c (revision b7a68f67ff4911e8a842d03f6f97fa91a8d483f5)
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
990313bc27SLinus Torvalds  * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
1000313bc27SLinus Torvalds  * ,u64,int,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
1220313bc27SLinus Torvalds  * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1230313bc27SLinus Torvalds  * family of functions. Using any of these functions without first calling
1240313bc27SLinus Torvalds  * 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)
1603655adc7SJason A. Donenfeld  *	u32 get_random_u32()
1613655adc7SJason A. Donenfeld  *	u64 get_random_u64()
1623655adc7SJason A. Donenfeld  *	unsigned int get_random_int()
1633655adc7SJason A. Donenfeld  *	unsigned long get_random_long()
1643655adc7SJason A. Donenfeld  *
1653655adc7SJason A. Donenfeld  * These interfaces will return the requested number of random bytes
1660313bc27SLinus Torvalds  * into the given buffer or as a return value. This is equivalent to
167dd7aa36eSJason A. Donenfeld  * a read from /dev/urandom. The u32, u64, int, and long family of
168dd7aa36eSJason A. Donenfeld  * functions may be higher performance for one-off random integers,
169dd7aa36eSJason A. Donenfeld  * because they do a bit of buffering and do not invoke reseeding
170dd7aa36eSJason A. Donenfeld  * until the buffer is emptied.
1713655adc7SJason A. Donenfeld  *
1723655adc7SJason A. Donenfeld  *********************************************************************/
1733655adc7SJason A. Donenfeld 
174e85c0fc1SJason A. Donenfeld enum {
175e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_START_INTERVAL = HZ,
176e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_INTERVAL = 60 * HZ
177e85c0fc1SJason A. Donenfeld };
1783655adc7SJason A. Donenfeld 
1793655adc7SJason A. Donenfeld static struct {
1803655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
1813655adc7SJason A. Donenfeld 	unsigned long birth;
1823655adc7SJason A. Donenfeld 	unsigned long generation;
1833655adc7SJason A. Donenfeld 	spinlock_t lock;
1843655adc7SJason A. Donenfeld } base_crng = {
1853655adc7SJason A. Donenfeld 	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
1863655adc7SJason A. Donenfeld };
1873655adc7SJason A. Donenfeld 
1883655adc7SJason A. Donenfeld struct crng {
1893655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
1903655adc7SJason A. Donenfeld 	unsigned long generation;
1913655adc7SJason A. Donenfeld 	local_lock_t lock;
1923655adc7SJason A. Donenfeld };
1933655adc7SJason A. Donenfeld 
1943655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct crng, crngs) = {
1953655adc7SJason A. Donenfeld 	.generation = ULONG_MAX,
1963655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(crngs.lock),
1973655adc7SJason A. Donenfeld };
1983655adc7SJason A. Donenfeld 
199e85c0fc1SJason A. Donenfeld /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
200a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len);
2013655adc7SJason A. Donenfeld 
202e85c0fc1SJason A. Donenfeld /* This extracts a new crng key from the input pool. */
203e85c0fc1SJason A. Donenfeld static void crng_reseed(void)
2043655adc7SJason A. Donenfeld {
2053655adc7SJason A. Donenfeld 	unsigned long flags;
2063655adc7SJason A. Donenfeld 	unsigned long next_gen;
2073655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2083655adc7SJason A. Donenfeld 
209e85c0fc1SJason A. Donenfeld 	extract_entropy(key, sizeof(key));
2103655adc7SJason A. Donenfeld 
2113655adc7SJason A. Donenfeld 	/*
2123655adc7SJason A. Donenfeld 	 * We copy the new key into the base_crng, overwriting the old one,
2133655adc7SJason A. Donenfeld 	 * and update the generation counter. We avoid hitting ULONG_MAX,
2143655adc7SJason A. Donenfeld 	 * because the per-cpu crngs are initialized to ULONG_MAX, so this
2153655adc7SJason A. Donenfeld 	 * forces new CPUs that come online to always initialize.
2163655adc7SJason A. Donenfeld 	 */
2173655adc7SJason A. Donenfeld 	spin_lock_irqsave(&base_crng.lock, flags);
2183655adc7SJason A. Donenfeld 	memcpy(base_crng.key, key, sizeof(base_crng.key));
2193655adc7SJason A. Donenfeld 	next_gen = base_crng.generation + 1;
2203655adc7SJason A. Donenfeld 	if (next_gen == ULONG_MAX)
2213655adc7SJason A. Donenfeld 		++next_gen;
2223655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.generation, next_gen);
2233655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.birth, jiffies);
224f5bda35fSJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready))
225e3d2c5e7SJason A. Donenfeld 		crng_init = CRNG_READY;
2263655adc7SJason A. Donenfeld 	spin_unlock_irqrestore(&base_crng.lock, flags);
2273655adc7SJason A. Donenfeld 	memzero_explicit(key, sizeof(key));
2283655adc7SJason A. Donenfeld }
2293655adc7SJason A. Donenfeld 
2303655adc7SJason A. Donenfeld /*
2313655adc7SJason A. Donenfeld  * This generates a ChaCha block using the provided key, and then
2323655adc7SJason A. Donenfeld  * immediately overwites that key with half the block. It returns
2333655adc7SJason A. Donenfeld  * the resultant ChaCha state to the user, along with the second
2343655adc7SJason A. Donenfeld  * half of the block containing 32 bytes of random data that may
2353655adc7SJason A. Donenfeld  * be used; random_data_len may not be greater than 32.
2368717627dSJason A. Donenfeld  *
2378717627dSJason A. Donenfeld  * The returned ChaCha state contains within it a copy of the old
2388717627dSJason A. Donenfeld  * key value, at index 4, so the state should always be zeroed out
2398717627dSJason A. Donenfeld  * immediately after using in order to maintain forward secrecy.
2408717627dSJason A. Donenfeld  * If the state cannot be erased in a timely manner, then it is
2418717627dSJason A. Donenfeld  * safer to set the random_data parameter to &chacha_state[4] so
2428717627dSJason A. Donenfeld  * that this function overwrites it before returning.
2433655adc7SJason A. Donenfeld  */
2443655adc7SJason A. Donenfeld static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
2453655adc7SJason A. Donenfeld 				  u32 chacha_state[CHACHA_STATE_WORDS],
2463655adc7SJason A. Donenfeld 				  u8 *random_data, size_t random_data_len)
2473655adc7SJason A. Donenfeld {
2483655adc7SJason A. Donenfeld 	u8 first_block[CHACHA_BLOCK_SIZE];
2493655adc7SJason A. Donenfeld 
2503655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
2513655adc7SJason A. Donenfeld 
2523655adc7SJason A. Donenfeld 	chacha_init_consts(chacha_state);
2533655adc7SJason A. Donenfeld 	memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
2543655adc7SJason A. Donenfeld 	memset(&chacha_state[12], 0, sizeof(u32) * 4);
2553655adc7SJason A. Donenfeld 	chacha20_block(chacha_state, first_block);
2563655adc7SJason A. Donenfeld 
2573655adc7SJason A. Donenfeld 	memcpy(key, first_block, CHACHA_KEY_SIZE);
2588717627dSJason A. Donenfeld 	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
2593655adc7SJason A. Donenfeld 	memzero_explicit(first_block, sizeof(first_block));
2603655adc7SJason A. Donenfeld }
2613655adc7SJason A. Donenfeld 
2623655adc7SJason A. Donenfeld /*
263e85c0fc1SJason A. Donenfeld  * Return whether the crng seed is considered to be sufficiently old
264e85c0fc1SJason A. Donenfeld  * that a reseeding is needed. This happens if the last reseeding
265e85c0fc1SJason A. Donenfeld  * was CRNG_RESEED_INTERVAL ago, or during early boot, at an interval
266e85c0fc1SJason A. Donenfeld  * proportional to the uptime.
2677a7ff644SJason A. Donenfeld  */
2687a7ff644SJason A. Donenfeld static bool crng_has_old_seed(void)
2697a7ff644SJason A. Donenfeld {
2707a7ff644SJason A. Donenfeld 	static bool early_boot = true;
2717a7ff644SJason A. Donenfeld 	unsigned long interval = CRNG_RESEED_INTERVAL;
2727a7ff644SJason A. Donenfeld 
2737a7ff644SJason A. Donenfeld 	if (unlikely(READ_ONCE(early_boot))) {
2747a7ff644SJason A. Donenfeld 		time64_t uptime = ktime_get_seconds();
2757a7ff644SJason A. Donenfeld 		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
2767a7ff644SJason A. Donenfeld 			WRITE_ONCE(early_boot, false);
2777a7ff644SJason A. Donenfeld 		else
278e85c0fc1SJason A. Donenfeld 			interval = max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
2797a7ff644SJason A. Donenfeld 					 (unsigned int)uptime / 2 * HZ);
2807a7ff644SJason A. Donenfeld 	}
2818a5b8a4aSJason A. Donenfeld 	return time_is_before_jiffies(READ_ONCE(base_crng.birth) + interval);
2827a7ff644SJason A. Donenfeld }
2837a7ff644SJason A. Donenfeld 
2847a7ff644SJason A. Donenfeld /*
2853655adc7SJason A. Donenfeld  * This function returns a ChaCha state that you may use for generating
2863655adc7SJason A. Donenfeld  * random data. It also returns up to 32 bytes on its own of random data
2873655adc7SJason A. Donenfeld  * that may be used; random_data_len may not be greater than 32.
2883655adc7SJason A. Donenfeld  */
2893655adc7SJason A. Donenfeld static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
2903655adc7SJason A. Donenfeld 			    u8 *random_data, size_t random_data_len)
2913655adc7SJason A. Donenfeld {
2923655adc7SJason A. Donenfeld 	unsigned long flags;
2933655adc7SJason A. Donenfeld 	struct crng *crng;
2943655adc7SJason A. Donenfeld 
2953655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
2963655adc7SJason A. Donenfeld 
2973655adc7SJason A. Donenfeld 	/*
2983655adc7SJason A. Donenfeld 	 * For the fast path, we check whether we're ready, unlocked first, and
2993655adc7SJason A. Donenfeld 	 * then re-check once locked later. In the case where we're really not
3005c3b747eSJason A. Donenfeld 	 * ready, we do fast key erasure with the base_crng directly, extracting
301e3d2c5e7SJason A. Donenfeld 	 * when crng_init is CRNG_EMPTY.
3023655adc7SJason A. Donenfeld 	 */
303a96cfe2dSJason A. Donenfeld 	if (!crng_ready()) {
3043655adc7SJason A. Donenfeld 		bool ready;
3053655adc7SJason A. Donenfeld 
3063655adc7SJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
3073655adc7SJason A. Donenfeld 		ready = crng_ready();
3085c3b747eSJason A. Donenfeld 		if (!ready) {
309e3d2c5e7SJason A. Donenfeld 			if (crng_init == CRNG_EMPTY)
3105c3b747eSJason A. Donenfeld 				extract_entropy(base_crng.key, sizeof(base_crng.key));
3113655adc7SJason A. Donenfeld 			crng_fast_key_erasure(base_crng.key, chacha_state,
3123655adc7SJason A. Donenfeld 					      random_data, random_data_len);
3135c3b747eSJason A. Donenfeld 		}
3143655adc7SJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
3153655adc7SJason A. Donenfeld 		if (!ready)
3163655adc7SJason A. Donenfeld 			return;
3173655adc7SJason A. Donenfeld 	}
3183655adc7SJason A. Donenfeld 
3193655adc7SJason A. Donenfeld 	/*
320e85c0fc1SJason A. Donenfeld 	 * If the base_crng is old enough, we reseed, which in turn bumps the
321e85c0fc1SJason A. Donenfeld 	 * generation counter that we check below.
3223655adc7SJason A. Donenfeld 	 */
3237a7ff644SJason A. Donenfeld 	if (unlikely(crng_has_old_seed()))
324e85c0fc1SJason A. Donenfeld 		crng_reseed();
3253655adc7SJason A. Donenfeld 
3263655adc7SJason A. Donenfeld 	local_lock_irqsave(&crngs.lock, flags);
3273655adc7SJason A. Donenfeld 	crng = raw_cpu_ptr(&crngs);
3283655adc7SJason A. Donenfeld 
3293655adc7SJason A. Donenfeld 	/*
3303655adc7SJason A. Donenfeld 	 * If our per-cpu crng is older than the base_crng, then it means
3313655adc7SJason A. Donenfeld 	 * somebody reseeded the base_crng. In that case, we do fast key
3323655adc7SJason A. Donenfeld 	 * erasure on the base_crng, and use its output as the new key
3333655adc7SJason A. Donenfeld 	 * for our per-cpu crng. This brings us up to date with base_crng.
3343655adc7SJason A. Donenfeld 	 */
3353655adc7SJason A. Donenfeld 	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
3363655adc7SJason A. Donenfeld 		spin_lock(&base_crng.lock);
3373655adc7SJason A. Donenfeld 		crng_fast_key_erasure(base_crng.key, chacha_state,
3383655adc7SJason A. Donenfeld 				      crng->key, sizeof(crng->key));
3393655adc7SJason A. Donenfeld 		crng->generation = base_crng.generation;
3403655adc7SJason A. Donenfeld 		spin_unlock(&base_crng.lock);
3413655adc7SJason A. Donenfeld 	}
3423655adc7SJason A. Donenfeld 
3433655adc7SJason A. Donenfeld 	/*
3443655adc7SJason A. Donenfeld 	 * Finally, when we've made it this far, our per-cpu crng has an up
3453655adc7SJason A. Donenfeld 	 * to date key, and we can do fast key erasure with it to produce
3463655adc7SJason A. Donenfeld 	 * some random data and a ChaCha state for the caller. All other
3473655adc7SJason A. Donenfeld 	 * branches of this function are "unlikely", so most of the time we
3483655adc7SJason A. Donenfeld 	 * should wind up here immediately.
3493655adc7SJason A. Donenfeld 	 */
3503655adc7SJason A. Donenfeld 	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
3513655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&crngs.lock, flags);
3523655adc7SJason A. Donenfeld }
3533655adc7SJason A. Donenfeld 
354a1940263SJason A. Donenfeld static void _get_random_bytes(void *buf, size_t len)
3553655adc7SJason A. Donenfeld {
3563655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
3573655adc7SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE];
358a1940263SJason A. Donenfeld 	size_t first_block_len;
3593655adc7SJason A. Donenfeld 
360a1940263SJason A. Donenfeld 	if (!len)
3613655adc7SJason A. Donenfeld 		return;
3623655adc7SJason A. Donenfeld 
363a1940263SJason A. Donenfeld 	first_block_len = min_t(size_t, 32, len);
364a1940263SJason A. Donenfeld 	crng_make_state(chacha_state, buf, first_block_len);
365a1940263SJason A. Donenfeld 	len -= first_block_len;
366a1940263SJason A. Donenfeld 	buf += first_block_len;
3673655adc7SJason A. Donenfeld 
368a1940263SJason A. Donenfeld 	while (len) {
369a1940263SJason A. Donenfeld 		if (len < CHACHA_BLOCK_SIZE) {
3703655adc7SJason A. Donenfeld 			chacha20_block(chacha_state, tmp);
371a1940263SJason A. Donenfeld 			memcpy(buf, tmp, len);
3723655adc7SJason A. Donenfeld 			memzero_explicit(tmp, sizeof(tmp));
3733655adc7SJason A. Donenfeld 			break;
3743655adc7SJason A. Donenfeld 		}
3753655adc7SJason A. Donenfeld 
3763655adc7SJason A. Donenfeld 		chacha20_block(chacha_state, buf);
3773655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
3783655adc7SJason A. Donenfeld 			++chacha_state[13];
379a1940263SJason A. Donenfeld 		len -= CHACHA_BLOCK_SIZE;
3803655adc7SJason A. Donenfeld 		buf += CHACHA_BLOCK_SIZE;
3813655adc7SJason A. Donenfeld 	}
3823655adc7SJason A. Donenfeld 
3833655adc7SJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
3843655adc7SJason A. Donenfeld }
3853655adc7SJason A. Donenfeld 
3863655adc7SJason A. Donenfeld /*
3873655adc7SJason A. Donenfeld  * This function is the exported kernel interface.  It returns some
3883655adc7SJason A. Donenfeld  * number of good random numbers, suitable for key generation, seeding
389248561adSJason A. Donenfeld  * TCP sequence numbers, etc. In order to ensure that the randomness
390248561adSJason A. Donenfeld  * by this function is okay, the function wait_for_random_bytes()
391248561adSJason A. Donenfeld  * should be called and return 0 at least once at any point prior.
3923655adc7SJason A. Donenfeld  */
393a1940263SJason A. Donenfeld void get_random_bytes(void *buf, size_t len)
3943655adc7SJason A. Donenfeld {
395cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
396a1940263SJason A. Donenfeld 	_get_random_bytes(buf, len);
3973655adc7SJason A. Donenfeld }
3983655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_bytes);
3993655adc7SJason A. Donenfeld 
4001b388e77SJens Axboe static ssize_t get_random_bytes_user(struct iov_iter *iter)
4013655adc7SJason A. Donenfeld {
4023655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
4031b388e77SJens Axboe 	u8 block[CHACHA_BLOCK_SIZE];
4041b388e77SJens Axboe 	size_t ret = 0, copied;
4053655adc7SJason A. Donenfeld 
4061b388e77SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
4073655adc7SJason A. Donenfeld 		return 0;
4083655adc7SJason A. Donenfeld 
409aba120ccSJason A. Donenfeld 	/*
410aba120ccSJason A. Donenfeld 	 * Immediately overwrite the ChaCha key at index 4 with random
41163b8ea5eSJason A. Donenfeld 	 * bytes, in case userspace causes copy_to_iter() below to sleep
412aba120ccSJason A. Donenfeld 	 * forever, so that we still retain forward secrecy in that case.
413aba120ccSJason A. Donenfeld 	 */
414aba120ccSJason A. Donenfeld 	crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
415aba120ccSJason A. Donenfeld 	/*
416aba120ccSJason A. Donenfeld 	 * However, if we're doing a read of len <= 32, we don't need to
417aba120ccSJason A. Donenfeld 	 * use chacha_state after, so we can simply return those bytes to
418aba120ccSJason A. Donenfeld 	 * the user directly.
419aba120ccSJason A. Donenfeld 	 */
4201b388e77SJens Axboe 	if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
4211b388e77SJens Axboe 		ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
422aba120ccSJason A. Donenfeld 		goto out_zero_chacha;
423aba120ccSJason A. Donenfeld 	}
4243655adc7SJason A. Donenfeld 
4255209aed5SJason A. Donenfeld 	for (;;) {
4261b388e77SJens Axboe 		chacha20_block(chacha_state, block);
4273655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4283655adc7SJason A. Donenfeld 			++chacha_state[13];
4293655adc7SJason A. Donenfeld 
4301b388e77SJens Axboe 		copied = copy_to_iter(block, sizeof(block), iter);
4311b388e77SJens Axboe 		ret += copied;
4321b388e77SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
4335209aed5SJason A. Donenfeld 			break;
434e3c1c4fdSJason A. Donenfeld 
4351b388e77SJens Axboe 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
4365209aed5SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
437e3c1c4fdSJason A. Donenfeld 			if (signal_pending(current))
438e3c1c4fdSJason A. Donenfeld 				break;
439e3c1c4fdSJason A. Donenfeld 			cond_resched();
440e3c1c4fdSJason A. Donenfeld 		}
4415209aed5SJason A. Donenfeld 	}
4423655adc7SJason A. Donenfeld 
4431b388e77SJens Axboe 	memzero_explicit(block, sizeof(block));
444aba120ccSJason A. Donenfeld out_zero_chacha:
445aba120ccSJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
4465209aed5SJason A. Donenfeld 	return ret ? ret : -EFAULT;
4473655adc7SJason A. Donenfeld }
4483655adc7SJason A. Donenfeld 
4493655adc7SJason A. Donenfeld /*
4503655adc7SJason A. Donenfeld  * Batched entropy returns random integers. The quality of the random
4513655adc7SJason A. Donenfeld  * number is good as /dev/urandom. In order to ensure that the randomness
4523655adc7SJason A. Donenfeld  * provided by this function is okay, the function wait_for_random_bytes()
4533655adc7SJason A. Donenfeld  * should be called and return 0 at least once at any point prior.
4543655adc7SJason A. Donenfeld  */
4553655adc7SJason A. Donenfeld 
4563092adceSJason A. Donenfeld #define DEFINE_BATCHED_ENTROPY(type)						\
4573092adceSJason A. Donenfeld struct batch_ ##type {								\
4583092adceSJason A. Donenfeld 	/*									\
4593092adceSJason A. Donenfeld 	 * We make this 1.5x a ChaCha block, so that we get the			\
4603092adceSJason A. Donenfeld 	 * remaining 32 bytes from fast key erasure, plus one full		\
4613092adceSJason A. Donenfeld 	 * block from the detached ChaCha state. We can increase		\
4623092adceSJason A. Donenfeld 	 * the size of this later if needed so long as we keep the		\
4633092adceSJason A. Donenfeld 	 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.		\
4643092adceSJason A. Donenfeld 	 */									\
4653092adceSJason A. Donenfeld 	type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))];		\
4663092adceSJason A. Donenfeld 	local_lock_t lock;							\
4673092adceSJason A. Donenfeld 	unsigned long generation;						\
4683092adceSJason A. Donenfeld 	unsigned int position;							\
4693092adceSJason A. Donenfeld };										\
4703092adceSJason A. Donenfeld 										\
4713092adceSJason A. Donenfeld static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = {	\
4723092adceSJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock),			\
4733092adceSJason A. Donenfeld 	.position = UINT_MAX							\
4743092adceSJason A. Donenfeld };										\
4753092adceSJason A. Donenfeld 										\
4763092adceSJason A. Donenfeld type get_random_ ##type(void)							\
4773092adceSJason A. Donenfeld {										\
4783092adceSJason A. Donenfeld 	type ret;								\
4793092adceSJason A. Donenfeld 	unsigned long flags;							\
4803092adceSJason A. Donenfeld 	struct batch_ ##type *batch;						\
4813092adceSJason A. Donenfeld 	unsigned long next_gen;							\
4823092adceSJason A. Donenfeld 										\
4833092adceSJason A. Donenfeld 	warn_unseeded_randomness();						\
4843092adceSJason A. Donenfeld 										\
4853092adceSJason A. Donenfeld 	if  (!crng_ready()) {							\
4863092adceSJason A. Donenfeld 		_get_random_bytes(&ret, sizeof(ret));				\
4873092adceSJason A. Donenfeld 		return ret;							\
4883092adceSJason A. Donenfeld 	}									\
4893092adceSJason A. Donenfeld 										\
4903092adceSJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_ ##type.lock, flags);		\
4913092adceSJason A. Donenfeld 	batch = raw_cpu_ptr(&batched_entropy_##type);				\
4923092adceSJason A. Donenfeld 										\
4933092adceSJason A. Donenfeld 	next_gen = READ_ONCE(base_crng.generation);				\
4943092adceSJason A. Donenfeld 	if (batch->position >= ARRAY_SIZE(batch->entropy) ||			\
4953092adceSJason A. Donenfeld 	    next_gen != batch->generation) {					\
4963092adceSJason A. Donenfeld 		_get_random_bytes(batch->entropy, sizeof(batch->entropy));	\
4973092adceSJason A. Donenfeld 		batch->position = 0;						\
4983092adceSJason A. Donenfeld 		batch->generation = next_gen;					\
4993092adceSJason A. Donenfeld 	}									\
5003092adceSJason A. Donenfeld 										\
5013092adceSJason A. Donenfeld 	ret = batch->entropy[batch->position];					\
5023092adceSJason A. Donenfeld 	batch->entropy[batch->position] = 0;					\
5033092adceSJason A. Donenfeld 	++batch->position;							\
5043092adceSJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags);		\
5053092adceSJason A. Donenfeld 	return ret;								\
5063092adceSJason A. Donenfeld }										\
5073092adceSJason A. Donenfeld EXPORT_SYMBOL(get_random_ ##type);
5083655adc7SJason A. Donenfeld 
5093092adceSJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u64)
5103092adceSJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u32)
5113655adc7SJason A. Donenfeld 
5123191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
5133191dd5aSJason A. Donenfeld /*
5143191dd5aSJason A. Donenfeld  * This function is called when the CPU is coming up, with entry
5153191dd5aSJason A. Donenfeld  * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
5163191dd5aSJason A. Donenfeld  */
517560181c2SJason A. Donenfeld int __cold random_prepare_cpu(unsigned int cpu)
5183191dd5aSJason A. Donenfeld {
5193191dd5aSJason A. Donenfeld 	/*
5203191dd5aSJason A. Donenfeld 	 * When the cpu comes back online, immediately invalidate both
5213191dd5aSJason A. Donenfeld 	 * the per-cpu crng and all batches, so that we serve fresh
5223191dd5aSJason A. Donenfeld 	 * randomness.
5233191dd5aSJason A. Donenfeld 	 */
5243191dd5aSJason A. Donenfeld 	per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
5253191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
5263191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
5273191dd5aSJason A. Donenfeld 	return 0;
5283191dd5aSJason A. Donenfeld }
5293191dd5aSJason A. Donenfeld #endif
5303191dd5aSJason A. Donenfeld 
531a5ed7cb1SJason A. Donenfeld 
532a5ed7cb1SJason A. Donenfeld /**********************************************************************
533a5ed7cb1SJason A. Donenfeld  *
534a5ed7cb1SJason A. Donenfeld  * Entropy accumulation and extraction routines.
535a5ed7cb1SJason A. Donenfeld  *
536a5ed7cb1SJason A. Donenfeld  * Callers may add entropy via:
537a5ed7cb1SJason A. Donenfeld  *
538a1940263SJason A. Donenfeld  *     static void mix_pool_bytes(const void *buf, size_t len)
539a5ed7cb1SJason A. Donenfeld  *
540a5ed7cb1SJason A. Donenfeld  * After which, if added entropy should be credited:
541a5ed7cb1SJason A. Donenfeld  *
542a1940263SJason A. Donenfeld  *     static void credit_init_bits(size_t bits)
543a5ed7cb1SJason A. Donenfeld  *
544e85c0fc1SJason A. Donenfeld  * Finally, extract entropy via:
545a5ed7cb1SJason A. Donenfeld  *
546a1940263SJason A. Donenfeld  *     static void extract_entropy(void *buf, size_t len)
547a5ed7cb1SJason A. Donenfeld  *
548a5ed7cb1SJason A. Donenfeld  **********************************************************************/
549a5ed7cb1SJason A. Donenfeld 
550c5704490SJason A. Donenfeld enum {
5516e8ec255SJason A. Donenfeld 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
552e3d2c5e7SJason A. Donenfeld 	POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
553e3d2c5e7SJason A. Donenfeld 	POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
5541da177e4SLinus Torvalds };
5551da177e4SLinus Torvalds 
55690ed1e67SJason A. Donenfeld static struct {
5576e8ec255SJason A. Donenfeld 	struct blake2s_state hash;
55843358209SMatt Mackall 	spinlock_t lock;
559e85c0fc1SJason A. Donenfeld 	unsigned int init_bits;
56090ed1e67SJason A. Donenfeld } input_pool = {
5616e8ec255SJason A. Donenfeld 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
5626e8ec255SJason A. Donenfeld 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
5636e8ec255SJason A. Donenfeld 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
5646e8ec255SJason A. Donenfeld 	.hash.outlen = BLAKE2S_HASH_SIZE,
565eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
5661da177e4SLinus Torvalds };
5671da177e4SLinus Torvalds 
568a1940263SJason A. Donenfeld static void _mix_pool_bytes(const void *buf, size_t len)
569a5ed7cb1SJason A. Donenfeld {
570a1940263SJason A. Donenfeld 	blake2s_update(&input_pool.hash, buf, len);
571a5ed7cb1SJason A. Donenfeld }
57290ed1e67SJason A. Donenfeld 
5731da177e4SLinus Torvalds /*
574e85c0fc1SJason A. Donenfeld  * This function adds bytes into the input pool. It does not
575e85c0fc1SJason A. Donenfeld  * update the initialization bit counter; the caller should call
576e85c0fc1SJason A. Donenfeld  * credit_init_bits if this is appropriate.
5771da177e4SLinus Torvalds  */
578a1940263SJason A. Donenfeld static void mix_pool_bytes(const void *buf, size_t len)
5791da177e4SLinus Torvalds {
580902c098aSTheodore Ts'o 	unsigned long flags;
581902c098aSTheodore Ts'o 
58290ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
583a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
58490ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
5851da177e4SLinus Torvalds }
5861da177e4SLinus Torvalds 
587a5ed7cb1SJason A. Donenfeld /*
588a5ed7cb1SJason A. Donenfeld  * This is an HKDF-like construction for using the hashed collected entropy
589a5ed7cb1SJason A. Donenfeld  * as a PRF key, that's then expanded block-by-block.
590a5ed7cb1SJason A. Donenfeld  */
591a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len)
592a5ed7cb1SJason A. Donenfeld {
593a5ed7cb1SJason A. Donenfeld 	unsigned long flags;
594a5ed7cb1SJason A. Donenfeld 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
595a5ed7cb1SJason A. Donenfeld 	struct {
596a5ed7cb1SJason A. Donenfeld 		unsigned long rdseed[32 / sizeof(long)];
597a5ed7cb1SJason A. Donenfeld 		size_t counter;
598a5ed7cb1SJason A. Donenfeld 	} block;
599a5ed7cb1SJason A. Donenfeld 	size_t i;
600a5ed7cb1SJason A. Donenfeld 
601a5ed7cb1SJason A. Donenfeld 	for (i = 0; i < ARRAY_SIZE(block.rdseed); ++i) {
602a5ed7cb1SJason A. Donenfeld 		if (!arch_get_random_seed_long(&block.rdseed[i]) &&
603a5ed7cb1SJason A. Donenfeld 		    !arch_get_random_long(&block.rdseed[i]))
604a5ed7cb1SJason A. Donenfeld 			block.rdseed[i] = random_get_entropy();
605a5ed7cb1SJason A. Donenfeld 	}
606a5ed7cb1SJason A. Donenfeld 
607a5ed7cb1SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
608a5ed7cb1SJason A. Donenfeld 
609a5ed7cb1SJason A. Donenfeld 	/* seed = HASHPRF(last_key, entropy_input) */
610a5ed7cb1SJason A. Donenfeld 	blake2s_final(&input_pool.hash, seed);
611a5ed7cb1SJason A. Donenfeld 
612a5ed7cb1SJason A. Donenfeld 	/* next_key = HASHPRF(seed, RDSEED || 0) */
613a5ed7cb1SJason A. Donenfeld 	block.counter = 0;
614a5ed7cb1SJason A. Donenfeld 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
615a5ed7cb1SJason A. Donenfeld 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
616a5ed7cb1SJason A. Donenfeld 
617a5ed7cb1SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
618a5ed7cb1SJason A. Donenfeld 	memzero_explicit(next_key, sizeof(next_key));
619a5ed7cb1SJason A. Donenfeld 
620a1940263SJason A. Donenfeld 	while (len) {
621a1940263SJason A. Donenfeld 		i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
622a5ed7cb1SJason A. Donenfeld 		/* output = HASHPRF(seed, RDSEED || ++counter) */
623a5ed7cb1SJason A. Donenfeld 		++block.counter;
624a5ed7cb1SJason A. Donenfeld 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
625a1940263SJason A. Donenfeld 		len -= i;
626a5ed7cb1SJason A. Donenfeld 		buf += i;
627a5ed7cb1SJason A. Donenfeld 	}
628a5ed7cb1SJason A. Donenfeld 
629a5ed7cb1SJason A. Donenfeld 	memzero_explicit(seed, sizeof(seed));
630a5ed7cb1SJason A. Donenfeld 	memzero_explicit(&block, sizeof(block));
631a5ed7cb1SJason A. Donenfeld }
632a5ed7cb1SJason A. Donenfeld 
633560181c2SJason A. Donenfeld #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
634560181c2SJason A. Donenfeld 
635560181c2SJason A. Donenfeld static void __cold _credit_init_bits(size_t bits)
636a5ed7cb1SJason A. Donenfeld {
637f5bda35fSJason A. Donenfeld 	static struct execute_work set_ready;
638fed7ef06SJason A. Donenfeld 	unsigned int new, orig, add;
6395c3b747eSJason A. Donenfeld 	unsigned long flags;
6405c3b747eSJason A. Donenfeld 
641560181c2SJason A. Donenfeld 	if (!bits)
6425c3b747eSJason A. Donenfeld 		return;
6435c3b747eSJason A. Donenfeld 
644a1940263SJason A. Donenfeld 	add = min_t(size_t, bits, POOL_BITS);
6455c3b747eSJason A. Donenfeld 
646e85c0fc1SJason A. Donenfeld 	orig = READ_ONCE(input_pool.init_bits);
647*b7a68f67SUros Bizjak 	do {
648fed7ef06SJason A. Donenfeld 		new = min_t(unsigned int, POOL_BITS, orig + add);
649*b7a68f67SUros Bizjak 	} while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
6505c3b747eSJason A. Donenfeld 
65168c9c8b1SJason A. Donenfeld 	if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
65268c9c8b1SJason A. Donenfeld 		crng_reseed(); /* Sets crng_init to CRNG_READY under base_crng.lock. */
65360e5b288SJason A. Donenfeld 		if (static_key_initialized)
654f5bda35fSJason A. Donenfeld 			execute_in_process_context(crng_set_ready, &set_ready);
65568c9c8b1SJason A. Donenfeld 		wake_up_interruptible(&crng_init_wait);
65668c9c8b1SJason A. Donenfeld 		kill_fasync(&fasync, SIGIO, POLL_IN);
65768c9c8b1SJason A. Donenfeld 		pr_notice("crng init done\n");
658cc1e127bSJason A. Donenfeld 		if (urandom_warning.missed)
65968c9c8b1SJason A. Donenfeld 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
66068c9c8b1SJason A. Donenfeld 				  urandom_warning.missed);
66168c9c8b1SJason A. Donenfeld 	} else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
6625c3b747eSJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
66368c9c8b1SJason A. Donenfeld 		/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
664e3d2c5e7SJason A. Donenfeld 		if (crng_init == CRNG_EMPTY) {
6655c3b747eSJason A. Donenfeld 			extract_entropy(base_crng.key, sizeof(base_crng.key));
666e3d2c5e7SJason A. Donenfeld 			crng_init = CRNG_EARLY;
6675c3b747eSJason A. Donenfeld 		}
6685c3b747eSJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
6695c3b747eSJason A. Donenfeld 	}
6705c3b747eSJason A. Donenfeld }
6715c3b747eSJason A. Donenfeld 
67292c653cfSJason A. Donenfeld 
67392c653cfSJason A. Donenfeld /**********************************************************************
67492c653cfSJason A. Donenfeld  *
67592c653cfSJason A. Donenfeld  * Entropy collection routines.
67692c653cfSJason A. Donenfeld  *
67792c653cfSJason A. Donenfeld  * The following exported functions are used for pushing entropy into
67892c653cfSJason A. Donenfeld  * the above entropy accumulation routines:
67992c653cfSJason A. Donenfeld  *
680a1940263SJason A. Donenfeld  *	void add_device_randomness(const void *buf, size_t len);
681a1940263SJason A. Donenfeld  *	void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy);
682a1940263SJason A. Donenfeld  *	void add_bootloader_randomness(const void *buf, size_t len);
683a1940263SJason A. Donenfeld  *	void add_vmfork_randomness(const void *unique_vm_id, size_t len);
68492c653cfSJason A. Donenfeld  *	void add_interrupt_randomness(int irq);
685a1940263SJason A. Donenfeld  *	void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
686a4b5c26bSJason A. Donenfeld  *	void add_disk_randomness(struct gendisk *disk);
68792c653cfSJason A. Donenfeld  *
68892c653cfSJason A. Donenfeld  * add_device_randomness() adds data to the input pool that
68992c653cfSJason A. Donenfeld  * is likely to differ between two devices (or possibly even per boot).
69092c653cfSJason A. Donenfeld  * This would be things like MAC addresses or serial numbers, or the
69192c653cfSJason A. Donenfeld  * read-out of the RTC. This does *not* credit any actual entropy to
69292c653cfSJason A. Donenfeld  * the pool, but it initializes the pool to different values for devices
69392c653cfSJason A. Donenfeld  * that might otherwise be identical and have very little entropy
69492c653cfSJason A. Donenfeld  * available to them (particularly common in the embedded world).
69592c653cfSJason A. Donenfeld  *
69692c653cfSJason A. Donenfeld  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
69792c653cfSJason A. Donenfeld  * entropy as specified by the caller. If the entropy pool is full it will
69892c653cfSJason A. Donenfeld  * block until more entropy is needed.
69992c653cfSJason A. Donenfeld  *
7005c3b747eSJason A. Donenfeld  * add_bootloader_randomness() is called by bootloader drivers, such as EFI
7015c3b747eSJason A. Donenfeld  * and device tree, and credits its input depending on whether or not the
7025c3b747eSJason A. Donenfeld  * configuration option CONFIG_RANDOM_TRUST_BOOTLOADER is set.
70392c653cfSJason A. Donenfeld  *
704ae099e8eSJason A. Donenfeld  * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
705ae099e8eSJason A. Donenfeld  * representing the current instance of a VM to the pool, without crediting,
706ae099e8eSJason A. Donenfeld  * and then force-reseeds the crng so that it takes effect immediately.
707ae099e8eSJason A. Donenfeld  *
70892c653cfSJason A. Donenfeld  * add_interrupt_randomness() uses the interrupt timing as random
70992c653cfSJason A. Donenfeld  * inputs to the entropy pool. Using the cycle counters and the irq source
71092c653cfSJason A. Donenfeld  * as inputs, it feeds the input pool roughly once a second or after 64
71192c653cfSJason A. Donenfeld  * interrupts, crediting 1 bit of entropy for whichever comes first.
71292c653cfSJason A. Donenfeld  *
713a4b5c26bSJason A. Donenfeld  * add_input_randomness() uses the input layer interrupt timing, as well
714a4b5c26bSJason A. Donenfeld  * as the event type information from the hardware.
715a4b5c26bSJason A. Donenfeld  *
716a4b5c26bSJason A. Donenfeld  * add_disk_randomness() uses what amounts to the seek time of block
717a4b5c26bSJason A. Donenfeld  * layer request events, on a per-disk_devt basis, as input to the
718a4b5c26bSJason A. Donenfeld  * entropy pool. Note that high-speed solid state drives with very low
719a4b5c26bSJason A. Donenfeld  * seek times do not make for good sources of entropy, as their seek
720a4b5c26bSJason A. Donenfeld  * times are usually fairly consistent.
721a4b5c26bSJason A. Donenfeld  *
722a4b5c26bSJason A. Donenfeld  * The last two routines try to estimate how many bits of entropy
723a4b5c26bSJason A. Donenfeld  * to credit. They do this by keeping track of the first and second
724a4b5c26bSJason A. Donenfeld  * order deltas of the event timings.
725a4b5c26bSJason A. Donenfeld  *
72692c653cfSJason A. Donenfeld  **********************************************************************/
72792c653cfSJason A. Donenfeld 
72839e0f991SJason A. Donenfeld static bool trust_cpu __initdata = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
72939e0f991SJason A. Donenfeld static bool trust_bootloader __initdata = IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER);
73092c653cfSJason A. Donenfeld static int __init parse_trust_cpu(char *arg)
73192c653cfSJason A. Donenfeld {
73292c653cfSJason A. Donenfeld 	return kstrtobool(arg, &trust_cpu);
73392c653cfSJason A. Donenfeld }
734d97c68d1SJason A. Donenfeld static int __init parse_trust_bootloader(char *arg)
735d97c68d1SJason A. Donenfeld {
736d97c68d1SJason A. Donenfeld 	return kstrtobool(arg, &trust_bootloader);
737d97c68d1SJason A. Donenfeld }
73892c653cfSJason A. Donenfeld early_param("random.trust_cpu", parse_trust_cpu);
739d97c68d1SJason A. Donenfeld early_param("random.trust_bootloader", parse_trust_bootloader);
740775f4b29STheodore Ts'o 
741b7b67d13SJason A. Donenfeld static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
742b7b67d13SJason A. Donenfeld {
743b7b67d13SJason A. Donenfeld 	unsigned long flags, entropy = random_get_entropy();
744b7b67d13SJason A. Donenfeld 
745b7b67d13SJason A. Donenfeld 	/*
746b7b67d13SJason A. Donenfeld 	 * Encode a representation of how long the system has been suspended,
747b7b67d13SJason A. Donenfeld 	 * in a way that is distinct from prior system suspends.
748b7b67d13SJason A. Donenfeld 	 */
749b7b67d13SJason A. Donenfeld 	ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
750b7b67d13SJason A. Donenfeld 
751b7b67d13SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
752b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&action, sizeof(action));
753b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(stamps, sizeof(stamps));
754b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
755b7b67d13SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
756b7b67d13SJason A. Donenfeld 
757b7b67d13SJason A. Donenfeld 	if (crng_ready() && (action == PM_RESTORE_PREPARE ||
758b7b67d13SJason A. Donenfeld 	    (action == PM_POST_SUSPEND &&
759b7b67d13SJason A. Donenfeld 	     !IS_ENABLED(CONFIG_PM_AUTOSLEEP) && !IS_ENABLED(CONFIG_ANDROID)))) {
760e85c0fc1SJason A. Donenfeld 		crng_reseed();
761b7b67d13SJason A. Donenfeld 		pr_notice("crng reseeded on system resumption\n");
762b7b67d13SJason A. Donenfeld 	}
763b7b67d13SJason A. Donenfeld 	return 0;
764b7b67d13SJason A. Donenfeld }
765b7b67d13SJason A. Donenfeld 
766b7b67d13SJason A. Donenfeld static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
767b7b67d13SJason A. Donenfeld 
768775f4b29STheodore Ts'o /*
76992c653cfSJason A. Donenfeld  * The first collection of entropy occurs at system boot while interrupts
7702f14062bSJason A. Donenfeld  * are still turned off. Here we push in latent entropy, RDSEED, a timestamp,
7712f14062bSJason A. Donenfeld  * utsname(), and the command line. Depending on the above configuration knob,
7722f14062bSJason A. Donenfeld  * RDSEED may be considered sufficient for initialization. Note that much
7732f14062bSJason A. Donenfeld  * earlier setup may already have pushed entropy into the input pool by the
7742f14062bSJason A. Donenfeld  * time we get here.
775775f4b29STheodore Ts'o  */
7762f14062bSJason A. Donenfeld int __init random_init(const char *command_line)
777775f4b29STheodore Ts'o {
77892c653cfSJason A. Donenfeld 	ktime_t now = ktime_get_real();
77977fc95f8SJason A. Donenfeld 	unsigned int i, arch_bits;
780a1940263SJason A. Donenfeld 	unsigned long entropy;
781775f4b29STheodore Ts'o 
7821754abb3SJason A. Donenfeld #if defined(LATENT_ENTROPY_PLUGIN)
7831754abb3SJason A. Donenfeld 	static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
7841754abb3SJason A. Donenfeld 	_mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
7851754abb3SJason A. Donenfeld #endif
7861754abb3SJason A. Donenfeld 
78777fc95f8SJason A. Donenfeld 	for (i = 0, arch_bits = BLAKE2S_BLOCK_SIZE * 8;
788a1940263SJason A. Donenfeld 	     i < BLAKE2S_BLOCK_SIZE; i += sizeof(entropy)) {
789a1940263SJason A. Donenfeld 		if (!arch_get_random_seed_long_early(&entropy) &&
790a1940263SJason A. Donenfeld 		    !arch_get_random_long_early(&entropy)) {
791a1940263SJason A. Donenfeld 			entropy = random_get_entropy();
79277fc95f8SJason A. Donenfeld 			arch_bits -= sizeof(entropy) * 8;
79392c653cfSJason A. Donenfeld 		}
794a1940263SJason A. Donenfeld 		_mix_pool_bytes(&entropy, sizeof(entropy));
79592c653cfSJason A. Donenfeld 	}
796afba0b80SJason A. Donenfeld 	_mix_pool_bytes(&now, sizeof(now));
797afba0b80SJason A. Donenfeld 	_mix_pool_bytes(utsname(), sizeof(*(utsname())));
7982f14062bSJason A. Donenfeld 	_mix_pool_bytes(command_line, strlen(command_line));
7992f14062bSJason A. Donenfeld 	add_latent_entropy();
800655b2264STheodore Ts'o 
80160e5b288SJason A. Donenfeld 	/*
80260e5b288SJason A. Donenfeld 	 * If we were initialized by the bootloader before jump labels are
80360e5b288SJason A. Donenfeld 	 * initialized, then we should enable the static branch here, where
80460e5b288SJason A. Donenfeld 	 * it's guaranteed that jump labels have been initialized.
80560e5b288SJason A. Donenfeld 	 */
80660e5b288SJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
80760e5b288SJason A. Donenfeld 		crng_set_ready(NULL);
80860e5b288SJason A. Donenfeld 
809e85c0fc1SJason A. Donenfeld 	if (crng_ready())
810e85c0fc1SJason A. Donenfeld 		crng_reseed();
81112e45a2aSJason A. Donenfeld 	else if (trust_cpu)
81277fc95f8SJason A. Donenfeld 		_credit_init_bits(arch_bits);
813775f4b29STheodore Ts'o 
814b7b67d13SJason A. Donenfeld 	WARN_ON(register_pm_notifier(&pm_notifier));
815b7b67d13SJason A. Donenfeld 
8164b758edaSJason A. Donenfeld 	WARN(!random_get_entropy(), "Missing cycle counter and fallback timer; RNG "
8174b758edaSJason A. Donenfeld 				    "entropy collection will consequently suffer.");
81892c653cfSJason A. Donenfeld 	return 0;
81992c653cfSJason A. Donenfeld }
8201da177e4SLinus Torvalds 
821a2080a67SLinus Torvalds /*
822e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
823e192be9dSTheodore Ts'o  * initialize it.
824a2080a67SLinus Torvalds  *
825e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
826e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
827e192be9dSTheodore Ts'o  * identical devices.
828a2080a67SLinus Torvalds  */
829a1940263SJason A. Donenfeld void add_device_randomness(const void *buf, size_t len)
830a2080a67SLinus Torvalds {
8314b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
8324b758edaSJason A. Donenfeld 	unsigned long flags;
833a2080a67SLinus Torvalds 
8343ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
8354b758edaSJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
836a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
8373ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
838a2080a67SLinus Torvalds }
839a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
840a2080a67SLinus Torvalds 
84192c653cfSJason A. Donenfeld /*
84292c653cfSJason A. Donenfeld  * Interface for in-kernel drivers of true hardware RNGs.
84392c653cfSJason A. Donenfeld  * Those devices may produce endless random bits and will be throttled
84492c653cfSJason A. Donenfeld  * when our pool is full.
84592c653cfSJason A. Donenfeld  */
846a1940263SJason A. Donenfeld void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy)
84792c653cfSJason A. Donenfeld {
848a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
849e85c0fc1SJason A. Donenfeld 	credit_init_bits(entropy);
850e85c0fc1SJason A. Donenfeld 
851e85c0fc1SJason A. Donenfeld 	/*
852e85c0fc1SJason A. Donenfeld 	 * Throttle writing to once every CRNG_RESEED_INTERVAL, unless
853e85c0fc1SJason A. Donenfeld 	 * we're not yet initialized.
854e85c0fc1SJason A. Donenfeld 	 */
855e85c0fc1SJason A. Donenfeld 	if (!kthread_should_stop() && crng_ready())
856e85c0fc1SJason A. Donenfeld 		schedule_timeout_interruptible(CRNG_RESEED_INTERVAL);
85792c653cfSJason A. Donenfeld }
85892c653cfSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
85992c653cfSJason A. Donenfeld 
86092c653cfSJason A. Donenfeld /*
8615c3b747eSJason A. Donenfeld  * Handle random seed passed by bootloader, and credit it if
8625c3b747eSJason A. Donenfeld  * CONFIG_RANDOM_TRUST_BOOTLOADER is set.
86392c653cfSJason A. Donenfeld  */
86439e0f991SJason A. Donenfeld void __init add_bootloader_randomness(const void *buf, size_t len)
86592c653cfSJason A. Donenfeld {
866a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
867d97c68d1SJason A. Donenfeld 	if (trust_bootloader)
868a1940263SJason A. Donenfeld 		credit_init_bits(len * 8);
86992c653cfSJason A. Donenfeld }
87092c653cfSJason A. Donenfeld 
871a4107d34SJason A. Donenfeld #if IS_ENABLED(CONFIG_VMGENID)
872f3c2682bSJason A. Donenfeld static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
873f3c2682bSJason A. Donenfeld 
874ae099e8eSJason A. Donenfeld /*
875ae099e8eSJason A. Donenfeld  * Handle a new unique VM ID, which is unique, not secret, so we
876ae099e8eSJason A. Donenfeld  * don't credit it, but we do immediately force a reseed after so
877ae099e8eSJason A. Donenfeld  * that it's used by the crng posthaste.
878ae099e8eSJason A. Donenfeld  */
879560181c2SJason A. Donenfeld void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
880ae099e8eSJason A. Donenfeld {
881a1940263SJason A. Donenfeld 	add_device_randomness(unique_vm_id, len);
882ae099e8eSJason A. Donenfeld 	if (crng_ready()) {
883e85c0fc1SJason A. Donenfeld 		crng_reseed();
884ae099e8eSJason A. Donenfeld 		pr_notice("crng reseeded due to virtual machine fork\n");
885ae099e8eSJason A. Donenfeld 	}
886f3c2682bSJason A. Donenfeld 	blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
887ae099e8eSJason A. Donenfeld }
888a4107d34SJason A. Donenfeld #if IS_MODULE(CONFIG_VMGENID)
889ae099e8eSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_vmfork_randomness);
890a4107d34SJason A. Donenfeld #endif
891f3c2682bSJason A. Donenfeld 
892560181c2SJason A. Donenfeld int __cold register_random_vmfork_notifier(struct notifier_block *nb)
893f3c2682bSJason A. Donenfeld {
894f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_register(&vmfork_chain, nb);
895f3c2682bSJason A. Donenfeld }
896f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
897f3c2682bSJason A. Donenfeld 
898560181c2SJason A. Donenfeld int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
899f3c2682bSJason A. Donenfeld {
900f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_unregister(&vmfork_chain, nb);
901f3c2682bSJason A. Donenfeld }
902f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
903a4107d34SJason A. Donenfeld #endif
904ae099e8eSJason A. Donenfeld 
90592c653cfSJason A. Donenfeld struct fast_pool {
90658340f8eSJason A. Donenfeld 	struct work_struct mix;
907f5eab0e2SJason A. Donenfeld 	unsigned long pool[4];
90892c653cfSJason A. Donenfeld 	unsigned long last;
9093191dd5aSJason A. Donenfeld 	unsigned int count;
91092c653cfSJason A. Donenfeld };
91192c653cfSJason A. Donenfeld 
912f5eab0e2SJason A. Donenfeld static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
913f5eab0e2SJason A. Donenfeld #ifdef CONFIG_64BIT
914e73aaae2SJason A. Donenfeld #define FASTMIX_PERM SIPHASH_PERMUTATION
915e73aaae2SJason A. Donenfeld 	.pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 }
916f5eab0e2SJason A. Donenfeld #else
917e73aaae2SJason A. Donenfeld #define FASTMIX_PERM HSIPHASH_PERMUTATION
918e73aaae2SJason A. Donenfeld 	.pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 }
919f5eab0e2SJason A. Donenfeld #endif
920f5eab0e2SJason A. Donenfeld };
921f5eab0e2SJason A. Donenfeld 
92292c653cfSJason A. Donenfeld /*
923f5eab0e2SJason A. Donenfeld  * This is [Half]SipHash-1-x, starting from an empty key. Because
924f5eab0e2SJason A. Donenfeld  * the key is fixed, it assumes that its inputs are non-malicious,
925f5eab0e2SJason A. Donenfeld  * and therefore this has no security on its own. s represents the
9264b758edaSJason A. Donenfeld  * four-word SipHash state, while v represents a two-word input.
92792c653cfSJason A. Donenfeld  */
928791332b3SJason A. Donenfeld static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
92992c653cfSJason A. Donenfeld {
930791332b3SJason A. Donenfeld 	s[3] ^= v1;
931e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
932791332b3SJason A. Donenfeld 	s[0] ^= v1;
933791332b3SJason A. Donenfeld 	s[3] ^= v2;
934e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
935791332b3SJason A. Donenfeld 	s[0] ^= v2;
936f5eab0e2SJason A. Donenfeld }
937775f4b29STheodore Ts'o 
9383191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
9393191dd5aSJason A. Donenfeld /*
9403191dd5aSJason A. Donenfeld  * This function is called when the CPU has just come online, with
9413191dd5aSJason A. Donenfeld  * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
9423191dd5aSJason A. Donenfeld  */
943560181c2SJason A. Donenfeld int __cold random_online_cpu(unsigned int cpu)
9443191dd5aSJason A. Donenfeld {
9453191dd5aSJason A. Donenfeld 	/*
9463191dd5aSJason A. Donenfeld 	 * During CPU shutdown and before CPU onlining, add_interrupt_
9473191dd5aSJason A. Donenfeld 	 * randomness() may schedule mix_interrupt_randomness(), and
9483191dd5aSJason A. Donenfeld 	 * set the MIX_INFLIGHT flag. However, because the worker can
9493191dd5aSJason A. Donenfeld 	 * be scheduled on a different CPU during this period, that
9503191dd5aSJason A. Donenfeld 	 * flag will never be cleared. For that reason, we zero out
9513191dd5aSJason A. Donenfeld 	 * the flag here, which runs just after workqueues are onlined
9523191dd5aSJason A. Donenfeld 	 * for the CPU again. This also has the effect of setting the
9533191dd5aSJason A. Donenfeld 	 * irq randomness count to zero so that new accumulated irqs
9543191dd5aSJason A. Donenfeld 	 * are fresh.
9553191dd5aSJason A. Donenfeld 	 */
9563191dd5aSJason A. Donenfeld 	per_cpu_ptr(&irq_randomness, cpu)->count = 0;
9573191dd5aSJason A. Donenfeld 	return 0;
9583191dd5aSJason A. Donenfeld }
9593191dd5aSJason A. Donenfeld #endif
9603191dd5aSJason A. Donenfeld 
96158340f8eSJason A. Donenfeld static void mix_interrupt_randomness(struct work_struct *work)
96258340f8eSJason A. Donenfeld {
96358340f8eSJason A. Donenfeld 	struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
964f5eab0e2SJason A. Donenfeld 	/*
9654b758edaSJason A. Donenfeld 	 * The size of the copied stack pool is explicitly 2 longs so that we
9664b758edaSJason A. Donenfeld 	 * only ever ingest half of the siphash output each time, retaining
9674b758edaSJason A. Donenfeld 	 * the other half as the next "key" that carries over. The entropy is
9684b758edaSJason A. Donenfeld 	 * supposed to be sufficiently dispersed between bits so on average
9694b758edaSJason A. Donenfeld 	 * we don't wind up "losing" some.
970f5eab0e2SJason A. Donenfeld 	 */
9714b758edaSJason A. Donenfeld 	unsigned long pool[2];
972e3e33fc2SJason A. Donenfeld 	unsigned int count;
97358340f8eSJason A. Donenfeld 
97458340f8eSJason A. Donenfeld 	/* Check to see if we're running on the wrong CPU due to hotplug. */
97558340f8eSJason A. Donenfeld 	local_irq_disable();
97658340f8eSJason A. Donenfeld 	if (fast_pool != this_cpu_ptr(&irq_randomness)) {
97758340f8eSJason A. Donenfeld 		local_irq_enable();
97858340f8eSJason A. Donenfeld 		return;
97958340f8eSJason A. Donenfeld 	}
98058340f8eSJason A. Donenfeld 
98158340f8eSJason A. Donenfeld 	/*
98258340f8eSJason A. Donenfeld 	 * Copy the pool to the stack so that the mixer always has a
98358340f8eSJason A. Donenfeld 	 * consistent view, before we reenable irqs again.
98458340f8eSJason A. Donenfeld 	 */
985f5eab0e2SJason A. Donenfeld 	memcpy(pool, fast_pool->pool, sizeof(pool));
986e3e33fc2SJason A. Donenfeld 	count = fast_pool->count;
9873191dd5aSJason A. Donenfeld 	fast_pool->count = 0;
98858340f8eSJason A. Donenfeld 	fast_pool->last = jiffies;
98958340f8eSJason A. Donenfeld 	local_irq_enable();
99058340f8eSJason A. Donenfeld 
99158340f8eSJason A. Donenfeld 	mix_pool_bytes(pool, sizeof(pool));
992e3e33fc2SJason A. Donenfeld 	credit_init_bits(max(1u, (count & U16_MAX) / 64));
993c2a7de4fSJason A. Donenfeld 
99458340f8eSJason A. Donenfeld 	memzero_explicit(pool, sizeof(pool));
99558340f8eSJason A. Donenfeld }
99658340f8eSJason A. Donenfeld 
997703f7066SSebastian Andrzej Siewior void add_interrupt_randomness(int irq)
9981da177e4SLinus Torvalds {
99958340f8eSJason A. Donenfeld 	enum { MIX_INFLIGHT = 1U << 31 };
10004b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
10011b2a1a7eSChristoph Lameter 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
1002775f4b29STheodore Ts'o 	struct pt_regs *regs = get_irq_regs();
100358340f8eSJason A. Donenfeld 	unsigned int new_count;
10043060d6feSYinghai Lu 
1005791332b3SJason A. Donenfeld 	fast_mix(fast_pool->pool, entropy,
1006791332b3SJason A. Donenfeld 		 (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
10073191dd5aSJason A. Donenfeld 	new_count = ++fast_pool->count;
1008775f4b29STheodore Ts'o 
100958340f8eSJason A. Donenfeld 	if (new_count & MIX_INFLIGHT)
10101da177e4SLinus Torvalds 		return;
1011840f9507STheodore Ts'o 
1012534d2eafSJason A. Donenfeld 	if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
10131da177e4SLinus Torvalds 		return;
10141da177e4SLinus Torvalds 
101558340f8eSJason A. Donenfeld 	if (unlikely(!fast_pool->mix.func))
101658340f8eSJason A. Donenfeld 		INIT_WORK(&fast_pool->mix, mix_interrupt_randomness);
10173191dd5aSJason A. Donenfeld 	fast_pool->count |= MIX_INFLIGHT;
101858340f8eSJason A. Donenfeld 	queue_work_on(raw_smp_processor_id(), system_highpri_wq, &fast_pool->mix);
10191da177e4SLinus Torvalds }
10204b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
10211da177e4SLinus Torvalds 
1022a4b5c26bSJason A. Donenfeld /* There is one of these per entropy source */
1023a4b5c26bSJason A. Donenfeld struct timer_rand_state {
1024a4b5c26bSJason A. Donenfeld 	unsigned long last_time;
1025a4b5c26bSJason A. Donenfeld 	long last_delta, last_delta2;
1026a4b5c26bSJason A. Donenfeld };
1027a4b5c26bSJason A. Donenfeld 
1028a4b5c26bSJason A. Donenfeld /*
1029a4b5c26bSJason A. Donenfeld  * This function adds entropy to the entropy "pool" by using timing
1030a4b5c26bSJason A. Donenfeld  * delays. It uses the timer_rand_state structure to make an estimate
1031e3e33fc2SJason A. Donenfeld  * of how many bits of entropy this call has added to the pool. The
1032e3e33fc2SJason A. Donenfeld  * value "num" is also added to the pool; it should somehow describe
1033e3e33fc2SJason A. Donenfeld  * the type of event that just happened.
1034a4b5c26bSJason A. Donenfeld  */
1035a4b5c26bSJason A. Donenfeld static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1036a4b5c26bSJason A. Donenfeld {
1037a4b5c26bSJason A. Donenfeld 	unsigned long entropy = random_get_entropy(), now = jiffies, flags;
1038a4b5c26bSJason A. Donenfeld 	long delta, delta2, delta3;
1039e3e33fc2SJason A. Donenfeld 	unsigned int bits;
1040a4b5c26bSJason A. Donenfeld 
1041e3e33fc2SJason A. Donenfeld 	/*
1042e3e33fc2SJason A. Donenfeld 	 * If we're in a hard IRQ, add_interrupt_randomness() will be called
1043e3e33fc2SJason A. Donenfeld 	 * sometime after, so mix into the fast pool.
1044e3e33fc2SJason A. Donenfeld 	 */
1045e3e33fc2SJason A. Donenfeld 	if (in_hardirq()) {
1046791332b3SJason A. Donenfeld 		fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
1047e3e33fc2SJason A. Donenfeld 	} else {
1048a4b5c26bSJason A. Donenfeld 		spin_lock_irqsave(&input_pool.lock, flags);
1049a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&entropy, sizeof(entropy));
1050a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&num, sizeof(num));
1051a4b5c26bSJason A. Donenfeld 		spin_unlock_irqrestore(&input_pool.lock, flags);
1052e3e33fc2SJason A. Donenfeld 	}
1053a4b5c26bSJason A. Donenfeld 
1054a4b5c26bSJason A. Donenfeld 	if (crng_ready())
1055a4b5c26bSJason A. Donenfeld 		return;
1056a4b5c26bSJason A. Donenfeld 
1057a4b5c26bSJason A. Donenfeld 	/*
1058a4b5c26bSJason A. Donenfeld 	 * Calculate number of bits of randomness we probably added.
1059a4b5c26bSJason A. Donenfeld 	 * We take into account the first, second and third-order deltas
1060a4b5c26bSJason A. Donenfeld 	 * in order to make our estimate.
1061a4b5c26bSJason A. Donenfeld 	 */
1062a4b5c26bSJason A. Donenfeld 	delta = now - READ_ONCE(state->last_time);
1063a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_time, now);
1064a4b5c26bSJason A. Donenfeld 
1065a4b5c26bSJason A. Donenfeld 	delta2 = delta - READ_ONCE(state->last_delta);
1066a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta, delta);
1067a4b5c26bSJason A. Donenfeld 
1068a4b5c26bSJason A. Donenfeld 	delta3 = delta2 - READ_ONCE(state->last_delta2);
1069a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta2, delta2);
1070a4b5c26bSJason A. Donenfeld 
1071a4b5c26bSJason A. Donenfeld 	if (delta < 0)
1072a4b5c26bSJason A. Donenfeld 		delta = -delta;
1073a4b5c26bSJason A. Donenfeld 	if (delta2 < 0)
1074a4b5c26bSJason A. Donenfeld 		delta2 = -delta2;
1075a4b5c26bSJason A. Donenfeld 	if (delta3 < 0)
1076a4b5c26bSJason A. Donenfeld 		delta3 = -delta3;
1077a4b5c26bSJason A. Donenfeld 	if (delta > delta2)
1078a4b5c26bSJason A. Donenfeld 		delta = delta2;
1079a4b5c26bSJason A. Donenfeld 	if (delta > delta3)
1080a4b5c26bSJason A. Donenfeld 		delta = delta3;
1081a4b5c26bSJason A. Donenfeld 
1082a4b5c26bSJason A. Donenfeld 	/*
1083e3e33fc2SJason A. Donenfeld 	 * delta is now minimum absolute delta. Round down by 1 bit
1084e3e33fc2SJason A. Donenfeld 	 * on general principles, and limit entropy estimate to 11 bits.
1085a4b5c26bSJason A. Donenfeld 	 */
1086e3e33fc2SJason A. Donenfeld 	bits = min(fls(delta >> 1), 11);
1087e3e33fc2SJason A. Donenfeld 
1088e3e33fc2SJason A. Donenfeld 	/*
1089e3e33fc2SJason A. Donenfeld 	 * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
1090e3e33fc2SJason A. Donenfeld 	 * will run after this, which uses a different crediting scheme of 1 bit
1091e3e33fc2SJason A. Donenfeld 	 * per every 64 interrupts. In order to let that function do accounting
1092e3e33fc2SJason A. Donenfeld 	 * close to the one in this function, we credit a full 64/64 bit per bit,
1093e3e33fc2SJason A. Donenfeld 	 * and then subtract one to account for the extra one added.
1094e3e33fc2SJason A. Donenfeld 	 */
1095e3e33fc2SJason A. Donenfeld 	if (in_hardirq())
1096e3e33fc2SJason A. Donenfeld 		this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
1097e3e33fc2SJason A. Donenfeld 	else
1098560181c2SJason A. Donenfeld 		_credit_init_bits(bits);
1099a4b5c26bSJason A. Donenfeld }
1100a4b5c26bSJason A. Donenfeld 
1101a1940263SJason A. Donenfeld void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
1102a4b5c26bSJason A. Donenfeld {
1103a4b5c26bSJason A. Donenfeld 	static unsigned char last_value;
1104a4b5c26bSJason A. Donenfeld 	static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
1105a4b5c26bSJason A. Donenfeld 
1106a4b5c26bSJason A. Donenfeld 	/* Ignore autorepeat and the like. */
1107a4b5c26bSJason A. Donenfeld 	if (value == last_value)
1108a4b5c26bSJason A. Donenfeld 		return;
1109a4b5c26bSJason A. Donenfeld 
1110a4b5c26bSJason A. Donenfeld 	last_value = value;
1111a4b5c26bSJason A. Donenfeld 	add_timer_randomness(&input_timer_state,
1112a4b5c26bSJason A. Donenfeld 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1113a4b5c26bSJason A. Donenfeld }
1114a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_input_randomness);
1115a4b5c26bSJason A. Donenfeld 
1116a4b5c26bSJason A. Donenfeld #ifdef CONFIG_BLOCK
1117a4b5c26bSJason A. Donenfeld void add_disk_randomness(struct gendisk *disk)
1118a4b5c26bSJason A. Donenfeld {
1119a4b5c26bSJason A. Donenfeld 	if (!disk || !disk->random)
1120a4b5c26bSJason A. Donenfeld 		return;
1121a4b5c26bSJason A. Donenfeld 	/* First major is 1, so we get >= 0x200 here. */
1122a4b5c26bSJason A. Donenfeld 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1123a4b5c26bSJason A. Donenfeld }
1124a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_disk_randomness);
1125a4b5c26bSJason A. Donenfeld 
1126560181c2SJason A. Donenfeld void __cold rand_initialize_disk(struct gendisk *disk)
1127a4b5c26bSJason A. Donenfeld {
1128a4b5c26bSJason A. Donenfeld 	struct timer_rand_state *state;
1129a4b5c26bSJason A. Donenfeld 
1130a4b5c26bSJason A. Donenfeld 	/*
1131a4b5c26bSJason A. Donenfeld 	 * If kzalloc returns null, we just won't use that entropy
1132a4b5c26bSJason A. Donenfeld 	 * source.
1133a4b5c26bSJason A. Donenfeld 	 */
1134a4b5c26bSJason A. Donenfeld 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1135a4b5c26bSJason A. Donenfeld 	if (state) {
1136a4b5c26bSJason A. Donenfeld 		state->last_time = INITIAL_JIFFIES;
1137a4b5c26bSJason A. Donenfeld 		disk->random = state;
1138a4b5c26bSJason A. Donenfeld 	}
1139a4b5c26bSJason A. Donenfeld }
1140a4b5c26bSJason A. Donenfeld #endif
1141a4b5c26bSJason A. Donenfeld 
114278c768e6SJason A. Donenfeld struct entropy_timer_state {
114378c768e6SJason A. Donenfeld 	unsigned long entropy;
114478c768e6SJason A. Donenfeld 	struct timer_list timer;
114578c768e6SJason A. Donenfeld 	unsigned int samples, samples_per_bit;
114678c768e6SJason A. Donenfeld };
114778c768e6SJason A. Donenfeld 
11481da177e4SLinus Torvalds /*
114950ee7529SLinus Torvalds  * Each time the timer fires, we expect that we got an unpredictable
115050ee7529SLinus Torvalds  * jump in the cycle counter. Even if the timer is running on another
115150ee7529SLinus Torvalds  * CPU, the timer activity will be touching the stack of the CPU that is
115250ee7529SLinus Torvalds  * generating entropy..
115350ee7529SLinus Torvalds  *
115450ee7529SLinus Torvalds  * Note that we don't re-arm the timer in the timer itself - we are
115550ee7529SLinus Torvalds  * happy to be scheduled away, since that just makes the load more
115650ee7529SLinus Torvalds  * complex, but we do not want the timer to keep ticking unless the
115750ee7529SLinus Torvalds  * entropy loop is running.
115850ee7529SLinus Torvalds  *
115950ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
116050ee7529SLinus Torvalds  */
1161560181c2SJason A. Donenfeld static void __cold entropy_timer(struct timer_list *timer)
116250ee7529SLinus Torvalds {
116378c768e6SJason A. Donenfeld 	struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
116478c768e6SJason A. Donenfeld 
116578c768e6SJason A. Donenfeld 	if (++state->samples == state->samples_per_bit) {
1166e85c0fc1SJason A. Donenfeld 		credit_init_bits(1);
116778c768e6SJason A. Donenfeld 		state->samples = 0;
116878c768e6SJason A. Donenfeld 	}
116950ee7529SLinus Torvalds }
117050ee7529SLinus Torvalds 
117150ee7529SLinus Torvalds /*
117250ee7529SLinus Torvalds  * If we have an actual cycle counter, see if we can
117350ee7529SLinus Torvalds  * generate enough entropy with timing noise
117450ee7529SLinus Torvalds  */
1175560181c2SJason A. Donenfeld static void __cold try_to_generate_entropy(void)
117650ee7529SLinus Torvalds {
1177829d680eSJason A. Donenfeld 	enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 30 };
117878c768e6SJason A. Donenfeld 	struct entropy_timer_state stack;
117978c768e6SJason A. Donenfeld 	unsigned int i, num_different = 0;
118078c768e6SJason A. Donenfeld 	unsigned long last = random_get_entropy();
118150ee7529SLinus Torvalds 
118278c768e6SJason A. Donenfeld 	for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
11834b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
118478c768e6SJason A. Donenfeld 		if (stack.entropy != last)
118578c768e6SJason A. Donenfeld 			++num_different;
118678c768e6SJason A. Donenfeld 		last = stack.entropy;
118778c768e6SJason A. Donenfeld 	}
118878c768e6SJason A. Donenfeld 	stack.samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
118978c768e6SJason A. Donenfeld 	if (stack.samples_per_bit > MAX_SAMPLES_PER_BIT)
119050ee7529SLinus Torvalds 		return;
119150ee7529SLinus Torvalds 
119278c768e6SJason A. Donenfeld 	stack.samples = 0;
119350ee7529SLinus Torvalds 	timer_setup_on_stack(&stack.timer, entropy_timer, 0);
11943e504d20SJason A. Donenfeld 	while (!crng_ready() && !signal_pending(current)) {
119550ee7529SLinus Torvalds 		if (!timer_pending(&stack.timer))
119650ee7529SLinus Torvalds 			mod_timer(&stack.timer, jiffies + 1);
11974b758edaSJason A. Donenfeld 		mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
119850ee7529SLinus Torvalds 		schedule();
11994b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
120050ee7529SLinus Torvalds 	}
120150ee7529SLinus Torvalds 
120250ee7529SLinus Torvalds 	del_timer_sync(&stack.timer);
120350ee7529SLinus Torvalds 	destroy_timer_on_stack(&stack.timer);
12044b758edaSJason A. Donenfeld 	mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
120550ee7529SLinus Torvalds }
120650ee7529SLinus Torvalds 
1207a6adf8e7SJason A. Donenfeld 
1208a6adf8e7SJason A. Donenfeld /**********************************************************************
1209a6adf8e7SJason A. Donenfeld  *
1210a6adf8e7SJason A. Donenfeld  * Userspace reader/writer interfaces.
1211a6adf8e7SJason A. Donenfeld  *
1212a6adf8e7SJason A. Donenfeld  * getrandom(2) is the primary modern interface into the RNG and should
1213a6adf8e7SJason A. Donenfeld  * be used in preference to anything else.
1214a6adf8e7SJason A. Donenfeld  *
12150313bc27SLinus Torvalds  * Reading from /dev/random has the same functionality as calling
12160313bc27SLinus Torvalds  * getrandom(2) with flags=0. In earlier versions, however, it had
12170313bc27SLinus Torvalds  * vastly different semantics and should therefore be avoided, to
12180313bc27SLinus Torvalds  * prevent backwards compatibility issues.
12190313bc27SLinus Torvalds  *
12200313bc27SLinus Torvalds  * Reading from /dev/urandom has the same functionality as calling
12210313bc27SLinus Torvalds  * getrandom(2) with flags=GRND_INSECURE. Because it does not block
12220313bc27SLinus Torvalds  * waiting for the RNG to be ready, it should not be used.
1223a6adf8e7SJason A. Donenfeld  *
1224a6adf8e7SJason A. Donenfeld  * Writing to either /dev/random or /dev/urandom adds entropy to
1225a6adf8e7SJason A. Donenfeld  * the input pool but does not credit it.
1226a6adf8e7SJason A. Donenfeld  *
12270313bc27SLinus Torvalds  * Polling on /dev/random indicates when the RNG is initialized, on
12280313bc27SLinus Torvalds  * the read side, and when it wants new entropy, on the write side.
1229a6adf8e7SJason A. Donenfeld  *
1230a6adf8e7SJason A. Donenfeld  * Both /dev/random and /dev/urandom have the same set of ioctls for
1231a6adf8e7SJason A. Donenfeld  * adding entropy, getting the entropy count, zeroing the count, and
1232a6adf8e7SJason A. Donenfeld  * reseeding the crng.
1233a6adf8e7SJason A. Donenfeld  *
1234a6adf8e7SJason A. Donenfeld  **********************************************************************/
1235a6adf8e7SJason A. Donenfeld 
1236a1940263SJason A. Donenfeld SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
12371da177e4SLinus Torvalds {
12381b388e77SJens Axboe 	struct iov_iter iter;
12391b388e77SJens Axboe 	struct iovec iov;
12401b388e77SJens Axboe 	int ret;
12411b388e77SJens Axboe 
1242a6adf8e7SJason A. Donenfeld 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
1243a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1244301f0595STheodore Ts'o 
1245a6adf8e7SJason A. Donenfeld 	/*
1246a6adf8e7SJason A. Donenfeld 	 * Requesting insecure and blocking randomness at the same time makes
1247a6adf8e7SJason A. Donenfeld 	 * no sense.
1248a6adf8e7SJason A. Donenfeld 	 */
1249a6adf8e7SJason A. Donenfeld 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1250a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1251c6f1deb1SAndy Lutomirski 
1252f5bda35fSJason A. Donenfeld 	if (!crng_ready() && !(flags & GRND_INSECURE)) {
1253a6adf8e7SJason A. Donenfeld 		if (flags & GRND_NONBLOCK)
1254a6adf8e7SJason A. Donenfeld 			return -EAGAIN;
125530c08efeSAndy Lutomirski 		ret = wait_for_random_bytes();
1256a6adf8e7SJason A. Donenfeld 		if (unlikely(ret))
125730c08efeSAndy Lutomirski 			return ret;
1258a6adf8e7SJason A. Donenfeld 	}
12591b388e77SJens Axboe 
12601b388e77SJens Axboe 	ret = import_single_range(READ, ubuf, len, &iov, &iter);
12611b388e77SJens Axboe 	if (unlikely(ret))
12621b388e77SJens Axboe 		return ret;
12631b388e77SJens Axboe 	return get_random_bytes_user(&iter);
126430c08efeSAndy Lutomirski }
126530c08efeSAndy Lutomirski 
1266248045b8SJason A. Donenfeld static __poll_t random_poll(struct file *file, poll_table *wait)
126789b310a2SChristoph Hellwig {
126830c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1269e85c0fc1SJason A. Donenfeld 	return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
12701da177e4SLinus Torvalds }
12711da177e4SLinus Torvalds 
12721ce6c8d6SJason A. Donenfeld static ssize_t write_pool_user(struct iov_iter *iter)
12737f397dcdSMatt Mackall {
127404ec96b7SJason A. Donenfeld 	u8 block[BLAKE2S_BLOCK_SIZE];
127522b0a222SJens Axboe 	ssize_t ret = 0;
127622b0a222SJens Axboe 	size_t copied;
12777f397dcdSMatt Mackall 
127822b0a222SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
127922b0a222SJens Axboe 		return 0;
128022b0a222SJens Axboe 
128122b0a222SJens Axboe 	for (;;) {
128222b0a222SJens Axboe 		copied = copy_from_iter(block, sizeof(block), iter);
128322b0a222SJens Axboe 		ret += copied;
128422b0a222SJens Axboe 		mix_pool_bytes(block, copied);
128522b0a222SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
128622b0a222SJens Axboe 			break;
12871ce6c8d6SJason A. Donenfeld 
12881ce6c8d6SJason A. Donenfeld 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
12891ce6c8d6SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
12901ce6c8d6SJason A. Donenfeld 			if (signal_pending(current))
12911ce6c8d6SJason A. Donenfeld 				break;
129291f3f1e3SMatt Mackall 			cond_resched();
12937f397dcdSMatt Mackall 		}
12941ce6c8d6SJason A. Donenfeld 	}
12957f397dcdSMatt Mackall 
12967b5164fbSJason A. Donenfeld 	memzero_explicit(block, sizeof(block));
129722b0a222SJens Axboe 	return ret ? ret : -EFAULT;
12987f397dcdSMatt Mackall }
12997f397dcdSMatt Mackall 
130022b0a222SJens Axboe static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
13011da177e4SLinus Torvalds {
13021ce6c8d6SJason A. Donenfeld 	return write_pool_user(iter);
13031da177e4SLinus Torvalds }
13041da177e4SLinus Torvalds 
13051b388e77SJens Axboe static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
13060313bc27SLinus Torvalds {
13070313bc27SLinus Torvalds 	static int maxwarn = 10;
13080313bc27SLinus Torvalds 
130948bff105SJason A. Donenfeld 	/*
131048bff105SJason A. Donenfeld 	 * Opportunistically attempt to initialize the RNG on platforms that
131148bff105SJason A. Donenfeld 	 * have fast cycle counters, but don't (for now) require it to succeed.
131248bff105SJason A. Donenfeld 	 */
131348bff105SJason A. Donenfeld 	if (!crng_ready())
131448bff105SJason A. Donenfeld 		try_to_generate_entropy();
131548bff105SJason A. Donenfeld 
1316cc1e127bSJason A. Donenfeld 	if (!crng_ready()) {
1317cc1e127bSJason A. Donenfeld 		if (!ratelimit_disable && maxwarn <= 0)
1318cc1e127bSJason A. Donenfeld 			++urandom_warning.missed;
1319cc1e127bSJason A. Donenfeld 		else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
1320cc1e127bSJason A. Donenfeld 			--maxwarn;
13211b388e77SJens Axboe 			pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
13221b388e77SJens Axboe 				  current->comm, iov_iter_count(iter));
13230313bc27SLinus Torvalds 		}
1324cc1e127bSJason A. Donenfeld 	}
13250313bc27SLinus Torvalds 
13261b388e77SJens Axboe 	return get_random_bytes_user(iter);
13270313bc27SLinus Torvalds }
13280313bc27SLinus Torvalds 
13291b388e77SJens Axboe static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
1330a6adf8e7SJason A. Donenfeld {
1331a6adf8e7SJason A. Donenfeld 	int ret;
1332a6adf8e7SJason A. Donenfeld 
1333a6adf8e7SJason A. Donenfeld 	ret = wait_for_random_bytes();
1334a6adf8e7SJason A. Donenfeld 	if (ret != 0)
1335a6adf8e7SJason A. Donenfeld 		return ret;
13361b388e77SJens Axboe 	return get_random_bytes_user(iter);
1337a6adf8e7SJason A. Donenfeld }
1338a6adf8e7SJason A. Donenfeld 
133943ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
13401da177e4SLinus Torvalds {
13411da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
134222b0a222SJens Axboe 	int ent_count;
13431da177e4SLinus Torvalds 
13441da177e4SLinus Torvalds 	switch (cmd) {
13451da177e4SLinus Torvalds 	case RNDGETENTCNT:
1346a6adf8e7SJason A. Donenfeld 		/* Inherently racy, no point locking. */
1347e85c0fc1SJason A. Donenfeld 		if (put_user(input_pool.init_bits, p))
13481da177e4SLinus Torvalds 			return -EFAULT;
13491da177e4SLinus Torvalds 		return 0;
13501da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
13511da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13521da177e4SLinus Torvalds 			return -EPERM;
13531da177e4SLinus Torvalds 		if (get_user(ent_count, p))
13541da177e4SLinus Torvalds 			return -EFAULT;
1355a49c010eSJason A. Donenfeld 		if (ent_count < 0)
1356a49c010eSJason A. Donenfeld 			return -EINVAL;
1357e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1358a49c010eSJason A. Donenfeld 		return 0;
135922b0a222SJens Axboe 	case RNDADDENTROPY: {
136022b0a222SJens Axboe 		struct iov_iter iter;
136122b0a222SJens Axboe 		struct iovec iov;
136222b0a222SJens Axboe 		ssize_t ret;
136322b0a222SJens Axboe 		int len;
136422b0a222SJens Axboe 
13651da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13661da177e4SLinus Torvalds 			return -EPERM;
13671da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
13681da177e4SLinus Torvalds 			return -EFAULT;
13691da177e4SLinus Torvalds 		if (ent_count < 0)
13701da177e4SLinus Torvalds 			return -EINVAL;
137122b0a222SJens Axboe 		if (get_user(len, p++))
13721da177e4SLinus Torvalds 			return -EFAULT;
137322b0a222SJens Axboe 		ret = import_single_range(WRITE, p, len, &iov, &iter);
137422b0a222SJens Axboe 		if (unlikely(ret))
137522b0a222SJens Axboe 			return ret;
13761ce6c8d6SJason A. Donenfeld 		ret = write_pool_user(&iter);
137722b0a222SJens Axboe 		if (unlikely(ret < 0))
137822b0a222SJens Axboe 			return ret;
137922b0a222SJens Axboe 		/* Since we're crediting, enforce that it was all written into the pool. */
138022b0a222SJens Axboe 		if (unlikely(ret != len))
138122b0a222SJens Axboe 			return -EFAULT;
1382e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1383a49c010eSJason A. Donenfeld 		return 0;
138422b0a222SJens Axboe 	}
13851da177e4SLinus Torvalds 	case RNDZAPENTCNT:
13861da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1387e85c0fc1SJason A. Donenfeld 		/* No longer has any effect. */
13881da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13891da177e4SLinus Torvalds 			return -EPERM;
13901da177e4SLinus Torvalds 		return 0;
1391d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1392d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1393d848e5f8STheodore Ts'o 			return -EPERM;
1394a96cfe2dSJason A. Donenfeld 		if (!crng_ready())
1395d848e5f8STheodore Ts'o 			return -ENODATA;
1396e85c0fc1SJason A. Donenfeld 		crng_reseed();
1397d848e5f8STheodore Ts'o 		return 0;
13981da177e4SLinus Torvalds 	default:
13991da177e4SLinus Torvalds 		return -EINVAL;
14001da177e4SLinus Torvalds 	}
14011da177e4SLinus Torvalds }
14021da177e4SLinus Torvalds 
14039a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
14049a6f70bbSJeff Dike {
14059a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
14069a6f70bbSJeff Dike }
14079a6f70bbSJeff Dike 
14082b8693c0SArjan van de Ven const struct file_operations random_fops = {
14091b388e77SJens Axboe 	.read_iter = random_read_iter,
141022b0a222SJens Axboe 	.write_iter = random_write_iter,
1411a11e1d43SLinus Torvalds 	.poll = random_poll,
141243ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1413507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
14149a6f70bbSJeff Dike 	.fasync = random_fasync,
14156038f373SArnd Bergmann 	.llseek = noop_llseek,
141679025e72SJens Axboe 	.splice_read = generic_file_splice_read,
141779025e72SJens Axboe 	.splice_write = iter_file_splice_write,
14181da177e4SLinus Torvalds };
14191da177e4SLinus Torvalds 
14200313bc27SLinus Torvalds const struct file_operations urandom_fops = {
14211b388e77SJens Axboe 	.read_iter = urandom_read_iter,
142222b0a222SJens Axboe 	.write_iter = random_write_iter,
14230313bc27SLinus Torvalds 	.unlocked_ioctl = random_ioctl,
14240313bc27SLinus Torvalds 	.compat_ioctl = compat_ptr_ioctl,
14250313bc27SLinus Torvalds 	.fasync = random_fasync,
14260313bc27SLinus Torvalds 	.llseek = noop_llseek,
142779025e72SJens Axboe 	.splice_read = generic_file_splice_read,
142879025e72SJens Axboe 	.splice_write = iter_file_splice_write,
14290313bc27SLinus Torvalds };
14300313bc27SLinus Torvalds 
14310deff3c4SJason A. Donenfeld 
14321da177e4SLinus Torvalds /********************************************************************
14331da177e4SLinus Torvalds  *
14340deff3c4SJason A. Donenfeld  * Sysctl interface.
14350deff3c4SJason A. Donenfeld  *
14360deff3c4SJason A. Donenfeld  * These are partly unused legacy knobs with dummy values to not break
14370deff3c4SJason A. Donenfeld  * userspace and partly still useful things. They are usually accessible
14380deff3c4SJason A. Donenfeld  * in /proc/sys/kernel/random/ and are as follows:
14390deff3c4SJason A. Donenfeld  *
14400deff3c4SJason A. Donenfeld  * - boot_id - a UUID representing the current boot.
14410deff3c4SJason A. Donenfeld  *
14420deff3c4SJason A. Donenfeld  * - uuid - a random UUID, different each time the file is read.
14430deff3c4SJason A. Donenfeld  *
14440deff3c4SJason A. Donenfeld  * - poolsize - the number of bits of entropy that the input pool can
14450deff3c4SJason A. Donenfeld  *   hold, tied to the POOL_BITS constant.
14460deff3c4SJason A. Donenfeld  *
14470deff3c4SJason A. Donenfeld  * - entropy_avail - the number of bits of entropy currently in the
14480deff3c4SJason A. Donenfeld  *   input pool. Always <= poolsize.
14490deff3c4SJason A. Donenfeld  *
14500deff3c4SJason A. Donenfeld  * - write_wakeup_threshold - the amount of entropy in the input pool
14510deff3c4SJason A. Donenfeld  *   below which write polls to /dev/random will unblock, requesting
1452e3d2c5e7SJason A. Donenfeld  *   more entropy, tied to the POOL_READY_BITS constant. It is writable
14530deff3c4SJason A. Donenfeld  *   to avoid breaking old userspaces, but writing to it does not
14540deff3c4SJason A. Donenfeld  *   change any behavior of the RNG.
14550deff3c4SJason A. Donenfeld  *
1456d0efdf35SJason A. Donenfeld  * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
14570deff3c4SJason A. Donenfeld  *   It is writable to avoid breaking old userspaces, but writing
14580deff3c4SJason A. Donenfeld  *   to it does not change any behavior of the RNG.
14591da177e4SLinus Torvalds  *
14601da177e4SLinus Torvalds  ********************************************************************/
14611da177e4SLinus Torvalds 
14621da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
14631da177e4SLinus Torvalds 
14641da177e4SLinus Torvalds #include <linux/sysctl.h>
14651da177e4SLinus Torvalds 
1466d0efdf35SJason A. Donenfeld static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
1467e3d2c5e7SJason A. Donenfeld static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
1468489c7fc4SJason A. Donenfeld static int sysctl_poolsize = POOL_BITS;
146964276a99SJason A. Donenfeld static u8 sysctl_bootid[UUID_SIZE];
14701da177e4SLinus Torvalds 
14711da177e4SLinus Torvalds /*
1472f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
14731da177e4SLinus Torvalds  * UUID. The difference is in whether table->data is NULL; if it is,
14741da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
14751da177e4SLinus Torvalds  */
1476a1940263SJason A. Donenfeld static int proc_do_uuid(struct ctl_table *table, int write, void *buf,
1477248045b8SJason A. Donenfeld 			size_t *lenp, loff_t *ppos)
14781da177e4SLinus Torvalds {
147964276a99SJason A. Donenfeld 	u8 tmp_uuid[UUID_SIZE], *uuid;
148064276a99SJason A. Donenfeld 	char uuid_string[UUID_STRING_LEN + 1];
148164276a99SJason A. Donenfeld 	struct ctl_table fake_table = {
148264276a99SJason A. Donenfeld 		.data = uuid_string,
148364276a99SJason A. Donenfeld 		.maxlen = UUID_STRING_LEN
148464276a99SJason A. Donenfeld 	};
148564276a99SJason A. Donenfeld 
148664276a99SJason A. Donenfeld 	if (write)
148764276a99SJason A. Donenfeld 		return -EPERM;
14881da177e4SLinus Torvalds 
14891da177e4SLinus Torvalds 	uuid = table->data;
14901da177e4SLinus Torvalds 	if (!uuid) {
14911da177e4SLinus Torvalds 		uuid = tmp_uuid;
14921da177e4SLinus Torvalds 		generate_random_uuid(uuid);
149344e4360fSMathieu Desnoyers 	} else {
149444e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
149544e4360fSMathieu Desnoyers 
149644e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
149744e4360fSMathieu Desnoyers 		if (!uuid[8])
149844e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
149944e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
150044e4360fSMathieu Desnoyers 	}
15011da177e4SLinus Torvalds 
150264276a99SJason A. Donenfeld 	snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
1503a1940263SJason A. Donenfeld 	return proc_dostring(&fake_table, 0, buf, lenp, ppos);
15041da177e4SLinus Torvalds }
15051da177e4SLinus Torvalds 
150677553cf8SJason A. Donenfeld /* The same as proc_dointvec, but writes don't change anything. */
1507a1940263SJason A. Donenfeld static int proc_do_rointvec(struct ctl_table *table, int write, void *buf,
150877553cf8SJason A. Donenfeld 			    size_t *lenp, loff_t *ppos)
150977553cf8SJason A. Donenfeld {
1510a1940263SJason A. Donenfeld 	return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
151177553cf8SJason A. Donenfeld }
151277553cf8SJason A. Donenfeld 
15135475e8f0SXiaoming Ni static struct ctl_table random_table[] = {
15141da177e4SLinus Torvalds 	{
15151da177e4SLinus Torvalds 		.procname	= "poolsize",
15161da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
15171da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15181da177e4SLinus Torvalds 		.mode		= 0444,
15196d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
15201da177e4SLinus Torvalds 	},
15211da177e4SLinus Torvalds 	{
15221da177e4SLinus Torvalds 		.procname	= "entropy_avail",
1523e85c0fc1SJason A. Donenfeld 		.data		= &input_pool.init_bits,
15241da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15251da177e4SLinus Torvalds 		.mode		= 0444,
1526c5704490SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
15271da177e4SLinus Torvalds 	},
15281da177e4SLinus Torvalds 	{
15291da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
15300deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_write_wakeup_bits,
15311da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15321da177e4SLinus Torvalds 		.mode		= 0644,
153377553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
15341da177e4SLinus Torvalds 	},
15351da177e4SLinus Torvalds 	{
1536f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
15370deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_min_urandom_seed,
1538f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1539f5c2742cSTheodore Ts'o 		.mode		= 0644,
154077553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
1541f5c2742cSTheodore Ts'o 	},
1542f5c2742cSTheodore Ts'o 	{
15431da177e4SLinus Torvalds 		.procname	= "boot_id",
15441da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
15451da177e4SLinus Torvalds 		.mode		= 0444,
15466d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
15471da177e4SLinus Torvalds 	},
15481da177e4SLinus Torvalds 	{
15491da177e4SLinus Torvalds 		.procname	= "uuid",
15501da177e4SLinus Torvalds 		.mode		= 0444,
15516d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
15521da177e4SLinus Torvalds 	},
1553894d2491SEric W. Biederman 	{ }
15541da177e4SLinus Torvalds };
15555475e8f0SXiaoming Ni 
15565475e8f0SXiaoming Ni /*
15572f14062bSJason A. Donenfeld  * random_init() is called before sysctl_init(),
15582f14062bSJason A. Donenfeld  * so we cannot call register_sysctl_init() in random_init()
15595475e8f0SXiaoming Ni  */
15605475e8f0SXiaoming Ni static int __init random_sysctls_init(void)
15615475e8f0SXiaoming Ni {
15625475e8f0SXiaoming Ni 	register_sysctl_init("kernel/random", random_table);
15635475e8f0SXiaoming Ni 	return 0;
15645475e8f0SXiaoming Ni }
15655475e8f0SXiaoming Ni device_initcall(random_sysctls_init);
15660deff3c4SJason A. Donenfeld #endif
1567