PostgreSQL Source Code  git master
execParallel.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * execParallel.c
4  * Support routines for parallel execution.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * This file contains routines that are intended to support setting up,
10  * using, and tearing down a ParallelContext from within the PostgreSQL
11  * executor. The ParallelContext machinery will handle starting the
12  * workers and ensuring that their state generally matches that of the
13  * leader; see src/backend/access/transam/README.parallel for details.
14  * However, we must save and restore relevant executor state, such as
15  * any ParamListInfo associated with the query, buffer/WAL usage info, and
16  * the actual plan to be passed down to the worker.
17  *
18  * IDENTIFICATION
19  * src/backend/executor/execParallel.c
20  *
21  *-------------------------------------------------------------------------
22  */
23 
24 #include "postgres.h"
25 
26 #include "executor/execParallel.h"
27 #include "executor/executor.h"
28 #include "executor/nodeAgg.h"
29 #include "executor/nodeAppend.h"
31 #include "executor/nodeCustom.h"
33 #include "executor/nodeHash.h"
34 #include "executor/nodeHashjoin.h"
37 #include "executor/nodeIndexscan.h"
38 #include "executor/nodeMemoize.h"
39 #include "executor/nodeSeqscan.h"
40 #include "executor/nodeSort.h"
41 #include "executor/nodeSubplan.h"
42 #include "executor/tqueue.h"
43 #include "jit/jit.h"
44 #include "nodes/nodeFuncs.h"
45 #include "pgstat.h"
46 #include "storage/spin.h"
47 #include "tcop/tcopprot.h"
48 #include "utils/datum.h"
49 #include "utils/dsa.h"
50 #include "utils/lsyscache.h"
51 #include "utils/memutils.h"
52 #include "utils/snapmgr.h"
53 
54 /*
55  * Magic numbers for parallel executor communication. We use constants
56  * greater than any 32-bit integer here so that values < 2^32 can be used
57  * by individual parallel nodes to store their own state.
58  */
59 #define PARALLEL_KEY_EXECUTOR_FIXED UINT64CONST(0xE000000000000001)
60 #define PARALLEL_KEY_PLANNEDSTMT UINT64CONST(0xE000000000000002)
61 #define PARALLEL_KEY_PARAMLISTINFO UINT64CONST(0xE000000000000003)
62 #define PARALLEL_KEY_BUFFER_USAGE UINT64CONST(0xE000000000000004)
63 #define PARALLEL_KEY_TUPLE_QUEUE UINT64CONST(0xE000000000000005)
64 #define PARALLEL_KEY_INSTRUMENTATION UINT64CONST(0xE000000000000006)
65 #define PARALLEL_KEY_DSA UINT64CONST(0xE000000000000007)
66 #define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xE000000000000008)
67 #define PARALLEL_KEY_JIT_INSTRUMENTATION UINT64CONST(0xE000000000000009)
68 #define PARALLEL_KEY_WAL_USAGE UINT64CONST(0xE00000000000000A)
69 
70 #define PARALLEL_TUPLE_QUEUE_SIZE 65536
71 
72 /*
73  * Fixed-size random stuff that we need to pass to parallel workers.
74  */
76 {
77  int64 tuples_needed; /* tuple bound, see ExecSetTupleBound */
79  int eflags;
80  int jit_flags;
82 
83 /*
84  * DSM structure for accumulating per-PlanState instrumentation.
85  *
86  * instrument_options: Same meaning here as in instrument.c.
87  *
88  * instrument_offset: Offset, relative to the start of this structure,
89  * of the first Instrumentation object. This will depend on the length of
90  * the plan_node_id array.
91  *
92  * num_workers: Number of workers.
93  *
94  * num_plan_nodes: Number of plan nodes.
95  *
96  * plan_node_id: Array of plan nodes for which we are gathering instrumentation
97  * from parallel workers. The length of this array is given by num_plan_nodes.
98  */
100 {
106  /* array of num_plan_nodes * num_workers Instrumentation objects follows */
107 };
108 #define GetInstrumentationArray(sei) \
109  (AssertVariableIsOfTypeMacro(sei, SharedExecutorInstrumentation *), \
110  (Instrumentation *) (((char *) sei) + sei->instrument_offset))
111 
112 /* Context object for ExecParallelEstimate. */
114 {
116  int nnodes;
118 
119 /* Context object for ExecParallelInitializeDSM. */
121 {
124  int nnodes;
126 
127 /* Helper functions that run in the parallel leader. */
128 static char *ExecSerializePlan(Plan *plan, EState *estate);
129 static bool ExecParallelEstimate(PlanState *planstate,
131 static bool ExecParallelInitializeDSM(PlanState *planstate,
134  bool reinitialize);
135 static bool ExecParallelReInitializeDSM(PlanState *planstate,
136  ParallelContext *pcxt);
137 static bool ExecParallelRetrieveInstrumentation(PlanState *planstate,
138  SharedExecutorInstrumentation *instrumentation);
139 
140 /* Helper function that runs in the parallel worker. */
142 
143 /*
144  * Create a serialized representation of the plan to be sent to each worker.
145  */
146 static char *
148 {
149  PlannedStmt *pstmt;
150  ListCell *lc;
151 
152  /* We can't scribble on the original plan, so make a copy. */
153  plan = copyObject(plan);
154 
155  /*
156  * The worker will start its own copy of the executor, and that copy will
157  * insert a junk filter if the toplevel node has any resjunk entries. We
158  * don't want that to happen, because while resjunk columns shouldn't be
159  * sent back to the user, here the tuples are coming back to another
160  * backend which may very well need them. So mutate the target list
161  * accordingly. This is sort of a hack; there might be better ways to do
162  * this...
163  */
164  foreach(lc, plan->targetlist)
165  {
166  TargetEntry *tle = lfirst_node(TargetEntry, lc);
167 
168  tle->resjunk = false;
169  }
170 
171  /*
172  * Create a dummy PlannedStmt. Most of the fields don't need to be valid
173  * for our purposes, but the worker will need at least a minimal
174  * PlannedStmt to start the executor.
175  */
176  pstmt = makeNode(PlannedStmt);
177  pstmt->commandType = CMD_SELECT;
178  pstmt->queryId = pgstat_get_my_query_id();
179  pstmt->hasReturning = false;
180  pstmt->hasModifyingCTE = false;
181  pstmt->canSetTag = true;
182  pstmt->transientPlan = false;
183  pstmt->dependsOnRole = false;
184  pstmt->parallelModeNeeded = false;
185  pstmt->planTree = plan;
186  pstmt->partPruneInfos = estate->es_part_prune_infos;
187  pstmt->rtable = estate->es_range_table;
188  pstmt->permInfos = estate->es_rteperminfos;
189  pstmt->resultRelations = NIL;
190  pstmt->appendRelations = NIL;
191 
192  /*
193  * Transfer only parallel-safe subplans, leaving a NULL "hole" in the list
194  * for unsafe ones (so that the list indexes of the safe ones are
195  * preserved). This positively ensures that the worker won't try to run,
196  * or even do ExecInitNode on, an unsafe subplan. That's important to
197  * protect, eg, non-parallel-aware FDWs from getting into trouble.
198  */
199  pstmt->subplans = NIL;
200  foreach(lc, estate->es_plannedstmt->subplans)
201  {
202  Plan *subplan = (Plan *) lfirst(lc);
203 
204  if (subplan && !subplan->parallel_safe)
205  subplan = NULL;
206  pstmt->subplans = lappend(pstmt->subplans, subplan);
207  }
208 
209  pstmt->rewindPlanIDs = NULL;
210  pstmt->rowMarks = NIL;
211  pstmt->relationOids = NIL;
212  pstmt->invalItems = NIL; /* workers can't replan anyway... */
213  pstmt->paramExecTypes = estate->es_plannedstmt->paramExecTypes;
214  pstmt->utilityStmt = NULL;
215  pstmt->stmt_location = -1;
216  pstmt->stmt_len = -1;
217 
218  /* Return serialized copy of our dummy PlannedStmt. */
219  return nodeToString(pstmt);
220 }
221 
222 /*
223  * Parallel-aware plan nodes (and occasionally others) may need some state
224  * which is shared across all parallel workers. Before we size the DSM, give
225  * them a chance to call shm_toc_estimate_chunk or shm_toc_estimate_keys on
226  * &pcxt->estimator.
227  *
228  * While we're at it, count the number of PlanState nodes in the tree, so
229  * we know how many Instrumentation structures we need.
230  */
231 static bool
233 {
234  if (planstate == NULL)
235  return false;
236 
237  /* Count this node. */
238  e->nnodes++;
239 
240  switch (nodeTag(planstate))
241  {
242  case T_SeqScanState:
243  if (planstate->plan->parallel_aware)
244  ExecSeqScanEstimate((SeqScanState *) planstate,
245  e->pcxt);
246  break;
247  case T_IndexScanState:
248  if (planstate->plan->parallel_aware)
250  e->pcxt);
251  break;
252  case T_IndexOnlyScanState:
253  if (planstate->plan->parallel_aware)
255  e->pcxt);
256  break;
257  case T_ForeignScanState:
258  if (planstate->plan->parallel_aware)
260  e->pcxt);
261  break;
262  case T_AppendState:
263  if (planstate->plan->parallel_aware)
264  ExecAppendEstimate((AppendState *) planstate,
265  e->pcxt);
266  break;
267  case T_CustomScanState:
268  if (planstate->plan->parallel_aware)
270  e->pcxt);
271  break;
272  case T_BitmapHeapScanState:
273  if (planstate->plan->parallel_aware)
275  e->pcxt);
276  break;
277  case T_HashJoinState:
278  if (planstate->plan->parallel_aware)
279  ExecHashJoinEstimate((HashJoinState *) planstate,
280  e->pcxt);
281  break;
282  case T_HashState:
283  /* even when not parallel-aware, for EXPLAIN ANALYZE */
284  ExecHashEstimate((HashState *) planstate, e->pcxt);
285  break;
286  case T_SortState:
287  /* even when not parallel-aware, for EXPLAIN ANALYZE */
288  ExecSortEstimate((SortState *) planstate, e->pcxt);
289  break;
290  case T_IncrementalSortState:
291  /* even when not parallel-aware, for EXPLAIN ANALYZE */
292  ExecIncrementalSortEstimate((IncrementalSortState *) planstate, e->pcxt);
293  break;
294  case T_AggState:
295  /* even when not parallel-aware, for EXPLAIN ANALYZE */
296  ExecAggEstimate((AggState *) planstate, e->pcxt);
297  break;
298  case T_MemoizeState:
299  /* even when not parallel-aware, for EXPLAIN ANALYZE */
300  ExecMemoizeEstimate((MemoizeState *) planstate, e->pcxt);
301  break;
302  default:
303  break;
304  }
305 
306  return planstate_tree_walker(planstate, ExecParallelEstimate, e);
307 }
308 
309 /*
310  * Estimate the amount of space required to serialize the indicated parameters.
311  */
312 static Size
314 {
315  int paramid;
316  Size sz = sizeof(int);
317 
318  paramid = -1;
319  while ((paramid = bms_next_member(params, paramid)) >= 0)
320  {
321  Oid typeOid;
322  int16 typLen;
323  bool typByVal;
324  ParamExecData *prm;
325 
326  prm = &(estate->es_param_exec_vals[paramid]);
327  typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
328  paramid);
329 
330  sz = add_size(sz, sizeof(int)); /* space for paramid */
331 
332  /* space for datum/isnull */
333  if (OidIsValid(typeOid))
334  get_typlenbyval(typeOid, &typLen, &typByVal);
335  else
336  {
337  /* If no type OID, assume by-value, like copyParamList does. */
338  typLen = sizeof(Datum);
339  typByVal = true;
340  }
341  sz = add_size(sz,
342  datumEstimateSpace(prm->value, prm->isnull,
343  typByVal, typLen));
344  }
345  return sz;
346 }
347 
348 /*
349  * Serialize specified PARAM_EXEC parameters.
350  *
351  * We write the number of parameters first, as a 4-byte integer, and then
352  * write details for each parameter in turn. The details for each parameter
353  * consist of a 4-byte paramid (location of param in execution time internal
354  * parameter array) and then the datum as serialized by datumSerialize().
355  */
356 static dsa_pointer
358 {
359  Size size;
360  int nparams;
361  int paramid;
362  ParamExecData *prm;
363  dsa_pointer handle;
364  char *start_address;
365 
366  /* Allocate enough space for the current parameter values. */
367  size = EstimateParamExecSpace(estate, params);
368  handle = dsa_allocate(area, size);
369  start_address = dsa_get_address(area, handle);
370 
371  /* First write the number of parameters as a 4-byte integer. */
372  nparams = bms_num_members(params);
373  memcpy(start_address, &nparams, sizeof(int));
374  start_address += sizeof(int);
375 
376  /* Write details for each parameter in turn. */
377  paramid = -1;
378  while ((paramid = bms_next_member(params, paramid)) >= 0)
379  {
380  Oid typeOid;
381  int16 typLen;
382  bool typByVal;
383 
384  prm = &(estate->es_param_exec_vals[paramid]);
385  typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
386  paramid);
387 
388  /* Write paramid. */
389  memcpy(start_address, &paramid, sizeof(int));
390  start_address += sizeof(int);
391 
392  /* Write datum/isnull */
393  if (OidIsValid(typeOid))
394  get_typlenbyval(typeOid, &typLen, &typByVal);
395  else
396  {
397  /* If no type OID, assume by-value, like copyParamList does. */
398  typLen = sizeof(Datum);
399  typByVal = true;
400  }
401  datumSerialize(prm->value, prm->isnull, typByVal, typLen,
402  &start_address);
403  }
404 
405  return handle;
406 }
407 
408 /*
409  * Restore specified PARAM_EXEC parameters.
410  */
411 static void
412 RestoreParamExecParams(char *start_address, EState *estate)
413 {
414  int nparams;
415  int i;
416  int paramid;
417 
418  memcpy(&nparams, start_address, sizeof(int));
419  start_address += sizeof(int);
420 
421  for (i = 0; i < nparams; i++)
422  {
423  ParamExecData *prm;
424 
425  /* Read paramid */
426  memcpy(&paramid, start_address, sizeof(int));
427  start_address += sizeof(int);
428  prm = &(estate->es_param_exec_vals[paramid]);
429 
430  /* Read datum/isnull. */
431  prm->value = datumRestore(&start_address, &prm->isnull);
432  prm->execPlan = NULL;
433  }
434 }
435 
436 /*
437  * Initialize the dynamic shared memory segment that will be used to control
438  * parallel execution.
439  */
440 static bool
443 {
444  if (planstate == NULL)
445  return false;
446 
447  /* If instrumentation is enabled, initialize slot for this node. */
448  if (d->instrumentation != NULL)
450  planstate->plan->plan_node_id;
451 
452  /* Count this node. */
453  d->nnodes++;
454 
455  /*
456  * Call initializers for DSM-using plan nodes.
457  *
458  * Most plan nodes won't do anything here, but plan nodes that allocated
459  * DSM may need to initialize shared state in the DSM before parallel
460  * workers are launched. They can allocate the space they previously
461  * estimated using shm_toc_allocate, and add the keys they previously
462  * estimated using shm_toc_insert, in each case targeting pcxt->toc.
463  */
464  switch (nodeTag(planstate))
465  {
466  case T_SeqScanState:
467  if (planstate->plan->parallel_aware)
469  d->pcxt);
470  break;
471  case T_IndexScanState:
472  if (planstate->plan->parallel_aware)
474  d->pcxt);
475  break;
476  case T_IndexOnlyScanState:
477  if (planstate->plan->parallel_aware)
479  d->pcxt);
480  break;
481  case T_ForeignScanState:
482  if (planstate->plan->parallel_aware)
484  d->pcxt);
485  break;
486  case T_AppendState:
487  if (planstate->plan->parallel_aware)
488  ExecAppendInitializeDSM((AppendState *) planstate,
489  d->pcxt);
490  break;
491  case T_CustomScanState:
492  if (planstate->plan->parallel_aware)
494  d->pcxt);
495  break;
496  case T_BitmapHeapScanState:
497  if (planstate->plan->parallel_aware)
499  d->pcxt);
500  break;
501  case T_HashJoinState:
502  if (planstate->plan->parallel_aware)
504  d->pcxt);
505  break;
506  case T_HashState:
507  /* even when not parallel-aware, for EXPLAIN ANALYZE */
508  ExecHashInitializeDSM((HashState *) planstate, d->pcxt);
509  break;
510  case T_SortState:
511  /* even when not parallel-aware, for EXPLAIN ANALYZE */
512  ExecSortInitializeDSM((SortState *) planstate, d->pcxt);
513  break;
514  case T_IncrementalSortState:
515  /* even when not parallel-aware, for EXPLAIN ANALYZE */
517  break;
518  case T_AggState:
519  /* even when not parallel-aware, for EXPLAIN ANALYZE */
520  ExecAggInitializeDSM((AggState *) planstate, d->pcxt);
521  break;
522  case T_MemoizeState:
523  /* even when not parallel-aware, for EXPLAIN ANALYZE */
524  ExecMemoizeInitializeDSM((MemoizeState *) planstate, d->pcxt);
525  break;
526  default:
527  break;
528  }
529 
530  return planstate_tree_walker(planstate, ExecParallelInitializeDSM, d);
531 }
532 
533 /*
534  * It sets up the response queues for backend workers to return tuples
535  * to the main backend and start the workers.
536  */
537 static shm_mq_handle **
539 {
540  shm_mq_handle **responseq;
541  char *tqueuespace;
542  int i;
543 
544  /* Skip this if no workers. */
545  if (pcxt->nworkers == 0)
546  return NULL;
547 
548  /* Allocate memory for shared memory queue handles. */
549  responseq = (shm_mq_handle **)
550  palloc(pcxt->nworkers * sizeof(shm_mq_handle *));
551 
552  /*
553  * If not reinitializing, allocate space from the DSM for the queues;
554  * otherwise, find the already allocated space.
555  */
556  if (!reinitialize)
557  tqueuespace =
558  shm_toc_allocate(pcxt->toc,
560  pcxt->nworkers));
561  else
562  tqueuespace = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE, false);
563 
564  /* Create the queues, and become the receiver for each. */
565  for (i = 0; i < pcxt->nworkers; ++i)
566  {
567  shm_mq *mq;
568 
569  mq = shm_mq_create(tqueuespace +
572 
574  responseq[i] = shm_mq_attach(mq, pcxt->seg, NULL);
575  }
576 
577  /* Add array of queues to shm_toc, so others can find it. */
578  if (!reinitialize)
579  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE, tqueuespace);
580 
581  /* Return array of handles. */
582  return responseq;
583 }
584 
585 /*
586  * Sets up the required infrastructure for backend workers to perform
587  * execution and return results to the main backend.
588  */
591  Bitmapset *sendParams, int nworkers,
592  int64 tuples_needed)
593 {
595  ParallelContext *pcxt;
599  char *pstmt_data;
600  char *pstmt_space;
601  char *paramlistinfo_space;
602  BufferUsage *bufusage_space;
603  WalUsage *walusage_space;
604  SharedExecutorInstrumentation *instrumentation = NULL;
605  SharedJitInstrumentation *jit_instrumentation = NULL;
606  int pstmt_len;
607  int paramlistinfo_len;
608  int instrumentation_len = 0;
609  int jit_instrumentation_len = 0;
610  int instrument_offset = 0;
611  Size dsa_minsize = dsa_minimum_size();
612  char *query_string;
613  int query_len;
614 
615  /*
616  * Force any initplan outputs that we're going to pass to workers to be
617  * evaluated, if they weren't already.
618  *
619  * For simplicity, we use the EState's per-output-tuple ExprContext here.
620  * That risks intra-query memory leakage, since we might pass through here
621  * many times before that ExprContext gets reset; but ExecSetParamPlan
622  * doesn't normally leak any memory in the context (see its comments), so
623  * it doesn't seem worth complicating this function's API to pass it a
624  * shorter-lived ExprContext. This might need to change someday.
625  */
626  ExecSetParamPlanMulti(sendParams, GetPerTupleExprContext(estate));
627 
628  /* Allocate object for return value. */
629  pei = palloc0(sizeof(ParallelExecutorInfo));
630  pei->finished = false;
631  pei->planstate = planstate;
632 
633  /* Fix up and serialize plan to be sent to workers. */
634  pstmt_data = ExecSerializePlan(planstate->plan, estate);
635 
636  /* Create a parallel context. */
637  pcxt = CreateParallelContext("postgres", "ParallelQueryMain", nworkers);
638  pei->pcxt = pcxt;
639 
640  /*
641  * Before telling the parallel context to create a dynamic shared memory
642  * segment, we need to figure out how big it should be. Estimate space
643  * for the various things we need to store.
644  */
645 
646  /* Estimate space for fixed-size state. */
649  shm_toc_estimate_keys(&pcxt->estimator, 1);
650 
651  /* Estimate space for query text. */
652  query_len = strlen(estate->es_sourceText);
653  shm_toc_estimate_chunk(&pcxt->estimator, query_len + 1);
654  shm_toc_estimate_keys(&pcxt->estimator, 1);
655 
656  /* Estimate space for serialized PlannedStmt. */
657  pstmt_len = strlen(pstmt_data) + 1;
658  shm_toc_estimate_chunk(&pcxt->estimator, pstmt_len);
659  shm_toc_estimate_keys(&pcxt->estimator, 1);
660 
661  /* Estimate space for serialized ParamListInfo. */
662  paramlistinfo_len = EstimateParamListSpace(estate->es_param_list_info);
663  shm_toc_estimate_chunk(&pcxt->estimator, paramlistinfo_len);
664  shm_toc_estimate_keys(&pcxt->estimator, 1);
665 
666  /*
667  * Estimate space for BufferUsage.
668  *
669  * If EXPLAIN is not in use and there are no extensions loaded that care,
670  * we could skip this. But we have no way of knowing whether anyone's
671  * looking at pgBufferUsage, so do it unconditionally.
672  */
674  mul_size(sizeof(BufferUsage), pcxt->nworkers));
675  shm_toc_estimate_keys(&pcxt->estimator, 1);
676 
677  /*
678  * Same thing for WalUsage.
679  */
681  mul_size(sizeof(WalUsage), pcxt->nworkers));
682  shm_toc_estimate_keys(&pcxt->estimator, 1);
683 
684  /* Estimate space for tuple queues. */
687  shm_toc_estimate_keys(&pcxt->estimator, 1);
688 
689  /*
690  * Give parallel-aware nodes a chance to add to the estimates, and get a
691  * count of how many PlanState nodes there are.
692  */
693  e.pcxt = pcxt;
694  e.nnodes = 0;
695  ExecParallelEstimate(planstate, &e);
696 
697  /* Estimate space for instrumentation, if required. */
698  if (estate->es_instrument)
699  {
700  instrumentation_len =
701  offsetof(SharedExecutorInstrumentation, plan_node_id) +
702  sizeof(int) * e.nnodes;
703  instrumentation_len = MAXALIGN(instrumentation_len);
704  instrument_offset = instrumentation_len;
705  instrumentation_len +=
706  mul_size(sizeof(Instrumentation),
707  mul_size(e.nnodes, nworkers));
708  shm_toc_estimate_chunk(&pcxt->estimator, instrumentation_len);
709  shm_toc_estimate_keys(&pcxt->estimator, 1);
710 
711  /* Estimate space for JIT instrumentation, if required. */
712  if (estate->es_jit_flags != PGJIT_NONE)
713  {
714  jit_instrumentation_len =
715  offsetof(SharedJitInstrumentation, jit_instr) +
716  sizeof(JitInstrumentation) * nworkers;
717  shm_toc_estimate_chunk(&pcxt->estimator, jit_instrumentation_len);
718  shm_toc_estimate_keys(&pcxt->estimator, 1);
719  }
720  }
721 
722  /* Estimate space for DSA area. */
723  shm_toc_estimate_chunk(&pcxt->estimator, dsa_minsize);
724  shm_toc_estimate_keys(&pcxt->estimator, 1);
725 
726  /* Everyone's had a chance to ask for space, so now create the DSM. */
727  InitializeParallelDSM(pcxt);
728 
729  /*
730  * OK, now we have a dynamic shared memory segment, and it should be big
731  * enough to store all of the data we estimated we would want to put into
732  * it, plus whatever general stuff (not specifically executor-related) the
733  * ParallelContext itself needs to store there. None of the space we
734  * asked for has been allocated or initialized yet, though, so do that.
735  */
736 
737  /* Store fixed-size state. */
738  fpes = shm_toc_allocate(pcxt->toc, sizeof(FixedParallelExecutorState));
739  fpes->tuples_needed = tuples_needed;
741  fpes->eflags = estate->es_top_eflags;
742  fpes->jit_flags = estate->es_jit_flags;
744 
745  /* Store query string */
746  query_string = shm_toc_allocate(pcxt->toc, query_len + 1);
747  memcpy(query_string, estate->es_sourceText, query_len + 1);
748  shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, query_string);
749 
750  /* Store serialized PlannedStmt. */
751  pstmt_space = shm_toc_allocate(pcxt->toc, pstmt_len);
752  memcpy(pstmt_space, pstmt_data, pstmt_len);
753  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PLANNEDSTMT, pstmt_space);
754 
755  /* Store serialized ParamListInfo. */
756  paramlistinfo_space = shm_toc_allocate(pcxt->toc, paramlistinfo_len);
757  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PARAMLISTINFO, paramlistinfo_space);
758  SerializeParamList(estate->es_param_list_info, &paramlistinfo_space);
759 
760  /* Allocate space for each worker's BufferUsage; no need to initialize. */
761  bufusage_space = shm_toc_allocate(pcxt->toc,
762  mul_size(sizeof(BufferUsage), pcxt->nworkers));
763  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufusage_space);
764  pei->buffer_usage = bufusage_space;
765 
766  /* Same for WalUsage. */
767  walusage_space = shm_toc_allocate(pcxt->toc,
768  mul_size(sizeof(WalUsage), pcxt->nworkers));
769  shm_toc_insert(pcxt->toc, PARALLEL_KEY_WAL_USAGE, walusage_space);
770  pei->wal_usage = walusage_space;
771 
772  /* Set up the tuple queues that the workers will write into. */
773  pei->tqueue = ExecParallelSetupTupleQueues(pcxt, false);
774 
775  /* We don't need the TupleQueueReaders yet, though. */
776  pei->reader = NULL;
777 
778  /*
779  * If instrumentation options were supplied, allocate space for the data.
780  * It only gets partially initialized here; the rest happens during
781  * ExecParallelInitializeDSM.
782  */
783  if (estate->es_instrument)
784  {
785  Instrumentation *instrument;
786  int i;
787 
788  instrumentation = shm_toc_allocate(pcxt->toc, instrumentation_len);
789  instrumentation->instrument_options = estate->es_instrument;
790  instrumentation->instrument_offset = instrument_offset;
791  instrumentation->num_workers = nworkers;
792  instrumentation->num_plan_nodes = e.nnodes;
793  instrument = GetInstrumentationArray(instrumentation);
794  for (i = 0; i < nworkers * e.nnodes; ++i)
795  InstrInit(&instrument[i], estate->es_instrument);
797  instrumentation);
798  pei->instrumentation = instrumentation;
799 
800  if (estate->es_jit_flags != PGJIT_NONE)
801  {
802  jit_instrumentation = shm_toc_allocate(pcxt->toc,
803  jit_instrumentation_len);
804  jit_instrumentation->num_workers = nworkers;
805  memset(jit_instrumentation->jit_instr, 0,
806  sizeof(JitInstrumentation) * nworkers);
808  jit_instrumentation);
809  pei->jit_instrumentation = jit_instrumentation;
810  }
811  }
812 
813  /*
814  * Create a DSA area that can be used by the leader and all workers.
815  * (However, if we failed to create a DSM and are using private memory
816  * instead, then skip this.)
817  */
818  if (pcxt->seg != NULL)
819  {
820  char *area_space;
821 
822  area_space = shm_toc_allocate(pcxt->toc, dsa_minsize);
823  shm_toc_insert(pcxt->toc, PARALLEL_KEY_DSA, area_space);
824  pei->area = dsa_create_in_place(area_space, dsa_minsize,
826  pcxt->seg);
827 
828  /*
829  * Serialize parameters, if any, using DSA storage. We don't dare use
830  * the main parallel query DSM for this because we might relaunch
831  * workers after the values have changed (and thus the amount of
832  * storage required has changed).
833  */
834  if (!bms_is_empty(sendParams))
835  {
836  pei->param_exec = SerializeParamExecParams(estate, sendParams,
837  pei->area);
838  fpes->param_exec = pei->param_exec;
839  }
840  }
841 
842  /*
843  * Give parallel-aware nodes a chance to initialize their shared data.
844  * This also initializes the elements of instrumentation->ps_instrument,
845  * if it exists.
846  */
847  d.pcxt = pcxt;
848  d.instrumentation = instrumentation;
849  d.nnodes = 0;
850 
851  /* Install our DSA area while initializing the plan. */
852  estate->es_query_dsa = pei->area;
853  ExecParallelInitializeDSM(planstate, &d);
854  estate->es_query_dsa = NULL;
855 
856  /*
857  * Make sure that the world hasn't shifted under our feet. This could
858  * probably just be an Assert(), but let's be conservative for now.
859  */
860  if (e.nnodes != d.nnodes)
861  elog(ERROR, "inconsistent count of PlanState nodes");
862 
863  /* OK, we're ready to rock and roll. */
864  return pei;
865 }
866 
867 /*
868  * Set up tuple queue readers to read the results of a parallel subplan.
869  *
870  * This is separate from ExecInitParallelPlan() because we can launch the
871  * worker processes and let them start doing something before we do this.
872  */
873 void
875 {
876  int nworkers = pei->pcxt->nworkers_launched;
877  int i;
878 
879  Assert(pei->reader == NULL);
880 
881  if (nworkers > 0)
882  {
883  pei->reader = (TupleQueueReader **)
884  palloc(nworkers * sizeof(TupleQueueReader *));
885 
886  for (i = 0; i < nworkers; i++)
887  {
888  shm_mq_set_handle(pei->tqueue[i],
889  pei->pcxt->worker[i].bgwhandle);
890  pei->reader[i] = CreateTupleQueueReader(pei->tqueue[i]);
891  }
892  }
893 }
894 
895 /*
896  * Re-initialize the parallel executor shared memory state before launching
897  * a fresh batch of workers.
898  */
899 void
902  Bitmapset *sendParams)
903 {
904  EState *estate = planstate->state;
906 
907  /* Old workers must already be shut down */
908  Assert(pei->finished);
909 
910  /*
911  * Force any initplan outputs that we're going to pass to workers to be
912  * evaluated, if they weren't already (see comments in
913  * ExecInitParallelPlan).
914  */
915  ExecSetParamPlanMulti(sendParams, GetPerTupleExprContext(estate));
916 
918  pei->tqueue = ExecParallelSetupTupleQueues(pei->pcxt, true);
919  pei->reader = NULL;
920  pei->finished = false;
921 
922  fpes = shm_toc_lookup(pei->pcxt->toc, PARALLEL_KEY_EXECUTOR_FIXED, false);
923 
924  /* Free any serialized parameters from the last round. */
925  if (DsaPointerIsValid(fpes->param_exec))
926  {
927  dsa_free(pei->area, fpes->param_exec);
929  }
930 
931  /* Serialize current parameter values if required. */
932  if (!bms_is_empty(sendParams))
933  {
934  pei->param_exec = SerializeParamExecParams(estate, sendParams,
935  pei->area);
936  fpes->param_exec = pei->param_exec;
937  }
938 
939  /* Traverse plan tree and let each child node reset associated state. */
940  estate->es_query_dsa = pei->area;
941  ExecParallelReInitializeDSM(planstate, pei->pcxt);
942  estate->es_query_dsa = NULL;
943 }
944 
945 /*
946  * Traverse plan tree to reinitialize per-node dynamic shared memory state
947  */
948 static bool
950  ParallelContext *pcxt)
951 {
952  if (planstate == NULL)
953  return false;
954 
955  /*
956  * Call reinitializers for DSM-using plan nodes.
957  */
958  switch (nodeTag(planstate))
959  {
960  case T_SeqScanState:
961  if (planstate->plan->parallel_aware)
963  pcxt);
964  break;
965  case T_IndexScanState:
966  if (planstate->plan->parallel_aware)
968  pcxt);
969  break;
970  case T_IndexOnlyScanState:
971  if (planstate->plan->parallel_aware)
973  pcxt);
974  break;
975  case T_ForeignScanState:
976  if (planstate->plan->parallel_aware)
978  pcxt);
979  break;
980  case T_AppendState:
981  if (planstate->plan->parallel_aware)
982  ExecAppendReInitializeDSM((AppendState *) planstate, pcxt);
983  break;
984  case T_CustomScanState:
985  if (planstate->plan->parallel_aware)
987  pcxt);
988  break;
989  case T_BitmapHeapScanState:
990  if (planstate->plan->parallel_aware)
992  pcxt);
993  break;
994  case T_HashJoinState:
995  if (planstate->plan->parallel_aware)
997  pcxt);
998  break;
999  case T_HashState:
1000  case T_SortState:
1001  case T_IncrementalSortState:
1002  case T_MemoizeState:
1003  /* these nodes have DSM state, but no reinitialization is required */
1004  break;
1005 
1006  default:
1007  break;
1008  }
1009 
1010  return planstate_tree_walker(planstate, ExecParallelReInitializeDSM, pcxt);
1011 }
1012 
1013 /*
1014  * Copy instrumentation information about this node and its descendants from
1015  * dynamic shared memory.
1016  */
1017 static bool
1019  SharedExecutorInstrumentation *instrumentation)
1020 {
1021  Instrumentation *instrument;
1022  int i;
1023  int n;
1024  int ibytes;
1025  int plan_node_id = planstate->plan->plan_node_id;
1026  MemoryContext oldcontext;
1027 
1028  /* Find the instrumentation for this node. */
1029  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1030  if (instrumentation->plan_node_id[i] == plan_node_id)
1031  break;
1032  if (i >= instrumentation->num_plan_nodes)
1033  elog(ERROR, "plan node %d not found", plan_node_id);
1034 
1035  /* Accumulate the statistics from all workers. */
1036  instrument = GetInstrumentationArray(instrumentation);
1037  instrument += i * instrumentation->num_workers;
1038  for (n = 0; n < instrumentation->num_workers; ++n)
1039  InstrAggNode(planstate->instrument, &instrument[n]);
1040 
1041  /*
1042  * Also store the per-worker detail.
1043  *
1044  * Worker instrumentation should be allocated in the same context as the
1045  * regular instrumentation information, which is the per-query context.
1046  * Switch into per-query memory context.
1047  */
1048  oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
1049  ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));
1050  planstate->worker_instrument =
1051  palloc(ibytes + offsetof(WorkerInstrumentation, instrument));
1052  MemoryContextSwitchTo(oldcontext);
1053 
1054  planstate->worker_instrument->num_workers = instrumentation->num_workers;
1055  memcpy(&planstate->worker_instrument->instrument, instrument, ibytes);
1056 
1057  /* Perform any node-type-specific work that needs to be done. */
1058  switch (nodeTag(planstate))
1059  {
1060  case T_SortState:
1062  break;
1063  case T_IncrementalSortState:
1065  break;
1066  case T_HashState:
1068  break;
1069  case T_AggState:
1071  break;
1072  case T_MemoizeState:
1074  break;
1075  default:
1076  break;
1077  }
1078 
1080  instrumentation);
1081 }
1082 
1083 /*
1084  * Add up the workers' JIT instrumentation from dynamic shared memory.
1085  */
1086 static void
1088  SharedJitInstrumentation *shared_jit)
1089 {
1090  JitInstrumentation *combined;
1091  int ibytes;
1092 
1093  int n;
1094 
1095  /*
1096  * Accumulate worker JIT instrumentation into the combined JIT
1097  * instrumentation, allocating it if required.
1098  */
1099  if (!planstate->state->es_jit_worker_instr)
1100  planstate->state->es_jit_worker_instr =
1102  combined = planstate->state->es_jit_worker_instr;
1103 
1104  /* Accumulate all the workers' instrumentations. */
1105  for (n = 0; n < shared_jit->num_workers; ++n)
1106  InstrJitAgg(combined, &shared_jit->jit_instr[n]);
1107 
1108  /*
1109  * Store the per-worker detail.
1110  *
1111  * Similar to ExecParallelRetrieveInstrumentation(), allocate the
1112  * instrumentation in per-query context.
1113  */
1114  ibytes = offsetof(SharedJitInstrumentation, jit_instr)
1115  + mul_size(shared_jit->num_workers, sizeof(JitInstrumentation));
1116  planstate->worker_jit_instrument =
1117  MemoryContextAlloc(planstate->state->es_query_cxt, ibytes);
1118 
1119  memcpy(planstate->worker_jit_instrument, shared_jit, ibytes);
1120 }
1121 
1122 /*
1123  * Finish parallel execution. We wait for parallel workers to finish, and
1124  * accumulate their buffer/WAL usage.
1125  */
1126 void
1128 {
1129  int nworkers = pei->pcxt->nworkers_launched;
1130  int i;
1131 
1132  /* Make this be a no-op if called twice in a row. */
1133  if (pei->finished)
1134  return;
1135 
1136  /*
1137  * Detach from tuple queues ASAP, so that any still-active workers will
1138  * notice that no further results are wanted.
1139  */
1140  if (pei->tqueue != NULL)
1141  {
1142  for (i = 0; i < nworkers; i++)
1143  shm_mq_detach(pei->tqueue[i]);
1144  pfree(pei->tqueue);
1145  pei->tqueue = NULL;
1146  }
1147 
1148  /*
1149  * While we're waiting for the workers to finish, let's get rid of the
1150  * tuple queue readers. (Any other local cleanup could be done here too.)
1151  */
1152  if (pei->reader != NULL)
1153  {
1154  for (i = 0; i < nworkers; i++)
1156  pfree(pei->reader);
1157  pei->reader = NULL;
1158  }
1159 
1160  /* Now wait for the workers to finish. */
1162 
1163  /*
1164  * Next, accumulate buffer/WAL usage. (This must wait for the workers to
1165  * finish, or we might get incomplete data.)
1166  */
1167  for (i = 0; i < nworkers; i++)
1169 
1170  pei->finished = true;
1171 }
1172 
1173 /*
1174  * Accumulate instrumentation, and then clean up whatever ParallelExecutorInfo
1175  * resources still exist after ExecParallelFinish. We separate these
1176  * routines because someone might want to examine the contents of the DSM
1177  * after ExecParallelFinish and before calling this routine.
1178  */
1179 void
1181 {
1182  /* Accumulate instrumentation, if any. */
1183  if (pei->instrumentation)
1185  pei->instrumentation);
1186 
1187  /* Accumulate JIT instrumentation, if any. */
1188  if (pei->jit_instrumentation)
1190  pei->jit_instrumentation);
1191 
1192  /* Free any serialized parameters. */
1193  if (DsaPointerIsValid(pei->param_exec))
1194  {
1195  dsa_free(pei->area, pei->param_exec);
1197  }
1198  if (pei->area != NULL)
1199  {
1200  dsa_detach(pei->area);
1201  pei->area = NULL;
1202  }
1203  if (pei->pcxt != NULL)
1204  {
1206  pei->pcxt = NULL;
1207  }
1208  pfree(pei);
1209 }
1210 
1211 /*
1212  * Create a DestReceiver to write tuples we produce to the shm_mq designated
1213  * for that purpose.
1214  */
1215 static DestReceiver *
1217 {
1218  char *mqspace;
1219  shm_mq *mq;
1220 
1221  mqspace = shm_toc_lookup(toc, PARALLEL_KEY_TUPLE_QUEUE, false);
1223  mq = (shm_mq *) mqspace;
1225  return CreateTupleQueueDestReceiver(shm_mq_attach(mq, seg, NULL));
1226 }
1227 
1228 /*
1229  * Create a QueryDesc for the PlannedStmt we are to execute, and return it.
1230  */
1231 static QueryDesc *
1233  int instrument_options)
1234 {
1235  char *pstmtspace;
1236  char *paramspace;
1237  PlannedStmt *pstmt;
1238  ParamListInfo paramLI;
1239  char *queryString;
1240 
1241  /* Get the query string from shared memory */
1242  queryString = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, false);
1243 
1244  /* Reconstruct leader-supplied PlannedStmt. */
1245  pstmtspace = shm_toc_lookup(toc, PARALLEL_KEY_PLANNEDSTMT, false);
1246  pstmt = (PlannedStmt *) stringToNode(pstmtspace);
1247 
1248  /* Reconstruct ParamListInfo. */
1249  paramspace = shm_toc_lookup(toc, PARALLEL_KEY_PARAMLISTINFO, false);
1250  paramLI = RestoreParamList(&paramspace);
1251 
1252  /* Create a QueryDesc for the query. */
1253  return CreateQueryDesc(pstmt,
1254  queryString,
1256  receiver, paramLI, NULL, instrument_options);
1257 }
1258 
1259 /*
1260  * Copy instrumentation information from this node and its descendants into
1261  * dynamic shared memory, so that the parallel leader can retrieve it.
1262  */
1263 static bool
1265  SharedExecutorInstrumentation *instrumentation)
1266 {
1267  int i;
1268  int plan_node_id = planstate->plan->plan_node_id;
1269  Instrumentation *instrument;
1270 
1271  InstrEndLoop(planstate->instrument);
1272 
1273  /*
1274  * If we shuffled the plan_node_id values in ps_instrument into sorted
1275  * order, we could use binary search here. This might matter someday if
1276  * we're pushing down sufficiently large plan trees. For now, do it the
1277  * slow, dumb way.
1278  */
1279  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1280  if (instrumentation->plan_node_id[i] == plan_node_id)
1281  break;
1282  if (i >= instrumentation->num_plan_nodes)
1283  elog(ERROR, "plan node %d not found", plan_node_id);
1284 
1285  /*
1286  * Add our statistics to the per-node, per-worker totals. It's possible
1287  * that this could happen more than once if we relaunched workers.
1288  */
1289  instrument = GetInstrumentationArray(instrumentation);
1290  instrument += i * instrumentation->num_workers;
1292  Assert(ParallelWorkerNumber < instrumentation->num_workers);
1293  InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
1294 
1296  instrumentation);
1297 }
1298 
1299 /*
1300  * Initialize the PlanState and its descendants with the information
1301  * retrieved from shared memory. This has to be done once the PlanState
1302  * is allocated and initialized by executor; that is, after ExecutorStart().
1303  */
1304 static bool
1306 {
1307  if (planstate == NULL)
1308  return false;
1309 
1310  switch (nodeTag(planstate))
1311  {
1312  case T_SeqScanState:
1313  if (planstate->plan->parallel_aware)
1314  ExecSeqScanInitializeWorker((SeqScanState *) planstate, pwcxt);
1315  break;
1316  case T_IndexScanState:
1317  if (planstate->plan->parallel_aware)
1319  pwcxt);
1320  break;
1321  case T_IndexOnlyScanState:
1322  if (planstate->plan->parallel_aware)
1324  pwcxt);
1325  break;
1326  case T_ForeignScanState:
1327  if (planstate->plan->parallel_aware)
1329  pwcxt);
1330  break;
1331  case T_AppendState:
1332  if (planstate->plan->parallel_aware)
1333  ExecAppendInitializeWorker((AppendState *) planstate, pwcxt);
1334  break;
1335  case T_CustomScanState:
1336  if (planstate->plan->parallel_aware)
1338  pwcxt);
1339  break;
1340  case T_BitmapHeapScanState:
1341  if (planstate->plan->parallel_aware)
1343  pwcxt);
1344  break;
1345  case T_HashJoinState:
1346  if (planstate->plan->parallel_aware)
1348  pwcxt);
1349  break;
1350  case T_HashState:
1351  /* even when not parallel-aware, for EXPLAIN ANALYZE */
1352  ExecHashInitializeWorker((HashState *) planstate, pwcxt);
1353  break;
1354  case T_SortState:
1355  /* even when not parallel-aware, for EXPLAIN ANALYZE */
1356  ExecSortInitializeWorker((SortState *) planstate, pwcxt);
1357  break;
1358  case T_IncrementalSortState:
1359  /* even when not parallel-aware, for EXPLAIN ANALYZE */
1361  pwcxt);
1362  break;
1363  case T_AggState:
1364  /* even when not parallel-aware, for EXPLAIN ANALYZE */
1365  ExecAggInitializeWorker((AggState *) planstate, pwcxt);
1366  break;
1367  case T_MemoizeState:
1368  /* even when not parallel-aware, for EXPLAIN ANALYZE */
1369  ExecMemoizeInitializeWorker((MemoizeState *) planstate, pwcxt);
1370  break;
1371  default:
1372  break;
1373  }
1374 
1376  pwcxt);
1377 }
1378 
1379 /*
1380  * Main entrypoint for parallel query worker processes.
1381  *
1382  * We reach this function from ParallelWorkerMain, so the setup necessary to
1383  * create a sensible parallel environment has already been done;
1384  * ParallelWorkerMain worries about stuff like the transaction state, combo
1385  * CID mappings, and GUC values, so we don't need to deal with any of that
1386  * here.
1387  *
1388  * Our job is to deal with concerns specific to the executor. The parallel
1389  * group leader will have stored a serialized PlannedStmt, and it's our job
1390  * to execute that plan and write the resulting tuples to the appropriate
1391  * tuple queue. Various bits of supporting information that we need in order
1392  * to do this are also stored in the dsm_segment and can be accessed through
1393  * the shm_toc.
1394  */
1395 void
1397 {
1399  BufferUsage *buffer_usage;
1400  WalUsage *wal_usage;
1401  DestReceiver *receiver;
1402  QueryDesc *queryDesc;
1403  SharedExecutorInstrumentation *instrumentation;
1404  SharedJitInstrumentation *jit_instrumentation;
1405  int instrument_options = 0;
1406  void *area_space;
1407  dsa_area *area;
1408  ParallelWorkerContext pwcxt;
1409 
1410  /* Get fixed-size state. */
1411  fpes = shm_toc_lookup(toc, PARALLEL_KEY_EXECUTOR_FIXED, false);
1412 
1413  /* Set up DestReceiver, SharedExecutorInstrumentation, and QueryDesc. */
1414  receiver = ExecParallelGetReceiver(seg, toc);
1415  instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_INSTRUMENTATION, true);
1416  if (instrumentation != NULL)
1417  instrument_options = instrumentation->instrument_options;
1418  jit_instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_JIT_INSTRUMENTATION,
1419  true);
1420  queryDesc = ExecParallelGetQueryDesc(toc, receiver, instrument_options);
1421 
1422  /* Setting debug_query_string for individual workers */
1423  debug_query_string = queryDesc->sourceText;
1424 
1425  /* Report workers' query for monitoring purposes */
1427 
1428  /* Attach to the dynamic shared memory area. */
1429  area_space = shm_toc_lookup(toc, PARALLEL_KEY_DSA, false);
1430  area = dsa_attach_in_place(area_space, seg);
1431 
1432  /* Start up the executor */
1433  queryDesc->plannedstmt->jitFlags = fpes->jit_flags;
1434  ExecutorStart(queryDesc, fpes->eflags);
1435 
1436  /* Special executor initialization steps for parallel workers */
1437  queryDesc->planstate->state->es_query_dsa = area;
1438  if (DsaPointerIsValid(fpes->param_exec))
1439  {
1440  char *paramexec_space;
1441 
1442  paramexec_space = dsa_get_address(area, fpes->param_exec);
1443  RestoreParamExecParams(paramexec_space, queryDesc->estate);
1444  }
1445  pwcxt.toc = toc;
1446  pwcxt.seg = seg;
1447  ExecParallelInitializeWorker(queryDesc->planstate, &pwcxt);
1448 
1449  /* Pass down any tuple bound */
1450  ExecSetTupleBound(fpes->tuples_needed, queryDesc->planstate);
1451 
1452  /*
1453  * Prepare to track buffer/WAL usage during query execution.
1454  *
1455  * We do this after starting up the executor to match what happens in the
1456  * leader, which also doesn't count buffer accesses and WAL activity that
1457  * occur during executor startup.
1458  */
1460 
1461  /*
1462  * Run the plan. If we specified a tuple bound, be careful not to demand
1463  * more tuples than that.
1464  */
1465  ExecutorRun(queryDesc,
1467  fpes->tuples_needed < 0 ? (int64) 0 : fpes->tuples_needed,
1468  true);
1469 
1470  /* Shut down the executor */
1471  ExecutorFinish(queryDesc);
1472 
1473  /* Report buffer/WAL usage during parallel execution. */
1474  buffer_usage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
1475  wal_usage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
1477  &wal_usage[ParallelWorkerNumber]);
1478 
1479  /* Report instrumentation data if any instrumentation options are set. */
1480  if (instrumentation != NULL)
1482  instrumentation);
1483 
1484  /* Report JIT instrumentation data if any */
1485  if (queryDesc->estate->es_jit && jit_instrumentation != NULL)
1486  {
1487  Assert(ParallelWorkerNumber < jit_instrumentation->num_workers);
1488  jit_instrumentation->jit_instr[ParallelWorkerNumber] =
1489  queryDesc->estate->es_jit->instr;
1490  }
1491 
1492  /* Must do this after capturing instrumentation. */
1493  ExecutorEnd(queryDesc);
1494 
1495  /* Cleanup. */
1496  dsa_detach(area);
1497  FreeQueryDesc(queryDesc);
1498  receiver->rDestroy(receiver);
1499 }
int ParallelWorkerNumber
Definition: parallel.c:113
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:203
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:773
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:486
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:927
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:165
uint64 pgstat_get_my_query_id(void)
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:649
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
signed short int16
Definition: c.h:429
#define MAXALIGN(LEN)
Definition: c.h:747
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:362
#define OidIsValid(objectId)
Definition: c.h:711
size_t Size
Definition: c.h:541
Datum datumRestore(char **start_address, bool *isnull)
Definition: datum.c:521
void datumSerialize(Datum value, bool isnull, bool typByVal, int typLen, char **start_address)
Definition: datum.c:459
Size datumEstimateSpace(Datum value, bool isnull, bool typByVal, int typLen)
Definition: datum.c:412
dsa_area * dsa_create_in_place(void *place, size_t size, int tranche_id, dsm_segment *segment)
Definition: dsa.c:481
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:944
void dsa_detach(dsa_area *area)
Definition: dsa.c:1922
dsa_area * dsa_attach_in_place(void *place, dsm_segment *segment)
Definition: dsa.c:553
void dsa_free(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:832
size_t dsa_minimum_size(void)
Definition: dsa.c:1181
uint64 dsa_pointer
Definition: dsa.h:62
#define dsa_allocate(area, size)
Definition: dsa.h:84
#define InvalidDsaPointer
Definition: dsa.h:78
#define DsaPointerIsValid(x)
Definition: dsa.h:81
#define ERROR
Definition: elog.h:39
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:132
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
#define PARALLEL_KEY_BUFFER_USAGE
Definition: execParallel.c:62
static bool ExecParallelReInitializeDSM(PlanState *planstate, ParallelContext *pcxt)
Definition: execParallel.c:949
#define PARALLEL_KEY_JIT_INSTRUMENTATION
Definition: execParallel.c:67
struct ExecParallelEstimateContext ExecParallelEstimateContext
#define PARALLEL_KEY_PARAMLISTINFO
Definition: execParallel.c:61
#define PARALLEL_TUPLE_QUEUE_SIZE
Definition: execParallel.c:70
static bool ExecParallelRetrieveInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
static dsa_pointer SerializeParamExecParams(EState *estate, Bitmapset *params, dsa_area *area)
Definition: execParallel.c:357
void ExecParallelCleanup(ParallelExecutorInfo *pei)
struct ExecParallelInitializeDSMContext ExecParallelInitializeDSMContext
#define PARALLEL_KEY_INSTRUMENTATION
Definition: execParallel.c:64
static DestReceiver * ExecParallelGetReceiver(dsm_segment *seg, shm_toc *toc)
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
ParallelExecutorInfo * ExecInitParallelPlan(PlanState *planstate, EState *estate, Bitmapset *sendParams, int nworkers, int64 tuples_needed)
Definition: execParallel.c:590
static shm_mq_handle ** ExecParallelSetupTupleQueues(ParallelContext *pcxt, bool reinitialize)
Definition: execParallel.c:538
#define PARALLEL_KEY_PLANNEDSTMT
Definition: execParallel.c:60
static bool ExecParallelEstimate(PlanState *planstate, ExecParallelEstimateContext *e)
Definition: execParallel.c:232
#define GetInstrumentationArray(sei)
Definition: execParallel.c:108
void ExecParallelReinitialize(PlanState *planstate, ParallelExecutorInfo *pei, Bitmapset *sendParams)
Definition: execParallel.c:900
#define PARALLEL_KEY_DSA
Definition: execParallel.c:65
static bool ExecParallelInitializeWorker(PlanState *planstate, ParallelWorkerContext *pwcxt)
void ExecParallelCreateReaders(ParallelExecutorInfo *pei)
Definition: execParallel.c:874
#define PARALLEL_KEY_TUPLE_QUEUE
Definition: execParallel.c:63
static QueryDesc * ExecParallelGetQueryDesc(shm_toc *toc, DestReceiver *receiver, int instrument_options)
#define PARALLEL_KEY_EXECUTOR_FIXED
Definition: execParallel.c:59
static char * ExecSerializePlan(Plan *plan, EState *estate)
Definition: execParallel.c:147
struct FixedParallelExecutorState FixedParallelExecutorState
#define PARALLEL_KEY_QUERY_TEXT
Definition: execParallel.c:66
static Size EstimateParamExecSpace(EState *estate, Bitmapset *params)
Definition: execParallel.c:313
void ExecParallelFinish(ParallelExecutorInfo *pei)
static bool ExecParallelReportInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
#define PARALLEL_KEY_WAL_USAGE
Definition: execParallel.c:68
static void ExecParallelRetrieveJitInstrumentation(PlanState *planstate, SharedJitInstrumentation *shared_jit)
static bool ExecParallelInitializeDSM(PlanState *planstate, ExecParallelInitializeDSMContext *d)
Definition: execParallel.c:441
static void RestoreParamExecParams(char *start_address, EState *estate)
Definition: execParallel.c:412
void ExecSetTupleBound(int64 tuples_needed, PlanState *child_node)
Definition: execProcnode.c:849
#define GetPerTupleExprContext(estate)
Definition: executor.h:538
#define IsParallelWorker()
Definition: parallel.h:61
void InstrAccumParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:218
void InstrEndLoop(Instrumentation *instr)
Definition: instrument.c:140
void InstrAggNode(Instrumentation *dst, Instrumentation *add)
Definition: instrument.c:169
void InstrEndParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:208
void InstrStartParallelQuery(void)
Definition: instrument.c:200
void InstrInit(Instrumentation *instr, int instrument_options)
Definition: instrument.c:58
int i
Definition: isn.c:73
void InstrJitAgg(JitInstrumentation *dst, JitInstrumentation *add)
Definition: jit.c:184
struct JitInstrumentation JitInstrumentation
#define PGJIT_NONE
Definition: jit.h:19
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2209
@ LWTRANCHE_PARALLEL_QUERY_DSA
Definition: lwlock.h:193
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc0(Size size)
Definition: mcxt.c:1230
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1037
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
void * palloc(Size size)
Definition: mcxt.c:1199
void ExecAggEstimate(AggState *node, ParallelContext *pcxt)
Definition: nodeAgg.c:4681
void ExecAggInitializeWorker(AggState *node, ParallelWorkerContext *pwcxt)
Definition: nodeAgg.c:4727
void ExecAggRetrieveInstrumentation(AggState *node)
Definition: nodeAgg.c:4740
void ExecAggInitializeDSM(AggState *node, ParallelContext *pcxt)
Definition: nodeAgg.c:4702
void ExecAppendReInitializeDSM(AppendState *node, ParallelContext *pcxt)
Definition: nodeAppend.c:523
void ExecAppendInitializeWorker(AppendState *node, ParallelWorkerContext *pwcxt)
Definition: nodeAppend.c:539
void ExecAppendInitializeDSM(AppendState *node, ParallelContext *pcxt)
Definition: nodeAppend.c:502
void ExecAppendEstimate(AppendState *node, ParallelContext *pcxt)
Definition: nodeAppend.c:483
void ExecBitmapHeapInitializeWorker(BitmapHeapScanState *node, ParallelWorkerContext *pwcxt)
void ExecBitmapHeapEstimate(BitmapHeapScanState *node, ParallelContext *pcxt)
void ExecBitmapHeapInitializeDSM(BitmapHeapScanState *node, ParallelContext *pcxt)
void ExecBitmapHeapReInitializeDSM(BitmapHeapScanState *node, ParallelContext *pcxt)
void ExecCustomScanInitializeDSM(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:184
void ExecCustomScanEstimate(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:171
void ExecCustomScanReInitializeDSM(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:200
void ExecCustomScanInitializeWorker(CustomScanState *node, ParallelWorkerContext *pwcxt)
Definition: nodeCustom.c:215
void ExecForeignScanInitializeDSM(ForeignScanState *node, ParallelContext *pcxt)
void ExecForeignScanReInitializeDSM(ForeignScanState *node, ParallelContext *pcxt)
void ExecForeignScanEstimate(ForeignScanState *node, ParallelContext *pcxt)
void ExecForeignScanInitializeWorker(ForeignScanState *node, ParallelWorkerContext *pwcxt)
#define planstate_tree_walker(ps, w, c)
Definition: nodeFuncs.h:177
void ExecHashInitializeDSM(HashState *node, ParallelContext *pcxt)
Definition: nodeHash.c:2600
void ExecHashInitializeWorker(HashState *node, ParallelWorkerContext *pwcxt)
Definition: nodeHash.c:2625
void ExecHashEstimate(HashState *node, ParallelContext *pcxt)
Definition: nodeHash.c:2581
void ExecHashRetrieveInstrumentation(HashState *node)
Definition: nodeHash.c:2666
void ExecHashJoinInitializeDSM(HashJoinState *state, ParallelContext *pcxt)
void ExecHashJoinEstimate(HashJoinState *state, ParallelContext *pcxt)
void ExecHashJoinReInitializeDSM(HashJoinState *state, ParallelContext *pcxt)
void ExecHashJoinInitializeWorker(HashJoinState *state, ParallelWorkerContext *pwcxt)
void ExecIncrementalSortEstimate(IncrementalSortState *node, ParallelContext *pcxt)
void ExecIncrementalSortInitializeDSM(IncrementalSortState *node, ParallelContext *pcxt)
void ExecIncrementalSortRetrieveInstrumentation(IncrementalSortState *node)
void ExecIncrementalSortInitializeWorker(IncrementalSortState *node, ParallelWorkerContext *pwcxt)
void ExecIndexOnlyScanEstimate(IndexOnlyScanState *node, ParallelContext *pcxt)
void ExecIndexOnlyScanInitializeWorker(IndexOnlyScanState *node, ParallelWorkerContext *pwcxt)
void ExecIndexOnlyScanReInitializeDSM(IndexOnlyScanState *node, ParallelContext *pcxt)
void ExecIndexOnlyScanInitializeDSM(IndexOnlyScanState *node, ParallelContext *pcxt)
void ExecIndexScanEstimate(IndexScanState *node, ParallelContext *pcxt)
void ExecIndexScanReInitializeDSM(IndexScanState *node, ParallelContext *pcxt)
void ExecIndexScanInitializeDSM(IndexScanState *node, ParallelContext *pcxt)
void ExecIndexScanInitializeWorker(IndexScanState *node, ParallelWorkerContext *pwcxt)
void ExecMemoizeInitializeDSM(MemoizeState *node, ParallelContext *pcxt)
Definition: nodeMemoize.c:1173
void ExecMemoizeEstimate(MemoizeState *node, ParallelContext *pcxt)
Definition: nodeMemoize.c:1152
void ExecMemoizeRetrieveInstrumentation(MemoizeState *node)
Definition: nodeMemoize.c:1211
void ExecMemoizeInitializeWorker(MemoizeState *node, ParallelWorkerContext *pwcxt)
Definition: nodeMemoize.c:1198
void ExecSeqScanReInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:290
void ExecSeqScanInitializeWorker(SeqScanState *node, ParallelWorkerContext *pwcxt)
Definition: nodeSeqscan.c:306
void ExecSeqScanInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:268
void ExecSeqScanEstimate(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:250
void ExecSortInitializeWorker(SortState *node, ParallelWorkerContext *pwcxt)
Definition: nodeSort.c:469
void ExecSortEstimate(SortState *node, ParallelContext *pcxt)
Definition: nodeSort.c:423
void ExecSortInitializeDSM(SortState *node, ParallelContext *pcxt)
Definition: nodeSort.c:444
void ExecSortRetrieveInstrumentation(SortState *node)
Definition: nodeSort.c:483
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1268
#define copyObject(obj)
Definition: nodes.h:233
#define nodeTag(nodeptr)
Definition: nodes.h:122
@ CMD_SELECT
Definition: nodes.h:265
#define makeNode(_type_)
Definition: nodes.h:165
char * nodeToString(const void *obj)
Definition: outfuncs.c:874
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
Size EstimateParamListSpace(ParamListInfo paramLI)
Definition: params.c:167
void SerializeParamList(ParamListInfo paramLI, char **start_address)
Definition: params.c:229
ParamListInfo RestoreParamList(char **start_address)
Definition: params.c:292
#define lfirst(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:174
#define NIL
Definition: pg_list.h:66
static Oid list_nth_oid(const List *list, int n)
Definition: pg_list.h:319
const char * debug_query_string
Definition: postgres.c:82
uintptr_t Datum
Definition: postgres.h:412
unsigned int Oid
Definition: postgres_ext.h:31
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
e
Definition: preproc-init.c:82
void * stringToNode(const char *str)
Definition: read.c:90
@ ForwardScanDirection
Definition: sdir.h:26
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:291
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:225
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:320
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:178
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:844
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:207
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
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:805
#define InvalidSnapshot
Definition: snapshot.h:123
PGPROC * MyProc
Definition: proc.c:68
List * es_part_prune_infos
Definition: execnodes.h:619
struct dsa_area * es_query_dsa
Definition: execnodes.h:687
int es_top_eflags
Definition: execnodes.h:659
struct JitContext * es_jit
Definition: execnodes.h:699
int es_instrument
Definition: execnodes.h:660
PlannedStmt * es_plannedstmt
Definition: execnodes.h:618
struct JitInstrumentation * es_jit_worker_instr
Definition: execnodes.h:700
ParamExecData * es_param_exec_vals
Definition: execnodes.h:648
List * es_range_table
Definition: execnodes.h:611
List * es_rteperminfos
Definition: execnodes.h:617
ParamListInfo es_param_list_info
Definition: execnodes.h:647
MemoryContext es_query_cxt
Definition: execnodes.h:653
int es_jit_flags
Definition: execnodes.h:698
const char * es_sourceText
Definition: execnodes.h:620
ParallelContext * pcxt
Definition: execParallel.c:115
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.c:123
JitInstrumentation instr
Definition: jit.h:61
dsm_segment * seg
Definition: parallel.h:43
shm_toc_estimator estimator
Definition: parallel.h:42
ParallelWorkerInfo * worker
Definition: parallel.h:46
shm_toc * toc
Definition: parallel.h:45
int nworkers_launched
Definition: parallel.h:38
PlanState * planstate
Definition: execParallel.h:26
struct SharedJitInstrumentation * jit_instrumentation
Definition: execParallel.h:31
BufferUsage * buffer_usage
Definition: execParallel.h:28
dsa_pointer param_exec
Definition: execParallel.h:33
ParallelContext * pcxt
Definition: execParallel.h:27
WalUsage * wal_usage
Definition: execParallel.h:29
shm_mq_handle ** tqueue
Definition: execParallel.h:36
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.h:30
struct TupleQueueReader ** reader
Definition: execParallel.h:37
dsm_segment * seg
Definition: parallel.h:53
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
void * execPlan
Definition: params.h:148
struct SharedJitInstrumentation * worker_jit_instrument
Definition: execnodes.h:1042
Instrumentation * instrument
Definition: execnodes.h:1038
Plan * plan
Definition: execnodes.h:1028
EState * state
Definition: execnodes.h:1030
WorkerInstrumentation * worker_instrument
Definition: execnodes.h:1039
bool parallel_aware
Definition: plannodes.h:144
bool parallel_safe
Definition: plannodes.h:145
int plan_node_id
Definition: plannodes.h:155
List * targetlist
Definition: plannodes.h:156
struct Plan * planTree
Definition: plannodes.h:71
bool hasModifyingCTE
Definition: plannodes.h:59
List * appendRelations
Definition: plannodes.h:84
List * permInfos
Definition: plannodes.h:78
bool canSetTag
Definition: plannodes.h:61
List * rowMarks
Definition: plannodes.h:91
int stmt_location
Definition: plannodes.h:102
int stmt_len
Definition: plannodes.h:103
int jitFlags
Definition: plannodes.h:69
Bitmapset * rewindPlanIDs
Definition: plannodes.h:89
bool hasReturning
Definition: plannodes.h:57
List * invalItems
Definition: plannodes.h:95
bool transientPlan
Definition: plannodes.h:63
List * resultRelations
Definition: plannodes.h:82
List * subplans
Definition: plannodes.h:86
List * relationOids
Definition: plannodes.h:93
bool dependsOnRole
Definition: plannodes.h:65
CmdType commandType
Definition: plannodes.h:53
Node * utilityStmt
Definition: plannodes.h:99
List * rtable
Definition: plannodes.h:76
List * partPruneInfos
Definition: plannodes.h:73
List * paramExecTypes
Definition: plannodes.h:97
bool parallelModeNeeded
Definition: plannodes.h:67
uint64 queryId
Definition: plannodes.h:55
const char * sourceText
Definition: execdesc.h:38
EState * estate
Definition: execdesc.h:48
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * planstate
Definition: execdesc.h:49
int plan_node_id[FLEXIBLE_ARRAY_MEMBER]
Definition: execParallel.c:105
JitInstrumentation jit_instr[FLEXIBLE_ARRAY_MEMBER]
Definition: jit.h:51
bool resjunk
Definition: primnodes.h:1562
Instrumentation instrument[FLEXIBLE_ARRAY_MEMBER]
Definition: instrument.h:96
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
Definition: dsa.c:367
Definition: shm_mq.c:73
TupleQueueReader * CreateTupleQueueReader(shm_mq_handle *handle)
Definition: tqueue.c:139
DestReceiver * CreateTupleQueueDestReceiver(shm_mq_handle *handle)
Definition: tqueue.c:119
void DestroyTupleQueueReader(TupleQueueReader *reader)
Definition: tqueue.c:155