kernel - Quick pass add __read_frequently
[dragonfly.git] / sys / kern / kern_nrandom.c
1 /*
2  * Copyright (c) 2004-2014 The DragonFly Project. All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * by Alex Hornung <alex@alexhornung.com>
7  * by Robin J Carey
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, this list of conditions, and the following disclaimer,
14  *    without modification, immediately at the beginning of the file.
15  * 2. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 /*                         --- NOTES ---
31  *
32  * Note: The word "entropy" is often incorrectly used to describe
33  * random data. The word "entropy" originates from the science of
34  * Physics. The correct descriptive definition would be something
35  * along the lines of "seed", "unpredictable numbers" or
36  * "unpredictable data".
37  *
38  * Note: Some /dev/[u]random implementations save "seed" between
39  * boots which represents a security hazard since an adversary
40  * could acquire this data (since it is stored in a file). If
41  * the unpredictable data used in the above routines is only
42  * generated during Kernel operation, then an adversary can only
43  * acquire that data through a Kernel security compromise and/or
44  * a cryptographic algorithm failure/cryptanalysis.
45  *
46  * Note: On FreeBSD-4.11, interrupts have to be manually enabled
47  * using the rndcontrol(8) command.
48  *
49  *              --- DESIGN (FreeBSD-4.11 based) ---
50  *
51  *   The rnddev module automatically initializes itself the first time
52  * it is used (client calls any public rnddev_*() interface routine).
53  * Both CSPRNGs are initially seeded from the precise nano[up]time() routines.
54  * Tests show this method produces good enough results, suitable for intended
55  * use. It is necessary for both CSPRNGs to be completely seeded, initially.
56  *
57  *   After initialization and during Kernel operation the only suitable
58  * unpredictable data available is:
59  *
60  *      (1) Keyboard scan-codes.
61  *      (2) Nanouptime acquired by a Keyboard/Read-Event.
62  *      (3) Suitable interrupt source; hard-disk/ATA-device.
63  *
64  *      (X) Mouse-event (xyz-data unsuitable); NOT IMPLEMENTED.
65  *
66  *   This data is added to both CSPRNGs in real-time as it happens/
67  * becomes-available. Additionally, unpredictable (?) data may be
68  * acquired from a true-random number generator if such a device is
69  * available to the system (not advisable !).
70  *   Nanouptime() acquired by a Read-Event is a very important aspect of
71  * this design, since it ensures that unpredictable data is added to
72  * the CSPRNGs even if there are no other sources.
73  *   The nanouptime() Kernel routine is used since time relative to
74  * boot is less adversary-known than time itself.
75  *
76  *   This design has been thoroughly tested with debug logging
77  * and the output from both /dev/random and /dev/urandom has
78  * been tested with the DIEHARD test-suite; both pass.
79  *
80  * MODIFICATIONS MADE TO ORIGINAL "kern_random.c":
81  *
82  * 6th July 2005:
83  *
84  * o Changed ReadSeed() function to schedule future read-seed-events
85  *   by at least one second. Previous implementation used a randomised
86  *   scheduling { 0, 1, 2, 3 seconds }.
87  * o Changed SEED_NANOUP() function to use a "previous" accumulator
88  *   algorithm similar to ReadSeed(). This ensures that there is no
89  *   way that an adversary can tell what number is being added to the
90  *   CSPRNGs, since the number added to the CSPRNGs at Event-Time is
91  *   the sum of nanouptime()@Event and an unknown/secret number.
92  * o Changed rnddev_add_interrupt() function to schedule future
93  *   interrupt-events by at least one second. Previous implementation
94  *   had no scheduling algorithm which allowed an "interrupt storm"
95  *   to occur resulting in skewed data entering into the CSPRNGs.
96  *
97  *
98  * 9th July 2005:
99  *
100  * o Some small cleanups and change all internal functions to be
101  *   static/private.
102  * o Removed ReadSeed() since its functionality is already performed
103  *   by another function { rnddev_add_interrupt_OR_read() } and remove
104  *   the silly rndByte accumulator/feedback-thing (since multipying by
105  *   rndByte could yield a value of 0).
106  * o Made IBAA/L14 public interface become static/private;
107  *   Local to this file (not changed to that in the original C modules).
108  *
109  * 16th July 2005:
110  *
111  * o SEED_NANOUP() -> NANOUP_EVENT() function rename.
112  * o Make NANOUP_EVENT() handle the time-buffering directly so that all
113  *   time-stamp-events use this single time-buffer (including keyboard).
114  *   This removes dependancy on "time_second" Kernel variable.
115  * o Removed second-time-buffer code in rnddev_add_interrupt_OR_read (void).
116  * o Rewrote the time-buffering algorithm in NANOUP_EVENT() to use a
117  *   randomised time-delay range.
118  *
119  * 12th Dec 2005:
120  *
121  * o Updated to (hopefully final) L15 algorithm.
122  *
123  * 12th June 2006:
124  *
125  * o Added missing (u_char *) cast in RnddevRead() function.
126  * o Changed copyright to 3-clause BSD license and cleaned up the layout
127  *   of this file.
128  *
129  * For a proper changelog, refer to the version control history of this
130  * file.
131  */
132
133 #include <sys/types.h>
134 #include <sys/kernel.h>
135 #include <sys/systm.h>
136 #include <sys/poll.h>
137 #include <sys/event.h>
138 #include <sys/random.h>
139 #include <sys/systimer.h>
140 #include <sys/time.h>
141 #include <sys/proc.h>
142 #include <sys/lock.h>
143 #include <sys/sysctl.h>
144 #include <sys/spinlock.h>
145 #include <sys/csprng.h>
146 #include <machine/atomic.h>
147 #include <machine/clock.h>
148
149 #include <sys/spinlock2.h>
150
151 struct csprng_state csprng_state;
152
153 /*
154  * Portability note: The u_char/unsigned char type is used where
155  * uint8_t from <stdint.h> or u_int8_t from <sys/types.h> should really
156  * be being used. On FreeBSD, it is safe to make the assumption that these
157  * different types are equivalent (on all architectures).
158  * The FreeBSD <sys/crypto/rc4> module also makes this assumption.
159  */
160
161 /*------------------------------ IBAA ----------------------------------*/
162
163 /*-------------------------- IBAA CSPRNG -------------------------------*/
164
165 /*
166  * NOTE: The original source code from which this source code (IBAA)
167  *       was taken has no copyright/license. The algorithm has no patent
168  *       and is freely/publicly available from:
169  *
170  *           http://www.burtleburtle.net/bob/rand/isaac.html
171  */
172
173 /*
174  * ^ means XOR, & means bitwise AND, a<<b means shift a by b.
175  * barrel(a) shifts a 19 bits to the left, and bits wrap around
176  * ind(x) is (x AND 255), or (x mod 256)
177  */
178 typedef u_int32_t       u4;   /* unsigned four bytes, 32 bits */
179
180 #define ALPHA           (8)
181 #define SIZE            (1 << ALPHA)
182 #define MASK            (SIZE - 1)
183 #define ind(x)          ((x) & (SIZE - 1))
184 #define barrel(a)       (((a) << 20) ^ ((a) >> 12))  /* beta=32,shift=20 */
185  
186 static void IBAA
187 (
188         u4 *m,          /* Memory: array of SIZE ALPHA-bit terms */
189         u4 *r,          /* Results: the sequence, same size as m */
190         u4 *aa,         /* Accumulator: a single value */
191         u4 *bb,         /* the previous result */
192         u4 *counter     /* counter */
193 )
194 {
195         u4 a, b, x, y, i;
196  
197         a = *aa;
198         b = *bb + *counter;
199         ++*counter;
200         for (i = 0; i < SIZE; ++i) {
201                 x = m[i];  
202                 a = barrel(a) + m[ind(i + (SIZE / 2))]; /* set a */
203                 m[i] = y = m[ind(x)] + a + b;           /* set m */
204                 r[i] = b = m[ind(y >> ALPHA)] + x;      /* set r */
205         }
206         *bb = b; *aa = a;
207 }
208
209 /*-------------------------- IBAA CSPRNG -------------------------------*/
210
211
212 static u4       IBAA_memory[SIZE];
213 static u4       IBAA_results[SIZE];
214 static u4       IBAA_aa;
215 static u4       IBAA_bb;
216 static u4       IBAA_counter;
217
218 static volatile int IBAA_byte_index;
219
220
221 static void     IBAA_Init(void);
222 static void     IBAA_Call(void);
223 static void     IBAA_Seed(const u_int32_t val);
224 static u_char   IBAA_Byte(void);
225
226 /*
227  * Initialize IBAA. 
228  */
229 static void
230 IBAA_Init(void)
231 {
232         size_t  i;
233
234         for (i = 0; i < SIZE; ++i) {
235                 IBAA_memory[i] = i;
236         }
237         IBAA_aa = IBAA_bb = 0;
238         IBAA_counter = 0;
239         IBAA_byte_index = sizeof(IBAA_results); /* force IBAA_Call() */
240 }
241
242 /*
243  * PRIVATE: Call IBAA to produce 256 32-bit u4 results.
244  */
245 static void
246 IBAA_Call (void)
247 {
248         IBAA(IBAA_memory, IBAA_results, &IBAA_aa, &IBAA_bb, &IBAA_counter);
249         IBAA_byte_index = 0;
250 }
251
252 /*
253  * Add a 32-bit u4 seed value into IBAAs memory.  Mix the low 4 bits 
254  * with 4 bits of PNG data to reduce the possibility of a seeding-based
255  * attack.
256  */
257 static void
258 IBAA_Seed (const u_int32_t val)
259 {
260         static int memIndex;
261         u4 *iptr;
262
263         iptr = &IBAA_memory[memIndex & MASK];
264         *iptr = ((*iptr << 3) | (*iptr >> 29)) + (val ^ (IBAA_Byte() & 15));
265         ++memIndex;
266 }
267
268 static void
269 IBAA_Vector (const char *buf, int bytes)
270 {
271         int i;
272
273         while (bytes >= sizeof(int)) {
274                 IBAA_Seed(*(const int *)buf);
275                 buf += sizeof(int);
276                 bytes -= sizeof(int);
277         }
278
279         /*
280          * Warm up the generator to get rid of weak initial states.
281          */
282         for (i = 0; i < 10; ++i)
283                 IBAA_Call();
284 }
285
286 /*
287  * Extract a byte from IBAAs 256 32-bit u4 results array. 
288  *
289  * NOTE: This code is designed to prevent MP races from taking
290  * IBAA_byte_index out of bounds.
291  */
292 static u_char
293 IBAA_Byte(void)
294 {
295         u_char result;
296         int index;
297
298         index = IBAA_byte_index;
299         if (index == sizeof(IBAA_results)) {
300                 IBAA_Call();
301                 index = 0;
302         }
303         result = ((u_char *)IBAA_results)[index];
304         IBAA_byte_index = index + 1;
305         return result;
306 }
307
308 /*------------------------------ IBAA ----------------------------------*/
309
310
311 /*------------------------------- L15 ----------------------------------*/
312
313 /*
314  * IMPORTANT NOTE: LByteType must be exactly 8-bits in size or this software
315  * will not function correctly.
316  */
317 typedef unsigned char   LByteType;
318
319 #define L15_STATE_SIZE  256
320
321 static LByteType        L15_x, L15_y;
322 static LByteType        L15_start_x;
323 static LByteType        L15_state[L15_STATE_SIZE];
324
325 /*
326  * PRIVATE FUNCS:
327  */
328
329 static void             L15_Swap(const LByteType pos1, const LByteType pos2);
330 static void             L15_InitState(void);
331 static void             L15_KSA(const LByteType * const key,
332                                 const size_t keyLen);
333 static void             L15_Discard(const LByteType numCalls);
334
335 /*
336  * PUBLIC INTERFACE:
337  */
338 static void             L15(const LByteType * const key, const size_t keyLen);
339 static LByteType        L15_Byte(void);
340 static void             L15_Vector(const LByteType * const key,
341                                 const size_t keyLen);
342
343 static __inline void
344 L15_Swap(const LByteType pos1, const LByteType pos2)
345 {
346         const LByteType save1 = L15_state[pos1];
347
348         L15_state[pos1] = L15_state[pos2];
349         L15_state[pos2] = save1;
350 }
351
352 static void
353 L15_InitState (void)
354 {
355         size_t i;
356         for (i = 0; i < L15_STATE_SIZE; ++i)
357                 L15_state[i] = i;
358 }
359
360 #define  L_SCHEDULE(xx)                                         \
361                                                                 \
362 for (i = 0; i < L15_STATE_SIZE; ++i) {                          \
363     L15_Swap(i, (stateIndex += (L15_state[i] + (xx))));         \
364 }
365
366 static void
367 L15_KSA (const LByteType * const key, const size_t keyLen)
368 {
369         size_t  i, keyIndex;
370         static LByteType stateIndex = 0;
371
372         for (keyIndex = 0; keyIndex < keyLen; ++keyIndex) {
373                 L_SCHEDULE(key[keyIndex]);
374         }
375         L_SCHEDULE(keyLen);
376 }
377
378 static void
379 L15_Discard(const LByteType numCalls)
380 {
381         LByteType i;
382         for (i = 0; i < numCalls; ++i) {
383                 (void)L15_Byte();
384         }
385 }
386
387
388 /*
389  * PUBLIC INTERFACE:
390  */
391 static void
392 L15(const LByteType * const key, const size_t keyLen)
393 {
394         L15_x = L15_start_x = 0;
395         L15_y = L15_STATE_SIZE - 1;
396         L15_InitState();
397         L15_KSA(key, keyLen);
398         L15_Discard(L15_Byte());
399 }
400
401 static LByteType
402 L15_Byte(void)
403 {
404         LByteType z;
405
406         L15_Swap(L15_state[L15_x], L15_y);
407         z = (L15_state [L15_x++] + L15_state[L15_y--]);
408         if (L15_x == L15_start_x) {
409                 --L15_y;
410         }
411         return (L15_state[z]);
412 }
413
414 static void
415 L15_Vector (const LByteType * const key, const size_t keyLen)
416 {
417         L15_KSA(key, keyLen);
418 }
419
420 /*------------------------------- L15 ----------------------------------*/
421
422 /************************************************************************
423  *                              KERNEL INTERFACE                        *
424  ************************************************************************
425  *
426  * By Robin J Carey, Matthew Dillon and Alex Hornung.
427  */
428
429 static int rand_thread_value;
430 static void NANOUP_EVENT(void);
431 static thread_t rand_td;
432 static struct spinlock rand_spin;
433
434 static int sysctl_kern_random(SYSCTL_HANDLER_ARGS);
435
436 static int nrandevents;
437 static int rand_mode = 2;
438 static struct systimer systimer_rand;
439
440 static int sysctl_kern_rand_mode(SYSCTL_HANDLER_ARGS);
441
442 SYSCTL_INT(_kern, OID_AUTO, nrandevents, CTLFLAG_RD, &nrandevents, 0, "");
443 SYSCTL_PROC(_kern, OID_AUTO, random, CTLFLAG_RD | CTLFLAG_ANYBODY, 0, 0,
444                 sysctl_kern_random, "I", "Acquire random data");
445 SYSCTL_PROC(_kern, OID_AUTO, rand_mode, CTLTYPE_STRING | CTLFLAG_RW, NULL, 0,
446     sysctl_kern_rand_mode, "A", "RNG mode (csprng, ibaa or mixed)");
447
448
449 /*
450  * Called from early boot (pre-SMP)
451  */
452 void
453 rand_initialize(void)
454 {
455         struct timespec now;
456         int i;
457
458         csprng_init(&csprng_state);
459 #if 0
460         /*
461          * XXX: we do the reseeding when someone uses the RNG instead
462          * of regularly using init_reseed (which initializes a callout)
463          * to avoid unnecessary and regular reseeding.
464          */
465         csprng_init_reseed(&csprng_state);
466 #endif
467
468
469         spin_init(&rand_spin, "randinit");
470
471         /* Initialize IBAA. */
472         IBAA_Init();
473
474         /* Initialize L15. */
475         nanouptime(&now);
476         L15((const LByteType *)&now.tv_nsec, sizeof(now.tv_nsec));
477         for (i = 0; i < (SIZE / 2); ++i) {
478                 nanotime(&now);
479                 add_buffer_randomness_src((const uint8_t *)&now.tv_nsec,
480                     sizeof(now.tv_nsec), RAND_SRC_TIMING);
481                 nanouptime(&now);
482                 add_buffer_randomness_src((const uint8_t *)&now.tv_nsec,
483                     sizeof(now.tv_nsec), RAND_SRC_TIMING);
484         }
485
486         /*
487          * Warm up the generator to get rid of weak initial states.
488          */
489         for (i = 0; i < 10; ++i)
490                 IBAA_Call();
491 }
492
493 /*
494  * Keyboard events
495  */
496 void
497 add_keyboard_randomness(u_char scancode)
498 {
499         spin_lock(&rand_spin);
500         L15_Vector((const LByteType *) &scancode, sizeof (scancode));
501         spin_unlock(&rand_spin);
502         add_interrupt_randomness(0);
503 }
504
505 /*
506  * Interrupt events.  This is SMP safe and allowed to race.
507  *
508  * This adjusts rand_thread_value which will be incorporated into the next
509  * time-buffered seed.  It does not effect the seeding period per-say.
510  */
511 void
512 add_interrupt_randomness(int intr)
513 {
514         if (tsc_present) {
515                 rand_thread_value = (rand_thread_value << 4) ^ 1 ^
516                 ((int)rdtsc() % 151);
517         }
518         ++rand_thread_value;                            /* ~1 bit */
519 }
520
521 /*
522  * True random number source
523  */
524 int
525 add_buffer_randomness(const char *buf, int bytes)
526 {
527         spin_lock(&rand_spin);
528         L15_Vector((const LByteType *)buf, bytes);
529         IBAA_Vector(buf, bytes);
530         spin_unlock(&rand_spin);
531
532         atomic_add_int(&nrandevents, 1);
533
534         csprng_add_entropy(&csprng_state, RAND_SRC_UNKNOWN,
535             (const uint8_t *)buf, bytes, 0);
536
537         return 0;
538 }
539
540
541 int
542 add_buffer_randomness_src(const char *buf, int bytes, int srcid)
543 {
544         spin_lock(&rand_spin);
545         L15_Vector((const LByteType *)buf, bytes);
546         IBAA_Vector(buf, bytes);
547         spin_unlock(&rand_spin);
548
549         atomic_add_int(&nrandevents, 1);
550
551         csprng_add_entropy(&csprng_state, srcid & 0xff,
552             (const uint8_t *)buf, bytes, 0);
553
554         return 0;
555 }
556
557
558 /*
559  * Kqueue filter (always succeeds)
560  */
561 int
562 random_filter_read(struct knote *kn, long hint)
563 {
564         return (1);
565 }
566
567 /*
568  * Heavy weight random number generator.  May return less then the
569  * requested number of bytes.
570  *
571  * Instead of stopping early,
572  */
573 u_int
574 read_random(void *buf, u_int nbytes)
575 {
576         int i, j;
577
578         if (rand_mode == 0) {
579                 /* Only use CSPRNG */
580                 i = csprng_get_random(&csprng_state, buf, nbytes, 0);
581         } else if (rand_mode == 1) {
582                 /* Only use IBAA */
583                 spin_lock(&rand_spin);
584                 for (i = 0; i < nbytes; i++)
585                         ((u_char *)buf)[i] = IBAA_Byte();
586                 spin_unlock(&rand_spin);
587         } else {
588                 /* Mix both CSPRNG and IBAA */
589                 i = csprng_get_random(&csprng_state, buf, nbytes, 0);
590                 spin_lock(&rand_spin);
591                 for (j = 0; j < i; j++)
592                         ((u_char *)buf)[j] ^= IBAA_Byte();
593                 spin_unlock(&rand_spin);
594         }
595
596         add_interrupt_randomness(0);
597         return (i > 0) ? i : 0;
598 }
599
600 /*
601  * Heavy weight random number generator.  Must return the requested
602  * number of bytes.
603  */
604 u_int
605 read_random_unlimited(void *buf, u_int nbytes)
606 {
607         u_int i;
608
609         spin_lock(&rand_spin);
610         for (i = 0; i < nbytes; ++i)
611                 ((u_char *)buf)[i] = IBAA_Byte();
612         spin_unlock(&rand_spin);
613         add_interrupt_randomness(0);
614         return (i);
615 }
616
617 /*
618  * Read random data via sysctl().
619  */
620 static
621 int
622 sysctl_kern_random(SYSCTL_HANDLER_ARGS)
623 {
624         char buf[64];
625         size_t n;
626         size_t r;
627         int error = 0;
628
629         n = req->oldlen;
630         if (n > 1024 * 1024)
631                 n = 1024 * 1024;
632         while (n > 0) {
633                 if ((r = n) > sizeof(buf))
634                         r = sizeof(buf);
635                 read_random_unlimited(buf, r);
636                 error = SYSCTL_OUT(req, buf, r);
637                 if (error)
638                         break;
639                 n -= r;
640         }
641         return(error);
642 }
643
644 /*
645  * Change the random mode via sysctl().
646  */
647 static
648 const char *
649 rand_mode_to_str(int mode)
650 {
651         switch (mode) {
652         case 0:
653                 return "csprng";
654         case 1:
655                 return "ibaa";
656         case 2:
657                 return "mixed";
658         default:
659                 return "unknown";
660         }
661 }
662
663 static
664 int
665 sysctl_kern_rand_mode(SYSCTL_HANDLER_ARGS)
666 {
667         char mode[32];
668         int error;
669
670         strncpy(mode, rand_mode_to_str(rand_mode), sizeof(mode)-1);
671         error = sysctl_handle_string(oidp, mode, sizeof(mode), req);
672         if (error || req->newptr == NULL)
673             return error;
674
675         if ((strncmp(mode, "csprng", sizeof(mode))) == 0)
676                 rand_mode = 0;
677         else if ((strncmp(mode, "ibaa", sizeof(mode))) == 0)
678                 rand_mode = 1;
679         else if ((strncmp(mode, "mixed", sizeof(mode))) == 0)
680                 rand_mode = 2;
681         else
682                 error = EINVAL;
683
684         return error;
685 }
686
687 /*
688  * Random number generator helper thread.  This limits code overhead from
689  * high frequency events by delaying the clearing of rand_thread_value.
690  *
691  * This is a time-buffered loop, with a randomizing delay.  Note that interrupt
692  * entropy does not cause the thread to wakeup any faster, but does improve the
693  * quality of the entropy produced.
694  */
695 static
696 void
697 rand_thread_loop(void *dummy)
698 {
699         int64_t count;
700
701         for (;;) {
702                 /*
703                  * Generate entropy.
704                  */
705                 NANOUP_EVENT();
706                 spin_lock(&rand_spin);
707                 count = (uint8_t)L15_Byte();
708                 spin_unlock(&rand_spin);
709
710                 /*
711                  * Calculate 1/10 of a second to 2/10 of a second, fine-grained
712                  * using a L15_Byte() feedback.
713                  *
714                  * Go faster in the first 1200 seconds after boot.  This effects
715                  * the time-after-next interrupt (pipeline delay).
716                  */
717                 count = sys_cputimer->freq * (count + 256) / (256 * 10);
718                 if (time_uptime < 120)
719                         count = count / 10 + 1;
720                 systimer_rand.periodic = count;
721
722                 tsleep(rand_td, 0, "rwait", 0);
723         }
724 }
725
726 /*
727  * Systimer trigger - fine-grained random trigger
728  */
729 static
730 void
731 rand_thread_wakeup(struct systimer *timer, int in_ipi, struct intrframe *frame)
732 {
733         wakeup(rand_td);
734 }
735
736 static
737 void
738 rand_thread_init(void)
739 {
740         systimer_init_periodic_nq(&systimer_rand, rand_thread_wakeup, NULL, 25);
741         lwkt_create(rand_thread_loop, NULL, &rand_td, NULL, 0, 0, "random");
742 }
743
744 SYSINIT(rand, SI_SUB_HELPER_THREADS, SI_ORDER_ANY, rand_thread_init, 0);
745
746 /*
747  * Caller is time-buffered.  Incorporate any accumulated interrupt randomness
748  * as well as the high frequency bits of the TSC.
749  *
750  * A delta nanoseconds value is used to remove absolute time from the generated
751  * entropy.  Even though we are pushing 32 bits, this entropy is probably only
752  * good for one or two bits without any interrupt sources, and possibly 8 bits with.
753  */
754 static void
755 NANOUP_EVENT(void)
756 {
757         static struct timespec  last;
758         struct timespec         now;
759         int                     nsec;
760
761         /*
762          * Delta nanoseconds since last event
763          */
764         nanouptime(&now);
765         nsec = now.tv_nsec - last.tv_nsec;
766         last = now;
767
768         /*
769          * Interrupt randomness.
770          */
771         nsec ^= rand_thread_value;
772
773         /*
774          * The TSC, if present, generally has an even higher
775          * resolution.  Integrate a portion of it into our seed.
776          */
777         if (tsc_present)
778                 nsec ^= (rdtsc() & 255) << 8;
779
780         /* 
781          * Ok.
782          */
783
784         add_buffer_randomness_src((const uint8_t *)&nsec, sizeof(nsec), RAND_SRC_INTR);
785 }
786