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