PostgreSQL Source Code  git master
parallel.c File Reference
#include "postgres.h"
#include "access/nbtree.h"
#include "access/parallel.h"
#include "access/session.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_enum.h"
#include "catalog/storage.h"
#include "commands/async.h"
#include "commands/vacuum.h"
#include "executor/execParallel.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqmq.h"
#include "miscadmin.h"
#include "optimizer/optimizer.h"
#include "pgstat.h"
#include "storage/ipc.h"
#include "storage/predicate.h"
#include "storage/sinval.h"
#include "storage/spin.h"
#include "tcop/tcopprot.h"
#include "utils/combocid.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/relmapper.h"
#include "utils/snapmgr.h"
#include "utils/typcache.h"
Include dependency graph for parallel.c:

Go to the source code of this file.

Data Structures

struct  FixedParallelState
 

Macros

#define PARALLEL_ERROR_QUEUE_SIZE   16384
 
#define PARALLEL_MAGIC   0x50477c7c
 
#define PARALLEL_KEY_FIXED   UINT64CONST(0xFFFFFFFFFFFF0001)
 
#define PARALLEL_KEY_ERROR_QUEUE   UINT64CONST(0xFFFFFFFFFFFF0002)
 
#define PARALLEL_KEY_LIBRARY   UINT64CONST(0xFFFFFFFFFFFF0003)
 
#define PARALLEL_KEY_GUC   UINT64CONST(0xFFFFFFFFFFFF0004)
 
#define PARALLEL_KEY_COMBO_CID   UINT64CONST(0xFFFFFFFFFFFF0005)
 
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0006)
 
#define PARALLEL_KEY_ACTIVE_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0007)
 
#define PARALLEL_KEY_TRANSACTION_STATE   UINT64CONST(0xFFFFFFFFFFFF0008)
 
#define PARALLEL_KEY_ENTRYPOINT   UINT64CONST(0xFFFFFFFFFFFF0009)
 
#define PARALLEL_KEY_SESSION_DSM   UINT64CONST(0xFFFFFFFFFFFF000A)
 
#define PARALLEL_KEY_PENDING_SYNCS   UINT64CONST(0xFFFFFFFFFFFF000B)
 
#define PARALLEL_KEY_REINDEX_STATE   UINT64CONST(0xFFFFFFFFFFFF000C)
 
#define PARALLEL_KEY_RELMAPPER_STATE   UINT64CONST(0xFFFFFFFFFFFF000D)
 
#define PARALLEL_KEY_UNCOMMITTEDENUMS   UINT64CONST(0xFFFFFFFFFFFF000E)
 
#define PARALLEL_KEY_CLIENTCONNINFO   UINT64CONST(0xFFFFFFFFFFFF000F)
 

Typedefs

typedef struct FixedParallelState FixedParallelState
 

Functions

static void HandleParallelMessage (ParallelContext *pcxt, int i, StringInfo msg)
 
static void WaitForParallelWorkersToExit (ParallelContext *pcxt)
 
static parallel_worker_main_type LookupParallelWorkerFunction (const char *libraryname, const char *funcname)
 
static void ParallelWorkerShutdown (int code, Datum arg)
 
ParallelContextCreateParallelContext (const char *library_name, const char *function_name, int nworkers)
 
void InitializeParallelDSM (ParallelContext *pcxt)
 
void ReinitializeParallelDSM (ParallelContext *pcxt)
 
void ReinitializeParallelWorkers (ParallelContext *pcxt, int nworkers_to_launch)
 
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 AtEOSubXact_Parallel (bool isCommit, SubTransactionId mySubId)
 
void AtEOXact_Parallel (bool isCommit)
 
void ParallelWorkerMain (Datum main_arg)
 
void ParallelWorkerReportLastRecEnd (XLogRecPtr last_xlog_end)
 

Variables

int ParallelWorkerNumber = -1
 
volatile sig_atomic_t ParallelMessagePending = false
 
bool InitializingParallelWorker = false
 
static FixedParallelStateMyFixedParallelState
 
static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list)
 
static pid_t ParallelLeaderPid
 
struct {
   const char *   fn_name
 
