PostgreSQL Source Code  git master
parallel.h File Reference
#include "access/xlogdefs.h"
#include "lib/ilist.h"
#include "postmaster/bgworker.h"
#include "storage/shm_mq.h"
#include "storage/shm_toc.h"
Include dependency graph for parallel.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  ParallelWorkerInfo
 
struct  ParallelContext
 
struct  ParallelWorkerContext
 

Macros

#define IsParallelWorker()   (ParallelWorkerNumber >= 0)
 

Typedefs

typedef void(* parallel_worker_main_type) (dsm_segment *seg, shm_toc *toc)
 
typedef struct ParallelWorkerInfo ParallelWorkerInfo
 
typedef struct ParallelContext ParallelContext
 
typedef struct ParallelWorkerContext ParallelWorkerContext
 

Functions

ParallelContextCreateParallelContext (const char *library_name, const char *function_name, int nworkers)
 
void InitializeParallelDSM (ParallelContext *pcxt)
 
void ReinitializeParallelDSM (ParallelContext *pcxt)
 
void LaunchParallelWorkers (ParallelContext *pcxt)
 
void WaitForParallelWorkersToAttach (ParallelContext *pcxt)
 
void WaitForParallelWorkersToFinish (ParallelContext *pcxt)
 
void DestroyParallelContext (ParallelContext *pcxt)
 
bool ParallelContextActive (void)
 
void HandleParallelMessageInterrupt (void)
 
void HandleParallelMessages (void)
 
void AtEOXact_Parallel (bool isCommit)
 
void AtEOSubXact_Parallel (bool isCommit, SubTransactionId mySubId)
 
void ParallelWorkerReportLastRecEnd (XLogRecPtr last_xlog_end)
 
void ParallelWorkerMain (Datum main_arg)
 

Variables

volatile bool ParallelMessagePending
 
PGDLLIMPORT int ParallelWorkerNumber
 
PGDLLIMPORT bool InitializingParallelWorker
 

Macro Definition Documentation

◆ IsParallelWorker

Typedef Documentation

◆ parallel_worker_main_type

typedef void(* parallel_worker_main_type) (dsm_segment *seg, shm_toc *toc)

Definition at line 23 of file parallel.h.

◆ ParallelContext

◆ ParallelWorkerContext

◆ ParallelWorkerInfo

Function Documentation

◆ AtEOSubXact_Parallel()

void AtEOSubXact_Parallel ( bool  isCommit,
SubTransactionId  mySubId 
)

Definition at line 1170 of file parallel.c.

References DestroyParallelContext(), dlist_head_element, dlist_is_empty(), elog, ParallelContext::subid, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

1171 {
1172  while (!dlist_is_empty(&pcxt_list))
1173  {
1174  ParallelContext *pcxt;
1175 
1177  if (pcxt->subid != mySubId)
1178  break;
1179  if (isCommit)
1180  elog(WARNING, "leaked parallel context");
1181  DestroyParallelContext(pcxt);
1182  }
1183 }
SubTransactionId subid
Definition: parallel.h:35
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:871
#define WARNING
Definition: elog.h:40
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:487
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define elog(elevel,...)
Definition: elog.h:226
static dlist_head pcxt_list
Definition: parallel.c:122

◆ AtEOXact_Parallel()

void AtEOXact_Parallel ( bool  isCommit)

Definition at line 1189 of file parallel.c.

References DestroyParallelContext(), dlist_head_element, dlist_is_empty(), elog, and WARNING.

Referenced by AbortTransaction(), and CommitTransaction().

1190 {
1191  while (!dlist_is_empty(&pcxt_list))
1192  {
1193  ParallelContext *pcxt;
1194 
1196  if (isCommit)
1197  elog(WARNING, "leaked parallel context");
1198  DestroyParallelContext(pcxt);
1199  }
1200 }
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:871
#define WARNING
Definition: elog.h:40
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:487
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define elog(elevel,...)
Definition: elog.h:226
static dlist_head pcxt_list
Definition: parallel.c:122

◆ CreateParallelContext()

ParallelContext* CreateParallelContext ( const char *  library_name,
const char *  function_name,
int  nworkers 
)

Definition at line 159 of file parallel.c.

References Assert, dlist_push_head(), ParallelContext::error_context_stack, error_context_stack, ParallelContext::estimator, ParallelContext::function_name, GetCurrentSubTransactionId(), IsInParallelMode(), ParallelContext::library_name, MemoryContextSwitchTo(), ParallelContext::node, ParallelContext::nworkers, palloc0(), pstrdup(), shm_toc_initialize_estimator, ParallelContext::subid, and TopTransactionContext.

Referenced by _bt_begin_parallel(), and ExecInitParallelPlan().

