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