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