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_all_inheritors(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), get_tabstat_entry(), 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(), process_syncing_tables_for_apply(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RelationCacheInitialize(), ReorderBufferAllocate(), ReorderBufferBuildTupleCidHash(), ReorderBufferToastInitHash(), reset_dbentry_counters(), ResetUnloggedRelationsInDbspaceDir(), ri_InitHashTables(), select_perl_context(), set_rtable_names(), smgropen(), and transformGraph().

#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 1856 of file dynahash.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

1857 {
1858  int i;
1859 
1860  /*
1861  * Search backward to make cleanup easy. Note we must check all entries,
1862  * not only those at the end of the array, because deletion technique
1863  * doesn't keep them in order.
1864  */
1865  for (i = num_seq_scans - 1; i >= 0; i--)
1866  {
1867  if (seq_scan_level[i] >= nestDepth)
1868  {
1869  if (isCommit)
1870  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1871  seq_scan_tables[i]);
1874  num_seq_scans--;
1875  }
1876  }
1877 }
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1777
#define WARNING
Definition: elog.h:40
static int num_seq_scans
Definition: dynahash.c:1778
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1776
int i
#define elog
Definition: elog.h:219
void AtEOXact_HashTables ( bool  isCommit)

Definition at line 1830 of file dynahash.c.

References elog, i, num_seq_scans, and WARNING.

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

1831 {
1832  /*
1833  * During abort cleanup, open scans are expected; just silently clean 'em
1834  * out. An open scan at commit means someone forgot a hash_seq_term()
1835  * call, so complain.
1836  *
1837  * Note: it's tempting to try to print the tabname here, but refrain for
1838  * fear of touching deallocated memory. This isn't a user-facing message
1839  * anyway, so it needn't be pretty.
1840  */
1841  if (isCommit)
1842  {
1843  int i;
1844 
1845  for (i = 0; i < num_seq_scans; i++)
1846  {
1847  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1848  seq_scan_tables[i]);
1849  }
1850  }
1851  num_seq_scans = 0;
1852 }
#define WARNING
Definition: elog.h:40
static int num_seq_scans
Definition: dynahash.c:1778
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1776
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:984
#define Assert(condition)
Definition: c.h:664
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:664
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131
uint32 get_hash_value ( HTAB hashp,
const void *  keyPtr 
)

Definition at line 856 of file dynahash.c.

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

Referenced by BufTableHashCode(), and LockTagHashCode().

857 {
858  return hashp->hash(keyPtr, hashp->keysize);
859 }
Size keysize
Definition: dynahash.c:225
HashValueFunc hash
Definition: dynahash.c:212
HTAB* hash_create ( const char *  tabname,
long  nelem,
HASHCTL info,
int  flags 
)

Definition at line 316 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(), 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_all_inheritors(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), get_tabstat_entry(), 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(), process_syncing_tables_for_apply(), 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(), and transformGraph().

