0
0
mirror of https://gitlab.nic.cz/labs/bird.git synced 2025-01-08 18:11:54 +00:00
bird/sysdep/unix/random.c
Ondrej Zajicek 0e39ed0004 Nest: Parametric network hashes
Currently, all fib hash tables use the same hashing function. This leads
to a situation where feeding routes through a pipe from one table to
another causes significant number of collisions, as routes are fed in the
order of increasing hash values, but dst tables are sized based on the
number of stored routes.

The patch makes fib hashing function parametric and chooses random
parameter for each table. Also generally improves quality of hashing
functions.

Unfortunately, while this patch fixes the issue with initial collisions,
having different hashing functions leads to 2x slowdown of pipe feeding,
presumably due to worse cache behavior in dst tables. Also, the original
issue significantly affects just the initial part of feed, when the dst
table is small, so even ideal fix would not improve that much.

Therefore, no merge for this patch.
2022-06-14 18:15:30 +02:00

110 lines
1.8 KiB
C

/*
* BIRD Internet Routing Daemon -- Random Numbers
*
* (c) 2000 Martin Mares <mj@ucw.cz>
*
* Can be freely distributed and used under the terms of the GNU GPL.
*/
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "sysdep/config.h"
#include "nest/bird.h"
#ifdef HAVE_GETRANDOM
#include <sys/random.h>
#endif
u32
random_u32(void)
{
u32 rand_low, rand_high;
rand_low = random();
rand_high = random();
return (rand_low & 0xffff) | ((rand_high & 0xffff) << 16);
}
/* Generate random hash parameter (odd, bits roughly balanced) */
u32
random_hash_param(void)
{
while (1)
{
u32 p = random_u32() | 1;
u32 c = u32_popcount(p);
if ((c >= 12) && (c <= 20))
return p;
}
}
/* If there is no getrandom() / getentropy(), use /dev/urandom */
#if !defined(HAVE_GETRANDOM) && !defined(HAVE_GETENTROPY)
#define HAVE_URANDOM_FD 1
static int urandom_fd = -1;
int
read_urandom_fd(void *buf, uint count)
{
if (urandom_fd < 0)
{
urandom_fd = open("/dev/urandom", O_RDONLY);
if (urandom_fd < 0)
die("Cannot open /dev/urandom: %m");
}
return read(urandom_fd, buf, count);
}
#endif
void
random_init(void)
{
uint seed;
/* Get random bytes to trip any errors early and to seed random() */
random_bytes(&seed, sizeof(seed));
srandom(seed);
}
void
random_bytes(void *buf, size_t count)
{
ASSERT(count <= 256);
while (count > 0)
{
int n = -1;
#if defined(HAVE_GETRANDOM)
n = getrandom(buf, count, 0);
#elif defined(HAVE_GETENTROPY)
n = getentropy(buf, count);
n = !n ? (int) count : n;
#elif defined(HAVE_URANDOM_FD)
n = read_urandom_fd(buf, count);
#endif
if (n < 0)
{
if (errno == EINTR)
continue;
die("Cannot get random bytes: %m");
}
buf += n;
count -= n;
}
}