PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
hsearch.h File Reference
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  HASHELEMENT
 
struct  HASHCTL
 
struct  HASH_SEQ_STATUS
 

Macros

#define HASH_PARTITION   0x0001 /* Hashtable is used w/partitioned locking */
 
#define HASH_SEGMENT   0x0002 /* Set segment size */
 
#define HASH_DIRSIZE   0x0004 /* Set directory size (initial and max) */
 
#define HASH_FFACTOR   0x0008 /* Set fill factor */
 
#define HASH_ELEM   0x0010 /* Set keysize and entrysize */
 
#define HASH_BLOBS   0x0020 /* Select support functions for binary keys */
 
#define HASH_FUNCTION   0x0040 /* Set user defined hash function */
 
#define HASH_COMPARE   0x0080 /* Set user defined comparison function */
 
#define HASH_KEYCOPY   0x0100 /* Set user defined key-copying function */
 
#define HASH_ALLOC   0x0200 /* Set memory allocator */
 
#define HASH_CONTEXT   0x0400 /* Set memory allocation context */
 
#define HASH_SHARED_MEM   0x0800 /* Hashtable is in shared memory */
 
#define HASH_ATTACH   0x1000 /* Do not initialize hctl */
 
#define HASH_FIXED_SIZE   0x2000 /* Initial size is a hard limit */
 
#define NO_MAX_DSIZE   (-1)
 
#define oid_hash   uint32_hash /* Remove me eventually */
 

Typedefs

typedef uint32(* HashValueFunc )(const void *key, Size keysize)
 
typedef int(* HashCompareFunc )(const void *key1, const void *key2, Size keysize)
 
typedef void *(* HashCopyFunc )(void *dest, const void *src, Size keysize)
 
typedef void *(* HashAllocFunc )(Size request)
 
typedef struct HASHELEMENT HASHELEMENT
 
typedef struct HASHHDR HASHHDR
 
typedef struct HTAB HTAB
 
typedef struct HASHCTL HASHCTL
 

Enumerations

enum  HASHACTION { HASH_FIND, HASH_ENTER, HASH_REMOVE, HASH_ENTER_NULL }
 

Functions

HTABhash_create (const char *tabname, long nelem, HASHCTL *info, int flags)
 
void hash_destroy (HTAB *hashp)
 
void hash_stats (const char *where, HTAB *hashp)
 
void * hash_search (HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
 
uint32 get_hash_value (HTAB *hashp, const void *keyPtr)
 
void * hash_search_with_hash_value (HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
 
bool hash_update_hash_key (HTAB *hashp, void *existingEntry, const void *newKeyPtr)
 
long hash_get_num_entries (HTAB *hashp)
 
void hash_seq_init (HASH_SEQ_STATUS *status, HTAB *hashp)
 
void * hash_seq_search (HASH_SEQ_STATUS *status)
 
void hash_seq_term (HASH_SEQ_STATUS *status)
 
void hash_freeze (HTAB *hashp)
 
Size hash_estimate_size (long num_entries, Size entrysize)
 
long hash_select_dirsize (long num_entries)
 
Size hash_get_shared_size (HASHCTL *info, int flags)
 
void AtEOXact_HashTables (bool isCommit)
 
void AtEOSubXact_HashTables (bool isCommit, int nestDepth)
 
uint32 string_hash (const void *key, Size keysize)
 
uint32 tag_hash (const void *key, Size keysize)
 
uint32 uint32_hash (const void *key, Size keysize)
 
uint32 bitmap_hash (const void *key, Size keysize)
 
int bitmap_match (const void *key1, const void *key2, Size keysize)
 

Macro Definition Documentation

#define HASH_ALLOC   0x0200 /* Set memory allocator */

Definition at line 92 of file hsearch.h.

Referenced by hash_create(), and ShmemInitHash().

#define HASH_ATTACH   0x1000 /* Do not initialize hctl */

Definition at line 95 of file hsearch.h.

Referenced by hash_create(), and ShmemInitHash().

#define HASH_COMPARE   0x0080 /* Set user defined comparison function */
#define HASH_DIRSIZE   0x0004 /* Set directory size (initial and max) */

Definition at line 85 of file hsearch.h.

Referenced by hash_create(), hash_get_shared_size(), and ShmemInitHash().

#define HASH_ELEM   0x0010 /* Set keysize and entrysize */

Definition at line 87 of file hsearch.h.

Referenced by _hash_finish_split(), _PG_init(), assign_record_type_typmod(), begin_heap_rewrite(), build_join_rel_hash(), BuildEventTriggerCache(), CompactCheckpointerRequestQueue(), compute_array_stats(), compute_tsvector_stats(), create_seq_hashtable(), createConnHash(), do_autovacuum(), EnablePortalManager(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), GetComboCommandId(), GetConnection(), GetSerializableTransactionSnapshotInt(), gistInitBuildBuffers(), gistInitParentMap(), hash_create(), init_procedure_caches(), init_rel_sync_cache(), init_timezone_hashtable(), init_ts_config_cache(), InitBufferPoolAccess(), InitBufTable(), InitializeAttoptCache(), InitializeRelfilenodeMap(), InitializeShippableCache(), InitializeTableSpaceCache(), InitLocalBuffers(), InitLocks(), InitPredicateLocks(), InitQueryHashTable(), InitShmemIndex(), load_categories_hash(), log_invalid_page(), logical_begin_heap_rewrite(), logicalrep_relmap_init(), lookup_collation_cache(), lookup_proof_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), mdinit(), pgss_shmem_startup(), pgstat_collect_oids(), pgstat_init_function_usage(), pgstat_read_statsfiles(), plpgsql_estate_setup(), plpgsql_HashTableInit(), PLy_add_exceptions(), populate_recordset_object_start(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RelationCacheInitialize(), ReorderBufferAllocate(), ReorderBufferBuildTupleCidHash(), ReorderBufferToastInitHash(), reset_dbentry_counters(), ResetUnloggedRelationsInDbspaceDir(), ri_InitHashTables(), select_perl_context(), set_rtable_names(), smgropen(), TQSendRecordInfo(), transformGraph(), and TupleQueueHandleControlMessage().

#define HASH_FFACTOR   0x0008 /* Set fill factor */

Definition at line 86 of file hsearch.h.

Referenced by hash_create().

#define HASH_FIXED_SIZE   0x2000 /* Initial size is a hard limit */

Definition at line 96 of file hsearch.h.

Referenced by hash_create(), and InitPredicateLocks().

#define HASH_FUNCTION   0x0040 /* Set user defined hash function */
#define HASH_KEYCOPY   0x0100 /* Set user defined key-copying function */

Definition at line 91 of file hsearch.h.

Referenced by hash_create().

#define HASH_PARTITION   0x0001 /* Hashtable is used w/partitioned locking */

Definition at line 83 of file hsearch.h.

Referenced by hash_create(), InitBufTable(), InitLocks(), and InitPredicateLocks().

#define HASH_SEGMENT   0x0002 /* Set segment size */

Definition at line 84 of file hsearch.h.

Referenced by hash_create().

#define HASH_SHARED_MEM   0x0800 /* Hashtable is in shared memory */

Definition at line 94 of file hsearch.h.

Referenced by hash_create(), and ShmemInitHash().

#define NO_MAX_DSIZE   (-1)

Definition at line 100 of file hsearch.h.

Referenced by dir_realloc(), and hdefault().

#define oid_hash   uint32_hash /* Remove me eventually */

Definition at line 158 of file hsearch.h.

Typedef Documentation

typedef void*(* HashAllocFunc)(Size request)

Definition at line 44 of file hsearch.h.

typedef int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)

Definition at line 29 of file hsearch.h.

typedef void*(* HashCopyFunc)(void *dest, const void *src, Size keysize)

Definition at line 37 of file hsearch.h.

Definition at line 58 of file hsearch.h.

typedef uint32(* HashValueFunc)(const void *key, Size keysize)

Definition at line 21 of file hsearch.h.

typedef struct HTAB HTAB

Definition at line 61 of file hsearch.h.

Enumeration Type Documentation

enum HASHACTION
Enumerator
HASH_FIND 
HASH_ENTER 
HASH_REMOVE 
HASH_ENTER_NULL 

Definition at line 103 of file hsearch.h.

104 {
105  HASH_FIND,
106  HASH_ENTER,
107  HASH_REMOVE,
109 } HASHACTION;
HASHACTION
Definition: hsearch.h:103

Function Documentation

void AtEOSubXact_HashTables ( bool  isCommit,
int  nestDepth 
)

Definition at line 1824 of file dynahash.c.

References elog, i, num_seq_scans, seq_scan_level, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

1825 {
1826  int i;
1827 
1828  /*
1829  * Search backward to make cleanup easy. Note we must check all entries,
1830  * not only those at the end of the array, because deletion technique
1831  * doesn't keep them in order.
1832  */
1833  for (i = num_seq_scans - 1; i >= 0; i--)
1834  {
1835  if (seq_scan_level[i] >= nestDepth)
1836  {
1837  if (isCommit)
1838  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1839  seq_scan_tables[i]);
1842  num_seq_scans--;
1843  }
1844  }
1845 }
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1745
#define WARNING
Definition: elog.h:40
static int num_seq_scans
Definition: dynahash.c:1746
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1744
int i
#define elog
Definition: elog.h:219
void AtEOXact_HashTables ( bool  isCommit)

