xref: /linux/drivers/char/random.c (revision b485625078cab3b824a84ce185b6e73733704b5b)
1 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
2 /*
3  * Copyright (C) 2017-2024 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
5  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved.
6  *
7  * This driver produces cryptographically secure pseudorandom data. It is divided
8  * into roughly six sections, each with a section header:
9  *
10  *   - Initialization and readiness waiting.
11  *   - Fast key erasure RNG, the "crng".
12  *   - Entropy accumulation and extraction routines.
13  *   - Entropy collection routines.
14  *   - Userspace reader/writer interfaces.
15  *   - Sysctl interface.
16  *
17  * The high level overview is that there is one input pool, into which
18  * various pieces of data are hashed. Prior to initialization, some of that
19  * data is then "credited" as having a certain number of bits of entropy.
20  * When enough bits of entropy are available, the hash is finalized and
21  * handed as a key to a stream cipher that expands it indefinitely for
22  * various consumers. This key is periodically refreshed as the various
23  * entropy collectors, described below, add data to the input pool.
24  */
25 
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27 
28 #include <linux/utsname.h>
29 #include <linux/module.h>
30 #include <linux/kernel.h>
31 #include <linux/major.h>
32 #include <linux/string.h>
33 #include <linux/fcntl.h>
34 #include <linux/slab.h>
35 #include <linux/random.h>
36 #include <linux/poll.h>
37 #include <linux/init.h>
38 #include <linux/fs.h>
39 #include <linux/blkdev.h>
40 #include <linux/interrupt.h>
41 #include <linux/mm.h>
42 #include <linux/nodemask.h>
43 #include <linux/spinlock.h>
44 #include <linux/kthread.h>
45 #include <linux/percpu.h>
46 #include <linux/ptrace.h>
47 #include <linux/workqueue.h>
48 #include <linux/irq.h>
49 #include <linux/ratelimit.h>
50 #include <linux/syscalls.h>
51 #include <linux/completion.h>
52 #include <linux/uuid.h>
53 #include <linux/uaccess.h>
54 #include <linux/suspend.h>
55 #include <linux/siphash.h>
56 #include <linux/sched/isolation.h>
57 #include <crypto/chacha.h>
58 #include <crypto/blake2s.h>
59 #ifdef CONFIG_VDSO_GETRANDOM
60 #include <vdso/getrandom.h>
61 #include <vdso/datapage.h>
62 #endif
63 #include <asm/archrandom.h>
64 #include <asm/processor.h>
65 #include <asm/irq.h>
66 #include <asm/irq_regs.h>
67 #include <asm/io.h>
68 
69 /*********************************************************************
70  *
71  * Initialization and readiness waiting.
72  *
73  * Much of the RNG infrastructure is devoted to various dependencies
74  * being able to wait until the RNG has collected enough entropy and
75  * is ready for safe consumption.
76  *
77  *********************************************************************/
78 
79 /*
80  * crng_init is protected by base_crng->lock, and only increases
81  * its value (from empty->early->ready).
82  */
83 static enum {
84 	CRNG_EMPTY = 0, /* Little to no entropy collected */
85 	CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */
86 	CRNG_READY = 2  /* Fully initialized with POOL_READY_BITS collected */
87 } crng_init __read_mostly = CRNG_EMPTY;
88 static DEFINE_STATIC_KEY_FALSE(crng_is_ready);
89 #define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)
90 /* Various types of waiters for crng_init->CRNG_READY transition. */
91 static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
92 static struct fasync_struct *fasync;
93 static ATOMIC_NOTIFIER_HEAD(random_ready_notifier);
94 
95 /* Control how we warn userspace. */
96 static struct ratelimit_state urandom_warning =
97 	RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);
98 static int ratelimit_disable __read_mostly =
99 	IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
100 module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
101 MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
102 
103 /*
104  * Returns whether or not the input pool has been seeded and thus guaranteed
105  * to supply cryptographically secure random numbers. This applies to: the
106  * /dev/urandom device, the get_random_bytes function, and the get_random_{u8,
107  * u16,u32,u64,long} family of functions.
108  *
109  * Returns: true if the input pool has been seeded.
110  *          false if the input pool has not been seeded.
111  */
112 bool rng_is_initialized(void)
113 {
114 	return crng_ready();
115 }
116 EXPORT_SYMBOL(rng_is_initialized);
117 
118 static void __cold crng_set_ready(struct work_struct *work)
119 {
120 	static_branch_enable(&crng_is_ready);
121 }
122 
123 /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
124 static void try_to_generate_entropy(void);
125 
126 /*
127  * Wait for the input pool to be seeded and thus guaranteed to supply
128  * cryptographically secure random numbers. This applies to: the /dev/urandom
129  * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64,
130  * long} family of functions. Using any of these functions without first
131  * calling this function forfeits the guarantee of security.
132  *
133  * Returns: 0 if the input pool has been seeded.
134  *          -ERESTARTSYS if the function was interrupted by a signal.
135  */
136 int wait_for_random_bytes(void)
137 {
138 	while (!crng_ready()) {
139 		int ret;
140 
141 		try_to_generate_entropy();
142 		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
143 		if (ret)
144 			return ret > 0 ? 0 : ret;
145 	}
146 	return 0;
147 }
148 EXPORT_SYMBOL(wait_for_random_bytes);
149 
150 /*
151  * Add a callback function that will be invoked when the crng is initialised,
152  * or immediately if it already has been. Only use this is you are absolutely
153  * sure it is required. Most users should instead be able to test
154  * `rng_is_initialized()` on demand, or make use of `get_random_bytes_wait()`.
155  */
156 int __cold execute_with_initialized_rng(struct notifier_block *nb)
157 {
158 	unsigned long flags;
159 	int ret = 0;
160 
161 	spin_lock_irqsave(&random_ready_notifier.lock, flags);
162 	if (crng_ready())
163 		nb->notifier_call(nb, 0, NULL);
164 	else
165 		ret = raw_notifier_chain_register((struct raw_notifier_head *)&random_ready_notifier.head, nb);
166 	spin_unlock_irqrestore(&random_ready_notifier.lock, flags);
167 	return ret;
168 }
169 
170 #define warn_unseeded_randomness() \
171 	if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \
172 		printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n", \
173 				__func__, (void *)_RET_IP_, crng_init)
174 
175 
176 /*********************************************************************
177  *
178  * Fast key erasure RNG, the "crng".
179  *
180  * These functions expand entropy from the entropy extractor into
181  * long streams for external consumption using the "fast key erasure"
182  * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
183  *
184  * There are a few exported interfaces for use by other drivers:
185  *
186  *	void get_random_bytes(void *buf, size_t len)
187  *	u8 get_random_u8()
188  *	u16 get_random_u16()
189  *	u32 get_random_u32()
190  *	u32 get_random_u32_below(u32 ceil)
191  *	u32 get_random_u32_above(u32 floor)
192  *	u32 get_random_u32_inclusive(u32 floor, u32 ceil)
193  *	u64 get_random_u64()
194  *	unsigned long get_random_long()
195  *
196  * These interfaces will return the requested number of random bytes
197  * into the given buffer or as a return value. This is equivalent to
198  * a read from /dev/urandom. The u8, u16, u32, u64, long family of
199  * functions may be higher performance for one-off random integers,
200  * because they do a bit of buffering and do not invoke reseeding
201  * until the buffer is emptied.
202  *
203  *********************************************************************/
204 
205 enum {
206 	CRNG_RESEED_START_INTERVAL = HZ,
207 	CRNG_RESEED_INTERVAL = 60 * HZ
208 };
209 
210 static struct {
211 	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
212 	unsigned long generation;
213 	spinlock_t lock;
214 } base_crng = {
215 	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
216 };
217 
218 struct crng {
219 	u8 key[CHACHA_KEY_SIZE];
220 	unsigned long generation;
221 	local_lock_t lock;
222 };
223 
224 static DEFINE_PER_CPU(struct crng, crngs) = {
225 	.generation = ULONG_MAX,
226 	.lock = INIT_LOCAL_LOCK(crngs.lock),
227 };
228 
229 /*
230  * Return the interval until the next reseeding, which is normally
231  * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval
232  * proportional to the uptime.
233  */
234 static unsigned int crng_reseed_interval(void)
235 {
236 	static bool early_boot = true;
237 
238 	if (unlikely(READ_ONCE(early_boot))) {
239 		time64_t uptime = ktime_get_seconds();
240 		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
241 			WRITE_ONCE(early_boot, false);
242 		else
243 			return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
244 				     (unsigned int)uptime / 2 * HZ);
245 	}
246 	return CRNG_RESEED_INTERVAL;
247 }
248 
249 /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
250 static void extract_entropy(void *buf, size_t len);
251 
252 /* This extracts a new crng key from the input pool. */
253 static void crng_reseed(struct work_struct *work)
254 {
255 	static DECLARE_DELAYED_WORK(next_reseed, crng_reseed);
256 	unsigned long flags;
257 	unsigned long next_gen;
258 	u8 key[CHACHA_KEY_SIZE];
259 
260 	/* Immediately schedule the next reseeding, so that it fires sooner rather than later. */
261 	if (likely(system_unbound_wq))
262 		queue_delayed_work(system_unbound_wq, &next_reseed, crng_reseed_interval());
263 
264 	extract_entropy(key, sizeof(key));
265 
266 	/*
267 	 * We copy the new key into the base_crng, overwriting the old one,
268 	 * and update the generation counter. We avoid hitting ULONG_MAX,
269 	 * because the per-cpu crngs are initialized to ULONG_MAX, so this
270 	 * forces new CPUs that come online to always initialize.
271 	 */
272 	spin_lock_irqsave(&base_crng.lock, flags);
273 	memcpy(base_crng.key, key, sizeof(base_crng.key));
274 	next_gen = base_crng.generation + 1;
275 	if (next_gen == ULONG_MAX)
276 		++next_gen;
277 	WRITE_ONCE(base_crng.generation, next_gen);
278 #ifdef CONFIG_VDSO_GETRANDOM
279 	/* base_crng.generation's invalid value is ULONG_MAX, while
280 	 * _vdso_rng_data.generation's invalid value is 0, so add one to the
281 	 * former to arrive at the latter. Use smp_store_release so that this
282 	 * is ordered with the write above to base_crng.generation. Pairs with
283 	 * the smp_rmb() before the syscall in the vDSO code.
284 	 */
285 	smp_store_release(&_vdso_rng_data.generation, next_gen + 1);
286 #endif
287 	if (!static_branch_likely(&crng_is_ready))
288 		crng_init = CRNG_READY;
289 	spin_unlock_irqrestore(&base_crng.lock, flags);
290 	memzero_explicit(key, sizeof(key));
291 }
292 
293 /*
294  * This generates a ChaCha block using the provided key, and then
295  * immediately overwrites that key with half the block. It returns
296  * the resultant ChaCha state to the user, along with the second
297  * half of the block containing 32 bytes of random data that may
298  * be used; random_data_len may not be greater than 32.
299  *
300  * The returned ChaCha state contains within it a copy of the old
301  * key value, at index 4, so the state should always be zeroed out
302  * immediately after using in order to maintain forward secrecy.
303  * If the state cannot be erased in a timely manner, then it is
304  * safer to set the random_data parameter to &chacha_state[4] so
305  * that this function overwrites it before returning.
306  */
307 static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
308 				  u32 chacha_state[CHACHA_STATE_WORDS],
309 				  u8 *random_data, size_t random_data_len)
310 {
311 	u8 first_block[CHACHA_BLOCK_SIZE];
312 
313 	BUG_ON(random_data_len > 32);
314 
315 	chacha_init_consts(chacha_state);
316 	memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
317 	memset(&chacha_state[12], 0, sizeof(u32) * 4);
318 	chacha20_block(chacha_state, first_block);
319 
320 	memcpy(key, first_block, CHACHA_KEY_SIZE);
321 	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
322 	memzero_explicit(first_block, sizeof(first_block));
323 }
324 
325 /*
326  * This function returns a ChaCha state that you may use for generating
327  * random data. It also returns up to 32 bytes on its own of random data
328  * that may be used; random_data_len may not be greater than 32.
329  */
330 static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
331 			    u8 *random_data, size_t random_data_len)
332 {
333 	unsigned long flags;
334 	struct crng *crng;
335 
336 	BUG_ON(random_data_len > 32);
337 
338 	/*
339 	 * For the fast path, we check whether we're ready, unlocked first, and
340 	 * then re-check once locked later. In the case where we're really not
341 	 * ready, we do fast key erasure with the base_crng directly, extracting
342 	 * when crng_init is CRNG_EMPTY.
343 	 */
344 	if (!crng_ready()) {
345 		bool ready;
346 
347 		spin_lock_irqsave(&base_crng.lock, flags);
348 		ready = crng_ready();
349 		if (!ready) {
350 			if (crng_init == CRNG_EMPTY)
351 				extract_entropy(base_crng.key, sizeof(base_crng.key));
352 			crng_fast_key_erasure(base_crng.key, chacha_state,
353 					      random_data, random_data_len);
354 		}
355 		spin_unlock_irqrestore(&base_crng.lock, flags);
356 		if (!ready)
357 			return;
358 	}
359 
360 	local_lock_irqsave(&crngs.lock, flags);
361 	crng = raw_cpu_ptr(&crngs);
362 
363 	/*
364 	 * If our per-cpu crng is older than the base_crng, then it means
365 	 * somebody reseeded the base_crng. In that case, we do fast key
366 	 * erasure on the base_crng, and use its output as the new key
367 	 * for our per-cpu crng. This brings us up to date with base_crng.
368 	 */
369 	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
370 		spin_lock(&base_crng.lock);
371 		crng_fast_key_erasure(base_crng.key, chacha_state,
372 				      crng->key, sizeof(crng->key));
373 		crng->generation = base_crng.generation;
374 		spin_unlock(&base_crng.lock);
375 	}
376 
377 	/*
378 	 * Finally, when we've made it this far, our per-cpu crng has an up
379 	 * to date key, and we can do fast key erasure with it to produce
380 	 * some random data and a ChaCha state for the caller. All other
381 	 * branches of this function are "unlikely", so most of the time we
382 	 * should wind up here immediately.
383 	 */
384 	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
385 	local_unlock_irqrestore(&crngs.lock, flags);
386 }
387 
388 static void _get_random_bytes(void *buf, size_t len)
389 {
390 	u32 chacha_state[CHACHA_STATE_WORDS];
391 	u8 tmp[CHACHA_BLOCK_SIZE];
392 	size_t first_block_len;
393 
394 	if (!len)
395 		return;
396 
397 	first_block_len = min_t(size_t, 32, len);
398 	crng_make_state(chacha_state, buf, first_block_len);
399 	len -= first_block_len;
400 	buf += first_block_len;
401 
402 	while (len) {
403 		if (len < CHACHA_BLOCK_SIZE) {
404 			chacha20_block(chacha_state, tmp);
405 			memcpy(buf, tmp, len);
406 			memzero_explicit(tmp, sizeof(tmp));
407 			break;
408 		}
409 
410 		chacha20_block(chacha_state, buf);
411 		if (unlikely(chacha_state[12] == 0))
412 			++chacha_state[13];
413 		len -= CHACHA_BLOCK_SIZE;
414 		buf += CHACHA_BLOCK_SIZE;
415 	}
416 
417 	memzero_explicit(chacha_state, sizeof(chacha_state));
418 }
419 
420 /*
421  * This returns random bytes in arbitrary quantities. The quality of the
422  * random bytes is good as /dev/urandom. In order to ensure that the
423  * randomness provided by this function is okay, the function
424  * wait_for_random_bytes() should be called and return 0 at least once
425  * at any point prior.
426  */
427 void get_random_bytes(void *buf, size_t len)
428 {
429 	warn_unseeded_randomness();
430 	_get_random_bytes(buf, len);
431 }
432 EXPORT_SYMBOL(get_random_bytes);
433 
434 static ssize_t get_random_bytes_user(struct iov_iter *iter)
435 {
436 	u32 chacha_state[CHACHA_STATE_WORDS];
437 	u8 block[CHACHA_BLOCK_SIZE];
438 	size_t ret = 0, copied;
439 
440 	if (unlikely(!iov_iter_count(iter)))
441 		return 0;
442 
443 	/*
444 	 * Immediately overwrite the ChaCha key at index 4 with random
445 	 * bytes, in case userspace causes copy_to_iter() below to sleep
446 	 * forever, so that we still retain forward secrecy in that case.
447 	 */
448 	crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
449 	/*
450 	 * However, if we're doing a read of len <= 32, we don't need to
451 	 * use chacha_state after, so we can simply return those bytes to
452 	 * the user directly.
453 	 */
454 	if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
455 		ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
456 		goto out_zero_chacha;
457 	}
458 
459 	for (;;) {
460 		chacha20_block(chacha_state, block);
461 		if (unlikely(chacha_state[12] == 0))
462 			++chacha_state[13];
463 
464 		copied = copy_to_iter(block, sizeof(block), iter);
465 		ret += copied;
466 		if (!iov_iter_count(iter) || copied != sizeof(block))
467 			break;
468 
469 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
470 		if (ret % PAGE_SIZE == 0) {
471 			if (signal_pending(current))
472 				break;
473 			cond_resched();
474 		}
475 	}
476 
477 	memzero_explicit(block, sizeof(block));
478 out_zero_chacha:
479 	memzero_explicit(chacha_state, sizeof(chacha_state));
480 	return ret ? ret : -EFAULT;
481 }
482 
483 /*
484  * Batched entropy returns random integers. The quality of the random
485  * number is good as /dev/urandom. In order to ensure that the randomness
486  * provided by this function is okay, the function wait_for_random_bytes()
487  * should be called and return 0 at least once at any point prior.
488  */
489 
490 #define DEFINE_BATCHED_ENTROPY(type)						\
491 struct batch_ ##type {								\
492 	/*									\
493 	 * We make this 1.5x a ChaCha block, so that we get the			\
494 	 * remaining 32 bytes from fast key erasure, plus one full		\
495 	 * block from the detached ChaCha state. We can increase		\
496 	 * the size of this later if needed so long as we keep the		\
497 	 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.		\
498 	 */									\
499 	type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))];		\
500 	local_lock_t lock;							\
501 	unsigned long generation;						\
502 	unsigned int position;							\
503 };										\
504 										\
505 static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = {	\
506 	.lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock),			\
507 	.position = UINT_MAX							\
508 };										\
509 										\
510 type get_random_ ##type(void)							\
511 {										\
512 	type ret;								\
513 	unsigned long flags;							\
514 	struct batch_ ##type *batch;						\
515 	unsigned long next_gen;							\
516 										\
517 	warn_unseeded_randomness();						\
518 										\
519 	if  (!crng_ready()) {							\
520 		_get_random_bytes(&ret, sizeof(ret));				\
521 		return ret;							\
522 	}									\
523 										\
524 	local_lock_irqsave(&batched_entropy_ ##type.lock, flags);		\
525 	batch = raw_cpu_ptr(&batched_entropy_##type);				\
526 										\
527 	next_gen = READ_ONCE(base_crng.generation);				\
528 	if (batch->position >= ARRAY_SIZE(batch->entropy) ||			\
529 	    next_gen != batch->generation) {					\
530 		_get_random_bytes(batch->entropy, sizeof(batch->entropy));	\
531 		batch->position = 0;						\
532 		batch->generation = next_gen;					\
533 	}									\
534 										\
535 	ret = batch->entropy[batch->position];					\
536 	batch->entropy[batch->position] = 0;					\
537 	++batch->position;							\
538 	local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags);		\
539 	return ret;								\
540 }										\
541 EXPORT_SYMBOL(get_random_ ##type);
542 
543 DEFINE_BATCHED_ENTROPY(u8)
544 DEFINE_BATCHED_ENTROPY(u16)
545 DEFINE_BATCHED_ENTROPY(u32)
546 DEFINE_BATCHED_ENTROPY(u64)
547 
548 u32 __get_random_u32_below(u32 ceil)
549 {
550 	/*
551 	 * This is the slow path for variable ceil. It is still fast, most of
552 	 * the time, by doing traditional reciprocal multiplication and
553 	 * opportunistically comparing the lower half to ceil itself, before
554 	 * falling back to computing a larger bound, and then rejecting samples
555 	 * whose lower half would indicate a range indivisible by ceil. The use
556 	 * of `-ceil % ceil` is analogous to `2^32 % ceil`, but is computable
557 	 * in 32-bits.
558 	 */
559 	u32 rand = get_random_u32();
560 	u64 mult;
561 
562 	/*
563 	 * This function is technically undefined for ceil == 0, and in fact
564 	 * for the non-underscored constant version in the header, we build bug
565 	 * on that. But for the non-constant case, it's convenient to have that
566 	 * evaluate to being a straight call to get_random_u32(), so that
567 	 * get_random_u32_inclusive() can work over its whole range without
568 	 * undefined behavior.
569 	 */
570 	if (unlikely(!ceil))
571 		return rand;
572 
573 	mult = (u64)ceil * rand;
574 	if (unlikely((u32)mult < ceil)) {
575 		u32 bound = -ceil % ceil;
576 		while (unlikely((u32)mult < bound))
577 			mult = (u64)ceil * get_random_u32();
578 	}
579 	return mult >> 32;
580 }
581 EXPORT_SYMBOL(__get_random_u32_below);
582 
583 #ifdef CONFIG_SMP
584 /*
585  * This function is called when the CPU is coming up, with entry
586  * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
587  */
588 int __cold random_prepare_cpu(unsigned int cpu)
589 {
590 	/*
591 	 * When the cpu comes back online, immediately invalidate both
592 	 * the per-cpu crng and all batches, so that we serve fresh
593 	 * randomness.
594 	 */
595 	per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
596 	per_cpu_ptr(&batched_entropy_u8, cpu)->position = UINT_MAX;
597 	per_cpu_ptr(&batched_entropy_u16, cpu)->position = UINT_MAX;
598 	per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
599 	per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
600 	return 0;
601 }
602 #endif
603 
604 
605 /**********************************************************************
606  *
607  * Entropy accumulation and extraction routines.
608  *
609  * Callers may add entropy via:
610  *
611  *     static void mix_pool_bytes(const void *buf, size_t len)
612  *
613  * After which, if added entropy should be credited:
614  *
615  *     static void credit_init_bits(size_t bits)
616  *
617  * Finally, extract entropy via:
618  *
619  *     static void extract_entropy(void *buf, size_t len)
620  *
621  **********************************************************************/
622 
623 enum {
624 	POOL_BITS = BLAKE2S_HASH_SIZE * 8,
625 	POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
626 	POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
627 };
628 
629 static struct {
630 	struct blake2s_state hash;
631 	spinlock_t lock;
632 	unsigned int init_bits;
633 } input_pool = {
634 	.hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
635 		    BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
636 		    BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
637 	.hash.outlen = BLAKE2S_HASH_SIZE,
638 	.lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
639 };
640 
641 static void _mix_pool_bytes(const void *buf, size_t len)
642 {
643 	blake2s_update(&input_pool.hash, buf, len);
644 }
645 
646 /*
647  * This function adds bytes into the input pool. It does not
648  * update the initialization bit counter; the caller should call
649  * credit_init_bits if this is appropriate.
650  */
651 static void mix_pool_bytes(const void *buf, size_t len)
652 {
653 	unsigned long flags;
654 
655 	spin_lock_irqsave(&input_pool.lock, flags);
656 	_mix_pool_bytes(buf, len);
657 	spin_unlock_irqrestore(&input_pool.lock, flags);
658 }
659 
660 /*
661  * This is an HKDF-like construction for using the hashed collected entropy
662  * as a PRF key, that's then expanded block-by-block.
663  */
664 static void extract_entropy(void *buf, size_t len)
665 {
666 	unsigned long flags;
667 	u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
668 	struct {
669 		unsigned long rdseed[32 / sizeof(long)];
670 		size_t counter;
671 	} block;
672 	size_t i, longs;
673 
674 	for (i = 0; i < ARRAY_SIZE(block.rdseed);) {
675 		longs = arch_get_random_seed_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
676 		if (longs) {
677 			i += longs;
678 			continue;
679 		}
680 		longs = arch_get_random_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
681 		if (longs) {
682 			i += longs;
683 			continue;
684 		}
685 		block.rdseed[i++] = random_get_entropy();
686 	}
687 
688 	spin_lock_irqsave(&input_pool.lock, flags);
689 
690 	/* seed = HASHPRF(last_key, entropy_input) */
691 	blake2s_final(&input_pool.hash, seed);
692 
693 	/* next_key = HASHPRF(seed, RDSEED || 0) */
694 	block.counter = 0;
695 	blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
696 	blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
697 
698 	spin_unlock_irqrestore(&input_pool.lock, flags);
699 	memzero_explicit(next_key, sizeof(next_key));
700 
701 	while (len) {
702 		i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
703 		/* output = HASHPRF(seed, RDSEED || ++counter) */
704 		++block.counter;
705 		blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
706 		len -= i;
707 		buf += i;
708 	}
709 
710 	memzero_explicit(seed, sizeof(seed));
711 	memzero_explicit(&block, sizeof(block));
712 }
713 
714 #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
715 
716 static void __cold _credit_init_bits(size_t bits)
717 {
718 	static DECLARE_WORK(set_ready, crng_set_ready);
719 	unsigned int new, orig, add;
720 	unsigned long flags;
721 
722 	if (!bits)
723 		return;
724 
725 	add = min_t(size_t, bits, POOL_BITS);
726 
727 	orig = READ_ONCE(input_pool.init_bits);
728 	do {
729 		new = min_t(unsigned int, POOL_BITS, orig + add);
730 	} while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
731 
732 	if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
733 		crng_reseed(NULL); /* Sets crng_init to CRNG_READY under base_crng.lock. */
734 		if (static_key_initialized && system_unbound_wq)
735 			queue_work(system_unbound_wq, &set_ready);
736 		atomic_notifier_call_chain(&random_ready_notifier, 0, NULL);
737 #ifdef CONFIG_VDSO_GETRANDOM
738 		WRITE_ONCE(_vdso_rng_data.is_ready, true);
739 #endif
740 		wake_up_interruptible(&crng_init_wait);
741 		kill_fasync(&fasync, SIGIO, POLL_IN);
742 		pr_notice("crng init done\n");
743 		if (urandom_warning.missed)
744 			pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
745 				  urandom_warning.missed);
746 	} else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
747 		spin_lock_irqsave(&base_crng.lock, flags);
748 		/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
749 		if (crng_init == CRNG_EMPTY) {
750 			extract_entropy(base_crng.key, sizeof(base_crng.key));
751 			crng_init = CRNG_EARLY;
752 		}
753 		spin_unlock_irqrestore(&base_crng.lock, flags);
754 	}
755 }
756 
757 
758 /**********************************************************************
759  *
760  * Entropy collection routines.
761  *
762  * The following exported functions are used for pushing entropy into
763  * the above entropy accumulation routines:
764  *
765  *	void add_device_randomness(const void *buf, size_t len);
766  *	void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after);
767  *	void add_bootloader_randomness(const void *buf, size_t len);
768  *	void add_vmfork_randomness(const void *unique_vm_id, size_t len);
769  *	void add_interrupt_randomness(int irq);
770  *	void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
771  *	void add_disk_randomness(struct gendisk *disk);
772  *
773  * add_device_randomness() adds data to the input pool that
774  * is likely to differ between two devices (or possibly even per boot).
775  * This would be things like MAC addresses or serial numbers, or the
776  * read-out of the RTC. This does *not* credit any actual entropy to
777  * the pool, but it initializes the pool to different values for devices
778  * that might otherwise be identical and have very little entropy
779  * available to them (particularly common in the embedded world).
780  *
781  * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
782  * entropy as specified by the caller. If the entropy pool is full it will
783  * block until more entropy is needed.
784  *
785  * add_bootloader_randomness() is called by bootloader drivers, such as EFI
786  * and device tree, and credits its input depending on whether or not the
787  * command line option 'random.trust_bootloader'.
788  *
789  * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
790  * representing the current instance of a VM to the pool, without crediting,
791  * and then force-reseeds the crng so that it takes effect immediately.
792  *
793  * add_interrupt_randomness() uses the interrupt timing as random
794  * inputs to the entropy pool. Using the cycle counters and the irq source
795  * as inputs, it feeds the input pool roughly once a second or after 64
796  * interrupts, crediting 1 bit of entropy for whichever comes first.
797  *
798  * add_input_randomness() uses the input layer interrupt timing, as well
799  * as the event type information from the hardware.
800  *
801  * add_disk_randomness() uses what amounts to the seek time of block
802  * layer request events, on a per-disk_devt basis, as input to the
803  * entropy pool. Note that high-speed solid state drives with very low
804  * seek times do not make for good sources of entropy, as their seek
805  * times are usually fairly consistent.
806  *
807  * The last two routines try to estimate how many bits of entropy
808  * to credit. They do this by keeping track of the first and second
809  * order deltas of the event timings.
810  *
811  **********************************************************************/
812 
813 static bool trust_cpu __initdata = true;
814 static bool trust_bootloader __initdata = true;
815 static int __init parse_trust_cpu(char *arg)
816 {
817 	return kstrtobool(arg, &trust_cpu);
818 }
819 static int __init parse_trust_bootloader(char *arg)
820 {
821 	return kstrtobool(arg, &trust_bootloader);
822 }
823 early_param("random.trust_cpu", parse_trust_cpu);
824 early_param("random.trust_bootloader", parse_trust_bootloader);
825 
826 static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
827 {
828 	unsigned long flags, entropy = random_get_entropy();
829 
830 	/*
831 	 * Encode a representation of how long the system has been suspended,
832 	 * in a way that is distinct from prior system suspends.
833 	 */
834 	ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
835 
836 	spin_lock_irqsave(&input_pool.lock, flags);
837 	_mix_pool_bytes(&action, sizeof(action));
838 	_mix_pool_bytes(stamps, sizeof(stamps));
839 	_mix_pool_bytes(&entropy, sizeof(entropy));
840 	spin_unlock_irqrestore(&input_pool.lock, flags);
841 
842 	if (crng_ready() && (action == PM_RESTORE_PREPARE ||
843 	    (action == PM_POST_SUSPEND && !IS_ENABLED(CONFIG_PM_AUTOSLEEP) &&
844 	     !IS_ENABLED(CONFIG_PM_USERSPACE_AUTOSLEEP)))) {
845 		crng_reseed(NULL);
846 		pr_notice("crng reseeded on system resumption\n");
847 	}
848 	return 0;
849 }
850 
851 static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
852 
853 /*
854  * This is called extremely early, before time keeping functionality is
855  * available, but arch randomness is. Interrupts are not yet enabled.
856  */
857 void __init random_init_early(const char *command_line)
858 {
859 	unsigned long entropy[BLAKE2S_BLOCK_SIZE / sizeof(long)];
860 	size_t i, longs, arch_bits;
861 
862 #if defined(LATENT_ENTROPY_PLUGIN)
863 	static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
864 	_mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
865 #endif
866 
867 	for (i = 0, arch_bits = sizeof(entropy) * 8; i < ARRAY_SIZE(entropy);) {
868 		longs = arch_get_random_seed_longs(entropy, ARRAY_SIZE(entropy) - i);
869 		if (longs) {
870 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
871 			i += longs;
872 			continue;
873 		}
874 		longs = arch_get_random_longs(entropy, ARRAY_SIZE(entropy) - i);
875 		if (longs) {
876 			_mix_pool_bytes(entropy, sizeof(*entropy) * longs);
877 			i += longs;
878 			continue;
879 		}
880 		arch_bits -= sizeof(*entropy) * 8;
881 		++i;
882 	}
883 
884 	_mix_pool_bytes(init_utsname(), sizeof(*(init_utsname())));
885 	_mix_pool_bytes(command_line, strlen(command_line));
886 
887 	/* Reseed if already seeded by earlier phases. */
888 	if (crng_ready())
889 		crng_reseed(NULL);
890 	else if (trust_cpu)
891 		_credit_init_bits(arch_bits);
892 }
893 
894 /*
895  * This is called a little bit after the prior function, and now there is
896  * access to timestamps counters. Interrupts are not yet enabled.
897  */
898 void __init random_init(void)
899 {
900 	unsigned long entropy = random_get_entropy();
901 	ktime_t now = ktime_get_real();
902 
903 	_mix_pool_bytes(&now, sizeof(now));
904 	_mix_pool_bytes(&entropy, sizeof(entropy));
905 	add_latent_entropy();
906 
907 	/*
908 	 * If we were initialized by the cpu or bootloader before jump labels
909 	 * or workqueues are initialized, then we should enable the static
910 	 * branch here, where it's guaranteed that these have been initialized.
911 	 */
912 	if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
913 		crng_set_ready(NULL);
914 
915 	/* Reseed if already seeded by earlier phases. */
916 	if (crng_ready())
917 		crng_reseed(NULL);
918 
919 	WARN_ON(register_pm_notifier(&pm_notifier));
920 
921 	WARN(!entropy, "Missing cycle counter and fallback timer; RNG "
922 		       "entropy collection will consequently suffer.");
923 }
924 
925 /*
926  * Add device- or boot-specific data to the input pool to help
927  * initialize it.
928  *
929  * None of this adds any entropy; it is meant to avoid the problem of
930  * the entropy pool having similar initial state across largely
931  * identical devices.
932  */
933 void add_device_randomness(const void *buf, size_t len)
934 {
935 	unsigned long entropy = random_get_entropy();
936 	unsigned long flags;
937 
938 	spin_lock_irqsave(&input_pool.lock, flags);
939 	_mix_pool_bytes(&entropy, sizeof(entropy));
940 	_mix_pool_bytes(buf, len);
941 	spin_unlock_irqrestore(&input_pool.lock, flags);
942 }
943 EXPORT_SYMBOL(add_device_randomness);
944 
945 /*
946  * Interface for in-kernel drivers of true hardware RNGs. Those devices
947  * may produce endless random bits, so this function will sleep for
948  * some amount of time after, if the sleep_after parameter is true.
949  */
950 void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after)
951 {
952 	mix_pool_bytes(buf, len);
953 	credit_init_bits(entropy);
954 
955 	/*
956 	 * Throttle writing to once every reseed interval, unless we're not yet
957 	 * initialized or no entropy is credited.
958 	 */
959 	if (sleep_after && !kthread_should_stop() && (crng_ready() || !entropy))
960 		schedule_timeout_interruptible(crng_reseed_interval());
961 }
962 EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
963 
964 /*
965  * Handle random seed passed by bootloader, and credit it depending
966  * on the command line option 'random.trust_bootloader'.
967  */
968 void __init add_bootloader_randomness(const void *buf, size_t len)
969 {
970 	mix_pool_bytes(buf, len);
971 	if (trust_bootloader)
972 		credit_init_bits(len * 8);
973 }
974 
975 #if IS_ENABLED(CONFIG_VMGENID)
976 static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
977 
978 /*
979  * Handle a new unique VM ID, which is unique, not secret, so we
980  * don't credit it, but we do immediately force a reseed after so
981  * that it's used by the crng posthaste.
982  */
983 void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
984 {
985 	add_device_randomness(unique_vm_id, len);
986 	if (crng_ready()) {
987 		crng_reseed(NULL);
988 		pr_notice("crng reseeded due to virtual machine fork\n");
989 	}
990 	blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
991 }
992 #if IS_MODULE(CONFIG_VMGENID)
993 EXPORT_SYMBOL_GPL(add_vmfork_randomness);
994 #endif
995 
996 int __cold register_random_vmfork_notifier(struct notifier_block *nb)
997 {
998 	return blocking_notifier_chain_register(&vmfork_chain, nb);
999 }
1000 EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
1001 
1002 int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
1003 {
1004 	return blocking_notifier_chain_unregister(&vmfork_chain, nb);
1005 }
1006 EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
1007 #endif
1008 
1009 struct fast_pool {
1010 	unsigned long pool[4];
1011 	unsigned long last;
1012 	unsigned int count;
1013 	struct timer_list mix;
1014 };
1015 
1016 static void mix_interrupt_randomness(struct timer_list *work);
1017 
1018 static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
1019 #ifdef CONFIG_64BIT
1020 #define FASTMIX_PERM SIPHASH_PERMUTATION
1021 	.pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 },
1022 #else
1023 #define FASTMIX_PERM HSIPHASH_PERMUTATION
1024 	.pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 },
1025 #endif
1026 	.mix = __TIMER_INITIALIZER(mix_interrupt_randomness, 0)
1027 };
1028 
1029 /*
1030  * This is [Half]SipHash-1-x, starting from an empty key. Because
1031  * the key is fixed, it assumes that its inputs are non-malicious,
1032  * and therefore this has no security on its own. s represents the
1033  * four-word SipHash state, while v represents a two-word input.
1034  */
1035 static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
1036 {
1037 	s[3] ^= v1;
1038 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1039 	s[0] ^= v1;
1040 	s[3] ^= v2;
1041 	FASTMIX_PERM(s[0], s[1], s[2], s[3]);
1042 	s[0] ^= v2;
1043 }
1044 
1045 #ifdef CONFIG_SMP
1046 /*
1047  * This function is called when the CPU has just come online, with
1048  * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
1049  */
1050 int __cold random_online_cpu(unsigned int cpu)
1051 {
1052 	/*
1053 	 * During CPU shutdown and before CPU onlining, add_interrupt_
1054 	 * randomness() may schedule mix_interrupt_randomness(), and
1055 	 * set the MIX_INFLIGHT flag. However, because the worker can
1056 	 * be scheduled on a different CPU during this period, that
1057 	 * flag will never be cleared. For that reason, we zero out
1058 	 * the flag here, which runs just after workqueues are onlined
1059 	 * for the CPU again. This also has the effect of setting the
1060 	 * irq randomness count to zero so that new accumulated irqs
1061 	 * are fresh.
1062 	 */
1063 	per_cpu_ptr(&irq_randomness, cpu)->count = 0;
1064 	return 0;
1065 }
1066 #endif
1067 
1068 static void mix_interrupt_randomness(struct timer_list *work)
1069 {
1070 	struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
1071 	/*
1072 	 * The size of the copied stack pool is explicitly 2 longs so that we
1073 	 * only ever ingest half of the siphash output each time, retaining
1074 	 * the other half as the next "key" that carries over. The entropy is
1075 	 * supposed to be sufficiently dispersed between bits so on average
1076 	 * we don't wind up "losing" some.
1077 	 */
1078 	unsigned long pool[2];
1079 	unsigned int count;
1080 
1081 	/* Check to see if we're running on the wrong CPU due to hotplug. */
1082 	local_irq_disable();
1083 	if (fast_pool != this_cpu_ptr(&irq_randomness)) {
1084 		local_irq_enable();
1085 		return;
1086 	}
1087 
1088 	/*
1089 	 * Copy the pool to the stack so that the mixer always has a
1090 	 * consistent view, before we reenable irqs again.
1091 	 */
1092 	memcpy(pool, fast_pool->pool, sizeof(pool));
1093 	count = fast_pool->count;
1094 	fast_pool->count = 0;
1095 	fast_pool->last = jiffies;
1096 	local_irq_enable();
1097 
1098 	mix_pool_bytes(pool, sizeof(pool));
1099 	credit_init_bits(clamp_t(unsigned int, (count & U16_MAX) / 64, 1, sizeof(pool) * 8));
1100 
1101 	memzero_explicit(pool, sizeof(pool));
1102 }
1103 
1104 void add_interrupt_randomness(int irq)
1105 {
1106 	enum { MIX_INFLIGHT = 1U << 31 };
1107 	unsigned long entropy = random_get_entropy();
1108 	struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
1109 	struct pt_regs *regs = get_irq_regs();
1110 	unsigned int new_count;
1111 
1112 	fast_mix(fast_pool->pool, entropy,
1113 		 (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
1114 	new_count = ++fast_pool->count;
1115 
1116 	if (new_count & MIX_INFLIGHT)
1117 		return;
1118 
1119 	if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
1120 		return;
1121 
1122 	fast_pool->count |= MIX_INFLIGHT;
1123 	if (!timer_pending(&fast_pool->mix)) {
1124 		fast_pool->mix.expires = jiffies;
1125 		add_timer_on(&fast_pool->mix, raw_smp_processor_id());
1126 	}
1127 }
1128 EXPORT_SYMBOL_GPL(add_interrupt_randomness);
1129 
1130 /* There is one of these per entropy source */
1131 struct timer_rand_state {
1132 	unsigned long last_time;
1133 	long last_delta, last_delta2;
1134 };
1135 
1136 /*
1137  * This function adds entropy to the entropy "pool" by using timing
1138  * delays. It uses the timer_rand_state structure to make an estimate
1139  * of how many bits of entropy this call has added to the pool. The
1140  * value "num" is also added to the pool; it should somehow describe
1141  * the type of event that just happened.
1142  */
1143 static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
1144 {
1145 	unsigned long entropy = random_get_entropy(), now = jiffies, flags;
1146 	long delta, delta2, delta3;
1147 	unsigned int bits;
1148 
1149 	/*
1150 	 * If we're in a hard IRQ, add_interrupt_randomness() will be called
1151 	 * sometime after, so mix into the fast pool.
1152 	 */
1153 	if (in_hardirq()) {
1154 		fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
1155 	} else {
1156 		spin_lock_irqsave(&input_pool.lock, flags);
1157 		_mix_pool_bytes(&entropy, sizeof(entropy));
1158 		_mix_pool_bytes(&num, sizeof(num));
1159 		spin_unlock_irqrestore(&input_pool.lock, flags);
1160 	}
1161 
1162 	if (crng_ready())
1163 		return;
1164 
1165 	/*
1166 	 * Calculate number of bits of randomness we probably added.
1167 	 * We take into account the first, second and third-order deltas
1168 	 * in order to make our estimate.
1169 	 */
1170 	delta = now - READ_ONCE(state->last_time);
1171 	WRITE_ONCE(state->last_time, now);
1172 
1173 	delta2 = delta - READ_ONCE(state->last_delta);
1174 	WRITE_ONCE(state->last_delta, delta);
1175 
1176 	delta3 = delta2 - READ_ONCE(state->last_delta2);
1177 	WRITE_ONCE(state->last_delta2, delta2);
1178 
1179 	if (delta < 0)
1180 		delta = -delta;
1181 	if (delta2 < 0)
1182 		delta2 = -delta2;
1183 	if (delta3 < 0)
1184 		delta3 = -delta3;
1185 	if (delta > delta2)
1186 		delta = delta2;
1187 	if (delta > delta3)
1188 		delta = delta3;
1189 
1190 	/*
1191 	 * delta is now minimum absolute delta. Round down by 1 bit
1192 	 * on general principles, and limit entropy estimate to 11 bits.
1193 	 */
1194 	bits = min(fls(delta >> 1), 11);
1195 
1196 	/*
1197 	 * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
1198 	 * will run after this, which uses a different crediting scheme of 1 bit
1199 	 * per every 64 interrupts. In order to let that function do accounting
1200 	 * close to the one in this function, we credit a full 64/64 bit per bit,
1201 	 * and then subtract one to account for the extra one added.
1202 	 */
1203 	if (in_hardirq())
1204 		this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
1205 	else
1206 		_credit_init_bits(bits);
1207 }
1208 
1209 void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
1210 {
1211 	static unsigned char last_value;
1212 	static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
1213 
1214 	/* Ignore autorepeat and the like. */
1215 	if (value == last_value)
1216 		return;
1217 
1218 	last_value = value;
1219 	add_timer_randomness(&input_timer_state,
1220 			     (type << 4) ^ code ^ (code >> 4) ^ value);
1221 }
1222 EXPORT_SYMBOL_GPL(add_input_randomness);
1223 
1224 #ifdef CONFIG_BLOCK
1225 void add_disk_randomness(struct gendisk *disk)
1226 {
1227 	if (!disk || !disk->random)
1228 		return;
1229 	/* First major is 1, so we get >= 0x200 here. */
1230 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1231 }
1232 EXPORT_SYMBOL_GPL(add_disk_randomness);
1233 
1234 void __cold rand_initialize_disk(struct gendisk *disk)
1235 {
1236 	struct timer_rand_state *state;
1237 
1238 	/*
1239 	 * If kzalloc returns null, we just won't use that entropy
1240 	 * source.
1241 	 */
1242 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1243 	if (state) {
1244 		state->last_time = INITIAL_JIFFIES;
1245 		disk->random = state;
1246 	}
1247 }
1248 #endif
1249 
1250 struct entropy_timer_state {
1251 	unsigned long entropy;
1252 	struct timer_list timer;
1253 	atomic_t samples;
1254 	unsigned int samples_per_bit;
1255 };
1256 
1257 /*
1258  * Each time the timer fires, we expect that we got an unpredictable jump in
1259  * the cycle counter. Even if the timer is running on another CPU, the timer
1260  * activity will be touching the stack of the CPU that is generating entropy.
1261  *
1262  * Note that we don't re-arm the timer in the timer itself - we are happy to be
1263  * scheduled away, since that just makes the load more complex, but we do not
1264  * want the timer to keep ticking unless the entropy loop is running.
1265  *
1266  * So the re-arming always happens in the entropy loop itself.
1267  */
1268 static void __cold entropy_timer(struct timer_list *timer)
1269 {
1270 	struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
1271 	unsigned long entropy = random_get_entropy();
1272 
1273 	mix_pool_bytes(&entropy, sizeof(entropy));
1274 	if (atomic_inc_return(&state->samples) % state->samples_per_bit == 0)
1275 		credit_init_bits(1);
1276 }
1277 
1278 /*
1279  * If we have an actual cycle counter, see if we can generate enough entropy
1280  * with timing noise.
1281  */
1282 static void __cold try_to_generate_entropy(void)
1283 {
1284 	enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 15 };
1285 	u8 stack_bytes[sizeof(struct entropy_timer_state) + SMP_CACHE_BYTES - 1];
1286 	struct entropy_timer_state *stack = PTR_ALIGN((void *)stack_bytes, SMP_CACHE_BYTES);
1287 	unsigned int i, num_different = 0;
1288 	unsigned long last = random_get_entropy();
1289 	int cpu = -1;
1290 
1291 	for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
1292 		stack->entropy = random_get_entropy();
1293 		if (stack->entropy != last)
1294 			++num_different;
1295 		last = stack->entropy;
1296 	}
1297 	stack->samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
1298 	if (stack->samples_per_bit > MAX_SAMPLES_PER_BIT)
1299 		return;
1300 
1301 	atomic_set(&stack->samples, 0);
1302 	timer_setup_on_stack(&stack->timer, entropy_timer, 0);
1303 	while (!crng_ready() && !signal_pending(current)) {
1304 		/*
1305 		 * Check !timer_pending() and then ensure that any previous callback has finished
1306 		 * executing by checking try_to_del_timer_sync(), before queueing the next one.
1307 		 */
1308 		if (!timer_pending(&stack->timer) && try_to_del_timer_sync(&stack->timer) >= 0) {
1309 			struct cpumask timer_cpus;
1310 			unsigned int num_cpus;
1311 
1312 			/*
1313 			 * Preemption must be disabled here, both to read the current CPU number
1314 			 * and to avoid scheduling a timer on a dead CPU.
1315 			 */
1316 			preempt_disable();
1317 
1318 			/* Only schedule callbacks on timer CPUs that are online. */
1319 			cpumask_and(&timer_cpus, housekeeping_cpumask(HK_TYPE_TIMER), cpu_online_mask);
1320 			num_cpus = cpumask_weight(&timer_cpus);
1321 			/* In very bizarre case of misconfiguration, fallback to all online. */
1322 			if (unlikely(num_cpus == 0)) {
1323 				timer_cpus = *cpu_online_mask;
1324 				num_cpus = cpumask_weight(&timer_cpus);
1325 			}
1326 
1327 			/* Basic CPU round-robin, which avoids the current CPU. */
1328 			do {
1329 				cpu = cpumask_next(cpu, &timer_cpus);
1330 				if (cpu >= nr_cpu_ids)
1331 					cpu = cpumask_first(&timer_cpus);
1332 			} while (cpu == smp_processor_id() && num_cpus > 1);
1333 
1334 			/* Expiring the timer at `jiffies` means it's the next tick. */
1335 			stack->timer.expires = jiffies;
1336 
1337 			add_timer_on(&stack->timer, cpu);
1338 
1339 			preempt_enable();
1340 		}
1341 		mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
1342 		schedule();
1343 		stack->entropy = random_get_entropy();
1344 	}
1345 	mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
1346 
1347 	del_timer_sync(&stack->timer);
1348 	destroy_timer_on_stack(&stack->timer);
1349 }
1350 
1351 
1352 /**********************************************************************
1353  *
1354  * Userspace reader/writer interfaces.
1355  *
1356  * getrandom(2) is the primary modern interface into the RNG and should
1357  * be used in preference to anything else.
1358  *
1359  * Reading from /dev/random has the same functionality as calling
1360  * getrandom(2) with flags=0. In earlier versions, however, it had
1361  * vastly different semantics and should therefore be avoided, to
1362  * prevent backwards compatibility issues.
1363  *
1364  * Reading from /dev/urandom has the same functionality as calling
1365  * getrandom(2) with flags=GRND_INSECURE. Because it does not block
1366  * waiting for the RNG to be ready, it should not be used.
1367  *
1368  * Writing to either /dev/random or /dev/urandom adds entropy to
1369  * the input pool but does not credit it.
1370  *
1371  * Polling on /dev/random indicates when the RNG is initialized, on
1372  * the read side, and when it wants new entropy, on the write side.
1373  *
1374  * Both /dev/random and /dev/urandom have the same set of ioctls for
1375  * adding entropy, getting the entropy count, zeroing the count, and
1376  * reseeding the crng.
1377  *
1378  **********************************************************************/
1379 
1380 SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
1381 {
1382 	struct iov_iter iter;
1383 	int ret;
1384 
1385 	if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
1386 		return -EINVAL;
1387 
1388 	/*
1389 	 * Requesting insecure and blocking randomness at the same time makes
1390 	 * no sense.
1391 	 */
1392 	if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
1393 		return -EINVAL;
1394 
1395 	if (!crng_ready() && !(flags & GRND_INSECURE)) {
1396 		if (flags & GRND_NONBLOCK)
1397 			return -EAGAIN;
1398 		ret = wait_for_random_bytes();
1399 		if (unlikely(ret))
1400 			return ret;
1401 	}
1402 
1403 	ret = import_ubuf(ITER_DEST, ubuf, len, &iter);
1404 	if (unlikely(ret))
1405 		return ret;
1406 	return get_random_bytes_user(&iter);
1407 }
1408 
1409 static __poll_t random_poll(struct file *file, poll_table *wait)
1410 {
1411 	poll_wait(file, &crng_init_wait, wait);
1412 	return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
1413 }
1414 
1415 static ssize_t write_pool_user(struct iov_iter *iter)
1416 {
1417 	u8 block[BLAKE2S_BLOCK_SIZE];
1418 	ssize_t ret = 0;
1419 	size_t copied;
1420 
1421 	if (unlikely(!iov_iter_count(iter)))
1422 		return 0;
1423 
1424 	for (;;) {
1425 		copied = copy_from_iter(block, sizeof(block), iter);
1426 		ret += copied;
1427 		mix_pool_bytes(block, copied);
1428 		if (!iov_iter_count(iter) || copied != sizeof(block))
1429 			break;
1430 
1431 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
1432 		if (ret % PAGE_SIZE == 0) {
1433 			if (signal_pending(current))
1434 				break;
1435 			cond_resched();
1436 		}
1437 	}
1438 
1439 	memzero_explicit(block, sizeof(block));
1440 	return ret ? ret : -EFAULT;
1441 }
1442 
1443 static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
1444 {
1445 	return write_pool_user(iter);
1446 }
1447 
1448 static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
1449 {
1450 	static int maxwarn = 10;
1451 
1452 	/*
1453 	 * Opportunistically attempt to initialize the RNG on platforms that
1454 	 * have fast cycle counters, but don't (for now) require it to succeed.
1455 	 */
1456 	if (!crng_ready())
1457 		try_to_generate_entropy();
1458 
1459 	if (!crng_ready()) {
1460 		if (!ratelimit_disable && maxwarn <= 0)
1461 			++urandom_warning.missed;
1462 		else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
1463 			--maxwarn;
1464 			pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
1465 				  current->comm, iov_iter_count(iter));
1466 		}
1467 	}
1468 
1469 	return get_random_bytes_user(iter);
1470 }
1471 
1472 static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
1473 {
1474 	int ret;
1475 
1476 	if (!crng_ready() &&
1477 	    ((kiocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) ||
1478 	     (kiocb->ki_filp->f_flags & O_NONBLOCK)))
1479 		return -EAGAIN;
1480 
1481 	ret = wait_for_random_bytes();
1482 	if (ret != 0)
1483 		return ret;
1484 	return get_random_bytes_user(iter);
1485 }
1486 
1487 static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1488 {
1489 	int __user *p = (int __user *)arg;
1490 	int ent_count;
1491 
1492 	switch (cmd) {
1493 	case RNDGETENTCNT:
1494 		/* Inherently racy, no point locking. */
1495 		if (put_user(input_pool.init_bits, p))
1496 			return -EFAULT;
1497 		return 0;
1498 	case RNDADDTOENTCNT:
1499 		if (!capable(CAP_SYS_ADMIN))
1500 			return -EPERM;
1501 		if (get_user(ent_count, p))
1502 			return -EFAULT;
1503 		if (ent_count < 0)
1504 			return -EINVAL;
1505 		credit_init_bits(ent_count);
1506 		return 0;
1507 	case RNDADDENTROPY: {
1508 		struct iov_iter iter;
1509 		ssize_t ret;
1510 		int len;
1511 
1512 		if (!capable(CAP_SYS_ADMIN))
1513 			return -EPERM;
1514 		if (get_user(ent_count, p++))
1515 			return -EFAULT;
1516 		if (ent_count < 0)
1517 			return -EINVAL;
1518 		if (get_user(len, p++))
1519 			return -EFAULT;
1520 		ret = import_ubuf(ITER_SOURCE, p, len, &iter);
1521 		if (unlikely(ret))
1522 			return ret;
1523 		ret = write_pool_user(&iter);
1524 		if (unlikely(ret < 0))
1525 			return ret;
1526 		/* Since we're crediting, enforce that it was all written into the pool. */
1527 		if (unlikely(ret != len))
1528 			return -EFAULT;
1529 		credit_init_bits(ent_count);
1530 		return 0;
1531 	}
1532 	case RNDZAPENTCNT:
1533 	case RNDCLEARPOOL:
1534 		/* No longer has any effect. */
1535 		if (!capable(CAP_SYS_ADMIN))
1536 			return -EPERM;
1537 		return 0;
1538 	case RNDRESEEDCRNG:
1539 		if (!capable(CAP_SYS_ADMIN))
1540 			return -EPERM;
1541 		if (!crng_ready())
1542 			return -ENODATA;
1543 		crng_reseed(NULL);
1544 		return 0;
1545 	default:
1546 		return -EINVAL;
1547 	}
1548 }
1549 
1550 static int random_fasync(int fd, struct file *filp, int on)
1551 {
1552 	return fasync_helper(fd, filp, on, &fasync);
1553 }
1554 
1555 const struct file_operations random_fops = {
1556 	.read_iter = random_read_iter,
1557 	.write_iter = random_write_iter,
1558 	.poll = random_poll,
1559 	.unlocked_ioctl = random_ioctl,
1560 	.compat_ioctl = compat_ptr_ioctl,
1561 	.fasync = random_fasync,
1562 	.llseek = noop_llseek,
1563 	.splice_read = copy_splice_read,
1564 	.splice_write = iter_file_splice_write,
1565 };
1566 
1567 const struct file_operations urandom_fops = {
1568 	.read_iter = urandom_read_iter,
1569 	.write_iter = random_write_iter,
1570 	.unlocked_ioctl = random_ioctl,
1571 	.compat_ioctl = compat_ptr_ioctl,
1572 	.fasync = random_fasync,
1573 	.llseek = noop_llseek,
1574 	.splice_read = copy_splice_read,
1575 	.splice_write = iter_file_splice_write,
1576 };
1577 
1578 
1579 /********************************************************************
1580  *
1581  * Sysctl interface.
1582  *
1583  * These are partly unused legacy knobs with dummy values to not break
1584  * userspace and partly still useful things. They are usually accessible
1585  * in /proc/sys/kernel/random/ and are as follows:
1586  *
1587  * - boot_id - a UUID representing the current boot.
1588  *
1589  * - uuid - a random UUID, different each time the file is read.
1590  *
1591  * - poolsize - the number of bits of entropy that the input pool can
1592  *   hold, tied to the POOL_BITS constant.
1593  *
1594  * - entropy_avail - the number of bits of entropy currently in the
1595  *   input pool. Always <= poolsize.
1596  *
1597  * - write_wakeup_threshold - the amount of entropy in the input pool
1598  *   below which write polls to /dev/random will unblock, requesting
1599  *   more entropy, tied to the POOL_READY_BITS constant. It is writable
1600  *   to avoid breaking old userspaces, but writing to it does not
1601  *   change any behavior of the RNG.
1602  *
1603  * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
1604  *   It is writable to avoid breaking old userspaces, but writing
1605  *   to it does not change any behavior of the RNG.
1606  *
1607  ********************************************************************/
1608 
1609 #ifdef CONFIG_SYSCTL
1610 
1611 #include <linux/sysctl.h>
1612 
1613 static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
1614 static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
1615 static int sysctl_poolsize = POOL_BITS;
1616 static u8 sysctl_bootid[UUID_SIZE];
1617 
1618 /*
1619  * This function is used to return both the bootid UUID, and random
1620  * UUID. The difference is in whether table->data is NULL; if it is,
1621  * then a new UUID is generated and returned to the user.
1622  */
1623 static int proc_do_uuid(const struct ctl_table *table, int write, void *buf,
1624 			size_t *lenp, loff_t *ppos)
1625 {
1626 	u8 tmp_uuid[UUID_SIZE], *uuid;
1627 	char uuid_string[UUID_STRING_LEN + 1];
1628 	struct ctl_table fake_table = {
1629 		.data = uuid_string,
1630 		.maxlen = UUID_STRING_LEN
1631 	};
1632 
1633 	if (write)
1634 		return -EPERM;
1635 
1636 	uuid = table->data;
1637 	if (!uuid) {
1638 		uuid = tmp_uuid;
1639 		generate_random_uuid(uuid);
1640 	} else {
1641 		static DEFINE_SPINLOCK(bootid_spinlock);
1642 
1643 		spin_lock(&bootid_spinlock);
1644 		if (!uuid[8])
1645 			generate_random_uuid(uuid);
1646 		spin_unlock(&bootid_spinlock);
1647 	}
1648 
1649 	snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
1650 	return proc_dostring(&fake_table, 0, buf, lenp, ppos);
1651 }
1652 
1653 /* The same as proc_dointvec, but writes don't change anything. */
1654 static int proc_do_rointvec(const struct ctl_table *table, int write, void *buf,
1655 			    size_t *lenp, loff_t *ppos)
1656 {
1657 	return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
1658 }
1659 
1660 static struct ctl_table random_table[] = {
1661 	{
1662 		.procname	= "poolsize",
1663 		.data		= &sysctl_poolsize,
1664 		.maxlen		= sizeof(int),
1665 		.mode		= 0444,
1666 		.proc_handler	= proc_dointvec,
1667 	},
1668 	{
1669 		.procname	= "entropy_avail",
1670 		.data		= &input_pool.init_bits,
1671 		.maxlen		= sizeof(int),
1672 		.mode		= 0444,
1673 		.proc_handler	= proc_dointvec,
1674 	},
1675 	{
1676 		.procname	= "write_wakeup_threshold",
1677 		.data		= &sysctl_random_write_wakeup_bits,
1678 		.maxlen		= sizeof(int),
1679 		.mode		= 0644,
1680 		.proc_handler	= proc_do_rointvec,
1681 	},
1682 	{
1683 		.procname	= "urandom_min_reseed_secs",
1684 		.data		= &sysctl_random_min_urandom_seed,
1685 		.maxlen		= sizeof(int),
1686 		.mode		= 0644,
1687 		.proc_handler	= proc_do_rointvec,
1688 	},
1689 	{
1690 		.procname	= "boot_id",
1691 		.data		= &sysctl_bootid,
1692 		.mode		= 0444,
1693 		.proc_handler	= proc_do_uuid,
1694 	},
1695 	{
1696 		.procname	= "uuid",
1697 		.mode		= 0444,
1698 		.proc_handler	= proc_do_uuid,
1699 	},
1700 };
1701 
1702 /*
1703  * random_init() is called before sysctl_init(),
1704  * so we cannot call register_sysctl_init() in random_init()
1705  */
1706 static int __init random_sysctls_init(void)
1707 {
1708 	register_sysctl_init("kernel/random", random_table);
1709 	return 0;
1710 }
1711 device_initcall(random_sysctls_init);
1712 #endif
1713