2 * Copyright (c) 2000-2013 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 "opt_random.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #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/mutex.h>
44 #include <sys/random.h>
45 #include <sys/selinfo.h>
46 #include <sys/sysctl.h>
47 #include <sys/unistd.h>
49 #include <machine/cpu.h>
50 #include <machine/vmparam.h>
52 #include <dev/random/randomdev.h>
53 #include <dev/random/randomdev_soft.h>
54 #include <dev/random/random_adaptors.h>
55 #include <dev/random/random_harvestq.h>
56 #include <dev/random/live_entropy_sources.h>
57 #include <dev/random/rwfile.h>
59 #define RANDOM_FIFO_MAX 1024 /* How many events to queue up */
62 * The harvest mutex protects the consistency of the entropy fifos and
63 * empty fifo and other associated structures.
65 struct mtx harvest_mtx;
67 /* Lockable FIFO queue holding entropy buffers */
70 STAILQ_HEAD(harvestlist, harvest) head;
73 /* Empty entropy buffers */
74 static struct entropyfifo emptyfifo;
76 /* Harvested entropy */
77 static struct entropyfifo harvestfifo;
79 /* <0 to end the kthread, 0 to let it run, 1 to flush the harvest queues */
80 int random_kthread_control = 0;
82 static struct proc *random_kthread_proc;
84 static event_proc_f random_cb;
87 static const char *entropy_files[] = {
93 /* Deal with entropy cached externally if this is present.
94 * Lots of policy may eventually arrive in this function.
95 * Called after / is mounted.
98 random_harvestq_cache(void *arg __unused)
100 uint8_t *keyfile, *data;
103 const char **entropy_file;
108 /* Get stuff that may have been preloaded by loader(8) */
109 keyfile = preload_search_by_type("/boot/entropy");
110 if (keyfile != NULL) {
111 data = preload_fetch_addr(keyfile);
112 size = preload_fetch_size(keyfile);
113 if (data != NULL && size != 0) {
114 for (i = 0; i < size; i += 16)
115 random_harvestq_internal(get_cyclecount(), data + i, 16, 16, RANDOM_CACHED);
116 printf("random: read %zu bytes from preloaded cache\n", size);
120 printf("random: no preloaded entropy cache available\n");
124 /* Read and attempt to overwrite the entropy cache files.
125 * If the file exists, can be read and then overwritten,
126 * then use it. Ignore it otherwise, but print out what is
129 data = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
130 zbuf = __DECONST(void *, zero_region);
131 for (entropy_file = entropy_files; *entropy_file; entropy_file++) {
132 error = randomdev_read_file(*entropy_file, data, PAGE_SIZE);
134 printf("random: entropy cache '%s' provides %ld bytes\n", *entropy_file, (long)PAGE_SIZE);
135 error = randomdev_write_file(*entropy_file, zbuf, PAGE_SIZE);
137 printf("random: entropy cache '%s' contents used and successfully overwritten\n", *entropy_file);
138 for (i = 0; i < PAGE_SIZE; i += 16)
139 random_harvestq_internal(get_cyclecount(), data + i, 16, 16, RANDOM_CACHED);
142 printf("random: entropy cache '%s' not overwritten and therefore not used; error = %d\n", *entropy_file, error);
145 printf("random: entropy cache '%s' not present or unreadable; error = %d\n", *entropy_file, error);
147 bzero(data, PAGE_SIZE);
148 free(data, M_ENTROPY);
151 EVENTHANDLER_DEFINE(mountroot, random_harvestq_cache, NULL, 0);
154 random_kthread(void *arg)
156 STAILQ_HEAD(, harvest) local_queue;
157 struct harvest *event = NULL;
159 event_proc_f entropy_processor = arg;
161 STAILQ_INIT(&local_queue);
164 /* Process until told to stop */
165 mtx_lock_spin(&harvest_mtx);
166 for (; random_kthread_control >= 0;) {
169 * Grab all the entropy events.
170 * Drain entropy source records into a thread-local
171 * queue for processing while not holding the mutex.
173 STAILQ_CONCAT(&local_queue, &harvestfifo.head);
174 local_count += harvestfifo.count;
175 harvestfifo.count = 0;
178 * Deal with events, if any.
179 * Then transfer the used events back into the empty fifo.
181 if (!STAILQ_EMPTY(&local_queue)) {
182 mtx_unlock_spin(&harvest_mtx);
183 STAILQ_FOREACH(event, &local_queue, next)
184 entropy_processor(event);
185 mtx_lock_spin(&harvest_mtx);
186 STAILQ_CONCAT(&emptyfifo.head, &local_queue);
187 emptyfifo.count += local_count;
191 KASSERT(local_count == 0, ("random_kthread: local_count %d",
195 * Do only one round of the hardware sources for now.
196 * Later we'll need to make it rate-adaptive.
198 mtx_unlock_spin(&harvest_mtx);
199 live_entropy_sources_feed(1, entropy_processor);
200 mtx_lock_spin(&harvest_mtx);
203 * If a queue flush was commanded, it has now happened,
204 * and we can mark this by resetting the command.
207 if (random_kthread_control == 1)
208 random_kthread_control = 0;
210 /* Work done, so don't belabour the issue */
211 msleep_spin_sbt(&random_kthread_control, &harvest_mtx,
212 "-", SBT_1S/10, 0, C_PREL(1));
215 mtx_unlock_spin(&harvest_mtx);
217 random_set_wakeup_exit(&random_kthread_control);
222 random_harvestq_init(event_proc_f cb)
227 /* Initialise the harvest fifos */
229 /* Contains the currently unused event structs. */
230 STAILQ_INIT(&emptyfifo.head);
231 for (i = 0; i < RANDOM_FIFO_MAX; i++) {
232 np = malloc(sizeof(struct harvest), M_ENTROPY, M_WAITOK);
233 STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
235 emptyfifo.count = RANDOM_FIFO_MAX;
237 /* Will contain the queued-up events. */
238 STAILQ_INIT(&harvestfifo.head);
239 harvestfifo.count = 0;
241 mtx_init(&harvest_mtx, "entropy harvest mutex", NULL, MTX_SPIN);
247 random_harvestq_start_kproc(void *arg __unused)
251 if (random_cb == NULL)
254 /* Start the hash/reseed thread */
255 error = kproc_create(random_kthread, random_cb,
256 &random_kthread_proc, RFHIGHPID, 0, "rand_harvestq"); /* RANDOM_CSPRNG_NAME */
259 panic("Cannot create entropy maintenance thread.");
261 SYSINIT(random_kthread, SI_SUB_DRIVERS, SI_ORDER_ANY,
262 random_harvestq_start_kproc, NULL);
265 random_harvestq_deinit(void)
269 /* Destroy the harvest fifos */
270 while (!STAILQ_EMPTY(&emptyfifo.head)) {
271 np = STAILQ_FIRST(&emptyfifo.head);
272 STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
276 while (!STAILQ_EMPTY(&harvestfifo.head)) {
277 np = STAILQ_FIRST(&harvestfifo.head);
278 STAILQ_REMOVE_HEAD(&harvestfifo.head, next);
281 harvestfifo.count = 0;
284 * Command the hash/reseed thread to end and wait for it to finish
286 mtx_lock_spin(&harvest_mtx);
287 if (random_kthread_proc != NULL) {
288 random_kthread_control = -1;
289 msleep_spin((void *)&random_kthread_control, &harvest_mtx,
292 mtx_unlock_spin(&harvest_mtx);
294 mtx_destroy(&harvest_mtx);
298 * Entropy harvesting routine.
299 * This is supposed to be fast; do not do anything slow in here!
301 * It is also illegal (and morally reprehensible) to insert any
302 * high-rate data here. "High-rate" is define as a data source
303 * that will usually cause lots of failures of the "Lockless read"
304 * check a few lines below. This includes the "always-on" sources
305 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
308 random_harvestq_internal(u_int64_t somecounter, const void *entropy,
309 u_int count, u_int bits, enum esource origin)
311 struct harvest *event;
313 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE,
314 ("random_harvest_internal: origin %d invalid\n", origin));
316 /* Lockless read to avoid lock operations if fifo is full. */
317 if (harvestfifo.count >= RANDOM_FIFO_MAX)
320 mtx_lock_spin(&harvest_mtx);
323 * On't overfill the harvest queue; this could steal all
326 if (harvestfifo.count < RANDOM_FIFO_MAX) {
327 event = STAILQ_FIRST(&emptyfifo.head);
329 /* Add the harvested data to the fifo */
330 STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
332 event->somecounter = somecounter;
335 event->source = origin;
337 /* XXXX Come back and make this dynamic! */
338 count = MIN(count, HARVESTSIZE);
339 memcpy(event->entropy, entropy, count);
341 STAILQ_INSERT_TAIL(&harvestfifo.head,
347 mtx_unlock_spin(&harvest_mtx);