OSDN Git Service

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