1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _TOOLS_LINUX_BITOPS_H_
3 #define _TOOLS_LINUX_BITOPS_H_
4
5 #include <asm/types.h>
6 #ifndef __WORDSIZE
7 #define __WORDSIZE (__SIZEOF_LONG__ * 8)
8 #endif
9
10 #ifndef BITS_PER_LONG
11 # define BITS_PER_LONG __WORDSIZE
12 #endif
13 #include <linux/bits.h>
14 #include <linux/compiler.h>
15
16 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
17 #define BITS_TO_U64(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(u64))
18 #define BITS_TO_U32(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(u32))
19 #define BITS_TO_BYTES(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE)
20
21 extern unsigned int __sw_hweight8(unsigned int w);
22 extern unsigned int __sw_hweight16(unsigned int w);
23 extern unsigned int __sw_hweight32(unsigned int w);
24 extern unsigned long __sw_hweight64(__u64 w);
25
26 /*
27 * Include this here because some architectures need generic_ffs/fls in
28 * scope
29 *
30 * XXX: this needs to be asm/bitops.h, when we get to per arch optimizations
31 */
32 #include <asm-generic/bitops.h>
33
34 #define for_each_set_bit(bit, addr, size) \
35 for ((bit) = find_first_bit((addr), (size)); \
36 (bit) < (size); \
37 (bit) = find_next_bit((addr), (size), (bit) + 1))
38
39 #define for_each_clear_bit(bit, addr, size) \
40 for ((bit) = find_first_zero_bit((addr), (size)); \
41 (bit) < (size); \
42 (bit) = find_next_zero_bit((addr), (size), (bit) + 1))
43
44 /* same as for_each_set_bit() but use bit as value to start with */
45 #define for_each_set_bit_from(bit, addr, size) \
46 for ((bit) = find_next_bit((addr), (size), (bit)); \
47 (bit) < (size); \
48 (bit) = find_next_bit((addr), (size), (bit) + 1))
49
hweight_long(unsigned long w)50 static inline unsigned long hweight_long(unsigned long w)
51 {
52 return sizeof(w) == 4 ? hweight32(w) : hweight64(w);
53 }
54
fls_long(unsigned long l)55 static inline unsigned fls_long(unsigned long l)
56 {
57 if (sizeof(l) == 4)
58 return fls(l);
59 return fls64(l);
60 }
61
62 /**
63 * rol32 - rotate a 32-bit value left
64 * @word: value to rotate
65 * @shift: bits to roll
66 */
rol32(__u32 word,unsigned int shift)67 static inline __u32 rol32(__u32 word, unsigned int shift)
68 {
69 return (word << shift) | (word >> ((-shift) & 31));
70 }
71
72 #endif
73