PostgreSQL Source Code  git master
dynahash.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/xact.h"
#include "common/hashfn.h"
#include "port/pg_bitutils.h"
#include "storage/shmem.h"
#include "storage/spin.h"
#include "utils/dynahash.h"
#include "utils/memutils.h"
Include dependency graph for dynahash.c:

Go to the source code of this file.

Data Structures

struct  FreeListData
 
struct  HASHHDR
 
struct  HTAB
 

Macros

#define DEF_SEGSIZE   256
 
#define DEF_SEGSIZE_SHIFT   8 /* must be log2(DEF_SEGSIZE) */
 
#define DEF_DIRSIZE   256
 
#define NUM_FREELISTS   32
 
#define IS_PARTITIONED(hctl)   ((hctl)->num_partitions != 0)
 
#define FREELIST_IDX(hctl, hashcode)   (IS_PARTITIONED(hctl) ? (hashcode) % NUM_FREELISTS : 0)
 
#define ELEMENTKEY(helem)   (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT)))
 
#define ELEMENT_FROM_KEY(key)   ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT))))
 
#define MOD(x, y)   ((x) & ((y)-1))
 
#define MAX_SEQ_SCANS   100
 

Typedefs

typedef HASHELEMENTHASHBUCKET
 
typedef HASHBUCKETHASHSEGMENT
 

Functions

static void * DynaHashAlloc (Size size)
 
static HASHSEGMENT seg_alloc (HTAB *hashp)
 
static bool element_alloc (HTAB *hashp, int nelem, int freelist_idx)
 
static bool dir_realloc (HTAB *hashp)
 
static bool expand_table (HTAB *hashp)
 
static HASHBUCKET get_hash_entry (HTAB *hashp, int freelist_idx)
 
static void hdefault (HTAB *hashp)
 
static int choose_nelem_alloc (Size entrysize)
 
static bool init_htab (HTAB *hashp, long nelem)
 
static void hash_corrupted (HTAB *hashp)
 
static long next_pow2_long (long num)
 
static int next_pow2_int (long num)
 
static void register_seq_scan (HTAB *hashp)
 
static void deregister_seq_scan (HTAB *hashp)
 
static bool has_seq_scans (HTAB *hashp)
 
static int string_compare (const char *key1, const char *key2, Size keysize)
 
HTABhash_create (const char *tabname, long nelem, const HASHCTL *info, int flags)
 
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 hash_destroy (HTAB *hashp)
 
void hash_stats (const char *where, HTAB *hashp)
 
uint32 get_hash_value (HTAB *hashp, const void *keyPtr)
 
static uint32 calc_bucket (HASHHDR *hctl, uint32 hash_val)
 
void * hash_search (HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
 
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)
 
int my_log2 (long num)
 
void AtEOXact_HashTables (bool isCommit)
 
void AtEOSubXact_HashTables (bool isCommit, int nestDepth)
 

Variables

static MemoryContext CurrentDynaHashCxt = NULL
 
static HTABseq_scan_tables [MAX_SEQ_SCANS]
 
static int seq_scan_level [MAX_SEQ_SCANS]
 
static int num_seq_scans = 0
 

Macro Definition Documentation

◆ DEF_DIRSIZE

#define DEF_DIRSIZE   256

Definition at line 125 of file dynahash.c.

Referenced by hash_estimate_size(), hash_select_dirsize(), and hdefault().

◆ DEF_SEGSIZE

#define DEF_SEGSIZE   256

Definition at line 123 of file dynahash.c.

Referenced by hash_estimate_size(), hash_select_dirsize(), and hdefault().

◆ DEF_SEGSIZE_SHIFT

#define DEF_SEGSIZE_SHIFT   8 /* must be log2(DEF_SEGSIZE) */

Definition at line 124 of file dynahash.c.

Referenced by hdefault().

◆ ELEMENT_FROM_KEY

#define ELEMENT_FROM_KEY (   key)    ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT))))

Definition at line 249 of file dynahash.c.

Referenced by hash_update_hash_key().

◆ ELEMENTKEY

#define ELEMENTKEY (   helem)    (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT)))

Definition at line 244 of file dynahash.c.

Referenced by hash_search_with_hash_value(), hash_seq_search(), and hash_update_hash_key().

◆ FREELIST_IDX

#define FREELIST_IDX (   hctl,
  hashcode 
)    (IS_PARTITIONED(hctl) ? (hashcode) % NUM_FREELISTS : 0)

Definition at line 212 of file dynahash.c.

Referenced by hash_search_with_hash_value().

◆ IS_PARTITIONED

#define IS_PARTITIONED (   hctl)    ((hctl)->num_partitions != 0)

◆ MAX_SEQ_SCANS

#define MAX_SEQ_SCANS   100

Definition at line 1827 of file dynahash.c.

Referenced by register_seq_scan().

◆ MOD

#define MOD (   x,
 
)    ((x) & ((y)-1))

◆ NUM_FREELISTS

#define NUM_FREELISTS   32

Definition at line 128 of file dynahash.c.

Referenced by get_hash_entry(), hash_create(), hash_get_num_entries(), and init_htab().

Typedef Documentation

◆ HASHBUCKET

Definition at line 131 of file dynahash.c.

◆ HASHSEGMENT

Definition at line 134 of file dynahash.c.

Function Documentation

◆ AtEOSubXact_HashTables()

void AtEOSubXact_HashTables ( bool  isCommit,
int  nestDepth 
)

Definition at line 1909 of file dynahash.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

