randomdev_soft.c revision 137152
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 137152 2004-11-03 10:02:50Z rwatson $");
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, PUSER, "term", 0);
212
213	/* Destroy the harvest fifos */
214	while (!STAILQ_EMPTY(&emptyfifo.head)) {
215		np = STAILQ_FIRST(&emptyfifo.head);
216		STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
217		free(np, M_ENTROPY);
218	}
219	for (e = RANDOM_START; e < ENTROPYSOURCE; e++) {
220		while (!STAILQ_EMPTY(&harvestfifo[e].head)) {
221			np = STAILQ_FIRST(&harvestfifo[e].head);
222			STAILQ_REMOVE_HEAD(&harvestfifo[e].head, next);
223			free(np, M_ENTROPY);
224		}
225	}
226
227	random_yarrow_deinit_alg();
228
229	mtx_destroy(&harvest_mtx);
230
231	sysctl_ctx_free(&random_clist);
232}
233
234/* ARGSUSED */
235static void
236random_kthread(void *arg __unused)
237{
238	STAILQ_HEAD(, harvest) local_queue;
239	struct harvest *event = NULL;
240	int active, local_count;
241	enum esource source;
242
243	STAILQ_INIT(&local_queue);
244	local_count = 0;
245
246	/* Process until told to stop */
247	for (; random_kthread_control == 0;) {
248
249		active = 0;
250
251		/* Cycle through all the entropy sources */
252		mtx_lock_spin(&harvest_mtx);
253		for (source = RANDOM_START; source < ENTROPYSOURCE; source++) {
254			/*
255			 * Drain entropy source records into a thread-local
256			 * queue for processing while not holding the mutex.
257			 */
258			STAILQ_CONCAT(&local_queue, &harvestfifo[source].head);
259			local_count += harvestfifo[source].count;
260			harvestfifo[source].count = 0;
261		}
262
263		/*
264		 * Deal with events, if any, dropping the mutex as we process
265		 * each event.  Then push the events back into the empty
266		 * fifo.
267		 */
268		if (!STAILQ_EMPTY(&local_queue)) {
269			mtx_unlock_spin(&harvest_mtx);
270			STAILQ_FOREACH(event, &local_queue, next)
271				random_process_event(event);
272			mtx_lock_spin(&harvest_mtx);
273			STAILQ_CONCAT(&emptyfifo.head, &local_queue);
274			emptyfifo.count += local_count;
275			local_count = 0;
276		}
277		mtx_unlock_spin(&harvest_mtx);
278
279		KASSERT(local_count == 0, ("random_kthread: local_count %d",
280		    local_count));
281
282		/* Found nothing, so don't belabour the issue */
283		if (!active)
284			tsleep(&harvestfifo, PUSER, "-", hz / 10);
285
286	}
287
288	random_set_wakeup_exit(&random_kthread_control);
289	/* NOTREACHED */
290}
291
292/* Entropy harvesting routine. This is supposed to be fast; do
293 * not do anything slow in here!
294 */
295static void
296random_harvest_internal(u_int64_t somecounter, const void *entropy,
297    u_int count, u_int bits, u_int frac, enum esource origin)
298{
299	struct harvest *event;
300
301	KASSERT(origin == RANDOM_START || origin == RANDOM_WRITE ||
302            origin == RANDOM_KEYBOARD || origin == RANDOM_MOUSE ||
303            origin == RANDOM_NET || origin == RANDOM_INTERRUPT ||
304            origin == RANDOM_PURE || origin == ENTROPYSOURCE,
305	    ("random_harvest_internal: origin %d invalid\n", origin));
306
307	/* Lockless read to avoid lock operations if fifo is full. */
308	if (harvestfifo[origin].count >= RANDOM_FIFO_MAX)
309		return;
310
311	mtx_lock_spin(&harvest_mtx);
312
313	/*
314	 * Don't make the harvest queues too big - help to prevent low-grade
315	 * entropy swamping
316	 */
317	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
318		event = STAILQ_FIRST(&emptyfifo.head);
319		if (event != NULL) {
320			/* Add the harvested data to the fifo */
321			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
322			harvestfifo[origin].count++;
323			event->somecounter = somecounter;
324			event->size = count;
325			event->bits = bits;
326			event->frac = frac;
327			event->source = origin;
328
329			/* XXXX Come back and make this dynamic! */
330			count = MIN(count, HARVESTSIZE);
331			memcpy(event->entropy, entropy, count);
332
333			STAILQ_INSERT_TAIL(&harvestfifo[origin].head,
334			    event, next);
335		}
336	}
337	mtx_unlock_spin(&harvest_mtx);
338}
339
340void
341random_yarrow_write(void *buf, int count)
342{
343	int i;
344	u_int chunk;
345
346	/*
347	 * Break the input up into HARVESTSIZE chunks. The writer has too
348	 * much control here, so "estimate" the the entropy as zero.
349	 */
350	for (i = 0; i < count; i += HARVESTSIZE) {
351		chunk = HARVESTSIZE;
352		if (i + chunk >= count)
353			chunk = (u_int)(count - i);
354		random_harvest_internal(get_cyclecount(), (char *)buf + i,
355		    chunk, 0, 0, RANDOM_WRITE);
356	}
357}
358
359void
360random_yarrow_unblock(void)
361{
362	if (!random_systat.seeded) {
363		random_systat.seeded = 1;
364		selwakeuppri(&random_systat.rsel, PUSER);
365		wakeup(&random_systat);
366	}
367}
368