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