1 /*
2 * Copyright (c) 2008 Travis Geiselbrecht
3 *
4 * Use of this source code is governed by a MIT-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/MIT
7 */
8 #pragma once
9
10 #include <arch/atomic.h>
11 #include <arch/ops.h>
12 #include <lk/compiler.h>
13
14 __BEGIN_CDECLS
15
16 #define clz(x) __builtin_clz(x)
17 #define ctz(x) __builtin_ctz(x)
18 #define ffs(x) __builtin_ffs(x)
19
20 #define BIT(x, bit) ((x) & (1UL << (bit)))
21 #define BIT_SHIFT(x, bit) (((x) >> (bit)) & 1)
22 #define BITS(x, high, low) ((x) & (((1UL<<((high)+1))-1) & ~((1UL<<(low))-1)))
23 #define BITS_SHIFT(x, high, low) (((x) >> (low)) & ((1UL<<((high)-(low)+1))-1))
24 #define BIT_SET(x, bit) (((x) & (1UL << (bit))) ? 1 : 0)
25
26 #define BITMAP_BITS_PER_WORD (sizeof(unsigned long) * 8)
27 #define BITMAP_NUM_WORDS(x) (((x) + BITMAP_BITS_PER_WORD - 1) / BITMAP_BITS_PER_WORD)
28 #define BITMAP_WORD(x) ((x) / BITMAP_BITS_PER_WORD)
29 #define BITMAP_BIT_IN_WORD(x) ((x) & (BITMAP_BITS_PER_WORD - 1))
30
31 #define BITMAP_BITS_PER_INT (sizeof(unsigned int) * 8)
32 #define BITMAP_BIT_IN_INT(x) ((x) & (BITMAP_BITS_PER_INT - 1))
33 #define BITMAP_INT(x) ((x) / BITMAP_BITS_PER_INT)
34
35 #define BIT_MASK(x) (((x) >= sizeof(unsigned long) * 8) ? (0UL-1) : ((1UL << (x)) - 1))
36
bitmap_set(unsigned long * bitmap,int bit)37 static inline int bitmap_set(unsigned long *bitmap, int bit) {
38 unsigned long mask = 1UL << BITMAP_BIT_IN_INT(bit);
39 return atomic_or(&((int *)bitmap)[BITMAP_INT(bit)], mask) & mask ? 1 : 0;
40 }
41
bitmap_clear(unsigned long * bitmap,int bit)42 static inline int bitmap_clear(unsigned long *bitmap, int bit) {
43 unsigned long mask = 1UL << BITMAP_BIT_IN_INT(bit);
44
45 return atomic_and(&((int *)bitmap)[BITMAP_INT(bit)], ~mask) & mask ? 1:0;
46 }
47
bitmap_test(unsigned long * bitmap,int bit)48 static inline int bitmap_test(unsigned long *bitmap, int bit) {
49 return BIT_SET(bitmap[BITMAP_WORD(bit)], BITMAP_BIT_IN_WORD(bit));
50 }
51
52 /* find first zero bit starting from LSB */
_ffz(unsigned long x)53 static inline unsigned long _ffz(unsigned long x) {
54 return __builtin_ffsl(~x) - 1;
55 }
56
bitmap_ffz(unsigned long * bitmap,int numbits)57 static inline int bitmap_ffz(unsigned long *bitmap, int numbits) {
58 uint i;
59 int bit;
60
61 for (i = 0; i < BITMAP_NUM_WORDS(numbits); i++) {
62 if (bitmap[i] == ~0UL)
63 continue;
64 bit = i * BITMAP_BITS_PER_WORD + _ffz(bitmap[i]);
65 if (bit < numbits)
66 return bit;
67 return -1;
68 }
69 return -1;
70 }
71
72 __END_CDECLS
73