xref: /linux/drivers/char/random.c (revision 1b2a1a7e8ad1144dc3f676f2651cb84e01548d59)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * random.c -- A strong random number generator
31da177e4SLinus Torvalds  *
49e95ce27SMatt Mackall  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
71da177e4SLinus Torvalds  * rights reserved.
81da177e4SLinus Torvalds  *
91da177e4SLinus Torvalds  * Redistribution and use in source and binary forms, with or without
101da177e4SLinus Torvalds  * modification, are permitted provided that the following conditions
111da177e4SLinus Torvalds  * are met:
121da177e4SLinus Torvalds  * 1. Redistributions of source code must retain the above copyright
131da177e4SLinus Torvalds  *    notice, and the entire permission notice in its entirety,
141da177e4SLinus Torvalds  *    including the disclaimer of warranties.
151da177e4SLinus Torvalds  * 2. Redistributions in binary form must reproduce the above copyright
161da177e4SLinus Torvalds  *    notice, this list of conditions and the following disclaimer in the
171da177e4SLinus Torvalds  *    documentation and/or other materials provided with the distribution.
181da177e4SLinus Torvalds  * 3. The name of the author may not be used to endorse or promote
191da177e4SLinus Torvalds  *    products derived from this software without specific prior
201da177e4SLinus Torvalds  *    written permission.
211da177e4SLinus Torvalds  *
221da177e4SLinus Torvalds  * ALTERNATIVELY, this product may be distributed under the terms of
231da177e4SLinus Torvalds  * the GNU General Public License, in which case the provisions of the GPL are
241da177e4SLinus Torvalds  * required INSTEAD OF the above restrictions.  (This clause is
251da177e4SLinus Torvalds  * necessary due to a potential bad interaction between the GPL and
261da177e4SLinus Torvalds  * the restrictions contained in a BSD-style copyright.)
271da177e4SLinus Torvalds  *
281da177e4SLinus Torvalds  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
291da177e4SLinus Torvalds  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
301da177e4SLinus Torvalds  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
311da177e4SLinus Torvalds  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
321da177e4SLinus Torvalds  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
331da177e4SLinus Torvalds  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
341da177e4SLinus Torvalds  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
351da177e4SLinus Torvalds  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
361da177e4SLinus Torvalds  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
371da177e4SLinus Torvalds  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
381da177e4SLinus Torvalds  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
391da177e4SLinus Torvalds  * DAMAGE.
401da177e4SLinus Torvalds  */
411da177e4SLinus Torvalds 
421da177e4SLinus Torvalds /*
431da177e4SLinus Torvalds  * (now, with legal B.S. out of the way.....)
441da177e4SLinus Torvalds  *
451da177e4SLinus Torvalds  * This routine gathers environmental noise from device drivers, etc.,
461da177e4SLinus Torvalds  * and returns good random numbers, suitable for cryptographic use.
471da177e4SLinus Torvalds  * Besides the obvious cryptographic uses, these numbers are also good
481da177e4SLinus Torvalds  * for seeding TCP sequence numbers, and other places where it is
491da177e4SLinus Torvalds  * desirable to have numbers which are not only random, but hard to
501da177e4SLinus Torvalds  * predict by an attacker.
511da177e4SLinus Torvalds  *
521da177e4SLinus Torvalds  * Theory of operation
531da177e4SLinus Torvalds  * ===================
541da177e4SLinus Torvalds  *
551da177e4SLinus Torvalds  * Computers are very predictable devices.  Hence it is extremely hard
561da177e4SLinus Torvalds  * to produce truly random numbers on a computer --- as opposed to
571da177e4SLinus Torvalds  * pseudo-random numbers, which can easily generated by using a
581da177e4SLinus Torvalds  * algorithm.  Unfortunately, it is very easy for attackers to guess
591da177e4SLinus Torvalds  * the sequence of pseudo-random number generators, and for some
601da177e4SLinus Torvalds  * applications this is not acceptable.  So instead, we must try to
611da177e4SLinus Torvalds  * gather "environmental noise" from the computer's environment, which
621da177e4SLinus Torvalds  * must be hard for outside attackers to observe, and use that to
631da177e4SLinus Torvalds  * generate random numbers.  In a Unix environment, this is best done
641da177e4SLinus Torvalds  * from inside the kernel.
651da177e4SLinus Torvalds  *
661da177e4SLinus Torvalds  * Sources of randomness from the environment include inter-keyboard
671da177e4SLinus Torvalds  * timings, inter-interrupt timings from some interrupts, and other
681da177e4SLinus Torvalds  * events which are both (a) non-deterministic and (b) hard for an
691da177e4SLinus Torvalds  * outside observer to measure.  Randomness from these sources are
701da177e4SLinus Torvalds  * added to an "entropy pool", which is mixed using a CRC-like function.
711da177e4SLinus Torvalds  * This is not cryptographically strong, but it is adequate assuming
721da177e4SLinus Torvalds  * the randomness is not chosen maliciously, and it is fast enough that
731da177e4SLinus Torvalds  * the overhead of doing it on every interrupt is very reasonable.
741da177e4SLinus Torvalds  * As random bytes are mixed into the entropy pool, the routines keep
751da177e4SLinus Torvalds  * an *estimate* of how many bits of randomness have been stored into
761da177e4SLinus Torvalds  * the random number generator's internal state.
771da177e4SLinus Torvalds  *
781da177e4SLinus Torvalds  * When random bytes are desired, they are obtained by taking the SHA
791da177e4SLinus Torvalds  * hash of the contents of the "entropy pool".  The SHA hash avoids
801da177e4SLinus Torvalds  * exposing the internal state of the entropy pool.  It is believed to
811da177e4SLinus Torvalds  * be computationally infeasible to derive any useful information
821da177e4SLinus Torvalds  * about the input of SHA from its output.  Even if it is possible to
831da177e4SLinus Torvalds  * analyze SHA in some clever way, as long as the amount of data
841da177e4SLinus Torvalds  * returned from the generator is less than the inherent entropy in
851da177e4SLinus Torvalds  * the pool, the output data is totally unpredictable.  For this
861da177e4SLinus Torvalds  * reason, the routine decreases its internal estimate of how many
871da177e4SLinus Torvalds  * bits of "true randomness" are contained in the entropy pool as it
881da177e4SLinus Torvalds  * outputs random numbers.
891da177e4SLinus Torvalds  *
901da177e4SLinus Torvalds  * If this estimate goes to zero, the routine can still generate
911da177e4SLinus Torvalds  * random numbers; however, an attacker may (at least in theory) be
921da177e4SLinus Torvalds  * able to infer the future output of the generator from prior
931da177e4SLinus Torvalds  * outputs.  This requires successful cryptanalysis of SHA, which is
941da177e4SLinus Torvalds  * not believed to be feasible, but there is a remote possibility.
951da177e4SLinus Torvalds  * Nonetheless, these numbers should be useful for the vast majority
961da177e4SLinus Torvalds  * of purposes.
971da177e4SLinus Torvalds  *
981da177e4SLinus Torvalds  * Exported interfaces ---- output
991da177e4SLinus Torvalds  * ===============================
1001da177e4SLinus Torvalds  *
1011da177e4SLinus Torvalds  * There are three exported interfaces; the first is one designed to
1021da177e4SLinus Torvalds  * be used from within the kernel:
1031da177e4SLinus Torvalds  *
1041da177e4SLinus Torvalds  * 	void get_random_bytes(void *buf, int nbytes);
1051da177e4SLinus Torvalds  *
1061da177e4SLinus Torvalds  * This interface will return the requested number of random bytes,
1071da177e4SLinus Torvalds  * and place it in the requested buffer.
1081da177e4SLinus Torvalds  *
1091da177e4SLinus Torvalds  * The two other interfaces are two character devices /dev/random and
1101da177e4SLinus Torvalds  * /dev/urandom.  /dev/random is suitable for use when very high
1111da177e4SLinus Torvalds  * quality randomness is desired (for example, for key generation or
1121da177e4SLinus Torvalds  * one-time pads), as it will only return a maximum of the number of
1131da177e4SLinus Torvalds  * bits of randomness (as estimated by the random number generator)
1141da177e4SLinus Torvalds  * contained in the entropy pool.
1151da177e4SLinus Torvalds  *
1161da177e4SLinus Torvalds  * The /dev/urandom device does not have this limit, and will return
1171da177e4SLinus Torvalds  * as many bytes as are requested.  As more and more random bytes are
1181da177e4SLinus Torvalds  * requested without giving time for the entropy pool to recharge,
1191da177e4SLinus Torvalds  * this will result in random numbers that are merely cryptographically
1201da177e4SLinus Torvalds  * strong.  For many applications, however, this is acceptable.
1211da177e4SLinus Torvalds  *
1221da177e4SLinus Torvalds  * Exported interfaces ---- input
1231da177e4SLinus Torvalds  * ==============================
1241da177e4SLinus Torvalds  *
1251da177e4SLinus Torvalds  * The current exported interfaces for gathering environmental noise
1261da177e4SLinus Torvalds  * from the devices are:
1271da177e4SLinus Torvalds  *
128a2080a67SLinus Torvalds  *	void add_device_randomness(const void *buf, unsigned int size);
1291da177e4SLinus Torvalds  * 	void add_input_randomness(unsigned int type, unsigned int code,
1301da177e4SLinus Torvalds  *                                unsigned int value);
131775f4b29STheodore Ts'o  *	void add_interrupt_randomness(int irq, int irq_flags);
132442a4fffSJarod Wilson  * 	void add_disk_randomness(struct gendisk *disk);
1331da177e4SLinus Torvalds  *
134a2080a67SLinus Torvalds  * add_device_randomness() is for adding data to the random pool that
135a2080a67SLinus Torvalds  * is likely to differ between two devices (or possibly even per boot).
136a2080a67SLinus Torvalds  * This would be things like MAC addresses or serial numbers, or the
137a2080a67SLinus Torvalds  * read-out of the RTC. This does *not* add any actual entropy to the
138a2080a67SLinus Torvalds  * pool, but it initializes the pool to different values for devices
139a2080a67SLinus Torvalds  * that might otherwise be identical and have very little entropy
140a2080a67SLinus Torvalds  * available to them (particularly common in the embedded world).
141a2080a67SLinus Torvalds  *
1421da177e4SLinus Torvalds  * add_input_randomness() uses the input layer interrupt timing, as well as
1431da177e4SLinus Torvalds  * the event type information from the hardware.
1441da177e4SLinus Torvalds  *
145775f4b29STheodore Ts'o  * add_interrupt_randomness() uses the interrupt timing as random
146775f4b29STheodore Ts'o  * inputs to the entropy pool. Using the cycle counters and the irq source
147775f4b29STheodore Ts'o  * as inputs, it feeds the randomness roughly once a second.
148442a4fffSJarod Wilson  *
149442a4fffSJarod Wilson  * add_disk_randomness() uses what amounts to the seek time of block
150442a4fffSJarod Wilson  * layer request events, on a per-disk_devt basis, as input to the
151442a4fffSJarod Wilson  * entropy pool. Note that high-speed solid state drives with very low
152442a4fffSJarod Wilson  * seek times do not make for good sources of entropy, as their seek
153442a4fffSJarod Wilson  * times are usually fairly consistent.
1541da177e4SLinus Torvalds  *
1551da177e4SLinus Torvalds  * All of these routines try to estimate how many bits of randomness a
1561da177e4SLinus Torvalds  * particular randomness source.  They do this by keeping track of the
1571da177e4SLinus Torvalds  * first and second order deltas of the event timings.
1581da177e4SLinus Torvalds  *
1591da177e4SLinus Torvalds  * Ensuring unpredictability at system startup
1601da177e4SLinus Torvalds  * ============================================
1611da177e4SLinus Torvalds  *
1621da177e4SLinus Torvalds  * When any operating system starts up, it will go through a sequence
1631da177e4SLinus Torvalds  * of actions that are fairly predictable by an adversary, especially
1641da177e4SLinus Torvalds  * if the start-up does not involve interaction with a human operator.
1651da177e4SLinus Torvalds  * This reduces the actual number of bits of unpredictability in the
1661da177e4SLinus Torvalds  * entropy pool below the value in entropy_count.  In order to
1671da177e4SLinus Torvalds  * counteract this effect, it helps to carry information in the
1681da177e4SLinus Torvalds  * entropy pool across shut-downs and start-ups.  To do this, put the
1691da177e4SLinus Torvalds  * following lines an appropriate script which is run during the boot
1701da177e4SLinus Torvalds  * sequence:
1711da177e4SLinus Torvalds  *
1721da177e4SLinus Torvalds  *	echo "Initializing random number generator..."
1731da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
1741da177e4SLinus Torvalds  *	# Carry a random seed from start-up to start-up
1751da177e4SLinus Torvalds  *	# Load and then save the whole entropy pool
1761da177e4SLinus Torvalds  *	if [ -f $random_seed ]; then
1771da177e4SLinus Torvalds  *		cat $random_seed >/dev/urandom
1781da177e4SLinus Torvalds  *	else
1791da177e4SLinus Torvalds  *		touch $random_seed
1801da177e4SLinus Torvalds  *	fi
1811da177e4SLinus Torvalds  *	chmod 600 $random_seed
1821da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
1831da177e4SLinus Torvalds  *
1841da177e4SLinus Torvalds  * and the following lines in an appropriate script which is run as
1851da177e4SLinus Torvalds  * the system is shutdown:
1861da177e4SLinus Torvalds  *
1871da177e4SLinus Torvalds  *	# Carry a random seed from shut-down to start-up
1881da177e4SLinus Torvalds  *	# Save the whole entropy pool
1891da177e4SLinus Torvalds  *	echo "Saving random seed..."
1901da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
1911da177e4SLinus Torvalds  *	touch $random_seed
1921da177e4SLinus Torvalds  *	chmod 600 $random_seed
1931da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
1941da177e4SLinus Torvalds  *
1951da177e4SLinus Torvalds  * For example, on most modern systems using the System V init
1961da177e4SLinus Torvalds  * scripts, such code fragments would be found in
1971da177e4SLinus Torvalds  * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
1981da177e4SLinus Torvalds  * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
1991da177e4SLinus Torvalds  *
2001da177e4SLinus Torvalds  * Effectively, these commands cause the contents of the entropy pool
2011da177e4SLinus Torvalds  * to be saved at shut-down time and reloaded into the entropy pool at
2021da177e4SLinus Torvalds  * start-up.  (The 'dd' in the addition to the bootup script is to
2031da177e4SLinus Torvalds  * make sure that /etc/random-seed is different for every start-up,
2041da177e4SLinus Torvalds  * even if the system crashes without executing rc.0.)  Even with
2051da177e4SLinus Torvalds  * complete knowledge of the start-up activities, predicting the state
2061da177e4SLinus Torvalds  * of the entropy pool requires knowledge of the previous history of
2071da177e4SLinus Torvalds  * the system.
2081da177e4SLinus Torvalds  *
2091da177e4SLinus Torvalds  * Configuring the /dev/random driver under Linux
2101da177e4SLinus Torvalds  * ==============================================
2111da177e4SLinus Torvalds  *
2121da177e4SLinus Torvalds  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
2131da177e4SLinus Torvalds  * the /dev/mem major number (#1).  So if your system does not have
2141da177e4SLinus Torvalds  * /dev/random and /dev/urandom created already, they can be created
2151da177e4SLinus Torvalds  * by using the commands:
2161da177e4SLinus Torvalds  *
2171da177e4SLinus Torvalds  * 	mknod /dev/random c 1 8
2181da177e4SLinus Torvalds  * 	mknod /dev/urandom c 1 9
2191da177e4SLinus Torvalds  *
2201da177e4SLinus Torvalds  * Acknowledgements:
2211da177e4SLinus Torvalds  * =================
2221da177e4SLinus Torvalds  *
2231da177e4SLinus Torvalds  * Ideas for constructing this random number generator were derived
2241da177e4SLinus Torvalds  * from Pretty Good Privacy's random number generator, and from private
2251da177e4SLinus Torvalds  * discussions with Phil Karn.  Colin Plumb provided a faster random
2261da177e4SLinus Torvalds  * number generator, which speed up the mixing function of the entropy
2271da177e4SLinus Torvalds  * pool, taken from PGPfone.  Dale Worley has also contributed many
2281da177e4SLinus Torvalds  * useful ideas and suggestions to improve this driver.
2291da177e4SLinus Torvalds  *
2301da177e4SLinus Torvalds  * Any flaws in the design are solely my responsibility, and should
2311da177e4SLinus Torvalds  * not be attributed to the Phil, Colin, or any of authors of PGP.
2321da177e4SLinus Torvalds  *
2331da177e4SLinus Torvalds  * Further background information on this topic may be obtained from
2341da177e4SLinus Torvalds  * RFC 1750, "Randomness Recommendations for Security", by Donald
2351da177e4SLinus Torvalds  * Eastlake, Steve Crocker, and Jeff Schiller.
2361da177e4SLinus Torvalds  */
2371da177e4SLinus Torvalds 
2381da177e4SLinus Torvalds #include <linux/utsname.h>
2391da177e4SLinus Torvalds #include <linux/module.h>
2401da177e4SLinus Torvalds #include <linux/kernel.h>
2411da177e4SLinus Torvalds #include <linux/major.h>
2421da177e4SLinus Torvalds #include <linux/string.h>
2431da177e4SLinus Torvalds #include <linux/fcntl.h>
2441da177e4SLinus Torvalds #include <linux/slab.h>
2451da177e4SLinus Torvalds #include <linux/random.h>
2461da177e4SLinus Torvalds #include <linux/poll.h>
2471da177e4SLinus Torvalds #include <linux/init.h>
2481da177e4SLinus Torvalds #include <linux/fs.h>
2491da177e4SLinus Torvalds #include <linux/genhd.h>
2501da177e4SLinus Torvalds #include <linux/interrupt.h>
25127ac792cSAndrea Righi #include <linux/mm.h>
2521da177e4SLinus Torvalds #include <linux/spinlock.h>
253c84dbf61STorsten Duwe #include <linux/kthread.h>
2541da177e4SLinus Torvalds #include <linux/percpu.h>
2551da177e4SLinus Torvalds #include <linux/cryptohash.h>
2565b739ef8SNeil Horman #include <linux/fips.h>
257775f4b29STheodore Ts'o #include <linux/ptrace.h>
258e6d4947bSTheodore Ts'o #include <linux/kmemcheck.h>
2596265e169STheodore Ts'o #include <linux/workqueue.h>
260d178a1ebSYinghai Lu #include <linux/irq.h>
261c6e9d6f3STheodore Ts'o #include <linux/syscalls.h>
262c6e9d6f3STheodore Ts'o #include <linux/completion.h>
263d178a1ebSYinghai Lu 
2641da177e4SLinus Torvalds #include <asm/processor.h>
2651da177e4SLinus Torvalds #include <asm/uaccess.h>
2661da177e4SLinus Torvalds #include <asm/irq.h>
267775f4b29STheodore Ts'o #include <asm/irq_regs.h>
2681da177e4SLinus Torvalds #include <asm/io.h>
2691da177e4SLinus Torvalds 
27000ce1db1STheodore Ts'o #define CREATE_TRACE_POINTS
27100ce1db1STheodore Ts'o #include <trace/events/random.h>
27200ce1db1STheodore Ts'o 
27343759d4fSTheodore Ts'o /* #define ADD_INTERRUPT_BENCH */
27443759d4fSTheodore Ts'o 
2751da177e4SLinus Torvalds /*
2761da177e4SLinus Torvalds  * Configuration information
2771da177e4SLinus Torvalds  */
27830e37ec5SH. Peter Anvin #define INPUT_POOL_SHIFT	12
27930e37ec5SH. Peter Anvin #define INPUT_POOL_WORDS	(1 << (INPUT_POOL_SHIFT-5))
28030e37ec5SH. Peter Anvin #define OUTPUT_POOL_SHIFT	10
28130e37ec5SH. Peter Anvin #define OUTPUT_POOL_WORDS	(1 << (OUTPUT_POOL_SHIFT-5))
2821da177e4SLinus Torvalds #define SEC_XFER_SIZE		512
283e954bc91SMatt Mackall #define EXTRACT_SIZE		10
2841da177e4SLinus Torvalds 
285392a546dSTheodore Ts'o #define DEBUG_RANDOM_BOOT 0
286392a546dSTheodore Ts'o 
287d2e7c96aSH. Peter Anvin #define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
288d2e7c96aSH. Peter Anvin 
2891da177e4SLinus Torvalds /*
29095b709b6STheodore Ts'o  * To allow fractional bits to be tracked, the entropy_count field is
29195b709b6STheodore Ts'o  * denominated in units of 1/8th bits.
29230e37ec5SH. Peter Anvin  *
29330e37ec5SH. Peter Anvin  * 2*(ENTROPY_SHIFT + log2(poolbits)) must <= 31, or the multiply in
29430e37ec5SH. Peter Anvin  * credit_entropy_bits() needs to be 64 bits wide.
295a283b5c4SH. Peter Anvin  */
296a283b5c4SH. Peter Anvin #define ENTROPY_SHIFT 3
297a283b5c4SH. Peter Anvin #define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
298a283b5c4SH. Peter Anvin 
299a283b5c4SH. Peter Anvin /*
3001da177e4SLinus Torvalds  * The minimum number of bits of entropy before we wake up a read on
3011da177e4SLinus Torvalds  * /dev/random.  Should be enough to do a significant reseed.
3021da177e4SLinus Torvalds  */
3032132a96fSGreg Price static int random_read_wakeup_bits = 64;
3041da177e4SLinus Torvalds 
3051da177e4SLinus Torvalds /*
3061da177e4SLinus Torvalds  * If the entropy count falls under this number of bits, then we
3071da177e4SLinus Torvalds  * should wake up processes which are selecting or polling on write
3081da177e4SLinus Torvalds  * access to /dev/random.
3091da177e4SLinus Torvalds  */
3102132a96fSGreg Price static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
3111da177e4SLinus Torvalds 
3121da177e4SLinus Torvalds /*
313dfd38750SGreg Price  * The minimum number of seconds between urandom pool reseeding.  We
314f5c2742cSTheodore Ts'o  * do this to limit the amount of entropy that can be drained from the
315f5c2742cSTheodore Ts'o  * input pool even if there are heavy demands on /dev/urandom.
3161da177e4SLinus Torvalds  */
317f5c2742cSTheodore Ts'o static int random_min_urandom_seed = 60;
3181da177e4SLinus Torvalds 
3191da177e4SLinus Torvalds /*
3206e9fa2c8STheodore Ts'o  * Originally, we used a primitive polynomial of degree .poolwords
3216e9fa2c8STheodore Ts'o  * over GF(2).  The taps for various sizes are defined below.  They
3226e9fa2c8STheodore Ts'o  * were chosen to be evenly spaced except for the last tap, which is 1
3236e9fa2c8STheodore Ts'o  * to get the twisting happening as fast as possible.
3241da177e4SLinus Torvalds  *
3256e9fa2c8STheodore Ts'o  * For the purposes of better mixing, we use the CRC-32 polynomial as
3266e9fa2c8STheodore Ts'o  * well to make a (modified) twisted Generalized Feedback Shift
3276e9fa2c8STheodore Ts'o  * Register.  (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR
3286e9fa2c8STheodore Ts'o  * generators.  ACM Transactions on Modeling and Computer Simulation
3296e9fa2c8STheodore Ts'o  * 2(3):179-194.  Also see M. Matsumoto & Y. Kurita, 1994.  Twisted
330dfd38750SGreg Price  * GFSR generators II.  ACM Transactions on Modeling and Computer
3316e9fa2c8STheodore Ts'o  * Simulation 4:254-266)
3321da177e4SLinus Torvalds  *
3331da177e4SLinus Torvalds  * Thanks to Colin Plumb for suggesting this.
3341da177e4SLinus Torvalds  *
3356e9fa2c8STheodore Ts'o  * The mixing operation is much less sensitive than the output hash,
3366e9fa2c8STheodore Ts'o  * where we use SHA-1.  All that we want of mixing operation is that
3376e9fa2c8STheodore Ts'o  * it be a good non-cryptographic hash; i.e. it not produce collisions
3386e9fa2c8STheodore Ts'o  * when fed "random" data of the sort we expect to see.  As long as
3396e9fa2c8STheodore Ts'o  * the pool state differs for different inputs, we have preserved the
3406e9fa2c8STheodore Ts'o  * input entropy and done a good job.  The fact that an intelligent
3416e9fa2c8STheodore Ts'o  * attacker can construct inputs that will produce controlled
3426e9fa2c8STheodore Ts'o  * alterations to the pool's state is not important because we don't
3436e9fa2c8STheodore Ts'o  * consider such inputs to contribute any randomness.  The only
3446e9fa2c8STheodore Ts'o  * property we need with respect to them is that the attacker can't
3456e9fa2c8STheodore Ts'o  * increase his/her knowledge of the pool's state.  Since all
3466e9fa2c8STheodore Ts'o  * additions are reversible (knowing the final state and the input,
3476e9fa2c8STheodore Ts'o  * you can reconstruct the initial state), if an attacker has any
3486e9fa2c8STheodore Ts'o  * uncertainty about the initial state, he/she can only shuffle that
3496e9fa2c8STheodore Ts'o  * uncertainty about, but never cause any collisions (which would
3501da177e4SLinus Torvalds  * decrease the uncertainty).
3511da177e4SLinus Torvalds  *
3526e9fa2c8STheodore Ts'o  * Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
3536e9fa2c8STheodore Ts'o  * Videau in their paper, "The Linux Pseudorandom Number Generator
3546e9fa2c8STheodore Ts'o  * Revisited" (see: http://eprint.iacr.org/2012/251.pdf).  In their
3556e9fa2c8STheodore Ts'o  * paper, they point out that we are not using a true Twisted GFSR,
3566e9fa2c8STheodore Ts'o  * since Matsumoto & Kurita used a trinomial feedback polynomial (that
3576e9fa2c8STheodore Ts'o  * is, with only three taps, instead of the six that we are using).
3586e9fa2c8STheodore Ts'o  * As a result, the resulting polynomial is neither primitive nor
3596e9fa2c8STheodore Ts'o  * irreducible, and hence does not have a maximal period over
3606e9fa2c8STheodore Ts'o  * GF(2**32).  They suggest a slight change to the generator
3616e9fa2c8STheodore Ts'o  * polynomial which improves the resulting TGFSR polynomial to be
3626e9fa2c8STheodore Ts'o  * irreducible, which we have made here.
3631da177e4SLinus Torvalds  */
3641da177e4SLinus Torvalds static struct poolinfo {
365a283b5c4SH. Peter Anvin 	int poolbitshift, poolwords, poolbytes, poolbits, poolfracbits;
366a283b5c4SH. Peter Anvin #define S(x) ilog2(x)+5, (x), (x)*4, (x)*32, (x) << (ENTROPY_SHIFT+5)
3671da177e4SLinus Torvalds 	int tap1, tap2, tap3, tap4, tap5;
3681da177e4SLinus Torvalds } poolinfo_table[] = {
3696e9fa2c8STheodore Ts'o 	/* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
3706e9fa2c8STheodore Ts'o 	/* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
3716e9fa2c8STheodore Ts'o 	{ S(128),	104,	76,	51,	25,	1 },
3726e9fa2c8STheodore Ts'o 	/* was: x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 */
3736e9fa2c8STheodore Ts'o 	/* x^32 + x^26 + x^19 + x^14 + x^7 + x + 1 */
3746e9fa2c8STheodore Ts'o 	{ S(32),	26,	19,	14,	7,	1 },
3751da177e4SLinus Torvalds #if 0
3761da177e4SLinus Torvalds 	/* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
3779ed17b70SH. Peter Anvin 	{ S(2048),	1638,	1231,	819,	411,	1 },
3781da177e4SLinus Torvalds 
3791da177e4SLinus Torvalds 	/* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
3809ed17b70SH. Peter Anvin 	{ S(1024),	817,	615,	412,	204,	1 },
3811da177e4SLinus Torvalds 
3821da177e4SLinus Torvalds 	/* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
3839ed17b70SH. Peter Anvin 	{ S(1024),	819,	616,	410,	207,	2 },
3841da177e4SLinus Torvalds 
3851da177e4SLinus Torvalds 	/* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
3869ed17b70SH. Peter Anvin 	{ S(512),	411,	308,	208,	104,	1 },
3871da177e4SLinus Torvalds 
3881da177e4SLinus Torvalds 	/* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
3899ed17b70SH. Peter Anvin 	{ S(512),	409,	307,	206,	102,	2 },
3901da177e4SLinus Torvalds 	/* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
3919ed17b70SH. Peter Anvin 	{ S(512),	409,	309,	205,	103,	2 },
3921da177e4SLinus Torvalds 
3931da177e4SLinus Torvalds 	/* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
3949ed17b70SH. Peter Anvin 	{ S(256),	205,	155,	101,	52,	1 },
3951da177e4SLinus Torvalds 
3961da177e4SLinus Torvalds 	/* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
3979ed17b70SH. Peter Anvin 	{ S(128),	103,	78,	51,	27,	2 },
3981da177e4SLinus Torvalds 
3991da177e4SLinus Torvalds 	/* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
4009ed17b70SH. Peter Anvin 	{ S(64),	52,	39,	26,	14,	1 },
4011da177e4SLinus Torvalds #endif
4021da177e4SLinus Torvalds };
4031da177e4SLinus Torvalds 
4041da177e4SLinus Torvalds /*
4051da177e4SLinus Torvalds  * Static global variables
4061da177e4SLinus Torvalds  */
4071da177e4SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
4081da177e4SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
409c6e9d6f3STheodore Ts'o static DECLARE_WAIT_QUEUE_HEAD(urandom_init_wait);
4109a6f70bbSJeff Dike static struct fasync_struct *fasync;
4111da177e4SLinus Torvalds 
4121da177e4SLinus Torvalds /**********************************************************************
4131da177e4SLinus Torvalds  *
4141da177e4SLinus Torvalds  * OS independent entropy store.   Here are the functions which handle
4151da177e4SLinus Torvalds  * storing entropy in an entropy pool.
4161da177e4SLinus Torvalds  *
4171da177e4SLinus Torvalds  **********************************************************************/
4181da177e4SLinus Torvalds 
4191da177e4SLinus Torvalds struct entropy_store;
4201da177e4SLinus Torvalds struct entropy_store {
42143358209SMatt Mackall 	/* read-only data: */
42230e37ec5SH. Peter Anvin 	const struct poolinfo *poolinfo;
4231da177e4SLinus Torvalds 	__u32 *pool;
4241da177e4SLinus Torvalds 	const char *name;
4251da177e4SLinus Torvalds 	struct entropy_store *pull;
4266265e169STheodore Ts'o 	struct work_struct push_work;
4271da177e4SLinus Torvalds 
4281da177e4SLinus Torvalds 	/* read-write data: */
429f5c2742cSTheodore Ts'o 	unsigned long last_pulled;
43043358209SMatt Mackall 	spinlock_t lock;
431c59974aeSTheodore Ts'o 	unsigned short add_ptr;
432c59974aeSTheodore Ts'o 	unsigned short input_rotate;
433cda796a3SMatt Mackall 	int entropy_count;
434775f4b29STheodore Ts'o 	int entropy_total;
435775f4b29STheodore Ts'o 	unsigned int initialized:1;
436c59974aeSTheodore Ts'o 	unsigned int limit:1;
437c59974aeSTheodore Ts'o 	unsigned int last_data_init:1;
438e954bc91SMatt Mackall 	__u8 last_data[EXTRACT_SIZE];
4391da177e4SLinus Torvalds };
4401da177e4SLinus Torvalds 
4416265e169STheodore Ts'o static void push_to_pool(struct work_struct *work);
4421da177e4SLinus Torvalds static __u32 input_pool_data[INPUT_POOL_WORDS];
4431da177e4SLinus Torvalds static __u32 blocking_pool_data[OUTPUT_POOL_WORDS];
4441da177e4SLinus Torvalds static __u32 nonblocking_pool_data[OUTPUT_POOL_WORDS];
4451da177e4SLinus Torvalds 
4461da177e4SLinus Torvalds static struct entropy_store input_pool = {
4471da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[0],
4481da177e4SLinus Torvalds 	.name = "input",
4491da177e4SLinus Torvalds 	.limit = 1,
450eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
4511da177e4SLinus Torvalds 	.pool = input_pool_data
4521da177e4SLinus Torvalds };
4531da177e4SLinus Torvalds 
4541da177e4SLinus Torvalds static struct entropy_store blocking_pool = {
4551da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[1],
4561da177e4SLinus Torvalds 	.name = "blocking",
4571da177e4SLinus Torvalds 	.limit = 1,
4581da177e4SLinus Torvalds 	.pull = &input_pool,
459eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(blocking_pool.lock),
4606265e169STheodore Ts'o 	.pool = blocking_pool_data,
4616265e169STheodore Ts'o 	.push_work = __WORK_INITIALIZER(blocking_pool.push_work,
4626265e169STheodore Ts'o 					push_to_pool),
4631da177e4SLinus Torvalds };
4641da177e4SLinus Torvalds 
4651da177e4SLinus Torvalds static struct entropy_store nonblocking_pool = {
4661da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[1],
4671da177e4SLinus Torvalds 	.name = "nonblocking",
4681da177e4SLinus Torvalds 	.pull = &input_pool,
469eece09ecSThomas Gleixner 	.lock = __SPIN_LOCK_UNLOCKED(nonblocking_pool.lock),
4706265e169STheodore Ts'o 	.pool = nonblocking_pool_data,
4716265e169STheodore Ts'o 	.push_work = __WORK_INITIALIZER(nonblocking_pool.push_work,
4726265e169STheodore Ts'o 					push_to_pool),
4731da177e4SLinus Torvalds };
4741da177e4SLinus Torvalds 
475775f4b29STheodore Ts'o static __u32 const twist_table[8] = {
476775f4b29STheodore Ts'o 	0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
477775f4b29STheodore Ts'o 	0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
478775f4b29STheodore Ts'o 
4791da177e4SLinus Torvalds /*
480e68e5b66SMatt Mackall  * This function adds bytes into the entropy "pool".  It does not
4811da177e4SLinus Torvalds  * update the entropy estimate.  The caller should call
482adc782daSMatt Mackall  * credit_entropy_bits if this is appropriate.
4831da177e4SLinus Torvalds  *
4841da177e4SLinus Torvalds  * The pool is stirred with a primitive polynomial of the appropriate
4851da177e4SLinus Torvalds  * degree, and then twisted.  We twist by three bits at a time because
4861da177e4SLinus Torvalds  * it's cheap to do so and helps slightly in the expected case where
4871da177e4SLinus Torvalds  * the entropy is concentrated in the low-order bits.
4881da177e4SLinus Torvalds  */
48900ce1db1STheodore Ts'o static void _mix_pool_bytes(struct entropy_store *r, const void *in,
49085608f8eSTheodore Ts'o 			    int nbytes)
4911da177e4SLinus Torvalds {
49285608f8eSTheodore Ts'o 	unsigned long i, tap1, tap2, tap3, tap4, tap5;
493feee7697SMatt Mackall 	int input_rotate;
4941da177e4SLinus Torvalds 	int wordmask = r->poolinfo->poolwords - 1;
495e68e5b66SMatt Mackall 	const char *bytes = in;
4966d38b827SMatt Mackall 	__u32 w;
4971da177e4SLinus Torvalds 
4981da177e4SLinus Torvalds 	tap1 = r->poolinfo->tap1;
4991da177e4SLinus Torvalds 	tap2 = r->poolinfo->tap2;
5001da177e4SLinus Torvalds 	tap3 = r->poolinfo->tap3;
5011da177e4SLinus Torvalds 	tap4 = r->poolinfo->tap4;
5021da177e4SLinus Torvalds 	tap5 = r->poolinfo->tap5;
5031da177e4SLinus Torvalds 
50491fcb532STheodore Ts'o 	input_rotate = r->input_rotate;
50591fcb532STheodore Ts'o 	i = r->add_ptr;
5061da177e4SLinus Torvalds 
507e68e5b66SMatt Mackall 	/* mix one byte at a time to simplify size handling and churn faster */
508e68e5b66SMatt Mackall 	while (nbytes--) {
509c59974aeSTheodore Ts'o 		w = rol32(*bytes++, input_rotate);
510993ba211SMatt Mackall 		i = (i - 1) & wordmask;
5111da177e4SLinus Torvalds 
5121da177e4SLinus Torvalds 		/* XOR in the various taps */
513993ba211SMatt Mackall 		w ^= r->pool[i];
5141da177e4SLinus Torvalds 		w ^= r->pool[(i + tap1) & wordmask];
5151da177e4SLinus Torvalds 		w ^= r->pool[(i + tap2) & wordmask];
5161da177e4SLinus Torvalds 		w ^= r->pool[(i + tap3) & wordmask];
5171da177e4SLinus Torvalds 		w ^= r->pool[(i + tap4) & wordmask];
5181da177e4SLinus Torvalds 		w ^= r->pool[(i + tap5) & wordmask];
519993ba211SMatt Mackall 
520993ba211SMatt Mackall 		/* Mix the result back in with a twist */
5211da177e4SLinus Torvalds 		r->pool[i] = (w >> 3) ^ twist_table[w & 7];
522feee7697SMatt Mackall 
523feee7697SMatt Mackall 		/*
524feee7697SMatt Mackall 		 * Normally, we add 7 bits of rotation to the pool.
525feee7697SMatt Mackall 		 * At the beginning of the pool, add an extra 7 bits
526feee7697SMatt Mackall 		 * rotation, so that successive passes spread the
527feee7697SMatt Mackall 		 * input bits across the pool evenly.
528feee7697SMatt Mackall 		 */
529c59974aeSTheodore Ts'o 		input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
5301da177e4SLinus Torvalds 	}
5311da177e4SLinus Torvalds 
53291fcb532STheodore Ts'o 	r->input_rotate = input_rotate;
53391fcb532STheodore Ts'o 	r->add_ptr = i;
5341da177e4SLinus Torvalds }
5351da177e4SLinus Torvalds 
53600ce1db1STheodore Ts'o static void __mix_pool_bytes(struct entropy_store *r, const void *in,
53785608f8eSTheodore Ts'o 			     int nbytes)
53800ce1db1STheodore Ts'o {
53900ce1db1STheodore Ts'o 	trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
54085608f8eSTheodore Ts'o 	_mix_pool_bytes(r, in, nbytes);
54100ce1db1STheodore Ts'o }
54200ce1db1STheodore Ts'o 
543902c098aSTheodore Ts'o static void mix_pool_bytes(struct entropy_store *r, const void *in,
54485608f8eSTheodore Ts'o 			   int nbytes)
5451da177e4SLinus Torvalds {
546902c098aSTheodore Ts'o 	unsigned long flags;
547902c098aSTheodore Ts'o 
54800ce1db1STheodore Ts'o 	trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
549902c098aSTheodore Ts'o 	spin_lock_irqsave(&r->lock, flags);
55085608f8eSTheodore Ts'o 	_mix_pool_bytes(r, in, nbytes);
551902c098aSTheodore Ts'o 	spin_unlock_irqrestore(&r->lock, flags);
5521da177e4SLinus Torvalds }
5531da177e4SLinus Torvalds 
554775f4b29STheodore Ts'o struct fast_pool {
555775f4b29STheodore Ts'o 	__u32		pool[4];
556775f4b29STheodore Ts'o 	unsigned long	last;
557ee3e00e9STheodore Ts'o 	unsigned short	reg_idx;
558840f9507STheodore Ts'o 	unsigned char	count;
559775f4b29STheodore Ts'o };
560775f4b29STheodore Ts'o 
561775f4b29STheodore Ts'o /*
562775f4b29STheodore Ts'o  * This is a fast mixing routine used by the interrupt randomness
563775f4b29STheodore Ts'o  * collector.  It's hardcoded for an 128 bit pool and assumes that any
564775f4b29STheodore Ts'o  * locks that might be needed are taken by the caller.
565775f4b29STheodore Ts'o  */
56643759d4fSTheodore Ts'o static void fast_mix(struct fast_pool *f)
567775f4b29STheodore Ts'o {
56843759d4fSTheodore Ts'o 	__u32 a = f->pool[0],	b = f->pool[1];
56943759d4fSTheodore Ts'o 	__u32 c = f->pool[2],	d = f->pool[3];
570775f4b29STheodore Ts'o 
57143759d4fSTheodore Ts'o 	a += b;			c += d;
57243759d4fSTheodore Ts'o 	b = rol32(a, 6);	d = rol32(c, 27);
57343759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
574655b2264STheodore Ts'o 
57543759d4fSTheodore Ts'o 	a += b;			c += d;
57643759d4fSTheodore Ts'o 	b = rol32(a, 16);	d = rol32(c, 14);
57743759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
57843759d4fSTheodore Ts'o 
57943759d4fSTheodore Ts'o 	a += b;			c += d;
58043759d4fSTheodore Ts'o 	b = rol32(a, 6);	d = rol32(c, 27);
58143759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
58243759d4fSTheodore Ts'o 
58343759d4fSTheodore Ts'o 	a += b;			c += d;
58443759d4fSTheodore Ts'o 	b = rol32(a, 16);	d = rol32(c, 14);
58543759d4fSTheodore Ts'o 	d ^= a;			b ^= c;
58643759d4fSTheodore Ts'o 
58743759d4fSTheodore Ts'o 	f->pool[0] = a;  f->pool[1] = b;
58843759d4fSTheodore Ts'o 	f->pool[2] = c;  f->pool[3] = d;
589655b2264STheodore Ts'o 	f->count++;
590775f4b29STheodore Ts'o }
591775f4b29STheodore Ts'o 
5921da177e4SLinus Torvalds /*
593a283b5c4SH. Peter Anvin  * Credit (or debit) the entropy store with n bits of entropy.
594a283b5c4SH. Peter Anvin  * Use credit_entropy_bits_safe() if the value comes from userspace
595a283b5c4SH. Peter Anvin  * or otherwise should be checked for extreme values.
5961da177e4SLinus Torvalds  */
597adc782daSMatt Mackall static void credit_entropy_bits(struct entropy_store *r, int nbits)
5981da177e4SLinus Torvalds {
599902c098aSTheodore Ts'o 	int entropy_count, orig;
60030e37ec5SH. Peter Anvin 	const int pool_size = r->poolinfo->poolfracbits;
60130e37ec5SH. Peter Anvin 	int nfrac = nbits << ENTROPY_SHIFT;
6021da177e4SLinus Torvalds 
603adc782daSMatt Mackall 	if (!nbits)
604adc782daSMatt Mackall 		return;
605adc782daSMatt Mackall 
606902c098aSTheodore Ts'o retry:
607902c098aSTheodore Ts'o 	entropy_count = orig = ACCESS_ONCE(r->entropy_count);
60830e37ec5SH. Peter Anvin 	if (nfrac < 0) {
60930e37ec5SH. Peter Anvin 		/* Debit */
61030e37ec5SH. Peter Anvin 		entropy_count += nfrac;
61130e37ec5SH. Peter Anvin 	} else {
61230e37ec5SH. Peter Anvin 		/*
61330e37ec5SH. Peter Anvin 		 * Credit: we have to account for the possibility of
61430e37ec5SH. Peter Anvin 		 * overwriting already present entropy.	 Even in the
61530e37ec5SH. Peter Anvin 		 * ideal case of pure Shannon entropy, new contributions
61630e37ec5SH. Peter Anvin 		 * approach the full value asymptotically:
61730e37ec5SH. Peter Anvin 		 *
61830e37ec5SH. Peter Anvin 		 * entropy <- entropy + (pool_size - entropy) *
61930e37ec5SH. Peter Anvin 		 *	(1 - exp(-add_entropy/pool_size))
62030e37ec5SH. Peter Anvin 		 *
62130e37ec5SH. Peter Anvin 		 * For add_entropy <= pool_size/2 then
62230e37ec5SH. Peter Anvin 		 * (1 - exp(-add_entropy/pool_size)) >=
62330e37ec5SH. Peter Anvin 		 *    (add_entropy/pool_size)*0.7869...
62430e37ec5SH. Peter Anvin 		 * so we can approximate the exponential with
62530e37ec5SH. Peter Anvin 		 * 3/4*add_entropy/pool_size and still be on the
62630e37ec5SH. Peter Anvin 		 * safe side by adding at most pool_size/2 at a time.
62730e37ec5SH. Peter Anvin 		 *
62830e37ec5SH. Peter Anvin 		 * The use of pool_size-2 in the while statement is to
62930e37ec5SH. Peter Anvin 		 * prevent rounding artifacts from making the loop
63030e37ec5SH. Peter Anvin 		 * arbitrarily long; this limits the loop to log2(pool_size)*2
63130e37ec5SH. Peter Anvin 		 * turns no matter how large nbits is.
63230e37ec5SH. Peter Anvin 		 */
63330e37ec5SH. Peter Anvin 		int pnfrac = nfrac;
63430e37ec5SH. Peter Anvin 		const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
63530e37ec5SH. Peter Anvin 		/* The +2 corresponds to the /4 in the denominator */
63630e37ec5SH. Peter Anvin 
63730e37ec5SH. Peter Anvin 		do {
63830e37ec5SH. Peter Anvin 			unsigned int anfrac = min(pnfrac, pool_size/2);
63930e37ec5SH. Peter Anvin 			unsigned int add =
64030e37ec5SH. Peter Anvin 				((pool_size - entropy_count)*anfrac*3) >> s;
64130e37ec5SH. Peter Anvin 
64230e37ec5SH. Peter Anvin 			entropy_count += add;
64330e37ec5SH. Peter Anvin 			pnfrac -= anfrac;
64430e37ec5SH. Peter Anvin 		} while (unlikely(entropy_count < pool_size-2 && pnfrac));
64530e37ec5SH. Peter Anvin 	}
64600ce1db1STheodore Ts'o 
64779a84687SHannes Frederic Sowa 	if (unlikely(entropy_count < 0)) {
648f80bbd8bSTheodore Ts'o 		pr_warn("random: negative entropy/overflow: pool %s count %d\n",
649f80bbd8bSTheodore Ts'o 			r->name, entropy_count);
650f80bbd8bSTheodore Ts'o 		WARN_ON(1);
6518b76f46aSAndrew Morton 		entropy_count = 0;
65230e37ec5SH. Peter Anvin 	} else if (entropy_count > pool_size)
65330e37ec5SH. Peter Anvin 		entropy_count = pool_size;
654902c098aSTheodore Ts'o 	if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
655902c098aSTheodore Ts'o 		goto retry;
6561da177e4SLinus Torvalds 
657775f4b29STheodore Ts'o 	r->entropy_total += nbits;
6580891ad82SLinus Torvalds 	if (!r->initialized && r->entropy_total > 128) {
659775f4b29STheodore Ts'o 		r->initialized = 1;
6606265e169STheodore Ts'o 		r->entropy_total = 0;
6610891ad82SLinus Torvalds 		if (r == &nonblocking_pool) {
6624af712e8SHannes Frederic Sowa 			prandom_reseed_late();
663c6e9d6f3STheodore Ts'o 			wake_up_interruptible(&urandom_init_wait);
6640891ad82SLinus Torvalds 			pr_notice("random: %s pool is initialized\n", r->name);
6654af712e8SHannes Frederic Sowa 		}
666775f4b29STheodore Ts'o 	}
667775f4b29STheodore Ts'o 
668a283b5c4SH. Peter Anvin 	trace_credit_entropy_bits(r->name, nbits,
669a283b5c4SH. Peter Anvin 				  entropy_count >> ENTROPY_SHIFT,
67000ce1db1STheodore Ts'o 				  r->entropy_total, _RET_IP_);
67100ce1db1STheodore Ts'o 
6726265e169STheodore Ts'o 	if (r == &input_pool) {
6737d1b08c4SGreg Price 		int entropy_bits = entropy_count >> ENTROPY_SHIFT;
6746265e169STheodore Ts'o 
67588c730daSMatt Mackall 		/* should we wake readers? */
6762132a96fSGreg Price 		if (entropy_bits >= random_read_wakeup_bits) {
67788c730daSMatt Mackall 			wake_up_interruptible(&random_read_wait);
6789a6f70bbSJeff Dike 			kill_fasync(&fasync, SIGIO, POLL_IN);
6799a6f70bbSJeff Dike 		}
6806265e169STheodore Ts'o 		/* If the input pool is getting full, send some
6816265e169STheodore Ts'o 		 * entropy to the two output pools, flipping back and
6826265e169STheodore Ts'o 		 * forth between them, until the output pools are 75%
6836265e169STheodore Ts'o 		 * full.
6846265e169STheodore Ts'o 		 */
6852132a96fSGreg Price 		if (entropy_bits > random_write_wakeup_bits &&
6866265e169STheodore Ts'o 		    r->initialized &&
6872132a96fSGreg Price 		    r->entropy_total >= 2*random_read_wakeup_bits) {
6886265e169STheodore Ts'o 			static struct entropy_store *last = &blocking_pool;
6896265e169STheodore Ts'o 			struct entropy_store *other = &blocking_pool;
6906265e169STheodore Ts'o 
6916265e169STheodore Ts'o 			if (last == &blocking_pool)
6926265e169STheodore Ts'o 				other = &nonblocking_pool;
6936265e169STheodore Ts'o 			if (other->entropy_count <=
6946265e169STheodore Ts'o 			    3 * other->poolinfo->poolfracbits / 4)
6956265e169STheodore Ts'o 				last = other;
6966265e169STheodore Ts'o 			if (last->entropy_count <=
6976265e169STheodore Ts'o 			    3 * last->poolinfo->poolfracbits / 4) {
6986265e169STheodore Ts'o 				schedule_work(&last->push_work);
6996265e169STheodore Ts'o 				r->entropy_total = 0;
7006265e169STheodore Ts'o 			}
7016265e169STheodore Ts'o 		}
7026265e169STheodore Ts'o 	}
7031da177e4SLinus Torvalds }
7041da177e4SLinus Torvalds 
705a283b5c4SH. Peter Anvin static void credit_entropy_bits_safe(struct entropy_store *r, int nbits)
706a283b5c4SH. Peter Anvin {
707a283b5c4SH. Peter Anvin 	const int nbits_max = (int)(~0U >> (ENTROPY_SHIFT + 1));
708a283b5c4SH. Peter Anvin 
709a283b5c4SH. Peter Anvin 	/* Cap the value to avoid overflows */
710a283b5c4SH. Peter Anvin 	nbits = min(nbits,  nbits_max);
711a283b5c4SH. Peter Anvin 	nbits = max(nbits, -nbits_max);
712a283b5c4SH. Peter Anvin 
713a283b5c4SH. Peter Anvin 	credit_entropy_bits(r, nbits);
7141da177e4SLinus Torvalds }
7151da177e4SLinus Torvalds 
7161da177e4SLinus Torvalds /*********************************************************************
7171da177e4SLinus Torvalds  *
7181da177e4SLinus Torvalds  * Entropy input management
7191da177e4SLinus Torvalds  *
7201da177e4SLinus Torvalds  *********************************************************************/
7211da177e4SLinus Torvalds 
7221da177e4SLinus Torvalds /* There is one of these per entropy source */
7231da177e4SLinus Torvalds struct timer_rand_state {
7241da177e4SLinus Torvalds 	cycles_t last_time;
7251da177e4SLinus Torvalds 	long last_delta, last_delta2;
7261da177e4SLinus Torvalds 	unsigned dont_count_entropy:1;
7271da177e4SLinus Torvalds };
7281da177e4SLinus Torvalds 
729644008dfSTheodore Ts'o #define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
730644008dfSTheodore Ts'o 
731a2080a67SLinus Torvalds /*
732a2080a67SLinus Torvalds  * Add device- or boot-specific data to the input and nonblocking
733a2080a67SLinus Torvalds  * pools to help initialize them to unique values.
734a2080a67SLinus Torvalds  *
735a2080a67SLinus Torvalds  * None of this adds any entropy, it is meant to avoid the
736a2080a67SLinus Torvalds  * problem of the nonblocking pool having similar initial state
737a2080a67SLinus Torvalds  * across largely identical devices.
738a2080a67SLinus Torvalds  */
739a2080a67SLinus Torvalds void add_device_randomness(const void *buf, unsigned int size)
740a2080a67SLinus Torvalds {
74161875f30STheodore Ts'o 	unsigned long time = random_get_entropy() ^ jiffies;
7423ef4cb2dSTheodore Ts'o 	unsigned long flags;
743a2080a67SLinus Torvalds 
7445910895fSTheodore Ts'o 	trace_add_device_randomness(size, _RET_IP_);
7453ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&input_pool.lock, flags);
74685608f8eSTheodore Ts'o 	_mix_pool_bytes(&input_pool, buf, size);
74785608f8eSTheodore Ts'o 	_mix_pool_bytes(&input_pool, &time, sizeof(time));
7483ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&input_pool.lock, flags);
7493ef4cb2dSTheodore Ts'o 
7503ef4cb2dSTheodore Ts'o 	spin_lock_irqsave(&nonblocking_pool.lock, flags);
75185608f8eSTheodore Ts'o 	_mix_pool_bytes(&nonblocking_pool, buf, size);
75285608f8eSTheodore Ts'o 	_mix_pool_bytes(&nonblocking_pool, &time, sizeof(time));
7533ef4cb2dSTheodore Ts'o 	spin_unlock_irqrestore(&nonblocking_pool.lock, flags);
754a2080a67SLinus Torvalds }
755a2080a67SLinus Torvalds EXPORT_SYMBOL(add_device_randomness);
756a2080a67SLinus Torvalds 
757644008dfSTheodore Ts'o static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
7583060d6feSYinghai Lu 
7591da177e4SLinus Torvalds /*
7601da177e4SLinus Torvalds  * This function adds entropy to the entropy "pool" by using timing
7611da177e4SLinus Torvalds  * delays.  It uses the timer_rand_state structure to make an estimate
7621da177e4SLinus Torvalds  * of how many bits of entropy this call has added to the pool.
7631da177e4SLinus Torvalds  *
7641da177e4SLinus Torvalds  * The number "num" is also added to the pool - it should somehow describe
7651da177e4SLinus Torvalds  * the type of event which just happened.  This is currently 0-255 for
7661da177e4SLinus Torvalds  * keyboard scan codes, and 256 upwards for interrupts.
7671da177e4SLinus Torvalds  *
7681da177e4SLinus Torvalds  */
7691da177e4SLinus Torvalds static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
7701da177e4SLinus Torvalds {
77140db23e5STheodore Ts'o 	struct entropy_store	*r;
7721da177e4SLinus Torvalds 	struct {
7731da177e4SLinus Torvalds 		long jiffies;
774cf833d0bSLinus Torvalds 		unsigned cycles;
7751da177e4SLinus Torvalds 		unsigned num;
7761da177e4SLinus Torvalds 	} sample;
7771da177e4SLinus Torvalds 	long delta, delta2, delta3;
7781da177e4SLinus Torvalds 
7791da177e4SLinus Torvalds 	preempt_disable();
7801da177e4SLinus Torvalds 
7811da177e4SLinus Torvalds 	sample.jiffies = jiffies;
78261875f30STheodore Ts'o 	sample.cycles = random_get_entropy();
7831da177e4SLinus Torvalds 	sample.num = num;
78440db23e5STheodore Ts'o 	r = nonblocking_pool.initialized ? &input_pool : &nonblocking_pool;
78585608f8eSTheodore Ts'o 	mix_pool_bytes(r, &sample, sizeof(sample));
7861da177e4SLinus Torvalds 
7871da177e4SLinus Torvalds 	/*
7881da177e4SLinus Torvalds 	 * Calculate number of bits of randomness we probably added.
7891da177e4SLinus Torvalds 	 * We take into account the first, second and third-order deltas
7901da177e4SLinus Torvalds 	 * in order to make our estimate.
7911da177e4SLinus Torvalds 	 */
7921da177e4SLinus Torvalds 
7931da177e4SLinus Torvalds 	if (!state->dont_count_entropy) {
7941da177e4SLinus Torvalds 		delta = sample.jiffies - state->last_time;
7951da177e4SLinus Torvalds 		state->last_time = sample.jiffies;
7961da177e4SLinus Torvalds 
7971da177e4SLinus Torvalds 		delta2 = delta - state->last_delta;
7981da177e4SLinus Torvalds 		state->last_delta = delta;
7991da177e4SLinus Torvalds 
8001da177e4SLinus Torvalds 		delta3 = delta2 - state->last_delta2;
8011da177e4SLinus Torvalds 		state->last_delta2 = delta2;
8021da177e4SLinus Torvalds 
8031da177e4SLinus Torvalds 		if (delta < 0)
8041da177e4SLinus Torvalds 			delta = -delta;
8051da177e4SLinus Torvalds 		if (delta2 < 0)
8061da177e4SLinus Torvalds 			delta2 = -delta2;
8071da177e4SLinus Torvalds 		if (delta3 < 0)
8081da177e4SLinus Torvalds 			delta3 = -delta3;
8091da177e4SLinus Torvalds 		if (delta > delta2)
8101da177e4SLinus Torvalds 			delta = delta2;
8111da177e4SLinus Torvalds 		if (delta > delta3)
8121da177e4SLinus Torvalds 			delta = delta3;
8131da177e4SLinus Torvalds 
8141da177e4SLinus Torvalds 		/*
8151da177e4SLinus Torvalds 		 * delta is now minimum absolute delta.
8161da177e4SLinus Torvalds 		 * Round down by 1 bit on general principles,
8171da177e4SLinus Torvalds 		 * and limit entropy entimate to 12 bits.
8181da177e4SLinus Torvalds 		 */
81940db23e5STheodore Ts'o 		credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
8201da177e4SLinus Torvalds 	}
8211da177e4SLinus Torvalds 	preempt_enable();
8221da177e4SLinus Torvalds }
8231da177e4SLinus Torvalds 
824d251575aSStephen Hemminger void add_input_randomness(unsigned int type, unsigned int code,
8251da177e4SLinus Torvalds 				 unsigned int value)
8261da177e4SLinus Torvalds {
8271da177e4SLinus Torvalds 	static unsigned char last_value;
8281da177e4SLinus Torvalds 
8291da177e4SLinus Torvalds 	/* ignore autorepeat and the like */
8301da177e4SLinus Torvalds 	if (value == last_value)
8311da177e4SLinus Torvalds 		return;
8321da177e4SLinus Torvalds 
8331da177e4SLinus Torvalds 	last_value = value;
8341da177e4SLinus Torvalds 	add_timer_randomness(&input_timer_state,
8351da177e4SLinus Torvalds 			     (type << 4) ^ code ^ (code >> 4) ^ value);
836f80bbd8bSTheodore Ts'o 	trace_add_input_randomness(ENTROPY_BITS(&input_pool));
8371da177e4SLinus Torvalds }
83880fc9f53SDmitry Torokhov EXPORT_SYMBOL_GPL(add_input_randomness);
8391da177e4SLinus Torvalds 
840775f4b29STheodore Ts'o static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
841775f4b29STheodore Ts'o 
84243759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
84343759d4fSTheodore Ts'o static unsigned long avg_cycles, avg_deviation;
84443759d4fSTheodore Ts'o 
84543759d4fSTheodore Ts'o #define AVG_SHIFT 8     /* Exponential average factor k=1/256 */
84643759d4fSTheodore Ts'o #define FIXED_1_2 (1 << (AVG_SHIFT-1))
84743759d4fSTheodore Ts'o 
84843759d4fSTheodore Ts'o static void add_interrupt_bench(cycles_t start)
84943759d4fSTheodore Ts'o {
85043759d4fSTheodore Ts'o         long delta = random_get_entropy() - start;
85143759d4fSTheodore Ts'o 
85243759d4fSTheodore Ts'o         /* Use a weighted moving average */
85343759d4fSTheodore Ts'o         delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
85443759d4fSTheodore Ts'o         avg_cycles += delta;
85543759d4fSTheodore Ts'o         /* And average deviation */
85643759d4fSTheodore Ts'o         delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
85743759d4fSTheodore Ts'o         avg_deviation += delta;
85843759d4fSTheodore Ts'o }
85943759d4fSTheodore Ts'o #else
86043759d4fSTheodore Ts'o #define add_interrupt_bench(x)
86143759d4fSTheodore Ts'o #endif
86243759d4fSTheodore Ts'o 
863ee3e00e9STheodore Ts'o static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
864ee3e00e9STheodore Ts'o {
865ee3e00e9STheodore Ts'o 	__u32 *ptr = (__u32 *) regs;
866ee3e00e9STheodore Ts'o 
867ee3e00e9STheodore Ts'o 	if (regs == NULL)
868ee3e00e9STheodore Ts'o 		return 0;
869ee3e00e9STheodore Ts'o 	if (f->reg_idx >= sizeof(struct pt_regs) / sizeof(__u32))
870ee3e00e9STheodore Ts'o 		f->reg_idx = 0;
871ee3e00e9STheodore Ts'o 	return *(ptr + f->reg_idx++);
872ee3e00e9STheodore Ts'o }
873ee3e00e9STheodore Ts'o 
874775f4b29STheodore Ts'o void add_interrupt_randomness(int irq, int irq_flags)
8751da177e4SLinus Torvalds {
876775f4b29STheodore Ts'o 	struct entropy_store	*r;
877*1b2a1a7eSChristoph Lameter 	struct fast_pool	*fast_pool = this_cpu_ptr(&irq_randomness);
878775f4b29STheodore Ts'o 	struct pt_regs		*regs = get_irq_regs();
879775f4b29STheodore Ts'o 	unsigned long		now = jiffies;
880655b2264STheodore Ts'o 	cycles_t		cycles = random_get_entropy();
88143759d4fSTheodore Ts'o 	__u32			c_high, j_high;
882655b2264STheodore Ts'o 	__u64			ip;
88383664a69SH. Peter Anvin 	unsigned long		seed;
88491fcb532STheodore Ts'o 	int			credit = 0;
8853060d6feSYinghai Lu 
886ee3e00e9STheodore Ts'o 	if (cycles == 0)
887ee3e00e9STheodore Ts'o 		cycles = get_reg(fast_pool, regs);
888655b2264STheodore Ts'o 	c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
889655b2264STheodore Ts'o 	j_high = (sizeof(now) > 4) ? now >> 32 : 0;
89043759d4fSTheodore Ts'o 	fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
89143759d4fSTheodore Ts'o 	fast_pool->pool[1] ^= now ^ c_high;
892655b2264STheodore Ts'o 	ip = regs ? instruction_pointer(regs) : _RET_IP_;
89343759d4fSTheodore Ts'o 	fast_pool->pool[2] ^= ip;
894ee3e00e9STheodore Ts'o 	fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
895ee3e00e9STheodore Ts'o 		get_reg(fast_pool, regs);
8963060d6feSYinghai Lu 
89743759d4fSTheodore Ts'o 	fast_mix(fast_pool);
89843759d4fSTheodore Ts'o 	add_interrupt_bench(cycles);
899775f4b29STheodore Ts'o 
900840f9507STheodore Ts'o 	if ((fast_pool->count < 64) &&
901840f9507STheodore Ts'o 	    !time_after(now, fast_pool->last + HZ))
9021da177e4SLinus Torvalds 		return;
903840f9507STheodore Ts'o 
904840f9507STheodore Ts'o 	r = nonblocking_pool.initialized ? &input_pool : &nonblocking_pool;
905840f9507STheodore Ts'o 	if (!spin_trylock(&r->lock))
9061da177e4SLinus Torvalds 		return;
9071da177e4SLinus Torvalds 
908775f4b29STheodore Ts'o 	fast_pool->last = now;
90985608f8eSTheodore Ts'o 	__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
91083664a69SH. Peter Anvin 
91183664a69SH. Peter Anvin 	/*
91283664a69SH. Peter Anvin 	 * If we have architectural seed generator, produce a seed and
91348d6be95STheodore Ts'o 	 * add it to the pool.  For the sake of paranoia don't let the
91448d6be95STheodore Ts'o 	 * architectural seed generator dominate the input from the
91548d6be95STheodore Ts'o 	 * interrupt noise.
91683664a69SH. Peter Anvin 	 */
91783664a69SH. Peter Anvin 	if (arch_get_random_seed_long(&seed)) {
91885608f8eSTheodore Ts'o 		__mix_pool_bytes(r, &seed, sizeof(seed));
91948d6be95STheodore Ts'o 		credit = 1;
92083664a69SH. Peter Anvin 	}
92191fcb532STheodore Ts'o 	spin_unlock(&r->lock);
92283664a69SH. Peter Anvin 
923ee3e00e9STheodore Ts'o 	fast_pool->count = 0;
924840f9507STheodore Ts'o 
925ee3e00e9STheodore Ts'o 	/* award one bit for the contents of the fast pool */
926ee3e00e9STheodore Ts'o 	credit_entropy_bits(r, credit + 1);
9271da177e4SLinus Torvalds }
9281da177e4SLinus Torvalds 
9299361401eSDavid Howells #ifdef CONFIG_BLOCK
9301da177e4SLinus Torvalds void add_disk_randomness(struct gendisk *disk)
9311da177e4SLinus Torvalds {
9321da177e4SLinus Torvalds 	if (!disk || !disk->random)
9331da177e4SLinus Torvalds 		return;
9341da177e4SLinus Torvalds 	/* first major is 1, so we get >= 0x200 here */
935f331c029STejun Heo 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
936f80bbd8bSTheodore Ts'o 	trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
9371da177e4SLinus Torvalds }
938bdcfa3e5SChristoph Hellwig EXPORT_SYMBOL_GPL(add_disk_randomness);
9399361401eSDavid Howells #endif
9401da177e4SLinus Torvalds 
9411da177e4SLinus Torvalds /*********************************************************************
9421da177e4SLinus Torvalds  *
9431da177e4SLinus Torvalds  * Entropy extraction routines
9441da177e4SLinus Torvalds  *
9451da177e4SLinus Torvalds  *********************************************************************/
9461da177e4SLinus Torvalds 
9471da177e4SLinus Torvalds static ssize_t extract_entropy(struct entropy_store *r, void *buf,
9481da177e4SLinus Torvalds 			       size_t nbytes, int min, int rsvd);
9491da177e4SLinus Torvalds 
9501da177e4SLinus Torvalds /*
95125985edcSLucas De Marchi  * This utility inline function is responsible for transferring entropy
9521da177e4SLinus Torvalds  * from the primary pool to the secondary extraction pool. We make
9531da177e4SLinus Torvalds  * sure we pull enough for a 'catastrophic reseed'.
9541da177e4SLinus Torvalds  */
9556265e169STheodore Ts'o static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes);
9561da177e4SLinus Torvalds static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
9571da177e4SLinus Torvalds {
958cff85031STheodore Ts'o 	if (!r->pull ||
959cff85031STheodore Ts'o 	    r->entropy_count >= (nbytes << (ENTROPY_SHIFT + 3)) ||
960cff85031STheodore Ts'o 	    r->entropy_count > r->poolinfo->poolfracbits)
961cff85031STheodore Ts'o 		return;
962cff85031STheodore Ts'o 
963f5c2742cSTheodore Ts'o 	if (r->limit == 0 && random_min_urandom_seed) {
964f5c2742cSTheodore Ts'o 		unsigned long now = jiffies;
965f5c2742cSTheodore Ts'o 
966f5c2742cSTheodore Ts'o 		if (time_before(now,
967f5c2742cSTheodore Ts'o 				r->last_pulled + random_min_urandom_seed * HZ))
968f5c2742cSTheodore Ts'o 			return;
969f5c2742cSTheodore Ts'o 		r->last_pulled = now;
970f5c2742cSTheodore Ts'o 	}
971cff85031STheodore Ts'o 
9726265e169STheodore Ts'o 	_xfer_secondary_pool(r, nbytes);
9736265e169STheodore Ts'o }
9746265e169STheodore Ts'o 
9756265e169STheodore Ts'o static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
9766265e169STheodore Ts'o {
9771da177e4SLinus Torvalds 	__u32	tmp[OUTPUT_POOL_WORDS];
9781da177e4SLinus Torvalds 
9792132a96fSGreg Price 	/* For /dev/random's pool, always leave two wakeups' worth */
9802132a96fSGreg Price 	int rsvd_bytes = r->limit ? 0 : random_read_wakeup_bits / 4;
9815a021e9fSMatt Mackall 	int bytes = nbytes;
9825a021e9fSMatt Mackall 
9832132a96fSGreg Price 	/* pull at least as much as a wakeup */
9842132a96fSGreg Price 	bytes = max_t(int, bytes, random_read_wakeup_bits / 8);
9855a021e9fSMatt Mackall 	/* but never more than the buffer size */
986d2e7c96aSH. Peter Anvin 	bytes = min_t(int, bytes, sizeof(tmp));
9871da177e4SLinus Torvalds 
988f80bbd8bSTheodore Ts'o 	trace_xfer_secondary_pool(r->name, bytes * 8, nbytes * 8,
989f80bbd8bSTheodore Ts'o 				  ENTROPY_BITS(r), ENTROPY_BITS(r->pull));
990d2e7c96aSH. Peter Anvin 	bytes = extract_entropy(r->pull, tmp, bytes,
9912132a96fSGreg Price 				random_read_wakeup_bits / 8, rsvd_bytes);
99285608f8eSTheodore Ts'o 	mix_pool_bytes(r, tmp, bytes);
993adc782daSMatt Mackall 	credit_entropy_bits(r, bytes*8);
9941da177e4SLinus Torvalds }
9956265e169STheodore Ts'o 
9966265e169STheodore Ts'o /*
9976265e169STheodore Ts'o  * Used as a workqueue function so that when the input pool is getting
9986265e169STheodore Ts'o  * full, we can "spill over" some entropy to the output pools.  That
9996265e169STheodore Ts'o  * way the output pools can store some of the excess entropy instead
10006265e169STheodore Ts'o  * of letting it go to waste.
10016265e169STheodore Ts'o  */
10026265e169STheodore Ts'o static void push_to_pool(struct work_struct *work)
10036265e169STheodore Ts'o {
10046265e169STheodore Ts'o 	struct entropy_store *r = container_of(work, struct entropy_store,
10056265e169STheodore Ts'o 					      push_work);
10066265e169STheodore Ts'o 	BUG_ON(!r);
10072132a96fSGreg Price 	_xfer_secondary_pool(r, random_read_wakeup_bits/8);
10086265e169STheodore Ts'o 	trace_push_to_pool(r->name, r->entropy_count >> ENTROPY_SHIFT,
10096265e169STheodore Ts'o 			   r->pull->entropy_count >> ENTROPY_SHIFT);
10101da177e4SLinus Torvalds }
10111da177e4SLinus Torvalds 
10121da177e4SLinus Torvalds /*
101319fa5be1SGreg Price  * This function decides how many bytes to actually take from the
101419fa5be1SGreg Price  * given pool, and also debits the entropy count accordingly.
10151da177e4SLinus Torvalds  */
10161da177e4SLinus Torvalds static size_t account(struct entropy_store *r, size_t nbytes, int min,
10171da177e4SLinus Torvalds 		      int reserved)
10181da177e4SLinus Torvalds {
1019a283b5c4SH. Peter Anvin 	int entropy_count, orig;
102079a84687SHannes Frederic Sowa 	size_t ibytes, nfrac;
10211da177e4SLinus Torvalds 
1022a283b5c4SH. Peter Anvin 	BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
10231da177e4SLinus Torvalds 
10241da177e4SLinus Torvalds 	/* Can we pull enough? */
102510b3a32dSJiri Kosina retry:
102610b3a32dSJiri Kosina 	entropy_count = orig = ACCESS_ONCE(r->entropy_count);
1027a283b5c4SH. Peter Anvin 	ibytes = nbytes;
1028a283b5c4SH. Peter Anvin 	/* If limited, never pull more than available */
1029e33ba5faSTheodore Ts'o 	if (r->limit) {
1030e33ba5faSTheodore Ts'o 		int have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
1031e33ba5faSTheodore Ts'o 
1032e33ba5faSTheodore Ts'o 		if ((have_bytes -= reserved) < 0)
1033e33ba5faSTheodore Ts'o 			have_bytes = 0;
1034e33ba5faSTheodore Ts'o 		ibytes = min_t(size_t, ibytes, have_bytes);
1035e33ba5faSTheodore Ts'o 	}
10360fb7a01aSGreg Price 	if (ibytes < min)
10370fb7a01aSGreg Price 		ibytes = 0;
103879a84687SHannes Frederic Sowa 
103979a84687SHannes Frederic Sowa 	if (unlikely(entropy_count < 0)) {
104079a84687SHannes Frederic Sowa 		pr_warn("random: negative entropy count: pool %s count %d\n",
104179a84687SHannes Frederic Sowa 			r->name, entropy_count);
104279a84687SHannes Frederic Sowa 		WARN_ON(1);
104379a84687SHannes Frederic Sowa 		entropy_count = 0;
104479a84687SHannes Frederic Sowa 	}
104579a84687SHannes Frederic Sowa 	nfrac = ibytes << (ENTROPY_SHIFT + 3);
104679a84687SHannes Frederic Sowa 	if ((size_t) entropy_count > nfrac)
104779a84687SHannes Frederic Sowa 		entropy_count -= nfrac;
104879a84687SHannes Frederic Sowa 	else
1049e33ba5faSTheodore Ts'o 		entropy_count = 0;
1050f9c6d498STheodore Ts'o 
105110b3a32dSJiri Kosina 	if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
105210b3a32dSJiri Kosina 		goto retry;
10531da177e4SLinus Torvalds 
1054f80bbd8bSTheodore Ts'o 	trace_debit_entropy(r->name, 8 * ibytes);
10550fb7a01aSGreg Price 	if (ibytes &&
10562132a96fSGreg Price 	    (r->entropy_count >> ENTROPY_SHIFT) < random_write_wakeup_bits) {
1057b9809552STheodore Ts'o 		wake_up_interruptible(&random_write_wait);
1058b9809552STheodore Ts'o 		kill_fasync(&fasync, SIGIO, POLL_OUT);
1059b9809552STheodore Ts'o 	}
1060b9809552STheodore Ts'o 
1061a283b5c4SH. Peter Anvin 	return ibytes;
10621da177e4SLinus Torvalds }
10631da177e4SLinus Torvalds 
106419fa5be1SGreg Price /*
106519fa5be1SGreg Price  * This function does the actual extraction for extract_entropy and
106619fa5be1SGreg Price  * extract_entropy_user.
106719fa5be1SGreg Price  *
106819fa5be1SGreg Price  * Note: we assume that .poolwords is a multiple of 16 words.
106919fa5be1SGreg Price  */
10701da177e4SLinus Torvalds static void extract_buf(struct entropy_store *r, __u8 *out)
10711da177e4SLinus Torvalds {
1072602b6aeeSMatt Mackall 	int i;
1073d2e7c96aSH. Peter Anvin 	union {
1074d2e7c96aSH. Peter Anvin 		__u32 w[5];
107585a1f777STheodore Ts'o 		unsigned long l[LONGS(20)];
1076d2e7c96aSH. Peter Anvin 	} hash;
1077d2e7c96aSH. Peter Anvin 	__u32 workspace[SHA_WORKSPACE_WORDS];
1078902c098aSTheodore Ts'o 	unsigned long flags;
10791da177e4SLinus Torvalds 
10801da177e4SLinus Torvalds 	/*
1081dfd38750SGreg Price 	 * If we have an architectural hardware random number
108246884442STheodore Ts'o 	 * generator, use it for SHA's initial vector
108385a1f777STheodore Ts'o 	 */
108446884442STheodore Ts'o 	sha_init(hash.w);
108585a1f777STheodore Ts'o 	for (i = 0; i < LONGS(20); i++) {
108685a1f777STheodore Ts'o 		unsigned long v;
108785a1f777STheodore Ts'o 		if (!arch_get_random_long(&v))
108885a1f777STheodore Ts'o 			break;
108946884442STheodore Ts'o 		hash.l[i] = v;
109085a1f777STheodore Ts'o 	}
109185a1f777STheodore Ts'o 
109246884442STheodore Ts'o 	/* Generate a hash across the pool, 16 words (512 bits) at a time */
109346884442STheodore Ts'o 	spin_lock_irqsave(&r->lock, flags);
109446884442STheodore Ts'o 	for (i = 0; i < r->poolinfo->poolwords; i += 16)
109546884442STheodore Ts'o 		sha_transform(hash.w, (__u8 *)(r->pool + i), workspace);
109646884442STheodore Ts'o 
109785a1f777STheodore Ts'o 	/*
10981c0ad3d4SMatt Mackall 	 * We mix the hash back into the pool to prevent backtracking
10991c0ad3d4SMatt Mackall 	 * attacks (where the attacker knows the state of the pool
11001c0ad3d4SMatt Mackall 	 * plus the current outputs, and attempts to find previous
11011c0ad3d4SMatt Mackall 	 * ouputs), unless the hash function can be inverted. By
11021c0ad3d4SMatt Mackall 	 * mixing at least a SHA1 worth of hash data back, we make
11031c0ad3d4SMatt Mackall 	 * brute-forcing the feedback as hard as brute-forcing the
11041c0ad3d4SMatt Mackall 	 * hash.
11051da177e4SLinus Torvalds 	 */
110685608f8eSTheodore Ts'o 	__mix_pool_bytes(r, hash.w, sizeof(hash.w));
1107902c098aSTheodore Ts'o 	spin_unlock_irqrestore(&r->lock, flags);
11081c0ad3d4SMatt Mackall 
1109ffd8d3faSMatt Mackall 	memset(workspace, 0, sizeof(workspace));
11101da177e4SLinus Torvalds 
11111da177e4SLinus Torvalds 	/*
11121c0ad3d4SMatt Mackall 	 * In case the hash function has some recognizable output
11131c0ad3d4SMatt Mackall 	 * pattern, we fold it in half. Thus, we always feed back
11141c0ad3d4SMatt Mackall 	 * twice as much data as we output.
11151da177e4SLinus Torvalds 	 */
1116d2e7c96aSH. Peter Anvin 	hash.w[0] ^= hash.w[3];
1117d2e7c96aSH. Peter Anvin 	hash.w[1] ^= hash.w[4];
1118d2e7c96aSH. Peter Anvin 	hash.w[2] ^= rol32(hash.w[2], 16);
1119d2e7c96aSH. Peter Anvin 
1120d2e7c96aSH. Peter Anvin 	memcpy(out, &hash, EXTRACT_SIZE);
1121d2e7c96aSH. Peter Anvin 	memset(&hash, 0, sizeof(hash));
11221da177e4SLinus Torvalds }
11231da177e4SLinus Torvalds 
112419fa5be1SGreg Price /*
112519fa5be1SGreg Price  * This function extracts randomness from the "entropy pool", and
112619fa5be1SGreg Price  * returns it in a buffer.
112719fa5be1SGreg Price  *
112819fa5be1SGreg Price  * The min parameter specifies the minimum amount we can pull before
112919fa5be1SGreg Price  * failing to avoid races that defeat catastrophic reseeding while the
113019fa5be1SGreg Price  * reserved parameter indicates how much entropy we must leave in the
113119fa5be1SGreg Price  * pool after each pull to avoid starving other readers.
113219fa5be1SGreg Price  */
11331da177e4SLinus Torvalds static ssize_t extract_entropy(struct entropy_store *r, void *buf,
11341da177e4SLinus Torvalds 				 size_t nbytes, int min, int reserved)
11351da177e4SLinus Torvalds {
11361da177e4SLinus Torvalds 	ssize_t ret = 0, i;
11371da177e4SLinus Torvalds 	__u8 tmp[EXTRACT_SIZE];
11381e7e2e05SJarod Wilson 	unsigned long flags;
11391da177e4SLinus Torvalds 
1140ec8f02daSJarod Wilson 	/* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
11411e7e2e05SJarod Wilson 	if (fips_enabled) {
11421e7e2e05SJarod Wilson 		spin_lock_irqsave(&r->lock, flags);
11431e7e2e05SJarod Wilson 		if (!r->last_data_init) {
1144c59974aeSTheodore Ts'o 			r->last_data_init = 1;
11451e7e2e05SJarod Wilson 			spin_unlock_irqrestore(&r->lock, flags);
11461e7e2e05SJarod Wilson 			trace_extract_entropy(r->name, EXTRACT_SIZE,
1147a283b5c4SH. Peter Anvin 					      ENTROPY_BITS(r), _RET_IP_);
11481e7e2e05SJarod Wilson 			xfer_secondary_pool(r, EXTRACT_SIZE);
11491e7e2e05SJarod Wilson 			extract_buf(r, tmp);
11501e7e2e05SJarod Wilson 			spin_lock_irqsave(&r->lock, flags);
11511e7e2e05SJarod Wilson 			memcpy(r->last_data, tmp, EXTRACT_SIZE);
11521e7e2e05SJarod Wilson 		}
11531e7e2e05SJarod Wilson 		spin_unlock_irqrestore(&r->lock, flags);
11541e7e2e05SJarod Wilson 	}
1155ec8f02daSJarod Wilson 
1156a283b5c4SH. Peter Anvin 	trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
11571da177e4SLinus Torvalds 	xfer_secondary_pool(r, nbytes);
11581da177e4SLinus Torvalds 	nbytes = account(r, nbytes, min, reserved);
11591da177e4SLinus Torvalds 
11601da177e4SLinus Torvalds 	while (nbytes) {
11611da177e4SLinus Torvalds 		extract_buf(r, tmp);
11625b739ef8SNeil Horman 
1163e954bc91SMatt Mackall 		if (fips_enabled) {
11645b739ef8SNeil Horman 			spin_lock_irqsave(&r->lock, flags);
11655b739ef8SNeil Horman 			if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
11665b739ef8SNeil Horman 				panic("Hardware RNG duplicated output!\n");
11675b739ef8SNeil Horman 			memcpy(r->last_data, tmp, EXTRACT_SIZE);
11685b739ef8SNeil Horman 			spin_unlock_irqrestore(&r->lock, flags);
11695b739ef8SNeil Horman 		}
11701da177e4SLinus Torvalds 		i = min_t(int, nbytes, EXTRACT_SIZE);
11711da177e4SLinus Torvalds 		memcpy(buf, tmp, i);
11721da177e4SLinus Torvalds 		nbytes -= i;
11731da177e4SLinus Torvalds 		buf += i;
11741da177e4SLinus Torvalds 		ret += i;
11751da177e4SLinus Torvalds 	}
11761da177e4SLinus Torvalds 
11771da177e4SLinus Torvalds 	/* Wipe data just returned from memory */
11781da177e4SLinus Torvalds 	memset(tmp, 0, sizeof(tmp));
11791da177e4SLinus Torvalds 
11801da177e4SLinus Torvalds 	return ret;
11811da177e4SLinus Torvalds }
11821da177e4SLinus Torvalds 
118319fa5be1SGreg Price /*
118419fa5be1SGreg Price  * This function extracts randomness from the "entropy pool", and
118519fa5be1SGreg Price  * returns it in a userspace buffer.
118619fa5be1SGreg Price  */
11871da177e4SLinus Torvalds static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,
11881da177e4SLinus Torvalds 				    size_t nbytes)
11891da177e4SLinus Torvalds {
11901da177e4SLinus Torvalds 	ssize_t ret = 0, i;
11911da177e4SLinus Torvalds 	__u8 tmp[EXTRACT_SIZE];
1192c6e9d6f3STheodore Ts'o 	int large_request = (nbytes > 256);
11931da177e4SLinus Torvalds 
1194a283b5c4SH. Peter Anvin 	trace_extract_entropy_user(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
11951da177e4SLinus Torvalds 	xfer_secondary_pool(r, nbytes);
11961da177e4SLinus Torvalds 	nbytes = account(r, nbytes, 0, 0);
11971da177e4SLinus Torvalds 
11981da177e4SLinus Torvalds 	while (nbytes) {
1199c6e9d6f3STheodore Ts'o 		if (large_request && need_resched()) {
12001da177e4SLinus Torvalds 			if (signal_pending(current)) {
12011da177e4SLinus Torvalds 				if (ret == 0)
12021da177e4SLinus Torvalds 					ret = -ERESTARTSYS;
12031da177e4SLinus Torvalds 				break;
12041da177e4SLinus Torvalds 			}
12051da177e4SLinus Torvalds 			schedule();
12061da177e4SLinus Torvalds 		}
12071da177e4SLinus Torvalds 
12081da177e4SLinus Torvalds 		extract_buf(r, tmp);
12091da177e4SLinus Torvalds 		i = min_t(int, nbytes, EXTRACT_SIZE);
12101da177e4SLinus Torvalds 		if (copy_to_user(buf, tmp, i)) {
12111da177e4SLinus Torvalds 			ret = -EFAULT;
12121da177e4SLinus Torvalds 			break;
12131da177e4SLinus Torvalds 		}
12141da177e4SLinus Torvalds 
12151da177e4SLinus Torvalds 		nbytes -= i;
12161da177e4SLinus Torvalds 		buf += i;
12171da177e4SLinus Torvalds 		ret += i;
12181da177e4SLinus Torvalds 	}
12191da177e4SLinus Torvalds 
12201da177e4SLinus Torvalds 	/* Wipe data just returned from memory */
12211da177e4SLinus Torvalds 	memset(tmp, 0, sizeof(tmp));
12221da177e4SLinus Torvalds 
12231da177e4SLinus Torvalds 	return ret;
12241da177e4SLinus Torvalds }
12251da177e4SLinus Torvalds 
12261da177e4SLinus Torvalds /*
12271da177e4SLinus Torvalds  * This function is the exported kernel interface.  It returns some
1228c2557a30STheodore Ts'o  * number of good random numbers, suitable for key generation, seeding
122918e9cea7SGreg Price  * TCP sequence numbers, etc.  It does not rely on the hardware random
123018e9cea7SGreg Price  * number generator.  For random bytes direct from the hardware RNG
123118e9cea7SGreg Price  * (when available), use get_random_bytes_arch().
12321da177e4SLinus Torvalds  */
12331da177e4SLinus Torvalds void get_random_bytes(void *buf, int nbytes)
12341da177e4SLinus Torvalds {
1235392a546dSTheodore Ts'o #if DEBUG_RANDOM_BOOT > 0
1236392a546dSTheodore Ts'o 	if (unlikely(nonblocking_pool.initialized == 0))
1237392a546dSTheodore Ts'o 		printk(KERN_NOTICE "random: %pF get_random_bytes called "
1238392a546dSTheodore Ts'o 		       "with %d bits of entropy available\n",
1239392a546dSTheodore Ts'o 		       (void *) _RET_IP_,
1240392a546dSTheodore Ts'o 		       nonblocking_pool.entropy_total);
1241392a546dSTheodore Ts'o #endif
12425910895fSTheodore Ts'o 	trace_get_random_bytes(nbytes, _RET_IP_);
1243c2557a30STheodore Ts'o 	extract_entropy(&nonblocking_pool, buf, nbytes, 0, 0);
1244c2557a30STheodore Ts'o }
1245c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes);
1246c2557a30STheodore Ts'o 
1247c2557a30STheodore Ts'o /*
1248c2557a30STheodore Ts'o  * This function will use the architecture-specific hardware random
1249c2557a30STheodore Ts'o  * number generator if it is available.  The arch-specific hw RNG will
1250c2557a30STheodore Ts'o  * almost certainly be faster than what we can do in software, but it
1251c2557a30STheodore Ts'o  * is impossible to verify that it is implemented securely (as
1252c2557a30STheodore Ts'o  * opposed, to, say, the AES encryption of a sequence number using a
1253c2557a30STheodore Ts'o  * key known by the NSA).  So it's useful if we need the speed, but
1254c2557a30STheodore Ts'o  * only if we're willing to trust the hardware manufacturer not to
1255c2557a30STheodore Ts'o  * have put in a back door.
1256c2557a30STheodore Ts'o  */
1257c2557a30STheodore Ts'o void get_random_bytes_arch(void *buf, int nbytes)
1258c2557a30STheodore Ts'o {
125963d77173SH. Peter Anvin 	char *p = buf;
126063d77173SH. Peter Anvin 
12615910895fSTheodore Ts'o 	trace_get_random_bytes_arch(nbytes, _RET_IP_);
126263d77173SH. Peter Anvin 	while (nbytes) {
126363d77173SH. Peter Anvin 		unsigned long v;
126463d77173SH. Peter Anvin 		int chunk = min(nbytes, (int)sizeof(unsigned long));
126563d77173SH. Peter Anvin 
126663d77173SH. Peter Anvin 		if (!arch_get_random_long(&v))
126763d77173SH. Peter Anvin 			break;
126863d77173SH. Peter Anvin 
1269bd29e568SLuck, Tony 		memcpy(p, &v, chunk);
127063d77173SH. Peter Anvin 		p += chunk;
127163d77173SH. Peter Anvin 		nbytes -= chunk;
127263d77173SH. Peter Anvin 	}
127363d77173SH. Peter Anvin 
1274c2557a30STheodore Ts'o 	if (nbytes)
127563d77173SH. Peter Anvin 		extract_entropy(&nonblocking_pool, p, nbytes, 0, 0);
12761da177e4SLinus Torvalds }
1277c2557a30STheodore Ts'o EXPORT_SYMBOL(get_random_bytes_arch);
1278c2557a30STheodore Ts'o 
12791da177e4SLinus Torvalds 
12801da177e4SLinus Torvalds /*
12811da177e4SLinus Torvalds  * init_std_data - initialize pool with system data
12821da177e4SLinus Torvalds  *
12831da177e4SLinus Torvalds  * @r: pool to initialize
12841da177e4SLinus Torvalds  *
12851da177e4SLinus Torvalds  * This function clears the pool's entropy count and mixes some system
12861da177e4SLinus Torvalds  * data into the pool to prepare it for use. The pool is not cleared
12871da177e4SLinus Torvalds  * as that can only decrease the entropy in the pool.
12881da177e4SLinus Torvalds  */
12891da177e4SLinus Torvalds static void init_std_data(struct entropy_store *r)
12901da177e4SLinus Torvalds {
12913e88bdffSTheodore Ts'o 	int i;
1292902c098aSTheodore Ts'o 	ktime_t now = ktime_get_real();
1293902c098aSTheodore Ts'o 	unsigned long rv;
12941da177e4SLinus Torvalds 
1295f5c2742cSTheodore Ts'o 	r->last_pulled = jiffies;
129685608f8eSTheodore Ts'o 	mix_pool_bytes(r, &now, sizeof(now));
12979ed17b70SH. Peter Anvin 	for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
129883664a69SH. Peter Anvin 		if (!arch_get_random_seed_long(&rv) &&
129983664a69SH. Peter Anvin 		    !arch_get_random_long(&rv))
1300ae9ecd92STheodore Ts'o 			rv = random_get_entropy();
130185608f8eSTheodore Ts'o 		mix_pool_bytes(r, &rv, sizeof(rv));
13023e88bdffSTheodore Ts'o 	}
130385608f8eSTheodore Ts'o 	mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
13041da177e4SLinus Torvalds }
13051da177e4SLinus Torvalds 
1306cbc96b75STony Luck /*
1307cbc96b75STony Luck  * Note that setup_arch() may call add_device_randomness()
1308cbc96b75STony Luck  * long before we get here. This allows seeding of the pools
1309cbc96b75STony Luck  * with some platform dependent data very early in the boot
1310cbc96b75STony Luck  * process. But it limits our options here. We must use
1311cbc96b75STony Luck  * statically allocated structures that already have all
1312cbc96b75STony Luck  * initializations complete at compile time. We should also
1313cbc96b75STony Luck  * take care not to overwrite the precious per platform data
1314cbc96b75STony Luck  * we were given.
1315cbc96b75STony Luck  */
131653c3f63eSMatt Mackall static int rand_initialize(void)
13171da177e4SLinus Torvalds {
13181da177e4SLinus Torvalds 	init_std_data(&input_pool);
13191da177e4SLinus Torvalds 	init_std_data(&blocking_pool);
13201da177e4SLinus Torvalds 	init_std_data(&nonblocking_pool);
13211da177e4SLinus Torvalds 	return 0;
13221da177e4SLinus Torvalds }
1323ae9ecd92STheodore Ts'o early_initcall(rand_initialize);
13241da177e4SLinus Torvalds 
13259361401eSDavid Howells #ifdef CONFIG_BLOCK
13261da177e4SLinus Torvalds void rand_initialize_disk(struct gendisk *disk)
13271da177e4SLinus Torvalds {
13281da177e4SLinus Torvalds 	struct timer_rand_state *state;
13291da177e4SLinus Torvalds 
13301da177e4SLinus Torvalds 	/*
1331f8595815SEric Dumazet 	 * If kzalloc returns null, we just won't use that entropy
13321da177e4SLinus Torvalds 	 * source.
13331da177e4SLinus Torvalds 	 */
1334f8595815SEric Dumazet 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1335644008dfSTheodore Ts'o 	if (state) {
1336644008dfSTheodore Ts'o 		state->last_time = INITIAL_JIFFIES;
13371da177e4SLinus Torvalds 		disk->random = state;
13381da177e4SLinus Torvalds 	}
1339644008dfSTheodore Ts'o }
13409361401eSDavid Howells #endif
13411da177e4SLinus Torvalds 
13421da177e4SLinus Torvalds static ssize_t
1343c6e9d6f3STheodore Ts'o _random_read(int nonblock, char __user *buf, size_t nbytes)
13441da177e4SLinus Torvalds {
134512ff3a51SGreg Price 	ssize_t n;
13461da177e4SLinus Torvalds 
13471da177e4SLinus Torvalds 	if (nbytes == 0)
13481da177e4SLinus Torvalds 		return 0;
13491da177e4SLinus Torvalds 
135012ff3a51SGreg Price 	nbytes = min_t(size_t, nbytes, SEC_XFER_SIZE);
135112ff3a51SGreg Price 	while (1) {
135212ff3a51SGreg Price 		n = extract_entropy_user(&blocking_pool, buf, nbytes);
135312ff3a51SGreg Price 		if (n < 0)
135412ff3a51SGreg Price 			return n;
1355f80bbd8bSTheodore Ts'o 		trace_random_read(n*8, (nbytes-n)*8,
1356f80bbd8bSTheodore Ts'o 				  ENTROPY_BITS(&blocking_pool),
1357f80bbd8bSTheodore Ts'o 				  ENTROPY_BITS(&input_pool));
135812ff3a51SGreg Price 		if (n > 0)
135912ff3a51SGreg Price 			return n;
1360331c6490SH. Peter Anvin 
136112ff3a51SGreg Price 		/* Pool is (near) empty.  Maybe wait and retry. */
1362c6e9d6f3STheodore Ts'o 		if (nonblock)
136312ff3a51SGreg Price 			return -EAGAIN;
13641da177e4SLinus Torvalds 
13651da177e4SLinus Torvalds 		wait_event_interruptible(random_read_wait,
1366a283b5c4SH. Peter Anvin 			ENTROPY_BITS(&input_pool) >=
13672132a96fSGreg Price 			random_read_wakeup_bits);
136812ff3a51SGreg Price 		if (signal_pending(current))
136912ff3a51SGreg Price 			return -ERESTARTSYS;
13701da177e4SLinus Torvalds 	}
13711da177e4SLinus Torvalds }
13721da177e4SLinus Torvalds 
13731da177e4SLinus Torvalds static ssize_t
1374c6e9d6f3STheodore Ts'o random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1375c6e9d6f3STheodore Ts'o {
1376c6e9d6f3STheodore Ts'o 	return _random_read(file->f_flags & O_NONBLOCK, buf, nbytes);
1377c6e9d6f3STheodore Ts'o }
1378c6e9d6f3STheodore Ts'o 
1379c6e9d6f3STheodore Ts'o static ssize_t
138090b75ee5SMatt Mackall urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
13811da177e4SLinus Torvalds {
1382301f0595STheodore Ts'o 	int ret;
1383301f0595STheodore Ts'o 
1384301f0595STheodore Ts'o 	if (unlikely(nonblocking_pool.initialized == 0))
1385301f0595STheodore Ts'o 		printk_once(KERN_NOTICE "random: %s urandom read "
1386301f0595STheodore Ts'o 			    "with %d bits of entropy available\n",
1387301f0595STheodore Ts'o 			    current->comm, nonblocking_pool.entropy_total);
1388301f0595STheodore Ts'o 
138979a84687SHannes Frederic Sowa 	nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
1390301f0595STheodore Ts'o 	ret = extract_entropy_user(&nonblocking_pool, buf, nbytes);
1391f80bbd8bSTheodore Ts'o 
1392f80bbd8bSTheodore Ts'o 	trace_urandom_read(8 * nbytes, ENTROPY_BITS(&nonblocking_pool),
1393f80bbd8bSTheodore Ts'o 			   ENTROPY_BITS(&input_pool));
1394f80bbd8bSTheodore Ts'o 	return ret;
13951da177e4SLinus Torvalds }
13961da177e4SLinus Torvalds 
13971da177e4SLinus Torvalds static unsigned int
13981da177e4SLinus Torvalds random_poll(struct file *file, poll_table * wait)
13991da177e4SLinus Torvalds {
14001da177e4SLinus Torvalds 	unsigned int mask;
14011da177e4SLinus Torvalds 
14021da177e4SLinus Torvalds 	poll_wait(file, &random_read_wait, wait);
14031da177e4SLinus Torvalds 	poll_wait(file, &random_write_wait, wait);
14041da177e4SLinus Torvalds 	mask = 0;
14052132a96fSGreg Price 	if (ENTROPY_BITS(&input_pool) >= random_read_wakeup_bits)
14061da177e4SLinus Torvalds 		mask |= POLLIN | POLLRDNORM;
14072132a96fSGreg Price 	if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
14081da177e4SLinus Torvalds 		mask |= POLLOUT | POLLWRNORM;
14091da177e4SLinus Torvalds 	return mask;
14101da177e4SLinus Torvalds }
14111da177e4SLinus Torvalds 
14127f397dcdSMatt Mackall static int
14137f397dcdSMatt Mackall write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
14147f397dcdSMatt Mackall {
14157f397dcdSMatt Mackall 	size_t bytes;
14167f397dcdSMatt Mackall 	__u32 buf[16];
14177f397dcdSMatt Mackall 	const char __user *p = buffer;
14187f397dcdSMatt Mackall 
14197f397dcdSMatt Mackall 	while (count > 0) {
14207f397dcdSMatt Mackall 		bytes = min(count, sizeof(buf));
14217f397dcdSMatt Mackall 		if (copy_from_user(&buf, p, bytes))
14227f397dcdSMatt Mackall 			return -EFAULT;
14237f397dcdSMatt Mackall 
14247f397dcdSMatt Mackall 		count -= bytes;
14257f397dcdSMatt Mackall 		p += bytes;
14267f397dcdSMatt Mackall 
142785608f8eSTheodore Ts'o 		mix_pool_bytes(r, buf, bytes);
142891f3f1e3SMatt Mackall 		cond_resched();
14297f397dcdSMatt Mackall 	}
14307f397dcdSMatt Mackall 
14317f397dcdSMatt Mackall 	return 0;
14327f397dcdSMatt Mackall }
14337f397dcdSMatt Mackall 
143490b75ee5SMatt Mackall static ssize_t random_write(struct file *file, const char __user *buffer,
14351da177e4SLinus Torvalds 			    size_t count, loff_t *ppos)
14361da177e4SLinus Torvalds {
14377f397dcdSMatt Mackall 	size_t ret;
14387f397dcdSMatt Mackall 
14397f397dcdSMatt Mackall 	ret = write_pool(&blocking_pool, buffer, count);
14407f397dcdSMatt Mackall 	if (ret)
14417f397dcdSMatt Mackall 		return ret;
14427f397dcdSMatt Mackall 	ret = write_pool(&nonblocking_pool, buffer, count);
14437f397dcdSMatt Mackall 	if (ret)
14447f397dcdSMatt Mackall 		return ret;
14457f397dcdSMatt Mackall 
14467f397dcdSMatt Mackall 	return (ssize_t)count;
14471da177e4SLinus Torvalds }
14481da177e4SLinus Torvalds 
144943ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
14501da177e4SLinus Torvalds {
14511da177e4SLinus Torvalds 	int size, ent_count;
14521da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
14531da177e4SLinus Torvalds 	int retval;
14541da177e4SLinus Torvalds 
14551da177e4SLinus Torvalds 	switch (cmd) {
14561da177e4SLinus Torvalds 	case RNDGETENTCNT:
145743ae4860SMatt Mackall 		/* inherently racy, no point locking */
1458a283b5c4SH. Peter Anvin 		ent_count = ENTROPY_BITS(&input_pool);
1459a283b5c4SH. Peter Anvin 		if (put_user(ent_count, p))
14601da177e4SLinus Torvalds 			return -EFAULT;
14611da177e4SLinus Torvalds 		return 0;
14621da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
14631da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14641da177e4SLinus Torvalds 			return -EPERM;
14651da177e4SLinus Torvalds 		if (get_user(ent_count, p))
14661da177e4SLinus Torvalds 			return -EFAULT;
1467a283b5c4SH. Peter Anvin 		credit_entropy_bits_safe(&input_pool, ent_count);
14681da177e4SLinus Torvalds 		return 0;
14691da177e4SLinus Torvalds 	case RNDADDENTROPY:
14701da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14711da177e4SLinus Torvalds 			return -EPERM;
14721da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
14731da177e4SLinus Torvalds 			return -EFAULT;
14741da177e4SLinus Torvalds 		if (ent_count < 0)
14751da177e4SLinus Torvalds 			return -EINVAL;
14761da177e4SLinus Torvalds 		if (get_user(size, p++))
14771da177e4SLinus Torvalds 			return -EFAULT;
14787f397dcdSMatt Mackall 		retval = write_pool(&input_pool, (const char __user *)p,
14797f397dcdSMatt Mackall 				    size);
14801da177e4SLinus Torvalds 		if (retval < 0)
14811da177e4SLinus Torvalds 			return retval;
1482a283b5c4SH. Peter Anvin 		credit_entropy_bits_safe(&input_pool, ent_count);
14831da177e4SLinus Torvalds 		return 0;
14841da177e4SLinus Torvalds 	case RNDZAPENTCNT:
14851da177e4SLinus Torvalds 	case RNDCLEARPOOL:
1486ae9ecd92STheodore Ts'o 		/*
1487ae9ecd92STheodore Ts'o 		 * Clear the entropy pool counters. We no longer clear
1488ae9ecd92STheodore Ts'o 		 * the entropy pool, as that's silly.
1489ae9ecd92STheodore Ts'o 		 */
14901da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
14911da177e4SLinus Torvalds 			return -EPERM;
1492ae9ecd92STheodore Ts'o 		input_pool.entropy_count = 0;
1493ae9ecd92STheodore Ts'o 		nonblocking_pool.entropy_count = 0;
1494ae9ecd92STheodore Ts'o 		blocking_pool.entropy_count = 0;
14951da177e4SLinus Torvalds 		return 0;
14961da177e4SLinus Torvalds 	default:
14971da177e4SLinus Torvalds 		return -EINVAL;
14981da177e4SLinus Torvalds 	}
14991da177e4SLinus Torvalds }
15001da177e4SLinus Torvalds 
15019a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
15029a6f70bbSJeff Dike {
15039a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
15049a6f70bbSJeff Dike }
15059a6f70bbSJeff Dike 
15062b8693c0SArjan van de Ven const struct file_operations random_fops = {
15071da177e4SLinus Torvalds 	.read  = random_read,
15081da177e4SLinus Torvalds 	.write = random_write,
15091da177e4SLinus Torvalds 	.poll  = random_poll,
151043ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
15119a6f70bbSJeff Dike 	.fasync = random_fasync,
15126038f373SArnd Bergmann 	.llseek = noop_llseek,
15131da177e4SLinus Torvalds };
15141da177e4SLinus Torvalds 
15152b8693c0SArjan van de Ven const struct file_operations urandom_fops = {
15161da177e4SLinus Torvalds 	.read  = urandom_read,
15171da177e4SLinus Torvalds 	.write = random_write,
151843ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
15199a6f70bbSJeff Dike 	.fasync = random_fasync,
15206038f373SArnd Bergmann 	.llseek = noop_llseek,
15211da177e4SLinus Torvalds };
15221da177e4SLinus Torvalds 
1523c6e9d6f3STheodore Ts'o SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
1524c6e9d6f3STheodore Ts'o 		unsigned int, flags)
1525c6e9d6f3STheodore Ts'o {
1526c6e9d6f3STheodore Ts'o 	if (flags & ~(GRND_NONBLOCK|GRND_RANDOM))
1527c6e9d6f3STheodore Ts'o 		return -EINVAL;
1528c6e9d6f3STheodore Ts'o 
1529c6e9d6f3STheodore Ts'o 	if (count > INT_MAX)
1530c6e9d6f3STheodore Ts'o 		count = INT_MAX;
1531c6e9d6f3STheodore Ts'o 
1532c6e9d6f3STheodore Ts'o 	if (flags & GRND_RANDOM)
1533c6e9d6f3STheodore Ts'o 		return _random_read(flags & GRND_NONBLOCK, buf, count);
1534c6e9d6f3STheodore Ts'o 
1535c6e9d6f3STheodore Ts'o 	if (unlikely(nonblocking_pool.initialized == 0)) {
1536c6e9d6f3STheodore Ts'o 		if (flags & GRND_NONBLOCK)
1537c6e9d6f3STheodore Ts'o 			return -EAGAIN;
1538c6e9d6f3STheodore Ts'o 		wait_event_interruptible(urandom_init_wait,
1539c6e9d6f3STheodore Ts'o 					 nonblocking_pool.initialized);
1540c6e9d6f3STheodore Ts'o 		if (signal_pending(current))
1541c6e9d6f3STheodore Ts'o 			return -ERESTARTSYS;
1542c6e9d6f3STheodore Ts'o 	}
1543c6e9d6f3STheodore Ts'o 	return urandom_read(NULL, buf, count, NULL);
1544c6e9d6f3STheodore Ts'o }
1545c6e9d6f3STheodore Ts'o 
15461da177e4SLinus Torvalds /***************************************************************
15471da177e4SLinus Torvalds  * Random UUID interface
15481da177e4SLinus Torvalds  *
15491da177e4SLinus Torvalds  * Used here for a Boot ID, but can be useful for other kernel
15501da177e4SLinus Torvalds  * drivers.
15511da177e4SLinus Torvalds  ***************************************************************/
15521da177e4SLinus Torvalds 
15531da177e4SLinus Torvalds /*
15541da177e4SLinus Torvalds  * Generate random UUID
15551da177e4SLinus Torvalds  */
15561da177e4SLinus Torvalds void generate_random_uuid(unsigned char uuid_out[16])
15571da177e4SLinus Torvalds {
15581da177e4SLinus Torvalds 	get_random_bytes(uuid_out, 16);
1559c41b20e7SAdam Buchbinder 	/* Set UUID version to 4 --- truly random generation */
15601da177e4SLinus Torvalds 	uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
15611da177e4SLinus Torvalds 	/* Set the UUID variant to DCE */
15621da177e4SLinus Torvalds 	uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
15631da177e4SLinus Torvalds }
15641da177e4SLinus Torvalds EXPORT_SYMBOL(generate_random_uuid);
15651da177e4SLinus Torvalds 
15661da177e4SLinus Torvalds /********************************************************************
15671da177e4SLinus Torvalds  *
15681da177e4SLinus Torvalds  * Sysctl interface
15691da177e4SLinus Torvalds  *
15701da177e4SLinus Torvalds  ********************************************************************/
15711da177e4SLinus Torvalds 
15721da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
15731da177e4SLinus Torvalds 
15741da177e4SLinus Torvalds #include <linux/sysctl.h>
15751da177e4SLinus Torvalds 
15761da177e4SLinus Torvalds static int min_read_thresh = 8, min_write_thresh;
15778c2aa339SGreg Price static int max_read_thresh = OUTPUT_POOL_WORDS * 32;
15781da177e4SLinus Torvalds static int max_write_thresh = INPUT_POOL_WORDS * 32;
15791da177e4SLinus Torvalds static char sysctl_bootid[16];
15801da177e4SLinus Torvalds 
15811da177e4SLinus Torvalds /*
1582f22052b2SGreg Price  * This function is used to return both the bootid UUID, and random
15831da177e4SLinus Torvalds  * UUID.  The difference is in whether table->data is NULL; if it is,
15841da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
15851da177e4SLinus Torvalds  *
1586f22052b2SGreg Price  * If the user accesses this via the proc interface, the UUID will be
1587f22052b2SGreg Price  * returned as an ASCII string in the standard UUID format; if via the
1588f22052b2SGreg Price  * sysctl system call, as 16 bytes of binary data.
15891da177e4SLinus Torvalds  */
1590a151427eSJoe Perches static int proc_do_uuid(struct ctl_table *table, int write,
15911da177e4SLinus Torvalds 			void __user *buffer, size_t *lenp, loff_t *ppos)
15921da177e4SLinus Torvalds {
1593a151427eSJoe Perches 	struct ctl_table fake_table;
15941da177e4SLinus Torvalds 	unsigned char buf[64], tmp_uuid[16], *uuid;
15951da177e4SLinus Torvalds 
15961da177e4SLinus Torvalds 	uuid = table->data;
15971da177e4SLinus Torvalds 	if (!uuid) {
15981da177e4SLinus Torvalds 		uuid = tmp_uuid;
15991da177e4SLinus Torvalds 		generate_random_uuid(uuid);
160044e4360fSMathieu Desnoyers 	} else {
160144e4360fSMathieu Desnoyers 		static DEFINE_SPINLOCK(bootid_spinlock);
160244e4360fSMathieu Desnoyers 
160344e4360fSMathieu Desnoyers 		spin_lock(&bootid_spinlock);
160444e4360fSMathieu Desnoyers 		if (!uuid[8])
160544e4360fSMathieu Desnoyers 			generate_random_uuid(uuid);
160644e4360fSMathieu Desnoyers 		spin_unlock(&bootid_spinlock);
160744e4360fSMathieu Desnoyers 	}
16081da177e4SLinus Torvalds 
160935900771SJoe Perches 	sprintf(buf, "%pU", uuid);
161035900771SJoe Perches 
16111da177e4SLinus Torvalds 	fake_table.data = buf;
16121da177e4SLinus Torvalds 	fake_table.maxlen = sizeof(buf);
16131da177e4SLinus Torvalds 
16148d65af78SAlexey Dobriyan 	return proc_dostring(&fake_table, write, buffer, lenp, ppos);
16151da177e4SLinus Torvalds }
16161da177e4SLinus Torvalds 
1617a283b5c4SH. Peter Anvin /*
1618a283b5c4SH. Peter Anvin  * Return entropy available scaled to integral bits
1619a283b5c4SH. Peter Anvin  */
16205eb10d91SJoe Perches static int proc_do_entropy(struct ctl_table *table, int write,
1621a283b5c4SH. Peter Anvin 			   void __user *buffer, size_t *lenp, loff_t *ppos)
1622a283b5c4SH. Peter Anvin {
16235eb10d91SJoe Perches 	struct ctl_table fake_table;
1624a283b5c4SH. Peter Anvin 	int entropy_count;
1625a283b5c4SH. Peter Anvin 
1626a283b5c4SH. Peter Anvin 	entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
1627a283b5c4SH. Peter Anvin 
1628a283b5c4SH. Peter Anvin 	fake_table.data = &entropy_count;
1629a283b5c4SH. Peter Anvin 	fake_table.maxlen = sizeof(entropy_count);
1630a283b5c4SH. Peter Anvin 
1631a283b5c4SH. Peter Anvin 	return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
1632a283b5c4SH. Peter Anvin }
1633a283b5c4SH. Peter Anvin 
16341da177e4SLinus Torvalds static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
1635a151427eSJoe Perches extern struct ctl_table random_table[];
1636a151427eSJoe Perches struct ctl_table random_table[] = {
16371da177e4SLinus Torvalds 	{
16381da177e4SLinus Torvalds 		.procname	= "poolsize",
16391da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
16401da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16411da177e4SLinus Torvalds 		.mode		= 0444,
16426d456111SEric W. Biederman 		.proc_handler	= proc_dointvec,
16431da177e4SLinus Torvalds 	},
16441da177e4SLinus Torvalds 	{
16451da177e4SLinus Torvalds 		.procname	= "entropy_avail",
16461da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16471da177e4SLinus Torvalds 		.mode		= 0444,
1648a283b5c4SH. Peter Anvin 		.proc_handler	= proc_do_entropy,
16491da177e4SLinus Torvalds 		.data		= &input_pool.entropy_count,
16501da177e4SLinus Torvalds 	},
16511da177e4SLinus Torvalds 	{
16521da177e4SLinus Torvalds 		.procname	= "read_wakeup_threshold",
16532132a96fSGreg Price 		.data		= &random_read_wakeup_bits,
16541da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16551da177e4SLinus Torvalds 		.mode		= 0644,
16566d456111SEric W. Biederman 		.proc_handler	= proc_dointvec_minmax,
16571da177e4SLinus Torvalds 		.extra1		= &min_read_thresh,
16581da177e4SLinus Torvalds 		.extra2		= &max_read_thresh,
16591da177e4SLinus Torvalds 	},
16601da177e4SLinus Torvalds 	{
16611da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
16622132a96fSGreg Price 		.data		= &random_write_wakeup_bits,
16631da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
16641da177e4SLinus Torvalds 		.mode		= 0644,
16656d456111SEric W. Biederman 		.proc_handler	= proc_dointvec_minmax,
16661da177e4SLinus Torvalds 		.extra1		= &min_write_thresh,
16671da177e4SLinus Torvalds 		.extra2		= &max_write_thresh,
16681da177e4SLinus Torvalds 	},
16691da177e4SLinus Torvalds 	{
1670f5c2742cSTheodore Ts'o 		.procname	= "urandom_min_reseed_secs",
1671f5c2742cSTheodore Ts'o 		.data		= &random_min_urandom_seed,
1672f5c2742cSTheodore Ts'o 		.maxlen		= sizeof(int),
1673f5c2742cSTheodore Ts'o 		.mode		= 0644,
1674f5c2742cSTheodore Ts'o 		.proc_handler	= proc_dointvec,
1675f5c2742cSTheodore Ts'o 	},
1676f5c2742cSTheodore Ts'o 	{
16771da177e4SLinus Torvalds 		.procname	= "boot_id",
16781da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
16791da177e4SLinus Torvalds 		.maxlen		= 16,
16801da177e4SLinus Torvalds 		.mode		= 0444,
16816d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16821da177e4SLinus Torvalds 	},
16831da177e4SLinus Torvalds 	{
16841da177e4SLinus Torvalds 		.procname	= "uuid",
16851da177e4SLinus Torvalds 		.maxlen		= 16,
16861da177e4SLinus Torvalds 		.mode		= 0444,
16876d456111SEric W. Biederman 		.proc_handler	= proc_do_uuid,
16881da177e4SLinus Torvalds 	},
168943759d4fSTheodore Ts'o #ifdef ADD_INTERRUPT_BENCH
169043759d4fSTheodore Ts'o 	{
169143759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_cycles",
169243759d4fSTheodore Ts'o 		.data		= &avg_cycles,
169343759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_cycles),
169443759d4fSTheodore Ts'o 		.mode		= 0444,
169543759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
169643759d4fSTheodore Ts'o 	},
169743759d4fSTheodore Ts'o 	{
169843759d4fSTheodore Ts'o 		.procname	= "add_interrupt_avg_deviation",
169943759d4fSTheodore Ts'o 		.data		= &avg_deviation,
170043759d4fSTheodore Ts'o 		.maxlen		= sizeof(avg_deviation),
170143759d4fSTheodore Ts'o 		.mode		= 0444,
170243759d4fSTheodore Ts'o 		.proc_handler	= proc_doulongvec_minmax,
170343759d4fSTheodore Ts'o 	},
170443759d4fSTheodore Ts'o #endif
1705894d2491SEric W. Biederman 	{ }
17061da177e4SLinus Torvalds };
17071da177e4SLinus Torvalds #endif 	/* CONFIG_SYSCTL */
17081da177e4SLinus Torvalds 
17096e5714eaSDavid S. Miller static u32 random_int_secret[MD5_MESSAGE_BYTES / 4] ____cacheline_aligned;
17101da177e4SLinus Torvalds 
171147d06e53STheodore Ts'o int random_int_secret_init(void)
17121da177e4SLinus Torvalds {
17136e5714eaSDavid S. Miller 	get_random_bytes(random_int_secret, sizeof(random_int_secret));
17141da177e4SLinus Torvalds 	return 0;
17151da177e4SLinus Torvalds }
17161da177e4SLinus Torvalds 
17171da177e4SLinus Torvalds /*
17181da177e4SLinus Torvalds  * Get a random word for internal kernel use only. Similar to urandom but
17191da177e4SLinus Torvalds  * with the goal of minimal entropy pool depletion. As a result, the random
17201da177e4SLinus Torvalds  * value is not cryptographically secure but for several uses the cost of
17211da177e4SLinus Torvalds  * depleting entropy is too high
17221da177e4SLinus Torvalds  */
172374feec5dSTheodore Ts'o static DEFINE_PER_CPU(__u32 [MD5_DIGEST_WORDS], get_random_int_hash);
17241da177e4SLinus Torvalds unsigned int get_random_int(void)
17251da177e4SLinus Torvalds {
172663d77173SH. Peter Anvin 	__u32 *hash;
17276e5714eaSDavid S. Miller 	unsigned int ret;
17288a0a9bd4SLinus Torvalds 
172963d77173SH. Peter Anvin 	if (arch_get_random_int(&ret))
173063d77173SH. Peter Anvin 		return ret;
173163d77173SH. Peter Anvin 
173263d77173SH. Peter Anvin 	hash = get_cpu_var(get_random_int_hash);
17338a0a9bd4SLinus Torvalds 
173461875f30STheodore Ts'o 	hash[0] += current->pid + jiffies + random_get_entropy();
17356e5714eaSDavid S. Miller 	md5_transform(hash, random_int_secret);
17366e5714eaSDavid S. Miller 	ret = hash[0];
17378a0a9bd4SLinus Torvalds 	put_cpu_var(get_random_int_hash);
17388a0a9bd4SLinus Torvalds 
17398a0a9bd4SLinus Torvalds 	return ret;
17401da177e4SLinus Torvalds }
174116c7fa05SAndy Shevchenko EXPORT_SYMBOL(get_random_int);
17421da177e4SLinus Torvalds 
17431da177e4SLinus Torvalds /*
17441da177e4SLinus Torvalds  * randomize_range() returns a start address such that
17451da177e4SLinus Torvalds  *
17461da177e4SLinus Torvalds  *    [...... <range> .....]
17471da177e4SLinus Torvalds  *  start                  end
17481da177e4SLinus Torvalds  *
17491da177e4SLinus Torvalds  * a <range> with size "len" starting at the return value is inside in the
17501da177e4SLinus Torvalds  * area defined by [start, end], but is otherwise randomized.
17511da177e4SLinus Torvalds  */
17521da177e4SLinus Torvalds unsigned long
17531da177e4SLinus Torvalds randomize_range(unsigned long start, unsigned long end, unsigned long len)
17541da177e4SLinus Torvalds {
17551da177e4SLinus Torvalds 	unsigned long range = end - len - start;
17561da177e4SLinus Torvalds 
17571da177e4SLinus Torvalds 	if (end <= start + len)
17581da177e4SLinus Torvalds 		return 0;
17591da177e4SLinus Torvalds 	return PAGE_ALIGN(get_random_int() % range + start);
17601da177e4SLinus Torvalds }
1761c84dbf61STorsten Duwe 
1762c84dbf61STorsten Duwe /* Interface for in-kernel drivers of true hardware RNGs.
1763c84dbf61STorsten Duwe  * Those devices may produce endless random bits and will be throttled
1764c84dbf61STorsten Duwe  * when our pool is full.
1765c84dbf61STorsten Duwe  */
1766c84dbf61STorsten Duwe void add_hwgenerator_randomness(const char *buffer, size_t count,
1767c84dbf61STorsten Duwe 				size_t entropy)
1768c84dbf61STorsten Duwe {
1769c84dbf61STorsten Duwe 	struct entropy_store *poolp = &input_pool;
1770c84dbf61STorsten Duwe 
1771c84dbf61STorsten Duwe 	/* Suspend writing if we're above the trickle threshold.
1772c84dbf61STorsten Duwe 	 * We'll be woken up again once below random_write_wakeup_thresh,
1773c84dbf61STorsten Duwe 	 * or when the calling thread is about to terminate.
1774c84dbf61STorsten Duwe 	 */
1775c84dbf61STorsten Duwe 	wait_event_interruptible(random_write_wait, kthread_should_stop() ||
1776c84dbf61STorsten Duwe 			ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
1777c84dbf61STorsten Duwe 	mix_pool_bytes(poolp, buffer, count);
1778c84dbf61STorsten Duwe 	credit_entropy_bits(poolp, entropy);
1779c84dbf61STorsten Duwe }
1780c84dbf61STorsten Duwe EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
1781