]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/parallel.c
pgindent run for 9.6
[postgresql] / src / backend / access / transam / parallel.c
1 /*-------------------------------------------------------------------------
2  *
3  * parallel.c
4  *        Infrastructure for launching parallel workers
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        src/backend/access/transam/parallel.c
11  *
12  *-------------------------------------------------------------------------
13  */
14
15 #include "postgres.h"
16
17 #include "access/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 "optimizer/planmain.h"
26 #include "storage/ipc.h"
27 #include "storage/sinval.h"
28 #include "storage/spin.h"
29 #include "tcop/tcopprot.h"
30 #include "utils/combocid.h"
31 #include "utils/guc.h"
32 #include "utils/inval.h"
33 #include "utils/memutils.h"
34 #include "utils/resowner.h"
35 #include "utils/snapmgr.h"
36
37 /*
38  * We don't want to waste a lot of memory on an error queue which, most of
39  * the time, will process only a handful of small messages.  However, it is
40  * desirable to make it large enough that a typical ErrorResponse can be sent
41  * without blocking.  That way, a worker that errors out can write the whole
42  * message into the queue and terminate without waiting for the user backend.
43  */
44 #define PARALLEL_ERROR_QUEUE_SIZE                       16384
45
46 /* Magic number for parallel context TOC. */
47 #define PARALLEL_MAGIC                                          0x50477c7c
48
49 /*
50  * Magic numbers for parallel state sharing.  Higher-level code should use
51  * smaller values, leaving these very large ones for use by this module.
52  */
53 #define PARALLEL_KEY_FIXED                                      UINT64CONST(0xFFFFFFFFFFFF0001)
54 #define PARALLEL_KEY_ERROR_QUEUE                        UINT64CONST(0xFFFFFFFFFFFF0002)
55 #define PARALLEL_KEY_LIBRARY                            UINT64CONST(0xFFFFFFFFFFFF0003)
56 #define PARALLEL_KEY_GUC                                        UINT64CONST(0xFFFFFFFFFFFF0004)
57 #define PARALLEL_KEY_COMBO_CID                          UINT64CONST(0xFFFFFFFFFFFF0005)
58 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT       UINT64CONST(0xFFFFFFFFFFFF0006)
59 #define PARALLEL_KEY_ACTIVE_SNAPSHOT            UINT64CONST(0xFFFFFFFFFFFF0007)
60 #define PARALLEL_KEY_TRANSACTION_STATE          UINT64CONST(0xFFFFFFFFFFFF0008)
61 #define PARALLEL_KEY_EXTENSION_TRAMPOLINE       UINT64CONST(0xFFFFFFFFFFFF0009)
62
63 /* Fixed-size parallel state. */
64 typedef struct FixedParallelState
65 {
66         /* Fixed-size state that workers must restore. */
67         Oid                     database_id;
68         Oid                     authenticated_user_id;
69         Oid                     current_user_id;
70         int                     sec_context;
71         PGPROC     *parallel_master_pgproc;
72         pid_t           parallel_master_pid;
73         BackendId       parallel_master_backend_id;
74
75         /* Entrypoint for parallel workers. */
76         parallel_worker_main_type entrypoint;
77
78         /* Mutex protects remaining fields. */
79         slock_t         mutex;
80
81         /* Maximum XactLastRecEnd of any worker. */
82         XLogRecPtr      last_xlog_end;
83 } FixedParallelState;
84
85 /*
86  * Our parallel worker number.  We initialize this to -1, meaning that we are
87  * not a parallel worker.  In parallel workers, it will be set to a value >= 0
88  * and < the number of workers before any user code is invoked; each parallel
89  * worker will get a different parallel worker number.
90  */
91 int                     ParallelWorkerNumber = -1;
92
93 /* Is there a parallel message pending which we need to receive? */
94 bool            ParallelMessagePending = false;
95
96 /* Are we initializing a parallel worker? */
97 bool            InitializingParallelWorker = false;
98
99 /* Pointer to our fixed parallel state. */
100 static FixedParallelState *MyFixedParallelState;
101
102 /* List of active parallel contexts. */
103 static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list);
104
105 /* Private functions. */
106 static void HandleParallelMessage(ParallelContext *, int, StringInfo msg);
107 static void ParallelErrorContext(void *arg);
108 static void ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc);
109 static void ParallelWorkerMain(Datum main_arg);
110 static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
111
112 /*
113  * Establish a new parallel context.  This should be done after entering
114  * parallel mode, and (unless there is an error) the context should be
115  * destroyed before exiting the current subtransaction.
116  */
117 ParallelContext *
118 CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
119 {
120         MemoryContext oldcontext;
121         ParallelContext *pcxt;
122
123         /* It is unsafe to create a parallel context if not in parallel mode. */
124         Assert(IsInParallelMode());
125
126         /* Number of workers should be non-negative. */
127         Assert(nworkers >= 0);
128
129         /*
130          * If dynamic shared memory is not available, we won't be able to use
131          * background workers.
132          */
133         if (dynamic_shared_memory_type == DSM_IMPL_NONE)
134                 nworkers = 0;
135
136         /*
137          * If we are running under serializable isolation, we can't use parallel
138          * workers, at least not until somebody enhances that mechanism to be
139          * parallel-aware.
140          */
141         if (IsolationIsSerializable())
142                 nworkers = 0;
143
144         /* We might be running in a short-lived memory context. */
145         oldcontext = MemoryContextSwitchTo(TopTransactionContext);
146
147         /* Initialize a new ParallelContext. */
148         pcxt = palloc0(sizeof(ParallelContext));
149         pcxt->subid = GetCurrentSubTransactionId();
150         pcxt->nworkers = nworkers;
151         pcxt->entrypoint = entrypoint;
152         pcxt->error_context_stack = error_context_stack;
153         shm_toc_initialize_estimator(&pcxt->estimator);
154         dlist_push_head(&pcxt_list, &pcxt->node);
155
156         /* Restore previous memory context. */
157         MemoryContextSwitchTo(oldcontext);
158
159         return pcxt;
160 }
161
162 /*
163  * Establish a new parallel context that calls a function provided by an
164  * extension.  This works around the fact that the library might get mapped
165  * at a different address in each backend.
166  */
167 ParallelContext *
168 CreateParallelContextForExternalFunction(char *library_name,
169                                                                                  char *function_name,
170                                                                                  int nworkers)
171 {
172         MemoryContext oldcontext;
173         ParallelContext *pcxt;
174
175         /* We might be running in a very short-lived memory context. */
176         oldcontext = MemoryContextSwitchTo(TopTransactionContext);
177
178         /* Create the context. */
179         pcxt = CreateParallelContext(ParallelExtensionTrampoline, nworkers);
180         pcxt->library_name = pstrdup(library_name);
181         pcxt->function_name = pstrdup(function_name);
182
183         /* Restore previous memory context. */
184         MemoryContextSwitchTo(oldcontext);
185
186         return pcxt;
187 }
188
189 /*
190  * Establish the dynamic shared memory segment for a parallel context and
191  * copied state and other bookkeeping information that will need by parallel
192  * workers into it.
193  */
194 void
195 InitializeParallelDSM(ParallelContext *pcxt)
196 {
197         MemoryContext oldcontext;
198         Size            library_len = 0;
199         Size            guc_len = 0;
200         Size            combocidlen = 0;
201         Size            tsnaplen = 0;
202         Size            asnaplen = 0;
203         Size            tstatelen = 0;
204         Size            segsize = 0;
205         int                     i;
206         FixedParallelState *fps;
207         Snapshot        transaction_snapshot = GetTransactionSnapshot();
208         Snapshot        active_snapshot = GetActiveSnapshot();
209
210         /* We might be running in a very short-lived memory context. */
211         oldcontext = MemoryContextSwitchTo(TopTransactionContext);
212
213         /* Allow space to store the fixed-size parallel state. */
214         shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
215         shm_toc_estimate_keys(&pcxt->estimator, 1);
216
217         /*
218          * Normally, the user will have requested at least one worker process, but
219          * if by chance they have not, we can skip a bunch of things here.
220          */
221         if (pcxt->nworkers > 0)
222         {
223                 /* Estimate space for various kinds of state sharing. */
224                 library_len = EstimateLibraryStateSpace();
225                 shm_toc_estimate_chunk(&pcxt->estimator, library_len);
226                 guc_len = EstimateGUCStateSpace();
227                 shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
228                 combocidlen = EstimateComboCIDStateSpace();
229                 shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
230                 tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
231                 shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
232                 asnaplen = EstimateSnapshotSpace(active_snapshot);
233                 shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
234                 tstatelen = EstimateTransactionStateSpace();
235                 shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
236                 /* If you add more chunks here, you probably need to add keys. */
237                 shm_toc_estimate_keys(&pcxt->estimator, 6);
238
239                 /* Estimate space need for error queues. */
240                 StaticAssertStmt(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
241                                                  PARALLEL_ERROR_QUEUE_SIZE,
242                                                  "parallel error queue size not buffer-aligned");
243                 shm_toc_estimate_chunk(&pcxt->estimator,
244                                                            mul_size(PARALLEL_ERROR_QUEUE_SIZE,
245                                                                                 pcxt->nworkers));
246                 shm_toc_estimate_keys(&pcxt->estimator, 1);
247
248                 /* Estimate how much we'll need for extension entrypoint info. */
249                 if (pcxt->library_name != NULL)
250                 {
251                         Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
252                         Assert(pcxt->function_name != NULL);
253                         shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
254                                                                    + strlen(pcxt->function_name) + 2);
255                         shm_toc_estimate_keys(&pcxt->estimator, 1);
256                 }
257         }
258
259         /*
260          * Create DSM and initialize with new table of contents.  But if the user
261          * didn't request any workers, then don't bother creating a dynamic shared
262          * memory segment; instead, just use backend-private memory.
263          *
264          * Also, if we can't create a dynamic shared memory segment because the
265          * maximum number of segments have already been created, then fall back to
266          * backend-private memory, and plan not to use any workers.  We hope this
267          * won't happen very often, but it's better to abandon the use of
268          * parallelism than to fail outright.
269          */
270         segsize = shm_toc_estimate(&pcxt->estimator);
271         if (pcxt->nworkers != 0)
272                 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
273         if (pcxt->seg != NULL)
274                 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
275                                                                    dsm_segment_address(pcxt->seg),
276                                                                    segsize);
277         else
278         {
279                 pcxt->nworkers = 0;
280                 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
281                 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
282                                                                    segsize);
283         }
284
285         /* Initialize fixed-size state in shared memory. */
286         fps = (FixedParallelState *)
287                 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
288         fps->database_id = MyDatabaseId;
289         fps->authenticated_user_id = GetAuthenticatedUserId();
290         GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
291         fps->parallel_master_pgproc = MyProc;
292         fps->parallel_master_pid = MyProcPid;
293         fps->parallel_master_backend_id = MyBackendId;
294         fps->entrypoint = pcxt->entrypoint;
295         SpinLockInit(&fps->mutex);
296         fps->last_xlog_end = 0;
297         shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
298
299         /* We can skip the rest of this if we're not budgeting for any workers. */
300         if (pcxt->nworkers > 0)
301         {
302                 char       *libraryspace;
303                 char       *gucspace;
304                 char       *combocidspace;
305                 char       *tsnapspace;
306                 char       *asnapspace;
307                 char       *tstatespace;
308                 char       *error_queue_space;
309
310                 /* Serialize shared libraries we have loaded. */
311                 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
312                 SerializeLibraryState(library_len, libraryspace);
313                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
314
315                 /* Serialize GUC settings. */
316                 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
317                 SerializeGUCState(guc_len, gucspace);
318                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
319
320                 /* Serialize combo CID state. */
321                 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
322                 SerializeComboCIDState(combocidlen, combocidspace);
323                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
324
325                 /* Serialize transaction snapshot and active snapshot. */
326                 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
327                 SerializeSnapshot(transaction_snapshot, tsnapspace);
328                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
329                                            tsnapspace);
330                 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
331                 SerializeSnapshot(active_snapshot, asnapspace);
332                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
333
334                 /* Serialize transaction state. */
335                 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
336                 SerializeTransactionState(tstatelen, tstatespace);
337                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
338
339                 /* Allocate space for worker information. */
340                 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
341
342                 /*
343                  * Establish error queues in dynamic shared memory.
344                  *
345                  * These queues should be used only for transmitting ErrorResponse,
346                  * NoticeResponse, and NotifyResponse protocol messages.  Tuple data
347                  * should be transmitted via separate (possibly larger?) queues.
348                  */
349                 error_queue_space =
350                         shm_toc_allocate(pcxt->toc,
351                                                          mul_size(PARALLEL_ERROR_QUEUE_SIZE,
352                                                                           pcxt->nworkers));
353                 for (i = 0; i < pcxt->nworkers; ++i)
354                 {
355                         char       *start;
356                         shm_mq     *mq;
357
358                         start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
359                         mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
360                         shm_mq_set_receiver(mq, MyProc);
361                         pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
362                 }
363                 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
364
365                 /* Serialize extension entrypoint information. */
366                 if (pcxt->library_name != NULL)
367                 {
368                         Size            lnamelen = strlen(pcxt->library_name);
369                         char       *extensionstate;
370
371                         extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
372                                                                                   + strlen(pcxt->function_name) + 2);
373                         strcpy(extensionstate, pcxt->library_name);
374                         strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
375                         shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
376                                                    extensionstate);
377                 }
378         }
379
380         /* Restore previous memory context. */
381         MemoryContextSwitchTo(oldcontext);
382 }
383
384 /*
385  * Reinitialize the dynamic shared memory segment for a parallel context such
386  * that we could launch workers for it again.
387  */
388 void
389 ReinitializeParallelDSM(ParallelContext *pcxt)
390 {
391         FixedParallelState *fps;
392         char       *error_queue_space;
393         int                     i;
394
395         if (pcxt->nworkers_launched == 0)
396                 return;
397
398         WaitForParallelWorkersToFinish(pcxt);
399         WaitForParallelWorkersToExit(pcxt);
400
401         /* Reset a few bits of fixed parallel state to a clean state. */
402         fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
403         fps->last_xlog_end = 0;
404
405         /* Recreate error queues. */
406         error_queue_space =
407                 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
408         for (i = 0; i < pcxt->nworkers; ++i)
409         {
410                 char       *start;
411                 shm_mq     *mq;
412
413                 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
414                 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
415                 shm_mq_set_receiver(mq, MyProc);
416                 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
417         }
418
419         /* Reset number of workers launched. */
420         pcxt->nworkers_launched = 0;
421 }
422
423 /*
424  * Launch parallel workers.
425  */
426 void
427 LaunchParallelWorkers(ParallelContext *pcxt)
428 {
429         MemoryContext oldcontext;
430         BackgroundWorker worker;
431         int                     i;
432         bool            any_registrations_failed = false;
433
434         /* Skip this if we have no workers. */
435         if (pcxt->nworkers == 0)
436                 return;
437
438         /* We need to be a lock group leader. */
439         BecomeLockGroupLeader();
440
441         /* If we do have workers, we'd better have a DSM segment. */
442         Assert(pcxt->seg != NULL);
443
444         /* We might be running in a short-lived memory context. */
445         oldcontext = MemoryContextSwitchTo(TopTransactionContext);
446
447         /* Configure a worker. */
448         snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
449                          MyProcPid);
450         worker.bgw_flags =
451                 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
452         worker.bgw_start_time = BgWorkerStart_ConsistentState;
453         worker.bgw_restart_time = BGW_NEVER_RESTART;
454         worker.bgw_main = ParallelWorkerMain;
455         worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
456         worker.bgw_notify_pid = MyProcPid;
457         memset(&worker.bgw_extra, 0, BGW_EXTRALEN);
458
459         /*
460          * Start workers.
461          *
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.
466          */
467         for (i = 0; i < pcxt->nworkers; ++i)
468         {
469                 memcpy(worker.bgw_extra, &i, sizeof(int));
470                 if (!any_registrations_failed &&
471                         RegisterDynamicBackgroundWorker(&worker,
472                                                                                         &pcxt->worker[i].bgwhandle))
473                 {
474                         shm_mq_set_handle(pcxt->worker[i].error_mqh,
475                                                           pcxt->worker[i].bgwhandle);
476                         pcxt->nworkers_launched++;
477                 }
478                 else
479                 {
480                         /*
481                          * If we weren't able to register the worker, then we've bumped up
482                          * against the max_worker_processes limit, and future
483                          * registrations will probably fail too, so arrange to skip them.
484                          * But we still have to execute this code for the remaining slots
485                          * to make sure that we forget about the error queues we budgeted
486                          * for those workers.  Otherwise, we'll wait for them to start,
487                          * but they never will.
488                          */
489                         any_registrations_failed = true;
490                         pcxt->worker[i].bgwhandle = NULL;
491                         pcxt->worker[i].error_mqh = NULL;
492                 }
493         }
494
495         /* Restore previous memory context. */
496         MemoryContextSwitchTo(oldcontext);
497 }
498
499 /*
500  * Wait for all workers to finish computing.
501  *
502  * Even if the parallel operation seems to have completed successfully, it's
503  * important to call this function afterwards.  We must not miss any errors
504  * the workers may have thrown during the parallel operation, or any that they
505  * may yet throw while shutting down.
506  *
507  * Also, we want to update our notion of XactLastRecEnd based on worker
508  * feedback.
509  */
510 void
511 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
512 {
513         for (;;)
514         {
515                 bool            anyone_alive = false;
516                 int                     i;
517
518                 /*
519                  * This will process any parallel messages that are pending, which may
520                  * change the outcome of the loop that follows.  It may also throw an
521                  * error propagated from a worker.
522                  */
523                 CHECK_FOR_INTERRUPTS();
524
525                 for (i = 0; i < pcxt->nworkers_launched; ++i)
526                 {
527                         if (pcxt->worker[i].error_mqh != NULL)
528                         {
529                                 anyone_alive = true;
530                                 break;
531                         }
532                 }
533
534                 if (!anyone_alive)
535                         break;
536
537                 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1);
538                 ResetLatch(&MyProc->procLatch);
539         }
540
541         if (pcxt->toc != NULL)
542         {
543                 FixedParallelState *fps;
544
545                 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
546                 if (fps->last_xlog_end > XactLastRecEnd)
547                         XactLastRecEnd = fps->last_xlog_end;
548         }
549 }
550
551 /*
552  * Wait for all workers to exit.
553  *
554  * This function ensures that workers have been completely shutdown.  The
555  * difference between WaitForParallelWorkersToFinish and this function is
556  * that former just ensures that last message sent by worker backend is
557  * received by master backend whereas this ensures the complete shutdown.
558  */
559 static void
560 WaitForParallelWorkersToExit(ParallelContext *pcxt)
561 {
562         int                     i;
563
564         /* Wait until the workers actually die. */
565         for (i = 0; i < pcxt->nworkers_launched; ++i)
566         {
567                 BgwHandleStatus status;
568
569                 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
570                         continue;
571
572                 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
573
574                 /*
575                  * If the postmaster kicked the bucket, we have no chance of cleaning
576                  * up safely -- we won't be able to tell when our workers are actually
577                  * dead.  This doesn't necessitate a PANIC since they will all abort
578                  * eventually, but we can't safely continue this session.
579                  */
580                 if (status == BGWH_POSTMASTER_DIED)
581                         ereport(FATAL,
582                                         (errcode(ERRCODE_ADMIN_SHUTDOWN),
583                                  errmsg("postmaster exited during a parallel transaction")));
584
585                 /* Release memory. */
586                 pfree(pcxt->worker[i].bgwhandle);
587                 pcxt->worker[i].bgwhandle = NULL;
588         }
589 }
590
591 /*
592  * Destroy a parallel context.
593  *
594  * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
595  * first, before calling this function.  When this function is invoked, any
596  * remaining workers are forcibly killed; the dynamic shared memory segment
597  * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
598  */
599 void
600 DestroyParallelContext(ParallelContext *pcxt)
601 {
602         int                     i;
603
604         /*
605          * Be careful about order of operations here!  We remove the parallel
606          * context from the list before we do anything else; otherwise, if an
607          * error occurs during a subsequent step, we might try to nuke it again
608          * from AtEOXact_Parallel or AtEOSubXact_Parallel.
609          */
610         dlist_delete(&pcxt->node);
611
612         /* Kill each worker in turn, and forget their error queues. */
613         if (pcxt->worker != NULL)
614         {
615                 for (i = 0; i < pcxt->nworkers_launched; ++i)
616                 {
617                         if (pcxt->worker[i].error_mqh != NULL)
618                         {
619                                 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
620
621                                 pfree(pcxt->worker[i].error_mqh);
622                                 pcxt->worker[i].error_mqh = NULL;
623                         }
624                 }
625         }
626
627         /*
628          * If we have allocated a shared memory segment, detach it.  This will
629          * implicitly detach the error queues, and any other shared memory queues,
630          * stored there.
631          */
632         if (pcxt->seg != NULL)
633         {
634                 dsm_detach(pcxt->seg);
635                 pcxt->seg = NULL;
636         }
637
638         /*
639          * If this parallel context is actually in backend-private memory rather
640          * than shared memory, free that memory instead.
641          */
642         if (pcxt->private_memory != NULL)
643         {
644                 pfree(pcxt->private_memory);
645                 pcxt->private_memory = NULL;
646         }
647
648         /*
649          * We can't finish transaction commit or abort until all of the workers
650          * have exited.  This means, in particular, that we can't respond to
651          * interrupts at this stage.
652          */
653         HOLD_INTERRUPTS();
654         WaitForParallelWorkersToExit(pcxt);
655         RESUME_INTERRUPTS();
656
657         /* Free the worker array itself. */
658         if (pcxt->worker != NULL)
659         {
660                 pfree(pcxt->worker);
661                 pcxt->worker = NULL;
662         }
663
664         /* Free memory. */
665         pfree(pcxt);
666 }
667
668 /*
669  * Are there any parallel contexts currently active?
670  */
671 bool
672 ParallelContextActive(void)
673 {
674         return !dlist_is_empty(&pcxt_list);
675 }
676
677 /*
678  * Handle receipt of an interrupt indicating a parallel worker message.
679  */
680 void
681 HandleParallelMessageInterrupt(void)
682 {
683         int                     save_errno = errno;
684
685         InterruptPending = true;
686         ParallelMessagePending = true;
687         SetLatch(MyLatch);
688
689         errno = save_errno;
690 }
691
692 /*
693  * Handle any queued protocol messages received from parallel workers.
694  */
695 void
696 HandleParallelMessages(void)
697 {
698         dlist_iter      iter;
699
700         ParallelMessagePending = false;
701
702         dlist_foreach(iter, &pcxt_list)
703         {
704                 ParallelContext *pcxt;
705                 int                     i;
706                 Size            nbytes;
707                 void       *data;
708
709                 pcxt = dlist_container(ParallelContext, node, iter.cur);
710                 if (pcxt->worker == NULL)
711                         continue;
712
713                 for (i = 0; i < pcxt->nworkers_launched; ++i)
714                 {
715                         /*
716                          * Read as many messages as we can from each worker, but stop when
717                          * either (1) the error queue goes away, which can happen if we
718                          * receive a Terminate message from the worker; or (2) no more
719                          * messages can be read from the worker without blocking.
720                          */
721                         while (pcxt->worker[i].error_mqh != NULL)
722                         {
723                                 shm_mq_result res;
724
725                                 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
726                                                                          &data, true);
727                                 if (res == SHM_MQ_WOULD_BLOCK)
728                                         break;
729                                 else if (res == SHM_MQ_SUCCESS)
730                                 {
731                                         StringInfoData msg;
732
733                                         initStringInfo(&msg);
734                                         appendBinaryStringInfo(&msg, data, nbytes);
735                                         HandleParallelMessage(pcxt, i, &msg);
736                                         pfree(msg.data);
737                                 }
738                                 else
739                                         ereport(ERROR,
740                                                         (errcode(ERRCODE_INTERNAL_ERROR),       /* XXX: wrong errcode? */
741                                                          errmsg("lost connection to parallel worker")));
742
743                                 /* This might make the error queue go away. */
744                                 CHECK_FOR_INTERRUPTS();
745                         }
746                 }
747         }
748 }
749
750 /*
751  * Handle a single protocol message received from a single parallel worker.
752  */
753 static void
754 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
755 {
756         char            msgtype;
757
758         msgtype = pq_getmsgbyte(msg);
759
760         switch (msgtype)
761         {
762                 case 'K':                               /* BackendKeyData */
763                         {
764                                 int32           pid = pq_getmsgint(msg, 4);
765
766                                 (void) pq_getmsgint(msg, 4);    /* discard cancel key */
767                                 (void) pq_getmsgend(msg);
768                                 pcxt->worker[i].pid = pid;
769                                 break;
770                         }
771
772                 case 'E':                               /* ErrorResponse */
773                 case 'N':                               /* NoticeResponse */
774                         {
775                                 ErrorData       edata;
776                                 ErrorContextCallback errctx;
777                                 ErrorContextCallback *save_error_context_stack;
778
779                                 /*
780                                  * Rethrow the error using the error context callbacks that
781                                  * were in effect when the context was created, not the
782                                  * current ones.
783                                  */
784                                 save_error_context_stack = error_context_stack;
785                                 errctx.callback = ParallelErrorContext;
786                                 errctx.arg = &pcxt->worker[i].pid;
787                                 errctx.previous = pcxt->error_context_stack;
788                                 error_context_stack = &errctx;
789
790                                 /* Parse ErrorResponse or NoticeResponse. */
791                                 pq_parse_errornotice(msg, &edata);
792
793                                 /* Death of a worker isn't enough justification for suicide. */
794                                 edata.elevel = Min(edata.elevel, ERROR);
795
796                                 /* Rethrow error or notice. */
797                                 ThrowErrorData(&edata);
798
799                                 /* Restore previous context. */
800                                 error_context_stack = save_error_context_stack;
801
802                                 break;
803                         }
804
805                 case 'A':                               /* NotifyResponse */
806                         {
807                                 /* Propagate NotifyResponse. */
808                                 pq_putmessage(msg->data[0], &msg->data[1], msg->len - 1);
809                                 break;
810                         }
811
812                 case 'X':                               /* Terminate, indicating clean exit */
813                         {
814                                 pfree(pcxt->worker[i].error_mqh);
815                                 pcxt->worker[i].error_mqh = NULL;
816                                 break;
817                         }
818
819                 default:
820                         {
821                                 elog(ERROR, "unknown message type: %c (%d bytes)",
822                                          msgtype, msg->len);
823                         }
824         }
825 }
826
827 /*
828  * End-of-subtransaction cleanup for parallel contexts.
829  *
830  * Currently, it's forbidden to enter or leave a subtransaction while
831  * parallel mode is in effect, so we could just blow away everything.  But
832  * we may want to relax that restriction in the future, so this code
833  * contemplates that there may be multiple subtransaction IDs in pcxt_list.
834  */
835 void
836 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
837 {
838         while (!dlist_is_empty(&pcxt_list))
839         {
840                 ParallelContext *pcxt;
841
842                 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
843                 if (pcxt->subid != mySubId)
844                         break;
845                 if (isCommit)
846                         elog(WARNING, "leaked parallel context");
847                 DestroyParallelContext(pcxt);
848         }
849 }
850
851 /*
852  * End-of-transaction cleanup for parallel contexts.
853  */
854 void
855 AtEOXact_Parallel(bool isCommit)
856 {
857         while (!dlist_is_empty(&pcxt_list))
858         {
859                 ParallelContext *pcxt;
860
861                 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
862                 if (isCommit)
863                         elog(WARNING, "leaked parallel context");
864                 DestroyParallelContext(pcxt);
865         }
866 }
867
868 /*
869  * Main entrypoint for parallel workers.
870  */
871 static void
872 ParallelWorkerMain(Datum main_arg)
873 {
874         dsm_segment *seg;
875         shm_toc    *toc;
876         FixedParallelState *fps;
877         char       *error_queue_space;
878         shm_mq     *mq;
879         shm_mq_handle *mqh;
880         char       *libraryspace;
881         char       *gucspace;
882         char       *combocidspace;
883         char       *tsnapspace;
884         char       *asnapspace;
885         char       *tstatespace;
886         StringInfoData msgbuf;
887
888         /* Set flag to indicate that we're initializing a parallel worker. */
889         InitializingParallelWorker = true;
890
891         /* Establish signal handlers. */
892         pqsignal(SIGTERM, die);
893         BackgroundWorkerUnblockSignals();
894
895         /* Determine and set our parallel worker number. */
896         Assert(ParallelWorkerNumber == -1);
897         memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
898
899         /* Set up a memory context and resource owner. */
900         Assert(CurrentResourceOwner == NULL);
901         CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
902         CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
903                                                                                                  "parallel worker",
904                                                                                                  ALLOCSET_DEFAULT_MINSIZE,
905                                                                                                  ALLOCSET_DEFAULT_INITSIZE,
906                                                                                                  ALLOCSET_DEFAULT_MAXSIZE);
907
908         /*
909          * Now that we have a resource owner, we can attach to the dynamic shared
910          * memory segment and read the table of contents.
911          */
912         seg = dsm_attach(DatumGetUInt32(main_arg));
913         if (seg == NULL)
914                 ereport(ERROR,
915                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
916                                  errmsg("could not map dynamic shared memory segment")));
917         toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
918         if (toc == NULL)
919                 ereport(ERROR,
920                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
921                    errmsg("invalid magic number in dynamic shared memory segment")));
922
923         /* Look up fixed parallel state. */
924         fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
925         Assert(fps != NULL);
926         MyFixedParallelState = fps;
927
928         /*
929          * Now that we have a worker number, we can find and attach to the error
930          * queue provided for us.  That's good, because until we do that, any
931          * errors that happen here will not be reported back to the process that
932          * requested that this worker be launched.
933          */
934         error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
935         mq = (shm_mq *) (error_queue_space +
936                                          ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
937         shm_mq_set_sender(mq, MyProc);
938         mqh = shm_mq_attach(mq, seg, NULL);
939         pq_redirect_to_shm_mq(seg, mqh);
940         pq_set_parallel_master(fps->parallel_master_pid,
941                                                    fps->parallel_master_backend_id);
942
943         /*
944          * Send a BackendKeyData message to the process that initiated parallelism
945          * so that it has access to our PID before it receives any other messages
946          * from us.  Our cancel key is sent, too, since that's the way the
947          * protocol message is defined, but it won't actually be used for anything
948          * in this case.
949          */
950         pq_beginmessage(&msgbuf, 'K');
951         pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
952         pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
953         pq_endmessage(&msgbuf);
954
955         /*
956          * Hooray! Primary initialization is complete.  Now, we need to set up our
957          * backend-local state to match the original backend.
958          */
959
960         /*
961          * Join locking group.  We must do this before anything that could try to
962          * acquire a heavyweight lock, because any heavyweight locks acquired to
963          * this point could block either directly against the parallel group
964          * leader or against some process which in turn waits for a lock that
965          * conflicts with the parallel group leader, causing an undetected
966          * deadlock.  (If we can't join the lock group, the leader has gone away,
967          * so just exit quietly.)
968          */
969         if (!BecomeLockGroupMember(fps->parallel_master_pgproc,
970                                                            fps->parallel_master_pid))
971                 return;
972
973         /*
974          * Load libraries that were loaded by original backend.  We want to do
975          * this before restoring GUCs, because the libraries might define custom
976          * variables.
977          */
978         libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
979         Assert(libraryspace != NULL);
980         RestoreLibraryState(libraryspace);
981
982         /* Restore database connection. */
983         BackgroundWorkerInitializeConnectionByOid(fps->database_id,
984                                                                                           fps->authenticated_user_id);
985
986         /* Restore GUC values from launching backend. */
987         gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
988         Assert(gucspace != NULL);
989         StartTransactionCommand();
990         RestoreGUCState(gucspace);
991         CommitTransactionCommand();
992
993         /* Crank up a transaction state appropriate to a parallel worker. */
994         tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
995         StartParallelWorkerTransaction(tstatespace);
996
997         /* Restore combo CID state. */
998         combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
999         Assert(combocidspace != NULL);
1000         RestoreComboCIDState(combocidspace);
1001
1002         /* Restore transaction snapshot. */
1003         tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
1004         Assert(tsnapspace != NULL);
1005         RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
1006                                                            fps->parallel_master_pgproc);
1007
1008         /* Restore active snapshot. */
1009         asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1010         Assert(asnapspace != NULL);
1011         PushActiveSnapshot(RestoreSnapshot(asnapspace));
1012
1013         /*
1014          * We've changed which tuples we can see, and must therefore invalidate
1015          * system caches.
1016          */
1017         InvalidateSystemCaches();
1018
1019         /* Restore user ID and security context. */
1020         SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1021
1022         /*
1023          * We've initialized all of our state now; nothing should change
1024          * hereafter.
1025          */
1026         InitializingParallelWorker = false;
1027         EnterParallelMode();
1028
1029         /*
1030          * Time to do the real work: invoke the caller-supplied code.
1031          *
1032          * If you get a crash at this line, see the comments for
1033          * ParallelExtensionTrampoline.
1034          */
1035         fps->entrypoint(seg, toc);
1036
1037         /* Must exit parallel mode to pop active snapshot. */
1038         ExitParallelMode();
1039
1040         /* Must pop active snapshot so resowner.c doesn't complain. */
1041         PopActiveSnapshot();
1042
1043         /* Shut down the parallel-worker transaction. */
1044         EndParallelWorkerTransaction();
1045
1046         /* Report success. */
1047         pq_putmessage('X', NULL, 0);
1048 }
1049
1050 /*
1051  * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1052  * function living in a dynamically loaded module, because the module might
1053  * not be loaded in every process, or might be loaded but not at the same
1054  * address.  To work around that problem, CreateParallelContextForExtension()
1055  * arranges to call this function rather than calling the extension-provided
1056  * function directly; and this function then looks up the real entrypoint and
1057  * calls it.
1058  */
1059 static void
1060 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1061 {
1062         char       *extensionstate;
1063         char       *library_name;
1064         char       *function_name;
1065         parallel_worker_main_type entrypt;
1066
1067         extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1068         Assert(extensionstate != NULL);
1069         library_name = extensionstate;
1070         function_name = extensionstate + strlen(library_name) + 1;
1071
1072         entrypt = (parallel_worker_main_type)
1073                 load_external_function(library_name, function_name, true, NULL);
1074         entrypt(seg, toc);
1075 }
1076
1077 /*
1078  * Give the user a hint that this is a message propagated from a parallel
1079  * worker.  Otherwise, it can sometimes be confusing to understand what
1080  * actually happened.
1081  */
1082 static void
1083 ParallelErrorContext(void *arg)
1084 {
1085         if (force_parallel_mode != FORCE_PARALLEL_REGRESS)
1086                 errcontext("parallel worker, PID %d", *(int32 *) arg);
1087 }
1088
1089 /*
1090  * Update shared memory with the ending location of the last WAL record we
1091  * wrote, if it's greater than the value already stored there.
1092  */
1093 void
1094 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1095 {
1096         FixedParallelState *fps = MyFixedParallelState;
1097
1098         Assert(fps != NULL);
1099         SpinLockAcquire(&fps->mutex);
1100         if (fps->last_xlog_end < last_xlog_end)
1101                 fps->last_xlog_end = last_xlog_end;
1102         SpinLockRelease(&fps->mutex);
1103 }