PostgreSQL Source Code git master
Loading...
Searching...
No Matches
execParallel.c File Reference
Include dependency graph for execParallel.c:

Go to the source code of this file.

Data Structures

struct  FixedParallelExecutorState
 
struct  SharedExecutorInstrumentation
 
struct  ExecParallelEstimateContext
 
struct  ExecParallelInitializeDSMContext
 

Macros

#define PARALLEL_KEY_EXECUTOR_FIXED   UINT64CONST(0xE000000000000001)
 
#define PARALLEL_KEY_PLANNEDSTMT   UINT64CONST(0xE000000000000002)
 
#define PARALLEL_KEY_PARAMLISTINFO   UINT64CONST(0xE000000000000003)
 
#define PARALLEL_KEY_BUFFER_USAGE   UINT64CONST(0xE000000000000004)
 
#define PARALLEL_KEY_TUPLE_QUEUE   UINT64CONST(0xE000000000000005)
 
#define PARALLEL_KEY_INSTRUMENTATION   UINT64CONST(0xE000000000000006)
 
#define PARALLEL_KEY_DSA   UINT64CONST(0xE000000000000007)
 
#define PARALLEL_KEY_QUERY_TEXT   UINT64CONST(0xE000000000000008)
 
#define PARALLEL_KEY_JIT_INSTRUMENTATION   UINT64CONST(0xE000000000000009)
 
#define PARALLEL_KEY_WAL_USAGE   UINT64CONST(0xE00000000000000A)
 
#define PARALLEL_TUPLE_QUEUE_SIZE   65536
 
#define GetInstrumentationArray(sei)
 

Typedefs

typedef struct FixedParallelExecutorState FixedParallelExecutorState
 
typedef struct ExecParallelEstimateContext ExecParallelEstimateContext
 
typedef struct ExecParallelInitializeDSMContext ExecParallelInitializeDSMContext
 

Functions

static charExecSerializePlan (Plan *plan, EState *estate)
 
static bool ExecParallelEstimate (PlanState *planstate, ExecParallelEstimateContext *e)
 
static bool ExecParallelInitializeDSM (PlanState *planstate, ExecParallelInitializeDSMContext *d)
 
static shm_mq_handle ** ExecParallelSetupTupleQueues (ParallelContext *pcxt, bool reinitialize)
 
static bool ExecParallelReInitializeDSM (PlanState *planstate, ParallelContext *pcxt)
 
