diff --git a/libdrm/xf86drm.c b/libdrm/xf86drm.c
index b49a7df..4e3a3db 100755
--- a/libdrm/xf86drm.c
+++ b/libdrm/xf86drm.c
@@ -998,6 +998,8 @@ int drmFreeBufs(int fd, int count, int *list)
 }
 
 
+extern int drmHashEntries(void *t);
+
 /**
  * Close the device.
  *
@@ -1020,6 +1022,13 @@ int drmClose(int fd)
 
         drmHashDelete(drmHashTable, key);
         drmFree(entry);
+        
+        /* Clean up after ourselves */
+        if (!drmHashEntries(drmHashTable))
+        {
+            drmHashDestroy(drmHashTable);
+            drmHashTable = NULL;
+        }
     }
 
     return close(fd);
diff --git a/libdrm/xf86drmHash.c b/libdrm/xf86drmHash.c
index 82cbc2a..fb76edb 100755
--- a/libdrm/xf86drmHash.c
+++ b/libdrm/xf86drmHash.c
@@ -251,6 +251,7 @@ int drmHashInsert(void *t, unsigned long key, void *value)
     bucket->value        = value;
     bucket->next         = table->buckets[hash];
     table->buckets[hash] = bucket;
+    table->entries++;
 #if HASH_DEBUG
     printf("Inserted %d at %d/%p\n", key, hash, bucket);
 #endif
@@ -270,6 +271,7 @@ int drmHashDelete(void *t, unsigned long key)
     if (!bucket) return 1;	/* Not found */
 
     table->buckets[hash] = bucket->next;
+    table->entries--;
     HASH_FREE(bucket);
     return 0;
 }
@@ -302,6 +304,13 @@ int drmHashFirst(void *t, unsigned long *key, void **value)
     return drmHashNext(table, key, value);
 }
 
+int drmHashEntries(void *t)
+{
+    HashTablePtr  table = (HashTablePtr)t;
+    return table->entries;
+}
+
+
 #if HASH_MAIN
 #define DIST_LIMIT 10
 static int dist[DIST_LIMIT];
