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