static bool ExecParallelRetrieveInstrumentation (PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
 
static DestReceiverExecParallelGetReceiver (dsm_segment *seg, shm_toc *toc)
 
static Size EstimateParamExecSpace (EState *estate, Bitmapset *params)
 
static dsa_pointer SerializeParamExecParams (EState *estate, Bitmapset *params, dsa_area *area)
 
static void RestoreParamExecParams (char *start_address, EState *estate)
 
ParallelExecutorInfoExecInitParallelPlan (PlanState *planstate, EState *estate, Bitmapset *sendParams, int nworkers, int64 tuples_needed)
 
void ExecParallelCreateReaders (ParallelExecutorInfo *pei)
 
void ExecParallelReinitialize (PlanState *planstate, ParallelExecutorInfo *pei, Bitmapset *sendParams)
 
static void ExecParallelRetrieveJitInstrumentation (PlanState *planstate, SharedJitInstrumentation *shared_jit)
 
void ExecParallelFinish (ParallelExecutorInfo *pei)
 
void ExecParallelCleanup (ParallelExecutorInfo *pei)
 
static QueryDescExecParallelGetQueryDesc (shm_toc *toc, DestReceiver *receiver, int instrument_options)
 
static bool ExecParallelReportInstrumentation (PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
 
static bool ExecParallelInitializeWorker (PlanState *planstate, ParallelWorkerContext *pwcxt)
 
void ParallelQueryMain (dsm_segment *seg, shm_toc *toc)
 

Macro Definition Documentation

◆ GetInstrumentationArray

#define GetInstrumentationArray (   sei)
Value:
(Instrumentation *) (((char *) sei) + sei->instrument_offset))
#define AssertVariableIsOfTypeMacro(varname, typename)
Definition c.h:977
static int fb(int x)

Definition at line 108 of file execParallel.c.

113{
114 ParallelContext *pcxt;
115 int nnodes;
117
118/* Context object for ExecParallelInitializeDSM. */
120{
123 int nnodes;
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;
255 /* even when not parallel-aware, for EXPLAIN ANALYZE */
257 e->pcxt);
258 break;
260 /* even when not parallel-aware, for EXPLAIN ANALYZE */
262 e->pcxt);
263 break;
265 if (planstate->plan->parallel_aware)
267 e->pcxt);
268 break;
270 if (planstate->plan->parallel_aware)
272 e->pcxt);
273 break;
274 case T_AppendState:
275 if (planstate->plan->parallel_aware)
276 ExecAppendEstimate((AppendState *) planstate,
277 e->pcxt);
278 break;
280 if (planstate->plan->parallel_aware)
282 e->pcxt);
283 break;
285 if (planstate->plan->parallel_aware)
287 e->pcxt);
288 break;
289 case T_HashJoinState:
290 if (planstate->plan->parallel_aware)
292 e->pcxt);
293 break;
294 case T_HashState:
295 /* even when not parallel-aware, for EXPLAIN ANALYZE */
296 ExecHashEstimate((HashState *) planstate, e->pcxt);
297 break;
298 case T_SortState:
299 /* even when not parallel-aware, for EXPLAIN ANALYZE */
300 ExecSortEstimate((SortState *) planstate, e->pcxt);
301 break;
303 /* even when not parallel-aware, for EXPLAIN ANALYZE */
305 break;
306 case T_AggState:
307 /* even when not parallel-aware, for EXPLAIN ANALYZE */
308 ExecAggEstimate((AggState *) planstate, e->pcxt);
309 break;
310 case T_MemoizeState:
311 /* even when not parallel-aware, for EXPLAIN ANALYZE */
312 ExecMemoizeEstimate((MemoizeState *) planstate, e->pcxt);
313 break;
314 default:
315 break;
316 }
317
318 return planstate_tree_walker(planstate, ExecParallelEstimate, e);
319}
320
321/*
322 * Estimate the amount of space required to serialize the indicated parameters.
323 */
324static Size
326{
327 int paramid;
328 Size sz = sizeof(int);
329
330 paramid = -1;
331 while ((paramid = bms_next_member(params, paramid)) >= 0)
332 {
333 Oid typeOid;
334 int16 typLen;
335 bool typByVal;
337
338 prm = &(estate->es_param_exec_vals[paramid]);
339 typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
340 paramid);
341
342 sz = add_size(sz, sizeof(int)); /* space for paramid */
343
344 /* space for datum/isnull */
345 if (OidIsValid(typeOid))
346 get_typlenbyval(typeOid, &typLen, &typByVal);
347 else
348 {
349 /* If no type OID, assume by-value, like copyParamList does. */
350 typLen = sizeof(Datum);
351 typByVal = true;
352 }
353 sz = add_size(sz,
354 datumEstimateSpace(prm->value, prm->isnull,
355 typByVal, typLen));
356 }
357 return sz;
358}
359
360/*
361 * Serialize specified PARAM_EXEC parameters.
362 *
363 * We write the number of parameters first, as a 4-byte integer, and then
364 * write details for each parameter in turn. The details for each parameter
365 * consist of a 4-byte paramid (location of param in execution time internal
366 * parameter array) and then the datum as serialized by datumSerialize().
367 */
368static dsa_pointer
369SerializeParamExecParams(EState *estate, Bitmapset *params, dsa_area *area)
370{
371 Size size;
372 int nparams;
373 int paramid;
375 dsa_pointer handle;
376 char *start_address;
377
378 /* Allocate enough space for the current parameter values. */
379 size = EstimateParamExecSpace(estate, params);
380 handle = dsa_allocate(area, size);
381 start_address = dsa_get_address(area, handle);
382
383 /* First write the number of parameters as a 4-byte integer. */
384 nparams = bms_num_members(params);
385 memcpy(start_address, &nparams, sizeof(int));
386 start_address += sizeof(int);
387
388 /* Write details for each parameter in turn. */
389 paramid = -1;
390 while ((paramid = bms_next_member(params, paramid)) >= 0)
391 {
392 Oid typeOid;
393 int16 typLen;
394 bool typByVal;
395
396 prm = &(estate->es_param_exec_vals[paramid]);
397 typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
398 paramid);
399
400 /* Write paramid. */
401 memcpy(start_address, &paramid, sizeof(int));
402 start_address += sizeof(int);
403
404 /* Write datum/isnull */
405 if (OidIsValid(typeOid))
406 get_typlenbyval(typeOid, &typLen, &typByVal);
407 else
408 {
409 /* If no type OID, assume by-value, like copyParamList does. */
410 typLen = sizeof(Datum);
411 typByVal = true;
412 }
413 datumSerialize(prm->value, prm->isnull, typByVal, typLen,
415 }
416
417 return handle;
418}
419
420/*
421 * Restore specified PARAM_EXEC parameters.
422 */
423static void
425{
426 int nparams;
427 int i;
428 int paramid;
429
430 memcpy(&nparams, start_address, sizeof(int));
431 start_address += sizeof(int);
432
433 for (i = 0; i < nparams; i++)
434 {
436
437 /* Read paramid */
438 memcpy(&paramid, start_address, sizeof(int));
439 start_address += sizeof(int);
440 prm = &(estate->es_param_exec_vals[paramid]);
441
442 /* Read datum/isnull. */
443 prm->value = datumRestore(&start_address, &prm->isnull);
444 prm->execPlan = NULL;
445 }
446}
447
448/*
449 * Initialize the dynamic shared memory segment that will be used to control
450 * parallel execution.
451 */
452static bool
455{
456 if (planstate == NULL)
457 return false;
458
459 /* If instrumentation is enabled, initialize slot for this node. */
460 if (d->instrumentation != NULL)
462 planstate->plan->plan_node_id;
463
464 /* Count this node. */
465 d->nnodes++;
466
467 /*
468 * Call initializers for DSM-using plan nodes.
469 *
470 * Most plan nodes won't do anything here, but plan nodes that allocated
471 * DSM may need to initialize shared state in the DSM before parallel
472 * workers are launched. They can allocate the space they previously
473 * estimated using shm_toc_allocate, and add the keys they previously
474 * estimated using shm_toc_insert, in each case targeting pcxt->toc.
475 */
476 switch (nodeTag(planstate))
477 {
478 case T_SeqScanState:
479 if (planstate->plan->parallel_aware)
481 d->pcxt);
482 break;
483 case T_IndexScanState:
484 /* even when not parallel-aware, for EXPLAIN ANALYZE */
486 break;
488 /* even when not parallel-aware, for EXPLAIN ANALYZE */
490 d->pcxt);
491 break;
493 /* even when not parallel-aware, for EXPLAIN ANALYZE */
495 break;
497 if (planstate->plan->parallel_aware)
499 d->pcxt);
500 break;
502 if (planstate->plan->parallel_aware)
504 d->pcxt);
505 break;
506 case T_AppendState:
507 if (planstate->plan->parallel_aware)
509 d->pcxt);
510 break;
512 if (planstate->plan->parallel_aware)
514 d->pcxt);
515 break;
517 if (planstate->plan->parallel_aware)
519 d->pcxt);
520 break;
521 case T_HashJoinState:
522 if (planstate->plan->parallel_aware)
524 d->pcxt);
525 break;
526 case T_HashState:
527 /* even when not parallel-aware, for EXPLAIN ANALYZE */
528 ExecHashInitializeDSM((HashState *) planstate, d->pcxt);
529 break;
530 case T_SortState:
531 /* even when not parallel-aware, for EXPLAIN ANALYZE */
532 ExecSortInitializeDSM((SortState *) planstate, d->pcxt);
533 break;
535 /* even when not parallel-aware, for EXPLAIN ANALYZE */
537 break;
538 case T_AggState:
539 /* even when not parallel-aware, for EXPLAIN ANALYZE */
540 ExecAggInitializeDSM((AggState *) planstate, d->pcxt);
541 break;
542 case T_MemoizeState:
543 /* even when not parallel-aware, for EXPLAIN ANALYZE */
544 ExecMemoizeInitializeDSM((MemoizeState *) planstate, d->pcxt);
545 break;
546 default:
547 break;
548 }
549
551}
552
553/*
554 * It sets up the response queues for backend workers to return tuples
555 * to the main backend and start the workers.
556 */
557static shm_mq_handle **
559{
561 char *tqueuespace;
562 int i;
563
564 /* Skip this if no workers. */
565 if (pcxt->nworkers == 0)
566 return NULL;
567
568 /* Allocate memory for shared memory queue handles. */
570 palloc(pcxt->nworkers * sizeof(shm_mq_handle *));
571
572 /*
573 * If not reinitializing, allocate space from the DSM for the queues;
574 * otherwise, find the already allocated space.
575 */
576 if (!reinitialize)
578 shm_toc_allocate(pcxt->toc,
580 pcxt->nworkers));
581 else
583
584 /* Create the queues, and become the receiver for each. */
585 for (i = 0; i < pcxt->nworkers; ++i)
586 {
587 shm_mq *mq;
588
592
594 responseq[i] = shm_mq_attach(mq, pcxt->seg, NULL);
595 }
596
597 /* Add array of queues to shm_toc, so others can find it. */
598 if (!reinitialize)
600
601 /* Return array of handles. */
602 return responseq;
603}
604
605/*
606 * Sets up the required infrastructure for backend workers to perform
607 * execution and return results to the main backend.
608 */
610ExecInitParallelPlan(PlanState *planstate, EState *estate,
611 Bitmapset *sendParams, int nworkers,
612 int64 tuples_needed)
613{
615 ParallelContext *pcxt;
619 char *pstmt_data;
620 char *pstmt_space;
624 SharedExecutorInstrumentation *instrumentation = NULL;
625 SharedJitInstrumentation *jit_instrumentation = NULL;
626 int pstmt_len;
628 int instrumentation_len = 0;
630 int instrument_offset = 0;
632 char *query_string;
633 int query_len;
634
635 /*
636 * Force any initplan outputs that we're going to pass to workers to be
637 * evaluated, if they weren't already.
638 *
639 * For simplicity, we use the EState's per-output-tuple ExprContext here.
640 * That risks intra-query memory leakage, since we might pass through here
641 * many times before that ExprContext gets reset; but ExecSetParamPlan
642 * doesn't normally leak any memory in the context (see its comments), so
643 * it doesn't seem worth complicating this function's API to pass it a
644 * shorter-lived ExprContext. This might need to change someday.
645 */
647
648 /* Allocate object for return value. */
650 pei->finished = false;
651 pei->planstate = planstate;
652
653 /* Fix up and serialize plan to be sent to workers. */
654 pstmt_data = ExecSerializePlan(planstate->plan, estate);
655
656 /* Create a parallel context. */
657 pcxt = CreateParallelContext("postgres", "ParallelQueryMain", nworkers);
658 pei->pcxt = pcxt;
659
660 /*
661 * Before telling the parallel context to create a dynamic shared memory
662 * segment, we need to figure out how big it should be. Estimate space
663 * for the various things we need to store.
664 */
665
666 /* Estimate space for fixed-size state. */
670
671 /* Estimate space for query text. */
672 query_len = strlen(estate->es_sourceText);
673 shm_toc_estimate_chunk(&pcxt->estimator, query_len + 1);
675
676 /* Estimate space for serialized PlannedStmt. */
680
681 /* Estimate space for serialized ParamListInfo. */
685
686 /*
687 * Estimate space for BufferUsage.
688 *
689 * If EXPLAIN is not in use and there are no extensions loaded that care,
690 * we could skip this. But we have no way of knowing whether anyone's
691 * looking at pgBufferUsage, so do it unconditionally.
692 */
694 mul_size(sizeof(BufferUsage), pcxt->nworkers));
696
697 /*
698 * Same thing for WalUsage.
699 */
701 mul_size(sizeof(WalUsage), pcxt->nworkers));
703
704 /* Estimate space for tuple queues. */
708
709 /*
710 * Give parallel-aware nodes a chance to add to the estimates, and get a
711 * count of how many PlanState nodes there are.
712 */
713 e.pcxt = pcxt;
714 e.nnodes = 0;
715 ExecParallelEstimate(planstate, &e);
716
717 /* Estimate space for instrumentation, if required. */
718 if (estate->es_instrument)
719 {
722 sizeof(int) * e.nnodes;
724 instrument_offset = instrumentation_len;
727 mul_size(e.nnodes, nworkers));
730
731 /* Estimate space for JIT instrumentation, if required. */
732 if (estate->es_jit_flags != PGJIT_NONE)
733 {
736 sizeof(JitInstrumentation) * nworkers;
739 }
740 }
741
742 /* Estimate space for DSA area. */
745
746 /*
747 * InitializeParallelDSM() passes the active snapshot to the parallel
748 * worker, which uses it to set es_snapshot. Make sure we don't set
749 * es_snapshot differently in the child.
750 */
752
753 /* Everyone's had a chance to ask for space, so now create the DSM. */
755
756 /*
757 * OK, now we have a dynamic shared memory segment, and it should be big
758 * enough to store all of the data we estimated we would want to put into
759 * it, plus whatever general stuff (not specifically executor-related) the
760 * ParallelContext itself needs to store there. None of the space we
761 * asked for has been allocated or initialized yet, though, so do that.
762 */
763
764 /* Store fixed-size state. */
766 fpes->tuples_needed = tuples_needed;
767 fpes->param_exec = InvalidDsaPointer;
768 fpes->eflags = estate->es_top_eflags;
769 fpes->jit_flags = estate->es_jit_flags;
771
772 /* Store query string */
773 query_string = shm_toc_allocate(pcxt->toc, query_len + 1);
774 memcpy(query_string, estate->es_sourceText, query_len + 1);
775 shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, query_string);
776
777 /* Store serialized PlannedStmt. */
781
782 /* Store serialized ParamListInfo. */
786
787 /* Allocate space for each worker's BufferUsage; no need to initialize. */
789 mul_size(sizeof(BufferUsage), pcxt->nworkers));
792
793 /* Same for WalUsage. */
795 mul_size(sizeof(WalUsage), pcxt->nworkers));
798
799 /* Set up the tuple queues that the workers will write into. */
800 pei->tqueue = ExecParallelSetupTupleQueues(pcxt, false);
801
802 /* We don't need the TupleQueueReaders yet, though. */
803 pei->reader = NULL;
804
805 /*
806 * If instrumentation options were supplied, allocate space for the data.
807 * It only gets partially initialized here; the rest happens during
808 * ExecParallelInitializeDSM.
809 */
810 if (estate->es_instrument)
811 {
812 Instrumentation *instrument;
813 int i;
814
815 instrumentation = shm_toc_allocate(pcxt->toc, instrumentation_len);
816 instrumentation->instrument_options = estate->es_instrument;
817 instrumentation->instrument_offset = instrument_offset;
818 instrumentation->num_workers = nworkers;
819 instrumentation->num_plan_nodes = e.nnodes;
820 instrument = GetInstrumentationArray(instrumentation);
821 for (i = 0; i < nworkers * e.nnodes; ++i)
822 InstrInit(&instrument[i], estate->es_instrument);
824 instrumentation);
825 pei->instrumentation = instrumentation;
826
827 if (estate->es_jit_flags != PGJIT_NONE)
828 {
829 jit_instrumentation = shm_toc_allocate(pcxt->toc,
831 jit_instrumentation->num_workers = nworkers;
832 memset(jit_instrumentation->jit_instr, 0,
833 sizeof(JitInstrumentation) * nworkers);
835 jit_instrumentation);
836 pei->jit_instrumentation = jit_instrumentation;
837 }
838 }
839
840 /*
841 * Create a DSA area that can be used by the leader and all workers.
842 * (However, if we failed to create a DSM and are using private memory
843 * instead, then skip this.)
844 */
845 if (pcxt->seg != NULL)
846 {
847 char *area_space;
848
853 pcxt->seg);
854
855 /*
856 * Serialize parameters, if any, using DSA storage. We don't dare use
857 * the main parallel query DSM for this because we might relaunch
858 * workers after the values have changed (and thus the amount of
859 * storage required has changed).
860 */
862 {
864 pei->area);
865 fpes->param_exec = pei->param_exec;
866 }
867 }
868
869 /*
870 * Give parallel-aware nodes a chance to initialize their shared data.
871 * This also initializes the elements of instrumentation->ps_instrument,
872 * if it exists.
873 */
874 d.pcxt = pcxt;
875 d.instrumentation = instrumentation;
876 d.nnodes = 0;
877
878 /* Install our DSA area while initializing the plan. */
879 estate->es_query_dsa = pei->area;
880 ExecParallelInitializeDSM(planstate, &d);
881 estate->es_query_dsa = NULL;
882
883 /*
884 * Make sure that the world hasn't shifted under our feet. This could
885 * probably just be an Assert(), but let's be conservative for now.
886 */
887 if (e.nnodes != d.nnodes)
888 elog(ERROR, "inconsistent count of PlanState nodes");
889
890 /* OK, we're ready to rock and roll. */
891 return pei;
892}
893
894/*
895 * Set up tuple queue readers to read the results of a parallel subplan.
896 *
897 * This is separate from ExecInitParallelPlan() because we can launch the
898 * worker processes and let them start doing something before we do this.
899 */
900void
902{
903 int nworkers = pei->pcxt->nworkers_launched;
904 int i;
905
906 Assert(pei->reader == NULL);
907
908 if (nworkers > 0)
909 {
910 pei->reader = (TupleQueueReader **)
911 palloc(nworkers * sizeof(TupleQueueReader *));
912
913 for (i = 0; i < nworkers; i++)
914 {
916 pei->pcxt->worker[i].bgwhandle);
917 pei->reader[i] = CreateTupleQueueReader(pei->tqueue[i]);
918 }
919 }
920}
921
922/*
923 * Re-initialize the parallel executor shared memory state before launching
924 * a fresh batch of workers.
925 */
926void
930{
931 EState *estate = planstate->state;
933
934 /* Old workers must already be shut down */
935 Assert(pei->finished);
936
937 /*
938 * Force any initplan outputs that we're going to pass to workers to be
939 * evaluated, if they weren't already (see comments in
940 * ExecInitParallelPlan).
941 */
943
945 pei->tqueue = ExecParallelSetupTupleQueues(pei->pcxt, true);
946 pei->reader = NULL;
947 pei->finished = false;
948
950
951 /* Free any serialized parameters from the last round. */
952 if (DsaPointerIsValid(fpes->param_exec))
953 {
954 dsa_free(pei->area, fpes->param_exec);
955 fpes->param_exec = InvalidDsaPointer;
956 }
957
958 /* Serialize current parameter values if required. */
960 {
962 pei->area);
963 fpes->param_exec = pei->param_exec;
964 }
965
966 /* Traverse plan tree and let each child node reset associated state. */
967 estate->es_query_dsa = pei->area;
968 ExecParallelReInitializeDSM(planstate, pei->pcxt);
969 estate->es_query_dsa = NULL;
970}
971
972/*
973 * Traverse plan tree to reinitialize per-node dynamic shared memory state
974 */
975static bool
977 ParallelContext *pcxt)
978{
979 if (planstate == NULL)
980 return false;
981
982 /*
983 * Call reinitializers for DSM-using plan nodes.
984 */
985 switch (nodeTag(planstate))
986 {
987 case T_SeqScanState:
988 if (planstate->plan->parallel_aware)
990 pcxt);
991 break;
992 case T_IndexScanState:
993 if (planstate->plan->parallel_aware)
995 pcxt);
996 break;
998 if (planstate->plan->parallel_aware)
1000 pcxt);
1001 break;
1002 case T_ForeignScanState:
1003 if (planstate->plan->parallel_aware)
1005 pcxt);
1006 break;
1008 if (planstate->plan->parallel_aware)
1010 pcxt);
1011 break;
1012 case T_AppendState:
1013 if (planstate->plan->parallel_aware)
1014 ExecAppendReInitializeDSM((AppendState *) planstate, pcxt);
1015 break;
1016 case T_CustomScanState:
1017 if (planstate->plan->parallel_aware)
1019 pcxt);
1020 break;
1022 if (planstate->plan->parallel_aware)
1024 pcxt);
1025 break;
1026 case T_HashJoinState:
1027 if (planstate->plan->parallel_aware)
1029 pcxt);
1030 break;
1032 case T_HashState:
1033 case T_SortState:
1035 case T_MemoizeState:
1036 /* these nodes have DSM state, but no reinitialization is required */
1037 break;
1038
1039 default:
1040 break;
1041 }
1042
1043 return planstate_tree_walker(planstate, ExecParallelReInitializeDSM, pcxt);
1044}
1045
1046/*
1047 * Copy instrumentation information about this node and its descendants from
1048 * dynamic shared memory.
1049 */
1050static bool
1052 SharedExecutorInstrumentation *instrumentation)
1053{
1054 Instrumentation *instrument;
1055 int i;
1056 int n;
1057 int ibytes;
1058 int plan_node_id = planstate->plan->plan_node_id;
1059 MemoryContext oldcontext;
1060
1061 /* Find the instrumentation for this node. */
1062 for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1063 if (instrumentation->plan_node_id[i] == plan_node_id)
1064 break;
1065 if (i >= instrumentation->num_plan_nodes)
1066 elog(ERROR, "plan node %d not found", plan_node_id);
1067
1068 /* Accumulate the statistics from all workers. */
1069 instrument = GetInstrumentationArray(instrumentation);
1070 instrument += i * instrumentation->num_workers;
1071 for (n = 0; n < instrumentation->num_workers; ++n)
1072 InstrAggNode(planstate->instrument, &instrument[n]);
1073
1074 /*
1075 * Also store the per-worker detail.
1076 *
1077 * Worker instrumentation should be allocated in the same context as the
1078 * regular instrumentation information, which is the per-query context.
1079 * Switch into per-query memory context.
1080 */
1081 oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
1082 ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));
1083 planstate->worker_instrument =
1085 MemoryContextSwitchTo(oldcontext);
1086
1087 planstate->worker_instrument->num_workers = instrumentation->num_workers;
1088 memcpy(&planstate->worker_instrument->instrument, instrument, ibytes);
1089
1090 /* Perform any node-type-specific work that needs to be done. */
1091 switch (nodeTag(planstate))
1092 {
1093 case T_IndexScanState:
1095 break;
1098 break;
1101 break;
1102 case T_SortState:
1104 break;
1107 break;
1108 case T_HashState:
1110 break;
1111 case T_AggState:
1113 break;
1114 case T_MemoizeState:
1116 break;
1119 break;
1120 default:
1121 break;
1122 }
1123
1125 instrumentation);
1126}
1127
1128/*
1129 * Add up the workers' JIT instrumentation from dynamic shared memory.
1130 */
1131static void
1134{
1136 int ibytes;
1137
1138 int n;
1139
1140 /*
1141 * Accumulate worker JIT instrumentation into the combined JIT
1142 * instrumentation, allocating it if required.
1143 */
1144 if (!planstate->state->es_jit_worker_instr)
1145 planstate->state->es_jit_worker_instr =
1147 combined = planstate->state->es_jit_worker_instr;
1148
1149 /* Accumulate all the workers' instrumentations. */
1150 for (n = 0; n < shared_jit->num_workers; ++n)
1151 InstrJitAgg(combined, &shared_jit->jit_instr[n]);
1152
1153 /*
1154 * Store the per-worker detail.
1155 *
1156 * Similar to ExecParallelRetrieveInstrumentation(), allocate the
1157 * instrumentation in per-query context.
1158 */
1160 + mul_size(shared_jit->num_workers, sizeof(JitInstrumentation));
1161 planstate->worker_jit_instrument =
1163
1165}
1166
1167/*
1168 * Finish parallel execution. We wait for parallel workers to finish, and
1169 * accumulate their buffer/WAL usage.
1170 */
1171void
1173{
1174 int nworkers = pei->pcxt->nworkers_launched;
1175 int i;
1176
1177 /* Make this be a no-op if called twice in a row. */
1178 if (pei->finished)
1179 return;
1180
1181 /*
1182 * Detach from tuple queues ASAP, so that any still-active workers will
1183 * notice that no further results are wanted.
1184 */
1185 if (pei->tqueue != NULL)
1186 {
1187 for (i = 0; i < nworkers; i++)
1188 shm_mq_detach(pei->tqueue[i]);
1189 pfree(pei->tqueue);
1190 pei->tqueue = NULL;
1191 }
1192
1193 /*
1194 * While we're waiting for the workers to finish, let's get rid of the
1195 * tuple queue readers. (Any other local cleanup could be done here too.)
1196 */
1197 if (pei->reader != NULL)
1198 {
1199 for (i = 0; i < nworkers; i++)
1201 pfree(pei->reader);
1202 pei->reader = NULL;
1203 }
1204
1205 /* Now wait for the workers to finish. */
1207
1208 /*
1209 * Next, accumulate buffer/WAL usage. (This must wait for the workers to
1210 * finish, or we might get incomplete data.)
1211 */
1212 for (i = 0; i < nworkers; i++)
1214
1215 pei->finished = true;
1216}
1217
1218/*
1219 * Accumulate instrumentation, and then clean up whatever ParallelExecutorInfo
1220 * resources still exist after ExecParallelFinish. We separate these
1221 * routines because someone might want to examine the contents of the DSM
1222 * after ExecParallelFinish and before calling this routine.
1223 */
1224void
1226{
1227 /* Accumulate instrumentation, if any. */
1228 if (pei->instrumentation)
1230 pei->instrumentation);
1231
1232 /* Accumulate JIT instrumentation, if any. */
1233 if (pei->jit_instrumentation)
1235 pei->jit_instrumentation);
1236
1237 /* Free any serialized parameters. */
1238 if (DsaPointerIsValid(pei->param_exec))
1239 {
1240 dsa_free(pei->area, pei->param_exec);
1242 }
1243 if (pei->area != NULL)
1244 {
1245 dsa_detach(pei->area);
1246 pei->area = NULL;
1247 }
1248 if (pei->pcxt != NULL)
1249 {
1251 pei->pcxt = NULL;
1252 }
1253 pfree(pei);
1254}
1255
1256/*
1257 * Create a DestReceiver to write tuples we produce to the shm_mq designated
1258 * for that purpose.
1259 */
1260static DestReceiver *
1262{
1263 char *mqspace;
1264 shm_mq *mq;
1265
1268 mq = (shm_mq *) mqspace;
1271}
1272
1273/*
1274 * Create a QueryDesc for the PlannedStmt we are to execute, and return it.
1275 */
1276static QueryDesc *
1278 int instrument_options)
1279{
1280 char *pstmtspace;
1281 char *paramspace;
1282 PlannedStmt *pstmt;
1283 ParamListInfo paramLI;
1284 char *queryString;
1285
1286 /* Get the query string from shared memory */
1287 queryString = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, false);
1288
1289 /* Reconstruct leader-supplied PlannedStmt. */
1291 pstmt = (PlannedStmt *) stringToNode(pstmtspace);
1292
1293 /* Reconstruct ParamListInfo. */
1295 paramLI = RestoreParamList(&paramspace);
1296
1297 /* Create a QueryDesc for the query. */
1298 return CreateQueryDesc(pstmt,
1299 queryString,
1301 receiver, paramLI, NULL, instrument_options);
1302}
1303
1304/*
1305 * Copy instrumentation information from this node and its descendants into
1306 * dynamic shared memory, so that the parallel leader can retrieve it.
1307 */
1308static bool
1310 SharedExecutorInstrumentation *instrumentation)
1311{
1312 int i;
1313 int plan_node_id = planstate->plan->plan_node_id;
1314 Instrumentation *instrument;
1315
1316 InstrEndLoop(planstate->instrument);
1317
1318 /*
1319 * If we shuffled the plan_node_id values in ps_instrument into sorted
1320 * order, we could use binary search here. This might matter someday if
1321 * we're pushing down sufficiently large plan trees. For now, do it the
1322 * slow, dumb way.
1323 */
1324 for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1325 if (instrumentation->plan_node_id[i] == plan_node_id)
1326 break;
1327 if (i >= instrumentation->num_plan_nodes)
1328 elog(ERROR, "plan node %d not found", plan_node_id);
1329
1330 /*
1331 * Add our statistics to the per-node, per-worker totals. It's possible
1332 * that this could happen more than once if we relaunched workers.
1333 */
1334 instrument = GetInstrumentationArray(instrumentation);
1335 instrument += i * instrumentation->num_workers;
1338 InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
1339
1341 instrumentation);
1342}
1343
1344/*
1345 * Initialize the PlanState and its descendants with the information
1346 * retrieved from shared memory. This has to be done once the PlanState
1347 * is allocated and initialized by executor; that is, after ExecutorStart().
1348 */
1349static bool
1351{
1352 if (planstate == NULL)
1353 return false;
1354
1355 switch (nodeTag(planstate))
1356 {
1357 case T_SeqScanState:
1358 if (planstate->plan->parallel_aware)
1360 break;
1361 case T_IndexScanState:
1362 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1364 break;
1366 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1368 pwcxt);
1369 break;
1371 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1373 pwcxt);
1374 break;
1375 case T_ForeignScanState:
1376 if (planstate->plan->parallel_aware)
1378 pwcxt);
1379 break;
1381 if (planstate->plan->parallel_aware)
1383 pwcxt);
1384 break;
1385 case T_AppendState:
1386 if (planstate->plan->parallel_aware)
1388 break;
1389 case T_CustomScanState:
1390 if (planstate->plan->parallel_aware)
1392 pwcxt);
1393 break;
1395 if (planstate->plan->parallel_aware)
1397 pwcxt);
1398 break;
1399 case T_HashJoinState:
1400 if (planstate->plan->parallel_aware)
1402 pwcxt);
1403 break;
1404 case T_HashState:
1405 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1407 break;
1408 case T_SortState:
1409 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1411 break;
1413 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1415 pwcxt);
1416 break;
1417 case T_AggState:
1418 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1419 ExecAggInitializeWorker((AggState *) planstate, pwcxt);
1420 break;
1421 case T_MemoizeState:
1422 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1424 break;
1425 default:
1426 break;
1427 }
1428
1430 pwcxt);
1431}
1432
1433/*
1434 * Main entrypoint for parallel query worker processes.
1435 *
1436 * We reach this function from ParallelWorkerMain, so the setup necessary to
1437 * create a sensible parallel environment has already been done;
1438 * ParallelWorkerMain worries about stuff like the transaction state, combo
1439 * CID mappings, and GUC values, so we don't need to deal with any of that
1440 * here.
1441 *
1442 * Our job is to deal with concerns specific to the executor. The parallel
1443 * group leader will have stored a serialized PlannedStmt, and it's our job
1444 * to execute that plan and write the resulting tuples to the appropriate
1445 * tuple queue. Various bits of supporting information that we need in order
1446 * to do this are also stored in the dsm_segment and can be accessed through
1447 * the shm_toc.
1448 */
1449void
1451{
1453 BufferUsage *buffer_usage;
1454 WalUsage *wal_usage;
1456 QueryDesc *queryDesc;
1457 SharedExecutorInstrumentation *instrumentation;
1458 SharedJitInstrumentation *jit_instrumentation;
1459 int instrument_options = 0;
1460 void *area_space;
1461 dsa_area *area;
1463
1464 /* Get fixed-size state. */
1466
1467 /* Set up DestReceiver, SharedExecutorInstrumentation, and QueryDesc. */
1469 instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_INSTRUMENTATION, true);
1470 if (instrumentation != NULL)
1471 instrument_options = instrumentation->instrument_options;
1472 jit_instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_JIT_INSTRUMENTATION,
1473 true);
1474 queryDesc = ExecParallelGetQueryDesc(toc, receiver, instrument_options);
1475
1476 /* Setting debug_query_string for individual workers */
1477 debug_query_string = queryDesc->sourceText;
1478
1479 /* Report workers' query for monitoring purposes */
1481
1482 /* Attach to the dynamic shared memory area. */
1484 area = dsa_attach_in_place(area_space, seg);
1485
1486 /* Start up the executor */
1487 queryDesc->plannedstmt->jitFlags = fpes->jit_flags;
1488 ExecutorStart(queryDesc, fpes->eflags);
1489
1490 /* Special executor initialization steps for parallel workers */
1491 queryDesc->planstate->state->es_query_dsa = area;
1492 if (DsaPointerIsValid(fpes->param_exec))
1493 {
1494 char *paramexec_space;
1495
1496 paramexec_space = dsa_get_address(area, fpes->param_exec);
1498 }
1499 pwcxt.toc = toc;
1500 pwcxt.seg = seg;
1502
1503 /* Pass down any tuple bound */
1504 ExecSetTupleBound(fpes->tuples_needed, queryDesc->planstate);
1505
1506 /*
1507 * Prepare to track buffer/WAL usage during query execution.
1508 *
1509 * We do this after starting up the executor to match what happens in the
1510 * leader, which also doesn't count buffer accesses and WAL activity that
1511 * occur during executor startup.
1512 */
1514
1515 /*
1516 * Run the plan. If we specified a tuple bound, be careful not to demand
1517 * more tuples than that.
1518 */
1519 ExecutorRun(queryDesc,
1521 fpes->tuples_needed < 0 ? (int64) 0 : fpes->tuples_needed);
1522
1523 /* Shut down the executor */
1524 ExecutorFinish(queryDesc);
1525
1526 /* Report buffer/WAL usage during parallel execution. */
1527 buffer_usage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
1528 wal_usage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
1530 &wal_usage[ParallelWorkerNumber]);
1531
1532 /* Report instrumentation data if any instrumentation options are set. */
1533 if (instrumentation != NULL)
1535 instrumentation);
1536
1537 /* Report JIT instrumentation data if any */
1538 if (queryDesc->estate->es_jit && jit_instrumentation != NULL)
1539 {
1541 jit_instrumentation->jit_instr[ParallelWorkerNumber] =
1542 queryDesc->estate->es_jit->instr;
1543 }
1544
1545 /* Must do this after capturing instrumentation. */
1546 ExecutorEnd(queryDesc);
1547
1548 /* Cleanup. */
1549 dsa_detach(area);
1550 FreeQueryDesc(queryDesc);
1551 receiver->rDestroy(receiver);
1552}
int ParallelWorkerNumber
Definition parallel.c:115
void InitializeParallelDSM(ParallelContext *pcxt)
Definition parallel.c:211
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition parallel.c:803
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition parallel.c:509
void DestroyParallelContext(ParallelContext *pcxt)
Definition parallel.c:957
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:1305
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:750
#define bms_is_empty(a)
Definition bitmapset.h:118
#define MAXALIGN(LEN)
Definition c.h:826
#define Assert(condition)
Definition c.h:873
int64_t int64
Definition c.h:543
int16_t int16
Definition c.h:541
#define OidIsValid(objectId)
Definition c.h:788
size_t Size
Definition c.h:619
Datum datumRestore(char **start_address, bool *isnull)
Definition datum.c:523
void datumSerialize(Datum value, bool isnull, bool typByVal, int typLen, char **start_address)
Definition datum.c:461
Size datumEstimateSpace(Datum value, bool isnull, bool typByVal, int typLen)
Definition datum.c:414
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:2002
void dsa_free(dsa_area *area, dsa_pointer dp)
Definition dsa.c:841
size_t dsa_minimum_size(void)
Definition dsa.c:1246
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
static bool ExecParallelReInitializeDSM(PlanState *planstate, ParallelContext *pcxt)
#define PARALLEL_KEY_JIT_INSTRUMENTATION
#define PARALLEL_KEY_PARAMLISTINFO
#define PARALLEL_TUPLE_QUEUE_SIZE
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)
void ExecParallelCleanup(ParallelExecutorInfo *pei)
#define PARALLEL_KEY_INSTRUMENTATION
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)
#define PARALLEL_KEY_PLANNEDSTMT
static bool ExecParallelEstimate(PlanState *planstate, ExecParallelEstimateContext *e)
#define GetInstrumentationArray(sei)
void ExecParallelReinitialize(PlanState *planstate, ParallelExecutorInfo *pei, Bitmapset *sendParams)
#define PARALLEL_KEY_DSA
static bool ExecParallelInitializeWorker(PlanState *planstate, ParallelWorkerContext *pwcxt)
void ExecParallelCreateReaders(ParallelExecutorInfo *pei)
#define PARALLEL_KEY_TUPLE_QUEUE
#define PARALLEL_KEY_EXECUTOR_FIXED
static char * ExecSerializePlan(Plan *plan, EState *estate)
ParallelExecutorInfo * ExecInitParallelPlan(PlanState *planstate, EState *estate, Bitmapset *sendParams, int nworkers, int64 tuples_needed)
#define PARALLEL_KEY_QUERY_TEXT
static Size EstimateParamExecSpace(EState *estate, Bitmapset *params)
void ExecParallelFinish(ParallelExecutorInfo *pei)
static bool ExecParallelReportInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
#define PARALLEL_KEY_WAL_USAGE
static void ExecParallelRetrieveJitInstrumentation(PlanState *planstate, SharedJitInstrumentation *shared_jit)
static bool ExecParallelInitializeDSM(PlanState *planstate, ExecParallelInitializeDSMContext *d)
static void RestoreParamExecParams(char *start_address, EState *estate)
void ExecSetTupleBound(int64 tuples_needed, PlanState *child_node)
#define GetPerTupleExprContext(estate)
Definition executor.h:656
#define palloc0_object(type)
Definition fe_memutils.h:75
#define IsParallelWorker()
Definition parallel.h:60
void InstrAccumParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition instrument.c:215
void InstrEndLoop(Instrumentation *instr)
Definition instrument.c:140
void InstrAggNode(Instrumentation *dst, Instrumentation *add)
Definition instrument.c:165
void InstrEndParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition instrument.c:205
void InstrStartParallelQuery(void)
Definition instrument.c:197
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
#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:2401
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1266
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
void ExecAggEstimate(AggState *node, ParallelContext *pcxt)
Definition nodeAgg.c:4779
void ExecAggInitializeWorker(AggState *node, ParallelWorkerContext *pwcxt)
Definition nodeAgg.c:4825
void ExecAggRetrieveInstrumentation(AggState *node)
Definition nodeAgg.c:4838
void ExecAggInitializeDSM(AggState *node, ParallelContext *pcxt)
Definition nodeAgg.c:4800
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)
void ExecMemoizeEstimate(MemoizeState *node, ParallelContext *pcxt)
void ExecMemoizeRetrieveInstrumentation(MemoizeState *node)
void ExecMemoizeInitializeWorker(MemoizeState *node, ParallelWorkerContext *pwcxt)
void ExecSeqScanReInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
void ExecSeqScanInitializeWorker(SeqScanState *node, ParallelWorkerContext *pwcxt)
void ExecSeqScanInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
void ExecSeqScanEstimate(SeqScanState *node, ParallelContext *pcxt)
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)
void ExecTidRangeScanEstimate(TidRangeScanState *node, ParallelContext *pcxt)
void ExecTidRangeScanInitializeWorker(TidRangeScanState *node, ParallelWorkerContext *pwcxt)
void ExecTidRangeScanInitializeDSM(TidRangeScanState *node, ParallelContext *pcxt)
void ExecTidRangeScanReInitializeDSM(TidRangeScanState *node, ParallelContext *pcxt)
#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:802
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:228
ParamListInfo RestoreParamList(char **start_address)
Definition params.c:290
#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
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
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:495
Size mul_size(Size s1, Size s2)
Definition shmem.c:510
Snapshot GetActiveSnapshot(void)
Definition snapmgr.c:800
#define InvalidSnapshot
Definition snapshot.h:119
PGPROC * MyProc
Definition proc.c:67
List * es_part_prune_infos
Definition execnodes.h:672
struct dsa_area * es_query_dsa
Definition execnodes.h:754
int es_top_eflags
Definition execnodes.h:721
struct JitContext * es_jit
Definition execnodes.h:766
int es_instrument
Definition execnodes.h:722
PlannedStmt * es_plannedstmt
Definition execnodes.h:671
struct JitInstrumentation * es_jit_worker_instr
Definition execnodes.h:767
ParamExecData * es_param_exec_vals
Definition execnodes.h:707
List * es_range_table
Definition execnodes.h:664
List * es_rteperminfos
Definition execnodes.h:670
Bitmapset * es_unpruned_relids
Definition execnodes.h:675
ParamListInfo es_param_list_info
Definition execnodes.h:706
MemoryContext es_query_cxt
Definition execnodes.h:712
int es_jit_flags
Definition execnodes.h:765
const char * es_sourceText
Definition execnodes.h:679
Snapshot es_snapshot
Definition execnodes.h:662
SharedExecutorInstrumentation * instrumentation
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
struct SharedJitInstrumentation * jit_instrumentation
BufferUsage * buffer_usage
dsa_pointer param_exec
ParallelContext * pcxt
shm_mq_handle ** tqueue
SharedExecutorInstrumentation * instrumentation
struct TupleQueueReader ** reader
BackgroundWorkerHandle * bgwhandle
Definition parallel.h:27
struct SharedJitInstrumentation * worker_jit_instrument
Definition execnodes.h:1181
Instrumentation * instrument
Definition execnodes.h:1177
Plan * plan
Definition execnodes.h:1167
EState * state
Definition execnodes.h:1169
WorkerInstrumentation * worker_instrument
Definition execnodes.h:1178
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
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]
JitInstrumentation jit_instr[FLEXIBLE_ARRAY_MEMBER]
Definition jit.h:54
Instrumentation instrument[FLEXIBLE_ARRAY_MEMBER]
Definition instrument.h:100
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

