randomdev.c revision 126080
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 126080 2004-02-21 21:10:55Z phk $");
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_version =	D_VERSION,
68	.d_flags =	D_NEEDGIANT,
69	.d_close =	random_close,
70	.d_read =	random_read,
71	.d_write =	random_write,
72	.d_ioctl =	random_ioctl,
73	.d_poll =	random_poll,
74	.d_name =	"random",
75};
76
77static void random_kthread(void *);
78static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
79static void random_write_internal(void *, int);
80
81MALLOC_DEFINE(M_ENTROPY, "entropy", "Entropy harvesting buffers");
82
83/* Lockable FIFO queue holding entropy buffers */
84struct entropyfifo {
85	struct mtx lock;
86	int count;
87	STAILQ_HEAD(harvestlist, harvest) head;
88};
89
90/* Empty entropy buffers */
91static struct entropyfifo emptyfifo;
92#define EMPTYBUFFERS	1024
93
94/* Harvested entropy */
95static struct entropyfifo harvestfifo[ENTROPYSOURCE];
96
97static struct random_systat {
98	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
99	struct selinfo	rsel;	/* For poll(2) */
100} random_systat;
101
102/* <0 to end the kthread, 0 to let it run */
103static int random_kthread_control = 0;
104
105static struct proc *random_kthread_proc;
106
107/* For use with make_dev(9)/destroy_dev(9). */
108static dev_t	random_dev;
109
110/* ARGSUSED */
111static int
112random_check_boolean(SYSCTL_HANDLER_ARGS)
113{
114	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
115		*(u_int *)(oidp->oid_arg1) = 1;
116        return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
117}
118
119SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
120	0, "Random Number Generator");
121SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
122	0, "Entropy Device Parameters");
123SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
124	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
125	random_check_boolean, "I", "Seeded State");
126SYSCTL_NODE(_kern_random_sys, OID_AUTO, harvest, CTLFLAG_RW,
127	0, "Entropy Sources");
128SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, ethernet,
129	CTLTYPE_INT|CTLFLAG_RW, &harvest.ethernet, 0,
130	random_check_boolean, "I", "Harvest NIC entropy");
131SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, point_to_point,
132	CTLTYPE_INT|CTLFLAG_RW, &harvest.point_to_point, 0,
133	random_check_boolean, "I", "Harvest serial net entropy");
134SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, interrupt,
135	CTLTYPE_INT|CTLFLAG_RW, &harvest.interrupt, 0,
136	random_check_boolean, "I", "Harvest IRQ entropy");
137SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, swi,
138	CTLTYPE_INT|CTLFLAG_RW, &harvest.swi, 0,
139	random_check_boolean, "I", "Harvest SWI entropy");
140
141/* ARGSUSED */
142static int
143random_close(dev_t dev __unused, int flags, int fmt __unused, struct thread *td)
144{
145	if (flags & FWRITE) {
146		if (suser(td) == 0 && securelevel_gt(td->td_ucred, 0) == 0)
147			random_reseed();
148	}
149	return 0;
150}
151
152/* ARGSUSED */
153static int
154random_read(dev_t dev __unused, struct uio *uio, int flag)
155{
156	int	c, ret;
157	int	error = 0;
158	void	*random_buf;
159
160	while (!random_systat.seeded) {
161		if (flag & IO_NDELAY)
162			error =  EWOULDBLOCK;
163		else
164			error = tsleep(&random_systat, PUSER|PCATCH,
165				"block", 0);
166		if (error != 0)
167			return error;
168	}
169	c = uio->uio_resid < PAGE_SIZE ? uio->uio_resid : PAGE_SIZE;
170	random_buf = (void *)malloc((u_long)c, M_TEMP, M_WAITOK);
171	while (uio->uio_resid > 0 && error == 0) {
172		ret = read_random_real(random_buf, c);
173		error = uiomove(random_buf, ret, uio);
174	}
175	free(random_buf, M_TEMP);
176	return error;
177}
178
179/* ARGSUSED */
180static int
181random_write(dev_t dev __unused, struct uio *uio, int flag __unused)
182{
183	int	c;
184	int	error;
185	void	*random_buf;
186
187	error = 0;
188	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
189	while (uio->uio_resid > 0) {
190		c = (int)(uio->uio_resid < PAGE_SIZE
191		    ? uio->uio_resid
192		    : PAGE_SIZE);
193		error = uiomove(random_buf, c, uio);
194		if (error)
195			break;
196		random_write_internal(random_buf, c);
197	}
198	free(random_buf, M_TEMP);
199	return error;
200}
201
202/* ARGSUSED */
203static int
204random_ioctl(dev_t dev __unused, u_long cmd, caddr_t addr __unused,
205    int flags __unused, struct thread *td __unused)
206{
207	switch (cmd) {
208	/* Really handled in upper layer */
209	case FIOASYNC:
210	case FIONBIO:
211		return 0;
212	default:
213		return ENOTTY;
214	}
215}
216
217/* ARGSUSED */
218static int
219random_poll(dev_t dev __unused, int events, struct thread *td)
220{
221	int	revents;
222
223	revents = 0;
224	if (events & (POLLIN | POLLRDNORM)) {
225		if (random_systat.seeded)
226			revents = events & (POLLIN | POLLRDNORM);
227		else
228			selrecord(td, &random_systat.rsel);
229	}
230	return revents;
231}
232
233/* ARGSUSED */
234static int
235random_modevent(module_t mod __unused, int type, void *data __unused)
236{
237	int	error, i;
238	struct harvest *np;
239
240	switch(type) {
241	case MOD_LOAD:
242		random_init();
243
244		/* This can be turned off by the very paranoid
245		 * a reseed will turn it back on.
246		 */
247		random_systat.seeded = 1;
248
249		/* Initialise the harvest fifos */
250		STAILQ_INIT(&emptyfifo.head);
251		emptyfifo.count = 0;
252		mtx_init(&emptyfifo.lock, "entropy harvest buffers", NULL,
253			MTX_SPIN);
254		for (i = 0; i < EMPTYBUFFERS; i++) {
255			np = malloc(sizeof(struct harvest), M_ENTROPY,
256				M_WAITOK);
257			STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
258		}
259		for (i = 0; i < ENTROPYSOURCE; i++) {
260			STAILQ_INIT(&harvestfifo[i].head);
261			harvestfifo[i].count = 0;
262			mtx_init(&harvestfifo[i].lock, "entropy harvest", NULL,
263				MTX_SPIN);
264		}
265
266		if (bootverbose)
267			printf("random: <entropy source>\n");
268		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
269			GID_WHEEL, 0666, "random");
270		make_dev_alias(random_dev, "urandom");
271
272		/* Start the hash/reseed thread */
273		error = kthread_create(random_kthread, NULL,
274			&random_kthread_proc, RFHIGHPID, 0, "random");
275		if (error != 0)
276			return error;
277
278		/* Register the randomness harvesting routine */
279		random_init_harvester(random_harvest_internal,
280			read_random_real);
281
282		return 0;
283
284	case MOD_UNLOAD:
285		/* Deregister the randomness harvesting routine */
286		random_deinit_harvester();
287
288		/* Command the hash/reseed thread to end and
289		 * wait for it to finish
290		 */
291		random_kthread_control = -1;
292		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
293
294		/* Destroy the harvest fifos */
295		while (!STAILQ_EMPTY(&emptyfifo.head)) {
296			np = STAILQ_FIRST(&emptyfifo.head);
297			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
298			free(np, M_ENTROPY);
299		}
300		mtx_destroy(&emptyfifo.lock);
301		for (i = 0; i < ENTROPYSOURCE; i++) {
302			while (!STAILQ_EMPTY(&harvestfifo[i].head)) {
303				np = STAILQ_FIRST(&harvestfifo[i].head);
304				STAILQ_REMOVE_HEAD(&harvestfifo[i].head, next);
305				free(np, M_ENTROPY);
306			}
307			mtx_destroy(&harvestfifo[i].lock);
308		}
309
310		random_deinit();
311
312		destroy_dev(random_dev);
313		return 0;
314
315	case MOD_SHUTDOWN:
316		return 0;
317
318	default:
319		return EOPNOTSUPP;
320	}
321}
322
323DEV_MODULE(random, random_modevent, NULL);
324
325/* ARGSUSED */
326static void
327random_kthread(void *arg __unused)
328{
329	struct harvest	*event = NULL;
330	int		found, active;
331	enum esource	source;
332
333	/* Process until told to stop */
334	for (; random_kthread_control == 0;) {
335
336		active = 0;
337
338		/* Cycle through all the entropy sources */
339		for (source = 0; source < ENTROPYSOURCE; source++) {
340
341			found = 0;
342
343			/* Lock up queue draining */
344			mtx_lock_spin(&harvestfifo[source].lock);
345
346			if (!STAILQ_EMPTY(&harvestfifo[source].head)) {
347
348				/* Get a harvested entropy event */
349				harvestfifo[source].count--;
350				event = STAILQ_FIRST(&harvestfifo[source].head);
351				STAILQ_REMOVE_HEAD(&harvestfifo[source].head,
352					next);
353
354				active = found = 1;
355
356			}
357
358			/* Unlock the queue */
359			mtx_unlock_spin(&harvestfifo[source].lock);
360
361			/* Deal with the event and dispose of it */
362			if (found) {
363
364				random_process_event(event);
365
366				/* Lock the empty event buffer fifo */
367				mtx_lock_spin(&emptyfifo.lock);
368
369				STAILQ_INSERT_TAIL(&emptyfifo.head, event, next);
370
371				mtx_unlock_spin(&emptyfifo.lock);
372
373			}
374
375		}
376
377		/* Found nothing, so don't belabour the issue */
378		if (!active)
379			tsleep(&harvestfifo, PUSER, "-", hz/10);
380
381	}
382
383	random_set_wakeup_exit(&random_kthread_control);
384	/* NOTREACHED */
385}
386
387/* Entropy harvesting routine. This is supposed to be fast; do
388 * not do anything slow in here!
389 */
390static void
391random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
392	u_int bits, u_int frac, enum esource origin)
393{
394	struct harvest	*event;
395
396	/* Lock the particular fifo */
397	mtx_lock_spin(&harvestfifo[origin].lock);
398
399	/* Don't make the harvest queues too big - help to prevent
400	 * low-grade entropy swamping
401	 */
402	if (harvestfifo[origin].count < RANDOM_FIFO_MAX) {
403
404		/* Lock the empty event buffer fifo */
405		mtx_lock_spin(&emptyfifo.lock);
406
407		if (!STAILQ_EMPTY(&emptyfifo.head)) {
408			event = STAILQ_FIRST(&emptyfifo.head);
409			STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
410		}
411		else
412			event = NULL;
413
414		mtx_unlock_spin(&emptyfifo.lock);
415
416		/* If we didn't obtain a buffer, tough */
417		if (event) {
418
419			/* Add the harvested data to the fifo */
420			harvestfifo[origin].count++;
421			event->somecounter = somecounter;
422			event->size = count;
423			event->bits = bits;
424			event->frac = frac;
425			event->source = origin;
426
427			/* XXXX Come back and make this dynamic! */
428			count = count > HARVESTSIZE ? HARVESTSIZE : count;
429			memcpy(event->entropy, entropy, count);
430
431			STAILQ_INSERT_TAIL(&harvestfifo[origin].head, event, next);
432		}
433
434	}
435
436	mtx_unlock_spin(&harvestfifo[origin].lock);
437
438}
439
440static void
441random_write_internal(void *buf, int count)
442{
443	int	i;
444	u_int	chunk;
445
446	/* Break the input up into HARVESTSIZE chunks.
447	 * The writer has too much control here, so "estimate" the
448	 * the entropy as zero.
449	 */
450	for (i = 0; i < count; i += HARVESTSIZE) {
451		chunk = HARVESTSIZE;
452		if (i + chunk >= count)
453			chunk = (u_int)(count - i);
454		random_harvest_internal(get_cyclecount(), (char *)buf + i,
455			chunk, 0, 0, RANDOM_WRITE);
456	}
457}
458
459void
460random_unblock(void)
461{
462	if (!random_systat.seeded) {
463		random_systat.seeded = 1;
464		selwakeuppri(&random_systat.rsel, PUSER);
465		wakeup(&random_systat);
466	}
467}
468