hash.c revision 848b8605
1/**
2 * \file hash.c
3 * Generic hash table.
4 *
5 * Used for display lists, texture objects, vertex/fragment programs,
6 * buffer objects, etc.  The hash functions are thread-safe.
7 *
8 * \note key=0 is illegal.
9 *
10 * \author Brian Paul
11 */
12
13/*
14 * Mesa 3-D graphics library
15 *
16 * Copyright (C) 1999-2006  Brian Paul   All Rights Reserved.
17 *
18 * Permission is hereby granted, free of charge, to any person obtaining a
19 * copy of this software and associated documentation files (the "Software"),
20 * to deal in the Software without restriction, including without limitation
21 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
22 * and/or sell copies of the Software, and to permit persons to whom the
23 * Software is furnished to do so, subject to the following conditions:
24 *
25 * The above copyright notice and this permission notice shall be included
26 * in all copies or substantial portions of the Software.
27 *
28 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
29 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
31 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
32 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
33 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
34 * OTHER DEALINGS IN THE SOFTWARE.
35 */
36
37#include "glheader.h"
38#include "imports.h"
39#include "hash.h"
40#include "util/hash_table.h"
41
42/**
43 * Magic GLuint object name that gets stored outside of the struct hash_table.
44 *
45 * The hash table needs a particular pointer to be the marker for a key that
46 * was deleted from the table, along with NULL for the "never allocated in the
47 * table" marker.  Legacy GL allows any GLuint to be used as a GL object name,
48 * and we use a 1:1 mapping from GLuints to key pointers, so we need to be
49 * able to track a GLuint that happens to match the deleted key outside of
50 * struct hash_table.  We tell the hash table to use "1" as the deleted key
51 * value, so that we test the deleted-key-in-the-table path as best we can.
52 */
53#define DELETED_KEY_VALUE 1
54
55/**
56 * The hash table data structure.
57 */
58struct _mesa_HashTable {
59   struct hash_table *ht;
60   GLuint MaxKey;                        /**< highest key inserted so far */
61   mtx_t Mutex;                /**< mutual exclusion lock */
62   mtx_t WalkMutex;            /**< for _mesa_HashWalk() */
63   GLboolean InDeleteAll;                /**< Debug check */
64   /** Value that would be in the table for DELETED_KEY_VALUE. */
65   void *deleted_key_data;
66};
67
68/** @{
69 * Mapping from our use of GLuint as both the key and the hash value to the
70 * hash_table.h API
71 *
72 * There exist many integer hash functions, designed to avoid collisions when
73 * the integers are spread across key space with some patterns.  In GL, the
74 * pattern (in the case of glGen*()ed object IDs) is that the keys are unique
75 * contiguous integers starting from 1.  Because of that, we just use the key
76 * as the hash value, to minimize the cost of the hash function.  If objects
77 * are never deleted, we will never see a collision in the table, because the
78 * table resizes itself when it approaches full, and thus key % table_size ==
79 * key.
80 *
81 * The case where we could have collisions for genned objects would be
82 * something like: glGenBuffers(&a, 100); glDeleteBuffers(&a + 50, 50);
83 * glGenBuffers(&b, 100), because objects 1-50 and 101-200 are allocated at
84 * the end of that sequence, instead of 1-150.  So far it doesn't appear to be
85 * a problem.
86 */
87static bool
88uint_key_compare(const void *a, const void *b)
89{
90   return a == b;
91}
92
93static uint32_t
94uint_hash(GLuint id)
95{
96   return id;
97}
98
99static void *
100uint_key(GLuint id)
101{
102   return (void *)(uintptr_t) id;
103}
104/** @} */
105
106/**
107 * Create a new hash table.
108 *
109 * \return pointer to a new, empty hash table.
110 */
111struct _mesa_HashTable *
112_mesa_NewHashTable(void)
113{
114   struct _mesa_HashTable *table = CALLOC_STRUCT(_mesa_HashTable);
115
116   if (table) {
117      table->ht = _mesa_hash_table_create(NULL, uint_key_compare);
118      if (table->ht == NULL) {
119         free(table);
120         _mesa_error_no_memory(__func__);
121         return NULL;
122      }
123
124      _mesa_hash_table_set_deleted_key(table->ht, uint_key(DELETED_KEY_VALUE));
125      mtx_init(&table->Mutex, mtx_plain);
126      mtx_init(&table->WalkMutex, mtx_plain);
127   }
128   else {
129      _mesa_error_no_memory(__func__);
130   }
131
132   return table;
133}
134
135
136
137/**
138 * Delete a hash table.
139 * Frees each entry on the hash table and then the hash table structure itself.
140 * Note that the caller should have already traversed the table and deleted
141 * the objects in the table (i.e. We don't free the entries' data pointer).
142 *
143 * \param table the hash table to delete.
144 */
145void
146_mesa_DeleteHashTable(struct _mesa_HashTable *table)
147{
148   assert(table);
149
150   if (_mesa_hash_table_next_entry(table->ht, NULL) != NULL) {
151      _mesa_problem(NULL, "In _mesa_DeleteHashTable, found non-freed data");
152   }
153
154   _mesa_hash_table_destroy(table->ht, NULL);
155
156   mtx_destroy(&table->Mutex);
157   mtx_destroy(&table->WalkMutex);
158   free(table);
159}
160
161
162
163/**
164 * Lookup an entry in the hash table, without locking.
165 * \sa _mesa_HashLookup
166 */
167static inline void *
168_mesa_HashLookup_unlocked(struct _mesa_HashTable *table, GLuint key)
169{
170   const struct hash_entry *entry;
171
172   assert(table);
173   assert(key);
174
175   if (key == DELETED_KEY_VALUE)
176      return table->deleted_key_data;
177
178   entry = _mesa_hash_table_search(table->ht, uint_hash(key), uint_key(key));
179   if (!entry)
180      return NULL;
181
182   return entry->data;
183}
184
185
186/**
187 * Lookup an entry in the hash table.
188 *
189 * \param table the hash table.
190 * \param key the key.
191 *
192 * \return pointer to user's data or NULL if key not in table
193 */
194void *
195_mesa_HashLookup(struct _mesa_HashTable *table, GLuint key)
196{
197   void *res;
198   assert(table);
199   mtx_lock(&table->Mutex);
200   res = _mesa_HashLookup_unlocked(table, key);
201   mtx_unlock(&table->Mutex);
202   return res;
203}
204
205
206/**
207 * Lookup an entry in the hash table without locking the mutex.
208 *
209 * The hash table mutex must be locked manually by calling
210 * _mesa_HashLockMutex() before calling this function.
211 *
212 * \param table the hash table.
213 * \param key the key.
214 *
215 * \return pointer to user's data or NULL if key not in table
216 */
217void *
218_mesa_HashLookupLocked(struct _mesa_HashTable *table, GLuint key)
219{
220   return _mesa_HashLookup_unlocked(table, key);
221}
222
223
224/**
225 * Lock the hash table mutex.
226 *
227 * This function should be used when multiple objects need
228 * to be looked up in the hash table, to avoid having to lock
229 * and unlock the mutex each time.
230 *
231 * \param table the hash table.
232 */
233void
234_mesa_HashLockMutex(struct _mesa_HashTable *table)
235{
236   assert(table);
237   mtx_lock(&table->Mutex);
238}
239
240
241/**
242 * Unlock the hash table mutex.
243 *
244 * \param table the hash table.
245 */
246void
247_mesa_HashUnlockMutex(struct _mesa_HashTable *table)
248{
249   assert(table);
250   mtx_unlock(&table->Mutex);
251}
252
253
254static inline void
255_mesa_HashInsert_unlocked(struct _mesa_HashTable *table, GLuint key, void *data)
256{
257   uint32_t hash = uint_hash(key);
258   struct hash_entry *entry;
259
260   assert(table);
261   assert(key);
262
263   if (key > table->MaxKey)
264      table->MaxKey = key;
265
266   if (key == DELETED_KEY_VALUE) {
267      table->deleted_key_data = data;
268   } else {
269      entry = _mesa_hash_table_search(table->ht, hash, uint_key(key));
270      if (entry) {
271         entry->data = data;
272      } else {
273         _mesa_hash_table_insert(table->ht, hash, uint_key(key), data);
274      }
275   }
276}
277
278
279/**
280 * Insert a key/pointer pair into the hash table without locking the mutex.
281 * If an entry with this key already exists we'll replace the existing entry.
282 *
283 * The hash table mutex must be locked manually by calling
284 * _mesa_HashLockMutex() before calling this function.
285 *
286 * \param table the hash table.
287 * \param key the key (not zero).
288 * \param data pointer to user data.
289 */
290void
291_mesa_HashInsertLocked(struct _mesa_HashTable *table, GLuint key, void *data)
292{
293   _mesa_HashInsert_unlocked(table, key, data);
294}
295
296
297/**
298 * Insert a key/pointer pair into the hash table.
299 * If an entry with this key already exists we'll replace the existing entry.
300 *
301 * \param table the hash table.
302 * \param key the key (not zero).
303 * \param data pointer to user data.
304 */
305void
306_mesa_HashInsert(struct _mesa_HashTable *table, GLuint key, void *data)
307{
308   assert(table);
309   mtx_lock(&table->Mutex);
310   _mesa_HashInsert_unlocked(table, key, data);
311   mtx_unlock(&table->Mutex);
312}
313
314
315/**
316 * Remove an entry from the hash table.
317 *
318 * \param table the hash table.
319 * \param key key of entry to remove.
320 *
321 * While holding the hash table's lock, searches the entry with the matching
322 * key and unlinks it.
323 */
324void
325_mesa_HashRemove(struct _mesa_HashTable *table, GLuint key)
326{
327   struct hash_entry *entry;
328
329   assert(table);
330   assert(key);
331
332   /* have to check this outside of mutex lock */
333   if (table->InDeleteAll) {
334      _mesa_problem(NULL, "_mesa_HashRemove illegally called from "
335                    "_mesa_HashDeleteAll callback function");
336      return;
337   }
338
339   mtx_lock(&table->Mutex);
340   if (key == DELETED_KEY_VALUE) {
341      table->deleted_key_data = NULL;
342   } else {
343      entry = _mesa_hash_table_search(table->ht, uint_hash(key), uint_key(key));
344      _mesa_hash_table_remove(table->ht, entry);
345   }
346   mtx_unlock(&table->Mutex);
347}
348
349
350
351/**
352 * Delete all entries in a hash table, but don't delete the table itself.
353 * Invoke the given callback function for each table entry.
354 *
355 * \param table  the hash table to delete
356 * \param callback  the callback function
357 * \param userData  arbitrary pointer to pass along to the callback
358 *                  (this is typically a struct gl_context pointer)
359 */
360void
361_mesa_HashDeleteAll(struct _mesa_HashTable *table,
362                    void (*callback)(GLuint key, void *data, void *userData),
363                    void *userData)
364{
365   struct hash_entry *entry;
366
367   ASSERT(table);
368   ASSERT(callback);
369   mtx_lock(&table->Mutex);
370   table->InDeleteAll = GL_TRUE;
371   hash_table_foreach(table->ht, entry) {
372      callback((uintptr_t)entry->key, entry->data, userData);
373      _mesa_hash_table_remove(table->ht, entry);
374   }
375   if (table->deleted_key_data) {
376      callback(DELETED_KEY_VALUE, table->deleted_key_data, userData);
377      table->deleted_key_data = NULL;
378   }
379   table->InDeleteAll = GL_FALSE;
380   mtx_unlock(&table->Mutex);
381}
382
383
384/**
385 * Clone all entries in a hash table, into a new table.
386 *
387 * \param table  the hash table to clone
388 */
389struct _mesa_HashTable *
390_mesa_HashClone(const struct _mesa_HashTable *table)
391{
392   /* cast-away const */
393   struct _mesa_HashTable *table2 = (struct _mesa_HashTable *) table;
394   struct hash_entry *entry;
395   struct _mesa_HashTable *clonetable;
396
397   ASSERT(table);
398   mtx_lock(&table2->Mutex);
399
400   clonetable = _mesa_NewHashTable();
401   assert(clonetable);
402   hash_table_foreach(table->ht, entry) {
403      _mesa_HashInsert(clonetable, (GLint)(uintptr_t)entry->key, entry->data);
404   }
405
406   mtx_unlock(&table2->Mutex);
407
408   return clonetable;
409}
410
411
412/**
413 * Walk over all entries in a hash table, calling callback function for each.
414 * Note: we use a separate mutex in this function to avoid a recursive
415 * locking deadlock (in case the callback calls _mesa_HashRemove()) and to
416 * prevent multiple threads/contexts from getting tangled up.
417 * A lock-less version of this function could be used when the table will
418 * not be modified.
419 * \param table  the hash table to walk
420 * \param callback  the callback function
421 * \param userData  arbitrary pointer to pass along to the callback
422 *                  (this is typically a struct gl_context pointer)
423 */
424void
425_mesa_HashWalk(const struct _mesa_HashTable *table,
426               void (*callback)(GLuint key, void *data, void *userData),
427               void *userData)
428{
429   /* cast-away const */
430   struct _mesa_HashTable *table2 = (struct _mesa_HashTable *) table;
431   struct hash_entry *entry;
432
433   ASSERT(table);
434   ASSERT(callback);
435   mtx_lock(&table2->WalkMutex);
436   hash_table_foreach(table->ht, entry) {
437      callback((uintptr_t)entry->key, entry->data, userData);
438   }
439   if (table->deleted_key_data)
440      callback(DELETED_KEY_VALUE, table->deleted_key_data, userData);
441   mtx_unlock(&table2->WalkMutex);
442}
443
444static void
445debug_print_entry(GLuint key, void *data, void *userData)
446{
447   _mesa_debug(NULL, "%u %p\n", key, data);
448}
449
450/**
451 * Dump contents of hash table for debugging.
452 *
453 * \param table the hash table.
454 */
455void
456_mesa_HashPrint(const struct _mesa_HashTable *table)
457{
458   if (table->deleted_key_data)
459      debug_print_entry(DELETED_KEY_VALUE, table->deleted_key_data, NULL);
460   _mesa_HashWalk(table, debug_print_entry, NULL);
461}
462
463
464/**
465 * Find a block of adjacent unused hash keys.
466 *
467 * \param table the hash table.
468 * \param numKeys number of keys needed.
469 *
470 * \return Starting key of free block or 0 if failure.
471 *
472 * If there are enough free keys between the maximum key existing in the table
473 * (_mesa_HashTable::MaxKey) and the maximum key possible, then simply return
474 * the adjacent key. Otherwise do a full search for a free key block in the
475 * allowable key range.
476 */
477GLuint
478_mesa_HashFindFreeKeyBlock(struct _mesa_HashTable *table, GLuint numKeys)
479{
480   const GLuint maxKey = ~((GLuint) 0) - 1;
481   mtx_lock(&table->Mutex);
482   if (maxKey - numKeys > table->MaxKey) {
483      /* the quick solution */
484      mtx_unlock(&table->Mutex);
485      return table->MaxKey + 1;
486   }
487   else {
488      /* the slow solution */
489      GLuint freeCount = 0;
490      GLuint freeStart = 1;
491      GLuint key;
492      for (key = 1; key != maxKey; key++) {
493	 if (_mesa_HashLookup_unlocked(table, key)) {
494	    /* darn, this key is already in use */
495	    freeCount = 0;
496	    freeStart = key+1;
497	 }
498	 else {
499	    /* this key not in use, check if we've found enough */
500	    freeCount++;
501	    if (freeCount == numKeys) {
502               mtx_unlock(&table->Mutex);
503	       return freeStart;
504	    }
505	 }
506      }
507      /* cannot allocate a block of numKeys consecutive keys */
508      mtx_unlock(&table->Mutex);
509      return 0;
510   }
511}
512
513
514/**
515 * Return the number of entries in the hash table.
516 */
517GLuint
518_mesa_HashNumEntries(const struct _mesa_HashTable *table)
519{
520   struct hash_entry *entry;
521   GLuint count = 0;
522
523   if (table->deleted_key_data)
524      count++;
525
526   hash_table_foreach(table->ht, entry)
527      count++;
528
529   return count;
530}
531