randomdev_soft.c revision 153575
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 153575 2005-12-20 21:41:52Z ps $");
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
50#include <machine/bus.h>
51#include <machine/cpu.h>
52
53#include <dev/random/randomdev.h>
54#include <dev/random/randomdev_soft.h>
55
56#define RANDOM_FIFO_MAX	256	/* How many events to queue up */
57
58static void random_kthread(void *);
59static void
60random_harvest_internal(u_int64_t, const void *, u_int,
61    u_int, u_int, enum esource);
62static int random_yarrow_poll(int event,struct thread *td);
63static int random_yarrow_block(int flag);
64
65struct random_systat random_yarrow = {
66	.ident = "Software, Yarrow",
67	.init = random_yarrow_init,
68	.deinit = random_yarrow_deinit,
69	.block = random_yarrow_block,
70	.read = random_yarrow_read,
71	.write = random_yarrow_write,
72	.poll = random_yarrow_poll,
73	.reseed = random_yarrow_reseed,
74	.seeded = 1,
75};
76
77MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers");
78
79/*
80 * The harvest mutex protects the consistency of the entropy fifos and
81 * empty fifo.
82 */
83struct mtx	harvest_mtx;
84
85/* Lockable FIFO queue holding entropy buffers */
86struct entropyfifo {
87	int count;
88	STAILQ_HEAD(harvestlist, harvest) head;
89};
90
91/* Empty entropy buffers */
92static struct entropyfifo emptyfifo;
93
94#define EMPTYBUFFERS	1024
95
96/* Harvested entropy */
97static struct entropyfifo harvestfifo[ENTROPYSOURCE];
98
99/* <0 to end the kthread, 0 to let it run */
100static int random_kthread_control = 0;
101
102static struct proc *random_kthread_proc;
103
104/* List for the dynamic sysctls */
105struct sysctl_ctx_list random_clist;
106
107/* ARGSUSED */
108static int
109random_check_boolean(SYSCTL_HANDLER_ARGS)
110{
111	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
112		*(u_int *)(oidp->oid_arg1) = 1;
113	return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
114}
115
116/* ARGSUSED */
117void
118random_yarrow_init(void)
119{
120	int error, i;
121	struct harvest *np;
122	struct sysctl_oid *o, *random_o, *random_sys_o, *random_sys_harvest_o;
123	enum esource e;
124
125	o = SYSCTL_ADD_NODE(&random_clist,
126	    SYSCTL_STATIC_CHILDREN(_kern),
127	    OID_AUTO, "random", CTLFLAG_RW, 0,
128	    "Software Random Number Generator");
129
130	random_o = o;
131
132	random_yarrow_init_alg(&random_clist, random_o);
133
134	o = SYSCTL_ADD_NODE(&random_clist,
135	    SYSCTL_CHILDREN(random_o),
136	    OID_AUTO, "sys", CTLFLAG_RW, 0,
137	    "Entropy Device Parameters");
138
139	random_sys_o = o;
140
141	o = SYSCTL_ADD_PROC(&random_clist,
142	    SYSCTL_CHILDREN(random_sys_o),
143	    OID_AUTO, "seeded", CTLTYPE_INT | CTLFLAG_RW,
144	    &random_systat.seeded, 1, random_check_boolean, "I",
145	    "Seeded State");
146
147	o = SYSCTL_ADD_NODE(&random_clist,
148	    SYSCTL_CHILDREN(random_sys_o),
149	    OID_AUTO, "harvest", CTLFLAG_RW, 0,
150	    "Entropy Sources");
151
152	random_sys_harvest_o = o;
153
154	o = SYSCTL_ADD_PROC(&random_clist,
155	    SYSCTL_CHILDREN(random_sys_harvest_o),
156	    OID_AUTO, "ethernet", CTLTYPE_INT | CTLFLAG_RW,
157	    &harvest.ethernet, 1, random_check_boolean, "I",
158	    "Harvest NIC entropy");
159	o = SYSCTL_ADD_PROC(&random_clist,
160	    SYSCTL_CHILDREN(random_sys_harvest_o),
161	    OID_AUTO, "point_to_point", CTLTYPE_INT | CTLFLAG_RW,
162	    &harvest.point_to_point, 1, random_check_boolean, "I",
163	    "Harvest serial net entropy");
164	o = SYSCTL_ADD_PROC(&random_clist,
165	    SYSCTL_CHILDREN(random_sys_harvest_o),
166	    OID_AUTO, "interrupt", CTLTYPE_INT | CTLFLAG_RW,
167	    &harvest.interrupt, 1, random_check_boolean, "I",
168	    "Harvest IRQ entropy");
169	o = SYSCTL_ADD_PROC(&random_clist,
170	    SYSCTL_CHILDREN(random_sys_harvest_o),
171	    OID_AUTO, "swi", CTLTYPE_INT | CTLFLAG_RW,
172	    &harvest.swi, 0, random_check_boolean, "I",
173	    "Harvest SWI entropy");
174
175	/* Initialise the harvest fifos */
176	STAILQ_INIT(&emptyfifo.head);
177	emptyfifo.count = 0;
178	for (i = 0; i < EMPTYBUFFERS; i++) {
179		np = malloc(sizeof(struct harvest), M_ENTROPY, M_WAITOK);
180		STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
181	}
182	for (e = RANDOM_START; e < ENTROPYSOURCE; e++) {
183		STAILQ_INIT(&harvestfifo[e].head);
184		harvestfifo[e].count = 0;
185	}
186
187	mtx_init(&harvest_mtx, "entropy harvest mutex", NULL, MTX_SPIN);
188
189	/* Start the hash/reseed thread */
190	error = kthread_create(random_kthread, NULL,
191	    &random_kthread_proc, RFHIGHPID, 0, "yarrow");
192	if (error != 0)
193		panic("Cannot create entropy maintenance thread.");
194
195	/* Register the randomness harvesting routine */
196	random_yarrow_init_harvester(random_harvest_internal,
197	    random_yarrow_read);
198}
199
200/* ARGSUSED */
201void
202random_yarrow_deinit(void)
203{
204	struct harvest *np;
205	enum esource e;
206
207	/* Deregister the randomness harvesting routine */
208	random_yarrow_deinit_harvester();
209
210	/*
211	 * Command the hash/reseed thread to end and wait for it to finish
212	 */
213	random_kthread_control = -1;
214	tsleep((void *)&random_kthread_control, curthread->td_priority, "term",
215	    0);
216
217	/* Destroy the harvest fifos */
218	while (!STAILQ_EMPTY(&emptyfifo.head)) {
219		np = STAILQ_FIRST(&emptyfifo.head);
220		STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
221		free(np, M_ENTROPY);
222	}
223	for (e = RANDOM_START; e < ENTROPYSOURCE; e++) {
224		while (!STAILQ_EMPTY(&harvestfifo[e].head)) {
225			np = STAILQ_FIRST(&harvestfifo[e].head);
226			STAILQ_REMOVE_HEAD(&harvestfifo[e].head, next);
227			free(np, M_ENTROPY);
228		}
229	}
230
231	random_yarrow_deinit_alg();
232
233	mtx_destroy(&harvest_mtx);
234
235	sysctl_ctx_free(&random_clist);
236}
237
238/* ARGSUSED */
239static void
240random_kthread(void *arg __unused)
241{
242	STAILQ_HEAD(, harvest) local_queue;
243	struct harvest *event = NULL;
244	int active, local_count;
245	enum esource source;
246
247	STAILQ_INIT(&local_queue);
248	local_count = 0;
249
250	/* Process until told to stop */
251	for (; random_kthread_control == 0;) {
252
253		active = 0;
254
255		/* Cycle through all the entropy sources */
256		mtx_lock_spin(&harvest_mtx);
257		for (source = RANDOM_START; source < ENTROPYSOURCE; source++) {
258			/*
259			 * Drain entropy source records into a thread-local
260			 * queue for processing while not holding the mutex.
261			 */
262			STAILQ_CONCAT(&local_queue, &harvestfifo[source].head);
263			local_count += harvestfifo[source].count;
264			harvestfifo[source].count = 0;
265		}
266
267		/*
268		 * Deal with events, if any, dropping the mutex as we process
269		 * each event.  Then push the events back into the empty
270		 * fifo.
271		 */
272		if (!STAILQ_EMPTY(&local_queue)) {
273			mtx_unlock_spin(&harvest_mtx);
274			STAILQ_FOREACH(event, &local_queue, next)
275				random_process_event(event);
276			mtx_lock_spin(&harvest_mtx);
277			STAILQ_CONCAT(&emptyfifo.head, &local_queue);
278			emptyfifo.count += local_count;
279			local_count = 0;
280		}
281		mtx_unlock_spin(&harvest_mtx);
282
283		KASSERT(local_count == 0, ("random_kthread: local_count %d",
284		    local_count));
285
286		/* Found nothing, so don't belabour the issue */
287		if (!active)
288			tsleep(&harvestfifo, curthread->td_priority, "-",
289			    hz / 10);
290
291	}
292
293	random_set_wakeup_exit(&random_kthread_control);
294	/* NOTREACHED */
295}
296
297/* Entropy harvesting routine. This is supposed to be fast; do
298 * not do anything slow in here!
299 */
300static void
301random_harvest_internal(u_int64_t somecounter, const void *entropy,
302    u_int count, u_int bits, u_int frac, enum esource origin)
303{
304	struct harvest *event;
305
306	KASSERT(origin == RANDOM_START || origin == RANDOM_WRITE ||
307            origin == RANDOM_KEYBOARD || origin == RANDOM_MOUSE ||
308            origin == RANDOM_NET || origin == RANDOM_INTERRUPT ||
309            origin == RANDOM_PURE,
310	    ("random_harvest_internal: origin %d invalid\n", origin));
311
312	/* Lockless read to avoid lock operations if fifo is full. */
313	if (harvestfifo[origin].count >= RANDOM_FIFO_MAX)
314		return;
315
316	mtx_lock_spin(&harvest_mtx);
317
318	/*
319	 * Don't make the harvest queues too big - help to prevent low-grade
320	 * entropy swamping
321	 */
322	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
323		event = STAILQ_FIRST(&emptyfifo.head);
324		if (event != NULL) {
325			/* Add the harvested data to the fifo */
326			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
327			harvestfifo[origin].count++;
328			event->somecounter = somecounter;
329			event->size = count;
330			event->bits = bits;
331			event->frac = frac;
332			event->source = origin;
333
334			/* XXXX Come back and make this dynamic! */
335			count = MIN(count, HARVESTSIZE);
336			memcpy(event->entropy, entropy, count);
337
338			STAILQ_INSERT_TAIL(&harvestfifo[origin].head,
339			    event, next);
340		}
341	}
342	mtx_unlock_spin(&harvest_mtx);
343}
344
345void
346random_yarrow_write(void *buf, int count)
347{
348	int i;
349	u_int chunk;
350
351	/*
352	 * Break the input up into HARVESTSIZE chunks. The writer has too
353	 * much control here, so "estimate" the the entropy as zero.
354	 */
355	for (i = 0; i < count; i += HARVESTSIZE) {
356		chunk = HARVESTSIZE;
357		if (i + chunk >= count)
358			chunk = (u_int)(count - i);
359		random_harvest_internal(get_cyclecount(), (char *)buf + i,
360		    chunk, 0, 0, RANDOM_WRITE);
361	}
362}
363
364void
365random_yarrow_unblock(void)
366{
367	if (!random_systat.seeded) {
368		random_systat.seeded = 1;
369		selwakeuppri(&random_systat.rsel, PUSER);
370		wakeup(&random_systat);
371	}
372}
373
374static int
375random_yarrow_poll(int events, struct thread *td)
376{
377	int revents = 0;
378	mtx_lock(&random_reseed_mtx);
379
380	if (random_systat.seeded)
381		revents = events & (POLLIN | POLLRDNORM);
382	else
383		selrecord(td, &random_systat.rsel);
384
385	mtx_unlock(&random_reseed_mtx);
386	return revents;
387}
388
389static int
390random_yarrow_block(int flag)
391{
392	int error = 0;
393
394	mtx_lock(&random_reseed_mtx);
395
396	/* Blocking logic */
397	while (random_systat.seeded && !error) {
398		if (flag & O_NONBLOCK)
399			error = EWOULDBLOCK;
400		else {
401			printf("Entropy device is blocking.\n");
402			error = msleep(&random_systat,
403			    &random_reseed_mtx,
404			    PUSER | PCATCH, "block", 0);
405		}
406	}
407	mtx_unlock(&random_reseed_mtx);
408
409	return error;
410}
411