Definition at line 1798 of file dynahash.c.

References elog, i, num_seq_scans, and WARNING.

Referenced by AbortTransaction(), BackgroundWriterMain(), CheckpointerMain(), CommitTransaction(), PrepareTransaction(), and WalWriterMain().

1799 {
1800  /*
1801  * During abort cleanup, open scans are expected; just silently clean 'em
1802  * out. An open scan at commit means someone forgot a hash_seq_term()
1803  * call, so complain.
1804  *
1805  * Note: it's tempting to try to print the tabname here, but refrain for
1806  * fear of touching deallocated memory. This isn't a user-facing message
1807  * anyway, so it needn't be pretty.
1808  */
1809  if (isCommit)
1810  {
1811  int i;
1812 
1813  for (i = 0; i < num_seq_scans; i++)
1814  {
1815  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1816  seq_scan_tables[i]);
1817  }
1818  }
1819  num_seq_scans = 0;
1820 }
#define WARNING
Definition: elog.h:40
static int num_seq_scans
Definition: dynahash.c:1746
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1744
int i
#define elog
Definition: elog.h:219
uint32 bitmap_hash ( const void *  key,
Size  keysize 
)

Definition at line 76 of file hashfn.c.

References Assert, and bms_hash_value().

Referenced by build_join_rel_hash().

77 {
78  Assert(keysize == sizeof(Bitmapset *));
79  return bms_hash_value(*((const Bitmapset *const *) key));
80 }
uint32 bms_hash_value(const Bitmapset *a)
Definition: bitmapset.c:954
#define Assert(condition)
Definition: c.h:675
int bitmap_match ( const void *  key1,
const void *  key2,
Size  keysize 
)

Definition at line 86 of file hashfn.c.

References Assert, and bms_equal().

Referenced by build_join_rel_hash().

87 {
88  Assert(keysize == sizeof(Bitmapset *));
89  return !bms_equal(*((const Bitmapset *const *) key1),
90  *((const Bitmapset *const *) key2));
91 }
#define Assert(condition)
Definition: c.h:675
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:130
uint32 get_hash_value ( HTAB hashp,
const void *  keyPtr 
)

Definition at line 839 of file dynahash.c.

References HTAB::hash, and HTAB::keysize.

Referenced by BufTableHashCode(), and LockTagHashCode().

840 {
841  return hashp->hash(keyPtr, hashp->keysize);
842 }
Size keysize
Definition: dynahash.c:210
HashValueFunc hash
Definition: dynahash.c:197
HTAB* hash_create ( const char *  tabname,
long  nelem,
HASHCTL info,
int  flags 
)

Definition at line 301 of file dynahash.c.

References HASHCTL::alloc, HTAB::alloc, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Assert, CurrentDynaHashCxt, HTAB::dir, HASHCTL::dsize, HASHHDR::dsize, DynaHashAlloc(), element_alloc(), elog, HASHCTL::entrysize, HASHHDR::entrysize, ereport, errcode(), errmsg(), ERROR, HASHCTL::ffactor, HASHHDR::ffactor, HTAB::frozen, HASHCTL::hash, HTAB::hash, HASH_ALLOC, HASH_ATTACH, HASH_BLOBS, HASH_COMPARE, HASH_CONTEXT, HASH_DIRSIZE, HASH_ELEM, HASH_FFACTOR, HASH_FIXED_SIZE, HASH_FUNCTION, HASH_KEYCOPY, HASH_PARTITION, HASH_SEGMENT, HASH_SHARED_MEM, HASHCTL::hctl, HTAB::hctl, HASHCTL::hcxt, HTAB::hcxt, hdefault(), i, init_htab(), IS_PARTITIONED, HTAB::isfixed, HTAB::isshared, HASHCTL::keycopy, HTAB::keycopy, HASHCTL::keysize, HASHHDR::keysize, HTAB::keysize, HASHCTL::match, HTAB::match, HASHCTL::max_dsize, HASHHDR::max_dsize, MemSet, my_log2(), next_pow2_int(), NULL, NUM_FREELISTS, HASHCTL::num_partitions, HASHHDR::num_partitions, HASHHDR::sshift, HTAB::sshift, HASHCTL::ssize, HASHHDR::ssize, HTAB::ssize, string_compare(), string_hash(), strlcpy(), HTAB::tabname, tag_hash(), TopMemoryContext, and uint32_hash().