   parallel_worker_main_type   fn_addr
 
InternalParallelWorkers []
 

Macro Definition Documentation

◆ PARALLEL_ERROR_QUEUE_SIZE

#define PARALLEL_ERROR_QUEUE_SIZE   16384

Definition at line 55 of file parallel.c.

◆ PARALLEL_KEY_ACTIVE_SNAPSHOT

#define PARALLEL_KEY_ACTIVE_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0007)

Definition at line 71 of file parallel.c.

◆ PARALLEL_KEY_CLIENTCONNINFO

#define PARALLEL_KEY_CLIENTCONNINFO   UINT64CONST(0xFFFFFFFFFFFF000F)

Definition at line 79 of file parallel.c.

◆ PARALLEL_KEY_COMBO_CID

#define PARALLEL_KEY_COMBO_CID   UINT64CONST(0xFFFFFFFFFFFF0005)

Definition at line 69 of file parallel.c.

◆ PARALLEL_KEY_ENTRYPOINT

#define PARALLEL_KEY_ENTRYPOINT   UINT64CONST(0xFFFFFFFFFFFF0009)

Definition at line 73 of file parallel.c.

◆ PARALLEL_KEY_ERROR_QUEUE

#define PARALLEL_KEY_ERROR_QUEUE   UINT64CONST(0xFFFFFFFFFFFF0002)

Definition at line 66 of file parallel.c.

◆ PARALLEL_KEY_FIXED

#define PARALLEL_KEY_FIXED   UINT64CONST(0xFFFFFFFFFFFF0001)

Definition at line 65 of file parallel.c.

◆ PARALLEL_KEY_GUC

#define PARALLEL_KEY_GUC   UINT64CONST(0xFFFFFFFFFFFF0004)

Definition at line 68 of file parallel.c.

◆ PARALLEL_KEY_LIBRARY

#define PARALLEL_KEY_LIBRARY   UINT64CONST(0xFFFFFFFFFFFF0003)

Definition at line 67 of file parallel.c.

◆ PARALLEL_KEY_PENDING_SYNCS

#define PARALLEL_KEY_PENDING_SYNCS   UINT64CONST(0xFFFFFFFFFFFF000B)

Definition at line 75 of file parallel.c.

◆ PARALLEL_KEY_REINDEX_STATE

#define PARALLEL_KEY_REINDEX_STATE   UINT64CONST(0xFFFFFFFFFFFF000C)

Definition at line 76 of file parallel.c.

◆ PARALLEL_KEY_RELMAPPER_STATE

#define PARALLEL_KEY_RELMAPPER_STATE   UINT64CONST(0xFFFFFFFFFFFF000D)

Definition at line 77 of file parallel.c.

◆ PARALLEL_KEY_SESSION_DSM

#define PARALLEL_KEY_SESSION_DSM   UINT64CONST(0xFFFFFFFFFFFF000A)

Definition at line 74 of file parallel.c.

◆ PARALLEL_KEY_TRANSACTION_SNAPSHOT

#define PARALLEL_KEY_TRANSACTION_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0006)

Definition at line 70 of file parallel.c.

◆ PARALLEL_KEY_TRANSACTION_STATE

#define PARALLEL_KEY_TRANSACTION_STATE   UINT64CONST(0xFFFFFFFFFFFF0008)

Definition at line 72 of file parallel.c.

◆ PARALLEL_KEY_UNCOMMITTEDENUMS

#define PARALLEL_KEY_UNCOMMITTEDENUMS   UINT64CONST(0xFFFFFFFFFFFF000E)

Definition at line 78 of file parallel.c.

◆ PARALLEL_MAGIC

#define PARALLEL_MAGIC   0x50477c7c

Definition at line 58 of file parallel.c.

Typedef Documentation

◆ FixedParallelState

Function Documentation

◆ AtEOSubXact_Parallel()

void AtEOSubXact_Parallel ( bool  isCommit,
SubTransactionId  mySubId 
)

Definition at line 1226 of file parallel.c.

1227 {
1228  while (!dlist_is_empty(&pcxt_list))
1229  {
1230  ParallelContext *pcxt;
1231 
1233  if (pcxt->subid != mySubId)
1234  break;
1235  if (isCommit)
1236  elog(WARNING, "leaked parallel context");
1237  DestroyParallelContext(pcxt);
1238  }
1239 }
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:927
static dlist_head pcxt_list
Definition: parallel.c:125
#define WARNING
Definition: elog.h:32
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:553
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:325
SubTransactionId subid
Definition: parallel.h:35

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_Parallel()

void AtEOXact_Parallel ( bool  isCommit)

Definition at line 1245 of file parallel.c.

1246 {
1247  while (!dlist_is_empty(&pcxt_list))
1248  {
1249  ParallelContext *pcxt;
1250 
1252  if (isCommit)
1253  elog(WARNING, "leaked parallel context");
1254  DestroyParallelContext(pcxt);
1255  }
1256 }

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

Referenced by AbortTransaction(), and CommitTransaction().

◆ CreateParallelContext()

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

Definition at line 165 of file parallel.c.

167 {
168  MemoryContext oldcontext;
169  ParallelContext *pcxt;
170 
171  /* It is unsafe to create a parallel context if not in parallel mode. */
173 
174  /* Number of workers should be non-negative. */
175  Assert(nworkers >= 0);
176 
177  /* We might be running in a short-lived memory context. */
179 
180  /* Initialize a new ParallelContext. */
181  pcxt = palloc0(sizeof(ParallelContext));
183  pcxt->nworkers = nworkers;
184  pcxt->nworkers_to_launch = nworkers;
185  pcxt->library_name = pstrdup(library_name);
186  pcxt->function_name = pstrdup(function_name);
189  dlist_push_head(&pcxt_list, &pcxt->node);
190 
191  /* Restore previous memory context. */
192  MemoryContextSwitchTo(oldcontext);
193 
194  return pcxt;
195 }
ErrorContextCallback * error_context_stack
Definition: elog.c:94
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:336
Assert(fmt[strlen(fmt) - 1] !='\n')
MemoryContext TopTransactionContext
Definition: mcxt.c:135
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void * palloc0(Size size)
Definition: mcxt.c:1230
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
#define shm_toc_initialize_estimator(e)
Definition: shm_toc.h:49
char * library_name
Definition: parallel.h:39
ErrorContextCallback * error_context_stack
Definition: parallel.h:41
shm_toc_estimator estimator
Definition: parallel.h:42
dlist_node node
Definition: parallel.h:34
int nworkers_to_launch
Definition: parallel.h:37
char * function_name
Definition: parallel.h:40
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:779
bool IsInParallelMode(void)
Definition: xact.c:1068

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

Referenced by _bt_begin_parallel(), ExecInitParallelPlan(), and parallel_vacuum_init().

◆ DestroyParallelContext()

void DestroyParallelContext ( ParallelContext pcxt)

Definition at line 927 of file parallel.c.

928 {
929  int i;
930 
931  /*
932  * Be careful about order of operations here! We remove the parallel
933  * context from the list before we do anything else; otherwise, if an
934  * error occurs during a subsequent step, we might try to nuke it again
935  * from AtEOXact_Parallel or AtEOSubXact_Parallel.
936  */
937  dlist_delete(&pcxt->node);
938 
939  /* Kill each worker in turn, and forget their error queues. */
940  if (pcxt->worker != NULL)
941  {
942  for (i = 0; i < pcxt->nworkers_launched; ++i)
943  {
944  if (pcxt->worker[i].error_mqh != NULL)
945  {
947 
949  pcxt->worker[i].error_mqh = NULL;
950  }
951  }
952  }
953 
954  /*
955  * If we have allocated a shared memory segment, detach it. This will
956  * implicitly detach the error queues, and any other shared memory queues,
957  * stored there.
958  */
959  if (pcxt->seg != NULL)
960  {
961  dsm_detach(pcxt->seg);
962  pcxt->seg = NULL;
963  }
964 
965  /*
966  * If this parallel context is actually in backend-private memory rather
967  * than shared memory, free that memory instead.
968  */
969  if (pcxt->private_memory != NULL)
970  {
971  pfree(pcxt->private_memory);
972  pcxt->private_memory = NULL;
973  }
974 
975  /*
976  * We can't finish transaction commit or abort until all of the workers
977  * have exited. This means, in particular, that we can't respond to
978  * interrupts at this stage.
979  */
980  HOLD_INTERRUPTS();
983 
984  /* Free the worker array itself. */
985  if (pcxt->worker != NULL)
986  {
987  pfree(pcxt->worker);
988  pcxt->worker = NULL;
989  }
990 
991  /* Free memory. */
992  pfree(pcxt->library_name);
993  pfree(pcxt->function_name);
994  pfree(pcxt);
995 }
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:887
void TerminateBackgroundWorker(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1207
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:777
static void dlist_delete(dlist_node *node)
Definition: ilist.h:394
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1306
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:844
dsm_segment * seg
Definition: parallel.h:43
ParallelWorkerInfo * worker
Definition: parallel.h:46
void * private_memory
Definition: parallel.h:44
int nworkers_launched
Definition: parallel.h:38
BackgroundWorkerHandle * bgwhandle
Definition: parallel.h:27
shm_mq_handle * error_mqh
Definition: parallel.h:28

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_begin_parallel(), _bt_end_parallel(), AtEOSubXact_Parallel(), AtEOXact_Parallel(), ExecParallelCleanup(), and parallel_vacuum_end().

◆ HandleParallelMessage()

static void HandleParallelMessage ( ParallelContext pcxt,
int  i,
StringInfo  msg 
)
static

Definition at line 1114 of file parallel.c.

1115 {
1116  char msgtype;
1117 
1118  if (pcxt->known_attached_workers != NULL &&
1119  !pcxt->known_attached_workers[i])
1120  {
1121  pcxt->known_attached_workers[i] = true;
1122  pcxt->nknown_attached_workers++;
1123  }
1124 
1125  msgtype = pq_getmsgbyte(msg);
1126 
1127  switch (msgtype)
1128  {
1129  case 'K': /* BackendKeyData */
1130  {
1131  int32 pid = pq_getmsgint(msg, 4);
1132 
1133  (void) pq_getmsgint(msg, 4); /* discard cancel key */
1134  (void) pq_getmsgend(msg);
1135  pcxt->worker[i].pid = pid;
1136  break;
1137  }
1138 
1139  case 'E': /* ErrorResponse */
1140  case 'N': /* NoticeResponse */
1141  {
1142  ErrorData edata;
1143  ErrorContextCallback *save_error_context_stack;
1144 
1145  /* Parse ErrorResponse or NoticeResponse. */
1146  pq_parse_errornotice(msg, &edata);
1147 
1148  /* Death of a worker isn't enough justification for suicide. */
1149  edata.elevel = Min(edata.elevel, ERROR);
1150 
1151  /*
1152  * If desired, add a context line to show that this is a
1153  * message propagated from a parallel worker. Otherwise, it
1154  * can sometimes be confusing to understand what actually
1155  * happened. (We don't do this in FORCE_PARALLEL_REGRESS mode
1156  * because it causes test-result instability depending on
1157  * whether a parallel worker is actually used or not.)
1158  */
1160  {
1161  if (edata.context)
1162  edata.context = psprintf("%s\n%s", edata.context,
1163  _("parallel worker"));
1164  else
1165  edata.context = pstrdup(_("parallel worker"));
1166  }
1167 
1168  /*
1169  * Context beyond that should use the error context callbacks
1170  * that were in effect when the ParallelContext was created,
1171  * not the current ones.
1172  */
1173  save_error_context_stack = error_context_stack;
1175 
1176  /* Rethrow error or print notice. */
1177  ThrowErrorData(&edata);
1178 
1179  /* Not an error, so restore previous context stack. */
1180  error_context_stack = save_error_context_stack;
1181 
1182  break;
1183  }
1184 
1185  case 'A': /* NotifyResponse */
1186  {
1187  /* Propagate NotifyResponse. */
1188  int32 pid;
1189  const char *channel;
1190  const char *payload;
1191 
1192  pid = pq_getmsgint(msg, 4);
1193  channel = pq_getmsgrawstring(msg);
1194  payload = pq_getmsgrawstring(msg);
1195  pq_endmessage(msg);
1196 
1197  NotifyMyFrontEnd(channel, payload, pid);
1198 
1199  break;
1200  }
1201 
1202  case 'X': /* Terminate, indicating clean exit */
1203  {
1204  shm_mq_detach(pcxt->worker[i].error_mqh);
1205  pcxt->worker[i].error_mqh = NULL;
1206  break;
1207  }
1208 
1209  default:
1210  {
1211  elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
1212  msgtype, msg->len);
1213  }
1214  }
1215 }
void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
Definition: async.c:2278
#define Min(x, y)
Definition: c.h:937
signed int int32
Definition: c.h:430
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1676
#define _(x)
Definition: elog.c:90
#define ERROR
Definition: elog.h:35
@ FORCE_PARALLEL_REGRESS
Definition: optimizer.h:107
int force_parallel_mode
Definition: planner.c:71
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:610
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition: pqmq.c:204
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
char * context
Definition: elog.h:382
int elevel
Definition: elog.h:367
bool * known_attached_workers
Definition: parallel.h:48
int nknown_attached_workers
Definition: parallel.h:47

References _, ErrorData::context, ErrorData::elevel, elog(), ERROR, error_context_stack, ParallelContext::error_context_stack, ParallelWorkerInfo::error_mqh, force_parallel_mode, FORCE_PARALLEL_REGRESS, i, ParallelContext::known_attached_workers, StringInfoData::len, Min, ParallelContext::nknown_attached_workers, NotifyMyFrontEnd(), ParallelWorkerInfo::pid, pq_endmessage(), pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgrawstring(), pq_parse_errornotice(), psprintf(), pstrdup(), shm_mq_detach(), ThrowErrorData(), and ParallelContext::worker.

Referenced by HandleParallelMessages().

◆ HandleParallelMessageInterrupt()

void HandleParallelMessageInterrupt ( void  )

Definition at line 1014 of file parallel.c.

1015 {
1016  InterruptPending = true;
1017  ParallelMessagePending = true;
1018  SetLatch(MyLatch);
1019 }
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:116
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:58
void SetLatch(Latch *latch)
Definition: latch.c:591

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

Referenced by procsignal_sigusr1_handler().

◆ HandleParallelMessages()

void HandleParallelMessages ( void  )

Definition at line 1025 of file parallel.c.

1026 {
1027  dlist_iter iter;
1028  MemoryContext oldcontext;
1029 
1030  static MemoryContext hpm_context = NULL;
1031 
1032  /*
1033  * This is invoked from ProcessInterrupts(), and since some of the
1034  * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
1035  * for recursive calls if more signals are received while this runs. It's
1036  * unclear that recursive entry would be safe, and it doesn't seem useful
1037  * even if it is safe, so let's block interrupts until done.
1038  */
1039  HOLD_INTERRUPTS();
1040 
1041  /*
1042  * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
1043  * don't want to risk leaking data into long-lived contexts, so let's do
1044  * our work here in a private context that we can reset on each use.
1045  */
1046  if (hpm_context == NULL) /* first time through? */
1048  "HandleParallelMessages",
1050  else
1051  MemoryContextReset(hpm_context);
1052 
1053  oldcontext = MemoryContextSwitchTo(hpm_context);
1054 
1055  /* OK to process messages. Reset the flag saying there are more to do. */
1056  ParallelMessagePending = false;
1057 
1058  dlist_foreach(iter, &pcxt_list)
1059  {
1060  ParallelContext *pcxt;
1061  int i;
1062 
1063  pcxt = dlist_container(ParallelContext, node, iter.cur);
1064  if (pcxt->worker == NULL)
1065  continue;
1066 
1067  for (i = 0; i < pcxt->nworkers_launched; ++i)
1068  {
1069  /*
1070  * Read as many messages as we can from each worker, but stop when
1071  * either (1) the worker's error queue goes away, which can happen
1072  * if we receive a Terminate message from the worker; or (2) no
1073  * more messages can be read from the worker without blocking.
1074  */
1075  while (pcxt->worker[i].error_mqh != NULL)
1076  {
1078  Size nbytes;
1079  void *data;
1080 
1081  res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
1082  &data, true);
1083  if (res == SHM_MQ_WOULD_BLOCK)
1084  break;
1085  else if (res == SHM_MQ_SUCCESS)
1086  {
1087  StringInfoData msg;
1088 
1089  initStringInfo(&msg);
1090  appendBinaryStringInfo(&msg, data, nbytes);
1091  HandleParallelMessage(pcxt, i, &msg);
1092  pfree(msg.data);
1093  }
1094  else
1095  ereport(ERROR,
1096  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1097  errmsg("lost connection to parallel worker")));
1098  }
1099  }
1100  }
1101 
1102  MemoryContextSwitchTo(oldcontext);
1103 
1104  /* Might as well clear the context on our way out */
1105  MemoryContextReset(hpm_context);
1106 
1108 }
static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
Definition: parallel.c:1114
size_t Size
Definition: c.h:541
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
#define dlist_foreach(iter, lhead)
Definition: ilist.h:573
#define dlist_container(type, membername, ptr)
Definition: ilist.h:543
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:303
MemoryContext TopMemoryContext
Definition: mcxt.c:130
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
const void * data
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
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
dlist_node * cur
Definition: ilist.h:179

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

