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 #include <machine/cpu.h>
52 #include <dev/random/randomdev.h>
53 #include <dev/random/random_harvestq.h>
55 static void random_kthread(void);
57 /* List for the dynamic sysctls */
58 static struct sysctl_ctx_list random_clist;
61 * How many events to queue up. We create this many items in
62 * an 'empty' queue, then transfer them to the 'harvest' queue with
63 * supplied junk. When used, they are transferred back to the
66 #define RANDOM_RING_MAX 1024
67 #define RANDOM_ACCUM_MAX 8
69 /* 1 to let the kernel thread run, 0 to terminate */
70 volatile int random_kthread_control;
73 * Put all the harvest queue context stuff in one place.
74 * this make is a bit easier to lock and protect.
76 static struct harvest_context {
77 /* The harvest mutex protects all of harvest_context and
81 /* Round-robin destination cache. */
82 u_int hc_destination[ENTROPYSOURCE];
83 /* The context of the kernel thread processing harvested entropy */
84 struct proc *hc_kthread_proc;
85 /* Allow the sysadmin to select the broad category of
86 * entropy types to harvest.
90 * Lockless ring buffer holding entropy events
91 * If ring.in == ring.out,
92 * the buffer is empty.
93 * If ring.in != ring.out,
94 * the buffer contains harvested entropy.
95 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX),
98 * NOTE: ring.in points to the last added element,
99 * and ring.out points to the last consumed element.
101 * The ring.in variable needs locking as there are multiple
102 * sources to the ring. Only the sources may change ring.in,
103 * but the consumer may examine it.
105 * The ring.out variable does not need locking as there is
106 * only one consumer. Only the consumer may change ring.out,
107 * but the sources may examine it.
109 struct entropy_ring {
110 struct harvest_event ring[RANDOM_RING_MAX];
114 struct fast_entropy_accumulator {
116 uint32_t buf[RANDOM_ACCUM_MAX];
117 } hc_entropy_fast_accumulator;
120 static struct kproc_desc random_proc_kp = {
123 &harvest_context.hc_kthread_proc,
127 /* Pass the given event straight through to Fortuna/Yarrow/Whatever. */
129 random_harvestq_fast_process_event(struct harvest_event *event)
131 if (random_alg_context.ra_event_processor)
132 random_alg_context.ra_event_processor(event);
138 u_int maxloop, ring_out, i;
141 * Locking is not needed as this is the only place we modify ring.out, and
142 * we only examine ring.in without changing it. Both of these are volatile,
143 * and this is a unique thread.
145 for (random_kthread_control = 1; random_kthread_control;) {
146 /* Deal with events, if any. Restrict the number we do in one go. */
147 maxloop = RANDOM_RING_MAX;
148 while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) {
149 ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX;
150 random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out);
151 harvest_context.hc_entropy_ring.out = ring_out;
155 random_sources_feed();
156 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
157 for (i = 0; i < RANDOM_ACCUM_MAX; i++) {
158 if (harvest_context.hc_entropy_fast_accumulator.buf[i]) {
159 random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), 4, RANDOM_FAST);
160 harvest_context.hc_entropy_fast_accumulator.buf[i] = 0;
163 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
164 tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1));
166 wakeup(&harvest_context.hc_kthread_proc);
170 SYSINIT(random_device_h_proc, SI_SUB_CREATE_INIT, SI_ORDER_ANY, kproc_start, &random_proc_kp);
173 RANDOM_CHECK_UINT(harvestmask, 0, RANDOM_HARVEST_EVERYTHING_MASK);
177 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
182 error = sysctl_wire_old_buffer(req, 0);
184 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
185 for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--)
186 sbuf_cat(&sbuf, (harvest_context.hc_source_mask & (1 << i)) ? "1" : "0");
187 error = sbuf_finish(&sbuf);
193 static const char *(random_source_descr[]) = {
204 "HIGH_PERFORMANCE", /* ENVIRONMENTAL_END */
213 /* "ENTROPYSOURCE" */
218 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
223 error = sysctl_wire_old_buffer(req, 0);
225 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
226 for (i = RANDOM_ENVIRONMENTAL_END; i >= 0; i--) {
227 sbuf_cat(&sbuf, (i == RANDOM_ENVIRONMENTAL_END) ? "" : ",");
228 sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "[" : "");
229 sbuf_cat(&sbuf, random_source_descr[i]);
230 sbuf_cat(&sbuf, !(harvest_context.hc_source_mask & (1 << i)) ? "]" : "");
232 error = sbuf_finish(&sbuf);
240 random_harvestq_init(void *unused __unused)
242 struct sysctl_oid *random_sys_o;
244 random_sys_o = SYSCTL_ADD_NODE(&random_clist,
245 SYSCTL_STATIC_CHILDREN(_kern_random),
246 OID_AUTO, "harvest", CTLFLAG_RW, 0,
247 "Entropy Device Parameters");
248 harvest_context.hc_source_mask = RANDOM_HARVEST_EVERYTHING_MASK;
249 SYSCTL_ADD_PROC(&random_clist,
250 SYSCTL_CHILDREN(random_sys_o),
251 OID_AUTO, "mask", CTLTYPE_UINT | CTLFLAG_RW,
252 &harvest_context.hc_source_mask, 0,
253 random_check_uint_harvestmask, "IU",
254 "Entropy harvesting mask");
255 SYSCTL_ADD_PROC(&random_clist,
256 SYSCTL_CHILDREN(random_sys_o),
257 OID_AUTO, "mask_bin", CTLTYPE_STRING | CTLFLAG_RD,
258 NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)");
259 SYSCTL_ADD_PROC(&random_clist,
260 SYSCTL_CHILDREN(random_sys_o),
261 OID_AUTO, "mask_symbolic", CTLTYPE_STRING | CTLFLAG_RD,
262 NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)");
263 RANDOM_HARVEST_INIT_LOCK();
264 harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
266 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_init, NULL);
269 * This is used to prime the RNG by grabbing any early random stuff
270 * known to the kernel, and inserting it directly into the hashing
271 * module, e.g. Fortuna or Yarrow.
275 random_harvestq_prime(void *unused __unused)
277 struct harvest_event event;
278 size_t count, size, i;
279 uint8_t *keyfile, *data;
282 * Get entropy that may have been preloaded by loader(8)
283 * and use it to pre-charge the entropy harvest queue.
285 keyfile = preload_search_by_type(RANDOM_HARVESTQ_BOOT_ENTROPY_FILE);
286 if (keyfile != NULL) {
287 data = preload_fetch_addr(keyfile);
288 size = preload_fetch_size(keyfile);
289 /* Trim the size. If the admin has a file with a funny size, we lose some. Tough. */
290 size -= (size % sizeof(event.he_entropy));
291 if (data != NULL && size != 0) {
292 for (i = 0; i < size; i += sizeof(event.he_entropy)) {
293 count = sizeof(event.he_entropy);
294 event.he_somecounter = (uint32_t)get_cyclecount();
295 event.he_size = count;
296 event.he_bits = count/4; /* Underestimate the size for Yarrow */
297 event.he_source = RANDOM_CACHED;
298 event.he_destination = harvest_context.hc_destination[0]++;
299 memcpy(event.he_entropy, data + i, sizeof(event.he_entropy));
300 random_harvestq_fast_process_event(&event);
301 explicit_bzero(&event, sizeof(event));
303 explicit_bzero(data, size);
305 printf("random: read %zu bytes from preloaded cache\n", size);
308 printf("random: no preloaded entropy cache\n");
311 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_FOURTH, random_harvestq_prime, NULL);
315 random_harvestq_deinit(void *unused __unused)
318 /* Command the hash/reseed thread to end and wait for it to finish */
319 random_kthread_control = 0;
320 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", 0);
321 sysctl_ctx_free(&random_clist);
323 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_deinit, NULL);
326 * Entropy harvesting queue routine.
328 * This is supposed to be fast; do not do anything slow in here!
329 * It is also illegal (and morally reprehensible) to insert any
330 * high-rate data here. "High-rate" is defined as a data source
331 * that will usually cause lots of failures of the "Lockless read"
332 * check a few lines below. This includes the "always-on" sources
333 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
335 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
336 * counters are built in, but on older hardware it will do a real time clock
337 * read which can be quite expensive.
340 random_harvest_queue(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
342 struct harvest_event *event;
345 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
346 if (!(harvest_context.hc_source_mask & (1 << origin)))
348 RANDOM_HARVEST_LOCK();
349 ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
350 if (ring_in != harvest_context.hc_entropy_ring.out) {
351 /* The ring is not full */
352 event = harvest_context.hc_entropy_ring.ring + ring_in;
353 event->he_somecounter = (uint32_t)get_cyclecount();
354 event->he_source = origin;
355 event->he_destination = harvest_context.hc_destination[origin]++;
356 event->he_bits = bits;
357 if (size <= sizeof(event->he_entropy)) {
358 event->he_size = size;
359 memcpy(event->he_entropy, entropy, size);
362 /* Big event, so squash it */
363 event->he_size = sizeof(event->he_entropy[0]);
364 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
366 harvest_context.hc_entropy_ring.in = ring_in;
368 RANDOM_HARVEST_UNLOCK();
372 * Entropy harvesting fast routine.
374 * This is supposed to be very fast; do not do anything slow in here!
375 * This is the right place for high-rate harvested data.
378 random_harvest_fast(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
382 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
383 /* XXX: FIX!! The above KASSERT is BS. Right now we ignore most structure and just accumulate the supplied data */
384 if (!(harvest_context.hc_source_mask & (1 << origin)))
386 pos = harvest_context.hc_entropy_fast_accumulator.pos;
387 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
388 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
392 * Entropy harvesting direct routine.
394 * This is not supposed to be fast, but will only be used during
395 * (e.g.) booting when initial entropy is being gathered.
398 random_harvest_direct(const void *entropy, u_int size, u_int bits, enum random_entropy_source origin)
400 struct harvest_event event;
402 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
403 if (!(harvest_context.hc_source_mask & (1 << origin)))
405 size = MIN(size, sizeof(event.he_entropy));
406 event.he_somecounter = (uint32_t)get_cyclecount();
407 event.he_size = size;
408 event.he_bits = bits;
409 event.he_source = origin;
410 event.he_destination = harvest_context.hc_destination[origin]++;
411 memcpy(event.he_entropy, entropy, size);
412 random_harvestq_fast_process_event(&event);
413 explicit_bzero(&event, sizeof(event));