1910 {
1911  int i;
1912 
1913  /*
1914  * Search backward to make cleanup easy. Note we must check all entries,
1915  * not only those at the end of the array, because deletion technique
1916  * doesn't keep them in order.
1917  */
1918  for (i = num_seq_scans - 1; i >= 0; i--)
1919  {
1920  if (seq_scan_level[i] >= nestDepth)
1921  {
1922  if (isCommit)
1923  elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1924  seq_scan_tables[i]);
1927  num_seq_scans--;
1928  }
1929  }
1930 }
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1830
#define WARNING
Definition: elog.h:40
static int num_seq_scans
Definition: dynahash.c:1831
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1829
#define elog(elevel,...)
Definition: elog.h:232
int i

◆ AtEOXact_HashTables()

void AtEOXact_HashTables ( bool  isCommit)

Definition at line 1883 of file dynahash.c.

References elog, i, num_seq_scans, and WARNING.

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

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

◆ calc_bucket()

static uint32 calc_bucket ( HASHHDR hctl,
uint32  hash_val 
)
inlinestatic

Definition at line 915 of file dynahash.c.

References HASHHDR::high_mask, HASHHDR::low_mask, and HASHHDR::max_bucket.

Referenced by expand_table(), hash_search_with_hash_value(), and hash_update_hash_key().

916 {
917  uint32 bucket;
918 
919  bucket = hash_val & hctl->high_mask;
920  if (bucket > hctl->max_bucket)
921  bucket = bucket & hctl->low_mask;
922 
923  return bucket;
924 }
uint32 max_bucket
Definition: dynahash.c:186
uint32 low_mask
Definition: dynahash.c:188
unsigned int uint32
Definition: c.h:441
uint32 high_mask
Definition: dynahash.c:187

◆ choose_nelem_alloc()

static int choose_nelem_alloc ( Size  entrysize)
static

Definition at line 653 of file dynahash.c.

References MAXALIGN, and HASHHDR::nelem_alloc.

Referenced by hash_estimate_size(), and init_htab().

654 {
655  int nelem_alloc;
656  Size elementSize;
657  Size allocSize;
658 
659  /* Each element has a HASHELEMENT header plus user data. */
660  /* NB: this had better match element_alloc() */
661  elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(entrysize);
662 
663  /*
664  * The idea here is to choose nelem_alloc at least 32, but round up so
665  * that the allocation request will be a power of 2 or just less. This
666  * makes little difference for hash tables in shared memory, but for hash
667  * tables managed by palloc, the allocation request will be rounded up to
668  * a power of 2 anyway. If we fail to take this into account, we'll waste
669  * as much as half the allocated space.
670  */
671  allocSize = 32 * 4; /* assume elementSize at least 8 */
672  do
673  {
674  allocSize <<= 1;
675  nelem_alloc = allocSize / elementSize;
676  } while (nelem_alloc < 32);
677 
678  return nelem_alloc;
679 }
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757

◆ deregister_seq_scan()

static void deregister_seq_scan ( HTAB hashp)
static

Definition at line 1848 of file dynahash.c.

References elog, ERROR, i, num_seq_scans, seq_scan_level, and HTAB::tabname.

Referenced by hash_seq_term().

1849 {
1850  int i;
1851 
1852  /* Search backward since it's most likely at the stack top */
1853  for (i = num_seq_scans - 1; i >= 0; i--)
1854  {
1855  if (seq_scan_tables[i] == hashp)
1856  {
1859  num_seq_scans--;
1860  return;
1861  }
1862  }
1863  elog(ERROR, "no hash_seq_search scan for hash table \"%s\"",
1864  hashp->tabname);
1865 }
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1830
#define ERROR
Definition: elog.h:46
static int num_seq_scans
Definition: dynahash.c:1831
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1829
char * tabname
Definition: dynahash.c:228
#define elog(elevel,...)
Definition: elog.h:232
int i

◆ dir_realloc()

static bool dir_realloc ( HTAB hashp)
static

Definition at line 1646 of file dynahash.c.

References HTAB::alloc, Assert, HTAB::dir, HASHHDR::dsize, DynaHashAlloc(), HTAB::hctl, HTAB::hcxt, HASHHDR::max_dsize, MemSet, NO_MAX_DSIZE, and pfree().

Referenced by expand_table().

1647 {
1648  HASHSEGMENT *p;
1649  HASHSEGMENT *old_p;
1650  long new_dsize;
1651  long old_dirsize;
1652  long new_dirsize;
1653 
1654  if (hashp->hctl->max_dsize != NO_MAX_DSIZE)
1655  return false;
1656 
1657  /* Reallocate directory */
1658  new_dsize = hashp->hctl->dsize << 1;
1659  old_dirsize = hashp->hctl->dsize * sizeof(HASHSEGMENT);
1660  new_dirsize = new_dsize * sizeof(HASHSEGMENT);
1661 
1662  old_p = hashp->dir;
1663  CurrentDynaHashCxt = hashp->hcxt;
1664  p = (HASHSEGMENT *) hashp->alloc((Size) new_dirsize);
1665 
1666  if (p != NULL)
1667  {
1668  memcpy(p, old_p, old_dirsize);
1669  MemSet(((char *) p) + old_dirsize, 0, new_dirsize - old_dirsize);
1670  hashp->dir = p;
1671  hashp->hctl->dsize = new_dsize;
1672 
1673  /* XXX assume the allocator is palloc, so we know how to free */
1674  Assert(hashp->alloc == DynaHashAlloc);
1675  pfree(old_p);
1676 
1677  return true;
1678  }
1679 
1680  return false;
1681 }
long dsize
Definition: dynahash.c:184
#define NO_MAX_DSIZE
Definition: hsearch.h:108
HashAllocFunc alloc
Definition: dynahash.c:226
#define MemSet(start, val, len)
Definition: c.h:1008
void pfree(void *pointer)
Definition: mcxt.c:1169
HASHBUCKET * HASHSEGMENT
Definition: dynahash.c:134
long max_dsize
Definition: dynahash.c:194
HASHHDR * hctl
Definition: dynahash.c:221
MemoryContext hcxt
Definition: dynahash.c:227
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
static void * DynaHashAlloc(Size size)
Definition: dynahash.c:289
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286
HASHSEGMENT * dir
Definition: dynahash.c:222

