LCOV - code coverage report
Current view: top level - src/backend/executor - nodeHash.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1034 1084 95.4 %
Date: 2019-11-22 08:06:54 Functions: 51 52 98.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * nodeHash.c
       4             :  *    Routines to hash relations for hashjoin
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/executor/nodeHash.c
      12             :  *
      13             :  * See note on parallelism in nodeHashjoin.c.
      14             :  *
      15             :  *-------------------------------------------------------------------------
      16             :  */
      17             : /*
      18             :  * INTERFACE ROUTINES
      19             :  *      MultiExecHash   - generate an in-memory hash table of the relation
      20             :  *      ExecInitHash    - initialize node and subnodes
      21             :  *      ExecEndHash     - shutdown node and subnodes
      22             :  */
      23             : 
      24             : #include "postgres.h"
      25             : 
      26             : #include <math.h>
      27             : #include <limits.h>
      28             : 
      29             : #include "access/htup_details.h"
      30             : #include "access/parallel.h"
      31             : #include "catalog/pg_statistic.h"
      32             : #include "commands/tablespace.h"
      33             : #include "executor/execdebug.h"
      34             : #include "executor/hashjoin.h"
      35             : #include "executor/nodeHash.h"
      36             : #include "executor/nodeHashjoin.h"
      37             : #include "miscadmin.h"
      38             : #include "pgstat.h"
      39             : #include "port/atomics.h"
      40             : #include "utils/dynahash.h"
      41             : #include "utils/lsyscache.h"
      42             : #include "utils/memutils.h"
      43             : #include "utils/syscache.h"
      44             : 
      45             : static void ExecHashIncreaseNumBatches(HashJoinTable hashtable);
      46             : static void ExecHashIncreaseNumBuckets(HashJoinTable hashtable);
      47             : static void ExecParallelHashIncreaseNumBatches(HashJoinTable hashtable);
      48             : static void ExecParallelHashIncreaseNumBuckets(HashJoinTable hashtable);
      49             : static void ExecHashBuildSkewHash(HashJoinTable hashtable, Hash *node,
      50             :                                   int mcvsToUse);
      51             : static void ExecHashSkewTableInsert(HashJoinTable hashtable,
      52             :                                     TupleTableSlot *slot,
      53             :                                     uint32 hashvalue,
      54             :                                     int bucketNumber);
      55             : static void ExecHashRemoveNextSkewBucket(HashJoinTable hashtable);
      56             : 
      57             : static void *dense_alloc(HashJoinTable hashtable, Size size);
      58             : static HashJoinTuple ExecParallelHashTupleAlloc(HashJoinTable hashtable,
      59             :                                                 size_t size,
      60             :                                                 dsa_pointer *shared);
      61             : static void MultiExecPrivateHash(HashState *node);
      62             : static void MultiExecParallelHash(HashState *node);
      63             : static inline HashJoinTuple ExecParallelHashFirstTuple(HashJoinTable table,
      64             :                                                        int bucketno);
      65             : static inline HashJoinTuple ExecParallelHashNextTuple(HashJoinTable table,
      66             :                                                       HashJoinTuple tuple);
      67             : static inline void ExecParallelHashPushTuple(dsa_pointer_atomic *head,
      68             :                                              HashJoinTuple tuple,
      69             :                                              dsa_pointer tuple_shared);
      70             : static void ExecParallelHashJoinSetUpBatches(HashJoinTable hashtable, int nbatch);
      71             : static void ExecParallelHashEnsureBatchAccessors(HashJoinTable hashtable);
      72             : static void ExecParallelHashRepartitionFirst(HashJoinTable hashtable);
      73             : static void ExecParallelHashRepartitionRest(HashJoinTable hashtable);
      74             : static HashMemoryChunk ExecParallelHashPopChunkQueue(HashJoinTable table,
      75             :                                                      dsa_pointer *shared);
      76             : static bool ExecParallelHashTuplePrealloc(HashJoinTable hashtable,
      77             :                                           int batchno,
      78             :                                           size_t size);
      79             : static void ExecParallelHashMergeCounters(HashJoinTable hashtable);
      80             : static void ExecParallelHashCloseBatchAccessors(HashJoinTable hashtable);
      81             : 
      82             : 
      83             : /* ----------------------------------------------------------------
      84             :  *      ExecHash
      85             :  *
      86             :  *      stub for pro forma compliance
      87             :  * ----------------------------------------------------------------
      88             :  */
      89             : static TupleTableSlot *
      90           0 : ExecHash(PlanState *pstate)
      91             : {
      92           0 :     elog(ERROR, "Hash node does not support ExecProcNode call convention");
      93             :     return NULL;
      94             : }
      95             : 
      96             : /* ----------------------------------------------------------------
      97             :  *      MultiExecHash
      98             :  *
      99             :  *      build hash table for hashjoin, doing partitioning if more
     100             :  *      than one batch is required.
     101             :  * ----------------------------------------------------------------
     102             :  */
     103             : Node *
     104      255338 : MultiExecHash(HashState *node)
     105             : {
     106             :     /* must provide our own instrumentation support */
     107      255338 :     if (node->ps.instrument)
     108         212 :         InstrStartNode(node->ps.instrument);
     109             : 
     110      255338 :     if (node->parallel_state != NULL)
     111         224 :         MultiExecParallelHash(node);
     112             :     else
     113      255114 :         MultiExecPrivateHash(node);
     114             : 
     115             :     /* must provide our own instrumentation support */
     116      255338 :     if (node->ps.instrument)
     117         212 :         InstrStopNode(node->ps.instrument, node->hashtable->partialTuples);
     118             : 
     119             :     /*
     120             :      * We do not return the hash table directly because it's not a subtype of
     121             :      * Node, and so would violate the MultiExecProcNode API.  Instead, our
     122             :      * parent Hashjoin node is expected to know how to fish it out of our node
     123             :      * state.  Ugly but not really worth cleaning up, since Hashjoin knows
     124             :      * quite a bit more about Hash besides that.
     125             :      */
     126      255338 :     return NULL;
     127             : }
     128             : 
     129             : /* ----------------------------------------------------------------
     130             :  *      MultiExecPrivateHash
     131             :  *
     132             :  *      parallel-oblivious version, building a backend-private
     133             :  *      hash table and (if necessary) batch files.
     134             :  * ----------------------------------------------------------------
     135             :  */
     136             : static void
     137      255114 : MultiExecPrivateHash(HashState *node)
     138             : {
     139             :     PlanState  *outerNode;
     140             :     List       *hashkeys;
     141             :     HashJoinTable hashtable;
     142             :     TupleTableSlot *slot;
     143             :     ExprContext *econtext;
     144             :     uint32      hashvalue;
     145             : 
     146             :     /*
     147             :      * get state info from node
     148             :      */
     149      255114 :     outerNode = outerPlanState(node);
     150      255114 :     hashtable = node->hashtable;
     151             : 
     152             :     /*
     153             :      * set expression context
     154             :      */
     155      255114 :     hashkeys = node->hashkeys;
     156      255114 :     econtext = node->ps.ps_ExprContext;
     157             : 
     158             :     /*
     159             :      * Get all tuples from the node below the Hash node and insert into the
     160             :      * hash table (or temp files).
     161             :      */
     162             :     for (;;)
     163             :     {
     164    14232578 :         slot = ExecProcNode(outerNode);
     165     7243846 :         if (TupIsNull(slot))
     166             :             break;
     167             :         /* We have to compute the hash value */
     168     6988732 :         econtext->ecxt_outertuple = slot;
     169     6988732 :         if (ExecHashGetHashValue(hashtable, econtext, hashkeys,
     170     6988732 :                                  false, hashtable->keepNulls,
     171             :                                  &hashvalue))
     172             :         {
     173             :             int         bucketNumber;
     174             : 
     175     6988728 :             bucketNumber = ExecHashGetSkewBucket(hashtable, hashvalue);
     176     6988728 :             if (bucketNumber != INVALID_SKEW_BUCKET_NO)
     177             :             {
     178             :                 /* It's a skew tuple, so put it into that hash table */
     179         172 :                 ExecHashSkewTableInsert(hashtable, slot, hashvalue,
     180             :                                         bucketNumber);
     181         172 :                 hashtable->skewTuples += 1;
     182             :             }
     183             :             else
     184             :             {
     185             :                 /* Not subject to skew optimization, so insert normally */
     186     6988556 :                 ExecHashTableInsert(hashtable, slot, hashvalue);
     187             :             }
     188     6988728 :             hashtable->totalTuples += 1;
     189             :         }
     190             :     }
     191             : 
     192             :     /* resize the hash table if needed (NTUP_PER_BUCKET exceeded) */
     193      255114 :     if (hashtable->nbuckets != hashtable->nbuckets_optimal)
     194         390 :         ExecHashIncreaseNumBuckets(hashtable);
     195             : 
     196             :     /* Account for the buckets in spaceUsed (reported in EXPLAIN ANALYZE) */
     197      255114 :     hashtable->spaceUsed += hashtable->nbuckets * sizeof(HashJoinTuple);
     198      255114 :     if (hashtable->spaceUsed > hashtable->spacePeak)
     199      255092 :         hashtable->spacePeak = hashtable->spaceUsed;
     200             : 
     201      255114 :     hashtable->partialTuples = hashtable->totalTuples;
     202      255114 : }
     203             : 
     204             : /* ----------------------------------------------------------------
     205             :  *      MultiExecParallelHash
     206             :  *
     207             :  *      parallel-aware version, building a shared hash table and
     208             :  *      (if necessary) batch files using the combined effort of
     209             :  *      a set of co-operating backends.
     210             :  * ----------------------------------------------------------------
     211             :  */
     212             : static void
     213         224 : MultiExecParallelHash(HashState *node)
     214             : {
     215             :     ParallelHashJoinState *pstate;
     216             :     PlanState  *outerNode;
     217             :     List       *hashkeys;
     218             :     HashJoinTable hashtable;
     219             :     TupleTableSlot *slot;
     220             :     ExprContext *econtext;
     221             :     uint32      hashvalue;
     222             :     Barrier    *build_barrier;
     223             :     int         i;
     224             : 
     225             :     /*
     226             :      * get state info from node
     227             :      */
     228         224 :     outerNode = outerPlanState(node);
     229         224 :     hashtable = node->hashtable;
     230             : 
     231             :     /*
     232             :      * set expression context
     233             :      */
     234         224 :     hashkeys = node->hashkeys;
     235         224 :     econtext = node->ps.ps_ExprContext;
     236             : 
     237             :     /*
     238             :      * Synchronize the parallel hash table build.  At this stage we know that
     239             :      * the shared hash table has been or is being set up by
     240             :      * ExecHashTableCreate(), but we don't know if our peers have returned
     241             :      * from there or are here in MultiExecParallelHash(), and if so how far
     242             :      * through they are.  To find out, we check the build_barrier phase then
     243             :      * and jump to the right step in the build algorithm.
     244             :      */
     245         224 :     pstate = hashtable->parallel_state;
     246         224 :     build_barrier = &pstate->build_barrier;
     247             :     Assert(BarrierPhase(build_barrier) >= PHJ_BUILD_ALLOCATING);
     248         224 :     switch (BarrierPhase(build_barrier))
     249             :     {
     250             :         case PHJ_BUILD_ALLOCATING:
     251             : 
     252             :             /*
     253             :              * Either I just allocated the initial hash table in
     254             :              * ExecHashTableCreate(), or someone else is doing that.  Either
     255             :              * way, wait for everyone to arrive here so we can proceed.
     256             :              */
     257          96 :             BarrierArriveAndWait(build_barrier, WAIT_EVENT_HASH_BUILD_ALLOCATING);
     258             :             /* Fall through. */
     259             : 
     260             :         case PHJ_BUILD_HASHING_INNER:
     261             : 
     262             :             /*
     263             :              * It's time to begin hashing, or if we just arrived here then
     264             :              * hashing is already underway, so join in that effort.  While
     265             :              * hashing we have to be prepared to help increase the number of
     266             :              * batches or buckets at any time, and if we arrived here when
     267             :              * that was already underway we'll have to help complete that work
     268             :              * immediately so that it's safe to access batches and buckets
     269             :              * below.
     270             :              */
     271         156 :             if (PHJ_GROW_BATCHES_PHASE(BarrierAttach(&pstate->grow_batches_barrier)) !=
     272             :                 PHJ_GROW_BATCHES_ELECTING)
     273           2 :                 ExecParallelHashIncreaseNumBatches(hashtable);
     274         156 :             if (PHJ_GROW_BUCKETS_PHASE(BarrierAttach(&pstate->grow_buckets_barrier)) !=
     275             :                 PHJ_GROW_BUCKETS_ELECTING)
     276           0 :                 ExecParallelHashIncreaseNumBuckets(hashtable);
     277         156 :             ExecParallelHashEnsureBatchAccessors(hashtable);
     278         156 :             ExecParallelHashTableSetCurrentBatch(hashtable, 0);
     279             :             for (;;)
     280             :             {
     281     2400260 :                 slot = ExecProcNode(outerNode);
     282     1200208 :                 if (TupIsNull(slot))
     283             :                     break;
     284     1200052 :                 econtext->ecxt_outertuple = slot;
     285     1200052 :                 if (ExecHashGetHashValue(hashtable, econtext, hashkeys,
     286     1200052 :                                          false, hashtable->keepNulls,
     287             :                                          &hashvalue))
     288     1200052 :                     ExecParallelHashTableInsert(hashtable, slot, hashvalue);
     289     1200052 :                 hashtable->partialTuples++;
     290             :             }
     291             : 
     292             :             /*
     293             :              * Make sure that any tuples we wrote to disk are visible to
     294             :              * others before anyone tries to load them.
     295             :              */
     296         882 :             for (i = 0; i < hashtable->nbatch; ++i)
     297         726 :                 sts_end_write(hashtable->batches[i].inner_tuples);
     298             : 
     299             :             /*
     300             :              * Update shared counters.  We need an accurate total tuple count
     301             :              * to control the empty table optimization.
     302             :              */
     303         156 :             ExecParallelHashMergeCounters(hashtable);
     304             : 
     305         156 :             BarrierDetach(&pstate->grow_buckets_barrier);
     306         156 :             BarrierDetach(&pstate->grow_batches_barrier);
     307             : 
     308             :             /*
     309             :              * Wait for everyone to finish building and flushing files and
     310             :              * counters.
     311             :              */
     312         156 :             if (BarrierArriveAndWait(build_barrier,
     313             :                                      WAIT_EVENT_HASH_BUILD_HASHING_INNER))
     314             :             {
     315             :                 /*
     316             :                  * Elect one backend to disable any further growth.  Batches
     317             :                  * are now fixed.  While building them we made sure they'd fit
     318             :                  * in our memory budget when we load them back in later (or we
     319             :                  * tried to do that and gave up because we detected extreme
     320             :                  * skew).
     321             :                  */
     322          96 :                 pstate->growth = PHJ_GROWTH_DISABLED;
     323             :             }
     324             :     }
     325             : 
     326             :     /*
     327             :      * We're not yet attached to a batch.  We all agree on the dimensions and
     328             :      * number of inner tuples (for the empty table optimization).
     329             :      */
     330         224 :     hashtable->curbatch = -1;
     331         224 :     hashtable->nbuckets = pstate->nbuckets;
     332         224 :     hashtable->log2_nbuckets = my_log2(hashtable->nbuckets);
     333         224 :     hashtable->totalTuples = pstate->total_tuples;
     334         224 :     ExecParallelHashEnsureBatchAccessors(hashtable);
     335             : 
     336             :     /*
     337             :      * The next synchronization point is in ExecHashJoin's HJ_BUILD_HASHTABLE
     338             :      * case, which will bring the build phase to PHJ_BUILD_DONE (if it isn't
     339             :      * there already).
     340             :      */
     341             :     Assert(BarrierPhase(build_barrier) == PHJ_BUILD_HASHING_OUTER ||
     342             :            BarrierPhase(build_barrier) == PHJ_BUILD_DONE);
     343         224 : }
     344             : 
     345             : /* ----------------------------------------------------------------
     346             :  *      ExecInitHash
     347             :  *
     348             :  *      Init routine for Hash node
     349             :  * ----------------------------------------------------------------
     350             :  */
     351             : HashState *
     352       27030 : ExecInitHash(Hash *node, EState *estate, int eflags)
     353             : {
     354             :     HashState  *hashstate;
     355             : 
     356             :     /* check for unsupported flags */
     357             :     Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
     358             : 
     359             :     /*
     360             :      * create state structure
     361             :      */
     362       27030 :     hashstate = makeNode(HashState);
     363       27030 :     hashstate->ps.plan = (Plan *) node;
     364       27030 :     hashstate->ps.state = estate;
     365       27030 :     hashstate->ps.ExecProcNode = ExecHash;
     366       27030 :     hashstate->hashtable = NULL;
     367       27030 :     hashstate->hashkeys = NIL;   /* will be set by parent HashJoin */
     368             : 
     369             :     /*
     370             :      * Miscellaneous initialization
     371             :      *
     372             :      * create expression context for node
     373             :      */
     374       27030 :     ExecAssignExprContext(estate, &hashstate->ps);
     375             : 
     376             :     /*
     377             :      * initialize child nodes
     378             :      */
     379       27030 :     outerPlanState(hashstate) = ExecInitNode(outerPlan(node), estate, eflags);
     380             : 
     381             :     /*
     382             :      * initialize our result slot and type. No need to build projection
     383             :      * because this node doesn't do projections.
     384             :      */
     385       27030 :     ExecInitResultTupleSlotTL(&hashstate->ps, &TTSOpsMinimalTuple);
     386       27030 :     hashstate->ps.ps_ProjInfo = NULL;
     387             : 
     388             :     /*
     389             :      * initialize child expressions
     390             :      */
     391             :     Assert(node->plan.qual == NIL);
     392       27030 :     hashstate->hashkeys =
     393       27030 :         ExecInitExprList(node->hashkeys, (PlanState *) hashstate);
     394             : 
     395       27030 :     return hashstate;
     396             : }
     397             : 
     398             : /* ---------------------------------------------------------------
     399             :  *      ExecEndHash
     400             :  *
     401             :  *      clean up routine for Hash node
     402             :  * ----------------------------------------------------------------
     403             :  */
     404             : void
     405       26994 : ExecEndHash(HashState *node)
     406             : {
     407             :     PlanState  *outerPlan;
     408             : 
     409             :     /*
     410             :      * free exprcontext
     411             :      */
     412       26994 :     ExecFreeExprContext(&node->ps);
     413             : 
     414             :     /*
     415             :      * shut down the subplan
     416             :      */
     417       26994 :     outerPlan = outerPlanState(node);
     418       26994 :     ExecEndNode(outerPlan);
     419       26994 : }
     420             : 
     421             : 
     422             : /* ----------------------------------------------------------------
     423             :  *      ExecHashTableCreate
     424             :  *
     425             :  *      create an empty hashtable data structure for hashjoin.
     426             :  * ----------------------------------------------------------------
     427             :  */
     428             : HashJoinTable
     429      255338 : ExecHashTableCreate(HashState *state, List *hashOperators, List *hashCollations, bool keepNulls)
     430             : {
     431             :     Hash       *node;
     432             :     HashJoinTable hashtable;
     433             :     Plan       *outerNode;
     434             :     size_t      space_allowed;
     435             :     int         nbuckets;
     436             :     int         nbatch;
     437             :     double      rows;
     438             :     int         num_skew_mcvs;
     439             :     int         log2_nbuckets;
     440             :     int         nkeys;
     441             :     int         i;
     442             :     ListCell   *ho;
     443             :     ListCell   *hc;
     444             :     MemoryContext oldcxt;
     445             : 
     446             :     /*
     447             :      * Get information about the size of the relation to be hashed (it's the
     448             :      * "outer" subtree of this node, but the inner relation of the hashjoin).
     449             :      * Compute the appropriate size of the hash table.
     450             :      */
     451      255338 :     node = (Hash *) state->ps.plan;
     452      255338 :     outerNode = outerPlan(node);
     453             : 
     454             :     /*
     455             :      * If this is shared hash table with a partial plan, then we can't use
     456             :      * outerNode->plan_rows to estimate its size.  We need an estimate of the
     457             :      * total number of rows across all copies of the partial plan.
     458             :      */
     459      255338 :     rows = node->plan.parallel_aware ? node->rows_total : outerNode->plan_rows;
     460             : 
     461      766238 :     ExecChooseHashTableSize(rows, outerNode->plan_width,
     462      255338 :                             OidIsValid(node->skewTable),
     463      255338 :                             state->parallel_state != NULL,
     464      255338 :                             state->parallel_state != NULL ?
     465         224 :                             state->parallel_state->nparticipants - 1 : 0,
     466             :                             &space_allowed,
     467             :                             &nbuckets, &nbatch, &num_skew_mcvs);
     468             : 
     469             :     /* nbuckets must be a power of 2 */
     470      255338 :     log2_nbuckets = my_log2(nbuckets);
     471             :     Assert(nbuckets == (1 << log2_nbuckets));
     472             : 
     473             :     /*
     474             :      * Initialize the hash table control block.
     475             :      *
     476             :      * The hashtable control block is just palloc'd from the executor's
     477             :      * per-query memory context.  Everything else should be kept inside the
     478             :      * subsidiary hashCxt or batchCxt.
     479             :      */
     480      255338 :     hashtable = (HashJoinTable) palloc(sizeof(HashJoinTableData));
     481      255338 :     hashtable->nbuckets = nbuckets;
     482      255338 :     hashtable->nbuckets_original = nbuckets;
     483      255338 :     hashtable->nbuckets_optimal = nbuckets;
     484      255338 :     hashtable->log2_nbuckets = log2_nbuckets;
     485      255338 :     hashtable->log2_nbuckets_optimal = log2_nbuckets;
     486      255338 :     hashtable->buckets.unshared = NULL;
     487      255338 :     hashtable->keepNulls = keepNulls;
     488      255338 :     hashtable->skewEnabled = false;
     489      255338 :     hashtable->skewBucket = NULL;
     490      255338 :     hashtable->skewBucketLen = 0;
     491      255338 :     hashtable->nSkewBuckets = 0;
     492      255338 :     hashtable->skewBucketNums = NULL;
     493      255338 :     hashtable->nbatch = nbatch;
     494      255338 :     hashtable->curbatch = 0;
     495      255338 :     hashtable->nbatch_original = nbatch;
     496      255338 :     hashtable->nbatch_outstart = nbatch;
     497      255338 :     hashtable->growEnabled = true;
     498      255338 :     hashtable->totalTuples = 0;
     499      255338 :     hashtable->partialTuples = 0;
     500      255338 :     hashtable->skewTuples = 0;
     501      255338 :     hashtable->innerBatchFile = NULL;
     502      255338 :     hashtable->outerBatchFile = NULL;
     503      255338 :     hashtable->spaceUsed = 0;
     504      255338 :     hashtable->spacePeak = 0;
     505      255338 :     hashtable->spaceAllowed = space_allowed;
     506      255338 :     hashtable->spaceUsedSkew = 0;
     507      255338 :     hashtable->spaceAllowedSkew =
     508      255338 :         hashtable->spaceAllowed * SKEW_WORK_MEM_PERCENT / 100;
     509      255338 :     hashtable->chunks = NULL;
     510      255338 :     hashtable->current_chunk = NULL;
     511      255338 :     hashtable->parallel_state = state->parallel_state;
     512      255338 :     hashtable->area = state->ps.state->es_query_dsa;
     513      255338 :     hashtable->batches = NULL;
     514             : 
     515             : #ifdef HJDEBUG
     516             :     printf("Hashjoin %p: initial nbatch = %d, nbuckets = %d\n",
     517             :            hashtable, nbatch, nbuckets);
     518             : #endif
     519             : 
     520             :     /*
     521             :      * Create temporary memory contexts in which to keep the hashtable working
     522             :      * storage.  See notes in executor/hashjoin.h.
     523             :      */
     524      255338 :     hashtable->hashCxt = AllocSetContextCreate(CurrentMemoryContext,
     525             :                                                "HashTableContext",
     526             :                                                ALLOCSET_DEFAULT_SIZES);
     527             : 
     528      255338 :     hashtable->batchCxt = AllocSetContextCreate(hashtable->hashCxt,
     529             :                                                 "HashBatchContext",
     530             :                                                 ALLOCSET_DEFAULT_SIZES);
     531             : 
     532             :     /* Allocate data that will live for the life of the hashjoin */
     533             : 
     534      255338 :     oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
     535             : 
     536             :     /*
     537             :      * Get info about the hash functions to be used for each hash key. Also
     538             :      * remember whether the join operators are strict.
     539             :      */
     540      255338 :     nkeys = list_length(hashOperators);
     541      255338 :     hashtable->outer_hashfunctions =
     542      255338 :         (FmgrInfo *) palloc(nkeys * sizeof(FmgrInfo));
     543      255338 :     hashtable->inner_hashfunctions =
     544      255338 :         (FmgrInfo *) palloc(nkeys * sizeof(FmgrInfo));
     545      255338 :     hashtable->hashStrict = (bool *) palloc(nkeys * sizeof(bool));
     546      255338 :     hashtable->collations = (Oid *) palloc(nkeys * sizeof(Oid));
     547      255338 :     i = 0;
     548      511826 :     forboth(ho, hashOperators, hc, hashCollations)
     549             :     {
     550      256488 :         Oid         hashop = lfirst_oid(ho);
     551             :         Oid         left_hashfn;
     552             :         Oid         right_hashfn;
     553             : 
     554      256488 :         if (!get_op_hash_functions(hashop, &left_hashfn, &right_hashfn))
     555           0 :             elog(ERROR, "could not find hash function for hash operator %u",
     556             :                  hashop);
     557      256488 :         fmgr_info(left_hashfn, &hashtable->outer_hashfunctions[i]);
     558      256488 :         fmgr_info(right_hashfn, &hashtable->inner_hashfunctions[i]);
     559      256488 :         hashtable->hashStrict[i] = op_strict(hashop);
     560      256488 :         hashtable->collations[i] = lfirst_oid(hc);
     561      256488 :         i++;
     562             :     }
     563             : 
     564      255338 :     if (nbatch > 1 && hashtable->parallel_state == NULL)
     565             :     {
     566             :         /*
     567             :          * allocate and initialize the file arrays in hashCxt (not needed for
     568             :          * parallel case which uses shared tuplestores instead of raw files)
     569             :          */
     570          72 :         hashtable->innerBatchFile = (BufFile **)
     571          72 :             palloc0(nbatch * sizeof(BufFile *));
     572          72 :         hashtable->outerBatchFile = (BufFile **)
     573          72 :             palloc0(nbatch * sizeof(BufFile *));
     574             :         /* The files will not be opened until needed... */
     575             :         /* ... but make sure we have temp tablespaces established for them */
     576          72 :         PrepareTempTablespaces();
     577             :     }
     578             : 
     579      255338 :     MemoryContextSwitchTo(oldcxt);
     580             : 
     581      255338 :     if (hashtable->parallel_state)
     582             :     {
     583         224 :         ParallelHashJoinState *pstate = hashtable->parallel_state;
     584             :         Barrier    *build_barrier;
     585             : 
     586             :         /*
     587             :          * Attach to the build barrier.  The corresponding detach operation is
     588             :          * in ExecHashTableDetach.  Note that we won't attach to the
     589             :          * batch_barrier for batch 0 yet.  We'll attach later and start it out
     590             :          * in PHJ_BATCH_PROBING phase, because batch 0 is allocated up front
     591             :          * and then loaded while hashing (the standard hybrid hash join
     592             :          * algorithm), and we'll coordinate that using build_barrier.
     593             :          */
     594         224 :         build_barrier = &pstate->build_barrier;
     595         224 :         BarrierAttach(build_barrier);
     596             : 
     597             :         /*
     598             :          * So far we have no idea whether there are any other participants,
     599             :          * and if so, what phase they are working on.  The only thing we care
     600             :          * about at this point is whether someone has already created the
     601             :          * SharedHashJoinBatch objects and the hash table for batch 0.  One
     602             :          * backend will be elected to do that now if necessary.
     603             :          */
     604         320 :         if (BarrierPhase(build_barrier) == PHJ_BUILD_ELECTING &&
     605          96 :             BarrierArriveAndWait(build_barrier, WAIT_EVENT_HASH_BUILD_ELECTING))
     606             :         {
     607          96 :             pstate->nbatch = nbatch;
     608          96 :             pstate->space_allowed = space_allowed;
     609          96 :             pstate->growth = PHJ_GROWTH_OK;
     610             : 
     611             :             /* Set up the shared state for coordinating batches. */
     612          96 :             ExecParallelHashJoinSetUpBatches(hashtable, nbatch);
     613             : 
     614             :             /*
     615             :              * Allocate batch 0's hash table up front so we can load it
     616             :              * directly while hashing.
     617             :              */
     618          96 :             pstate->nbuckets = nbuckets;
     619          96 :             ExecParallelHashTableAlloc(hashtable, 0);
     620             :         }
     621             : 
     622             :         /*
     623             :          * The next Parallel Hash synchronization point is in
     624             :          * MultiExecParallelHash(), which will progress it all the way to
     625             :          * PHJ_BUILD_DONE.  The caller must not return control from this
     626             :          * executor node between now and then.
     627             :          */
     628             :     }
     629             :     else
     630             :     {
     631             :         /*
     632             :          * Prepare context for the first-scan space allocations; allocate the
     633             :          * hashbucket array therein, and set each bucket "empty".
     634             :          */
     635      255114 :         MemoryContextSwitchTo(hashtable->batchCxt);
     636             : 
     637      255114 :         hashtable->buckets.unshared = (HashJoinTuple *)
     638      255114 :             palloc0(nbuckets * sizeof(HashJoinTuple));
     639             : 
     640             :         /*
     641             :          * Set up for skew optimization, if possible and there's a need for
     642             :          * more than one batch.  (In a one-batch join, there's no point in
     643             :          * it.)
     644             :          */
     645      255114 :         if (nbatch > 1)
     646          72 :             ExecHashBuildSkewHash(hashtable, node, num_skew_mcvs);
     647             : 
     648      255114 :         MemoryContextSwitchTo(oldcxt);
     649             :     }
     650             : 
     651      255338 :     return hashtable;
     652             : }
     653             : 
     654             : 
     655             : /*
     656             :  * Compute appropriate size for hashtable given the estimated size of the
     657             :  * relation to be hashed (number of rows and average row width).
     658             :  *
     659             :  * This is exported so that the planner's costsize.c can use it.
     660             :  */
     661             : 
     662             : /* Target bucket loading (tuples per bucket) */
     663             : #define NTUP_PER_BUCKET         1
     664             : 
     665             : void
     666      521456 : ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew,
     667             :                         bool try_combined_work_mem,
     668             :                         int parallel_workers,
     669             :                         size_t *space_allowed,
     670             :                         int *numbuckets,
     671             :                         int *numbatches,
     672             :                         int *num_skew_mcvs)
     673             : {
     674             :     int         tupsize;
     675             :     double      inner_rel_bytes;
     676             :     long        bucket_bytes;
     677             :     long        hash_table_bytes;
     678             :     long        skew_table_bytes;
     679             :     long        max_pointers;
     680             :     long        mppow2;
     681      521456 :     int         nbatch = 1;
     682             :     int         nbuckets;
     683             :     double      dbuckets;
     684             : 
     685             :     /* Force a plausible relation size if no info */
     686      521456 :     if (ntuples <= 0.0)
     687          40 :         ntuples = 1000.0;
     688             : 
     689             :     /*
     690             :      * Estimate tupsize based on footprint of tuple in hashtable... note this
     691             :      * does not allow for any palloc overhead.  The manipulations of spaceUsed
     692             :      * don't count palloc overhead either.
     693             :      */
     694      521456 :     tupsize = HJTUPLE_OVERHEAD +
     695      521456 :         MAXALIGN(SizeofMinimalTupleHeader) +
     696      521456 :         MAXALIGN(tupwidth);
     697      521456 :     inner_rel_bytes = ntuples * tupsize;
     698             : 
     699             :     /*
     700             :      * Target in-memory hashtable size is work_mem kilobytes.
     701             :      */
     702      521456 :     hash_table_bytes = work_mem * 1024L;
     703             : 
     704             :     /*
     705             :      * Parallel Hash tries to use the combined work_mem of all workers to
     706             :      * avoid the need to batch.  If that won't work, it falls back to work_mem
     707             :      * per worker and tries to process batches in parallel.
     708             :      */
     709      521456 :     if (try_combined_work_mem)
     710        2740 :         hash_table_bytes += hash_table_bytes * parallel_workers;
     711             : 
     712      521456 :     *space_allowed = hash_table_bytes;
     713             : 
     714             :     /*
     715             :      * If skew optimization is possible, estimate the number of skew buckets
     716             :      * that will fit in the memory allowed, and decrement the assumed space
     717             :      * available for the main hash table accordingly.
     718             :      *
     719             :      * We make the optimistic assumption that each skew bucket will contain
     720             :      * one inner-relation tuple.  If that turns out to be low, we will recover
     721             :      * at runtime by reducing the number of skew buckets.
     722             :      *
     723             :      * hashtable->skewBucket will have up to 8 times as many HashSkewBucket
     724             :      * pointers as the number of MCVs we allow, since ExecHashBuildSkewHash
     725             :      * will round up to the next power of 2 and then multiply by 4 to reduce
     726             :      * collisions.
     727             :      */
     728      521456 :     if (useskew)
     729             :     {
     730      279200 :         skew_table_bytes = hash_table_bytes * SKEW_WORK_MEM_PERCENT / 100;
     731             : 
     732             :         /*----------
     733             :          * Divisor is:
     734             :          * size of a hash tuple +
     735             :          * worst-case size of skewBucket[] per MCV +
     736             :          * size of skewBucketNums[] entry +
     737             :          * size of skew bucket struct itself
     738             :          *----------
     739             :          */
     740      558400 :         *num_skew_mcvs = skew_table_bytes / (tupsize +
     741             :                                              (8 * sizeof(HashSkewBucket *)) +
     742      279200 :                                              sizeof(int) +
     743             :                                              SKEW_BUCKET_OVERHEAD);
     744      279200 :         if (*num_skew_mcvs > 0)
     745      279200 :             hash_table_bytes -= skew_table_bytes;
     746             :     }
     747             :     else
     748      242256 :         *num_skew_mcvs = 0;
     749             : 
     750             :     /*
     751             :      * Set nbuckets to achieve an average bucket load of NTUP_PER_BUCKET when
     752             :      * memory is filled, assuming a single batch; but limit the value so that
     753             :      * the pointer arrays we'll try to allocate do not exceed work_mem nor
     754             :      * MaxAllocSize.
     755             :      *
     756             :      * Note that both nbuckets and nbatch must be powers of 2 to make
     757             :      * ExecHashGetBucketAndBatch fast.
     758             :      */
     759      521456 :     max_pointers = *space_allowed / sizeof(HashJoinTuple);
     760      521456 :     max_pointers = Min(max_pointers, MaxAllocSize / sizeof(HashJoinTuple));
     761             :     /* If max_pointers isn't a power of 2, must round it down to one */
     762      521456 :     mppow2 = 1L << my_log2(max_pointers);
     763      521456 :     if (max_pointers != mppow2)
     764        1240 :         max_pointers = mppow2 / 2;
     765             : 
     766             :     /* Also ensure we avoid integer overflow in nbatch and nbuckets */
     767             :     /* (this step is redundant given the current value of MaxAllocSize) */
     768      521456 :     max_pointers = Min(max_pointers, INT_MAX / 2);
     769             : 
     770      521456 :     dbuckets = ceil(ntuples / NTUP_PER_BUCKET);
     771      521456 :     dbuckets = Min(dbuckets, max_pointers);
     772      521456 :     nbuckets = (int) dbuckets;
     773             :     /* don't let nbuckets be really small, though ... */
     774      521456 :     nbuckets = Max(nbuckets, 1024);
     775             :     /* ... and force it to be a power of 2. */
     776      521456 :     nbuckets = 1 << my_log2(nbuckets);
     777             : 
     778             :     /*
     779             :      * If there's not enough space to store the projected number of tuples and
     780             :      * the required bucket headers, we will need multiple batches.
     781             :      */
     782      521456 :     bucket_bytes = sizeof(HashJoinTuple) * nbuckets;
     783      521456 :     if (inner_rel_bytes + bucket_bytes > hash_table_bytes)
     784             :     {
     785             :         /* We'll need multiple batches */
     786             :         long        lbuckets;
     787             :         double      dbatch;
     788             :         int         minbatch;
     789             :         long        bucket_size;
     790             : 
     791             :         /*
     792             :          * If Parallel Hash with combined work_mem would still need multiple
     793             :          * batches, we'll have to fall back to regular work_mem budget.
     794             :          */
     795        2432 :         if (try_combined_work_mem)
     796             :         {
     797         144 :             ExecChooseHashTableSize(ntuples, tupwidth, useskew,
     798             :                                     false, parallel_workers,
     799             :                                     space_allowed,
     800             :                                     numbuckets,
     801             :                                     numbatches,
     802             :                                     num_skew_mcvs);
     803         144 :             return;
     804             :         }
     805             : 
     806             :         /*
     807             :          * Estimate the number of buckets we'll want to have when work_mem is
     808             :          * entirely full.  Each bucket will contain a bucket pointer plus
     809             :          * NTUP_PER_BUCKET tuples, whose projected size already includes
     810             :          * overhead for the hash code, pointer to the next tuple, etc.
     811             :          */
     812        2288 :         bucket_size = (tupsize * NTUP_PER_BUCKET + sizeof(HashJoinTuple));
     813        2288 :         lbuckets = 1L << my_log2(hash_table_bytes / bucket_size);
     814        2288 :         lbuckets = Min(lbuckets, max_pointers);
     815        2288 :         nbuckets = (int) lbuckets;
     816        2288 :         nbuckets = 1 << my_log2(nbuckets);
     817        2288 :         bucket_bytes = nbuckets * sizeof(HashJoinTuple);
     818             : 
     819             :         /*
     820             :          * Buckets are simple pointers to hashjoin tuples, while tupsize
     821             :          * includes the pointer, hash code, and MinimalTupleData.  So buckets
     822             :          * should never really exceed 25% of work_mem (even for
     823             :          * NTUP_PER_BUCKET=1); except maybe for work_mem values that are not
     824             :          * 2^N bytes, where we might get more because of doubling. So let's
     825             :          * look for 50% here.
     826             :          */
     827             :         Assert(bucket_bytes <= hash_table_bytes / 2);
     828             : 
     829             :         /* Calculate required number of batches. */
     830        2288 :         dbatch = ceil(inner_rel_bytes / (hash_table_bytes - bucket_bytes));
     831        2288 :         dbatch = Min(dbatch, max_pointers);
     832        2288 :         minbatch = (int) dbatch;
     833        2288 :         nbatch = 2;
     834       12520 :         while (nbatch < minbatch)
     835        7944 :             nbatch <<= 1;
     836             :     }
     837             : 
     838             :     Assert(nbuckets > 0);
     839             :     Assert(nbatch > 0);
     840             : 
     841      521312 :     *numbuckets = nbuckets;
     842      521312 :     *numbatches = nbatch;
     843             : }
     844             : 
     845             : 
     846             : /* ----------------------------------------------------------------
     847             :  *      ExecHashTableDestroy
     848             :  *
     849             :  *      destroy a hash table
     850             :  * ----------------------------------------------------------------
     851             :  */
     852             : void
     853      255306 : ExecHashTableDestroy(HashJoinTable hashtable)
     854             : {
     855             :     int         i;
     856             : 
     857             :     /*
     858             :      * Make sure all the temp files are closed.  We skip batch 0, since it
     859             :      * can't have any temp files (and the arrays might not even exist if
     860             :      * nbatch is only 1).  Parallel hash joins don't use these files.
     861             :      */
     862      255306 :     if (hashtable->innerBatchFile != NULL)
     863             :     {
     864         956 :         for (i = 1; i < hashtable->nbatch; i++)
     865             :         {
     866         840 :             if (hashtable->innerBatchFile[i])
     867           0 :                 BufFileClose(hashtable->innerBatchFile[i]);
     868         840 :             if (hashtable->outerBatchFile[i])
     869           0 :                 BufFileClose(hashtable->outerBatchFile[i]);
     870             :         }
     871             :     }
     872             : 
     873             :     /* Release working memory (batchCxt is a child, so it goes away too) */
     874      255306 :     MemoryContextDelete(hashtable->hashCxt);
     875             : 
     876             :     /* And drop the control block */
     877      255306 :     pfree(hashtable);
     878      255306 : }
     879             : 
     880             : /*
     881             :  * ExecHashIncreaseNumBatches
     882             :  *      increase the original number of batches in order to reduce
     883             :  *      current memory consumption
     884             :  */
     885             : static void
     886      380032 : ExecHashIncreaseNumBatches(HashJoinTable hashtable)
     887             : {
     888      380032 :     int         oldnbatch = hashtable->nbatch;
     889      380032 :     int         curbatch = hashtable->curbatch;
     890             :     int         nbatch;
     891             :     MemoryContext oldcxt;
     892             :     long        ninmemory;
     893             :     long        nfreed;
     894             :     HashMemoryChunk oldchunks;
     895             : 
     896             :     /* do nothing if we've decided to shut off growth */
     897      380032 :     if (!hashtable->growEnabled)
     898      379940 :         return;
     899             : 
     900             :     /* safety check to avoid overflow */
     901          92 :     if (oldnbatch > Min(INT_MAX / 2, MaxAllocSize / (sizeof(void *) * 2)))
     902           0 :         return;
     903             : 
     904          92 :     nbatch = oldnbatch * 2;
     905             :     Assert(nbatch > 1);
     906             : 
     907             : #ifdef HJDEBUG
     908             :     printf("Hashjoin %p: increasing nbatch to %d because space = %zu\n",
     909             :            hashtable, nbatch, hashtable->spaceUsed);
     910             : #endif
     911             : 
     912          92 :     oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
     913             : 
     914          92 :     if (hashtable->innerBatchFile == NULL)
     915             :     {
     916             :         /* we had no file arrays before */
     917          44 :         hashtable->innerBatchFile = (BufFile **)
     918          44 :             palloc0(nbatch * sizeof(BufFile *));
     919          44 :         hashtable->outerBatchFile = (BufFile **)
     920          44 :             palloc0(nbatch * sizeof(BufFile *));
     921             :         /* time to establish the temp tablespaces, too */
     922          44 :         PrepareTempTablespaces();
     923             :     }
     924             :     else
     925             :     {
     926             :         /* enlarge arrays and zero out added entries */
     927          48 :         hashtable->innerBatchFile = (BufFile **)
     928          48 :             repalloc(hashtable->innerBatchFile, nbatch * sizeof(BufFile *));
     929          48 :         hashtable->outerBatchFile = (BufFile **)
     930          48 :             repalloc(hashtable->outerBatchFile, nbatch * sizeof(BufFile *));
     931          48 :         MemSet(hashtable->innerBatchFile + oldnbatch, 0,
     932             :                (nbatch - oldnbatch) * sizeof(BufFile *));
     933          48 :         MemSet(hashtable->outerBatchFile + oldnbatch, 0,
     934             :                (nbatch - oldnbatch) * sizeof(BufFile *));
     935             :     }
     936             : 
     937          92 :     MemoryContextSwitchTo(oldcxt);
     938             : 
     939          92 :     hashtable->nbatch = nbatch;
     940             : 
     941             :     /*
     942             :      * Scan through the existing hash table entries and dump out any that are
     943             :      * no longer of the current batch.
     944             :      */
     945          92 :     ninmemory = nfreed = 0;
     946             : 
     947             :     /* If know we need to resize nbuckets, we can do it while rebatching. */
     948          92 :     if (hashtable->nbuckets_optimal != hashtable->nbuckets)
     949             :     {
     950             :         /* we never decrease the number of buckets */
     951             :         Assert(hashtable->nbuckets_optimal > hashtable->nbuckets);
     952             : 
     953          44 :         hashtable->nbuckets = hashtable->nbuckets_optimal;
     954          44 :         hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
     955             : 
     956          44 :         hashtable->buckets.unshared =
     957          44 :             repalloc(hashtable->buckets.unshared,
     958          44 :                      sizeof(HashJoinTuple) * hashtable->nbuckets);
     959             :     }
     960             : 
     961             :     /*
     962             :      * We will scan through the chunks directly, so that we can reset the
     963             :      * buckets now and not have to keep track which tuples in the buckets have
     964             :      * already been processed. We will free the old chunks as we go.
     965             :      */
     966          92 :     memset(hashtable->buckets.unshared, 0,
     967          92 :            sizeof(HashJoinTuple) * hashtable->nbuckets);
     968          92 :     oldchunks = hashtable->chunks;
     969          92 :     hashtable->chunks = NULL;
     970             : 
     971             :     /* so, let's scan through the old chunks, and all tuples in each chunk */
     972         544 :     while (oldchunks != NULL)
     973             :     {
     974         360 :         HashMemoryChunk nextchunk = oldchunks->next.unshared;
     975             : 
     976             :         /* position within the buffer (up to oldchunks->used) */
     977         360 :         size_t      idx = 0;
     978             : 
     979             :         /* process all tuples stored in this chunk (and then free it) */
     980      246376 :         while (idx < oldchunks->used)
     981             :         {
     982      245656 :             HashJoinTuple hashTuple = (HashJoinTuple) (HASH_CHUNK_DATA(oldchunks) + idx);
     983      245656 :             MinimalTuple tuple = HJTUPLE_MINTUPLE(hashTuple);
     984      245656 :             int         hashTupleSize = (HJTUPLE_OVERHEAD + tuple->t_len);
     985             :             int         bucketno;
     986             :             int         batchno;
     987             : 
     988      245656 :             ninmemory++;
     989      245656 :             ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
     990             :                                       &bucketno, &batchno);
     991             : 
     992      245656 :             if (batchno == curbatch)
     993             :             {
     994             :                 /* keep tuple in memory - copy it into the new chunk */
     995             :                 HashJoinTuple copyTuple;
     996             : 
     997       91988 :                 copyTuple = (HashJoinTuple) dense_alloc(hashtable, hashTupleSize);
     998       91988 :                 memcpy(copyTuple, hashTuple, hashTupleSize);
     999             : 
    1000             :                 /* and add it back to the appropriate bucket */
    1001       91988 :                 copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
    1002       91988 :                 hashtable->buckets.unshared[bucketno] = copyTuple;
    1003             :             }
    1004             :             else
    1005             :             {
    1006             :                 /* dump it out */
    1007             :                 Assert(batchno > curbatch);
    1008      153668 :                 ExecHashJoinSaveTuple(HJTUPLE_MINTUPLE(hashTuple),
    1009             :                                       hashTuple->hashvalue,
    1010      153668 :                                       &hashtable->innerBatchFile[batchno]);
    1011             : 
    1012      153668 :                 hashtable->spaceUsed -= hashTupleSize;
    1013      153668 :                 nfreed++;
    1014             :             }
    1015             : 
    1016             :             /* next tuple in this chunk */
    1017      245656 :             idx += MAXALIGN(hashTupleSize);
    1018             : 
    1019             :             /* allow this loop to be cancellable */
    1020      245656 :             CHECK_FOR_INTERRUPTS();
    1021             :         }
    1022             : 
    1023             :         /* we're done with this chunk - free it and proceed to the next one */
    1024         360 :         pfree(oldchunks);
    1025         360 :         oldchunks = nextchunk;
    1026             :     }
    1027             : 
    1028             : #ifdef HJDEBUG
    1029             :     printf("Hashjoin %p: freed %ld of %ld tuples, space now %zu\n",
    1030             :            hashtable, nfreed, ninmemory, hashtable->spaceUsed);
    1031             : #endif
    1032             : 
    1033             :     /*
    1034             :      * If we dumped out either all or none of the tuples in the table, disable
    1035             :      * further expansion of nbatch.  This situation implies that we have
    1036             :      * enough tuples of identical hashvalues to overflow spaceAllowed.
    1037             :      * Increasing nbatch will not fix it since there's no way to subdivide the
    1038             :      * group any more finely. We have to just gut it out and hope the server
    1039             :      * has enough RAM.
    1040             :      */
    1041          92 :     if (nfreed == 0 || nfreed == ninmemory)
    1042             :     {
    1043          22 :         hashtable->growEnabled = false;
    1044             : #ifdef HJDEBUG
    1045             :         printf("Hashjoin %p: disabling further increase of nbatch\n",
    1046             :                hashtable);
    1047             : #endif
    1048             :     }
    1049             : }
    1050             : 
    1051             : /*
    1052             :  * ExecParallelHashIncreaseNumBatches
    1053             :  *      Every participant attached to grow_batches_barrier must run this
    1054             :  *      function when it observes growth == PHJ_GROWTH_NEED_MORE_BATCHES.
    1055             :  */
    1056             : static void
    1057          34 : ExecParallelHashIncreaseNumBatches(HashJoinTable hashtable)
    1058             : {
    1059          34 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    1060             :     int         i;
    1061             : 
    1062             :     Assert(BarrierPhase(&pstate->build_barrier) == PHJ_BUILD_HASHING_INNER);
    1063             : 
    1064             :     /*
    1065             :      * It's unlikely, but we need to be prepared for new participants to show
    1066             :      * up while we're in the middle of this operation so we need to switch on
    1067             :      * barrier phase here.
    1068             :      */
    1069          34 :     switch (PHJ_GROW_BATCHES_PHASE(BarrierPhase(&pstate->grow_batches_barrier)))
    1070             :     {
    1071             :         case PHJ_GROW_BATCHES_ELECTING:
    1072             : 
    1073             :             /*
    1074             :              * Elect one participant to prepare to grow the number of batches.
    1075             :              * This involves reallocating or resetting the buckets of batch 0
    1076             :              * in preparation for all participants to begin repartitioning the
    1077             :              * tuples.
    1078             :              */
    1079          32 :             if (BarrierArriveAndWait(&pstate->grow_batches_barrier,
    1080             :                                      WAIT_EVENT_HASH_GROW_BATCHES_ELECTING))
    1081             :             {
    1082             :                 dsa_pointer_atomic *buckets;
    1083             :                 ParallelHashJoinBatch *old_batch0;
    1084             :                 int         new_nbatch;
    1085             :                 int         i;
    1086             : 
    1087             :                 /* Move the old batch out of the way. */
    1088          32 :                 old_batch0 = hashtable->batches[0].shared;
    1089          32 :                 pstate->old_batches = pstate->batches;
    1090          32 :                 pstate->old_nbatch = hashtable->nbatch;
    1091          32 :                 pstate->batches = InvalidDsaPointer;
    1092             : 
    1093             :                 /* Free this backend's old accessors. */
    1094          32 :                 ExecParallelHashCloseBatchAccessors(hashtable);
    1095             : 
    1096             :                 /* Figure out how many batches to use. */
    1097          32 :                 if (hashtable->nbatch == 1)
    1098             :                 {
    1099             :                     /*
    1100             :                      * We are going from single-batch to multi-batch.  We need
    1101             :                      * to switch from one large combined memory budget to the
    1102             :                      * regular work_mem budget.
    1103             :                      */
    1104          24 :                     pstate->space_allowed = work_mem * 1024L;
    1105             : 
    1106             :                     /*
    1107             :                      * The combined work_mem of all participants wasn't
    1108             :                      * enough. Therefore one batch per participant would be
    1109             :                      * approximately equivalent and would probably also be
    1110             :                      * insufficient.  So try two batches per participant,
    1111             :                      * rounded up to a power of two.
    1112             :                      */
    1113          24 :                     new_nbatch = 1 << my_log2(pstate->nparticipants * 2);
    1114             :                 }
    1115             :                 else
    1116             :                 {
    1117             :                     /*
    1118             :                      * We were already multi-batched.  Try doubling the number
    1119             :                      * of batches.
    1120             :                      */
    1121           8 :                     new_nbatch = hashtable->nbatch * 2;
    1122             :                 }
    1123             : 
    1124             :                 /* Allocate new larger generation of batches. */
    1125             :                 Assert(hashtable->nbatch == pstate->nbatch);
    1126          32 :                 ExecParallelHashJoinSetUpBatches(hashtable, new_nbatch);
    1127             :                 Assert(hashtable->nbatch == pstate->nbatch);
    1128             : 
    1129             :                 /* Replace or recycle batch 0's bucket array. */
    1130          32 :                 if (pstate->old_nbatch == 1)
    1131             :                 {
    1132             :                     double      dtuples;
    1133             :                     double      dbuckets;
    1134             :                     int         new_nbuckets;
    1135             : 
    1136             :                     /*
    1137             :                      * We probably also need a smaller bucket array.  How many
    1138             :                      * tuples do we expect per batch, assuming we have only
    1139             :                      * half of them so far?  Normally we don't need to change
    1140             :                      * the bucket array's size, because the size of each batch
    1141             :                      * stays the same as we add more batches, but in this
    1142             :                      * special case we move from a large batch to many smaller
    1143             :                      * batches and it would be wasteful to keep the large
    1144             :                      * array.
    1145             :                      */
    1146          24 :                     dtuples = (old_batch0->ntuples * 2.0) / new_nbatch;
    1147          24 :                     dbuckets = ceil(dtuples / NTUP_PER_BUCKET);
    1148          24 :                     dbuckets = Min(dbuckets,
    1149             :                                    MaxAllocSize / sizeof(dsa_pointer_atomic));
    1150          24 :                     new_nbuckets = (int) dbuckets;
    1151          24 :                     new_nbuckets = Max(new_nbuckets, 1024);
    1152          24 :                     new_nbuckets = 1 << my_log2(new_nbuckets);
    1153          24 :                     dsa_free(hashtable->area, old_batch0->buckets);
    1154          48 :                     hashtable->batches[0].shared->buckets =
    1155          24 :                         dsa_allocate(hashtable->area,
    1156             :                                      sizeof(dsa_pointer_atomic) * new_nbuckets);
    1157          24 :                     buckets = (dsa_pointer_atomic *)
    1158          24 :                         dsa_get_address(hashtable->area,
    1159          24 :                                         hashtable->batches[0].shared->buckets);
    1160       73752 :                     for (i = 0; i < new_nbuckets; ++i)
    1161       73728 :                         dsa_pointer_atomic_init(&buckets[i], InvalidDsaPointer);
    1162          24 :                     pstate->nbuckets = new_nbuckets;
    1163             :                 }
    1164             :                 else
    1165             :                 {
    1166             :                     /* Recycle the existing bucket array. */
    1167           8 :                     hashtable->batches[0].shared->buckets = old_batch0->buckets;
    1168           8 :                     buckets = (dsa_pointer_atomic *)
    1169           8 :                         dsa_get_address(hashtable->area, old_batch0->buckets);
    1170       32776 :                     for (i = 0; i < hashtable->nbuckets; ++i)
    1171       32768 :                         dsa_pointer_atomic_write(&buckets[i], InvalidDsaPointer);
    1172             :                 }
    1173             : 
    1174             :                 /* Move all chunks to the work queue for parallel processing. */
    1175          32 :                 pstate->chunk_work_queue = old_batch0->chunks;
    1176             : 
    1177             :                 /* Disable further growth temporarily while we're growing. */
    1178          32 :                 pstate->growth = PHJ_GROWTH_DISABLED;
    1179             :             }
    1180             :             else
    1181             :             {
    1182             :                 /* All other participants just flush their tuples to disk. */
    1183           0 :                 ExecParallelHashCloseBatchAccessors(hashtable);
    1184             :             }
    1185             :             /* Fall through. */
    1186             : 
    1187             :         case PHJ_GROW_BATCHES_ALLOCATING:
    1188             :             /* Wait for the above to be finished. */
    1189          32 :             BarrierArriveAndWait(&pstate->grow_batches_barrier,
    1190             :                                  WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATING);
    1191             :             /* Fall through. */
    1192             : 
    1193             :         case PHJ_GROW_BATCHES_REPARTITIONING:
    1194             :             /* Make sure that we have the current dimensions and buckets. */
    1195          34 :             ExecParallelHashEnsureBatchAccessors(hashtable);
    1196          34 :             ExecParallelHashTableSetCurrentBatch(hashtable, 0);
    1197             :             /* Then partition, flush counters. */
    1198          34 :             ExecParallelHashRepartitionFirst(hashtable);
    1199          34 :             ExecParallelHashRepartitionRest(hashtable);
    1200          34 :             ExecParallelHashMergeCounters(hashtable);
    1201             :             /* Wait for the above to be finished. */
    1202          34 :             BarrierArriveAndWait(&pstate->grow_batches_barrier,
    1203             :                                  WAIT_EVENT_HASH_GROW_BATCHES_REPARTITIONING);
    1204             :             /* Fall through. */
    1205             : 
    1206             :         case PHJ_GROW_BATCHES_DECIDING:
    1207             : 
    1208             :             /*
    1209             :              * Elect one participant to clean up and decide whether further
    1210             :              * repartitioning is needed, or should be disabled because it's
    1211             :              * not helping.
    1212             :              */
    1213          34 :             if (BarrierArriveAndWait(&pstate->grow_batches_barrier,
    1214             :                                      WAIT_EVENT_HASH_GROW_BATCHES_DECIDING))
    1215             :             {
    1216          32 :                 bool        space_exhausted = false;
    1217          32 :                 bool        extreme_skew_detected = false;
    1218             : 
    1219             :                 /* Make sure that we have the current dimensions and buckets. */
    1220          32 :                 ExecParallelHashEnsureBatchAccessors(hashtable);
    1221          32 :                 ExecParallelHashTableSetCurrentBatch(hashtable, 0);
    1222             : 
    1223             :                 /* Are any of the new generation of batches exhausted? */
    1224         224 :                 for (i = 0; i < hashtable->nbatch; ++i)
    1225             :                 {
    1226         192 :                     ParallelHashJoinBatch *batch = hashtable->batches[i].shared;
    1227             : 
    1228         384 :                     if (batch->space_exhausted ||
    1229         192 :                         batch->estimated_size > pstate->space_allowed)
    1230             :                     {
    1231             :                         int         parent;
    1232             : 
    1233          16 :                         space_exhausted = true;
    1234             : 
    1235             :                         /*
    1236             :                          * Did this batch receive ALL of the tuples from its
    1237             :                          * parent batch?  That would indicate that further
    1238             :                          * repartitioning isn't going to help (the hash values
    1239             :                          * are probably all the same).
    1240             :                          */
    1241          16 :                         parent = i % pstate->old_nbatch;
    1242          16 :                         if (batch->ntuples == hashtable->batches[parent].shared->old_ntuples)
    1243          16 :                             extreme_skew_detected = true;
    1244             :                     }
    1245             :                 }
    1246             : 
    1247             :                 /* Don't keep growing if it's not helping or we'd overflow. */
    1248          32 :                 if (extreme_skew_detected || hashtable->nbatch >= INT_MAX / 2)
    1249          16 :                     pstate->growth = PHJ_GROWTH_DISABLED;
    1250          16 :                 else if (space_exhausted)
    1251           0 :                     pstate->growth = PHJ_GROWTH_NEED_MORE_BATCHES;
    1252             :                 else
    1253          16 :                     pstate->growth = PHJ_GROWTH_OK;
    1254             : 
    1255             :                 /* Free the old batches in shared memory. */
    1256          32 :                 dsa_free(hashtable->area, pstate->old_batches);
    1257          32 :                 pstate->old_batches = InvalidDsaPointer;
    1258             :             }
    1259             :             /* Fall through. */
    1260             : 
    1261             :         case PHJ_GROW_BATCHES_FINISHING:
    1262             :             /* Wait for the above to complete. */
    1263          34 :             BarrierArriveAndWait(&pstate->grow_batches_barrier,
    1264             :                                  WAIT_EVENT_HASH_GROW_BATCHES_FINISHING);
    1265             :     }
    1266          34 : }
    1267             : 
    1268             : /*
    1269             :  * Repartition the tuples currently loaded into memory for inner batch 0
    1270             :  * because the number of batches has been increased.  Some tuples are retained
    1271             :  * in memory and some are written out to a later batch.
    1272             :  */
    1273             : static void
    1274          34 : ExecParallelHashRepartitionFirst(HashJoinTable hashtable)
    1275             : {
    1276             :     dsa_pointer chunk_shared;
    1277             :     HashMemoryChunk chunk;
    1278             : 
    1279             :     Assert(hashtable->nbatch == hashtable->parallel_state->nbatch);
    1280             : 
    1281         260 :     while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_shared)))
    1282             :     {
    1283         192 :         size_t      idx = 0;
    1284             : 
    1285             :         /* Repartition all tuples in this chunk. */
    1286      147432 :         while (idx < chunk->used)
    1287             :         {
    1288      147048 :             HashJoinTuple hashTuple = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + idx);
    1289      147048 :             MinimalTuple tuple = HJTUPLE_MINTUPLE(hashTuple);
    1290             :             HashJoinTuple copyTuple;
    1291             :             dsa_pointer shared;
    1292             :             int         bucketno;
    1293             :             int         batchno;
    1294             : 
    1295      147048 :             ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
    1296             :                                       &bucketno, &batchno);
    1297             : 
    1298             :             Assert(batchno < hashtable->nbatch);
    1299      147048 :             if (batchno == 0)
    1300             :             {
    1301             :                 /* It still belongs in batch 0.  Copy to a new chunk. */
    1302       33832 :                 copyTuple =
    1303       33832 :                     ExecParallelHashTupleAlloc(hashtable,
    1304       33832 :                                                HJTUPLE_OVERHEAD + tuple->t_len,
    1305             :                                                &shared);
    1306       33832 :                 copyTuple->hashvalue = hashTuple->hashvalue;
    1307       33832 :                 memcpy(HJTUPLE_MINTUPLE(copyTuple), tuple, tuple->t_len);
    1308       33832 :                 ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
    1309             :                                           copyTuple, shared);
    1310             :             }
    1311             :             else
    1312             :             {
    1313      113216 :                 size_t      tuple_size =
    1314      113216 :                 MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
    1315             : 
    1316             :                 /* It belongs in a later batch. */
    1317      113216 :                 hashtable->batches[batchno].estimated_size += tuple_size;
    1318      113216 :                 sts_puttuple(hashtable->batches[batchno].inner_tuples,
    1319      113216 :                              &hashTuple->hashvalue, tuple);
    1320             :             }
    1321             : 
    1322             :             /* Count this tuple. */
    1323      147048 :             ++hashtable->batches[0].old_ntuples;
    1324      147048 :             ++hashtable->batches[batchno].ntuples;
    1325             : 
    1326      147048 :             idx += MAXALIGN(HJTUPLE_OVERHEAD +
    1327             :                             HJTUPLE_MINTUPLE(hashTuple)->t_len);
    1328             :         }
    1329             : 
    1330             :         /* Free this chunk. */
    1331         192 :         dsa_free(hashtable->area, chunk_shared);
    1332             : 
    1333         192 :         CHECK_FOR_INTERRUPTS();
    1334             :     }
    1335          34 : }
    1336             : 
    1337             : /*
    1338             :  * Help repartition inner batches 1..n.
    1339             :  */
    1340             : static void
    1341          34 : ExecParallelHashRepartitionRest(HashJoinTable hashtable)
    1342             : {
    1343          34 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    1344          34 :     int         old_nbatch = pstate->old_nbatch;
    1345             :     SharedTuplestoreAccessor **old_inner_tuples;
    1346             :     ParallelHashJoinBatch *old_batches;
    1347             :     int         i;
    1348             : 
    1349             :     /* Get our hands on the previous generation of batches. */
    1350          34 :     old_batches = (ParallelHashJoinBatch *)
    1351          34 :         dsa_get_address(hashtable->area, pstate->old_batches);
    1352          34 :     old_inner_tuples = palloc0(sizeof(SharedTuplestoreAccessor *) * old_nbatch);
    1353          64 :     for (i = 1; i < old_nbatch; ++i)
    1354             :     {
    1355          30 :         ParallelHashJoinBatch *shared =
    1356          30 :         NthParallelHashJoinBatch(old_batches, i);
    1357             : 
    1358          30 :         old_inner_tuples[i] = sts_attach(ParallelHashJoinBatchInner(shared),
    1359             :                                          ParallelWorkerNumber + 1,
    1360             :                                          &pstate->fileset);
    1361             :     }
    1362             : 
    1363             :     /* Join in the effort to repartition them. */
    1364          64 :     for (i = 1; i < old_nbatch; ++i)
    1365             :     {
    1366             :         MinimalTuple tuple;
    1367             :         uint32      hashvalue;
    1368             : 
    1369             :         /* Scan one partition from the previous generation. */
    1370          30 :         sts_begin_parallel_scan(old_inner_tuples[i]);
    1371      107636 :         while ((tuple = sts_parallel_scan_next(old_inner_tuples[i], &hashvalue)))
    1372             :         {
    1373      107576 :             size_t      tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
    1374             :             int         bucketno;
    1375             :             int         batchno;
    1376             : 
    1377             :             /* Decide which partition it goes to in the new generation. */
    1378      107576 :             ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno,
    1379             :                                       &batchno);
    1380             : 
    1381      107576 :             hashtable->batches[batchno].estimated_size += tuple_size;
    1382      107576 :             ++hashtable->batches[batchno].ntuples;
    1383      107576 :             ++hashtable->batches[i].old_ntuples;
    1384             : 
    1385             :             /* Store the tuple its new batch. */
    1386      107576 :             sts_puttuple(hashtable->batches[batchno].inner_tuples,
    1387             :                          &hashvalue, tuple);
    1388             : 
    1389      107576 :             CHECK_FOR_INTERRUPTS();
    1390             :         }
    1391          30 :         sts_end_parallel_scan(old_inner_tuples[i]);
    1392             :     }
    1393             : 
    1394          34 :     pfree(old_inner_tuples);
    1395          34 : }
    1396             : 
    1397             : /*
    1398             :  * Transfer the backend-local per-batch counters to the shared totals.
    1399             :  */
    1400             : static void
    1401         190 : ExecParallelHashMergeCounters(HashJoinTable hashtable)
    1402             : {
    1403         190 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    1404             :     int         i;
    1405             : 
    1406         190 :     LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
    1407         190 :     pstate->total_tuples = 0;
    1408        1124 :     for (i = 0; i < hashtable->nbatch; ++i)
    1409             :     {
    1410         934 :         ParallelHashJoinBatchAccessor *batch = &hashtable->batches[i];
    1411             : 
    1412         934 :         batch->shared->size += batch->size;
    1413         934 :         batch->shared->estimated_size += batch->estimated_size;
    1414         934 :         batch->shared->ntuples += batch->ntuples;
    1415         934 :         batch->shared->old_ntuples += batch->old_ntuples;
    1416         934 :         batch->size = 0;
    1417         934 :         batch->estimated_size = 0;
    1418         934 :         batch->ntuples = 0;
    1419         934 :         batch->old_ntuples = 0;
    1420         934 :         pstate->total_tuples += batch->shared->ntuples;
    1421             :     }
    1422         190 :     LWLockRelease(&pstate->lock);
    1423         190 : }
    1424             : 
    1425             : /*
    1426             :  * ExecHashIncreaseNumBuckets
    1427             :  *      increase the original number of buckets in order to reduce
    1428             :  *      number of tuples per bucket
    1429             :  */
    1430             : static void
    1431         390 : ExecHashIncreaseNumBuckets(HashJoinTable hashtable)
    1432             : {
    1433             :     HashMemoryChunk chunk;
    1434             : 
    1435             :     /* do nothing if not an increase (it's called increase for a reason) */
    1436         390 :     if (hashtable->nbuckets >= hashtable->nbuckets_optimal)
    1437           0 :         return;
    1438             : 
    1439             : #ifdef HJDEBUG
    1440             :     printf("Hashjoin %p: increasing nbuckets %d => %d\n",
    1441             :            hashtable, hashtable->nbuckets, hashtable->nbuckets_optimal);
    1442             : #endif
    1443             : 
    1444         390 :     hashtable->nbuckets = hashtable->nbuckets_optimal;
    1445         390 :     hashtable->log2_nbuckets = hashtable->log2_nbuckets_optimal;
    1446             : 
    1447             :     Assert(hashtable->nbuckets > 1);
    1448             :     Assert(hashtable->nbuckets <= (INT_MAX / 2));
    1449             :     Assert(hashtable->nbuckets == (1 << hashtable->log2_nbuckets));
    1450             : 
    1451             :     /*
    1452             :      * Just reallocate the proper number of buckets - we don't need to walk
    1453             :      * through them - we can walk the dense-allocated chunks (just like in
    1454             :      * ExecHashIncreaseNumBatches, but without all the copying into new
    1455             :      * chunks)
    1456             :      */
    1457         390 :     hashtable->buckets.unshared =
    1458         390 :         (HashJoinTuple *) repalloc(hashtable->buckets.unshared,
    1459         390 :                                    hashtable->nbuckets * sizeof(HashJoinTuple));
    1460             : 
    1461         390 :     memset(hashtable->buckets.unshared, 0,
    1462         390 :            hashtable->nbuckets * sizeof(HashJoinTuple));
    1463             : 
    1464             :     /* scan through all tuples in all chunks to rebuild the hash table */
    1465        2058 :     for (chunk = hashtable->chunks; chunk != NULL; chunk = chunk->next.unshared)
    1466             :     {
    1467             :         /* process all tuples stored in this chunk */
    1468        1668 :         size_t      idx = 0;
    1469             : 
    1470     1255980 :         while (idx < chunk->used)
    1471             :         {
    1472     1252644 :             HashJoinTuple hashTuple = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + idx);
    1473             :             int         bucketno;
    1474             :             int         batchno;
    1475             : 
    1476     1252644 :             ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
    1477             :                                       &bucketno, &batchno);
    1478             : 
    1479             :             /* add the tuple to the proper bucket */
    1480     1252644 :             hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
    1481     1252644 :             hashtable->buckets.unshared[bucketno] = hashTuple;
    1482             : 
    1483             :             /* advance index past the tuple */
    1484     1252644 :             idx += MAXALIGN(HJTUPLE_OVERHEAD +
    1485             :                             HJTUPLE_MINTUPLE(hashTuple)->t_len);
    1486             :         }
    1487             : 
    1488             :         /* allow this loop to be cancellable */
    1489        1668 :         CHECK_FOR_INTERRUPTS();
    1490             :     }
    1491             : }
    1492             : 
    1493             : static void
    1494          96 : ExecParallelHashIncreaseNumBuckets(HashJoinTable hashtable)
    1495             : {
    1496          96 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    1497             :     int         i;
    1498             :     HashMemoryChunk chunk;
    1499             :     dsa_pointer chunk_s;
    1500             : 
    1501             :     Assert(BarrierPhase(&pstate->build_barrier) == PHJ_BUILD_HASHING_INNER);
    1502             : 
    1503             :     /*
    1504             :      * It's unlikely, but we need to be prepared for new participants to show
    1505             :      * up while we're in the middle of this operation so we need to switch on
    1506             :      * barrier phase here.
    1507             :      */
    1508          96 :     switch (PHJ_GROW_BUCKETS_PHASE(BarrierPhase(&pstate->grow_buckets_barrier)))
    1509             :     {
    1510             :         case PHJ_GROW_BUCKETS_ELECTING:
    1511             :             /* Elect one participant to prepare to increase nbuckets. */
    1512          96 :             if (BarrierArriveAndWait(&pstate->grow_buckets_barrier,
    1513             :                                      WAIT_EVENT_HASH_GROW_BUCKETS_ELECTING))
    1514             :             {
    1515             :                 size_t      size;
    1516             :                 dsa_pointer_atomic *buckets;
    1517             : 
    1518             :                 /* Double the size of the bucket array. */
    1519          72 :                 pstate->nbuckets *= 2;
    1520          72 :                 size = pstate->nbuckets * sizeof(dsa_pointer_atomic);
    1521          72 :                 hashtable->batches[0].shared->size += size / 2;
    1522          72 :                 dsa_free(hashtable->area, hashtable->batches[0].shared->buckets);
    1523         144 :                 hashtable->batches[0].shared->buckets =
    1524          72 :                     dsa_allocate(hashtable->area, size);
    1525          72 :                 buckets = (dsa_pointer_atomic *)
    1526          72 :                     dsa_get_address(hashtable->area,
    1527          72 :                                     hashtable->batches[0].shared->buckets);
    1528      622664 :                 for (i = 0; i < pstate->nbuckets; ++i)
    1529      622592 :                     dsa_pointer_atomic_init(&buckets[i], InvalidDsaPointer);
    1530             : 
    1531             :                 /* Put the chunk list onto the work queue. */
    1532          72 :                 pstate->chunk_work_queue = hashtable->batches[0].shared->chunks;
    1533             : 
    1534             :                 /* Clear the flag. */
    1535          72 :                 pstate->growth = PHJ_GROWTH_OK;
    1536             :             }
    1537             :             /* Fall through. */
    1538             : 
    1539             :         case PHJ_GROW_BUCKETS_ALLOCATING:
    1540             :             /* Wait for the above to complete. */
    1541          96 :             BarrierArriveAndWait(&pstate->grow_buckets_barrier,
    1542             :                                  WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATING);
    1543             :             /* Fall through. */
    1544             : 
    1545             :         case PHJ_GROW_BUCKETS_REINSERTING:
    1546             :             /* Reinsert all tuples into the hash table. */
    1547          96 :             ExecParallelHashEnsureBatchAccessors(hashtable);
    1548          96 :             ExecParallelHashTableSetCurrentBatch(hashtable, 0);
    1549         632 :             while ((chunk = ExecParallelHashPopChunkQueue(hashtable, &chunk_s)))
    1550             :             {
    1551         440 :                 size_t      idx = 0;
    1552             : 
    1553      360800 :                 while (idx < chunk->used)
    1554             :                 {
    1555      359920 :                     HashJoinTuple hashTuple = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + idx);
    1556      359920 :                     dsa_pointer shared = chunk_s + HASH_CHUNK_HEADER_SIZE + idx;
    1557             :                     int         bucketno;
    1558             :                     int         batchno;
    1559             : 
    1560      359920 :                     ExecHashGetBucketAndBatch(hashtable, hashTuple->hashvalue,
    1561             :                                               &bucketno, &batchno);
    1562             :                     Assert(batchno == 0);
    1563             : 
    1564             :                     /* add the tuple to the proper bucket */
    1565      359920 :                     ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
    1566             :                                               hashTuple, shared);
    1567             : 
    1568             :                     /* advance index past the tuple */
    1569      359920 :                     idx += MAXALIGN(HJTUPLE_OVERHEAD +
    1570             :                                     HJTUPLE_MINTUPLE(hashTuple)->t_len);
    1571             :                 }
    1572             : 
    1573             :                 /* allow this loop to be cancellable */
    1574         440 :                 CHECK_FOR_INTERRUPTS();
    1575             :             }
    1576          96 :             BarrierArriveAndWait(&pstate->grow_buckets_barrier,
    1577             :                                  WAIT_EVENT_HASH_GROW_BUCKETS_REINSERTING);
    1578             :     }
    1579          96 : }
    1580             : 
    1581             : /*
    1582             :  * ExecHashTableInsert
    1583             :  *      insert a tuple into the hash table depending on the hash value
    1584             :  *      it may just go to a temp file for later batches
    1585             :  *
    1586             :  * Note: the passed TupleTableSlot may contain a regular, minimal, or virtual
    1587             :  * tuple; the minimal case in particular is certain to happen while reloading
    1588             :  * tuples from batch files.  We could save some cycles in the regular-tuple
    1589             :  * case by not forcing the slot contents into minimal form; not clear if it's
    1590             :  * worth the messiness required.
    1591             :  */
    1592             : void
    1593     8759960 : ExecHashTableInsert(HashJoinTable hashtable,
    1594             :                     TupleTableSlot *slot,
    1595             :                     uint32 hashvalue)
    1596             : {
    1597             :     bool        shouldFree;
    1598     8759960 :     MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
    1599             :     int         bucketno;
    1600             :     int         batchno;
    1601             : 
    1602     8759960 :     ExecHashGetBucketAndBatch(hashtable, hashvalue,
    1603             :                               &bucketno, &batchno);
    1604             : 
    1605             :     /*
    1606             :      * decide whether to put the tuple in the hash table or a temp file
    1607             :      */
    1608     8759960 :     if (batchno == hashtable->curbatch)
    1609             :     {
    1610             :         /*
    1611             :          * put the tuple in hash table
    1612             :          */
    1613             :         HashJoinTuple hashTuple;
    1614             :         int         hashTupleSize;
    1615     7142308 :         double      ntuples = (hashtable->totalTuples - hashtable->skewTuples);
    1616             : 
    1617             :         /* Create the HashJoinTuple */
    1618     7142308 :         hashTupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
    1619     7142308 :         hashTuple = (HashJoinTuple) dense_alloc(hashtable, hashTupleSize);
    1620             : 
    1621     7142308 :         hashTuple->hashvalue = hashvalue;
    1622     7142308 :         memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
    1623             : 
    1624             :         /*
    1625             :          * We always reset the tuple-matched flag on insertion.  This is okay
    1626             :          * even when reloading a tuple from a batch file, since the tuple
    1627             :          * could not possibly have been matched to an outer tuple before it
    1628             :          * went into the batch file.
    1629             :          */
    1630     7142308 :         HeapTupleHeaderClearMatch(HJTUPLE_MINTUPLE(hashTuple));
    1631             : 
    1632             :         /* Push it onto the front of the bucket's list */
    1633     7142308 :         hashTuple->next.unshared = hashtable->buckets.unshared[bucketno];
    1634     7142308 :         hashtable->buckets.unshared[bucketno] = hashTuple;
    1635             : 
    1636             :         /*
    1637             :          * Increase the (optimal) number of buckets if we just exceeded the
    1638             :          * NTUP_PER_BUCKET threshold, but only when there's still a single
    1639             :          * batch.
    1640             :          */
    1641    12451200 :         if (hashtable->nbatch == 1 &&
    1642     5308892 :             ntuples > (hashtable->nbuckets_optimal * NTUP_PER_BUCKET))
    1643             :         {
    1644             :             /* Guard against integer overflow and alloc size overflow */
    1645        1600 :             if (hashtable->nbuckets_optimal <= INT_MAX / 2 &&
    1646         800 :                 hashtable->nbuckets_optimal * 2 <= MaxAllocSize / sizeof(HashJoinTuple))
    1647             :             {
    1648         800 :                 hashtable->nbuckets_optimal *= 2;
    1649         800 :                 hashtable->log2_nbuckets_optimal += 1;
    1650             :             }
    1651             :         }
    1652             : 
    1653             :         /* Account for space used, and back off if we've used too much */
    1654     7142308 :         hashtable->spaceUsed += hashTupleSize;
    1655     7142308 :         if (hashtable->spaceUsed > hashtable->spacePeak)
    1656     5776326 :             hashtable->spacePeak = hashtable->spaceUsed;
    1657    21426924 :         if (hashtable->spaceUsed +
    1658     7142308 :             hashtable->nbuckets_optimal * sizeof(HashJoinTuple)
    1659     7142308 :             > hashtable->spaceAllowed)
    1660      380032 :             ExecHashIncreaseNumBatches(hashtable);
    1661             :     }
    1662             :     else
    1663             :     {
    1664             :         /*
    1665             :          * put the tuple into a temp file for later batches
    1666             :          */
    1667             :         Assert(batchno > hashtable->curbatch);
    1668     1617652 :         ExecHashJoinSaveTuple(tuple,
    1669             :                               hashvalue,
    1670     1617652 :                               &hashtable->innerBatchFile[batchno]);
    1671             :     }
    1672             : 
    1673     8759960 :     if (shouldFree)
    1674     6542108 :         heap_free_minimal_tuple(tuple);
    1675     8759960 : }
    1676             : 
    1677             : /*
    1678             :  * ExecParallelHashTableInsert
    1679             :  *      insert a tuple into a shared hash table or shared batch tuplestore
    1680             :  */
    1681             : void
    1682     1200052 : ExecParallelHashTableInsert(HashJoinTable hashtable,
    1683             :                             TupleTableSlot *slot,
    1684             :                             uint32 hashvalue)
    1685             : {
    1686             :     bool        shouldFree;
    1687     1200052 :     MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
    1688             :     dsa_pointer shared;
    1689             :     int         bucketno;
    1690             :     int         batchno;
    1691             : 
    1692             : retry:
    1693     1200284 :     ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
    1694             : 
    1695     1200284 :     if (batchno == 0)
    1696             :     {
    1697             :         HashJoinTuple hashTuple;
    1698             : 
    1699             :         /* Try to load it into memory. */
    1700             :         Assert(BarrierPhase(&hashtable->parallel_state->build_barrier) ==
    1701             :                PHJ_BUILD_HASHING_INNER);
    1702      661612 :         hashTuple = ExecParallelHashTupleAlloc(hashtable,
    1703      661612 :                                                HJTUPLE_OVERHEAD + tuple->t_len,
    1704             :                                                &shared);
    1705      661612 :         if (hashTuple == NULL)
    1706         216 :             goto retry;
    1707             : 
    1708             :         /* Store the hash value in the HashJoinTuple header. */
    1709      661396 :         hashTuple->hashvalue = hashvalue;
    1710      661396 :         memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
    1711             : 
    1712             :         /* Push it onto the front of the bucket's list */
    1713      661396 :         ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
    1714             :                                   hashTuple, shared);
    1715             :     }
    1716             :     else
    1717             :     {
    1718      538672 :         size_t      tuple_size = MAXALIGN(HJTUPLE_OVERHEAD + tuple->t_len);
    1719             : 
    1720             :         Assert(batchno > 0);
    1721             : 
    1722             :         /* Try to preallocate space in the batch if necessary. */
    1723      538672 :         if (hashtable->batches[batchno].preallocated < tuple_size)
    1724             :         {
    1725        1048 :             if (!ExecParallelHashTuplePrealloc(hashtable, batchno, tuple_size))
    1726          16 :                 goto retry;
    1727             :         }
    1728             : 
    1729             :         Assert(hashtable->batches[batchno].preallocated >= tuple_size);
    1730      538656 :         hashtable->batches[batchno].preallocated -= tuple_size;
    1731      538656 :         sts_puttuple(hashtable->batches[batchno].inner_tuples, &hashvalue,
    1732             :                      tuple);
    1733             :     }
    1734     1200052 :     ++hashtable->batches[batchno].ntuples;
    1735             : 
    1736     1200052 :     if (shouldFree)
    1737     1200052 :         heap_free_minimal_tuple(tuple);
    1738     1200052 : }
    1739             : 
    1740             : /*
    1741             :  * Insert a tuple into the current hash table.  Unlike
    1742             :  * ExecParallelHashTableInsert, this version is not prepared to send the tuple
    1743             :  * to other batches or to run out of memory, and should only be called with
    1744             :  * tuples that belong in the current batch once growth has been disabled.
    1745             :  */
    1746             : void
    1747      651872 : ExecParallelHashTableInsertCurrentBatch(HashJoinTable hashtable,
    1748             :                                         TupleTableSlot *slot,
    1749             :                                         uint32 hashvalue)
    1750             : {
    1751             :     bool        shouldFree;
    1752      651872 :     MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
    1753             :     HashJoinTuple hashTuple;
    1754             :     dsa_pointer shared;
    1755             :     int         batchno;
    1756             :     int         bucketno;
    1757             : 
    1758      651872 :     ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
    1759             :     Assert(batchno == hashtable->curbatch);
    1760      651872 :     hashTuple = ExecParallelHashTupleAlloc(hashtable,
    1761      651872 :                                            HJTUPLE_OVERHEAD + tuple->t_len,
    1762             :                                            &shared);
    1763      651872 :     hashTuple->hashvalue = hashvalue;
    1764      651872 :     memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
    1765      651872 :     HeapTupleHeaderClearMatch(HJTUPLE_MINTUPLE(hashTuple));
    1766      651872 :     ExecParallelHashPushTuple(&hashtable->buckets.shared[bucketno],
    1767             :                               hashTuple, shared);
    1768             : 
    1769      651872 :     if (shouldFree)
    1770           0 :         heap_free_minimal_tuple(tuple);
    1771      651872 : }
    1772             : 
    1773             : /*
    1774             :  * ExecHashGetHashValue
    1775             :  *      Compute the hash value for a tuple
    1776             :  *
    1777             :  * The tuple to be tested must be in econtext->ecxt_outertuple (thus Vars in
    1778             :  * the hashkeys expressions need to have OUTER_VAR as varno). If outer_tuple
    1779             :  * is false (meaning it's the HashJoin's inner node, Hash), econtext,
    1780             :  * hashkeys, and slot need to be from Hash, with hashkeys/slot referencing and
    1781             :  * being suitable for tuples from the node below the Hash. Conversely, if
    1782             :  * outer_tuple is true, econtext is from HashJoin, and hashkeys/slot need to
    1783             :  * be appropriate for tuples from HashJoin's outer node.
    1784             :  *
    1785             :  * A true result means the tuple's hash value has been successfully computed
    1786             :  * and stored at *hashvalue.  A false result means the tuple cannot match
    1787             :  * because it contains a null attribute, and hence it should be discarded
    1788             :  * immediately.  (If keep_nulls is true then false is never returned.)
    1789             :  */
    1790             : bool
    1791    17729290 : ExecHashGetHashValue(HashJoinTable hashtable,
    1792             :                      ExprContext *econtext,
    1793             :                      List *hashkeys,
    1794             :                      bool outer_tuple,
    1795             :                      bool keep_nulls,
    1796             :                      uint32 *hashvalue)
    1797             : {
    1798    17729290 :     uint32      hashkey = 0;
    1799             :     FmgrInfo   *hashfunctions;
    1800             :     ListCell   *hk;
    1801    17729290 :     int         i = 0;
    1802             :     MemoryContext oldContext;
    1803             : 
    1804             :     /*
    1805             :      * We reset the eval context each time to reclaim any memory leaked in the
    1806             :      * hashkey expressions.
    1807             :      */
    1808    17729290 :     ResetExprContext(econtext);
    1809             : 
    1810    17729290 :     oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
    1811             : 
    1812    17729290 :     if (outer_tuple)
    1813     9540506 :         hashfunctions = hashtable->outer_hashfunctions;
    1814             :     else
    1815     8188784 :         hashfunctions = hashtable->inner_hashfunctions;
    1816             : 
    1817    36482410 :     foreach(hk, hashkeys)
    1818             :     {
    1819    18753588 :         ExprState  *keyexpr = (ExprState *) lfirst(hk);
    1820             :         Datum       keyval;
    1821             :         bool        isNull;
    1822             : 
    1823             :         /* rotate hashkey left 1 bit at each step */
    1824    18753588 :         hashkey = (hashkey << 1) | ((hashkey & 0x80000000) ? 1 : 0);
    1825             : 
    1826             :         /*
    1827             :          * Get the join attribute value of the tuple
    1828             :          */
    1829    18753588 :         keyval = ExecEvalExpr(keyexpr, econtext, &isNull);
    1830             : 
    1831             :         /*
    1832             :          * If the attribute is NULL, and the join operator is strict, then
    1833             :          * this tuple cannot pass the join qual so we can reject it
    1834             :          * immediately (unless we're scanning the outside of an outer join, in
    1835             :          * which case we must not reject it).  Otherwise we act like the
    1836             :          * hashcode of NULL is zero (this will support operators that act like
    1837             :          * IS NOT DISTINCT, though not any more-random behavior).  We treat
    1838             :          * the hash support function as strict even if the operator is not.
    1839             :          *
    1840             :          * Note: currently, all hashjoinable operators must be strict since
    1841             :          * the hash index AM assumes that.  However, it takes so little extra
    1842             :          * code here to allow non-strict that we may as well do it.
    1843             :          */
    1844    18753588 :         if (isNull)
    1845             :         {
    1846         610 :             if (hashtable->hashStrict[i] && !keep_nulls)
    1847             :             {
    1848         468 :                 MemoryContextSwitchTo(oldContext);
    1849         468 :                 return false;   /* cannot match */
    1850             :             }
    1851             :             /* else, leave hashkey unmodified, equivalent to hashcode 0 */
    1852             :         }
    1853             :         else
    1854             :         {
    1855             :             /* Compute the hash function */
    1856             :             uint32      hkey;
    1857             : 
    1858    18752978 :             hkey = DatumGetUInt32(FunctionCall1Coll(&hashfunctions[i], hashtable->collations[i], keyval));
    1859    18752978 :             hashkey ^= hkey;
    1860             :         }
    1861             : 
    1862    18753120 :         i++;
    1863             :     }
    1864             : 
    1865    17728822 :     MemoryContextSwitchTo(oldContext);
    1866             : 
    1867    17728822 :     *hashvalue = hashkey;
    1868    17728822 :     return true;
    1869             : }
    1870             : 
    1871             : /*
    1872             :  * ExecHashGetBucketAndBatch
    1873             :  *      Determine the bucket number and batch number for a hash value
    1874             :  *
    1875             :  * Note: on-the-fly increases of nbatch must not change the bucket number
    1876             :  * for a given hash code (since we don't move tuples to different hash
    1877             :  * chains), and must only cause the batch number to remain the same or
    1878             :  * increase.  Our algorithm is
    1879             :  *      bucketno = hashvalue MOD nbuckets
    1880             :  *      batchno = (hashvalue DIV nbuckets) MOD nbatch
    1881             :  * where nbuckets and nbatch are both expected to be powers of 2, so we can
    1882             :  * do the computations by shifting and masking.  (This assumes that all hash
    1883             :  * functions are good about randomizing all their output bits, else we are
    1884             :  * likely to have very skewed bucket or batch occupancy.)
    1885             :  *
    1886             :  * nbuckets and log2_nbuckets may change while nbatch == 1 because of dynamic
    1887             :  * bucket count growth.  Once we start batching, the value is fixed and does
    1888             :  * not change over the course of the join (making it possible to compute batch
    1889             :  * number the way we do here).
    1890             :  *
    1891             :  * nbatch is always a power of 2; we increase it only by doubling it.  This
    1892             :  * effectively adds one more bit to the top of the batchno.
    1893             :  */
    1894             : void
    1895    23971178 : ExecHashGetBucketAndBatch(HashJoinTable hashtable,
    1896             :                           uint32 hashvalue,
    1897             :                           int *bucketno,
    1898             :                           int *batchno)
    1899             : {
    1900    23971178 :     uint32      nbuckets = (uint32) hashtable->nbuckets;
    1901    23971178 :     uint32      nbatch = (uint32) hashtable->nbatch;
    1902             : 
    1903    23971178 :     if (nbatch > 1)
    1904             :     {
    1905             :         /* we can do MOD by masking, DIV by shifting */
    1906     8878188 :         *bucketno = hashvalue & (nbuckets - 1);
    1907     8878188 :         *batchno = (hashvalue >> hashtable->log2_nbuckets) & (nbatch - 1);
    1908             :     }
    1909             :     else
    1910             :     {
    1911    15092990 :         *bucketno = hashvalue & (nbuckets - 1);
    1912    15092990 :         *batchno = 0;
    1913             :     }
    1914    23971178 : }
    1915             : 
    1916             : /*
    1917             :  * ExecScanHashBucket
    1918             :  *      scan a hash bucket for matches to the current outer tuple
    1919             :  *
    1920             :  * The current outer tuple must be stored in econtext->ecxt_outertuple.
    1921             :  *
    1922             :  * On success, the inner tuple is stored into hjstate->hj_CurTuple and
    1923             :  * econtext->ecxt_innertuple, using hjstate->hj_HashTupleSlot as the slot
    1924             :  * for the latter.
    1925             :  */
    1926             : bool
    1927    12061166 : ExecScanHashBucket(HashJoinState *hjstate,
    1928             :                    ExprContext *econtext)
    1929             : {
    1930    12061166 :     ExprState  *hjclauses = hjstate->hashclauses;
    1931    12061166 :     HashJoinTable hashtable = hjstate->hj_HashTable;
    1932    12061166 :     HashJoinTuple hashTuple = hjstate->hj_CurTuple;
    1933    12061166 :     uint32      hashvalue = hjstate->hj_CurHashValue;
    1934             : 
    1935             :     /*
    1936             :      * hj_CurTuple is the address of the tuple last returned from the current
    1937             :      * bucket, or NULL if it's time to start scanning a new bucket.
    1938             :      *
    1939             :      * If the tuple hashed to a skew bucket then scan the skew bucket
    1940             :      * otherwise scan the standard hashtable bucket.
    1941             :      */
    1942    12061166 :     if (hashTuple != NULL)
    1943     3721140 :         hashTuple = hashTuple->next.unshared;
    1944     8340026 :     else if (hjstate->hj_CurSkewBucketNo != INVALID_SKEW_BUCKET_NO)
    1945         800 :         hashTuple = hashtable->skewBucket[hjstate->hj_CurSkewBucketNo]->tuples;
    1946             :     else
    1947     8339226 :         hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
    1948             : 
    1949    26531096 :     while (hashTuple != NULL)
    1950             :     {
    1951     7928770 :         if (hashTuple->hashvalue == hashvalue)
    1952             :         {
    1953             :             TupleTableSlot *inntuple;
    1954             : 
    1955             :             /* insert hashtable's tuple into exec slot so ExecQual sees it */
    1956     5520006 :             inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
    1957             :                                              hjstate->hj_HashTupleSlot,
    1958             :                                              false);    /* do not pfree */
    1959     5520006 :             econtext->ecxt_innertuple = inntuple;
    1960             : 
    1961     5520006 :             if (ExecQualAndReset(hjclauses, econtext))
    1962             :             {
    1963     5520006 :                 hjstate->hj_CurTuple = hashTuple;
    1964     5520006 :                 return true;
    1965             :             }
    1966             :         }
    1967             : 
    1968     2408764 :         hashTuple = hashTuple->next.unshared;
    1969             :     }
    1970             : 
    1971             :     /*
    1972             :      * no match
    1973             :      */
    1974     6541160 :     return false;
    1975             : }
    1976             : 
    1977             : /*
    1978             :  * ExecParallelScanHashBucket
    1979             :  *      scan a hash bucket for matches to the current outer tuple
    1980             :  *
    1981             :  * The current outer tuple must be stored in econtext->ecxt_outertuple.
    1982             :  *
    1983             :  * On success, the inner tuple is stored into hjstate->hj_CurTuple and
    1984             :  * econtext->ecxt_innertuple, using hjstate->hj_HashTupleSlot as the slot
    1985             :  * for the latter.
    1986             :  */
    1987             : bool
    1988     2400032 : ExecParallelScanHashBucket(HashJoinState *hjstate,
    1989             :                            ExprContext *econtext)
    1990             : {
    1991     2400032 :     ExprState  *hjclauses = hjstate->hashclauses;
    1992     2400032 :     HashJoinTable hashtable = hjstate->hj_HashTable;
    1993     2400032 :     HashJoinTuple hashTuple = hjstate->hj_CurTuple;
    1994     2400032 :     uint32      hashvalue = hjstate->hj_CurHashValue;
    1995             : 
    1996             :     /*
    1997             :      * hj_CurTuple is the address of the tuple last returned from the current
    1998             :      * bucket, or NULL if it's time to start scanning a new bucket.
    1999             :      */
    2000     2400032 :     if (hashTuple != NULL)
    2001     1200016 :         hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
    2002             :     else
    2003     1200016 :         hashTuple = ExecParallelHashFirstTuple(hashtable,
    2004             :                                                hjstate->hj_CurBucketNo);
    2005             : 
    2006     5593208 :     while (hashTuple != NULL)
    2007             :     {
    2008     1993160 :         if (hashTuple->hashvalue == hashvalue)
    2009             :         {
    2010             :             TupleTableSlot *inntuple;
    2011             : 
    2012             :             /* insert hashtable's tuple into exec slot so ExecQual sees it */
    2013     1200016 :             inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
    2014             :                                              hjstate->hj_HashTupleSlot,
    2015             :                                              false);    /* do not pfree */
    2016     1200016 :             econtext->ecxt_innertuple = inntuple;
    2017             : 
    2018     1200016 :             if (ExecQualAndReset(hjclauses, econtext))
    2019             :             {
    2020     1200016 :                 hjstate->hj_CurTuple = hashTuple;
    2021     1200016 :                 return true;
    2022             :             }
    2023             :         }
    2024             : 
    2025      793144 :         hashTuple = ExecParallelHashNextTuple(hashtable, hashTuple);
    2026             :     }
    2027             : 
    2028             :     /*
    2029             :      * no match
    2030             :      */
    2031     1200016 :     return false;
    2032             : }
    2033             : 
    2034             : /*
    2035             :  * ExecPrepHashTableForUnmatched
    2036             :  *      set up for a series of ExecScanHashTableForUnmatched calls
    2037             :  */
    2038             : void
    2039        3740 : ExecPrepHashTableForUnmatched(HashJoinState *hjstate)
    2040             : {
    2041             :     /*----------
    2042             :      * During this scan we use the HashJoinState fields as follows:
    2043             :      *
    2044             :      * hj_CurBucketNo: next regular bucket to scan
    2045             :      * hj_CurSkewBucketNo: next skew bucket (an index into skewBucketNums)
    2046             :      * hj_CurTuple: last tuple returned, or NULL to start next bucket
    2047             :      *----------
    2048             :      */
    2049        3740 :     hjstate->hj_CurBucketNo = 0;
    2050        3740 :     hjstate->hj_CurSkewBucketNo = 0;
    2051        3740 :     hjstate->hj_CurTuple = NULL;
    2052        3740 : }
    2053             : 
    2054             : /*
    2055             :  * ExecScanHashTableForUnmatched
    2056             :  *      scan the hash table for unmatched inner tuples
    2057             :  *
    2058             :  * On success, the inner tuple is stored into hjstate->hj_CurTuple and
    2059             :  * econtext->ecxt_innertuple, using hjstate->hj_HashTupleSlot as the slot
    2060             :  * for the latter.
    2061             :  */
    2062             : bool
    2063      206108 : ExecScanHashTableForUnmatched(HashJoinState *hjstate, ExprContext *econtext)
    2064             : {
    2065      206108 :     HashJoinTable hashtable = hjstate->hj_HashTable;
    2066      206108 :     HashJoinTuple hashTuple = hjstate->hj_CurTuple;
    2067             : 
    2068             :     for (;;)
    2069             :     {
    2070             :         /*
    2071             :          * hj_CurTuple is the address of the tuple last returned from the
    2072             :          * current bucket, or NULL if it's time to start scanning a new
    2073             :          * bucket.
    2074             :          */
    2075     9102620 :         if (hashTuple != NULL)
    2076      202368 :             hashTuple = hashTuple->next.unshared;
    2077     4451996 :         else if (hjstate->hj_CurBucketNo < hashtable->nbuckets)
    2078             :         {
    2079     4448260 :             hashTuple = hashtable->buckets.unshared[hjstate->hj_CurBucketNo];
    2080     4448260 :             hjstate->hj_CurBucketNo++;
    2081             :         }
    2082        3736 :         else if (hjstate->hj_CurSkewBucketNo < hashtable->nSkewBuckets)
    2083             :         {
    2084           0 :             int         j = hashtable->skewBucketNums[hjstate->hj_CurSkewBucketNo];
    2085             : 
    2086           0 :             hashTuple = hashtable->skewBucket[j]->tuples;
    2087           0 :             hjstate->hj_CurSkewBucketNo++;
    2088             :         }
    2089             :         else
    2090        3736 :             break;              /* finished all buckets */
    2091             : 
    2092     9526222 :         while (hashTuple != NULL)
    2093             :         {
    2094      427338 :             if (!HeapTupleHeaderHasMatch(HJTUPLE_MINTUPLE(hashTuple)))
    2095             :             {
    2096             :                 TupleTableSlot *inntuple;
    2097             : 
    2098             :                 /* insert hashtable's tuple into exec slot */
    2099      202372 :                 inntuple = ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple),
    2100             :                                                  hjstate->hj_HashTupleSlot,
    2101             :                                                  false);    /* do not pfree */
    2102      202372 :                 econtext->ecxt_innertuple = inntuple;
    2103             : 
    2104             :                 /*
    2105             :                  * Reset temp memory each time; although this function doesn't
    2106             :                  * do any qual eval, the caller will, so let's keep it
    2107             :                  * parallel to ExecScanHashBucket.
    2108             :                  */
    2109      202372 :                 ResetExprContext(econtext);
    2110             : 
    2111      202372 :                 hjstate->hj_CurTuple = hashTuple;
    2112      202372 :                 return true;
    2113             :             }
    2114             : 
    2115      224966 :             hashTuple = hashTuple->next.unshared;
    2116             :         }
    2117             : 
    2118             :         /* allow this loop to be cancellable */
    2119     4448256 :         CHECK_FOR_INTERRUPTS();
    2120             :     }
    2121             : 
    2122             :     /*
    2123             :      * no more unmatched tuples
    2124             :      */
    2125        3736 :     return false;
    2126             : }
    2127             : 
    2128             : /*
    2129             :  * ExecHashTableReset
    2130             :  *
    2131             :  *      reset hash table header for new batch
    2132             :  */
    2133             : void
    2134         840 : ExecHashTableReset(HashJoinTable hashtable)
    2135             : {
    2136             :     MemoryContext oldcxt;
    2137         840 :     int         nbuckets = hashtable->nbuckets;
    2138             : 
    2139             :     /*
    2140             :      * Release all the hash buckets and tuples acquired in the prior pass, and
    2141             :      * reinitialize the context for a new pass.
    2142             :      */
    2143         840 :     MemoryContextReset(hashtable->batchCxt);
    2144         840 :     oldcxt = MemoryContextSwitchTo(hashtable->batchCxt);
    2145             : 
    2146             :     /* Reallocate and reinitialize the hash bucket headers. */
    2147         840 :     hashtable->buckets.unshared = (HashJoinTuple *)
    2148         840 :         palloc0(nbuckets * sizeof(HashJoinTuple));
    2149             : 
    2150         840 :     hashtable->spaceUsed = 0;
    2151             : 
    2152         840 :     MemoryContextSwitchTo(oldcxt);
    2153             : 
    2154             :     /* Forget the chunks (the memory was freed by the context reset above). */
    2155         840 :     hashtable->chunks = NULL;
    2156         840 : }
    2157             : 
    2158             : /*
    2159             :  * ExecHashTableResetMatchFlags
    2160             :  *      Clear all the HeapTupleHeaderHasMatch flags in the table
    2161             :  */
    2162             : void
    2163          20 : ExecHashTableResetMatchFlags(HashJoinTable hashtable)
    2164             : {
    2165             :     HashJoinTuple tuple;
    2166             :     int         i;
    2167             : 
    2168             :     /* Reset all flags in the main table ... */
    2169       20500 :     for (i = 0; i < hashtable->nbuckets; i++)
    2170             :     {
    2171       41048 :         for (tuple = hashtable->buckets.unshared[i]; tuple != NULL;
    2172          88 :              tuple = tuple->next.unshared)
    2173          88 :             HeapTupleHeaderClearMatch(HJTUPLE_MINTUPLE(tuple));
    2174             :     }
    2175             : 
    2176             :     /* ... and the same for the skew buckets, if any */
    2177          20 :     for (i = 0; i < hashtable->nSkewBuckets; i++)
    2178             :     {
    2179           0 :         int         j = hashtable->skewBucketNums[i];
    2180           0 :         HashSkewBucket *skewBucket = hashtable->skewBucket[j];
    2181             : 
    2182           0 :         for (tuple = skewBucket->tuples; tuple != NULL; tuple = tuple->next.unshared)
    2183           0 :             HeapTupleHeaderClearMatch(HJTUPLE_MINTUPLE(tuple));
    2184             :     }
    2185          20 : }
    2186             : 
    2187             : 
    2188             : void
    2189      241466 : ExecReScanHash(HashState *node)
    2190             : {
    2191             :     /*
    2192             :      * if chgParam of subnode is not null then plan will be re-scanned by
    2193             :      * first ExecProcNode.
    2194             :      */
    2195      241466 :     if (node->ps.lefttree->chgParam == NULL)
    2196           0 :         ExecReScan(node->ps.lefttree);
    2197      241466 : }
    2198             : 
    2199             : 
    2200             : /*
    2201             :  * ExecHashBuildSkewHash
    2202             :  *
    2203             :  *      Set up for skew optimization if we can identify the most common values
    2204             :  *      (MCVs) of the outer relation's join key.  We make a skew hash bucket
    2205             :  *      for the hash value of each MCV, up to the number of slots allowed
    2206             :  *      based on available memory.
    2207             :  */
    2208             : static void
    2209          72 : ExecHashBuildSkewHash(HashJoinTable hashtable, Hash *node, int mcvsToUse)
    2210             : {
    2211             :     HeapTupleData *statsTuple;
    2212             :     AttStatsSlot sslot;
    2213             : 
    2214             :     /* Do nothing if planner didn't identify the outer relation's join key */
    2215          72 :     if (!OidIsValid(node->skewTable))
    2216          48 :         return;
    2217             :     /* Also, do nothing if we don't have room for at least one skew bucket */
    2218          72 :     if (mcvsToUse <= 0)
    2219           0 :         return;
    2220             : 
    2221             :     /*
    2222             :      * Try to find the MCV statistics for the outer relation's join key.
    2223             :      */
    2224         216 :     statsTuple = SearchSysCache3(STATRELATTINH,
    2225          72 :                                  ObjectIdGetDatum(node->skewTable),
    2226          72 :                                  Int16GetDatum(node->skewColumn),
    2227          72 :                                  BoolGetDatum(node->skewInherit));
    2228          72 :     if (!HeapTupleIsValid(statsTuple))
    2229          48 :         return;
    2230             : 
    2231          24 :     if (get_attstatsslot(&sslot, statsTuple,
    2232             :                          STATISTIC_KIND_MCV, InvalidOid,
    2233             :                          ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
    2234             :     {
    2235             :         double      frac;
    2236             :         int         nbuckets;
    2237             :         FmgrInfo   *hashfunctions;
    2238             :         int         i;
    2239             : 
    2240           4 :         if (mcvsToUse > sslot.nvalues)
    2241           0 :             mcvsToUse = sslot.nvalues;
    2242             : 
    2243             :         /*
    2244             :          * Calculate the expected fraction of outer relation that will
    2245             :          * participate in the skew optimization.  If this isn't at least
    2246             :          * SKEW_MIN_OUTER_FRACTION, don't use skew optimization.
    2247             :          */
    2248           4 :         frac = 0;
    2249          44 :         for (i = 0; i < mcvsToUse; i++)
    2250          40 :             frac += sslot.numbers[i];
    2251           4 :         if (frac < SKEW_MIN_OUTER_FRACTION)
    2252             :         {
    2253           0 :             free_attstatsslot(&sslot);
    2254           0 :             ReleaseSysCache(statsTuple);
    2255           0 :             return;
    2256             :         }
    2257             : 
    2258             :         /*
    2259             :          * Okay, set up the skew hashtable.
    2260             :          *
    2261             :          * skewBucket[] is an open addressing hashtable with a power of 2 size
    2262             :          * that is greater than the number of MCV values.  (This ensures there
    2263             :          * will be at least one null entry, so searches will always
    2264             :          * terminate.)
    2265             :          *
    2266             :          * Note: this code could fail if mcvsToUse exceeds INT_MAX/8 or
    2267             :          * MaxAllocSize/sizeof(void *)/8, but that is not currently possible
    2268             :          * since we limit pg_statistic entries to much less than that.
    2269             :          */
    2270           4 :         nbuckets = 2;
    2271          20 :         while (nbuckets <= mcvsToUse)
    2272          12 :             nbuckets <<= 1;
    2273             :         /* use two more bits just to help avoid collisions */
    2274           4 :         nbuckets <<= 2;
    2275             : 
    2276           4 :         hashtable->skewEnabled = true;
    2277           4 :         hashtable->skewBucketLen = nbuckets;
    2278             : 
    2279             :         /*
    2280             :          * We allocate the bucket memory in the hashtable's batch context. It
    2281             :          * is only needed during the first batch, and this ensures it will be
    2282             :          * automatically removed once the first batch is done.
    2283             :          */
    2284           4 :         hashtable->skewBucket = (HashSkewBucket **)
    2285           4 :             MemoryContextAllocZero(hashtable->batchCxt,
    2286             :                                    nbuckets * sizeof(HashSkewBucket *));
    2287           4 :         hashtable->skewBucketNums = (int *)
    2288           4 :             MemoryContextAllocZero(hashtable->batchCxt,
    2289             :                                    mcvsToUse * sizeof(int));
    2290             : 
    2291           8 :         hashtable->spaceUsed += nbuckets * sizeof(HashSkewBucket *)
    2292           4 :             + mcvsToUse * sizeof(int);
    2293           8 :         hashtable->spaceUsedSkew += nbuckets * sizeof(HashSkewBucket *)
    2294           4 :             + mcvsToUse * sizeof(int);
    2295           4 :         if (hashtable->spaceUsed > hashtable->spacePeak)
    2296           4 :             hashtable->spacePeak = hashtable->spaceUsed;
    2297             : 
    2298             :         /*
    2299             :          * Create a skew bucket for each MCV hash value.
    2300             :          *
    2301             :          * Note: it is very important that we create the buckets in order of
    2302             :          * decreasing MCV frequency.  If we have to remove some buckets, they
    2303             :          * must be removed in reverse order of creation (see notes in
    2304             :          * ExecHashRemoveNextSkewBucket) and we want the least common MCVs to
    2305             :          * be removed first.
    2306             :          */
    2307           4 :         hashfunctions = hashtable->outer_hashfunctions;
    2308             : 
    2309          44 :         for (i = 0; i < mcvsToUse; i++)
    2310             :         {
    2311             :             uint32      hashvalue;
    2312             :             int         bucket;
    2313             : 
    2314          40 :             hashvalue = DatumGetUInt32(FunctionCall1Coll(&hashfunctions[0],
    2315             :                                                          hashtable->collations[0],
    2316             :                                                          sslot.values[i]));
    2317             : 
    2318             :             /*
    2319             :              * While we have not hit a hole in the hashtable and have not hit
    2320             :              * the desired bucket, we have collided with some previous hash
    2321             :              * value, so try the next bucket location.  NB: this code must
    2322             :              * match ExecHashGetSkewBucket.
    2323             :              */
    2324          40 :             bucket = hashvalue & (nbuckets - 1);
    2325          80 :             while (hashtable->skewBucket[bucket] != NULL &&
    2326           0 :                    hashtable->skewBucket[bucket]->hashvalue != hashvalue)
    2327           0 :                 bucket = (bucket + 1) & (nbuckets - 1);
    2328             : 
    2329             :             /*
    2330             :              * If we found an existing bucket with the same hashvalue, leave
    2331             :              * it alone.  It's okay for two MCVs to share a hashvalue.
    2332             :              */
    2333          40 :             if (hashtable->skewBucket[bucket] != NULL)
    2334           0 :                 continue;
    2335             : 
    2336             :             /* Okay, create a new skew bucket for this hashvalue. */
    2337          80 :             hashtable->skewBucket[bucket] = (HashSkewBucket *)
    2338          40 :                 MemoryContextAlloc(hashtable->batchCxt,
    2339             :                                    sizeof(HashSkewBucket));
    2340          40 :             hashtable->skewBucket[bucket]->hashvalue = hashvalue;
    2341          40 :             hashtable->skewBucket[bucket]->tuples = NULL;
    2342          40 :             hashtable->skewBucketNums[hashtable->nSkewBuckets] = bucket;
    2343          40 :             hashtable->nSkewBuckets++;
    2344          40 :             hashtable->spaceUsed += SKEW_BUCKET_OVERHEAD;
    2345          40 :             hashtable->spaceUsedSkew += SKEW_BUCKET_OVERHEAD;
    2346          40 :             if (hashtable->spaceUsed > hashtable->spacePeak)
    2347          40 :                 hashtable->spacePeak = hashtable->spaceUsed;
    2348             :         }
    2349             : 
    2350           4 :         free_attstatsslot(&sslot);
    2351             :     }
    2352             : 
    2353          24 :     ReleaseSysCache(statsTuple);
    2354             : }
    2355             : 
    2356             : /*
    2357             :  * ExecHashGetSkewBucket
    2358             :  *
    2359             :  *      Returns the index of the skew bucket for this hashvalue,
    2360             :  *      or INVALID_SKEW_BUCKET_NO if the hashvalue is not
    2361             :  *      associated with any active skew bucket.
    2362             :  */
    2363             : int
    2364    17514898 : ExecHashGetSkewBucket(HashJoinTable hashtable, uint32 hashvalue)
    2365             : {
    2366             :     int         bucket;
    2367             : 
    2368             :     /*
    2369             :      * Always return INVALID_SKEW_BUCKET_NO if not doing skew optimization (in
    2370             :      * particular, this happens after the initial batch is done).
    2371             :      */
    2372    17514898 :     if (!hashtable->skewEnabled)
    2373    17434898 :         return INVALID_SKEW_BUCKET_NO;
    2374             : 
    2375             :     /*
    2376             :      * Since skewBucketLen is a power of 2, we can do a modulo by ANDing.
    2377             :      */
    2378       80000 :     bucket = hashvalue & (hashtable->skewBucketLen - 1);
    2379             : 
    2380             :     /*
    2381             :      * While we have not hit a hole in the hashtable and have not hit the
    2382             :      * desired bucket, we have collided with some other hash value, so try the
    2383             :      * next bucket location.
    2384             :      */
    2385      169940 :     while (hashtable->skewBucket[bucket] != NULL &&
    2386        5456 :            hashtable->skewBucket[bucket]->hashvalue != hashvalue)
    2387        4484 :         bucket = (bucket + 1) & (hashtable->skewBucketLen - 1);
    2388             : 
    2389             :     /*
    2390             :      * Found the desired bucket?
    2391             :      */
    2392       80000 :     if (hashtable->skewBucket[bucket] != NULL)
    2393         972 :         return bucket;
    2394             : 
    2395             :     /*
    2396             :      * There must not be any hashtable entry for this hash value.
    2397             :      */
    2398       79028 :     return INVALID_SKEW_BUCKET_NO;
    2399             : }
    2400             : 
    2401             : /*
    2402             :  * ExecHashSkewTableInsert
    2403             :  *
    2404             :  *      Insert a tuple into the skew hashtable.
    2405             :  *
    2406             :  * This should generally match up with the current-batch case in
    2407             :  * ExecHashTableInsert.
    2408             :  */
    2409             : static void
    2410         172 : ExecHashSkewTableInsert(HashJoinTable hashtable,
    2411             :                         TupleTableSlot *slot,
    2412             :                         uint32 hashvalue,
    2413             :                         int bucketNumber)
    2414             : {
    2415             :     bool        shouldFree;
    2416         172 :     MinimalTuple tuple = ExecFetchSlotMinimalTuple(slot, &shouldFree);
    2417             :     HashJoinTuple hashTuple;
    2418             :     int         hashTupleSize;
    2419             : 
    2420             :     /* Create the HashJoinTuple */
    2421         172 :     hashTupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
    2422         172 :     hashTuple = (HashJoinTuple) MemoryContextAlloc(hashtable->batchCxt,
    2423             :                                                    hashTupleSize);
    2424         172 :     hashTuple->hashvalue = hashvalue;
    2425         172 :     memcpy(HJTUPLE_MINTUPLE(hashTuple), tuple, tuple->t_len);
    2426         172 :     HeapTupleHeaderClearMatch(HJTUPLE_MINTUPLE(hashTuple));
    2427             : 
    2428             :     /* Push it onto the front of the skew bucket's list */
    2429         172 :     hashTuple->next.unshared = hashtable->skewBucket[bucketNumber]->tuples;
    2430         172 :     hashtable->skewBucket[bucketNumber]->tuples = hashTuple;
    2431             :     Assert(hashTuple != hashTuple->next.unshared);
    2432             : 
    2433             :     /* Account for space used, and back off if we've used too much */
    2434         172 :     hashtable->spaceUsed += hashTupleSize;
    2435         172 :     hashtable->spaceUsedSkew += hashTupleSize;
    2436         172 :     if (hashtable->spaceUsed > hashtable->spacePeak)
    2437         128 :         hashtable->spacePeak = hashtable->spaceUsed;
    2438         376 :     while (hashtable->spaceUsedSkew > hashtable->spaceAllowedSkew)
    2439          32 :         ExecHashRemoveNextSkewBucket(hashtable);
    2440             : 
    2441             :     /* Check we are not over the total spaceAllowed, either */
    2442         172 :     if (hashtable->spaceUsed > hashtable->spaceAllowed)
    2443           0 :         ExecHashIncreaseNumBatches(hashtable);
    2444             : 
    2445         172 :     if (shouldFree)
    2446         172 :         heap_free_minimal_tuple(tuple);
    2447         172 : }
    2448             : 
    2449             : /*
    2450             :  *      ExecHashRemoveNextSkewBucket
    2451             :  *
    2452             :  *      Remove the least valuable skew bucket by pushing its tuples into
    2453             :  *      the main hash table.
    2454             :  */
    2455             : static void
    2456          32 : ExecHashRemoveNextSkewBucket(HashJoinTable hashtable)
    2457             : {
    2458             :     int         bucketToRemove;
    2459             :     HashSkewBucket *bucket;
    2460             :     uint32      hashvalue;
    2461             :     int         bucketno;
    2462             :     int         batchno;
    2463             :     HashJoinTuple hashTuple;
    2464             : 
    2465             :     /* Locate the bucket to remove */
    2466          32 :     bucketToRemove = hashtable->skewBucketNums[hashtable->nSkewBuckets - 1];
    2467          32 :     bucket = hashtable->skewBucket[bucketToRemove];
    2468             : 
    2469             :     /*
    2470             :      * Calculate which bucket and batch the tuples belong to in the main
    2471             :      * hashtable.  They all have the same hash value, so it's the same for all
    2472             :      * of them.  Also note that it's not possible for nbatch to increase while
    2473             :      * we are processing the tuples.
    2474             :      */
    2475          32 :     hashvalue = bucket->hashvalue;
    2476          32 :     ExecHashGetBucketAndBatch(hashtable, hashvalue, &bucketno, &batchno);
    2477             : 
    2478             :     /* Process all tuples in the bucket */
    2479          32 :     hashTuple = bucket->tuples;
    2480         156 :     while (hashTuple != NULL)
    2481             :     {
    2482          92 :         HashJoinTuple nextHashTuple = hashTuple->next.unshared;
    2483             :         MinimalTuple tuple;
    2484             :         Size        tupleSize;
    2485             : 
    2486             :         /*
    2487             :          * This code must agree with ExecHashTableInsert.  We do not use
    2488             :          * ExecHashTableInsert directly as ExecHashTableInsert expects a
    2489             :          * TupleTableSlot while we already have HashJoinTuples.
    2490             :          */
    2491          92 :         tuple = HJTUPLE_MINTUPLE(hashTuple);
    2492          92 :         tupleSize = HJTUPLE_OVERHEAD + tuple->t_len;
    2493             : 
    2494             :         /* Decide whether to put the tuple in the hash table or a temp file */
    2495          92 :         if (batchno == hashtable->curbatch)
    2496             :         {
    2497             :             /* Move the tuple to the main hash table */
    2498             :             HashJoinTuple copyTuple;
    2499             : 
    2500             :             /*
    2501             :              * We must copy the tuple into the dense storage, else it will not
    2502             :              * be found by, eg, ExecHashIncreaseNumBatches.
    2503             :              */
    2504           8 :             copyTuple = (HashJoinTuple) dense_alloc(hashtable, tupleSize);
    2505           8 :             memcpy(copyTuple, hashTuple, tupleSize);
    2506           8 :             pfree(hashTuple);
    2507             : 
    2508           8 :             copyTuple->next.unshared = hashtable->buckets.unshared[bucketno];
    2509           8 :             hashtable->buckets.unshared[bucketno] = copyTuple;
    2510             : 
    2511             :             /* We have reduced skew space, but overall space doesn't change */
    2512           8 :             hashtable->spaceUsedSkew -= tupleSize;
    2513             :         }
    2514             :         else
    2515             :         {
    2516             :             /* Put the tuple into a temp file for later batches */
    2517             :             Assert(batchno > hashtable->curbatch);
    2518          84 :             ExecHashJoinSaveTuple(tuple, hashvalue,
    2519          84 :                                   &hashtable->innerBatchFile[batchno]);
    2520          84 :             pfree(hashTuple);
    2521          84 :             hashtable->spaceUsed -= tupleSize;
    2522          84 :             hashtable->spaceUsedSkew -= tupleSize;
    2523             :         }
    2524             : 
    2525          92 :         hashTuple = nextHashTuple;
    2526             : 
    2527             :         /* allow this loop to be cancellable */
    2528          92 :         CHECK_FOR_INTERRUPTS();
    2529             :     }
    2530             : 
    2531             :     /*
    2532             :      * Free the bucket struct itself and reset the hashtable entry to NULL.
    2533             :      *
    2534             :      * NOTE: this is not nearly as simple as it looks on the surface, because
    2535             :      * of the possibility of collisions in the hashtable.  Suppose that hash
    2536             :      * values A and B collide at a particular hashtable entry, and that A was
    2537             :      * entered first so B gets shifted to a different table entry.  If we were
    2538             :      * to remove A first then ExecHashGetSkewBucket would mistakenly start
    2539             :      * reporting that B is not in the hashtable, because it would hit the NULL
    2540             :      * before finding B.  However, we always remove entries in the reverse
    2541             :      * order of creation, so this failure cannot happen.
    2542             :      */
    2543          32 :     hashtable->skewBucket[bucketToRemove] = NULL;
    2544          32 :     hashtable->nSkewBuckets--;
    2545          32 :     pfree(bucket);
    2546          32 :     hashtable->spaceUsed -= SKEW_BUCKET_OVERHEAD;
    2547          32 :     hashtable->spaceUsedSkew -= SKEW_BUCKET_OVERHEAD;
    2548             : 
    2549             :     /*
    2550             :      * If we have removed all skew buckets then give up on skew optimization.
    2551             :      * Release the arrays since they aren't useful any more.
    2552             :      */
    2553          32 :     if (hashtable->nSkewBuckets == 0)
    2554             :     {
    2555           0 :         hashtable->skewEnabled = false;
    2556           0 :         pfree(hashtable->skewBucket);
    2557           0 :         pfree(hashtable->skewBucketNums);
    2558           0 :         hashtable->skewBucket = NULL;
    2559           0 :         hashtable->skewBucketNums = NULL;
    2560           0 :         hashtable->spaceUsed -= hashtable->spaceUsedSkew;
    2561           0 :         hashtable->spaceUsedSkew = 0;
    2562             :     }
    2563          32 : }
    2564             : 
    2565             : /*
    2566             :  * Reserve space in the DSM segment for instrumentation data.
    2567             :  */
    2568             : void
    2569         112 : ExecHashEstimate(HashState *node, ParallelContext *pcxt)
    2570             : {
    2571             :     size_t      size;
    2572             : 
    2573             :     /* don't need this if not instrumenting or no workers */
    2574         112 :     if (!node->ps.instrument || pcxt->nworkers == 0)
    2575          56 :         return;
    2576             : 
    2577          56 :     size = mul_size(pcxt->nworkers, sizeof(HashInstrumentation));
    2578          56 :     size = add_size(size, offsetof(SharedHashInfo, hinstrument));
    2579          56 :     shm_toc_estimate_chunk(&pcxt->estimator, size);
    2580          56 :     shm_toc_estimate_keys(&pcxt->estimator, 1);
    2581             : }
    2582             : 
    2583             : /*
    2584             :  * Set up a space in the DSM for all workers to record instrumentation data
    2585             :  * about their hash table.
    2586             :  */
    2587             : void
    2588         112 : ExecHashInitializeDSM(HashState *node, ParallelContext *pcxt)
    2589             : {
    2590             :     size_t      size;
    2591             : 
    2592             :     /* don't need this if not instrumenting or no workers */
    2593         112 :     if (!node->ps.instrument || pcxt->nworkers == 0)
    2594          56 :         return;
    2595             : 
    2596          56 :     size = offsetof(SharedHashInfo, hinstrument) +
    2597          56 :         pcxt->nworkers * sizeof(HashInstrumentation);
    2598          56 :     node->shared_info = (SharedHashInfo *) shm_toc_allocate(pcxt->toc, size);
    2599          56 :     memset(node->shared_info, 0, size);
    2600          56 :     node->shared_info->num_workers = pcxt->nworkers;
    2601          56 :     shm_toc_insert(pcxt->toc, node->ps.plan->plan_node_id,
    2602          56 :                    node->shared_info);
    2603             : }
    2604             : 
    2605             : /*
    2606             :  * Locate the DSM space for hash table instrumentation data that we'll write
    2607             :  * to at shutdown time.
    2608             :  */
    2609             : void
    2610         340 : ExecHashInitializeWorker(HashState *node, ParallelWorkerContext *pwcxt)
    2611             : {
    2612             :     SharedHashInfo *shared_info;
    2613             : 
    2614             :     /* don't need this if not instrumenting */
    2615         340 :     if (!node->ps.instrument)
    2616         172 :         return;
    2617             : 
    2618         168 :     shared_info = (SharedHashInfo *)
    2619         168 :         shm_toc_lookup(pwcxt->toc, node->ps.plan->plan_node_id, false);
    2620         168 :     node->hinstrument = &shared_info->hinstrument[ParallelWorkerNumber];
    2621             : }
    2622             : 
    2623             : /*
    2624             :  * Copy instrumentation data from this worker's hash table (if it built one)
    2625             :  * to DSM memory so the leader can retrieve it.  This must be done in an
    2626             :  * ExecShutdownHash() rather than ExecEndHash() because the latter runs after
    2627             :  * we've detached from the DSM segment.
    2628             :  */
    2629             : void
    2630       26012 : ExecShutdownHash(HashState *node)
    2631             : {
    2632       26012 :     if (node->hinstrument && node->hashtable)
    2633         160 :         ExecHashGetInstrumentation(node->hinstrument, node->hashtable);
    2634       26012 : }
    2635             : 
    2636             : /*
    2637             :  * Retrieve instrumentation data from workers before the DSM segment is
    2638             :  * detached, so that EXPLAIN can access it.
    2639             :  */
    2640             : void
    2641          56 : ExecHashRetrieveInstrumentation(HashState *node)
    2642             : {
    2643          56 :     SharedHashInfo *shared_info = node->shared_info;
    2644             :     size_t      size;
    2645             : 
    2646          56 :     if (shared_info == NULL)
    2647           0 :         return;
    2648             : 
    2649             :     /* Replace node->shared_info with a copy in backend-local memory. */
    2650          56 :     size = offsetof(SharedHashInfo, hinstrument) +
    2651          56 :         shared_info->num_workers * sizeof(HashInstrumentation);
    2652          56 :     node->shared_info = palloc(size);
    2653          56 :     memcpy(node->shared_info, shared_info, size);
    2654             : }
    2655             : 
    2656             : /*
    2657             :  * Copy the instrumentation data from 'hashtable' into a HashInstrumentation
    2658             :  * struct.
    2659             :  */
    2660             : void
    2661         212 : ExecHashGetInstrumentation(HashInstrumentation *instrument,
    2662             :                            HashJoinTable hashtable)
    2663             : {
    2664         212 :     instrument->nbuckets = hashtable->nbuckets;
    2665         212 :     instrument->nbuckets_original = hashtable->nbuckets_original;
    2666         212 :     instrument->nbatch = hashtable->nbatch;
    2667         212 :     instrument->nbatch_original = hashtable->nbatch_original;
    2668         212 :     instrument->space_peak = hashtable->spacePeak;
    2669         212 : }
    2670             : 
    2671             : /*
    2672             :  * Allocate 'size' bytes from the currently active HashMemoryChunk
    2673             :  */
    2674             : static void *
    2675     7234304 : dense_alloc(HashJoinTable hashtable, Size size)
    2676             : {
    2677             :     HashMemoryChunk newChunk;
    2678             :     char       *ptr;
    2679             : 
    2680             :     /* just in case the size is not already aligned properly */
    2681     7234304 :     size = MAXALIGN(size);
    2682             : 
    2683             :     /*
    2684             :      * If tuple size is larger than threshold, allocate a separate chunk.
    2685             :      */
    2686     7234304 :     if (size > HASH_CHUNK_THRESHOLD)
    2687             :     {
    2688             :         /* allocate new chunk and put it at the beginning of the list */
    2689           0 :         newChunk = (HashMemoryChunk) MemoryContextAlloc(hashtable->batchCxt,
    2690             :                                                         HASH_CHUNK_HEADER_SIZE + size);
    2691           0 :         newChunk->maxlen = size;
    2692           0 :         newChunk->used = size;
    2693           0 :         newChunk->ntuples = 1;
    2694             : 
    2695             :         /*
    2696             :          * Add this chunk to the list after the first existing chunk, so that
    2697             :          * we don't lose the remaining space in the "current" chunk.
    2698             :          */
    2699           0 :         if (hashtable->chunks != NULL)
    2700             :         {
    2701           0 :             newChunk->next = hashtable->chunks->next;
    2702           0 :             hashtable->chunks->next.unshared = newChunk;
    2703             :         }
    2704             :         else
    2705             :         {
    2706           0 :             newChunk->next.unshared = hashtable->chunks;
    2707           0 :             hashtable->chunks = newChunk;
    2708             :         }
    2709             : 
    2710           0 :         return HASH_CHUNK_DATA(newChunk);
    2711             :     }
    2712             : 
    2713             :     /*
    2714             :      * See if we have enough space for it in the current chunk (if any). If
    2715             :      * not, allocate a fresh chunk.
    2716             :      */
    2717    14218246 :     if ((hashtable->chunks == NULL) ||
    2718     6983942 :         (hashtable->chunks->maxlen - hashtable->chunks->used) < size)
    2719             :     {
    2720             :         /* allocate new chunk and put it at the beginning of the list */
    2721      259166 :         newChunk = (HashMemoryChunk) MemoryContextAlloc(hashtable->batchCxt,
    2722             :                                                         HASH_CHUNK_HEADER_SIZE + HASH_CHUNK_SIZE);
    2723             : 
    2724      259166 :         newChunk->maxlen = HASH_CHUNK_SIZE;
    2725      259166 :         newChunk->used = size;
    2726      259166 :         newChunk->ntuples = 1;
    2727             : 
    2728      259166 :         newChunk->next.unshared = hashtable->chunks;
    2729      259166 :         hashtable->chunks = newChunk;
    2730             : 
    2731      259166 :         return HASH_CHUNK_DATA(newChunk);
    2732             :     }
    2733             : 
    2734             :     /* There is enough space in the current chunk, let's add the tuple */
    2735     6975138 :     ptr = HASH_CHUNK_DATA(hashtable->chunks) + hashtable->chunks->used;
    2736     6975138 :     hashtable->chunks->used += size;
    2737     6975138 :     hashtable->chunks->ntuples += 1;
    2738             : 
    2739             :     /* return pointer to the start of the tuple memory */
    2740     6975138 :     return ptr;
    2741             : }
    2742             : 
    2743             : /*
    2744             :  * Allocate space for a tuple in shared dense storage.  This is equivalent to
    2745             :  * dense_alloc but for Parallel Hash using shared memory.
    2746             :  *
    2747             :  * While loading a tuple into shared memory, we might run out of memory and
    2748             :  * decide to repartition, or determine that the load factor is too high and
    2749             :  * decide to expand the bucket array, or discover that another participant has
    2750             :  * commanded us to help do that.  Return NULL if number of buckets or batches
    2751             :  * has changed, indicating that the caller must retry (considering the
    2752             :  * possibility that the tuple no longer belongs in the same batch).
    2753             :  */
    2754             : static HashJoinTuple
    2755     1347316 : ExecParallelHashTupleAlloc(HashJoinTable hashtable, size_t size,
    2756             :                            dsa_pointer *shared)
    2757             : {
    2758     1347316 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    2759             :     dsa_pointer chunk_shared;
    2760             :     HashMemoryChunk chunk;
    2761             :     Size        chunk_size;
    2762             :     HashJoinTuple result;
    2763     1347316 :     int         curbatch = hashtable->curbatch;
    2764             : 
    2765     1347316 :     size = MAXALIGN(size);
    2766             : 
    2767             :     /*
    2768             :      * Fast path: if there is enough space in this backend's current chunk,
    2769             :      * then we can allocate without any locking.
    2770             :      */
    2771     1347316 :     chunk = hashtable->current_chunk;
    2772     1347316 :     if (chunk != NULL &&
    2773     1346708 :         size <= HASH_CHUNK_THRESHOLD &&
    2774     1346708 :         chunk->maxlen - chunk->used >= size)
    2775             :     {
    2776             : 
    2777     1345146 :         chunk_shared = hashtable->current_chunk_shared;
    2778             :         Assert(chunk == dsa_get_address(hashtable->area, chunk_shared));
    2779     1345146 :         *shared = chunk_shared + HASH_CHUNK_HEADER_SIZE + chunk->used;
    2780     1345146 :         result = (HashJoinTuple) (HASH_CHUNK_DATA(chunk) + chunk->used);
    2781     1345146 :         chunk->used += size;
    2782             : 
    2783             :         Assert(chunk->used <= chunk->maxlen);
    2784             :         Assert(result == dsa_get_address(hashtable->area, *shared));
    2785             : 
    2786     1345146 :         return result;
    2787             :     }
    2788             : 
    2789             :     /* Slow path: try to allocate a new chunk. */
    2790        2170 :     LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
    2791             : 
    2792             :     /*
    2793             :      * Check if we need to help increase the number of buckets or batches.
    2794             :      */
    2795        4316 :     if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
    2796        2146 :         pstate->growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
    2797             :     {
    2798         120 :         ParallelHashGrowth growth = pstate->growth;
    2799             : 
    2800         120 :         hashtable->current_chunk = NULL;
    2801         120 :         LWLockRelease(&pstate->lock);
    2802             : 
    2803             :         /* Another participant has commanded us to help grow. */
    2804         120 :         if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
    2805          24 :             ExecParallelHashIncreaseNumBatches(hashtable);
    2806          96 :         else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
    2807          96 :             ExecParallelHashIncreaseNumBuckets(hashtable);
    2808             : 
    2809             :         /* The caller must retry. */
    2810         120 :         return NULL;
    2811             :     }
    2812             : 
    2813             :     /* Oversized tuples get their own chunk. */
    2814        2050 :     if (size > HASH_CHUNK_THRESHOLD)
    2815          32 :         chunk_size = size + HASH_CHUNK_HEADER_SIZE;
    2816             :     else
    2817        2018 :         chunk_size = HASH_CHUNK_SIZE;
    2818             : 
    2819             :     /* Check if it's time to grow batches or buckets. */
    2820        2050 :     if (pstate->growth != PHJ_GROWTH_DISABLED)
    2821             :     {
    2822             :         Assert(curbatch == 0);
    2823             :         Assert(BarrierPhase(&pstate->build_barrier) == PHJ_BUILD_HASHING_INNER);
    2824             : 
    2825             :         /*
    2826             :          * Check if our space limit would be exceeded.  To avoid choking on
    2827             :          * very large tuples or very low work_mem setting, we'll always allow
    2828             :          * each backend to allocate at least one chunk.
    2829             :          */
    2830        1752 :         if (hashtable->batches[0].at_least_one_chunk &&
    2831         754 :             hashtable->batches[0].shared->size +
    2832         754 :             chunk_size > pstate->space_allowed)
    2833             :         {
    2834          24 :             pstate->growth = PHJ_GROWTH_NEED_MORE_BATCHES;
    2835          24 :             hashtable->batches[0].shared->space_exhausted = true;
    2836          24 :             LWLockRelease(&pstate->lock);
    2837             : 
    2838          24 :             return NULL;
    2839             :         }
    2840             : 
    2841             :         /* Check if our load factor limit would be exceeded. */
    2842         974 :         if (hashtable->nbatch == 1)
    2843             :         {
    2844         834 :             hashtable->batches[0].shared->ntuples += hashtable->batches[0].ntuples;
    2845         834 :             hashtable->batches[0].ntuples = 0;
    2846             :             /* Guard against integer overflow and alloc size overflow */
    2847        1668 :             if (hashtable->batches[0].shared->ntuples + 1 >
    2848         906 :                 hashtable->nbuckets * NTUP_PER_BUCKET &&
    2849         144 :                 hashtable->nbuckets < (INT_MAX / 2) &&
    2850          72 :                 hashtable->nbuckets * 2 <=
    2851             :                 MaxAllocSize / sizeof(dsa_pointer_atomic))
    2852             :             {
    2853          72 :                 pstate->growth = PHJ_GROWTH_NEED_MORE_BUCKETS;
    2854          72 :                 LWLockRelease(&pstate->lock);
    2855             : 
    2856          72 :                 return NULL;
    2857             :             }
    2858             :         }
    2859             :     }
    2860             : 
    2861             :     /* We are cleared to allocate a new chunk. */
    2862        1954 :     chunk_shared = dsa_allocate(hashtable->area, chunk_size);
    2863        1954 :     hashtable->batches[curbatch].shared->size += chunk_size;
    2864        1954 :     hashtable->batches[curbatch].at_least_one_chunk = true;
    2865             : 
    2866             :     /* Set up the chunk. */
    2867        1954 :     chunk = (HashMemoryChunk) dsa_get_address(hashtable->area, chunk_shared);
    2868        1954 :     *shared = chunk_shared + HASH_CHUNK_HEADER_SIZE;
    2869        1954 :     chunk->maxlen = chunk_size - HASH_CHUNK_HEADER_SIZE;
    2870        1954 :     chunk->used = size;
    2871             : 
    2872             :     /*
    2873             :      * Push it onto the list of chunks, so that it can be found if we need to
    2874             :      * increase the number of buckets or batches (batch 0 only) and later for
    2875             :      * freeing the memory (all batches).
    2876             :      */
    2877        1954 :     chunk->next.shared = hashtable->batches[curbatch].shared->chunks;
    2878        1954 :     hashtable->batches[curbatch].shared->chunks = chunk_shared;
    2879             : 
    2880        1954 :     if (size <= HASH_CHUNK_THRESHOLD)
    2881             :     {
    2882             :         /*
    2883             :          * Make this the current chunk so that we can use the fast path to
    2884             :          * fill the rest of it up in future calls.
    2885             :          */
    2886        1930 :         hashtable->current_chunk = chunk;
    2887        1930 :         hashtable->current_chunk_shared = chunk_shared;
    2888             :     }
    2889        1954 :     LWLockRelease(&pstate->lock);
    2890             : 
    2891             :     Assert(HASH_CHUNK_DATA(chunk) == dsa_get_address(hashtable->area, *shared));
    2892        1954 :     result = (HashJoinTuple) HASH_CHUNK_DATA(chunk);
    2893             : 
    2894        1954 :     return result;
    2895             : }
    2896             : 
    2897             : /*
    2898             :  * One backend needs to set up the shared batch state including tuplestores.
    2899             :  * Other backends will ensure they have correctly configured accessors by
    2900             :  * called ExecParallelHashEnsureBatchAccessors().
    2901             :  */
    2902             : static void
    2903         128 : ExecParallelHashJoinSetUpBatches(HashJoinTable hashtable, int nbatch)
    2904             : {
    2905         128 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    2906             :     ParallelHashJoinBatch *batches;
    2907             :     MemoryContext oldcxt;
    2908             :     int         i;
    2909             : 
    2910             :     Assert(hashtable->batches == NULL);
    2911             : 
    2912             :     /* Allocate space. */
    2913         128 :     pstate->batches =
    2914         128 :         dsa_allocate0(hashtable->area,
    2915             :                       EstimateParallelHashJoinBatch(hashtable) * nbatch);
    2916         128 :     pstate->nbatch = nbatch;
    2917         128 :     batches = dsa_get_address(hashtable->area, pstate->batches);
    2918             : 
    2919             :     /* Use hash join memory context. */
    2920         128 :     oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
    2921             : 
    2922             :     /* Allocate this backend's accessor array. */
    2923         128 :     hashtable->nbatch = nbatch;
    2924         128 :     hashtable->batches = (ParallelHashJoinBatchAccessor *)
    2925         128 :         palloc0(sizeof(ParallelHashJoinBatchAccessor) * hashtable->nbatch);
    2926             : 
    2927             :     /* Set up the shared state, tuplestores and backend-local accessors. */
    2928         640 :     for (i = 0; i < hashtable->nbatch; ++i)
    2929             :     {
    2930         512 :         ParallelHashJoinBatchAccessor *accessor = &hashtable->batches[i];
    2931         512 :         ParallelHashJoinBatch *shared = NthParallelHashJoinBatch(batches, i);
    2932             :         char        name[MAXPGPATH];
    2933             : 
    2934             :         /*
    2935             :          * All members of shared were zero-initialized.  We just need to set
    2936             :          * up the Barrier.
    2937             :          */
    2938         512 :         BarrierInit(&shared->batch_barrier, 0);
    2939         512 :         if (i == 0)
    2940             :         {
    2941             :             /* Batch 0 doesn't need to be loaded. */
    2942         128 :             BarrierAttach(&shared->batch_barrier);
    2943         640 :             while (BarrierPhase(&shared->batch_barrier) < PHJ_BATCH_PROBING)
    2944         384 :                 BarrierArriveAndWait(&shared->batch_barrier, 0);
    2945         128 :             BarrierDetach(&shared->batch_barrier);
    2946             :         }
    2947             : 
    2948             :         /* Initialize accessor state.  All members were zero-initialized. */
    2949         512 :         accessor->shared = shared;
    2950             : 
    2951             :         /* Initialize the shared tuplestores. */
    2952         512 :         snprintf(name, sizeof(name), "i%dof%d", i, hashtable->nbatch);
    2953         512 :         accessor->inner_tuples =
    2954         512 :             sts_initialize(ParallelHashJoinBatchInner(shared),
    2955             :                            pstate->nparticipants,
    2956             :                            ParallelWorkerNumber + 1,
    2957             :                            sizeof(uint32),
    2958             :                            SHARED_TUPLESTORE_SINGLE_PASS,
    2959             :                            &pstate->fileset,
    2960             :                            name);
    2961         512 :         snprintf(name, sizeof(name), "o%dof%d", i, hashtable->nbatch);
    2962         512 :         accessor->outer_tuples =
    2963         512 :             sts_initialize(ParallelHashJoinBatchOuter(shared,
    2964             :                                                       pstate->nparticipants),
    2965             :                            pstate->nparticipants,
    2966             :                            ParallelWorkerNumber + 1,
    2967             :                            sizeof(uint32),
    2968             :                            SHARED_TUPLESTORE_SINGLE_PASS,
    2969             :                            &pstate->fileset,
    2970             :                            name);
    2971             :     }
    2972             : 
    2973         128 :     MemoryContextSwitchTo(oldcxt);
    2974         128 : }
    2975             : 
    2976             : /*
    2977             :  * Free the current set of ParallelHashJoinBatchAccessor objects.
    2978             :  */
    2979             : static void
    2980          32 : ExecParallelHashCloseBatchAccessors(HashJoinTable hashtable)
    2981             : {
    2982             :     int         i;
    2983             : 
    2984          88 :     for (i = 0; i < hashtable->nbatch; ++i)
    2985             :     {
    2986             :         /* Make sure no files are left open. */
    2987          56 :         sts_end_write(hashtable->batches[i].inner_tuples);
    2988          56 :         sts_end_write(hashtable->batches[i].outer_tuples);
    2989          56 :         sts_end_parallel_scan(hashtable->batches[i].inner_tuples);
    2990          56 :         sts_end_parallel_scan(hashtable->batches[i].outer_tuples);
    2991             :     }
    2992          32 :     pfree(hashtable->batches);
    2993          32 :     hashtable->batches = NULL;
    2994          32 : }
    2995             : 
    2996             : /*
    2997             :  * Make sure this backend has up-to-date accessors for the current set of
    2998             :  * batches.
    2999             :  */
    3000             : static void
    3001         542 : ExecParallelHashEnsureBatchAccessors(HashJoinTable hashtable)
    3002             : {
    3003         542 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    3004             :     ParallelHashJoinBatch *batches;
    3005             :     MemoryContext oldcxt;
    3006             :     int         i;
    3007             : 
    3008         542 :     if (hashtable->batches != NULL)
    3009             :     {
    3010         414 :         if (hashtable->nbatch == pstate->nbatch)
    3011         414 :             return;
    3012           0 :         ExecParallelHashCloseBatchAccessors(hashtable);
    3013             :     }
    3014             : 
    3015             :     /*
    3016             :      * It's possible for a backend to start up very late so that the whole
    3017             :      * join is finished and the shm state for tracking batches has already
    3018             :      * been freed by ExecHashTableDetach().  In that case we'll just leave
    3019             :      * hashtable->batches as NULL so that ExecParallelHashJoinNewBatch() gives
    3020             :      * up early.
    3021             :      */
    3022         128 :     if (!DsaPointerIsValid(pstate->batches))
    3023           0 :         return;
    3024             : 
    3025             :     /* Use hash join memory context. */
    3026         128 :     oldcxt = MemoryContextSwitchTo(hashtable->hashCxt);
    3027             : 
    3028             :     /* Allocate this backend's accessor array. */
    3029         128 :     hashtable->nbatch = pstate->nbatch;
    3030         128 :     hashtable->batches = (ParallelHashJoinBatchAccessor *)
    3031         128 :         palloc0(sizeof(ParallelHashJoinBatchAccessor) * hashtable->nbatch);
    3032             : 
    3033             :     /* Find the base of the pseudo-array of ParallelHashJoinBatch objects. */
    3034         128 :     batches = (ParallelHashJoinBatch *)
    3035         128 :         dsa_get_address(hashtable->area, pstate->batches);
    3036             : 
    3037             :     /* Set up the accessor array and attach to the tuplestores. */
    3038         728 :     for (i = 0; i < hashtable->nbatch; ++i)
    3039             :     {
    3040         600 :         ParallelHashJoinBatchAccessor *accessor = &hashtable->batches[i];
    3041         600 :         ParallelHashJoinBatch *shared = NthParallelHashJoinBatch(batches, i);
    3042             : 
    3043         600 :         accessor->shared = shared;
    3044         600 :         accessor->preallocated = 0;
    3045         600 :         accessor->done = false;
    3046         600 :         accessor->inner_tuples =
    3047         600 :             sts_attach(ParallelHashJoinBatchInner(shared),
    3048             :                        ParallelWorkerNumber + 1,
    3049             :                        &pstate->fileset);
    3050         600 :         accessor->outer_tuples =
    3051         600 :             sts_attach(ParallelHashJoinBatchOuter(shared,
    3052             :                                                   pstate->nparticipants),
    3053             :                        ParallelWorkerNumber + 1,
    3054             :                        &pstate->fileset);
    3055             :     }
    3056             : 
    3057         128 :     MemoryContextSwitchTo(oldcxt);
    3058             : }
    3059             : 
    3060             : /*
    3061             :  * Allocate an empty shared memory hash table for a given batch.
    3062             :  */
    3063             : void
    3064         456 : ExecParallelHashTableAlloc(HashJoinTable hashtable, int batchno)
    3065             : {
    3066         456 :     ParallelHashJoinBatch *batch = hashtable->batches[batchno].shared;
    3067             :     dsa_pointer_atomic *buckets;
    3068         456 :     int         nbuckets = hashtable->parallel_state->nbuckets;
    3069             :     int         i;
    3070             : 
    3071         456 :     batch->buckets =
    3072         456 :         dsa_allocate(hashtable->area, sizeof(dsa_pointer_atomic) * nbuckets);
    3073         456 :     buckets = (dsa_pointer_atomic *)
    3074         456 :         dsa_get_address(hashtable->area, batch->buckets);
    3075     1667528 :     for (i = 0; i < nbuckets; ++i)
    3076     1667072 :         dsa_pointer_atomic_init(&buckets[i], InvalidDsaPointer);
    3077         456 : }
    3078             : 
    3079             : /*
    3080             :  * If we are currently attached to a shared hash join batch, detach.  If we
    3081             :  * are last to detach, clean up.
    3082             :  */
    3083             : void
    3084       17408 : ExecHashTableDetachBatch(HashJoinTable hashtable)
    3085             : {
    3086       18176 :     if (hashtable->parallel_state != NULL &&
    3087         768 :         hashtable->curbatch >= 0)
    3088             :     {
    3089         544 :         int         curbatch = hashtable->curbatch;
    3090         544 :         ParallelHashJoinBatch *batch = hashtable->batches[curbatch].shared;
    3091             : 
    3092             :         /* Make sure any temporary files are closed. */
    3093         544 :         sts_end_parallel_scan(hashtable->batches[curbatch].inner_tuples);
    3094         544 :         sts_end_parallel_scan(hashtable->batches[curbatch].outer_tuples);
    3095             : 
    3096             :         /* Detach from the batch we were last working on. */
    3097         544 :         if (BarrierArriveAndDetach(&batch->batch_barrier))
    3098             :         {
    3099             :             /*
    3100             :              * Technically we shouldn't access the barrier because we're no
    3101             :              * longer attached, but since there is no way it's moving after
    3102             :              * this point it seems safe to make the following assertion.
    3103             :              */
    3104             :             Assert(BarrierPhase(&batch->batch_barrier) == PHJ_BATCH_DONE);
    3105             : 
    3106             :             /* Free shared chunks and buckets. */
    3107        2674 :             while (DsaPointerIsValid(batch->chunks))
    3108             :             {
    3109        1762 :                 HashMemoryChunk chunk =
    3110        1762 :                 dsa_get_address(hashtable->area, batch->chunks);
    3111        1762 :                 dsa_pointer next = chunk->next.shared;
    3112             : 
    3113        1762 :                 dsa_free(hashtable->area, batch->chunks);
    3114        1762 :                 batch->chunks = next;
    3115             :             }
    3116         456 :             if (DsaPointerIsValid(batch->buckets))
    3117             :             {
    3118         456 :                 dsa_free(hashtable->area, batch->buckets);
    3119         456 :                 batch->buckets = InvalidDsaPointer;
    3120             :             }
    3121             :         }
    3122             : 
    3123             :         /*
    3124             :          * Track the largest batch we've been attached to.  Though each
    3125             :          * backend might see a different subset of batches, explain.c will
    3126             :          * scan the results from all backends to find the largest value.
    3127             :          */
    3128         544 :         hashtable->spacePeak =
    3129         544 :             Max(hashtable->spacePeak,
    3130             :                 batch->size + sizeof(dsa_pointer_atomic) * hashtable->nbuckets);
    3131             : 
    3132             :         /* Remember that we are not attached to a batch. */
    3133         544 :         hashtable->curbatch = -1;
    3134             :     }
    3135       17408 : }
    3136             : 
    3137             : /*
    3138             :  * Detach from all shared resources.  If we are last to detach, clean up.
    3139             :  */
    3140             : void
    3141       16864 : ExecHashTableDetach(HashJoinTable hashtable)
    3142             : {
    3143       16864 :     if (hashtable->parallel_state)
    3144             :     {
    3145         224 :         ParallelHashJoinState *pstate = hashtable->parallel_state;
    3146             :         int         i;
    3147             : 
    3148             :         /* Make sure any temporary files are closed. */
    3149         224 :         if (hashtable->batches)
    3150             :         {
    3151        1280 :             for (i = 0; i < hashtable->nbatch; ++i)
    3152             :             {
    3153        1056 :                 sts_end_write(hashtable->batches[i].inner_tuples);
    3154        1056 :                 sts_end_write(hashtable->batches[i].outer_tuples);
    3155        1056 :                 sts_end_parallel_scan(hashtable->batches[i].inner_tuples);
    3156        1056 :                 sts_end_parallel_scan(hashtable->batches[i].outer_tuples);
    3157             :             }
    3158             :         }
    3159             : 
    3160             :         /* If we're last to detach, clean up shared memory. */
    3161         224 :         if (BarrierDetach(&pstate->build_barrier))
    3162             :         {
    3163          96 :             if (DsaPointerIsValid(pstate->batches))
    3164             :             {
    3165          96 :                 dsa_free(hashtable->area, pstate->batches);
    3166          96 :                 pstate->batches = InvalidDsaPointer;
    3167             :             }
    3168             :         }
    3169             : 
    3170         224 :         hashtable->parallel_state = NULL;
    3171             :     }
    3172       16864 : }
    3173             : 
    3174             : /*
    3175             :  * Get the first tuple in a given bucket identified by number.
    3176             :  */
    3177             : static inline HashJoinTuple
    3178     1200016 : ExecParallelHashFirstTuple(HashJoinTable hashtable, int bucketno)
    3179             : {
    3180             :     HashJoinTuple tuple;
    3181             :     dsa_pointer p;
    3182             : 
    3183             :     Assert(hashtable->parallel_state);
    3184     1200016 :     p = dsa_pointer_atomic_read(&hashtable->buckets.shared[bucketno]);
    3185     1200016 :     tuple = (HashJoinTuple) dsa_get_address(hashtable->area, p);
    3186             : 
    3187     1200016 :     return tuple;
    3188             : }
    3189             : 
    3190             : /*
    3191             :  * Get the next tuple in the same bucket as 'tuple'.
    3192             :  */
    3193             : static inline HashJoinTuple
    3194     1993160 : ExecParallelHashNextTuple(HashJoinTable hashtable, HashJoinTuple tuple)
    3195             : {
    3196             :     HashJoinTuple next;
    3197             : 
    3198             :     Assert(hashtable->parallel_state);
    3199     1993160 :     next = (HashJoinTuple) dsa_get_address(hashtable->area, tuple->next.shared);
    3200             : 
    3201     1993160 :     return next;
    3202             : }
    3203             : 
    3204             : /*
    3205             :  * Insert a tuple at the front of a chain of tuples in DSA memory atomically.
    3206             :  */
    3207             : static inline void
    3208     1711146 : ExecParallelHashPushTuple(dsa_pointer_atomic *head,
    3209             :                           HashJoinTuple tuple,
    3210             :                           dsa_pointer tuple_shared)
    3211             : {
    3212             :     for (;;)
    3213             :     {
    3214     1715272 :         tuple->next.shared = dsa_pointer_atomic_read(head);
    3215     1711146 :         if (dsa_pointer_atomic_compare_exchange(head,
    3216     1711146 :                                                 &tuple->next.shared,
    3217             :                                                 tuple_shared))
    3218     1707020 :             break;
    3219             :     }
    3220     1707020 : }
    3221             : 
    3222             : /*
    3223             :  * Prepare to work on a given batch.
    3224             :  */
    3225             : void
    3226        1226 : ExecParallelHashTableSetCurrentBatch(HashJoinTable hashtable, int batchno)
    3227             : {
    3228             :     Assert(hashtable->batches[batchno].shared->buckets != InvalidDsaPointer);
    3229             : 
    3230        1226 :     hashtable->curbatch = batchno;
    3231        1226 :     hashtable->buckets.shared = (dsa_pointer_atomic *)
    3232        1226 :         dsa_get_address(hashtable->area,
    3233        1226 :                         hashtable->batches[batchno].shared->buckets);
    3234        1226 :     hashtable->nbuckets = hashtable->parallel_state->nbuckets;
    3235        1226 :     hashtable->log2_nbuckets = my_log2(hashtable->nbuckets);
    3236        1226 :     hashtable->current_chunk = NULL;
    3237        1226 :     hashtable->current_chunk_shared = InvalidDsaPointer;
    3238        1226 :     hashtable->batches[batchno].at_least_one_chunk = false;
    3239        1226 : }
    3240             : 
    3241             : /*
    3242             :  * Take the next available chunk from the queue of chunks being worked on in
    3243             :  * parallel.  Return NULL if there are none left.  Otherwise return a pointer
    3244             :  * to the chunk, and set *shared to the DSA pointer to the chunk.
    3245             :  */
    3246             : static HashMemoryChunk
    3247         762 : ExecParallelHashPopChunkQueue(HashJoinTable hashtable, dsa_pointer *shared)
    3248             : {
    3249         762 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    3250             :     HashMemoryChunk chunk;
    3251             : 
    3252         762 :     LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
    3253         762 :     if (DsaPointerIsValid(pstate->chunk_work_queue))
    3254             :     {
    3255         632 :         *shared = pstate->chunk_work_queue;
    3256         632 :         chunk = (HashMemoryChunk)
    3257         632 :             dsa_get_address(hashtable->area, *shared);
    3258         632 :         pstate->chunk_work_queue = chunk->next.shared;
    3259             :     }
    3260             :     else
    3261         130 :         chunk = NULL;
    3262         762 :     LWLockRelease(&pstate->lock);
    3263             : 
    3264         762 :     return chunk;
    3265             : }
    3266             : 
    3267             : /*
    3268             :  * Increase the space preallocated in this backend for a given inner batch by
    3269             :  * at least a given amount.  This allows us to track whether a given batch
    3270             :  * would fit in memory when loaded back in.  Also increase the number of
    3271             :  * batches or buckets if required.
    3272             :  *
    3273             :  * This maintains a running estimation of how much space will be taken when we
    3274             :  * load the batch back into memory by simulating the way chunks will be handed
    3275             :  * out to workers.  It's not perfectly accurate because the tuples will be
    3276             :  * packed into memory chunks differently by ExecParallelHashTupleAlloc(), but
    3277             :  * it should be pretty close.  It tends to overestimate by a fraction of a
    3278             :  * chunk per worker since all workers gang up to preallocate during hashing,
    3279             :  * but workers tend to reload batches alone if there are enough to go around,
    3280             :  * leaving fewer partially filled chunks.  This effect is bounded by
    3281             :  * nparticipants.
    3282             :  *
    3283             :  * Return false if the number of batches or buckets has changed, and the
    3284             :  * caller should reconsider which batch a given tuple now belongs in and call
    3285             :  * again.
    3286             :  */
    3287             : static bool
    3288        1048 : ExecParallelHashTuplePrealloc(HashJoinTable hashtable, int batchno, size_t size)
    3289             : {
    3290        1048 :     ParallelHashJoinState *pstate = hashtable->parallel_state;
    3291        1048 :     ParallelHashJoinBatchAccessor *batch = &hashtable->batches[batchno];
    3292        1048 :     size_t      want = Max(size, HASH_CHUNK_SIZE - HASH_CHUNK_HEADER_SIZE);
    3293             : 
    3294             :     Assert(batchno > 0);
    3295             :     Assert(batchno < hashtable->nbatch);
    3296             :     Assert(size == MAXALIGN(size));
    3297             : 
    3298        1048 :     LWLockAcquire(&pstate->lock, LW_EXCLUSIVE);
    3299             : 
    3300             :     /* Has another participant commanded us to help grow? */
    3301        2088 :     if (pstate->growth == PHJ_GROWTH_NEED_MORE_BATCHES ||
    3302        1040 :         pstate->growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
    3303             :     {
    3304           8 :         ParallelHashGrowth growth = pstate->growth;
    3305             : 
    3306           8 :         LWLockRelease(&pstate->lock);
    3307           8 :         if (growth == PHJ_GROWTH_NEED_MORE_BATCHES)
    3308           8 :             ExecParallelHashIncreaseNumBatches(hashtable);
    3309           0 :         else if (growth == PHJ_GROWTH_NEED_MORE_BUCKETS)
    3310           0 :             ExecParallelHashIncreaseNumBuckets(hashtable);
    3311             : 
    3312           8 :         return false;
    3313             :     }
    3314             : 
    3315        1928 :     if (pstate->growth != PHJ_GROWTH_DISABLED &&
    3316        1262 :         batch->at_least_one_chunk &&
    3317         374 :         (batch->shared->estimated_size + want + HASH_CHUNK_HEADER_SIZE
    3318         374 :          > pstate->space_allowed))
    3319             :     {
    3320             :         /*
    3321             :          * We have determined that this batch would exceed the space budget if
    3322             :          * loaded into memory.  Command all participants to help repartition.
    3323             :          */
    3324           8 :         batch->shared->space_exhausted = true;
    3325           8 :         pstate->growth = PHJ_GROWTH_NEED_MORE_BATCHES;
    3326           8 :         LWLockRelease(&pstate->lock);
    3327             : 
    3328           8 :         return false;
    3329             :     }
    3330             : 
    3331        1032 :     batch->at_least_one_chunk = true;
    3332        1032 :     batch->shared->estimated_size += want + HASH_CHUNK_HEADER_SIZE;
    3333        1032 :     batch->preallocated = want;
    3334        1032 :     LWLockRelease(&pstate->lock);
    3335             : 
    3336        1032 :     return true;
    3337             : }

Generated by: LCOV version 1.13