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