Final pass of libdrm.so work:
[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 #else
106 #define HASH_ALLOC drmMalloc
107 #define HASH_FREE  drmFree
108 #define HASH_RANDOM_DECL        void *state
109 #define HASH_RANDOM_INIT(seed)  state = drmRandomCreate(seed)
110 #define HASH_RANDOM             drmRandom(state)
111
112 #endif
113
114 typedef struct HashBucket {
115     unsigned long     key;
116     void              *value;
117     struct HashBucket *next;
118 } HashBucket, *HashBucketPtr;
119
120 typedef struct HashTable {
121     unsigned long    magic;
122     unsigned long    entries;
123     unsigned long    hits;      /* At top of linked list */
124     unsigned long    partials;  /* Not at top of linked list */
125     unsigned long    misses;    /* Not in table */
126     HashBucketPtr    buckets[HASH_SIZE];
127     int              p0;
128     HashBucketPtr    p1;
129 } HashTable, *HashTablePtr;
130
131 #if HASH_MAIN
132 extern void *N(HashCreate)(void);
133 extern int  N(HashDestroy)(void *t);
134 extern int  N(HashLookup)(void *t, unsigned long key, unsigned long *value);
135 extern int  N(HashInsert)(void *t, unsigned long key, unsigned long value);
136 extern int  N(HashDelete)(void *t, unsigned long key);
137 #endif
138
139 static unsigned long HashHash(unsigned long key)
140 {
141     unsigned long        hash = 0;
142     unsigned long        tmp  = key;
143     static int           init = 0;
144     static unsigned long scatter[256];
145     int                  i;
146
147     if (!init) {
148         HASH_RANDOM_DECL;
149         HASH_RANDOM_INIT(37);
150         for (i = 0; i < 256; i++) scatter[i] = HASH_RANDOM;
151         ++init;
152     }
153
154     while (tmp) {
155         hash = (hash << 1) + scatter[tmp & 0xff];
156         tmp >>= 8;
157     }
158
159     hash %= HASH_SIZE;
160 #if HASH_DEBUG
161     printf( "Hash(%d) = %d\n", key, hash);
162 #endif
163     return hash;
164 }
165
166 void *N(HashCreate)(void)
167 {
168     HashTablePtr table;
169     int          i;
170
171     table           = HASH_ALLOC(sizeof(*table));
172     if (!table) return NULL;
173     table->magic    = HASH_MAGIC;
174     table->entries  = 0;
175     table->hits     = 0;
176     table->partials = 0;
177     table->misses   = 0;
178
179     for (i = 0; i < HASH_SIZE; i++) table->buckets[i] = NULL;
180     return table;
181 }
182
183 int N(HashDestroy)(void *t)
184 {
185     HashTablePtr  table = (HashTablePtr)t;
186     HashBucketPtr bucket;
187     HashBucketPtr next;
188     int           i;
189
190     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
191
192     for (i = 0; i < HASH_SIZE; i++) {
193         for (bucket = table->buckets[i]; bucket;) {
194             next = bucket->next;
195             HASH_FREE(bucket);
196             bucket = next;
197         }
198     }
199     HASH_FREE(table);
200     return 0;
201 }
202
203 /* Find the bucket and organize the list so that this bucket is at the
204    top. */
205
206 static HashBucketPtr HashFind(HashTablePtr table,
207                               unsigned long key, unsigned long *h)
208 {
209     unsigned long hash = HashHash(key);
210     HashBucketPtr prev = NULL;
211     HashBucketPtr bucket;
212
213     if (h) *h = hash;
214
215     for (bucket = table->buckets[hash]; bucket; bucket = bucket->next) {
216         if (bucket->key == key) {
217             if (prev) {
218                                 /* Organize */
219                 prev->next           = bucket->next;
220                 bucket->next         = table->buckets[hash];
221                 table->buckets[hash] = bucket;
222                 ++table->partials;
223             } else {
224                 ++table->hits;
225             }
226             return bucket;
227         }
228         prev = bucket;
229     }
230     ++table->misses;
231     return NULL;
232 }
233
234 int N(HashLookup)(void *t, unsigned long key, void **value)
235 {
236     HashTablePtr  table = (HashTablePtr)t;
237     HashBucketPtr bucket;
238
239     if (!table || table->magic != HASH_MAGIC) return -1; /* Bad magic */
240
241     bucket = HashFind(table, key, NULL);
242     if (!bucket) return 1;      /* Not found */
243     *value = bucket->value;
244     return 0;                   /* Found */
245 }
246
247 int N(HashInsert)(void *t, unsigned long key, void *value)
248 {
249     HashTablePtr  table = (HashTablePtr)t;
250     HashBucketPtr bucket;
251     unsigned long hash;
252
253     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
254
255     if (HashFind(table, key, &hash)) return 1; /* Already in table */
256
257     bucket               = HASH_ALLOC(sizeof(*bucket));
258     if (!bucket) return -1;     /* Error */
259     bucket->key          = key;
260     bucket->value        = value;
261     bucket->next         = table->buckets[hash];
262     table->buckets[hash] = bucket;
263 #if HASH_DEBUG
264     printf("Inserted %d at %d/%p\n", key, hash, bucket);
265 #endif
266     return 0;                   /* Added to table */
267 }
268
269 int N(HashDelete)(void *t, unsigned long key)
270 {
271     HashTablePtr  table = (HashTablePtr)t;
272     unsigned long hash;
273     HashBucketPtr bucket;
274
275     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
276
277     bucket = HashFind(table, key, &hash);
278
279     if (!bucket) return 1;      /* Not found */
280
281     table->buckets[hash] = bucket->next;
282     HASH_FREE(bucket);
283     return 0;
284 }
285
286 int N(HashNext)(void *t, unsigned long *key, void **value)
287 {
288     HashTablePtr  table = (HashTablePtr)t;
289
290     for (; table->p0 < HASH_SIZE;
291          ++table->p0, table->p1 = table->buckets[table->p0]) {
292         if (table->p1) {
293             *key       = table->p1->key;
294             *value     = table->p1->value;
295             table->p1  = table->p1->next;
296             return 1;
297         }
298     }
299     return 0;
300 }
301
302 int N(HashFirst)(void *t, unsigned long *key, void **value)
303 {
304     HashTablePtr  table = (HashTablePtr)t;
305
306     if (table->magic != HASH_MAGIC) return -1; /* Bad magic */
307
308     table->p0 = 0;
309     table->p1 = table->buckets[0];
310     return N(HashNext)(table, key, value);
311 }
312
313 #if HASH_MAIN
314 #define DIST_LIMIT 10
315 static int dist[DIST_LIMIT];
316
317 static void clear_dist(void) {
318     int i;
319
320     for (i = 0; i < DIST_LIMIT; i++) dist[i] = 0;
321 }
322
323 static int count_entries(HashBucketPtr bucket)
324 {
325     int count = 0;
326
327     for (; bucket; bucket = bucket->next) ++count;
328     return count;
329 }
330
331 static void update_dist(int count)
332 {
333     if (count >= DIST_LIMIT) ++dist[DIST_LIMIT-1];
334     else                     ++dist[count];
335 }
336
337 static void compute_dist(HashTablePtr table)
338 {
339     int           i;
340     HashBucketPtr bucket;
341
342     printf("Entries = %ld, hits = %ld, partials = %ld, misses = %ld\n",
343            table->entries, table->hits, table->partials, table->misses);
344     clear_dist();
345     for (i = 0; i < HASH_SIZE; i++) {
346         bucket = table->buckets[i];
347         update_dist(count_entries(bucket));
348     }
349     for (i = 0; i < DIST_LIMIT; i++) {
350         if (i != DIST_LIMIT-1) printf("%5d %10d\n", i, dist[i]);
351         else                   printf("other %10d\n", dist[i]);
352     }
353 }
354
355 static void check_table(HashTablePtr table,
356                         unsigned long key, unsigned long value)
357 {
358     unsigned long retval  = 0;
359     int           retcode = N(HashLookup)(table, key, &retval);
360
361     switch (retcode) {
362     case -1:
363         printf("Bad magic = 0x%08lx:"
364                " key = %lu, expected = %lu, returned = %lu\n",
365                table->magic, key, value, retval);
366         break;
367     case 1:
368         printf("Not found: key = %lu, expected = %lu returned = %lu\n",
369                key, value, retval);
370         break;
371     case 0:
372         if (value != retval)
373             printf("Bad value: key = %lu, expected = %lu, returned = %lu\n",
374                    key, value, retval);
375         break;
376     default:
377         printf("Bad retcode = %d: key = %lu, expected = %lu, returned = %lu\n",
378                retcode, key, value, retval);
379         break;
380     }
381 }
382
383 int main(void)
384 {
385     HashTablePtr table;
386     int          i;
387
388     printf("\n***** 256 consecutive integers ****\n");
389     table = N(HashCreate)();
390     for (i = 0; i < 256; i++) N(HashInsert)(table, i, i);
391     for (i = 0; i < 256; i++) check_table(table, i, i);
392     for (i = 256; i >= 0; i--) check_table(table, i, i);
393     compute_dist(table);
394     N(HashDestroy)(table);
395
396     printf("\n***** 1024 consecutive integers ****\n");
397     table = N(HashCreate)();
398     for (i = 0; i < 1024; i++) N(HashInsert)(table, i, i);
399     for (i = 0; i < 1024; i++) check_table(table, i, i);
400     for (i = 1024; i >= 0; i--) check_table(table, i, i);
401     compute_dist(table);
402     N(HashDestroy)(table);
403
404     printf("\n***** 1024 consecutive page addresses (4k pages) ****\n");
405     table = N(HashCreate)();
406     for (i = 0; i < 1024; i++) N(HashInsert)(table, i*4096, i);
407     for (i = 0; i < 1024; i++) check_table(table, i*4096, i);
408     for (i = 1024; i >= 0; i--) check_table(table, i*4096, i);
409     compute_dist(table);
410     N(HashDestroy)(table);
411
412     printf("\n***** 1024 random integers ****\n");
413     table = N(HashCreate)();
414     srandom(0xbeefbeef);
415     for (i = 0; i < 1024; i++) N(HashInsert)(table, random(), i);
416     srandom(0xbeefbeef);
417     for (i = 0; i < 1024; i++) check_table(table, random(), i);
418     srandom(0xbeefbeef);
419     for (i = 0; i < 1024; i++) check_table(table, random(), i);
420     compute_dist(table);
421     N(HashDestroy)(table);
422
423     printf("\n***** 5000 random integers ****\n");
424     table = N(HashCreate)();
425     srandom(0xbeefbeef);
426     for (i = 0; i < 5000; i++) N(HashInsert)(table, random(), i);
427     srandom(0xbeefbeef);
428     for (i = 0; i < 5000; i++) check_table(table, random(), i);
429     srandom(0xbeefbeef);
430     for (i = 0; i < 5000; i++) check_table(table, random(), i);
431     compute_dist(table);
432     N(HashDestroy)(table);
433
434     return 0;
435 }
436 #endif