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