PostgreSQL Source Code  git master
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_ELEM   0x0008 /* Set keysize and entrysize (now required!) */
 
#define HASH_STRINGS   0x0010 /* Select support functions for string keys */
 
#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)
 

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, const 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)
 

Macro Definition Documentation

◆ HASH_ALLOC

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

Definition at line 101 of file hsearch.h.

◆ HASH_ATTACH

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

Definition at line 104 of file hsearch.h.

◆ HASH_BLOBS

#define HASH_BLOBS   0x0020 /* Select support functions for binary keys */

Definition at line 97 of file hsearch.h.

◆ HASH_COMPARE

#define HASH_COMPARE   0x0080 /* Set user defined comparison function */

Definition at line 99 of file hsearch.h.

◆ HASH_CONTEXT

#define HASH_CONTEXT   0x0400 /* Set memory allocation context */

Definition at line 102 of file hsearch.h.

◆ HASH_DIRSIZE

#define HASH_DIRSIZE   0x0004 /* Set directory size (initial and max) */

Definition at line 94 of file hsearch.h.

◆ HASH_ELEM

#define HASH_ELEM   0x0008 /* Set keysize and entrysize (now required!) */

Definition at line 95 of file hsearch.h.

◆ HASH_FIXED_SIZE

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

Definition at line 105 of file hsearch.h.

◆ HASH_FUNCTION

#define HASH_FUNCTION   0x0040 /* Set user defined hash function */

Definition at line 98 of file hsearch.h.

◆ HASH_KEYCOPY

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

Definition at line 100 of file hsearch.h.

◆ HASH_PARTITION

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

Definition at line 92 of file hsearch.h.

◆ HASH_SEGMENT

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

Definition at line 93 of file hsearch.h.

◆ HASH_SHARED_MEM

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

Definition at line 103 of file hsearch.h.

◆ HASH_STRINGS

#define HASH_STRINGS   0x0010 /* Select support functions for string keys */

Definition at line 96 of file hsearch.h.

◆ NO_MAX_DSIZE

#define NO_MAX_DSIZE   (-1)

Definition at line 108 of file hsearch.h.

Typedef Documentation

◆ HashAllocFunc

typedef void*(* HashAllocFunc) (Size request)

Definition at line 44 of file hsearch.h.

◆ HashCompareFunc

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

Definition at line 29 of file hsearch.h.

◆ HashCopyFunc

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

Definition at line 37 of file hsearch.h.

◆ HASHCTL

typedef struct HASHCTL HASHCTL

◆ HASHELEMENT

typedef struct HASHELEMENT HASHELEMENT

◆ HASHHDR

typedef struct HASHHDR HASHHDR

Definition at line 44 of file hsearch.h.

◆ HashValueFunc

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

Definition at line 21 of file hsearch.h.

◆ HTAB

typedef struct HTAB HTAB

Definition at line 44 of file hsearch.h.

Enumeration Type Documentation

◆ HASHACTION

enum HASHACTION
Enumerator
HASH_FIND 
HASH_ENTER 
HASH_REMOVE 
HASH_ENTER_NULL 

Definition at line 111 of file hsearch.h.

112 {
113  HASH_FIND,
114  HASH_ENTER,
115  HASH_REMOVE,
117 } HASHACTION;
HASHACTION
Definition: hsearch.h:112
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_REMOVE
Definition: hsearch.h:115
@ HASH_ENTER
Definition: hsearch.h:114
@ HASH_ENTER_NULL
Definition: hsearch.h:116

Function Documentation

◆ AtEOSubXact_HashTables()

void AtEOSubXact_HashTables ( bool  isCommit,
int  nestDepth 
)

Definition at line 1904 of file dynahash.c.

1905 {
1906  int i;
1907 
1908  /*
1909  * Search backward to make cleanup easy. Note we must check all entries,
1910  * not only those at the end of the array, because deletion technique
1911  * doesn't keep them in order.
1912  */
1913  for (i = num_seq_scans - 1; i >= 0; i--)
1914  {
1915  if (seq_scan_level[i] >= nestDepth)
1916  {
1917  if (isCommit)
1918  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1919  seq_scan_tables[i]);
1922  num_seq_scans--;
1923  }
1924  }
1925 }
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1824
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1825
static int num_seq_scans
Definition: dynahash.c:1826
#define WARNING
Definition: elog.h:36
int i
Definition: isn.c:73

References elog(), i, num_seq_scans, seq_scan_level, seq_scan_tables, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_HashTables()

void AtEOXact_HashTables ( bool  isCommit)

Definition at line 1878 of file dynahash.c.

1879 {
1880  /*
1881  * During abort cleanup, open scans are expected; just silently clean 'em
1882  * out. An open scan at commit means someone forgot a hash_seq_term()
1883  * call, so complain.
1884  *
1885  * Note: it's tempting to try to print the tabname here, but refrain for
1886  * fear of touching deallocated memory. This isn't a user-facing message
1887  * anyway, so it needn't be pretty.
1888  */
1889  if (isCommit)
1890  {
1891  int i;
1892 
1893  for (i = 0; i < num_seq_scans; i++)
1894  {
1895  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1896  seq_scan_tables[i]);
1897  }
1898  }
1899  num_seq_scans = 0;
1900 }

References elog(), i, num_seq_scans, seq_scan_tables, and WARNING.

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

◆ get_hash_value()

uint32 get_hash_value ( HTAB hashp,
const void *  keyPtr 
)

Definition at line 909 of file dynahash.c.

910 {
911  return hashp->hash(keyPtr, hashp->keysize);
912 }
HashValueFunc hash
Definition: dynahash.c:223
Size keysize
Definition: dynahash.c:236

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

Referenced by BufTableHashCode(), and LockTagHashCode().

◆ hash_create()

HTAB* hash_create ( const char *  tabname,
long  nelem,
const HASHCTL info,
int  flags 
)

Definition at line 350 of file dynahash.c.

