PostgreSQL Source Code  git master
parallel.c File Reference
#include "postgres.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 "commands/async.h"
#include "executor/execParallel.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqmq.h"
#include "miscadmin.h"
#include "optimizer/planmain.h"
#include "pgstat.h"
#include "storage/ipc.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/resowner.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_REINDEX_STATE   UINT64CONST(0xFFFFFFFFFFFF000B)
 

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)
 
ParallelContextCreateParallelContext (const char *library_name, const char *function_name, int nworkers)
 
void InitializeParallelDSM (ParallelContext *pcxt)
 
void ReinitializeParallelDSM (ParallelContext *pcxt)
 
void LaunchParallelWorkers (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 bool ParallelMessagePending = false
 
bool InitializingParallelWorker = false
 
static FixedParallelStateMyFixedParallelState
 
static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list)
 
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 51 of file parallel.c.

Referenced by InitializeParallelDSM(), ParallelWorkerMain(), and ReinitializeParallelDSM().

◆ PARALLEL_KEY_ACTIVE_SNAPSHOT

#define PARALLEL_KEY_ACTIVE_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0007)

Definition at line 67 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_COMBO_CID

#define PARALLEL_KEY_COMBO_CID   UINT64CONST(0xFFFFFFFFFFFF0005)

Definition at line 65 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_ENTRYPOINT

#define PARALLEL_KEY_ENTRYPOINT   UINT64CONST(0xFFFFFFFFFFFF0009)

Definition at line 69 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_ERROR_QUEUE

#define PARALLEL_KEY_ERROR_QUEUE   UINT64CONST(0xFFFFFFFFFFFF0002)

Definition at line 62 of file parallel.c.

Referenced by InitializeParallelDSM(), ParallelWorkerMain(), and ReinitializeParallelDSM().

◆ PARALLEL_KEY_FIXED

#define PARALLEL_KEY_FIXED   UINT64CONST(0xFFFFFFFFFFFF0001)

◆ PARALLEL_KEY_GUC

#define PARALLEL_KEY_GUC   UINT64CONST(0xFFFFFFFFFFFF0004)

Definition at line 64 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_LIBRARY

#define PARALLEL_KEY_LIBRARY   UINT64CONST(0xFFFFFFFFFFFF0003)

Definition at line 63 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_REINDEX_STATE

#define PARALLEL_KEY_REINDEX_STATE   UINT64CONST(0xFFFFFFFFFFFF000B)

Definition at line 71 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_SESSION_DSM

#define PARALLEL_KEY_SESSION_DSM   UINT64CONST(0xFFFFFFFFFFFF000A)

Definition at line 70 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_TRANSACTION_SNAPSHOT

#define PARALLEL_KEY_TRANSACTION_SNAPSHOT   UINT64CONST(0xFFFFFFFFFFFF0006)

Definition at line 66 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_KEY_TRANSACTION_STATE

#define PARALLEL_KEY_TRANSACTION_STATE   UINT64CONST(0xFFFFFFFFFFFF0008)

Definition at line 68 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

◆ PARALLEL_MAGIC

#define PARALLEL_MAGIC   0x50477c7c

Definition at line 54 of file parallel.c.

Referenced by InitializeParallelDSM(), and ParallelWorkerMain().

Typedef Documentation

◆ FixedParallelState

Function Documentation

◆ AtEOSubXact_Parallel()

void AtEOSubXact_Parallel ( bool  isCommit,
SubTransactionId  mySubId 
)

Definition at line 932 of file parallel.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

933 {
934  while (!dlist_is_empty(&pcxt_list))
935  {
936  ParallelContext *pcxt;
937 
939  if (pcxt->subid != mySubId)
940  break;
941  if (isCommit)
942  elog(WARNING, "leaked parallel context");
944  }
945 }
SubTransactionId subid
Definition: parallel.h:35
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:640
#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
static dlist_head pcxt_list
Definition: parallel.c:114
#define elog
Definition: elog.h:219

◆ AtEOXact_Parallel()

void AtEOXact_Parallel ( bool  isCommit)

Definition at line 951 of file parallel.c.

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

Referenced by AbortTransaction(), and CommitTransaction().

952 {
953  while (!dlist_is_empty(&pcxt_list))
954  {
955  ParallelContext *pcxt;
956 
958  if (isCommit)
959  elog(WARNING, "leaked parallel context");
961  }
962 }
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:640
#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
static dlist_head pcxt_list
Definition: parallel.c:114
#define elog
Definition: elog.h:219

◆ CreateParallelContext()

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

Definition at line 144 of file parallel.c.

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

Referenced by ExecInitParallelPlan().

