xref: /linux/drivers/char/random.c (revision 36ec807b627b4c0a0a382f0ae48eac7187d14b2b)
1a07fdae3SJason A. Donenfeld // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
21da177e4SLinus Torvalds /*
34ad10a5fSJason A. Donenfeld  * Copyright (C) 2017-2024 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>
561c21fe00SJason A. Donenfeld #include <linux/sched/isolation.h>
571ca1b917SEric Biggers #include <crypto/chacha.h>
589f9eff85SJason A. Donenfeld #include <crypto/blake2s.h>
594ad10a5fSJason A. Donenfeld #ifdef CONFIG_VDSO_GETRANDOM
604ad10a5fSJason A. Donenfeld #include <vdso/getrandom.h>
614ad10a5fSJason A. Donenfeld #include <vdso/datapage.h>
624ad10a5fSJason A. Donenfeld #endif
636bb20c15SJason A. Donenfeld #include <asm/archrandom.h>
641da177e4SLinus Torvalds #include <asm/processor.h>
651da177e4SLinus Torvalds #include <asm/irq.h>
66775f4b29STheodore Ts'o #include <asm/irq_regs.h>
671da177e4SLinus Torvalds #include <asm/io.h>
681da177e4SLinus Torvalds 
695f1bb112SJason A. Donenfeld /*********************************************************************
705f1bb112SJason A. Donenfeld  *
715f1bb112SJason A. Donenfeld  * Initialization and readiness waiting.
725f1bb112SJason A. Donenfeld  *
735f1bb112SJason A. Donenfeld  * Much of the RNG infrastructure is devoted to various dependencies
745f1bb112SJason A. Donenfeld  * being able to wait until the RNG has collected enough entropy and
755f1bb112SJason A. Donenfeld  * is ready for safe consumption.
765f1bb112SJason A. Donenfeld  *
775f1bb112SJason A. Donenfeld  *********************************************************************/
785f1bb112SJason A. Donenfeld 
795f1bb112SJason A. Donenfeld /*
805f1bb112SJason A. Donenfeld  * crng_init is protected by base_crng->lock, and only increases
81e3d2c5e7SJason A. Donenfeld  * its value (from empty->early->ready).
825f1bb112SJason A. Donenfeld  */
83e3d2c5e7SJason A. Donenfeld static enum {
84e3d2c5e7SJason A. Donenfeld 	CRNG_EMPTY = 0, /* Little to no entropy collected */
85e3d2c5e7SJason A. Donenfeld 	CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */
86e3d2c5e7SJason A. Donenfeld 	CRNG_READY = 2  /* Fully initialized with POOL_READY_BITS collected */
87f5bda35fSJason A. Donenfeld } crng_init __read_mostly = CRNG_EMPTY;
88f5bda35fSJason A. Donenfeld static DEFINE_STATIC_KEY_FALSE(crng_is_ready);
89f5bda35fSJason A. Donenfeld #define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)
90e3d2c5e7SJason A. Donenfeld /* Various types of waiters for crng_init->CRNG_READY transition. */
915f1bb112SJason A. Donenfeld static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
925f1bb112SJason A. Donenfeld static struct fasync_struct *fasync;
93bbc7e1beSJason A. Donenfeld static ATOMIC_NOTIFIER_HEAD(random_ready_notifier);
945f1bb112SJason A. Donenfeld 
955f1bb112SJason A. Donenfeld /* Control how we warn userspace. */
960313bc27SLinus Torvalds static struct ratelimit_state urandom_warning =
97c01d4d0aSJason A. Donenfeld 	RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);
98cc1e127bSJason A. Donenfeld static int ratelimit_disable __read_mostly =
99cc1e127bSJason A. Donenfeld 	IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
1005f1bb112SJason A. Donenfeld module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
1015f1bb112SJason A. Donenfeld MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
1025f1bb112SJason A. Donenfeld 
1035f1bb112SJason A. Donenfeld /*
1045f1bb112SJason A. Donenfeld  * Returns whether or not the input pool has been seeded and thus guaranteed
1050313bc27SLinus Torvalds  * to supply cryptographically secure random numbers. This applies to: the
106a890d1c6SJason A. Donenfeld  * /dev/urandom device, the get_random_bytes function, and the get_random_{u8,
107de492c83SJason A. Donenfeld  * u16,u32,u64,long} family of functions.
1085f1bb112SJason A. Donenfeld  *
1095f1bb112SJason A. Donenfeld  * Returns: true if the input pool has been seeded.
1105f1bb112SJason A. Donenfeld  *          false if the input pool has not been seeded.
1115f1bb112SJason A. Donenfeld  */
1125f1bb112SJason A. Donenfeld bool rng_is_initialized(void)
1135f1bb112SJason A. Donenfeld {
1145f1bb112SJason A. Donenfeld 	return crng_ready();
1155f1bb112SJason A. Donenfeld }
1165f1bb112SJason A. Donenfeld EXPORT_SYMBOL(rng_is_initialized);
1175f1bb112SJason A. Donenfeld 
118560181c2SJason A. Donenfeld static void __cold crng_set_ready(struct work_struct *work)
119f5bda35fSJason A. Donenfeld {
120f5bda35fSJason A. Donenfeld 	static_branch_enable(&crng_is_ready);
121f5bda35fSJason A. Donenfeld }
122f5bda35fSJason A. Donenfeld 
1235f1bb112SJason A. Donenfeld /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
1245f1bb112SJason A. Donenfeld static void try_to_generate_entropy(void);
1255f1bb112SJason A. Donenfeld 
1265f1bb112SJason A. Donenfeld /*
1275f1bb112SJason A. Donenfeld  * Wait for the input pool to be seeded and thus guaranteed to supply
1280313bc27SLinus Torvalds  * cryptographically secure random numbers. This applies to: the /dev/urandom
129a890d1c6SJason A. Donenfeld  * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64,
130b240bab5SJason A. Donenfeld  * long} family of functions. Using any of these functions without first
131a890d1c6SJason A. Donenfeld  * calling this function forfeits the guarantee of security.
1325f1bb112SJason A. Donenfeld  *
1335f1bb112SJason A. Donenfeld  * Returns: 0 if the input pool has been seeded.
1345f1bb112SJason A. Donenfeld  *          -ERESTARTSYS if the function was interrupted by a signal.
1355f1bb112SJason A. Donenfeld  */
1365f1bb112SJason A. Donenfeld int wait_for_random_bytes(void)
1375f1bb112SJason A. Donenfeld {
138a96cfe2dSJason A. Donenfeld 	while (!crng_ready()) {
1395f1bb112SJason A. Donenfeld 		int ret;
1403e504d20SJason A. Donenfeld 
1413e504d20SJason A. Donenfeld 		try_to_generate_entropy();
1425f1bb112SJason A. Donenfeld 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
1435f1bb112SJason A. Donenfeld 		if (ret)
1445f1bb112SJason A. Donenfeld 			return ret > 0 ? 0 : ret;
145a96cfe2dSJason A. Donenfeld 	}
1465f1bb112SJason A. Donenfeld 	return 0;
1475f1bb112SJason A. Donenfeld }
1485f1bb112SJason A. Donenfeld EXPORT_SYMBOL(wait_for_random_bytes);
1495f1bb112SJason A. Donenfeld 
150bbc7e1beSJason A. Donenfeld /*
151bbc7e1beSJason A. Donenfeld  * Add a callback function that will be invoked when the crng is initialised,
152bbc7e1beSJason A. Donenfeld  * or immediately if it already has been. Only use this is you are absolutely
153bbc7e1beSJason A. Donenfeld  * sure it is required. Most users should instead be able to test
154bbc7e1beSJason A. Donenfeld  * `rng_is_initialized()` on demand, or make use of `get_random_bytes_wait()`.
155bbc7e1beSJason A. Donenfeld  */
156bbc7e1beSJason A. Donenfeld int __cold execute_with_initialized_rng(struct notifier_block *nb)
157bbc7e1beSJason A. Donenfeld {
158bbc7e1beSJason A. Donenfeld 	unsigned long flags;
159bbc7e1beSJason A. Donenfeld 	int ret = 0;
160bbc7e1beSJason A. Donenfeld 
161bbc7e1beSJason A. Donenfeld 	spin_lock_irqsave(&random_ready_notifier.lock, flags);
162bbc7e1beSJason A. Donenfeld 	if (crng_ready())
163bbc7e1beSJason A. Donenfeld 		nb->notifier_call(nb, 0, NULL);
164bbc7e1beSJason A. Donenfeld 	else
165bbc7e1beSJason A. Donenfeld 		ret = raw_notifier_chain_register((struct raw_notifier_head *)&random_ready_notifier.head, nb);
166bbc7e1beSJason A. Donenfeld 	spin_unlock_irqrestore(&random_ready_notifier.lock, flags);
167bbc7e1beSJason A. Donenfeld 	return ret;
168bbc7e1beSJason A. Donenfeld }
169bbc7e1beSJason A. Donenfeld 
170cc1e127bSJason A. Donenfeld #define warn_unseeded_randomness() \
171560181c2SJason A. Donenfeld 	if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \
172560181c2SJason A. Donenfeld 		printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n", \
173560181c2SJason A. Donenfeld 				__func__, (void *)_RET_IP_, crng_init)
1745f1bb112SJason A. Donenfeld 
1755f1bb112SJason A. Donenfeld 
1763655adc7SJason A. Donenfeld /*********************************************************************
1773655adc7SJason A. Donenfeld  *
1783655adc7SJason A. Donenfeld  * Fast key erasure RNG, the "crng".
1793655adc7SJason A. Donenfeld  *
1803655adc7SJason A. Donenfeld  * These functions expand entropy from the entropy extractor into
1813655adc7SJason A. Donenfeld  * long streams for external consumption using the "fast key erasure"
1823655adc7SJason A. Donenfeld  * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
1833655adc7SJason A. Donenfeld  *
1843655adc7SJason A. Donenfeld  * There are a few exported interfaces for use by other drivers:
1853655adc7SJason A. Donenfeld  *
186a1940263SJason A. Donenfeld  *	void get_random_bytes(void *buf, size_t len)
187a890d1c6SJason A. Donenfeld  *	u8 get_random_u8()
188a890d1c6SJason A. Donenfeld  *	u16 get_random_u16()
1893655adc7SJason A. Donenfeld  *	u32 get_random_u32()
190e9a688bcSJason A. Donenfeld  *	u32 get_random_u32_below(u32 ceil)
1917f576b25SJason A. Donenfeld  *	u32 get_random_u32_above(u32 floor)
1927f576b25SJason A. Donenfeld  *	u32 get_random_u32_inclusive(u32 floor, u32 ceil)
1933655adc7SJason A. Donenfeld  *	u64 get_random_u64()
1943655adc7SJason A. Donenfeld  *	unsigned long get_random_long()
1953655adc7SJason A. Donenfeld  *
1963655adc7SJason A. Donenfeld  * These interfaces will return the requested number of random bytes
1970313bc27SLinus Torvalds  * into the given buffer or as a return value. This is equivalent to
198de492c83SJason A. Donenfeld  * a read from /dev/urandom. The u8, u16, u32, u64, long family of
199de492c83SJason A. Donenfeld  * functions may be higher performance for one-off random integers,
200de492c83SJason A. Donenfeld  * because they do a bit of buffering and do not invoke reseeding
201de492c83SJason A. Donenfeld  * until the buffer is emptied.
2023655adc7SJason A. Donenfeld  *
2033655adc7SJason A. Donenfeld  *********************************************************************/
2043655adc7SJason A. Donenfeld 
205e85c0fc1SJason A. Donenfeld enum {
206e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_START_INTERVAL = HZ,
207e85c0fc1SJason A. Donenfeld 	CRNG_RESEED_INTERVAL = 60 * HZ
208e85c0fc1SJason A. Donenfeld };
2093655adc7SJason A. Donenfeld 
2103655adc7SJason A. Donenfeld static struct {
2113655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
2123655adc7SJason A. Donenfeld 	unsigned long generation;
2133655adc7SJason A. Donenfeld 	spinlock_t lock;
2143655adc7SJason A. Donenfeld } base_crng = {
2153655adc7SJason A. Donenfeld 	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
2163655adc7SJason A. Donenfeld };
2173655adc7SJason A. Donenfeld 
2183655adc7SJason A. Donenfeld struct crng {
2193655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2203655adc7SJason A. Donenfeld 	unsigned long generation;
2213655adc7SJason A. Donenfeld 	local_lock_t lock;
2223655adc7SJason A. Donenfeld };
2233655adc7SJason A. Donenfeld 
2243655adc7SJason A. Donenfeld static DEFINE_PER_CPU(struct crng, crngs) = {
2253655adc7SJason A. Donenfeld 	.generation = ULONG_MAX,
2263655adc7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(crngs.lock),
2273655adc7SJason A. Donenfeld };
2283655adc7SJason A. Donenfeld 
2299148de31SJason A. Donenfeld /*
2309148de31SJason A. Donenfeld  * Return the interval until the next reseeding, which is normally
2319148de31SJason A. Donenfeld  * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval
2329148de31SJason A. Donenfeld  * proportional to the uptime.
2339148de31SJason A. Donenfeld  */
2349148de31SJason A. Donenfeld static unsigned int crng_reseed_interval(void)
2359148de31SJason A. Donenfeld {
2369148de31SJason A. Donenfeld 	static bool early_boot = true;
2379148de31SJason A. Donenfeld 
2389148de31SJason A. Donenfeld 	if (unlikely(READ_ONCE(early_boot))) {
2399148de31SJason A. Donenfeld 		time64_t uptime = ktime_get_seconds();
2409148de31SJason A. Donenfeld 		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
2419148de31SJason A. Donenfeld 			WRITE_ONCE(early_boot, false);
2429148de31SJason A. Donenfeld 		else
2439148de31SJason A. Donenfeld 			return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
2449148de31SJason A. Donenfeld 				     (unsigned int)uptime / 2 * HZ);
2459148de31SJason A. Donenfeld 	}
2469148de31SJason A. Donenfeld 	return CRNG_RESEED_INTERVAL;
2479148de31SJason A. Donenfeld }
2489148de31SJason A. Donenfeld 
249e85c0fc1SJason A. Donenfeld /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
250a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len);
2513655adc7SJason A. Donenfeld 
252e85c0fc1SJason A. Donenfeld /* This extracts a new crng key from the input pool. */
2539148de31SJason A. Donenfeld static void crng_reseed(struct work_struct *work)
2543655adc7SJason A. Donenfeld {
2559148de31SJason A. Donenfeld 	static DECLARE_DELAYED_WORK(next_reseed, crng_reseed);
2563655adc7SJason A. Donenfeld 	unsigned long flags;
2573655adc7SJason A. Donenfeld 	unsigned long next_gen;
2583655adc7SJason A. Donenfeld 	u8 key[CHACHA_KEY_SIZE];
2593655adc7SJason A. Donenfeld 
2609148de31SJason A. Donenfeld 	/* Immediately schedule the next reseeding, so that it fires sooner rather than later. */
2619148de31SJason A. Donenfeld 	if (likely(system_unbound_wq))
2629148de31SJason A. Donenfeld 		queue_delayed_work(system_unbound_wq, &next_reseed, crng_reseed_interval());
2639148de31SJason A. Donenfeld 
264e85c0fc1SJason A. Donenfeld 	extract_entropy(key, sizeof(key));
2653655adc7SJason A. Donenfeld 
2663655adc7SJason A. Donenfeld 	/*
2673655adc7SJason A. Donenfeld 	 * We copy the new key into the base_crng, overwriting the old one,
2683655adc7SJason A. Donenfeld 	 * and update the generation counter. We avoid hitting ULONG_MAX,
2693655adc7SJason A. Donenfeld 	 * because the per-cpu crngs are initialized to ULONG_MAX, so this
2703655adc7SJason A. Donenfeld 	 * forces new CPUs that come online to always initialize.
2713655adc7SJason A. Donenfeld 	 */
2723655adc7SJason A. Donenfeld 	spin_lock_irqsave(&base_crng.lock, flags);
2733655adc7SJason A. Donenfeld 	memcpy(base_crng.key, key, sizeof(base_crng.key));
2743655adc7SJason A. Donenfeld 	next_gen = base_crng.generation + 1;
2753655adc7SJason A. Donenfeld 	if (next_gen == ULONG_MAX)
2763655adc7SJason A. Donenfeld 		++next_gen;
2773655adc7SJason A. Donenfeld 	WRITE_ONCE(base_crng.generation, next_gen);
2784ad10a5fSJason A. Donenfeld #ifdef CONFIG_VDSO_GETRANDOM
2794ad10a5fSJason A. Donenfeld 	/* base_crng.generation's invalid value is ULONG_MAX, while
2804ad10a5fSJason A. Donenfeld 	 * _vdso_rng_data.generation's invalid value is 0, so add one to the
2814ad10a5fSJason A. Donenfeld 	 * former to arrive at the latter. Use smp_store_release so that this
2824ad10a5fSJason A. Donenfeld 	 * is ordered with the write above to base_crng.generation. Pairs with
2834ad10a5fSJason A. Donenfeld 	 * the smp_rmb() before the syscall in the vDSO code.
2844ad10a5fSJason A. Donenfeld 	 */
2854ad10a5fSJason A. Donenfeld 	smp_store_release(&_vdso_rng_data.generation, next_gen + 1);
2864ad10a5fSJason A. Donenfeld #endif
287f5bda35fSJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready))
288e3d2c5e7SJason A. Donenfeld 		crng_init = CRNG_READY;
2893655adc7SJason A. Donenfeld 	spin_unlock_irqrestore(&base_crng.lock, flags);
2903655adc7SJason A. Donenfeld 	memzero_explicit(key, sizeof(key));
2913655adc7SJason A. Donenfeld }
2923655adc7SJason A. Donenfeld 
2933655adc7SJason A. Donenfeld /*
2943655adc7SJason A. Donenfeld  * This generates a ChaCha block using the provided key, and then
2957f637be4SJason A. Donenfeld  * immediately overwrites that key with half the block. It returns
2963655adc7SJason A. Donenfeld  * the resultant ChaCha state to the user, along with the second
2973655adc7SJason A. Donenfeld  * half of the block containing 32 bytes of random data that may
2983655adc7SJason A. Donenfeld  * be used; random_data_len may not be greater than 32.
2998717627dSJason A. Donenfeld  *
3008717627dSJason A. Donenfeld  * The returned ChaCha state contains within it a copy of the old
3018717627dSJason A. Donenfeld  * key value, at index 4, so the state should always be zeroed out
3028717627dSJason A. Donenfeld  * immediately after using in order to maintain forward secrecy.
3038717627dSJason A. Donenfeld  * If the state cannot be erased in a timely manner, then it is
3048717627dSJason A. Donenfeld  * safer to set the random_data parameter to &chacha_state[4] so
3058717627dSJason A. Donenfeld  * that this function overwrites it before returning.
3063655adc7SJason A. Donenfeld  */
3073655adc7SJason A. Donenfeld static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
3083655adc7SJason A. Donenfeld 				  u32 chacha_state[CHACHA_STATE_WORDS],
3093655adc7SJason A. Donenfeld 				  u8 *random_data, size_t random_data_len)
3103655adc7SJason A. Donenfeld {
3113655adc7SJason A. Donenfeld 	u8 first_block[CHACHA_BLOCK_SIZE];
3123655adc7SJason A. Donenfeld 
3133655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
3143655adc7SJason A. Donenfeld 
3153655adc7SJason A. Donenfeld 	chacha_init_consts(chacha_state);
3163655adc7SJason A. Donenfeld 	memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
3173655adc7SJason A. Donenfeld 	memset(&chacha_state[12], 0, sizeof(u32) * 4);
3183655adc7SJason A. Donenfeld 	chacha20_block(chacha_state, first_block);
3193655adc7SJason A. Donenfeld 
3203655adc7SJason A. Donenfeld 	memcpy(key, first_block, CHACHA_KEY_SIZE);
3218717627dSJason A. Donenfeld 	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
3223655adc7SJason A. Donenfeld 	memzero_explicit(first_block, sizeof(first_block));
3233655adc7SJason A. Donenfeld }
3243655adc7SJason A. Donenfeld 
3253655adc7SJason A. Donenfeld /*
3263655adc7SJason A. Donenfeld  * This function returns a ChaCha state that you may use for generating
3273655adc7SJason A. Donenfeld  * random data. It also returns up to 32 bytes on its own of random data
3283655adc7SJason A. Donenfeld  * that may be used; random_data_len may not be greater than 32.
3293655adc7SJason A. Donenfeld  */
3303655adc7SJason A. Donenfeld static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
3313655adc7SJason A. Donenfeld 			    u8 *random_data, size_t random_data_len)
3323655adc7SJason A. Donenfeld {
3333655adc7SJason A. Donenfeld 	unsigned long flags;
3343655adc7SJason A. Donenfeld 	struct crng *crng;
3353655adc7SJason A. Donenfeld 
3363655adc7SJason A. Donenfeld 	BUG_ON(random_data_len > 32);
3373655adc7SJason A. Donenfeld 
3383655adc7SJason A. Donenfeld 	/*
3393655adc7SJason A. Donenfeld 	 * For the fast path, we check whether we're ready, unlocked first, and
3403655adc7SJason A. Donenfeld 	 * then re-check once locked later. In the case where we're really not
3415c3b747eSJason A. Donenfeld 	 * ready, we do fast key erasure with the base_crng directly, extracting
342e3d2c5e7SJason A. Donenfeld 	 * when crng_init is CRNG_EMPTY.
3433655adc7SJason A. Donenfeld 	 */
344a96cfe2dSJason A. Donenfeld 	if (!crng_ready()) {
3453655adc7SJason A. Donenfeld 		bool ready;
3463655adc7SJason A. Donenfeld 
3473655adc7SJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
3483655adc7SJason A. Donenfeld 		ready = crng_ready();
3495c3b747eSJason A. Donenfeld 		if (!ready) {
350e3d2c5e7SJason A. Donenfeld 			if (crng_init == CRNG_EMPTY)
3515c3b747eSJason A. Donenfeld 				extract_entropy(base_crng.key, sizeof(base_crng.key));
3523655adc7SJason A. Donenfeld 			crng_fast_key_erasure(base_crng.key, chacha_state,
3533655adc7SJason A. Donenfeld 					      random_data, random_data_len);
3545c3b747eSJason A. Donenfeld 		}
3553655adc7SJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
3563655adc7SJason A. Donenfeld 		if (!ready)
3573655adc7SJason A. Donenfeld 			return;
3583655adc7SJason A. Donenfeld 	}
3593655adc7SJason A. Donenfeld 
3603655adc7SJason A. Donenfeld 	local_lock_irqsave(&crngs.lock, flags);
3613655adc7SJason A. Donenfeld 	crng = raw_cpu_ptr(&crngs);
3623655adc7SJason A. Donenfeld 
3633655adc7SJason A. Donenfeld 	/*
3643655adc7SJason A. Donenfeld 	 * If our per-cpu crng is older than the base_crng, then it means
3653655adc7SJason A. Donenfeld 	 * somebody reseeded the base_crng. In that case, we do fast key
3663655adc7SJason A. Donenfeld 	 * erasure on the base_crng, and use its output as the new key
3673655adc7SJason A. Donenfeld 	 * for our per-cpu crng. This brings us up to date with base_crng.
3683655adc7SJason A. Donenfeld 	 */
3693655adc7SJason A. Donenfeld 	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
3703655adc7SJason A. Donenfeld 		spin_lock(&base_crng.lock);
3713655adc7SJason A. Donenfeld 		crng_fast_key_erasure(base_crng.key, chacha_state,
3723655adc7SJason A. Donenfeld 				      crng->key, sizeof(crng->key));
3733655adc7SJason A. Donenfeld 		crng->generation = base_crng.generation;
3743655adc7SJason A. Donenfeld 		spin_unlock(&base_crng.lock);
3753655adc7SJason A. Donenfeld 	}
3763655adc7SJason A. Donenfeld 
3773655adc7SJason A. Donenfeld 	/*
3783655adc7SJason A. Donenfeld 	 * Finally, when we've made it this far, our per-cpu crng has an up
3793655adc7SJason A. Donenfeld 	 * to date key, and we can do fast key erasure with it to produce
3803655adc7SJason A. Donenfeld 	 * some random data and a ChaCha state for the caller. All other
3813655adc7SJason A. Donenfeld 	 * branches of this function are "unlikely", so most of the time we
3823655adc7SJason A. Donenfeld 	 * should wind up here immediately.
3833655adc7SJason A. Donenfeld 	 */
3843655adc7SJason A. Donenfeld 	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
3853655adc7SJason A. Donenfeld 	local_unlock_irqrestore(&crngs.lock, flags);
3863655adc7SJason A. Donenfeld }
3873655adc7SJason A. Donenfeld 
388a1940263SJason A. Donenfeld static void _get_random_bytes(void *buf, size_t len)
3893655adc7SJason A. Donenfeld {
3903655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
3913655adc7SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE];
392a1940263SJason A. Donenfeld 	size_t first_block_len;
3933655adc7SJason A. Donenfeld 
394a1940263SJason A. Donenfeld 	if (!len)
3953655adc7SJason A. Donenfeld 		return;
3963655adc7SJason A. Donenfeld 
397a1940263SJason A. Donenfeld 	first_block_len = min_t(size_t, 32, len);
398a1940263SJason A. Donenfeld 	crng_make_state(chacha_state, buf, first_block_len);
399a1940263SJason A. Donenfeld 	len -= first_block_len;
400a1940263SJason A. Donenfeld 	buf += first_block_len;
4013655adc7SJason A. Donenfeld 
402a1940263SJason A. Donenfeld 	while (len) {
403a1940263SJason A. Donenfeld 		if (len < CHACHA_BLOCK_SIZE) {
4043655adc7SJason A. Donenfeld 			chacha20_block(chacha_state, tmp);
405a1940263SJason A. Donenfeld 			memcpy(buf, tmp, len);
4063655adc7SJason A. Donenfeld 			memzero_explicit(tmp, sizeof(tmp));
4073655adc7SJason A. Donenfeld 			break;
4083655adc7SJason A. Donenfeld 		}
4093655adc7SJason A. Donenfeld 
4103655adc7SJason A. Donenfeld 		chacha20_block(chacha_state, buf);
4113655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4123655adc7SJason A. Donenfeld 			++chacha_state[13];
413a1940263SJason A. Donenfeld 		len -= CHACHA_BLOCK_SIZE;
4143655adc7SJason A. Donenfeld 		buf += CHACHA_BLOCK_SIZE;
4153655adc7SJason A. Donenfeld 	}
4163655adc7SJason A. Donenfeld 
4173655adc7SJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
4183655adc7SJason A. Donenfeld }
4193655adc7SJason A. Donenfeld 
4203655adc7SJason A. Donenfeld /*
42119258d05SJason A. Donenfeld  * This returns random bytes in arbitrary quantities. The quality of the
42219258d05SJason A. Donenfeld  * random bytes is good as /dev/urandom. In order to ensure that the
42319258d05SJason A. Donenfeld  * randomness provided by this function is okay, the function
42419258d05SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once
42519258d05SJason A. Donenfeld  * at any point prior.
4263655adc7SJason A. Donenfeld  */
427a1940263SJason A. Donenfeld void get_random_bytes(void *buf, size_t len)
4283655adc7SJason A. Donenfeld {
429cc1e127bSJason A. Donenfeld 	warn_unseeded_randomness();
430a1940263SJason A. Donenfeld 	_get_random_bytes(buf, len);
4313655adc7SJason A. Donenfeld }
4323655adc7SJason A. Donenfeld EXPORT_SYMBOL(get_random_bytes);
4333655adc7SJason A. Donenfeld 
4341b388e77SJens Axboe static ssize_t get_random_bytes_user(struct iov_iter *iter)
4353655adc7SJason A. Donenfeld {
4363655adc7SJason A. Donenfeld 	u32 chacha_state[CHACHA_STATE_WORDS];
4371b388e77SJens Axboe 	u8 block[CHACHA_BLOCK_SIZE];
4381b388e77SJens Axboe 	size_t ret = 0, copied;
4393655adc7SJason A. Donenfeld 
4401b388e77SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
4413655adc7SJason A. Donenfeld 		return 0;
4423655adc7SJason A. Donenfeld 
443aba120ccSJason A. Donenfeld 	/*
444aba120ccSJason A. Donenfeld 	 * Immediately overwrite the ChaCha key at index 4 with random
44563b8ea5eSJason A. Donenfeld 	 * bytes, in case userspace causes copy_to_iter() below to sleep
446aba120ccSJason A. Donenfeld 	 * forever, so that we still retain forward secrecy in that case.
447aba120ccSJason A. Donenfeld 	 */
448aba120ccSJason A. Donenfeld 	crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
449aba120ccSJason A. Donenfeld 	/*
450aba120ccSJason A. Donenfeld 	 * However, if we're doing a read of len <= 32, we don't need to
451aba120ccSJason A. Donenfeld 	 * use chacha_state after, so we can simply return those bytes to
452aba120ccSJason A. Donenfeld 	 * the user directly.
453aba120ccSJason A. Donenfeld 	 */
4541b388e77SJens Axboe 	if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
4551b388e77SJens Axboe 		ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
456aba120ccSJason A. Donenfeld 		goto out_zero_chacha;
457aba120ccSJason A. Donenfeld 	}
4583655adc7SJason A. Donenfeld 
4595209aed5SJason A. Donenfeld 	for (;;) {
4601b388e77SJens Axboe 		chacha20_block(chacha_state, block);
4613655adc7SJason A. Donenfeld 		if (unlikely(chacha_state[12] == 0))
4623655adc7SJason A. Donenfeld 			++chacha_state[13];
4633655adc7SJason A. Donenfeld 
4641b388e77SJens Axboe 		copied = copy_to_iter(block, sizeof(block), iter);
4651b388e77SJens Axboe 		ret += copied;
4661b388e77SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
4675209aed5SJason A. Donenfeld 			break;
468e3c1c4fdSJason A. Donenfeld 
4691b388e77SJens Axboe 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
4705209aed5SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
471e3c1c4fdSJason A. Donenfeld 			if (signal_pending(current))
472e3c1c4fdSJason A. Donenfeld 				break;
473e3c1c4fdSJason A. Donenfeld 			cond_resched();
474e3c1c4fdSJason A. Donenfeld 		}
4755209aed5SJason A. Donenfeld 	}
4763655adc7SJason A. Donenfeld 
4771b388e77SJens Axboe 	memzero_explicit(block, sizeof(block));
478aba120ccSJason A. Donenfeld out_zero_chacha:
479aba120ccSJason A. Donenfeld 	memzero_explicit(chacha_state, sizeof(chacha_state));
4805209aed5SJason A. Donenfeld 	return ret ? ret : -EFAULT;
4813655adc7SJason A. Donenfeld }
4823655adc7SJason A. Donenfeld 
4833655adc7SJason A. Donenfeld /*
4843655adc7SJason A. Donenfeld  * Batched entropy returns random integers. The quality of the random
4853655adc7SJason A. Donenfeld  * number is good as /dev/urandom. In order to ensure that the randomness
4863655adc7SJason A. Donenfeld  * provided by this function is okay, the function wait_for_random_bytes()
4873655adc7SJason A. Donenfeld  * should be called and return 0 at least once at any point prior.
4883655adc7SJason A. Donenfeld  */
4893655adc7SJason A. Donenfeld 
4903092adceSJason A. Donenfeld #define DEFINE_BATCHED_ENTROPY(type)						\
4913092adceSJason A. Donenfeld struct batch_ ##type {								\
4923092adceSJason A. Donenfeld 	/*									\
4933092adceSJason A. Donenfeld 	 * We make this 1.5x a ChaCha block, so that we get the			\
4943092adceSJason A. Donenfeld 	 * remaining 32 bytes from fast key erasure, plus one full		\
4953092adceSJason A. Donenfeld 	 * block from the detached ChaCha state. We can increase		\
4963092adceSJason A. Donenfeld 	 * the size of this later if needed so long as we keep the		\
4973092adceSJason A. Donenfeld 	 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.		\
4983092adceSJason A. Donenfeld 	 */									\
4993092adceSJason A. Donenfeld 	type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))];		\
5003092adceSJason A. Donenfeld 	local_lock_t lock;							\
5013092adceSJason A. Donenfeld 	unsigned long generation;						\
5023092adceSJason A. Donenfeld 	unsigned int position;							\
5033092adceSJason A. Donenfeld };										\
5043092adceSJason A. Donenfeld 										\
5053092adceSJason A. Donenfeld static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = {	\
5063092adceSJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock),			\
5073092adceSJason A. Donenfeld 	.position = UINT_MAX							\
5083092adceSJason A. Donenfeld };										\
5093092adceSJason A. Donenfeld 										\
5103092adceSJason A. Donenfeld type get_random_ ##type(void)							\
5113092adceSJason A. Donenfeld {										\
5123092adceSJason A. Donenfeld 	type ret;								\
5133092adceSJason A. Donenfeld 	unsigned long flags;							\
5143092adceSJason A. Donenfeld 	struct batch_ ##type *batch;						\
5153092adceSJason A. Donenfeld 	unsigned long next_gen;							\
5163092adceSJason A. Donenfeld 										\
5173092adceSJason A. Donenfeld 	warn_unseeded_randomness();						\
5183092adceSJason A. Donenfeld 										\
5193092adceSJason A. Donenfeld 	if  (!crng_ready()) {							\
5203092adceSJason A. Donenfeld 		_get_random_bytes(&ret, sizeof(ret));				\
5213092adceSJason A. Donenfeld 		return ret;							\
5223092adceSJason A. Donenfeld 	}									\
5233092adceSJason A. Donenfeld 										\
5243092adceSJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_ ##type.lock, flags);		\
5253092adceSJason A. Donenfeld 	batch = raw_cpu_ptr(&batched_entropy_##type);				\
5263092adceSJason A. Donenfeld 										\
5273092adceSJason A. Donenfeld 	next_gen = READ_ONCE(base_crng.generation);				\
5283092adceSJason A. Donenfeld 	if (batch->position >= ARRAY_SIZE(batch->entropy) ||			\
5293092adceSJason A. Donenfeld 	    next_gen != batch->generation) {					\
5303092adceSJason A. Donenfeld 		_get_random_bytes(batch->entropy, sizeof(batch->entropy));	\
5313092adceSJason A. Donenfeld 		batch->position = 0;						\
5323092adceSJason A. Donenfeld 		batch->generation = next_gen;					\
5333092adceSJason A. Donenfeld 	}									\
5343092adceSJason A. Donenfeld 										\
5353092adceSJason A. Donenfeld 	ret = batch->entropy[batch->position];					\
5363092adceSJason A. Donenfeld 	batch->entropy[batch->position] = 0;					\
5373092adceSJason A. Donenfeld 	++batch->position;							\
5383092adceSJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags);		\
5393092adceSJason A. Donenfeld 	return ret;								\
5403092adceSJason A. Donenfeld }										\
5413092adceSJason A. Donenfeld EXPORT_SYMBOL(get_random_ ##type);
5423655adc7SJason A. Donenfeld 
543585cd5feSJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u8)
544a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u16)
545a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u32)
546a890d1c6SJason A. Donenfeld DEFINE_BATCHED_ENTROPY(u64)
5473655adc7SJason A. Donenfeld 
548e9a688bcSJason A. Donenfeld u32 __get_random_u32_below(u32 ceil)
549e9a688bcSJason A. Donenfeld {
550e9a688bcSJason A. Donenfeld 	/*
551e9a688bcSJason A. Donenfeld 	 * This is the slow path for variable ceil. It is still fast, most of
552e9a688bcSJason A. Donenfeld 	 * the time, by doing traditional reciprocal multiplication and
553e9a688bcSJason A. Donenfeld 	 * opportunistically comparing the lower half to ceil itself, before
554e9a688bcSJason A. Donenfeld 	 * falling back to computing a larger bound, and then rejecting samples
555e9a688bcSJason A. Donenfeld 	 * whose lower half would indicate a range indivisible by ceil. The use
556e9a688bcSJason A. Donenfeld 	 * of `-ceil % ceil` is analogous to `2^32 % ceil`, but is computable
557e9a688bcSJason A. Donenfeld 	 * in 32-bits.
558e9a688bcSJason A. Donenfeld 	 */
5597f576b25SJason A. Donenfeld 	u32 rand = get_random_u32();
5607f576b25SJason A. Donenfeld 	u64 mult;
5617f576b25SJason A. Donenfeld 
5627f576b25SJason A. Donenfeld 	/*
5637f576b25SJason A. Donenfeld 	 * This function is technically undefined for ceil == 0, and in fact
5647f576b25SJason A. Donenfeld 	 * for the non-underscored constant version in the header, we build bug
5657f576b25SJason A. Donenfeld 	 * on that. But for the non-constant case, it's convenient to have that
5667f576b25SJason A. Donenfeld 	 * evaluate to being a straight call to get_random_u32(), so that
5677f576b25SJason A. Donenfeld 	 * get_random_u32_inclusive() can work over its whole range without
5687f576b25SJason A. Donenfeld 	 * undefined behavior.
5697f576b25SJason A. Donenfeld 	 */
5707f576b25SJason A. Donenfeld 	if (unlikely(!ceil))
5717f576b25SJason A. Donenfeld 		return rand;
5727f576b25SJason A. Donenfeld 
5737f576b25SJason A. Donenfeld 	mult = (u64)ceil * rand;
574e9a688bcSJason A. Donenfeld 	if (unlikely((u32)mult < ceil)) {
575e9a688bcSJason A. Donenfeld 		u32 bound = -ceil % ceil;
576e9a688bcSJason A. Donenfeld 		while (unlikely((u32)mult < bound))
577e9a688bcSJason A. Donenfeld 			mult = (u64)ceil * get_random_u32();
578e9a688bcSJason A. Donenfeld 	}
579e9a688bcSJason A. Donenfeld 	return mult >> 32;
580e9a688bcSJason A. Donenfeld }
581e9a688bcSJason A. Donenfeld EXPORT_SYMBOL(__get_random_u32_below);
582e9a688bcSJason A. Donenfeld 
5833191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
5843191dd5aSJason A. Donenfeld /*
5853191dd5aSJason A. Donenfeld  * This function is called when the CPU is coming up, with entry
5863191dd5aSJason A. Donenfeld  * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
5873191dd5aSJason A. Donenfeld  */
588560181c2SJason A. Donenfeld int __cold random_prepare_cpu(unsigned int cpu)
5893191dd5aSJason A. Donenfeld {
5903191dd5aSJason A. Donenfeld 	/*
5913191dd5aSJason A. Donenfeld 	 * When the cpu comes back online, immediately invalidate both
5923191dd5aSJason A. Donenfeld 	 * the per-cpu crng and all batches, so that we serve fresh
5933191dd5aSJason A. Donenfeld 	 * randomness.
5943191dd5aSJason A. Donenfeld 	 */
5953191dd5aSJason A. Donenfeld 	per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
596a890d1c6SJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u8, cpu)->position = UINT_MAX;
597a890d1c6SJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u16, cpu)->position = UINT_MAX;
5983191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
5993191dd5aSJason A. Donenfeld 	per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
6003191dd5aSJason A. Donenfeld 	return 0;
6013191dd5aSJason A. Donenfeld }
6023191dd5aSJason A. Donenfeld #endif
6033191dd5aSJason A. Donenfeld 
604a5ed7cb1SJason A. Donenfeld 
605a5ed7cb1SJason A. Donenfeld /**********************************************************************
606a5ed7cb1SJason A. Donenfeld  *
607a5ed7cb1SJason A. Donenfeld  * Entropy accumulation and extraction routines.
608a5ed7cb1SJason A. Donenfeld  *
609a5ed7cb1SJason A. Donenfeld  * Callers may add entropy via:
610a5ed7cb1SJason A. Donenfeld  *
611a1940263SJason A. Donenfeld  *     static void mix_pool_bytes(const void *buf, size_t len)
612a5ed7cb1SJason A. Donenfeld  *
613a5ed7cb1SJason A. Donenfeld  * After which, if added entropy should be credited:
614a5ed7cb1SJason A. Donenfeld  *
615a1940263SJason A. Donenfeld  *     static void credit_init_bits(size_t bits)
616a5ed7cb1SJason A. Donenfeld  *
617e85c0fc1SJason A. Donenfeld  * Finally, extract entropy via:
618a5ed7cb1SJason A. Donenfeld  *
619a1940263SJason A. Donenfeld  *     static void extract_entropy(void *buf, size_t len)
620a5ed7cb1SJason A. Donenfeld  *
621a5ed7cb1SJason A. Donenfeld  **********************************************************************/
622a5ed7cb1SJason A. Donenfeld 
623c5704490SJason A. Donenfeld enum {
6246e8ec255SJason A. Donenfeld 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
625e3d2c5e7SJason A. Donenfeld 	POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
626e3d2c5e7SJason A. Donenfeld 	POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
6271da177e4SLinus Torvalds };
6281da177e4SLinus Torvalds 
62990ed1e67SJason A. Donenfeld static struct {
6306e8ec255SJason A. Donenfeld 	struct blake2s_state hash;
63143358209SMatt Mackall 	spinlock_t lock;
632e85c0fc1SJason A. Donenfeld 	unsigned int init_bits;
63390ed1e67SJason A. Donenfeld } input_pool = {
6346e8ec255SJason A. Donenfeld 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
6356e8ec255SJason A. Donenfeld 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
6366e8ec255SJason A. Donenfeld 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
6376e8ec255SJason A. Donenfeld 	.hash.outlen = BLAKE2S_HASH_SIZE,
638eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
6391da177e4SLinus Torvalds };
6401da177e4SLinus Torvalds 
641a1940263SJason A. Donenfeld static void _mix_pool_bytes(const void *buf, size_t len)
642a5ed7cb1SJason A. Donenfeld {
643a1940263SJason A. Donenfeld 	blake2s_update(&input_pool.hash, buf, len);
644a5ed7cb1SJason A. Donenfeld }
64590ed1e67SJason A. Donenfeld 
6461da177e4SLinus Torvalds /*
647e85c0fc1SJason A. Donenfeld  * This function adds bytes into the input pool. It does not
648e85c0fc1SJason A. Donenfeld  * update the initialization bit counter; the caller should call
649e85c0fc1SJason A. Donenfeld  * credit_init_bits if this is appropriate.
6501da177e4SLinus Torvalds  */
651a1940263SJason A. Donenfeld static void mix_pool_bytes(const void *buf, size_t len)
6521da177e4SLinus Torvalds {
653902c098aSTheodore Ts'o 	unsigned long flags;
654902c098aSTheodore Ts'o 
65590ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
656a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
65790ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
6581da177e4SLinus Torvalds }
6591da177e4SLinus Torvalds 
660a5ed7cb1SJason A. Donenfeld /*
661a5ed7cb1SJason A. Donenfeld  * This is an HKDF-like construction for using the hashed collected entropy
662a5ed7cb1SJason A. Donenfeld  * as a PRF key, that's then expanded block-by-block.
663a5ed7cb1SJason A. Donenfeld  */
664a1940263SJason A. Donenfeld static void extract_entropy(void *buf, size_t len)
665a5ed7cb1SJason A. Donenfeld {
666a5ed7cb1SJason A. Donenfeld 	unsigned long flags;
667a5ed7cb1SJason A. Donenfeld 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
668a5ed7cb1SJason A. Donenfeld 	struct {
669a5ed7cb1SJason A. Donenfeld 		unsigned long rdseed[32 / sizeof(long)];
670a5ed7cb1SJason A. Donenfeld 		size_t counter;
671a5ed7cb1SJason A. Donenfeld 	} block;
672d349ab99SJason A. Donenfeld 	size_t i, longs;
673a5ed7cb1SJason A. Donenfeld 
674d349ab99SJason A. Donenfeld 	for (i = 0; i < ARRAY_SIZE(block.rdseed);) {
675d349ab99SJason A. Donenfeld 		longs = arch_get_random_seed_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
676d349ab99SJason A. Donenfeld 		if (longs) {
677d349ab99SJason A. Donenfeld 			i += longs;
678d349ab99SJason A. Donenfeld 			continue;
679d349ab99SJason A. Donenfeld 		}
680d349ab99SJason A. Donenfeld 		longs = arch_get_random_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
681d349ab99SJason A. Donenfeld 		if (longs) {
682d349ab99SJason A. Donenfeld 			i += longs;
683d349ab99SJason A. Donenfeld 			continue;
684d349ab99SJason A. Donenfeld 		}
685d349ab99SJason A. Donenfeld 		block.rdseed[i++] = random_get_entropy();
686a5ed7cb1SJason A. Donenfeld 	}
687a5ed7cb1SJason A. Donenfeld 
688a5ed7cb1SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
689a5ed7cb1SJason A. Donenfeld 
690a5ed7cb1SJason A. Donenfeld 	/* seed = HASHPRF(last_key, entropy_input) */
691a5ed7cb1SJason A. Donenfeld 	blake2s_final(&input_pool.hash, seed);
692a5ed7cb1SJason A. Donenfeld 
693a5ed7cb1SJason A. Donenfeld 	/* next_key = HASHPRF(seed, RDSEED || 0) */
694a5ed7cb1SJason A. Donenfeld 	block.counter = 0;
695a5ed7cb1SJason A. Donenfeld 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
696a5ed7cb1SJason A. Donenfeld 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
697a5ed7cb1SJason A. Donenfeld 
698a5ed7cb1SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
699a5ed7cb1SJason A. Donenfeld 	memzero_explicit(next_key, sizeof(next_key));
700a5ed7cb1SJason A. Donenfeld 
701a1940263SJason A. Donenfeld 	while (len) {
702a1940263SJason A. Donenfeld 		i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
703a5ed7cb1SJason A. Donenfeld 		/* output = HASHPRF(seed, RDSEED || ++counter) */
704a5ed7cb1SJason A. Donenfeld 		++block.counter;
705a5ed7cb1SJason A. Donenfeld 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
706a1940263SJason A. Donenfeld 		len -= i;
707a5ed7cb1SJason A. Donenfeld 		buf += i;
708a5ed7cb1SJason A. Donenfeld 	}
709a5ed7cb1SJason A. Donenfeld 
710a5ed7cb1SJason A. Donenfeld 	memzero_explicit(seed, sizeof(seed));
711a5ed7cb1SJason A. Donenfeld 	memzero_explicit(&block, sizeof(block));
712a5ed7cb1SJason A. Donenfeld }
713a5ed7cb1SJason A. Donenfeld 
714560181c2SJason A. Donenfeld #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
715560181c2SJason A. Donenfeld 
716560181c2SJason A. Donenfeld static void __cold _credit_init_bits(size_t bits)
717a5ed7cb1SJason A. Donenfeld {
718e871abcdSJason A. Donenfeld 	static DECLARE_WORK(set_ready, crng_set_ready);
719fed7ef06SJason A. Donenfeld 	unsigned int new, orig, add;
7205c3b747eSJason A. Donenfeld 	unsigned long flags;
7215c3b747eSJason A. Donenfeld 
722560181c2SJason A. Donenfeld 	if (!bits)
7235c3b747eSJason A. Donenfeld 		return;
7245c3b747eSJason A. Donenfeld 
725a1940263SJason A. Donenfeld 	add = min_t(size_t, bits, POOL_BITS);
7265c3b747eSJason A. Donenfeld 
727e85c0fc1SJason A. Donenfeld 	orig = READ_ONCE(input_pool.init_bits);
728b7a68f67SUros Bizjak 	do {
729fed7ef06SJason A. Donenfeld 		new = min_t(unsigned int, POOL_BITS, orig + add);
730b7a68f67SUros Bizjak 	} while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
7315c3b747eSJason A. Donenfeld 
73268c9c8b1SJason A. Donenfeld 	if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
7339148de31SJason A. Donenfeld 		crng_reseed(NULL); /* Sets crng_init to CRNG_READY under base_crng.lock. */
734e871abcdSJason A. Donenfeld 		if (static_key_initialized && system_unbound_wq)
735e871abcdSJason A. Donenfeld 			queue_work(system_unbound_wq, &set_ready);
736bbc7e1beSJason A. Donenfeld 		atomic_notifier_call_chain(&random_ready_notifier, 0, NULL);
7374ad10a5fSJason A. Donenfeld #ifdef CONFIG_VDSO_GETRANDOM
7384ad10a5fSJason A. Donenfeld 		WRITE_ONCE(_vdso_rng_data.is_ready, true);
7394ad10a5fSJason A. Donenfeld #endif
74068c9c8b1SJason A. Donenfeld 		wake_up_interruptible(&crng_init_wait);
74168c9c8b1SJason A. Donenfeld 		kill_fasync(&fasync, SIGIO, POLL_IN);
74268c9c8b1SJason A. Donenfeld 		pr_notice("crng init done\n");
743cc1e127bSJason A. Donenfeld 		if (urandom_warning.missed)
74468c9c8b1SJason A. Donenfeld 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
74568c9c8b1SJason A. Donenfeld 				  urandom_warning.missed);
74668c9c8b1SJason A. Donenfeld 	} else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
7475c3b747eSJason A. Donenfeld 		spin_lock_irqsave(&base_crng.lock, flags);
74868c9c8b1SJason A. Donenfeld 		/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
749e3d2c5e7SJason A. Donenfeld 		if (crng_init == CRNG_EMPTY) {
7505c3b747eSJason A. Donenfeld 			extract_entropy(base_crng.key, sizeof(base_crng.key));
751e3d2c5e7SJason A. Donenfeld 			crng_init = CRNG_EARLY;
7525c3b747eSJason A. Donenfeld 		}
7535c3b747eSJason A. Donenfeld 		spin_unlock_irqrestore(&base_crng.lock, flags);
7545c3b747eSJason A. Donenfeld 	}
7555c3b747eSJason A. Donenfeld }
7565c3b747eSJason A. Donenfeld 
75792c653cfSJason A. Donenfeld 
75892c653cfSJason A. Donenfeld /**********************************************************************
75992c653cfSJason A. Donenfeld  *
76092c653cfSJason A. Donenfeld  * Entropy collection routines.
76192c653cfSJason A. Donenfeld  *
76292c653cfSJason A. Donenfeld  * The following exported functions are used for pushing entropy into
76392c653cfSJason A. Donenfeld  * the above entropy accumulation routines:
76492c653cfSJason A. Donenfeld  *
765a1940263SJason A. Donenfeld  *	void add_device_randomness(const void *buf, size_t len);
766db516da9SJason A. Donenfeld  *	void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after);
767a1940263SJason A. Donenfeld  *	void add_bootloader_randomness(const void *buf, size_t len);
768a1940263SJason A. Donenfeld  *	void add_vmfork_randomness(const void *unique_vm_id, size_t len);
76992c653cfSJason A. Donenfeld  *	void add_interrupt_randomness(int irq);
770a1940263SJason A. Donenfeld  *	void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
771a4b5c26bSJason A. Donenfeld  *	void add_disk_randomness(struct gendisk *disk);
77292c653cfSJason A. Donenfeld  *
77392c653cfSJason A. Donenfeld  * add_device_randomness() adds data to the input pool that
77492c653cfSJason A. Donenfeld  * is likely to differ between two devices (or possibly even per boot).
77592c653cfSJason A. Donenfeld  * This would be things like MAC addresses or serial numbers, or the
77692c653cfSJason A. Donenfeld  * read-out of the RTC. This does *not* credit any actual entropy to
77792c653cfSJason A. Donenfeld  * the pool, but it initializes the pool to different values for devices
77892c653cfSJason A. Donenfeld  * that might otherwise be identical and have very little entropy
77992c653cfSJason A. Donenfeld  * available to them (particularly common in the embedded world).
78092c653cfSJason A. Donenfeld  *
78192c653cfSJason A. Donenfeld  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
78292c653cfSJason A. Donenfeld  * entropy as specified by the caller. If the entropy pool is full it will
78392c653cfSJason A. Donenfeld  * block until more entropy is needed.
78492c653cfSJason A. Donenfeld  *
7855c3b747eSJason A. Donenfeld  * add_bootloader_randomness() is called by bootloader drivers, such as EFI
7865c3b747eSJason A. Donenfeld  * and device tree, and credits its input depending on whether or not the
787b9b01a56SJason A. Donenfeld  * command line option 'random.trust_bootloader'.
78892c653cfSJason A. Donenfeld  *
789ae099e8eSJason A. Donenfeld  * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
790ae099e8eSJason A. Donenfeld  * representing the current instance of a VM to the pool, without crediting,
791ae099e8eSJason A. Donenfeld  * and then force-reseeds the crng so that it takes effect immediately.
792ae099e8eSJason A. Donenfeld  *
79392c653cfSJason A. Donenfeld  * add_interrupt_randomness() uses the interrupt timing as random
79492c653cfSJason A. Donenfeld  * inputs to the entropy pool. Using the cycle counters and the irq source
79592c653cfSJason A. Donenfeld  * as inputs, it feeds the input pool roughly once a second or after 64
79692c653cfSJason A. Donenfeld  * interrupts, crediting 1 bit of entropy for whichever comes first.
79792c653cfSJason A. Donenfeld  *
798a4b5c26bSJason A. Donenfeld  * add_input_randomness() uses the input layer interrupt timing, as well
799a4b5c26bSJason A. Donenfeld  * as the event type information from the hardware.
800a4b5c26bSJason A. Donenfeld  *
801a4b5c26bSJason A. Donenfeld  * add_disk_randomness() uses what amounts to the seek time of block
802a4b5c26bSJason A. Donenfeld  * layer request events, on a per-disk_devt basis, as input to the
803a4b5c26bSJason A. Donenfeld  * entropy pool. Note that high-speed solid state drives with very low
804a4b5c26bSJason A. Donenfeld  * seek times do not make for good sources of entropy, as their seek
805a4b5c26bSJason A. Donenfeld  * times are usually fairly consistent.
806a4b5c26bSJason A. Donenfeld  *
807a4b5c26bSJason A. Donenfeld  * The last two routines try to estimate how many bits of entropy
808a4b5c26bSJason A. Donenfeld  * to credit. They do this by keeping track of the first and second
809a4b5c26bSJason A. Donenfeld  * order deltas of the event timings.
810a4b5c26bSJason A. Donenfeld  *
81192c653cfSJason A. Donenfeld  **********************************************************************/
81292c653cfSJason A. Donenfeld 
813b9b01a56SJason A. Donenfeld static bool trust_cpu __initdata = true;
814b9b01a56SJason A. Donenfeld static bool trust_bootloader __initdata = true;
81592c653cfSJason A. Donenfeld static int __init parse_trust_cpu(char *arg)
81692c653cfSJason A. Donenfeld {
81792c653cfSJason A. Donenfeld 	return kstrtobool(arg, &trust_cpu);
81892c653cfSJason A. Donenfeld }
819d97c68d1SJason A. Donenfeld static int __init parse_trust_bootloader(char *arg)
820d97c68d1SJason A. Donenfeld {
821d97c68d1SJason A. Donenfeld 	return kstrtobool(arg, &trust_bootloader);
822d97c68d1SJason A. Donenfeld }
82392c653cfSJason A. Donenfeld early_param("random.trust_cpu", parse_trust_cpu);
824d97c68d1SJason A. Donenfeld early_param("random.trust_bootloader", parse_trust_bootloader);
825775f4b29STheodore Ts'o 
826b7b67d13SJason A. Donenfeld static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
827b7b67d13SJason A. Donenfeld {
828b7b67d13SJason A. Donenfeld 	unsigned long flags, entropy = random_get_entropy();
829b7b67d13SJason A. Donenfeld 
830b7b67d13SJason A. Donenfeld 	/*
831b7b67d13SJason A. Donenfeld 	 * Encode a representation of how long the system has been suspended,
832b7b67d13SJason A. Donenfeld 	 * in a way that is distinct from prior system suspends.
833b7b67d13SJason A. Donenfeld 	 */
834b7b67d13SJason A. Donenfeld 	ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
835b7b67d13SJason A. Donenfeld 
836b7b67d13SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
837b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&action, sizeof(action));
838b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(stamps, sizeof(stamps));
839b7b67d13SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
840b7b67d13SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
841b7b67d13SJason A. Donenfeld 
842b7b67d13SJason A. Donenfeld 	if (crng_ready() && (action == PM_RESTORE_PREPARE ||
843261e224dSKalesh Singh 	    (action == PM_POST_SUSPEND && !IS_ENABLED(CONFIG_PM_AUTOSLEEP) &&
844261e224dSKalesh Singh 	     !IS_ENABLED(CONFIG_PM_USERSPACE_AUTOSLEEP)))) {
8459148de31SJason A. Donenfeld 		crng_reseed(NULL);
846b7b67d13SJason A. Donenfeld 		pr_notice("crng reseeded on system resumption\n");
847b7b67d13SJason A. Donenfeld 	}
848b7b67d13SJason A. Donenfeld 	return 0;
849b7b67d13SJason A. Donenfeld }
850b7b67d13SJason A. Donenfeld 
851b7b67d13SJason A. Donenfeld static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
852b7b67d13SJason A. Donenfeld 
853775f4b29STheodore Ts'o /*
854f6238499SJason A. Donenfeld  * This is called extremely early, before time keeping functionality is
855f6238499SJason A. Donenfeld  * available, but arch randomness is. Interrupts are not yet enabled.
856775f4b29STheodore Ts'o  */
857f6238499SJason A. Donenfeld void __init random_init_early(const char *command_line)
858775f4b29STheodore Ts'o {
859d349ab99SJason A. Donenfeld 	unsigned long entropy[BLAKE2S_BLOCK_SIZE / sizeof(long)];
860f6238499SJason A. Donenfeld 	size_t i, longs, arch_bits;
861775f4b29STheodore Ts'o 
8621754abb3SJason A. Donenfeld #if defined(LATENT_ENTROPY_PLUGIN)
8631754abb3SJason A. Donenfeld 	static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
8641754abb3SJason A. Donenfeld 	_mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
8651754abb3SJason A. Donenfeld #endif
8661754abb3SJason A. Donenfeld 
867d349ab99SJason A. Donenfeld 	for (i = 0, arch_bits = sizeof(entropy) * 8; i < ARRAY_SIZE(entropy);) {
8682c03e16fSJason A. Donenfeld 		longs = arch_get_random_seed_longs(entropy, ARRAY_SIZE(entropy) - i);
869d349ab99SJason A. Donenfeld 		if (longs) {
870d349ab99SJason A. Donenfeld 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
871d349ab99SJason A. Donenfeld 			i += longs;
872d349ab99SJason A. Donenfeld 			continue;
87392c653cfSJason A. Donenfeld 		}
8742c03e16fSJason A. Donenfeld 		longs = arch_get_random_longs(entropy, ARRAY_SIZE(entropy) - i);
875d349ab99SJason A. Donenfeld 		if (longs) {
876d349ab99SJason A. Donenfeld 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
877d349ab99SJason A. Donenfeld 			i += longs;
878d349ab99SJason A. Donenfeld 			continue;
879d349ab99SJason A. Donenfeld 		}
880d349ab99SJason A. Donenfeld 		arch_bits -= sizeof(*entropy) * 8;
881d349ab99SJason A. Donenfeld 		++i;
88292c653cfSJason A. Donenfeld 	}
883f6238499SJason A. Donenfeld 
884dd54fd7dSJason A. Donenfeld 	_mix_pool_bytes(init_utsname(), sizeof(*(init_utsname())));
8852f14062bSJason A. Donenfeld 	_mix_pool_bytes(command_line, strlen(command_line));
886f6238499SJason A. Donenfeld 
887f6238499SJason A. Donenfeld 	/* Reseed if already seeded by earlier phases. */
888f6238499SJason A. Donenfeld 	if (crng_ready())
8899148de31SJason A. Donenfeld 		crng_reseed(NULL);
890f6238499SJason A. Donenfeld 	else if (trust_cpu)
891f6238499SJason A. Donenfeld 		_credit_init_bits(arch_bits);
892f6238499SJason A. Donenfeld }
893f6238499SJason A. Donenfeld 
894f6238499SJason A. Donenfeld /*
895f6238499SJason A. Donenfeld  * This is called a little bit after the prior function, and now there is
896f6238499SJason A. Donenfeld  * access to timestamps counters. Interrupts are not yet enabled.
897f6238499SJason A. Donenfeld  */
898f6238499SJason A. Donenfeld void __init random_init(void)
899f6238499SJason A. Donenfeld {
900f6238499SJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
901f6238499SJason A. Donenfeld 	ktime_t now = ktime_get_real();
902f6238499SJason A. Donenfeld 
903f6238499SJason A. Donenfeld 	_mix_pool_bytes(&now, sizeof(now));
904f6238499SJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
9052f14062bSJason A. Donenfeld 	add_latent_entropy();
906655b2264STheodore Ts'o 
90760e5b288SJason A. Donenfeld 	/*
908f6238499SJason A. Donenfeld 	 * If we were initialized by the cpu or bootloader before jump labels
909e871abcdSJason A. Donenfeld 	 * or workqueues are initialized, then we should enable the static
910e871abcdSJason A. Donenfeld 	 * branch here, where it's guaranteed that these have been initialized.
91160e5b288SJason A. Donenfeld 	 */
91260e5b288SJason A. Donenfeld 	if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
91360e5b288SJason A. Donenfeld 		crng_set_ready(NULL);
91460e5b288SJason A. Donenfeld 
915f6238499SJason A. Donenfeld 	/* Reseed if already seeded by earlier phases. */
916e85c0fc1SJason A. Donenfeld 	if (crng_ready())
9179148de31SJason A. Donenfeld 		crng_reseed(NULL);
918775f4b29STheodore Ts'o 
919b7b67d13SJason A. Donenfeld 	WARN_ON(register_pm_notifier(&pm_notifier));
920b7b67d13SJason A. Donenfeld 
921f6238499SJason A. Donenfeld 	WARN(!entropy, "Missing cycle counter and fallback timer; RNG "
9224b758edaSJason A. Donenfeld 		       "entropy collection will consequently suffer.");
92392c653cfSJason A. Donenfeld }
9241da177e4SLinus Torvalds 
925a2080a67SLinus Torvalds /*
926e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
927e192be9dSTheodore Ts'o  * initialize it.
928a2080a67SLinus Torvalds  *
929e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
930e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
931e192be9dSTheodore Ts'o  * identical devices.
932a2080a67SLinus Torvalds  */
933a1940263SJason A. Donenfeld void add_device_randomness(const void *buf, size_t len)
934a2080a67SLinus Torvalds {
9354b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
9364b758edaSJason A. Donenfeld 	unsigned long flags;
937a2080a67SLinus Torvalds 
9383ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
9394b758edaSJason A. Donenfeld 	_mix_pool_bytes(&entropy, sizeof(entropy));
940a1940263SJason A. Donenfeld 	_mix_pool_bytes(buf, len);
9413ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
942a2080a67SLinus Torvalds }
943a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
944a2080a67SLinus Torvalds 
94592c653cfSJason A. Donenfeld /*
946db516da9SJason A. Donenfeld  * Interface for in-kernel drivers of true hardware RNGs. Those devices
947db516da9SJason A. Donenfeld  * may produce endless random bits, so this function will sleep for
948db516da9SJason A. Donenfeld  * some amount of time after, if the sleep_after parameter is true.
94992c653cfSJason A. Donenfeld  */
950db516da9SJason A. Donenfeld void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after)
95192c653cfSJason A. Donenfeld {
952a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
953e85c0fc1SJason A. Donenfeld 	credit_init_bits(entropy);
954e85c0fc1SJason A. Donenfeld 
955e85c0fc1SJason A. Donenfeld 	/*
956745558f9SDominik Brodowski 	 * Throttle writing to once every reseed interval, unless we're not yet
957d775335eSJason A. Donenfeld 	 * initialized or no entropy is credited.
958e85c0fc1SJason A. Donenfeld 	 */
959db516da9SJason A. Donenfeld 	if (sleep_after && !kthread_should_stop() && (crng_ready() || !entropy))
960745558f9SDominik Brodowski 		schedule_timeout_interruptible(crng_reseed_interval());
96192c653cfSJason A. Donenfeld }
96292c653cfSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
96392c653cfSJason A. Donenfeld 
96492c653cfSJason A. Donenfeld /*
965b9b01a56SJason A. Donenfeld  * Handle random seed passed by bootloader, and credit it depending
966b9b01a56SJason A. Donenfeld  * on the command line option 'random.trust_bootloader'.
96792c653cfSJason A. Donenfeld  */
96839e0f991SJason A. Donenfeld void __init add_bootloader_randomness(const void *buf, size_t len)
96992c653cfSJason A. Donenfeld {
970a1940263SJason A. Donenfeld 	mix_pool_bytes(buf, len);
971d97c68d1SJason A. Donenfeld 	if (trust_bootloader)
972a1940263SJason A. Donenfeld 		credit_init_bits(len * 8);
97392c653cfSJason A. Donenfeld }
97492c653cfSJason A. Donenfeld 
975a4107d34SJason A. Donenfeld #if IS_ENABLED(CONFIG_VMGENID)
976f3c2682bSJason A. Donenfeld static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
977f3c2682bSJason A. Donenfeld 
978ae099e8eSJason A. Donenfeld /*
979ae099e8eSJason A. Donenfeld  * Handle a new unique VM ID, which is unique, not secret, so we
980ae099e8eSJason A. Donenfeld  * don't credit it, but we do immediately force a reseed after so
981ae099e8eSJason A. Donenfeld  * that it's used by the crng posthaste.
982ae099e8eSJason A. Donenfeld  */
983560181c2SJason A. Donenfeld void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
984ae099e8eSJason A. Donenfeld {
985a1940263SJason A. Donenfeld 	add_device_randomness(unique_vm_id, len);
986ae099e8eSJason A. Donenfeld 	if (crng_ready()) {
9879148de31SJason A. Donenfeld 		crng_reseed(NULL);
988ae099e8eSJason A. Donenfeld 		pr_notice("crng reseeded due to virtual machine fork\n");
989ae099e8eSJason A. Donenfeld 	}
990f3c2682bSJason A. Donenfeld 	blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
991ae099e8eSJason A. Donenfeld }
992a4107d34SJason A. Donenfeld #if IS_MODULE(CONFIG_VMGENID)
993ae099e8eSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_vmfork_randomness);
994a4107d34SJason A. Donenfeld #endif
995f3c2682bSJason A. Donenfeld 
996560181c2SJason A. Donenfeld int __cold register_random_vmfork_notifier(struct notifier_block *nb)
997f3c2682bSJason A. Donenfeld {
998f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_register(&vmfork_chain, nb);
999f3c2682bSJason A. Donenfeld }
1000f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
1001f3c2682bSJason A. Donenfeld 
1002560181c2SJason A. Donenfeld int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
1003f3c2682bSJason A. Donenfeld {
1004f3c2682bSJason A. Donenfeld 	return blocking_notifier_chain_unregister(&vmfork_chain, nb);
1005f3c2682bSJason A. Donenfeld }
1006f3c2682bSJason A. Donenfeld EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
1007a4107d34SJason A. Donenfeld #endif
1008ae099e8eSJason A. Donenfeld 
100992c653cfSJason A. Donenfeld struct fast_pool {
1010f5eab0e2SJason A. Donenfeld 	unsigned long pool[4];
101192c653cfSJason A. Donenfeld 	unsigned long last;
10123191dd5aSJason A. Donenfeld 	unsigned int count;
1013748bc4ddSJason A. Donenfeld 	struct timer_list mix;
101492c653cfSJason A. Donenfeld };
101592c653cfSJason A. Donenfeld 
1016748bc4ddSJason A. Donenfeld static void mix_interrupt_randomness(struct timer_list *work);
1017748bc4ddSJason A. Donenfeld 
1018f5eab0e2SJason A. Donenfeld static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
1019f5eab0e2SJason A. Donenfeld #ifdef CONFIG_64BIT
1020e73aaae2SJason A. Donenfeld #define FASTMIX_PERM SIPHASH_PERMUTATION
1021748bc4ddSJason A. Donenfeld 	.pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 },
1022f5eab0e2SJason A. Donenfeld #else
1023e73aaae2SJason A. Donenfeld #define FASTMIX_PERM HSIPHASH_PERMUTATION
1024748bc4ddSJason A. Donenfeld 	.pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 },
1025f5eab0e2SJason A. Donenfeld #endif
1026748bc4ddSJason A. Donenfeld 	.mix = __TIMER_INITIALIZER(mix_interrupt_randomness, 0)
1027f5eab0e2SJason A. Donenfeld };
1028f5eab0e2SJason A. Donenfeld 
102992c653cfSJason A. Donenfeld /*
1030f5eab0e2SJason A. Donenfeld  * This is [Half]SipHash-1-x, starting from an empty key. Because
1031f5eab0e2SJason A. Donenfeld  * the key is fixed, it assumes that its inputs are non-malicious,
1032f5eab0e2SJason A. Donenfeld  * and therefore this has no security on its own. s represents the
10334b758edaSJason A. Donenfeld  * four-word SipHash state, while v represents a two-word input.
103492c653cfSJason A. Donenfeld  */
1035791332b3SJason A. Donenfeld static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
103692c653cfSJason A. Donenfeld {
1037791332b3SJason A. Donenfeld 	s[3] ^= v1;
1038e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1039791332b3SJason A. Donenfeld 	s[0] ^= v1;
1040791332b3SJason A. Donenfeld 	s[3] ^= v2;
1041e73aaae2SJason A. Donenfeld 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1042791332b3SJason A. Donenfeld 	s[0] ^= v2;
1043f5eab0e2SJason A. Donenfeld }
1044775f4b29STheodore Ts'o 
10453191dd5aSJason A. Donenfeld #ifdef CONFIG_SMP
10463191dd5aSJason A. Donenfeld /*
10473191dd5aSJason A. Donenfeld  * This function is called when the CPU has just come online, with
10483191dd5aSJason A. Donenfeld  * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
10493191dd5aSJason A. Donenfeld  */
1050560181c2SJason A. Donenfeld int __cold random_online_cpu(unsigned int cpu)
10513191dd5aSJason A. Donenfeld {
10523191dd5aSJason A. Donenfeld 	/*
10533191dd5aSJason A. Donenfeld 	 * During CPU shutdown and before CPU onlining, add_interrupt_
10543191dd5aSJason A. Donenfeld 	 * randomness() may schedule mix_interrupt_randomness(), and
10553191dd5aSJason A. Donenfeld 	 * set the MIX_INFLIGHT flag. However, because the worker can
10563191dd5aSJason A. Donenfeld 	 * be scheduled on a different CPU during this period, that
10573191dd5aSJason A. Donenfeld 	 * flag will never be cleared. For that reason, we zero out
10583191dd5aSJason A. Donenfeld 	 * the flag here, which runs just after workqueues are onlined
10593191dd5aSJason A. Donenfeld 	 * for the CPU again. This also has the effect of setting the
10603191dd5aSJason A. Donenfeld 	 * irq randomness count to zero so that new accumulated irqs
10613191dd5aSJason A. Donenfeld 	 * are fresh.
10623191dd5aSJason A. Donenfeld 	 */
10633191dd5aSJason A. Donenfeld 	per_cpu_ptr(&irq_randomness, cpu)->count = 0;
10643191dd5aSJason A. Donenfeld 	return 0;
10653191dd5aSJason A. Donenfeld }
10663191dd5aSJason A. Donenfeld #endif
10673191dd5aSJason A. Donenfeld 
1068748bc4ddSJason A. Donenfeld static void mix_interrupt_randomness(struct timer_list *work)
106958340f8eSJason A. Donenfeld {
107058340f8eSJason A. Donenfeld 	struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
1071f5eab0e2SJason A. Donenfeld 	/*
10724b758edaSJason A. Donenfeld 	 * The size of the copied stack pool is explicitly 2 longs so that we
10734b758edaSJason A. Donenfeld 	 * only ever ingest half of the siphash output each time, retaining
10744b758edaSJason A. Donenfeld 	 * the other half as the next "key" that carries over. The entropy is
10754b758edaSJason A. Donenfeld 	 * supposed to be sufficiently dispersed between bits so on average
10764b758edaSJason A. Donenfeld 	 * we don't wind up "losing" some.
1077f5eab0e2SJason A. Donenfeld 	 */
10784b758edaSJason A. Donenfeld 	unsigned long pool[2];
1079e3e33fc2SJason A. Donenfeld 	unsigned int count;
108058340f8eSJason A. Donenfeld 
108158340f8eSJason A. Donenfeld 	/* Check to see if we're running on the wrong CPU due to hotplug. */
108258340f8eSJason A. Donenfeld 	local_irq_disable();
108358340f8eSJason A. Donenfeld 	if (fast_pool != this_cpu_ptr(&irq_randomness)) {
108458340f8eSJason A. Donenfeld 		local_irq_enable();
108558340f8eSJason A. Donenfeld 		return;
108658340f8eSJason A. Donenfeld 	}
108758340f8eSJason A. Donenfeld 
108858340f8eSJason A. Donenfeld 	/*
108958340f8eSJason A. Donenfeld 	 * Copy the pool to the stack so that the mixer always has a
109058340f8eSJason A. Donenfeld 	 * consistent view, before we reenable irqs again.
109158340f8eSJason A. Donenfeld 	 */
1092f5eab0e2SJason A. Donenfeld 	memcpy(pool, fast_pool->pool, sizeof(pool));
1093e3e33fc2SJason A. Donenfeld 	count = fast_pool->count;
10943191dd5aSJason A. Donenfeld 	fast_pool->count = 0;
109558340f8eSJason A. Donenfeld 	fast_pool->last = jiffies;
109658340f8eSJason A. Donenfeld 	local_irq_enable();
109758340f8eSJason A. Donenfeld 
109858340f8eSJason A. Donenfeld 	mix_pool_bytes(pool, sizeof(pool));
1099e78a802aSJason A. Donenfeld 	credit_init_bits(clamp_t(unsigned int, (count & U16_MAX) / 64, 1, sizeof(pool) * 8));
1100c2a7de4fSJason A. Donenfeld 
110158340f8eSJason A. Donenfeld 	memzero_explicit(pool, sizeof(pool));
110258340f8eSJason A. Donenfeld }
110358340f8eSJason A. Donenfeld 
1104703f7066SSebastian Andrzej Siewior void add_interrupt_randomness(int irq)
11051da177e4SLinus Torvalds {
110658340f8eSJason A. Donenfeld 	enum { MIX_INFLIGHT = 1U << 31 };
11074b758edaSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
11081b2a1a7eSChristoph Lameter 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
1109775f4b29STheodore Ts'o 	struct pt_regs *regs = get_irq_regs();
111058340f8eSJason A. Donenfeld 	unsigned int new_count;
11113060d6feSYinghai Lu 
1112791332b3SJason A. Donenfeld 	fast_mix(fast_pool->pool, entropy,
1113791332b3SJason A. Donenfeld 		 (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
11143191dd5aSJason A. Donenfeld 	new_count = ++fast_pool->count;
1115775f4b29STheodore Ts'o 
111658340f8eSJason A. Donenfeld 	if (new_count & MIX_INFLIGHT)
11171da177e4SLinus Torvalds 		return;
1118840f9507STheodore Ts'o 
1119534d2eafSJason A. Donenfeld 	if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
11201da177e4SLinus Torvalds 		return;
11211da177e4SLinus Torvalds 
11223191dd5aSJason A. Donenfeld 	fast_pool->count |= MIX_INFLIGHT;
1123748bc4ddSJason A. Donenfeld 	if (!timer_pending(&fast_pool->mix)) {
1124748bc4ddSJason A. Donenfeld 		fast_pool->mix.expires = jiffies;
1125748bc4ddSJason A. Donenfeld 		add_timer_on(&fast_pool->mix, raw_smp_processor_id());
1126748bc4ddSJason A. Donenfeld 	}
11271da177e4SLinus Torvalds }
11284b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
11291da177e4SLinus Torvalds 
1130a4b5c26bSJason A. Donenfeld /* There is one of these per entropy source */
1131a4b5c26bSJason A. Donenfeld struct timer_rand_state {
1132a4b5c26bSJason A. Donenfeld 	unsigned long last_time;
1133a4b5c26bSJason A. Donenfeld 	long last_delta, last_delta2;
1134a4b5c26bSJason A. Donenfeld };
1135a4b5c26bSJason A. Donenfeld 
1136a4b5c26bSJason A. Donenfeld /*
1137a4b5c26bSJason A. Donenfeld  * This function adds entropy to the entropy "pool" by using timing
1138a4b5c26bSJason A. Donenfeld  * delays. It uses the timer_rand_state structure to make an estimate
1139e3e33fc2SJason A. Donenfeld  * of how many bits of entropy this call has added to the pool. The
1140e3e33fc2SJason A. Donenfeld  * value "num" is also added to the pool; it should somehow describe
1141e3e33fc2SJason A. Donenfeld  * the type of event that just happened.
1142a4b5c26bSJason A. Donenfeld  */
1143a4b5c26bSJason A. Donenfeld static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1144a4b5c26bSJason A. Donenfeld {
1145a4b5c26bSJason A. Donenfeld 	unsigned long entropy = random_get_entropy(), now = jiffies, flags;
1146a4b5c26bSJason A. Donenfeld 	long delta, delta2, delta3;
1147e3e33fc2SJason A. Donenfeld 	unsigned int bits;
1148a4b5c26bSJason A. Donenfeld 
1149e3e33fc2SJason A. Donenfeld 	/*
1150e3e33fc2SJason A. Donenfeld 	 * If we're in a hard IRQ, add_interrupt_randomness() will be called
1151e3e33fc2SJason A. Donenfeld 	 * sometime after, so mix into the fast pool.
1152e3e33fc2SJason A. Donenfeld 	 */
1153e3e33fc2SJason A. Donenfeld 	if (in_hardirq()) {
1154791332b3SJason A. Donenfeld 		fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
1155e3e33fc2SJason A. Donenfeld 	} else {
1156a4b5c26bSJason A. Donenfeld 		spin_lock_irqsave(&input_pool.lock, flags);
1157a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&entropy, sizeof(entropy));
1158a4b5c26bSJason A. Donenfeld 		_mix_pool_bytes(&num, sizeof(num));
1159a4b5c26bSJason A. Donenfeld 		spin_unlock_irqrestore(&input_pool.lock, flags);
1160e3e33fc2SJason A. Donenfeld 	}
1161a4b5c26bSJason A. Donenfeld 
1162a4b5c26bSJason A. Donenfeld 	if (crng_ready())
1163a4b5c26bSJason A. Donenfeld 		return;
1164a4b5c26bSJason A. Donenfeld 
1165a4b5c26bSJason A. Donenfeld 	/*
1166a4b5c26bSJason A. Donenfeld 	 * Calculate number of bits of randomness we probably added.
1167a4b5c26bSJason A. Donenfeld 	 * We take into account the first, second and third-order deltas
1168a4b5c26bSJason A. Donenfeld 	 * in order to make our estimate.
1169a4b5c26bSJason A. Donenfeld 	 */
1170a4b5c26bSJason A. Donenfeld 	delta = now - READ_ONCE(state->last_time);
1171a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_time, now);
1172a4b5c26bSJason A. Donenfeld 
1173a4b5c26bSJason A. Donenfeld 	delta2 = delta - READ_ONCE(state->last_delta);
1174a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta, delta);
1175a4b5c26bSJason A. Donenfeld 
1176a4b5c26bSJason A. Donenfeld 	delta3 = delta2 - READ_ONCE(state->last_delta2);
1177a4b5c26bSJason A. Donenfeld 	WRITE_ONCE(state->last_delta2, delta2);
1178a4b5c26bSJason A. Donenfeld 
1179a4b5c26bSJason A. Donenfeld 	if (delta < 0)
1180a4b5c26bSJason A. Donenfeld 		delta = -delta;
1181a4b5c26bSJason A. Donenfeld 	if (delta2 < 0)
1182a4b5c26bSJason A. Donenfeld 		delta2 = -delta2;
1183a4b5c26bSJason A. Donenfeld 	if (delta3 < 0)
1184a4b5c26bSJason A. Donenfeld 		delta3 = -delta3;
1185a4b5c26bSJason A. Donenfeld 	if (delta > delta2)
1186a4b5c26bSJason A. Donenfeld 		delta = delta2;
1187a4b5c26bSJason A. Donenfeld 	if (delta > delta3)
1188a4b5c26bSJason A. Donenfeld 		delta = delta3;
1189a4b5c26bSJason A. Donenfeld 
1190a4b5c26bSJason A. Donenfeld 	/*
1191e3e33fc2SJason A. Donenfeld 	 * delta is now minimum absolute delta. Round down by 1 bit
1192e3e33fc2SJason A. Donenfeld 	 * on general principles, and limit entropy estimate to 11 bits.
1193a4b5c26bSJason A. Donenfeld 	 */
1194e3e33fc2SJason A. Donenfeld 	bits = min(fls(delta >> 1), 11);
1195e3e33fc2SJason A. Donenfeld 
1196e3e33fc2SJason A. Donenfeld 	/*
1197e3e33fc2SJason A. Donenfeld 	 * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
1198e3e33fc2SJason A. Donenfeld 	 * will run after this, which uses a different crediting scheme of 1 bit
1199e3e33fc2SJason A. Donenfeld 	 * per every 64 interrupts. In order to let that function do accounting
1200e3e33fc2SJason A. Donenfeld 	 * close to the one in this function, we credit a full 64/64 bit per bit,
1201e3e33fc2SJason A. Donenfeld 	 * and then subtract one to account for the extra one added.
1202e3e33fc2SJason A. Donenfeld 	 */
1203e3e33fc2SJason A. Donenfeld 	if (in_hardirq())
1204e3e33fc2SJason A. Donenfeld 		this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
1205e3e33fc2SJason A. Donenfeld 	else
1206560181c2SJason A. Donenfeld 		_credit_init_bits(bits);
1207a4b5c26bSJason A. Donenfeld }
1208a4b5c26bSJason A. Donenfeld 
1209a1940263SJason A. Donenfeld void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
1210a4b5c26bSJason A. Donenfeld {
1211a4b5c26bSJason A. Donenfeld 	static unsigned char last_value;
1212a4b5c26bSJason A. Donenfeld 	static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
1213a4b5c26bSJason A. Donenfeld 
1214a4b5c26bSJason A. Donenfeld 	/* Ignore autorepeat and the like. */
1215a4b5c26bSJason A. Donenfeld 	if (value == last_value)
1216a4b5c26bSJason A. Donenfeld 		return;
1217a4b5c26bSJason A. Donenfeld 
1218a4b5c26bSJason A. Donenfeld 	last_value = value;
1219a4b5c26bSJason A. Donenfeld 	add_timer_randomness(&input_timer_state,
1220a4b5c26bSJason A. Donenfeld 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1221a4b5c26bSJason A. Donenfeld }
1222a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_input_randomness);
1223a4b5c26bSJason A. Donenfeld 
1224a4b5c26bSJason A. Donenfeld #ifdef CONFIG_BLOCK
1225a4b5c26bSJason A. Donenfeld void add_disk_randomness(struct gendisk *disk)
1226a4b5c26bSJason A. Donenfeld {
1227a4b5c26bSJason A. Donenfeld 	if (!disk || !disk->random)
1228a4b5c26bSJason A. Donenfeld 		return;
1229a4b5c26bSJason A. Donenfeld 	/* First major is 1, so we get >= 0x200 here. */
1230a4b5c26bSJason A. Donenfeld 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1231a4b5c26bSJason A. Donenfeld }
1232a4b5c26bSJason A. Donenfeld EXPORT_SYMBOL_GPL(add_disk_randomness);
1233a4b5c26bSJason A. Donenfeld 
1234560181c2SJason A. Donenfeld void __cold rand_initialize_disk(struct gendisk *disk)
1235a4b5c26bSJason A. Donenfeld {
1236a4b5c26bSJason A. Donenfeld 	struct timer_rand_state *state;
1237a4b5c26bSJason A. Donenfeld 
1238a4b5c26bSJason A. Donenfeld 	/*
1239a4b5c26bSJason A. Donenfeld 	 * If kzalloc returns null, we just won't use that entropy
1240a4b5c26bSJason A. Donenfeld 	 * source.
1241a4b5c26bSJason A. Donenfeld 	 */
1242a4b5c26bSJason A. Donenfeld 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1243a4b5c26bSJason A. Donenfeld 	if (state) {
1244a4b5c26bSJason A. Donenfeld 		state->last_time = INITIAL_JIFFIES;
1245a4b5c26bSJason A. Donenfeld 		disk->random = state;
1246a4b5c26bSJason A. Donenfeld 	}
1247a4b5c26bSJason A. Donenfeld }
1248a4b5c26bSJason A. Donenfeld #endif
1249a4b5c26bSJason A. Donenfeld 
125078c768e6SJason A. Donenfeld struct entropy_timer_state {
125178c768e6SJason A. Donenfeld 	unsigned long entropy;
125278c768e6SJason A. Donenfeld 	struct timer_list timer;
12531c21fe00SJason A. Donenfeld 	atomic_t samples;
12541c21fe00SJason A. Donenfeld 	unsigned int samples_per_bit;
125578c768e6SJason A. Donenfeld };
125678c768e6SJason A. Donenfeld 
12571da177e4SLinus Torvalds /*
12580e42d14bSJason A. Donenfeld  * Each time the timer fires, we expect that we got an unpredictable jump in
12590e42d14bSJason A. Donenfeld  * the cycle counter. Even if the timer is running on another CPU, the timer
12600e42d14bSJason A. Donenfeld  * activity will be touching the stack of the CPU that is generating entropy.
126150ee7529SLinus Torvalds  *
12620e42d14bSJason A. Donenfeld  * Note that we don't re-arm the timer in the timer itself - we are happy to be
12630e42d14bSJason A. Donenfeld  * scheduled away, since that just makes the load more complex, but we do not
12640e42d14bSJason A. Donenfeld  * want the timer to keep ticking unless the entropy loop is running.
126550ee7529SLinus Torvalds  *
126650ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
126750ee7529SLinus Torvalds  */
1268560181c2SJason A. Donenfeld static void __cold entropy_timer(struct timer_list *timer)
126950ee7529SLinus Torvalds {
127078c768e6SJason A. Donenfeld 	struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
1271b83e45fdSJason A. Donenfeld 	unsigned long entropy = random_get_entropy();
127278c768e6SJason A. Donenfeld 
1273b83e45fdSJason A. Donenfeld 	mix_pool_bytes(&entropy, sizeof(entropy));
12741c21fe00SJason A. Donenfeld 	if (atomic_inc_return(&state->samples) % state->samples_per_bit == 0)
1275e85c0fc1SJason A. Donenfeld 		credit_init_bits(1);
127650ee7529SLinus Torvalds }
127750ee7529SLinus Torvalds 
127850ee7529SLinus Torvalds /*
12790e42d14bSJason A. Donenfeld  * If we have an actual cycle counter, see if we can generate enough entropy
12800e42d14bSJason A. Donenfeld  * with timing noise.
128150ee7529SLinus Torvalds  */
1282560181c2SJason A. Donenfeld static void __cold try_to_generate_entropy(void)
128350ee7529SLinus Torvalds {
128412273347SJason A. Donenfeld 	enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 15 };
128539ec9e6bSJason A. Donenfeld 	u8 stack_bytes[sizeof(struct entropy_timer_state) + SMP_CACHE_BYTES - 1];
128639ec9e6bSJason A. Donenfeld 	struct entropy_timer_state *stack = PTR_ALIGN((void *)stack_bytes, SMP_CACHE_BYTES);
128778c768e6SJason A. Donenfeld 	unsigned int i, num_different = 0;
128878c768e6SJason A. Donenfeld 	unsigned long last = random_get_entropy();
12891c21fe00SJason A. Donenfeld 	int cpu = -1;
129050ee7529SLinus Torvalds 
129178c768e6SJason A. Donenfeld 	for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
129239ec9e6bSJason A. Donenfeld 		stack->entropy = random_get_entropy();
129339ec9e6bSJason A. Donenfeld 		if (stack->entropy != last)
129478c768e6SJason A. Donenfeld 			++num_different;
129539ec9e6bSJason A. Donenfeld 		last = stack->entropy;
129678c768e6SJason A. Donenfeld 	}
129739ec9e6bSJason A. Donenfeld 	stack->samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
129839ec9e6bSJason A. Donenfeld 	if (stack->samples_per_bit > MAX_SAMPLES_PER_BIT)
129950ee7529SLinus Torvalds 		return;
130050ee7529SLinus Torvalds 
130139ec9e6bSJason A. Donenfeld 	atomic_set(&stack->samples, 0);
130239ec9e6bSJason A. Donenfeld 	timer_setup_on_stack(&stack->timer, entropy_timer, 0);
13033e504d20SJason A. Donenfeld 	while (!crng_ready() && !signal_pending(current)) {
13041c21fe00SJason A. Donenfeld 		/*
13051c21fe00SJason A. Donenfeld 		 * Check !timer_pending() and then ensure that any previous callback has finished
13061c21fe00SJason A. Donenfeld 		 * executing by checking try_to_del_timer_sync(), before queueing the next one.
13071c21fe00SJason A. Donenfeld 		 */
130839ec9e6bSJason A. Donenfeld 		if (!timer_pending(&stack->timer) && try_to_del_timer_sync(&stack->timer) >= 0) {
13091c21fe00SJason A. Donenfeld 			struct cpumask timer_cpus;
13101c21fe00SJason A. Donenfeld 			unsigned int num_cpus;
13111c21fe00SJason A. Donenfeld 
13121c21fe00SJason A. Donenfeld 			/*
13131c21fe00SJason A. Donenfeld 			 * Preemption must be disabled here, both to read the current CPU number
13141c21fe00SJason A. Donenfeld 			 * and to avoid scheduling a timer on a dead CPU.
13151c21fe00SJason A. Donenfeld 			 */
13161c21fe00SJason A. Donenfeld 			preempt_disable();
13171c21fe00SJason A. Donenfeld 
13181c21fe00SJason A. Donenfeld 			/* Only schedule callbacks on timer CPUs that are online. */
13191c21fe00SJason A. Donenfeld 			cpumask_and(&timer_cpus, housekeeping_cpumask(HK_TYPE_TIMER), cpu_online_mask);
13201c21fe00SJason A. Donenfeld 			num_cpus = cpumask_weight(&timer_cpus);
13211c21fe00SJason A. Donenfeld 			/* In very bizarre case of misconfiguration, fallback to all online. */
13221c21fe00SJason A. Donenfeld 			if (unlikely(num_cpus == 0)) {
13231c21fe00SJason A. Donenfeld 				timer_cpus = *cpu_online_mask;
13241c21fe00SJason A. Donenfeld 				num_cpus = cpumask_weight(&timer_cpus);
13251c21fe00SJason A. Donenfeld 			}
13261c21fe00SJason A. Donenfeld 
13271c21fe00SJason A. Donenfeld 			/* Basic CPU round-robin, which avoids the current CPU. */
13281c21fe00SJason A. Donenfeld 			do {
13291c21fe00SJason A. Donenfeld 				cpu = cpumask_next(cpu, &timer_cpus);
13308ca09d5fSLinus Torvalds 				if (cpu >= nr_cpu_ids)
13311c21fe00SJason A. Donenfeld 					cpu = cpumask_first(&timer_cpus);
13321c21fe00SJason A. Donenfeld 			} while (cpu == smp_processor_id() && num_cpus > 1);
13331c21fe00SJason A. Donenfeld 
13341c21fe00SJason A. Donenfeld 			/* Expiring the timer at `jiffies` means it's the next tick. */
133539ec9e6bSJason A. Donenfeld 			stack->timer.expires = jiffies;
13361c21fe00SJason A. Donenfeld 
133739ec9e6bSJason A. Donenfeld 			add_timer_on(&stack->timer, cpu);
13381c21fe00SJason A. Donenfeld 
13391c21fe00SJason A. Donenfeld 			preempt_enable();
13401c21fe00SJason A. Donenfeld 		}
134139ec9e6bSJason A. Donenfeld 		mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
134250ee7529SLinus Torvalds 		schedule();
134339ec9e6bSJason A. Donenfeld 		stack->entropy = random_get_entropy();
134450ee7529SLinus Torvalds 	}
134539ec9e6bSJason A. Donenfeld 	mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
134650ee7529SLinus Torvalds 
134739ec9e6bSJason A. Donenfeld 	del_timer_sync(&stack->timer);
134839ec9e6bSJason A. Donenfeld 	destroy_timer_on_stack(&stack->timer);
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 
1380a1940263SJason A. Donenfeld SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
13811da177e4SLinus Torvalds {
13821b388e77SJens Axboe 	struct iov_iter iter;
13831b388e77SJens Axboe 	int ret;
13841b388e77SJens Axboe 
1385a6adf8e7SJason A. Donenfeld 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
1386a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1387301f0595STheodore Ts'o 
1388a6adf8e7SJason A. Donenfeld 	/*
1389a6adf8e7SJason A. Donenfeld 	 * Requesting insecure and blocking randomness at the same time makes
1390a6adf8e7SJason A. Donenfeld 	 * no sense.
1391a6adf8e7SJason A. Donenfeld 	 */
1392a6adf8e7SJason A. Donenfeld 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1393a6adf8e7SJason A. Donenfeld 		return -EINVAL;
1394c6f1deb1SAndy Lutomirski 
1395f5bda35fSJason A. Donenfeld 	if (!crng_ready() && !(flags & GRND_INSECURE)) {
1396a6adf8e7SJason A. Donenfeld 		if (flags & GRND_NONBLOCK)
1397a6adf8e7SJason A. Donenfeld 			return -EAGAIN;
139830c08efeSAndy Lutomirski 		ret = wait_for_random_bytes();
1399a6adf8e7SJason A. Donenfeld 		if (unlikely(ret))
140030c08efeSAndy Lutomirski 			return ret;
1401a6adf8e7SJason A. Donenfeld 	}
14021b388e77SJens Axboe 
14039fd7874cSJens Axboe 	ret = import_ubuf(ITER_DEST, ubuf, len, &iter);
14041b388e77SJens Axboe 	if (unlikely(ret))
14051b388e77SJens Axboe 		return ret;
14061b388e77SJens Axboe 	return get_random_bytes_user(&iter);
140730c08efeSAndy Lutomirski }
140830c08efeSAndy Lutomirski 
1409248045b8SJason A. Donenfeld static __poll_t random_poll(struct file *file, poll_table *wait)
141089b310a2SChristoph Hellwig {
141130c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1412e85c0fc1SJason A. Donenfeld 	return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
14131da177e4SLinus Torvalds }
14141da177e4SLinus Torvalds 
14151ce6c8d6SJason A. Donenfeld static ssize_t write_pool_user(struct iov_iter *iter)
14167f397dcdSMatt Mackall {
141704ec96b7SJason A. Donenfeld 	u8 block[BLAKE2S_BLOCK_SIZE];
141822b0a222SJens Axboe 	ssize_t ret = 0;
141922b0a222SJens Axboe 	size_t copied;
14207f397dcdSMatt Mackall 
142122b0a222SJens Axboe 	if (unlikely(!iov_iter_count(iter)))
142222b0a222SJens Axboe 		return 0;
142322b0a222SJens Axboe 
142422b0a222SJens Axboe 	for (;;) {
142522b0a222SJens Axboe 		copied = copy_from_iter(block, sizeof(block), iter);
142622b0a222SJens Axboe 		ret += copied;
142722b0a222SJens Axboe 		mix_pool_bytes(block, copied);
142822b0a222SJens Axboe 		if (!iov_iter_count(iter) || copied != sizeof(block))
142922b0a222SJens Axboe 			break;
14301ce6c8d6SJason A. Donenfeld 
14311ce6c8d6SJason A. Donenfeld 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
14321ce6c8d6SJason A. Donenfeld 		if (ret % PAGE_SIZE == 0) {
14331ce6c8d6SJason A. Donenfeld 			if (signal_pending(current))
14341ce6c8d6SJason A. Donenfeld 				break;
143591f3f1e3SMatt Mackall 			cond_resched();
14367f397dcdSMatt Mackall 		}
14371ce6c8d6SJason A. Donenfeld 	}
14387f397dcdSMatt Mackall 
14397b5164fbSJason A. Donenfeld 	memzero_explicit(block, sizeof(block));
144022b0a222SJens Axboe 	return ret ? ret : -EFAULT;
14417f397dcdSMatt Mackall }
14427f397dcdSMatt Mackall 
144322b0a222SJens Axboe static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
14441da177e4SLinus Torvalds {
14451ce6c8d6SJason A. Donenfeld 	return write_pool_user(iter);
14461da177e4SLinus Torvalds }
14471da177e4SLinus Torvalds 
14481b388e77SJens Axboe static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
14490313bc27SLinus Torvalds {
14500313bc27SLinus Torvalds 	static int maxwarn = 10;
14510313bc27SLinus Torvalds 
145248bff105SJason A. Donenfeld 	/*
145348bff105SJason A. Donenfeld 	 * Opportunistically attempt to initialize the RNG on platforms that
145448bff105SJason A. Donenfeld 	 * have fast cycle counters, but don't (for now) require it to succeed.
145548bff105SJason A. Donenfeld 	 */
145648bff105SJason A. Donenfeld 	if (!crng_ready())
145748bff105SJason A. Donenfeld 		try_to_generate_entropy();
145848bff105SJason A. Donenfeld 
1459cc1e127bSJason A. Donenfeld 	if (!crng_ready()) {
1460cc1e127bSJason A. Donenfeld 		if (!ratelimit_disable && maxwarn <= 0)
1461cc1e127bSJason A. Donenfeld 			++urandom_warning.missed;
1462cc1e127bSJason A. Donenfeld 		else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
1463cc1e127bSJason A. Donenfeld 			--maxwarn;
14641b388e77SJens Axboe 			pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
14651b388e77SJens Axboe 				  current->comm, iov_iter_count(iter));
14660313bc27SLinus Torvalds 		}
1467cc1e127bSJason A. Donenfeld 	}
14680313bc27SLinus Torvalds 
14691b388e77SJens Axboe 	return get_random_bytes_user(iter);
14700313bc27SLinus Torvalds }
14710313bc27SLinus Torvalds 
14721b388e77SJens Axboe static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
1473a6adf8e7SJason A. Donenfeld {
1474a6adf8e7SJason A. Donenfeld 	int ret;
1475a6adf8e7SJason A. Donenfeld 
1476cd4f24aeSJason A. Donenfeld 	if (!crng_ready() &&
1477cd4f24aeSJason A. Donenfeld 	    ((kiocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) ||
1478cd4f24aeSJason A. Donenfeld 	     (kiocb->ki_filp->f_flags & O_NONBLOCK)))
1479cd4f24aeSJason A. Donenfeld 		return -EAGAIN;
1480cd4f24aeSJason A. Donenfeld 
1481a6adf8e7SJason A. Donenfeld 	ret = wait_for_random_bytes();
1482a6adf8e7SJason A. Donenfeld 	if (ret != 0)
1483a6adf8e7SJason A. Donenfeld 		return ret;
14841b388e77SJens Axboe 	return get_random_bytes_user(iter);
1485a6adf8e7SJason A. Donenfeld }
1486a6adf8e7SJason A. Donenfeld 
148743ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
14881da177e4SLinus Torvalds {
14891da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
149022b0a222SJens Axboe 	int ent_count;
14911da177e4SLinus Torvalds 
14921da177e4SLinus Torvalds 	switch (cmd) {
14931da177e4SLinus Torvalds 	case RNDGETENTCNT:
1494a6adf8e7SJason A. Donenfeld 		/* Inherently racy, no point locking. */
1495e85c0fc1SJason A. Donenfeld 		if (put_user(input_pool.init_bits, p))
14961da177e4SLinus Torvalds 			return -EFAULT;
14971da177e4SLinus Torvalds 		return 0;
14981da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
14991da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
15001da177e4SLinus Torvalds 			return -EPERM;
15011da177e4SLinus Torvalds 		if (get_user(ent_count, p))
15021da177e4SLinus Torvalds 			return -EFAULT;
1503a49c010eSJason A. Donenfeld 		if (ent_count < 0)
1504a49c010eSJason A. Donenfeld 			return -EINVAL;
1505e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1506a49c010eSJason A. Donenfeld 		return 0;
150722b0a222SJens Axboe 	case RNDADDENTROPY: {
150822b0a222SJens Axboe 		struct iov_iter iter;
150922b0a222SJens Axboe 		ssize_t ret;
151022b0a222SJens Axboe 		int len;
151122b0a222SJens Axboe 
15121da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
15131da177e4SLinus Torvalds 			return -EPERM;
15141da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
15151da177e4SLinus Torvalds 			return -EFAULT;
15161da177e4SLinus Torvalds 		if (ent_count < 0)
15171da177e4SLinus Torvalds 			return -EINVAL;
151822b0a222SJens Axboe 		if (get_user(len, p++))
15191da177e4SLinus Torvalds 			return -EFAULT;
15209fd7874cSJens Axboe 		ret = import_ubuf(ITER_SOURCE, p, len, &iter);
152122b0a222SJens Axboe 		if (unlikely(ret))
152222b0a222SJens Axboe 			return ret;
15231ce6c8d6SJason A. Donenfeld 		ret = write_pool_user(&iter);
152422b0a222SJens Axboe 		if (unlikely(ret < 0))
152522b0a222SJens Axboe 			return ret;
152622b0a222SJens Axboe 		/* Since we're crediting, enforce that it was all written into the pool. */
152722b0a222SJens Axboe 		if (unlikely(ret != len))
152822b0a222SJens Axboe 			return -EFAULT;
1529e85c0fc1SJason A. Donenfeld 		credit_init_bits(ent_count);
1530a49c010eSJason A. Donenfeld 		return 0;
153122b0a222SJens Axboe 	}
15321da177e4SLinus Torvalds 	case RNDZAPENTCNT:
15331da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1534e85c0fc1SJason A. Donenfeld 		/* No longer has any effect. */
15351da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
15361da177e4SLinus Torvalds 			return -EPERM;
15371da177e4SLinus Torvalds 		return 0;
1538d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1539d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1540d848e5f8STheodore Ts'o 			return -EPERM;
1541a96cfe2dSJason A. Donenfeld 		if (!crng_ready())
1542d848e5f8STheodore Ts'o 			return -ENODATA;
15439148de31SJason A. Donenfeld 		crng_reseed(NULL);
1544d848e5f8STheodore Ts'o 		return 0;
15451da177e4SLinus Torvalds 	default:
15461da177e4SLinus Torvalds 		return -EINVAL;
15471da177e4SLinus Torvalds 	}
15481da177e4SLinus Torvalds }
15491da177e4SLinus Torvalds 
15509a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
15519a6f70bbSJeff Dike {
15529a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
15539a6f70bbSJeff Dike }
15549a6f70bbSJeff Dike 
15552b8693c0SArjan van de Ven const struct file_operations random_fops = {
15561b388e77SJens Axboe 	.read_iter = random_read_iter,
155722b0a222SJens Axboe 	.write_iter = random_write_iter,
1558a11e1d43SLinus Torvalds 	.poll = random_poll,
155943ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1560507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
15619a6f70bbSJeff Dike 	.fasync = random_fasync,
15626038f373SArnd Bergmann 	.llseek = noop_llseek,
1563b0072734SDavid Howells 	.splice_read = copy_splice_read,
156479025e72SJens Axboe 	.splice_write = iter_file_splice_write,
15651da177e4SLinus Torvalds };
15661da177e4SLinus Torvalds 
15670313bc27SLinus Torvalds const struct file_operations urandom_fops = {
15681b388e77SJens Axboe 	.read_iter = urandom_read_iter,
156922b0a222SJens Axboe 	.write_iter = random_write_iter,
15700313bc27SLinus Torvalds 	.unlocked_ioctl = random_ioctl,
15710313bc27SLinus Torvalds 	.compat_ioctl = compat_ptr_ioctl,
15720313bc27SLinus Torvalds 	.fasync = random_fasync,
15730313bc27SLinus Torvalds 	.llseek = noop_llseek,
1574b0072734SDavid Howells 	.splice_read = copy_splice_read,
157579025e72SJens Axboe 	.splice_write = iter_file_splice_write,
15760313bc27SLinus Torvalds };
15770313bc27SLinus Torvalds 
15780deff3c4SJason A. Donenfeld 
15791da177e4SLinus Torvalds /********************************************************************
15801da177e4SLinus Torvalds  *
15810deff3c4SJason A. Donenfeld  * Sysctl interface.
15820deff3c4SJason A. Donenfeld  *
15830deff3c4SJason A. Donenfeld  * These are partly unused legacy knobs with dummy values to not break
15840deff3c4SJason A. Donenfeld  * userspace and partly still useful things. They are usually accessible
15850deff3c4SJason A. Donenfeld  * in /proc/sys/kernel/random/ and are as follows:
15860deff3c4SJason A. Donenfeld  *
15870deff3c4SJason A. Donenfeld  * - boot_id - a UUID representing the current boot.
15880deff3c4SJason A. Donenfeld  *
15890deff3c4SJason A. Donenfeld  * - uuid - a random UUID, different each time the file is read.
15900deff3c4SJason A. Donenfeld  *
15910deff3c4SJason A. Donenfeld  * - poolsize - the number of bits of entropy that the input pool can
15920deff3c4SJason A. Donenfeld  *   hold, tied to the POOL_BITS constant.
15930deff3c4SJason A. Donenfeld  *
15940deff3c4SJason A. Donenfeld  * - entropy_avail - the number of bits of entropy currently in the
15950deff3c4SJason A. Donenfeld  *   input pool. Always <= poolsize.
15960deff3c4SJason A. Donenfeld  *
15970deff3c4SJason A. Donenfeld  * - write_wakeup_threshold - the amount of entropy in the input pool
15980deff3c4SJason A. Donenfeld  *   below which write polls to /dev/random will unblock, requesting
1599e3d2c5e7SJason A. Donenfeld  *   more entropy, tied to the POOL_READY_BITS constant. It is writable
16000deff3c4SJason A. Donenfeld  *   to avoid breaking old userspaces, but writing to it does not
16010deff3c4SJason A. Donenfeld  *   change any behavior of the RNG.
16020deff3c4SJason A. Donenfeld  *
1603d0efdf35SJason A. Donenfeld  * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
16040deff3c4SJason A. Donenfeld  *   It is writable to avoid breaking old userspaces, but writing
16050deff3c4SJason A. Donenfeld  *   to it does not change any behavior of the RNG.
16061da177e4SLinus Torvalds  *
16071da177e4SLinus Torvalds  ********************************************************************/
16081da177e4SLinus Torvalds 
16091da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
16101da177e4SLinus Torvalds 
16111da177e4SLinus Torvalds #include <linux/sysctl.h>
16121da177e4SLinus Torvalds 
1613d0efdf35SJason A. Donenfeld static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
1614e3d2c5e7SJason A. Donenfeld static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
1615489c7fc4SJason A. Donenfeld static int sysctl_poolsize = POOL_BITS;
161664276a99SJason A. Donenfeld static u8 sysctl_bootid[UUID_SIZE];
16171da177e4SLinus Torvalds 
16181da177e4SLinus Torvalds /*
1619f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
16201da177e4SLinus Torvalds  * UUID. The difference is in whether table->data is NULL; if it is,
16211da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
16221da177e4SLinus Torvalds  */
1623*78eb4ea2SJoel Granados static int proc_do_uuid(const struct ctl_table *table, int write, void *buf,
1624248045b8SJason A. Donenfeld 			size_t *lenp, loff_t *ppos)
16251da177e4SLinus Torvalds {
162664276a99SJason A. Donenfeld 	u8 tmp_uuid[UUID_SIZE], *uuid;
162764276a99SJason A. Donenfeld 	char uuid_string[UUID_STRING_LEN + 1];
162864276a99SJason A. Donenfeld 	struct ctl_table fake_table = {
162964276a99SJason A. Donenfeld 		.data = uuid_string,
163064276a99SJason A. Donenfeld 		.maxlen = UUID_STRING_LEN
163164276a99SJason A. Donenfeld 	};
163264276a99SJason A. Donenfeld 
163364276a99SJason A. Donenfeld 	if (write)
163464276a99SJason A. Donenfeld 		return -EPERM;
16351da177e4SLinus Torvalds 
16361da177e4SLinus Torvalds 	uuid = table->data;
16371da177e4SLinus Torvalds 	if (!uuid) {
16381da177e4SLinus Torvalds 		uuid = tmp_uuid;
16391da177e4SLinus Torvalds 		generate_random_uuid(uuid);
164044e4360fSMathieu Desnoyers 	} else {
164144e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
164244e4360fSMathieu Desnoyers 
164344e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
164444e4360fSMathieu Desnoyers 		if (!uuid[8])
164544e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
164644e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
164744e4360fSMathieu Desnoyers 	}
16481da177e4SLinus Torvalds 
164964276a99SJason A. Donenfeld 	snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
1650a1940263SJason A. Donenfeld 	return proc_dostring(&fake_table, 0, buf, lenp, ppos);
16511da177e4SLinus Torvalds }
16521da177e4SLinus Torvalds 
165377553cf8SJason A. Donenfeld /* The same as proc_dointvec, but writes don't change anything. */
1654*78eb4ea2SJoel Granados static int proc_do_rointvec(const struct ctl_table *table, int write, void *buf,
165577553cf8SJason A. Donenfeld 			    size_t *lenp, loff_t *ppos)
165677553cf8SJason A. Donenfeld {
1657a1940263SJason A. Donenfeld 	return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
165877553cf8SJason A. Donenfeld }
165977553cf8SJason A. Donenfeld 
16605475e8f0SXiaoming Ni static struct ctl_table random_table[] = {
16611da177e4SLinus Torvalds 	{
16621da177e4SLinus Torvalds 		.procname	= "poolsize",
16631da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
16641da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16651da177e4SLinus Torvalds 		.mode		= 0444,
16666d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
16671da177e4SLinus Torvalds 	},
16681da177e4SLinus Torvalds 	{
16691da177e4SLinus Torvalds 		.procname	= "entropy_avail",
1670e85c0fc1SJason A. Donenfeld 		.data		= &input_pool.init_bits,
16711da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16721da177e4SLinus Torvalds 		.mode		= 0444,
1673c5704490SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
16741da177e4SLinus Torvalds 	},
16751da177e4SLinus Torvalds 	{
16761da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
16770deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_write_wakeup_bits,
16781da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16791da177e4SLinus Torvalds 		.mode		= 0644,
168077553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
16811da177e4SLinus Torvalds 	},
16821da177e4SLinus Torvalds 	{
1683f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
16840deff3c4SJason A. Donenfeld 		.data		= &sysctl_random_min_urandom_seed,
1685f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1686f5c2742cSTheodore Ts'o 		.mode		= 0644,
168777553cf8SJason A. Donenfeld 		.proc_handler	= proc_do_rointvec,
1688f5c2742cSTheodore Ts'o 	},
1689f5c2742cSTheodore Ts'o 	{
16901da177e4SLinus Torvalds 		.procname	= "boot_id",
16911da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
16921da177e4SLinus Torvalds 		.mode		= 0444,
16936d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16941da177e4SLinus Torvalds 	},
16951da177e4SLinus Torvalds 	{
16961da177e4SLinus Torvalds 		.procname	= "uuid",
16971da177e4SLinus Torvalds 		.mode		= 0444,
16986d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16991da177e4SLinus Torvalds 	},
17001da177e4SLinus Torvalds };
17015475e8f0SXiaoming Ni 
17025475e8f0SXiaoming Ni /*
17032f14062bSJason A. Donenfeld  * random_init() is called before sysctl_init(),
17042f14062bSJason A. Donenfeld  * so we cannot call register_sysctl_init() in random_init()
17055475e8f0SXiaoming Ni  */
17065475e8f0SXiaoming Ni static int __init random_sysctls_init(void)
17075475e8f0SXiaoming Ni {
17085475e8f0SXiaoming Ni 	register_sysctl_init("kernel/random", random_table);
17095475e8f0SXiaoming Ni 	return 0;
17105475e8f0SXiaoming Ni }
17115475e8f0SXiaoming Ni device_initcall(random_sysctls_init);
17120deff3c4SJason A. Donenfeld #endif
1713