]> git.ozlabs.org Git - ccan/blob - ccan/tdb/hash.c
tdb2: don't cancel transactions on lock failures in tdb1 backend.
[ccan] / ccan / tdb / hash.c
1  /*
2    Unix SMB/CIFS implementation.
3
4    trivial database library
5
6    Copyright (C) Rusty Russell             2010
7
8      ** NOTE! The following LGPL license applies to the tdb
9      ** library. This does NOT imply that all of Samba is released
10      ** under the LGPL
11
12    This library is free software; you can redistribute it and/or
13    modify it under the terms of the GNU Lesser General Public
14    License as published by the Free Software Foundation; either
15    version 3 of the License, or (at your option) any later version.
16
17    This library is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20    Lesser General Public License for more details.
21
22    You should have received a copy of the GNU Lesser General Public
23    License along with this library; if not, see <http://www.gnu.org/licenses/>.
24 */
25 #include "tdb_private.h"
26
27 /* This is based on the hash algorithm from gdbm */
28 unsigned int tdb_old_hash(TDB_DATA *key)
29 {
30         uint32_t value; /* Used to compute the hash value.  */
31         uint32_t   i;   /* Used to cycle through random values. */
32
33         /* Set the initial value from the key size. */
34         for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
35                 value = (value + (key->dptr[i] << (i*5 % 24)));
36
37         return (1103515243 * value + 12345);  
38 }
39
40 #if HAVE_LITTLE_ENDIAN
41 # define HASH_LITTLE_ENDIAN 1
42 # define HASH_BIG_ENDIAN 0
43 #elif HAVE_BIG_ENDIAN
44 # define HASH_LITTLE_ENDIAN 0
45 # define HASH_BIG_ENDIAN 1
46 #else
47 # error Unknown endian
48 #endif
49
50 /*
51 -------------------------------------------------------------------------------
52 lookup3.c, by Bob Jenkins, May 2006, Public Domain.
53
54 These are functions for producing 32-bit hashes for hash table lookup.
55 hash_word(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() 
56 are externally useful functions.  Routines to test the hash are included 
57 if SELF_TEST is defined.  You can use this free for any purpose.  It's in
58 the public domain.  It has no warranty.
59
60 You probably want to use hashlittle().  hashlittle() and hashbig()
61 hash byte arrays.  hashlittle() is is faster than hashbig() on
62 little-endian machines.  Intel and AMD are little-endian machines.
63 On second thought, you probably want hashlittle2(), which is identical to
64 hashlittle() except it returns two 32-bit hashes for the price of one.  
65 You could implement hashbig2() if you wanted but I haven't bothered here.
66
67 If you want to find a hash of, say, exactly 7 integers, do
68   a = i1;  b = i2;  c = i3;
69   mix(a,b,c);
70   a += i4; b += i5; c += i6;
71   mix(a,b,c);
72   a += i7;
73   final(a,b,c);
74 then use c as the hash value.  If you have a variable length array of
75 4-byte integers to hash, use hash_word().  If you have a byte array (like
76 a character string), use hashlittle().  If you have several byte arrays, or
77 a mix of things, see the comments above hashlittle().  
78
79 Why is this so big?  I read 12 bytes at a time into 3 4-byte integers, 
80 then mix those integers.  This is fast (you can do a lot more thorough
81 mixing with 12*3 instructions on 3 integers than you can with 3 instructions
82 on 1 byte), but shoehorning those bytes into integers efficiently is messy.
83 */
84
85 #define hashsize(n) ((uint32_t)1<<(n))
86 #define hashmask(n) (hashsize(n)-1)
87 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
88
89 /*
90 -------------------------------------------------------------------------------
91 mix -- mix 3 32-bit values reversibly.
92
93 This is reversible, so any information in (a,b,c) before mix() is
94 still in (a,b,c) after mix().
95
96 If four pairs of (a,b,c) inputs are run through mix(), or through
97 mix() in reverse, there are at least 32 bits of the output that
98 are sometimes the same for one pair and different for another pair.
99 This was tested for:
100 * pairs that differed by one bit, by two bits, in any combination
101   of top bits of (a,b,c), or in any combination of bottom bits of
102   (a,b,c).
103 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
104   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
105   is commonly produced by subtraction) look like a single 1-bit
106   difference.
107 * the base values were pseudorandom, all zero but one bit set, or 
108   all zero plus a counter that starts at zero.
109
110 Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
111 satisfy this are
112     4  6  8 16 19  4
113     9 15  3 18 27 15
114    14  9  3  7 17  3
115 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
116 for "differ" defined as + with a one-bit base and a two-bit delta.  I
117 used http://burtleburtle.net/bob/hash/avalanche.html to choose 
118 the operations, constants, and arrangements of the variables.
119
120 This does not achieve avalanche.  There are input bits of (a,b,c)
121 that fail to affect some output bits of (a,b,c), especially of a.  The
122 most thoroughly mixed value is c, but it doesn't really even achieve
123 avalanche in c.
124
125 This allows some parallelism.  Read-after-writes are good at doubling
126 the number of bits affected, so the goal of mixing pulls in the opposite
127 direction as the goal of parallelism.  I did what I could.  Rotates
128 seem to cost as much as shifts on every machine I could lay my hands
129 on, and rotates are much kinder to the top and bottom bits, so I used
130 rotates.
131 -------------------------------------------------------------------------------
132 */
133 #define mix(a,b,c) \
134 { \
135   a -= c;  a ^= rot(c, 4);  c += b; \
136   b -= a;  b ^= rot(a, 6);  a += c; \
137   c -= b;  c ^= rot(b, 8);  b += a; \
138   a -= c;  a ^= rot(c,16);  c += b; \
139   b -= a;  b ^= rot(a,19);  a += c; \
140   c -= b;  c ^= rot(b, 4);  b += a; \
141 }
142
143 /*
144 -------------------------------------------------------------------------------
145 final -- final mixing of 3 32-bit values (a,b,c) into c
146
147 Pairs of (a,b,c) values differing in only a few bits will usually
148 produce values of c that look totally different.  This was tested for
149 * pairs that differed by one bit, by two bits, in any combination
150   of top bits of (a,b,c), or in any combination of bottom bits of
151   (a,b,c).
152 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
153   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
154   is commonly produced by subtraction) look like a single 1-bit
155   difference.
156 * the base values were pseudorandom, all zero but one bit set, or 
157   all zero plus a counter that starts at zero.
158
159 These constants passed:
160  14 11 25 16 4 14 24
161  12 14 25 16 4 14 24
162 and these came close:
163   4  8 15 26 3 22 24
164  10  8 15 26 3 22 24
165  11  8 15 26 3 22 24
166 -------------------------------------------------------------------------------
167 */
168 #define final(a,b,c) \
169 { \
170   c ^= b; c -= rot(b,14); \
171   a ^= c; a -= rot(c,11); \
172   b ^= a; b -= rot(a,25); \
173   c ^= b; c -= rot(b,16); \
174   a ^= c; a -= rot(c,4);  \
175   b ^= a; b -= rot(a,14); \
176   c ^= b; c -= rot(b,24); \
177 }
178
179
180 /*
181 -------------------------------------------------------------------------------
182 hashlittle() -- hash a variable-length key into a 32-bit value
183   k       : the key (the unaligned variable-length array of bytes)
184   length  : the length of the key, counting by bytes
185   val2    : IN: can be any 4-byte value OUT: second 32 bit hash.
186 Returns a 32-bit value.  Every bit of the key affects every bit of
187 the return value.  Two keys differing by one or two bits will have
188 totally different hash values.  Note that the return value is better
189 mixed than val2, so use that first.
190
191 The best hash table sizes are powers of 2.  There is no need to do
192 mod a prime (mod is sooo slow!).  If you need less than 32 bits,
193 use a bitmask.  For example, if you need only 10 bits, do
194   h = (h & hashmask(10));
195 In which case, the hash table should have hashsize(10) elements.
196
197 If you are hashing n strings (uint8_t **)k, do it like this:
198   for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
199
200 By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
201 code any way you wish, private, educational, or commercial.  It's free.
202
203 Use for hash table lookup, or anything where one collision in 2^^32 is
204 acceptable.  Do NOT use for cryptographic purposes.
205 -------------------------------------------------------------------------------
206 */
207
208 static uint32_t hashlittle( const void *key, size_t length )
209 {
210   uint32_t a,b,c;                                          /* internal state */
211   union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
212
213   /* Set up the internal state */
214   a = b = c = 0xdeadbeef + ((uint32_t)length);
215
216   u.ptr = key;
217   if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
218     const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
219 #ifdef VALGRIND
220     const uint8_t  *k8;
221 #endif
222
223     /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
224     while (length > 12)
225     {
226       a += k[0];
227       b += k[1];
228       c += k[2];
229       mix(a,b,c);
230       length -= 12;
231       k += 3;
232     }
233
234     /*----------------------------- handle the last (probably partial) block */
235     /* 
236      * "k[2]&0xffffff" actually reads beyond the end of the string, but
237      * then masks off the part it's not allowed to read.  Because the
238      * string is aligned, the masked-off tail is in the same word as the
239      * rest of the string.  Every machine with memory protection I've seen
240      * does it on word boundaries, so is OK with this.  But VALGRIND will
241      * still catch it and complain.  The masking trick does make the hash
242      * noticably faster for short strings (like English words).
243      */
244 #ifndef VALGRIND
245
246     switch(length)
247     {
248     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
249     case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
250     case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
251     case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
252     case 8 : b+=k[1]; a+=k[0]; break;
253     case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
254     case 6 : b+=k[1]&0xffff; a+=k[0]; break;
255     case 5 : b+=k[1]&0xff; a+=k[0]; break;
256     case 4 : a+=k[0]; break;
257     case 3 : a+=k[0]&0xffffff; break;
258     case 2 : a+=k[0]&0xffff; break;
259     case 1 : a+=k[0]&0xff; break;
260     case 0 : return c;              /* zero length strings require no mixing */
261     }
262
263 #else /* make valgrind happy */
264
265     k8 = (const uint8_t *)k;
266     switch(length)
267     {
268     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
269     case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
270     case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
271     case 9 : c+=k8[8];                   /* fall through */
272     case 8 : b+=k[1]; a+=k[0]; break;
273     case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
274     case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
275     case 5 : b+=k8[4];                   /* fall through */
276     case 4 : a+=k[0]; break;
277     case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
278     case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
279     case 1 : a+=k8[0]; break;
280     case 0 : return c;
281     }
282
283 #endif /* !valgrind */
284
285   } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
286     const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
287     const uint8_t  *k8;
288
289     /*--------------- all but last block: aligned reads and different mixing */
290     while (length > 12)
291     {
292       a += k[0] + (((uint32_t)k[1])<<16);
293       b += k[2] + (((uint32_t)k[3])<<16);
294       c += k[4] + (((uint32_t)k[5])<<16);
295       mix(a,b,c);
296       length -= 12;
297       k += 6;
298     }
299
300     /*----------------------------- handle the last (probably partial) block */
301     k8 = (const uint8_t *)k;
302     switch(length)
303     {
304     case 12: c+=k[4]+(((uint32_t)k[5])<<16);
305              b+=k[2]+(((uint32_t)k[3])<<16);
306              a+=k[0]+(((uint32_t)k[1])<<16);
307              break;
308     case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
309     case 10: c+=k[4];
310              b+=k[2]+(((uint32_t)k[3])<<16);
311              a+=k[0]+(((uint32_t)k[1])<<16);
312              break;
313     case 9 : c+=k8[8];                      /* fall through */
314     case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
315              a+=k[0]+(((uint32_t)k[1])<<16);
316              break;
317     case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
318     case 6 : b+=k[2];
319              a+=k[0]+(((uint32_t)k[1])<<16);
320              break;
321     case 5 : b+=k8[4];                      /* fall through */
322     case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
323              break;
324     case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
325     case 2 : a+=k[0];
326              break;
327     case 1 : a+=k8[0];
328              break;
329     case 0 : return c;                     /* zero length requires no mixing */
330     }
331
332   } else {                        /* need to read the key one byte at a time */
333     const uint8_t *k = (const uint8_t *)key;
334
335     /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
336     while (length > 12)
337     {
338       a += k[0];
339       a += ((uint32_t)k[1])<<8;
340       a += ((uint32_t)k[2])<<16;
341       a += ((uint32_t)k[3])<<24;
342       b += k[4];
343       b += ((uint32_t)k[5])<<8;
344       b += ((uint32_t)k[6])<<16;
345       b += ((uint32_t)k[7])<<24;
346       c += k[8];
347       c += ((uint32_t)k[9])<<8;
348       c += ((uint32_t)k[10])<<16;
349       c += ((uint32_t)k[11])<<24;
350       mix(a,b,c);
351       length -= 12;
352       k += 12;
353     }
354
355     /*-------------------------------- last block: affect all 32 bits of (c) */
356     switch(length)                   /* all the case statements fall through */
357     {
358     case 12: c+=((uint32_t)k[11])<<24;
359     case 11: c+=((uint32_t)k[10])<<16;
360     case 10: c+=((uint32_t)k[9])<<8;
361     case 9 : c+=k[8];
362     case 8 : b+=((uint32_t)k[7])<<24;
363     case 7 : b+=((uint32_t)k[6])<<16;
364     case 6 : b+=((uint32_t)k[5])<<8;
365     case 5 : b+=k[4];
366     case 4 : a+=((uint32_t)k[3])<<24;
367     case 3 : a+=((uint32_t)k[2])<<16;
368     case 2 : a+=((uint32_t)k[1])<<8;
369     case 1 : a+=k[0];
370              break;
371     case 0 : return c;
372     }
373   }
374
375   final(a,b,c);
376   return c;
377 }
378
379 unsigned int tdb_jenkins_hash(TDB_DATA *key)
380 {
381         return hashlittle(key->dptr, key->dsize);
382 }