PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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/instrument.h"
#include "executor/nodeHash.h"
#include "executor/nodeHashjoin.h"
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/tuplestore.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 voiddense_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)
 
static bool ExecHashIncreaseBatchSize (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)
 
TuplestorestateExecHashBuildNullTupleStore (HashJoinTable hashtable)
 
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 680 of file nodeHash.c.

Function Documentation

◆ dense_alloc()

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

Definition at line 2954 of file nodeHash.c.

2955{
2957 char *ptr;
2958
2959 /* just in case the size is not already aligned properly */
2960 size = MAXALIGN(size);
2961
2962 /*
2963 * If tuple size is larger than threshold, allocate a separate chunk.
2964 */
2965 if (size > HASH_CHUNK_THRESHOLD)
2966 {
2967 /* allocate new chunk and put it at the beginning of the list */
2969 HASH_CHUNK_HEADER_SIZE + size);
2970 newChunk->maxlen = size;
2971 newChunk->used = size;
2972 newChunk->ntuples = 1;
2973
2974 /*
2975 * Add this chunk to the list after the first existing chunk, so that
2976 * we don't lose the remaining space in the "current" chunk.
2977 */
2978 if (hashtable->chunks != NULL)
2979 {
2980 newChunk->next = hashtable->chunks->next;
2981 hashtable->chunks->next.unshared = newChunk;
2982 }
2983 else
2984 {
2985 newChunk->next.unshared = hashtable->chunks;
2986 hashtable->chunks = newChunk;
2987 }
2988
2989 return HASH_CHUNK_DATA(newChunk);
2990 }
2991
2992 /*
2993 * See if we have enough space for it in the current chunk (if any). If
2994 * not, allocate a fresh chunk.
2995 */
2996 if ((hashtable->chunks == NULL) ||
2997 (hashtable->chunks->maxlen - hashtable->chunks->used) < size)
2998 {
2999 /* allocate new chunk and put it at the beginning of the list */
3002
3003 newChunk->maxlen = HASH_CHUNK_SIZE;
3004 newChunk->used = size;
3005 newChunk->ntuples = 1;
3006
3007 newChunk->next.unshared = hashtable->chunks;
3008 hashtable->chunks = newChunk;
3009
3010 return HASH_CHUNK_DATA(newChunk);
3011 }
3012
3013 /* There is enough space in the current chunk, let's add the tuple */
3014 ptr = HASH_CHUNK_DATA(hashtable->chunks) + hashtable->chunks->used;
3015 hashtable->chunks->used += size;
3016 hashtable->chunks->ntuples += 1;
3017
3018 /* return pointer to the start of the tuple memory */
3019 return ptr;
3020}
#define MAXALIGN(LEN)
Definition c.h:898
struct HashMemoryChunkData * HashMemoryChunk
Definition hashjoin.h:159
#define HASH_CHUNK_DATA(hc)
Definition hashjoin.h:163
#define HASH_CHUNK_THRESHOLD
Definition hashjoin.h:165
#define HASH_CHUNK_HEADER_SIZE
Definition hashjoin.h:162
#define HASH_CHUNK_SIZE
Definition hashjoin.h:161
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
static int fb(int x)
HashMemoryChunk chunks
Definition hashjoin.h:373
MemoryContext batchCxt
Definition hashjoin.h:369
struct HashMemoryChunkData * unshared
Definition hashjoin.h:148
union HashMemoryChunkData::@112 next

References HashJoinTableData::batchCxt, HashJoinTableData::chunks, fb(), HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HASH_CHUNK_SIZE, HASH_CHUNK_THRESHOLD, MAXALIGN, HashMemoryChunkData::maxlen, MemoryContextAlloc(), HashMemoryChunkData::next, HashMemoryChunkData::ntuples, 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 683 of file nodeHash.c.

690{
691 int tupsize;
692 double inner_rel_bytes;
693 size_t hash_table_bytes;
694 size_t bucket_bytes;
695 size_t max_pointers;
696 int nbatch = 1;
697 int nbuckets;
698 double dbuckets;
699
700 /* Force a plausible relation size if no info */
701 if (ntuples <= 0.0)
702 ntuples = 1000.0;
703
704 /*
705 * Estimate tupsize based on footprint of tuple in hashtable... note this
706 * does not allow for any palloc overhead. The manipulations of spaceUsed
707 * don't count palloc overhead either.
708 */
712 inner_rel_bytes = ntuples * tupsize;
713
714 /*
715 * Compute in-memory hashtable size limit from GUCs.
716 */
718
719 /*
720 * Parallel Hash tries to use the combined hash_mem of all workers to
721 * avoid the need to batch. If that won't work, it falls back to hash_mem
722 * per worker and tries to process batches in parallel.
723 */
725 {
726 /* Careful, this could overflow size_t */
727 double newlimit;
728
729 newlimit = (double) hash_table_bytes * (double) (parallel_workers + 1);
730 newlimit = Min(newlimit, (double) SIZE_MAX);
732 }
733
734 *space_allowed = hash_table_bytes;
735
736 /*
737 * If skew optimization is possible, estimate the number of skew buckets
738 * that will fit in the memory allowed, and decrement the assumed space
739 * available for the main hash table accordingly.
740 *
741 * We make the optimistic assumption that each skew bucket will contain
742 * one inner-relation tuple. If that turns out to be low, we will recover
743 * at runtime by reducing the number of skew buckets.
744 *
745 * hashtable->skewBucket will have up to 8 times as many HashSkewBucket
746 * pointers as the number of MCVs we allow, since ExecHashBuildSkewHash
747 * will round up to the next power of 2 and then multiply by 4 to reduce
748 * collisions.
749 */
750 if (useskew)
751 {
752 size_t bytes_per_mcv;
753 size_t skew_mcvs;
754
755 /*----------
756 * Compute number of MCVs we could hold in hash_table_bytes
757 *
758 * Divisor is:
759 * size of a hash tuple +
760 * worst-case size of skewBucket[] per MCV +
761 * size of skewBucketNums[] entry +
762 * size of skew bucket struct itself
763 *----------
764 */
766 (8 * sizeof(HashSkewBucket *)) +
767 sizeof(int) +
770
771 /*
772 * Now scale by SKEW_HASH_MEM_PERCENT (we do it in this order so as
773 * not to worry about size_t overflow in the multiplication)
774 */
776
777 /* Now clamp to integer range */
779
781
782 /* Reduce hash_table_bytes by the amount needed for the skew table */
783 if (skew_mcvs > 0)
785 }
786 else
787 *num_skew_mcvs = 0;
788
789 /*
790 * Set nbuckets to achieve an average bucket load of NTUP_PER_BUCKET when
791 * memory is filled, assuming a single batch; but limit the value so that
792 * the pointer arrays we'll try to allocate do not exceed hash_table_bytes
793 * nor MaxAllocSize.
794 *
795 * Note that both nbuckets and nbatch must be powers of 2 to make
796 * ExecHashGetBucketAndBatch fast.
797 */
800 /* If max_pointers isn't a power of 2, must round it down to one */
802
803 /* Also ensure we avoid integer overflow in nbatch and nbuckets */
804 /* (this step is redundant given the current value of MaxAllocSize) */
806
807 dbuckets = ceil(ntuples / NTUP_PER_BUCKET);
809 nbuckets = (int) dbuckets;
810 /* don't let nbuckets be really small, though ... */
811 nbuckets = Max(nbuckets, 1024);
812 /* ... and force it to be a power of 2. */
813 nbuckets = pg_nextpower2_32(nbuckets);
814
815 /*
816 * If there's not enough space to store the projected number of tuples and
817 * the required bucket headers, we will need multiple batches.
818 */
819 bucket_bytes = sizeof(HashJoinTuple) * nbuckets;
821 {
822 /* We'll need multiple batches */
823 size_t sbuckets;
824 double dbatch;
825 int minbatch;
826 size_t bucket_size;
827
828 /*
829 * If Parallel Hash with combined hash_mem would still need multiple
830 * batches, we'll have to fall back to regular hash_mem budget.
831 */
833 {
835 false, parallel_workers,
836 space_allowed,
837 numbuckets,
838 numbatches,
840 return;
841 }
842
843 /*
844 * Estimate the number of buckets we'll want to have when hash_mem is
845 * entirely full. Each bucket will contain a bucket pointer plus
846 * NTUP_PER_BUCKET tuples, whose projected size already includes
847 * overhead for the hash code, pointer to the next tuple, etc.
848 */
851 sbuckets = 1; /* avoid pg_nextpower2_size_t(0) */
852 else
855 nbuckets = (int) sbuckets;
856 nbuckets = pg_nextpower2_32(nbuckets);
857 bucket_bytes = nbuckets * sizeof(HashJoinTuple);
858
859 /*
860 * Buckets are simple pointers to hashjoin tuples, while tupsize
861 * includes the pointer, hash code, and MinimalTupleData. So buckets
862 * should never really exceed 25% of hash_mem (even for
863 * NTUP_PER_BUCKET=1); except maybe for hash_mem values that are not
864 * 2^N bytes, where we might get more because of doubling. So let's
865 * look for 50% here.
866 */
868
869 /* Calculate required number of batches. */
872 minbatch = (int) dbatch;
873 nbatch = pg_nextpower2_32(Max(2, minbatch));
874 }
875
876 /*
877 * Optimize the total amount of memory consumed by the hash node.
878 *
879 * The nbatch calculation above focuses on the in-memory hash table,
880 * assuming no per-batch overhead. But each batch may have two files, each
881 * with a BLCKSZ buffer. For large nbatch values these buffers may use
882 * significantly more memory than the hash table.
883 *
884 * The total memory usage may be expressed by this formula:
885 *
886 * (inner_rel_bytes / nbatch) + (2 * nbatch * BLCKSZ)
887 *
888 * where (inner_rel_bytes / nbatch) is the size of the in-memory hash
889 * table and (2 * nbatch * BLCKSZ) is the amount of memory used by file
890 * buffers.
891 *
892 * The nbatch calculation however ignores the second part. And for very
893 * large inner_rel_bytes, there may be no nbatch that keeps total memory
894 * usage under the budget (work_mem * hash_mem_multiplier). To deal with
895 * that, we will adjust nbatch to minimize total memory consumption across
896 * both the hashtable and file buffers.
897 *
898 * As we increase the size of the hashtable, the number of batches
899 * decreases, and the total memory usage follows a U-shaped curve. We find
900 * the minimum nbatch by "walking back" -- checking if halving nbatch
901 * would lower the total memory usage. We stop when it no longer helps.
902 *
903 * We only reduce the number of batches. Adding batches reduces memory
904 * usage only when most of the memory is used by the hash table, with
905 * total memory usage within the limit or not far from it. We don't want
906 * to start batching when not needed, even if that would reduce memory
907 * usage.
908 *
909 * While growing the hashtable, we also adjust the number of buckets to
910 * maintain a load factor of NTUP_PER_BUCKET while squeezing tuples back
911 * from batches into the hashtable.
912 *
913 * Note that we can only change nbuckets during initial hashtable sizing.
914 * Once we start building the hash, nbuckets is fixed (we may still grow
915 * the hash table).
916 *
917 * We double several parameters (space_allowed, nbuckets, num_skew_mcvs),
918 * which introduces a risk of overflow. We avoid this by exiting the loop.
919 * We could do something smarter (e.g. capping nbuckets and continue), but
920 * the complexity is not worth it. Such cases are extremely rare, and this
921 * is a best-effort attempt to reduce memory usage.
922 */
923 while (nbatch > 1)
924 {
925 /* Check that buckets won't overflow MaxAllocSize */
926 if (nbuckets > (MaxAllocSize / sizeof(HashJoinTuple) / 2))
927 break;
928
929 /* num_skew_mcvs should be less than nbuckets */
930 Assert((*num_skew_mcvs) < (INT_MAX / 2));
931
932 /*
933 * Check that space_allowed won't overflow SIZE_MAX.
934 *
935 * We don't use hash_table_bytes here, because it does not include the
936 * skew buckets. And we want to limit the overall memory limit.
937 */
938 if ((*space_allowed) > (SIZE_MAX / 2))
939 break;
940
941 /*
942 * Will halving the number of batches and doubling the size of the
943 * hashtable reduce overall memory usage?
944 *
945 * This is the same as (S = space_allowed):
946 *
947 * (S + 2 * nbatch * BLCKSZ) < (S * 2 + nbatch * BLCKSZ)
948 *
949 * but avoiding intermediate overflow.
950 */
951 if (nbatch < (*space_allowed) / BLCKSZ)
952 break;
953
954 /*
955 * MaxAllocSize is sufficiently small that we are not worried about
956 * overflowing nbuckets.
957 */
958 nbuckets *= 2;
959
960 *num_skew_mcvs = (*num_skew_mcvs) * 2;
961 *space_allowed = (*space_allowed) * 2;
962
963 nbatch /= 2;
964 }
965
966 Assert(nbuckets > 0);
967 Assert(nbatch > 0);
968
969 *numbuckets = nbuckets;
970 *numbatches = nbatch;
971}
#define Min(x, y)
Definition c.h:1093
#define Max(x, y)
Definition c.h:1087
#define Assert(condition)
Definition c.h:945
struct HashJoinTupleData * HashJoinTuple
Definition execnodes.h:2215
#define MaxAllocSize
Definition fe_memutils.h:22
#define HJTUPLE_OVERHEAD
Definition hashjoin.h:101
#define SKEW_BUCKET_OVERHEAD
Definition hashjoin.h:130
#define SKEW_HASH_MEM_PERCENT
Definition hashjoin.h:132
#define SizeofMinimalTupleHeader
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:683
#define NTUP_PER_BUCKET
Definition nodeHash.c:680
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680
static uint32 pg_nextpower2_32(uint32 num)
#define pg_nextpower2_size_t
#define pg_prevpower2_size_t

References Assert, ExecChooseHashTableSize(), fb(), 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 ExecChooseHashTableSize(), ExecHashTableCreate(), and initial_cost_hashjoin().

◆ ExecEndHash()

void ExecEndHash ( HashState node)

Definition at line 452 of file nodeHash.c.

453{
455
456 /*
457 * shut down the subplan
458 */
461}
void ExecEndNode(PlanState *node)
#define outerPlanState(node)
Definition execnodes.h:1273
#define outerPlan(node)
Definition plannodes.h:265

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:226

References elog, ERROR, and fb().

Referenced by ExecInitHash().

◆ ExecHashAccumInstrumentation()

void ExecHashAccumInstrumentation ( HashInstrumentation instrument,
HashJoinTable  hashtable 
)

Definition at line 2935 of file nodeHash.c.

2937{
2938 instrument->nbuckets = Max(instrument->nbuckets,
2939 hashtable->nbuckets);
2940 instrument->nbuckets_original = Max(instrument->nbuckets_original,
2941 hashtable->nbuckets_original);
2942 instrument->nbatch = Max(instrument->nbatch,
2943 hashtable->nbatch);
2944 instrument->nbatch_original = Max(instrument->nbatch_original,
2945 hashtable->nbatch_original);
2946 instrument->space_peak = Max(instrument->space_peak,
2947 hashtable->spacePeak);
2948}

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

◆ ExecHashBuildNullTupleStore()

Tuplestorestate * ExecHashBuildNullTupleStore ( HashJoinTable  hashtable)

Definition at line 2799 of file nodeHash.c.