◆ PARALLEL_KEY_BUFFER_USAGE

#define PARALLEL_KEY_BUFFER_USAGE   UINT64CONST(0xE000000000000004)

Definition at line 62 of file execParallel.c.

◆ PARALLEL_KEY_DSA

#define PARALLEL_KEY_DSA   UINT64CONST(0xE000000000000007)

Definition at line 65 of file execParallel.c.

◆ PARALLEL_KEY_EXECUTOR_FIXED

#define PARALLEL_KEY_EXECUTOR_FIXED   UINT64CONST(0xE000000000000001)

Definition at line 59 of file execParallel.c.

◆ PARALLEL_KEY_INSTRUMENTATION

#define PARALLEL_KEY_INSTRUMENTATION   UINT64CONST(0xE000000000000006)

Definition at line 64 of file execParallel.c.

◆ PARALLEL_KEY_JIT_INSTRUMENTATION

#define PARALLEL_KEY_JIT_INSTRUMENTATION   UINT64CONST(0xE000000000000009)

Definition at line 67 of file execParallel.c.

◆ PARALLEL_KEY_PARAMLISTINFO

#define PARALLEL_KEY_PARAMLISTINFO   UINT64CONST(0xE000000000000003)

Definition at line 61 of file execParallel.c.

◆ PARALLEL_KEY_PLANNEDSTMT