351 {
352  HTAB *hashp;
353  HASHHDR *hctl;
354 
355  /*
356  * Hash tables now allocate space for key and data, but you have to say
357  * how much space to allocate.
358  */
359  Assert(flags & HASH_ELEM);
360  Assert(info->keysize > 0);
361  Assert(info->entrysize >= info->keysize);
362 
363  /*
364  * For shared hash tables, we have a local hash header (HTAB struct) that
365  * we allocate in TopMemoryContext; all else is in shared memory.
366  *
367  * For non-shared hash tables, everything including the hash header is in
368  * a memory context created specially for the hash table --- this makes
369  * hash_destroy very simple. The memory context is made a child of either
370  * a context specified by the caller, or TopMemoryContext if nothing is
371  * specified.
372  */
373  if (flags & HASH_SHARED_MEM)
374  {
375  /* Set up to allocate the hash header */
377  }
378  else
379  {
380  /* Create the hash table's private memory context */
381  if (flags & HASH_CONTEXT)
382  CurrentDynaHashCxt = info->hcxt;
383  else
386  "dynahash",
388  }
389 
390  /* Initialize the hash header, plus a copy of the table name */
391  hashp = (HTAB *) DynaHashAlloc(sizeof(HTAB) + strlen(tabname) + 1);
392  MemSet(hashp, 0, sizeof(HTAB));
393 
394  hashp->tabname = (char *) (hashp + 1);
395  strcpy(hashp->tabname, tabname);
396 
397  /* If we have a private context, label it with hashtable's name */
398  if (!(flags & HASH_SHARED_MEM))
400 
401  /*
402  * Select the appropriate hash function (see comments at head of file).
403  */
404  if (flags & HASH_FUNCTION)
405  {
406  Assert(!(flags & (HASH_BLOBS | HASH_STRINGS)));
407  hashp->hash = info->hash;
408  }
409  else if (flags & HASH_BLOBS)
410  {
411  Assert(!(flags & HASH_STRINGS));
412  /* We can optimize hashing for common key sizes */
413  if (info->keysize == sizeof(uint32))
414  hashp->hash = uint32_hash;
415  else
416  hashp->hash = tag_hash;
417  }
418  else
419  {
420  /*
421  * string_hash used to be considered the default hash method, and in a
422  * non-assert build it effectively still is. But we now consider it
423  * an assertion error to not say HASH_STRINGS explicitly. To help
424  * catch mistaken usage of HASH_STRINGS, we also insist on a
425  * reasonably long string length: if the keysize is only 4 or 8 bytes,
426  * it's almost certainly an integer or pointer not a string.
427  */
428  Assert(flags & HASH_STRINGS);
429  Assert(info->keysize > 8);
430 
431  hashp->hash = string_hash;
432  }
433 
434  /*
435  * If you don't specify a match function, it defaults to string_compare if
436  * you used string_hash, and to memcmp otherwise.
437  *
438  * Note: explicitly specifying string_hash is deprecated, because this
439  * might not work for callers in loadable modules on some platforms due to
440  * referencing a trampoline instead of the string_hash function proper.
441  * Specify HASH_STRINGS instead.
442  */
443  if (flags & HASH_COMPARE)
444  hashp->match = info->match;
445  else if (hashp->hash == string_hash)
447  else
448  hashp->match = memcmp;
449 
450  /*
451  * Similarly, the key-copying function defaults to strlcpy or memcpy.
452  */
453  if (flags & HASH_KEYCOPY)
454  hashp->keycopy = info->keycopy;
455  else if (hashp->hash == string_hash)
456  {
457  /*
458  * The signature of keycopy is meant for memcpy(), which returns
459  * void*, but strlcpy() returns size_t. Since we never use the return
460  * value of keycopy, and size_t is pretty much always the same size as
461  * void *, this should be safe. The extra cast in the middle is to
462  * avoid warnings from -Wcast-function-type.
463  */
465  }
466  else
467  hashp->keycopy = memcpy;
468 
469  /* And select the entry allocation function, too. */
470  if (flags & HASH_ALLOC)
471  hashp->alloc = info->alloc;
472  else
473  hashp->alloc = DynaHashAlloc;
474 
475  if (flags & HASH_SHARED_MEM)
476  {
477  /*
478  * ctl structure and directory are preallocated for shared memory
479  * tables. Note that HASH_DIRSIZE and HASH_ALLOC had better be set as
480  * well.
481  */
482  hashp->hctl = info->hctl;
483  hashp->dir = (HASHSEGMENT *) (((char *) info->hctl) + sizeof(HASHHDR));
484  hashp->hcxt = NULL;
485  hashp->isshared = true;
486 
487  /* hash table already exists, we're just attaching to it */
488  if (flags & HASH_ATTACH)
489  {
490  /* make local copies of some heavily-used values */
491  hctl = hashp->hctl;
492  hashp->keysize = hctl->keysize;
493  hashp->ssize = hctl->ssize;
494  hashp->sshift = hctl->sshift;
495 
496  return hashp;
497  }
498  }
499  else
500  {
501  /* setup hash table defaults */
502  hashp->hctl = NULL;
503  hashp->dir = NULL;
504  hashp->hcxt = CurrentDynaHashCxt;
505  hashp->isshared = false;
506  }
507 
508  if (!hashp->hctl)
509  {
510  hashp->hctl = (HASHHDR *) hashp->alloc(sizeof(HASHHDR));
511  if (!hashp->hctl)
512  ereport(ERROR,
513  (errcode(ERRCODE_OUT_OF_MEMORY),
514  errmsg("out of memory")));
515  }
516 
517  hashp->frozen = false;
518 
519  hdefault(hashp);
520 
521  hctl = hashp->hctl;
522 
523  if (flags & HASH_PARTITION)
524  {
525  /* Doesn't make sense to partition a local hash table */
526  Assert(flags & HASH_SHARED_MEM);
527 
528  /*
529  * The number of partitions had better be a power of 2. Also, it must
530  * be less than INT_MAX (see init_htab()), so call the int version of
531  * next_pow2.
532  */
534 
535  hctl->num_partitions = info->num_partitions;
536  }
537 
538  if (flags & HASH_SEGMENT)
539  {
540  hctl->ssize = info->ssize;
541  hctl->sshift = my_log2(info->ssize);
542  /* ssize had better be a power of 2 */
543  Assert(hctl->ssize == (1L << hctl->sshift));
544  }
545 
546  /*
547  * SHM hash tables have fixed directory size passed by the caller.
548  */
549  if (flags & HASH_DIRSIZE)
550  {
551  hctl->max_dsize = info->max_dsize;
552  hctl->dsize = info->dsize;
553  }
554 
555  /* remember the entry sizes, too */
556  hctl->keysize = info->keysize;
557  hctl->entrysize = info->entrysize;
558 
559  /* make local copies of heavily-used constant fields */
560  hashp->keysize = hctl->keysize;
561  hashp->ssize = hctl->ssize;
562  hashp->sshift = hctl->sshift;
563 
564  /* Build the hash directory structure */
565  if (!init_htab(hashp, nelem))
566  elog(ERROR, "failed to initialize hash table \"%s\"", hashp->tabname);
567 
568  /*
569  * For a shared hash table, preallocate the requested number of elements.
570  * This reduces problems with run-time out-of-shared-memory conditions.
571  *
572  * For a non-shared hash table, preallocate the requested number of
573  * elements if it's less than our chosen nelem_alloc. This avoids wasting
574  * space if the caller correctly estimates a small table size.
575  */
576  if ((flags & HASH_SHARED_MEM) ||
577  nelem < hctl->nelem_alloc)
578  {
579  int i,
580  freelist_partitions,
581  nelem_alloc,
582  nelem_alloc_first;
583 
584  /*
585  * If hash table is partitioned, give each freelist an equal share of
586  * the initial allocation. Otherwise only freeList[0] is used.
587  */
588  if (IS_PARTITIONED(hashp->hctl))
589  freelist_partitions = NUM_FREELISTS;
590  else
591  freelist_partitions = 1;
592 
593  nelem_alloc = nelem / freelist_partitions;
594  if (nelem_alloc <= 0)
595  nelem_alloc = 1;
596 
597  /*
598  * Make sure we'll allocate all the requested elements; freeList[0]
599  * gets the excess if the request isn't divisible by NUM_FREELISTS.
600  */
601  if (nelem_alloc * freelist_partitions < nelem)
602  nelem_alloc_first =
603  nelem - nelem_alloc * (freelist_partitions - 1);
604  else
605  nelem_alloc_first = nelem_alloc;
606 
607  for (i = 0; i < freelist_partitions; i++)
608  {
609  int temp = (i == 0) ? nelem_alloc_first : nelem_alloc;
610 
611  if (!element_alloc(hashp, temp, i))
612  ereport(ERROR,
613  (errcode(ERRCODE_OUT_OF_MEMORY),
614  errmsg("out of memory")));
615  }
616  }
617 
618  if (flags & HASH_FIXED_SIZE)
619  hashp->isfixed = true;
620  return hashp;
621 }
unsigned int uint32
Definition: c.h:490
#define MemSet(start, val, len)
Definition: c.h:1004
void(* pg_funcptr_t)(void)
Definition: c.h:372
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:289
static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx)
Definition: dynahash.c:1699
static bool init_htab(HTAB *hashp, long nelem)
Definition: dynahash.c:687
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286
static int next_pow2_int(long num)
Definition: dynahash.c:1786
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:210
#define NUM_FREELISTS
Definition: dynahash.c:128
static int string_compare(const char *key1, const char *key2, Size keysize)
Definition: dynahash.c:305
static void hdefault(HTAB *hashp)
Definition: dynahash.c:627
int my_log2(long num)
Definition: dynahash.c:1760
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
uint32 tag_hash(const void *key, Size keysize)
Definition: hashfn.c:677
uint32 uint32_hash(const void *key, Size keysize)
Definition: hashfn.c:688
uint32 string_hash(const void *key, Size keysize)
Definition: hashfn.c:660
#define HASH_KEYCOPY
Definition: hsearch.h:100
#define HASH_STRINGS
Definition: hsearch.h:96
int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)
Definition: hsearch.h:29
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_ALLOC
Definition: hsearch.h:101
#define HASH_DIRSIZE
Definition: hsearch.h:94
#define HASH_SEGMENT
Definition: hsearch.h:93
#define HASH_ATTACH
Definition: hsearch.h:104
#define HASH_COMPARE
Definition: hsearch.h:99
#define HASH_FUNCTION
Definition: hsearch.h:98
#define HASH_BLOBS
Definition: hsearch.h:97
#define HASH_SHARED_MEM
Definition: hsearch.h:103
#define HASH_FIXED_SIZE
Definition: hsearch.h:105
#define HASH_PARTITION
Definition: hsearch.h:92
void *(* HashCopyFunc)(void *dest, const void *src, Size keysize)
Definition: hsearch.h:37
Assert(fmt[strlen(fmt) - 1] !='\n')
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:505
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
long ssize
Definition: hsearch.h:70
HashAllocFunc alloc
Definition: hsearch.h:84
Size keysize
Definition: hsearch.h:75
HashValueFunc hash
Definition: hsearch.h:78
Size entrysize
Definition: hsearch.h:76
long dsize
Definition: hsearch.h:72
HashCompareFunc match
Definition: hsearch.h:80
HASHHDR * hctl
Definition: hsearch.h:88
MemoryContext hcxt
Definition: hsearch.h:86
long num_partitions
Definition: hsearch.h:68
HashCopyFunc keycopy
Definition: hsearch.h:82
long max_dsize
Definition: hsearch.h:73
long max_dsize
Definition: dynahash.c:194
long num_partitions
Definition: dynahash.c:193
Size entrysize
Definition: dynahash.c:192
Size keysize
Definition: dynahash.c:191
int sshift
Definition: dynahash.c:196
long ssize
Definition: dynahash.c:195
long dsize
Definition: dynahash.c:184
Definition: dynahash.c:220
bool isfixed
Definition: dynahash.c:230
bool isshared
Definition: dynahash.c:229
HashCompareFunc match
Definition: dynahash.c:224
char * tabname
Definition: dynahash.c:228
HASHHDR * hctl
Definition: dynahash.c:221
MemoryContext hcxt
Definition: dynahash.c:227
HashAllocFunc alloc
Definition: dynahash.c:226
long ssize
Definition: dynahash.c:237
HASHSEGMENT * dir
Definition: dynahash.c:222
int sshift
Definition: dynahash.c:238
HashCopyFunc keycopy
Definition: dynahash.c:225
bool frozen
Definition: dynahash.c:233

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