2800{
2801 Tuplestorestate *tstore;
2803
2804 /*
2805 * We keep the tuplestore in the hashCxt to ensure it won't go away too
2806 * soon. Size it at work_mem/16 so that it doesn't bloat the node's space
2807 * consumption too much.
2808 */
2809 oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
2810 tstore = tuplestore_begin_heap(false, false, work_mem / 16);
2812 return tstore;
2813}
int work_mem
Definition globals.c:131
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
MemoryContext hashCxt
Definition hashjoin.h:368
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition tuplestore.c:331

References fb(), HashJoinTableData::hashCxt, MemoryContextSwitchTo(), tuplestore_begin_heap(), and work_mem.

Referenced by ExecHashJoinOuterGetTuple(), ExecParallelHashJoinOuterGetTuple(), ExecParallelHashJoinPartitionOuter(), MultiExecParallelHash(), and MultiExecPrivateHash().

◆ ExecHashBuildSkewHash()

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

Definition at line 2429 of file nodeHash.c.

2431{
2432 HeapTupleData *statsTuple;
2434
2435 /* Do nothing if planner didn't identify the outer relation's join key */
2436 if (!OidIsValid(node->skewTable))
2437 return;
2438 /* Also, do nothing if we don't have room for at least one skew bucket */
2439 if (mcvsToUse <= 0)
2440 return;
2441
2442 /*
2443 * Try to find the MCV statistics for the outer relation's join key.
2444 */
2445 statsTuple = SearchSysCache3(STATRELATTINH,
2448 BoolGetDatum(node->skewInherit));
2449 if (!HeapTupleIsValid(statsTuple))
2450 return;
2451
2452 if (get_attstatsslot(&sslot, statsTuple,
2455 {
2456 double frac;
2457 int nbuckets;
2458 int i;
2459
2460 if (mcvsToUse > sslot.nvalues)
2461 mcvsToUse = sslot.nvalues;
2462
2463 /*
2464 * Calculate the expected fraction of outer relation that will
2465 * participate in the skew optimization. If this isn't at least
2466 * SKEW_MIN_OUTER_FRACTION, don't use skew optimization.
2467 */
2468 frac = 0;
2469 for (i = 0; i < mcvsToUse; i++)
2470 frac += sslot.numbers[i];
2472 {
2474 ReleaseSysCache(statsTuple);
2475 return;
2476 }
2477
2478 /*
2479 * Okay, set up the skew hashtable.
2480 *
2481 * skewBucket[] is an open addressing hashtable with a power of 2 size
2482 * that is greater than the number of MCV values. (This ensures there
2483 * will be at least one null entry, so searches will always
2484 * terminate.)
2485 *
2486 * Note: this code could fail if mcvsToUse exceeds INT_MAX/8 or
2487 * MaxAllocSize/sizeof(void *)/8, but that is not currently possible
2488 * since we limit pg_statistic entries to much less than that.
2489 */
2490 nbuckets = pg_nextpower2_32(mcvsToUse + 1);
2491 /* use two more bits just to help avoid collisions */
2492 nbuckets <<= 2;
2493
2494 hashtable->skewEnabled = true;
2495 hashtable->skewBucketLen = nbuckets;
2496
2497 /*
2498 * We allocate the bucket memory in the hashtable's batch context. It
2499 * is only needed during the first batch, and this ensures it will be
2500 * automatically removed once the first batch is done.
2501 */
2502 hashtable->skewBucket = (HashSkewBucket **)
2504 nbuckets * sizeof(HashSkewBucket *));
2505 hashtable->skewBucketNums = (int *)
2507 mcvsToUse * sizeof(int));
2508
2509 hashtable->spaceUsed += nbuckets * sizeof(HashSkewBucket *)
2510 + mcvsToUse * sizeof(int);
2511 hashtable->spaceUsedSkew += nbuckets * sizeof(HashSkewBucket *)
2512 + mcvsToUse * sizeof(int);
2513 if (hashtable->spaceUsed > hashtable->spacePeak)
2514 hashtable->spacePeak = hashtable->spaceUsed;
2515
2516 /*
2517 * Create a skew bucket for each MCV hash value.
2518 *
2519 * Note: it is very important that we create the buckets in order of
2520 * decreasing MCV frequency. If we have to remove some buckets, they
2521 * must be removed in reverse order of creation (see notes in
2522 * ExecHashRemoveNextSkewBucket) and we want the least common MCVs to
2523 * be removed first.
2524 */
2525
2526 for (i = 0; i < mcvsToUse; i++)
2527 {
2528 uint32 hashvalue;
2529 int bucket;
2530
2531 hashvalue = DatumGetUInt32(FunctionCall1Coll(hashstate->skew_hashfunction,
2532 hashstate->skew_collation,
2533 sslot.values[i]));
2534
2535 /*
2536 * While we have not hit a hole in the hashtable and have not hit
2537 * the desired bucket, we have collided with some previous hash
2538 * value, so try the next bucket location. NB: this code must
2539 * match ExecHashGetSkewBucket.
2540 */
2541 bucket = hashvalue & (nbuckets - 1);
2542 while (hashtable->skewBucket[bucket] != NULL &&
2543 hashtable->skewBucket[bucket]->hashvalue != hashvalue)
2544 bucket = (bucket + 1) & (nbuckets - 1);
2545
2546 /*
2547 * If we found an existing bucket with the same hashvalue, leave
2548 * it alone. It's okay for two MCVs to share a hashvalue.
2549 */
2550 if (hashtable->skewBucket[bucket] != NULL)
2551 continue;
2552
2553 /* Okay, create a new skew bucket for this hashvalue. */
2554 hashtable->skewBucket[bucket] = (HashSkewBucket *)
2555 MemoryContextAlloc(hashtable->batchCxt,
2556 sizeof(HashSkewBucket));
2557 hashtable->skewBucket[bucket]->hashvalue = hashvalue;
2558 hashtable->skewBucket[bucket]->tuples = NULL;
2559 hashtable->skewBucketNums[hashtable->nSkewBuckets] = bucket;
2560 hashtable->nSkewBuckets++;
2561 hashtable->spaceUsed += SKEW_BUCKET_OVERHEAD;
2562 hashtable->spaceUsedSkew += SKEW_BUCKET_OVERHEAD;
2563 if (hashtable->spaceUsed > hashtable->spacePeak)
2564 hashtable->spacePeak = hashtable->spaceUsed;
2565 }
2566
2568 }
2569
2570 ReleaseSysCache(statsTuple);
2571}
uint32_t uint32
Definition c.h:618
#define OidIsValid(objectId)
Definition c.h:860
Datum FunctionCall1Coll(FmgrInfo *flinfo, Oid collation, Datum arg1)
Definition fmgr.c:1131
#define SKEW_MIN_OUTER_FRACTION
Definition hashjoin.h:133
#define HeapTupleIsValid(tuple)
Definition htup.h:78
int i
Definition isn.c:77
void free_attstatsslot(AttStatsSlot *sslot)
Definition lsyscache.c:3566
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition lsyscache.c:3456
#define ATTSTATSSLOT_NUMBERS
Definition lsyscache.h:44
#define ATTSTATSSLOT_VALUES
Definition lsyscache.h:43
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1266
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:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
#define InvalidOid
HashSkewBucket ** skewBucket
Definition hashjoin.h:328
HashJoinTuple tuples
Definition hashjoin.h:127
uint32 hashvalue
Definition hashjoin.h:126
AttrNumber skewColumn
Definition plannodes.h:1430
Oid skewTable
Definition plannodes.h:1428
bool skewInherit
Definition plannodes.h:1432
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache3(SysCacheIdentifier cacheId, Datum key1, Datum key2, Datum key3)
Definition syscache.c:240

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

Referenced by ExecHashTableCreate().

◆ ExecHashEstimate()

void ExecHashEstimate ( HashState node,
ParallelContext pcxt 
)

Definition at line 2819 of file nodeHash.c.

2820{
2821 size_t size;
2822
2823 /* don't need this if not instrumenting or no workers */
2824 if (!node->ps.instrument || pcxt->nworkers == 0)
2825 return;
2826
2827 size = mul_size(pcxt->nworkers, sizeof(HashInstrumentation));
2828 size = add_size(size, offsetof(SharedHashInfo, hinstrument));
2829 shm_toc_estimate_chunk(&pcxt->estimator, size);
2831}
#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:485
Size mul_size(Size s1, Size s2)
Definition shmem.c:500
PlanState ps
Definition execnodes.h:2665
shm_toc_estimator estimator
Definition parallel.h:43
Instrumentation * instrument
Definition execnodes.h:1187

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

Referenced by ExecParallelEstimate().

◆ ExecHashGetBucketAndBatch()

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

Definition at line 1986 of file nodeHash.c.

1990{
1991 uint32 nbuckets = (uint32) hashtable->nbuckets;
1992 uint32 nbatch = (uint32) hashtable->nbatch;
1993
1994 if (nbatch > 1)
1995 {
1996 *bucketno = hashvalue & (nbuckets - 1);
1997 *batchno = pg_rotate_right32(hashvalue,
1998 hashtable->log2_nbuckets) & (nbatch - 1);
1999 }
2000 else
2001 {
2002 *bucketno = hashvalue & (nbuckets - 1);
2003 *batchno = 0;
2004 }
2005}
static uint32 pg_rotate_right32(uint32 word, int n)

References fb(), 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 2581 of file nodeHash.c.

2582{
2583 int bucket;
2584
2585 /*
2586 * Always return INVALID_SKEW_BUCKET_NO if not doing skew optimization (in
2587 * particular, this happens after the initial batch is done).
2588 */
2589 if (!hashtable->skewEnabled)
2591
2592 /*
2593 * Since skewBucketLen is a power of 2, we can do a modulo by ANDing.
2594 */
2595 bucket = hashvalue & (hashtable->skewBucketLen - 1);
2596
2597 /*
2598 * While we have not hit a hole in the hashtable and have not hit the
2599 * desired bucket, we have collided with some other hash value, so try the
2600 * next bucket location.
2601 */
2602 while (hashtable->skewBucket[bucket] != NULL &&
2603 hashtable->skewBucket[bucket]->hashvalue != hashvalue)
2604 bucket = (bucket + 1) & (hashtable->skewBucketLen - 1);
2605
2606 /*
2607 * Found the desired bucket?
2608 */
2609 if (hashtable->skewBucket[bucket] != NULL)
2610 return bucket;
2611
2612 /*
2613 * There must not be any hashtable entry for this hash value.
2614 */
2616}
#define INVALID_SKEW_BUCKET_NO
Definition hashjoin.h:131

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

Referenced by ExecHashJoinImpl(), and MultiExecPrivateHash().

◆ ExecHashIncreaseBatchSize()

static bool ExecHashIncreaseBatchSize ( HashJoinTable  hashtable)
static

Definition at line 1023 of file nodeHash.c.

1024{
1025 /*
1026 * How much additional memory would doubling nbatch use? Each batch may
1027 * require two buffered files (inner/outer), with a BLCKSZ buffer.
1028 */
1029 size_t batchSpace = (hashtable->nbatch * 2 * (size_t) BLCKSZ);
1030
1031 /*
1032 * Compare the new space needed for doubling nbatch and for enlarging the
1033 * in-memory hash table. If doubling the hash table needs less memory,
1034 * just do that. Otherwise, continue with doubling the nbatch.
1035 *
1036 * We're either doubling spaceAllowed or batchSpace, so which of those
1037 * increases the memory usage the least is the same as comparing the
1038 * values directly.
1039 */
1040 if (hashtable->spaceAllowed <= batchSpace)
1041 {
1042 hashtable->spaceAllowed *= 2;
1043 return true;
1044 }
1045
1046 return false;
1047}

References fb(), HashJoinTableData::nbatch, and HashJoinTableData::spaceAllowed.

Referenced by ExecHashIncreaseNumBatches().

◆ ExecHashIncreaseNumBatches()

static void ExecHashIncreaseNumBatches ( HashJoinTable  hashtable)
static

Definition at line 1055 of file nodeHash.c.

1056{
1057 int oldnbatch = hashtable->nbatch;
1058 int curbatch = hashtable->curbatch;
1059 int nbatch;
1060 long ninmemory;
1061 long nfreed;
1063
1064 /* do nothing if we've decided to shut off growth */
1065 if (!hashtable->growEnabled)
1066 return;
1067
1068 /* safety check to avoid overflow */
1069 if (oldnbatch > Min(INT_MAX / 2, MaxAllocSize / (sizeof(void *) * 2)))
1070 return;
1071
1072 /* consider increasing size of the in-memory hash table instead */
1073 if (ExecHashIncreaseBatchSize(hashtable))
1074 return;
1075
1076 nbatch = oldnbatch * 2;
1077 Assert(nbatch > 1);
1078
1079#ifdef HJDEBUG
1080 printf("Hashjoin %p: increasing nbatch to %d because space = %zu\n",
1081 hashtable, nbatch, hashtable->spaceUsed);
1082#endif
1083
1084 if (hashtable->innerBatchFile == NULL)
1085 {
1087
1088 /* we had no file arrays before */
1089 hashtable->innerBatchFile = palloc0_array(BufFile *, nbatch);
1090 hashtable->outerBatchFile = palloc0_array(BufFile *, nbatch);
1091
1093
1094 /* time to establish the temp tablespaces, too */
1096 }
1097 else
1098 {
1099 /* enlarge arrays and zero out added entries */
1100 hashtable->innerBatchFile = repalloc0_array(hashtable->innerBatchFile, BufFile *, oldnbatch, nbatch);
1101 hashtable->outerBatchFile = repalloc0_array(hashtable->outerBatchFile, BufFile *, oldnbatch, nbatch);
1102 }
1103
1104 hashtable->nbatch = nbatch;
1105
1106 /*
1107 * Scan through the existing hash table entries and dump out any that are
1108 * no longer of the current batch.
1109 */
1110 ninmemory = nfreed = 0;
1111
1112 /* If know we need to resize nbuckets, we can do it while rebatching. */
1113 if (hashtable->nbuckets_optimal != hashtable->nbuckets)
1114 {
1115 /* we never decrease the number of buckets */
1116 Assert(hashtable->nbuckets_optimal > hashtable->nbuckets);
1117
1118 hashtable->nbuckets = hashtable->nbuckets_optimal;
1119 hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
1120
1121 hashtable->buckets.unshared =
1122 repalloc_array(hashtable->buckets.unshared,
1123 HashJoinTuple, hashtable->nbuckets);
1124 }
1125
1126 /*
1127 * We will scan through the chunks directly, so that we can reset the
1128 * buckets now and not have to keep track which tuples in the buckets have
1129 * already been processed. We will free the old chunks as we go.
1130 */
1131 memset(hashtable->buckets.unshared, 0,
1132 sizeof(HashJoinTuple) * hashtable->nbuckets);
1133 oldchunks = hashtable->chunks;
1134 hashtable->chunks = NULL;
1135
1136 /* so, let's scan through the old chunks, and all tuples in each chunk */
1137 while (oldchunks != NULL)
1138 {
1140
1141 /* position within the buffer (up to oldchunks->used) */
1142 size_t idx = 0;
1143
1144 /* process all tuples stored in this chunk (and then free it) */
1145 while (idx < oldchunks->used)
1146 {
1149 int hashTupleSize = (HJTUPLE_OVERHEAD + tuple->t_len);
1150 int bucketno;
1151 int batchno;
1152
1153 ninmemory++;
1154 ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1155 &bucketno, &batchno);
1156
1157 if (batchno == curbatch)
1158 {
1159 /* keep tuple in memory - copy it into the new chunk */
1161
1164
1165 /* and add it back to the appropriate bucket */
1166 copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1167 hashtable->buckets.unshared[bucketno] = copyTuple;
1168 }
1169 else
1170 {
1171 /* dump it out */
1172 Assert(batchno > curbatch);
1174 hashTuple->hashvalue,
1175 &hashtable->innerBatchFile[batchno],
1176 hashtable);
1177
1178 hashtable->spaceUsed -= hashTupleSize;
1179 nfreed++;
1180 }
1181
1182 /* next tuple in this chunk */
1184
1185 /* allow this loop to be cancellable */
1187 }
1188
1189 /* we're done with this chunk - free it and proceed to the next one */
1192 }
1193
1194#ifdef HJDEBUG
1195 printf("Hashjoin %p: freed %ld of %ld tuples, space now %zu\n",
1196 hashtable, nfreed, ninmemory, hashtable->spaceUsed);
1197#endif
1198
1199 /*
1200 * If we dumped out either all or none of the tuples in the table, disable
1201 * further expansion of nbatch. This situation implies that we have
1202 * enough tuples of identical hashvalues to overflow spaceAllowed.
1203 * Increasing nbatch will not fix it since there's no way to subdivide the
1204 * group any more finely. We have to just gut it out and hope the server
1205 * has enough RAM.
1206 */
1207 if (nfreed == 0 || nfreed == ninmemory)
1208 {
1209 hashtable->growEnabled = false;
1210#ifdef HJDEBUG
1211 printf("Hashjoin %p: disabling further increase of nbatch\n",
1212 hashtable);
1213#endif
1214 }
1215}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:262
void PrepareTempTablespaces(void)
#define repalloc_array(pointer, type, count)
Definition fe_memutils.h:78
#define palloc0_array(type, count)
Definition fe_memutils.h:77
#define HJTUPLE_MINTUPLE(hjtup)
Definition hashjoin.h:102
void pfree(void *pointer)
Definition mcxt.c:1616
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
static bool ExecHashIncreaseBatchSize(HashJoinTable hashtable)
Definition nodeHash.c:1023
static void * dense_alloc(HashJoinTable hashtable, Size size)
Definition nodeHash.c:2954
void ExecHashGetBucketAndBatch(HashJoinTable hashtable, uint32 hashvalue, int *bucketno, int *batchno)
Definition nodeHash.c:1986
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:266
struct HashJoinTupleData ** unshared
Definition hashjoin.h:322
MemoryContext spillCxt
Definition hashjoin.h:370
union HashJoinTableData::@113 buckets
BufFile ** innerBatchFile
Definition hashjoin.h:359
int log2_nbuckets_optimal
Definition hashjoin.h:316
BufFile ** outerBatchFile
Definition hashjoin.h:360

