PostgreSQL Source Code  git master
nodeHash.c File Reference
#include "postgres.h"
#include <math.h>
#include <limits.h>
#include "access/htup_details.h"
#include "access/parallel.h"
#include "catalog/pg_statistic.h"
#include "commands/tablespace.h"
#include "executor/executor.h"
#include "executor/hashjoin.h"
#include "executor/nodeHash.h"
#include "executor/nodeHashjoin.h"
#include "miscadmin.h"
#include "port/atomics.h"
#include "port/pg_bitutils.h"
#include "utils/dynahash.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/wait_event.h"
Include dependency graph for nodeHash.c:

Go to the source code of this file.

Macros

#define NTUP_PER_BUCKET   1
 

Functions

static void ExecHashIncreaseNumBatches (HashJoinTable hashtable)
 
static void ExecHashIncreaseNumBuckets (HashJoinTable hashtable)
 
static void ExecParallelHashIncreaseNumBatches (HashJoinTable hashtable)
 
static void ExecParallelHashIncreaseNumBuckets (HashJoinTable hashtable)
 
static void ExecHashBuildSkewHash (HashState *hashstate, HashJoinTable hashtable, Hash *node, int mcvsToUse)
 
static void ExecHashSkewTableInsert (HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue, int bucketNumber)
 
static void ExecHashRemoveNextSkewBucket (HashJoinTable hashtable)
 
static void * dense_alloc (HashJoinTable hashtable, Size size)
 
static HashJoinTuple ExecParallelHashTupleAlloc (HashJoinTable hashtable, size_t size, dsa_pointer *shared)
 
static void MultiExecPrivateHash (HashState *node)
 
static void MultiExecParallelHash (HashState *node)
 
static HashJoinTuple ExecParallelHashFirstTuple (HashJoinTable hashtable, int bucketno)
 
static HashJoinTuple ExecParallelHashNextTuple (HashJoinTable hashtable, HashJoinTuple tuple)
 
static void ExecParallelHashPushTuple (dsa_pointer_atomic *head, HashJoinTuple tuple, dsa_pointer tuple_shared)
 
static void ExecParallelHashJoinSetUpBatches (HashJoinTable hashtable, int nbatch)
 
static void ExecParallelHashEnsureBatchAccessors (HashJoinTable hashtable)
 
static void ExecParallelHashRepartitionFirst (HashJoinTable hashtable)
 
static void ExecParallelHashRepartitionRest (HashJoinTable hashtable)
 
static HashMemoryChunk ExecParallelHashPopChunkQueue (HashJoinTable hashtable, dsa_pointer *shared)
 
static bool ExecParallelHashTuplePrealloc (HashJoinTable hashtable, int batchno, size_t size)
 
static void ExecParallelHashMergeCounters (HashJoinTable hashtable)
 
static void ExecParallelHashCloseBatchAccessors (HashJoinTable hashtable)
 
static TupleTableSlotExecHash (PlanState *pstate)
 
NodeMultiExecHash (HashState *node)
 
HashStateExecInitHash (Hash *node, EState *estate, int eflags)
 
void ExecEndHash (HashState *node)
 
HashJoinTable ExecHashTableCreate (HashState *state)
 
