randomdev.c revision 122871
1/*-
2 * Copyright (c) 2000, 2001, 2002, 2003 Mark R V Murray
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 *
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/dev/random/randomdev.c 122871 2003-11-17 23:02:21Z markm $");
30
31#include <sys/param.h>
32#include <sys/systm.h>
33#include <sys/bus.h>
34#include <sys/conf.h>
35#include <sys/fcntl.h>
36#include <sys/filio.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
56static d_close_t	random_close;
57static d_read_t		random_read;
58static d_write_t	random_write;
59static d_ioctl_t	random_ioctl;
60static d_poll_t		random_poll;
61
62#define RANDOM_MINOR	0
63
64#define RANDOM_FIFO_MAX	256	/* How many events to queue up */
65
66static struct cdevsw random_cdevsw = {
67	.d_close =	random_close,
68	.d_read =	random_read,
69	.d_write =	random_write,
70	.d_ioctl =	random_ioctl,
71	.d_poll =	random_poll,
72	.d_name =	"random",
73};
74
75static void random_kthread(void *);
76static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
77static void random_write_internal(void *, int);
78
79MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers");
80
81/* FIFO queues holding harvested entropy */
82static struct harvestfifo {
83	struct mtx lock;
84	int count;
85	STAILQ_HEAD(harvestlist, harvest) head;
86} harvestfifo[ENTROPYSOURCE];
87
88static struct random_systat {
89	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
90	struct selinfo	rsel;	/* For poll(2) */
91} random_systat;
92
93/* <0 to end the kthread, 0 to let it run */
94static int random_kthread_control = 0;
95
96static struct proc *random_kthread_proc;
97
98/* For use with make_dev(9)/destroy_dev(9). */
99static dev_t	random_dev;
100static dev_t	urandom_dev;
101
102/* ARGSUSED */
103static int
104random_check_boolean(SYSCTL_HANDLER_ARGS)
105{
106	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
107		*(u_int *)(oidp->oid_arg1) = 1;
108        return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
109}
110
111SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
112	0, "Random Number Generator");
113SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
114	0, "Entropy Device Parameters");
115SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
116	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
117	random_check_boolean, "I", "Seeded State");
118SYSCTL_NODE(_kern_random_sys, OID_AUTO, harvest, CTLFLAG_RW,
119	0, "Entropy Sources");
120SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, ethernet,
121	CTLTYPE_INT|CTLFLAG_RW, &harvest.ethernet, 0,
122	random_check_boolean, "I", "Harvest NIC entropy");
123SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, point_to_point,
124	CTLTYPE_INT|CTLFLAG_RW, &harvest.point_to_point, 0,
125	random_check_boolean, "I", "Harvest serial net entropy");
126SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, interrupt,
127	CTLTYPE_INT|CTLFLAG_RW, &harvest.interrupt, 0,
128	random_check_boolean, "I", "Harvest IRQ entropy");
129SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, swi,
130	CTLTYPE_INT|CTLFLAG_RW, &harvest.swi, 0,
131	random_check_boolean, "I", "Harvest SWI entropy");
132
133/* ARGSUSED */
134static int
135random_close(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
136{
137	if (flags & FWRITE) {
138		if (suser(td) == 0 && securelevel_gt(td->td_ucred, 0) == 0)
139			random_reseed();
140	}
141	return 0;
142}
143
144/* ARGSUSED */
145static int
146random_read(dev_t dev __unused, struct uio *uio, int flag)
147{
148	int	c, ret;
149	int	error = 0;
150	void	*random_buf;
151
152	while (!random_systat.seeded) {
153		if (flag & IO_NDELAY)
154			error =  EWOULDBLOCK;
155		else
156			error = tsleep(&random_systat, PUSER|PCATCH,
157				"block", 0);
158		if (error != 0)
159			return error;
160	}
161	c = uio->uio_resid < PAGE_SIZE ? uio->uio_resid : PAGE_SIZE;
162	random_buf = (void *)malloc((u_long)c, M_TEMP, M_WAITOK);
163	while (uio->uio_resid > 0 && error == 0) {
164		ret = read_random_real(random_buf, c);
165		error = uiomove(random_buf, ret, uio);
166	}
167	free(random_buf, M_TEMP);
168	return error;
169}
170
171/* ARGSUSED */
172static int
173random_write(dev_t dev __unused, struct uio *uio, int flag __unused)
174{
175	int	c;
176	int	error;
177	void	*random_buf;
178
179	error = 0;
180	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
181	while (uio->uio_resid > 0) {
182		c = (int)(uio->uio_resid < PAGE_SIZE
183		    ? uio->uio_resid
184		    : PAGE_SIZE);
185		error = uiomove(random_buf, c, uio);
186		if (error)
187			break;
188		random_write_internal(random_buf, c);
189	}
190	free(random_buf, M_TEMP);
191	return error;
192}
193
194/* ARGSUSED */
195static int
196random_ioctl(dev_t dev __unused, u_long cmd, caddr_t addr __unused,
197    int flags __unused, struct thread *td __unused)
198{
199	switch (cmd) {
200	/* Really handled in upper layer */
201	case FIOASYNC:
202	case FIONBIO:
203		return 0;
204	default:
205		return ENOTTY;
206	}
207}
208
209/* ARGSUSED */
210static int
211random_poll(dev_t dev __unused, int events, struct thread *td)
212{
213	int	revents;
214
215	revents = 0;
216	if (events & (POLLIN | POLLRDNORM)) {
217		if (random_systat.seeded)
218			revents = events & (POLLIN | POLLRDNORM);
219		else
220			selrecord(td, &random_systat.rsel);
221	}
222	return revents;
223}
224
225/* ARGSUSED */
226static int
227random_modevent(module_t mod __unused, int type, void *data __unused)
228{
229	int	error, i;
230	struct harvest *np;
231
232	switch(type) {
233	case MOD_LOAD:
234		random_init();
235
236		/* This can be turned off by the very paranoid
237		 * a reseed will turn it back on.
238		 */
239		random_systat.seeded = 1;
240
241		/* Initialise the harvest fifos */
242		for (i = 0; i < ENTROPYSOURCE; i++) {
243			STAILQ_INIT(&harvestfifo[i].head);
244			harvestfifo[i].count = 0;
245			mtx_init(&harvestfifo[i].lock, "entropy harvest", NULL, MTX_DEF);
246		}
247
248		if (bootverbose)
249			printf("random: <entropy source>\n");
250		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
251			GID_WHEEL, 0666, "random");
252		urandom_dev = make_dev_alias(random_dev, "urandom");
253
254		/* Start the hash/reseed thread */
255		error = kthread_create(random_kthread, NULL,
256			&random_kthread_proc, RFHIGHPID, 0, "random");
257		if (error != 0)
258			return error;
259
260		/* Register the randomness harvesting routine */
261		random_init_harvester(random_harvest_internal,
262			read_random_real);
263
264		return 0;
265
266	case MOD_UNLOAD:
267		/* Deregister the randomness harvesting routine */
268		random_deinit_harvester();
269
270		/* Command the hash/reseed thread to end and
271		 * wait for it to finish
272		 */
273		random_kthread_control = -1;
274		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
275
276		/* Destroy the harvest fifos */
277		for (i = 0; i < ENTROPYSOURCE; i++) {
278			while (!STAILQ_EMPTY(&harvestfifo[i].head)) {
279				np = STAILQ_FIRST(&harvestfifo[i].head);
280				STAILQ_REMOVE_HEAD(&harvestfifo[i].head, next);
281				free(np, M_ENTROPY);
282			}
283			mtx_destroy(&harvestfifo[i].lock);
284		}
285
286		random_deinit();
287
288		destroy_dev(random_dev);
289		destroy_dev(urandom_dev);
290		return 0;
291
292	case MOD_SHUTDOWN:
293		return 0;
294
295	default:
296		return EOPNOTSUPP;
297	}
298}
299
300DEV_MODULE(random, random_modevent, NULL);
301
302/* ARGSUSED */
303static void
304random_kthread(void *arg __unused)
305{
306	struct harvest	*event = NULL;
307	int		found, active;
308	enum esource	source;
309
310	/* Process until told to stop */
311	for (; random_kthread_control == 0;) {
312
313		active = 0;
314
315		/* Cycle through all the entropy sources */
316		for (source = 0; source < ENTROPYSOURCE; source++) {
317
318			found = 0;
319
320			/* Lock up queue draining */
321			mtx_lock(&harvestfifo[source].lock);
322
323			if (!STAILQ_EMPTY(&harvestfifo[source].head)) {
324
325				/* Get a harvested entropy event */
326				harvestfifo[source].count--;
327				event = STAILQ_FIRST(&harvestfifo[source].head);
328				STAILQ_REMOVE_HEAD(&harvestfifo[source].head,
329					next);
330				active = found = 1;
331
332			}
333
334			/* Unlock the queue */
335			mtx_unlock(&harvestfifo[source].lock);
336
337			/* Deal with the event and dispose of it */
338			if (found) {
339				random_process_event(event);
340				free(event, M_ENTROPY);
341			}
342
343		}
344
345		/* Found nothing, so don't belabour the issue */
346		if (!active)
347			tsleep(&harvestfifo, PUSER, "-", hz/10);
348
349	}
350
351	random_set_wakeup_exit(&random_kthread_control);
352	/* NOTREACHED */
353}
354
355/* Entropy harvesting routine. This is supposed to be fast; do
356 * not do anything slow in here!
357 */
358static void
359random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
360	u_int bits, u_int frac, enum esource origin)
361{
362	struct harvest	*event;
363
364	/* Lock the particular fifo */
365	mtx_lock(&harvestfifo[origin].lock);
366
367	/* Don't make the harvest queues too big - memory is precious */
368	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
369
370		event = malloc(sizeof(struct harvest), M_ENTROPY, M_NOWAIT);
371
372		/* If we can't malloc() a buffer, tough */
373		if (event) {
374
375			/* Add the harvested data to the fifo */
376			harvestfifo[origin].count++;
377			event->somecounter = somecounter;
378			event->size = count;
379			event->bits = bits;
380			event->frac = frac;
381			event->source = origin;
382
383			/* XXXX Come back and make this dynamic! */
384			count = count > HARVESTSIZE ? HARVESTSIZE : count;
385			memcpy(event->entropy, entropy, count);
386
387			STAILQ_INSERT_TAIL(&harvestfifo[origin].head, event, next);
388		}
389
390	}
391
392	mtx_unlock(&harvestfifo[origin].lock);
393
394}
395
396static void
397random_write_internal(void *buf, int count)
398{
399	int	i;
400	u_int	chunk;
401
402	/* Break the input up into HARVESTSIZE chunks.
403	 * The writer has too much control here, so "estimate" the
404	 * the entropy as zero.
405	 */
406	for (i = 0; i < count; i += HARVESTSIZE) {
407		chunk = HARVESTSIZE;
408		if (i + chunk >= count)
409			chunk = (u_int)(count - i);
410		random_harvest_internal(get_cyclecount(), (char *)buf + i,
411			chunk, 0, 0, RANDOM_WRITE);
412	}
413}
414
415void
416random_unblock(void)
417{
418	if (!random_systat.seeded) {
419		random_systat.seeded = 1;
420		selwakeuppri(&random_systat.rsel, PUSER);
421		wakeup(&random_systat);
422	}
423}
424