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