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