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