146 {
147  MemoryContext oldcontext;
148  ParallelContext *pcxt;
149 
150  /* It is unsafe to create a parallel context if not in parallel mode. */
152 
153  /* Number of workers should be non-negative. */
154  Assert(nworkers >= 0);
155 
156  /*
157  * If dynamic shared memory is not available, we won't be able to use
158  * background workers.
159  */
161  nworkers = 0;
162 
163  /*
164  * If we are running under serializable isolation, we can't use parallel
165  * workers, at least not until somebody enhances that mechanism to be
166  * parallel-aware.
167  */
169  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:48
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
char * pstrdup(const char *in)
Definition: mcxt.c:1063
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:906
char * function_name
Definition: parallel.h:39
int dynamic_shared_memory_type
Definition: dsm_impl.c:113
#define shm_toc_initialize_estimator(e)
Definition: shm_toc.h:49
void * palloc0(Size size)
Definition: mcxt.c:864
char * library_name
Definition: parallel.h:38
#define Assert(condition)
Definition: c.h:680
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
#define DSM_IMPL_NONE
Definition: dsm_impl.h:17
dlist_node node
Definition: parallel.h:34
ErrorContextCallback * error_context_stack
Definition: parallel.h:40
#define IsolationIsSerializable()
Definition: xact.h:44
static dlist_head pcxt_list
Definition: parallel.c:114

◆ DestroyParallelContext()

void DestroyParallelContext ( ParallelContext pcxt)

Definition at line 640 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 AtEOSubXact_Parallel(), AtEOXact_Parallel(), and ExecParallelCleanup().

641 {
642  int i;
643 
644  /*
645  * Be careful about order of operations here! We remove the parallel
646  * context from the list before we do anything else; otherwise, if an
647  * error occurs during a subsequent step, we might try to nuke it again
648  * from AtEOXact_Parallel or AtEOSubXact_Parallel.
649  */
650  dlist_delete(&pcxt->node);
651 
652  /* Kill each worker in turn, and forget their error queues. */
653  if (pcxt->worker != NULL)
654  {
655  for (i = 0; i < pcxt->nworkers_launched; ++i)
656  {
657  if (pcxt->worker[i].error_mqh != NULL)
658  {
660 
661  shm_mq_detach(pcxt->worker[i].error_mqh);
662  pcxt->worker[i].error_mqh = NULL;
663  }
664  }
665  }
666 
667  /*
668  * If we have allocated a shared memory segment, detach it. This will
669  * implicitly detach the error queues, and any other shared memory queues,
670  * stored there.
671  */
672  if (pcxt->seg != NULL)
673  {
674  dsm_detach(pcxt->seg);
675  pcxt->seg = NULL;
676  }
677 
678  /*
679  * If this parallel context is actually in backend-private memory rather
680  * than shared memory, free that memory instead.
681  */
682  if (pcxt->private_memory != NULL)
683  {
684  pfree(pcxt->private_memory);
685  pcxt->private_memory = NULL;
686  }
687 
688  /*
689  * We can't finish transaction commit or abort until all of the workers
690  * have exited. This means, in particular, that we can't respond to
691  * interrupts at this stage.
692  */
693  HOLD_INTERRUPTS();
696 
697  /* Free the worker array itself. */
698  if (pcxt->worker != NULL)
699  {
700  pfree(pcxt->worker);
701  pcxt->worker = NULL;
702  }
703 
704  /* Free memory. */
705  pfree(pcxt->library_name);
706  pfree(pcxt->function_name);
707  pfree(pcxt);
708 }
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:775
dsm_segment * seg
Definition: parallel.h:42
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:600
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:936
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:1184
char * library_name
Definition: parallel.h:38
dlist_node node
Definition: parallel.h:34
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:713
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
void * private_memory
Definition: parallel.h:43

◆ HandleParallelMessage()

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

Definition at line 827 of file parallel.c.

References _, ErrorData::context, ErrorData::elevel, elog, ERROR, ParallelContext::error_context_stack, error_context_stack, ParallelWorkerInfo::error_mqh, force_parallel_mode, FORCE_PARALLEL_REGRESS, i, StringInfoData::len, Min, 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().

828 {
829  char msgtype;
830 
831  msgtype = pq_getmsgbyte(msg);
832 
833  switch (msgtype)
834  {
835  case 'K': /* BackendKeyData */
836  {
837  int32 pid = pq_getmsgint(msg, 4);
838 
839  (void) pq_getmsgint(msg, 4); /* discard cancel key */
840  (void) pq_getmsgend(msg);
841  pcxt->worker[i].pid = pid;
842  break;
843  }
844 
845  case 'E': /* ErrorResponse */
846  case 'N': /* NoticeResponse */
847  {
848  ErrorData edata;
849  ErrorContextCallback *save_error_context_stack;
850 
851  /* Parse ErrorResponse or NoticeResponse. */
852  pq_parse_errornotice(msg, &edata);
853 
854  /* Death of a worker isn't enough justification for suicide. */
855  edata.elevel = Min(edata.elevel, ERROR);
856 
857  /*
858  * If desired, add a context line to show that this is a
859  * message propagated from a parallel worker. Otherwise, it
860  * can sometimes be confusing to understand what actually
861  * happened. (We don't do this in FORCE_PARALLEL_REGRESS mode
862  * because it causes test-result instability depending on
863  * whether a parallel worker is actually used or not.)
864  */
866  {
867  if (edata.context)
868  edata.context = psprintf("%s\n%s", edata.context,
869  _("parallel worker"));
870  else
871  edata.context = pstrdup(_("parallel worker"));
872  }
873 
874  /*
875  * Context beyond that should use the error context callbacks
876  * that were in effect when the ParallelContext was created,
877  * not the current ones.
878  */
879  save_error_context_stack = error_context_stack;
881 
882  /* Rethrow error or print notice. */
883  ThrowErrorData(&edata);
884 
885  /* Not an error, so restore previous context stack. */
886  error_context_stack = save_error_context_stack;
887 
888  break;
889  }
890 
891  case 'A': /* NotifyResponse */
892  {
893  /* Propagate NotifyResponse. */
894  int32 pid;
895  const char *channel;
896  const char *payload;
897 
898  pid = pq_getmsgint(msg, 4);
899  channel = pq_getmsgrawstring(msg);
900  payload = pq_getmsgrawstring(msg);
901  pq_endmessage(msg);
902 
903  NotifyMyFrontEnd(channel, payload, pid);
904 
905  break;
906  }
907 
908  case 'X': /* Terminate, indicating clean exit */
909  {
911  pcxt->worker[i].error_mqh = NULL;
912  break;
913  }
914 
915  default:
916  {
917  elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
918  msgtype, msg->len);
919  }
920  }
921 }
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:775
char * pstrdup(const char *in)
Definition: mcxt.c:1063
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define Min(x, y)
Definition: c.h:826
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:610
signed int int32
Definition: c.h:294
ErrorContextCallback * error_context_stack
Definition: elog.c:88
ParallelWorkerInfo * worker
Definition: parallel.h:45
#define ERROR
Definition: elog.h:43
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition: pqmq.c:215
shm_mq_handle * error_mqh
Definition: parallel.h:28
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1612
int elevel
Definition: elog.h:331
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
int force_parallel_mode
Definition: planner.c:63
char * context
Definition: elog.h:347
ErrorContextCallback * error_context_stack
Definition: parallel.h:40
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
int i
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define elog
Definition: elog.h:219
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
#define _(x)
Definition: elog.c:84
void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
Definition: async.c:2096

◆ HandleParallelMessageInterrupt()

void HandleParallelMessageInterrupt ( void  )

Definition at line 727 of file parallel.c.

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

Referenced by procsignal_sigusr1_handler().

728 {
729  InterruptPending = true;
730  ParallelMessagePending = true;
731  SetLatch(MyLatch);
732 }
volatile bool ParallelMessagePending
Definition: parallel.c:105
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ HandleParallelMessages()

void HandleParallelMessages ( void  )

Definition at line 738 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().

