randomdev.c revision 74810
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 74810 2001-03-26 12:41:29Z phk $
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};
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	switch (cmd) {
205	/* Really handled in upper layer */
206	case FIOASYNC:
207	case FIONBIO:
208		return 0;
209	default:
210		return ENOTTY;
211	}
212}
213
214static int
215random_poll(dev_t dev, int events, struct proc *p)
216{
217	int	revents;
218
219	revents = 0;
220	if (events & (POLLIN | POLLRDNORM)) {
221		if (random_systat.seeded)
222			revents = events & (POLLIN | POLLRDNORM);
223		else
224			selrecord(p, &random_systat.rsel);
225	}
226	return revents;
227}
228
229static int
230random_modevent(module_t mod, int type, void *data)
231{
232	int	error;
233
234	switch(type) {
235	case MOD_LOAD:
236		random_init();
237
238		/* This can be turned off by the very paranoid
239		 * a reseed will turn it back on.
240		 */
241		random_systat.seeded = 1;
242
243		/* Number of envents to process off the harvest
244		 * queue before giving it a break and sleeping
245		 */
246		random_systat.burst = 20;
247
248		/* Initialise the harvest ringbuffer */
249		harvestring.head = 0;
250		harvestring.tail = 0;
251
252		if (bootverbose)
253			printf("random: <entropy source>\n");
254		random_dev = make_dev(&random_cdevsw, RANDOM_MINOR, UID_ROOT,
255			GID_WHEEL, 0666, "random");
256		urandom_dev = make_dev_alias(random_dev, "urandom");
257
258		/* Start the hash/reseed thread */
259		error = kthread_create(random_kthread, NULL,
260			&random_kthread_proc, RFHIGHPID, "random");
261		if (error != 0)
262			return error;
263
264		/* Register the randomness harvesting routine */
265		random_init_harvester(random_harvest_internal,
266			read_random_real);
267
268		return 0;
269
270	case MOD_UNLOAD:
271		/* Deregister the randomness harvesting routine */
272		random_deinit_harvester();
273
274		/* Command the hash/reseed thread to end and
275		 * wait for it to finish
276		 */
277		random_kthread_control = -1;
278		tsleep((void *)&random_kthread_control, PUSER, "term", 0);
279
280		random_deinit();
281
282		destroy_dev(random_dev);
283		destroy_dev(urandom_dev);
284		return 0;
285
286	case MOD_SHUTDOWN:
287		return 0;
288
289	default:
290		return EOPNOTSUPP;
291	}
292}
293
294DEV_MODULE(random, random_modevent, NULL);
295
296static void
297random_kthread(void *arg /* NOTUSED */)
298{
299	struct harvest	*event;
300	int		newtail, burst;
301
302	/* Drain the harvest queue (in 'burst' size chunks,
303	 * if 'burst' > 0. If 'burst' == 0, then completely
304	 * drain the queue.
305	 */
306	for (burst = 0; ; burst++) {
307
308		if ((harvestring.tail == harvestring.head) ||
309			(random_systat.burst && burst == random_systat.burst)) {
310				tsleep(&harvestring, PUSER, "sleep", hz/10);
311				burst = 0;
312
313		}
314		else {
315
316			/* Suck a harvested entropy event out of the queue and
317			 * hand it to the event processor
318			 */
319
320			newtail = (harvestring.tail + 1) & HARVEST_RING_MASK;
321			event = &harvestring.data[harvestring.tail];
322
323			/* Bump the ring counter. This action is assumed
324			 * to be atomic.
325			 */
326			harvestring.tail = newtail;
327
328			random_process_event(event);
329
330		}
331
332		/* Is the thread scheduled for a shutdown? */
333		if (random_kthread_control != 0) {
334#ifdef DEBUG
335			mtx_lock(&Giant);
336			printf("Random kthread setting terminate\n");
337			mtx_unlock(&Giant);
338#endif
339			random_set_wakeup_exit(&random_kthread_control);
340			/* NOTREACHED */
341			break;
342		}
343
344	}
345
346}
347
348/* Entropy harvesting routine. This is supposed to be fast; do
349 * not do anything slow in here!
350 */
351static void
352random_harvest_internal(u_int64_t somecounter, void *entropy, u_int count,
353	u_int bits, u_int frac, enum esource origin)
354{
355	struct harvest	*harvest;
356	int		newhead;
357
358	newhead = (harvestring.head + 1) & HARVEST_RING_MASK;
359
360	if (newhead != harvestring.tail) {
361
362		/* Add the harvested data to the ring buffer */
363
364		harvest = &harvestring.data[harvestring.head];
365
366		/* Stuff the harvested data into the ring */
367		harvest->somecounter = somecounter;
368		count = count > HARVESTSIZE ? HARVESTSIZE : count;
369		memcpy(harvest->entropy, entropy, count);
370		harvest->size = count;
371		harvest->bits = bits;
372		harvest->frac = frac;
373		harvest->source = origin < ENTROPYSOURCE ? origin : 0;
374
375		/* Bump the ring counter. This action is assumed
376		 * to be atomic.
377		 */
378		harvestring.head = newhead;
379
380	}
381
382}
383
384static void
385random_write_internal(void *buf, u_int count)
386{
387	u_int	i;
388
389	/* Break the input up into HARVESTSIZE chunks.
390	 * The writer has too much control here, so "estimate" the
391	 * the entropy as zero.
392	 */
393	for (i = 0; i < count; i += HARVESTSIZE) {
394		random_harvest_internal(get_cyclecount(), (char *)buf + i,
395			HARVESTSIZE, 0, 0, RANDOM_WRITE);
396	}
397
398	/* Maybe the loop iterated at least once */
399	if (i > count)
400		i -= HARVESTSIZE;
401
402	/* Get the last bytes even if the input length is not
403	 * a multiple of HARVESTSIZE.
404	 */
405	count %= HARVESTSIZE;
406	if (count) {
407		random_harvest_internal(get_cyclecount(), (char *)buf + i,
408			count, 0, 0, RANDOM_WRITE);
409	}
410}
411
412void
413random_unblock(void)
414{
415	if (!random_systat.seeded) {
416		random_systat.seeded = 1;
417		selwakeup(&random_systat.rsel);
418		wakeup(&random_systat);
419	}
420}
421