fix mem leak in HashHash() (bug 5171)
[profile/ivi/libdrm.git] / libdrm / xf86drmHash.c
1 /* xf86drmHash.c -- Small hash table support for integer -> integer mapping
2  * Created: Sun Apr 18 09:35:45 1999 by faith@precisioninsight.com
3  *
4  * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the next
15  * paragraph) shall be included in all copies or substantial portions of the
16  * Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  *
26  * Authors: Rickard E. (Rik) Faith <faith@valinux.com>
27  *
28  * $XFree86: xc/programs/Xserver/hw/xfree86/os-support/linux/drm/xf86drmHash.c,v 1.4 2001/03/21 18:08:54 dawes Exp $
29  *
30  * DESCRIPTION
31  *
32  * This file contains a straightforward implementation of a fixed-sized
33  * hash table using self-organizing linked lists [Knuth73, pp. 398-399] for
34  * collision resolution.  There are two potentially interesting things
35  * about this implementation:
36  *
37  * 1) The table is power-of-two sized.  Prime sized tables are more
38  * traditional, but do not have a significant advantage over power-of-two
39  * sized table, especially when double hashing is not used for collision
40  * resolution.
41  *
42  * 2) The hash computation uses a table of random integers [Hanson97,
43  * pp. 39-41].
44  *
45  * FUTURE ENHANCEMENTS
46  *
47  * With a table size of 512, the current implementation is sufficient for a
48  * few hundred keys.  Since this is well above the expected size of the
49  * tables for which this implementation was designed, the implementation of
50  * dynamic hash tables was postponed until the need arises.  A common (and
51  * naive) approach to dynamic hash table implementation simply creates a
52  * new hash table when necessary, rehashes all the data into the new table,
53  * and destroys the old table.  The approach in [Larson88] is superior in
54  * two ways: 1) only a portion of the table is expanded when needed,
55  * distributing the expansion cost over several insertions, and 2) portions
56  * of the table can be locked, enabling a scalable thread-safe
57  * implementation.
58  *
59  * REFERENCES
60  *
61  * [Hanson97] David R. Hanson.  C Interfaces and Implementations:
62  * Techniques for Creating Reusable Software.  Reading, Massachusetts:
63  * Addison-Wesley, 1997.
64  *
65  * [Knuth73] Donald E. Knuth. The Art of Computer Programming.  Volume 3:
66  * Sorting and Searching.  Reading, Massachusetts: Addison-Wesley, 1973.
67  *
68  * [Larson88] Per-Ake Larson. "Dynamic Hash Tables".  CACM 31(4), April
69  * 1988, pp. 446-457.
70  *
71  */
72
73 #define HASH_MAIN 0
74
75 #if HASH_MAIN
76 # include <stdio.h>
77 # include <stdlib.h>
78 #else
79 # include "drm.h"
80 # include "xf86drm.h"
81 # ifdef XFree86LOADER
82 #  include "xf86.h"
83 #  include "xf86_ansic.h"
84 # else
85 #  include <stdio.h>
86 #  include <stdlib.h>
87 # endif
88 #endif
89
90 #define N(x)  drm##x
91
92 #define HASH_MAGIC 0xdeadbeef
93 #define HASH_DEBUG 0
94 #define HASH_SIZE  512          /* Good for about 100 entries */
95                                 /* If you change this value, you probably
96                                    have to change the HashHash hashing
97                                    function! */
98
99 #if HASH_MAIN
100 #define HASH_ALLOC malloc
101 #define HASH_FREE  free
102 #define HASH_RANDOM_DECL
103 #define HASH_RANDOM_INIT(seed)  srandom(seed)
104 #define HASH_RANDOM             random()
105 #define HASH_RANDOM_DESTROY
106 #else
107 #define HASH_ALLOC drmMalloc
108 #define HASH_FREE  drmFree
109 #define HASH_RANDOM_DECL        void *state
110 #define HASH_RANDOM_INIT(seed)  state = drmRandomCreate(seed)
111 #define HASH_RANDOM             drmRandom(state)
112 #define HASH_RANDOM_DESTROY     drmRandomDestroy(state)
113
114 #endif
115
116 typedef struct HashBucket {
117     unsigned long     key;
118     void              *value;
119     struct HashBucket *next;
120 } HashBucket, *HashBucketPtr;
121
122 typedef struct HashTable {
123     unsigned long    magic;
124     unsigned long    entries;
125     unsigned long    hits;      /* At top of linked list */
126     unsigned long    partials;  /* Not at top of linked list */
127     unsigned long    misses;    /* Not in table */
128     HashBucketPtr    buckets[HASH_SIZE];
129     int              p0;
130     HashBucketPtr    p1;
131 } HashTable, *HashTablePtr;
132
133 #if HASH_MAIN
134 extern void *N(HashCreate)(void);
135 extern int  N(HashDestroy)(void *t);
136 extern int  N(HashLookup)(void *t, unsigned long key, unsigned long *value);
137 extern int  N(HashInsert)(void *t, unsigned long key, unsigned long value);
138 extern int  N(HashDelete)(void *t, unsigned long key);
139 #endif
140
141 static unsigned long HashHash(unsigned long key)
142 {
143     unsigned long        hash = 0;
144     unsigned long        tmp  = key;
145     static int           init = 0;
146     static unsigned long scatter[256];
147     int                  i;
148
149     if (!init) {
150         HASH_RANDOM_DECL;
151         HASH_RANDOM_INIT(37);
152         for (i = 0; i < 256; i++) scatter[i] = HASH_RANDOM;
153         HASH_RANDOM_DESTROY;
154         ++init;
155     }
156
157     while (tmp) {
158         hash = (hash << 1) + scatter[tmp & 0xff];
159         tmp >>= 8;
160     }
161
162     hash %= HASH_SIZE;
163 #if HASH_DEBUG
164     printf( "Hash(%d) = %d\n", key, hash);
165 #endif
166     return hash;
167 }
168
169 void *N(HashCreate)(void)
170 {
171     HashTablePtr table;
172     int          i;
173
174     table           = HASH_ALLOC(sizeof(*table));
175     if (!table) return NULL;
176     table->magic    = HASH_MAGIC;
177     table->entries  = 0;
178     table->hits     = 0;
179     table->partials = 0;
180     table->misses   = 0;
181
182     for (i = 0; i < HASH_SIZE; i++) table->buckets[i] = NULL;
183     return table;
184 }
185
186 int N(HashDestroy)(void *t)
187 {
188     HashTablePtr  table = (HashTablePtr)t;
189     HashBucketPtr bucket;
190     HashBucketPtr next;
191     int           i;
192
193     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
194
195     for (i = 0; i < HASH_SIZE; i++) {
196         for (bucket = table->buckets[i]; bucket;) {
197             next = bucket->next;
198             HASH_FREE(bucket);
199             bucket = next;
200         }
201     }
202     HASH_FREE(table);
203     return 0;
204 }
205
206 /* Find the bucket and organize the list so that this bucket is at the
207    top. */
208
209 static HashBucketPtr HashFind(HashTablePtr table,
210                               unsigned long key, unsigned long *h)
211 {
212     unsigned long hash = HashHash(key);
213     HashBucketPtr prev = NULL;
214     HashBucketPtr bucket;
215
216     if (h) *h = hash;
217
218     for (bucket = table->buckets[hash]; bucket; bucket = bucket->next) {
219         if (bucket->key == key) {
220             if (prev) {
221                                 /* Organize */
222                 prev->next           = bucket->next;
223                 bucket->next         = table->buckets[hash];
224                 table->buckets[hash] = bucket;
225                 ++table->partials;
226             } else {
227                 ++table->hits;
228             }
229             return bucket;
230         }
231         prev = bucket;
232     }
233     ++table->misses;
234     return NULL;
235 }
236
237 int N(HashLookup)(void *t, unsigned long key, void **value)
238 {
239     HashTablePtr  table = (HashTablePtr)t;
240     HashBucketPtr bucket;
241
242     if (!table || table->magic != HASH_MAGIC) return -1; /* Bad magic */
243
244     bucket = HashFind(table, key, NULL);
245     if (!bucket) return 1;      /* Not found */
246     *value = bucket->value;
247     return 0;                   /* Found */
248 }
249
250 int N(HashInsert)(void *t, unsigned long key, void *value)
251 {
252     HashTablePtr  table = (HashTablePtr)t;
253     HashBucketPtr bucket;
254     unsigned long hash;
255
256     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
257
258     if (HashFind(table, key, &hash)) return 1; /* Already in table */
259
260     bucket               = HASH_ALLOC(sizeof(*bucket));
261     if (!bucket) return -1;     /* Error */
262     bucket->key          = key;
263     bucket->value        = value;
264     bucket->next         = table->buckets[hash];
265     table->buckets[hash] = bucket;
266 #if HASH_DEBUG
267     printf("Inserted %d at %d/%p\n", key, hash, bucket);
268 #endif
269     return 0;                   /* Added to table */
270 }
271
272 int N(HashDelete)(void *t, unsigned long key)
273 {
274     HashTablePtr  table = (HashTablePtr)t;
275     unsigned long hash;
276     HashBucketPtr bucket;
277
278     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
279
280     bucket = HashFind(table, key, &hash);
281
282     if (!bucket) return 1;      /* Not found */
283
284     table->buckets[hash] = bucket->next;
285     HASH_FREE(bucket);
286     return 0;
287 }
288
289 int N(HashNext)(void *t, unsigned long *key, void **value)
290 {
291     HashTablePtr  table = (HashTablePtr)t;
292
293     for (; table->p0 < HASH_SIZE;
294          ++table->p0, table->p1 = table->buckets[table->p0]) {
295         if (table->p1) {
296             *key       = table->p1->key;
297             *value     = table->p1->value;
298             table->p1  = table->p1->next;
299             return 1;
300         }
301     }
302     return 0;
303 }
304
305 int N(HashFirst)(void *t, unsigned long *key, void **value)
306 {
307     HashTablePtr  table = (HashTablePtr)t;
308
309     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
310
311     table->p0 = 0;
312     table->p1 = table->buckets[0];
313     return N(HashNext)(table, key, value);
314 }
315
316 #if HASH_MAIN
317 #define DIST_LIMIT 10
318 static int dist[DIST_LIMIT];
319
320 static void clear_dist(void) {
321     int i;
322
323     for (i = 0; i < DIST_LIMIT; i++) dist[i] = 0;
324 }
325
326 static int count_entries(HashBucketPtr bucket)
327 {
328     int count = 0;
329
330     for (; bucket; bucket = bucket->next) ++count;
331     return count;
332 }
333
334 static void update_dist(int count)
335 {
336     if (count >= DIST_LIMIT) ++dist[DIST_LIMIT-1];
337     else                     ++dist[count];
338 }
339
340 static void compute_dist(HashTablePtr table)
341 {
342     int           i;
343     HashBucketPtr bucket;
344
345     printf("Entries = %ld, hits = %ld, partials = %ld, misses = %ld\n",
346            table->entries, table->hits, table->partials, table->misses);
347     clear_dist();
348     for (i = 0; i < HASH_SIZE; i++) {
349         bucket = table->buckets[i];
350         update_dist(count_entries(bucket));
351     }
352     for (i = 0; i < DIST_LIMIT; i++) {
353         if (i != DIST_LIMIT-1) printf("%5d %10d\n", i, dist[i]);
354         else                   printf("other %10d\n", dist[i]);
355     }
356 }
357
358 static void check_table(HashTablePtr table,
359                         unsigned long key, unsigned long value)
360 {
361     unsigned long retval  = 0;
362     int           retcode = N(HashLookup)(table, key, &retval);
363
364     switch (retcode) {
365     case -1:
366         printf("Bad magic = 0x%08lx:"
367                " key = %lu, expected = %lu, returned = %lu\n",
368                table->magic, key, value, retval);
369         break;
370     case 1:
371         printf("Not found: key = %lu, expected = %lu returned = %lu\n",
372                key, value, retval);
373         break;
374     case 0:
375         if (value != retval)
376             printf("Bad value: key = %lu, expected = %lu, returned = %lu\n",
377                    key, value, retval);
378         break;
379     default:
380         printf("Bad retcode = %d: key = %lu, expected = %lu, returned = %lu\n",
381                retcode, key, value, retval);
382         break;
383     }
384 }
385
386 int main(void)
387 {
388     HashTablePtr table;
389     int          i;
390
391     printf("\n***** 256 consecutive integers ****\n");
392     table = N(HashCreate)();
393     for (i = 0; i < 256; i++) N(HashInsert)(table, i, i);
394     for (i = 0; i < 256; i++) check_table(table, i, i);
395     for (i = 256; i >= 0; i--) check_table(table, i, i);
396     compute_dist(table);
397     N(HashDestroy)(table);
398
399     printf("\n***** 1024 consecutive integers ****\n");
400     table = N(HashCreate)();
401     for (i = 0; i < 1024; i++) N(HashInsert)(table, i, i);
402     for (i = 0; i < 1024; i++) check_table(table, i, i);
403     for (i = 1024; i >= 0; i--) check_table(table, i, i);
404     compute_dist(table);
405     N(HashDestroy)(table);
406
407     printf("\n***** 1024 consecutive page addresses (4k pages) ****\n");
408     table = N(HashCreate)();
409     for (i = 0; i < 1024; i++) N(HashInsert)(table, i*4096, i);
410     for (i = 0; i < 1024; i++) check_table(table, i*4096, i);
411     for (i = 1024; i >= 0; i--) check_table(table, i*4096, i);
412     compute_dist(table);
413     N(HashDestroy)(table);
414
415     printf("\n***** 1024 random integers ****\n");
416     table = N(HashCreate)();
417     srandom(0xbeefbeef);
418     for (i = 0; i < 1024; i++) N(HashInsert)(table, random(), i);
419     srandom(0xbeefbeef);
420     for (i = 0; i < 1024; i++) check_table(table, random(), i);
421     srandom(0xbeefbeef);
422     for (i = 0; i < 1024; i++) check_table(table, random(), i);
423     compute_dist(table);
424     N(HashDestroy)(table);
425
426     printf("\n***** 5000 random integers ****\n");
427     table = N(HashCreate)();
428     srandom(0xbeefbeef);
429     for (i = 0; i < 5000; i++) N(HashInsert)(table, random(), i);
430     srandom(0xbeefbeef);
431     for (i = 0; i < 5000; i++) check_table(table, random(), i);
432     srandom(0xbeefbeef);
433     for (i = 0; i < 5000; i++) check_table(table, random(), i);
434     compute_dist(table);
435     N(HashDestroy)(table);
436
437     return 0;
438 }
439 #endif