739 {
740  dlist_iter iter;
741  MemoryContext oldcontext;
742 
743  static MemoryContext hpm_context = NULL;
744 
745  /*
746  * This is invoked from ProcessInterrupts(), and since some of the
747  * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
748  * for recursive calls if more signals are received while this runs. It's
749  * unclear that recursive entry would be safe, and it doesn't seem useful
750  * even if it is safe, so let's block interrupts until done.
751  */
752  HOLD_INTERRUPTS();
753 
754  /*
755  * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
756  * don't want to risk leaking data into long-lived contexts, so let's do
757  * our work here in a private context that we can reset on each use.
758  */
759  if (hpm_context == NULL) /* first time through? */
761  "HandleParallelMessages",
763  else
764  MemoryContextReset(hpm_context);
765 
766  oldcontext = MemoryContextSwitchTo(hpm_context);
767 
768  /* OK to process messages. Reset the flag saying there are more to do. */
769  ParallelMessagePending = false;
770 
771  dlist_foreach(iter, &pcxt_list)
772  {
773  ParallelContext *pcxt;
774  int i;
775 
776  pcxt = dlist_container(ParallelContext, node, iter.cur);
777  if (pcxt->worker == NULL)
778  continue;
779 
780  for (i = 0; i < pcxt->nworkers_launched; ++i)
781  {
782  /*
783  * Read as many messages as we can from each worker, but stop when
784  * either (1) the worker's error queue goes away, which can happen
785  * if we receive a Terminate message from the worker; or (2) no
786  * more messages can be read from the worker without blocking.
787  */
788  while (pcxt->worker[i].error_mqh != NULL)
789  {
790  shm_mq_result res;
791  Size nbytes;
792  void *data;
793 
794  res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
795  &data, true);
796  if (res == SHM_MQ_WOULD_BLOCK)
797  break;
798  else if (res == SHM_MQ_SUCCESS)
799  {
800  StringInfoData msg;
801 
802  initStringInfo(&msg);
803  appendBinaryStringInfo(&msg, data, nbytes);
804  HandleParallelMessage(pcxt, i, &msg);
805  pfree(msg.data);
806  }
807  else
808  ereport(ERROR,
809  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
810  errmsg("lost connection to parallel worker")));
811  }
812  }
813  }
814 
815  MemoryContextSwitchTo(oldcontext);
816 
817  /* Might as well clear the context on our way out */
818  MemoryContextReset(hpm_context);
819 
821 }
#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:575
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:134
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
volatile bool ParallelMessagePending
Definition: parallel.c:105
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:936
#define ERROR
Definition: elog.h:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
Definition: parallel.c:827
shm_mq_handle * error_mqh
Definition: parallel.h:28
int nworkers_launched
Definition: parallel.h:37
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
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:414
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
static dlist_head pcxt_list
Definition: parallel.c:114
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition: shm_mq.c:522
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208

◆ 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(), EstimateGUCStateSpace(), EstimateLibraryStateSpace(), EstimateReindexStateSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ParallelContext::estimator, ParallelContext::function_name, GetActiveSnapshot(), GetAuthenticatedUserId(), GetCurrentRoleId(), 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_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_REINDEX_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, SerializeComboCIDState(), SerializeGUCState(), SerializeLibraryState(), SerializeReindexState(), SerializeSnapshot(), SerializeTransactionState(), session_auth_is_superuser, 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::temp_namespace_id, FixedParallelState::temp_toast_namespace_id, ParallelContext::toc, TopMemoryContext, TopTransactionContext, and ParallelContext::worker.

