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 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc);
112 static void ParallelWorkerMain(Datum main_arg);
113 static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
117 * Establish a new parallel context. This should be done after entering
118 * parallel mode, and (unless there is an error) the context should be
119 * destroyed before exiting the current subtransaction.
122 CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
124 MemoryContext oldcontext;
125 ParallelContext *pcxt;
127 /* It is unsafe to create a parallel context if not in parallel mode. */
128 Assert(IsInParallelMode());
130 /* Number of workers should be non-negative. */
131 Assert(nworkers >= 0);
134 * If dynamic shared memory is not available, we won't be able to use
135 * background workers.
137 if (dynamic_shared_memory_type == DSM_IMPL_NONE)
141 * If we are running under serializable isolation, we can't use parallel
142 * workers, at least not until somebody enhances that mechanism to be
145 if (IsolationIsSerializable())
148 /* We might be running in a short-lived memory context. */
149 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
151 /* Initialize a new ParallelContext. */
152 pcxt = palloc0(sizeof(ParallelContext));
153 pcxt->subid = GetCurrentSubTransactionId();
154 pcxt->nworkers = nworkers;
155 pcxt->entrypoint = entrypoint;
156 pcxt->error_context_stack = error_context_stack;
157 shm_toc_initialize_estimator(&pcxt->estimator);
158 dlist_push_head(&pcxt_list, &pcxt->node);
160 /* Restore previous memory context. */
161 MemoryContextSwitchTo(oldcontext);
167 * Establish a new parallel context that calls a function provided by an
168 * extension. This works around the fact that the library might get mapped
169 * at a different address in each backend.
172 CreateParallelContextForExternalFunction(char *library_name,
176 MemoryContext oldcontext;
177 ParallelContext *pcxt;
179 /* We might be running in a very short-lived memory context. */
180 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
182 /* Create the context. */
183 pcxt = CreateParallelContext(ParallelExtensionTrampoline, nworkers);
184 pcxt->library_name = pstrdup(library_name);
185 pcxt->function_name = pstrdup(function_name);
187 /* Restore previous memory context. */
188 MemoryContextSwitchTo(oldcontext);
194 * Establish the dynamic shared memory segment for a parallel context and
195 * copy state and other bookkeeping information that will be needed by
196 * parallel workers into it.
199 InitializeParallelDSM(ParallelContext *pcxt)
201 MemoryContext oldcontext;
202 Size library_len = 0;
204 Size combocidlen = 0;
210 FixedParallelState *fps;
211 Snapshot transaction_snapshot = GetTransactionSnapshot();
212 Snapshot active_snapshot = GetActiveSnapshot();
214 /* We might be running in a very short-lived memory context. */
215 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
217 /* Allow space to store the fixed-size parallel state. */
218 shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
219 shm_toc_estimate_keys(&pcxt->estimator, 1);
222 * Normally, the user will have requested at least one worker process, but
223 * if by chance they have not, we can skip a bunch of things here.
225 if (pcxt->nworkers > 0)
227 /* Estimate space for various kinds of state sharing. */
228 library_len = EstimateLibraryStateSpace();
229 shm_toc_estimate_chunk(&pcxt->estimator, library_len);
230 guc_len = EstimateGUCStateSpace();
231 shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
232 combocidlen = EstimateComboCIDStateSpace();
233 shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
234 tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
235 shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
236 asnaplen = EstimateSnapshotSpace(active_snapshot);
237 shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
238 tstatelen = EstimateTransactionStateSpace();
239 shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
240 /* If you add more chunks here, you probably need to add keys. */
241 shm_toc_estimate_keys(&pcxt->estimator, 6);
243 /* Estimate space need for error queues. */
244 StaticAssertStmt(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
245 PARALLEL_ERROR_QUEUE_SIZE,
246 "parallel error queue size not buffer-aligned");
247 shm_toc_estimate_chunk(&pcxt->estimator,
248 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
250 shm_toc_estimate_keys(&pcxt->estimator, 1);
252 /* Estimate how much we'll need for extension entrypoint info. */
253 if (pcxt->library_name != NULL)
255 Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
256 Assert(pcxt->function_name != NULL);
257 shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
258 + strlen(pcxt->function_name) + 2);
259 shm_toc_estimate_keys(&pcxt->estimator, 1);
264 * Create DSM and initialize with new table of contents. But if the user
265 * didn't request any workers, then don't bother creating a dynamic shared
266 * memory segment; instead, just use backend-private memory.
268 * Also, if we can't create a dynamic shared memory segment because the
269 * maximum number of segments have already been created, then fall back to
270 * backend-private memory, and plan not to use any workers. We hope this
271 * won't happen very often, but it's better to abandon the use of
272 * parallelism than to fail outright.
274 segsize = shm_toc_estimate(&pcxt->estimator);
275 if (pcxt->nworkers > 0)
276 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
277 if (pcxt->seg != NULL)
278 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
279 dsm_segment_address(pcxt->seg),
284 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
285 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
289 /* Initialize fixed-size state in shared memory. */
290 fps = (FixedParallelState *)
291 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
292 fps->database_id = MyDatabaseId;
293 fps->authenticated_user_id = GetAuthenticatedUserId();
294 GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
295 GetTempNamespaceState(&fps->temp_namespace_id,
296 &fps->temp_toast_namespace_id);
297 fps->parallel_master_pgproc = MyProc;
298 fps->parallel_master_pid = MyProcPid;
299 fps->parallel_master_backend_id = MyBackendId;
300 fps->entrypoint = pcxt->entrypoint;
301 SpinLockInit(&fps->mutex);
302 fps->last_xlog_end = 0;
303 shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
305 /* We can skip the rest of this if we're not budgeting for any workers. */
306 if (pcxt->nworkers > 0)
314 char *error_queue_space;
316 /* Serialize shared libraries we have loaded. */
317 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
318 SerializeLibraryState(library_len, libraryspace);
319 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
321 /* Serialize GUC settings. */
322 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
323 SerializeGUCState(guc_len, gucspace);
324 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
326 /* Serialize combo CID state. */
327 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
328 SerializeComboCIDState(combocidlen, combocidspace);
329 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
331 /* Serialize transaction snapshot and active snapshot. */
332 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
333 SerializeSnapshot(transaction_snapshot, tsnapspace);
334 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
336 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
337 SerializeSnapshot(active_snapshot, asnapspace);
338 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
340 /* Serialize transaction state. */
341 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
342 SerializeTransactionState(tstatelen, tstatespace);
343 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
345 /* Allocate space for worker information. */
346 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
349 * Establish error queues in dynamic shared memory.
351 * These queues should be used only for transmitting ErrorResponse,
352 * NoticeResponse, and NotifyResponse protocol messages. Tuple data
353 * should be transmitted via separate (possibly larger?) queues.
356 shm_toc_allocate(pcxt->toc,
357 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
359 for (i = 0; i < pcxt->nworkers; ++i)
364 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
365 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
366 shm_mq_set_receiver(mq, MyProc);
367 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
369 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
371 /* Serialize extension entrypoint information. */
372 if (pcxt->library_name != NULL)
374 Size lnamelen = strlen(pcxt->library_name);
375 char *extensionstate;
377 extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
378 + strlen(pcxt->function_name) + 2);
379 strcpy(extensionstate, pcxt->library_name);
380 strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
381 shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
386 /* Restore previous memory context. */
387 MemoryContextSwitchTo(oldcontext);
391 * Reinitialize the dynamic shared memory segment for a parallel context such
392 * that we could launch workers for it again.
395 ReinitializeParallelDSM(ParallelContext *pcxt)
397 FixedParallelState *fps;
398 char *error_queue_space;
401 /* Wait for any old workers to exit. */
402 if (pcxt->nworkers_launched > 0)
404 WaitForParallelWorkersToFinish(pcxt);
405 WaitForParallelWorkersToExit(pcxt);
406 pcxt->nworkers_launched = 0;
409 /* Reset a few bits of fixed parallel state to a clean state. */
410 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
411 fps->last_xlog_end = 0;
413 /* Recreate error queues. */
415 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
416 for (i = 0; i < pcxt->nworkers; ++i)
421 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
422 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
423 shm_mq_set_receiver(mq, MyProc);
424 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
429 * Launch parallel workers.
432 LaunchParallelWorkers(ParallelContext *pcxt)
434 MemoryContext oldcontext;
435 BackgroundWorker worker;
437 bool any_registrations_failed = false;
439 /* Skip this if we have no workers. */
440 if (pcxt->nworkers == 0)
443 /* We need to be a lock group leader. */
444 BecomeLockGroupLeader();
446 /* If we do have workers, we'd better have a DSM segment. */
447 Assert(pcxt->seg != NULL);
449 /* We might be running in a short-lived memory context. */
450 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
452 /* Configure a worker. */
453 snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
456 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
457 worker.bgw_start_time = BgWorkerStart_ConsistentState;
458 worker.bgw_restart_time = BGW_NEVER_RESTART;
459 worker.bgw_main = ParallelWorkerMain;
460 worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
461 worker.bgw_notify_pid = MyProcPid;
462 memset(&worker.bgw_extra, 0, BGW_EXTRALEN);
467 * The caller must be able to tolerate ending up with fewer workers than
468 * expected, so there is no need to throw an error here if registration
469 * fails. It wouldn't help much anyway, because registering the worker in
470 * no way guarantees that it will start up and initialize successfully.
472 for (i = 0; i < pcxt->nworkers; ++i)
474 memcpy(worker.bgw_extra, &i, sizeof(int));
475 if (!any_registrations_failed &&
476 RegisterDynamicBackgroundWorker(&worker,
477 &pcxt->worker[i].bgwhandle))
479 shm_mq_set_handle(pcxt->worker[i].error_mqh,
480 pcxt->worker[i].bgwhandle);
481 pcxt->nworkers_launched++;
486 * If we weren't able to register the worker, then we've bumped up
487 * against the max_worker_processes limit, and future
488 * registrations will probably fail too, so arrange to skip them.
489 * But we still have to execute this code for the remaining slots
490 * to make sure that we forget about the error queues we budgeted
491 * for those workers. Otherwise, we'll wait for them to start,
492 * but they never will.
494 any_registrations_failed = true;
495 pcxt->worker[i].bgwhandle = NULL;
496 pfree(pcxt->worker[i].error_mqh);
497 pcxt->worker[i].error_mqh = NULL;
501 /* Restore previous memory context. */
502 MemoryContextSwitchTo(oldcontext);
506 * Wait for all workers to finish computing.
508 * Even if the parallel operation seems to have completed successfully, it's
509 * important to call this function afterwards. We must not miss any errors
510 * the workers may have thrown during the parallel operation, or any that they
511 * may yet throw while shutting down.
513 * Also, we want to update our notion of XactLastRecEnd based on worker
517 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
521 bool anyone_alive = false;
525 * This will process any parallel messages that are pending, which may
526 * change the outcome of the loop that follows. It may also throw an
527 * error propagated from a worker.
529 CHECK_FOR_INTERRUPTS();
531 for (i = 0; i < pcxt->nworkers_launched; ++i)
533 if (pcxt->worker[i].error_mqh != NULL)
543 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1);
544 ResetLatch(&MyProc->procLatch);
547 if (pcxt->toc != NULL)
549 FixedParallelState *fps;
551 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
552 if (fps->last_xlog_end > XactLastRecEnd)
553 XactLastRecEnd = fps->last_xlog_end;
558 * Wait for all workers to exit.
560 * This function ensures that workers have been completely shutdown. The
561 * difference between WaitForParallelWorkersToFinish and this function is
562 * that former just ensures that last message sent by worker backend is
563 * received by master backend whereas this ensures the complete shutdown.
566 WaitForParallelWorkersToExit(ParallelContext *pcxt)
570 /* Wait until the workers actually die. */
571 for (i = 0; i < pcxt->nworkers_launched; ++i)
573 BgwHandleStatus status;
575 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
578 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
581 * If the postmaster kicked the bucket, we have no chance of cleaning
582 * up safely -- we won't be able to tell when our workers are actually
583 * dead. This doesn't necessitate a PANIC since they will all abort
584 * eventually, but we can't safely continue this session.
586 if (status == BGWH_POSTMASTER_DIED)
588 (errcode(ERRCODE_ADMIN_SHUTDOWN),
589 errmsg("postmaster exited during a parallel transaction")));
591 /* Release memory. */
592 pfree(pcxt->worker[i].bgwhandle);
593 pcxt->worker[i].bgwhandle = NULL;
598 * Destroy a parallel context.
600 * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
601 * first, before calling this function. When this function is invoked, any
602 * remaining workers are forcibly killed; the dynamic shared memory segment
603 * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
606 DestroyParallelContext(ParallelContext *pcxt)
611 * Be careful about order of operations here! We remove the parallel
612 * context from the list before we do anything else; otherwise, if an
613 * error occurs during a subsequent step, we might try to nuke it again
614 * from AtEOXact_Parallel or AtEOSubXact_Parallel.
616 dlist_delete(&pcxt->node);
618 /* Kill each worker in turn, and forget their error queues. */
619 if (pcxt->worker != NULL)
621 for (i = 0; i < pcxt->nworkers_launched; ++i)
623 if (pcxt->worker[i].error_mqh != NULL)
625 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
627 pfree(pcxt->worker[i].error_mqh);
628 pcxt->worker[i].error_mqh = NULL;
634 * If we have allocated a shared memory segment, detach it. This will
635 * implicitly detach the error queues, and any other shared memory queues,
638 if (pcxt->seg != NULL)
640 dsm_detach(pcxt->seg);
645 * If this parallel context is actually in backend-private memory rather
646 * than shared memory, free that memory instead.
648 if (pcxt->private_memory != NULL)
650 pfree(pcxt->private_memory);
651 pcxt->private_memory = NULL;
655 * We can't finish transaction commit or abort until all of the workers
656 * have exited. This means, in particular, that we can't respond to
657 * interrupts at this stage.
660 WaitForParallelWorkersToExit(pcxt);
663 /* Free the worker array itself. */
664 if (pcxt->worker != NULL)
675 * Are there any parallel contexts currently active?
678 ParallelContextActive(void)
680 return !dlist_is_empty(&pcxt_list);
684 * Handle receipt of an interrupt indicating a parallel worker message.
686 * Note: this is called within a signal handler! All we can do is set
687 * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
688 * HandleParallelMessages().
691 HandleParallelMessageInterrupt(void)
693 InterruptPending = true;
694 ParallelMessagePending = true;
699 * Handle any queued protocol messages received from parallel workers.
702 HandleParallelMessages(void)
707 * This is invoked from ProcessInterrupts(), and since some of the
708 * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
709 * for recursive calls if more signals are received while this runs. It's
710 * unclear that recursive entry would be safe, and it doesn't seem useful
711 * even if it is safe, so let's block interrupts until done.
715 ParallelMessagePending = false;
717 dlist_foreach(iter, &pcxt_list)
719 ParallelContext *pcxt;
722 pcxt = dlist_container(ParallelContext, node, iter.cur);
723 if (pcxt->worker == NULL)
726 for (i = 0; i < pcxt->nworkers_launched; ++i)
729 * Read as many messages as we can from each worker, but stop when
730 * either (1) the worker's error queue goes away, which can happen
731 * if we receive a Terminate message from the worker; or (2) no
732 * more messages can be read from the worker without blocking.
734 while (pcxt->worker[i].error_mqh != NULL)
740 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
742 if (res == SHM_MQ_WOULD_BLOCK)
744 else if (res == SHM_MQ_SUCCESS)
748 initStringInfo(&msg);
749 appendBinaryStringInfo(&msg, data, nbytes);
750 HandleParallelMessage(pcxt, i, &msg);
755 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
756 errmsg("lost connection to parallel worker")));
765 * Handle a single protocol message received from a single parallel worker.
768 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
772 msgtype = pq_getmsgbyte(msg);
776 case 'K': /* BackendKeyData */
778 int32 pid = pq_getmsgint(msg, 4);
780 (void) pq_getmsgint(msg, 4); /* discard cancel key */
781 (void) pq_getmsgend(msg);
782 pcxt->worker[i].pid = pid;
786 case 'E': /* ErrorResponse */
787 case 'N': /* NoticeResponse */
790 ErrorContextCallback *save_error_context_stack;
792 /* Parse ErrorResponse or NoticeResponse. */
793 pq_parse_errornotice(msg, &edata);
795 /* Death of a worker isn't enough justification for suicide. */
796 edata.elevel = Min(edata.elevel, ERROR);
799 * If desired, add a context line to show that this is a
800 * message propagated from a parallel worker. Otherwise, it
801 * can sometimes be confusing to understand what actually
802 * happened. (We don't do this in FORCE_PARALLEL_REGRESS mode
803 * because it causes test-result instability depending on
804 * whether a parallel worker is actually used or not.)
806 if (force_parallel_mode != FORCE_PARALLEL_REGRESS)
809 edata.context = psprintf("%s\n%s", edata.context,
810 _("parallel worker"));
812 edata.context = pstrdup(_("parallel worker"));
816 * Context beyond that should use the error context callbacks
817 * that were in effect when the ParallelContext was created,
818 * not the current ones.
820 save_error_context_stack = error_context_stack;
821 error_context_stack = pcxt->error_context_stack;
823 /* Rethrow error or print notice. */
824 ThrowErrorData(&edata);
826 /* Not an error, so restore previous context stack. */
827 error_context_stack = save_error_context_stack;
832 case 'A': /* NotifyResponse */
834 /* Propagate NotifyResponse. */
839 pid = pq_getmsgint(msg, 4);
840 channel = pq_getmsgrawstring(msg);
841 payload = pq_getmsgrawstring(msg);
844 NotifyMyFrontEnd(channel, payload, pid);
849 case 'X': /* Terminate, indicating clean exit */
851 pfree(pcxt->worker[i].error_mqh);
852 pcxt->worker[i].error_mqh = NULL;
858 elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
865 * End-of-subtransaction cleanup for parallel contexts.
867 * Currently, it's forbidden to enter or leave a subtransaction while
868 * parallel mode is in effect, so we could just blow away everything. But
869 * we may want to relax that restriction in the future, so this code
870 * contemplates that there may be multiple subtransaction IDs in pcxt_list.
873 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
875 while (!dlist_is_empty(&pcxt_list))
877 ParallelContext *pcxt;
879 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
880 if (pcxt->subid != mySubId)
883 elog(WARNING, "leaked parallel context");
884 DestroyParallelContext(pcxt);
889 * End-of-transaction cleanup for parallel contexts.
892 AtEOXact_Parallel(bool isCommit)
894 while (!dlist_is_empty(&pcxt_list))
896 ParallelContext *pcxt;
898 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
900 elog(WARNING, "leaked parallel context");
901 DestroyParallelContext(pcxt);
906 * Main entrypoint for parallel workers.
909 ParallelWorkerMain(Datum main_arg)
913 FixedParallelState *fps;
914 char *error_queue_space;
923 StringInfoData msgbuf;
925 /* Set flag to indicate that we're initializing a parallel worker. */
926 InitializingParallelWorker = true;
928 /* Establish signal handlers. */
929 pqsignal(SIGTERM, die);
930 BackgroundWorkerUnblockSignals();
932 /* Determine and set our parallel worker number. */
933 Assert(ParallelWorkerNumber == -1);
934 memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
936 /* Set up a memory context and resource owner. */
937 Assert(CurrentResourceOwner == NULL);
938 CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
939 CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
941 ALLOCSET_DEFAULT_MINSIZE,
942 ALLOCSET_DEFAULT_INITSIZE,
943 ALLOCSET_DEFAULT_MAXSIZE);
946 * Now that we have a resource owner, we can attach to the dynamic shared
947 * memory segment and read the table of contents.
949 seg = dsm_attach(DatumGetUInt32(main_arg));
952 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
953 errmsg("could not map dynamic shared memory segment")));
954 toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
957 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
958 errmsg("invalid magic number in dynamic shared memory segment")));
960 /* Look up fixed parallel state. */
961 fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
963 MyFixedParallelState = fps;
966 * Now that we have a worker number, we can find and attach to the error
967 * queue provided for us. That's good, because until we do that, any
968 * errors that happen here will not be reported back to the process that
969 * requested that this worker be launched.
971 error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
972 mq = (shm_mq *) (error_queue_space +
973 ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
974 shm_mq_set_sender(mq, MyProc);
975 mqh = shm_mq_attach(mq, seg, NULL);
976 pq_redirect_to_shm_mq(seg, mqh);
977 pq_set_parallel_master(fps->parallel_master_pid,
978 fps->parallel_master_backend_id);
981 * Send a BackendKeyData message to the process that initiated parallelism
982 * so that it has access to our PID before it receives any other messages
983 * from us. Our cancel key is sent, too, since that's the way the
984 * protocol message is defined, but it won't actually be used for anything
987 pq_beginmessage(&msgbuf, 'K');
988 pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
989 pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
990 pq_endmessage(&msgbuf);
993 * Hooray! Primary initialization is complete. Now, we need to set up our
994 * backend-local state to match the original backend.
998 * Join locking group. We must do this before anything that could try to
999 * acquire a heavyweight lock, because any heavyweight locks acquired to
1000 * this point could block either directly against the parallel group
1001 * leader or against some process which in turn waits for a lock that
1002 * conflicts with the parallel group leader, causing an undetected
1003 * deadlock. (If we can't join the lock group, the leader has gone away,
1004 * so just exit quietly.)
1006 if (!BecomeLockGroupMember(fps->parallel_master_pgproc,
1007 fps->parallel_master_pid))
1011 * Load libraries that were loaded by original backend. We want to do
1012 * this before restoring GUCs, because the libraries might define custom
1015 libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
1016 Assert(libraryspace != NULL);
1017 RestoreLibraryState(libraryspace);
1019 /* Restore database connection. */
1020 BackgroundWorkerInitializeConnectionByOid(fps->database_id,
1021 fps->authenticated_user_id);
1024 * Set the client encoding to the database encoding, since that is what
1025 * the leader will expect.
1027 SetClientEncoding(GetDatabaseEncoding());
1029 /* Restore GUC values from launching backend. */
1030 gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
1031 Assert(gucspace != NULL);
1032 StartTransactionCommand();
1033 RestoreGUCState(gucspace);
1034 CommitTransactionCommand();
1036 /* Crank up a transaction state appropriate to a parallel worker. */
1037 tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
1038 StartParallelWorkerTransaction(tstatespace);
1040 /* Restore combo CID state. */
1041 combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
1042 Assert(combocidspace != NULL);
1043 RestoreComboCIDState(combocidspace);
1045 /* Restore transaction snapshot. */
1046 tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
1047 Assert(tsnapspace != NULL);
1048 RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
1049 fps->parallel_master_pgproc);
1051 /* Restore active snapshot. */
1052 asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1053 Assert(asnapspace != NULL);
1054 PushActiveSnapshot(RestoreSnapshot(asnapspace));
1057 * We've changed which tuples we can see, and must therefore invalidate
1060 InvalidateSystemCaches();
1062 /* Restore user ID and security context. */
1063 SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1065 /* Restore temp-namespace state to ensure search path matches leader's. */
1066 SetTempNamespaceState(fps->temp_namespace_id,
1067 fps->temp_toast_namespace_id);
1069 /* Set ParallelMasterBackendId so we know how to address temp relations. */
1070 ParallelMasterBackendId = fps->parallel_master_backend_id;
1073 * We've initialized all of our state now; nothing should change
1076 InitializingParallelWorker = false;
1077 EnterParallelMode();
1080 * Time to do the real work: invoke the caller-supplied code.
1082 * If you get a crash at this line, see the comments for
1083 * ParallelExtensionTrampoline.
1085 fps->entrypoint(seg, toc);
1087 /* Must exit parallel mode to pop active snapshot. */
1090 /* Must pop active snapshot so resowner.c doesn't complain. */
1091 PopActiveSnapshot();
1093 /* Shut down the parallel-worker transaction. */
1094 EndParallelWorkerTransaction();
1096 /* Report success. */
1097 pq_putmessage('X', NULL, 0);
1101 * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1102 * function living in a dynamically loaded module, because the module might
1103 * not be loaded in every process, or might be loaded but not at the same
1104 * address. To work around that problem, CreateParallelContextForExtension()
1105 * arranges to call this function rather than calling the extension-provided
1106 * function directly; and this function then looks up the real entrypoint and
1110 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1112 char *extensionstate;
1114 char *function_name;
1115 parallel_worker_main_type entrypt;
1117 extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1118 Assert(extensionstate != NULL);
1119 library_name = extensionstate;
1120 function_name = extensionstate + strlen(library_name) + 1;
1122 entrypt = (parallel_worker_main_type)
1123 load_external_function(library_name, function_name, true, NULL);
1128 * Update shared memory with the ending location of the last WAL record we
1129 * wrote, if it's greater than the value already stored there.
1132 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1134 FixedParallelState *fps = MyFixedParallelState;
1136 Assert(fps != NULL);
1137 SpinLockAcquire(&fps->mutex);
1138 if (fps->last_xlog_end < last_xlog_end)
1139 fps->last_xlog_end = last_xlog_end;
1140 SpinLockRelease(&fps->mutex);