References Assert, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, HashJoinTableData::chunks, HashJoinTableData::curbatch, dense_alloc(), ExecHashGetBucketAndBatch(), ExecHashIncreaseBatchSize(), ExecHashJoinSaveTuple(), fb(), HashJoinTableData::growEnabled, HASH_CHUNK_DATA, 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, HashMemoryChunkData::next, HashJoinTableData::outerBatchFile, palloc0_array, pfree(), PrepareTempTablespaces(), printf, repalloc0_array, repalloc_array, HashJoinTableData::spaceUsed, HashJoinTableData::spillCxt, MinimalTupleData::t_len, HashMemoryChunkData::unshared, and HashJoinTableData::unshared.

Referenced by ExecHashSkewTableInsert(), and ExecHashTableInsert().

◆ ExecHashIncreaseNumBuckets()

static void ExecHashIncreaseNumBuckets ( HashJoinTable  hashtable)
static

Definition at line 1612 of file nodeHash.c.

1613{
1614 HashMemoryChunk chunk;
1615
1616 /* do nothing if not an increase (it's called increase for a reason) */
1617 if (hashtable->nbuckets >= hashtable->nbuckets_optimal)
1618 return;
1619
1620#ifdef HJDEBUG
1621 printf("Hashjoin %p: increasing nbuckets %d => %d\n",
1622 hashtable, hashtable->nbuckets, hashtable->nbuckets_optimal);
1623#endif
1624
1625 hashtable->nbuckets = hashtable->nbuckets_optimal;
1626 hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
1627
1628 Assert(hashtable->nbuckets > 1);
1629 Assert(hashtable->nbuckets <= (INT_MAX / 2));
1630 Assert(hashtable->nbuckets == (1 << hashtable->log2_nbuckets));
1631
1632 /*
1633 * Just reallocate the proper number of buckets - we don't need to walk
1634 * through them - we can walk the dense-allocated chunks (just like in
1635 * ExecHashIncreaseNumBatches, but without all the copying into new
1636 * chunks)
1637 */
1638 hashtable->buckets.unshared =
1639 repalloc_array(hashtable->buckets.unshared,
1640 HashJoinTuple, hashtable->nbuckets);
1641
1642 memset(hashtable->buckets.unshared, 0,
1643 hashtable->nbuckets * sizeof(HashJoinTuple));
1644
1645 /* scan through all tuples in all chunks to rebuild the hash table */
1646 for (chunk = hashtable->chunks; chunk != NULL; chunk = chunk->next.unshared)
1647 {
1648 /* process all tuples stored in this chunk */
1649 size_t idx = 0;
1650
1651 while (idx < chunk->used)
1652 {
1654 int bucketno;
1655 int batchno;
1656
1657 ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1658 &bucketno, &batchno);
1659
1660 /* add the tuple to the proper bucket */
1661 hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1662 hashtable->buckets.unshared[bucketno] = hashTuple;
1663
1664 /* advance index past the tuple */
1666 HJTUPLE_MINTUPLE(hashTuple)->t_len);
1667 }
1668
1669 /* allow this loop to be cancellable */
1671 }
1672}

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

Referenced by MultiExecPrivateHash().

◆ ExecHashInitializeDSM()

void ExecHashInitializeDSM ( HashState node,
ParallelContext pcxt 
)

Definition at line 2838 of file nodeHash.c.

2839{
2840 size_t size;
2841
2842 /* don't need this if not instrumenting or no workers */
2843 if (!node->ps.instrument || pcxt->nworkers == 0)
2844 return;
2845
2846 size = offsetof(SharedHashInfo, hinstrument) +
2847 pcxt->nworkers * sizeof(HashInstrumentation);
2848 node->shared_info = (SharedHashInfo *) shm_toc_allocate(pcxt->toc, size);
2849
2850 /* Each per-worker area must start out as zeroes. */
2851 memset(node->shared_info, 0, size);
2852
2853 node->shared_info->num_workers = pcxt->nworkers;
2854 shm_toc_insert(pcxt->toc, node->ps.plan->plan_node_id,
2855 node->shared_info);
2856}
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition shm_toc.c:88
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition shm_toc.c:171
SharedHashInfo * shared_info
Definition execnodes.h:2681
shm_toc * toc
Definition parallel.h:46
Plan * plan
Definition execnodes.h:1177
int plan_node_id
Definition plannodes.h:231

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

Referenced by ExecParallelInitializeDSM().

◆ ExecHashInitializeWorker()

void ExecHashInitializeWorker ( HashState node,
ParallelWorkerContext pwcxt 
)

Definition at line 2863 of file nodeHash.c.

2864{
2865 SharedHashInfo *shared_info;
2866
2867 /* don't need this if not instrumenting */
2868 if (!node->ps.instrument)
2869 return;
2870
2871 /*
2872 * Find our entry in the shared area, and set up a pointer to it so that
2873 * we'll accumulate stats there when shutting down or rebuilding the hash
2874 * table.
2875 */
2876 shared_info = (SharedHashInfo *)
2877 shm_toc_lookup(pwcxt->toc, node->ps.plan->plan_node_id, false);
2878 node->hinstrument = &shared_info->hinstrument[ParallelWorkerNumber];
2879}
int ParallelWorkerNumber
Definition parallel.c:117
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition shm_toc.c:232
HashInstrumentation * hinstrument
Definition execnodes.h:2688
HashInstrumentation hinstrument[FLEXIBLE_ARRAY_MEMBER]

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

Referenced by ExecParallelInitializeWorker().

◆ ExecHashRemoveNextSkewBucket()

static void ExecHashRemoveNextSkewBucket ( HashJoinTable  hashtable)
static

Definition at line 2674 of file nodeHash.c.

2675{
2676 int bucketToRemove;
2678 uint32 hashvalue;
2679 int bucketno;
2680 int batchno;
2682
2683 /* Locate the bucket to remove */
2684 bucketToRemove = hashtable->skewBucketNums[hashtable->nSkewBuckets - 1];
2685 bucket = hashtable->skewBucket[bucketToRemove];
2686
2687 /*
2688 * Calculate which bucket and batch the tuples belong to in the main
2689 * hashtable. They all have the same hash value, so it's the same for all
2690 * of them. Also note that it's not possible for nbatch to increase while
2691 * we are processing the tuples.
2692 */
2693 hashvalue = bucket->hashvalue;
2694 ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
2695
2696 /* Process all tuples in the bucket */
2697 hashTuple = bucket->tuples;
2698 while (hashTuple != NULL)
2699 {
2701 MinimalTuple tuple;
2703
2704 /*
2705 * This code must agree with ExecHashTableInsert. We do not use
2706 * ExecHashTableInsert directly as ExecHashTableInsert expects a
2707 * TupleTableSlot while we already have HashJoinTuples.
2708 */
2709 tuple = HJTUPLE_MINTUPLE(hashTuple);
2710 tupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
2711
2712 /* Decide whether to put the tuple in the hash table or a temp file */
2713 if (batchno == hashtable->curbatch)
2714 {
2715 /* Move the tuple to the main hash table */
2717
2718 /*
2719 * We must copy the tuple into the dense storage, else it will not
2720 * be found by, eg, ExecHashIncreaseNumBatches.
2721 */
2725
2726 copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
2727 hashtable->buckets.unshared[bucketno] = copyTuple;
2728
2729 /* We have reduced skew space, but overall space doesn't change */
2730 hashtable->spaceUsedSkew -= tupleSize;
2731 }
2732 else
2733 {
2734 /* Put the tuple into a temp file for later batches */
2735 Assert(batchno > hashtable->curbatch);
2736 ExecHashJoinSaveTuple(tuple, hashvalue,
2737 &hashtable->innerBatchFile[batchno],
2738 hashtable);
2740 hashtable->spaceUsed -= tupleSize;
2741 hashtable->spaceUsedSkew -= tupleSize;
2742 }
2743
2744 /*
2745 * We must reduce skewTuples, but totalTuples doesn't change since it
2746 * counts both main and skew tuples.
2747 */
2748 hashtable->skewTuples -= 1;
2749
2751
2752 /* allow this loop to be cancellable */
2754 }
2755
2756 /*
2757 * Free the bucket struct itself and reset the hashtable entry to NULL.
2758 *
2759 * NOTE: this is not nearly as simple as it looks on the surface, because
2760 * of the possibility of collisions in the hashtable. Suppose that hash
2761 * values A and B collide at a particular hashtable entry, and that A was
2762 * entered first so B gets shifted to a different table entry. If we were
2763 * to remove A first then ExecHashGetSkewBucket would mistakenly start
2764 * reporting that B is not in the hashtable, because it would hit the NULL
2765 * before finding B. However, we always remove entries in the reverse
2766 * order of creation, so this failure cannot happen.
2767 */
2768 hashtable->skewBucket[bucketToRemove] = NULL;
2769 hashtable->nSkewBuckets--;
2770 pfree(bucket);
2771 hashtable->spaceUsed -= SKEW_BUCKET_OVERHEAD;
2772 hashtable->spaceUsedSkew -= SKEW_BUCKET_OVERHEAD;
2773
2774 /*
2775 * If we have removed all skew buckets then give up on skew optimization.
2776 * Release the arrays since they aren't useful any more.
2777 */
2778 if (hashtable->nSkewBuckets == 0)
2779 {
2780 hashtable->skewEnabled = false;
2781 pfree(hashtable->skewBucket);
2782 pfree(hashtable->skewBucketNums);
2783 hashtable->skewBucket = NULL;
2784 hashtable->skewBucketNums = NULL;
2785 hashtable->spaceUsed -= hashtable->spaceUsedSkew;
2786 hashtable->spaceUsedSkew = 0;
2787 }
2788}
size_t Size
Definition c.h:691
union HashJoinTupleData::@111 next
struct HashJoinTupleData * unshared
Definition hashjoin.h:94

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

Referenced by ExecHashSkewTableInsert().

◆ ExecHashRetrieveInstrumentation()

void ExecHashRetrieveInstrumentation ( HashState node)

Definition at line 2904 of file nodeHash.c.

2905{
2906 SharedHashInfo *shared_info = node->shared_info;
2907 size_t size;
2908
2909 if (shared_info == NULL)
2910 return;
2911
2912 /* Replace node->shared_info with a copy in backend-local memory. */
2913 size = offsetof(SharedHashInfo, hinstrument) +
2914 shared_info->num_workers * sizeof(HashInstrumentation);
2915 node->shared_info = palloc(size);
2916 memcpy(node->shared_info, shared_info, size);
2917}
void * palloc(Size size)
Definition mcxt.c:1387

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecHashSkewTableInsert()

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

Definition at line 2627 of file nodeHash.c.

2631{
2632 bool shouldFree;
2635 int hashTupleSize;
2636
2637 /* Create the HashJoinTuple */
2641 hashTuple->hashvalue = hashvalue;
2642 memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
2644
2645 /* Push it onto the front of the skew bucket's list */
2646 hashTuple->next.unshared = hashtable->skewBucket[bucketNumber]->tuples;
2647 hashtable->skewBucket[bucketNumber]->tuples = hashTuple;
2648 Assert(hashTuple != hashTuple->next.unshared);
2649
2650 /* Account for space used, and back off if we've used too much */
2651 hashtable->skewTuples += 1;
2652 hashtable->spaceUsed += hashTupleSize;
2653 hashtable->spaceUsedSkew += hashTupleSize;
2654 if (hashtable->spaceUsed > hashtable->spacePeak)
2655 hashtable->spacePeak = hashtable->spaceUsed;
2656 while (hashtable->spaceUsedSkew > hashtable->spaceAllowedSkew)
2658
2659 /* Check we are not over the total spaceAllowed, either */
2660 if (hashtable->spaceUsed > hashtable->spaceAllowed)
2661 ExecHashIncreaseNumBatches(hashtable);
2662
2663 if (shouldFree)
2665}
MinimalTuple ExecFetchSlotMinimalTuple(TupleTableSlot *slot, bool *shouldFree)
void heap_free_minimal_tuple(MinimalTuple mtup)
Definition heaptuple.c:1478
static void HeapTupleHeaderClearMatch(MinimalTupleData *tup)
static void ExecHashRemoveNextSkewBucket(HashJoinTable hashtable)
Definition nodeHash.c:2674
static void ExecHashIncreaseNumBatches(HashJoinTable hashtable)
Definition nodeHash.c:1055

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

Referenced by MultiExecPrivateHash().

◆ ExecHashTableCreate()

HashJoinTable ExecHashTableCreate ( HashState state)

