4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 only,
8 * as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License version 2 for more details (a copy is included
14 * in the LICENSE file that accompanied this code).
16 * You should have received a copy of the GNU General Public License
17 * version 2 along with this program; If not, see
18 * http://www.gnu.org/licenses/gpl-2.0.html
25 /* Fast hashing routine for ints, longs and pointers.
26 (C) 2002 Nadia Yvette Chambers, IBM */
29 * Knuth recommends primes in approximately golden ratio to the maximum
30 * integer representable by a machine word for multiplicative hashing.
31 * Chuck Lever verified the effectiveness of this technique:
32 * http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf
34 * These primes are chosen to be bit-sparse, that is operations on
35 * them can use shifts and additions instead of multiplications for
36 * machines where multiplications are slow.
39 #include <linux/types.h>
41 /* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */
42 #define GOLDEN_RATIO_PRIME_32 0x9e370001UL
43 /* 2^63 + 2^61 - 2^57 + 2^54 - 2^51 - 2^18 + 1 */
44 #define GOLDEN_RATIO_PRIME_64 0x9e37fffffffc0001UL
46 #if __BITS_PER_LONG == 32
47 #define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_32
48 #define hash_long(val, bits) hash_32(val, bits)
49 #elif __BITS_PER_LONG == 64
50 #define hash_long(val, bits) hash_64(val, bits)
51 #define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_64
53 #error Wordsize not 32 or 64
56 static __always_inline __u64 hash_64(__u64 val, unsigned int bits)
60 /* Sigh, gcc can't optimise this alone like it does for 32 bits. */
75 /* High bits are more random, so use them. */
76 return hash >> (64 - bits);
79 static inline __u32 hash_32(__u32 val, unsigned int bits)
81 /* On some cpus multiply is faster, on others gcc will do shifts */
82 __u32 hash = val * GOLDEN_RATIO_PRIME_32;
84 /* High bits are more random, so use them. */
85 return hash >> (32 - bits);
88 static inline unsigned long hash_ptr(const void *ptr, unsigned int bits)
90 return hash_long((unsigned long)ptr, bits);
93 static inline __u32 hash32_ptr(const void *ptr)
95 unsigned long val = (unsigned long)ptr;
97 #if __BITS_PER_LONG == 64
103 #endif /* _LINUX_HASH_H */