◆ DynaHashAlloc()

static void * DynaHashAlloc ( Size  size)
static

Definition at line 289 of file dynahash.c.

References Assert, MemoryContextAlloc(), and MemoryContextIsValid.

Referenced by dir_realloc(), hash_create(), hash_destroy(), and hash_search_with_hash_value().

290 {
293 }
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
#define Assert(condition)
Definition: c.h:804
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286

◆ element_alloc()

static bool element_alloc ( HTAB hashp,
int  nelem,
int  freelist_idx 
)
static

Definition at line 1704 of file dynahash.c.

References HTAB::alloc, HASHHDR::entrysize, FreeListData::freeList, HASHHDR::freeList, HTAB::hctl, HTAB::hcxt, i, IS_PARTITIONED, HTAB::isfixed, HASHELEMENT::link, MAXALIGN, FreeListData::mutex, SpinLockAcquire, and SpinLockRelease.

Referenced by get_hash_entry(), and hash_create().

1705 {
1706  HASHHDR *hctl = hashp->hctl;
1707  Size elementSize;
1708  HASHELEMENT *firstElement;
1709  HASHELEMENT *tmpElement;
1710  HASHELEMENT *prevElement;
1711  int i;
1712 
1713  if (hashp->isfixed)
1714  return false;
1715 
1716  /* Each element has a HASHELEMENT header plus user data. */
1717  elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(hctl->entrysize);
1718 
1719  CurrentDynaHashCxt = hashp->hcxt;
1720  firstElement = (HASHELEMENT *) hashp->alloc(nelem * elementSize);
1721 
1722  if (!firstElement)
1723  return false;
1724 
1725  /* prepare to link all the new entries into the freelist */
1726  prevElement = NULL;
1727  tmpElement = firstElement;
1728  for (i = 0; i < nelem; i++)
1729  {
1730  tmpElement->link = prevElement;
1731  prevElement = tmpElement;
1732  tmpElement = (HASHELEMENT *) (((char *) tmpElement) + elementSize);
1733  }
1734 
1735  /* if partitioned, must lock to touch freeList */
1736  if (IS_PARTITIONED(hctl))
1737  SpinLockAcquire(&hctl->freeList[freelist_idx].mutex);
1738 
1739  /* freelist could be nonempty if two backends did this concurrently */
1740  firstElement->link = hctl->freeList[freelist_idx].freeList;
1741  hctl->freeList[freelist_idx].freeList = prevElement;
1742 
1743  if (IS_PARTITIONED(hctl))
1744  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1745 
1746  return true;
1747 }
Size entrysize
Definition: dynahash.c:192
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:210
HashAllocFunc alloc
Definition: dynahash.c:226
slock_t mutex
Definition: dynahash.c:155
#define SpinLockAcquire(lock)
Definition: spin.h:62
HASHHDR * hctl
Definition: dynahash.c:221
#define SpinLockRelease(lock)
Definition: spin.h:64
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:180
MemoryContext hcxt
Definition: dynahash.c:227
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
bool isfixed
Definition: dynahash.c:230
struct HASHELEMENT * link
Definition: hsearch.h:53
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286
int i
HASHELEMENT * freeList
Definition: dynahash.c:157

◆ expand_table()

static bool expand_table ( HTAB hashp)
static

Definition at line 1549 of file dynahash.c.

References Assert, calc_bucket(), HTAB::dir, dir_realloc(), HASHHDR::dsize, HASHELEMENT::hashvalue, HTAB::hctl, HASHHDR::high_mask, IS_PARTITIONED, HASHELEMENT::link, HASHHDR::low_mask, HASHHDR::max_bucket, MOD, HASHHDR::nsegs, seg_alloc(), HTAB::sshift, and HTAB::ssize.

Referenced by hash_search_with_hash_value().

