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