Definition at line 471 of file nodeHash.c.

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

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(), fb(), HashJoinTableData::growEnabled, ParallelHashJoinState::growth, HashJoinTableData::hashCxt, HashJoinTableData::innerBatchFile, HashJoinTableData::log2_nbuckets, HashJoinTableData::log2_nbuckets_optimal, MemoryContextSwitchTo(), 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, pg_ceil_log2_32(), PHJ_BUILD_ELECT, PHJ_GROWTH_OK, Hash::plan, PrepareTempTablespaces(), printf, HashJoinTableData::reportTuples, 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 981 of file nodeHash.c.

982{
983 int i;
984
985 /*
986 * Make sure all the temp files are closed. We skip batch 0, since it
987 * can't have any temp files (and the arrays might not even exist if
988 * nbatch is only 1). Parallel hash joins don't use these files.
989 */
990 if (hashtable->innerBatchFile != NULL)
991 {
992 for (i = 1; i < hashtable->nbatch; i++)
993 {
994 if (hashtable->innerBatchFile[i])
995 BufFileClose(hashtable->innerBatchFile[i]);
996 if (hashtable->outerBatchFile[i])
997 BufFileClose(hashtable->outerBatchFile[i]);
998 }
999 }
1000
1001 /* Release working memory (batchCxt is a child, so it goes away too) */
1002 MemoryContextDelete(hashtable->hashCxt);
1003
1004 /* And drop the control block */
1005 pfree(hashtable);
1006}
void BufFileClose(BufFile *file)
Definition buffile.c:413
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472

References BufFileClose(), fb(), 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 3459 of file nodeHash.c.

3460{
3461 ParallelHashJoinState *pstate = hashtable->parallel_state;
3462
3463 /*
3464 * If we're involved in a parallel query, we must either have gotten all
3465 * the way to PHJ_BUILD_RUN, or joined too late and be in PHJ_BUILD_FREE.
3466 */
3467 Assert(!pstate ||
3469
3470 if (pstate && BarrierPhase(&pstate->build_barrier) == PHJ_BUILD_RUN)
3471 {
3472 int i;
3473
3474 /* Make sure any temporary files are closed. */
3475 if (hashtable->batches)
3476 {
3477 for (i = 0; i < hashtable->nbatch; ++i)
3478 {
3479 sts_end_write(hashtable->batches[i].inner_tuples);
3480 sts_end_write(hashtable->batches[i].outer_tuples);
3483 }
3484 }
3485
3486 /* If we're last to detach, clean up shared memory. */
3488 {
3489 /*
3490 * Late joining processes will see this state and give up
3491 * immediately.
3492 */
3494
3495 if (DsaPointerIsValid(pstate->batches))
3496 {
3497 dsa_free(hashtable->area, pstate->batches);
3498 pstate->batches = InvalidDsaPointer;
3499 }
3500 }
3501 }
3502 hashtable->parallel_state = NULL;
3503}
bool BarrierArriveAndDetach(Barrier *barrier)
Definition barrier.c:203
void dsa_free(dsa_area *area, dsa_pointer dp)
Definition dsa.c:841
#define InvalidDsaPointer
Definition dsa.h:78
#define DsaPointerIsValid(x)
Definition dsa.h:106
#define PHJ_BUILD_FREE
Definition hashjoin.h:285
#define PHJ_BUILD_RUN
Definition hashjoin.h:284
void sts_end_write(SharedTuplestoreAccessor *accessor)
void sts_end_parallel_scan(SharedTuplestoreAccessor *accessor)
ParallelHashJoinBatchAccessor * batches
Definition hashjoin.h:379
ParallelHashJoinState * parallel_state
Definition hashjoin.h:378
dsa_area * area
Definition hashjoin.h:377
SharedTuplestoreAccessor * outer_tuples
Definition hashjoin.h:232
SharedTuplestoreAccessor * inner_tuples
Definition hashjoin.h:231
dsa_pointer batches
Definition hashjoin.h:259

References HashJoinTableData::area, Assert, BarrierArriveAndDetach(), BarrierPhase(), ParallelHashJoinState::batches, HashJoinTableData::batches, ParallelHashJoinState::build_barrier, dsa_free(), DsaPointerIsValid, fb(), 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 3367 of file nodeHash.c.

3368{
3369 if (hashtable->parallel_state != NULL &&
3370 hashtable->curbatch >= 0)
3371 {
3372 int curbatch = hashtable->curbatch;
3373 ParallelHashJoinBatch *batch = hashtable->batches[curbatch].shared;
3374 bool attached = true;
3375
3376 /* Make sure any temporary files are closed. */
3377 sts_end_parallel_scan(hashtable->batches[curbatch].inner_tuples);
3378 sts_end_parallel_scan(hashtable->batches[curbatch].outer_tuples);
3379
3380 /* After attaching we always get at least to PHJ_BATCH_PROBE. */
3381 Assert(BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE ||
3382 BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_SCAN);
3383
3384 /*
3385 * If we're abandoning the PHJ_BATCH_PROBE phase early without having
3386 * reached the end of it, it means the plan doesn't want any more
3387 * tuples, and it is happy to abandon any tuples buffered in this
3388 * process's subplans. For correctness, we can't allow any process to
3389 * execute the PHJ_BATCH_SCAN phase, because we will never have the
3390 * complete set of match bits. Therefore we skip emitting unmatched
3391 * tuples in all backends (if this is a full/right join), as if those
3392 * tuples were all due to be emitted by this process and it has
3393 * abandoned them too.
3394 */
3395 if (BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE &&
3396 !hashtable->batches[curbatch].outer_eof)
3397 {
3398 /*
3399 * This flag may be written to by multiple backends during
3400 * PHJ_BATCH_PROBE phase, but will only be read in PHJ_BATCH_SCAN
3401 * phase so requires no extra locking.
3402 */
3403 batch->skip_unmatched = true;
3404 }
3405
3406 /*
3407 * Even if we aren't doing a full/right outer join, we'll step through
3408 * the PHJ_BATCH_SCAN phase just to maintain the invariant that
3409 * freeing happens in PHJ_BATCH_FREE, but that'll be wait-free.
3410 */
3411 if (BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE)
3413 if (attached && BarrierArriveAndDetach(&batch->batch_barrier))
3414 {
3415 /*
3416 * We are not longer attached to the batch barrier, but we're the
3417 * process that was chosen to free resources and it's safe to
3418 * assert the current phase. The ParallelHashJoinBatch can't go
3419 * away underneath us while we are attached to the build barrier,
3420 * making this access safe.
3421 */
3422 Assert(BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_FREE);
3423
3424 /* Free shared chunks and buckets. */
3425 while (DsaPointerIsValid(batch->chunks))
3426 {
3427 HashMemoryChunk chunk =
3428 dsa_get_address(hashtable->area, batch->chunks);
3429 dsa_pointer next = chunk->next.shared;
3430
3431 dsa_free(hashtable->area, batch->chunks);
3432 batch->chunks = next;
3433 }
3434 if (DsaPointerIsValid(batch->buckets))
3435 {
3436 dsa_free(hashtable->area, batch->buckets);
3437 batch->buckets = InvalidDsaPointer;
3438 }
3439 }
3440
3441 /*
3442 * Track the largest batch we've been attached to. Though each
3443 * backend might see a different subset of batches, explain.c will
3444 * scan the results from all backends to find the largest value.
3445 */
3446 hashtable->spacePeak =
3447 Max(hashtable->spacePeak,
3448 batch->size + sizeof(dsa_pointer_atomic) * hashtable->nbuckets);
3449
3450 /* Remember that we are not attached to a batch. */
3451 hashtable->curbatch = -1;
3452 }
3453}
bool BarrierArriveAndDetachExceptLast(Barrier *barrier)
Definition barrier.c:213
static int32 next
Definition blutils.c:225
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition dsa.c:957
uint64 dsa_pointer
Definition dsa.h:62
#define PHJ_BATCH_SCAN
Definition hashjoin.h:292
#define PHJ_BATCH_PROBE
Definition hashjoin.h:291
#define PHJ_BATCH_FREE
Definition hashjoin.h:293
dsa_pointer shared
Definition hashjoin.h:149
ParallelHashJoinBatch * shared
Definition hashjoin.h:220

References HashJoinTableData::area, Assert, BarrierArriveAndDetach(), BarrierArriveAndDetachExceptLast(), BarrierPhase(), HashJoinTableData::batches, HashJoinTableData::curbatch, dsa_free(), dsa_get_address(), DsaPointerIsValid, fb(), ParallelHashJoinBatchAccessor::inner_tuples, InvalidDsaPointer, Max, HashJoinTableData::nbuckets, next, HashMemoryChunkData::next, ParallelHashJoinBatchAccessor::outer_eof, ParallelHashJoinBatchAccessor::outer_tuples, HashJoinTableData::parallel_state, PHJ_BATCH_FREE, PHJ_BATCH_PROBE, PHJ_BATCH_SCAN, HashMemoryChunkData::shared, ParallelHashJoinBatchAccessor::shared, 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 1774 of file nodeHash.c.

1777{
1778 bool shouldFree;
1780 int bucketno;
1781 int batchno;
1782
1783 ExecHashGetBucketAndBatch(hashtable, hashvalue,
1784 &bucketno, &batchno);
1785
1786 /*
1787 * decide whether to put the tuple in the hash table or a temp file
1788 */
1789 if (batchno == hashtable->curbatch)
1790 {
1791 /*
1792 * put the tuple in hash table
1793 */
1795 int hashTupleSize;
1796
1797 /* Create the HashJoinTuple */
1800
1801 hashTuple->hashvalue = hashvalue;
1802 memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
1803
1804 /*
1805 * We always reset the tuple-matched flag on insertion. This is okay
1806 * even when reloading a tuple from a batch file, since the tuple
1807 * could not possibly have been matched to an outer tuple before it
1808 * went into the batch file.
1809 */
1811
1812 /* Push it onto the front of the bucket's list */
1813 hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
1814 hashtable->buckets.unshared[bucketno] = hashTuple;
1815
1816 /*
1817 * Increase the (optimal) number of buckets if we just exceeded the
1818 * NTUP_PER_BUCKET threshold, but only when there's still a single
1819 * batch. Note that totalTuples - skewTuples is a reliable indicator
1820 * of the hash table's size only as long as there's just one batch.
1821 */
1822 if (hashtable->nbatch == 1 &&
1823 (hashtable->totalTuples - hashtable->skewTuples) >
1824 (hashtable->nbuckets_optimal * NTUP_PER_BUCKET))
1825 {
1826 /* Guard against integer overflow and alloc size overflow */
1827 if (hashtable->nbuckets_optimal <= INT_MAX / 2 &&
1828 hashtable->nbuckets_optimal * 2 <= MaxAllocSize / sizeof(HashJoinTuple))
1829 {
1830 hashtable->nbuckets_optimal *= 2;
1831 hashtable->log2_nbuckets_optimal += 1;
1832 }
1833 }
1834
1835 /* Account for space used, and back off if we've used too much */
1836 hashtable->spaceUsed += hashTupleSize;
1837 if (hashtable->spaceUsed > hashtable->spacePeak)
1838 hashtable->spacePeak = hashtable->spaceUsed;
1839 if (hashtable->spaceUsed +
1840 hashtable->nbuckets_optimal * sizeof(HashJoinTuple)
1841 > hashtable->spaceAllowed)
1842 ExecHashIncreaseNumBatches(hashtable);
1843 }
1844 else
1845 {
1846 /*
1847 * put the tuple into a temp file for later batches
1848 */
1849 Assert(batchno > hashtable->curbatch);
1851 hashvalue,
1852 &hashtable->innerBatchFile[batchno],
1853 hashtable);
1854 }
1855
1856 if (shouldFree)
1858}

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

Referenced by ExecHashJoinNewBatch(), and MultiExecPrivateHash().

◆ ExecHashTableReset()

void ExecHashTableReset ( HashJoinTable  hashtable)

Definition at line 2353 of file nodeHash.c.

2354{
2356 int nbuckets = hashtable->nbuckets;
2357
2358 /*
2359 * Release all the hash buckets and tuples acquired in the prior pass, and
2360 * reinitialize the context for a new pass.
2361 */
2362 MemoryContextReset(hashtable->batchCxt);
2364
2365 /* Reallocate and reinitialize the hash bucket headers. */
2366 hashtable->buckets.unshared = palloc0_array(HashJoinTuple, nbuckets);
2367
2368 hashtable->spaceUsed = 0;
2369
2371
2372 /* Forget the chunks (the memory was freed by the context reset above). */
2373 hashtable->chunks = NULL;
2374}
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403

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

Referenced by ExecHashJoinNewBatch().

◆ ExecHashTableResetMatchFlags()

void ExecHashTableResetMatchFlags ( HashJoinTable  hashtable)

Definition at line 2381 of file nodeHash.c.

2382{
2383 HashJoinTuple tuple;
2384 int i;
2385
2386 /* Reset all flags in the main table ... */
2387 for (i = 0; i < hashtable->nbuckets; i++)
2388 {
2389 for (tuple = hashtable->buckets.unshared[i]; tuple != NULL;
2390 tuple = tuple->next.unshared)
2392 }
2393
2394 /* ... and the same for the skew buckets, if any */
2395 for (i = 0; i < hashtable->nSkewBuckets; i++)
2396 {
2397 int j = hashtable->skewBucketNums[i];
2398 HashSkewBucket *skewBucket = hashtable->skewBucket[j];
2399
2400 for (tuple = skewBucket->tuples; tuple != NULL; tuple = tuple->next.unshared)
2402 }
2403}
int j
Definition isn.c:78

References HashJoinTableData::buckets, fb(), 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 399 of file nodeHash.c.

400{
402
403 /* check for unsupported flags */
405
406 /*
407 * create state structure
408 */
410 hashstate->ps.plan = (Plan *) node;
411 hashstate->ps.state = estate;
412 hashstate->ps.ExecProcNode = ExecHash;
413 /* delay building hashtable until ExecHashTableCreate() in executor run */
414 hashstate->hashtable = NULL;
415
416 /*
417 * Miscellaneous initialization
418 *
419 * create expression context for node
420 */
421 ExecAssignExprContext(estate, &hashstate->ps);
422
423 /*
424 * initialize child nodes
425 */
426 outerPlanState(hashstate) = ExecInitNode(outerPlan(node), estate, eflags);
427
428 /*
429 * initialize our result slot and type. No need to build projection
430 * because this node doesn't do projections.
431 */
433 hashstate->ps.ps_ProjInfo = NULL;
434
435 Assert(node->plan.qual == NIL);
436
437 /* these fields will be filled by ExecInitHashJoin() */
438 hashstate->hash_expr = NULL;
439 hashstate->null_tuple_store = NULL;
440 hashstate->keep_null_tuples = false;
441
442 return hashstate;
443}
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsMinimalTuple
Definition execTuples.c:86
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition execUtils.c:490
#define EXEC_FLAG_BACKWARD
Definition executor.h:70
#define EXEC_FLAG_MARK
Definition executor.h:71
static TupleTableSlot * ExecHash(PlanState *pstate)
Definition nodeHash.c:92
#define makeNode(_type_)
Definition nodes.h:161
#define NIL
Definition pg_list.h:68
Plan plan
Definition plannodes.h:1419
List * qual
Definition plannodes.h:235

References Assert, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, ExecAssignExprContext(), ExecHash(), ExecInitNode(), ExecInitResultTupleSlotTL(), fb(), makeNode, NIL, outerPlan, outerPlanState, Hash::plan, Plan::qual, and TTSOpsMinimalTuple.