1550 {
1551  HASHHDR *hctl = hashp->hctl;
1552  HASHSEGMENT old_seg,
1553  new_seg;
1554  long old_bucket,
1555  new_bucket;
1556  long new_segnum,
1557  new_segndx;
1558  long old_segnum,
1559  old_segndx;
1560  HASHBUCKET *oldlink,
1561  *newlink;
1562  HASHBUCKET currElement,
1563  nextElement;
1564 
1565  Assert(!IS_PARTITIONED(hctl));
1566 
1567 #ifdef HASH_STATISTICS
1568  hash_expansions++;
1569 #endif
1570 
1571  new_bucket = hctl->max_bucket + 1;
1572  new_segnum = new_bucket >> hashp->sshift;
1573  new_segndx = MOD(new_bucket, hashp->ssize);
1574 
1575  if (new_segnum >= hctl->nsegs)
1576  {
1577  /* Allocate new segment if necessary -- could fail if dir full */
1578  if (new_segnum >= hctl->dsize)
1579  if (!dir_realloc(hashp))
1580  return false;
1581  if (!(hashp->dir[new_segnum] = seg_alloc(hashp)))
1582  return false;
1583  hctl->nsegs++;
1584  }
1585 
1586  /* OK, we created a new bucket */
1587  hctl->max_bucket++;
1588 
1589  /*
1590  * *Before* changing masks, find old bucket corresponding to same hash
1591  * values; values in that bucket may need to be relocated to new bucket.
1592  * Note that new_bucket is certainly larger than low_mask at this point,
1593  * so we can skip the first step of the regular hash mask calc.
1594  */
1595  old_bucket = (new_bucket & hctl->low_mask);
1596 
1597  /*
1598  * If we crossed a power of 2, readjust masks.
1599  */
1600  if ((uint32) new_bucket > hctl->high_mask)
1601  {
1602  hctl->low_mask = hctl->high_mask;
1603  hctl->high_mask = (uint32) new_bucket | hctl->low_mask;
1604  }
1605 
1606  /*
1607  * Relocate records to the new bucket. NOTE: because of the way the hash
1608  * masking is done in calc_bucket, only one old bucket can need to be
1609  * split at this point. With a different way of reducing the hash value,
1610  * that might not be true!
1611  */
1612  old_segnum = old_bucket >> hashp->sshift;
1613  old_segndx = MOD(old_bucket, hashp->ssize);
1614 
1615  old_seg = hashp->dir[old_segnum];
1616  new_seg = hashp->dir[new_segnum];
1617 
1618  oldlink = &old_seg[old_segndx];
1619  newlink = &new_seg[new_segndx];
1620 
1621  for (currElement = *oldlink;
1622  currElement != NULL;
1623  currElement = nextElement)
1624  {
1625  nextElement = currElement->link;
1626  if ((long) calc_bucket(hctl, currElement->hashvalue) == old_bucket)
1627  {
1628  *oldlink = currElement;
1629  oldlink = &currElement->link;
1630  }
1631  else
1632  {
1633  *newlink = currElement;
1634  newlink = &currElement->link;
1635  }
1636  }
1637  /* don't forget to terminate the rebuilt hash chains... */
1638  *oldlink = NULL;
1639  *newlink = NULL;
1640 
1641  return true;
1642 }
long dsize
Definition: dynahash.c:184
uint32 max_bucket
Definition: dynahash.c:186
static uint32 calc_bucket(HASHHDR *hctl, uint32 hash_val)
Definition: dynahash.c:915
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:210
uint32 low_mask
Definition: dynahash.c:188
long ssize
Definition: dynahash.c:237
int sshift
Definition: dynahash.c:238
#define MOD(x, y)
Definition: dynahash.c:255
HASHHDR * hctl
Definition: dynahash.c:221
unsigned int uint32
Definition: c.h:441
uint32 high_mask
Definition: dynahash.c:187
#define Assert(condition)
Definition: c.h:804
static HASHSEGMENT seg_alloc(HTAB *hashp)
Definition: dynahash.c:1685
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHSEGMENT * dir
Definition: dynahash.c:222
static bool dir_realloc(HTAB *hashp)
Definition: dynahash.c:1646
uint32 hashvalue
Definition: hsearch.h:54
long nsegs
Definition: dynahash.c:185

◆ get_hash_entry()

static HASHBUCKET get_hash_entry ( HTAB hashp,
int  freelist_idx 
)
static

Definition at line 1297 of file dynahash.c.

References element_alloc(), FreeListData::freeList, HASHHDR::freeList, HTAB::hctl, IS_PARTITIONED, HASHELEMENT::link, FreeListData::mutex, HASHHDR::nelem_alloc, FreeListData::nentries, NUM_FREELISTS, SpinLockAcquire, and SpinLockRelease.

Referenced by hash_search_with_hash_value().

1298 {
1299  HASHHDR *hctl = hashp->hctl;
1300  HASHBUCKET newElement;
1301 
1302  for (;;)
1303  {
1304  /* if partitioned, must lock to touch nentries and freeList */
1305  if (IS_PARTITIONED(hctl))
1306  SpinLockAcquire(&hctl->freeList[freelist_idx].mutex);
1307 
1308  /* try to get an entry from the freelist */
1309  newElement = hctl->freeList[freelist_idx].freeList;
1310 
1311  if (newElement != NULL)
1312  break;
1313 
1314  if (IS_PARTITIONED(hctl))
1315  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1316 
1317  /*
1318  * No free elements in this freelist. In a partitioned table, there
1319  * might be entries in other freelists, but to reduce contention we
1320  * prefer to first try to get another chunk of buckets from the main
1321  * shmem allocator. If that fails, though, we *MUST* root through all
1322  * the other freelists before giving up. There are multiple callers
1323  * that assume that they can allocate every element in the initially
1324  * requested table size, or that deleting an element guarantees they
1325  * can insert a new element, even if shared memory is entirely full.
1326  * Failing because the needed element is in a different freelist is
1327  * not acceptable.
1328  */
1329  if (!element_alloc(hashp, hctl->nelem_alloc, freelist_idx))
1330  {
1331  int borrow_from_idx;
1332 
1333  if (!IS_PARTITIONED(hctl))
1334  return NULL; /* out of memory */
1335 
1336  /* try to borrow element from another freelist */
1337  borrow_from_idx = freelist_idx;
1338  for (;;)
1339  {
1340  borrow_from_idx = (borrow_from_idx + 1) % NUM_FREELISTS;
1341  if (borrow_from_idx == freelist_idx)
1342  break; /* examined all freelists, fail */
1343 
1344  SpinLockAcquire(&(hctl->freeList[borrow_from_idx].mutex));
1345  newElement = hctl->freeList[borrow_from_idx].freeList;
1346 
1347  if (newElement != NULL)
1348  {
1349  hctl->freeList[borrow_from_idx].freeList = newElement->link;
1350  SpinLockRelease(&(hctl->freeList[borrow_from_idx].mutex));
1351 
1352  /* careful: count the new element in its proper freelist */
1353  SpinLockAcquire(&hctl->freeList[freelist_idx].mutex);
1354  hctl->freeList[freelist_idx].nentries++;
1355  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1356 
1357  return newElement;
1358  }
1359 
1360  SpinLockRelease(&(hctl->freeList[borrow_from_idx].mutex));
1361  }
1362 
1363  /* no elements available to borrow either, so out of memory */
1364  return NULL;
1365  }
1366  }
1367 
1368  /* remove entry from freelist, bump nentries */
1369  hctl->freeList[freelist_idx].freeList = newElement->link;
1370  hctl->freeList[freelist_idx].nentries++;
1371 
1372  if (IS_PARTITIONED(hctl))
1373  SpinLockRelease(&hctl->freeList[freelist_idx].mutex);
1374 
1375  return newElement;
1376 }
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:210
#define NUM_FREELISTS
Definition: dynahash.c:128
slock_t mutex
Definition: dynahash.c:155
#define SpinLockAcquire(lock)
Definition: spin.h:62
HASHHDR * hctl
Definition: dynahash.c:221
long nentries
Definition: dynahash.c:156
#define SpinLockRelease(lock)
Definition: spin.h:64
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:180
int nelem_alloc
Definition: dynahash.c:197
struct HASHELEMENT * link
Definition: hsearch.h:53
HASHELEMENT * freeList
Definition: dynahash.c:157
static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx)
Definition: dynahash.c:1704

