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

Generated by: LCOV version 1.13