161 {
162  MemoryContext oldcontext;
163  ParallelContext *pcxt;
164 
165  /* It is unsafe to create a parallel context if not in parallel mode. */
167 
168  /* Number of workers should be non-negative. */
169  Assert(nworkers >= 0);
170 
171  /* We might be running in a short-lived memory context. */
173 
174  /* Initialize a new ParallelContext. */
175  pcxt = palloc0(sizeof(ParallelContext));
177  pcxt->nworkers = nworkers;
178  pcxt->library_name = pstrdup(library_name);
179  pcxt->function_name = pstrdup(function_name);
182  dlist_push_head(&pcxt_list, &pcxt->node);
183 
184  /* Restore previous memory context. */
185  MemoryContextSwitchTo(oldcontext);
186 
187  return pcxt;
188 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
char * pstrdup(const char *in)
Definition: mcxt.c:1161
shm_toc_estimator estimator
Definition: parallel.h:41
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubTransactionId subid
Definition: parallel.h:35
ErrorContextCallback * error_context_stack
Definition: elog.c:88
bool IsInParallelMode(void)
Definition: xact.c:994
char * function_name
Definition: parallel.h:39
#define shm_toc_initialize_estimator(e)
Definition: shm_toc.h:49
void * palloc0(Size size)
Definition: mcxt.c:955
char * library_name
Definition: parallel.h:38
#define Assert(condition)
Definition: c.h:732
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:708
dlist_node node
Definition: parallel.h:34
ErrorContextCallback * error_context_stack
Definition: parallel.h:40
static dlist_head pcxt_list
Definition: parallel.c:122

◆ DestroyParallelContext()

void DestroyParallelContext ( ParallelContext pcxt)

Definition at line 871 of file parallel.c.

References ParallelWorkerInfo::bgwhandle, dlist_delete(), dsm_detach(), ParallelWorkerInfo::error_mqh, ParallelContext::function_name, HOLD_INTERRUPTS, i, ParallelContext::library_name, ParallelContext::node, ParallelContext::nworkers_launched, pfree(), ParallelContext::private_memory, RESUME_INTERRUPTS, ParallelContext::seg, shm_mq_detach(), TerminateBackgroundWorker(), WaitForParallelWorkersToExit(), and ParallelContext::worker.

Referenced by _bt_end_parallel(), AtEOSubXact_Parallel(), AtEOXact_Parallel(), and ExecParallelCleanup().

872 {
873  int i;
874 
875  /*
876  * Be careful about order of operations here! We remove the parallel
877  * context from the list before we do anything else; otherwise, if an
878  * error occurs during a subsequent step, we might try to nuke it again
879  * from AtEOXact_Parallel or AtEOSubXact_Parallel.
880  */
881  dlist_delete(&pcxt->node);
882 
883  /* Kill each worker in turn, and forget their error queues. */
884  if (pcxt->worker != NULL)
885  {
886  for (i = 0; i < pcxt->nworkers_launched; ++i)
887  {
888  if (pcxt->worker[i].error_mqh != NULL)
889  {
891 
892  shm_mq_detach(pcxt->worker[i].error_mqh);
893  pcxt->worker[i].error_mqh = NULL;
894  }
895  }
896  }
897 
898  /*
899  * If we have allocated a shared memory segment, detach it. This will
900  * implicitly detach the error queues, and any other shared memory queues,
901  * stored there.
902  */
903  if (pcxt->seg != NULL)
904  {
905  dsm_detach(pcxt->seg);
906  pcxt->seg = NULL;
907  }
908 
909  /*
910  * If this parallel context is actually in backend-private memory rather
911  * than shared memory, free that memory instead.
912  */
913  if (pcxt->private_memory != NULL)
914  {
915  pfree(pcxt->private_memory);
916  pcxt->private_memory = NULL;
917  }
918 
919  /*
920  * We can't finish transaction commit or abort until all of the workers
921  * have exited. This means, in particular, that we can't respond to
922  * interrupts at this stage.
923  */
924  HOLD_INTERRUPTS();
927 
928  /* Free the worker array itself. */
929  if (pcxt->worker != NULL)
930  {
931  pfree(pcxt->worker);
932  pcxt->worker = NULL;
933  }
934 
935  /* Free memory. */
936  pfree(pcxt->library_name);
937  pfree(pcxt->function_name);
938  pfree(pcxt);
939 }
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:793
dsm_segment * seg
Definition: parallel.h:42
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:831
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:1031
char * function_name
Definition: parallel.h:39
shm_mq_handle * error_mqh
Definition: parallel.h:28
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int nworkers_launched
Definition: parallel.h:37
void TerminateBackgroundWorker(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1177
char * library_name
Definition: parallel.h:38
dlist_node node
Definition: parallel.h:34
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:664
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
int i
void * private_memory
Definition: parallel.h:43

◆ HandleParallelMessageInterrupt()

void HandleParallelMessageInterrupt ( void  )

Definition at line 958 of file parallel.c.

References InterruptPending, MyLatch, ParallelMessagePending, and SetLatch().

Referenced by procsignal_sigusr1_handler().

959 {
960  InterruptPending = true;
961  ParallelMessagePending = true;
962  SetLatch(MyLatch);
963 }
void SetLatch(Latch *latch)
Definition: latch.c:436
volatile bool ParallelMessagePending
Definition: parallel.c:113
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54

◆ HandleParallelMessages()

void HandleParallelMessages ( void  )

Definition at line 969 of file parallel.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, appendBinaryStringInfo(), dlist_iter::cur, StringInfoData::data, dlist_container, dlist_foreach, ereport, errcode(), errmsg(), ERROR, ParallelWorkerInfo::error_mqh, HandleParallelMessage(), HOLD_INTERRUPTS, i, initStringInfo(), MemoryContextReset(), MemoryContextSwitchTo(), ParallelContext::nworkers_launched, ParallelMessagePending, pfree(), RESUME_INTERRUPTS, shm_mq_receive(), SHM_MQ_SUCCESS, SHM_MQ_WOULD_BLOCK, TopMemoryContext, and ParallelContext::worker.

Referenced by ProcessInterrupts().

970 {
971  dlist_iter iter;
972  MemoryContext oldcontext;
973 
974  static MemoryContext hpm_context = NULL;
975 
976  /*
977  * This is invoked from ProcessInterrupts(), and since some of the
978  * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
979  * for recursive calls if more signals are received while this runs. It's
980  * unclear that recursive entry would be safe, and it doesn't seem useful
981  * even if it is safe, so let's block interrupts until done.
982  */
983  HOLD_INTERRUPTS();
984 
985  /*
986  * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
987  * don't want to risk leaking data into long-lived contexts, so let's do
988  * our work here in a private context that we can reset on each use.
989  */
990  if (hpm_context == NULL) /* first time through? */
992  "HandleParallelMessages",
994  else
995  MemoryContextReset(hpm_context);
996 
997  oldcontext = MemoryContextSwitchTo(hpm_context);
998 
999  /* OK to process messages. Reset the flag saying there are more to do. */
1000  ParallelMessagePending = false;
1001 
1002  dlist_foreach(iter, &pcxt_list)
1003  {
1004  ParallelContext *pcxt;
1005  int i;
1006 
1007  pcxt = dlist_container(ParallelContext, node, iter.cur);
1008  if (pcxt->worker == NULL)
1009  continue;
1010 
1011  for (i = 0; i < pcxt->nworkers_launched; ++i)
1012  {
1013  /*
1014  * Read as many messages as we can from each worker, but stop when
1015  * either (1) the worker's error queue goes away, which can happen
1016  * if we receive a Terminate message from the worker; or (2) no
1017  * more messages can be read from the worker without blocking.
1018  */
1019  while (pcxt->worker[i].error_mqh != NULL)
1020  {
1021  shm_mq_result res;
1022  Size nbytes;
1023  void *data;
1024 
1025  res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
1026  &data, true);
1027  if (res == SHM_MQ_WOULD_BLOCK)
1028  break;
1029  else if (res == SHM_MQ_SUCCESS)
1030  {
1031  StringInfoData msg;
1032 
1033  initStringInfo(&msg);
1034  appendBinaryStringInfo(&msg, data, nbytes);
1035  HandleParallelMessage(pcxt, i, &msg);
1036  pfree(msg.data);
1037  }
1038  else
1039  ereport(ERROR,
1040  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1041  errmsg("lost connection to parallel worker")));
1042  }
1043  }
1044  }
1045 
1046  MemoryContextSwitchTo(oldcontext);
1047 
1048  /* Might as well clear the context on our way out */
1049  MemoryContextReset(hpm_context);
1050 
1052 }
#define AllocSetContextCreate
Definition: memutils.h:169
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:570
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
volatile bool ParallelMessagePending
Definition: parallel.c:113
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
Definition: parallel.c:1058
shm_mq_handle * error_mqh
Definition: parallel.h:28
int nworkers_launched
Definition: parallel.h:37
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
dlist_node * cur
Definition: ilist.h:161
shm_mq_result
Definition: shm_mq.h:36
size_t Size
Definition: c.h:466
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
int i
static dlist_head pcxt_list
Definition: parallel.c:122
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition: shm_mq.c:540
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:214

◆ InitializeParallelDSM()

void InitializeParallelDSM ( ParallelContext pcxt)

Definition at line 196 of file parallel.c.