void ExecChooseHashTableSize (double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
 
void ExecHashTableDestroy (HashJoinTable hashtable)
 
void ExecHashTableInsert (HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
 
void ExecParallelHashTableInsert (HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
 
void ExecParallelHashTableInsertCurrentBatch (HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
 
void ExecHashGetBucketAndBatch (HashJoinTable hashtable, uint32 hashvalue, int *bucketno, int *batchno)
 
bool ExecScanHashBucket (HashJoinState *hjstate, ExprContext *econtext)
 
bool ExecParallelScanHashBucket (HashJoinState *hjstate, ExprContext *econtext)
 
void ExecPrepHashTableForUnmatched (HashJoinState *hjstate)
 
bool ExecParallelPrepHashTableForUnmatched (HashJoinState *hjstate)
 
bool ExecScanHashTableForUnmatched (HashJoinState *hjstate, ExprContext *econtext)
 
bool ExecParallelScanHashTableForUnmatched (HashJoinState *hjstate, ExprContext *econtext)
 
void ExecHashTableReset (HashJoinTable hashtable)
 
void ExecHashTableResetMatchFlags (HashJoinTable hashtable)
 
void ExecReScanHash (HashState *node)
 
int ExecHashGetSkewBucket (HashJoinTable hashtable, uint32 hashvalue)
 
void ExecHashEstimate (HashState *node, ParallelContext *pcxt)
 
void ExecHashInitializeDSM (HashState *node, ParallelContext *pcxt)
 
void ExecHashInitializeWorker (HashState *node, ParallelWorkerContext *pwcxt)
 
void ExecShutdownHash (HashState *node)
 
void ExecHashRetrieveInstrumentation (HashState *node)
 
void ExecHashAccumInstrumentation (HashInstrumentation *instrument, HashJoinTable hashtable)
 
void ExecParallelHashTableAlloc (HashJoinTable hashtable, int batchno)
 
void ExecHashTableDetachBatch (HashJoinTable hashtable)
 
void ExecHashTableDetach (HashJoinTable hashtable)
 
void ExecParallelHashTableSetCurrentBatch (HashJoinTable hashtable, int batchno)
 
size_t get_hash_memory_limit (void)
 

Macro Definition Documentation

◆ NTUP_PER_BUCKET

#define NTUP_PER_BUCKET   1

Definition at line 656 of file nodeHash.c.

Function Documentation

◆ dense_alloc()

static void * dense_alloc ( HashJoinTable  hashtable,
Size  size 
)
static

Definition at line 2755 of file nodeHash.c.

2756 {
2757  HashMemoryChunk newChunk;
2758  char *ptr;
2759 
2760  /* just in case the size is not already aligned properly */
2761  size = MAXALIGN(size);
2762 
2763  /*
2764  * If tuple size is larger than threshold, allocate a separate chunk.
2765  */
2766  if (size > HASH_CHUNK_THRESHOLD)
2767  {
2768  /* allocate new chunk and put it at the beginning of the list */
2769  newChunk = (HashMemoryChunk) MemoryContextAlloc(hashtable->batchCxt,
2771  newChunk->maxlen = size;
2772  newChunk->used = size;
2773  newChunk->ntuples = 1;
2774 
2775  /*
2776  * Add this chunk to the list after the first existing chunk, so that
2777  * we don't lose the remaining space in the "current" chunk.
2778  */
2779  if (hashtable->chunks != NULL)
2780  {
2781  newChunk->next = hashtable->chunks->next;
2782  hashtable->chunks->next.unshared = newChunk;
2783  }
2784  else
2785  {
2786  newChunk->next.unshared = hashtable->chunks;
2787  hashtable->chunks = newChunk;
2788  }
2789 
2790  return HASH_CHUNK_DATA(newChunk);
2791  }
2792 
2793  /*
2794  * See if we have enough space for it in the current chunk (if any). If
2795  * not, allocate a fresh chunk.
2796  */
2797  if ((hashtable->chunks == NULL) ||
2798  (hashtable->chunks->maxlen - hashtable->chunks->used) < size)
2799  {
2800  /* allocate new chunk and put it at the beginning of the list */
2801  newChunk = (HashMemoryChunk) MemoryContextAlloc(hashtable->batchCxt,
2803 
2804  newChunk->maxlen = HASH_CHUNK_SIZE;
2805  newChunk->used = size;
2806  newChunk->ntuples = 1;
2807 
2808  newChunk->next.unshared = hashtable->chunks;
2809  hashtable->chunks = newChunk;
2810 
2811  return HASH_CHUNK_DATA(newChunk);
2812  }
2813 
2814  /* There is enough space in the current chunk, let's add the tuple */
2815  ptr = HASH_CHUNK_DATA(hashtable->chunks) + hashtable->chunks->used;
2816  hashtable->chunks->used += size;
2817  hashtable->chunks->ntuples += 1;
2818 
2819  /* return pointer to the start of the tuple memory */
2820  return ptr;
2821 }
#define MAXALIGN(LEN)
Definition: c.h:814
struct HashMemoryChunkData * HashMemoryChunk
Definition: hashjoin.h:148
#define HASH_CHUNK_DATA(hc)
Definition: hashjoin.h:152
#define HASH_CHUNK_THRESHOLD
Definition: hashjoin.h:154
#define HASH_CHUNK_HEADER_SIZE
Definition: hashjoin.h:151
#define HASH_CHUNK_SIZE
Definition: hashjoin.h:150
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
static pg_noinline void Size size
Definition: slab.c:607
HashMemoryChunk chunks
Definition: hashjoin.h:355
MemoryContext batchCxt
Definition: hashjoin.h:351
struct HashMemoryChunkData * unshared
Definition: hashjoin.h:137
union HashMemoryChunkData::@105 next

References HashJoinTableData::batchCxt, HashJoinTableData::chunks, HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HASH_CHUNK_SIZE, HASH_CHUNK_THRESHOLD, MAXALIGN, HashMemoryChunkData::maxlen, MemoryContextAlloc(), HashMemoryChunkData::next, HashMemoryChunkData::ntuples, size, HashMemoryChunkData::unshared, and HashMemoryChunkData::used.

Referenced by ExecHashIncreaseNumBatches(), ExecHashRemoveNextSkewBucket(), and ExecHashTableInsert().

◆ ExecChooseHashTableSize()

void ExecChooseHashTableSize ( double  ntuples,
int  tupwidth,
bool  useskew,
bool  try_combined_hash_mem,
int  parallel_workers,
size_t *  space_allowed,
int *  numbuckets,
int *  numbatches,
int *  num_skew_mcvs 
)

Definition at line 659 of file nodeHash.c.

666 {
667  int tupsize;
668  double inner_rel_bytes;
669  size_t hash_table_bytes;
670  size_t bucket_bytes;
671  size_t max_pointers;
672  int nbatch = 1;
673  int nbuckets;
674  double dbuckets;
675 
676  /* Force a plausible relation size if no info */
677  if (ntuples <= 0.0)
678  ntuples = 1000.0;
679 
680  /*
681  * Estimate tupsize based on footprint of tuple in hashtable... note this
682  * does not allow for any palloc overhead. The manipulations of spaceUsed
683  * don't count palloc overhead either.
684  */
685  tupsize = HJTUPLE_OVERHEAD +
687  MAXALIGN(tupwidth);
688  inner_rel_bytes = ntuples * tupsize;
689 
690  /*
691  * Compute in-memory hashtable size limit from GUCs.
692  */
693  hash_table_bytes = get_hash_memory_limit();
694 
695  /*
696  * Parallel Hash tries to use the combined hash_mem of all workers to
697  * avoid the need to batch. If that won't work, it falls back to hash_mem
698  * per worker and tries to process batches in parallel.
699  */
700  if (try_combined_hash_mem)
701  {
702  /* Careful, this could overflow size_t */
703  double newlimit;
704 
705  newlimit = (double) hash_table_bytes * (double) (parallel_workers + 1);
706  newlimit = Min(newlimit, (double) SIZE_MAX);
707  hash_table_bytes = (size_t) newlimit;
708  }
709 
710  *space_allowed = hash_table_bytes;
711 
712  /*
713  * If skew optimization is possible, estimate the number of skew buckets
714  * that will fit in the memory allowed, and decrement the assumed space
715  * available for the main hash table accordingly.
716  *
717  * We make the optimistic assumption that each skew bucket will contain
718  * one inner-relation tuple. If that turns out to be low, we will recover
719  * at runtime by reducing the number of skew buckets.
720  *
721  * hashtable->skewBucket will have up to 8 times as many HashSkewBucket
722  * pointers as the number of MCVs we allow, since ExecHashBuildSkewHash
723  * will round up to the next power of 2 and then multiply by 4 to reduce
724  * collisions.
725  */
726  if (useskew)
727  {
728  size_t bytes_per_mcv;
729  size_t skew_mcvs;
730 
731  /*----------
732  * Compute number of MCVs we could hold in hash_table_bytes
733  *
734  * Divisor is:
735  * size of a hash tuple +
736  * worst-case size of skewBucket[] per MCV +
737  * size of skewBucketNums[] entry +
738  * size of skew bucket struct itself
739  *----------
740  */
741  bytes_per_mcv = tupsize +
742  (8 * sizeof(HashSkewBucket *)) +
743  sizeof(int) +
745  skew_mcvs = hash_table_bytes / bytes_per_mcv;
746 
747  /*
748  * Now scale by SKEW_HASH_MEM_PERCENT (we do it in this order so as
749  * not to worry about size_t overflow in the multiplication)
750  */
751  skew_mcvs = (skew_mcvs * SKEW_HASH_MEM_PERCENT) / 100;
752 
753  /* Now clamp to integer range */
754  skew_mcvs = Min(skew_mcvs, INT_MAX);
755 
756  *num_skew_mcvs = (int) skew_mcvs;
757 
758  /* Reduce hash_table_bytes by the amount needed for the skew table */
759  if (skew_mcvs > 0)
760  hash_table_bytes -= skew_mcvs * bytes_per_mcv;
761  }
762  else
763  *num_skew_mcvs = 0;
764 
765  /*
766  * Set nbuckets to achieve an average bucket load of NTUP_PER_BUCKET when
767  * memory is filled, assuming a single batch; but limit the value so that
768  * the pointer arrays we'll try to allocate do not exceed hash_table_bytes
769  * nor MaxAllocSize.
770  *
771  * Note that both nbuckets and nbatch must be powers of 2 to make
772  * ExecHashGetBucketAndBatch fast.
773  */
774  max_pointers = hash_table_bytes / sizeof(HashJoinTuple);
775  max_pointers = Min(max_pointers, MaxAllocSize / sizeof(HashJoinTuple));
776  /* If max_pointers isn't a power of 2, must round it down to one */
777  max_pointers = pg_prevpower2_size_t(max_pointers);
778 
779  /* Also ensure we avoid integer overflow in nbatch and nbuckets */
780  /* (this step is redundant given the current value of MaxAllocSize) */
781  max_pointers = Min(max_pointers, INT_MAX / 2 + 1);
782 
783  dbuckets = ceil(ntuples / NTUP_PER_BUCKET);
784  dbuckets = Min(dbuckets, max_pointers);
785  nbuckets = (int) dbuckets;
786  /* don't let nbuckets be really small, though ... */
787  nbuckets = Max(nbuckets, 1024);
788  /* ... and force it to be a power of 2. */
789  nbuckets = pg_nextpower2_32(nbuckets);
790 
791  /*
792  * If there's not enough space to store the projected number of tuples and
793  * the required bucket headers, we will need multiple batches.
794  */
795  bucket_bytes = sizeof(HashJoinTuple) * nbuckets;
796  if (inner_rel_bytes + bucket_bytes > hash_table_bytes)
797  {
798  /* We'll need multiple batches */
799  size_t sbuckets;
800  double dbatch;
801  int minbatch;
802  size_t bucket_size;
803 
804  /*
805  * If Parallel Hash with combined hash_mem would still need multiple
806  * batches, we'll have to fall back to regular hash_mem budget.
807  */
808  if (try_combined_hash_mem)
809  {
810  ExecChooseHashTableSize(ntuples, tupwidth, useskew,
811  false, parallel_workers,
812  space_allowed,
813  numbuckets,
814  numbatches,
815  num_skew_mcvs);
816  return;
817  }
818 
819  /*
820  * Estimate the number of buckets we'll want to have when hash_mem is
821  * entirely full. Each bucket will contain a bucket pointer plus
822  * NTUP_PER_BUCKET tuples, whose projected size already includes
823  * overhead for the hash code, pointer to the next tuple, etc.
824  */
825  bucket_size = (tupsize * NTUP_PER_BUCKET + sizeof(HashJoinTuple));
826  if (hash_table_bytes <= bucket_size)
827  sbuckets = 1; /* avoid pg_nextpower2_size_t(0) */
828  else
829  sbuckets = pg_nextpower2_size_t(hash_table_bytes / bucket_size);
830  sbuckets = Min(sbuckets, max_pointers);
831  nbuckets = (int) sbuckets;
832  nbuckets = pg_nextpower2_32(nbuckets);
833  bucket_bytes = nbuckets * sizeof(HashJoinTuple);
834 
835  /*
836  * Buckets are simple pointers to hashjoin tuples, while tupsize
837  * includes the pointer, hash code, and MinimalTupleData. So buckets
838  * should never really exceed 25% of hash_mem (even for
839  * NTUP_PER_BUCKET=1); except maybe for hash_mem values that are not
840  * 2^N bytes, where we might get more because of doubling. So let's
841  * look for 50% here.
842  */
843  Assert(bucket_bytes <= hash_table_bytes / 2);
844 
845  /* Calculate required number of batches. */
846  dbatch = ceil(inner_rel_bytes / (hash_table_bytes - bucket_bytes));
847  dbatch = Min(dbatch, max_pointers);
848  minbatch = (int) dbatch;
849  nbatch = pg_nextpower2_32(Max(2, minbatch));
850  }
851 
852  Assert(nbuckets > 0);
853  Assert(nbatch > 0);
854 
855  *numbuckets = nbuckets;
856  *numbatches = nbatch;
857 }
#define Min(x, y)
Definition: c.h:1007
#define Max(x, y)
Definition: c.h:1001
#define Assert(condition)
Definition: c.h:861
struct HashJoinTupleData * HashJoinTuple
Definition: execnodes.h:2216
#define HJTUPLE_OVERHEAD
Definition: hashjoin.h:90
#define SKEW_BUCKET_OVERHEAD
Definition: hashjoin.h:119
#define SKEW_HASH_MEM_PERCENT
Definition: hashjoin.h:121
#define SizeofMinimalTupleHeader
Definition: htup_details.h:647
#define MaxAllocSize
Definition: memutils.h:40
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:659
#define NTUP_PER_BUCKET
Definition: nodeHash.c:656
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3481
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:189
#define pg_nextpower2_size_t
Definition: pg_bitutils.h:417
#define pg_prevpower2_size_t
Definition: pg_bitutils.h:418

References Assert, get_hash_memory_limit(), HJTUPLE_OVERHEAD, Max, MAXALIGN, MaxAllocSize, Min, NTUP_PER_BUCKET, pg_nextpower2_32(), pg_nextpower2_size_t, pg_prevpower2_size_t, SizeofMinimalTupleHeader, SKEW_BUCKET_OVERHEAD, and SKEW_HASH_MEM_PERCENT.

Referenced by ExecHashTableCreate(), and initial_cost_hashjoin().

◆ ExecEndHash()

void ExecEndHash ( HashState node)

Definition at line 428 of file nodeHash.c.

429 {
431 
432  /*
433  * shut down the subplan
434  */
435  outerPlan = outerPlanState(node);
437 }
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
#define outerPlanState(node)
Definition: execnodes.h:1219
#define outerPlan(node)
Definition: plannodes.h:183

References ExecEndNode(), outerPlan, and outerPlanState.

Referenced by ExecEndNode().

◆ ExecHash()

static TupleTableSlot* ExecHash ( PlanState pstate)
static

Definition at line 92 of file nodeHash.c.

93 {
94  elog(ERROR, "Hash node does not support ExecProcNode call convention");
95  return NULL;
96 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225

References elog, and ERROR.

Referenced by ExecInitHash().

◆ ExecHashAccumInstrumentation()

void ExecHashAccumInstrumentation ( HashInstrumentation instrument,
HashJoinTable  hashtable 
)

Definition at line 2736 of file nodeHash.c.

2738 {
2739  instrument->nbuckets = Max(instrument->nbuckets,
2740  hashtable->nbuckets);
2741  instrument->nbuckets_original = Max(instrument->nbuckets_original,
2742  hashtable->nbuckets_original);
2743  instrument->nbatch = Max(instrument->nbatch,
2744  hashtable->nbatch);
2745  instrument->nbatch_original = Max(instrument->nbatch_original,
2746  hashtable->nbatch_original);
2747  instrument->space_peak = Max(instrument->space_peak,
2748  hashtable->spacePeak);
2749 }

References Max, HashJoinTableData::nbatch, HashInstrumentation::nbatch, HashJoinTableData::nbatch_original, HashInstrumentation::nbatch_original, HashJoinTableData::nbuckets, HashInstrumentation::nbuckets, HashJoinTableData::nbuckets_original, HashInstrumentation::nbuckets_original, HashInstrumentation::space_peak, and HashJoinTableData::spacePeak.

Referenced by ExecReScanHashJoin(), and ExecShutdownHash().

◆ ExecHashBuildSkewHash()

static void ExecHashBuildSkewHash ( HashState hashstate,
HashJoinTable  hashtable,
Hash node,
int  mcvsToUse 
)
static

Definition at line 2262 of file nodeHash.c.

2264 {
2265  HeapTupleData *statsTuple;
2266  AttStatsSlot sslot;
2267 
2268  /* Do nothing if planner didn't identify the outer relation's join key */
2269  if (!OidIsValid(node->skewTable))
2270  return;
2271  /* Also, do nothing if we don't have room for at least one skew bucket */
2272  if (mcvsToUse <= 0)
2273  return;
2274 
2275  /*
2276  * Try to find the MCV statistics for the outer relation's join key.
2277  */
2278  statsTuple = SearchSysCache3(STATRELATTINH,
2279  ObjectIdGetDatum(node->skewTable),
2280  Int16GetDatum(node->skewColumn),
2281  BoolGetDatum(node->skewInherit));
2282  if (!HeapTupleIsValid(statsTuple))
2283  return;
2284 
2285  if (get_attstatsslot(&sslot, statsTuple,
2286  STATISTIC_KIND_MCV, InvalidOid,
2288  {
2289  double frac;
2290  int nbuckets;
2291  int i;
2292 
2293  if (mcvsToUse > sslot.nvalues)
2294  mcvsToUse = sslot.nvalues;
2295 
2296  /*
2297  * Calculate the expected fraction of outer relation that will
2298  * participate in the skew optimization. If this isn't at least
2299  * SKEW_MIN_OUTER_FRACTION, don't use skew optimization.
2300  */
2301  frac = 0;
2302  for (i = 0; i < mcvsToUse; i++)
2303  frac += sslot.numbers[i];
2304  if (frac < SKEW_MIN_OUTER_FRACTION)
2305  {
2306  free_attstatsslot(&sslot);
2307  ReleaseSysCache(statsTuple);
2308  return;
2309  }
2310 
2311  /*
2312  * Okay, set up the skew hashtable.
2313  *
2314  * skewBucket[] is an open addressing hashtable with a power of 2 size
2315  * that is greater than the number of MCV values. (This ensures there
2316  * will be at least one null entry, so searches will always
2317  * terminate.)
2318  *
2319  * Note: this code could fail if mcvsToUse exceeds INT_MAX/8 or
2320  * MaxAllocSize/sizeof(void *)/8, but that is not currently possible
2321  * since we limit pg_statistic entries to much less than that.
2322  */
2323  nbuckets = pg_nextpower2_32(mcvsToUse + 1);
2324  /* use two more bits just to help avoid collisions */
2325  nbuckets <<= 2;
2326 
2327  hashtable->skewEnabled = true;
2328  hashtable->skewBucketLen = nbuckets;
2329 
2330  /*
2331  * We allocate the bucket memory in the hashtable's batch context. It
2332  * is only needed during the first batch, and this ensures it will be
2333  * automatically removed once the first batch is done.
2334  */
2335  hashtable->skewBucket = (HashSkewBucket **)
2336  MemoryContextAllocZero(hashtable->batchCxt,
2337  nbuckets * sizeof(HashSkewBucket *));
2338  hashtable->skewBucketNums = (int *)
2339  MemoryContextAllocZero(hashtable->batchCxt,
2340  mcvsToUse * sizeof(int));
2341 
2342  hashtable->spaceUsed += nbuckets * sizeof(HashSkewBucket *)
2343  + mcvsToUse * sizeof(int);
2344  hashtable->spaceUsedSkew += nbuckets * sizeof(HashSkewBucket *)
2345  + mcvsToUse * sizeof(int);
2346  if (hashtable->spaceUsed > hashtable->spacePeak)
2347  hashtable->spacePeak = hashtable->spaceUsed;
2348 
2349  /*
2350  * Create a skew bucket for each MCV hash value.
2351  *
2352  * Note: it is very important that we create the buckets in order of
2353  * decreasing MCV frequency. If we have to remove some buckets, they
2354  * must be removed in reverse order of creation (see notes in
2355  * ExecHashRemoveNextSkewBucket) and we want the least common MCVs to
2356  * be removed first.
2357  */
2358 
2359  for (i = 0; i < mcvsToUse; i++)
2360  {
2361  uint32 hashvalue;
2362  int bucket;
2363 
2364  hashvalue = DatumGetUInt32(FunctionCall1Coll(hashstate->skew_hashfunction,
2365  hashstate->skew_collation,
2366  sslot.values[i]));
2367 
2368  /*
2369  * While we have not hit a hole in the hashtable and have not hit
2370  * the desired bucket, we have collided with some previous hash
2371  * value, so try the next bucket location. NB: this code must
2372  * match ExecHashGetSkewBucket.
2373  */
2374  bucket = hashvalue & (nbuckets - 1);
2375  while (hashtable->skewBucket[bucket] != NULL &&
2376  hashtable->skewBucket[bucket]->hashvalue != hashvalue)
2377  bucket = (bucket + 1) & (nbuckets - 1);
2378 
2379  /*
2380  * If we found an existing bucket with the same hashvalue, leave
2381  * it alone. It's okay for two MCVs to share a hashvalue.
2382  */
2383  if (hashtable->skewBucket[bucket] != NULL)
2384  continue;
2385 
2386  /* Okay, create a new skew bucket for this hashvalue. */
2387  hashtable->skewBucket[bucket] = (HashSkewBucket *)
2388  MemoryContextAlloc(hashtable->batchCxt,
2389  sizeof(HashSkewBucket));
2390  hashtable->skewBucket[bucket]->hashvalue = hashvalue;
2391  hashtable->skewBucket[bucket]->tuples = NULL;
2392  hashtable->skewBucketNums[hashtable->nSkewBuckets] = bucket;
2393  hashtable->nSkewBuckets++;
2394  hashtable->spaceUsed += SKEW_BUCKET_OVERHEAD;
2395  hashtable->spaceUsedSkew += SKEW_BUCKET_OVERHEAD;
2396  if (hashtable->spaceUsed > hashtable->spacePeak)
2397  hashtable->spacePeak = hashtable->spaceUsed;
2398  }
2399 
2400  free_attstatsslot(&sslot);
2401  }
2402 
2403  ReleaseSysCache(statsTuple);
2404 }
unsigned int uint32
Definition: c.h:509
#define OidIsValid(objectId)
Definition: c.h:778
Datum FunctionCall1Coll(FmgrInfo *flinfo, Oid collation, Datum arg1)
Definition: fmgr.c:1129
#define SKEW_MIN_OUTER_FRACTION
Definition: hashjoin.h:122
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3344
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3234
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:42
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1215
static uint32 DatumGetUInt32(Datum X)
Definition: postgres.h:222
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
Datum * values
Definition: lsyscache.h:53
float4 * numbers
Definition: lsyscache.h:56
int * skewBucketNums
Definition: hashjoin.h:320
HashSkewBucket ** skewBucket
Definition: hashjoin.h:317
HashJoinTuple tuples
Definition: hashjoin.h:116
uint32 hashvalue
Definition: hashjoin.h:115
Oid skew_collation
Definition: execnodes.h:2781
FmgrInfo * skew_hashfunction
Definition: execnodes.h:2780
AttrNumber skewColumn
Definition: plannodes.h:1208
Oid skewTable
Definition: plannodes.h:1207
bool skewInherit
Definition: plannodes.h:1209
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:243

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, HashJoinTableData::batchCxt, BoolGetDatum(), DatumGetUInt32(), free_attstatsslot(), FunctionCall1Coll(), get_attstatsslot(), HashSkewBucket::hashvalue, HeapTupleIsValid, i, if(), Int16GetDatum(), InvalidOid, MemoryContextAlloc(), MemoryContextAllocZero(), HashJoinTableData::nSkewBuckets, AttStatsSlot::numbers, AttStatsSlot::nvalues, ObjectIdGetDatum(), OidIsValid, pg_nextpower2_32(), ReleaseSysCache(), SearchSysCache3(), SKEW_BUCKET_OVERHEAD, HashState::skew_collation, HashState::skew_hashfunction, SKEW_MIN_OUTER_FRACTION, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketLen, HashJoinTableData::skewBucketNums, Hash::skewColumn, HashJoinTableData::skewEnabled, Hash::skewInherit, Hash::skewTable, HashJoinTableData::spacePeak, HashJoinTableData::spaceUsed, HashJoinTableData::spaceUsedSkew, HashSkewBucket::tuples, and AttStatsSlot::values.

Referenced by ExecHashTableCreate().

◆ ExecHashEstimate()

void ExecHashEstimate ( HashState node,
ParallelContext pcxt 
)

Definition at line 2620 of file nodeHash.c.

2621 {
2622  size_t size;
2623 
2624  /* don't need this if not instrumenting or no workers */
2625  if (!node->ps.instrument || pcxt->nworkers == 0)
2626  return;
2627 
2628  size = mul_size(pcxt->nworkers, sizeof(HashInstrumentation));
2629  size = add_size(size, offsetof(SharedHashInfo, hinstrument));
2631  shm_toc_estimate_keys(&pcxt->estimator, 1);
2632 }
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
PlanState ps
Definition: execnodes.h:2776
shm_toc_estimator estimator
Definition: parallel.h:41
Instrumentation * instrument
Definition: execnodes.h:1133

References add_size(), ParallelContext::estimator, PlanState::instrument, mul_size(), ParallelContext::nworkers, HashState::ps, shm_toc_estimate_chunk, shm_toc_estimate_keys, and size.

Referenced by ExecParallelEstimate().

◆ ExecHashGetBucketAndBatch()

void ExecHashGetBucketAndBatch ( HashJoinTable  hashtable,
uint32  hashvalue,
int *  bucketno,
int *  batchno 
)

Definition at line 1819 of file nodeHash.c.

1823 {
1824  uint32 nbuckets = (uint32) hashtable->nbuckets;
1825  uint32 nbatch = (uint32) hashtable->nbatch;
1826 
1827  if (nbatch > 1)
1828  {
1829  *bucketno = hashvalue & (nbuckets - 1);
1830  *batchno = pg_rotate_right32(hashvalue,
1831  hashtable->log2_nbuckets) & (nbatch - 1);
1832  }
1833  else
1834  {
1835  *bucketno = hashvalue & (nbuckets - 1);
1836  *batchno = 0;
1837  }
1838 }
static uint32 pg_rotate_right32(uint32 word, int n)
Definition: pg_bitutils.h:398

References HashJoinTableData::log2_nbuckets, HashJoinTableData::nbatch, HashJoinTableData::nbuckets, and pg_rotate_right32().

Referenced by ExecHashIncreaseNumBatches(), ExecHashIncreaseNumBuckets(), ExecHashJoinImpl(), ExecHashRemoveNextSkewBucket(), ExecHashTableInsert(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashJoinPartitionOuter(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecParallelHashTableInsert(), and ExecParallelHashTableInsertCurrentBatch().

◆ ExecHashGetSkewBucket()

int ExecHashGetSkewBucket ( HashJoinTable  hashtable,
uint32  hashvalue 
)

Definition at line 2414 of file nodeHash.c.

2415 {
2416  int bucket;
2417 
2418  /*
2419  * Always return INVALID_SKEW_BUCKET_NO if not doing skew optimization (in
2420  * particular, this happens after the initial batch is done).
2421  */
2422  if (!hashtable->skewEnabled)
2423  return INVALID_SKEW_BUCKET_NO;
2424 
2425  /*
2426  * Since skewBucketLen is a power of 2, we can do a modulo by ANDing.
2427  */
2428  bucket = hashvalue & (hashtable->skewBucketLen - 1);
2429 
2430  /*
2431  * While we have not hit a hole in the hashtable and have not hit the
2432  * desired bucket, we have collided with some other hash value, so try the
2433  * next bucket location.
2434  */
2435  while (hashtable->skewBucket[bucket] != NULL &&
2436  hashtable->skewBucket[bucket]->hashvalue != hashvalue)
2437  bucket = (bucket + 1) & (hashtable->skewBucketLen - 1);
2438 
2439  /*
2440  * Found the desired bucket?
2441  */
2442  if (hashtable->skewBucket[bucket] != NULL)
2443  return bucket;
2444 
2445  /*
2446  * There must not be any hashtable entry for this hash value.
2447  */
2448  return INVALID_SKEW_BUCKET_NO;
2449 }
#define INVALID_SKEW_BUCKET_NO
Definition: hashjoin.h:120

References HashSkewBucket::hashvalue, INVALID_SKEW_BUCKET_NO, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketLen, and HashJoinTableData::skewEnabled.

Referenced by ExecHashJoinImpl(), and MultiExecPrivateHash().

◆ ExecHashIncreaseNumBatches()

static void ExecHashIncreaseNumBatches ( HashJoinTable  hashtable)
static

Definition at line 900 of file nodeHash.c.

901 {
902  int oldnbatch = hashtable->nbatch;
903  int curbatch = hashtable->curbatch;
904  int nbatch;
905  long ninmemory;
906  long nfreed;
907  HashMemoryChunk oldchunks;
908 
909  /* do nothing if we've decided to shut off growth */
910  if (!hashtable->growEnabled)
911  return;
912 
913  /* safety check to avoid overflow */
914  if (oldnbatch > Min(INT_MAX / 2, MaxAllocSize / (sizeof(void *) * 2)))
915  return;
916 
917  nbatch = oldnbatch * 2;
918  Assert(nbatch > 1);
919 
920 #ifdef HJDEBUG
921  printf("Hashjoin %p: increasing nbatch to %d because space = %zu\n",
922  hashtable, nbatch, hashtable->spaceUsed);
923 #endif
924 
925  if (hashtable->innerBatchFile == NULL)
926  {
927  MemoryContext oldcxt = MemoryContextSwitchTo(hashtable->spillCxt);
928 
929  /* we had no file arrays before */
930  hashtable->innerBatchFile = palloc0_array(BufFile *, nbatch);
931  hashtable->outerBatchFile = palloc0_array(BufFile *, nbatch);
932 
933  MemoryContextSwitchTo(oldcxt);
934 
935  /* time to establish the temp tablespaces, too */
937  }
938  else
939  {
940  /* enlarge arrays and zero out added entries */
941  hashtable->innerBatchFile = repalloc0_array(hashtable->innerBatchFile, BufFile *, oldnbatch, nbatch);
942  hashtable->outerBatchFile = repalloc0_array(hashtable->outerBatchFile, BufFile *, oldnbatch, nbatch);
943  }
944 
945  hashtable->nbatch = nbatch;
946 
947  /*
948  * Scan through the existing hash table entries and dump out any that are
949  * no longer of the current batch.
950  */
951  ninmemory = nfreed = 0;
952 
953  /* If know we need to resize nbuckets, we can do it while rebatching. */
954  if (hashtable->nbuckets_optimal != hashtable->nbuckets)
955  {
956  /* we never decrease the number of buckets */
957  Assert(hashtable->nbuckets_optimal > hashtable->nbuckets);
958 
959  hashtable->nbuckets = hashtable->nbuckets_optimal;
960  hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
961 
962  hashtable->buckets.unshared =
963  repalloc_array(hashtable->buckets.unshared,
964  HashJoinTuple, hashtable->nbuckets);
965  }
966 
967  /*
968  * We will scan through the chunks directly, so that we can reset the
969  * buckets now and not have to keep track which tuples in the buckets have
970  * already been processed. We will free the old chunks as we go.
971  */
972  memset(hashtable->buckets.unshared, 0,
973  sizeof(HashJoinTuple) * hashtable->nbuckets);
974  oldchunks = hashtable->chunks;
975  hashtable->chunks = NULL;
976 
977  /* so, let's scan through the old chunks, and all tuples in each chunk */
978  while (oldchunks != NULL)
979  {
980  HashMemoryChunk nextchunk = oldchunks->next.unshared;
981 
982  /* position within the buffer (up to oldchunks->used) */
983  size_t idx = 0;
984 
985  /* process all tuples stored in this chunk (and then free it) */
986  while (idx < oldchunks->used)
987  {
988  HashJoinTuple hashTuple = (HashJoinTuple) (HASH_CHUNK_DATA(oldchunks) + idx);
989  MinimalTuple tuple = HJTUPLE_MINTUPLE(hashTuple);
990  int hashTupleSize = (HJTUPLE_OVERHEAD + tuple->t_len);
991  int bucketno;
992  int batchno;
993 
994  ninmemory++;
995  ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
996  &bucketno, &batchno);
997 
998  if (batchno == curbatch)
999  {
1000  /* keep tuple in memory - copy it into the new chunk */
1001  HashJoinTuple copyTuple;
1002 
1003  copyTuple = (HashJoinTuple) dense_alloc(hashtable, hashTupleSize);
1004  memcpy(copyTuple, hashTuple, hashTupleSize);
1005 
1006  /* and add it back to the appropriate bucket */
1007  copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1008  hashtable->buckets.unshared[bucketno] = copyTuple;
1009  }
1010  else
1011  {
1012  /* dump it out */
1013  Assert(batchno > curbatch);
1015  hashTuple->hashvalue,
1016  &hashtable->innerBatchFile[batchno],
1017  hashtable);
1018 
1019  hashtable->spaceUsed -= hashTupleSize;
1020  nfreed++;
1021  }
1022 
1023  /* next tuple in this chunk */
1024  idx += MAXALIGN(hashTupleSize);
1025 
1026  /* allow this loop to be cancellable */
1028  }
1029 
1030  /* we're done with this chunk - free it and proceed to the next one */
1031  pfree(oldchunks);
1032  oldchunks = nextchunk;
1033  }
1034 
1035 #ifdef HJDEBUG
1036  printf("Hashjoin %p: freed %ld of %ld tuples, space now %zu\n",
1037  hashtable, nfreed, ninmemory, hashtable->spaceUsed);
1038 #endif
1039 
1040  /*
1041  * If we dumped out either all or none of the tuples in the table, disable
1042  * further expansion of nbatch. This situation implies that we have
1043  * enough tuples of identical hashvalues to overflow spaceAllowed.
1044  * Increasing nbatch will not fix it since there's no way to subdivide the
1045  * group any more finely. We have to just gut it out and hope the server
1046  * has enough RAM.
1047  */
1048  if (nfreed == 0 || nfreed == ninmemory)
1049  {
1050  hashtable->growEnabled = false;
1051 #ifdef HJDEBUG
1052  printf("Hashjoin %p: disabling further increase of nbatch\n",
1053  hashtable);
1054 #endif
1055  }
1056 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
void PrepareTempTablespaces(void)
Definition: tablespace.c:1331
#define repalloc_array(pointer, type, count)
Definition: fe_memutils.h:66
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
#define HJTUPLE_MINTUPLE(hjtup)
Definition: hashjoin.h:91
void pfree(void *pointer)
Definition: mcxt.c:1521
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
static void * dense_alloc(HashJoinTable hashtable, Size size)
Definition: nodeHash.c:2755
void ExecHashGetBucketAndBatch(HashJoinTable hashtable, uint32 hashvalue, int *bucketno, int *batchno)
Definition: nodeHash.c:1819
void ExecHashJoinSaveTuple(MinimalTuple tuple, uint32 hashvalue, BufFile **fileptr, HashJoinTable hashtable)
#define repalloc0_array(pointer, type, oldcount, count)
Definition: palloc.h:109
#define printf(...)
Definition: port.h:244
MemoryContextSwitchTo(old_ctx)
struct HashJoinTupleData ** unshared
Definition: hashjoin.h:311
union HashJoinTableData::@106 buckets
MemoryContext spillCxt
Definition: hashjoin.h:352
BufFile ** innerBatchFile
Definition: hashjoin.h:341
int log2_nbuckets_optimal
Definition: hashjoin.h:305
BufFile ** outerBatchFile
Definition: hashjoin.h:342
uint32 hashvalue
Definition: hashjoin.h:86
struct HashJoinTupleData * unshared
Definition: hashjoin.h:83
union HashJoinTupleData::@104 next

References Assert, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, HashJoinTableData::chunks, HashJoinTableData::curbatch, dense_alloc(), ExecHashGetBucketAndBatch(), ExecHashJoinSaveTuple(), HashJoinTableData::growEnabled, HASH_CHUNK_DATA, HashJoinTupleData::hashvalue, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, idx(), HashJoinTableData::innerBatchFile, HashJoinTableData::log2_nbuckets, HashJoinTableData::log2_nbuckets_optimal, MAXALIGN, MaxAllocSize, MemoryContextSwitchTo(), Min, HashJoinTableData::nbatch, HashJoinTableData::nbuckets, HashJoinTableData::nbuckets_optimal, HashJoinTupleData::next, HashMemoryChunkData::next, HashJoinTableData::outerBatchFile, palloc0_array, pfree(), PrepareTempTablespaces(), printf, repalloc0_array, repalloc_array, HashJoinTableData::spaceUsed, HashJoinTableData::spillCxt, MinimalTupleData::t_len, HashJoinTupleData::unshared, HashMemoryChunkData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashSkewTableInsert(), and ExecHashTableInsert().

◆ ExecHashIncreaseNumBuckets()

static void ExecHashIncreaseNumBuckets ( HashJoinTable  hashtable)
static

Definition at line 1446 of file nodeHash.c.

1447 {
1449 
1450  /* do nothing if not an increase (it's called increase for a reason) */
1451  if (hashtable->nbuckets >= hashtable->nbuckets_optimal)
1452  return;
1453 
1454 #ifdef HJDEBUG
1455  printf("Hashjoin %p: increasing nbuckets %d => %d\n",
1456  hashtable, hashtable->nbuckets, hashtable->nbuckets_optimal);
1457 #endif
1458 
1459  hashtable->nbuckets = hashtable->nbuckets_optimal;
1460  hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
1461 
1462  Assert(hashtable->nbuckets > 1);
1463  Assert(hashtable->nbuckets <= (INT_MAX / 2));
1464  Assert(hashtable->nbuckets == (1 << hashtable->log2_nbuckets));
1465 
1466  /*
1467  * Just reallocate the proper number of buckets - we don't need to walk
1468  * through them - we can walk the dense-allocated chunks (just like in
1469  * ExecHashIncreaseNumBatches, but without all the copying into new
1470  * chunks)
1471  */
1472  hashtable->buckets.unshared =
1473  repalloc_array(hashtable->buckets.unshared,
1474  HashJoinTuple, hashtable->nbuckets);
1475 
1476  memset(hashtable->buckets.unshared, 0,
1477  hashtable->nbuckets * sizeof(HashJoinTuple));
1478 
1479  /* scan through all tuples in all chunks to rebuild the hash table */
1480  for (chunk = hashtable->chunks; chunk != NULL; chunk = chunk->next.unshared)
1481  {
1482  /* process all tuples stored in this chunk */
1483  size_t idx = 0;
1484 
1485  while (idx < chunk->used)
1486  {
1488  int bucketno;
1489  int batchno;
1490 
1491  ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1492  &bucketno, &batchno);
1493 
1494  /* add the tuple to the proper bucket */
1495  hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1496  hashtable->buckets.unshared[bucketno] = hashTuple;
1497 
1498  /* advance index past the tuple */
1500  HJTUPLE_MINTUPLE(hashTuple)->t_len);
1501  }
1502 
1503  /* allow this loop to be cancellable */
1505  }
1506 }
uint64 chunk

References Assert, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, chunk, HashJoinTableData::chunks, ExecHashGetBucketAndBatch(), HASH_CHUNK_DATA, HashJoinTupleData::hashvalue, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, idx(), HashJoinTableData::log2_nbuckets, HashJoinTableData::log2_nbuckets_optimal, MAXALIGN, HashJoinTableData::nbuckets, HashJoinTableData::nbuckets_optimal, HashJoinTupleData::next, printf, repalloc_array, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by MultiExecPrivateHash().

◆ ExecHashInitializeDSM()

void ExecHashInitializeDSM ( HashState node,
ParallelContext pcxt 
)

Definition at line 2639 of file nodeHash.c.

2640 {
2641  size_t size;
2642 
2643  /* don't need this if not instrumenting or no workers */
2644  if (!node->ps.instrument || pcxt->nworkers == 0)
2645  return;
2646 
2647  size = offsetof(SharedHashInfo, hinstrument) +
2648  pcxt->nworkers * sizeof(HashInstrumentation);
2649  node->shared_info = (SharedHashInfo *) shm_toc_allocate(pcxt->toc, size);
2650 
2651  /* Each per-worker area must start out as zeroes. */
2652  memset(node->shared_info, 0, size);
2653 
2654  node->shared_info->num_workers = pcxt->nworkers;
2655  shm_toc_insert(pcxt->toc, node->ps.plan->plan_node_id,
2656  node->shared_info);
2657 }
struct HashInstrumentation HashInstrumentation
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
SharedHashInfo * shared_info
Definition: execnodes.h:2789
shm_toc * toc
Definition: parallel.h:44
Plan * plan
Definition: execnodes.h:1123
int plan_node_id
Definition: plannodes.h:152

References PlanState::instrument, SharedHashInfo::num_workers, ParallelContext::nworkers, PlanState::plan, Plan::plan_node_id, HashState::ps, HashState::shared_info, shm_toc_allocate(), shm_toc_insert(), size, and ParallelContext::toc.

Referenced by ExecParallelInitializeDSM().

◆ ExecHashInitializeWorker()

void ExecHashInitializeWorker ( HashState node,
ParallelWorkerContext pwcxt 
)

Definition at line 2664 of file nodeHash.c.

2665 {
2666  SharedHashInfo *shared_info;
2667 
2668  /* don't need this if not instrumenting */
2669  if (!node->ps.instrument)
2670  return;
2671 
2672  /*
2673  * Find our entry in the shared area, and set up a pointer to it so that
2674  * we'll accumulate stats there when shutting down or rebuilding the hash
2675  * table.
2676  */
2677  shared_info = (SharedHashInfo *)
2678  shm_toc_lookup(pwcxt->toc, node->ps.plan->plan_node_id, false);
2679  node->hinstrument = &shared_info->hinstrument[ParallelWorkerNumber];
2680 }
int ParallelWorkerNumber
Definition: parallel.c:112
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
HashInstrumentation * hinstrument
Definition: execnodes.h:2796
HashInstrumentation hinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2767

References SharedHashInfo::hinstrument, HashState::hinstrument, PlanState::instrument, ParallelWorkerNumber, PlanState::plan, Plan::plan_node_id, HashState::ps, shm_toc_lookup(), and ParallelWorkerContext::toc.

Referenced by ExecParallelInitializeWorker().

◆ ExecHashRemoveNextSkewBucket()

static void ExecHashRemoveNextSkewBucket ( HashJoinTable  hashtable)
static

Definition at line 2506 of file nodeHash.c.

2507 {
2508  int bucketToRemove;
2509  HashSkewBucket *bucket;
2510  uint32 hashvalue;
2511  int bucketno;
2512  int batchno;
2513  HashJoinTuple hashTuple;
2514 
2515  /* Locate the bucket to remove */
2516  bucketToRemove = hashtable->skewBucketNums[hashtable->nSkewBuckets - 1];
2517  bucket = hashtable->skewBucket[bucketToRemove];
2518 
2519  /*
2520  * Calculate which bucket and batch the tuples belong to in the main
2521  * hashtable. They all have the same hash value, so it's the same for all
2522  * of them. Also note that it's not possible for nbatch to increase while
2523  * we are processing the tuples.
2524  */
2525  hashvalue = bucket->hashvalue;
2526  ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
2527 
2528  /* Process all tuples in the bucket */
2529  hashTuple = bucket->tuples;
2530  while (hashTuple != NULL)
2531  {
2532  HashJoinTuple nextHashTuple = hashTuple->next.unshared;
2533  MinimalTuple tuple;
2534  Size tupleSize;
2535 
2536  /*
2537  * This code must agree with ExecHashTableInsert. We do not use
2538  * ExecHashTableInsert directly as ExecHashTableInsert expects a
2539  * TupleTableSlot while we already have HashJoinTuples.
2540  */
2541  tuple = HJTUPLE_MINTUPLE(hashTuple);
2542  tupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
2543 
2544  /* Decide whether to put the tuple in the hash table or a temp file */
2545  if (batchno == hashtable->curbatch)
2546  {
2547  /* Move the tuple to the main hash table */
2548  HashJoinTuple copyTuple;
2549 
2550  /*
2551  * We must copy the tuple into the dense storage, else it will not
2552  * be found by, eg, ExecHashIncreaseNumBatches.
2553  */
2554  copyTuple = (HashJoinTuple) dense_alloc(hashtable, tupleSize);
2555  memcpy(copyTuple, hashTuple, tupleSize);
2556  pfree(hashTuple);
2557 
2558  copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
2559  hashtable->buckets.unshared[bucketno] = copyTuple;
2560 
2561  /* We have reduced skew space, but overall space doesn't change */
2562  hashtable->spaceUsedSkew -= tupleSize;
2563  }
2564  else
2565  {
2566  /* Put the tuple into a temp file for later batches */
2567  Assert(batchno > hashtable->curbatch);
2568  ExecHashJoinSaveTuple(tuple, hashvalue,
2569  &hashtable->innerBatchFile[batchno],
2570  hashtable);
2571  pfree(hashTuple);
2572  hashtable->spaceUsed -= tupleSize;
2573  hashtable->spaceUsedSkew -= tupleSize;
2574  }
2575 
2576  hashTuple = nextHashTuple;
2577 
2578  /* allow this loop to be cancellable */
2580  }
2581 
2582  /*
2583  * Free the bucket struct itself and reset the hashtable entry to NULL.
2584  *
2585  * NOTE: this is not nearly as simple as it looks on the surface, because
2586  * of the possibility of collisions in the hashtable. Suppose that hash
2587  * values A and B collide at a particular hashtable entry, and that A was
2588  * entered first so B gets shifted to a different table entry. If we were
2589  * to remove A first then ExecHashGetSkewBucket would mistakenly start
2590  * reporting that B is not in the hashtable, because it would hit the NULL
2591  * before finding B. However, we always remove entries in the reverse
2592  * order of creation, so this failure cannot happen.
2593  */
2594  hashtable->skewBucket[bucketToRemove] = NULL;
2595  hashtable->nSkewBuckets--;
2596  pfree(bucket);
2597  hashtable->spaceUsed -= SKEW_BUCKET_OVERHEAD;
2598  hashtable->spaceUsedSkew -= SKEW_BUCKET_OVERHEAD;
2599 
2600  /*
2601  * If we have removed all skew buckets then give up on skew optimization.
2602  * Release the arrays since they aren't useful any more.
2603  */
2604  if (hashtable->nSkewBuckets == 0)
2605  {
2606  hashtable->skewEnabled = false;
2607  pfree(hashtable->skewBucket);
2608  pfree(hashtable->skewBucketNums);
2609  hashtable->skewBucket = NULL;
2610  hashtable->skewBucketNums = NULL;
2611  hashtable->spaceUsed -= hashtable->spaceUsedSkew;
2612  hashtable->spaceUsedSkew = 0;
2613  }
2614 }
size_t Size
Definition: c.h:608

References Assert, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, HashJoinTableData::curbatch, dense_alloc(), ExecHashGetBucketAndBatch(), ExecHashJoinSaveTuple(), HashSkewBucket::hashvalue, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, HashJoinTableData::innerBatchFile, HashJoinTupleData::next, HashJoinTableData::nSkewBuckets, pfree(), SKEW_BUCKET_OVERHEAD, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketNums, HashJoinTableData::skewEnabled, HashJoinTableData::spaceUsed, HashJoinTableData::spaceUsedSkew, MinimalTupleData::t_len, HashSkewBucket::tuples, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashSkewTableInsert().

◆ ExecHashRetrieveInstrumentation()

void ExecHashRetrieveInstrumentation ( HashState node)

Definition at line 2705 of file nodeHash.c.

2706 {
2707  SharedHashInfo *shared_info = node->shared_info;
2708  size_t size;
2709 
2710  if (shared_info == NULL)
2711  return;
2712 
2713  /* Replace node->shared_info with a copy in backend-local memory. */
2714  size = offsetof(SharedHashInfo, hinstrument) +
2715  shared_info->num_workers * sizeof(HashInstrumentation);
2716  node->shared_info = palloc(size);
2717  memcpy(node->shared_info, shared_info, size);
2718 }
void * palloc(Size size)
Definition: mcxt.c:1317

References SharedHashInfo::num_workers, palloc(), HashState::shared_info, and size.

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecHashSkewTableInsert()

static void ExecHashSkewTableInsert ( HashJoinTable  hashtable,
TupleTableSlot slot,
uint32  hashvalue,
int  bucketNumber 
)
static

Definition at line 2460 of file nodeHash.c.

2464 {
2465  bool shouldFree;
2466  MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
2467  HashJoinTuple hashTuple;
2468  int hashTupleSize;
2469 
2470  /* Create the HashJoinTuple */
2471  hashTupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
2472  hashTuple = (HashJoinTuple) MemoryContextAlloc(hashtable->batchCxt,
2473  hashTupleSize);
2474  hashTuple->hashvalue = hashvalue;
2475  memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
2477 
2478  /* Push it onto the front of the skew bucket's list */
2479  hashTuple->next.unshared = hashtable->skewBucket[bucketNumber]->tuples;
2480  hashtable->skewBucket[bucketNumber]->tuples = hashTuple;
2481  Assert(hashTuple != hashTuple->next.unshared);
2482 
2483  /* Account for space used, and back off if we've used too much */
2484  hashtable->spaceUsed += hashTupleSize;
2485  hashtable->spaceUsedSkew += hashTupleSize;
2486  if (hashtable->spaceUsed > hashtable->spacePeak)
2487  hashtable->spacePeak = hashtable->spaceUsed;
2488  while (hashtable->spaceUsedSkew > hashtable->spaceAllowedSkew)
2489  ExecHashRemoveNextSkewBucket(hashtable);
2490 
2491  /* Check we are not over the total spaceAllowed, either */
2492  if (hashtable->spaceUsed > hashtable->spaceAllowed)
2493  ExecHashIncreaseNumBatches(hashtable);
2494 
2495  if (shouldFree)
2496  heap_free_minimal_tuple(tuple);
2497 }
MinimalTuple ExecFetchSlotMinimalTuple(TupleTableSlot *slot, bool *shouldFree)
Definition: execTuples.c:1779
void heap_free_minimal_tuple(MinimalTuple mtup)
Definition: heaptuple.c:1523
#define HeapTupleHeaderClearMatch(tup)
Definition: htup_details.h:524
static void ExecHashRemoveNextSkewBucket(HashJoinTable hashtable)
Definition: nodeHash.c:2506
static void ExecHashIncreaseNumBatches(HashJoinTable hashtable)
Definition: nodeHash.c:900
Size spaceAllowedSkew
Definition: hashjoin.h:348

References Assert, HashJoinTableData::batchCxt, ExecFetchSlotMinimalTuple(), ExecHashIncreaseNumBatches(), ExecHashRemoveNextSkewBucket(), HashJoinTupleData::hashvalue, heap_free_minimal_tuple(), HeapTupleHeaderClearMatch, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, MemoryContextAlloc(), HashJoinTupleData::next, HashJoinTableData::skewBucket, HashJoinTableData::spaceAllowed, HashJoinTableData::spaceAllowedSkew, HashJoinTableData::spacePeak, HashJoinTableData::spaceUsed, HashJoinTableData::spaceUsedSkew, MinimalTupleData::t_len, HashSkewBucket::tuples, and HashJoinTupleData::unshared.

Referenced by MultiExecPrivateHash().

◆ ExecHashTableCreate()

HashJoinTable ExecHashTableCreate ( HashState state)

Definition at line 447 of file nodeHash.c.

448 {
449  Hash *node;
450  HashJoinTable hashtable;
451  Plan *outerNode;
452  size_t space_allowed;
453  int nbuckets;
454  int nbatch;
455  double rows;
456  int num_skew_mcvs;
457  int log2_nbuckets;
458  MemoryContext oldcxt;
459 
460  /*
461  * Get information about the size of the relation to be hashed (it's the
462  * "outer" subtree of this node, but the inner relation of the hashjoin).
463  * Compute the appropriate size of the hash table.
464  */
465  node = (Hash *) state->ps.plan;
466  outerNode = outerPlan(node);
467 
468  /*
469  * If this is shared hash table with a partial plan, then we can't use
470  * outerNode->plan_rows to estimate its size. We need an estimate of the
471  * total number of rows across all copies of the partial plan.
472  */
473  rows = node->plan.parallel_aware ? node->rows_total : outerNode->plan_rows;
474 
475  ExecChooseHashTableSize(rows, outerNode->plan_width,
476  OidIsValid(node->skewTable),
477  state->parallel_state != NULL,
478  state->parallel_state != NULL ?
479  state->parallel_state->nparticipants - 1 : 0,
480  &space_allowed,
481  &nbuckets, &nbatch, &num_skew_mcvs);
482 
483  /* nbuckets must be a power of 2 */
484  log2_nbuckets = my_log2(nbuckets);
485  Assert(nbuckets == (1 << log2_nbuckets));
486 
487  /*
488  * Initialize the hash table control block.
489  *
490  * The hashtable control block is just palloc'd from the executor's
491  * per-query memory context. Everything else should be kept inside the
492  * subsidiary hashCxt, batchCxt or spillCxt.
493  */
494  hashtable = palloc_object(HashJoinTableData);
495  hashtable->nbuckets = nbuckets;
496  hashtable->nbuckets_original = nbuckets;
497  hashtable->nbuckets_optimal = nbuckets;
498  hashtable->log2_nbuckets = log2_nbuckets;
499  hashtable->log2_nbuckets_optimal = log2_nbuckets;
500  hashtable->buckets.unshared = NULL;
501  hashtable->skewEnabled = false;
502  hashtable->skewBucket = NULL;
503  hashtable->skewBucketLen = 0;
504  hashtable->nSkewBuckets = 0;
505  hashtable->skewBucketNums = NULL;
506  hashtable->nbatch = nbatch;
507  hashtable->curbatch = 0;
508  hashtable->nbatch_original = nbatch;
509  hashtable->nbatch_outstart = nbatch;
510  hashtable->growEnabled = true;
511  hashtable->totalTuples = 0;
512  hashtable->partialTuples = 0;
513  hashtable->skewTuples = 0;
514  hashtable->innerBatchFile = NULL;
515  hashtable->outerBatchFile = NULL;
516  hashtable->spaceUsed = 0;
517  hashtable->spacePeak = 0;
518  hashtable->spaceAllowed = space_allowed;
519  hashtable->spaceUsedSkew = 0;
520  hashtable->spaceAllowedSkew =
521  hashtable->spaceAllowed * SKEW_HASH_MEM_PERCENT / 100;
522  hashtable->chunks = NULL;
523  hashtable->current_chunk = NULL;
524  hashtable->parallel_state = state->parallel_state;
525  hashtable->area = state->ps.state->es_query_dsa;
526  hashtable->batches = NULL;
527 
528 #ifdef HJDEBUG
529  printf("Hashjoin %p: initial nbatch = %d, nbuckets = %d\n",
530  hashtable, nbatch, nbuckets);
531 #endif
532 
533  /*
534  * Create temporary memory contexts in which to keep the hashtable working
535  * storage. See notes in executor/hashjoin.h.
536  */
538  "HashTableContext",
540 
541  hashtable->batchCxt = AllocSetContextCreate(hashtable->hashCxt,
542  "HashBatchContext",
544 
545  hashtable->spillCxt = AllocSetContextCreate(hashtable->hashCxt,
546  "HashSpillContext",
548 
549  /* Allocate data that will live for the life of the hashjoin */
550 
551  oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
552 
553  if (nbatch > 1 && hashtable->parallel_state == NULL)
554  {
555  MemoryContext oldctx;
556 
557  /*
558  * allocate and initialize the file arrays in hashCxt (not needed for
559  * parallel case which uses shared tuplestores instead of raw files)
560  */
561  oldctx = MemoryContextSwitchTo(hashtable->spillCxt);
562 
563  hashtable->innerBatchFile = palloc0_array(BufFile *, nbatch);
564  hashtable->outerBatchFile = palloc0_array(BufFile *, nbatch);
565 
566  MemoryContextSwitchTo(oldctx);
567 
568  /* The files will not be opened until needed... */
569  /* ... but make sure we have temp tablespaces established for them */
571  }
572 
573  MemoryContextSwitchTo(oldcxt);
574 
575  if (hashtable->parallel_state)
576  {
577  ParallelHashJoinState *pstate = hashtable->parallel_state;
578  Barrier *build_barrier;
579 
580  /*
581  * Attach to the build barrier. The corresponding detach operation is
582  * in ExecHashTableDetach. Note that we won't attach to the
583  * batch_barrier for batch 0 yet. We'll attach later and start it out
584  * in PHJ_BATCH_PROBE phase, because batch 0 is allocated up front and
585  * then loaded while hashing (the standard hybrid hash join
586  * algorithm), and we'll coordinate that using build_barrier.
587  */
588  build_barrier = &pstate->build_barrier;
589  BarrierAttach(build_barrier);
590 
591  /*
592  * So far we have no idea whether there are any other participants,
593  * and if so, what phase they are working on. The only thing we care
594  * about at this point is whether someone has already created the
595  * SharedHashJoinBatch objects and the hash table for batch 0. One
596  * backend will be elected to do that now if necessary.
597  */
598  if (BarrierPhase(build_barrier) == PHJ_BUILD_ELECT &&
599  BarrierArriveAndWait(build_barrier, WAIT_EVENT_HASH_BUILD_ELECT))
600  {
601  pstate->nbatch = nbatch;
602  pstate->space_allowed = space_allowed;
603  pstate->growth = PHJ_GROWTH_OK;
604 
605  /* Set up the shared state for coordinating batches. */
606  ExecParallelHashJoinSetUpBatches(hashtable, nbatch);
607 
608  /*
609  * Allocate batch 0's hash table up front so we can load it
610  * directly while hashing.
611  */
612  pstate->nbuckets = nbuckets;
613  ExecParallelHashTableAlloc(hashtable, 0);
614  }
615 
616  /*
617  * The next Parallel Hash synchronization point is in
618  * MultiExecParallelHash(), which will progress it all the way to
619  * PHJ_BUILD_RUN. The caller must not return control from this
620  * executor node between now and then.
621  */
622  }
623  else
624  {
625  /*
626  * Prepare context for the first-scan space allocations; allocate the
627  * hashbucket array therein, and set each bucket "empty".
628  */
629  MemoryContextSwitchTo(hashtable->batchCxt);
630 
631  hashtable->buckets.unshared = palloc0_array(HashJoinTuple, nbuckets);
632 
633  /*
634  * Set up for skew optimization, if possible and there's a need for
635  * more than one batch. (In a one-batch join, there's no point in
636  * it.)
637  */
638  if (nbatch > 1)
639  ExecHashBuildSkewHash(state, hashtable, node, num_skew_mcvs);
640 
641  MemoryContextSwitchTo(oldcxt);
642  }
643 
644  return hashtable;
645 }
int BarrierAttach(Barrier *barrier)
Definition: barrier.c:236
int BarrierPhase(Barrier *barrier)
Definition: barrier.c:265
bool BarrierArriveAndWait(Barrier *barrier, uint32 wait_event_info)
Definition: barrier.c:125
int my_log2(long num)
Definition: dynahash.c:1794
#define palloc_object(type)
Definition: fe_memutils.h:62
@ PHJ_GROWTH_OK
Definition: hashjoin.h:233
#define PHJ_BUILD_ELECT
Definition: hashjoin.h:269
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static void ExecHashBuildSkewHash(HashState *hashstate, HashJoinTable hashtable, Hash *node, int mcvsToUse)
Definition: nodeHash.c:2262
static void ExecParallelHashJoinSetUpBatches(HashJoinTable hashtable, int nbatch)
Definition: nodeHash.c:2983
void ExecParallelHashTableAlloc(HashJoinTable hashtable, int batchno)
Definition: nodeHash.c:3148
ParallelHashJoinBatchAccessor * batches
Definition: hashjoin.h:361
MemoryContext hashCxt
Definition: hashjoin.h:350
double totalTuples
Definition: hashjoin.h:330
double partialTuples
Definition: hashjoin.h:331
ParallelHashJoinState * parallel_state
Definition: hashjoin.h:360
HashMemoryChunk current_chunk
Definition: hashjoin.h:358
dsa_area * area
Definition: hashjoin.h:359
double skewTuples
Definition: hashjoin.h:332
Cardinality rows_total
Definition: plannodes.h:1211
Plan plan
Definition: plannodes.h:1200
ParallelHashGrowth growth
Definition: hashjoin.h:253
bool parallel_aware
Definition: plannodes.h:141
int plan_width
Definition: plannodes.h:136
Cardinality plan_rows
Definition: plannodes.h:135
Definition: regguts.h:323

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierAttach(), BarrierPhase(), HashJoinTableData::batchCxt, HashJoinTableData::batches, HashJoinTableData::buckets, ParallelHashJoinState::build_barrier, HashJoinTableData::chunks, HashJoinTableData::curbatch, HashJoinTableData::current_chunk, CurrentMemoryContext, ExecChooseHashTableSize(), ExecHashBuildSkewHash(), ExecParallelHashJoinSetUpBatches(), ExecParallelHashTableAlloc(), HashJoinTableData::growEnabled, ParallelHashJoinState::growth, HashJoinTableData::hashCxt, HashJoinTableData::innerBatchFile, HashJoinTableData::log2_nbuckets, HashJoinTableData::log2_nbuckets_optimal, MemoryContextSwitchTo(), my_log2(), ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, HashJoinTableData::nbatch_original, HashJoinTableData::nbatch_outstart, ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, HashJoinTableData::nbuckets_optimal, HashJoinTableData::nbuckets_original, HashJoinTableData::nSkewBuckets, OidIsValid, HashJoinTableData::outerBatchFile, outerPlan, palloc0_array, palloc_object, Plan::parallel_aware, HashJoinTableData::parallel_state, HashJoinTableData::partialTuples, PHJ_BUILD_ELECT, PHJ_GROWTH_OK, Hash::plan, Plan::plan_rows, Plan::plan_width, PrepareTempTablespaces(), printf, Hash::rows_total, SKEW_HASH_MEM_PERCENT, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketLen, HashJoinTableData::skewBucketNums, HashJoinTableData::skewEnabled, Hash::skewTable, HashJoinTableData::skewTuples, ParallelHashJoinState::space_allowed, HashJoinTableData::spaceAllowed, HashJoinTableData::spaceAllowedSkew, HashJoinTableData::spacePeak, HashJoinTableData::spaceUsed, HashJoinTableData::spaceUsedSkew, HashJoinTableData::spillCxt, HashJoinTableData::totalTuples, and HashJoinTableData::unshared.

Referenced by ExecHashJoinImpl().

◆ ExecHashTableDestroy()

void ExecHashTableDestroy ( HashJoinTable  hashtable)

Definition at line 867 of file nodeHash.c.

868 {
869  int i;
870 
871  /*
872  * Make sure all the temp files are closed. We skip batch 0, since it
873  * can't have any temp files (and the arrays might not even exist if
874  * nbatch is only 1). Parallel hash joins don't use these files.
875  */
876  if (hashtable->innerBatchFile != NULL)
877  {
878  for (i = 1; i < hashtable->nbatch; i++)
879  {
880  if (hashtable->innerBatchFile[i])
881  BufFileClose(hashtable->innerBatchFile[i]);
882  if (hashtable->outerBatchFile[i])
883  BufFileClose(hashtable->outerBatchFile[i]);
884  }
885  }
886 
887  /* Release working memory (batchCxt is a child, so it goes away too) */
888  MemoryContextDelete(hashtable->hashCxt);
889 
890  /* And drop the control block */
891  pfree(hashtable);
892 }
void BufFileClose(BufFile *file)
Definition: buffile.c:412
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454

References BufFileClose(), HashJoinTableData::hashCxt, i, HashJoinTableData::innerBatchFile, MemoryContextDelete(), HashJoinTableData::nbatch, HashJoinTableData::outerBatchFile, and pfree().

Referenced by ExecEndHashJoin(), and ExecReScanHashJoin().

◆ ExecHashTableDetach()

void ExecHashTableDetach ( HashJoinTable  hashtable)

Definition at line 3260 of file nodeHash.c.

3261 {
3262  ParallelHashJoinState *pstate = hashtable->parallel_state;
3263 
3264  /*
3265  * If we're involved in a parallel query, we must either have gotten all
3266  * the way to PHJ_BUILD_RUN, or joined too late and be in PHJ_BUILD_FREE.
3267  */
3268  Assert(!pstate ||
3270 
3271  if (pstate && BarrierPhase(&pstate->build_barrier) == PHJ_BUILD_RUN)
3272  {
3273  int i;
3274 
3275  /* Make sure any temporary files are closed. */
3276  if (hashtable->batches)
3277  {
3278  for (i = 0; i < hashtable->nbatch; ++i)
3279  {
3280  sts_end_write(hashtable->batches[i].inner_tuples);
3281  sts_end_write(hashtable->batches[i].outer_tuples);
3284  }
3285  }
3286 
3287  /* If we're last to detach, clean up shared memory. */
3288  if (BarrierArriveAndDetach(&pstate->build_barrier))
3289  {
3290  /*
3291  * Late joining processes will see this state and give up
3292  * immediately.
3293  */
3295 
3296  if (DsaPointerIsValid(pstate->batches))
3297  {
3298  dsa_free(hashtable->area, pstate->batches);
3299  pstate->batches = InvalidDsaPointer;
3300  }
3301  }
3302  }
3303  hashtable->parallel_state = NULL;
3304 }
bool BarrierArriveAndDetach(Barrier *barrier)
Definition: barrier.c:203
void dsa_free(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:826
#define InvalidDsaPointer
Definition: dsa.h:78
#define DsaPointerIsValid(x)
Definition: dsa.h:106
#define PHJ_BUILD_FREE
Definition: hashjoin.h:274
#define PHJ_BUILD_RUN
Definition: hashjoin.h:273
void sts_end_write(SharedTuplestoreAccessor *accessor)
void sts_end_parallel_scan(SharedTuplestoreAccessor *accessor)
SharedTuplestoreAccessor * outer_tuples
Definition: hashjoin.h:221
SharedTuplestoreAccessor * inner_tuples
Definition: hashjoin.h:220
dsa_pointer batches
Definition: hashjoin.h:248

References HashJoinTableData::area, Assert, BarrierArriveAndDetach(), BarrierPhase(), ParallelHashJoinState::batches, HashJoinTableData::batches, ParallelHashJoinState::build_barrier, dsa_free(), DsaPointerIsValid, i, ParallelHashJoinBatchAccessor::inner_tuples, InvalidDsaPointer, HashJoinTableData::nbatch, ParallelHashJoinBatchAccessor::outer_tuples, HashJoinTableData::parallel_state, PHJ_BUILD_FREE, PHJ_BUILD_RUN, sts_end_parallel_scan(), and sts_end_write().

Referenced by ExecHashJoinReInitializeDSM(), and ExecShutdownHashJoin().

◆ ExecHashTableDetachBatch()

void ExecHashTableDetachBatch ( HashJoinTable  hashtable)

Definition at line 3168 of file nodeHash.c.

3169 {
3170  if (hashtable->parallel_state != NULL &&
3171  hashtable->curbatch >= 0)
3172  {
3173  int curbatch = hashtable->curbatch;
3174  ParallelHashJoinBatch *batch = hashtable->batches[curbatch].shared;
3175  bool attached = true;
3176 
3177  /* Make sure any temporary files are closed. */
3178  sts_end_parallel_scan(hashtable->batches[curbatch].inner_tuples);
3179  sts_end_parallel_scan(hashtable->batches[curbatch].outer_tuples);
3180 
3181  /* After attaching we always get at least to PHJ_BATCH_PROBE. */
3184 
3185  /*
3186  * If we're abandoning the PHJ_BATCH_PROBE phase early without having
3187  * reached the end of it, it means the plan doesn't want any more
3188  * tuples, and it is happy to abandon any tuples buffered in this
3189  * process's subplans. For correctness, we can't allow any process to
3190  * execute the PHJ_BATCH_SCAN phase, because we will never have the
3191  * complete set of match bits. Therefore we skip emitting unmatched
3192  * tuples in all backends (if this is a full/right join), as if those
3193  * tuples were all due to be emitted by this process and it has
3194  * abandoned them too.
3195  */
3196  if (BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE &&
3197  !hashtable->batches[curbatch].outer_eof)
3198  {
3199  /*
3200  * This flag may be written to by multiple backends during
3201  * PHJ_BATCH_PROBE phase, but will only be read in PHJ_BATCH_SCAN
3202  * phase so requires no extra locking.
3203  */
3204  batch->skip_unmatched = true;
3205  }
3206 
3207  /*
3208  * Even if we aren't doing a full/right outer join, we'll step through
3209  * the PHJ_BATCH_SCAN phase just to maintain the invariant that
3210  * freeing happens in PHJ_BATCH_FREE, but that'll be wait-free.
3211  */
3212  if (BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE)
3213  attached = BarrierArriveAndDetachExceptLast(&batch->batch_barrier);
3214  if (attached && BarrierArriveAndDetach(&batch->batch_barrier))
3215  {
3216  /*
3217  * We are not longer attached to the batch barrier, but we're the
3218  * process that was chosen to free resources and it's safe to
3219  * assert the current phase. The ParallelHashJoinBatch can't go
3220  * away underneath us while we are attached to the build barrier,
3221  * making this access safe.
3222  */
3224 
3225  /* Free shared chunks and buckets. */
3226  while (DsaPointerIsValid(batch->chunks))
3227  {
3229  dsa_get_address(hashtable->area, batch->chunks);
3230  dsa_pointer next = chunk->next.shared;
3231 
3232  dsa_free(hashtable->area, batch->chunks);
3233  batch->chunks = next;
3234  }
3235  if (DsaPointerIsValid(batch->buckets))
3236  {
3237  dsa_free(hashtable->area, batch->buckets);
3238  batch->buckets = InvalidDsaPointer;
3239  }
3240  }
3241 
3242  /*
3243  * Track the largest batch we've been attached to. Though each
3244  * backend might see a different subset of batches, explain.c will
3245  * scan the results from all backends to find the largest value.
3246  */
3247  hashtable->spacePeak =
3248  Max(hashtable->spacePeak,
3249  batch->size + sizeof(dsa_pointer_atomic) * hashtable->nbuckets);
3250 
3251  /* Remember that we are not attached to a batch. */
3252  hashtable->curbatch = -1;
3253  }
3254 }
bool BarrierArriveAndDetachExceptLast(Barrier *barrier)
Definition: barrier.c:213
static int32 next
Definition: blutils.c:222
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:942
uint64 dsa_pointer
Definition: dsa.h:62
#define PHJ_BATCH_SCAN
Definition: hashjoin.h:281
#define PHJ_BATCH_PROBE
Definition: hashjoin.h:280
#define PHJ_BATCH_FREE
Definition: hashjoin.h:282
ParallelHashJoinBatch * shared
Definition: hashjoin.h:209
dsa_pointer chunks
Definition: hashjoin.h:167
dsa_pointer buckets
Definition: hashjoin.h:164

References HashJoinTableData::area, Assert, BarrierArriveAndDetach(), BarrierArriveAndDetachExceptLast(), BarrierPhase(), ParallelHashJoinBatch::batch_barrier, HashJoinTableData::batches, ParallelHashJoinBatch::buckets, chunk, ParallelHashJoinBatch::chunks, HashJoinTableData::curbatch, dsa_free(), dsa_get_address(), DsaPointerIsValid, ParallelHashJoinBatchAccessor::inner_tuples, InvalidDsaPointer, Max, HashJoinTableData::nbuckets, next, ParallelHashJoinBatchAccessor::outer_eof, ParallelHashJoinBatchAccessor::outer_tuples, HashJoinTableData::parallel_state, PHJ_BATCH_FREE, PHJ_BATCH_PROBE, PHJ_BATCH_SCAN, ParallelHashJoinBatchAccessor::shared, ParallelHashJoinBatch::size, ParallelHashJoinBatch::skip_unmatched, HashJoinTableData::spacePeak, and sts_end_parallel_scan().

Referenced by ExecHashJoinReInitializeDSM(), ExecParallelHashJoinNewBatch(), ExecParallelPrepHashTableForUnmatched(), and ExecShutdownHashJoin().

◆ ExecHashTableInsert()

void ExecHashTableInsert ( HashJoinTable  hashtable,
TupleTableSlot slot,
uint32  hashvalue 
)

Definition at line 1608 of file nodeHash.c.

1611 {
1612  bool shouldFree;
1613  MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
1614  int bucketno;
1615  int batchno;
1616 
1617  ExecHashGetBucketAndBatch(hashtable, hashvalue,
1618  &bucketno, &batchno);
1619 
1620  /*
1621  * decide whether to put the tuple in the hash table or a temp file
1622  */
1623  if (batchno == hashtable->curbatch)
1624  {
1625  /*
1626  * put the tuple in hash table
1627  */
1628  HashJoinTuple hashTuple;
1629  int hashTupleSize;
1630  double ntuples = (hashtable->totalTuples - hashtable->skewTuples);
1631 
1632  /* Create the HashJoinTuple */
1633  hashTupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
1634  hashTuple = (HashJoinTuple) dense_alloc(hashtable, hashTupleSize);
1635 
1636  hashTuple->hashvalue = hashvalue;
1637  memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
1638 
1639  /*
1640  * We always reset the tuple-matched flag on insertion. This is okay
1641  * even when reloading a tuple from a batch file, since the tuple
1642  * could not possibly have been matched to an outer tuple before it
1643  * went into the batch file.
1644  */
1646 
1647  /* Push it onto the front of the bucket's list */
1648  hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1649  hashtable->buckets.unshared[bucketno] = hashTuple;
1650 
1651  /*
1652  * Increase the (optimal) number of buckets if we just exceeded the
1653  * NTUP_PER_BUCKET threshold, but only when there's still a single
1654  * batch.
1655  */
1656  if (hashtable->nbatch == 1 &&
1657  ntuples > (hashtable->nbuckets_optimal * NTUP_PER_BUCKET))
1658  {
1659  /* Guard against integer overflow and alloc size overflow */
1660  if (hashtable->nbuckets_optimal <= INT_MAX / 2 &&
1661  hashtable->nbuckets_optimal * 2 <= MaxAllocSize / sizeof(HashJoinTuple))
1662  {
1663  hashtable->nbuckets_optimal *= 2;
1664  hashtable->log2_nbuckets_optimal += 1;
1665  }
1666  }
1667 
1668  /* Account for space used, and back off if we've used too much */
1669  hashtable->spaceUsed += hashTupleSize;
1670  if (hashtable->spaceUsed > hashtable->spacePeak)
1671  hashtable->spacePeak = hashtable->spaceUsed;
1672  if (hashtable->spaceUsed +
1673  hashtable->nbuckets_optimal * sizeof(HashJoinTuple)
1674  > hashtable->spaceAllowed)
1675  ExecHashIncreaseNumBatches(hashtable);
1676  }
1677  else
1678  {
1679  /*
1680  * put the tuple into a temp file for later batches
1681  */
1682  Assert(batchno > hashtable->curbatch);
1683  ExecHashJoinSaveTuple(tuple,
1684  hashvalue,
1685  &hashtable->innerBatchFile[batchno],
1686  hashtable);
1687  }
1688 
1689  if (shouldFree)
1690  heap_free_minimal_tuple(tuple);
1691 }

References Assert, HashJoinTableData::buckets, HashJoinTableData::curbatch, dense_alloc(), ExecFetchSlotMinimalTuple(), ExecHashGetBucketAndBatch(), ExecHashIncreaseNumBatches(), ExecHashJoinSaveTuple(), HashJoinTupleData::hashvalue, heap_free_minimal_tuple(), HeapTupleHeaderClearMatch, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, HashJoinTableData::innerBatchFile, HashJoinTableData::log2_nbuckets_optimal, MaxAllocSize, HashJoinTableData::nbatch, HashJoinTableData::nbuckets_optimal, HashJoinTupleData::next, NTUP_PER_BUCKET, HashJoinTableData::skewTuples, HashJoinTableData::spaceAllowed, HashJoinTableData::spacePeak, HashJoinTableData::spaceUsed, MinimalTupleData::t_len, HashJoinTableData::totalTuples, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashJoinNewBatch(), and MultiExecPrivateHash().

◆ ExecHashTableReset()

void ExecHashTableReset ( HashJoinTable  hashtable)

Definition at line 2186 of file nodeHash.c.

2187 {
2188  MemoryContext oldcxt;
2189  int nbuckets = hashtable->nbuckets;
2190 
2191  /*
2192  * Release all the hash buckets and tuples acquired in the prior pass, and
2193  * reinitialize the context for a new pass.
2194  */
2195  MemoryContextReset(hashtable->batchCxt);
2196  oldcxt = MemoryContextSwitchTo(hashtable->batchCxt);
2197 
2198  /* Reallocate and reinitialize the hash bucket headers. */
2199  hashtable->buckets.unshared = palloc0_array(HashJoinTuple, nbuckets);
2200 
2201  hashtable->spaceUsed = 0;
2202 
2203  MemoryContextSwitchTo(oldcxt);
2204 
2205  /* Forget the chunks (the memory was freed by the context reset above). */
2206  hashtable->chunks = NULL;
2207 }
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383

References HashJoinTableData::batchCxt, HashJoinTableData::buckets, HashJoinTableData::chunks, MemoryContextReset(), MemoryContextSwitchTo(), HashJoinTableData::nbuckets, palloc0_array, HashJoinTableData::spaceUsed, and HashJoinTableData::unshared.

Referenced by ExecHashJoinNewBatch().

◆ ExecHashTableResetMatchFlags()

void ExecHashTableResetMatchFlags ( HashJoinTable  hashtable)

Definition at line 2214 of file nodeHash.c.

2215 {
2216  HashJoinTuple tuple;
2217  int i;
2218 
2219  /* Reset all flags in the main table ... */
2220  for (i = 0; i < hashtable->nbuckets; i++)
2221  {
2222  for (tuple = hashtable->buckets.unshared[i]; tuple != NULL;
2223  tuple = tuple->next.unshared)
2225  }
2226 
2227  /* ... and the same for the skew buckets, if any */
2228  for (i = 0; i < hashtable->nSkewBuckets; i++)
2229  {
2230  int j = hashtable->skewBucketNums[i];
2231  HashSkewBucket *skewBucket = hashtable->skewBucket[j];
2232 
2233  for (tuple = skewBucket->tuples; tuple != NULL; tuple = tuple->next.unshared)
2235  }
2236 }
int j
Definition: isn.c:74

References HashJoinTableData::buckets, HeapTupleHeaderClearMatch, HJTUPLE_MINTUPLE, i, j, HashJoinTableData::nbuckets, HashJoinTupleData::next, HashJoinTableData::nSkewBuckets, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketNums, HashSkewBucket::tuples, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by ExecReScanHashJoin().

◆ ExecInitHash()

HashState* ExecInitHash ( Hash node,
EState estate,
int  eflags 
)

Definition at line 371 of file nodeHash.c.

372 {
373  HashState *hashstate;
374 
375  /* check for unsupported flags */
376  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
377 
378  /*
379  * create state structure
380  */
381  hashstate = makeNode(HashState);
382  hashstate->ps.plan = (Plan *) node;
383  hashstate->ps.state = estate;
384  hashstate->ps.ExecProcNode = ExecHash;
385  /* delay building hashtable until ExecHashTableCreate() in executor run */
386  hashstate->hashtable = NULL;
387 
388  /*
389  * Miscellaneous initialization
390  *
391  * create expression context for node
392  */
393  ExecAssignExprContext(estate, &hashstate->ps);
394 
395  /*
396  * initialize child nodes
397  */
398  outerPlanState(hashstate) = ExecInitNode(outerPlan(node), estate, eflags);
399 
400  /*
401  * initialize our result slot and type. No need to build projection
402  * because this node doesn't do projections.
403  */
405  hashstate->ps.ps_ProjInfo = NULL;
406 
407  Assert(node->plan.qual == NIL);
408 
409  /*
410  * Delay initialization of hash_expr until ExecInitHashJoin(). We cannot
411  * build the ExprState here as we don't yet know the join type we're going
412  * to be hashing values for and we need to know that before calling
413  * ExecBuildHash32Expr as the keep_nulls parameter depends on the join
414  * type.
415  */
416  hashstate->hash_expr = NULL;
417 
418  return hashstate;
419 }
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1886
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:483
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
#define EXEC_FLAG_MARK
Definition: executor.h:69
static TupleTableSlot * ExecHash(PlanState *pstate)
Definition: nodeHash.c:92
#define makeNode(_type_)
Definition: nodes.h:155
#define NIL
Definition: pg_list.h:68
HashJoinTable hashtable
Definition: execnodes.h:2777
ExprState * hash_expr
Definition: execnodes.h:2778
EState * state
Definition: execnodes.h:1125
ProjectionInfo * ps_ProjInfo
Definition: execnodes.h:1163
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1129
List * qual
Definition: plannodes.h:154

References Assert, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, ExecAssignExprContext(), ExecHash(), ExecInitNode(), ExecInitResultTupleSlotTL(), PlanState::ExecProcNode, HashState::hash_expr, HashState::hashtable, makeNode, NIL, outerPlan, outerPlanState, PlanState::plan, Hash::plan, HashState::ps, PlanState::ps_ProjInfo, Plan::qual, PlanState::state, and TTSOpsMinimalTuple.

Referenced by ExecInitNode().

◆ ExecParallelHashCloseBatchAccessors()

static void ExecParallelHashCloseBatchAccessors ( HashJoinTable  hashtable)
static

Definition at line 3063 of file nodeHash.c.

3064 {
3065  int i;
3066 
3067  for (i = 0; i < hashtable->nbatch; ++i)
3068  {
3069  /* Make sure no files are left open. */
3070  sts_end_write(hashtable->batches[i].inner_tuples);
3071  sts_end_write(hashtable->batches[i].outer_tuples);
3074  }
3075  pfree(hashtable->batches);
3076  hashtable->batches = NULL;
3077 }

References HashJoinTableData::batches, i, ParallelHashJoinBatchAccessor::inner_tuples, HashJoinTableData::nbatch, ParallelHashJoinBatchAccessor::outer_tuples, pfree(), sts_end_parallel_scan(), and sts_end_write().

Referenced by ExecParallelHashEnsureBatchAccessors(), and ExecParallelHashIncreaseNumBatches().

◆ ExecParallelHashEnsureBatchAccessors()

static void ExecParallelHashEnsureBatchAccessors ( HashJoinTable  hashtable)
static

Definition at line 3084 of file nodeHash.c.

3085 {
3086  ParallelHashJoinState *pstate = hashtable->parallel_state;
3087  ParallelHashJoinBatch *batches;
3088  MemoryContext oldcxt;
3089  int i;
3090 
3091  if (hashtable->batches != NULL)
3092  {
3093  if (hashtable->nbatch == pstate->nbatch)
3094  return;
3096  }
3097 
3098  /*
3099  * We should never see a state where the batch-tracking array is freed,
3100  * because we should have given up sooner if we join when the build
3101  * barrier has reached the PHJ_BUILD_FREE phase.
3102  */
3103  Assert(DsaPointerIsValid(pstate->batches));
3104 
3105  /*
3106  * Use hash join spill memory context to allocate accessors, including
3107  * buffers for the temporary files.
3108  */
3109  oldcxt = MemoryContextSwitchTo(hashtable->spillCxt);
3110 
3111  /* Allocate this backend's accessor array. */
3112  hashtable->nbatch = pstate->nbatch;
3113  hashtable->batches =
3115 
3116  /* Find the base of the pseudo-array of ParallelHashJoinBatch objects. */
3117  batches = (ParallelHashJoinBatch *)
3118  dsa_get_address(hashtable->area, pstate->batches);
3119 
3120  /* Set up the accessor array and attach to the tuplestores. */
3121  for (i = 0; i < hashtable->nbatch; ++i)
3122  {
3123  ParallelHashJoinBatchAccessor *accessor = &hashtable->batches[i];
3124  ParallelHashJoinBatch *shared = NthParallelHashJoinBatch(batches, i);
3125 
3126  accessor->shared = shared;
3127  accessor->preallocated = 0;
3128  accessor->done = false;
3129  accessor->outer_eof = false;
3130  accessor->inner_tuples =
3133  &pstate->fileset);
3134  accessor->outer_tuples =
3136  pstate->nparticipants),
3138  &pstate->fileset);
3139  }
3140 
3141  MemoryContextSwitchTo(oldcxt);
3142 }
#define ParallelHashJoinBatchInner(batch)
Definition: hashjoin.h:182
#define NthParallelHashJoinBatch(base, n)
Definition: hashjoin.h:198
#define ParallelHashJoinBatchOuter(batch, nparticipants)
Definition: hashjoin.h:187
static void ExecParallelHashCloseBatchAccessors(HashJoinTable hashtable)
Definition: nodeHash.c:3063
SharedTuplestoreAccessor * sts_attach(SharedTuplestore *sts, int my_participant_number, SharedFileSet *fileset)
SharedFileSet fileset
Definition: hashjoin.h:265

References HashJoinTableData::area, Assert, ParallelHashJoinState::batches, HashJoinTableData::batches, ParallelHashJoinBatchAccessor::done, dsa_get_address(), DsaPointerIsValid, ExecParallelHashCloseBatchAccessors(), ParallelHashJoinState::fileset, i, ParallelHashJoinBatchAccessor::inner_tuples, MemoryContextSwitchTo(), ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinState::nparticipants, NthParallelHashJoinBatch, ParallelHashJoinBatchAccessor::outer_eof, ParallelHashJoinBatchAccessor::outer_tuples, palloc0_array, HashJoinTableData::parallel_state, ParallelHashJoinBatchInner, ParallelHashJoinBatchOuter, ParallelWorkerNumber, ParallelHashJoinBatchAccessor::preallocated, ParallelHashJoinBatchAccessor::shared, HashJoinTableData::spillCxt, and sts_attach().

Referenced by ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), and MultiExecParallelHash().

◆ ExecParallelHashFirstTuple()

static HashJoinTuple ExecParallelHashFirstTuple ( HashJoinTable  hashtable,
int  bucketno 
)
inlinestatic

Definition at line 3310 of file nodeHash.c.

3311 {
3312  HashJoinTuple tuple;
3313  dsa_pointer p;
3314 
3315  Assert(hashtable->parallel_state);
3316  p = dsa_pointer_atomic_read(&hashtable->buckets.shared[bucketno]);
3317  tuple = (HashJoinTuple) dsa_get_address(hashtable->area, p);
3318 
3319  return tuple;
3320 }
#define dsa_pointer_atomic_read
Definition: dsa.h:65
dsa_pointer_atomic * shared
Definition: hashjoin.h:313

References HashJoinTableData::area, Assert, HashJoinTableData::buckets, dsa_get_address(), dsa_pointer_atomic_read, HashJoinTableData::parallel_state, and HashJoinTableData::shared.

Referenced by ExecParallelScanHashBucket(), and ExecParallelScanHashTableForUnmatched().

◆ ExecParallelHashIncreaseNumBatches()

static void ExecParallelHashIncreaseNumBatches ( HashJoinTable  hashtable)
static

Definition at line 1064 of file nodeHash.c.

1065 {
1066  ParallelHashJoinState *pstate = hashtable->parallel_state;
1067 
1069 
1070  /*
1071  * It's unlikely, but we need to be prepared for new participants to show
1072  * up while we're in the middle of this operation so we need to switch on
1073  * barrier phase here.
1074  */
1076  {
1078 
1079  /*
1080  * Elect one participant to prepare to grow the number of batches.
1081  * This involves reallocating or resetting the buckets of batch 0
1082  * in preparation for all participants to begin repartitioning the
1083  * tuples.
1084  */
1086  WAIT_EVENT_HASH_GROW_BATCHES_ELECT))
1087  {
1088  dsa_pointer_atomic *buckets;
1089  ParallelHashJoinBatch *old_batch0;
1090  int new_nbatch;
1091  int i;
1092 
1093  /* Move the old batch out of the way. */
1094  old_batch0 = hashtable->batches[0].shared;
1095  pstate->old_batches = pstate->batches;
1096  pstate->old_nbatch = hashtable->nbatch;
1097  pstate->batches = InvalidDsaPointer;
1098 
1099  /* Free this backend's old accessors. */
1101 
1102  /* Figure out how many batches to use. */
1103  if (hashtable->nbatch == 1)
1104  {
1105  /*
1106  * We are going from single-batch to multi-batch. We need
1107  * to switch from one large combined memory budget to the
1108  * regular hash_mem budget.
1109  */
1111 
1112  /*
1113  * The combined hash_mem of all participants wasn't
1114  * enough. Therefore one batch per participant would be
1115  * approximately equivalent and would probably also be
1116  * insufficient. So try two batches per participant,
1117  * rounded up to a power of two.
1118  */
1119  new_nbatch = pg_nextpower2_32(pstate->nparticipants * 2);
1120  }
1121  else
1122  {
1123  /*
1124  * We were already multi-batched. Try doubling the number
1125  * of batches.
1126  */
1127  new_nbatch = hashtable->nbatch * 2;
1128  }
1129 
1130  /* Allocate new larger generation of batches. */
1131  Assert(hashtable->nbatch == pstate->nbatch);
1132  ExecParallelHashJoinSetUpBatches(hashtable, new_nbatch);
1133  Assert(hashtable->nbatch == pstate->nbatch);
1134 
1135  /* Replace or recycle batch 0's bucket array. */
1136  if (pstate->old_nbatch == 1)
1137  {
1138  double dtuples;
1139  double dbuckets;
1140  int new_nbuckets;
1141  uint32 max_buckets;
1142 
1143  /*
1144  * We probably also need a smaller bucket array. How many
1145  * tuples do we expect per batch, assuming we have only
1146  * half of them so far? Normally we don't need to change
1147  * the bucket array's size, because the size of each batch
1148  * stays the same as we add more batches, but in this
1149  * special case we move from a large batch to many smaller
1150  * batches and it would be wasteful to keep the large
1151  * array.
1152  */
1153  dtuples = (old_batch0->ntuples * 2.0) / new_nbatch;
1154 
1155  /*
1156  * We need to calculate the maximum number of buckets to
1157  * stay within the MaxAllocSize boundary. Round the
1158  * maximum number to the previous power of 2 given that
1159  * later we round the number to the next power of 2.
1160  */
1161  max_buckets = pg_prevpower2_32((uint32)
1162  (MaxAllocSize / sizeof(dsa_pointer_atomic)));
1163  dbuckets = ceil(dtuples / NTUP_PER_BUCKET);
1164  dbuckets = Min(dbuckets, max_buckets);
1165  new_nbuckets = (int) dbuckets;
1166  new_nbuckets = Max(new_nbuckets, 1024);
1167  new_nbuckets = pg_nextpower2_32(new_nbuckets);
1168  dsa_free(hashtable->area, old_batch0->buckets);
1169  hashtable->batches[0].shared->buckets =
1170  dsa_allocate(hashtable->area,
1171  sizeof(dsa_pointer_atomic) * new_nbuckets);
1172  buckets = (dsa_pointer_atomic *)
1173  dsa_get_address(hashtable->area,
1174  hashtable->batches[0].shared->buckets);
1175  for (i = 0; i < new_nbuckets; ++i)
1177  pstate->nbuckets = new_nbuckets;
1178  }
1179  else
1180  {
1181  /* Recycle the existing bucket array. */
1182  hashtable->batches[0].shared->buckets = old_batch0->buckets;
1183  buckets = (dsa_pointer_atomic *)
1184  dsa_get_address(hashtable->area, old_batch0->buckets);
1185  for (i = 0; i < hashtable->nbuckets; ++i)
1187  }
1188 
1189  /* Move all chunks to the work queue for parallel processing. */
1190  pstate->chunk_work_queue = old_batch0->chunks;
1191 
1192  /* Disable further growth temporarily while we're growing. */
1193  pstate->growth = PHJ_GROWTH_DISABLED;
1194  }
1195  else
1196  {
1197  /* All other participants just flush their tuples to disk. */
1199  }
1200  /* Fall through. */
1201 
1203  /* Wait for the above to be finished. */
1205  WAIT_EVENT_HASH_GROW_BATCHES_REALLOCATE);
1206  /* Fall through. */
1207 
1209  /* Make sure that we have the current dimensions and buckets. */
1212  /* Then partition, flush counters. */
1215  ExecParallelHashMergeCounters(hashtable);
1216  /* Wait for the above to be finished. */
1218  WAIT_EVENT_HASH_GROW_BATCHES_REPARTITION);
1219  /* Fall through. */
1220 
1222 
1223  /*
1224  * Elect one participant to clean up and decide whether further
1225  * repartitioning is needed, or should be disabled because it's
1226  * not helping.
1227  */
1229  WAIT_EVENT_HASH_GROW_BATCHES_DECIDE))
1230  {
1231  bool space_exhausted = false;
1232  bool extreme_skew_detected = false;
1233 
1234  /* Make sure that we have the current dimensions and buckets. */
1237 
1238  /* Are any of the new generation of batches exhausted? */
1239  for (int i = 0; i < hashtable->nbatch; ++i)
1240  {
1241  ParallelHashJoinBatch *batch = hashtable->batches[i].shared;
1242 
1243  if (batch->space_exhausted ||
1244  batch->estimated_size > pstate->space_allowed)
1245  {
1246  int parent;
1247 
1248  space_exhausted = true;
1249 
1250  /*
1251  * Did this batch receive ALL of the tuples from its
1252  * parent batch? That would indicate that further
1253  * repartitioning isn't going to help (the hash values
1254  * are probably all the same).
1255  */
1256  parent = i % pstate->old_nbatch;
1257  if (batch->ntuples == hashtable->batches[parent].shared->old_ntuples)
1258  extreme_skew_detected = true;
1259  }
1260  }
1261 
1262  /* Don't keep growing if it's not helping or we'd overflow. */
1263  if (extreme_skew_detected || hashtable->nbatch >= INT_MAX / 2)
1264  pstate->growth = PHJ_GROWTH_DISABLED;
1265  else if (space_exhausted)
1267  else
1268  pstate->growth = PHJ_GROWTH_OK;
1269 
1270  /* Free the old batches in shared memory. */
1271  dsa_free(hashtable->area, pstate->old_batches);
1272  pstate->old_batches = InvalidDsaPointer;
1273  }
1274  /* Fall through. */
1275 
1277  /* Wait for the above to complete. */
1279  WAIT_EVENT_HASH_GROW_BATCHES_FINISH);
1280  }
1281 }
#define dsa_pointer_atomic_init
Definition: dsa.h:64
#define dsa_allocate(area, size)
Definition: dsa.h:109
#define dsa_pointer_atomic_write
Definition: dsa.h:66
#define PHJ_GROW_BATCHES_REPARTITION
Definition: hashjoin.h:287
#define PHJ_GROW_BATCHES_ELECT
Definition: hashjoin.h:285
#define PHJ_BUILD_HASH_INNER
Definition: hashjoin.h:271
#define PHJ_GROW_BATCHES_DECIDE
Definition: hashjoin.h:288
#define PHJ_GROW_BATCHES_REALLOCATE
Definition: hashjoin.h:286
#define PHJ_GROW_BATCHES_FINISH
Definition: hashjoin.h:289
#define PHJ_GROW_BATCHES_PHASE(n)
Definition: hashjoin.h:290
@ PHJ_GROWTH_NEED_MORE_BATCHES
Definition: hashjoin.h:237
@ PHJ_GROWTH_DISABLED
Definition: hashjoin.h:239
void ExecParallelHashTableSetCurrentBatch(HashJoinTable hashtable, int batchno)
Definition: nodeHash.c:3358
static void ExecParallelHashEnsureBatchAccessors(HashJoinTable hashtable)
Definition: nodeHash.c:3084
static void ExecParallelHashRepartitionRest(HashJoinTable hashtable)
Definition: nodeHash.c:1356
static void ExecParallelHashMergeCounters(HashJoinTable hashtable)
Definition: nodeHash.c:1416
static void ExecParallelHashRepartitionFirst(HashJoinTable hashtable)
Definition: nodeHash.c:1289
static uint32 pg_prevpower2_32(uint32 num)
Definition: pg_bitutils.h:235
Barrier grow_batches_barrier
Definition: hashjoin.h:261
dsa_pointer old_batches
Definition: hashjoin.h:249
dsa_pointer chunk_work_queue
Definition: hashjoin.h:254

References HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierPhase(), ParallelHashJoinState::batches, HashJoinTableData::batches, ParallelHashJoinBatch::buckets, ParallelHashJoinState::build_barrier, ParallelHashJoinState::chunk_work_queue, ParallelHashJoinBatch::chunks, dsa_allocate, dsa_free(), dsa_get_address(), dsa_pointer_atomic_init, dsa_pointer_atomic_write, ParallelHashJoinBatch::estimated_size, ExecParallelHashCloseBatchAccessors(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashJoinSetUpBatches(), ExecParallelHashMergeCounters(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecParallelHashTableSetCurrentBatch(), get_hash_memory_limit(), ParallelHashJoinState::grow_batches_barrier, ParallelHashJoinState::growth, i, InvalidDsaPointer, Max, MaxAllocSize, Min, ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, ParallelHashJoinState::nparticipants, NTUP_PER_BUCKET, ParallelHashJoinBatch::ntuples, ParallelHashJoinState::old_batches, ParallelHashJoinState::old_nbatch, ParallelHashJoinBatch::old_ntuples, HashJoinTableData::parallel_state, pg_nextpower2_32(), pg_prevpower2_32(), PHJ_BUILD_HASH_INNER, PHJ_GROW_BATCHES_DECIDE, PHJ_GROW_BATCHES_ELECT, PHJ_GROW_BATCHES_FINISH, PHJ_GROW_BATCHES_PHASE, PHJ_GROW_BATCHES_REALLOCATE, PHJ_GROW_BATCHES_REPARTITION, PHJ_GROWTH_DISABLED, PHJ_GROWTH_NEED_MORE_BATCHES, PHJ_GROWTH_OK, ParallelHashJoinBatchAccessor::shared, ParallelHashJoinState::space_allowed, and ParallelHashJoinBatch::space_exhausted.

Referenced by ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), and MultiExecParallelHash().

◆ ExecParallelHashIncreaseNumBuckets()

static void ExecParallelHashIncreaseNumBuckets ( HashJoinTable  hashtable)
static

Definition at line 1509 of file nodeHash.c.

1510 {
1511  ParallelHashJoinState *pstate = hashtable->parallel_state;
1512  int i;
1514  dsa_pointer chunk_s;
1515 
1517 
1518  /*
1519  * It's unlikely, but we need to be prepared for new participants to show
1520  * up while we're in the middle of this operation so we need to switch on
1521  * barrier phase here.
1522  */
1524  {
1526  /* Elect one participant to prepare to increase nbuckets. */
1528  WAIT_EVENT_HASH_GROW_BUCKETS_ELECT))
1529  {
1530  size_t size;
1531  dsa_pointer_atomic *buckets;
1532 
1533  /* Double the size of the bucket array. */
1534  pstate->nbuckets *= 2;
1535  size = pstate->nbuckets * sizeof(dsa_pointer_atomic);
1536  hashtable->batches[0].shared->size += size / 2;
1537  dsa_free(hashtable->area, hashtable->batches[0].shared->buckets);
1538  hashtable->batches[0].shared->buckets =
1539  dsa_allocate(hashtable->area, size);
1540  buckets = (dsa_pointer_atomic *)
1541  dsa_get_address(hashtable->area,
1542  hashtable->batches[0].shared->buckets);
1543  for (i = 0; i < pstate->nbuckets; ++i)
1545 
1546  /* Put the chunk list onto the work queue. */
1547  pstate->chunk_work_queue = hashtable->batches[0].shared->chunks;
1548 
1549  /* Clear the flag. */
1550  pstate->growth = PHJ_GROWTH_OK;
1551  }
1552  /* Fall through. */
1553 
1555  /* Wait for the above to complete. */
1557  WAIT_EVENT_HASH_GROW_BUCKETS_REALLOCATE);
1558  /* Fall through. */
1559 
1561  /* Reinsert all tuples into the hash table. */
1564  while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_s)))
1565  {
1566  size_t idx = 0;
1567 
1568  while (idx < chunk->used)
1569  {
1571  dsa_pointer shared = chunk_s + HASH_CHUNK_HEADER_SIZE + idx;
1572  int bucketno;
1573  int batchno;
1574 
1575  ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1576  &bucketno, &batchno);
1577  Assert(batchno == 0);
1578 
1579  /* add the tuple to the proper bucket */
1580  ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
1581  hashTuple, shared);
1582 
1583  /* advance index past the tuple */
1585  HJTUPLE_MINTUPLE(hashTuple)->t_len);
1586  }
1587 
1588  /* allow this loop to be cancellable */
1590  }
1592  WAIT_EVENT_HASH_GROW_BUCKETS_REINSERT);
1593  }
1594 }
pg_atomic_uint64 dsa_pointer_atomic
Definition: dsa.h:63
#define PHJ_GROW_BUCKETS_REINSERT
Definition: hashjoin.h:295
#define PHJ_GROW_BUCKETS_ELECT
Definition: hashjoin.h:293
#define PHJ_GROW_BUCKETS_PHASE(n)
Definition: hashjoin.h:296
#define PHJ_GROW_BUCKETS_REALLOCATE
Definition: hashjoin.h:294
static void ExecParallelHashPushTuple(dsa_pointer_atomic *head, HashJoinTuple tuple, dsa_pointer tuple_shared)
Definition: nodeHash.c:3340
static HashMemoryChunk ExecParallelHashPopChunkQueue(HashJoinTable hashtable, dsa_pointer *shared)
Definition: nodeHash.c:3379
Barrier grow_buckets_barrier
Definition: hashjoin.h:262

References HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinBatch::buckets, HashJoinTableData::buckets, ParallelHashJoinState::build_barrier, CHECK_FOR_INTERRUPTS, chunk, ParallelHashJoinState::chunk_work_queue, ParallelHashJoinBatch::chunks, dsa_allocate, dsa_free(), dsa_get_address(), dsa_pointer_atomic_init, ExecHashGetBucketAndBatch(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashPopChunkQueue(), ExecParallelHashPushTuple(), ExecParallelHashTableSetCurrentBatch(), ParallelHashJoinState::grow_buckets_barrier, ParallelHashJoinState::growth, HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HashJoinTupleData::hashvalue, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, i, idx(), InvalidDsaPointer, MAXALIGN, ParallelHashJoinState::nbuckets, HashJoinTableData::parallel_state, PHJ_BUILD_HASH_INNER, PHJ_GROW_BUCKETS_ELECT, PHJ_GROW_BUCKETS_PHASE, PHJ_GROW_BUCKETS_REALLOCATE, PHJ_GROW_BUCKETS_REINSERT, PHJ_GROWTH_OK, ParallelHashJoinBatchAccessor::shared, HashJoinTableData::shared, size, and ParallelHashJoinBatch::size.

Referenced by ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), and MultiExecParallelHash().

◆ ExecParallelHashJoinSetUpBatches()

