1 /* tnum: tracked (or tristate) numbers
3 * A tnum tracks knowledge about the bits of a value. Each bit can be either
4 * known (0 or 1), or unknown (x). Arithmetic operations on tnums will
5 * propagate the unknown bits such that the tnum result represents all the
6 * possible results for possible values of the operands.
8 #include <linux/kernel.h>
9 #include <linux/tnum.h>
11 #define TNUM(_v, _m) (struct tnum){.value = _v, .mask = _m}
12 /* A completely unknown value */
13 const struct tnum tnum_unknown = { .value = 0, .mask = -1 };
15 struct tnum tnum_const(u64 value)
17 return TNUM(value, 0);
20 struct tnum tnum_lshift(struct tnum a, u8 shift)
22 return TNUM(a.value << shift, a.mask << shift);
25 struct tnum tnum_rshift(struct tnum a, u8 shift)
27 return TNUM(a.value >> shift, a.mask >> shift);
30 struct tnum tnum_add(struct tnum a, struct tnum b)
32 u64 sm, sv, sigma, chi, mu;
35 sv = a.value + b.value;
38 mu = chi | a.mask | b.mask;
39 return TNUM(sv & ~mu, mu);
42 struct tnum tnum_sub(struct tnum a, struct tnum b)
44 u64 dv, alpha, beta, chi, mu;
46 dv = a.value - b.value;
50 mu = chi | a.mask | b.mask;
51 return TNUM(dv & ~mu, mu);
54 struct tnum tnum_and(struct tnum a, struct tnum b)
58 alpha = a.value | a.mask;
59 beta = b.value | b.mask;
60 v = a.value & b.value;
61 return TNUM(v, alpha & beta & ~v);
64 struct tnum tnum_or(struct tnum a, struct tnum b)
68 v = a.value | b.value;
70 return TNUM(v, mu & ~v);
73 struct tnum tnum_xor(struct tnum a, struct tnum b)
77 v = a.value ^ b.value;
79 return TNUM(v & ~mu, mu);
82 /* half-multiply add: acc += (unknown * mask * value).
83 * An intermediate step in the multiply algorithm.
85 static struct tnum hma(struct tnum acc, u64 value, u64 mask)
89 acc = tnum_add(acc, TNUM(0, value));
96 struct tnum tnum_mul(struct tnum a, struct tnum b)
101 pi = a.value * b.value;
102 acc = hma(TNUM(pi, 0), a.mask, b.mask | b.value);
103 return hma(acc, b.mask, a.value);
106 /* Note that if a and b disagree - i.e. one has a 'known 1' where the other has
107 * a 'known 0' - this will return a 'known 1' for that bit.
109 struct tnum tnum_intersect(struct tnum a, struct tnum b)
113 v = a.value | b.value;
114 mu = a.mask & b.mask;
115 return TNUM(v & ~mu, mu);
118 struct tnum tnum_cast(struct tnum a, u8 size)
120 a.value &= (1ULL << (size * 8)) - 1;
121 a.mask &= (1ULL << (size * 8)) - 1;
125 bool tnum_is_aligned(struct tnum a, u64 size)
129 return !((a.value | a.mask) & (size - 1));
132 bool tnum_in(struct tnum a, struct tnum b)
134 if (b.mask & ~a.mask)
137 return a.value == b.value;
140 int tnum_strn(char *str, size_t size, struct tnum a)
142 return snprintf(str, size, "(%#llx; %#llx)", a.value, a.mask);
144 EXPORT_SYMBOL_GPL(tnum_strn);
146 int tnum_sbin(char *str, size_t size, struct tnum a)
150 for (n = 64; n; n--) {
154 else if (a.value & 1)
162 str[min(size - 1, (size_t)64)] = 0;