[linux-lvm] [PATCH] misc: use getrandom(GRND_INSECURE) instead of /dev/urandom when possible

Jason A. Donenfeld Jason at zx2c4.com
Fri Apr 8 15:30:54 UTC 2022


getrandom(GRND_INSECURE) is the same as /dev/urandom, except:

- It won't leave a warning in dmesg if used at early boot time, which is
  a common occurance;

- It won't introduce a tiny delay at early boot on newer kernels when
  /dev/urandom tries to opportunistically create jitter entropy;

- It only requires 1 syscall, rather than 3.

Other than that, it returns the same "quality" of randomness as
/dev/urandom, and never blocks.

It's only available on kernels ≥5.6, so we try to use it, cache the
result of that attempt, and fall back to /dev/urandom if it didn't work
out.
---
 lib/misc/lvm-wrappers.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/lib/misc/lvm-wrappers.c b/lib/misc/lvm-wrappers.c
index 2e0cfd514..1239f1085 100644
--- a/lib/misc/lvm-wrappers.c
+++ b/lib/misc/lvm-wrappers.c
@@ -16,6 +16,7 @@
 
 #include <unistd.h>
 #include <fcntl.h>
+#include <sys/random.h>
 
 #ifdef UDEV_SYNC_SUPPORT
 #include <libudev.h>
@@ -111,8 +112,17 @@ int lvm_getpagesize(void)
 
 int read_urandom(void *buf, size_t len)
 {
+	static int have_getrandom = -1;
 	int fd;
 
+	if (have_getrandom) {
+		bool success = getrandom(buf, len, GRND_INSECURE) == len;
+		if (have_getrandom == -1)
+			have_getrandom = success;
+		if (success)
+			return 1;
+	}
+
 	/* FIXME: we should stat here, and handle other cases */
 	/* FIXME: use common _io() routine's open/read/close */
 	if ((fd = open("/dev/urandom", O_RDONLY)) < 0) {
-- 
2.35.1



More information about the linux-lvm mailing list