random: remove useless header comment
[linux-block.git] / drivers / char / random.c
CommitLineData
a07fdae3 1// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
1da177e4 2/*
9f9eff85 3 * Copyright (C) 2017-2022 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
9e95ce27 4 * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
1da177e4
LT
5 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All
6 * rights reserved.
1da177e4
LT
7 */
8
9/*
1da177e4
LT
10 * Exported interfaces ---- output
11 * ===============================
12 *
92e507d2 13 * There are four exported interfaces; two for use within the kernel,
c0a8a61e 14 * and two for use from userspace.
1da177e4 15 *
92e507d2
GS
16 * Exported interfaces ---- userspace output
17 * -----------------------------------------
1da177e4 18 *
92e507d2 19 * The userspace interfaces are two character devices /dev/random and
1da177e4
LT
20 * /dev/urandom. /dev/random is suitable for use when very high
21 * quality randomness is desired (for example, for key generation or
22 * one-time pads), as it will only return a maximum of the number of
23 * bits of randomness (as estimated by the random number generator)
24 * contained in the entropy pool.
25 *
26 * The /dev/urandom device does not have this limit, and will return
27 * as many bytes as are requested. As more and more random bytes are
28 * requested without giving time for the entropy pool to recharge,
29 * this will result in random numbers that are merely cryptographically
30 * strong. For many applications, however, this is acceptable.
31 *
92e507d2
GS
32 * Exported interfaces ---- kernel output
33 * --------------------------------------
34 *
186873c5 35 * The primary kernel interfaces are:
92e507d2 36 *
04ec96b7 37 * void get_random_bytes(void *buf, size_t nbytes);
248045b8
JD
38 * u32 get_random_u32()
39 * u64 get_random_u64()
40 * unsigned int get_random_int()
41 * unsigned long get_random_long()
92e507d2 42 *
186873c5
JD
43 * These interfaces will return the requested number of random bytes
44 * into the given buffer or as a return value. This is equivalent to a
45 * read from /dev/urandom. The get_random_{u32,u64,int,long}() family
46 * of functions may be higher performance for one-off random integers,
47 * because they do a bit of buffering.
92e507d2
GS
48 *
49 * prandom_u32()
50 * -------------
51 *
52 * For even weaker applications, see the pseudorandom generator
53 * prandom_u32(), prandom_max(), and prandom_bytes(). If the random
54 * numbers aren't security-critical at all, these are *far* cheaper.
55 * Useful for self-tests, random error simulation, randomized backoffs,
56 * and any other application where you trust that nobody is trying to
57 * maliciously mess with you by guessing the "random" numbers.
58 *
1da177e4
LT
59 * Exported interfaces ---- input
60 * ==============================
61 *
62 * The current exported interfaces for gathering environmental noise
63 * from the devices are:
64 *
04ec96b7 65 * void add_device_randomness(const void *buf, size_t size);
248045b8 66 * void add_input_randomness(unsigned int type, unsigned int code,
1da177e4 67 * unsigned int value);
703f7066 68 * void add_interrupt_randomness(int irq);
248045b8 69 * void add_disk_randomness(struct gendisk *disk);
04ec96b7 70 * void add_hwgenerator_randomness(const void *buffer, size_t count,
2b6c6e3d 71 * size_t entropy);
04ec96b7 72 * void add_bootloader_randomness(const void *buf, size_t size);
1da177e4 73 *
a2080a67
LT
74 * add_device_randomness() is for adding data to the random pool that
75 * is likely to differ between two devices (or possibly even per boot).
76 * This would be things like MAC addresses or serial numbers, or the
77 * read-out of the RTC. This does *not* add any actual entropy to the
78 * pool, but it initializes the pool to different values for devices
79 * that might otherwise be identical and have very little entropy
80 * available to them (particularly common in the embedded world).
81 *
1da177e4
LT
82 * add_input_randomness() uses the input layer interrupt timing, as well as
83 * the event type information from the hardware.
84 *
775f4b29
TT
85 * add_interrupt_randomness() uses the interrupt timing as random
86 * inputs to the entropy pool. Using the cycle counters and the irq source
87 * as inputs, it feeds the randomness roughly once a second.
442a4fff
JW
88 *
89 * add_disk_randomness() uses what amounts to the seek time of block
90 * layer request events, on a per-disk_devt basis, as input to the
91 * entropy pool. Note that high-speed solid state drives with very low
92 * seek times do not make for good sources of entropy, as their seek
93 * times are usually fairly consistent.
1da177e4
LT
94 *
95 * All of these routines try to estimate how many bits of randomness a
96 * particular randomness source. They do this by keeping track of the
97 * first and second order deltas of the event timings.
98 *
2b6c6e3d
MB
99 * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
100 * entropy as specified by the caller. If the entropy pool is full it will
101 * block until more entropy is needed.
102 *
103 * add_bootloader_randomness() is the same as add_hwgenerator_randomness() or
104 * add_device_randomness(), depending on whether or not the configuration
105 * option CONFIG_RANDOM_TRUST_BOOTLOADER is set.
106 *
1da177e4
LT
107 * Ensuring unpredictability at system startup
108 * ============================================
109 *
110 * When any operating system starts up, it will go through a sequence
111 * of actions that are fairly predictable by an adversary, especially
112 * if the start-up does not involve interaction with a human operator.
113 * This reduces the actual number of bits of unpredictability in the
114 * entropy pool below the value in entropy_count. In order to
115 * counteract this effect, it helps to carry information in the
116 * entropy pool across shut-downs and start-ups. To do this, put the
117 * following lines an appropriate script which is run during the boot
118 * sequence:
119 *
120 * echo "Initializing random number generator..."
121 * random_seed=/var/run/random-seed
122 * # Carry a random seed from start-up to start-up
123 * # Load and then save the whole entropy pool
124 * if [ -f $random_seed ]; then
125 * cat $random_seed >/dev/urandom
126 * else
127 * touch $random_seed
128 * fi
129 * chmod 600 $random_seed
130 * dd if=/dev/urandom of=$random_seed count=1 bs=512
131 *
132 * and the following lines in an appropriate script which is run as
133 * the system is shutdown:
134 *
135 * # Carry a random seed from shut-down to start-up
136 * # Save the whole entropy pool
137 * echo "Saving random seed..."
138 * random_seed=/var/run/random-seed
139 * touch $random_seed
140 * chmod 600 $random_seed
141 * dd if=/dev/urandom of=$random_seed count=1 bs=512
142 *
143 * For example, on most modern systems using the System V init
144 * scripts, such code fragments would be found in
145 * /etc/rc.d/init.d/random. On older Linux systems, the correct script
146 * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
147 *
148 * Effectively, these commands cause the contents of the entropy pool
149 * to be saved at shut-down time and reloaded into the entropy pool at
150 * start-up. (The 'dd' in the addition to the bootup script is to
151 * make sure that /etc/random-seed is different for every start-up,
152 * even if the system crashes without executing rc.0.) Even with
153 * complete knowledge of the start-up activities, predicting the state
154 * of the entropy pool requires knowledge of the previous history of
155 * the system.
156 *
157 * Configuring the /dev/random driver under Linux
158 * ==============================================
159 *
160 * The /dev/random driver under Linux uses minor numbers 8 and 9 of
161 * the /dev/mem major number (#1). So if your system does not have
162 * /dev/random and /dev/urandom created already, they can be created
163 * by using the commands:
164 *
248045b8
JD
165 * mknod /dev/random c 1 8
166 * mknod /dev/urandom c 1 9
1da177e4
LT
167 */
168
12cd53af
YL
169#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
170
1da177e4 171#include <linux/utsname.h>
1da177e4
LT
172#include <linux/module.h>
173#include <linux/kernel.h>
174#include <linux/major.h>
175#include <linux/string.h>
176#include <linux/fcntl.h>
177#include <linux/slab.h>
178#include <linux/random.h>
179#include <linux/poll.h>
180#include <linux/init.h>
181#include <linux/fs.h>
182#include <linux/genhd.h>
183#include <linux/interrupt.h>
27ac792c 184#include <linux/mm.h>
dd0f0cf5 185#include <linux/nodemask.h>
1da177e4 186#include <linux/spinlock.h>
c84dbf61 187#include <linux/kthread.h>
1da177e4 188#include <linux/percpu.h>
775f4b29 189#include <linux/ptrace.h>
6265e169 190#include <linux/workqueue.h>
0244ad00 191#include <linux/irq.h>
4e00b339 192#include <linux/ratelimit.h>
c6e9d6f3
TT
193#include <linux/syscalls.h>
194#include <linux/completion.h>
8da4b8c4 195#include <linux/uuid.h>
1ca1b917 196#include <crypto/chacha.h>
9f9eff85 197#include <crypto/blake2s.h>
d178a1eb 198
1da177e4 199#include <asm/processor.h>
7c0f6ba6 200#include <linux/uaccess.h>
1da177e4 201#include <asm/irq.h>
775f4b29 202#include <asm/irq_regs.h>
1da177e4
LT
203#include <asm/io.h>
204
c5704490 205enum {
6e8ec255 206 POOL_BITS = BLAKE2S_HASH_SIZE * 8,
c5704490 207 POOL_MIN_BITS = POOL_BITS /* No point in settling for less. */
1da177e4
LT
208};
209
1da177e4
LT
210/*
211 * Static global variables
212 */
a11e1d43 213static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
9a6f70bb 214static struct fasync_struct *fasync;
1da177e4 215
205a525c
HX
216static DEFINE_SPINLOCK(random_ready_list_lock);
217static LIST_HEAD(random_ready_list);
218
e192be9d
TT
219/*
220 * crng_init = 0 --> Uninitialized
221 * 1 --> Initialized
222 * 2 --> Initialized from input_pool
223 *
224 * crng_init is protected by primary_crng->lock, and only increases
225 * its value (from 0->1->2).
226 */
227static int crng_init = 0;
43838a23 228#define crng_ready() (likely(crng_init > 1))
e192be9d 229static int crng_init_cnt = 0;
e192be9d 230static void process_random_ready_list(void);
04ec96b7 231static void _get_random_bytes(void *buf, size_t nbytes);
e192be9d 232
4e00b339
TT
233static struct ratelimit_state unseeded_warning =
234 RATELIMIT_STATE_INIT("warn_unseeded_randomness", HZ, 3);
235static struct ratelimit_state urandom_warning =
236 RATELIMIT_STATE_INIT("warn_urandom_randomness", HZ, 3);
237
238static int ratelimit_disable __read_mostly;
239
240module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
241MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
242
1da177e4
LT
243/**********************************************************************
244 *
245 * OS independent entropy store. Here are the functions which handle
246 * storing entropy in an entropy pool.
247 *
248 **********************************************************************/
249
90ed1e67 250static struct {
6e8ec255 251 struct blake2s_state hash;
43358209 252 spinlock_t lock;
04ec96b7 253 unsigned int entropy_count;
90ed1e67 254} input_pool = {
6e8ec255
JD
255 .hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
256 BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
257 BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
258 .hash.outlen = BLAKE2S_HASH_SIZE,
eece09ec 259 .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
1da177e4
LT
260};
261
9c07f578 262static void extract_entropy(void *buf, size_t nbytes);
246c03dd 263static bool drain_entropy(void *buf, size_t nbytes);
90ed1e67 264
a9412d51 265static void crng_reseed(void);
90ed1e67 266
1da177e4 267/*
e68e5b66 268 * This function adds bytes into the entropy "pool". It does not
1da177e4 269 * update the entropy estimate. The caller should call
adc782da 270 * credit_entropy_bits if this is appropriate.
1da177e4 271 */
04ec96b7 272static void _mix_pool_bytes(const void *in, size_t nbytes)
1da177e4 273{
6e8ec255 274 blake2s_update(&input_pool.hash, in, nbytes);
1da177e4
LT
275}
276
04ec96b7 277static void mix_pool_bytes(const void *in, size_t nbytes)
1da177e4 278{
902c098a
TT
279 unsigned long flags;
280
90ed1e67
JD
281 spin_lock_irqsave(&input_pool.lock, flags);
282 _mix_pool_bytes(in, nbytes);
283 spin_unlock_irqrestore(&input_pool.lock, flags);
1da177e4
LT
284}
285
775f4b29 286struct fast_pool {
b2f408fe
JD
287 union {
288 u32 pool32[4];
289 u64 pool64[2];
290 };
248045b8
JD
291 unsigned long last;
292 u16 reg_idx;
293 u8 count;
775f4b29
TT
294};
295
296/*
297 * This is a fast mixing routine used by the interrupt randomness
298 * collector. It's hardcoded for an 128 bit pool and assumes that any
299 * locks that might be needed are taken by the caller.
300 */
b2f408fe 301static void fast_mix(u32 pool[4])
775f4b29 302{
b2f408fe
JD
303 u32 a = pool[0], b = pool[1];
304 u32 c = pool[2], d = pool[3];
43759d4f
TT
305
306 a += b; c += d;
19acc77a 307 b = rol32(b, 6); d = rol32(d, 27);
43759d4f
TT
308 d ^= a; b ^= c;
309
310 a += b; c += d;
19acc77a 311 b = rol32(b, 16); d = rol32(d, 14);
43759d4f
TT
312 d ^= a; b ^= c;
313
314 a += b; c += d;
19acc77a 315 b = rol32(b, 6); d = rol32(d, 27);
43759d4f
TT
316 d ^= a; b ^= c;
317
318 a += b; c += d;
19acc77a 319 b = rol32(b, 16); d = rol32(d, 14);
43759d4f
TT
320 d ^= a; b ^= c;
321
b2f408fe
JD
322 pool[0] = a; pool[1] = b;
323 pool[2] = c; pool[3] = d;
775f4b29
TT
324}
325
205a525c
HX
326static void process_random_ready_list(void)
327{
328 unsigned long flags;
329 struct random_ready_callback *rdy, *tmp;
330
331 spin_lock_irqsave(&random_ready_list_lock, flags);
332 list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
333 struct module *owner = rdy->owner;
334
335 list_del_init(&rdy->list);
336 rdy->func(rdy);
337 module_put(owner);
338 }
339 spin_unlock_irqrestore(&random_ready_list_lock, flags);
340}
341
04ec96b7 342static void credit_entropy_bits(size_t nbits)
1da177e4 343{
04ec96b7 344 unsigned int entropy_count, orig, add;
18263c4e 345
04ec96b7 346 if (!nbits)
adc782da
MM
347 return;
348
04ec96b7 349 add = min_t(size_t, nbits, POOL_BITS);
a49c010e 350
c5704490
JD
351 do {
352 orig = READ_ONCE(input_pool.entropy_count);
04ec96b7 353 entropy_count = min_t(unsigned int, POOL_BITS, orig + add);
c5704490 354 } while (cmpxchg(&input_pool.entropy_count, orig, entropy_count) != orig);
1da177e4 355
c5704490 356 if (crng_init < 2 && entropy_count >= POOL_MIN_BITS)
a9412d51 357 crng_reseed();
1da177e4
LT
358}
359
e192be9d
TT
360/*********************************************************************
361 *
362 * CRNG using CHACHA20
363 *
364 *********************************************************************/
365
186873c5
JD
366enum {
367 CRNG_RESEED_INTERVAL = 300 * HZ,
368 CRNG_INIT_CNT_THRESH = 2 * CHACHA_KEY_SIZE
369};
370
371static struct {
372 u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
373 unsigned long birth;
374 unsigned long generation;
375 spinlock_t lock;
376} base_crng = {
377 .lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
378};
379
380struct crng {
381 u8 key[CHACHA_KEY_SIZE];
382 unsigned long generation;
383 local_lock_t lock;
384};
385
386static DEFINE_PER_CPU(struct crng, crngs) = {
387 .generation = ULONG_MAX,
388 .lock = INIT_LOCAL_LOCK(crngs.lock),
389};
e192be9d
TT
390
391static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
392
dc12baac
TT
393/*
394 * crng_fast_load() can be called by code in the interrupt service
73c7733f
JD
395 * path. So we can't afford to dilly-dally. Returns the number of
396 * bytes processed from cp.
dc12baac 397 */
04ec96b7 398static size_t crng_fast_load(const void *cp, size_t len)
e192be9d
TT
399{
400 unsigned long flags;
04ec96b7 401 const u8 *src = (const u8 *)cp;
73c7733f 402 size_t ret = 0;
e192be9d 403
186873c5 404 if (!spin_trylock_irqsave(&base_crng.lock, flags))
e192be9d 405 return 0;
43838a23 406 if (crng_init != 0) {
186873c5 407 spin_unlock_irqrestore(&base_crng.lock, flags);
e192be9d
TT
408 return 0;
409 }
e192be9d 410 while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
04ec96b7
JD
411 base_crng.key[crng_init_cnt % sizeof(base_crng.key)] ^= *src;
412 src++; crng_init_cnt++; len--; ret++;
e192be9d
TT
413 }
414 if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
0791e8b6 415 ++base_crng.generation;
e192be9d 416 crng_init = 1;
e192be9d 417 }
186873c5 418 spin_unlock_irqrestore(&base_crng.lock, flags);
7c2fe2b3
DB
419 if (crng_init == 1)
420 pr_notice("fast init done\n");
73c7733f 421 return ret;
e192be9d
TT
422}
423
dc12baac
TT
424/*
425 * crng_slow_load() is called by add_device_randomness, which has two
426 * attributes. (1) We can't trust the buffer passed to it is
427 * guaranteed to be unpredictable (so it might not have any entropy at
428 * all), and (2) it doesn't have the performance constraints of
429 * crng_fast_load().
430 *
66e4c2b9
JD
431 * So, we simply hash the contents in with the current key. Finally,
432 * we do *not* advance crng_init_cnt since buffer we may get may be
433 * something like a fixed DMI table (for example), which might very
434 * well be unique to the machine, but is otherwise unvarying.
dc12baac 435 */
04ec96b7 436static void crng_slow_load(const void *cp, size_t len)
dc12baac 437{
248045b8 438 unsigned long flags;
66e4c2b9
JD
439 struct blake2s_state hash;
440
441 blake2s_init(&hash, sizeof(base_crng.key));
dc12baac 442
186873c5 443 if (!spin_trylock_irqsave(&base_crng.lock, flags))
66e4c2b9 444 return;
dc12baac 445 if (crng_init != 0) {
186873c5 446 spin_unlock_irqrestore(&base_crng.lock, flags);
66e4c2b9 447 return;
dc12baac 448 }
66e4c2b9
JD
449
450 blake2s_update(&hash, base_crng.key, sizeof(base_crng.key));
451 blake2s_update(&hash, cp, len);
452 blake2s_final(&hash, base_crng.key);
453
186873c5 454 spin_unlock_irqrestore(&base_crng.lock, flags);
dc12baac
TT
455}
456
a9412d51 457static void crng_reseed(void)
e192be9d 458{
248045b8 459 unsigned long flags;
186873c5
JD
460 unsigned long next_gen;
461 u8 key[CHACHA_KEY_SIZE];
7191c628 462 bool finalize_init = false;
e192be9d 463
246c03dd
JD
464 /* Only reseed if we can, to prevent brute forcing a small amount of new bits. */
465 if (!drain_entropy(key, sizeof(key)))
466 return;
a9412d51 467
186873c5
JD
468 /*
469 * We copy the new key into the base_crng, overwriting the old one,
470 * and update the generation counter. We avoid hitting ULONG_MAX,
471 * because the per-cpu crngs are initialized to ULONG_MAX, so this
472 * forces new CPUs that come online to always initialize.
473 */
474 spin_lock_irqsave(&base_crng.lock, flags);
475 memcpy(base_crng.key, key, sizeof(base_crng.key));
476 next_gen = base_crng.generation + 1;
477 if (next_gen == ULONG_MAX)
478 ++next_gen;
479 WRITE_ONCE(base_crng.generation, next_gen);
480 WRITE_ONCE(base_crng.birth, jiffies);
a9412d51 481 if (crng_init < 2) {
a9412d51 482 crng_init = 2;
7191c628
DB
483 finalize_init = true;
484 }
485 spin_unlock_irqrestore(&base_crng.lock, flags);
486 memzero_explicit(key, sizeof(key));
487 if (finalize_init) {
a9412d51
JD
488 process_random_ready_list();
489 wake_up_interruptible(&crng_init_wait);
490 kill_fasync(&fasync, SIGIO, POLL_IN);
491 pr_notice("crng init done\n");
492 if (unseeded_warning.missed) {
493 pr_notice("%d get_random_xx warning(s) missed due to ratelimiting\n",
494 unseeded_warning.missed);
495 unseeded_warning.missed = 0;
496 }
497 if (urandom_warning.missed) {
498 pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
499 urandom_warning.missed);
500 urandom_warning.missed = 0;
501 }
502 }
e192be9d
TT
503}
504
186873c5
JD
505/*
506 * The general form here is based on a "fast key erasure RNG" from
507 * <https://blog.cr.yp.to/20170723-random.html>. It generates a ChaCha
508 * block using the provided key, and then immediately overwites that
509 * key with half the block. It returns the resultant ChaCha state to the
510 * user, along with the second half of the block containing 32 bytes of
511 * random data that may be used; random_data_len may not be greater than
512 * 32.
513 */
514static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
515 u32 chacha_state[CHACHA_STATE_WORDS],
516 u8 *random_data, size_t random_data_len)
e192be9d 517{
186873c5 518 u8 first_block[CHACHA_BLOCK_SIZE];
009ba856 519
186873c5
JD
520 BUG_ON(random_data_len > 32);
521
522 chacha_init_consts(chacha_state);
523 memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
524 memset(&chacha_state[12], 0, sizeof(u32) * 4);
525 chacha20_block(chacha_state, first_block);
526
527 memcpy(key, first_block, CHACHA_KEY_SIZE);
528 memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
529 memzero_explicit(first_block, sizeof(first_block));
1e7f583a
TT
530}
531
c92e040d 532/*
186873c5
JD
533 * This function returns a ChaCha state that you may use for generating
534 * random data. It also returns up to 32 bytes on its own of random data
535 * that may be used; random_data_len may not be greater than 32.
c92e040d 536 */
186873c5
JD
537static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
538 u8 *random_data, size_t random_data_len)
c92e040d 539{
248045b8 540 unsigned long flags;
186873c5 541 struct crng *crng;
c92e040d 542
186873c5
JD
543 BUG_ON(random_data_len > 32);
544
545 /*
546 * For the fast path, we check whether we're ready, unlocked first, and
547 * then re-check once locked later. In the case where we're really not
548 * ready, we do fast key erasure with the base_crng directly, because
549 * this is what crng_{fast,slow}_load mutate during early init.
550 */
551 if (unlikely(!crng_ready())) {
552 bool ready;
553
554 spin_lock_irqsave(&base_crng.lock, flags);
555 ready = crng_ready();
556 if (!ready)
557 crng_fast_key_erasure(base_crng.key, chacha_state,
558 random_data, random_data_len);
559 spin_unlock_irqrestore(&base_crng.lock, flags);
560 if (!ready)
561 return;
c92e040d 562 }
186873c5
JD
563
564 /*
565 * If the base_crng is more than 5 minutes old, we reseed, which
566 * in turn bumps the generation counter that we check below.
567 */
568 if (unlikely(time_after(jiffies, READ_ONCE(base_crng.birth) + CRNG_RESEED_INTERVAL)))
569 crng_reseed();
570
571 local_lock_irqsave(&crngs.lock, flags);
572 crng = raw_cpu_ptr(&crngs);
573
574 /*
575 * If our per-cpu crng is older than the base_crng, then it means
576 * somebody reseeded the base_crng. In that case, we do fast key
577 * erasure on the base_crng, and use its output as the new key
578 * for our per-cpu crng. This brings us up to date with base_crng.
579 */
580 if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
581 spin_lock(&base_crng.lock);
582 crng_fast_key_erasure(base_crng.key, chacha_state,
583 crng->key, sizeof(crng->key));
584 crng->generation = base_crng.generation;
585 spin_unlock(&base_crng.lock);
586 }
587
588 /*
589 * Finally, when we've made it this far, our per-cpu crng has an up
590 * to date key, and we can do fast key erasure with it to produce
591 * some random data and a ChaCha state for the caller. All other
592 * branches of this function are "unlikely", so most of the time we
593 * should wind up here immediately.
594 */
595 crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
596 local_unlock_irqrestore(&crngs.lock, flags);
c92e040d
TT
597}
598
186873c5 599static ssize_t get_random_bytes_user(void __user *buf, size_t nbytes)
e192be9d 600{
186873c5 601 bool large_request = nbytes > 256;
04ec96b7
JD
602 ssize_t ret = 0;
603 size_t len;
186873c5
JD
604 u32 chacha_state[CHACHA_STATE_WORDS];
605 u8 output[CHACHA_BLOCK_SIZE];
606
607 if (!nbytes)
608 return 0;
609
04ec96b7 610 len = min_t(size_t, 32, nbytes);
186873c5
JD
611 crng_make_state(chacha_state, output, len);
612
613 if (copy_to_user(buf, output, len))
614 return -EFAULT;
615 nbytes -= len;
616 buf += len;
617 ret += len;
e192be9d
TT
618
619 while (nbytes) {
620 if (large_request && need_resched()) {
186873c5 621 if (signal_pending(current))
e192be9d 622 break;
e192be9d
TT
623 schedule();
624 }
625
186873c5
JD
626 chacha20_block(chacha_state, output);
627 if (unlikely(chacha_state[12] == 0))
628 ++chacha_state[13];
629
04ec96b7 630 len = min_t(size_t, nbytes, CHACHA_BLOCK_SIZE);
186873c5 631 if (copy_to_user(buf, output, len)) {
e192be9d
TT
632 ret = -EFAULT;
633 break;
634 }
635
186873c5
JD
636 nbytes -= len;
637 buf += len;
638 ret += len;
e192be9d 639 }
e192be9d 640
186873c5
JD
641 memzero_explicit(chacha_state, sizeof(chacha_state));
642 memzero_explicit(output, sizeof(output));
e192be9d
TT
643 return ret;
644}
645
1da177e4
LT
646/*********************************************************************
647 *
648 * Entropy input management
649 *
650 *********************************************************************/
651
652/* There is one of these per entropy source */
653struct timer_rand_state {
654 cycles_t last_time;
90b75ee5 655 long last_delta, last_delta2;
1da177e4
LT
656};
657
644008df
TT
658#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
659
a2080a67 660/*
e192be9d
TT
661 * Add device- or boot-specific data to the input pool to help
662 * initialize it.
a2080a67 663 *
e192be9d
TT
664 * None of this adds any entropy; it is meant to avoid the problem of
665 * the entropy pool having similar initial state across largely
666 * identical devices.
a2080a67 667 */
04ec96b7 668void add_device_randomness(const void *buf, size_t size)
a2080a67 669{
61875f30 670 unsigned long time = random_get_entropy() ^ jiffies;
3ef4cb2d 671 unsigned long flags;
a2080a67 672
dc12baac
TT
673 if (!crng_ready() && size)
674 crng_slow_load(buf, size);
ee7998c5 675
3ef4cb2d 676 spin_lock_irqsave(&input_pool.lock, flags);
90ed1e67
JD
677 _mix_pool_bytes(buf, size);
678 _mix_pool_bytes(&time, sizeof(time));
3ef4cb2d 679 spin_unlock_irqrestore(&input_pool.lock, flags);
a2080a67
LT
680}
681EXPORT_SYMBOL(add_device_randomness);
682
644008df 683static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
3060d6fe 684
1da177e4
LT
685/*
686 * This function adds entropy to the entropy "pool" by using timing
687 * delays. It uses the timer_rand_state structure to make an estimate
688 * of how many bits of entropy this call has added to the pool.
689 *
690 * The number "num" is also added to the pool - it should somehow describe
691 * the type of event which just happened. This is currently 0-255 for
692 * keyboard scan codes, and 256 upwards for interrupts.
693 *
694 */
04ec96b7 695static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1da177e4
LT
696{
697 struct {
1da177e4 698 long jiffies;
d38bb085
JD
699 unsigned int cycles;
700 unsigned int num;
1da177e4
LT
701 } sample;
702 long delta, delta2, delta3;
703
1da177e4 704 sample.jiffies = jiffies;
61875f30 705 sample.cycles = random_get_entropy();
1da177e4 706 sample.num = num;
90ed1e67 707 mix_pool_bytes(&sample, sizeof(sample));
1da177e4
LT
708
709 /*
710 * Calculate number of bits of randomness we probably added.
711 * We take into account the first, second and third-order deltas
712 * in order to make our estimate.
713 */
e00d996a
QC
714 delta = sample.jiffies - READ_ONCE(state->last_time);
715 WRITE_ONCE(state->last_time, sample.jiffies);
5e747dd9 716
e00d996a
QC
717 delta2 = delta - READ_ONCE(state->last_delta);
718 WRITE_ONCE(state->last_delta, delta);
5e747dd9 719
e00d996a
QC
720 delta3 = delta2 - READ_ONCE(state->last_delta2);
721 WRITE_ONCE(state->last_delta2, delta2);
5e747dd9
RV
722
723 if (delta < 0)
724 delta = -delta;
725 if (delta2 < 0)
726 delta2 = -delta2;
727 if (delta3 < 0)
728 delta3 = -delta3;
729 if (delta > delta2)
730 delta = delta2;
731 if (delta > delta3)
732 delta = delta3;
1da177e4 733
5e747dd9
RV
734 /*
735 * delta is now minimum absolute delta.
736 * Round down by 1 bit on general principles,
727d499a 737 * and limit entropy estimate to 12 bits.
5e747dd9 738 */
04ec96b7 739 credit_entropy_bits(min_t(unsigned int, fls(delta >> 1), 11));
1da177e4
LT
740}
741
d251575a 742void add_input_randomness(unsigned int type, unsigned int code,
248045b8 743 unsigned int value)
1da177e4
LT
744{
745 static unsigned char last_value;
746
747 /* ignore autorepeat and the like */
748 if (value == last_value)
749 return;
750
1da177e4
LT
751 last_value = value;
752 add_timer_randomness(&input_timer_state,
753 (type << 4) ^ code ^ (code >> 4) ^ value);
754}
80fc9f53 755EXPORT_SYMBOL_GPL(add_input_randomness);
1da177e4 756
775f4b29
TT
757static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
758
d38bb085 759static u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
ee3e00e9 760{
248045b8 761 u32 *ptr = (u32 *)regs;
92e75428 762 unsigned int idx;
ee3e00e9
TT
763
764 if (regs == NULL)
765 return 0;
92e75428 766 idx = READ_ONCE(f->reg_idx);
d38bb085 767 if (idx >= sizeof(struct pt_regs) / sizeof(u32))
92e75428
TT
768 idx = 0;
769 ptr += idx++;
770 WRITE_ONCE(f->reg_idx, idx);
9dfa7bba 771 return *ptr;
ee3e00e9
TT
772}
773
703f7066 774void add_interrupt_randomness(int irq)
1da177e4 775{
248045b8
JD
776 struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
777 struct pt_regs *regs = get_irq_regs();
778 unsigned long now = jiffies;
779 cycles_t cycles = random_get_entropy();
3060d6fe 780
ee3e00e9
TT
781 if (cycles == 0)
782 cycles = get_reg(fast_pool, regs);
3060d6fe 783
b2f408fe
JD
784 if (sizeof(cycles) == 8)
785 fast_pool->pool64[0] ^= cycles ^ rol64(now, 32) ^ irq;
786 else {
787 fast_pool->pool32[0] ^= cycles ^ irq;
788 fast_pool->pool32[1] ^= now;
789 }
790
791 if (sizeof(unsigned long) == 8)
792 fast_pool->pool64[1] ^= regs ? instruction_pointer(regs) : _RET_IP_;
793 else {
794 fast_pool->pool32[2] ^= regs ? instruction_pointer(regs) : _RET_IP_;
795 fast_pool->pool32[3] ^= get_reg(fast_pool, regs);
796 }
797
798 fast_mix(fast_pool->pool32);
799 ++fast_pool->count;
3060d6fe 800
43838a23 801 if (unlikely(crng_init == 0)) {
04ec96b7 802 if (fast_pool->count >= 64 &&
b2f408fe 803 crng_fast_load(fast_pool->pool32, sizeof(fast_pool->pool32)) > 0) {
e192be9d
TT
804 fast_pool->count = 0;
805 fast_pool->last = now;
c30c575d 806 if (spin_trylock(&input_pool.lock)) {
b2f408fe 807 _mix_pool_bytes(&fast_pool->pool32, sizeof(fast_pool->pool32));
c30c575d
JD
808 spin_unlock(&input_pool.lock);
809 }
e192be9d
TT
810 }
811 return;
812 }
813
248045b8 814 if ((fast_pool->count < 64) && !time_after(now, fast_pool->last + HZ))
1da177e4
LT
815 return;
816
90ed1e67 817 if (!spin_trylock(&input_pool.lock))
91fcb532 818 return;
83664a69 819
91fcb532 820 fast_pool->last = now;
b2f408fe 821 _mix_pool_bytes(&fast_pool->pool32, sizeof(fast_pool->pool32));
90ed1e67 822 spin_unlock(&input_pool.lock);
83664a69 823
ee3e00e9 824 fast_pool->count = 0;
83664a69 825
ee3e00e9 826 /* award one bit for the contents of the fast pool */
90ed1e67 827 credit_entropy_bits(1);
1da177e4 828}
4b44f2d1 829EXPORT_SYMBOL_GPL(add_interrupt_randomness);
1da177e4 830
9361401e 831#ifdef CONFIG_BLOCK
1da177e4
LT
832void add_disk_randomness(struct gendisk *disk)
833{
834 if (!disk || !disk->random)
835 return;
836 /* first major is 1, so we get >= 0x200 here */
f331c029 837 add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1da177e4 838}
bdcfa3e5 839EXPORT_SYMBOL_GPL(add_disk_randomness);
9361401e 840#endif
1da177e4 841
1da177e4
LT
842/*********************************************************************
843 *
844 * Entropy extraction routines
845 *
846 *********************************************************************/
847
19fa5be1 848/*
6e8ec255
JD
849 * This is an HKDF-like construction for using the hashed collected entropy
850 * as a PRF key, that's then expanded block-by-block.
19fa5be1 851 */
9c07f578 852static void extract_entropy(void *buf, size_t nbytes)
1da177e4 853{
902c098a 854 unsigned long flags;
6e8ec255
JD
855 u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
856 struct {
28f425e5 857 unsigned long rdseed[32 / sizeof(long)];
6e8ec255
JD
858 size_t counter;
859 } block;
860 size_t i;
861
28f425e5
JD
862 for (i = 0; i < ARRAY_SIZE(block.rdseed); ++i) {
863 if (!arch_get_random_seed_long(&block.rdseed[i]) &&
864 !arch_get_random_long(&block.rdseed[i]))
865 block.rdseed[i] = random_get_entropy();
85a1f777
TT
866 }
867
90ed1e67 868 spin_lock_irqsave(&input_pool.lock, flags);
46884442 869
6e8ec255
JD
870 /* seed = HASHPRF(last_key, entropy_input) */
871 blake2s_final(&input_pool.hash, seed);
1da177e4 872
28f425e5 873 /* next_key = HASHPRF(seed, RDSEED || 0) */
6e8ec255
JD
874 block.counter = 0;
875 blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
876 blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
1da177e4 877
6e8ec255
JD
878 spin_unlock_irqrestore(&input_pool.lock, flags);
879 memzero_explicit(next_key, sizeof(next_key));
e192be9d
TT
880
881 while (nbytes) {
6e8ec255 882 i = min_t(size_t, nbytes, BLAKE2S_HASH_SIZE);
28f425e5 883 /* output = HASHPRF(seed, RDSEED || ++counter) */
6e8ec255
JD
884 ++block.counter;
885 blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
e192be9d
TT
886 nbytes -= i;
887 buf += i;
e192be9d
TT
888 }
889
6e8ec255
JD
890 memzero_explicit(seed, sizeof(seed));
891 memzero_explicit(&block, sizeof(block));
e192be9d
TT
892}
893
246c03dd
JD
894/*
895 * First we make sure we have POOL_MIN_BITS of entropy in the pool, and then we
896 * set the entropy count to zero (but don't actually touch any data). Only then
897 * can we extract a new key with extract_entropy().
898 */
899static bool drain_entropy(void *buf, size_t nbytes)
900{
901 unsigned int entropy_count;
902 do {
903 entropy_count = READ_ONCE(input_pool.entropy_count);
904 if (entropy_count < POOL_MIN_BITS)
905 return false;
906 } while (cmpxchg(&input_pool.entropy_count, entropy_count, 0) != entropy_count);
907 extract_entropy(buf, nbytes);
908 wake_up_interruptible(&random_write_wait);
909 kill_fasync(&fasync, SIGIO, POLL_OUT);
910 return true;
911}
912
eecabf56 913#define warn_unseeded_randomness(previous) \
248045b8 914 _warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous))
eecabf56 915
248045b8 916static void _warn_unseeded_randomness(const char *func_name, void *caller, void **previous)
eecabf56
TT
917{
918#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM
919 const bool print_once = false;
920#else
921 static bool print_once __read_mostly;
922#endif
923
248045b8 924 if (print_once || crng_ready() ||
eecabf56
TT
925 (previous && (caller == READ_ONCE(*previous))))
926 return;
927 WRITE_ONCE(*previous, caller);
928#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM
929 print_once = true;
930#endif
4e00b339 931 if (__ratelimit(&unseeded_warning))
248045b8
JD
932 printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n",
933 func_name, caller, crng_init);
eecabf56
TT
934}
935
1da177e4
LT
936/*
937 * This function is the exported kernel interface. It returns some
c2557a30 938 * number of good random numbers, suitable for key generation, seeding
18e9cea7
GP
939 * TCP sequence numbers, etc. It does not rely on the hardware random
940 * number generator. For random bytes direct from the hardware RNG
e297a783
JD
941 * (when available), use get_random_bytes_arch(). In order to ensure
942 * that the randomness provided by this function is okay, the function
943 * wait_for_random_bytes() should be called and return 0 at least once
944 * at any point prior.
1da177e4 945 */
04ec96b7 946static void _get_random_bytes(void *buf, size_t nbytes)
c2557a30 947{
186873c5
JD
948 u32 chacha_state[CHACHA_STATE_WORDS];
949 u8 tmp[CHACHA_BLOCK_SIZE];
04ec96b7 950 size_t len;
e192be9d 951
186873c5
JD
952 if (!nbytes)
953 return;
954
04ec96b7 955 len = min_t(size_t, 32, nbytes);
186873c5
JD
956 crng_make_state(chacha_state, buf, len);
957 nbytes -= len;
958 buf += len;
959
960 while (nbytes) {
961 if (nbytes < CHACHA_BLOCK_SIZE) {
962 chacha20_block(chacha_state, tmp);
963 memcpy(buf, tmp, nbytes);
964 memzero_explicit(tmp, sizeof(tmp));
965 break;
966 }
967
968 chacha20_block(chacha_state, buf);
969 if (unlikely(chacha_state[12] == 0))
970 ++chacha_state[13];
1ca1b917 971 nbytes -= CHACHA_BLOCK_SIZE;
186873c5 972 buf += CHACHA_BLOCK_SIZE;
e192be9d
TT
973 }
974
186873c5 975 memzero_explicit(chacha_state, sizeof(chacha_state));
c2557a30 976}
eecabf56 977
04ec96b7 978void get_random_bytes(void *buf, size_t nbytes)
eecabf56
TT
979{
980 static void *previous;
981
982 warn_unseeded_randomness(&previous);
983 _get_random_bytes(buf, nbytes);
984}
c2557a30
TT
985EXPORT_SYMBOL(get_random_bytes);
986
50ee7529
LT
987/*
988 * Each time the timer fires, we expect that we got an unpredictable
989 * jump in the cycle counter. Even if the timer is running on another
990 * CPU, the timer activity will be touching the stack of the CPU that is
991 * generating entropy..
992 *
993 * Note that we don't re-arm the timer in the timer itself - we are
994 * happy to be scheduled away, since that just makes the load more
995 * complex, but we do not want the timer to keep ticking unless the
996 * entropy loop is running.
997 *
998 * So the re-arming always happens in the entropy loop itself.
999 */
1000static void entropy_timer(struct timer_list *t)
1001{
90ed1e67 1002 credit_entropy_bits(1);
50ee7529
LT
1003}
1004
1005/*
1006 * If we have an actual cycle counter, see if we can
1007 * generate enough entropy with timing noise
1008 */
1009static void try_to_generate_entropy(void)
1010{
1011 struct {
1012 unsigned long now;
1013 struct timer_list timer;
1014 } stack;
1015
1016 stack.now = random_get_entropy();
1017
1018 /* Slow counter - or none. Don't even bother */
1019 if (stack.now == random_get_entropy())
1020 return;
1021
1022 timer_setup_on_stack(&stack.timer, entropy_timer, 0);
1023 while (!crng_ready()) {
1024 if (!timer_pending(&stack.timer))
248045b8 1025 mod_timer(&stack.timer, jiffies + 1);
90ed1e67 1026 mix_pool_bytes(&stack.now, sizeof(stack.now));
50ee7529
LT
1027 schedule();
1028 stack.now = random_get_entropy();
1029 }
1030
1031 del_timer_sync(&stack.timer);
1032 destroy_timer_on_stack(&stack.timer);
90ed1e67 1033 mix_pool_bytes(&stack.now, sizeof(stack.now));
50ee7529
LT
1034}
1035
e297a783
JD
1036/*
1037 * Wait for the urandom pool to be seeded and thus guaranteed to supply
1038 * cryptographically secure random numbers. This applies to: the /dev/urandom
1039 * device, the get_random_bytes function, and the get_random_{u32,u64,int,long}
1040 * family of functions. Using any of these functions without first calling
1041 * this function forfeits the guarantee of security.
1042 *
1043 * Returns: 0 if the urandom pool has been seeded.
1044 * -ERESTARTSYS if the function was interrupted by a signal.
1045 */
1046int wait_for_random_bytes(void)
1047{
1048 if (likely(crng_ready()))
1049 return 0;
50ee7529
LT
1050
1051 do {
1052 int ret;
1053 ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
1054 if (ret)
1055 return ret > 0 ? 0 : ret;
1056
1057 try_to_generate_entropy();
1058 } while (!crng_ready());
1059
1060 return 0;
e297a783
JD
1061}
1062EXPORT_SYMBOL(wait_for_random_bytes);
1063
9a47249d
JD
1064/*
1065 * Returns whether or not the urandom pool has been seeded and thus guaranteed
1066 * to supply cryptographically secure random numbers. This applies to: the
1067 * /dev/urandom device, the get_random_bytes function, and the get_random_{u32,
1068 * ,u64,int,long} family of functions.
1069 *
1070 * Returns: true if the urandom pool has been seeded.
1071 * false if the urandom pool has not been seeded.
1072 */
1073bool rng_is_initialized(void)
1074{
1075 return crng_ready();
1076}
1077EXPORT_SYMBOL(rng_is_initialized);
1078
205a525c
HX
1079/*
1080 * Add a callback function that will be invoked when the nonblocking
1081 * pool is initialised.
1082 *
1083 * returns: 0 if callback is successfully added
1084 * -EALREADY if pool is already initialised (callback not called)
1085 * -ENOENT if module for callback is not alive
1086 */
1087int add_random_ready_callback(struct random_ready_callback *rdy)
1088{
1089 struct module *owner;
1090 unsigned long flags;
1091 int err = -EALREADY;
1092
e192be9d 1093 if (crng_ready())
205a525c
HX
1094 return err;
1095
1096 owner = rdy->owner;
1097 if (!try_module_get(owner))
1098 return -ENOENT;
1099
1100 spin_lock_irqsave(&random_ready_list_lock, flags);
e192be9d 1101 if (crng_ready())
205a525c
HX
1102 goto out;
1103
1104 owner = NULL;
1105
1106 list_add(&rdy->list, &random_ready_list);
1107 err = 0;
1108
1109out:
1110 spin_unlock_irqrestore(&random_ready_list_lock, flags);
1111
1112 module_put(owner);
1113
1114 return err;
1115}
1116EXPORT_SYMBOL(add_random_ready_callback);
1117
1118/*
1119 * Delete a previously registered readiness callback function.
1120 */
1121void del_random_ready_callback(struct random_ready_callback *rdy)
1122{
1123 unsigned long flags;
1124 struct module *owner = NULL;
1125
1126 spin_lock_irqsave(&random_ready_list_lock, flags);
1127 if (!list_empty(&rdy->list)) {
1128 list_del_init(&rdy->list);
1129 owner = rdy->owner;
1130 }
1131 spin_unlock_irqrestore(&random_ready_list_lock, flags);
1132
1133 module_put(owner);
1134}
1135EXPORT_SYMBOL(del_random_ready_callback);
1136
c2557a30
TT
1137/*
1138 * This function will use the architecture-specific hardware random
04ec96b7
JD
1139 * number generator if it is available. It is not recommended for
1140 * use. Use get_random_bytes() instead. It returns the number of
1141 * bytes filled in.
c2557a30 1142 */
04ec96b7 1143size_t __must_check get_random_bytes_arch(void *buf, size_t nbytes)
1da177e4 1144{
04ec96b7 1145 size_t left = nbytes;
d38bb085 1146 u8 *p = buf;
63d77173 1147
753d433b 1148 while (left) {
63d77173 1149 unsigned long v;
04ec96b7 1150 size_t chunk = min_t(size_t, left, sizeof(unsigned long));
c2557a30 1151
63d77173
PA
1152 if (!arch_get_random_long(&v))
1153 break;
8ddd6efa 1154
bd29e568 1155 memcpy(p, &v, chunk);
63d77173 1156 p += chunk;
753d433b 1157 left -= chunk;
63d77173
PA
1158 }
1159
753d433b 1160 return nbytes - left;
1da177e4 1161}
c2557a30
TT
1162EXPORT_SYMBOL(get_random_bytes_arch);
1163
85664172
JD
1164static bool trust_cpu __ro_after_init = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
1165static int __init parse_trust_cpu(char *arg)
1166{
1167 return kstrtobool(arg, &trust_cpu);
1168}
1169early_param("random.trust_cpu", parse_trust_cpu);
1170
1da177e4 1171/*
85664172
JD
1172 * Note that setup_arch() may call add_device_randomness()
1173 * long before we get here. This allows seeding of the pools
1174 * with some platform dependent data very early in the boot
1175 * process. But it limits our options here. We must use
1176 * statically allocated structures that already have all
1177 * initializations complete at compile time. We should also
1178 * take care not to overwrite the precious per platform data
1179 * we were given.
1da177e4 1180 */
85664172 1181int __init rand_initialize(void)
1da177e4 1182{
04ec96b7 1183 size_t i;
902c098a 1184 ktime_t now = ktime_get_real();
85664172 1185 bool arch_init = true;
902c098a 1186 unsigned long rv;
1da177e4 1187
04ec96b7 1188 for (i = 0; i < BLAKE2S_BLOCK_SIZE; i += sizeof(rv)) {
85664172
JD
1189 if (!arch_get_random_seed_long_early(&rv) &&
1190 !arch_get_random_long_early(&rv)) {
1191 rv = random_get_entropy();
1192 arch_init = false;
1193 }
a02cf3d0 1194 mix_pool_bytes(&rv, sizeof(rv));
85664172 1195 }
a02cf3d0
JD
1196 mix_pool_bytes(&now, sizeof(now));
1197 mix_pool_bytes(utsname(), sizeof(*(utsname())));
1198
186873c5 1199 extract_entropy(base_crng.key, sizeof(base_crng.key));
0791e8b6
JD
1200 ++base_crng.generation;
1201
85664172 1202 if (arch_init && trust_cpu && crng_init < 2) {
85664172
JD
1203 crng_init = 2;
1204 pr_notice("crng init done (trusting CPU's manufacturer)\n");
1205 }
85664172 1206
4e00b339
TT
1207 if (ratelimit_disable) {
1208 urandom_warning.interval = 0;
1209 unseeded_warning.interval = 0;
1210 }
1da177e4
LT
1211 return 0;
1212}
1da177e4 1213
9361401e 1214#ifdef CONFIG_BLOCK
1da177e4
LT
1215void rand_initialize_disk(struct gendisk *disk)
1216{
1217 struct timer_rand_state *state;
1218
1219 /*
f8595815 1220 * If kzalloc returns null, we just won't use that entropy
1da177e4
LT
1221 * source.
1222 */
f8595815 1223 state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
644008df
TT
1224 if (state) {
1225 state->last_time = INITIAL_JIFFIES;
1da177e4 1226 disk->random = state;
644008df 1227 }
1da177e4 1228}
9361401e 1229#endif
1da177e4 1230
248045b8
JD
1231static ssize_t urandom_read(struct file *file, char __user *buf, size_t nbytes,
1232 loff_t *ppos)
1da177e4 1233{
9b4d0087 1234 static int maxwarn = 10;
301f0595 1235
e192be9d 1236 if (!crng_ready() && maxwarn > 0) {
9b4d0087 1237 maxwarn--;
4e00b339 1238 if (__ratelimit(&urandom_warning))
12cd53af
YL
1239 pr_notice("%s: uninitialized urandom read (%zd bytes read)\n",
1240 current->comm, nbytes);
9b4d0087 1241 }
c6f1deb1 1242
14c17463 1243 return get_random_bytes_user(buf, nbytes);
1da177e4
LT
1244}
1245
248045b8
JD
1246static ssize_t random_read(struct file *file, char __user *buf, size_t nbytes,
1247 loff_t *ppos)
30c08efe
AL
1248{
1249 int ret;
1250
1251 ret = wait_for_random_bytes();
1252 if (ret != 0)
1253 return ret;
14c17463 1254 return get_random_bytes_user(buf, nbytes);
30c08efe
AL
1255}
1256
248045b8 1257static __poll_t random_poll(struct file *file, poll_table *wait)
1da177e4 1258{
a11e1d43 1259 __poll_t mask;
1da177e4 1260
30c08efe 1261 poll_wait(file, &crng_init_wait, wait);
a11e1d43
LT
1262 poll_wait(file, &random_write_wait, wait);
1263 mask = 0;
30c08efe 1264 if (crng_ready())
a9a08845 1265 mask |= EPOLLIN | EPOLLRDNORM;
489c7fc4 1266 if (input_pool.entropy_count < POOL_MIN_BITS)
a9a08845 1267 mask |= EPOLLOUT | EPOLLWRNORM;
1da177e4
LT
1268 return mask;
1269}
1270
04ec96b7 1271static int write_pool(const char __user *ubuf, size_t count)
1da177e4 1272{
04ec96b7 1273 size_t len;
7b5164fb 1274 int ret = 0;
04ec96b7 1275 u8 block[BLAKE2S_BLOCK_SIZE];
1da177e4 1276
04ec96b7
JD
1277 while (count) {
1278 len = min(count, sizeof(block));
7b5164fb
JD
1279 if (copy_from_user(block, ubuf, len)) {
1280 ret = -EFAULT;
1281 goto out;
1282 }
04ec96b7
JD
1283 count -= len;
1284 ubuf += len;
1285 mix_pool_bytes(block, len);
91f3f1e3 1286 cond_resched();
1da177e4 1287 }
7f397dcd 1288
7b5164fb
JD
1289out:
1290 memzero_explicit(block, sizeof(block));
1291 return ret;
7f397dcd
MM
1292}
1293
90b75ee5
MM
1294static ssize_t random_write(struct file *file, const char __user *buffer,
1295 size_t count, loff_t *ppos)
7f397dcd 1296{
04ec96b7 1297 int ret;
7f397dcd 1298
90ed1e67 1299 ret = write_pool(buffer, count);
7f397dcd
MM
1300 if (ret)
1301 return ret;
1302
7f397dcd 1303 return (ssize_t)count;
1da177e4
LT
1304}
1305
43ae4860 1306static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1da177e4
LT
1307{
1308 int size, ent_count;
1309 int __user *p = (int __user *)arg;
1310 int retval;
1311
1312 switch (cmd) {
1313 case RNDGETENTCNT:
43ae4860 1314 /* inherently racy, no point locking */
c5704490 1315 if (put_user(input_pool.entropy_count, p))
1da177e4
LT
1316 return -EFAULT;
1317 return 0;
1318 case RNDADDTOENTCNT:
1319 if (!capable(CAP_SYS_ADMIN))
1320 return -EPERM;
1321 if (get_user(ent_count, p))
1322 return -EFAULT;
a49c010e
JD
1323 if (ent_count < 0)
1324 return -EINVAL;
1325 credit_entropy_bits(ent_count);
1326 return 0;
1da177e4
LT
1327 case RNDADDENTROPY:
1328 if (!capable(CAP_SYS_ADMIN))
1329 return -EPERM;
1330 if (get_user(ent_count, p++))
1331 return -EFAULT;
1332 if (ent_count < 0)
1333 return -EINVAL;
1334 if (get_user(size, p++))
1335 return -EFAULT;
90ed1e67 1336 retval = write_pool((const char __user *)p, size);
1da177e4
LT
1337 if (retval < 0)
1338 return retval;
a49c010e
JD
1339 credit_entropy_bits(ent_count);
1340 return 0;
1da177e4
LT
1341 case RNDZAPENTCNT:
1342 case RNDCLEARPOOL:
ae9ecd92
TT
1343 /*
1344 * Clear the entropy pool counters. We no longer clear
1345 * the entropy pool, as that's silly.
1346 */
1da177e4
LT
1347 if (!capable(CAP_SYS_ADMIN))
1348 return -EPERM;
489c7fc4 1349 if (xchg(&input_pool.entropy_count, 0)) {
042e293e
JD
1350 wake_up_interruptible(&random_write_wait);
1351 kill_fasync(&fasync, SIGIO, POLL_OUT);
1352 }
1da177e4 1353 return 0;
d848e5f8
TT
1354 case RNDRESEEDCRNG:
1355 if (!capable(CAP_SYS_ADMIN))
1356 return -EPERM;
1357 if (crng_init < 2)
1358 return -ENODATA;
a9412d51 1359 crng_reseed();
d848e5f8 1360 return 0;
1da177e4
LT
1361 default:
1362 return -EINVAL;
1363 }
1364}
1365
9a6f70bb
JD
1366static int random_fasync(int fd, struct file *filp, int on)
1367{
1368 return fasync_helper(fd, filp, on, &fasync);
1369}
1370
2b8693c0 1371const struct file_operations random_fops = {
248045b8 1372 .read = random_read,
1da177e4 1373 .write = random_write,
248045b8 1374 .poll = random_poll,
43ae4860 1375 .unlocked_ioctl = random_ioctl,
507e4e2b 1376 .compat_ioctl = compat_ptr_ioctl,
9a6f70bb 1377 .fasync = random_fasync,
6038f373 1378 .llseek = noop_llseek,
1da177e4
LT
1379};
1380
2b8693c0 1381const struct file_operations urandom_fops = {
248045b8 1382 .read = urandom_read,
1da177e4 1383 .write = random_write,
43ae4860 1384 .unlocked_ioctl = random_ioctl,
4aa37c46 1385 .compat_ioctl = compat_ptr_ioctl,
9a6f70bb 1386 .fasync = random_fasync,
6038f373 1387 .llseek = noop_llseek,
1da177e4
LT
1388};
1389
248045b8
JD
1390SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int,
1391 flags)
c6e9d6f3 1392{
248045b8 1393 if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
75551dbf
AL
1394 return -EINVAL;
1395
1396 /*
1397 * Requesting insecure and blocking randomness at the same time makes
1398 * no sense.
1399 */
248045b8 1400 if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
c6e9d6f3
TT
1401 return -EINVAL;
1402
1403 if (count > INT_MAX)
1404 count = INT_MAX;
1405
75551dbf 1406 if (!(flags & GRND_INSECURE) && !crng_ready()) {
04ec96b7
JD
1407 int ret;
1408
c6e9d6f3
TT
1409 if (flags & GRND_NONBLOCK)
1410 return -EAGAIN;
e297a783
JD
1411 ret = wait_for_random_bytes();
1412 if (unlikely(ret))
1413 return ret;
c6e9d6f3 1414 }
14c17463 1415 return get_random_bytes_user(buf, count);
c6e9d6f3
TT
1416}
1417
1da177e4
LT
1418/********************************************************************
1419 *
1420 * Sysctl interface
1421 *
1422 ********************************************************************/
1423
1424#ifdef CONFIG_SYSCTL
1425
1426#include <linux/sysctl.h>
1427
db61ffe3 1428static int random_min_urandom_seed = 60;
489c7fc4
JD
1429static int random_write_wakeup_bits = POOL_MIN_BITS;
1430static int sysctl_poolsize = POOL_BITS;
1da177e4
LT
1431static char sysctl_bootid[16];
1432
1433/*
f22052b2 1434 * This function is used to return both the bootid UUID, and random
1da177e4
LT
1435 * UUID. The difference is in whether table->data is NULL; if it is,
1436 * then a new UUID is generated and returned to the user.
1437 *
f22052b2
GP
1438 * If the user accesses this via the proc interface, the UUID will be
1439 * returned as an ASCII string in the standard UUID format; if via the
1440 * sysctl system call, as 16 bytes of binary data.
1da177e4 1441 */
248045b8
JD
1442static int proc_do_uuid(struct ctl_table *table, int write, void *buffer,
1443 size_t *lenp, loff_t *ppos)
1da177e4 1444{
a151427e 1445 struct ctl_table fake_table;
1da177e4
LT
1446 unsigned char buf[64], tmp_uuid[16], *uuid;
1447
1448 uuid = table->data;
1449 if (!uuid) {
1450 uuid = tmp_uuid;
1da177e4 1451 generate_random_uuid(uuid);
44e4360f
MD
1452 } else {
1453 static DEFINE_SPINLOCK(bootid_spinlock);
1454
1455 spin_lock(&bootid_spinlock);
1456 if (!uuid[8])
1457 generate_random_uuid(uuid);
1458 spin_unlock(&bootid_spinlock);
1459 }
1da177e4 1460
35900771
JP
1461 sprintf(buf, "%pU", uuid);
1462
1da177e4
LT
1463 fake_table.data = buf;
1464 fake_table.maxlen = sizeof(buf);
1465
8d65af78 1466 return proc_dostring(&fake_table, write, buffer, lenp, ppos);
1da177e4
LT
1467}
1468
5475e8f0 1469static struct ctl_table random_table[] = {
1da177e4 1470 {
1da177e4
LT
1471 .procname = "poolsize",
1472 .data = &sysctl_poolsize,
1473 .maxlen = sizeof(int),
1474 .mode = 0444,
6d456111 1475 .proc_handler = proc_dointvec,
1da177e4
LT
1476 },
1477 {
1da177e4 1478 .procname = "entropy_avail",
c5704490 1479 .data = &input_pool.entropy_count,
1da177e4
LT
1480 .maxlen = sizeof(int),
1481 .mode = 0444,
c5704490 1482 .proc_handler = proc_dointvec,
1da177e4 1483 },
1da177e4 1484 {
1da177e4 1485 .procname = "write_wakeup_threshold",
2132a96f 1486 .data = &random_write_wakeup_bits,
1da177e4
LT
1487 .maxlen = sizeof(int),
1488 .mode = 0644,
489c7fc4 1489 .proc_handler = proc_dointvec,
1da177e4 1490 },
f5c2742c
TT
1491 {
1492 .procname = "urandom_min_reseed_secs",
1493 .data = &random_min_urandom_seed,
1494 .maxlen = sizeof(int),
1495 .mode = 0644,
1496 .proc_handler = proc_dointvec,
1497 },
1da177e4 1498 {
1da177e4
LT
1499 .procname = "boot_id",
1500 .data = &sysctl_bootid,
1501 .maxlen = 16,
1502 .mode = 0444,
6d456111 1503 .proc_handler = proc_do_uuid,
1da177e4
LT
1504 },
1505 {
1da177e4
LT
1506 .procname = "uuid",
1507 .maxlen = 16,
1508 .mode = 0444,
6d456111 1509 .proc_handler = proc_do_uuid,
1da177e4 1510 },
894d2491 1511 { }
1da177e4 1512};
5475e8f0
XN
1513
1514/*
1515 * rand_initialize() is called before sysctl_init(),
1516 * so we cannot call register_sysctl_init() in rand_initialize()
1517 */
1518static int __init random_sysctls_init(void)
1519{
1520 register_sysctl_init("kernel/random", random_table);
1521 return 0;
1522}
1523device_initcall(random_sysctls_init);
248045b8 1524#endif /* CONFIG_SYSCTL */
1da177e4 1525
f5b98461
JD
1526struct batched_entropy {
1527 union {
186873c5
JD
1528 /*
1529 * We make this 1.5x a ChaCha block, so that we get the
1530 * remaining 32 bytes from fast key erasure, plus one full
1531 * block from the detached ChaCha state. We can increase
1532 * the size of this later if needed so long as we keep the
1533 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.
1534 */
1535 u64 entropy_u64[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(u64))];
1536 u32 entropy_u32[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(u32))];
f5b98461 1537 };
77760fd7 1538 local_lock_t lock;
0791e8b6 1539 unsigned long generation;
f5b98461
JD
1540 unsigned int position;
1541};
b1132dea 1542
1da177e4 1543/*
f5b98461 1544 * Get a random word for internal kernel use only. The quality of the random
186873c5
JD
1545 * number is good as /dev/urandom. In order to ensure that the randomness
1546 * provided by this function is okay, the function wait_for_random_bytes()
1547 * should be called and return 0 at least once at any point prior.
1da177e4 1548 */
b7d5dc21 1549static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = {
186873c5
JD
1550 .lock = INIT_LOCAL_LOCK(batched_entropy_u64.lock),
1551 .position = UINT_MAX
b7d5dc21
SAS
1552};
1553
c440408c 1554u64 get_random_u64(void)
1da177e4 1555{
c440408c 1556 u64 ret;
b7d5dc21 1557 unsigned long flags;
f5b98461 1558 struct batched_entropy *batch;
eecabf56 1559 static void *previous;
0791e8b6 1560 unsigned long next_gen;
8a0a9bd4 1561
eecabf56 1562 warn_unseeded_randomness(&previous);
d06bfd19 1563
77760fd7 1564 local_lock_irqsave(&batched_entropy_u64.lock, flags);
b7d5dc21 1565 batch = raw_cpu_ptr(&batched_entropy_u64);
77760fd7 1566
0791e8b6 1567 next_gen = READ_ONCE(base_crng.generation);
186873c5 1568 if (batch->position >= ARRAY_SIZE(batch->entropy_u64) ||
77760fd7 1569 next_gen != batch->generation) {
186873c5 1570 _get_random_bytes(batch->entropy_u64, sizeof(batch->entropy_u64));
f5b98461 1571 batch->position = 0;
77760fd7 1572 batch->generation = next_gen;
f5b98461 1573 }
77760fd7 1574
186873c5
JD
1575 ret = batch->entropy_u64[batch->position];
1576 batch->entropy_u64[batch->position] = 0;
1577 ++batch->position;
77760fd7 1578 local_unlock_irqrestore(&batched_entropy_u64.lock, flags);
8a0a9bd4 1579 return ret;
1da177e4 1580}
c440408c 1581EXPORT_SYMBOL(get_random_u64);
1da177e4 1582
b7d5dc21 1583static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = {
186873c5
JD
1584 .lock = INIT_LOCAL_LOCK(batched_entropy_u32.lock),
1585 .position = UINT_MAX
b7d5dc21 1586};
77760fd7 1587
c440408c 1588u32 get_random_u32(void)
f5b98461 1589{
c440408c 1590 u32 ret;
b7d5dc21 1591 unsigned long flags;
f5b98461 1592 struct batched_entropy *batch;
eecabf56 1593 static void *previous;
0791e8b6 1594 unsigned long next_gen;
ec9ee4ac 1595
eecabf56 1596 warn_unseeded_randomness(&previous);
d06bfd19 1597
77760fd7 1598 local_lock_irqsave(&batched_entropy_u32.lock, flags);
b7d5dc21 1599 batch = raw_cpu_ptr(&batched_entropy_u32);
77760fd7 1600
0791e8b6 1601 next_gen = READ_ONCE(base_crng.generation);
186873c5 1602 if (batch->position >= ARRAY_SIZE(batch->entropy_u32) ||
77760fd7 1603 next_gen != batch->generation) {
186873c5 1604 _get_random_bytes(batch->entropy_u32, sizeof(batch->entropy_u32));
f5b98461 1605 batch->position = 0;
77760fd7 1606 batch->generation = next_gen;
f5b98461 1607 }
77760fd7 1608
186873c5
JD
1609 ret = batch->entropy_u32[batch->position];
1610 batch->entropy_u32[batch->position] = 0;
1611 ++batch->position;
77760fd7 1612 local_unlock_irqrestore(&batched_entropy_u32.lock, flags);
ec9ee4ac
DC
1613 return ret;
1614}
c440408c 1615EXPORT_SYMBOL(get_random_u32);
ec9ee4ac 1616
99fdafde
JC
1617/**
1618 * randomize_page - Generate a random, page aligned address
1619 * @start: The smallest acceptable address the caller will take.
1620 * @range: The size of the area, starting at @start, within which the
1621 * random address must fall.
1622 *
1623 * If @start + @range would overflow, @range is capped.
1624 *
1625 * NOTE: Historical use of randomize_range, which this replaces, presumed that
1626 * @start was already page aligned. We now align it regardless.
1627 *
1628 * Return: A page aligned address within [start, start + range). On error,
1629 * @start is returned.
1630 */
248045b8 1631unsigned long randomize_page(unsigned long start, unsigned long range)
99fdafde
JC
1632{
1633 if (!PAGE_ALIGNED(start)) {
1634 range -= PAGE_ALIGN(start) - start;
1635 start = PAGE_ALIGN(start);
1636 }
1637
1638 if (start > ULONG_MAX - range)
1639 range = ULONG_MAX - start;
1640
1641 range >>= PAGE_SHIFT;
1642
1643 if (range == 0)
1644 return start;
1645
1646 return start + (get_random_long() % range << PAGE_SHIFT);
1647}
1648
c84dbf61
TD
1649/* Interface for in-kernel drivers of true hardware RNGs.
1650 * Those devices may produce endless random bits and will be throttled
1651 * when our pool is full.
1652 */
04ec96b7 1653void add_hwgenerator_randomness(const void *buffer, size_t count,
c84dbf61
TD
1654 size_t entropy)
1655{
43838a23 1656 if (unlikely(crng_init == 0)) {
73c7733f 1657 size_t ret = crng_fast_load(buffer, count);
90ed1e67 1658 mix_pool_bytes(buffer, ret);
73c7733f
JD
1659 count -= ret;
1660 buffer += ret;
1661 if (!count || crng_init == 0)
1662 return;
3371f3da 1663 }
e192be9d 1664
c321e907 1665 /* Throttle writing if we're above the trickle threshold.
489c7fc4
JD
1666 * We'll be woken up again once below POOL_MIN_BITS, when
1667 * the calling thread is about to terminate, or once
1668 * CRNG_RESEED_INTERVAL has elapsed.
e192be9d 1669 */
c321e907 1670 wait_event_interruptible_timeout(random_write_wait,
f7e67b8e 1671 !system_wq || kthread_should_stop() ||
489c7fc4 1672 input_pool.entropy_count < POOL_MIN_BITS,
c321e907 1673 CRNG_RESEED_INTERVAL);
90ed1e67
JD
1674 mix_pool_bytes(buffer, count);
1675 credit_entropy_bits(entropy);
c84dbf61
TD
1676}
1677EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
428826f5
HYW
1678
1679/* Handle random seed passed by bootloader.
1680 * If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise
1681 * it would be regarded as device data.
1682 * The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER.
1683 */
04ec96b7 1684void add_bootloader_randomness(const void *buf, size_t size)
428826f5
HYW
1685{
1686 if (IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER))
1687 add_hwgenerator_randomness(buf, size, size * 8);
1688 else
1689 add_device_randomness(buf, size);
1690}
3fd57e7a 1691EXPORT_SYMBOL_GPL(add_bootloader_randomness);