References FixedParallelState::authenticated_user_id, BUFFERALIGN, FixedParallelState::current_user_id, FixedParallelState::database_id, dsm_create(), DSM_CREATE_NULL_IF_MAXSEGMENTS, DSM_HANDLE_INVALID, dsm_segment_address(), ParallelWorkerInfo::error_mqh, EstimateComboCIDStateSpace(), EstimateEnumBlacklistSpace(), EstimateGUCStateSpace(), EstimateLibraryStateSpace(), EstimateReindexStateSpace(), EstimateRelationMapSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ParallelContext::estimator, ParallelContext::function_name, GetActiveSnapshot(), GetAuthenticatedUserId(), GetCurrentRoleId(), GetCurrentStatementStartTimestamp(), GetCurrentTransactionStartTimestamp(), GetSessionDsmHandle(), GetTempNamespaceState(), GetTransactionSnapshot(), GetUserIdAndSecContext(), i, FixedParallelState::is_superuser, FixedParallelState::last_xlog_end, ParallelContext::library_name, MemoryContextAlloc(), MemoryContextSwitchTo(), mul_size(), FixedParallelState::mutex, MyBackendId, MyDatabaseId, MyProc, MyProcPid, ParallelContext::nworkers, FixedParallelState::outer_user_id, palloc0(), PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ACTIVE_SNAPSHOT, PARALLEL_KEY_COMBO_CID, PARALLEL_KEY_ENTRYPOINT, PARALLEL_KEY_ENUMBLACKLIST, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_REINDEX_STATE, PARALLEL_KEY_RELMAPPER_STATE, PARALLEL_KEY_SESSION_DSM, PARALLEL_KEY_TRANSACTION_SNAPSHOT, PARALLEL_KEY_TRANSACTION_STATE, PARALLEL_MAGIC, FixedParallelState::parallel_master_backend_id, FixedParallelState::parallel_master_pgproc, FixedParallelState::parallel_master_pid, ParallelContext::private_memory, FixedParallelState::sec_context, ParallelContext::seg, FixedParallelState::serializable_xact_handle, SerializeComboCIDState(), SerializeEnumBlacklist(), SerializeGUCState(), SerializeLibraryState(), SerializeReindexState(), SerializeRelationMap(), SerializeSnapshot(), SerializeTransactionState(), session_auth_is_superuser, ShareSerializableXact(), shm_mq_attach(), shm_mq_create(), shm_mq_set_receiver(), shm_toc_allocate(), shm_toc_create(), shm_toc_estimate(), shm_toc_estimate_chunk, shm_toc_estimate_keys, shm_toc_insert(), SpinLockInit, StaticAssertStmt, FixedParallelState::stmt_ts, FixedParallelState::temp_namespace_id, FixedParallelState::temp_toast_namespace_id, ParallelContext::toc, TopMemoryContext, TopTransactionContext, ParallelContext::worker, and FixedParallelState::xact_ts.

Referenced by _bt_begin_parallel(), and ExecInitParallelPlan().

