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