Referenced by _hash_finish_split(), _PG_init(), AddEventToPendingNotifies(), AddPendingSync(), assign_record_type_typmod(), begin_heap_rewrite(), build_guc_variables(), build_join_rel_hash(), BuildEventTriggerCache(), CheckForSessionAndXactLocks(), CompactCheckpointerRequestQueue(), compute_array_stats(), compute_tsvector_stats(), create_seq_hashtable(), createConnHash(), CreateLocalPredicateLockHash(), CreatePartitionDirectory(), do_autovacuum(), EnablePortalManager(), ExecInitModifyTable(), ExecuteTruncateGuts(), find_all_inheritors(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), GetComboCommandId(), GetConnection(), gistInitBuildBuffers(), gistInitParentMap(), init_procedure_caches(), init_rel_sync_cache(), init_timezone_hashtable(), init_ts_config_cache(), init_uncommitted_enums(), InitBufferPoolAccess(), InitializeAttoptCache(), InitializeRelfilenumberMap(), InitializeShippableCache(), InitializeTableSpaceCache(), InitLocalBuffers(), InitLocks(), InitQueryHashTable(), InitRecoveryTransactionEnvironment(), InitSync(), json_unique_check_init(), load_categories_hash(), log_invalid_page(), logical_begin_heap_rewrite(), logicalrep_partmap_init(), logicalrep_relmap_init(), lookup_collation_cache(), lookup_proof_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), pa_allocate_worker(), 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(), ResetUnloggedRelationsInDbspaceDir(), ri_InitHashTables(), select_perl_context(), SerializePendingSyncs(), set_rtable_names(), ShmemInitHash(), smgropen(), transformGraph(), and XLogPrefetcherAllocate().