Referenced by _hash_finish_split(), _PG_init(), assign_record_type_typmod(), begin_heap_rewrite(), build_join_rel_hash(), BuildEventTriggerCache(), CompactCheckpointerRequestQueue(), compute_array_stats(), compute_tsvector_stats(), create_seq_hashtable(), createConnHash(), do_autovacuum(), EnablePortalManager(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), GetComboCommandId(), GetConnection(), GetSerializableTransactionSnapshotInt(), gistInitBuildBuffers(), gistInitParentMap(), init_procedure_caches(), init_rel_sync_cache(), init_timezone_hashtable(), init_ts_config_cache(), InitBufferPoolAccess(), InitializeAttoptCache(), InitializeRelfilenodeMap(), InitializeShippableCache(), InitializeTableSpaceCache(), InitLocalBuffers(), InitLocks(), InitQueryHashTable(), load_categories_hash(), log_invalid_page(), logical_begin_heap_rewrite(), logicalrep_relmap_init(), lookup_collation_cache(), lookup_proof_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), mdinit(), pgstat_collect_oids(), pgstat_init_function_usage(), pgstat_read_statsfiles(), plpgsql_estate_setup(), plpgsql_HashTableInit(), PLy_add_exceptions(), populate_recordset_object_start(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RelationCacheInitialize(), ReorderBufferAllocate(), ReorderBufferBuildTupleCidHash(), ReorderBufferToastInitHash(), reset_dbentry_counters(), ResetUnloggedRelationsInDbspaceDir(), ri_InitHashTables(), select_perl_context(), set_rtable_names(), ShmemInitHash(), smgropen(), TQSendRecordInfo(), transformGraph(), and TupleQueueHandleControlMessage().

302 {
303  HTAB *hashp;
304  HASHHDR *hctl;
305 
306  /*
307  * For shared hash tables, we have a local hash header (HTAB struct) that
308  * we allocate in TopMemoryContext; all else is in shared memory.
309  *
310  * For non-shared hash tables, everything including the hash header is in
311  * a memory context created specially for the hash table --- this makes
312  * hash_destroy very simple. The memory context is made a child of either
313  * a context specified by the caller, or TopMemoryContext if nothing is
314  * specified.
315  */
316  if (flags & HASH_SHARED_MEM)
317  {
318  /* Set up to allocate the hash header */
320  }
321  else
322  {
323  /* Create the hash table's private memory context */
324  if (flags & HASH_CONTEXT)
325  CurrentDynaHashCxt = info->hcxt;
326  else
329  tabname,
331  }
332 
333  /* Initialize the hash header, plus a copy of the table name */
334  hashp = (HTAB *) DynaHashAlloc(sizeof(HTAB) + strlen(tabname) +1);
335  MemSet(hashp, 0, sizeof(HTAB));
336 
337  hashp->tabname = (char *) (hashp + 1);
338  strcpy(hashp->tabname, tabname);
339 
340  /*
341  * Select the appropriate hash function (see comments at head of file).
342  */
343  if (flags & HASH_FUNCTION)
344  hashp->hash = info->hash;
345  else if (flags & HASH_BLOBS)
346  {
347  /* We can optimize hashing for common key sizes */
349  if (info->keysize == sizeof(uint32))
350  hashp->hash = uint32_hash;
351  else
352  hashp->hash = tag_hash;
353  }
354  else
355  hashp->hash = string_hash; /* default hash function */
356 
357  /*
358  * If you don't specify a match function, it defaults to string_compare if
359  * you used string_hash (either explicitly or by default) and to memcmp
360  * otherwise.
361  *
362  * Note: explicitly specifying string_hash is deprecated, because this
363  * might not work for callers in loadable modules on some platforms due to
364  * referencing a trampoline instead of the string_hash function proper.
365  * Just let it default, eh?
366  */
367  if (flags & HASH_COMPARE)
368  hashp->match = info->match;
369  else if (hashp->hash == string_hash)
371  else
372  hashp->match = memcmp;
373 
374  /*
375  * Similarly, the key-copying function defaults to strlcpy or memcpy.
376  */
377  if (flags & HASH_KEYCOPY)
378  hashp->keycopy = info->keycopy;
379  else if (hashp->hash == string_hash)
380  hashp->keycopy = (HashCopyFunc) strlcpy;
381  else
382  hashp->keycopy = memcpy;
383 
384  /* And select the entry allocation function, too. */
385  if (flags & HASH_ALLOC)
386  hashp->alloc = info->alloc;
387  else
388  hashp->alloc = DynaHashAlloc;
389 
390  if (flags & HASH_SHARED_MEM)
391  {
392  /*
393  * ctl structure and directory are preallocated for shared memory
394  * tables. Note that HASH_DIRSIZE and HASH_ALLOC had better be set as
395  * well.
396  */
397  hashp->hctl = info->hctl;
398  hashp->dir = (HASHSEGMENT *) (((char *) info->hctl) + sizeof(HASHHDR));
399  hashp->hcxt = NULL;
400  hashp->isshared = true;
401 
402  /* hash table already exists, we're just attaching to it */
403  if (flags & HASH_ATTACH)
404  {
405  /* make local copies of some heavily-used values */
406  hctl = hashp->hctl;
407  hashp->keysize = hctl->keysize;
408  hashp->ssize = hctl->ssize;
409  hashp->sshift = hctl->sshift;
410 
411  return hashp;
412  }
413  }
414  else
415  {
416  /* setup hash table defaults */
417  hashp->hctl = NULL;
418  hashp->dir = NULL;
419  hashp->hcxt = CurrentDynaHashCxt;
420  hashp->isshared = false;
421  }
422 
423  if (!hashp->hctl)
424  {
425  hashp->hctl = (HASHHDR *) hashp->alloc(sizeof(HASHHDR));
426  if (!hashp->hctl)
427  ereport(ERROR,
428  (errcode(ERRCODE_OUT_OF_MEMORY),
429  errmsg("out of memory")));
430  }
431 
432  hashp->frozen = false;
433 
434  hdefault(hashp);
435 
436  hctl = hashp->hctl;
437 
438  if (flags & HASH_PARTITION)
439  {
440  /* Doesn't make sense to partition a local hash table */
441  Assert(flags & HASH_SHARED_MEM);
442 
443  /*
444  * The number of partitions had better be a power of 2. Also, it must
445  * be less than INT_MAX (see init_htab()), so call the int version of
446  * next_pow2.
447  */
449 
450  hctl->num_partitions = info->num_partitions;
451  }
452 
453  if (flags & HASH_SEGMENT)
454  {
455  hctl->ssize = info->ssize;
456  hctl->sshift = my_log2(info->ssize);
457  /* ssize had better be a power of 2 */
458  Assert(hctl->ssize == (1L << hctl->sshift));
459  }
460  if (flags & HASH_FFACTOR)
461  hctl->ffactor = info->ffactor;
462 
463  /*
464  * SHM hash tables have fixed directory size passed by the caller.
465  */
466  if (flags & HASH_DIRSIZE)
467  {
468  hctl->max_dsize = info->max_dsize;
469  hctl->dsize = info->dsize;
470  }
471 
472  /*
473  * hash table now allocates space for key and data but you have to say how
474  * much space to allocate
475  */
476  if (flags & HASH_ELEM)
477  {
478  Assert(info->entrysize >= info->keysize);
479  hctl->keysize = info->keysize;
480  hctl->entrysize = info->entrysize;
481  }
482 
483  /* make local copies of heavily-used constant fields */
484  hashp->keysize = hctl->keysize;
485  hashp->ssize = hctl->ssize;
486  hashp->sshift = hctl->sshift;
487 
488  /* Build the hash directory structure */
489  if (!init_htab(hashp, nelem))
490  elog(ERROR, "failed to initialize hash table \"%s\"", hashp->tabname);
491 
492  /*
493  * For a shared hash table, preallocate the requested number of elements.
494  * This reduces problems with run-time out-of-shared-memory conditions.
495  *
496  * For a non-shared hash table, preallocate the requested number of
497  * elements if it's less than our chosen nelem_alloc. This avoids wasting
498  * space if the caller correctly estimates a small table size.
499  */
500  if ((flags & HASH_SHARED_MEM) ||
501  nelem < hctl->nelem_alloc)
502  {
503  int i,
504  freelist_partitions,
505  nelem_alloc,
506  nelem_alloc_first;
507 
508  /*
509  * If hash table is partitioned all freeLists have equal number of
510  * elements. Otherwise only freeList[0] is used.
511  */
512  if (IS_PARTITIONED(hashp->hctl))
513  freelist_partitions = NUM_FREELISTS;
514  else
515  freelist_partitions = 1;
516 
517  nelem_alloc = nelem / freelist_partitions;
518  if (nelem_alloc == 0)
519  nelem_alloc = 1;
520 
521  /* Make sure all memory will be used */
522  if (nelem_alloc * freelist_partitions < nelem)
523  nelem_alloc_first =
524  nelem - nelem_alloc * (freelist_partitions - 1);
525  else
526  nelem_alloc_first = nelem_alloc;
527 
528  for (i = 0; i < freelist_partitions; i++)
529  {
530  int temp = (i == 0) ? nelem_alloc_first : nelem_alloc;
531 
532  if (!element_alloc(hashp, temp, i))
533  ereport(ERROR,
534  (errcode(ERRCODE_OUT_OF_MEMORY),
535  errmsg("out of memory")));
536  }
537  }
538 
539  if (flags & HASH_FIXED_SIZE)
540  hashp->isfixed = true;
541  return hashp;
542 }
Size keysize
Definition: dynahash.c:164
Size keysize
Definition: dynahash.c:210
long dsize
Definition: dynahash.c:157
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
long ssize
Definition: hsearch.h:68
HashCopyFunc keycopy
Definition: hsearch.h:76
Size entrysize
Definition: dynahash.c:165
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:184
uint32 string_hash(const void *key, Size keysize)
Definition: hashfn.c:34
long num_partitions
Definition: dynahash.c:166
Size entrysize
Definition: hsearch.h:73
#define NUM_FREELISTS
Definition: dynahash.c:115
int errcode(int sqlerrcode)
Definition: elog.c:575
HashAllocFunc alloc
Definition: dynahash.c:200
#define MemSet(start, val, len)
Definition: c.h:857
#define HASH_SHARED_MEM
Definition: hsearch.h:94
static int string_compare(const char *key1, const char *key2, Size keysize)
Definition: dynahash.c:278
long dsize
Definition: hsearch.h:69
uint32 uint32_hash(const void *key, Size keysize)
Definition: hashfn.c:64
#define HASH_PARTITION
Definition: hsearch.h:83
#define HASH_ATTACH
Definition: hsearch.h:95
long ffactor
Definition: dynahash.c:167
HashValueFunc hash
Definition: dynahash.c:197
Definition: dynahash.c:193
long max_dsize
Definition: hsearch.h:70
long ssize
Definition: dynahash.c:211
#define ERROR
Definition: elog.h:43
long num_partitions
Definition: hsearch.h:67
int sshift
Definition: dynahash.c:212
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
HashAllocFunc alloc
Definition: hsearch.h:77
#define HASH_KEYCOPY
Definition: hsearch.h:91
long max_dsize
Definition: dynahash.c:168
static void hdefault(HTAB *hashp)
Definition: dynahash.c:548
HASHHDR * hctl
Definition: dynahash.c:195
unsigned int uint32
Definition: c.h:268
static bool init_htab(HTAB *hashp, long nelem)
Definition: dynahash.c:614
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
int my_log2(long num)
Definition: dynahash.c:1682
HashCompareFunc match
Definition: dynahash.c:198
static int next_pow2_int(long num)
Definition: dynahash.c:1706
bool isshared
Definition: dynahash.c:203
#define HASH_BLOBS
Definition: hsearch.h:88
bool frozen
Definition: dynahash.c:207
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
uint32 tag_hash(const void *key, Size keysize)
Definition: hashfn.c:52
long ssize
Definition: dynahash.c:169
Size keysize
Definition: hsearch.h:72
HashCompareFunc match
Definition: hsearch.h:75
MemoryContext hcxt
Definition: dynahash.c:201
HashCopyFunc keycopy
Definition: dynahash.c:199
#define HASH_SEGMENT
Definition: hsearch.h:84
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define HASH_COMPARE
Definition: hsearch.h:90
HASHHDR * hctl
Definition: hsearch.h:79
long ffactor
Definition: hsearch.h:71
char * tabname
Definition: dynahash.c:202
#define HASH_FIXED_SIZE
Definition: hsearch.h:96
bool isfixed
Definition: dynahash.c:204
#define HASH_FFACTOR
Definition: hsearch.h:86
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:263
int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)
Definition: hsearch.h:29
#define HASH_DIRSIZE
Definition: hsearch.h:85
int errmsg(const char *fmt,...)
Definition: elog.c:797
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:260
int i
#define HASH_ALLOC
Definition: hsearch.h:92
HASHSEGMENT * dir
Definition: dynahash.c:196
#define elog
Definition: elog.h:219
static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx)
Definition: dynahash.c:1621
int sshift
Definition: dynahash.c:170
void *(* HashCopyFunc)(void *dest, const void *src, Size keysize)
Definition: hsearch.h:37
HashValueFunc hash
Definition: hsearch.h:74
#define HASH_FUNCTION
Definition: hsearch.h:89
void hash_destroy ( HTAB hashp)