#define PARALLEL_KEY_PLANNEDSTMT   UINT64CONST(0xE000000000000002)

Definition at line 60 of file execParallel.c.

◆ PARALLEL_KEY_QUERY_TEXT

#define PARALLEL_KEY_QUERY_TEXT   UINT64CONST(0xE000000000000008)

Definition at line 66 of file execParallel.c.

◆ PARALLEL_KEY_TUPLE_QUEUE

#define PARALLEL_KEY_TUPLE_QUEUE   UINT64CONST(0xE000000000000005)

Definition at line 63 of file execParallel.c.

◆ PARALLEL_KEY_WAL_USAGE

#define PARALLEL_KEY_WAL_USAGE   UINT64CONST(0xE00000000000000A)

Definition at line 68 of file execParallel.c.

◆ PARALLEL_TUPLE_QUEUE_SIZE

#define PARALLEL_TUPLE_QUEUE_SIZE   65536

Definition at line 70 of file execParallel.c.

Typedef Documentation

◆ ExecParallelEstimateContext

◆ ExecParallelInitializeDSMContext

◆ FixedParallelExecutorState

Function Documentation

◆ EstimateParamExecSpace()

static Size EstimateParamExecSpace ( EState estate,
Bitmapset params 
)
static

Definition at line 326 of file execParallel.c.

327{
328 int paramid;
329 Size sz = sizeof(int);
330
331 paramid = -1;
332 while ((paramid = bms_next_member(params, paramid)) >= 0)
333 {
334 Oid typeOid;
335 int16 typLen;
336 bool typByVal;
338
339 prm = &(estate->es_param_exec_vals[paramid]);
340 typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
341 paramid);
342
343 sz = add_size(sz, sizeof(int)); /* space for paramid */
344
345 /* space for datum/isnull */
346 if (OidIsValid(typeOid))
347 get_typlenbyval(typeOid, &typLen, &typByVal);
348 else
349 {
350 /* If no type OID, assume by-value, like copyParamList does. */
351 typLen = sizeof(Datum);
352 typByVal = true;
353 }
354 sz = add_size(sz,
355 datumEstimateSpace(prm->value, prm->isnull,
356 typByVal, typLen));
357 }
358 return sz;
359}

References add_size(), bms_next_member(), datumEstimateSpace(), EState::es_param_exec_vals, EState::es_plannedstmt, fb(), get_typlenbyval(), list_nth_oid(), OidIsValid, and PlannedStmt::paramExecTypes.

Referenced by SerializeParamExecParams().

◆ ExecInitParallelPlan()

ParallelExecutorInfo * ExecInitParallelPlan ( PlanState planstate,
EState estate,
Bitmapset sendParams,
int  nworkers,
int64  tuples_needed 
)

Definition at line 611 of file execParallel.c.