Referenced by 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 segsize = 0;
207  int i;
208  FixedParallelState *fps;
209  dsm_handle session_dsm_handle = DSM_HANDLE_INVALID;
210  Snapshot transaction_snapshot = GetTransactionSnapshot();
211  Snapshot active_snapshot = GetActiveSnapshot();
212 
213  /* We might be running in a very short-lived memory context. */
215 
216  /* Allow space to store the fixed-size parallel state. */
218  shm_toc_estimate_keys(&pcxt->estimator, 1);
219 
220  /*
221  * Normally, the user will have requested at least one worker process, but
222  * if by chance they have not, we can skip a bunch of things here.
223  */
224  if (pcxt->nworkers > 0)
225  {
226  /* Get (or create) the per-session DSM segment's handle. */
227  session_dsm_handle = GetSessionDsmHandle();
228 
229  /*
230  * If we weren't able to create a per-session DSM segment, then we can
231  * continue but we can't safely launch any workers because their
232  * record typmods would be incompatible so they couldn't exchange
233  * tuples.
234  */
235  if (session_dsm_handle == DSM_HANDLE_INVALID)
236  pcxt->nworkers = 0;
237  }
238 
239  if (pcxt->nworkers > 0)
240  {
241  /* Estimate space for various kinds of state sharing. */
242  library_len = EstimateLibraryStateSpace();
243  shm_toc_estimate_chunk(&pcxt->estimator, library_len);
244  guc_len = EstimateGUCStateSpace();
245  shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
246  combocidlen = EstimateComboCIDStateSpace();
247  shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
248  tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
249  shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
250  asnaplen = EstimateSnapshotSpace(active_snapshot);
251  shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
252  tstatelen = EstimateTransactionStateSpace();
253  shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
255  reindexlen = EstimateReindexStateSpace();
256  shm_toc_estimate_chunk(&pcxt->estimator, reindexlen);
257  /* If you add more chunks here, you probably need to add keys. */
258  shm_toc_estimate_keys(&pcxt->estimator, 8);
259 
260  /* Estimate space need for error queues. */
263  "parallel error queue size not buffer-aligned");
266  pcxt->nworkers));
267  shm_toc_estimate_keys(&pcxt->estimator, 1);
268 
269  /* Estimate how much we'll need for the entrypoint info. */
270  shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name) +
271  strlen(pcxt->function_name) + 2);
272  shm_toc_estimate_keys(&pcxt->estimator, 1);
273  }
274 
275  /*
276  * Create DSM and initialize with new table of contents. But if the user
277  * didn't request any workers, then don't bother creating a dynamic shared
278  * memory segment; instead, just use backend-private memory.
279  *
280  * Also, if we can't create a dynamic shared memory segment because the
281  * maximum number of segments have already been created, then fall back to
282  * backend-private memory, and plan not to use any workers. We hope this
283  * won't happen very often, but it's better to abandon the use of
284  * parallelism than to fail outright.
285  */
286  segsize = shm_toc_estimate(&pcxt->estimator);
287  if (pcxt->nworkers > 0)
289  if (pcxt->seg != NULL)
291  dsm_segment_address(pcxt->seg),
292  segsize);
293  else
294  {
295  pcxt->nworkers = 0;
298  segsize);
299  }
300 
301  /* Initialize fixed-size state in shared memory. */
302  fps = (FixedParallelState *)
303  shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
304  fps->database_id = MyDatabaseId;
314  SpinLockInit(&fps->mutex);
315  fps->last_xlog_end = 0;
317 
318  /* We can skip the rest of this if we're not budgeting for any workers. */
319  if (pcxt->nworkers > 0)
320  {
321  char *libraryspace;
322  char *gucspace;
323  char *combocidspace;
324  char *tsnapspace;
325  char *asnapspace;
326  char *tstatespace;
327  char *reindexspace;
328  char *error_queue_space;
329  char *session_dsm_handle_space;
330  char *entrypointstate;
331  Size lnamelen;
332 
333  /* Serialize shared libraries we have loaded. */
334  libraryspace = shm_toc_allocate(pcxt->toc, library_len);
335  SerializeLibraryState(library_len, libraryspace);
336  shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
337 
338  /* Serialize GUC settings. */
339  gucspace = shm_toc_allocate(pcxt->toc, guc_len);
340  SerializeGUCState(guc_len, gucspace);
341  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
342 
343  /* Serialize combo CID state. */
344  combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
345  SerializeComboCIDState(combocidlen, combocidspace);
346  shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
347 
348  /* Serialize transaction snapshot and active snapshot. */
349  tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
350  SerializeSnapshot(transaction_snapshot, tsnapspace);
352  tsnapspace);
353  asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
354  SerializeSnapshot(active_snapshot, asnapspace);
355  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
356 
357  /* Provide the handle for per-session segment. */
358  session_dsm_handle_space = shm_toc_allocate(pcxt->toc,
359  sizeof(dsm_handle));
360  *(dsm_handle *) session_dsm_handle_space = session_dsm_handle;
362  session_dsm_handle_space);
363 
364  /* Serialize transaction state. */
365  tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
366  SerializeTransactionState(tstatelen, tstatespace);
368 
369  /* Serialize reindex state. */
370  reindexspace = shm_toc_allocate(pcxt->toc, reindexlen);
371  SerializeReindexState(reindexlen, reindexspace);
372  shm_toc_insert(pcxt->toc, PARALLEL_KEY_REINDEX_STATE, reindexspace);
373 
374  /* Allocate space for worker information. */
375  pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
376 
377  /*
378  * Establish error queues in dynamic shared memory.
379  *
380  * These queues should be used only for transmitting ErrorResponse,
381  * NoticeResponse, and NotifyResponse protocol messages. Tuple data
382  * should be transmitted via separate (possibly larger?) queues.
383  */
384  error_queue_space =
385  shm_toc_allocate(pcxt->toc,
387  pcxt->nworkers));
388  for (i = 0; i < pcxt->nworkers; ++i)
389  {
390  char *start;
391  shm_mq *mq;
392 
393  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
394  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
396  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
397  }
398  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
399 
400  /*
401  * Serialize entrypoint information. It's unsafe to pass function
402  * pointers across processes, as the function pointer may be different
403  * in each process in EXEC_BACKEND builds, so we always pass library
404  * and function name. (We use library name "postgres" for functions
405  * in the core backend.)
406  */
407  lnamelen = strlen(pcxt->library_name);
408  entrypointstate = shm_toc_allocate(pcxt->toc, lnamelen +
409  strlen(pcxt->function_name) + 2);
410  strcpy(entrypointstate, pcxt->library_name);
411  strcpy(entrypointstate + lnamelen + 1, pcxt->function_name);
412  shm_toc_insert(pcxt->toc, PARALLEL_KEY_ENTRYPOINT, entrypointstate);
413  }
414 
415  /* Restore previous memory context. */
416  MemoryContextSwitchTo(oldcontext);
417 }
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:51
shm_toc * shm_toc_create(uint64 magic, void *address, Size nbytes)
Definition: shm_toc.c:40
int MyProcPid
Definition: globals.c:39
BackendId MyBackendId
Definition: globals.c:73
MemoryContext TopTransactionContext
Definition: mcxt.c:48
uint32 dsm_handle
Definition: dsm_impl.h:55
PGPROC * MyProc
Definition: proc.c:67
dsm_segment * seg
Definition: parallel.h:42
void SerializeReindexState(Size maxsize, char *start_address)
Definition: index.c:3979
shm_toc_estimator estimator
Definition: parallel.h:41
#define SpinLockInit(lock)
Definition: spin.h:60
void GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
Definition: namespace.c:3234
Oid authenticated_user_id
Definition: parallel.c:78
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
PGPROC * parallel_master_pgproc
Definition: parallel.c:85
Oid temp_toast_namespace_id
Definition: parallel.c:82
Size shm_toc_estimate(shm_toc_estimator *e)
Definition: shm_toc.c:263
void SerializeTransactionState(Size maxsize, char *start_address)
Definition: xact.c:4997
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
Oid GetCurrentRoleId(void)
Definition: miscinit.c:636
#define DSM_HANDLE_INVALID
Definition: dsm.h:23
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:764
ParallelWorkerInfo * worker
Definition: parallel.h:45
void SerializeLibraryState(Size maxsize, char *start_address)
Definition: dfmgr.c:728
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:343
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:66
char * function_name
Definition: parallel.h:39
void SerializeSnapshot(Snapshot snapshot, char *start_address)
Definition: snapmgr.c:2068
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:170
#define PARALLEL_KEY_FIXED
Definition: parallel.c:61
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:62
#define DSM_CREATE_NULL_IF_MAXSEGMENTS
Definition: dsm.h:20
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
shm_mq_handle * error_mqh
Definition: parallel.h:28
#define PARALLEL_KEY_GUC
Definition: parallel.c:64
Size EstimateGUCStateSpace(void)
Definition: guc.c:9135
Size EstimateComboCIDStateSpace(void)
Definition: combocid.c:299
XLogRecPtr last_xlog_end
Definition: parallel.c:93
Size EstimateReindexStateSpace(void)
Definition: index.c:3968
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Size EstimateSnapshotSpace(Snapshot snap)
Definition: snapmgr.c:2044
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
void * palloc0(Size size)
Definition: mcxt.c:864
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:452
Oid MyDatabaseId
Definition: globals.c:77
pid_t parallel_master_pid
Definition: parallel.c:86
Size EstimateLibraryStateSpace(void)
Definition: dfmgr.c:711
#define PARALLEL_MAGIC
Definition: parallel.c:54
char * library_name
Definition: parallel.h:38
BackendId parallel_master_backend_id
Definition: parallel.c:87
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:987
Size EstimateTransactionStateSpace(void)
Definition: xact.c:4964
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:71
size_t Size
Definition: c.h:414
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
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:287
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:68
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:693
int i
Definition: shm_mq.c:69
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:70
#define BUFFERALIGN(LEN)
Definition: c.h:635
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:199
dsm_handle GetSessionDsmHandle(void)
Definition: session.c:70
bool session_auth_is_superuser
Definition: guc.c:449
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:69
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:65
void SerializeGUCState(Size maxsize, char *start_address)
Definition: guc.c:9282
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:67
void SerializeComboCIDState(Size maxsize, char *start_address)
Definition: combocid.c:318
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:63
shm_toc * toc
Definition: parallel.h:44
void * private_memory
Definition: parallel.h:43

