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