◆ hash_destroy()

void hash_destroy ( HTAB hashp)

Definition at line 863 of file dynahash.c.

864 {
865  if (hashp != NULL)
866  {
867  /* allocation method must be one we know how to free, too */
868  Assert(hashp->alloc == DynaHashAlloc);
869  /* so this hashtable must have its own context */
870  Assert(hashp->hcxt != NULL);
871 
872  hash_stats("destroy", hashp);
873 
874  /*
875  * Free everything by destroying the hash table's memory context.
876  */
877  MemoryContextDelete(hashp->hcxt);
878  }
879 }
void hash_stats(const char *where, HTAB *hashp)
Definition: dynahash.c:882
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387

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

Referenced by _hash_finish_split(), CheckForSessionAndXactLocks(), CompactCheckpointerRequestQueue(), ExecuteTruncateGuts(), find_all_inheritors(), InitLocks(), pgoutput_shutdown(), populate_recordset_object_end(), PostPrepare_PredicateLocks(), process_syncing_tables_for_apply(), ReleasePredicateLocksLocal(), ReorderBufferReturnTXN(), ReorderBufferToastReset(), ReorderBufferTruncateTXN(), ResetSequenceCaches(), ResetUnloggedRelationsInDbspaceDir(), SerializePendingSyncs(), set_rtable_names(), ShutdownRecoveryTransactionEnvironment(), XLogCheckInvalidPages(), and XLogPrefetcherFree().

◆ hash_estimate_size()

Size hash_estimate_size ( long  num_entries,
Size  entrysize 
)

Definition at line 781 of file dynahash.c.

782 {
783  Size size;
784  long nBuckets,
785  nSegments,
786  nDirEntries,
787  nElementAllocs,
788  elementSize,
789  elementAllocCnt;
790 
791  /* estimate number of buckets wanted */
792  nBuckets = next_pow2_long(num_entries);
793  /* # of segments needed for nBuckets */
794  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
795  /* directory entries */
796  nDirEntries = DEF_DIRSIZE;
797  while (nDirEntries < nSegments)
798  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
799 
800  /* fixed control info */
801  size = MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */
802  /* directory */
803  size = add_size(size, mul_size(nDirEntries, sizeof(HASHSEGMENT)));
804  /* segments */
805  size = add_size(size, mul_size(nSegments,
806  MAXALIGN(DEF_SEGSIZE * sizeof(HASHBUCKET))));
807  /* elements --- allocated in groups of choose_nelem_alloc() entries */
808  elementAllocCnt = choose_nelem_alloc(entrysize);
809  nElementAllocs = (num_entries - 1) / elementAllocCnt + 1;
810  elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(entrysize);
811  size = add_size(size,
812  mul_size(nElementAllocs,
813  mul_size(elementAllocCnt, elementSize)));
814 
815  return size;
816 }
#define MAXALIGN(LEN)
Definition: c.h:795
size_t Size
Definition: c.h:589
#define DEF_DIRSIZE
Definition: dynahash.c:125
static int choose_nelem_alloc(Size entrysize)
Definition: dynahash.c:654
#define DEF_SEGSIZE
Definition: dynahash.c:123
static long next_pow2_long(long num)
Definition: dynahash.c:1778
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

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

◆ hash_freeze()

void hash_freeze ( HTAB hashp)

Definition at line 1527 of file dynahash.c.

1528 {
1529  if (hashp->isshared)
1530  elog(ERROR, "cannot freeze shared hashtable \"%s\"", hashp->tabname);
1531  if (!hashp->frozen && has_seq_scans(hashp))
1532  elog(ERROR, "cannot freeze hashtable \"%s\" because it has active scans",
1533  hashp->tabname);
1534  hashp->frozen = true;
1535 }
static bool has_seq_scans(HTAB *hashp)
Definition: dynahash.c:1864

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

◆ hash_get_num_entries()

long hash_get_num_entries ( HTAB hashp)

Definition at line 1377 of file dynahash.c.

