xref: /linux/security/selinux/include/hash.h (revision 929126ef4a0e2723622eb3ba11017ca5fecd37d3)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #ifndef _SELINUX_HASH_H_
4 #define _SELINUX_HASH_H_
5 
6 /* Based on MurmurHash3, written by Austin Appleby and placed in the
7  * public domain.
8  */
9 static inline u32 avtab_hash(const struct avtab_key *keyp, u32 mask)
10 {
11 	static const u32 c1 = 0xcc9e2d51;
12 	static const u32 c2 = 0x1b873593;
13 	static const u32 r1 = 15;
14 	static const u32 r2 = 13;
15 	static const u32 m = 5;
16 	static const u32 n = 0xe6546b64;
17 
18 	u32 hash = 0;
19 
20 #define mix(input)                                         \
21 	do {                                               \
22 		u32 v = input;                             \
23 		v *= c1;                                   \
24 		v = (v << r1) | (v >> (32 - r1));          \
25 		v *= c2;                                   \
26 		hash ^= v;                                 \
27 		hash = (hash << r2) | (hash >> (32 - r2)); \
28 		hash = hash * m + n;                       \
29 	} while (0)
30 
31 	mix(keyp->target_class);
32 	mix(keyp->target_type);
33 	mix(keyp->source_type);
34 
35 #undef mix
36 
37 	hash ^= hash >> 16;
38 	hash *= 0x85ebca6b;
39 	hash ^= hash >> 13;
40 	hash *= 0xc2b2ae35;
41 	hash ^= hash >> 16;
42 
43 	return hash & mask;
44 }
45 
46 #endif /* _SELINUX_HASH_H_ */
47