xref: /linux/drivers/char/random.c (revision 8a5b8a4a4ceb353b4dd5bafd09e2b15751bcdb51)
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 */
81e3d2c5e7SJason A. Donenfeld } crng_init = CRNG_EMPTY;
82e3d2c5e7SJason A. Donenfeld #define crng_ready() (likely(crng_init >= CRNG_READY))
83e3d2c5e7SJason A. Donenfeld /* Various types of waiters for crng_init->CRNG_READY transition. */
845f1bb112SJason A. Donenfeld static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
855f1bb112SJason A. Donenfeld static struct fasync_struct *fasync;
865acd3548SJason A. Donenfeld static DEFINE_SPINLOCK(random_ready_chain_lock);
875acd3548SJason A. Donenfeld static RAW_NOTIFIER_HEAD(random_ready_chain);
885f1bb112SJason A. Donenfeld 
895f1bb112SJason A. Donenfeld /* Control how we warn userspace. */
900313bc27SLinus Torvalds static struct ratelimit_state urandom_warning =
910313bc27SLinus Torvalds 	RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
92cc1e127bSJason A. Donenfeld static int ratelimit_disable __read_mostly =
93cc1e127bSJason A. Donenfeld 	IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
945f1bb112SJason A. Donenfeld module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
955f1bb112SJason A. Donenfeld MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
965f1bb112SJason A. Donenfeld 
975f1bb112SJason A. Donenfeld /*
985f1bb112SJason A. Donenfeld  * Returns whether or not the input pool has been seeded and thus guaranteed
990313bc27SLinus Torvalds  * to supply cryptographically secure random numbers. This applies to: the
1000313bc27SLinus Torvalds  * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
1010313bc27SLinus Torvalds  * ,u64,int,long} family of functions.
1025f1bb112SJason A. Donenfeld  *
1035f1bb112SJason A. Donenfeld  * Returns: true if the input pool has been seeded.
1045f1bb112SJason A. Donenfeld  *          false if the input pool has not been seeded.
1055f1bb112SJason A. Donenfeld  */
1065f1bb112SJason A. Donenfeld bool rng_is_initialized(void)
1075f1bb112SJason A. Donenfeld {
1085f1bb112SJason A. Donenfeld 	return crng_ready();
1095f1bb112SJason A. Donenfeld }
1105f1bb112SJason A. Donenfeld EXPORT_SYMBOL(rng_is_initialized);
1115f1bb112SJason A. Donenfeld 
1125f1bb112SJason A. Donenfeld /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
1135f1bb112SJason A. Donenfeld static void try_to_generate_entropy(void);
1145f1bb112SJason A. Donenfeld 
1155f1bb112SJason A. Donenfeld /*
1165f1bb112SJason A. Donenfeld  * Wait for the input pool to be seeded and thus guaranteed to supply
1170313bc27SLinus Torvalds  * cryptographically secure random numbers. This applies to: the /dev/urandom
1180313bc27SLinus Torvalds  * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1190313bc27SLinus Torvalds  * family of functions. Using any of these functions without first calling
1200313bc27SLinus Torvalds  * this function forfeits the guarantee of security.
1215f1bb112SJason A. Donenfeld  *
1225f1bb112SJason A. Donenfeld  * Returns: 0 if the input pool has been seeded.
1235f1bb112SJason A. Donenfeld  *          -ERESTARTSYS if the function was interrupted by a signal.
1245f1bb112SJason A. Donenfeld  */
1255f1bb112SJason A. Donenfeld int wait_for_random_bytes(void)
1265f1bb112SJason A. Donenfeld {
127a96cfe2dSJason A. Donenfeld 	while (!crng_ready()) {
1285f1bb112SJason A. Donenfeld 		int ret;
1293e504d20SJason A. Donenfeld 
1303e504d20SJason A. Donenfeld 		try_to_generate_entropy();
1315f1bb112SJason A. Donenfeld 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
1325f1bb112SJason A. Donenfeld 		if (ret)
1335f1bb112SJason A. Donenfeld 			return ret > 0 ? 0 : ret;
134a96cfe2dSJason A. Donenfeld 	}
1355f1bb112SJason A. Donenfeld 	return 0;
1365f1bb112SJason A. Donenfeld }
1375f1bb112SJason A. Donenfeld EXPORT_SYMBOL(wait_for_random_bytes);
1385f1bb112SJason A. Donenfeld 
1395f1bb112SJason A. Donenfeld /*
1405f1bb112SJason A. Donenfeld  * Add a callback function that will be invoked when the input
1415f1bb112SJason A. Donenfeld  * pool is initialised.
1425f1bb112SJason A. Donenfeld  *
1435f1bb112SJason A. Donenfeld  * returns: 0 if callback is successfully added
1445f1bb112SJason A. Donenfeld  *	    -EALREADY if pool is already initialised (callback not called)
1455f1bb112SJason A. Donenfeld  */
1465acd3548SJason A. Donenfeld int register_random_ready_notifier(struct notifier_block *nb)
1475f1bb112SJason A. Donenfeld {
1485f1bb112SJason A. Donenfeld 	unsigned long flags;
1495acd3548SJason A. Donenfeld 	int ret = -EALREADY;
1505f1bb112SJason A. Donenfeld 
1515f1bb112SJason A. Donenfeld 	if (crng_ready())
1525acd3548SJason A. Donenfeld 		return ret;
1535f1bb112SJason A. Donenfeld 
1545acd3548SJason A. Donenfeld 	spin_lock_irqsave(&random_ready_chain_lock, flags);
1555acd3548SJason A. Donenfeld 	if (!crng_ready())
1565acd3548SJason A. Donenfeld 		ret = raw_notifier_chain_register(&random_ready_chain, nb);
1575acd3548SJason A. Donenfeld 	spin_unlock_irqrestore(&random_ready_chain_lock, flags);
1585acd3548SJason A. Donenfeld 	return ret;
1595f1bb112SJason A. Donenfeld }
1605f1bb112SJason A. Donenfeld 
1615f1bb112SJason A. Donenfeld /*
1625f1bb112SJason A. Donenfeld  * Delete a previously registered readiness callback function.
1635f1bb112SJason A. Donenfeld  */
1645acd3548SJason A. Donenfeld int unregister_random_ready_notifier(struct notifier_block *nb)
1655f1bb112SJason A. Donenfeld {
1665f1bb112SJason A. Donenfeld 	unsigned long flags;
1675acd3548SJason A. Donenfeld 	int ret;
1685f1bb112SJason A. Donenfeld 
1695acd3548SJason A. Donenfeld 	spin_lock_irqsave(&random_ready_chain_lock, flags);
1705acd3548SJason A. Donenfeld 	ret = raw_notifier_chain_unregister(&random_ready_chain, nb);
1715acd3548SJason A. Donenfeld 	spin_unlock_irqrestore(&random_ready_chain_lock, flags);
1725acd3548SJason A. Donenfeld 	return ret;
1735f1bb112SJason A. Donenfeld }
1745f1bb112SJason A. Donenfeld 
1755f1bb112SJason A. Donenfeld static void process_random_ready_list(void)
1765f1bb112SJason A. Donenfeld {
1775f1bb112SJason A. Donenfeld 	unsigned long flags;
1785f1bb112SJason A. Donenfeld 
1795acd3548SJason A. Donenfeld 	spin_lock_irqsave(&random_ready_chain_lock, flags);
1805acd3548SJason A. Donenfeld 	raw_notifier_call_chain(&random_ready_chain, 0, NULL);
1815acd3548SJason A. Donenfeld 	spin_unlock_irqrestore(&random_ready_chain_lock, flags);
1825f1bb112SJason A. Donenfeld }
1835f1bb112SJason A. Donenfeld 
184cc1e127bSJason A. Donenfeld #define warn_unseeded_randomness() \
185cc1e127bSJason A. Donenfeld 	_warn_unseeded_randomness(__func__, (void *)_RET_IP_)
1865f1bb112SJason A. Donenfeld 
187cc1e127bSJason A. Donenfeld static void _warn_unseeded_randomness(const char *func_name, void *caller)
1885f1bb112SJason A. Donenfeld {
189cc1e127bSJason A. Donenfeld 	if (!IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) || crng_ready())
1905f1bb112SJason A. Donenfeld 		return;
1915f1bb112SJason A. Donenfeld 	printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n",
1925f1bb112SJason A. Donenfeld 			func_name, caller, crng_init);
1935f1bb112SJason A. Donenfeld }
1945f1bb112SJason A. Donenfeld 
1955f1bb112SJason A. Donenfeld 
1963655adc7SJason A. Donenfeld /*********************************************************************
1973655adc7SJason A. Donenfeld  *
1983655adc7SJason A. Donenfeld  * Fast key erasure RNG, the "crng".
1993655adc7SJason A. Donenfeld  *
2003655adc7SJason A. Donenfeld  * These functions expand entropy from the entropy extractor into
2013655adc7SJason A. Donenfeld  * long streams for external consumption using the "fast key erasure"
2023655adc7SJason A. Donenfeld  * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
2033655adc7SJason A. Donenfeld  *
2043655adc7SJason A. Donenfeld  * There are a few exported interfaces for use by other drivers:
2053655adc7SJason A. Donenfeld  *
2063655adc7SJason A. Donenfeld  *	void get_random_bytes(void *buf, size_t nbytes)
2073655adc7SJason A. Donenfeld  *	u32 get_random_u32()
2083655adc7SJason A. Donenfeld  *	u64 get_random_u64()
2093655adc7SJason A. Donenfeld  *	unsigned int get_random_int()
2103655adc7SJason A. Donenfeld  *	unsigned long get_random_long()
2113655adc7SJason A. Donenfeld  *
2123655adc7SJason A. Donenfeld  * These interfaces will return the requested number of random bytes
2130313bc27SLinus Torvalds  * into the given buffer or as a return value. This is equivalent to
214dd7aa36eSJason A. Donenfeld  * a read from /dev/urandom. The u32, u64, int, and long family of
215dd7aa36eSJason A. Donenfeld  * functions may be higher performance for one-off random integers,
216dd7aa36eSJason A. Donenfeld  * because they do a bit of buffering and do not invoke reseeding
217dd7aa36eSJason A. Donenfeld  * until the buffer is emptied.
2183655adc7SJason A. Donenfeld  *
2193655adc7SJason A. Donenfeld  *********************************************************************/
2203655adc7SJason A. Donenfeld 
221e85c0fc1SJason A. Donenfeld enum {
222e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_START_INTERVAL = HZ,
223e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_INTERVAL = 60 * HZ
224e85c0fc1SJason A. Donenfeld };
2253655adc7SJason A. Donenfeld 
2263655adc7SJason A. Donenfeld static struct {
2273655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
2283655adc7SJason A. Donenfeld 	unsigned long birth;
2293655adc7SJason A. Donenfeld 	unsigned long generation;
2303655adc7SJason A. Donenfeld 	spinlock_t lock;
2313655adc7SJason A. Donenfeld } base_crng = {
2323655adc7SJason A. Donenfeld 	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
2333655adc7SJason A. Donenfeld };
2343655adc7SJason A. Donenfeld 
2353655adc7SJason A. Donenfeld struct crng {
2363655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2373655adc7SJason A. Donenfeld 	unsigned long generation;
2383655adc7SJason A. Donenfeld 	local_lock_t lock;
2393655adc7SJason A. Donenfeld };
2403655adc7SJason A. Donenfeld 
2413655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct crng, crngs) = {
2423655adc7SJason A. Donenfeld 	.generation = ULONG_MAX,
2433655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(crngs.lock),
2443655adc7SJason A. Donenfeld };
2453655adc7SJason A. Donenfeld 
246e85c0fc1SJason A. Donenfeld /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
2475c3b747eSJason A. Donenfeld static void extract_entropy(void *buf, size_t nbytes);
2483655adc7SJason A. Donenfeld 
249e85c0fc1SJason A. Donenfeld /* This extracts a new crng key from the input pool. */
250e85c0fc1SJason A. Donenfeld static void crng_reseed(void)
2513655adc7SJason A. Donenfeld {
2523655adc7SJason A. Donenfeld 	unsigned long flags;
2533655adc7SJason A. Donenfeld 	unsigned long next_gen;
2543655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2553655adc7SJason A. Donenfeld 
256e85c0fc1SJason A. Donenfeld 	extract_entropy(key, sizeof(key));
2573655adc7SJason A. Donenfeld 
2583655adc7SJason A. Donenfeld 	/*
2593655adc7SJason A. Donenfeld 	 * We copy the new key into the base_crng, overwriting the old one,
2603655adc7SJason A. Donenfeld 	 * and update the generation counter. We avoid hitting ULONG_MAX,
2613655adc7SJason A. Donenfeld 	 * because the per-cpu crngs are initialized to ULONG_MAX, so this
2623655adc7SJason A. Donenfeld 	 * forces new CPUs that come online to always initialize.
2633655adc7SJason A. Donenfeld 	 */
2643655adc7SJason A. Donenfeld 	spin_lock_irqsave(&base_crng.lock, flags);
2653655adc7SJason A. Donenfeld 	memcpy(base_crng.key, key, sizeof(base_crng.key));
2663655adc7SJason A. Donenfeld 	next_gen = base_crng.generation + 1;
2673655adc7SJason A. Donenfeld 	if (next_gen == ULONG_MAX)
2683655adc7SJason A. Donenfeld 		++next_gen;
2693655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.generation, next_gen);
2703655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.birth, jiffies);
27168c9c8b1SJason A. Donenfeld 	if (!crng_ready())
272e3d2c5e7SJason A. Donenfeld 		crng_init = CRNG_READY;
2733655adc7SJason A. Donenfeld 	spin_unlock_irqrestore(&base_crng.lock, flags);
2743655adc7SJason A. Donenfeld 	memzero_explicit(key, sizeof(key));
2753655adc7SJason A. Donenfeld }
2763655adc7SJason A. Donenfeld 
2773655adc7SJason A. Donenfeld /*
2783655adc7SJason A. Donenfeld  * This generates a ChaCha block using the provided key, and then
2793655adc7SJason A. Donenfeld  * immediately overwites that key with half the block. It returns
2803655adc7SJason A. Donenfeld  * the resultant ChaCha state to the user, along with the second
2813655adc7SJason A. Donenfeld  * half of the block containing 32 bytes of random data that may
2823655adc7SJason A. Donenfeld  * be used; random_data_len may not be greater than 32.
2838717627dSJason A. Donenfeld  *
2848717627dSJason A. Donenfeld  * The returned ChaCha state contains within it a copy of the old
2858717627dSJason A. Donenfeld  * key value, at index 4, so the state should always be zeroed out
2868717627dSJason A. Donenfeld  * immediately after using in order to maintain forward secrecy.
2878717627dSJason A. Donenfeld  * If the state cannot be erased in a timely manner, then it is
2888717627dSJason A. Donenfeld  * safer to set the random_data parameter to &chacha_state[4] so
2898717627dSJason A. Donenfeld  * that this function overwrites it before returning.
2903655adc7SJason A. Donenfeld  */
2913655adc7SJason A. Donenfeld static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
2923655adc7SJason A. Donenfeld 				  u32 chacha_state[CHACHA_STATE_WORDS],
2933655adc7SJason A. Donenfeld 				  u8 *random_data, size_t random_data_len)
2943655adc7SJason A. Donenfeld {
2953655adc7SJason A. Donenfeld 	u8 first_block[CHACHA_BLOCK_SIZE];
2963655adc7SJason A. Donenfeld 
2973655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
2983655adc7SJason A. Donenfeld 
2993655adc7SJason A. Donenfeld 	chacha_init_consts(chacha_state);
3003655adc7SJason A. Donenfeld 	memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
3013655adc7SJason A. Donenfeld 	memset(&chacha_state[12], 0, sizeof(u32) * 4);
3023655adc7SJason A. Donenfeld 	chacha20_block(chacha_state, first_block);
3033655adc7SJason A. Donenfeld 
3043655adc7SJason A. Donenfeld 	memcpy(key, first_block, CHACHA_KEY_SIZE);
3058717627dSJason A. Donenfeld 	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
3063655adc7SJason A. Donenfeld 	memzero_explicit(first_block, sizeof(first_block));
3073655adc7SJason A. Donenfeld }
3083655adc7SJason A. Donenfeld 
3093655adc7SJason A. Donenfeld /*
310e85c0fc1SJason A. Donenfeld  * Return whether the crng seed is considered to be sufficiently old
311e85c0fc1SJason A. Donenfeld  * that a reseeding is needed. This happens if the last reseeding
312e85c0fc1SJason A. Donenfeld  * was CRNG_RESEED_INTERVAL ago, or during early boot, at an interval
313e85c0fc1SJason A. Donenfeld  * proportional to the uptime.
3147a7ff644SJason A. Donenfeld  */
3157a7ff644SJason A. Donenfeld static bool crng_has_old_seed(void)
3167a7ff644SJason A. Donenfeld {
3177a7ff644SJason A. Donenfeld 	static bool early_boot = true;
3187a7ff644SJason A. Donenfeld 	unsigned long interval = CRNG_RESEED_INTERVAL;
3197a7ff644SJason A. Donenfeld 
3207a7ff644SJason A. Donenfeld 	if (unlikely(READ_ONCE(early_boot))) {
3217a7ff644SJason A. Donenfeld 		time64_t uptime = ktime_get_seconds();
3227a7ff644SJason A. Donenfeld 		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
3237a7ff644SJason A. Donenfeld 			WRITE_ONCE(early_boot, false);
3247a7ff644SJason A. Donenfeld 		else
325e85c0fc1SJason A. Donenfeld 			interval = max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
3267a7ff644SJason A. Donenfeld 					 (unsigned int)uptime / 2 * HZ);
3277a7ff644SJason A. Donenfeld 	}
328*8a5b8a4aSJason A. Donenfeld 	return time_is_before_jiffies(READ_ONCE(base_crng.birth) + interval);
3297a7ff644SJason A. Donenfeld }
3307a7ff644SJason A. Donenfeld 
3317a7ff644SJason A. Donenfeld /*
3323655adc7SJason A. Donenfeld  * This function returns a ChaCha state that you may use for generating
3333655adc7SJason A. Donenfeld  * random data. It also returns up to 32 bytes on its own of random data
3343655adc7SJason A. Donenfeld  * that may be used; random_data_len may not be greater than 32.
3353655adc7SJason A. Donenfeld  */
3363655adc7SJason A. Donenfeld static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
3373655adc7SJason A. Donenfeld 			    u8 *random_data, size_t random_data_len)
3383655adc7SJason A. Donenfeld {
3393655adc7SJason A. Donenfeld 	unsigned long flags;
3403655adc7SJason A. Donenfeld 	struct crng *crng;
3413655adc7SJason A. Donenfeld 
3423655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
3433655adc7SJason A. Donenfeld 
3443655adc7SJason A. Donenfeld 	/*
3453655adc7SJason A. Donenfeld 	 * For the fast path, we check whether we're ready, unlocked first, and
3463655adc7SJason A. Donenfeld 	 * then re-check once locked later. In the case where we're really not
3475c3b747eSJason A. Donenfeld 	 * ready, we do fast key erasure with the base_crng directly, extracting
348e3d2c5e7SJason A. Donenfeld 	 * when crng_init is CRNG_EMPTY.
3493655adc7SJason A. Donenfeld 	 */
350a96cfe2dSJason A. Donenfeld 	if (!crng_ready()) {
3513655adc7SJason A. Donenfeld 		bool ready;
3523655adc7SJason A. Donenfeld 
3533655adc7SJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
3543655adc7SJason A. Donenfeld 		ready = crng_ready();
3555c3b747eSJason A. Donenfeld 		if (!ready) {
356e3d2c5e7SJason A. Donenfeld 			if (crng_init == CRNG_EMPTY)
3575c3b747eSJason A. Donenfeld 				extract_entropy(base_crng.key, sizeof(base_crng.key));
3583655adc7SJason A. Donenfeld 			crng_fast_key_erasure(base_crng.key, chacha_state,
3593655adc7SJason A. Donenfeld 					      random_data, random_data_len);
3605c3b747eSJason A. Donenfeld 		}
3613655adc7SJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
3623655adc7SJason A. Donenfeld 		if (!ready)
3633655adc7SJason A. Donenfeld 			return;
3643655adc7SJason A. Donenfeld 	}
3653655adc7SJason A. Donenfeld 
3663655adc7SJason A. Donenfeld 	/*
367e85c0fc1SJason A. Donenfeld 	 * If the base_crng is old enough, we reseed, which in turn bumps the
368e85c0fc1SJason A. Donenfeld 	 * generation counter that we check below.
3693655adc7SJason A. Donenfeld 	 */
3707a7ff644SJason A. Donenfeld 	if (unlikely(crng_has_old_seed()))
371e85c0fc1SJason A. Donenfeld 		crng_reseed();
3723655adc7SJason A. Donenfeld 
3733655adc7SJason A. Donenfeld 	local_lock_irqsave(&crngs.lock, flags);
3743655adc7SJason A. Donenfeld 	crng = raw_cpu_ptr(&crngs);
3753655adc7SJason A. Donenfeld 
3763655adc7SJason A. Donenfeld 	/*
3773655adc7SJason A. Donenfeld 	 * If our per-cpu crng is older than the base_crng, then it means
3783655adc7SJason A. Donenfeld 	 * somebody reseeded the base_crng. In that case, we do fast key
3793655adc7SJason A. Donenfeld 	 * erasure on the base_crng, and use its output as the new key
3803655adc7SJason A. Donenfeld 	 * for our per-cpu crng. This brings us up to date with base_crng.
3813655adc7SJason A. Donenfeld 	 */
3823655adc7SJason A. Donenfeld 	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
3833655adc7SJason A. Donenfeld 		spin_lock(&base_crng.lock);
3843655adc7SJason A. Donenfeld 		crng_fast_key_erasure(base_crng.key, chacha_state,
3853655adc7SJason A. Donenfeld 				      crng->key, sizeof(crng->key));
3863655adc7SJason A. Donenfeld 		crng->generation = base_crng.generation;
3873655adc7SJason A. Donenfeld 		spin_unlock(&base_crng.lock);
3883655adc7SJason A. Donenfeld 	}
3893655adc7SJason A. Donenfeld 
3903655adc7SJason A. Donenfeld 	/*
3913655adc7SJason A. Donenfeld 	 * Finally, when we've made it this far, our per-cpu crng has an up
3923655adc7SJason A. Donenfeld 	 * to date key, and we can do fast key erasure with it to produce
3933655adc7SJason A. Donenfeld 	 * some random data and a ChaCha state for the caller. All other
3943655adc7SJason A. Donenfeld 	 * branches of this function are "unlikely", so most of the time we
3953655adc7SJason A. Donenfeld 	 * should wind up here immediately.
3963655adc7SJason A. Donenfeld 	 */
3973655adc7SJason A. Donenfeld 	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
3983655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&crngs.lock, flags);
3993655adc7SJason A. Donenfeld }
4003655adc7SJason A. Donenfeld 
4013655adc7SJason A. Donenfeld static void _get_random_bytes(void *buf, size_t nbytes)
4023655adc7SJason A. Donenfeld {
4033655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
4043655adc7SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE];
4053655adc7SJason A. Donenfeld 	size_t len;
4063655adc7SJason A. Donenfeld 
4073655adc7SJason A. Donenfeld 	if (!nbytes)
4083655adc7SJason A. Donenfeld 		return;
4093655adc7SJason A. Donenfeld 
4103655adc7SJason A. Donenfeld 	len = min_t(size_t, 32, nbytes);
4113655adc7SJason A. Donenfeld 	crng_make_state(chacha_state, buf, len);
4123655adc7SJason A. Donenfeld 	nbytes -= len;
4133655adc7SJason A. Donenfeld 	buf += len;
4143655adc7SJason A. Donenfeld 
4153655adc7SJason A. Donenfeld 	while (nbytes) {
4163655adc7SJason A. Donenfeld 		if (nbytes < CHACHA_BLOCK_SIZE) {
4173655adc7SJason A. Donenfeld 			chacha20_block(chacha_state, tmp);
4183655adc7SJason A. Donenfeld 			memcpy(buf, tmp, nbytes);
4193655adc7SJason A. Donenfeld 			memzero_explicit(tmp, sizeof(tmp));
4203655adc7SJason A. Donenfeld 			break;
4213655adc7SJason A. Donenfeld 		}
4223655adc7SJason A. Donenfeld 
4233655adc7SJason A. Donenfeld 		chacha20_block(chacha_state, buf);
4243655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4253655adc7SJason A. Donenfeld 			++chacha_state[13];
4263655adc7SJason A. Donenfeld 		nbytes -= CHACHA_BLOCK_SIZE;
4273655adc7SJason A. Donenfeld 		buf += CHACHA_BLOCK_SIZE;
4283655adc7SJason A. Donenfeld 	}
4293655adc7SJason A. Donenfeld 
4303655adc7SJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
4313655adc7SJason A. Donenfeld }
4323655adc7SJason A. Donenfeld 
4333655adc7SJason A. Donenfeld /*
4343655adc7SJason A. Donenfeld  * This function is the exported kernel interface.  It returns some
4353655adc7SJason A. Donenfeld  * number of good random numbers, suitable for key generation, seeding
4363655adc7SJason A. Donenfeld  * TCP sequence numbers, etc.  It does not rely on the hardware random
4373655adc7SJason A. Donenfeld  * number generator.  For random bytes direct from the hardware RNG
4383655adc7SJason A. Donenfeld  * (when available), use get_random_bytes_arch(). In order to ensure
4393655adc7SJason A. Donenfeld  * that the randomness provided by this function is okay, the function
4403655adc7SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once
4413655adc7SJason A. Donenfeld  * at any point prior.
4423655adc7SJason A. Donenfeld  */
4433655adc7SJason A. Donenfeld void get_random_bytes(void *buf, size_t nbytes)
4443655adc7SJason A. Donenfeld {
445cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
4463655adc7SJason A. Donenfeld 	_get_random_bytes(buf, nbytes);
4473655adc7SJason A. Donenfeld }
4483655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_bytes);
4493655adc7SJason A. Donenfeld 
4503655adc7SJason A. Donenfeld static ssize_t get_random_bytes_user(void __user *buf, size_t nbytes)
4513655adc7SJason A. Donenfeld {
4525209aed5SJason A. Donenfeld 	size_t len, left, ret = 0;
4533655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
4543655adc7SJason A. Donenfeld 	u8 output[CHACHA_BLOCK_SIZE];
4553655adc7SJason A. Donenfeld 
4563655adc7SJason A. Donenfeld 	if (!nbytes)
4573655adc7SJason A. Donenfeld 		return 0;
4583655adc7SJason A. Donenfeld 
459aba120ccSJason A. Donenfeld 	/*
460aba120ccSJason A. Donenfeld 	 * Immediately overwrite the ChaCha key at index 4 with random
461aba120ccSJason A. Donenfeld 	 * bytes, in case userspace causes copy_to_user() below to sleep
462aba120ccSJason A. Donenfeld 	 * forever, so that we still retain forward secrecy in that case.
463aba120ccSJason A. Donenfeld 	 */
464aba120ccSJason A. Donenfeld 	crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
465aba120ccSJason A. Donenfeld 	/*
466aba120ccSJason A. Donenfeld 	 * However, if we're doing a read of len <= 32, we don't need to
467aba120ccSJason A. Donenfeld 	 * use chacha_state after, so we can simply return those bytes to
468aba120ccSJason A. Donenfeld 	 * the user directly.
469aba120ccSJason A. Donenfeld 	 */
470aba120ccSJason A. Donenfeld 	if (nbytes <= CHACHA_KEY_SIZE) {
4715209aed5SJason A. Donenfeld 		ret = nbytes - copy_to_user(buf, &chacha_state[4], nbytes);
472aba120ccSJason A. Donenfeld 		goto out_zero_chacha;
473aba120ccSJason A. Donenfeld 	}
4743655adc7SJason A. Donenfeld 
4755209aed5SJason A. Donenfeld 	for (;;) {
4763655adc7SJason A. Donenfeld 		chacha20_block(chacha_state, output);
4773655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4783655adc7SJason A. Donenfeld 			++chacha_state[13];
4793655adc7SJason A. Donenfeld 
4803655adc7SJason A. Donenfeld 		len = min_t(size_t, nbytes, CHACHA_BLOCK_SIZE);
4815209aed5SJason A. Donenfeld 		left = copy_to_user(buf, output, len);
4825209aed5SJason A. Donenfeld 		if (left) {
4835209aed5SJason A. Donenfeld 			ret += len - left;
4843655adc7SJason A. Donenfeld 			break;
4853655adc7SJason A. Donenfeld 		}
4863655adc7SJason A. Donenfeld 
4873655adc7SJason A. Donenfeld 		buf += len;
4883655adc7SJason A. Donenfeld 		ret += len;
4895209aed5SJason A. Donenfeld 		nbytes -= len;
4905209aed5SJason A. Donenfeld 		if (!nbytes)
4915209aed5SJason A. Donenfeld 			break;
492e3c1c4fdSJason A. Donenfeld 
493e3c1c4fdSJason A. Donenfeld 		BUILD_BUG_ON(PAGE_SIZE % CHACHA_BLOCK_SIZE != 0);
4945209aed5SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
495e3c1c4fdSJason A. Donenfeld 			if (signal_pending(current))
496e3c1c4fdSJason A. Donenfeld 				break;
497e3c1c4fdSJason A. Donenfeld 			cond_resched();
498e3c1c4fdSJason A. Donenfeld 		}
4995209aed5SJason A. Donenfeld 	}
5003655adc7SJason A. Donenfeld 
5013655adc7SJason A. Donenfeld 	memzero_explicit(output, sizeof(output));
502aba120ccSJason A. Donenfeld out_zero_chacha:
503aba120ccSJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
5045209aed5SJason A. Donenfeld 	return ret ? ret : -EFAULT;
5053655adc7SJason A. Donenfeld }
5063655adc7SJason A. Donenfeld 
5073655adc7SJason A. Donenfeld /*
5083655adc7SJason A. Donenfeld  * Batched entropy returns random integers. The quality of the random
5093655adc7SJason A. Donenfeld  * number is good as /dev/urandom. In order to ensure that the randomness
5103655adc7SJason A. Donenfeld  * provided by this function is okay, the function wait_for_random_bytes()
5113655adc7SJason A. Donenfeld  * should be called and return 0 at least once at any point prior.
5123655adc7SJason A. Donenfeld  */
5133655adc7SJason A. Donenfeld struct batched_entropy {
5143655adc7SJason A. Donenfeld 	union {
5153655adc7SJason A. Donenfeld 		/*
5163655adc7SJason A. Donenfeld 		 * We make this 1.5x a ChaCha block, so that we get the
5173655adc7SJason A. Donenfeld 		 * remaining 32 bytes from fast key erasure, plus one full
5183655adc7SJason A. Donenfeld 		 * block from the detached ChaCha state. We can increase
5193655adc7SJason A. Donenfeld 		 * the size of this later if needed so long as we keep the
5203655adc7SJason A. Donenfeld 		 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.
5213655adc7SJason A. Donenfeld 		 */
5223655adc7SJason A. Donenfeld 		u64 entropy_u64[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(u64))];
5233655adc7SJason A. Donenfeld 		u32 entropy_u32[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(u32))];
5243655adc7SJason A. Donenfeld 	};
5253655adc7SJason A. Donenfeld 	local_lock_t lock;
5263655adc7SJason A. Donenfeld 	unsigned long generation;
5273655adc7SJason A. Donenfeld 	unsigned int position;
5283655adc7SJason A. Donenfeld };
5293655adc7SJason A. Donenfeld 
5303655adc7SJason A. Donenfeld 
5313655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
5323655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_u64.lock),
5333655adc7SJason A. Donenfeld 	.position = UINT_MAX
5343655adc7SJason A. Donenfeld };
5353655adc7SJason A. Donenfeld 
5363655adc7SJason A. Donenfeld u64 get_random_u64(void)
5373655adc7SJason A. Donenfeld {
5383655adc7SJason A. Donenfeld 	u64 ret;
5393655adc7SJason A. Donenfeld 	unsigned long flags;
5403655adc7SJason A. Donenfeld 	struct batched_entropy *batch;
5413655adc7SJason A. Donenfeld 	unsigned long next_gen;
5423655adc7SJason A. Donenfeld 
543cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
5443655adc7SJason A. Donenfeld 
545cbe89e5aSJason A. Donenfeld 	if  (!crng_ready()) {
546cbe89e5aSJason A. Donenfeld 		_get_random_bytes(&ret, sizeof(ret));
547cbe89e5aSJason A. Donenfeld 		return ret;
548cbe89e5aSJason A. Donenfeld 	}
549cbe89e5aSJason A. Donenfeld 
5503655adc7SJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_u64.lock, flags);
5513655adc7SJason A. Donenfeld 	batch = raw_cpu_ptr(&batched_entropy_u64);
5523655adc7SJason A. Donenfeld 
5533655adc7SJason A. Donenfeld 	next_gen = READ_ONCE(base_crng.generation);
5543655adc7SJason A. Donenfeld 	if (batch->position >= ARRAY_SIZE(batch->entropy_u64) ||
5553655adc7SJason A. Donenfeld 	    next_gen != batch->generation) {
5563655adc7SJason A. Donenfeld 		_get_random_bytes(batch->entropy_u64, sizeof(batch->entropy_u64));
5573655adc7SJason A. Donenfeld 		batch->position = 0;
5583655adc7SJason A. Donenfeld 		batch->generation = next_gen;
5593655adc7SJason A. Donenfeld 	}
5603655adc7SJason A. Donenfeld 
5613655adc7SJason A. Donenfeld 	ret = batch->entropy_u64[batch->position];
5623655adc7SJason A. Donenfeld 	batch->entropy_u64[batch->position] = 0;
5633655adc7SJason A. Donenfeld 	++batch->position;
5643655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_u64.lock, flags);
5653655adc7SJason A. Donenfeld 	return ret;
5663655adc7SJason A. Donenfeld }
5673655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_u64);
5683655adc7SJason A. Donenfeld 
5693655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
5703655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_u32.lock),
5713655adc7SJason A. Donenfeld 	.position = UINT_MAX
5723655adc7SJason A. Donenfeld };
5733655adc7SJason A. Donenfeld 
5743655adc7SJason A. Donenfeld u32 get_random_u32(void)
5753655adc7SJason A. Donenfeld {
5763655adc7SJason A. Donenfeld 	u32 ret;
5773655adc7SJason A. Donenfeld 	unsigned long flags;
5783655adc7SJason A. Donenfeld 	struct batched_entropy *batch;
5793655adc7SJason A. Donenfeld 	unsigned long next_gen;
5803655adc7SJason A. Donenfeld 
581cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
5823655adc7SJason A. Donenfeld 
583cbe89e5aSJason A. Donenfeld 	if  (!crng_ready()) {
584cbe89e5aSJason A. Donenfeld 		_get_random_bytes(&ret, sizeof(ret));
585cbe89e5aSJason A. Donenfeld 		return ret;
586cbe89e5aSJason A. Donenfeld 	}
587cbe89e5aSJason A. Donenfeld 
5883655adc7SJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_u32.lock, flags);
5893655adc7SJason A. Donenfeld 	batch = raw_cpu_ptr(&batched_entropy_u32);
5903655adc7SJason A. Donenfeld 
5913655adc7SJason A. Donenfeld 	next_gen = READ_ONCE(base_crng.generation);
5923655adc7SJason A. Donenfeld 	if (batch->position >= ARRAY_SIZE(batch->entropy_u32) ||
5933655adc7SJason A. Donenfeld 	    next_gen != batch->generation) {
5943655adc7SJason A. Donenfeld 		_get_random_bytes(batch->entropy_u32, sizeof(batch->entropy_u32));
5953655adc7SJason A. Donenfeld 		batch->position = 0;
5963655adc7SJason A. Donenfeld 		batch->generation = next_gen;
5973655adc7SJason A. Donenfeld 	}
5983655adc7SJason A. Donenfeld 
5993655adc7SJason A. Donenfeld 	ret = batch->entropy_u32[batch->position];
6003655adc7SJason A. Donenfeld 	batch->entropy_u32[batch->position] = 0;
6013655adc7SJason A. Donenfeld 	++batch->position;
6023655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_u32.lock, flags);
6033655adc7SJason A. Donenfeld 	return ret;
6043655adc7SJason A. Donenfeld }
6053655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_u32);
6063655adc7SJason A. Donenfeld 
6073191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
6083191dd5aSJason A. Donenfeld /*
6093191dd5aSJason A. Donenfeld  * This function is called when the CPU is coming up, with entry
6103191dd5aSJason A. Donenfeld  * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
6113191dd5aSJason A. Donenfeld  */
6123191dd5aSJason A. Donenfeld int random_prepare_cpu(unsigned int cpu)
6133191dd5aSJason A. Donenfeld {
6143191dd5aSJason A. Donenfeld 	/*
6153191dd5aSJason A. Donenfeld 	 * When the cpu comes back online, immediately invalidate both
6163191dd5aSJason A. Donenfeld 	 * the per-cpu crng and all batches, so that we serve fresh
6173191dd5aSJason A. Donenfeld 	 * randomness.
6183191dd5aSJason A. Donenfeld 	 */
6193191dd5aSJason A. Donenfeld 	per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
6203191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
6213191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
6223191dd5aSJason A. Donenfeld 	return 0;
6233191dd5aSJason A. Donenfeld }
6243191dd5aSJason A. Donenfeld #endif
6253191dd5aSJason A. Donenfeld 
6263655adc7SJason A. Donenfeld /**
6273655adc7SJason A. Donenfeld  * randomize_page - Generate a random, page aligned address
6283655adc7SJason A. Donenfeld  * @start:	The smallest acceptable address the caller will take.
6293655adc7SJason A. Donenfeld  * @range:	The size of the area, starting at @start, within which the
6303655adc7SJason A. Donenfeld  *		random address must fall.
6313655adc7SJason A. Donenfeld  *
6323655adc7SJason A. Donenfeld  * If @start + @range would overflow, @range is capped.
6333655adc7SJason A. Donenfeld  *
6343655adc7SJason A. Donenfeld  * NOTE: Historical use of randomize_range, which this replaces, presumed that
6353655adc7SJason A. Donenfeld  * @start was already page aligned.  We now align it regardless.
6363655adc7SJason A. Donenfeld  *
6373655adc7SJason A. Donenfeld  * Return: A page aligned address within [start, start + range).  On error,
6383655adc7SJason A. Donenfeld  * @start is returned.
6393655adc7SJason A. Donenfeld  */
6403655adc7SJason A. Donenfeld unsigned long randomize_page(unsigned long start, unsigned long range)
6413655adc7SJason A. Donenfeld {
6423655adc7SJason A. Donenfeld 	if (!PAGE_ALIGNED(start)) {
6433655adc7SJason A. Donenfeld 		range -= PAGE_ALIGN(start) - start;
6443655adc7SJason A. Donenfeld 		start = PAGE_ALIGN(start);
6453655adc7SJason A. Donenfeld 	}
6463655adc7SJason A. Donenfeld 
6473655adc7SJason A. Donenfeld 	if (start > ULONG_MAX - range)
6483655adc7SJason A. Donenfeld 		range = ULONG_MAX - start;
6493655adc7SJason A. Donenfeld 
6503655adc7SJason A. Donenfeld 	range >>= PAGE_SHIFT;
6513655adc7SJason A. Donenfeld 
6523655adc7SJason A. Donenfeld 	if (range == 0)
6533655adc7SJason A. Donenfeld 		return start;
6543655adc7SJason A. Donenfeld 
6553655adc7SJason A. Donenfeld 	return start + (get_random_long() % range << PAGE_SHIFT);
6563655adc7SJason A. Donenfeld }
6573655adc7SJason A. Donenfeld 
6583655adc7SJason A. Donenfeld /*
6593655adc7SJason A. Donenfeld  * This function will use the architecture-specific hardware random
6603655adc7SJason A. Donenfeld  * number generator if it is available. It is not recommended for
6613655adc7SJason A. Donenfeld  * use. Use get_random_bytes() instead. It returns the number of
6623655adc7SJason A. Donenfeld  * bytes filled in.
6633655adc7SJason A. Donenfeld  */
6643655adc7SJason A. Donenfeld size_t __must_check get_random_bytes_arch(void *buf, size_t nbytes)
6653655adc7SJason A. Donenfeld {
6663655adc7SJason A. Donenfeld 	size_t left = nbytes;
6673655adc7SJason A. Donenfeld 	u8 *p = buf;
6683655adc7SJason A. Donenfeld 
6693655adc7SJason A. Donenfeld 	while (left) {
6703655adc7SJason A. Donenfeld 		unsigned long v;
6713655adc7SJason A. Donenfeld 		size_t chunk = min_t(size_t, left, sizeof(unsigned long));
6723655adc7SJason A. Donenfeld 
6733655adc7SJason A. Donenfeld 		if (!arch_get_random_long(&v))
6743655adc7SJason A. Donenfeld 			break;
6753655adc7SJason A. Donenfeld 
6763655adc7SJason A. Donenfeld 		memcpy(p, &v, chunk);
6773655adc7SJason A. Donenfeld 		p += chunk;
6783655adc7SJason A. Donenfeld 		left -= chunk;
6793655adc7SJason A. Donenfeld 	}
6803655adc7SJason A. Donenfeld 
6813655adc7SJason A. Donenfeld 	return nbytes - left;
6823655adc7SJason A. Donenfeld }
6833655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_bytes_arch);
6843655adc7SJason A. Donenfeld 
685a5ed7cb1SJason A. Donenfeld 
686a5ed7cb1SJason A. Donenfeld /**********************************************************************
687a5ed7cb1SJason A. Donenfeld  *
688a5ed7cb1SJason A. Donenfeld  * Entropy accumulation and extraction routines.
689a5ed7cb1SJason A. Donenfeld  *
690a5ed7cb1SJason A. Donenfeld  * Callers may add entropy via:
691a5ed7cb1SJason A. Donenfeld  *
692a5ed7cb1SJason A. Donenfeld  *     static void mix_pool_bytes(const void *in, size_t nbytes)
693a5ed7cb1SJason A. Donenfeld  *
694a5ed7cb1SJason A. Donenfeld  * After which, if added entropy should be credited:
695a5ed7cb1SJason A. Donenfeld  *
696e85c0fc1SJason A. Donenfeld  *     static void credit_init_bits(size_t nbits)
697a5ed7cb1SJason A. Donenfeld  *
698e85c0fc1SJason A. Donenfeld  * Finally, extract entropy via:
699a5ed7cb1SJason A. Donenfeld  *
700a5ed7cb1SJason A. Donenfeld  *     static void extract_entropy(void *buf, size_t nbytes)
701a5ed7cb1SJason A. Donenfeld  *
702a5ed7cb1SJason A. Donenfeld  **********************************************************************/
703a5ed7cb1SJason A. Donenfeld 
704c5704490SJason A. Donenfeld enum {
7056e8ec255SJason A. Donenfeld 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
706e3d2c5e7SJason A. Donenfeld 	POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
707e3d2c5e7SJason A. Donenfeld 	POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
7081da177e4SLinus Torvalds };
7091da177e4SLinus Torvalds 
71090ed1e67SJason A. Donenfeld static struct {
7116e8ec255SJason A. Donenfeld 	struct blake2s_state hash;
71243358209SMatt Mackall 	spinlock_t lock;
713e85c0fc1SJason A. Donenfeld 	unsigned int init_bits;
71490ed1e67SJason A. Donenfeld } input_pool = {
7156e8ec255SJason A. Donenfeld 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
7166e8ec255SJason A. Donenfeld 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
7176e8ec255SJason A. Donenfeld 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
7186e8ec255SJason A. Donenfeld 	.hash.outlen = BLAKE2S_HASH_SIZE,
719eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
7201da177e4SLinus Torvalds };
7211da177e4SLinus Torvalds 
722a5ed7cb1SJason A. Donenfeld static void _mix_pool_bytes(const void *in, size_t nbytes)
723a5ed7cb1SJason A. Donenfeld {
724a5ed7cb1SJason A. Donenfeld 	blake2s_update(&input_pool.hash, in, nbytes);
725a5ed7cb1SJason A. Donenfeld }
72690ed1e67SJason A. Donenfeld 
7271da177e4SLinus Torvalds /*
728e85c0fc1SJason A. Donenfeld  * This function adds bytes into the input pool. It does not
729e85c0fc1SJason A. Donenfeld  * update the initialization bit counter; the caller should call
730e85c0fc1SJason A. Donenfeld  * credit_init_bits if this is appropriate.
7311da177e4SLinus Torvalds  */
73204ec96b7SJason A. Donenfeld static void mix_pool_bytes(const void *in, size_t nbytes)
7331da177e4SLinus Torvalds {
734902c098aSTheodore Ts'o 	unsigned long flags;
735902c098aSTheodore Ts'o 
73690ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
73790ed1e67SJason A. Donenfeld 	_mix_pool_bytes(in, nbytes);
73890ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
7391da177e4SLinus Torvalds }
7401da177e4SLinus Torvalds 
741a5ed7cb1SJason A. Donenfeld /*
742a5ed7cb1SJason A. Donenfeld  * This is an HKDF-like construction for using the hashed collected entropy
743a5ed7cb1SJason A. Donenfeld  * as a PRF key, that's then expanded block-by-block.
744a5ed7cb1SJason A. Donenfeld  */
745a5ed7cb1SJason A. Donenfeld static void extract_entropy(void *buf, size_t nbytes)
746a5ed7cb1SJason A. Donenfeld {
747a5ed7cb1SJason A. Donenfeld 	unsigned long flags;
748a5ed7cb1SJason A. Donenfeld 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
749a5ed7cb1SJason A. Donenfeld 	struct {
750a5ed7cb1SJason A. Donenfeld 		unsigned long rdseed[32 / sizeof(long)];
751a5ed7cb1SJason A. Donenfeld 		size_t counter;
752a5ed7cb1SJason A. Donenfeld 	} block;
753a5ed7cb1SJason A. Donenfeld 	size_t i;
754a5ed7cb1SJason A. Donenfeld 
755a5ed7cb1SJason A. Donenfeld 	for (i = 0; i < ARRAY_SIZE(block.rdseed); ++i) {
756a5ed7cb1SJason A. Donenfeld 		if (!arch_get_random_seed_long(&block.rdseed[i]) &&
757a5ed7cb1SJason A. Donenfeld 		    !arch_get_random_long(&block.rdseed[i]))
758a5ed7cb1SJason A. Donenfeld 			block.rdseed[i] = random_get_entropy();
759a5ed7cb1SJason A. Donenfeld 	}
760a5ed7cb1SJason A. Donenfeld 
761a5ed7cb1SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
762a5ed7cb1SJason A. Donenfeld 
763a5ed7cb1SJason A. Donenfeld 	/* seed = HASHPRF(last_key, entropy_input) */
764a5ed7cb1SJason A. Donenfeld 	blake2s_final(&input_pool.hash, seed);
765a5ed7cb1SJason A. Donenfeld 
766a5ed7cb1SJason A. Donenfeld 	/* next_key = HASHPRF(seed, RDSEED || 0) */
767a5ed7cb1SJason A. Donenfeld 	block.counter = 0;
768a5ed7cb1SJason A. Donenfeld 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
769a5ed7cb1SJason A. Donenfeld 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
770a5ed7cb1SJason A. Donenfeld 
771a5ed7cb1SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
772a5ed7cb1SJason A. Donenfeld 	memzero_explicit(next_key, sizeof(next_key));
773a5ed7cb1SJason A. Donenfeld 
774a5ed7cb1SJason A. Donenfeld 	while (nbytes) {
775a5ed7cb1SJason A. Donenfeld 		i = min_t(size_t, nbytes, BLAKE2S_HASH_SIZE);
776a5ed7cb1SJason A. Donenfeld 		/* output = HASHPRF(seed, RDSEED || ++counter) */
777a5ed7cb1SJason A. Donenfeld 		++block.counter;
778a5ed7cb1SJason A. Donenfeld 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
779a5ed7cb1SJason A. Donenfeld 		nbytes -= i;
780a5ed7cb1SJason A. Donenfeld 		buf += i;
781a5ed7cb1SJason A. Donenfeld 	}
782a5ed7cb1SJason A. Donenfeld 
783a5ed7cb1SJason A. Donenfeld 	memzero_explicit(seed, sizeof(seed));
784a5ed7cb1SJason A. Donenfeld 	memzero_explicit(&block, sizeof(block));
785a5ed7cb1SJason A. Donenfeld }
786a5ed7cb1SJason A. Donenfeld 
787e85c0fc1SJason A. Donenfeld static void credit_init_bits(size_t nbits)
788a5ed7cb1SJason A. Donenfeld {
789fed7ef06SJason A. Donenfeld 	unsigned int new, orig, add;
7905c3b747eSJason A. Donenfeld 	unsigned long flags;
7915c3b747eSJason A. Donenfeld 
792e85c0fc1SJason A. Donenfeld 	if (crng_ready() || !nbits)
7935c3b747eSJason A. Donenfeld 		return;
7945c3b747eSJason A. Donenfeld 
7955c3b747eSJason A. Donenfeld 	add = min_t(size_t, nbits, POOL_BITS);
7965c3b747eSJason A. Donenfeld 
7975c3b747eSJason A. Donenfeld 	do {
798e85c0fc1SJason A. Donenfeld 		orig = READ_ONCE(input_pool.init_bits);
799fed7ef06SJason A. Donenfeld 		new = min_t(unsigned int, POOL_BITS, orig + add);
800fed7ef06SJason A. Donenfeld 	} while (cmpxchg(&input_pool.init_bits, orig, new) != orig);
8015c3b747eSJason A. Donenfeld 
80268c9c8b1SJason A. Donenfeld 	if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
80368c9c8b1SJason A. Donenfeld 		crng_reseed(); /* Sets crng_init to CRNG_READY under base_crng.lock. */
80468c9c8b1SJason A. Donenfeld 		process_random_ready_list();
80568c9c8b1SJason A. Donenfeld 		wake_up_interruptible(&crng_init_wait);
80668c9c8b1SJason A. Donenfeld 		kill_fasync(&fasync, SIGIO, POLL_IN);
80768c9c8b1SJason A. Donenfeld 		pr_notice("crng init done\n");
808cc1e127bSJason A. Donenfeld 		if (urandom_warning.missed)
80968c9c8b1SJason A. Donenfeld 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
81068c9c8b1SJason A. Donenfeld 				  urandom_warning.missed);
81168c9c8b1SJason A. Donenfeld 	} else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
8125c3b747eSJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
81368c9c8b1SJason A. Donenfeld 		/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
814e3d2c5e7SJason A. Donenfeld 		if (crng_init == CRNG_EMPTY) {
8155c3b747eSJason A. Donenfeld 			extract_entropy(base_crng.key, sizeof(base_crng.key));
816e3d2c5e7SJason A. Donenfeld 			crng_init = CRNG_EARLY;
8175c3b747eSJason A. Donenfeld 		}
8185c3b747eSJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
8195c3b747eSJason A. Donenfeld 	}
8205c3b747eSJason A. Donenfeld }
8215c3b747eSJason A. Donenfeld 
82292c653cfSJason A. Donenfeld 
82392c653cfSJason A. Donenfeld /**********************************************************************
82492c653cfSJason A. Donenfeld  *
82592c653cfSJason A. Donenfeld  * Entropy collection routines.
82692c653cfSJason A. Donenfeld  *
82792c653cfSJason A. Donenfeld  * The following exported functions are used for pushing entropy into
82892c653cfSJason A. Donenfeld  * the above entropy accumulation routines:
82992c653cfSJason A. Donenfeld  *
83092c653cfSJason A. Donenfeld  *	void add_device_randomness(const void *buf, size_t size);
83192c653cfSJason A. Donenfeld  *	void add_hwgenerator_randomness(const void *buffer, size_t count,
83292c653cfSJason A. Donenfeld  *					size_t entropy);
83392c653cfSJason A. Donenfeld  *	void add_bootloader_randomness(const void *buf, size_t size);
834ae099e8eSJason A. Donenfeld  *	void add_vmfork_randomness(const void *unique_vm_id, size_t size);
83592c653cfSJason A. Donenfeld  *	void add_interrupt_randomness(int irq);
836a4b5c26bSJason A. Donenfeld  *	void add_input_randomness(unsigned int type, unsigned int code,
837a4b5c26bSJason A. Donenfeld  *	                          unsigned int value);
838a4b5c26bSJason A. Donenfeld  *	void add_disk_randomness(struct gendisk *disk);
83992c653cfSJason A. Donenfeld  *
84092c653cfSJason A. Donenfeld  * add_device_randomness() adds data to the input pool that
84192c653cfSJason A. Donenfeld  * is likely to differ between two devices (or possibly even per boot).
84292c653cfSJason A. Donenfeld  * This would be things like MAC addresses or serial numbers, or the
84392c653cfSJason A. Donenfeld  * read-out of the RTC. This does *not* credit any actual entropy to
84492c653cfSJason A. Donenfeld  * the pool, but it initializes the pool to different values for devices
84592c653cfSJason A. Donenfeld  * that might otherwise be identical and have very little entropy
84692c653cfSJason A. Donenfeld  * available to them (particularly common in the embedded world).
84792c653cfSJason A. Donenfeld  *
84892c653cfSJason A. Donenfeld  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
84992c653cfSJason A. Donenfeld  * entropy as specified by the caller. If the entropy pool is full it will
85092c653cfSJason A. Donenfeld  * block until more entropy is needed.
85192c653cfSJason A. Donenfeld  *
8525c3b747eSJason A. Donenfeld  * add_bootloader_randomness() is called by bootloader drivers, such as EFI
8535c3b747eSJason A. Donenfeld  * and device tree, and credits its input depending on whether or not the
8545c3b747eSJason A. Donenfeld  * configuration option CONFIG_RANDOM_TRUST_BOOTLOADER is set.
85592c653cfSJason A. Donenfeld  *
856ae099e8eSJason A. Donenfeld  * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
857ae099e8eSJason A. Donenfeld  * representing the current instance of a VM to the pool, without crediting,
858ae099e8eSJason A. Donenfeld  * and then force-reseeds the crng so that it takes effect immediately.
859ae099e8eSJason A. Donenfeld  *
86092c653cfSJason A. Donenfeld  * add_interrupt_randomness() uses the interrupt timing as random
86192c653cfSJason A. Donenfeld  * inputs to the entropy pool. Using the cycle counters and the irq source
86292c653cfSJason A. Donenfeld  * as inputs, it feeds the input pool roughly once a second or after 64
86392c653cfSJason A. Donenfeld  * interrupts, crediting 1 bit of entropy for whichever comes first.
86492c653cfSJason A. Donenfeld  *
865a4b5c26bSJason A. Donenfeld  * add_input_randomness() uses the input layer interrupt timing, as well
866a4b5c26bSJason A. Donenfeld  * as the event type information from the hardware.
867a4b5c26bSJason A. Donenfeld  *
868a4b5c26bSJason A. Donenfeld  * add_disk_randomness() uses what amounts to the seek time of block
869a4b5c26bSJason A. Donenfeld  * layer request events, on a per-disk_devt basis, as input to the
870a4b5c26bSJason A. Donenfeld  * entropy pool. Note that high-speed solid state drives with very low
871a4b5c26bSJason A. Donenfeld  * seek times do not make for good sources of entropy, as their seek
872a4b5c26bSJason A. Donenfeld  * times are usually fairly consistent.
873a4b5c26bSJason A. Donenfeld  *
874a4b5c26bSJason A. Donenfeld  * The last two routines try to estimate how many bits of entropy
875a4b5c26bSJason A. Donenfeld  * to credit. They do this by keeping track of the first and second
876a4b5c26bSJason A. Donenfeld  * order deltas of the event timings.
877a4b5c26bSJason A. Donenfeld  *
87892c653cfSJason A. Donenfeld  **********************************************************************/
87992c653cfSJason A. Donenfeld 
88092c653cfSJason A. Donenfeld static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
881d97c68d1SJason A. Donenfeld static bool trust_bootloader __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER);
88292c653cfSJason A. Donenfeld static int __init parse_trust_cpu(char *arg)
88392c653cfSJason A. Donenfeld {
88492c653cfSJason A. Donenfeld 	return kstrtobool(arg, &trust_cpu);
88592c653cfSJason A. Donenfeld }
886d97c68d1SJason A. Donenfeld static int __init parse_trust_bootloader(char *arg)
887d97c68d1SJason A. Donenfeld {
888d97c68d1SJason A. Donenfeld 	return kstrtobool(arg, &trust_bootloader);
889d97c68d1SJason A. Donenfeld }
89092c653cfSJason A. Donenfeld early_param("random.trust_cpu", parse_trust_cpu);
891d97c68d1SJason A. Donenfeld early_param("random.trust_bootloader", parse_trust_bootloader);
892775f4b29STheodore Ts'o 
893b7b67d13SJason A. Donenfeld static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
894b7b67d13SJason A. Donenfeld {
895b7b67d13SJason A. Donenfeld 	unsigned long flags, entropy = random_get_entropy();
896b7b67d13SJason A. Donenfeld 
897b7b67d13SJason A. Donenfeld 	/*
898b7b67d13SJason A. Donenfeld 	 * Encode a representation of how long the system has been suspended,
899b7b67d13SJason A. Donenfeld 	 * in a way that is distinct from prior system suspends.
900b7b67d13SJason A. Donenfeld 	 */
901b7b67d13SJason A. Donenfeld 	ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
902b7b67d13SJason A. Donenfeld 
903b7b67d13SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
904b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&action, sizeof(action));
905b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(stamps, sizeof(stamps));
906b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
907b7b67d13SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
908b7b67d13SJason A. Donenfeld 
909b7b67d13SJason A. Donenfeld 	if (crng_ready() && (action == PM_RESTORE_PREPARE ||
910b7b67d13SJason A. Donenfeld 	    (action == PM_POST_SUSPEND &&
911b7b67d13SJason A. Donenfeld 	     !IS_ENABLED(CONFIG_PM_AUTOSLEEP) && !IS_ENABLED(CONFIG_ANDROID)))) {
912e85c0fc1SJason A. Donenfeld 		crng_reseed();
913b7b67d13SJason A. Donenfeld 		pr_notice("crng reseeded on system resumption\n");
914b7b67d13SJason A. Donenfeld 	}
915b7b67d13SJason A. Donenfeld 	return 0;
916b7b67d13SJason A. Donenfeld }
917b7b67d13SJason A. Donenfeld 
918b7b67d13SJason A. Donenfeld static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
919b7b67d13SJason A. Donenfeld 
920775f4b29STheodore Ts'o /*
92192c653cfSJason A. Donenfeld  * The first collection of entropy occurs at system boot while interrupts
92292c653cfSJason A. Donenfeld  * are still turned off. Here we push in RDSEED, a timestamp, and utsname().
92392c653cfSJason A. Donenfeld  * Depending on the above configuration knob, RDSEED may be considered
92492c653cfSJason A. Donenfeld  * sufficient for initialization. Note that much earlier setup may already
92592c653cfSJason A. Donenfeld  * have pushed entropy into the input pool by the time we get here.
926775f4b29STheodore Ts'o  */
92792c653cfSJason A. Donenfeld int __init rand_initialize(void)
928775f4b29STheodore Ts'o {
92992c653cfSJason A. Donenfeld 	size_t i;
93092c653cfSJason A. Donenfeld 	ktime_t now = ktime_get_real();
93192c653cfSJason A. Donenfeld 	bool arch_init = true;
93292c653cfSJason A. Donenfeld 	unsigned long rv;
933775f4b29STheodore Ts'o 
9341754abb3SJason A. Donenfeld #if defined(LATENT_ENTROPY_PLUGIN)
9351754abb3SJason A. Donenfeld 	static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
9361754abb3SJason A. Donenfeld 	_mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
9371754abb3SJason A. Donenfeld #endif
9381754abb3SJason A. Donenfeld 
93992c653cfSJason A. Donenfeld 	for (i = 0; i < BLAKE2S_BLOCK_SIZE; i += sizeof(rv)) {
94092c653cfSJason A. Donenfeld 		if (!arch_get_random_seed_long_early(&rv) &&
94192c653cfSJason A. Donenfeld 		    !arch_get_random_long_early(&rv)) {
94292c653cfSJason A. Donenfeld 			rv = random_get_entropy();
94392c653cfSJason A. Donenfeld 			arch_init = false;
94492c653cfSJason A. Donenfeld 		}
945afba0b80SJason A. Donenfeld 		_mix_pool_bytes(&rv, sizeof(rv));
94692c653cfSJason A. Donenfeld 	}
947afba0b80SJason A. Donenfeld 	_mix_pool_bytes(&now, sizeof(now));
948afba0b80SJason A. Donenfeld 	_mix_pool_bytes(utsname(), sizeof(*(utsname())));
949655b2264STheodore Ts'o 
950e85c0fc1SJason A. Donenfeld 	if (crng_ready())
951e85c0fc1SJason A. Donenfeld 		crng_reseed();
952e85c0fc1SJason A. Donenfeld 	else if (arch_init && trust_cpu)
953e85c0fc1SJason A. Donenfeld 		credit_init_bits(BLAKE2S_BLOCK_SIZE * 8);
954775f4b29STheodore Ts'o 
955b7b67d13SJason A. Donenfeld 	WARN_ON(register_pm_notifier(&pm_notifier));
956b7b67d13SJason A. Donenfeld 
9574b758edaSJason A. Donenfeld 	WARN(!random_get_entropy(), "Missing cycle counter and fallback timer; RNG "
9584b758edaSJason A. Donenfeld 				    "entropy collection will consequently suffer.");
95992c653cfSJason A. Donenfeld 	return 0;
96092c653cfSJason A. Donenfeld }
9611da177e4SLinus Torvalds 
962a2080a67SLinus Torvalds /*
963e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
964e192be9dSTheodore Ts'o  * initialize it.
965a2080a67SLinus Torvalds  *
966e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
967e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
968e192be9dSTheodore Ts'o  * identical devices.
969a2080a67SLinus Torvalds  */
97004ec96b7SJason A. Donenfeld void add_device_randomness(const void *buf, size_t size)
971a2080a67SLinus Torvalds {
9724b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
9734b758edaSJason A. Donenfeld 	unsigned long flags;
974a2080a67SLinus Torvalds 
9753ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
9764b758edaSJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
97790ed1e67SJason A. Donenfeld 	_mix_pool_bytes(buf, size);
9783ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
979a2080a67SLinus Torvalds }
980a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
981a2080a67SLinus Torvalds 
98292c653cfSJason A. Donenfeld /*
98392c653cfSJason A. Donenfeld  * Interface for in-kernel drivers of true hardware RNGs.
98492c653cfSJason A. Donenfeld  * Those devices may produce endless random bits and will be throttled
98592c653cfSJason A. Donenfeld  * when our pool is full.
98692c653cfSJason A. Donenfeld  */
98792c653cfSJason A. Donenfeld void add_hwgenerator_randomness(const void *buffer, size_t count,
98892c653cfSJason A. Donenfeld 				size_t entropy)
98992c653cfSJason A. Donenfeld {
99092c653cfSJason A. Donenfeld 	mix_pool_bytes(buffer, count);
991e85c0fc1SJason A. Donenfeld 	credit_init_bits(entropy);
992e85c0fc1SJason A. Donenfeld 
993e85c0fc1SJason A. Donenfeld 	/*
994e85c0fc1SJason A. Donenfeld 	 * Throttle writing to once every CRNG_RESEED_INTERVAL, unless
995e85c0fc1SJason A. Donenfeld 	 * we're not yet initialized.
996e85c0fc1SJason A. Donenfeld 	 */
997e85c0fc1SJason A. Donenfeld 	if (!kthread_should_stop() && crng_ready())
998e85c0fc1SJason A. Donenfeld 		schedule_timeout_interruptible(CRNG_RESEED_INTERVAL);
99992c653cfSJason A. Donenfeld }
100092c653cfSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
100192c653cfSJason A. Donenfeld 
100292c653cfSJason A. Donenfeld /*
10035c3b747eSJason A. Donenfeld  * Handle random seed passed by bootloader, and credit it if
10045c3b747eSJason A. Donenfeld  * CONFIG_RANDOM_TRUST_BOOTLOADER is set.
100592c653cfSJason A. Donenfeld  */
100692c653cfSJason A. Donenfeld void add_bootloader_randomness(const void *buf, size_t size)
100792c653cfSJason A. Donenfeld {
10085c3b747eSJason A. Donenfeld 	mix_pool_bytes(buf, size);
1009d97c68d1SJason A. Donenfeld 	if (trust_bootloader)
1010e85c0fc1SJason A. Donenfeld 		credit_init_bits(size * 8);
101192c653cfSJason A. Donenfeld }
101292c653cfSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_bootloader_randomness);
101392c653cfSJason A. Donenfeld 
1014a4107d34SJason A. Donenfeld #if IS_ENABLED(CONFIG_VMGENID)
1015f3c2682bSJason A. Donenfeld static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
1016f3c2682bSJason A. Donenfeld 
1017ae099e8eSJason A. Donenfeld /*
1018ae099e8eSJason A. Donenfeld  * Handle a new unique VM ID, which is unique, not secret, so we
1019ae099e8eSJason A. Donenfeld  * don't credit it, but we do immediately force a reseed after so
1020ae099e8eSJason A. Donenfeld  * that it's used by the crng posthaste.
1021ae099e8eSJason A. Donenfeld  */
1022ae099e8eSJason A. Donenfeld void add_vmfork_randomness(const void *unique_vm_id, size_t size)
1023ae099e8eSJason A. Donenfeld {
1024ae099e8eSJason A. Donenfeld 	add_device_randomness(unique_vm_id, size);
1025ae099e8eSJason A. Donenfeld 	if (crng_ready()) {
1026e85c0fc1SJason A. Donenfeld 		crng_reseed();
1027ae099e8eSJason A. Donenfeld 		pr_notice("crng reseeded due to virtual machine fork\n");
1028ae099e8eSJason A. Donenfeld 	}
1029f3c2682bSJason A. Donenfeld 	blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
1030ae099e8eSJason A. Donenfeld }
1031a4107d34SJason A. Donenfeld #if IS_MODULE(CONFIG_VMGENID)
1032ae099e8eSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_vmfork_randomness);
1033a4107d34SJason A. Donenfeld #endif
1034f3c2682bSJason A. Donenfeld 
1035f3c2682bSJason A. Donenfeld int register_random_vmfork_notifier(struct notifier_block *nb)
1036f3c2682bSJason A. Donenfeld {
1037f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_register(&vmfork_chain, nb);
1038f3c2682bSJason A. Donenfeld }
1039f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
1040f3c2682bSJason A. Donenfeld 
1041f3c2682bSJason A. Donenfeld int unregister_random_vmfork_notifier(struct notifier_block *nb)
1042f3c2682bSJason A. Donenfeld {
1043f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_unregister(&vmfork_chain, nb);
1044f3c2682bSJason A. Donenfeld }
1045f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
1046a4107d34SJason A. Donenfeld #endif
1047ae099e8eSJason A. Donenfeld 
104892c653cfSJason A. Donenfeld struct fast_pool {
104958340f8eSJason A. Donenfeld 	struct work_struct mix;
1050f5eab0e2SJason A. Donenfeld 	unsigned long pool[4];
105192c653cfSJason A. Donenfeld 	unsigned long last;
10523191dd5aSJason A. Donenfeld 	unsigned int count;
105392c653cfSJason A. Donenfeld };
105492c653cfSJason A. Donenfeld 
1055f5eab0e2SJason A. Donenfeld static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
1056f5eab0e2SJason A. Donenfeld #ifdef CONFIG_64BIT
1057e73aaae2SJason A. Donenfeld #define FASTMIX_PERM SIPHASH_PERMUTATION
1058e73aaae2SJason A. Donenfeld 	.pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 }
1059f5eab0e2SJason A. Donenfeld #else
1060e73aaae2SJason A. Donenfeld #define FASTMIX_PERM HSIPHASH_PERMUTATION
1061e73aaae2SJason A. Donenfeld 	.pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 }
1062f5eab0e2SJason A. Donenfeld #endif
1063f5eab0e2SJason A. Donenfeld };
1064f5eab0e2SJason A. Donenfeld 
106592c653cfSJason A. Donenfeld /*
1066f5eab0e2SJason A. Donenfeld  * This is [Half]SipHash-1-x, starting from an empty key. Because
1067f5eab0e2SJason A. Donenfeld  * the key is fixed, it assumes that its inputs are non-malicious,
1068f5eab0e2SJason A. Donenfeld  * and therefore this has no security on its own. s represents the
10694b758edaSJason A. Donenfeld  * four-word SipHash state, while v represents a two-word input.
107092c653cfSJason A. Donenfeld  */
1071791332b3SJason A. Donenfeld static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
107292c653cfSJason A. Donenfeld {
1073791332b3SJason A. Donenfeld 	s[3] ^= v1;
1074e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1075791332b3SJason A. Donenfeld 	s[0] ^= v1;
1076791332b3SJason A. Donenfeld 	s[3] ^= v2;
1077e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1078791332b3SJason A. Donenfeld 	s[0] ^= v2;
1079f5eab0e2SJason A. Donenfeld }
1080775f4b29STheodore Ts'o 
10813191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
10823191dd5aSJason A. Donenfeld /*
10833191dd5aSJason A. Donenfeld  * This function is called when the CPU has just come online, with
10843191dd5aSJason A. Donenfeld  * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
10853191dd5aSJason A. Donenfeld  */
10863191dd5aSJason A. Donenfeld int random_online_cpu(unsigned int cpu)
10873191dd5aSJason A. Donenfeld {
10883191dd5aSJason A. Donenfeld 	/*
10893191dd5aSJason A. Donenfeld 	 * During CPU shutdown and before CPU onlining, add_interrupt_
10903191dd5aSJason A. Donenfeld 	 * randomness() may schedule mix_interrupt_randomness(), and
10913191dd5aSJason A. Donenfeld 	 * set the MIX_INFLIGHT flag. However, because the worker can
10923191dd5aSJason A. Donenfeld 	 * be scheduled on a different CPU during this period, that
10933191dd5aSJason A. Donenfeld 	 * flag will never be cleared. For that reason, we zero out
10943191dd5aSJason A. Donenfeld 	 * the flag here, which runs just after workqueues are onlined
10953191dd5aSJason A. Donenfeld 	 * for the CPU again. This also has the effect of setting the
10963191dd5aSJason A. Donenfeld 	 * irq randomness count to zero so that new accumulated irqs
10973191dd5aSJason A. Donenfeld 	 * are fresh.
10983191dd5aSJason A. Donenfeld 	 */
10993191dd5aSJason A. Donenfeld 	per_cpu_ptr(&irq_randomness, cpu)->count = 0;
11003191dd5aSJason A. Donenfeld 	return 0;
11013191dd5aSJason A. Donenfeld }
11023191dd5aSJason A. Donenfeld #endif
11033191dd5aSJason A. Donenfeld 
110458340f8eSJason A. Donenfeld static void mix_interrupt_randomness(struct work_struct *work)
110558340f8eSJason A. Donenfeld {
110658340f8eSJason A. Donenfeld 	struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
1107f5eab0e2SJason A. Donenfeld 	/*
11084b758edaSJason A. Donenfeld 	 * The size of the copied stack pool is explicitly 2 longs so that we
11094b758edaSJason A. Donenfeld 	 * only ever ingest half of the siphash output each time, retaining
11104b758edaSJason A. Donenfeld 	 * the other half as the next "key" that carries over. The entropy is
11114b758edaSJason A. Donenfeld 	 * supposed to be sufficiently dispersed between bits so on average
11124b758edaSJason A. Donenfeld 	 * we don't wind up "losing" some.
1113f5eab0e2SJason A. Donenfeld 	 */
11144b758edaSJason A. Donenfeld 	unsigned long pool[2];
1115e3e33fc2SJason A. Donenfeld 	unsigned int count;
111658340f8eSJason A. Donenfeld 
111758340f8eSJason A. Donenfeld 	/* Check to see if we're running on the wrong CPU due to hotplug. */
111858340f8eSJason A. Donenfeld 	local_irq_disable();
111958340f8eSJason A. Donenfeld 	if (fast_pool != this_cpu_ptr(&irq_randomness)) {
112058340f8eSJason A. Donenfeld 		local_irq_enable();
112158340f8eSJason A. Donenfeld 		return;
112258340f8eSJason A. Donenfeld 	}
112358340f8eSJason A. Donenfeld 
112458340f8eSJason A. Donenfeld 	/*
112558340f8eSJason A. Donenfeld 	 * Copy the pool to the stack so that the mixer always has a
112658340f8eSJason A. Donenfeld 	 * consistent view, before we reenable irqs again.
112758340f8eSJason A. Donenfeld 	 */
1128f5eab0e2SJason A. Donenfeld 	memcpy(pool, fast_pool->pool, sizeof(pool));
1129e3e33fc2SJason A. Donenfeld 	count = fast_pool->count;
11303191dd5aSJason A. Donenfeld 	fast_pool->count = 0;
113158340f8eSJason A. Donenfeld 	fast_pool->last = jiffies;
113258340f8eSJason A. Donenfeld 	local_irq_enable();
113358340f8eSJason A. Donenfeld 
113458340f8eSJason A. Donenfeld 	mix_pool_bytes(pool, sizeof(pool));
1135e3e33fc2SJason A. Donenfeld 	credit_init_bits(max(1u, (count & U16_MAX) / 64));
1136c2a7de4fSJason A. Donenfeld 
113758340f8eSJason A. Donenfeld 	memzero_explicit(pool, sizeof(pool));
113858340f8eSJason A. Donenfeld }
113958340f8eSJason A. Donenfeld 
1140703f7066SSebastian Andrzej Siewior void add_interrupt_randomness(int irq)
11411da177e4SLinus Torvalds {
114258340f8eSJason A. Donenfeld 	enum { MIX_INFLIGHT = 1U << 31 };
11434b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
11441b2a1a7eSChristoph Lameter 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
1145775f4b29STheodore Ts'o 	struct pt_regs *regs = get_irq_regs();
114658340f8eSJason A. Donenfeld 	unsigned int new_count;
11473060d6feSYinghai Lu 
1148791332b3SJason A. Donenfeld 	fast_mix(fast_pool->pool, entropy,
1149791332b3SJason A. Donenfeld 		 (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
11503191dd5aSJason A. Donenfeld 	new_count = ++fast_pool->count;
1151775f4b29STheodore Ts'o 
115258340f8eSJason A. Donenfeld 	if (new_count & MIX_INFLIGHT)
11531da177e4SLinus Torvalds 		return;
1154840f9507STheodore Ts'o 
11555c3b747eSJason A. Donenfeld 	if (new_count < 64 && !time_is_before_jiffies(fast_pool->last + HZ))
11561da177e4SLinus Torvalds 		return;
11571da177e4SLinus Torvalds 
115858340f8eSJason A. Donenfeld 	if (unlikely(!fast_pool->mix.func))
115958340f8eSJason A. Donenfeld 		INIT_WORK(&fast_pool->mix, mix_interrupt_randomness);
11603191dd5aSJason A. Donenfeld 	fast_pool->count |= MIX_INFLIGHT;
116158340f8eSJason A. Donenfeld 	queue_work_on(raw_smp_processor_id(), system_highpri_wq, &fast_pool->mix);
11621da177e4SLinus Torvalds }
11634b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
11641da177e4SLinus Torvalds 
1165a4b5c26bSJason A. Donenfeld /* There is one of these per entropy source */
1166a4b5c26bSJason A. Donenfeld struct timer_rand_state {
1167a4b5c26bSJason A. Donenfeld 	unsigned long last_time;
1168a4b5c26bSJason A. Donenfeld 	long last_delta, last_delta2;
1169a4b5c26bSJason A. Donenfeld };
1170a4b5c26bSJason A. Donenfeld 
1171a4b5c26bSJason A. Donenfeld /*
1172a4b5c26bSJason A. Donenfeld  * This function adds entropy to the entropy "pool" by using timing
1173a4b5c26bSJason A. Donenfeld  * delays. It uses the timer_rand_state structure to make an estimate
1174e3e33fc2SJason A. Donenfeld  * of how many bits of entropy this call has added to the pool. The
1175e3e33fc2SJason A. Donenfeld  * value "num" is also added to the pool; it should somehow describe
1176e3e33fc2SJason A. Donenfeld  * the type of event that just happened.
1177a4b5c26bSJason A. Donenfeld  */
1178a4b5c26bSJason A. Donenfeld static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1179a4b5c26bSJason A. Donenfeld {
1180a4b5c26bSJason A. Donenfeld 	unsigned long entropy = random_get_entropy(), now = jiffies, flags;
1181a4b5c26bSJason A. Donenfeld 	long delta, delta2, delta3;
1182e3e33fc2SJason A. Donenfeld 	unsigned int bits;
1183a4b5c26bSJason A. Donenfeld 
1184e3e33fc2SJason A. Donenfeld 	/*
1185e3e33fc2SJason A. Donenfeld 	 * If we're in a hard IRQ, add_interrupt_randomness() will be called
1186e3e33fc2SJason A. Donenfeld 	 * sometime after, so mix into the fast pool.
1187e3e33fc2SJason A. Donenfeld 	 */
1188e3e33fc2SJason A. Donenfeld 	if (in_hardirq()) {
1189791332b3SJason A. Donenfeld 		fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
1190e3e33fc2SJason A. Donenfeld 	} else {
1191a4b5c26bSJason A. Donenfeld 		spin_lock_irqsave(&input_pool.lock, flags);
1192a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&entropy, sizeof(entropy));
1193a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&num, sizeof(num));
1194a4b5c26bSJason A. Donenfeld 		spin_unlock_irqrestore(&input_pool.lock, flags);
1195e3e33fc2SJason A. Donenfeld 	}
1196a4b5c26bSJason A. Donenfeld 
1197a4b5c26bSJason A. Donenfeld 	if (crng_ready())
1198a4b5c26bSJason A. Donenfeld 		return;
1199a4b5c26bSJason A. Donenfeld 
1200a4b5c26bSJason A. Donenfeld 	/*
1201a4b5c26bSJason A. Donenfeld 	 * Calculate number of bits of randomness we probably added.
1202a4b5c26bSJason A. Donenfeld 	 * We take into account the first, second and third-order deltas
1203a4b5c26bSJason A. Donenfeld 	 * in order to make our estimate.
1204a4b5c26bSJason A. Donenfeld 	 */
1205a4b5c26bSJason A. Donenfeld 	delta = now - READ_ONCE(state->last_time);
1206a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_time, now);
1207a4b5c26bSJason A. Donenfeld 
1208a4b5c26bSJason A. Donenfeld 	delta2 = delta - READ_ONCE(state->last_delta);
1209a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta, delta);
1210a4b5c26bSJason A. Donenfeld 
1211a4b5c26bSJason A. Donenfeld 	delta3 = delta2 - READ_ONCE(state->last_delta2);
1212a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta2, delta2);
1213a4b5c26bSJason A. Donenfeld 
1214a4b5c26bSJason A. Donenfeld 	if (delta < 0)
1215a4b5c26bSJason A. Donenfeld 		delta = -delta;
1216a4b5c26bSJason A. Donenfeld 	if (delta2 < 0)
1217a4b5c26bSJason A. Donenfeld 		delta2 = -delta2;
1218a4b5c26bSJason A. Donenfeld 	if (delta3 < 0)
1219a4b5c26bSJason A. Donenfeld 		delta3 = -delta3;
1220a4b5c26bSJason A. Donenfeld 	if (delta > delta2)
1221a4b5c26bSJason A. Donenfeld 		delta = delta2;
1222a4b5c26bSJason A. Donenfeld 	if (delta > delta3)
1223a4b5c26bSJason A. Donenfeld 		delta = delta3;
1224a4b5c26bSJason A. Donenfeld 
1225a4b5c26bSJason A. Donenfeld 	/*
1226e3e33fc2SJason A. Donenfeld 	 * delta is now minimum absolute delta. Round down by 1 bit
1227e3e33fc2SJason A. Donenfeld 	 * on general principles, and limit entropy estimate to 11 bits.
1228a4b5c26bSJason A. Donenfeld 	 */
1229e3e33fc2SJason A. Donenfeld 	bits = min(fls(delta >> 1), 11);
1230e3e33fc2SJason A. Donenfeld 
1231e3e33fc2SJason A. Donenfeld 	/*
1232e3e33fc2SJason A. Donenfeld 	 * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
1233e3e33fc2SJason A. Donenfeld 	 * will run after this, which uses a different crediting scheme of 1 bit
1234e3e33fc2SJason A. Donenfeld 	 * per every 64 interrupts. In order to let that function do accounting
1235e3e33fc2SJason A. Donenfeld 	 * close to the one in this function, we credit a full 64/64 bit per bit,
1236e3e33fc2SJason A. Donenfeld 	 * and then subtract one to account for the extra one added.
1237e3e33fc2SJason A. Donenfeld 	 */
1238e3e33fc2SJason A. Donenfeld 	if (in_hardirq())
1239e3e33fc2SJason A. Donenfeld 		this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
1240e3e33fc2SJason A. Donenfeld 	else
1241e3e33fc2SJason A. Donenfeld 		credit_init_bits(bits);
1242a4b5c26bSJason A. Donenfeld }
1243a4b5c26bSJason A. Donenfeld 
1244a4b5c26bSJason A. Donenfeld void add_input_randomness(unsigned int type, unsigned int code,
1245a4b5c26bSJason A. Donenfeld 			  unsigned int value)
1246a4b5c26bSJason A. Donenfeld {
1247a4b5c26bSJason A. Donenfeld 	static unsigned char last_value;
1248a4b5c26bSJason A. Donenfeld 	static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
1249a4b5c26bSJason A. Donenfeld 
1250a4b5c26bSJason A. Donenfeld 	/* Ignore autorepeat and the like. */
1251a4b5c26bSJason A. Donenfeld 	if (value == last_value)
1252a4b5c26bSJason A. Donenfeld 		return;
1253a4b5c26bSJason A. Donenfeld 
1254a4b5c26bSJason A. Donenfeld 	last_value = value;
1255a4b5c26bSJason A. Donenfeld 	add_timer_randomness(&input_timer_state,
1256a4b5c26bSJason A. Donenfeld 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1257a4b5c26bSJason A. Donenfeld }
1258a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_input_randomness);
1259a4b5c26bSJason A. Donenfeld 
1260a4b5c26bSJason A. Donenfeld #ifdef CONFIG_BLOCK
1261a4b5c26bSJason A. Donenfeld void add_disk_randomness(struct gendisk *disk)
1262a4b5c26bSJason A. Donenfeld {
1263a4b5c26bSJason A. Donenfeld 	if (!disk || !disk->random)
1264a4b5c26bSJason A. Donenfeld 		return;
1265a4b5c26bSJason A. Donenfeld 	/* First major is 1, so we get >= 0x200 here. */
1266a4b5c26bSJason A. Donenfeld 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1267a4b5c26bSJason A. Donenfeld }
1268a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_disk_randomness);
1269a4b5c26bSJason A. Donenfeld 
1270a4b5c26bSJason A. Donenfeld void rand_initialize_disk(struct gendisk *disk)
1271a4b5c26bSJason A. Donenfeld {
1272a4b5c26bSJason A. Donenfeld 	struct timer_rand_state *state;
1273a4b5c26bSJason A. Donenfeld 
1274a4b5c26bSJason A. Donenfeld 	/*
1275a4b5c26bSJason A. Donenfeld 	 * If kzalloc returns null, we just won't use that entropy
1276a4b5c26bSJason A. Donenfeld 	 * source.
1277a4b5c26bSJason A. Donenfeld 	 */
1278a4b5c26bSJason A. Donenfeld 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1279a4b5c26bSJason A. Donenfeld 	if (state) {
1280a4b5c26bSJason A. Donenfeld 		state->last_time = INITIAL_JIFFIES;
1281a4b5c26bSJason A. Donenfeld 		disk->random = state;
1282a4b5c26bSJason A. Donenfeld 	}
1283a4b5c26bSJason A. Donenfeld }
1284a4b5c26bSJason A. Donenfeld #endif
1285a4b5c26bSJason A. Donenfeld 
128678c768e6SJason A. Donenfeld struct entropy_timer_state {
128778c768e6SJason A. Donenfeld 	unsigned long entropy;
128878c768e6SJason A. Donenfeld 	struct timer_list timer;
128978c768e6SJason A. Donenfeld 	unsigned int samples, samples_per_bit;
129078c768e6SJason A. Donenfeld };
129178c768e6SJason A. Donenfeld 
12921da177e4SLinus Torvalds /*
129350ee7529SLinus Torvalds  * Each time the timer fires, we expect that we got an unpredictable
129450ee7529SLinus Torvalds  * jump in the cycle counter. Even if the timer is running on another
129550ee7529SLinus Torvalds  * CPU, the timer activity will be touching the stack of the CPU that is
129650ee7529SLinus Torvalds  * generating entropy..
129750ee7529SLinus Torvalds  *
129850ee7529SLinus Torvalds  * Note that we don't re-arm the timer in the timer itself - we are
129950ee7529SLinus Torvalds  * happy to be scheduled away, since that just makes the load more
130050ee7529SLinus Torvalds  * complex, but we do not want the timer to keep ticking unless the
130150ee7529SLinus Torvalds  * entropy loop is running.
130250ee7529SLinus Torvalds  *
130350ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
130450ee7529SLinus Torvalds  */
130578c768e6SJason A. Donenfeld static void entropy_timer(struct timer_list *timer)
130650ee7529SLinus Torvalds {
130778c768e6SJason A. Donenfeld 	struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
130878c768e6SJason A. Donenfeld 
130978c768e6SJason A. Donenfeld 	if (++state->samples == state->samples_per_bit) {
1310e85c0fc1SJason A. Donenfeld 		credit_init_bits(1);
131178c768e6SJason A. Donenfeld 		state->samples = 0;
131278c768e6SJason A. Donenfeld 	}
131350ee7529SLinus Torvalds }
131450ee7529SLinus Torvalds 
131550ee7529SLinus Torvalds /*
131650ee7529SLinus Torvalds  * If we have an actual cycle counter, see if we can
131750ee7529SLinus Torvalds  * generate enough entropy with timing noise
131850ee7529SLinus Torvalds  */
131950ee7529SLinus Torvalds static void try_to_generate_entropy(void)
132050ee7529SLinus Torvalds {
132178c768e6SJason A. Donenfeld 	enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = 32 };
132278c768e6SJason A. Donenfeld 	struct entropy_timer_state stack;
132378c768e6SJason A. Donenfeld 	unsigned int i, num_different = 0;
132478c768e6SJason A. Donenfeld 	unsigned long last = random_get_entropy();
132550ee7529SLinus Torvalds 
132678c768e6SJason A. Donenfeld 	for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
13274b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
132878c768e6SJason A. Donenfeld 		if (stack.entropy != last)
132978c768e6SJason A. Donenfeld 			++num_different;
133078c768e6SJason A. Donenfeld 		last = stack.entropy;
133178c768e6SJason A. Donenfeld 	}
133278c768e6SJason A. Donenfeld 	stack.samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
133378c768e6SJason A. Donenfeld 	if (stack.samples_per_bit > MAX_SAMPLES_PER_BIT)
133450ee7529SLinus Torvalds 		return;
133550ee7529SLinus Torvalds 
133678c768e6SJason A. Donenfeld 	stack.samples = 0;
133750ee7529SLinus Torvalds 	timer_setup_on_stack(&stack.timer, entropy_timer, 0);
13383e504d20SJason A. Donenfeld 	while (!crng_ready() && !signal_pending(current)) {
133950ee7529SLinus Torvalds 		if (!timer_pending(&stack.timer))
134050ee7529SLinus Torvalds 			mod_timer(&stack.timer, jiffies + 1);
13414b758edaSJason A. Donenfeld 		mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
134250ee7529SLinus Torvalds 		schedule();
13434b758edaSJason A. Donenfeld 		stack.entropy = random_get_entropy();
134450ee7529SLinus Torvalds 	}
134550ee7529SLinus Torvalds 
134650ee7529SLinus Torvalds 	del_timer_sync(&stack.timer);
134750ee7529SLinus Torvalds 	destroy_timer_on_stack(&stack.timer);
13484b758edaSJason A. Donenfeld 	mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
134950ee7529SLinus Torvalds }
135050ee7529SLinus Torvalds 
1351a6adf8e7SJason A. Donenfeld 
1352a6adf8e7SJason A. Donenfeld /**********************************************************************
1353a6adf8e7SJason A. Donenfeld  *
1354a6adf8e7SJason A. Donenfeld  * Userspace reader/writer interfaces.
1355a6adf8e7SJason A. Donenfeld  *
1356a6adf8e7SJason A. Donenfeld  * getrandom(2) is the primary modern interface into the RNG and should
1357a6adf8e7SJason A. Donenfeld  * be used in preference to anything else.
1358a6adf8e7SJason A. Donenfeld  *
13590313bc27SLinus Torvalds  * Reading from /dev/random has the same functionality as calling
13600313bc27SLinus Torvalds  * getrandom(2) with flags=0. In earlier versions, however, it had
13610313bc27SLinus Torvalds  * vastly different semantics and should therefore be avoided, to
13620313bc27SLinus Torvalds  * prevent backwards compatibility issues.
13630313bc27SLinus Torvalds  *
13640313bc27SLinus Torvalds  * Reading from /dev/urandom has the same functionality as calling
13650313bc27SLinus Torvalds  * getrandom(2) with flags=GRND_INSECURE. Because it does not block
13660313bc27SLinus Torvalds  * waiting for the RNG to be ready, it should not be used.
1367a6adf8e7SJason A. Donenfeld  *
1368a6adf8e7SJason A. Donenfeld  * Writing to either /dev/random or /dev/urandom adds entropy to
1369a6adf8e7SJason A. Donenfeld  * the input pool but does not credit it.
1370a6adf8e7SJason A. Donenfeld  *
13710313bc27SLinus Torvalds  * Polling on /dev/random indicates when the RNG is initialized, on
13720313bc27SLinus Torvalds  * the read side, and when it wants new entropy, on the write side.
1373a6adf8e7SJason A. Donenfeld  *
1374a6adf8e7SJason A. Donenfeld  * Both /dev/random and /dev/urandom have the same set of ioctls for
1375a6adf8e7SJason A. Donenfeld  * adding entropy, getting the entropy count, zeroing the count, and
1376a6adf8e7SJason A. Donenfeld  * reseeding the crng.
1377a6adf8e7SJason A. Donenfeld  *
1378a6adf8e7SJason A. Donenfeld  **********************************************************************/
1379a6adf8e7SJason A. Donenfeld 
1380a6adf8e7SJason A. Donenfeld SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int,
1381a6adf8e7SJason A. Donenfeld 		flags)
13821da177e4SLinus Torvalds {
1383a6adf8e7SJason A. Donenfeld 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
1384a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1385301f0595STheodore Ts'o 
1386a6adf8e7SJason A. Donenfeld 	/*
1387a6adf8e7SJason A. Donenfeld 	 * Requesting insecure and blocking randomness at the same time makes
1388a6adf8e7SJason A. Donenfeld 	 * no sense.
1389a6adf8e7SJason A. Donenfeld 	 */
1390a6adf8e7SJason A. Donenfeld 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1391a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1392c6f1deb1SAndy Lutomirski 
1393a6adf8e7SJason A. Donenfeld 	if (count > INT_MAX)
1394a6adf8e7SJason A. Donenfeld 		count = INT_MAX;
13951da177e4SLinus Torvalds 
1396a6adf8e7SJason A. Donenfeld 	if (!(flags & GRND_INSECURE) && !crng_ready()) {
139730c08efeSAndy Lutomirski 		int ret;
139830c08efeSAndy Lutomirski 
1399a6adf8e7SJason A. Donenfeld 		if (flags & GRND_NONBLOCK)
1400a6adf8e7SJason A. Donenfeld 			return -EAGAIN;
140130c08efeSAndy Lutomirski 		ret = wait_for_random_bytes();
1402a6adf8e7SJason A. Donenfeld 		if (unlikely(ret))
140330c08efeSAndy Lutomirski 			return ret;
1404a6adf8e7SJason A. Donenfeld 	}
1405a6adf8e7SJason A. Donenfeld 	return get_random_bytes_user(buf, count);
140630c08efeSAndy Lutomirski }
140730c08efeSAndy Lutomirski 
1408248045b8SJason A. Donenfeld static __poll_t random_poll(struct file *file, poll_table *wait)
140989b310a2SChristoph Hellwig {
141030c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1411e85c0fc1SJason A. Donenfeld 	return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
14121da177e4SLinus Torvalds }
14131da177e4SLinus Torvalds 
141404ec96b7SJason A. Donenfeld static int write_pool(const char __user *ubuf, size_t count)
14157f397dcdSMatt Mackall {
141604ec96b7SJason A. Donenfeld 	size_t len;
14177b5164fbSJason A. Donenfeld 	int ret = 0;
141804ec96b7SJason A. Donenfeld 	u8 block[BLAKE2S_BLOCK_SIZE];
14197f397dcdSMatt Mackall 
142004ec96b7SJason A. Donenfeld 	while (count) {
142104ec96b7SJason A. Donenfeld 		len = min(count, sizeof(block));
14227b5164fbSJason A. Donenfeld 		if (copy_from_user(block, ubuf, len)) {
14237b5164fbSJason A. Donenfeld 			ret = -EFAULT;
14247b5164fbSJason A. Donenfeld 			goto out;
14257b5164fbSJason A. Donenfeld 		}
142604ec96b7SJason A. Donenfeld 		count -= len;
142704ec96b7SJason A. Donenfeld 		ubuf += len;
142804ec96b7SJason A. Donenfeld 		mix_pool_bytes(block, len);
142991f3f1e3SMatt Mackall 		cond_resched();
14307f397dcdSMatt Mackall 	}
14317f397dcdSMatt Mackall 
14327b5164fbSJason A. Donenfeld out:
14337b5164fbSJason A. Donenfeld 	memzero_explicit(block, sizeof(block));
14347b5164fbSJason A. Donenfeld 	return ret;
14357f397dcdSMatt Mackall }
14367f397dcdSMatt Mackall 
143790b75ee5SMatt Mackall static ssize_t random_write(struct file *file, const char __user *buffer,
14381da177e4SLinus Torvalds 			    size_t count, loff_t *ppos)
14391da177e4SLinus Torvalds {
144004ec96b7SJason A. Donenfeld 	int ret;
14417f397dcdSMatt Mackall 
144290ed1e67SJason A. Donenfeld 	ret = write_pool(buffer, count);
14437f397dcdSMatt Mackall 	if (ret)
14447f397dcdSMatt Mackall 		return ret;
14457f397dcdSMatt Mackall 
14467f397dcdSMatt Mackall 	return (ssize_t)count;
14471da177e4SLinus Torvalds }
14481da177e4SLinus Torvalds 
14490313bc27SLinus Torvalds static ssize_t urandom_read(struct file *file, char __user *buf, size_t nbytes,
14500313bc27SLinus Torvalds 			    loff_t *ppos)
14510313bc27SLinus Torvalds {
14520313bc27SLinus Torvalds 	static int maxwarn = 10;
14530313bc27SLinus Torvalds 
145448bff105SJason A. Donenfeld 	/*
145548bff105SJason A. Donenfeld 	 * Opportunistically attempt to initialize the RNG on platforms that
145648bff105SJason A. Donenfeld 	 * have fast cycle counters, but don't (for now) require it to succeed.
145748bff105SJason A. Donenfeld 	 */
145848bff105SJason A. Donenfeld 	if (!crng_ready())
145948bff105SJason A. Donenfeld 		try_to_generate_entropy();
146048bff105SJason A. Donenfeld 
1461cc1e127bSJason A. Donenfeld 	if (!crng_ready()) {
1462cc1e127bSJason A. Donenfeld 		if (!ratelimit_disable && maxwarn <= 0)
1463cc1e127bSJason A. Donenfeld 			++urandom_warning.missed;
1464cc1e127bSJason A. Donenfeld 		else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
1465cc1e127bSJason A. Donenfeld 			--maxwarn;
14660313bc27SLinus Torvalds 			pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
14670313bc27SLinus Torvalds 				  current->comm, nbytes);
14680313bc27SLinus Torvalds 		}
1469cc1e127bSJason A. Donenfeld 	}
14700313bc27SLinus Torvalds 
14710313bc27SLinus Torvalds 	return get_random_bytes_user(buf, nbytes);
14720313bc27SLinus Torvalds }
14730313bc27SLinus Torvalds 
1474a6adf8e7SJason A. Donenfeld static ssize_t random_read(struct file *file, char __user *buf, size_t nbytes,
1475a6adf8e7SJason A. Donenfeld 			   loff_t *ppos)
1476a6adf8e7SJason A. Donenfeld {
1477a6adf8e7SJason A. Donenfeld 	int ret;
1478a6adf8e7SJason A. Donenfeld 
1479a6adf8e7SJason A. Donenfeld 	ret = wait_for_random_bytes();
1480a6adf8e7SJason A. Donenfeld 	if (ret != 0)
1481a6adf8e7SJason A. Donenfeld 		return ret;
1482a6adf8e7SJason A. Donenfeld 	return get_random_bytes_user(buf, nbytes);
1483a6adf8e7SJason A. Donenfeld }
1484a6adf8e7SJason A. Donenfeld 
148543ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
14861da177e4SLinus Torvalds {
14871da177e4SLinus Torvalds 	int size, ent_count;
14881da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
14891da177e4SLinus Torvalds 	int retval;
14901da177e4SLinus Torvalds 
14911da177e4SLinus Torvalds 	switch (cmd) {
14921da177e4SLinus Torvalds 	case RNDGETENTCNT:
1493a6adf8e7SJason A. Donenfeld 		/* Inherently racy, no point locking. */
1494e85c0fc1SJason A. Donenfeld 		if (put_user(input_pool.init_bits, p))
14951da177e4SLinus Torvalds 			return -EFAULT;
14961da177e4SLinus Torvalds 		return 0;
14971da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
14981da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14991da177e4SLinus Torvalds 			return -EPERM;
15001da177e4SLinus Torvalds 		if (get_user(ent_count, p))
15011da177e4SLinus Torvalds 			return -EFAULT;
1502a49c010eSJason A. Donenfeld 		if (ent_count < 0)
1503a49c010eSJason A. Donenfeld 			return -EINVAL;
1504e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1505a49c010eSJason A. Donenfeld 		return 0;
15061da177e4SLinus Torvalds 	case RNDADDENTROPY:
15071da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
15081da177e4SLinus Torvalds 			return -EPERM;
15091da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
15101da177e4SLinus Torvalds 			return -EFAULT;
15111da177e4SLinus Torvalds 		if (ent_count < 0)
15121da177e4SLinus Torvalds 			return -EINVAL;
15131da177e4SLinus Torvalds 		if (get_user(size, p++))
15141da177e4SLinus Torvalds 			return -EFAULT;
151590ed1e67SJason A. Donenfeld 		retval = write_pool((const char __user *)p, size);
15161da177e4SLinus Torvalds 		if (retval < 0)
15171da177e4SLinus Torvalds 			return retval;
1518e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1519a49c010eSJason A. Donenfeld 		return 0;
15201da177e4SLinus Torvalds 	case RNDZAPENTCNT:
15211da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1522e85c0fc1SJason A. Donenfeld 		/* No longer has any effect. */
15231da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
15241da177e4SLinus Torvalds 			return -EPERM;
15251da177e4SLinus Torvalds 		return 0;
1526d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1527d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1528d848e5f8STheodore Ts'o 			return -EPERM;
1529a96cfe2dSJason A. Donenfeld 		if (!crng_ready())
1530d848e5f8STheodore Ts'o 			return -ENODATA;
1531e85c0fc1SJason A. Donenfeld 		crng_reseed();
1532d848e5f8STheodore Ts'o 		return 0;
15331da177e4SLinus Torvalds 	default:
15341da177e4SLinus Torvalds 		return -EINVAL;
15351da177e4SLinus Torvalds 	}
15361da177e4SLinus Torvalds }
15371da177e4SLinus Torvalds 
15389a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
15399a6f70bbSJeff Dike {
15409a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
15419a6f70bbSJeff Dike }
15429a6f70bbSJeff Dike 
15432b8693c0SArjan van de Ven const struct file_operations random_fops = {
15441da177e4SLinus Torvalds 	.read = random_read,
15451da177e4SLinus Torvalds 	.write = random_write,
1546a11e1d43SLinus Torvalds 	.poll = random_poll,
154743ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1548507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
15499a6f70bbSJeff Dike 	.fasync = random_fasync,
15506038f373SArnd Bergmann 	.llseek = noop_llseek,
15511da177e4SLinus Torvalds };
15521da177e4SLinus Torvalds 
15530313bc27SLinus Torvalds const struct file_operations urandom_fops = {
15540313bc27SLinus Torvalds 	.read = urandom_read,
15550313bc27SLinus Torvalds 	.write = random_write,
15560313bc27SLinus Torvalds 	.unlocked_ioctl = random_ioctl,
15570313bc27SLinus Torvalds 	.compat_ioctl = compat_ptr_ioctl,
15580313bc27SLinus Torvalds 	.fasync = random_fasync,
15590313bc27SLinus Torvalds 	.llseek = noop_llseek,
15600313bc27SLinus Torvalds };
15610313bc27SLinus Torvalds 
15620deff3c4SJason A. Donenfeld 
15631da177e4SLinus Torvalds /********************************************************************
15641da177e4SLinus Torvalds  *
15650deff3c4SJason A. Donenfeld  * Sysctl interface.
15660deff3c4SJason A. Donenfeld  *
15670deff3c4SJason A. Donenfeld  * These are partly unused legacy knobs with dummy values to not break
15680deff3c4SJason A. Donenfeld  * userspace and partly still useful things. They are usually accessible
15690deff3c4SJason A. Donenfeld  * in /proc/sys/kernel/random/ and are as follows:
15700deff3c4SJason A. Donenfeld  *
15710deff3c4SJason A. Donenfeld  * - boot_id - a UUID representing the current boot.
15720deff3c4SJason A. Donenfeld  *
15730deff3c4SJason A. Donenfeld  * - uuid - a random UUID, different each time the file is read.
15740deff3c4SJason A. Donenfeld  *
15750deff3c4SJason A. Donenfeld  * - poolsize - the number of bits of entropy that the input pool can
15760deff3c4SJason A. Donenfeld  *   hold, tied to the POOL_BITS constant.
15770deff3c4SJason A. Donenfeld  *
15780deff3c4SJason A. Donenfeld  * - entropy_avail - the number of bits of entropy currently in the
15790deff3c4SJason A. Donenfeld  *   input pool. Always <= poolsize.
15800deff3c4SJason A. Donenfeld  *
15810deff3c4SJason A. Donenfeld  * - write_wakeup_threshold - the amount of entropy in the input pool
15820deff3c4SJason A. Donenfeld  *   below which write polls to /dev/random will unblock, requesting
1583e3d2c5e7SJason A. Donenfeld  *   more entropy, tied to the POOL_READY_BITS constant. It is writable
15840deff3c4SJason A. Donenfeld  *   to avoid breaking old userspaces, but writing to it does not
15850deff3c4SJason A. Donenfeld  *   change any behavior of the RNG.
15860deff3c4SJason A. Donenfeld  *
1587d0efdf35SJason A. Donenfeld  * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
15880deff3c4SJason A. Donenfeld  *   It is writable to avoid breaking old userspaces, but writing
15890deff3c4SJason A. Donenfeld  *   to it does not change any behavior of the RNG.
15901da177e4SLinus Torvalds  *
15911da177e4SLinus Torvalds  ********************************************************************/
15921da177e4SLinus Torvalds 
15931da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
15941da177e4SLinus Torvalds 
15951da177e4SLinus Torvalds #include <linux/sysctl.h>
15961da177e4SLinus Torvalds 
1597d0efdf35SJason A. Donenfeld static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
1598e3d2c5e7SJason A. Donenfeld static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
1599489c7fc4SJason A. Donenfeld static int sysctl_poolsize = POOL_BITS;
160064276a99SJason A. Donenfeld static u8 sysctl_bootid[UUID_SIZE];
16011da177e4SLinus Torvalds 
16021da177e4SLinus Torvalds /*
1603f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
16041da177e4SLinus Torvalds  * UUID. The difference is in whether table->data is NULL; if it is,
16051da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
16061da177e4SLinus Torvalds  */
1607248045b8SJason A. Donenfeld static int proc_do_uuid(struct ctl_table *table, int write, void *buffer,
1608248045b8SJason A. Donenfeld 			size_t *lenp, loff_t *ppos)
16091da177e4SLinus Torvalds {
161064276a99SJason A. Donenfeld 	u8 tmp_uuid[UUID_SIZE], *uuid;
161164276a99SJason A. Donenfeld 	char uuid_string[UUID_STRING_LEN + 1];
161264276a99SJason A. Donenfeld 	struct ctl_table fake_table = {
161364276a99SJason A. Donenfeld 		.data = uuid_string,
161464276a99SJason A. Donenfeld 		.maxlen = UUID_STRING_LEN
161564276a99SJason A. Donenfeld 	};
161664276a99SJason A. Donenfeld 
161764276a99SJason A. Donenfeld 	if (write)
161864276a99SJason A. Donenfeld 		return -EPERM;
16191da177e4SLinus Torvalds 
16201da177e4SLinus Torvalds 	uuid = table->data;
16211da177e4SLinus Torvalds 	if (!uuid) {
16221da177e4SLinus Torvalds 		uuid = tmp_uuid;
16231da177e4SLinus Torvalds 		generate_random_uuid(uuid);
162444e4360fSMathieu Desnoyers 	} else {
162544e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
162644e4360fSMathieu Desnoyers 
162744e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
162844e4360fSMathieu Desnoyers 		if (!uuid[8])
162944e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
163044e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
163144e4360fSMathieu Desnoyers 	}
16321da177e4SLinus Torvalds 
163364276a99SJason A. Donenfeld 	snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
163464276a99SJason A. Donenfeld 	return proc_dostring(&fake_table, 0, buffer, lenp, ppos);
16351da177e4SLinus Torvalds }
16361da177e4SLinus Torvalds 
163777553cf8SJason A. Donenfeld /* The same as proc_dointvec, but writes don't change anything. */
163877553cf8SJason A. Donenfeld static int proc_do_rointvec(struct ctl_table *table, int write, void *buffer,
163977553cf8SJason A. Donenfeld 			    size_t *lenp, loff_t *ppos)
164077553cf8SJason A. Donenfeld {
164177553cf8SJason A. Donenfeld 	return write ? 0 : proc_dointvec(table, 0, buffer, lenp, ppos);
164277553cf8SJason A. Donenfeld }
164377553cf8SJason A. Donenfeld 
16445475e8f0SXiaoming Ni static struct ctl_table random_table[] = {
16451da177e4SLinus Torvalds 	{
16461da177e4SLinus Torvalds 		.procname	= "poolsize",
16471da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
16481da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16491da177e4SLinus Torvalds 		.mode		= 0444,
16506d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
16511da177e4SLinus Torvalds 	},
16521da177e4SLinus Torvalds 	{
16531da177e4SLinus Torvalds 		.procname	= "entropy_avail",
1654e85c0fc1SJason A. Donenfeld 		.data		= &input_pool.init_bits,
16551da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16561da177e4SLinus Torvalds 		.mode		= 0444,
1657c5704490SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
16581da177e4SLinus Torvalds 	},
16591da177e4SLinus Torvalds 	{
16601da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
16610deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_write_wakeup_bits,
16621da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16631da177e4SLinus Torvalds 		.mode		= 0644,
166477553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
16651da177e4SLinus Torvalds 	},
16661da177e4SLinus Torvalds 	{
1667f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
16680deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_min_urandom_seed,
1669f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1670f5c2742cSTheodore Ts'o 		.mode		= 0644,
167177553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
1672f5c2742cSTheodore Ts'o 	},
1673f5c2742cSTheodore Ts'o 	{
16741da177e4SLinus Torvalds 		.procname	= "boot_id",
16751da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
16761da177e4SLinus Torvalds 		.mode		= 0444,
16776d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16781da177e4SLinus Torvalds 	},
16791da177e4SLinus Torvalds 	{
16801da177e4SLinus Torvalds 		.procname	= "uuid",
16811da177e4SLinus Torvalds 		.mode		= 0444,
16826d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16831da177e4SLinus Torvalds 	},
1684894d2491SEric W. Biederman 	{ }
16851da177e4SLinus Torvalds };
16865475e8f0SXiaoming Ni 
16875475e8f0SXiaoming Ni /*
16885475e8f0SXiaoming Ni  * rand_initialize() is called before sysctl_init(),
16895475e8f0SXiaoming Ni  * so we cannot call register_sysctl_init() in rand_initialize()
16905475e8f0SXiaoming Ni  */
16915475e8f0SXiaoming Ni static int __init random_sysctls_init(void)
16925475e8f0SXiaoming Ni {
16935475e8f0SXiaoming Ni 	register_sysctl_init("kernel/random", random_table);
16945475e8f0SXiaoming Ni 	return 0;
16955475e8f0SXiaoming Ni }
16965475e8f0SXiaoming Ni device_initcall(random_sysctls_init);
16970deff3c4SJason A. Donenfeld #endif
1698