1378 {
1379  int i;
1380  long sum = hashp->hctl->freeList[0].nentries;
1381 
1382  /*
1383  * We currently don't bother with acquiring the mutexes; it's only
1384  * sensible to call this function if you've got lock on all partitions of
1385  * the table.
1386  */
1387  if (IS_PARTITIONED(hashp->hctl))
1388  {
1389  for (i = 1; i < NUM_FREELISTS; i++)
1390  sum += hashp->hctl->freeList[i].nentries;
1391  }
1392 
1393  return sum;
1394 }
long nentries
Definition: dynahash.c:156
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:180

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

Referenced by build_guc_variables(), compute_array_stats(), compute_tsvector_stats(), entry_alloc(), entry_dealloc(), entry_reset(), EstimatePendingSyncsSpace(), EstimateUncommittedEnumsSpace(), get_crosstab_tuplestore(), get_explain_guc_options(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), hash_stats(), pgss_shmem_shutdown(), ResetUnloggedRelationsInDbspaceDir(), SerializePendingSyncs(), transformGraph(), and XLogHaveInvalidPages().

◆ hash_get_shared_size()

Size hash_get_shared_size ( HASHCTL info,
int  flags 
)

Definition at line 852 of file dynahash.c.

853 {
854  Assert(flags & HASH_DIRSIZE);
855  Assert(info->dsize == info->max_dsize);
856  return sizeof(HASHHDR) + info->dsize * sizeof(HASHSEGMENT);
857 }
struct HASHHDR HASHHDR
Definition: hsearch.h:58

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

Referenced by ShmemInitHash().

◆ hash_search()

void* hash_search ( HTAB hashp,
const void *  keyPtr,
HASHACTION  action,
bool foundPtr 
)

Definition at line 953 of file dynahash.c.

957 {
958  return hash_search_with_hash_value(hashp,
959  keyPtr,
960  hashp->hash(keyPtr, hashp->keysize),
961  action,
962  foundPtr);
963 }
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:966

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

