randomdev_soft.c revision 137276
1/*-
2 * Copyright (c) 2000-2004 Mark R V Murray
3 * Copyright (c) 2004 Robert N. M. Watson
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer
11 *    in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/dev/random/randomdev_soft.c 137276 2004-11-05 20:15:06Z jhb $");
31
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/bus.h>
35#include <sys/conf.h>
36#include <sys/fcntl.h>
37#include <sys/kernel.h>
38#include <sys/kthread.h>
39#include <sys/lock.h>
40#include <sys/malloc.h>
41#include <sys/mutex.h>
42#include <sys/poll.h>
43#include <sys/proc.h>
44#include <sys/random.h>
45#include <sys/selinfo.h>
46#include <sys/sysctl.h>
47#include <sys/uio.h>
48#include <sys/unistd.h>
49#include <sys/vnode.h>
50
51#include <machine/bus.h>
52#include <machine/cpu.h>
53
54#include <dev/random/randomdev.h>
55#include <dev/random/randomdev_soft.h>
56
57#define RANDOM_FIFO_MAX	256	/* How many events to queue up */
58
59static void random_kthread(void *);
60static void
61random_harvest_internal(u_int64_t, const void *, u_int,
62    u_int, u_int, enum esource);
63
64struct random_systat random_yarrow = {
65	.ident = "Software, Yarrow",
66	.init = random_yarrow_init,
67	.deinit = random_yarrow_deinit,
68	.read = random_yarrow_read,
69	.write = random_yarrow_write,
70	.reseed = random_yarrow_reseed,
71	.seeded = 1,
72};
73
74MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers");
75
76/*
77 * The harvest mutex protects the consistency of the entropy fifos and
78 * empty fifo.
79 */
80struct mtx	harvest_mtx;
81
82/* Lockable FIFO queue holding entropy buffers */
83struct entropyfifo {
84	int count;
85	STAILQ_HEAD(harvestlist, harvest) head;
86};
87
88/* Empty entropy buffers */
89static struct entropyfifo emptyfifo;
90
91#define EMPTYBUFFERS	1024
92
93/* Harvested entropy */
94static struct entropyfifo harvestfifo[ENTROPYSOURCE];
95
96/* <0 to end the kthread, 0 to let it run */
97static int random_kthread_control = 0;
98
99static struct proc *random_kthread_proc;
100
101/* List for the dynamic sysctls */
102struct sysctl_ctx_list random_clist;
103
104/* ARGSUSED */
105static int
106random_check_boolean(SYSCTL_HANDLER_ARGS)
107{
108	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
109		*(u_int *)(oidp->oid_arg1) = 1;
110	return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
111}
112
113/* ARGSUSED */
114void
115random_yarrow_init(void)
116{
117	int error, i;
118	struct harvest *np;
119	struct sysctl_oid *o, *random_o, *random_sys_o, *random_sys_harvest_o;
120	enum esource e;
121
122	o = SYSCTL_ADD_NODE(&random_clist,
123	    SYSCTL_STATIC_CHILDREN(_kern),
124	    OID_AUTO, "random", CTLFLAG_RW, 0,
125	    "Software Random Number Generator");
126
127	random_o = o;
128
129	random_yarrow_init_alg(&random_clist, random_o);
130
131	o = SYSCTL_ADD_NODE(&random_clist,
132	    SYSCTL_CHILDREN(random_o),
133	    OID_AUTO, "sys", CTLFLAG_RW, 0,
134	    "Entropy Device Parameters");
135
136	random_sys_o = o;
137
138	o = SYSCTL_ADD_PROC(&random_clist,
139	    SYSCTL_CHILDREN(random_sys_o),
140	    OID_AUTO, "seeded", CTLTYPE_INT | CTLFLAG_RW,
141	    &random_systat.seeded, 1, random_check_boolean, "I",
142	    "Seeded State");
143
144	o = SYSCTL_ADD_NODE(&random_clist,
145	    SYSCTL_CHILDREN(random_sys_o),
146	    OID_AUTO, "harvest", CTLFLAG_RW, 0,
147	    "Entropy Sources");
148
149	random_sys_harvest_o = o;
150
151	o = SYSCTL_ADD_PROC(&random_clist,
152	    SYSCTL_CHILDREN(random_sys_harvest_o),
153	    OID_AUTO, "ethernet", CTLTYPE_INT | CTLFLAG_RW,
154	    &harvest.ethernet, 1, random_check_boolean, "I",
155	    "Harvest NIC entropy");
156	o = SYSCTL_ADD_PROC(&random_clist,
157	    SYSCTL_CHILDREN(random_sys_harvest_o),
158	    OID_AUTO, "point_to_point", CTLTYPE_INT | CTLFLAG_RW,
159	    &harvest.point_to_point, 1, random_check_boolean, "I",
160	    "Harvest serial net entropy");
161	o = SYSCTL_ADD_PROC(&random_clist,
162	    SYSCTL_CHILDREN(random_sys_harvest_o),
163	    OID_AUTO, "interrupt", CTLTYPE_INT | CTLFLAG_RW,
164	    &harvest.interrupt, 1, random_check_boolean, "I",
165	    "Harvest IRQ entropy");
166	o = SYSCTL_ADD_PROC(&random_clist,
167	    SYSCTL_CHILDREN(random_sys_harvest_o),
168	    OID_AUTO, "swi", CTLTYPE_INT | CTLFLAG_RW,
169	    &harvest.swi, 0, random_check_boolean, "I",
170	    "Harvest SWI entropy");
171
172	/* Initialise the harvest fifos */
173	STAILQ_INIT(&emptyfifo.head);
174	emptyfifo.count = 0;
175	for (i = 0; i < EMPTYBUFFERS; i++) {
176		np = malloc(sizeof(struct harvest), M_ENTROPY, M_WAITOK);
177		STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
178	}
179	for (e = RANDOM_START; e < ENTROPYSOURCE; e++) {
180		STAILQ_INIT(&harvestfifo[e].head);
181		harvestfifo[e].count = 0;
182	}
183
184	mtx_init(&harvest_mtx, "entropy harvest mutex", NULL, MTX_SPIN);
185
186	/* Start the hash/reseed thread */
187	error = kthread_create(random_kthread, NULL,
188	    &random_kthread_proc, RFHIGHPID, 0, "yarrow");
189	if (error != 0)
190		panic("Cannot create entropy maintenance thread.");
191
192	/* Register the randomness harvesting routine */
193	random_yarrow_init_harvester(random_harvest_internal,
194	    random_yarrow_read);
195}
196
197/* ARGSUSED */
198void
199random_yarrow_deinit(void)
200{
201	struct harvest *np;
202	enum esource e;
203
204	/* Deregister the randomness harvesting routine */
205	random_yarrow_deinit_harvester();
206
207	/*
208	 * Command the hash/reseed thread to end and wait for it to finish
209	 */
210	random_kthread_control = -1;
211	tsleep((void *)&random_kthread_control, curthread->td_priority, "term",
212	    0);
213
214	/* Destroy the harvest fifos */
215	while (!STAILQ_EMPTY(&emptyfifo.head)) {
216		np = STAILQ_FIRST(&emptyfifo.head);
217		STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
218		free(np, M_ENTROPY);
219	}
220	for (e = RANDOM_START; e < ENTROPYSOURCE; e++) {
221		while (!STAILQ_EMPTY(&harvestfifo[e].head)) {
222			np = STAILQ_FIRST(&harvestfifo[e].head);
223			STAILQ_REMOVE_HEAD(&harvestfifo[e].head, next);
224			free(np, M_ENTROPY);
225		}
226	}
227
228	random_yarrow_deinit_alg();
229
230	mtx_destroy(&harvest_mtx);
231
232	sysctl_ctx_free(&random_clist);
233}
234
235/* ARGSUSED */
236static void
237random_kthread(void *arg __unused)
238{
239	STAILQ_HEAD(, harvest) local_queue;
240	struct harvest *event = NULL;
241	int active, local_count;
242	enum esource source;
243
244	STAILQ_INIT(&local_queue);
245	local_count = 0;
246
247	/* Process until told to stop */
248	for (; random_kthread_control == 0;) {
249
250		active = 0;
251
252		/* Cycle through all the entropy sources */
253		mtx_lock_spin(&harvest_mtx);
254		for (source = RANDOM_START; source < ENTROPYSOURCE; source++) {
255			/*
256			 * Drain entropy source records into a thread-local
257			 * queue for processing while not holding the mutex.
258			 */
259			STAILQ_CONCAT(&local_queue, &harvestfifo[source].head);
260			local_count += harvestfifo[source].count;
261			harvestfifo[source].count = 0;
262		}
263
264		/*
265		 * Deal with events, if any, dropping the mutex as we process
266		 * each event.  Then push the events back into the empty
267		 * fifo.
268		 */
269		if (!STAILQ_EMPTY(&local_queue)) {
270			mtx_unlock_spin(&harvest_mtx);
271			STAILQ_FOREACH(event, &local_queue, next)
272				random_process_event(event);
273			mtx_lock_spin(&harvest_mtx);
274			STAILQ_CONCAT(&emptyfifo.head, &local_queue);
275			emptyfifo.count += local_count;
276			local_count = 0;
277		}
278		mtx_unlock_spin(&harvest_mtx);
279
280		KASSERT(local_count == 0, ("random_kthread: local_count %d",
281		    local_count));
282
283		/* Found nothing, so don't belabour the issue */
284		if (!active)
285			tsleep(&harvestfifo, curthread->td_priority, "-",
286			    hz / 10);
287
288	}
289
290	random_set_wakeup_exit(&random_kthread_control);
291	/* NOTREACHED */
292}
293
294/* Entropy harvesting routine. This is supposed to be fast; do
295 * not do anything slow in here!
296 */
297static void
298random_harvest_internal(u_int64_t somecounter, const void *entropy,
299    u_int count, u_int bits, u_int frac, enum esource origin)
300{
301	struct harvest *event;
302
303	KASSERT(origin == RANDOM_START || origin == RANDOM_WRITE ||
304            origin == RANDOM_KEYBOARD || origin == RANDOM_MOUSE ||
305            origin == RANDOM_NET || origin == RANDOM_INTERRUPT ||
306            origin == RANDOM_PURE || origin == ENTROPYSOURCE,
307	    ("random_harvest_internal: origin %d invalid\n", origin));
308
309	/* Lockless read to avoid lock operations if fifo is full. */
310	if (harvestfifo[origin].count >= RANDOM_FIFO_MAX)
311		return;
312
313	mtx_lock_spin(&harvest_mtx);
314
315	/*
316	 * Don't make the harvest queues too big - help to prevent low-grade
317	 * entropy swamping
318	 */
319	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
320		event = STAILQ_FIRST(&emptyfifo.head);
321		if (event != NULL) {
322			/* Add the harvested data to the fifo */
323			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
324			harvestfifo[origin].count++;
325			event->somecounter = somecounter;
326			event->size = count;
327			event->bits = bits;
328			event->frac = frac;
329			event->source = origin;
330
331			/* XXXX Come back and make this dynamic! */
332			count = MIN(count, HARVESTSIZE);
333			memcpy(event->entropy, entropy, count);
334
335			STAILQ_INSERT_TAIL(&harvestfifo[origin].head,
336			    event, next);
337		}
338	}
339	mtx_unlock_spin(&harvest_mtx);
340}
341
342void
343random_yarrow_write(void *buf, int count)
344{
345	int i;
346	u_int chunk;
347
348	/*
349	 * Break the input up into HARVESTSIZE chunks. The writer has too
350	 * much control here, so "estimate" the the entropy as zero.
351	 */
352	for (i = 0; i < count; i += HARVESTSIZE) {
353		chunk = HARVESTSIZE;
354		if (i + chunk >= count)
355			chunk = (u_int)(count - i);
356		random_harvest_internal(get_cyclecount(), (char *)buf + i,
357		    chunk, 0, 0, RANDOM_WRITE);
358	}
359}
360
361void
362random_yarrow_unblock(void)
363{
364	if (!random_systat.seeded) {
365		random_systat.seeded = 1;
366		selwakeuppri(&random_systat.rsel, PUSER);
367		wakeup(&random_systat);
368	}
369}
370