summaryrefslogtreecommitdiff
path: root/lib/find_bit.c
diff options
context:
space:
mode:
authorYury Norov [NVIDIA] <yury.norov@gmail.com>2025-06-19 14:26:23 -0400
committerYury Norov <yury.norov@gmail.com>2025-07-08 19:11:57 -0400
commitc56f97c5c71f17d781461d44acb777cd21521b81 (patch)
treeba7b64c3d174d2978426d06e1a3e58eafb61c503 /lib/find_bit.c
parent733923397fd95405a48f165c9b1fbc8c4b0a4681 (diff)
bitmap: generalize node_random()
Generalize node_random() and make it available to general bitmaps and cpumasks users. Notice, find_first_bit() is generally faster than find_nth_bit(), and we employ it when there's a single set bit in the bitmap. See commit 3e061d924fe9c7b4 ("lib/nodemask: optimize node_random for nodemask with single NUMA node"). CC: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: "Yury Norov [NVIDIA]" <yury.norov@gmail.com>
Diffstat (limited to 'lib/find_bit.c')
-rw-r--r--lib/find_bit.c24
1 files changed, 24 insertions, 0 deletions
diff --git a/lib/find_bit.c b/lib/find_bit.c
index 06b6342aa3ae..d4b5a29e3e72 100644
--- a/lib/find_bit.c
+++ b/lib/find_bit.c
@@ -18,6 +18,7 @@
#include <linux/math.h>
#include <linux/minmax.h>
#include <linux/swab.h>
+#include <linux/random.h>
/*
* Common helper for find_bit() function family
@@ -291,3 +292,26 @@ EXPORT_SYMBOL(_find_next_bit_le);
#endif
#endif /* __BIG_ENDIAN */
+
+/**
+ * find_random_bit - find a set bit at random position
+ * @addr: The address to base the search on
+ * @size: The bitmap size in bits
+ *
+ * Returns: a position of a random set bit; >= @size otherwise
+ */
+unsigned long find_random_bit(const unsigned long *addr, unsigned long size)
+{
+ int w = bitmap_weight(addr, size);
+
+ switch (w) {
+ case 0:
+ return size;
+ case 1:
+ /* Performance trick for single-bit bitmaps */
+ return find_first_bit(addr, size);
+ default:
+ return find_nth_bit(addr, size, get_random_u32_below(w));
+ }
+}
+EXPORT_SYMBOL(find_random_bit);