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