Definition at line 793 of file dynahash.c.

References HTAB::alloc, Assert, DynaHashAlloc(), hash_stats(), HTAB::hcxt, MemoryContextDelete(), and NULL.

Referenced by _hash_finish_split(), clear_external_function_hash(), CompactCheckpointerRequestQueue(), DestroyTupleQueueReader(), InitLocks(), pgoutput_shutdown(), pgstat_recv_dropdb(), pgstat_recv_resetcounter(), pgstat_vacuum_stat(), populate_record_worker(), populate_recordset_object_end(), PostPrepare_PredicateLocks(), ReleasePredicateLocks(), ReorderBufferReturnTXN(), ReorderBufferToastReset(), ResetSequenceCaches(), ResetUnloggedRelationsInDbspaceDir(), set_rtable_names(), SetForwardFsyncRequests(), tqueueDestroyReceiver(), and XLogCheckInvalidPages().

794 {
795  if (hashp != NULL)
796  {
797  /* allocation method must be one we know how to free, too */
798  Assert(hashp->alloc == DynaHashAlloc);
799  /* so this hashtable must have it's own context */
800  Assert(hashp->hcxt != NULL);
801 
802  hash_stats("destroy", hashp);
803 
804  /*
805  * Free everything by destroying the hash table's memory context.
806  */
807  MemoryContextDelete(hashp->hcxt);
808  }
809 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void hash_stats(const char *where, HTAB *hashp)
Definition: dynahash.c:812
HashAllocFunc alloc
Definition: dynahash.c:200
MemoryContext hcxt
Definition: dynahash.c:201
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:263
Size hash_estimate_size ( long  num_entries,
Size  entrysize 
)

Definition at line 711 of file dynahash.c.

References add_size(), choose_nelem_alloc(), DEF_DIRSIZE, DEF_FFACTOR, DEF_SEGSIZE, MAXALIGN, mul_size(), and next_pow2_long().

Referenced by BufTableShmemSize(), CreateSharedMemoryAndSemaphores(), LockShmemSize(), pgss_memsize(), and PredicateLockShmemSize().

712 {
713  Size size;
714  long nBuckets,
715  nSegments,
716  nDirEntries,
717  nElementAllocs,
718  elementSize,
719  elementAllocCnt;
720 
721  /* estimate number of buckets wanted */
722  nBuckets = next_pow2_long((num_entries - 1) / DEF_FFACTOR + 1);
723  /* # of segments needed for nBuckets */
724  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
725  /* directory entries */
726  nDirEntries = DEF_DIRSIZE;
727  while (nDirEntries < nSegments)
728  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
729 
730  /* fixed control info */
731  size = MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */
732  /* directory */
733  size = add_size(size, mul_size(nDirEntries, sizeof(HASHSEGMENT)));
734  /* segments */
735  size = add_size(size, mul_size(nSegments,
736  MAXALIGN(DEF_SEGSIZE * sizeof(HASHBUCKET))));
737  /* elements --- allocated in groups of choose_nelem_alloc() entries */
738  elementAllocCnt = choose_nelem_alloc(entrysize);
739  nElementAllocs = (num_entries - 1) / elementAllocCnt + 1;
740  elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(entrysize);
741  size = add_size(size,
742  mul_size(nElementAllocs,
743  mul_size(elementAllocCnt, elementSize)));
744 
745  return size;
746 }
static long next_pow2_long(long num)
Definition: dynahash.c:1698
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588
static int choose_nelem_alloc(Size entrysize)
Definition: dynahash.c:581
#define DEF_FFACTOR
Definition: dynahash.c:112
#define DEF_SEGSIZE
Definition: dynahash.c:109
#define DEF_DIRSIZE
Definition: dynahash.c:111
void hash_freeze ( HTAB hashp)

Definition at line 1449 of file dynahash.c.

References elog, ERROR, HTAB::frozen, has_seq_scans(), HTAB::isshared, and HTAB::tabname.

1450 {
1451  if (hashp->isshared)
1452  elog(ERROR, "cannot freeze shared hashtable \"%s\"", hashp->tabname);
1453  if (!hashp->frozen && has_seq_scans(hashp))
1454  elog(ERROR, "cannot freeze hashtable \"%s\" because it has active scans",
1455  hashp->tabname);
1456  hashp->frozen = true;
1457 }
#define ERROR
Definition: elog.h:43
static bool has_seq_scans(HTAB *hashp)
Definition: dynahash.c:1784
bool isshared
Definition: dynahash.c:203
bool frozen
Definition: dynahash.c:207
char * tabname
Definition: dynahash.c:202
#define elog
Definition: elog.h:219
long hash_get_num_entries ( HTAB hashp)

Definition at line 1297 of file dynahash.c.

References HASHHDR::freeList, HTAB::hctl, i, IS_PARTITIONED, FreeListData::nentries, and NUM_FREELISTS.

Referenced by compute_array_stats(), compute_tsvector_stats(), entry_alloc(), entry_dealloc(), get_crosstab_tuplestore(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), hash_stats(), init_htab(), pgss_shmem_shutdown(), pgstat_vacuum_stat(), populate_record_worker(), ResetUnloggedRelationsInDbspaceDir(), transformGraph(), and XLogHaveInvalidPages().

1298 {
1299  int i;
1300  long sum = hashp->hctl->freeList[0].nentries;
1301 
1302  /*
1303  * We currently don't bother with the mutex; it's only sensible to call
1304  * this function if you've got lock on all partitions of the table.
1305  */
1306 
1307  if (!IS_PARTITIONED(hashp->hctl))
1308  return sum;
1309 
1310  for (i = 1; i < NUM_FREELISTS; i++)
1311  sum += hashp->hctl->freeList[i].nentries;
1312 
1313  return sum;
1314 }
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:184
#define NUM_FREELISTS
Definition: dynahash.c:115
HASHHDR * hctl
Definition: dynahash.c:195
long nentries
Definition: dynahash.c:131
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:153
int i
Size hash_get_shared_size ( HASHCTL info,
int  flags 
)

Definition at line 782 of file dynahash.c.

References Assert, HASHCTL::dsize, HASH_DIRSIZE, and HASHCTL::max_dsize.

Referenced by ShmemInitHash().

783 {
785  Assert(info->dsize == info->max_dsize);
786  return sizeof(HASHHDR) + info->dsize * sizeof(HASHSEGMENT);
787 }
long dsize
Definition: hsearch.h:69
long max_dsize
Definition: hsearch.h:70
struct HASHHDR HASHHDR
Definition: hsearch.h:58
#define Assert(condition)
Definition: c.h:675
#define HASH_DIRSIZE
Definition: hsearch.h:85
void* hash_search ( HTAB hashp,
const void *  keyPtr,
HASHACTION  action,
bool foundPtr 
)

Definition at line 885 of file dynahash.c.

References HTAB::hash, hash_search_with_hash_value(), and HTAB::keysize.

Referenced by _hash_finish_split(), _hash_splitbucket(), add_join_rel(), ApplyLogicalMappingFile(), assign_record_type_typmod(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), build_join_rel_hash(), BuildEventTriggerCache(), CheckAndPromotePredicateLockRequest(), CheckForSerializableConflictOut(), CompactCheckpointerRequestQueue(), compile_plperl_function(), compile_pltcl_function(), compute_array_stats(), compute_tsvector_stats(), createNewConnection(), deleteConnection(), do_autovacuum(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), DropPreparedStatement(), DropRelFileNodeAllLocalBuffers(), DropRelFileNodeLocalBuffers(), entry_alloc(), entry_dealloc(), entry_reset(), EventCacheLookup(), FetchPreparedStatement(), find_funcstat_entry(), find_join_rel(), find_oper_cache_entry(), find_rendezvous_variable(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPrivateRefCountEntry(), get_attribute_options(), get_cast_hashentry(), get_pgstat_tabentry_relid(), get_rel_sync_entry(), get_tablespace(), GetComboCommandId(), GetConnection(), getConnectionByName(), GetExtensibleNodeEntry(), GetPrivateRefCountEntry(), getState(), gistGetNodeBuffer(), gistGetParent(), gistMemorizeParent(), gistRelocateBuildBuffersOnSplit(), hash_object_field_end(), init_sequence(), InitPredicateLocks(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), is_shippable(), LocalBufferAlloc(), LocalPrefetchBuffer(), LockAcquireExtended(), LockHasWaiters(), LockRelease(), log_invalid_page(), logical_rewrite_log_mapping(), logicalrep_rel_open(), logicalrep_relmap_update(), logicalrep_typmap_getid(), logicalrep_typmap_update(), lookup_C_func(), lookup_collation_cache(), lookup_proof_cache(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), make_oper_cache_entry(), mdsync(), pg_tzset(), pgss_store(), pgstat_collect_oids(), pgstat_fetch_stat_dbentry(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), pgstat_get_db_entry(), pgstat_get_tab_entry(), pgstat_init_function_usage(), pgstat_read_db_statsfile(), pgstat_read_statsfiles(), pgstat_recv_dropdb(), pgstat_recv_funcpurge(), pgstat_recv_funcstat(), pgstat_recv_resetsinglecounter(), pgstat_recv_tabpurge(), pgstat_recv_tabstat(), pgstat_vacuum_stat(), plperl_spi_exec_prepared(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query_prepared(), plpgsql_HashTableDelete(), plpgsql_HashTableInsert(), plpgsql_HashTableLookup(), pltcl_fetch_interp(), PLy_generate_spi_exceptions(), PLy_procedure_get(), PLy_spi_subtransaction_abort(), populate_record_worker(), populate_recordset_object_end(), populate_recordset_object_field_end(), predicatelock_twophase_recover(), PredicateLockExists(), PredicateLockTwoPhaseFinish(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RegisterPredicateLockingXid(), rel_sync_cache_relation_cb(), ReleaseOneSerializableXact(), RelfilenodeMapInvalidateCallback(), RelidByRelfilenode(), RememberFsyncRequest(), RemoveLocalLock(), ReorderBufferBuildTupleCidHash(), ReorderBufferCleanupTXN(), ReorderBufferToastAppendChunk(), ReorderBufferToastReplace(), ReorderBufferTXNByXid(), ReservePrivateRefCountEntry(), ResetUnloggedRelationsInDbspaceDir(), ResolveCminCmaxDuringDecoding(), rewrite_heap_dead_tuple(), rewrite_heap_tuple(), ri_FetchPreparedPlan(), ri_HashCompareOp(), ri_HashPreparedPlan(), ri_LoadConstraintInfo(), select_perl_context(), set_rtable_names(), ShmemInitStruct(), smgrclose(), smgrclosenode(), smgropen(), StorePreparedStatement(), table_recheck_autovac(), TQRemapRecord(), TQSendRecordInfo(), and TupleQueueHandleControlMessage().

889 {
890  return hash_search_with_hash_value(hashp,
891  keyPtr,
892  hashp->hash(keyPtr, hashp->keysize),
893  action,
894  foundPtr);
895 }
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:898
Size keysize
Definition: dynahash.c:210
HashValueFunc hash
Definition: dynahash.c:197
void* hash_search_with_hash_value ( HTAB hashp,
const void *  keyPtr,
uint32  hashvalue,
HASHACTION  action,
bool foundPtr 
)

Definition at line 898 of file dynahash.c.

References HTAB::alloc, Assert, calc_bucket(), HTAB::dir, DynaHashAlloc(), ELEMENTKEY, elog, ereport, errcode(), errmsg(), ERROR, expand_table(), HASHHDR::ffactor, FreeListData::freeList, HASHHDR::freeList, FREELIST_IDX, HTAB::frozen, get_hash_entry(), has_seq_scans(), hash_corrupted(), HASH_ENTER, HASH_ENTER_NULL, HASH_FIND, HASH_REMOVE, HASHELEMENT::hashvalue, HTAB::hctl, IS_PARTITIONED, HTAB::isshared, HTAB::keycopy, HTAB::keysize, HASHELEMENT::link, HTAB::match, HASHHDR::max_bucket, MOD, FreeListData::mutex, FreeListData::nentries, NULL, SpinLockAcquire, SpinLockRelease, HTAB::sshift, HTAB::ssize, and HTAB::tabname.

Referenced by BufTableDelete(), BufTableInsert(), BufTableLookup(), CheckTargetForConflictsIn(), CleanUpLock(), ClearOldPredicateLocks(), CreatePredicateLock(), DecrementParentLocks(), DeleteChildTargetLocks(), DeleteLockTarget(), DropAllPredicateLocksFromTable(), FastPathGetRelationLockEntry(), GetLockConflicts(), hash_search(), lock_twophase_recover(), LockAcquireExtended(), LockRefindAndRelease(), LockRelease(), LockWaiterCount(), PageIsPredicateLocked(), PredicateLockAcquire(), ReleaseOneSerializableXact(), RemoveScratchTarget(), RemoveTargetIfNoLongerUsed(), RestoreScratchTarget(), SetupLockInTable(), and TransferPredicateLocksToNewTarget().

903 {
904  HASHHDR *hctl = hashp->hctl;
905  Size keysize;
906  uint32 bucket;
907  long segment_num;
908  long segment_ndx;
909  HASHSEGMENT segp;
910  HASHBUCKET currBucket;
911  HASHBUCKET *prevBucketPtr;
912  HashCompareFunc match;
913  int freelist_idx = FREELIST_IDX(hctl, hashvalue);
914 
915 #if HASH_STATISTICS
916  hash_accesses++;
917  hctl->accesses++;
918 #endif
919 
920  /*
921  * If inserting, check if it is time to split a bucket.
922  *
923  * NOTE: failure to expand table is not a fatal error, it just means we
924  * have to run at higher fill factor than we wanted. However, if we're
925  * using the palloc allocator then it will throw error anyway on
926  * out-of-memory, so we must do this before modifying the table.
927  */
928  if (action == HASH_ENTER || action == HASH_ENTER_NULL)
929  {
930  /*
931  * Can't split if running in partitioned mode, nor if frozen, nor if
932  * table is the subject of any active hash_seq_search scans. Strange
933  * order of these tests is to try to check cheaper conditions first.
934  */
935  if (!IS_PARTITIONED(hctl) && !hashp->frozen &&
936  hctl->freeList[0].nentries / (long) (hctl->max_bucket + 1) >= hctl->ffactor &&
937  !has_seq_scans(hashp))
938  (void) expand_table(hashp);
939  }
940 
941  /*
942  * Do the initial lookup
943  */
944  bucket = calc_bucket(hctl, hashvalue);
945 
946  segment_num = bucket >> hashp->sshift;
947  segment_ndx = MOD(bucket, hashp->ssize);
948 
949  segp = hashp->dir[segment_num];
950 
951  if (segp == NULL)
952  hash_corrupted(hashp);
953 
954  prevBucketPtr = &segp[segment_ndx];
955  currBucket = *prevBucketPtr;
956 
957  /*
958  * Follow collision chain looking for matching key
959  */
960  match = hashp->match; /* save one fetch in inner loop */
961  keysize = hashp->keysize; /* ditto */
962 
963  while (currBucket != NULL)
964  {
965  if (currBucket->hashvalue == hashvalue &&
966  match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0)
967  break;
968  prevBucketPtr = &(currBucket->link);
969  currBucket = *prevBucketPtr;
970 #if HASH_STATISTICS
971  hash_collisions++;
972  hctl->collisions++;
973 #endif
974  }
975 
976  if (foundPtr)
977  *foundPtr = (bool) (currBucket != NULL);
978 
979  /*
980  * OK, now what?
981  */
982  switch (action)
983  {
984  case HASH_FIND:
985  if (currBucket != NULL)
986  return (void *) ELEMENTKEY(currBucket);
987  return NULL;
988 
989  case HASH_REMOVE:
990  if (currBucket != NULL)
991  {
992  /* if partitioned, must lock to touch nentries and freeList */
993  if (IS_PARTITIONED(hctl))
994  SpinLockAcquire(&(hctl->freeList[freelist_idx].mutex));
995 
996  Assert(hctl->freeList[freelist_idx].nentries > 0);
997  hctl->freeList[freelist_idx].nentries--;
998 
999  /* remove record from hash bucket's chain. */
1000  *prevBucketPtr = currBucket->link;
1001 
1002  /* add the record to the freelist for this table. */
1003  currBucket->link = hctl->freeList[freelist_idx].freeList;
1004  hctl->freeList[freelist_idx].freeList = currBucket;
1005 
1006  if (IS_PARTITIONED(hctl))
1007  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1008 
1009  /*
1010  * better hope the caller is synchronizing access to this
1011  * element, because someone else is going to reuse it the next
1012  * time something is added to the table
1013  */
1014  return (void *) ELEMENTKEY(currBucket);
1015  }
1016  return NULL;
1017 
1018  case HASH_ENTER_NULL:
1019  /* ENTER_NULL does not work with palloc-based allocator */
1020  Assert(hashp->alloc != DynaHashAlloc);
1021  /* FALL THRU */
1022 
1023  case HASH_ENTER:
1024  /* Return existing element if found, else create one */
1025  if (currBucket != NULL)
1026  return (void *) ELEMENTKEY(currBucket);
1027 
1028  /* disallow inserts if frozen */
1029  if (hashp->frozen)
1030  elog(ERROR, "cannot insert into frozen hashtable \"%s\"",
1031  hashp->tabname);
1032 
1033  currBucket = get_hash_entry(hashp, freelist_idx);
1034  if (currBucket == NULL)
1035  {
1036  /* out of memory */
1037  if (action == HASH_ENTER_NULL)
1038  return NULL;
1039  /* report a generic message */
1040  if (hashp->isshared)
1041  ereport(ERROR,
1042  (errcode(ERRCODE_OUT_OF_MEMORY),
1043  errmsg("out of shared memory")));
1044  else
1045  ereport(ERROR,
1046  (errcode(ERRCODE_OUT_OF_MEMORY),
1047  errmsg("out of memory")));
1048  }
1049 
1050  /* link into hashbucket chain */
1051  *prevBucketPtr = currBucket;
1052  currBucket->link = NULL;
1053 
1054  /* copy key into record */
1055  currBucket->hashvalue = hashvalue;
1056  hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize);
1057 
1058  /*
1059  * Caller is expected to fill the data field on return. DO NOT
1060  * insert any code that could possibly throw error here, as doing
1061  * so would leave the table entry incomplete and hence corrupt the
1062  * caller's data structure.
1063  */
1064 
1065  return (void *) ELEMENTKEY(currBucket);
1066  }
1067 
1068  elog(ERROR, "unrecognized hash action code: %d", (int) action);
1069 
1070  return NULL; /* keep compiler quiet */
1071 }
Size keysize
Definition: dynahash.c:210
uint32 max_bucket
Definition: dynahash.c:159
static uint32 calc_bucket(HASHHDR *hctl, uint32 hash_val)
Definition: dynahash.c:846
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:184
#define ELEMENTKEY(helem)
Definition: dynahash.c:218
int errcode(int sqlerrcode)
Definition: elog.c:575
HashAllocFunc alloc
Definition: dynahash.c:200
slock_t mutex
Definition: dynahash.c:130
static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx)
Definition: dynahash.c:1226
char bool
Definition: c.h:202
long ffactor
Definition: dynahash.c:167
#define SpinLockAcquire(lock)
Definition: spin.h:62
long ssize
Definition: dynahash.c:211
#define ERROR
Definition: elog.h:43
int sshift
Definition: dynahash.c:212
#define MOD(x, y)
Definition: dynahash.c:229
HASHHDR * hctl
Definition: dynahash.c:195
static void hash_corrupted(HTAB *hashp)
Definition: dynahash.c:1668
static bool has_seq_scans(HTAB *hashp)
Definition: dynahash.c:1784
unsigned int uint32
Definition: c.h:268
long nentries
Definition: dynahash.c:131
#define ereport(elevel, rest)
Definition: elog.h:122
HashCompareFunc match
Definition: dynahash.c:198
bool isshared
Definition: dynahash.c:203
#define SpinLockRelease(lock)
Definition: spin.h:64
bool frozen
Definition: dynahash.c:207
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:153
HashCopyFunc keycopy
Definition: dynahash.c:199
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
size_t Size
Definition: c.h:356
static bool expand_table(HTAB *hashp)
Definition: dynahash.c:1466
char * tabname
Definition: dynahash.c:202
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:263
int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)
Definition: hsearch.h:29
int errmsg(const char *fmt,...)
Definition: elog.c:797
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHELEMENT * freeList
Definition: dynahash.c:132
HASHSEGMENT * dir
Definition: dynahash.c:196
#define elog
Definition: elog.h:219
#define FREELIST_IDX(hctl, hashcode)
Definition: dynahash.c:186
uint32 hashvalue
Definition: hsearch.h:54
long hash_select_dirsize ( long  num_entries)

Definition at line 758 of file dynahash.c.

References DEF_DIRSIZE, DEF_FFACTOR, DEF_SEGSIZE, and next_pow2_long().

Referenced by ShmemInitHash().

759 {
760  long nBuckets,
761  nSegments,
762  nDirEntries;
763 
764  /* estimate number of buckets wanted */
765  nBuckets = next_pow2_long((num_entries - 1) / DEF_FFACTOR + 1);
766  /* # of segments needed for nBuckets */
767  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
768  /* directory entries */
769  nDirEntries = DEF_DIRSIZE;
770  while (nDirEntries < nSegments)
771  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
772 
773  return nDirEntries;
774 }
static long next_pow2_long(long num)
Definition: dynahash.c:1698
#define DEF_FFACTOR
Definition: dynahash.c:112
#define DEF_SEGSIZE
Definition: dynahash.c:109
#define DEF_DIRSIZE
Definition: dynahash.c:111
void hash_seq_init ( HASH_SEQ_STATUS status,
HTAB hashp 
)

Definition at line 1343 of file dynahash.c.

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, HTAB::frozen, HASH_SEQ_STATUS::hashp, NULL, and register_seq_scan().

Referenced by AtAbort_Portals(), AtCleanup_Portals(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AtPrepare_Locks(), AtSubAbort_Portals(), AtSubCleanup_Portals(), AtSubCommit_Portals(), CheckForBufferLeaks(), CheckTableForSerializableConflictIn(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), forget_invalid_pages(), forget_invalid_pages_db(), gc_qtexts(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_relmap_invalidate_cb(), logicalrep_typmap_invalidate_cb(), mdsync(), packGraph(), pg_cursor(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), pgstat_send_funcstats(), pgstat_vacuum_stat(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), plperl_fini(), PortalHashTableDeleteAll(), PostPrepare_Locks(), PreCommit_Portals(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenodeMapInvalidateCallback(), RememberFsyncRequest(), ReorderBufferToastReset(), selectColorTrigrams(), smgrcloseall(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

1344 {
1345  status->hashp = hashp;
1346  status->curBucket = 0;
1347  status->curEntry = NULL;
1348  if (!hashp->frozen)
1349  register_seq_scan(hashp);
1350 }
uint32 curBucket
Definition: hsearch.h:115
HASHELEMENT * curEntry
Definition: hsearch.h:116
HTAB * hashp
Definition: hsearch.h:114
bool frozen
Definition: dynahash.c:207
#define NULL
Definition: c.h:229
static void register_seq_scan(HTAB *hashp)
Definition: dynahash.c:1751
void* hash_seq_search ( HASH_SEQ_STATUS status)

Definition at line 1353 of file dynahash.c.

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, HTAB::dir, ELEMENTKEY, hash_seq_term(), HASH_SEQ_STATUS::hashp, HTAB::hctl, HASHELEMENT::link, HASHHDR::max_bucket, MOD, NULL, HTAB::sshift, and HTAB::ssize.

Referenced by AtAbort_Portals(), AtCleanup_Portals(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AtPrepare_Locks(), AtSubAbort_Portals(), AtSubCleanup_Portals(), AtSubCommit_Portals(), CheckForBufferLeaks(), CheckTableForSerializableConflictIn(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), forget_invalid_pages(), forget_invalid_pages_db(), gc_qtexts(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_relmap_invalidate_cb(), logicalrep_typmap_invalidate_cb(), mdsync(), packGraph(), pg_cursor(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), pgstat_send_funcstats(), pgstat_vacuum_stat(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), plperl_fini(), PortalHashTableDeleteAll(), PostPrepare_Locks(), PreCommit_Portals(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenodeMapInvalidateCallback(), RememberFsyncRequest(), ReorderBufferToastReset(), selectColorTrigrams(), smgrcloseall(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

1354 {
1355  HTAB *hashp;
1356  HASHHDR *hctl;
1357  uint32 max_bucket;
1358  long ssize;
1359  long segment_num;
1360  long segment_ndx;
1361  HASHSEGMENT segp;
1362  uint32 curBucket;
1363  HASHELEMENT *curElem;
1364 
1365  if ((curElem = status->curEntry) != NULL)
1366  {
1367  /* Continuing scan of curBucket... */
1368  status->curEntry = curElem->link;
1369  if (status->curEntry == NULL) /* end of this bucket */
1370  ++status->curBucket;
1371  return (void *) ELEMENTKEY(curElem);
1372  }
1373 
1374  /*
1375  * Search for next nonempty bucket starting at curBucket.
1376  */
1377  curBucket = status->curBucket;
1378  hashp = status->hashp;
1379  hctl = hashp->hctl;
1380  ssize = hashp->ssize;
1381  max_bucket = hctl->max_bucket;
1382 
1383  if (curBucket > max_bucket)
1384  {
1385  hash_seq_term(status);
1386  return NULL; /* search is done */
1387  }
1388 
1389  /*
1390  * first find the right segment in the table directory.
1391  */
1392  segment_num = curBucket >> hashp->sshift;
1393  segment_ndx = MOD(curBucket, ssize);
1394 
1395  segp = hashp->dir[segment_num];
1396 
1397  /*
1398  * Pick up the first item in this bucket's chain. If chain is not empty
1399  * we can begin searching it. Otherwise we have to advance to find the
1400  * next nonempty bucket. We try to optimize that case since searching a
1401  * near-empty hashtable has to iterate this loop a lot.
1402  */
1403  while ((curElem = segp[segment_ndx]) == NULL)
1404  {
1405  /* empty bucket, advance to next */
1406  if (++curBucket > max_bucket)
1407  {
1408  status->curBucket = curBucket;
1409  hash_seq_term(status);
1410  return NULL; /* search is done */
1411  }
1412  if (++segment_ndx >= ssize)
1413  {
1414  segment_num++;
1415  segment_ndx = 0;
1416  segp = hashp->dir[segment_num];
1417  }
1418  }
1419 
1420  /* Begin scan of curBucket... */
1421  status->curEntry = curElem->link;
1422  if (status->curEntry == NULL) /* end of this bucket */
1423  ++curBucket;
1424  status->curBucket = curBucket;
1425  return (void *) ELEMENTKEY(curElem);
1426 }
uint32 curBucket
Definition: hsearch.h:115
uint32 max_bucket
Definition: dynahash.c:159
#define ELEMENTKEY(helem)
Definition: dynahash.c:218
HASHELEMENT * curEntry
Definition: hsearch.h:116
Definition: dynahash.c:193
long ssize
Definition: dynahash.c:211
int sshift
Definition: dynahash.c:212
#define MOD(x, y)
Definition: dynahash.c:229
HASHHDR * hctl
Definition: dynahash.c:195
unsigned int uint32
Definition: c.h:268
HTAB * hashp
Definition: hsearch.h:114
#define NULL
Definition: c.h:229
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHSEGMENT * dir
Definition: dynahash.c:196
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1429
void hash_seq_term ( HASH_SEQ_STATUS status)

Definition at line 1429 of file dynahash.c.

References deregister_seq_scan(), HTAB::frozen, and HASH_SEQ_STATUS::hashp.

Referenced by gc_qtexts(), hash_seq_search(), logicalrep_relmap_invalidate_cb(), pgss_shmem_shutdown(), PortalHashTableDeleteAll(), PreCommit_Portals(), and RelationCacheInitializePhase3().

1430 {
1431  if (!status->hashp->frozen)
1432  deregister_seq_scan(status->hashp);
1433 }
HTAB * hashp
Definition: hsearch.h:114
bool frozen
Definition: dynahash.c:207
static void deregister_seq_scan(HTAB *hashp)
Definition: dynahash.c:1763
void hash_stats ( const char *  where,
HTAB hashp 
)

Definition at line 812 of file dynahash.c.

References hash_get_num_entries(), HTAB::hctl, HASHHDR::keysize, HASHHDR::max_bucket, and HASHHDR::nsegs.

Referenced by hash_destroy().

813 {
814 #if HASH_STATISTICS
815  fprintf(stderr, "%s: this HTAB -- accesses %ld collisions %ld\n",
816  where, hashp->hctl->accesses, hashp->hctl->collisions);
817 
818  fprintf(stderr, "hash_stats: entries %ld keysize %ld maxp %u segmentcount %ld\n",
819  hash_get_num_entries(hashp), (long) hashp->hctl->keysize,
820  hashp->hctl->max_bucket, hashp->hctl->nsegs);
821  fprintf(stderr, "%s: total accesses %ld total collisions %ld\n",
822  where, hash_accesses, hash_collisions);
823  fprintf(stderr, "hash_stats: total expansions %ld\n",
824  hash_expansions);
825 #endif
826 }
Size keysize
Definition: dynahash.c:164
uint32 max_bucket
Definition: dynahash.c:159
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1297
HASHHDR * hctl
Definition: dynahash.c:195
long nsegs
Definition: dynahash.c:158
bool hash_update_hash_key ( HTAB hashp,
void *  existingEntry,
const void *  newKeyPtr 
)

Definition at line 1093 of file dynahash.c.

References calc_bucket(), HTAB::dir, ELEMENT_FROM_KEY, ELEMENTKEY, elog, ERROR, HTAB::frozen, HTAB::hash, hash_corrupted(), HASHELEMENT::hashvalue, HTAB::hctl, HTAB::keycopy, HTAB::keysize, HASHELEMENT::link, HTAB::match, MOD, NULL, HTAB::sshift, HTAB::ssize, and HTAB::tabname.

Referenced by PostPrepare_Locks().

1096 {
1097  HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry);
1098  HASHHDR *hctl = hashp->hctl;
1099  uint32 newhashvalue;
1100  Size keysize;
1101  uint32 bucket;
1102  uint32 newbucket;
1103  long segment_num;
1104  long segment_ndx;
1105  HASHSEGMENT segp;
1106  HASHBUCKET currBucket;
1107  HASHBUCKET *prevBucketPtr;
1108  HASHBUCKET *oldPrevPtr;
1109  HashCompareFunc match;
1110 
1111 #if HASH_STATISTICS
1112  hash_accesses++;
1113  hctl->accesses++;
1114 #endif
1115 
1116  /* disallow updates if frozen */
1117  if (hashp->frozen)
1118  elog(ERROR, "cannot update in frozen hashtable \"%s\"",
1119  hashp->tabname);
1120 
1121  /*
1122  * Lookup the existing element using its saved hash value. We need to do
1123  * this to be able to unlink it from its hash chain, but as a side benefit
1124  * we can verify the validity of the passed existingEntry pointer.
1125  */
1126  bucket = calc_bucket(hctl, existingElement->hashvalue);
1127 
1128  segment_num = bucket >> hashp->sshift;
1129  segment_ndx = MOD(bucket, hashp->ssize);
1130 
1131  segp = hashp->dir[segment_num];
1132 
1133  if (segp == NULL)
1134  hash_corrupted(hashp);
1135 
1136  prevBucketPtr = &segp[segment_ndx];
1137  currBucket = *prevBucketPtr;
1138 
1139  while (currBucket != NULL)
1140  {
1141  if (currBucket == existingElement)
1142  break;
1143  prevBucketPtr = &(currBucket->link);
1144  currBucket = *prevBucketPtr;
1145  }
1146 
1147  if (currBucket == NULL)
1148  elog(ERROR, "hash_update_hash_key argument is not in hashtable \"%s\"",
1149  hashp->tabname);
1150 
1151  oldPrevPtr = prevBucketPtr;
1152 
1153  /*
1154  * Now perform the equivalent of a HASH_ENTER operation to locate the hash
1155  * chain we want to put the entry into.
1156  */
1157  newhashvalue = hashp->hash(newKeyPtr, hashp->keysize);
1158 
1159  newbucket = calc_bucket(hctl, newhashvalue);
1160 
1161  segment_num = newbucket >> hashp->sshift;
1162  segment_ndx = MOD(newbucket, hashp->ssize);
1163 
1164  segp = hashp->dir[segment_num];
1165 
1166  if (segp == NULL)
1167  hash_corrupted(hashp);
1168 
1169  prevBucketPtr = &segp[segment_ndx];
1170  currBucket = *prevBucketPtr;
1171 
1172  /*
1173  * Follow collision chain looking for matching key
1174  */
1175  match = hashp->match; /* save one fetch in inner loop */
1176  keysize = hashp->keysize; /* ditto */
1177 
1178  while (currBucket != NULL)
1179  {
1180  if (currBucket->hashvalue == newhashvalue &&
1181  match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0)
1182  break;
1183  prevBucketPtr = &(currBucket->link);
1184  currBucket = *prevBucketPtr;
1185 #if HASH_STATISTICS
1186  hash_collisions++;
1187  hctl->collisions++;
1188 #endif
1189  }
1190 
1191  if (currBucket != NULL)
1192  return false; /* collision with an existing entry */
1193 
1194  currBucket = existingElement;
1195 
1196  /*
1197  * If old and new hash values belong to the same bucket, we need not
1198  * change any chain links, and indeed should not since this simplistic
1199  * update will corrupt the list if currBucket is the last element. (We
1200  * cannot fall out earlier, however, since we need to scan the bucket to
1201  * check for duplicate keys.)
1202  */
1203  if (bucket != newbucket)
1204  {
1205  /* OK to remove record from old hash bucket's chain. */
1206  *oldPrevPtr = currBucket->link;
1207 
1208  /* link into new hashbucket chain */
1209  *prevBucketPtr = currBucket;
1210  currBucket->link = NULL;
1211  }
1212 
1213  /* copy new key into record */
1214  currBucket->hashvalue = newhashvalue;
1215  hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize);
1216 
1217  /* rest of record is untouched */
1218 
1219  return true;
1220 }
Size keysize
Definition: dynahash.c:210
static uint32 calc_bucket(HASHHDR *hctl, uint32 hash_val)
Definition: dynahash.c:846
#define ELEMENTKEY(helem)
Definition: dynahash.c:218
#define ELEMENT_FROM_KEY(key)
Definition: dynahash.c:223
HashValueFunc hash
Definition: dynahash.c:197
long ssize
Definition: dynahash.c:211
#define ERROR
Definition: elog.h:43
int sshift
Definition: dynahash.c:212
#define MOD(x, y)
Definition: dynahash.c:229
HASHHDR * hctl
Definition: dynahash.c:195
static void hash_corrupted(HTAB *hashp)
Definition: dynahash.c:1668
unsigned int uint32
Definition: c.h:268
HashCompareFunc match
Definition: dynahash.c:198
bool frozen
Definition: dynahash.c:207
HashCopyFunc keycopy
Definition: dynahash.c:199
#define NULL
Definition: c.h:229
size_t Size
Definition: c.h:356
char * tabname
Definition: dynahash.c:202
int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)
Definition: hsearch.h:29
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHSEGMENT * dir
Definition: dynahash.c:196
#define elog
Definition: elog.h:219
uint32 hashvalue
Definition: hsearch.h:54
uint32 string_hash ( const void *  key,
Size  keysize 
)

Definition at line 34 of file hashfn.c.

References DatumGetUInt32, hash_any(), and Min.

Referenced by hash_create().

35 {
36  /*
37  * If the string exceeds keysize-1 bytes, we want to hash only that many,
38  * because when it is copied into the hash table it will be truncated at
39  * that length.
40  */
41  Size s_len = strlen((const char *) key);
42 
43  s_len = Min(s_len, keysize - 1);
44  return DatumGetUInt32(hash_any((const unsigned char *) key,
45  (int) s_len));
46 }
#define DatumGetUInt32(X)
Definition: postgres.h:492
#define Min(x, y)
Definition: c.h:806
Datum hash_any(register const unsigned char *k, register int keylen)
Definition: hashfunc.c:307
size_t Size
Definition: c.h:356
uint32 tag_hash ( const void *  key,
Size  keysize 
)

Definition at line 52 of file hashfn.c.

References DatumGetUInt32, and hash_any().

Referenced by hash_create().

53 {
54  return DatumGetUInt32(hash_any((const unsigned char *) key,
55  (int) keysize));
56 }
#define DatumGetUInt32(X)
Definition: postgres.h:492
Datum hash_any(register const unsigned char *k, register int keylen)
Definition: hashfunc.c:307
uint32 uint32_hash ( const void *  key,
Size  keysize 
)

Definition at line 64 of file hashfn.c.

References Assert, DatumGetUInt32, and hash_uint32().

Referenced by hash_create().

65 {
66  Assert(keysize == sizeof(uint32));
67  return DatumGetUInt32(hash_uint32(*((const uint32 *) key)));
68 }
#define DatumGetUInt32(X)
Definition: postgres.h:492
unsigned int uint32
Definition: c.h:268
Datum hash_uint32(uint32 k)
Definition: hashfunc.c:512
#define Assert(condition)
Definition: c.h:675