randomdev.c revision 74771
1/*-
2 * Copyright (c) 2000 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 * $FreeBSD: head/sys/dev/random/randomdev.c 74771 2001-03-25 06:55:19Z markm $
27 */
28
29#include <sys/param.h>
30#include <sys/queue.h>
31#include <sys/systm.h>
32#include <sys/conf.h>
33#include <sys/filio.h>
34#include <sys/fcntl.h>
35#include <sys/uio.h>
36#include <sys/kernel.h>
37#include <sys/kthread.h>
38#include <sys/malloc.h>
39#include <sys/module.h>
40#include <sys/bus.h>
41#include <sys/poll.h>
42#include <sys/selinfo.h>
43#include <sys/random.h>
44#include <sys/sysctl.h>
45#include <sys/vnode.h>
46#include <sys/unistd.h>
47
48#include <machine/bus.h>
49#include <machine/cpu.h>
50#include <machine/resource.h>
51
52#include <dev/random/randomdev.h>
53
54static d_open_t		random_open;
55static d_close_t	random_close;
56static d_read_t		random_read;
57static d_write_t	random_write;
58static d_ioctl_t	random_ioctl;
59static d_poll_t		random_poll;
60
61#define CDEV_MAJOR	2
62#define RANDOM_MINOR	3
63
64static struct cdevsw random_cdevsw = {
65	/* open */	random_open,
66	/* close */	random_close,
67	/* read */	random_read,
68	/* write */	random_write,
69	/* ioctl */	random_ioctl,
70	/* poll */	random_poll,
71	/* mmap */	nommap,
72	/* strategy */	nostrategy,
73	/* name */	"random",
74	/* maj */	CDEV_MAJOR,
75	/* dump */	nodump,
76	/* psize */	nopsize,
77	/* flags */	0,
78	/* bmaj */	-1
79};
80
81static void random_kthread(void *);
82static void random_harvest_internal(u_int64_t, void *, u_int, u_int, u_int, enum esource);
83static void random_write_internal(void *, u_int);
84
85/* Ring buffer holding harvested entropy */
86static struct harvestring {
87	volatile u_int	head;
88	volatile u_int	tail;
89	struct harvest	data[HARVEST_RING_SIZE];
90} harvestring;
91
92static struct random_systat {
93	u_int		seeded;	/* 0 causes blocking 1 allows normal output */
94	u_int		burst;	/* number of events to do before sleeping */
95	struct selinfo	rsel;	/* For poll(2) */
96} random_systat;
97
98/* <0 to end the kthread, 0 to let it run */
99static int random_kthread_control = 0;
100
101static struct proc *random_kthread_proc;
102
103/* For use with make_dev(9)/destroy_dev(9). */
104static dev_t	random_dev;
105static dev_t	urandom_dev;
106
107static int
108random_check_boolean(SYSCTL_HANDLER_ARGS)
109{
110	if (oidp->oid_arg1 != NULL && *(u_int *)(oidp->oid_arg1) != 0)
111		*(u_int *)(oidp->oid_arg1) = 1;
112        return sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
113}
114
115RANDOM_CHECK_UINT(burst, 0, 20);
116
117SYSCTL_NODE(_kern, OID_AUTO, random, CTLFLAG_RW,
118	0, "Random Number Generator");
119SYSCTL_NODE(_kern_random, OID_AUTO, sys, CTLFLAG_RW,
120	0, "Entropy Device Parameters");
121SYSCTL_PROC(_kern_random_sys, OID_AUTO, seeded,
122	CTLTYPE_INT|CTLFLAG_RW, &random_systat.seeded, 1,
123	random_check_boolean, "I", "Seeded State");
124SYSCTL_PROC(_kern_random_sys, OID_AUTO, burst,
125	CTLTYPE_INT|CTLFLAG_RW, &random_systat.burst, 20,
126	random_check_uint_burst, "I", "Harvest Burst Size");
127SYSCTL_NODE(_kern_random_sys, OID_AUTO, harvest, CTLFLAG_RW,
128	0, "Entropy Sources");
129SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, ethernet,
130	CTLTYPE_INT|CTLFLAG_RW, &harvest.ethernet, 0,
131	random_check_boolean, "I", "Harvest NIC entropy");
132SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, point_to_point,
133	CTLTYPE_INT|CTLFLAG_RW, &harvest.point_to_point, 0,
134	random_check_boolean, "I", "Harvest serial net entropy");
135SYSCTL_PROC(_kern_random_sys_harvest, OID_AUTO, interrupt,
136	CTLTYPE_INT|CTLFLAG_RW, &harvest.interrupt, 0,
137	random_check_boolean, "I", "Harvest IRQ entropy");
138
139static int
140random_open(dev_t dev, int flags, int fmt, struct proc *p)
141{
142	if ((flags & FWRITE) && (securelevel > 0 || suser(p)))
143		return EPERM;
144	else
145		return 0;
146}
147
148static int
149random_close(dev_t dev, int flags, int fmt, struct proc *p)
150{
151	if ((flags & FWRITE) && !(securelevel > 0 || suser(p)))
152		random_reseed();
153	return 0;
154}
155
156static int
157random_read(dev_t dev, struct uio *uio, int flag)
158{
159	u_int	c, ret;
160	int	error = 0;
161	void	*random_buf;
162
163	while (!random_systat.seeded) {
164		if (flag & IO_NDELAY)
165			error =  EWOULDBLOCK;
166		else
167			error = tsleep(&random_systat, PUSER|PCATCH,
168				"block", 0);
169		if (error != 0)
170			return error;
171	}
172	c = min(uio->uio_resid, PAGE_SIZE);
173	random_buf = (void *)malloc(c, M_TEMP, M_WAITOK);
174	while (uio->uio_resid > 0 && error == 0) {
175		ret = read_random_real(random_buf, c);
176		error = uiomove(random_buf, ret, uio);
177	}
178	free(random_buf, M_TEMP);
179	return error;
180}
181
182static int
183random_write(dev_t dev, struct uio *uio, int flag)
184{
185	u_int	c;
186	int	error;
187	void	*random_buf;
188
189	error = 0;
190	random_buf = (void *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
191	while (uio->uio_resid > 0) {
192		c = min(uio->uio_resid, 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
202static int
203random_ioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
204{
205	switch (cmd) {
206	/* Really handled in upper layer */
207	case FIOASYNC:
208	case FIONBIO:
209		return 0;
210	default:
211		return ENOTTY;
212	}
213}
214
215static int
216random_poll(dev_t dev, int events, struct proc *p)
217{
218	int	revents;
219
220	revents = 0;
221	if (events & (POLLIN | POLLRDNORM)) {
222		if (random_systat.seeded)
223			revents = events & (POLLIN | POLLRDNORM);
224		else
225			selrecord(p, &random_systat.rsel);
226	}
227	return revents;
228}
229
230static int
231random_modevent(module_t mod, int type, void *data)
232{
233	int	error;
234
235	switch(type) {
236	case MOD_LOAD:
237		random_init();
238
239		/* This can be turned off by the very paranoid
240		 * a reseed will turn it back on.
241		 */
242		random_systat.seeded = 1;
243
244		/* Number of envents to process off the harvest
245		 * queue before giving it a break and sleeping
246		 */
247		random_systat.burst = 20;
248
249		/* Initialise the harvest ringbuffer */
250		harvestring.head = 0;
251		harvestring.tail = 0;
252
253		if (bootverbose)
254			printf("random: <entropy source>\n");
255		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
256			GID_WHEEL, 0666, "random");
257		urandom_dev = make_dev_alias(random_dev, "urandom");
258
259		/* Start the hash/reseed thread */
260		error = kthread_create(random_kthread, NULL,
261			&random_kthread_proc, RFHIGHPID, "random");
262		if (error != 0)
263			return error;
264
265		/* Register the randomness harvesting routine */
266		random_init_harvester(random_harvest_internal,
267			read_random_real);
268
269		return 0;
270
271	case MOD_UNLOAD:
272		/* Deregister the randomness harvesting routine */
273		random_deinit_harvester();
274
275		/* Command the hash/reseed thread to end and
276		 * wait for it to finish
277		 */
278		random_kthread_control = -1;
279		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
280
281		random_deinit();
282
283		destroy_dev(random_dev);
284		destroy_dev(urandom_dev);
285		return 0;
286
287	case MOD_SHUTDOWN:
288		return 0;
289
290	default:
291		return EOPNOTSUPP;
292	}
293}
294
295DEV_MODULE(random, random_modevent, NULL);
296
297static void
298random_kthread(void *arg /* NOTUSED */)
299{
300	struct harvest	*event;
301	int		newtail, burst;
302
303	/* Drain the harvest queue (in 'burst' size chunks,
304	 * if 'burst' > 0. If 'burst' == 0, then completely
305	 * drain the queue.
306	 */
307	for (burst = 0; ; burst++) {
308
309		if ((harvestring.tail == harvestring.head) ||
310			(random_systat.burst && burst == random_systat.burst)) {
311				tsleep(&harvestring, PUSER, "sleep", hz/10);
312				burst = 0;
313
314		}
315		else {
316
317			/* Suck a harvested entropy event out of the queue and
318			 * hand it to the event processor
319			 */
320
321			newtail = (harvestring.tail + 1) & HARVEST_RING_MASK;
322			event = &harvestring.data[harvestring.tail];
323
324			/* Bump the ring counter. This action is assumed
325			 * to be atomic.
326			 */
327			harvestring.tail = newtail;
328
329			random_process_event(event);
330
331		}
332
333		/* Is the thread scheduled for a shutdown? */
334		if (random_kthread_control != 0) {
335#ifdef DEBUG
336			mtx_lock(&Giant);
337			printf("Random kthread setting terminate\n");
338			mtx_unlock(&Giant);
339#endif
340			random_set_wakeup_exit(&random_kthread_control);
341			/* NOTREACHED */
342			break;
343		}
344
345	}
346
347}
348
349/* Entropy harvesting routine. This is supposed to be fast; do
350 * not do anything slow in here!
351 */
352static void
353random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
354	u_int bits, u_int frac, enum esource origin)
355{
356	struct harvest	*harvest;
357	int		newhead;
358
359	newhead = (harvestring.head + 1) & HARVEST_RING_MASK;
360
361	if (newhead != harvestring.tail) {
362
363		/* Add the harvested data to the ring buffer */
364
365		harvest = &harvestring.data[harvestring.head];
366
367		/* Stuff the harvested data into the ring */
368		harvest->somecounter = somecounter;
369		count = count > HARVESTSIZE ? HARVESTSIZE : count;
370		memcpy(harvest->entropy, entropy, count);
371		harvest->size = count;
372		harvest->bits = bits;
373		harvest->frac = frac;
374		harvest->source = origin < ENTROPYSOURCE ? origin : 0;
375
376		/* Bump the ring counter. This action is assumed
377		 * to be atomic.
378		 */
379		harvestring.head = newhead;
380
381	}
382
383}
384
385static void
386random_write_internal(void *buf, u_int count)
387{
388	u_int	i;
389
390	/* Break the input up into HARVESTSIZE chunks.
391	 * The writer has too much control here, so "estimate" the
392	 * the entropy as zero.
393	 */
394	for (i = 0; i < count; i += HARVESTSIZE) {
395		random_harvest_internal(get_cyclecount(), (char *)buf + i,
396			HARVESTSIZE, 0, 0, RANDOM_WRITE);
397	}
398
399	/* Maybe the loop iterated at least once */
400	if (i > count)
401		i -= HARVESTSIZE;
402
403	/* Get the last bytes even if the input length is not
404	 * a multiple of HARVESTSIZE.
405	 */
406	count %= HARVESTSIZE;
407	if (count) {
408		random_harvest_internal(get_cyclecount(), (char *)buf + i,
409			count, 0, 0, RANDOM_WRITE);
410	}
411}
412
413void
414random_unblock(void)
415{
416	if (!random_systat.seeded) {
417		random_systat.seeded = 1;
418		selwakeup(&random_systat.rsel);
419		wakeup(&random_systat);
420	}
421}
422