static void ExecParallelHashJoinSetUpBatches ( HashJoinTable  hashtable,
int  nbatch 
)
static

Definition at line 2983 of file nodeHash.c.

2984 {
2985  ParallelHashJoinState *pstate = hashtable->parallel_state;
2986  ParallelHashJoinBatch *batches;
2987  MemoryContext oldcxt;
2988  int i;
2989 
2990  Assert(hashtable->batches == NULL);
2991 
2992  /* Allocate space. */
2993  pstate->batches =
2994  dsa_allocate0(hashtable->area,
2995  EstimateParallelHashJoinBatch(hashtable) * nbatch);
2996  pstate->nbatch = nbatch;
2997  batches = dsa_get_address(hashtable->area, pstate->batches);
2998 
2999  /*
3000  * Use hash join spill memory context to allocate accessors, including
3001  * buffers for the temporary files.
3002  */
3003  oldcxt = MemoryContextSwitchTo(hashtable->spillCxt);
3004 
3005  /* Allocate this backend's accessor array. */
3006  hashtable->nbatch = nbatch;
3007  hashtable->batches =
3009 
3010  /* Set up the shared state, tuplestores and backend-local accessors. */
3011  for (i = 0; i < hashtable->nbatch; ++i)
3012  {
3013  ParallelHashJoinBatchAccessor *accessor = &hashtable->batches[i];
3014  ParallelHashJoinBatch *shared = NthParallelHashJoinBatch(batches, i);
3015  char name[MAXPGPATH];
3016 
3017  /*
3018  * All members of shared were zero-initialized. We just need to set
3019  * up the Barrier.
3020  */
3021  BarrierInit(&shared->batch_barrier, 0);
3022  if (i == 0)
3023  {
3024  /* Batch 0 doesn't need to be loaded. */
3025  BarrierAttach(&shared->batch_barrier);
3026  while (BarrierPhase(&shared->batch_barrier) < PHJ_BATCH_PROBE)
3027  BarrierArriveAndWait(&shared->batch_barrier, 0);
3028  BarrierDetach(&shared->batch_barrier);
3029  }
3030 
3031  /* Initialize accessor state. All members were zero-initialized. */
3032  accessor->shared = shared;
3033 
3034  /* Initialize the shared tuplestores. */
3035  snprintf(name, sizeof(name), "i%dof%d", i, hashtable->nbatch);
3036  accessor->inner_tuples =
3038  pstate->nparticipants,
3040  sizeof(uint32),
3042  &pstate->fileset,
3043  name);
3044  snprintf(name, sizeof(name), "o%dof%d", i, hashtable->nbatch);
3045  accessor->outer_tuples =
3047  pstate->nparticipants),
3048  pstate->nparticipants,
3050  sizeof(uint32),
3052  &pstate->fileset,
3053  name);
3054  }
3055 
3056  MemoryContextSwitchTo(oldcxt);
3057 }
void BarrierInit(Barrier *barrier, int participants)
Definition: barrier.c:100
bool BarrierDetach(Barrier *barrier)
Definition: barrier.c:256
#define dsa_allocate0(area, size)
Definition: dsa.h:113
#define EstimateParallelHashJoinBatch(hashtable)
Definition: hashjoin.h:193
#define MAXPGPATH
#define snprintf
Definition: port.h:238
SharedTuplestoreAccessor * sts_initialize(SharedTuplestore *sts, int participants, int my_participant_number, size_t meta_data_size, int flags, SharedFileSet *fileset, const char *name)
#define SHARED_TUPLESTORE_SINGLE_PASS
const char * name

References HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierAttach(), BarrierDetach(), BarrierInit(), BarrierPhase(), ParallelHashJoinBatch::batch_barrier, ParallelHashJoinState::batches, HashJoinTableData::batches, dsa_allocate0, dsa_get_address(), EstimateParallelHashJoinBatch, ParallelHashJoinState::fileset, i, ParallelHashJoinBatchAccessor::inner_tuples, MAXPGPATH, MemoryContextSwitchTo(), name, ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinState::nparticipants, NthParallelHashJoinBatch, ParallelHashJoinBatchAccessor::outer_tuples, palloc0_array, HashJoinTableData::parallel_state, ParallelHashJoinBatchInner, ParallelHashJoinBatchOuter, ParallelWorkerNumber, PHJ_BATCH_PROBE, ParallelHashJoinBatchAccessor::shared, SHARED_TUPLESTORE_SINGLE_PASS, snprintf, HashJoinTableData::spillCxt, and sts_initialize().

Referenced by ExecHashTableCreate(), and ExecParallelHashIncreaseNumBatches().

◆ ExecParallelHashMergeCounters()

static void ExecParallelHashMergeCounters ( HashJoinTable  hashtable)
static

Definition at line 1416 of file nodeHash.c.

1417 {
1418  ParallelHashJoinState *pstate = hashtable->parallel_state;
1419  int i;
1420 
1421  LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
1422  pstate->total_tuples = 0;
1423  for (i = 0; i < hashtable->nbatch; ++i)
1424  {
1425  ParallelHashJoinBatchAccessor *batch = &hashtable->batches[i];
1426 
1427  batch->shared->size += batch->size;
1428  batch->shared->estimated_size += batch->estimated_size;
1429  batch->shared->ntuples += batch->ntuples;
1430  batch->shared->old_ntuples += batch->old_ntuples;
1431  batch->size = 0;
1432  batch->estimated_size = 0;
1433  batch->ntuples = 0;
1434  batch->old_ntuples = 0;
1435  pstate->total_tuples += batch->shared->ntuples;
1436  }
1437  LWLockRelease(&pstate->lock);
1438 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_EXCLUSIVE
Definition: lwlock.h:114

References HashJoinTableData::batches, ParallelHashJoinBatch::estimated_size, ParallelHashJoinBatchAccessor::estimated_size, i, ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), HashJoinTableData::nbatch, ParallelHashJoinBatch::ntuples, ParallelHashJoinBatchAccessor::ntuples, ParallelHashJoinBatch::old_ntuples, ParallelHashJoinBatchAccessor::old_ntuples, HashJoinTableData::parallel_state, ParallelHashJoinBatchAccessor::shared, ParallelHashJoinBatch::size, ParallelHashJoinBatchAccessor::size, and ParallelHashJoinState::total_tuples.