Referenced by ExecInitNode().

◆ ExecParallelHashCloseBatchAccessors()

static void ExecParallelHashCloseBatchAccessors ( HashJoinTable  hashtable)
static

Definition at line 3262 of file nodeHash.c.

3263{
3264 int i;
3265
3266 for (i = 0; i < hashtable->nbatch; ++i)
3267 {
3268 /* Make sure no files are left open. */
3269 sts_end_write(hashtable->batches[i].inner_tuples);
3270 sts_end_write(hashtable->batches[i].outer_tuples);
3273 }
3274 pfree(hashtable->batches);
3275 hashtable->batches = NULL;
3276}

References HashJoinTableData::batches, fb(), 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 3283 of file nodeHash.c.

3284{
3285 ParallelHashJoinState *pstate = hashtable->parallel_state;
3286 ParallelHashJoinBatch *batches;
3288 int i;
3289
3290 if (hashtable->batches != NULL)
3291 {
3292 if (hashtable->nbatch == pstate->nbatch)
3293 return;
3295 }
3296
3297 /*
3298 * We should never see a state where the batch-tracking array is freed,
3299 * because we should have given up sooner if we join when the build
3300 * barrier has reached the PHJ_BUILD_FREE phase.
3301 */
3303
3304 /*
3305 * Use hash join spill memory context to allocate accessors, including
3306 * buffers for the temporary files.
3307 */
3309
3310 /* Allocate this backend's accessor array. */
3311 hashtable->nbatch = pstate->nbatch;
3312 hashtable->batches =
3314
3315 /* Find the base of the pseudo-array of ParallelHashJoinBatch objects. */
3316 batches = (ParallelHashJoinBatch *)
3317 dsa_get_address(hashtable->area, pstate->batches);
3318
3319 /* Set up the accessor array and attach to the tuplestores. */
3320 for (i = 0; i < hashtable->nbatch; ++i)
3321 {
3324
3325 accessor->shared = shared;
3326 accessor->preallocated = 0;
3327 accessor->done = false;
3328 accessor->outer_eof = false;
3329 accessor->inner_tuples =
3332 &pstate->fileset);
3333 accessor->outer_tuples =
3335 pstate->nparticipants),
3337 &pstate->fileset);
3338 }
3339
3341}
#define ParallelHashJoinBatchInner(batch)
Definition hashjoin.h:193
#define NthParallelHashJoinBatch(base, n)
Definition hashjoin.h:209
#define ParallelHashJoinBatchOuter(batch, nparticipants)
Definition hashjoin.h:198
static void ExecParallelHashCloseBatchAccessors(HashJoinTable hashtable)
Definition nodeHash.c:3262
SharedTuplestoreAccessor * sts_attach(SharedTuplestore *sts, int my_participant_number, SharedFileSet *fileset)
SharedFileSet fileset
Definition hashjoin.h:276

References HashJoinTableData::area, Assert, ParallelHashJoinState::batches, HashJoinTableData::batches, dsa_get_address(), DsaPointerIsValid, ExecParallelHashCloseBatchAccessors(), fb(), ParallelHashJoinState::fileset, i, MemoryContextSwitchTo(), ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinState::nparticipants, NthParallelHashJoinBatch, palloc0_array, HashJoinTableData::parallel_state, ParallelHashJoinBatchInner, ParallelHashJoinBatchOuter, ParallelWorkerNumber, HashJoinTableData::spillCxt, and sts_attach().

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

◆ ExecParallelHashFirstTuple()

static HashJoinTuple ExecParallelHashFirstTuple ( HashJoinTable  hashtable,
int  bucketno 
)
inlinestatic

Definition at line 3509 of file nodeHash.c.

3510{
3511 HashJoinTuple tuple;
3512 dsa_pointer p;
3513
3514 Assert(hashtable->parallel_state);
3516 tuple = (HashJoinTuple) dsa_get_address(hashtable->area, p);
3517
3518 return tuple;
3519}
#define dsa_pointer_atomic_read
Definition dsa.h:65
dsa_pointer_atomic * shared
Definition hashjoin.h:324

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

Referenced by ExecParallelScanHashBucket(), and ExecParallelScanHashTableForUnmatched().

◆ ExecParallelHashIncreaseNumBatches()

static void ExecParallelHashIncreaseNumBatches ( HashJoinTable  hashtable)
static

Definition at line 1223 of file nodeHash.c.

1224{
1225 ParallelHashJoinState *pstate = hashtable->parallel_state;
1226
1228
1229 /*
1230 * It's unlikely, but we need to be prepared for new participants to show
1231 * up while we're in the middle of this operation so we need to switch on
1232 * barrier phase here.
1233 */
1235 {
1237
1238 /*
1239 * Elect one participant to prepare to grow the number of batches.
1240 * This involves reallocating or resetting the buckets of batch 0
1241 * in preparation for all participants to begin repartitioning the
1242 * tuples.
1243 */
1246 {
1247 dsa_pointer_atomic *buckets;
1249 int new_nbatch;
1250 int i;
1251
1252 /* Move the old batch out of the way. */
1253 old_batch0 = hashtable->batches[0].shared;
1254 pstate->old_batches = pstate->batches;
1255 pstate->old_nbatch = hashtable->nbatch;
1256 pstate->batches = InvalidDsaPointer;
1257
1258 /* Free this backend's old accessors. */
1260
1261 /* Figure out how many batches to use. */
1262 if (hashtable->nbatch == 1)
1263 {
1264 /*
1265 * We are going from single-batch to multi-batch. We need
1266 * to switch from one large combined memory budget to the
1267 * regular hash_mem budget.
1268 */
1270
1271 /*
1272 * The combined hash_mem of all participants wasn't
1273 * enough. Therefore one batch per participant would be
1274 * approximately equivalent and would probably also be
1275 * insufficient. So try two batches per participant,
1276 * rounded up to a power of two.
1277 */
1279 }
1280 else
1281 {
1282 /*
1283 * We were already multi-batched. Try doubling the number
1284 * of batches.
1285 */
1286 new_nbatch = hashtable->nbatch * 2;
1287 }
1288
1289 /* Allocate new larger generation of batches. */
1290 Assert(hashtable->nbatch == pstate->nbatch);
1292 Assert(hashtable->nbatch == pstate->nbatch);
1293
1294 /* Replace or recycle batch 0's bucket array. */
1295 if (pstate->old_nbatch == 1)
1296 {
1297 double dtuples;
1298 double dbuckets;
1299 int new_nbuckets;
1300 uint32 max_buckets;
1301
1302 /*
1303 * We probably also need a smaller bucket array. How many
1304 * tuples do we expect per batch, assuming we have only
1305 * half of them so far? Normally we don't need to change
1306 * the bucket array's size, because the size of each batch
1307 * stays the same as we add more batches, but in this
1308 * special case we move from a large batch to many smaller
1309 * batches and it would be wasteful to keep the large
1310 * array.
1311 */
1312 dtuples = (old_batch0->ntuples * 2.0) / new_nbatch;
1313
1314 /*
1315 * We need to calculate the maximum number of buckets to
1316 * stay within the MaxAllocSize boundary. Round the
1317 * maximum number to the previous power of 2 given that
1318 * later we round the number to the next power of 2.
1319 */
1320 max_buckets = pg_prevpower2_32((uint32)
1321 (MaxAllocSize / sizeof(dsa_pointer_atomic)));
1323 dbuckets = Min(dbuckets, max_buckets);
1325 new_nbuckets = Max(new_nbuckets, 1024);
1327 dsa_free(hashtable->area, old_batch0->buckets);
1328 hashtable->batches[0].shared->buckets =
1329 dsa_allocate(hashtable->area,
1331 buckets = (dsa_pointer_atomic *)
1332 dsa_get_address(hashtable->area,
1333 hashtable->batches[0].shared->buckets);
1334 for (i = 0; i < new_nbuckets; ++i)
1336 pstate->nbuckets = new_nbuckets;
1337 }
1338 else
1339 {
1340 /* Recycle the existing bucket array. */
1341 hashtable->batches[0].shared->buckets = old_batch0->buckets;
1342 buckets = (dsa_pointer_atomic *)
1343 dsa_get_address(hashtable->area, old_batch0->buckets);
1344 for (i = 0; i < hashtable->nbuckets; ++i)
1346 }
1347
1348 /* Move all chunks to the work queue for parallel processing. */
1349 pstate->chunk_work_queue = old_batch0->chunks;
1350
1351 /* Disable further growth temporarily while we're growing. */
1352 pstate->growth = PHJ_GROWTH_DISABLED;
1353 }
1354 else
1355 {
1356 /* All other participants just flush their tuples to disk. */
1358 }
1360
1362 /* Wait for the above to be finished. */
1366
1368 /* Make sure that we have the current dimensions and buckets. */
1371 /* Then partition, flush counters. */
1375 /* Wait for the above to be finished. */
1379
1381
1382 /*
1383 * Elect one participant to clean up and decide whether further
1384 * repartitioning is needed, or should be disabled because it's
1385 * not helping.
1386 */
1389 {
1390 ParallelHashJoinBatch *old_batches;
1391 bool space_exhausted = false;
1392 bool extreme_skew_detected = false;
1393
1394 /* Make sure that we have the current dimensions and buckets. */
1397
1398 old_batches = dsa_get_address(hashtable->area, pstate->old_batches);
1399
1400 /* Are any of the new generation of batches exhausted? */
1401 for (int i = 0; i < hashtable->nbatch; ++i)
1402 {
1405 int parent;
1406
1407 batch = hashtable->batches[i].shared;
1408 if (batch->space_exhausted ||
1409 batch->estimated_size > pstate->space_allowed)
1410 space_exhausted = true;
1411
1412 parent = i % pstate->old_nbatch;
1413 old_batch = NthParallelHashJoinBatch(old_batches, parent);
1414 if (old_batch->space_exhausted ||
1415 batch->estimated_size > pstate->space_allowed)
1416 {
1417 /*
1418 * Did this batch receive ALL of the tuples from its
1419 * parent batch? That would indicate that further
1420 * repartitioning isn't going to help (the hash values
1421 * are probably all the same).
1422 */
1423 if (batch->ntuples == hashtable->batches[parent].shared->old_ntuples)
1424 extreme_skew_detected = true;
1425 }
1426 }
1427
1428 /* Don't keep growing if it's not helping or we'd overflow. */
1429 if (extreme_skew_detected || hashtable->nbatch >= INT_MAX / 2)
1430 pstate->growth = PHJ_GROWTH_DISABLED;
1431 else if (space_exhausted)
1433 else
1434 pstate->growth = PHJ_GROWTH_OK;
1435
1436 /* Free the old batches in shared memory. */
1437 dsa_free(hashtable->area, pstate->old_batches);
1439 }
1441
1443 /* Wait for the above to complete. */
1446 }
1447}
#define pg_fallthrough
Definition c.h:152
#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:298
#define PHJ_GROW_BATCHES_ELECT
Definition hashjoin.h:296
#define PHJ_BUILD_HASH_INNER
Definition hashjoin.h:282
#define PHJ_GROW_BATCHES_DECIDE
Definition hashjoin.h:299
#define PHJ_GROW_BATCHES_REALLOCATE
Definition hashjoin.h:297
#define PHJ_GROW_BATCHES_FINISH
Definition hashjoin.h:300
#define PHJ_GROW_BATCHES_PHASE(n)
Definition hashjoin.h:301
@ PHJ_GROWTH_NEED_MORE_BATCHES
Definition hashjoin.h:248
@ PHJ_GROWTH_DISABLED
Definition hashjoin.h:250
void ExecParallelHashTableSetCurrentBatch(HashJoinTable hashtable, int batchno)
Definition nodeHash.c:3557
static void ExecParallelHashEnsureBatchAccessors(HashJoinTable hashtable)
Definition nodeHash.c:3283
static void ExecParallelHashRepartitionRest(HashJoinTable hashtable)
Definition nodeHash.c:1522
static void ExecParallelHashMergeCounters(HashJoinTable hashtable)
Definition nodeHash.c:1582
static void ExecParallelHashRepartitionFirst(HashJoinTable hashtable)
Definition nodeHash.c:1455
static uint32 pg_prevpower2_32(uint32 num)
dsa_pointer buckets
Definition hashjoin.h:175
Barrier grow_batches_barrier
Definition hashjoin.h:272
dsa_pointer old_batches
Definition hashjoin.h:260
dsa_pointer chunk_work_queue
Definition hashjoin.h:265

References HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierPhase(), ParallelHashJoinState::batches, HashJoinTableData::batches, ParallelHashJoinBatch::buckets, ParallelHashJoinState::build_barrier, ParallelHashJoinState::chunk_work_queue, dsa_allocate, dsa_free(), dsa_get_address(), dsa_pointer_atomic_init, dsa_pointer_atomic_write, ExecParallelHashCloseBatchAccessors(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashJoinSetUpBatches(), ExecParallelHashMergeCounters(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecParallelHashTableSetCurrentBatch(), fb(), 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, NthParallelHashJoinBatch, NTUP_PER_BUCKET, ParallelHashJoinState::old_batches, ParallelHashJoinState::old_nbatch, ParallelHashJoinBatch::old_ntuples, HashJoinTableData::parallel_state, pg_fallthrough, 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, and ParallelHashJoinState::space_allowed.

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

◆ ExecParallelHashIncreaseNumBuckets()

static void ExecParallelHashIncreaseNumBuckets ( HashJoinTable  hashtable)
static

Definition at line 1675 of file nodeHash.c.

1676{
1677 ParallelHashJoinState *pstate = hashtable->parallel_state;
1678 int i;
1679 HashMemoryChunk chunk;
1681
1683
1684 /*
1685 * It's unlikely, but we need to be prepared for new participants to show
1686 * up while we're in the middle of this operation so we need to switch on
1687 * barrier phase here.
1688 */
1690 {
1692 /* Elect one participant to prepare to increase nbuckets. */
1695 {
1696 size_t size;
1697 dsa_pointer_atomic *buckets;
1698
1699 /* Double the size of the bucket array. */
1700 pstate->nbuckets *= 2;
1701 size = pstate->nbuckets * sizeof(dsa_pointer_atomic);
1702 hashtable->batches[0].shared->size += size / 2;
1703 dsa_free(hashtable->area, hashtable->batches[0].shared->buckets);
1704 hashtable->batches[0].shared->buckets =
1705 dsa_allocate(hashtable->area, size);
1706 buckets = (dsa_pointer_atomic *)
1707 dsa_get_address(hashtable->area,
1708 hashtable->batches[0].shared->buckets);
1709 for (i = 0; i < pstate->nbuckets; ++i)
1711
1712 /* Put the chunk list onto the work queue. */
1713 pstate->chunk_work_queue = hashtable->batches[0].shared->chunks;
1714
1715 /* Clear the flag. */
1716 pstate->growth = PHJ_GROWTH_OK;
1717 }
1719
1721 /* Wait for the above to complete. */
1725
1727 /* Reinsert all tuples into the hash table. */
1730 while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_s)))
1731 {
1732 size_t idx = 0;
1733
1734 while (idx < chunk->used)
1735 {
1738 int bucketno;
1739 int batchno;
1740
1741 ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1742 &bucketno, &batchno);
1743 Assert(batchno == 0);
1744
1745 /* add the tuple to the proper bucket */
1747 hashTuple, shared);
1748
1749 /* advance index past the tuple */
1751 HJTUPLE_MINTUPLE(hashTuple)->t_len);
1752 }
1753
1754 /* allow this loop to be cancellable */
1756 }
1759 }
1760}
pg_atomic_uint64 dsa_pointer_atomic
Definition dsa.h:63
#define PHJ_GROW_BUCKETS_REINSERT
Definition hashjoin.h:306
#define PHJ_GROW_BUCKETS_ELECT
Definition hashjoin.h:304
#define PHJ_GROW_BUCKETS_PHASE(n)
Definition hashjoin.h:307
#define PHJ_GROW_BUCKETS_REALLOCATE
Definition hashjoin.h:305
static void ExecParallelHashPushTuple(dsa_pointer_atomic *head, HashJoinTuple tuple, dsa_pointer tuple_shared)
Definition nodeHash.c:3539
static HashMemoryChunk ExecParallelHashPopChunkQueue(HashJoinTable hashtable, dsa_pointer *shared)
Definition nodeHash.c:3578
dsa_pointer chunks
Definition hashjoin.h:178
Barrier grow_buckets_barrier
Definition hashjoin.h:273