Referenced by ProcessInterrupts().

◆ InitializeParallelDSM()

void InitializeParallelDSM ( ParallelContext pcxt)

Definition at line 203 of file parallel.c.

204 {
205  MemoryContext oldcontext;
206  Size library_len = 0;
207  Size guc_len = 0;
208  Size combocidlen = 0;
209  Size tsnaplen = 0;
210  Size asnaplen = 0;
211  Size tstatelen = 0;
212  Size pendingsyncslen = 0;
213  Size reindexlen = 0;
214  Size relmapperlen = 0;
215  Size uncommittedenumslen = 0;
216  Size clientconninfolen = 0;
217  Size segsize = 0;
218  int i;
219  FixedParallelState *fps;
220  dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
221  Snapshot transaction_snapshot = GetTransactionSnapshot();
222  Snapshot active_snapshot = GetActiveSnapshot();
223 
224  /* We might be running in a very short-lived memory context. */
226 
227  /* Allow space to store the fixed-size parallel state. */
229  shm_toc_estimate_keys(&pcxt->estimator, 1);
230 
231  /*
232  * Normally, the user will have requested at least one worker process, but
233  * if by chance they have not, we can skip a bunch of things here.
234  */
235  if (pcxt->nworkers > 0)
236  {
237  /* Get (or create) the per-session DSM segment's handle. */
238  session_dsm_handle = GetSessionDsmHandle();
239 
240  /*
241  * If we weren't able to create a per-session DSM segment, then we can
242  * continue but we can't safely launch any workers because their
243  * record typmods would be incompatible so they couldn't exchange
244  * tuples.
245  */
246  if (session_dsm_handle == DSM_HANDLE_INVALID)
247  pcxt->nworkers = 0;
248  }
249 
250  if (pcxt->nworkers > 0)
251  {
252  /* Estimate space for various kinds of state sharing. */
253  library_len = EstimateLibraryStateSpace();
254  shm_toc_estimate_chunk(&pcxt->estimator, library_len);
255  guc_len = EstimateGUCStateSpace();
256  shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
257  combocidlen = EstimateComboCIDStateSpace();
258  shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
260  {
261  tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
262  shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
263  }
264  asnaplen = EstimateSnapshotSpace(active_snapshot);
265  shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
266  tstatelen = EstimateTransactionStateSpace();
267  shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
269  pendingsyncslen = EstimatePendingSyncsSpace();
270  shm_toc_estimate_chunk(&pcxt->estimator, pendingsyncslen);
271  reindexlen = EstimateReindexStateSpace();
272  shm_toc_estimate_chunk(&pcxt->estimator, reindexlen);
273  relmapperlen = EstimateRelationMapSpace();
274  shm_toc_estimate_chunk(&pcxt->estimator, relmapperlen);
275  uncommittedenumslen = EstimateUncommittedEnumsSpace();
276  shm_toc_estimate_chunk(&pcxt->estimator, uncommittedenumslen);
277  clientconninfolen = EstimateClientConnectionInfoSpace();
278  shm_toc_estimate_chunk(&pcxt->estimator, clientconninfolen);
279  /* If you add more chunks here, you probably need to add keys. */
280  shm_toc_estimate_keys(&pcxt->estimator, 12);
281 
282  /* Estimate space need for error queues. */
285  "parallel error queue size not buffer-aligned");
288  pcxt->nworkers));
289  shm_toc_estimate_keys(&pcxt->estimator, 1);
290 
291  /* Estimate how much we'll need for the entrypoint info. */
292  shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
293  strlen(pcxt->function_name) + 2);
294  shm_toc_estimate_keys(&pcxt->estimator, 1);
295  }
296 
297  /*
298  * Create DSM and initialize with new table of contents. But if the user
299  * didn't request any workers, then don't bother creating a dynamic shared
300  * memory segment; instead, just use backend-private memory.
301  *
302  * Also, if we can't create a dynamic shared memory segment because the
303  * maximum number of segments have already been created, then fall back to
304  * backend-private memory, and plan not to use any workers. We hope this
305  * won't happen very often, but it's better to abandon the use of
306  * parallelism than to fail outright.
307  */
308  segsize = shm_toc_estimate(&pcxt->estimator);
309  if (pcxt->nworkers > 0)
311  if (pcxt->seg != NULL)
313  dsm_segment_address(pcxt->seg),
314  segsize);
315  else
316  {
317  pcxt->nworkers = 0;
320  segsize);
321  }
322 
323  /* Initialize fixed-size state in shared memory. */
324  fps = (FixedParallelState *)
325  shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
326  fps->database_id = MyDatabaseId;
339  SpinLockInit(&fps->mutex);
340  fps->last_xlog_end = 0;
342 
343  /* We can skip the rest of this if we're not budgeting for any workers. */
344  if (pcxt->nworkers > 0)
345  {
346  char *libraryspace;
347  char *gucspace;
348  char *combocidspace;
349  char *tsnapspace;
350  char *asnapspace;
351  char *tstatespace;
352  char *pendingsyncsspace;
353  char *reindexspace;
354  char *relmapperspace;
355  char *error_queue_space;
356  char *session_dsm_handle_space;
357  char *entrypointstate;
358  char *uncommittedenumsspace;
359  char *clientconninfospace;
360  Size lnamelen;
361 
362  /* Serialize shared libraries we have loaded. */
363  libraryspace = shm_toc_allocate(pcxt->toc, library_len);
364  SerializeLibraryState(library_len, libraryspace);
365  shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
366 
367  /* Serialize GUC settings. */
368  gucspace = shm_toc_allocate(pcxt->toc, guc_len);
369  SerializeGUCState(guc_len, gucspace);
370  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
371 
372  /* Serialize combo CID state. */
373  combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
374  SerializeComboCIDState(combocidlen, combocidspace);
375  shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
376 
377  /*
378  * Serialize the transaction snapshot if the transaction
379  * isolation-level uses a transaction snapshot.
380  */
382  {
383  tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
384  SerializeSnapshot(transaction_snapshot, tsnapspace);
386  tsnapspace);
387  }
388 
389  /* Serialize the active snapshot. */
390  asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
391  SerializeSnapshot(active_snapshot, asnapspace);
392  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
393 
394  /* Provide the handle for per-session segment. */
395  session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
396  sizeof(dsm_handle));
397  *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
399  session_dsm_handle_space);
400 
401  /* Serialize transaction state. */
402  tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
403  SerializeTransactionState(tstatelen, tstatespace);
405 
406  /* Serialize pending syncs. */
407  pendingsyncsspace = shm_toc_allocate(pcxt->toc, pendingsyncslen);
408  SerializePendingSyncs(pendingsyncslen, pendingsyncsspace);
410  pendingsyncsspace);
411 
412  /* Serialize reindex state. */
413  reindexspace = shm_toc_allocate(pcxt->toc, reindexlen);
414  SerializeReindexState(reindexlen, reindexspace);
415  shm_toc_insert(pcxt->toc, PARALLEL_KEY_REINDEX_STATE, reindexspace);
416 
417  /* Serialize relmapper state. */
418  relmapperspace = shm_toc_allocate(pcxt->toc, relmapperlen);
419  SerializeRelationMap(relmapperlen, relmapperspace);
421  relmapperspace);
422 
423  /* Serialize uncommitted enum state. */
424  uncommittedenumsspace = shm_toc_allocate(pcxt->toc,
425  uncommittedenumslen);
426  SerializeUncommittedEnums(uncommittedenumsspace, uncommittedenumslen);
428  uncommittedenumsspace);
429 
430  /* Serialize our ClientConnectionInfo. */
431  clientconninfospace = shm_toc_allocate(pcxt->toc, clientconninfolen);
432  SerializeClientConnectionInfo(clientconninfolen, clientconninfospace);
434  clientconninfospace);
435 
436  /* Allocate space for worker information. */
437  pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
438 
439  /*
440  * Establish error queues in dynamic shared memory.
441  *
442  * These queues should be used only for transmitting ErrorResponse,
443  * NoticeResponse, and NotifyResponse protocol messages. Tuple data
444  * should be transmitted via separate (possibly larger?) queues.
445  */
446  error_queue_space =
447  shm_toc_allocate(pcxt->toc,
449  pcxt->nworkers));
450  for (i = 0; i < pcxt->nworkers; ++i)
451  {
452  char *start;
453  shm_mq *mq;
454 
455  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
458  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
459  }
460  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
461 
462  /*
463  * Serialize entrypoint information. It's unsafe to pass function
464  * pointers across processes, as the function pointer may be different
465  * in each process in EXEC_BACKEND builds, so we always pass library
466  * and function name. (We use library name "postgres" for functions
467  * in the core backend.)
468  */
469  lnamelen = strlen(pcxt->library_name);
470  entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
471  strlen(pcxt->function_name) + 2);
472  strcpy(entrypointstate, pcxt->library_name);
473  strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
474  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
475  }
476 
477  /* Restore previous memory context. */
478  MemoryContextSwitchTo(oldcontext);
479 }
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:72
#define PARALLEL_KEY_GUC
Definition: parallel.c:68
#define PARALLEL_KEY_UNCOMMITTEDENUMS
Definition: parallel.c:78
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:70
#define PARALLEL_KEY_CLIENTCONNINFO
Definition: parallel.c:79
#define PARALLEL_KEY_PENDING_SYNCS
Definition: parallel.c:75
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:71
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:66
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:74
#define PARALLEL_MAGIC
Definition: parallel.c:58
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:76
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:67
#define PARALLEL_KEY_FIXED
Definition: parallel.c:65
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:73
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:69
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:55
#define PARALLEL_KEY_RELMAPPER_STATE
Definition: parallel.c:77
#define BUFFERALIGN(LEN)
Definition: c.h:749
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:869
void SerializeComboCIDState(Size maxsize, char *start_address)
Definition: combocid.c:316
Size EstimateComboCIDStateSpace(void)
Definition: combocid.c:297
void SerializeLibraryState(Size maxsize, char *start_address)
Definition: dfmgr.c:671
Size EstimateLibraryStateSpace(void)
Definition: dfmgr.c:654
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1067
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:490
#define DSM_CREATE_NULL_IF_MAXSEGMENTS
Definition: dsm.h:20
#define DSM_HANDLE_INVALID
Definition: dsm.h:23
uint32 dsm_handle
Definition: dsm_impl.h:55
int MyProcPid
Definition: globals.c:44
BackendId MyBackendId
Definition: globals.c:85
Oid MyDatabaseId
Definition: globals.c:89
void SerializeGUCState(Size maxsize, char *start_address)
Definition: guc.c:5909
Size EstimateGUCStateSpace(void)
Definition: guc.c:5756
bool session_auth_is_superuser
Definition: guc_tables.c:483
void SerializeReindexState(Size maxsize, char *start_address)
Definition: index.c:4148
Size EstimateReindexStateSpace(void)
Definition: index.c:4137
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
void SerializeClientConnectionInfo(Size maxsize, char *start_address)
Definition: miscinit.c:1030
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:618
Size EstimateClientConnectionInfoSpace(void)
Definition: miscinit.c:1014
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:566
Oid GetCurrentRoleId(void)
Definition: miscinit.c:911
void GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
Definition: namespace.c:3356
Size EstimateUncommittedEnumsSpace(void)
Definition: pg_enum.c:724
void SerializeUncommittedEnums(void *space, Size size)
Definition: pg_enum.c:738
SerializableXactHandle ShareSerializableXact(void)
Definition: predicate.c:5184
Size EstimateRelationMapSpace(void)
Definition: relmapper.c:711
void SerializeRelationMap(Size maxSize, char *startAddress)
Definition: relmapper.c:722
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_create(void *address, Size size)
Definition: shm_mq.c:178
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:207
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
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#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:2147
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
Size EstimateSnapshotSpace(Snapshot snapshot)
Definition: snapmgr.c:2123
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:805
#define SpinLockInit(lock)
Definition: spin.h:60
PGPROC * MyProc
Definition: proc.c:68
void SerializePendingSyncs(Size maxSize, char *startAddress)
Definition: storage.c:577
Size EstimatePendingSyncsSpace(void)
Definition: storage.c:564
Oid temp_toast_namespace_id
Definition: parallel.c:90
XLogRecPtr last_xlog_end
Definition: parallel.c:104
TimestampTz stmt_ts
Definition: parallel.c:97
SerializableXactHandle serializable_xact_handle
Definition: parallel.c:98
TimestampTz xact_ts
Definition: parallel.c:96
PGPROC * parallel_leader_pgproc
Definition: parallel.c:93
pid_t parallel_leader_pid
Definition: parallel.c:94
BackendId parallel_leader_backend_id
Definition: parallel.c:95
Oid authenticated_user_id
Definition: parallel.c:86
shm_toc * toc
Definition: parallel.h:45
Definition: shm_mq.c:73
void SerializeTransactionState(Size maxsize, char *start_address)
Definition: xact.c:5352
Size EstimateTransactionStateSpace(void)
Definition: xact.c:5324
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:863
TimestampTz GetCurrentTransactionStartTimestamp(void)
Definition: xact.c:854
#define IsolationUsesXactSnapshot()
Definition: xact.h:51

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, EstimateClientConnectionInfoSpace(), EstimateComboCIDStateSpace(), EstimateGUCStateSpace(), EstimateLibraryStateSpace(), EstimatePendingSyncsSpace(), EstimateReindexStateSpace(), EstimateRelationMapSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), EstimateUncommittedEnumsSpace(), ParallelContext::estimator, ParallelContext::function_name, GetActiveSnapshot(), GetAuthenticatedUserId(), GetCurrentRoleId(), GetCurrentStatementStartTimestamp(), GetCurrentTransactionStartTimestamp(), GetSessionDsmHandle(), GetTempNamespaceState(), GetTransactionSnapshot(), GetUserIdAndSecContext(), i, FixedParallelState::is_superuser, IsolationUsesXactSnapshot, 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_CLIENTCONNINFO, PARALLEL_KEY_COMBO_CID, PARALLEL_KEY_ENTRYPOINT, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_PENDING_SYNCS, PARALLEL_KEY_REINDEX_STATE, PARALLEL_KEY_RELMAPPER_STATE, PARALLEL_KEY_SESSION_DSM, PARALLEL_KEY_TRANSACTION_SNAPSHOT, PARALLEL_KEY_TRANSACTION_STATE, PARALLEL_KEY_UNCOMMITTEDENUMS, FixedParallelState::parallel_leader_backend_id, FixedParallelState::parallel_leader_pgproc, FixedParallelState::parallel_leader_pid, PARALLEL_MAGIC, ParallelContext::private_memory, FixedParallelState::sec_context, ParallelContext::seg, FixedParallelState::serializable_xact_handle, SerializeClientConnectionInfo(), SerializeComboCIDState(), SerializeGUCState(), SerializeLibraryState(), SerializePendingSyncs(), SerializeReindexState(), SerializeRelationMap(), SerializeSnapshot(), SerializeTransactionState(), SerializeUncommittedEnums(), 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(), ExecInitParallelPlan(), and parallel_vacuum_init().

