1 /*-
2  * Copyright (c) 2017 Oliver Pinter
3  * Copyright (c) 2017 W. Dean Freeman
4  * Copyright (c) 2000-2015 Mark R V Murray
5  * Copyright (c) 2013 Arthur Mesh
6  * Copyright (c) 2004 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer
14  *    in this position and unchanged.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD: stable/12/sys/dev/random/random_harvestq.c 371678 2022-02-22 07:30:53Z obrien $");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/ck.h>
38 #include <sys/conf.h>
39 #include <sys/epoch.h>
40 #include <sys/eventhandler.h>
41 #include <sys/hash.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/linker.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/module.h>
48 #include <sys/mutex.h>
49 #include <sys/random.h>
50 #include <sys/sbuf.h>
51 #include <sys/sysctl.h>
52 #include <sys/unistd.h>
53 
54 #include <machine/atomic.h>
55 #include <machine/cpu.h>
56 
57 #include <crypto/rijndael/rijndael-api-fst.h>
58 #include <crypto/sha2/sha256.h>
59 
60 #include <dev/random/hash.h>
61 #include <dev/random/randomdev.h>
62 #include <dev/random/random_harvestq.h>
63 
64 /*
65  * Note that random_sources_feed() will also use this to try and split up
66  * entropy into a subset of pools per iteration with the goal of feeding
67  * HARVESTSIZE into every pool at least once per second.
68  */
69 #define	RANDOM_KTHREAD_HZ	10
70 
71 static void random_kthread(void);
72 static void random_sources_feed(void);
73 
74 static u_int read_rate;
75 
76 /*
77  * Random must initialize much earlier than epoch, but we can initialize the
78  * epoch code before SMP starts.  Prior to SMP, we can safely bypass
79  * concurrency primitives.
80  */
81 static __read_mostly bool epoch_inited;
82 static __read_mostly epoch_t rs_epoch;
83 
84 /*
85  * How many events to queue up. We create this many items in
86  * an 'empty' queue, then transfer them to the 'harvest' queue with
87  * supplied junk. When used, they are transferred back to the
88  * 'empty' queue.
89  */
90 #define	RANDOM_RING_MAX		1024
91 #define	RANDOM_ACCUM_MAX	8
92 
93 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
94 volatile int random_kthread_control;
95 
96 
97 /* Allow the sysadmin to select the broad category of
98  * entropy types to harvest.
99  */
100 __read_frequently u_int hc_source_mask;
101 
102 struct random_sources {
103 	CK_LIST_ENTRY(random_sources)	 rrs_entries;
104 	struct random_source		*rrs_source;
105 };
106 
107 static CK_LIST_HEAD(sources_head, random_sources) source_list =
108     CK_LIST_HEAD_INITIALIZER(source_list);
109 
110 SYSCTL_NODE(_kern_random, OID_AUTO, harvest, CTLFLAG_RW, 0,
111     "Entropy Device Parameters");
112 
113 /*
114  * Put all the harvest queue context stuff in one place.
115  * this make is a bit easier to lock and protect.
116  */
117 static struct harvest_context {
118 	/* The harvest mutex protects all of harvest_context and
119 	 * the related data.
120 	 */
121 	struct mtx hc_mtx;
122 	/* Round-robin destination cache. */
123 	u_int hc_destination[ENTROPYSOURCE];
124 	/* The context of the kernel thread processing harvested entropy */
125 	struct proc *hc_kthread_proc;
126 	/*
127 	 * Lockless ring buffer holding entropy events
128 	 * If ring.in == ring.out,
129 	 *     the buffer is empty.
130 	 * If ring.in != ring.out,
131 	 *     the buffer contains harvested entropy.
132 	 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX),
133 	 *     the buffer is full.
134 	 *
135 	 * NOTE: ring.in points to the last added element,
136 	 * and ring.out points to the last consumed element.
137 	 *
138 	 * The ring.in variable needs locking as there are multiple
139 	 * sources to the ring. Only the sources may change ring.in,
140 	 * but the consumer may examine it.
141 	 *
142 	 * The ring.out variable does not need locking as there is
143 	 * only one consumer. Only the consumer may change ring.out,
144 	 * but the sources may examine it.
145 	 */
146 	struct entropy_ring {
147 		struct harvest_event ring[RANDOM_RING_MAX];
148 		volatile u_int in;
149 		volatile u_int out;
150 	} hc_entropy_ring;
151 	struct fast_entropy_accumulator {
152 		volatile u_int pos;
153 		uint32_t buf[RANDOM_ACCUM_MAX];
154 	} hc_entropy_fast_accumulator;
155 } harvest_context;
156 
157 static struct kproc_desc random_proc_kp = {
158 	"rand_harvestq",
159 	random_kthread,
160 	&harvest_context.hc_kthread_proc,
161 };
162 
163 /* Pass the given event straight through to Fortuna/Whatever. */
164 static __inline void
random_harvestq_fast_process_event(struct harvest_event * event)165 random_harvestq_fast_process_event(struct harvest_event *event)
166 {
167 	p_random_alg_context->ra_event_processor(event);
168 	explicit_bzero(event, sizeof(*event));
169 }
170 
171 static void
random_kthread(void)172 random_kthread(void)
173 {
174         u_int maxloop, ring_out, i;
175 
176 	/*
177 	 * Locking is not needed as this is the only place we modify ring.out, and
178 	 * we only examine ring.in without changing it. Both of these are volatile,
179 	 * and this is a unique thread.
180 	 */
181 	for (random_kthread_control = 1; random_kthread_control;) {
182 		/* Deal with events, if any. Restrict the number we do in one go. */
183 		maxloop = RANDOM_RING_MAX;
184 		while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) {
185 			ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX;
186 			random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out);
187 			harvest_context.hc_entropy_ring.out = ring_out;
188 			if (!--maxloop)
189 				break;
190 		}
191 		random_sources_feed();
192 		/* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
193 		for (i = 0; i < RANDOM_ACCUM_MAX; i++) {
194 			if (harvest_context.hc_entropy_fast_accumulator.buf[i]) {
195 				random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA);
196 				harvest_context.hc_entropy_fast_accumulator.buf[i] = 0;
197 			}
198 		}
199 		/* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
200 		tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-",
201 		    SBT_1S/RANDOM_KTHREAD_HZ, 0, C_PREL(1));
202 	}
203 	random_kthread_control = -1;
204 	wakeup(&harvest_context.hc_kthread_proc);
205 	kproc_exit(0);
206 	/* NOTREACHED */
207 }
208 /* This happens well after SI_SUB_RANDOM */
209 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
210     &random_proc_kp);
211 
212 static void
rs_epoch_init(void * dummy __unused)213 rs_epoch_init(void *dummy __unused)
214 {
215 	rs_epoch = epoch_alloc(EPOCH_PREEMPT);
216 	epoch_inited = true;
217 }
218 SYSINIT(rs_epoch_init, SI_SUB_EPOCH, SI_ORDER_ANY, rs_epoch_init, NULL);
219 
220 /*
221  * Run through all fast sources reading entropy for the given
222  * number of rounds, which should be a multiple of the number
223  * of entropy accumulation pools in use; it is 32 for Fortuna.
224  */
225 static void
random_sources_feed(void)226 random_sources_feed(void)
227 {
228 	uint32_t entropy[HARVESTSIZE];
229 	struct epoch_tracker et;
230 	struct random_sources *rrs;
231 	u_int i, n, local_read_rate, npools;
232 	bool rse_warm;
233 
234 	rse_warm = epoch_inited;
235 
236 	/*
237 	 * Step over all of live entropy sources, and feed their output
238 	 * to the system-wide RNG.
239 	 */
240 	local_read_rate = atomic_readandclear_32(&read_rate);
241 	/* Perform at least one read per round */
242 	local_read_rate = MAX(local_read_rate, 1);
243 	/* But not exceeding RANDOM_KEYSIZE_WORDS */
244 	local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS);
245 
246 	/*
247 	 * Evenly-ish distribute pool population across the second based on how
248 	 * frequently random_kthread iterates.
249 	 *
250 	 * For Fortuna, the math currently works out as such:
251 	 * 64 bits * 4 pools = 256 bits per iteration
252 	 * 256 bits * 10 Hz = 2560 bits per second, 320 B/s
253 	 *
254 	 */
255 	npools = howmany(p_random_alg_context->ra_poolcount * local_read_rate,
256 	    RANDOM_KTHREAD_HZ);
257 
258 	if (rse_warm)
259 		epoch_enter_preempt(rs_epoch, &et);
260 	CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
261 		for (i = 0; i < npools; i++) {
262 			n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
263 			KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
264 			/*
265 			 * Sometimes the HW entropy source doesn't have anything
266 			 * ready for us.  This isn't necessarily untrustworthy.
267 			 * We don't perform any other verification of an entropy
268 			 * source (i.e., length is allowed to be anywhere from 1
269 			 * to sizeof(entropy), quality is unchecked, etc), so
270 			 * don't balk verbosely at slow random sources either.
271 			 * There are reports that RDSEED on x86 metal falls
272 			 * behind the rate at which we query it, for example.
273 			 * But it's still a better entropy source than RDRAND.
274 			 */
275 			if (n == 0)
276 				continue;
277 			random_harvest_direct(entropy, n, rrs->rrs_source->rs_source);
278 		}
279 	}
280 	if (rse_warm)
281 		epoch_exit_preempt(rs_epoch, &et);
282 	explicit_bzero(entropy, sizeof(entropy));
283 }
284 
285 void
read_rate_increment(u_int chunk)286 read_rate_increment(u_int chunk)
287 {
288 
289 	atomic_add_32(&read_rate, chunk);
290 }
291 
292 /* ARGSUSED */
293 static int
random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)294 random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)
295 {
296 	int error;
297 	u_int value, orig_value;
298 
299 	orig_value = value = hc_source_mask;
300 	error = sysctl_handle_int(oidp, &value, 0, req);
301 	if (error != 0 || req->newptr == NULL)
302 		return (error);
303 
304 	if (flsl(value) > ENTROPYSOURCE)
305 		return (EINVAL);
306 
307 	/*
308 	 * Disallow userspace modification of pure entropy sources.
309 	 */
310 	hc_source_mask = (value & ~RANDOM_HARVEST_PURE_MASK) |
311 	    (orig_value & RANDOM_HARVEST_PURE_MASK);
312 	return (0);
313 }
314 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask, CTLTYPE_UINT | CTLFLAG_RW,
315     NULL, 0, random_check_uint_harvestmask, "IU", "Entropy harvesting mask");
316 
317 /* ARGSUSED */
318 static int
random_print_harvestmask(SYSCTL_HANDLER_ARGS)319 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
320 {
321 	struct sbuf sbuf;
322 	int error, i;
323 
324 	error = sysctl_wire_old_buffer(req, 0);
325 	if (error == 0) {
326 		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
327 		for (i = ENTROPYSOURCE - 1; i >= 0; i--)
328 			sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0");
329 		error = sbuf_finish(&sbuf);
330 		sbuf_delete(&sbuf);
331 	}
332 	return (error);
333 }
334 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin,
335     CTLTYPE_STRING | CTLFLAG_RD, NULL, 0, random_print_harvestmask, "A",
336     "Entropy harvesting mask (printable)");
337 
338 static const char *random_source_descr[ENTROPYSOURCE] = {
339 	[RANDOM_CACHED] = "CACHED",
340 	[RANDOM_ATTACH] = "ATTACH",
341 	[RANDOM_KEYBOARD] = "KEYBOARD",
342 	[RANDOM_MOUSE] = "MOUSE",
343 	[RANDOM_NET_TUN] = "NET_TUN",
344 	[RANDOM_NET_ETHER] = "NET_ETHER",
345 	[RANDOM_NET_NG] = "NET_NG",
346 	[RANDOM_INTERRUPT] = "INTERRUPT",
347 	[RANDOM_SWI] = "SWI",
348 	[RANDOM_FS_ATIME] = "FS_ATIME",
349 	[RANDOM_UMA] = "UMA", /* ENVIRONMENTAL_END */
350 	[RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */
351 	[RANDOM_PURE_SAFE] = "PURE_SAFE",
352 	[RANDOM_PURE_GLXSB] = "PURE_GLXSB",
353 	[RANDOM_PURE_UBSEC] = "PURE_UBSEC",
354 	[RANDOM_PURE_HIFN] = "PURE_HIFN",
355 	[RANDOM_PURE_RDRAND] = "PURE_RDRAND",
356 	[RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
357 	[RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
358 	[RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
359 	[RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
360 	[RANDOM_PURE_CCP] = "PURE_CCP",
361 	[RANDOM_PURE_DARN] = "PURE_DARN",
362 	[RANDOM_PURE_TPM] = "PURE_TPM",
363 	/* "ENTROPYSOURCE" */
364 };
365 
366 /* ARGSUSED */
367 static int
random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)368 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
369 {
370 	struct sbuf sbuf;
371 	int error, i;
372 	bool first;
373 
374 	first = true;
375 	error = sysctl_wire_old_buffer(req, 0);
376 	if (error == 0) {
377 		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
378 		for (i = ENTROPYSOURCE - 1; i >= 0; i--) {
379 			if (i >= RANDOM_PURE_START &&
380 			    (hc_source_mask & (1 << i)) == 0)
381 				continue;
382 			if (!first)
383 				sbuf_cat(&sbuf, ",");
384 			sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : "");
385 			sbuf_cat(&sbuf, random_source_descr[i]);
386 			sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : "");
387 			first = false;
388 		}
389 		error = sbuf_finish(&sbuf);
390 		sbuf_delete(&sbuf);
391 	}
392 	return (error);
393 }
394 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic,
395     CTLTYPE_STRING | CTLFLAG_RD, NULL, 0, random_print_harvestmask_symbolic,
396     "A", "Entropy harvesting mask (symbolic)");
397 
398 /* ARGSUSED */
399 static void
random_harvestq_init(void * unused __unused)400 random_harvestq_init(void *unused __unused)
401 {
402 	hc_source_mask = RANDOM_HARVEST_EVERYTHING_MASK;
403 	RANDOM_HARVEST_INIT_LOCK();
404 	harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
405 }
406 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_init, NULL);
407 
408 /*
409  * Subroutine to slice up a contiguous chunk of 'entropy' and feed it into the
410  * underlying algorithm.  Returns number of bytes actually fed into underlying
411  * algorithm.
412  */
413 static size_t
random_early_prime(char * entropy,size_t len)414 random_early_prime(char *entropy, size_t len)
415 {
416 	struct harvest_event event;
417 	size_t i;
418 
419 	len = rounddown(len, sizeof(event.he_entropy));
420 	if (len == 0)
421 		return (0);
422 
423 	for (i = 0; i < len; i += sizeof(event.he_entropy)) {
424 		event.he_somecounter = (uint32_t)get_cyclecount();
425 		event.he_size = sizeof(event.he_entropy);
426 		event.he_source = RANDOM_CACHED;
427 		event.he_destination =
428 		    harvest_context.hc_destination[RANDOM_CACHED]++;
429 		memcpy(event.he_entropy, entropy + i, sizeof(event.he_entropy));
430 		random_harvestq_fast_process_event(&event);
431 	}
432 	explicit_bzero(entropy, len);
433 	return (len);
434 }
435 
436 /*
437  * Subroutine to search for known loader-loaded files in memory and feed them
438  * into the underlying algorithm early in boot.  Returns the number of bytes
439  * loaded (zero if none were loaded).
440  */
441 static size_t
random_prime_loader_file(const char * type)442 random_prime_loader_file(const char *type)
443 {
444 	uint8_t *keyfile, *data;
445 	size_t size;
446 
447 	keyfile = preload_search_by_type(type);
448 	if (keyfile == NULL)
449 		return (0);
450 
451 	data = preload_fetch_addr(keyfile);
452 	size = preload_fetch_size(keyfile);
453 	if (data == NULL)
454 		return (0);
455 
456 	return (random_early_prime(data, size));
457 }
458 
459 /*
460  * This is used to prime the RNG by grabbing any early random stuff
461  * known to the kernel, and inserting it directly into the hashing
462  * module, currently Fortuna.
463  */
464 /* ARGSUSED */
465 static void
random_harvestq_prime(void * unused __unused)466 random_harvestq_prime(void *unused __unused)
467 {
468 	size_t size;
469 
470 	/*
471 	 * Get entropy that may have been preloaded by loader(8)
472 	 * and use it to pre-charge the entropy harvest queue.
473 	 */
474 	size = random_prime_loader_file(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
475 	if (bootverbose) {
476 		if (size > 0)
477 			printf("random: read %zu bytes from preloaded cache\n",
478 			    size);
479 		else
480 			printf("random: no preloaded entropy cache\n");
481 	}
482 }
483 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL);
484 
485 /* ARGSUSED */
486 static void
random_harvestq_deinit(void * unused __unused)487 random_harvestq_deinit(void *unused __unused)
488 {
489 
490 	/* Command the hash/reseed thread to end and wait for it to finish */
491 	random_kthread_control = 0;
492 	while (random_kthread_control >= 0)
493 		tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
494 }
495 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_deinit, NULL);
496 
497 /*-
498  * Entropy harvesting queue routine.
499  *
500  * This is supposed to be fast; do not do anything slow in here!
501  * It is also illegal (and morally reprehensible) to insert any
502  * high-rate data here. "High-rate" is defined as a data source
503  * that will usually cause lots of failures of the "Lockless read"
504  * check a few lines below. This includes the "always-on" sources
505  * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
506  */
507 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
508  * counters are built in, but on older hardware it will do a real time clock
509  * read which can be quite expensive.
510  */
511 void
random_harvest_queue_(const void * entropy,u_int size,enum random_entropy_source origin)512 random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin)
513 {
514 	struct harvest_event *event;
515 	u_int ring_in;
516 
517 	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
518 	RANDOM_HARVEST_LOCK();
519 	ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
520 	if (ring_in != harvest_context.hc_entropy_ring.out) {
521 		/* The ring is not full */
522 		event = harvest_context.hc_entropy_ring.ring + ring_in;
523 		event->he_somecounter = (uint32_t)get_cyclecount();
524 		event->he_source = origin;
525 		event->he_destination = harvest_context.hc_destination[origin]++;
526 		if (size <= sizeof(event->he_entropy)) {
527 			event->he_size = size;
528 			memcpy(event->he_entropy, entropy, size);
529 		}
530 		else {
531 			/* Big event, so squash it */
532 			event->he_size = sizeof(event->he_entropy[0]);
533 			event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
534 		}
535 		harvest_context.hc_entropy_ring.in = ring_in;
536 	}
537 	RANDOM_HARVEST_UNLOCK();
538 }
539 
540 /*-
541  * Entropy harvesting fast routine.
542  *
543  * This is supposed to be very fast; do not do anything slow in here!
544  * This is the right place for high-rate harvested data.
545  */
546 void
random_harvest_fast_(const void * entropy,u_int size)547 random_harvest_fast_(const void *entropy, u_int size)
548 {
549 	u_int pos;
550 
551 	pos = harvest_context.hc_entropy_fast_accumulator.pos;
552 	harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
553 	harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
554 }
555 
556 /*-
557  * Entropy harvesting direct routine.
558  *
559  * This is not supposed to be fast, but will only be used during
560  * (e.g.) booting when initial entropy is being gathered.
561  */
562 void
random_harvest_direct_(const void * entropy,u_int size,enum random_entropy_source origin)563 random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin)
564 {
565 	struct harvest_event event;
566 
567 	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
568 	size = MIN(size, sizeof(event.he_entropy));
569 	event.he_somecounter = (uint32_t)get_cyclecount();
570 	event.he_size = size;
571 	event.he_source = origin;
572 	event.he_destination = harvest_context.hc_destination[origin]++;
573 	memcpy(event.he_entropy, entropy, size);
574 	random_harvestq_fast_process_event(&event);
575 }
576 
577 void
random_harvest_register_source(enum random_entropy_source source)578 random_harvest_register_source(enum random_entropy_source source)
579 {
580 
581 	hc_source_mask |= (1 << source);
582 }
583 
584 void
random_harvest_deregister_source(enum random_entropy_source source)585 random_harvest_deregister_source(enum random_entropy_source source)
586 {
587 
588 	hc_source_mask &= ~(1 << source);
589 }
590 
591 void
random_source_register(struct random_source * rsource)592 random_source_register(struct random_source *rsource)
593 {
594 	struct random_sources *rrs;
595 
596 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
597 
598 	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
599 	rrs->rrs_source = rsource;
600 
601 	random_harvest_register_source(rsource->rs_source);
602 
603 	printf("random: registering fast source %s\n", rsource->rs_ident);
604 
605 	RANDOM_HARVEST_LOCK();
606 	CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
607 	RANDOM_HARVEST_UNLOCK();
608 }
609 
610 void
random_source_deregister(struct random_source * rsource)611 random_source_deregister(struct random_source *rsource)
612 {
613 	struct random_sources *rrs = NULL;
614 
615 	KASSERT(rsource != NULL, ("invalid input to %s", __func__));
616 
617 	random_harvest_deregister_source(rsource->rs_source);
618 
619 	RANDOM_HARVEST_LOCK();
620 	CK_LIST_FOREACH(rrs, &source_list, rrs_entries)
621 		if (rrs->rrs_source == rsource) {
622 			CK_LIST_REMOVE(rrs, rrs_entries);
623 			break;
624 		}
625 	RANDOM_HARVEST_UNLOCK();
626 
627 	if (rrs != NULL && epoch_inited)
628 		epoch_wait_preempt(rs_epoch);
629 	free(rrs, M_ENTROPY);
630 }
631 
632 static int
random_source_handler(SYSCTL_HANDLER_ARGS)633 random_source_handler(SYSCTL_HANDLER_ARGS)
634 {
635 	struct epoch_tracker et;
636 	struct random_sources *rrs;
637 	struct sbuf sbuf;
638 	int error, count;
639 
640 	error = sysctl_wire_old_buffer(req, 0);
641 	if (error != 0)
642 		return (error);
643 
644 	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
645 	count = 0;
646 	epoch_enter_preempt(rs_epoch, &et);
647 	CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
648 		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
649 		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
650 		sbuf_cat(&sbuf, "'");
651 	}
652 	epoch_exit_preempt(rs_epoch, &et);
653 	error = sbuf_finish(&sbuf);
654 	sbuf_delete(&sbuf);
655 	return (error);
656 }
657 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
658 	    NULL, 0, random_source_handler, "A",
659 	    "List of active fast entropy sources.");
660 
661 MODULE_VERSION(random_harvestq, 1);
662