[PATCH 1/4] bitops: Add single_bit_set()

From: Matti Vaittinen
Date: Mon Nov 22 2021 - 06:03:37 EST


There are cases when it is useful to check a bit-mask has only one bit
set. Add a generic helper for it instead of baking own one for each
user.

Signed-off-by: Matti Vaittinen <matti.vaittinen@xxxxxxxxxxxxxxxxx>
---
I am not at all sure what would be the best place for this. Please let
me know if you think some other file would be more appropriate.
---
include/linux/bitops.h | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)

diff --git a/include/linux/bitops.h b/include/linux/bitops.h
index 5e62e2383b7f..dd6c7baed3d3 100644
--- a/include/linux/bitops.h
+++ b/include/linux/bitops.h
@@ -66,6 +66,26 @@ extern unsigned long __sw_hweight64(__u64 w);
(start) < (size); \
(start) = find_next_clump8(&(clump), (bits), (size), (start) + 8))

+/**
+ * single_bit_set - check if only one bit is set in value
+ * @bits: value to check
+ * @bits_to_check: how many bits we should scan
+ *
+ * Return: true if only one of the checked bits is set, othervice return false.
+ */
+static inline bool single_bit_set(const unsigned long bits, int bits_to_check)
+{
+ int bit;
+
+ bit = find_first_bit(&bits, bits_to_check);
+ if (bit == bits_to_check)
+ return false;
+
+ bit = find_next_bit(&bits, bits_to_check, bit + 1);
+
+ return (bit == bits_to_check);
+}
+
static inline int get_bitmask_order(unsigned int count)
{
int order;
--
2.31.1


--
Matti Vaittinen, Linux device drivers
ROHM Semiconductors, Finland SWDC
Kiviharjunlenkki 1E
90220 OULU
FINLAND

~~~ "I don't think so," said Rene Descartes. Just then he vanished ~~~
Simon says - in Latin please.
~~~ "non cogito me" dixit Rene Descarte, deinde evanescavit ~~~
Thanks to Simon Glass for the translation =]

Attachment: signature.asc
Description: PGP signature