1 /*-------------------------------------------------------------------------
4 * Infrastructure for launching parallel workers
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/access/transam/parallel.c
12 *-------------------------------------------------------------------------
17 #include "access/parallel.h"
18 #include "access/xact.h"
19 #include "access/xlog.h"
20 #include "catalog/namespace.h"
21 #include "commands/async.h"
22 #include "libpq/libpq.h"
23 #include "libpq/pqformat.h"
24 #include "libpq/pqmq.h"
25 #include "miscadmin.h"
26 #include "optimizer/planmain.h"
27 #include "storage/ipc.h"
28 #include "storage/sinval.h"
29 #include "storage/spin.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/combocid.h"
32 #include "utils/guc.h"
33 #include "utils/inval.h"
34 #include "utils/memutils.h"
35 #include "utils/resowner.h"
36 #include "utils/snapmgr.h"
40 * We don't want to waste a lot of memory on an error queue which, most of
41 * the time, will process only a handful of small messages. However, it is
42 * desirable to make it large enough that a typical ErrorResponse can be sent
43 * without blocking. That way, a worker that errors out can write the whole
44 * message into the queue and terminate without waiting for the user backend.
46 #define PARALLEL_ERROR_QUEUE_SIZE 16384
48 /* Magic number for parallel context TOC. */
49 #define PARALLEL_MAGIC 0x50477c7c
52 * Magic numbers for parallel state sharing. Higher-level code should use
53 * smaller values, leaving these very large ones for use by this module.
55 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
56 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
57 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
58 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
59 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
60 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
61 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
62 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
63 #define PARALLEL_KEY_EXTENSION_TRAMPOLINE UINT64CONST(0xFFFFFFFFFFFF0009)
65 /* Fixed-size parallel state. */
66 typedef struct FixedParallelState
68 /* Fixed-size state that workers must restore. */
70 Oid authenticated_user_id;
72 Oid temp_namespace_id;
73 Oid temp_toast_namespace_id;
75 PGPROC *parallel_master_pgproc;
76 pid_t parallel_master_pid;
77 BackendId parallel_master_backend_id;
79 /* Entrypoint for parallel workers. */
80 parallel_worker_main_type entrypoint;
82 /* Mutex protects remaining fields. */
85 /* Maximum XactLastRecEnd of any worker. */
86 XLogRecPtr last_xlog_end;
90 * Our parallel worker number. We initialize this to -1, meaning that we are
91 * not a parallel worker. In parallel workers, it will be set to a value >= 0
92 * and < the number of workers before any user code is invoked; each parallel
93 * worker will get a different parallel worker number.
95 int ParallelWorkerNumber = -1;
97 /* Is there a parallel message pending which we need to receive? */
98 volatile bool ParallelMessagePending = false;
100 /* Are we initializing a parallel worker? */
101 bool InitializingParallelWorker = false;
103 /* Pointer to our fixed parallel state. */
104 static FixedParallelState *MyFixedParallelState;
106 /* List of active parallel contexts. */
107 static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list);
109 /* Private functions. */
110 static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg);
111 static void ParallelErrorContext(void *arg);
112 static void ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc);
113 static void ParallelWorkerMain(Datum main_arg);
114 static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
118 * Establish a new parallel context. This should be done after entering
119 * parallel mode, and (unless there is an error) the context should be
120 * destroyed before exiting the current subtransaction.
123 CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
125 MemoryContext oldcontext;
126 ParallelContext *pcxt;
128 /* It is unsafe to create a parallel context if not in parallel mode. */
129 Assert(IsInParallelMode());
131 /* Number of workers should be non-negative. */
132 Assert(nworkers >= 0);
135 * If dynamic shared memory is not available, we won't be able to use
136 * background workers.
138 if (dynamic_shared_memory_type == DSM_IMPL_NONE)
142 * If we are running under serializable isolation, we can't use parallel
143 * workers, at least not until somebody enhances that mechanism to be
146 if (IsolationIsSerializable())
149 /* We might be running in a short-lived memory context. */
150 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
152 /* Initialize a new ParallelContext. */
153 pcxt = palloc0(sizeof(ParallelContext));
154 pcxt->subid = GetCurrentSubTransactionId();
155 pcxt->nworkers = nworkers;
156 pcxt->entrypoint = entrypoint;
157 pcxt->error_context_stack = error_context_stack;
158 shm_toc_initialize_estimator(&pcxt->estimator);
159 dlist_push_head(&pcxt_list, &pcxt->node);
161 /* Restore previous memory context. */
162 MemoryContextSwitchTo(oldcontext);
168 * Establish a new parallel context that calls a function provided by an
169 * extension. This works around the fact that the library might get mapped
170 * at a different address in each backend.
173 CreateParallelContextForExternalFunction(char *library_name,
177 MemoryContext oldcontext;
178 ParallelContext *pcxt;
180 /* We might be running in a very short-lived memory context. */
181 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
183 /* Create the context. */
184 pcxt = CreateParallelContext(ParallelExtensionTrampoline, nworkers);
185 pcxt->library_name = pstrdup(library_name);
186 pcxt->function_name = pstrdup(function_name);
188 /* Restore previous memory context. */
189 MemoryContextSwitchTo(oldcontext);
195 * Establish the dynamic shared memory segment for a parallel context and
196 * copy state and other bookkeeping information that will be needed by
197 * parallel workers into it.
200 InitializeParallelDSM(ParallelContext *pcxt)
202 MemoryContext oldcontext;
203 Size library_len = 0;
205 Size combocidlen = 0;
211 FixedParallelState *fps;
212 Snapshot transaction_snapshot = GetTransactionSnapshot();
213 Snapshot active_snapshot = GetActiveSnapshot();
215 /* We might be running in a very short-lived memory context. */
216 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
218 /* Allow space to store the fixed-size parallel state. */
219 shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
220 shm_toc_estimate_keys(&pcxt->estimator, 1);
223 * Normally, the user will have requested at least one worker process, but
224 * if by chance they have not, we can skip a bunch of things here.
226 if (pcxt->nworkers > 0)
228 /* Estimate space for various kinds of state sharing. */
229 library_len = EstimateLibraryStateSpace();
230 shm_toc_estimate_chunk(&pcxt->estimator, library_len);
231 guc_len = EstimateGUCStateSpace();
232 shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
233 combocidlen = EstimateComboCIDStateSpace();
234 shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
235 tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
236 shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
237 asnaplen = EstimateSnapshotSpace(active_snapshot);
238 shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
239 tstatelen = EstimateTransactionStateSpace();
240 shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
241 /* If you add more chunks here, you probably need to add keys. */
242 shm_toc_estimate_keys(&pcxt->estimator, 6);
244 /* Estimate space need for error queues. */
245 StaticAssertStmt(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
246 PARALLEL_ERROR_QUEUE_SIZE,
247 "parallel error queue size not buffer-aligned");
248 shm_toc_estimate_chunk(&pcxt->estimator,
249 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
251 shm_toc_estimate_keys(&pcxt->estimator, 1);
253 /* Estimate how much we'll need for extension entrypoint info. */
254 if (pcxt->library_name != NULL)
256 Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
257 Assert(pcxt->function_name != NULL);
258 shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
259 + strlen(pcxt->function_name) + 2);
260 shm_toc_estimate_keys(&pcxt->estimator, 1);
265 * Create DSM and initialize with new table of contents. But if the user
266 * didn't request any workers, then don't bother creating a dynamic shared
267 * memory segment; instead, just use backend-private memory.
269 * Also, if we can't create a dynamic shared memory segment because the
270 * maximum number of segments have already been created, then fall back to
271 * backend-private memory, and plan not to use any workers. We hope this
272 * won't happen very often, but it's better to abandon the use of
273 * parallelism than to fail outright.
275 segsize = shm_toc_estimate(&pcxt->estimator);
276 if (pcxt->nworkers > 0)
277 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
278 if (pcxt->seg != NULL)
279 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
280 dsm_segment_address(pcxt->seg),
285 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
286 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
290 /* Initialize fixed-size state in shared memory. */
291 fps = (FixedParallelState *)
292 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
293 fps->database_id = MyDatabaseId;
294 fps->authenticated_user_id = GetAuthenticatedUserId();
295 GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
296 GetTempNamespaceState(&fps->temp_namespace_id,
297 &fps->temp_toast_namespace_id);
298 fps->parallel_master_pgproc = MyProc;
299 fps->parallel_master_pid = MyProcPid;
300 fps->parallel_master_backend_id = MyBackendId;
301 fps->entrypoint = pcxt->entrypoint;
302 SpinLockInit(&fps->mutex);
303 fps->last_xlog_end = 0;
304 shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
306 /* We can skip the rest of this if we're not budgeting for any workers. */
307 if (pcxt->nworkers > 0)
315 char *error_queue_space;
317 /* Serialize shared libraries we have loaded. */
318 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
319 SerializeLibraryState(library_len, libraryspace);
320 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
322 /* Serialize GUC settings. */
323 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
324 SerializeGUCState(guc_len, gucspace);
325 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
327 /* Serialize combo CID state. */
328 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
329 SerializeComboCIDState(combocidlen, combocidspace);
330 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
332 /* Serialize transaction snapshot and active snapshot. */
333 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
334 SerializeSnapshot(transaction_snapshot, tsnapspace);
335 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
337 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
338 SerializeSnapshot(active_snapshot, asnapspace);
339 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
341 /* Serialize transaction state. */
342 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
343 SerializeTransactionState(tstatelen, tstatespace);
344 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
346 /* Allocate space for worker information. */
347 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
350 * Establish error queues in dynamic shared memory.
352 * These queues should be used only for transmitting ErrorResponse,
353 * NoticeResponse, and NotifyResponse protocol messages. Tuple data
354 * should be transmitted via separate (possibly larger?) queues.
357 shm_toc_allocate(pcxt->toc,
358 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
360 for (i = 0; i < pcxt->nworkers; ++i)
365 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
366 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
367 shm_mq_set_receiver(mq, MyProc);
368 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
370 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
372 /* Serialize extension entrypoint information. */
373 if (pcxt->library_name != NULL)
375 Size lnamelen = strlen(pcxt->library_name);
376 char *extensionstate;
378 extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
379 + strlen(pcxt->function_name) + 2);
380 strcpy(extensionstate, pcxt->library_name);
381 strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
382 shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
387 /* Restore previous memory context. */
388 MemoryContextSwitchTo(oldcontext);
392 * Reinitialize the dynamic shared memory segment for a parallel context such
393 * that we could launch workers for it again.
396 ReinitializeParallelDSM(ParallelContext *pcxt)
398 FixedParallelState *fps;
399 char *error_queue_space;
402 /* Wait for any old workers to exit. */
403 if (pcxt->nworkers_launched > 0)
405 WaitForParallelWorkersToFinish(pcxt);
406 WaitForParallelWorkersToExit(pcxt);
407 pcxt->nworkers_launched = 0;
410 /* Reset a few bits of fixed parallel state to a clean state. */
411 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
412 fps->last_xlog_end = 0;
414 /* Recreate error queues. */
416 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
417 for (i = 0; i < pcxt->nworkers; ++i)
422 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
423 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
424 shm_mq_set_receiver(mq, MyProc);
425 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
430 * Launch parallel workers.
433 LaunchParallelWorkers(ParallelContext *pcxt)
435 MemoryContext oldcontext;
436 BackgroundWorker worker;
438 bool any_registrations_failed = false;
440 /* Skip this if we have no workers. */
441 if (pcxt->nworkers == 0)
444 /* We need to be a lock group leader. */
445 BecomeLockGroupLeader();
447 /* If we do have workers, we'd better have a DSM segment. */
448 Assert(pcxt->seg != NULL);
450 /* We might be running in a short-lived memory context. */
451 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
453 /* Configure a worker. */
454 snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
457 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
458 worker.bgw_start_time = BgWorkerStart_ConsistentState;
459 worker.bgw_restart_time = BGW_NEVER_RESTART;
460 worker.bgw_main = ParallelWorkerMain;
461 worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
462 worker.bgw_notify_pid = MyProcPid;
463 memset(&worker.bgw_extra, 0, BGW_EXTRALEN);
468 * The caller must be able to tolerate ending up with fewer workers than
469 * expected, so there is no need to throw an error here if registration
470 * fails. It wouldn't help much anyway, because registering the worker in
471 * no way guarantees that it will start up and initialize successfully.
473 for (i = 0; i < pcxt->nworkers; ++i)
475 memcpy(worker.bgw_extra, &i, sizeof(int));
476 if (!any_registrations_failed &&
477 RegisterDynamicBackgroundWorker(&worker,
478 &pcxt->worker[i].bgwhandle))
480 shm_mq_set_handle(pcxt->worker[i].error_mqh,
481 pcxt->worker[i].bgwhandle);
482 pcxt->nworkers_launched++;
487 * If we weren't able to register the worker, then we've bumped up
488 * against the max_worker_processes limit, and future
489 * registrations will probably fail too, so arrange to skip them.
490 * But we still have to execute this code for the remaining slots
491 * to make sure that we forget about the error queues we budgeted
492 * for those workers. Otherwise, we'll wait for them to start,
493 * but they never will.
495 any_registrations_failed = true;
496 pcxt->worker[i].bgwhandle = NULL;
497 pfree(pcxt->worker[i].error_mqh);
498 pcxt->worker[i].error_mqh = NULL;
502 /* Restore previous memory context. */
503 MemoryContextSwitchTo(oldcontext);
507 * Wait for all workers to finish computing.
509 * Even if the parallel operation seems to have completed successfully, it's
510 * important to call this function afterwards. We must not miss any errors
511 * the workers may have thrown during the parallel operation, or any that they
512 * may yet throw while shutting down.
514 * Also, we want to update our notion of XactLastRecEnd based on worker
518 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
522 bool anyone_alive = false;
526 * This will process any parallel messages that are pending, which may
527 * change the outcome of the loop that follows. It may also throw an
528 * error propagated from a worker.
530 CHECK_FOR_INTERRUPTS();
532 for (i = 0; i < pcxt->nworkers_launched; ++i)
534 if (pcxt->worker[i].error_mqh != NULL)
544 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1);
545 ResetLatch(&MyProc->procLatch);
548 if (pcxt->toc != NULL)
550 FixedParallelState *fps;
552 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
553 if (fps->last_xlog_end > XactLastRecEnd)
554 XactLastRecEnd = fps->last_xlog_end;
559 * Wait for all workers to exit.
561 * This function ensures that workers have been completely shutdown. The
562 * difference between WaitForParallelWorkersToFinish and this function is
563 * that former just ensures that last message sent by worker backend is
564 * received by master backend whereas this ensures the complete shutdown.
567 WaitForParallelWorkersToExit(ParallelContext *pcxt)
571 /* Wait until the workers actually die. */
572 for (i = 0; i < pcxt->nworkers_launched; ++i)
574 BgwHandleStatus status;
576 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
579 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
582 * If the postmaster kicked the bucket, we have no chance of cleaning
583 * up safely -- we won't be able to tell when our workers are actually
584 * dead. This doesn't necessitate a PANIC since they will all abort
585 * eventually, but we can't safely continue this session.
587 if (status == BGWH_POSTMASTER_DIED)
589 (errcode(ERRCODE_ADMIN_SHUTDOWN),
590 errmsg("postmaster exited during a parallel transaction")));
592 /* Release memory. */
593 pfree(pcxt->worker[i].bgwhandle);
594 pcxt->worker[i].bgwhandle = NULL;
599 * Destroy a parallel context.
601 * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
602 * first, before calling this function. When this function is invoked, any
603 * remaining workers are forcibly killed; the dynamic shared memory segment
604 * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
607 DestroyParallelContext(ParallelContext *pcxt)
612 * Be careful about order of operations here! We remove the parallel
613 * context from the list before we do anything else; otherwise, if an
614 * error occurs during a subsequent step, we might try to nuke it again
615 * from AtEOXact_Parallel or AtEOSubXact_Parallel.
617 dlist_delete(&pcxt->node);
619 /* Kill each worker in turn, and forget their error queues. */
620 if (pcxt->worker != NULL)
622 for (i = 0; i < pcxt->nworkers_launched; ++i)
624 if (pcxt->worker[i].error_mqh != NULL)
626 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
628 pfree(pcxt->worker[i].error_mqh);
629 pcxt->worker[i].error_mqh = NULL;
635 * If we have allocated a shared memory segment, detach it. This will
636 * implicitly detach the error queues, and any other shared memory queues,
639 if (pcxt->seg != NULL)
641 dsm_detach(pcxt->seg);
646 * If this parallel context is actually in backend-private memory rather
647 * than shared memory, free that memory instead.
649 if (pcxt->private_memory != NULL)
651 pfree(pcxt->private_memory);
652 pcxt->private_memory = NULL;
656 * We can't finish transaction commit or abort until all of the workers
657 * have exited. This means, in particular, that we can't respond to
658 * interrupts at this stage.
661 WaitForParallelWorkersToExit(pcxt);
664 /* Free the worker array itself. */
665 if (pcxt->worker != NULL)
676 * Are there any parallel contexts currently active?
679 ParallelContextActive(void)
681 return !dlist_is_empty(&pcxt_list);
685 * Handle receipt of an interrupt indicating a parallel worker message.
687 * Note: this is called within a signal handler! All we can do is set
688 * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
689 * HandleParallelMessages().
692 HandleParallelMessageInterrupt(void)
694 InterruptPending = true;
695 ParallelMessagePending = true;
700 * Handle any queued protocol messages received from parallel workers.
703 HandleParallelMessages(void)
707 ParallelMessagePending = false;
709 dlist_foreach(iter, &pcxt_list)
711 ParallelContext *pcxt;
716 pcxt = dlist_container(ParallelContext, node, iter.cur);
717 if (pcxt->worker == NULL)
720 for (i = 0; i < pcxt->nworkers_launched; ++i)
723 * Read as many messages as we can from each worker, but stop when
724 * either (1) the error queue goes away, which can happen if we
725 * receive a Terminate message from the worker; or (2) no more
726 * messages can be read from the worker without blocking.
728 while (pcxt->worker[i].error_mqh != NULL)
732 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
734 if (res == SHM_MQ_WOULD_BLOCK)
736 else if (res == SHM_MQ_SUCCESS)
740 initStringInfo(&msg);
741 appendBinaryStringInfo(&msg, data, nbytes);
742 HandleParallelMessage(pcxt, i, &msg);
747 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
748 errmsg("lost connection to parallel worker")));
755 * Handle a single protocol message received from a single parallel worker.
758 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
762 msgtype = pq_getmsgbyte(msg);
766 case 'K': /* BackendKeyData */
768 int32 pid = pq_getmsgint(msg, 4);
770 (void) pq_getmsgint(msg, 4); /* discard cancel key */
771 (void) pq_getmsgend(msg);
772 pcxt->worker[i].pid = pid;
776 case 'E': /* ErrorResponse */
777 case 'N': /* NoticeResponse */
780 ErrorContextCallback errctx;
781 ErrorContextCallback *save_error_context_stack;
784 * Rethrow the error using the error context callbacks that
785 * were in effect when the context was created, not the
788 save_error_context_stack = error_context_stack;
789 errctx.callback = ParallelErrorContext;
791 errctx.previous = pcxt->error_context_stack;
792 error_context_stack = &errctx;
794 /* Parse ErrorResponse or NoticeResponse. */
795 pq_parse_errornotice(msg, &edata);
797 /* Death of a worker isn't enough justification for suicide. */
798 edata.elevel = Min(edata.elevel, ERROR);
800 /* Rethrow error or notice. */
801 ThrowErrorData(&edata);
803 /* Restore previous context. */
804 error_context_stack = save_error_context_stack;
809 case 'A': /* NotifyResponse */
811 /* Propagate NotifyResponse. */
816 pid = pq_getmsgint(msg, 4);
817 channel = pq_getmsgrawstring(msg);
818 payload = pq_getmsgrawstring(msg);
821 NotifyMyFrontEnd(channel, payload, pid);
826 case 'X': /* Terminate, indicating clean exit */
828 pfree(pcxt->worker[i].error_mqh);
829 pcxt->worker[i].error_mqh = NULL;
835 elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
842 * End-of-subtransaction cleanup for parallel contexts.
844 * Currently, it's forbidden to enter or leave a subtransaction while
845 * parallel mode is in effect, so we could just blow away everything. But
846 * we may want to relax that restriction in the future, so this code
847 * contemplates that there may be multiple subtransaction IDs in pcxt_list.
850 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
852 while (!dlist_is_empty(&pcxt_list))
854 ParallelContext *pcxt;
856 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
857 if (pcxt->subid != mySubId)
860 elog(WARNING, "leaked parallel context");
861 DestroyParallelContext(pcxt);
866 * End-of-transaction cleanup for parallel contexts.
869 AtEOXact_Parallel(bool isCommit)
871 while (!dlist_is_empty(&pcxt_list))
873 ParallelContext *pcxt;
875 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
877 elog(WARNING, "leaked parallel context");
878 DestroyParallelContext(pcxt);
883 * Main entrypoint for parallel workers.
886 ParallelWorkerMain(Datum main_arg)
890 FixedParallelState *fps;
891 char *error_queue_space;
900 StringInfoData msgbuf;
902 /* Set flag to indicate that we're initializing a parallel worker. */
903 InitializingParallelWorker = true;
905 /* Establish signal handlers. */
906 pqsignal(SIGTERM, die);
907 BackgroundWorkerUnblockSignals();
909 /* Determine and set our parallel worker number. */
910 Assert(ParallelWorkerNumber == -1);
911 memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
913 /* Set up a memory context and resource owner. */
914 Assert(CurrentResourceOwner == NULL);
915 CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
916 CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
918 ALLOCSET_DEFAULT_MINSIZE,
919 ALLOCSET_DEFAULT_INITSIZE,
920 ALLOCSET_DEFAULT_MAXSIZE);
923 * Now that we have a resource owner, we can attach to the dynamic shared
924 * memory segment and read the table of contents.
926 seg = dsm_attach(DatumGetUInt32(main_arg));
929 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
930 errmsg("could not map dynamic shared memory segment")));
931 toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
934 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
935 errmsg("invalid magic number in dynamic shared memory segment")));
937 /* Look up fixed parallel state. */
938 fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
940 MyFixedParallelState = fps;
943 * Now that we have a worker number, we can find and attach to the error
944 * queue provided for us. That's good, because until we do that, any
945 * errors that happen here will not be reported back to the process that
946 * requested that this worker be launched.
948 error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
949 mq = (shm_mq *) (error_queue_space +
950 ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
951 shm_mq_set_sender(mq, MyProc);
952 mqh = shm_mq_attach(mq, seg, NULL);
953 pq_redirect_to_shm_mq(seg, mqh);
954 pq_set_parallel_master(fps->parallel_master_pid,
955 fps->parallel_master_backend_id);
958 * Send a BackendKeyData message to the process that initiated parallelism
959 * so that it has access to our PID before it receives any other messages
960 * from us. Our cancel key is sent, too, since that's the way the
961 * protocol message is defined, but it won't actually be used for anything
964 pq_beginmessage(&msgbuf, 'K');
965 pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
966 pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
967 pq_endmessage(&msgbuf);
970 * Hooray! Primary initialization is complete. Now, we need to set up our
971 * backend-local state to match the original backend.
975 * Join locking group. We must do this before anything that could try to
976 * acquire a heavyweight lock, because any heavyweight locks acquired to
977 * this point could block either directly against the parallel group
978 * leader or against some process which in turn waits for a lock that
979 * conflicts with the parallel group leader, causing an undetected
980 * deadlock. (If we can't join the lock group, the leader has gone away,
981 * so just exit quietly.)
983 if (!BecomeLockGroupMember(fps->parallel_master_pgproc,
984 fps->parallel_master_pid))
988 * Load libraries that were loaded by original backend. We want to do
989 * this before restoring GUCs, because the libraries might define custom
992 libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
993 Assert(libraryspace != NULL);
994 RestoreLibraryState(libraryspace);
996 /* Restore database connection. */
997 BackgroundWorkerInitializeConnectionByOid(fps->database_id,
998 fps->authenticated_user_id);
1001 * Set the client encoding to the database encoding, since that is what
1002 * the leader will expect.
1004 SetClientEncoding(GetDatabaseEncoding());
1006 /* Restore GUC values from launching backend. */
1007 gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
1008 Assert(gucspace != NULL);
1009 StartTransactionCommand();
1010 RestoreGUCState(gucspace);
1011 CommitTransactionCommand();
1013 /* Crank up a transaction state appropriate to a parallel worker. */
1014 tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
1015 StartParallelWorkerTransaction(tstatespace);
1017 /* Restore combo CID state. */
1018 combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
1019 Assert(combocidspace != NULL);
1020 RestoreComboCIDState(combocidspace);
1022 /* Restore transaction snapshot. */
1023 tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
1024 Assert(tsnapspace != NULL);
1025 RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
1026 fps->parallel_master_pgproc);
1028 /* Restore active snapshot. */
1029 asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1030 Assert(asnapspace != NULL);
1031 PushActiveSnapshot(RestoreSnapshot(asnapspace));
1034 * We've changed which tuples we can see, and must therefore invalidate
1037 InvalidateSystemCaches();
1039 /* Restore user ID and security context. */
1040 SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1042 /* Restore temp-namespace state to ensure search path matches leader's. */
1043 SetTempNamespaceState(fps->temp_namespace_id,
1044 fps->temp_toast_namespace_id);
1046 /* Set ParallelMasterBackendId so we know how to address temp relations. */
1047 ParallelMasterBackendId = fps->parallel_master_backend_id;
1050 * We've initialized all of our state now; nothing should change
1053 InitializingParallelWorker = false;
1054 EnterParallelMode();
1057 * Time to do the real work: invoke the caller-supplied code.
1059 * If you get a crash at this line, see the comments for
1060 * ParallelExtensionTrampoline.
1062 fps->entrypoint(seg, toc);
1064 /* Must exit parallel mode to pop active snapshot. */
1067 /* Must pop active snapshot so resowner.c doesn't complain. */
1068 PopActiveSnapshot();
1070 /* Shut down the parallel-worker transaction. */
1071 EndParallelWorkerTransaction();
1073 /* Report success. */
1074 pq_putmessage('X', NULL, 0);
1078 * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1079 * function living in a dynamically loaded module, because the module might
1080 * not be loaded in every process, or might be loaded but not at the same
1081 * address. To work around that problem, CreateParallelContextForExtension()
1082 * arranges to call this function rather than calling the extension-provided
1083 * function directly; and this function then looks up the real entrypoint and
1087 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1089 char *extensionstate;
1091 char *function_name;
1092 parallel_worker_main_type entrypt;
1094 extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1095 Assert(extensionstate != NULL);
1096 library_name = extensionstate;
1097 function_name = extensionstate + strlen(library_name) + 1;
1099 entrypt = (parallel_worker_main_type)
1100 load_external_function(library_name, function_name, true, NULL);
1105 * Give the user a hint that this is a message propagated from a parallel
1106 * worker. Otherwise, it can sometimes be confusing to understand what
1107 * actually happened.
1110 ParallelErrorContext(void *arg)
1112 if (force_parallel_mode != FORCE_PARALLEL_REGRESS)
1113 errcontext("parallel worker");
1117 * Update shared memory with the ending location of the last WAL record we
1118 * wrote, if it's greater than the value already stored there.
1121 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1123 FixedParallelState *fps = MyFixedParallelState;
1125 Assert(fps != NULL);
1126 SpinLockAcquire(&fps->mutex);
1127 if (fps->last_xlog_end < last_xlog_end)
1128 fps->last_xlog_end = last_xlog_end;
1129 SpinLockRelease(&fps->mutex);