◆ LaunchParallelWorkers()

void LaunchParallelWorkers ( ParallelContext pcxt)

Definition at line 462 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, MemoryContextSwitchTo(), MyProcPid, ParallelContext::nworkers, ParallelContext::nworkers_launched, RegisterDynamicBackgroundWorker(), ParallelContext::seg, shm_mq_detach(), shm_mq_set_handle(), snprintf(), TopTransactionContext, UInt32GetDatum, and ParallelContext::worker.

Referenced by ExecGather(), and ExecGatherMerge().

463 {
464  MemoryContext oldcontext;
465  BackgroundWorker worker;
466  int i;
467  bool any_registrations_failed = false;
468 
469  /* Skip this if we have no workers. */
470  if (pcxt->nworkers == 0)
471  return;
472 
473  /* We need to be a lock group leader. */
475 
476  /* If we do have workers, we'd better have a DSM segment. */
477  Assert(pcxt->seg != NULL);
478 
479  /* We might be running in a short-lived memory context. */
481 
482  /* Configure a worker. */
483  memset(&worker, 0, sizeof(worker));
484  snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
485  MyProcPid);
486  snprintf(worker.bgw_type, BGW_MAXLEN, "parallel worker");
487  worker.bgw_flags =
492  sprintf(worker.bgw_library_name, "postgres");
493  sprintf(worker.bgw_function_name, "ParallelWorkerMain");
495  worker.bgw_notify_pid = MyProcPid;
496 
497  /*
498  * Start workers.
499  *
500  * The caller must be able to tolerate ending up with fewer workers than
501  * expected, so there is no need to throw an error here if registration
502  * fails. It wouldn't help much anyway, because registering the worker in
503  * no way guarantees that it will start up and initialize successfully.
504  */
505  for (i = 0; i < pcxt->nworkers; ++i)
506  {
507  memcpy(worker.bgw_extra, &i, sizeof(int));
508  if (!any_registrations_failed &&
510  &pcxt->worker[i].bgwhandle))
511  {
513  pcxt->worker[i].bgwhandle);
514  pcxt->nworkers_launched++;
515  }
516  else
517  {
518  /*
519  * If we weren't able to register the worker, then we've bumped up
520  * against the max_worker_processes limit, and future
521  * registrations will probably fail too, so arrange to skip them.
522  * But we still have to execute this code for the remaining slots
523  * to make sure that we forget about the error queues we budgeted
524  * for those workers. Otherwise, we'll wait for them to start,
525  * but they never will.
526  */
527  any_registrations_failed = true;
528  pcxt->worker[i].bgwhandle = NULL;
529  shm_mq_detach(pcxt->worker[i].error_mqh);
530  pcxt->worker[i].error_mqh = NULL;
531  }
532  }
533 
534  /* Restore previous memory context. */
535  MemoryContextSwitchTo(oldcontext);
536 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
int MyProcPid
Definition: globals.c:39
MemoryContext TopTransactionContext
Definition: mcxt.c:48
void shm_mq_detach(shm_mq_handle *mqh)
Definition: shm_mq.c:775
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:1015
int bgw_restart_time
Definition: bgworker.h:94
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
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:499
int nworkers_launched
Definition: parallel.h:37
void BecomeLockGroupLeader(void)
Definition: proc.c:1824
void shm_mq_set_handle(shm_mq_handle *mqh, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:315
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:680
#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:939
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

◆ LookupParallelWorkerFunction()

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

Definition at line 1219 of file parallel.c.

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

Referenced by ParallelWorkerMain().

1220 {
1221  /*
1222  * If the function is to be loaded from postgres itself, search the
1223  * InternalParallelWorkers array.
1224  */
1225  if (strcmp(libraryname, "postgres") == 0)
1226  {
1227  int i;
1228 
1229  for (i = 0; i < lengthof(InternalParallelWorkers); i++)
1230  {
1231  if (strcmp(InternalParallelWorkers[i].fn_name, funcname) == 0)
1232  return InternalParallelWorkers[i].fn_addr;
1233  }
1234 
1235  /* We can only reach this by programming error. */
1236  elog(ERROR, "internal function \"%s\" not found", funcname);
1237  }
1238 
1239  /* Otherwise load from external library. */
1240  return (parallel_worker_main_type)
1241  load_external_function(libraryname, funcname, true, NULL);
1242 }
static const struct @21 InternalParallelWorkers[]
#define lengthof(array)
Definition: c.h:610
parallel_worker_main_type fn_addr
Definition: parallel.c:123
#define ERROR
Definition: elog.h:43
PGFunction load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:94
const char * fn_name
Definition: parallel.c:122
void(* parallel_worker_main_type)(dsm_segment *seg, shm_toc *toc)
Definition: parallel.h:23
int i
#define elog
Definition: elog.h:219

◆ ParallelContextActive()

bool ParallelContextActive ( void  )

Definition at line 714 of file parallel.c.

References dlist_is_empty().

Referenced by ExitParallelMode().

715 {
716  return !dlist_is_empty(&pcxt_list);
717 }
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static dlist_head pcxt_list
Definition: parallel.c:114

◆ ParallelWorkerMain()

void ParallelWorkerMain ( Datum  main_arg)

Definition at line 968 of file parallel.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, AttachSession(), FixedParallelState::authenticated_user_id, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), BecomeLockGroupMember(), BackgroundWorker::bgw_extra, CommitTransactionCommand(), FixedParallelState::current_user_id, CurrentMemoryContext, CurrentResourceOwner, 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, FixedParallelState::outer_user_id, PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ACTIVE_SNAPSHOT, PARALLEL_KEY_COMBO_CID, PARALLEL_KEY_ENTRYPOINT, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, PARALLEL_KEY_GUC, PARALLEL_KEY_LIBRARY, PARALLEL_KEY_REINDEX_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, ParallelWorkerNumber, PopActiveSnapshot(), pq_beginmessage(), pq_endmessage(), pq_putmessage, pq_redirect_to_shm_mq(), pq_sendint32(), pq_set_parallel_master(), pqsignal(), PushActiveSnapshot(), ResourceOwnerCreate(), RestoreComboCIDState(), RestoreGUCState(), RestoreLibraryState(), RestoreReindexState(), RestoreSnapshot(), RestoreTransactionSnapshot(), FixedParallelState::sec_context, SetClientEncoding(), SetCurrentRoleId(), SetTempNamespaceState(), SetUserIdAndSecContext(), shm_mq_attach(), shm_mq_set_sender(), shm_toc_attach(), shm_toc_lookup(), StartParallelWorkerTransaction(), StartTransactionCommand(), FixedParallelState::temp_namespace_id, FixedParallelState::temp_toast_namespace_id, and TopMemoryContext.