◆ LaunchParallelWorkers()

void LaunchParallelWorkers ( ParallelContext pcxt)

Definition at line 550 of file parallel.c.

551 {
552  MemoryContext oldcontext;
553  BackgroundWorker worker;
554  int i;
555  bool any_registrations_failed = false;
556 
557  /* Skip this if we have no workers. */
558  if (pcxt->nworkers == 0 || pcxt->nworkers_to_launch == 0)
559  return;
560 
561  /* We need to be a lock group leader. */
563 
564  /* If we do have workers, we'd better have a DSM segment. */
565  Assert(pcxt->seg != NULL);
566 
567  /* We might be running in a short-lived memory context. */
569 
570  /* Configure a worker. */
571  memset(&worker, 0, sizeof(worker));
572  snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
573  MyProcPid);
574  snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
575  worker.bgw_flags =
580  sprintf(worker.bgw_library_name, "postgres");
581  sprintf(worker.bgw_function_name, "ParallelWorkerMain");
583  worker.bgw_notify_pid = MyProcPid;
584 
585  /*
586  * Start workers.
587  *
588  * The caller must be able to tolerate ending up with fewer workers than
589  * expected, so there is no need to throw an error here if registration
590  * fails. It wouldn't help much anyway, because registering the worker in
591  * no way guarantees that it will start up and initialize successfully.
592  */
593  for (i = 0; i < pcxt->nworkers_to_launch; ++i)
594  {
595  memcpy(worker.bgw_extra, &i, sizeof(int));
596  if (!any_registrations_failed &&
598  &pcxt->worker[i].bgwhandle))
599  {
601  pcxt->worker[i].bgwhandle);
602  pcxt->nworkers_launched++;
603  }
604  else
605  {
606  /*
607  * If we weren't able to register the worker, then we've bumped up
608  * against the max_worker_processes limit, and future
609  * registrations will probably fail too, so arrange to skip them.
610  * But we still have to execute this code for the remaining slots
611  * to make sure that we forget about the error queues we budgeted
612  * for those workers. Otherwise, we'll wait for them to start,
613  * but they never will.
614  */
615  any_registrations_failed = true;
616  pcxt->worker[i].bgwhandle = NULL;
618  pcxt->worker[i].error_mqh = NULL;
619  }
620  }
621 
622  /*
623  * Now that nworkers_launched has taken its final value, we can initialize
624  * known_attached_workers.
625  */
626  if (pcxt->nworkers_launched > 0)
627  {
628  pcxt->known_attached_workers =
629  palloc0(sizeof(bool) * pcxt->nworkers_launched);
630  pcxt->nknown_attached_workers = 0;
631  }
632 
633  /* Restore previous memory context. */
634  MemoryContextSwitchTo(oldcontext);
635 }
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:956
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
@ 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
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1095
#define sprintf
Definition: port.h:240
#define snprintf
Definition: port.h:238
static Datum UInt32GetDatum(uint32 X)
Definition: postgres.h:580
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:320
void BecomeLockGroupLeader(void)
Definition: proc.c:1905
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[BGW_MAXLEN]
Definition: bgworker.h:96

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, ParallelContext::nworkers_to_launch, palloc0(), RegisterDynamicBackgroundWorker(), ParallelContext::seg, shm_mq_detach(), shm_mq_set_handle(), snprintf, sprintf, TopTransactionContext, UInt32GetDatum(), and ParallelContext::worker.

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