197 {
198  MemoryContext oldcontext;
199  Size library_len = 0;
200  Size guc_len = 0;
201  Size combocidlen = 0;
202  Size tsnaplen = 0;
203  Size asnaplen = 0;
204  Size tstatelen = 0;
205  Size reindexlen = 0;
206  Size relmapperlen = 0;
207  Size enumblacklistlen = 0;
208  Size segsize = 0;
209  int i;
210  FixedParallelState *fps;
211  dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
212  Snapshot transaction_snapshot = GetTransactionSnapshot();
213  Snapshot active_snapshot = GetActiveSnapshot();
214 
215  /* We might be running in a very short-lived memory context. */
217 
218  /* Allow space to store the fixed-size parallel state. */
220  shm_toc_estimate_keys(&pcxt->estimator, 1);
221 
222  /*
223  * Normally, the user will have requested at least one worker process, but
224  * if by chance they have not, we can skip a bunch of things here.
225  */
226  if (pcxt->nworkers > 0)
227  {
228  /* Get (or create) the per-session DSM segment's handle. */
229  session_dsm_handle = GetSessionDsmHandle();
230 
231  /*
232  * If we weren't able to create a per-session DSM segment, then we can
233  * continue but we can't safely launch any workers because their
234  * record typmods would be incompatible so they couldn't exchange
235  * tuples.
236  */
237  if (session_dsm_handle == DSM_HANDLE_INVALID)
238  pcxt->nworkers = 0;
239  }
240 
241  if (pcxt->nworkers > 0)
242  {
243  /* Estimate space for various kinds of state sharing. */
244  library_len = EstimateLibraryStateSpace();
245  shm_toc_estimate_chunk(&pcxt->estimator, library_len);
246  guc_len = EstimateGUCStateSpace();
247  shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
248  combocidlen = EstimateComboCIDStateSpace();
249  shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
250  tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
251  shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
252  asnaplen = EstimateSnapshotSpace(active_snapshot);
253  shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
254  tstatelen = EstimateTransactionStateSpace();
255  shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
257  reindexlen = EstimateReindexStateSpace();
258  shm_toc_estimate_chunk(&pcxt->estimator, reindexlen);
259  relmapperlen = EstimateRelationMapSpace();
260  shm_toc_estimate_chunk(&pcxt->estimator, relmapperlen);
261  enumblacklistlen = EstimateEnumBlacklistSpace();
262  shm_toc_estimate_chunk(&pcxt->estimator, enumblacklistlen);
263  /* If you add more chunks here, you probably need to add keys. */
264  shm_toc_estimate_keys(&pcxt->estimator, 10);
265 
266  /* Estimate space need for error queues. */
269  "parallel error queue size not buffer-aligned");
272  pcxt->nworkers));
273  shm_toc_estimate_keys(&pcxt->estimator, 1);
274 
275  /* Estimate how much we'll need for the entrypoint info. */
276  shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
277  strlen(pcxt->function_name) + 2);
278  shm_toc_estimate_keys(&pcxt->estimator, 1);
279  }
280 
281  /*
282  * Create DSM and initialize with new table of contents. But if the user
283  * didn't request any workers, then don't bother creating a dynamic shared
284  * memory segment; instead, just use backend-private memory.
285  *
286  * Also, if we can't create a dynamic shared memory segment because the
287  * maximum number of segments have already been created, then fall back to
288  * backend-private memory, and plan not to use any workers. We hope this
289  * won't happen very often, but it's better to abandon the use of
290  * parallelism than to fail outright.
291  */
292  segsize = shm_toc_estimate(&pcxt->estimator);
293  if (pcxt->nworkers > 0)
295  if (pcxt->seg != NULL)
297  dsm_segment_address(pcxt->seg),
298  segsize);
299  else
300  {
301  pcxt->nworkers = 0;
304  segsize);
305  }
306 
307  /* Initialize fixed-size state in shared memory. */
308  fps = (FixedParallelState *)
309  shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
310  fps->database_id = MyDatabaseId;
323  SpinLockInit(&fps->mutex);
324  fps->last_xlog_end = 0;
326 
327  /* We can skip the rest of this if we're not budgeting for any workers. */
328  if (pcxt->nworkers > 0)
329  {
330  char *libraryspace;
331  char *gucspace;
332  char *combocidspace;
333  char *tsnapspace;
334  char *asnapspace;
335  char *tstatespace;
336  char *reindexspace;
337  char *relmapperspace;
338  char *error_queue_space;
339  char *session_dsm_handle_space;
340  char *entrypointstate;
341  char *enumblacklistspace;
342  Size lnamelen;
343 
344  /* Serialize shared libraries we have loaded. */
345  libraryspace = shm_toc_allocate(pcxt->toc, library_len);
346  SerializeLibraryState(library_len, libraryspace);
347  shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
348 
349  /* Serialize GUC settings. */
350  gucspace = shm_toc_allocate(pcxt->toc, guc_len);
351  SerializeGUCState(guc_len, gucspace);
352  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
353 
354  /* Serialize combo CID state. */
355  combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
356  SerializeComboCIDState(combocidlen, combocidspace);
357  shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
358 
359  /* Serialize transaction snapshot and active snapshot. */
360  tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
361  SerializeSnapshot(transaction_snapshot, tsnapspace);
363  tsnapspace);
364  asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
365  SerializeSnapshot(active_snapshot, asnapspace);
366  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
367 
368  /* Provide the handle for per-session segment. */
369  session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
370  sizeof(dsm_handle));
371  *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
373  session_dsm_handle_space);
374 
375  /* Serialize transaction state. */
376  tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
377  SerializeTransactionState(tstatelen, tstatespace);
379 
380  /* Serialize reindex state. */
381  reindexspace = shm_toc_allocate(pcxt->toc, reindexlen);
382  SerializeReindexState(reindexlen, reindexspace);
383  shm_toc_insert(pcxt->toc, PARALLEL_KEY_REINDEX_STATE, reindexspace);
384 
385  /* Serialize relmapper state. */
386  relmapperspace = shm_toc_allocate(pcxt->toc, relmapperlen);
387  SerializeRelationMap(relmapperlen, relmapperspace);
389  relmapperspace);
390 
391  /* Serialize enum blacklist state. */
392  enumblacklistspace = shm_toc_allocate(pcxt->toc, enumblacklistlen);
393  SerializeEnumBlacklist(enumblacklistspace, enumblacklistlen);
395  enumblacklistspace);
396 
397  /* Allocate space for worker information. */
398  pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
399 
400  /*
401  * Establish error queues in dynamic shared memory.
402  *
403  * These queues should be used only for transmitting ErrorResponse,
404  * NoticeResponse, and NotifyResponse protocol messages. Tuple data
405  * should be transmitted via separate (possibly larger?) queues.
406  */
407  error_queue_space =
408  shm_toc_allocate(pcxt->toc,
410  pcxt->nworkers));
411  for (i = 0; i < pcxt->nworkers; ++i)
412  {
413  char *start;
414  shm_mq *mq;
415 
416  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
417  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
419  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
420  }
421  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
422 
423  /*
424  * Serialize entrypoint information. It's unsafe to pass function
425  * pointers across processes, as the function pointer may be different
426  * in each process in EXEC_BACKEND builds, so we always pass library
427  * and function name. (We use library name "postgres" for functions
428  * in the core backend.)
429  */
430  lnamelen = strlen(pcxt->library_name);
431  entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
432  strlen(pcxt->function_name) + 2);
433  strcpy(entrypointstate, pcxt->library_name);
434  strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
435  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
436  }
437 
438  /* Restore previous memory context. */
439  MemoryContextSwitchTo(oldcontext);
440 }
void SerializeEnumBlacklist(void *space, Size size)
Definition: pg_enum.c:710
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:54
shm_toc * shm_toc_create(uint64 magic, void *address, Size nbytes)
Definition: shm_toc.c:40
int MyProcPid
Definition: globals.c:40
BackendId MyBackendId
Definition: globals.c:81
MemoryContext TopTransactionContext
Definition: mcxt.c:49
uint32 dsm_handle
Definition: dsm_impl.h:54
PGPROC * MyProc
Definition: proc.c:68
dsm_segment * seg
Definition: parallel.h:42
void SerializeReindexState(Size maxsize, char *start_address)
Definition: index.c:3786
shm_toc_estimator estimator
Definition: parallel.h:41
#define SpinLockInit(lock)
Definition: spin.h:60
void GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
Definition: namespace.c:3305
Oid authenticated_user_id
Definition: parallel.c:83
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
#define PARALLEL_KEY_ENUMBLACKLIST
Definition: parallel.c:76
PGPROC * parallel_master_pgproc
Definition: parallel.c:90
Oid temp_toast_namespace_id
Definition: parallel.c:87
#define PARALLEL_KEY_RELMAPPER_STATE
Definition: parallel.c:75
Size shm_toc_estimate(shm_toc_estimator *e)
Definition: shm_toc.c:263
void SerializeTransactionState(Size maxsize, char *start_address)
Definition: xact.c:5179
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
Oid GetCurrentRoleId(void)
Definition: miscinit.c:739
SerializableXactHandle serializable_xact_handle
Definition: parallel.c:95
#define DSM_HANDLE_INVALID
Definition: dsm.h:23
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:842
ParallelWorkerInfo * worker
Definition: parallel.h:45
void SerializeLibraryState(Size maxsize, char *start_address)
Definition: dfmgr.c:736
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:439
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:69
char * function_name
Definition: parallel.h:39
void SerializeSnapshot(Snapshot snapshot, char *start_address)
Definition: snapmgr.c:2102
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:169
#define PARALLEL_KEY_FIXED
Definition: parallel.c:64
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:65
#define DSM_CREATE_NULL_IF_MAXSEGMENTS
Definition: dsm.h:20
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:485
shm_mq_handle * error_mqh
Definition: parallel.h:28
#define PARALLEL_KEY_GUC
Definition: parallel.c:67
void SerializeRelationMap(Size maxSize, char *startAddress)
Definition: relmapper.c:657
Size EstimateGUCStateSpace(void)
Definition: guc.c:10011
Size EstimateComboCIDStateSpace(void)
Definition: combocid.c:299
XLogRecPtr last_xlog_end
Definition: parallel.c:101
Size EstimateEnumBlacklistSpace(void)
Definition: pg_enum.c:696
Size EstimateReindexStateSpace(void)
Definition: index.c:3775
MemoryContext TopMemoryContext
Definition: mcxt.c:44
TimestampTz GetCurrentTransactionStartTimestamp(void)
Definition: xact.c:783
Size EstimateSnapshotSpace(Snapshot snap)
Definition: snapmgr.c:2078
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
void * palloc0(Size size)
Definition: mcxt.c:955
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:437
Oid MyDatabaseId
Definition: globals.c:85
pid_t parallel_master_pid
Definition: parallel.c:91
Size EstimateLibraryStateSpace(void)
Definition: dfmgr.c:719
#define PARALLEL_MAGIC
Definition: parallel.c:57
TimestampTz xact_ts
Definition: parallel.c:93
char * library_name
Definition: parallel.h:38
BackendId parallel_master_backend_id
Definition: parallel.c:92
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:938
Size EstimateTransactionStateSpace(void)
Definition: xact.c:5151
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:74
size_t Size
Definition: c.h:466
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
Size EstimateRelationMapSpace(void)
Definition: relmapper.c:646
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:282
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:71
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
TimestampTz stmt_ts
Definition: parallel.c:94
Definition: shm_mq.c:70
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:73
#define BUFFERALIGN(LEN)
Definition: c.h:687
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:198
dsm_handle GetSessionDsmHandle(void)
Definition: session.c:70
bool session_auth_is_superuser
Definition: guc.c:507
SerializableXactHandle ShareSerializableXact(void)
Definition: predicate.c:5183
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:72
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:68
void SerializeGUCState(Size maxsize, char *start_address)
Definition: guc.c:10153
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:70
void SerializeComboCIDState(Size maxsize, char *start_address)
Definition: combocid.c:318
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:66
shm_toc * toc
Definition: parallel.h:44
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:792
void * private_memory
Definition: parallel.h:43

◆ LaunchParallelWorkers()

void LaunchParallelWorkers ( ParallelContext pcxt)

Definition at line 494 of file parallel.c.

References Assert, BecomeLockGroupLeader(), BackgroundWorker::bgw_extra, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BGW_MAXLEN, BackgroundWorker::bgw_name, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, ParallelWorkerInfo::bgwhandle, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_CLASS_PARALLEL, BGWORKER_SHMEM_ACCESS, BgWorkerStart_ConsistentState, dsm_segment_handle(), ParallelWorkerInfo::error_mqh, i, ParallelContext::known_attached_workers, MemoryContextSwitchTo(), MyProcPid, ParallelContext::nknown_attached_workers, ParallelContext::nworkers, ParallelContext::nworkers_launched, palloc0(), RegisterDynamicBackgroundWorker(), ParallelContext::seg, shm_mq_detach(), shm_mq_set_handle(), snprintf, sprintf, TopTransactionContext, UInt32GetDatum, and ParallelContext::worker.

Referenced by _bt_begin_parallel(), ExecGather(), and ExecGatherMerge().