969 {
970  dsm_segment *seg;
971  shm_toc *toc;
972  FixedParallelState *fps;
973  char *error_queue_space;
974  shm_mq *mq;
975  shm_mq_handle *mqh;
976  char *libraryspace;
977  char *entrypointstate;
978  char *library_name;
979  char *function_name;
981  char *gucspace;
982  char *combocidspace;
983  char *tsnapspace;
984  char *asnapspace;
985  char *tstatespace;
986  char *reindexspace;
987  StringInfoData msgbuf;
988  char *session_dsm_handle_space;
989 
990  /* Set flag to indicate that we're initializing a parallel worker. */
992 
993  /* Establish signal handlers. */
994  pqsignal(SIGTERM, die);
996 
997  /* Determine and set our parallel worker number. */
999  memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
1000 
1001  /* Set up a memory context and resource owner. */
1002  Assert(CurrentResourceOwner == NULL);
1003  CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
1005  "Parallel worker",
1007 
1008  /*
1009  * Now that we have a resource owner, we can attach to the dynamic shared
1010  * memory segment and read the table of contents.
1011  */
1012  seg = dsm_attach(DatumGetUInt32(main_arg));
1013  if (seg == NULL)
1014  ereport(ERROR,
1015  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1016  errmsg("could not map dynamic shared memory segment")));
1018  if (toc == NULL)
1019  ereport(ERROR,
1020  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1021  errmsg("invalid magic number in dynamic shared memory segment")));
1022 
1023  /* Look up fixed parallel state. */
1024  fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED, false);
1025  MyFixedParallelState = fps;
1026 
1027  /*
1028  * Now that we have a worker number, we can find and attach to the error
1029  * queue provided for us. That's good, because until we do that, any
1030  * errors that happen here will not be reported back to the process that
1031  * requested that this worker be launched.
1032  */
1033  error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE, false);
1034  mq = (shm_mq *) (error_queue_space +
1037  mqh = shm_mq_attach(mq, seg, NULL);
1038  pq_redirect_to_shm_mq(seg, mqh);
1041 
1042  /*
1043  * Send a BackendKeyData message to the process that initiated parallelism
1044  * so that it has access to our PID before it receives any other messages
1045  * from us. Our cancel key is sent, too, since that's the way the
1046  * protocol message is defined, but it won't actually be used for anything
1047  * in this case.
1048  */
1049  pq_beginmessage(&msgbuf, 'K');
1050  pq_sendint32(&msgbuf, (int32) MyProcPid);
1051  pq_sendint32(&msgbuf, (int32) MyCancelKey);
1052  pq_endmessage(&msgbuf);
1053 
1054  /*
1055  * Hooray! Primary initialization is complete. Now, we need to set up our
1056  * backend-local state to match the original backend.
1057  */
1058 
1059  /*
1060  * Join locking group. We must do this before anything that could try to
1061  * acquire a heavyweight lock, because any heavyweight locks acquired to
1062  * this point could block either directly against the parallel group
1063  * leader or against some process which in turn waits for a lock that
1064  * conflicts with the parallel group leader, causing an undetected
1065  * deadlock. (If we can't join the lock group, the leader has gone away,
1066  * so just exit quietly.)
1067  */
1069  fps->parallel_master_pid))
1070  return;
1071 
1072  /*
1073  * Load libraries that were loaded by original backend. We want to do
1074  * this before restoring GUCs, because the libraries might define custom
1075  * variables.
1076  */
1077  libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY, false);
1078  RestoreLibraryState(libraryspace);
1079 
1080  /*
1081  * Identify the entry point to be called. In theory this could result in
1082  * loading an additional library, though most likely the entry point is in
1083  * the core backend or in a library we just loaded.
1084  */
1085  entrypointstate = shm_toc_lookup(toc, PARALLEL_KEY_ENTRYPOINT, false);
1086  library_name = entrypointstate;
1087  function_name = entrypointstate + strlen(library_name) + 1;
1088 
1089  entrypt = LookupParallelWorkerFunction(library_name, function_name);
1090 
1091  /* Restore database connection. */
1093  fps->authenticated_user_id);
1094 
1095  /*
1096  * Set the client encoding to the database encoding, since that is what
1097  * the leader will expect.
1098  */
1100 
1101  /* Restore GUC values from launching backend. */
1102  gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC, false);
1104  RestoreGUCState(gucspace);
1106 
1107  /* Crank up a transaction state appropriate to a parallel worker. */
1108  tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE, false);
1109  StartParallelWorkerTransaction(tstatespace);
1110 
1111  /* Restore combo CID state. */
1112  combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID, false);
1113  RestoreComboCIDState(combocidspace);
1114 
1115  /* Attach to the per-session DSM segment and contained objects. */
1116  session_dsm_handle_space =
1118  AttachSession(*(dsm_handle *) session_dsm_handle_space);
1119 
1120  /* Restore transaction snapshot. */
1121  tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT, false);
1123  fps->parallel_master_pgproc);
1124 
1125  /* Restore active snapshot. */
1126  asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, false);
1127  PushActiveSnapshot(RestoreSnapshot(asnapspace));
1128 
1129  /*
1130  * We've changed which tuples we can see, and must therefore invalidate
1131  * system caches.
1132  */
1134 
1135  /*
1136  * Restore current role id. Skip verifying whether session user is
1137  * allowed to become this role and blindly restore the leader's state for
1138  * current role.
1139  */
1141 
1142  /* Restore user ID and security context. */
1144 
1145  /* Restore temp-namespace state to ensure search path matches leader's. */
1148 
1149  /* Set ParallelMasterBackendId so we know how to address temp relations. */
1151 
1152  /* Restore reindex state. */
1153  reindexspace = shm_toc_lookup(toc, PARALLEL_KEY_REINDEX_STATE, false);
1154  RestoreReindexState(reindexspace);
1155 
1156  /*
1157  * We've initialized all of our state now; nothing should change
1158  * hereafter.
1159  */
1162 
1163  /*
1164  * Time to do the real work: invoke the caller-supplied code.
1165  */
1166  entrypt(seg, toc);
1167 
1168  /* Must exit parallel mode to pop active snapshot. */
1169  ExitParallelMode();
1170 
1171  /* Must pop active snapshot so resowner.c doesn't complain. */
1173 
1174  /* Shut down the parallel-worker transaction. */
1176 
1177  /* Detach from the per-session DSM segment. */
1178  DetachSession();
1179 
1180  /* Report success. */
1181  pq_putmessage('X', NULL, 0);
1182 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
#define DatumGetUInt32(X)
Definition: postgres.h:492
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:51
int MyProcPid
Definition: globals.c:39
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:2127
uint32 dsm_handle
Definition: dsm_impl.h:55
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
PGPROC * MyProc
Definition: proc.c:67
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void CommitTransactionCommand(void)
Definition: xact.c:2745
void EndParallelWorkerTransaction(void)
Definition: xact.c:5088
void RestoreTransactionSnapshot(Snapshot snapshot, void *master_pgproc)
Definition: snapmgr.c:2191
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:548
Oid authenticated_user_id
Definition: parallel.c:78
int errcode(int sqlerrcode)
Definition: elog.c:575
PGPROC * parallel_master_pgproc
Definition: parallel.c:85
Oid temp_toast_namespace_id
Definition: parallel.c:82
void DetachSession(void)
Definition: session.c:201
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:1854
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
void InvalidateSystemCaches(void)
Definition: inval.c:641
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:294
#define ERROR
Definition: elog.h:43
#define PARALLEL_KEY_TRANSACTION_SNAPSHOT
Definition: parallel.c:66
int32 MyCancelKey
Definition: globals.c:42
void ExitParallelMode(void)
Definition: xact.c:886
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define PARALLEL_KEY_FIXED
Definition: parallel.c:61
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:62
void SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
Definition: namespace.c:3250
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
#define PARALLEL_KEY_GUC
Definition: parallel.c:64
int SetClientEncoding(int encoding)
Definition: mbutils.c:201
int ParallelWorkerNumber
Definition: parallel.c:102
void AttachSession(dsm_handle handle)
Definition: session.c:155
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
Definition: postmaster.c:5611
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:218
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname)
Definition: parallel.c:1219
void RestoreLibraryState(char *start_address)
Definition: dfmgr.c:750
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition: shm_toc.c:64
int GetDatabaseEncoding(void)
Definition: mbutils.c:1004
pid_t parallel_master_pid
Definition: parallel.c:86
#define PARALLEL_MAGIC
Definition: parallel.c:54
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:168
BackendId parallel_master_backend_id
Definition: parallel.c:87
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:987
#define Assert(condition)
Definition: c.h:680
BackendId ParallelMasterBackendId
Definition: globals.c:75
void StartParallelWorkerTransaction(char *tstatespace)
Definition: xact.c:5065
void StartTransactionCommand(void)
Definition: xact.c:2674
#define PARALLEL_KEY_REINDEX_STATE
Definition: parallel.c:71
void EnterParallelMode(void)
Definition: xact.c:873
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:287
void pq_set_parallel_master(pid_t pid, BackendId backend_id)
Definition: pqmq.c:80
#define PARALLEL_KEY_TRANSACTION_STATE
Definition: parallel.c:68
void RestoreReindexState(void *reindexstate)
Definition: index.c:3997
int errmsg(const char *fmt,...)
Definition: elog.c:797
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:111
void die(SIGNAL_ARGS)
Definition: postgres.c:2656
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:657
bool InitializingParallelWorker
Definition: parallel.c:108
Definition: shm_mq.c:69
#define PARALLEL_KEY_SESSION_DSM
Definition: parallel.c:70
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:42
#define PARALLEL_KEY_ENTRYPOINT
Definition: parallel.c:69
#define PARALLEL_KEY_COMBO_CID
Definition: parallel.c:65
#define PARALLEL_KEY_ACTIVE_SNAPSHOT
Definition: parallel.c:67
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
#define PARALLEL_KEY_LIBRARY
Definition: parallel.c:63
void RestoreGUCState(void *gucstate)
Definition: guc.c:9347
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5640