◆ LookupParallelWorkerFunction()

static parallel_worker_main_type LookupParallelWorkerFunction ( const char *  libraryname,
const char *  funcname 
)
static

Definition at line 1599 of file parallel.c.

1600 {
1601  /*
1602  * If the function is to be loaded from postgres itself, search the
1603  * InternalParallelWorkers array.
1604  */
1605  if (strcmp(libraryname, "postgres") == 0)
1606  {
1607  int i;
1608 
1609  for (i = 0; i < lengthof(InternalParallelWorkers); i++)
1610  {
1611  if (strcmp(InternalParallelWorkers[i].fn_name, funcname) == 0)
1613  }
1614 
1615  /* We can only reach this by programming error. */
1616  elog(ERROR, "internal function \"%s\" not found", funcname);
1617  }
1618 
1619  /* Otherwise load from external library. */
1620  return (parallel_worker_main_type)
1621  load_external_function(libraryname, funcname, true, NULL);
1622 }
static const struct @13 InternalParallelWorkers[]
parallel_worker_main_type fn_addr
Definition: parallel.c:137
const char * fn_name
Definition: parallel.c:136
#define lengthof(array)
Definition: c.h:724
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
void(* parallel_worker_main_type)(dsm_segment *seg, shm_toc *toc)
Definition: parallel.h:23

References elog(), ERROR, fn_addr, fn_name, i, InternalParallelWorkers, lengthof, and load_external_function().

Referenced by ParallelWorkerMain().

◆ ParallelContextActive()

bool ParallelContextActive ( void  )

Definition at line 1001 of file parallel.c.

1002 {
1003  return !dlist_is_empty(&pcxt_list);
1004 }

References dlist_is_empty(), and pcxt_list.

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

◆ ParallelWorkerMain()

void ParallelWorkerMain ( Datum  main_arg)

Definition at line 1262 of file parallel.c.

