[Concept,03/15] bitops: linux: Add fns() to find N'th set bit

Message ID 20251230234134.906477-4-sjg@u-boot.org
State New
Headers
Series ext4l: Infrastructure and fixes for write support (part K) |

Commit Message

Simon Glass Dec. 30, 2025, 11:41 p.m. UTC
  From: Simon Glass <simon.glass@canonical.com>

Add the fns() function from Linux to find the N'th set bit in a word.
This is needed by lib/find_bit.c which uses it in the FIND_NTH_BIT
macro.

Taken from Linux v6.19

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <simon.glass@canonical.com>
---

 include/linux/bitops.h | 13 +++++++++++++
 1 file changed, 13 insertions(+)
  

Patch

diff --git a/include/linux/bitops.h b/include/linux/bitops.h
index f826d7f3b34..86f7ee492b4 100644
--- a/include/linux/bitops.h
+++ b/include/linux/bitops.h
@@ -194,6 +194,19 @@  static inline unsigned long __ffs64(u64 word)
 	return __ffs((unsigned long)word);
 }
 
+/**
+ * fns - find N'th set bit in a word
+ * @word: The word to search
+ * @n: Bit to find
+ */
+static inline unsigned int fns(unsigned long word, unsigned int n)
+{
+	while (word && n--)
+		word &= word - 1;
+
+	return word ? __ffs(word) : BITS_PER_LONG;
+}
+
 /**
  * __set_bit - Set a bit in memory
  * @nr: the bit to set