614{
616 ParallelContext *pcxt;
620 char *pstmt_data;
621 char *pstmt_space;
625 SharedExecutorInstrumentation *instrumentation = NULL;
626 SharedJitInstrumentation *jit_instrumentation = NULL;
627 int pstmt_len;
629 int instrumentation_len = 0;
631 int instrument_offset = 0;
633 char *query_string;
634 int query_len;
635
636 /*
637 * Force any initplan outputs that we're going to pass to workers to be
638 * evaluated, if they weren't already.
639 *
640 * For simplicity, we use the EState's per-output-tuple ExprContext here.
641 * That risks intra-query memory leakage, since we might pass through here
642 * many times before that ExprContext gets reset; but ExecSetParamPlan
643 * doesn't normally leak any memory in the context (see its comments), so
644 * it doesn't seem worth complicating this function's API to pass it a
645 * shorter-lived ExprContext. This might need to change someday.
646 */
648
649 /* Allocate object for return value. */
651 pei->finished = false;
652 pei->planstate = planstate;
653
654 /* Fix up and serialize plan to be sent to workers. */
655 pstmt_data = ExecSerializePlan(planstate->plan, estate);
656
657 /* Create a parallel context. */
658 pcxt = CreateParallelContext("postgres", "ParallelQueryMain", nworkers);
659 pei->pcxt = pcxt;
660
661 /*
662 * Before telling the parallel context to create a dynamic shared memory
663 * segment, we need to figure out how big it should be. Estimate space
664 * for the various things we need to store.
665 */
666
667 /* Estimate space for fixed-size state. */
671
672 /* Estimate space for query text. */
673 query_len = strlen(estate->es_sourceText);
674 shm_toc_estimate_chunk(&pcxt->estimator, query_len + 1);
676
677 /* Estimate space for serialized PlannedStmt. */
681
682 /* Estimate space for serialized ParamListInfo. */
686
687 /*
688 * Estimate space for BufferUsage.
689 *
690 * If EXPLAIN is not in use and there are no extensions loaded that care,
691 * we could skip this. But we have no way of knowing whether anyone's
692 * looking at pgBufferUsage, so do it unconditionally.
693 */
695 mul_size(sizeof(BufferUsage), pcxt->nworkers));
697
698 /*
699 * Same thing for WalUsage.
700 */
702 mul_size(sizeof(WalUsage), pcxt->nworkers));
704
705 /* Estimate space for tuple queues. */
709
710 /*
711 * Give parallel-aware nodes a chance to add to the estimates, and get a
712 * count of how many PlanState nodes there are.
713 */
714 e.pcxt = pcxt;
715 e.nnodes = 0;
716 ExecParallelEstimate(planstate, &e);
717
718 /* Estimate space for instrumentation, if required. */
719 if (estate->es_instrument)
720 {
723 sizeof(int) * e.nnodes;
725 instrument_offset = instrumentation_len;
728 mul_size(e.nnodes, nworkers));
731
732 /* Estimate space for JIT instrumentation, if required. */
733 if (estate->es_jit_flags != PGJIT_NONE)
734 {
737 sizeof(JitInstrumentation) * nworkers;
740 }
741 }
742
743 /* Estimate space for DSA area. */
746
747 /*
748 * InitializeParallelDSM() passes the active snapshot to the parallel
749 * worker, which uses it to set es_snapshot. Make sure we don't set
750 * es_snapshot differently in the child.
751 */
753
754 /* Everyone's had a chance to ask for space, so now create the DSM. */
756
757 /*
758 * OK, now we have a dynamic shared memory segment, and it should be big
759 * enough to store all of the data we estimated we would want to put into
760 * it, plus whatever general stuff (not specifically executor-related) the
761 * ParallelContext itself needs to store there. None of the space we
762 * asked for has been allocated or initialized yet, though, so do that.
763 */
764
765 /* Store fixed-size state. */
767 fpes->tuples_needed = tuples_needed;
768 fpes->param_exec = InvalidDsaPointer;
769 fpes->eflags = estate->es_top_eflags;
770 fpes->jit_flags = estate->es_jit_flags;
772
773 /* Store query string */
774 query_string = shm_toc_allocate(pcxt->toc, query_len + 1);
775 memcpy(query_string, estate->es_sourceText, query_len + 1);
776 shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, query_string);
777
778 /* Store serialized PlannedStmt. */
782
783 /* Store serialized ParamListInfo. */
787
788 /* Allocate space for each worker's BufferUsage; no need to initialize. */
790 mul_size(sizeof(BufferUsage), pcxt->nworkers));
793
794 /* Same for WalUsage. */
796 mul_size(sizeof(WalUsage), pcxt->nworkers));
799
800 /* Set up the tuple queues that the workers will write into. */
801 pei->tqueue = ExecParallelSetupTupleQueues(pcxt, false);
802
803 /* We don't need the TupleQueueReaders yet, though. */
804 pei->reader = NULL;
805
806 /*
807 * If instrumentation options were supplied, allocate space for the data.
808 * It only gets partially initialized here; the rest happens during
809 * ExecParallelInitializeDSM.
810 */
811 if (estate->es_instrument)
812 {
813 Instrumentation *instrument;
814 int i;
815
816 instrumentation = shm_toc_allocate(pcxt->toc, instrumentation_len);
817 instrumentation->instrument_options = estate->es_instrument;
818 instrumentation->instrument_offset = instrument_offset;
819 instrumentation->num_workers = nworkers;
820 instrumentation->num_plan_nodes = e.nnodes;
821 instrument = GetInstrumentationArray(instrumentation);
822 for (i = 0; i < nworkers * e.nnodes; ++i)
823 InstrInit(&instrument[i], estate->es_instrument);
825 instrumentation);
826 pei->instrumentation = instrumentation;
827
828 if (estate->es_jit_flags != PGJIT_NONE)
829 {
830 jit_instrumentation = shm_toc_allocate(pcxt->toc,
832 jit_instrumentation->num_workers = nworkers;
833 memset(jit_instrumentation->jit_instr, 0,
834 sizeof(JitInstrumentation) * nworkers);
836 jit_instrumentation);
837 pei->jit_instrumentation = jit_instrumentation;
838 }
839 }
840
841 /*
842 * Create a DSA area that can be used by the leader and all workers.
843 * (However, if we failed to create a DSM and are using private memory
844 * instead, then skip this.)
845 */
846 if (pcxt->seg != NULL)
847 {
848 char *area_space;
849
854 pcxt->seg);
855
856 /*
857 * Serialize parameters, if any, using DSA storage. We don't dare use
858 * the main parallel query DSM for this because we might relaunch
859 * workers after the values have changed (and thus the amount of
860 * storage required has changed).
861 */
863 {
865 pei->area);
866 fpes->param_exec = pei->param_exec;
867 }
868 }
869
870 /*
871 * Give parallel-aware nodes a chance to initialize their shared data.
872 * This also initializes the elements of instrumentation->ps_instrument,
873 * if it exists.
874 */
875 d.pcxt = pcxt;
876 d.instrumentation = instrumentation;
877 d.nnodes = 0;
878
879 /* Install our DSA area while initializing the plan. */
880 estate->es_query_dsa = pei->area;
881 ExecParallelInitializeDSM(planstate, &d);
882 estate->es_query_dsa = NULL;
883
884 /*
885 * Make sure that the world hasn't shifted under our feet. This could
886 * probably just be an Assert(), but let's be conservative for now.
887 */
888 if (e.nnodes != d.nnodes)
889 elog(ERROR, "inconsistent count of PlanState nodes");
890
891 /* OK, we're ready to rock and roll. */
892 return pei;
893}

References ParallelExecutorInfo::area, Assert, bms_is_empty, ParallelExecutorInfo::buffer_usage, CreateParallelContext(), dsa_create_in_place, dsa_minimum_size(), elog, ERROR, EState::es_instrument, EState::es_jit_flags, EState::es_param_list_info, EState::es_query_dsa, EState::es_snapshot, EState::es_sourceText, EState::es_top_eflags, EstimateParamListSpace(), ParallelContext::estimator, ExecParallelEstimate(), ExecParallelInitializeDSM(), ExecParallelSetupTupleQueues(), ExecSerializePlan(), ExecSetParamPlanMulti(), fb(), ParallelExecutorInfo::finished, GetActiveSnapshot(), GetInstrumentationArray, GetPerTupleExprContext, i, InitializeParallelDSM(), InstrInit(), SharedExecutorInstrumentation::instrument_offset, SharedExecutorInstrumentation::instrument_options, ExecParallelInitializeDSMContext::instrumentation, ParallelExecutorInfo::instrumentation, InvalidDsaPointer, SharedJitInstrumentation::jit_instr, ParallelExecutorInfo::jit_instrumentation, MAXALIGN, mul_size(), ExecParallelInitializeDSMContext::nnodes, SharedExecutorInstrumentation::num_plan_nodes, SharedExecutorInstrumentation::num_workers, SharedJitInstrumentation::num_workers, ParallelContext::nworkers, palloc0_object, PARALLEL_KEY_BUFFER_USAGE, PARALLEL_KEY_DSA, PARALLEL_KEY_EXECUTOR_FIXED, PARALLEL_KEY_INSTRUMENTATION, PARALLEL_KEY_JIT_INSTRUMENTATION, PARALLEL_KEY_PARAMLISTINFO, PARALLEL_KEY_PLANNEDSTMT, PARALLEL_KEY_QUERY_TEXT, PARALLEL_KEY_WAL_USAGE, PARALLEL_TUPLE_QUEUE_SIZE, ParallelExecutorInfo::param_exec, ExecParallelInitializeDSMContext::pcxt, ParallelExecutorInfo::pcxt, PGJIT_NONE, PlanState::plan, ParallelExecutorInfo::planstate, ParallelExecutorInfo::reader, ParallelContext::seg, SerializeParamExecParams(), SerializeParamList(), shm_toc_allocate(), shm_toc_estimate_chunk, shm_toc_estimate_keys, shm_toc_insert(), ParallelContext::toc, ParallelExecutorInfo::tqueue, and ParallelExecutorInfo::wal_usage.

Referenced by ExecGather(), and ExecGatherMerge().

◆ ExecParallelCleanup()

void ExecParallelCleanup ( ParallelExecutorInfo pei)

Definition at line 1226 of file execParallel.c.

1227{
1228 /* Accumulate instrumentation, if any. */
1229 if (pei->instrumentation)
1231 pei->instrumentation);
1232
1233 /* Accumulate JIT instrumentation, if any. */
1234 if (pei->jit_instrumentation)
1236 pei->jit_instrumentation);
1237
1238 /* Free any serialized parameters. */
1239 if (DsaPointerIsValid(pei->param_exec))
1240 {
1241 dsa_free(pei->area, pei->param_exec);
1243 }
1244 if (pei->area != NULL)
1245 {
1246 dsa_detach(pei->area);
1247 pei->area = NULL;
1248 }
1249 if (pei->pcxt != NULL)
1250 {
1252 pei->pcxt = NULL;
1253 }
1254 pfree(pei);
1255}

References ParallelExecutorInfo::area, DestroyParallelContext(), dsa_detach(), dsa_free(), DsaPointerIsValid, ExecParallelRetrieveInstrumentation(), ExecParallelRetrieveJitInstrumentation(), fb(), ParallelExecutorInfo::instrumentation, InvalidDsaPointer, ParallelExecutorInfo::jit_instrumentation, ParallelExecutorInfo::param_exec, ParallelExecutorInfo::pcxt, pfree(), and ParallelExecutorInfo::planstate.

Referenced by ExecShutdownGather(), and ExecShutdownGatherMerge().

◆ ExecParallelCreateReaders()

void ExecParallelCreateReaders ( ParallelExecutorInfo pei)

Definition at line 902 of file execParallel.c.

903{
904 int nworkers = pei->pcxt->nworkers_launched;
905 int i;
906
907 Assert(pei->reader == NULL);
908
909 if (nworkers > 0)
910 {
911 pei->reader = (TupleQueueReader **)
912 palloc(nworkers * sizeof(TupleQueueReader *));
913
914 for (i = 0; i < nworkers; i++)
915 {
917 pei->pcxt->worker[i].bgwhandle);
918 pei->reader[i] = CreateTupleQueueReader(pei->tqueue[i]);
919 }
920 }
921}

References Assert, ParallelWorkerInfo::bgwhandle, CreateTupleQueueReader(), fb(), i, ParallelContext::nworkers_launched, palloc(), ParallelExecutorInfo::pcxt, ParallelExecutorInfo::reader, shm_mq_set_handle(), ParallelExecutorInfo::tqueue, and ParallelContext::worker.

Referenced by ExecGather(), and ExecGatherMerge().