1263 {
1264  dsm_segment *seg;
1265  shm_toc *toc;
1266  FixedParallelState *fps;
1267  char *error_queue_space;
1268  shm_mq *mq;
1269  shm_mq_handle *mqh;
1270  char *libraryspace;
1271  char *entrypointstate;
1272  char *library_name;
1273  char *function_name;
1274  parallel_worker_main_type entrypt;
1275  char *gucspace;
1276  char *combocidspace;
1277  char *tsnapspace;
1278  char *asnapspace;
1279  char *tstatespace;
1280  char *pendingsyncsspace;
1281  char *reindexspace;
1282  char *relmapperspace;
1283  char *uncommittedenumsspace;
1284  char *clientconninfospace;
1285  StringInfoData msgbuf;
1286  char *session_dsm_handle_space;
1287  Snapshot tsnapshot;
1288  Snapshot asnapshot;
1289 
1290  /* Set flag to indicate that we're initializing a parallel worker. */
1292 
1293  /* Establish signal handlers. */
1294  pqsignal(SIGTERM, die);
1296 
1297  /* Determine and set our parallel worker number. */
1299  memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
1300 
1301  /* Set up a memory context to work in, just for cleanliness. */
1303  "Parallel worker",
1305 
1306  /*
1307  * Attach to the dynamic shared memory segment for the parallel query, and
1308  * find its table of contents.
1309  *
1310  * Note: at this point, we have not created any ResourceOwner in this
1311  * process. This will result in our DSM mapping surviving until process
1312  * exit, which is fine. If there were a ResourceOwner, it would acquire
1313  * ownership of the mapping, but we have no need for that.
1314  */
1315  seg = dsm_attach(DatumGetUInt32(main_arg));
1316  if (seg == NULL)
1317  ereport(ERROR,
1318  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1319  errmsg("could not map dynamic shared memory segment")));
1321  if (toc == NULL)
1322  ereport(ERROR,
1323  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1324  errmsg("invalid magic number in dynamic shared memory segment")));
1325 
1326  /* Look up fixed parallel state. */
1327  fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1328  MyFixedParallelState = fps;
1329 
1330  /* Arrange to signal the leader if we exit. */
1334 
1335  /*
1336  * Now we can find and attach to the error queue provided for us. That's
1337  * good, because until we do that, any errors that happen here will not be
1338  * reported back to the process that requested that this worker be
1339  * launched.
1340  */
1341  error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1342  mq = (shm_mq *) (error_queue_space +
1345  mqh = shm_mq_attach(mq, seg, NULL);
1346  pq_redirect_to_shm_mq(seg, mqh);
1349 
1350  /*
1351  * Send a BackendKeyData message to the process that initiated parallelism
1352  * so that it has access to our PID before it receives any other messages
1353  * from us. Our cancel key is sent, too, since that's the way the
1354  * protocol message is defined, but it won't actually be used for anything
1355  * in this case.
1356  */
1357  pq_beginmessage(&msgbuf, 'K');
1358  pq_sendint32(&msgbuf, (int32) MyProcPid);
1359  pq_sendint32(&msgbuf, (int32) MyCancelKey);
1360  pq_endmessage(&msgbuf);
1361 
1362  /*
1363  * Hooray! Primary initialization is complete. Now, we need to set up our
1364  * backend-local state to match the original backend.
1365  */
1366 
1367  /*
1368  * Join locking group. We must do this before anything that could try to
1369  * acquire a heavyweight lock, because any heavyweight locks acquired to
1370  * this point could block either directly against the parallel group
1371  * leader or against some process which in turn waits for a lock that
1372  * conflicts with the parallel group leader, causing an undetected
1373  * deadlock. (If we can't join the lock group, the leader has gone away,
1374  * so just exit quietly.)
1375  */
1377  fps->parallel_leader_pid))
1378  return;
1379 
1380  /*
1381  * Restore transaction and statement start-time timestamps. This must
1382  * happen before anything that would start a transaction, else asserts in
1383  * xact.c will fire.
1384  */
1386 
1387  /*
1388  * Identify the entry point to be called. In theory this could result in
1389  * loading an additional library, though most likely the entry point is in
1390  * the core backend or in a library we just loaded.
1391  */
1392  entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1393  library_name = entrypointstate;
1394  function_name = entrypointstate + strlen(library_name) + 1;
1395 
1396  entrypt = LookupParallelWorkerFunction(library_name, function_name);
1397 
1398  /* Restore database connection. */
1400  fps->authenticated_user_id,
1401  0);
1402 
1403  /*
1404  * Set the client encoding to the database encoding, since that is what
1405  * the leader will expect.
1406  */
1408 
1409  /*
1410  * Load libraries that were loaded by original backend. We want to do
1411  * this before restoring GUCs, because the libraries might define custom
1412  * variables.
1413  */
1414  libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1416  RestoreLibraryState(libraryspace);
1417 
1418  /* Restore GUC values from launching backend. */
1419  gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1420  RestoreGUCState(gucspace);
1422 
1423  /* Crank up a transaction state appropriate to a parallel worker. */
1424  tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1425  StartParallelWorkerTransaction(tstatespace);
1426 
1427  /* Restore combo CID state. */
1428  combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1429  RestoreComboCIDState(combocidspace);
1430 
1431  /* Attach to the per-session DSM segment and contained objects. */
1432  session_dsm_handle_space =
1434  AttachSession(*(dsm_handle *) session_dsm_handle_space);
1435 
1436  /*
1437  * If the transaction isolation level is REPEATABLE READ or SERIALIZABLE,
1438  * the leader has serialized the transaction snapshot and we must restore
1439  * it. At lower isolation levels, there is no transaction-lifetime
1440  * snapshot, but we need TransactionXmin to get set to a value which is
1441  * less than or equal to the xmin of every snapshot that will be used by
1442  * this worker. The easiest way to accomplish that is to install the
1443  * active snapshot as the transaction snapshot. Code running in this
1444  * parallel worker might take new snapshots via GetTransactionSnapshot()
1445  * or GetLatestSnapshot(), but it shouldn't have any way of acquiring a
1446  * snapshot older than the active snapshot.
1447  */
1448  asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1449  tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, true);
1450  asnapshot = RestoreSnapshot(asnapspace);
1451  tsnapshot = tsnapspace ? RestoreSnapshot(tsnapspace) : asnapshot;
1452  RestoreTransactionSnapshot(tsnapshot,
1453  fps->parallel_leader_pgproc);
1454  PushActiveSnapshot(asnapshot);
1455 
1456  /*
1457  * We've changed which tuples we can see, and must therefore invalidate
1458  * system caches.
1459  */
1461 
1462  /*
1463  * Restore current role id. Skip verifying whether session user is
1464  * allowed to become this role and blindly restore the leader's state for
1465  * current role.
1466  */
1468 
1469  /* Restore user ID and security context. */
1471 
1472  /* Restore temp-namespace state to ensure search path matches leader's. */
1475 
1476  /* Restore pending syncs. */
1477  pendingsyncsspace = shm_toc_lookup(toc, PARALLEL_KEY_PENDING_SYNCS,
1478  false);
1479  RestorePendingSyncs(pendingsyncsspace);
1480 
1481  /* Restore reindex state. */
1482  reindexspace = shm_toc_lookup(toc, PARALLEL_KEY_REINDEX_STATE, false);
1483  RestoreReindexState(reindexspace);
1484 
1485  /* Restore relmapper state. */
1486  relmapperspace = shm_toc_lookup(toc, PARALLEL_KEY_RELMAPPER_STATE, false);
1487  RestoreRelationMap(relmapperspace);
1488 
1489  /* Restore uncommitted enums. */
1490  uncommittedenumsspace = shm_toc_lookup(toc, PARALLEL_KEY_UNCOMMITTEDENUMS,
1491  false);
1492  RestoreUncommittedEnums(uncommittedenumsspace);
1493 
1494  /* Restore the ClientConnectionInfo. */
1495  clientconninfospace = shm_toc_lookup(toc, PARALLEL_KEY_CLIENTCONNINFO,
1496  false);
1497  RestoreClientConnectionInfo(clientconninfospace);
1498 
1499  /*
1500  * Initialize SystemUser now that MyClientConnectionInfo is restored.
1501  * Also ensure that auth_method is actually valid, aka authn_id is not NULL.
1502  */
1506 
1507  /* Attach to the leader's serializable transaction, if SERIALIZABLE. */
1509 
1510  /*
1511  * We've initialized all of our state now; nothing should change
1512  * hereafter.
1513  */
1516 
1517  /*
1518  * Time to do the real work: invoke the caller-supplied code.
1519  */
1520  entrypt(seg, toc);
1521 
1522  /* Must exit parallel mode to pop active snapshot. */
1523  ExitParallelMode();
1524 
1525  /* Must pop active snapshot so snapmgr.c doesn't complain. */
1527 
1528  /* Shut down the parallel-worker transaction. */
1530 
1531  /* Detach from the per-session DSM segment. */
1532  DetachSession();
1533 
1534  /* Report success. */
1535  pq_putmessage('X', NULL, 0);
1536 }
static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
Definition: parallel.c:1599
int ParallelWorkerNumber
Definition: parallel.c:113
bool InitializingParallelWorker
Definition: parallel.c:119
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:122
static pid_t ParallelLeaderPid
Definition: parallel.c:128
static void ParallelWorkerShutdown(int code, Datum arg)
Definition: parallel.c:1571
void RestoreComboCIDState(char *comboCIDstate)
Definition: combocid.c:342
void RestoreLibraryState(char *start_address)
Definition: dfmgr.c:693
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:639
int32 MyCancelKey
Definition: globals.c:48
BackendId ParallelLeaderBackendId
Definition: globals.c:87
void RestoreGUCState(void *gucstate)
Definition: guc.c:6001
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3118
void RestoreReindexState(void *reindexstate)
Definition: index.c:4166
void InvalidateSystemCaches(void)
Definition: inval.c:702
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
int SetClientEncoding(int encoding)
Definition: mbutils.c:208
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:838
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:932
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:997
void RestoreClientConnectionInfo(char *conninfo)
Definition: miscinit.c:1062
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:625
void SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
Definition: namespace.c:3372
void RestoreUncommittedEnums(void *space)
Definition: pg_enum.c:770
#define die(msg)
Definition: pg_test_fsync.c:95
pqsigfunc pqsignal(int signo, pqsigfunc func)
static uint32 DatumGetUInt32(Datum X)
Definition: postgres.h:570
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5601
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5568
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
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:76
void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
Definition: pqmq.c:51
void AttachSerializableXact(SerializableXactHandle handle)
Definition: predicate.c:5193
void RestoreRelationMap(char *startAddress)
Definition: relmapper.c:739
void DetachSession(void)
Definition: session.c:201
void AttachSession(dsm_handle handle)
Definition: session.c:155
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:225
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition: shm_toc.c:64
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:683
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:2206
void RestoreTransactionSnapshot(Snapshot snapshot, void *source_pgproc)
Definition: snapmgr.c:2271
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:1935
void RestorePendingSyncs(char *startAddress)
Definition: storage.c:628
const char * authn_id
Definition: libpq-be.h:113
UserAuth auth_method
Definition: libpq-be.h:119
void ExitParallelMode(void)
Definition: xact.c:1048
void EnterParallelMode(void)
Definition: xact.c:1035
void StartTransactionCommand(void)
Definition: xact.c:2925
void StartParallelWorkerTransaction(char *tstatespace)
Definition: xact.c:5423
void SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
Definition: xact.c:843
void EndParallelWorkerTransaction(void)
Definition: xact.c:5448
void CommitTransactionCommand(void)
Definition: xact.c:3022

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AttachSerializableXact(), AttachSession(), ClientConnectionInfo::auth_method, FixedParallelState::authenticated_user_id, ClientConnectionInfo::authn_id, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), BecomeLockGroupMember(), before_shmem_exit(), 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(), hba_authname(), InitializeSystemUser(), InitializingParallelWorker, InvalidateSystemCaches(), FixedParallelState::is_superuser, LookupParallelWorkerFunction(), MyBgworkerEntry, MyCancelKey, MyClientConnectionInfo, MyFixedParallelState, MyProc, MyProcPid, FixedParallelState::outer_user_id, PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ACTIVE_SNAPSHOT, PARALLEL_KEY_CLIENTCONNINFO, PARALLEL_KEY_COMBO_CID, PARALLEL_KEY_ENTRYPOINT, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_PENDING_SYNCS, PARALLEL_KEY_REINDEX_STATE, PARALLEL_KEY_RELMAPPER_STATE, PARALLEL_KEY_SESSION_DSM, PARALLEL_KEY_TRANSACTION_SNAPSHOT, PARALLEL_KEY_TRANSACTION_STATE, PARALLEL_KEY_UNCOMMITTEDENUMS, FixedParallelState::parallel_leader_backend_id, FixedParallelState::parallel_leader_pgproc, FixedParallelState::parallel_leader_pid, PARALLEL_MAGIC, ParallelLeaderBackendId, ParallelLeaderPid, ParallelWorkerNumber, ParallelWorkerShutdown(), PointerGetDatum(), PopActiveSnapshot(), pq_beginmessage(), pq_endmessage(), pq_putmessage, pq_redirect_to_shm_mq(), pq_sendint32(), pq_set_parallel_leader(), pqsignal(), PushActiveSnapshot(), RestoreClientConnectionInfo(), RestoreComboCIDState(), RestoreGUCState(), RestoreLibraryState(), RestorePendingSyncs(), RestoreReindexState(), RestoreRelationMap(), RestoreSnapshot(), RestoreTransactionSnapshot(), RestoreUncommittedEnums(), 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.