References HashJoinTableData::area, Assert, BarrierArriveAndWait(), BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinBatch::buckets, HashJoinTableData::buckets, ParallelHashJoinState::build_barrier, CHECK_FOR_INTERRUPTS, ParallelHashJoinState::chunk_work_queue, ParallelHashJoinBatch::chunks, dsa_allocate, dsa_free(), dsa_get_address(), dsa_pointer_atomic_init, ExecHashGetBucketAndBatch(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashPopChunkQueue(), ExecParallelHashPushTuple(), ExecParallelHashTableSetCurrentBatch(), fb(), ParallelHashJoinState::grow_buckets_barrier, ParallelHashJoinState::growth, HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HJTUPLE_MINTUPLE, HJTUPLE_OVERHEAD, i, idx(), InvalidDsaPointer, MAXALIGN, ParallelHashJoinState::nbuckets, HashJoinTableData::parallel_state, pg_fallthrough, 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, and ParallelHashJoinBatch::size.

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

◆ ExecParallelHashJoinSetUpBatches()

static void ExecParallelHashJoinSetUpBatches ( HashJoinTable  hashtable,
int  nbatch 
)
static

Definition at line 3182 of file nodeHash.c.

3183{
3184 ParallelHashJoinState *pstate = hashtable->parallel_state;
3185 ParallelHashJoinBatch *batches;
3187 int i;
3188
3189 Assert(hashtable->batches == NULL);
3190
3191 /* Allocate space. */
3192 pstate->batches =
3193 dsa_allocate0(hashtable->area,
3194 EstimateParallelHashJoinBatch(hashtable) * nbatch);
3195 pstate->nbatch = nbatch;
3196 batches = dsa_get_address(hashtable->area, pstate->batches);
3197
3198 /*
3199 * Use hash join spill memory context to allocate accessors, including
3200 * buffers for the temporary files.
3201 */
3203
3204 /* Allocate this backend's accessor array. */
3205 hashtable->nbatch = nbatch;
3206 hashtable->batches =
3208
3209 /* Set up the shared state, tuplestores and backend-local accessors. */
3210 for (i = 0; i < hashtable->nbatch; ++i)
3211 {
3214 char name[MAXPGPATH];
3215
3216 /*
3217 * All members of shared were zero-initialized. We just need to set
3218 * up the Barrier.
3219 */
3220 BarrierInit(&shared->batch_barrier, 0);
3221 if (i == 0)
3222 {
3223 /* Batch 0 doesn't need to be loaded. */
3224 BarrierAttach(&shared->batch_barrier);
3225 while (BarrierPhase(&shared->batch_barrier) < PHJ_BATCH_PROBE)
3227 BarrierDetach(&shared->batch_barrier);
3228 }
3229
3230 /* Initialize accessor state. All members were zero-initialized. */
3231 accessor->shared = shared;
3232
3233 /* Initialize the shared tuplestores. */
3234 snprintf(name, sizeof(name), "i%dof%d", i, hashtable->nbatch);
3235 accessor->inner_tuples =
3237 pstate->nparticipants,
3239 sizeof(uint32),
3241 &pstate->fileset,
3242 name);
3243 snprintf(name, sizeof(name), "o%dof%d", i, hashtable->nbatch);
3244 accessor->outer_tuples =
3246 pstate->nparticipants),
3247 pstate->nparticipants,
3249 sizeof(uint32),
3251 &pstate->fileset,
3252 name);
3253 }
3254
3256}
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:204
#define MAXPGPATH
#define snprintf
Definition port.h:260
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, fb(), ParallelHashJoinState::fileset, i, MAXPGPATH, MemoryContextSwitchTo(), name, ParallelHashJoinState::nbatch, HashJoinTableData::nbatch, ParallelHashJoinState::nparticipants, NthParallelHashJoinBatch, palloc0_array, HashJoinTableData::parallel_state, ParallelHashJoinBatchInner, ParallelHashJoinBatchOuter, ParallelWorkerNumber, PHJ_BATCH_PROBE, 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 1582 of file nodeHash.c.

1583{
1584 ParallelHashJoinState *pstate = hashtable->parallel_state;
1585 int i;
1586
1587 LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
1588 pstate->total_tuples = 0;
1589 for (i = 0; i < hashtable->nbatch; ++i)
1590 {
1592
1593 batch->shared->size += batch->size;
1594 batch->shared->estimated_size += batch->estimated_size;
1595 batch->shared->ntuples += batch->ntuples;
1596 batch->shared->old_ntuples += batch->old_ntuples;
1597 batch->size = 0;
1598 batch->estimated_size = 0;
1599 batch->ntuples = 0;
1600 batch->old_ntuples = 0;
1601 pstate->total_tuples += batch->shared->ntuples;
1602 }
1603 LWLockRelease(&pstate->lock);
1604}
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1177
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1794
@ LW_EXCLUSIVE
Definition lwlock.h:112

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

Referenced by ExecParallelHashIncreaseNumBatches(), and MultiExecParallelHash().

◆ ExecParallelHashNextTuple()

static HashJoinTuple ExecParallelHashNextTuple ( HashJoinTable  hashtable,
HashJoinTuple  tuple 
)
inlinestatic

◆ ExecParallelHashPopChunkQueue()

static HashMemoryChunk ExecParallelHashPopChunkQueue ( HashJoinTable  hashtable,
dsa_pointer shared 
)
static

Definition at line 3578 of file nodeHash.c.

3579{
3580 ParallelHashJoinState *pstate = hashtable->parallel_state;
3581 HashMemoryChunk chunk;
3582
3583 LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
3585 {
3586 *shared = pstate->chunk_work_queue;
3587 chunk = (HashMemoryChunk)
3588 dsa_get_address(hashtable->area, *shared);
3589 pstate->chunk_work_queue = chunk->next.shared;
3590 }
3591 else
3592 chunk = NULL;
3593 LWLockRelease(&pstate->lock);
3594
3595 return chunk;
3596}

References HashJoinTableData::area, ParallelHashJoinState::chunk_work_queue, dsa_get_address(), DsaPointerIsValid, fb(), ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), HashMemoryChunkData::next, HashJoinTableData::parallel_state, and HashMemoryChunkData::shared.

Referenced by ExecParallelHashIncreaseNumBuckets(), and ExecParallelHashRepartitionFirst().

◆ ExecParallelHashPushTuple()

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

◆ ExecParallelHashRepartitionFirst()

static void ExecParallelHashRepartitionFirst ( HashJoinTable  hashtable)
static

Definition at line 1455 of file nodeHash.c.

1456{
1458 HashMemoryChunk chunk;
1459
1460 Assert(hashtable->nbatch == hashtable->parallel_state->nbatch);
1461
1462 while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_shared)))
1463 {
1464 size_t idx = 0;
1465
1466 /* Repartition all tuples in this chunk. */
1467 while (idx < chunk->used)
1468 {
1472 dsa_pointer shared;
1473 int bucketno;
1474 int batchno;
1475
1476 ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
1477 &bucketno, &batchno);
1478
1480 if (batchno == 0)
1481 {
1482 /* It still belongs in batch 0. Copy to a new chunk. */
1483 copyTuple =
1485 HJTUPLE_OVERHEAD + tuple->t_len,
1486 &shared);
1487 copyTuple->hashvalue = hashTuple->hashvalue;
1488 memcpy(HJTUPLE_MINTUPLE(copyTuple), tuple, tuple->t_len);
1490 copyTuple, shared);
1491 }
1492 else
1493 {
1494 size_t tuple_size =
1496
1497 /* It belongs in a later batch. */
1500 &hashTuple->hashvalue, tuple);
1501 }
1502
1503 /* Count this tuple. */
1504 ++hashtable->batches[0].old_ntuples;
1505 ++hashtable->batches[batchno].ntuples;
1506
1508 HJTUPLE_MINTUPLE(hashTuple)->t_len);
1509 }
1510
1511 /* Free this chunk. */
1512 dsa_free(hashtable->area, chunk_shared);
1513
1515 }
1516}
static HashJoinTuple ExecParallelHashTupleAlloc(HashJoinTable hashtable, size_t size, dsa_pointer *shared)
Definition nodeHash.c:3034
void sts_puttuple(SharedTuplestoreAccessor *accessor, void *meta_data, MinimalTuple tuple)

References HashJoinTableData::area, Assert, HashJoinTableData::batches, HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, dsa_free(), ParallelHashJoinBatchAccessor::estimated_size, ExecHashGetBucketAndBatch(), ExecParallelHashPopChunkQueue(), ExecParallelHashPushTuple(), ExecParallelHashTupleAlloc(), fb(), HASH_CHUNK_DATA, 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 1522 of file nodeHash.c.

1523{
1524 ParallelHashJoinState *pstate = hashtable->parallel_state;
1525 int old_nbatch = pstate->old_nbatch;
1527 ParallelHashJoinBatch *old_batches;
1528 int i;
1529
1530 /* Get our hands on the previous generation of batches. */
1531 old_batches = (ParallelHashJoinBatch *)
1532 dsa_get_address(hashtable->area, pstate->old_batches);
1534 for (i = 1; i < old_nbatch; ++i)
1535 {
1536 ParallelHashJoinBatch *shared =
1537 NthParallelHashJoinBatch(old_batches, i);
1538
1541 &pstate->fileset);
1542 }
1543
1544 /* Join in the effort to repartition them. */
1545 for (i = 1; i < old_nbatch; ++i)
1546 {
1547 MinimalTuple tuple;
1548 uint32 hashvalue;
1549
1550 /* Scan one partition from the previous generation. */
1552 while ((tuple = sts_parallel_scan_next(old_inner_tuples[i], &hashvalue)))
1553 {
1554 size_t tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
1555 int bucketno;
1556 int batchno;
1557
1558 /* Decide which partition it goes to in the new generation. */
1559 ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno,
1560 &batchno);
1561
1563 ++hashtable->batches[batchno].ntuples;
1564 ++hashtable->batches[i].old_ntuples;
1565
1566 /* Store the tuple its new batch. */
1568 &hashvalue, tuple);
1569
1571 }
1573 }
1574
1576}
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(), fb(), 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 3347 of file nodeHash.c.

3348{
3350 dsa_pointer_atomic *buckets;
3351 int nbuckets = hashtable->parallel_state->nbuckets;
3352 int i;
3353
3354 batch->buckets =
3355 dsa_allocate(hashtable->area, sizeof(dsa_pointer_atomic) * nbuckets);
3356 buckets = (dsa_pointer_atomic *)
3357 dsa_get_address(hashtable->area, batch->buckets);
3358 for (i = 0; i < nbuckets; ++i)
3360}

References HashJoinTableData::area, HashJoinTableData::batches, dsa_allocate, dsa_get_address(), dsa_pointer_atomic_init, fb(), 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 1865 of file nodeHash.c.

1868{
1869 bool shouldFree;
1871 dsa_pointer shared;
1872 int bucketno;
1873 int batchno;
1874
1875retry:
1876 ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
1877
1878 if (batchno == 0)
1879 {
1881
1882 /* Try to load it into memory. */
1886 HJTUPLE_OVERHEAD + tuple->t_len,
1887 &shared);
1888 if (hashTuple == NULL)
1889 goto retry;
1890
1891 /* Store the hash value in the HashJoinTuple header. */
1892 hashTuple->hashvalue = hashvalue;
1893 memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
1895
1896 /* Push it onto the front of the bucket's list */
1898 hashTuple, shared);
1899 }
1900 else
1901 {
1902 size_t tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
1903
1904 Assert(batchno > 0);
1905
1906 /* Try to preallocate space in the batch if necessary. */
1907 if (hashtable->batches[batchno].preallocated < tuple_size)
1908 {
1910 goto retry;
1911 }
1912
1914 hashtable->batches[batchno].preallocated -= tuple_size;
1915 sts_puttuple(hashtable->batches[batchno].inner_tuples, &hashvalue,
1916 tuple);
1917 }
1918 ++hashtable->batches[batchno].ntuples;
1919
1920 if (shouldFree)
1922}
static bool ExecParallelHashTuplePrealloc(HashJoinTable hashtable, int batchno, size_t size)
Definition nodeHash.c:3619

References Assert, BarrierPhase(), HashJoinTableData::batches, HashJoinTableData::buckets, ParallelHashJoinState::build_barrier, ExecFetchSlotMinimalTuple(), ExecHashGetBucketAndBatch(), ExecParallelHashPushTuple(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), fb(), 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()

◆ ExecParallelHashTableSetCurrentBatch()

void ExecParallelHashTableSetCurrentBatch ( HashJoinTable  hashtable,
int  batchno 
)

Definition at line 3557 of file nodeHash.c.

3558{
3560
3561 hashtable->curbatch = batchno;
3562 hashtable->buckets.shared = (dsa_pointer_atomic *)
3563 dsa_get_address(hashtable->area,
3564 hashtable->batches[batchno].shared->buckets);
3565 hashtable->nbuckets = hashtable->parallel_state->nbuckets;
3566 hashtable->log2_nbuckets = pg_ceil_log2_32(hashtable->nbuckets);
3567 hashtable->current_chunk = NULL;
3569 hashtable->batches[batchno].at_least_one_chunk = false;
3570}
HashMemoryChunk current_chunk
Definition hashjoin.h:376
dsa_pointer current_chunk_shared
Definition hashjoin.h:380

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(), fb(), InvalidDsaPointer, HashJoinTableData::log2_nbuckets, ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, HashJoinTableData::parallel_state, pg_ceil_log2_32(), 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 3034 of file nodeHash.c.