495 {
496  MemoryContext oldcontext;
497  BackgroundWorker worker;
498  int i;
499  bool any_registrations_failed = false;
500 
501  /* Skip this if we have no workers. */
502  if (pcxt->nworkers == 0)
503  return;
504 
505  /* We need to be a lock group leader. */
507 
508  /* If we do have workers, we'd better have a DSM segment. */
509  Assert(pcxt->seg != NULL);
510 
511  /* We might be running in a short-lived memory context. */
513 
514  /* Configure a worker. */
515  memset(&worker, 0, sizeof(worker));
516  snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
517  MyProcPid);
518  snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
519  worker.bgw_flags =
524  sprintf(worker.bgw_library_name, "postgres");
525  sprintf(worker.bgw_function_name, "ParallelWorkerMain");
527  worker.bgw_notify_pid = MyProcPid;
528 
529  /*
530  * Start workers.
531  *
532  * The caller must be able to tolerate ending up with fewer workers than
533  * expected, so there is no need to throw an error here if registration
534  * fails. It wouldn't help much anyway, because registering the worker in
535  * no way guarantees that it will start up and initialize successfully.
536  */
537  for (i = 0; i < pcxt->nworkers; ++i)
538  {
539  memcpy(worker.bgw_extra, &i, sizeof(int));
540  if (!any_registrations_failed &&
542  &pcxt->worker[i].bgwhandle))
543  {
545  pcxt->worker[i].bgwhandle);
546  pcxt->nworkers_launched++;
547  }
548  else
549  {
550  /*
551  * If we weren't able to register the worker, then we've bumped up
552  * against the max_worker_processes limit, and future
553  * registrations will probably fail too, so arrange to skip them.
554  * But we still have to execute this code for the remaining slots
555  * to make sure that we forget about the error queues we budgeted
556  * for those workers. Otherwise, we'll wait for them to start,
557  * but they never will.
558  */
559  any_registrations_failed = true;
560  pcxt->worker[i].bgwhandle = NULL;
561  shm_mq_detach(pcxt->worker[i].error_mqh);
562  pcxt->worker[i].error_mqh = NULL;
563  }
564  }
565 
566  /*
567  * Now that nworkers_launched has taken its final value, we can initialize
568  * known_attached_workers.
569  */
570  if (pcxt->nworkers_launched > 0)
571  {
572  pcxt->known_attached_workers =
573  palloc0(sizeof(bool) * pcxt->nworkers_launched);
574  pcxt->nknown_attached_workers = 0;
575  }
576 
577  /* Restore previous memory context. */
578  MemoryContextSwitchTo(oldcontext);
579 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
int MyProcPid
Definition: globals.c:40
MemoryContext TopTransactionContext
Definition: mcxt.c:49
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:793
dsm_segment * seg
Definition: parallel.h:42
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:966
int bgw_restart_time
Definition: bgworker.h:94
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
int nknown_attached_workers
Definition: parallel.h:46
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
#define sprintf
Definition: port.h:194
ParallelWorkerInfo * worker
Definition: parallel.h:45
Datum bgw_main_arg
Definition: bgworker.h:97
shm_mq_handle * error_mqh
Definition: parallel.h:28
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define UInt32GetDatum(X)
Definition: postgres.h:493
int nworkers_launched
Definition: parallel.h:37
void BecomeLockGroupLeader(void)
Definition: proc.c:1849
bool * known_attached_workers
Definition: parallel.h:47
void * palloc0(Size size)
Definition: mcxt.c:955
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:310
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:732
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:932
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
pid_t bgw_notify_pid
Definition: bgworker.h:99
int i
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define snprintf
Definition: port.h:192

◆ ParallelContextActive()

bool ParallelContextActive ( void  )

Definition at line 945 of file parallel.c.

References dlist_is_empty().

Referenced by AtPrepare_PredicateLocks(), ExitParallelMode(), and ReleasePredicateLocks().

946 {
947  return !dlist_is_empty(&pcxt_list);
948 }
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static dlist_head pcxt_list
Definition: parallel.c:122

◆ ParallelWorkerMain()

void ParallelWorkerMain ( Datum  main_arg)

Definition at line 1206 of file parallel.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, AttachSerializableXact(), AttachSession(), FixedParallelState::authenticated_user_id, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), BecomeLockGroupMember(), BackgroundWorker::bgw_extra, CommitTransactionCommand(), FixedParallelState::current_user_id, CurrentMemoryContext, FixedParallelState::database_id, DatumGetUInt32, DetachSession(), die, dsm_attach(), dsm_segment_address(), EndParallelWorkerTransaction(), EnterParallelMode(), ereport, errcode(), errmsg(), ERROR, ExitParallelMode(), GetDatabaseEncoding(), InitializingParallelWorker, InvalidateSystemCaches(), FixedParallelState::is_superuser, LookupParallelWorkerFunction(), MyBgworkerEntry, MyCancelKey, MyProc, MyProcPid, on_shmem_exit(), FixedParallelState::outer_user_id, PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ACTIVE_SNAPSHOT, PARALLEL_KEY_COMBO_CID, PARALLEL_KEY_ENTRYPOINT, PARALLEL_KEY_ENUMBLACKLIST, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_REINDEX_STATE, PARALLEL_KEY_RELMAPPER_STATE, PARALLEL_KEY_SESSION_DSM, PARALLEL_KEY_TRANSACTION_SNAPSHOT, PARALLEL_KEY_TRANSACTION_STATE, PARALLEL_MAGIC, FixedParallelState::parallel_master_backend_id, FixedParallelState::parallel_master_pgproc, FixedParallelState::parallel_master_pid, ParallelMasterBackendId, ParallelMasterPid, ParallelWorkerNumber, ParallelWorkerShutdown(), PopActiveSnapshot(), pq_beginmessage(), pq_endmessage(), pq_putmessage, pq_redirect_to_shm_mq(), pq_sendint32(), pq_set_parallel_master(), pqsignal(), PushActiveSnapshot(), RestoreComboCIDState(), RestoreEnumBlacklist(), RestoreGUCState(), RestoreLibraryState(), RestoreReindexState(), RestoreRelationMap(), RestoreSnapshot(), RestoreTransactionSnapshot(), FixedParallelState::sec_context, FixedParallelState::serializable_xact_handle, SetClientEncoding(), SetCurrentRoleId(), SetParallelStartTimestamps(), SetTempNamespaceState(), SetUserIdAndSecContext(), shm_mq_attach(), shm_mq_set_sender(), shm_toc_attach(), shm_toc_lookup(), StartParallelWorkerTransaction(), StartTransactionCommand(), FixedParallelState::stmt_ts, FixedParallelState::temp_namespace_id, FixedParallelState::temp_toast_namespace_id, TopMemoryContext, and FixedParallelState::xact_ts.