◆ ExecParallelEstimate()

static bool ExecParallelEstimate ( PlanState planstate,
ExecParallelEstimateContext e 
)
static

Definition at line 235 of file execParallel.c.

236{
237 if (planstate == NULL)
238 return false;
239
240 /* Count this node. */
241 e->nnodes++;
242
243 switch (nodeTag(planstate))
244 {
245 case T_SeqScanState:
246 if (planstate->plan->parallel_aware)
247 ExecSeqScanEstimate((SeqScanState *) planstate,
248 e->pcxt);
249 break;
250 case T_IndexScanState:
251 /* even when not parallel-aware, for EXPLAIN ANALYZE */
253 e->pcxt);
254 break;
256 /* even when not parallel-aware, for EXPLAIN ANALYZE */
258 e->pcxt);
259 break;
261 /* even when not parallel-aware, for EXPLAIN ANALYZE */
263 e->pcxt);
264 break;
266 if (planstate->plan->parallel_aware)
268 e->pcxt);
269 break;
271 if (planstate->plan->parallel_aware)
273 e->pcxt);
274 break;
275 case T_AppendState:
276 if (planstate->plan->parallel_aware)
277 ExecAppendEstimate((AppendState *) planstate,
278 e->pcxt);
279 break;
281 if (planstate->plan->parallel_aware)
283 e->pcxt);
284 break;
286 if (planstate->plan->parallel_aware)
288 e->pcxt);
289 break;
290 case T_HashJoinState:
291 if (planstate->plan->parallel_aware)
293 e->pcxt);
294 break;
295 case T_HashState:
296 /* even when not parallel-aware, for EXPLAIN ANALYZE */
297 ExecHashEstimate((HashState *) planstate, e->pcxt);
298 break;
299 case T_SortState:
300 /* even when not parallel-aware, for EXPLAIN ANALYZE */
301 ExecSortEstimate((SortState *) planstate, e->pcxt);
302 break;
304 /* even when not parallel-aware, for EXPLAIN ANALYZE */
306 break;
307 case T_AggState:
308 /* even when not parallel-aware, for EXPLAIN ANALYZE */
309 ExecAggEstimate((AggState *) planstate, e->pcxt);
310 break;
311 case T_MemoizeState:
312 /* even when not parallel-aware, for EXPLAIN ANALYZE */
313 ExecMemoizeEstimate((MemoizeState *) planstate, e->pcxt);
314 break;
315 default:
316 break;
317 }
318
319 return planstate_tree_walker(planstate, ExecParallelEstimate, e);
320}

References ExecAggEstimate(), ExecAppendEstimate(), ExecBitmapHeapEstimate(), ExecBitmapIndexScanEstimate(), ExecCustomScanEstimate(), ExecForeignScanEstimate(), ExecHashEstimate(), ExecHashJoinEstimate(), ExecIncrementalSortEstimate(), ExecIndexOnlyScanEstimate(), ExecIndexScanEstimate(), ExecMemoizeEstimate(), ExecParallelEstimate(), ExecSeqScanEstimate(), ExecSortEstimate(), ExecTidRangeScanEstimate(), fb(), nodeTag, Plan::parallel_aware, PlanState::plan, and planstate_tree_walker.

Referenced by ExecInitParallelPlan(), and ExecParallelEstimate().

◆ ExecParallelFinish()

void ExecParallelFinish ( ParallelExecutorInfo pei)

Definition at line 1173 of file execParallel.c.

1174{
1175 int nworkers = pei->pcxt->nworkers_launched;
1176 int i;
1177
1178 /* Make this be a no-op if called twice in a row. */
1179 if (pei->finished)
1180 return;
1181
1182 /*
1183 * Detach from tuple queues ASAP, so that any still-active workers will
1184 * notice that no further results are wanted.
1185 */
1186 if (pei->tqueue != NULL)
1187 {
1188 for (i = 0; i < nworkers; i++)
1189 shm_mq_detach(pei->tqueue[i]);
1190 pfree(pei->tqueue);
1191 pei->tqueue = NULL;
1192 }
1193
1194 /*
1195 * While we're waiting for the workers to finish, let's get rid of the
1196 * tuple queue readers. (Any other local cleanup could be done here too.)
1197 */
1198 if (pei->reader != NULL)
1199 {
1200 for (i = 0; i < nworkers; i++)
1202 pfree(pei->reader);
1203 pei->reader = NULL;
1204 }
1205
1206 /* Now wait for the workers to finish. */
1208
1209 /*
1210 * Next, accumulate buffer/WAL usage. (This must wait for the workers to
1211 * finish, or we might get incomplete data.)
1212 */
1213 for (i = 0; i < nworkers; i++)
1215
1216 pei->finished = true;
1217}

References ParallelExecutorInfo::buffer_usage, DestroyTupleQueueReader(), fb(), ParallelExecutorInfo::finished, i, InstrAccumParallelQuery(), ParallelContext::nworkers_launched, ParallelExecutorInfo::pcxt, pfree(), ParallelExecutorInfo::reader, shm_mq_detach(), ParallelExecutorInfo::tqueue, WaitForParallelWorkersToFinish(), and ParallelExecutorInfo::wal_usage.

Referenced by ExecShutdownGatherMergeWorkers(), and ExecShutdownGatherWorkers().

◆ ExecParallelGetQueryDesc()

static QueryDesc * ExecParallelGetQueryDesc ( shm_toc toc,
DestReceiver receiver,
int  instrument_options 
)
static

Definition at line 1278 of file execParallel.c.

1280{
1281 char *pstmtspace;
1282 char *paramspace;
1283 PlannedStmt *pstmt;
1284 ParamListInfo paramLI;
1285 char *queryString;
1286
1287 /* Get the query string from shared memory */
1288 queryString = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, false);
1289
1290 /* Reconstruct leader-supplied PlannedStmt. */
1292 pstmt = (PlannedStmt *) stringToNode(pstmtspace);
1293
1294 /* Reconstruct ParamListInfo. */
1296 paramLI = RestoreParamList(&paramspace);
1297
1298 /* Create a QueryDesc for the query. */
1299 return CreateQueryDesc(pstmt,
1300 queryString,
1302 receiver, paramLI, NULL, instrument_options);
1303}

References CreateQueryDesc(), fb(), GetActiveSnapshot(), InvalidSnapshot, PARALLEL_KEY_PARAMLISTINFO, PARALLEL_KEY_PLANNEDSTMT, PARALLEL_KEY_QUERY_TEXT, RestoreParamList(), shm_toc_lookup(), and stringToNode().

Referenced by ParallelQueryMain().

◆ ExecParallelGetReceiver()

◆ ExecParallelInitializeDSM()

static bool ExecParallelInitializeDSM ( PlanState planstate,
ExecParallelInitializeDSMContext d 
)
static

Definition at line 454 of file execParallel.c.

456{
457 if (planstate == NULL)
458 return false;
459
460 /* If instrumentation is enabled, initialize slot for this node. */
461 if (d->instrumentation != NULL)
463 planstate->plan->plan_node_id;
464
465 /* Count this node. */
466 d->nnodes++;
467
468 /*
469 * Call initializers for DSM-using plan nodes.
470 *
471 * Most plan nodes won't do anything here, but plan nodes that allocated
472 * DSM may need to initialize shared state in the DSM before parallel
473 * workers are launched. They can allocate the space they previously
474 * estimated using shm_toc_allocate, and add the keys they previously
475 * estimated using shm_toc_insert, in each case targeting pcxt->toc.
476 */
477 switch (nodeTag(planstate))
478 {
479 case T_SeqScanState:
480 if (planstate->plan->parallel_aware)
482 d->pcxt);
483 break;
484 case T_IndexScanState:
485 /* even when not parallel-aware, for EXPLAIN ANALYZE */
487 break;
489 /* even when not parallel-aware, for EXPLAIN ANALYZE */
491 d->pcxt);
492 break;
494 /* even when not parallel-aware, for EXPLAIN ANALYZE */
496 break;
498 if (planstate->plan->parallel_aware)
500 d->pcxt);
501 break;
503 if (planstate->plan->parallel_aware)
505 d->pcxt);
506 break;
507 case T_AppendState:
508 if (planstate->plan->parallel_aware)
510 d->pcxt);
511 break;
513 if (planstate->plan->parallel_aware)
515 d->pcxt);
516 break;
518 if (planstate->plan->parallel_aware)
520 d->pcxt);
521 break;
522 case T_HashJoinState:
523 if (planstate->plan->parallel_aware)
525 d->pcxt);
526 break;
527 case T_HashState:
528 /* even when not parallel-aware, for EXPLAIN ANALYZE */
529 ExecHashInitializeDSM((HashState *) planstate, d->pcxt);
530 break;
531 case T_SortState:
532 /* even when not parallel-aware, for EXPLAIN ANALYZE */
533 ExecSortInitializeDSM((SortState *) planstate, d->pcxt);
534 break;
536 /* even when not parallel-aware, for EXPLAIN ANALYZE */
538 break;
539 case T_AggState:
540 /* even when not parallel-aware, for EXPLAIN ANALYZE */
541 ExecAggInitializeDSM((AggState *) planstate, d->pcxt);
542 break;
543 case T_MemoizeState:
544 /* even when not parallel-aware, for EXPLAIN ANALYZE */
545 ExecMemoizeInitializeDSM((MemoizeState *) planstate, d->pcxt);
546 break;
547 default:
548 break;
549 }
550
552}

References ExecAggInitializeDSM(), ExecAppendInitializeDSM(), ExecBitmapHeapInitializeDSM(), ExecBitmapIndexScanInitializeDSM(), ExecCustomScanInitializeDSM(), ExecForeignScanInitializeDSM(), ExecHashInitializeDSM(), ExecHashJoinInitializeDSM(), ExecIncrementalSortInitializeDSM(), ExecIndexOnlyScanInitializeDSM(), ExecIndexScanInitializeDSM(), ExecMemoizeInitializeDSM(), ExecParallelInitializeDSM(), ExecSeqScanInitializeDSM(), ExecSortInitializeDSM(), ExecTidRangeScanInitializeDSM(), fb(), ExecParallelInitializeDSMContext::instrumentation, ExecParallelInitializeDSMContext::nnodes, nodeTag, Plan::parallel_aware, ExecParallelInitializeDSMContext::pcxt, PlanState::plan, SharedExecutorInstrumentation::plan_node_id, Plan::plan_node_id, and planstate_tree_walker.

Referenced by ExecInitParallelPlan(), and ExecParallelInitializeDSM().

◆ ExecParallelInitializeWorker()

static bool ExecParallelInitializeWorker ( PlanState planstate,
ParallelWorkerContext pwcxt 
)
static

Definition at line 1351 of file execParallel.c.

1352{
1353 if (planstate == NULL)
1354 return false;
1355
1356 switch (nodeTag(planstate))
1357 {
1358 case T_SeqScanState:
1359 if (planstate->plan->parallel_aware)
1361 break;
1362 case T_IndexScanState:
1363 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1365 break;
1367 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1369 pwcxt);
1370 break;
1372 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1374 pwcxt);
1375 break;
1376 case T_ForeignScanState:
1377 if (planstate->plan->parallel_aware)
1379 pwcxt);
1380 break;
1382 if (planstate->plan->parallel_aware)
1384 pwcxt);
1385 break;
1386 case T_AppendState:
1387 if (planstate->plan->parallel_aware)
1389 break;
1390 case T_CustomScanState:
1391 if (planstate->plan->parallel_aware)
1393 pwcxt);
1394 break;
1396 if (planstate->plan->parallel_aware)
1398 pwcxt);
1399 break;
1400 case T_HashJoinState:
1401 if (planstate->plan->parallel_aware)
1403 pwcxt);
1404 break;
1405 case T_HashState:
1406 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1408 break;
1409 case T_SortState:
1410 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1412 break;
1414 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1416 pwcxt);
1417 break;
1418 case T_AggState:
1419 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1420 ExecAggInitializeWorker((AggState *) planstate, pwcxt);
1421 break;
1422 case T_MemoizeState:
1423 /* even when not parallel-aware, for EXPLAIN ANALYZE */
1425 break;
1426 default:
1427 break;
1428 }
1429
1431 pwcxt);
1432}