◆ ParallelWorkerReportLastRecEnd()

void ParallelWorkerReportLastRecEnd ( XLogRecPtr  last_xlog_end)

Definition at line 1543 of file parallel.c.

1544 {
1546 
1547  Assert(fps != NULL);
1548  SpinLockAcquire(&fps->mutex);
1549  if (fps->last_xlog_end < last_xlog_end)
1550  fps->last_xlog_end = last_xlog_end;
1551  SpinLockRelease(&fps->mutex);
1552 }
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62

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

Referenced by CommitTransaction().

◆ ParallelWorkerShutdown()

static void ParallelWorkerShutdown ( int  code,
Datum  arg 
)
static

Definition at line 1571 of file parallel.c.

1572 {
1576 
1578 }
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:261
@ PROCSIG_PARALLEL_MESSAGE
Definition: procsignal.h:34

References arg, DatumGetPointer(), dsm_detach(), ParallelLeaderBackendId, ParallelLeaderPid, PROCSIG_PARALLEL_MESSAGE, and SendProcSignal().

Referenced by ParallelWorkerMain().

◆ ReinitializeParallelDSM()

void ReinitializeParallelDSM ( ParallelContext pcxt)

Definition at line 486 of file parallel.c.

487 {
488  FixedParallelState *fps;
489 
490  /* Wait for any old workers to exit. */
491  if (pcxt->nworkers_launched > 0)
492  {
495  pcxt->nworkers_launched = 0;
496  if (pcxt->known_attached_workers)
497  {
499  pcxt->known_attached_workers = NULL;
500  pcxt->nknown_attached_workers = 0;
501  }
502  }
503 
504  /* Reset a few bits of fixed parallel state to a clean state. */
505  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
506  fps->last_xlog_end = 0;
507 
508  /* Recreate error queues (if they exist). */
509  if (pcxt->nworkers > 0)
510  {
511  char *error_queue_space;
512  int i;
513 
514  error_queue_space =
516  for (i = 0; i < pcxt->nworkers; ++i)
517  {
518  char *start;
519  shm_mq *mq;
520 
521  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
524  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
525  }
526  }
527 }
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:773

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(), and parallel_vacuum_process_all_indexes().

◆ ReinitializeParallelWorkers()

void ReinitializeParallelWorkers ( ParallelContext pcxt,
int  nworkers_to_launch 
)

Definition at line 536 of file parallel.c.

537 {
538  /*
539  * The number of workers that need to be launched must be less than the
540  * number of workers with which the parallel context is initialized.
541  */
542  Assert(pcxt->nworkers >= nworkers_to_launch);
543  pcxt->nworkers_to_launch = nworkers_to_launch;
544 }

References Assert(), ParallelContext::nworkers, and ParallelContext::nworkers_to_launch.

Referenced by parallel_vacuum_process_all_indexes().

◆ WaitForParallelWorkersToAttach()

void WaitForParallelWorkersToAttach ( ParallelContext pcxt)

Definition at line 670 of file parallel.c.

