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