Referenced by ExecParallelHashIncreaseNumBatches(), and MultiExecParallelHash().

◆ ExecParallelHashNextTuple()

static HashJoinTuple ExecParallelHashNextTuple ( HashJoinTable  hashtable,
HashJoinTuple  tuple 
)
inlinestatic

Definition at line 3326 of file nodeHash.c.

3327 {
3329 
3330  Assert(hashtable->parallel_state);
3331  next = (HashJoinTuple) dsa_get_address(hashtable->area, tuple->next.shared);
3332 
3333  return next;
3334 }
dsa_pointer shared
Definition: hashjoin.h:84

References HashJoinTableData::area, Assert, dsa_get_address(), next, HashJoinTupleData::next, HashJoinTableData::parallel_state, and HashJoinTupleData::shared.

Referenced by ExecParallelScanHashBucket(), and ExecParallelScanHashTableForUnmatched().

◆ ExecParallelHashPopChunkQueue()

static HashMemoryChunk ExecParallelHashPopChunkQueue ( HashJoinTable  hashtable,
dsa_pointer shared 
)
static

Definition at line 3379 of file nodeHash.c.

3380 {
3381  ParallelHashJoinState *pstate = hashtable->parallel_state;
3383 
3384  LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
3385  if (DsaPointerIsValid(pstate->chunk_work_queue))
3386  {
3387  *shared = pstate->chunk_work_queue;
3389  dsa_get_address(hashtable->area, *shared);
3390  pstate->chunk_work_queue = chunk->next.shared;
3391  }
3392  else
3393  chunk = NULL;
3394  LWLockRelease(&pstate->lock);
3395 
3396  return chunk;
3397 }

References HashJoinTableData::area, chunk, ParallelHashJoinState::chunk_work_queue, dsa_get_address(), DsaPointerIsValid, ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), and HashJoinTableData::parallel_state.

Referenced by ExecParallelHashIncreaseNumBuckets(), and ExecParallelHashRepartitionFirst().

◆ ExecParallelHashPushTuple()

static void ExecParallelHashPushTuple ( dsa_pointer_atomic head,
HashJoinTuple  tuple,
dsa_pointer  tuple_shared 
)
inlinestatic

Definition at line 3340 of file nodeHash.c.

3343 {
3344  for (;;)
3345  {
3346  tuple->next.shared = dsa_pointer_atomic_read(head);
3348  &tuple->next.shared,
3349  tuple_shared))
3350  break;
3351  }
3352 }
#define dsa_pointer_atomic_compare_exchange
Definition: dsa.h:68

References dsa_pointer_atomic_compare_exchange, dsa_pointer_atomic_read, HashJoinTupleData::next, and HashJoinTupleData::shared.

Referenced by ExecParallelHashIncreaseNumBuckets(), ExecParallelHashRepartitionFirst(), ExecParallelHashTableInsert(), and ExecParallelHashTableInsertCurrentBatch().

◆ ExecParallelHashRepartitionFirst()

static void ExecParallelHashRepartitionFirst ( HashJoinTable  hashtable)
static

Definition at line 1289 of file nodeHash.c.

1290 {
1291  dsa_pointer chunk_shared;
1293 
1294  Assert(hashtable->nbatch == hashtable->parallel_state->nbatch);
1295 
1296  while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_shared)))
1297  {
1298  size_t idx = 0;
1299 
1300  /* Repartition all tuples in this chunk. */
1301  while (idx < chunk->used)
1302  {
1304  MinimalTuple tuple = HJTUPLE_MINTUPLE(hashTuple);
1305  HashJoinTuple copyTuple;
1306  dsa_pointer shared;
1307  int bucketno;
1308  int batchno;
1309 
1310  ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1311  &bucketno, &batchno);
1312 
1313  Assert(batchno < hashtable->nbatch);
1314  if (batchno == 0)
1315  {
1316  /* It still belongs in batch 0. Copy to a new chunk. */
1317  copyTuple =
1318  ExecParallelHashTupleAlloc(hashtable,
1319  HJTUPLE_OVERHEAD + tuple->t_len,
1320  &shared);
1321  copyTuple->hashvalue = hashTuple->hashvalue;
1322  memcpy(HJTUPLE_MINTUPLE(copyTuple), tuple, tuple->t_len);
1323  ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
1324  copyTuple, shared);
1325  }
1326  else
1327  {
1328  size_t tuple_size =
1329  MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
1330 
1331  /* It belongs in a later batch. */
1332  hashtable->batches[batchno].estimated_size += tuple_size;
1333  sts_puttuple(hashtable->batches[batchno].inner_tuples,
1334  &hashTuple->hashvalue, tuple);
1335  }
1336 
1337  /* Count this tuple. */
1338  ++hashtable->batches[0].old_ntuples;
1339  ++hashtable->batches[batchno].ntuples;
1340 
1342  HJTUPLE_MINTUPLE(hashTuple)->t_len);
1343  }
1344 
1345  /* Free this chunk. */
1346  dsa_free(hashtable->area, chunk_shared);
1347 
1349  }
1350 }
static HashJoinTuple ExecParallelHashTupleAlloc(HashJoinTable hashtable, size_t size, dsa_pointer *shared)
Definition: nodeHash.c:2835
void sts_puttuple(SharedTuplestoreAccessor *accessor, void *meta_data, MinimalTuple tuple)

References HashJoinTableData::area, Assert, HashJoinTableData::batches, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, chunk, dsa_free(), ParallelHashJoinBatchAccessor::estimated_size, ExecHashGetBucketAndBatch(), ExecParallelHashPopChunkQueue(), ExecParallelHashPushTuple(), ExecParallelHashTupleAlloc(), HASH_CHUNK_DATA, HashJoinTupleData::hashvalue, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, idx(), ParallelHashJoinBatchAccessor::inner_tuples, MAXALIGN, ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinBatchAccessor::ntuples, ParallelHashJoinBatchAccessor::old_ntuples, HashJoinTableData::parallel_state, HashJoinTableData::shared, sts_puttuple(), and MinimalTupleData::t_len.

Referenced by ExecParallelHashIncreaseNumBatches().

◆ ExecParallelHashRepartitionRest()

static void ExecParallelHashRepartitionRest ( HashJoinTable  hashtable)
static

Definition at line 1356 of file nodeHash.c.

1357 {
1358  ParallelHashJoinState *pstate = hashtable->parallel_state;
1359  int old_nbatch = pstate->old_nbatch;
1360  SharedTuplestoreAccessor **old_inner_tuples;
1361  ParallelHashJoinBatch *old_batches;
1362  int i;
1363 
1364  /* Get our hands on the previous generation of batches. */
1365  old_batches = (ParallelHashJoinBatch *)
1366  dsa_get_address(hashtable->area, pstate->old_batches);
1367  old_inner_tuples = palloc0_array(SharedTuplestoreAccessor *, old_nbatch);
1368  for (i = 1; i < old_nbatch; ++i)
1369  {
1370  ParallelHashJoinBatch *shared =
1371  NthParallelHashJoinBatch(old_batches, i);
1372 
1373  old_inner_tuples[i] = sts_attach(ParallelHashJoinBatchInner(shared),
1375  &pstate->fileset);
1376  }
1377 
1378  /* Join in the effort to repartition them. */
1379  for (i = 1; i < old_nbatch; ++i)
1380  {
1381  MinimalTuple tuple;
1382  uint32 hashvalue;
1383 
1384  /* Scan one partition from the previous generation. */
1385  sts_begin_parallel_scan(old_inner_tuples[i]);
1386  while ((tuple = sts_parallel_scan_next(old_inner_tuples[i], &hashvalue)))
1387  {
1388  size_t tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
1389  int bucketno;
1390  int batchno;
1391 
1392  /* Decide which partition it goes to in the new generation. */
1393  ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno,
1394  &batchno);
1395 
1396  hashtable->batches[batchno].estimated_size += tuple_size;
1397  ++hashtable->batches[batchno].ntuples;
1398  ++hashtable->batches[i].old_ntuples;
1399 
1400  /* Store the tuple its new batch. */
1401  sts_puttuple(hashtable->batches[batchno].inner_tuples,
1402  &hashvalue, tuple);
1403 
1405  }
1406  sts_end_parallel_scan(old_inner_tuples[i]);
1407  }
1408 
1409  pfree(old_inner_tuples);
1410 }
MinimalTuple sts_parallel_scan_next(SharedTuplestoreAccessor *accessor, void *meta_data)
void sts_begin_parallel_scan(SharedTuplestoreAccessor *accessor)

References HashJoinTableData::area, HashJoinTableData::batches, CHECK_FOR_INTERRUPTS, dsa_get_address(), ParallelHashJoinBatchAccessor::estimated_size, ExecHashGetBucketAndBatch(), ParallelHashJoinState::fileset, HJTUPLE_OVERHEAD, i, ParallelHashJoinBatchAccessor::inner_tuples, MAXALIGN, NthParallelHashJoinBatch, ParallelHashJoinBatchAccessor::ntuples, ParallelHashJoinState::old_batches, ParallelHashJoinState::old_nbatch, ParallelHashJoinBatchAccessor::old_ntuples, palloc0_array, HashJoinTableData::parallel_state, ParallelHashJoinBatchInner, ParallelWorkerNumber, pfree(), sts_attach(), sts_begin_parallel_scan(), sts_end_parallel_scan(), sts_parallel_scan_next(), sts_puttuple(), and MinimalTupleData::t_len.

Referenced by ExecParallelHashIncreaseNumBatches().

◆ ExecParallelHashTableAlloc()

void ExecParallelHashTableAlloc ( HashJoinTable  hashtable,
int  batchno 
)

Definition at line 3148 of file nodeHash.c.

3149 {
3150  ParallelHashJoinBatch *batch = hashtable->batches[batchno].shared;
3151  dsa_pointer_atomic *buckets;
3152  int nbuckets = hashtable->parallel_state->nbuckets;
3153  int i;
3154 
3155  batch->buckets =
3156  dsa_allocate(hashtable->area, sizeof(dsa_pointer_atomic) * nbuckets);
3157  buckets = (dsa_pointer_atomic *)
3158  dsa_get_address(hashtable->area, batch->buckets);
3159  for (i = 0; i < nbuckets; ++i)
3161 }

References HashJoinTableData::area, HashJoinTableData::batches, ParallelHashJoinBatch::buckets, dsa_allocate, dsa_get_address(), dsa_pointer_atomic_init, i, InvalidDsaPointer, ParallelHashJoinState::nbuckets, HashJoinTableData::parallel_state, and ParallelHashJoinBatchAccessor::shared.

Referenced by ExecHashTableCreate(), and ExecParallelHashJoinNewBatch().

◆ ExecParallelHashTableInsert()

void ExecParallelHashTableInsert ( HashJoinTable  hashtable,
TupleTableSlot slot,
uint32  hashvalue 
)

Definition at line 1698 of file nodeHash.c.

1701 {
1702  bool shouldFree;
1703  MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
1704  dsa_pointer shared;
1705  int bucketno;
1706  int batchno;
1707 
1708 retry:
1709  ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
1710 
1711  if (batchno == 0)
1712  {
1713  HashJoinTuple hashTuple;
1714 
1715  /* Try to load it into memory. */
1718  hashTuple = ExecParallelHashTupleAlloc(hashtable,
1719  HJTUPLE_OVERHEAD + tuple->t_len,
1720  &shared);
1721  if (hashTuple == NULL)
1722  goto retry;
1723 
1724  /* Store the hash value in the HashJoinTuple header. */
1725  hashTuple->hashvalue = hashvalue;
1726  memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
1728 
1729  /* Push it onto the front of the bucket's list */
1730  ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
1731  hashTuple, shared);
1732  }
1733  else
1734  {
1735  size_t tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
1736 
1737  Assert(batchno > 0);
1738 
1739  /* Try to preallocate space in the batch if necessary. */
1740  if (hashtable->batches[batchno].preallocated < tuple_size)
1741  {
1742  if (!ExecParallelHashTuplePrealloc(hashtable, batchno, tuple_size))
1743  goto retry;
1744  }
1745 
1746  Assert(hashtable->batches[batchno].preallocated >= tuple_size);
1747  hashtable->batches[batchno].preallocated -= tuple_size;
1748  sts_puttuple(hashtable->batches[batchno].inner_tuples, &hashvalue,
1749  tuple);
1750  }
1751  ++hashtable->batches[batchno].ntuples;
1752 
1753  if (shouldFree)
1754  heap_free_minimal_tuple(tuple);
1755 }
static bool ExecParallelHashTuplePrealloc(HashJoinTable hashtable, int batchno, size_t size)
Definition: nodeHash.c:3420