671 {
672  int i;
673 
674  /* Skip this if we have no launched workers. */
675  if (pcxt->nworkers_launched == 0)
676  return;
677 
678  for (;;)
679  {
680  /*
681  * This will process any parallel messages that are pending and it may
682  * also throw an error propagated from a worker.
683  */
685 
686  for (i = 0; i < pcxt->nworkers_launched; ++i)
687  {
689  shm_mq *mq;
690  int rc;
691  pid_t pid;
692 
693  if (pcxt->known_attached_workers[i])
694  continue;
695 
696  /*
697  * If error_mqh is NULL, then the worker has already exited
698  * cleanly.
699  */
700  if (pcxt->worker[i].error_mqh == NULL)
701  {
702  pcxt->known_attached_workers[i] = true;
703  ++pcxt->nknown_attached_workers;
704  continue;
705  }
706 
708  if (status == BGWH_STARTED)
709  {
710  /* Has the worker attached to the error queue? */
711  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
712  if (shm_mq_get_sender(mq) != NULL)
713  {
714  /* Yes, so it is known to be attached. */
715  pcxt->known_attached_workers[i] = true;
716  ++pcxt->nknown_attached_workers;
717  }
718  }
719  else if (status == BGWH_STOPPED)
720  {
721  /*
722  * If the worker stopped without attaching to the error queue,
723  * throw an error.
724  */
725  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
726  if (shm_mq_get_sender(mq) == NULL)
727  ereport(ERROR,
728  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
729  errmsg("parallel worker failed to initialize"),
730  errhint("More details may be available in the server log.")));
731 
732  pcxt->known_attached_workers[i] = true;
733  ++pcxt->nknown_attached_workers;
734  }
735  else
736  {
737  /*
738  * Worker not yet started, so we must wait. The postmaster
739  * will notify us if the worker's state changes. Our latch
740  * might also get set for some other reason, but if so we'll
741  * just end up waiting for the same worker again.
742  */
743  rc = WaitLatch(MyLatch,
746 
747  if (rc & WL_LATCH_SET)
749  }
750  }
751 
752  /* If all workers are known to have started, we're done. */
753  if (pcxt->nknown_attached_workers >= pcxt->nworkers_launched)
754  {
756  break;
757  }
758  }
759 }
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1068
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_STARTED
Definition: bgworker.h:105
@ BGWH_STOPPED
Definition: bgworker.h:107
int errhint(const char *fmt,...)
Definition: elog.c:1153
void ResetLatch(Latch *latch)
Definition: latch.c:683
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:476
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
shm_mq * shm_mq_get_queue(shm_mq_handle *mqh)
Definition: shm_mq.c:906
PGPROC * shm_mq_get_sender(shm_mq *mq)
Definition: shm_mq.c:258
@ WAIT_EVENT_BGWORKER_STARTUP
Definition: wait_event.h:87

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().

◆ WaitForParallelWorkersToExit()

static void WaitForParallelWorkersToExit ( ParallelContext pcxt)
static

Definition at line 887 of file parallel.c.

888 {
889  int i;
890 
891  /* Wait until the workers actually die. */
892  for (i = 0; i < pcxt->nworkers_launched; ++i)
893  {
895 
896  if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
897  continue;
898 
900 
901  /*
902  * If the postmaster kicked the bucket, we have no chance of cleaning
903  * up safely -- we won't be able to tell when our workers are actually
904  * dead. This doesn't necessitate a PANIC since they will all abort
905  * eventually, but we can't safely continue this session.
906  */
908  ereport(FATAL,
909  (errcode(ERRCODE_ADMIN_SHUTDOWN),
910  errmsg("postmaster exited during a parallel transaction")));
911 
912  /* Release memory. */
913  pfree(pcxt->worker[i].bgwhandle);
914  pcxt->worker[i].bgwhandle = NULL;
915  }
916 }
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1168
@ BGWH_POSTMASTER_DIED
Definition: bgworker.h:108
#define FATAL
Definition: elog.h:37

References BGWH_POSTMASTER_DIED, ParallelWorkerInfo::bgwhandle, ereport, errcode(), errmsg(), FATAL, i, ParallelContext::nworkers_launched, pfree(), status(), WaitForBackgroundWorkerShutdown(), and ParallelContext::worker.

Referenced by DestroyParallelContext(), and ReinitializeParallelDSM().

◆ WaitForParallelWorkersToFinish()

void WaitForParallelWorkersToFinish ( ParallelContext pcxt)

Definition at line 773 of file parallel.c.

774 {
775  for (;;)
776  {
777  bool anyone_alive = false;
778  int nfinished = 0;
779  int i;
780 
781  /*
782  * This will process any parallel messages that are pending, which may
783  * change the outcome of the loop that follows. It may also throw an
784  * error propagated from a worker.
785  */
787 
788  for (i = 0; i < pcxt->nworkers_launched; ++i)
789  {
790  /*
791  * If error_mqh is NULL, then the worker has already exited
792  * cleanly. If we have received a message through error_mqh from
793  * the worker, we know it started up cleanly, and therefore we're
794  * certain to be notified when it exits.
795  */
796  if (pcxt->worker[i].error_mqh == NULL)
797  ++nfinished;
798  else if (pcxt->known_attached_workers[i])
799  {
800  anyone_alive = true;
801  break;
802  }
803  }
804 
805  if (!anyone_alive)
806  {
807  /* If all workers are known to have finished, we're done. */
808  if (nfinished >= pcxt->nworkers_launched)
809  {
810  Assert(nfinished == pcxt->nworkers_launched);
811  break;
812  }
813 
814  /*
815  * We didn't detect any living workers, but not all workers are
816  * known to have exited cleanly. Either not all workers have
817  * launched yet, or maybe some of them failed to start or
818  * terminated abnormally.
819  */
820  for (i = 0; i < pcxt->nworkers_launched; ++i)
821  {
822  pid_t pid;
823  shm_mq *mq;
824 
825  /*
826  * If the worker is BGWH_NOT_YET_STARTED or BGWH_STARTED, we
827  * should just keep waiting. If it is BGWH_STOPPED, then
828  * further investigation is needed.
829  */
830  if (pcxt->worker[i].error_mqh == NULL ||
831  pcxt->worker[i].bgwhandle == NULL ||
833  &pid) != BGWH_STOPPED)
834  continue;
835 
836  /*
837  * Check whether the worker ended up stopped without ever
838  * attaching to the error queue. If so, the postmaster was
839  * unable to fork the worker or it exited without initializing
840  * properly. We must throw an error, since the caller may
841  * have been expecting the worker to do some work before
842  * exiting.
843  */
844  mq = shm_mq_get_queue(pcxt->worker[i].error_mqh);
845  if (shm_mq_get_sender(mq) == NULL)
846  ereport(ERROR,
847  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
848  errmsg("parallel worker failed to initialize"),
849  errhint("More details may be available in the server log.")));
850 
851  /*
852  * The worker is stopped, but is attached to the error queue.
853  * Unless there's a bug somewhere, this will only happen when
854  * the worker writes messages and terminates after the
855  * CHECK_FOR_INTERRUPTS() near the top of this function and
856  * before the call to GetBackgroundWorkerPid(). In that case,
857  * or latch should have been set as well and the right things
858  * will happen on the next pass through the loop.
859  */
860  }
861  }
862 
866  }
867 
868  if (pcxt->toc != NULL)
869  {
870  FixedParallelState *fps;
871 
872  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
873  if (fps->last_xlog_end > XactLastRecEnd)
875  }
876 }
@ WAIT_EVENT_PARALLEL_FINISH
Definition: wait_event.h:116
XLogRecPtr XactLastRecEnd
Definition: xlog.c:257

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(), parallel_vacuum_process_all_indexes(), and ReinitializeParallelDSM().

Variable Documentation

◆ fn_addr

Definition at line 137 of file parallel.c.

Referenced by LookupParallelWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 136 of file parallel.c.

Referenced by LookupParallelWorkerFunction().

◆ InitializingParallelWorker

bool InitializingParallelWorker = false

◆ 

const { ... } InternalParallelWorkers[]
Initial value:
=
{
{
"ParallelQueryMain", ParallelQueryMain
},
{
"_bt_parallel_build_main", _bt_parallel_build_main
},
{
"parallel_vacuum_main", parallel_vacuum_main
}
}
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
void _bt_parallel_build_main(dsm_segment *seg, shm_toc *toc)
Definition: nbtsort.c:1798
void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc)

Referenced by LookupParallelWorkerFunction().

◆ MyFixedParallelState

FixedParallelState* MyFixedParallelState
static

Definition at line 122 of file parallel.c.

Referenced by ParallelWorkerMain(), and ParallelWorkerReportLastRecEnd().

◆ ParallelLeaderPid

pid_t ParallelLeaderPid
static

Definition at line 128 of file parallel.c.

Referenced by ParallelWorkerMain(), and ParallelWorkerShutdown().

◆ ParallelMessagePending

volatile sig_atomic_t ParallelMessagePending = false

◆ ParallelWorkerNumber

◆ pcxt_list