1207 {
1208  dsm_segment *seg;
1209  shm_toc *toc;
1210  FixedParallelState *fps;
1211  char *error_queue_space;
1212  shm_mq *mq;
1213  shm_mq_handle *mqh;
1214  char *libraryspace;
1215  char *entrypointstate;
1216  char *library_name;
1217  char *function_name;
1218  parallel_worker_main_type entrypt;
1219  char *gucspace;
1220  char *combocidspace;
1221  char *tsnapspace;
1222  char *asnapspace;
1223  char *tstatespace;
1224  char *reindexspace;
1225  char *relmapperspace;
1226  char *enumblacklistspace;
1227  StringInfoData msgbuf;
1228  char *session_dsm_handle_space;
1229 
1230  /* Set flag to indicate that we're initializing a parallel worker. */
1232 
1233  /* Establish signal handlers. */
1234  pqsignal(SIGTERM, die);
1236 
1237  /* Determine and set our parallel worker number. */
1239  memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
1240 
1241  /* Set up a memory context to work in, just for cleanliness. */
1243  "Parallel worker",
1245 
1246  /*
1247  * Attach to the dynamic shared memory segment for the parallel query, and
1248  * find its table of contents.
1249  *
1250  * Note: at this point, we have not created any ResourceOwner in this
1251  * process. This will result in our DSM mapping surviving until process
1252  * exit, which is fine. If there were a ResourceOwner, it would acquire
1253  * ownership of the mapping, but we have no need for that.
1254  */
1255  seg = dsm_attach(DatumGetUInt32(main_arg));
1256  if (seg == NULL)
1257  ereport(ERROR,
1258  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1259  errmsg("could not map dynamic shared memory segment")));
1261  if (toc == NULL)
1262  ereport(ERROR,
1263  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1264  errmsg("invalid magic number in dynamic shared memory segment")));
1265 
1266  /* Look up fixed parallel state. */
1267  fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1268  MyFixedParallelState = fps;
1269 
1270  /* Arrange to signal the leader if we exit. */
1274 
1275  /*
1276  * Now we can find and attach to the error queue provided for us. That's
1277  * good, because until we do that, any errors that happen here will not be
1278  * reported back to the process that requested that this worker be
1279  * launched.
1280  */
1281  error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1282  mq = (shm_mq *) (error_queue_space +
1285  mqh = shm_mq_attach(mq, seg, NULL);
1286  pq_redirect_to_shm_mq(seg, mqh);
1289 
1290  /*
1291  * Send a BackendKeyData message to the process that initiated parallelism
1292  * so that it has access to our PID before it receives any other messages
1293  * from us. Our cancel key is sent, too, since that's the way the
1294  * protocol message is defined, but it won't actually be used for anything
1295  * in this case.
1296  */
1297  pq_beginmessage(&msgbuf, 'K');
1298  pq_sendint32(&msgbuf, (int32) MyProcPid);
1299  pq_sendint32(&msgbuf, (int32) MyCancelKey);
1300  pq_endmessage(&msgbuf);
1301 
1302  /*
1303  * Hooray! Primary initialization is complete. Now, we need to set up our
1304  * backend-local state to match the original backend.
1305  */
1306 
1307  /*
1308  * Join locking group. We must do this before anything that could try to
1309  * acquire a heavyweight lock, because any heavyweight locks acquired to
1310  * this point could block either directly against the parallel group
1311  * leader or against some process which in turn waits for a lock that
1312  * conflicts with the parallel group leader, causing an undetected
1313  * deadlock. (If we can't join the lock group, the leader has gone away,
1314  * so just exit quietly.)
1315  */
1317  fps->parallel_master_pid))
1318  return;
1319 
1320  /*
1321  * Restore transaction and statement start-time timestamps. This must
1322  * happen before anything that would start a transaction, else asserts in
1323  * xact.c will fire.
1324  */
1326 
1327  /*
1328  * Identify the entry point to be called. In theory this could result in
1329  * loading an additional library, though most likely the entry point is in
1330  * the core backend or in a library we just loaded.
1331  */
1332  entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1333  library_name = entrypointstate;
1334  function_name = entrypointstate + strlen(library_name) + 1;
1335 
1336  entrypt = LookupParallelWorkerFunction(library_name, function_name);
1337 
1338  /* Restore database connection. */
1340  fps->authenticated_user_id,
1341  0);
1342 
1343  /*
1344  * Set the client encoding to the database encoding, since that is what
1345  * the leader will expect.
1346  */
1348 
1349  /*
1350  * Load libraries that were loaded by original backend. We want to do
1351  * this before restoring GUCs, because the libraries might define custom
1352  * variables.
1353  */
1354  libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1356  RestoreLibraryState(libraryspace);
1357 
1358  /* Restore GUC values from launching backend. */
1359  gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1360  RestoreGUCState(gucspace);
1362 
1363  /* Crank up a transaction state appropriate to a parallel worker. */
1364  tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1365  StartParallelWorkerTransaction(tstatespace);
1366 
1367  /* Restore combo CID state. */
1368  combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1369  RestoreComboCIDState(combocidspace);
1370 
1371  /* Attach to the per-session DSM segment and contained objects. */
1372  session_dsm_handle_space =
1374  AttachSession(*(dsm_handle *) session_dsm_handle_space);
1375 
1376  /* Restore transaction snapshot. */
1377  tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, false);
1379  fps->parallel_master_pgproc);
1380 
1381  /* Restore active snapshot. */
1382  asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1383  PushActiveSnapshot(RestoreSnapshot(asnapspace));
1384 
1385  /*
1386  * We've changed which tuples we can see, and must therefore invalidate
1387  * system caches.
1388  */
1390 
1391  /*
1392  * Restore current role id. Skip verifying whether session user is
1393  * allowed to become this role and blindly restore the leader's state for
1394  * current role.
1395  */
1397 
1398  /* Restore user ID and security context. */
1400 
1401  /* Restore temp-namespace state to ensure search path matches leader's. */
1404 
1405  /* Restore reindex state. */
1406  reindexspace = shm_toc_lookup(toc, PARALLEL_KEY_REINDEX_STATE, false);
1407  RestoreReindexState(reindexspace);
1408 
1409  /* Restore relmapper state. */
1410  relmapperspace = shm_toc_lookup(toc, PARALLEL_KEY_RELMAPPER_STATE, false);
1411  RestoreRelationMap(relmapperspace);
1412 
1413  /* Restore enum blacklist. */
1414  enumblacklistspace = shm_toc_lookup(toc, PARALLEL_KEY_ENUMBLACKLIST,
1415  false);
1416  RestoreEnumBlacklist(enumblacklistspace);
1417 
1418  /* Attach to the leader's serializable transaction, if SERIALIZABLE. */
1420 
1421  /*
1422  * We've initialized all of our state now; nothing should change
1423  * hereafter.
1424  */
1427 
1428  /*
1429  * Time to do the real work: invoke the caller-supplied code.
1430  */
1431  entrypt(seg, toc);
1432 
1433  /* Must exit parallel mode to pop active snapshot. */
1434  ExitParallelMode();
1435 
1436  /* Must pop active snapshot so snapmgr.c doesn't complain. */
1438 
1439  /* Shut down the parallel-worker transaction. */
1441 
1442  /* Detach from the per-session DSM segment. */
1443  DetachSession();
1444 
1445  /* Report success. */
1446  pq_putmessage('X', NULL, 0);
1447 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
#define DatumGetUInt32(X)
Definition: postgres.h:486
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:54
#define AllocSetContextCreate
Definition: memutils.h:169
int MyProcPid
Definition: globals.c:40
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:2161
uint32 dsm_handle
Definition: dsm_impl.h:54
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:492
void AttachSerializableXact(SerializableXactHandle handle)
Definition: predicate.c:5192
PGPROC * MyProc
Definition: proc.c:68
void CommitTransactionCommand(void)
Definition: xact.c:2895
void EndParallelWorkerTransaction(void)
Definition: xact.c:5274
void RestoreTransactionSnapshot(Snapshot snapshot, void *master_pgproc)
Definition: snapmgr.c:2225
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:533
Oid authenticated_user_id
Definition: parallel.c:83
#define PARALLEL_KEY_ENUMBLACKLIST
Definition: parallel.c:76
int errcode(int sqlerrcode)
Definition: elog.c:570
PGPROC * parallel_master_pgproc
Definition: parallel.c:90
Oid temp_toast_namespace_id
Definition: parallel.c:87
void DetachSession(void)
Definition: session.c:201
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:1879
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define PARALLEL_KEY_RELMAPPER_STATE
Definition: parallel.c:75
void InvalidateSystemCaches(void)
Definition: inval.c:643
static pid_t ParallelMasterPid
Definition: parallel.c:125
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:346
SerializableXactHandle serializable_xact_handle
Definition: parallel.c:95
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define ERROR
Definition: elog.h:43
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:69
int32 MyCancelKey
Definition: globals.c:44
void ExitParallelMode(void)
Definition: xact.c:974
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
#define PARALLEL_KEY_FIXED
Definition: parallel.c:64
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:65
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
void SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
Definition: namespace.c:3321
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define PARALLEL_KEY_GUC
Definition: parallel.c:67
int SetClientEncoding(int encoding)
Definition: mbutils.c:201
int ParallelWorkerNumber
Definition: parallel.c:110
void AttachSession(dsm_handle handle)
Definition: session.c:155
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static void ParallelWorkerShutdown(int code, Datum arg)
Definition: parallel.c:1472
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:216
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
Definition: parallel.c:1498
void RestoreLibraryState(char *start_address)
Definition: dfmgr.c:758
uintptr_t Datum
Definition: postgres.h:367
void RestoreEnumBlacklist(void *space)
Definition: pg_enum.c:742
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition: shm_toc.c:64
int GetDatabaseEncoding(void)
Definition: mbutils.c:996
pid_t parallel_master_pid
Definition: parallel.c:91
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5661
#define PARALLEL_MAGIC
Definition: parallel.c:57
void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
Definition: pqmq.c:55
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimestampTz xact_ts
Definition: parallel.c:93
BackendId parallel_master_backend_id
Definition: parallel.c:92
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:938
#define Assert(condition)
Definition: c.h:732
BackendId ParallelMasterBackendId
Definition: globals.c:83
void StartParallelWorkerTransaction(char *tstatespace)
Definition: xact.c:5249
void StartTransactionCommand(void)
Definition: xact.c:2794
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:74
void EnterParallelMode(void)
Definition: xact.c:961
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:282
void pq_set_parallel_master(pid_t pid, BackendId backend_id)
Definition: pqmq.c:80
void SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
Definition: xact.c:772
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:71
void RestoreReindexState(void *reindexstate)
Definition: index.c:3804
int errmsg(const char *fmt,...)
Definition: elog.c:784
void(* parallel_worker_main_type)(dsm_segment *seg, shm_toc *toc)
Definition: parallel.h:23
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:119
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:760
bool InitializingParallelWorker
Definition: parallel.c:116
TimestampTz stmt_ts
Definition: parallel.c:94
Definition: shm_mq.c:70
void RestoreRelationMap(char *startAddress)
Definition: relmapper.c:674
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:73
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:42
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:72
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:68
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:70
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
#define die(msg)
Definition: pg_test_fsync.c:97
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:66
void RestoreGUCState(void *gucstate)
Definition: guc.c:10218
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5690

