[PATCH 2/2] random: fix locking for crng_init in crng_reseed()

Dominik Brodowski
2022-02-05T10:35:15Z

crng_init is protected by primary_crng->lock. Therefore, we need
to hold this lock when increasing crng_init to 2. As we shouldn't
hold this lock for too long, only hold it for crng_finalize_init(),
and split out the parts which can be delayed to crng_late_init().

If crng_finalize_init() cannot proceed due to workqueues not yet
being available, it is called again in rand_initialize(). Then, we
do not need to call crng_late_init(): At this time, the boot
process is still so early that there are no other processes to wake
up.

Signed-off-by: Dominik Brodowski <linux@dominikbrodowski.net>
---
drivers/char/random.c | 20 +++++++++++++++-----
1 file changed, 15 insertions(+), 5 deletions(-)

diff --git a/drivers/char/random.c b/drivers/char/random.c
index 2df08d05e850..c70a9abbd8cb 100644
--- a/drivers/char/random.c
+++ b/drivers/char/random.c
@@ -557,19 +557,24 @@ static void __init crng_initialize_primary(void)
primary_crng.init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
}

-static void crng_finalize_init(void)
+static bool crng_finalize_init(void)
{
if (!system_wq) {
/* We can't call numa_crng_init until we have workqueues,
* so mark this for processing later. */
crng_need_final_init = true;
- return;
+ return false;
}

invalidate_batched_entropy();
numa_crng_init();
crng_init = 2;
crng_need_final_init = false;
+ return true;
+}
+
+static void crng_late_init(void)
+{
process_random_ready_list();
wake_up_interruptible(&crng_init_wait);
kill_fasync(&fasync, SIGIO, POLL_IN);
@@ -710,6 +715,7 @@ static int crng_slow_load(const u8 *cp, size_t len)

static void crng_reseed(struct crng_state *crng)
{
+ bool needs_late_init = false;
unsigned long flags;
int i;
union {
@@ -744,9 +750,11 @@ static void crng_reseed(struct crng_state *crng)
}
memzero_explicit(&buf, sizeof(buf));
WRITE_ONCE(crng->init_time, jiffies);
- spin_unlock_irqrestore(&crng->lock, flags);
if (crng == &primary_crng && crng_init < 2)
- crng_finalize_init();
+ needs_late_init = crng_finalize_init();
+ spin_unlock_irqrestore(&crng->lock, flags);
+ if (needs_late_init)
+ crng_late_init();
}

static void _extract_crng(struct crng_state *crng, u8 out[CHACHA_BLOCK_SIZE])
@@ -1383,8 +1391,10 @@ static void __init init_std_data(void)
int __init rand_initialize(void)
{
init_std_data();
- if (crng_need_final_init)
+ if (crng_need_final_init) {
crng_finalize_init();
+ pr_notice("crng init done\n");
+ }
crng_initialize_primary();
crng_global_init_time = jiffies;
if (ratelimit_disable) {
--
2.35.1