3036{
3037 ParallelHashJoinState *pstate = hashtable->parallel_state;
3039 HashMemoryChunk chunk;
3040 Size chunk_size;
3041 HashJoinTuple result;
3042 int curbatch = hashtable->curbatch;
3043
3044 size = MAXALIGN(size);
3045
3046 /*
3047 * Fast path: if there is enough space in this backend's current chunk,
3048 * then we can allocate without any locking.
3049 */
3050 chunk = hashtable->current_chunk;
3051 if (chunk != NULL &&
3052 size <= HASH_CHUNK_THRESHOLD &&
3053 chunk->maxlen - chunk->used >= size)
3054 {
3055
3057 Assert(chunk == dsa_get_address(hashtable->area, chunk_shared));
3058 *shared = chunk_shared + HASH_CHUNK_HEADER_SIZE + chunk->used;
3059 result = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + chunk->used);
3060 chunk->used += size;
3061
3062 Assert(chunk->used <= chunk->maxlen);
3063 Assert(result == dsa_get_address(hashtable->area, *shared));
3064
3065 return result;
3066 }
3067
3068 /* Slow path: try to allocate a new chunk. */
3069 LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
3070
3071 /*
3072 * Check if we need to help increase the number of buckets or batches.
3073 */
3074 if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
3076 {
3077 ParallelHashGrowth growth = pstate->growth;
3078
3079 hashtable->current_chunk = NULL;
3080 LWLockRelease(&pstate->lock);
3081
3082 /* Another participant has commanded us to help grow. */
3083 if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
3085 else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
3087
3088 /* The caller must retry. */
3089 return NULL;
3090 }
3091
3092 /* Oversized tuples get their own chunk. */
3093 if (size > HASH_CHUNK_THRESHOLD)
3094 chunk_size = size + HASH_CHUNK_HEADER_SIZE;
3095 else
3096 chunk_size = HASH_CHUNK_SIZE;
3097
3098 /* Check if it's time to grow batches or buckets. */
3099 if (pstate->growth != PHJ_GROWTH_DISABLED)
3100 {
3101 Assert(curbatch == 0);
3103
3104 /*
3105 * Check if our space limit would be exceeded. To avoid choking on
3106 * very large tuples or very low hash_mem setting, we'll always allow
3107 * each backend to allocate at least one chunk.
3108 */
3109 if (hashtable->batches[0].at_least_one_chunk &&
3110 hashtable->batches[0].shared->size +
3111 chunk_size > pstate->space_allowed)
3112 {
3114 hashtable->batches[0].shared->space_exhausted = true;
3115 LWLockRelease(&pstate->lock);
3116
3117 return NULL;
3118 }
3119
3120 /* Check if our load factor limit would be exceeded. */
3121 if (hashtable->nbatch == 1)
3122 {
3123 hashtable->batches[0].shared->ntuples += hashtable->batches[0].ntuples;
3124 hashtable->batches[0].ntuples = 0;
3125 /* Guard against integer overflow and alloc size overflow */
3126 if (hashtable->batches[0].shared->ntuples + 1 >
3127 hashtable->nbuckets * NTUP_PER_BUCKET &&
3128 hashtable->nbuckets < (INT_MAX / 2) &&
3129 hashtable->nbuckets * 2 <=
3131 {
3133 LWLockRelease(&pstate->lock);
3134
3135 return NULL;
3136 }
3137 }
3138 }
3139
3140 /* We are cleared to allocate a new chunk. */
3141 chunk_shared = dsa_allocate(hashtable->area, chunk_size);
3142 hashtable->batches[curbatch].shared->size += chunk_size;
3143 hashtable->batches[curbatch].at_least_one_chunk = true;
3144
3145 /* Set up the chunk. */
3146 chunk = (HashMemoryChunk) dsa_get_address(hashtable->area, chunk_shared);
3148 chunk->maxlen = chunk_size - HASH_CHUNK_HEADER_SIZE;
3149 chunk->used = size;
3150
3151 /*
3152 * Push it onto the list of chunks, so that it can be found if we need to
3153 * increase the number of buckets or batches (batch 0 only) and later for
3154 * freeing the memory (all batches).
3155 */
3156 chunk->next.shared = hashtable->batches[curbatch].shared->chunks;
3157 hashtable->batches[curbatch].shared->chunks = chunk_shared;
3158
3159 if (size <= HASH_CHUNK_THRESHOLD)
3160 {
3161 /*
3162 * Make this the current chunk so that we can use the fast path to
3163 * fill the rest of it up in future calls.
3164 */
3165 hashtable->current_chunk = chunk;
3167 }
3168 LWLockRelease(&pstate->lock);
3169
3170 Assert(HASH_CHUNK_DATA(chunk) == dsa_get_address(hashtable->area, *shared));
3171 result = (HashJoinTuple) HASH_CHUNK_DATA(chunk);
3172
3173 return result;
3174}
ParallelHashGrowth
Definition hashjoin.h:242
@ PHJ_GROWTH_NEED_MORE_BUCKETS
Definition hashjoin.h:246
static void ExecParallelHashIncreaseNumBuckets(HashJoinTable hashtable)
Definition nodeHash.c:1675
static void ExecParallelHashIncreaseNumBatches(HashJoinTable hashtable)
Definition nodeHash.c:1223

References HashJoinTableData::area, Assert, ParallelHashJoinBatchAccessor::at_least_one_chunk, BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinState::build_barrier, ParallelHashJoinBatch::chunks, HashJoinTableData::curbatch, HashJoinTableData::current_chunk, HashJoinTableData::current_chunk_shared, dsa_allocate, dsa_get_address(), ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), fb(), ParallelHashJoinState::growth, HASH_CHUNK_DATA, HASH_CHUNK_HEADER_SIZE, HASH_CHUNK_SIZE, HASH_CHUNK_THRESHOLD, ParallelHashJoinState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, MaxAllocSize, HashMemoryChunkData::maxlen, HashJoinTableData::nbatch, HashJoinTableData::nbuckets, HashMemoryChunkData::next, 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, HashMemoryChunkData::shared, ParallelHashJoinBatchAccessor::shared, ParallelHashJoinBatch::size, ParallelHashJoinState::space_allowed, ParallelHashJoinBatch::space_exhausted, and HashMemoryChunkData::used.

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

◆ ExecParallelHashTuplePrealloc()

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

Definition at line 3619 of file nodeHash.c.

3620{
3621 ParallelHashJoinState *pstate = hashtable->parallel_state;
3624
3625 Assert(batchno > 0);
3627 Assert(size == MAXALIGN(size));
3628
3629 LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
3630
3631 /* Has another participant commanded us to help grow? */
3632 if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
3634 {
3635 ParallelHashGrowth growth = pstate->growth;
3636
3637 LWLockRelease(&pstate->lock);
3638 if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
3640 else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
3642
3643 return false;
3644 }
3645
3646 if (pstate->growth != PHJ_GROWTH_DISABLED &&
3647 batch->at_least_one_chunk &&
3648 (batch->shared->estimated_size + want + HASH_CHUNK_HEADER_SIZE
3649 > pstate->space_allowed))
3650 {
3651 /*
3652 * We have determined that this batch would exceed the space budget if
3653 * loaded into memory. Command all participants to help repartition.
3654 */
3655 batch->shared->space_exhausted = true;
3657 LWLockRelease(&pstate->lock);
3658
3659 return false;
3660 }
3661
3662 batch->at_least_one_chunk = true;
3663 batch->shared->estimated_size += want + HASH_CHUNK_HEADER_SIZE;
3664 batch->preallocated = want;
3665 LWLockRelease(&pstate->lock);
3666
3667 return true;
3668}

References Assert, HashJoinTableData::batches, ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), fb(), 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, and ParallelHashJoinState::space_allowed.

Referenced by ExecParallelHashTableInsert().

◆ ExecParallelPrepHashTableForUnmatched()

bool ExecParallelPrepHashTableForUnmatched ( HashJoinState hjstate)

Definition at line 2151 of file nodeHash.c.

2152{
2153 HashJoinTable hashtable = hjstate->hj_HashTable;
2154 int curbatch = hashtable->curbatch;
2155 ParallelHashJoinBatch *batch = hashtable->batches[curbatch].shared;
2156
2157 Assert(BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_PROBE);
2158
2159 /*
2160 * It would not be deadlock-free to wait on the batch barrier, because it
2161 * is in PHJ_BATCH_PROBE phase, and thus processes attached to it have
2162 * already emitted tuples. Therefore, we'll hold a wait-free election:
2163 * only one process can continue to the next phase, and all others detach
2164 * from this batch. They can still go any work on other batches, if there
2165 * are any.
2166 */
2167 if (!BarrierArriveAndDetachExceptLast(&batch->batch_barrier))
2168 {
2169 /* This process considers the batch to be done. */
2170 hashtable->batches[hashtable->curbatch].done = true;
2171
2172 /* Make sure any temporary files are closed. */
2173 sts_end_parallel_scan(hashtable->batches[curbatch].inner_tuples);
2174 sts_end_parallel_scan(hashtable->batches[curbatch].outer_tuples);
2175
2176 /*
2177 * Track largest batch we've seen, which would normally happen in
2178 * ExecHashTableDetachBatch().
2179 */
2180 hashtable->spacePeak =
2181 Max(hashtable->spacePeak,
2182 batch->size + sizeof(dsa_pointer_atomic) * hashtable->nbuckets);
2183 hashtable->curbatch = -1;
2184 return false;
2185 }
2186
2187 /* Now we are alone with this batch. */
2188 Assert(BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_SCAN);
2189
2190 /*
2191 * Has another process decided to give up early and command all processes
2192 * to skip the unmatched scan?
2193 */
2194 if (batch->skip_unmatched)
2195 {
2196 hashtable->batches[hashtable->curbatch].done = true;
2197 ExecHashTableDetachBatch(hashtable);
2198 return false;
2199 }
2200
2201 /* Now prepare the process local state, just as for non-parallel join. */
2203
2204 return true;
2205}
void ExecHashTableDetachBatch(HashJoinTable hashtable)
Definition nodeHash.c:3367
void ExecPrepHashTableForUnmatched(HashJoinState *hjstate)
Definition nodeHash.c:2130

References Assert, BarrierArriveAndDetachExceptLast(), BarrierPhase(), HashJoinTableData::batches, HashJoinTableData::curbatch, ParallelHashJoinBatchAccessor::done, ExecHashTableDetachBatch(), ExecPrepHashTableForUnmatched(), fb(), ParallelHashJoinBatchAccessor::inner_tuples, Max, HashJoinTableData::nbuckets, ParallelHashJoinBatchAccessor::outer_tuples, PHJ_BATCH_PROBE, PHJ_BATCH_SCAN, ParallelHashJoinBatchAccessor::shared, HashJoinTableData::spacePeak, and sts_end_parallel_scan().

Referenced by ExecHashJoinImpl().

◆ ExecParallelScanHashBucket()

bool ExecParallelScanHashBucket ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 2079 of file nodeHash.c.

2081{
2082 ExprState *hjclauses = hjstate->hashclauses;
2083 HashJoinTable hashtable = hjstate->hj_HashTable;
2084 HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2085 uint32 hashvalue = hjstate->hj_CurHashValue;
2086
2087 /*
2088 * hj_CurTuple is the address of the tuple last returned from the current
2089 * bucket, or NULL if it's time to start scanning a new bucket.
2090 */
2091 if (hashTuple != NULL)
2093 else
2095 hjstate->hj_CurBucketNo);
2096
2097 while (hashTuple != NULL)
2098 {
2099 if (hashTuple->hashvalue == hashvalue)
2100 {
2102
2103 /* insert hashtable's tuple into exec slot so ExecQual sees it */
2105 hjstate->hj_HashTupleSlot,
2106 false); /* do not pfree */
2107 econtext->ecxt_innertuple = inntuple;
2108
2109 if (ExecQualAndReset(hjclauses, econtext))
2110 {
2111 hjstate->hj_CurTuple = hashTuple;
2112 return true;
2113 }
2114 }
2115
2117 }
2118
2119 /*
2120 * no match
2121 */
2122 return false;
2123}
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
static bool ExecQualAndReset(ExprState *state, ExprContext *econtext)
Definition executor.h:549
static HashJoinTuple ExecParallelHashFirstTuple(HashJoinTable hashtable, int bucketno)
Definition nodeHash.c:3509
static HashJoinTuple ExecParallelHashNextTuple(HashJoinTable hashtable, HashJoinTuple tuple)
Definition nodeHash.c:3525
TupleTableSlot * ecxt_innertuple
Definition execnodes.h:286

References ExprContext::ecxt_innertuple, ExecParallelHashFirstTuple(), ExecParallelHashNextTuple(), ExecQualAndReset(), ExecStoreMinimalTuple(), fb(), and HJTUPLE_MINTUPLE.

Referenced by ExecHashJoinImpl().

◆ ExecParallelScanHashTableForUnmatched()

bool ExecParallelScanHashTableForUnmatched ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 2290 of file nodeHash.c.

2292{
2293 HashJoinTable hashtable = hjstate->hj_HashTable;
2294 HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2295
2296 for (;;)
2297 {
2298 /*
2299 * hj_CurTuple is the address of the tuple last returned from the
2300 * current bucket, or NULL if it's time to start scanning a new
2301 * bucket.
2302 */
2303 if (hashTuple != NULL)
2305 else if (hjstate->hj_CurBucketNo < hashtable->nbuckets)
2307 hjstate->hj_CurBucketNo++);
2308 else
2309 break; /* finished all buckets */
2310
2311 while (hashTuple != NULL)
2312 {
2314 {
2316
2317 /* insert hashtable's tuple into exec slot */
2319 hjstate->hj_HashTupleSlot,
2320 false); /* do not pfree */
2321 econtext->ecxt_innertuple = inntuple;
2322
2323 /*
2324 * Reset temp memory each time; although this function doesn't
2325 * do any qual eval, the caller will, so let's keep it
2326 * parallel to ExecScanHashBucket.
2327 */
2328 ResetExprContext(econtext);
2329
2330 hjstate->hj_CurTuple = hashTuple;
2331 return true;
2332 }
2333
2335 }
2336
2337 /* allow this loop to be cancellable */
2339 }
2340
2341 /*
2342 * no more unmatched tuples
2343 */
2344 return false;
2345}
#define ResetExprContext(econtext)
Definition executor.h:654
static bool HeapTupleHeaderHasMatch(const MinimalTupleData *tup)

References CHECK_FOR_INTERRUPTS, ExprContext::ecxt_innertuple, ExecParallelHashFirstTuple(), ExecParallelHashNextTuple(), ExecStoreMinimalTuple(), fb(), HeapTupleHeaderHasMatch(), HJTUPLE_MINTUPLE, HashJoinTableData::nbuckets, and ResetExprContext.

Referenced by ExecHashJoinImpl().

◆ ExecPrepHashTableForUnmatched()

void ExecPrepHashTableForUnmatched ( HashJoinState hjstate)

Definition at line 2130 of file nodeHash.c.

2131{
2132 /*----------
2133 * During this scan we use the HashJoinState fields as follows:
2134 *
2135 * hj_CurBucketNo: next regular bucket to scan
2136 * hj_CurSkewBucketNo: next skew bucket (an index into skewBucketNums)
2137 * hj_CurTuple: last tuple returned, or NULL to start next bucket
2138 *----------
2139 */
2140 hjstate->hj_CurBucketNo = 0;
2141 hjstate->hj_CurSkewBucketNo = 0;
2142 hjstate->hj_CurTuple = NULL;
2143}

References fb().

Referenced by ExecHashJoinImpl(), and ExecParallelPrepHashTableForUnmatched().

◆ ExecReScanHash()

void ExecReScanHash ( HashState node)

Definition at line 2407 of file nodeHash.c.

2408{
2410
2411 /*
2412 * if chgParam of subnode is not null then plan will be re-scanned by
2413 * first ExecProcNode.
2414 */
2415 if (outerPlan->chgParam == NULL)
2417}
void ExecReScan(PlanState *node)
Definition execAmi.c:78

References ExecReScan(), fb(), outerPlan, and outerPlanState.

Referenced by ExecReScan().

◆ ExecScanHashBucket()

