lib/math/prime_numbers.c

Source file repositories/reference/linux-study-clean/lib/math/prime_numbers.c

File Facts

System
Linux kernel
Corpus path
lib/math/prime_numbers.c
Extension
.c
Size
5598 bytes
Lines
263
Domain
Kernel Services
Bucket
lib
Inferred role
Kernel Services: exported/initcall integration point
Status
integration implementation candidate

Why This File Exists

Shared kernel service surface used by multiple subsystems, including helpers, cryptography, virtualization support, and async I/O infrastructure.

Dependency Surface

Detected Declarations

Annotated Snippet

// SPDX-License-Identifier: GPL-2.0-only

#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/prime_numbers.h>
#include <linux/slab.h>

#include "prime_numbers_private.h"

#if BITS_PER_LONG == 64
static const struct primes small_primes = {
	.last = 61,
	.sz = 64,
	.primes = {
		BIT(2) |
		BIT(3) |
		BIT(5) |
		BIT(7) |
		BIT(11) |
		BIT(13) |
		BIT(17) |
		BIT(19) |
		BIT(23) |
		BIT(29) |
		BIT(31) |
		BIT(37) |
		BIT(41) |
		BIT(43) |
		BIT(47) |
		BIT(53) |
		BIT(59) |
		BIT(61)
	}
};
#elif BITS_PER_LONG == 32
static const struct primes small_primes = {
	.last = 31,
	.sz = 32,
	.primes = {
		BIT(2) |
		BIT(3) |
		BIT(5) |
		BIT(7) |
		BIT(11) |
		BIT(13) |
		BIT(17) |
		BIT(19) |
		BIT(23) |
		BIT(29) |
		BIT(31)
	}
};
#else
#error "unhandled BITS_PER_LONG"
#endif

static DEFINE_MUTEX(lock);
static const struct primes __rcu *primes = RCU_INITIALIZER(&small_primes);

#if IS_ENABLED(CONFIG_PRIME_NUMBERS_KUNIT_TEST)
/*
 * Calls the callback under RCU lock. The callback must not retain
 * the primes pointer.
 */
void with_primes(void *ctx, primes_fn fn)
{
	rcu_read_lock();
	fn(ctx, rcu_dereference(primes));
	rcu_read_unlock();
}
EXPORT_SYMBOL(with_primes);

EXPORT_SYMBOL(slow_is_prime_number);

#else
static
#endif
bool slow_is_prime_number(unsigned long x)
{
	unsigned long y = int_sqrt(x);

	while (y > 1) {
		if ((x % y) == 0)
			break;
		y--;
	}

	return y == 1;
}

Annotation

Implementation Notes