1
2
3
4
5
6
7#ifndef _LINUX_BITFIELD_H
8#define _LINUX_BITFIELD_H
9
10#include <linux/build_bug.h>
11#include <asm/byteorder.h>
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42#define __bf_shf(x) (__builtin_ffsll(x) - 1)
43
44#define __BF_FIELD_CHECK(_mask, _reg, _val, _pfx) \
45 ({ \
46 BUILD_BUG_ON_MSG(!__builtin_constant_p(_mask), \
47 _pfx "mask is not constant"); \
48 BUILD_BUG_ON_MSG((_mask) == 0, _pfx "mask is zero"); \
49 BUILD_BUG_ON_MSG(__builtin_constant_p(_val) ? \
50 ~((_mask) >> __bf_shf(_mask)) & (_val) : 0, \
51 _pfx "value too large for the field"); \
52 BUILD_BUG_ON_MSG((_mask) > (typeof(_reg))~0ull, \
53 _pfx "type of reg too small for mask"); \
54 __BUILD_BUG_ON_NOT_POWER_OF_2((_mask) + \
55 (1ULL << __bf_shf(_mask))); \
56 })
57
58
59
60
61
62
63
64
65#define FIELD_FIT(_mask, _val) \
66 ({ \
67 __BF_FIELD_CHECK(_mask, 0ULL, _val, "FIELD_FIT: "); \
68 !((((typeof(_mask))_val) << __bf_shf(_mask)) & ~(_mask)); \
69 })
70
71
72
73
74
75
76
77
78
79#define FIELD_PREP(_mask, _val) \
80 ({ \
81 __BF_FIELD_CHECK(_mask, 0ULL, _val, "FIELD_PREP: "); \
82 ((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask); \
83 })
84
85
86
87
88
89
90
91
92
93#define FIELD_GET(_mask, _reg) \
94 ({ \
95 __BF_FIELD_CHECK(_mask, _reg, 0U, "FIELD_GET: "); \
96 (typeof(_mask))(((_reg) & (_mask)) >> __bf_shf(_mask)); \
97 })
98
99extern void __compiletime_error("value doesn't fit into mask")
100__field_overflow(void);
101extern void __compiletime_error("bad bitfield mask")
102__bad_mask(void);
103static __always_inline u64 field_multiplier(u64 field)
104{
105 if ((field | (field - 1)) & ((field | (field - 1)) + 1))
106 __bad_mask();
107 return field & -field;
108}
109static __always_inline u64 field_mask(u64 field)
110{
111 return field / field_multiplier(field);
112}
113#define ____MAKE_OP(type,base,to,from) \
114static __always_inline __##type type##_encode_bits(base v, base field) \
115{ \
116 if (__builtin_constant_p(v) && (v & ~field_mask(field))) \
117 __field_overflow(); \
118 return to((v & field_mask(field)) * field_multiplier(field)); \
119} \
120static __always_inline __##type type##_replace_bits(__##type old, \
121 base val, base field) \
122{ \
123 return (old & ~to(field)) | type##_encode_bits(val, field); \
124} \
125static __always_inline void type##p_replace_bits(__##type *p, \
126 base val, base field) \
127{ \
128 *p = (*p & ~to(field)) | type##_encode_bits(val, field); \
129} \
130static __always_inline base type##_get_bits(__##type v, base field) \
131{ \
132 return (from(v) & field)/field_multiplier(field); \
133}
134#define __MAKE_OP(size) \
135 ____MAKE_OP(le##size,u##size,cpu_to_le##size,le##size##_to_cpu) \
136 ____MAKE_OP(be##size,u##size,cpu_to_be##size,be##size##_to_cpu) \
137 ____MAKE_OP(u##size,u##size,,)
138____MAKE_OP(u8,u8,,)
139__MAKE_OP(16)
140__MAKE_OP(32)
141__MAKE_OP(64)
142#undef __MAKE_OP
143#undef ____MAKE_OP
144
145#endif
146