317 {
318  HTAB *hashp;
319  HASHHDR *hctl;
320 
321  /*
322  * For shared hash tables, we have a local hash header (HTAB struct) that
323  * we allocate in TopMemoryContext; all else is in shared memory.
324  *
325  * For non-shared hash tables, everything including the hash header is in
326  * a memory context created specially for the hash table --- this makes
327  * hash_destroy very simple. The memory context is made a child of either
328  * a context specified by the caller, or TopMemoryContext if nothing is
329  * specified.
330  */
331  if (flags & HASH_SHARED_MEM)
332  {
333  /* Set up to allocate the hash header */
335  }
336  else
337  {
338  /* Create the hash table's private memory context */
339  if (flags & HASH_CONTEXT)
340  CurrentDynaHashCxt = info->hcxt;
341  else
344  tabname,
346  }
347 
348  /* Initialize the hash header, plus a copy of the table name */
349  hashp = (HTAB *) DynaHashAlloc(sizeof(HTAB) + strlen(tabname) + 1);
350  MemSet(hashp, 0, sizeof(HTAB));
351 
352  hashp->tabname = (char *) (hashp + 1);
353  strcpy(hashp->tabname, tabname);
354 
355  /*
356  * Select the appropriate hash function (see comments at head of file).
357  */
358  if (flags & HASH_FUNCTION)
359  hashp->hash = info->hash;
360  else if (flags & HASH_BLOBS)
361  {
362  /* We can optimize hashing for common key sizes */
364  if (info->keysize == sizeof(uint32))
365  hashp->hash = uint32_hash;
366  else
367  hashp->hash = tag_hash;
368  }
369  else
370  hashp->hash = string_hash; /* default hash function */
371 
372  /*
373  * If you don't specify a match function, it defaults to string_compare if
374  * you used string_hash (either explicitly or by default) and to memcmp
375  * otherwise.
376  *
377  * Note: explicitly specifying string_hash is deprecated, because this
378  * might not work for callers in loadable modules on some platforms due to
379  * referencing a trampoline instead of the string_hash function proper.
380  * Just let it default, eh?
381  */
382  if (flags & HASH_COMPARE)
383  hashp->match = info->match;
384  else if (hashp->hash == string_hash)
386  else
387  hashp->match = memcmp;
388 
389  /*
390  * Similarly, the key-copying function defaults to strlcpy or memcpy.
391  */
392  if (flags & HASH_KEYCOPY)
393  hashp->keycopy = info->keycopy;
394  else if (hashp->hash == string_hash)
395  hashp->keycopy = (HashCopyFunc) strlcpy;
396  else
397  hashp->keycopy = memcpy;
398 
399  /* And select the entry allocation function, too. */
400  if (flags & HASH_ALLOC)
401  hashp->alloc = info->alloc;
402  else
403  hashp->alloc = DynaHashAlloc;
404 
405  if (flags & HASH_SHARED_MEM)
406  {
407  /*
408  * ctl structure and directory are preallocated for shared memory
409  * tables. Note that HASH_DIRSIZE and HASH_ALLOC had better be set as
410  * well.
411  */
412  hashp->hctl = info->hctl;
413  hashp->dir = (HASHSEGMENT *) (((char *) info->hctl) + sizeof(HASHHDR));
414  hashp->hcxt = NULL;
415  hashp->isshared = true;
416 
417  /* hash table already exists, we're just attaching to it */
418  if (flags & HASH_ATTACH)
419  {
420  /* make local copies of some heavily-used values */
421  hctl = hashp->hctl;
422  hashp->keysize = hctl->keysize;
423  hashp->ssize = hctl->ssize;
424  hashp->sshift = hctl->sshift;
425 
426  return hashp;
427  }
428  }
429  else
430  {
431  /* setup hash table defaults */
432  hashp->hctl = NULL;
433  hashp->dir = NULL;
434  hashp->hcxt = CurrentDynaHashCxt;
435  hashp->isshared = false;
436  }
437 
438  if (!hashp->hctl)
439  {
440  hashp->hctl = (HASHHDR *) hashp->alloc(sizeof(HASHHDR));
441  if (!hashp->hctl)
442  ereport(ERROR,
443  (errcode(ERRCODE_OUT_OF_MEMORY),
444  errmsg("out of memory")));
445  }
446 
447  hashp->frozen = false;
448 
449  hdefault(hashp);
450 
451  hctl = hashp->hctl;
452 
453  if (flags & HASH_PARTITION)
454  {
455  /* Doesn't make sense to partition a local hash table */
456  Assert(flags & HASH_SHARED_MEM);
457 
458  /*
459  * The number of partitions had better be a power of 2. Also, it must
460  * be less than INT_MAX (see init_htab()), so call the int version of
461  * next_pow2.
462  */
464 
465  hctl->num_partitions = info->num_partitions;
466  }
467 
468  if (flags & HASH_SEGMENT)
469  {
470  hctl->ssize = info->ssize;
471  hctl->sshift = my_log2(info->ssize);
472  /* ssize had better be a power of 2 */
473  Assert(hctl->ssize == (1L << hctl->sshift));
474  }
475  if (flags & HASH_FFACTOR)
476  hctl->ffactor = info->ffactor;
477 
478  /*
479  * SHM hash tables have fixed directory size passed by the caller.
480  */
481  if (flags & HASH_DIRSIZE)
482  {
483  hctl->max_dsize = info->max_dsize;
484  hctl->dsize = info->dsize;
485  }
486 
487  /*
488  * hash table now allocates space for key and data but you have to say how
489  * much space to allocate
490  */
491  if (flags & HASH_ELEM)
492  {
493  Assert(info->entrysize >= info->keysize);
494  hctl->keysize = info->keysize;
495  hctl->entrysize = info->entrysize;
496  }
497 
498  /* make local copies of heavily-used constant fields */
499  hashp->keysize = hctl->keysize;
500  hashp->ssize = hctl->ssize;
501  hashp->sshift = hctl->sshift;
502 
503  /* Build the hash directory structure */
504  if (!init_htab(hashp, nelem))
505  elog(ERROR, "failed to initialize hash table \"%s\"", hashp->tabname);
506 
507  /*
508  * For a shared hash table, preallocate the requested number of elements.
509  * This reduces problems with run-time out-of-shared-memory conditions.
510  *
511  * For a non-shared hash table, preallocate the requested number of
512  * elements if it's less than our chosen nelem_alloc. This avoids wasting
513  * space if the caller correctly estimates a small table size.
514  */
515  if ((flags & HASH_SHARED_MEM) ||
516  nelem < hctl->nelem_alloc)
517  {
518  int i,
519  freelist_partitions,
520  nelem_alloc,
521  nelem_alloc_first;
522 
523  /*
524  * If hash table is partitioned, give each freelist an equal share of
525  * the initial allocation. Otherwise only freeList[0] is used.
526  */
527  if (IS_PARTITIONED(hashp->hctl))
528  freelist_partitions = NUM_FREELISTS;
529  else
530  freelist_partitions = 1;
531 
532  nelem_alloc = nelem / freelist_partitions;
533  if (nelem_alloc <= 0)
534  nelem_alloc = 1;
535 
536  /*
537  * Make sure we'll allocate all the requested elements; freeList[0]
538  * gets the excess if the request isn't divisible by NUM_FREELISTS.
539  */
540  if (nelem_alloc * freelist_partitions < nelem)
541  nelem_alloc_first =
542  nelem - nelem_alloc * (freelist_partitions - 1);
543  else
544  nelem_alloc_first = nelem_alloc;
545 
546  for (i = 0; i < freelist_partitions; i++)
547  {
548  int temp = (i == 0) ? nelem_alloc_first : nelem_alloc;
549 
550  if (!element_alloc(hashp, temp, i))
551  ereport(ERROR,
552  (errcode(ERRCODE_OUT_OF_MEMORY),
553  errmsg("out of memory")));
554  }
555  }
556 
557  if (flags & HASH_FIXED_SIZE)
558  hashp->isfixed = true;
559  return hashp;
560 }
Size keysize
Definition: dynahash.c:179
Size keysize
Definition: dynahash.c:225
long dsize
Definition: dynahash.c:172
#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:180
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:199
uint32 string_hash(const void *key, Size keysize)
Definition: hashfn.c:34
long num_partitions
Definition: dynahash.c:181
Size entrysize
Definition: hsearch.h:73
#define NUM_FREELISTS
Definition: dynahash.c:116
int errcode(int sqlerrcode)
Definition: elog.c:575
HashAllocFunc alloc
Definition: dynahash.c:215
#define MemSet(start, val, len)
Definition: c.h:846
#define HASH_SHARED_MEM
Definition: hsearch.h:94
static int string_compare(const char *key1, const char *key2, Size keysize)
Definition: dynahash.c:293
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:182
HashValueFunc hash
Definition: dynahash.c:212
Definition: dynahash.c:208
long max_dsize
Definition: hsearch.h:70
long ssize
Definition: dynahash.c:226
#define ERROR
Definition: elog.h:43
long num_partitions
Definition: hsearch.h:67
int sshift
Definition: dynahash.c:227
#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:183
static void hdefault(HTAB *hashp)
Definition: dynahash.c:566
HASHHDR * hctl
Definition: dynahash.c:210
unsigned int uint32
Definition: c.h:258
static bool init_htab(HTAB *hashp, long nelem)
Definition: dynahash.c:632
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
int my_log2(long num)
Definition: dynahash.c:1714
HashCompareFunc match
Definition: dynahash.c:213
static int next_pow2_int(long num)
Definition: dynahash.c:1738
bool isshared
Definition: dynahash.c:218
#define HASH_BLOBS
Definition: hsearch.h:88
bool frozen
Definition: dynahash.c:222
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:184
Size keysize
Definition: hsearch.h:72
HashCompareFunc match
Definition: hsearch.h:75
MemoryContext hcxt
Definition: dynahash.c:216
HashCopyFunc keycopy
Definition: dynahash.c:214
#define HASH_SEGMENT
Definition: hsearch.h:84
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:664
#define HASH_COMPARE
Definition: hsearch.h:90
HASHHDR * hctl
Definition: hsearch.h:79
long ffactor
Definition: hsearch.h:71
char * tabname
Definition: dynahash.c:217
#define HASH_FIXED_SIZE
Definition: hsearch.h:96
bool isfixed
Definition: dynahash.c:219
#define HASH_FFACTOR
Definition: hsearch.h:86
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:278
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:275
int i
#define HASH_ALLOC
Definition: hsearch.h:92
HASHSEGMENT * dir
Definition: dynahash.c:211
#define elog
Definition: elog.h:219
static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx)
Definition: dynahash.c:1653
int sshift
Definition: dynahash.c:185
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 810 of file dynahash.c.

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

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