Referenced by _hash_finish_split(), _hash_splitbucket(), add_guc_variable(), add_join_rel(), AddEnumLabel(), AddEventToPendingNotifies(), AddPendingSync(), ApplyLogicalMappingFile(), assign_record_type_typmod(), AsyncExistsPendingNotify(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), build_guc_variables(), build_join_rel_hash(), BuildEventTriggerCache(), CheckAndPromotePredicateLockRequest(), CheckForSerializableConflictOut(), CheckForSessionAndXactLocks(), CompactCheckpointerRequestQueue(), compile_plperl_function(), compile_pltcl_function(), compute_array_stats(), compute_tsvector_stats(), createNewConnection(), define_custom_variable(), deleteConnection(), do_autovacuum(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), DropPreparedStatement(), DropRelationAllLocalBuffers(), DropRelationLocalBuffers(), entry_alloc(), entry_dealloc(), entry_reset(), EnumUncommitted(), EventCacheLookup(), ExecInitModifyTable(), ExecLookupResultRelByOid(), ExecuteTruncateGuts(), FetchPreparedStatement(), find_all_inheritors(), find_join_rel(), find_oper_cache_entry(), find_option(), find_rendezvous_variable(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPrivateRefCountEntry(), get_attribute_options(), get_cast_hashentry(), 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(), JsObjectGetField(), json_unique_check_key(), LocalBufferAlloc(), LockAcquireExtended(), LockHasWaiters(), LockHeldByMe(), LockRelease(), log_invalid_page(), logical_rewrite_log_mapping(), logicalrep_partition_open(), logicalrep_rel_open(), logicalrep_relmap_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(), MarkGUCPrefixReserved(), pa_allocate_worker(), pa_find_worker(), pa_free_worker(), PartitionDirectoryLookup(), pg_tzset(), pgss_store(), plperl_spi_exec_prepared(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query_prepared(), plpgsql_HashTableDelete(), plpgsql_HashTableInsert(), plpgsql_HashTableLookup(), pltcl_fetch_interp(), PLy_commit(), PLy_generate_spi_exceptions(), PLy_procedure_get(), PLy_rollback(), PLy_spi_subtransaction_abort(), populate_recordset_object_field_end(), predicatelock_twophase_recover(), PredicateLockExists(), PredicateLockTwoPhaseFinish(), PrefetchLocalBuffer(), process_syncing_tables_for_apply(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RegisterPredicateLockingXid(), rel_sync_cache_relation_cb(), RelationPreTruncate(), ReleaseOneSerializableXact(), RelFileLocatorSkippingWAL(), RelfilenumberMapInvalidateCallback(), RelidByRelfilenumber(), RememberSyncRequest(), RemoveLocalLock(), ReorderBufferBuildTupleCidHash(), ReorderBufferCleanupTXN(), ReorderBufferToastAppendChunk(), ReorderBufferToastReplace(), ReorderBufferTXNByXid(), ReservePrivateRefCountEntry(), ResetUnloggedRelationsInDbspaceDir(), ResolveCminCmaxDuringDecoding(), RestoreUncommittedEnums(), rewrite_heap_dead_tuple(), rewrite_heap_tuple(), ri_FetchPreparedPlan(), ri_HashCompareOp(), ri_HashPreparedPlan(), ri_LoadConstraintInfo(), select_perl_context(), SerializePendingSyncs(), set_rtable_names(), ShmemInitStruct(), smgrclose(), smgrcloserellocator(), smgrDoPendingSyncs(), smgropen(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), StandbyReleaseLocks(), StandbyReleaseOldLocks(), StandbyReleaseXidEntryLocks(), StorePreparedStatement(), table_recheck_autovac(), XLogPrefetcherAddFilter(), XLogPrefetcherCompleteFilters(), and XLogPrefetcherIsFiltered().

◆ hash_search_with_hash_value()

void* hash_search_with_hash_value ( HTAB hashp,
const void *  keyPtr,
uint32  hashvalue,
HASHACTION  action,
bool foundPtr 
)

Definition at line 966 of file dynahash.c.

971 {
972  HASHHDR *hctl = hashp->hctl;
973  int freelist_idx = FREELIST_IDX(hctl, hashvalue);
974  Size keysize;
975  uint32 bucket;
976  long segment_num;
977  long segment_ndx;
978  HASHSEGMENT segp;
979  HASHBUCKET currBucket;
980  HASHBUCKET *prevBucketPtr;
981  HashCompareFunc match;
982 
983 #ifdef HASH_STATISTICS
984  hash_accesses++;
985  hctl->accesses++;
986 #endif
987 
988  /*
989  * If inserting, check if it is time to split a bucket.
990  *
991  * NOTE: failure to expand table is not a fatal error, it just means we
992  * have to run at higher fill factor than we wanted. However, if we're
993  * using the palloc allocator then it will throw error anyway on
994  * out-of-memory, so we must do this before modifying the table.
995  */
997  {
998  /*
999  * Can't split if running in partitioned mode, nor if frozen, nor if
1000  * table is the subject of any active hash_seq_search scans.
1001  */
1002  if (hctl->freeList[0].nentries > (long) hctl->max_bucket &&
1003  !IS_PARTITIONED(hctl) && !hashp->frozen &&
1004  !has_seq_scans(hashp))
1005  (void) expand_table(hashp);
1006  }
1007 
1008  /*
1009  * Do the initial lookup
1010  */
1011  bucket = calc_bucket(hctl, hashvalue);
1012 
1013  segment_num = bucket >> hashp->sshift;
1014  segment_ndx = MOD(bucket, hashp->ssize);
1015 
1016  segp = hashp->dir[segment_num];
1017 
1018  if (segp == NULL)
1019  hash_corrupted(hashp);
1020 
1021  prevBucketPtr = &segp[segment_ndx];
1022  currBucket = *prevBucketPtr;
1023 
1024  /*
1025  * Follow collision chain looking for matching key
1026  */
1027  match = hashp->match; /* save one fetch in inner loop */
1028  keysize = hashp->keysize; /* ditto */
1029 
1030  while (currBucket != NULL)
1031  {
1032  if (currBucket->hashvalue == hashvalue &&
1033  match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0)
1034  break;
1035  prevBucketPtr = &(currBucket->link);
1036  currBucket = *prevBucketPtr;
1037 #ifdef HASH_STATISTICS
1038  hash_collisions++;
1039  hctl->collisions++;
1040 #endif
1041  }
1042 
1043  if (foundPtr)
1044  *foundPtr = (bool) (currBucket != NULL);
1045 
1046  /*
1047  * OK, now what?
1048  */
1049  switch (action)
1050  {
1051  case HASH_FIND:
1052  if (currBucket != NULL)
1053  return (void *) ELEMENTKEY(currBucket);
1054  return NULL;
1055 
1056  case HASH_REMOVE:
1057  if (currBucket != NULL)
1058  {
1059  /* if partitioned, must lock to touch nentries and freeList */
1060  if (IS_PARTITIONED(hctl))
1061  SpinLockAcquire(&(hctl->freeList[freelist_idx].mutex));
1062 
1063  /* delete the record from the appropriate nentries counter. */
1064  Assert(hctl->freeList[freelist_idx].nentries > 0);
1065  hctl->freeList[freelist_idx].nentries--;
1066 
1067  /* remove record from hash bucket's chain. */
1068  *prevBucketPtr = currBucket->link;
1069 
1070  /* add the record to the appropriate freelist. */
1071  currBucket->link = hctl->freeList[freelist_idx].freeList;
1072  hctl->freeList[freelist_idx].freeList = currBucket;
1073 
1074  if (IS_PARTITIONED(hctl))
1075  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1076 
1077  /*
1078  * better hope the caller is synchronizing access to this
1079  * element, because someone else is going to reuse it the next
1080  * time something is added to the table
1081  */
1082  return (void *) ELEMENTKEY(currBucket);
1083  }
1084  return NULL;
1085 
1086  case HASH_ENTER:
1087  case HASH_ENTER_NULL:
1088  /* Return existing element if found, else create one */
1089  if (currBucket != NULL)
1090  return (void *) ELEMENTKEY(currBucket);
1091 
1092  /* disallow inserts if frozen */
1093  if (hashp->frozen)
1094  elog(ERROR, "cannot insert into frozen hashtable \"%s\"",
1095  hashp->tabname);
1096 
1097  currBucket = get_hash_entry(hashp, freelist_idx);
1098  if (currBucket == NULL)
1099  {
1100  /* out of memory */
1101  if (action == HASH_ENTER_NULL)
1102  return NULL;
1103  /* report a generic message */
1104  if (hashp->isshared)
1105  ereport(ERROR,
1106  (errcode(ERRCODE_OUT_OF_MEMORY),
1107  errmsg("out of shared memory")));
1108  else
1109  ereport(ERROR,
1110  (errcode(ERRCODE_OUT_OF_MEMORY),
1111  errmsg("out of memory")));
1112  }
1113 
1114  /* link into hashbucket chain */
1115  *prevBucketPtr = currBucket;
1116  currBucket->link = NULL;
1117 
1118  /* copy key into record */
1119  currBucket->hashvalue = hashvalue;
1120  hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize);
1121 
1122  /*
1123  * Caller is expected to fill the data field on return. DO NOT
1124  * insert any code that could possibly throw error here, as doing
1125  * so would leave the table entry incomplete and hence corrupt the
1126  * caller's data structure.
1127  */
1128 
1129  return (void *) ELEMENTKEY(currBucket);
1130  }
1131 
1132  elog(ERROR, "unrecognized hash action code: %d", (int) action);
1133 
1134  return NULL; /* keep compiler quiet */
1135 }
unsigned char bool
Definition: c.h:440
#define MOD(x, y)
Definition: dynahash.c:255
static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx)
Definition: dynahash.c:1292
static bool expand_table(HTAB *hashp)
Definition: dynahash.c:1544
#define ELEMENTKEY(helem)
Definition: dynahash.c:244
#define FREELIST_IDX(hctl, hashcode)
Definition: dynahash.c:212
static void hash_corrupted(HTAB *hashp)
Definition: dynahash.c:1746
static uint32 calc_bucket(HASHHDR *hctl, uint32 hash_val)
Definition: dynahash.c:916
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
slock_t mutex
Definition: dynahash.c:155
HASHELEMENT * freeList
Definition: dynahash.c:157
struct HASHELEMENT * link
Definition: hsearch.h:53
uint32 hashvalue
Definition: hsearch.h:54
uint32 max_bucket
Definition: dynahash.c:186

References generate_unaccent_rules::action, Assert(), calc_bucket(), HTAB::dir, ELEMENTKEY, elog(), ereport, errcode(), errmsg(), ERROR, expand_table(), 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().

◆ hash_select_dirsize()

long hash_select_dirsize ( long  num_entries)

Definition at line 828 of file dynahash.c.

829 {
830  long nBuckets,
831  nSegments,
832  nDirEntries;
833 
834  /* estimate number of buckets wanted */
835  nBuckets = next_pow2_long(num_entries);
836  /* # of segments needed for nBuckets */
837  nSegments = next_pow2_long((nBuckets - 1) / DEF_SEGSIZE + 1);
838  /* directory entries */
839  nDirEntries = DEF_DIRSIZE;
840  while (nDirEntries < nSegments)
841  nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */
842 
843  return nDirEntries;
844 }

References DEF_DIRSIZE, DEF_SEGSIZE, and next_pow2_long().

Referenced by ShmemInitHash().

◆ hash_seq_init()

void hash_seq_init ( HASH_SEQ_STATUS status,
HTAB hashp 
)

Definition at line 1421 of file dynahash.c.

1422 {
1423  status->hashp = hashp;
1424  status->curBucket = 0;
1425  status->curEntry = NULL;
1426  if (!hashp->frozen)
1427  register_seq_scan(hashp);
1428 }
static void register_seq_scan(HTAB *hashp)
Definition: dynahash.c:1831
HASHELEMENT * curEntry
Definition: hsearch.h:124
uint32 curBucket
Definition: hsearch.h:123
HTAB * hashp
Definition: hsearch.h:122

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(), BeginReportingGUCOptions(), CheckForBufferLeaks(), CheckForSessionAndXactLocks(), CheckTableForSerializableConflictIn(), cleanup_rel_sync_cache(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DestroyPartitionDirectory(), disconnect_cached_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), ExecuteTruncateGuts(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPortalSnapshots(), gc_qtexts(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), HoldPinnedPortals(), InitializeGUCOptions(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_partmap_reset_relmap(), logicalrep_relmap_invalidate_cb(), MarkGUCPrefixReserved(), packGraph(), pg_cursor(), pg_get_shmem_allocations(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_inval_callback(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections(), PostPrepare_Locks(), PreCommit_Portals(), ProcessConfigFileInternal(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), rel_sync_cache_relation_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenumberMapInvalidateCallback(), RememberSyncRequest(), ReorderBufferLargestTXN(), ReorderBufferToastReset(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrcloseall(), smgrDoPendingSyncs(), smgrreleaseall(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

◆ hash_seq_search()

void* hash_seq_search ( HASH_SEQ_STATUS status)

Definition at line 1431 of file dynahash.c.

1432 {
1433  HTAB *hashp;
1434  HASHHDR *hctl;
1435  uint32 max_bucket;
1436  long ssize;
1437  long segment_num;
1438  long segment_ndx;
1439  HASHSEGMENT segp;
1440  uint32 curBucket;
1441  HASHELEMENT *curElem;
1442 
1443  if ((curElem = status->curEntry) != NULL)
1444  {
1445  /* Continuing scan of curBucket... */
1446  status->curEntry = curElem->link;
1447  if (status->curEntry == NULL) /* end of this bucket */
1448  ++status->curBucket;
1449  return (void *) ELEMENTKEY(curElem);
1450  }
1451 
1452  /*
1453  * Search for next nonempty bucket starting at curBucket.
1454  */
1455  curBucket = status->curBucket;
1456  hashp = status->hashp;
1457  hctl = hashp->hctl;
1458  ssize = hashp->ssize;
1459  max_bucket = hctl->max_bucket;
1460 
1461  if (curBucket > max_bucket)
1462  {
1463  hash_seq_term(status);
1464  return NULL; /* search is done */
1465  }
1466 
1467  /*
1468  * first find the right segment in the table directory.
1469  */
1470  segment_num = curBucket >> hashp->sshift;
1471  segment_ndx = MOD(curBucket, ssize);
1472 
1473  segp = hashp->dir[segment_num];
1474 
1475  /*
1476  * Pick up the first item in this bucket's chain. If chain is not empty
1477  * we can begin searching it. Otherwise we have to advance to find the
1478  * next nonempty bucket. We try to optimize that case since searching a
1479  * near-empty hashtable has to iterate this loop a lot.
1480  */
1481  while ((curElem = segp[segment_ndx]) == NULL)
1482  {
1483  /* empty bucket, advance to next */
1484  if (++curBucket > max_bucket)
1485  {
1486  status->curBucket = curBucket;
1487  hash_seq_term(status);
1488  return NULL; /* search is done */
1489  }
1490  if (++segment_ndx >= ssize)
1491  {
1492  segment_num++;
1493  segment_ndx = 0;
1494  segp = hashp->dir[segment_num];
1495  }
1496  }
1497 
1498  /* Begin scan of curBucket... */
1499  status->curEntry = curElem->link;
1500  if (status->curEntry == NULL) /* end of this bucket */
1501  ++curBucket;
1502  status->curBucket = curBucket;
1503  return (void *) ELEMENTKEY(curElem);
1504 }
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1507

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(), BeginReportingGUCOptions(), CheckForBufferLeaks(), CheckForSessionAndXactLocks(), CheckTableForSerializableConflictIn(), cleanup_rel_sync_cache(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DestroyPartitionDirectory(), disconnect_cached_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), ExecuteTruncateGuts(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPortalSnapshots(), gc_qtexts(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), HoldPinnedPortals(), InitializeGUCOptions(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_partmap_reset_relmap(), logicalrep_relmap_invalidate_cb(), MarkGUCPrefixReserved(), packGraph(), pg_cursor(), pg_get_shmem_allocations(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_inval_callback(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections(), PostPrepare_Locks(), PreCommit_Portals(), ProcessConfigFileInternal(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), rel_sync_cache_relation_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenumberMapInvalidateCallback(), RememberSyncRequest(), ReorderBufferLargestTXN(), ReorderBufferToastReset(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrcloseall(), smgrDoPendingSyncs(), smgrreleaseall(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

◆ hash_seq_term()

void hash_seq_term ( HASH_SEQ_STATUS status)

◆ hash_stats()

void hash_stats ( const char *  where,
HTAB hashp 
)

Definition at line 882 of file dynahash.c.

883 {
884 #ifdef HASH_STATISTICS
885  fprintf(stderr, "%s: this HTAB -- accesses %ld collisions %ld\n",
886  where, hashp->hctl->accesses, hashp->hctl->collisions);
887 
888  fprintf(stderr, "hash_stats: entries %ld keysize %ld maxp %u segmentcount %ld\n",
889  hash_get_num_entries(hashp), (long) hashp->hctl->keysize,
890  hashp->hctl->max_bucket, hashp->hctl->nsegs);
891  fprintf(stderr, "%s: total accesses %ld total collisions %ld\n",
892  where, hash_accesses, hash_collisions);
893  fprintf(stderr, "hash_stats: total expansions %ld\n",
894  hash_expansions);
895 #endif
896 }
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1377
#define fprintf
Definition: port.h:242
long nsegs
Definition: dynahash.c:185

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

Referenced by hash_destroy().

◆ hash_update_hash_key()

bool hash_update_hash_key ( HTAB hashp,
void *  existingEntry,
const void *  newKeyPtr 
)

Definition at line 1157 of file dynahash.c.

1160 {
1161  HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry);
1162  HASHHDR *hctl = hashp->hctl;
1163  uint32 newhashvalue;
1164  Size keysize;
1165  uint32 bucket;
1166  uint32 newbucket;
1167  long segment_num;
1168  long segment_ndx;
1169  HASHSEGMENT segp;
1170  HASHBUCKET currBucket;
1171  HASHBUCKET *prevBucketPtr;
1172  HASHBUCKET *oldPrevPtr;
1173  HashCompareFunc match;
1174 
1175 #ifdef HASH_STATISTICS
1176  hash_accesses++;
1177  hctl->accesses++;
1178 #endif
1179 
1180  /* disallow updates if frozen */
1181  if (hashp->frozen)
1182  elog(ERROR, "cannot update in frozen hashtable \"%s\"",
1183  hashp->tabname);
1184 
1185  /*
1186  * Lookup the existing element using its saved hash value. We need to do
1187  * this to be able to unlink it from its hash chain, but as a side benefit
1188  * we can verify the validity of the passed existingEntry pointer.
1189  */
1190  bucket = calc_bucket(hctl, existingElement->hashvalue);
1191 
1192  segment_num = bucket >> hashp->sshift;
1193  segment_ndx = MOD(bucket, hashp->ssize);
1194 
1195  segp = hashp->dir[segment_num];
1196 
1197  if (segp == NULL)
1198  hash_corrupted(hashp);
1199 
1200  prevBucketPtr = &segp[segment_ndx];
1201  currBucket = *prevBucketPtr;
1202 
1203  while (currBucket != NULL)
1204  {
1205  if (currBucket == existingElement)
1206  break;
1207  prevBucketPtr = &(currBucket->link);
1208  currBucket = *prevBucketPtr;
1209  }
1210 
1211  if (currBucket == NULL)
1212  elog(ERROR, "hash_update_hash_key argument is not in hashtable \"%s\"",
1213  hashp->tabname);
1214 
1215  oldPrevPtr = prevBucketPtr;
1216 
1217  /*
1218  * Now perform the equivalent of a HASH_ENTER operation to locate the hash
1219  * chain we want to put the entry into.
1220  */
1221  newhashvalue = hashp->hash(newKeyPtr, hashp->keysize);
1222 
1223  newbucket = calc_bucket(hctl, newhashvalue);
1224 
1225  segment_num = newbucket >> hashp->sshift;
1226  segment_ndx = MOD(newbucket, hashp->ssize);
1227 
1228  segp = hashp->dir[segment_num];
1229 
1230  if (segp == NULL)
1231  hash_corrupted(hashp);
1232 
1233  prevBucketPtr = &segp[segment_ndx];
1234  currBucket = *prevBucketPtr;
1235 
1236  /*
1237  * Follow collision chain looking for matching key
1238  */
1239  match = hashp->match; /* save one fetch in inner loop */
1240  keysize = hashp->keysize; /* ditto */
1241 
1242  while (currBucket != NULL)
1243  {
1244  if (currBucket->hashvalue == newhashvalue &&
1245  match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0)
1246  break;
1247  prevBucketPtr = &(currBucket->link);
1248  currBucket = *prevBucketPtr;
1249 #ifdef HASH_STATISTICS
1250  hash_collisions++;
1251  hctl->collisions++;
1252 #endif
1253  }
1254 
1255  if (currBucket != NULL)
1256  return false; /* collision with an existing entry */
1257 
1258  currBucket = existingElement;
1259 
1260  /*
1261  * If old and new hash values belong to the same bucket, we need not
1262  * change any chain links, and indeed should not since this simplistic
1263  * update will corrupt the list if currBucket is the last element. (We
1264  * cannot fall out earlier, however, since we need to scan the bucket to
1265  * check for duplicate keys.)
1266  */
1267  if (bucket != newbucket)
1268  {
1269  /* OK to remove record from old hash bucket's chain. */
1270  *oldPrevPtr = currBucket->link;
1271 
1272  /* link into new hashbucket chain */
1273  *prevBucketPtr = currBucket;
1274  currBucket->link = NULL;
1275  }
1276 
1277  /* copy new key into record */
1278  currBucket->hashvalue = newhashvalue;
1279  hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize);
1280 
1281  /* rest of record is untouched */
1282 
1283  return true;
1284 }
#define ELEMENT_FROM_KEY(key)
Definition: dynahash.c:249

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().