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