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