◆ get_hash_value()

uint32 get_hash_value ( HTAB hashp,
const void *  keyPtr 
)

Definition at line 908 of file dynahash.c.

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

Referenced by BufTableHashCode(), and LockTagHashCode().

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

◆ has_seq_scans()

static bool has_seq_scans ( HTAB hashp)
static

Definition at line 1869 of file dynahash.c.

References i, and num_seq_scans.

Referenced by hash_freeze(), and hash_search_with_hash_value().

1870 {
1871  int i;
1872 
1873  for (i = 0; i < num_seq_scans; i++)
1874  {
1875  if (seq_scan_tables[i] == hashp)
1876  return true;
1877  }
1878  return false;
1879 }
static int num_seq_scans
Definition: dynahash.c:1831
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1829
int i

◆ hash_corrupted()

static void hash_corrupted ( HTAB hashp)
static

Definition at line 1751 of file dynahash.c.

References elog, FATAL, HTAB::isshared, PANIC, and HTAB::tabname.

Referenced by hash_search_with_hash_value(), and hash_update_hash_key().

1752 {
1753  /*
1754  * If the corruption is in a shared hashtable, we'd better force a
1755  * systemwide restart. Otherwise, just shut down this one backend.
1756  */
1757  if (hashp->isshared)
1758  elog(PANIC, "hash table \"%s\" corrupted", hashp->tabname);
1759  else
1760  elog(FATAL, "hash table \"%s\" corrupted", hashp->tabname);
1761 }
#define PANIC
Definition: elog.h:50
#define FATAL
Definition: elog.h:49
bool isshared
Definition: dynahash.c:229
char * tabname
Definition: dynahash.c:228
#define elog(elevel,...)
Definition: elog.h:232

◆ hash_create()

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

Definition at line 349 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, HTAB::frozen, HASHCTL::hash, HTAB::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, 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, MemoryContextSetIdentifier(), MemSet, my_log2(), HASHHDR::nelem_alloc, 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(), AddEventToPendingNotifies(), AddPendingSync(), apply_handle_stream_start(), assign_record_type_typmod(), begin_heap_rewrite(), build_join_rel_hash(), BuildEventTriggerCache(), 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(), get_tabstat_entry(), GetComboCommandId(), GetConnection(), gistInitBuildBuffers(), gistInitParentMap(), init_procedure_caches(), init_rel_sync_cache(), init_timezone_hashtable(), init_ts_config_cache(), init_uncommitted_enums(), InitBufferPoolAccess(), InitializeAttoptCache(), InitializeRelfilenodeMap(), InitializeShippableCache(), InitializeTableSpaceCache(), InitLocalBuffers(), InitLocks(), InitQueryHashTable(), InitRecoveryTransactionEnvironment(), InitSync(), 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(), 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(), SerializePendingSyncs(), set_rtable_names(), ShmemInitHash(), smgropen(), transformGraph(), and XLogPrefetcherAllocate().

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

◆ hash_destroy()

void hash_destroy ( HTAB hashp)

Definition at line 862 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(), EnableSyncRequestForwarding(), ExecuteTruncateGuts(), 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(), ReleasePredicateLocksLocal(), ReorderBufferReturnTXN(), ReorderBufferToastReset(), ReorderBufferTruncateTXN(), ResetSequenceCaches(), ResetUnloggedRelationsInDbspaceDir(), SerializePendingSyncs(), set_rtable_names(), ShutdownRecoveryTransactionEnvironment(), XLogCheckInvalidPages(), and XLogPrefetcherFree().

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

◆ hash_estimate_size()

Size hash_estimate_size ( long  num_entries,
Size  entrysize 
)

Definition at line 780 of file dynahash.c.

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

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

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

◆ hash_freeze()

void hash_freeze ( HTAB hashp)

Definition at line 1532 of file dynahash.c.

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

1533 {
1534  if (hashp->isshared)
1535  elog(ERROR, "cannot freeze shared hashtable \"%s\"", hashp->tabname);
1536  if (!hashp->frozen && has_seq_scans(hashp))
1537  elog(ERROR, "cannot freeze hashtable \"%s\" because it has active scans",
1538  hashp->tabname);
1539  hashp->frozen = true;
1540 }
#define ERROR
Definition: elog.h:46
static bool has_seq_scans(HTAB *hashp)
Definition: dynahash.c:1869
bool isshared
Definition: dynahash.c:229
bool frozen
Definition: dynahash.c:233
char * tabname
Definition: dynahash.c:228
#define elog(elevel,...)
Definition: elog.h:232

◆ hash_get_num_entries()

long hash_get_num_entries ( HTAB hashp)

Definition at line 1382 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(), entry_reset(), EstimatePendingSyncsSpace(), EstimateUncommittedEnumsSpace(), get_crosstab_tuplestore(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), hash_stats(), pgss_shmem_shutdown(), pgstat_vacuum_stat(), ResetUnloggedRelationsInDbspaceDir(), SerializePendingSyncs(), transformGraph(), and XLogHaveInvalidPages().

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