811 {
812  if (hashp != NULL)
813  {
814  /* allocation method must be one we know how to free, too */
815  Assert(hashp->alloc == DynaHashAlloc);
816  /* so this hashtable must have it's own context */
817  Assert(hashp->hcxt != NULL);
818 
819  hash_stats("destroy", hashp);
820 
821  /*
822  * Free everything by destroying the hash table's memory context.
823  */
824  MemoryContextDelete(hashp->hcxt);
825  }
826 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void hash_stats(const char *where, HTAB *hashp)
Definition: dynahash.c:829
HashAllocFunc alloc
Definition: dynahash.c:215
MemoryContext hcxt
Definition: dynahash.c:216
#define Assert(condition)
Definition: c.h:664
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:278
Size hash_estimate_size ( long  num_entries,
Size  entrysize 
)

Definition at line 728 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().

729 {
730  Size size;
731  long nBuckets,
732  nSegments,
733  nDirEntries,
734  nElementAllocs,
735  elementSize,
736  elementAllocCnt;
737 
738  /* estimate number of buckets wanted */
739  nBuckets = next_pow2_long((num_entries - 1) / DEF_FFACTOR + 1);
740  /* # of segments needed for nBuckets */
741  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
742  /* directory entries */
743  nDirEntries = DEF_DIRSIZE;
744  while (nDirEntries < nSegments)
745  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
746 
747  /* fixed control info */
748  size = MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */
749  /* directory */
750  size = add_size(size, mul_size(nDirEntries, sizeof(HASHSEGMENT)));
751  /* segments */
752  size = add_size(size, mul_size(nSegments,
753  MAXALIGN(DEF_SEGSIZE * sizeof(HASHBUCKET))));
754  /* elements --- allocated in groups of choose_nelem_alloc() entries */
755  elementAllocCnt = choose_nelem_alloc(entrysize);
756  nElementAllocs = (num_entries - 1) / elementAllocCnt + 1;
757  elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(entrysize);
758  size = add_size(size,
759  mul_size(nElementAllocs,
760  mul_size(elementAllocCnt, elementSize)));
761 
762  return size;
763 }
static long next_pow2_long(long num)
Definition: dynahash.c:1730
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:350
#define MAXALIGN(LEN)
Definition: c.h:576
static int choose_nelem_alloc(Size entrysize)
Definition: dynahash.c:599
#define DEF_FFACTOR
Definition: dynahash.c:113
#define DEF_SEGSIZE
Definition: dynahash.c:110
#define DEF_DIRSIZE
Definition: dynahash.c:112
void hash_freeze ( HTAB hashp)

Definition at line 1481 of file dynahash.c.

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

1482 {
1483  if (hashp->isshared)
1484  elog(ERROR, "cannot freeze shared hashtable \"%s\"", hashp->tabname);
1485  if (!hashp->frozen && has_seq_scans(hashp))
1486  elog(ERROR, "cannot freeze hashtable \"%s\" because it has active scans",
1487  hashp->tabname);
1488  hashp->frozen = true;
1489 }
#define ERROR
Definition: elog.h:43
static bool has_seq_scans(HTAB *hashp)
Definition: dynahash.c:1816
bool isshared
Definition: dynahash.c:218
bool frozen
Definition: dynahash.c:222
char * tabname
Definition: dynahash.c:217
#define elog
Definition: elog.h:219
long hash_get_num_entries ( HTAB hashp)

Definition at line 1331 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(), pgss_shmem_shutdown(), pgstat_vacuum_stat(), ResetUnloggedRelationsInDbspaceDir(), transformGraph(), and XLogHaveInvalidPages().

1332 {
1333  int i;
1334  long sum = hashp->hctl->freeList[0].nentries;
1335 
1336  /*
1337  * We currently don't bother with acquiring the mutexes; it's only
1338  * sensible to call this function if you've got lock on all partitions of
1339  * the table.
1340  */
1341  if (IS_PARTITIONED(hashp->hctl))
1342  {
1343  for (i = 1; i < NUM_FREELISTS; i++)
1344  sum += hashp->hctl->freeList[i].nentries;
1345  }
1346 
1347  return sum;
1348 }
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:199
#define NUM_FREELISTS
Definition: dynahash.c:116
HASHHDR * hctl
Definition: dynahash.c:210
long nentries
Definition: dynahash.c:144
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:168
int i
Size hash_get_shared_size ( HASHCTL info,
int  flags 
)

Definition at line 799 of file dynahash.c.

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

Referenced by ShmemInitHash().

800 {
802  Assert(info->dsize == info->max_dsize);
803  return sizeof(HASHHDR) + info->dsize * sizeof(HASHSEGMENT);
804 }
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:664
#define HASH_DIRSIZE
Definition: hsearch.h:85
void* hash_search ( HTAB hashp,
const void *  keyPtr,
HASHACTION  action,
bool foundPtr 
)

Definition at line 902 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_all_inheritors(), find_funcstat_entry(), find_join_rel(), find_oper_cache_entry(), find_rendezvous_variable(), find_tabstat_entry(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPrivateRefCountEntry(), get_attribute_options(), get_cast_hashentry(), get_pgstat_tabentry_relid(), get_rel_sync_entry(), get_tablespace(), get_tabstat_entry(), GetComboCommandId(), GetConnection(), getConnectionByName(), GetExtensibleNodeEntry(), GetPrivateRefCountEntry(), getState(), gistGetNodeBuffer(), gistGetParent(), gistMemorizeParent(), gistRelocateBuildBuffersOnSplit(), hash_object_field_end(), init_sequence(), InitPredicateLocks(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), is_shippable(), JsObjectGetField(), 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_recordset_object_field_end(), predicatelock_twophase_recover(), PredicateLockExists(), PredicateLockTwoPhaseFinish(), process_syncing_tables_for_apply(), 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(), and table_recheck_autovac().

906 {
907  return hash_search_with_hash_value(hashp,
908  keyPtr,
909  hashp->hash(keyPtr, hashp->keysize),
910  action,
911  foundPtr);
912 }
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:915
Size keysize
Definition: dynahash.c:225
HashValueFunc hash
Definition: dynahash.c:212
void* hash_search_with_hash_value ( HTAB hashp,
const void *  keyPtr,
uint32  hashvalue,
HASHACTION  action,
bool foundPtr 
)

Definition at line 915 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, 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().

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

Definition at line 775 of file dynahash.c.

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

Referenced by ShmemInitHash().

776 {
777  long nBuckets,
778  nSegments,
779  nDirEntries;
780 
781  /* estimate number of buckets wanted */
782  nBuckets = next_pow2_long((num_entries - 1) / DEF_FFACTOR + 1);
783  /* # of segments needed for nBuckets */
784  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
785  /* directory entries */
786  nDirEntries = DEF_DIRSIZE;
787  while (nDirEntries < nSegments)
788  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
789 
790  return nDirEntries;
791 }
static long next_pow2_long(long num)
Definition: dynahash.c:1730
#define DEF_FFACTOR
Definition: dynahash.c:113
#define DEF_SEGSIZE
Definition: dynahash.c:110
#define DEF_DIRSIZE
Definition: dynahash.c:112
void hash_seq_init ( HASH_SEQ_STATUS status,
HTAB hashp 
)

Definition at line 1375 of file dynahash.c.

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, HTAB::frozen, HASH_SEQ_STATUS::hashp, 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_inval_callback(), 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().

1376 {
1377  status->hashp = hashp;
1378  status->curBucket = 0;
1379  status->curEntry = NULL;
1380  if (!hashp->frozen)
1381  register_seq_scan(hashp);
1382 }
uint32 curBucket
Definition: hsearch.h:115
HASHELEMENT * curEntry
Definition: hsearch.h:116
HTAB * hashp
Definition: hsearch.h:114
bool frozen
Definition: dynahash.c:222
static void register_seq_scan(HTAB *hashp)
Definition: dynahash.c:1783
void* hash_seq_search ( HASH_SEQ_STATUS status)

Definition at line 1385 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, 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_inval_callback(), 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().

1386 {
1387  HTAB *hashp;
1388  HASHHDR *hctl;
1389  uint32 max_bucket;
1390  long ssize;
1391  long segment_num;
1392  long segment_ndx;
1393  HASHSEGMENT segp;
1394  uint32 curBucket;
1395  HASHELEMENT *curElem;
1396 
1397  if ((curElem = status->curEntry) != NULL)
1398  {
1399  /* Continuing scan of curBucket... */
1400  status->curEntry = curElem->link;
1401  if (status->curEntry == NULL) /* end of this bucket */
1402  ++status->curBucket;
1403  return (void *) ELEMENTKEY(curElem);
1404  }
1405 
1406  /*
1407  * Search for next nonempty bucket starting at curBucket.
1408  */
1409  curBucket = status->curBucket;
1410  hashp = status->hashp;
1411  hctl = hashp->hctl;
1412  ssize = hashp->ssize;
1413  max_bucket = hctl->max_bucket;
1414 
1415  if (curBucket > max_bucket)
1416  {
1417  hash_seq_term(status);
1418  return NULL; /* search is done */
1419  }
1420 
1421  /*
1422  * first find the right segment in the table directory.
1423  */
1424  segment_num = curBucket >> hashp->sshift;
1425  segment_ndx = MOD(curBucket, ssize);
1426 
1427  segp = hashp->dir[segment_num];
1428 
1429  /*
1430  * Pick up the first item in this bucket's chain. If chain is not empty
1431  * we can begin searching it. Otherwise we have to advance to find the
1432  * next nonempty bucket. We try to optimize that case since searching a
1433  * near-empty hashtable has to iterate this loop a lot.
1434  */
1435  while ((curElem = segp[segment_ndx]) == NULL)
1436  {
1437  /* empty bucket, advance to next */
1438  if (++curBucket > max_bucket)
1439  {
1440  status->curBucket = curBucket;
1441  hash_seq_term(status);
1442  return NULL; /* search is done */
1443  }
1444  if (++segment_ndx >= ssize)
1445  {
1446  segment_num++;
1447  segment_ndx = 0;
1448  segp = hashp->dir[segment_num];
1449  }
1450  }
1451 
1452  /* Begin scan of curBucket... */
1453  status->curEntry = curElem->link;
1454  if (status->curEntry == NULL) /* end of this bucket */
1455  ++curBucket;
1456  status->curBucket = curBucket;
1457  return (void *) ELEMENTKEY(curElem);
1458 }
uint32 curBucket
Definition: hsearch.h:115
uint32 max_bucket
Definition: dynahash.c:174
#define ELEMENTKEY(helem)
Definition: dynahash.c:233
HASHELEMENT * curEntry
Definition: hsearch.h:116
Definition: dynahash.c:208
long ssize
Definition: dynahash.c:226
int sshift
Definition: dynahash.c:227
#define MOD(x, y)
Definition: dynahash.c:244
HASHHDR * hctl
Definition: dynahash.c:210
unsigned int uint32
Definition: c.h:258
HTAB * hashp
Definition: hsearch.h:114
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHSEGMENT * dir
Definition: dynahash.c:211
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1461
void hash_seq_term ( HASH_SEQ_STATUS status)

Definition at line 1461 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().

1462 {
1463  if (!status->hashp->frozen)
1464  deregister_seq_scan(status->hashp);
1465 }
HTAB * hashp
Definition: hsearch.h:114
bool frozen
Definition: dynahash.c:222
static void deregister_seq_scan(HTAB *hashp)
Definition: dynahash.c:1795
void hash_stats ( const char *  where,
HTAB hashp 
)

Definition at line 829 of file dynahash.c.

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

Referenced by hash_destroy().

830 {
831 #if HASH_STATISTICS
832  fprintf(stderr, "%s: this HTAB -- accesses %ld collisions %ld\n",
833  where, hashp->hctl->accesses, hashp->hctl->collisions);
834 
835  fprintf(stderr, "hash_stats: entries %ld keysize %ld maxp %u segmentcount %ld\n",
836  hash_get_num_entries(hashp), (long) hashp->hctl->keysize,
837  hashp->hctl->max_bucket, hashp->hctl->nsegs);
838  fprintf(stderr, "%s: total accesses %ld total collisions %ld\n",
839  where, hash_accesses, hash_collisions);
840  fprintf(stderr, "hash_stats: total expansions %ld\n",
841  hash_expansions);
842 #endif
843 }
Size keysize
Definition: dynahash.c:179
uint32 max_bucket
Definition: dynahash.c:174
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1331
HASHHDR * hctl
Definition: dynahash.c:210
long nsegs
Definition: dynahash.c:173
bool hash_update_hash_key ( HTAB hashp,
void *  existingEntry,
const void *  newKeyPtr 
)

Definition at line 1111 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, HTAB::sshift, HTAB::ssize, and HTAB::tabname.

Referenced by PostPrepare_Locks().

1114 {
1115  HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry);
1116  HASHHDR *hctl = hashp->hctl;
1117  uint32 newhashvalue;
1118  Size keysize;
1119  uint32 bucket;
1120  uint32 newbucket;
1121  long segment_num;
1122  long segment_ndx;
1123  HASHSEGMENT segp;
1124  HASHBUCKET currBucket;
1125  HASHBUCKET *prevBucketPtr;
1126  HASHBUCKET *oldPrevPtr;
1127  HashCompareFunc match;
1128 
1129 #if HASH_STATISTICS
1130  hash_accesses++;
1131  hctl->accesses++;
1132 #endif
1133 
1134  /* disallow updates if frozen */
1135  if (hashp->frozen)
1136  elog(ERROR, "cannot update in frozen hashtable \"%s\"",
1137  hashp->tabname);
1138 
1139  /*
1140  * Lookup the existing element using its saved hash value. We need to do
1141  * this to be able to unlink it from its hash chain, but as a side benefit
1142  * we can verify the validity of the passed existingEntry pointer.
1143  */
1144  bucket = calc_bucket(hctl, existingElement->hashvalue);
1145 
1146  segment_num = bucket >> hashp->sshift;
1147  segment_ndx = MOD(bucket, hashp->ssize);
1148 
1149  segp = hashp->dir[segment_num];
1150 
1151  if (segp == NULL)
1152  hash_corrupted(hashp);
1153 
1154  prevBucketPtr = &segp[segment_ndx];
1155  currBucket = *prevBucketPtr;
1156 
1157  while (currBucket != NULL)
1158  {
1159  if (currBucket == existingElement)
1160  break;
1161  prevBucketPtr = &(currBucket->link);
1162  currBucket = *prevBucketPtr;
1163  }
1164 
1165  if (currBucket == NULL)
1166  elog(ERROR, "hash_update_hash_key argument is not in hashtable \"%s\"",
1167  hashp->tabname);
1168 
1169  oldPrevPtr = prevBucketPtr;
1170 
1171  /*
1172  * Now perform the equivalent of a HASH_ENTER operation to locate the hash
1173  * chain we want to put the entry into.
1174  */
1175  newhashvalue = hashp->hash(newKeyPtr, hashp->keysize);
1176 
1177  newbucket = calc_bucket(hctl, newhashvalue);
1178 
1179  segment_num = newbucket >> hashp->sshift;
1180  segment_ndx = MOD(newbucket, hashp->ssize);
1181 
1182  segp = hashp->dir[segment_num];
1183 
1184  if (segp == NULL)
1185  hash_corrupted(hashp);
1186 
1187  prevBucketPtr = &segp[segment_ndx];
1188  currBucket = *prevBucketPtr;
1189 
1190  /*
1191  * Follow collision chain looking for matching key
1192  */
1193  match = hashp->match; /* save one fetch in inner loop */
1194  keysize = hashp->keysize; /* ditto */
1195 
1196  while (currBucket != NULL)
1197  {
1198  if (currBucket->hashvalue == newhashvalue &&
1199  match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0)
1200  break;
1201  prevBucketPtr = &(currBucket->link);
1202  currBucket = *prevBucketPtr;
1203 #if HASH_STATISTICS
1204  hash_collisions++;
1205  hctl->collisions++;
1206 #endif
1207  }
1208 
1209  if (currBucket != NULL)
1210  return false; /* collision with an existing entry */
1211 
1212  currBucket = existingElement;
1213 
1214  /*
1215  * If old and new hash values belong to the same bucket, we need not
1216  * change any chain links, and indeed should not since this simplistic
1217  * update will corrupt the list if currBucket is the last element. (We
1218  * cannot fall out earlier, however, since we need to scan the bucket to
1219  * check for duplicate keys.)
1220  */
1221  if (bucket != newbucket)
1222  {
1223  /* OK to remove record from old hash bucket's chain. */
1224  *oldPrevPtr = currBucket->link;
1225 
1226  /* link into new hashbucket chain */
1227  *prevBucketPtr = currBucket;
1228  currBucket->link = NULL;
1229  }
1230 
1231  /* copy new key into record */
1232  currBucket->hashvalue = newhashvalue;
1233  hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize);
1234 
1235  /* rest of record is untouched */
1236 
1237  return true;
1238 }
Size keysize
Definition: dynahash.c:225
static uint32 calc_bucket(HASHHDR *hctl, uint32 hash_val)
Definition: dynahash.c:863
#define ELEMENTKEY(helem)
Definition: dynahash.c:233
#define ELEMENT_FROM_KEY(key)
Definition: dynahash.c:238
HashValueFunc hash
Definition: dynahash.c:212
long ssize
Definition: dynahash.c:226
#define ERROR
Definition: elog.h:43
int sshift
Definition: dynahash.c:227
#define MOD(x, y)
Definition: dynahash.c:244
HASHHDR * hctl
Definition: dynahash.c:210
static void hash_corrupted(HTAB *hashp)
Definition: dynahash.c:1700
unsigned int uint32
Definition: c.h:258
HashCompareFunc match
Definition: dynahash.c:213
bool frozen
Definition: dynahash.c:222
HashCopyFunc keycopy
Definition: dynahash.c:214
size_t Size
Definition: c.h:350
char * tabname
Definition: dynahash.c:217
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:211
#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:795
Datum hash_any(register const unsigned char *k, register int keylen)
Definition: hashfunc.c:428
size_t Size
Definition: c.h:350
uint32 tag_hash ( const void *  key,
Size  keysize 
)

Definition at line 52 of file hashfn.c.

References DatumGetUInt32, and hash_any().

Referenced by dshash_memhash(), and 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:428
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:258
Datum hash_uint32(uint32 k)
Definition: hashfunc.c:853
#define Assert(condition)
Definition: c.h:664