File: /usr/src/linux/drivers/char/random.c

1     /*
2      * random.c -- A strong random number generator
3      *
4      * Version 1.89, last modified 19-Sep-99
5      * 
6      * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
7      * rights reserved.
8      *
9      * Redistribution and use in source and binary forms, with or without
10      * modification, are permitted provided that the following conditions
11      * are met:
12      * 1. Redistributions of source code must retain the above copyright
13      *    notice, and the entire permission notice in its entirety,
14      *    including the disclaimer of warranties.
15      * 2. Redistributions in binary form must reproduce the above copyright
16      *    notice, this list of conditions and the following disclaimer in the
17      *    documentation and/or other materials provided with the distribution.
18      * 3. The name of the author may not be used to endorse or promote
19      *    products derived from this software without specific prior
20      *    written permission.
21      * 
22      * ALTERNATIVELY, this product may be distributed under the terms of
23      * the GNU General Public License, in which case the provisions of the GPL are
24      * required INSTEAD OF the above restrictions.  (This clause is
25      * necessary due to a potential bad interaction between the GPL and
26      * the restrictions contained in a BSD-style copyright.)
27      * 
28      * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
29      * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30      * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
31      * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
32      * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33      * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34      * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35      * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36      * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37      * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38      * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
39      * DAMAGE.
40      */
41     
42     /*
43      * (now, with legal B.S. out of the way.....) 
44      * 
45      * This routine gathers environmental noise from device drivers, etc.,
46      * and returns good random numbers, suitable for cryptographic use.
47      * Besides the obvious cryptographic uses, these numbers are also good
48      * for seeding TCP sequence numbers, and other places where it is
49      * desirable to have numbers which are not only random, but hard to
50      * predict by an attacker.
51      *
52      * Theory of operation
53      * ===================
54      * 
55      * Computers are very predictable devices.  Hence it is extremely hard
56      * to produce truly random numbers on a computer --- as opposed to
57      * pseudo-random numbers, which can easily generated by using a
58      * algorithm.  Unfortunately, it is very easy for attackers to guess
59      * the sequence of pseudo-random number generators, and for some
60      * applications this is not acceptable.  So instead, we must try to
61      * gather "environmental noise" from the computer's environment, which
62      * must be hard for outside attackers to observe, and use that to
63      * generate random numbers.  In a Unix environment, this is best done
64      * from inside the kernel.
65      * 
66      * Sources of randomness from the environment include inter-keyboard
67      * timings, inter-interrupt timings from some interrupts, and other
68      * events which are both (a) non-deterministic and (b) hard for an
69      * outside observer to measure.  Randomness from these sources are
70      * added to an "entropy pool", which is mixed using a CRC-like function.
71      * This is not cryptographically strong, but it is adequate assuming
72      * the randomness is not chosen maliciously, and it is fast enough that
73      * the overhead of doing it on every interrupt is very reasonable.
74      * As random bytes are mixed into the entropy pool, the routines keep
75      * an *estimate* of how many bits of randomness have been stored into
76      * the random number generator's internal state.
77      * 
78      * When random bytes are desired, they are obtained by taking the SHA
79      * hash of the contents of the "entropy pool".  The SHA hash avoids
80      * exposing the internal state of the entropy pool.  It is believed to
81      * be computationally infeasible to derive any useful information
82      * about the input of SHA from its output.  Even if it is possible to
83      * analyze SHA in some clever way, as long as the amount of data
84      * returned from the generator is less than the inherent entropy in
85      * the pool, the output data is totally unpredictable.  For this
86      * reason, the routine decreases its internal estimate of how many
87      * bits of "true randomness" are contained in the entropy pool as it
88      * outputs random numbers.
89      * 
90      * If this estimate goes to zero, the routine can still generate
91      * random numbers; however, an attacker may (at least in theory) be
92      * able to infer the future output of the generator from prior
93      * outputs.  This requires successful cryptanalysis of SHA, which is
94      * not believed to be feasible, but there is a remote possibility.
95      * Nonetheless, these numbers should be useful for the vast majority
96      * of purposes.
97      * 
98      * Exported interfaces ---- output
99      * ===============================
100      * 
101      * There are three exported interfaces; the first is one designed to
102      * be used from within the kernel:
103      *
104      * 	void get_random_bytes(void *buf, int nbytes);
105      *
106      * This interface will return the requested number of random bytes,
107      * and place it in the requested buffer.
108      * 
109      * The two other interfaces are two character devices /dev/random and
110      * /dev/urandom.  /dev/random is suitable for use when very high
111      * quality randomness is desired (for example, for key generation or
112      * one-time pads), as it will only return a maximum of the number of
113      * bits of randomness (as estimated by the random number generator)
114      * contained in the entropy pool.
115      * 
116      * The /dev/urandom device does not have this limit, and will return
117      * as many bytes as are requested.  As more and more random bytes are
118      * requested without giving time for the entropy pool to recharge,
119      * this will result in random numbers that are merely cryptographically
120      * strong.  For many applications, however, this is acceptable.
121      *
122      * Exported interfaces ---- input
123      * ==============================
124      * 
125      * The current exported interfaces for gathering environmental noise
126      * from the devices are:
127      * 
128      * 	void add_keyboard_randomness(unsigned char scancode);
129      * 	void add_mouse_randomness(__u32 mouse_data);
130      * 	void add_interrupt_randomness(int irq);
131      * 	void add_blkdev_randomness(int irq);
132      * 
133      * add_keyboard_randomness() uses the inter-keypress timing, as well as the
134      * scancode as random inputs into the "entropy pool".
135      * 
136      * add_mouse_randomness() uses the mouse interrupt timing, as well as
137      * the reported position of the mouse from the hardware.
138      *
139      * add_interrupt_randomness() uses the inter-interrupt timing as random
140      * inputs to the entropy pool.  Note that not all interrupts are good
141      * sources of randomness!  For example, the timer interrupts is not a
142      * good choice, because the periodicity of the interrupts is too
143      * regular, and hence predictable to an attacker.  Disk interrupts are
144      * a better measure, since the timing of the disk interrupts are more
145      * unpredictable.
146      * 
147      * add_blkdev_randomness() times the finishing time of block requests.
148      * 
149      * All of these routines try to estimate how many bits of randomness a
150      * particular randomness source.  They do this by keeping track of the
151      * first and second order deltas of the event timings.
152      *
153      * Ensuring unpredictability at system startup
154      * ============================================
155      * 
156      * When any operating system starts up, it will go through a sequence
157      * of actions that are fairly predictable by an adversary, especially
158      * if the start-up does not involve interaction with a human operator.
159      * This reduces the actual number of bits of unpredictability in the
160      * entropy pool below the value in entropy_count.  In order to
161      * counteract this effect, it helps to carry information in the
162      * entropy pool across shut-downs and start-ups.  To do this, put the
163      * following lines an appropriate script which is run during the boot
164      * sequence: 
165      *
166      *	echo "Initializing random number generator..."
167      * 	random_seed=/var/run/random-seed
168      *	# Carry a random seed from start-up to start-up
169      *	# Load and then save 512 bytes, which is the size of the entropy pool
170      * 	if [ -f $random_seed ]; then
171      *		cat $random_seed >/dev/urandom
172      * 	fi
173      *	dd if=/dev/urandom of=$random_seed count=1
174      * 	chmod 600 $random_seed
175      *
176      * and the following lines in an appropriate script which is run as
177      * the system is shutdown:
178      * 
179      *	# Carry a random seed from shut-down to start-up
180      *	# Save 512 bytes, which is the size of the entropy pool
181      *	echo "Saving random seed..."
182      * 	random_seed=/var/run/random-seed
183      *	dd if=/dev/urandom of=$random_seed count=1
184      * 	chmod 600 $random_seed
185      * 
186      * For example, on most modern systems using the System V init
187      * scripts, such code fragments would be found in
188      * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
189      * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
190      * 
191      * Effectively, these commands cause the contents of the entropy pool
192      * to be saved at shut-down time and reloaded into the entropy pool at
193      * start-up.  (The 'dd' in the addition to the bootup script is to
194      * make sure that /etc/random-seed is different for every start-up,
195      * even if the system crashes without executing rc.0.)  Even with
196      * complete knowledge of the start-up activities, predicting the state
197      * of the entropy pool requires knowledge of the previous history of
198      * the system.
199      *
200      * Configuring the /dev/random driver under Linux
201      * ==============================================
202      *
203      * The /dev/random driver under Linux uses minor numbers 8 and 9 of
204      * the /dev/mem major number (#1).  So if your system does not have
205      * /dev/random and /dev/urandom created already, they can be created
206      * by using the commands:
207      *
208      * 	mknod /dev/random c 1 8
209      * 	mknod /dev/urandom c 1 9
210      * 
211      * Acknowledgements:
212      * =================
213      *
214      * Ideas for constructing this random number generator were derived
215      * from Pretty Good Privacy's random number generator, and from private
216      * discussions with Phil Karn.  Colin Plumb provided a faster random
217      * number generator, which speed up the mixing function of the entropy
218      * pool, taken from PGPfone.  Dale Worley has also contributed many
219      * useful ideas and suggestions to improve this driver.
220      * 
221      * Any flaws in the design are solely my responsibility, and should
222      * not be attributed to the Phil, Colin, or any of authors of PGP.
223      * 
224      * The code for SHA transform was taken from Peter Gutmann's
225      * implementation, which has been placed in the public domain.
226      * The code for MD5 transform was taken from Colin Plumb's
227      * implementation, which has been placed in the public domain.
228      * The MD5 cryptographic checksum was devised by Ronald Rivest, and is
229      * documented in RFC 1321, "The MD5 Message Digest Algorithm".
230      * 
231      * Further background information on this topic may be obtained from
232      * RFC 1750, "Randomness Recommendations for Security", by Donald
233      * Eastlake, Steve Crocker, and Jeff Schiller.
234      */
235     
236     #include <linux/utsname.h>
237     #include <linux/config.h>
238     #include <linux/module.h>
239     #include <linux/kernel.h>
240     #include <linux/major.h>
241     #include <linux/string.h>
242     #include <linux/fcntl.h>
243     #include <linux/slab.h>
244     #include <linux/random.h>
245     #include <linux/poll.h>
246     #include <linux/init.h>
247     
248     #include <asm/processor.h>
249     #include <asm/uaccess.h>
250     #include <asm/irq.h>
251     #include <asm/io.h>
252     
253     /*
254      * Configuration information
255      */
256     #define DEFAULT_POOL_SIZE 512
257     #define SECONDARY_POOL_SIZE 128
258     #define BATCH_ENTROPY_SIZE 256
259     #define USE_SHA
260     
261     /*
262      * The minimum number of bits of entropy before we wake up a read on
263      * /dev/random.  Should always be at least 8, or at least 1 byte.
264      */
265     static int random_read_wakeup_thresh = 8;
266     
267     /*
268      * If the entropy count falls under this number of bits, then we
269      * should wake up processes which are selecting or polling on write
270      * access to /dev/random.
271      */
272     static int random_write_wakeup_thresh = 128;
273     
274     /*
275      * A pool of size POOLWORDS is stirred with a primitive polynomial
276      * of degree POOLWORDS over GF(2).  The taps for various sizes are
277      * defined below.  They are chosen to be evenly spaced (minimum RMS
278      * distance from evenly spaced; the numbers in the comments are a
279      * scaled squared error sum) except for the last tap, which is 1 to
280      * get the twisting happening as fast as possible.
281      */
282     static struct poolinfo {
283     	int	poolwords;
284     	int	tap1, tap2, tap3, tap4, tap5;
285     } poolinfo_table[] = {
286     	/* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
287     	{ 2048,	1638,	1231,	819, 	411,	1 },
288     
289     	/* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
290     	{ 1024,	817, 	615,	412,	204,	1 },
291     
292     #if 0				/* Alternate polynomial */
293     	/* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
294     	{ 1024,	819,	616,	410,	207,	2 },
295     #endif
296     	
297     	/* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
298     	{ 512,	411,	308,	208,	104,	1 },
299     
300     #if 0				/* Alternates */
301     	/* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
302     	{ 512,	409,	307,	206,	102,	2 },
303     	/* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
304     	{ 512,	409,	309,	205,	103,	2 },
305     #endif
306     
307     	/* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
308     	{ 256,	205,	155,	101,	52,	1 },
309     	
310     	/* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
311     	{ 128,	103,	76,	51,	25,	1 },
312     
313     #if 0	/* Alternate polynomial */
314     	/* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
315     	{ 128,	103,	78,	51,	27,	2 },
316     #endif
317     
318     	/* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
319     	{ 64,	52,	39,	26,	14,	1 },
320     
321     	/* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
322     	{ 32,	26,	20,	14,	7,	1 },
323     
324     	{ 0, 	0,	0,	0,	0,	0 },
325     };		
326     	
327     /*
328      * For the purposes of better mixing, we use the CRC-32 polynomial as
329      * well to make a twisted Generalized Feedback Shift Reigster
330      *
331      * (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR generators.  ACM
332      * Transactions on Modeling and Computer Simulation 2(3):179-194.
333      * Also see M. Matsumoto & Y. Kurita, 1994.  Twisted GFSR generators
334      * II.  ACM Transactions on Mdeling and Computer Simulation 4:254-266)
335      *
336      * Thanks to Colin Plumb for suggesting this.
337      * 
338      * We have not analyzed the resultant polynomial to prove it primitive;
339      * in fact it almost certainly isn't.  Nonetheless, the irreducible factors
340      * of a random large-degree polynomial over GF(2) are more than large enough
341      * that periodicity is not a concern.
342      * 
343      * The input hash is much less sensitive than the output hash.  All
344      * that we want of it is that it be a good non-cryptographic hash;
345      * i.e. it not produce collisions when fed "random" data of the sort
346      * we expect to see.  As long as the pool state differs for different
347      * inputs, we have preserved the input entropy and done a good job.
348      * The fact that an intelligent attacker can construct inputs that
349      * will produce controlled alterations to the pool's state is not
350      * important because we don't consider such inputs to contribute any
351      * randomness.  The only property we need with respect to them is that
352      * the attacker can't increase his/her knowledge of the pool's state.
353      * Since all additions are reversible (knowing the final state and the
354      * input, you can reconstruct the initial state), if an attacker has
355      * any uncertainty about the initial state, he/she can only shuffle
356      * that uncertainty about, but never cause any collisions (which would
357      * decrease the uncertainty).
358      *
359      * The chosen system lets the state of the pool be (essentially) the input
360      * modulo the generator polymnomial.  Now, for random primitive polynomials,
361      * this is a universal class of hash functions, meaning that the chance
362      * of a collision is limited by the attacker's knowledge of the generator
363      * polynomail, so if it is chosen at random, an attacker can never force
364      * a collision.  Here, we use a fixed polynomial, but we *can* assume that
365      * ###--> it is unknown to the processes generating the input entropy. <-###
366      * Because of this important property, this is a good, collision-resistant
367      * hash; hash collisions will occur no more often than chance.
368      */
369     
370     /*
371      * Linux 2.2 compatibility
372      */
373     #ifndef DECLARE_WAITQUEUE
374     #define DECLARE_WAITQUEUE(WAIT, PTR)	struct wait_queue WAIT = { PTR, NULL }
375     #endif
376     #ifndef DECLARE_WAIT_QUEUE_HEAD
377     #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
378     #endif
379     
380     /*
381      * Static global variables
382      */
383     static struct entropy_store *random_state; /* The default global store */
384     static struct entropy_store *sec_random_state; /* secondary store */
385     static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
386     static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
387     
388     /*
389      * Forward procedure declarations
390      */
391     #ifdef CONFIG_SYSCTL
392     static void sysctl_init_random(struct entropy_store *random_state);
393     #endif
394     
395     /*****************************************************************
396      *
397      * Utility functions, with some ASM defined functions for speed
398      * purposes
399      * 
400      *****************************************************************/
401     
402     #ifndef MIN
403     #define MIN(a,b) (((a) < (b)) ? (a) : (b))
404     #endif
405     
406     /*
407      * Unfortunately, while the GCC optimizer for the i386 understands how
408      * to optimize a static rotate left of x bits, it doesn't know how to
409      * deal with a variable rotate of x bits.  So we use a bit of asm magic.
410      */
411     #if (!defined (__i386__))
412     extern inline __u32 rotate_left(int i, __u32 word)
413     {
414     	return (word << i) | (word >> (32 - i));
415     	
416     }
417     #else
418     extern inline __u32 rotate_left(int i, __u32 word)
419     {
420     	__asm__("roll %%cl,%0"
421     		:"=r" (word)
422     		:"0" (word),"c" (i));
423     	return word;
424     }
425     #endif
426     
427     /*
428      * More asm magic....
429      * 
430      * For entropy estimation, we need to do an integral base 2
431      * logarithm.  
432      *
433      * Note the "12bits" suffix - this is used for numbers between
434      * 0 and 4095 only.  This allows a few shortcuts.
435      */
436     #if 0	/* Slow but clear version */
437     static inline __u32 int_ln_12bits(__u32 word)
438     {
439     	__u32 nbits = 0;
440     	
441     	while (word >>= 1)
442     		nbits++;
443     	return nbits;
444     }
445     #else	/* Faster (more clever) version, courtesy Colin Plumb */
446     static inline __u32 int_ln_12bits(__u32 word)
447     {
448     	/* Smear msbit right to make an n-bit mask */
449     	word |= word >> 8;
450     	word |= word >> 4;
451     	word |= word >> 2;
452     	word |= word >> 1;
453     	/* Remove one bit to make this a logarithm */
454     	word >>= 1;
455     	/* Count the bits set in the word */
456     	word -= (word >> 1) & 0x555;
457     	word = (word & 0x333) + ((word >> 2) & 0x333);
458     	word += (word >> 4);
459     	word += (word >> 8);
460     	return word & 15;
461     }
462     #endif
463     
464     /**********************************************************************
465      *
466      * OS independent entropy store.   Here are the functions which handle
467      * storing entropy in an entropy pool.
468      * 
469      **********************************************************************/
470     
471     struct entropy_store {
472     	unsigned	add_ptr;
473     	int		entropy_count;
474     	int		input_rotate;
475     	int		extract_count;
476     	struct poolinfo poolinfo;
477     	__u32		*pool;
478     };
479     
480     /*
481      * Initialize the entropy store.  The input argument is the size of
482      * the random pool.
483      * 
484      * Returns an negative error if there is a problem.
485      */
486     static int create_entropy_store(int size, struct entropy_store **ret_bucket)
487     {
488     	struct	entropy_store	*r;
489     	struct	poolinfo	*p;
490     	int	poolwords;
491     
492     	poolwords = (size + 3) / 4; /* Convert bytes->words */
493     	/* The pool size must be a multiple of 16 32-bit words */
494     	poolwords = ((poolwords + 15) / 16) * 16; 
495     
496     	for (p = poolinfo_table; p->poolwords; p++) {
497     		if (poolwords == p->poolwords)
498     			break;
499     	}
500     	if (p->poolwords == 0)
501     		return -EINVAL;
502     
503     	r = kmalloc(sizeof(struct entropy_store), GFP_KERNEL);
504     	if (!r)
505     		return -ENOMEM;
506     
507     	memset (r, 0, sizeof(struct entropy_store));
508     	r->poolinfo = *p;
509     
510     	r->pool = kmalloc(poolwords*4, GFP_KERNEL);
511     	if (!r->pool) {
512     		kfree(r);
513     		return -ENOMEM;
514     	}
515     	memset(r->pool, 0, poolwords*4);
516     	*ret_bucket = r;
517     	return 0;
518     }
519     
520     /* Clear the entropy pool and associated counters. */
521     static void clear_entropy_store(struct entropy_store *r)
522     {
523     	r->add_ptr = 0;
524     	r->entropy_count = 0;
525     	r->input_rotate = 0;
526     	r->extract_count = 0;
527     	memset(r->pool, 0, r->poolinfo.poolwords*4);
528     }
529     
530     static void free_entropy_store(struct entropy_store *r)
531     {
532     	if (r->pool)
533     		kfree(r->pool);
534     	kfree(r);
535     }
536     
537     /*
538      * This function adds a byte into the entropy "pool".  It does not
539      * update the entropy estimate.  The caller should call
540      * credit_entropy_store if this is appropriate.
541      * 
542      * The pool is stirred with a primitive polynomial of the appropriate
543      * degree, and then twisted.  We twist by three bits at a time because
544      * it's cheap to do so and helps slightly in the expected case where
545      * the entropy is concentrated in the low-order bits.
546      */
547     static void add_entropy_words(struct entropy_store *r, const __u32 *in,
548     			     int num)
549     {
550     	static __u32 const twist_table[8] = {
551     		         0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
552     		0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
553     	unsigned i;
554     	int new_rotate;
555     	__u32 w;
556     
557     	while (num--) {
558     		w = rotate_left(r->input_rotate, *in);
559     		i = r->add_ptr = (r->add_ptr - 1) & (r->poolinfo.poolwords-1);
560     		/*
561     		 * Normally, we add 7 bits of rotation to the pool.
562     		 * At the beginning of the pool, add an extra 7 bits
563     		 * rotation, so that successive passes spread the
564     		 * input bits across the pool evenly.
565     		 */
566     		new_rotate = r->input_rotate + 14;
567     		if (i)
568     			new_rotate = r->input_rotate + 7;
569     		r->input_rotate = new_rotate & 31;
570     
571     		/* XOR in the various taps */
572     		w ^= r->pool[(i+r->poolinfo.tap1)&(r->poolinfo.poolwords-1)];
573     		w ^= r->pool[(i+r->poolinfo.tap2)&(r->poolinfo.poolwords-1)];
574     		w ^= r->pool[(i+r->poolinfo.tap3)&(r->poolinfo.poolwords-1)];
575     		w ^= r->pool[(i+r->poolinfo.tap4)&(r->poolinfo.poolwords-1)];
576     		w ^= r->pool[(i+r->poolinfo.tap5)&(r->poolinfo.poolwords-1)];
577     		w ^= r->pool[i];
578     		r->pool[i] = (w >> 3) ^ twist_table[w & 7];
579     	}
580     }
581     
582     /*
583      * Credit (or debit) the entropy store with n bits of entropy
584      */
585     static void credit_entropy_store(struct entropy_store *r, int num)
586     {
587     	int	max_entropy = r->poolinfo.poolwords*32;
588     
589     	if (r->entropy_count + num < 0)
590     		r->entropy_count = 0;
591     	else if (r->entropy_count + num > max_entropy)
592     		r->entropy_count = max_entropy;
593     	else
594     		r->entropy_count = r->entropy_count + num;
595     }
596     
597     /**********************************************************************
598      *
599      * Entropy batch input management
600      *
601      * We batch entropy to be added to avoid increasing interrupt latency
602      *
603      **********************************************************************/
604     
605     static __u32	*batch_entropy_pool;
606     static int	*batch_entropy_credit;
607     static int	batch_max;
608     static int	batch_head, batch_tail;
609     static struct tq_struct	batch_tqueue;
610     static void batch_entropy_process(void *private_);
611     
612     /* note: the size must be a power of 2 */
613     static int __init batch_entropy_init(int size, struct entropy_store *r)
614     {
615     	batch_entropy_pool = kmalloc(2*size*sizeof(__u32), GFP_KERNEL);
616     	if (!batch_entropy_pool)
617     		return -1;
618     	batch_entropy_credit =kmalloc(size*sizeof(int), GFP_KERNEL);
619     	if (!batch_entropy_credit) {
620     		kfree(batch_entropy_pool);
621     		return -1;
622     	}
623     	batch_head = batch_tail = 0;
624     	batch_max = size;
625     	batch_tqueue.routine = batch_entropy_process;
626     	batch_tqueue.data = r;
627     	return 0;
628     }
629     
630     void batch_entropy_store(u32 a, u32 b, int num)
631     {
632     	int	new;
633     
634     	if (!batch_max)
635     		return;
636     	
637     	batch_entropy_pool[2*batch_head] = a;
638     	batch_entropy_pool[(2*batch_head) + 1] = b;
639     	batch_entropy_credit[batch_head] = num;
640     
641     	new = (batch_head+1) & (batch_max-1);
642     	if (new != batch_tail) {
643     		queue_task(&batch_tqueue, &tq_timer);
644     		batch_head = new;
645     	} else {
646     #if 0
647     		printk(KERN_NOTICE "random: batch entropy buffer full\n");
648     #endif
649     	}
650     }
651     
652     static void batch_entropy_process(void *private_)
653     {
654     	int	num = 0;
655     	int	max_entropy;
656     	struct entropy_store *r	= (struct entropy_store *) private_, *p;
657     	
658     	if (!batch_max)
659     		return;
660     
661     	max_entropy = r->poolinfo.poolwords*32;
662     	while (batch_head != batch_tail) {
663     		add_entropy_words(r, batch_entropy_pool + 2*batch_tail, 2);
664     		p = r;
665     		if (r->entropy_count > max_entropy && (num & 1))
666     			r = sec_random_state;
667     		credit_entropy_store(r, batch_entropy_credit[batch_tail]);
668     		batch_tail = (batch_tail+1) & (batch_max-1);
669     		num++;
670     	}
671     	if (r->entropy_count >= random_read_wakeup_thresh)
672     		wake_up_interruptible(&random_read_wait);
673     }
674     
675     /*********************************************************************
676      *
677      * Entropy input management
678      *
679      *********************************************************************/
680     
681     /* There is one of these per entropy source */
682     struct timer_rand_state {
683     	__u32		last_time;
684     	__s32		last_delta,last_delta2;
685     	int		dont_count_entropy:1;
686     };
687     
688     static struct timer_rand_state keyboard_timer_state;
689     static struct timer_rand_state mouse_timer_state;
690     static struct timer_rand_state extract_timer_state;
691     static struct timer_rand_state *irq_timer_state[NR_IRQS];
692     static struct timer_rand_state *blkdev_timer_state[MAX_BLKDEV];
693     
694     /*
695      * This function adds entropy to the entropy "pool" by using timing
696      * delays.  It uses the timer_rand_state structure to make an estimate
697      * of how many bits of entropy this call has added to the pool.
698      *
699      * The number "num" is also added to the pool - it should somehow describe
700      * the type of event which just happened.  This is currently 0-255 for
701      * keyboard scan codes, and 256 upwards for interrupts.
702      * On the i386, this is assumed to be at most 16 bits, and the high bits
703      * are used for a high-resolution timer.
704      *
705      */
706     static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
707     {
708     	__u32		time;
709     	__s32		delta, delta2, delta3;
710     	int		entropy = 0;
711     
712     #if defined (__i386__)
713     	if ( test_bit(X86_FEATURE_TSC, &boot_cpu_data.x86_capability) ) {
714     		__u32 high;
715     		rdtsc(time, high);
716     		num ^= high;
717     	} else {
718     		time = jiffies;
719     	}
720     #elif defined (__x86_64__)
721     	__u32 high;
722     	rdtsc(time, high);
723     	num ^= high;
724     #else
725     	time = jiffies;
726     #endif
727     
728     	/*
729     	 * Calculate number of bits of randomness we probably added.
730     	 * We take into account the first, second and third-order deltas
731     	 * in order to make our estimate.
732     	 */
733     	if (!state->dont_count_entropy) {
734     		delta = time - state->last_time;
735     		state->last_time = time;
736     
737     		delta2 = delta - state->last_delta;
738     		state->last_delta = delta;
739     
740     		delta3 = delta2 - state->last_delta2;
741     		state->last_delta2 = delta2;
742     
743     		if (delta < 0)
744     			delta = -delta;
745     		if (delta2 < 0)
746     			delta2 = -delta2;
747     		if (delta3 < 0)
748     			delta3 = -delta3;
749     		if (delta > delta2)
750     			delta = delta2;
751     		if (delta > delta3)
752     			delta = delta3;
753     
754     		/*
755     		 * delta is now minimum absolute delta.
756     		 * Round down by 1 bit on general principles,
757     		 * and limit entropy entimate to 12 bits.
758     		 */
759     		delta >>= 1;
760     		delta &= (1 << 12) - 1;
761     
762     		entropy = int_ln_12bits(delta);
763     	}
764     	batch_entropy_store(num, time, entropy);
765     }
766     
767     void add_keyboard_randomness(unsigned char scancode)
768     {
769     	static unsigned char last_scancode;
770     	/* ignore autorepeat (multiple key down w/o key up) */
771     	if (scancode != last_scancode) {
772     		last_scancode = scancode;
773     		add_timer_randomness(&keyboard_timer_state, scancode);
774     	}
775     }
776     
777     void add_mouse_randomness(__u32 mouse_data)
778     {
779     	add_timer_randomness(&mouse_timer_state, mouse_data);
780     }
781     
782     void add_interrupt_randomness(int irq)
783     {
784     	if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
785     		return;
786     
787     	add_timer_randomness(irq_timer_state[irq], 0x100+irq);
788     }
789     
790     void add_blkdev_randomness(int major)
791     {
792     	if (major >= MAX_BLKDEV)
793     		return;
794     
795     	if (blkdev_timer_state[major] == 0) {
796     		rand_initialize_blkdev(major, GFP_ATOMIC);
797     		if (blkdev_timer_state[major] == 0)
798     			return;
799     	}
800     		
801     	add_timer_randomness(blkdev_timer_state[major], 0x200+major);
802     }
803     
804     /******************************************************************
805      *
806      * Hash function definition
807      *
808      *******************************************************************/
809     
810     /*
811      * This chunk of code defines a function
812      * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
813      * 		__u32 const data[16])
814      * 
815      * The function hashes the input data to produce a digest in the first
816      * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
817      * more words for internal purposes.  (This buffer is exported so the
818      * caller can wipe it once rather than this code doing it each call,
819      * and tacking it onto the end of the digest[] array is the quick and
820      * dirty way of doing it.)
821      *
822      * It so happens that MD5 and SHA share most of the initial vector
823      * used to initialize the digest[] array before the first call:
824      * 1) 0x67452301
825      * 2) 0xefcdab89
826      * 3) 0x98badcfe
827      * 4) 0x10325476
828      * 5) 0xc3d2e1f0 (SHA only)
829      * 
830      * For /dev/random purposes, the length of the data being hashed is
831      * fixed in length, so appending a bit count in the usual way is not
832      * cryptographically necessary.
833      */
834     
835     #ifdef USE_SHA
836     
837     #define HASH_BUFFER_SIZE 5
838     #define HASH_EXTRA_SIZE 80
839     #define HASH_TRANSFORM SHATransform
840     
841     /* Various size/speed tradeoffs are available.  Choose 0..3. */
842     #define SHA_CODE_SIZE 0
843     
844     /*
845      * SHA transform algorithm, taken from code written by Peter Gutmann,
846      * and placed in the public domain.
847      */
848     
849     /* The SHA f()-functions.  */
850     
851     #define f1(x,y,z)   ( z ^ (x & (y^z)) )		/* Rounds  0-19: x ? y : z */
852     #define f2(x,y,z)   (x ^ y ^ z)			/* Rounds 20-39: XOR */
853     #define f3(x,y,z)   ( (x & y) + (z & (x ^ y)) )	/* Rounds 40-59: majority */
854     #define f4(x,y,z)   (x ^ y ^ z)			/* Rounds 60-79: XOR */
855     
856     /* The SHA Mysterious Constants */
857     
858     #define K1  0x5A827999L			/* Rounds  0-19: sqrt(2) * 2^30 */
859     #define K2  0x6ED9EBA1L			/* Rounds 20-39: sqrt(3) * 2^30 */
860     #define K3  0x8F1BBCDCL			/* Rounds 40-59: sqrt(5) * 2^30 */
861     #define K4  0xCA62C1D6L			/* Rounds 60-79: sqrt(10) * 2^30 */
862     
863     #define ROTL(n,X)  ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
864     
865     #define subRound(a, b, c, d, e, f, k, data) \
866         ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
867     
868     
869     static void SHATransform(__u32 digest[85], __u32 const data[16])
870     {
871         __u32 A, B, C, D, E;     /* Local vars */
872         __u32 TEMP;
873         int	i;
874     #define W (digest + HASH_BUFFER_SIZE)	/* Expanded data array */
875     
876         /*
877          * Do the preliminary expansion of 16 to 80 words.  Doing it
878          * out-of-line line this is faster than doing it in-line on
879          * register-starved machines like the x86, and not really any
880          * slower on real processors.
881          */
882         memcpy(W, data, 16*sizeof(__u32));
883         for (i = 0; i < 64; i++) {
884     	    TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
885     	    W[i+16] = ROTL(1, TEMP);
886         }
887     
888         /* Set up first buffer and local data buffer */
889         A = digest[ 0 ];
890         B = digest[ 1 ];
891         C = digest[ 2 ];
892         D = digest[ 3 ];
893         E = digest[ 4 ];
894     
895         /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
896     #if SHA_CODE_SIZE == 0
897         /*
898          * Approximately 50% of the speed of the largest version, but
899          * takes up 1/16 the space.  Saves about 6k on an i386 kernel.
900          */
901         for (i = 0; i < 80; i++) {
902     	if (i < 40) {
903     	    if (i < 20)
904     		TEMP = f1(B, C, D) + K1;
905     	    else
906     		TEMP = f2(B, C, D) + K2;
907     	} else {
908     	    if (i < 60)
909     		TEMP = f3(B, C, D) + K3;
910     	    else
911     		TEMP = f4(B, C, D) + K4;
912     	}
913     	TEMP += ROTL(5, A) + E + W[i];
914     	E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
915         }
916     #elif SHA_CODE_SIZE == 1
917         for (i = 0; i < 20; i++) {
918     	TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
919     	E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
920         }
921         for (; i < 40; i++) {
922     	TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
923     	E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
924         }
925         for (; i < 60; i++) {
926     	TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
927     	E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
928         }
929         for (; i < 80; i++) {
930     	TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
931     	E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
932         }
933     #elif SHA_CODE_SIZE == 2
934         for (i = 0; i < 20; i += 5) {
935     	subRound( A, B, C, D, E, f1, K1, W[ i   ] );
936     	subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
937     	subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
938     	subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
939     	subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
940         }
941         for (; i < 40; i += 5) {
942     	subRound( A, B, C, D, E, f2, K2, W[ i   ] );
943     	subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
944     	subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
945     	subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
946     	subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
947         }
948         for (; i < 60; i += 5) {
949     	subRound( A, B, C, D, E, f3, K3, W[ i   ] );
950     	subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
951     	subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
952     	subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
953     	subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
954         }
955         for (; i < 80; i += 5) {
956     	subRound( A, B, C, D, E, f4, K4, W[ i   ] );
957     	subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
958     	subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
959     	subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
960     	subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
961         }
962     #elif SHA_CODE_SIZE == 3 /* Really large version */
963         subRound( A, B, C, D, E, f1, K1, W[  0 ] );
964         subRound( E, A, B, C, D, f1, K1, W[  1 ] );
965         subRound( D, E, A, B, C, f1, K1, W[  2 ] );
966         subRound( C, D, E, A, B, f1, K1, W[  3 ] );
967         subRound( B, C, D, E, A, f1, K1, W[  4 ] );
968         subRound( A, B, C, D, E, f1, K1, W[  5 ] );
969         subRound( E, A, B, C, D, f1, K1, W[  6 ] );
970         subRound( D, E, A, B, C, f1, K1, W[  7 ] );
971         subRound( C, D, E, A, B, f1, K1, W[  8 ] );
972         subRound( B, C, D, E, A, f1, K1, W[  9 ] );
973         subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
974         subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
975         subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
976         subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
977         subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
978         subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
979         subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
980         subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
981         subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
982         subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
983     
984         subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
985         subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
986         subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
987         subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
988         subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
989         subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
990         subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
991         subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
992         subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
993         subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
994         subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
995         subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
996         subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
997         subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
998         subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
999         subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
1000         subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
1001         subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
1002         subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
1003         subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
1004         
1005         subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
1006         subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
1007         subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
1008         subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1009         subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1010         subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1011         subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1012         subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1013         subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1014         subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1015         subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1016         subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1017         subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1018         subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1019         subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1020         subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1021         subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1022         subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1023         subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1024         subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1025     
1026         subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1027         subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1028         subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1029         subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1030         subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1031         subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1032         subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1033         subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1034         subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1035         subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1036         subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1037         subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1038         subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1039         subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1040         subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1041         subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1042         subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1043         subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1044         subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1045         subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1046     #else
1047     #error Illegal SHA_CODE_SIZE
1048     #endif
1049     
1050         /* Build message digest */
1051         digest[ 0 ] += A;
1052         digest[ 1 ] += B;
1053         digest[ 2 ] += C;
1054         digest[ 3 ] += D;
1055         digest[ 4 ] += E;
1056     
1057     	/* W is wiped by the caller */
1058     #undef W
1059     }
1060     
1061     #undef ROTL
1062     #undef f1
1063     #undef f2
1064     #undef f3
1065     #undef f4
1066     #undef K1	
1067     #undef K2
1068     #undef K3	
1069     #undef K4	
1070     #undef subRound
1071     	
1072     #else /* !USE_SHA - Use MD5 */
1073     
1074     #define HASH_BUFFER_SIZE 4
1075     #define HASH_EXTRA_SIZE 0
1076     #define HASH_TRANSFORM MD5Transform
1077     	
1078     /*
1079      * MD5 transform algorithm, taken from code written by Colin Plumb,
1080      * and put into the public domain
1081      */
1082     
1083     /* The four core functions - F1 is optimized somewhat */
1084     
1085     /* #define F1(x, y, z) (x & y | ~x & z) */
1086     #define F1(x, y, z) (z ^ (x & (y ^ z)))
1087     #define F2(x, y, z) F1(z, x, y)
1088     #define F3(x, y, z) (x ^ y ^ z)
1089     #define F4(x, y, z) (y ^ (x | ~z))
1090     
1091     /* This is the central step in the MD5 algorithm. */
1092     #define MD5STEP(f, w, x, y, z, data, s) \
1093     	( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1094     
1095     /*
1096      * The core of the MD5 algorithm, this alters an existing MD5 hash to
1097      * reflect the addition of 16 longwords of new data.  MD5Update blocks
1098      * the data and converts bytes into longwords for this routine.
1099      */
1100     static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1101     {
1102     	__u32 a, b, c, d;
1103     
1104     	a = buf[0];
1105     	b = buf[1];
1106     	c = buf[2];
1107     	d = buf[3];
1108     
1109     	MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
1110     	MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1111     	MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1112     	MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1113     	MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
1114     	MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1115     	MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1116     	MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1117     	MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
1118     	MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1119     	MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1120     	MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1121     	MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
1122     	MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1123     	MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1124     	MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1125     
1126     	MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
1127     	MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
1128     	MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1129     	MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1130     	MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
1131     	MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
1132     	MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1133     	MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1134     	MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
1135     	MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
1136     	MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1137     	MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1138     	MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
1139     	MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
1140     	MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1141     	MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1142     
1143     	MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
1144     	MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1145     	MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1146     	MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1147     	MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
1148     	MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1149     	MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1150     	MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1151     	MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
1152     	MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1153     	MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1154     	MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1155     	MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
1156     	MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1157     	MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1158     	MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1159     
1160     	MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
1161     	MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1162     	MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1163     	MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1164     	MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
1165     	MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1166     	MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1167     	MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1168     	MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
1169     	MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1170     	MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1171     	MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1172     	MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
1173     	MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1174     	MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1175     	MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1176     
1177     	buf[0] += a;
1178     	buf[1] += b;
1179     	buf[2] += c;
1180     	buf[3] += d;
1181     }
1182     
1183     #undef F1
1184     #undef F2
1185     #undef F3
1186     #undef F4
1187     #undef MD5STEP
1188     
1189     #endif /* !USE_SHA */
1190     
1191     /*********************************************************************
1192      *
1193      * Entropy extraction routines
1194      *
1195      *********************************************************************/
1196     
1197     #define EXTRACT_ENTROPY_USER		1
1198     #define EXTRACT_ENTROPY_SECONDARY	2
1199     #define TMP_BUF_SIZE			(HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1200     #define SEC_XFER_SIZE			(TMP_BUF_SIZE*4)
1201     
1202     static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1203     			       size_t nbytes, int flags);
1204     
1205     /*
1206      * This utility inline function is responsible for transfering entropy
1207      * from the primary pool to the secondary extraction pool.  We pull 
1208      * randomness under two conditions; one is if there isn't enough entropy 
1209      * in the secondary pool.  The other is after we have extract 1024 bytes,
1210      * at which point we do a "catastrophic reseeding".
1211      */
1212     static inline void xfer_secondary_pool(struct entropy_store *r,
1213     				       size_t nbytes)
1214     {
1215     	__u32	tmp[TMP_BUF_SIZE];
1216     
1217     	if (r->entropy_count < nbytes*8) {
1218     		extract_entropy(random_state, tmp, sizeof(tmp), 0);
1219     		add_entropy_words(r, tmp, TMP_BUF_SIZE);
1220     		credit_entropy_store(r, TMP_BUF_SIZE*8);
1221     	}
1222     	if (r->extract_count > 1024) {
1223     		extract_entropy(random_state, tmp, sizeof(tmp), 0);
1224     		add_entropy_words(r, tmp, TMP_BUF_SIZE);
1225     		r->extract_count = 0;
1226     	}
1227     }
1228     
1229     /*
1230      * This function extracts randomness from the "entropy pool", and
1231      * returns it in a buffer.  This function computes how many remaining
1232      * bits of entropy are left in the pool, but it does not restrict the
1233      * number of bytes that are actually obtained.  If the EXTRACT_ENTROPY_USER
1234      * flag is given, then the buf pointer is assumed to be in user space.
1235      * If the EXTRACT_ENTROPY_SECONDARY flag is given, then this function will 
1236      *
1237      * Note: extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
1238      */
1239     static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1240     			       size_t nbytes, int flags)
1241     {
1242     	ssize_t ret, i;
1243     	__u32 tmp[TMP_BUF_SIZE];
1244     	__u32 x;
1245     
1246     	add_timer_randomness(&extract_timer_state, nbytes);
1247     	
1248     	/* Redundant, but just in case... */
1249     	if (r->entropy_count > r->poolinfo.poolwords) 
1250     		r->entropy_count = r->poolinfo.poolwords;
1251     
1252     	if (flags & EXTRACT_ENTROPY_SECONDARY)
1253     		xfer_secondary_pool(r, nbytes);
1254     
1255     	if (r->entropy_count / 8 >= nbytes)
1256     		r->entropy_count -= nbytes*8;
1257     	else
1258     		r->entropy_count = 0;
1259     
1260     	if (r->entropy_count < random_write_wakeup_thresh)
1261     		wake_up_interruptible(&random_write_wait);
1262     
1263     	r->extract_count += nbytes;
1264     	
1265     	ret = 0;
1266     	while (nbytes) {
1267     		/*
1268     		 * Check if we need to break out or reschedule....
1269     		 */
1270     		if ((flags & EXTRACT_ENTROPY_USER) && current->need_resched) {
1271     			if (signal_pending(current)) {
1272     				if (ret == 0)
1273     					ret = -ERESTARTSYS;
1274     				break;
1275     			}
1276     			schedule();
1277     		}
1278     
1279     		/* Hash the pool to get the output */
1280     		tmp[0] = 0x67452301;
1281     		tmp[1] = 0xefcdab89;
1282     		tmp[2] = 0x98badcfe;
1283     		tmp[3] = 0x10325476;
1284     #ifdef USE_SHA
1285     		tmp[4] = 0xc3d2e1f0;
1286     #endif
1287     		/*
1288     		 * As we hash the pool, we mix intermediate values of
1289     		 * the hash back into the pool.  This eliminates
1290     		 * backtracking attacks (where the attacker knows
1291     		 * the state of the pool plus the current outputs, and
1292     		 * attempts to find previous ouputs), unless the hash
1293     		 * function can be inverted.
1294     		 */
1295     		for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1296     			HASH_TRANSFORM(tmp, r->pool+i);
1297     			add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1298     		}
1299     		
1300     		/*
1301     		 * In case the hash function has some recognizable
1302     		 * output pattern, we fold it in half.
1303     		 */
1304     		for (i = 0; i <  HASH_BUFFER_SIZE/2; i++)
1305     			tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1306     #if HASH_BUFFER_SIZE & 1	/* There's a middle word to deal with */
1307     		x = tmp[HASH_BUFFER_SIZE/2];
1308     		x ^= (x >> 16);		/* Fold it in half */
1309     		((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1310     #endif
1311     		
1312     		/* Copy data to destination buffer */
1313     		i = MIN(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1314     		if (flags & EXTRACT_ENTROPY_USER) {
1315     			i -= copy_to_user(buf, (__u8 const *)tmp, i);
1316     			if (!i) {
1317     				ret = -EFAULT;
1318     				break;
1319     			}
1320     		} else
1321     			memcpy(buf, (__u8 const *)tmp, i);
1322     		nbytes -= i;
1323     		buf += i;
1324     		ret += i;
1325     		add_timer_randomness(&extract_timer_state, nbytes);
1326     	}
1327     
1328     	/* Wipe data just returned from memory */
1329     	memset(tmp, 0, sizeof(tmp));
1330     	
1331     	return ret;
1332     }
1333     
1334     /*
1335      * This function is the exported kernel interface.  It returns some
1336      * number of good random numbers, suitable for seeding TCP sequence
1337      * numbers, etc.
1338      */
1339     void get_random_bytes(void *buf, int nbytes)
1340     {
1341     	if (sec_random_state)  
1342     		extract_entropy(sec_random_state, (char *) buf, nbytes, 
1343     				EXTRACT_ENTROPY_SECONDARY);
1344     	else if (random_state)
1345     		extract_entropy(random_state, (char *) buf, nbytes, 0);
1346     	else
1347     		printk(KERN_NOTICE "get_random_bytes called before "
1348     				   "random driver initialization\n");
1349     }
1350     
1351     /*********************************************************************
1352      *
1353      * Functions to interface with Linux
1354      *
1355      *********************************************************************/
1356     
1357     /*
1358      * Initialize the random pool with standard stuff.
1359      *
1360      * NOTE: This is an OS-dependent function.
1361      */
1362     static void init_std_data(struct entropy_store *r)
1363     {
1364     	struct timeval 	tv;
1365     	__u32		words[2];
1366     	char 		*p;
1367     	int		i;
1368     
1369     	do_gettimeofday(&tv);
1370     	words[0] = tv.tv_sec;
1371     	words[1] = tv.tv_usec;
1372     	add_entropy_words(r, words, 2);
1373     
1374     	/*
1375     	 *	This doesn't lock system.utsname. However, we are generating
1376     	 *	entropy so a race with a name set here is fine.
1377     	 */
1378     	p = (char *) &system_utsname;
1379     	for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1380     		memcpy(words, p, sizeof(words));
1381     		add_entropy_words(r, words, sizeof(words)/4);
1382     		p += sizeof(words);
1383     	}
1384     }
1385     
1386     void __init rand_initialize(void)
1387     {
1388     	int i;
1389     
1390     	if (create_entropy_store(DEFAULT_POOL_SIZE, &random_state))
1391     		return;		/* Error, return */
1392     	if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1393     		return;		/* Error, return */
1394     	if (create_entropy_store(SECONDARY_POOL_SIZE, &sec_random_state))
1395     		return;		/* Error, return */
1396     	clear_entropy_store(random_state);
1397     	clear_entropy_store(sec_random_state);
1398     	init_std_data(random_state);
1399     #ifdef CONFIG_SYSCTL
1400     	sysctl_init_random(random_state);
1401     #endif
1402     	for (i = 0; i < NR_IRQS; i++)
1403     		irq_timer_state[i] = NULL;
1404     	for (i = 0; i < MAX_BLKDEV; i++)
1405     		blkdev_timer_state[i] = NULL;
1406     	memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1407     	memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1408     	memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1409     	extract_timer_state.dont_count_entropy = 1;
1410     }
1411     
1412     void rand_initialize_irq(int irq)
1413     {
1414     	struct timer_rand_state *state;
1415     	
1416     	if (irq >= NR_IRQS || irq_timer_state[irq])
1417     		return;
1418     
1419     	/*
1420     	 * If kmalloc returns null, we just won't use that entropy
1421     	 * source.
1422     	 */
1423     	state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1424     	if (state) {
1425     		memset(state, 0, sizeof(struct timer_rand_state));
1426     		irq_timer_state[irq] = state;
1427     	}
1428     }
1429     
1430     void rand_initialize_blkdev(int major, int mode)
1431     {
1432     	struct timer_rand_state *state;
1433     	
1434     	if (major >= MAX_BLKDEV || blkdev_timer_state[major])
1435     		return;
1436     
1437     	/*
1438     	 * If kmalloc returns null, we just won't use that entropy
1439     	 * source.
1440     	 */
1441     	state = kmalloc(sizeof(struct timer_rand_state), mode);
1442     	if (state) {
1443     		memset(state, 0, sizeof(struct timer_rand_state));
1444     		blkdev_timer_state[major] = state;
1445     	}
1446     }
1447     
1448     
1449     static ssize_t
1450     random_read(struct file * file, char * buf, size_t nbytes, loff_t *ppos)
1451     {
1452     	DECLARE_WAITQUEUE(wait, current);
1453     	ssize_t			n, retval = 0, count = 0;
1454     	
1455     	if (nbytes == 0)
1456     		return 0;
1457     
1458     	add_wait_queue(&random_read_wait, &wait);
1459     	while (nbytes > 0) {
1460     		set_current_state(TASK_INTERRUPTIBLE);
1461     		
1462     		n = nbytes;
1463     		if (n > SEC_XFER_SIZE)
1464     			n = SEC_XFER_SIZE;
1465     		if (n > random_state->entropy_count / 8)
1466     			n = random_state->entropy_count / 8;
1467     		if (n == 0) {
1468     			if (file->f_flags & O_NONBLOCK) {
1469     				retval = -EAGAIN;
1470     				break;
1471     			}
1472     			if (signal_pending(current)) {
1473     				retval = -ERESTARTSYS;
1474     				break;
1475     			}
1476     			schedule();
1477     			continue;
1478     		}
1479     		n = extract_entropy(sec_random_state, buf, n,
1480     				    EXTRACT_ENTROPY_USER |
1481     				    EXTRACT_ENTROPY_SECONDARY);
1482     		if (n < 0) {
1483     			retval = n;
1484     			break;
1485     		}
1486     		count += n;
1487     		buf += n;
1488     		nbytes -= n;
1489     		break;		/* This break makes the device work */
1490     				/* like a named pipe */
1491     	}
1492     	current->state = TASK_RUNNING;
1493     	remove_wait_queue(&random_read_wait, &wait);
1494     
1495     	/*
1496     	 * If we gave the user some bytes, update the access time.
1497     	 */
1498     	if (count != 0) {
1499     		UPDATE_ATIME(file->f_dentry->d_inode);
1500     	}
1501     	
1502     	return (count ? count : retval);
1503     }
1504     
1505     static ssize_t
1506     urandom_read(struct file * file, char * buf,
1507     		      size_t nbytes, loff_t *ppos)
1508     {
1509     	return extract_entropy(sec_random_state, buf, nbytes,
1510     			       EXTRACT_ENTROPY_USER |
1511     			       EXTRACT_ENTROPY_SECONDARY);
1512     }
1513     
1514     static unsigned int
1515     random_poll(struct file *file, poll_table * wait)
1516     {
1517     	unsigned int mask;
1518     
1519     	poll_wait(file, &random_read_wait, wait);
1520     	poll_wait(file, &random_write_wait, wait);
1521     	mask = 0;
1522     	if (random_state->entropy_count >= random_read_wakeup_thresh)
1523     		mask |= POLLIN | POLLRDNORM;
1524     	if (random_state->entropy_count < random_write_wakeup_thresh)
1525     		mask |= POLLOUT | POLLWRNORM;
1526     	return mask;
1527     }
1528     
1529     static ssize_t
1530     random_write(struct file * file, const char * buffer,
1531     	     size_t count, loff_t *ppos)
1532     {
1533     	int		ret = 0;
1534     	size_t		bytes;
1535     	__u32 		buf[16];
1536     	const char 	*p = buffer;
1537     	size_t		c = count;
1538     
1539     	while (c > 0) {
1540     		bytes = MIN(c, sizeof(buf));
1541     
1542     		bytes -= copy_from_user(&buf, p, bytes);
1543     		if (!bytes) {
1544     			ret = -EFAULT;
1545     			break;
1546     		}
1547     		c -= bytes;
1548     		p += bytes;
1549     
1550     		/* Convert bytes to words */
1551     		bytes = (bytes + 3) / sizeof(__u32);
1552     		add_entropy_words(random_state, buf, bytes);
1553     	}
1554     	if (p == buffer) {
1555     		return (ssize_t)ret;
1556     	} else {
1557     		file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1558     		mark_inode_dirty(file->f_dentry->d_inode);
1559     		return (ssize_t)(p - buffer);
1560     	}
1561     }
1562     
1563     static int
1564     random_ioctl(struct inode * inode, struct file * file,
1565     	     unsigned int cmd, unsigned long arg)
1566     {
1567     	int *p, size, ent_count;
1568     	int retval;
1569     	
1570     	switch (cmd) {
1571     	case RNDGETENTCNT:
1572     		ent_count = random_state->entropy_count;
1573     		if (put_user(ent_count, (int *) arg))
1574     			return -EFAULT;
1575     		return 0;
1576     	case RNDADDTOENTCNT:
1577     		if (!capable(CAP_SYS_ADMIN))
1578     			return -EPERM;
1579     		if (get_user(ent_count, (int *) arg))
1580     			return -EFAULT;
1581     		credit_entropy_store(random_state, ent_count);
1582     		/*
1583     		 * Wake up waiting processes if we have enough
1584     		 * entropy.
1585     		 */
1586     		if (random_state->entropy_count >= random_read_wakeup_thresh)
1587     			wake_up_interruptible(&random_read_wait);
1588     		return 0;
1589     	case RNDGETPOOL:
1590     		if (!capable(CAP_SYS_ADMIN))
1591     			return -EPERM;
1592     		p = (int *) arg;
1593     		ent_count = random_state->entropy_count;
1594     		if (put_user(ent_count, p++) ||
1595     		    get_user(size, p) ||
1596     		    put_user(random_state->poolinfo.poolwords, p++))
1597     			return -EFAULT;
1598     		if (size < 0)
1599     			return -EINVAL;
1600     		if (size > random_state->poolinfo.poolwords)
1601     			size = random_state->poolinfo.poolwords;
1602     		if (copy_to_user(p, random_state->pool, size*sizeof(__u32)))
1603     			return -EFAULT;
1604     		return 0;
1605     	case RNDADDENTROPY:
1606     		if (!capable(CAP_SYS_ADMIN))
1607     			return -EPERM;
1608     		p = (int *) arg;
1609     		if (get_user(ent_count, p++))
1610     			return -EFAULT;
1611     		if (ent_count < 0)
1612     			return -EINVAL;
1613     		if (get_user(size, p++))
1614     			return -EFAULT;
1615     		retval = random_write(file, (const char *) p,
1616     				      size, &file->f_pos);
1617     		if (retval < 0)
1618     			return retval;
1619     		credit_entropy_store(random_state, ent_count);
1620     		/*
1621     		 * Wake up waiting processes if we have enough
1622     		 * entropy.
1623     		 */
1624     		if (random_state->entropy_count >= random_read_wakeup_thresh)
1625     			wake_up_interruptible(&random_read_wait);
1626     		return 0;
1627     	case RNDZAPENTCNT:
1628     		if (!capable(CAP_SYS_ADMIN))
1629     			return -EPERM;
1630     		random_state->entropy_count = 0;
1631     		return 0;
1632     	case RNDCLEARPOOL:
1633     		/* Clear the entropy pool and associated counters. */
1634     		if (!capable(CAP_SYS_ADMIN))
1635     			return -EPERM;
1636     		clear_entropy_store(random_state);
1637     		init_std_data(random_state);
1638     		return 0;
1639     	default:
1640     		return -EINVAL;
1641     	}
1642     }
1643     
1644     struct file_operations random_fops = {
1645     	read:		random_read,
1646     	write:		random_write,
1647     	poll:		random_poll,
1648     	ioctl:		random_ioctl,
1649     };
1650     
1651     struct file_operations urandom_fops = {
1652     	read:		urandom_read,
1653     	write:		random_write,
1654     	ioctl:		random_ioctl,
1655     };
1656     
1657     /***************************************************************
1658      * Random UUID interface
1659      * 
1660      * Used here for a Boot ID, but can be useful for other kernel 
1661      * drivers.
1662      ***************************************************************/
1663     
1664     /*
1665      * Generate random UUID
1666      */
1667     void generate_random_uuid(unsigned char uuid_out[16])
1668     {
1669     	get_random_bytes(uuid_out, 16);
1670     	/* Set UUID version to 4 --- truely random generation */
1671     	uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1672     	/* Set the UUID variant to DCE */
1673     	uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1674     }
1675     
1676     /********************************************************************
1677      *
1678      * Sysctl interface
1679      *
1680      ********************************************************************/
1681     
1682     #ifdef CONFIG_SYSCTL
1683     
1684     #include <linux/sysctl.h>
1685     
1686     static int sysctl_poolsize;
1687     static int min_read_thresh, max_read_thresh;
1688     static int min_write_thresh, max_write_thresh;
1689     static char sysctl_bootid[16];
1690     
1691     /*
1692      * This function handles a request from the user to change the pool size 
1693      * of the primary entropy store.
1694      */
1695     static int change_poolsize(int poolsize)
1696     {
1697     	struct entropy_store	*new_store, *old_store;
1698     	int			ret;
1699     	
1700     	if ((ret = create_entropy_store(poolsize, &new_store)))
1701     		return ret;
1702     
1703     	add_entropy_words(new_store, random_state->pool,
1704     			  random_state->poolinfo.poolwords);
1705     	credit_entropy_store(new_store, random_state->entropy_count);
1706     
1707     	sysctl_init_random(new_store);
1708     	old_store = random_state;
1709     	random_state = batch_tqueue.data = new_store;
1710     	free_entropy_store(old_store);
1711     	return 0;
1712     }
1713     
1714     static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1715     			    void *buffer, size_t *lenp)
1716     {
1717     	int	ret;
1718     
1719     	sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1720     
1721     	ret = proc_dointvec(table, write, filp, buffer, lenp);
1722     	if (ret || !write ||
1723     	    (sysctl_poolsize == random_state->poolinfo.poolwords * 4))
1724     		return ret;
1725     
1726     	return change_poolsize(sysctl_poolsize);
1727     }
1728     
1729     static int poolsize_strategy(ctl_table *table, int *name, int nlen,
1730     			     void *oldval, size_t *oldlenp,
1731     			     void *newval, size_t newlen, void **context)
1732     {
1733     	int	len;
1734     	
1735     	sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1736     
1737     	/*
1738     	 * We only handle the write case, since the read case gets
1739     	 * handled by the default handler (and we don't care if the
1740     	 * write case happens twice; it's harmless).
1741     	 */
1742     	if (newval && newlen) {
1743     		len = newlen;
1744     		if (len > table->maxlen)
1745     			len = table->maxlen;
1746     		if (copy_from_user(table->data, newval, len))
1747     			return -EFAULT;
1748     	}
1749     
1750     	if (sysctl_poolsize != random_state->poolinfo.poolwords * 4)
1751     		return change_poolsize(sysctl_poolsize);
1752     
1753     	return 0;
1754     }
1755     
1756     /*
1757      * These functions is used to return both the bootid UUID, and random
1758      * UUID.  The difference is in whether table->data is NULL; if it is,
1759      * then a new UUID is generated and returned to the user.
1760      * 
1761      * If the user accesses this via the proc interface, it will be returned
1762      * as an ASCII string in the standard UUID format.  If accesses via the 
1763      * sysctl system call, it is returned as 16 bytes of binary data.
1764      */
1765     static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1766     			void *buffer, size_t *lenp)
1767     {
1768     	ctl_table	fake_table;
1769     	unsigned char	buf[64], tmp_uuid[16], *uuid;
1770     
1771     	uuid = table->data;
1772     	if (!uuid) {
1773     		uuid = tmp_uuid;
1774     		uuid[8] = 0;
1775     	}
1776     	if (uuid[8] == 0)
1777     		generate_random_uuid(uuid);
1778     
1779     	sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1780     		"%02x%02x%02x%02x%02x%02x",
1781     		uuid[0],  uuid[1],  uuid[2],  uuid[3],
1782     		uuid[4],  uuid[5],  uuid[6],  uuid[7],
1783     		uuid[8],  uuid[9],  uuid[10], uuid[11],
1784     		uuid[12], uuid[13], uuid[14], uuid[15]);
1785     	fake_table.data = buf;
1786     	fake_table.maxlen = sizeof(buf);
1787     
1788     	return proc_dostring(&fake_table, write, filp, buffer, lenp);
1789     }
1790     
1791     static int uuid_strategy(ctl_table *table, int *name, int nlen,
1792     			 void *oldval, size_t *oldlenp,
1793     			 void *newval, size_t newlen, void **context)
1794     {
1795     	unsigned char	tmp_uuid[16], *uuid;
1796     	unsigned int	len;
1797     
1798     	if (!oldval || !oldlenp)
1799     		return 1;
1800     
1801     	uuid = table->data;
1802     	if (!uuid) {
1803     		uuid = tmp_uuid;
1804     		uuid[8] = 0;
1805     	}
1806     	if (uuid[8] == 0)
1807     		generate_random_uuid(uuid);
1808     
1809     	if (get_user(len, oldlenp))
1810     		return -EFAULT;
1811     	if (len) {
1812     		if (len > 16)
1813     			len = 16;
1814     		if (copy_to_user(oldval, uuid, len) ||
1815     		    put_user(len, oldlenp))
1816     			return -EFAULT;
1817     	}
1818     	return 1;
1819     }
1820     
1821     ctl_table random_table[] = {
1822     	{RANDOM_POOLSIZE, "poolsize",
1823     	 &sysctl_poolsize, sizeof(int), 0644, NULL,
1824     	 &proc_do_poolsize, &poolsize_strategy},
1825     	{RANDOM_ENTROPY_COUNT, "entropy_avail",
1826     	 NULL, sizeof(int), 0444, NULL,
1827     	 &proc_dointvec},
1828     	{RANDOM_READ_THRESH, "read_wakeup_threshold",
1829     	 &random_read_wakeup_thresh, sizeof(int), 0644, NULL,
1830     	 &proc_dointvec_minmax, &sysctl_intvec, 0,
1831     	 &min_read_thresh, &max_read_thresh},
1832     	{RANDOM_WRITE_THRESH, "write_wakeup_threshold",
1833     	 &random_write_wakeup_thresh, sizeof(int), 0644, NULL,
1834     	 &proc_dointvec_minmax, &sysctl_intvec, 0,
1835     	 &min_write_thresh, &max_write_thresh},
1836     	{RANDOM_BOOT_ID, "boot_id",
1837     	 &sysctl_bootid, 16, 0444, NULL,
1838     	 &proc_do_uuid, &uuid_strategy},
1839     	{RANDOM_UUID, "uuid",
1840     	 NULL, 16, 0444, NULL,
1841     	 &proc_do_uuid, &uuid_strategy},
1842     	{0}
1843     };
1844     
1845     static void sysctl_init_random(struct entropy_store *random_state)
1846     {
1847     	min_read_thresh = 8;
1848     	min_write_thresh = 0;
1849     	max_read_thresh = max_write_thresh =
1850     		random_state->poolinfo.poolwords * 32;
1851     	random_table[1].data = &random_state->entropy_count;
1852     }
1853     #endif 	/* CONFIG_SYSCTL */
1854     
1855     /********************************************************************
1856      *
1857      * Random funtions for networking
1858      *
1859      ********************************************************************/
1860     
1861     /*
1862      * TCP initial sequence number picking.  This uses the random number
1863      * generator to pick an initial secret value.  This value is hashed
1864      * along with the TCP endpoint information to provide a unique
1865      * starting point for each pair of TCP endpoints.  This defeats
1866      * attacks which rely on guessing the initial TCP sequence number.
1867      * This algorithm was suggested by Steve Bellovin.
1868      *
1869      * Using a very strong hash was taking an appreciable amount of the total
1870      * TCP connection establishment time, so this is a weaker hash,
1871      * compensated for by changing the secret periodically.
1872      */
1873     
1874     /* F, G and H are basic MD4 functions: selection, majority, parity */
1875     #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1876     #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1877     #define H(x, y, z) ((x) ^ (y) ^ (z))
1878     
1879     /*
1880      * The generic round function.  The application is so specific that
1881      * we don't bother protecting all the arguments with parens, as is generally
1882      * good macro practice, in favor of extra legibility.
1883      * Rotation is separate from addition to prevent recomputation
1884      */
1885     #define ROUND(f, a, b, c, d, x, s)	\
1886     	(a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1887     #define K1 0
1888     #define K2 013240474631UL
1889     #define K3 015666365641UL
1890     
1891     /*
1892      * Basic cut-down MD4 transform.  Returns only 32 bits of result.
1893      */
1894     static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
1895     {
1896     	__u32	a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1897     
1898     	/* Round 1 */
1899     	ROUND(F, a, b, c, d, in[0] + K1,  3);
1900     	ROUND(F, d, a, b, c, in[1] + K1,  7);
1901     	ROUND(F, c, d, a, b, in[2] + K1, 11);
1902     	ROUND(F, b, c, d, a, in[3] + K1, 19);
1903     	ROUND(F, a, b, c, d, in[4] + K1,  3);
1904     	ROUND(F, d, a, b, c, in[5] + K1,  7);
1905     	ROUND(F, c, d, a, b, in[6] + K1, 11);
1906     	ROUND(F, b, c, d, a, in[7] + K1, 19);
1907     
1908     	/* Round 2 */
1909     	ROUND(G, a, b, c, d, in[1] + K2,  3);
1910     	ROUND(G, d, a, b, c, in[3] + K2,  5);
1911     	ROUND(G, c, d, a, b, in[5] + K2,  9);
1912     	ROUND(G, b, c, d, a, in[7] + K2, 13);
1913     	ROUND(G, a, b, c, d, in[0] + K2,  3);
1914     	ROUND(G, d, a, b, c, in[2] + K2,  5);
1915     	ROUND(G, c, d, a, b, in[4] + K2,  9);
1916     	ROUND(G, b, c, d, a, in[6] + K2, 13);
1917     
1918     	/* Round 3 */
1919     	ROUND(H, a, b, c, d, in[3] + K3,  3);
1920     	ROUND(H, d, a, b, c, in[7] + K3,  9);
1921     	ROUND(H, c, d, a, b, in[2] + K3, 11);
1922     	ROUND(H, b, c, d, a, in[6] + K3, 15);
1923     	ROUND(H, a, b, c, d, in[1] + K3,  3);
1924     	ROUND(H, d, a, b, c, in[5] + K3,  9);
1925     	ROUND(H, c, d, a, b, in[0] + K3, 11);
1926     	ROUND(H, b, c, d, a, in[4] + K3, 15);
1927     
1928     	return buf[1] + b;	/* "most hashed" word */
1929     	/* Alternative: return sum of all words? */
1930     }
1931     
1932     #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1933     
1934     static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
1935     {
1936     	__u32	a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1937     
1938     	/* Round 1 */
1939     	ROUND(F, a, b, c, d, in[ 0] + K1,  3);
1940     	ROUND(F, d, a, b, c, in[ 1] + K1,  7);
1941     	ROUND(F, c, d, a, b, in[ 2] + K1, 11);
1942     	ROUND(F, b, c, d, a, in[ 3] + K1, 19);
1943     	ROUND(F, a, b, c, d, in[ 4] + K1,  3);
1944     	ROUND(F, d, a, b, c, in[ 5] + K1,  7);
1945     	ROUND(F, c, d, a, b, in[ 6] + K1, 11);
1946     	ROUND(F, b, c, d, a, in[ 7] + K1, 19);
1947     	ROUND(F, a, b, c, d, in[ 8] + K1,  3);
1948     	ROUND(F, d, a, b, c, in[ 9] + K1,  7);
1949     	ROUND(F, c, d, a, b, in[10] + K1, 11);
1950     	ROUND(F, b, c, d, a, in[11] + K1, 19);
1951     
1952     	/* Round 2 */
1953     	ROUND(G, a, b, c, d, in[ 1] + K2,  3);
1954     	ROUND(G, d, a, b, c, in[ 3] + K2,  5);
1955     	ROUND(G, c, d, a, b, in[ 5] + K2,  9);
1956     	ROUND(G, b, c, d, a, in[ 7] + K2, 13);
1957     	ROUND(G, a, b, c, d, in[ 9] + K2,  3);
1958     	ROUND(G, d, a, b, c, in[11] + K2,  5);
1959     	ROUND(G, c, d, a, b, in[ 0] + K2,  9);
1960     	ROUND(G, b, c, d, a, in[ 2] + K2, 13);
1961     	ROUND(G, a, b, c, d, in[ 4] + K2,  3);
1962     	ROUND(G, d, a, b, c, in[ 6] + K2,  5);
1963     	ROUND(G, c, d, a, b, in[ 8] + K2,  9);
1964     	ROUND(G, b, c, d, a, in[10] + K2, 13);
1965     
1966     	/* Round 3 */
1967     	ROUND(H, a, b, c, d, in[ 3] + K3,  3);
1968     	ROUND(H, d, a, b, c, in[ 7] + K3,  9);
1969     	ROUND(H, c, d, a, b, in[11] + K3, 11);
1970     	ROUND(H, b, c, d, a, in[ 2] + K3, 15);
1971     	ROUND(H, a, b, c, d, in[ 6] + K3,  3);
1972     	ROUND(H, d, a, b, c, in[10] + K3,  9);
1973     	ROUND(H, c, d, a, b, in[ 1] + K3, 11);
1974     	ROUND(H, b, c, d, a, in[ 5] + K3, 15);
1975     	ROUND(H, a, b, c, d, in[ 9] + K3,  3);
1976     	ROUND(H, d, a, b, c, in[ 0] + K3,  9);
1977     	ROUND(H, c, d, a, b, in[ 4] + K3, 11);
1978     	ROUND(H, b, c, d, a, in[ 8] + K3, 15);
1979     
1980     	return buf[1] + b;	/* "most hashed" word */
1981     	/* Alternative: return sum of all words? */
1982     }
1983     #endif
1984     
1985     #undef ROUND
1986     #undef F
1987     #undef G
1988     #undef H
1989     #undef K1
1990     #undef K2
1991     #undef K3
1992     
1993     /* This should not be decreased so low that ISNs wrap too fast. */
1994     #define REKEY_INTERVAL	300
1995     #define HASH_BITS 24
1996     
1997     #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1998     __u32 secure_tcpv6_sequence_number(__u32 *saddr, __u32 *daddr,
1999     				   __u16 sport, __u16 dport)
2000     {
2001     	static __u32	rekey_time;
2002     	static __u32	count;
2003     	static __u32	secret[12];
2004     	struct timeval 	tv;
2005     	__u32		seq;
2006     
2007     	/* The procedure is the same as for IPv4, but addresses are longer. */
2008     
2009     	do_gettimeofday(&tv);	/* We need the usecs below... */
2010     
2011     	if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) {
2012     		rekey_time = tv.tv_sec;
2013     		/* First five words are overwritten below. */
2014     		get_random_bytes(&secret[5], sizeof(secret)-5*4);
2015     		count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS;
2016     	}
2017     
2018     	memcpy(secret, saddr, 16);
2019     	secret[4]=(sport << 16) + dport;
2020     
2021     	seq = (twothirdsMD4Transform(daddr, secret) &
2022     	       ((1<<HASH_BITS)-1)) + count;
2023     
2024     	seq += tv.tv_usec + tv.tv_sec*1000000;
2025     	return seq;
2026     }
2027     
2028     __u32 secure_ipv6_id(__u32 *daddr)
2029     {
2030     	static time_t	rekey_time;
2031     	static __u32	secret[12];
2032     	time_t		t;
2033     
2034     	/*
2035     	 * Pick a random secret every REKEY_INTERVAL seconds.
2036     	 */
2037     	t = CURRENT_TIME;
2038     	if (!rekey_time || (t - rekey_time) > REKEY_INTERVAL) {
2039     		rekey_time = t;
2040     		/* First word is overwritten below. */
2041     		get_random_bytes(secret, sizeof(secret));
2042     	}
2043     
2044     	return twothirdsMD4Transform(daddr, secret);
2045     }
2046     
2047     #endif
2048     
2049     
2050     __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
2051     				 __u16 sport, __u16 dport)
2052     {
2053     	static __u32	rekey_time;
2054     	static __u32	count;
2055     	static __u32	secret[12];
2056     	struct timeval 	tv;
2057     	__u32		seq;
2058     
2059     	/*
2060     	 * Pick a random secret every REKEY_INTERVAL seconds.
2061     	 */
2062     	do_gettimeofday(&tv);	/* We need the usecs below... */
2063     
2064     	if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) {
2065     		rekey_time = tv.tv_sec;
2066     		/* First three words are overwritten below. */
2067     		get_random_bytes(&secret[3], sizeof(secret)-12);
2068     		count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS;
2069     	}
2070     
2071     	/*
2072     	 *  Pick a unique starting offset for each TCP connection endpoints
2073     	 *  (saddr, daddr, sport, dport).
2074     	 *  Note that the words are placed into the first words to be
2075     	 *  mixed in with the halfMD4.  This is because the starting
2076     	 *  vector is also a random secret (at secret+8), and further
2077     	 *  hashing fixed data into it isn't going to improve anything,
2078     	 *  so we should get started with the variable data.
2079     	 */
2080     	secret[0]=saddr;
2081     	secret[1]=daddr;
2082     	secret[2]=(sport << 16) + dport;
2083     
2084     	seq = (halfMD4Transform(secret+8, secret) &
2085     	       ((1<<HASH_BITS)-1)) + count;
2086     
2087     	/*
2088     	 *	As close as possible to RFC 793, which
2089     	 *	suggests using a 250 kHz clock.
2090     	 *	Further reading shows this assumes 2 Mb/s networks.
2091     	 *	For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2092     	 *	That's funny, Linux has one built in!  Use it!
2093     	 *	(Networks are faster now - should this be increased?)
2094     	 */
2095     	seq += tv.tv_usec + tv.tv_sec*1000000;
2096     #if 0
2097     	printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2098     	       saddr, daddr, sport, dport, seq);
2099     #endif
2100     	return seq;
2101     }
2102     
2103     /*  The code below is shamelessly stolen from secure_tcp_sequence_number().
2104      *  All blames to Andrey V. Savochkin <saw@msu.ru>.
2105      */
2106     __u32 secure_ip_id(__u32 daddr)
2107     {
2108     	static time_t	rekey_time;
2109     	static __u32	secret[12];
2110     	time_t		t;
2111     
2112     	/*
2113     	 * Pick a random secret every REKEY_INTERVAL seconds.
2114     	 */
2115     	t = CURRENT_TIME;
2116     	if (!rekey_time || (t - rekey_time) > REKEY_INTERVAL) {
2117     		rekey_time = t;
2118     		/* First word is overwritten below. */
2119     		get_random_bytes(secret+1, sizeof(secret)-4);
2120     	}
2121     
2122     	/*
2123     	 *  Pick a unique starting offset for each IP destination.
2124     	 *  Note that the words are placed into the first words to be
2125     	 *  mixed in with the halfMD4.  This is because the starting
2126     	 *  vector is also a random secret (at secret+8), and further
2127     	 *  hashing fixed data into it isn't going to improve anything,
2128     	 *  so we should get started with the variable data.
2129     	 */
2130     	secret[0]=daddr;
2131     
2132     	return halfMD4Transform(secret+8, secret);
2133     }
2134     
2135     #ifdef CONFIG_SYN_COOKIES
2136     /*
2137      * Secure SYN cookie computation. This is the algorithm worked out by
2138      * Dan Bernstein and Eric Schenk.
2139      *
2140      * For linux I implement the 1 minute counter by looking at the jiffies clock.
2141      * The count is passed in as a parameter, so this code doesn't much care.
2142      */
2143     
2144     #define COOKIEBITS 24	/* Upper bits store count */
2145     #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2146     
2147     static int	syncookie_init;
2148     static __u32	syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2149     
2150     __u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2151     		__u16 dport, __u32 sseq, __u32 count, __u32 data)
2152     {
2153     	__u32 	tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2154     	__u32	seq;
2155     
2156     	/*
2157     	 * Pick two random secrets the first time we need a cookie.
2158     	 */
2159     	if (syncookie_init == 0) {
2160     		get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2161     		syncookie_init = 1;
2162     	}
2163     
2164     	/*
2165     	 * Compute the secure sequence number.
2166     	 * The output should be:
2167        	 *   HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2168     	 *      + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2169     	 * Where sseq is their sequence number and count increases every
2170     	 * minute by 1.
2171     	 * As an extra hack, we add a small "data" value that encodes the
2172     	 * MSS into the second hash value.
2173     	 */
2174     
2175     	memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2176     	tmp[0]=saddr;
2177     	tmp[1]=daddr;
2178     	tmp[2]=(sport << 16) + dport;
2179     	HASH_TRANSFORM(tmp+16, tmp);
2180     	seq = tmp[17] + sseq + (count << COOKIEBITS);
2181     
2182     	memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2183     	tmp[0]=saddr;
2184     	tmp[1]=daddr;
2185     	tmp[2]=(sport << 16) + dport;
2186     	tmp[3] = count;	/* minute counter */
2187     	HASH_TRANSFORM(tmp+16, tmp);
2188     
2189     	/* Add in the second hash and the data */
2190     	return seq + ((tmp[17] + data) & COOKIEMASK);
2191     }
2192     
2193     /*
2194      * This retrieves the small "data" value from the syncookie.
2195      * If the syncookie is bad, the data returned will be out of
2196      * range.  This must be checked by the caller.
2197      *
2198      * The count value used to generate the cookie must be within
2199      * "maxdiff" if the current (passed-in) "count".  The return value
2200      * is (__u32)-1 if this test fails.
2201      */
2202     __u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2203     		__u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2204     {
2205     	__u32 	tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2206     	__u32	diff;
2207     
2208     	if (syncookie_init == 0)
2209     		return (__u32)-1;	/* Well, duh! */
2210     
2211     	/* Strip away the layers from the cookie */
2212     	memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2213     	tmp[0]=saddr;
2214     	tmp[1]=daddr;
2215     	tmp[2]=(sport << 16) + dport;
2216     	HASH_TRANSFORM(tmp+16, tmp);
2217     	cookie -= tmp[17] + sseq;
2218     	/* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2219     
2220     	diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2221     	if (diff >= maxdiff)
2222     		return (__u32)-1;
2223     
2224     	memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2225     	tmp[0] = saddr;
2226     	tmp[1] = daddr;
2227     	tmp[2] = (sport << 16) + dport;
2228     	tmp[3] = count - diff;	/* minute counter */
2229     	HASH_TRANSFORM(tmp+16, tmp);
2230     
2231     	return (cookie - tmp[17]) & COOKIEMASK;	/* Leaving the data behind */
2232     }
2233     #endif
2234     
2235     
2236     
2237     EXPORT_SYMBOL(add_keyboard_randomness);
2238     EXPORT_SYMBOL(add_mouse_randomness);
2239     EXPORT_SYMBOL(add_interrupt_randomness);
2240     EXPORT_SYMBOL(add_blkdev_randomness);
2241     EXPORT_SYMBOL(batch_entropy_store);
2242     
2243