◆ hash_get_shared_size()

Size hash_get_shared_size ( HASHCTL info,
int  flags 
)

Definition at line 851 of file dynahash.c.

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

Referenced by ShmemInitHash().

852 {
853  Assert(flags & HASH_DIRSIZE);
854  Assert(info->dsize == info->max_dsize);
855  return sizeof(HASHHDR) + info->dsize * sizeof(HASHSEGMENT);
856 }
long dsize
Definition: hsearch.h:72
long max_dsize
Definition: hsearch.h:73
struct HASHHDR HASHHDR
Definition: hsearch.h:58
#define Assert(condition)
Definition: c.h:804
#define HASH_DIRSIZE
Definition: hsearch.h:94

◆ hash_search()

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

Definition at line 954 of file dynahash.c.

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

Referenced by _hash_finish_split(), _hash_splitbucket(), add_join_rel(), AddEnumLabel(), AddEventToPendingNotifies(), AddPendingSync(), apply_handle_stream_abort(), apply_handle_stream_commit(), ApplyLogicalMappingFile(), assign_record_type_typmod(), AsyncExistsPendingNotify(), 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(), EnumUncommitted(), EventCacheLookup(), ExecInitModifyTable(), ExecLookupResultRelByOid(), ExecuteTruncateGuts(), 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(), LockAcquireExtended(), LockHasWaiters(), LockHeldByMe(), LockRelease(), log_invalid_page(), logical_rewrite_log_mapping(), logicalrep_partition_open(), logicalrep_rel_open(), logicalrep_relmap_update(), logicalrep_typmap_gettypname(), 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(), PartitionDirectoryLookup(), 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(), 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(), RelfilenodeMapInvalidateCallback(), RelFileNodeSkippingWAL(), RelidByRelfilenode(), 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(), smgrclosenode(), smgrDoPendingSyncs(), smgropen(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), StandbyReleaseLocks(), StandbyReleaseOldLocks(), StorePreparedStatement(), stream_cleanup_files(), stream_open_file(), subxact_info_read(), subxact_info_write(), table_recheck_autovac(), XLogPrefetcherAddFilter(), XLogPrefetcherCompleteFilters(), and XLogPrefetcherIsFiltered().

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

◆ 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 967 of file dynahash.c.

References HTAB::alloc, Assert, calc_bucket(), HTAB::dir, DynaHashAlloc(), 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, HASHHDR::keysize, 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().

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

◆ hash_select_dirsize()

long hash_select_dirsize ( long  num_entries)

Definition at line 827 of file dynahash.c.

References DEF_DIRSIZE, DEF_SEGSIZE, and next_pow2_long().

Referenced by ShmemInitHash().

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

◆ hash_seq_init()

void hash_seq_init ( HASH_SEQ_STATUS status,
HTAB hashp 
)

