xref: /linux/drivers/char/random.c (revision c30c575db4858f0bbe5e315ff2e529c782f33a1f)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * random.c -- A strong random number generator
31da177e4SLinus Torvalds  *
49f9eff85SJason A. Donenfeld  * Copyright (C) 2017-2022 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
5b169c13dSJason A. Donenfeld  *
69e95ce27SMatt Mackall  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
71da177e4SLinus Torvalds  *
81da177e4SLinus Torvalds  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
91da177e4SLinus Torvalds  * rights reserved.
101da177e4SLinus Torvalds  *
111da177e4SLinus Torvalds  * Redistribution and use in source and binary forms, with or without
121da177e4SLinus Torvalds  * modification, are permitted provided that the following conditions
131da177e4SLinus Torvalds  * are met:
141da177e4SLinus Torvalds  * 1. Redistributions of source code must retain the above copyright
151da177e4SLinus Torvalds  *    notice, and the entire permission notice in its entirety,
161da177e4SLinus Torvalds  *    including the disclaimer of warranties.
171da177e4SLinus Torvalds  * 2. Redistributions in binary form must reproduce the above copyright
181da177e4SLinus Torvalds  *    notice, this list of conditions and the following disclaimer in the
191da177e4SLinus Torvalds  *    documentation and/or other materials provided with the distribution.
201da177e4SLinus Torvalds  * 3. The name of the author may not be used to endorse or promote
211da177e4SLinus Torvalds  *    products derived from this software without specific prior
221da177e4SLinus Torvalds  *    written permission.
231da177e4SLinus Torvalds  *
241da177e4SLinus Torvalds  * ALTERNATIVELY, this product may be distributed under the terms of
251da177e4SLinus Torvalds  * the GNU General Public License, in which case the provisions of the GPL are
261da177e4SLinus Torvalds  * required INSTEAD OF the above restrictions.  (This clause is
271da177e4SLinus Torvalds  * necessary due to a potential bad interaction between the GPL and
281da177e4SLinus Torvalds  * the restrictions contained in a BSD-style copyright.)
291da177e4SLinus Torvalds  *
301da177e4SLinus Torvalds  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
311da177e4SLinus Torvalds  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
321da177e4SLinus Torvalds  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
331da177e4SLinus Torvalds  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
341da177e4SLinus Torvalds  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
351da177e4SLinus Torvalds  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
361da177e4SLinus Torvalds  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
371da177e4SLinus Torvalds  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
381da177e4SLinus Torvalds  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
391da177e4SLinus Torvalds  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
401da177e4SLinus Torvalds  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
411da177e4SLinus Torvalds  * DAMAGE.
421da177e4SLinus Torvalds  */
431da177e4SLinus Torvalds 
441da177e4SLinus Torvalds /*
451da177e4SLinus Torvalds  * Exported interfaces ---- output
461da177e4SLinus Torvalds  * ===============================
471da177e4SLinus Torvalds  *
4892e507d2SGeorge Spelvin  * There are four exported interfaces; two for use within the kernel,
49c0a8a61eSSchspa Shi  * and two for use from userspace.
501da177e4SLinus Torvalds  *
5192e507d2SGeorge Spelvin  * Exported interfaces ---- userspace output
5292e507d2SGeorge Spelvin  * -----------------------------------------
531da177e4SLinus Torvalds  *
5492e507d2SGeorge Spelvin  * The userspace interfaces are two character devices /dev/random and
551da177e4SLinus Torvalds  * /dev/urandom.  /dev/random is suitable for use when very high
561da177e4SLinus Torvalds  * quality randomness is desired (for example, for key generation or
571da177e4SLinus Torvalds  * one-time pads), as it will only return a maximum of the number of
581da177e4SLinus Torvalds  * bits of randomness (as estimated by the random number generator)
591da177e4SLinus Torvalds  * contained in the entropy pool.
601da177e4SLinus Torvalds  *
611da177e4SLinus Torvalds  * The /dev/urandom device does not have this limit, and will return
621da177e4SLinus Torvalds  * as many bytes as are requested.  As more and more random bytes are
631da177e4SLinus Torvalds  * requested without giving time for the entropy pool to recharge,
641da177e4SLinus Torvalds  * this will result in random numbers that are merely cryptographically
651da177e4SLinus Torvalds  * strong.  For many applications, however, this is acceptable.
661da177e4SLinus Torvalds  *
6792e507d2SGeorge Spelvin  * Exported interfaces ---- kernel output
6892e507d2SGeorge Spelvin  * --------------------------------------
6992e507d2SGeorge Spelvin  *
7092e507d2SGeorge Spelvin  * The primary kernel interface is
7192e507d2SGeorge Spelvin  *
7292e507d2SGeorge Spelvin  *	void get_random_bytes(void *buf, int nbytes);
7392e507d2SGeorge Spelvin  *
7492e507d2SGeorge Spelvin  * This interface will return the requested number of random bytes,
7592e507d2SGeorge Spelvin  * and place it in the requested buffer.  This is equivalent to a
7692e507d2SGeorge Spelvin  * read from /dev/urandom.
7792e507d2SGeorge Spelvin  *
7892e507d2SGeorge Spelvin  * For less critical applications, there are the functions:
7992e507d2SGeorge Spelvin  *
8092e507d2SGeorge Spelvin  *	u32 get_random_u32()
8192e507d2SGeorge Spelvin  *	u64 get_random_u64()
8292e507d2SGeorge Spelvin  *	unsigned int get_random_int()
8392e507d2SGeorge Spelvin  *	unsigned long get_random_long()
8492e507d2SGeorge Spelvin  *
8592e507d2SGeorge Spelvin  * These are produced by a cryptographic RNG seeded from get_random_bytes,
8692e507d2SGeorge Spelvin  * and so do not deplete the entropy pool as much.  These are recommended
8792e507d2SGeorge Spelvin  * for most in-kernel operations *if the result is going to be stored in
8892e507d2SGeorge Spelvin  * the kernel*.
8992e507d2SGeorge Spelvin  *
9092e507d2SGeorge Spelvin  * Specifically, the get_random_int() family do not attempt to do
9192e507d2SGeorge Spelvin  * "anti-backtracking".  If you capture the state of the kernel (e.g.
9292e507d2SGeorge Spelvin  * by snapshotting the VM), you can figure out previous get_random_int()
9392e507d2SGeorge Spelvin  * return values.  But if the value is stored in the kernel anyway,
9492e507d2SGeorge Spelvin  * this is not a problem.
9592e507d2SGeorge Spelvin  *
9692e507d2SGeorge Spelvin  * It *is* safe to expose get_random_int() output to attackers (e.g. as
9792e507d2SGeorge Spelvin  * network cookies); given outputs 1..n, it's not feasible to predict
9892e507d2SGeorge Spelvin  * outputs 0 or n+1.  The only concern is an attacker who breaks into
9992e507d2SGeorge Spelvin  * the kernel later; the get_random_int() engine is not reseeded as
10092e507d2SGeorge Spelvin  * often as the get_random_bytes() one.
10192e507d2SGeorge Spelvin  *
10292e507d2SGeorge Spelvin  * get_random_bytes() is needed for keys that need to stay secret after
10392e507d2SGeorge Spelvin  * they are erased from the kernel.  For example, any key that will
10492e507d2SGeorge Spelvin  * be wrapped and stored encrypted.  And session encryption keys: we'd
10592e507d2SGeorge Spelvin  * like to know that after the session is closed and the keys erased,
10692e507d2SGeorge Spelvin  * the plaintext is unrecoverable to someone who recorded the ciphertext.
10792e507d2SGeorge Spelvin  *
10892e507d2SGeorge Spelvin  * But for network ports/cookies, stack canaries, PRNG seeds, address
10992e507d2SGeorge Spelvin  * space layout randomization, session *authentication* keys, or other
11092e507d2SGeorge Spelvin  * applications where the sensitive data is stored in the kernel in
11192e507d2SGeorge Spelvin  * plaintext for as long as it's sensitive, the get_random_int() family
11292e507d2SGeorge Spelvin  * is just fine.
11392e507d2SGeorge Spelvin  *
11492e507d2SGeorge Spelvin  * Consider ASLR.  We want to keep the address space secret from an
11592e507d2SGeorge Spelvin  * outside attacker while the process is running, but once the address
11692e507d2SGeorge Spelvin  * space is torn down, it's of no use to an attacker any more.  And it's
11792e507d2SGeorge Spelvin  * stored in kernel data structures as long as it's alive, so worrying
11892e507d2SGeorge Spelvin  * about an attacker's ability to extrapolate it from the get_random_int()
11992e507d2SGeorge Spelvin  * CRNG is silly.
12092e507d2SGeorge Spelvin  *
12192e507d2SGeorge Spelvin  * Even some cryptographic keys are safe to generate with get_random_int().
12292e507d2SGeorge Spelvin  * In particular, keys for SipHash are generally fine.  Here, knowledge
12392e507d2SGeorge Spelvin  * of the key authorizes you to do something to a kernel object (inject
12492e507d2SGeorge Spelvin  * packets to a network connection, or flood a hash table), and the
12592e507d2SGeorge Spelvin  * key is stored with the object being protected.  Once it goes away,
12692e507d2SGeorge Spelvin  * we no longer care if anyone knows the key.
12792e507d2SGeorge Spelvin  *
12892e507d2SGeorge Spelvin  * prandom_u32()
12992e507d2SGeorge Spelvin  * -------------
13092e507d2SGeorge Spelvin  *
13192e507d2SGeorge Spelvin  * For even weaker applications, see the pseudorandom generator
13292e507d2SGeorge Spelvin  * prandom_u32(), prandom_max(), and prandom_bytes().  If the random
13392e507d2SGeorge Spelvin  * numbers aren't security-critical at all, these are *far* cheaper.
13492e507d2SGeorge Spelvin  * Useful for self-tests, random error simulation, randomized backoffs,
13592e507d2SGeorge Spelvin  * and any other application where you trust that nobody is trying to
13692e507d2SGeorge Spelvin  * maliciously mess with you by guessing the "random" numbers.
13792e507d2SGeorge Spelvin  *
1381da177e4SLinus Torvalds  * Exported interfaces ---- input
1391da177e4SLinus Torvalds  * ==============================
1401da177e4SLinus Torvalds  *
1411da177e4SLinus Torvalds  * The current exported interfaces for gathering environmental noise
1421da177e4SLinus Torvalds  * from the devices are:
1431da177e4SLinus Torvalds  *
144a2080a67SLinus Torvalds  *	void add_device_randomness(const void *buf, unsigned int size);
1451da177e4SLinus Torvalds  *	void add_input_randomness(unsigned int type, unsigned int code,
1461da177e4SLinus Torvalds  *                                unsigned int value);
147703f7066SSebastian Andrzej Siewior  *	void add_interrupt_randomness(int irq);
148442a4fffSJarod Wilson  *	void add_disk_randomness(struct gendisk *disk);
1492b6c6e3dSMark Brown  *	void add_hwgenerator_randomness(const char *buffer, size_t count,
1502b6c6e3dSMark Brown  *					size_t entropy);
1512b6c6e3dSMark Brown  *	void add_bootloader_randomness(const void *buf, unsigned int size);
1521da177e4SLinus Torvalds  *
153a2080a67SLinus Torvalds  * add_device_randomness() is for adding data to the random pool that
154a2080a67SLinus Torvalds  * is likely to differ between two devices (or possibly even per boot).
155a2080a67SLinus Torvalds  * This would be things like MAC addresses or serial numbers, or the
156a2080a67SLinus Torvalds  * read-out of the RTC. This does *not* add any actual entropy to the
157a2080a67SLinus Torvalds  * pool, but it initializes the pool to different values for devices
158a2080a67SLinus Torvalds  * that might otherwise be identical and have very little entropy
159a2080a67SLinus Torvalds  * available to them (particularly common in the embedded world).
160a2080a67SLinus Torvalds  *
1611da177e4SLinus Torvalds  * add_input_randomness() uses the input layer interrupt timing, as well as
1621da177e4SLinus Torvalds  * the event type information from the hardware.
1631da177e4SLinus Torvalds  *
164775f4b29STheodore Ts'o  * add_interrupt_randomness() uses the interrupt timing as random
165775f4b29STheodore Ts'o  * inputs to the entropy pool. Using the cycle counters and the irq source
166775f4b29STheodore Ts'o  * as inputs, it feeds the randomness roughly once a second.
167442a4fffSJarod Wilson  *
168442a4fffSJarod Wilson  * add_disk_randomness() uses what amounts to the seek time of block
169442a4fffSJarod Wilson  * layer request events, on a per-disk_devt basis, as input to the
170442a4fffSJarod Wilson  * entropy pool. Note that high-speed solid state drives with very low
171442a4fffSJarod Wilson  * seek times do not make for good sources of entropy, as their seek
172442a4fffSJarod Wilson  * times are usually fairly consistent.
1731da177e4SLinus Torvalds  *
1741da177e4SLinus Torvalds  * All of these routines try to estimate how many bits of randomness a
1751da177e4SLinus Torvalds  * particular randomness source.  They do this by keeping track of the
1761da177e4SLinus Torvalds  * first and second order deltas of the event timings.
1771da177e4SLinus Torvalds  *
1782b6c6e3dSMark Brown  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
1792b6c6e3dSMark Brown  * entropy as specified by the caller. If the entropy pool is full it will
1802b6c6e3dSMark Brown  * block until more entropy is needed.
1812b6c6e3dSMark Brown  *
1822b6c6e3dSMark Brown  * add_bootloader_randomness() is the same as add_hwgenerator_randomness() or
1832b6c6e3dSMark Brown  * add_device_randomness(), depending on whether or not the configuration
1842b6c6e3dSMark Brown  * option CONFIG_RANDOM_TRUST_BOOTLOADER is set.
1852b6c6e3dSMark Brown  *
1861da177e4SLinus Torvalds  * Ensuring unpredictability at system startup
1871da177e4SLinus Torvalds  * ============================================
1881da177e4SLinus Torvalds  *
1891da177e4SLinus Torvalds  * When any operating system starts up, it will go through a sequence
1901da177e4SLinus Torvalds  * of actions that are fairly predictable by an adversary, especially
1911da177e4SLinus Torvalds  * if the start-up does not involve interaction with a human operator.
1921da177e4SLinus Torvalds  * This reduces the actual number of bits of unpredictability in the
1931da177e4SLinus Torvalds  * entropy pool below the value in entropy_count.  In order to
1941da177e4SLinus Torvalds  * counteract this effect, it helps to carry information in the
1951da177e4SLinus Torvalds  * entropy pool across shut-downs and start-ups.  To do this, put the
1961da177e4SLinus Torvalds  * following lines an appropriate script which is run during the boot
1971da177e4SLinus Torvalds  * sequence:
1981da177e4SLinus Torvalds  *
1991da177e4SLinus Torvalds  *	echo "Initializing random number generator..."
2001da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
2011da177e4SLinus Torvalds  *	# Carry a random seed from start-up to start-up
2021da177e4SLinus Torvalds  *	# Load and then save the whole entropy pool
2031da177e4SLinus Torvalds  *	if [ -f $random_seed ]; then
2041da177e4SLinus Torvalds  *		cat $random_seed >/dev/urandom
2051da177e4SLinus Torvalds  *	else
2061da177e4SLinus Torvalds  *		touch $random_seed
2071da177e4SLinus Torvalds  *	fi
2081da177e4SLinus Torvalds  *	chmod 600 $random_seed
2091da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
2101da177e4SLinus Torvalds  *
2111da177e4SLinus Torvalds  * and the following lines in an appropriate script which is run as
2121da177e4SLinus Torvalds  * the system is shutdown:
2131da177e4SLinus Torvalds  *
2141da177e4SLinus Torvalds  *	# Carry a random seed from shut-down to start-up
2151da177e4SLinus Torvalds  *	# Save the whole entropy pool
2161da177e4SLinus Torvalds  *	echo "Saving random seed..."
2171da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
2181da177e4SLinus Torvalds  *	touch $random_seed
2191da177e4SLinus Torvalds  *	chmod 600 $random_seed
2201da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
2211da177e4SLinus Torvalds  *
2221da177e4SLinus Torvalds  * For example, on most modern systems using the System V init
2231da177e4SLinus Torvalds  * scripts, such code fragments would be found in
2241da177e4SLinus Torvalds  * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
2251da177e4SLinus Torvalds  * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
2261da177e4SLinus Torvalds  *
2271da177e4SLinus Torvalds  * Effectively, these commands cause the contents of the entropy pool
2281da177e4SLinus Torvalds  * to be saved at shut-down time and reloaded into the entropy pool at
2291da177e4SLinus Torvalds  * start-up.  (The 'dd' in the addition to the bootup script is to
2301da177e4SLinus Torvalds  * make sure that /etc/random-seed is different for every start-up,
2311da177e4SLinus Torvalds  * even if the system crashes without executing rc.0.)  Even with
2321da177e4SLinus Torvalds  * complete knowledge of the start-up activities, predicting the state
2331da177e4SLinus Torvalds  * of the entropy pool requires knowledge of the previous history of
2341da177e4SLinus Torvalds  * the system.
2351da177e4SLinus Torvalds  *
2361da177e4SLinus Torvalds  * Configuring the /dev/random driver under Linux
2371da177e4SLinus Torvalds  * ==============================================
2381da177e4SLinus Torvalds  *
2391da177e4SLinus Torvalds  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
2401da177e4SLinus Torvalds  * the /dev/mem major number (#1).  So if your system does not have
2411da177e4SLinus Torvalds  * /dev/random and /dev/urandom created already, they can be created
2421da177e4SLinus Torvalds  * by using the commands:
2431da177e4SLinus Torvalds  *
2441da177e4SLinus Torvalds  *	mknod /dev/random c 1 8
2451da177e4SLinus Torvalds  *	mknod /dev/urandom c 1 9
2461da177e4SLinus Torvalds  */
2471da177e4SLinus Torvalds 
24812cd53afSYangtao Li #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
24912cd53afSYangtao Li 
2501da177e4SLinus Torvalds #include <linux/utsname.h>
2511da177e4SLinus Torvalds #include <linux/module.h>
2521da177e4SLinus Torvalds #include <linux/kernel.h>
2531da177e4SLinus Torvalds #include <linux/major.h>
2541da177e4SLinus Torvalds #include <linux/string.h>
2551da177e4SLinus Torvalds #include <linux/fcntl.h>
2561da177e4SLinus Torvalds #include <linux/slab.h>
2571da177e4SLinus Torvalds #include <linux/random.h>
2581da177e4SLinus Torvalds #include <linux/poll.h>
2591da177e4SLinus Torvalds #include <linux/init.h>
2601da177e4SLinus Torvalds #include <linux/fs.h>
2611da177e4SLinus Torvalds #include <linux/genhd.h>
2621da177e4SLinus Torvalds #include <linux/interrupt.h>
26327ac792cSAndrea Righi #include <linux/mm.h>
264dd0f0cf5SMichael Ellerman #include <linux/nodemask.h>
2651da177e4SLinus Torvalds #include <linux/spinlock.h>
266c84dbf61STorsten Duwe #include <linux/kthread.h>
2671da177e4SLinus Torvalds #include <linux/percpu.h>
268775f4b29STheodore Ts'o #include <linux/ptrace.h>
2696265e169STheodore Ts'o #include <linux/workqueue.h>
270d178a1ebSYinghai Lu #include <linux/irq.h>
2714e00b339STheodore Ts'o #include <linux/ratelimit.h>
272c6e9d6f3STheodore Ts'o #include <linux/syscalls.h>
273c6e9d6f3STheodore Ts'o #include <linux/completion.h>
2748da4b8c4SAndy Shevchenko #include <linux/uuid.h>
2751ca1b917SEric Biggers #include <crypto/chacha.h>
2769f9eff85SJason A. Donenfeld #include <crypto/blake2s.h>
277d178a1ebSYinghai Lu 
2781da177e4SLinus Torvalds #include <asm/processor.h>
2797c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
2801da177e4SLinus Torvalds #include <asm/irq.h>
281775f4b29STheodore Ts'o #include <asm/irq_regs.h>
2821da177e4SLinus Torvalds #include <asm/io.h>
2831da177e4SLinus Torvalds 
28400ce1db1STheodore Ts'o #define CREATE_TRACE_POINTS
28500ce1db1STheodore Ts'o #include <trace/events/random.h>
28600ce1db1STheodore Ts'o 
28743759d4fSTheodore Ts'o /* #define ADD_INTERRUPT_BENCH */
28843759d4fSTheodore Ts'o 
289c5704490SJason A. Donenfeld enum {
2906e8ec255SJason A. Donenfeld 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
291c5704490SJason A. Donenfeld 	POOL_MIN_BITS = POOL_BITS /* No point in settling for less. */
2921da177e4SLinus Torvalds };
2931da177e4SLinus Torvalds 
2941da177e4SLinus Torvalds /*
2951da177e4SLinus Torvalds  * Static global variables
2961da177e4SLinus Torvalds  */
297a11e1d43SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
2989a6f70bbSJeff Dike static struct fasync_struct *fasync;
2991da177e4SLinus Torvalds 
300205a525cSHerbert Xu static DEFINE_SPINLOCK(random_ready_list_lock);
301205a525cSHerbert Xu static LIST_HEAD(random_ready_list);
302205a525cSHerbert Xu 
303e192be9dSTheodore Ts'o struct crng_state {
304d38bb085SJason A. Donenfeld 	u32 state[16];
305e192be9dSTheodore Ts'o 	unsigned long init_time;
306e192be9dSTheodore Ts'o 	spinlock_t lock;
307e192be9dSTheodore Ts'o };
308e192be9dSTheodore Ts'o 
309764ed189SRasmus Villemoes static struct crng_state primary_crng = {
310e192be9dSTheodore Ts'o 	.lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
31196562f28SDominik Brodowski 	.state[0] = CHACHA_CONSTANT_EXPA,
31296562f28SDominik Brodowski 	.state[1] = CHACHA_CONSTANT_ND_3,
31396562f28SDominik Brodowski 	.state[2] = CHACHA_CONSTANT_2_BY,
31496562f28SDominik Brodowski 	.state[3] = CHACHA_CONSTANT_TE_K,
315e192be9dSTheodore Ts'o };
316e192be9dSTheodore Ts'o 
317e192be9dSTheodore Ts'o /*
318e192be9dSTheodore Ts'o  * crng_init =  0 --> Uninitialized
319e192be9dSTheodore Ts'o  *		1 --> Initialized
320e192be9dSTheodore Ts'o  *		2 --> Initialized from input_pool
321e192be9dSTheodore Ts'o  *
322e192be9dSTheodore Ts'o  * crng_init is protected by primary_crng->lock, and only increases
323e192be9dSTheodore Ts'o  * its value (from 0->1->2).
324e192be9dSTheodore Ts'o  */
325e192be9dSTheodore Ts'o static int crng_init = 0;
32643838a23STheodore Ts'o #define crng_ready() (likely(crng_init > 1))
327e192be9dSTheodore Ts'o static int crng_init_cnt = 0;
3281ca1b917SEric Biggers #define CRNG_INIT_CNT_THRESH (2 * CHACHA_KEY_SIZE)
329a9412d51SJason A. Donenfeld static void extract_crng(u8 out[CHACHA_BLOCK_SIZE]);
330a9412d51SJason A. Donenfeld static void crng_backtrack_protect(u8 tmp[CHACHA_BLOCK_SIZE], int used);
331e192be9dSTheodore Ts'o static void process_random_ready_list(void);
332eecabf56STheodore Ts'o static void _get_random_bytes(void *buf, int nbytes);
333e192be9dSTheodore Ts'o 
3344e00b339STheodore Ts'o static struct ratelimit_state unseeded_warning =
3354e00b339STheodore Ts'o 	RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
3364e00b339STheodore Ts'o static struct ratelimit_state urandom_warning =
3374e00b339STheodore Ts'o 	RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
3384e00b339STheodore Ts'o 
3394e00b339STheodore Ts'o static int ratelimit_disable __read_mostly;
3404e00b339STheodore Ts'o 
3414e00b339STheodore Ts'o module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
3424e00b339STheodore Ts'o MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
3434e00b339STheodore Ts'o 
3441da177e4SLinus Torvalds /**********************************************************************
3451da177e4SLinus Torvalds  *
3461da177e4SLinus Torvalds  * OS independent entropy store.   Here are the functions which handle
3471da177e4SLinus Torvalds  * storing entropy in an entropy pool.
3481da177e4SLinus Torvalds  *
3491da177e4SLinus Torvalds  **********************************************************************/
3501da177e4SLinus Torvalds 
35190ed1e67SJason A. Donenfeld static struct {
3526e8ec255SJason A. Donenfeld 	struct blake2s_state hash;
35343358209SMatt Mackall 	spinlock_t lock;
354cda796a3SMatt Mackall 	int entropy_count;
35590ed1e67SJason A. Donenfeld } input_pool = {
3566e8ec255SJason A. Donenfeld 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
3576e8ec255SJason A. Donenfeld 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
3586e8ec255SJason A. Donenfeld 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
3596e8ec255SJason A. Donenfeld 	.hash.outlen = BLAKE2S_HASH_SIZE,
360eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
3611da177e4SLinus Torvalds };
3621da177e4SLinus Torvalds 
3639c07f578SJason A. Donenfeld static void extract_entropy(void *buf, size_t nbytes);
36490ed1e67SJason A. Donenfeld 
365a9412d51SJason A. Donenfeld static void crng_reseed(void);
36690ed1e67SJason A. Donenfeld 
3671da177e4SLinus Torvalds /*
368e68e5b66SMatt Mackall  * This function adds bytes into the entropy "pool".  It does not
3691da177e4SLinus Torvalds  * update the entropy estimate.  The caller should call
370adc782daSMatt Mackall  * credit_entropy_bits if this is appropriate.
3711da177e4SLinus Torvalds  */
37290ed1e67SJason A. Donenfeld static void _mix_pool_bytes(const void *in, int nbytes)
3731da177e4SLinus Torvalds {
3746e8ec255SJason A. Donenfeld 	blake2s_update(&input_pool.hash, in, nbytes);
3751da177e4SLinus Torvalds }
3761da177e4SLinus Torvalds 
37790ed1e67SJason A. Donenfeld static void __mix_pool_bytes(const void *in, int nbytes)
37800ce1db1STheodore Ts'o {
37990ed1e67SJason A. Donenfeld 	trace_mix_pool_bytes_nolock(nbytes, _RET_IP_);
38090ed1e67SJason A. Donenfeld 	_mix_pool_bytes(in, nbytes);
38100ce1db1STheodore Ts'o }
38200ce1db1STheodore Ts'o 
38390ed1e67SJason A. Donenfeld static void mix_pool_bytes(const void *in, int nbytes)
3841da177e4SLinus Torvalds {
385902c098aSTheodore Ts'o 	unsigned long flags;
386902c098aSTheodore Ts'o 
38790ed1e67SJason A. Donenfeld 	trace_mix_pool_bytes(nbytes, _RET_IP_);
38890ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
38990ed1e67SJason A. Donenfeld 	_mix_pool_bytes(in, nbytes);
39090ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
3911da177e4SLinus Torvalds }
3921da177e4SLinus Torvalds 
393775f4b29STheodore Ts'o struct fast_pool {
394d38bb085SJason A. Donenfeld 	u32 pool[4];
395775f4b29STheodore Ts'o 	unsigned long last;
396d38bb085SJason A. Donenfeld 	u16 reg_idx;
397d38bb085SJason A. Donenfeld 	u8 count;
398775f4b29STheodore Ts'o };
399775f4b29STheodore Ts'o 
400775f4b29STheodore Ts'o /*
401775f4b29STheodore Ts'o  * This is a fast mixing routine used by the interrupt randomness
402775f4b29STheodore Ts'o  * collector.  It's hardcoded for an 128 bit pool and assumes that any
403775f4b29STheodore Ts'o  * locks that might be needed are taken by the caller.
404775f4b29STheodore Ts'o  */
40543759d4fSTheodore Ts'o static void fast_mix(struct fast_pool *f)
406775f4b29STheodore Ts'o {
407d38bb085SJason A. Donenfeld 	u32 a = f->pool[0],	b = f->pool[1];
408d38bb085SJason A. Donenfeld 	u32 c = f->pool[2],	d = f->pool[3];
409775f4b29STheodore Ts'o 
41043759d4fSTheodore Ts'o 	a += b;			c += d;
41119acc77aSGeorge Spelvin 	b = rol32(b, 6);	d = rol32(d, 27);
41243759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
413655b2264STheodore Ts'o 
41443759d4fSTheodore Ts'o 	a += b;			c += d;
41519acc77aSGeorge Spelvin 	b = rol32(b, 16);	d = rol32(d, 14);
41643759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
41743759d4fSTheodore Ts'o 
41843759d4fSTheodore Ts'o 	a += b;			c += d;
41919acc77aSGeorge Spelvin 	b = rol32(b, 6);	d = rol32(d, 27);
42043759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
42143759d4fSTheodore Ts'o 
42243759d4fSTheodore Ts'o 	a += b;			c += d;
42319acc77aSGeorge Spelvin 	b = rol32(b, 16);	d = rol32(d, 14);
42443759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
42543759d4fSTheodore Ts'o 
42643759d4fSTheodore Ts'o 	f->pool[0] = a;  f->pool[1] = b;
42743759d4fSTheodore Ts'o 	f->pool[2] = c;  f->pool[3] = d;
428655b2264STheodore Ts'o 	f->count++;
429775f4b29STheodore Ts'o }
430775f4b29STheodore Ts'o 
431205a525cSHerbert Xu static void process_random_ready_list(void)
432205a525cSHerbert Xu {
433205a525cSHerbert Xu 	unsigned long flags;
434205a525cSHerbert Xu 	struct random_ready_callback *rdy, *tmp;
435205a525cSHerbert Xu 
436205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
437205a525cSHerbert Xu 	list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
438205a525cSHerbert Xu 		struct module *owner = rdy->owner;
439205a525cSHerbert Xu 
440205a525cSHerbert Xu 		list_del_init(&rdy->list);
441205a525cSHerbert Xu 		rdy->func(rdy);
442205a525cSHerbert Xu 		module_put(owner);
443205a525cSHerbert Xu 	}
444205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
445205a525cSHerbert Xu }
446205a525cSHerbert Xu 
44790ed1e67SJason A. Donenfeld static void credit_entropy_bits(int nbits)
4481da177e4SLinus Torvalds {
4499c07f578SJason A. Donenfeld 	int entropy_count, orig;
45018263c4eSJason A. Donenfeld 
451a49c010eSJason A. Donenfeld 	if (nbits <= 0)
452adc782daSMatt Mackall 		return;
453adc782daSMatt Mackall 
454a49c010eSJason A. Donenfeld 	nbits = min(nbits, POOL_BITS);
455a49c010eSJason A. Donenfeld 
45630e37ec5SH. Peter Anvin 	do {
457c5704490SJason A. Donenfeld 		orig = READ_ONCE(input_pool.entropy_count);
458c5704490SJason A. Donenfeld 		entropy_count = min(POOL_BITS, orig + nbits);
459c5704490SJason A. Donenfeld 	} while (cmpxchg(&input_pool.entropy_count, orig, entropy_count) != orig);
46030e37ec5SH. Peter Anvin 
461c5704490SJason A. Donenfeld 	trace_credit_entropy_bits(nbits, entropy_count, _RET_IP_);
46200ce1db1STheodore Ts'o 
463c5704490SJason A. Donenfeld 	if (crng_init < 2 && entropy_count >= POOL_MIN_BITS)
464a9412d51SJason A. Donenfeld 		crng_reseed();
4651da177e4SLinus Torvalds }
4661da177e4SLinus Torvalds 
4671da177e4SLinus Torvalds /*********************************************************************
4681da177e4SLinus Torvalds  *
469e192be9dSTheodore Ts'o  * CRNG using CHACHA20
470e192be9dSTheodore Ts'o  *
471e192be9dSTheodore Ts'o  *********************************************************************/
472e192be9dSTheodore Ts'o 
473e192be9dSTheodore Ts'o #define CRNG_RESEED_INTERVAL (300 * HZ)
474e192be9dSTheodore Ts'o 
475e192be9dSTheodore Ts'o static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
476e192be9dSTheodore Ts'o 
477b169c13dSJason A. Donenfeld static void invalidate_batched_entropy(void);
478b169c13dSJason A. Donenfeld 
479dc12baacSTheodore Ts'o /*
480dc12baacSTheodore Ts'o  * crng_fast_load() can be called by code in the interrupt service
48173c7733fSJason A. Donenfeld  * path.  So we can't afford to dilly-dally. Returns the number of
48273c7733fSJason A. Donenfeld  * bytes processed from cp.
483dc12baacSTheodore Ts'o  */
484d38bb085SJason A. Donenfeld static size_t crng_fast_load(const u8 *cp, size_t len)
485e192be9dSTheodore Ts'o {
486e192be9dSTheodore Ts'o 	unsigned long flags;
487d38bb085SJason A. Donenfeld 	u8 *p;
48873c7733fSJason A. Donenfeld 	size_t ret = 0;
489e192be9dSTheodore Ts'o 
490e192be9dSTheodore Ts'o 	if (!spin_trylock_irqsave(&primary_crng.lock, flags))
491e192be9dSTheodore Ts'o 		return 0;
49243838a23STheodore Ts'o 	if (crng_init != 0) {
493e192be9dSTheodore Ts'o 		spin_unlock_irqrestore(&primary_crng.lock, flags);
494e192be9dSTheodore Ts'o 		return 0;
495e192be9dSTheodore Ts'o 	}
496d38bb085SJason A. Donenfeld 	p = (u8 *)&primary_crng.state[4];
497e192be9dSTheodore Ts'o 	while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
4981ca1b917SEric Biggers 		p[crng_init_cnt % CHACHA_KEY_SIZE] ^= *cp;
49973c7733fSJason A. Donenfeld 		cp++; crng_init_cnt++; len--; ret++;
500e192be9dSTheodore Ts'o 	}
501e192be9dSTheodore Ts'o 	if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
502b169c13dSJason A. Donenfeld 		invalidate_batched_entropy();
503e192be9dSTheodore Ts'o 		crng_init = 1;
504e192be9dSTheodore Ts'o 	}
5057c2fe2b3SDominik Brodowski 	spin_unlock_irqrestore(&primary_crng.lock, flags);
5067c2fe2b3SDominik Brodowski 	if (crng_init == 1)
5077c2fe2b3SDominik Brodowski 		pr_notice("fast init done\n");
50873c7733fSJason A. Donenfeld 	return ret;
509e192be9dSTheodore Ts'o }
510e192be9dSTheodore Ts'o 
511dc12baacSTheodore Ts'o /*
512dc12baacSTheodore Ts'o  * crng_slow_load() is called by add_device_randomness, which has two
513dc12baacSTheodore Ts'o  * attributes.  (1) We can't trust the buffer passed to it is
514dc12baacSTheodore Ts'o  * guaranteed to be unpredictable (so it might not have any entropy at
515dc12baacSTheodore Ts'o  * all), and (2) it doesn't have the performance constraints of
516dc12baacSTheodore Ts'o  * crng_fast_load().
517dc12baacSTheodore Ts'o  *
518dc12baacSTheodore Ts'o  * So we do something more comprehensive which is guaranteed to touch
519dc12baacSTheodore Ts'o  * all of the primary_crng's state, and which uses a LFSR with a
520dc12baacSTheodore Ts'o  * period of 255 as part of the mixing algorithm.  Finally, we do
521dc12baacSTheodore Ts'o  * *not* advance crng_init_cnt since buffer we may get may be something
522dc12baacSTheodore Ts'o  * like a fixed DMI table (for example), which might very well be
523dc12baacSTheodore Ts'o  * unique to the machine, but is otherwise unvarying.
524dc12baacSTheodore Ts'o  */
525d38bb085SJason A. Donenfeld static int crng_slow_load(const u8 *cp, size_t len)
526dc12baacSTheodore Ts'o {
527dc12baacSTheodore Ts'o 	unsigned long flags;
528d38bb085SJason A. Donenfeld 	static u8 lfsr = 1;
529d38bb085SJason A. Donenfeld 	u8 tmp;
530d38bb085SJason A. Donenfeld 	unsigned int i, max = CHACHA_KEY_SIZE;
531d38bb085SJason A. Donenfeld 	const u8 *src_buf = cp;
532d38bb085SJason A. Donenfeld 	u8 *dest_buf = (u8 *)&primary_crng.state[4];
533dc12baacSTheodore Ts'o 
534dc12baacSTheodore Ts'o 	if (!spin_trylock_irqsave(&primary_crng.lock, flags))
535dc12baacSTheodore Ts'o 		return 0;
536dc12baacSTheodore Ts'o 	if (crng_init != 0) {
537dc12baacSTheodore Ts'o 		spin_unlock_irqrestore(&primary_crng.lock, flags);
538dc12baacSTheodore Ts'o 		return 0;
539dc12baacSTheodore Ts'o 	}
540dc12baacSTheodore Ts'o 	if (len > max)
541dc12baacSTheodore Ts'o 		max = len;
542dc12baacSTheodore Ts'o 
543dc12baacSTheodore Ts'o 	for (i = 0; i < max; i++) {
544dc12baacSTheodore Ts'o 		tmp = lfsr;
545dc12baacSTheodore Ts'o 		lfsr >>= 1;
546dc12baacSTheodore Ts'o 		if (tmp & 1)
547dc12baacSTheodore Ts'o 			lfsr ^= 0xE1;
5481ca1b917SEric Biggers 		tmp = dest_buf[i % CHACHA_KEY_SIZE];
5491ca1b917SEric Biggers 		dest_buf[i % CHACHA_KEY_SIZE] ^= src_buf[i % len] ^ lfsr;
550dc12baacSTheodore Ts'o 		lfsr += (tmp << 3) | (tmp >> 5);
551dc12baacSTheodore Ts'o 	}
552dc12baacSTheodore Ts'o 	spin_unlock_irqrestore(&primary_crng.lock, flags);
553dc12baacSTheodore Ts'o 	return 1;
554dc12baacSTheodore Ts'o }
555dc12baacSTheodore Ts'o 
556a9412d51SJason A. Donenfeld static void crng_reseed(void)
557e192be9dSTheodore Ts'o {
558e192be9dSTheodore Ts'o 	unsigned long flags;
559a9412d51SJason A. Donenfeld 	int i, entropy_count;
560e192be9dSTheodore Ts'o 	union {
561d38bb085SJason A. Donenfeld 		u8 block[CHACHA_BLOCK_SIZE];
562d38bb085SJason A. Donenfeld 		u32 key[8];
563e192be9dSTheodore Ts'o 	} buf;
564e192be9dSTheodore Ts'o 
5659c07f578SJason A. Donenfeld 	do {
5669c07f578SJason A. Donenfeld 		entropy_count = READ_ONCE(input_pool.entropy_count);
567c5704490SJason A. Donenfeld 		if (entropy_count < POOL_MIN_BITS)
568e192be9dSTheodore Ts'o 			return;
5699c07f578SJason A. Donenfeld 	} while (cmpxchg(&input_pool.entropy_count, entropy_count, 0) != entropy_count);
5709c07f578SJason A. Donenfeld 	extract_entropy(buf.key, sizeof(buf.key));
5719c07f578SJason A. Donenfeld 	wake_up_interruptible(&random_write_wait);
5729c07f578SJason A. Donenfeld 	kill_fasync(&fasync, SIGIO, POLL_OUT);
573a9412d51SJason A. Donenfeld 
574a9412d51SJason A. Donenfeld 	spin_lock_irqsave(&primary_crng.lock, flags);
57528f425e5SJason A. Donenfeld 	for (i = 0; i < 8; i++)
576a9412d51SJason A. Donenfeld 		primary_crng.state[i + 4] ^= buf.key[i];
577e192be9dSTheodore Ts'o 	memzero_explicit(&buf, sizeof(buf));
578a9412d51SJason A. Donenfeld 	WRITE_ONCE(primary_crng.init_time, jiffies);
579a9412d51SJason A. Donenfeld 	spin_unlock_irqrestore(&primary_crng.lock, flags);
580a9412d51SJason A. Donenfeld 	if (crng_init < 2) {
581a9412d51SJason A. Donenfeld 		invalidate_batched_entropy();
582a9412d51SJason A. Donenfeld 		crng_init = 2;
583a9412d51SJason A. Donenfeld 		process_random_ready_list();
584a9412d51SJason A. Donenfeld 		wake_up_interruptible(&crng_init_wait);
585a9412d51SJason A. Donenfeld 		kill_fasync(&fasync, SIGIO, POLL_IN);
586a9412d51SJason A. Donenfeld 		pr_notice("crng init done\n");
587a9412d51SJason A. Donenfeld 		if (unseeded_warning.missed) {
588a9412d51SJason A. Donenfeld 			pr_notice("%d get_random_xx warning(s) missed due to ratelimiting\n",
589a9412d51SJason A. Donenfeld 				  unseeded_warning.missed);
590a9412d51SJason A. Donenfeld 			unseeded_warning.missed = 0;
591e192be9dSTheodore Ts'o 		}
592a9412d51SJason A. Donenfeld 		if (urandom_warning.missed) {
593a9412d51SJason A. Donenfeld 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
594a9412d51SJason A. Donenfeld 				  urandom_warning.missed);
595a9412d51SJason A. Donenfeld 			urandom_warning.missed = 0;
596009ba856SEric Biggers 		}
597a9412d51SJason A. Donenfeld 	}
598e192be9dSTheodore Ts'o }
599e192be9dSTheodore Ts'o 
600d38bb085SJason A. Donenfeld static void extract_crng(u8 out[CHACHA_BLOCK_SIZE])
6011e7f583aSTheodore Ts'o {
602a9412d51SJason A. Donenfeld 	unsigned long flags, init_time;
603a9412d51SJason A. Donenfeld 
604a9412d51SJason A. Donenfeld 	if (crng_ready()) {
605a9412d51SJason A. Donenfeld 		init_time = READ_ONCE(primary_crng.init_time);
606a9412d51SJason A. Donenfeld 		if (time_after(jiffies, init_time + CRNG_RESEED_INTERVAL))
607a9412d51SJason A. Donenfeld 			crng_reseed();
608a9412d51SJason A. Donenfeld 	}
609a9412d51SJason A. Donenfeld 	spin_lock_irqsave(&primary_crng.lock, flags);
610a9412d51SJason A. Donenfeld 	chacha20_block(&primary_crng.state[0], out);
611a9412d51SJason A. Donenfeld 	if (primary_crng.state[12] == 0)
612a9412d51SJason A. Donenfeld 		primary_crng.state[13]++;
613a9412d51SJason A. Donenfeld 	spin_unlock_irqrestore(&primary_crng.lock, flags);
6141e7f583aSTheodore Ts'o }
6151e7f583aSTheodore Ts'o 
616c92e040dSTheodore Ts'o /*
617c92e040dSTheodore Ts'o  * Use the leftover bytes from the CRNG block output (if there is
618c92e040dSTheodore Ts'o  * enough) to mutate the CRNG key to provide backtracking protection.
619c92e040dSTheodore Ts'o  */
620a9412d51SJason A. Donenfeld static void crng_backtrack_protect(u8 tmp[CHACHA_BLOCK_SIZE], int used)
621c92e040dSTheodore Ts'o {
622c92e040dSTheodore Ts'o 	unsigned long flags;
623d38bb085SJason A. Donenfeld 	u32 *s, *d;
624c92e040dSTheodore Ts'o 	int i;
625c92e040dSTheodore Ts'o 
626d38bb085SJason A. Donenfeld 	used = round_up(used, sizeof(u32));
6271ca1b917SEric Biggers 	if (used + CHACHA_KEY_SIZE > CHACHA_BLOCK_SIZE) {
628c92e040dSTheodore Ts'o 		extract_crng(tmp);
629c92e040dSTheodore Ts'o 		used = 0;
630c92e040dSTheodore Ts'o 	}
631a9412d51SJason A. Donenfeld 	spin_lock_irqsave(&primary_crng.lock, flags);
632d38bb085SJason A. Donenfeld 	s = (u32 *)&tmp[used];
633a9412d51SJason A. Donenfeld 	d = &primary_crng.state[4];
634c92e040dSTheodore Ts'o 	for (i = 0; i < 8; i++)
635c92e040dSTheodore Ts'o 		*d++ ^= *s++;
636a9412d51SJason A. Donenfeld 	spin_unlock_irqrestore(&primary_crng.lock, flags);
637c92e040dSTheodore Ts'o }
638c92e040dSTheodore Ts'o 
639e192be9dSTheodore Ts'o static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
640e192be9dSTheodore Ts'o {
6411ca1b917SEric Biggers 	ssize_t ret = 0, i = CHACHA_BLOCK_SIZE;
642d38bb085SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
643e192be9dSTheodore Ts'o 	int large_request = (nbytes > 256);
644e192be9dSTheodore Ts'o 
645e192be9dSTheodore Ts'o 	while (nbytes) {
646e192be9dSTheodore Ts'o 		if (large_request && need_resched()) {
647e192be9dSTheodore Ts'o 			if (signal_pending(current)) {
648e192be9dSTheodore Ts'o 				if (ret == 0)
649e192be9dSTheodore Ts'o 					ret = -ERESTARTSYS;
650e192be9dSTheodore Ts'o 				break;
651e192be9dSTheodore Ts'o 			}
652e192be9dSTheodore Ts'o 			schedule();
653e192be9dSTheodore Ts'o 		}
654e192be9dSTheodore Ts'o 
655e192be9dSTheodore Ts'o 		extract_crng(tmp);
6561ca1b917SEric Biggers 		i = min_t(int, nbytes, CHACHA_BLOCK_SIZE);
657e192be9dSTheodore Ts'o 		if (copy_to_user(buf, tmp, i)) {
658e192be9dSTheodore Ts'o 			ret = -EFAULT;
659e192be9dSTheodore Ts'o 			break;
660e192be9dSTheodore Ts'o 		}
661e192be9dSTheodore Ts'o 
662e192be9dSTheodore Ts'o 		nbytes -= i;
663e192be9dSTheodore Ts'o 		buf += i;
664e192be9dSTheodore Ts'o 		ret += i;
665e192be9dSTheodore Ts'o 	}
666c92e040dSTheodore Ts'o 	crng_backtrack_protect(tmp, i);
667e192be9dSTheodore Ts'o 
668e192be9dSTheodore Ts'o 	/* Wipe data just written to memory */
669e192be9dSTheodore Ts'o 	memzero_explicit(tmp, sizeof(tmp));
670e192be9dSTheodore Ts'o 
671e192be9dSTheodore Ts'o 	return ret;
672e192be9dSTheodore Ts'o }
673e192be9dSTheodore Ts'o 
674e192be9dSTheodore Ts'o /*********************************************************************
675e192be9dSTheodore Ts'o  *
6761da177e4SLinus Torvalds  * Entropy input management
6771da177e4SLinus Torvalds  *
6781da177e4SLinus Torvalds  *********************************************************************/
6791da177e4SLinus Torvalds 
6801da177e4SLinus Torvalds /* There is one of these per entropy source */
6811da177e4SLinus Torvalds struct timer_rand_state {
6821da177e4SLinus Torvalds 	cycles_t last_time;
6831da177e4SLinus Torvalds 	long last_delta, last_delta2;
6841da177e4SLinus Torvalds };
6851da177e4SLinus Torvalds 
686644008dfSTheodore Ts'o #define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
687644008dfSTheodore Ts'o 
688a2080a67SLinus Torvalds /*
689e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
690e192be9dSTheodore Ts'o  * initialize it.
691a2080a67SLinus Torvalds  *
692e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
693e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
694e192be9dSTheodore Ts'o  * identical devices.
695a2080a67SLinus Torvalds  */
696a2080a67SLinus Torvalds void add_device_randomness(const void *buf, unsigned int size)
697a2080a67SLinus Torvalds {
69861875f30STheodore Ts'o 	unsigned long time = random_get_entropy() ^ jiffies;
6993ef4cb2dSTheodore Ts'o 	unsigned long flags;
700a2080a67SLinus Torvalds 
701dc12baacSTheodore Ts'o 	if (!crng_ready() && size)
702dc12baacSTheodore Ts'o 		crng_slow_load(buf, size);
703ee7998c5SKees Cook 
7045910895fSTheodore Ts'o 	trace_add_device_randomness(size, _RET_IP_);
7053ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
70690ed1e67SJason A. Donenfeld 	_mix_pool_bytes(buf, size);
70790ed1e67SJason A. Donenfeld 	_mix_pool_bytes(&time, sizeof(time));
7083ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
709a2080a67SLinus Torvalds }
710a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
711a2080a67SLinus Torvalds 
712644008dfSTheodore Ts'o static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
7133060d6feSYinghai Lu 
7141da177e4SLinus Torvalds /*
7151da177e4SLinus Torvalds  * This function adds entropy to the entropy "pool" by using timing
7161da177e4SLinus Torvalds  * delays.  It uses the timer_rand_state structure to make an estimate
7171da177e4SLinus Torvalds  * of how many bits of entropy this call has added to the pool.
7181da177e4SLinus Torvalds  *
7191da177e4SLinus Torvalds  * The number "num" is also added to the pool - it should somehow describe
7201da177e4SLinus Torvalds  * the type of event which just happened.  This is currently 0-255 for
7211da177e4SLinus Torvalds  * keyboard scan codes, and 256 upwards for interrupts.
7221da177e4SLinus Torvalds  *
7231da177e4SLinus Torvalds  */
7241da177e4SLinus Torvalds static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
7251da177e4SLinus Torvalds {
7261da177e4SLinus Torvalds 	struct {
7271da177e4SLinus Torvalds 		long jiffies;
728d38bb085SJason A. Donenfeld 		unsigned int cycles;
729d38bb085SJason A. Donenfeld 		unsigned int num;
7301da177e4SLinus Torvalds 	} sample;
7311da177e4SLinus Torvalds 	long delta, delta2, delta3;
7321da177e4SLinus Torvalds 
7331da177e4SLinus Torvalds 	sample.jiffies = jiffies;
73461875f30STheodore Ts'o 	sample.cycles = random_get_entropy();
7351da177e4SLinus Torvalds 	sample.num = num;
73690ed1e67SJason A. Donenfeld 	mix_pool_bytes(&sample, sizeof(sample));
7371da177e4SLinus Torvalds 
7381da177e4SLinus Torvalds 	/*
7391da177e4SLinus Torvalds 	 * Calculate number of bits of randomness we probably added.
7401da177e4SLinus Torvalds 	 * We take into account the first, second and third-order deltas
7411da177e4SLinus Torvalds 	 * in order to make our estimate.
7421da177e4SLinus Torvalds 	 */
743e00d996aSQian Cai 	delta = sample.jiffies - READ_ONCE(state->last_time);
744e00d996aSQian Cai 	WRITE_ONCE(state->last_time, sample.jiffies);
7451da177e4SLinus Torvalds 
746e00d996aSQian Cai 	delta2 = delta - READ_ONCE(state->last_delta);
747e00d996aSQian Cai 	WRITE_ONCE(state->last_delta, delta);
7481da177e4SLinus Torvalds 
749e00d996aSQian Cai 	delta3 = delta2 - READ_ONCE(state->last_delta2);
750e00d996aSQian Cai 	WRITE_ONCE(state->last_delta2, delta2);
7511da177e4SLinus Torvalds 
7521da177e4SLinus Torvalds 	if (delta < 0)
7531da177e4SLinus Torvalds 		delta = -delta;
7541da177e4SLinus Torvalds 	if (delta2 < 0)
7551da177e4SLinus Torvalds 		delta2 = -delta2;
7561da177e4SLinus Torvalds 	if (delta3 < 0)
7571da177e4SLinus Torvalds 		delta3 = -delta3;
7581da177e4SLinus Torvalds 	if (delta > delta2)
7591da177e4SLinus Torvalds 		delta = delta2;
7601da177e4SLinus Torvalds 	if (delta > delta3)
7611da177e4SLinus Torvalds 		delta = delta3;
7621da177e4SLinus Torvalds 
7631da177e4SLinus Torvalds 	/*
7641da177e4SLinus Torvalds 	 * delta is now minimum absolute delta.
7651da177e4SLinus Torvalds 	 * Round down by 1 bit on general principles,
766727d499aSYangtao Li 	 * and limit entropy estimate to 12 bits.
7671da177e4SLinus Torvalds 	 */
76890ed1e67SJason A. Donenfeld 	credit_entropy_bits(min_t(int, fls(delta >> 1), 11));
7691da177e4SLinus Torvalds }
7701da177e4SLinus Torvalds 
771d251575aSStephen Hemminger void add_input_randomness(unsigned int type, unsigned int code,
7721da177e4SLinus Torvalds 			  unsigned int value)
7731da177e4SLinus Torvalds {
7741da177e4SLinus Torvalds 	static unsigned char last_value;
7751da177e4SLinus Torvalds 
7761da177e4SLinus Torvalds 	/* ignore autorepeat and the like */
7771da177e4SLinus Torvalds 	if (value == last_value)
7781da177e4SLinus Torvalds 		return;
7791da177e4SLinus Torvalds 
7801da177e4SLinus Torvalds 	last_value = value;
7811da177e4SLinus Torvalds 	add_timer_randomness(&input_timer_state,
7821da177e4SLinus Torvalds 			     (type << 4) ^ code ^ (code >> 4) ^ value);
783c5704490SJason A. Donenfeld 	trace_add_input_randomness(input_pool.entropy_count);
7841da177e4SLinus Torvalds }
78580fc9f53SDmitry Torokhov EXPORT_SYMBOL_GPL(add_input_randomness);
7861da177e4SLinus Torvalds 
787775f4b29STheodore Ts'o static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
788775f4b29STheodore Ts'o 
78943759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
79043759d4fSTheodore Ts'o static unsigned long avg_cycles, avg_deviation;
79143759d4fSTheodore Ts'o 
79243759d4fSTheodore Ts'o #define AVG_SHIFT 8 /* Exponential average factor k=1/256 */
79343759d4fSTheodore Ts'o #define FIXED_1_2 (1 << (AVG_SHIFT - 1))
79443759d4fSTheodore Ts'o 
79543759d4fSTheodore Ts'o static void add_interrupt_bench(cycles_t start)
79643759d4fSTheodore Ts'o {
79743759d4fSTheodore Ts'o 	long delta = random_get_entropy() - start;
79843759d4fSTheodore Ts'o 
79943759d4fSTheodore Ts'o 	/* Use a weighted moving average */
80043759d4fSTheodore Ts'o 	delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
80143759d4fSTheodore Ts'o 	avg_cycles += delta;
80243759d4fSTheodore Ts'o 	/* And average deviation */
80343759d4fSTheodore Ts'o 	delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
80443759d4fSTheodore Ts'o 	avg_deviation += delta;
80543759d4fSTheodore Ts'o }
80643759d4fSTheodore Ts'o #else
80743759d4fSTheodore Ts'o #define add_interrupt_bench(x)
80843759d4fSTheodore Ts'o #endif
80943759d4fSTheodore Ts'o 
810d38bb085SJason A. Donenfeld static u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
811ee3e00e9STheodore Ts'o {
812d38bb085SJason A. Donenfeld 	u32 *ptr = (u32 *)regs;
81392e75428STheodore Ts'o 	unsigned int idx;
814ee3e00e9STheodore Ts'o 
815ee3e00e9STheodore Ts'o 	if (regs == NULL)
816ee3e00e9STheodore Ts'o 		return 0;
81792e75428STheodore Ts'o 	idx = READ_ONCE(f->reg_idx);
818d38bb085SJason A. Donenfeld 	if (idx >= sizeof(struct pt_regs) / sizeof(u32))
81992e75428STheodore Ts'o 		idx = 0;
82092e75428STheodore Ts'o 	ptr += idx++;
82192e75428STheodore Ts'o 	WRITE_ONCE(f->reg_idx, idx);
8229dfa7bbaSMichael Schmitz 	return *ptr;
823ee3e00e9STheodore Ts'o }
824ee3e00e9STheodore Ts'o 
825703f7066SSebastian Andrzej Siewior void add_interrupt_randomness(int irq)
8261da177e4SLinus Torvalds {
8271b2a1a7eSChristoph Lameter 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
828775f4b29STheodore Ts'o 	struct pt_regs *regs = get_irq_regs();
829775f4b29STheodore Ts'o 	unsigned long now = jiffies;
830655b2264STheodore Ts'o 	cycles_t cycles = random_get_entropy();
831d38bb085SJason A. Donenfeld 	u32 c_high, j_high;
832d38bb085SJason A. Donenfeld 	u64 ip;
8333060d6feSYinghai Lu 
834ee3e00e9STheodore Ts'o 	if (cycles == 0)
835ee3e00e9STheodore Ts'o 		cycles = get_reg(fast_pool, regs);
836655b2264STheodore Ts'o 	c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
837655b2264STheodore Ts'o 	j_high = (sizeof(now) > 4) ? now >> 32 : 0;
83843759d4fSTheodore Ts'o 	fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
83943759d4fSTheodore Ts'o 	fast_pool->pool[1] ^= now ^ c_high;
840655b2264STheodore Ts'o 	ip = regs ? instruction_pointer(regs) : _RET_IP_;
84143759d4fSTheodore Ts'o 	fast_pool->pool[2] ^= ip;
842248045b8SJason A. Donenfeld 	fast_pool->pool[3] ^=
843248045b8SJason A. Donenfeld 		(sizeof(ip) > 4) ? ip >> 32 : get_reg(fast_pool, regs);
8443060d6feSYinghai Lu 
84543759d4fSTheodore Ts'o 	fast_mix(fast_pool);
84643759d4fSTheodore Ts'o 	add_interrupt_bench(cycles);
847775f4b29STheodore Ts'o 
84843838a23STheodore Ts'o 	if (unlikely(crng_init == 0)) {
849e192be9dSTheodore Ts'o 		if ((fast_pool->count >= 64) &&
850d38bb085SJason A. Donenfeld 		    crng_fast_load((u8 *)fast_pool->pool, sizeof(fast_pool->pool)) > 0) {
851e192be9dSTheodore Ts'o 			fast_pool->count = 0;
852e192be9dSTheodore Ts'o 			fast_pool->last = now;
853*c30c575dSJason A. Donenfeld 			if (spin_trylock(&input_pool.lock)) {
854*c30c575dSJason A. Donenfeld 				_mix_pool_bytes(&fast_pool->pool, sizeof(fast_pool->pool));
855*c30c575dSJason A. Donenfeld 				spin_unlock(&input_pool.lock);
856*c30c575dSJason A. Donenfeld 			}
857e192be9dSTheodore Ts'o 		}
858e192be9dSTheodore Ts'o 		return;
859e192be9dSTheodore Ts'o 	}
860e192be9dSTheodore Ts'o 
861248045b8SJason A. Donenfeld 	if ((fast_pool->count < 64) && !time_after(now, fast_pool->last + HZ))
8621da177e4SLinus Torvalds 		return;
863840f9507STheodore Ts'o 
86490ed1e67SJason A. Donenfeld 	if (!spin_trylock(&input_pool.lock))
8651da177e4SLinus Torvalds 		return;
8661da177e4SLinus Torvalds 
867775f4b29STheodore Ts'o 	fast_pool->last = now;
86890ed1e67SJason A. Donenfeld 	__mix_pool_bytes(&fast_pool->pool, sizeof(fast_pool->pool));
86990ed1e67SJason A. Donenfeld 	spin_unlock(&input_pool.lock);
87083664a69SH. Peter Anvin 
871ee3e00e9STheodore Ts'o 	fast_pool->count = 0;
872840f9507STheodore Ts'o 
873ee3e00e9STheodore Ts'o 	/* award one bit for the contents of the fast pool */
87490ed1e67SJason A. Donenfeld 	credit_entropy_bits(1);
8751da177e4SLinus Torvalds }
8764b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
8771da177e4SLinus Torvalds 
8789361401eSDavid Howells #ifdef CONFIG_BLOCK
8791da177e4SLinus Torvalds void add_disk_randomness(struct gendisk *disk)
8801da177e4SLinus Torvalds {
8811da177e4SLinus Torvalds 	if (!disk || !disk->random)
8821da177e4SLinus Torvalds 		return;
8831da177e4SLinus Torvalds 	/* first major is 1, so we get >= 0x200 here */
884f331c029STejun Heo 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
885c5704490SJason A. Donenfeld 	trace_add_disk_randomness(disk_devt(disk), input_pool.entropy_count);
8861da177e4SLinus Torvalds }
887bdcfa3e5SChristoph Hellwig EXPORT_SYMBOL_GPL(add_disk_randomness);
8889361401eSDavid Howells #endif
8891da177e4SLinus Torvalds 
8901da177e4SLinus Torvalds /*********************************************************************
8911da177e4SLinus Torvalds  *
8921da177e4SLinus Torvalds  * Entropy extraction routines
8931da177e4SLinus Torvalds  *
8941da177e4SLinus Torvalds  *********************************************************************/
8951da177e4SLinus Torvalds 
8961da177e4SLinus Torvalds /*
8976e8ec255SJason A. Donenfeld  * This is an HKDF-like construction for using the hashed collected entropy
8986e8ec255SJason A. Donenfeld  * as a PRF key, that's then expanded block-by-block.
89919fa5be1SGreg Price  */
9009c07f578SJason A. Donenfeld static void extract_entropy(void *buf, size_t nbytes)
9011da177e4SLinus Torvalds {
902902c098aSTheodore Ts'o 	unsigned long flags;
9036e8ec255SJason A. Donenfeld 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
9046e8ec255SJason A. Donenfeld 	struct {
90528f425e5SJason A. Donenfeld 		unsigned long rdseed[32 / sizeof(long)];
9066e8ec255SJason A. Donenfeld 		size_t counter;
9076e8ec255SJason A. Donenfeld 	} block;
9086e8ec255SJason A. Donenfeld 	size_t i;
9091da177e4SLinus Torvalds 
910c5704490SJason A. Donenfeld 	trace_extract_entropy(nbytes, input_pool.entropy_count);
9119c07f578SJason A. Donenfeld 
91228f425e5SJason A. Donenfeld 	for (i = 0; i < ARRAY_SIZE(block.rdseed); ++i) {
91328f425e5SJason A. Donenfeld 		if (!arch_get_random_seed_long(&block.rdseed[i]) &&
91428f425e5SJason A. Donenfeld 		    !arch_get_random_long(&block.rdseed[i]))
91528f425e5SJason A. Donenfeld 			block.rdseed[i] = random_get_entropy();
91685a1f777STheodore Ts'o 	}
91785a1f777STheodore Ts'o 
91890ed1e67SJason A. Donenfeld 	spin_lock_irqsave(&input_pool.lock, flags);
91946884442STheodore Ts'o 
9206e8ec255SJason A. Donenfeld 	/* seed = HASHPRF(last_key, entropy_input) */
9216e8ec255SJason A. Donenfeld 	blake2s_final(&input_pool.hash, seed);
9226e8ec255SJason A. Donenfeld 
92328f425e5SJason A. Donenfeld 	/* next_key = HASHPRF(seed, RDSEED || 0) */
9246e8ec255SJason A. Donenfeld 	block.counter = 0;
9256e8ec255SJason A. Donenfeld 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
9266e8ec255SJason A. Donenfeld 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
9276e8ec255SJason A. Donenfeld 
92890ed1e67SJason A. Donenfeld 	spin_unlock_irqrestore(&input_pool.lock, flags);
9296e8ec255SJason A. Donenfeld 	memzero_explicit(next_key, sizeof(next_key));
930e192be9dSTheodore Ts'o 
931e192be9dSTheodore Ts'o 	while (nbytes) {
9326e8ec255SJason A. Donenfeld 		i = min_t(size_t, nbytes, BLAKE2S_HASH_SIZE);
93328f425e5SJason A. Donenfeld 		/* output = HASHPRF(seed, RDSEED || ++counter) */
9346e8ec255SJason A. Donenfeld 		++block.counter;
9356e8ec255SJason A. Donenfeld 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
936e192be9dSTheodore Ts'o 		nbytes -= i;
937e192be9dSTheodore Ts'o 		buf += i;
938e192be9dSTheodore Ts'o 	}
939e192be9dSTheodore Ts'o 
9406e8ec255SJason A. Donenfeld 	memzero_explicit(seed, sizeof(seed));
9416e8ec255SJason A. Donenfeld 	memzero_explicit(&block, sizeof(block));
942e192be9dSTheodore Ts'o }
943e192be9dSTheodore Ts'o 
944eecabf56STheodore Ts'o #define warn_unseeded_randomness(previous) \
945eecabf56STheodore Ts'o 	_warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous))
946eecabf56STheodore Ts'o 
947248045b8SJason A. Donenfeld static void _warn_unseeded_randomness(const char *func_name, void *caller, void **previous)
948eecabf56STheodore Ts'o {
949eecabf56STheodore Ts'o #ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
950eecabf56STheodore Ts'o 	const bool print_once = false;
951eecabf56STheodore Ts'o #else
952eecabf56STheodore Ts'o 	static bool print_once __read_mostly;
953eecabf56STheodore Ts'o #endif
954eecabf56STheodore Ts'o 
955248045b8SJason A. Donenfeld 	if (print_once || crng_ready() ||
956eecabf56STheodore Ts'o 	    (previous && (caller == READ_ONCE(*previous))))
957eecabf56STheodore Ts'o 		return;
958eecabf56STheodore Ts'o 	WRITE_ONCE(*previous, caller);
959eecabf56STheodore Ts'o #ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
960eecabf56STheodore Ts'o 	print_once = true;
961eecabf56STheodore Ts'o #endif
9624e00b339STheodore Ts'o 	if (__ratelimit(&unseeded_warning))
963248045b8SJason A. Donenfeld 		printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n",
964248045b8SJason A. Donenfeld 				func_name, caller, crng_init);
965eecabf56STheodore Ts'o }
966eecabf56STheodore Ts'o 
9671da177e4SLinus Torvalds /*
9681da177e4SLinus Torvalds  * This function is the exported kernel interface.  It returns some
969c2557a30STheodore Ts'o  * number of good random numbers, suitable for key generation, seeding
97018e9cea7SGreg Price  * TCP sequence numbers, etc.  It does not rely on the hardware random
97118e9cea7SGreg Price  * number generator.  For random bytes direct from the hardware RNG
972e297a783SJason A. Donenfeld  * (when available), use get_random_bytes_arch(). In order to ensure
973e297a783SJason A. Donenfeld  * that the randomness provided by this function is okay, the function
974e297a783SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once
975e297a783SJason A. Donenfeld  * at any point prior.
9761da177e4SLinus Torvalds  */
977eecabf56STheodore Ts'o static void _get_random_bytes(void *buf, int nbytes)
9781da177e4SLinus Torvalds {
979d38bb085SJason A. Donenfeld 	u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
980e192be9dSTheodore Ts'o 
9815910895fSTheodore Ts'o 	trace_get_random_bytes(nbytes, _RET_IP_);
982e192be9dSTheodore Ts'o 
9831ca1b917SEric Biggers 	while (nbytes >= CHACHA_BLOCK_SIZE) {
984e192be9dSTheodore Ts'o 		extract_crng(buf);
9851ca1b917SEric Biggers 		buf += CHACHA_BLOCK_SIZE;
9861ca1b917SEric Biggers 		nbytes -= CHACHA_BLOCK_SIZE;
987e192be9dSTheodore Ts'o 	}
988e192be9dSTheodore Ts'o 
989e192be9dSTheodore Ts'o 	if (nbytes > 0) {
990e192be9dSTheodore Ts'o 		extract_crng(tmp);
991e192be9dSTheodore Ts'o 		memcpy(buf, tmp, nbytes);
992c92e040dSTheodore Ts'o 		crng_backtrack_protect(tmp, nbytes);
993c92e040dSTheodore Ts'o 	} else
9941ca1b917SEric Biggers 		crng_backtrack_protect(tmp, CHACHA_BLOCK_SIZE);
995c92e040dSTheodore Ts'o 	memzero_explicit(tmp, sizeof(tmp));
996c2557a30STheodore Ts'o }
997eecabf56STheodore Ts'o 
998eecabf56STheodore Ts'o void get_random_bytes(void *buf, int nbytes)
999eecabf56STheodore Ts'o {
1000eecabf56STheodore Ts'o 	static void *previous;
1001eecabf56STheodore Ts'o 
1002eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
1003eecabf56STheodore Ts'o 	_get_random_bytes(buf, nbytes);
1004eecabf56STheodore Ts'o }
1005c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes);
1006c2557a30STheodore Ts'o 
100750ee7529SLinus Torvalds /*
100850ee7529SLinus Torvalds  * Each time the timer fires, we expect that we got an unpredictable
100950ee7529SLinus Torvalds  * jump in the cycle counter. Even if the timer is running on another
101050ee7529SLinus Torvalds  * CPU, the timer activity will be touching the stack of the CPU that is
101150ee7529SLinus Torvalds  * generating entropy..
101250ee7529SLinus Torvalds  *
101350ee7529SLinus Torvalds  * Note that we don't re-arm the timer in the timer itself - we are
101450ee7529SLinus Torvalds  * happy to be scheduled away, since that just makes the load more
101550ee7529SLinus Torvalds  * complex, but we do not want the timer to keep ticking unless the
101650ee7529SLinus Torvalds  * entropy loop is running.
101750ee7529SLinus Torvalds  *
101850ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
101950ee7529SLinus Torvalds  */
102050ee7529SLinus Torvalds static void entropy_timer(struct timer_list *t)
102150ee7529SLinus Torvalds {
102290ed1e67SJason A. Donenfeld 	credit_entropy_bits(1);
102350ee7529SLinus Torvalds }
102450ee7529SLinus Torvalds 
102550ee7529SLinus Torvalds /*
102650ee7529SLinus Torvalds  * If we have an actual cycle counter, see if we can
102750ee7529SLinus Torvalds  * generate enough entropy with timing noise
102850ee7529SLinus Torvalds  */
102950ee7529SLinus Torvalds static void try_to_generate_entropy(void)
103050ee7529SLinus Torvalds {
103150ee7529SLinus Torvalds 	struct {
103250ee7529SLinus Torvalds 		unsigned long now;
103350ee7529SLinus Torvalds 		struct timer_list timer;
103450ee7529SLinus Torvalds 	} stack;
103550ee7529SLinus Torvalds 
103650ee7529SLinus Torvalds 	stack.now = random_get_entropy();
103750ee7529SLinus Torvalds 
103850ee7529SLinus Torvalds 	/* Slow counter - or none. Don't even bother */
103950ee7529SLinus Torvalds 	if (stack.now == random_get_entropy())
104050ee7529SLinus Torvalds 		return;
104150ee7529SLinus Torvalds 
104250ee7529SLinus Torvalds 	timer_setup_on_stack(&stack.timer, entropy_timer, 0);
104350ee7529SLinus Torvalds 	while (!crng_ready()) {
104450ee7529SLinus Torvalds 		if (!timer_pending(&stack.timer))
104550ee7529SLinus Torvalds 			mod_timer(&stack.timer, jiffies + 1);
104690ed1e67SJason A. Donenfeld 		mix_pool_bytes(&stack.now, sizeof(stack.now));
104750ee7529SLinus Torvalds 		schedule();
104850ee7529SLinus Torvalds 		stack.now = random_get_entropy();
104950ee7529SLinus Torvalds 	}
105050ee7529SLinus Torvalds 
105150ee7529SLinus Torvalds 	del_timer_sync(&stack.timer);
105250ee7529SLinus Torvalds 	destroy_timer_on_stack(&stack.timer);
105390ed1e67SJason A. Donenfeld 	mix_pool_bytes(&stack.now, sizeof(stack.now));
105450ee7529SLinus Torvalds }
105550ee7529SLinus Torvalds 
1056c2557a30STheodore Ts'o /*
1057e297a783SJason A. Donenfeld  * Wait for the urandom pool to be seeded and thus guaranteed to supply
1058e297a783SJason A. Donenfeld  * cryptographically secure random numbers. This applies to: the /dev/urandom
1059e297a783SJason A. Donenfeld  * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1060e297a783SJason A. Donenfeld  * family of functions. Using any of these functions without first calling
1061e297a783SJason A. Donenfeld  * this function forfeits the guarantee of security.
1062e297a783SJason A. Donenfeld  *
1063e297a783SJason A. Donenfeld  * Returns: 0 if the urandom pool has been seeded.
1064e297a783SJason A. Donenfeld  *          -ERESTARTSYS if the function was interrupted by a signal.
1065e297a783SJason A. Donenfeld  */
1066e297a783SJason A. Donenfeld int wait_for_random_bytes(void)
1067e297a783SJason A. Donenfeld {
1068e297a783SJason A. Donenfeld 	if (likely(crng_ready()))
1069e297a783SJason A. Donenfeld 		return 0;
107050ee7529SLinus Torvalds 
107150ee7529SLinus Torvalds 	do {
107250ee7529SLinus Torvalds 		int ret;
107350ee7529SLinus Torvalds 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
107450ee7529SLinus Torvalds 		if (ret)
107550ee7529SLinus Torvalds 			return ret > 0 ? 0 : ret;
107650ee7529SLinus Torvalds 
107750ee7529SLinus Torvalds 		try_to_generate_entropy();
107850ee7529SLinus Torvalds 	} while (!crng_ready());
107950ee7529SLinus Torvalds 
108050ee7529SLinus Torvalds 	return 0;
1081e297a783SJason A. Donenfeld }
1082e297a783SJason A. Donenfeld EXPORT_SYMBOL(wait_for_random_bytes);
1083e297a783SJason A. Donenfeld 
1084e297a783SJason A. Donenfeld /*
10859a47249dSJason A. Donenfeld  * Returns whether or not the urandom pool has been seeded and thus guaranteed
10869a47249dSJason A. Donenfeld  * to supply cryptographically secure random numbers. This applies to: the
10879a47249dSJason A. Donenfeld  * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
10889a47249dSJason A. Donenfeld  * ,u64,int,long} family of functions.
10899a47249dSJason A. Donenfeld  *
10909a47249dSJason A. Donenfeld  * Returns: true if the urandom pool has been seeded.
10919a47249dSJason A. Donenfeld  *          false if the urandom pool has not been seeded.
10929a47249dSJason A. Donenfeld  */
10939a47249dSJason A. Donenfeld bool rng_is_initialized(void)
10949a47249dSJason A. Donenfeld {
10959a47249dSJason A. Donenfeld 	return crng_ready();
10969a47249dSJason A. Donenfeld }
10979a47249dSJason A. Donenfeld EXPORT_SYMBOL(rng_is_initialized);
10989a47249dSJason A. Donenfeld 
10999a47249dSJason A. Donenfeld /*
1100205a525cSHerbert Xu  * Add a callback function that will be invoked when the nonblocking
1101205a525cSHerbert Xu  * pool is initialised.
1102205a525cSHerbert Xu  *
1103205a525cSHerbert Xu  * returns: 0 if callback is successfully added
1104205a525cSHerbert Xu  *	    -EALREADY if pool is already initialised (callback not called)
1105205a525cSHerbert Xu  *	    -ENOENT if module for callback is not alive
1106205a525cSHerbert Xu  */
1107205a525cSHerbert Xu int add_random_ready_callback(struct random_ready_callback *rdy)
1108205a525cSHerbert Xu {
1109205a525cSHerbert Xu 	struct module *owner;
1110205a525cSHerbert Xu 	unsigned long flags;
1111205a525cSHerbert Xu 	int err = -EALREADY;
1112205a525cSHerbert Xu 
1113e192be9dSTheodore Ts'o 	if (crng_ready())
1114205a525cSHerbert Xu 		return err;
1115205a525cSHerbert Xu 
1116205a525cSHerbert Xu 	owner = rdy->owner;
1117205a525cSHerbert Xu 	if (!try_module_get(owner))
1118205a525cSHerbert Xu 		return -ENOENT;
1119205a525cSHerbert Xu 
1120205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
1121e192be9dSTheodore Ts'o 	if (crng_ready())
1122205a525cSHerbert Xu 		goto out;
1123205a525cSHerbert Xu 
1124205a525cSHerbert Xu 	owner = NULL;
1125205a525cSHerbert Xu 
1126205a525cSHerbert Xu 	list_add(&rdy->list, &random_ready_list);
1127205a525cSHerbert Xu 	err = 0;
1128205a525cSHerbert Xu 
1129205a525cSHerbert Xu out:
1130205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
1131205a525cSHerbert Xu 
1132205a525cSHerbert Xu 	module_put(owner);
1133205a525cSHerbert Xu 
1134205a525cSHerbert Xu 	return err;
1135205a525cSHerbert Xu }
1136205a525cSHerbert Xu EXPORT_SYMBOL(add_random_ready_callback);
1137205a525cSHerbert Xu 
1138205a525cSHerbert Xu /*
1139205a525cSHerbert Xu  * Delete a previously registered readiness callback function.
1140205a525cSHerbert Xu  */
1141205a525cSHerbert Xu void del_random_ready_callback(struct random_ready_callback *rdy)
1142205a525cSHerbert Xu {
1143205a525cSHerbert Xu 	unsigned long flags;
1144205a525cSHerbert Xu 	struct module *owner = NULL;
1145205a525cSHerbert Xu 
1146205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
1147205a525cSHerbert Xu 	if (!list_empty(&rdy->list)) {
1148205a525cSHerbert Xu 		list_del_init(&rdy->list);
1149205a525cSHerbert Xu 		owner = rdy->owner;
1150205a525cSHerbert Xu 	}
1151205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
1152205a525cSHerbert Xu 
1153205a525cSHerbert Xu 	module_put(owner);
1154205a525cSHerbert Xu }
1155205a525cSHerbert Xu EXPORT_SYMBOL(del_random_ready_callback);
1156205a525cSHerbert Xu 
1157205a525cSHerbert Xu /*
1158c2557a30STheodore Ts'o  * This function will use the architecture-specific hardware random
1159c2557a30STheodore Ts'o  * number generator if it is available.  The arch-specific hw RNG will
1160c2557a30STheodore Ts'o  * almost certainly be faster than what we can do in software, but it
1161c2557a30STheodore Ts'o  * is impossible to verify that it is implemented securely (as
1162c2557a30STheodore Ts'o  * opposed, to, say, the AES encryption of a sequence number using a
1163c2557a30STheodore Ts'o  * key known by the NSA).  So it's useful if we need the speed, but
1164c2557a30STheodore Ts'o  * only if we're willing to trust the hardware manufacturer not to
1165c2557a30STheodore Ts'o  * have put in a back door.
1166753d433bSTobin C. Harding  *
1167753d433bSTobin C. Harding  * Return number of bytes filled in.
1168c2557a30STheodore Ts'o  */
1169753d433bSTobin C. Harding int __must_check get_random_bytes_arch(void *buf, int nbytes)
1170c2557a30STheodore Ts'o {
1171753d433bSTobin C. Harding 	int left = nbytes;
1172d38bb085SJason A. Donenfeld 	u8 *p = buf;
117363d77173SH. Peter Anvin 
1174753d433bSTobin C. Harding 	trace_get_random_bytes_arch(left, _RET_IP_);
1175753d433bSTobin C. Harding 	while (left) {
117663d77173SH. Peter Anvin 		unsigned long v;
1177753d433bSTobin C. Harding 		int chunk = min_t(int, left, sizeof(unsigned long));
117863d77173SH. Peter Anvin 
117963d77173SH. Peter Anvin 		if (!arch_get_random_long(&v))
118063d77173SH. Peter Anvin 			break;
118163d77173SH. Peter Anvin 
1182bd29e568SLuck, Tony 		memcpy(p, &v, chunk);
118363d77173SH. Peter Anvin 		p += chunk;
1184753d433bSTobin C. Harding 		left -= chunk;
118563d77173SH. Peter Anvin 	}
118663d77173SH. Peter Anvin 
1187753d433bSTobin C. Harding 	return nbytes - left;
11881da177e4SLinus Torvalds }
1189c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes_arch);
11901da177e4SLinus Torvalds 
119185664172SJason A. Donenfeld static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
119285664172SJason A. Donenfeld static int __init parse_trust_cpu(char *arg)
11931da177e4SLinus Torvalds {
119485664172SJason A. Donenfeld 	return kstrtobool(arg, &trust_cpu);
11953e88bdffSTheodore Ts'o }
119685664172SJason A. Donenfeld early_param("random.trust_cpu", parse_trust_cpu);
11971da177e4SLinus Torvalds 
1198cbc96b75STony Luck /*
1199cbc96b75STony Luck  * Note that setup_arch() may call add_device_randomness()
1200cbc96b75STony Luck  * long before we get here. This allows seeding of the pools
1201cbc96b75STony Luck  * with some platform dependent data very early in the boot
1202cbc96b75STony Luck  * process. But it limits our options here. We must use
1203cbc96b75STony Luck  * statically allocated structures that already have all
1204cbc96b75STony Luck  * initializations complete at compile time. We should also
1205cbc96b75STony Luck  * take care not to overwrite the precious per platform data
1206cbc96b75STony Luck  * we were given.
1207cbc96b75STony Luck  */
1208d5553523SKees Cook int __init rand_initialize(void)
12091da177e4SLinus Torvalds {
121085664172SJason A. Donenfeld 	int i;
121185664172SJason A. Donenfeld 	ktime_t now = ktime_get_real();
121285664172SJason A. Donenfeld 	bool arch_init = true;
121385664172SJason A. Donenfeld 	unsigned long rv;
121485664172SJason A. Donenfeld 
121585664172SJason A. Donenfeld 	for (i = BLAKE2S_BLOCK_SIZE; i > 0; i -= sizeof(rv)) {
121685664172SJason A. Donenfeld 		if (!arch_get_random_seed_long_early(&rv) &&
121785664172SJason A. Donenfeld 		    !arch_get_random_long_early(&rv)) {
121885664172SJason A. Donenfeld 			rv = random_get_entropy();
121985664172SJason A. Donenfeld 			arch_init = false;
122085664172SJason A. Donenfeld 		}
1221a02cf3d0SJason A. Donenfeld 		mix_pool_bytes(&rv, sizeof(rv));
122285664172SJason A. Donenfeld 	}
1223a02cf3d0SJason A. Donenfeld 	mix_pool_bytes(&now, sizeof(now));
1224a02cf3d0SJason A. Donenfeld 	mix_pool_bytes(utsname(), sizeof(*(utsname())));
1225a02cf3d0SJason A. Donenfeld 
1226a02cf3d0SJason A. Donenfeld 	extract_entropy(&primary_crng.state[4], sizeof(u32) * 12);
122785664172SJason A. Donenfeld 	if (arch_init && trust_cpu && crng_init < 2) {
122885664172SJason A. Donenfeld 		invalidate_batched_entropy();
122985664172SJason A. Donenfeld 		crng_init = 2;
123085664172SJason A. Donenfeld 		pr_notice("crng init done (trusting CPU's manufacturer)\n");
123185664172SJason A. Donenfeld 	}
123285664172SJason A. Donenfeld 	primary_crng.init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
123385664172SJason A. Donenfeld 
12344e00b339STheodore Ts'o 	if (ratelimit_disable) {
12354e00b339STheodore Ts'o 		urandom_warning.interval = 0;
12364e00b339STheodore Ts'o 		unseeded_warning.interval = 0;
12374e00b339STheodore Ts'o 	}
12381da177e4SLinus Torvalds 	return 0;
12391da177e4SLinus Torvalds }
12401da177e4SLinus Torvalds 
12419361401eSDavid Howells #ifdef CONFIG_BLOCK
12421da177e4SLinus Torvalds void rand_initialize_disk(struct gendisk *disk)
12431da177e4SLinus Torvalds {
12441da177e4SLinus Torvalds 	struct timer_rand_state *state;
12451da177e4SLinus Torvalds 
12461da177e4SLinus Torvalds 	/*
1247f8595815SEric Dumazet 	 * If kzalloc returns null, we just won't use that entropy
12481da177e4SLinus Torvalds 	 * source.
12491da177e4SLinus Torvalds 	 */
1250f8595815SEric Dumazet 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1251644008dfSTheodore Ts'o 	if (state) {
1252644008dfSTheodore Ts'o 		state->last_time = INITIAL_JIFFIES;
12531da177e4SLinus Torvalds 		disk->random = state;
12541da177e4SLinus Torvalds 	}
1255644008dfSTheodore Ts'o }
12569361401eSDavid Howells #endif
12571da177e4SLinus Torvalds 
1258248045b8SJason A. Donenfeld static ssize_t urandom_read_nowarn(struct file *file, char __user *buf,
1259248045b8SJason A. Donenfeld 				   size_t nbytes, loff_t *ppos)
1260c6f1deb1SAndy Lutomirski {
1261c6f1deb1SAndy Lutomirski 	int ret;
1262c6f1deb1SAndy Lutomirski 
1263c5704490SJason A. Donenfeld 	nbytes = min_t(size_t, nbytes, INT_MAX >> 6);
1264c6f1deb1SAndy Lutomirski 	ret = extract_crng_user(buf, nbytes);
1265c5704490SJason A. Donenfeld 	trace_urandom_read(8 * nbytes, 0, input_pool.entropy_count);
1266c6f1deb1SAndy Lutomirski 	return ret;
1267c6f1deb1SAndy Lutomirski }
1268c6f1deb1SAndy Lutomirski 
1269248045b8SJason A. Donenfeld static ssize_t urandom_read(struct file *file, char __user *buf, size_t nbytes,
1270248045b8SJason A. Donenfeld 			    loff_t *ppos)
12711da177e4SLinus Torvalds {
12729b4d0087STheodore Ts'o 	static int maxwarn = 10;
1273301f0595STheodore Ts'o 
1274e192be9dSTheodore Ts'o 	if (!crng_ready() && maxwarn > 0) {
12759b4d0087STheodore Ts'o 		maxwarn--;
12764e00b339STheodore Ts'o 		if (__ratelimit(&urandom_warning))
127712cd53afSYangtao Li 			pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
1278e192be9dSTheodore Ts'o 				  current->comm, nbytes);
12799b4d0087STheodore Ts'o 	}
1280c6f1deb1SAndy Lutomirski 
1281c6f1deb1SAndy Lutomirski 	return urandom_read_nowarn(file, buf, nbytes, ppos);
12821da177e4SLinus Torvalds }
12831da177e4SLinus Torvalds 
1284248045b8SJason A. Donenfeld static ssize_t random_read(struct file *file, char __user *buf, size_t nbytes,
1285248045b8SJason A. Donenfeld 			   loff_t *ppos)
128630c08efeSAndy Lutomirski {
128730c08efeSAndy Lutomirski 	int ret;
128830c08efeSAndy Lutomirski 
128930c08efeSAndy Lutomirski 	ret = wait_for_random_bytes();
129030c08efeSAndy Lutomirski 	if (ret != 0)
129130c08efeSAndy Lutomirski 		return ret;
129230c08efeSAndy Lutomirski 	return urandom_read_nowarn(file, buf, nbytes, ppos);
129330c08efeSAndy Lutomirski }
129430c08efeSAndy Lutomirski 
1295248045b8SJason A. Donenfeld static __poll_t random_poll(struct file *file, poll_table *wait)
129689b310a2SChristoph Hellwig {
1297a11e1d43SLinus Torvalds 	__poll_t mask;
129889b310a2SChristoph Hellwig 
129930c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1300a11e1d43SLinus Torvalds 	poll_wait(file, &random_write_wait, wait);
1301a11e1d43SLinus Torvalds 	mask = 0;
130230c08efeSAndy Lutomirski 	if (crng_ready())
1303a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
1304489c7fc4SJason A. Donenfeld 	if (input_pool.entropy_count < POOL_MIN_BITS)
1305a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
13061da177e4SLinus Torvalds 	return mask;
13071da177e4SLinus Torvalds }
13081da177e4SLinus Torvalds 
1309248045b8SJason A. Donenfeld static int write_pool(const char __user *buffer, size_t count)
13107f397dcdSMatt Mackall {
13117f397dcdSMatt Mackall 	size_t bytes;
131291c2afcaSJason A. Donenfeld 	u8 buf[BLAKE2S_BLOCK_SIZE];
13137f397dcdSMatt Mackall 	const char __user *p = buffer;
13147f397dcdSMatt Mackall 
13157f397dcdSMatt Mackall 	while (count > 0) {
13167f397dcdSMatt Mackall 		bytes = min(count, sizeof(buf));
131791c2afcaSJason A. Donenfeld 		if (copy_from_user(buf, p, bytes))
13187f397dcdSMatt Mackall 			return -EFAULT;
13197f397dcdSMatt Mackall 		count -= bytes;
13207f397dcdSMatt Mackall 		p += bytes;
132190ed1e67SJason A. Donenfeld 		mix_pool_bytes(buf, bytes);
132291f3f1e3SMatt Mackall 		cond_resched();
13237f397dcdSMatt Mackall 	}
13247f397dcdSMatt Mackall 
13257f397dcdSMatt Mackall 	return 0;
13267f397dcdSMatt Mackall }
13277f397dcdSMatt Mackall 
132890b75ee5SMatt Mackall static ssize_t random_write(struct file *file, const char __user *buffer,
13291da177e4SLinus Torvalds 			    size_t count, loff_t *ppos)
13301da177e4SLinus Torvalds {
13317f397dcdSMatt Mackall 	size_t ret;
13327f397dcdSMatt Mackall 
133390ed1e67SJason A. Donenfeld 	ret = write_pool(buffer, count);
13347f397dcdSMatt Mackall 	if (ret)
13357f397dcdSMatt Mackall 		return ret;
13367f397dcdSMatt Mackall 
13377f397dcdSMatt Mackall 	return (ssize_t)count;
13381da177e4SLinus Torvalds }
13391da177e4SLinus Torvalds 
134043ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
13411da177e4SLinus Torvalds {
13421da177e4SLinus Torvalds 	int size, ent_count;
13431da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
13441da177e4SLinus Torvalds 	int retval;
13451da177e4SLinus Torvalds 
13461da177e4SLinus Torvalds 	switch (cmd) {
13471da177e4SLinus Torvalds 	case RNDGETENTCNT:
134843ae4860SMatt Mackall 		/* inherently racy, no point locking */
1349c5704490SJason A. Donenfeld 		if (put_user(input_pool.entropy_count, p))
13501da177e4SLinus Torvalds 			return -EFAULT;
13511da177e4SLinus Torvalds 		return 0;
13521da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
13531da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13541da177e4SLinus Torvalds 			return -EPERM;
13551da177e4SLinus Torvalds 		if (get_user(ent_count, p))
13561da177e4SLinus Torvalds 			return -EFAULT;
1357a49c010eSJason A. Donenfeld 		if (ent_count < 0)
1358a49c010eSJason A. Donenfeld 			return -EINVAL;
1359a49c010eSJason A. Donenfeld 		credit_entropy_bits(ent_count);
1360a49c010eSJason A. Donenfeld 		return 0;
13611da177e4SLinus Torvalds 	case RNDADDENTROPY:
13621da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13631da177e4SLinus Torvalds 			return -EPERM;
13641da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
13651da177e4SLinus Torvalds 			return -EFAULT;
13661da177e4SLinus Torvalds 		if (ent_count < 0)
13671da177e4SLinus Torvalds 			return -EINVAL;
13681da177e4SLinus Torvalds 		if (get_user(size, p++))
13691da177e4SLinus Torvalds 			return -EFAULT;
137090ed1e67SJason A. Donenfeld 		retval = write_pool((const char __user *)p, size);
13711da177e4SLinus Torvalds 		if (retval < 0)
13721da177e4SLinus Torvalds 			return retval;
1373a49c010eSJason A. Donenfeld 		credit_entropy_bits(ent_count);
1374a49c010eSJason A. Donenfeld 		return 0;
13751da177e4SLinus Torvalds 	case RNDZAPENTCNT:
13761da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1377ae9ecd92STheodore Ts'o 		/*
1378ae9ecd92STheodore Ts'o 		 * Clear the entropy pool counters. We no longer clear
1379ae9ecd92STheodore Ts'o 		 * the entropy pool, as that's silly.
1380ae9ecd92STheodore Ts'o 		 */
13811da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
13821da177e4SLinus Torvalds 			return -EPERM;
1383489c7fc4SJason A. Donenfeld 		if (xchg(&input_pool.entropy_count, 0)) {
1384042e293eSJason A. Donenfeld 			wake_up_interruptible(&random_write_wait);
1385042e293eSJason A. Donenfeld 			kill_fasync(&fasync, SIGIO, POLL_OUT);
1386042e293eSJason A. Donenfeld 		}
13871da177e4SLinus Torvalds 		return 0;
1388d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1389d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1390d848e5f8STheodore Ts'o 			return -EPERM;
1391d848e5f8STheodore Ts'o 		if (crng_init < 2)
1392d848e5f8STheodore Ts'o 			return -ENODATA;
1393a9412d51SJason A. Donenfeld 		crng_reseed();
1394d848e5f8STheodore Ts'o 		return 0;
13951da177e4SLinus Torvalds 	default:
13961da177e4SLinus Torvalds 		return -EINVAL;
13971da177e4SLinus Torvalds 	}
13981da177e4SLinus Torvalds }
13991da177e4SLinus Torvalds 
14009a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
14019a6f70bbSJeff Dike {
14029a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
14039a6f70bbSJeff Dike }
14049a6f70bbSJeff Dike 
14052b8693c0SArjan van de Ven const struct file_operations random_fops = {
14061da177e4SLinus Torvalds 	.read = random_read,
14071da177e4SLinus Torvalds 	.write = random_write,
1408a11e1d43SLinus Torvalds 	.poll = random_poll,
140943ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1410507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
14119a6f70bbSJeff Dike 	.fasync = random_fasync,
14126038f373SArnd Bergmann 	.llseek = noop_llseek,
14131da177e4SLinus Torvalds };
14141da177e4SLinus Torvalds 
14152b8693c0SArjan van de Ven const struct file_operations urandom_fops = {
14161da177e4SLinus Torvalds 	.read = urandom_read,
14171da177e4SLinus Torvalds 	.write = random_write,
141843ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
14194aa37c46SJason A. Donenfeld 	.compat_ioctl = compat_ptr_ioctl,
14209a6f70bbSJeff Dike 	.fasync = random_fasync,
14216038f373SArnd Bergmann 	.llseek = noop_llseek,
14221da177e4SLinus Torvalds };
14231da177e4SLinus Torvalds 
1424248045b8SJason A. Donenfeld SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int,
1425248045b8SJason A. Donenfeld 		flags)
1426c6e9d6f3STheodore Ts'o {
1427e297a783SJason A. Donenfeld 	int ret;
1428e297a783SJason A. Donenfeld 
142975551dbfSAndy Lutomirski 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
143075551dbfSAndy Lutomirski 		return -EINVAL;
143175551dbfSAndy Lutomirski 
143275551dbfSAndy Lutomirski 	/*
143375551dbfSAndy Lutomirski 	 * Requesting insecure and blocking randomness at the same time makes
143475551dbfSAndy Lutomirski 	 * no sense.
143575551dbfSAndy Lutomirski 	 */
143675551dbfSAndy Lutomirski 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1437c6e9d6f3STheodore Ts'o 		return -EINVAL;
1438c6e9d6f3STheodore Ts'o 
1439c6e9d6f3STheodore Ts'o 	if (count > INT_MAX)
1440c6e9d6f3STheodore Ts'o 		count = INT_MAX;
1441c6e9d6f3STheodore Ts'o 
144275551dbfSAndy Lutomirski 	if (!(flags & GRND_INSECURE) && !crng_ready()) {
1443c6e9d6f3STheodore Ts'o 		if (flags & GRND_NONBLOCK)
1444c6e9d6f3STheodore Ts'o 			return -EAGAIN;
1445e297a783SJason A. Donenfeld 		ret = wait_for_random_bytes();
1446e297a783SJason A. Donenfeld 		if (unlikely(ret))
1447e297a783SJason A. Donenfeld 			return ret;
1448c6e9d6f3STheodore Ts'o 	}
1449c6f1deb1SAndy Lutomirski 	return urandom_read_nowarn(NULL, buf, count, NULL);
1450c6e9d6f3STheodore Ts'o }
1451c6e9d6f3STheodore Ts'o 
14521da177e4SLinus Torvalds /********************************************************************
14531da177e4SLinus Torvalds  *
14541da177e4SLinus Torvalds  * Sysctl interface
14551da177e4SLinus Torvalds  *
14561da177e4SLinus Torvalds  ********************************************************************/
14571da177e4SLinus Torvalds 
14581da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
14591da177e4SLinus Torvalds 
14601da177e4SLinus Torvalds #include <linux/sysctl.h>
14611da177e4SLinus Torvalds 
1462db61ffe3SFabio Estevam static int random_min_urandom_seed = 60;
1463489c7fc4SJason A. Donenfeld static int random_write_wakeup_bits = POOL_MIN_BITS;
1464489c7fc4SJason A. Donenfeld static int sysctl_poolsize = POOL_BITS;
14651da177e4SLinus Torvalds static char sysctl_bootid[16];
14661da177e4SLinus Torvalds 
14671da177e4SLinus Torvalds /*
1468f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
14691da177e4SLinus Torvalds  * UUID.  The difference is in whether table->data is NULL; if it is,
14701da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
14711da177e4SLinus Torvalds  *
1472f22052b2SGreg Price  * If the user accesses this via the proc interface, the UUID will be
1473f22052b2SGreg Price  * returned as an ASCII string in the standard UUID format; if via the
1474f22052b2SGreg Price  * sysctl system call, as 16 bytes of binary data.
14751da177e4SLinus Torvalds  */
1476248045b8SJason A. Donenfeld static int proc_do_uuid(struct ctl_table *table, int write, void *buffer,
1477248045b8SJason A. Donenfeld 			size_t *lenp, loff_t *ppos)
14781da177e4SLinus Torvalds {
1479a151427eSJoe Perches 	struct ctl_table fake_table;
14801da177e4SLinus Torvalds 	unsigned char buf[64], tmp_uuid[16], *uuid;
14811da177e4SLinus Torvalds 
14821da177e4SLinus Torvalds 	uuid = table->data;
14831da177e4SLinus Torvalds 	if (!uuid) {
14841da177e4SLinus Torvalds 		uuid = tmp_uuid;
14851da177e4SLinus Torvalds 		generate_random_uuid(uuid);
148644e4360fSMathieu Desnoyers 	} else {
148744e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
148844e4360fSMathieu Desnoyers 
148944e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
149044e4360fSMathieu Desnoyers 		if (!uuid[8])
149144e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
149244e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
149344e4360fSMathieu Desnoyers 	}
14941da177e4SLinus Torvalds 
149535900771SJoe Perches 	sprintf(buf, "%pU", uuid);
149635900771SJoe Perches 
14971da177e4SLinus Torvalds 	fake_table.data = buf;
14981da177e4SLinus Torvalds 	fake_table.maxlen = sizeof(buf);
14991da177e4SLinus Torvalds 
15008d65af78SAlexey Dobriyan 	return proc_dostring(&fake_table, write, buffer, lenp, ppos);
15011da177e4SLinus Torvalds }
15021da177e4SLinus Torvalds 
15035475e8f0SXiaoming Ni static struct ctl_table random_table[] = {
15041da177e4SLinus Torvalds 	{
15051da177e4SLinus Torvalds 		.procname	= "poolsize",
15061da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
15071da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15081da177e4SLinus Torvalds 		.mode		= 0444,
15096d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
15101da177e4SLinus Torvalds 	},
15111da177e4SLinus Torvalds 	{
15121da177e4SLinus Torvalds 		.procname	= "entropy_avail",
1513c5704490SJason A. Donenfeld 		.data		= &input_pool.entropy_count,
15141da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15151da177e4SLinus Torvalds 		.mode		= 0444,
1516c5704490SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
15171da177e4SLinus Torvalds 	},
15181da177e4SLinus Torvalds 	{
15191da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
15202132a96fSGreg Price 		.data		= &random_write_wakeup_bits,
15211da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
15221da177e4SLinus Torvalds 		.mode		= 0644,
1523489c7fc4SJason A. Donenfeld 		.proc_handler	= proc_dointvec,
15241da177e4SLinus Torvalds 	},
15251da177e4SLinus Torvalds 	{
1526f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
1527f5c2742cSTheodore Ts'o 		.data		= &random_min_urandom_seed,
1528f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1529f5c2742cSTheodore Ts'o 		.mode		= 0644,
1530f5c2742cSTheodore Ts'o 		.proc_handler	= proc_dointvec,
1531f5c2742cSTheodore Ts'o 	},
1532f5c2742cSTheodore Ts'o 	{
15331da177e4SLinus Torvalds 		.procname	= "boot_id",
15341da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
15351da177e4SLinus Torvalds 		.maxlen		= 16,
15361da177e4SLinus Torvalds 		.mode		= 0444,
15376d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
15381da177e4SLinus Torvalds 	},
15391da177e4SLinus Torvalds 	{
15401da177e4SLinus Torvalds 		.procname	= "uuid",
15411da177e4SLinus Torvalds 		.maxlen		= 16,
15421da177e4SLinus Torvalds 		.mode		= 0444,
15436d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
15441da177e4SLinus Torvalds 	},
154543759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
154643759d4fSTheodore Ts'o 	{
154743759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_cycles",
154843759d4fSTheodore Ts'o 		.data		= &avg_cycles,
154943759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_cycles),
155043759d4fSTheodore Ts'o 		.mode		= 0444,
155143759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
155243759d4fSTheodore Ts'o 	},
155343759d4fSTheodore Ts'o 	{
155443759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_deviation",
155543759d4fSTheodore Ts'o 		.data		= &avg_deviation,
155643759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_deviation),
155743759d4fSTheodore Ts'o 		.mode		= 0444,
155843759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
155943759d4fSTheodore Ts'o 	},
156043759d4fSTheodore Ts'o #endif
1561894d2491SEric W. Biederman 	{ }
15621da177e4SLinus Torvalds };
15635475e8f0SXiaoming Ni 
15645475e8f0SXiaoming Ni /*
15655475e8f0SXiaoming Ni  * rand_initialize() is called before sysctl_init(),
15665475e8f0SXiaoming Ni  * so we cannot call register_sysctl_init() in rand_initialize()
15675475e8f0SXiaoming Ni  */
15685475e8f0SXiaoming Ni static int __init random_sysctls_init(void)
15695475e8f0SXiaoming Ni {
15705475e8f0SXiaoming Ni 	register_sysctl_init("kernel/random", random_table);
15715475e8f0SXiaoming Ni 	return 0;
15725475e8f0SXiaoming Ni }
15735475e8f0SXiaoming Ni device_initcall(random_sysctls_init);
15741da177e4SLinus Torvalds #endif	/* CONFIG_SYSCTL */
15751da177e4SLinus Torvalds 
157677760fd7SJason A. Donenfeld static atomic_t batch_generation = ATOMIC_INIT(0);
157777760fd7SJason A. Donenfeld 
1578f5b98461SJason A. Donenfeld struct batched_entropy {
1579f5b98461SJason A. Donenfeld 	union {
15801ca1b917SEric Biggers 		u64 entropy_u64[CHACHA_BLOCK_SIZE / sizeof(u64)];
15811ca1b917SEric Biggers 		u32 entropy_u32[CHACHA_BLOCK_SIZE / sizeof(u32)];
1582f5b98461SJason A. Donenfeld 	};
158377760fd7SJason A. Donenfeld 	local_lock_t lock;
1584f5b98461SJason A. Donenfeld 	unsigned int position;
158577760fd7SJason A. Donenfeld 	int generation;
1586f5b98461SJason A. Donenfeld };
1587b1132deaSEric Biggers 
15881da177e4SLinus Torvalds /*
1589f5b98461SJason A. Donenfeld  * Get a random word for internal kernel use only. The quality of the random
159069efea71SJason A. Donenfeld  * number is good as /dev/urandom, but there is no backtrack protection, with
159169efea71SJason A. Donenfeld  * the goal of being quite fast and not depleting entropy. In order to ensure
1592e297a783SJason A. Donenfeld  * that the randomness provided by this function is okay, the function
159369efea71SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once at any
159469efea71SJason A. Donenfeld  * point prior.
15951da177e4SLinus Torvalds  */
1596b7d5dc21SSebastian Andrzej Siewior static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
159777760fd7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_u64.lock)
1598b7d5dc21SSebastian Andrzej Siewior };
1599b7d5dc21SSebastian Andrzej Siewior 
1600c440408cSJason A. Donenfeld u64 get_random_u64(void)
1601ec9ee4acSDaniel Cashman {
1602c440408cSJason A. Donenfeld 	u64 ret;
1603b7d5dc21SSebastian Andrzej Siewior 	unsigned long flags;
1604f5b98461SJason A. Donenfeld 	struct batched_entropy *batch;
1605eecabf56STheodore Ts'o 	static void *previous;
160677760fd7SJason A. Donenfeld 	int next_gen;
1607ec9ee4acSDaniel Cashman 
1608eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
1609d06bfd19SJason A. Donenfeld 
161077760fd7SJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_u64.lock, flags);
1611b7d5dc21SSebastian Andrzej Siewior 	batch = raw_cpu_ptr(&batched_entropy_u64);
161277760fd7SJason A. Donenfeld 
161377760fd7SJason A. Donenfeld 	next_gen = atomic_read(&batch_generation);
161477760fd7SJason A. Donenfeld 	if (batch->position % ARRAY_SIZE(batch->entropy_u64) == 0 ||
161577760fd7SJason A. Donenfeld 	    next_gen != batch->generation) {
1616a5e9f557SEric Biggers 		extract_crng((u8 *)batch->entropy_u64);
1617f5b98461SJason A. Donenfeld 		batch->position = 0;
161877760fd7SJason A. Donenfeld 		batch->generation = next_gen;
1619f5b98461SJason A. Donenfeld 	}
162077760fd7SJason A. Donenfeld 
1621c440408cSJason A. Donenfeld 	ret = batch->entropy_u64[batch->position++];
162277760fd7SJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_u64.lock, flags);
1623ec9ee4acSDaniel Cashman 	return ret;
1624ec9ee4acSDaniel Cashman }
1625c440408cSJason A. Donenfeld EXPORT_SYMBOL(get_random_u64);
1626ec9ee4acSDaniel Cashman 
1627b7d5dc21SSebastian Andrzej Siewior static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
162877760fd7SJason A. Donenfeld 	.lock = INIT_LOCAL_LOCK(batched_entropy_u32.lock)
1629b7d5dc21SSebastian Andrzej Siewior };
163077760fd7SJason A. Donenfeld 
1631c440408cSJason A. Donenfeld u32 get_random_u32(void)
1632f5b98461SJason A. Donenfeld {
1633c440408cSJason A. Donenfeld 	u32 ret;
1634b7d5dc21SSebastian Andrzej Siewior 	unsigned long flags;
1635f5b98461SJason A. Donenfeld 	struct batched_entropy *batch;
1636eecabf56STheodore Ts'o 	static void *previous;
163777760fd7SJason A. Donenfeld 	int next_gen;
1638f5b98461SJason A. Donenfeld 
1639eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
1640d06bfd19SJason A. Donenfeld 
164177760fd7SJason A. Donenfeld 	local_lock_irqsave(&batched_entropy_u32.lock, flags);
1642b7d5dc21SSebastian Andrzej Siewior 	batch = raw_cpu_ptr(&batched_entropy_u32);
164377760fd7SJason A. Donenfeld 
164477760fd7SJason A. Donenfeld 	next_gen = atomic_read(&batch_generation);
164577760fd7SJason A. Donenfeld 	if (batch->position % ARRAY_SIZE(batch->entropy_u32) == 0 ||
164677760fd7SJason A. Donenfeld 	    next_gen != batch->generation) {
1647a5e9f557SEric Biggers 		extract_crng((u8 *)batch->entropy_u32);
1648f5b98461SJason A. Donenfeld 		batch->position = 0;
164977760fd7SJason A. Donenfeld 		batch->generation = next_gen;
1650f5b98461SJason A. Donenfeld 	}
165177760fd7SJason A. Donenfeld 
1652c440408cSJason A. Donenfeld 	ret = batch->entropy_u32[batch->position++];
165377760fd7SJason A. Donenfeld 	local_unlock_irqrestore(&batched_entropy_u32.lock, flags);
1654f5b98461SJason A. Donenfeld 	return ret;
1655f5b98461SJason A. Donenfeld }
1656c440408cSJason A. Donenfeld EXPORT_SYMBOL(get_random_u32);
1657f5b98461SJason A. Donenfeld 
1658b169c13dSJason A. Donenfeld /* It's important to invalidate all potential batched entropy that might
1659b169c13dSJason A. Donenfeld  * be stored before the crng is initialized, which we can do lazily by
166077760fd7SJason A. Donenfeld  * bumping the generation counter.
166177760fd7SJason A. Donenfeld  */
1662b169c13dSJason A. Donenfeld static void invalidate_batched_entropy(void)
1663b169c13dSJason A. Donenfeld {
166477760fd7SJason A. Donenfeld 	atomic_inc(&batch_generation);
1665b169c13dSJason A. Donenfeld }
1666b169c13dSJason A. Donenfeld 
166799fdafdeSJason Cooper /**
166899fdafdeSJason Cooper  * randomize_page - Generate a random, page aligned address
166999fdafdeSJason Cooper  * @start:	The smallest acceptable address the caller will take.
167099fdafdeSJason Cooper  * @range:	The size of the area, starting at @start, within which the
167199fdafdeSJason Cooper  *		random address must fall.
167299fdafdeSJason Cooper  *
167399fdafdeSJason Cooper  * If @start + @range would overflow, @range is capped.
167499fdafdeSJason Cooper  *
167599fdafdeSJason Cooper  * NOTE: Historical use of randomize_range, which this replaces, presumed that
167699fdafdeSJason Cooper  * @start was already page aligned.  We now align it regardless.
167799fdafdeSJason Cooper  *
167899fdafdeSJason Cooper  * Return: A page aligned address within [start, start + range).  On error,
167999fdafdeSJason Cooper  * @start is returned.
168099fdafdeSJason Cooper  */
1681248045b8SJason A. Donenfeld unsigned long randomize_page(unsigned long start, unsigned long range)
168299fdafdeSJason Cooper {
168399fdafdeSJason Cooper 	if (!PAGE_ALIGNED(start)) {
168499fdafdeSJason Cooper 		range -= PAGE_ALIGN(start) - start;
168599fdafdeSJason Cooper 		start = PAGE_ALIGN(start);
168699fdafdeSJason Cooper 	}
168799fdafdeSJason Cooper 
168899fdafdeSJason Cooper 	if (start > ULONG_MAX - range)
168999fdafdeSJason Cooper 		range = ULONG_MAX - start;
169099fdafdeSJason Cooper 
169199fdafdeSJason Cooper 	range >>= PAGE_SHIFT;
169299fdafdeSJason Cooper 
169399fdafdeSJason Cooper 	if (range == 0)
169499fdafdeSJason Cooper 		return start;
169599fdafdeSJason Cooper 
169699fdafdeSJason Cooper 	return start + (get_random_long() % range << PAGE_SHIFT);
169799fdafdeSJason Cooper }
169899fdafdeSJason Cooper 
1699c84dbf61STorsten Duwe /* Interface for in-kernel drivers of true hardware RNGs.
1700c84dbf61STorsten Duwe  * Those devices may produce endless random bits and will be throttled
1701c84dbf61STorsten Duwe  * when our pool is full.
1702c84dbf61STorsten Duwe  */
1703c84dbf61STorsten Duwe void add_hwgenerator_randomness(const char *buffer, size_t count,
1704c84dbf61STorsten Duwe 				size_t entropy)
1705c84dbf61STorsten Duwe {
170643838a23STheodore Ts'o 	if (unlikely(crng_init == 0)) {
170773c7733fSJason A. Donenfeld 		size_t ret = crng_fast_load(buffer, count);
170890ed1e67SJason A. Donenfeld 		mix_pool_bytes(buffer, ret);
170973c7733fSJason A. Donenfeld 		count -= ret;
171073c7733fSJason A. Donenfeld 		buffer += ret;
171173c7733fSJason A. Donenfeld 		if (!count || crng_init == 0)
1712e192be9dSTheodore Ts'o 			return;
17133371f3daSTheodore Ts'o 	}
1714e192be9dSTheodore Ts'o 
1715c321e907SDominik Brodowski 	/* Throttle writing if we're above the trickle threshold.
1716489c7fc4SJason A. Donenfeld 	 * We'll be woken up again once below POOL_MIN_BITS, when
1717489c7fc4SJason A. Donenfeld 	 * the calling thread is about to terminate, or once
1718489c7fc4SJason A. Donenfeld 	 * CRNG_RESEED_INTERVAL has elapsed.
1719e192be9dSTheodore Ts'o 	 */
1720c321e907SDominik Brodowski 	wait_event_interruptible_timeout(random_write_wait,
1721f7e67b8eSDominik Brodowski 			!system_wq || kthread_should_stop() ||
1722489c7fc4SJason A. Donenfeld 			input_pool.entropy_count < POOL_MIN_BITS,
1723c321e907SDominik Brodowski 			CRNG_RESEED_INTERVAL);
172490ed1e67SJason A. Donenfeld 	mix_pool_bytes(buffer, count);
172590ed1e67SJason A. Donenfeld 	credit_entropy_bits(entropy);
1726c84dbf61STorsten Duwe }
1727c84dbf61STorsten Duwe EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
1728428826f5SHsin-Yi Wang 
1729428826f5SHsin-Yi Wang /* Handle random seed passed by bootloader.
1730428826f5SHsin-Yi Wang  * If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
1731428826f5SHsin-Yi Wang  * it would be regarded as device data.
1732428826f5SHsin-Yi Wang  * The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
1733428826f5SHsin-Yi Wang  */
1734428826f5SHsin-Yi Wang void add_bootloader_randomness(const void *buf, unsigned int size)
1735428826f5SHsin-Yi Wang {
1736428826f5SHsin-Yi Wang 	if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
1737428826f5SHsin-Yi Wang 		add_hwgenerator_randomness(buf, size, size * 8);
1738428826f5SHsin-Yi Wang 	else
1739428826f5SHsin-Yi Wang 		add_device_randomness(buf, size);
1740428826f5SHsin-Yi Wang }
1741428826f5SHsin-Yi Wang EXPORT_SYMBOL_GPL(add_bootloader_randomness);
1742