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