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