Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * parallel.c
4 : : * Infrastructure for launching parallel workers
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : * IDENTIFICATION
10 : : * src/backend/access/transam/parallel.c
11 : : *
12 : : *-------------------------------------------------------------------------
13 : : */
14 : :
15 : : #include "postgres.h"
16 : :
17 : : #include "access/brin.h"
18 : : #include "access/gin.h"
19 : : #include "access/nbtree.h"
20 : : #include "access/parallel.h"
21 : : #include "access/session.h"
22 : : #include "access/xact.h"
23 : : #include "access/xlog.h"
24 : : #include "catalog/index.h"
25 : : #include "catalog/namespace.h"
26 : : #include "catalog/pg_enum.h"
27 : : #include "catalog/storage.h"
28 : : #include "commands/async.h"
29 : : #include "commands/vacuum.h"
30 : : #include "executor/execParallel.h"
31 : : #include "libpq/libpq.h"
32 : : #include "libpq/pqformat.h"
33 : : #include "libpq/pqmq.h"
34 : : #include "miscadmin.h"
35 : : #include "optimizer/optimizer.h"
36 : : #include "pgstat.h"
37 : : #include "storage/ipc.h"
38 : : #include "storage/predicate.h"
39 : : #include "storage/proc.h"
40 : : #include "tcop/tcopprot.h"
41 : : #include "utils/combocid.h"
42 : : #include "utils/guc.h"
43 : : #include "utils/inval.h"
44 : : #include "utils/memutils.h"
45 : : #include "utils/relmapper.h"
46 : : #include "utils/snapmgr.h"
47 : : #include "utils/wait_event.h"
48 : :
49 : : /*
50 : : * We don't want to waste a lot of memory on an error queue which, most of
51 : : * the time, will process only a handful of small messages. However, it is
52 : : * desirable to make it large enough that a typical ErrorResponse can be sent
53 : : * without blocking. That way, a worker that errors out can write the whole
54 : : * message into the queue and terminate without waiting for the user backend.
55 : : */
56 : : #define PARALLEL_ERROR_QUEUE_SIZE 16384
57 : :
58 : : /* Magic number for parallel context TOC. */
59 : : #define PARALLEL_MAGIC 0x50477c7c
60 : :
61 : : /*
62 : : * Magic numbers for per-context parallel state sharing. Higher-level code
63 : : * should use smaller values, leaving these very large ones for use by this
64 : : * module.
65 : : */
66 : : #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
67 : : #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
68 : : #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
69 : : #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
70 : : #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
71 : : #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
72 : : #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
73 : : #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
74 : : #define PARALLEL_KEY_ENTRYPOINT UINT64CONST(0xFFFFFFFFFFFF0009)
75 : : #define PARALLEL_KEY_SESSION_DSM UINT64CONST(0xFFFFFFFFFFFF000A)
76 : : #define PARALLEL_KEY_PENDING_SYNCS UINT64CONST(0xFFFFFFFFFFFF000B)
77 : : #define PARALLEL_KEY_REINDEX_STATE UINT64CONST(0xFFFFFFFFFFFF000C)
78 : : #define PARALLEL_KEY_RELMAPPER_STATE UINT64CONST(0xFFFFFFFFFFFF000D)
79 : : #define PARALLEL_KEY_UNCOMMITTEDENUMS UINT64CONST(0xFFFFFFFFFFFF000E)
80 : : #define PARALLEL_KEY_CLIENTCONNINFO UINT64CONST(0xFFFFFFFFFFFF000F)
81 : :
82 : : /* Fixed-size parallel state. */
83 : : typedef struct FixedParallelState
84 : : {
85 : : /* Fixed-size state that workers must restore. */
86 : : Oid database_id;
87 : : Oid authenticated_user_id;
88 : : Oid session_user_id;
89 : : Oid outer_user_id;
90 : : Oid current_user_id;
91 : : Oid temp_namespace_id;
92 : : Oid temp_toast_namespace_id;
93 : : int sec_context;
94 : : bool session_user_is_superuser;
95 : : bool role_is_superuser;
96 : : PGPROC *parallel_leader_pgproc;
97 : : pid_t parallel_leader_pid;
98 : : ProcNumber parallel_leader_proc_number;
99 : : TimestampTz xact_ts;
100 : : TimestampTz stmt_ts;
101 : : SerializableXactHandle serializable_xact_handle;
102 : :
103 : : /* Maximum XactLastRecEnd of any worker. */
104 : : pg_atomic_uint64 last_xlog_end;
105 : : } FixedParallelState;
106 : :
107 : : /*
108 : : * Our parallel worker number. We initialize this to -1, meaning that we are
109 : : * not a parallel worker. In parallel workers, it will be set to a value >= 0
110 : : * and < the number of workers before any user code is invoked; each parallel
111 : : * worker will get a different parallel worker number.
112 : : */
113 : : int ParallelWorkerNumber = -1;
114 : :
115 : : /* Is there a parallel message pending which we need to receive? */
116 : : volatile sig_atomic_t ParallelMessagePending = false;
117 : :
118 : : /* Are we initializing a parallel worker? */
119 : : bool InitializingParallelWorker = false;
120 : :
121 : : /* Pointer to our fixed parallel state. */
122 : : static FixedParallelState *MyFixedParallelState;
123 : :
124 : : /* List of active parallel contexts. */
125 : : static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list);
126 : :
127 : : /* Backend-local copy of data from FixedParallelState. */
128 : : static pid_t ParallelLeaderPid;
129 : :
130 : : /*
131 : : * List of internal parallel worker entry points. We need this for
132 : : * reasons explained in LookupParallelWorkerFunction(), below.
133 : : */
134 : : static const struct
135 : : {
136 : : const char *fn_name;
137 : : parallel_worker_main_type fn_addr;
138 : : } InternalParallelWorkers[] =
139 : :
140 : : {
141 : : {
142 : : "ParallelQueryMain", ParallelQueryMain
143 : : },
144 : : {
145 : : "_bt_parallel_build_main", _bt_parallel_build_main
146 : : },
147 : : {
148 : : "_brin_parallel_build_main", _brin_parallel_build_main
149 : : },
150 : : {
151 : : "_gin_parallel_build_main", _gin_parallel_build_main
152 : : },
153 : : {
154 : : "parallel_vacuum_main", parallel_vacuum_main
155 : : }
156 : : };
157 : :
158 : : /* Private functions. */
159 : : static void ProcessParallelMessage(ParallelContext *pcxt, int i, StringInfo msg);
160 : : static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
161 : : static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname);
162 : : static void ParallelWorkerShutdown(int code, Datum arg);
163 : :
164 : :
165 : : /*
166 : : * Establish a new parallel context. This should be done after entering
167 : : * parallel mode, and (unless there is an error) the context should be
168 : : * destroyed before exiting the current subtransaction.
169 : : */
170 : : ParallelContext *
171 : 681 : CreateParallelContext(const char *library_name, const char *function_name,
172 : : int nworkers)
173 : : {
174 : : MemoryContext oldcontext;
175 : : ParallelContext *pcxt;
176 : :
177 : : /* It is unsafe to create a parallel context if not in parallel mode. */
178 : : Assert(IsInParallelMode());
179 : :
180 : : /* Number of workers should be non-negative. */
181 : : Assert(nworkers >= 0);
182 : :
183 : : /* We might be running in a short-lived memory context. */
184 : 681 : oldcontext = MemoryContextSwitchTo(TopTransactionContext);
185 : :
186 : : /* Initialize a new ParallelContext. */
187 : 681 : pcxt = palloc0_object(ParallelContext);
188 : 681 : pcxt->subid = GetCurrentSubTransactionId();
189 : 681 : pcxt->nworkers = nworkers;
190 : 681 : pcxt->nworkers_to_launch = nworkers;
191 : 681 : pcxt->library_name = pstrdup(library_name);
192 : 681 : pcxt->function_name = pstrdup(function_name);
193 : 681 : pcxt->error_context_stack = error_context_stack;
194 : 681 : shm_toc_initialize_estimator(&pcxt->estimator);
195 : 681 : dlist_push_head(&pcxt_list, &pcxt->node);
196 : :
197 : : /* Restore previous memory context. */
198 : 681 : MemoryContextSwitchTo(oldcontext);
199 : :
200 : 681 : return pcxt;
201 : : }
202 : :
203 : : /*
204 : : * Establish the dynamic shared memory segment for a parallel context and
205 : : * copy state and other bookkeeping information that will be needed by
206 : : * parallel workers into it.
207 : : */
208 : : void
209 : 681 : InitializeParallelDSM(ParallelContext *pcxt)
210 : : {
211 : : MemoryContext oldcontext;
212 : 681 : Size library_len = 0;
213 : 681 : Size guc_len = 0;
214 : 681 : Size combocidlen = 0;
215 : 681 : Size tsnaplen = 0;
216 : 681 : Size asnaplen = 0;
217 : 681 : Size tstatelen = 0;
218 : 681 : Size pendingsyncslen = 0;
219 : 681 : Size reindexlen = 0;
220 : 681 : Size relmapperlen = 0;
221 : 681 : Size uncommittedenumslen = 0;
222 : 681 : Size clientconninfolen = 0;
223 : 681 : Size segsize = 0;
224 : : int i;
225 : : FixedParallelState *fps;
226 : 681 : dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
227 : 681 : Snapshot transaction_snapshot = GetTransactionSnapshot();
228 : 681 : Snapshot active_snapshot = GetActiveSnapshot();
229 : :
230 : : /* We might be running in a very short-lived memory context. */
231 : 681 : oldcontext = MemoryContextSwitchTo(TopTransactionContext);
232 : :
233 : : /* Allow space to store the fixed-size parallel state. */
234 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
235 : 681 : shm_toc_estimate_keys(&pcxt->estimator, 1);
236 : :
237 : : /*
238 : : * If we manage to reach here while non-interruptible, it's unsafe to
239 : : * launch any workers: we would fail to process interrupts sent by them.
240 : : * We can deal with that edge case by pretending no workers were
241 : : * requested.
242 : : */
243 [ + - + - : 681 : if (!INTERRUPTS_CAN_BE_PROCESSED())
- + ]
244 : 0 : pcxt->nworkers = 0;
245 : :
246 : : /*
247 : : * Normally, the user will have requested at least one worker process, but
248 : : * if by chance they have not, we can skip a bunch of things here.
249 : : */
250 [ + - ]: 681 : if (pcxt->nworkers > 0)
251 : : {
252 : : /* Get (or create) the per-session DSM segment's handle. */
253 : 681 : session_dsm_handle = GetSessionDsmHandle();
254 : :
255 : : /*
256 : : * If we weren't able to create a per-session DSM segment, then we can
257 : : * continue but we can't safely launch any workers because their
258 : : * record typmods would be incompatible so they couldn't exchange
259 : : * tuples.
260 : : */
261 [ - + ]: 681 : if (session_dsm_handle == DSM_HANDLE_INVALID)
262 : 0 : pcxt->nworkers = 0;
263 : : }
264 : :
265 [ + - ]: 681 : if (pcxt->nworkers > 0)
266 : : {
267 : : StaticAssertDecl(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
268 : : PARALLEL_ERROR_QUEUE_SIZE,
269 : : "parallel error queue size not buffer-aligned");
270 : :
271 : : /* Estimate space for various kinds of state sharing. */
272 : 681 : library_len = EstimateLibraryStateSpace();
273 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, library_len);
274 : 681 : guc_len = EstimateGUCStateSpace();
275 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
276 : 681 : combocidlen = EstimateComboCIDStateSpace();
277 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
278 [ + + ]: 681 : if (IsolationUsesXactSnapshot())
279 : : {
280 : 11 : tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
281 : 11 : shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
282 : : }
283 : 681 : asnaplen = EstimateSnapshotSpace(active_snapshot);
284 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
285 : 681 : tstatelen = EstimateTransactionStateSpace();
286 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
287 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, sizeof(dsm_handle));
288 : 681 : pendingsyncslen = EstimatePendingSyncsSpace();
289 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, pendingsyncslen);
290 : 681 : reindexlen = EstimateReindexStateSpace();
291 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, reindexlen);
292 : 681 : relmapperlen = EstimateRelationMapSpace();
293 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, relmapperlen);
294 : 681 : uncommittedenumslen = EstimateUncommittedEnumsSpace();
295 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, uncommittedenumslen);
296 : 681 : clientconninfolen = EstimateClientConnectionInfoSpace();
297 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, clientconninfolen);
298 : : /* If you add more chunks here, you probably need to add keys. */
299 : 681 : shm_toc_estimate_keys(&pcxt->estimator, 12);
300 : :
301 : : /* Estimate space need for error queues. */
302 : 681 : shm_toc_estimate_chunk(&pcxt->estimator,
303 : : mul_size(PARALLEL_ERROR_QUEUE_SIZE,
304 : : pcxt->nworkers));
305 : 681 : shm_toc_estimate_keys(&pcxt->estimator, 1);
306 : :
307 : : /* Estimate how much we'll need for the entrypoint info. */
308 : 681 : shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
309 : : strlen(pcxt->function_name) + 2);
310 : 681 : shm_toc_estimate_keys(&pcxt->estimator, 1);
311 : : }
312 : :
313 : : /*
314 : : * Create DSM and initialize with new table of contents. But if the user
315 : : * didn't request any workers, then don't bother creating a dynamic shared
316 : : * memory segment; instead, just use backend-private memory.
317 : : *
318 : : * Also, if we can't create a dynamic shared memory segment because the
319 : : * maximum number of segments have already been created, then fall back to
320 : : * backend-private memory, and plan not to use any workers. We hope this
321 : : * won't happen very often, but it's better to abandon the use of
322 : : * parallelism than to fail outright.
323 : : */
324 : 681 : segsize = shm_toc_estimate(&pcxt->estimator);
325 [ + - ]: 681 : if (pcxt->nworkers > 0)
326 : 681 : pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
327 [ + - ]: 681 : if (pcxt->seg != NULL)
328 : 681 : pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
329 : : dsm_segment_address(pcxt->seg),
330 : : segsize);
331 : : else
332 : : {
333 : 0 : pcxt->nworkers = 0;
334 : 0 : pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
335 : 0 : pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
336 : : segsize);
337 : : }
338 : :
339 : : /* Initialize fixed-size state in shared memory. */
340 : : fps = (FixedParallelState *)
341 : 681 : shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
342 : 681 : fps->database_id = MyDatabaseId;
343 : 681 : fps->authenticated_user_id = GetAuthenticatedUserId();
344 : 681 : fps->session_user_id = GetSessionUserId();
345 : 681 : fps->outer_user_id = GetCurrentRoleId();
346 : 681 : GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
347 : 681 : fps->session_user_is_superuser = GetSessionUserIsSuperuser();
348 : 681 : fps->role_is_superuser = current_role_is_superuser;
349 : 681 : GetTempNamespaceState(&fps->temp_namespace_id,
350 : : &fps->temp_toast_namespace_id);
351 : 681 : fps->parallel_leader_pgproc = MyProc;
352 : 681 : fps->parallel_leader_pid = MyProcPid;
353 : 681 : fps->parallel_leader_proc_number = MyProcNumber;
354 : 681 : fps->xact_ts = GetCurrentTransactionStartTimestamp();
355 : 681 : fps->stmt_ts = GetCurrentStatementStartTimestamp();
356 : 681 : fps->serializable_xact_handle = ShareSerializableXact();
357 : 681 : pg_atomic_init_u64(&fps->last_xlog_end, InvalidXLogRecPtr);
358 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
359 : :
360 : : /* We can skip the rest of this if we're not budgeting for any workers. */
361 [ + - ]: 681 : if (pcxt->nworkers > 0)
362 : : {
363 : : char *libraryspace;
364 : : char *gucspace;
365 : : char *combocidspace;
366 : : char *tsnapspace;
367 : : char *asnapspace;
368 : : char *tstatespace;
369 : : char *pendingsyncsspace;
370 : : char *reindexspace;
371 : : char *relmapperspace;
372 : : char *error_queue_space;
373 : : char *session_dsm_handle_space;
374 : : char *entrypointstate;
375 : : char *uncommittedenumsspace;
376 : : char *clientconninfospace;
377 : : Size lnamelen;
378 : :
379 : : /* Serialize shared libraries we have loaded. */
380 : 681 : libraryspace = shm_toc_allocate(pcxt->toc, library_len);
381 : 681 : SerializeLibraryState(library_len, libraryspace);
382 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
383 : :
384 : : /* Serialize GUC settings. */
385 : 681 : gucspace = shm_toc_allocate(pcxt->toc, guc_len);
386 : 681 : SerializeGUCState(guc_len, gucspace);
387 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
388 : :
389 : : /* Serialize combo CID state. */
390 : 681 : combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
391 : 681 : SerializeComboCIDState(combocidlen, combocidspace);
392 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
393 : :
394 : : /*
395 : : * Serialize the transaction snapshot if the transaction isolation
396 : : * level uses a transaction snapshot.
397 : : */
398 [ + + ]: 681 : if (IsolationUsesXactSnapshot())
399 : : {
400 : 11 : tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
401 : 11 : SerializeSnapshot(transaction_snapshot, tsnapspace);
402 : 11 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
403 : : tsnapspace);
404 : : }
405 : :
406 : : /* Serialize the active snapshot. */
407 : 681 : asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
408 : 681 : SerializeSnapshot(active_snapshot, asnapspace);
409 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
410 : :
411 : : /* Provide the handle for per-session segment. */
412 : 681 : session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
413 : : sizeof(dsm_handle));
414 : 681 : *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
415 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_SESSION_DSM,
416 : : session_dsm_handle_space);
417 : :
418 : : /* Serialize transaction state. */
419 : 681 : tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
420 : 681 : SerializeTransactionState(tstatelen, tstatespace);
421 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
422 : :
423 : : /* Serialize pending syncs. */
424 : 681 : pendingsyncsspace = shm_toc_allocate(pcxt->toc, pendingsyncslen);
425 : 681 : SerializePendingSyncs(pendingsyncslen, pendingsyncsspace);
426 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_PENDING_SYNCS,
427 : : pendingsyncsspace);
428 : :
429 : : /* Serialize reindex state. */
430 : 681 : reindexspace = shm_toc_allocate(pcxt->toc, reindexlen);
431 : 681 : SerializeReindexState(reindexlen, reindexspace);
432 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_REINDEX_STATE, reindexspace);
433 : :
434 : : /* Serialize relmapper state. */
435 : 681 : relmapperspace = shm_toc_allocate(pcxt->toc, relmapperlen);
436 : 681 : SerializeRelationMap(relmapperlen, relmapperspace);
437 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_RELMAPPER_STATE,
438 : : relmapperspace);
439 : :
440 : : /* Serialize uncommitted enum state. */
441 : 681 : uncommittedenumsspace = shm_toc_allocate(pcxt->toc,
442 : : uncommittedenumslen);
443 : 681 : SerializeUncommittedEnums(uncommittedenumsspace, uncommittedenumslen);
444 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_UNCOMMITTEDENUMS,
445 : : uncommittedenumsspace);
446 : :
447 : : /* Serialize our ClientConnectionInfo. */
448 : 681 : clientconninfospace = shm_toc_allocate(pcxt->toc, clientconninfolen);
449 : 681 : SerializeClientConnectionInfo(clientconninfolen, clientconninfospace);
450 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_CLIENTCONNINFO,
451 : : clientconninfospace);
452 : :
453 : : /* Allocate space for worker information. */
454 : 681 : pcxt->worker = palloc0_array(ParallelWorkerInfo, pcxt->nworkers);
455 : :
456 : : /*
457 : : * Establish error queues in dynamic shared memory.
458 : : *
459 : : * These queues should be used only for transmitting ErrorResponse,
460 : : * NoticeResponse, and NotifyResponse protocol messages. Tuple data
461 : : * should be transmitted via separate (possibly larger?) queues.
462 : : */
463 : : error_queue_space =
464 : 681 : shm_toc_allocate(pcxt->toc,
465 : : mul_size(PARALLEL_ERROR_QUEUE_SIZE,
466 : 681 : pcxt->nworkers));
467 [ + + ]: 2195 : for (i = 0; i < pcxt->nworkers; ++i)
468 : : {
469 : : char *start;
470 : : shm_mq *mq;
471 : :
472 : 1514 : start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
473 : 1514 : mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
474 : 1514 : shm_mq_set_receiver(mq, MyProc);
475 : 1514 : pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
476 : : }
477 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
478 : :
479 : : /*
480 : : * Serialize entrypoint information. It's unsafe to pass function
481 : : * pointers across processes, as the function pointer may be different
482 : : * in each process in EXEC_BACKEND builds, so we always pass library
483 : : * and function name. (We use library name "postgres" for functions
484 : : * in the core backend.)
485 : : */
486 : 681 : lnamelen = strlen(pcxt->library_name);
487 : 681 : entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
488 : 681 : strlen(pcxt->function_name) + 2);
489 : 681 : strcpy(entrypointstate, pcxt->library_name);
490 : 681 : strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
491 : 681 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
492 : : }
493 : :
494 : : /* Update nworkers_to_launch, in case we changed nworkers above. */
495 : 681 : pcxt->nworkers_to_launch = pcxt->nworkers;
496 : :
497 : : /* Restore previous memory context. */
498 : 681 : MemoryContextSwitchTo(oldcontext);
499 : 681 : }
500 : :
501 : : /*
502 : : * Reinitialize the dynamic shared memory segment for a parallel context such
503 : : * that we could launch workers for it again.
504 : : */
505 : : void
506 : 177 : ReinitializeParallelDSM(ParallelContext *pcxt)
507 : : {
508 : : MemoryContext oldcontext;
509 : : FixedParallelState *fps;
510 : :
511 : : /* We might be running in a very short-lived memory context. */
512 : 177 : oldcontext = MemoryContextSwitchTo(TopTransactionContext);
513 : :
514 : : /* Wait for any old workers to exit. */
515 [ + - ]: 177 : if (pcxt->nworkers_launched > 0)
516 : : {
517 : 177 : WaitForParallelWorkersToFinish(pcxt);
518 : 177 : WaitForParallelWorkersToExit(pcxt);
519 : 177 : pcxt->nworkers_launched = 0;
520 [ + - ]: 177 : if (pcxt->known_attached_workers)
521 : : {
522 : 177 : pfree(pcxt->known_attached_workers);
523 : 177 : pcxt->known_attached_workers = NULL;
524 : 177 : pcxt->nknown_attached_workers = 0;
525 : : }
526 : : }
527 : :
528 : : /* Reset a few bits of fixed parallel state to a clean state. */
529 : 177 : fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
530 : 177 : pg_atomic_write_u64(&fps->last_xlog_end, InvalidXLogRecPtr);
531 : :
532 : : /* Recreate error queues (if they exist). */
533 [ + - ]: 177 : if (pcxt->nworkers > 0)
534 : : {
535 : : char *error_queue_space;
536 : : int i;
537 : :
538 : : error_queue_space =
539 : 177 : shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, false);
540 [ + + ]: 731 : for (i = 0; i < pcxt->nworkers; ++i)
541 : : {
542 : : char *start;
543 : : shm_mq *mq;
544 : :
545 : 554 : start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
546 : 554 : mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
547 : 554 : shm_mq_set_receiver(mq, MyProc);
548 : 554 : pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
549 : : }
550 : : }
551 : :
552 : : /* Restore previous memory context. */
553 : 177 : MemoryContextSwitchTo(oldcontext);
554 : 177 : }
555 : :
556 : : /*
557 : : * Reinitialize parallel workers for a parallel context such that we could
558 : : * launch a different number of workers. This is required for cases where
559 : : * we need to reuse the same DSM segment, but the number of workers can
560 : : * vary from run-to-run.
561 : : */
562 : : void
563 : 31 : ReinitializeParallelWorkers(ParallelContext *pcxt, int nworkers_to_launch)
564 : : {
565 : : /*
566 : : * The number of workers that need to be launched must be less than the
567 : : * number of workers with which the parallel context is initialized. But
568 : : * the caller might not know that InitializeParallelDSM reduced nworkers,
569 : : * so just silently trim the request.
570 : : */
571 : 31 : pcxt->nworkers_to_launch = Min(pcxt->nworkers, nworkers_to_launch);
572 : 31 : }
573 : :
574 : : /*
575 : : * Launch parallel workers.
576 : : */
577 : : void
578 : 858 : LaunchParallelWorkers(ParallelContext *pcxt)
579 : : {
580 : : MemoryContext oldcontext;
581 : : BackgroundWorker worker;
582 : : int i;
583 : 858 : bool any_registrations_failed = false;
584 : :
585 : : /* Skip this if we have no workers. */
586 [ + - - + ]: 858 : if (pcxt->nworkers == 0 || pcxt->nworkers_to_launch == 0)
587 : 0 : return;
588 : :
589 : : /* We need to be a lock group leader. */
590 : 858 : BecomeLockGroupLeader();
591 : :
592 : : /* If we do have workers, we'd better have a DSM segment. */
593 : : Assert(pcxt->seg != NULL);
594 : :
595 : : /* We might be running in a short-lived memory context. */
596 : 858 : oldcontext = MemoryContextSwitchTo(TopTransactionContext);
597 : :
598 : : /* Configure a worker. */
599 : 858 : memset(&worker, 0, sizeof(worker));
600 : 858 : snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
601 : : MyProcPid);
602 : 858 : snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
603 : 858 : worker.bgw_flags =
604 : : BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION
605 : : | BGWORKER_CLASS_PARALLEL;
606 : 858 : worker.bgw_start_time = BgWorkerStart_ConsistentState;
607 : 858 : worker.bgw_restart_time = BGW_NEVER_RESTART;
608 : 858 : sprintf(worker.bgw_library_name, "postgres");
609 : 858 : sprintf(worker.bgw_function_name, "ParallelWorkerMain");
610 : 858 : worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
611 : 858 : worker.bgw_notify_pid = MyProcPid;
612 : :
613 : : /*
614 : : * Start workers.
615 : : *
616 : : * The caller must be able to tolerate ending up with fewer workers than
617 : : * expected, so there is no need to throw an error here if registration
618 : : * fails. It wouldn't help much anyway, because registering the worker in
619 : : * no way guarantees that it will start up and initialize successfully.
620 : : */
621 [ + + ]: 2925 : for (i = 0; i < pcxt->nworkers_to_launch; ++i)
622 : : {
623 : 2067 : memcpy(worker.bgw_extra, &i, sizeof(int));
624 [ + + + + ]: 4096 : if (!any_registrations_failed &&
625 : 2029 : RegisterDynamicBackgroundWorker(&worker,
626 : 2029 : &pcxt->worker[i].bgwhandle))
627 : : {
628 : 2007 : shm_mq_set_handle(pcxt->worker[i].error_mqh,
629 : 2007 : pcxt->worker[i].bgwhandle);
630 : 2007 : pcxt->nworkers_launched++;
631 : : }
632 : : else
633 : : {
634 : : /*
635 : : * If we weren't able to register the worker, then we've bumped up
636 : : * against the max_worker_processes limit, and future
637 : : * registrations will probably fail too, so arrange to skip them.
638 : : * But we still have to execute this code for the remaining slots
639 : : * to make sure that we forget about the error queues we budgeted
640 : : * for those workers. Otherwise, we'll wait for them to start,
641 : : * but they never will.
642 : : */
643 : 60 : any_registrations_failed = true;
644 : 60 : pcxt->worker[i].bgwhandle = NULL;
645 : 60 : shm_mq_detach(pcxt->worker[i].error_mqh);
646 : 60 : pcxt->worker[i].error_mqh = NULL;
647 : : }
648 : : }
649 : :
650 : : /*
651 : : * Now that nworkers_launched has taken its final value, we can initialize
652 : : * known_attached_workers.
653 : : */
654 [ + + ]: 858 : if (pcxt->nworkers_launched > 0)
655 : : {
656 : 845 : pcxt->known_attached_workers = palloc0_array(bool, pcxt->nworkers_launched);
657 : 845 : pcxt->nknown_attached_workers = 0;
658 : : }
659 : :
660 : : /* Restore previous memory context. */
661 : 858 : MemoryContextSwitchTo(oldcontext);
662 : : }
663 : :
664 : : /*
665 : : * Wait for all workers to attach to their error queues, and throw an error if
666 : : * any worker fails to do this.
667 : : *
668 : : * Callers can assume that if this function returns successfully, then the
669 : : * number of workers given by pcxt->nworkers_launched have initialized and
670 : : * attached to their error queues. Whether or not these workers are guaranteed
671 : : * to still be running depends on what code the caller asked them to run;
672 : : * this function does not guarantee that they have not exited. However, it
673 : : * does guarantee that any workers which exited must have done so cleanly and
674 : : * after successfully performing the work with which they were tasked.
675 : : *
676 : : * If this function is not called, then some of the workers that were launched
677 : : * may not have been started due to a fork() failure, or may have exited during
678 : : * early startup prior to attaching to the error queue, so nworkers_launched
679 : : * cannot be viewed as completely reliable. It will never be less than the
680 : : * number of workers which actually started, but it might be more. Any workers
681 : : * that failed to start will still be discovered by
682 : : * WaitForParallelWorkersToFinish and an error will be thrown at that time,
683 : : * provided that function is eventually reached.
684 : : *
685 : : * In general, the leader process should do as much work as possible before
686 : : * calling this function. fork() failures and other early-startup failures
687 : : * are very uncommon, and having the leader sit idle when it could be doing
688 : : * useful work is undesirable. However, if the leader needs to wait for
689 : : * all of its workers or for a specific worker, it may want to call this
690 : : * function before doing so. If not, it must make some other provision for
691 : : * the failure-to-start case, lest it wait forever. On the other hand, a
692 : : * leader which never waits for a worker that might not be started yet, or
693 : : * at least never does so prior to WaitForParallelWorkersToFinish(), need not
694 : : * call this function at all.
695 : : */
696 : : void
697 : 130 : WaitForParallelWorkersToAttach(ParallelContext *pcxt)
698 : : {
699 : : int i;
700 : :
701 : : /* Skip this if we have no launched workers. */
702 [ - + ]: 130 : if (pcxt->nworkers_launched == 0)
703 : 0 : return;
704 : :
705 : : for (;;)
706 : : {
707 : : /*
708 : : * This will process any parallel messages that are pending and it may
709 : : * also throw an error propagated from a worker.
710 : : */
711 [ + + ]: 7361252 : CHECK_FOR_INTERRUPTS();
712 : :
713 [ + + ]: 16065451 : for (i = 0; i < pcxt->nworkers_launched; ++i)
714 : : {
715 : : BgwHandleStatus status;
716 : : shm_mq *mq;
717 : : int rc;
718 : : pid_t pid;
719 : :
720 [ + + ]: 8704199 : if (pcxt->known_attached_workers[i])
721 : 1029570 : continue;
722 : :
723 : : /*
724 : : * If error_mqh is NULL, then the worker has already exited
725 : : * cleanly.
726 : : */
727 [ - + ]: 7674629 : if (pcxt->worker[i].error_mqh == NULL)
728 : : {
729 : 0 : pcxt->known_attached_workers[i] = true;
730 : 0 : ++pcxt->nknown_attached_workers;
731 : 0 : continue;
732 : : }
733 : :
734 : 7674629 : status = GetBackgroundWorkerPid(pcxt->worker[i].bgwhandle, &pid);
735 [ + + ]: 7674629 : if (status == BGWH_STARTED)
736 : : {
737 : : /* Has the worker attached to the error queue? */
738 : 7674552 : mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
739 [ + + ]: 7674552 : if (shm_mq_get_sender(mq) != NULL)
740 : : {
741 : : /* Yes, so it is known to be attached. */
742 : 122 : pcxt->known_attached_workers[i] = true;
743 : 122 : ++pcxt->nknown_attached_workers;
744 : : }
745 : : }
746 [ - + ]: 77 : else if (status == BGWH_STOPPED)
747 : : {
748 : : /*
749 : : * If the worker stopped without attaching to the error queue,
750 : : * throw an error.
751 : : */
752 : 0 : mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
753 [ # # ]: 0 : if (shm_mq_get_sender(mq) == NULL)
754 [ # # ]: 0 : ereport(ERROR,
755 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
756 : : errmsg("parallel worker failed to initialize"),
757 : : errhint("More details may be available in the server log.")));
758 : :
759 : 0 : pcxt->known_attached_workers[i] = true;
760 : 0 : ++pcxt->nknown_attached_workers;
761 : : }
762 : : else
763 : : {
764 : : /*
765 : : * Worker not yet started, so we must wait. The postmaster
766 : : * will notify us if the worker's state changes. Our latch
767 : : * might also get set for some other reason, but if so we'll
768 : : * just end up waiting for the same worker again.
769 : : */
770 : 77 : rc = WaitLatch(MyLatch,
771 : : WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
772 : : -1, WAIT_EVENT_BGWORKER_STARTUP);
773 : :
774 [ + - ]: 77 : if (rc & WL_LATCH_SET)
775 : 77 : ResetLatch(MyLatch);
776 : : }
777 : : }
778 : :
779 : : /* If all workers are known to have started, we're done. */
780 [ + + ]: 7361252 : if (pcxt->nknown_attached_workers >= pcxt->nworkers_launched)
781 : : {
782 : : Assert(pcxt->nknown_attached_workers == pcxt->nworkers_launched);
783 : 130 : break;
784 : : }
785 : : }
786 : : }
787 : :
788 : : /*
789 : : * Wait for all workers to finish computing.
790 : : *
791 : : * Even if the parallel operation seems to have completed successfully, it's
792 : : * important to call this function afterwards. We must not miss any errors
793 : : * the workers may have thrown during the parallel operation, or any that they
794 : : * may yet throw while shutting down.
795 : : *
796 : : * Also, we want to update our notion of XactLastRecEnd based on worker
797 : : * feedback.
798 : : */
799 : : void
800 : 1027 : WaitForParallelWorkersToFinish(ParallelContext *pcxt)
801 : : {
802 : : for (;;)
803 : 832 : {
804 : 1859 : bool anyone_alive = false;
805 : 1859 : int nfinished = 0;
806 : : int i;
807 : :
808 : : /*
809 : : * This will process any parallel messages that are pending, which may
810 : : * change the outcome of the loop that follows. It may also throw an
811 : : * error propagated from a worker.
812 : : */
813 [ + + ]: 1859 : CHECK_FOR_INTERRUPTS();
814 : :
815 [ + + ]: 6500 : for (i = 0; i < pcxt->nworkers_launched; ++i)
816 : : {
817 : : /*
818 : : * If error_mqh is NULL, then the worker has already exited
819 : : * cleanly. If we have received a message through error_mqh from
820 : : * the worker, we know it started up cleanly, and therefore we're
821 : : * certain to be notified when it exits.
822 : : */
823 [ + + ]: 4680 : if (pcxt->worker[i].error_mqh == NULL)
824 : 3787 : ++nfinished;
825 [ + + ]: 893 : else if (pcxt->known_attached_workers[i])
826 : : {
827 : 39 : anyone_alive = true;
828 : 39 : break;
829 : : }
830 : : }
831 : :
832 [ + + ]: 1859 : if (!anyone_alive)
833 : : {
834 : : /* If all workers are known to have finished, we're done. */
835 [ + + ]: 1820 : if (nfinished >= pcxt->nworkers_launched)
836 : : {
837 : : Assert(nfinished == pcxt->nworkers_launched);
838 : 1027 : break;
839 : : }
840 : :
841 : : /*
842 : : * We didn't detect any living workers, but not all workers are
843 : : * known to have exited cleanly. Either not all workers have
844 : : * launched yet, or maybe some of them failed to start or
845 : : * terminated abnormally.
846 : : */
847 [ + + ]: 2885 : for (i = 0; i < pcxt->nworkers_launched; ++i)
848 : : {
849 : : pid_t pid;
850 : : shm_mq *mq;
851 : :
852 : : /*
853 : : * If the worker is BGWH_NOT_YET_STARTED or BGWH_STARTED, we
854 : : * should just keep waiting. If it is BGWH_STOPPED, then
855 : : * further investigation is needed.
856 : : */
857 [ + + ]: 2092 : if (pcxt->worker[i].error_mqh == NULL ||
858 [ + - + - ]: 1708 : pcxt->worker[i].bgwhandle == NULL ||
859 : 854 : GetBackgroundWorkerPid(pcxt->worker[i].bgwhandle,
860 : : &pid) != BGWH_STOPPED)
861 : 2092 : continue;
862 : :
863 : : /*
864 : : * Check whether the worker ended up stopped without ever
865 : : * attaching to the error queue. If so, the postmaster was
866 : : * unable to fork the worker or it exited without initializing
867 : : * properly. We must throw an error, since the caller may
868 : : * have been expecting the worker to do some work before
869 : : * exiting.
870 : : */
871 : 0 : mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
872 [ # # ]: 0 : if (shm_mq_get_sender(mq) == NULL)
873 [ # # ]: 0 : ereport(ERROR,
874 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
875 : : errmsg("parallel worker failed to initialize"),
876 : : errhint("More details may be available in the server log.")));
877 : :
878 : : /*
879 : : * The worker is stopped, but is attached to the error queue.
880 : : * Unless there's a bug somewhere, this will only happen when
881 : : * the worker writes messages and terminates after the
882 : : * CHECK_FOR_INTERRUPTS() near the top of this function and
883 : : * before the call to GetBackgroundWorkerPid(). In that case,
884 : : * our latch should have been set as well and the right things
885 : : * will happen on the next pass through the loop.
886 : : */
887 : : }
888 : : }
889 : :
890 : 832 : (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, -1,
891 : : WAIT_EVENT_PARALLEL_FINISH);
892 : 832 : ResetLatch(MyLatch);
893 : : }
894 : :
895 [ + - ]: 1027 : if (pcxt->toc != NULL)
896 : : {
897 : : FixedParallelState *fps;
898 : : XLogRecPtr last_xlog_end;
899 : :
900 : 1027 : fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
901 : 1027 : last_xlog_end = pg_atomic_read_u64(&fps->last_xlog_end);
902 [ + + ]: 1027 : if (last_xlog_end > XactLastRecEnd)
903 : 57 : XactLastRecEnd = last_xlog_end;
904 : : }
905 : 1027 : }
906 : :
907 : : /*
908 : : * Wait for all workers to exit.
909 : : *
910 : : * This function ensures that workers have been completely shutdown. The
911 : : * difference between WaitForParallelWorkersToFinish and this function is
912 : : * that the former just ensures that last message sent by a worker backend is
913 : : * received by the leader backend whereas this ensures the complete shutdown.
914 : : */
915 : : static void
916 : 858 : WaitForParallelWorkersToExit(ParallelContext *pcxt)
917 : : {
918 : : int i;
919 : :
920 : : /* Wait until the workers actually die. */
921 [ + + ]: 2865 : for (i = 0; i < pcxt->nworkers_launched; ++i)
922 : : {
923 : : BgwHandleStatus status;
924 : :
925 [ + - - + ]: 2007 : if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
926 : 0 : continue;
927 : :
928 : 2007 : status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
929 : :
930 : : /*
931 : : * If the postmaster kicked the bucket, we have no chance of cleaning
932 : : * up safely -- we won't be able to tell when our workers are actually
933 : : * dead. This doesn't necessitate a PANIC since they will all abort
934 : : * eventually, but we can't safely continue this session.
935 : : */
936 [ - + ]: 2007 : if (status == BGWH_POSTMASTER_DIED)
937 [ # # ]: 0 : ereport(FATAL,
938 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
939 : : errmsg("postmaster exited during a parallel transaction")));
940 : :
941 : : /* Release memory. */
942 : 2007 : pfree(pcxt->worker[i].bgwhandle);
943 : 2007 : pcxt->worker[i].bgwhandle = NULL;
944 : : }
945 : 858 : }
946 : :
947 : : /*
948 : : * Destroy a parallel context.
949 : : *
950 : : * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
951 : : * first, before calling this function. When this function is invoked, any
952 : : * remaining workers are forcibly killed; the dynamic shared memory segment
953 : : * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
954 : : */
955 : : void
956 : 681 : DestroyParallelContext(ParallelContext *pcxt)
957 : : {
958 : : int i;
959 : :
960 : : /*
961 : : * Be careful about order of operations here! We remove the parallel
962 : : * context from the list before we do anything else; otherwise, if an
963 : : * error occurs during a subsequent step, we might try to nuke it again
964 : : * from AtEOXact_Parallel or AtEOSubXact_Parallel.
965 : : */
966 : 681 : dlist_delete(&pcxt->node);
967 : :
968 : : /* Kill each worker in turn, and forget their error queues. */
969 [ + - ]: 681 : if (pcxt->worker != NULL)
970 : : {
971 [ + + ]: 2138 : for (i = 0; i < pcxt->nworkers_launched; ++i)
972 : : {
973 [ + + ]: 1457 : if (pcxt->worker[i].error_mqh != NULL)
974 : : {
975 : 8 : TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
976 : :
977 : 8 : shm_mq_detach(pcxt->worker[i].error_mqh);
978 : 8 : pcxt->worker[i].error_mqh = NULL;
979 : : }
980 : : }
981 : : }
982 : :
983 : : /*
984 : : * If we have allocated a shared memory segment, detach it. This will
985 : : * implicitly detach the error queues, and any other shared memory queues,
986 : : * stored there.
987 : : */
988 [ + - ]: 681 : if (pcxt->seg != NULL)
989 : : {
990 : 681 : dsm_detach(pcxt->seg);
991 : 681 : pcxt->seg = NULL;
992 : : }
993 : :
994 : : /*
995 : : * If this parallel context is actually in backend-private memory rather
996 : : * than shared memory, free that memory instead.
997 : : */
998 [ - + ]: 681 : if (pcxt->private_memory != NULL)
999 : : {
1000 : 0 : pfree(pcxt->private_memory);
1001 : 0 : pcxt->private_memory = NULL;
1002 : : }
1003 : :
1004 : : /*
1005 : : * We can't finish transaction commit or abort until all of the workers
1006 : : * have exited. This means, in particular, that we can't respond to
1007 : : * interrupts at this stage.
1008 : : */
1009 : 681 : HOLD_INTERRUPTS();
1010 : 681 : WaitForParallelWorkersToExit(pcxt);
1011 : 681 : RESUME_INTERRUPTS();
1012 : :
1013 : : /* Free the worker array itself. */
1014 [ + - ]: 681 : if (pcxt->worker != NULL)
1015 : : {
1016 : 681 : pfree(pcxt->worker);
1017 : 681 : pcxt->worker = NULL;
1018 : : }
1019 : :
1020 : : /* Free memory. */
1021 : 681 : pfree(pcxt->library_name);
1022 : 681 : pfree(pcxt->function_name);
1023 : 681 : pfree(pcxt);
1024 : 681 : }
1025 : :
1026 : : /*
1027 : : * Are there any parallel contexts currently active?
1028 : : */
1029 : : bool
1030 : 0 : ParallelContextActive(void)
1031 : : {
1032 : 0 : return !dlist_is_empty(&pcxt_list);
1033 : : }
1034 : :
1035 : : /*
1036 : : * Handle receipt of an interrupt indicating a parallel worker message.
1037 : : *
1038 : : * Note: this is called within a signal handler! All we can do is set
1039 : : * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
1040 : : * ProcessParallelMessages().
1041 : : */
1042 : : void
1043 : 2148 : HandleParallelMessageInterrupt(void)
1044 : : {
1045 : 2148 : InterruptPending = true;
1046 : 2148 : ParallelMessagePending = true;
1047 : : /* latch will be set by procsignal_sigusr1_handler */
1048 : 2148 : }
1049 : :
1050 : : /*
1051 : : * Process any queued protocol messages received from parallel workers.
1052 : : */
1053 : : void
1054 : 2102 : ProcessParallelMessages(void)
1055 : : {
1056 : : dlist_iter iter;
1057 : : MemoryContext oldcontext;
1058 : :
1059 : : static MemoryContext hpm_context = NULL;
1060 : :
1061 : : /*
1062 : : * This is invoked from ProcessInterrupts(), and since some of the
1063 : : * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
1064 : : * for recursive calls if more signals are received while this runs. It's
1065 : : * unclear that recursive entry would be safe, and it doesn't seem useful
1066 : : * even if it is safe, so let's block interrupts until done.
1067 : : */
1068 : 2102 : HOLD_INTERRUPTS();
1069 : :
1070 : : /*
1071 : : * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
1072 : : * don't want to risk leaking data into long-lived contexts, so let's do
1073 : : * our work here in a private context that we can reset on each use.
1074 : : */
1075 [ + + ]: 2102 : if (hpm_context == NULL) /* first time through? */
1076 : 119 : hpm_context = AllocSetContextCreate(TopMemoryContext,
1077 : : "ProcessParallelMessages",
1078 : : ALLOCSET_DEFAULT_SIZES);
1079 : : else
1080 : 1983 : MemoryContextReset(hpm_context);
1081 : :
1082 : 2102 : oldcontext = MemoryContextSwitchTo(hpm_context);
1083 : :
1084 : : /* OK to process messages. Reset the flag saying there are more to do. */
1085 : 2102 : ParallelMessagePending = false;
1086 : :
1087 [ + - + + ]: 4312 : dlist_foreach(iter, &pcxt_list)
1088 : : {
1089 : : ParallelContext *pcxt;
1090 : : int i;
1091 : :
1092 : 2218 : pcxt = dlist_container(ParallelContext, node, iter.cur);
1093 [ - + ]: 2218 : if (pcxt->worker == NULL)
1094 : 0 : continue;
1095 : :
1096 [ + + ]: 8884 : for (i = 0; i < pcxt->nworkers_launched; ++i)
1097 : : {
1098 : : /*
1099 : : * Read as many messages as we can from each worker, but stop when
1100 : : * either (1) the worker's error queue goes away, which can happen
1101 : : * if we receive a Terminate message from the worker; or (2) no
1102 : : * more messages can be read from the worker without blocking.
1103 : : */
1104 [ + + ]: 8679 : while (pcxt->worker[i].error_mqh != NULL)
1105 : : {
1106 : : shm_mq_result res;
1107 : : Size nbytes;
1108 : : void *data;
1109 : :
1110 : 3926 : res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
1111 : : &data, true);
1112 [ + + ]: 3926 : if (res == SHM_MQ_WOULD_BLOCK)
1113 : 1913 : break;
1114 [ + - ]: 2013 : else if (res == SHM_MQ_SUCCESS)
1115 : : {
1116 : : StringInfoData msg;
1117 : :
1118 : 2013 : initStringInfo(&msg);
1119 : 2013 : appendBinaryStringInfo(&msg, data, nbytes);
1120 : 2013 : ProcessParallelMessage(pcxt, i, &msg);
1121 : 2005 : pfree(msg.data);
1122 : : }
1123 : : else
1124 [ # # ]: 0 : ereport(ERROR,
1125 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1126 : : errmsg("lost connection to parallel worker")));
1127 : : }
1128 : : }
1129 : : }
1130 : :
1131 : 2094 : MemoryContextSwitchTo(oldcontext);
1132 : :
1133 : : /* Might as well clear the context on our way out */
1134 : 2094 : MemoryContextReset(hpm_context);
1135 : :
1136 : 2094 : RESUME_INTERRUPTS();
1137 : 2094 : }
1138 : :
1139 : : /*
1140 : : * Process a single protocol message received from a single parallel worker.
1141 : : */
1142 : : static void
1143 : 2013 : ProcessParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
1144 : : {
1145 : : char msgtype;
1146 : :
1147 [ + - ]: 2013 : if (pcxt->known_attached_workers != NULL &&
1148 [ + + ]: 2013 : !pcxt->known_attached_workers[i])
1149 : : {
1150 : 1885 : pcxt->known_attached_workers[i] = true;
1151 : 1885 : pcxt->nknown_attached_workers++;
1152 : : }
1153 : :
1154 : 2013 : msgtype = pq_getmsgbyte(msg);
1155 : :
1156 [ + - + + : 2013 : switch (msgtype)
- ]
1157 : : {
1158 : 8 : case PqMsg_ErrorResponse:
1159 : : case PqMsg_NoticeResponse:
1160 : : {
1161 : : ErrorData edata;
1162 : : ErrorContextCallback *save_error_context_stack;
1163 : :
1164 : : /* Parse ErrorResponse or NoticeResponse. */
1165 : 8 : pq_parse_errornotice(msg, &edata);
1166 : :
1167 : : /* Death of a worker isn't enough justification for suicide. */
1168 : 8 : edata.elevel = Min(edata.elevel, ERROR);
1169 : :
1170 : : /*
1171 : : * If desired, add a context line to show that this is a
1172 : : * message propagated from a parallel worker. Otherwise, it
1173 : : * can sometimes be confusing to understand what actually
1174 : : * happened. (We don't do this in DEBUG_PARALLEL_REGRESS mode
1175 : : * because it causes test-result instability depending on
1176 : : * whether a parallel worker is actually used or not.)
1177 : : */
1178 [ + - ]: 8 : if (debug_parallel_query != DEBUG_PARALLEL_REGRESS)
1179 : : {
1180 [ + + ]: 8 : if (edata.context)
1181 : 4 : edata.context = psprintf("%s\n%s", edata.context,
1182 : : _("parallel worker"));
1183 : : else
1184 : 4 : edata.context = pstrdup(_("parallel worker"));
1185 : : }
1186 : :
1187 : : /*
1188 : : * Context beyond that should use the error context callbacks
1189 : : * that were in effect when the ParallelContext was created,
1190 : : * not the current ones.
1191 : : */
1192 : 8 : save_error_context_stack = error_context_stack;
1193 : 8 : error_context_stack = pcxt->error_context_stack;
1194 : :
1195 : : /* Rethrow error or print notice. */
1196 : 8 : ThrowErrorData(&edata);
1197 : :
1198 : : /* Not an error, so restore previous context stack. */
1199 : 0 : error_context_stack = save_error_context_stack;
1200 : :
1201 : 0 : break;
1202 : : }
1203 : :
1204 : 0 : case PqMsg_NotificationResponse:
1205 : : {
1206 : : /* Propagate NotifyResponse. */
1207 : : int32 pid;
1208 : : const char *channel;
1209 : : const char *payload;
1210 : :
1211 : 0 : pid = pq_getmsgint(msg, 4);
1212 : 0 : channel = pq_getmsgrawstring(msg);
1213 : 0 : payload = pq_getmsgrawstring(msg);
1214 : 0 : pq_endmessage(msg);
1215 : :
1216 : 0 : NotifyMyFrontEnd(channel, payload, pid);
1217 : :
1218 : 0 : break;
1219 : : }
1220 : :
1221 : 6 : case PqMsg_Progress:
1222 : : {
1223 : : /*
1224 : : * Only incremental progress reporting is currently supported.
1225 : : * However, it's possible to add more fields to the message to
1226 : : * allow for handling of other backend progress APIs.
1227 : : */
1228 : 6 : int index = pq_getmsgint(msg, 4);
1229 : 6 : int64 incr = pq_getmsgint64(msg);
1230 : :
1231 : 6 : pq_getmsgend(msg);
1232 : :
1233 : 6 : pgstat_progress_incr_param(index, incr);
1234 : :
1235 : 6 : break;
1236 : : }
1237 : :
1238 : 1999 : case PqMsg_Terminate:
1239 : : {
1240 : 1999 : shm_mq_detach(pcxt->worker[i].error_mqh);
1241 : 1999 : pcxt->worker[i].error_mqh = NULL;
1242 : 1999 : break;
1243 : : }
1244 : :
1245 : 0 : default:
1246 : : {
1247 [ # # ]: 0 : elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
1248 : : msgtype, msg->len);
1249 : : }
1250 : : }
1251 : 2005 : }
1252 : :
1253 : : /*
1254 : : * End-of-subtransaction cleanup for parallel contexts.
1255 : : *
1256 : : * Here we remove only parallel contexts initiated within the current
1257 : : * subtransaction.
1258 : : */
1259 : : void
1260 : 22873 : AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
1261 : : {
1262 [ + + ]: 22877 : while (!dlist_is_empty(&pcxt_list))
1263 : : {
1264 : : ParallelContext *pcxt;
1265 : :
1266 : 4 : pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
1267 [ - + ]: 4 : if (pcxt->subid != mySubId)
1268 : 0 : break;
1269 [ - + ]: 4 : if (isCommit)
1270 [ # # ]: 0 : elog(WARNING, "leaked parallel context");
1271 : 4 : DestroyParallelContext(pcxt);
1272 : : }
1273 : 22873 : }
1274 : :
1275 : : /*
1276 : : * End-of-transaction cleanup for parallel contexts.
1277 : : *
1278 : : * We nuke all remaining parallel contexts.
1279 : : */
1280 : : void
1281 : 665141 : AtEOXact_Parallel(bool isCommit)
1282 : : {
1283 [ + + ]: 665145 : while (!dlist_is_empty(&pcxt_list))
1284 : : {
1285 : : ParallelContext *pcxt;
1286 : :
1287 : 4 : pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
1288 [ - + ]: 4 : if (isCommit)
1289 [ # # ]: 0 : elog(WARNING, "leaked parallel context");
1290 : 4 : DestroyParallelContext(pcxt);
1291 : : }
1292 : 665141 : }
1293 : :
1294 : : /*
1295 : : * Main entrypoint for parallel workers.
1296 : : */
1297 : : void
1298 : 2007 : ParallelWorkerMain(Datum main_arg)
1299 : : {
1300 : : dsm_segment *seg;
1301 : : shm_toc *toc;
1302 : : FixedParallelState *fps;
1303 : : char *error_queue_space;
1304 : : shm_mq *mq;
1305 : : shm_mq_handle *mqh;
1306 : : char *libraryspace;
1307 : : char *entrypointstate;
1308 : : char *library_name;
1309 : : char *function_name;
1310 : : parallel_worker_main_type entrypt;
1311 : : char *gucspace;
1312 : : char *combocidspace;
1313 : : char *tsnapspace;
1314 : : char *asnapspace;
1315 : : char *tstatespace;
1316 : : char *pendingsyncsspace;
1317 : : char *reindexspace;
1318 : : char *relmapperspace;
1319 : : char *uncommittedenumsspace;
1320 : : char *clientconninfospace;
1321 : : char *session_dsm_handle_space;
1322 : : Snapshot tsnapshot;
1323 : : Snapshot asnapshot;
1324 : :
1325 : : /* Set flag to indicate that we're initializing a parallel worker. */
1326 : 2007 : InitializingParallelWorker = true;
1327 : :
1328 : : /* Establish signal handlers. */
1329 : 2007 : BackgroundWorkerUnblockSignals();
1330 : :
1331 : : /* Determine and set our parallel worker number. */
1332 : : Assert(ParallelWorkerNumber == -1);
1333 : 2007 : memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
1334 : :
1335 : : /* Set up a memory context to work in, just for cleanliness. */
1336 : 2007 : CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
1337 : : "Parallel worker",
1338 : : ALLOCSET_DEFAULT_SIZES);
1339 : :
1340 : : /*
1341 : : * Attach to the dynamic shared memory segment for the parallel query, and
1342 : : * find its table of contents.
1343 : : *
1344 : : * Note: at this point, we have not created any ResourceOwner in this
1345 : : * process. This will result in our DSM mapping surviving until process
1346 : : * exit, which is fine. If there were a ResourceOwner, it would acquire
1347 : : * ownership of the mapping, but we have no need for that.
1348 : : */
1349 : 2007 : seg = dsm_attach(DatumGetUInt32(main_arg));
1350 [ - + ]: 2007 : if (seg == NULL)
1351 [ # # ]: 0 : ereport(ERROR,
1352 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1353 : : errmsg("could not map dynamic shared memory segment")));
1354 : 2007 : toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
1355 [ - + ]: 2007 : if (toc == NULL)
1356 [ # # ]: 0 : ereport(ERROR,
1357 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1358 : : errmsg("invalid magic number in dynamic shared memory segment")));
1359 : :
1360 : : /* Look up fixed parallel state. */
1361 : 2007 : fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1362 : 2007 : MyFixedParallelState = fps;
1363 : :
1364 : : /* Arrange to signal the leader if we exit. */
1365 : 2007 : ParallelLeaderPid = fps->parallel_leader_pid;
1366 : 2007 : ParallelLeaderProcNumber = fps->parallel_leader_proc_number;
1367 : 2007 : before_shmem_exit(ParallelWorkerShutdown, PointerGetDatum(seg));
1368 : :
1369 : : /*
1370 : : * Now we can find and attach to the error queue provided for us. That's
1371 : : * good, because until we do that, any errors that happen here will not be
1372 : : * reported back to the process that requested that this worker be
1373 : : * launched.
1374 : : */
1375 : 2007 : error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1376 : 2007 : mq = (shm_mq *) (error_queue_space +
1377 : 2007 : ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
1378 : 2007 : shm_mq_set_sender(mq, MyProc);
1379 : 2007 : mqh = shm_mq_attach(mq, seg, NULL);
1380 : 2007 : pq_redirect_to_shm_mq(seg, mqh);
1381 : 2007 : pq_set_parallel_leader(fps->parallel_leader_pid,
1382 : : fps->parallel_leader_proc_number);
1383 : :
1384 : : /*
1385 : : * Hooray! Primary initialization is complete. Now, we need to set up our
1386 : : * backend-local state to match the original backend.
1387 : : */
1388 : :
1389 : : /*
1390 : : * Join locking group. We must do this before anything that could try to
1391 : : * acquire a heavyweight lock, because any heavyweight locks acquired to
1392 : : * this point could block either directly against the parallel group
1393 : : * leader or against some process which in turn waits for a lock that
1394 : : * conflicts with the parallel group leader, causing an undetected
1395 : : * deadlock. (If we can't join the lock group, the leader has gone away,
1396 : : * so just exit quietly.)
1397 : : */
1398 [ - + ]: 2007 : if (!BecomeLockGroupMember(fps->parallel_leader_pgproc,
1399 : : fps->parallel_leader_pid))
1400 : 0 : return;
1401 : :
1402 : : /*
1403 : : * Restore transaction and statement start-time timestamps. This must
1404 : : * happen before anything that would start a transaction, else asserts in
1405 : : * xact.c will fire.
1406 : : */
1407 : 2007 : SetParallelStartTimestamps(fps->xact_ts, fps->stmt_ts);
1408 : :
1409 : : /*
1410 : : * Identify the entry point to be called. In theory this could result in
1411 : : * loading an additional library, though most likely the entry point is in
1412 : : * the core backend or in a library we just loaded.
1413 : : */
1414 : 2007 : entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1415 : 2007 : library_name = entrypointstate;
1416 : 2007 : function_name = entrypointstate + strlen(library_name) + 1;
1417 : :
1418 : 2007 : entrypt = LookupParallelWorkerFunction(library_name, function_name);
1419 : :
1420 : : /*
1421 : : * Restore current session authorization and role id. No verification
1422 : : * happens here, we just blindly adopt the leader's state. Note that this
1423 : : * has to happen before InitPostgres, since InitializeSessionUserId will
1424 : : * not set these variables.
1425 : : */
1426 : 2007 : SetAuthenticatedUserId(fps->authenticated_user_id);
1427 : 2007 : SetSessionAuthorization(fps->session_user_id,
1428 : 2007 : fps->session_user_is_superuser);
1429 : 2007 : SetCurrentRoleId(fps->outer_user_id, fps->role_is_superuser);
1430 : :
1431 : : /*
1432 : : * Restore database connection. We skip connection authorization checks,
1433 : : * reasoning that (a) the leader checked these things when it started, and
1434 : : * (b) we do not want parallel mode to cause these failures, because that
1435 : : * would make use of parallel query plans not transparent to applications.
1436 : : */
1437 : 2007 : BackgroundWorkerInitializeConnectionByOid(fps->database_id,
1438 : : fps->authenticated_user_id,
1439 : : BGWORKER_BYPASS_ALLOWCONN |
1440 : : BGWORKER_BYPASS_ROLELOGINCHECK);
1441 : :
1442 : : /*
1443 : : * Set the client encoding to the database encoding, since that is what
1444 : : * the leader will expect. (We're cheating a bit by not calling
1445 : : * PrepareClientEncoding first. It's okay because this call will always
1446 : : * result in installing a no-op conversion. No error should be possible,
1447 : : * but check anyway.)
1448 : : */
1449 [ - + ]: 2007 : if (SetClientEncoding(GetDatabaseEncoding()) < 0)
1450 [ # # ]: 0 : elog(ERROR, "SetClientEncoding(%d) failed", GetDatabaseEncoding());
1451 : :
1452 : : /*
1453 : : * Load libraries that were loaded by original backend. We want to do
1454 : : * this before restoring GUCs, because the libraries might define custom
1455 : : * variables.
1456 : : */
1457 : 2007 : libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1458 : 2007 : StartTransactionCommand();
1459 : 2007 : RestoreLibraryState(libraryspace);
1460 : 2007 : CommitTransactionCommand();
1461 : :
1462 : : /* Crank up a transaction state appropriate to a parallel worker. */
1463 : 2007 : tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1464 : 2007 : StartParallelWorkerTransaction(tstatespace);
1465 : :
1466 : : /*
1467 : : * Restore state that affects catalog access. Ideally we'd do this even
1468 : : * before calling InitPostgres, but that has order-of-initialization
1469 : : * problems, and also the relmapper would get confused during the
1470 : : * CommitTransactionCommand call above.
1471 : : */
1472 : 2007 : pendingsyncsspace = shm_toc_lookup(toc, PARALLEL_KEY_PENDING_SYNCS,
1473 : : false);
1474 : 2007 : RestorePendingSyncs(pendingsyncsspace);
1475 : 2007 : relmapperspace = shm_toc_lookup(toc, PARALLEL_KEY_RELMAPPER_STATE, false);
1476 : 2007 : RestoreRelationMap(relmapperspace);
1477 : 2007 : reindexspace = shm_toc_lookup(toc, PARALLEL_KEY_REINDEX_STATE, false);
1478 : 2007 : RestoreReindexState(reindexspace);
1479 : 2007 : combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1480 : 2007 : RestoreComboCIDState(combocidspace);
1481 : :
1482 : : /* Attach to the per-session DSM segment and contained objects. */
1483 : : session_dsm_handle_space =
1484 : 2007 : shm_toc_lookup(toc, PARALLEL_KEY_SESSION_DSM, false);
1485 : 2007 : AttachSession(*(dsm_handle *) session_dsm_handle_space);
1486 : :
1487 : : /*
1488 : : * If the transaction isolation level is REPEATABLE READ or SERIALIZABLE,
1489 : : * the leader has serialized the transaction snapshot and we must restore
1490 : : * it. At lower isolation levels, there is no transaction-lifetime
1491 : : * snapshot, but we need TransactionXmin to get set to a value which is
1492 : : * less than or equal to the xmin of every snapshot that will be used by
1493 : : * this worker. The easiest way to accomplish that is to install the
1494 : : * active snapshot as the transaction snapshot. Code running in this
1495 : : * parallel worker might take new snapshots via GetTransactionSnapshot()
1496 : : * or GetLatestSnapshot(), but it shouldn't have any way of acquiring a
1497 : : * snapshot older than the active snapshot.
1498 : : */
1499 : 2007 : asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1500 : 2007 : tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, true);
1501 : 2007 : asnapshot = RestoreSnapshot(asnapspace);
1502 [ + + ]: 2007 : tsnapshot = tsnapspace ? RestoreSnapshot(tsnapspace) : asnapshot;
1503 : 2007 : RestoreTransactionSnapshot(tsnapshot,
1504 : 2007 : fps->parallel_leader_pgproc);
1505 : 2007 : PushActiveSnapshot(asnapshot);
1506 : :
1507 : : /*
1508 : : * We've changed which tuples we can see, and must therefore invalidate
1509 : : * system caches.
1510 : : */
1511 : 2007 : InvalidateSystemCaches();
1512 : :
1513 : : /*
1514 : : * Restore GUC values from launching backend. We can't do this earlier,
1515 : : * because GUC check hooks that do catalog lookups need to see the same
1516 : : * database state as the leader. Also, the check hooks for
1517 : : * session_authorization and role assume we already set the correct role
1518 : : * OIDs.
1519 : : */
1520 : 2007 : gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1521 : 2007 : RestoreGUCState(gucspace);
1522 : :
1523 : : /*
1524 : : * Restore current user ID and security context. No verification happens
1525 : : * here, we just blindly adopt the leader's state. We can't do this till
1526 : : * after restoring GUCs, else we'll get complaints about restoring
1527 : : * session_authorization and role. (In effect, we're assuming that all
1528 : : * the restored values are okay to set, even if we are now inside a
1529 : : * restricted context.)
1530 : : */
1531 : 2007 : SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1532 : :
1533 : : /* Restore temp-namespace state to ensure search path matches leader's. */
1534 : 2007 : SetTempNamespaceState(fps->temp_namespace_id,
1535 : : fps->temp_toast_namespace_id);
1536 : :
1537 : : /* Restore uncommitted enums. */
1538 : 2007 : uncommittedenumsspace = shm_toc_lookup(toc, PARALLEL_KEY_UNCOMMITTEDENUMS,
1539 : : false);
1540 : 2007 : RestoreUncommittedEnums(uncommittedenumsspace);
1541 : :
1542 : : /* Restore the ClientConnectionInfo. */
1543 : 2007 : clientconninfospace = shm_toc_lookup(toc, PARALLEL_KEY_CLIENTCONNINFO,
1544 : : false);
1545 : 2007 : RestoreClientConnectionInfo(clientconninfospace);
1546 : :
1547 : : /*
1548 : : * Initialize SystemUser now that MyClientConnectionInfo is restored. Also
1549 : : * ensure that auth_method is actually valid, aka authn_id is not NULL.
1550 : : */
1551 [ + + ]: 2007 : if (MyClientConnectionInfo.authn_id)
1552 : 2 : InitializeSystemUser(MyClientConnectionInfo.authn_id,
1553 : : hba_authname(MyClientConnectionInfo.auth_method));
1554 : :
1555 : : /* Attach to the leader's serializable transaction, if SERIALIZABLE. */
1556 : 2007 : AttachSerializableXact(fps->serializable_xact_handle);
1557 : :
1558 : : /*
1559 : : * We've initialized all of our state now; nothing should change
1560 : : * hereafter.
1561 : : */
1562 : 2007 : InitializingParallelWorker = false;
1563 : 2007 : EnterParallelMode();
1564 : :
1565 : : /*
1566 : : * Time to do the real work: invoke the caller-supplied code.
1567 : : */
1568 : 2007 : entrypt(seg, toc);
1569 : :
1570 : : /* Must exit parallel mode to pop active snapshot. */
1571 : 1999 : ExitParallelMode();
1572 : :
1573 : : /* Must pop active snapshot so snapmgr.c doesn't complain. */
1574 : 1999 : PopActiveSnapshot();
1575 : :
1576 : : /* Shut down the parallel-worker transaction. */
1577 : 1999 : EndParallelWorkerTransaction();
1578 : :
1579 : : /* Detach from the per-session DSM segment. */
1580 : 1999 : DetachSession();
1581 : :
1582 : : /* Report success. */
1583 : 1999 : pq_putmessage(PqMsg_Terminate, NULL, 0);
1584 : : }
1585 : :
1586 : : /*
1587 : : * Update shared memory with the ending location of the last WAL record we
1588 : : * wrote, if it's greater than the value already stored there.
1589 : : */
1590 : : void
1591 : 1999 : ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1592 : : {
1593 : 1999 : FixedParallelState *fps = MyFixedParallelState;
1594 : :
1595 : : Assert(fps != NULL);
1596 : 1999 : pg_atomic_monotonic_advance_u64(&fps->last_xlog_end, last_xlog_end);
1597 : 1999 : }
1598 : :
1599 : : /*
1600 : : * Make sure the leader tries to read from our error queue one more time.
1601 : : * This guards against the case where we exit uncleanly without sending an
1602 : : * ErrorResponse to the leader, for example because some code calls proc_exit
1603 : : * directly.
1604 : : *
1605 : : * Also explicitly detach from dsm segment so that subsystems using
1606 : : * on_dsm_detach() have a chance to send stats before the stats subsystem is
1607 : : * shut down as part of a before_shmem_exit() hook.
1608 : : *
1609 : : * One might think this could instead be solved by carefully ordering the
1610 : : * attaching to dsm segments, so that the pgstats segments get detached from
1611 : : * later than the parallel query one. That turns out to not work because the
1612 : : * stats hash might need to grow which can cause new segments to be allocated,
1613 : : * which then will be detached from earlier.
1614 : : */
1615 : : static void
1616 : 2007 : ParallelWorkerShutdown(int code, Datum arg)
1617 : : {
1618 : 2007 : SendProcSignal(ParallelLeaderPid,
1619 : : PROCSIG_PARALLEL_MESSAGE,
1620 : : ParallelLeaderProcNumber);
1621 : :
1622 : 2007 : dsm_detach((dsm_segment *) DatumGetPointer(arg));
1623 : 2007 : }
1624 : :
1625 : : /*
1626 : : * Look up (and possibly load) a parallel worker entry point function.
1627 : : *
1628 : : * For functions contained in the core code, we use library name "postgres"
1629 : : * and consult the InternalParallelWorkers array. External functions are
1630 : : * looked up, and loaded if necessary, using load_external_function().
1631 : : *
1632 : : * The point of this is to pass function names as strings across process
1633 : : * boundaries. We can't pass actual function addresses because of the
1634 : : * possibility that the function has been loaded at a different address
1635 : : * in a different process. This is obviously a hazard for functions in
1636 : : * loadable libraries, but it can happen even for functions in the core code
1637 : : * on platforms using EXEC_BACKEND (e.g., Windows).
1638 : : *
1639 : : * At some point it might be worthwhile to get rid of InternalParallelWorkers[]
1640 : : * in favor of applying load_external_function() for core functions too;
1641 : : * but that raises portability issues that are not worth addressing now.
1642 : : */
1643 : : static parallel_worker_main_type
1644 : 2007 : LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
1645 : : {
1646 : : /*
1647 : : * If the function is to be loaded from postgres itself, search the
1648 : : * InternalParallelWorkers array.
1649 : : */
1650 [ + - ]: 2007 : if (strcmp(libraryname, "postgres") == 0)
1651 : : {
1652 [ + - ]: 2395 : for (size_t i = 0; i < lengthof(InternalParallelWorkers); i++)
1653 : : {
1654 [ + + ]: 2395 : if (strcmp(InternalParallelWorkers[i].fn_name, funcname) == 0)
1655 : 2007 : return InternalParallelWorkers[i].fn_addr;
1656 : : }
1657 : :
1658 : : /* We can only reach this by programming error. */
1659 [ # # ]: 0 : elog(ERROR, "internal function \"%s\" not found", funcname);
1660 : : }
1661 : :
1662 : : /* Otherwise load from external library. */
1663 : 0 : return (parallel_worker_main_type)
1664 : 0 : load_external_function(libraryname, funcname, true, NULL);
1665 : : }
|