PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2017, 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 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"
29 #include "executor/nodeCustom.h"
31 #include "executor/nodeSeqscan.h"
32 #include "executor/nodeIndexscan.h"
34 #include "executor/tqueue.h"
35 #include "nodes/nodeFuncs.h"
36 #include "optimizer/planmain.h"
37 #include "optimizer/planner.h"
38 #include "storage/spin.h"
39 #include "tcop/tcopprot.h"
40 #include "utils/dsa.h"
41 #include "utils/memutils.h"
42 #include "utils/snapmgr.h"
43 #include "pgstat.h"
44 
45 /*
46  * Magic numbers for parallel executor communication. We use constants
47  * greater than any 32-bit integer here so that values < 2^32 can be used
48  * by individual parallel nodes to store their own state.
49  */
50 #define PARALLEL_KEY_PLANNEDSTMT UINT64CONST(0xE000000000000001)
51 #define PARALLEL_KEY_PARAMS UINT64CONST(0xE000000000000002)
52 #define PARALLEL_KEY_BUFFER_USAGE UINT64CONST(0xE000000000000003)
53 #define PARALLEL_KEY_TUPLE_QUEUE UINT64CONST(0xE000000000000004)
54 #define PARALLEL_KEY_INSTRUMENTATION UINT64CONST(0xE000000000000005)
55 #define PARALLEL_KEY_DSA UINT64CONST(0xE000000000000006)
56 #define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xE000000000000007)
57 
58 #define PARALLEL_TUPLE_QUEUE_SIZE 65536
59 
60 /*
61  * DSM structure for accumulating per-PlanState instrumentation.
62  *
63  * instrument_options: Same meaning here as in instrument.c.
64  *
65  * instrument_offset: Offset, relative to the start of this structure,
66  * of the first Instrumentation object. This will depend on the length of
67  * the plan_node_id array.
68  *
69  * num_workers: Number of workers.
70  *
71  * num_plan_nodes: Number of plan nodes.
72  *
73  * plan_node_id: Array of plan nodes for which we are gathering instrumentation
74  * from parallel workers. The length of this array is given by num_plan_nodes.
75  */
77 {
82  int plan_node_id[FLEXIBLE_ARRAY_MEMBER];
83  /* array of num_plan_nodes * num_workers Instrumentation objects follows */
84 };
85 #define GetInstrumentationArray(sei) \
86  (AssertVariableIsOfTypeMacro(sei, SharedExecutorInstrumentation *), \
87  (Instrumentation *) (((char *) sei) + sei->instrument_offset))
88 
89 /* Context object for ExecParallelEstimate. */
91 {
93  int nnodes;
95 
96 /* Context object for ExecParallelInitializeDSM. */
98 {
101  int nnodes;
103 
104 /* Helper functions that run in the parallel leader. */
105 static char *ExecSerializePlan(Plan *plan, EState *estate);
106 static bool ExecParallelEstimate(PlanState *node,
108 static bool ExecParallelInitializeDSM(PlanState *node,
111  bool reinitialize);
112 static bool ExecParallelRetrieveInstrumentation(PlanState *planstate,
113  SharedExecutorInstrumentation *instrumentation);
114 
115 /* Helper function that runs in the parallel worker. */
117 
118 /*
119  * Create a serialized representation of the plan to be sent to each worker.
120  */
121 static char *
123 {
124  PlannedStmt *pstmt;
125  ListCell *lc;
126 
127  /* We can't scribble on the original plan, so make a copy. */
128  plan = copyObject(plan);
129 
130  /*
131  * The worker will start its own copy of the executor, and that copy will
132  * insert a junk filter if the toplevel node has any resjunk entries. We
133  * don't want that to happen, because while resjunk columns shouldn't be
134  * sent back to the user, here the tuples are coming back to another
135  * backend which may very well need them. So mutate the target list
136  * accordingly. This is sort of a hack; there might be better ways to do
137  * this...
138  */
139  foreach(lc, plan->targetlist)
140  {
141  TargetEntry *tle = lfirst_node(TargetEntry, lc);
142 
143  tle->resjunk = false;
144  }
145 
146  /*
147  * Create a dummy PlannedStmt. Most of the fields don't need to be valid
148  * for our purposes, but the worker will need at least a minimal
149  * PlannedStmt to start the executor.
150  */
151  pstmt = makeNode(PlannedStmt);
152  pstmt->commandType = CMD_SELECT;
153  pstmt->queryId = 0;
154  pstmt->hasReturning = false;
155  pstmt->hasModifyingCTE = false;
156  pstmt->canSetTag = true;
157  pstmt->transientPlan = false;
158  pstmt->dependsOnRole = false;
159  pstmt->parallelModeNeeded = false;
160  pstmt->planTree = plan;
161  pstmt->rtable = estate->es_range_table;
162  pstmt->resultRelations = NIL;
163  pstmt->nonleafResultRelations = NIL;
164 
165  /*
166  * Transfer only parallel-safe subplans, leaving a NULL "hole" in the list
167  * for unsafe ones (so that the list indexes of the safe ones are
168  * preserved). This positively ensures that the worker won't try to run,
169  * or even do ExecInitNode on, an unsafe subplan. That's important to
170  * protect, eg, non-parallel-aware FDWs from getting into trouble.
171  */
172  pstmt->subplans = NIL;
173  foreach(lc, estate->es_plannedstmt->subplans)
174  {
175  Plan *subplan = (Plan *) lfirst(lc);
176 
177  if (subplan && !subplan->parallel_safe)
178  subplan = NULL;
179  pstmt->subplans = lappend(pstmt->subplans, subplan);
180  }
181 
182  pstmt->rewindPlanIDs = NULL;
183  pstmt->rowMarks = NIL;
184  pstmt->relationOids = NIL;
185  pstmt->invalItems = NIL; /* workers can't replan anyway... */
186  pstmt->nParamExec = estate->es_plannedstmt->nParamExec;
187  pstmt->utilityStmt = NULL;
188  pstmt->stmt_location = -1;
189  pstmt->stmt_len = -1;
190 
191  /* Return serialized copy of our dummy PlannedStmt. */
192  return nodeToString(pstmt);
193 }
194 
195 /*
196  * Ordinary plan nodes won't do anything here, but parallel-aware plan nodes
197  * may need some state which is shared across all parallel workers. Before
198  * we size the DSM, give them a chance to call shm_toc_estimate_chunk or
199  * shm_toc_estimate_keys on &pcxt->estimator.
200  *
201  * While we're at it, count the number of PlanState nodes in the tree, so
202  * we know how many SharedPlanStateInstrumentation structures we need.
203  */
204 static bool
206 {
207  if (planstate == NULL)
208  return false;
209 
210  /* Count this node. */
211  e->nnodes++;
212 
213  /* Call estimators for parallel-aware nodes. */
214  if (planstate->plan->parallel_aware)
215  {
216  switch (nodeTag(planstate))
217  {
218  case T_SeqScanState:
219  ExecSeqScanEstimate((SeqScanState *) planstate,
220  e->pcxt);
221  break;
222  case T_IndexScanState:
224  e->pcxt);
225  break;
228  e->pcxt);
229  break;
230  case T_ForeignScanState:
232  e->pcxt);
233  break;
234  case T_CustomScanState:
236  e->pcxt);
237  break;
240  e->pcxt);
241  break;
242  default:
243  break;
244  }
245  }
246 
247  return planstate_tree_walker(planstate, ExecParallelEstimate, e);
248 }
249 
250 /*
251  * Initialize the dynamic shared memory segment that will be used to control
252  * parallel execution.
253  */
254 static bool
257 {
258  if (planstate == NULL)
259  return false;
260 
261  /* If instrumentation is enabled, initialize slot for this node. */
262  if (d->instrumentation != NULL)
264  planstate->plan->plan_node_id;
265 
266  /* Count this node. */
267  d->nnodes++;
268 
269  /*
270  * Call initializers for parallel-aware plan nodes.
271  *
272  * Ordinary plan nodes won't do anything here, but parallel-aware plan
273  * nodes may need to initialize shared state in the DSM before parallel
274  * workers are available. They can allocate the space they previously
275  * estimated using shm_toc_allocate, and add the keys they previously
276  * estimated using shm_toc_insert, in each case targeting pcxt->toc.
277  */
278  if (planstate->plan->parallel_aware)
279  {
280  switch (nodeTag(planstate))
281  {
282  case T_SeqScanState:
284  d->pcxt);
285  break;
286  case T_IndexScanState:
288  d->pcxt);
289  break;
292  d->pcxt);
293  break;
294  case T_ForeignScanState:
296  d->pcxt);
297  break;
298  case T_CustomScanState:
300  d->pcxt);
301  break;
304  d->pcxt);
305  break;
306 
307  default:
308  break;
309  }
310  }
311 
312  return planstate_tree_walker(planstate, ExecParallelInitializeDSM, d);
313 }
314 
315 /*
316  * It sets up the response queues for backend workers to return tuples
317  * to the main backend and start the workers.
318  */
319 static shm_mq_handle **
321 {
322  shm_mq_handle **responseq;
323  char *tqueuespace;
324  int i;
325 
326  /* Skip this if no workers. */
327  if (pcxt->nworkers == 0)
328  return NULL;
329 
330  /* Allocate memory for shared memory queue handles. */
331  responseq = (shm_mq_handle **)
332  palloc(pcxt->nworkers * sizeof(shm_mq_handle *));
333 
334  /*
335  * If not reinitializing, allocate space from the DSM for the queues;
336  * otherwise, find the already allocated space.
337  */
338  if (!reinitialize)
339  tqueuespace =
340  shm_toc_allocate(pcxt->toc,
342  pcxt->nworkers));
343  else
344  tqueuespace = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE);
345 
346  /* Create the queues, and become the receiver for each. */
347  for (i = 0; i < pcxt->nworkers; ++i)
348  {
349  shm_mq *mq;
350 
351  mq = shm_mq_create(tqueuespace +
353  (Size) PARALLEL_TUPLE_QUEUE_SIZE);
354 
356  responseq[i] = shm_mq_attach(mq, pcxt->seg, NULL);
357  }
358 
359  /* Add array of queues to shm_toc, so others can find it. */
360  if (!reinitialize)
361  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE, tqueuespace);
362 
363  /* Return array of handles. */
364  return responseq;
365 }
366 
367 /*
368  * Re-initialize the parallel executor info such that it can be reused by
369  * workers.
370  */
371 void
373 {
375  pei->tqueue = ExecParallelSetupTupleQueues(pei->pcxt, true);
376  pei->finished = false;
377 }
378 
379 /*
380  * Sets up the required infrastructure for backend workers to perform
381  * execution and return results to the main backend.
382  */
384 ExecInitParallelPlan(PlanState *planstate, EState *estate, int nworkers)
385 {
387  ParallelContext *pcxt;
390  char *pstmt_data;
391  char *pstmt_space;
392  char *param_space;
393  BufferUsage *bufusage_space;
394  SharedExecutorInstrumentation *instrumentation = NULL;
395  int pstmt_len;
396  int param_len;
397  int instrumentation_len = 0;
398  int instrument_offset = 0;
399  Size dsa_minsize = dsa_minimum_size();
400  char *query_string;
401  int query_len;
402 
403  /* Allocate object for return value. */
404  pei = palloc0(sizeof(ParallelExecutorInfo));
405  pei->finished = false;
406  pei->planstate = planstate;
407 
408  /* Fix up and serialize plan to be sent to workers. */
409  pstmt_data = ExecSerializePlan(planstate->plan, estate);
410 
411  /* Create a parallel context. */
412  pcxt = CreateParallelContext("postgres", "ParallelQueryMain", nworkers);
413  pei->pcxt = pcxt;
414 
415  /*
416  * Before telling the parallel context to create a dynamic shared memory
417  * segment, we need to figure out how big it should be. Estimate space
418  * for the various things we need to store.
419  */
420 
421  /* Estimate space for query text. */
422  query_len = strlen(estate->es_sourceText);
423  shm_toc_estimate_chunk(&pcxt->estimator, query_len);
424  shm_toc_estimate_keys(&pcxt->estimator, 1);
425 
426  /* Estimate space for serialized PlannedStmt. */
427  pstmt_len = strlen(pstmt_data) + 1;
428  shm_toc_estimate_chunk(&pcxt->estimator, pstmt_len);
429  shm_toc_estimate_keys(&pcxt->estimator, 1);
430 
431  /* Estimate space for serialized ParamListInfo. */
432  param_len = EstimateParamListSpace(estate->es_param_list_info);
433  shm_toc_estimate_chunk(&pcxt->estimator, param_len);
434  shm_toc_estimate_keys(&pcxt->estimator, 1);
435 
436  /*
437  * Estimate space for BufferUsage.
438  *
439  * If EXPLAIN is not in use and there are no extensions loaded that care,
440  * we could skip this. But we have no way of knowing whether anyone's
441  * looking at pgBufferUsage, so do it unconditionally.
442  */
444  mul_size(sizeof(BufferUsage), pcxt->nworkers));
445  shm_toc_estimate_keys(&pcxt->estimator, 1);
446 
447  /* Estimate space for tuple queues. */
450  shm_toc_estimate_keys(&pcxt->estimator, 1);
451 
452  /*
453  * Give parallel-aware nodes a chance to add to the estimates, and get a
454  * count of how many PlanState nodes there are.
455  */
456  e.pcxt = pcxt;
457  e.nnodes = 0;
458  ExecParallelEstimate(planstate, &e);
459 
460  /* Estimate space for instrumentation, if required. */
461  if (estate->es_instrument)
462  {
463  instrumentation_len =
464  offsetof(SharedExecutorInstrumentation, plan_node_id) +
465  sizeof(int) * e.nnodes;
466  instrumentation_len = MAXALIGN(instrumentation_len);
467  instrument_offset = instrumentation_len;
468  instrumentation_len +=
469  mul_size(sizeof(Instrumentation),
470  mul_size(e.nnodes, nworkers));
471  shm_toc_estimate_chunk(&pcxt->estimator, instrumentation_len);
472  shm_toc_estimate_keys(&pcxt->estimator, 1);
473  }
474 
475  /* Estimate space for DSA area. */
476  shm_toc_estimate_chunk(&pcxt->estimator, dsa_minsize);
477  shm_toc_estimate_keys(&pcxt->estimator, 1);
478 
479  /* Everyone's had a chance to ask for space, so now create the DSM. */
480  InitializeParallelDSM(pcxt);
481 
482  /*
483  * OK, now we have a dynamic shared memory segment, and it should be big
484  * enough to store all of the data we estimated we would want to put into
485  * it, plus whatever general stuff (not specifically executor-related) the
486  * ParallelContext itself needs to store there. None of the space we
487  * asked for has been allocated or initialized yet, though, so do that.
488  */
489 
490  /* Store query string */
491  query_string = shm_toc_allocate(pcxt->toc, query_len);
492  memcpy(query_string, estate->es_sourceText, query_len);
493  shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, query_string);
494 
495  /* Store serialized PlannedStmt. */
496  pstmt_space = shm_toc_allocate(pcxt->toc, pstmt_len);
497  memcpy(pstmt_space, pstmt_data, pstmt_len);
498  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PLANNEDSTMT, pstmt_space);
499 
500  /* Store serialized ParamListInfo. */
501  param_space = shm_toc_allocate(pcxt->toc, param_len);
502  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PARAMS, param_space);
503  SerializeParamList(estate->es_param_list_info, &param_space);
504 
505  /* Allocate space for each worker's BufferUsage; no need to initialize. */
506  bufusage_space = shm_toc_allocate(pcxt->toc,
507  mul_size(sizeof(BufferUsage), pcxt->nworkers));
508  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufusage_space);
509  pei->buffer_usage = bufusage_space;
510 
511  /* Set up tuple queues. */
512  pei->tqueue = ExecParallelSetupTupleQueues(pcxt, false);
513 
514  /*
515  * If instrumentation options were supplied, allocate space for the data.
516  * It only gets partially initialized here; the rest happens during
517  * ExecParallelInitializeDSM.
518  */
519  if (estate->es_instrument)
520  {
521  Instrumentation *instrument;
522  int i;
523 
524  instrumentation = shm_toc_allocate(pcxt->toc, instrumentation_len);
525  instrumentation->instrument_options = estate->es_instrument;
526  instrumentation->instrument_offset = instrument_offset;
527  instrumentation->num_workers = nworkers;
528  instrumentation->num_plan_nodes = e.nnodes;
529  instrument = GetInstrumentationArray(instrumentation);
530  for (i = 0; i < nworkers * e.nnodes; ++i)
531  InstrInit(&instrument[i], estate->es_instrument);
533  instrumentation);
534  pei->instrumentation = instrumentation;
535  }
536 
537  /*
538  * Create a DSA area that can be used by the leader and all workers.
539  * (However, if we failed to create a DSM and are using private memory
540  * instead, then skip this.)
541  */
542  if (pcxt->seg != NULL)
543  {
544  char *area_space;
545 
546  area_space = shm_toc_allocate(pcxt->toc, dsa_minsize);
547  shm_toc_insert(pcxt->toc, PARALLEL_KEY_DSA, area_space);
548  pei->area = dsa_create_in_place(area_space, dsa_minsize,
550  pcxt->seg);
551  }
552 
553  /*
554  * Make the area available to executor nodes running in the leader. See
555  * also ParallelQueryMain which makes it available to workers.
556  */
557  estate->es_query_dsa = pei->area;
558 
559  /*
560  * Give parallel-aware nodes a chance to initialize their shared data.
561  * This also initializes the elements of instrumentation->ps_instrument,
562  * if it exists.
563  */
564  d.pcxt = pcxt;
565  d.instrumentation = instrumentation;
566  d.nnodes = 0;
567  ExecParallelInitializeDSM(planstate, &d);
568 
569  /*
570  * Make sure that the world hasn't shifted under our feat. This could
571  * probably just be an Assert(), but let's be conservative for now.
572  */
573  if (e.nnodes != d.nnodes)
574  elog(ERROR, "inconsistent count of PlanState nodes");
575 
576  /* OK, we're ready to rock and roll. */
577  return pei;
578 }
579 
580 /*
581  * Copy instrumentation information about this node and its descendants from
582  * dynamic shared memory.
583  */
584 static bool
586  SharedExecutorInstrumentation *instrumentation)
587 {
588  Instrumentation *instrument;
589  int i;
590  int n;
591  int ibytes;
592  int plan_node_id = planstate->plan->plan_node_id;
593  MemoryContext oldcontext;
594 
595  /* Find the instrumentation for this node. */
596  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
597  if (instrumentation->plan_node_id[i] == plan_node_id)
598  break;
599  if (i >= instrumentation->num_plan_nodes)
600  elog(ERROR, "plan node %d not found", plan_node_id);
601 
602  /* Accumulate the statistics from all workers. */
603  instrument = GetInstrumentationArray(instrumentation);
604  instrument += i * instrumentation->num_workers;
605  for (n = 0; n < instrumentation->num_workers; ++n)
606  InstrAggNode(planstate->instrument, &instrument[n]);
607 
608  /*
609  * Also store the per-worker detail.
610  *
611  * Worker instrumentation should be allocated in the same context as the
612  * regular instrumentation information, which is the per-query context.
613  * Switch into per-query memory context.
614  */
615  oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
616  ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));
617  planstate->worker_instrument =
618  palloc(ibytes + offsetof(WorkerInstrumentation, instrument));
619  MemoryContextSwitchTo(oldcontext);
620 
621  planstate->worker_instrument->num_workers = instrumentation->num_workers;
622  memcpy(&planstate->worker_instrument->instrument, instrument, ibytes);
623 
625  instrumentation);
626 }
627 
628 /*
629  * Finish parallel execution. We wait for parallel workers to finish, and
630  * accumulate their buffer usage and instrumentation.
631  */
632 void
634 {
635  int i;
636 
637  if (pei->finished)
638  return;
639 
640  /* First, wait for the workers to finish. */
642 
643  /* Next, accumulate buffer usage. */
644  for (i = 0; i < pei->pcxt->nworkers_launched; ++i)
646 
647  /* Finally, accumulate instrumentation, if any. */
648  if (pei->instrumentation)
650  pei->instrumentation);
651 
652  pei->finished = true;
653 }
654 
655 /*
656  * Clean up whatever ParallelExecutorInfo resources still exist after
657  * ExecParallelFinish. We separate these routines because someone might
658  * want to examine the contents of the DSM after ExecParallelFinish and
659  * before calling this routine.
660  */
661 void
663 {
664  if (pei->area != NULL)
665  {
666  dsa_detach(pei->area);
667  pei->area = NULL;
668  }
669  if (pei->pcxt != NULL)
670  {
672  pei->pcxt = NULL;
673  }
674  pfree(pei);
675 }
676 
677 /*
678  * Create a DestReceiver to write tuples we produce to the shm_mq designated
679  * for that purpose.
680  */
681 static DestReceiver *
683 {
684  char *mqspace;
685  shm_mq *mq;
686 
689  mq = (shm_mq *) mqspace;
692 }
693 
694 /*
695  * Create a QueryDesc for the PlannedStmt we are to execute, and return it.
696  */
697 static QueryDesc *
699  int instrument_options)
700 {
701  char *pstmtspace;
702  char *paramspace;
703  PlannedStmt *pstmt;
704  ParamListInfo paramLI;
705  char *queryString;
706 
707  /* Get the query string from shared memory */
708  queryString = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT);
709 
710  /* Reconstruct leader-supplied PlannedStmt. */
711  pstmtspace = shm_toc_lookup(toc, PARALLEL_KEY_PLANNEDSTMT);
712  pstmt = (PlannedStmt *) stringToNode(pstmtspace);
713 
714  /* Reconstruct ParamListInfo. */
715  paramspace = shm_toc_lookup(toc, PARALLEL_KEY_PARAMS);
716  paramLI = RestoreParamList(&paramspace);
717 
718  /*
719  * Create a QueryDesc for the query.
720  *
721  * It's not obvious how to obtain the query string from here; and even if
722  * we could copying it would take more cycles than not copying it. But
723  * it's a bit unsatisfying to just use a dummy string here, so consider
724  * revising this someday.
725  */
726  return CreateQueryDesc(pstmt,
727  queryString,
729  receiver, paramLI, NULL, instrument_options);
730 }
731 
732 /*
733  * Copy instrumentation information from this node and its descendants into
734  * dynamic shared memory, so that the parallel leader can retrieve it.
735  */
736 static bool
738  SharedExecutorInstrumentation *instrumentation)
739 {
740  int i;
741  int plan_node_id = planstate->plan->plan_node_id;
742  Instrumentation *instrument;
743 
744  InstrEndLoop(planstate->instrument);
745 
746  /*
747  * If we shuffled the plan_node_id values in ps_instrument into sorted
748  * order, we could use binary search here. This might matter someday if
749  * we're pushing down sufficiently large plan trees. For now, do it the
750  * slow, dumb way.
751  */
752  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
753  if (instrumentation->plan_node_id[i] == plan_node_id)
754  break;
755  if (i >= instrumentation->num_plan_nodes)
756  elog(ERROR, "plan node %d not found", plan_node_id);
757 
758  /*
759  * Add our statistics to the per-node, per-worker totals. It's possible
760  * that this could happen more than once if we relaunched workers.
761  */
762  instrument = GetInstrumentationArray(instrumentation);
763  instrument += i * instrumentation->num_workers;
765  Assert(ParallelWorkerNumber < instrumentation->num_workers);
766  InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
767 
769  instrumentation);
770 }
771 
772 /*
773  * Initialize the PlanState and its descendants with the information
774  * retrieved from shared memory. This has to be done once the PlanState
775  * is allocated and initialized by executor; that is, after ExecutorStart().
776  */
777 static bool
779 {
780  if (planstate == NULL)
781  return false;
782 
783  /* Call initializers for parallel-aware plan nodes. */
784  if (planstate->plan->parallel_aware)
785  {
786  switch (nodeTag(planstate))
787  {
788  case T_SeqScanState:
789  ExecSeqScanInitializeWorker((SeqScanState *) planstate, toc);
790  break;
791  case T_IndexScanState:
792  ExecIndexScanInitializeWorker((IndexScanState *) planstate, toc);
793  break;
796  break;
797  case T_ForeignScanState:
799  toc);
800  break;
801  case T_CustomScanState:
803  toc);
804  break;
807  (BitmapHeapScanState *) planstate, toc);
808  break;
809  default:
810  break;
811  }
812  }
813 
814  return planstate_tree_walker(planstate, ExecParallelInitializeWorker, toc);
815 }
816 
817 /*
818  * Main entrypoint for parallel query worker processes.
819  *
820  * We reach this function from ParallelWorkerMain, so the setup necessary to
821  * create a sensible parallel environment has already been done;
822  * ParallelWorkerMain worries about stuff like the transaction state, combo
823  * CID mappings, and GUC values, so we don't need to deal with any of that
824  * here.
825  *
826  * Our job is to deal with concerns specific to the executor. The parallel
827  * group leader will have stored a serialized PlannedStmt, and it's our job
828  * to execute that plan and write the resulting tuples to the appropriate
829  * tuple queue. Various bits of supporting information that we need in order
830  * to do this are also stored in the dsm_segment and can be accessed through
831  * the shm_toc.
832  */
833 void
835 {
836  BufferUsage *buffer_usage;
837  DestReceiver *receiver;
838  QueryDesc *queryDesc;
839  SharedExecutorInstrumentation *instrumentation;
840  int instrument_options = 0;
841  void *area_space;
842  dsa_area *area;
843 
844  /* Set up DestReceiver, SharedExecutorInstrumentation, and QueryDesc. */
845  receiver = ExecParallelGetReceiver(seg, toc);
846  instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_INSTRUMENTATION);
847  if (instrumentation != NULL)
848  instrument_options = instrumentation->instrument_options;
849  queryDesc = ExecParallelGetQueryDesc(toc, receiver, instrument_options);
850 
851  /* Setting debug_query_string for individual workers */
852  debug_query_string = queryDesc->sourceText;
853 
854  /* Report workers' query for monitoring purposes */
856 
857  /* Prepare to track buffer usage during query execution. */
859 
860  /* Attach to the dynamic shared memory area. */
861  area_space = shm_toc_lookup(toc, PARALLEL_KEY_DSA);
862  area = dsa_attach_in_place(area_space, seg);
863 
864  /* Start up the executor */
865  ExecutorStart(queryDesc, 0);
866 
867  /* Special executor initialization steps for parallel workers */
868  queryDesc->planstate->state->es_query_dsa = area;
869  ExecParallelInitializeWorker(queryDesc->planstate, toc);
870 
871  /* Run the plan */
872  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
873 
874  /* Shut down the executor */
875  ExecutorFinish(queryDesc);
876 
877  /* Report buffer usage during parallel execution. */
878  buffer_usage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE);
880 
881  /* Report instrumentation data if any instrumentation options are set. */
882  if (instrumentation != NULL)
884  instrumentation);
885 
886  /* Must do this after capturing instrumentation. */
887  ExecutorEnd(queryDesc);
888 
889  /* Cleanup. */
890  dsa_detach(area);
891  FreeQueryDesc(queryDesc);
892  (*receiver->rDestroy) (receiver);
893 }
void ExecIndexScanInitializeWorker(IndexScanState *node, shm_toc *toc)
bool dependsOnRole
Definition: plannodes.h:57
void ExecSeqScanInitializeWorker(SeqScanState *node, shm_toc *toc)
Definition: nodeSeqscan.c:331
#define NIL
Definition: pg_list.h:69
void ExecIndexScanInitializeDSM(IndexScanState *node, ParallelContext *pcxt)
struct dsa_area * es_query_dsa
Definition: execnodes.h:488
void * stringToNode(char *str)
Definition: read.c:38
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
ParallelContext * pcxt
Definition: execParallel.h:27
uint32 queryId
Definition: plannodes.h:47
WorkerInstrumentation * worker_instrument
Definition: execnodes.h:820
struct ExecParallelEstimateContext ExecParallelEstimateContext
int plan_node_id[FLEXIBLE_ARRAY_MEMBER]
Definition: execParallel.c:82
Instrumentation * instrument
Definition: execnodes.h:819
void ExecIndexOnlyScanInitializeWorker(IndexOnlyScanState *node, shm_toc *toc)
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:136
void ExecParallelFinish(ParallelExecutorInfo *pei)
Definition: execParallel.c:633
#define PARALLEL_KEY_TUPLE_QUEUE
Definition: execParallel.c:53
List * nonleafResultRelations
Definition: plannodes.h:72
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:106
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
PGPROC * MyProc
Definition: proc.c:67
void InstrAggNode(Instrumentation *dst, Instrumentation *add)
Definition: instrument.c:143
dsm_segment * seg
Definition: parallel.h:42
static bool ExecParallelReportInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
Definition: execParallel.c:737
void ExecCustomScanInitializeWorker(CustomScanState *node, shm_toc *toc)
Definition: nodeCustom.c:188
List * relationOids
Definition: plannodes.h:88
shm_toc_estimator estimator
Definition: parallel.h:41
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:144
dsa_area * dsa_attach_in_place(void *place, dsm_segment *segment)
Definition: dsa.c:540
int plan_node_id
Definition: plannodes.h:143
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
PlannedStmt * es_plannedstmt
Definition: execnodes.h:412
PlanState * planstate
Definition: execParallel.h:26
void InstrEndParallelQuery(BufferUsage *result)
Definition: instrument.c:177
static char * ExecSerializePlan(Plan *plan, EState *estate)
Definition: execParallel.c:122
ParallelExecutorInfo * ExecInitParallelPlan(PlanState *planstate, EState *estate, int nworkers)
Definition: execParallel.c:384
static shm_mq_handle ** ExecParallelSetupTupleQueues(ParallelContext *pcxt, bool reinitialize)
Definition: execParallel.c:320
EState * state
Definition: execnodes.h:815
List * es_range_table
Definition: execnodes.h:411
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:49
bool transientPlan
Definition: plannodes.h:55
Size EstimateParamListSpace(ParamListInfo paramLI)
Definition: params.c:95
int stmt_len
Definition: plannodes.h:98
struct Plan * planTree
Definition: plannodes.h:61
List * invalItems
Definition: plannodes.h:90
void InstrEndLoop(Instrumentation *instr)
Definition: instrument.c:114
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.c:100
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:458
ParallelContext * pcxt
Definition: execParallel.c:92
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:504
#define PARALLEL_KEY_INSTRUMENTATION
Definition: execParallel.c:54
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:594
const char * es_sourceText
Definition: execnodes.h:413
int nParamExec
Definition: plannodes.h:92
void pfree(void *pointer)
Definition: mcxt.c:950
MemoryContext es_query_cxt
Definition: execnodes.h:448
void ExecSeqScanInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:309
static bool ExecParallelInitializeDSM(PlanState *node, ExecParallelInitializeDSMContext *d)
Definition: execParallel.c:255
bool resjunk
Definition: primnodes.h:1374
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
Definition: execParallel.c:834
void ExecBitmapHeapInitializeDSM(BitmapHeapScanState *node, ParallelContext *pcxt)
BufferUsage * buffer_usage
Definition: execParallel.h:28
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:296
void ExecIndexOnlyScanEstimate(IndexOnlyScanState *node, ParallelContext *pcxt)
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
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:167
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define PARALLEL_KEY_PLANNEDSTMT
Definition: execParallel.c:50
ParamListInfo RestoreParamList(char **start_address)
Definition: params.c:224
int stmt_location
Definition: plannodes.h:97
void * shm_toc_lookup(shm_toc *toc, uint64 key)
Definition: shm_toc.c:218
static bool ExecParallelRetrieveInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
Definition: execParallel.c:585
bool hasReturning
Definition: plannodes.h:49
struct ExecParallelInitializeDSMContext ExecParallelInitializeDSMContext
void dsa_detach(dsa_area *area)
Definition: dsa.c:1884
void ExecForeignScanInitializeWorker(ForeignScanState *node, shm_toc *toc)
Node * utilityStmt
Definition: plannodes.h:94
int ParallelWorkerNumber
Definition: parallel.c:94
static bool ExecParallelInitializeWorker(PlanState *planstate, shm_toc *toc)
Definition: execParallel.c:778
bool parallel_aware
Definition: plannodes.h:137
#define PARALLEL_TUPLE_QUEUE_SIZE
Definition: execParallel.c:58
void InstrAccumParallelQuery(BufferUsage *result)
Definition: instrument.c:185
int es_instrument
Definition: execnodes.h:458
int nworkers_launched
Definition: parallel.h:37
static bool ExecParallelEstimate(PlanState *node, ExecParallelEstimateContext *e)
Definition: execParallel.c:205
dsa_area * dsa_create_in_place(void *place, size_t size, int tranche_id, dsm_segment *segment)
Definition: dsa.c:468
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:215
#define PARALLEL_KEY_BUFFER_USAGE
Definition: execParallel.c:52
#define IsParallelWorker()
Definition: parallel.h:52
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:398
#define PARALLEL_KEY_PARAMS
Definition: execParallel.c:51
List * lappend(List *list, void *datum)
Definition: list.c:128
const char * debug_query_string
Definition: postgres.c:83
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:188
#define InvalidSnapshot
Definition: snapshot.h:25
void InstrStartParallelQuery(void)
Definition: instrument.c:170
void InstrInit(Instrumentation *instr, int instrument_options)
Definition: instrument.c:54
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
bool canSetTag
Definition: plannodes.h:53
Instrumentation instrument[FLEXIBLE_ARRAY_MEMBER]
Definition: instrument.h:69
void * palloc0(Size size)
Definition: mcxt.c:878
CmdType commandType
Definition: plannodes.h:45
void ExecForeignScanInitializeDSM(ForeignScanState *node, ParallelContext *pcxt)
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:380
List * rowMarks
Definition: plannodes.h:86
Plan * plan
Definition: execnodes.h:813
void ExecParallelReinitialize(ParallelExecutorInfo *pei)
Definition: execParallel.c:372
void ExecCustomScanInitializeDSM(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:172
Size dsa_minimum_size(void)
Definition: dsa.c:1160
#define makeNode(_type_)
Definition: nodes.h:557
void ExecParallelCleanup(ParallelExecutorInfo *pei)
Definition: execParallel.c:662
List * subplans
Definition: plannodes.h:81
#define NULL
Definition: c.h:229
void SerializeParamList(ParamListInfo paramLI, char **start_address)
Definition: params.c:158
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:84
bool hasModifyingCTE
Definition: plannodes.h:51
void ExecBitmapHeapInitializeWorker(BitmapHeapScanState *node, shm_toc *toc)
void ExecForeignScanEstimate(ForeignScanState *node, ParallelContext *pcxt)
size_t Size
Definition: c.h:356
void ExecSeqScanEstimate(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:292
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:52
#define MAXALIGN(LEN)
Definition: c.h:588
List * rtable
Definition: plannodes.h:63
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:83
#define nodeTag(nodeptr)
Definition: nodes.h:514
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:284
List * targetlist
Definition: plannodes.h:144
const char * sourceText
Definition: execdesc.h:38
#define PARALLEL_KEY_DSA
Definition: execParallel.c:55
e
Definition: preproc-init.c:82
Definition: dsa.c:354
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:161
void * palloc(Size size)
Definition: mcxt.c:849
List * resultRelations
Definition: plannodes.h:66
bool parallelModeNeeded
Definition: plannodes.h:59
void ExecBitmapHeapEstimate(BitmapHeapScanState *node, ParallelContext *pcxt)
int i
#define PARALLEL_KEY_QUERY_TEXT
Definition: execParallel.c:56
Definition: shm_mq.c:69
char * nodeToString(const void *obj)
Definition: outfuncs.c:4219
void ExecCustomScanEstimate(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:159
ParamListInfo es_param_list_info
Definition: execnodes.h:442
void ExecIndexOnlyScanInitializeDSM(IndexOnlyScanState *node, ParallelContext *pcxt)
bool parallel_safe
Definition: plannodes.h:138
shm_mq_handle ** tqueue
Definition: execParallel.h:30
static DestReceiver * ExecParallelGetReceiver(dsm_segment *seg, shm_toc *toc)
Definition: execParallel.c:682
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:196
#define elog
Definition: elog.h:219
DestReceiver * CreateTupleQueueDestReceiver(shm_mq_handle *handle)
Definition: tqueue.c:606
#define copyObject(obj)
Definition: nodes.h:621
void ExecIndexScanEstimate(IndexScanState *node, ParallelContext *pcxt)
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.h:29
bool planstate_tree_walker(PlanState *planstate, bool(*walker)(), void *context)
Definition: nodeFuncs.c:3719
static QueryDesc * ExecParallelGetQueryDesc(shm_toc *toc, DestReceiver *receiver, int instrument_options)
Definition: execParallel.c:698
#define offsetof(type, field)
Definition: c.h:555
#define GetInstrumentationArray(sei)
Definition: execParallel.c:85
shm_toc * toc
Definition: parallel.h:44