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