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/xact.h"
18 #include "access/xlog.h"
19 #include "access/parallel.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"
39 * We don't want to waste a lot of memory on an error queue which, most of
40 * the time, will process only a handful of small messages. However, it is
41 * desirable to make it large enough that a typical ErrorResponse can be sent
42 * without blocking. That way, a worker that errors out can write the whole
43 * message into the queue and terminate without waiting for the user backend.
45 #define PARALLEL_ERROR_QUEUE_SIZE 16384
47 /* Magic number for parallel context TOC. */
48 #define PARALLEL_MAGIC 0x50477c7c
51 * Magic numbers for parallel state sharing. Higher-level code should use
52 * smaller values, leaving these very large ones for use by this module.
54 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
55 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
56 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
57 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
58 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
59 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
60 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
61 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
62 #define PARALLEL_KEY_EXTENSION_TRAMPOLINE UINT64CONST(0xFFFFFFFFFFFF0009)
64 /* Fixed-size parallel state. */
65 typedef struct FixedParallelState
67 /* Fixed-size state that workers must restore. */
69 Oid authenticated_user_id;
71 Oid temp_namespace_id;
72 Oid temp_toast_namespace_id;
74 PGPROC *parallel_master_pgproc;
75 pid_t parallel_master_pid;
76 BackendId parallel_master_backend_id;
78 /* Entrypoint for parallel workers. */
79 parallel_worker_main_type entrypoint;
81 /* Mutex protects remaining fields. */
84 /* Maximum XactLastRecEnd of any worker. */
85 XLogRecPtr last_xlog_end;
89 * Our parallel worker number. We initialize this to -1, meaning that we are
90 * not a parallel worker. In parallel workers, it will be set to a value >= 0
91 * and < the number of workers before any user code is invoked; each parallel
92 * worker will get a different parallel worker number.
94 int ParallelWorkerNumber = -1;
96 /* Is there a parallel message pending which we need to receive? */
97 bool ParallelMessagePending = false;
99 /* Are we initializing a parallel worker? */
100 bool InitializingParallelWorker = false;
102 /* Pointer to our fixed parallel state. */
103 static FixedParallelState *MyFixedParallelState;
105 /* List of active parallel contexts. */
106 static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list);
108 /* Private functions. */
109 static void HandleParallelMessage(ParallelContext *, int, StringInfo msg);
110 static void ParallelErrorContext(void *arg);
111 static void ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc);
112 static void ParallelWorkerMain(Datum main_arg);
113 static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
116 * Establish a new parallel context. This should be done after entering
117 * parallel mode, and (unless there is an error) the context should be
118 * destroyed before exiting the current subtransaction.
121 CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
123 MemoryContext oldcontext;
124 ParallelContext *pcxt;
126 /* It is unsafe to create a parallel context if not in parallel mode. */
127 Assert(IsInParallelMode());
129 /* Number of workers should be non-negative. */
130 Assert(nworkers >= 0);
133 * If dynamic shared memory is not available, we won't be able to use
134 * background workers.
136 if (dynamic_shared_memory_type == DSM_IMPL_NONE)
140 * If we are running under serializable isolation, we can't use parallel
141 * workers, at least not until somebody enhances that mechanism to be
144 if (IsolationIsSerializable())
147 /* We might be running in a short-lived memory context. */
148 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
150 /* Initialize a new ParallelContext. */
151 pcxt = palloc0(sizeof(ParallelContext));
152 pcxt->subid = GetCurrentSubTransactionId();
153 pcxt->nworkers = nworkers;
154 pcxt->entrypoint = entrypoint;
155 pcxt->error_context_stack = error_context_stack;
156 shm_toc_initialize_estimator(&pcxt->estimator);
157 dlist_push_head(&pcxt_list, &pcxt->node);
159 /* Restore previous memory context. */
160 MemoryContextSwitchTo(oldcontext);
166 * Establish a new parallel context that calls a function provided by an
167 * extension. This works around the fact that the library might get mapped
168 * at a different address in each backend.
171 CreateParallelContextForExternalFunction(char *library_name,
175 MemoryContext oldcontext;
176 ParallelContext *pcxt;
178 /* We might be running in a very short-lived memory context. */
179 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
181 /* Create the context. */
182 pcxt = CreateParallelContext(ParallelExtensionTrampoline, nworkers);
183 pcxt->library_name = pstrdup(library_name);
184 pcxt->function_name = pstrdup(function_name);
186 /* Restore previous memory context. */
187 MemoryContextSwitchTo(oldcontext);
193 * Establish the dynamic shared memory segment for a parallel context and
194 * copy state and other bookkeeping information that will be needed by
195 * parallel workers into it.
198 InitializeParallelDSM(ParallelContext *pcxt)
200 MemoryContext oldcontext;
201 Size library_len = 0;
203 Size combocidlen = 0;
209 FixedParallelState *fps;
210 Snapshot transaction_snapshot = GetTransactionSnapshot();
211 Snapshot active_snapshot = GetActiveSnapshot();
213 /* We might be running in a very short-lived memory context. */
214 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
216 /* Allow space to store the fixed-size parallel state. */
217 shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
218 shm_toc_estimate_keys(&pcxt->estimator, 1);
221 * Normally, the user will have requested at least one worker process, but
222 * if by chance they have not, we can skip a bunch of things here.
224 if (pcxt->nworkers > 0)
226 /* Estimate space for various kinds of state sharing. */
227 library_len = EstimateLibraryStateSpace();
228 shm_toc_estimate_chunk(&pcxt->estimator, library_len);
229 guc_len = EstimateGUCStateSpace();
230 shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
231 combocidlen = EstimateComboCIDStateSpace();
232 shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
233 tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
234 shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
235 asnaplen = EstimateSnapshotSpace(active_snapshot);
236 shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
237 tstatelen = EstimateTransactionStateSpace();
238 shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
239 /* If you add more chunks here, you probably need to add keys. */
240 shm_toc_estimate_keys(&pcxt->estimator, 6);
242 /* Estimate space need for error queues. */
243 StaticAssertStmt(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
244 PARALLEL_ERROR_QUEUE_SIZE,
245 "parallel error queue size not buffer-aligned");
246 shm_toc_estimate_chunk(&pcxt->estimator,
247 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
249 shm_toc_estimate_keys(&pcxt->estimator, 1);
251 /* Estimate how much we'll need for extension entrypoint info. */
252 if (pcxt->library_name != NULL)
254 Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
255 Assert(pcxt->function_name != NULL);
256 shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
257 + strlen(pcxt->function_name) + 2);
258 shm_toc_estimate_keys(&pcxt->estimator, 1);
263 * Create DSM and initialize with new table of contents. But if the user
264 * didn't request any workers, then don't bother creating a dynamic shared
265 * memory segment; instead, just use backend-private memory.
267 * Also, if we can't create a dynamic shared memory segment because the
268 * maximum number of segments have already been created, then fall back to
269 * backend-private memory, and plan not to use any workers. We hope this
270 * won't happen very often, but it's better to abandon the use of
271 * parallelism than to fail outright.
273 segsize = shm_toc_estimate(&pcxt->estimator);
274 if (pcxt->nworkers > 0)
275 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
276 if (pcxt->seg != NULL)
277 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
278 dsm_segment_address(pcxt->seg),
283 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
284 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
288 /* Initialize fixed-size state in shared memory. */
289 fps = (FixedParallelState *)
290 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
291 fps->database_id = MyDatabaseId;
292 fps->authenticated_user_id = GetAuthenticatedUserId();
293 GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
294 GetTempNamespaceState(&fps->temp_namespace_id,
295 &fps->temp_toast_namespace_id);
296 fps->parallel_master_pgproc = MyProc;
297 fps->parallel_master_pid = MyProcPid;
298 fps->parallel_master_backend_id = MyBackendId;
299 fps->entrypoint = pcxt->entrypoint;
300 SpinLockInit(&fps->mutex);
301 fps->last_xlog_end = 0;
302 shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
304 /* We can skip the rest of this if we're not budgeting for any workers. */
305 if (pcxt->nworkers > 0)
313 char *error_queue_space;
315 /* Serialize shared libraries we have loaded. */
316 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
317 SerializeLibraryState(library_len, libraryspace);
318 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
320 /* Serialize GUC settings. */
321 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
322 SerializeGUCState(guc_len, gucspace);
323 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
325 /* Serialize combo CID state. */
326 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
327 SerializeComboCIDState(combocidlen, combocidspace);
328 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
330 /* Serialize transaction snapshot and active snapshot. */
331 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
332 SerializeSnapshot(transaction_snapshot, tsnapspace);
333 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
335 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
336 SerializeSnapshot(active_snapshot, asnapspace);
337 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
339 /* Serialize transaction state. */
340 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
341 SerializeTransactionState(tstatelen, tstatespace);
342 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
344 /* Allocate space for worker information. */
345 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
348 * Establish error queues in dynamic shared memory.
350 * These queues should be used only for transmitting ErrorResponse,
351 * NoticeResponse, and NotifyResponse protocol messages. Tuple data
352 * should be transmitted via separate (possibly larger?) queues.
355 shm_toc_allocate(pcxt->toc,
356 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
358 for (i = 0; i < pcxt->nworkers; ++i)
363 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
364 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
365 shm_mq_set_receiver(mq, MyProc);
366 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
368 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
370 /* Serialize extension entrypoint information. */
371 if (pcxt->library_name != NULL)
373 Size lnamelen = strlen(pcxt->library_name);
374 char *extensionstate;
376 extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
377 + strlen(pcxt->function_name) + 2);
378 strcpy(extensionstate, pcxt->library_name);
379 strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
380 shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
385 /* Restore previous memory context. */
386 MemoryContextSwitchTo(oldcontext);
390 * Reinitialize the dynamic shared memory segment for a parallel context such
391 * that we could launch workers for it again.
394 ReinitializeParallelDSM(ParallelContext *pcxt)
396 FixedParallelState *fps;
397 char *error_queue_space;
400 /* Wait for any old workers to exit. */
401 if (pcxt->nworkers_launched > 0)
403 WaitForParallelWorkersToFinish(pcxt);
404 WaitForParallelWorkersToExit(pcxt);
405 pcxt->nworkers_launched = 0;
408 /* Reset a few bits of fixed parallel state to a clean state. */
409 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
410 fps->last_xlog_end = 0;
412 /* Recreate error queues. */
414 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
415 for (i = 0; i < pcxt->nworkers; ++i)
420 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
421 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
422 shm_mq_set_receiver(mq, MyProc);
423 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
428 * Launch parallel workers.
431 LaunchParallelWorkers(ParallelContext *pcxt)
433 MemoryContext oldcontext;
434 BackgroundWorker worker;
436 bool any_registrations_failed = false;
438 /* Skip this if we have no workers. */
439 if (pcxt->nworkers == 0)
442 /* We need to be a lock group leader. */
443 BecomeLockGroupLeader();
445 /* If we do have workers, we'd better have a DSM segment. */
446 Assert(pcxt->seg != NULL);
448 /* We might be running in a short-lived memory context. */
449 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
451 /* Configure a worker. */
452 snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
455 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
456 worker.bgw_start_time = BgWorkerStart_ConsistentState;
457 worker.bgw_restart_time = BGW_NEVER_RESTART;
458 worker.bgw_main = ParallelWorkerMain;
459 worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
460 worker.bgw_notify_pid = MyProcPid;
461 memset(&worker.bgw_extra, 0, BGW_EXTRALEN);
466 * The caller must be able to tolerate ending up with fewer workers than
467 * expected, so there is no need to throw an error here if registration
468 * fails. It wouldn't help much anyway, because registering the worker in
469 * no way guarantees that it will start up and initialize successfully.
471 for (i = 0; i < pcxt->nworkers; ++i)
473 memcpy(worker.bgw_extra, &i, sizeof(int));
474 if (!any_registrations_failed &&
475 RegisterDynamicBackgroundWorker(&worker,
476 &pcxt->worker[i].bgwhandle))
478 shm_mq_set_handle(pcxt->worker[i].error_mqh,
479 pcxt->worker[i].bgwhandle);
480 pcxt->nworkers_launched++;
485 * If we weren't able to register the worker, then we've bumped up
486 * against the max_worker_processes limit, and future
487 * registrations will probably fail too, so arrange to skip them.
488 * But we still have to execute this code for the remaining slots
489 * to make sure that we forget about the error queues we budgeted
490 * for those workers. Otherwise, we'll wait for them to start,
491 * but they never will.
493 any_registrations_failed = true;
494 pcxt->worker[i].bgwhandle = NULL;
495 pfree(pcxt->worker[i].error_mqh);
496 pcxt->worker[i].error_mqh = NULL;
500 /* Restore previous memory context. */
501 MemoryContextSwitchTo(oldcontext);
505 * Wait for all workers to finish computing.
507 * Even if the parallel operation seems to have completed successfully, it's
508 * important to call this function afterwards. We must not miss any errors
509 * the workers may have thrown during the parallel operation, or any that they
510 * may yet throw while shutting down.
512 * Also, we want to update our notion of XactLastRecEnd based on worker
516 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
520 bool anyone_alive = false;
524 * This will process any parallel messages that are pending, which may
525 * change the outcome of the loop that follows. It may also throw an
526 * error propagated from a worker.
528 CHECK_FOR_INTERRUPTS();
530 for (i = 0; i < pcxt->nworkers_launched; ++i)
532 if (pcxt->worker[i].error_mqh != NULL)
542 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1);
543 ResetLatch(&MyProc->procLatch);
546 if (pcxt->toc != NULL)
548 FixedParallelState *fps;
550 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
551 if (fps->last_xlog_end > XactLastRecEnd)
552 XactLastRecEnd = fps->last_xlog_end;
557 * Wait for all workers to exit.
559 * This function ensures that workers have been completely shutdown. The
560 * difference between WaitForParallelWorkersToFinish and this function is
561 * that former just ensures that last message sent by worker backend is
562 * received by master backend whereas this ensures the complete shutdown.
565 WaitForParallelWorkersToExit(ParallelContext *pcxt)
569 /* Wait until the workers actually die. */
570 for (i = 0; i < pcxt->nworkers_launched; ++i)
572 BgwHandleStatus status;
574 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
577 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
580 * If the postmaster kicked the bucket, we have no chance of cleaning
581 * up safely -- we won't be able to tell when our workers are actually
582 * dead. This doesn't necessitate a PANIC since they will all abort
583 * eventually, but we can't safely continue this session.
585 if (status == BGWH_POSTMASTER_DIED)
587 (errcode(ERRCODE_ADMIN_SHUTDOWN),
588 errmsg("postmaster exited during a parallel transaction")));
590 /* Release memory. */
591 pfree(pcxt->worker[i].bgwhandle);
592 pcxt->worker[i].bgwhandle = NULL;
597 * Destroy a parallel context.
599 * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
600 * first, before calling this function. When this function is invoked, any
601 * remaining workers are forcibly killed; the dynamic shared memory segment
602 * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
605 DestroyParallelContext(ParallelContext *pcxt)
610 * Be careful about order of operations here! We remove the parallel
611 * context from the list before we do anything else; otherwise, if an
612 * error occurs during a subsequent step, we might try to nuke it again
613 * from AtEOXact_Parallel or AtEOSubXact_Parallel.
615 dlist_delete(&pcxt->node);
617 /* Kill each worker in turn, and forget their error queues. */
618 if (pcxt->worker != NULL)
620 for (i = 0; i < pcxt->nworkers_launched; ++i)
622 if (pcxt->worker[i].error_mqh != NULL)
624 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
626 pfree(pcxt->worker[i].error_mqh);
627 pcxt->worker[i].error_mqh = NULL;
633 * If we have allocated a shared memory segment, detach it. This will
634 * implicitly detach the error queues, and any other shared memory queues,
637 if (pcxt->seg != NULL)
639 dsm_detach(pcxt->seg);
644 * If this parallel context is actually in backend-private memory rather
645 * than shared memory, free that memory instead.
647 if (pcxt->private_memory != NULL)
649 pfree(pcxt->private_memory);
650 pcxt->private_memory = NULL;
654 * We can't finish transaction commit or abort until all of the workers
655 * have exited. This means, in particular, that we can't respond to
656 * interrupts at this stage.
659 WaitForParallelWorkersToExit(pcxt);
662 /* Free the worker array itself. */
663 if (pcxt->worker != NULL)
674 * Are there any parallel contexts currently active?
677 ParallelContextActive(void)
679 return !dlist_is_empty(&pcxt_list);
683 * Handle receipt of an interrupt indicating a parallel worker message.
686 HandleParallelMessageInterrupt(void)
688 int save_errno = errno;
690 InterruptPending = true;
691 ParallelMessagePending = true;
698 * Handle any queued protocol messages received from parallel workers.
701 HandleParallelMessages(void)
705 ParallelMessagePending = false;
707 dlist_foreach(iter, &pcxt_list)
709 ParallelContext *pcxt;
714 pcxt = dlist_container(ParallelContext, node, iter.cur);
715 if (pcxt->worker == NULL)
718 for (i = 0; i < pcxt->nworkers_launched; ++i)
721 * Read as many messages as we can from each worker, but stop when
722 * either (1) the error queue goes away, which can happen if we
723 * receive a Terminate message from the worker; or (2) no more
724 * messages can be read from the worker without blocking.
726 while (pcxt->worker[i].error_mqh != NULL)
730 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
732 if (res == SHM_MQ_WOULD_BLOCK)
734 else if (res == SHM_MQ_SUCCESS)
738 initStringInfo(&msg);
739 appendBinaryStringInfo(&msg, data, nbytes);
740 HandleParallelMessage(pcxt, i, &msg);
745 (errcode(ERRCODE_INTERNAL_ERROR), /* XXX: wrong errcode? */
746 errmsg("lost connection to parallel worker")));
748 /* This might make the error queue go away. */
749 CHECK_FOR_INTERRUPTS();
756 * Handle a single protocol message received from a single parallel worker.
759 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
763 msgtype = pq_getmsgbyte(msg);
767 case 'K': /* BackendKeyData */
769 int32 pid = pq_getmsgint(msg, 4);
771 (void) pq_getmsgint(msg, 4); /* discard cancel key */
772 (void) pq_getmsgend(msg);
773 pcxt->worker[i].pid = pid;
777 case 'E': /* ErrorResponse */
778 case 'N': /* NoticeResponse */
781 ErrorContextCallback errctx;
782 ErrorContextCallback *save_error_context_stack;
785 * Rethrow the error using the error context callbacks that
786 * were in effect when the context was created, not the
789 save_error_context_stack = error_context_stack;
790 errctx.callback = ParallelErrorContext;
792 errctx.previous = pcxt->error_context_stack;
793 error_context_stack = &errctx;
795 /* Parse ErrorResponse or NoticeResponse. */
796 pq_parse_errornotice(msg, &edata);
798 /* Death of a worker isn't enough justification for suicide. */
799 edata.elevel = Min(edata.elevel, ERROR);
801 /* Rethrow error or notice. */
802 ThrowErrorData(&edata);
804 /* Restore previous context. */
805 error_context_stack = save_error_context_stack;
810 case 'A': /* NotifyResponse */
812 /* Propagate NotifyResponse. */
817 pid = pq_getmsgint(msg, 4);
818 channel = pq_getmsgrawstring(msg);
819 payload = pq_getmsgrawstring(msg);
822 NotifyMyFrontEnd(channel, payload, pid);
827 case 'X': /* Terminate, indicating clean exit */
829 pfree(pcxt->worker[i].error_mqh);
830 pcxt->worker[i].error_mqh = NULL;
836 elog(ERROR, "unknown message type: %c (%d bytes)",
843 * End-of-subtransaction cleanup for parallel contexts.
845 * Currently, it's forbidden to enter or leave a subtransaction while
846 * parallel mode is in effect, so we could just blow away everything. But
847 * we may want to relax that restriction in the future, so this code
848 * contemplates that there may be multiple subtransaction IDs in pcxt_list.
851 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
853 while (!dlist_is_empty(&pcxt_list))
855 ParallelContext *pcxt;
857 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
858 if (pcxt->subid != mySubId)
861 elog(WARNING, "leaked parallel context");
862 DestroyParallelContext(pcxt);
867 * End-of-transaction cleanup for parallel contexts.
870 AtEOXact_Parallel(bool isCommit)
872 while (!dlist_is_empty(&pcxt_list))
874 ParallelContext *pcxt;
876 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
878 elog(WARNING, "leaked parallel context");
879 DestroyParallelContext(pcxt);
884 * Main entrypoint for parallel workers.
887 ParallelWorkerMain(Datum main_arg)
891 FixedParallelState *fps;
892 char *error_queue_space;
901 StringInfoData msgbuf;
903 /* Set flag to indicate that we're initializing a parallel worker. */
904 InitializingParallelWorker = true;
906 /* Establish signal handlers. */
907 pqsignal(SIGTERM, die);
908 BackgroundWorkerUnblockSignals();
910 /* Determine and set our parallel worker number. */
911 Assert(ParallelWorkerNumber == -1);
912 memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
914 /* Set up a memory context and resource owner. */
915 Assert(CurrentResourceOwner == NULL);
916 CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
917 CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
919 ALLOCSET_DEFAULT_MINSIZE,
920 ALLOCSET_DEFAULT_INITSIZE,
921 ALLOCSET_DEFAULT_MAXSIZE);
924 * Now that we have a resource owner, we can attach to the dynamic shared
925 * memory segment and read the table of contents.
927 seg = dsm_attach(DatumGetUInt32(main_arg));
930 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
931 errmsg("could not map dynamic shared memory segment")));
932 toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
935 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
936 errmsg("invalid magic number in dynamic shared memory segment")));
938 /* Look up fixed parallel state. */
939 fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
941 MyFixedParallelState = fps;
944 * Now that we have a worker number, we can find and attach to the error
945 * queue provided for us. That's good, because until we do that, any
946 * errors that happen here will not be reported back to the process that
947 * requested that this worker be launched.
949 error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
950 mq = (shm_mq *) (error_queue_space +
951 ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
952 shm_mq_set_sender(mq, MyProc);
953 mqh = shm_mq_attach(mq, seg, NULL);
954 pq_redirect_to_shm_mq(seg, mqh);
955 pq_set_parallel_master(fps->parallel_master_pid,
956 fps->parallel_master_backend_id);
959 * Send a BackendKeyData message to the process that initiated parallelism
960 * so that it has access to our PID before it receives any other messages
961 * from us. Our cancel key is sent, too, since that's the way the
962 * protocol message is defined, but it won't actually be used for anything
965 pq_beginmessage(&msgbuf, 'K');
966 pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
967 pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
968 pq_endmessage(&msgbuf);
971 * Hooray! Primary initialization is complete. Now, we need to set up our
972 * backend-local state to match the original backend.
976 * Join locking group. We must do this before anything that could try to
977 * acquire a heavyweight lock, because any heavyweight locks acquired to
978 * this point could block either directly against the parallel group
979 * leader or against some process which in turn waits for a lock that
980 * conflicts with the parallel group leader, causing an undetected
981 * deadlock. (If we can't join the lock group, the leader has gone away,
982 * so just exit quietly.)
984 if (!BecomeLockGroupMember(fps->parallel_master_pgproc,
985 fps->parallel_master_pid))
989 * Load libraries that were loaded by original backend. We want to do
990 * this before restoring GUCs, because the libraries might define custom
993 libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
994 Assert(libraryspace != NULL);
995 RestoreLibraryState(libraryspace);
997 /* Restore database connection. */
998 BackgroundWorkerInitializeConnectionByOid(fps->database_id,
999 fps->authenticated_user_id);
1002 * Set the client encoding to the database encoding, since that is what
1003 * the leader will expect.
1005 SetClientEncoding(GetDatabaseEncoding());
1007 /* Restore GUC values from launching backend. */
1008 gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
1009 Assert(gucspace != NULL);
1010 StartTransactionCommand();
1011 RestoreGUCState(gucspace);
1012 CommitTransactionCommand();
1014 /* Crank up a transaction state appropriate to a parallel worker. */
1015 tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
1016 StartParallelWorkerTransaction(tstatespace);
1018 /* Restore combo CID state. */
1019 combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
1020 Assert(combocidspace != NULL);
1021 RestoreComboCIDState(combocidspace);
1023 /* Restore transaction snapshot. */
1024 tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
1025 Assert(tsnapspace != NULL);
1026 RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
1027 fps->parallel_master_pgproc);
1029 /* Restore active snapshot. */
1030 asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1031 Assert(asnapspace != NULL);
1032 PushActiveSnapshot(RestoreSnapshot(asnapspace));
1035 * We've changed which tuples we can see, and must therefore invalidate
1038 InvalidateSystemCaches();
1040 /* Restore user ID and security context. */
1041 SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1043 /* Restore temp-namespace state to ensure search path matches leader's. */
1044 SetTempNamespaceState(fps->temp_namespace_id,
1045 fps->temp_toast_namespace_id);
1047 /* Set ParallelMasterBackendId so we know how to address temp relations. */
1048 ParallelMasterBackendId = fps->parallel_master_backend_id;
1051 * We've initialized all of our state now; nothing should change
1054 InitializingParallelWorker = false;
1055 EnterParallelMode();
1058 * Time to do the real work: invoke the caller-supplied code.
1060 * If you get a crash at this line, see the comments for
1061 * ParallelExtensionTrampoline.
1063 fps->entrypoint(seg, toc);
1065 /* Must exit parallel mode to pop active snapshot. */
1068 /* Must pop active snapshot so resowner.c doesn't complain. */
1069 PopActiveSnapshot();
1071 /* Shut down the parallel-worker transaction. */
1072 EndParallelWorkerTransaction();
1074 /* Report success. */
1075 pq_putmessage('X', NULL, 0);
1079 * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1080 * function living in a dynamically loaded module, because the module might
1081 * not be loaded in every process, or might be loaded but not at the same
1082 * address. To work around that problem, CreateParallelContextForExtension()
1083 * arranges to call this function rather than calling the extension-provided
1084 * function directly; and this function then looks up the real entrypoint and
1088 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1090 char *extensionstate;
1092 char *function_name;
1093 parallel_worker_main_type entrypt;
1095 extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1096 Assert(extensionstate != NULL);
1097 library_name = extensionstate;
1098 function_name = extensionstate + strlen(library_name) + 1;
1100 entrypt = (parallel_worker_main_type)
1101 load_external_function(library_name, function_name, true, NULL);
1106 * Give the user a hint that this is a message propagated from a parallel
1107 * worker. Otherwise, it can sometimes be confusing to understand what
1108 * actually happened.
1111 ParallelErrorContext(void *arg)
1113 if (force_parallel_mode != FORCE_PARALLEL_REGRESS)
1114 errcontext("parallel worker");
1118 * Update shared memory with the ending location of the last WAL record we
1119 * wrote, if it's greater than the value already stored there.
1122 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1124 FixedParallelState *fps = MyFixedParallelState;
1126 Assert(fps != NULL);
1127 SpinLockAcquire(&fps->mutex);
1128 if (fps->last_xlog_end < last_xlog_end)
1129 fps->last_xlog_end = last_xlog_end;
1130 SpinLockRelease(&fps->mutex);