[v1,2/2] x86: Use rdtsc for generating entropy for random_bits

Message ID 20220328220936.2724834-2-goldstein.w.n@gmail.com
State Dropped
Headers
Series [v1,1/2] random-bits: Factor out entropy generating function |

Checks

Context Check Description
dj/TryBot-apply_patch success Patch applied to master at the time it was sent
dj/TryBot-32bit success Build for i686

Commit Message

Noah Goldstein March 28, 2022, 10:09 p.m. UTC
  `rdtsc` generates a comparable amount of entropy and is faster than
`clock_gettime`.

Entropy:
random_bits w/ rdtsc:
    Entropy = 7.805972 bits per byte.

random_bits w/ clock_gettime:
    Entropy = 7.806116 bits per byte.

Measured entropy of `random_bits` using `rdtsc` vs `clock_gettime`
using ent: https://www.fourmilab.ch/random/

Performance:
random_bits w/:   rdtsc,  clock_gettime

    throughput:   16.35,  38.36
       latency:   23.68,  54.15

Time as cycles (measured with `rdtsc`) / Trials. benchmarks done on
Tigerlake.
---
 sysdeps/x86_64/random-bits-entropy.h | 36 ++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
 create mode 100644 sysdeps/x86_64/random-bits-entropy.h
  

Patch

diff --git a/sysdeps/x86_64/random-bits-entropy.h b/sysdeps/x86_64/random-bits-entropy.h
new file mode 100644
index 0000000000..1e96659aa3
--- /dev/null
+++ b/sysdeps/x86_64/random-bits-entropy.h
@@ -0,0 +1,36 @@ 
+/* Function for generating entropy quick on x86 with rdtsc.
+   Copyright (C) 2022 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <https://www.gnu.org/licenses/>.  */
+
+#include <stdint.h>
+
+/* rdtsc is faster than generic (clock_gettime) and has roughly the same
+   entropy. Result of filling a file using random_bits with rdtsc vs
+   clock_gettime as an entropy function:
+
+   $> ent gettime-random.txt
+      Entropy = 7.806116 bits per byte.
+
+   $> ent rdtsc-random.txt
+      Entropy = 7.805972 bits per byte.
+ */
+
+static inline uint32_t
+random_bits_entropy (void)
+{
+  return __builtin_ia32_rdtsc ();
+}