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