References ExecAggInitializeWorker(), ExecAppendInitializeWorker(), ExecBitmapHeapInitializeWorker(), ExecBitmapIndexScanInitializeWorker(), ExecCustomScanInitializeWorker(), ExecForeignScanInitializeWorker(), ExecHashInitializeWorker(), ExecHashJoinInitializeWorker(), ExecIncrementalSortInitializeWorker(), ExecIndexOnlyScanInitializeWorker(), ExecIndexScanInitializeWorker(), ExecMemoizeInitializeWorker(), ExecParallelInitializeWorker(), ExecSeqScanInitializeWorker(), ExecSortInitializeWorker(), ExecTidRangeScanInitializeWorker(), fb(), nodeTag, Plan::parallel_aware, PlanState::plan, and planstate_tree_walker.

Referenced by ExecParallelInitializeWorker(), and ParallelQueryMain().

◆ ExecParallelReinitialize()

void ExecParallelReinitialize ( PlanState planstate,
ParallelExecutorInfo pei,
Bitmapset sendParams 
)

Definition at line 928 of file execParallel.c.

931{
932 EState *estate = planstate->state;
934
935 /* Old workers must already be shut down */
936 Assert(pei->finished);
937
938 /*
939 * Force any initplan outputs that we're going to pass to workers to be
940 * evaluated, if they weren't already (see comments in
941 * ExecInitParallelPlan).
942 */
944
946 pei->tqueue = ExecParallelSetupTupleQueues(pei->pcxt, true);
947 pei->reader = NULL;
948 pei->finished = false;
949
951
952 /* Free any serialized parameters from the last round. */
953 if (DsaPointerIsValid(fpes->param_exec))
954 {
955 dsa_free(pei->area, fpes->param_exec);
956 fpes->param_exec = InvalidDsaPointer;
957 }
958
959 /* Serialize current parameter values if required. */
961 {
963 pei->area);
964 fpes->param_exec = pei->param_exec;
965 }
966
967 /* Traverse plan tree and let each child node reset associated state. */
968 estate->es_query_dsa = pei->area;
969 ExecParallelReInitializeDSM(planstate, pei->pcxt);
970 estate->es_query_dsa = NULL;
971}

References ParallelExecutorInfo::area, Assert, bms_is_empty, dsa_free(), DsaPointerIsValid, EState::es_query_dsa, ExecParallelReInitializeDSM(), ExecParallelSetupTupleQueues(), ExecSetParamPlanMulti(), fb(), ParallelExecutorInfo::finished, GetPerTupleExprContext, InvalidDsaPointer, PARALLEL_KEY_EXECUTOR_FIXED, ParallelExecutorInfo::param_exec, ParallelExecutorInfo::pcxt, ParallelExecutorInfo::reader, ReinitializeParallelDSM(), SerializeParamExecParams(), shm_toc_lookup(), PlanState::state, ParallelContext::toc, and ParallelExecutorInfo::tqueue.

Referenced by ExecGather(), and ExecGatherMerge().

◆ ExecParallelReInitializeDSM()

static bool ExecParallelReInitializeDSM ( PlanState planstate,
ParallelContext pcxt 
)
static

Definition at line 977 of file execParallel.c.

979{
980 if (planstate == NULL)
981 return false;
982
983 /*
984 * Call reinitializers for DSM-using plan nodes.
985 */
986 switch (nodeTag(planstate))
987 {
988 case T_SeqScanState:
989 if (planstate->plan->parallel_aware)
991 pcxt);
992 break;
993 case T_IndexScanState:
994 if (planstate->plan->parallel_aware)
996 pcxt);
997 break;
999 if (planstate->plan->parallel_aware)
1001 pcxt);
1002 break;
1003 case T_ForeignScanState:
1004 if (planstate->plan->parallel_aware)
1006 pcxt);
1007 break;
1009 if (planstate->plan->parallel_aware)
1011 pcxt);
1012 break;
1013 case T_AppendState:
1014 if (planstate->plan->parallel_aware)
1015 ExecAppendReInitializeDSM((AppendState *) planstate, pcxt);
1016 break;
1017 case T_CustomScanState:
1018 if (planstate->plan->parallel_aware)
1020 pcxt);
1021 break;
1023 if (planstate->plan->parallel_aware)
1025 pcxt);
1026 break;
1027 case T_HashJoinState:
1028 if (planstate->plan->parallel_aware)
1030 pcxt);
1031 break;
1033 case T_HashState:
1034 case T_SortState:
1036 case T_MemoizeState:
1037 /* these nodes have DSM state, but no reinitialization is required */
1038 break;
1039
1040 default:
1041 break;
1042 }
1043
1044 return planstate_tree_walker(planstate, ExecParallelReInitializeDSM, pcxt);
1045}

References ExecAppendReInitializeDSM(), ExecBitmapHeapReInitializeDSM(), ExecCustomScanReInitializeDSM(), ExecForeignScanReInitializeDSM(), ExecHashJoinReInitializeDSM(), ExecIndexOnlyScanReInitializeDSM(), ExecIndexScanReInitializeDSM(), ExecParallelReInitializeDSM(), ExecSeqScanReInitializeDSM(), ExecTidRangeScanReInitializeDSM(), fb(), nodeTag, Plan::parallel_aware, PlanState::plan, and planstate_tree_walker.

Referenced by ExecParallelReinitialize(), and ExecParallelReInitializeDSM().

◆ ExecParallelReportInstrumentation()

static bool ExecParallelReportInstrumentation ( PlanState planstate,
SharedExecutorInstrumentation instrumentation 
)
static

Definition at line 1310 of file execParallel.c.

1312{
1313 int i;
1314 int plan_node_id = planstate->plan->plan_node_id;
1315 Instrumentation *instrument;
1316
1317 InstrEndLoop(planstate->instrument);
1318
1319 /*
1320 * If we shuffled the plan_node_id values in ps_instrument into sorted
1321 * order, we could use binary search here. This might matter someday if
1322 * we're pushing down sufficiently large plan trees. For now, do it the
1323 * slow, dumb way.
1324 */
1325 for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1326 if (instrumentation->plan_node_id[i] == plan_node_id)
1327 break;
1328 if (i >= instrumentation->num_plan_nodes)
1329 elog(ERROR, "plan node %d not found", plan_node_id);
1330
1331 /*
1332 * Add our statistics to the per-node, per-worker totals. It's possible
1333 * that this could happen more than once if we relaunched workers.
1334 */
1335 instrument = GetInstrumentationArray(instrumentation);
1336 instrument += i * instrumentation->num_workers;
1339 InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
1340
1342 instrumentation);
1343}

References Assert, elog, ERROR, ExecParallelReportInstrumentation(), fb(), GetInstrumentationArray, i, InstrAggNode(), InstrEndLoop(), PlanState::instrument, IsParallelWorker, SharedExecutorInstrumentation::num_plan_nodes, SharedExecutorInstrumentation::num_workers, ParallelWorkerNumber, PlanState::plan, SharedExecutorInstrumentation::plan_node_id, Plan::plan_node_id, and planstate_tree_walker.

Referenced by ExecParallelReportInstrumentation(), and ParallelQueryMain().

◆ ExecParallelRetrieveInstrumentation()

static bool ExecParallelRetrieveInstrumentation ( PlanState planstate,
SharedExecutorInstrumentation instrumentation 
)
static

Definition at line 1052 of file execParallel.c.

1054{
1055 Instrumentation *instrument;
1056 int i;
1057 int n;
1058 int ibytes;
1059 int plan_node_id = planstate->plan->plan_node_id;
1060 MemoryContext oldcontext;
1061
1062 /* Find the instrumentation for this node. */
1063 for (i = 0; i < instrumentation->num_plan_nodes; ++i)
1064 if (instrumentation->plan_node_id[i] == plan_node_id)
1065 break;
1066 if (i >= instrumentation->num_plan_nodes)
1067 elog(ERROR, "plan node %d not found", plan_node_id);
1068
1069 /* Accumulate the statistics from all workers. */
1070 instrument = GetInstrumentationArray(instrumentation);
1071 instrument += i * instrumentation->num_workers;
1072 for (n = 0; n < instrumentation->num_workers; ++n)
1073 InstrAggNode(planstate->instrument, &instrument[n]);
1074
1075 /*
1076 * Also store the per-worker detail.
1077 *
1078 * Worker instrumentation should be allocated in the same context as the
1079 * regular instrumentation information, which is the per-query context.
1080 * Switch into per-query memory context.
1081 */
1082 oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
1083 ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));
1084 planstate->worker_instrument =
1086 MemoryContextSwitchTo(oldcontext);
1087
1088 planstate->worker_instrument->num_workers = instrumentation->num_workers;
1089 memcpy(&planstate->worker_instrument->instrument, instrument, ibytes);
1090
1091 /* Perform any node-type-specific work that needs to be done. */
1092 switch (nodeTag(planstate))
1093 {
1094 case T_IndexScanState:
1096 break;
1099 break;
1102 break;
1103 case T_SortState:
1105 break;
1108 break;
1109 case T_HashState:
1111 break;
1112 case T_AggState:
1114 break;
1115 case T_MemoizeState:
1117 break;
1120 break;
1121 default:
1122 break;
1123 }
1124
1126 instrumentation);
1127}

References elog, ERROR, EState::es_query_cxt, ExecAggRetrieveInstrumentation(), ExecBitmapHeapRetrieveInstrumentation(), ExecBitmapIndexScanRetrieveInstrumentation(), ExecHashRetrieveInstrumentation(), ExecIncrementalSortRetrieveInstrumentation(), ExecIndexOnlyScanRetrieveInstrumentation(), ExecIndexScanRetrieveInstrumentation(), ExecMemoizeRetrieveInstrumentation(), ExecParallelRetrieveInstrumentation(), ExecSortRetrieveInstrumentation(), fb(), GetInstrumentationArray, i, InstrAggNode(), WorkerInstrumentation::instrument, PlanState::instrument, MemoryContextSwitchTo(), mul_size(), nodeTag, SharedExecutorInstrumentation::num_plan_nodes, SharedExecutorInstrumentation::num_workers, WorkerInstrumentation::num_workers, palloc(), PlanState::plan, SharedExecutorInstrumentation::plan_node_id, Plan::plan_node_id, planstate_tree_walker, PlanState::state, and PlanState::worker_instrument.

Referenced by ExecParallelCleanup(), and ExecParallelRetrieveInstrumentation().

◆ ExecParallelRetrieveJitInstrumentation()

static void ExecParallelRetrieveJitInstrumentation ( PlanState planstate,
SharedJitInstrumentation shared_jit 
)
static

Definition at line 1133 of file execParallel.c.

1135{
1137 int ibytes;
1138
1139 int n;
1140
1141 /*
1142 * Accumulate worker JIT instrumentation into the combined JIT
1143 * instrumentation, allocating it if required.
1144 */
1145 if (!planstate->state->es_jit_worker_instr)
1146 planstate->state->es_jit_worker_instr =
1148 combined = planstate->state->es_jit_worker_instr;
1149
1150 /* Accumulate all the workers' instrumentations. */
1151 for (n = 0; n < shared_jit->num_workers; ++n)
1152 InstrJitAgg(combined, &shared_jit->jit_instr[n]);
1153
1154 /*
1155 * Store the per-worker detail.
1156 *
1157 * Similar to ExecParallelRetrieveInstrumentation(), allocate the
1158 * instrumentation in per-query context.
1159 */
1161 + mul_size(shared_jit->num_workers, sizeof(JitInstrumentation));
1162 planstate->worker_jit_instrument =
1164
1166}

References EState::es_jit_worker_instr, EState::es_query_cxt, fb(), InstrJitAgg(), MemoryContextAlloc(), MemoryContextAllocZero(), mul_size(), PlanState::state, and PlanState::worker_jit_instrument.

Referenced by ExecParallelCleanup().

◆ ExecParallelSetupTupleQueues()

static shm_mq_handle ** ExecParallelSetupTupleQueues ( ParallelContext pcxt,
bool  reinitialize 
)
static

Definition at line 559 of file execParallel.c.

560{
562 char *tqueuespace;
563 int i;
564
565 /* Skip this if no workers. */
566 if (pcxt->nworkers == 0)
567 return NULL;
568
569 /* Allocate memory for shared memory queue handles. */
571 palloc(pcxt->nworkers * sizeof(shm_mq_handle *));
572
573 /*
574 * If not reinitializing, allocate space from the DSM for the queues;
575 * otherwise, find the already allocated space.
576 */
577 if (!reinitialize)
579 shm_toc_allocate(pcxt->toc,
581 pcxt->nworkers));
582 else
584
585 /* Create the queues, and become the receiver for each. */
586 for (i = 0; i < pcxt->nworkers; ++i)
587 {
588 shm_mq *mq;
589
593
595 responseq[i] = shm_mq_attach(mq, pcxt->seg, NULL);
596 }
597
598 /* Add array of queues to shm_toc, so others can find it. */
599 if (!reinitialize)
601
602 /* Return array of handles. */
603 return responseq;
604}