Definition at line 1426 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(), 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(), gc_qtexts(), GetLockmodeName(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), HoldPinnedPortals(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_relmap_invalidate_cb(), packArcInfoCmp(), 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(), pgstat_send_funcstats(), pgstat_vacuum_stat(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections(), PostPrepare_Locks(), PreCommit_Portals(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenodeMapInvalidateCallback(), RememberSyncRequest(), RememberToFreeTupleDescAtEOX(), ReorderBufferLargestTXN(), ReorderBufferToastReset(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrcloseall(), smgrDoPendingSyncs(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

1427 {
1428  status->hashp = hashp;
1429  status->curBucket = 0;
1430  status->curEntry = NULL;
1431  if (!hashp->frozen)
1432  register_seq_scan(hashp);
1433 }
uint32 curBucket
Definition: hsearch.h:123
HASHELEMENT * curEntry
Definition: hsearch.h:124
HTAB * hashp
Definition: hsearch.h:122
bool frozen
Definition: dynahash.c:233
static void register_seq_scan(HTAB *hashp)
Definition: dynahash.c:1836

◆ hash_seq_search()

void* hash_seq_search ( HASH_SEQ_STATUS status)

Definition at line 1436 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, HASHHDR::ssize, and HTAB::ssize.

Referenced by AtAbort_Portals(), AtCleanup_Portals(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AtPrepare_Locks(), AtSubAbort_Portals(), AtSubCleanup_Portals(), AtSubCommit_Portals(), CheckForBufferLeaks(), 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(), gc_qtexts(), GetLockmodeName(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), HoldPinnedPortals(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_relmap_invalidate_cb(), packArcInfoCmp(), 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(), pgstat_send_funcstats(), pgstat_vacuum_stat(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections(), PostPrepare_Locks(), PreCommit_Portals(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenodeMapInvalidateCallback(), RememberSyncRequest(), RememberToFreeTupleDescAtEOX(), ReorderBufferLargestTXN(), ReorderBufferToastReset(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrcloseall(), smgrDoPendingSyncs(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

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

◆ hash_seq_term()

void hash_seq_term ( HASH_SEQ_STATUS status)

◆ hash_stats()

void hash_stats ( const char *  where,
HTAB hashp 
)

Definition at line 881 of file dynahash.c.

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

Referenced by hash_destroy().

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

◆ hash_update_hash_key()

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

Definition at line 1162 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, HASHHDR::keysize, HTAB::keysize, HASHELEMENT::link, HTAB::match, MOD, HTAB::sshift, HTAB::ssize, and HTAB::tabname.

Referenced by PostPrepare_Locks().

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

◆ hdefault()

static void hdefault ( HTAB hashp)
static

Definition at line 626 of file dynahash.c.

References DEF_DIRSIZE, DEF_SEGSIZE, DEF_SEGSIZE_SHIFT, HASHHDR::dsize, HTAB::hctl, HASHHDR::max_dsize, MemSet, NO_MAX_DSIZE, HASHHDR::nsegs, HASHHDR::num_partitions, HASHHDR::sshift, and HASHHDR::ssize.

Referenced by hash_create().

627 {
628  HASHHDR *hctl = hashp->hctl;
629 
630  MemSet(hctl, 0, sizeof(HASHHDR));
631 
632  hctl->dsize = DEF_DIRSIZE;
633  hctl->nsegs = 0;
634 
635  hctl->num_partitions = 0; /* not partitioned */
636 
637  /* table has no fixed maximum size */
638  hctl->max_dsize = NO_MAX_DSIZE;
639 
640  hctl->ssize = DEF_SEGSIZE;
641  hctl->sshift = DEF_SEGSIZE_SHIFT;
642 
643 #ifdef HASH_STATISTICS
644  hctl->accesses = hctl->collisions = 0;
645 #endif
646 }
long dsize
Definition: dynahash.c:184
#define NO_MAX_DSIZE
Definition: hsearch.h:108
long num_partitions
Definition: dynahash.c:193
#define MemSet(start, val, len)
Definition: c.h:1008
#define DEF_SEGSIZE_SHIFT
Definition: dynahash.c:124
long max_dsize
Definition: dynahash.c:194
HASHHDR * hctl
Definition: dynahash.c:221
long ssize
Definition: dynahash.c:195
int sshift
Definition: dynahash.c:196
#define DEF_SEGSIZE
Definition: dynahash.c:123
#define DEF_DIRSIZE
Definition: dynahash.c:125
long nsegs
Definition: dynahash.c:185

◆ init_htab()

static bool init_htab ( HTAB hashp,
long  nelem 
)
static

Definition at line 686 of file dynahash.c.

References HTAB::alloc, choose_nelem_alloc(), HTAB::dir, HASHHDR::dsize, HASHHDR::entrysize, fprintf, HASHHDR::freeList, HTAB::hctl, HTAB::hcxt, HASHHDR::high_mask, i, IS_PARTITIONED, HASHHDR::low_mask, HASHHDR::max_bucket, FreeListData::mutex, HASHHDR::nelem_alloc, next_pow2_int(), HASHHDR::nsegs, NUM_FREELISTS, HASHHDR::num_partitions, seg_alloc(), SpinLockInit, HASHHDR::sshift, and HASHHDR::ssize.

Referenced by hash_create().

687 {
688  HASHHDR *hctl = hashp->hctl;
689  HASHSEGMENT *segp;
690  int nbuckets;
691  int nsegs;
692  int i;
693 
694  /*
695  * initialize mutexes if it's a partitioned table
696  */
697  if (IS_PARTITIONED(hctl))
698  for (i = 0; i < NUM_FREELISTS; i++)
699  SpinLockInit(&(hctl->freeList[i].mutex));
700 
701  /*
702  * Allocate space for the next greater power of two number of buckets,
703  * assuming a desired maximum load factor of 1.
704  */
705  nbuckets = next_pow2_int(nelem);
706 
707  /*
708  * In a partitioned table, nbuckets must be at least equal to
709  * num_partitions; were it less, keys with apparently different partition
710  * numbers would map to the same bucket, breaking partition independence.
711  * (Normally nbuckets will be much bigger; this is just a safety check.)
712  */
713  while (nbuckets < hctl->num_partitions)
714  nbuckets <<= 1;
715 
716  hctl->max_bucket = hctl->low_mask = nbuckets - 1;
717  hctl->high_mask = (nbuckets << 1) - 1;
718 
719  /*
720  * Figure number of directory segments needed, round up to a power of 2
721  */
722  nsegs = (nbuckets - 1) / hctl->ssize + 1;
723  nsegs = next_pow2_int(nsegs);
724 
725  /*
726  * Make sure directory is big enough. If pre-allocated directory is too
727  * small, choke (caller screwed up).
728  */
729  if (nsegs > hctl->dsize)
730  {
731  if (!(hashp->dir))
732  hctl->dsize = nsegs;
733  else
734  return false;
735  }
736 
737  /* Allocate a directory */
738  if (!(hashp->dir))
739  {
740  CurrentDynaHashCxt = hashp->hcxt;
741  hashp->dir = (HASHSEGMENT *)
742  hashp->alloc(hctl->dsize * sizeof(HASHSEGMENT));
743  if (!hashp->dir)
744  return false;
745  }
746 
747  /* Allocate initial segments */
748  for (segp = hashp->dir; hctl->nsegs < nsegs; hctl->nsegs++, segp++)
749  {
750  *segp = seg_alloc(hashp);
751  if (*segp == NULL)
752  return false;
753  }
754 
755  /* Choose number of entries to allocate at a time */
757 
758 #ifdef HASH_DEBUG
759  fprintf(stderr, "init_htab:\n%s%p\n%s%ld\n%s%ld\n%s%d\n%s%ld\n%s%u\n%s%x\n%s%x\n%s%ld\n",
760  "TABLE POINTER ", hashp,
761  "DIRECTORY SIZE ", hctl->dsize,
762  "SEGMENT SIZE ", hctl->ssize,
763  "SEGMENT SHIFT ", hctl->sshift,
764  "MAX BUCKET ", hctl->max_bucket,
765  "HIGH MASK ", hctl->high_mask,
766  "LOW MASK ", hctl->low_mask,
767  "NSEGS ", hctl->nsegs);
768 #endif
769  return true;
770 }
long dsize
Definition: dynahash.c:184
uint32 max_bucket
Definition: dynahash.c:186
Size entrysize
Definition: dynahash.c:192
#define IS_PARTITIONED(hctl)
Definition: dynahash.c:210
#define SpinLockInit(lock)
Definition: spin.h:60
#define NUM_FREELISTS
Definition: dynahash.c:128
HashAllocFunc alloc
Definition: dynahash.c:226
slock_t mutex
Definition: dynahash.c:155
uint32 low_mask
Definition: dynahash.c:188
#define fprintf
Definition: port.h:220
HASHHDR * hctl
Definition: dynahash.c:221
uint32 high_mask
Definition: dynahash.c:187
static int next_pow2_int(long num)
Definition: dynahash.c:1791
long ssize
Definition: dynahash.c:195
FreeListData freeList[NUM_FREELISTS]
Definition: dynahash.c:180
MemoryContext hcxt
Definition: dynahash.c:227
int nelem_alloc
Definition: dynahash.c:197
static HASHSEGMENT seg_alloc(HTAB *hashp)
Definition: dynahash.c:1685
static int choose_nelem_alloc(Size entrysize)
Definition: dynahash.c:653
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286
int i
HASHSEGMENT * dir
Definition: dynahash.c:222
int sshift
Definition: dynahash.c:196
long nsegs
Definition: dynahash.c:185

◆ my_log2()

int my_log2 ( long  num)

Definition at line 1765 of file dynahash.c.

References pg_ceil_log2_32(), and pg_ceil_log2_64().

Referenced by ExecChooseHashTableSize(), ExecHashTableCreate(), ExecParallelHashIncreaseNumBatches(), ExecParallelHashTableSetCurrentBatch(), hash_choose_num_partitions(), hash_create(), MultiExecParallelHash(), next_pow2_int(), next_pow2_long(), and subxact_info_read().

1766 {
1767  /*
1768  * guard against too-large input, which would be invalid for
1769  * pg_ceil_log2_*()
1770  */
1771  if (num > LONG_MAX / 2)
1772  num = LONG_MAX / 2;
1773 
1774 #if SIZEOF_LONG < 8
1775  return pg_ceil_log2_32(num);
1776 #else
1777  return pg_ceil_log2_64(num);
1778 #endif
1779 }
static uint64 pg_ceil_log2_64(uint64 num)
Definition: pg_bitutils.h:202
static uint32 pg_ceil_log2_32(uint32 num)
Definition: pg_bitutils.h:189

◆ next_pow2_int()

static int next_pow2_int ( long  num)
static

Definition at line 1791 of file dynahash.c.

References my_log2().

Referenced by hash_create(), and init_htab().

1792 {
1793  if (num > INT_MAX / 2)
1794  num = INT_MAX / 2;
1795  return 1 << my_log2(num);
1796 }
int my_log2(long num)
Definition: dynahash.c:1765

◆ next_pow2_long()

static long next_pow2_long ( long  num)
static

Definition at line 1783 of file dynahash.c.

References my_log2().

Referenced by hash_estimate_size(), and hash_select_dirsize().

1784 {
1785  /* my_log2's internal range check is sufficient */
1786  return 1L << my_log2(num);
1787 }
int my_log2(long num)
Definition: dynahash.c:1765

◆ register_seq_scan()

static void register_seq_scan ( HTAB hashp)
static

Definition at line 1836 of file dynahash.c.

References elog, ERROR, GetCurrentTransactionNestLevel(), MAX_SEQ_SCANS, num_seq_scans, seq_scan_level, and HTAB::tabname.

Referenced by hash_seq_init().

1837 {
1839  elog(ERROR, "too many active hash_seq_search scans, cannot start one on \"%s\"",
1840  hashp->tabname);
1841  seq_scan_tables[num_seq_scans] = hashp;
1843  num_seq_scans++;
1844 }
static int seq_scan_level[MAX_SEQ_SCANS]
Definition: dynahash.c:1830
#define ERROR
Definition: elog.h:46
#define MAX_SEQ_SCANS
Definition: dynahash.c:1827
static int num_seq_scans
Definition: dynahash.c:1831
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition: dynahash.c:1829
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
char * tabname
Definition: dynahash.c:228
#define elog(elevel,...)
Definition: elog.h:232

◆ seg_alloc()

static HASHSEGMENT seg_alloc ( HTAB hashp)
static

Definition at line 1685 of file dynahash.c.

References HTAB::alloc, HTAB::hcxt, MemSet, and HTAB::ssize.

Referenced by expand_table(), and init_htab().

1686 {
1687  HASHSEGMENT segp;
1688 
1689  CurrentDynaHashCxt = hashp->hcxt;
1690  segp = (HASHSEGMENT) hashp->alloc(sizeof(HASHBUCKET) * hashp->ssize);
1691 
1692  if (!segp)
1693  return NULL;
1694 
1695  MemSet(segp, 0, sizeof(HASHBUCKET) * hashp->ssize);
1696 
1697  return segp;
1698 }
HashAllocFunc alloc
Definition: dynahash.c:226
#define MemSet(start, val, len)
Definition: c.h:1008
HASHBUCKET * HASHSEGMENT
Definition: dynahash.c:134
long ssize
Definition: dynahash.c:237
MemoryContext hcxt
Definition: dynahash.c:227
static MemoryContext CurrentDynaHashCxt
Definition: dynahash.c:286

◆ string_compare()

static int string_compare ( const char *  key1,
const char *  key2,
Size  keysize 
)
static

Definition at line 304 of file dynahash.c.

Referenced by hash_create().

305 {
306  return strncmp(key1, key2, keysize - 1);
307 }

Variable Documentation

◆ CurrentDynaHashCxt

MemoryContext CurrentDynaHashCxt = NULL
static

Definition at line 286 of file dynahash.c.

Referenced by hash_create().

◆ num_seq_scans

int num_seq_scans = 0
static

◆ seq_scan_level

int seq_scan_level[MAX_SEQ_SCANS]
static

Definition at line 1830 of file dynahash.c.

Referenced by AtEOSubXact_HashTables(), deregister_seq_scan(), and register_seq_scan().

◆ seq_scan_tables

HTAB* seq_scan_tables[MAX_SEQ_SCANS]
static

Definition at line 1829 of file dynahash.c.