1 #ifndef _PERF_LINUX_BITOPS_H_
2 #define _PERF_LINUX_BITOPS_H_
4 #include <linux/kernel.h>
5 #include <linux/compiler.h>
6 #include <asm/hweight.h>
8 #define BITS_PER_LONG __WORDSIZE
9 #define BITS_PER_BYTE 8
10 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
12 #define for_each_set_bit(bit, addr, size) \
13 for ((bit) = find_first_bit((addr), (size)); \
15 (bit) = find_next_bit((addr), (size), (bit) + 1))
17 /* same as for_each_set_bit() but use bit as value to start with */
18 #define for_each_set_bit_cont(bit, addr, size) \
19 for ((bit) = find_next_bit((addr), (size), (bit)); \
21 (bit) = find_next_bit((addr), (size), (bit) + 1))
23 static inline void set_bit(int nr
, unsigned long *addr
)
25 addr
[nr
/ BITS_PER_LONG
] |= 1UL << (nr
% BITS_PER_LONG
);
28 static inline void clear_bit(int nr
, unsigned long *addr
)
30 addr
[nr
/ BITS_PER_LONG
] &= ~(1UL << (nr
% BITS_PER_LONG
));
33 static __always_inline
int test_bit(unsigned int nr
, const unsigned long *addr
)
35 return ((1UL << (nr
% BITS_PER_LONG
)) &
36 (((unsigned long *)addr
)[nr
/ BITS_PER_LONG
])) != 0;
39 static inline unsigned long hweight_long(unsigned long w
)
41 return sizeof(w
) == 4 ? hweight32(w
) : hweight64(w
);
44 #define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
47 * __ffs - find first bit in word.
48 * @word: The word to search
50 * Undefined if no bit exists, so code should check against 0 first.
52 static __always_inline
unsigned long __ffs(unsigned long word
)
56 #if BITS_PER_LONG == 64
57 if ((word
& 0xffffffff) == 0) {
62 if ((word
& 0xffff) == 0) {
66 if ((word
& 0xff) == 0) {
70 if ((word
& 0xf) == 0) {
74 if ((word
& 0x3) == 0) {
78 if ((word
& 0x1) == 0)
84 * Find the first set bit in a memory region.
86 static inline unsigned long
87 find_first_bit(const unsigned long *addr
, unsigned long size
)
89 const unsigned long *p
= addr
;
90 unsigned long result
= 0;
93 while (size
& ~(BITS_PER_LONG
-1)) {
96 result
+= BITS_PER_LONG
;
97 size
-= BITS_PER_LONG
;
102 tmp
= (*p
) & (~0UL >> (BITS_PER_LONG
- size
));
103 if (tmp
== 0UL) /* Are any bits set? */
104 return result
+ size
; /* Nope. */
106 return result
+ __ffs(tmp
);
110 * Find the next set bit in a memory region.
112 static inline unsigned long
113 find_next_bit(const unsigned long *addr
, unsigned long size
, unsigned long offset
)
115 const unsigned long *p
= addr
+ BITOP_WORD(offset
);
116 unsigned long result
= offset
& ~(BITS_PER_LONG
-1);
122 offset
%= BITS_PER_LONG
;
125 tmp
&= (~0UL << offset
);
126 if (size
< BITS_PER_LONG
)
130 size
-= BITS_PER_LONG
;
131 result
+= BITS_PER_LONG
;
133 while (size
& ~(BITS_PER_LONG
-1)) {
136 result
+= BITS_PER_LONG
;
137 size
-= BITS_PER_LONG
;
144 tmp
&= (~0UL >> (BITS_PER_LONG
- size
));
145 if (tmp
== 0UL) /* Are any bits set? */
146 return result
+ size
; /* Nope. */
148 return result
+ __ffs(tmp
);