bool ExecScanHashBucket ( HashJoinState hjstate,
ExprContext econtext 
)

Definition at line 2018 of file nodeHash.c.

2020{
2021 ExprState *hjclauses = hjstate->hashclauses;
2022 HashJoinTable hashtable = hjstate->hj_HashTable;
2023 HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2024 uint32 hashvalue = hjstate->hj_CurHashValue;
2025
2026 /*
2027 * hj_CurTuple is the address of the tuple last returned from the current
2028 * bucket, or NULL if it's time to start scanning a new bucket.
2029 *
2030 * If the tuple hashed to a skew bucket then scan the skew bucket
2031 * otherwise scan the standard hashtable bucket.
2032 */
2033 if (hashTuple != NULL)
2035 else if (hjstate->hj_CurSkewBucketNo != INVALID_SKEW_BUCKET_NO)
2036 hashTuple = hashtable->skewBucket[hjstate->hj_CurSkewBucketNo]->tuples;
2037 else
2038 hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
2039
2040 while (hashTuple != NULL)
2041 {
2042 if (hashTuple->hashvalue == hashvalue)
2043 {
2045
2046 /* insert hashtable's tuple into exec slot so ExecQual sees it */
2048 hjstate->hj_HashTupleSlot,
2049 false); /* do not pfree */
2050 econtext->ecxt_innertuple = inntuple;
2051
2052 if (ExecQualAndReset(hjclauses, econtext))
2053 {
2054 hjstate->hj_CurTuple = hashTuple;
2055 return true;
2056 }
2057 }
2058
2059 hashTuple = hashTuple->next.unshared;
2060 }
2061
2062 /*
2063 * no match
2064 */
2065 return false;
2066}

References HashJoinTableData::buckets, ExprContext::ecxt_innertuple, ExecQualAndReset(), ExecStoreMinimalTuple(), fb(), 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 2216 of file nodeHash.c.

2217{
2218 HashJoinTable hashtable = hjstate->hj_HashTable;
2219 HashJoinTuple hashTuple = hjstate->hj_CurTuple;
2220
2221 for (;;)
2222 {
2223 /*
2224 * hj_CurTuple is the address of the tuple last returned from the
2225 * current bucket, or NULL if it's time to start scanning a new
2226 * bucket.
2227 */
2228 if (hashTuple != NULL)
2230 else if (hjstate->hj_CurBucketNo < hashtable->nbuckets)
2231 {
2232 hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
2233 hjstate->hj_CurBucketNo++;
2234 }
2235 else if (hjstate->hj_CurSkewBucketNo < hashtable->nSkewBuckets)
2236 {
2237 int j = hashtable->skewBucketNums[hjstate->hj_CurSkewBucketNo];
2238
2239 hashTuple = hashtable->skewBucket[j]->tuples;
2240 hjstate->hj_CurSkewBucketNo++;
2241 }
2242 else
2243 break; /* finished all buckets */
2244
2245 while (hashTuple != NULL)
2246 {
2248 {
2250
2251 /* insert hashtable's tuple into exec slot */
2253 hjstate->hj_HashTupleSlot,
2254 false); /* do not pfree */
2255 econtext->ecxt_innertuple = inntuple;
2256
2257 /*
2258 * Reset temp memory each time; although this function doesn't
2259 * do any qual eval, the caller will, so let's keep it
2260 * parallel to ExecScanHashBucket.
2261 */
2262 ResetExprContext(econtext);
2263
2264 hjstate->hj_CurTuple = hashTuple;
2265 return true;
2266 }
2267
2268 hashTuple = hashTuple->next.unshared;
2269 }
2270
2271 /* allow this loop to be cancellable */
2273 }
2274
2275 /*
2276 * no more unmatched tuples
2277 */
2278 return false;
2279}

References HashJoinTableData::buckets, CHECK_FOR_INTERRUPTS, ExprContext::ecxt_innertuple, ExecStoreMinimalTuple(), fb(), HeapTupleHeaderHasMatch(), 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 2889 of file nodeHash.c.

2890{
2891 /* Allocate save space if EXPLAIN'ing and we didn't do so already */
2892 if (node->ps.instrument && !node->hinstrument)
2894 /* Now accumulate data for the current (final) hash table */
2895 if (node->hinstrument && node->hashtable)
2897}
#define palloc0_object(type)
Definition fe_memutils.h:75
void ExecHashAccumInstrumentation(HashInstrumentation *instrument, HashJoinTable hashtable)
Definition nodeHash.c:2935
HashJoinTable hashtable
Definition execnodes.h:2666

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 3680 of file nodeHash.c.

3681{
3682 double mem_limit;
3683
3684 /* Do initial calculation in double arithmetic */
3685 mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3686
3687 /* Clamp in case it doesn't fit in size_t */
3688 mem_limit = Min(mem_limit, (double) SIZE_MAX);
3689
3690 return (size_t) mem_limit;
3691}
double hash_mem_multiplier
Definition globals.c:132

References fb(), hash_mem_multiplier, Min, and work_mem.

Referenced by consider_groupingsets_paths(), cost_memoize_rescan(), create_setop_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)
114 else
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:88
static void MultiExecParallelHash(HashState *node)
Definition nodeHash.c:234
static void MultiExecPrivateHash(HashState *node)
Definition nodeHash.c:139
double reportTuples
Definition hashjoin.h:349
struct ParallelHashJoinState * parallel_state
Definition execnodes.h:2691

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

Referenced by MultiExecProcNode().

◆ MultiExecParallelHash()

static void MultiExecParallelHash ( HashState node)
static

Definition at line 234 of file nodeHash.c.

235{
236 ParallelHashJoinState *pstate;
238 HashJoinTable hashtable;
239 TupleTableSlot *slot;
240 ExprContext *econtext;
241 Barrier *build_barrier;
242 int i;
243
244 /*
245 * get state info from node
246 */
248 hashtable = node->hashtable;
249
250 /*
251 * set expression context
252 */
253 econtext = node->ps.ps_ExprContext;
254
255 /*
256 * Synchronize the parallel hash table build. At this stage we know that
257 * the shared hash table has been or is being set up by
258 * ExecHashTableCreate(), but we don't know if our peers have returned
259 * from there or are here in MultiExecParallelHash(), and if so how far
260 * through they are. To find out, we check the build_barrier phase then
261 * and jump to the right step in the build algorithm.
262 */
263 pstate = hashtable->parallel_state;
264 build_barrier = &pstate->build_barrier;
265 Assert(BarrierPhase(build_barrier) >= PHJ_BUILD_ALLOCATE);
266 switch (BarrierPhase(build_barrier))
267 {
269
270 /*
271 * Either I just allocated the initial hash table in
272 * ExecHashTableCreate(), or someone else is doing that. Either
273 * way, wait for everyone to arrive here so we can proceed.
274 */
277
279
280 /*
281 * It's time to begin hashing, or if we just arrived here then
282 * hashing is already underway, so join in that effort. While
283 * hashing we have to be prepared to help increase the number of
284 * batches or buckets at any time, and if we arrived here when
285 * that was already underway we'll have to help complete that work
286 * immediately so that it's safe to access batches and buckets
287 * below.
288 */
297 for (;;)
298 {
299 bool isnull;
300 uint32 hashvalue;
301
302 slot = ExecProcNode(outerNode);
303 if (TupIsNull(slot))
304 break;
305 econtext->ecxt_outertuple = slot;
306
307 ResetExprContext(econtext);
308
310 econtext,
311 &isnull));
312
313 if (!isnull)
314 {
315 /* normal case with a non-null join key */
316 ExecParallelHashTableInsert(hashtable, slot, hashvalue);
317 hashtable->reportTuples++;
318 }
319 else if (node->keep_null_tuples)
320 {
321 /* null join key, but save tuple to be emitted later */
322 if (node->null_tuple_store == NULL)
325 hashtable->reportTuples++;
326 }
327 /* else we can discard the tuple immediately */
328 }
329
330 /*
331 * Make sure that any tuples we wrote to disk are visible to
332 * others before anyone tries to load them.
333 */
334 for (i = 0; i < hashtable->nbatch; ++i)
335 sts_end_write(hashtable->batches[i].inner_tuples);
336
337 /*
338 * Update shared counters. We need an accurate total tuple count
339 * to control the empty table optimization.
340 */
342
345
346 /*
347 * Wait for everyone to finish building and flushing files and
348 * counters.
349 */
350 if (BarrierArriveAndWait(build_barrier,
352 {
353 /*
354 * Elect one backend to disable any further growth. Batches
355 * are now fixed. While building them we made sure they'd fit
356 * in our memory budget when we load them back in later (or we
357 * tried to do that and gave up because we detected extreme
358 * skew).
359 */
360 pstate->growth = PHJ_GROWTH_DISABLED;
361 }
362 }
363
364 /*
365 * We're not yet attached to a batch. We all agree on the dimensions and
366 * number of inner tuples. (In parallel mode, totalTuples isn't used in
367 * this module, but we must report it for nodeHashjoin.c's empty-table
368 * optimization.)
369 */
370 hashtable->curbatch = -1;
371 hashtable->nbuckets = pstate->nbuckets;
372 hashtable->log2_nbuckets = pg_ceil_log2_32(hashtable->nbuckets);
373 hashtable->totalTuples = pstate->total_tuples;
374
375 /*
376 * Unless we're completely done and the batch state has been freed, make
377 * sure we have accessors.
378 */
379 if (BarrierPhase(build_barrier) < PHJ_BUILD_FREE)
381
382 /*
383 * The next synchronization point is in ExecHashJoin's HJ_BUILD_HASHTABLE
384 * case, which will bring the build phase to PHJ_BUILD_RUN (if it isn't
385 * there already).
386 */
387 Assert(BarrierPhase(build_barrier) == PHJ_BUILD_HASH_OUTER ||
388 BarrierPhase(build_barrier) == PHJ_BUILD_RUN ||
389 BarrierPhase(build_barrier) == PHJ_BUILD_FREE);
390}
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition executor.h:315
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:439
#define PHJ_BUILD_HASH_OUTER
Definition hashjoin.h:283
#define PHJ_BUILD_ALLOCATE
Definition hashjoin.h:281
void ExecParallelHashTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
Definition nodeHash.c:1865
Tuplestorestate * ExecHashBuildNullTupleStore(HashJoinTable hashtable)
Definition nodeHash.c:2799
TupleTableSlot * ecxt_outertuple
Definition execnodes.h:288
bool keep_null_tuples
Definition execnodes.h:2673
Tuplestorestate * null_tuple_store
Definition execnodes.h:2672
ExprState * hash_expr
Definition execnodes.h:2667
ExprContext * ps_ExprContext
Definition execnodes.h:1216
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition tuplestore.c:743
#define TupIsNull(slot)
Definition tuptable.h:325

References Assert, BarrierArriveAndWait(), BarrierAttach(), BarrierDetach(), BarrierPhase(), HashJoinTableData::batches, ParallelHashJoinState::build_barrier, HashJoinTableData::curbatch, DatumGetUInt32(), ExprContext::ecxt_outertuple, ExecEvalExprSwitchContext(), ExecHashBuildNullTupleStore(), ExecParallelHashEnsureBatchAccessors(), ExecParallelHashIncreaseNumBatches(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashMergeCounters(), ExecParallelHashTableInsert(), ExecParallelHashTableSetCurrentBatch(), ExecProcNode(), fb(), ParallelHashJoinState::grow_batches_barrier, ParallelHashJoinState::grow_buckets_barrier, ParallelHashJoinState::growth, HashState::hash_expr, HashState::hashtable, i, ParallelHashJoinBatchAccessor::inner_tuples, HashState::keep_null_tuples, HashJoinTableData::log2_nbuckets, HashJoinTableData::nbatch, ParallelHashJoinState::nbuckets, HashJoinTableData::nbuckets, HashState::null_tuple_store, outerPlanState, HashJoinTableData::parallel_state, pg_ceil_log2_32(), pg_fallthrough, 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, HashJoinTableData::reportTuples, ResetExprContext, sts_end_write(), ParallelHashJoinState::total_tuples, HashJoinTableData::totalTuples, TupIsNull, and tuplestore_puttupleslot().

Referenced by MultiExecHash().

◆ MultiExecPrivateHash()

static void MultiExecPrivateHash ( HashState node)
static

Definition at line 139 of file nodeHash.c.

140{
142 HashJoinTable hashtable;
143 TupleTableSlot *slot;
144 ExprContext *econtext;
145 double nullTuples = 0;
146
147 /*
148 * get state info from node
149 */
151 hashtable = node->hashtable;
152
153 /*
154 * set expression context
155 */
156 econtext = node->ps.ps_ExprContext;
157
158 /*
159 * Get all tuples from the node below the Hash node and insert the
160 * potentially-matchable ones into the hash table (or temp files). Tuples
161 * that can't possibly match because they have null join keys are dumped
162 * into a separate tuplestore, or just summarily discarded if we don't
163 * need to emit them with null-extension.
164 */
165 for (;;)
166 {
167 bool isnull;
168 Datum hashdatum;
169
170 slot = ExecProcNode(outerNode);
171 if (TupIsNull(slot))
172 break;
173 /* We have to compute the hash value */
174 econtext->ecxt_outertuple = slot;
175
176 ResetExprContext(econtext);
177
178 hashdatum = ExecEvalExprSwitchContext(node->hash_expr, econtext,
179 &isnull);
180
181 if (!isnull)
182 {
183 /* normal case with a non-null join key */
184 uint32 hashvalue = DatumGetUInt32(hashdatum);
185 int bucketNumber;
186
187 bucketNumber = ExecHashGetSkewBucket(hashtable, hashvalue);
189 {
190 /* It's a skew tuple, so put it into that hash table */
191 ExecHashSkewTableInsert(hashtable, slot, hashvalue,
193 }
194 else
195 {
196 /* Not subject to skew optimization, so insert normally */
197 ExecHashTableInsert(hashtable, slot, hashvalue);
198 }
199 hashtable->totalTuples += 1;
200 }
201 else if (node->keep_null_tuples)
202 {
203 /* null join key, but we must save tuple to be emitted later */
204 if (node->null_tuple_store == NULL)
207 nullTuples += 1;
208 }
209 /* else we can discard the tuple immediately */
210 }
211
212 /* resize the hash table if needed (NTUP_PER_BUCKET exceeded) */
213 if (hashtable->nbuckets != hashtable->nbuckets_optimal)
215
216 /* Account for the buckets in spaceUsed (reported in EXPLAIN ANALYZE) */
217 hashtable->spaceUsed += hashtable->nbuckets * sizeof(HashJoinTuple);
218 if (hashtable->spaceUsed > hashtable->spacePeak)
219 hashtable->spacePeak = hashtable->spaceUsed;
220
221 /* Report total number of tuples output (but not those discarded) */
222 hashtable->reportTuples = hashtable->totalTuples + nullTuples;
223}
static void ExecHashIncreaseNumBuckets(HashJoinTable hashtable)
Definition nodeHash.c:1612
int ExecHashGetSkewBucket(HashJoinTable hashtable, uint32 hashvalue)
Definition nodeHash.c:2581
static void ExecHashSkewTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue, int bucketNumber)
Definition nodeHash.c:2627
void ExecHashTableInsert(HashJoinTable hashtable, TupleTableSlot *slot, uint32 hashvalue)
Definition nodeHash.c:1774
uint64_t Datum
Definition postgres.h:70

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

Referenced by MultiExecHash().