◆ ParallelWorkerReportLastRecEnd()

void ParallelWorkerReportLastRecEnd ( XLogRecPtr  last_xlog_end)

Definition at line 1189 of file parallel.c.

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

Referenced by CommitTransaction().

1190 {
1192 
1193  Assert(fps != NULL);
1194  SpinLockAcquire(&fps->mutex);
1195  if (fps->last_xlog_end < last_xlog_end)
1196  fps->last_xlog_end = last_xlog_end;
1197  SpinLockRelease(&fps->mutex);
1198 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr last_xlog_end
Definition: parallel.c:93
#define SpinLockRelease(lock)
Definition: spin.h:64
#define Assert(condition)
Definition: c.h:680
static FixedParallelState * MyFixedParallelState
Definition: parallel.c:111

◆ ReinitializeParallelDSM()

void ReinitializeParallelDSM ( ParallelContext pcxt)

Definition at line 424 of file parallel.c.

References Assert, ParallelWorkerInfo::error_mqh, i, FixedParallelState::last_xlog_end, MyProc, ParallelContext::nworkers, ParallelContext::nworkers_launched, PARALLEL_ERROR_QUEUE_SIZE, PARALLEL_KEY_ERROR_QUEUE, PARALLEL_KEY_FIXED, 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().

425 {
426  FixedParallelState *fps;
427  char *error_queue_space;
428  int i;
429 
430  /* Wait for any old workers to exit. */
431  if (pcxt->nworkers_launched > 0)
432  {
435  pcxt->nworkers_launched = 0;
436  }
437 
438  /* Reset a few bits of fixed parallel state to a clean state. */
439  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
440  fps->last_xlog_end = 0;
441 
442  /* Recreate error queues (if they exist). */
443  error_queue_space =
445  Assert(pcxt->nworkers == 0 || error_queue_space != NULL);
446  for (i = 0; i < pcxt->nworkers; ++i)
447  {
448  char *start;
449  shm_mq *mq;
450 
451  start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
452  mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
454  pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
455  }
456 }
#define PARALLEL_ERROR_QUEUE_SIZE
Definition: parallel.c:51
PGPROC * MyProc
Definition: proc.c:67
dsm_segment * seg
Definition: parallel.h:42
static void WaitForParallelWorkersToExit(ParallelContext *pcxt)
Definition: parallel.c:600
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:550
ParallelWorkerInfo * worker
Definition: parallel.h:45
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:170
#define PARALLEL_KEY_FIXED
Definition: parallel.c:61
#define PARALLEL_KEY_ERROR_QUEUE
Definition: parallel.c:62
shm_mq_handle * error_mqh
Definition: parallel.h:28
int nworkers_launched
Definition: parallel.h:37
XLogRecPtr last_xlog_end
Definition: parallel.c:93
#define Assert(condition)
Definition: c.h:680
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:287
int i
Definition: shm_mq.c:69
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:199
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
shm_toc * toc
Definition: parallel.h:44

◆ WaitForParallelWorkersToExit()

static void WaitForParallelWorkersToExit ( ParallelContext pcxt)
static

Definition at line 600 of file parallel.c.

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

601 {
602  int i;
603 
604  /* Wait until the workers actually die. */
605  for (i = 0; i < pcxt->nworkers_launched; ++i)
606  {
608 
609  if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
610  continue;
611 
613 
614  /*
615  * If the postmaster kicked the bucket, we have no chance of cleaning
616  * up safely -- we won't be able to tell when our workers are actually
617  * dead. This doesn't necessitate a PANIC since they will all abort
618  * eventually, but we can't safely continue this session.
619  */
620  if (status == BGWH_POSTMASTER_DIED)
621  ereport(FATAL,
622  (errcode(ERRCODE_ADMIN_SHUTDOWN),
623  errmsg("postmaster exited during a parallel transaction")));
624 
625  /* Release memory. */
626  pfree(pcxt->worker[i].bgwhandle);
627  pcxt->worker[i].bgwhandle = NULL;
628  }
629 }
int errcode(int sqlerrcode)
Definition: elog.c:575
ParallelWorkerInfo * worker
Definition: parallel.h:45
void pfree(void *pointer)
Definition: mcxt.c:936
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1145
#define FATAL
Definition: elog.h:52
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:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

◆ WaitForParallelWorkersToFinish()

void WaitForParallelWorkersToFinish ( ParallelContext pcxt)

Definition at line 550 of file parallel.c.

References CHECK_FOR_INTERRUPTS, ParallelWorkerInfo::error_mqh, i, FixedParallelState::last_xlog_end, MyLatch, ParallelContext::nworkers_launched, PARALLEL_KEY_FIXED, ResetLatch(), shm_toc_lookup(), ParallelContext::toc, WAIT_EVENT_PARALLEL_FINISH, WaitLatch(), WL_LATCH_SET, ParallelContext::worker, and XactLastRecEnd.

Referenced by ExecParallelFinish(), and ReinitializeParallelDSM().

551 {
552  for (;;)
553  {
554  bool anyone_alive = false;
555  int i;
556 
557  /*
558  * This will process any parallel messages that are pending, which may
559  * change the outcome of the loop that follows. It may also throw an
560  * error propagated from a worker.
561  */
563 
564  for (i = 0; i < pcxt->nworkers_launched; ++i)
565  {
566  if (pcxt->worker[i].error_mqh != NULL)
567  {
568  anyone_alive = true;
569  break;
570  }
571  }
572 
573  if (!anyone_alive)
574  break;
575 
579  }
580 
581  if (pcxt->toc != NULL)
582  {
583  FixedParallelState *fps;
584 
585  fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED, false);
586  if (fps->last_xlog_end > XactLastRecEnd)
588  }
589 }
XLogRecPtr XactLastRecEnd
Definition: xlog.c:339
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
ParallelWorkerInfo * worker
Definition: parallel.h:45
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
#define PARALLEL_KEY_FIXED
Definition: parallel.c:61
shm_mq_handle * error_mqh
Definition: parallel.h:28
int nworkers_launched
Definition: parallel.h:37
XLogRecPtr last_xlog_end
Definition: parallel.c:93
int i
struct Latch * MyLatch
Definition: globals.c:52
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define WL_LATCH_SET
Definition: latch.h:124
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
shm_toc * toc
Definition: parallel.h:44

Variable Documentation

◆ fn_addr

Definition at line 123 of file parallel.c.

Referenced by LookupParallelWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 122 of file parallel.c.

Referenced by LookupParallelWorkerFunction().

◆ InitializingParallelWorker

bool InitializingParallelWorker = false

◆ InternalParallelWorkers

const { ... } InternalParallelWorkers[]
Initial value:
=
{
{
"ParallelQueryMain", ParallelQueryMain
}
}
void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)

Referenced by LookupParallelWorkerFunction().

◆ MyFixedParallelState

FixedParallelState* MyFixedParallelState
static

Definition at line 111 of file parallel.c.

Referenced by ParallelWorkerReportLastRecEnd().

◆ ParallelMessagePending

volatile bool ParallelMessagePending = false

◆ ParallelWorkerNumber

◆ pcxt_list

dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list)
static

Definition at line 114 of file parallel.c.