References Assert, BarrierPhase(), HashJoinTableData::batches, HashJoinTableData::buckets, ParallelHashJoinState::build_barrier, ExecFetchSlotMinimalTuple(), ExecHashGetBucketAndBatch(), ExecParallelHashPushTuple(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), HashJoinTupleData::hashvalue, heap_free_minimal_tuple(), HeapTupleHeaderClearMatch, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, ParallelHashJoinBatchAccessor::inner_tuples, MAXALIGN, ParallelHashJoinBatchAccessor::ntuples, HashJoinTableData::parallel_state, PHJ_BUILD_HASH_INNER, ParallelHashJoinBatchAccessor::preallocated, HashJoinTableData::shared, sts_puttuple(), and MinimalTupleData::t_len.

Referenced by MultiExecParallelHash().

◆ ExecParallelHashTableInsertCurrentBatch()

void ExecParallelHashTableInsertCurrentBatch ( HashJoinTable  hashtable,
TupleTableSlot slot,
uint32  hashvalue 
)

Definition at line 1764 of file nodeHash.c.

1767 {
1768  bool shouldFree;
1769  MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
1770  HashJoinTuple hashTuple;
1771  dsa_pointer shared;
1772  int batchno;
1773  int bucketno;
1774 
1775  ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
1776  Assert(batchno == hashtable->curbatch);
1777  hashTuple = ExecParallelHashTupleAlloc(hashtable,
1778  HJTUPLE_OVERHEAD + tuple->t_len,
1779  &shared);
1780  hashTuple->hashvalue = hashvalue;
1781  memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
1783  ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
1784  hashTuple, shared);
1785 
1786  if (shouldFree)
1787  heap_free_minimal_tuple(tuple);
1788 }

References Assert, HashJoinTableData::buckets, HashJoinTableData::curbatch, ExecFetchSlotMinimalTuple(), ExecHashGetBucketAndBatch(), ExecParallelHashPushTuple(), ExecParallelHashTupleAlloc(), HashJoinTupleData::hashvalue, heap_free_minimal_tuple(), HeapTupleHeaderClearMatch, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, HashJoinTableData::shared, and MinimalTupleData::t_len.

Referenced by ExecParallelHashJoinNewBatch().

◆ ExecParallelHashTableSetCurrentBatch()

void ExecParallelHashTableSetCurrentBatch ( HashJoinTable  hashtable,
int  batchno 
)

Definition at line 3358 of file nodeHash.c.

3359 {
3360  Assert(hashtable->batches[batchno].shared->buckets != InvalidDsaPointer);
3361 
3362  hashtable->curbatch = batchno;
3363  hashtable->buckets.shared = (dsa_pointer_atomic *)
3364  dsa_get_address(hashtable->area,
3365  hashtable->batches[batchno].shared->buckets);
3366  hashtable->nbuckets = hashtable->parallel_state->nbuckets;
3367  hashtable->log2_nbuckets = my_log2(hashtable->nbuckets);
3368  hashtable->current_chunk = NULL;
3370  hashtable->batches[batchno].at_least_one_chunk = false;
3371 }
dsa_pointer current_chunk_shared
Definition: hashjoin.h:362

References HashJoinTableData::area, Assert, ParallelHashJoinBatchAccessor::at_least_one_chunk, HashJoinTableData::batches, ParallelHashJoinBatch::buckets, HashJoinTableData::buckets, HashJoinTableData::curbatch, HashJoinTableData::current_chunk, HashJoinTableData::current_chunk_shared, dsa_get_address(), InvalidDsaPointer, HashJoinTableData::log2_nbuckets, my_log2(), ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, HashJoinTableData::parallel_state, ParallelHashJoinBatchAccessor::shared, and HashJoinTableData::shared.

Referenced by ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashJoinNewBatch(), and MultiExecParallelHash().

◆ ExecParallelHashTupleAlloc()

static HashJoinTuple ExecParallelHashTupleAlloc ( HashJoinTable  hashtable,
size_t  size,
dsa_pointer shared 
)
static

Definition at line 2835 of file nodeHash.c.

2837 {
2838  ParallelHashJoinState *pstate = hashtable->parallel_state;
2839  dsa_pointer chunk_shared;
2841  Size chunk_size;
2842  HashJoinTuple result;
2843  int curbatch = hashtable->curbatch;
2844 
2845  size = MAXALIGN(size);
2846 
2847  /*
2848  * Fast path: if there is enough space in this backend's current chunk,
2849  * then we can allocate without any locking.
2850  */
2851  chunk = hashtable->current_chunk;
2852  if (chunk != NULL &&
2854  chunk->maxlen - chunk->used >= size)
2855  {
2856 
2857  chunk_shared = hashtable->current_chunk_shared;
2858  Assert(chunk == dsa_get_address(hashtable->area, chunk_shared));
2859  *shared = chunk_shared + HASH_CHUNK_HEADER_SIZE + chunk->used;
2860  result = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + chunk->used);
2861  chunk->used += size;
2862 
2863  Assert(chunk->used <= chunk->maxlen);
2864  Assert(result == dsa_get_address(hashtable->area, *shared));
2865 
2866  return result;
2867  }
2868 
2869  /* Slow path: try to allocate a new chunk. */
2870  LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
2871 
2872  /*
2873  * Check if we need to help increase the number of buckets or batches.
2874  */
2875  if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
2877  {
2878  ParallelHashGrowth growth = pstate->growth;
2879 
2880  hashtable->current_chunk = NULL;
2881  LWLockRelease(&pstate->lock);
2882 
2883  /* Another participant has commanded us to help grow. */
2884  if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
2886  else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
2888 
2889  /* The caller must retry. */
2890  return NULL;
2891  }
2892 
2893  /* Oversized tuples get their own chunk. */
2894  if (size > HASH_CHUNK_THRESHOLD)
2895  chunk_size = size + HASH_CHUNK_HEADER_SIZE;
2896  else
2897  chunk_size = HASH_CHUNK_SIZE;
2898 
2899  /* Check if it's time to grow batches or buckets. */
2900  if (pstate->growth != PHJ_GROWTH_DISABLED)
2901  {
2902  Assert(curbatch == 0);
2904 
2905  /*
2906  * Check if our space limit would be exceeded. To avoid choking on
2907  * very large tuples or very low hash_mem setting, we'll always allow
2908  * each backend to allocate at least one chunk.
2909  */
2910  if (hashtable->batches[0].at_least_one_chunk &&
2911  hashtable->batches[0].shared->size +
2912  chunk_size > pstate->space_allowed)
2913  {
2915  hashtable->batches[0].shared->space_exhausted = true;
2916  LWLockRelease(&pstate->lock);
2917 
2918  return NULL;
2919  }
2920 
2921  /* Check if our load factor limit would be exceeded. */
2922  if (hashtable->nbatch == 1)
2923  {
2924  hashtable->batches[0].shared->ntuples += hashtable->batches[0].ntuples;
2925  hashtable->batches[0].ntuples = 0;
2926  /* Guard against integer overflow and alloc size overflow */
2927  if (hashtable->batches[0].shared->ntuples + 1 >
2928  hashtable->nbuckets * NTUP_PER_BUCKET &&
2929  hashtable->nbuckets < (INT_MAX / 2) &&
2930  hashtable->nbuckets * 2 <=
2931  MaxAllocSize / sizeof(dsa_pointer_atomic))
2932  {
2934  LWLockRelease(&pstate->lock);
2935 
2936  return NULL;
2937  }
2938  }
2939  }
2940 
2941  /* We are cleared to allocate a new chunk. */
2942  chunk_shared = dsa_allocate(hashtable->area, chunk_size);
2943  hashtable->batches[curbatch].shared->size += chunk_size;
2944  hashtable->batches[curbatch].at_least_one_chunk = true;
2945 
2946  /* Set up the chunk. */
2947  chunk = (HashMemoryChunk) dsa_get_address(hashtable->area, chunk_shared);
2948  *shared = chunk_shared + HASH_CHUNK_HEADER_SIZE;
2949  chunk->maxlen = chunk_size - HASH_CHUNK_HEADER_SIZE;
2950  chunk->used = size;
2951 
2952  /*
2953  * Push it onto the list of chunks, so that it can be found if we need to
2954  * increase the number of buckets or batches (batch 0 only) and later for
2955  * freeing the memory (all batches).
2956  */
2957  chunk->next.shared = hashtable->batches[curbatch].shared->chunks;
2958  hashtable->batches[curbatch].shared->chunks = chunk_shared;
2959 
2960  if (size <= HASH_CHUNK_THRESHOLD)
2961  {
2962  /*
2963  * Make this the current chunk so that we can use the fast path to
2964  * fill the rest of it up in future calls.
2965  */
2966  hashtable->current_chunk = chunk;
2967  hashtable->current_chunk_shared = chunk_shared;
2968  }
2969  LWLockRelease(&pstate->lock);
2970 
2971  Assert(HASH_CHUNK_DATA(chunk) == dsa_get_address(hashtable->area, *shared));
2972  result = (HashJoinTuple) HASH_CHUNK_DATA(chunk);
2973 
2974  return result;
2975 }
ParallelHashGrowth
Definition: hashjoin.h:231
@ PHJ_GROWTH_NEED_MORE_BUCKETS
Definition: hashjoin.h:235
static void ExecParallelHashIncreaseNumBuckets(HashJoinTable hashtable)
Definition: nodeHash.c:1509
static void ExecParallelHashIncreaseNumBatches(HashJoinTable hashtable)
Definition: nodeHash.c:1064

References HashJoinTableData::area, Assert, ParallelHashJoinBatchAccessor::at_least_one_chunk, BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinState::build_barrier, chunk, ParallelHashJoinBatch::chunks, HashJoinTableData::curbatch, HashJoinTableData::current_chunk, HashJoinTableData::current_chunk_shared, dsa_allocate, dsa_get_address(), ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), ParallelHashJoinState::growth, HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HASH_CHUNK_SIZE, HASH_CHUNK_THRESHOLD, ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, MaxAllocSize, HashJoinTableData::nbatch, HashJoinTableData::nbuckets, NTUP_PER_BUCKET, ParallelHashJoinBatch::ntuples, ParallelHashJoinBatchAccessor::ntuples, HashJoinTableData::parallel_state, PHJ_BUILD_HASH_INNER, PHJ_GROWTH_DISABLED, PHJ_GROWTH_NEED_MORE_BATCHES, PHJ_GROWTH_NEED_MORE_BUCKETS, ParallelHashJoinBatchAccessor::shared, size, ParallelHashJoinBatch::size, ParallelHashJoinState::space_allowed, and ParallelHashJoinBatch::space_exhausted.

Referenced by ExecParallelHashRepartitionFirst(), ExecParallelHashTableInsert(), and ExecParallelHashTableInsertCurrentBatch().

◆ ExecParallelHashTuplePrealloc()

static bool ExecParallelHashTuplePrealloc ( HashJoinTable  hashtable,
int  batchno,
size_t  size 
)
static

Definition at line 3420 of file nodeHash.c.

3421 {
3422  ParallelHashJoinState *pstate = hashtable->parallel_state;
3423  ParallelHashJoinBatchAccessor *batch = &hashtable->batches[batchno];
3424  size_t want = Max(size, HASH_CHUNK_SIZE - HASH_CHUNK_HEADER_SIZE);
3425 
3426  Assert(batchno > 0);
3427  Assert(batchno < hashtable->nbatch);
3428  Assert(size == MAXALIGN(size));
3429 
3430  LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
3431 
3432  /* Has another participant commanded us to help grow? */
3433  if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
3435  {
3436  ParallelHashGrowth growth = pstate->growth;
3437 
3438  LWLockRelease(&pstate->lock);
3439  if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
3441  else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
3443 
3444  return false;
3445  }
3446 
3447  if (pstate->growth != PHJ_GROWTH_DISABLED &&
3448  batch->at_least_one_chunk &&
3449  (batch->shared->estimated_size + want + HASH_CHUNK_HEADER_SIZE
3450  > pstate->space_allowed))
3451  {
3452  /*
3453  * We have determined that this batch would exceed the space budget if
3454  * loaded into memory. Command all participants to help repartition.
3455  */
3456  batch->shared->space_exhausted = true;
3458  LWLockRelease(&pstate->lock);
3459 
3460  return false;
3461  }
3462 
3463  batch->at_least_one_chunk = true;
3464  batch->shared->estimated_size += want + HASH_CHUNK_HEADER_SIZE;
3465  batch->preallocated = want;
3466  LWLockRelease(&pstate->lock);
3467 
3468  return true;
3469 }

References Assert, ParallelHashJoinBatchAccessor::at_least_one_chunk, HashJoinTableData::batches, ParallelHashJoinBatch::estimated_size, ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), ParallelHashJoinState::growth, HASH_CHUNK_HEADER_SIZE, HASH_CHUNK_SIZE, ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), Max, MAXALIGN, HashJoinTableData::parallel_state, PHJ_GROWTH_DISABLED, PHJ_GROWTH_NEED_MORE_BATCHES, PHJ_GROWTH_NEED_MORE_BUCKETS, ParallelHashJoinBatchAccessor::preallocated, ParallelHashJoinBatchAccessor::shared, size, ParallelHashJoinState::space_allowed, and ParallelHashJoinBatch::space_exhausted.

Referenced by ExecParallelHashTableInsert().

◆ ExecParallelPrepHashTableForUnmatched()

bool ExecParallelPrepHashTableForUnmatched ( HashJoinState hjstate)

Definition at line 1984 of file nodeHash.c.

1985 {
1986  HashJoinTable hashtable = hjstate->hj_HashTable;
1987  int curbatch = hashtable->curbatch;
1988  ParallelHashJoinBatch *batch = hashtable->batches[curbatch].shared;
1989 
1991 
1992  /*
1993  * It would not be deadlock-free to wait on the batch barrier, because it
1994  * is in PHJ_BATCH_PROBE phase, and thus processes attached to it have
1995  * already emitted tuples. Therefore, we'll hold a wait-free election:
1996  * only one process can continue to the next phase, and all others detach
1997  * from this batch. They can still go any work on other batches, if there
1998  * are any.
1999  */
2001  {
2002  /* This process considers the batch to be done. */
2003  hashtable->batches[hashtable->curbatch].done = true;
2004 
2005  /* Make sure any temporary files are closed. */
2006  sts_end_parallel_scan(hashtable->batches[curbatch].inner_tuples);
2007  sts_end_parallel_scan(hashtable->batches[curbatch].outer_tuples);
2008 
2009  /*
2010  * Track largest batch we've seen, which would normally happen in
2011  * ExecHashTableDetachBatch().
2012  */
2013  hashtable->spacePeak =
2014  Max(hashtable->spacePeak,
2015  batch->size + sizeof(dsa_pointer_atomic) * hashtable->nbuckets);
2016  hashtable->curbatch = -1;
2017  return false;
2018  }
2019 
2020  /* Now we are alone with this batch. */
2022 
2023  /*
2024  * Has another process decided to give up early and command all processes
2025  * to skip the unmatched scan?
2026  */
2027  if (batch->skip_unmatched)
2028  {
2029  hashtable->batches[hashtable->curbatch].done = true;
2030  ExecHashTableDetachBatch(hashtable);
2031  return false;
2032  }
2033 
2034  /* Now prepare the process local state, just as for non-parallel join. */
2036 
2037  return true;
2038 }
void ExecHashTableDetachBatch(HashJoinTable hashtable)
Definition: nodeHash.c:3168
void ExecPrepHashTableForUnmatched(HashJoinState *hjstate)
Definition: nodeHash.c:1963
HashJoinTable hj_HashTable
Definition: execnodes.h:2224

References Assert, BarrierArriveAndDetachExceptLast(), BarrierPhase(), ParallelHashJoinBatch::batch_barrier, HashJoinTableData::batches, HashJoinTableData::curbatch, ParallelHashJoinBatchAccessor::done, ExecHashTableDetachBatch(), ExecPrepHashTableForUnmatched(), HashJoinState::hj_HashTable, ParallelHashJoinBatchAccessor::inner_tuples, Max, HashJoinTableData::nbuckets, ParallelHashJoinBatchAccessor::outer_tuples, PHJ_BATCH_PROBE, PHJ_BATCH_SCAN, ParallelHashJoinBatchAccessor::shared, ParallelHashJoinBatch::size, ParallelHashJoinBatch::skip_unmatched, HashJoinTableData::spacePeak, and sts_end_parallel_scan().

Referenced by ExecHashJoinImpl().

◆ ExecParallelScanHashBucket()

bool ExecParallelScanHashBucket ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 1912 of file nodeHash.c.

1914 {
1915  ExprState *hjclauses = hjstate->hashclauses;
1916  HashJoinTable hashtable = hjstate->hj_HashTable;
1917  HashJoinTuple hashTuple = hjstate->hj_CurTuple;
1918  uint32 hashvalue = hjstate->hj_CurHashValue;
1919 
1920  /*
1921  * hj_CurTuple is the address of the tuple last returned from the current
1922  * bucket, or NULL if it's time to start scanning a new bucket.
1923  */
1924  if (hashTuple != NULL)
1925  hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
1926  else
1927  hashTuple = ExecParallelHashFirstTuple(hashtable,
1928  hjstate->hj_CurBucketNo);
1929 
1930  while (hashTuple != NULL)
1931  {
1932  if (hashTuple->hashvalue == hashvalue)
1933  {
1934  TupleTableSlot *inntuple;
1935 
1936  /* insert hashtable's tuple into exec slot so ExecQual sees it */
1937  inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
1938  hjstate->hj_HashTupleSlot,
1939  false); /* do not pfree */
1940  econtext->ecxt_innertuple = inntuple;
1941 
1942  if (ExecQualAndReset(hjclauses, econtext))
1943  {
1944  hjstate->hj_CurTuple = hashTuple;
1945  return true;
1946  }
1947  }
1948 
1949  hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
1950  }
1951 
1952  /*
1953  * no match
1954  */
1955  return false;
1956 }
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1533
static bool ExecQualAndReset(ExprState *state, ExprContext *econtext)
Definition: executor.h:451
static HashJoinTuple ExecParallelHashFirstTuple(HashJoinTable hashtable, int bucketno)
Definition: nodeHash.c:3310
static HashJoinTuple ExecParallelHashNextTuple(HashJoinTable hashtable, HashJoinTuple tuple)
Definition: nodeHash.c:3326
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:260
HashJoinTuple hj_CurTuple
Definition: execnodes.h:2228
ExprState * hashclauses
Definition: execnodes.h:2222
uint32 hj_CurHashValue
Definition: execnodes.h:2225
int hj_CurBucketNo
Definition: execnodes.h:2226
TupleTableSlot * hj_HashTupleSlot
Definition: execnodes.h:2230

References ExprContext::ecxt_innertuple, ExecParallelHashFirstTuple(), ExecParallelHashNextTuple(), ExecQualAndReset(), ExecStoreMinimalTuple(), HashJoinState::hashclauses, HashJoinTupleData::hashvalue, HashJoinState::hj_CurBucketNo, HashJoinState::hj_CurHashValue, HashJoinState::hj_CurTuple, HashJoinState::hj_HashTable, HashJoinState::hj_HashTupleSlot, and HJTUPLE_MINTUPLE.

Referenced by ExecHashJoinImpl().

◆ ExecParallelScanHashTableForUnmatched()

bool ExecParallelScanHashTableForUnmatched ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 2123 of file nodeHash.c.

2125 {
2126  HashJoinTable hashtable = hjstate->hj_HashTable;
2127  HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2128 
2129  for (;;)
2130  {
2131  /*
2132  * hj_CurTuple is the address of the tuple last returned from the
2133  * current bucket, or NULL if it's time to start scanning a new
2134  * bucket.
2135  */
2136  if (hashTuple != NULL)
2137  hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
2138  else if (hjstate->hj_CurBucketNo < hashtable->nbuckets)
2139  hashTuple = ExecParallelHashFirstTuple(hashtable,
2140  hjstate->hj_CurBucketNo++);
2141  else
2142  break; /* finished all buckets */
2143 
2144  while (hashTuple != NULL)
2145  {
2146  if (!HeapTupleHeaderHasMatch(HJTUPLE_MINTUPLE(hashTuple)))
2147  {
2148  TupleTableSlot *inntuple;
2149 
2150  /* insert hashtable's tuple into exec slot */
2151  inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
2152  hjstate->hj_HashTupleSlot,
2153  false); /* do not pfree */
2154  econtext->ecxt_innertuple = inntuple;
2155 
2156  /*
2157  * Reset temp memory each time; although this function doesn't
2158  * do any qual eval, the caller will, so let's keep it
2159  * parallel to ExecScanHashBucket.
2160  */
2161  ResetExprContext(econtext);
2162 
2163  hjstate->hj_CurTuple = hashTuple;
2164  return true;
2165  }
2166 
2167  hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
2168  }
2169 
2170  /* allow this loop to be cancellable */
2172  }
2173 
2174  /*
2175  * no more unmatched tuples
2176  */
2177  return false;
2178 }
#define ResetExprContext(econtext)
Definition: executor.h:555
#define HeapTupleHeaderHasMatch(tup)
Definition: htup_details.h:514

