xref: /linux/drivers/char/random.c (revision 727d499a6f4f29b6abdb635032f5e53e5905aedb)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * random.c -- A strong random number generator
31da177e4SLinus Torvalds  *
4b169c13dSJason A. Donenfeld  * Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All
5b169c13dSJason A. Donenfeld  * Rights Reserved.
6b169c13dSJason A. Donenfeld  *
79e95ce27SMatt Mackall  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
81da177e4SLinus Torvalds  *
91da177e4SLinus Torvalds  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
101da177e4SLinus Torvalds  * rights reserved.
111da177e4SLinus Torvalds  *
121da177e4SLinus Torvalds  * Redistribution and use in source and binary forms, with or without
131da177e4SLinus Torvalds  * modification, are permitted provided that the following conditions
141da177e4SLinus Torvalds  * are met:
151da177e4SLinus Torvalds  * 1. Redistributions of source code must retain the above copyright
161da177e4SLinus Torvalds  *    notice, and the entire permission notice in its entirety,
171da177e4SLinus Torvalds  *    including the disclaimer of warranties.
181da177e4SLinus Torvalds  * 2. Redistributions in binary form must reproduce the above copyright
191da177e4SLinus Torvalds  *    notice, this list of conditions and the following disclaimer in the
201da177e4SLinus Torvalds  *    documentation and/or other materials provided with the distribution.
211da177e4SLinus Torvalds  * 3. The name of the author may not be used to endorse or promote
221da177e4SLinus Torvalds  *    products derived from this software without specific prior
231da177e4SLinus Torvalds  *    written permission.
241da177e4SLinus Torvalds  *
251da177e4SLinus Torvalds  * ALTERNATIVELY, this product may be distributed under the terms of
261da177e4SLinus Torvalds  * the GNU General Public License, in which case the provisions of the GPL are
271da177e4SLinus Torvalds  * required INSTEAD OF the above restrictions.  (This clause is
281da177e4SLinus Torvalds  * necessary due to a potential bad interaction between the GPL and
291da177e4SLinus Torvalds  * the restrictions contained in a BSD-style copyright.)
301da177e4SLinus Torvalds  *
311da177e4SLinus Torvalds  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
321da177e4SLinus Torvalds  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
331da177e4SLinus Torvalds  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
341da177e4SLinus Torvalds  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
351da177e4SLinus Torvalds  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
361da177e4SLinus Torvalds  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
371da177e4SLinus Torvalds  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
381da177e4SLinus Torvalds  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
391da177e4SLinus Torvalds  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
401da177e4SLinus Torvalds  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
411da177e4SLinus Torvalds  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
421da177e4SLinus Torvalds  * DAMAGE.
431da177e4SLinus Torvalds  */
441da177e4SLinus Torvalds 
451da177e4SLinus Torvalds /*
461da177e4SLinus Torvalds  * (now, with legal B.S. out of the way.....)
471da177e4SLinus Torvalds  *
481da177e4SLinus Torvalds  * This routine gathers environmental noise from device drivers, etc.,
491da177e4SLinus Torvalds  * and returns good random numbers, suitable for cryptographic use.
501da177e4SLinus Torvalds  * Besides the obvious cryptographic uses, these numbers are also good
511da177e4SLinus Torvalds  * for seeding TCP sequence numbers, and other places where it is
521da177e4SLinus Torvalds  * desirable to have numbers which are not only random, but hard to
531da177e4SLinus Torvalds  * predict by an attacker.
541da177e4SLinus Torvalds  *
551da177e4SLinus Torvalds  * Theory of operation
561da177e4SLinus Torvalds  * ===================
571da177e4SLinus Torvalds  *
581da177e4SLinus Torvalds  * Computers are very predictable devices.  Hence it is extremely hard
591da177e4SLinus Torvalds  * to produce truly random numbers on a computer --- as opposed to
601da177e4SLinus Torvalds  * pseudo-random numbers, which can easily generated by using a
611da177e4SLinus Torvalds  * algorithm.  Unfortunately, it is very easy for attackers to guess
621da177e4SLinus Torvalds  * the sequence of pseudo-random number generators, and for some
631da177e4SLinus Torvalds  * applications this is not acceptable.  So instead, we must try to
641da177e4SLinus Torvalds  * gather "environmental noise" from the computer's environment, which
651da177e4SLinus Torvalds  * must be hard for outside attackers to observe, and use that to
661da177e4SLinus Torvalds  * generate random numbers.  In a Unix environment, this is best done
671da177e4SLinus Torvalds  * from inside the kernel.
681da177e4SLinus Torvalds  *
691da177e4SLinus Torvalds  * Sources of randomness from the environment include inter-keyboard
701da177e4SLinus Torvalds  * timings, inter-interrupt timings from some interrupts, and other
711da177e4SLinus Torvalds  * events which are both (a) non-deterministic and (b) hard for an
721da177e4SLinus Torvalds  * outside observer to measure.  Randomness from these sources are
731da177e4SLinus Torvalds  * added to an "entropy pool", which is mixed using a CRC-like function.
741da177e4SLinus Torvalds  * This is not cryptographically strong, but it is adequate assuming
751da177e4SLinus Torvalds  * the randomness is not chosen maliciously, and it is fast enough that
761da177e4SLinus Torvalds  * the overhead of doing it on every interrupt is very reasonable.
771da177e4SLinus Torvalds  * As random bytes are mixed into the entropy pool, the routines keep
781da177e4SLinus Torvalds  * an *estimate* of how many bits of randomness have been stored into
791da177e4SLinus Torvalds  * the random number generator's internal state.
801da177e4SLinus Torvalds  *
811da177e4SLinus Torvalds  * When random bytes are desired, they are obtained by taking the SHA
821da177e4SLinus Torvalds  * hash of the contents of the "entropy pool".  The SHA hash avoids
831da177e4SLinus Torvalds  * exposing the internal state of the entropy pool.  It is believed to
841da177e4SLinus Torvalds  * be computationally infeasible to derive any useful information
851da177e4SLinus Torvalds  * about the input of SHA from its output.  Even if it is possible to
861da177e4SLinus Torvalds  * analyze SHA in some clever way, as long as the amount of data
871da177e4SLinus Torvalds  * returned from the generator is less than the inherent entropy in
881da177e4SLinus Torvalds  * the pool, the output data is totally unpredictable.  For this
891da177e4SLinus Torvalds  * reason, the routine decreases its internal estimate of how many
901da177e4SLinus Torvalds  * bits of "true randomness" are contained in the entropy pool as it
911da177e4SLinus Torvalds  * outputs random numbers.
921da177e4SLinus Torvalds  *
931da177e4SLinus Torvalds  * If this estimate goes to zero, the routine can still generate
941da177e4SLinus Torvalds  * random numbers; however, an attacker may (at least in theory) be
951da177e4SLinus Torvalds  * able to infer the future output of the generator from prior
961da177e4SLinus Torvalds  * outputs.  This requires successful cryptanalysis of SHA, which is
971da177e4SLinus Torvalds  * not believed to be feasible, but there is a remote possibility.
981da177e4SLinus Torvalds  * Nonetheless, these numbers should be useful for the vast majority
991da177e4SLinus Torvalds  * of purposes.
1001da177e4SLinus Torvalds  *
1011da177e4SLinus Torvalds  * Exported interfaces ---- output
1021da177e4SLinus Torvalds  * ===============================
1031da177e4SLinus Torvalds  *
10492e507d2SGeorge Spelvin  * There are four exported interfaces; two for use within the kernel,
10592e507d2SGeorge Spelvin  * and two or use from userspace.
1061da177e4SLinus Torvalds  *
10792e507d2SGeorge Spelvin  * Exported interfaces ---- userspace output
10892e507d2SGeorge Spelvin  * -----------------------------------------
1091da177e4SLinus Torvalds  *
11092e507d2SGeorge Spelvin  * The userspace interfaces are two character devices /dev/random and
1111da177e4SLinus Torvalds  * /dev/urandom.  /dev/random is suitable for use when very high
1121da177e4SLinus Torvalds  * quality randomness is desired (for example, for key generation or
1131da177e4SLinus Torvalds  * one-time pads), as it will only return a maximum of the number of
1141da177e4SLinus Torvalds  * bits of randomness (as estimated by the random number generator)
1151da177e4SLinus Torvalds  * contained in the entropy pool.
1161da177e4SLinus Torvalds  *
1171da177e4SLinus Torvalds  * The /dev/urandom device does not have this limit, and will return
1181da177e4SLinus Torvalds  * as many bytes as are requested.  As more and more random bytes are
1191da177e4SLinus Torvalds  * requested without giving time for the entropy pool to recharge,
1201da177e4SLinus Torvalds  * this will result in random numbers that are merely cryptographically
1211da177e4SLinus Torvalds  * strong.  For many applications, however, this is acceptable.
1221da177e4SLinus Torvalds  *
12392e507d2SGeorge Spelvin  * Exported interfaces ---- kernel output
12492e507d2SGeorge Spelvin  * --------------------------------------
12592e507d2SGeorge Spelvin  *
12692e507d2SGeorge Spelvin  * The primary kernel interface is
12792e507d2SGeorge Spelvin  *
12892e507d2SGeorge Spelvin  * 	void get_random_bytes(void *buf, int nbytes);
12992e507d2SGeorge Spelvin  *
13092e507d2SGeorge Spelvin  * This interface will return the requested number of random bytes,
13192e507d2SGeorge Spelvin  * and place it in the requested buffer.  This is equivalent to a
13292e507d2SGeorge Spelvin  * read from /dev/urandom.
13392e507d2SGeorge Spelvin  *
13492e507d2SGeorge Spelvin  * For less critical applications, there are the functions:
13592e507d2SGeorge Spelvin  *
13692e507d2SGeorge Spelvin  * 	u32 get_random_u32()
13792e507d2SGeorge Spelvin  * 	u64 get_random_u64()
13892e507d2SGeorge Spelvin  * 	unsigned int get_random_int()
13992e507d2SGeorge Spelvin  * 	unsigned long get_random_long()
14092e507d2SGeorge Spelvin  *
14192e507d2SGeorge Spelvin  * These are produced by a cryptographic RNG seeded from get_random_bytes,
14292e507d2SGeorge Spelvin  * and so do not deplete the entropy pool as much.  These are recommended
14392e507d2SGeorge Spelvin  * for most in-kernel operations *if the result is going to be stored in
14492e507d2SGeorge Spelvin  * the kernel*.
14592e507d2SGeorge Spelvin  *
14692e507d2SGeorge Spelvin  * Specifically, the get_random_int() family do not attempt to do
14792e507d2SGeorge Spelvin  * "anti-backtracking".  If you capture the state of the kernel (e.g.
14892e507d2SGeorge Spelvin  * by snapshotting the VM), you can figure out previous get_random_int()
14992e507d2SGeorge Spelvin  * return values.  But if the value is stored in the kernel anyway,
15092e507d2SGeorge Spelvin  * this is not a problem.
15192e507d2SGeorge Spelvin  *
15292e507d2SGeorge Spelvin  * It *is* safe to expose get_random_int() output to attackers (e.g. as
15392e507d2SGeorge Spelvin  * network cookies); given outputs 1..n, it's not feasible to predict
15492e507d2SGeorge Spelvin  * outputs 0 or n+1.  The only concern is an attacker who breaks into
15592e507d2SGeorge Spelvin  * the kernel later; the get_random_int() engine is not reseeded as
15692e507d2SGeorge Spelvin  * often as the get_random_bytes() one.
15792e507d2SGeorge Spelvin  *
15892e507d2SGeorge Spelvin  * get_random_bytes() is needed for keys that need to stay secret after
15992e507d2SGeorge Spelvin  * they are erased from the kernel.  For example, any key that will
16092e507d2SGeorge Spelvin  * be wrapped and stored encrypted.  And session encryption keys: we'd
16192e507d2SGeorge Spelvin  * like to know that after the session is closed and the keys erased,
16292e507d2SGeorge Spelvin  * the plaintext is unrecoverable to someone who recorded the ciphertext.
16392e507d2SGeorge Spelvin  *
16492e507d2SGeorge Spelvin  * But for network ports/cookies, stack canaries, PRNG seeds, address
16592e507d2SGeorge Spelvin  * space layout randomization, session *authentication* keys, or other
16692e507d2SGeorge Spelvin  * applications where the sensitive data is stored in the kernel in
16792e507d2SGeorge Spelvin  * plaintext for as long as it's sensitive, the get_random_int() family
16892e507d2SGeorge Spelvin  * is just fine.
16992e507d2SGeorge Spelvin  *
17092e507d2SGeorge Spelvin  * Consider ASLR.  We want to keep the address space secret from an
17192e507d2SGeorge Spelvin  * outside attacker while the process is running, but once the address
17292e507d2SGeorge Spelvin  * space is torn down, it's of no use to an attacker any more.  And it's
17392e507d2SGeorge Spelvin  * stored in kernel data structures as long as it's alive, so worrying
17492e507d2SGeorge Spelvin  * about an attacker's ability to extrapolate it from the get_random_int()
17592e507d2SGeorge Spelvin  * CRNG is silly.
17692e507d2SGeorge Spelvin  *
17792e507d2SGeorge Spelvin  * Even some cryptographic keys are safe to generate with get_random_int().
17892e507d2SGeorge Spelvin  * In particular, keys for SipHash are generally fine.  Here, knowledge
17992e507d2SGeorge Spelvin  * of the key authorizes you to do something to a kernel object (inject
18092e507d2SGeorge Spelvin  * packets to a network connection, or flood a hash table), and the
18192e507d2SGeorge Spelvin  * key is stored with the object being protected.  Once it goes away,
18292e507d2SGeorge Spelvin  * we no longer care if anyone knows the key.
18392e507d2SGeorge Spelvin  *
18492e507d2SGeorge Spelvin  * prandom_u32()
18592e507d2SGeorge Spelvin  * -------------
18692e507d2SGeorge Spelvin  *
18792e507d2SGeorge Spelvin  * For even weaker applications, see the pseudorandom generator
18892e507d2SGeorge Spelvin  * prandom_u32(), prandom_max(), and prandom_bytes().  If the random
18992e507d2SGeorge Spelvin  * numbers aren't security-critical at all, these are *far* cheaper.
19092e507d2SGeorge Spelvin  * Useful for self-tests, random error simulation, randomized backoffs,
19192e507d2SGeorge Spelvin  * and any other application where you trust that nobody is trying to
19292e507d2SGeorge Spelvin  * maliciously mess with you by guessing the "random" numbers.
19392e507d2SGeorge Spelvin  *
1941da177e4SLinus Torvalds  * Exported interfaces ---- input
1951da177e4SLinus Torvalds  * ==============================
1961da177e4SLinus Torvalds  *
1971da177e4SLinus Torvalds  * The current exported interfaces for gathering environmental noise
1981da177e4SLinus Torvalds  * from the devices are:
1991da177e4SLinus Torvalds  *
200a2080a67SLinus Torvalds  *	void add_device_randomness(const void *buf, unsigned int size);
2011da177e4SLinus Torvalds  * 	void add_input_randomness(unsigned int type, unsigned int code,
2021da177e4SLinus Torvalds  *                                unsigned int value);
203775f4b29STheodore Ts'o  *	void add_interrupt_randomness(int irq, int irq_flags);
204442a4fffSJarod Wilson  * 	void add_disk_randomness(struct gendisk *disk);
2051da177e4SLinus Torvalds  *
206a2080a67SLinus Torvalds  * add_device_randomness() is for adding data to the random pool that
207a2080a67SLinus Torvalds  * is likely to differ between two devices (or possibly even per boot).
208a2080a67SLinus Torvalds  * This would be things like MAC addresses or serial numbers, or the
209a2080a67SLinus Torvalds  * read-out of the RTC. This does *not* add any actual entropy to the
210a2080a67SLinus Torvalds  * pool, but it initializes the pool to different values for devices
211a2080a67SLinus Torvalds  * that might otherwise be identical and have very little entropy
212a2080a67SLinus Torvalds  * available to them (particularly common in the embedded world).
213a2080a67SLinus Torvalds  *
2141da177e4SLinus Torvalds  * add_input_randomness() uses the input layer interrupt timing, as well as
2151da177e4SLinus Torvalds  * the event type information from the hardware.
2161da177e4SLinus Torvalds  *
217775f4b29STheodore Ts'o  * add_interrupt_randomness() uses the interrupt timing as random
218775f4b29STheodore Ts'o  * inputs to the entropy pool. Using the cycle counters and the irq source
219775f4b29STheodore Ts'o  * as inputs, it feeds the randomness roughly once a second.
220442a4fffSJarod Wilson  *
221442a4fffSJarod Wilson  * add_disk_randomness() uses what amounts to the seek time of block
222442a4fffSJarod Wilson  * layer request events, on a per-disk_devt basis, as input to the
223442a4fffSJarod Wilson  * entropy pool. Note that high-speed solid state drives with very low
224442a4fffSJarod Wilson  * seek times do not make for good sources of entropy, as their seek
225442a4fffSJarod Wilson  * times are usually fairly consistent.
2261da177e4SLinus Torvalds  *
2271da177e4SLinus Torvalds  * All of these routines try to estimate how many bits of randomness a
2281da177e4SLinus Torvalds  * particular randomness source.  They do this by keeping track of the
2291da177e4SLinus Torvalds  * first and second order deltas of the event timings.
2301da177e4SLinus Torvalds  *
2311da177e4SLinus Torvalds  * Ensuring unpredictability at system startup
2321da177e4SLinus Torvalds  * ============================================
2331da177e4SLinus Torvalds  *
2341da177e4SLinus Torvalds  * When any operating system starts up, it will go through a sequence
2351da177e4SLinus Torvalds  * of actions that are fairly predictable by an adversary, especially
2361da177e4SLinus Torvalds  * if the start-up does not involve interaction with a human operator.
2371da177e4SLinus Torvalds  * This reduces the actual number of bits of unpredictability in the
2381da177e4SLinus Torvalds  * entropy pool below the value in entropy_count.  In order to
2391da177e4SLinus Torvalds  * counteract this effect, it helps to carry information in the
2401da177e4SLinus Torvalds  * entropy pool across shut-downs and start-ups.  To do this, put the
2411da177e4SLinus Torvalds  * following lines an appropriate script which is run during the boot
2421da177e4SLinus Torvalds  * sequence:
2431da177e4SLinus Torvalds  *
2441da177e4SLinus Torvalds  *	echo "Initializing random number generator..."
2451da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
2461da177e4SLinus Torvalds  *	# Carry a random seed from start-up to start-up
2471da177e4SLinus Torvalds  *	# Load and then save the whole entropy pool
2481da177e4SLinus Torvalds  *	if [ -f $random_seed ]; then
2491da177e4SLinus Torvalds  *		cat $random_seed >/dev/urandom
2501da177e4SLinus Torvalds  *	else
2511da177e4SLinus Torvalds  *		touch $random_seed
2521da177e4SLinus Torvalds  *	fi
2531da177e4SLinus Torvalds  *	chmod 600 $random_seed
2541da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
2551da177e4SLinus Torvalds  *
2561da177e4SLinus Torvalds  * and the following lines in an appropriate script which is run as
2571da177e4SLinus Torvalds  * the system is shutdown:
2581da177e4SLinus Torvalds  *
2591da177e4SLinus Torvalds  *	# Carry a random seed from shut-down to start-up
2601da177e4SLinus Torvalds  *	# Save the whole entropy pool
2611da177e4SLinus Torvalds  *	echo "Saving random seed..."
2621da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
2631da177e4SLinus Torvalds  *	touch $random_seed
2641da177e4SLinus Torvalds  *	chmod 600 $random_seed
2651da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
2661da177e4SLinus Torvalds  *
2671da177e4SLinus Torvalds  * For example, on most modern systems using the System V init
2681da177e4SLinus Torvalds  * scripts, such code fragments would be found in
2691da177e4SLinus Torvalds  * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
2701da177e4SLinus Torvalds  * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
2711da177e4SLinus Torvalds  *
2721da177e4SLinus Torvalds  * Effectively, these commands cause the contents of the entropy pool
2731da177e4SLinus Torvalds  * to be saved at shut-down time and reloaded into the entropy pool at
2741da177e4SLinus Torvalds  * start-up.  (The 'dd' in the addition to the bootup script is to
2751da177e4SLinus Torvalds  * make sure that /etc/random-seed is different for every start-up,
2761da177e4SLinus Torvalds  * even if the system crashes without executing rc.0.)  Even with
2771da177e4SLinus Torvalds  * complete knowledge of the start-up activities, predicting the state
2781da177e4SLinus Torvalds  * of the entropy pool requires knowledge of the previous history of
2791da177e4SLinus Torvalds  * the system.
2801da177e4SLinus Torvalds  *
2811da177e4SLinus Torvalds  * Configuring the /dev/random driver under Linux
2821da177e4SLinus Torvalds  * ==============================================
2831da177e4SLinus Torvalds  *
2841da177e4SLinus Torvalds  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
2851da177e4SLinus Torvalds  * the /dev/mem major number (#1).  So if your system does not have
2861da177e4SLinus Torvalds  * /dev/random and /dev/urandom created already, they can be created
2871da177e4SLinus Torvalds  * by using the commands:
2881da177e4SLinus Torvalds  *
2891da177e4SLinus Torvalds  * 	mknod /dev/random c 1 8
2901da177e4SLinus Torvalds  * 	mknod /dev/urandom c 1 9
2911da177e4SLinus Torvalds  *
2921da177e4SLinus Torvalds  * Acknowledgements:
2931da177e4SLinus Torvalds  * =================
2941da177e4SLinus Torvalds  *
2951da177e4SLinus Torvalds  * Ideas for constructing this random number generator were derived
2961da177e4SLinus Torvalds  * from Pretty Good Privacy's random number generator, and from private
2971da177e4SLinus Torvalds  * discussions with Phil Karn.  Colin Plumb provided a faster random
2981da177e4SLinus Torvalds  * number generator, which speed up the mixing function of the entropy
2991da177e4SLinus Torvalds  * pool, taken from PGPfone.  Dale Worley has also contributed many
3001da177e4SLinus Torvalds  * useful ideas and suggestions to improve this driver.
3011da177e4SLinus Torvalds  *
3021da177e4SLinus Torvalds  * Any flaws in the design are solely my responsibility, and should
3031da177e4SLinus Torvalds  * not be attributed to the Phil, Colin, or any of authors of PGP.
3041da177e4SLinus Torvalds  *
3051da177e4SLinus Torvalds  * Further background information on this topic may be obtained from
3061da177e4SLinus Torvalds  * RFC 1750, "Randomness Recommendations for Security", by Donald
3071da177e4SLinus Torvalds  * Eastlake, Steve Crocker, and Jeff Schiller.
3081da177e4SLinus Torvalds  */
3091da177e4SLinus Torvalds 
31012cd53afSYangtao Li #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31112cd53afSYangtao Li 
3121da177e4SLinus Torvalds #include <linux/utsname.h>
3131da177e4SLinus Torvalds #include <linux/module.h>
3141da177e4SLinus Torvalds #include <linux/kernel.h>
3151da177e4SLinus Torvalds #include <linux/major.h>
3161da177e4SLinus Torvalds #include <linux/string.h>
3171da177e4SLinus Torvalds #include <linux/fcntl.h>
3181da177e4SLinus Torvalds #include <linux/slab.h>
3191da177e4SLinus Torvalds #include <linux/random.h>
3201da177e4SLinus Torvalds #include <linux/poll.h>
3211da177e4SLinus Torvalds #include <linux/init.h>
3221da177e4SLinus Torvalds #include <linux/fs.h>
3231da177e4SLinus Torvalds #include <linux/genhd.h>
3241da177e4SLinus Torvalds #include <linux/interrupt.h>
32527ac792cSAndrea Righi #include <linux/mm.h>
326dd0f0cf5SMichael Ellerman #include <linux/nodemask.h>
3271da177e4SLinus Torvalds #include <linux/spinlock.h>
328c84dbf61STorsten Duwe #include <linux/kthread.h>
3291da177e4SLinus Torvalds #include <linux/percpu.h>
3301da177e4SLinus Torvalds #include <linux/cryptohash.h>
3315b739ef8SNeil Horman #include <linux/fips.h>
332775f4b29STheodore Ts'o #include <linux/ptrace.h>
3336265e169STheodore Ts'o #include <linux/workqueue.h>
334d178a1ebSYinghai Lu #include <linux/irq.h>
3354e00b339STheodore Ts'o #include <linux/ratelimit.h>
336c6e9d6f3STheodore Ts'o #include <linux/syscalls.h>
337c6e9d6f3STheodore Ts'o #include <linux/completion.h>
3388da4b8c4SAndy Shevchenko #include <linux/uuid.h>
3391ca1b917SEric Biggers #include <crypto/chacha.h>
340d178a1ebSYinghai Lu 
3411da177e4SLinus Torvalds #include <asm/processor.h>
3427c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
3431da177e4SLinus Torvalds #include <asm/irq.h>
344775f4b29STheodore Ts'o #include <asm/irq_regs.h>
3451da177e4SLinus Torvalds #include <asm/io.h>
3461da177e4SLinus Torvalds 
34700ce1db1STheodore Ts'o #define CREATE_TRACE_POINTS
34800ce1db1STheodore Ts'o #include <trace/events/random.h>
34900ce1db1STheodore Ts'o 
35043759d4fSTheodore Ts'o /* #define ADD_INTERRUPT_BENCH */
35143759d4fSTheodore Ts'o 
3521da177e4SLinus Torvalds /*
3531da177e4SLinus Torvalds  * Configuration information
3541da177e4SLinus Torvalds  */
35530e37ec5SH. Peter Anvin #define INPUT_POOL_SHIFT	12
35630e37ec5SH. Peter Anvin #define INPUT_POOL_WORDS	(1 << (INPUT_POOL_SHIFT-5))
35730e37ec5SH. Peter Anvin #define OUTPUT_POOL_SHIFT	10
35830e37ec5SH. Peter Anvin #define OUTPUT_POOL_WORDS	(1 << (OUTPUT_POOL_SHIFT-5))
359e954bc91SMatt Mackall #define EXTRACT_SIZE		10
3601da177e4SLinus Torvalds 
361392a546dSTheodore Ts'o 
362d2e7c96aSH. Peter Anvin #define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
363d2e7c96aSH. Peter Anvin 
3641da177e4SLinus Torvalds /*
36595b709b6STheodore Ts'o  * To allow fractional bits to be tracked, the entropy_count field is
36695b709b6STheodore Ts'o  * denominated in units of 1/8th bits.
36730e37ec5SH. Peter Anvin  *
3683bd0b5bfSRasmus Villemoes  * 2*(ENTROPY_SHIFT + poolbitshift) must <= 31, or the multiply in
36930e37ec5SH. Peter Anvin  * credit_entropy_bits() needs to be 64 bits wide.
370a283b5c4SH. Peter Anvin  */
371a283b5c4SH. Peter Anvin #define ENTROPY_SHIFT 3
372a283b5c4SH. Peter Anvin #define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
373a283b5c4SH. Peter Anvin 
374a283b5c4SH. Peter Anvin /*
3751da177e4SLinus Torvalds  * If the entropy count falls under this number of bits, then we
3761da177e4SLinus Torvalds  * should wake up processes which are selecting or polling on write
3771da177e4SLinus Torvalds  * access to /dev/random.
3781da177e4SLinus Torvalds  */
3792132a96fSGreg Price static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
3801da177e4SLinus Torvalds 
3811da177e4SLinus Torvalds /*
3826e9fa2c8STheodore Ts'o  * Originally, we used a primitive polynomial of degree .poolwords
3836e9fa2c8STheodore Ts'o  * over GF(2).  The taps for various sizes are defined below.  They
3846e9fa2c8STheodore Ts'o  * were chosen to be evenly spaced except for the last tap, which is 1
3856e9fa2c8STheodore Ts'o  * to get the twisting happening as fast as possible.
3861da177e4SLinus Torvalds  *
3876e9fa2c8STheodore Ts'o  * For the purposes of better mixing, we use the CRC-32 polynomial as
3886e9fa2c8STheodore Ts'o  * well to make a (modified) twisted Generalized Feedback Shift
3896e9fa2c8STheodore Ts'o  * Register.  (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR
3906e9fa2c8STheodore Ts'o  * generators.  ACM Transactions on Modeling and Computer Simulation
3916e9fa2c8STheodore Ts'o  * 2(3):179-194.  Also see M. Matsumoto & Y. Kurita, 1994.  Twisted
392dfd38750SGreg Price  * GFSR generators II.  ACM Transactions on Modeling and Computer
3936e9fa2c8STheodore Ts'o  * Simulation 4:254-266)
3941da177e4SLinus Torvalds  *
3951da177e4SLinus Torvalds  * Thanks to Colin Plumb for suggesting this.
3961da177e4SLinus Torvalds  *
3976e9fa2c8STheodore Ts'o  * The mixing operation is much less sensitive than the output hash,
3986e9fa2c8STheodore Ts'o  * where we use SHA-1.  All that we want of mixing operation is that
3996e9fa2c8STheodore Ts'o  * it be a good non-cryptographic hash; i.e. it not produce collisions
4006e9fa2c8STheodore Ts'o  * when fed "random" data of the sort we expect to see.  As long as
4016e9fa2c8STheodore Ts'o  * the pool state differs for different inputs, we have preserved the
4026e9fa2c8STheodore Ts'o  * input entropy and done a good job.  The fact that an intelligent
4036e9fa2c8STheodore Ts'o  * attacker can construct inputs that will produce controlled
4046e9fa2c8STheodore Ts'o  * alterations to the pool's state is not important because we don't
4056e9fa2c8STheodore Ts'o  * consider such inputs to contribute any randomness.  The only
4066e9fa2c8STheodore Ts'o  * property we need with respect to them is that the attacker can't
4076e9fa2c8STheodore Ts'o  * increase his/her knowledge of the pool's state.  Since all
4086e9fa2c8STheodore Ts'o  * additions are reversible (knowing the final state and the input,
4096e9fa2c8STheodore Ts'o  * you can reconstruct the initial state), if an attacker has any
4106e9fa2c8STheodore Ts'o  * uncertainty about the initial state, he/she can only shuffle that
4116e9fa2c8STheodore Ts'o  * uncertainty about, but never cause any collisions (which would
4121da177e4SLinus Torvalds  * decrease the uncertainty).
4131da177e4SLinus Torvalds  *
4146e9fa2c8STheodore Ts'o  * Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
4156e9fa2c8STheodore Ts'o  * Videau in their paper, "The Linux Pseudorandom Number Generator
4166e9fa2c8STheodore Ts'o  * Revisited" (see: http://eprint.iacr.org/2012/251.pdf).  In their
4176e9fa2c8STheodore Ts'o  * paper, they point out that we are not using a true Twisted GFSR,
4186e9fa2c8STheodore Ts'o  * since Matsumoto & Kurita used a trinomial feedback polynomial (that
4196e9fa2c8STheodore Ts'o  * is, with only three taps, instead of the six that we are using).
4206e9fa2c8STheodore Ts'o  * As a result, the resulting polynomial is neither primitive nor
4216e9fa2c8STheodore Ts'o  * irreducible, and hence does not have a maximal period over
4226e9fa2c8STheodore Ts'o  * GF(2**32).  They suggest a slight change to the generator
4236e9fa2c8STheodore Ts'o  * polynomial which improves the resulting TGFSR polynomial to be
4246e9fa2c8STheodore Ts'o  * irreducible, which we have made here.
4251da177e4SLinus Torvalds  */
42626e0854aSRasmus Villemoes static const struct poolinfo {
4273bd0b5bfSRasmus Villemoes 	int poolbitshift, poolwords, poolbytes, poolfracbits;
4283bd0b5bfSRasmus Villemoes #define S(x) ilog2(x)+5, (x), (x)*4, (x) << (ENTROPY_SHIFT+5)
4291da177e4SLinus Torvalds 	int tap1, tap2, tap3, tap4, tap5;
4301da177e4SLinus Torvalds } poolinfo_table[] = {
4316e9fa2c8STheodore Ts'o 	/* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
4326e9fa2c8STheodore Ts'o 	/* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
4336e9fa2c8STheodore Ts'o 	{ S(128),	104,	76,	51,	25,	1 },
4346e9fa2c8STheodore Ts'o 	/* was: x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 */
4356e9fa2c8STheodore Ts'o 	/* x^32 + x^26 + x^19 + x^14 + x^7 + x + 1 */
4366e9fa2c8STheodore Ts'o 	{ S(32),	26,	19,	14,	7,	1 },
4371da177e4SLinus Torvalds #if 0
4381da177e4SLinus Torvalds 	/* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
4399ed17b70SH. Peter Anvin 	{ S(2048),	1638,	1231,	819,	411,	1 },
4401da177e4SLinus Torvalds 
4411da177e4SLinus Torvalds 	/* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
4429ed17b70SH. Peter Anvin 	{ S(1024),	817,	615,	412,	204,	1 },
4431da177e4SLinus Torvalds 
4441da177e4SLinus Torvalds 	/* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
4459ed17b70SH. Peter Anvin 	{ S(1024),	819,	616,	410,	207,	2 },
4461da177e4SLinus Torvalds 
4471da177e4SLinus Torvalds 	/* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
4489ed17b70SH. Peter Anvin 	{ S(512),	411,	308,	208,	104,	1 },
4491da177e4SLinus Torvalds 
4501da177e4SLinus Torvalds 	/* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
4519ed17b70SH. Peter Anvin 	{ S(512),	409,	307,	206,	102,	2 },
4521da177e4SLinus Torvalds 	/* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
4539ed17b70SH. Peter Anvin 	{ S(512),	409,	309,	205,	103,	2 },
4541da177e4SLinus Torvalds 
4551da177e4SLinus Torvalds 	/* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
4569ed17b70SH. Peter Anvin 	{ S(256),	205,	155,	101,	52,	1 },
4571da177e4SLinus Torvalds 
4581da177e4SLinus Torvalds 	/* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
4599ed17b70SH. Peter Anvin 	{ S(128),	103,	78,	51,	27,	2 },
4601da177e4SLinus Torvalds 
4611da177e4SLinus Torvalds 	/* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
4629ed17b70SH. Peter Anvin 	{ S(64),	52,	39,	26,	14,	1 },
4631da177e4SLinus Torvalds #endif
4641da177e4SLinus Torvalds };
4651da177e4SLinus Torvalds 
4661da177e4SLinus Torvalds /*
4671da177e4SLinus Torvalds  * Static global variables
4681da177e4SLinus Torvalds  */
469a11e1d43SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
4709a6f70bbSJeff Dike static struct fasync_struct *fasync;
4711da177e4SLinus Torvalds 
472205a525cSHerbert Xu static DEFINE_SPINLOCK(random_ready_list_lock);
473205a525cSHerbert Xu static LIST_HEAD(random_ready_list);
474205a525cSHerbert Xu 
475e192be9dSTheodore Ts'o struct crng_state {
476e192be9dSTheodore Ts'o 	__u32		state[16];
477e192be9dSTheodore Ts'o 	unsigned long	init_time;
478e192be9dSTheodore Ts'o 	spinlock_t	lock;
479e192be9dSTheodore Ts'o };
480e192be9dSTheodore Ts'o 
481764ed189SRasmus Villemoes static struct crng_state primary_crng = {
482e192be9dSTheodore Ts'o 	.lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
483e192be9dSTheodore Ts'o };
484e192be9dSTheodore Ts'o 
485e192be9dSTheodore Ts'o /*
486e192be9dSTheodore Ts'o  * crng_init =  0 --> Uninitialized
487e192be9dSTheodore Ts'o  *		1 --> Initialized
488e192be9dSTheodore Ts'o  *		2 --> Initialized from input_pool
489e192be9dSTheodore Ts'o  *
490e192be9dSTheodore Ts'o  * crng_init is protected by primary_crng->lock, and only increases
491e192be9dSTheodore Ts'o  * its value (from 0->1->2).
492e192be9dSTheodore Ts'o  */
493e192be9dSTheodore Ts'o static int crng_init = 0;
49443838a23STheodore Ts'o #define crng_ready() (likely(crng_init > 1))
495e192be9dSTheodore Ts'o static int crng_init_cnt = 0;
496d848e5f8STheodore Ts'o static unsigned long crng_global_init_time = 0;
4971ca1b917SEric Biggers #define CRNG_INIT_CNT_THRESH (2*CHACHA_KEY_SIZE)
4981ca1b917SEric Biggers static void _extract_crng(struct crng_state *crng, __u8 out[CHACHA_BLOCK_SIZE]);
499c92e040dSTheodore Ts'o static void _crng_backtrack_protect(struct crng_state *crng,
5001ca1b917SEric Biggers 				    __u8 tmp[CHACHA_BLOCK_SIZE], int used);
501e192be9dSTheodore Ts'o static void process_random_ready_list(void);
502eecabf56STheodore Ts'o static void _get_random_bytes(void *buf, int nbytes);
503e192be9dSTheodore Ts'o 
5044e00b339STheodore Ts'o static struct ratelimit_state unseeded_warning =
5054e00b339STheodore Ts'o 	RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
5064e00b339STheodore Ts'o static struct ratelimit_state urandom_warning =
5074e00b339STheodore Ts'o 	RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
5084e00b339STheodore Ts'o 
5094e00b339STheodore Ts'o static int ratelimit_disable __read_mostly;
5104e00b339STheodore Ts'o 
5114e00b339STheodore Ts'o module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
5124e00b339STheodore Ts'o MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
5134e00b339STheodore Ts'o 
5141da177e4SLinus Torvalds /**********************************************************************
5151da177e4SLinus Torvalds  *
5161da177e4SLinus Torvalds  * OS independent entropy store.   Here are the functions which handle
5171da177e4SLinus Torvalds  * storing entropy in an entropy pool.
5181da177e4SLinus Torvalds  *
5191da177e4SLinus Torvalds  **********************************************************************/
5201da177e4SLinus Torvalds 
5211da177e4SLinus Torvalds struct entropy_store;
5221da177e4SLinus Torvalds struct entropy_store {
52343358209SMatt Mackall 	/* read-only data: */
52430e37ec5SH. Peter Anvin 	const struct poolinfo *poolinfo;
5251da177e4SLinus Torvalds 	__u32 *pool;
5261da177e4SLinus Torvalds 	const char *name;
5271da177e4SLinus Torvalds 
5281da177e4SLinus Torvalds 	/* read-write data: */
52943358209SMatt Mackall 	spinlock_t lock;
530c59974aeSTheodore Ts'o 	unsigned short add_ptr;
531c59974aeSTheodore Ts'o 	unsigned short input_rotate;
532cda796a3SMatt Mackall 	int entropy_count;
533775f4b29STheodore Ts'o 	unsigned int initialized:1;
534c59974aeSTheodore Ts'o 	unsigned int last_data_init:1;
535e954bc91SMatt Mackall 	__u8 last_data[EXTRACT_SIZE];
5361da177e4SLinus Torvalds };
5371da177e4SLinus Torvalds 
538e192be9dSTheodore Ts'o static ssize_t extract_entropy(struct entropy_store *r, void *buf,
539e192be9dSTheodore Ts'o 			       size_t nbytes, int min, int rsvd);
540e192be9dSTheodore Ts'o static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
541e192be9dSTheodore Ts'o 				size_t nbytes, int fips);
542e192be9dSTheodore Ts'o 
543e192be9dSTheodore Ts'o static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
5440766f788SEmese Revfy static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
5451da177e4SLinus Torvalds 
5461da177e4SLinus Torvalds static struct entropy_store input_pool = {
5471da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[0],
5481da177e4SLinus Torvalds 	.name = "input",
549eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
5501da177e4SLinus Torvalds 	.pool = input_pool_data
5511da177e4SLinus Torvalds };
5521da177e4SLinus Torvalds 
553775f4b29STheodore Ts'o static __u32 const twist_table[8] = {
554775f4b29STheodore Ts'o 	0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
555775f4b29STheodore Ts'o 	0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
556775f4b29STheodore Ts'o 
5571da177e4SLinus Torvalds /*
558e68e5b66SMatt Mackall  * This function adds bytes into the entropy "pool".  It does not
5591da177e4SLinus Torvalds  * update the entropy estimate.  The caller should call
560adc782daSMatt Mackall  * credit_entropy_bits if this is appropriate.
5611da177e4SLinus Torvalds  *
5621da177e4SLinus Torvalds  * The pool is stirred with a primitive polynomial of the appropriate
5631da177e4SLinus Torvalds  * degree, and then twisted.  We twist by three bits at a time because
5641da177e4SLinus Torvalds  * it's cheap to do so and helps slightly in the expected case where
5651da177e4SLinus Torvalds  * the entropy is concentrated in the low-order bits.
5661da177e4SLinus Torvalds  */
56700ce1db1STheodore Ts'o static void _mix_pool_bytes(struct entropy_store *r, const void *in,
56885608f8eSTheodore Ts'o 			    int nbytes)
5691da177e4SLinus Torvalds {
57085608f8eSTheodore Ts'o 	unsigned long i, tap1, tap2, tap3, tap4, tap5;
571feee7697SMatt Mackall 	int input_rotate;
5721da177e4SLinus Torvalds 	int wordmask = r->poolinfo->poolwords - 1;
573e68e5b66SMatt Mackall 	const char *bytes = in;
5746d38b827SMatt Mackall 	__u32 w;
5751da177e4SLinus Torvalds 
5761da177e4SLinus Torvalds 	tap1 = r->poolinfo->tap1;
5771da177e4SLinus Torvalds 	tap2 = r->poolinfo->tap2;
5781da177e4SLinus Torvalds 	tap3 = r->poolinfo->tap3;
5791da177e4SLinus Torvalds 	tap4 = r->poolinfo->tap4;
5801da177e4SLinus Torvalds 	tap5 = r->poolinfo->tap5;
5811da177e4SLinus Torvalds 
58291fcb532STheodore Ts'o 	input_rotate = r->input_rotate;
58391fcb532STheodore Ts'o 	i = r->add_ptr;
5841da177e4SLinus Torvalds 
585e68e5b66SMatt Mackall 	/* mix one byte at a time to simplify size handling and churn faster */
586e68e5b66SMatt Mackall 	while (nbytes--) {
587c59974aeSTheodore Ts'o 		w = rol32(*bytes++, input_rotate);
588993ba211SMatt Mackall 		i = (i - 1) & wordmask;
5891da177e4SLinus Torvalds 
5901da177e4SLinus Torvalds 		/* XOR in the various taps */
591993ba211SMatt Mackall 		w ^= r->pool[i];
5921da177e4SLinus Torvalds 		w ^= r->pool[(i + tap1) & wordmask];
5931da177e4SLinus Torvalds 		w ^= r->pool[(i + tap2) & wordmask];
5941da177e4SLinus Torvalds 		w ^= r->pool[(i + tap3) & wordmask];
5951da177e4SLinus Torvalds 		w ^= r->pool[(i + tap4) & wordmask];
5961da177e4SLinus Torvalds 		w ^= r->pool[(i + tap5) & wordmask];
597993ba211SMatt Mackall 
598993ba211SMatt Mackall 		/* Mix the result back in with a twist */
5991da177e4SLinus Torvalds 		r->pool[i] = (w >> 3) ^ twist_table[w & 7];
600feee7697SMatt Mackall 
601feee7697SMatt Mackall 		/*
602feee7697SMatt Mackall 		 * Normally, we add 7 bits of rotation to the pool.
603feee7697SMatt Mackall 		 * At the beginning of the pool, add an extra 7 bits
604feee7697SMatt Mackall 		 * rotation, so that successive passes spread the
605feee7697SMatt Mackall 		 * input bits across the pool evenly.
606feee7697SMatt Mackall 		 */
607c59974aeSTheodore Ts'o 		input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
6081da177e4SLinus Torvalds 	}
6091da177e4SLinus Torvalds 
61091fcb532STheodore Ts'o 	r->input_rotate = input_rotate;
61191fcb532STheodore Ts'o 	r->add_ptr = i;
6121da177e4SLinus Torvalds }
6131da177e4SLinus Torvalds 
61400ce1db1STheodore Ts'o static void __mix_pool_bytes(struct entropy_store *r, const void *in,
61585608f8eSTheodore Ts'o 			     int nbytes)
61600ce1db1STheodore Ts'o {
61700ce1db1STheodore Ts'o 	trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
61885608f8eSTheodore Ts'o 	_mix_pool_bytes(r, in, nbytes);
61900ce1db1STheodore Ts'o }
62000ce1db1STheodore Ts'o 
621902c098aSTheodore Ts'o static void mix_pool_bytes(struct entropy_store *r, const void *in,
62285608f8eSTheodore Ts'o 			   int nbytes)
6231da177e4SLinus Torvalds {
624902c098aSTheodore Ts'o 	unsigned long flags;
625902c098aSTheodore Ts'o 
62600ce1db1STheodore Ts'o 	trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
627902c098aSTheodore Ts'o 	spin_lock_irqsave(&r->lock, flags);
62885608f8eSTheodore Ts'o 	_mix_pool_bytes(r, in, nbytes);
629902c098aSTheodore Ts'o 	spin_unlock_irqrestore(&r->lock, flags);
6301da177e4SLinus Torvalds }
6311da177e4SLinus Torvalds 
632775f4b29STheodore Ts'o struct fast_pool {
633775f4b29STheodore Ts'o 	__u32		pool[4];
634775f4b29STheodore Ts'o 	unsigned long	last;
635ee3e00e9STheodore Ts'o 	unsigned short	reg_idx;
636840f9507STheodore Ts'o 	unsigned char	count;
637775f4b29STheodore Ts'o };
638775f4b29STheodore Ts'o 
639775f4b29STheodore Ts'o /*
640775f4b29STheodore Ts'o  * This is a fast mixing routine used by the interrupt randomness
641775f4b29STheodore Ts'o  * collector.  It's hardcoded for an 128 bit pool and assumes that any
642775f4b29STheodore Ts'o  * locks that might be needed are taken by the caller.
643775f4b29STheodore Ts'o  */
64443759d4fSTheodore Ts'o static void fast_mix(struct fast_pool *f)
645775f4b29STheodore Ts'o {
64643759d4fSTheodore Ts'o 	__u32 a = f->pool[0],	b = f->pool[1];
64743759d4fSTheodore Ts'o 	__u32 c = f->pool[2],	d = f->pool[3];
648775f4b29STheodore Ts'o 
64943759d4fSTheodore Ts'o 	a += b;			c += d;
65019acc77aSGeorge Spelvin 	b = rol32(b, 6);	d = rol32(d, 27);
65143759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
652655b2264STheodore Ts'o 
65343759d4fSTheodore Ts'o 	a += b;			c += d;
65419acc77aSGeorge Spelvin 	b = rol32(b, 16);	d = rol32(d, 14);
65543759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
65643759d4fSTheodore Ts'o 
65743759d4fSTheodore Ts'o 	a += b;			c += d;
65819acc77aSGeorge Spelvin 	b = rol32(b, 6);	d = rol32(d, 27);
65943759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
66043759d4fSTheodore Ts'o 
66143759d4fSTheodore Ts'o 	a += b;			c += d;
66219acc77aSGeorge Spelvin 	b = rol32(b, 16);	d = rol32(d, 14);
66343759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
66443759d4fSTheodore Ts'o 
66543759d4fSTheodore Ts'o 	f->pool[0] = a;  f->pool[1] = b;
66643759d4fSTheodore Ts'o 	f->pool[2] = c;  f->pool[3] = d;
667655b2264STheodore Ts'o 	f->count++;
668775f4b29STheodore Ts'o }
669775f4b29STheodore Ts'o 
670205a525cSHerbert Xu static void process_random_ready_list(void)
671205a525cSHerbert Xu {
672205a525cSHerbert Xu 	unsigned long flags;
673205a525cSHerbert Xu 	struct random_ready_callback *rdy, *tmp;
674205a525cSHerbert Xu 
675205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
676205a525cSHerbert Xu 	list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
677205a525cSHerbert Xu 		struct module *owner = rdy->owner;
678205a525cSHerbert Xu 
679205a525cSHerbert Xu 		list_del_init(&rdy->list);
680205a525cSHerbert Xu 		rdy->func(rdy);
681205a525cSHerbert Xu 		module_put(owner);
682205a525cSHerbert Xu 	}
683205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
684205a525cSHerbert Xu }
685205a525cSHerbert Xu 
6861da177e4SLinus Torvalds /*
687a283b5c4SH. Peter Anvin  * Credit (or debit) the entropy store with n bits of entropy.
688a283b5c4SH. Peter Anvin  * Use credit_entropy_bits_safe() if the value comes from userspace
689a283b5c4SH. Peter Anvin  * or otherwise should be checked for extreme values.
6901da177e4SLinus Torvalds  */
691adc782daSMatt Mackall static void credit_entropy_bits(struct entropy_store *r, int nbits)
6921da177e4SLinus Torvalds {
693eb9d1bf0STheodore Ts'o 	int entropy_count, orig, has_initialized = 0;
69430e37ec5SH. Peter Anvin 	const int pool_size = r->poolinfo->poolfracbits;
69530e37ec5SH. Peter Anvin 	int nfrac = nbits << ENTROPY_SHIFT;
6961da177e4SLinus Torvalds 
697adc782daSMatt Mackall 	if (!nbits)
698adc782daSMatt Mackall 		return;
699adc782daSMatt Mackall 
700902c098aSTheodore Ts'o retry:
7016aa7de05SMark Rutland 	entropy_count = orig = READ_ONCE(r->entropy_count);
70230e37ec5SH. Peter Anvin 	if (nfrac < 0) {
70330e37ec5SH. Peter Anvin 		/* Debit */
70430e37ec5SH. Peter Anvin 		entropy_count += nfrac;
70530e37ec5SH. Peter Anvin 	} else {
70630e37ec5SH. Peter Anvin 		/*
70730e37ec5SH. Peter Anvin 		 * Credit: we have to account for the possibility of
70830e37ec5SH. Peter Anvin 		 * overwriting already present entropy.	 Even in the
70930e37ec5SH. Peter Anvin 		 * ideal case of pure Shannon entropy, new contributions
71030e37ec5SH. Peter Anvin 		 * approach the full value asymptotically:
71130e37ec5SH. Peter Anvin 		 *
71230e37ec5SH. Peter Anvin 		 * entropy <- entropy + (pool_size - entropy) *
71330e37ec5SH. Peter Anvin 		 *	(1 - exp(-add_entropy/pool_size))
71430e37ec5SH. Peter Anvin 		 *
71530e37ec5SH. Peter Anvin 		 * For add_entropy <= pool_size/2 then
71630e37ec5SH. Peter Anvin 		 * (1 - exp(-add_entropy/pool_size)) >=
71730e37ec5SH. Peter Anvin 		 *    (add_entropy/pool_size)*0.7869...
71830e37ec5SH. Peter Anvin 		 * so we can approximate the exponential with
71930e37ec5SH. Peter Anvin 		 * 3/4*add_entropy/pool_size and still be on the
72030e37ec5SH. Peter Anvin 		 * safe side by adding at most pool_size/2 at a time.
72130e37ec5SH. Peter Anvin 		 *
72230e37ec5SH. Peter Anvin 		 * The use of pool_size-2 in the while statement is to
72330e37ec5SH. Peter Anvin 		 * prevent rounding artifacts from making the loop
72430e37ec5SH. Peter Anvin 		 * arbitrarily long; this limits the loop to log2(pool_size)*2
72530e37ec5SH. Peter Anvin 		 * turns no matter how large nbits is.
72630e37ec5SH. Peter Anvin 		 */
72730e37ec5SH. Peter Anvin 		int pnfrac = nfrac;
72830e37ec5SH. Peter Anvin 		const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
72930e37ec5SH. Peter Anvin 		/* The +2 corresponds to the /4 in the denominator */
73030e37ec5SH. Peter Anvin 
73130e37ec5SH. Peter Anvin 		do {
73230e37ec5SH. Peter Anvin 			unsigned int anfrac = min(pnfrac, pool_size/2);
73330e37ec5SH. Peter Anvin 			unsigned int add =
73430e37ec5SH. Peter Anvin 				((pool_size - entropy_count)*anfrac*3) >> s;
73530e37ec5SH. Peter Anvin 
73630e37ec5SH. Peter Anvin 			entropy_count += add;
73730e37ec5SH. Peter Anvin 			pnfrac -= anfrac;
73830e37ec5SH. Peter Anvin 		} while (unlikely(entropy_count < pool_size-2 && pnfrac));
73930e37ec5SH. Peter Anvin 	}
74000ce1db1STheodore Ts'o 
741870e05b1SYangtao Li 	if (WARN_ON(entropy_count < 0)) {
74212cd53afSYangtao Li 		pr_warn("negative entropy/overflow: pool %s count %d\n",
743f80bbd8bSTheodore Ts'o 			r->name, entropy_count);
7448b76f46aSAndrew Morton 		entropy_count = 0;
74530e37ec5SH. Peter Anvin 	} else if (entropy_count > pool_size)
74630e37ec5SH. Peter Anvin 		entropy_count = pool_size;
747902c098aSTheodore Ts'o 	if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
748902c098aSTheodore Ts'o 		goto retry;
7491da177e4SLinus Torvalds 
75058be0106STheodore Ts'o 	if (has_initialized) {
751775f4b29STheodore Ts'o 		r->initialized = 1;
75258be0106STheodore Ts'o 		kill_fasync(&fasync, SIGIO, POLL_IN);
75358be0106STheodore Ts'o 	}
754775f4b29STheodore Ts'o 
755a283b5c4SH. Peter Anvin 	trace_credit_entropy_bits(r->name, nbits,
756eb9d1bf0STheodore Ts'o 				  entropy_count >> ENTROPY_SHIFT, _RET_IP_);
75700ce1db1STheodore Ts'o 
7586265e169STheodore Ts'o 	if (r == &input_pool) {
7597d1b08c4SGreg Price 		int entropy_bits = entropy_count >> ENTROPY_SHIFT;
7606265e169STheodore Ts'o 
761eb9d1bf0STheodore Ts'o 		if (crng_init < 2) {
762eb9d1bf0STheodore Ts'o 			if (entropy_bits < 128)
763eb9d1bf0STheodore Ts'o 				return;
764e192be9dSTheodore Ts'o 			crng_reseed(&primary_crng, r);
76512faac30SYangtao Li 			entropy_bits = ENTROPY_BITS(r);
766e192be9dSTheodore Ts'o 		}
7676265e169STheodore Ts'o 	}
7681da177e4SLinus Torvalds }
7691da177e4SLinus Torvalds 
77086a574deSTheodore Ts'o static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
771a283b5c4SH. Peter Anvin {
7729f886f4dSTheodore Ts'o 	const int nbits_max = r->poolinfo->poolwords * 32;
773a283b5c4SH. Peter Anvin 
77486a574deSTheodore Ts'o 	if (nbits < 0)
77586a574deSTheodore Ts'o 		return -EINVAL;
77686a574deSTheodore Ts'o 
777a283b5c4SH. Peter Anvin 	/* Cap the value to avoid overflows */
778a283b5c4SH. Peter Anvin 	nbits = min(nbits,  nbits_max);
779a283b5c4SH. Peter Anvin 
780a283b5c4SH. Peter Anvin 	credit_entropy_bits(r, nbits);
78186a574deSTheodore Ts'o 	return 0;
7821da177e4SLinus Torvalds }
7831da177e4SLinus Torvalds 
7841da177e4SLinus Torvalds /*********************************************************************
7851da177e4SLinus Torvalds  *
786e192be9dSTheodore Ts'o  * CRNG using CHACHA20
787e192be9dSTheodore Ts'o  *
788e192be9dSTheodore Ts'o  *********************************************************************/
789e192be9dSTheodore Ts'o 
790e192be9dSTheodore Ts'o #define CRNG_RESEED_INTERVAL (300*HZ)
791e192be9dSTheodore Ts'o 
792e192be9dSTheodore Ts'o static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
793e192be9dSTheodore Ts'o 
7941e7f583aSTheodore Ts'o #ifdef CONFIG_NUMA
7951e7f583aSTheodore Ts'o /*
7961e7f583aSTheodore Ts'o  * Hack to deal with crazy userspace progams when they are all trying
7971e7f583aSTheodore Ts'o  * to access /dev/urandom in parallel.  The programs are almost
7981e7f583aSTheodore Ts'o  * certainly doing something terribly wrong, but we'll work around
7991e7f583aSTheodore Ts'o  * their brain damage.
8001e7f583aSTheodore Ts'o  */
8011e7f583aSTheodore Ts'o static struct crng_state **crng_node_pool __read_mostly;
8021e7f583aSTheodore Ts'o #endif
8031e7f583aSTheodore Ts'o 
804b169c13dSJason A. Donenfeld static void invalidate_batched_entropy(void);
805fe6f1a6aSJon DeVree static void numa_crng_init(void);
806b169c13dSJason A. Donenfeld 
8079b254366SKees Cook static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
8089b254366SKees Cook static int __init parse_trust_cpu(char *arg)
8099b254366SKees Cook {
8109b254366SKees Cook 	return kstrtobool(arg, &trust_cpu);
8119b254366SKees Cook }
8129b254366SKees Cook early_param("random.trust_cpu", parse_trust_cpu);
8139b254366SKees Cook 
814e192be9dSTheodore Ts'o static void crng_initialize(struct crng_state *crng)
815e192be9dSTheodore Ts'o {
816e192be9dSTheodore Ts'o 	int		i;
81739a8883aSTheodore Ts'o 	int		arch_init = 1;
818e192be9dSTheodore Ts'o 	unsigned long	rv;
819e192be9dSTheodore Ts'o 
820e192be9dSTheodore Ts'o 	memcpy(&crng->state[0], "expand 32-byte k", 16);
821e192be9dSTheodore Ts'o 	if (crng == &primary_crng)
822e192be9dSTheodore Ts'o 		_extract_entropy(&input_pool, &crng->state[4],
823e192be9dSTheodore Ts'o 				 sizeof(__u32) * 12, 0);
824e192be9dSTheodore Ts'o 	else
825eecabf56STheodore Ts'o 		_get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
826e192be9dSTheodore Ts'o 	for (i = 4; i < 16; i++) {
827e192be9dSTheodore Ts'o 		if (!arch_get_random_seed_long(&rv) &&
82839a8883aSTheodore Ts'o 		    !arch_get_random_long(&rv)) {
829e192be9dSTheodore Ts'o 			rv = random_get_entropy();
83039a8883aSTheodore Ts'o 			arch_init = 0;
83139a8883aSTheodore Ts'o 		}
832e192be9dSTheodore Ts'o 		crng->state[i] ^= rv;
833e192be9dSTheodore Ts'o 	}
834fe6f1a6aSJon DeVree 	if (trust_cpu && arch_init && crng == &primary_crng) {
835fe6f1a6aSJon DeVree 		invalidate_batched_entropy();
836fe6f1a6aSJon DeVree 		numa_crng_init();
83739a8883aSTheodore Ts'o 		crng_init = 2;
83812cd53afSYangtao Li 		pr_notice("crng done (trusting CPU's manufacturer)\n");
83939a8883aSTheodore Ts'o 	}
840e192be9dSTheodore Ts'o 	crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
841e192be9dSTheodore Ts'o }
842e192be9dSTheodore Ts'o 
8438ef35c86STheodore Ts'o #ifdef CONFIG_NUMA
8446c1e851cSTheodore Ts'o static void do_numa_crng_init(struct work_struct *work)
8458ef35c86STheodore Ts'o {
8468ef35c86STheodore Ts'o 	int i;
8478ef35c86STheodore Ts'o 	struct crng_state *crng;
8488ef35c86STheodore Ts'o 	struct crng_state **pool;
8498ef35c86STheodore Ts'o 
8508ef35c86STheodore Ts'o 	pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
8518ef35c86STheodore Ts'o 	for_each_online_node(i) {
8528ef35c86STheodore Ts'o 		crng = kmalloc_node(sizeof(struct crng_state),
8538ef35c86STheodore Ts'o 				    GFP_KERNEL | __GFP_NOFAIL, i);
8548ef35c86STheodore Ts'o 		spin_lock_init(&crng->lock);
8558ef35c86STheodore Ts'o 		crng_initialize(crng);
8568ef35c86STheodore Ts'o 		pool[i] = crng;
8578ef35c86STheodore Ts'o 	}
8588ef35c86STheodore Ts'o 	mb();
8598ef35c86STheodore Ts'o 	if (cmpxchg(&crng_node_pool, NULL, pool)) {
8608ef35c86STheodore Ts'o 		for_each_node(i)
8618ef35c86STheodore Ts'o 			kfree(pool[i]);
8628ef35c86STheodore Ts'o 		kfree(pool);
8638ef35c86STheodore Ts'o 	}
8648ef35c86STheodore Ts'o }
8656c1e851cSTheodore Ts'o 
8666c1e851cSTheodore Ts'o static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init);
8676c1e851cSTheodore Ts'o 
8686c1e851cSTheodore Ts'o static void numa_crng_init(void)
8696c1e851cSTheodore Ts'o {
8706c1e851cSTheodore Ts'o 	schedule_work(&numa_crng_init_work);
8716c1e851cSTheodore Ts'o }
8728ef35c86STheodore Ts'o #else
8738ef35c86STheodore Ts'o static void numa_crng_init(void) {}
8748ef35c86STheodore Ts'o #endif
8758ef35c86STheodore Ts'o 
876dc12baacSTheodore Ts'o /*
877dc12baacSTheodore Ts'o  * crng_fast_load() can be called by code in the interrupt service
878dc12baacSTheodore Ts'o  * path.  So we can't afford to dilly-dally.
879dc12baacSTheodore Ts'o  */
880e192be9dSTheodore Ts'o static int crng_fast_load(const char *cp, size_t len)
881e192be9dSTheodore Ts'o {
882e192be9dSTheodore Ts'o 	unsigned long flags;
883e192be9dSTheodore Ts'o 	char *p;
884e192be9dSTheodore Ts'o 
885e192be9dSTheodore Ts'o 	if (!spin_trylock_irqsave(&primary_crng.lock, flags))
886e192be9dSTheodore Ts'o 		return 0;
88743838a23STheodore Ts'o 	if (crng_init != 0) {
888e192be9dSTheodore Ts'o 		spin_unlock_irqrestore(&primary_crng.lock, flags);
889e192be9dSTheodore Ts'o 		return 0;
890e192be9dSTheodore Ts'o 	}
891e192be9dSTheodore Ts'o 	p = (unsigned char *) &primary_crng.state[4];
892e192be9dSTheodore Ts'o 	while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
8931ca1b917SEric Biggers 		p[crng_init_cnt % CHACHA_KEY_SIZE] ^= *cp;
894e192be9dSTheodore Ts'o 		cp++; crng_init_cnt++; len--;
895e192be9dSTheodore Ts'o 	}
8964a072c71SJason A. Donenfeld 	spin_unlock_irqrestore(&primary_crng.lock, flags);
897e192be9dSTheodore Ts'o 	if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
898b169c13dSJason A. Donenfeld 		invalidate_batched_entropy();
899e192be9dSTheodore Ts'o 		crng_init = 1;
90012cd53afSYangtao Li 		pr_notice("fast init done\n");
901e192be9dSTheodore Ts'o 	}
902e192be9dSTheodore Ts'o 	return 1;
903e192be9dSTheodore Ts'o }
904e192be9dSTheodore Ts'o 
905dc12baacSTheodore Ts'o /*
906dc12baacSTheodore Ts'o  * crng_slow_load() is called by add_device_randomness, which has two
907dc12baacSTheodore Ts'o  * attributes.  (1) We can't trust the buffer passed to it is
908dc12baacSTheodore Ts'o  * guaranteed to be unpredictable (so it might not have any entropy at
909dc12baacSTheodore Ts'o  * all), and (2) it doesn't have the performance constraints of
910dc12baacSTheodore Ts'o  * crng_fast_load().
911dc12baacSTheodore Ts'o  *
912dc12baacSTheodore Ts'o  * So we do something more comprehensive which is guaranteed to touch
913dc12baacSTheodore Ts'o  * all of the primary_crng's state, and which uses a LFSR with a
914dc12baacSTheodore Ts'o  * period of 255 as part of the mixing algorithm.  Finally, we do
915dc12baacSTheodore Ts'o  * *not* advance crng_init_cnt since buffer we may get may be something
916dc12baacSTheodore Ts'o  * like a fixed DMI table (for example), which might very well be
917dc12baacSTheodore Ts'o  * unique to the machine, but is otherwise unvarying.
918dc12baacSTheodore Ts'o  */
919dc12baacSTheodore Ts'o static int crng_slow_load(const char *cp, size_t len)
920dc12baacSTheodore Ts'o {
921dc12baacSTheodore Ts'o 	unsigned long		flags;
922dc12baacSTheodore Ts'o 	static unsigned char	lfsr = 1;
923dc12baacSTheodore Ts'o 	unsigned char		tmp;
9241ca1b917SEric Biggers 	unsigned		i, max = CHACHA_KEY_SIZE;
925dc12baacSTheodore Ts'o 	const char *		src_buf = cp;
926dc12baacSTheodore Ts'o 	char *			dest_buf = (char *) &primary_crng.state[4];
927dc12baacSTheodore Ts'o 
928dc12baacSTheodore Ts'o 	if (!spin_trylock_irqsave(&primary_crng.lock, flags))
929dc12baacSTheodore Ts'o 		return 0;
930dc12baacSTheodore Ts'o 	if (crng_init != 0) {
931dc12baacSTheodore Ts'o 		spin_unlock_irqrestore(&primary_crng.lock, flags);
932dc12baacSTheodore Ts'o 		return 0;
933dc12baacSTheodore Ts'o 	}
934dc12baacSTheodore Ts'o 	if (len > max)
935dc12baacSTheodore Ts'o 		max = len;
936dc12baacSTheodore Ts'o 
937dc12baacSTheodore Ts'o 	for (i = 0; i < max ; i++) {
938dc12baacSTheodore Ts'o 		tmp = lfsr;
939dc12baacSTheodore Ts'o 		lfsr >>= 1;
940dc12baacSTheodore Ts'o 		if (tmp & 1)
941dc12baacSTheodore Ts'o 			lfsr ^= 0xE1;
9421ca1b917SEric Biggers 		tmp = dest_buf[i % CHACHA_KEY_SIZE];
9431ca1b917SEric Biggers 		dest_buf[i % CHACHA_KEY_SIZE] ^= src_buf[i % len] ^ lfsr;
944dc12baacSTheodore Ts'o 		lfsr += (tmp << 3) | (tmp >> 5);
945dc12baacSTheodore Ts'o 	}
946dc12baacSTheodore Ts'o 	spin_unlock_irqrestore(&primary_crng.lock, flags);
947dc12baacSTheodore Ts'o 	return 1;
948dc12baacSTheodore Ts'o }
949dc12baacSTheodore Ts'o 
950e192be9dSTheodore Ts'o static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
951e192be9dSTheodore Ts'o {
952e192be9dSTheodore Ts'o 	unsigned long	flags;
953e192be9dSTheodore Ts'o 	int		i, num;
954e192be9dSTheodore Ts'o 	union {
9551ca1b917SEric Biggers 		__u8	block[CHACHA_BLOCK_SIZE];
956e192be9dSTheodore Ts'o 		__u32	key[8];
957e192be9dSTheodore Ts'o 	} buf;
958e192be9dSTheodore Ts'o 
959e192be9dSTheodore Ts'o 	if (r) {
960e192be9dSTheodore Ts'o 		num = extract_entropy(r, &buf, 32, 16, 0);
961e192be9dSTheodore Ts'o 		if (num == 0)
962e192be9dSTheodore Ts'o 			return;
963c92e040dSTheodore Ts'o 	} else {
9641e7f583aSTheodore Ts'o 		_extract_crng(&primary_crng, buf.block);
965c92e040dSTheodore Ts'o 		_crng_backtrack_protect(&primary_crng, buf.block,
9661ca1b917SEric Biggers 					CHACHA_KEY_SIZE);
967c92e040dSTheodore Ts'o 	}
9680bb29a84STheodore Ts'o 	spin_lock_irqsave(&crng->lock, flags);
969e192be9dSTheodore Ts'o 	for (i = 0; i < 8; i++) {
970e192be9dSTheodore Ts'o 		unsigned long	rv;
971e192be9dSTheodore Ts'o 		if (!arch_get_random_seed_long(&rv) &&
972e192be9dSTheodore Ts'o 		    !arch_get_random_long(&rv))
973e192be9dSTheodore Ts'o 			rv = random_get_entropy();
974e192be9dSTheodore Ts'o 		crng->state[i+4] ^= buf.key[i] ^ rv;
975e192be9dSTheodore Ts'o 	}
976e192be9dSTheodore Ts'o 	memzero_explicit(&buf, sizeof(buf));
977e192be9dSTheodore Ts'o 	crng->init_time = jiffies;
9780bb29a84STheodore Ts'o 	spin_unlock_irqrestore(&crng->lock, flags);
979e192be9dSTheodore Ts'o 	if (crng == &primary_crng && crng_init < 2) {
980b169c13dSJason A. Donenfeld 		invalidate_batched_entropy();
9818ef35c86STheodore Ts'o 		numa_crng_init();
982e192be9dSTheodore Ts'o 		crng_init = 2;
983e192be9dSTheodore Ts'o 		process_random_ready_list();
984e192be9dSTheodore Ts'o 		wake_up_interruptible(&crng_init_wait);
98530c08efeSAndy Lutomirski 		kill_fasync(&fasync, SIGIO, POLL_IN);
98612cd53afSYangtao Li 		pr_notice("crng init done\n");
9874e00b339STheodore Ts'o 		if (unseeded_warning.missed) {
98812cd53afSYangtao Li 			pr_notice("%d get_random_xx warning(s) missed due to ratelimiting\n",
9894e00b339STheodore Ts'o 				  unseeded_warning.missed);
9904e00b339STheodore Ts'o 			unseeded_warning.missed = 0;
9914e00b339STheodore Ts'o 		}
9924e00b339STheodore Ts'o 		if (urandom_warning.missed) {
99312cd53afSYangtao Li 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
9944e00b339STheodore Ts'o 				  urandom_warning.missed);
9954e00b339STheodore Ts'o 			urandom_warning.missed = 0;
9964e00b339STheodore Ts'o 		}
997e192be9dSTheodore Ts'o 	}
998e192be9dSTheodore Ts'o }
999e192be9dSTheodore Ts'o 
10001e7f583aSTheodore Ts'o static void _extract_crng(struct crng_state *crng,
10011ca1b917SEric Biggers 			  __u8 out[CHACHA_BLOCK_SIZE])
1002e192be9dSTheodore Ts'o {
1003e192be9dSTheodore Ts'o 	unsigned long v, flags;
1004e192be9dSTheodore Ts'o 
100543838a23STheodore Ts'o 	if (crng_ready() &&
1006d848e5f8STheodore Ts'o 	    (time_after(crng_global_init_time, crng->init_time) ||
1007d848e5f8STheodore Ts'o 	     time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL)))
10081e7f583aSTheodore Ts'o 		crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
1009e192be9dSTheodore Ts'o 	spin_lock_irqsave(&crng->lock, flags);
1010e192be9dSTheodore Ts'o 	if (arch_get_random_long(&v))
1011e192be9dSTheodore Ts'o 		crng->state[14] ^= v;
1012e192be9dSTheodore Ts'o 	chacha20_block(&crng->state[0], out);
1013e192be9dSTheodore Ts'o 	if (crng->state[12] == 0)
1014e192be9dSTheodore Ts'o 		crng->state[13]++;
1015e192be9dSTheodore Ts'o 	spin_unlock_irqrestore(&crng->lock, flags);
1016e192be9dSTheodore Ts'o }
1017e192be9dSTheodore Ts'o 
10181ca1b917SEric Biggers static void extract_crng(__u8 out[CHACHA_BLOCK_SIZE])
10191e7f583aSTheodore Ts'o {
10201e7f583aSTheodore Ts'o 	struct crng_state *crng = NULL;
10211e7f583aSTheodore Ts'o 
10221e7f583aSTheodore Ts'o #ifdef CONFIG_NUMA
10231e7f583aSTheodore Ts'o 	if (crng_node_pool)
10241e7f583aSTheodore Ts'o 		crng = crng_node_pool[numa_node_id()];
10251e7f583aSTheodore Ts'o 	if (crng == NULL)
10261e7f583aSTheodore Ts'o #endif
10271e7f583aSTheodore Ts'o 		crng = &primary_crng;
10281e7f583aSTheodore Ts'o 	_extract_crng(crng, out);
10291e7f583aSTheodore Ts'o }
10301e7f583aSTheodore Ts'o 
1031c92e040dSTheodore Ts'o /*
1032c92e040dSTheodore Ts'o  * Use the leftover bytes from the CRNG block output (if there is
1033c92e040dSTheodore Ts'o  * enough) to mutate the CRNG key to provide backtracking protection.
1034c92e040dSTheodore Ts'o  */
1035c92e040dSTheodore Ts'o static void _crng_backtrack_protect(struct crng_state *crng,
10361ca1b917SEric Biggers 				    __u8 tmp[CHACHA_BLOCK_SIZE], int used)
1037c92e040dSTheodore Ts'o {
1038c92e040dSTheodore Ts'o 	unsigned long	flags;
1039c92e040dSTheodore Ts'o 	__u32		*s, *d;
1040c92e040dSTheodore Ts'o 	int		i;
1041c92e040dSTheodore Ts'o 
1042c92e040dSTheodore Ts'o 	used = round_up(used, sizeof(__u32));
10431ca1b917SEric Biggers 	if (used + CHACHA_KEY_SIZE > CHACHA_BLOCK_SIZE) {
1044c92e040dSTheodore Ts'o 		extract_crng(tmp);
1045c92e040dSTheodore Ts'o 		used = 0;
1046c92e040dSTheodore Ts'o 	}
1047c92e040dSTheodore Ts'o 	spin_lock_irqsave(&crng->lock, flags);
1048a5e9f557SEric Biggers 	s = (__u32 *) &tmp[used];
1049c92e040dSTheodore Ts'o 	d = &crng->state[4];
1050c92e040dSTheodore Ts'o 	for (i=0; i < 8; i++)
1051c92e040dSTheodore Ts'o 		*d++ ^= *s++;
1052c92e040dSTheodore Ts'o 	spin_unlock_irqrestore(&crng->lock, flags);
1053c92e040dSTheodore Ts'o }
1054c92e040dSTheodore Ts'o 
10551ca1b917SEric Biggers static void crng_backtrack_protect(__u8 tmp[CHACHA_BLOCK_SIZE], int used)
1056c92e040dSTheodore Ts'o {
1057c92e040dSTheodore Ts'o 	struct crng_state *crng = NULL;
1058c92e040dSTheodore Ts'o 
1059c92e040dSTheodore Ts'o #ifdef CONFIG_NUMA
1060c92e040dSTheodore Ts'o 	if (crng_node_pool)
1061c92e040dSTheodore Ts'o 		crng = crng_node_pool[numa_node_id()];
1062c92e040dSTheodore Ts'o 	if (crng == NULL)
1063c92e040dSTheodore Ts'o #endif
1064c92e040dSTheodore Ts'o 		crng = &primary_crng;
1065c92e040dSTheodore Ts'o 	_crng_backtrack_protect(crng, tmp, used);
1066c92e040dSTheodore Ts'o }
1067c92e040dSTheodore Ts'o 
1068e192be9dSTheodore Ts'o static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
1069e192be9dSTheodore Ts'o {
10701ca1b917SEric Biggers 	ssize_t ret = 0, i = CHACHA_BLOCK_SIZE;
10711ca1b917SEric Biggers 	__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
1072e192be9dSTheodore Ts'o 	int large_request = (nbytes > 256);
1073e192be9dSTheodore Ts'o 
1074e192be9dSTheodore Ts'o 	while (nbytes) {
1075e192be9dSTheodore Ts'o 		if (large_request && need_resched()) {
1076e192be9dSTheodore Ts'o 			if (signal_pending(current)) {
1077e192be9dSTheodore Ts'o 				if (ret == 0)
1078e192be9dSTheodore Ts'o 					ret = -ERESTARTSYS;
1079e192be9dSTheodore Ts'o 				break;
1080e192be9dSTheodore Ts'o 			}
1081e192be9dSTheodore Ts'o 			schedule();
1082e192be9dSTheodore Ts'o 		}
1083e192be9dSTheodore Ts'o 
1084e192be9dSTheodore Ts'o 		extract_crng(tmp);
10851ca1b917SEric Biggers 		i = min_t(int, nbytes, CHACHA_BLOCK_SIZE);
1086e192be9dSTheodore Ts'o 		if (copy_to_user(buf, tmp, i)) {
1087e192be9dSTheodore Ts'o 			ret = -EFAULT;
1088e192be9dSTheodore Ts'o 			break;
1089e192be9dSTheodore Ts'o 		}
1090e192be9dSTheodore Ts'o 
1091e192be9dSTheodore Ts'o 		nbytes -= i;
1092e192be9dSTheodore Ts'o 		buf += i;
1093e192be9dSTheodore Ts'o 		ret += i;
1094e192be9dSTheodore Ts'o 	}
1095c92e040dSTheodore Ts'o 	crng_backtrack_protect(tmp, i);
1096e192be9dSTheodore Ts'o 
1097e192be9dSTheodore Ts'o 	/* Wipe data just written to memory */
1098e192be9dSTheodore Ts'o 	memzero_explicit(tmp, sizeof(tmp));
1099e192be9dSTheodore Ts'o 
1100e192be9dSTheodore Ts'o 	return ret;
1101e192be9dSTheodore Ts'o }
1102e192be9dSTheodore Ts'o 
1103e192be9dSTheodore Ts'o 
1104e192be9dSTheodore Ts'o /*********************************************************************
1105e192be9dSTheodore Ts'o  *
11061da177e4SLinus Torvalds  * Entropy input management
11071da177e4SLinus Torvalds  *
11081da177e4SLinus Torvalds  *********************************************************************/
11091da177e4SLinus Torvalds 
11101da177e4SLinus Torvalds /* There is one of these per entropy source */
11111da177e4SLinus Torvalds struct timer_rand_state {
11121da177e4SLinus Torvalds 	cycles_t last_time;
11131da177e4SLinus Torvalds 	long last_delta, last_delta2;
11141da177e4SLinus Torvalds };
11151da177e4SLinus Torvalds 
1116644008dfSTheodore Ts'o #define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
1117644008dfSTheodore Ts'o 
1118a2080a67SLinus Torvalds /*
1119e192be9dSTheodore Ts'o  * Add device- or boot-specific data to the input pool to help
1120e192be9dSTheodore Ts'o  * initialize it.
1121a2080a67SLinus Torvalds  *
1122e192be9dSTheodore Ts'o  * None of this adds any entropy; it is meant to avoid the problem of
1123e192be9dSTheodore Ts'o  * the entropy pool having similar initial state across largely
1124e192be9dSTheodore Ts'o  * identical devices.
1125a2080a67SLinus Torvalds  */
1126a2080a67SLinus Torvalds void add_device_randomness(const void *buf, unsigned int size)
1127a2080a67SLinus Torvalds {
112861875f30STheodore Ts'o 	unsigned long time = random_get_entropy() ^ jiffies;
11293ef4cb2dSTheodore Ts'o 	unsigned long flags;
1130a2080a67SLinus Torvalds 
1131dc12baacSTheodore Ts'o 	if (!crng_ready() && size)
1132dc12baacSTheodore Ts'o 		crng_slow_load(buf, size);
1133ee7998c5SKees Cook 
11345910895fSTheodore Ts'o 	trace_add_device_randomness(size, _RET_IP_);
11353ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
113685608f8eSTheodore Ts'o 	_mix_pool_bytes(&input_pool, buf, size);
113785608f8eSTheodore Ts'o 	_mix_pool_bytes(&input_pool, &time, sizeof(time));
11383ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
1139a2080a67SLinus Torvalds }
1140a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
1141a2080a67SLinus Torvalds 
1142644008dfSTheodore Ts'o static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
11433060d6feSYinghai Lu 
11441da177e4SLinus Torvalds /*
11451da177e4SLinus Torvalds  * This function adds entropy to the entropy "pool" by using timing
11461da177e4SLinus Torvalds  * delays.  It uses the timer_rand_state structure to make an estimate
11471da177e4SLinus Torvalds  * of how many bits of entropy this call has added to the pool.
11481da177e4SLinus Torvalds  *
11491da177e4SLinus Torvalds  * The number "num" is also added to the pool - it should somehow describe
11501da177e4SLinus Torvalds  * the type of event which just happened.  This is currently 0-255 for
11511da177e4SLinus Torvalds  * keyboard scan codes, and 256 upwards for interrupts.
11521da177e4SLinus Torvalds  *
11531da177e4SLinus Torvalds  */
11541da177e4SLinus Torvalds static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
11551da177e4SLinus Torvalds {
115640db23e5STheodore Ts'o 	struct entropy_store	*r;
11571da177e4SLinus Torvalds 	struct {
11581da177e4SLinus Torvalds 		long jiffies;
1159cf833d0bSLinus Torvalds 		unsigned cycles;
11601da177e4SLinus Torvalds 		unsigned num;
11611da177e4SLinus Torvalds 	} sample;
11621da177e4SLinus Torvalds 	long delta, delta2, delta3;
11631da177e4SLinus Torvalds 
11641da177e4SLinus Torvalds 	sample.jiffies = jiffies;
116561875f30STheodore Ts'o 	sample.cycles = random_get_entropy();
11661da177e4SLinus Torvalds 	sample.num = num;
1167e192be9dSTheodore Ts'o 	r = &input_pool;
116885608f8eSTheodore Ts'o 	mix_pool_bytes(r, &sample, sizeof(sample));
11691da177e4SLinus Torvalds 
11701da177e4SLinus Torvalds 	/*
11711da177e4SLinus Torvalds 	 * Calculate number of bits of randomness we probably added.
11721da177e4SLinus Torvalds 	 * We take into account the first, second and third-order deltas
11731da177e4SLinus Torvalds 	 * in order to make our estimate.
11741da177e4SLinus Torvalds 	 */
11751da177e4SLinus Torvalds 	delta = sample.jiffies - state->last_time;
11761da177e4SLinus Torvalds 	state->last_time = sample.jiffies;
11771da177e4SLinus Torvalds 
11781da177e4SLinus Torvalds 	delta2 = delta - state->last_delta;
11791da177e4SLinus Torvalds 	state->last_delta = delta;
11801da177e4SLinus Torvalds 
11811da177e4SLinus Torvalds 	delta3 = delta2 - state->last_delta2;
11821da177e4SLinus Torvalds 	state->last_delta2 = delta2;
11831da177e4SLinus Torvalds 
11841da177e4SLinus Torvalds 	if (delta < 0)
11851da177e4SLinus Torvalds 		delta = -delta;
11861da177e4SLinus Torvalds 	if (delta2 < 0)
11871da177e4SLinus Torvalds 		delta2 = -delta2;
11881da177e4SLinus Torvalds 	if (delta3 < 0)
11891da177e4SLinus Torvalds 		delta3 = -delta3;
11901da177e4SLinus Torvalds 	if (delta > delta2)
11911da177e4SLinus Torvalds 		delta = delta2;
11921da177e4SLinus Torvalds 	if (delta > delta3)
11931da177e4SLinus Torvalds 		delta = delta3;
11941da177e4SLinus Torvalds 
11951da177e4SLinus Torvalds 	/*
11961da177e4SLinus Torvalds 	 * delta is now minimum absolute delta.
11971da177e4SLinus Torvalds 	 * Round down by 1 bit on general principles,
1198*727d499aSYangtao Li 	 * and limit entropy estimate to 12 bits.
11991da177e4SLinus Torvalds 	 */
120040db23e5STheodore Ts'o 	credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
12011da177e4SLinus Torvalds }
12021da177e4SLinus Torvalds 
1203d251575aSStephen Hemminger void add_input_randomness(unsigned int type, unsigned int code,
12041da177e4SLinus Torvalds 				 unsigned int value)
12051da177e4SLinus Torvalds {
12061da177e4SLinus Torvalds 	static unsigned char last_value;
12071da177e4SLinus Torvalds 
12081da177e4SLinus Torvalds 	/* ignore autorepeat and the like */
12091da177e4SLinus Torvalds 	if (value == last_value)
12101da177e4SLinus Torvalds 		return;
12111da177e4SLinus Torvalds 
12121da177e4SLinus Torvalds 	last_value = value;
12131da177e4SLinus Torvalds 	add_timer_randomness(&input_timer_state,
12141da177e4SLinus Torvalds 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1215f80bbd8bSTheodore Ts'o 	trace_add_input_randomness(ENTROPY_BITS(&input_pool));
12161da177e4SLinus Torvalds }
121780fc9f53SDmitry Torokhov EXPORT_SYMBOL_GPL(add_input_randomness);
12181da177e4SLinus Torvalds 
1219775f4b29STheodore Ts'o static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
1220775f4b29STheodore Ts'o 
122143759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
122243759d4fSTheodore Ts'o static unsigned long avg_cycles, avg_deviation;
122343759d4fSTheodore Ts'o 
122443759d4fSTheodore Ts'o #define AVG_SHIFT 8     /* Exponential average factor k=1/256 */
122543759d4fSTheodore Ts'o #define FIXED_1_2 (1 << (AVG_SHIFT-1))
122643759d4fSTheodore Ts'o 
122743759d4fSTheodore Ts'o static void add_interrupt_bench(cycles_t start)
122843759d4fSTheodore Ts'o {
122943759d4fSTheodore Ts'o         long delta = random_get_entropy() - start;
123043759d4fSTheodore Ts'o 
123143759d4fSTheodore Ts'o         /* Use a weighted moving average */
123243759d4fSTheodore Ts'o         delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
123343759d4fSTheodore Ts'o         avg_cycles += delta;
123443759d4fSTheodore Ts'o         /* And average deviation */
123543759d4fSTheodore Ts'o         delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
123643759d4fSTheodore Ts'o         avg_deviation += delta;
123743759d4fSTheodore Ts'o }
123843759d4fSTheodore Ts'o #else
123943759d4fSTheodore Ts'o #define add_interrupt_bench(x)
124043759d4fSTheodore Ts'o #endif
124143759d4fSTheodore Ts'o 
1242ee3e00e9STheodore Ts'o static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
1243ee3e00e9STheodore Ts'o {
1244ee3e00e9STheodore Ts'o 	__u32 *ptr = (__u32 *) regs;
124592e75428STheodore Ts'o 	unsigned int idx;
1246ee3e00e9STheodore Ts'o 
1247ee3e00e9STheodore Ts'o 	if (regs == NULL)
1248ee3e00e9STheodore Ts'o 		return 0;
124992e75428STheodore Ts'o 	idx = READ_ONCE(f->reg_idx);
125092e75428STheodore Ts'o 	if (idx >= sizeof(struct pt_regs) / sizeof(__u32))
125192e75428STheodore Ts'o 		idx = 0;
125292e75428STheodore Ts'o 	ptr += idx++;
125392e75428STheodore Ts'o 	WRITE_ONCE(f->reg_idx, idx);
12549dfa7bbaSMichael Schmitz 	return *ptr;
1255ee3e00e9STheodore Ts'o }
1256ee3e00e9STheodore Ts'o 
1257775f4b29STheodore Ts'o void add_interrupt_randomness(int irq, int irq_flags)
12581da177e4SLinus Torvalds {
1259775f4b29STheodore Ts'o 	struct entropy_store	*r;
12601b2a1a7eSChristoph Lameter 	struct fast_pool	*fast_pool = this_cpu_ptr(&irq_randomness);
1261775f4b29STheodore Ts'o 	struct pt_regs		*regs = get_irq_regs();
1262775f4b29STheodore Ts'o 	unsigned long		now = jiffies;
1263655b2264STheodore Ts'o 	cycles_t		cycles = random_get_entropy();
126443759d4fSTheodore Ts'o 	__u32			c_high, j_high;
1265655b2264STheodore Ts'o 	__u64			ip;
126683664a69SH. Peter Anvin 	unsigned long		seed;
126791fcb532STheodore Ts'o 	int			credit = 0;
12683060d6feSYinghai Lu 
1269ee3e00e9STheodore Ts'o 	if (cycles == 0)
1270ee3e00e9STheodore Ts'o 		cycles = get_reg(fast_pool, regs);
1271655b2264STheodore Ts'o 	c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
1272655b2264STheodore Ts'o 	j_high = (sizeof(now) > 4) ? now >> 32 : 0;
127343759d4fSTheodore Ts'o 	fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
127443759d4fSTheodore Ts'o 	fast_pool->pool[1] ^= now ^ c_high;
1275655b2264STheodore Ts'o 	ip = regs ? instruction_pointer(regs) : _RET_IP_;
127643759d4fSTheodore Ts'o 	fast_pool->pool[2] ^= ip;
1277ee3e00e9STheodore Ts'o 	fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
1278ee3e00e9STheodore Ts'o 		get_reg(fast_pool, regs);
12793060d6feSYinghai Lu 
128043759d4fSTheodore Ts'o 	fast_mix(fast_pool);
128143759d4fSTheodore Ts'o 	add_interrupt_bench(cycles);
1282775f4b29STheodore Ts'o 
128343838a23STheodore Ts'o 	if (unlikely(crng_init == 0)) {
1284e192be9dSTheodore Ts'o 		if ((fast_pool->count >= 64) &&
1285e192be9dSTheodore Ts'o 		    crng_fast_load((char *) fast_pool->pool,
1286e192be9dSTheodore Ts'o 				   sizeof(fast_pool->pool))) {
1287e192be9dSTheodore Ts'o 			fast_pool->count = 0;
1288e192be9dSTheodore Ts'o 			fast_pool->last = now;
1289e192be9dSTheodore Ts'o 		}
1290e192be9dSTheodore Ts'o 		return;
1291e192be9dSTheodore Ts'o 	}
1292e192be9dSTheodore Ts'o 
1293840f9507STheodore Ts'o 	if ((fast_pool->count < 64) &&
1294840f9507STheodore Ts'o 	    !time_after(now, fast_pool->last + HZ))
12951da177e4SLinus Torvalds 		return;
1296840f9507STheodore Ts'o 
1297e192be9dSTheodore Ts'o 	r = &input_pool;
1298840f9507STheodore Ts'o 	if (!spin_trylock(&r->lock))
12991da177e4SLinus Torvalds 		return;
13001da177e4SLinus Torvalds 
1301775f4b29STheodore Ts'o 	fast_pool->last = now;
130285608f8eSTheodore Ts'o 	__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
130383664a69SH. Peter Anvin 
130483664a69SH. Peter Anvin 	/*
130583664a69SH. Peter Anvin 	 * If we have architectural seed generator, produce a seed and
130648d6be95STheodore Ts'o 	 * add it to the pool.  For the sake of paranoia don't let the
130748d6be95STheodore Ts'o 	 * architectural seed generator dominate the input from the
130848d6be95STheodore Ts'o 	 * interrupt noise.
130983664a69SH. Peter Anvin 	 */
131083664a69SH. Peter Anvin 	if (arch_get_random_seed_long(&seed)) {
131185608f8eSTheodore Ts'o 		__mix_pool_bytes(r, &seed, sizeof(seed));
131248d6be95STheodore Ts'o 		credit = 1;
131383664a69SH. Peter Anvin 	}
131491fcb532STheodore Ts'o 	spin_unlock(&r->lock);
131583664a69SH. Peter Anvin 
1316ee3e00e9STheodore Ts'o 	fast_pool->count = 0;
1317840f9507STheodore Ts'o 
1318ee3e00e9STheodore Ts'o 	/* award one bit for the contents of the fast pool */
1319ee3e00e9STheodore Ts'o 	credit_entropy_bits(r, credit + 1);
13201da177e4SLinus Torvalds }
13214b44f2d1SStephan Mueller EXPORT_SYMBOL_GPL(add_interrupt_randomness);
13221da177e4SLinus Torvalds 
13239361401eSDavid Howells #ifdef CONFIG_BLOCK
13241da177e4SLinus Torvalds void add_disk_randomness(struct gendisk *disk)
13251da177e4SLinus Torvalds {
13261da177e4SLinus Torvalds 	if (!disk || !disk->random)
13271da177e4SLinus Torvalds 		return;
13281da177e4SLinus Torvalds 	/* first major is 1, so we get >= 0x200 here */
1329f331c029STejun Heo 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1330f80bbd8bSTheodore Ts'o 	trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
13311da177e4SLinus Torvalds }
1332bdcfa3e5SChristoph Hellwig EXPORT_SYMBOL_GPL(add_disk_randomness);
13339361401eSDavid Howells #endif
13341da177e4SLinus Torvalds 
13351da177e4SLinus Torvalds /*********************************************************************
13361da177e4SLinus Torvalds  *
13371da177e4SLinus Torvalds  * Entropy extraction routines
13381da177e4SLinus Torvalds  *
13391da177e4SLinus Torvalds  *********************************************************************/
13401da177e4SLinus Torvalds 
13411da177e4SLinus Torvalds /*
134219fa5be1SGreg Price  * This function decides how many bytes to actually take from the
134319fa5be1SGreg Price  * given pool, and also debits the entropy count accordingly.
13441da177e4SLinus Torvalds  */
13451da177e4SLinus Torvalds static size_t account(struct entropy_store *r, size_t nbytes, int min,
13461da177e4SLinus Torvalds 		      int reserved)
13471da177e4SLinus Torvalds {
134843d8a72cSStephan Müller 	int entropy_count, orig, have_bytes;
134979a84687SHannes Frederic Sowa 	size_t ibytes, nfrac;
13501da177e4SLinus Torvalds 
1351a283b5c4SH. Peter Anvin 	BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
13521da177e4SLinus Torvalds 
13531da177e4SLinus Torvalds 	/* Can we pull enough? */
135410b3a32dSJiri Kosina retry:
13556aa7de05SMark Rutland 	entropy_count = orig = READ_ONCE(r->entropy_count);
1356a283b5c4SH. Peter Anvin 	ibytes = nbytes;
135743d8a72cSStephan Müller 	/* never pull more than available */
135843d8a72cSStephan Müller 	have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
1359e33ba5faSTheodore Ts'o 
1360e33ba5faSTheodore Ts'o 	if ((have_bytes -= reserved) < 0)
1361e33ba5faSTheodore Ts'o 		have_bytes = 0;
1362e33ba5faSTheodore Ts'o 	ibytes = min_t(size_t, ibytes, have_bytes);
13630fb7a01aSGreg Price 	if (ibytes < min)
13640fb7a01aSGreg Price 		ibytes = 0;
136579a84687SHannes Frederic Sowa 
1366870e05b1SYangtao Li 	if (WARN_ON(entropy_count < 0)) {
136712cd53afSYangtao Li 		pr_warn("negative entropy count: pool %s count %d\n",
136879a84687SHannes Frederic Sowa 			r->name, entropy_count);
136979a84687SHannes Frederic Sowa 		entropy_count = 0;
137079a84687SHannes Frederic Sowa 	}
137179a84687SHannes Frederic Sowa 	nfrac = ibytes << (ENTROPY_SHIFT + 3);
137279a84687SHannes Frederic Sowa 	if ((size_t) entropy_count > nfrac)
137379a84687SHannes Frederic Sowa 		entropy_count -= nfrac;
137479a84687SHannes Frederic Sowa 	else
1375e33ba5faSTheodore Ts'o 		entropy_count = 0;
1376f9c6d498STheodore Ts'o 
137710b3a32dSJiri Kosina 	if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
137810b3a32dSJiri Kosina 		goto retry;
13791da177e4SLinus Torvalds 
1380f80bbd8bSTheodore Ts'o 	trace_debit_entropy(r->name, 8 * ibytes);
138112faac30SYangtao Li 	if (ibytes && ENTROPY_BITS(r) < random_write_wakeup_bits) {
1382a11e1d43SLinus Torvalds 		wake_up_interruptible(&random_write_wait);
1383b9809552STheodore Ts'o 		kill_fasync(&fasync, SIGIO, POLL_OUT);
1384b9809552STheodore Ts'o 	}
1385b9809552STheodore Ts'o 
1386a283b5c4SH. Peter Anvin 	return ibytes;
13871da177e4SLinus Torvalds }
13881da177e4SLinus Torvalds 
138919fa5be1SGreg Price /*
139019fa5be1SGreg Price  * This function does the actual extraction for extract_entropy and
139119fa5be1SGreg Price  * extract_entropy_user.
139219fa5be1SGreg Price  *
139319fa5be1SGreg Price  * Note: we assume that .poolwords is a multiple of 16 words.
139419fa5be1SGreg Price  */
13951da177e4SLinus Torvalds static void extract_buf(struct entropy_store *r, __u8 *out)
13961da177e4SLinus Torvalds {
1397602b6aeeSMatt Mackall 	int i;
1398d2e7c96aSH. Peter Anvin 	union {
1399d2e7c96aSH. Peter Anvin 		__u32 w[5];
140085a1f777STheodore Ts'o 		unsigned long l[LONGS(20)];
1401d2e7c96aSH. Peter Anvin 	} hash;
1402d2e7c96aSH. Peter Anvin 	__u32 workspace[SHA_WORKSPACE_WORDS];
1403902c098aSTheodore Ts'o 	unsigned long flags;
14041da177e4SLinus Torvalds 
14051da177e4SLinus Torvalds 	/*
1406dfd38750SGreg Price 	 * If we have an architectural hardware random number
140746884442STheodore Ts'o 	 * generator, use it for SHA's initial vector
140885a1f777STheodore Ts'o 	 */
140946884442STheodore Ts'o 	sha_init(hash.w);
141085a1f777STheodore Ts'o 	for (i = 0; i < LONGS(20); i++) {
141185a1f777STheodore Ts'o 		unsigned long v;
141285a1f777STheodore Ts'o 		if (!arch_get_random_long(&v))
141385a1f777STheodore Ts'o 			break;
141446884442STheodore Ts'o 		hash.l[i] = v;
141585a1f777STheodore Ts'o 	}
141685a1f777STheodore Ts'o 
141746884442STheodore Ts'o 	/* Generate a hash across the pool, 16 words (512 bits) at a time */
141846884442STheodore Ts'o 	spin_lock_irqsave(&r->lock, flags);
141946884442STheodore Ts'o 	for (i = 0; i < r->poolinfo->poolwords; i += 16)
142046884442STheodore Ts'o 		sha_transform(hash.w, (__u8 *)(r->pool + i), workspace);
142146884442STheodore Ts'o 
142285a1f777STheodore Ts'o 	/*
14231c0ad3d4SMatt Mackall 	 * We mix the hash back into the pool to prevent backtracking
14241c0ad3d4SMatt Mackall 	 * attacks (where the attacker knows the state of the pool
14251c0ad3d4SMatt Mackall 	 * plus the current outputs, and attempts to find previous
14261c0ad3d4SMatt Mackall 	 * ouputs), unless the hash function can be inverted. By
14271c0ad3d4SMatt Mackall 	 * mixing at least a SHA1 worth of hash data back, we make
14281c0ad3d4SMatt Mackall 	 * brute-forcing the feedback as hard as brute-forcing the
14291c0ad3d4SMatt Mackall 	 * hash.
14301da177e4SLinus Torvalds 	 */
143185608f8eSTheodore Ts'o 	__mix_pool_bytes(r, hash.w, sizeof(hash.w));
1432902c098aSTheodore Ts'o 	spin_unlock_irqrestore(&r->lock, flags);
14331c0ad3d4SMatt Mackall 
1434d4c5efdbSDaniel Borkmann 	memzero_explicit(workspace, sizeof(workspace));
14351da177e4SLinus Torvalds 
14361da177e4SLinus Torvalds 	/*
14371c0ad3d4SMatt Mackall 	 * In case the hash function has some recognizable output
14381c0ad3d4SMatt Mackall 	 * pattern, we fold it in half. Thus, we always feed back
14391c0ad3d4SMatt Mackall 	 * twice as much data as we output.
14401da177e4SLinus Torvalds 	 */
1441d2e7c96aSH. Peter Anvin 	hash.w[0] ^= hash.w[3];
1442d2e7c96aSH. Peter Anvin 	hash.w[1] ^= hash.w[4];
1443d2e7c96aSH. Peter Anvin 	hash.w[2] ^= rol32(hash.w[2], 16);
1444d2e7c96aSH. Peter Anvin 
1445d2e7c96aSH. Peter Anvin 	memcpy(out, &hash, EXTRACT_SIZE);
1446d4c5efdbSDaniel Borkmann 	memzero_explicit(&hash, sizeof(hash));
14471da177e4SLinus Torvalds }
14481da177e4SLinus Torvalds 
1449e192be9dSTheodore Ts'o static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
1450e192be9dSTheodore Ts'o 				size_t nbytes, int fips)
1451e192be9dSTheodore Ts'o {
1452e192be9dSTheodore Ts'o 	ssize_t ret = 0, i;
1453e192be9dSTheodore Ts'o 	__u8 tmp[EXTRACT_SIZE];
1454e192be9dSTheodore Ts'o 	unsigned long flags;
1455e192be9dSTheodore Ts'o 
1456e192be9dSTheodore Ts'o 	while (nbytes) {
1457e192be9dSTheodore Ts'o 		extract_buf(r, tmp);
1458e192be9dSTheodore Ts'o 
1459e192be9dSTheodore Ts'o 		if (fips) {
1460e192be9dSTheodore Ts'o 			spin_lock_irqsave(&r->lock, flags);
1461e192be9dSTheodore Ts'o 			if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
1462e192be9dSTheodore Ts'o 				panic("Hardware RNG duplicated output!\n");
1463e192be9dSTheodore Ts'o 			memcpy(r->last_data, tmp, EXTRACT_SIZE);
1464e192be9dSTheodore Ts'o 			spin_unlock_irqrestore(&r->lock, flags);
1465e192be9dSTheodore Ts'o 		}
1466e192be9dSTheodore Ts'o 		i = min_t(int, nbytes, EXTRACT_SIZE);
1467e192be9dSTheodore Ts'o 		memcpy(buf, tmp, i);
1468e192be9dSTheodore Ts'o 		nbytes -= i;
1469e192be9dSTheodore Ts'o 		buf += i;
1470e192be9dSTheodore Ts'o 		ret += i;
1471e192be9dSTheodore Ts'o 	}
1472e192be9dSTheodore Ts'o 
1473e192be9dSTheodore Ts'o 	/* Wipe data just returned from memory */
1474e192be9dSTheodore Ts'o 	memzero_explicit(tmp, sizeof(tmp));
1475e192be9dSTheodore Ts'o 
1476e192be9dSTheodore Ts'o 	return ret;
1477e192be9dSTheodore Ts'o }
1478e192be9dSTheodore Ts'o 
147919fa5be1SGreg Price /*
148019fa5be1SGreg Price  * This function extracts randomness from the "entropy pool", and
148119fa5be1SGreg Price  * returns it in a buffer.
148219fa5be1SGreg Price  *
148319fa5be1SGreg Price  * The min parameter specifies the minimum amount we can pull before
148419fa5be1SGreg Price  * failing to avoid races that defeat catastrophic reseeding while the
148519fa5be1SGreg Price  * reserved parameter indicates how much entropy we must leave in the
148619fa5be1SGreg Price  * pool after each pull to avoid starving other readers.
148719fa5be1SGreg Price  */
14881da177e4SLinus Torvalds static ssize_t extract_entropy(struct entropy_store *r, void *buf,
14891da177e4SLinus Torvalds 				 size_t nbytes, int min, int reserved)
14901da177e4SLinus Torvalds {
14911da177e4SLinus Torvalds 	__u8 tmp[EXTRACT_SIZE];
14921e7e2e05SJarod Wilson 	unsigned long flags;
14931da177e4SLinus Torvalds 
1494ec8f02daSJarod Wilson 	/* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
14951e7e2e05SJarod Wilson 	if (fips_enabled) {
14961e7e2e05SJarod Wilson 		spin_lock_irqsave(&r->lock, flags);
14971e7e2e05SJarod Wilson 		if (!r->last_data_init) {
1498c59974aeSTheodore Ts'o 			r->last_data_init = 1;
14991e7e2e05SJarod Wilson 			spin_unlock_irqrestore(&r->lock, flags);
15001e7e2e05SJarod Wilson 			trace_extract_entropy(r->name, EXTRACT_SIZE,
1501a283b5c4SH. Peter Anvin 					      ENTROPY_BITS(r), _RET_IP_);
15021e7e2e05SJarod Wilson 			extract_buf(r, tmp);
15031e7e2e05SJarod Wilson 			spin_lock_irqsave(&r->lock, flags);
15041e7e2e05SJarod Wilson 			memcpy(r->last_data, tmp, EXTRACT_SIZE);
15051e7e2e05SJarod Wilson 		}
15061e7e2e05SJarod Wilson 		spin_unlock_irqrestore(&r->lock, flags);
15071e7e2e05SJarod Wilson 	}
1508ec8f02daSJarod Wilson 
1509a283b5c4SH. Peter Anvin 	trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
15101da177e4SLinus Torvalds 	nbytes = account(r, nbytes, min, reserved);
15111da177e4SLinus Torvalds 
1512e192be9dSTheodore Ts'o 	return _extract_entropy(r, buf, nbytes, fips_enabled);
15131da177e4SLinus Torvalds }
15141da177e4SLinus Torvalds 
1515eecabf56STheodore Ts'o #define warn_unseeded_randomness(previous) \
1516eecabf56STheodore Ts'o 	_warn_unseeded_randomness(__func__, (void *) _RET_IP_, (previous))
1517eecabf56STheodore Ts'o 
1518eecabf56STheodore Ts'o static void _warn_unseeded_randomness(const char *func_name, void *caller,
1519eecabf56STheodore Ts'o 				      void **previous)
1520eecabf56STheodore Ts'o {
1521eecabf56STheodore Ts'o #ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
1522eecabf56STheodore Ts'o 	const bool print_once = false;
1523eecabf56STheodore Ts'o #else
1524eecabf56STheodore Ts'o 	static bool print_once __read_mostly;
1525eecabf56STheodore Ts'o #endif
1526eecabf56STheodore Ts'o 
1527eecabf56STheodore Ts'o 	if (print_once ||
1528eecabf56STheodore Ts'o 	    crng_ready() ||
1529eecabf56STheodore Ts'o 	    (previous && (caller == READ_ONCE(*previous))))
1530eecabf56STheodore Ts'o 		return;
1531eecabf56STheodore Ts'o 	WRITE_ONCE(*previous, caller);
1532eecabf56STheodore Ts'o #ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
1533eecabf56STheodore Ts'o 	print_once = true;
1534eecabf56STheodore Ts'o #endif
15354e00b339STheodore Ts'o 	if (__ratelimit(&unseeded_warning))
15361b710b1bSSergey Senozhatsky 		printk_deferred(KERN_NOTICE "random: %s called from %pS "
15371b710b1bSSergey Senozhatsky 				"with crng_init=%d\n", func_name, caller,
15381b710b1bSSergey Senozhatsky 				crng_init);
1539eecabf56STheodore Ts'o }
1540eecabf56STheodore Ts'o 
15411da177e4SLinus Torvalds /*
15421da177e4SLinus Torvalds  * This function is the exported kernel interface.  It returns some
1543c2557a30STheodore Ts'o  * number of good random numbers, suitable for key generation, seeding
154418e9cea7SGreg Price  * TCP sequence numbers, etc.  It does not rely on the hardware random
154518e9cea7SGreg Price  * number generator.  For random bytes direct from the hardware RNG
1546e297a783SJason A. Donenfeld  * (when available), use get_random_bytes_arch(). In order to ensure
1547e297a783SJason A. Donenfeld  * that the randomness provided by this function is okay, the function
1548e297a783SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once
1549e297a783SJason A. Donenfeld  * at any point prior.
15501da177e4SLinus Torvalds  */
1551eecabf56STheodore Ts'o static void _get_random_bytes(void *buf, int nbytes)
15521da177e4SLinus Torvalds {
15531ca1b917SEric Biggers 	__u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
1554e192be9dSTheodore Ts'o 
15555910895fSTheodore Ts'o 	trace_get_random_bytes(nbytes, _RET_IP_);
1556e192be9dSTheodore Ts'o 
15571ca1b917SEric Biggers 	while (nbytes >= CHACHA_BLOCK_SIZE) {
1558e192be9dSTheodore Ts'o 		extract_crng(buf);
15591ca1b917SEric Biggers 		buf += CHACHA_BLOCK_SIZE;
15601ca1b917SEric Biggers 		nbytes -= CHACHA_BLOCK_SIZE;
1561e192be9dSTheodore Ts'o 	}
1562e192be9dSTheodore Ts'o 
1563e192be9dSTheodore Ts'o 	if (nbytes > 0) {
1564e192be9dSTheodore Ts'o 		extract_crng(tmp);
1565e192be9dSTheodore Ts'o 		memcpy(buf, tmp, nbytes);
1566c92e040dSTheodore Ts'o 		crng_backtrack_protect(tmp, nbytes);
1567c92e040dSTheodore Ts'o 	} else
15681ca1b917SEric Biggers 		crng_backtrack_protect(tmp, CHACHA_BLOCK_SIZE);
1569c92e040dSTheodore Ts'o 	memzero_explicit(tmp, sizeof(tmp));
1570c2557a30STheodore Ts'o }
1571eecabf56STheodore Ts'o 
1572eecabf56STheodore Ts'o void get_random_bytes(void *buf, int nbytes)
1573eecabf56STheodore Ts'o {
1574eecabf56STheodore Ts'o 	static void *previous;
1575eecabf56STheodore Ts'o 
1576eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
1577eecabf56STheodore Ts'o 	_get_random_bytes(buf, nbytes);
1578eecabf56STheodore Ts'o }
1579c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes);
1580c2557a30STheodore Ts'o 
158150ee7529SLinus Torvalds 
158250ee7529SLinus Torvalds /*
158350ee7529SLinus Torvalds  * Each time the timer fires, we expect that we got an unpredictable
158450ee7529SLinus Torvalds  * jump in the cycle counter. Even if the timer is running on another
158550ee7529SLinus Torvalds  * CPU, the timer activity will be touching the stack of the CPU that is
158650ee7529SLinus Torvalds  * generating entropy..
158750ee7529SLinus Torvalds  *
158850ee7529SLinus Torvalds  * Note that we don't re-arm the timer in the timer itself - we are
158950ee7529SLinus Torvalds  * happy to be scheduled away, since that just makes the load more
159050ee7529SLinus Torvalds  * complex, but we do not want the timer to keep ticking unless the
159150ee7529SLinus Torvalds  * entropy loop is running.
159250ee7529SLinus Torvalds  *
159350ee7529SLinus Torvalds  * So the re-arming always happens in the entropy loop itself.
159450ee7529SLinus Torvalds  */
159550ee7529SLinus Torvalds static void entropy_timer(struct timer_list *t)
159650ee7529SLinus Torvalds {
159750ee7529SLinus Torvalds 	credit_entropy_bits(&input_pool, 1);
159850ee7529SLinus Torvalds }
159950ee7529SLinus Torvalds 
160050ee7529SLinus Torvalds /*
160150ee7529SLinus Torvalds  * If we have an actual cycle counter, see if we can
160250ee7529SLinus Torvalds  * generate enough entropy with timing noise
160350ee7529SLinus Torvalds  */
160450ee7529SLinus Torvalds static void try_to_generate_entropy(void)
160550ee7529SLinus Torvalds {
160650ee7529SLinus Torvalds 	struct {
160750ee7529SLinus Torvalds 		unsigned long now;
160850ee7529SLinus Torvalds 		struct timer_list timer;
160950ee7529SLinus Torvalds 	} stack;
161050ee7529SLinus Torvalds 
161150ee7529SLinus Torvalds 	stack.now = random_get_entropy();
161250ee7529SLinus Torvalds 
161350ee7529SLinus Torvalds 	/* Slow counter - or none. Don't even bother */
161450ee7529SLinus Torvalds 	if (stack.now == random_get_entropy())
161550ee7529SLinus Torvalds 		return;
161650ee7529SLinus Torvalds 
161750ee7529SLinus Torvalds 	timer_setup_on_stack(&stack.timer, entropy_timer, 0);
161850ee7529SLinus Torvalds 	while (!crng_ready()) {
161950ee7529SLinus Torvalds 		if (!timer_pending(&stack.timer))
162050ee7529SLinus Torvalds 			mod_timer(&stack.timer, jiffies+1);
162150ee7529SLinus Torvalds 		mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
162250ee7529SLinus Torvalds 		schedule();
162350ee7529SLinus Torvalds 		stack.now = random_get_entropy();
162450ee7529SLinus Torvalds 	}
162550ee7529SLinus Torvalds 
162650ee7529SLinus Torvalds 	del_timer_sync(&stack.timer);
162750ee7529SLinus Torvalds 	destroy_timer_on_stack(&stack.timer);
162850ee7529SLinus Torvalds 	mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
162950ee7529SLinus Torvalds }
163050ee7529SLinus Torvalds 
1631c2557a30STheodore Ts'o /*
1632e297a783SJason A. Donenfeld  * Wait for the urandom pool to be seeded and thus guaranteed to supply
1633e297a783SJason A. Donenfeld  * cryptographically secure random numbers. This applies to: the /dev/urandom
1634e297a783SJason A. Donenfeld  * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1635e297a783SJason A. Donenfeld  * family of functions. Using any of these functions without first calling
1636e297a783SJason A. Donenfeld  * this function forfeits the guarantee of security.
1637e297a783SJason A. Donenfeld  *
1638e297a783SJason A. Donenfeld  * Returns: 0 if the urandom pool has been seeded.
1639e297a783SJason A. Donenfeld  *          -ERESTARTSYS if the function was interrupted by a signal.
1640e297a783SJason A. Donenfeld  */
1641e297a783SJason A. Donenfeld int wait_for_random_bytes(void)
1642e297a783SJason A. Donenfeld {
1643e297a783SJason A. Donenfeld 	if (likely(crng_ready()))
1644e297a783SJason A. Donenfeld 		return 0;
164550ee7529SLinus Torvalds 
164650ee7529SLinus Torvalds 	do {
164750ee7529SLinus Torvalds 		int ret;
164850ee7529SLinus Torvalds 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
164950ee7529SLinus Torvalds 		if (ret)
165050ee7529SLinus Torvalds 			return ret > 0 ? 0 : ret;
165150ee7529SLinus Torvalds 
165250ee7529SLinus Torvalds 		try_to_generate_entropy();
165350ee7529SLinus Torvalds 	} while (!crng_ready());
165450ee7529SLinus Torvalds 
165550ee7529SLinus Torvalds 	return 0;
1656e297a783SJason A. Donenfeld }
1657e297a783SJason A. Donenfeld EXPORT_SYMBOL(wait_for_random_bytes);
1658e297a783SJason A. Donenfeld 
1659e297a783SJason A. Donenfeld /*
16609a47249dSJason A. Donenfeld  * Returns whether or not the urandom pool has been seeded and thus guaranteed
16619a47249dSJason A. Donenfeld  * to supply cryptographically secure random numbers. This applies to: the
16629a47249dSJason A. Donenfeld  * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
16639a47249dSJason A. Donenfeld  * ,u64,int,long} family of functions.
16649a47249dSJason A. Donenfeld  *
16659a47249dSJason A. Donenfeld  * Returns: true if the urandom pool has been seeded.
16669a47249dSJason A. Donenfeld  *          false if the urandom pool has not been seeded.
16679a47249dSJason A. Donenfeld  */
16689a47249dSJason A. Donenfeld bool rng_is_initialized(void)
16699a47249dSJason A. Donenfeld {
16709a47249dSJason A. Donenfeld 	return crng_ready();
16719a47249dSJason A. Donenfeld }
16729a47249dSJason A. Donenfeld EXPORT_SYMBOL(rng_is_initialized);
16739a47249dSJason A. Donenfeld 
16749a47249dSJason A. Donenfeld /*
1675205a525cSHerbert Xu  * Add a callback function that will be invoked when the nonblocking
1676205a525cSHerbert Xu  * pool is initialised.
1677205a525cSHerbert Xu  *
1678205a525cSHerbert Xu  * returns: 0 if callback is successfully added
1679205a525cSHerbert Xu  *	    -EALREADY if pool is already initialised (callback not called)
1680205a525cSHerbert Xu  *	    -ENOENT if module for callback is not alive
1681205a525cSHerbert Xu  */
1682205a525cSHerbert Xu int add_random_ready_callback(struct random_ready_callback *rdy)
1683205a525cSHerbert Xu {
1684205a525cSHerbert Xu 	struct module *owner;
1685205a525cSHerbert Xu 	unsigned long flags;
1686205a525cSHerbert Xu 	int err = -EALREADY;
1687205a525cSHerbert Xu 
1688e192be9dSTheodore Ts'o 	if (crng_ready())
1689205a525cSHerbert Xu 		return err;
1690205a525cSHerbert Xu 
1691205a525cSHerbert Xu 	owner = rdy->owner;
1692205a525cSHerbert Xu 	if (!try_module_get(owner))
1693205a525cSHerbert Xu 		return -ENOENT;
1694205a525cSHerbert Xu 
1695205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
1696e192be9dSTheodore Ts'o 	if (crng_ready())
1697205a525cSHerbert Xu 		goto out;
1698205a525cSHerbert Xu 
1699205a525cSHerbert Xu 	owner = NULL;
1700205a525cSHerbert Xu 
1701205a525cSHerbert Xu 	list_add(&rdy->list, &random_ready_list);
1702205a525cSHerbert Xu 	err = 0;
1703205a525cSHerbert Xu 
1704205a525cSHerbert Xu out:
1705205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
1706205a525cSHerbert Xu 
1707205a525cSHerbert Xu 	module_put(owner);
1708205a525cSHerbert Xu 
1709205a525cSHerbert Xu 	return err;
1710205a525cSHerbert Xu }
1711205a525cSHerbert Xu EXPORT_SYMBOL(add_random_ready_callback);
1712205a525cSHerbert Xu 
1713205a525cSHerbert Xu /*
1714205a525cSHerbert Xu  * Delete a previously registered readiness callback function.
1715205a525cSHerbert Xu  */
1716205a525cSHerbert Xu void del_random_ready_callback(struct random_ready_callback *rdy)
1717205a525cSHerbert Xu {
1718205a525cSHerbert Xu 	unsigned long flags;
1719205a525cSHerbert Xu 	struct module *owner = NULL;
1720205a525cSHerbert Xu 
1721205a525cSHerbert Xu 	spin_lock_irqsave(&random_ready_list_lock, flags);
1722205a525cSHerbert Xu 	if (!list_empty(&rdy->list)) {
1723205a525cSHerbert Xu 		list_del_init(&rdy->list);
1724205a525cSHerbert Xu 		owner = rdy->owner;
1725205a525cSHerbert Xu 	}
1726205a525cSHerbert Xu 	spin_unlock_irqrestore(&random_ready_list_lock, flags);
1727205a525cSHerbert Xu 
1728205a525cSHerbert Xu 	module_put(owner);
1729205a525cSHerbert Xu }
1730205a525cSHerbert Xu EXPORT_SYMBOL(del_random_ready_callback);
1731205a525cSHerbert Xu 
1732205a525cSHerbert Xu /*
1733c2557a30STheodore Ts'o  * This function will use the architecture-specific hardware random
1734c2557a30STheodore Ts'o  * number generator if it is available.  The arch-specific hw RNG will
1735c2557a30STheodore Ts'o  * almost certainly be faster than what we can do in software, but it
1736c2557a30STheodore Ts'o  * is impossible to verify that it is implemented securely (as
1737c2557a30STheodore Ts'o  * opposed, to, say, the AES encryption of a sequence number using a
1738c2557a30STheodore Ts'o  * key known by the NSA).  So it's useful if we need the speed, but
1739c2557a30STheodore Ts'o  * only if we're willing to trust the hardware manufacturer not to
1740c2557a30STheodore Ts'o  * have put in a back door.
1741753d433bSTobin C. Harding  *
1742753d433bSTobin C. Harding  * Return number of bytes filled in.
1743c2557a30STheodore Ts'o  */
1744753d433bSTobin C. Harding int __must_check get_random_bytes_arch(void *buf, int nbytes)
1745c2557a30STheodore Ts'o {
1746753d433bSTobin C. Harding 	int left = nbytes;
174763d77173SH. Peter Anvin 	char *p = buf;
174863d77173SH. Peter Anvin 
1749753d433bSTobin C. Harding 	trace_get_random_bytes_arch(left, _RET_IP_);
1750753d433bSTobin C. Harding 	while (left) {
175163d77173SH. Peter Anvin 		unsigned long v;
1752753d433bSTobin C. Harding 		int chunk = min_t(int, left, sizeof(unsigned long));
175363d77173SH. Peter Anvin 
175463d77173SH. Peter Anvin 		if (!arch_get_random_long(&v))
175563d77173SH. Peter Anvin 			break;
175663d77173SH. Peter Anvin 
1757bd29e568SLuck, Tony 		memcpy(p, &v, chunk);
175863d77173SH. Peter Anvin 		p += chunk;
1759753d433bSTobin C. Harding 		left -= chunk;
176063d77173SH. Peter Anvin 	}
176163d77173SH. Peter Anvin 
1762753d433bSTobin C. Harding 	return nbytes - left;
17631da177e4SLinus Torvalds }
1764c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes_arch);
17651da177e4SLinus Torvalds 
17661da177e4SLinus Torvalds /*
17671da177e4SLinus Torvalds  * init_std_data - initialize pool with system data
17681da177e4SLinus Torvalds  *
17691da177e4SLinus Torvalds  * @r: pool to initialize
17701da177e4SLinus Torvalds  *
17711da177e4SLinus Torvalds  * This function clears the pool's entropy count and mixes some system
17721da177e4SLinus Torvalds  * data into the pool to prepare it for use. The pool is not cleared
17731da177e4SLinus Torvalds  * as that can only decrease the entropy in the pool.
17741da177e4SLinus Torvalds  */
1775d5553523SKees Cook static void __init init_std_data(struct entropy_store *r)
17761da177e4SLinus Torvalds {
17773e88bdffSTheodore Ts'o 	int i;
1778902c098aSTheodore Ts'o 	ktime_t now = ktime_get_real();
1779902c098aSTheodore Ts'o 	unsigned long rv;
17801da177e4SLinus Torvalds 
178185608f8eSTheodore Ts'o 	mix_pool_bytes(r, &now, sizeof(now));
17829ed17b70SH. Peter Anvin 	for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
178383664a69SH. Peter Anvin 		if (!arch_get_random_seed_long(&rv) &&
178483664a69SH. Peter Anvin 		    !arch_get_random_long(&rv))
1785ae9ecd92STheodore Ts'o 			rv = random_get_entropy();
178685608f8eSTheodore Ts'o 		mix_pool_bytes(r, &rv, sizeof(rv));
17873e88bdffSTheodore Ts'o 	}
178885608f8eSTheodore Ts'o 	mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
17891da177e4SLinus Torvalds }
17901da177e4SLinus Torvalds 
1791cbc96b75STony Luck /*
1792cbc96b75STony Luck  * Note that setup_arch() may call add_device_randomness()
1793cbc96b75STony Luck  * long before we get here. This allows seeding of the pools
1794cbc96b75STony Luck  * with some platform dependent data very early in the boot
1795cbc96b75STony Luck  * process. But it limits our options here. We must use
1796cbc96b75STony Luck  * statically allocated structures that already have all
1797cbc96b75STony Luck  * initializations complete at compile time. We should also
1798cbc96b75STony Luck  * take care not to overwrite the precious per platform data
1799cbc96b75STony Luck  * we were given.
1800cbc96b75STony Luck  */
1801d5553523SKees Cook int __init rand_initialize(void)
18021da177e4SLinus Torvalds {
18031da177e4SLinus Torvalds 	init_std_data(&input_pool);
1804e192be9dSTheodore Ts'o 	crng_initialize(&primary_crng);
1805d848e5f8STheodore Ts'o 	crng_global_init_time = jiffies;
18064e00b339STheodore Ts'o 	if (ratelimit_disable) {
18074e00b339STheodore Ts'o 		urandom_warning.interval = 0;
18084e00b339STheodore Ts'o 		unseeded_warning.interval = 0;
18094e00b339STheodore Ts'o 	}
18101da177e4SLinus Torvalds 	return 0;
18111da177e4SLinus Torvalds }
18121da177e4SLinus Torvalds 
18139361401eSDavid Howells #ifdef CONFIG_BLOCK
18141da177e4SLinus Torvalds void rand_initialize_disk(struct gendisk *disk)
18151da177e4SLinus Torvalds {
18161da177e4SLinus Torvalds 	struct timer_rand_state *state;
18171da177e4SLinus Torvalds 
18181da177e4SLinus Torvalds 	/*
1819f8595815SEric Dumazet 	 * If kzalloc returns null, we just won't use that entropy
18201da177e4SLinus Torvalds 	 * source.
18211da177e4SLinus Torvalds 	 */
1822f8595815SEric Dumazet 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1823644008dfSTheodore Ts'o 	if (state) {
1824644008dfSTheodore Ts'o 		state->last_time = INITIAL_JIFFIES;
18251da177e4SLinus Torvalds 		disk->random = state;
18261da177e4SLinus Torvalds 	}
1827644008dfSTheodore Ts'o }
18289361401eSDavid Howells #endif
18291da177e4SLinus Torvalds 
18301da177e4SLinus Torvalds static ssize_t
1831c6f1deb1SAndy Lutomirski urandom_read_nowarn(struct file *file, char __user *buf, size_t nbytes,
1832c6f1deb1SAndy Lutomirski 		    loff_t *ppos)
1833c6f1deb1SAndy Lutomirski {
1834c6f1deb1SAndy Lutomirski 	int ret;
1835c6f1deb1SAndy Lutomirski 
1836c6f1deb1SAndy Lutomirski 	nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
1837c6f1deb1SAndy Lutomirski 	ret = extract_crng_user(buf, nbytes);
1838c6f1deb1SAndy Lutomirski 	trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
1839c6f1deb1SAndy Lutomirski 	return ret;
1840c6f1deb1SAndy Lutomirski }
1841c6f1deb1SAndy Lutomirski 
1842c6f1deb1SAndy Lutomirski static ssize_t
184390b75ee5SMatt Mackall urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
18441da177e4SLinus Torvalds {
1845e192be9dSTheodore Ts'o 	unsigned long flags;
18469b4d0087STheodore Ts'o 	static int maxwarn = 10;
1847301f0595STheodore Ts'o 
1848e192be9dSTheodore Ts'o 	if (!crng_ready() && maxwarn > 0) {
18499b4d0087STheodore Ts'o 		maxwarn--;
18504e00b339STheodore Ts'o 		if (__ratelimit(&urandom_warning))
185112cd53afSYangtao Li 			pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
1852e192be9dSTheodore Ts'o 				  current->comm, nbytes);
1853e192be9dSTheodore Ts'o 		spin_lock_irqsave(&primary_crng.lock, flags);
1854e192be9dSTheodore Ts'o 		crng_init_cnt = 0;
1855e192be9dSTheodore Ts'o 		spin_unlock_irqrestore(&primary_crng.lock, flags);
18569b4d0087STheodore Ts'o 	}
1857c6f1deb1SAndy Lutomirski 
1858c6f1deb1SAndy Lutomirski 	return urandom_read_nowarn(file, buf, nbytes, ppos);
18591da177e4SLinus Torvalds }
18601da177e4SLinus Torvalds 
186130c08efeSAndy Lutomirski static ssize_t
186230c08efeSAndy Lutomirski random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
186330c08efeSAndy Lutomirski {
186430c08efeSAndy Lutomirski 	int ret;
186530c08efeSAndy Lutomirski 
186630c08efeSAndy Lutomirski 	ret = wait_for_random_bytes();
186730c08efeSAndy Lutomirski 	if (ret != 0)
186830c08efeSAndy Lutomirski 		return ret;
186930c08efeSAndy Lutomirski 	return urandom_read_nowarn(file, buf, nbytes, ppos);
187030c08efeSAndy Lutomirski }
187130c08efeSAndy Lutomirski 
187289b310a2SChristoph Hellwig static __poll_t
1873a11e1d43SLinus Torvalds random_poll(struct file *file, poll_table * wait)
187489b310a2SChristoph Hellwig {
1875a11e1d43SLinus Torvalds 	__poll_t mask;
187689b310a2SChristoph Hellwig 
187730c08efeSAndy Lutomirski 	poll_wait(file, &crng_init_wait, wait);
1878a11e1d43SLinus Torvalds 	poll_wait(file, &random_write_wait, wait);
1879a11e1d43SLinus Torvalds 	mask = 0;
188030c08efeSAndy Lutomirski 	if (crng_ready())
1881a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
18822132a96fSGreg Price 	if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
1883a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
18841da177e4SLinus Torvalds 	return mask;
18851da177e4SLinus Torvalds }
18861da177e4SLinus Torvalds 
18877f397dcdSMatt Mackall static int
18887f397dcdSMatt Mackall write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
18897f397dcdSMatt Mackall {
18907f397dcdSMatt Mackall 	size_t bytes;
189181e69df3STheodore Ts'o 	__u32 t, buf[16];
18927f397dcdSMatt Mackall 	const char __user *p = buffer;
18937f397dcdSMatt Mackall 
18947f397dcdSMatt Mackall 	while (count > 0) {
189581e69df3STheodore Ts'o 		int b, i = 0;
189681e69df3STheodore Ts'o 
18977f397dcdSMatt Mackall 		bytes = min(count, sizeof(buf));
18987f397dcdSMatt Mackall 		if (copy_from_user(&buf, p, bytes))
18997f397dcdSMatt Mackall 			return -EFAULT;
19007f397dcdSMatt Mackall 
190181e69df3STheodore Ts'o 		for (b = bytes ; b > 0 ; b -= sizeof(__u32), i++) {
190281e69df3STheodore Ts'o 			if (!arch_get_random_int(&t))
190381e69df3STheodore Ts'o 				break;
190481e69df3STheodore Ts'o 			buf[i] ^= t;
190581e69df3STheodore Ts'o 		}
190681e69df3STheodore Ts'o 
19077f397dcdSMatt Mackall 		count -= bytes;
19087f397dcdSMatt Mackall 		p += bytes;
19097f397dcdSMatt Mackall 
191085608f8eSTheodore Ts'o 		mix_pool_bytes(r, buf, bytes);
191191f3f1e3SMatt Mackall 		cond_resched();
19127f397dcdSMatt Mackall 	}
19137f397dcdSMatt Mackall 
19147f397dcdSMatt Mackall 	return 0;
19157f397dcdSMatt Mackall }
19167f397dcdSMatt Mackall 
191790b75ee5SMatt Mackall static ssize_t random_write(struct file *file, const char __user *buffer,
19181da177e4SLinus Torvalds 			    size_t count, loff_t *ppos)
19191da177e4SLinus Torvalds {
19207f397dcdSMatt Mackall 	size_t ret;
19217f397dcdSMatt Mackall 
1922e192be9dSTheodore Ts'o 	ret = write_pool(&input_pool, buffer, count);
19237f397dcdSMatt Mackall 	if (ret)
19247f397dcdSMatt Mackall 		return ret;
19257f397dcdSMatt Mackall 
19267f397dcdSMatt Mackall 	return (ssize_t)count;
19271da177e4SLinus Torvalds }
19281da177e4SLinus Torvalds 
192943ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
19301da177e4SLinus Torvalds {
19311da177e4SLinus Torvalds 	int size, ent_count;
19321da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
19331da177e4SLinus Torvalds 	int retval;
19341da177e4SLinus Torvalds 
19351da177e4SLinus Torvalds 	switch (cmd) {
19361da177e4SLinus Torvalds 	case RNDGETENTCNT:
193743ae4860SMatt Mackall 		/* inherently racy, no point locking */
1938a283b5c4SH. Peter Anvin 		ent_count = ENTROPY_BITS(&input_pool);
1939a283b5c4SH. Peter Anvin 		if (put_user(ent_count, p))
19401da177e4SLinus Torvalds 			return -EFAULT;
19411da177e4SLinus Torvalds 		return 0;
19421da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
19431da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
19441da177e4SLinus Torvalds 			return -EPERM;
19451da177e4SLinus Torvalds 		if (get_user(ent_count, p))
19461da177e4SLinus Torvalds 			return -EFAULT;
194786a574deSTheodore Ts'o 		return credit_entropy_bits_safe(&input_pool, ent_count);
19481da177e4SLinus Torvalds 	case RNDADDENTROPY:
19491da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
19501da177e4SLinus Torvalds 			return -EPERM;
19511da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
19521da177e4SLinus Torvalds 			return -EFAULT;
19531da177e4SLinus Torvalds 		if (ent_count < 0)
19541da177e4SLinus Torvalds 			return -EINVAL;
19551da177e4SLinus Torvalds 		if (get_user(size, p++))
19561da177e4SLinus Torvalds 			return -EFAULT;
19577f397dcdSMatt Mackall 		retval = write_pool(&input_pool, (const char __user *)p,
19587f397dcdSMatt Mackall 				    size);
19591da177e4SLinus Torvalds 		if (retval < 0)
19601da177e4SLinus Torvalds 			return retval;
196186a574deSTheodore Ts'o 		return credit_entropy_bits_safe(&input_pool, ent_count);
19621da177e4SLinus Torvalds 	case RNDZAPENTCNT:
19631da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1964ae9ecd92STheodore Ts'o 		/*
1965ae9ecd92STheodore Ts'o 		 * Clear the entropy pool counters. We no longer clear
1966ae9ecd92STheodore Ts'o 		 * the entropy pool, as that's silly.
1967ae9ecd92STheodore Ts'o 		 */
19681da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
19691da177e4SLinus Torvalds 			return -EPERM;
1970ae9ecd92STheodore Ts'o 		input_pool.entropy_count = 0;
19711da177e4SLinus Torvalds 		return 0;
1972d848e5f8STheodore Ts'o 	case RNDRESEEDCRNG:
1973d848e5f8STheodore Ts'o 		if (!capable(CAP_SYS_ADMIN))
1974d848e5f8STheodore Ts'o 			return -EPERM;
1975d848e5f8STheodore Ts'o 		if (crng_init < 2)
1976d848e5f8STheodore Ts'o 			return -ENODATA;
1977d848e5f8STheodore Ts'o 		crng_reseed(&primary_crng, NULL);
1978d848e5f8STheodore Ts'o 		crng_global_init_time = jiffies - 1;
1979d848e5f8STheodore Ts'o 		return 0;
19801da177e4SLinus Torvalds 	default:
19811da177e4SLinus Torvalds 		return -EINVAL;
19821da177e4SLinus Torvalds 	}
19831da177e4SLinus Torvalds }
19841da177e4SLinus Torvalds 
19859a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
19869a6f70bbSJeff Dike {
19879a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
19889a6f70bbSJeff Dike }
19899a6f70bbSJeff Dike 
19902b8693c0SArjan van de Ven const struct file_operations random_fops = {
19911da177e4SLinus Torvalds 	.read  = random_read,
19921da177e4SLinus Torvalds 	.write = random_write,
1993a11e1d43SLinus Torvalds 	.poll  = random_poll,
199443ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
1995507e4e2bSArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
19969a6f70bbSJeff Dike 	.fasync = random_fasync,
19976038f373SArnd Bergmann 	.llseek = noop_llseek,
19981da177e4SLinus Torvalds };
19991da177e4SLinus Torvalds 
20002b8693c0SArjan van de Ven const struct file_operations urandom_fops = {
20011da177e4SLinus Torvalds 	.read  = urandom_read,
20021da177e4SLinus Torvalds 	.write = random_write,
200343ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
20044aa37c46SJason A. Donenfeld 	.compat_ioctl = compat_ptr_ioctl,
20059a6f70bbSJeff Dike 	.fasync = random_fasync,
20066038f373SArnd Bergmann 	.llseek = noop_llseek,
20071da177e4SLinus Torvalds };
20081da177e4SLinus Torvalds 
2009c6e9d6f3STheodore Ts'o SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
2010c6e9d6f3STheodore Ts'o 		unsigned int, flags)
2011c6e9d6f3STheodore Ts'o {
2012e297a783SJason A. Donenfeld 	int ret;
2013e297a783SJason A. Donenfeld 
201475551dbfSAndy Lutomirski 	if (flags & ~(GRND_NONBLOCK|GRND_RANDOM|GRND_INSECURE))
201575551dbfSAndy Lutomirski 		return -EINVAL;
201675551dbfSAndy Lutomirski 
201775551dbfSAndy Lutomirski 	/*
201875551dbfSAndy Lutomirski 	 * Requesting insecure and blocking randomness at the same time makes
201975551dbfSAndy Lutomirski 	 * no sense.
202075551dbfSAndy Lutomirski 	 */
202175551dbfSAndy Lutomirski 	if ((flags & (GRND_INSECURE|GRND_RANDOM)) == (GRND_INSECURE|GRND_RANDOM))
2022c6e9d6f3STheodore Ts'o 		return -EINVAL;
2023c6e9d6f3STheodore Ts'o 
2024c6e9d6f3STheodore Ts'o 	if (count > INT_MAX)
2025c6e9d6f3STheodore Ts'o 		count = INT_MAX;
2026c6e9d6f3STheodore Ts'o 
202775551dbfSAndy Lutomirski 	if (!(flags & GRND_INSECURE) && !crng_ready()) {
2028c6e9d6f3STheodore Ts'o 		if (flags & GRND_NONBLOCK)
2029c6e9d6f3STheodore Ts'o 			return -EAGAIN;
2030e297a783SJason A. Donenfeld 		ret = wait_for_random_bytes();
2031e297a783SJason A. Donenfeld 		if (unlikely(ret))
2032e297a783SJason A. Donenfeld 			return ret;
2033c6e9d6f3STheodore Ts'o 	}
2034c6f1deb1SAndy Lutomirski 	return urandom_read_nowarn(NULL, buf, count, NULL);
2035c6e9d6f3STheodore Ts'o }
2036c6e9d6f3STheodore Ts'o 
20371da177e4SLinus Torvalds /********************************************************************
20381da177e4SLinus Torvalds  *
20391da177e4SLinus Torvalds  * Sysctl interface
20401da177e4SLinus Torvalds  *
20411da177e4SLinus Torvalds  ********************************************************************/
20421da177e4SLinus Torvalds 
20431da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
20441da177e4SLinus Torvalds 
20451da177e4SLinus Torvalds #include <linux/sysctl.h>
20461da177e4SLinus Torvalds 
2047c95ea0c6SAndy Lutomirski static int min_write_thresh;
20481da177e4SLinus Torvalds static int max_write_thresh = INPUT_POOL_WORDS * 32;
2049db61ffe3SFabio Estevam static int random_min_urandom_seed = 60;
20501da177e4SLinus Torvalds static char sysctl_bootid[16];
20511da177e4SLinus Torvalds 
20521da177e4SLinus Torvalds /*
2053f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
20541da177e4SLinus Torvalds  * UUID.  The difference is in whether table->data is NULL; if it is,
20551da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
20561da177e4SLinus Torvalds  *
2057f22052b2SGreg Price  * If the user accesses this via the proc interface, the UUID will be
2058f22052b2SGreg Price  * returned as an ASCII string in the standard UUID format; if via the
2059f22052b2SGreg Price  * sysctl system call, as 16 bytes of binary data.
20601da177e4SLinus Torvalds  */
2061a151427eSJoe Perches static int proc_do_uuid(struct ctl_table *table, int write,
20621da177e4SLinus Torvalds 			void __user *buffer, size_t *lenp, loff_t *ppos)
20631da177e4SLinus Torvalds {
2064a151427eSJoe Perches 	struct ctl_table fake_table;
20651da177e4SLinus Torvalds 	unsigned char buf[64], tmp_uuid[16], *uuid;
20661da177e4SLinus Torvalds 
20671da177e4SLinus Torvalds 	uuid = table->data;
20681da177e4SLinus Torvalds 	if (!uuid) {
20691da177e4SLinus Torvalds 		uuid = tmp_uuid;
20701da177e4SLinus Torvalds 		generate_random_uuid(uuid);
207144e4360fSMathieu Desnoyers 	} else {
207244e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
207344e4360fSMathieu Desnoyers 
207444e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
207544e4360fSMathieu Desnoyers 		if (!uuid[8])
207644e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
207744e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
207844e4360fSMathieu Desnoyers 	}
20791da177e4SLinus Torvalds 
208035900771SJoe Perches 	sprintf(buf, "%pU", uuid);
208135900771SJoe Perches 
20821da177e4SLinus Torvalds 	fake_table.data = buf;
20831da177e4SLinus Torvalds 	fake_table.maxlen = sizeof(buf);
20841da177e4SLinus Torvalds 
20858d65af78SAlexey Dobriyan 	return proc_dostring(&fake_table, write, buffer, lenp, ppos);
20861da177e4SLinus Torvalds }
20871da177e4SLinus Torvalds 
2088a283b5c4SH. Peter Anvin /*
2089a283b5c4SH. Peter Anvin  * Return entropy available scaled to integral bits
2090a283b5c4SH. Peter Anvin  */
20915eb10d91SJoe Perches static int proc_do_entropy(struct ctl_table *table, int write,
2092a283b5c4SH. Peter Anvin 			   void __user *buffer, size_t *lenp, loff_t *ppos)
2093a283b5c4SH. Peter Anvin {
20945eb10d91SJoe Perches 	struct ctl_table fake_table;
2095a283b5c4SH. Peter Anvin 	int entropy_count;
2096a283b5c4SH. Peter Anvin 
2097a283b5c4SH. Peter Anvin 	entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
2098a283b5c4SH. Peter Anvin 
2099a283b5c4SH. Peter Anvin 	fake_table.data = &entropy_count;
2100a283b5c4SH. Peter Anvin 	fake_table.maxlen = sizeof(entropy_count);
2101a283b5c4SH. Peter Anvin 
2102a283b5c4SH. Peter Anvin 	return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
2103a283b5c4SH. Peter Anvin }
2104a283b5c4SH. Peter Anvin 
21051da177e4SLinus Torvalds static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
2106a151427eSJoe Perches extern struct ctl_table random_table[];
2107a151427eSJoe Perches struct ctl_table random_table[] = {
21081da177e4SLinus Torvalds 	{
21091da177e4SLinus Torvalds 		.procname	= "poolsize",
21101da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
21111da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
21121da177e4SLinus Torvalds 		.mode		= 0444,
21136d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
21141da177e4SLinus Torvalds 	},
21151da177e4SLinus Torvalds 	{
21161da177e4SLinus Torvalds 		.procname	= "entropy_avail",
21171da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
21181da177e4SLinus Torvalds 		.mode		= 0444,
2119a283b5c4SH. Peter Anvin 		.proc_handler	= proc_do_entropy,
21201da177e4SLinus Torvalds 		.data		= &input_pool.entropy_count,
21211da177e4SLinus Torvalds 	},
21221da177e4SLinus Torvalds 	{
21231da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
21242132a96fSGreg Price 		.data		= &random_write_wakeup_bits,
21251da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
21261da177e4SLinus Torvalds 		.mode		= 0644,
21276d456111SEric W. Biederman 		.proc_handler	= proc_dointvec_minmax,
21281da177e4SLinus Torvalds 		.extra1		= &min_write_thresh,
21291da177e4SLinus Torvalds 		.extra2		= &max_write_thresh,
21301da177e4SLinus Torvalds 	},
21311da177e4SLinus Torvalds 	{
2132f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
2133f5c2742cSTheodore Ts'o 		.data		= &random_min_urandom_seed,
2134f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
2135f5c2742cSTheodore Ts'o 		.mode		= 0644,
2136f5c2742cSTheodore Ts'o 		.proc_handler	= proc_dointvec,
2137f5c2742cSTheodore Ts'o 	},
2138f5c2742cSTheodore Ts'o 	{
21391da177e4SLinus Torvalds 		.procname	= "boot_id",
21401da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
21411da177e4SLinus Torvalds 		.maxlen		= 16,
21421da177e4SLinus Torvalds 		.mode		= 0444,
21436d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
21441da177e4SLinus Torvalds 	},
21451da177e4SLinus Torvalds 	{
21461da177e4SLinus Torvalds 		.procname	= "uuid",
21471da177e4SLinus Torvalds 		.maxlen		= 16,
21481da177e4SLinus Torvalds 		.mode		= 0444,
21496d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
21501da177e4SLinus Torvalds 	},
215143759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
215243759d4fSTheodore Ts'o 	{
215343759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_cycles",
215443759d4fSTheodore Ts'o 		.data		= &avg_cycles,
215543759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_cycles),
215643759d4fSTheodore Ts'o 		.mode		= 0444,
215743759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
215843759d4fSTheodore Ts'o 	},
215943759d4fSTheodore Ts'o 	{
216043759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_deviation",
216143759d4fSTheodore Ts'o 		.data		= &avg_deviation,
216243759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_deviation),
216343759d4fSTheodore Ts'o 		.mode		= 0444,
216443759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
216543759d4fSTheodore Ts'o 	},
216643759d4fSTheodore Ts'o #endif
2167894d2491SEric W. Biederman 	{ }
21681da177e4SLinus Torvalds };
21691da177e4SLinus Torvalds #endif 	/* CONFIG_SYSCTL */
21701da177e4SLinus Torvalds 
2171f5b98461SJason A. Donenfeld struct batched_entropy {
2172f5b98461SJason A. Donenfeld 	union {
21731ca1b917SEric Biggers 		u64 entropy_u64[CHACHA_BLOCK_SIZE / sizeof(u64)];
21741ca1b917SEric Biggers 		u32 entropy_u32[CHACHA_BLOCK_SIZE / sizeof(u32)];
2175f5b98461SJason A. Donenfeld 	};
2176f5b98461SJason A. Donenfeld 	unsigned int position;
2177b7d5dc21SSebastian Andrzej Siewior 	spinlock_t batch_lock;
2178f5b98461SJason A. Donenfeld };
2179b1132deaSEric Biggers 
21801da177e4SLinus Torvalds /*
2181f5b98461SJason A. Donenfeld  * Get a random word for internal kernel use only. The quality of the random
2182f5b98461SJason A. Donenfeld  * number is either as good as RDRAND or as good as /dev/urandom, with the
2183e297a783SJason A. Donenfeld  * goal of being quite fast and not depleting entropy. In order to ensure
2184e297a783SJason A. Donenfeld  * that the randomness provided by this function is okay, the function
2185e297a783SJason A. Donenfeld  * wait_for_random_bytes() should be called and return 0 at least once
2186e297a783SJason A. Donenfeld  * at any point prior.
21871da177e4SLinus Torvalds  */
2188b7d5dc21SSebastian Andrzej Siewior static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
2189b7d5dc21SSebastian Andrzej Siewior 	.batch_lock	= __SPIN_LOCK_UNLOCKED(batched_entropy_u64.lock),
2190b7d5dc21SSebastian Andrzej Siewior };
2191b7d5dc21SSebastian Andrzej Siewior 
2192c440408cSJason A. Donenfeld u64 get_random_u64(void)
2193ec9ee4acSDaniel Cashman {
2194c440408cSJason A. Donenfeld 	u64 ret;
2195b7d5dc21SSebastian Andrzej Siewior 	unsigned long flags;
2196f5b98461SJason A. Donenfeld 	struct batched_entropy *batch;
2197eecabf56STheodore Ts'o 	static void *previous;
2198ec9ee4acSDaniel Cashman 
2199c440408cSJason A. Donenfeld #if BITS_PER_LONG == 64
2200c440408cSJason A. Donenfeld 	if (arch_get_random_long((unsigned long *)&ret))
2201ec9ee4acSDaniel Cashman 		return ret;
2202c440408cSJason A. Donenfeld #else
2203c440408cSJason A. Donenfeld 	if (arch_get_random_long((unsigned long *)&ret) &&
2204c440408cSJason A. Donenfeld 	    arch_get_random_long((unsigned long *)&ret + 1))
2205c440408cSJason A. Donenfeld 	    return ret;
2206c440408cSJason A. Donenfeld #endif
2207ec9ee4acSDaniel Cashman 
2208eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
2209d06bfd19SJason A. Donenfeld 
2210b7d5dc21SSebastian Andrzej Siewior 	batch = raw_cpu_ptr(&batched_entropy_u64);
2211b7d5dc21SSebastian Andrzej Siewior 	spin_lock_irqsave(&batch->batch_lock, flags);
2212c440408cSJason A. Donenfeld 	if (batch->position % ARRAY_SIZE(batch->entropy_u64) == 0) {
2213a5e9f557SEric Biggers 		extract_crng((u8 *)batch->entropy_u64);
2214f5b98461SJason A. Donenfeld 		batch->position = 0;
2215f5b98461SJason A. Donenfeld 	}
2216c440408cSJason A. Donenfeld 	ret = batch->entropy_u64[batch->position++];
2217b7d5dc21SSebastian Andrzej Siewior 	spin_unlock_irqrestore(&batch->batch_lock, flags);
2218ec9ee4acSDaniel Cashman 	return ret;
2219ec9ee4acSDaniel Cashman }
2220c440408cSJason A. Donenfeld EXPORT_SYMBOL(get_random_u64);
2221ec9ee4acSDaniel Cashman 
2222b7d5dc21SSebastian Andrzej Siewior static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
2223b7d5dc21SSebastian Andrzej Siewior 	.batch_lock	= __SPIN_LOCK_UNLOCKED(batched_entropy_u32.lock),
2224b7d5dc21SSebastian Andrzej Siewior };
2225c440408cSJason A. Donenfeld u32 get_random_u32(void)
2226f5b98461SJason A. Donenfeld {
2227c440408cSJason A. Donenfeld 	u32 ret;
2228b7d5dc21SSebastian Andrzej Siewior 	unsigned long flags;
2229f5b98461SJason A. Donenfeld 	struct batched_entropy *batch;
2230eecabf56STheodore Ts'o 	static void *previous;
2231f5b98461SJason A. Donenfeld 
2232f5b98461SJason A. Donenfeld 	if (arch_get_random_int(&ret))
2233f5b98461SJason A. Donenfeld 		return ret;
2234f5b98461SJason A. Donenfeld 
2235eecabf56STheodore Ts'o 	warn_unseeded_randomness(&previous);
2236d06bfd19SJason A. Donenfeld 
2237b7d5dc21SSebastian Andrzej Siewior 	batch = raw_cpu_ptr(&batched_entropy_u32);
2238b7d5dc21SSebastian Andrzej Siewior 	spin_lock_irqsave(&batch->batch_lock, flags);
2239c440408cSJason A. Donenfeld 	if (batch->position % ARRAY_SIZE(batch->entropy_u32) == 0) {
2240a5e9f557SEric Biggers 		extract_crng((u8 *)batch->entropy_u32);
2241f5b98461SJason A. Donenfeld 		batch->position = 0;
2242f5b98461SJason A. Donenfeld 	}
2243c440408cSJason A. Donenfeld 	ret = batch->entropy_u32[batch->position++];
2244b7d5dc21SSebastian Andrzej Siewior 	spin_unlock_irqrestore(&batch->batch_lock, flags);
2245f5b98461SJason A. Donenfeld 	return ret;
2246f5b98461SJason A. Donenfeld }
2247c440408cSJason A. Donenfeld EXPORT_SYMBOL(get_random_u32);
2248f5b98461SJason A. Donenfeld 
2249b169c13dSJason A. Donenfeld /* It's important to invalidate all potential batched entropy that might
2250b169c13dSJason A. Donenfeld  * be stored before the crng is initialized, which we can do lazily by
2251b169c13dSJason A. Donenfeld  * simply resetting the counter to zero so that it's re-extracted on the
2252b169c13dSJason A. Donenfeld  * next usage. */
2253b169c13dSJason A. Donenfeld static void invalidate_batched_entropy(void)
2254b169c13dSJason A. Donenfeld {
2255b169c13dSJason A. Donenfeld 	int cpu;
2256b169c13dSJason A. Donenfeld 	unsigned long flags;
2257b169c13dSJason A. Donenfeld 
2258b169c13dSJason A. Donenfeld 	for_each_possible_cpu (cpu) {
2259b7d5dc21SSebastian Andrzej Siewior 		struct batched_entropy *batched_entropy;
2260b7d5dc21SSebastian Andrzej Siewior 
2261b7d5dc21SSebastian Andrzej Siewior 		batched_entropy = per_cpu_ptr(&batched_entropy_u32, cpu);
2262b7d5dc21SSebastian Andrzej Siewior 		spin_lock_irqsave(&batched_entropy->batch_lock, flags);
2263b7d5dc21SSebastian Andrzej Siewior 		batched_entropy->position = 0;
2264b7d5dc21SSebastian Andrzej Siewior 		spin_unlock(&batched_entropy->batch_lock);
2265b7d5dc21SSebastian Andrzej Siewior 
2266b7d5dc21SSebastian Andrzej Siewior 		batched_entropy = per_cpu_ptr(&batched_entropy_u64, cpu);
2267b7d5dc21SSebastian Andrzej Siewior 		spin_lock(&batched_entropy->batch_lock);
2268b7d5dc21SSebastian Andrzej Siewior 		batched_entropy->position = 0;
2269b7d5dc21SSebastian Andrzej Siewior 		spin_unlock_irqrestore(&batched_entropy->batch_lock, flags);
2270b169c13dSJason A. Donenfeld 	}
2271b169c13dSJason A. Donenfeld }
2272b169c13dSJason A. Donenfeld 
227399fdafdeSJason Cooper /**
227499fdafdeSJason Cooper  * randomize_page - Generate a random, page aligned address
227599fdafdeSJason Cooper  * @start:	The smallest acceptable address the caller will take.
227699fdafdeSJason Cooper  * @range:	The size of the area, starting at @start, within which the
227799fdafdeSJason Cooper  *		random address must fall.
227899fdafdeSJason Cooper  *
227999fdafdeSJason Cooper  * If @start + @range would overflow, @range is capped.
228099fdafdeSJason Cooper  *
228199fdafdeSJason Cooper  * NOTE: Historical use of randomize_range, which this replaces, presumed that
228299fdafdeSJason Cooper  * @start was already page aligned.  We now align it regardless.
228399fdafdeSJason Cooper  *
228499fdafdeSJason Cooper  * Return: A page aligned address within [start, start + range).  On error,
228599fdafdeSJason Cooper  * @start is returned.
228699fdafdeSJason Cooper  */
228799fdafdeSJason Cooper unsigned long
228899fdafdeSJason Cooper randomize_page(unsigned long start, unsigned long range)
228999fdafdeSJason Cooper {
229099fdafdeSJason Cooper 	if (!PAGE_ALIGNED(start)) {
229199fdafdeSJason Cooper 		range -= PAGE_ALIGN(start) - start;
229299fdafdeSJason Cooper 		start = PAGE_ALIGN(start);
229399fdafdeSJason Cooper 	}
229499fdafdeSJason Cooper 
229599fdafdeSJason Cooper 	if (start > ULONG_MAX - range)
229699fdafdeSJason Cooper 		range = ULONG_MAX - start;
229799fdafdeSJason Cooper 
229899fdafdeSJason Cooper 	range >>= PAGE_SHIFT;
229999fdafdeSJason Cooper 
230099fdafdeSJason Cooper 	if (range == 0)
230199fdafdeSJason Cooper 		return start;
230299fdafdeSJason Cooper 
230399fdafdeSJason Cooper 	return start + (get_random_long() % range << PAGE_SHIFT);
230499fdafdeSJason Cooper }
230599fdafdeSJason Cooper 
2306c84dbf61STorsten Duwe /* Interface for in-kernel drivers of true hardware RNGs.
2307c84dbf61STorsten Duwe  * Those devices may produce endless random bits and will be throttled
2308c84dbf61STorsten Duwe  * when our pool is full.
2309c84dbf61STorsten Duwe  */
2310c84dbf61STorsten Duwe void add_hwgenerator_randomness(const char *buffer, size_t count,
2311c84dbf61STorsten Duwe 				size_t entropy)
2312c84dbf61STorsten Duwe {
2313c84dbf61STorsten Duwe 	struct entropy_store *poolp = &input_pool;
2314c84dbf61STorsten Duwe 
231543838a23STheodore Ts'o 	if (unlikely(crng_init == 0)) {
2316e192be9dSTheodore Ts'o 		crng_fast_load(buffer, count);
2317e192be9dSTheodore Ts'o 		return;
23183371f3daSTheodore Ts'o 	}
2319e192be9dSTheodore Ts'o 
2320e192be9dSTheodore Ts'o 	/* Suspend writing if we're above the trickle threshold.
2321e192be9dSTheodore Ts'o 	 * We'll be woken up again once below random_write_wakeup_thresh,
2322e192be9dSTheodore Ts'o 	 * or when the calling thread is about to terminate.
2323e192be9dSTheodore Ts'o 	 */
232408e97aecSHerbert Xu 	wait_event_interruptible(random_write_wait, kthread_should_stop() ||
2325e192be9dSTheodore Ts'o 			ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
2326c84dbf61STorsten Duwe 	mix_pool_bytes(poolp, buffer, count);
2327c84dbf61STorsten Duwe 	credit_entropy_bits(poolp, entropy);
2328c84dbf61STorsten Duwe }
2329c84dbf61STorsten Duwe EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
2330428826f5SHsin-Yi Wang 
2331428826f5SHsin-Yi Wang /* Handle random seed passed by bootloader.
2332428826f5SHsin-Yi Wang  * If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
2333428826f5SHsin-Yi Wang  * it would be regarded as device data.
2334428826f5SHsin-Yi Wang  * The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
2335428826f5SHsin-Yi Wang  */
2336428826f5SHsin-Yi Wang void add_bootloader_randomness(const void *buf, unsigned int size)
2337428826f5SHsin-Yi Wang {
2338428826f5SHsin-Yi Wang 	if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
2339428826f5SHsin-Yi Wang 		add_hwgenerator_randomness(buf, size, size * 8);
2340428826f5SHsin-Yi Wang 	else
2341428826f5SHsin-Yi Wang 		add_device_randomness(buf, size);
2342428826f5SHsin-Yi Wang }
2343428826f5SHsin-Yi Wang EXPORT_SYMBOL_GPL(add_bootloader_randomness);
2344