PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parallel.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parallel.c
4  * Infrastructure for launching parallel workers
5  *
6  * Portions Copyright (c) 1996-2017, 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/session.h"
19 #include "access/xact.h"
20 #include "access/xlog.h"
21 #include "catalog/namespace.h"
22 #include "commands/async.h"
23 #include "executor/execParallel.h"
24 #include "libpq/libpq.h"
25 #include "libpq/pqformat.h"
26 #include "libpq/pqmq.h"
27 #include "miscadmin.h"
28 #include "optimizer/planmain.h"
29 #include "pgstat.h"
30 #include "storage/ipc.h"
31 #include "storage/sinval.h"
32 #include "storage/spin.h"
33 #include "tcop/tcopprot.h"
34 #include "utils/combocid.h"
35 #include "utils/guc.h"
36 #include "utils/inval.h"
37 #include "utils/memutils.h"
38 #include "utils/resowner.h"
39 #include "utils/snapmgr.h"
40 #include "utils/typcache.h"
41 
42 
43 /*
44  * We don't want to waste a lot of memory on an error queue which, most of
45  * the time, will process only a handful of small messages. However, it is
46  * desirable to make it large enough that a typical ErrorResponse can be sent
47  * without blocking. That way, a worker that errors out can write the whole
48  * message into the queue and terminate without waiting for the user backend.
49  */
50 #define PARALLEL_ERROR_QUEUE_SIZE 16384
51 
52 /* Magic number for parallel context TOC. */
53 #define PARALLEL_MAGIC 0x50477c7c
54 
55 /*
56  * Magic numbers for per-context parallel state sharing. Higher-level code
57  * should use smaller values, leaving these very large ones for use by this
58  * module.
59  */
60 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
61 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
62 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
63 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
64 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
65 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
66 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
67 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
68 #define PARALLEL_KEY_ENTRYPOINT UINT64CONST(0xFFFFFFFFFFFF0009)
69 #define PARALLEL_KEY_SESSION_DSM UINT64CONST(0xFFFFFFFFFFFF000A)
70 
71 /* Fixed-size parallel state. */
72 typedef struct FixedParallelState
73 {
74  /* Fixed-size state that workers must restore. */
84 
85  /* Mutex protects remaining fields. */
87 
88  /* Maximum XactLastRecEnd of any worker. */
91 
92 /*
93  * Our parallel worker number. We initialize this to -1, meaning that we are
94  * not a parallel worker. In parallel workers, it will be set to a value >= 0
95  * and < the number of workers before any user code is invoked; each parallel
96  * worker will get a different parallel worker number.
97  */
99 
100 /* Is there a parallel message pending which we need to receive? */
101 volatile bool ParallelMessagePending = false;
102 
103 /* Are we initializing a parallel worker? */
105 
106 /* Pointer to our fixed parallel state. */
108 
109 /* List of active parallel contexts. */
111 
112 /*
113  * List of internal parallel worker entry points. We need this for
114  * reasons explained in LookupParallelWorkerFunction(), below.
115  */
116 static const struct
117 {
118  const char *fn_name;
121 
122 {
123  {
124  "ParallelQueryMain", ParallelQueryMain
125  }
126 };
127 
128 /* Private functions. */
129 static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg);
131 static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname);
132 
133 
134 /*
135  * Establish a new parallel context. This should be done after entering
136  * parallel mode, and (unless there is an error) the context should be
137  * destroyed before exiting the current subtransaction.
138  */
140 CreateParallelContext(const char *library_name, const char *function_name,
141  int nworkers)
142 {
143  MemoryContext oldcontext;
144  ParallelContext *pcxt;
145 
146  /* It is unsafe to create a parallel context if not in parallel mode. */
148 
149  /* Number of workers should be non-negative. */
150  Assert(nworkers >= 0);
151 
152  /*
153  * If dynamic shared memory is not available, we won't be able to use
154  * background workers.
155  */
157  nworkers = 0;
158 
159  /*
160  * If we are running under serializable isolation, we can't use parallel
161  * workers, at least not until somebody enhances that mechanism to be
162  * parallel-aware.
163  */
165  nworkers = 0;
166 
167  /* We might be running in a short-lived memory context. */
169 
170  /* Initialize a new ParallelContext. */
171  pcxt = palloc0(sizeof(ParallelContext));
173  pcxt->nworkers = nworkers;
174  pcxt->library_name = pstrdup(library_name);
175  pcxt->function_name = pstrdup(function_name);
178  dlist_push_head(&pcxt_list, &pcxt->node);
179 
180  /* Restore previous memory context. */
181  MemoryContextSwitchTo(oldcontext);
182 
183  return pcxt;
184 }
185 
186 /*
187  * Establish the dynamic shared memory segment for a parallel context and
188  * copy state and other bookkeeping information that will be needed by
189  * parallel workers into it.
190  */
191 void
193 {
194  MemoryContext oldcontext;
195  Size library_len = 0;
196  Size guc_len = 0;
197  Size combocidlen = 0;
198  Size tsnaplen = 0;
199  Size asnaplen = 0;
200  Size tstatelen = 0;
201  Size segsize = 0;
202  int i;
203  FixedParallelState *fps;
204  dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
205  Snapshot transaction_snapshot = GetTransactionSnapshot();
206  Snapshot active_snapshot = GetActiveSnapshot();
207 
208  /* We might be running in a very short-lived memory context. */
210 
211  /* Allow space to store the fixed-size parallel state. */
213  shm_toc_estimate_keys(&pcxt->estimator, 1);
214 
215  /*
216  * Normally, the user will have requested at least one worker process, but
217  * if by chance they have not, we can skip a bunch of things here.
218  */
219  if (pcxt->nworkers > 0)
220  {
221  /* Get (or create) the per-session DSM segment's handle. */
222  session_dsm_handle = GetSessionDsmHandle();
223 
224  /*
225  * If we weren't able to create a per-session DSM segment, then we can
226  * continue but we can't safely launch any workers because their
227  * record typmods would be incompatible so they couldn't exchange
228  * tuples.
229  */
230  if (session_dsm_handle == DSM_HANDLE_INVALID)
231  pcxt->nworkers = 0;
232  }
233 
234  if (pcxt->nworkers > 0)
235  {
236  /* Estimate space for various kinds of state sharing. */
237  library_len = EstimateLibraryStateSpace();
238  shm_toc_estimate_chunk(&pcxt->estimator, library_len);
239  guc_len = EstimateGUCStateSpace();
240  shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
241  combocidlen = EstimateComboCIDStateSpace();
242  shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
243  tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
244  shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
245  asnaplen = EstimateSnapshotSpace(active_snapshot);
246  shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
247  tstatelen = EstimateTransactionStateSpace();
248  shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
250  /* If you add more chunks here, you probably need to add keys. */
251  shm_toc_estimate_keys(&pcxt->estimator, 7);
252 
253  /* Estimate space need for error queues. */
256  "parallel error queue size not buffer-aligned");
259  pcxt->nworkers));
260  shm_toc_estimate_keys(&pcxt->estimator, 1);
261 
262  /* Estimate how much we'll need for the entrypoint info. */
263  shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
264  strlen(pcxt->function_name) + 2);
265  shm_toc_estimate_keys(&pcxt->estimator, 1);
266  }
267 
268  /*
269  * Create DSM and initialize with new table of contents. But if the user
270  * didn't request any workers, then don't bother creating a dynamic shared
271  * memory segment; instead, just use backend-private memory.
272  *
273  * Also, if we can't create a dynamic shared memory segment because the
274  * maximum number of segments have already been created, then fall back to
275  * backend-private memory, and plan not to use any workers. We hope this
276  * won't happen very often, but it's better to abandon the use of
277  * parallelism than to fail outright.
278  */
279  segsize = shm_toc_estimate(&pcxt->estimator);
280  if (pcxt->nworkers > 0)
282  if (pcxt->seg != NULL)
284  dsm_segment_address(pcxt->seg),
285  segsize);
286  else
287  {
288  pcxt->nworkers = 0;
291  segsize);
292  }
293 
294  /* Initialize fixed-size state in shared memory. */
295  fps = (FixedParallelState *)
296  shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
297  fps->database_id = MyDatabaseId;
305  SpinLockInit(&fps->mutex);
306  fps->last_xlog_end = 0;
308 
309  /* We can skip the rest of this if we're not budgeting for any workers. */
310  if (pcxt->nworkers > 0)
311  {
312  char *libraryspace;
313  char *gucspace;
314  char *combocidspace;
315  char *tsnapspace;
316  char *asnapspace;
317  char *tstatespace;
318  char *error_queue_space;
319  char *session_dsm_handle_space;
320  char *entrypointstate;
321  Size lnamelen;
322 
323  /* Serialize shared libraries we have loaded. */
324  libraryspace = shm_toc_allocate(pcxt->toc, library_len);
325  SerializeLibraryState(library_len, libraryspace);
326  shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
327 
328  /* Serialize GUC settings. */
329  gucspace = shm_toc_allocate(pcxt->toc, guc_len);
330  SerializeGUCState(guc_len, gucspace);
331  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
332 
333  /* Serialize combo CID state. */
334  combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
335  SerializeComboCIDState(combocidlen, combocidspace);
336  shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
337 
338  /* Serialize transaction snapshot and active snapshot. */
339  tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
340  SerializeSnapshot(transaction_snapshot, tsnapspace);
342  tsnapspace);
343  asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
344  SerializeSnapshot(active_snapshot, asnapspace);
345  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
346 
347  /* Provide the handle for per-session segment. */
348  session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
349  sizeof(dsm_handle));
350  *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
352  session_dsm_handle_space);
353 
354  /* Serialize transaction state. */
355  tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
356  SerializeTransactionState(tstatelen, tstatespace);
358 
359  /* Allocate space for worker information. */
360  pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
361 
362  /*
363  * Establish error queues in dynamic shared memory.
364  *
365  * These queues should be used only for transmitting ErrorResponse,
366  * NoticeResponse, and NotifyResponse protocol messages. Tuple data
367  * should be transmitted via separate (possibly larger?) queues.
368  */
369  error_queue_space =
370  shm_toc_allocate(pcxt->toc,
372  pcxt->nworkers));
373  for (i = 0; i < pcxt->nworkers; ++i)
374  {
375  char *start;
376  shm_mq *mq;
377 
378  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
379  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
381  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
382  }
383  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
384 
385  /*
386  * Serialize entrypoint information. It's unsafe to pass function
387  * pointers across processes, as the function pointer may be different
388  * in each process in EXEC_BACKEND builds, so we always pass library
389  * and function name. (We use library name "postgres" for functions
390  * in the core backend.)
391  */
392  lnamelen = strlen(pcxt->library_name);
393  entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
394  strlen(pcxt->function_name) + 2);
395  strcpy(entrypointstate, pcxt->library_name);
396  strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
397  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
398  }
399 
400  /* Restore previous memory context. */
401  MemoryContextSwitchTo(oldcontext);
402 }
403 
404 /*
405  * Reinitialize the dynamic shared memory segment for a parallel context such
406  * that we could launch workers for it again.
407  */
408 void
410 {
411  FixedParallelState *fps;
412  char *error_queue_space;
413  int i;
414 
415  /* Wait for any old workers to exit. */
416  if (pcxt->nworkers_launched > 0)
417  {
420  pcxt->nworkers_launched = 0;
421  }
422 
423  /* Reset a few bits of fixed parallel state to a clean state. */
424  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
425  fps->last_xlog_end = 0;
426 
427  /* Recreate error queues. */
428  error_queue_space =
430  for (i = 0; i < pcxt->nworkers; ++i)
431  {
432  char *start;
433  shm_mq *mq;
434 
435  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
436  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
438  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
439  }
440 }
441 
442 /*
443  * Launch parallel workers.
444  */
445 void
447 {
448  MemoryContext oldcontext;
449  BackgroundWorker worker;
450  int i;
451  bool any_registrations_failed = false;
452 
453  /* Skip this if we have no workers. */
454  if (pcxt->nworkers == 0)
455  return;
456 
457  /* We need to be a lock group leader. */
459 
460  /* If we do have workers, we'd better have a DSM segment. */
461  Assert(pcxt->seg != NULL);
462 
463  /* We might be running in a short-lived memory context. */
465 
466  /* Configure a worker. */
467  memset(&worker, 0, sizeof(worker));
468  snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
469  MyProcPid);
470  snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
471  worker.bgw_flags =
476  sprintf(worker.bgw_library_name, "postgres");
477  sprintf(worker.bgw_function_name, "ParallelWorkerMain");
479  worker.bgw_notify_pid = MyProcPid;
480 
481  /*
482  * Start workers.
483  *
484  * The caller must be able to tolerate ending up with fewer workers than
485  * expected, so there is no need to throw an error here if registration
486  * fails. It wouldn't help much anyway, because registering the worker in
487  * no way guarantees that it will start up and initialize successfully.
488  */
489  for (i = 0; i < pcxt->nworkers; ++i)
490  {
491  memcpy(worker.bgw_extra, &i, sizeof(int));
492  if (!any_registrations_failed &&
494  &pcxt->worker[i].bgwhandle))
495  {
497  pcxt->worker[i].bgwhandle);
498  pcxt->nworkers_launched++;
499  }
500  else
501  {
502  /*
503  * If we weren't able to register the worker, then we've bumped up
504  * against the max_worker_processes limit, and future
505  * registrations will probably fail too, so arrange to skip them.
506  * But we still have to execute this code for the remaining slots
507  * to make sure that we forget about the error queues we budgeted
508  * for those workers. Otherwise, we'll wait for them to start,
509  * but they never will.
510  */
511  any_registrations_failed = true;
512  pcxt->worker[i].bgwhandle = NULL;
513  shm_mq_detach(pcxt->worker[i].error_mqh);
514  pcxt->worker[i].error_mqh = NULL;
515  }
516  }
517 
518  /* Restore previous memory context. */
519  MemoryContextSwitchTo(oldcontext);
520 }
521 
522 /*
523  * Wait for all workers to finish computing.
524  *
525  * Even if the parallel operation seems to have completed successfully, it's
526  * important to call this function afterwards. We must not miss any errors
527  * the workers may have thrown during the parallel operation, or any that they
528  * may yet throw while shutting down.
529  *
530  * Also, we want to update our notion of XactLastRecEnd based on worker
531  * feedback.
532  */
533 void
535 {
536  for (;;)
537  {
538  bool anyone_alive = false;
539  int i;
540 
541  /*
542  * This will process any parallel messages that are pending, which may
543  * change the outcome of the loop that follows. It may also throw an
544  * error propagated from a worker.
545  */
547 
548  for (i = 0; i < pcxt->nworkers_launched; ++i)
549  {
550  if (pcxt->worker[i].error_mqh != NULL)
551  {
552  anyone_alive = true;
553  break;
554  }
555  }
556 
557  if (!anyone_alive)
558  break;
559 
563  }
564 
565  if (pcxt->toc != NULL)
566  {
567  FixedParallelState *fps;
568 
569  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
570  if (fps->last_xlog_end > XactLastRecEnd)
572  }
573 }
574 
575 /*
576  * Wait for all workers to exit.
577  *
578  * This function ensures that workers have been completely shutdown. The
579  * difference between WaitForParallelWorkersToFinish and this function is
580  * that former just ensures that last message sent by worker backend is
581  * received by master backend whereas this ensures the complete shutdown.
582  */
583 static void
585 {
586  int i;
587 
588  /* Wait until the workers actually die. */
589  for (i = 0; i < pcxt->nworkers_launched; ++i)
590  {
592 
593  if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
594  continue;
595 
597 
598  /*
599  * If the postmaster kicked the bucket, we have no chance of cleaning
600  * up safely -- we won't be able to tell when our workers are actually
601  * dead. This doesn't necessitate a PANIC since they will all abort
602  * eventually, but we can't safely continue this session.
603  */
604  if (status == BGWH_POSTMASTER_DIED)
605  ereport(FATAL,
606  (errcode(ERRCODE_ADMIN_SHUTDOWN),
607  errmsg("postmaster exited during a parallel transaction")));
608 
609  /* Release memory. */
610  pfree(pcxt->worker[i].bgwhandle);
611  pcxt->worker[i].bgwhandle = NULL;
612  }
613 }
614 
615 /*
616  * Destroy a parallel context.
617  *
618  * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
619  * first, before calling this function. When this function is invoked, any
620  * remaining workers are forcibly killed; the dynamic shared memory segment
621  * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
622  */
623 void
625 {
626  int i;
627 
628  /*
629  * Be careful about order of operations here! We remove the parallel
630  * context from the list before we do anything else; otherwise, if an
631  * error occurs during a subsequent step, we might try to nuke it again
632  * from AtEOXact_Parallel or AtEOSubXact_Parallel.
633  */
634  dlist_delete(&pcxt->node);
635 
636  /* Kill each worker in turn, and forget their error queues. */
637  if (pcxt->worker != NULL)
638  {
639  for (i = 0; i < pcxt->nworkers_launched; ++i)
640  {
641  if (pcxt->worker[i].error_mqh != NULL)
642  {
644 
645  shm_mq_detach(pcxt->worker[i].error_mqh);
646  pcxt->worker[i].error_mqh = NULL;
647  }
648  }
649  }
650 
651  /*
652  * If we have allocated a shared memory segment, detach it. This will
653  * implicitly detach the error queues, and any other shared memory queues,
654  * stored there.
655  */
656  if (pcxt->seg != NULL)
657  {
658  dsm_detach(pcxt->seg);
659  pcxt->seg = NULL;
660  }
661 
662  /*
663  * If this parallel context is actually in backend-private memory rather
664  * than shared memory, free that memory instead.
665  */
666  if (pcxt->private_memory != NULL)
667  {
668  pfree(pcxt->private_memory);
669  pcxt->private_memory = NULL;
670  }
671 
672  /*
673  * We can't finish transaction commit or abort until all of the workers
674  * have exited. This means, in particular, that we can't respond to
675  * interrupts at this stage.
676  */
677  HOLD_INTERRUPTS();
680 
681  /* Free the worker array itself. */
682  if (pcxt->worker != NULL)
683  {
684  pfree(pcxt->worker);
685  pcxt->worker = NULL;
686  }
687 
688  /* Free memory. */
689  pfree(pcxt->library_name);
690  pfree(pcxt->function_name);
691  pfree(pcxt);
692 }
693 
694 /*
695  * Are there any parallel contexts currently active?
696  */
697 bool
699 {
700  return !dlist_is_empty(&pcxt_list);
701 }
702 
703 /*
704  * Handle receipt of an interrupt indicating a parallel worker message.
705  *
706  * Note: this is called within a signal handler! All we can do is set
707  * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
708  * HandleParallelMessages().
709  */
710 void
712 {
713  InterruptPending = true;
714  ParallelMessagePending = true;
715  SetLatch(MyLatch);
716 }
717 
718 /*
719  * Handle any queued protocol messages received from parallel workers.
720  */
721 void
723 {
724  dlist_iter iter;
725  MemoryContext oldcontext;
726 
727  static MemoryContext hpm_context = NULL;
728 
729  /*
730  * This is invoked from ProcessInterrupts(), and since some of the
731  * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
732  * for recursive calls if more signals are received while this runs. It's
733  * unclear that recursive entry would be safe, and it doesn't seem useful
734  * even if it is safe, so let's block interrupts until done.
735  */
736  HOLD_INTERRUPTS();
737 
738  /*
739  * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
740  * don't want to risk leaking data into long-lived contexts, so let's do
741  * our work here in a private context that we can reset on each use.
742  */
743  if (hpm_context == NULL) /* first time through? */
745  "HandleParallelMessages",
747  else
748  MemoryContextReset(hpm_context);
749 
750  oldcontext = MemoryContextSwitchTo(hpm_context);
751 
752  /* OK to process messages. Reset the flag saying there are more to do. */
753  ParallelMessagePending = false;
754 
755  dlist_foreach(iter, &pcxt_list)
756  {
757  ParallelContext *pcxt;
758  int i;
759 
760  pcxt = dlist_container(ParallelContext, node, iter.cur);
761  if (pcxt->worker == NULL)
762  continue;
763 
764  for (i = 0; i < pcxt->nworkers_launched; ++i)
765  {
766  /*
767  * Read as many messages as we can from each worker, but stop when
768  * either (1) the worker's error queue goes away, which can happen
769  * if we receive a Terminate message from the worker; or (2) no
770  * more messages can be read from the worker without blocking.
771  */
772  while (pcxt->worker[i].error_mqh != NULL)
773  {
774  shm_mq_result res;
775  Size nbytes;
776  void *data;
777 
778  res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
779  &data, true);
780  if (res == SHM_MQ_WOULD_BLOCK)
781  break;
782  else if (res == SHM_MQ_SUCCESS)
783  {
784  StringInfoData msg;
785 
786  initStringInfo(&msg);
787  appendBinaryStringInfo(&msg, data, nbytes);
788  HandleParallelMessage(pcxt, i, &msg);
789  pfree(msg.data);
790  }
791  else
792  ereport(ERROR,
793  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
794  errmsg("lost connection to parallel worker")));
795  }
796  }
797  }
798 
799  MemoryContextSwitchTo(oldcontext);
800 
801  /* Might as well clear the context on our way out */
802  MemoryContextReset(hpm_context);
803 
805 }
806 
807 /*
808  * Handle a single protocol message received from a single parallel worker.
809  */
810 static void
812 {
813  char msgtype;
814 
815  msgtype = pq_getmsgbyte(msg);
816 
817  switch (msgtype)
818  {
819  case 'K': /* BackendKeyData */
820  {
821  int32 pid = pq_getmsgint(msg, 4);
822 
823  (void) pq_getmsgint(msg, 4); /* discard cancel key */
824  (void) pq_getmsgend(msg);
825  pcxt->worker[i].pid = pid;
826  break;
827  }
828 
829  case 'E': /* ErrorResponse */
830  case 'N': /* NoticeResponse */
831  {
832  ErrorData edata;
833  ErrorContextCallback *save_error_context_stack;
834 
835  /* Parse ErrorResponse or NoticeResponse. */
836  pq_parse_errornotice(msg, &edata);
837 
838  /* Death of a worker isn't enough justification for suicide. */
839  edata.elevel = Min(edata.elevel, ERROR);
840 
841  /*
842  * If desired, add a context line to show that this is a
843  * message propagated from a parallel worker. Otherwise, it
844  * can sometimes be confusing to understand what actually
845  * happened. (We don't do this in FORCE_PARALLEL_REGRESS mode
846  * because it causes test-result instability depending on
847  * whether a parallel worker is actually used or not.)
848  */
850  {
851  if (edata.context)
852  edata.context = psprintf("%s\n%s", edata.context,
853  _("parallel worker"));
854  else
855  edata.context = pstrdup(_("parallel worker"));
856  }
857 
858  /*
859  * Context beyond that should use the error context callbacks
860  * that were in effect when the ParallelContext was created,
861  * not the current ones.
862  */
863  save_error_context_stack = error_context_stack;
865 
866  /* Rethrow error or print notice. */
867  ThrowErrorData(&edata);
868 
869  /* Not an error, so restore previous context stack. */
870  error_context_stack = save_error_context_stack;
871 
872  break;
873  }
874 
875  case 'A': /* NotifyResponse */
876  {
877  /* Propagate NotifyResponse. */
878  int32 pid;
879  const char *channel;
880  const char *payload;
881 
882  pid = pq_getmsgint(msg, 4);
883  channel = pq_getmsgrawstring(msg);
884  payload = pq_getmsgrawstring(msg);
885  pq_endmessage(msg);
886 
887  NotifyMyFrontEnd(channel, payload, pid);
888 
889  break;
890  }
891 
892  case 'X': /* Terminate, indicating clean exit */
893  {
894  shm_mq_detach(pcxt->worker[i].error_mqh);
895  pcxt->worker[i].error_mqh = NULL;
896  break;
897  }
898 
899  default:
900  {
901  elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
902  msgtype, msg->len);
903  }
904  }
905 }
906 
907 /*
908  * End-of-subtransaction cleanup for parallel contexts.
909  *
910  * Currently, it's forbidden to enter or leave a subtransaction while
911  * parallel mode is in effect, so we could just blow away everything. But
912  * we may want to relax that restriction in the future, so this code
913  * contemplates that there may be multiple subtransaction IDs in pcxt_list.
914  */
915 void
916 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
917 {
918  while (!dlist_is_empty(&pcxt_list))
919  {
920  ParallelContext *pcxt;
921 
922  pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
923  if (pcxt->subid != mySubId)
924  break;
925  if (isCommit)
926  elog(WARNING, "leaked parallel context");
928  }
929 }
930 
931 /*
932  * End-of-transaction cleanup for parallel contexts.
933  */
934 void
935 AtEOXact_Parallel(bool isCommit)
936 {
937  while (!dlist_is_empty(&pcxt_list))
938  {
939  ParallelContext *pcxt;
940 
941  pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
942  if (isCommit)
943  elog(WARNING, "leaked parallel context");
945  }
946 }
947 
948 /*
949  * Main entrypoint for parallel workers.
950  */
951 void
953 {
954  dsm_segment *seg;
955  shm_toc *toc;
956  FixedParallelState *fps;
957  char *error_queue_space;
958  shm_mq *mq;
959  shm_mq_handle *mqh;
960  char *libraryspace;
961  char *entrypointstate;
962  char *library_name;
963  char *function_name;
965  char *gucspace;
966  char *combocidspace;
967  char *tsnapspace;
968  char *asnapspace;
969  char *tstatespace;
970  StringInfoData msgbuf;
971  char *session_dsm_handle_space;
972 
973  /* Set flag to indicate that we're initializing a parallel worker. */
975 
976  /* Establish signal handlers. */
977  pqsignal(SIGTERM, die);
979 
980  /* Determine and set our parallel worker number. */
982  memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
983 
984  /* Set up a memory context and resource owner. */
985  Assert(CurrentResourceOwner == NULL);
986  CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
988  "Parallel worker",
990 
991  /*
992  * Now that we have a resource owner, we can attach to the dynamic shared
993  * memory segment and read the table of contents.
994  */
995  seg = dsm_attach(DatumGetUInt32(main_arg));
996  if (seg == NULL)
997  ereport(ERROR,
998  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
999  errmsg("could not map dynamic shared memory segment")));
1001  if (toc == NULL)
1002  ereport(ERROR,
1003  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1004  errmsg("invalid magic number in dynamic shared memory segment")));
1005 
1006  /* Look up fixed parallel state. */
1007  fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1008  MyFixedParallelState = fps;
1009 
1010  /*
1011  * Now that we have a worker number, we can find and attach to the error
1012  * queue provided for us. That's good, because until we do that, any
1013  * errors that happen here will not be reported back to the process that
1014  * requested that this worker be launched.
1015  */
1016  error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1017  mq = (shm_mq *) (error_queue_space +
1020  mqh = shm_mq_attach(mq, seg, NULL);
1021  pq_redirect_to_shm_mq(seg, mqh);
1024 
1025  /*
1026  * Send a BackendKeyData message to the process that initiated parallelism
1027  * so that it has access to our PID before it receives any other messages
1028  * from us. Our cancel key is sent, too, since that's the way the
1029  * protocol message is defined, but it won't actually be used for anything
1030  * in this case.
1031  */
1032  pq_beginmessage(&msgbuf, 'K');
1033  pq_sendint32(&msgbuf, (int32) MyProcPid);
1034  pq_sendint32(&msgbuf, (int32) MyCancelKey);
1035  pq_endmessage(&msgbuf);
1036 
1037  /*
1038  * Hooray! Primary initialization is complete. Now, we need to set up our
1039  * backend-local state to match the original backend.
1040  */
1041 
1042  /*
1043  * Join locking group. We must do this before anything that could try to
1044  * acquire a heavyweight lock, because any heavyweight locks acquired to
1045  * this point could block either directly against the parallel group
1046  * leader or against some process which in turn waits for a lock that
1047  * conflicts with the parallel group leader, causing an undetected
1048  * deadlock. (If we can't join the lock group, the leader has gone away,
1049  * so just exit quietly.)
1050  */
1052  fps->parallel_master_pid))
1053  return;
1054 
1055  /*
1056  * Load libraries that were loaded by original backend. We want to do
1057  * this before restoring GUCs, because the libraries might define custom
1058  * variables.
1059  */
1060  libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1061  RestoreLibraryState(libraryspace);
1062 
1063  /*
1064  * Identify the entry point to be called. In theory this could result in
1065  * loading an additional library, though most likely the entry point is in
1066  * the core backend or in a library we just loaded.
1067  */
1068  entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1069  library_name = entrypointstate;
1070  function_name = entrypointstate + strlen(library_name) + 1;
1071 
1072  entrypt = LookupParallelWorkerFunction(library_name, function_name);
1073 
1074  /* Restore database connection. */
1076  fps->authenticated_user_id);
1077 
1078  /*
1079  * Set the client encoding to the database encoding, since that is what
1080  * the leader will expect.
1081  */
1083 
1084  /* Restore GUC values from launching backend. */
1085  gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1087  RestoreGUCState(gucspace);
1089 
1090  /* Crank up a transaction state appropriate to a parallel worker. */
1091  tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1092  StartParallelWorkerTransaction(tstatespace);
1093 
1094  /* Restore combo CID state. */
1095  combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1096  RestoreComboCIDState(combocidspace);
1097 
1098  /* Attach to the per-session DSM segment and contained objects. */
1099  session_dsm_handle_space =
1101  AttachSession(*(dsm_handle *) session_dsm_handle_space);
1102 
1103  /* Restore transaction snapshot. */
1104  tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, false);
1106  fps->parallel_master_pgproc);
1107 
1108  /* Restore active snapshot. */
1109  asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1110  PushActiveSnapshot(RestoreSnapshot(asnapspace));
1111 
1112  /*
1113  * We've changed which tuples we can see, and must therefore invalidate
1114  * system caches.
1115  */
1117 
1118  /* Restore user ID and security context. */
1120 
1121  /* Restore temp-namespace state to ensure search path matches leader's. */
1124 
1125  /* Set ParallelMasterBackendId so we know how to address temp relations. */
1127 
1128  /*
1129  * We've initialized all of our state now; nothing should change
1130  * hereafter.
1131  */
1134 
1135  /*
1136  * Time to do the real work: invoke the caller-supplied code.
1137  */
1138  entrypt(seg, toc);
1139 
1140  /* Must exit parallel mode to pop active snapshot. */
1141  ExitParallelMode();
1142 
1143  /* Must pop active snapshot so resowner.c doesn't complain. */
1145 
1146  /* Shut down the parallel-worker transaction. */
1148 
1149  /* Detach from the per-session DSM segment. */
1150  DetachSession();
1151 
1152  /* Report success. */
1153  pq_putmessage('X', NULL, 0);
1154 }
1155 
1156 /*
1157  * Update shared memory with the ending location of the last WAL record we
1158  * wrote, if it's greater than the value already stored there.
1159  */
1160 void
1162 {
1164 
1165  Assert(fps != NULL);
1166  SpinLockAcquire(&fps->mutex);
1167  if (fps->last_xlog_end < last_xlog_end)
1168  fps->last_xlog_end = last_xlog_end;
1169  SpinLockRelease(&fps->mutex);
1170 }
1171 
1172 /*
1173  * Look up (and possibly load) a parallel worker entry point function.
1174  *
1175  * For functions contained in the core code, we use library name "postgres"
1176  * and consult the InternalParallelWorkers array. External functions are
1177  * looked up, and loaded if necessary, using load_external_function().
1178  *
1179  * The point of this is to pass function names as strings across process
1180  * boundaries. We can't pass actual function addresses because of the
1181  * possibility that the function has been loaded at a different address
1182  * in a different process. This is obviously a hazard for functions in
1183  * loadable libraries, but it can happen even for functions in the core code
1184  * on platforms using EXEC_BACKEND (e.g., Windows).
1185  *
1186  * At some point it might be worthwhile to get rid of InternalParallelWorkers[]
1187  * in favor of applying load_external_function() for core functions too;
1188  * but that raises portability issues that are not worth addressing now.
1189  */
1191 LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
1192 {
1193  /*
1194  * If the function is to be loaded from postgres itself, search the
1195  * InternalParallelWorkers array.
1196  */
1197  if (strcmp(libraryname, "postgres") == 0)
1198  {
1199  int i;
1200 
1201  for (i = 0; i < lengthof(InternalParallelWorkers); i++)
1202  {
1203  if (strcmp(InternalParallelWorkers[i].fn_name, funcname) == 0)
1204  return InternalParallelWorkers[i].fn_addr;
1205  }
1206 
1207  /* We can only reach this by programming error. */
1208  elog(ERROR, "internal function \"%s\" not found", funcname);
1209  }
1210 
1211  /* Otherwise load from external library. */
1212  return (parallel_worker_main_type)
1213  load_external_function(libraryname, funcname, true, NULL);
1214 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
#define DatumGetUInt32(X)
Definition: postgres.h:492
int slock_t
Definition: s_lock.h:888
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:50
static const struct @21 InternalParallelWorkers[]
shm_toc * shm_toc_create(uint64 magic, void *address, Size nbytes)
Definition: shm_toc.c:40
int MyProcPid
Definition: globals.c:39
BackendId MyBackendId
Definition: globals.c:73
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:2121
MemoryContext TopTransactionContext
Definition: mcxt.c:48
uint32 dsm_handle
Definition: dsm_impl.h:55
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:140
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
XLogRecPtr XactLastRecEnd
Definition: xlog.c:339
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:775
PGPROC * MyProc
Definition: proc.c:67
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
dsm_segment * seg
Definition: parallel.h:42
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:584
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
char * pstrdup(const char *in)
Definition: mcxt.c:1076
void CommitTransactionCommand(void)
Definition: xact.c:2744
shm_toc_estimator estimator
Definition: parallel.h:41
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void EndParallelWorkerTransaction(void)
Definition: xact.c:5084
#define SpinLockInit(lock)
Definition: spin.h:60
void GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
Definition: namespace.c:3234
void RestoreTransactionSnapshot(Snapshot snapshot, void *master_pgproc)
Definition: snapmgr.c:2185
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:561
#define Min(x, y)
Definition: c.h:812
Oid authenticated_user_id
Definition: parallel.c:76
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1028
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:575
PGPROC * parallel_master_pgproc
Definition: parallel.c:81
Oid temp_toast_namespace_id
Definition: parallel.c:79
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
void DetachSession(void)
Definition: session.c:201
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:1854
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
uint32 SubTransactionId
Definition: c.h:395
Size shm_toc_estimate(shm_toc_estimator *e)
Definition: shm_toc.c:263
#define lengthof(array)
Definition: c.h:556
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
void SerializeTransactionState(Size maxsize, char *start_address)
Definition: xact.c:4993
parallel_worker_main_type fn_addr
Definition: parallel.c:119
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
void InvalidateSystemCaches(void)
Definition: inval.c:641
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void RestoreComboCIDState(char *comboCIDstate)
Definition: combocid.c:344
signed int int32
Definition: c.h:246
SubTransactionId subid
Definition: parallel.h:35
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ErrorContextCallback * error_context_stack
Definition: elog.c:88
volatile bool ParallelMessagePending
Definition: parallel.c:101
#define DSM_HANDLE_INVALID
Definition: dsm.h:23
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:763
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:534
#define SpinLockAcquire(lock)
Definition: spin.h:62
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:624
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
ParallelWorkerInfo * worker
Definition: parallel.h:45
Datum bgw_main_arg
Definition: bgworker.h:97
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
void pfree(void *pointer)
Definition: mcxt.c:949
bool IsInParallelMode(void)
Definition: xact.c:906
void SerializeLibraryState(Size maxsize, char *start_address)
Definition: dfmgr.c:728
#define ERROR
Definition: elog.h:43
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1138
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:343
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:65
char * function_name
Definition: parallel.h:39
void SerializeSnapshot(Snapshot snapshot, char *start_address)
Definition: snapmgr.c:2062
int32 MyCancelKey
Definition: globals.c:42
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition: pqmq.c:215
#define FATAL
Definition: elog.h:52
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:170
void ExitParallelMode(void)
Definition: xact.c:886
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
#define PARALLEL_KEY_FIXED
Definition: parallel.c:60
void HandleParallelMessages(void)
Definition: parallel.c:722
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:61
void SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
Definition: namespace.c:3250
static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
Definition: parallel.c:811
#define DSM_CREATE_NULL_IF_MAXSEGMENTS
Definition: dsm.h:20
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
shm_mq_handle * error_mqh
Definition: parallel.h:28
#define PARALLEL_KEY_GUC
Definition: parallel.c:63
int SetClientEncoding(int encoding)
Definition: mbutils.c:201
int ParallelWorkerNumber
Definition: parallel.c:98
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
int dynamic_shared_memory_type
Definition: dsm_impl.c:113
Size EstimateGUCStateSpace(void)
Definition: guc.c:9102
void AttachSession(dsm_handle handle)
Definition: session.c:155
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define shm_toc_initialize_estimator(e)
Definition: shm_toc.h:49
Size EstimateComboCIDStateSpace(void)
Definition: combocid.c:299
#define UInt32GetDatum(X)
Definition: postgres.h:499
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
Definition: postmaster.c:5563
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int nworkers_launched
Definition: parallel.h:37
XLogRecPtr last_xlog_end
Definition: parallel.c:89
BgwHandleStatus
Definition: bgworker.h:102
PGFunction load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:94
void LaunchParallelWorkers(ParallelContext *pcxt)
Definition: parallel.c:446
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:218
void BecomeLockGroupLeader(void)
Definition: proc.c:1824
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1612
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define DLIST_STATIC_INIT(name)
Definition: ilist.h:248
#define WARNING
Definition: elog.h:40
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:192
int elevel
Definition: elog.h:331
bool ParallelContextActive(void)
Definition: parallel.c:698
#define SpinLockRelease(lock)
Definition: spin.h:64
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:487
Size EstimateSnapshotSpace(Snapshot snap)
Definition: snapmgr.c:2038
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:877
static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
Definition: parallel.c:1191
void RestoreLibraryState(char *start_address)
Definition: dfmgr.c:750
uintptr_t Datum
Definition: postgres.h:372
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:465
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition: shm_toc.c:64
int GetDatabaseEncoding(void)
Definition: mbutils.c:1004
int BackendId
Definition: backendid.h:21
Oid MyDatabaseId
Definition: globals.c:77
pid_t parallel_master_pid
Definition: parallel.c:82
Size EstimateLibraryStateSpace(void)
Definition: dfmgr.c:711
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:409
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:315
dlist_node * cur
Definition: ilist.h:161
#define PARALLEL_MAGIC
Definition: parallel.c:53
void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
Definition: pqmq.c:55
void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
Definition: parallel.c:1161
void TerminateBackgroundWorker(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1177
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
volatile bool InterruptPending
Definition: globals.c:29
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
shm_mq_result
Definition: shm_mq.h:36
char * library_name
Definition: parallel.h:38
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
BackendId parallel_master_backend_id
Definition: parallel.c:83
int force_parallel_mode
Definition: planner.c:63
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1000
uint64 XLogRecPtr
Definition: xlogdefs.h:21
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:681
BackendId ParallelMasterBackendId
Definition: globals.c:75
void StartParallelWorkerTransaction(char *tstatespace)
Definition: xact.c:5061
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
Size EstimateTransactionStateSpace(void)
Definition: xact.c:4960
void StartTransactionCommand(void)
Definition: xact.c:2673
const char * fn_name
Definition: parallel.c:118
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define DSM_IMPL_NONE
Definition: dsm_impl.h:17
#define BGW_MAXLEN
Definition: bgworker.h:85
size_t Size
Definition: c.h:350
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
dlist_node node
Definition: parallel.h:34
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:939
void EnterParallelMode(void)
Definition: xact.c:873
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
char * context
Definition: elog.h:347
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:287
ErrorContextCallback * error_context_stack
Definition: parallel.h:40
void pq_set_parallel_master(pid_t pid, BackendId backend_id)
Definition: pqmq.c:80
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:67
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:726
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsolationIsSerializable()
Definition: xact.h:44
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:952
pid_t bgw_notify_pid
Definition: bgworker.h:99
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:107
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
void die(SIGNAL_ARGS)
Definition: postgres.c:2652
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
bool InitializingParallelWorker
Definition: parallel.c:104
int i
Definition: shm_mq.c:69
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:69
#define BUFFERALIGN(LEN)
Definition: c.h:578
struct Latch * MyLatch
Definition: globals.c:52
void HandleParallelMessageInterrupt(void)
Definition: parallel.c:711
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:199
static dlist_head pcxt_list
Definition: parallel.c:110
#define elog
Definition: elog.h:219
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:42
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
struct FixedParallelState FixedParallelState
dsm_handle GetSessionDsmHandle(void)
Definition: session.c:70
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition: shm_mq.c:522
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:935
Definition: proc.h:95
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:68
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:64
#define WL_LATCH_SET
Definition: latch.h:124
#define _(x)
Definition: elog.c:84
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:916
void SerializeGUCState(Size maxsize, char *start_address)
Definition: guc.c:9249
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:66
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
void SerializeComboCIDState(Size maxsize, char *start_address)
Definition: combocid.c:318
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:62
void RestoreGUCState(void *gucstate)
Definition: guc.c:9327
shm_toc * toc
Definition: parallel.h:44
void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
Definition: async.c:2096
void * private_memory
Definition: parallel.h:43
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
void(* parallel_worker_main_type)(dsm_segment *seg, shm_toc *toc)
Definition: parallel.h:23
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5592