2 * Copyright (c) 2000-2015 Mark R V Murray
3 * Copyright (c) 2013 Arthur Mesh
4 * Copyright (c) 2004 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/systm.h>
36 #include <sys/eventhandler.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/linker.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
45 #include <sys/random.h>
47 #include <sys/sysctl.h>
48 #include <sys/unistd.h>
50 #if defined(RANDOM_LOADABLE)
55 #include <machine/atomic.h>
56 #include <machine/cpu.h>
58 #include <dev/random/randomdev.h>
59 #include <dev/random/random_harvestq.h>
61 static void random_kthread(void);
62 static void random_sources_feed(void);
64 static u_int read_rate;
66 /* List for the dynamic sysctls */
67 static struct sysctl_ctx_list random_clist;
70 * How many events to queue up. We create this many items in
71 * an 'empty' queue, then transfer them to the 'harvest' queue with
72 * supplied junk. When used, they are transferred back to the
75 #define RANDOM_RING_MAX 1024
76 #define RANDOM_ACCUM_MAX 8
78 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
79 volatile int random_kthread_control;
82 * Put all the harvest queue context stuff in one place.
83 * this make is a bit easier to lock and protect.
85 static struct harvest_context {
86 /* The harvest mutex protects all of harvest_context and
90 /* Round-robin destination cache. */
91 u_int hc_destination[ENTROPYSOURCE];
92 /* The context of the kernel thread processing harvested entropy */
93 struct proc *hc_kthread_proc;
94 /* Allow the sysadmin to select the broad category of
95 * entropy types to harvest.
99 * Lockless ring buffer holding entropy events
100 * If ring.in == ring.out,
101 * the buffer is empty.
102 * If ring.in != ring.out,
103 * the buffer contains harvested entropy.
104 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX),
105 * the buffer is full.
107 * NOTE: ring.in points to the last added element,
108 * and ring.out points to the last consumed element.
110 * The ring.in variable needs locking as there are multiple
111 * sources to the ring. Only the sources may change ring.in,
112 * but the consumer may examine it.
114 * The ring.out variable does not need locking as there is
115 * only one consumer. Only the consumer may change ring.out,
116 * but the sources may examine it.
118 struct entropy_ring {
119 struct harvest_event ring[RANDOM_RING_MAX];
123 struct fast_entropy_accumulator {
125 uint32_t buf[RANDOM_ACCUM_MAX];
126 } hc_entropy_fast_accumulator;
129 static struct kproc_desc random_proc_kp = {
132 &harvest_context.hc_kthread_proc,
135 /* Pass the given event straight through to Fortuna/Yarrow/Whatever. */
137 random_harvestq_fast_process_event(struct harvest_event *event)
139 #if defined(RANDOM_LOADABLE)
140 RANDOM_CONFIG_S_LOCK();
141 if (p_random_alg_context)
143 p_random_alg_context->ra_event_processor(event);
144 #if defined(RANDOM_LOADABLE)
145 RANDOM_CONFIG_S_UNLOCK();
152 u_int maxloop, ring_out, i;
155 * Locking is not needed as this is the only place we modify ring.out, and
156 * we only examine ring.in without changing it. Both of these are volatile,
157 * and this is a unique thread.
159 for (random_kthread_control = 1; random_kthread_control;) {
160 /* Deal with events, if any. Restrict the number we do in one go. */
161 maxloop = RANDOM_RING_MAX;
162 while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) {
163 ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX;
164 random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out);
165 harvest_context.hc_entropy_ring.out = ring_out;
169 random_sources_feed();
170 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
171 for (i = 0; i < RANDOM_ACCUM_MAX; i++) {
172 if (harvest_context.hc_entropy_fast_accumulator.buf[i]) {
173 random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), 4, RANDOM_UMA);
174 harvest_context.hc_entropy_fast_accumulator.buf[i] = 0;
177 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
178 tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1));
180 random_kthread_control = -1;
181 wakeup(&harvest_context.hc_kthread_proc);
185 /* This happens well after SI_SUB_RANDOM */
186 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
190 * Run through all fast sources reading entropy for the given
191 * number of rounds, which should be a multiple of the number
192 * of entropy accumulation pools in use; 2 for Yarrow and 32
196 random_sources_feed(void)
198 uint32_t entropy[HARVESTSIZE];
199 struct random_sources *rrs;
200 u_int i, n, local_read_rate;
203 * Step over all of live entropy sources, and feed their output
204 * to the system-wide RNG.
206 #if defined(RANDOM_LOADABLE)
207 RANDOM_CONFIG_S_LOCK();
208 if (p_random_alg_context) {
209 /* It's an indenting error. Yeah, Yeah. */
211 local_read_rate = atomic_readandclear_32(&read_rate);
212 LIST_FOREACH(rrs, &source_list, rrs_entries) {
213 for (i = 0; i < p_random_alg_context->ra_poolcount*(local_read_rate + 1); i++) {
214 n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
215 KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
216 /* It would appear that in some circumstances (e.g. virtualisation),
217 * the underlying hardware entropy source might not always return
218 * random numbers. Accept this but make a noise. If too much happens,
219 * can that source be trusted?
222 printf("%s: rs_read for hardware device '%s' returned no entropy.\n", __func__, rrs->rrs_source->rs_ident);
225 random_harvest_direct(entropy, n, (n*8)/2, rrs->rrs_source->rs_source);
228 explicit_bzero(entropy, sizeof(entropy));
229 #if defined(RANDOM_LOADABLE)
231 RANDOM_CONFIG_S_UNLOCK();
236 read_rate_increment(u_int chunk)
239 atomic_add_32(&read_rate, chunk);
243 RANDOM_CHECK_UINT(harvestmask, 0, RANDOM_HARVEST_EVERYTHING_MASK);
247 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
252 error = sysctl_wire_old_buffer(req, 0);
254 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
255 for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--)
256 sbuf_cat(&sbuf, (harvest_context.hc_source_mask & (1 << i)) ? "1" : "0");
257 error = sbuf_finish(&sbuf);
263 static const char *random_source_descr[ENTROPYSOURCE] = {
264 [RANDOM_CACHED] = "CACHED",
265 [RANDOM_ATTACH] = "ATTACH",
266 [RANDOM_KEYBOARD] = "KEYBOARD",
267 [RANDOM_MOUSE] = "MOUSE",
268 [RANDOM_NET_TUN] = "NET_TUN",
269 [RANDOM_NET_ETHER] = "NET_ETHER",
270 [RANDOM_NET_NG] = "NET_NG",
271 [RANDOM_INTERRUPT] = "INTERRUPT",
272 [RANDOM_SWI] = "SWI",
273 [RANDOM_FS_ATIME] = "FS_ATIME",
274 [RANDOM_UMA] = "UMA", /* ENVIRONMENTAL_END */
275 [RANDOM_PURE_OCTEON] = "PURE_OCTEON",
276 [RANDOM_PURE_SAFE] = "PURE_SAFE",
277 [RANDOM_PURE_GLXSB] = "PURE_GLXSB",
278 [RANDOM_PURE_UBSEC] = "PURE_UBSEC",
279 [RANDOM_PURE_HIFN] = "PURE_HIFN",
280 [RANDOM_PURE_RDRAND] = "PURE_RDRAND",
281 [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
282 [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
283 [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
284 [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
285 /* "ENTROPYSOURCE" */
290 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
295 error = sysctl_wire_old_buffer(req, 0);
297 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
298 for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--) {
299 sbuf_cat(&sbuf, (i == RANDOM_ENVIRONMENTAL_END) ? "" : ",");
300 sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "[" : "");
301 sbuf_cat(&sbuf, random_source_descr[i]);
302 sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "]" : "");
304 error = sbuf_finish(&sbuf);
312 random_harvestq_init(void *unused __unused)
314 struct sysctl_oid *random_sys_o;
316 random_sys_o = SYSCTL_ADD_NODE(&random_clist,
317 SYSCTL_STATIC_CHILDREN(_kern_random),
318 OID_AUTO, "harvest", CTLFLAG_RW, 0,
319 "Entropy Device Parameters");
320 harvest_context.hc_source_mask = RANDOM_HARVEST_EVERYTHING_MASK;
321 SYSCTL_ADD_PROC(&random_clist,
322 SYSCTL_CHILDREN(random_sys_o),
323 OID_AUTO, "mask", CTLTYPE_UINT | CTLFLAG_RW,
324 &harvest_context.hc_source_mask, 0,
325 random_check_uint_harvestmask, "IU",
326 "Entropy harvesting mask");
327 SYSCTL_ADD_PROC(&random_clist,
328 SYSCTL_CHILDREN(random_sys_o),
329 OID_AUTO, "mask_bin", CTLTYPE_STRING | CTLFLAG_RD,
330 NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)");
331 SYSCTL_ADD_PROC(&random_clist,
332 SYSCTL_CHILDREN(random_sys_o),
333 OID_AUTO, "mask_symbolic", CTLTYPE_STRING | CTLFLAG_RD,
334 NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)");
335 RANDOM_HARVEST_INIT_LOCK();
336 harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
338 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_init, NULL);
341 * This is used to prime the RNG by grabbing any early random stuff
342 * known to the kernel, and inserting it directly into the hashing
343 * module, e.g. Fortuna or Yarrow.
347 random_harvestq_prime(void *unused __unused)
349 struct harvest_event event;
350 size_t count, size, i;
351 uint8_t *keyfile, *data;
354 * Get entropy that may have been preloaded by loader(8)
355 * and use it to pre-charge the entropy harvest queue.
357 keyfile = preload_search_by_type(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
358 #ifndef NO_BACKWARD_COMPATIBILITY
360 keyfile = preload_search_by_type(RANDOM_LEGACY_BOOT_ENTROPY_MODULE);
362 if (keyfile != NULL) {
363 data = preload_fetch_addr(keyfile);
364 size = preload_fetch_size(keyfile);
365 /* skip the first bit of the stash so others like arc4 can also have some. */
366 if (size > RANDOM_CACHED_SKIP_START) {
367 data += RANDOM_CACHED_SKIP_START;
368 size -= RANDOM_CACHED_SKIP_START;
370 /* Trim the size. If the admin has a file with a funny size, we lose some. Tough. */
371 size -= (size % sizeof(event.he_entropy));
372 if (data != NULL && size != 0) {
373 for (i = 0; i < size; i += sizeof(event.he_entropy)) {
374 count = sizeof(event.he_entropy);
375 event.he_somecounter = (uint32_t)get_cyclecount();
376 event.he_size = count;
377 event.he_bits = count/4; /* Underestimate the size for Yarrow */
378 event.he_source = RANDOM_CACHED;
379 event.he_destination = harvest_context.hc_destination[0]++;
380 memcpy(event.he_entropy, data + i, sizeof(event.he_entropy));
381 random_harvestq_fast_process_event(&event);
382 explicit_bzero(&event, sizeof(event));
384 explicit_bzero(data, size);
386 printf("random: read %zu bytes from preloaded cache\n", size);
389 printf("random: no preloaded entropy cache\n");
392 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_FOURTH, random_harvestq_prime, NULL);
396 random_harvestq_deinit(void *unused __unused)
399 /* Command the hash/reseed thread to end and wait for it to finish */
400 random_kthread_control = 0;
401 while (random_kthread_control >= 0)
402 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
403 sysctl_ctx_free(&random_clist);
405 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_deinit, NULL);
408 * Entropy harvesting queue routine.
410 * This is supposed to be fast; do not do anything slow in here!
411 * It is also illegal (and morally reprehensible) to insert any
412 * high-rate data here. "High-rate" is defined as a data source
413 * that will usually cause lots of failures of the "Lockless read"
414 * check a few lines below. This includes the "always-on" sources
415 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
417 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
418 * counters are built in, but on older hardware it will do a real time clock
419 * read which can be quite expensive.
422 random_harvest_queue(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
424 struct harvest_event *event;
427 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
428 if (!(harvest_context.hc_source_mask & (1 << origin)))
430 RANDOM_HARVEST_LOCK();
431 ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
432 if (ring_in != harvest_context.hc_entropy_ring.out) {
433 /* The ring is not full */
434 event = harvest_context.hc_entropy_ring.ring + ring_in;
435 event->he_somecounter = (uint32_t)get_cyclecount();
436 event->he_source = origin;
437 event->he_destination = harvest_context.hc_destination[origin]++;
438 event->he_bits = bits;
439 if (size <= sizeof(event->he_entropy)) {
440 event->he_size = size;
441 memcpy(event->he_entropy, entropy, size);
444 /* Big event, so squash it */
445 event->he_size = sizeof(event->he_entropy[0]);
446 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
448 harvest_context.hc_entropy_ring.in = ring_in;
450 RANDOM_HARVEST_UNLOCK();
454 * Entropy harvesting fast routine.
456 * This is supposed to be very fast; do not do anything slow in here!
457 * This is the right place for high-rate harvested data.
460 random_harvest_fast(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
464 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
465 /* XXX: FIX!! The above KASSERT is BS. Right now we ignore most structure and just accumulate the supplied data */
466 if (!(harvest_context.hc_source_mask & (1 << origin)))
468 pos = harvest_context.hc_entropy_fast_accumulator.pos;
469 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
470 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
474 * Entropy harvesting direct routine.
476 * This is not supposed to be fast, but will only be used during
477 * (e.g.) booting when initial entropy is being gathered.
480 random_harvest_direct(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
482 struct harvest_event event;
484 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
485 if (!(harvest_context.hc_source_mask & (1 << origin)))
487 size = MIN(size, sizeof(event.he_entropy));
488 event.he_somecounter = (uint32_t)get_cyclecount();
489 event.he_size = size;
490 event.he_bits = bits;
491 event.he_source = origin;
492 event.he_destination = harvest_context.hc_destination[origin]++;
493 memcpy(event.he_entropy, entropy, size);
494 random_harvestq_fast_process_event(&event);
495 explicit_bzero(&event, sizeof(event));
498 MODULE_VERSION(random_harvestq, 1);