random: remove unnecessary unlikely()
[linux-block.git] / drivers / char / random.c
CommitLineData
1da177e4
LT
1/*
2 * random.c -- A strong random number generator
3 *
b169c13d
JD
4 * Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All
5 * Rights Reserved.
6 *
9e95ce27 7 * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
1da177e4
LT
8 *
9 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All
10 * rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, and the entire permission notice in its entirety,
17 * including the disclaimer of warranties.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. The name of the author may not be used to endorse or promote
22 * products derived from this software without specific prior
23 * written permission.
24 *
25 * ALTERNATIVELY, this product may be distributed under the terms of
26 * the GNU General Public License, in which case the provisions of the GPL are
27 * required INSTEAD OF the above restrictions. (This clause is
28 * necessary due to a potential bad interaction between the GPL and
29 * the restrictions contained in a BSD-style copyright.)
30 *
31 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
32 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
34 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
35 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
37 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
38 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
39 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
41 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
42 * DAMAGE.
43 */
44
45/*
46 * (now, with legal B.S. out of the way.....)
47 *
48 * This routine gathers environmental noise from device drivers, etc.,
49 * and returns good random numbers, suitable for cryptographic use.
50 * Besides the obvious cryptographic uses, these numbers are also good
51 * for seeding TCP sequence numbers, and other places where it is
52 * desirable to have numbers which are not only random, but hard to
53 * predict by an attacker.
54 *
55 * Theory of operation
56 * ===================
57 *
58 * Computers are very predictable devices. Hence it is extremely hard
59 * to produce truly random numbers on a computer --- as opposed to
60 * pseudo-random numbers, which can easily generated by using a
61 * algorithm. Unfortunately, it is very easy for attackers to guess
62 * the sequence of pseudo-random number generators, and for some
63 * applications this is not acceptable. So instead, we must try to
64 * gather "environmental noise" from the computer's environment, which
65 * must be hard for outside attackers to observe, and use that to
66 * generate random numbers. In a Unix environment, this is best done
67 * from inside the kernel.
68 *
69 * Sources of randomness from the environment include inter-keyboard
70 * timings, inter-interrupt timings from some interrupts, and other
71 * events which are both (a) non-deterministic and (b) hard for an
72 * outside observer to measure. Randomness from these sources are
73 * added to an "entropy pool", which is mixed using a CRC-like function.
74 * This is not cryptographically strong, but it is adequate assuming
75 * the randomness is not chosen maliciously, and it is fast enough that
76 * the overhead of doing it on every interrupt is very reasonable.
77 * As random bytes are mixed into the entropy pool, the routines keep
78 * an *estimate* of how many bits of randomness have been stored into
79 * the random number generator's internal state.
80 *
81 * When random bytes are desired, they are obtained by taking the SHA
82 * hash of the contents of the "entropy pool". The SHA hash avoids
83 * exposing the internal state of the entropy pool. It is believed to
84 * be computationally infeasible to derive any useful information
85 * about the input of SHA from its output. Even if it is possible to
86 * analyze SHA in some clever way, as long as the amount of data
87 * returned from the generator is less than the inherent entropy in
88 * the pool, the output data is totally unpredictable. For this
89 * reason, the routine decreases its internal estimate of how many
90 * bits of "true randomness" are contained in the entropy pool as it
91 * outputs random numbers.
92 *
93 * If this estimate goes to zero, the routine can still generate
94 * random numbers; however, an attacker may (at least in theory) be
95 * able to infer the future output of the generator from prior
96 * outputs. This requires successful cryptanalysis of SHA, which is
97 * not believed to be feasible, but there is a remote possibility.
98 * Nonetheless, these numbers should be useful for the vast majority
99 * of purposes.
100 *
101 * Exported interfaces ---- output
102 * ===============================
103 *
92e507d2
GS
104 * There are four exported interfaces; two for use within the kernel,
105 * and two or use from userspace.
1da177e4 106 *
92e507d2
GS
107 * Exported interfaces ---- userspace output
108 * -----------------------------------------
1da177e4 109 *
92e507d2 110 * The userspace interfaces are two character devices /dev/random and
1da177e4
LT
111 * /dev/urandom. /dev/random is suitable for use when very high
112 * quality randomness is desired (for example, for key generation or
113 * one-time pads), as it will only return a maximum of the number of
114 * bits of randomness (as estimated by the random number generator)
115 * contained in the entropy pool.
116 *
117 * The /dev/urandom device does not have this limit, and will return
118 * as many bytes as are requested. As more and more random bytes are
119 * requested without giving time for the entropy pool to recharge,
120 * this will result in random numbers that are merely cryptographically
121 * strong. For many applications, however, this is acceptable.
122 *
92e507d2
GS
123 * Exported interfaces ---- kernel output
124 * --------------------------------------
125 *
126 * The primary kernel interface is
127 *
128 * void get_random_bytes(void *buf, int nbytes);
129 *
130 * This interface will return the requested number of random bytes,
131 * and place it in the requested buffer. This is equivalent to a
132 * read from /dev/urandom.
133 *
134 * For less critical applications, there are the functions:
135 *
136 * u32 get_random_u32()
137 * u64 get_random_u64()
138 * unsigned int get_random_int()
139 * unsigned long get_random_long()
140 *
141 * These are produced by a cryptographic RNG seeded from get_random_bytes,
142 * and so do not deplete the entropy pool as much. These are recommended
143 * for most in-kernel operations *if the result is going to be stored in
144 * the kernel*.
145 *
146 * Specifically, the get_random_int() family do not attempt to do
147 * "anti-backtracking". If you capture the state of the kernel (e.g.
148 * by snapshotting the VM), you can figure out previous get_random_int()
149 * return values. But if the value is stored in the kernel anyway,
150 * this is not a problem.
151 *
152 * It *is* safe to expose get_random_int() output to attackers (e.g. as
153 * network cookies); given outputs 1..n, it's not feasible to predict
154 * outputs 0 or n+1. The only concern is an attacker who breaks into
155 * the kernel later; the get_random_int() engine is not reseeded as
156 * often as the get_random_bytes() one.
157 *
158 * get_random_bytes() is needed for keys that need to stay secret after
159 * they are erased from the kernel. For example, any key that will
160 * be wrapped and stored encrypted. And session encryption keys: we'd
161 * like to know that after the session is closed and the keys erased,
162 * the plaintext is unrecoverable to someone who recorded the ciphertext.
163 *
164 * But for network ports/cookies, stack canaries, PRNG seeds, address
165 * space layout randomization, session *authentication* keys, or other
166 * applications where the sensitive data is stored in the kernel in
167 * plaintext for as long as it's sensitive, the get_random_int() family
168 * is just fine.
169 *
170 * Consider ASLR. We want to keep the address space secret from an
171 * outside attacker while the process is running, but once the address
172 * space is torn down, it's of no use to an attacker any more. And it's
173 * stored in kernel data structures as long as it's alive, so worrying
174 * about an attacker's ability to extrapolate it from the get_random_int()
175 * CRNG is silly.
176 *
177 * Even some cryptographic keys are safe to generate with get_random_int().
178 * In particular, keys for SipHash are generally fine. Here, knowledge
179 * of the key authorizes you to do something to a kernel object (inject
180 * packets to a network connection, or flood a hash table), and the
181 * key is stored with the object being protected. Once it goes away,
182 * we no longer care if anyone knows the key.
183 *
184 * prandom_u32()
185 * -------------
186 *
187 * For even weaker applications, see the pseudorandom generator
188 * prandom_u32(), prandom_max(), and prandom_bytes(). If the random
189 * numbers aren't security-critical at all, these are *far* cheaper.
190 * Useful for self-tests, random error simulation, randomized backoffs,
191 * and any other application where you trust that nobody is trying to
192 * maliciously mess with you by guessing the "random" numbers.
193 *
1da177e4
LT
194 * Exported interfaces ---- input
195 * ==============================
196 *
197 * The current exported interfaces for gathering environmental noise
198 * from the devices are:
199 *
a2080a67 200 * void add_device_randomness(const void *buf, unsigned int size);
1da177e4
LT
201 * void add_input_randomness(unsigned int type, unsigned int code,
202 * unsigned int value);
775f4b29 203 * void add_interrupt_randomness(int irq, int irq_flags);
442a4fff 204 * void add_disk_randomness(struct gendisk *disk);
1da177e4 205 *
a2080a67
LT
206 * add_device_randomness() is for adding data to the random pool that
207 * is likely to differ between two devices (or possibly even per boot).
208 * This would be things like MAC addresses or serial numbers, or the
209 * read-out of the RTC. This does *not* add any actual entropy to the
210 * pool, but it initializes the pool to different values for devices
211 * that might otherwise be identical and have very little entropy
212 * available to them (particularly common in the embedded world).
213 *
1da177e4
LT
214 * add_input_randomness() uses the input layer interrupt timing, as well as
215 * the event type information from the hardware.
216 *
775f4b29
TT
217 * add_interrupt_randomness() uses the interrupt timing as random
218 * inputs to the entropy pool. Using the cycle counters and the irq source
219 * as inputs, it feeds the randomness roughly once a second.
442a4fff
JW
220 *
221 * add_disk_randomness() uses what amounts to the seek time of block
222 * layer request events, on a per-disk_devt basis, as input to the
223 * entropy pool. Note that high-speed solid state drives with very low
224 * seek times do not make for good sources of entropy, as their seek
225 * times are usually fairly consistent.
1da177e4
LT
226 *
227 * All of these routines try to estimate how many bits of randomness a
228 * particular randomness source. They do this by keeping track of the
229 * first and second order deltas of the event timings.
230 *
231 * Ensuring unpredictability at system startup
232 * ============================================
233 *
234 * When any operating system starts up, it will go through a sequence
235 * of actions that are fairly predictable by an adversary, especially
236 * if the start-up does not involve interaction with a human operator.
237 * This reduces the actual number of bits of unpredictability in the
238 * entropy pool below the value in entropy_count. In order to
239 * counteract this effect, it helps to carry information in the
240 * entropy pool across shut-downs and start-ups. To do this, put the
241 * following lines an appropriate script which is run during the boot
242 * sequence:
243 *
244 * echo "Initializing random number generator..."
245 * random_seed=/var/run/random-seed
246 * # Carry a random seed from start-up to start-up
247 * # Load and then save the whole entropy pool
248 * if [ -f $random_seed ]; then
249 * cat $random_seed >/dev/urandom
250 * else
251 * touch $random_seed
252 * fi
253 * chmod 600 $random_seed
254 * dd if=/dev/urandom of=$random_seed count=1 bs=512
255 *
256 * and the following lines in an appropriate script which is run as
257 * the system is shutdown:
258 *
259 * # Carry a random seed from shut-down to start-up
260 * # Save the whole entropy pool
261 * echo "Saving random seed..."
262 * random_seed=/var/run/random-seed
263 * touch $random_seed
264 * chmod 600 $random_seed
265 * dd if=/dev/urandom of=$random_seed count=1 bs=512
266 *
267 * For example, on most modern systems using the System V init
268 * scripts, such code fragments would be found in
269 * /etc/rc.d/init.d/random. On older Linux systems, the correct script
270 * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
271 *
272 * Effectively, these commands cause the contents of the entropy pool
273 * to be saved at shut-down time and reloaded into the entropy pool at
274 * start-up. (The 'dd' in the addition to the bootup script is to
275 * make sure that /etc/random-seed is different for every start-up,
276 * even if the system crashes without executing rc.0.) Even with
277 * complete knowledge of the start-up activities, predicting the state
278 * of the entropy pool requires knowledge of the previous history of
279 * the system.
280 *
281 * Configuring the /dev/random driver under Linux
282 * ==============================================
283 *
284 * The /dev/random driver under Linux uses minor numbers 8 and 9 of
285 * the /dev/mem major number (#1). So if your system does not have
286 * /dev/random and /dev/urandom created already, they can be created
287 * by using the commands:
288 *
289 * mknod /dev/random c 1 8
290 * mknod /dev/urandom c 1 9
291 *
292 * Acknowledgements:
293 * =================
294 *
295 * Ideas for constructing this random number generator were derived
296 * from Pretty Good Privacy's random number generator, and from private
297 * discussions with Phil Karn. Colin Plumb provided a faster random
298 * number generator, which speed up the mixing function of the entropy
299 * pool, taken from PGPfone. Dale Worley has also contributed many
300 * useful ideas and suggestions to improve this driver.
301 *
302 * Any flaws in the design are solely my responsibility, and should
303 * not be attributed to the Phil, Colin, or any of authors of PGP.
304 *
305 * Further background information on this topic may be obtained from
306 * RFC 1750, "Randomness Recommendations for Security", by Donald
307 * Eastlake, Steve Crocker, and Jeff Schiller.
308 */
309
310#include <linux/utsname.h>
1da177e4
LT
311#include <linux/module.h>
312#include <linux/kernel.h>
313#include <linux/major.h>
314#include <linux/string.h>
315#include <linux/fcntl.h>
316#include <linux/slab.h>
317#include <linux/random.h>
318#include <linux/poll.h>
319#include <linux/init.h>
320#include <linux/fs.h>
321#include <linux/genhd.h>
322#include <linux/interrupt.h>
27ac792c 323#include <linux/mm.h>
dd0f0cf5 324#include <linux/nodemask.h>
1da177e4 325#include <linux/spinlock.h>
c84dbf61 326#include <linux/kthread.h>
1da177e4
LT
327#include <linux/percpu.h>
328#include <linux/cryptohash.h>
5b739ef8 329#include <linux/fips.h>
775f4b29 330#include <linux/ptrace.h>
6265e169 331#include <linux/workqueue.h>
0244ad00 332#include <linux/irq.h>
4e00b339 333#include <linux/ratelimit.h>
c6e9d6f3
TT
334#include <linux/syscalls.h>
335#include <linux/completion.h>
8da4b8c4 336#include <linux/uuid.h>
1ca1b917 337#include <crypto/chacha.h>
d178a1eb 338
1da177e4 339#include <asm/processor.h>
7c0f6ba6 340#include <linux/uaccess.h>
1da177e4 341#include <asm/irq.h>
775f4b29 342#include <asm/irq_regs.h>
1da177e4
LT
343#include <asm/io.h>
344
00ce1db1
TT
345#define CREATE_TRACE_POINTS
346#include <trace/events/random.h>
347
43759d4f
TT
348/* #define ADD_INTERRUPT_BENCH */
349
1da177e4
LT
350/*
351 * Configuration information
352 */
30e37ec5
PA
353#define INPUT_POOL_SHIFT 12
354#define INPUT_POOL_WORDS (1 << (INPUT_POOL_SHIFT-5))
355#define OUTPUT_POOL_SHIFT 10
356#define OUTPUT_POOL_WORDS (1 << (OUTPUT_POOL_SHIFT-5))
30e37ec5 357#define EXTRACT_SIZE 10
1da177e4 358
1da177e4 359
d2e7c96a
PA
360#define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
361
a283b5c4 362/*
95b709b6
TT
363 * To allow fractional bits to be tracked, the entropy_count field is
364 * denominated in units of 1/8th bits.
30e37ec5 365 *
3bd0b5bf 366 * 2*(ENTROPY_SHIFT + poolbitshift) must <= 31, or the multiply in
30e37ec5 367 * credit_entropy_bits() needs to be 64 bits wide.
a283b5c4
PA
368 */
369#define ENTROPY_SHIFT 3
370#define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
371
1da177e4
LT
372/*
373 * If the entropy count falls under this number of bits, then we
374 * should wake up processes which are selecting or polling on write
375 * access to /dev/random.
376 */
2132a96f 377static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
1da177e4 378
1da177e4 379/*
6e9fa2c8
TT
380 * Originally, we used a primitive polynomial of degree .poolwords
381 * over GF(2). The taps for various sizes are defined below. They
382 * were chosen to be evenly spaced except for the last tap, which is 1
383 * to get the twisting happening as fast as possible.
384 *
385 * For the purposes of better mixing, we use the CRC-32 polynomial as
386 * well to make a (modified) twisted Generalized Feedback Shift
387 * Register. (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR
388 * generators. ACM Transactions on Modeling and Computer Simulation
389 * 2(3):179-194. Also see M. Matsumoto & Y. Kurita, 1994. Twisted
dfd38750 390 * GFSR generators II. ACM Transactions on Modeling and Computer
6e9fa2c8
TT
391 * Simulation 4:254-266)
392 *
393 * Thanks to Colin Plumb for suggesting this.
394 *
395 * The mixing operation is much less sensitive than the output hash,
396 * where we use SHA-1. All that we want of mixing operation is that
397 * it be a good non-cryptographic hash; i.e. it not produce collisions
398 * when fed "random" data of the sort we expect to see. As long as
399 * the pool state differs for different inputs, we have preserved the
400 * input entropy and done a good job. The fact that an intelligent
401 * attacker can construct inputs that will produce controlled
402 * alterations to the pool's state is not important because we don't
403 * consider such inputs to contribute any randomness. The only
404 * property we need with respect to them is that the attacker can't
405 * increase his/her knowledge of the pool's state. Since all
406 * additions are reversible (knowing the final state and the input,
407 * you can reconstruct the initial state), if an attacker has any
408 * uncertainty about the initial state, he/she can only shuffle that
409 * uncertainty about, but never cause any collisions (which would
410 * decrease the uncertainty).
411 *
412 * Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
413 * Videau in their paper, "The Linux Pseudorandom Number Generator
414 * Revisited" (see: http://eprint.iacr.org/2012/251.pdf). In their
415 * paper, they point out that we are not using a true Twisted GFSR,
416 * since Matsumoto & Kurita used a trinomial feedback polynomial (that
417 * is, with only three taps, instead of the six that we are using).
418 * As a result, the resulting polynomial is neither primitive nor
419 * irreducible, and hence does not have a maximal period over
420 * GF(2**32). They suggest a slight change to the generator
421 * polynomial which improves the resulting TGFSR polynomial to be
422 * irreducible, which we have made here.
1da177e4 423 */
26e0854a 424static const struct poolinfo {
3bd0b5bf
RV
425 int poolbitshift, poolwords, poolbytes, poolfracbits;
426#define S(x) ilog2(x)+5, (x), (x)*4, (x) << (ENTROPY_SHIFT+5)
1da177e4
LT
427 int tap1, tap2, tap3, tap4, tap5;
428} poolinfo_table[] = {
6e9fa2c8
TT
429 /* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
430 /* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
431 { S(128), 104, 76, 51, 25, 1 },
432 /* was: x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 */
433 /* x^32 + x^26 + x^19 + x^14 + x^7 + x + 1 */
434 { S(32), 26, 19, 14, 7, 1 },
1da177e4
LT
435#if 0
436 /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
9ed17b70 437 { S(2048), 1638, 1231, 819, 411, 1 },
1da177e4
LT
438
439 /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
9ed17b70 440 { S(1024), 817, 615, 412, 204, 1 },
1da177e4
LT
441
442 /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
9ed17b70 443 { S(1024), 819, 616, 410, 207, 2 },
1da177e4
LT
444
445 /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
9ed17b70 446 { S(512), 411, 308, 208, 104, 1 },
1da177e4
LT
447
448 /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
9ed17b70 449 { S(512), 409, 307, 206, 102, 2 },
1da177e4 450 /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
9ed17b70 451 { S(512), 409, 309, 205, 103, 2 },
1da177e4
LT
452
453 /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
9ed17b70 454 { S(256), 205, 155, 101, 52, 1 },
1da177e4
LT
455
456 /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
9ed17b70 457 { S(128), 103, 78, 51, 27, 2 },
1da177e4
LT
458
459 /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
9ed17b70 460 { S(64), 52, 39, 26, 14, 1 },
1da177e4
LT
461#endif
462};
463
1da177e4
LT
464/*
465 * Static global variables
466 */
a11e1d43 467static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
9a6f70bb 468static struct fasync_struct *fasync;
1da177e4 469
205a525c
HX
470static DEFINE_SPINLOCK(random_ready_list_lock);
471static LIST_HEAD(random_ready_list);
472
e192be9d
TT
473struct crng_state {
474 __u32 state[16];
475 unsigned long init_time;
476 spinlock_t lock;
477};
478
764ed189 479static struct crng_state primary_crng = {
e192be9d
TT
480 .lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
481};
482
483/*
484 * crng_init = 0 --> Uninitialized
485 * 1 --> Initialized
486 * 2 --> Initialized from input_pool
487 *
488 * crng_init is protected by primary_crng->lock, and only increases
489 * its value (from 0->1->2).
490 */
491static int crng_init = 0;
43838a23 492#define crng_ready() (likely(crng_init > 1))
e192be9d 493static int crng_init_cnt = 0;
d848e5f8 494static unsigned long crng_global_init_time = 0;
1ca1b917
EB
495#define CRNG_INIT_CNT_THRESH (2*CHACHA_KEY_SIZE)
496static void _extract_crng(struct crng_state *crng, __u8 out[CHACHA_BLOCK_SIZE]);
c92e040d 497static void _crng_backtrack_protect(struct crng_state *crng,
1ca1b917 498 __u8 tmp[CHACHA_BLOCK_SIZE], int used);
e192be9d 499static void process_random_ready_list(void);
eecabf56 500static void _get_random_bytes(void *buf, int nbytes);
e192be9d 501
4e00b339
TT
502static struct ratelimit_state unseeded_warning =
503 RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
504static struct ratelimit_state urandom_warning =
505 RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
506
507static int ratelimit_disable __read_mostly;
508
509module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
510MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
511
1da177e4
LT
512/**********************************************************************
513 *
514 * OS independent entropy store. Here are the functions which handle
515 * storing entropy in an entropy pool.
516 *
517 **********************************************************************/
518
519struct entropy_store;
520struct entropy_store {
43358209 521 /* read-only data: */
30e37ec5 522 const struct poolinfo *poolinfo;
1da177e4
LT
523 __u32 *pool;
524 const char *name;
1da177e4
LT
525
526 /* read-write data: */
43358209 527 spinlock_t lock;
c59974ae
TT
528 unsigned short add_ptr;
529 unsigned short input_rotate;
cda796a3 530 int entropy_count;
775f4b29 531 unsigned int initialized:1;
c59974ae 532 unsigned int last_data_init:1;
e954bc91 533 __u8 last_data[EXTRACT_SIZE];
1da177e4
LT
534};
535
e192be9d
TT
536static ssize_t extract_entropy(struct entropy_store *r, void *buf,
537 size_t nbytes, int min, int rsvd);
538static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
539 size_t nbytes, int fips);
540
541static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
0766f788 542static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
1da177e4
LT
543
544static struct entropy_store input_pool = {
545 .poolinfo = &poolinfo_table[0],
546 .name = "input",
eece09ec 547 .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
1da177e4
LT
548 .pool = input_pool_data
549};
550
775f4b29
TT
551static __u32 const twist_table[8] = {
552 0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
553 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
554
1da177e4 555/*
e68e5b66 556 * This function adds bytes into the entropy "pool". It does not
1da177e4 557 * update the entropy estimate. The caller should call
adc782da 558 * credit_entropy_bits if this is appropriate.
1da177e4
LT
559 *
560 * The pool is stirred with a primitive polynomial of the appropriate
561 * degree, and then twisted. We twist by three bits at a time because
562 * it's cheap to do so and helps slightly in the expected case where
563 * the entropy is concentrated in the low-order bits.
564 */
00ce1db1 565static void _mix_pool_bytes(struct entropy_store *r, const void *in,
85608f8e 566 int nbytes)
1da177e4 567{
85608f8e 568 unsigned long i, tap1, tap2, tap3, tap4, tap5;
feee7697 569 int input_rotate;
1da177e4 570 int wordmask = r->poolinfo->poolwords - 1;
e68e5b66 571 const char *bytes = in;
6d38b827 572 __u32 w;
1da177e4 573
1da177e4
LT
574 tap1 = r->poolinfo->tap1;
575 tap2 = r->poolinfo->tap2;
576 tap3 = r->poolinfo->tap3;
577 tap4 = r->poolinfo->tap4;
578 tap5 = r->poolinfo->tap5;
1da177e4 579
91fcb532
TT
580 input_rotate = r->input_rotate;
581 i = r->add_ptr;
1da177e4 582
e68e5b66
MM
583 /* mix one byte at a time to simplify size handling and churn faster */
584 while (nbytes--) {
c59974ae 585 w = rol32(*bytes++, input_rotate);
993ba211 586 i = (i - 1) & wordmask;
1da177e4
LT
587
588 /* XOR in the various taps */
993ba211 589 w ^= r->pool[i];
1da177e4
LT
590 w ^= r->pool[(i + tap1) & wordmask];
591 w ^= r->pool[(i + tap2) & wordmask];
592 w ^= r->pool[(i + tap3) & wordmask];
593 w ^= r->pool[(i + tap4) & wordmask];
594 w ^= r->pool[(i + tap5) & wordmask];
993ba211
MM
595
596 /* Mix the result back in with a twist */
1da177e4 597 r->pool[i] = (w >> 3) ^ twist_table[w & 7];
feee7697
MM
598
599 /*
600 * Normally, we add 7 bits of rotation to the pool.
601 * At the beginning of the pool, add an extra 7 bits
602 * rotation, so that successive passes spread the
603 * input bits across the pool evenly.
604 */
c59974ae 605 input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
1da177e4
LT
606 }
607
91fcb532
TT
608 r->input_rotate = input_rotate;
609 r->add_ptr = i;
1da177e4
LT
610}
611
00ce1db1 612static void __mix_pool_bytes(struct entropy_store *r, const void *in,
85608f8e 613 int nbytes)
00ce1db1
TT
614{
615 trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
85608f8e 616 _mix_pool_bytes(r, in, nbytes);
00ce1db1
TT
617}
618
619static void mix_pool_bytes(struct entropy_store *r, const void *in,
85608f8e 620 int nbytes)
1da177e4 621{
902c098a
TT
622 unsigned long flags;
623
00ce1db1 624 trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
902c098a 625 spin_lock_irqsave(&r->lock, flags);
85608f8e 626 _mix_pool_bytes(r, in, nbytes);
902c098a 627 spin_unlock_irqrestore(&r->lock, flags);
1da177e4
LT
628}
629
775f4b29
TT
630struct fast_pool {
631 __u32 pool[4];
632 unsigned long last;
ee3e00e9 633 unsigned short reg_idx;
840f9507 634 unsigned char count;
775f4b29
TT
635};
636
637/*
638 * This is a fast mixing routine used by the interrupt randomness
639 * collector. It's hardcoded for an 128 bit pool and assumes that any
640 * locks that might be needed are taken by the caller.
641 */
43759d4f 642static void fast_mix(struct fast_pool *f)
775f4b29 643{
43759d4f
TT
644 __u32 a = f->pool[0], b = f->pool[1];
645 __u32 c = f->pool[2], d = f->pool[3];
646
647 a += b; c += d;
19acc77a 648 b = rol32(b, 6); d = rol32(d, 27);
43759d4f
TT
649 d ^= a; b ^= c;
650
651 a += b; c += d;
19acc77a 652 b = rol32(b, 16); d = rol32(d, 14);
43759d4f
TT
653 d ^= a; b ^= c;
654
655 a += b; c += d;
19acc77a 656 b = rol32(b, 6); d = rol32(d, 27);
43759d4f
TT
657 d ^= a; b ^= c;
658
659 a += b; c += d;
19acc77a 660 b = rol32(b, 16); d = rol32(d, 14);
43759d4f
TT
661 d ^= a; b ^= c;
662
663 f->pool[0] = a; f->pool[1] = b;
664 f->pool[2] = c; f->pool[3] = d;
655b2264 665 f->count++;
775f4b29
TT
666}
667
205a525c
HX
668static void process_random_ready_list(void)
669{
670 unsigned long flags;
671 struct random_ready_callback *rdy, *tmp;
672
673 spin_lock_irqsave(&random_ready_list_lock, flags);
674 list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
675 struct module *owner = rdy->owner;
676
677 list_del_init(&rdy->list);
678 rdy->func(rdy);
679 module_put(owner);
680 }
681 spin_unlock_irqrestore(&random_ready_list_lock, flags);
682}
683
1da177e4 684/*
a283b5c4
PA
685 * Credit (or debit) the entropy store with n bits of entropy.
686 * Use credit_entropy_bits_safe() if the value comes from userspace
687 * or otherwise should be checked for extreme values.
1da177e4 688 */
adc782da 689static void credit_entropy_bits(struct entropy_store *r, int nbits)
1da177e4 690{
eb9d1bf0 691 int entropy_count, orig, has_initialized = 0;
30e37ec5
PA
692 const int pool_size = r->poolinfo->poolfracbits;
693 int nfrac = nbits << ENTROPY_SHIFT;
1da177e4 694
adc782da
MM
695 if (!nbits)
696 return;
697
902c098a 698retry:
6aa7de05 699 entropy_count = orig = READ_ONCE(r->entropy_count);
30e37ec5
PA
700 if (nfrac < 0) {
701 /* Debit */
702 entropy_count += nfrac;
703 } else {
704 /*
705 * Credit: we have to account for the possibility of
706 * overwriting already present entropy. Even in the
707 * ideal case of pure Shannon entropy, new contributions
708 * approach the full value asymptotically:
709 *
710 * entropy <- entropy + (pool_size - entropy) *
711 * (1 - exp(-add_entropy/pool_size))
712 *
713 * For add_entropy <= pool_size/2 then
714 * (1 - exp(-add_entropy/pool_size)) >=
715 * (add_entropy/pool_size)*0.7869...
716 * so we can approximate the exponential with
717 * 3/4*add_entropy/pool_size and still be on the
718 * safe side by adding at most pool_size/2 at a time.
719 *
720 * The use of pool_size-2 in the while statement is to
721 * prevent rounding artifacts from making the loop
722 * arbitrarily long; this limits the loop to log2(pool_size)*2
723 * turns no matter how large nbits is.
724 */
725 int pnfrac = nfrac;
726 const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
727 /* The +2 corresponds to the /4 in the denominator */
728
729 do {
730 unsigned int anfrac = min(pnfrac, pool_size/2);
731 unsigned int add =
732 ((pool_size - entropy_count)*anfrac*3) >> s;
733
734 entropy_count += add;
735 pnfrac -= anfrac;
736 } while (unlikely(entropy_count < pool_size-2 && pnfrac));
737 }
00ce1db1 738
870e05b1 739 if (WARN_ON(entropy_count < 0)) {
f80bbd8b
TT
740 pr_warn("random: negative entropy/overflow: pool %s count %d\n",
741 r->name, entropy_count);
8b76f46a 742 entropy_count = 0;
30e37ec5
PA
743 } else if (entropy_count > pool_size)
744 entropy_count = pool_size;
902c098a
TT
745 if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
746 goto retry;
1da177e4 747
58be0106 748 if (has_initialized) {
0891ad82 749 r->initialized = 1;
58be0106
TT
750 kill_fasync(&fasync, SIGIO, POLL_IN);
751 }
775f4b29 752
a283b5c4 753 trace_credit_entropy_bits(r->name, nbits,
eb9d1bf0 754 entropy_count >> ENTROPY_SHIFT, _RET_IP_);
00ce1db1 755
6265e169 756 if (r == &input_pool) {
7d1b08c4 757 int entropy_bits = entropy_count >> ENTROPY_SHIFT;
6265e169 758
eb9d1bf0
TT
759 if (crng_init < 2) {
760 if (entropy_bits < 128)
761 return;
e192be9d
TT
762 crng_reseed(&primary_crng, r);
763 entropy_bits = r->entropy_count >> ENTROPY_SHIFT;
764 }
9a6f70bb 765 }
1da177e4
LT
766}
767
86a574de 768static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
a283b5c4 769{
9f886f4d 770 const int nbits_max = r->poolinfo->poolwords * 32;
a283b5c4 771
86a574de
TT
772 if (nbits < 0)
773 return -EINVAL;
774
a283b5c4
PA
775 /* Cap the value to avoid overflows */
776 nbits = min(nbits, nbits_max);
a283b5c4
PA
777
778 credit_entropy_bits(r, nbits);
86a574de 779 return 0;
a283b5c4
PA
780}
781
e192be9d
TT
782/*********************************************************************
783 *
784 * CRNG using CHACHA20
785 *
786 *********************************************************************/
787
788#define CRNG_RESEED_INTERVAL (300*HZ)
789
790static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
791
1e7f583a
TT
792#ifdef CONFIG_NUMA
793/*
794 * Hack to deal with crazy userspace progams when they are all trying
795 * to access /dev/urandom in parallel. The programs are almost
796 * certainly doing something terribly wrong, but we'll work around
797 * their brain damage.
798 */
799static struct crng_state **crng_node_pool __read_mostly;
800#endif
801
b169c13d 802static void invalidate_batched_entropy(void);
fe6f1a6a 803static void numa_crng_init(void);
b169c13d 804
9b254366
KC
805static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
806static int __init parse_trust_cpu(char *arg)
807{
808 return kstrtobool(arg, &trust_cpu);
809}
810early_param("random.trust_cpu", parse_trust_cpu);
811
e192be9d
TT
812static void crng_initialize(struct crng_state *crng)
813{
814 int i;
39a8883a 815 int arch_init = 1;
e192be9d
TT
816 unsigned long rv;
817
818 memcpy(&crng->state[0], "expand 32-byte k", 16);
819 if (crng == &primary_crng)
820 _extract_entropy(&input_pool, &crng->state[4],
821 sizeof(__u32) * 12, 0);
822 else
eecabf56 823 _get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
e192be9d
TT
824 for (i = 4; i < 16; i++) {
825 if (!arch_get_random_seed_long(&rv) &&
39a8883a 826 !arch_get_random_long(&rv)) {
e192be9d 827 rv = random_get_entropy();
39a8883a
TT
828 arch_init = 0;
829 }
e192be9d
TT
830 crng->state[i] ^= rv;
831 }
fe6f1a6a
JD
832 if (trust_cpu && arch_init && crng == &primary_crng) {
833 invalidate_batched_entropy();
834 numa_crng_init();
39a8883a
TT
835 crng_init = 2;
836 pr_notice("random: crng done (trusting CPU's manufacturer)\n");
837 }
e192be9d
TT
838 crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
839}
840
8ef35c86 841#ifdef CONFIG_NUMA
6c1e851c 842static void do_numa_crng_init(struct work_struct *work)
8ef35c86
TT
843{
844 int i;
845 struct crng_state *crng;
846 struct crng_state **pool;
847
848 pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
849 for_each_online_node(i) {
850 crng = kmalloc_node(sizeof(struct crng_state),
851 GFP_KERNEL | __GFP_NOFAIL, i);
852 spin_lock_init(&crng->lock);
853 crng_initialize(crng);
854 pool[i] = crng;
855 }
856 mb();
857 if (cmpxchg(&crng_node_pool, NULL, pool)) {
858 for_each_node(i)
859 kfree(pool[i]);
860 kfree(pool);
861 }
862}
6c1e851c
TT
863
864static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init);
865
866static void numa_crng_init(void)
867{
868 schedule_work(&numa_crng_init_work);
869}
8ef35c86
TT
870#else
871static void numa_crng_init(void) {}
872#endif
873
dc12baac
TT
874/*
875 * crng_fast_load() can be called by code in the interrupt service
876 * path. So we can't afford to dilly-dally.
877 */
e192be9d
TT
878static int crng_fast_load(const char *cp, size_t len)
879{
880 unsigned long flags;
881 char *p;
882
883 if (!spin_trylock_irqsave(&primary_crng.lock, flags))
884 return 0;
43838a23 885 if (crng_init != 0) {
e192be9d
TT
886 spin_unlock_irqrestore(&primary_crng.lock, flags);
887 return 0;
888 }
889 p = (unsigned char *) &primary_crng.state[4];
890 while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
1ca1b917 891 p[crng_init_cnt % CHACHA_KEY_SIZE] ^= *cp;
e192be9d
TT
892 cp++; crng_init_cnt++; len--;
893 }
4a072c71 894 spin_unlock_irqrestore(&primary_crng.lock, flags);
e192be9d 895 if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
b169c13d 896 invalidate_batched_entropy();
e192be9d 897 crng_init = 1;
e192be9d
TT
898 pr_notice("random: fast init done\n");
899 }
e192be9d
TT
900 return 1;
901}
902
dc12baac
TT
903/*
904 * crng_slow_load() is called by add_device_randomness, which has two
905 * attributes. (1) We can't trust the buffer passed to it is
906 * guaranteed to be unpredictable (so it might not have any entropy at
907 * all), and (2) it doesn't have the performance constraints of
908 * crng_fast_load().
909 *
910 * So we do something more comprehensive which is guaranteed to touch
911 * all of the primary_crng's state, and which uses a LFSR with a
912 * period of 255 as part of the mixing algorithm. Finally, we do
913 * *not* advance crng_init_cnt since buffer we may get may be something
914 * like a fixed DMI table (for example), which might very well be
915 * unique to the machine, but is otherwise unvarying.
916 */
917static int crng_slow_load(const char *cp, size_t len)
918{
919 unsigned long flags;
920 static unsigned char lfsr = 1;
921 unsigned char tmp;
1ca1b917 922 unsigned i, max = CHACHA_KEY_SIZE;
dc12baac
TT
923 const char * src_buf = cp;
924 char * dest_buf = (char *) &primary_crng.state[4];
925
926 if (!spin_trylock_irqsave(&primary_crng.lock, flags))
927 return 0;
928 if (crng_init != 0) {
929 spin_unlock_irqrestore(&primary_crng.lock, flags);
930 return 0;
931 }
932 if (len > max)
933 max = len;
934
935 for (i = 0; i < max ; i++) {
936 tmp = lfsr;
937 lfsr >>= 1;
938 if (tmp & 1)
939 lfsr ^= 0xE1;
1ca1b917
EB
940 tmp = dest_buf[i % CHACHA_KEY_SIZE];
941 dest_buf[i % CHACHA_KEY_SIZE] ^= src_buf[i % len] ^ lfsr;
dc12baac
TT
942 lfsr += (tmp << 3) | (tmp >> 5);
943 }
944 spin_unlock_irqrestore(&primary_crng.lock, flags);
945 return 1;
946}
947
e192be9d
TT
948static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
949{
950 unsigned long flags;
951 int i, num;
952 union {
1ca1b917 953 __u8 block[CHACHA_BLOCK_SIZE];
e192be9d
TT
954 __u32 key[8];
955 } buf;
956
957 if (r) {
958 num = extract_entropy(r, &buf, 32, 16, 0);
959 if (num == 0)
960 return;
c92e040d 961 } else {
1e7f583a 962 _extract_crng(&primary_crng, buf.block);
c92e040d 963 _crng_backtrack_protect(&primary_crng, buf.block,
1ca1b917 964 CHACHA_KEY_SIZE);
c92e040d 965 }
0bb29a84 966 spin_lock_irqsave(&crng->lock, flags);
e192be9d
TT
967 for (i = 0; i < 8; i++) {
968 unsigned long rv;
969 if (!arch_get_random_seed_long(&rv) &&
970 !arch_get_random_long(&rv))
971 rv = random_get_entropy();
972 crng->state[i+4] ^= buf.key[i] ^ rv;
973 }
974 memzero_explicit(&buf, sizeof(buf));
975 crng->init_time = jiffies;
0bb29a84 976 spin_unlock_irqrestore(&crng->lock, flags);
e192be9d 977 if (crng == &primary_crng && crng_init < 2) {
b169c13d 978 invalidate_batched_entropy();
8ef35c86 979 numa_crng_init();
e192be9d
TT
980 crng_init = 2;
981 process_random_ready_list();
982 wake_up_interruptible(&crng_init_wait);
30c08efe 983 kill_fasync(&fasync, SIGIO, POLL_IN);
e192be9d 984 pr_notice("random: crng init done\n");
4e00b339
TT
985 if (unseeded_warning.missed) {
986 pr_notice("random: %d get_random_xx warning(s) missed "
987 "due to ratelimiting\n",
988 unseeded_warning.missed);
989 unseeded_warning.missed = 0;
990 }
991 if (urandom_warning.missed) {
992 pr_notice("random: %d urandom warning(s) missed "
993 "due to ratelimiting\n",
994 urandom_warning.missed);
995 urandom_warning.missed = 0;
996 }
e192be9d 997 }
e192be9d
TT
998}
999
1e7f583a 1000static void _extract_crng(struct crng_state *crng,
1ca1b917 1001 __u8 out[CHACHA_BLOCK_SIZE])
e192be9d
TT
1002{
1003 unsigned long v, flags;
e192be9d 1004
43838a23 1005 if (crng_ready() &&
d848e5f8
TT
1006 (time_after(crng_global_init_time, crng->init_time) ||
1007 time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL)))
1e7f583a 1008 crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
e192be9d
TT
1009 spin_lock_irqsave(&crng->lock, flags);
1010 if (arch_get_random_long(&v))
1011 crng->state[14] ^= v;
1012 chacha20_block(&crng->state[0], out);
1013 if (crng->state[12] == 0)
1014 crng->state[13]++;
1015 spin_unlock_irqrestore(&crng->lock, flags);
1016}
1017
1ca1b917 1018static void extract_crng(__u8 out[CHACHA_BLOCK_SIZE])
1e7f583a
TT
1019{
1020 struct crng_state *crng = NULL;
1021
1022#ifdef CONFIG_NUMA
1023 if (crng_node_pool)
1024 crng = crng_node_pool[numa_node_id()];
1025 if (crng == NULL)
1026#endif
1027 crng = &primary_crng;
1028 _extract_crng(crng, out);
1029}
1030
c92e040d
TT
1031/*
1032 * Use the leftover bytes from the CRNG block output (if there is
1033 * enough) to mutate the CRNG key to provide backtracking protection.
1034 */
1035static void _crng_backtrack_protect(struct crng_state *crng,
1ca1b917 1036 __u8 tmp[CHACHA_BLOCK_SIZE], int used)
c92e040d
TT
1037{
1038 unsigned long flags;
1039 __u32 *s, *d;
1040 int i;
1041
1042 used = round_up(used, sizeof(__u32));
1ca1b917 1043 if (used + CHACHA_KEY_SIZE > CHACHA_BLOCK_SIZE) {
c92e040d
TT
1044 extract_crng(tmp);
1045 used = 0;
1046 }
1047 spin_lock_irqsave(&crng->lock, flags);
a5e9f557 1048 s = (__u32 *) &tmp[used];
c92e040d
TT
1049 d = &crng->state[4];
1050 for (i=0; i < 8; i++)
1051 *d++ ^= *s++;
1052 spin_unlock_irqrestore(&crng->lock, flags);
1053}
1054
1ca1b917 1055static void crng_backtrack_protect(__u8 tmp[CHACHA_BLOCK_SIZE], int used)
c92e040d
TT
1056{
1057 struct crng_state *crng = NULL;
1058
1059#ifdef CONFIG_NUMA
1060 if (crng_node_pool)
1061 crng = crng_node_pool[numa_node_id()];
1062 if (crng == NULL)
1063#endif
1064 crng = &primary_crng;
1065 _crng_backtrack_protect(crng, tmp, used);
1066}
1067
e192be9d
TT
1068static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
1069{
1ca1b917
EB
1070 ssize_t ret = 0, i = CHACHA_BLOCK_SIZE;
1071 __u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
e192be9d
TT
1072 int large_request = (nbytes > 256);
1073
1074 while (nbytes) {
1075 if (large_request && need_resched()) {
1076 if (signal_pending(current)) {
1077 if (ret == 0)
1078 ret = -ERESTARTSYS;
1079 break;
1080 }
1081 schedule();
1082 }
1083
1084 extract_crng(tmp);
1ca1b917 1085 i = min_t(int, nbytes, CHACHA_BLOCK_SIZE);
e192be9d
TT
1086 if (copy_to_user(buf, tmp, i)) {
1087 ret = -EFAULT;
1088 break;
1089 }
1090
1091 nbytes -= i;
1092 buf += i;
1093 ret += i;
1094 }
c92e040d 1095 crng_backtrack_protect(tmp, i);
e192be9d
TT
1096
1097 /* Wipe data just written to memory */
1098 memzero_explicit(tmp, sizeof(tmp));
1099
1100 return ret;
1101}
1102
1103
1da177e4
LT
1104/*********************************************************************
1105 *
1106 * Entropy input management
1107 *
1108 *********************************************************************/
1109
1110/* There is one of these per entropy source */
1111struct timer_rand_state {
1112 cycles_t last_time;
90b75ee5 1113 long last_delta, last_delta2;
1da177e4
LT
1114};
1115
644008df
TT
1116#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
1117
a2080a67 1118/*
e192be9d
TT
1119 * Add device- or boot-specific data to the input pool to help
1120 * initialize it.
a2080a67 1121 *
e192be9d
TT
1122 * None of this adds any entropy; it is meant to avoid the problem of
1123 * the entropy pool having similar initial state across largely
1124 * identical devices.
a2080a67
LT
1125 */
1126void add_device_randomness(const void *buf, unsigned int size)
1127{
61875f30 1128 unsigned long time = random_get_entropy() ^ jiffies;
3ef4cb2d 1129 unsigned long flags;
a2080a67 1130
dc12baac
TT
1131 if (!crng_ready() && size)
1132 crng_slow_load(buf, size);
ee7998c5 1133
5910895f 1134 trace_add_device_randomness(size, _RET_IP_);
3ef4cb2d 1135 spin_lock_irqsave(&input_pool.lock, flags);
85608f8e
TT
1136 _mix_pool_bytes(&input_pool, buf, size);
1137 _mix_pool_bytes(&input_pool, &time, sizeof(time));
3ef4cb2d 1138 spin_unlock_irqrestore(&input_pool.lock, flags);
a2080a67
LT
1139}
1140EXPORT_SYMBOL(add_device_randomness);
1141
644008df 1142static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
3060d6fe 1143
1da177e4
LT
1144/*
1145 * This function adds entropy to the entropy "pool" by using timing
1146 * delays. It uses the timer_rand_state structure to make an estimate
1147 * of how many bits of entropy this call has added to the pool.
1148 *
1149 * The number "num" is also added to the pool - it should somehow describe
1150 * the type of event which just happened. This is currently 0-255 for
1151 * keyboard scan codes, and 256 upwards for interrupts.
1152 *
1153 */
1154static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
1155{
40db23e5 1156 struct entropy_store *r;
1da177e4 1157 struct {
1da177e4 1158 long jiffies;
cf833d0b 1159 unsigned cycles;
1da177e4
LT
1160 unsigned num;
1161 } sample;
1162 long delta, delta2, delta3;
1163
1da177e4 1164 sample.jiffies = jiffies;
61875f30 1165 sample.cycles = random_get_entropy();
1da177e4 1166 sample.num = num;
e192be9d 1167 r = &input_pool;
85608f8e 1168 mix_pool_bytes(r, &sample, sizeof(sample));
1da177e4
LT
1169
1170 /*
1171 * Calculate number of bits of randomness we probably added.
1172 * We take into account the first, second and third-order deltas
1173 * in order to make our estimate.
1174 */
5e747dd9
RV
1175 delta = sample.jiffies - state->last_time;
1176 state->last_time = sample.jiffies;
1177
1178 delta2 = delta - state->last_delta;
1179 state->last_delta = delta;
1180
1181 delta3 = delta2 - state->last_delta2;
1182 state->last_delta2 = delta2;
1183
1184 if (delta < 0)
1185 delta = -delta;
1186 if (delta2 < 0)
1187 delta2 = -delta2;
1188 if (delta3 < 0)
1189 delta3 = -delta3;
1190 if (delta > delta2)
1191 delta = delta2;
1192 if (delta > delta3)
1193 delta = delta3;
1da177e4 1194
5e747dd9
RV
1195 /*
1196 * delta is now minimum absolute delta.
1197 * Round down by 1 bit on general principles,
1198 * and limit entropy entimate to 12 bits.
1199 */
1200 credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
1da177e4
LT
1201}
1202
d251575a 1203void add_input_randomness(unsigned int type, unsigned int code,
1da177e4
LT
1204 unsigned int value)
1205{
1206 static unsigned char last_value;
1207
1208 /* ignore autorepeat and the like */
1209 if (value == last_value)
1210 return;
1211
1da177e4
LT
1212 last_value = value;
1213 add_timer_randomness(&input_timer_state,
1214 (type << 4) ^ code ^ (code >> 4) ^ value);
f80bbd8b 1215 trace_add_input_randomness(ENTROPY_BITS(&input_pool));
1da177e4 1216}
80fc9f53 1217EXPORT_SYMBOL_GPL(add_input_randomness);
1da177e4 1218
775f4b29
TT
1219static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
1220
43759d4f
TT
1221#ifdef ADD_INTERRUPT_BENCH
1222static unsigned long avg_cycles, avg_deviation;
1223
1224#define AVG_SHIFT 8 /* Exponential average factor k=1/256 */
1225#define FIXED_1_2 (1 << (AVG_SHIFT-1))
1226
1227static void add_interrupt_bench(cycles_t start)
1228{
1229 long delta = random_get_entropy() - start;
1230
1231 /* Use a weighted moving average */
1232 delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
1233 avg_cycles += delta;
1234 /* And average deviation */
1235 delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
1236 avg_deviation += delta;
1237}
1238#else
1239#define add_interrupt_bench(x)
1240#endif
1241
ee3e00e9
TT
1242static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
1243{
1244 __u32 *ptr = (__u32 *) regs;
92e75428 1245 unsigned int idx;
ee3e00e9
TT
1246
1247 if (regs == NULL)
1248 return 0;
92e75428
TT
1249 idx = READ_ONCE(f->reg_idx);
1250 if (idx >= sizeof(struct pt_regs) / sizeof(__u32))
1251 idx = 0;
1252 ptr += idx++;
1253 WRITE_ONCE(f->reg_idx, idx);
9dfa7bba 1254 return *ptr;
ee3e00e9
TT
1255}
1256
775f4b29 1257void add_interrupt_randomness(int irq, int irq_flags)
1da177e4 1258{
775f4b29 1259 struct entropy_store *r;
1b2a1a7e 1260 struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
775f4b29
TT
1261 struct pt_regs *regs = get_irq_regs();
1262 unsigned long now = jiffies;
655b2264 1263 cycles_t cycles = random_get_entropy();
43759d4f 1264 __u32 c_high, j_high;
655b2264 1265 __u64 ip;
83664a69 1266 unsigned long seed;
91fcb532 1267 int credit = 0;
3060d6fe 1268
ee3e00e9
TT
1269 if (cycles == 0)
1270 cycles = get_reg(fast_pool, regs);
655b2264
TT
1271 c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
1272 j_high = (sizeof(now) > 4) ? now >> 32 : 0;
43759d4f
TT
1273 fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
1274 fast_pool->pool[1] ^= now ^ c_high;
655b2264 1275 ip = regs ? instruction_pointer(regs) : _RET_IP_;
43759d4f 1276 fast_pool->pool[2] ^= ip;
ee3e00e9
TT
1277 fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
1278 get_reg(fast_pool, regs);
3060d6fe 1279
43759d4f 1280 fast_mix(fast_pool);
43759d4f 1281 add_interrupt_bench(cycles);
3060d6fe 1282
43838a23 1283 if (unlikely(crng_init == 0)) {
e192be9d
TT
1284 if ((fast_pool->count >= 64) &&
1285 crng_fast_load((char *) fast_pool->pool,
1286 sizeof(fast_pool->pool))) {
1287 fast_pool->count = 0;
1288 fast_pool->last = now;
1289 }
1290 return;
1291 }
1292
ee3e00e9
TT
1293 if ((fast_pool->count < 64) &&
1294 !time_after(now, fast_pool->last + HZ))
1da177e4
LT
1295 return;
1296
e192be9d 1297 r = &input_pool;
840f9507 1298 if (!spin_trylock(&r->lock))
91fcb532 1299 return;
83664a69 1300
91fcb532 1301 fast_pool->last = now;
85608f8e 1302 __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
83664a69
PA
1303
1304 /*
1305 * If we have architectural seed generator, produce a seed and
48d6be95
TT
1306 * add it to the pool. For the sake of paranoia don't let the
1307 * architectural seed generator dominate the input from the
1308 * interrupt noise.
83664a69
PA
1309 */
1310 if (arch_get_random_seed_long(&seed)) {
85608f8e 1311 __mix_pool_bytes(r, &seed, sizeof(seed));
48d6be95 1312 credit = 1;
83664a69 1313 }
91fcb532 1314 spin_unlock(&r->lock);
83664a69 1315
ee3e00e9 1316 fast_pool->count = 0;
83664a69 1317
ee3e00e9
TT
1318 /* award one bit for the contents of the fast pool */
1319 credit_entropy_bits(r, credit + 1);
1da177e4 1320}
4b44f2d1 1321EXPORT_SYMBOL_GPL(add_interrupt_randomness);
1da177e4 1322
9361401e 1323#ifdef CONFIG_BLOCK
1da177e4
LT
1324void add_disk_randomness(struct gendisk *disk)
1325{
1326 if (!disk || !disk->random)
1327 return;
1328 /* first major is 1, so we get >= 0x200 here */
f331c029 1329 add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
f80bbd8b 1330 trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
1da177e4 1331}
bdcfa3e5 1332EXPORT_SYMBOL_GPL(add_disk_randomness);
9361401e 1333#endif
1da177e4 1334
1da177e4
LT
1335/*********************************************************************
1336 *
1337 * Entropy extraction routines
1338 *
1339 *********************************************************************/
1340
1da177e4 1341/*
19fa5be1
GP
1342 * This function decides how many bytes to actually take from the
1343 * given pool, and also debits the entropy count accordingly.
1da177e4 1344 */
1da177e4
LT
1345static size_t account(struct entropy_store *r, size_t nbytes, int min,
1346 int reserved)
1347{
43d8a72c 1348 int entropy_count, orig, have_bytes;
79a84687 1349 size_t ibytes, nfrac;
1da177e4 1350
a283b5c4 1351 BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
1da177e4
LT
1352
1353 /* Can we pull enough? */
10b3a32d 1354retry:
6aa7de05 1355 entropy_count = orig = READ_ONCE(r->entropy_count);
a283b5c4 1356 ibytes = nbytes;
43d8a72c
SM
1357 /* never pull more than available */
1358 have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
e33ba5fa 1359
43d8a72c
SM
1360 if ((have_bytes -= reserved) < 0)
1361 have_bytes = 0;
1362 ibytes = min_t(size_t, ibytes, have_bytes);
0fb7a01a 1363 if (ibytes < min)
a283b5c4 1364 ibytes = 0;
79a84687 1365
870e05b1 1366 if (WARN_ON(entropy_count < 0)) {
79a84687
HFS
1367 pr_warn("random: negative entropy count: pool %s count %d\n",
1368 r->name, entropy_count);
79a84687
HFS
1369 entropy_count = 0;
1370 }
1371 nfrac = ibytes << (ENTROPY_SHIFT + 3);
1372 if ((size_t) entropy_count > nfrac)
1373 entropy_count -= nfrac;
1374 else
e33ba5fa 1375 entropy_count = 0;
f9c6d498 1376
0fb7a01a
GP
1377 if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
1378 goto retry;
1da177e4 1379
f80bbd8b 1380 trace_debit_entropy(r->name, 8 * ibytes);
0fb7a01a 1381 if (ibytes &&
2132a96f 1382 (r->entropy_count >> ENTROPY_SHIFT) < random_write_wakeup_bits) {
a11e1d43 1383 wake_up_interruptible(&random_write_wait);
b9809552
TT
1384 kill_fasync(&fasync, SIGIO, POLL_OUT);
1385 }
1386
a283b5c4 1387 return ibytes;
1da177e4
LT
1388}
1389
19fa5be1
GP
1390/*
1391 * This function does the actual extraction for extract_entropy and
1392 * extract_entropy_user.
1393 *
1394 * Note: we assume that .poolwords is a multiple of 16 words.
1395 */
1da177e4
LT
1396static void extract_buf(struct entropy_store *r, __u8 *out)
1397{
602b6aee 1398 int i;
d2e7c96a
PA
1399 union {
1400 __u32 w[5];
85a1f777 1401 unsigned long l[LONGS(20)];
d2e7c96a
PA
1402 } hash;
1403 __u32 workspace[SHA_WORKSPACE_WORDS];
902c098a 1404 unsigned long flags;
1da177e4 1405
85a1f777 1406 /*
dfd38750 1407 * If we have an architectural hardware random number
46884442 1408 * generator, use it for SHA's initial vector
85a1f777 1409 */
46884442 1410 sha_init(hash.w);
85a1f777
TT
1411 for (i = 0; i < LONGS(20); i++) {
1412 unsigned long v;
1413 if (!arch_get_random_long(&v))
1414 break;
46884442 1415 hash.l[i] = v;
85a1f777
TT
1416 }
1417
46884442
TT
1418 /* Generate a hash across the pool, 16 words (512 bits) at a time */
1419 spin_lock_irqsave(&r->lock, flags);
1420 for (i = 0; i < r->poolinfo->poolwords; i += 16)
1421 sha_transform(hash.w, (__u8 *)(r->pool + i), workspace);
1422
1da177e4 1423 /*
1c0ad3d4
MM
1424 * We mix the hash back into the pool to prevent backtracking
1425 * attacks (where the attacker knows the state of the pool
1426 * plus the current outputs, and attempts to find previous
1427 * ouputs), unless the hash function can be inverted. By
1428 * mixing at least a SHA1 worth of hash data back, we make
1429 * brute-forcing the feedback as hard as brute-forcing the
1430 * hash.
1da177e4 1431 */
85608f8e 1432 __mix_pool_bytes(r, hash.w, sizeof(hash.w));
902c098a 1433 spin_unlock_irqrestore(&r->lock, flags);
1da177e4 1434
d4c5efdb 1435 memzero_explicit(workspace, sizeof(workspace));
1da177e4
LT
1436
1437 /*
1c0ad3d4
MM
1438 * In case the hash function has some recognizable output
1439 * pattern, we fold it in half. Thus, we always feed back
1440 * twice as much data as we output.
1da177e4 1441 */
d2e7c96a
PA
1442 hash.w[0] ^= hash.w[3];
1443 hash.w[1] ^= hash.w[4];
1444 hash.w[2] ^= rol32(hash.w[2], 16);
1445
d2e7c96a 1446 memcpy(out, &hash, EXTRACT_SIZE);
d4c5efdb 1447 memzero_explicit(&hash, sizeof(hash));
1da177e4
LT
1448}
1449
e192be9d
TT
1450static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
1451 size_t nbytes, int fips)
1452{
1453 ssize_t ret = 0, i;
1454 __u8 tmp[EXTRACT_SIZE];
1455 unsigned long flags;
1456
1457 while (nbytes) {
1458 extract_buf(r, tmp);
1459
1460 if (fips) {
1461 spin_lock_irqsave(&r->lock, flags);
1462 if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
1463 panic("Hardware RNG duplicated output!\n");
1464 memcpy(r->last_data, tmp, EXTRACT_SIZE);
1465 spin_unlock_irqrestore(&r->lock, flags);
1466 }
1467 i = min_t(int, nbytes, EXTRACT_SIZE);
1468 memcpy(buf, tmp, i);
1469 nbytes -= i;
1470 buf += i;
1471 ret += i;
1472 }
1473
1474 /* Wipe data just returned from memory */
1475 memzero_explicit(tmp, sizeof(tmp));
1476
1477 return ret;
1478}
1479
19fa5be1
GP
1480/*
1481 * This function extracts randomness from the "entropy pool", and
1482 * returns it in a buffer.
1483 *
1484 * The min parameter specifies the minimum amount we can pull before
1485 * failing to avoid races that defeat catastrophic reseeding while the
1486 * reserved parameter indicates how much entropy we must leave in the
1487 * pool after each pull to avoid starving other readers.
1488 */
90b75ee5 1489static ssize_t extract_entropy(struct entropy_store *r, void *buf,
902c098a 1490 size_t nbytes, int min, int reserved)
1da177e4 1491{
1da177e4 1492 __u8 tmp[EXTRACT_SIZE];
1e7e2e05 1493 unsigned long flags;
1da177e4 1494
ec8f02da 1495 /* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
1e7e2e05
JW
1496 if (fips_enabled) {
1497 spin_lock_irqsave(&r->lock, flags);
1498 if (!r->last_data_init) {
c59974ae 1499 r->last_data_init = 1;
1e7e2e05
JW
1500 spin_unlock_irqrestore(&r->lock, flags);
1501 trace_extract_entropy(r->name, EXTRACT_SIZE,
a283b5c4 1502 ENTROPY_BITS(r), _RET_IP_);
1e7e2e05
JW
1503 extract_buf(r, tmp);
1504 spin_lock_irqsave(&r->lock, flags);
1505 memcpy(r->last_data, tmp, EXTRACT_SIZE);
1506 }
1507 spin_unlock_irqrestore(&r->lock, flags);
1508 }
ec8f02da 1509
a283b5c4 1510 trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
1da177e4
LT
1511 nbytes = account(r, nbytes, min, reserved);
1512
e192be9d 1513 return _extract_entropy(r, buf, nbytes, fips_enabled);
1da177e4
LT
1514}
1515
eecabf56
TT
1516#define warn_unseeded_randomness(previous) \
1517 _warn_unseeded_randomness(__func__, (void *) _RET_IP_, (previous))
1518
1519static void _warn_unseeded_randomness(const char *func_name, void *caller,
1520 void **previous)
1521{
1522#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
1523 const bool print_once = false;
1524#else
1525 static bool print_once __read_mostly;
1526#endif
1527
1528 if (print_once ||
1529 crng_ready() ||
1530 (previous && (caller == READ_ONCE(*previous))))
1531 return;
1532 WRITE_ONCE(*previous, caller);
1533#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
1534 print_once = true;
1535#endif
4e00b339 1536 if (__ratelimit(&unseeded_warning))
1b710b1b
SS
1537 printk_deferred(KERN_NOTICE "random: %s called from %pS "
1538 "with crng_init=%d\n", func_name, caller,
1539 crng_init);
eecabf56
TT
1540}
1541
1da177e4
LT
1542/*
1543 * This function is the exported kernel interface. It returns some
c2557a30 1544 * number of good random numbers, suitable for key generation, seeding
18e9cea7
GP
1545 * TCP sequence numbers, etc. It does not rely on the hardware random
1546 * number generator. For random bytes direct from the hardware RNG
e297a783
JD
1547 * (when available), use get_random_bytes_arch(). In order to ensure
1548 * that the randomness provided by this function is okay, the function
1549 * wait_for_random_bytes() should be called and return 0 at least once
1550 * at any point prior.
1da177e4 1551 */
eecabf56 1552static void _get_random_bytes(void *buf, int nbytes)
c2557a30 1553{
1ca1b917 1554 __u8 tmp[CHACHA_BLOCK_SIZE] __aligned(4);
e192be9d 1555
5910895f 1556 trace_get_random_bytes(nbytes, _RET_IP_);
e192be9d 1557
1ca1b917 1558 while (nbytes >= CHACHA_BLOCK_SIZE) {
e192be9d 1559 extract_crng(buf);
1ca1b917
EB
1560 buf += CHACHA_BLOCK_SIZE;
1561 nbytes -= CHACHA_BLOCK_SIZE;
e192be9d
TT
1562 }
1563
1564 if (nbytes > 0) {
1565 extract_crng(tmp);
1566 memcpy(buf, tmp, nbytes);
c92e040d
TT
1567 crng_backtrack_protect(tmp, nbytes);
1568 } else
1ca1b917 1569 crng_backtrack_protect(tmp, CHACHA_BLOCK_SIZE);
c92e040d 1570 memzero_explicit(tmp, sizeof(tmp));
c2557a30 1571}
eecabf56
TT
1572
1573void get_random_bytes(void *buf, int nbytes)
1574{
1575 static void *previous;
1576
1577 warn_unseeded_randomness(&previous);
1578 _get_random_bytes(buf, nbytes);
1579}
c2557a30
TT
1580EXPORT_SYMBOL(get_random_bytes);
1581
50ee7529
LT
1582
1583/*
1584 * Each time the timer fires, we expect that we got an unpredictable
1585 * jump in the cycle counter. Even if the timer is running on another
1586 * CPU, the timer activity will be touching the stack of the CPU that is
1587 * generating entropy..
1588 *
1589 * Note that we don't re-arm the timer in the timer itself - we are
1590 * happy to be scheduled away, since that just makes the load more
1591 * complex, but we do not want the timer to keep ticking unless the
1592 * entropy loop is running.
1593 *
1594 * So the re-arming always happens in the entropy loop itself.
1595 */
1596static void entropy_timer(struct timer_list *t)
1597{
1598 credit_entropy_bits(&input_pool, 1);
1599}
1600
1601/*
1602 * If we have an actual cycle counter, see if we can
1603 * generate enough entropy with timing noise
1604 */
1605static void try_to_generate_entropy(void)
1606{
1607 struct {
1608 unsigned long now;
1609 struct timer_list timer;
1610 } stack;
1611
1612 stack.now = random_get_entropy();
1613
1614 /* Slow counter - or none. Don't even bother */
1615 if (stack.now == random_get_entropy())
1616 return;
1617
1618 timer_setup_on_stack(&stack.timer, entropy_timer, 0);
1619 while (!crng_ready()) {
1620 if (!timer_pending(&stack.timer))
1621 mod_timer(&stack.timer, jiffies+1);
1622 mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
1623 schedule();
1624 stack.now = random_get_entropy();
1625 }
1626
1627 del_timer_sync(&stack.timer);
1628 destroy_timer_on_stack(&stack.timer);
1629 mix_pool_bytes(&input_pool, &stack.now, sizeof(stack.now));
1630}
1631
e297a783
JD
1632/*
1633 * Wait for the urandom pool to be seeded and thus guaranteed to supply
1634 * cryptographically secure random numbers. This applies to: the /dev/urandom
1635 * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1636 * family of functions. Using any of these functions without first calling
1637 * this function forfeits the guarantee of security.
1638 *
1639 * Returns: 0 if the urandom pool has been seeded.
1640 * -ERESTARTSYS if the function was interrupted by a signal.
1641 */
1642int wait_for_random_bytes(void)
1643{
1644 if (likely(crng_ready()))
1645 return 0;
50ee7529
LT
1646
1647 do {
1648 int ret;
1649 ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
1650 if (ret)
1651 return ret > 0 ? 0 : ret;
1652
1653 try_to_generate_entropy();
1654 } while (!crng_ready());
1655
1656 return 0;
e297a783
JD
1657}
1658EXPORT_SYMBOL(wait_for_random_bytes);
1659
9a47249d
JD
1660/*
1661 * Returns whether or not the urandom pool has been seeded and thus guaranteed
1662 * to supply cryptographically secure random numbers. This applies to: the
1663 * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
1664 * ,u64,int,long} family of functions.
1665 *
1666 * Returns: true if the urandom pool has been seeded.
1667 * false if the urandom pool has not been seeded.
1668 */
1669bool rng_is_initialized(void)
1670{
1671 return crng_ready();
1672}
1673EXPORT_SYMBOL(rng_is_initialized);
1674
205a525c
HX
1675/*
1676 * Add a callback function that will be invoked when the nonblocking
1677 * pool is initialised.
1678 *
1679 * returns: 0 if callback is successfully added
1680 * -EALREADY if pool is already initialised (callback not called)
1681 * -ENOENT if module for callback is not alive
1682 */
1683int add_random_ready_callback(struct random_ready_callback *rdy)
1684{
1685 struct module *owner;
1686 unsigned long flags;
1687 int err = -EALREADY;
1688
e192be9d 1689 if (crng_ready())
205a525c
HX
1690 return err;
1691
1692 owner = rdy->owner;
1693 if (!try_module_get(owner))
1694 return -ENOENT;
1695
1696 spin_lock_irqsave(&random_ready_list_lock, flags);
e192be9d 1697 if (crng_ready())
205a525c
HX
1698 goto out;
1699
1700 owner = NULL;
1701
1702 list_add(&rdy->list, &random_ready_list);
1703 err = 0;
1704
1705out:
1706 spin_unlock_irqrestore(&random_ready_list_lock, flags);
1707
1708 module_put(owner);
1709
1710 return err;
1711}
1712EXPORT_SYMBOL(add_random_ready_callback);
1713
1714/*
1715 * Delete a previously registered readiness callback function.
1716 */
1717void del_random_ready_callback(struct random_ready_callback *rdy)
1718{
1719 unsigned long flags;
1720 struct module *owner = NULL;
1721
1722 spin_lock_irqsave(&random_ready_list_lock, flags);
1723 if (!list_empty(&rdy->list)) {
1724 list_del_init(&rdy->list);
1725 owner = rdy->owner;
1726 }
1727 spin_unlock_irqrestore(&random_ready_list_lock, flags);
1728
1729 module_put(owner);
1730}
1731EXPORT_SYMBOL(del_random_ready_callback);
1732
c2557a30
TT
1733/*
1734 * This function will use the architecture-specific hardware random
1735 * number generator if it is available. The arch-specific hw RNG will
1736 * almost certainly be faster than what we can do in software, but it
1737 * is impossible to verify that it is implemented securely (as
1738 * opposed, to, say, the AES encryption of a sequence number using a
1739 * key known by the NSA). So it's useful if we need the speed, but
1740 * only if we're willing to trust the hardware manufacturer not to
1741 * have put in a back door.
753d433b
TH
1742 *
1743 * Return number of bytes filled in.
c2557a30 1744 */
753d433b 1745int __must_check get_random_bytes_arch(void *buf, int nbytes)
1da177e4 1746{
753d433b 1747 int left = nbytes;
63d77173
PA
1748 char *p = buf;
1749
753d433b
TH
1750 trace_get_random_bytes_arch(left, _RET_IP_);
1751 while (left) {
63d77173 1752 unsigned long v;
753d433b 1753 int chunk = min_t(int, left, sizeof(unsigned long));
c2557a30 1754
63d77173
PA
1755 if (!arch_get_random_long(&v))
1756 break;
8ddd6efa 1757
bd29e568 1758 memcpy(p, &v, chunk);
63d77173 1759 p += chunk;
753d433b 1760 left -= chunk;
63d77173
PA
1761 }
1762
753d433b 1763 return nbytes - left;
1da177e4 1764}
c2557a30
TT
1765EXPORT_SYMBOL(get_random_bytes_arch);
1766
1da177e4
LT
1767/*
1768 * init_std_data - initialize pool with system data
1769 *
1770 * @r: pool to initialize
1771 *
1772 * This function clears the pool's entropy count and mixes some system
1773 * data into the pool to prepare it for use. The pool is not cleared
1774 * as that can only decrease the entropy in the pool.
1775 */
d5553523 1776static void __init init_std_data(struct entropy_store *r)
1da177e4 1777{
3e88bdff 1778 int i;
902c098a
TT
1779 ktime_t now = ktime_get_real();
1780 unsigned long rv;
1da177e4 1781
85608f8e 1782 mix_pool_bytes(r, &now, sizeof(now));
9ed17b70 1783 for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
83664a69
PA
1784 if (!arch_get_random_seed_long(&rv) &&
1785 !arch_get_random_long(&rv))
ae9ecd92 1786 rv = random_get_entropy();
85608f8e 1787 mix_pool_bytes(r, &rv, sizeof(rv));
3e88bdff 1788 }
85608f8e 1789 mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
1da177e4
LT
1790}
1791
cbc96b75
TL
1792/*
1793 * Note that setup_arch() may call add_device_randomness()
1794 * long before we get here. This allows seeding of the pools
1795 * with some platform dependent data very early in the boot
1796 * process. But it limits our options here. We must use
1797 * statically allocated structures that already have all
1798 * initializations complete at compile time. We should also
1799 * take care not to overwrite the precious per platform data
1800 * we were given.
1801 */
d5553523 1802int __init rand_initialize(void)
1da177e4
LT
1803{
1804 init_std_data(&input_pool);
e192be9d 1805 crng_initialize(&primary_crng);
d848e5f8 1806 crng_global_init_time = jiffies;
4e00b339
TT
1807 if (ratelimit_disable) {
1808 urandom_warning.interval = 0;
1809 unseeded_warning.interval = 0;
1810 }
1da177e4
LT
1811 return 0;
1812}
1da177e4 1813
9361401e 1814#ifdef CONFIG_BLOCK
1da177e4
LT
1815void rand_initialize_disk(struct gendisk *disk)
1816{
1817 struct timer_rand_state *state;
1818
1819 /*
f8595815 1820 * If kzalloc returns null, we just won't use that entropy
1da177e4
LT
1821 * source.
1822 */
f8595815 1823 state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
644008df
TT
1824 if (state) {
1825 state->last_time = INITIAL_JIFFIES;
1da177e4 1826 disk->random = state;
644008df 1827 }
1da177e4 1828}
9361401e 1829#endif
1da177e4 1830
c6f1deb1
AL
1831static ssize_t
1832urandom_read_nowarn(struct file *file, char __user *buf, size_t nbytes,
1833 loff_t *ppos)
1834{
1835 int ret;
1836
1837 nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
1838 ret = extract_crng_user(buf, nbytes);
1839 trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
1840 return ret;
1841}
1842
1da177e4 1843static ssize_t
90b75ee5 1844urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1da177e4 1845{
e192be9d 1846 unsigned long flags;
9b4d0087 1847 static int maxwarn = 10;
301f0595 1848
e192be9d 1849 if (!crng_ready() && maxwarn > 0) {
9b4d0087 1850 maxwarn--;
4e00b339
TT
1851 if (__ratelimit(&urandom_warning))
1852 printk(KERN_NOTICE "random: %s: uninitialized "
1853 "urandom read (%zd bytes read)\n",
1854 current->comm, nbytes);
e192be9d
TT
1855 spin_lock_irqsave(&primary_crng.lock, flags);
1856 crng_init_cnt = 0;
1857 spin_unlock_irqrestore(&primary_crng.lock, flags);
9b4d0087 1858 }
c6f1deb1
AL
1859
1860 return urandom_read_nowarn(file, buf, nbytes, ppos);
1da177e4
LT
1861}
1862
30c08efe
AL
1863static ssize_t
1864random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1865{
1866 int ret;
1867
1868 ret = wait_for_random_bytes();
1869 if (ret != 0)
1870 return ret;
1871 return urandom_read_nowarn(file, buf, nbytes, ppos);
1872}
1873
afc9a42b 1874static __poll_t
a11e1d43 1875random_poll(struct file *file, poll_table * wait)
1da177e4 1876{
a11e1d43 1877 __poll_t mask;
1da177e4 1878
30c08efe 1879 poll_wait(file, &crng_init_wait, wait);
a11e1d43
LT
1880 poll_wait(file, &random_write_wait, wait);
1881 mask = 0;
30c08efe 1882 if (crng_ready())
a9a08845 1883 mask |= EPOLLIN | EPOLLRDNORM;
2132a96f 1884 if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
a9a08845 1885 mask |= EPOLLOUT | EPOLLWRNORM;
1da177e4
LT
1886 return mask;
1887}
1888
7f397dcd
MM
1889static int
1890write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
1da177e4 1891{
1da177e4 1892 size_t bytes;
81e69df3 1893 __u32 t, buf[16];
1da177e4 1894 const char __user *p = buffer;
1da177e4 1895
7f397dcd 1896 while (count > 0) {
81e69df3
TT
1897 int b, i = 0;
1898
7f397dcd
MM
1899 bytes = min(count, sizeof(buf));
1900 if (copy_from_user(&buf, p, bytes))
1901 return -EFAULT;
1da177e4 1902
81e69df3
TT
1903 for (b = bytes ; b > 0 ; b -= sizeof(__u32), i++) {
1904 if (!arch_get_random_int(&t))
1905 break;
1906 buf[i] ^= t;
1907 }
1908
7f397dcd 1909 count -= bytes;
1da177e4
LT
1910 p += bytes;
1911
85608f8e 1912 mix_pool_bytes(r, buf, bytes);
91f3f1e3 1913 cond_resched();
1da177e4 1914 }
7f397dcd
MM
1915
1916 return 0;
1917}
1918
90b75ee5
MM
1919static ssize_t random_write(struct file *file, const char __user *buffer,
1920 size_t count, loff_t *ppos)
7f397dcd
MM
1921{
1922 size_t ret;
7f397dcd 1923
e192be9d 1924 ret = write_pool(&input_pool, buffer, count);
7f397dcd
MM
1925 if (ret)
1926 return ret;
1927
7f397dcd 1928 return (ssize_t)count;
1da177e4
LT
1929}
1930
43ae4860 1931static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1da177e4
LT
1932{
1933 int size, ent_count;
1934 int __user *p = (int __user *)arg;
1935 int retval;
1936
1937 switch (cmd) {
1938 case RNDGETENTCNT:
43ae4860 1939 /* inherently racy, no point locking */
a283b5c4
PA
1940 ent_count = ENTROPY_BITS(&input_pool);
1941 if (put_user(ent_count, p))
1da177e4
LT
1942 return -EFAULT;
1943 return 0;
1944 case RNDADDTOENTCNT:
1945 if (!capable(CAP_SYS_ADMIN))
1946 return -EPERM;
1947 if (get_user(ent_count, p))
1948 return -EFAULT;
86a574de 1949 return credit_entropy_bits_safe(&input_pool, ent_count);
1da177e4
LT
1950 case RNDADDENTROPY:
1951 if (!capable(CAP_SYS_ADMIN))
1952 return -EPERM;
1953 if (get_user(ent_count, p++))
1954 return -EFAULT;
1955 if (ent_count < 0)
1956 return -EINVAL;
1957 if (get_user(size, p++))
1958 return -EFAULT;
7f397dcd
MM
1959 retval = write_pool(&input_pool, (const char __user *)p,
1960 size);
1da177e4
LT
1961 if (retval < 0)
1962 return retval;
86a574de 1963 return credit_entropy_bits_safe(&input_pool, ent_count);
1da177e4
LT
1964 case RNDZAPENTCNT:
1965 case RNDCLEARPOOL:
ae9ecd92
TT
1966 /*
1967 * Clear the entropy pool counters. We no longer clear
1968 * the entropy pool, as that's silly.
1969 */
1da177e4
LT
1970 if (!capable(CAP_SYS_ADMIN))
1971 return -EPERM;
ae9ecd92 1972 input_pool.entropy_count = 0;
1da177e4 1973 return 0;
d848e5f8
TT
1974 case RNDRESEEDCRNG:
1975 if (!capable(CAP_SYS_ADMIN))
1976 return -EPERM;
1977 if (crng_init < 2)
1978 return -ENODATA;
1979 crng_reseed(&primary_crng, NULL);
1980 crng_global_init_time = jiffies - 1;
1981 return 0;
1da177e4
LT
1982 default:
1983 return -EINVAL;
1984 }
1985}
1986
9a6f70bb
JD
1987static int random_fasync(int fd, struct file *filp, int on)
1988{
1989 return fasync_helper(fd, filp, on, &fasync);
1990}
1991
2b8693c0 1992const struct file_operations random_fops = {
1da177e4
LT
1993 .read = random_read,
1994 .write = random_write,
a11e1d43 1995 .poll = random_poll,
43ae4860 1996 .unlocked_ioctl = random_ioctl,
507e4e2b 1997 .compat_ioctl = compat_ptr_ioctl,
9a6f70bb 1998 .fasync = random_fasync,
6038f373 1999 .llseek = noop_llseek,
1da177e4
LT
2000};
2001
2b8693c0 2002const struct file_operations urandom_fops = {
1da177e4
LT
2003 .read = urandom_read,
2004 .write = random_write,
43ae4860 2005 .unlocked_ioctl = random_ioctl,
4aa37c46 2006 .compat_ioctl = compat_ptr_ioctl,
9a6f70bb 2007 .fasync = random_fasync,
6038f373 2008 .llseek = noop_llseek,
1da177e4
LT
2009};
2010
c6e9d6f3
TT
2011SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
2012 unsigned int, flags)
2013{
e297a783
JD
2014 int ret;
2015
75551dbf
AL
2016 if (flags & ~(GRND_NONBLOCK|GRND_RANDOM|GRND_INSECURE))
2017 return -EINVAL;
2018
2019 /*
2020 * Requesting insecure and blocking randomness at the same time makes
2021 * no sense.
2022 */
2023 if ((flags & (GRND_INSECURE|GRND_RANDOM)) == (GRND_INSECURE|GRND_RANDOM))
c6e9d6f3
TT
2024 return -EINVAL;
2025
2026 if (count > INT_MAX)
2027 count = INT_MAX;
2028
75551dbf 2029 if (!(flags & GRND_INSECURE) && !crng_ready()) {
c6e9d6f3
TT
2030 if (flags & GRND_NONBLOCK)
2031 return -EAGAIN;
e297a783
JD
2032 ret = wait_for_random_bytes();
2033 if (unlikely(ret))
2034 return ret;
c6e9d6f3 2035 }
c6f1deb1 2036 return urandom_read_nowarn(NULL, buf, count, NULL);
c6e9d6f3
TT
2037}
2038
1da177e4
LT
2039/********************************************************************
2040 *
2041 * Sysctl interface
2042 *
2043 ********************************************************************/
2044
2045#ifdef CONFIG_SYSCTL
2046
2047#include <linux/sysctl.h>
2048
c95ea0c6 2049static int min_write_thresh;
1da177e4 2050static int max_write_thresh = INPUT_POOL_WORDS * 32;
db61ffe3 2051static int random_min_urandom_seed = 60;
1da177e4
LT
2052static char sysctl_bootid[16];
2053
2054/*
f22052b2 2055 * This function is used to return both the bootid UUID, and random
1da177e4
LT
2056 * UUID. The difference is in whether table->data is NULL; if it is,
2057 * then a new UUID is generated and returned to the user.
2058 *
f22052b2
GP
2059 * If the user accesses this via the proc interface, the UUID will be
2060 * returned as an ASCII string in the standard UUID format; if via the
2061 * sysctl system call, as 16 bytes of binary data.
1da177e4 2062 */
a151427e 2063static int proc_do_uuid(struct ctl_table *table, int write,
1da177e4
LT
2064 void __user *buffer, size_t *lenp, loff_t *ppos)
2065{
a151427e 2066 struct ctl_table fake_table;
1da177e4
LT
2067 unsigned char buf[64], tmp_uuid[16], *uuid;
2068
2069 uuid = table->data;
2070 if (!uuid) {
2071 uuid = tmp_uuid;
1da177e4 2072 generate_random_uuid(uuid);
44e4360f
MD
2073 } else {
2074 static DEFINE_SPINLOCK(bootid_spinlock);
2075
2076 spin_lock(&bootid_spinlock);
2077 if (!uuid[8])
2078 generate_random_uuid(uuid);
2079 spin_unlock(&bootid_spinlock);
2080 }
1da177e4 2081
35900771
JP
2082 sprintf(buf, "%pU", uuid);
2083
1da177e4
LT
2084 fake_table.data = buf;
2085 fake_table.maxlen = sizeof(buf);
2086
8d65af78 2087 return proc_dostring(&fake_table, write, buffer, lenp, ppos);
1da177e4
LT
2088}
2089
a283b5c4
PA
2090/*
2091 * Return entropy available scaled to integral bits
2092 */
5eb10d91 2093static int proc_do_entropy(struct ctl_table *table, int write,
a283b5c4
PA
2094 void __user *buffer, size_t *lenp, loff_t *ppos)
2095{
5eb10d91 2096 struct ctl_table fake_table;
a283b5c4
PA
2097 int entropy_count;
2098
2099 entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
2100
2101 fake_table.data = &entropy_count;
2102 fake_table.maxlen = sizeof(entropy_count);
2103
2104 return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
2105}
2106
1da177e4 2107static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
a151427e
JP
2108extern struct ctl_table random_table[];
2109struct ctl_table random_table[] = {
1da177e4 2110 {
1da177e4
LT
2111 .procname = "poolsize",
2112 .data = &sysctl_poolsize,
2113 .maxlen = sizeof(int),
2114 .mode = 0444,
6d456111 2115 .proc_handler = proc_dointvec,
1da177e4
LT
2116 },
2117 {
1da177e4
LT
2118 .procname = "entropy_avail",
2119 .maxlen = sizeof(int),
2120 .mode = 0444,
a283b5c4 2121 .proc_handler = proc_do_entropy,
1da177e4
LT
2122 .data = &input_pool.entropy_count,
2123 },
1da177e4 2124 {
1da177e4 2125 .procname = "write_wakeup_threshold",
2132a96f 2126 .data = &random_write_wakeup_bits,
1da177e4
LT
2127 .maxlen = sizeof(int),
2128 .mode = 0644,
6d456111 2129 .proc_handler = proc_dointvec_minmax,
1da177e4
LT
2130 .extra1 = &min_write_thresh,
2131 .extra2 = &max_write_thresh,
2132 },
f5c2742c
TT
2133 {
2134 .procname = "urandom_min_reseed_secs",
2135 .data = &random_min_urandom_seed,
2136 .maxlen = sizeof(int),
2137 .mode = 0644,
2138 .proc_handler = proc_dointvec,
2139 },
1da177e4 2140 {
1da177e4
LT
2141 .procname = "boot_id",
2142 .data = &sysctl_bootid,
2143 .maxlen = 16,
2144 .mode = 0444,
6d456111 2145 .proc_handler = proc_do_uuid,
1da177e4
LT
2146 },
2147 {
1da177e4
LT
2148 .procname = "uuid",
2149 .maxlen = 16,
2150 .mode = 0444,
6d456111 2151 .proc_handler = proc_do_uuid,
1da177e4 2152 },
43759d4f
TT
2153#ifdef ADD_INTERRUPT_BENCH
2154 {
2155 .procname = "add_interrupt_avg_cycles",
2156 .data = &avg_cycles,
2157 .maxlen = sizeof(avg_cycles),
2158 .mode = 0444,
2159 .proc_handler = proc_doulongvec_minmax,
2160 },
2161 {
2162 .procname = "add_interrupt_avg_deviation",
2163 .data = &avg_deviation,
2164 .maxlen = sizeof(avg_deviation),
2165 .mode = 0444,
2166 .proc_handler = proc_doulongvec_minmax,
2167 },
2168#endif
894d2491 2169 { }
1da177e4
LT
2170};
2171#endif /* CONFIG_SYSCTL */
2172
f5b98461
JD
2173struct batched_entropy {
2174 union {
1ca1b917
EB
2175 u64 entropy_u64[CHACHA_BLOCK_SIZE / sizeof(u64)];
2176 u32 entropy_u32[CHACHA_BLOCK_SIZE / sizeof(u32)];
f5b98461
JD
2177 };
2178 unsigned int position;
b7d5dc21 2179 spinlock_t batch_lock;
f5b98461 2180};
b1132dea 2181
1da177e4 2182/*
f5b98461
JD
2183 * Get a random word for internal kernel use only. The quality of the random
2184 * number is either as good as RDRAND or as good as /dev/urandom, with the
e297a783
JD
2185 * goal of being quite fast and not depleting entropy. In order to ensure
2186 * that the randomness provided by this function is okay, the function
2187 * wait_for_random_bytes() should be called and return 0 at least once
2188 * at any point prior.
1da177e4 2189 */
b7d5dc21
SAS
2190static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
2191 .batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u64.lock),
2192};
2193
c440408c 2194u64 get_random_u64(void)
1da177e4 2195{
c440408c 2196 u64 ret;
b7d5dc21 2197 unsigned long flags;
f5b98461 2198 struct batched_entropy *batch;
eecabf56 2199 static void *previous;
8a0a9bd4 2200
c440408c
JD
2201#if BITS_PER_LONG == 64
2202 if (arch_get_random_long((unsigned long *)&ret))
63d77173 2203 return ret;
c440408c
JD
2204#else
2205 if (arch_get_random_long((unsigned long *)&ret) &&
2206 arch_get_random_long((unsigned long *)&ret + 1))
2207 return ret;
2208#endif
63d77173 2209
eecabf56 2210 warn_unseeded_randomness(&previous);
d06bfd19 2211
b7d5dc21
SAS
2212 batch = raw_cpu_ptr(&batched_entropy_u64);
2213 spin_lock_irqsave(&batch->batch_lock, flags);
c440408c 2214 if (batch->position % ARRAY_SIZE(batch->entropy_u64) == 0) {
a5e9f557 2215 extract_crng((u8 *)batch->entropy_u64);
f5b98461
JD
2216 batch->position = 0;
2217 }
c440408c 2218 ret = batch->entropy_u64[batch->position++];
b7d5dc21 2219 spin_unlock_irqrestore(&batch->batch_lock, flags);
8a0a9bd4 2220 return ret;
1da177e4 2221}
c440408c 2222EXPORT_SYMBOL(get_random_u64);
1da177e4 2223
b7d5dc21
SAS
2224static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
2225 .batch_lock = __SPIN_LOCK_UNLOCKED(batched_entropy_u32.lock),
2226};
c440408c 2227u32 get_random_u32(void)
f5b98461 2228{
c440408c 2229 u32 ret;
b7d5dc21 2230 unsigned long flags;
f5b98461 2231 struct batched_entropy *batch;
eecabf56 2232 static void *previous;
ec9ee4ac 2233
f5b98461 2234 if (arch_get_random_int(&ret))
ec9ee4ac
DC
2235 return ret;
2236
eecabf56 2237 warn_unseeded_randomness(&previous);
d06bfd19 2238
b7d5dc21
SAS
2239 batch = raw_cpu_ptr(&batched_entropy_u32);
2240 spin_lock_irqsave(&batch->batch_lock, flags);
c440408c 2241 if (batch->position % ARRAY_SIZE(batch->entropy_u32) == 0) {
a5e9f557 2242 extract_crng((u8 *)batch->entropy_u32);
f5b98461
JD
2243 batch->position = 0;
2244 }
c440408c 2245 ret = batch->entropy_u32[batch->position++];
b7d5dc21 2246 spin_unlock_irqrestore(&batch->batch_lock, flags);
ec9ee4ac
DC
2247 return ret;
2248}
c440408c 2249EXPORT_SYMBOL(get_random_u32);
ec9ee4ac 2250
b169c13d
JD
2251/* It's important to invalidate all potential batched entropy that might
2252 * be stored before the crng is initialized, which we can do lazily by
2253 * simply resetting the counter to zero so that it's re-extracted on the
2254 * next usage. */
2255static void invalidate_batched_entropy(void)
2256{
2257 int cpu;
2258 unsigned long flags;
2259
b169c13d 2260 for_each_possible_cpu (cpu) {
b7d5dc21
SAS
2261 struct batched_entropy *batched_entropy;
2262
2263 batched_entropy = per_cpu_ptr(&batched_entropy_u32, cpu);
2264 spin_lock_irqsave(&batched_entropy->batch_lock, flags);
2265 batched_entropy->position = 0;
2266 spin_unlock(&batched_entropy->batch_lock);
2267
2268 batched_entropy = per_cpu_ptr(&batched_entropy_u64, cpu);
2269 spin_lock(&batched_entropy->batch_lock);
2270 batched_entropy->position = 0;
2271 spin_unlock_irqrestore(&batched_entropy->batch_lock, flags);
b169c13d 2272 }
b169c13d
JD
2273}
2274
99fdafde
JC
2275/**
2276 * randomize_page - Generate a random, page aligned address
2277 * @start: The smallest acceptable address the caller will take.
2278 * @range: The size of the area, starting at @start, within which the
2279 * random address must fall.
2280 *
2281 * If @start + @range would overflow, @range is capped.
2282 *
2283 * NOTE: Historical use of randomize_range, which this replaces, presumed that
2284 * @start was already page aligned. We now align it regardless.
2285 *
2286 * Return: A page aligned address within [start, start + range). On error,
2287 * @start is returned.
2288 */
2289unsigned long
2290randomize_page(unsigned long start, unsigned long range)
2291{
2292 if (!PAGE_ALIGNED(start)) {
2293 range -= PAGE_ALIGN(start) - start;
2294 start = PAGE_ALIGN(start);
2295 }
2296
2297 if (start > ULONG_MAX - range)
2298 range = ULONG_MAX - start;
2299
2300 range >>= PAGE_SHIFT;
2301
2302 if (range == 0)
2303 return start;
2304
2305 return start + (get_random_long() % range << PAGE_SHIFT);
2306}
2307
c84dbf61
TD
2308/* Interface for in-kernel drivers of true hardware RNGs.
2309 * Those devices may produce endless random bits and will be throttled
2310 * when our pool is full.
2311 */
2312void add_hwgenerator_randomness(const char *buffer, size_t count,
2313 size_t entropy)
2314{
2315 struct entropy_store *poolp = &input_pool;
2316
43838a23 2317 if (unlikely(crng_init == 0)) {
e192be9d
TT
2318 crng_fast_load(buffer, count);
2319 return;
3371f3da 2320 }
e192be9d
TT
2321
2322 /* Suspend writing if we're above the trickle threshold.
2323 * We'll be woken up again once below random_write_wakeup_thresh,
2324 * or when the calling thread is about to terminate.
2325 */
08e97aec 2326 wait_event_interruptible(random_write_wait, kthread_should_stop() ||
e192be9d 2327 ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
c84dbf61
TD
2328 mix_pool_bytes(poolp, buffer, count);
2329 credit_entropy_bits(poolp, entropy);
2330}
2331EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
428826f5
HYW
2332
2333/* Handle random seed passed by bootloader.
2334 * If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
2335 * it would be regarded as device data.
2336 * The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
2337 */
2338void add_bootloader_randomness(const void *buf, unsigned int size)
2339{
2340 if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
2341 add_hwgenerator_randomness(buf, size, size * 8);
2342 else
2343 add_device_randomness(buf, size);
2344}
3fd57e7a 2345EXPORT_SYMBOL_GPL(add_bootloader_randomness);