1 #ifndef XC_BITOPS_H
2 #define XC_BITOPS_H 1
3
4 /* bitmap operations for single threaded access */
5
6 #include <stdlib.h>
7 #include <string.h>
8
9 #ifdef __LP64__
10 #define BITS_PER_LONG 64
11 #else
12 #define BITS_PER_LONG 32
13 #endif
14
15 #define BITMAP_ENTRY(_nr,_bmap) ((_bmap))[(_nr) / 8]
16 #define BITMAP_SHIFT(_nr) ((_nr) % 8)
17
18 /* calculate required space for number of bytes needed to hold nr_bits */
bitmap_size(unsigned long nr_bits)19 static inline unsigned long bitmap_size(unsigned long nr_bits)
20 {
21 return (nr_bits + 7) / 8;
22 }
23
bitmap_alloc(unsigned long nr_bits)24 static inline void *bitmap_alloc(unsigned long nr_bits)
25 {
26 unsigned long longs;
27
28 longs = (nr_bits + BITS_PER_LONG - 1) / BITS_PER_LONG;
29 return calloc(longs, sizeof(unsigned long));
30 }
31
bitmap_set(void * addr,unsigned long nr_bits)32 static inline void bitmap_set(void *addr, unsigned long nr_bits)
33 {
34 memset(addr, 0xff, bitmap_size(nr_bits));
35 }
36
bitmap_clear(void * addr,unsigned long nr_bits)37 static inline void bitmap_clear(void *addr, unsigned long nr_bits)
38 {
39 memset(addr, 0, bitmap_size(nr_bits));
40 }
41
test_bit(unsigned long nr,const void * _addr)42 static inline int test_bit(unsigned long nr, const void *_addr)
43 {
44 const char *addr = _addr;
45 return (BITMAP_ENTRY(nr, addr) >> BITMAP_SHIFT(nr)) & 1;
46 }
47
clear_bit(unsigned long nr,void * _addr)48 static inline void clear_bit(unsigned long nr, void *_addr)
49 {
50 char *addr = _addr;
51 BITMAP_ENTRY(nr, addr) &= ~(1UL << BITMAP_SHIFT(nr));
52 }
53
set_bit(unsigned long nr,void * _addr)54 static inline void set_bit(unsigned long nr, void *_addr)
55 {
56 char *addr = _addr;
57 BITMAP_ENTRY(nr, addr) |= (1UL << BITMAP_SHIFT(nr));
58 }
59
test_and_clear_bit(unsigned long nr,void * addr)60 static inline int test_and_clear_bit(unsigned long nr, void *addr)
61 {
62 int oldbit = test_bit(nr, addr);
63 clear_bit(nr, addr);
64 return oldbit;
65 }
66
test_and_set_bit(unsigned long nr,void * addr)67 static inline int test_and_set_bit(unsigned long nr, void *addr)
68 {
69 int oldbit = test_bit(nr, addr);
70 set_bit(nr, addr);
71 return oldbit;
72 }
73
bitmap_or(void * _dst,const void * _other,unsigned long nr_bits)74 static inline void bitmap_or(void *_dst, const void *_other,
75 unsigned long nr_bits)
76 {
77 char *dst = _dst;
78 const char *other = _other;
79 unsigned long i;
80 for ( i = 0; i < bitmap_size(nr_bits); ++i )
81 dst[i] |= other[i];
82 }
83
84 #endif /* XC_BITOPS_H */
85