1 /*-------------------------------------------------------------------------
4 * Infrastructure for launching parallel workers
6 * Portions Copyright (c) 1996-2014, 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 "commands/async.h"
21 #include "libpq/libpq.h"
22 #include "libpq/pqformat.h"
23 #include "libpq/pqmq.h"
24 #include "miscadmin.h"
25 #include "storage/ipc.h"
26 #include "storage/sinval.h"
27 #include "storage/spin.h"
28 #include "tcop/tcopprot.h"
29 #include "utils/combocid.h"
30 #include "utils/guc.h"
31 #include "utils/inval.h"
32 #include "utils/memutils.h"
33 #include "utils/resowner.h"
34 #include "utils/snapmgr.h"
37 * We don't want to waste a lot of memory on an error queue which, most of
38 * the time, will process only a handful of small messages. However, it is
39 * desirable to make it large enough that a typical ErrorResponse can be sent
40 * without blocking. That way, a worker that errors out can write the whole
41 * message into the queue and terminate without waiting for the user backend.
43 #define PARALLEL_ERROR_QUEUE_SIZE 16384
45 /* Magic number for parallel context TOC. */
46 #define PARALLEL_MAGIC 0x50477c7c
49 * Magic numbers for parallel state sharing. Higher-level code should use
50 * smaller values, leaving these very large ones for use by this module.
52 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
53 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
54 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
55 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
56 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
57 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
58 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
59 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
60 #define PARALLEL_KEY_EXTENSION_TRAMPOLINE UINT64CONST(0xFFFFFFFFFFFF0009)
62 /* Fixed-size parallel state. */
63 typedef struct FixedParallelState
65 /* Fixed-size state that workers must restore. */
67 Oid authenticated_user_id;
70 PGPROC *parallel_master_pgproc;
71 pid_t parallel_master_pid;
72 BackendId parallel_master_backend_id;
74 /* Entrypoint for parallel workers. */
75 parallel_worker_main_type entrypoint;
77 /* Mutex protects remaining fields. */
80 /* Track whether workers have attached. */
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
141 * parallel workers, at least not until somebody enhances that mechanism
142 * to be parallel-aware.
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 * copied state and other bookkeeping information that will need by parallel
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 PARALLEL_ERROR_QUEUE_SIZE * pcxt->nworkers);
248 shm_toc_estimate_keys(&pcxt->estimator, 1);
250 /* Estimate how much we'll need for extension entrypoint info. */
251 if (pcxt->library_name != NULL)
253 Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
254 Assert(pcxt->function_name != NULL);
255 shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
256 + strlen(pcxt->function_name) + 2);
257 shm_toc_estimate_keys(&pcxt->estimator, 1);
262 * Create DSM and initialize with new table of contents. But if the user
263 * didn't request any workers, then don't bother creating a dynamic shared
264 * memory segment; instead, just use backend-private memory.
266 * Also, if we can't create a dynamic shared memory segment because the
267 * maximum number of segments have already been created, then fall back to
268 * backend-private memory, and plan not to use any workers. We hope this
269 * won't happen very often, but it's better to abandon the use of
270 * parallelism than to fail outright.
272 segsize = shm_toc_estimate(&pcxt->estimator);
273 if (pcxt->nworkers != 0)
274 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
275 if (pcxt->seg != NULL)
276 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
277 dsm_segment_address(pcxt->seg),
282 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
283 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
287 /* Initialize fixed-size state in shared memory. */
288 fps = (FixedParallelState *)
289 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
290 fps->database_id = MyDatabaseId;
291 fps->authenticated_user_id = GetAuthenticatedUserId();
292 GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
293 fps->parallel_master_pgproc = MyProc;
294 fps->parallel_master_pid = MyProcPid;
295 fps->parallel_master_backend_id = MyBackendId;
296 fps->entrypoint = pcxt->entrypoint;
297 SpinLockInit(&fps->mutex);
298 fps->workers_expected = pcxt->nworkers;
299 fps->workers_attached = 0;
300 fps->last_xlog_end = 0;
301 shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
303 /* We can skip the rest of this if we're not budgeting for any workers. */
304 if (pcxt->nworkers > 0)
312 char *error_queue_space;
314 /* Serialize shared libraries we have loaded. */
315 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
316 SerializeLibraryState(library_len, libraryspace);
317 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
319 /* Serialize GUC settings. */
320 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
321 SerializeGUCState(guc_len, gucspace);
322 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
324 /* Serialize combo CID state. */
325 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
326 SerializeComboCIDState(combocidlen, combocidspace);
327 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
329 /* Serialize transaction snapshot and active snapshot. */
330 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
331 SerializeSnapshot(transaction_snapshot, tsnapspace);
332 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
334 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
335 SerializeSnapshot(active_snapshot, asnapspace);
336 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
338 /* Serialize transaction state. */
339 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
340 SerializeTransactionState(tstatelen, tstatespace);
341 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
343 /* Allocate space for worker information. */
344 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
347 * Establish error queues in dynamic shared memory.
349 * These queues should be used only for transmitting ErrorResponse,
350 * NoticeResponse, and NotifyResponse protocol messages. Tuple data
351 * should be transmitted via separate (possibly larger?) queues.
354 shm_toc_allocate(pcxt->toc,
355 PARALLEL_ERROR_QUEUE_SIZE * pcxt->nworkers);
356 for (i = 0; i < pcxt->nworkers; ++i)
361 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
362 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
363 shm_mq_set_receiver(mq, MyProc);
364 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
366 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
368 /* Serialize extension entrypoint information. */
369 if (pcxt->library_name != NULL)
371 Size lnamelen = strlen(pcxt->library_name);
372 char *extensionstate;
374 extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
375 + strlen(pcxt->function_name) + 2);
376 strcpy(extensionstate, pcxt->library_name);
377 strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
378 shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
383 /* Restore previous memory context. */
384 MemoryContextSwitchTo(oldcontext);
388 * Reinitialize the dynamic shared memory segment for a parallel context such
389 * that we could launch workers for it again.
392 ReinitializeParallelDSM(ParallelContext *pcxt)
394 FixedParallelState *fps;
395 char *error_queue_space;
398 if (pcxt->nworkers_launched == 0)
401 WaitForParallelWorkersToFinish(pcxt);
402 WaitForParallelWorkersToExit(pcxt);
404 /* Reset a few bits of fixed parallel state to a clean state. */
405 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
406 fps->workers_attached = 0;
407 fps->last_xlog_end = 0;
409 /* Recreate error queues. */
411 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
412 for (i = 0; i < pcxt->nworkers; ++i)
417 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
418 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
419 shm_mq_set_receiver(mq, MyProc);
420 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
423 /* Reset number of workers launched. */
424 pcxt->nworkers_launched = 0;
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 /* If we do have workers, we'd better have a DSM segment. */
443 Assert(pcxt->seg != NULL);
445 /* We might be running in a short-lived memory context. */
446 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
448 /* Configure a worker. */
449 snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
452 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
453 worker.bgw_start_time = BgWorkerStart_ConsistentState;
454 worker.bgw_restart_time = BGW_NEVER_RESTART;
455 worker.bgw_main = ParallelWorkerMain;
456 worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
457 worker.bgw_notify_pid = MyProcPid;
462 * The caller must be able to tolerate ending up with fewer workers than
463 * expected, so there is no need to throw an error here if registration
464 * fails. It wouldn't help much anyway, because registering the worker in
465 * no way guarantees that it will start up and initialize successfully.
467 for (i = 0; i < pcxt->nworkers; ++i)
469 if (!any_registrations_failed &&
470 RegisterDynamicBackgroundWorker(&worker,
471 &pcxt->worker[i].bgwhandle))
473 shm_mq_set_handle(pcxt->worker[i].error_mqh,
474 pcxt->worker[i].bgwhandle);
475 pcxt->nworkers_launched++;
480 * If we weren't able to register the worker, then we've bumped up
481 * against the max_worker_processes limit, and future
482 * registrations will probably fail too, so arrange to skip them.
483 * But we still have to execute this code for the remaining slots
484 * to make sure that we forget about the error queues we budgeted
485 * for those workers. Otherwise, we'll wait for them to start,
486 * but they never will.
488 any_registrations_failed = true;
489 pcxt->worker[i].bgwhandle = NULL;
490 pcxt->worker[i].error_mqh = NULL;
494 /* Restore previous memory context. */
495 MemoryContextSwitchTo(oldcontext);
499 * Wait for all workers to finish computing.
501 * Even if the parallel operation seems to have completed successfully, it's
502 * important to call this function afterwards. We must not miss any errors
503 * the workers may have thrown during the parallel operation, or any that they
504 * may yet throw while shutting down.
506 * Also, we want to update our notion of XactLastRecEnd based on worker
510 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
514 bool anyone_alive = false;
518 * This will process any parallel messages that are pending, which may
519 * change the outcome of the loop that follows. It may also throw an
520 * error propagated from a worker.
522 CHECK_FOR_INTERRUPTS();
524 for (i = 0; i < pcxt->nworkers; ++i)
526 if (pcxt->worker[i].error_mqh != NULL)
536 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1);
537 ResetLatch(&MyProc->procLatch);
540 if (pcxt->toc != NULL)
542 FixedParallelState *fps;
544 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
545 if (fps->last_xlog_end > XactLastRecEnd)
546 XactLastRecEnd = fps->last_xlog_end;
551 * Wait for all workers to exit.
553 * This function ensures that workers have been completely shutdown. The
554 * difference between WaitForParallelWorkersToFinish and this function is
555 * that former just ensures that last message sent by worker backend is
556 * received by master backend whereas this ensures the complete shutdown.
559 WaitForParallelWorkersToExit(ParallelContext *pcxt)
563 /* Wait until the workers actually die. */
564 for (i = 0; i < pcxt->nworkers; ++i)
566 BgwHandleStatus status;
568 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
571 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
574 * If the postmaster kicked the bucket, we have no chance of cleaning
575 * up safely -- we won't be able to tell when our workers are actually
576 * dead. This doesn't necessitate a PANIC since they will all abort
577 * eventually, but we can't safely continue this session.
579 if (status == BGWH_POSTMASTER_DIED)
581 (errcode(ERRCODE_ADMIN_SHUTDOWN),
582 errmsg("postmaster exited during a parallel transaction")));
584 /* Release memory. */
585 pfree(pcxt->worker[i].bgwhandle);
586 pcxt->worker[i].bgwhandle = NULL;
591 * Destroy a parallel context.
593 * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
594 * first, before calling this function. When this function is invoked, any
595 * remaining workers are forcibly killed; the dynamic shared memory segment
596 * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
599 DestroyParallelContext(ParallelContext *pcxt)
604 * Be careful about order of operations here! We remove the parallel
605 * context from the list before we do anything else; otherwise, if an
606 * error occurs during a subsequent step, we might try to nuke it again
607 * from AtEOXact_Parallel or AtEOSubXact_Parallel.
609 dlist_delete(&pcxt->node);
611 /* Kill each worker in turn, and forget their error queues. */
612 if (pcxt->worker != NULL)
614 for (i = 0; i < pcxt->nworkers; ++i)
616 if (pcxt->worker[i].error_mqh != NULL)
618 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
620 pfree(pcxt->worker[i].error_mqh);
621 pcxt->worker[i].error_mqh = NULL;
627 * If we have allocated a shared memory segment, detach it. This will
628 * implicitly detach the error queues, and any other shared memory queues,
631 if (pcxt->seg != NULL)
633 dsm_detach(pcxt->seg);
638 * If this parallel context is actually in backend-private memory rather
639 * than shared memory, free that memory instead.
641 if (pcxt->private_memory != NULL)
643 pfree(pcxt->private_memory);
644 pcxt->private_memory = NULL;
648 * We can't finish transaction commit or abort until all of the
649 * workers have exited. This means, in particular, that we can't respond
650 * to interrupts at this stage.
653 WaitForParallelWorkersToExit(pcxt);
656 /* Free the worker array itself. */
657 if (pcxt->worker != NULL)
668 * Are there any parallel contexts currently active?
671 ParallelContextActive(void)
673 return !dlist_is_empty(&pcxt_list);
677 * Handle receipt of an interrupt indicating a parallel worker message.
680 HandleParallelMessageInterrupt(void)
682 int save_errno = errno;
684 InterruptPending = true;
685 ParallelMessagePending = true;
692 * Handle any queued protocol messages received from parallel workers.
695 HandleParallelMessages(void)
699 ParallelMessagePending = false;
701 dlist_foreach(iter, &pcxt_list)
703 ParallelContext *pcxt;
708 pcxt = dlist_container(ParallelContext, node, iter.cur);
709 if (pcxt->worker == NULL)
712 for (i = 0; i < pcxt->nworkers; ++i)
715 * Read as many messages as we can from each worker, but stop when
716 * either (1) the error queue goes away, which can happen if we
717 * receive a Terminate message from the worker; or (2) no more
718 * messages can be read from the worker without blocking.
720 while (pcxt->worker[i].error_mqh != NULL)
724 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
726 if (res == SHM_MQ_WOULD_BLOCK)
728 else if (res == SHM_MQ_SUCCESS)
732 initStringInfo(&msg);
733 appendBinaryStringInfo(&msg, data, nbytes);
734 HandleParallelMessage(pcxt, i, &msg);
739 (errcode(ERRCODE_INTERNAL_ERROR), /* XXX: wrong errcode? */
740 errmsg("lost connection to parallel worker")));
742 /* This might make the error queue go away. */
743 CHECK_FOR_INTERRUPTS();
750 * Handle a single protocol message received from a single parallel worker.
753 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
757 msgtype = pq_getmsgbyte(msg);
761 case 'K': /* BackendKeyData */
763 int32 pid = pq_getmsgint(msg, 4);
765 (void) pq_getmsgint(msg, 4); /* discard cancel key */
766 (void) pq_getmsgend(msg);
767 pcxt->worker[i].pid = pid;
771 case 'E': /* ErrorResponse */
772 case 'N': /* NoticeResponse */
775 ErrorContextCallback errctx;
776 ErrorContextCallback *save_error_context_stack;
779 * Rethrow the error using the error context callbacks that
780 * were in effect when the context was created, not the
783 save_error_context_stack = error_context_stack;
784 errctx.callback = ParallelErrorContext;
785 errctx.arg = &pcxt->worker[i].pid;
786 errctx.previous = pcxt->error_context_stack;
787 error_context_stack = &errctx;
789 /* Parse ErrorResponse or NoticeResponse. */
790 pq_parse_errornotice(msg, &edata);
792 /* Death of a worker isn't enough justification for suicide. */
793 edata.elevel = Min(edata.elevel, ERROR);
795 /* Rethrow error or notice. */
796 ThrowErrorData(&edata);
798 /* Restore previous context. */
799 error_context_stack = save_error_context_stack;
804 case 'A': /* NotifyResponse */
806 /* Propagate NotifyResponse. */
807 pq_putmessage(msg->data[0], &msg->data[1], msg->len - 1);
811 case 'X': /* Terminate, indicating clean exit */
813 pfree(pcxt->worker[i].error_mqh);
814 pcxt->worker[i].error_mqh = NULL;
820 elog(ERROR, "unknown message type: %c (%d bytes)",
827 * End-of-subtransaction cleanup for parallel contexts.
829 * Currently, it's forbidden to enter or leave a subtransaction while
830 * parallel mode is in effect, so we could just blow away everything. But
831 * we may want to relax that restriction in the future, so this code
832 * contemplates that there may be multiple subtransaction IDs in pcxt_list.
835 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
837 while (!dlist_is_empty(&pcxt_list))
839 ParallelContext *pcxt;
841 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
842 if (pcxt->subid != mySubId)
845 elog(WARNING, "leaked parallel context");
846 DestroyParallelContext(pcxt);
851 * End-of-transaction cleanup for parallel contexts.
854 AtEOXact_Parallel(bool isCommit)
856 while (!dlist_is_empty(&pcxt_list))
858 ParallelContext *pcxt;
860 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
862 elog(WARNING, "leaked parallel context");
863 DestroyParallelContext(pcxt);
868 * Main entrypoint for parallel workers.
871 ParallelWorkerMain(Datum main_arg)
875 FixedParallelState *fps;
876 char *error_queue_space;
885 StringInfoData msgbuf;
887 /* Set flag to indicate that we're initializing a parallel worker. */
888 InitializingParallelWorker = true;
890 /* Establish signal handlers. */
891 pqsignal(SIGTERM, die);
892 BackgroundWorkerUnblockSignals();
894 /* Set up a memory context and resource owner. */
895 Assert(CurrentResourceOwner == NULL);
896 CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
897 CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
899 ALLOCSET_DEFAULT_MINSIZE,
900 ALLOCSET_DEFAULT_INITSIZE,
901 ALLOCSET_DEFAULT_MAXSIZE);
904 * Now that we have a resource owner, we can attach to the dynamic shared
905 * memory segment and read the table of contents.
907 seg = dsm_attach(DatumGetUInt32(main_arg));
910 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
911 errmsg("unable to map dynamic shared memory segment")));
912 toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
915 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
916 errmsg("bad magic number in dynamic shared memory segment")));
918 /* Determine and set our worker number. */
919 fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
921 Assert(ParallelWorkerNumber == -1);
922 SpinLockAcquire(&fps->mutex);
923 if (fps->workers_attached < fps->workers_expected)
924 ParallelWorkerNumber = fps->workers_attached++;
925 SpinLockRelease(&fps->mutex);
926 if (ParallelWorkerNumber < 0)
928 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
929 errmsg("too many parallel workers already attached")));
930 MyFixedParallelState = fps;
933 * Now that we have a worker number, we can find and attach to the error
934 * queue provided for us. That's good, because until we do that, any
935 * errors that happen here will not be reported back to the process that
936 * requested that this worker be launched.
938 error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
939 mq = (shm_mq *) (error_queue_space +
940 ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
941 shm_mq_set_sender(mq, MyProc);
942 mqh = shm_mq_attach(mq, seg, NULL);
943 pq_redirect_to_shm_mq(seg, mqh);
944 pq_set_parallel_master(fps->parallel_master_pid,
945 fps->parallel_master_backend_id);
948 * Send a BackendKeyData message to the process that initiated parallelism
949 * so that it has access to our PID before it receives any other messages
950 * from us. Our cancel key is sent, too, since that's the way the
951 * protocol message is defined, but it won't actually be used for anything
954 pq_beginmessage(&msgbuf, 'K');
955 pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
956 pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
957 pq_endmessage(&msgbuf);
960 * Hooray! Primary initialization is complete. Now, we need to set up our
961 * backend-local state to match the original backend.
965 * Load libraries that were loaded by original backend. We want to do
966 * this before restoring GUCs, because the libraries might define custom
969 libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
970 Assert(libraryspace != NULL);
971 RestoreLibraryState(libraryspace);
973 /* Restore database connection. */
974 BackgroundWorkerInitializeConnectionByOid(fps->database_id,
975 fps->authenticated_user_id);
977 /* Restore GUC values from launching backend. */
978 gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
979 Assert(gucspace != NULL);
980 StartTransactionCommand();
981 RestoreGUCState(gucspace);
982 CommitTransactionCommand();
984 /* Crank up a transaction state appropriate to a parallel worker. */
985 tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
986 StartParallelWorkerTransaction(tstatespace);
988 /* Restore combo CID state. */
989 combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
990 Assert(combocidspace != NULL);
991 RestoreComboCIDState(combocidspace);
993 /* Restore transaction snapshot. */
994 tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
995 Assert(tsnapspace != NULL);
996 RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
997 fps->parallel_master_pgproc);
999 /* Restore active snapshot. */
1000 asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1001 Assert(asnapspace != NULL);
1002 PushActiveSnapshot(RestoreSnapshot(asnapspace));
1005 * We've changed which tuples we can see, and must therefore invalidate
1008 InvalidateSystemCaches();
1010 /* Restore user ID and security context. */
1011 SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1014 * We've initialized all of our state now; nothing should change
1017 InitializingParallelWorker = false;
1018 EnterParallelMode();
1021 * Time to do the real work: invoke the caller-supplied code.
1023 * If you get a crash at this line, see the comments for
1024 * ParallelExtensionTrampoline.
1026 fps->entrypoint(seg, toc);
1028 /* Must exit parallel mode to pop active snapshot. */
1031 /* Must pop active snapshot so resowner.c doesn't complain. */
1032 PopActiveSnapshot();
1034 /* Shut down the parallel-worker transaction. */
1035 EndParallelWorkerTransaction();
1037 /* Report success. */
1038 pq_putmessage('X', NULL, 0);
1042 * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1043 * function living in a dynamically loaded module, because the module might
1044 * not be loaded in every process, or might be loaded but not at the same
1045 * address. To work around that problem, CreateParallelContextForExtension()
1046 * arranges to call this function rather than calling the extension-provided
1047 * function directly; and this function then looks up the real entrypoint and
1051 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1053 char *extensionstate;
1055 char *function_name;
1056 parallel_worker_main_type entrypt;
1058 extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1059 Assert(extensionstate != NULL);
1060 library_name = extensionstate;
1061 function_name = extensionstate + strlen(library_name) + 1;
1063 entrypt = (parallel_worker_main_type)
1064 load_external_function(library_name, function_name, true, NULL);
1069 * Give the user a hint that this is a message propagated from a parallel
1070 * worker. Otherwise, it can sometimes be confusing to understand what
1071 * actually happened.
1074 ParallelErrorContext(void *arg)
1076 errcontext("parallel worker, pid %d", *(int32 *) arg);
1080 * Update shared memory with the ending location of the last WAL record we
1081 * wrote, if it's greater than the value already stored there.
1084 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1086 FixedParallelState *fps = MyFixedParallelState;
1088 Assert(fps != NULL);
1089 SpinLockAcquire(&fps->mutex);
1090 if (fps->last_xlog_end < last_xlog_end)
1091 fps->last_xlog_end = last_xlog_end;
1092 SpinLockRelease(&fps->mutex);