LCOV - code coverage report
Current view: top level - src/backend/access/transam - parallel.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.2 % 482 435
Test Date: 2026-11-29 04:16:07 Functions: 94.7 % 19 18
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 63.7 % 193 123

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

Generated by: LCOV version 2.0-1