◆ ParallelWorkerReportLastRecEnd()

void ParallelWorkerReportLastRecEnd ( XLogRecPtr  last_xlog_end)

Definition at line 1454 of file parallel.c.

References Assert, FixedParallelState::last_xlog_end, FixedParallelState::mutex, MyFixedParallelState, SpinLockAcquire, and SpinLockRelease.

Referenced by CommitTransaction().

1455 {
1457 
1458  Assert(fps != NULL);
1459  SpinLockAcquire(&fps->mutex);
1460  if (fps->last_xlog_end < last_xlog_end)
1461  fps->last_xlog_end = last_xlog_end;
1462  SpinLockRelease(&fps->mutex);
1463 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr last_xlog_end
Definition: parallel.c:101
#define SpinLockRelease(lock)
Definition: spin.h:64
#define Assert(condition)
Definition: c.h:732
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:119

◆ ReinitializeParallelDSM()

void ReinitializeParallelDSM ( ParallelContext pcxt)

Definition at line 447 of file parallel.c.

References ParallelWorkerInfo::error_mqh, i, ParallelContext::known_attached_workers, FixedParallelState::last_xlog_end, MyProc, ParallelContext::nknown_attached_workers, ParallelContext::nworkers, ParallelContext::nworkers_launched, PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, pfree(), ParallelContext::seg, shm_mq_attach(), shm_mq_create(), shm_mq_set_receiver(), shm_toc_lookup(), ParallelContext::toc, WaitForParallelWorkersToExit(), WaitForParallelWorkersToFinish(), and ParallelContext::worker.

Referenced by ExecParallelReinitialize().

448 {
449  FixedParallelState *fps;
450 
451  /* Wait for any old workers to exit. */
452  if (pcxt->nworkers_launched > 0)
453  {
456  pcxt->nworkers_launched = 0;
457  if (pcxt->known_attached_workers)
458  {
460  pcxt->known_attached_workers = NULL;
461  pcxt->nknown_attached_workers = 0;
462  }
463  }
464 
465  /* Reset a few bits of fixed parallel state to a clean state. */
466  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
467  fps->last_xlog_end = 0;
468 
469  /* Recreate error queues (if they exist). */
470  if (pcxt->nworkers > 0)
471  {
472  char *error_queue_space;
473  int i;
474 
475  error_queue_space =
477  for (i = 0; i < pcxt->nworkers; ++i)
478  {
479  char *start;
480  shm_mq *mq;
481 
482  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
483  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
485  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
486  }
487  }
488 }
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:54
PGPROC * MyProc
Definition: proc.c:68
dsm_segment * seg
Definition: parallel.h:42
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:831
int nknown_attached_workers
Definition: parallel.h:46
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:717
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:1031
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:169
#define PARALLEL_KEY_FIXED
Definition: parallel.c:64
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:65
shm_mq_handle * error_mqh
Definition: parallel.h:28
int nworkers_launched
Definition: parallel.h:37
XLogRecPtr last_xlog_end
Definition: parallel.c:101
bool * known_attached_workers
Definition: parallel.h:47
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:282
int i
Definition: shm_mq.c:70
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:198
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
shm_toc * toc
Definition: parallel.h:44

◆ WaitForParallelWorkersToAttach()

void WaitForParallelWorkersToAttach ( ParallelContext pcxt)

Definition at line 614 of file parallel.c.

References Assert, BGWH_STARTED, BGWH_STOPPED, ParallelWorkerInfo::bgwhandle, CHECK_FOR_INTERRUPTS, ereport, errcode(), errhint(), errmsg(), ERROR, ParallelWorkerInfo::error_mqh, GetBackgroundWorkerPid(), i, ParallelContext::known_attached_workers, MyLatch, ParallelContext::nknown_attached_workers, ParallelContext::nworkers_launched, ResetLatch(), shm_mq_get_queue(), shm_mq_get_sender(), status(), WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and ParallelContext::worker.

Referenced by _bt_begin_parallel().

615 {
616  int i;
617 
618  /* Skip this if we have no launched workers. */
619  if (pcxt->nworkers_launched == 0)
620  return;
621 
622  for (;;)
623  {
624  /*
625  * This will process any parallel messages that are pending and it may
626  * also throw an error propagated from a worker.
627  */
629 
630  for (i = 0; i < pcxt->nworkers_launched; ++i)
631  {
633  shm_mq *mq;
634  int rc;
635  pid_t pid;
636 
637  if (pcxt->known_attached_workers[i])
638  continue;
639 
640  /*
641  * If error_mqh is NULL, then the worker has already exited
642  * cleanly.
643  */
644  if (pcxt->worker[i].error_mqh == NULL)
645  {
646  pcxt->known_attached_workers[i] = true;
647  ++pcxt->nknown_attached_workers;
648  continue;
649  }
650 
651  status = GetBackgroundWorkerPid(pcxt->worker[i].bgwhandle, &pid);
652  if (status == BGWH_STARTED)
653  {
654  /* Has the worker attached to the error queue? */
655  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
656  if (shm_mq_get_sender(mq) != NULL)
657  {
658  /* Yes, so it is known to be attached. */
659  pcxt->known_attached_workers[i] = true;
660  ++pcxt->nknown_attached_workers;
661  }
662  }
663  else if (status == BGWH_STOPPED)
664  {
665  /*
666  * If the worker stopped without attaching to the error queue,
667  * throw an error.
668  */
669  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
670  if (shm_mq_get_sender(mq) == NULL)
671  ereport(ERROR,
672  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
673  errmsg("parallel worker failed to initialize"),
674  errhint("More details may be available in the server log.")));
675 
676  pcxt->known_attached_workers[i] = true;
677  ++pcxt->nknown_attached_workers;
678  }
679  else
680  {
681  /*
682  * Worker not yet started, so we must wait. The postmaster
683  * will notify us if the worker's state changes. Our latch
684  * might also get set for some other reason, but if so we'll
685  * just end up waiting for the same worker again.
686  */
687  rc = WaitLatch(MyLatch,
690 
691  if (rc & WL_LATCH_SET)
693  }
694  }
695 
696  /* If all workers are known to have started, we're done. */
697  if (pcxt->nknown_attached_workers >= pcxt->nworkers_launched)
698  {
700  break;
701  }
702  }
703 }
int errhint(const char *fmt,...)
Definition: elog.c:974
PGPROC * shm_mq_get_sender(shm_mq *mq)
Definition: shm_mq.c:249
int errcode(int sqlerrcode)
Definition: elog.c:570
int nknown_attached_workers
Definition: parallel.h:46
void ResetLatch(Latch *latch)
Definition: latch.c:519
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
ParallelWorkerInfo * worker
Definition: parallel.h:45
#define ERROR
Definition: elog.h:43
shm_mq_handle * error_mqh
Definition: parallel.h:28
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
int nworkers_launched
Definition: parallel.h:37
BgwHandleStatus
Definition: bgworker.h:102
#define ereport(elevel, rest)
Definition: elog.h:141
bool * known_attached_workers
Definition: parallel.h:47
#define Assert(condition)
Definition: c.h:732
shm_mq * shm_mq_get_queue(shm_mq_handle *mqh)
Definition: shm_mq.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
Definition: shm_mq.c:70
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:124
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1044
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ WaitForParallelWorkersToFinish()

void WaitForParallelWorkersToFinish ( ParallelContext pcxt)

Definition at line 717 of file parallel.c.

References Assert, BGWH_STOPPED, ParallelWorkerInfo::bgwhandle, CHECK_FOR_INTERRUPTS, ereport, errcode(), errhint(), errmsg(), ERROR, ParallelWorkerInfo::error_mqh, GetBackgroundWorkerPid(), i, ParallelContext::known_attached_workers, FixedParallelState::last_xlog_end, MyLatch, ParallelContext::nworkers_launched, PARALLEL_KEY_FIXED, ResetLatch(), shm_mq_get_queue(), shm_mq_get_sender(), shm_toc_lookup(), ParallelContext::toc, WAIT_EVENT_PARALLEL_FINISH, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, ParallelContext::worker, and XactLastRecEnd.

Referenced by _bt_end_parallel(), ExecParallelFinish(), and ReinitializeParallelDSM().

718 {
719  for (;;)
720  {
721  bool anyone_alive = false;
722  int nfinished = 0;
723  int i;
724 
725  /*
726  * This will process any parallel messages that are pending, which may
727  * change the outcome of the loop that follows. It may also throw an
728  * error propagated from a worker.
729  */
731 
732  for (i = 0; i < pcxt->nworkers_launched; ++i)
733  {
734  /*
735  * If error_mqh is NULL, then the worker has already exited
736  * cleanly. If we have received a message through error_mqh from
737  * the worker, we know it started up cleanly, and therefore we're
738  * certain to be notified when it exits.
739  */
740  if (pcxt->worker[i].error_mqh == NULL)
741  ++nfinished;
742  else if (pcxt->known_attached_workers[i])
743  {
744  anyone_alive = true;
745  break;
746  }
747  }
748 
749  if (!anyone_alive)
750  {
751  /* If all workers are known to have finished, we're done. */
752  if (nfinished >= pcxt->nworkers_launched)
753  {
754  Assert(nfinished == pcxt->nworkers_launched);
755  break;
756  }
757 
758  /*
759  * We didn't detect any living workers, but not all workers are
760  * known to have exited cleanly. Either not all workers have
761  * launched yet, or maybe some of them failed to start or
762  * terminated abnormally.
763  */
764  for (i = 0; i < pcxt->nworkers_launched; ++i)
765  {
766  pid_t pid;
767  shm_mq *mq;
768 
769  /*
770  * If the worker is BGWH_NOT_YET_STARTED or BGWH_STARTED, we
771  * should just keep waiting. If it is BGWH_STOPPED, then
772  * further investigation is needed.
773  */
774  if (pcxt->worker[i].error_mqh == NULL ||
775  pcxt->worker[i].bgwhandle == NULL ||
777  &pid) != BGWH_STOPPED)
778  continue;
779 
780  /*
781  * Check whether the worker ended up stopped without ever
782  * attaching to the error queue. If so, the postmaster was
783  * unable to fork the worker or it exited without initializing
784  * properly. We must throw an error, since the caller may
785  * have been expecting the worker to do some work before
786  * exiting.
787  */
788  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
789  if (shm_mq_get_sender(mq) == NULL)
790  ereport(ERROR,
791  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
792  errmsg("parallel worker failed to initialize"),
793  errhint("More details may be available in the server log.")));
794 
795  /*
796  * The worker is stopped, but is attached to the error queue.
797  * Unless there's a bug somewhere, this will only happen when
798  * the worker writes messages and terminates after the
799  * CHECK_FOR_INTERRUPTS() near the top of this function and
800  * before the call to GetBackgroundWorkerPid(). In that case,
801  * or latch should have been set as well and the right things
802  * will happen on the next pass through the loop.
803  */
804  }
805  }
806 
810  }
811 
812  if (pcxt->toc != NULL)
813  {
814  FixedParallelState *fps;
815 
816  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
817  if (fps->last_xlog_end > XactLastRecEnd)
819  }
820 }
int errhint(const char *fmt,...)
Definition: elog.c:974
XLogRecPtr XactLastRecEnd
Definition: xlog.c:352
PGPROC * shm_mq_get_sender(shm_mq *mq)
Definition: shm_mq.c:249
int errcode(int sqlerrcode)
Definition: elog.c:570
void ResetLatch(Latch *latch)
Definition: latch.c:519
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
ParallelWorkerInfo * worker
Definition: parallel.h:45
#define ERROR
Definition: elog.h:43
#define PARALLEL_KEY_FIXED
Definition: parallel.c:64
shm_mq_handle * error_mqh
Definition: parallel.h:28
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
int nworkers_launched
Definition: parallel.h:37
XLogRecPtr last_xlog_end
Definition: parallel.c:101
#define ereport(elevel, rest)
Definition: elog.h:141
bool * known_attached_workers
Definition: parallel.h:47
#define Assert(condition)
Definition: c.h:732
shm_mq * shm_mq_get_queue(shm_mq_handle *mqh)
Definition: shm_mq.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
Definition: shm_mq.c:70
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define WL_LATCH_SET
Definition: latch.h:124
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1044
shm_toc * toc
Definition: parallel.h:44
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

Variable Documentation

◆ InitializingParallelWorker

PGDLLIMPORT bool InitializingParallelWorker

◆ ParallelMessagePending

volatile bool ParallelMessagePending

◆ ParallelWorkerNumber