PostgreSQL Source Code  git master
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-2023, 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/nbtree.h"
18 #include "access/parallel.h"
19 #include "access/session.h"
20 #include "access/xact.h"
21 #include "access/xlog.h"
22 #include "catalog/index.h"
23 #include "catalog/namespace.h"
24 #include "catalog/pg_enum.h"
25 #include "catalog/storage.h"
26 #include "commands/async.h"
27 #include "commands/progress.h"
28 #include "commands/vacuum.h"
29 #include "executor/execParallel.h"
30 #include "libpq/libpq.h"
31 #include "libpq/pqformat.h"
32 #include "libpq/pqmq.h"
33 #include "miscadmin.h"
34 #include "optimizer/optimizer.h"
35 #include "pgstat.h"
36 #include "storage/ipc.h"
37 #include "storage/predicate.h"
38 #include "storage/sinval.h"
39 #include "storage/spin.h"
40 #include "tcop/tcopprot.h"
41 #include "utils/combocid.h"
42 #include "utils/guc.h"
43 #include "utils/inval.h"
44 #include "utils/memutils.h"
45 #include "utils/relmapper.h"
46 #include "utils/snapmgr.h"
47 #include "utils/typcache.h"
48 
49 /*
50  * We don't want to waste a lot of memory on an error queue which, most of
51  * the time, will process only a handful of small messages. However, it is
52  * desirable to make it large enough that a typical ErrorResponse can be sent
53  * without blocking. That way, a worker that errors out can write the whole
54  * message into the queue and terminate without waiting for the user backend.
55  */
56 #define PARALLEL_ERROR_QUEUE_SIZE 16384
57 
58 /* Magic number for parallel context TOC. */
59 #define PARALLEL_MAGIC 0x50477c7c
60 
61 /*
62  * Magic numbers for per-context parallel state sharing. Higher-level code
63  * should use smaller values, leaving these very large ones for use by this
64  * module.
65  */
66 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
67 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
68 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
69 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
70 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
71 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
72 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
73 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
74 #define PARALLEL_KEY_ENTRYPOINT UINT64CONST(0xFFFFFFFFFFFF0009)
75 #define PARALLEL_KEY_SESSION_DSM UINT64CONST(0xFFFFFFFFFFFF000A)
76 #define PARALLEL_KEY_PENDING_SYNCS UINT64CONST(0xFFFFFFFFFFFF000B)
77 #define PARALLEL_KEY_REINDEX_STATE UINT64CONST(0xFFFFFFFFFFFF000C)
78 #define PARALLEL_KEY_RELMAPPER_STATE UINT64CONST(0xFFFFFFFFFFFF000D)
79 #define PARALLEL_KEY_UNCOMMITTEDENUMS UINT64CONST(0xFFFFFFFFFFFF000E)
80 #define PARALLEL_KEY_CLIENTCONNINFO UINT64CONST(0xFFFFFFFFFFFF000F)
81 
82 /* Fixed-size parallel state. */
83 typedef struct FixedParallelState
84 {
85  /* Fixed-size state that workers must restore. */
100 
101  /* Mutex protects remaining fields. */
103 
104  /* Maximum XactLastRecEnd of any worker. */
107 
108 /*
109  * Our parallel worker number. We initialize this to -1, meaning that we are
110  * not a parallel worker. In parallel workers, it will be set to a value >= 0
111  * and < the number of workers before any user code is invoked; each parallel
112  * worker will get a different parallel worker number.
113  */
115 
116 /* Is there a parallel message pending which we need to receive? */
117 volatile sig_atomic_t ParallelMessagePending = false;
118 
119 /* Are we initializing a parallel worker? */
121 
122 /* Pointer to our fixed parallel state. */
124 
125 /* List of active parallel contexts. */
127 
128 /* Backend-local copy of data from FixedParallelState. */
129 static pid_t ParallelLeaderPid;
130 
131 /*
132  * List of internal parallel worker entry points. We need this for
133  * reasons explained in LookupParallelWorkerFunction(), below.
134  */
135 static const struct
136 {
137  const char *fn_name;
140 
141 {
142  {
143  "ParallelQueryMain", ParallelQueryMain
144  },
145  {
146  "_bt_parallel_build_main", _bt_parallel_build_main
147  },
148  {
149  "parallel_vacuum_main", parallel_vacuum_main
150  }
151 };
152 
153 /* Private functions. */
154 static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg);
156 static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname);
157 static void ParallelWorkerShutdown(int code, Datum arg);
158 
159 
160 /*
161  * Establish a new parallel context. This should be done after entering
162  * parallel mode, and (unless there is an error) the context should be
163  * destroyed before exiting the current subtransaction.
164  */
166 CreateParallelContext(const char *library_name, const char *function_name,
167  int nworkers)
168 {
169  MemoryContext oldcontext;
170  ParallelContext *pcxt;
171 
172  /* It is unsafe to create a parallel context if not in parallel mode. */
174 
175  /* Number of workers should be non-negative. */
176  Assert(nworkers >= 0);
177 
178  /* We might be running in a short-lived memory context. */
180 
181  /* Initialize a new ParallelContext. */
182  pcxt = palloc0(sizeof(ParallelContext));
184  pcxt->nworkers = nworkers;
185  pcxt->nworkers_to_launch = nworkers;
186  pcxt->library_name = pstrdup(library_name);
187  pcxt->function_name = pstrdup(function_name);
190  dlist_push_head(&pcxt_list, &pcxt->node);
191 
192  /* Restore previous memory context. */
193  MemoryContextSwitchTo(oldcontext);
194 
195  return pcxt;
196 }
197 
198 /*
199  * Establish the dynamic shared memory segment for a parallel context and
200  * copy state and other bookkeeping information that will be needed by
201  * parallel workers into it.
202  */
203 void
205 {
206  MemoryContext oldcontext;
207  Size library_len = 0;
208  Size guc_len = 0;
209  Size combocidlen = 0;
210  Size tsnaplen = 0;
211  Size asnaplen = 0;
212  Size tstatelen = 0;
213  Size pendingsyncslen = 0;
214  Size reindexlen = 0;
215  Size relmapperlen = 0;
216  Size uncommittedenumslen = 0;
217  Size clientconninfolen = 0;
218  Size segsize = 0;
219  int i;
220  FixedParallelState *fps;
221  dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
222  Snapshot transaction_snapshot = GetTransactionSnapshot();
223  Snapshot active_snapshot = GetActiveSnapshot();
224 
225  /* We might be running in a very short-lived memory context. */
227 
228  /* Allow space to store the fixed-size parallel state. */
230  shm_toc_estimate_keys(&pcxt->estimator, 1);
231 
232  /*
233  * Normally, the user will have requested at least one worker process, but
234  * if by chance they have not, we can skip a bunch of things here.
235  */
236  if (pcxt->nworkers > 0)
237  {
238  /* Get (or create) the per-session DSM segment's handle. */
239  session_dsm_handle = GetSessionDsmHandle();
240 
241  /*
242  * If we weren't able to create a per-session DSM segment, then we can
243  * continue but we can't safely launch any workers because their
244  * record typmods would be incompatible so they couldn't exchange
245  * tuples.
246  */
247  if (session_dsm_handle == DSM_HANDLE_INVALID)
248  pcxt->nworkers = 0;
249  }
250 
251  if (pcxt->nworkers > 0)
252  {
253  /* Estimate space for various kinds of state sharing. */
254  library_len = EstimateLibraryStateSpace();
255  shm_toc_estimate_chunk(&pcxt->estimator, library_len);
256  guc_len = EstimateGUCStateSpace();
257  shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
258  combocidlen = EstimateComboCIDStateSpace();
259  shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
261  {
262  tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
263  shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
264  }
265  asnaplen = EstimateSnapshotSpace(active_snapshot);
266  shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
267  tstatelen = EstimateTransactionStateSpace();
268  shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
270  pendingsyncslen = EstimatePendingSyncsSpace();
271  shm_toc_estimate_chunk(&pcxt->estimator, pendingsyncslen);
272  reindexlen = EstimateReindexStateSpace();
273  shm_toc_estimate_chunk(&pcxt->estimator, reindexlen);
274  relmapperlen = EstimateRelationMapSpace();
275  shm_toc_estimate_chunk(&pcxt->estimator, relmapperlen);
276  uncommittedenumslen = EstimateUncommittedEnumsSpace();
277  shm_toc_estimate_chunk(&pcxt->estimator, uncommittedenumslen);
278  clientconninfolen = EstimateClientConnectionInfoSpace();
279  shm_toc_estimate_chunk(&pcxt->estimator, clientconninfolen);
280  /* If you add more chunks here, you probably need to add keys. */
281  shm_toc_estimate_keys(&pcxt->estimator, 12);
282 
283  /* Estimate space need for error queues. */
286  "parallel error queue size not buffer-aligned");
289  pcxt->nworkers));
290  shm_toc_estimate_keys(&pcxt->estimator, 1);
291 
292  /* Estimate how much we'll need for the entrypoint info. */
293  shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
294  strlen(pcxt->function_name) + 2);
295  shm_toc_estimate_keys(&pcxt->estimator, 1);
296  }
297 
298  /*
299  * Create DSM and initialize with new table of contents. But if the user
300  * didn't request any workers, then don't bother creating a dynamic shared
301  * memory segment; instead, just use backend-private memory.
302  *
303  * Also, if we can't create a dynamic shared memory segment because the
304  * maximum number of segments have already been created, then fall back to
305  * backend-private memory, and plan not to use any workers. We hope this
306  * won't happen very often, but it's better to abandon the use of
307  * parallelism than to fail outright.
308  */
309  segsize = shm_toc_estimate(&pcxt->estimator);
310  if (pcxt->nworkers > 0)
312  if (pcxt->seg != NULL)
314  dsm_segment_address(pcxt->seg),
315  segsize);
316  else
317  {
318  pcxt->nworkers = 0;
321  segsize);
322  }
323 
324  /* Initialize fixed-size state in shared memory. */
325  fps = (FixedParallelState *)
326  shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
327  fps->database_id = MyDatabaseId;
340  SpinLockInit(&fps->mutex);
341  fps->last_xlog_end = 0;
343 
344  /* We can skip the rest of this if we're not budgeting for any workers. */
345  if (pcxt->nworkers > 0)
346  {
347  char *libraryspace;
348  char *gucspace;
349  char *combocidspace;
350  char *tsnapspace;
351  char *asnapspace;
352  char *tstatespace;
353  char *pendingsyncsspace;
354  char *reindexspace;
355  char *relmapperspace;
356  char *error_queue_space;
357  char *session_dsm_handle_space;
358  char *entrypointstate;
359  char *uncommittedenumsspace;
360  char *clientconninfospace;
361  Size lnamelen;
362 
363  /* Serialize shared libraries we have loaded. */
364  libraryspace = shm_toc_allocate(pcxt->toc, library_len);
365  SerializeLibraryState(library_len, libraryspace);
366  shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
367 
368  /* Serialize GUC settings. */
369  gucspace = shm_toc_allocate(pcxt->toc, guc_len);
370  SerializeGUCState(guc_len, gucspace);
371  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
372 
373  /* Serialize combo CID state. */
374  combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
375  SerializeComboCIDState(combocidlen, combocidspace);
376  shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
377 
378  /*
379  * Serialize the transaction snapshot if the transaction isolation
380  * level uses a transaction snapshot.
381  */
383  {
384  tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
385  SerializeSnapshot(transaction_snapshot, tsnapspace);
387  tsnapspace);
388  }
389 
390  /* Serialize the active snapshot. */
391  asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
392  SerializeSnapshot(active_snapshot, asnapspace);
393  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
394 
395  /* Provide the handle for per-session segment. */
396  session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
397  sizeof(dsm_handle));
398  *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
400  session_dsm_handle_space);
401 
402  /* Serialize transaction state. */
403  tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
404  SerializeTransactionState(tstatelen, tstatespace);
406 
407  /* Serialize pending syncs. */
408  pendingsyncsspace = shm_toc_allocate(pcxt->toc, pendingsyncslen);
409  SerializePendingSyncs(pendingsyncslen, pendingsyncsspace);
411  pendingsyncsspace);
412 
413  /* Serialize reindex state. */
414  reindexspace = shm_toc_allocate(pcxt->toc, reindexlen);
415  SerializeReindexState(reindexlen, reindexspace);
416  shm_toc_insert(pcxt->toc, PARALLEL_KEY_REINDEX_STATE, reindexspace);
417 
418  /* Serialize relmapper state. */
419  relmapperspace = shm_toc_allocate(pcxt->toc, relmapperlen);
420  SerializeRelationMap(relmapperlen, relmapperspace);
422  relmapperspace);
423 
424  /* Serialize uncommitted enum state. */
425  uncommittedenumsspace = shm_toc_allocate(pcxt->toc,
426  uncommittedenumslen);
427  SerializeUncommittedEnums(uncommittedenumsspace, uncommittedenumslen);
429  uncommittedenumsspace);
430 
431  /* Serialize our ClientConnectionInfo. */
432  clientconninfospace = shm_toc_allocate(pcxt->toc, clientconninfolen);
433  SerializeClientConnectionInfo(clientconninfolen, clientconninfospace);
435  clientconninfospace);
436 
437  /* Allocate space for worker information. */
438  pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
439 
440  /*
441  * Establish error queues in dynamic shared memory.
442  *
443  * These queues should be used only for transmitting ErrorResponse,
444  * NoticeResponse, and NotifyResponse protocol messages. Tuple data
445  * should be transmitted via separate (possibly larger?) queues.
446  */
447  error_queue_space =
448  shm_toc_allocate(pcxt->toc,
450  pcxt->nworkers));
451  for (i = 0; i < pcxt->nworkers; ++i)
452  {
453  char *start;
454  shm_mq *mq;
455 
456  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
459  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
460  }
461  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
462 
463  /*
464  * Serialize entrypoint information. It's unsafe to pass function
465  * pointers across processes, as the function pointer may be different
466  * in each process in EXEC_BACKEND builds, so we always pass library
467  * and function name. (We use library name "postgres" for functions
468  * in the core backend.)
469  */
470  lnamelen = strlen(pcxt->library_name);
471  entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
472  strlen(pcxt->function_name) + 2);
473  strcpy(entrypointstate, pcxt->library_name);
474  strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
475  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
476  }
477 
478  /* Restore previous memory context. */
479  MemoryContextSwitchTo(oldcontext);
480 }
481 
482 /*
483  * Reinitialize the dynamic shared memory segment for a parallel context such
484  * that we could launch workers for it again.
485  */
486 void
488 {
489  FixedParallelState *fps;
490 
491  /* Wait for any old workers to exit. */
492  if (pcxt->nworkers_launched > 0)
493  {
496  pcxt->nworkers_launched = 0;
497  if (pcxt->known_attached_workers)
498  {
500  pcxt->known_attached_workers = NULL;
501  pcxt->nknown_attached_workers = 0;
502  }
503  }
504 
505  /* Reset a few bits of fixed parallel state to a clean state. */
506  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
507  fps->last_xlog_end = 0;
508 
509  /* Recreate error queues (if they exist). */
510  if (pcxt->nworkers > 0)
511  {
512  char *error_queue_space;
513  int i;
514 
515  error_queue_space =
517  for (i = 0; i < pcxt->nworkers; ++i)
518  {
519  char *start;
520  shm_mq *mq;
521 
522  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
525  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
526  }
527  }
528 }
529 
530 /*
531  * Reinitialize parallel workers for a parallel context such that we could
532  * launch a different number of workers. This is required for cases where
533  * we need to reuse the same DSM segment, but the number of workers can
534  * vary from run-to-run.
535  */
536 void
537 ReinitializeParallelWorkers(ParallelContext *pcxt, int nworkers_to_launch)
538 {
539  /*
540  * The number of workers that need to be launched must be less than the
541  * number of workers with which the parallel context is initialized.
542  */
543  Assert(pcxt->nworkers >= nworkers_to_launch);
544  pcxt->nworkers_to_launch = nworkers_to_launch;
545 }
546 
547 /*
548  * Launch parallel workers.
549  */
550 void
552 {
553  MemoryContext oldcontext;
554  BackgroundWorker worker;
555  int i;
556  bool any_registrations_failed = false;
557 
558  /* Skip this if we have no workers. */
559  if (pcxt->nworkers == 0 || pcxt->nworkers_to_launch == 0)
560  return;
561 
562  /* We need to be a lock group leader. */
564 
565  /* If we do have workers, we'd better have a DSM segment. */
566  Assert(pcxt->seg != NULL);
567 
568  /* We might be running in a short-lived memory context. */
570 
571  /* Configure a worker. */
572  memset(&worker, 0, sizeof(worker));
573  snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
574  MyProcPid);
575  snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
576  worker.bgw_flags =
581  sprintf(worker.bgw_library_name, "postgres");
582  sprintf(worker.bgw_function_name, "ParallelWorkerMain");
584  worker.bgw_notify_pid = MyProcPid;
585 
586  /*
587  * Start workers.
588  *
589  * The caller must be able to tolerate ending up with fewer workers than
590  * expected, so there is no need to throw an error here if registration
591  * fails. It wouldn't help much anyway, because registering the worker in
592  * no way guarantees that it will start up and initialize successfully.
593  */
594  for (i = 0; i < pcxt->nworkers_to_launch; ++i)
595  {
596  memcpy(worker.bgw_extra, &i, sizeof(int));
597  if (!any_registrations_failed &&
599  &pcxt->worker[i].bgwhandle))
600  {
602  pcxt->worker[i].bgwhandle);
603  pcxt->nworkers_launched++;
604  }
605  else
606  {
607  /*
608  * If we weren't able to register the worker, then we've bumped up
609  * against the max_worker_processes limit, and future
610  * registrations will probably fail too, so arrange to skip them.
611  * But we still have to execute this code for the remaining slots
612  * to make sure that we forget about the error queues we budgeted
613  * for those workers. Otherwise, we'll wait for them to start,
614  * but they never will.
615  */
616  any_registrations_failed = true;
617  pcxt->worker[i].bgwhandle = NULL;
619  pcxt->worker[i].error_mqh = NULL;
620  }
621  }
622 
623  /*
624  * Now that nworkers_launched has taken its final value, we can initialize
625  * known_attached_workers.
626  */
627  if (pcxt->nworkers_launched > 0)
628  {
629  pcxt->known_attached_workers =
630  palloc0(sizeof(bool) * pcxt->nworkers_launched);
631  pcxt->nknown_attached_workers = 0;
632  }
633 
634  /* Restore previous memory context. */
635  MemoryContextSwitchTo(oldcontext);
636 }
637 
638 /*
639  * Wait for all workers to attach to their error queues, and throw an error if
640  * any worker fails to do this.
641  *
642  * Callers can assume that if this function returns successfully, then the
643  * number of workers given by pcxt->nworkers_launched have initialized and
644  * attached to their error queues. Whether or not these workers are guaranteed
645  * to still be running depends on what code the caller asked them to run;
646  * this function does not guarantee that they have not exited. However, it
647  * does guarantee that any workers which exited must have done so cleanly and
648  * after successfully performing the work with which they were tasked.
649  *
650  * If this function is not called, then some of the workers that were launched
651  * may not have been started due to a fork() failure, or may have exited during
652  * early startup prior to attaching to the error queue, so nworkers_launched
653  * cannot be viewed as completely reliable. It will never be less than the
654  * number of workers which actually started, but it might be more. Any workers
655  * that failed to start will still be discovered by
656  * WaitForParallelWorkersToFinish and an error will be thrown at that time,
657  * provided that function is eventually reached.
658  *
659  * In general, the leader process should do as much work as possible before
660  * calling this function. fork() failures and other early-startup failures
661  * are very uncommon, and having the leader sit idle when it could be doing
662  * useful work is undesirable. However, if the leader needs to wait for
663  * all of its workers or for a specific worker, it may want to call this
664  * function before doing so. If not, it must make some other provision for
665  * the failure-to-start case, lest it wait forever. On the other hand, a
666  * leader which never waits for a worker that might not be started yet, or
667  * at least never does so prior to WaitForParallelWorkersToFinish(), need not
668  * call this function at all.
669  */
670 void
672 {
673  int i;
674 
675  /* Skip this if we have no launched workers. */
676  if (pcxt->nworkers_launched == 0)
677  return;
678 
679  for (;;)
680  {
681  /*
682  * This will process any parallel messages that are pending and it may
683  * also throw an error propagated from a worker.
684  */
686 
687  for (i = 0; i < pcxt->nworkers_launched; ++i)
688  {
689  BgwHandleStatus status;
690  shm_mq *mq;
691  int rc;
692  pid_t pid;
693 
694  if (pcxt->known_attached_workers[i])
695  continue;
696 
697  /*
698  * If error_mqh is NULL, then the worker has already exited
699  * cleanly.
700  */
701  if (pcxt->worker[i].error_mqh == NULL)
702  {
703  pcxt->known_attached_workers[i] = true;
704  ++pcxt->nknown_attached_workers;
705  continue;
706  }
707 
708  status = GetBackgroundWorkerPid(pcxt->worker[i].bgwhandle, &pid);
709  if (status == BGWH_STARTED)
710  {
711  /* Has the worker attached to the error queue? */
712  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
713  if (shm_mq_get_sender(mq) != NULL)
714  {
715  /* Yes, so it is known to be attached. */
716  pcxt->known_attached_workers[i] = true;
717  ++pcxt->nknown_attached_workers;
718  }
719  }
720  else if (status == BGWH_STOPPED)
721  {
722  /*
723  * If the worker stopped without attaching to the error queue,
724  * throw an error.
725  */
726  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
727  if (shm_mq_get_sender(mq) == NULL)
728  ereport(ERROR,
729  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
730  errmsg("parallel worker failed to initialize"),
731  errhint("More details may be available in the server log.")));
732 
733  pcxt->known_attached_workers[i] = true;
734  ++pcxt->nknown_attached_workers;
735  }
736  else
737  {
738  /*
739  * Worker not yet started, so we must wait. The postmaster
740  * will notify us if the worker's state changes. Our latch
741  * might also get set for some other reason, but if so we'll
742  * just end up waiting for the same worker again.
743  */
744  rc = WaitLatch(MyLatch,
746  -1, WAIT_EVENT_BGWORKER_STARTUP);
747 
748  if (rc & WL_LATCH_SET)
750  }
751  }
752 
753  /* If all workers are known to have started, we're done. */
754  if (pcxt->nknown_attached_workers >= pcxt->nworkers_launched)
755  {
757  break;
758  }
759  }
760 }
761 
762 /*
763  * Wait for all workers to finish computing.
764  *
765  * Even if the parallel operation seems to have completed successfully, it's
766  * important to call this function afterwards. We must not miss any errors
767  * the workers may have thrown during the parallel operation, or any that they
768  * may yet throw while shutting down.
769  *
770  * Also, we want to update our notion of XactLastRecEnd based on worker
771  * feedback.
772  */
773 void
775 {
776  for (;;)
777  {
778  bool anyone_alive = false;
779  int nfinished = 0;
780  int i;
781 
782  /*
783  * This will process any parallel messages that are pending, which may
784  * change the outcome of the loop that follows. It may also throw an
785  * error propagated from a worker.
786  */
788 
789  for (i = 0; i < pcxt->nworkers_launched; ++i)
790  {
791  /*
792  * If error_mqh is NULL, then the worker has already exited
793  * cleanly. If we have received a message through error_mqh from
794  * the worker, we know it started up cleanly, and therefore we're
795  * certain to be notified when it exits.
796  */
797  if (pcxt->worker[i].error_mqh == NULL)
798  ++nfinished;
799  else if (pcxt->known_attached_workers[i])
800  {
801  anyone_alive = true;
802  break;
803  }
804  }
805 
806  if (!anyone_alive)
807  {
808  /* If all workers are known to have finished, we're done. */
809  if (nfinished >= pcxt->nworkers_launched)
810  {
811  Assert(nfinished == pcxt->nworkers_launched);
812  break;
813  }
814 
815  /*
816  * We didn't detect any living workers, but not all workers are
817  * known to have exited cleanly. Either not all workers have
818  * launched yet, or maybe some of them failed to start or
819  * terminated abnormally.
820  */
821  for (i = 0; i < pcxt->nworkers_launched; ++i)
822  {
823  pid_t pid;
824  shm_mq *mq;
825 
826  /*
827  * If the worker is BGWH_NOT_YET_STARTED or BGWH_STARTED, we
828  * should just keep waiting. If it is BGWH_STOPPED, then
829  * further investigation is needed.
830  */
831  if (pcxt->worker[i].error_mqh == NULL ||
832  pcxt->worker[i].bgwhandle == NULL ||
834  &pid) != BGWH_STOPPED)
835  continue;
836 
837  /*
838  * Check whether the worker ended up stopped without ever
839  * attaching to the error queue. If so, the postmaster was
840  * unable to fork the worker or it exited without initializing
841  * properly. We must throw an error, since the caller may
842  * have been expecting the worker to do some work before
843  * exiting.
844  */
845  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
846  if (shm_mq_get_sender(mq) == NULL)
847  ereport(ERROR,
848  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
849  errmsg("parallel worker failed to initialize"),
850  errhint("More details may be available in the server log.")));
851 
852  /*
853  * The worker is stopped, but is attached to the error queue.
854  * Unless there's a bug somewhere, this will only happen when
855  * the worker writes messages and terminates after the
856  * CHECK_FOR_INTERRUPTS() near the top of this function and
857  * before the call to GetBackgroundWorkerPid(). In that case,
858  * or latch should have been set as well and the right things
859  * will happen on the next pass through the loop.
860  */
861  }
862  }
863 
865  WAIT_EVENT_PARALLEL_FINISH);
867  }
868 
869  if (pcxt->toc != NULL)
870  {
871  FixedParallelState *fps;
872 
873  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
874  if (fps->last_xlog_end > XactLastRecEnd)
876  }
877 }
878 
879 /*
880  * Wait for all workers to exit.
881  *
882  * This function ensures that workers have been completely shutdown. The
883  * difference between WaitForParallelWorkersToFinish and this function is
884  * that the former just ensures that last message sent by a worker backend is
885  * received by the leader backend whereas this ensures the complete shutdown.
886  */
887 static void
889 {
890  int i;
891 
892  /* Wait until the workers actually die. */
893  for (i = 0; i < pcxt->nworkers_launched; ++i)
894  {
895  BgwHandleStatus status;
896 
897  if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
898  continue;
899 
901 
902  /*
903  * If the postmaster kicked the bucket, we have no chance of cleaning
904  * up safely -- we won't be able to tell when our workers are actually
905  * dead. This doesn't necessitate a PANIC since they will all abort
906  * eventually, but we can't safely continue this session.
907  */
908  if (status == BGWH_POSTMASTER_DIED)
909  ereport(FATAL,
910  (errcode(ERRCODE_ADMIN_SHUTDOWN),
911  errmsg("postmaster exited during a parallel transaction")));
912 
913  /* Release memory. */
914  pfree(pcxt->worker[i].bgwhandle);
915  pcxt->worker[i].bgwhandle = NULL;
916  }
917 }
918 
919 /*
920  * Destroy a parallel context.
921  *
922  * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
923  * first, before calling this function. When this function is invoked, any
924  * remaining workers are forcibly killed; the dynamic shared memory segment
925  * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
926  */
927 void
929 {
930  int i;
931 
932  /*
933  * Be careful about order of operations here! We remove the parallel
934  * context from the list before we do anything else; otherwise, if an
935  * error occurs during a subsequent step, we might try to nuke it again
936  * from AtEOXact_Parallel or AtEOSubXact_Parallel.
937  */
938  dlist_delete(&pcxt->node);
939 
940  /* Kill each worker in turn, and forget their error queues. */
941  if (pcxt->worker != NULL)
942  {
943  for (i = 0; i < pcxt->nworkers_launched; ++i)
944  {
945  if (pcxt->worker[i].error_mqh != NULL)
946  {
948 
950  pcxt->worker[i].error_mqh = NULL;
951  }
952  }
953  }
954 
955  /*
956  * If we have allocated a shared memory segment, detach it. This will
957  * implicitly detach the error queues, and any other shared memory queues,
958  * stored there.
959  */
960  if (pcxt->seg != NULL)
961  {
962  dsm_detach(pcxt->seg);
963  pcxt->seg = NULL;
964  }
965 
966  /*
967  * If this parallel context is actually in backend-private memory rather
968  * than shared memory, free that memory instead.
969  */
970  if (pcxt->private_memory != NULL)
971  {
972  pfree(pcxt->private_memory);
973  pcxt->private_memory = NULL;
974  }
975 
976  /*
977  * We can't finish transaction commit or abort until all of the workers
978  * have exited. This means, in particular, that we can't respond to
979  * interrupts at this stage.
980  */
981  HOLD_INTERRUPTS();
984 
985  /* Free the worker array itself. */
986  if (pcxt->worker != NULL)
987  {
988  pfree(pcxt->worker);
989  pcxt->worker = NULL;
990  }
991 
992  /* Free memory. */
993  pfree(pcxt->library_name);
994  pfree(pcxt->function_name);
995  pfree(pcxt);
996 }
997 
998 /*
999  * Are there any parallel contexts currently active?
1000  */
1001 bool
1003 {
1004  return !dlist_is_empty(&pcxt_list);
1005 }
1006 
1007 /*
1008  * Handle receipt of an interrupt indicating a parallel worker message.
1009  *
1010  * Note: this is called within a signal handler! All we can do is set
1011  * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
1012  * HandleParallelMessages().
1013  */
1014 void
1016 {
1017  InterruptPending = true;
1018  ParallelMessagePending = true;
1019  SetLatch(MyLatch);
1020 }
1021 
1022 /*
1023  * Handle any queued protocol messages received from parallel workers.
1024  */
1025 void
1027 {
1028  dlist_iter iter;
1029  MemoryContext oldcontext;
1030 
1031  static MemoryContext hpm_context = NULL;
1032 
1033  /*
1034  * This is invoked from ProcessInterrupts(), and since some of the
1035  * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
1036  * for recursive calls if more signals are received while this runs. It's
1037  * unclear that recursive entry would be safe, and it doesn't seem useful
1038  * even if it is safe, so let's block interrupts until done.
1039  */
1040  HOLD_INTERRUPTS();
1041 
1042  /*
1043  * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
1044  * don't want to risk leaking data into long-lived contexts, so let's do
1045  * our work here in a private context that we can reset on each use.
1046  */
1047  if (hpm_context == NULL) /* first time through? */
1049  "HandleParallelMessages",
1051  else
1052  MemoryContextReset(hpm_context);
1053 
1054  oldcontext = MemoryContextSwitchTo(hpm_context);
1055 
1056  /* OK to process messages. Reset the flag saying there are more to do. */
1057  ParallelMessagePending = false;
1058 
1059  dlist_foreach(iter, &pcxt_list)
1060  {
1061  ParallelContext *pcxt;
1062  int i;
1063 
1064  pcxt = dlist_container(ParallelContext, node, iter.cur);
1065  if (pcxt->worker == NULL)
1066  continue;
1067 
1068  for (i = 0; i < pcxt->nworkers_launched; ++i)
1069  {
1070  /*
1071  * Read as many messages as we can from each worker, but stop when
1072  * either (1) the worker's error queue goes away, which can happen
1073  * if we receive a Terminate message from the worker; or (2) no
1074  * more messages can be read from the worker without blocking.
1075  */
1076  while (pcxt->worker[i].error_mqh != NULL)
1077  {
1079  Size nbytes;
1080  void *data;
1081 
1082  res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
1083  &data, true);
1084  if (res == SHM_MQ_WOULD_BLOCK)
1085  break;
1086  else if (res == SHM_MQ_SUCCESS)
1087  {
1088  StringInfoData msg;
1089 
1090  initStringInfo(&msg);
1091  appendBinaryStringInfo(&msg, data, nbytes);
1092  HandleParallelMessage(pcxt, i, &msg);
1093  pfree(msg.data);
1094  }
1095  else
1096  ereport(ERROR,
1097  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1098  errmsg("lost connection to parallel worker")));
1099  }
1100  }
1101  }
1102 
1103  MemoryContextSwitchTo(oldcontext);
1104 
1105  /* Might as well clear the context on our way out */
1106  MemoryContextReset(hpm_context);
1107 
1109 }
1110 
1111 /*
1112  * Handle a single protocol message received from a single parallel worker.
1113  */
1114 static void
1116 {
1117  char msgtype;
1118 
1119  if (pcxt->known_attached_workers != NULL &&
1120  !pcxt->known_attached_workers[i])
1121  {
1122  pcxt->known_attached_workers[i] = true;
1123  pcxt->nknown_attached_workers++;
1124  }
1125 
1126  msgtype = pq_getmsgbyte(msg);
1127 
1128  switch (msgtype)
1129  {
1130  case PqMsg_BackendKeyData:
1131  {
1132  int32 pid = pq_getmsgint(msg, 4);
1133 
1134  (void) pq_getmsgint(msg, 4); /* discard cancel key */
1135  (void) pq_getmsgend(msg);
1136  pcxt->worker[i].pid = pid;
1137  break;
1138  }
1139 
1140  case PqMsg_ErrorResponse:
1141  case PqMsg_NoticeResponse:
1142  {
1143  ErrorData edata;
1144  ErrorContextCallback *save_error_context_stack;
1145 
1146  /* Parse ErrorResponse or NoticeResponse. */
1147  pq_parse_errornotice(msg, &edata);
1148 
1149  /* Death of a worker isn't enough justification for suicide. */
1150  edata.elevel = Min(edata.elevel, ERROR);
1151 
1152  /*
1153  * If desired, add a context line to show that this is a
1154  * message propagated from a parallel worker. Otherwise, it
1155  * can sometimes be confusing to understand what actually
1156  * happened. (We don't do this in DEBUG_PARALLEL_REGRESS mode
1157  * because it causes test-result instability depending on
1158  * whether a parallel worker is actually used or not.)
1159  */
1161  {
1162  if (edata.context)
1163  edata.context = psprintf("%s\n%s", edata.context,
1164  _("parallel worker"));
1165  else
1166  edata.context = pstrdup(_("parallel worker"));
1167  }
1168 
1169  /*
1170  * Context beyond that should use the error context callbacks
1171  * that were in effect when the ParallelContext was created,
1172  * not the current ones.
1173  */
1174  save_error_context_stack = error_context_stack;
1176 
1177  /* Rethrow error or print notice. */
1178  ThrowErrorData(&edata);
1179 
1180  /* Not an error, so restore previous context stack. */
1181  error_context_stack = save_error_context_stack;
1182 
1183  break;
1184  }
1185 
1187  {
1188  /* Propagate NotifyResponse. */
1189  int32 pid;
1190  const char *channel;
1191  const char *payload;
1192 
1193  pid = pq_getmsgint(msg, 4);
1194  channel = pq_getmsgrawstring(msg);
1195  payload = pq_getmsgrawstring(msg);
1196  pq_endmessage(msg);
1197 
1198  NotifyMyFrontEnd(channel, payload, pid);
1199 
1200  break;
1201  }
1202 
1203  case 'P': /* Parallel progress reporting */
1204  {
1205  /*
1206  * Only incremental progress reporting is currently supported.
1207  * However, it's possible to add more fields to the message to
1208  * allow for handling of other backend progress APIs.
1209  */
1210  int index = pq_getmsgint(msg, 4);
1211  int64 incr = pq_getmsgint64(msg);
1212 
1213  pq_getmsgend(msg);
1214 
1216 
1217  break;
1218  }
1219 
1220  case PqMsg_Terminate:
1221  {
1222  shm_mq_detach(pcxt->worker[i].error_mqh);
1223  pcxt->worker[i].error_mqh = NULL;
1224  break;
1225  }
1226 
1227  default:
1228  {
1229  elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
1230  msgtype, msg->len);
1231  }
1232  }
1233 }
1234 
1235 /*
1236  * End-of-subtransaction cleanup for parallel contexts.
1237  *
1238  * Currently, it's forbidden to enter or leave a subtransaction while
1239  * parallel mode is in effect, so we could just blow away everything. But
1240  * we may want to relax that restriction in the future, so this code
1241  * contemplates that there may be multiple subtransaction IDs in pcxt_list.
1242  */
1243 void
1245 {
1246  while (!dlist_is_empty(&pcxt_list))
1247  {
1248  ParallelContext *pcxt;
1249 
1251  if (pcxt->subid != mySubId)
1252  break;
1253  if (isCommit)
1254  elog(WARNING, "leaked parallel context");
1255  DestroyParallelContext(pcxt);
1256  }
1257 }
1258 
1259 /*
1260  * End-of-transaction cleanup for parallel contexts.
1261  */
1262 void
1263 AtEOXact_Parallel(bool isCommit)
1264 {
1265  while (!dlist_is_empty(&pcxt_list))
1266  {
1267  ParallelContext *pcxt;
1268 
1270  if (isCommit)
1271  elog(WARNING, "leaked parallel context");
1272  DestroyParallelContext(pcxt);
1273  }
1274 }
1275 
1276 /*
1277  * Main entrypoint for parallel workers.
1278  */
1279 void
1281 {
1282  dsm_segment *seg;
1283  shm_toc *toc;
1284  FixedParallelState *fps;
1285  char *error_queue_space;
1286  shm_mq *mq;
1287  shm_mq_handle *mqh;
1288  char *libraryspace;
1289  char *entrypointstate;
1290  char *library_name;
1291  char *function_name;
1292  parallel_worker_main_type entrypt;
1293  char *gucspace;
1294  char *combocidspace;
1295  char *tsnapspace;
1296  char *asnapspace;
1297  char *tstatespace;
1298  char *pendingsyncsspace;
1299  char *reindexspace;
1300  char *relmapperspace;
1301  char *uncommittedenumsspace;
1302  char *clientconninfospace;
1303  StringInfoData msgbuf;
1304  char *session_dsm_handle_space;
1305  Snapshot tsnapshot;
1306  Snapshot asnapshot;
1307 
1308  /* Set flag to indicate that we're initializing a parallel worker. */
1310 
1311  /* Establish signal handlers. */
1312  pqsignal(SIGTERM, die);
1314 
1315  /* Determine and set our parallel worker number. */
1317  memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
1318 
1319  /* Set up a memory context to work in, just for cleanliness. */
1321  "Parallel worker",
1323 
1324  /*
1325  * Attach to the dynamic shared memory segment for the parallel query, and
1326  * find its table of contents.
1327  *
1328  * Note: at this point, we have not created any ResourceOwner in this
1329  * process. This will result in our DSM mapping surviving until process
1330  * exit, which is fine. If there were a ResourceOwner, it would acquire
1331  * ownership of the mapping, but we have no need for that.
1332  */
1333  seg = dsm_attach(DatumGetUInt32(main_arg));
1334  if (seg == NULL)
1335  ereport(ERROR,
1336  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1337  errmsg("could not map dynamic shared memory segment")));
1339  if (toc == NULL)
1340  ereport(ERROR,
1341  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1342  errmsg("invalid magic number in dynamic shared memory segment")));
1343 
1344  /* Look up fixed parallel state. */
1345  fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1346  MyFixedParallelState = fps;
1347 
1348  /* Arrange to signal the leader if we exit. */
1352 
1353  /*
1354  * Now we can find and attach to the error queue provided for us. That's
1355  * good, because until we do that, any errors that happen here will not be
1356  * reported back to the process that requested that this worker be
1357  * launched.
1358  */
1359  error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1360  mq = (shm_mq *) (error_queue_space +
1363  mqh = shm_mq_attach(mq, seg, NULL);
1364  pq_redirect_to_shm_mq(seg, mqh);
1367 
1368  /*
1369  * Send a BackendKeyData message to the process that initiated parallelism
1370  * so that it has access to our PID before it receives any other messages
1371  * from us. Our cancel key is sent, too, since that's the way the
1372  * protocol message is defined, but it won't actually be used for anything
1373  * in this case.
1374  */
1376  pq_sendint32(&msgbuf, (int32) MyProcPid);
1377  pq_sendint32(&msgbuf, (int32) MyCancelKey);
1378  pq_endmessage(&msgbuf);
1379 
1380  /*
1381  * Hooray! Primary initialization is complete. Now, we need to set up our
1382  * backend-local state to match the original backend.
1383  */
1384 
1385  /*
1386  * Join locking group. We must do this before anything that could try to
1387  * acquire a heavyweight lock, because any heavyweight locks acquired to
1388  * this point could block either directly against the parallel group
1389  * leader or against some process which in turn waits for a lock that
1390  * conflicts with the parallel group leader, causing an undetected
1391  * deadlock. (If we can't join the lock group, the leader has gone away,
1392  * so just exit quietly.)
1393  */
1395  fps->parallel_leader_pid))
1396  return;
1397 
1398  /*
1399  * Restore transaction and statement start-time timestamps. This must
1400  * happen before anything that would start a transaction, else asserts in
1401  * xact.c will fire.
1402  */
1404 
1405  /*
1406  * Identify the entry point to be called. In theory this could result in
1407  * loading an additional library, though most likely the entry point is in
1408  * the core backend or in a library we just loaded.
1409  */
1410  entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1411  library_name = entrypointstate;
1412  function_name = entrypointstate + strlen(library_name) + 1;
1413 
1414  entrypt = LookupParallelWorkerFunction(library_name, function_name);
1415 
1416  /* Restore database connection. */
1418  fps->authenticated_user_id,
1419  0);
1420 
1421  /*
1422  * Set the client encoding to the database encoding, since that is what
1423  * the leader will expect.
1424  */
1426 
1427  /*
1428  * Load libraries that were loaded by original backend. We want to do
1429  * this before restoring GUCs, because the libraries might define custom
1430  * variables.
1431  */
1432  libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1434  RestoreLibraryState(libraryspace);
1435 
1436  /* Restore GUC values from launching backend. */
1437  gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1438  RestoreGUCState(gucspace);
1440 
1441  /* Crank up a transaction state appropriate to a parallel worker. */
1442  tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1443  StartParallelWorkerTransaction(tstatespace);
1444 
1445  /* Restore combo CID state. */
1446  combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1447  RestoreComboCIDState(combocidspace);
1448 
1449  /* Attach to the per-session DSM segment and contained objects. */
1450  session_dsm_handle_space =
1452  AttachSession(*(dsm_handle *) session_dsm_handle_space);
1453 
1454  /*
1455  * If the transaction isolation level is REPEATABLE READ or SERIALIZABLE,
1456  * the leader has serialized the transaction snapshot and we must restore
1457  * it. At lower isolation levels, there is no transaction-lifetime
1458  * snapshot, but we need TransactionXmin to get set to a value which is
1459  * less than or equal to the xmin of every snapshot that will be used by
1460  * this worker. The easiest way to accomplish that is to install the
1461  * active snapshot as the transaction snapshot. Code running in this
1462  * parallel worker might take new snapshots via GetTransactionSnapshot()
1463  * or GetLatestSnapshot(), but it shouldn't have any way of acquiring a
1464  * snapshot older than the active snapshot.
1465  */
1466  asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1467  tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, true);
1468  asnapshot = RestoreSnapshot(asnapspace);
1469  tsnapshot = tsnapspace ? RestoreSnapshot(tsnapspace) : asnapshot;
1470  RestoreTransactionSnapshot(tsnapshot,
1471  fps->parallel_leader_pgproc);
1472  PushActiveSnapshot(asnapshot);
1473 
1474  /*
1475  * We've changed which tuples we can see, and must therefore invalidate
1476  * system caches.
1477  */
1479 
1480  /*
1481  * Restore current role id. Skip verifying whether session user is
1482  * allowed to become this role and blindly restore the leader's state for
1483  * current role.
1484  */
1486 
1487  /* Restore user ID and security context. */
1489 
1490  /* Restore temp-namespace state to ensure search path matches leader's. */
1493 
1494  /* Restore pending syncs. */
1495  pendingsyncsspace = shm_toc_lookup(toc, PARALLEL_KEY_PENDING_SYNCS,
1496  false);
1497  RestorePendingSyncs(pendingsyncsspace);
1498 
1499  /* Restore reindex state. */
1500  reindexspace = shm_toc_lookup(toc, PARALLEL_KEY_REINDEX_STATE, false);
1501  RestoreReindexState(reindexspace);
1502 
1503  /* Restore relmapper state. */
1504  relmapperspace = shm_toc_lookup(toc, PARALLEL_KEY_RELMAPPER_STATE, false);
1505  RestoreRelationMap(relmapperspace);
1506 
1507  /* Restore uncommitted enums. */
1508  uncommittedenumsspace = shm_toc_lookup(toc, PARALLEL_KEY_UNCOMMITTEDENUMS,
1509  false);
1510  RestoreUncommittedEnums(uncommittedenumsspace);
1511 
1512  /* Restore the ClientConnectionInfo. */
1513  clientconninfospace = shm_toc_lookup(toc, PARALLEL_KEY_CLIENTCONNINFO,
1514  false);
1515  RestoreClientConnectionInfo(clientconninfospace);
1516 
1517  /*
1518  * Initialize SystemUser now that MyClientConnectionInfo is restored. Also
1519  * ensure that auth_method is actually valid, aka authn_id is not NULL.
1520  */
1524 
1525  /* Attach to the leader's serializable transaction, if SERIALIZABLE. */
1527 
1528  /*
1529  * We've initialized all of our state now; nothing should change
1530  * hereafter.
1531  */
1534 
1535  /*
1536  * Time to do the real work: invoke the caller-supplied code.
1537  */
1538  entrypt(seg, toc);
1539 
1540  /* Must exit parallel mode to pop active snapshot. */
1541  ExitParallelMode();
1542 
1543  /* Must pop active snapshot so snapmgr.c doesn't complain. */
1545 
1546  /* Shut down the parallel-worker transaction. */
1548 
1549  /* Detach from the per-session DSM segment. */
1550  DetachSession();
1551 
1552  /* Report success. */
1553  pq_putmessage(PqMsg_Terminate, NULL, 0);
1554 }
1555 
1556 /*
1557  * Update shared memory with the ending location of the last WAL record we
1558  * wrote, if it's greater than the value already stored there.
1559  */
1560 void
1562 {
1564 
1565  Assert(fps != NULL);
1566  SpinLockAcquire(&fps->mutex);
1567  if (fps->last_xlog_end < last_xlog_end)
1568  fps->last_xlog_end = last_xlog_end;
1569  SpinLockRelease(&fps->mutex);
1570 }
1571 
1572 /*
1573  * Make sure the leader tries to read from our error queue one more time.
1574  * This guards against the case where we exit uncleanly without sending an
1575  * ErrorResponse to the leader, for example because some code calls proc_exit
1576  * directly.
1577  *
1578  * Also explicitly detach from dsm segment so that subsystems using
1579  * on_dsm_detach() have a chance to send stats before the stats subsystem is
1580  * shut down as part of a before_shmem_exit() hook.
1581  *
1582  * One might think this could instead be solved by carefully ordering the
1583  * attaching to dsm segments, so that the pgstats segments get detached from
1584  * later than the parallel query one. That turns out to not work because the
1585  * stats hash might need to grow which can cause new segments to be allocated,
1586  * which then will be detached from earlier.
1587  */
1588 static void
1590 {
1594 
1596 }
1597 
1598 /*
1599  * Look up (and possibly load) a parallel worker entry point function.
1600  *
1601  * For functions contained in the core code, we use library name "postgres"
1602  * and consult the InternalParallelWorkers array. External functions are
1603  * looked up, and loaded if necessary, using load_external_function().
1604  *
1605  * The point of this is to pass function names as strings across process
1606  * boundaries. We can't pass actual function addresses because of the
1607  * possibility that the function has been loaded at a different address
1608  * in a different process. This is obviously a hazard for functions in
1609  * loadable libraries, but it can happen even for functions in the core code
1610  * on platforms using EXEC_BACKEND (e.g., Windows).
1611  *
1612  * At some point it might be worthwhile to get rid of InternalParallelWorkers[]
1613  * in favor of applying load_external_function() for core functions too;
1614  * but that raises portability issues that are not worth addressing now.
1615  */
1617 LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
1618 {
1619  /*
1620  * If the function is to be loaded from postgres itself, search the
1621  * InternalParallelWorkers array.
1622  */
1623  if (strcmp(libraryname, "postgres") == 0)
1624  {
1625  int i;
1626 
1627  for (i = 0; i < lengthof(InternalParallelWorkers); i++)
1628  {
1629  if (strcmp(InternalParallelWorkers[i].fn_name, funcname) == 0)
1631  }
1632 
1633  /* We can only reach this by programming error. */
1634  elog(ERROR, "internal function \"%s\" not found", funcname);
1635  }
1636 
1637  /* Otherwise load from external library. */
1638  return (parallel_worker_main_type)
1639  load_external_function(libraryname, funcname, true, NULL);
1640 }
void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
Definition: async.c:2216
static const struct @13 InternalParallelWorkers[]
static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
Definition: parallel.c:1617
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:73
int ParallelWorkerNumber
Definition: parallel.c:114
void HandleParallelMessageInterrupt(void)
Definition: parallel.c:1015
struct FixedParallelState FixedParallelState
bool InitializingParallelWorker
Definition: parallel.c:120
#define PARALLEL_KEY_GUC
Definition: parallel.c:69
parallel_worker_main_type fn_addr
Definition: parallel.c:138
#define PARALLEL_KEY_UNCOMMITTEDENUMS
Definition: parallel.c:79
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:71
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:204
#define PARALLEL_KEY_CLIENTCONNINFO
Definition: parallel.c:80
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:123
#define PARALLEL_KEY_PENDING_SYNCS
Definition: parallel.c:76
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:774
void LaunchParallelWorkers(ParallelContext *pcxt)
Definition: parallel.c:551
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:487
void HandleParallelMessages(void)
Definition: parallel.c:1026
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:928
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:72
void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
Definition: parallel.c:1561
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:67
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:75
static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
Definition: parallel.c:1115
#define PARALLEL_MAGIC
Definition: parallel.c:59
bool ParallelContextActive(void)
Definition: parallel.c:1002
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1280
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:166
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:888
static pid_t ParallelLeaderPid
Definition: parallel.c:129
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:77
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:68
static void ParallelWorkerShutdown(int code, Datum arg)
Definition: parallel.c:1589
static dlist_head pcxt_list
Definition: parallel.c:126
const char * fn_name
Definition: parallel.c:137
#define PARALLEL_KEY_FIXED
Definition: parallel.c:66
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:74
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:117
void ReinitializeParallelWorkers(ParallelContext *pcxt, int nworkers_to_launch)
Definition: parallel.c:537
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:70
void WaitForParallelWorkersToAttach(ParallelContext *pcxt)
Definition: parallel.c:671
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:56
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:1244
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:1263
#define PARALLEL_KEY_RELMAPPER_STATE
Definition: parallel.c:78
void pgstat_progress_incr_param(int index, int64 incr)
int BackendId
Definition: backendid.h:21
void TerminateBackgroundWorker(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1237
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1198
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1098
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:986
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_POSTMASTER_DIED
Definition: bgworker.h:108
@ BGWH_STARTED
Definition: bgworker.h:105
@ BGWH_STOPPED
Definition: bgworker.h:107
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:53
#define BGW_MAXLEN
Definition: bgworker.h:86
#define Min(x, y)
Definition: c.h:993
uint32 SubTransactionId
Definition: c.h:645
signed int int32
Definition: c.h:483
#define BUFFERALIGN(LEN)
Definition: c.h:802
#define lengthof(array)
Definition: c.h:777
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:927
size_t Size
Definition: c.h:594
void RestoreComboCIDState(char *comboCIDstate)
Definition: combocid.c:342
void SerializeComboCIDState(Size maxsize, char *start_address)
Definition: combocid.c:316
Size EstimateComboCIDStateSpace(void)
Definition: combocid.c:297
int64 TimestampTz
Definition: timestamp.h:39
void RestoreLibraryState(char *start_address)
Definition: dfmgr.c:693
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
void SerializeLibraryState(Size maxsize, char *start_address)
Definition: dfmgr.c:671
Size EstimateLibraryStateSpace(void)
Definition: dfmgr.c:654
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1124
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1096
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:804
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:666
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:517
#define DSM_CREATE_NULL_IF_MAXSEGMENTS
Definition: dsm.h:20
uint32 dsm_handle
Definition: dsm_impl.h:55
#define DSM_HANDLE_INVALID
Definition: dsm_impl.h:58
ErrorContextCallback * error_context_stack
Definition: elog.c:95
int errhint(const char *fmt,...)
Definition: elog.c:1316
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1850
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define _(x)
Definition: elog.c:91
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
int32 MyCancelKey
Definition: globals.c:48
BackendId ParallelLeaderBackendId
Definition: globals.c:87
int MyProcPid
Definition: globals.c:44
BackendId MyBackendId
Definition: globals.c:85
struct Latch * MyLatch
Definition: globals.c:58
Oid MyDatabaseId
Definition: globals.c:89
void RestoreGUCState(void *gucstate)
Definition: guc.c:6068
void SerializeGUCState(Size maxsize, char *start_address)
Definition: guc.c:5976
Size EstimateGUCStateSpace(void)
Definition: guc.c:5823
bool current_role_is_superuser
Definition: guc_tables.c:516
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3066
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:603
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
#define DLIST_STATIC_INIT(name)
Definition: ilist.h:281
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
void(* parallel_worker_main_type)(dsm_segment *seg, shm_toc *toc)
Definition: parallel.h:23
#define funcname
Definition: indent_codes.h:69
void SerializeReindexState(Size maxsize, char *start_address)
Definition: index.c:4155
void RestoreReindexState(const void *reindexstate)
Definition: index.c:4173
Size EstimateReindexStateSpace(void)
Definition: index.c:4144
void InvalidateSystemCaches(void)
Definition: inval.c:793
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
int i
Definition: isn.c:73
void SetLatch(Latch *latch)
Definition: latch.c:633
void ResetLatch(Latch *latch)
Definition: latch.c:725
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:518
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49
Assert(fmt[strlen(fmt) - 1] !='\n')
int GetDatabaseEncoding(void)
Definition: mbutils.c:1268
int SetClientEncoding(int encoding)
Definition: mbutils.c:209
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
MemoryContext TopTransactionContext
Definition: mcxt.c:146
char * pstrdup(const char *in)
Definition: mcxt.c:1644
void pfree(void *pointer)
Definition: mcxt.c:1456
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void * palloc0(Size size)
Definition: mcxt.c:1257
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021
#define AllocSetContextCreate
Definition: memutils.h:126
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:150
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
void SerializeClientConnectionInfo(Size maxsize, char *start_address)
Definition: miscinit.c:1037
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:861
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:630
Size EstimateClientConnectionInfoSpace(void)
Definition: miscinit.c:1021
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:939
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:578
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1004
void RestoreClientConnectionInfo(char *conninfo)
Definition: miscinit.c:1069
Oid GetCurrentRoleId(void)
Definition: miscinit.c:918
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:637
void GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
Definition: namespace.c:3746
void SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
Definition: namespace.c:3762
void _bt_parallel_build_main(dsm_segment *seg, shm_toc *toc)
Definition: nbtsort.c:1800
@ DEBUG_PARALLEL_REGRESS
Definition: optimizer.h:107
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
void * arg
const void * data
void RestoreUncommittedEnums(void *space)
Definition: pg_enum.c:770
Size EstimateUncommittedEnumsSpace(void)
Definition: pg_enum.c:724
void SerializeUncommittedEnums(void *space, Size size)
Definition: pg_enum.c:738
#define die(msg)
int debug_parallel_query
Definition: planner.c:73
#define sprintf
Definition: port.h:240
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define snprintf
Definition: port.h:238
static uint32 DatumGetUInt32(Datum X)
Definition: postgres.h:222
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
static Datum UInt32GetDatum(uint32 X)
Definition: postgres.h:232
unsigned int Oid
Definition: postgres_ext.h:31
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5636
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5596
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:418
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:638
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:299
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:402
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:456
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:611
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
void pq_set_parallel_leader(pid_t pid, BackendId backend_id)
Definition: pqmq.c:78
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition: pqmq.c:216
void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
Definition: pqmq.c:53
void AttachSerializableXact(SerializableXactHandle handle)
Definition: predicate.c:5006
SerializableXactHandle ShareSerializableXact(void)
Definition: predicate.c:4997
void * SerializableXactHandle
Definition: predicate.h:37
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:262
@ PROCSIG_PARALLEL_MESSAGE
Definition: procsignal.h:34
#define PqMsg_NotificationResponse
Definition: protocol.h:41
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_ErrorResponse
Definition: protocol.h:44
#define PqMsg_NoticeResponse
Definition: protocol.h:49
#define PqMsg_Terminate
Definition: protocol.h:28
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Size EstimateRelationMapSpace(void)
Definition: relmapper.c:711
void SerializeRelationMap(Size maxSize, char *startAddress)
Definition: relmapper.c:722
void RestoreRelationMap(char *startAddress)
Definition: relmapper.c:739
int slock_t
Definition: s_lock.h:754
void DetachSession(void)
Definition: session.c:201
void AttachSession(dsm_handle handle)
Definition: session.c:155
dsm_handle GetSessionDsmHandle(void)
Definition: session.c:70
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:291
shm_mq * shm_mq_get_queue(shm_mq_handle *mqh)
Definition: shm_mq.c:906
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:225
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:320
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:178
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:844
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:207
PGPROC * shm_mq_get_sender(shm_mq *mq)
Definition: shm_mq.c:258
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition: shm_mq.c:573
shm_mq_result
Definition: shm_mq.h:37
@ SHM_MQ_SUCCESS
Definition: shm_mq.h:38
@ SHM_MQ_WOULD_BLOCK
Definition: shm_mq.h:39
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition: shm_toc.c:64
shm_toc * shm_toc_create(uint64 magic, void *address, Size nbytes)
Definition: shm_toc.c:40
Size shm_toc_estimate(shm_toc_estimator *e)
Definition: shm_toc.c:263
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#define shm_toc_initialize_estimator(e)
Definition: shm_toc.h:49
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
void SerializeSnapshot(Snapshot snapshot, char *start_address)
Definition: snapmgr.c:1722
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:223
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:655
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:1781
void RestoreTransactionSnapshot(Snapshot snapshot, void *source_pgproc)
Definition: snapmgr.c:1846
void PopActiveSnapshot(void)
Definition: snapmgr.c:750
Size EstimateSnapshotSpace(Snapshot snapshot)
Definition: snapmgr.c:1698
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:777
#define SpinLockInit(lock)
Definition: spin.h:60
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
PGPROC * MyProc
Definition: proc.c:66
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:1862
void BecomeLockGroupLeader(void)
Definition: proc.c:1832
void SerializePendingSyncs(Size maxSize, char *startAddress)
Definition: storage.c:577
Size EstimatePendingSyncsSpace(void)
Definition: storage.c:564
void RestorePendingSyncs(char *startAddress)
Definition: storage.c:628
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:233
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
Datum bgw_main_arg
Definition: bgworker.h:98
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
int bgw_restart_time
Definition: bgworker.h:95
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:99
pid_t bgw_notify_pid
Definition: bgworker.h:100
char bgw_library_name[MAXPGPATH]
Definition: bgworker.h:96
const char * authn_id
Definition: libpq-be.h:114
UserAuth auth_method
Definition: libpq-be.h:120
char * context
Definition: elog.h:443
int elevel
Definition: elog.h:428
Oid temp_toast_namespace_id
Definition: parallel.c:91
XLogRecPtr last_xlog_end
Definition: parallel.c:105
TimestampTz stmt_ts
Definition: parallel.c:98
SerializableXactHandle serializable_xact_handle
Definition: parallel.c:99
TimestampTz xact_ts
Definition: parallel.c:97
PGPROC * parallel_leader_pgproc
Definition: parallel.c:94
pid_t parallel_leader_pid
Definition: parallel.c:95
BackendId parallel_leader_backend_id
Definition: parallel.c:96
Oid authenticated_user_id
Definition: parallel.c:87
Definition: proc.h:162
char * library_name
Definition: parallel.h:39
dsm_segment * seg
Definition: parallel.h:43
bool * known_attached_workers
Definition: parallel.h:48
ErrorContextCallback * error_context_stack
Definition: parallel.h:41
SubTransactionId subid
Definition: parallel.h:35
shm_toc_estimator estimator
Definition: parallel.h:42
int nknown_attached_workers
Definition: parallel.h:47
ParallelWorkerInfo * worker
Definition: parallel.h:46
shm_toc * toc
Definition: parallel.h:45
dlist_node node
Definition: parallel.h:34
void * private_memory
Definition: parallel.h:44
int nworkers_launched
Definition: parallel.h:38
int nworkers_to_launch
Definition: parallel.h:37
char * function_name
Definition: parallel.h:40
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
shm_mq_handle * error_mqh
Definition: parallel.h:28
dlist_node * cur
Definition: ilist.h:179
Definition: type.h:95
Definition: shm_mq.c:73
void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc)
void SerializeTransactionState(Size maxsize, char *start_address)
Definition: xact.c:5385
void ExitParallelMode(void)
Definition: xact.c:1049
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:780
void EnterParallelMode(void)
Definition: xact.c:1036
Size EstimateTransactionStateSpace(void)
Definition: xact.c:5357
void StartTransactionCommand(void)
Definition: xact.c:2937
void StartParallelWorkerTransaction(char *tstatespace)
Definition: xact.c:5456
void SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
Definition: xact.c:844
bool IsInParallelMode(void)
Definition: xact.c:1069
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:864
TimestampTz GetCurrentTransactionStartTimestamp(void)
Definition: xact.c:855
void EndParallelWorkerTransaction(void)
Definition: xact.c:5481
void CommitTransactionCommand(void)
Definition: xact.c:3034
#define IsolationUsesXactSnapshot()
Definition: xact.h:51
XLogRecPtr XactLastRecEnd
Definition: xlog.c:257
uint64 XLogRecPtr
Definition: xlogdefs.h:21