References CHECK_FOR_INTERRUPTS, ExprContext::ecxt_innertuple, ExecParallelHashFirstTuple(), ExecParallelHashNextTuple(), ExecStoreMinimalTuple(), HeapTupleHeaderHasMatch, HashJoinState::hj_CurBucketNo, HashJoinState::hj_CurTuple, HashJoinState::hj_HashTable, HashJoinState::hj_HashTupleSlot, HJTUPLE_MINTUPLE, HashJoinTableData::nbuckets, and ResetExprContext.

Referenced by ExecHashJoinImpl().

◆ ExecPrepHashTableForUnmatched()

void ExecPrepHashTableForUnmatched ( HashJoinState hjstate)

Definition at line 1963 of file nodeHash.c.

1964 {
1965  /*----------
1966  * During this scan we use the HashJoinState fields as follows:
1967  *
1968  * hj_CurBucketNo: next regular bucket to scan
1969  * hj_CurSkewBucketNo: next skew bucket (an index into skewBucketNums)
1970  * hj_CurTuple: last tuple returned, or NULL to start next bucket
1971  *----------
1972  */
1973  hjstate->hj_CurBucketNo = 0;
1974  hjstate->hj_CurSkewBucketNo = 0;
1975  hjstate->hj_CurTuple = NULL;
1976 }
int hj_CurSkewBucketNo
Definition: execnodes.h:2227

References HashJoinState::hj_CurBucketNo, HashJoinState::hj_CurSkewBucketNo, and HashJoinState::hj_CurTuple.

Referenced by ExecHashJoinImpl(), and ExecParallelPrepHashTableForUnmatched().

◆ ExecReScanHash()

void ExecReScanHash ( HashState node)

Definition at line 2240 of file nodeHash.c.

2241 {
2243 
2244  /*
2245  * if chgParam of subnode is not null then plan will be re-scanned by
2246  * first ExecProcNode.
2247  */
2248  if (outerPlan->chgParam == NULL)
2250 }
void ExecReScan(PlanState *node)
Definition: execAmi.c:76

References ExecReScan(), outerPlan, and outerPlanState.

Referenced by ExecReScan().

◆ ExecScanHashBucket()

bool ExecScanHashBucket ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 1851 of file nodeHash.c.

1853 {
1854  ExprState *hjclauses = hjstate->hashclauses;
1855  HashJoinTable hashtable = hjstate->hj_HashTable;
1856  HashJoinTuple hashTuple = hjstate->hj_CurTuple;
1857  uint32 hashvalue = hjstate->hj_CurHashValue;
1858 
1859  /*
1860  * hj_CurTuple is the address of the tuple last returned from the current
1861  * bucket, or NULL if it's time to start scanning a new bucket.
1862  *
1863  * If the tuple hashed to a skew bucket then scan the skew bucket
1864  * otherwise scan the standard hashtable bucket.
1865  */
1866  if (hashTuple != NULL)
1867  hashTuple = hashTuple->next.unshared;
1868  else if (hjstate->hj_CurSkewBucketNo != INVALID_SKEW_BUCKET_NO)
1869  hashTuple = hashtable->skewBucket[hjstate->hj_CurSkewBucketNo]->tuples;
1870  else
1871  hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
1872 
1873  while (hashTuple != NULL)
1874  {
1875  if (hashTuple->hashvalue == hashvalue)
1876  {
1877  TupleTableSlot *inntuple;
1878 
1879  /* insert hashtable's tuple into exec slot so ExecQual sees it */
1880  inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
1881  hjstate->hj_HashTupleSlot,
1882  false); /* do not pfree */
1883  econtext->ecxt_innertuple = inntuple;
1884 
1885  if (ExecQualAndReset(hjclauses, econtext))
1886  {
1887  hjstate->hj_CurTuple = hashTuple;
1888  return true;
1889  }
1890  }
1891 
1892  hashTuple = hashTuple->next.unshared;
1893  }
1894 
1895  /*
1896  * no match
1897  */
1898  return false;
1899 }

References HashJoinTableData::buckets, ExprContext::ecxt_innertuple, ExecQualAndReset(), ExecStoreMinimalTuple(), HashJoinState::hashclauses, HashJoinTupleData::hashvalue, HashJoinState::hj_CurBucketNo, HashJoinState::hj_CurHashValue, HashJoinState::hj_CurSkewBucketNo, HashJoinState::hj_CurTuple, HashJoinState::hj_HashTable, HashJoinState::hj_HashTupleSlot, HJTUPLE_MINTUPLE, INVALID_SKEW_BUCKET_NO, HashJoinTupleData::next, HashJoinTableData::skewBucket, HashSkewBucket::tuples, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashJoinImpl().

◆ ExecScanHashTableForUnmatched()

bool ExecScanHashTableForUnmatched ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 2049 of file nodeHash.c.

2050 {
2051  HashJoinTable hashtable = hjstate->hj_HashTable;
2052  HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2053 
2054  for (;;)
2055  {
2056  /*
2057  * hj_CurTuple is the address of the tuple last returned from the
2058  * current bucket, or NULL if it's time to start scanning a new
2059  * bucket.
2060  */
2061  if (hashTuple != NULL)
2062  hashTuple = hashTuple->next.unshared;
2063  else if (hjstate->hj_CurBucketNo < hashtable->nbuckets)
2064  {
2065  hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
2066  hjstate->hj_CurBucketNo++;
2067  }
2068  else if (hjstate->hj_CurSkewBucketNo < hashtable->nSkewBuckets)
2069  {
2070  int j = hashtable->skewBucketNums[hjstate->hj_CurSkewBucketNo];
2071 
2072  hashTuple = hashtable->skewBucket[j]->tuples;
2073  hjstate->hj_CurSkewBucketNo++;
2074  }
2075  else
2076  break; /* finished all buckets */
2077 
2078  while (hashTuple != NULL)
2079  {
2080  if (!HeapTupleHeaderHasMatch(HJTUPLE_MINTUPLE(hashTuple)))
2081  {
2082  TupleTableSlot *inntuple;
2083 
2084  /* insert hashtable's tuple into exec slot */
2085  inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
2086  hjstate->hj_HashTupleSlot,
2087  false); /* do not pfree */
2088  econtext->ecxt_innertuple = inntuple;
2089 
2090  /*
2091  * Reset temp memory each time; although this function doesn't
2092  * do any qual eval, the caller will, so let's keep it
2093  * parallel to ExecScanHashBucket.
2094  */
2095  ResetExprContext(econtext);
2096 
2097  hjstate->hj_CurTuple = hashTuple;
2098  return true;
2099  }
2100 
2101  hashTuple = hashTuple->next.unshared;
2102  }
2103 
2104  /* allow this loop to be cancellable */
2106  }
2107 
2108  /*
2109  * no more unmatched tuples
2110  */
2111  return false;
2112 }

References HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, ExprContext::ecxt_innertuple, ExecStoreMinimalTuple(), HeapTupleHeaderHasMatch, HashJoinState::hj_CurBucketNo, HashJoinState::hj_CurSkewBucketNo, HashJoinState::hj_CurTuple, HashJoinState::hj_HashTable, HashJoinState::hj_HashTupleSlot, HJTUPLE_MINTUPLE, j, HashJoinTableData::nbuckets, HashJoinTupleData::next, HashJoinTableData::nSkewBuckets, ResetExprContext, HashJoinTableData::skewBucket, HashJoinTableData::skewBucketNums, HashSkewBucket::tuples, HashJoinTupleData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashJoinImpl().

◆ ExecShutdownHash()

void ExecShutdownHash ( HashState node)

Definition at line 2690 of file nodeHash.c.

2691 {
2692  /* Allocate save space if EXPLAIN'ing and we didn't do so already */
2693  if (node->ps.instrument && !node->hinstrument)
2695  /* Now accumulate data for the current (final) hash table */
2696  if (node->hinstrument && node->hashtable)
2698 }
#define palloc0_object(type)
Definition: fe_memutils.h:63
void ExecHashAccumInstrumentation(HashInstrumentation *instrument, HashJoinTable hashtable)
Definition: nodeHash.c:2736

References ExecHashAccumInstrumentation(), HashState::hashtable, HashState::hinstrument, PlanState::instrument, palloc0_object, and HashState::ps.

Referenced by ExecShutdownNode_walker().

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3481 of file nodeHash.c.

3482 {
3483  double mem_limit;
3484 
3485  /* Do initial calculation in double arithmetic */
3486  mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3487 
3488  /* Clamp in case it doesn't fit in size_t */
3489  mem_limit = Min(mem_limit, (double) SIZE_MAX);
3490 
3491  return (size_t) mem_limit;
3492 }
double hash_mem_multiplier
Definition: globals.c:131
int work_mem
Definition: globals.c:130

References hash_mem_multiplier, Min, and work_mem.

Referenced by BuildTupleHashTableExt(), choose_hashed_setop(), consider_groupingsets_paths(), cost_memoize_rescan(), create_unique_path(), ExecChooseHashTableSize(), ExecInitMemoize(), ExecParallelHashIncreaseNumBatches(), final_cost_hashjoin(), hash_agg_set_limits(), hash_choose_num_partitions(), subpath_is_hashable(), and subplan_is_hashable().

◆ MultiExecHash()

Node* MultiExecHash ( HashState node)

Definition at line 106 of file nodeHash.c.

107 {
108  /* must provide our own instrumentation support */
109  if (node->ps.instrument)
111 
112  if (node->parallel_state != NULL)
113  MultiExecParallelHash(node);
114  else
115  MultiExecPrivateHash(node);
116 
117  /* must provide our own instrumentation support */
118  if (node->ps.instrument)
120 
121  /*
122  * We do not return the hash table directly because it's not a subtype of
123  * Node, and so would violate the MultiExecProcNode API. Instead, our
124  * parent Hashjoin node is expected to know how to fish it out of our node
125  * state. Ugly but not really worth cleaning up, since Hashjoin knows
126  * quite a bit more about Hash besides that.
127  */
128  return NULL;
129 }
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:68
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:84
static void MultiExecParallelHash(HashState *node)
Definition: nodeHash.c:220
static void MultiExecPrivateHash(HashState *node)
Definition: nodeHash.c:139
struct ParallelHashJoinState * parallel_state
Definition: execnodes.h:2799

References HashState::hashtable, InstrStartNode(), InstrStopNode(), PlanState::instrument, MultiExecParallelHash(), MultiExecPrivateHash(), HashState::parallel_state, HashJoinTableData::partialTuples, and HashState::ps.

Referenced by MultiExecProcNode().

◆ MultiExecParallelHash()

static void MultiExecParallelHash ( HashState node)
static

Definition at line 220 of file nodeHash.c.

221 {
222  ParallelHashJoinState *pstate;
223  PlanState *outerNode;
224  HashJoinTable hashtable;
225  TupleTableSlot *slot;
226  ExprContext *econtext;
227  uint32 hashvalue;
228  Barrier *build_barrier;
229  int i;
230 
231  /*
232  * get state info from node
233  */
234  outerNode = outerPlanState(node);
235  hashtable = node->hashtable;
236 
237  /*
238  * set expression context
239  */
240  econtext = node->ps.ps_ExprContext;
241 
242  /*
243  * Synchronize the parallel hash table build. At this stage we know that
244  * the shared hash table has been or is being set up by
245  * ExecHashTableCreate(), but we don't know if our peers have returned
246  * from there or are here in MultiExecParallelHash(), and if so how far
247  * through they are. To find out, we check the build_barrier phase then
248  * and jump to the right step in the build algorithm.
249  */
250  pstate = hashtable->parallel_state;
251  build_barrier = &pstate->build_barrier;
252  Assert(BarrierPhase(build_barrier) >= PHJ_BUILD_ALLOCATE);
253  switch (BarrierPhase(build_barrier))
254  {
255  case PHJ_BUILD_ALLOCATE:
256 
257  /*
258  * Either I just allocated the initial hash table in
259  * ExecHashTableCreate(), or someone else is doing that. Either
260  * way, wait for everyone to arrive here so we can proceed.
261  */
262  BarrierArriveAndWait(build_barrier, WAIT_EVENT_HASH_BUILD_ALLOCATE);
263  /* Fall through. */
264 
266 
267  /*
268  * It's time to begin hashing, or if we just arrived here then
269  * hashing is already underway, so join in that effort. While
270  * hashing we have to be prepared to help increase the number of
271  * batches or buckets at any time, and if we arrived here when
272  * that was already underway we'll have to help complete that work
273  * immediately so that it's safe to access batches and buckets
274  * below.
275  */
284  for (;;)
285  {
286  bool isnull;
287 
288  slot = ExecProcNode(outerNode);
289  if (TupIsNull(slot))
290  break;
291  econtext->ecxt_outertuple = slot;
292 
293  ResetExprContext(econtext);
294 
296  econtext,
297  &isnull));
298 
299  if (!isnull)
300  ExecParallelHashTableInsert(hashtable, slot, hashvalue);
301  hashtable->partialTuples++;
302  }
303 
304  /*
305  * Make sure that any tuples we wrote to disk are visible to
306  * others before anyone tries to load them.
307  */
308  for (i = 0; i < hashtable->nbatch; ++i)
309  sts_end_write(hashtable->batches[i].inner_tuples);
310 
311  /*
312  * Update shared counters. We need an accurate total tuple count
313  * to control the empty table optimization.
314  */
316 
319 
320  /*
321  * Wait for everyone to finish building and flushing files and
322  * counters.
323  */
324  if (BarrierArriveAndWait(build_barrier,
325  WAIT_EVENT_HASH_BUILD_HASH_INNER))
326  {
327  /*
328  * Elect one backend to disable any further growth. Batches
329  * are now fixed. While building them we made sure they'd fit
330  * in our memory budget when we load them back in later (or we
331  * tried to do that and gave up because we detected extreme
332  * skew).
333  */
334  pstate->growth = PHJ_GROWTH_DISABLED;
335  }
336  }
337 
338  /*
339  * We're not yet attached to a batch. We all agree on the dimensions and
340  * number of inner tuples (for the empty table optimization).
341  */
342  hashtable->curbatch = -1;
343  hashtable->nbuckets = pstate->nbuckets;
344  hashtable->log2_nbuckets = my_log2(hashtable->nbuckets);
345  hashtable->totalTuples = pstate->total_tuples;
346 
347  /*
348  * Unless we're completely done and the batch state has been freed, make
349  * sure we have accessors.
350  */
351  if (BarrierPhase(build_barrier) < PHJ_BUILD_FREE)
353 
354  /*
355  * The next synchronization point is in ExecHashJoin's HJ_BUILD_HASHTABLE
356  * case, which will bring the build phase to PHJ_BUILD_RUN (if it isn't
357  * there already).
358  */
359  Assert(BarrierPhase(build_barrier) == PHJ_BUILD_HASH_OUTER ||
360  BarrierPhase(build_barrier) == PHJ_BUILD_RUN ||
361  BarrierPhase(build_barrier) == PHJ_BUILD_FREE);
362 }
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:359
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:273
#define PHJ_BUILD_HASH_OUTER
Definition: hashjoin.h:272
#define PHJ_BUILD_ALLOCATE
Definition: hashjoin.h:270
void ExecParallelHashTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
Definition: nodeHash.c:1698
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:262
ExprContext * ps_ExprContext
Definition: execnodes.h:1162
#define TupIsNull(slot)
Definition: tuptable.h:306

References Assert, BarrierArriveAndWait(), BarrierAttach(), BarrierDetach(), BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinState::build_barrier, HashJoinTableData::curbatch, DatumGetUInt32(), ExprContext::ecxt_outertuple, ExecEvalExprSwitchContext(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashMergeCounters(), ExecParallelHashTableInsert(), ExecParallelHashTableSetCurrentBatch(), ExecProcNode(), ParallelHashJoinState::grow_batches_barrier, ParallelHashJoinState::grow_buckets_barrier, ParallelHashJoinState::growth, HashState::hash_expr, HashState::hashtable, i, ParallelHashJoinBatchAccessor::inner_tuples, HashJoinTableData::log2_nbuckets, my_log2(), HashJoinTableData::nbatch, ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, outerPlanState, HashJoinTableData::parallel_state, HashJoinTableData::partialTuples, PHJ_BUILD_ALLOCATE, PHJ_BUILD_FREE, PHJ_BUILD_HASH_INNER, PHJ_BUILD_HASH_OUTER, PHJ_BUILD_RUN, PHJ_GROW_BATCHES_ELECT, PHJ_GROW_BATCHES_PHASE, PHJ_GROW_BUCKETS_ELECT, PHJ_GROW_BUCKETS_PHASE, PHJ_GROWTH_DISABLED, HashState::ps, PlanState::ps_ExprContext, ResetExprContext, sts_end_write(), ParallelHashJoinState::total_tuples, HashJoinTableData::totalTuples, and TupIsNull.

Referenced by MultiExecHash().

◆ MultiExecPrivateHash()

static void MultiExecPrivateHash ( HashState node)
static

Definition at line 139 of file nodeHash.c.

140 {
141  PlanState *outerNode;
142  HashJoinTable hashtable;
143  TupleTableSlot *slot;
144  ExprContext *econtext;
145 
146  /*
147  * get state info from node
148  */
149  outerNode = outerPlanState(node);
150  hashtable = node->hashtable;
151 
152  /*
153  * set expression context
154  */
155  econtext = node->ps.ps_ExprContext;
156 
157  /*
158  * Get all tuples from the node below the Hash node and insert into the
159  * hash table (or temp files).
160  */
161  for (;;)
162  {
163  bool isnull;
164  Datum hashdatum;
165 
166  slot = ExecProcNode(outerNode);
167  if (TupIsNull(slot))
168  break;
169  /* We have to compute the hash value */
170  econtext->ecxt_outertuple = slot;
171 
172  ResetExprContext(econtext);
173 
174  hashdatum = ExecEvalExprSwitchContext(node->hash_expr, econtext,
175  &isnull);
176 
177  if (!isnull)
178  {
179  uint32 hashvalue = DatumGetUInt32(hashdatum);
180  int bucketNumber;
181 
182  bucketNumber = ExecHashGetSkewBucket(hashtable, hashvalue);
183  if (bucketNumber != INVALID_SKEW_BUCKET_NO)
184  {
185  /* It's a skew tuple, so put it into that hash table */
186  ExecHashSkewTableInsert(hashtable, slot, hashvalue,
187  bucketNumber);
188  hashtable->skewTuples += 1;
189  }
190  else
191  {
192  /* Not subject to skew optimization, so insert normally */
193  ExecHashTableInsert(hashtable, slot, hashvalue);
194  }
195  hashtable->totalTuples += 1;
196  }
197  }
198 
199  /* resize the hash table if needed (NTUP_PER_BUCKET exceeded) */
200  if (hashtable->nbuckets != hashtable->nbuckets_optimal)
201  ExecHashIncreaseNumBuckets(hashtable);
202 
203  /* Account for the buckets in spaceUsed (reported in EXPLAIN ANALYZE) */
204  hashtable->spaceUsed += hashtable->nbuckets * sizeof(HashJoinTuple);
205  if (hashtable->spaceUsed > hashtable->spacePeak)
206  hashtable->spacePeak = hashtable->spaceUsed;
207 
208  hashtable->partialTuples = hashtable->totalTuples;
209 }
static void ExecHashIncreaseNumBuckets(HashJoinTable hashtable)
Definition: nodeHash.c:1446
int ExecHashGetSkewBucket(HashJoinTable hashtable, uint32 hashvalue)
Definition: nodeHash.c:2414
static void ExecHashSkewTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue, int bucketNumber)
Definition: nodeHash.c:2460
void ExecHashTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
Definition: nodeHash.c:1608
uintptr_t Datum
Definition: postgres.h:64

References DatumGetUInt32(), ExprContext::ecxt_outertuple, ExecEvalExprSwitchContext(), ExecHashGetSkewBucket(), ExecHashIncreaseNumBuckets(), ExecHashSkewTableInsert(), ExecHashTableInsert(), ExecProcNode(), HashState::hash_expr, HashState::hashtable, INVALID_SKEW_BUCKET_NO, HashJoinTableData::nbuckets, HashJoinTableData::nbuckets_optimal, outerPlanState, HashJoinTableData::partialTuples, HashState::ps, PlanState::ps_ExprContext, ResetExprContext, HashJoinTableData::skewTuples, HashJoinTableData::spacePeak, HashJoinTableData::spaceUsed, HashJoinTableData::totalTuples, and TupIsNull.

Referenced by MultiExecHash().