1/*-------------------------------------------------------------------------
4 * Concurrent hash tables backed by dynamic shared memory areas.
6 * This is an open hashing hash table, with a linked list at each table
7 * entry. It supports dynamic resizing, as required to prevent the linked
8 * lists from growing too long on average. Currently, only growing is
9 * supported: the hash table never becomes smaller.
11 * To deal with concurrency, it has a fixed size set of partitions, each of
12 * which is independently locked. Each bucket maps to a partition; so insert,
13 * find and iterate operations normally only acquire one lock. Therefore,
14 * good concurrency is achieved whenever such operations don't collide at the
15 * lock partition level. However, when a resize operation begins, all
16 * partition locks must be acquired simultaneously for a brief period. This
17 * is only expected to happen a small number of times until a stable size is
18 * found, since growth is geometric.
20 * Future versions may support iterators and incremental resizing; for now
21 * the implementation is minimalist.
23 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
24 * Portions Copyright (c) 1994, Regents of the University of California
27 * src/backend/lib/dshash.c
29 *-------------------------------------------------------------------------
40 * An item in the hash table. This wraps the user's entry object in an
41 * envelop that holds a pointer back to the bucket and a pointer to the next
46 /* The next item in the same bucket. */
48 /* The hashed key, to avoid having to recompute it. */
50 /* The user's entry object follows here. See ENTRY_FROM_ITEM(item). */
54 * The number of partitions for locking purposes. This is set to match
55 * NUM_BUFFER_PARTITIONS for now, on the basis that whatever's good enough for
56 * the buffer pool must be good enough for any other purpose. This could
57 * become a runtime parameter in future.
59 #define DSHASH_NUM_PARTITIONS_LOG2 7
60 #define DSHASH_NUM_PARTITIONS (1 << DSHASH_NUM_PARTITIONS_LOG2)
62/* A magic value used to identify our hash tables. */
63 #define DSHASH_MAGIC 0x75ff6a20
66 * Tracking information for each lock partition. Initially, each partition
67 * corresponds to one bucket, but each time the hash table grows, the buckets
68 * covered by each partition split so the number of buckets covered doubles.
70 * We might want to add padding here so that each partition is on a different
71 * cache line, but doing so would bloat this structure considerably.
75 LWLock lock;
/* Protects all buckets in this partition. */
76 size_t count;
/* # of items in this partition's buckets */
80 * The head object for a hash table. This will be stored in dynamic shared
91 * The following members are written to only when ALL partitions locks are
92 * held. They can be read when any one partition lock is held.
95 /* Number of buckets expressed as power of 2 (8 = 256 buckets). */
101 * Per-backend state for a dynamic hash table.
107 void *
arg;
/* User-supplied data pointer. */
113/* Given a pointer to an item, find the entry (user data) it holds. */
114 #define ENTRY_FROM_ITEM(item) \
115 ((char *)(item) + MAXALIGN(sizeof(dshash_table_item)))
117/* Given a pointer to an entry, find the item that holds it. */
118 #define ITEM_FROM_ENTRY(entry) \
119 ((dshash_table_item *)((char *)(entry) - \
120 MAXALIGN(sizeof(dshash_table_item))))
122/* How many resize operations (bucket splits) have there been? */
123 #define NUM_SPLITS(size_log2) \
124 (size_log2 - DSHASH_NUM_PARTITIONS_LOG2)
126/* How many buckets are there in a given size? */
127 #define NUM_BUCKETS(size_log2) \
128 (((size_t) 1) << (size_log2))
130/* How many buckets are there in each partition at a given size? */
131 #define BUCKETS_PER_PARTITION(size_log2) \
132 (((size_t) 1) << NUM_SPLITS(size_log2))
134/* Max entries before we need to grow. Half + quarter = 75% load factor. */
135 #define MAX_COUNT_PER_PARTITION(hash_table) \
136 (BUCKETS_PER_PARTITION(hash_table->size_log2) / 2 + \
137 BUCKETS_PER_PARTITION(hash_table->size_log2) / 4)
139/* Choose partition based on the highest order bits of the hash. */
140 #define PARTITION_FOR_HASH(hash) \
141 (hash >> ((sizeof(dshash_hash) * CHAR_BIT) - DSHASH_NUM_PARTITIONS_LOG2))
144 * Find the bucket index for a given hash and table size. Each time the table
145 * doubles in size, the appropriate bucket for a given hash value doubles and
146 * possibly adds one, depending on the newly revealed bit, so that all buckets
149 #define BUCKET_INDEX_FOR_HASH_AND_SIZE(hash, size_log2) \
150 (hash >> ((sizeof(dshash_hash) * CHAR_BIT) - (size_log2)))
152/* The index of the first bucket in a given partition. */
153 #define BUCKET_INDEX_FOR_PARTITION(partition, size_log2) \
154 ((partition) << NUM_SPLITS(size_log2))
156/* Choose partition based on bucket index. */
157 #define PARTITION_FOR_BUCKET_INDEX(bucket_idx, size_log2) \
158 ((bucket_idx) >> NUM_SPLITS(size_log2))
160/* The head of the active bucket for a given hash value (lvalue). */
161 #define BUCKET_FOR_HASH(hash_table, hash) \
162 (hash_table->buckets[ \
163 BUCKET_INDEX_FOR_HASH_AND_SIZE(hash, \
164 hash_table->size_log2)])
188 const void *
a,
const void *
b);
192 #define PARTITION_LOCK(hash_table, i) \
193 (&(hash_table)->control->partitions[(i)].lock)
195 #define ASSERT_NO_PARTITION_LOCKS_HELD_BY_ME(hash_table) \
196 Assert(!LWLockAnyHeldByMe(&(hash_table)->control->partitions[0].lock, \
197 DSHASH_NUM_PARTITIONS, sizeof(dshash_partition)))
200 * Create a new hash table backed by the given dynamic shared area, with the
201 * given parameters. The returned object is allocated in backend-local memory
202 * using the current MemoryContext. 'arg' will be passed through to the
203 * compare, hash, and copy functions.
211 /* Allocate the backend-local object representing the hash table. */
214 /* Allocate the control object in shared memory. */
217 /* Set up the local and shared hash table structs. */
218 hash_table->
area = area;
219 hash_table->
params = *params;
226 /* Set up the array of lock partitions. */
240 * Set up the initial array of buckets. Our initial size is the same as
241 * the number of partitions.
252 (
errcode(ERRCODE_OUT_OF_MEMORY),
254 errdetail(
"Failed on DSA request of size %zu.",
265 * Attach to an existing hash table using a handle. The returned object is
266 * allocated in backend-local memory using the current MemoryContext. 'arg'
267 * will be passed through to the compare and hash functions.
276 /* Allocate the backend-local object representing the hash table. */
279 /* Find the control object in shared memory. */
282 /* Set up the local hash table struct. */
283 hash_table->
area = area;
284 hash_table->
params = *params;
290 * These will later be set to the correct values by
291 * ensure_valid_bucket_pointers(), at which time we'll be holding a
292 * partition lock for interlocking against concurrent resizing.
301 * Detach from a hash table. This frees backend-local resources associated
302 * with the hash table, but the hash table will continue to exist until it is
303 * either explicitly destroyed (by a backend that is still attached to it), or
304 * the area that backs it is returned to the operating system.
311 /* The hash table may have been destroyed. Just free local memory. */
316 * Destroy a hash table, returning all memory to the area. The caller must be
317 * certain that no other backend will attempt to access the hash table before
318 * calling this function. Other backend must explicitly call dshash_detach to
319 * free up backend-local memory associated with the hash table. The backend
320 * that calls dshash_destroy must not call dshash_detach.
331 /* Free all the entries. */
333 for (
i = 0;
i < size; ++
i)
343 next_item_pointer = item->
next;
345 item_pointer = next_item_pointer;
350 * Vandalize the control block to help catch programming errors where
351 * other backends access the memory formerly occupied by this hash table.
355 /* Free the active table and control object. */
363 * Get a handle that can be used by other processes to attach to this hash
375 * Look up an entry, given a key. Returns a pointer to an entry if one can be
376 * found with the given key. Returns NULL if the key is not found. If a
377 * non-NULL value is returned, the entry is locked and must be released by
378 * calling dshash_release_lock. If an error is raised before
379 * dshash_release_lock is called, the lock will be released automatically, but
380 * the caller must take care to ensure that the entry is not left corrupted.
381 * The lock mode is either shared or exclusive depending on 'exclusive'.
383 * The caller must not hold a lock already.
385 * Note that the lock held is in fact an LWLock, so interrupts will be held on
386 * return from this function, and not resumed until dshash_release_lock is
387 * called. It is a very good idea for the caller to release the lock quickly.
406 /* Search the active bucket. */
417 /* The caller will free the lock by calling dshash_release_lock. */
423 * Returns a pointer to an exclusively locked item which must be released with
424 * dshash_release_lock. If the key is found in the hash table, 'found' is set
425 * to true and a pointer to the existing entry is returned. If the key is not
426 * found, 'found' is set to false, and a pointer to a newly created entry is
429 * Notes above dshash_find() regarding locking and error handling equally
438 size_t partition_index;
454 /* Search the active bucket. */
463 /* Check if we are getting too full. */
467 * The load factor (= keys / buckets) for all buckets protected by
468 * this partition is > 0.75. Presumably the same applies
469 * generally across the whole hash table (though we don't attempt
470 * to track that directly to avoid contention on some kind of
471 * central counter; we just assume that this partition is
472 * representative). This is a good time to resize.
474 * Give up our existing lock first, because resizing needs to
475 * reacquire all the locks in the right order to avoid deadlocks.
483 /* Finally we can try to insert the new item. */
487 /* Adjust per-lock-partition counter for load factor knowledge. */
491 /* The caller must release the lock with dshash_release_lock. */
496 * Remove an entry by key. Returns true if the key was found and the
497 * corresponding entry was removed.
499 * To delete an entry that you already have a pointer to, see
500 * dshash_delete_entry.
534 * Remove an entry. The entry must already be exclusively locked, and must
535 * have been obtained by dshash_find or dshash_find_or_insert. Note that this
536 * function releases the lock just like dshash_release_lock.
538 * To delete an entry by key, see dshash_delete_key.
555 * Unlock an entry which was locked by dshash_find or dshash_find_or_insert.
569 * A compare function that forwards to memcmp.
574 return memcmp(
a,
b, size);
578 * A hash function that forwards to tag_hash.
587 * A copy function that forwards to memcpy.
592 (void) memcpy(
dest, src, size);
596 * A compare function that forwards to strcmp.
601 Assert(strlen((
const char *)
a) < size);
602 Assert(strlen((
const char *)
b) < size);
604 return strcmp((
const char *)
a, (
const char *)
b);
608 * A hash function that forwards to string_hash.
613 Assert(strlen((
const char *) v) < size);
619 * A copy function that forwards to strcpy.
624 Assert(strlen((
const char *) src) < size);
626 (void) strcpy((
char *)
dest, (
const char *) src);
630 * Sequentially scan through dshash table and return all the elements one by
631 * one, return NULL when all elements have been returned.
633 * dshash_seq_term needs to be called when a scan finished. The caller may
634 * delete returned elements midst of a scan by using dshash_delete_current()
635 * if exclusive = true.
651 * Returns the next element.
653 * Returned elements are locked and the caller may not release the lock. It is
654 * released by future calls to dshash_seq_next() or dshash_seq_term().
662 * Not yet holding any partition locks. Need to determine the size of the
663 * hash table, it could have been resized since we were looking last.
664 * Since we iterate in partition order, we can start by unconditionally
667 * Once we hold the lock, no resizing can happen until the scan ends. So
668 * we don't need to repeatedly call ensure_valid_bucket_pointers().
694 /* Move to the next bucket if we finished the current bucket */
701 /* all buckets have been scanned. finish. */
705 /* Check if move to the next partition */
713 * Move to the next partition. Lock the next partition then
714 * release the current, not in the reverse order to avoid
715 * concurrent resizing. Avoid dead lock by taking lock in the
716 * same order with resize().
733 * The caller may delete the item. Store the next item in case of
742 * Terminates the seqscan and release all locks.
744 * Needs to be called after finishing or when exiting a seqscan.
754 * Remove the current entry of the seq scan.
774 * Print debugging information about the internal state of the hash table to
775 * stderr. The caller must hold no partition locks.
795 "hash table size = %zu\n", (
size_t) 1 << hash_table->
size_log2);
802 fprintf(stderr,
" partition %zu\n",
i);
804 " active buckets (key count = %zu)\n", partition->
count);
806 for (
j = begin;
j < end; ++
j)
820 fprintf(stderr,
" bucket %zu (key count = %zu)\n",
j, count);
829 * Delete a locked item to which we have a pointer.
852 * Grow the hash table if necessary to the requested number of buckets. The
853 * requested size must be double some previously observed size.
855 * Must be called without any partition lock held.
864 size_t new_size = ((size_t) 1) << new_size_log2;
868 * Acquire the locks for all lock partitions. This is expensive, but we
869 * shouldn't have to do it many times.
879 * Another backend has already increased the size; we can avoid
880 * obtaining all the locks and return early.
889 /* Allocate the space for the new table. */
897 * We've allocated the new bucket array; all that remains to do now is to
898 * reinsert all items, which amounts to adjusting all the pointers.
901 for (
i = 0;
i < size; ++
i)
911 next_item_pointer = item->
next;
915 item_pointer = next_item_pointer;
919 /* Swap the hash table into place and free the old one. */
923 hash_table->
buckets = new_buckets;
926 /* Release all the locks. */
932 * Make sure that our backend-local bucket pointers are up to date. The
933 * caller must have locked one lock partition, which prevents resize() from
934 * running concurrently.
948 * Scan a locked bucket for a match, using the provided compare function.
961 item_pointer = item->
next;
967 * Insert an already-allocated item into a bucket.
977 item->
next = *bucket;
978 *bucket = item_pointer;
982 * Allocate space for an entry with the given key and insert it into the
1003 * Search a bucket for a matching key and delete it.
1022 *bucket_head =
next;
1026 bucket_head = &item->
next;
1032 * Delete the specified item from the bucket.
1045 if (bucket_item == item)
1051 *bucket_head =
next;
1054 bucket_head = &bucket_item->
next;
1060 * Compute the hash value for a key.
1071 * Check whether two keys compare equal.
1078 hash_table->
arg) == 0;
#define PG_USED_FOR_ASSERTS_ONLY
#define fprintf(file, fmt, msg)
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
dsa_pointer dsa_allocate_extended(dsa_area *area, size_t size, int flags)
void dsa_free(dsa_area *area, dsa_pointer dp)
#define dsa_allocate(area, size)
#define InvalidDsaPointer
#define DsaPointerIsValid(x)
bool dshash_delete_key(dshash_table *hash_table, const void *key)
void dshash_memcpy(void *dest, const void *src, size_t size, void *arg)
void dshash_delete_entry(dshash_table *hash_table, void *entry)
void dshash_strcpy(void *dest, const void *src, size_t size, void *arg)
void dshash_destroy(dshash_table *hash_table)
void dshash_release_lock(dshash_table *hash_table, void *entry)
#define PARTITION_LOCK(hash_table, i)
void dshash_detach(dshash_table *hash_table)
void dshash_seq_init(dshash_seq_status *status, dshash_table *hash_table, bool exclusive)
void * dshash_find(dshash_table *hash_table, const void *key, bool exclusive)
#define BUCKET_INDEX_FOR_HASH_AND_SIZE(hash, size_log2)
static bool delete_key_from_bucket(dshash_table *hash_table, const void *key, dsa_pointer *bucket_head)
dshash_hash dshash_strhash(const void *v, size_t size, void *arg)
static dshash_hash hash_key(dshash_table *hash_table, const void *key)
#define ASSERT_NO_PARTITION_LOCKS_HELD_BY_ME(hash_table)
#define ITEM_FROM_ENTRY(entry)
dshash_table_handle dshash_get_hash_table_handle(dshash_table *hash_table)
void dshash_dump(dshash_table *hash_table)
static bool equal_keys(dshash_table *hash_table, const void *a, const void *b)
dshash_table * dshash_attach(dsa_area *area, const dshash_parameters *params, dshash_table_handle handle, void *arg)
void dshash_seq_term(dshash_seq_status *status)
static void insert_item_into_bucket(dshash_table *hash_table, dsa_pointer item_pointer, dshash_table_item *item, dsa_pointer *bucket)
static bool delete_item_from_bucket(dshash_table *hash_table, dshash_table_item *item, dsa_pointer *bucket_head)
#define DSHASH_NUM_PARTITIONS
int dshash_strcmp(const void *a, const void *b, size_t size, void *arg)
#define PARTITION_FOR_BUCKET_INDEX(bucket_idx, size_log2)
static dshash_table_item * insert_into_bucket(dshash_table *hash_table, const void *key, dsa_pointer *bucket)
void * dshash_find_or_insert(dshash_table *hash_table, const void *key, bool *found)
#define BUCKET_INDEX_FOR_PARTITION(partition, size_log2)
#define MAX_COUNT_PER_PARTITION(hash_table)
#define ENTRY_FROM_ITEM(item)
#define DSHASH_NUM_PARTITIONS_LOG2
static void delete_item(dshash_table *hash_table, dshash_table_item *item)
dshash_hash dshash_memhash(const void *v, size_t size, void *arg)
#define NUM_BUCKETS(size_log2)
static void ensure_valid_bucket_pointers(dshash_table *hash_table)
static dshash_table_item * find_in_bucket(dshash_table *hash_table, const void *key, dsa_pointer item_pointer)
void * dshash_seq_next(dshash_seq_status *status)
dshash_table * dshash_create(dsa_area *area, const dshash_parameters *params, void *arg)
static void resize(dshash_table *hash_table, size_t new_size_log2)
static void copy_key(dshash_table *hash_table, void *dest, const void *src)
int dshash_memcmp(const void *a, const void *b, size_t size, void *arg)
struct dshash_table_control dshash_table_control
#define PARTITION_FOR_HASH(hash)
struct dshash_partition dshash_partition
#define BUCKET_FOR_HASH(hash_table, hash)
void dshash_delete_current(dshash_seq_status *status)
dsa_pointer dshash_table_handle
int errdetail(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
uint32 tag_hash(const void *key, Size keysize)
uint32 string_hash(const void *key, Size keysize)
Assert(PointerIsAligned(start, uint64))
bool LWLockHeldByMe(LWLock *lock)
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
void LWLockRelease(LWLock *lock)
void LWLockInitialize(LWLock *lock, int tranche_id)
void pfree(void *pointer)
static unsigned hash(unsigned *uv, int n)
dshash_hash_function hash_function
dshash_compare_function compare_function
dshash_copy_function copy_function
dshash_table_item * curitem
dshash_table * hash_table
dshash_partition partitions[DSHASH_NUM_PARTITIONS]
dshash_table_handle handle
dshash_table_control * control