kernel - Update swapcache manual page
[dragonfly.git] / contrib / bind / lib / isc / random.c
blobcc48828ca790e9df6b8eee01fd8dbfaf28fbdb2f
1 /*
2 * Copyright (C) 2004, 2005, 2007, 2009 Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 1999-2003 Internet Software Consortium.
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
18 /* $Id: random.c,v 1.25.128.2 2009/07/16 23:46:44 tbox Exp $ */
20 /*! \file */
22 #include <config.h>
24 #include <stdlib.h>
25 #include <time.h> /* Required for time(). */
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
33 #include <isc/mutex.h>
34 #include <isc/once.h>
35 #include <isc/random.h>
36 #include <isc/string.h>
37 #include <isc/util.h>
39 static isc_once_t once = ISC_ONCE_INIT;
41 static void
42 initialize_rand(void)
44 #ifndef HAVE_ARC4RANDOM
45 unsigned int pid = getpid();
48 * The low bits of pid generally change faster.
49 * Xor them with the high bits of time which change slowly.
51 pid = ((pid << 16) & 0xffff0000) | ((pid >> 16) & 0xffff);
53 srand(time(NULL) ^ pid);
54 #endif
57 static void
58 initialize(void)
60 RUNTIME_CHECK(isc_once_do(&once, initialize_rand) == ISC_R_SUCCESS);
63 void
64 isc_random_seed(isc_uint32_t seed)
66 initialize();
68 #ifndef HAVE_ARC4RANDOM
69 srand(seed);
70 #else
71 arc4random_addrandom((u_char *) &seed, sizeof(isc_uint32_t));
72 #endif
75 void
76 isc_random_get(isc_uint32_t *val)
78 REQUIRE(val != NULL);
80 initialize();
82 #ifndef HAVE_ARC4RANDOM
84 * rand()'s lower bits are not random.
85 * rand()'s upper bit is zero.
87 #if RAND_MAX >= 0xfffff
88 /* We have at least 20 bits. Use lower 16 excluding lower most 4 */
89 *val = ((rand() >> 4) & 0xffff) | ((rand() << 12) & 0xffff0000);
90 #elif RAND_MAX >= 0x7fff
91 /* We have at least 15 bits. Use lower 10/11 excluding lower most 4 */
92 *val = ((rand() >> 4) & 0x000007ff) | ((rand() << 7) & 0x003ff800) |
93 ((rand() << 18) & 0xffc00000);
94 #else
95 #error RAND_MAX is too small
96 #endif
97 #else
98 *val = arc4random();
99 #endif
102 isc_uint32_t
103 isc_random_jitter(isc_uint32_t max, isc_uint32_t jitter) {
104 isc_uint32_t rnd;
106 REQUIRE(jitter < max);
108 if (jitter == 0)
109 return (max);
111 isc_random_get(&rnd);
112 return (max - rnd % jitter);