References fb(), i, mul_size(), MyProc, ParallelContext::nworkers, palloc(), PARALLEL_KEY_TUPLE_QUEUE, PARALLEL_TUPLE_QUEUE_SIZE, ParallelContext::seg, shm_mq_attach(), shm_mq_create(), shm_mq_set_receiver(), shm_toc_allocate(), shm_toc_insert(), shm_toc_lookup(), and ParallelContext::toc.

Referenced by ExecInitParallelPlan(), and ExecParallelReinitialize().

◆ ExecSerializePlan()

static char * ExecSerializePlan ( Plan plan,
EState estate 
)
static

Definition at line 147 of file execParallel.c.

148{
149 PlannedStmt *pstmt;
150 ListCell *lc;
151
152 /* We can't scribble on the original plan, so make a copy. */
154
155 /*
156 * The worker will start its own copy of the executor, and that copy will
157 * insert a junk filter if the toplevel node has any resjunk entries. We
158 * don't want that to happen, because while resjunk columns shouldn't be
159 * sent back to the user, here the tuples are coming back to another
160 * backend which may very well need them. So mutate the target list
161 * accordingly. This is sort of a hack; there might be better ways to do
162 * this...
163 */
164 foreach(lc, plan->targetlist)
165 {
167
168 tle->resjunk = false;
169 }
170
171 /*
172 * Create a dummy PlannedStmt. Most of the fields don't need to be valid
173 * for our purposes, but the worker will need at least a minimal
174 * PlannedStmt to start the executor.
175 */
176 pstmt = makeNode(PlannedStmt);
177 pstmt->commandType = CMD_SELECT;
179 pstmt->planId = pgstat_get_my_plan_id();
180 pstmt->hasReturning = false;
181 pstmt->hasModifyingCTE = false;
182 pstmt->canSetTag = true;
183 pstmt->transientPlan = false;
184 pstmt->dependsOnRole = false;
185 pstmt->parallelModeNeeded = false;
186 pstmt->planTree = plan;
187 pstmt->partPruneInfos = estate->es_part_prune_infos;
188 pstmt->rtable = estate->es_range_table;
189 pstmt->unprunableRelids = estate->es_unpruned_relids;
190 pstmt->permInfos = estate->es_rteperminfos;
191 pstmt->resultRelations = NIL;
192 pstmt->appendRelations = NIL;
194
195 /*
196 * Transfer only parallel-safe subplans, leaving a NULL "hole" in the list
197 * for unsafe ones (so that the list indexes of the safe ones are
198 * preserved). This positively ensures that the worker won't try to run,
199 * or even do ExecInitNode on, an unsafe subplan. That's important to
200 * protect, eg, non-parallel-aware FDWs from getting into trouble.
201 */
202 pstmt->subplans = NIL;
203 foreach(lc, estate->es_plannedstmt->subplans)
204 {
205 Plan *subplan = (Plan *) lfirst(lc);
206
207 if (subplan && !subplan->parallel_safe)
208 subplan = NULL;
209 pstmt->subplans = lappend(pstmt->subplans, subplan);
210 }
211
212 pstmt->rewindPlanIDs = NULL;
213 pstmt->rowMarks = NIL;
214 pstmt->relationOids = NIL;
215 pstmt->invalItems = NIL; /* workers can't replan anyway... */
217 pstmt->utilityStmt = NULL;
218 pstmt->stmt_location = -1;
219 pstmt->stmt_len = -1;
220
221 /* Return serialized copy of our dummy PlannedStmt. */
222 return nodeToString(pstmt);
223}

References PlannedStmt::appendRelations, PlannedStmt::canSetTag, CMD_SELECT, PlannedStmt::commandType, copyObject, PlannedStmt::dependsOnRole, EState::es_part_prune_infos, EState::es_plannedstmt, EState::es_range_table, EState::es_rteperminfos, EState::es_unpruned_relids, fb(), PlannedStmt::hasModifyingCTE, PlannedStmt::hasReturning, PlannedStmt::invalItems, lappend(), lfirst, lfirst_node, makeNode, NIL, nodeToString(), Plan::parallel_safe, PlannedStmt::parallelModeNeeded, PlannedStmt::paramExecTypes, PlannedStmt::partPruneInfos, PlannedStmt::permInfos, pgstat_get_my_plan_id(), pgstat_get_my_query_id(), plan, PLAN_STMT_INTERNAL, PlannedStmt::planId, PlannedStmt::planOrigin, PlannedStmt::planTree, PlannedStmt::queryId, PlannedStmt::relationOids, PlannedStmt::resultRelations, PlannedStmt::rewindPlanIDs, PlannedStmt::rowMarks, PlannedStmt::rtable, PlannedStmt::stmt_len, PlannedStmt::stmt_location, PlannedStmt::subplans, PlannedStmt::transientPlan, PlannedStmt::unprunableRelids, and PlannedStmt::utilityStmt.

Referenced by ExecInitParallelPlan().

◆ ParallelQueryMain()

void ParallelQueryMain ( dsm_segment seg,
shm_toc toc 
)

Definition at line 1451 of file execParallel.c.

1452{
1454 BufferUsage *buffer_usage;
1455 WalUsage *wal_usage;
1457 QueryDesc *queryDesc;
1458 SharedExecutorInstrumentation *instrumentation;
1459 SharedJitInstrumentation *jit_instrumentation;
1460 int instrument_options = 0;
1461 void *area_space;
1462 dsa_area *area;
1464
1465 /* Get fixed-size state. */
1467
1468 /* Set up DestReceiver, SharedExecutorInstrumentation, and QueryDesc. */
1470 instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_INSTRUMENTATION, true);
1471 if (instrumentation != NULL)
1472 instrument_options = instrumentation->instrument_options;
1473 jit_instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_JIT_INSTRUMENTATION,
1474 true);
1475 queryDesc = ExecParallelGetQueryDesc(toc, receiver, instrument_options);
1476
1477 /* Setting debug_query_string for individual workers */
1478 debug_query_string = queryDesc->sourceText;
1479
1480 /* Report workers' query for monitoring purposes */
1482
1483 /* Attach to the dynamic shared memory area. */
1485 area = dsa_attach_in_place(area_space, seg);
1486
1487 /* Start up the executor */
1488 queryDesc->plannedstmt->jitFlags = fpes->jit_flags;
1489 ExecutorStart(queryDesc, fpes->eflags);
1490
1491 /* Special executor initialization steps for parallel workers */
1492 queryDesc->planstate->state->es_query_dsa = area;
1493 if (DsaPointerIsValid(fpes->param_exec))
1494 {
1495 char *paramexec_space;
1496
1497 paramexec_space = dsa_get_address(area, fpes->param_exec);
1499 }
1500 pwcxt.toc = toc;
1501 pwcxt.seg = seg;
1503
1504 /* Pass down any tuple bound */
1505 ExecSetTupleBound(fpes->tuples_needed, queryDesc->planstate);
1506
1507 /*
1508 * Prepare to track buffer/WAL usage during query execution.
1509 *
1510 * We do this after starting up the executor to match what happens in the
1511 * leader, which also doesn't count buffer accesses and WAL activity that
1512 * occur during executor startup.
1513 */
1515
1516 /*
1517 * Run the plan. If we specified a tuple bound, be careful not to demand
1518 * more tuples than that.
1519 */
1520 ExecutorRun(queryDesc,
1522 fpes->tuples_needed < 0 ? (int64) 0 : fpes->tuples_needed);
1523
1524 /* Shut down the executor */
1525 ExecutorFinish(queryDesc);
1526
1527 /* Report buffer/WAL usage during parallel execution. */
1528 buffer_usage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
1529 wal_usage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
1531 &wal_usage[ParallelWorkerNumber]);
1532
1533 /* Report instrumentation data if any instrumentation options are set. */
1534 if (instrumentation != NULL)
1536 instrumentation);
1537
1538 /* Report JIT instrumentation data if any */
1539 if (queryDesc->estate->es_jit && jit_instrumentation != NULL)
1540 {
1542 jit_instrumentation->jit_instr[ParallelWorkerNumber] =
1543 queryDesc->estate->es_jit->instr;
1544 }
1545
1546 /* Must do this after capturing instrumentation. */
1547 ExecutorEnd(queryDesc);
1548
1549 /* Cleanup. */
1550 dsa_detach(area);
1551 FreeQueryDesc(queryDesc);
1552 receiver->rDestroy(receiver);
1553}

References Assert, debug_query_string, dsa_attach_in_place(), dsa_detach(), dsa_get_address(), DsaPointerIsValid, EState::es_jit, EState::es_query_dsa, QueryDesc::estate, ExecParallelGetQueryDesc(), ExecParallelGetReceiver(), ExecParallelInitializeWorker(), ExecParallelReportInstrumentation(), ExecSetTupleBound(), ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), fb(), ForwardScanDirection, FreeQueryDesc(), JitContext::instr, InstrEndParallelQuery(), InstrStartParallelQuery(), SharedExecutorInstrumentation::instrument_options, SharedJitInstrumentation::jit_instr, PlannedStmt::jitFlags, PARALLEL_KEY_BUFFER_USAGE, PARALLEL_KEY_DSA, PARALLEL_KEY_EXECUTOR_FIXED, PARALLEL_KEY_INSTRUMENTATION, PARALLEL_KEY_JIT_INSTRUMENTATION, PARALLEL_KEY_WAL_USAGE, ParallelWorkerNumber, pgstat_report_activity(), QueryDesc::plannedstmt, QueryDesc::planstate, RestoreParamExecParams(), shm_toc_lookup(), QueryDesc::sourceText, PlanState::state, and STATE_RUNNING.

◆ RestoreParamExecParams()

static void RestoreParamExecParams ( char start_address,
EState estate 
)
static

Definition at line 425 of file execParallel.c.

426{
427 int nparams;
428 int i;
429 int paramid;
430
431 memcpy(&nparams, start_address, sizeof(int));
432 start_address += sizeof(int);
433
434 for (i = 0; i < nparams; i++)
435 {
437
438 /* Read paramid */
439 memcpy(&paramid, start_address, sizeof(int));
440 start_address += sizeof(int);
441 prm = &(estate->es_param_exec_vals[paramid]);
442
443 /* Read datum/isnull. */
444 prm->value = datumRestore(&start_address, &prm->isnull);
445 prm->execPlan = NULL;
446 }
447}

References datumRestore(), EState::es_param_exec_vals, fb(), and i.

Referenced by ParallelQueryMain().

◆ SerializeParamExecParams()

static dsa_pointer SerializeParamExecParams ( EState estate,
Bitmapset params,
dsa_area area 
)
static

Definition at line 370 of file execParallel.c.

371{
372 Size size;
373 int nparams;
374 int paramid;
376 dsa_pointer handle;
377 char *start_address;
378
379 /* Allocate enough space for the current parameter values. */
380 size = EstimateParamExecSpace(estate, params);
381 handle = dsa_allocate(area, size);
382 start_address = dsa_get_address(area, handle);
383
384 /* First write the number of parameters as a 4-byte integer. */
385 nparams = bms_num_members(params);
386 memcpy(start_address, &nparams, sizeof(int));
387 start_address += sizeof(int);
388
389 /* Write details for each parameter in turn. */
390 paramid = -1;
391 while ((paramid = bms_next_member(params, paramid)) >= 0)
392 {
393 Oid typeOid;
394 int16 typLen;
395 bool typByVal;
396
397 prm = &(estate->es_param_exec_vals[paramid]);
398 typeOid = list_nth_oid(estate->es_plannedstmt->paramExecTypes,
399 paramid);
400
401 /* Write paramid. */
402 memcpy(start_address, &paramid, sizeof(int));
403 start_address += sizeof(int);
404
405 /* Write datum/isnull */
406 if (OidIsValid(typeOid))
407 get_typlenbyval(typeOid, &typLen, &typByVal);
408 else
409 {
410 /* If no type OID, assume by-value, like copyParamList does. */
411 typLen = sizeof(Datum);
412 typByVal = true;
413 }
414 datumSerialize(prm->value, prm->isnull, typByVal, typLen,
416 }
417
418 return handle;
419}

References bms_next_member(), bms_num_members(), datumSerialize(), dsa_allocate, dsa_get_address(), EState::es_param_exec_vals, EState::es_plannedstmt, EstimateParamExecSpace(), fb(), get_typlenbyval(), list_nth_oid(), OidIsValid, and PlannedStmt::paramExecTypes.

Referenced by ExecInitParallelPlan(), and ExecParallelReinitialize().