LCOV - code coverage report
Current view: top level - src/backend/storage/ipc - procarray.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 88.2 % 1327 1171
Test Date: 2026-03-24 02:15:55 Functions: 93.4 % 76 71
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * procarray.c
       4              :  *    POSTGRES process array code.
       5              :  *
       6              :  *
       7              :  * This module maintains arrays of PGPROC substructures, as well as associated
       8              :  * arrays in ProcGlobal, for all active backends.  Although there are several
       9              :  * uses for this, the principal one is as a means of determining the set of
      10              :  * currently running transactions.
      11              :  *
      12              :  * Because of various subtle race conditions it is critical that a backend
      13              :  * hold the correct locks while setting or clearing its xid (in
      14              :  * ProcGlobal->xids[]/MyProc->xid).  See notes in
      15              :  * src/backend/access/transam/README.
      16              :  *
      17              :  * The process arrays now also include structures representing prepared
      18              :  * transactions.  The xid and subxids fields of these are valid, as are the
      19              :  * myProcLocks lists.  They can be distinguished from regular backend PGPROCs
      20              :  * at need by checking for pid == 0.
      21              :  *
      22              :  * During hot standby, we also keep a list of XIDs representing transactions
      23              :  * that are known to be running on the primary (or more precisely, were running
      24              :  * as of the current point in the WAL stream).  This list is kept in the
      25              :  * KnownAssignedXids array, and is updated by watching the sequence of
      26              :  * arriving XIDs.  This is necessary because if we leave those XIDs out of
      27              :  * snapshots taken for standby queries, then they will appear to be already
      28              :  * complete, leading to MVCC failures.  Note that in hot standby, the PGPROC
      29              :  * array represents standby processes, which by definition are not running
      30              :  * transactions that have XIDs.
      31              :  *
      32              :  * It is perhaps possible for a backend on the primary to terminate without
      33              :  * writing an abort record for its transaction.  While that shouldn't really
      34              :  * happen, it would tie up KnownAssignedXids indefinitely, so we protect
      35              :  * ourselves by pruning the array when a valid list of running XIDs arrives.
      36              :  *
      37              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      38              :  * Portions Copyright (c) 1994, Regents of the University of California
      39              :  *
      40              :  *
      41              :  * IDENTIFICATION
      42              :  *    src/backend/storage/ipc/procarray.c
      43              :  *
      44              :  *-------------------------------------------------------------------------
      45              :  */
      46              : #include "postgres.h"
      47              : 
      48              : #include <signal.h>
      49              : 
      50              : #include "access/subtrans.h"
      51              : #include "access/transam.h"
      52              : #include "access/twophase.h"
      53              : #include "access/xact.h"
      54              : #include "access/xlogutils.h"
      55              : #include "catalog/catalog.h"
      56              : #include "catalog/pg_authid.h"
      57              : #include "miscadmin.h"
      58              : #include "pgstat.h"
      59              : #include "postmaster/bgworker.h"
      60              : #include "port/pg_lfind.h"
      61              : #include "storage/proc.h"
      62              : #include "storage/procarray.h"
      63              : #include "storage/procsignal.h"
      64              : #include "utils/acl.h"
      65              : #include "utils/builtins.h"
      66              : #include "utils/injection_point.h"
      67              : #include "utils/lsyscache.h"
      68              : #include "utils/rel.h"
      69              : #include "utils/snapmgr.h"
      70              : #include "utils/wait_event.h"
      71              : 
      72              : #define UINT32_ACCESS_ONCE(var)      ((uint32)(*((volatile uint32 *)&(var))))
      73              : 
      74              : /* Our shared memory area */
      75              : typedef struct ProcArrayStruct
      76              : {
      77              :     int         numProcs;       /* number of valid procs entries */
      78              :     int         maxProcs;       /* allocated size of procs array */
      79              : 
      80              :     /*
      81              :      * Known assigned XIDs handling
      82              :      */
      83              :     int         maxKnownAssignedXids;   /* allocated size of array */
      84              :     int         numKnownAssignedXids;   /* current # of valid entries */
      85              :     int         tailKnownAssignedXids;  /* index of oldest valid element */
      86              :     int         headKnownAssignedXids;  /* index of newest element, + 1 */
      87              : 
      88              :     /*
      89              :      * Highest subxid that has been removed from KnownAssignedXids array to
      90              :      * prevent overflow; or InvalidTransactionId if none.  We track this for
      91              :      * similar reasons to tracking overflowing cached subxids in PGPROC
      92              :      * entries.  Must hold exclusive ProcArrayLock to change this, and shared
      93              :      * lock to read it.
      94              :      */
      95              :     TransactionId lastOverflowedXid;
      96              : 
      97              :     /* oldest xmin of any replication slot */
      98              :     TransactionId replication_slot_xmin;
      99              :     /* oldest catalog xmin of any replication slot */
     100              :     TransactionId replication_slot_catalog_xmin;
     101              : 
     102              :     /* indexes into allProcs[], has PROCARRAY_MAXPROCS entries */
     103              :     int         pgprocnos[FLEXIBLE_ARRAY_MEMBER];
     104              : } ProcArrayStruct;
     105              : 
     106              : /*
     107              :  * State for the GlobalVisTest* family of functions. Those functions can
     108              :  * e.g. be used to decide if a deleted row can be removed without violating
     109              :  * MVCC semantics: If the deleted row's xmax is not considered to be running
     110              :  * by anyone, the row can be removed.
     111              :  *
     112              :  * To avoid slowing down GetSnapshotData(), we don't calculate a precise
     113              :  * cutoff XID while building a snapshot (looking at the frequently changing
     114              :  * xmins scales badly). Instead we compute two boundaries while building the
     115              :  * snapshot:
     116              :  *
     117              :  * 1) definitely_needed, indicating that rows deleted by XIDs >=
     118              :  *    definitely_needed are definitely still visible.
     119              :  *
     120              :  * 2) maybe_needed, indicating that rows deleted by XIDs < maybe_needed can
     121              :  *    definitely be removed
     122              :  *
     123              :  * When testing an XID that falls in between the two (i.e. XID >= maybe_needed
     124              :  * && XID < definitely_needed), the boundaries can be recomputed (using
     125              :  * ComputeXidHorizons()) to get a more accurate answer. This is cheaper than
     126              :  * maintaining an accurate value all the time.
     127              :  *
     128              :  * As it is not cheap to compute accurate boundaries, we limit the number of
     129              :  * times that happens in short succession. See GlobalVisTestShouldUpdate().
     130              :  *
     131              :  *
     132              :  * There are three backend lifetime instances of this struct, optimized for
     133              :  * different types of relations. As e.g. a normal user defined table in one
     134              :  * database is inaccessible to backends connected to another database, a test
     135              :  * specific to a relation can be more aggressive than a test for a shared
     136              :  * relation.  Currently we track four different states:
     137              :  *
     138              :  * 1) GlobalVisSharedRels, which only considers an XID's
     139              :  *    effects visible-to-everyone if neither snapshots in any database, nor a
     140              :  *    replication slot's xmin, nor a replication slot's catalog_xmin might
     141              :  *    still consider XID as running.
     142              :  *
     143              :  * 2) GlobalVisCatalogRels, which only considers an XID's
     144              :  *    effects visible-to-everyone if neither snapshots in the current
     145              :  *    database, nor a replication slot's xmin, nor a replication slot's
     146              :  *    catalog_xmin might still consider XID as running.
     147              :  *
     148              :  *    I.e. the difference to GlobalVisSharedRels is that
     149              :  *    snapshot in other databases are ignored.
     150              :  *
     151              :  * 3) GlobalVisDataRels, which only considers an XID's
     152              :  *    effects visible-to-everyone if neither snapshots in the current
     153              :  *    database, nor a replication slot's xmin consider XID as running.
     154              :  *
     155              :  *    I.e. the difference to GlobalVisCatalogRels is that
     156              :  *    replication slot's catalog_xmin is not taken into account.
     157              :  *
     158              :  * 4) GlobalVisTempRels, which only considers the current session, as temp
     159              :  *    tables are not visible to other sessions.
     160              :  *
     161              :  * GlobalVisTestFor(relation) returns the appropriate state
     162              :  * for the relation.
     163              :  *
     164              :  * The boundaries are FullTransactionIds instead of TransactionIds to avoid
     165              :  * wraparound dangers. There e.g. would otherwise exist no procarray state to
     166              :  * prevent maybe_needed to become old enough after the GetSnapshotData()
     167              :  * call.
     168              :  *
     169              :  * The typedef is in the header.
     170              :  */
     171              : struct GlobalVisState
     172              : {
     173              :     /* XIDs >= are considered running by some backend */
     174              :     FullTransactionId definitely_needed;
     175              : 
     176              :     /* XIDs < are not considered to be running by any backend */
     177              :     FullTransactionId maybe_needed;
     178              : };
     179              : 
     180              : /*
     181              :  * Result of ComputeXidHorizons().
     182              :  */
     183              : typedef struct ComputeXidHorizonsResult
     184              : {
     185              :     /*
     186              :      * The value of TransamVariables->latestCompletedXid when
     187              :      * ComputeXidHorizons() held ProcArrayLock.
     188              :      */
     189              :     FullTransactionId latest_completed;
     190              : 
     191              :     /*
     192              :      * The same for procArray->replication_slot_xmin and
     193              :      * procArray->replication_slot_catalog_xmin.
     194              :      */
     195              :     TransactionId slot_xmin;
     196              :     TransactionId slot_catalog_xmin;
     197              : 
     198              :     /*
     199              :      * Oldest xid that any backend might still consider running. This needs to
     200              :      * include processes running VACUUM, in contrast to the normal visibility
     201              :      * cutoffs, as vacuum needs to be able to perform pg_subtrans lookups when
     202              :      * determining visibility, but doesn't care about rows above its xmin to
     203              :      * be removed.
     204              :      *
     205              :      * This likely should only be needed to determine whether pg_subtrans can
     206              :      * be truncated. It currently includes the effects of replication slots,
     207              :      * for historical reasons. But that could likely be changed.
     208              :      */
     209              :     TransactionId oldest_considered_running;
     210              : 
     211              :     /*
     212              :      * Oldest xid for which deleted tuples need to be retained in shared
     213              :      * tables.
     214              :      *
     215              :      * This includes the effects of replication slots. If that's not desired,
     216              :      * look at shared_oldest_nonremovable_raw;
     217              :      */
     218              :     TransactionId shared_oldest_nonremovable;
     219              : 
     220              :     /*
     221              :      * Oldest xid that may be necessary to retain in shared tables. This is
     222              :      * the same as shared_oldest_nonremovable, except that is not affected by
     223              :      * replication slot's catalog_xmin.
     224              :      *
     225              :      * This is mainly useful to be able to send the catalog_xmin to upstream
     226              :      * streaming replication servers via hot_standby_feedback, so they can
     227              :      * apply the limit only when accessing catalog tables.
     228              :      */
     229              :     TransactionId shared_oldest_nonremovable_raw;
     230              : 
     231              :     /*
     232              :      * Oldest xid for which deleted tuples need to be retained in non-shared
     233              :      * catalog tables.
     234              :      */
     235              :     TransactionId catalog_oldest_nonremovable;
     236              : 
     237              :     /*
     238              :      * Oldest xid for which deleted tuples need to be retained in normal user
     239              :      * defined tables.
     240              :      */
     241              :     TransactionId data_oldest_nonremovable;
     242              : 
     243              :     /*
     244              :      * Oldest xid for which deleted tuples need to be retained in this
     245              :      * session's temporary tables.
     246              :      */
     247              :     TransactionId temp_oldest_nonremovable;
     248              : } ComputeXidHorizonsResult;
     249              : 
     250              : /*
     251              :  * Return value for GlobalVisHorizonKindForRel().
     252              :  */
     253              : typedef enum GlobalVisHorizonKind
     254              : {
     255              :     VISHORIZON_SHARED,
     256              :     VISHORIZON_CATALOG,
     257              :     VISHORIZON_DATA,
     258              :     VISHORIZON_TEMP,
     259              : } GlobalVisHorizonKind;
     260              : 
     261              : /*
     262              :  * Reason codes for KnownAssignedXidsCompress().
     263              :  */
     264              : typedef enum KAXCompressReason
     265              : {
     266              :     KAX_NO_SPACE,               /* need to free up space at array end */
     267              :     KAX_PRUNE,                  /* we just pruned old entries */
     268              :     KAX_TRANSACTION_END,        /* we just committed/removed some XIDs */
     269              :     KAX_STARTUP_PROCESS_IDLE,   /* startup process is about to sleep */
     270              : } KAXCompressReason;
     271              : 
     272              : 
     273              : static ProcArrayStruct *procArray;
     274              : 
     275              : static PGPROC *allProcs;
     276              : 
     277              : /*
     278              :  * Cache to reduce overhead of repeated calls to TransactionIdIsInProgress()
     279              :  */
     280              : static TransactionId cachedXidIsNotInProgress = InvalidTransactionId;
     281              : 
     282              : /*
     283              :  * Bookkeeping for tracking emulated transactions in recovery
     284              :  */
     285              : static TransactionId *KnownAssignedXids;
     286              : static bool *KnownAssignedXidsValid;
     287              : static TransactionId latestObservedXid = InvalidTransactionId;
     288              : 
     289              : /*
     290              :  * If we're in STANDBY_SNAPSHOT_PENDING state, standbySnapshotPendingXmin is
     291              :  * the highest xid that might still be running that we don't have in
     292              :  * KnownAssignedXids.
     293              :  */
     294              : static TransactionId standbySnapshotPendingXmin;
     295              : 
     296              : /*
     297              :  * State for visibility checks on different types of relations. See struct
     298              :  * GlobalVisState for details. As shared, catalog, normal and temporary
     299              :  * relations can have different horizons, one such state exists for each.
     300              :  */
     301              : static GlobalVisState GlobalVisSharedRels;
     302              : static GlobalVisState GlobalVisCatalogRels;
     303              : static GlobalVisState GlobalVisDataRels;
     304              : static GlobalVisState GlobalVisTempRels;
     305              : 
     306              : /*
     307              :  * This backend's RecentXmin at the last time the accurate xmin horizon was
     308              :  * recomputed, or InvalidTransactionId if it has not. Used to limit how many
     309              :  * times accurate horizons are recomputed. See GlobalVisTestShouldUpdate().
     310              :  */
     311              : static TransactionId ComputeXidHorizonsResultLastXmin;
     312              : 
     313              : #ifdef XIDCACHE_DEBUG
     314              : 
     315              : /* counters for XidCache measurement */
     316              : static long xc_by_recent_xmin = 0;
     317              : static long xc_by_known_xact = 0;
     318              : static long xc_by_my_xact = 0;
     319              : static long xc_by_latest_xid = 0;
     320              : static long xc_by_main_xid = 0;
     321              : static long xc_by_child_xid = 0;
     322              : static long xc_by_known_assigned = 0;
     323              : static long xc_no_overflow = 0;
     324              : static long xc_slow_answer = 0;
     325              : 
     326              : #define xc_by_recent_xmin_inc()     (xc_by_recent_xmin++)
     327              : #define xc_by_known_xact_inc()      (xc_by_known_xact++)
     328              : #define xc_by_my_xact_inc()         (xc_by_my_xact++)
     329              : #define xc_by_latest_xid_inc()      (xc_by_latest_xid++)
     330              : #define xc_by_main_xid_inc()        (xc_by_main_xid++)
     331              : #define xc_by_child_xid_inc()       (xc_by_child_xid++)
     332              : #define xc_by_known_assigned_inc()  (xc_by_known_assigned++)
     333              : #define xc_no_overflow_inc()        (xc_no_overflow++)
     334              : #define xc_slow_answer_inc()        (xc_slow_answer++)
     335              : 
     336              : static void DisplayXidCache(void);
     337              : #else                           /* !XIDCACHE_DEBUG */
     338              : 
     339              : #define xc_by_recent_xmin_inc()     ((void) 0)
     340              : #define xc_by_known_xact_inc()      ((void) 0)
     341              : #define xc_by_my_xact_inc()         ((void) 0)
     342              : #define xc_by_latest_xid_inc()      ((void) 0)
     343              : #define xc_by_main_xid_inc()        ((void) 0)
     344              : #define xc_by_child_xid_inc()       ((void) 0)
     345              : #define xc_by_known_assigned_inc()  ((void) 0)
     346              : #define xc_no_overflow_inc()        ((void) 0)
     347              : #define xc_slow_answer_inc()        ((void) 0)
     348              : #endif                          /* XIDCACHE_DEBUG */
     349              : 
     350              : /* Primitives for KnownAssignedXids array handling for standby */
     351              : static void KnownAssignedXidsCompress(KAXCompressReason reason, bool haveLock);
     352              : static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid,
     353              :                                  bool exclusive_lock);
     354              : static bool KnownAssignedXidsSearch(TransactionId xid, bool remove);
     355              : static bool KnownAssignedXidExists(TransactionId xid);
     356              : static void KnownAssignedXidsRemove(TransactionId xid);
     357              : static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids,
     358              :                                         TransactionId *subxids);
     359              : static void KnownAssignedXidsRemovePreceding(TransactionId removeXid);
     360              : static int  KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax);
     361              : static int  KnownAssignedXidsGetAndSetXmin(TransactionId *xarray,
     362              :                                            TransactionId *xmin,
     363              :                                            TransactionId xmax);
     364              : static TransactionId KnownAssignedXidsGetOldestXmin(void);
     365              : static void KnownAssignedXidsDisplay(int trace_level);
     366              : static void KnownAssignedXidsReset(void);
     367              : static inline void ProcArrayEndTransactionInternal(PGPROC *proc, TransactionId latestXid);
     368              : static void ProcArrayGroupClearXid(PGPROC *proc, TransactionId latestXid);
     369              : static void MaintainLatestCompletedXid(TransactionId latestXid);
     370              : static void MaintainLatestCompletedXidRecovery(TransactionId latestXid);
     371              : 
     372              : static inline FullTransactionId FullXidRelativeTo(FullTransactionId rel,
     373              :                                                   TransactionId xid);
     374              : static void GlobalVisUpdateApply(ComputeXidHorizonsResult *horizons);
     375              : 
     376              : /*
     377              :  * Report shared-memory space needed by ProcArrayShmemInit
     378              :  */
     379              : Size
     380         2207 : ProcArrayShmemSize(void)
     381              : {
     382              :     Size        size;
     383              : 
     384              :     /* Size of the ProcArray structure itself */
     385              : #define PROCARRAY_MAXPROCS  (MaxBackends + max_prepared_xacts)
     386              : 
     387         2207 :     size = offsetof(ProcArrayStruct, pgprocnos);
     388         2207 :     size = add_size(size, mul_size(sizeof(int), PROCARRAY_MAXPROCS));
     389              : 
     390              :     /*
     391              :      * During Hot Standby processing we have a data structure called
     392              :      * KnownAssignedXids, created in shared memory. Local data structures are
     393              :      * also created in various backends during GetSnapshotData(),
     394              :      * TransactionIdIsInProgress() and GetRunningTransactionData(). All of the
     395              :      * main structures created in those functions must be identically sized,
     396              :      * since we may at times copy the whole of the data structures around. We
     397              :      * refer to this size as TOTAL_MAX_CACHED_SUBXIDS.
     398              :      *
     399              :      * Ideally we'd only create this structure if we were actually doing hot
     400              :      * standby in the current run, but we don't know that yet at the time
     401              :      * shared memory is being set up.
     402              :      */
     403              : #define TOTAL_MAX_CACHED_SUBXIDS \
     404              :     ((PGPROC_MAX_CACHED_SUBXIDS + 1) * PROCARRAY_MAXPROCS)
     405              : 
     406         2207 :     if (EnableHotStandby)
     407              :     {
     408         2195 :         size = add_size(size,
     409              :                         mul_size(sizeof(TransactionId),
     410         2195 :                                  TOTAL_MAX_CACHED_SUBXIDS));
     411         2195 :         size = add_size(size,
     412         2195 :                         mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS));
     413              :     }
     414              : 
     415         2207 :     return size;
     416              : }
     417              : 
     418              : /*
     419              :  * Initialize the shared PGPROC array during postmaster startup.
     420              :  */
     421              : void
     422         1180 : ProcArrayShmemInit(void)
     423              : {
     424              :     bool        found;
     425              : 
     426              :     /* Create or attach to the ProcArray shared structure */
     427         1180 :     procArray = (ProcArrayStruct *)
     428         1180 :         ShmemInitStruct("Proc Array",
     429              :                         add_size(offsetof(ProcArrayStruct, pgprocnos),
     430              :                                  mul_size(sizeof(int),
     431         1180 :                                           PROCARRAY_MAXPROCS)),
     432              :                         &found);
     433              : 
     434         1180 :     if (!found)
     435              :     {
     436              :         /*
     437              :          * We're the first - initialize.
     438              :          */
     439         1180 :         procArray->numProcs = 0;
     440         1180 :         procArray->maxProcs = PROCARRAY_MAXPROCS;
     441         1180 :         procArray->maxKnownAssignedXids = TOTAL_MAX_CACHED_SUBXIDS;
     442         1180 :         procArray->numKnownAssignedXids = 0;
     443         1180 :         procArray->tailKnownAssignedXids = 0;
     444         1180 :         procArray->headKnownAssignedXids = 0;
     445         1180 :         procArray->lastOverflowedXid = InvalidTransactionId;
     446         1180 :         procArray->replication_slot_xmin = InvalidTransactionId;
     447         1180 :         procArray->replication_slot_catalog_xmin = InvalidTransactionId;
     448         1180 :         TransamVariables->xactCompletionCount = 1;
     449              :     }
     450              : 
     451         1180 :     allProcs = ProcGlobal->allProcs;
     452              : 
     453              :     /* Create or attach to the KnownAssignedXids arrays too, if needed */
     454         1180 :     if (EnableHotStandby)
     455              :     {
     456         1174 :         KnownAssignedXids = (TransactionId *)
     457         1174 :             ShmemInitStruct("KnownAssignedXids",
     458              :                             mul_size(sizeof(TransactionId),
     459         1174 :                                      TOTAL_MAX_CACHED_SUBXIDS),
     460              :                             &found);
     461         1174 :         KnownAssignedXidsValid = (bool *)
     462         1174 :             ShmemInitStruct("KnownAssignedXidsValid",
     463         1174 :                             mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS),
     464              :                             &found);
     465              :     }
     466         1180 : }
     467              : 
     468              : /*
     469              :  * Add the specified PGPROC to the shared array.
     470              :  */
     471              : void
     472        19788 : ProcArrayAdd(PGPROC *proc)
     473              : {
     474        19788 :     int         pgprocno = GetNumberFromPGProc(proc);
     475        19788 :     ProcArrayStruct *arrayP = procArray;
     476              :     int         index;
     477              :     int         movecount;
     478              : 
     479              :     /* See ProcGlobal comment explaining why both locks are held */
     480        19788 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     481        19788 :     LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
     482              : 
     483        19788 :     if (arrayP->numProcs >= arrayP->maxProcs)
     484              :     {
     485              :         /*
     486              :          * Oops, no room.  (This really shouldn't happen, since there is a
     487              :          * fixed supply of PGPROC structs too, and so we should have failed
     488              :          * earlier.)
     489              :          */
     490            0 :         ereport(FATAL,
     491              :                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     492              :                  errmsg("sorry, too many clients already")));
     493              :     }
     494              : 
     495              :     /*
     496              :      * Keep the procs array sorted by (PGPROC *) so that we can utilize
     497              :      * locality of references much better. This is useful while traversing the
     498              :      * ProcArray because there is an increased likelihood of finding the next
     499              :      * PGPROC structure in the cache.
     500              :      *
     501              :      * Since the occurrence of adding/removing a proc is much lower than the
     502              :      * access to the ProcArray itself, the overhead should be marginal
     503              :      */
     504        51115 :     for (index = 0; index < arrayP->numProcs; index++)
     505              :     {
     506        46023 :         int         this_procno = arrayP->pgprocnos[index];
     507              : 
     508              :         Assert(this_procno >= 0 && this_procno < (arrayP->maxProcs + NUM_AUXILIARY_PROCS));
     509              :         Assert(allProcs[this_procno].pgxactoff == index);
     510              : 
     511              :         /* If we have found our right position in the array, break */
     512        46023 :         if (this_procno > pgprocno)
     513        14696 :             break;
     514              :     }
     515              : 
     516        19788 :     movecount = arrayP->numProcs - index;
     517        19788 :     memmove(&arrayP->pgprocnos[index + 1],
     518        19788 :             &arrayP->pgprocnos[index],
     519              :             movecount * sizeof(*arrayP->pgprocnos));
     520        19788 :     memmove(&ProcGlobal->xids[index + 1],
     521        19788 :             &ProcGlobal->xids[index],
     522              :             movecount * sizeof(*ProcGlobal->xids));
     523        19788 :     memmove(&ProcGlobal->subxidStates[index + 1],
     524        19788 :             &ProcGlobal->subxidStates[index],
     525              :             movecount * sizeof(*ProcGlobal->subxidStates));
     526        19788 :     memmove(&ProcGlobal->statusFlags[index + 1],
     527        19788 :             &ProcGlobal->statusFlags[index],
     528              :             movecount * sizeof(*ProcGlobal->statusFlags));
     529              : 
     530        19788 :     arrayP->pgprocnos[index] = GetNumberFromPGProc(proc);
     531        19788 :     proc->pgxactoff = index;
     532        19788 :     ProcGlobal->xids[index] = proc->xid;
     533        19788 :     ProcGlobal->subxidStates[index] = proc->subxidStatus;
     534        19788 :     ProcGlobal->statusFlags[index] = proc->statusFlags;
     535              : 
     536        19788 :     arrayP->numProcs++;
     537              : 
     538              :     /* adjust pgxactoff for all following PGPROCs */
     539        19788 :     index++;
     540        53434 :     for (; index < arrayP->numProcs; index++)
     541              :     {
     542        33646 :         int         procno = arrayP->pgprocnos[index];
     543              : 
     544              :         Assert(procno >= 0 && procno < (arrayP->maxProcs + NUM_AUXILIARY_PROCS));
     545              :         Assert(allProcs[procno].pgxactoff == index - 1);
     546              : 
     547        33646 :         allProcs[procno].pgxactoff = index;
     548              :     }
     549              : 
     550              :     /*
     551              :      * Release in reversed acquisition order, to reduce frequency of having to
     552              :      * wait for XidGenLock while holding ProcArrayLock.
     553              :      */
     554        19788 :     LWLockRelease(XidGenLock);
     555        19788 :     LWLockRelease(ProcArrayLock);
     556        19788 : }
     557              : 
     558              : /*
     559              :  * Remove the specified PGPROC from the shared array.
     560              :  *
     561              :  * When latestXid is a valid XID, we are removing a live 2PC gxact from the
     562              :  * array, and thus causing it to appear as "not running" anymore.  In this
     563              :  * case we must advance latestCompletedXid.  (This is essentially the same
     564              :  * as ProcArrayEndTransaction followed by removal of the PGPROC, but we take
     565              :  * the ProcArrayLock only once, and don't damage the content of the PGPROC;
     566              :  * twophase.c depends on the latter.)
     567              :  */
     568              : void
     569        19759 : ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
     570              : {
     571        19759 :     ProcArrayStruct *arrayP = procArray;
     572              :     int         myoff;
     573              :     int         movecount;
     574              : 
     575              : #ifdef XIDCACHE_DEBUG
     576              :     /* dump stats at backend shutdown, but not prepared-xact end */
     577              :     if (proc->pid != 0)
     578              :         DisplayXidCache();
     579              : #endif
     580              : 
     581              :     /* See ProcGlobal comment explaining why both locks are held */
     582        19759 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     583        19759 :     LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
     584              : 
     585        19759 :     myoff = proc->pgxactoff;
     586              : 
     587              :     Assert(myoff >= 0 && myoff < arrayP->numProcs);
     588              :     Assert(ProcGlobal->allProcs[arrayP->pgprocnos[myoff]].pgxactoff == myoff);
     589              : 
     590        19759 :     if (TransactionIdIsValid(latestXid))
     591              :     {
     592              :         Assert(TransactionIdIsValid(ProcGlobal->xids[myoff]));
     593              : 
     594              :         /* Advance global latestCompletedXid while holding the lock */
     595          313 :         MaintainLatestCompletedXid(latestXid);
     596              : 
     597              :         /* Same with xactCompletionCount  */
     598          313 :         TransamVariables->xactCompletionCount++;
     599              : 
     600          313 :         ProcGlobal->xids[myoff] = InvalidTransactionId;
     601          313 :         ProcGlobal->subxidStates[myoff].overflowed = false;
     602          313 :         ProcGlobal->subxidStates[myoff].count = 0;
     603              :     }
     604              :     else
     605              :     {
     606              :         /* Shouldn't be trying to remove a live transaction here */
     607              :         Assert(!TransactionIdIsValid(ProcGlobal->xids[myoff]));
     608              :     }
     609              : 
     610              :     Assert(!TransactionIdIsValid(ProcGlobal->xids[myoff]));
     611              :     Assert(ProcGlobal->subxidStates[myoff].count == 0);
     612              :     Assert(ProcGlobal->subxidStates[myoff].overflowed == false);
     613              : 
     614        19759 :     ProcGlobal->statusFlags[myoff] = 0;
     615              : 
     616              :     /* Keep the PGPROC array sorted. See notes above */
     617        19759 :     movecount = arrayP->numProcs - myoff - 1;
     618        19759 :     memmove(&arrayP->pgprocnos[myoff],
     619        19759 :             &arrayP->pgprocnos[myoff + 1],
     620              :             movecount * sizeof(*arrayP->pgprocnos));
     621        19759 :     memmove(&ProcGlobal->xids[myoff],
     622        19759 :             &ProcGlobal->xids[myoff + 1],
     623              :             movecount * sizeof(*ProcGlobal->xids));
     624        19759 :     memmove(&ProcGlobal->subxidStates[myoff],
     625        19759 :             &ProcGlobal->subxidStates[myoff + 1],
     626              :             movecount * sizeof(*ProcGlobal->subxidStates));
     627        19759 :     memmove(&ProcGlobal->statusFlags[myoff],
     628        19759 :             &ProcGlobal->statusFlags[myoff + 1],
     629              :             movecount * sizeof(*ProcGlobal->statusFlags));
     630              : 
     631        19759 :     arrayP->pgprocnos[arrayP->numProcs - 1] = -1; /* for debugging */
     632        19759 :     arrayP->numProcs--;
     633              : 
     634              :     /*
     635              :      * Adjust pgxactoff of following procs for removed PGPROC (note that
     636              :      * numProcs already has been decremented).
     637              :      */
     638        57297 :     for (int index = myoff; index < arrayP->numProcs; index++)
     639              :     {
     640        37538 :         int         procno = arrayP->pgprocnos[index];
     641              : 
     642              :         Assert(procno >= 0 && procno < (arrayP->maxProcs + NUM_AUXILIARY_PROCS));
     643              :         Assert(allProcs[procno].pgxactoff - 1 == index);
     644              : 
     645        37538 :         allProcs[procno].pgxactoff = index;
     646              :     }
     647              : 
     648              :     /*
     649              :      * Release in reversed acquisition order, to reduce frequency of having to
     650              :      * wait for XidGenLock while holding ProcArrayLock.
     651              :      */
     652        19759 :     LWLockRelease(XidGenLock);
     653        19759 :     LWLockRelease(ProcArrayLock);
     654        19759 : }
     655              : 
     656              : 
     657              : /*
     658              :  * ProcArrayEndTransaction -- mark a transaction as no longer running
     659              :  *
     660              :  * This is used interchangeably for commit and abort cases.  The transaction
     661              :  * commit/abort must already be reported to WAL and pg_xact.
     662              :  *
     663              :  * proc is currently always MyProc, but we pass it explicitly for flexibility.
     664              :  * latestXid is the latest Xid among the transaction's main XID and
     665              :  * subtransactions, or InvalidTransactionId if it has no XID.  (We must ask
     666              :  * the caller to pass latestXid, instead of computing it from the PGPROC's
     667              :  * contents, because the subxid information in the PGPROC might be
     668              :  * incomplete.)
     669              :  */
     670              : void
     671       617613 : ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
     672              : {
     673       617613 :     if (TransactionIdIsValid(latestXid))
     674              :     {
     675              :         /*
     676              :          * We must lock ProcArrayLock while clearing our advertised XID, so
     677              :          * that we do not exit the set of "running" transactions while someone
     678              :          * else is taking a snapshot.  See discussion in
     679              :          * src/backend/access/transam/README.
     680              :          */
     681              :         Assert(TransactionIdIsValid(proc->xid));
     682              : 
     683              :         /*
     684              :          * If we can immediately acquire ProcArrayLock, we clear our own XID
     685              :          * and release the lock.  If not, use group XID clearing to improve
     686              :          * efficiency.
     687              :          */
     688       159202 :         if (LWLockConditionalAcquire(ProcArrayLock, LW_EXCLUSIVE))
     689              :         {
     690       159056 :             ProcArrayEndTransactionInternal(proc, latestXid);
     691       159056 :             LWLockRelease(ProcArrayLock);
     692              :         }
     693              :         else
     694          146 :             ProcArrayGroupClearXid(proc, latestXid);
     695              :     }
     696              :     else
     697              :     {
     698              :         /*
     699              :          * If we have no XID, we don't need to lock, since we won't affect
     700              :          * anyone else's calculation of a snapshot.  We might change their
     701              :          * estimate of global xmin, but that's OK.
     702              :          */
     703              :         Assert(!TransactionIdIsValid(proc->xid));
     704              :         Assert(proc->subxidStatus.count == 0);
     705              :         Assert(!proc->subxidStatus.overflowed);
     706              : 
     707       458411 :         proc->vxid.lxid = InvalidLocalTransactionId;
     708       458411 :         proc->xmin = InvalidTransactionId;
     709              : 
     710              :         /* be sure this is cleared in abort */
     711       458411 :         proc->delayChkptFlags = 0;
     712              : 
     713              :         /* must be cleared with xid/xmin: */
     714              :         /* avoid unnecessarily dirtying shared cachelines */
     715       458411 :         if (proc->statusFlags & PROC_VACUUM_STATE_MASK)
     716              :         {
     717              :             Assert(!LWLockHeldByMe(ProcArrayLock));
     718       118627 :             LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     719              :             Assert(proc->statusFlags == ProcGlobal->statusFlags[proc->pgxactoff]);
     720       118627 :             proc->statusFlags &= ~PROC_VACUUM_STATE_MASK;
     721       118627 :             ProcGlobal->statusFlags[proc->pgxactoff] = proc->statusFlags;
     722       118627 :             LWLockRelease(ProcArrayLock);
     723              :         }
     724              :     }
     725       617613 : }
     726              : 
     727              : /*
     728              :  * Mark a write transaction as no longer running.
     729              :  *
     730              :  * We don't do any locking here; caller must handle that.
     731              :  */
     732              : static inline void
     733       159202 : ProcArrayEndTransactionInternal(PGPROC *proc, TransactionId latestXid)
     734              : {
     735       159202 :     int         pgxactoff = proc->pgxactoff;
     736              : 
     737              :     /*
     738              :      * Note: we need exclusive lock here because we're going to change other
     739              :      * processes' PGPROC entries.
     740              :      */
     741              :     Assert(LWLockHeldByMeInMode(ProcArrayLock, LW_EXCLUSIVE));
     742              :     Assert(TransactionIdIsValid(ProcGlobal->xids[pgxactoff]));
     743              :     Assert(ProcGlobal->xids[pgxactoff] == proc->xid);
     744              : 
     745       159202 :     ProcGlobal->xids[pgxactoff] = InvalidTransactionId;
     746       159202 :     proc->xid = InvalidTransactionId;
     747       159202 :     proc->vxid.lxid = InvalidLocalTransactionId;
     748       159202 :     proc->xmin = InvalidTransactionId;
     749              : 
     750              :     /* be sure this is cleared in abort */
     751       159202 :     proc->delayChkptFlags = 0;
     752              : 
     753              :     /* must be cleared with xid/xmin: */
     754              :     /* avoid unnecessarily dirtying shared cachelines */
     755       159202 :     if (proc->statusFlags & PROC_VACUUM_STATE_MASK)
     756              :     {
     757          819 :         proc->statusFlags &= ~PROC_VACUUM_STATE_MASK;
     758          819 :         ProcGlobal->statusFlags[proc->pgxactoff] = proc->statusFlags;
     759              :     }
     760              : 
     761              :     /* Clear the subtransaction-XID cache too while holding the lock */
     762              :     Assert(ProcGlobal->subxidStates[pgxactoff].count == proc->subxidStatus.count &&
     763              :            ProcGlobal->subxidStates[pgxactoff].overflowed == proc->subxidStatus.overflowed);
     764       159202 :     if (proc->subxidStatus.count > 0 || proc->subxidStatus.overflowed)
     765              :     {
     766          595 :         ProcGlobal->subxidStates[pgxactoff].count = 0;
     767          595 :         ProcGlobal->subxidStates[pgxactoff].overflowed = false;
     768          595 :         proc->subxidStatus.count = 0;
     769          595 :         proc->subxidStatus.overflowed = false;
     770              :     }
     771              : 
     772              :     /* Also advance global latestCompletedXid while holding the lock */
     773       159202 :     MaintainLatestCompletedXid(latestXid);
     774              : 
     775              :     /* Same with xactCompletionCount  */
     776       159202 :     TransamVariables->xactCompletionCount++;
     777       159202 : }
     778              : 
     779              : /*
     780              :  * ProcArrayGroupClearXid -- group XID clearing
     781              :  *
     782              :  * When we cannot immediately acquire ProcArrayLock in exclusive mode at
     783              :  * commit time, add ourselves to a list of processes that need their XIDs
     784              :  * cleared.  The first process to add itself to the list will acquire
     785              :  * ProcArrayLock in exclusive mode and perform ProcArrayEndTransactionInternal
     786              :  * on behalf of all group members.  This avoids a great deal of contention
     787              :  * around ProcArrayLock when many processes are trying to commit at once,
     788              :  * since the lock need not be repeatedly handed off from one committing
     789              :  * process to the next.
     790              :  */
     791              : static void
     792          146 : ProcArrayGroupClearXid(PGPROC *proc, TransactionId latestXid)
     793              : {
     794          146 :     int         pgprocno = GetNumberFromPGProc(proc);
     795          146 :     PROC_HDR   *procglobal = ProcGlobal;
     796              :     uint32      nextidx;
     797              :     uint32      wakeidx;
     798              : 
     799              :     /* We should definitely have an XID to clear. */
     800              :     Assert(TransactionIdIsValid(proc->xid));
     801              : 
     802              :     /* Add ourselves to the list of processes needing a group XID clear. */
     803          146 :     proc->procArrayGroupMember = true;
     804          146 :     proc->procArrayGroupMemberXid = latestXid;
     805          146 :     nextidx = pg_atomic_read_u32(&procglobal->procArrayGroupFirst);
     806              :     while (true)
     807              :     {
     808          146 :         pg_atomic_write_u32(&proc->procArrayGroupNext, nextidx);
     809              : 
     810          146 :         if (pg_atomic_compare_exchange_u32(&procglobal->procArrayGroupFirst,
     811              :                                            &nextidx,
     812              :                                            (uint32) pgprocno))
     813          146 :             break;
     814              :     }
     815              : 
     816              :     /*
     817              :      * If the list was not empty, the leader will clear our XID.  It is
     818              :      * impossible to have followers without a leader because the first process
     819              :      * that has added itself to the list will always have nextidx as
     820              :      * INVALID_PROC_NUMBER.
     821              :      */
     822          146 :     if (nextidx != INVALID_PROC_NUMBER)
     823              :     {
     824            8 :         int         extraWaits = 0;
     825              : 
     826              :         /* Sleep until the leader clears our XID. */
     827            8 :         pgstat_report_wait_start(WAIT_EVENT_PROCARRAY_GROUP_UPDATE);
     828              :         for (;;)
     829              :         {
     830              :             /* acts as a read barrier */
     831            8 :             PGSemaphoreLock(proc->sem);
     832            8 :             if (!proc->procArrayGroupMember)
     833            8 :                 break;
     834            0 :             extraWaits++;
     835              :         }
     836            8 :         pgstat_report_wait_end();
     837              : 
     838              :         Assert(pg_atomic_read_u32(&proc->procArrayGroupNext) == INVALID_PROC_NUMBER);
     839              : 
     840              :         /* Fix semaphore count for any absorbed wakeups */
     841            8 :         while (extraWaits-- > 0)
     842            0 :             PGSemaphoreUnlock(proc->sem);
     843            8 :         return;
     844              :     }
     845              : 
     846              :     /* We are the leader.  Acquire the lock on behalf of everyone. */
     847          138 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     848              : 
     849              :     /*
     850              :      * Now that we've got the lock, clear the list of processes waiting for
     851              :      * group XID clearing, saving a pointer to the head of the list.  Trying
     852              :      * to pop elements one at a time could lead to an ABA problem.
     853              :      */
     854          138 :     nextidx = pg_atomic_exchange_u32(&procglobal->procArrayGroupFirst,
     855              :                                      INVALID_PROC_NUMBER);
     856              : 
     857              :     /* Remember head of list so we can perform wakeups after dropping lock. */
     858          138 :     wakeidx = nextidx;
     859              : 
     860              :     /* Walk the list and clear all XIDs. */
     861          284 :     while (nextidx != INVALID_PROC_NUMBER)
     862              :     {
     863          146 :         PGPROC     *nextproc = &allProcs[nextidx];
     864              : 
     865          146 :         ProcArrayEndTransactionInternal(nextproc, nextproc->procArrayGroupMemberXid);
     866              : 
     867              :         /* Move to next proc in list. */
     868          146 :         nextidx = pg_atomic_read_u32(&nextproc->procArrayGroupNext);
     869              :     }
     870              : 
     871              :     /* We're done with the lock now. */
     872          138 :     LWLockRelease(ProcArrayLock);
     873              : 
     874              :     /*
     875              :      * Now that we've released the lock, go back and wake everybody up.  We
     876              :      * don't do this under the lock so as to keep lock hold times to a
     877              :      * minimum.  The system calls we need to perform to wake other processes
     878              :      * up are probably much slower than the simple memory writes we did while
     879              :      * holding the lock.
     880              :      */
     881          284 :     while (wakeidx != INVALID_PROC_NUMBER)
     882              :     {
     883          146 :         PGPROC     *nextproc = &allProcs[wakeidx];
     884              : 
     885          146 :         wakeidx = pg_atomic_read_u32(&nextproc->procArrayGroupNext);
     886          146 :         pg_atomic_write_u32(&nextproc->procArrayGroupNext, INVALID_PROC_NUMBER);
     887              : 
     888              :         /* ensure all previous writes are visible before follower continues. */
     889          146 :         pg_write_barrier();
     890              : 
     891          146 :         nextproc->procArrayGroupMember = false;
     892              : 
     893          146 :         if (nextproc != MyProc)
     894            8 :             PGSemaphoreUnlock(nextproc->sem);
     895              :     }
     896              : }
     897              : 
     898              : /*
     899              :  * ProcArrayClearTransaction -- clear the transaction fields
     900              :  *
     901              :  * This is used after successfully preparing a 2-phase transaction.  We are
     902              :  * not actually reporting the transaction's XID as no longer running --- it
     903              :  * will still appear as running because the 2PC's gxact is in the ProcArray
     904              :  * too.  We just have to clear out our own PGPROC.
     905              :  */
     906              : void
     907          309 : ProcArrayClearTransaction(PGPROC *proc)
     908              : {
     909              :     int         pgxactoff;
     910              : 
     911              :     /*
     912              :      * Currently we need to lock ProcArrayLock exclusively here, as we
     913              :      * increment xactCompletionCount below. We also need it at least in shared
     914              :      * mode for pgproc->pgxactoff to stay the same below.
     915              :      *
     916              :      * We could however, as this action does not actually change anyone's view
     917              :      * of the set of running XIDs (our entry is duplicate with the gxact that
     918              :      * has already been inserted into the ProcArray), lower the lock level to
     919              :      * shared if we were to make xactCompletionCount an atomic variable. But
     920              :      * that doesn't seem worth it currently, as a 2PC commit is heavyweight
     921              :      * enough for this not to be the bottleneck.  If it ever becomes a
     922              :      * bottleneck it may also be worth considering to combine this with the
     923              :      * subsequent ProcArrayRemove()
     924              :      */
     925          309 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     926              : 
     927          309 :     pgxactoff = proc->pgxactoff;
     928              : 
     929          309 :     ProcGlobal->xids[pgxactoff] = InvalidTransactionId;
     930          309 :     proc->xid = InvalidTransactionId;
     931              : 
     932          309 :     proc->vxid.lxid = InvalidLocalTransactionId;
     933          309 :     proc->xmin = InvalidTransactionId;
     934              : 
     935              :     Assert(!(proc->statusFlags & PROC_VACUUM_STATE_MASK));
     936              :     Assert(!proc->delayChkptFlags);
     937              : 
     938              :     /*
     939              :      * Need to increment completion count even though transaction hasn't
     940              :      * really committed yet. The reason for that is that GetSnapshotData()
     941              :      * omits the xid of the current transaction, thus without the increment we
     942              :      * otherwise could end up reusing the snapshot later. Which would be bad,
     943              :      * because it might not count the prepared transaction as running.
     944              :      */
     945          309 :     TransamVariables->xactCompletionCount++;
     946              : 
     947              :     /* Clear the subtransaction-XID cache too */
     948              :     Assert(ProcGlobal->subxidStates[pgxactoff].count == proc->subxidStatus.count &&
     949              :            ProcGlobal->subxidStates[pgxactoff].overflowed == proc->subxidStatus.overflowed);
     950          309 :     if (proc->subxidStatus.count > 0 || proc->subxidStatus.overflowed)
     951              :     {
     952          103 :         ProcGlobal->subxidStates[pgxactoff].count = 0;
     953          103 :         ProcGlobal->subxidStates[pgxactoff].overflowed = false;
     954          103 :         proc->subxidStatus.count = 0;
     955          103 :         proc->subxidStatus.overflowed = false;
     956              :     }
     957              : 
     958          309 :     LWLockRelease(ProcArrayLock);
     959          309 : }
     960              : 
     961              : /*
     962              :  * Update TransamVariables->latestCompletedXid to point to latestXid if
     963              :  * currently older.
     964              :  */
     965              : static void
     966       160366 : MaintainLatestCompletedXid(TransactionId latestXid)
     967              : {
     968       160366 :     FullTransactionId cur_latest = TransamVariables->latestCompletedXid;
     969              : 
     970              :     Assert(FullTransactionIdIsValid(cur_latest));
     971              :     Assert(!RecoveryInProgress());
     972              :     Assert(LWLockHeldByMe(ProcArrayLock));
     973              : 
     974       160366 :     if (TransactionIdPrecedes(XidFromFullTransactionId(cur_latest), latestXid))
     975              :     {
     976       144611 :         TransamVariables->latestCompletedXid =
     977       144611 :             FullXidRelativeTo(cur_latest, latestXid);
     978              :     }
     979              : 
     980              :     Assert(IsBootstrapProcessingMode() ||
     981              :            FullTransactionIdIsNormal(TransamVariables->latestCompletedXid));
     982       160366 : }
     983              : 
     984              : /*
     985              :  * Same as MaintainLatestCompletedXid, except for use during WAL replay.
     986              :  */
     987              : static void
     988        23944 : MaintainLatestCompletedXidRecovery(TransactionId latestXid)
     989              : {
     990        23944 :     FullTransactionId cur_latest = TransamVariables->latestCompletedXid;
     991              :     FullTransactionId rel;
     992              : 
     993              :     Assert(AmStartupProcess() || !IsUnderPostmaster);
     994              :     Assert(LWLockHeldByMe(ProcArrayLock));
     995              : 
     996              :     /*
     997              :      * Need a FullTransactionId to compare latestXid with. Can't rely on
     998              :      * latestCompletedXid to be initialized in recovery. But in recovery it's
     999              :      * safe to access nextXid without a lock for the startup process.
    1000              :      */
    1001        23944 :     rel = TransamVariables->nextXid;
    1002              :     Assert(FullTransactionIdIsValid(TransamVariables->nextXid));
    1003              : 
    1004        47774 :     if (!FullTransactionIdIsValid(cur_latest) ||
    1005        23830 :         TransactionIdPrecedes(XidFromFullTransactionId(cur_latest), latestXid))
    1006              :     {
    1007        18430 :         TransamVariables->latestCompletedXid =
    1008        18430 :             FullXidRelativeTo(rel, latestXid);
    1009              :     }
    1010              : 
    1011              :     Assert(FullTransactionIdIsNormal(TransamVariables->latestCompletedXid));
    1012        23944 : }
    1013              : 
    1014              : /*
    1015              :  * ProcArrayInitRecovery -- initialize recovery xid mgmt environment
    1016              :  *
    1017              :  * Remember up to where the startup process initialized the CLOG and subtrans
    1018              :  * so we can ensure it's initialized gaplessly up to the point where necessary
    1019              :  * while in recovery.
    1020              :  */
    1021              : void
    1022          114 : ProcArrayInitRecovery(TransactionId initializedUptoXID)
    1023              : {
    1024              :     Assert(standbyState == STANDBY_INITIALIZED);
    1025              :     Assert(TransactionIdIsNormal(initializedUptoXID));
    1026              : 
    1027              :     /*
    1028              :      * we set latestObservedXid to the xid SUBTRANS has been initialized up
    1029              :      * to, so we can extend it from that point onwards in
    1030              :      * RecordKnownAssignedTransactionIds, and when we get consistent in
    1031              :      * ProcArrayApplyRecoveryInfo().
    1032              :      */
    1033          114 :     latestObservedXid = initializedUptoXID;
    1034          114 :     TransactionIdRetreat(latestObservedXid);
    1035          114 : }
    1036              : 
    1037              : /*
    1038              :  * ProcArrayApplyRecoveryInfo -- apply recovery info about xids
    1039              :  *
    1040              :  * Takes us through 3 states: Initialized, Pending and Ready.
    1041              :  * Normal case is to go all the way to Ready straight away, though there
    1042              :  * are atypical cases where we need to take it in steps.
    1043              :  *
    1044              :  * Use the data about running transactions on the primary to create the initial
    1045              :  * state of KnownAssignedXids. We also use these records to regularly prune
    1046              :  * KnownAssignedXids because we know it is possible that some transactions
    1047              :  * with FATAL errors fail to write abort records, which could cause eventual
    1048              :  * overflow.
    1049              :  *
    1050              :  * See comments for LogStandbySnapshot().
    1051              :  */
    1052              : void
    1053          826 : ProcArrayApplyRecoveryInfo(RunningTransactions running)
    1054              : {
    1055              :     TransactionId *xids;
    1056              :     TransactionId advanceNextXid;
    1057              :     int         nxids;
    1058              :     int         i;
    1059              : 
    1060              :     Assert(standbyState >= STANDBY_INITIALIZED);
    1061              :     Assert(TransactionIdIsValid(running->nextXid));
    1062              :     Assert(TransactionIdIsValid(running->oldestRunningXid));
    1063              :     Assert(TransactionIdIsNormal(running->latestCompletedXid));
    1064              : 
    1065              :     /*
    1066              :      * Remove stale transactions, if any.
    1067              :      */
    1068          826 :     ExpireOldKnownAssignedTransactionIds(running->oldestRunningXid);
    1069              : 
    1070              :     /*
    1071              :      * Adjust TransamVariables->nextXid before StandbyReleaseOldLocks(),
    1072              :      * because we will need it up to date for accessing two-phase transactions
    1073              :      * in StandbyReleaseOldLocks().
    1074              :      */
    1075          826 :     advanceNextXid = running->nextXid;
    1076          826 :     TransactionIdRetreat(advanceNextXid);
    1077          826 :     AdvanceNextFullTransactionIdPastXid(advanceNextXid);
    1078              :     Assert(FullTransactionIdIsValid(TransamVariables->nextXid));
    1079              : 
    1080              :     /*
    1081              :      * Remove stale locks, if any.
    1082              :      */
    1083          826 :     StandbyReleaseOldLocks(running->oldestRunningXid);
    1084              : 
    1085              :     /*
    1086              :      * If our snapshot is already valid, nothing else to do...
    1087              :      */
    1088          826 :     if (standbyState == STANDBY_SNAPSHOT_READY)
    1089          712 :         return;
    1090              : 
    1091              :     /*
    1092              :      * If our initial RunningTransactionsData had an overflowed snapshot then
    1093              :      * we knew we were missing some subxids from our snapshot. If we continue
    1094              :      * to see overflowed snapshots then we might never be able to start up, so
    1095              :      * we make another test to see if our snapshot is now valid. We know that
    1096              :      * the missing subxids are equal to or earlier than nextXid. After we
    1097              :      * initialise we continue to apply changes during recovery, so once the
    1098              :      * oldestRunningXid is later than the nextXid from the initial snapshot we
    1099              :      * know that we no longer have missing information and can mark the
    1100              :      * snapshot as valid.
    1101              :      */
    1102          114 :     if (standbyState == STANDBY_SNAPSHOT_PENDING)
    1103              :     {
    1104              :         /*
    1105              :          * If the snapshot isn't overflowed or if its empty we can reset our
    1106              :          * pending state and use this snapshot instead.
    1107              :          */
    1108            0 :         if (running->subxid_status != SUBXIDS_MISSING || running->xcnt == 0)
    1109              :         {
    1110              :             /*
    1111              :              * If we have already collected known assigned xids, we need to
    1112              :              * throw them away before we apply the recovery snapshot.
    1113              :              */
    1114            0 :             KnownAssignedXidsReset();
    1115            0 :             standbyState = STANDBY_INITIALIZED;
    1116              :         }
    1117              :         else
    1118              :         {
    1119            0 :             if (TransactionIdPrecedes(standbySnapshotPendingXmin,
    1120              :                                       running->oldestRunningXid))
    1121              :             {
    1122            0 :                 standbyState = STANDBY_SNAPSHOT_READY;
    1123            0 :                 elog(DEBUG1,
    1124              :                      "recovery snapshots are now enabled");
    1125              :             }
    1126              :             else
    1127            0 :                 elog(DEBUG1,
    1128              :                      "recovery snapshot waiting for non-overflowed snapshot or "
    1129              :                      "until oldest active xid on standby is at least %u (now %u)",
    1130              :                      standbySnapshotPendingXmin,
    1131              :                      running->oldestRunningXid);
    1132            0 :             return;
    1133              :         }
    1134              :     }
    1135              : 
    1136              :     Assert(standbyState == STANDBY_INITIALIZED);
    1137              : 
    1138              :     /*
    1139              :      * NB: this can be reached at least twice, so make sure new code can deal
    1140              :      * with that.
    1141              :      */
    1142              : 
    1143              :     /*
    1144              :      * Nobody else is running yet, but take locks anyhow
    1145              :      */
    1146          114 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    1147              : 
    1148              :     /*
    1149              :      * KnownAssignedXids is sorted so we cannot just add the xids, we have to
    1150              :      * sort them first.
    1151              :      *
    1152              :      * Some of the new xids are top-level xids and some are subtransactions.
    1153              :      * We don't call SubTransSetParent because it doesn't matter yet. If we
    1154              :      * aren't overflowed then all xids will fit in snapshot and so we don't
    1155              :      * need subtrans. If we later overflow, an xid assignment record will add
    1156              :      * xids to subtrans. If RunningTransactionsData is overflowed then we
    1157              :      * don't have enough information to correctly update subtrans anyway.
    1158              :      */
    1159              : 
    1160              :     /*
    1161              :      * Allocate a temporary array to avoid modifying the array passed as
    1162              :      * argument.
    1163              :      */
    1164          114 :     xids = palloc_array(TransactionId, running->xcnt + running->subxcnt);
    1165              : 
    1166              :     /*
    1167              :      * Add to the temp array any xids which have not already completed.
    1168              :      */
    1169          114 :     nxids = 0;
    1170          119 :     for (i = 0; i < running->xcnt + running->subxcnt; i++)
    1171              :     {
    1172            5 :         TransactionId xid = running->xids[i];
    1173              : 
    1174              :         /*
    1175              :          * The running-xacts snapshot can contain xids that were still visible
    1176              :          * in the procarray when the snapshot was taken, but were already
    1177              :          * WAL-logged as completed. They're not running anymore, so ignore
    1178              :          * them.
    1179              :          */
    1180            5 :         if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
    1181            0 :             continue;
    1182              : 
    1183            5 :         xids[nxids++] = xid;
    1184              :     }
    1185              : 
    1186          114 :     if (nxids > 0)
    1187              :     {
    1188            5 :         if (procArray->numKnownAssignedXids != 0)
    1189              :         {
    1190            0 :             LWLockRelease(ProcArrayLock);
    1191            0 :             elog(ERROR, "KnownAssignedXids is not empty");
    1192              :         }
    1193              : 
    1194              :         /*
    1195              :          * Sort the array so that we can add them safely into
    1196              :          * KnownAssignedXids.
    1197              :          *
    1198              :          * We have to sort them logically, because in KnownAssignedXidsAdd we
    1199              :          * call TransactionIdFollowsOrEquals and so on. But we know these XIDs
    1200              :          * come from RUNNING_XACTS, which means there are only normal XIDs
    1201              :          * from the same epoch, so this is safe.
    1202              :          */
    1203            5 :         qsort(xids, nxids, sizeof(TransactionId), xidLogicalComparator);
    1204              : 
    1205              :         /*
    1206              :          * Add the sorted snapshot into KnownAssignedXids.  The running-xacts
    1207              :          * snapshot may include duplicated xids because of prepared
    1208              :          * transactions, so ignore them.
    1209              :          */
    1210           10 :         for (i = 0; i < nxids; i++)
    1211              :         {
    1212            5 :             if (i > 0 && TransactionIdEquals(xids[i - 1], xids[i]))
    1213              :             {
    1214            0 :                 elog(DEBUG1,
    1215              :                      "found duplicated transaction %u for KnownAssignedXids insertion",
    1216              :                      xids[i]);
    1217            0 :                 continue;
    1218              :             }
    1219            5 :             KnownAssignedXidsAdd(xids[i], xids[i], true);
    1220              :         }
    1221              : 
    1222            5 :         KnownAssignedXidsDisplay(DEBUG3);
    1223              :     }
    1224              : 
    1225          114 :     pfree(xids);
    1226              : 
    1227              :     /*
    1228              :      * latestObservedXid is at least set to the point where SUBTRANS was
    1229              :      * started up to (cf. ProcArrayInitRecovery()) or to the biggest xid
    1230              :      * RecordKnownAssignedTransactionIds() was called for.  Initialize
    1231              :      * subtrans from thereon, up to nextXid - 1.
    1232              :      *
    1233              :      * We need to duplicate parts of RecordKnownAssignedTransactionId() here,
    1234              :      * because we've just added xids to the known assigned xids machinery that
    1235              :      * haven't gone through RecordKnownAssignedTransactionId().
    1236              :      */
    1237              :     Assert(TransactionIdIsNormal(latestObservedXid));
    1238          114 :     TransactionIdAdvance(latestObservedXid);
    1239          228 :     while (TransactionIdPrecedes(latestObservedXid, running->nextXid))
    1240              :     {
    1241            0 :         ExtendSUBTRANS(latestObservedXid);
    1242            0 :         TransactionIdAdvance(latestObservedXid);
    1243              :     }
    1244          114 :     TransactionIdRetreat(latestObservedXid);    /* = running->nextXid - 1 */
    1245              : 
    1246              :     /* ----------
    1247              :      * Now we've got the running xids we need to set the global values that
    1248              :      * are used to track snapshots as they evolve further.
    1249              :      *
    1250              :      * - latestCompletedXid which will be the xmax for snapshots
    1251              :      * - lastOverflowedXid which shows whether snapshots overflow
    1252              :      * - nextXid
    1253              :      *
    1254              :      * If the snapshot overflowed, then we still initialise with what we know,
    1255              :      * but the recovery snapshot isn't fully valid yet because we know there
    1256              :      * are some subxids missing. We don't know the specific subxids that are
    1257              :      * missing, so conservatively assume the last one is latestObservedXid.
    1258              :      * ----------
    1259              :      */
    1260          114 :     if (running->subxid_status == SUBXIDS_MISSING)
    1261              :     {
    1262            0 :         standbyState = STANDBY_SNAPSHOT_PENDING;
    1263              : 
    1264            0 :         standbySnapshotPendingXmin = latestObservedXid;
    1265            0 :         procArray->lastOverflowedXid = latestObservedXid;
    1266              :     }
    1267              :     else
    1268              :     {
    1269          114 :         standbyState = STANDBY_SNAPSHOT_READY;
    1270              : 
    1271          114 :         standbySnapshotPendingXmin = InvalidTransactionId;
    1272              : 
    1273              :         /*
    1274              :          * If the 'xids' array didn't include all subtransactions, we have to
    1275              :          * mark any snapshots taken as overflowed.
    1276              :          */
    1277          114 :         if (running->subxid_status == SUBXIDS_IN_SUBTRANS)
    1278           26 :             procArray->lastOverflowedXid = latestObservedXid;
    1279              :         else
    1280              :         {
    1281              :             Assert(running->subxid_status == SUBXIDS_IN_ARRAY);
    1282           88 :             procArray->lastOverflowedXid = InvalidTransactionId;
    1283              :         }
    1284              :     }
    1285              : 
    1286              :     /*
    1287              :      * If a transaction wrote a commit record in the gap between taking and
    1288              :      * logging the snapshot then latestCompletedXid may already be higher than
    1289              :      * the value from the snapshot, so check before we use the incoming value.
    1290              :      * It also might not yet be set at all.
    1291              :      */
    1292          114 :     MaintainLatestCompletedXidRecovery(running->latestCompletedXid);
    1293              : 
    1294              :     /*
    1295              :      * NB: No need to increment TransamVariables->xactCompletionCount here,
    1296              :      * nobody can see it yet.
    1297              :      */
    1298              : 
    1299          114 :     LWLockRelease(ProcArrayLock);
    1300              : 
    1301          114 :     KnownAssignedXidsDisplay(DEBUG3);
    1302          114 :     if (standbyState == STANDBY_SNAPSHOT_READY)
    1303          114 :         elog(DEBUG1, "recovery snapshots are now enabled");
    1304              :     else
    1305            0 :         elog(DEBUG1,
    1306              :              "recovery snapshot waiting for non-overflowed snapshot or "
    1307              :              "until oldest active xid on standby is at least %u (now %u)",
    1308              :              standbySnapshotPendingXmin,
    1309              :              running->oldestRunningXid);
    1310              : }
    1311              : 
    1312              : /*
    1313              :  * ProcArrayApplyXidAssignment
    1314              :  *      Process an XLOG_XACT_ASSIGNMENT WAL record
    1315              :  */
    1316              : void
    1317           21 : ProcArrayApplyXidAssignment(TransactionId topxid,
    1318              :                             int nsubxids, TransactionId *subxids)
    1319              : {
    1320              :     TransactionId max_xid;
    1321              :     int         i;
    1322              : 
    1323              :     Assert(standbyState >= STANDBY_INITIALIZED);
    1324              : 
    1325           21 :     max_xid = TransactionIdLatest(topxid, nsubxids, subxids);
    1326              : 
    1327              :     /*
    1328              :      * Mark all the subtransactions as observed.
    1329              :      *
    1330              :      * NOTE: This will fail if the subxid contains too many previously
    1331              :      * unobserved xids to fit into known-assigned-xids. That shouldn't happen
    1332              :      * as the code stands, because xid-assignment records should never contain
    1333              :      * more than PGPROC_MAX_CACHED_SUBXIDS entries.
    1334              :      */
    1335           21 :     RecordKnownAssignedTransactionIds(max_xid);
    1336              : 
    1337              :     /*
    1338              :      * Notice that we update pg_subtrans with the top-level xid, rather than
    1339              :      * the parent xid. This is a difference between normal processing and
    1340              :      * recovery, yet is still correct in all cases. The reason is that
    1341              :      * subtransaction commit is not marked in clog until commit processing, so
    1342              :      * all aborted subtransactions have already been clearly marked in clog.
    1343              :      * As a result we are able to refer directly to the top-level
    1344              :      * transaction's state rather than skipping through all the intermediate
    1345              :      * states in the subtransaction tree. This should be the first time we
    1346              :      * have attempted to SubTransSetParent().
    1347              :      */
    1348         1365 :     for (i = 0; i < nsubxids; i++)
    1349         1344 :         SubTransSetParent(subxids[i], topxid);
    1350              : 
    1351              :     /* KnownAssignedXids isn't maintained yet, so we're done for now */
    1352           21 :     if (standbyState == STANDBY_INITIALIZED)
    1353            0 :         return;
    1354              : 
    1355              :     /*
    1356              :      * Uses same locking as transaction commit
    1357              :      */
    1358           21 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    1359              : 
    1360              :     /*
    1361              :      * Remove subxids from known-assigned-xacts.
    1362              :      */
    1363           21 :     KnownAssignedXidsRemoveTree(InvalidTransactionId, nsubxids, subxids);
    1364              : 
    1365              :     /*
    1366              :      * Advance lastOverflowedXid to be at least the last of these subxids.
    1367              :      */
    1368           21 :     if (TransactionIdPrecedes(procArray->lastOverflowedXid, max_xid))
    1369           21 :         procArray->lastOverflowedXid = max_xid;
    1370              : 
    1371           21 :     LWLockRelease(ProcArrayLock);
    1372              : }
    1373              : 
    1374              : /*
    1375              :  * TransactionIdIsInProgress -- is given transaction running in some backend
    1376              :  *
    1377              :  * Aside from some shortcuts such as checking RecentXmin and our own Xid,
    1378              :  * there are four possibilities for finding a running transaction:
    1379              :  *
    1380              :  * 1. The given Xid is a main transaction Id.  We will find this out cheaply
    1381              :  * by looking at ProcGlobal->xids.
    1382              :  *
    1383              :  * 2. The given Xid is one of the cached subxact Xids in the PGPROC array.
    1384              :  * We can find this out cheaply too.
    1385              :  *
    1386              :  * 3. In Hot Standby mode, we must search the KnownAssignedXids list to see
    1387              :  * if the Xid is running on the primary.
    1388              :  *
    1389              :  * 4. Search the SubTrans tree to find the Xid's topmost parent, and then see
    1390              :  * if that is running according to ProcGlobal->xids[] or KnownAssignedXids.
    1391              :  * This is the slowest way, but sadly it has to be done always if the others
    1392              :  * failed, unless we see that the cached subxact sets are complete (none have
    1393              :  * overflowed).
    1394              :  *
    1395              :  * ProcArrayLock has to be held while we do 1, 2, 3.  If we save the top Xids
    1396              :  * while doing 1 and 3, we can release the ProcArrayLock while we do 4.
    1397              :  * This buys back some concurrency (and we can't retrieve the main Xids from
    1398              :  * ProcGlobal->xids[] again anyway; see GetNewTransactionId).
    1399              :  */
    1400              : bool
    1401     13696294 : TransactionIdIsInProgress(TransactionId xid)
    1402              : {
    1403              :     static TransactionId *xids = NULL;
    1404              :     static TransactionId *other_xids;
    1405              :     XidCacheStatus *other_subxidstates;
    1406     13696294 :     int         nxids = 0;
    1407     13696294 :     ProcArrayStruct *arrayP = procArray;
    1408              :     TransactionId topxid;
    1409              :     TransactionId latestCompletedXid;
    1410              :     int         mypgxactoff;
    1411              :     int         numProcs;
    1412              :     int         j;
    1413              : 
    1414              :     /*
    1415              :      * Don't bother checking a transaction older than RecentXmin; it could not
    1416              :      * possibly still be running.  (Note: in particular, this guarantees that
    1417              :      * we reject InvalidTransactionId, FrozenTransactionId, etc as not
    1418              :      * running.)
    1419              :      */
    1420     13696294 :     if (TransactionIdPrecedes(xid, RecentXmin))
    1421              :     {
    1422              :         xc_by_recent_xmin_inc();
    1423      5959076 :         return false;
    1424              :     }
    1425              : 
    1426              :     /*
    1427              :      * We may have just checked the status of this transaction, so if it is
    1428              :      * already known to be completed, we can fall out without any access to
    1429              :      * shared memory.
    1430              :      */
    1431      7737218 :     if (TransactionIdEquals(cachedXidIsNotInProgress, xid))
    1432              :     {
    1433              :         xc_by_known_xact_inc();
    1434      1253816 :         return false;
    1435              :     }
    1436              : 
    1437              :     /*
    1438              :      * Also, we can handle our own transaction (and subtransactions) without
    1439              :      * any access to shared memory.
    1440              :      */
    1441      6483402 :     if (TransactionIdIsCurrentTransactionId(xid))
    1442              :     {
    1443              :         xc_by_my_xact_inc();
    1444       198024 :         return true;
    1445              :     }
    1446              : 
    1447              :     /*
    1448              :      * If first time through, get workspace to remember main XIDs in. We
    1449              :      * malloc it permanently to avoid repeated palloc/pfree overhead.
    1450              :      */
    1451      6285378 :     if (xids == NULL)
    1452              :     {
    1453              :         /*
    1454              :          * In hot standby mode, reserve enough space to hold all xids in the
    1455              :          * known-assigned list. If we later finish recovery, we no longer need
    1456              :          * the bigger array, but we don't bother to shrink it.
    1457              :          */
    1458         1661 :         int         maxxids = RecoveryInProgress() ? TOTAL_MAX_CACHED_SUBXIDS : arrayP->maxProcs;
    1459              : 
    1460         1661 :         xids = (TransactionId *) malloc(maxxids * sizeof(TransactionId));
    1461         1661 :         if (xids == NULL)
    1462            0 :             ereport(ERROR,
    1463              :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    1464              :                      errmsg("out of memory")));
    1465              :     }
    1466              : 
    1467      6285378 :     other_xids = ProcGlobal->xids;
    1468      6285378 :     other_subxidstates = ProcGlobal->subxidStates;
    1469              : 
    1470      6285378 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    1471              : 
    1472              :     /*
    1473              :      * Now that we have the lock, we can check latestCompletedXid; if the
    1474              :      * target Xid is after that, it's surely still running.
    1475              :      */
    1476      6285378 :     latestCompletedXid =
    1477      6285378 :         XidFromFullTransactionId(TransamVariables->latestCompletedXid);
    1478      6285378 :     if (TransactionIdPrecedes(latestCompletedXid, xid))
    1479              :     {
    1480      1509118 :         LWLockRelease(ProcArrayLock);
    1481              :         xc_by_latest_xid_inc();
    1482      1509118 :         return true;
    1483              :     }
    1484              : 
    1485              :     /* No shortcuts, gotta grovel through the array */
    1486      4776260 :     mypgxactoff = MyProc->pgxactoff;
    1487      4776260 :     numProcs = arrayP->numProcs;
    1488      4952112 :     for (int pgxactoff = 0; pgxactoff < numProcs; pgxactoff++)
    1489              :     {
    1490              :         int         pgprocno;
    1491              :         PGPROC     *proc;
    1492              :         TransactionId pxid;
    1493              :         int         pxids;
    1494              : 
    1495              :         /* Ignore ourselves --- dealt with it above */
    1496      4936785 :         if (pgxactoff == mypgxactoff)
    1497        16846 :             continue;
    1498              : 
    1499              :         /* Fetch xid just once - see GetNewTransactionId */
    1500      4919939 :         pxid = UINT32_ACCESS_ONCE(other_xids[pgxactoff]);
    1501              : 
    1502      4919939 :         if (!TransactionIdIsValid(pxid))
    1503       117393 :             continue;
    1504              : 
    1505              :         /*
    1506              :          * Step 1: check the main Xid
    1507              :          */
    1508      4802546 :         if (TransactionIdEquals(pxid, xid))
    1509              :         {
    1510      4760797 :             LWLockRelease(ProcArrayLock);
    1511              :             xc_by_main_xid_inc();
    1512      4760797 :             return true;
    1513              :         }
    1514              : 
    1515              :         /*
    1516              :          * We can ignore main Xids that are younger than the target Xid, since
    1517              :          * the target could not possibly be their child.
    1518              :          */
    1519        41749 :         if (TransactionIdPrecedes(xid, pxid))
    1520        19492 :             continue;
    1521              : 
    1522              :         /*
    1523              :          * Step 2: check the cached child-Xids arrays
    1524              :          */
    1525        22257 :         pxids = other_subxidstates[pgxactoff].count;
    1526        22257 :         pg_read_barrier();      /* pairs with barrier in GetNewTransactionId() */
    1527        22257 :         pgprocno = arrayP->pgprocnos[pgxactoff];
    1528        22257 :         proc = &allProcs[pgprocno];
    1529        40772 :         for (j = pxids - 1; j >= 0; j--)
    1530              :         {
    1531              :             /* Fetch xid just once - see GetNewTransactionId */
    1532        18651 :             TransactionId cxid = UINT32_ACCESS_ONCE(proc->subxids.xids[j]);
    1533              : 
    1534        18651 :             if (TransactionIdEquals(cxid, xid))
    1535              :             {
    1536          136 :                 LWLockRelease(ProcArrayLock);
    1537              :                 xc_by_child_xid_inc();
    1538          136 :                 return true;
    1539              :             }
    1540              :         }
    1541              : 
    1542              :         /*
    1543              :          * Save the main Xid for step 4.  We only need to remember main Xids
    1544              :          * that have uncached children.  (Note: there is no race condition
    1545              :          * here because the overflowed flag cannot be cleared, only set, while
    1546              :          * we hold ProcArrayLock.  So we can't miss an Xid that we need to
    1547              :          * worry about.)
    1548              :          */
    1549        22121 :         if (other_subxidstates[pgxactoff].overflowed)
    1550          220 :             xids[nxids++] = pxid;
    1551              :     }
    1552              : 
    1553              :     /*
    1554              :      * Step 3: in hot standby mode, check the known-assigned-xids list.  XIDs
    1555              :      * in the list must be treated as running.
    1556              :      */
    1557        15327 :     if (RecoveryInProgress())
    1558              :     {
    1559              :         /* none of the PGPROC entries should have XIDs in hot standby mode */
    1560              :         Assert(nxids == 0);
    1561              : 
    1562            1 :         if (KnownAssignedXidExists(xid))
    1563              :         {
    1564            0 :             LWLockRelease(ProcArrayLock);
    1565              :             xc_by_known_assigned_inc();
    1566            0 :             return true;
    1567              :         }
    1568              : 
    1569              :         /*
    1570              :          * If the KnownAssignedXids overflowed, we have to check pg_subtrans
    1571              :          * too.  Fetch all xids from KnownAssignedXids that are lower than
    1572              :          * xid, since if xid is a subtransaction its parent will always have a
    1573              :          * lower value.  Note we will collect both main and subXIDs here, but
    1574              :          * there's no help for it.
    1575              :          */
    1576            1 :         if (TransactionIdPrecedesOrEquals(xid, procArray->lastOverflowedXid))
    1577            0 :             nxids = KnownAssignedXidsGet(xids, xid);
    1578              :     }
    1579              : 
    1580        15327 :     LWLockRelease(ProcArrayLock);
    1581              : 
    1582              :     /*
    1583              :      * If none of the relevant caches overflowed, we know the Xid is not
    1584              :      * running without even looking at pg_subtrans.
    1585              :      */
    1586        15327 :     if (nxids == 0)
    1587              :     {
    1588              :         xc_no_overflow_inc();
    1589        15107 :         cachedXidIsNotInProgress = xid;
    1590        15107 :         return false;
    1591              :     }
    1592              : 
    1593              :     /*
    1594              :      * Step 4: have to check pg_subtrans.
    1595              :      *
    1596              :      * At this point, we know it's either a subtransaction of one of the Xids
    1597              :      * in xids[], or it's not running.  If it's an already-failed
    1598              :      * subtransaction, we want to say "not running" even though its parent may
    1599              :      * still be running.  So first, check pg_xact to see if it's been aborted.
    1600              :      */
    1601              :     xc_slow_answer_inc();
    1602              : 
    1603          220 :     if (TransactionIdDidAbort(xid))
    1604              :     {
    1605            0 :         cachedXidIsNotInProgress = xid;
    1606            0 :         return false;
    1607              :     }
    1608              : 
    1609              :     /*
    1610              :      * It isn't aborted, so check whether the transaction tree it belongs to
    1611              :      * is still running (or, more precisely, whether it was running when we
    1612              :      * held ProcArrayLock).
    1613              :      */
    1614          220 :     topxid = SubTransGetTopmostTransaction(xid);
    1615              :     Assert(TransactionIdIsValid(topxid));
    1616          377 :     if (!TransactionIdEquals(topxid, xid) &&
    1617          157 :         pg_lfind32(topxid, xids, nxids))
    1618          157 :         return true;
    1619              : 
    1620           63 :     cachedXidIsNotInProgress = xid;
    1621           63 :     return false;
    1622              : }
    1623              : 
    1624              : 
    1625              : /*
    1626              :  * Determine XID horizons.
    1627              :  *
    1628              :  * This is used by wrapper functions like GetOldestNonRemovableTransactionId()
    1629              :  * (for VACUUM), GetReplicationHorizons() (for hot_standby_feedback), etc as
    1630              :  * well as "internally" by GlobalVisUpdate() (see comment above struct
    1631              :  * GlobalVisState).
    1632              :  *
    1633              :  * See the definition of ComputeXidHorizonsResult for the various computed
    1634              :  * horizons.
    1635              :  *
    1636              :  * For VACUUM separate horizons (used to decide which deleted tuples must
    1637              :  * be preserved), for shared and non-shared tables are computed.  For shared
    1638              :  * relations backends in all databases must be considered, but for non-shared
    1639              :  * relations that's not required, since only backends in my own database could
    1640              :  * ever see the tuples in them. Also, we can ignore concurrently running lazy
    1641              :  * VACUUMs because (a) they must be working on other tables, and (b) they
    1642              :  * don't need to do snapshot-based lookups.
    1643              :  *
    1644              :  * This also computes a horizon used to truncate pg_subtrans. For that
    1645              :  * backends in all databases have to be considered, and concurrently running
    1646              :  * lazy VACUUMs cannot be ignored, as they still may perform pg_subtrans
    1647              :  * accesses.
    1648              :  *
    1649              :  * Note: we include all currently running xids in the set of considered xids.
    1650              :  * This ensures that if a just-started xact has not yet set its snapshot,
    1651              :  * when it does set the snapshot it cannot set xmin less than what we compute.
    1652              :  * See notes in src/backend/access/transam/README.
    1653              :  *
    1654              :  * Note: despite the above, it's possible for the calculated values to move
    1655              :  * backwards on repeated calls. The calculated values are conservative, so
    1656              :  * that anything older is definitely not considered as running by anyone
    1657              :  * anymore, but the exact values calculated depend on a number of things. For
    1658              :  * example, if there are no transactions running in the current database, the
    1659              :  * horizon for normal tables will be latestCompletedXid. If a transaction
    1660              :  * begins after that, its xmin will include in-progress transactions in other
    1661              :  * databases that started earlier, so another call will return a lower value.
    1662              :  * Nonetheless it is safe to vacuum a table in the current database with the
    1663              :  * first result.  There are also replication-related effects: a walsender
    1664              :  * process can set its xmin based on transactions that are no longer running
    1665              :  * on the primary but are still being replayed on the standby, thus possibly
    1666              :  * making the values go backwards.  In this case there is a possibility that
    1667              :  * we lose data that the standby would like to have, but unless the standby
    1668              :  * uses a replication slot to make its xmin persistent there is little we can
    1669              :  * do about that --- data is only protected if the walsender runs continuously
    1670              :  * while queries are executed on the standby.  (The Hot Standby code deals
    1671              :  * with such cases by failing standby queries that needed to access
    1672              :  * already-removed data, so there's no integrity bug.)
    1673              :  *
    1674              :  * Note: the approximate horizons (see definition of GlobalVisState) are
    1675              :  * updated by the computations done here. That's currently required for
    1676              :  * correctness and a small optimization. Without doing so it's possible that
    1677              :  * heap vacuum's call to heap_page_prune_and_freeze() uses a more conservative
    1678              :  * horizon than later when deciding which tuples can be removed - which the
    1679              :  * code doesn't expect (breaking HOT).
    1680              :  */
    1681              : static void
    1682       214267 : ComputeXidHorizons(ComputeXidHorizonsResult *h)
    1683              : {
    1684       214267 :     ProcArrayStruct *arrayP = procArray;
    1685              :     TransactionId kaxmin;
    1686       214267 :     bool        in_recovery = RecoveryInProgress();
    1687       214267 :     TransactionId *other_xids = ProcGlobal->xids;
    1688              : 
    1689              :     /* inferred after ProcArrayLock is released */
    1690       214267 :     h->catalog_oldest_nonremovable = InvalidTransactionId;
    1691              : 
    1692       214267 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    1693              : 
    1694       214267 :     h->latest_completed = TransamVariables->latestCompletedXid;
    1695              : 
    1696              :     /*
    1697              :      * We initialize the MIN() calculation with latestCompletedXid + 1. This
    1698              :      * is a lower bound for the XIDs that might appear in the ProcArray later,
    1699              :      * and so protects us against overestimating the result due to future
    1700              :      * additions.
    1701              :      */
    1702              :     {
    1703              :         TransactionId initial;
    1704              : 
    1705       214267 :         initial = XidFromFullTransactionId(h->latest_completed);
    1706              :         Assert(TransactionIdIsValid(initial));
    1707       214267 :         TransactionIdAdvance(initial);
    1708              : 
    1709       214267 :         h->oldest_considered_running = initial;
    1710       214267 :         h->shared_oldest_nonremovable = initial;
    1711       214267 :         h->data_oldest_nonremovable = initial;
    1712              : 
    1713              :         /*
    1714              :          * Only modifications made by this backend affect the horizon for
    1715              :          * temporary relations. Instead of a check in each iteration of the
    1716              :          * loop over all PGPROCs it is cheaper to just initialize to the
    1717              :          * current top-level xid any.
    1718              :          *
    1719              :          * Without an assigned xid we could use a horizon as aggressive as
    1720              :          * GetNewTransactionId(), but we can get away with the much cheaper
    1721              :          * latestCompletedXid + 1: If this backend has no xid there, by
    1722              :          * definition, can't be any newer changes in the temp table than
    1723              :          * latestCompletedXid.
    1724              :          */
    1725       214267 :         if (TransactionIdIsValid(MyProc->xid))
    1726        42307 :             h->temp_oldest_nonremovable = MyProc->xid;
    1727              :         else
    1728       171960 :             h->temp_oldest_nonremovable = initial;
    1729              :     }
    1730              : 
    1731              :     /*
    1732              :      * Fetch slot horizons while ProcArrayLock is held - the
    1733              :      * LWLockAcquire/LWLockRelease are a barrier, ensuring this happens inside
    1734              :      * the lock.
    1735              :      */
    1736       214267 :     h->slot_xmin = procArray->replication_slot_xmin;
    1737       214267 :     h->slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
    1738              : 
    1739      1403577 :     for (int index = 0; index < arrayP->numProcs; index++)
    1740              :     {
    1741      1189310 :         int         pgprocno = arrayP->pgprocnos[index];
    1742      1189310 :         PGPROC     *proc = &allProcs[pgprocno];
    1743      1189310 :         int8        statusFlags = ProcGlobal->statusFlags[index];
    1744              :         TransactionId xid;
    1745              :         TransactionId xmin;
    1746              : 
    1747              :         /* Fetch xid just once - see GetNewTransactionId */
    1748      1189310 :         xid = UINT32_ACCESS_ONCE(other_xids[index]);
    1749      1189310 :         xmin = UINT32_ACCESS_ONCE(proc->xmin);
    1750              : 
    1751              :         /*
    1752              :          * Consider both the transaction's Xmin, and its Xid.
    1753              :          *
    1754              :          * We must check both because a transaction might have an Xmin but not
    1755              :          * (yet) an Xid; conversely, if it has an Xid, that could determine
    1756              :          * some not-yet-set Xmin.
    1757              :          */
    1758      1189310 :         xmin = TransactionIdOlder(xmin, xid);
    1759              : 
    1760              :         /* if neither is set, this proc doesn't influence the horizon */
    1761      1189310 :         if (!TransactionIdIsValid(xmin))
    1762       543818 :             continue;
    1763              : 
    1764              :         /*
    1765              :          * Don't ignore any procs when determining which transactions might be
    1766              :          * considered running.  While slots should ensure logical decoding
    1767              :          * backends are protected even without this check, it can't hurt to
    1768              :          * include them here as well..
    1769              :          */
    1770       645492 :         h->oldest_considered_running =
    1771       645492 :             TransactionIdOlder(h->oldest_considered_running, xmin);
    1772              : 
    1773              :         /*
    1774              :          * Skip over backends either vacuuming (which is ok with rows being
    1775              :          * removed, as long as pg_subtrans is not truncated) or doing logical
    1776              :          * decoding (which manages xmin separately, check below).
    1777              :          */
    1778       645492 :         if (statusFlags & (PROC_IN_VACUUM | PROC_IN_LOGICAL_DECODING))
    1779       223724 :             continue;
    1780              : 
    1781              :         /* shared tables need to take backends in all databases into account */
    1782       421768 :         h->shared_oldest_nonremovable =
    1783       421768 :             TransactionIdOlder(h->shared_oldest_nonremovable, xmin);
    1784              : 
    1785              :         /*
    1786              :          * Normally sessions in other databases are ignored for anything but
    1787              :          * the shared horizon.
    1788              :          *
    1789              :          * However, include them when MyDatabaseId is not (yet) set.  A
    1790              :          * backend in the process of starting up must not compute a "too
    1791              :          * aggressive" horizon, otherwise we could end up using it to prune
    1792              :          * still-needed data away.  If the current backend never connects to a
    1793              :          * database this is harmless, because data_oldest_nonremovable will
    1794              :          * never be utilized.
    1795              :          *
    1796              :          * Also, sessions marked with PROC_AFFECTS_ALL_HORIZONS should always
    1797              :          * be included.  (This flag is used for hot standby feedback, which
    1798              :          * can't be tied to a specific database.)
    1799              :          *
    1800              :          * Also, while in recovery we cannot compute an accurate per-database
    1801              :          * horizon, as all xids are managed via the KnownAssignedXids
    1802              :          * machinery.
    1803              :          */
    1804       421768 :         if (proc->databaseId == MyDatabaseId ||
    1805        20455 :             MyDatabaseId == InvalidOid ||
    1806        12159 :             (statusFlags & PROC_AFFECTS_ALL_HORIZONS) ||
    1807              :             in_recovery)
    1808              :         {
    1809       409611 :             h->data_oldest_nonremovable =
    1810       409611 :                 TransactionIdOlder(h->data_oldest_nonremovable, xmin);
    1811              :         }
    1812              :     }
    1813              : 
    1814              :     /*
    1815              :      * If in recovery fetch oldest xid in KnownAssignedXids, will be applied
    1816              :      * after lock is released.
    1817              :      */
    1818       214267 :     if (in_recovery)
    1819          373 :         kaxmin = KnownAssignedXidsGetOldestXmin();
    1820              : 
    1821              :     /*
    1822              :      * No other information from shared state is needed, release the lock
    1823              :      * immediately. The rest of the computations can be done without a lock.
    1824              :      */
    1825       214267 :     LWLockRelease(ProcArrayLock);
    1826              : 
    1827       214267 :     if (in_recovery)
    1828              :     {
    1829          373 :         h->oldest_considered_running =
    1830          373 :             TransactionIdOlder(h->oldest_considered_running, kaxmin);
    1831          373 :         h->shared_oldest_nonremovable =
    1832          373 :             TransactionIdOlder(h->shared_oldest_nonremovable, kaxmin);
    1833          373 :         h->data_oldest_nonremovable =
    1834          373 :             TransactionIdOlder(h->data_oldest_nonremovable, kaxmin);
    1835              :         /* temp relations cannot be accessed in recovery */
    1836              :     }
    1837              : 
    1838              :     Assert(TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1839              :                                          h->shared_oldest_nonremovable));
    1840              :     Assert(TransactionIdPrecedesOrEquals(h->shared_oldest_nonremovable,
    1841              :                                          h->data_oldest_nonremovable));
    1842              : 
    1843              :     /*
    1844              :      * Check whether there are replication slots requiring an older xmin.
    1845              :      */
    1846       214267 :     h->shared_oldest_nonremovable =
    1847       214267 :         TransactionIdOlder(h->shared_oldest_nonremovable, h->slot_xmin);
    1848       214267 :     h->data_oldest_nonremovable =
    1849       214267 :         TransactionIdOlder(h->data_oldest_nonremovable, h->slot_xmin);
    1850              : 
    1851              :     /*
    1852              :      * The only difference between catalog / data horizons is that the slot's
    1853              :      * catalog xmin is applied to the catalog one (so catalogs can be accessed
    1854              :      * for logical decoding). Initialize with data horizon, and then back up
    1855              :      * further if necessary. Have to back up the shared horizon as well, since
    1856              :      * that also can contain catalogs.
    1857              :      */
    1858       214267 :     h->shared_oldest_nonremovable_raw = h->shared_oldest_nonremovable;
    1859       214267 :     h->shared_oldest_nonremovable =
    1860       214267 :         TransactionIdOlder(h->shared_oldest_nonremovable,
    1861              :                            h->slot_catalog_xmin);
    1862       214267 :     h->catalog_oldest_nonremovable = h->data_oldest_nonremovable;
    1863       214267 :     h->catalog_oldest_nonremovable =
    1864       214267 :         TransactionIdOlder(h->catalog_oldest_nonremovable,
    1865              :                            h->slot_catalog_xmin);
    1866              : 
    1867              :     /*
    1868              :      * It's possible that slots backed up the horizons further than
    1869              :      * oldest_considered_running. Fix.
    1870              :      */
    1871       214267 :     h->oldest_considered_running =
    1872       214267 :         TransactionIdOlder(h->oldest_considered_running,
    1873              :                            h->shared_oldest_nonremovable);
    1874       214267 :     h->oldest_considered_running =
    1875       214267 :         TransactionIdOlder(h->oldest_considered_running,
    1876              :                            h->catalog_oldest_nonremovable);
    1877       214267 :     h->oldest_considered_running =
    1878       214267 :         TransactionIdOlder(h->oldest_considered_running,
    1879              :                            h->data_oldest_nonremovable);
    1880              : 
    1881              :     /*
    1882              :      * shared horizons have to be at least as old as the oldest visible in
    1883              :      * current db
    1884              :      */
    1885              :     Assert(TransactionIdPrecedesOrEquals(h->shared_oldest_nonremovable,
    1886              :                                          h->data_oldest_nonremovable));
    1887              :     Assert(TransactionIdPrecedesOrEquals(h->shared_oldest_nonremovable,
    1888              :                                          h->catalog_oldest_nonremovable));
    1889              : 
    1890              :     /*
    1891              :      * Horizons need to ensure that pg_subtrans access is still possible for
    1892              :      * the relevant backends.
    1893              :      */
    1894              :     Assert(TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1895              :                                          h->shared_oldest_nonremovable));
    1896              :     Assert(TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1897              :                                          h->catalog_oldest_nonremovable));
    1898              :     Assert(TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1899              :                                          h->data_oldest_nonremovable));
    1900              :     Assert(TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1901              :                                          h->temp_oldest_nonremovable));
    1902              :     Assert(!TransactionIdIsValid(h->slot_xmin) ||
    1903              :            TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1904              :                                          h->slot_xmin));
    1905              :     Assert(!TransactionIdIsValid(h->slot_catalog_xmin) ||
    1906              :            TransactionIdPrecedesOrEquals(h->oldest_considered_running,
    1907              :                                          h->slot_catalog_xmin));
    1908              : 
    1909              :     /* update approximate horizons with the computed horizons */
    1910       214267 :     GlobalVisUpdateApply(h);
    1911       214267 : }
    1912              : 
    1913              : /*
    1914              :  * Determine what kind of visibility horizon needs to be used for a
    1915              :  * relation. If rel is NULL, the most conservative horizon is used.
    1916              :  */
    1917              : static inline GlobalVisHorizonKind
    1918     18994704 : GlobalVisHorizonKindForRel(Relation rel)
    1919              : {
    1920              :     /*
    1921              :      * Other relkinds currently don't contain xids, nor always the necessary
    1922              :      * logical decoding markers.
    1923              :      */
    1924              :     Assert(!rel ||
    1925              :            rel->rd_rel->relkind == RELKIND_RELATION ||
    1926              :            rel->rd_rel->relkind == RELKIND_MATVIEW ||
    1927              :            rel->rd_rel->relkind == RELKIND_TOASTVALUE);
    1928              : 
    1929     18994704 :     if (rel == NULL || rel->rd_rel->relisshared || RecoveryInProgress())
    1930       121818 :         return VISHORIZON_SHARED;
    1931     18872886 :     else if (IsCatalogRelation(rel) ||
    1932     15065994 :              RelationIsAccessibleInLogicalDecoding(rel))
    1933      3806896 :         return VISHORIZON_CATALOG;
    1934     15065990 :     else if (!RELATION_IS_LOCAL(rel))
    1935     14978107 :         return VISHORIZON_DATA;
    1936              :     else
    1937        87883 :         return VISHORIZON_TEMP;
    1938              : }
    1939              : 
    1940              : /*
    1941              :  * Return the oldest XID for which deleted tuples must be preserved in the
    1942              :  * passed table.
    1943              :  *
    1944              :  * If rel is not NULL the horizon may be considerably more recent than
    1945              :  * otherwise (i.e. fewer tuples will be removable). In the NULL case a horizon
    1946              :  * that is correct (but not optimal) for all relations will be returned.
    1947              :  *
    1948              :  * This is used by VACUUM to decide which deleted tuples must be preserved in
    1949              :  * the passed in table.
    1950              :  */
    1951              : TransactionId
    1952       146303 : GetOldestNonRemovableTransactionId(Relation rel)
    1953              : {
    1954              :     ComputeXidHorizonsResult horizons;
    1955              : 
    1956       146303 :     ComputeXidHorizons(&horizons);
    1957              : 
    1958       146303 :     switch (GlobalVisHorizonKindForRel(rel))
    1959              :     {
    1960        21022 :         case VISHORIZON_SHARED:
    1961        21022 :             return horizons.shared_oldest_nonremovable;
    1962        89575 :         case VISHORIZON_CATALOG:
    1963        89575 :             return horizons.catalog_oldest_nonremovable;
    1964        20575 :         case VISHORIZON_DATA:
    1965        20575 :             return horizons.data_oldest_nonremovable;
    1966        15131 :         case VISHORIZON_TEMP:
    1967        15131 :             return horizons.temp_oldest_nonremovable;
    1968              :     }
    1969              : 
    1970              :     /* just to prevent compiler warnings */
    1971            0 :     return InvalidTransactionId;
    1972              : }
    1973              : 
    1974              : /*
    1975              :  * Return the oldest transaction id any currently running backend might still
    1976              :  * consider running. This should not be used for visibility / pruning
    1977              :  * determinations (see GetOldestNonRemovableTransactionId()), but for
    1978              :  * decisions like up to where pg_subtrans can be truncated.
    1979              :  */
    1980              : TransactionId
    1981         1805 : GetOldestTransactionIdConsideredRunning(void)
    1982              : {
    1983              :     ComputeXidHorizonsResult horizons;
    1984              : 
    1985         1805 :     ComputeXidHorizons(&horizons);
    1986              : 
    1987         1805 :     return horizons.oldest_considered_running;
    1988              : }
    1989              : 
    1990              : /*
    1991              :  * Return the visibility horizons for a hot standby feedback message.
    1992              :  */
    1993              : void
    1994           51 : GetReplicationHorizons(TransactionId *xmin, TransactionId *catalog_xmin)
    1995              : {
    1996              :     ComputeXidHorizonsResult horizons;
    1997              : 
    1998           51 :     ComputeXidHorizons(&horizons);
    1999              : 
    2000              :     /*
    2001              :      * Don't want to use shared_oldest_nonremovable here, as that contains the
    2002              :      * effect of replication slot's catalog_xmin. We want to send a separate
    2003              :      * feedback for the catalog horizon, so the primary can remove data table
    2004              :      * contents more aggressively.
    2005              :      */
    2006           51 :     *xmin = horizons.shared_oldest_nonremovable_raw;
    2007           51 :     *catalog_xmin = horizons.slot_catalog_xmin;
    2008           51 : }
    2009              : 
    2010              : /*
    2011              :  * GetMaxSnapshotXidCount -- get max size for snapshot XID array
    2012              :  *
    2013              :  * We have to export this for use by snapmgr.c.
    2014              :  */
    2015              : int
    2016        37009 : GetMaxSnapshotXidCount(void)
    2017              : {
    2018        37009 :     return procArray->maxProcs;
    2019              : }
    2020              : 
    2021              : /*
    2022              :  * GetMaxSnapshotSubxidCount -- get max size for snapshot sub-XID array
    2023              :  *
    2024              :  * We have to export this for use by snapmgr.c.
    2025              :  */
    2026              : int
    2027        36803 : GetMaxSnapshotSubxidCount(void)
    2028              : {
    2029        36803 :     return TOTAL_MAX_CACHED_SUBXIDS;
    2030              : }
    2031              : 
    2032              : /*
    2033              :  * Helper function for GetSnapshotData() that checks if the bulk of the
    2034              :  * visibility information in the snapshot is still valid. If so, it updates
    2035              :  * the fields that need to change and returns true. Otherwise it returns
    2036              :  * false.
    2037              :  *
    2038              :  * This very likely can be evolved to not need ProcArrayLock held (at very
    2039              :  * least in the case we already hold a snapshot), but that's for another day.
    2040              :  */
    2041              : static bool
    2042      2949284 : GetSnapshotDataReuse(Snapshot snapshot)
    2043              : {
    2044              :     uint64      curXactCompletionCount;
    2045              : 
    2046              :     Assert(LWLockHeldByMe(ProcArrayLock));
    2047              : 
    2048      2949284 :     if (unlikely(snapshot->snapXactCompletionCount == 0))
    2049        36786 :         return false;
    2050              : 
    2051      2912498 :     curXactCompletionCount = TransamVariables->xactCompletionCount;
    2052      2912498 :     if (curXactCompletionCount != snapshot->snapXactCompletionCount)
    2053       445276 :         return false;
    2054              : 
    2055              :     /*
    2056              :      * If the current xactCompletionCount is still the same as it was at the
    2057              :      * time the snapshot was built, we can be sure that rebuilding the
    2058              :      * contents of the snapshot the hard way would result in the same snapshot
    2059              :      * contents:
    2060              :      *
    2061              :      * As explained in transam/README, the set of xids considered running by
    2062              :      * GetSnapshotData() cannot change while ProcArrayLock is held. Snapshot
    2063              :      * contents only depend on transactions with xids and xactCompletionCount
    2064              :      * is incremented whenever a transaction with an xid finishes (while
    2065              :      * holding ProcArrayLock exclusively). Thus the xactCompletionCount check
    2066              :      * ensures we would detect if the snapshot would have changed.
    2067              :      *
    2068              :      * As the snapshot contents are the same as it was before, it is safe to
    2069              :      * re-enter the snapshot's xmin into the PGPROC array. None of the rows
    2070              :      * visible under the snapshot could already have been removed (that'd
    2071              :      * require the set of running transactions to change) and it fulfills the
    2072              :      * requirement that concurrent GetSnapshotData() calls yield the same
    2073              :      * xmin.
    2074              :      */
    2075      2467222 :     if (!TransactionIdIsValid(MyProc->xmin))
    2076       768849 :         MyProc->xmin = TransactionXmin = snapshot->xmin;
    2077              : 
    2078      2467222 :     RecentXmin = snapshot->xmin;
    2079              :     Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin));
    2080              : 
    2081      2467222 :     snapshot->curcid = GetCurrentCommandId(false);
    2082      2467222 :     snapshot->active_count = 0;
    2083      2467222 :     snapshot->regd_count = 0;
    2084      2467222 :     snapshot->copied = false;
    2085              : 
    2086      2467222 :     return true;
    2087              : }
    2088              : 
    2089              : /*
    2090              :  * GetSnapshotData -- returns information about running transactions.
    2091              :  *
    2092              :  * The returned snapshot includes xmin (lowest still-running xact ID),
    2093              :  * xmax (highest completed xact ID + 1), and a list of running xact IDs
    2094              :  * in the range xmin <= xid < xmax.  It is used as follows:
    2095              :  *      All xact IDs < xmin are considered finished.
    2096              :  *      All xact IDs >= xmax are considered still running.
    2097              :  *      For an xact ID xmin <= xid < xmax, consult list to see whether
    2098              :  *      it is considered running or not.
    2099              :  * This ensures that the set of transactions seen as "running" by the
    2100              :  * current xact will not change after it takes the snapshot.
    2101              :  *
    2102              :  * All running top-level XIDs are included in the snapshot, except for lazy
    2103              :  * VACUUM processes.  We also try to include running subtransaction XIDs,
    2104              :  * but since PGPROC has only a limited cache area for subxact XIDs, full
    2105              :  * information may not be available.  If we find any overflowed subxid arrays,
    2106              :  * we have to mark the snapshot's subxid data as overflowed, and extra work
    2107              :  * *may* need to be done to determine what's running (see XidInMVCCSnapshot()).
    2108              :  *
    2109              :  * We also update the following backend-global variables:
    2110              :  *      TransactionXmin: the oldest xmin of any snapshot in use in the
    2111              :  *          current transaction (this is the same as MyProc->xmin).
    2112              :  *      RecentXmin: the xmin computed for the most recent snapshot.  XIDs
    2113              :  *          older than this are known not running any more.
    2114              :  *
    2115              :  * And try to advance the bounds of GlobalVis{Shared,Catalog,Data,Temp}Rels
    2116              :  * for the benefit of the GlobalVisTest* family of functions.
    2117              :  *
    2118              :  * Note: this function should probably not be called with an argument that's
    2119              :  * not statically allocated (see xip allocation below).
    2120              :  */
    2121              : Snapshot
    2122      2949284 : GetSnapshotData(Snapshot snapshot)
    2123              : {
    2124      2949284 :     ProcArrayStruct *arrayP = procArray;
    2125      2949284 :     TransactionId *other_xids = ProcGlobal->xids;
    2126              :     TransactionId xmin;
    2127              :     TransactionId xmax;
    2128      2949284 :     int         count = 0;
    2129      2949284 :     int         subcount = 0;
    2130      2949284 :     bool        suboverflowed = false;
    2131              :     FullTransactionId latest_completed;
    2132              :     TransactionId oldestxid;
    2133              :     int         mypgxactoff;
    2134              :     TransactionId myxid;
    2135              :     uint64      curXactCompletionCount;
    2136              : 
    2137      2949284 :     TransactionId replication_slot_xmin = InvalidTransactionId;
    2138      2949284 :     TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
    2139              : 
    2140              :     Assert(snapshot != NULL);
    2141              : 
    2142              :     /*
    2143              :      * Allocating space for maxProcs xids is usually overkill; numProcs would
    2144              :      * be sufficient.  But it seems better to do the malloc while not holding
    2145              :      * the lock, so we can't look at numProcs.  Likewise, we allocate much
    2146              :      * more subxip storage than is probably needed.
    2147              :      *
    2148              :      * This does open a possibility for avoiding repeated malloc/free: since
    2149              :      * maxProcs does not change at runtime, we can simply reuse the previous
    2150              :      * xip arrays if any.  (This relies on the fact that all callers pass
    2151              :      * static SnapshotData structs.)
    2152              :      */
    2153      2949284 :     if (snapshot->xip == NULL)
    2154              :     {
    2155              :         /*
    2156              :          * First call for this snapshot. Snapshot is same size whether or not
    2157              :          * we are in recovery, see later comments.
    2158              :          */
    2159        36778 :         snapshot->xip = (TransactionId *)
    2160        36778 :             malloc(GetMaxSnapshotXidCount() * sizeof(TransactionId));
    2161        36778 :         if (snapshot->xip == NULL)
    2162            0 :             ereport(ERROR,
    2163              :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    2164              :                      errmsg("out of memory")));
    2165              :         Assert(snapshot->subxip == NULL);
    2166        36778 :         snapshot->subxip = (TransactionId *)
    2167        36778 :             malloc(GetMaxSnapshotSubxidCount() * sizeof(TransactionId));
    2168        36778 :         if (snapshot->subxip == NULL)
    2169            0 :             ereport(ERROR,
    2170              :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    2171              :                      errmsg("out of memory")));
    2172              :     }
    2173              : 
    2174              :     /*
    2175              :      * It is sufficient to get shared lock on ProcArrayLock, even if we are
    2176              :      * going to set MyProc->xmin.
    2177              :      */
    2178      2949284 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    2179              : 
    2180      2949284 :     if (GetSnapshotDataReuse(snapshot))
    2181              :     {
    2182      2467222 :         LWLockRelease(ProcArrayLock);
    2183      2467222 :         return snapshot;
    2184              :     }
    2185              : 
    2186       482062 :     latest_completed = TransamVariables->latestCompletedXid;
    2187       482062 :     mypgxactoff = MyProc->pgxactoff;
    2188       482062 :     myxid = other_xids[mypgxactoff];
    2189              :     Assert(myxid == MyProc->xid);
    2190              : 
    2191       482062 :     oldestxid = TransamVariables->oldestXid;
    2192       482062 :     curXactCompletionCount = TransamVariables->xactCompletionCount;
    2193              : 
    2194              :     /* xmax is always latestCompletedXid + 1 */
    2195       482062 :     xmax = XidFromFullTransactionId(latest_completed);
    2196       482062 :     TransactionIdAdvance(xmax);
    2197              :     Assert(TransactionIdIsNormal(xmax));
    2198              : 
    2199              :     /* initialize xmin calculation with xmax */
    2200       482062 :     xmin = xmax;
    2201              : 
    2202              :     /* take own xid into account, saves a check inside the loop */
    2203       482062 :     if (TransactionIdIsNormal(myxid) && NormalTransactionIdPrecedes(myxid, xmin))
    2204        32660 :         xmin = myxid;
    2205              : 
    2206       482062 :     snapshot->takenDuringRecovery = RecoveryInProgress();
    2207              : 
    2208       482062 :     if (!snapshot->takenDuringRecovery)
    2209              :     {
    2210       480774 :         int         numProcs = arrayP->numProcs;
    2211       480774 :         TransactionId *xip = snapshot->xip;
    2212       480774 :         int        *pgprocnos = arrayP->pgprocnos;
    2213       480774 :         XidCacheStatus *subxidStates = ProcGlobal->subxidStates;
    2214       480774 :         uint8      *allStatusFlags = ProcGlobal->statusFlags;
    2215              : 
    2216              :         /*
    2217              :          * First collect set of pgxactoff/xids that need to be included in the
    2218              :          * snapshot.
    2219              :          */
    2220      4338826 :         for (int pgxactoff = 0; pgxactoff < numProcs; pgxactoff++)
    2221              :         {
    2222              :             /* Fetch xid just once - see GetNewTransactionId */
    2223      3858052 :             TransactionId xid = UINT32_ACCESS_ONCE(other_xids[pgxactoff]);
    2224              :             uint8       statusFlags;
    2225              : 
    2226              :             Assert(allProcs[arrayP->pgprocnos[pgxactoff]].pgxactoff == pgxactoff);
    2227              : 
    2228              :             /*
    2229              :              * If the transaction has no XID assigned, we can skip it; it
    2230              :              * won't have sub-XIDs either.
    2231              :              */
    2232      3858052 :             if (likely(xid == InvalidTransactionId))
    2233      3107772 :                 continue;
    2234              : 
    2235              :             /*
    2236              :              * We don't include our own XIDs (if any) in the snapshot. It
    2237              :              * needs to be included in the xmin computation, but we did so
    2238              :              * outside the loop.
    2239              :              */
    2240       750280 :             if (pgxactoff == mypgxactoff)
    2241        63165 :                 continue;
    2242              : 
    2243              :             /*
    2244              :              * The only way we are able to get here with a non-normal xid is
    2245              :              * during bootstrap - with this backend using
    2246              :              * BootstrapTransactionId. But the above test should filter that
    2247              :              * out.
    2248              :              */
    2249              :             Assert(TransactionIdIsNormal(xid));
    2250              : 
    2251              :             /*
    2252              :              * If the XID is >= xmax, we can skip it; such transactions will
    2253              :              * be treated as running anyway (and any sub-XIDs will also be >=
    2254              :              * xmax).
    2255              :              */
    2256       687115 :             if (!NormalTransactionIdPrecedes(xid, xmax))
    2257       206511 :                 continue;
    2258              : 
    2259              :             /*
    2260              :              * Skip over backends doing logical decoding which manages xmin
    2261              :              * separately (check below) and ones running LAZY VACUUM.
    2262              :              */
    2263       480604 :             statusFlags = allStatusFlags[pgxactoff];
    2264       480604 :             if (statusFlags & (PROC_IN_LOGICAL_DECODING | PROC_IN_VACUUM))
    2265           76 :                 continue;
    2266              : 
    2267       480528 :             if (NormalTransactionIdPrecedes(xid, xmin))
    2268       292644 :                 xmin = xid;
    2269              : 
    2270              :             /* Add XID to snapshot. */
    2271       480528 :             xip[count++] = xid;
    2272              : 
    2273              :             /*
    2274              :              * Save subtransaction XIDs if possible (if we've already
    2275              :              * overflowed, there's no point).  Note that the subxact XIDs must
    2276              :              * be later than their parent, so no need to check them against
    2277              :              * xmin.  We could filter against xmax, but it seems better not to
    2278              :              * do that much work while holding the ProcArrayLock.
    2279              :              *
    2280              :              * The other backend can add more subxids concurrently, but cannot
    2281              :              * remove any.  Hence it's important to fetch nxids just once.
    2282              :              * Should be safe to use memcpy, though.  (We needn't worry about
    2283              :              * missing any xids added concurrently, because they must postdate
    2284              :              * xmax.)
    2285              :              *
    2286              :              * Again, our own XIDs are not included in the snapshot.
    2287              :              */
    2288       480528 :             if (!suboverflowed)
    2289              :             {
    2290              : 
    2291       480524 :                 if (subxidStates[pgxactoff].overflowed)
    2292          803 :                     suboverflowed = true;
    2293              :                 else
    2294              :                 {
    2295       479721 :                     int         nsubxids = subxidStates[pgxactoff].count;
    2296              : 
    2297       479721 :                     if (nsubxids > 0)
    2298              :                     {
    2299         6092 :                         int         pgprocno = pgprocnos[pgxactoff];
    2300         6092 :                         PGPROC     *proc = &allProcs[pgprocno];
    2301              : 
    2302         6092 :                         pg_read_barrier();  /* pairs with GetNewTransactionId */
    2303              : 
    2304         6092 :                         memcpy(snapshot->subxip + subcount,
    2305         6092 :                                proc->subxids.xids,
    2306              :                                nsubxids * sizeof(TransactionId));
    2307         6092 :                         subcount += nsubxids;
    2308              :                     }
    2309              :                 }
    2310              :             }
    2311              :         }
    2312              :     }
    2313              :     else
    2314              :     {
    2315              :         /*
    2316              :          * We're in hot standby, so get XIDs from KnownAssignedXids.
    2317              :          *
    2318              :          * We store all xids directly into subxip[]. Here's why:
    2319              :          *
    2320              :          * In recovery we don't know which xids are top-level and which are
    2321              :          * subxacts, a design choice that greatly simplifies xid processing.
    2322              :          *
    2323              :          * It seems like we would want to try to put xids into xip[] only, but
    2324              :          * that is fairly small. We would either need to make that bigger or
    2325              :          * to increase the rate at which we WAL-log xid assignment; neither is
    2326              :          * an appealing choice.
    2327              :          *
    2328              :          * We could try to store xids into xip[] first and then into subxip[]
    2329              :          * if there are too many xids. That only works if the snapshot doesn't
    2330              :          * overflow because we do not search subxip[] in that case. A simpler
    2331              :          * way is to just store all xids in the subxip array because this is
    2332              :          * by far the bigger array. We just leave the xip array empty.
    2333              :          *
    2334              :          * Either way we need to change the way XidInMVCCSnapshot() works
    2335              :          * depending upon when the snapshot was taken, or change normal
    2336              :          * snapshot processing so it matches.
    2337              :          *
    2338              :          * Note: It is possible for recovery to end before we finish taking
    2339              :          * the snapshot, and for newly assigned transaction ids to be added to
    2340              :          * the ProcArray.  xmax cannot change while we hold ProcArrayLock, so
    2341              :          * those newly added transaction ids would be filtered away, so we
    2342              :          * need not be concerned about them.
    2343              :          */
    2344         1288 :         subcount = KnownAssignedXidsGetAndSetXmin(snapshot->subxip, &xmin,
    2345              :                                                   xmax);
    2346              : 
    2347         1288 :         if (TransactionIdPrecedesOrEquals(xmin, procArray->lastOverflowedXid))
    2348            6 :             suboverflowed = true;
    2349              :     }
    2350              : 
    2351              : 
    2352              :     /*
    2353              :      * Fetch into local variable while ProcArrayLock is held - the
    2354              :      * LWLockRelease below is a barrier, ensuring this happens inside the
    2355              :      * lock.
    2356              :      */
    2357       482062 :     replication_slot_xmin = procArray->replication_slot_xmin;
    2358       482062 :     replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
    2359              : 
    2360       482062 :     if (!TransactionIdIsValid(MyProc->xmin))
    2361       262197 :         MyProc->xmin = TransactionXmin = xmin;
    2362              : 
    2363       482062 :     LWLockRelease(ProcArrayLock);
    2364              : 
    2365              :     /* maintain state for GlobalVis* */
    2366              :     {
    2367              :         TransactionId def_vis_xid;
    2368              :         TransactionId def_vis_xid_data;
    2369              :         FullTransactionId def_vis_fxid;
    2370              :         FullTransactionId def_vis_fxid_data;
    2371              :         FullTransactionId oldestfxid;
    2372              : 
    2373              :         /*
    2374              :          * Converting oldestXid is only safe when xid horizon cannot advance,
    2375              :          * i.e. holding locks. While we don't hold the lock anymore, all the
    2376              :          * necessary data has been gathered with lock held.
    2377              :          */
    2378       482062 :         oldestfxid = FullXidRelativeTo(latest_completed, oldestxid);
    2379              : 
    2380              :         /* Check whether there's a replication slot requiring an older xmin. */
    2381              :         def_vis_xid_data =
    2382       482062 :             TransactionIdOlder(xmin, replication_slot_xmin);
    2383              : 
    2384              :         /*
    2385              :          * Rows in non-shared, non-catalog tables possibly could be vacuumed
    2386              :          * if older than this xid.
    2387              :          */
    2388       482062 :         def_vis_xid = def_vis_xid_data;
    2389              : 
    2390              :         /*
    2391              :          * Check whether there's a replication slot requiring an older catalog
    2392              :          * xmin.
    2393              :          */
    2394              :         def_vis_xid =
    2395       482062 :             TransactionIdOlder(replication_slot_catalog_xmin, def_vis_xid);
    2396              : 
    2397       482062 :         def_vis_fxid = FullXidRelativeTo(latest_completed, def_vis_xid);
    2398       482062 :         def_vis_fxid_data = FullXidRelativeTo(latest_completed, def_vis_xid_data);
    2399              : 
    2400              :         /*
    2401              :          * Check if we can increase upper bound. As a previous
    2402              :          * GlobalVisUpdate() might have computed more aggressive values, don't
    2403              :          * overwrite them if so.
    2404              :          */
    2405              :         GlobalVisSharedRels.definitely_needed =
    2406       482062 :             FullTransactionIdNewer(def_vis_fxid,
    2407              :                                    GlobalVisSharedRels.definitely_needed);
    2408              :         GlobalVisCatalogRels.definitely_needed =
    2409       482062 :             FullTransactionIdNewer(def_vis_fxid,
    2410              :                                    GlobalVisCatalogRels.definitely_needed);
    2411              :         GlobalVisDataRels.definitely_needed =
    2412       482062 :             FullTransactionIdNewer(def_vis_fxid_data,
    2413              :                                    GlobalVisDataRels.definitely_needed);
    2414              :         /* See temp_oldest_nonremovable computation in ComputeXidHorizons() */
    2415       482062 :         if (TransactionIdIsNormal(myxid))
    2416              :             GlobalVisTempRels.definitely_needed =
    2417        63063 :                 FullXidRelativeTo(latest_completed, myxid);
    2418              :         else
    2419              :         {
    2420       418999 :             GlobalVisTempRels.definitely_needed = latest_completed;
    2421       418999 :             FullTransactionIdAdvance(&GlobalVisTempRels.definitely_needed);
    2422              :         }
    2423              : 
    2424              :         /*
    2425              :          * Check if we know that we can initialize or increase the lower
    2426              :          * bound. Currently the only cheap way to do so is to use
    2427              :          * TransamVariables->oldestXid as input.
    2428              :          *
    2429              :          * We should definitely be able to do better. We could e.g. put a
    2430              :          * global lower bound value into TransamVariables.
    2431              :          */
    2432              :         GlobalVisSharedRels.maybe_needed =
    2433       482062 :             FullTransactionIdNewer(GlobalVisSharedRels.maybe_needed,
    2434              :                                    oldestfxid);
    2435              :         GlobalVisCatalogRels.maybe_needed =
    2436       482062 :             FullTransactionIdNewer(GlobalVisCatalogRels.maybe_needed,
    2437              :                                    oldestfxid);
    2438              :         GlobalVisDataRels.maybe_needed =
    2439       482062 :             FullTransactionIdNewer(GlobalVisDataRels.maybe_needed,
    2440              :                                    oldestfxid);
    2441              :         /* accurate value known */
    2442       482062 :         GlobalVisTempRels.maybe_needed = GlobalVisTempRels.definitely_needed;
    2443              :     }
    2444              : 
    2445       482062 :     RecentXmin = xmin;
    2446              :     Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin));
    2447              : 
    2448       482062 :     snapshot->xmin = xmin;
    2449       482062 :     snapshot->xmax = xmax;
    2450       482062 :     snapshot->xcnt = count;
    2451       482062 :     snapshot->subxcnt = subcount;
    2452       482062 :     snapshot->suboverflowed = suboverflowed;
    2453       482062 :     snapshot->snapXactCompletionCount = curXactCompletionCount;
    2454              : 
    2455       482062 :     snapshot->curcid = GetCurrentCommandId(false);
    2456              : 
    2457              :     /*
    2458              :      * This is a new snapshot, so set both refcounts are zero, and mark it as
    2459              :      * not copied in persistent memory.
    2460              :      */
    2461       482062 :     snapshot->active_count = 0;
    2462       482062 :     snapshot->regd_count = 0;
    2463       482062 :     snapshot->copied = false;
    2464              : 
    2465       482062 :     return snapshot;
    2466              : }
    2467              : 
    2468              : /*
    2469              :  * ProcArrayInstallImportedXmin -- install imported xmin into MyProc->xmin
    2470              :  *
    2471              :  * This is called when installing a snapshot imported from another
    2472              :  * transaction.  To ensure that OldestXmin doesn't go backwards, we must
    2473              :  * check that the source transaction is still running, and we'd better do
    2474              :  * that atomically with installing the new xmin.
    2475              :  *
    2476              :  * Returns true if successful, false if source xact is no longer running.
    2477              :  */
    2478              : bool
    2479           16 : ProcArrayInstallImportedXmin(TransactionId xmin,
    2480              :                              VirtualTransactionId *sourcevxid)
    2481              : {
    2482           16 :     bool        result = false;
    2483           16 :     ProcArrayStruct *arrayP = procArray;
    2484              :     int         index;
    2485              : 
    2486              :     Assert(TransactionIdIsNormal(xmin));
    2487           16 :     if (!sourcevxid)
    2488            0 :         return false;
    2489              : 
    2490              :     /* Get lock so source xact can't end while we're doing this */
    2491           16 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    2492              : 
    2493              :     /*
    2494              :      * Find the PGPROC entry of the source transaction. (This could use
    2495              :      * GetPGProcByNumber(), unless it's a prepared xact.  But this isn't
    2496              :      * performance critical.)
    2497              :      */
    2498           16 :     for (index = 0; index < arrayP->numProcs; index++)
    2499              :     {
    2500           16 :         int         pgprocno = arrayP->pgprocnos[index];
    2501           16 :         PGPROC     *proc = &allProcs[pgprocno];
    2502           16 :         int         statusFlags = ProcGlobal->statusFlags[index];
    2503              :         TransactionId xid;
    2504              : 
    2505              :         /* Ignore procs running LAZY VACUUM */
    2506           16 :         if (statusFlags & PROC_IN_VACUUM)
    2507            0 :             continue;
    2508              : 
    2509              :         /* We are only interested in the specific virtual transaction. */
    2510           16 :         if (proc->vxid.procNumber != sourcevxid->procNumber)
    2511            0 :             continue;
    2512           16 :         if (proc->vxid.lxid != sourcevxid->localTransactionId)
    2513            0 :             continue;
    2514              : 
    2515              :         /*
    2516              :          * We check the transaction's database ID for paranoia's sake: if it's
    2517              :          * in another DB then its xmin does not cover us.  Caller should have
    2518              :          * detected this already, so we just treat any funny cases as
    2519              :          * "transaction not found".
    2520              :          */
    2521           16 :         if (proc->databaseId != MyDatabaseId)
    2522            0 :             continue;
    2523              : 
    2524              :         /*
    2525              :          * Likewise, let's just make real sure its xmin does cover us.
    2526              :          */
    2527           16 :         xid = UINT32_ACCESS_ONCE(proc->xmin);
    2528           16 :         if (!TransactionIdIsNormal(xid) ||
    2529           16 :             !TransactionIdPrecedesOrEquals(xid, xmin))
    2530            0 :             continue;
    2531              : 
    2532              :         /*
    2533              :          * We're good.  Install the new xmin.  As in GetSnapshotData, set
    2534              :          * TransactionXmin too.  (Note that because snapmgr.c called
    2535              :          * GetSnapshotData first, we'll be overwriting a valid xmin here, so
    2536              :          * we don't check that.)
    2537              :          */
    2538           16 :         MyProc->xmin = TransactionXmin = xmin;
    2539              : 
    2540           16 :         result = true;
    2541           16 :         break;
    2542              :     }
    2543              : 
    2544           16 :     LWLockRelease(ProcArrayLock);
    2545              : 
    2546           16 :     return result;
    2547              : }
    2548              : 
    2549              : /*
    2550              :  * ProcArrayInstallRestoredXmin -- install restored xmin into MyProc->xmin
    2551              :  *
    2552              :  * This is like ProcArrayInstallImportedXmin, but we have a pointer to the
    2553              :  * PGPROC of the transaction from which we imported the snapshot, rather than
    2554              :  * an XID.
    2555              :  *
    2556              :  * Note that this function also copies statusFlags from the source `proc` in
    2557              :  * order to avoid the case where MyProc's xmin needs to be skipped for
    2558              :  * computing xid horizon.
    2559              :  *
    2560              :  * Returns true if successful, false if source xact is no longer running.
    2561              :  */
    2562              : bool
    2563         2210 : ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc)
    2564              : {
    2565         2210 :     bool        result = false;
    2566              :     TransactionId xid;
    2567              : 
    2568              :     Assert(TransactionIdIsNormal(xmin));
    2569              :     Assert(proc != NULL);
    2570              : 
    2571              :     /*
    2572              :      * Get an exclusive lock so that we can copy statusFlags from source proc.
    2573              :      */
    2574         2210 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    2575              : 
    2576              :     /*
    2577              :      * Be certain that the referenced PGPROC has an advertised xmin which is
    2578              :      * no later than the one we're installing, so that the system-wide xmin
    2579              :      * can't go backwards.  Also, make sure it's running in the same database,
    2580              :      * so that the per-database xmin cannot go backwards.
    2581              :      */
    2582         2210 :     xid = UINT32_ACCESS_ONCE(proc->xmin);
    2583         2210 :     if (proc->databaseId == MyDatabaseId &&
    2584         2210 :         TransactionIdIsNormal(xid) &&
    2585         2210 :         TransactionIdPrecedesOrEquals(xid, xmin))
    2586              :     {
    2587              :         /*
    2588              :          * Install xmin and propagate the statusFlags that affect how the
    2589              :          * value is interpreted by vacuum.
    2590              :          */
    2591         2210 :         MyProc->xmin = TransactionXmin = xmin;
    2592         2210 :         MyProc->statusFlags = (MyProc->statusFlags & ~PROC_XMIN_FLAGS) |
    2593         2210 :             (proc->statusFlags & PROC_XMIN_FLAGS);
    2594         2210 :         ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
    2595              : 
    2596         2210 :         result = true;
    2597              :     }
    2598              : 
    2599         2210 :     LWLockRelease(ProcArrayLock);
    2600              : 
    2601         2210 :     return result;
    2602              : }
    2603              : 
    2604              : /*
    2605              :  * GetRunningTransactionData -- returns information about running transactions.
    2606              :  *
    2607              :  * Similar to GetSnapshotData but returns more information. We include
    2608              :  * all PGPROCs with an assigned TransactionId, even VACUUM processes and
    2609              :  * prepared transactions.
    2610              :  *
    2611              :  * We acquire XidGenLock and ProcArrayLock, but the caller is responsible for
    2612              :  * releasing them. Acquiring XidGenLock ensures that no new XIDs enter the proc
    2613              :  * array until the caller has WAL-logged this snapshot, and releases the
    2614              :  * lock. Acquiring ProcArrayLock ensures that no transactions commit until the
    2615              :  * lock is released.
    2616              :  *
    2617              :  * The returned data structure is statically allocated; caller should not
    2618              :  * modify it, and must not assume it is valid past the next call.
    2619              :  *
    2620              :  * This is never executed during recovery so there is no need to look at
    2621              :  * KnownAssignedXids.
    2622              :  *
    2623              :  * Dummy PGPROCs from prepared transaction are included, meaning that this
    2624              :  * may return entries with duplicated TransactionId values coming from
    2625              :  * transaction finishing to prepare.  Nothing is done about duplicated
    2626              :  * entries here to not hold on ProcArrayLock more than necessary.
    2627              :  *
    2628              :  * We don't worry about updating other counters, we want to keep this as
    2629              :  * simple as possible and leave GetSnapshotData() as the primary code for
    2630              :  * that bookkeeping.
    2631              :  *
    2632              :  * Note that if any transaction has overflowed its cached subtransactions
    2633              :  * then there is no real need include any subtransactions.
    2634              :  */
    2635              : RunningTransactions
    2636         1467 : GetRunningTransactionData(void)
    2637              : {
    2638              :     /* result workspace */
    2639              :     static RunningTransactionsData CurrentRunningXactsData;
    2640              : 
    2641         1467 :     ProcArrayStruct *arrayP = procArray;
    2642         1467 :     TransactionId *other_xids = ProcGlobal->xids;
    2643         1467 :     RunningTransactions CurrentRunningXacts = &CurrentRunningXactsData;
    2644              :     TransactionId latestCompletedXid;
    2645              :     TransactionId oldestRunningXid;
    2646              :     TransactionId oldestDatabaseRunningXid;
    2647              :     TransactionId *xids;
    2648              :     int         index;
    2649              :     int         count;
    2650              :     int         subcount;
    2651              :     bool        suboverflowed;
    2652              : 
    2653              :     Assert(!RecoveryInProgress());
    2654              : 
    2655              :     /*
    2656              :      * Allocating space for maxProcs xids is usually overkill; numProcs would
    2657              :      * be sufficient.  But it seems better to do the malloc while not holding
    2658              :      * the lock, so we can't look at numProcs.  Likewise, we allocate much
    2659              :      * more subxip storage than is probably needed.
    2660              :      *
    2661              :      * Should only be allocated in bgwriter, since only ever executed during
    2662              :      * checkpoints.
    2663              :      */
    2664         1467 :     if (CurrentRunningXacts->xids == NULL)
    2665              :     {
    2666              :         /*
    2667              :          * First call
    2668              :          */
    2669          588 :         CurrentRunningXacts->xids = (TransactionId *)
    2670          588 :             malloc(TOTAL_MAX_CACHED_SUBXIDS * sizeof(TransactionId));
    2671          588 :         if (CurrentRunningXacts->xids == NULL)
    2672            0 :             ereport(ERROR,
    2673              :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    2674              :                      errmsg("out of memory")));
    2675              :     }
    2676              : 
    2677         1467 :     xids = CurrentRunningXacts->xids;
    2678              : 
    2679         1467 :     count = subcount = 0;
    2680         1467 :     suboverflowed = false;
    2681              : 
    2682              :     /*
    2683              :      * Ensure that no xids enter or leave the procarray while we obtain
    2684              :      * snapshot.
    2685              :      */
    2686         1467 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    2687         1467 :     LWLockAcquire(XidGenLock, LW_SHARED);
    2688              : 
    2689         1467 :     latestCompletedXid =
    2690         1467 :         XidFromFullTransactionId(TransamVariables->latestCompletedXid);
    2691         1467 :     oldestDatabaseRunningXid = oldestRunningXid =
    2692         1467 :         XidFromFullTransactionId(TransamVariables->nextXid);
    2693              : 
    2694              :     /*
    2695              :      * Spin over procArray collecting all xids
    2696              :      */
    2697         7311 :     for (index = 0; index < arrayP->numProcs; index++)
    2698              :     {
    2699              :         TransactionId xid;
    2700              : 
    2701              :         /* Fetch xid just once - see GetNewTransactionId */
    2702         5844 :         xid = UINT32_ACCESS_ONCE(other_xids[index]);
    2703              : 
    2704              :         /*
    2705              :          * We don't need to store transactions that don't have a TransactionId
    2706              :          * yet because they will not show as running on a standby server.
    2707              :          */
    2708         5844 :         if (!TransactionIdIsValid(xid))
    2709         4990 :             continue;
    2710              : 
    2711              :         /*
    2712              :          * Be careful not to exclude any xids before calculating the values of
    2713              :          * oldestRunningXid and suboverflowed, since these are used to clean
    2714              :          * up transaction information held on standbys.
    2715              :          */
    2716          854 :         if (TransactionIdPrecedes(xid, oldestRunningXid))
    2717          576 :             oldestRunningXid = xid;
    2718              : 
    2719              :         /*
    2720              :          * Also, update the oldest running xid within the current database. As
    2721              :          * fetching pgprocno and PGPROC could cause cache misses, we do cheap
    2722              :          * TransactionId comparison first.
    2723              :          */
    2724          854 :         if (TransactionIdPrecedes(xid, oldestDatabaseRunningXid))
    2725              :         {
    2726          854 :             int         pgprocno = arrayP->pgprocnos[index];
    2727          854 :             PGPROC     *proc = &allProcs[pgprocno];
    2728              : 
    2729          854 :             if (proc->databaseId == MyDatabaseId)
    2730          211 :                 oldestDatabaseRunningXid = xid;
    2731              :         }
    2732              : 
    2733          854 :         if (ProcGlobal->subxidStates[index].overflowed)
    2734            2 :             suboverflowed = true;
    2735              : 
    2736              :         /*
    2737              :          * If we wished to exclude xids this would be the right place for it.
    2738              :          * Procs with the PROC_IN_VACUUM flag set don't usually assign xids,
    2739              :          * but they do during truncation at the end when they get the lock and
    2740              :          * truncate, so it is not much of a problem to include them if they
    2741              :          * are seen and it is cleaner to include them.
    2742              :          */
    2743              : 
    2744          854 :         xids[count++] = xid;
    2745              :     }
    2746              : 
    2747              :     /*
    2748              :      * Spin over procArray collecting all subxids, but only if there hasn't
    2749              :      * been a suboverflow.
    2750              :      */
    2751         1467 :     if (!suboverflowed)
    2752              :     {
    2753         1465 :         XidCacheStatus *other_subxidstates = ProcGlobal->subxidStates;
    2754              : 
    2755         7303 :         for (index = 0; index < arrayP->numProcs; index++)
    2756              :         {
    2757         5838 :             int         pgprocno = arrayP->pgprocnos[index];
    2758         5838 :             PGPROC     *proc = &allProcs[pgprocno];
    2759              :             int         nsubxids;
    2760              : 
    2761              :             /*
    2762              :              * Save subtransaction XIDs. Other backends can't add or remove
    2763              :              * entries while we're holding XidGenLock.
    2764              :              */
    2765         5838 :             nsubxids = other_subxidstates[index].count;
    2766         5838 :             if (nsubxids > 0)
    2767              :             {
    2768              :                 /* barrier not really required, as XidGenLock is held, but ... */
    2769           18 :                 pg_read_barrier();  /* pairs with GetNewTransactionId */
    2770              : 
    2771           18 :                 memcpy(&xids[count], proc->subxids.xids,
    2772              :                        nsubxids * sizeof(TransactionId));
    2773           18 :                 count += nsubxids;
    2774           18 :                 subcount += nsubxids;
    2775              : 
    2776              :                 /*
    2777              :                  * Top-level XID of a transaction is always less than any of
    2778              :                  * its subxids, so we don't need to check if any of the
    2779              :                  * subxids are smaller than oldestRunningXid
    2780              :                  */
    2781              :             }
    2782              :         }
    2783              :     }
    2784              : 
    2785              :     /*
    2786              :      * It's important *not* to include the limits set by slots here because
    2787              :      * snapbuild.c uses oldestRunningXid to manage its xmin horizon. If those
    2788              :      * were to be included here the initial value could never increase because
    2789              :      * of a circular dependency where slots only increase their limits when
    2790              :      * running xacts increases oldestRunningXid and running xacts only
    2791              :      * increases if slots do.
    2792              :      */
    2793              : 
    2794         1467 :     CurrentRunningXacts->xcnt = count - subcount;
    2795         1467 :     CurrentRunningXacts->subxcnt = subcount;
    2796         1467 :     CurrentRunningXacts->subxid_status = suboverflowed ? SUBXIDS_IN_SUBTRANS : SUBXIDS_IN_ARRAY;
    2797         1467 :     CurrentRunningXacts->nextXid = XidFromFullTransactionId(TransamVariables->nextXid);
    2798         1467 :     CurrentRunningXacts->oldestRunningXid = oldestRunningXid;
    2799         1467 :     CurrentRunningXacts->oldestDatabaseRunningXid = oldestDatabaseRunningXid;
    2800         1467 :     CurrentRunningXacts->latestCompletedXid = latestCompletedXid;
    2801              : 
    2802              :     Assert(TransactionIdIsValid(CurrentRunningXacts->nextXid));
    2803              :     Assert(TransactionIdIsValid(CurrentRunningXacts->oldestRunningXid));
    2804              :     Assert(TransactionIdIsNormal(CurrentRunningXacts->latestCompletedXid));
    2805              : 
    2806              :     /* We don't release the locks here, the caller is responsible for that */
    2807              : 
    2808         1467 :     return CurrentRunningXacts;
    2809              : }
    2810              : 
    2811              : /*
    2812              :  * GetOldestActiveTransactionId()
    2813              :  *
    2814              :  * Similar to GetSnapshotData but returns just oldestActiveXid. We include
    2815              :  * all PGPROCs with an assigned TransactionId, even VACUUM processes.
    2816              :  *
    2817              :  * If allDbs is true, we look at all databases, though there is no need to
    2818              :  * include WALSender since this has no effect on hot standby conflicts. If
    2819              :  * allDbs is false, skip processes attached to other databases.
    2820              :  *
    2821              :  * This is never executed during recovery so there is no need to look at
    2822              :  * KnownAssignedXids.
    2823              :  *
    2824              :  * We don't worry about updating other counters, we want to keep this as
    2825              :  * simple as possible and leave GetSnapshotData() as the primary code for
    2826              :  * that bookkeeping.
    2827              :  *
    2828              :  * inCommitOnly indicates getting the oldestActiveXid among the transactions
    2829              :  * in the commit critical section.
    2830              :  */
    2831              : TransactionId
    2832         5630 : GetOldestActiveTransactionId(bool inCommitOnly, bool allDbs)
    2833              : {
    2834         5630 :     ProcArrayStruct *arrayP = procArray;
    2835         5630 :     TransactionId *other_xids = ProcGlobal->xids;
    2836              :     TransactionId oldestRunningXid;
    2837              :     int         index;
    2838              : 
    2839              :     Assert(!RecoveryInProgress());
    2840              : 
    2841              :     /*
    2842              :      * Read nextXid, as the upper bound of what's still active.
    2843              :      *
    2844              :      * Reading a TransactionId is atomic, but we must grab the lock to make
    2845              :      * sure that all XIDs < nextXid are already present in the proc array (or
    2846              :      * have already completed), when we spin over it.
    2847              :      */
    2848         5630 :     LWLockAcquire(XidGenLock, LW_SHARED);
    2849         5630 :     oldestRunningXid = XidFromFullTransactionId(TransamVariables->nextXid);
    2850         5630 :     LWLockRelease(XidGenLock);
    2851              : 
    2852              :     /*
    2853              :      * Spin over procArray collecting all xids and subxids.
    2854              :      */
    2855         5630 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    2856        32786 :     for (index = 0; index < arrayP->numProcs; index++)
    2857              :     {
    2858              :         TransactionId xid;
    2859        27156 :         int         pgprocno = arrayP->pgprocnos[index];
    2860        27156 :         PGPROC     *proc = &allProcs[pgprocno];
    2861              : 
    2862              :         /* Fetch xid just once - see GetNewTransactionId */
    2863        27156 :         xid = UINT32_ACCESS_ONCE(other_xids[index]);
    2864              : 
    2865        27156 :         if (!TransactionIdIsNormal(xid))
    2866        21860 :             continue;
    2867              : 
    2868         5296 :         if (inCommitOnly &&
    2869         4459 :             (proc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0)
    2870         4115 :             continue;
    2871              : 
    2872         1181 :         if (!allDbs && proc->databaseId != MyDatabaseId)
    2873            0 :             continue;
    2874              : 
    2875         1181 :         if (TransactionIdPrecedes(xid, oldestRunningXid))
    2876          909 :             oldestRunningXid = xid;
    2877              : 
    2878              :         /*
    2879              :          * Top-level XID of a transaction is always less than any of its
    2880              :          * subxids, so we don't need to check if any of the subxids are
    2881              :          * smaller than oldestRunningXid
    2882              :          */
    2883              :     }
    2884         5630 :     LWLockRelease(ProcArrayLock);
    2885              : 
    2886         5630 :     return oldestRunningXid;
    2887              : }
    2888              : 
    2889              : /*
    2890              :  * GetOldestSafeDecodingTransactionId -- lowest xid not affected by vacuum
    2891              :  *
    2892              :  * Returns the oldest xid that we can guarantee not to have been affected by
    2893              :  * vacuum, i.e. no rows >= that xid have been vacuumed away unless the
    2894              :  * transaction aborted. Note that the value can (and most of the time will) be
    2895              :  * much more conservative than what really has been affected by vacuum, but we
    2896              :  * currently don't have better data available.
    2897              :  *
    2898              :  * This is useful to initialize the cutoff xid after which a new changeset
    2899              :  * extraction replication slot can start decoding changes.
    2900              :  *
    2901              :  * Must be called with ProcArrayLock held either shared or exclusively,
    2902              :  * although most callers will want to use exclusive mode since it is expected
    2903              :  * that the caller will immediately use the xid to peg the xmin horizon.
    2904              :  */
    2905              : TransactionId
    2906          723 : GetOldestSafeDecodingTransactionId(bool catalogOnly)
    2907              : {
    2908          723 :     ProcArrayStruct *arrayP = procArray;
    2909              :     TransactionId oldestSafeXid;
    2910              :     int         index;
    2911          723 :     bool        recovery_in_progress = RecoveryInProgress();
    2912              : 
    2913              :     Assert(LWLockHeldByMe(ProcArrayLock));
    2914              : 
    2915              :     /*
    2916              :      * Acquire XidGenLock, so no transactions can acquire an xid while we're
    2917              :      * running. If no transaction with xid were running concurrently a new xid
    2918              :      * could influence the RecentXmin et al.
    2919              :      *
    2920              :      * We initialize the computation to nextXid since that's guaranteed to be
    2921              :      * a safe, albeit pessimal, value.
    2922              :      */
    2923          723 :     LWLockAcquire(XidGenLock, LW_SHARED);
    2924          723 :     oldestSafeXid = XidFromFullTransactionId(TransamVariables->nextXid);
    2925              : 
    2926              :     /*
    2927              :      * If there's already a slot pegging the xmin horizon, we can start with
    2928              :      * that value, it's guaranteed to be safe since it's computed by this
    2929              :      * routine initially and has been enforced since.  We can always use the
    2930              :      * slot's general xmin horizon, but the catalog horizon is only usable
    2931              :      * when only catalog data is going to be looked at.
    2932              :      */
    2933          953 :     if (TransactionIdIsValid(procArray->replication_slot_xmin) &&
    2934          230 :         TransactionIdPrecedes(procArray->replication_slot_xmin,
    2935              :                               oldestSafeXid))
    2936           10 :         oldestSafeXid = procArray->replication_slot_xmin;
    2937              : 
    2938          723 :     if (catalogOnly &&
    2939          366 :         TransactionIdIsValid(procArray->replication_slot_catalog_xmin) &&
    2940           77 :         TransactionIdPrecedes(procArray->replication_slot_catalog_xmin,
    2941              :                               oldestSafeXid))
    2942           30 :         oldestSafeXid = procArray->replication_slot_catalog_xmin;
    2943              : 
    2944              :     /*
    2945              :      * If we're not in recovery, we walk over the procarray and collect the
    2946              :      * lowest xid. Since we're called with ProcArrayLock held and have
    2947              :      * acquired XidGenLock, no entries can vanish concurrently, since
    2948              :      * ProcGlobal->xids[i] is only set with XidGenLock held and only cleared
    2949              :      * with ProcArrayLock held.
    2950              :      *
    2951              :      * In recovery we can't lower the safe value besides what we've computed
    2952              :      * above, so we'll have to wait a bit longer there. We unfortunately can
    2953              :      * *not* use KnownAssignedXidsGetOldestXmin() since the KnownAssignedXids
    2954              :      * machinery can miss values and return an older value than is safe.
    2955              :      */
    2956          723 :     if (!recovery_in_progress)
    2957              :     {
    2958          690 :         TransactionId *other_xids = ProcGlobal->xids;
    2959              : 
    2960              :         /*
    2961              :          * Spin over procArray collecting min(ProcGlobal->xids[i])
    2962              :          */
    2963         3513 :         for (index = 0; index < arrayP->numProcs; index++)
    2964              :         {
    2965              :             TransactionId xid;
    2966              : 
    2967              :             /* Fetch xid just once - see GetNewTransactionId */
    2968         2823 :             xid = UINT32_ACCESS_ONCE(other_xids[index]);
    2969              : 
    2970         2823 :             if (!TransactionIdIsNormal(xid))
    2971         2816 :                 continue;
    2972              : 
    2973            7 :             if (TransactionIdPrecedes(xid, oldestSafeXid))
    2974            6 :                 oldestSafeXid = xid;
    2975              :         }
    2976              :     }
    2977              : 
    2978          723 :     LWLockRelease(XidGenLock);
    2979              : 
    2980          723 :     return oldestSafeXid;
    2981              : }
    2982              : 
    2983              : /*
    2984              :  * GetVirtualXIDsDelayingChkpt -- Get the VXIDs of transactions that are
    2985              :  * delaying checkpoint because they have critical actions in progress.
    2986              :  *
    2987              :  * Constructs an array of VXIDs of transactions that are currently in commit
    2988              :  * critical sections, as shown by having specified delayChkptFlags bits set
    2989              :  * in their PGPROC.
    2990              :  *
    2991              :  * Returns a palloc'd array that should be freed by the caller.
    2992              :  * *nvxids is the number of valid entries.
    2993              :  *
    2994              :  * Note that because backends set or clear delayChkptFlags without holding any
    2995              :  * lock, the result is somewhat indeterminate, but we don't really care.  Even
    2996              :  * in a multiprocessor with delayed writes to shared memory, it should be
    2997              :  * certain that setting of delayChkptFlags will propagate to shared memory
    2998              :  * when the backend takes a lock, so we cannot fail to see a virtual xact as
    2999              :  * delayChkptFlags if it's already inserted its commit record.  Whether it
    3000              :  * takes a little while for clearing of delayChkptFlags to propagate is
    3001              :  * unimportant for correctness.
    3002              :  */
    3003              : VirtualTransactionId *
    3004         3260 : GetVirtualXIDsDelayingChkpt(int *nvxids, int type)
    3005              : {
    3006              :     VirtualTransactionId *vxids;
    3007         3260 :     ProcArrayStruct *arrayP = procArray;
    3008         3260 :     int         count = 0;
    3009              :     int         index;
    3010              : 
    3011              :     Assert(type != 0);
    3012              : 
    3013              :     /* allocate what's certainly enough result space */
    3014         3260 :     vxids = palloc_array(VirtualTransactionId, arrayP->maxProcs);
    3015              : 
    3016         3260 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3017              : 
    3018        10885 :     for (index = 0; index < arrayP->numProcs; index++)
    3019              :     {
    3020         7625 :         int         pgprocno = arrayP->pgprocnos[index];
    3021         7625 :         PGPROC     *proc = &allProcs[pgprocno];
    3022              : 
    3023         7625 :         if ((proc->delayChkptFlags & type) != 0)
    3024              :         {
    3025              :             VirtualTransactionId vxid;
    3026              : 
    3027           35 :             GET_VXID_FROM_PGPROC(vxid, *proc);
    3028           35 :             if (VirtualTransactionIdIsValid(vxid))
    3029           35 :                 vxids[count++] = vxid;
    3030              :         }
    3031              :     }
    3032              : 
    3033         3260 :     LWLockRelease(ProcArrayLock);
    3034              : 
    3035         3260 :     *nvxids = count;
    3036         3260 :     return vxids;
    3037              : }
    3038              : 
    3039              : /*
    3040              :  * HaveVirtualXIDsDelayingChkpt -- Are any of the specified VXIDs delaying?
    3041              :  *
    3042              :  * This is used with the results of GetVirtualXIDsDelayingChkpt to see if any
    3043              :  * of the specified VXIDs are still in critical sections of code.
    3044              :  *
    3045              :  * Note: this is O(N^2) in the number of vxacts that are/were delaying, but
    3046              :  * those numbers should be small enough for it not to be a problem.
    3047              :  */
    3048              : bool
    3049           31 : HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids, int type)
    3050              : {
    3051           31 :     bool        result = false;
    3052           31 :     ProcArrayStruct *arrayP = procArray;
    3053              :     int         index;
    3054              : 
    3055              :     Assert(type != 0);
    3056              : 
    3057           31 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3058              : 
    3059          349 :     for (index = 0; index < arrayP->numProcs; index++)
    3060              :     {
    3061          318 :         int         pgprocno = arrayP->pgprocnos[index];
    3062          318 :         PGPROC     *proc = &allProcs[pgprocno];
    3063              :         VirtualTransactionId vxid;
    3064              : 
    3065          318 :         GET_VXID_FROM_PGPROC(vxid, *proc);
    3066              : 
    3067          318 :         if ((proc->delayChkptFlags & type) != 0 &&
    3068            7 :             VirtualTransactionIdIsValid(vxid))
    3069              :         {
    3070              :             int         i;
    3071              : 
    3072           17 :             for (i = 0; i < nvxids; i++)
    3073              :             {
    3074           10 :                 if (VirtualTransactionIdEquals(vxid, vxids[i]))
    3075              :                 {
    3076            0 :                     result = true;
    3077            0 :                     break;
    3078              :                 }
    3079              :             }
    3080            7 :             if (result)
    3081            0 :                 break;
    3082              :         }
    3083              :     }
    3084              : 
    3085           31 :     LWLockRelease(ProcArrayLock);
    3086              : 
    3087           31 :     return result;
    3088              : }
    3089              : 
    3090              : /*
    3091              :  * ProcNumberGetProc -- get a backend's PGPROC given its proc number
    3092              :  *
    3093              :  * The result may be out of date arbitrarily quickly, so the caller
    3094              :  * must be careful about how this information is used.  NULL is
    3095              :  * returned if the backend is not active.
    3096              :  */
    3097              : PGPROC *
    3098          649 : ProcNumberGetProc(ProcNumber procNumber)
    3099              : {
    3100              :     PGPROC     *result;
    3101              : 
    3102          649 :     if (procNumber < 0 || procNumber >= ProcGlobal->allProcCount)
    3103            1 :         return NULL;
    3104          648 :     result = GetPGProcByNumber(procNumber);
    3105              : 
    3106          648 :     if (result->pid == 0)
    3107            3 :         return NULL;
    3108              : 
    3109          645 :     return result;
    3110              : }
    3111              : 
    3112              : /*
    3113              :  * ProcNumberGetTransactionIds -- get a backend's transaction status
    3114              :  *
    3115              :  * Get the xid, xmin, nsubxid and overflow status of the backend.  The
    3116              :  * result may be out of date arbitrarily quickly, so the caller must be
    3117              :  * careful about how this information is used.
    3118              :  */
    3119              : void
    3120        10342 : ProcNumberGetTransactionIds(ProcNumber procNumber, TransactionId *xid,
    3121              :                             TransactionId *xmin, int *nsubxid, bool *overflowed)
    3122              : {
    3123              :     PGPROC     *proc;
    3124              : 
    3125        10342 :     *xid = InvalidTransactionId;
    3126        10342 :     *xmin = InvalidTransactionId;
    3127        10342 :     *nsubxid = 0;
    3128        10342 :     *overflowed = false;
    3129              : 
    3130        10342 :     if (procNumber < 0 || procNumber >= ProcGlobal->allProcCount)
    3131            0 :         return;
    3132        10342 :     proc = GetPGProcByNumber(procNumber);
    3133              : 
    3134              :     /* Need to lock out additions/removals of backends */
    3135        10342 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3136              : 
    3137        10342 :     if (proc->pid != 0)
    3138              :     {
    3139        10342 :         *xid = proc->xid;
    3140        10342 :         *xmin = proc->xmin;
    3141        10342 :         *nsubxid = proc->subxidStatus.count;
    3142        10342 :         *overflowed = proc->subxidStatus.overflowed;
    3143              :     }
    3144              : 
    3145        10342 :     LWLockRelease(ProcArrayLock);
    3146              : }
    3147              : 
    3148              : /*
    3149              :  * BackendPidGetProc -- get a backend's PGPROC given its PID
    3150              :  *
    3151              :  * Returns NULL if not found.  Note that it is up to the caller to be
    3152              :  * sure that the question remains meaningful for long enough for the
    3153              :  * answer to be used ...
    3154              :  */
    3155              : PGPROC *
    3156        10973 : BackendPidGetProc(int pid)
    3157              : {
    3158              :     PGPROC     *result;
    3159              : 
    3160        10973 :     if (pid == 0)               /* never match dummy PGPROCs */
    3161            4 :         return NULL;
    3162              : 
    3163        10969 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3164              : 
    3165        10969 :     result = BackendPidGetProcWithLock(pid);
    3166              : 
    3167        10969 :     LWLockRelease(ProcArrayLock);
    3168              : 
    3169        10969 :     return result;
    3170              : }
    3171              : 
    3172              : /*
    3173              :  * BackendPidGetProcWithLock -- get a backend's PGPROC given its PID
    3174              :  *
    3175              :  * Same as above, except caller must be holding ProcArrayLock.  The found
    3176              :  * entry, if any, can be assumed to be valid as long as the lock remains held.
    3177              :  */
    3178              : PGPROC *
    3179        12541 : BackendPidGetProcWithLock(int pid)
    3180              : {
    3181        12541 :     PGPROC     *result = NULL;
    3182        12541 :     ProcArrayStruct *arrayP = procArray;
    3183              :     int         index;
    3184              : 
    3185        12541 :     if (pid == 0)               /* never match dummy PGPROCs */
    3186            0 :         return NULL;
    3187              : 
    3188        50233 :     for (index = 0; index < arrayP->numProcs; index++)
    3189              :     {
    3190        44776 :         PGPROC     *proc = &allProcs[arrayP->pgprocnos[index]];
    3191              : 
    3192        44776 :         if (proc->pid == pid)
    3193              :         {
    3194         7084 :             result = proc;
    3195         7084 :             break;
    3196              :         }
    3197              :     }
    3198              : 
    3199        12541 :     return result;
    3200              : }
    3201              : 
    3202              : /*
    3203              :  * BackendXidGetPid -- get a backend's pid given its XID
    3204              :  *
    3205              :  * Returns 0 if not found or it's a prepared transaction.  Note that
    3206              :  * it is up to the caller to be sure that the question remains
    3207              :  * meaningful for long enough for the answer to be used ...
    3208              :  *
    3209              :  * Only main transaction Ids are considered.  This function is mainly
    3210              :  * useful for determining what backend owns a lock.
    3211              :  *
    3212              :  * Beware that not every xact has an XID assigned.  However, as long as you
    3213              :  * only call this using an XID found on disk, you're safe.
    3214              :  */
    3215              : int
    3216           30 : BackendXidGetPid(TransactionId xid)
    3217              : {
    3218           30 :     int         result = 0;
    3219           30 :     ProcArrayStruct *arrayP = procArray;
    3220           30 :     TransactionId *other_xids = ProcGlobal->xids;
    3221              :     int         index;
    3222              : 
    3223           30 :     if (xid == InvalidTransactionId)    /* never match invalid xid */
    3224            0 :         return 0;
    3225              : 
    3226           30 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3227              : 
    3228           92 :     for (index = 0; index < arrayP->numProcs; index++)
    3229              :     {
    3230           84 :         if (other_xids[index] == xid)
    3231              :         {
    3232           22 :             int         pgprocno = arrayP->pgprocnos[index];
    3233           22 :             PGPROC     *proc = &allProcs[pgprocno];
    3234              : 
    3235           22 :             result = proc->pid;
    3236           22 :             break;
    3237              :         }
    3238              :     }
    3239              : 
    3240           30 :     LWLockRelease(ProcArrayLock);
    3241              : 
    3242           30 :     return result;
    3243              : }
    3244              : 
    3245              : /*
    3246              :  * IsBackendPid -- is a given pid a running backend
    3247              :  *
    3248              :  * This is not called by the backend, but is called by external modules.
    3249              :  */
    3250              : bool
    3251            2 : IsBackendPid(int pid)
    3252              : {
    3253            2 :     return (BackendPidGetProc(pid) != NULL);
    3254              : }
    3255              : 
    3256              : 
    3257              : /*
    3258              :  * GetCurrentVirtualXIDs -- returns an array of currently active VXIDs.
    3259              :  *
    3260              :  * The array is palloc'd. The number of valid entries is returned into *nvxids.
    3261              :  *
    3262              :  * The arguments allow filtering the set of VXIDs returned.  Our own process
    3263              :  * is always skipped.  In addition:
    3264              :  *  If limitXmin is not InvalidTransactionId, skip processes with
    3265              :  *      xmin > limitXmin.
    3266              :  *  If excludeXmin0 is true, skip processes with xmin = 0.
    3267              :  *  If allDbs is false, skip processes attached to other databases.
    3268              :  *  If excludeVacuum isn't zero, skip processes for which
    3269              :  *      (statusFlags & excludeVacuum) is not zero.
    3270              :  *
    3271              :  * Note: the purpose of the limitXmin and excludeXmin0 parameters is to
    3272              :  * allow skipping backends whose oldest live snapshot is no older than
    3273              :  * some snapshot we have.  Since we examine the procarray with only shared
    3274              :  * lock, there are race conditions: a backend could set its xmin just after
    3275              :  * we look.  Indeed, on multiprocessors with weak memory ordering, the
    3276              :  * other backend could have set its xmin *before* we look.  We know however
    3277              :  * that such a backend must have held shared ProcArrayLock overlapping our
    3278              :  * own hold of ProcArrayLock, else we would see its xmin update.  Therefore,
    3279              :  * any snapshot the other backend is taking concurrently with our scan cannot
    3280              :  * consider any transactions as still running that we think are committed
    3281              :  * (since backends must hold ProcArrayLock exclusive to commit).
    3282              :  */
    3283              : VirtualTransactionId *
    3284          476 : GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0,
    3285              :                       bool allDbs, int excludeVacuum,
    3286              :                       int *nvxids)
    3287              : {
    3288              :     VirtualTransactionId *vxids;
    3289          476 :     ProcArrayStruct *arrayP = procArray;
    3290          476 :     int         count = 0;
    3291              :     int         index;
    3292              : 
    3293              :     /* allocate what's certainly enough result space */
    3294          476 :     vxids = palloc_array(VirtualTransactionId, arrayP->maxProcs);
    3295              : 
    3296          476 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3297              : 
    3298         2856 :     for (index = 0; index < arrayP->numProcs; index++)
    3299              :     {
    3300         2380 :         int         pgprocno = arrayP->pgprocnos[index];
    3301         2380 :         PGPROC     *proc = &allProcs[pgprocno];
    3302         2380 :         uint8       statusFlags = ProcGlobal->statusFlags[index];
    3303              : 
    3304         2380 :         if (proc == MyProc)
    3305          476 :             continue;
    3306              : 
    3307         1904 :         if (excludeVacuum & statusFlags)
    3308           13 :             continue;
    3309              : 
    3310         1891 :         if (allDbs || proc->databaseId == MyDatabaseId)
    3311              :         {
    3312              :             /* Fetch xmin just once - might change on us */
    3313          867 :             TransactionId pxmin = UINT32_ACCESS_ONCE(proc->xmin);
    3314              : 
    3315          867 :             if (excludeXmin0 && !TransactionIdIsValid(pxmin))
    3316          567 :                 continue;
    3317              : 
    3318              :             /*
    3319              :              * InvalidTransactionId precedes all other XIDs, so a proc that
    3320              :              * hasn't set xmin yet will not be rejected by this test.
    3321              :              */
    3322          600 :             if (!TransactionIdIsValid(limitXmin) ||
    3323          300 :                 TransactionIdPrecedesOrEquals(pxmin, limitXmin))
    3324              :             {
    3325              :                 VirtualTransactionId vxid;
    3326              : 
    3327          287 :                 GET_VXID_FROM_PGPROC(vxid, *proc);
    3328          287 :                 if (VirtualTransactionIdIsValid(vxid))
    3329          287 :                     vxids[count++] = vxid;
    3330              :             }
    3331              :         }
    3332              :     }
    3333              : 
    3334          476 :     LWLockRelease(ProcArrayLock);
    3335              : 
    3336          476 :     *nvxids = count;
    3337          476 :     return vxids;
    3338              : }
    3339              : 
    3340              : /*
    3341              :  * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs.
    3342              :  *
    3343              :  * Usage is limited to conflict resolution during recovery on standby servers.
    3344              :  * limitXmin is supplied as either a cutoff with snapshotConflictHorizon
    3345              :  * semantics, or InvalidTransactionId in cases where caller cannot accurately
    3346              :  * determine a safe snapshotConflictHorizon value.
    3347              :  *
    3348              :  * If limitXmin is InvalidTransactionId then we want to kill everybody,
    3349              :  * so we're not worried if they have a snapshot or not, nor does it really
    3350              :  * matter what type of lock we hold.  Caller must avoid calling here with
    3351              :  * snapshotConflictHorizon style cutoffs that were set to InvalidTransactionId
    3352              :  * during original execution, since that actually indicates that there is
    3353              :  * definitely no need for a recovery conflict (the snapshotConflictHorizon
    3354              :  * convention for InvalidTransactionId values is the opposite of our own!).
    3355              :  *
    3356              :  * All callers that are checking xmins always now supply a valid and useful
    3357              :  * value for limitXmin. The limitXmin is always lower than the lowest
    3358              :  * numbered KnownAssignedXid that is not already a FATAL error. This is
    3359              :  * because we only care about cleanup records that are cleaning up tuple
    3360              :  * versions from committed transactions. In that case they will only occur
    3361              :  * at the point where the record is less than the lowest running xid. That
    3362              :  * allows us to say that if any backend takes a snapshot concurrently with
    3363              :  * us then the conflict assessment made here would never include the snapshot
    3364              :  * that is being derived. So we take LW_SHARED on the ProcArray and allow
    3365              :  * concurrent snapshots when limitXmin is valid. We might think about adding
    3366              :  *   Assert(limitXmin < lowest(KnownAssignedXids))
    3367              :  * but that would not be true in the case of FATAL errors lagging in array,
    3368              :  * but we already know those are bogus anyway, so we skip that test.
    3369              :  *
    3370              :  * If dbOid is valid we skip backends attached to other databases.
    3371              :  *
    3372              :  * Be careful to *not* pfree the result from this function. We reuse
    3373              :  * this array sufficiently often that we use malloc for the result.
    3374              :  */
    3375              : VirtualTransactionId *
    3376        15350 : GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid)
    3377              : {
    3378              :     static VirtualTransactionId *vxids;
    3379        15350 :     ProcArrayStruct *arrayP = procArray;
    3380        15350 :     int         count = 0;
    3381              :     int         index;
    3382              : 
    3383              :     /*
    3384              :      * If first time through, get workspace to remember main XIDs in. We
    3385              :      * malloc it permanently to avoid repeated palloc/pfree overhead. Allow
    3386              :      * result space, remembering room for a terminator.
    3387              :      */
    3388        15350 :     if (vxids == NULL)
    3389              :     {
    3390           19 :         vxids = (VirtualTransactionId *)
    3391           19 :             malloc(sizeof(VirtualTransactionId) * (arrayP->maxProcs + 1));
    3392           19 :         if (vxids == NULL)
    3393            0 :             ereport(ERROR,
    3394              :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    3395              :                      errmsg("out of memory")));
    3396              :     }
    3397              : 
    3398        15350 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3399              : 
    3400        15499 :     for (index = 0; index < arrayP->numProcs; index++)
    3401              :     {
    3402          149 :         int         pgprocno = arrayP->pgprocnos[index];
    3403          149 :         PGPROC     *proc = &allProcs[pgprocno];
    3404              : 
    3405              :         /* Exclude prepared transactions */
    3406          149 :         if (proc->pid == 0)
    3407            0 :             continue;
    3408              : 
    3409          149 :         if (!OidIsValid(dbOid) ||
    3410          143 :             proc->databaseId == dbOid)
    3411              :         {
    3412              :             /* Fetch xmin just once - can't change on us, but good coding */
    3413           18 :             TransactionId pxmin = UINT32_ACCESS_ONCE(proc->xmin);
    3414              : 
    3415              :             /*
    3416              :              * We ignore an invalid pxmin because this means that backend has
    3417              :              * no snapshot currently. We hold a Share lock to avoid contention
    3418              :              * with users taking snapshots.  That is not a problem because the
    3419              :              * current xmin is always at least one higher than the latest
    3420              :              * removed xid, so any new snapshot would never conflict with the
    3421              :              * test here.
    3422              :              */
    3423           18 :             if (!TransactionIdIsValid(limitXmin) ||
    3424            3 :                 (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin)))
    3425              :             {
    3426              :                 VirtualTransactionId vxid;
    3427              : 
    3428            2 :                 GET_VXID_FROM_PGPROC(vxid, *proc);
    3429            2 :                 if (VirtualTransactionIdIsValid(vxid))
    3430            2 :                     vxids[count++] = vxid;
    3431              :             }
    3432              :         }
    3433              :     }
    3434              : 
    3435        15350 :     LWLockRelease(ProcArrayLock);
    3436              : 
    3437              :     /* add the terminator */
    3438        15350 :     vxids[count].procNumber = INVALID_PROC_NUMBER;
    3439        15350 :     vxids[count].localTransactionId = InvalidLocalTransactionId;
    3440              : 
    3441        15350 :     return vxids;
    3442              : }
    3443              : 
    3444              : /*
    3445              :  * SignalRecoveryConflict -- signal that a process is blocking recovery
    3446              :  *
    3447              :  * The 'pid' is redundant with 'proc', but it acts as a cross-check to
    3448              :  * detect process had exited and the PGPROC entry was reused for a different
    3449              :  * process.
    3450              :  *
    3451              :  * Returns true if the process was signaled, or false if not found.
    3452              :  */
    3453              : bool
    3454            5 : SignalRecoveryConflict(PGPROC *proc, pid_t pid, RecoveryConflictReason reason)
    3455              : {
    3456            5 :     bool        found = false;
    3457              : 
    3458            5 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3459              : 
    3460              :     /*
    3461              :      * Kill the pid if it's still here. If not, that's what we wanted so
    3462              :      * ignore any errors.
    3463              :      */
    3464            5 :     if (proc->pid == pid)
    3465              :     {
    3466            5 :         (void) pg_atomic_fetch_or_u32(&proc->pendingRecoveryConflicts, (1 << reason));
    3467              : 
    3468              :         /* wake up the process */
    3469            5 :         (void) SendProcSignal(pid, PROCSIG_RECOVERY_CONFLICT, GetNumberFromPGProc(proc));
    3470            5 :         found = true;
    3471              :     }
    3472              : 
    3473            5 :     LWLockRelease(ProcArrayLock);
    3474              : 
    3475            5 :     return found;
    3476              : }
    3477              : 
    3478              : /*
    3479              :  * SignalRecoveryConflictWithVirtualXID -- signal that a VXID is blocking recovery
    3480              :  *
    3481              :  * Like SignalRecoveryConflict, but the target is identified by VXID
    3482              :  */
    3483              : bool
    3484            5 : SignalRecoveryConflictWithVirtualXID(VirtualTransactionId vxid, RecoveryConflictReason reason)
    3485              : {
    3486            5 :     ProcArrayStruct *arrayP = procArray;
    3487              :     int         index;
    3488            5 :     pid_t       pid = 0;
    3489              : 
    3490            5 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3491              : 
    3492            5 :     for (index = 0; index < arrayP->numProcs; index++)
    3493              :     {
    3494            5 :         int         pgprocno = arrayP->pgprocnos[index];
    3495            5 :         PGPROC     *proc = &allProcs[pgprocno];
    3496              :         VirtualTransactionId procvxid;
    3497              : 
    3498            5 :         GET_VXID_FROM_PGPROC(procvxid, *proc);
    3499              : 
    3500            5 :         if (procvxid.procNumber == vxid.procNumber &&
    3501            5 :             procvxid.localTransactionId == vxid.localTransactionId)
    3502              :         {
    3503            5 :             pid = proc->pid;
    3504            5 :             if (pid != 0)
    3505              :             {
    3506            5 :                 (void) pg_atomic_fetch_or_u32(&proc->pendingRecoveryConflicts, (1 << reason));
    3507              : 
    3508              :                 /*
    3509              :                  * Kill the pid if it's still here. If not, that's what we
    3510              :                  * wanted so ignore any errors.
    3511              :                  */
    3512            5 :                 (void) SendProcSignal(pid, PROCSIG_RECOVERY_CONFLICT, vxid.procNumber);
    3513              :             }
    3514            5 :             break;
    3515              :         }
    3516              :     }
    3517              : 
    3518            5 :     LWLockRelease(ProcArrayLock);
    3519              : 
    3520            5 :     return pid != 0;
    3521              : }
    3522              : 
    3523              : /*
    3524              :  * SignalRecoveryConflictWithDatabase -- signal backends using specified database
    3525              :  *
    3526              :  * Like SignalRecoveryConflict, but signals all backends using the database.
    3527              :  */
    3528              : void
    3529            9 : SignalRecoveryConflictWithDatabase(Oid databaseid, RecoveryConflictReason reason)
    3530              : {
    3531            9 :     ProcArrayStruct *arrayP = procArray;
    3532              :     int         index;
    3533              : 
    3534              :     /* tell all backends to die */
    3535            9 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    3536              : 
    3537           18 :     for (index = 0; index < arrayP->numProcs; index++)
    3538              :     {
    3539            9 :         int         pgprocno = arrayP->pgprocnos[index];
    3540            9 :         PGPROC     *proc = &allProcs[pgprocno];
    3541              : 
    3542            9 :         if (databaseid == InvalidOid || proc->databaseId == databaseid)
    3543              :         {
    3544              :             VirtualTransactionId procvxid;
    3545              :             pid_t       pid;
    3546              : 
    3547            9 :             GET_VXID_FROM_PGPROC(procvxid, *proc);
    3548              : 
    3549            9 :             pid = proc->pid;
    3550            9 :             if (pid != 0)
    3551              :             {
    3552            9 :                 (void) pg_atomic_fetch_or_u32(&proc->pendingRecoveryConflicts, (1 << reason));
    3553              : 
    3554              :                 /*
    3555              :                  * Kill the pid if it's still here. If not, that's what we
    3556              :                  * wanted so ignore any errors.
    3557              :                  */
    3558            9 :                 (void) SendProcSignal(pid, PROCSIG_RECOVERY_CONFLICT, procvxid.procNumber);
    3559              :             }
    3560              :         }
    3561              :     }
    3562              : 
    3563            9 :     LWLockRelease(ProcArrayLock);
    3564            9 : }
    3565              : 
    3566              : /*
    3567              :  * MinimumActiveBackends --- count backends (other than myself) that are
    3568              :  *      in active transactions.  Return true if the count exceeds the
    3569              :  *      minimum threshold passed.  This is used as a heuristic to decide if
    3570              :  *      a pre-XLOG-flush delay is worthwhile during commit.
    3571              :  *
    3572              :  * Do not count backends that are blocked waiting for locks, since they are
    3573              :  * not going to get to run until someone else commits.
    3574              :  */
    3575              : bool
    3576            0 : MinimumActiveBackends(int min)
    3577              : {
    3578            0 :     ProcArrayStruct *arrayP = procArray;
    3579            0 :     int         count = 0;
    3580              :     int         index;
    3581              : 
    3582              :     /* Quick short-circuit if no minimum is specified */
    3583            0 :     if (min == 0)
    3584            0 :         return true;
    3585              : 
    3586              :     /*
    3587              :      * Note: for speed, we don't acquire ProcArrayLock.  This is a little bit
    3588              :      * bogus, but since we are only testing fields for zero or nonzero, it
    3589              :      * should be OK.  The result is only used for heuristic purposes anyway...
    3590              :      */
    3591            0 :     for (index = 0; index < arrayP->numProcs; index++)
    3592              :     {
    3593            0 :         int         pgprocno = arrayP->pgprocnos[index];
    3594            0 :         PGPROC     *proc = &allProcs[pgprocno];
    3595              : 
    3596              :         /*
    3597              :          * Since we're not holding a lock, need to be prepared to deal with
    3598              :          * garbage, as someone could have incremented numProcs but not yet
    3599              :          * filled the structure.
    3600              :          *
    3601              :          * If someone just decremented numProcs, 'proc' could also point to a
    3602              :          * PGPROC entry that's no longer in the array. It still points to a
    3603              :          * PGPROC struct, though, because freed PGPROC entries just go to the
    3604              :          * free list and are recycled. Its contents are nonsense in that case,
    3605              :          * but that's acceptable for this function.
    3606              :          */
    3607            0 :         if (pgprocno == -1)
    3608            0 :             continue;           /* do not count deleted entries */
    3609            0 :         if (proc == MyProc)
    3610            0 :             continue;           /* do not count myself */
    3611            0 :         if (proc->xid == InvalidTransactionId)
    3612            0 :             continue;           /* do not count if no XID assigned */
    3613            0 :         if (proc->pid == 0)
    3614            0 :             continue;           /* do not count prepared xacts */
    3615            0 :         if (proc->waitLock != NULL)
    3616            0 :             continue;           /* do not count if blocked on a lock */
    3617            0 :         count++;
    3618            0 :         if (count >= min)
    3619            0 :             break;
    3620              :     }
    3621              : 
    3622            0 :     return count >= min;
    3623              : }
    3624              : 
    3625              : /*
    3626              :  * CountDBBackends --- count backends that are using specified database
    3627              :  */
    3628              : int
    3629           16 : CountDBBackends(Oid databaseid)
    3630              : {
    3631           16 :     ProcArrayStruct *arrayP = procArray;
    3632           16 :     int         count = 0;
    3633              :     int         index;
    3634              : 
    3635           16 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3636              : 
    3637           24 :     for (index = 0; index < arrayP->numProcs; index++)
    3638              :     {
    3639            8 :         int         pgprocno = arrayP->pgprocnos[index];
    3640            8 :         PGPROC     *proc = &allProcs[pgprocno];
    3641              : 
    3642            8 :         if (proc->pid == 0)
    3643            0 :             continue;           /* do not count prepared xacts */
    3644            8 :         if (!OidIsValid(databaseid) ||
    3645            8 :             proc->databaseId == databaseid)
    3646            2 :             count++;
    3647              :     }
    3648              : 
    3649           16 :     LWLockRelease(ProcArrayLock);
    3650              : 
    3651           16 :     return count;
    3652              : }
    3653              : 
    3654              : /*
    3655              :  * CountDBConnections --- counts database backends (only regular backends)
    3656              :  */
    3657              : int
    3658            0 : CountDBConnections(Oid databaseid)
    3659              : {
    3660            0 :     ProcArrayStruct *arrayP = procArray;
    3661            0 :     int         count = 0;
    3662              :     int         index;
    3663              : 
    3664            0 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3665              : 
    3666            0 :     for (index = 0; index < arrayP->numProcs; index++)
    3667              :     {
    3668            0 :         int         pgprocno = arrayP->pgprocnos[index];
    3669            0 :         PGPROC     *proc = &allProcs[pgprocno];
    3670              : 
    3671            0 :         if (proc->pid == 0)
    3672            0 :             continue;           /* do not count prepared xacts */
    3673            0 :         if (proc->backendType != B_BACKEND)
    3674            0 :             continue;           /* count only regular backend processes */
    3675            0 :         if (!OidIsValid(databaseid) ||
    3676            0 :             proc->databaseId == databaseid)
    3677            0 :             count++;
    3678              :     }
    3679              : 
    3680            0 :     LWLockRelease(ProcArrayLock);
    3681              : 
    3682            0 :     return count;
    3683              : }
    3684              : 
    3685              : /*
    3686              :  * CountUserBackends --- count backends that are used by specified user
    3687              :  * (only regular backends, not any type of background worker)
    3688              :  */
    3689              : int
    3690            0 : CountUserBackends(Oid roleid)
    3691              : {
    3692            0 :     ProcArrayStruct *arrayP = procArray;
    3693            0 :     int         count = 0;
    3694              :     int         index;
    3695              : 
    3696            0 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3697              : 
    3698            0 :     for (index = 0; index < arrayP->numProcs; index++)
    3699              :     {
    3700            0 :         int         pgprocno = arrayP->pgprocnos[index];
    3701            0 :         PGPROC     *proc = &allProcs[pgprocno];
    3702              : 
    3703            0 :         if (proc->pid == 0)
    3704            0 :             continue;           /* do not count prepared xacts */
    3705            0 :         if (proc->backendType != B_BACKEND)
    3706            0 :             continue;           /* count only regular backend processes */
    3707            0 :         if (proc->roleId == roleid)
    3708            0 :             count++;
    3709              :     }
    3710              : 
    3711            0 :     LWLockRelease(ProcArrayLock);
    3712              : 
    3713            0 :     return count;
    3714              : }
    3715              : 
    3716              : /*
    3717              :  * CountOtherDBBackends -- check for other backends running in the given DB
    3718              :  *
    3719              :  * If there are other backends in the DB, we will wait a maximum of 5 seconds
    3720              :  * for them to exit (or 0.3s for testing purposes).  Autovacuum backends are
    3721              :  * encouraged to exit early by sending them SIGTERM, but normal user backends
    3722              :  * are just waited for.  If background workers connected to this database are
    3723              :  * marked as interruptible, they are terminated.
    3724              :  *
    3725              :  * The current backend is always ignored; it is caller's responsibility to
    3726              :  * check whether the current backend uses the given DB, if it's important.
    3727              :  *
    3728              :  * Returns true if there are (still) other backends in the DB, false if not.
    3729              :  * Also, *nbackends and *nprepared are set to the number of other backends
    3730              :  * and prepared transactions in the DB, respectively.
    3731              :  *
    3732              :  * This function is used to interlock DROP DATABASE and related commands
    3733              :  * against there being any active backends in the target DB --- dropping the
    3734              :  * DB while active backends remain would be a Bad Thing.  Note that we cannot
    3735              :  * detect here the possibility of a newly-started backend that is trying to
    3736              :  * connect to the doomed database, so additional interlocking is needed during
    3737              :  * backend startup.  The caller should normally hold an exclusive lock on the
    3738              :  * target DB before calling this, which is one reason we mustn't wait
    3739              :  * indefinitely.
    3740              :  */
    3741              : bool
    3742          487 : CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
    3743              : {
    3744          487 :     ProcArrayStruct *arrayP = procArray;
    3745              : 
    3746              : #define MAXAUTOVACPIDS  10      /* max autovacs to SIGTERM per iteration */
    3747              :     int         autovac_pids[MAXAUTOVACPIDS];
    3748              : 
    3749              :     /*
    3750              :      * Retry up to 50 times with 100ms between attempts (max 5s total). Can be
    3751              :      * reduced to 3 attempts (max 0.3s total) to speed up tests.
    3752              :      */
    3753          487 :     int         ntries = 50;
    3754              : 
    3755              : #ifdef USE_INJECTION_POINTS
    3756          487 :     if (IS_INJECTION_POINT_ATTACHED("procarray-reduce-count"))
    3757            1 :         ntries = 3;
    3758              : #endif
    3759              : 
    3760          494 :     for (int tries = 0; tries < ntries; tries++)
    3761              :     {
    3762          493 :         int         nautovacs = 0;
    3763          493 :         bool        found = false;
    3764              :         int         index;
    3765              : 
    3766          493 :         CHECK_FOR_INTERRUPTS();
    3767              : 
    3768          493 :         *nbackends = *nprepared = 0;
    3769              : 
    3770          493 :         LWLockAcquire(ProcArrayLock, LW_SHARED);
    3771              : 
    3772         1894 :         for (index = 0; index < arrayP->numProcs; index++)
    3773              :         {
    3774         1401 :             int         pgprocno = arrayP->pgprocnos[index];
    3775         1401 :             PGPROC     *proc = &allProcs[pgprocno];
    3776         1401 :             uint8       statusFlags = ProcGlobal->statusFlags[index];
    3777              : 
    3778         1401 :             if (proc->databaseId != databaseId)
    3779         1291 :                 continue;
    3780          110 :             if (proc == MyProc)
    3781          103 :                 continue;
    3782              : 
    3783            7 :             found = true;
    3784              : 
    3785            7 :             if (proc->pid == 0)
    3786            0 :                 (*nprepared)++;
    3787              :             else
    3788              :             {
    3789            7 :                 (*nbackends)++;
    3790            7 :                 if ((statusFlags & PROC_IS_AUTOVACUUM) &&
    3791              :                     nautovacs < MAXAUTOVACPIDS)
    3792            0 :                     autovac_pids[nautovacs++] = proc->pid;
    3793              :             }
    3794              :         }
    3795              : 
    3796          493 :         LWLockRelease(ProcArrayLock);
    3797              : 
    3798          493 :         if (!found)
    3799          486 :             return false;       /* no conflicting backends, so done */
    3800              : 
    3801              :         /*
    3802              :          * Send SIGTERM to any conflicting autovacuums before sleeping. We
    3803              :          * postpone this step until after the loop because we don't want to
    3804              :          * hold ProcArrayLock while issuing kill(). We have no idea what might
    3805              :          * block kill() inside the kernel...
    3806              :          */
    3807            7 :         for (index = 0; index < nautovacs; index++)
    3808            0 :             (void) kill(autovac_pids[index], SIGTERM);  /* ignore any error */
    3809              : 
    3810              :         /*
    3811              :          * Terminate all background workers for this database, if they have
    3812              :          * requested it (BGWORKER_INTERRUPTIBLE).
    3813              :          */
    3814            7 :         TerminateBackgroundWorkersForDatabase(databaseId);
    3815              : 
    3816              :         /* sleep, then try again */
    3817            7 :         pg_usleep(100 * 1000L); /* 100ms */
    3818              :     }
    3819              : 
    3820            1 :     return true;                /* timed out, still conflicts */
    3821              : }
    3822              : 
    3823              : /*
    3824              :  * Terminate existing connections to the specified database. This routine
    3825              :  * is used by the DROP DATABASE command when user has asked to forcefully
    3826              :  * drop the database.
    3827              :  *
    3828              :  * The current backend is always ignored; it is caller's responsibility to
    3829              :  * check whether the current backend uses the given DB, if it's important.
    3830              :  *
    3831              :  * If the target database has a prepared transaction or permissions checks
    3832              :  * fail for a connection, this fails without terminating anything.
    3833              :  */
    3834              : void
    3835            1 : TerminateOtherDBBackends(Oid databaseId)
    3836              : {
    3837            1 :     ProcArrayStruct *arrayP = procArray;
    3838            1 :     List       *pids = NIL;
    3839            1 :     int         nprepared = 0;
    3840              :     int         i;
    3841              : 
    3842            1 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3843              : 
    3844            4 :     for (i = 0; i < procArray->numProcs; i++)
    3845              :     {
    3846            3 :         int         pgprocno = arrayP->pgprocnos[i];
    3847            3 :         PGPROC     *proc = &allProcs[pgprocno];
    3848              : 
    3849            3 :         if (proc->databaseId != databaseId)
    3850            3 :             continue;
    3851            0 :         if (proc == MyProc)
    3852            0 :             continue;
    3853              : 
    3854            0 :         if (proc->pid != 0)
    3855            0 :             pids = lappend_int(pids, proc->pid);
    3856              :         else
    3857            0 :             nprepared++;
    3858              :     }
    3859              : 
    3860            1 :     LWLockRelease(ProcArrayLock);
    3861              : 
    3862            1 :     if (nprepared > 0)
    3863            0 :         ereport(ERROR,
    3864              :                 (errcode(ERRCODE_OBJECT_IN_USE),
    3865              :                  errmsg("database \"%s\" is being used by prepared transactions",
    3866              :                         get_database_name(databaseId)),
    3867              :                  errdetail_plural("There is %d prepared transaction using the database.",
    3868              :                                   "There are %d prepared transactions using the database.",
    3869              :                                   nprepared,
    3870              :                                   nprepared)));
    3871              : 
    3872            1 :     if (pids)
    3873              :     {
    3874              :         ListCell   *lc;
    3875              : 
    3876              :         /*
    3877              :          * Permissions checks relax the pg_terminate_backend checks in two
    3878              :          * ways, both by omitting the !OidIsValid(proc->roleId) check:
    3879              :          *
    3880              :          * - Accept terminating autovacuum workers, since DROP DATABASE
    3881              :          * without FORCE terminates them.
    3882              :          *
    3883              :          * - Accept terminating bgworkers.  For bgworker authors, it's
    3884              :          * convenient to be able to recommend FORCE if a worker is blocking
    3885              :          * DROP DATABASE unexpectedly.
    3886              :          *
    3887              :          * Unlike pg_terminate_backend, we don't raise some warnings - like
    3888              :          * "PID %d is not a PostgreSQL server process", because for us already
    3889              :          * finished session is not a problem.
    3890              :          */
    3891            0 :         foreach(lc, pids)
    3892              :         {
    3893            0 :             int         pid = lfirst_int(lc);
    3894            0 :             PGPROC     *proc = BackendPidGetProc(pid);
    3895              : 
    3896            0 :             if (proc != NULL)
    3897              :             {
    3898            0 :                 if (superuser_arg(proc->roleId) && !superuser())
    3899            0 :                     ereport(ERROR,
    3900              :                             (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    3901              :                              errmsg("permission denied to terminate process"),
    3902              :                              errdetail("Only roles with the %s attribute may terminate processes of roles with the %s attribute.",
    3903              :                                        "SUPERUSER", "SUPERUSER")));
    3904              : 
    3905            0 :                 if (!has_privs_of_role(GetUserId(), proc->roleId) &&
    3906            0 :                     !has_privs_of_role(GetUserId(), ROLE_PG_SIGNAL_BACKEND))
    3907            0 :                     ereport(ERROR,
    3908              :                             (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    3909              :                              errmsg("permission denied to terminate process"),
    3910              :                              errdetail("Only roles with privileges of the role whose process is being terminated or with privileges of the \"%s\" role may terminate this process.",
    3911              :                                        "pg_signal_backend")));
    3912              :             }
    3913              :         }
    3914              : 
    3915              :         /*
    3916              :          * There's a race condition here: once we release the ProcArrayLock,
    3917              :          * it's possible for the session to exit before we issue kill.  That
    3918              :          * race condition possibility seems too unlikely to worry about.  See
    3919              :          * pg_signal_backend.
    3920              :          */
    3921            0 :         foreach(lc, pids)
    3922              :         {
    3923            0 :             int         pid = lfirst_int(lc);
    3924            0 :             PGPROC     *proc = BackendPidGetProc(pid);
    3925              : 
    3926            0 :             if (proc != NULL)
    3927              :             {
    3928              :                 /*
    3929              :                  * If we have setsid(), signal the backend's whole process
    3930              :                  * group
    3931              :                  */
    3932              : #ifdef HAVE_SETSID
    3933            0 :                 (void) kill(-pid, SIGTERM);
    3934              : #else
    3935              :                 (void) kill(pid, SIGTERM);
    3936              : #endif
    3937              :             }
    3938              :         }
    3939              :     }
    3940            1 : }
    3941              : 
    3942              : /*
    3943              :  * ProcArraySetReplicationSlotXmin
    3944              :  *
    3945              :  * Install limits to future computations of the xmin horizon to prevent vacuum
    3946              :  * and HOT pruning from removing affected rows still needed by clients with
    3947              :  * replication slots.
    3948              :  */
    3949              : void
    3950         2555 : ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin,
    3951              :                                 bool already_locked)
    3952              : {
    3953              :     Assert(!already_locked || LWLockHeldByMe(ProcArrayLock));
    3954              : 
    3955         2555 :     if (!already_locked)
    3956         2047 :         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    3957              : 
    3958         2555 :     procArray->replication_slot_xmin = xmin;
    3959         2555 :     procArray->replication_slot_catalog_xmin = catalog_xmin;
    3960              : 
    3961         2555 :     if (!already_locked)
    3962         2047 :         LWLockRelease(ProcArrayLock);
    3963              : 
    3964         2555 :     elog(DEBUG1, "xmin required by slots: data %u, catalog %u",
    3965              :          xmin, catalog_xmin);
    3966         2555 : }
    3967              : 
    3968              : /*
    3969              :  * ProcArrayGetReplicationSlotXmin
    3970              :  *
    3971              :  * Return the current slot xmin limits. That's useful to be able to remove
    3972              :  * data that's older than those limits.
    3973              :  */
    3974              : void
    3975           22 : ProcArrayGetReplicationSlotXmin(TransactionId *xmin,
    3976              :                                 TransactionId *catalog_xmin)
    3977              : {
    3978           22 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    3979              : 
    3980           22 :     if (xmin != NULL)
    3981            0 :         *xmin = procArray->replication_slot_xmin;
    3982              : 
    3983           22 :     if (catalog_xmin != NULL)
    3984           22 :         *catalog_xmin = procArray->replication_slot_catalog_xmin;
    3985              : 
    3986           22 :     LWLockRelease(ProcArrayLock);
    3987           22 : }
    3988              : 
    3989              : /*
    3990              :  * XidCacheRemoveRunningXids
    3991              :  *
    3992              :  * Remove a bunch of TransactionIds from the list of known-running
    3993              :  * subtransactions for my backend.  Both the specified xid and those in
    3994              :  * the xids[] array (of length nxids) are removed from the subxids cache.
    3995              :  * latestXid must be the latest XID among the group.
    3996              :  */
    3997              : void
    3998          851 : XidCacheRemoveRunningXids(TransactionId xid,
    3999              :                           int nxids, const TransactionId *xids,
    4000              :                           TransactionId latestXid)
    4001              : {
    4002              :     int         i,
    4003              :                 j;
    4004              :     XidCacheStatus *mysubxidstat;
    4005              : 
    4006              :     Assert(TransactionIdIsValid(xid));
    4007              : 
    4008              :     /*
    4009              :      * We must hold ProcArrayLock exclusively in order to remove transactions
    4010              :      * from the PGPROC array.  (See src/backend/access/transam/README.)  It's
    4011              :      * possible this could be relaxed since we know this routine is only used
    4012              :      * to abort subtransactions, but pending closer analysis we'd best be
    4013              :      * conservative.
    4014              :      *
    4015              :      * Note that we do not have to be careful about memory ordering of our own
    4016              :      * reads wrt. GetNewTransactionId() here - only this process can modify
    4017              :      * relevant fields of MyProc/ProcGlobal->xids[].  But we do have to be
    4018              :      * careful about our own writes being well ordered.
    4019              :      */
    4020          851 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4021              : 
    4022          851 :     mysubxidstat = &ProcGlobal->subxidStates[MyProc->pgxactoff];
    4023              : 
    4024              :     /*
    4025              :      * Under normal circumstances xid and xids[] will be in increasing order,
    4026              :      * as will be the entries in subxids.  Scan backwards to avoid O(N^2)
    4027              :      * behavior when removing a lot of xids.
    4028              :      */
    4029          883 :     for (i = nxids - 1; i >= 0; i--)
    4030              :     {
    4031           32 :         TransactionId anxid = xids[i];
    4032              : 
    4033           32 :         for (j = MyProc->subxidStatus.count - 1; j >= 0; j--)
    4034              :         {
    4035           32 :             if (TransactionIdEquals(MyProc->subxids.xids[j], anxid))
    4036              :             {
    4037           32 :                 MyProc->subxids.xids[j] = MyProc->subxids.xids[MyProc->subxidStatus.count - 1];
    4038           32 :                 pg_write_barrier();
    4039           32 :                 mysubxidstat->count--;
    4040           32 :                 MyProc->subxidStatus.count--;
    4041           32 :                 break;
    4042              :             }
    4043              :         }
    4044              : 
    4045              :         /*
    4046              :          * Ordinarily we should have found it, unless the cache has
    4047              :          * overflowed. However it's also possible for this routine to be
    4048              :          * invoked multiple times for the same subtransaction, in case of an
    4049              :          * error during AbortSubTransaction.  So instead of Assert, emit a
    4050              :          * debug warning.
    4051              :          */
    4052           32 :         if (j < 0 && !MyProc->subxidStatus.overflowed)
    4053            0 :             elog(WARNING, "did not find subXID %u in MyProc", anxid);
    4054              :     }
    4055              : 
    4056          915 :     for (j = MyProc->subxidStatus.count - 1; j >= 0; j--)
    4057              :     {
    4058          914 :         if (TransactionIdEquals(MyProc->subxids.xids[j], xid))
    4059              :         {
    4060          850 :             MyProc->subxids.xids[j] = MyProc->subxids.xids[MyProc->subxidStatus.count - 1];
    4061          850 :             pg_write_barrier();
    4062          850 :             mysubxidstat->count--;
    4063          850 :             MyProc->subxidStatus.count--;
    4064          850 :             break;
    4065              :         }
    4066              :     }
    4067              :     /* Ordinarily we should have found it, unless the cache has overflowed */
    4068          851 :     if (j < 0 && !MyProc->subxidStatus.overflowed)
    4069            0 :         elog(WARNING, "did not find subXID %u in MyProc", xid);
    4070              : 
    4071              :     /* Also advance global latestCompletedXid while holding the lock */
    4072          851 :     MaintainLatestCompletedXid(latestXid);
    4073              : 
    4074              :     /* ... and xactCompletionCount */
    4075          851 :     TransamVariables->xactCompletionCount++;
    4076              : 
    4077          851 :     LWLockRelease(ProcArrayLock);
    4078          851 : }
    4079              : 
    4080              : #ifdef XIDCACHE_DEBUG
    4081              : 
    4082              : /*
    4083              :  * Print stats about effectiveness of XID cache
    4084              :  */
    4085              : static void
    4086              : DisplayXidCache(void)
    4087              : {
    4088              :     fprintf(stderr,
    4089              :             "XidCache: xmin: %ld, known: %ld, myxact: %ld, latest: %ld, mainxid: %ld, childxid: %ld, knownassigned: %ld, nooflo: %ld, slow: %ld\n",
    4090              :             xc_by_recent_xmin,
    4091              :             xc_by_known_xact,
    4092              :             xc_by_my_xact,
    4093              :             xc_by_latest_xid,
    4094              :             xc_by_main_xid,
    4095              :             xc_by_child_xid,
    4096              :             xc_by_known_assigned,
    4097              :             xc_no_overflow,
    4098              :             xc_slow_answer);
    4099              : }
    4100              : #endif                          /* XIDCACHE_DEBUG */
    4101              : 
    4102              : /*
    4103              :  * If rel != NULL, return test state appropriate for relation, otherwise
    4104              :  * return state usable for all relations.  The latter may consider XIDs as
    4105              :  * not-yet-visible-to-everyone that a state for a specific relation would
    4106              :  * already consider visible-to-everyone.
    4107              :  *
    4108              :  * This needs to be called while a snapshot is active or registered, otherwise
    4109              :  * there are wraparound and other dangers.
    4110              :  *
    4111              :  * See comment for GlobalVisState for details.
    4112              :  */
    4113              : GlobalVisState *
    4114     18848401 : GlobalVisTestFor(Relation rel)
    4115              : {
    4116     18848401 :     GlobalVisState *state = NULL;
    4117              : 
    4118              :     /* XXX: we should assert that a snapshot is pushed or registered */
    4119              :     Assert(RecentXmin);
    4120              : 
    4121     18848401 :     switch (GlobalVisHorizonKindForRel(rel))
    4122              :     {
    4123       100796 :         case VISHORIZON_SHARED:
    4124       100796 :             state = &GlobalVisSharedRels;
    4125       100796 :             break;
    4126      3717321 :         case VISHORIZON_CATALOG:
    4127      3717321 :             state = &GlobalVisCatalogRels;
    4128      3717321 :             break;
    4129     14957532 :         case VISHORIZON_DATA:
    4130     14957532 :             state = &GlobalVisDataRels;
    4131     14957532 :             break;
    4132        72752 :         case VISHORIZON_TEMP:
    4133        72752 :             state = &GlobalVisTempRels;
    4134        72752 :             break;
    4135              :     }
    4136              : 
    4137              :     Assert(FullTransactionIdIsValid(state->definitely_needed) &&
    4138              :            FullTransactionIdIsValid(state->maybe_needed));
    4139              : 
    4140     18848401 :     return state;
    4141              : }
    4142              : 
    4143              : /*
    4144              :  * Return true if it's worth updating the accurate maybe_needed boundary.
    4145              :  *
    4146              :  * As it is somewhat expensive to determine xmin horizons, we don't want to
    4147              :  * repeatedly do so when there is a low likelihood of it being beneficial.
    4148              :  *
    4149              :  * The current heuristic is that we update only if RecentXmin has changed
    4150              :  * since the last update. If the oldest currently running transaction has not
    4151              :  * finished, it is unlikely that recomputing the horizon would be useful.
    4152              :  */
    4153              : static bool
    4154       510796 : GlobalVisTestShouldUpdate(GlobalVisState *state)
    4155              : {
    4156              :     /* hasn't been updated yet */
    4157       510796 :     if (!TransactionIdIsValid(ComputeXidHorizonsResultLastXmin))
    4158         9920 :         return true;
    4159              : 
    4160              :     /*
    4161              :      * If the maybe_needed/definitely_needed boundaries are the same, it's
    4162              :      * unlikely to be beneficial to refresh boundaries.
    4163              :      */
    4164       500876 :     if (FullTransactionIdFollowsOrEquals(state->maybe_needed,
    4165              :                                          state->definitely_needed))
    4166            0 :         return false;
    4167              : 
    4168              :     /* does the last snapshot built have a different xmin? */
    4169       500876 :     return RecentXmin != ComputeXidHorizonsResultLastXmin;
    4170              : }
    4171              : 
    4172              : static void
    4173       214267 : GlobalVisUpdateApply(ComputeXidHorizonsResult *horizons)
    4174              : {
    4175              :     GlobalVisSharedRels.maybe_needed =
    4176       214267 :         FullXidRelativeTo(horizons->latest_completed,
    4177              :                           horizons->shared_oldest_nonremovable);
    4178              :     GlobalVisCatalogRels.maybe_needed =
    4179       214267 :         FullXidRelativeTo(horizons->latest_completed,
    4180              :                           horizons->catalog_oldest_nonremovable);
    4181              :     GlobalVisDataRels.maybe_needed =
    4182       214267 :         FullXidRelativeTo(horizons->latest_completed,
    4183              :                           horizons->data_oldest_nonremovable);
    4184              :     GlobalVisTempRels.maybe_needed =
    4185       214267 :         FullXidRelativeTo(horizons->latest_completed,
    4186              :                           horizons->temp_oldest_nonremovable);
    4187              : 
    4188              :     /*
    4189              :      * In longer running transactions it's possible that transactions we
    4190              :      * previously needed to treat as running aren't around anymore. So update
    4191              :      * definitely_needed to not be earlier than maybe_needed.
    4192              :      */
    4193              :     GlobalVisSharedRels.definitely_needed =
    4194       214267 :         FullTransactionIdNewer(GlobalVisSharedRels.maybe_needed,
    4195              :                                GlobalVisSharedRels.definitely_needed);
    4196              :     GlobalVisCatalogRels.definitely_needed =
    4197       214267 :         FullTransactionIdNewer(GlobalVisCatalogRels.maybe_needed,
    4198              :                                GlobalVisCatalogRels.definitely_needed);
    4199              :     GlobalVisDataRels.definitely_needed =
    4200       214267 :         FullTransactionIdNewer(GlobalVisDataRels.maybe_needed,
    4201              :                                GlobalVisDataRels.definitely_needed);
    4202       214267 :     GlobalVisTempRels.definitely_needed = GlobalVisTempRels.maybe_needed;
    4203              : 
    4204       214267 :     ComputeXidHorizonsResultLastXmin = RecentXmin;
    4205       214267 : }
    4206              : 
    4207              : /*
    4208              :  * Update boundaries in GlobalVis{Shared,Catalog, Data}Rels
    4209              :  * using ComputeXidHorizons().
    4210              :  */
    4211              : static void
    4212        66108 : GlobalVisUpdate(void)
    4213              : {
    4214              :     ComputeXidHorizonsResult horizons;
    4215              : 
    4216              :     /* updates the horizons as a side-effect */
    4217        66108 :     ComputeXidHorizons(&horizons);
    4218        66108 : }
    4219              : 
    4220              : /*
    4221              :  * Return true if no snapshot still considers fxid to be running.
    4222              :  *
    4223              :  * The state passed needs to have been initialized for the relation fxid is
    4224              :  * from (NULL is also OK), otherwise the result may not be correct.
    4225              :  *
    4226              :  * See comment for GlobalVisState for details.
    4227              :  */
    4228              : bool
    4229     12420821 : GlobalVisTestIsRemovableFullXid(GlobalVisState *state,
    4230              :                                 FullTransactionId fxid)
    4231              : {
    4232              :     /*
    4233              :      * If fxid is older than maybe_needed bound, it definitely is visible to
    4234              :      * everyone.
    4235              :      */
    4236     12420821 :     if (FullTransactionIdPrecedes(fxid, state->maybe_needed))
    4237      3118222 :         return true;
    4238              : 
    4239              :     /*
    4240              :      * If fxid is >= definitely_needed bound, it is very likely to still be
    4241              :      * considered running.
    4242              :      */
    4243      9302599 :     if (FullTransactionIdFollowsOrEquals(fxid, state->definitely_needed))
    4244      8791803 :         return false;
    4245              : 
    4246              :     /*
    4247              :      * fxid is between maybe_needed and definitely_needed, i.e. there might or
    4248              :      * might not exist a snapshot considering fxid running. If it makes sense,
    4249              :      * update boundaries and recheck.
    4250              :      */
    4251       510796 :     if (GlobalVisTestShouldUpdate(state))
    4252              :     {
    4253        66108 :         GlobalVisUpdate();
    4254              : 
    4255              :         Assert(FullTransactionIdPrecedes(fxid, state->definitely_needed));
    4256              : 
    4257        66108 :         return FullTransactionIdPrecedes(fxid, state->maybe_needed);
    4258              :     }
    4259              :     else
    4260       444688 :         return false;
    4261              : }
    4262              : 
    4263              : /*
    4264              :  * Wrapper around GlobalVisTestIsRemovableFullXid() for 32bit xids.
    4265              :  *
    4266              :  * It is crucial that this only gets called for xids from a source that
    4267              :  * protects against xid wraparounds (e.g. from a table and thus protected by
    4268              :  * relfrozenxid).
    4269              :  */
    4270              : bool
    4271     12419841 : GlobalVisTestIsRemovableXid(GlobalVisState *state, TransactionId xid)
    4272              : {
    4273              :     FullTransactionId fxid;
    4274              : 
    4275              :     /*
    4276              :      * Convert 32 bit argument to FullTransactionId. We can do so safely
    4277              :      * because we know the xid has to, at the very least, be between
    4278              :      * [oldestXid, nextXid), i.e. within 2 billion of xid. To avoid taking a
    4279              :      * lock to determine either, we can just compare with
    4280              :      * state->definitely_needed, which was based on those value at the time
    4281              :      * the current snapshot was built.
    4282              :      */
    4283     12419841 :     fxid = FullXidRelativeTo(state->definitely_needed, xid);
    4284              : 
    4285     12419841 :     return GlobalVisTestIsRemovableFullXid(state, fxid);
    4286              : }
    4287              : 
    4288              : /*
    4289              :  * Convenience wrapper around GlobalVisTestFor() and
    4290              :  * GlobalVisTestIsRemovableFullXid(), see their comments.
    4291              :  */
    4292              : bool
    4293          980 : GlobalVisCheckRemovableFullXid(Relation rel, FullTransactionId fxid)
    4294              : {
    4295              :     GlobalVisState *state;
    4296              : 
    4297          980 :     state = GlobalVisTestFor(rel);
    4298              : 
    4299          980 :     return GlobalVisTestIsRemovableFullXid(state, fxid);
    4300              : }
    4301              : 
    4302              : /*
    4303              :  * Convenience wrapper around GlobalVisTestFor() and
    4304              :  * GlobalVisTestIsRemovableXid(), see their comments.
    4305              :  */
    4306              : bool
    4307            8 : GlobalVisCheckRemovableXid(Relation rel, TransactionId xid)
    4308              : {
    4309              :     GlobalVisState *state;
    4310              : 
    4311            8 :     state = GlobalVisTestFor(rel);
    4312              : 
    4313            8 :     return GlobalVisTestIsRemovableXid(state, xid);
    4314              : }
    4315              : 
    4316              : /*
    4317              :  * Convert a 32 bit transaction id into 64 bit transaction id, by assuming it
    4318              :  * is within MaxTransactionId / 2 of XidFromFullTransactionId(rel).
    4319              :  *
    4320              :  * Be very careful about when to use this function. It can only safely be used
    4321              :  * when there is a guarantee that xid is within MaxTransactionId / 2 xids of
    4322              :  * rel. That e.g. can be guaranteed if the caller assures a snapshot is
    4323              :  * held by the backend and xid is from a table (where vacuum/freezing ensures
    4324              :  * the xid has to be within that range), or if xid is from the procarray and
    4325              :  * prevents xid wraparound that way.
    4326              :  */
    4327              : static inline FullTransactionId
    4328     14949199 : FullXidRelativeTo(FullTransactionId rel, TransactionId xid)
    4329              : {
    4330     14949199 :     TransactionId rel_xid = XidFromFullTransactionId(rel);
    4331              : 
    4332              :     Assert(TransactionIdIsValid(xid));
    4333              :     Assert(TransactionIdIsValid(rel_xid));
    4334              : 
    4335              :     /* not guaranteed to find issues, but likely to catch mistakes */
    4336              :     AssertTransactionIdInAllowableRange(xid);
    4337              : 
    4338     29898398 :     return FullTransactionIdFromU64(U64FromFullTransactionId(rel)
    4339     14949199 :                                     + (int32) (xid - rel_xid));
    4340              : }
    4341              : 
    4342              : 
    4343              : /* ----------------------------------------------
    4344              :  *      KnownAssignedTransactionIds sub-module
    4345              :  * ----------------------------------------------
    4346              :  */
    4347              : 
    4348              : /*
    4349              :  * In Hot Standby mode, we maintain a list of transactions that are (or were)
    4350              :  * running on the primary at the current point in WAL.  These XIDs must be
    4351              :  * treated as running by standby transactions, even though they are not in
    4352              :  * the standby server's PGPROC array.
    4353              :  *
    4354              :  * We record all XIDs that we know have been assigned.  That includes all the
    4355              :  * XIDs seen in WAL records, plus all unobserved XIDs that we can deduce have
    4356              :  * been assigned.  We can deduce the existence of unobserved XIDs because we
    4357              :  * know XIDs are assigned in sequence, with no gaps.  The KnownAssignedXids
    4358              :  * list expands as new XIDs are observed or inferred, and contracts when
    4359              :  * transaction completion records arrive.
    4360              :  *
    4361              :  * During hot standby we do not fret too much about the distinction between
    4362              :  * top-level XIDs and subtransaction XIDs. We store both together in the
    4363              :  * KnownAssignedXids list.  In backends, this is copied into snapshots in
    4364              :  * GetSnapshotData(), taking advantage of the fact that XidInMVCCSnapshot()
    4365              :  * doesn't care about the distinction either.  Subtransaction XIDs are
    4366              :  * effectively treated as top-level XIDs and in the typical case pg_subtrans
    4367              :  * links are *not* maintained (which does not affect visibility).
    4368              :  *
    4369              :  * We have room in KnownAssignedXids and in snapshots to hold maxProcs *
    4370              :  * (1 + PGPROC_MAX_CACHED_SUBXIDS) XIDs, so every primary transaction must
    4371              :  * report its subtransaction XIDs in a WAL XLOG_XACT_ASSIGNMENT record at
    4372              :  * least every PGPROC_MAX_CACHED_SUBXIDS.  When we receive one of these
    4373              :  * records, we mark the subXIDs as children of the top XID in pg_subtrans,
    4374              :  * and then remove them from KnownAssignedXids.  This prevents overflow of
    4375              :  * KnownAssignedXids and snapshots, at the cost that status checks for these
    4376              :  * subXIDs will take a slower path through TransactionIdIsInProgress().
    4377              :  * This means that KnownAssignedXids is not necessarily complete for subXIDs,
    4378              :  * though it should be complete for top-level XIDs; this is the same situation
    4379              :  * that holds with respect to the PGPROC entries in normal running.
    4380              :  *
    4381              :  * When we throw away subXIDs from KnownAssignedXids, we need to keep track of
    4382              :  * that, similarly to tracking overflow of a PGPROC's subxids array.  We do
    4383              :  * that by remembering the lastOverflowedXid, ie the last thrown-away subXID.
    4384              :  * As long as that is within the range of interesting XIDs, we have to assume
    4385              :  * that subXIDs are missing from snapshots.  (Note that subXID overflow occurs
    4386              :  * on primary when 65th subXID arrives, whereas on standby it occurs when 64th
    4387              :  * subXID arrives - that is not an error.)
    4388              :  *
    4389              :  * Should a backend on primary somehow disappear before it can write an abort
    4390              :  * record, then we just leave those XIDs in KnownAssignedXids. They actually
    4391              :  * aborted but we think they were running; the distinction is irrelevant
    4392              :  * because either way any changes done by the transaction are not visible to
    4393              :  * backends in the standby.  We prune KnownAssignedXids when
    4394              :  * XLOG_RUNNING_XACTS arrives, to forestall possible overflow of the
    4395              :  * array due to such dead XIDs.
    4396              :  */
    4397              : 
    4398              : /*
    4399              :  * RecordKnownAssignedTransactionIds
    4400              :  *      Record the given XID in KnownAssignedXids, as well as any preceding
    4401              :  *      unobserved XIDs.
    4402              :  *
    4403              :  * RecordKnownAssignedTransactionIds() should be run for *every* WAL record
    4404              :  * associated with a transaction. Must be called for each record after we
    4405              :  * have executed StartupCLOG() et al, since we must ExtendCLOG() etc..
    4406              :  *
    4407              :  * Called during recovery in analogy with and in place of GetNewTransactionId()
    4408              :  */
    4409              : void
    4410      2549575 : RecordKnownAssignedTransactionIds(TransactionId xid)
    4411              : {
    4412              :     Assert(standbyState >= STANDBY_INITIALIZED);
    4413              :     Assert(TransactionIdIsValid(xid));
    4414              :     Assert(TransactionIdIsValid(latestObservedXid));
    4415              : 
    4416      2549575 :     elog(DEBUG4, "record known xact %u latestObservedXid %u",
    4417              :          xid, latestObservedXid);
    4418              : 
    4419              :     /*
    4420              :      * When a newly observed xid arrives, it is frequently the case that it is
    4421              :      * *not* the next xid in sequence. When this occurs, we must treat the
    4422              :      * intervening xids as running also.
    4423              :      */
    4424      2549575 :     if (TransactionIdFollows(xid, latestObservedXid))
    4425              :     {
    4426              :         TransactionId next_expected_xid;
    4427              : 
    4428              :         /*
    4429              :          * Extend subtrans like we do in GetNewTransactionId() during normal
    4430              :          * operation using individual extend steps. Note that we do not need
    4431              :          * to extend clog since its extensions are WAL logged.
    4432              :          *
    4433              :          * This part has to be done regardless of standbyState since we
    4434              :          * immediately start assigning subtransactions to their toplevel
    4435              :          * transactions.
    4436              :          */
    4437        23801 :         next_expected_xid = latestObservedXid;
    4438        48334 :         while (TransactionIdPrecedes(next_expected_xid, xid))
    4439              :         {
    4440        24533 :             TransactionIdAdvance(next_expected_xid);
    4441        24533 :             ExtendSUBTRANS(next_expected_xid);
    4442              :         }
    4443              :         Assert(next_expected_xid == xid);
    4444              : 
    4445              :         /*
    4446              :          * If the KnownAssignedXids machinery isn't up yet, there's nothing
    4447              :          * more to do since we don't track assigned xids yet.
    4448              :          */
    4449        23801 :         if (standbyState <= STANDBY_INITIALIZED)
    4450              :         {
    4451            0 :             latestObservedXid = xid;
    4452            0 :             return;
    4453              :         }
    4454              : 
    4455              :         /*
    4456              :          * Add (latestObservedXid, xid] onto the KnownAssignedXids array.
    4457              :          */
    4458        23801 :         next_expected_xid = latestObservedXid;
    4459        23801 :         TransactionIdAdvance(next_expected_xid);
    4460        23801 :         KnownAssignedXidsAdd(next_expected_xid, xid, false);
    4461              : 
    4462              :         /*
    4463              :          * Now we can advance latestObservedXid
    4464              :          */
    4465        23801 :         latestObservedXid = xid;
    4466              : 
    4467              :         /* TransamVariables->nextXid must be beyond any observed xid */
    4468        23801 :         AdvanceNextFullTransactionIdPastXid(latestObservedXid);
    4469              :     }
    4470              : }
    4471              : 
    4472              : /*
    4473              :  * ExpireTreeKnownAssignedTransactionIds
    4474              :  *      Remove the given XIDs from KnownAssignedXids.
    4475              :  *
    4476              :  * Called during recovery in analogy with and in place of ProcArrayEndTransaction()
    4477              :  */
    4478              : void
    4479        23004 : ExpireTreeKnownAssignedTransactionIds(TransactionId xid, int nsubxids,
    4480              :                                       TransactionId *subxids, TransactionId max_xid)
    4481              : {
    4482              :     Assert(standbyState >= STANDBY_INITIALIZED);
    4483              : 
    4484              :     /*
    4485              :      * Uses same locking as transaction commit
    4486              :      */
    4487        23004 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4488              : 
    4489        23004 :     KnownAssignedXidsRemoveTree(xid, nsubxids, subxids);
    4490              : 
    4491              :     /* As in ProcArrayEndTransaction, advance latestCompletedXid */
    4492        23004 :     MaintainLatestCompletedXidRecovery(max_xid);
    4493              : 
    4494              :     /* ... and xactCompletionCount */
    4495        23004 :     TransamVariables->xactCompletionCount++;
    4496              : 
    4497        23004 :     LWLockRelease(ProcArrayLock);
    4498        23004 : }
    4499              : 
    4500              : /*
    4501              :  * ExpireAllKnownAssignedTransactionIds
    4502              :  *      Remove all entries in KnownAssignedXids and reset lastOverflowedXid.
    4503              :  */
    4504              : void
    4505          114 : ExpireAllKnownAssignedTransactionIds(void)
    4506              : {
    4507              :     FullTransactionId latestXid;
    4508              : 
    4509          114 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4510          114 :     KnownAssignedXidsRemovePreceding(InvalidTransactionId);
    4511              : 
    4512              :     /* Reset latestCompletedXid to nextXid - 1 */
    4513              :     Assert(FullTransactionIdIsValid(TransamVariables->nextXid));
    4514          114 :     latestXid = TransamVariables->nextXid;
    4515          114 :     FullTransactionIdRetreat(&latestXid);
    4516          114 :     TransamVariables->latestCompletedXid = latestXid;
    4517              : 
    4518              :     /*
    4519              :      * Any transactions that were in-progress were effectively aborted, so
    4520              :      * advance xactCompletionCount.
    4521              :      */
    4522          114 :     TransamVariables->xactCompletionCount++;
    4523              : 
    4524              :     /*
    4525              :      * Reset lastOverflowedXid.  Currently, lastOverflowedXid has no use after
    4526              :      * the call of this function.  But do this for unification with what
    4527              :      * ExpireOldKnownAssignedTransactionIds() do.
    4528              :      */
    4529          114 :     procArray->lastOverflowedXid = InvalidTransactionId;
    4530          114 :     LWLockRelease(ProcArrayLock);
    4531          114 : }
    4532              : 
    4533              : /*
    4534              :  * ExpireOldKnownAssignedTransactionIds
    4535              :  *      Remove KnownAssignedXids entries preceding the given XID and
    4536              :  *      potentially reset lastOverflowedXid.
    4537              :  */
    4538              : void
    4539          826 : ExpireOldKnownAssignedTransactionIds(TransactionId xid)
    4540              : {
    4541              :     TransactionId latestXid;
    4542              : 
    4543          826 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4544              : 
    4545              :     /* As in ProcArrayEndTransaction, advance latestCompletedXid */
    4546          826 :     latestXid = xid;
    4547          826 :     TransactionIdRetreat(latestXid);
    4548          826 :     MaintainLatestCompletedXidRecovery(latestXid);
    4549              : 
    4550              :     /* ... and xactCompletionCount */
    4551          826 :     TransamVariables->xactCompletionCount++;
    4552              : 
    4553              :     /*
    4554              :      * Reset lastOverflowedXid if we know all transactions that have been
    4555              :      * possibly running are being gone.  Not doing so could cause an incorrect
    4556              :      * lastOverflowedXid value, which makes extra snapshots be marked as
    4557              :      * suboverflowed.
    4558              :      */
    4559          826 :     if (TransactionIdPrecedes(procArray->lastOverflowedXid, xid))
    4560          819 :         procArray->lastOverflowedXid = InvalidTransactionId;
    4561          826 :     KnownAssignedXidsRemovePreceding(xid);
    4562          826 :     LWLockRelease(ProcArrayLock);
    4563          826 : }
    4564              : 
    4565              : /*
    4566              :  * KnownAssignedTransactionIdsIdleMaintenance
    4567              :  *      Opportunistically do maintenance work when the startup process
    4568              :  *      is about to go idle.
    4569              :  */
    4570              : void
    4571        15030 : KnownAssignedTransactionIdsIdleMaintenance(void)
    4572              : {
    4573        15030 :     KnownAssignedXidsCompress(KAX_STARTUP_PROCESS_IDLE, false);
    4574        15030 : }
    4575              : 
    4576              : 
    4577              : /*
    4578              :  * Private module functions to manipulate KnownAssignedXids
    4579              :  *
    4580              :  * There are 5 main uses of the KnownAssignedXids data structure:
    4581              :  *
    4582              :  *  * backends taking snapshots - all valid XIDs need to be copied out
    4583              :  *  * backends seeking to determine presence of a specific XID
    4584              :  *  * startup process adding new known-assigned XIDs
    4585              :  *  * startup process removing specific XIDs as transactions end
    4586              :  *  * startup process pruning array when special WAL records arrive
    4587              :  *
    4588              :  * This data structure is known to be a hot spot during Hot Standby, so we
    4589              :  * go to some lengths to make these operations as efficient and as concurrent
    4590              :  * as possible.
    4591              :  *
    4592              :  * The XIDs are stored in an array in sorted order --- TransactionIdPrecedes
    4593              :  * order, to be exact --- to allow binary search for specific XIDs.  Note:
    4594              :  * in general TransactionIdPrecedes would not provide a total order, but
    4595              :  * we know that the entries present at any instant should not extend across
    4596              :  * a large enough fraction of XID space to wrap around (the primary would
    4597              :  * shut down for fear of XID wrap long before that happens).  So it's OK to
    4598              :  * use TransactionIdPrecedes as a binary-search comparator.
    4599              :  *
    4600              :  * It's cheap to maintain the sortedness during insertions, since new known
    4601              :  * XIDs are always reported in XID order; we just append them at the right.
    4602              :  *
    4603              :  * To keep individual deletions cheap, we need to allow gaps in the array.
    4604              :  * This is implemented by marking array elements as valid or invalid using
    4605              :  * the parallel boolean array KnownAssignedXidsValid[].  A deletion is done
    4606              :  * by setting KnownAssignedXidsValid[i] to false, *without* clearing the
    4607              :  * XID entry itself.  This preserves the property that the XID entries are
    4608              :  * sorted, so we can do binary searches easily.  Periodically we compress
    4609              :  * out the unused entries; that's much cheaper than having to compress the
    4610              :  * array immediately on every deletion.
    4611              :  *
    4612              :  * The actually valid items in KnownAssignedXids[] and KnownAssignedXidsValid[]
    4613              :  * are those with indexes tail <= i < head; items outside this subscript range
    4614              :  * have unspecified contents.  When head reaches the end of the array, we
    4615              :  * force compression of unused entries rather than wrapping around, since
    4616              :  * allowing wraparound would greatly complicate the search logic.  We maintain
    4617              :  * an explicit tail pointer so that pruning of old XIDs can be done without
    4618              :  * immediately moving the array contents.  In most cases only a small fraction
    4619              :  * of the array contains valid entries at any instant.
    4620              :  *
    4621              :  * Although only the startup process can ever change the KnownAssignedXids
    4622              :  * data structure, we still need interlocking so that standby backends will
    4623              :  * not observe invalid intermediate states.  The convention is that backends
    4624              :  * must hold shared ProcArrayLock to examine the array.  To remove XIDs from
    4625              :  * the array, the startup process must hold ProcArrayLock exclusively, for
    4626              :  * the usual transactional reasons (compare commit/abort of a transaction
    4627              :  * during normal running).  Compressing unused entries out of the array
    4628              :  * likewise requires exclusive lock.  To add XIDs to the array, we just insert
    4629              :  * them into slots to the right of the head pointer and then advance the head
    4630              :  * pointer.  This doesn't require any lock at all, but on machines with weak
    4631              :  * memory ordering, we need to be careful that other processors see the array
    4632              :  * element changes before they see the head pointer change.  We handle this by
    4633              :  * using memory barriers when reading or writing the head/tail pointers (unless
    4634              :  * the caller holds ProcArrayLock exclusively).
    4635              :  *
    4636              :  * Algorithmic analysis:
    4637              :  *
    4638              :  * If we have a maximum of M slots, with N XIDs currently spread across
    4639              :  * S elements then we have N <= S <= M always.
    4640              :  *
    4641              :  *  * Adding a new XID is O(1) and needs no lock (unless compression must
    4642              :  *      happen)
    4643              :  *  * Compressing the array is O(S) and requires exclusive lock
    4644              :  *  * Removing an XID is O(logS) and requires exclusive lock
    4645              :  *  * Taking a snapshot is O(S) and requires shared lock
    4646              :  *  * Checking for an XID is O(logS) and requires shared lock
    4647              :  *
    4648              :  * In comparison, using a hash table for KnownAssignedXids would mean that
    4649              :  * taking snapshots would be O(M). If we can maintain S << M then the
    4650              :  * sorted array technique will deliver significantly faster snapshots.
    4651              :  * If we try to keep S too small then we will spend too much time compressing,
    4652              :  * so there is an optimal point for any workload mix. We use a heuristic to
    4653              :  * decide when to compress the array, though trimming also helps reduce
    4654              :  * frequency of compressing. The heuristic requires us to track the number of
    4655              :  * currently valid XIDs in the array (N).  Except in special cases, we'll
    4656              :  * compress when S >= 2N.  Bounding S at 2N in turn bounds the time for
    4657              :  * taking a snapshot to be O(N), which it would have to be anyway.
    4658              :  */
    4659              : 
    4660              : 
    4661              : /*
    4662              :  * Compress KnownAssignedXids by shifting valid data down to the start of the
    4663              :  * array, removing any gaps.
    4664              :  *
    4665              :  * A compression step is forced if "reason" is KAX_NO_SPACE, otherwise
    4666              :  * we do it only if a heuristic indicates it's a good time to do it.
    4667              :  *
    4668              :  * Compression requires holding ProcArrayLock in exclusive mode.
    4669              :  * Caller must pass haveLock = true if it already holds the lock.
    4670              :  */
    4671              : static void
    4672        38881 : KnownAssignedXidsCompress(KAXCompressReason reason, bool haveLock)
    4673              : {
    4674        38881 :     ProcArrayStruct *pArray = procArray;
    4675              :     int         head,
    4676              :                 tail,
    4677              :                 nelements;
    4678              :     int         compress_index;
    4679              :     int         i;
    4680              : 
    4681              :     /* Counters for compression heuristics */
    4682              :     static unsigned int transactionEndsCounter;
    4683              :     static TimestampTz lastCompressTs;
    4684              : 
    4685              :     /* Tuning constants */
    4686              : #define KAX_COMPRESS_FREQUENCY 128  /* in transactions */
    4687              : #define KAX_COMPRESS_IDLE_INTERVAL 1000 /* in ms */
    4688              : 
    4689              :     /*
    4690              :      * Since only the startup process modifies the head/tail pointers, we
    4691              :      * don't need a lock to read them here.
    4692              :      */
    4693        38881 :     head = pArray->headKnownAssignedXids;
    4694        38881 :     tail = pArray->tailKnownAssignedXids;
    4695        38881 :     nelements = head - tail;
    4696              : 
    4697              :     /*
    4698              :      * If we can choose whether to compress, use a heuristic to avoid
    4699              :      * compressing too often or not often enough.  "Compress" here simply
    4700              :      * means moving the values to the beginning of the array, so it is not as
    4701              :      * complex or costly as typical data compression algorithms.
    4702              :      */
    4703        38881 :     if (nelements == pArray->numKnownAssignedXids)
    4704              :     {
    4705              :         /*
    4706              :          * When there are no gaps between head and tail, don't bother to
    4707              :          * compress, except in the KAX_NO_SPACE case where we must compress to
    4708              :          * create some space after the head.
    4709              :          */
    4710        21036 :         if (reason != KAX_NO_SPACE)
    4711        21036 :             return;
    4712              :     }
    4713        17845 :     else if (reason == KAX_TRANSACTION_END)
    4714              :     {
    4715              :         /*
    4716              :          * Consider compressing only once every so many commits.  Frequency
    4717              :          * determined by benchmarks.
    4718              :          */
    4719        12716 :         if ((transactionEndsCounter++) % KAX_COMPRESS_FREQUENCY != 0)
    4720        12607 :             return;
    4721              : 
    4722              :         /*
    4723              :          * Furthermore, compress only if the used part of the array is less
    4724              :          * than 50% full (see comments above).
    4725              :          */
    4726          109 :         if (nelements < 2 * pArray->numKnownAssignedXids)
    4727            9 :             return;
    4728              :     }
    4729         5129 :     else if (reason == KAX_STARTUP_PROCESS_IDLE)
    4730              :     {
    4731              :         /*
    4732              :          * We're about to go idle for lack of new WAL, so we might as well
    4733              :          * compress.  But not too often, to avoid ProcArray lock contention
    4734              :          * with readers.
    4735              :          */
    4736         5014 :         if (lastCompressTs != 0)
    4737              :         {
    4738              :             TimestampTz compress_after;
    4739              : 
    4740         5013 :             compress_after = TimestampTzPlusMilliseconds(lastCompressTs,
    4741              :                                                          KAX_COMPRESS_IDLE_INTERVAL);
    4742         5013 :             if (GetCurrentTimestamp() < compress_after)
    4743         4979 :                 return;
    4744              :         }
    4745              :     }
    4746              : 
    4747              :     /* Need to compress, so get the lock if we don't have it. */
    4748          250 :     if (!haveLock)
    4749           35 :         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    4750              : 
    4751              :     /*
    4752              :      * We compress the array by reading the valid values from tail to head,
    4753              :      * re-aligning data to 0th element.
    4754              :      */
    4755          250 :     compress_index = 0;
    4756         8604 :     for (i = tail; i < head; i++)
    4757              :     {
    4758         8354 :         if (KnownAssignedXidsValid[i])
    4759              :         {
    4760          864 :             KnownAssignedXids[compress_index] = KnownAssignedXids[i];
    4761          864 :             KnownAssignedXidsValid[compress_index] = true;
    4762          864 :             compress_index++;
    4763              :         }
    4764              :     }
    4765              :     Assert(compress_index == pArray->numKnownAssignedXids);
    4766              : 
    4767          250 :     pArray->tailKnownAssignedXids = 0;
    4768          250 :     pArray->headKnownAssignedXids = compress_index;
    4769              : 
    4770          250 :     if (!haveLock)
    4771           35 :         LWLockRelease(ProcArrayLock);
    4772              : 
    4773              :     /* Update timestamp for maintenance.  No need to hold lock for this. */
    4774          250 :     lastCompressTs = GetCurrentTimestamp();
    4775              : }
    4776              : 
    4777              : /*
    4778              :  * Add xids into KnownAssignedXids at the head of the array.
    4779              :  *
    4780              :  * xids from from_xid to to_xid, inclusive, are added to the array.
    4781              :  *
    4782              :  * If exclusive_lock is true then caller already holds ProcArrayLock in
    4783              :  * exclusive mode, so we need no extra locking here.  Else caller holds no
    4784              :  * lock, so we need to be sure we maintain sufficient interlocks against
    4785              :  * concurrent readers.  (Only the startup process ever calls this, so no need
    4786              :  * to worry about concurrent writers.)
    4787              :  */
    4788              : static void
    4789        23806 : KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid,
    4790              :                      bool exclusive_lock)
    4791              : {
    4792        23806 :     ProcArrayStruct *pArray = procArray;
    4793              :     TransactionId next_xid;
    4794              :     int         head,
    4795              :                 tail;
    4796              :     int         nxids;
    4797              :     int         i;
    4798              : 
    4799              :     Assert(TransactionIdPrecedesOrEquals(from_xid, to_xid));
    4800              : 
    4801              :     /*
    4802              :      * Calculate how many array slots we'll need.  Normally this is cheap; in
    4803              :      * the unusual case where the XIDs cross the wrap point, we do it the hard
    4804              :      * way.
    4805              :      */
    4806        23806 :     if (to_xid >= from_xid)
    4807        23806 :         nxids = to_xid - from_xid + 1;
    4808              :     else
    4809              :     {
    4810            0 :         nxids = 1;
    4811            0 :         next_xid = from_xid;
    4812            0 :         while (TransactionIdPrecedes(next_xid, to_xid))
    4813              :         {
    4814            0 :             nxids++;
    4815            0 :             TransactionIdAdvance(next_xid);
    4816              :         }
    4817              :     }
    4818              : 
    4819              :     /*
    4820              :      * Since only the startup process modifies the head/tail pointers, we
    4821              :      * don't need a lock to read them here.
    4822              :      */
    4823        23806 :     head = pArray->headKnownAssignedXids;
    4824        23806 :     tail = pArray->tailKnownAssignedXids;
    4825              : 
    4826              :     Assert(head >= 0 && head <= pArray->maxKnownAssignedXids);
    4827              :     Assert(tail >= 0 && tail < pArray->maxKnownAssignedXids);
    4828              : 
    4829              :     /*
    4830              :      * Verify that insertions occur in TransactionId sequence.  Note that even
    4831              :      * if the last existing element is marked invalid, it must still have a
    4832              :      * correctly sequenced XID value.
    4833              :      */
    4834        38022 :     if (head > tail &&
    4835        14216 :         TransactionIdFollowsOrEquals(KnownAssignedXids[head - 1], from_xid))
    4836              :     {
    4837            0 :         KnownAssignedXidsDisplay(LOG);
    4838            0 :         elog(ERROR, "out-of-order XID insertion in KnownAssignedXids");
    4839              :     }
    4840              : 
    4841              :     /*
    4842              :      * If our xids won't fit in the remaining space, compress out free space
    4843              :      */
    4844        23806 :     if (head + nxids > pArray->maxKnownAssignedXids)
    4845              :     {
    4846            0 :         KnownAssignedXidsCompress(KAX_NO_SPACE, exclusive_lock);
    4847              : 
    4848            0 :         head = pArray->headKnownAssignedXids;
    4849              :         /* note: we no longer care about the tail pointer */
    4850              : 
    4851              :         /*
    4852              :          * If it still won't fit then we're out of memory
    4853              :          */
    4854            0 :         if (head + nxids > pArray->maxKnownAssignedXids)
    4855            0 :             elog(ERROR, "too many KnownAssignedXids");
    4856              :     }
    4857              : 
    4858              :     /* Now we can insert the xids into the space starting at head */
    4859        23806 :     next_xid = from_xid;
    4860        48344 :     for (i = 0; i < nxids; i++)
    4861              :     {
    4862        24538 :         KnownAssignedXids[head] = next_xid;
    4863        24538 :         KnownAssignedXidsValid[head] = true;
    4864        24538 :         TransactionIdAdvance(next_xid);
    4865        24538 :         head++;
    4866              :     }
    4867              : 
    4868              :     /* Adjust count of number of valid entries */
    4869        23806 :     pArray->numKnownAssignedXids += nxids;
    4870              : 
    4871              :     /*
    4872              :      * Now update the head pointer.  We use a write barrier to ensure that
    4873              :      * other processors see the above array updates before they see the head
    4874              :      * pointer change.  The barrier isn't required if we're holding
    4875              :      * ProcArrayLock exclusively.
    4876              :      */
    4877        23806 :     if (!exclusive_lock)
    4878        23801 :         pg_write_barrier();
    4879              : 
    4880        23806 :     pArray->headKnownAssignedXids = head;
    4881        23806 : }
    4882              : 
    4883              : /*
    4884              :  * KnownAssignedXidsSearch
    4885              :  *
    4886              :  * Searches KnownAssignedXids for a specific xid and optionally removes it.
    4887              :  * Returns true if it was found, false if not.
    4888              :  *
    4889              :  * Caller must hold ProcArrayLock in shared or exclusive mode.
    4890              :  * Exclusive lock must be held for remove = true.
    4891              :  */
    4892              : static bool
    4893        25673 : KnownAssignedXidsSearch(TransactionId xid, bool remove)
    4894              : {
    4895        25673 :     ProcArrayStruct *pArray = procArray;
    4896              :     int         first,
    4897              :                 last;
    4898              :     int         head;
    4899              :     int         tail;
    4900        25673 :     int         result_index = -1;
    4901              : 
    4902        25673 :     tail = pArray->tailKnownAssignedXids;
    4903        25673 :     head = pArray->headKnownAssignedXids;
    4904              : 
    4905              :     /*
    4906              :      * Only the startup process removes entries, so we don't need the read
    4907              :      * barrier in that case.
    4908              :      */
    4909        25673 :     if (!remove)
    4910            1 :         pg_read_barrier();      /* pairs with KnownAssignedXidsAdd */
    4911              : 
    4912              :     /*
    4913              :      * Standard binary search.  Note we can ignore the KnownAssignedXidsValid
    4914              :      * array here, since even invalid entries will contain sorted XIDs.
    4915              :      */
    4916        25673 :     first = tail;
    4917        25673 :     last = head - 1;
    4918        80939 :     while (first <= last)
    4919              :     {
    4920              :         int         mid_index;
    4921              :         TransactionId mid_xid;
    4922              : 
    4923        79753 :         mid_index = (first + last) / 2;
    4924        79753 :         mid_xid = KnownAssignedXids[mid_index];
    4925              : 
    4926        79753 :         if (xid == mid_xid)
    4927              :         {
    4928        24487 :             result_index = mid_index;
    4929        24487 :             break;
    4930              :         }
    4931        55266 :         else if (TransactionIdPrecedes(xid, mid_xid))
    4932        12401 :             last = mid_index - 1;
    4933              :         else
    4934        42865 :             first = mid_index + 1;
    4935              :     }
    4936              : 
    4937        25673 :     if (result_index < 0)
    4938         1186 :         return false;           /* not in array */
    4939              : 
    4940        24487 :     if (!KnownAssignedXidsValid[result_index])
    4941           35 :         return false;           /* in array, but invalid */
    4942              : 
    4943        24452 :     if (remove)
    4944              :     {
    4945        24452 :         KnownAssignedXidsValid[result_index] = false;
    4946              : 
    4947        24452 :         pArray->numKnownAssignedXids--;
    4948              :         Assert(pArray->numKnownAssignedXids >= 0);
    4949              : 
    4950              :         /*
    4951              :          * If we're removing the tail element then advance tail pointer over
    4952              :          * any invalid elements.  This will speed future searches.
    4953              :          */
    4954        24452 :         if (result_index == tail)
    4955              :         {
    4956        10806 :             tail++;
    4957        16962 :             while (tail < head && !KnownAssignedXidsValid[tail])
    4958         6156 :                 tail++;
    4959        10806 :             if (tail >= head)
    4960              :             {
    4961              :                 /* Array is empty, so we can reset both pointers */
    4962         9580 :                 pArray->headKnownAssignedXids = 0;
    4963         9580 :                 pArray->tailKnownAssignedXids = 0;
    4964              :             }
    4965              :             else
    4966              :             {
    4967         1226 :                 pArray->tailKnownAssignedXids = tail;
    4968              :             }
    4969              :         }
    4970              :     }
    4971              : 
    4972        24452 :     return true;
    4973              : }
    4974              : 
    4975              : /*
    4976              :  * Is the specified XID present in KnownAssignedXids[]?
    4977              :  *
    4978              :  * Caller must hold ProcArrayLock in shared or exclusive mode.
    4979              :  */
    4980              : static bool
    4981            1 : KnownAssignedXidExists(TransactionId xid)
    4982              : {
    4983              :     Assert(TransactionIdIsValid(xid));
    4984              : 
    4985            1 :     return KnownAssignedXidsSearch(xid, false);
    4986              : }
    4987              : 
    4988              : /*
    4989              :  * Remove the specified XID from KnownAssignedXids[].
    4990              :  *
    4991              :  * Caller must hold ProcArrayLock in exclusive mode.
    4992              :  */
    4993              : static void
    4994        25672 : KnownAssignedXidsRemove(TransactionId xid)
    4995              : {
    4996              :     Assert(TransactionIdIsValid(xid));
    4997              : 
    4998        25672 :     elog(DEBUG4, "remove KnownAssignedXid %u", xid);
    4999              : 
    5000              :     /*
    5001              :      * Note: we cannot consider it an error to remove an XID that's not
    5002              :      * present.  We intentionally remove subxact IDs while processing
    5003              :      * XLOG_XACT_ASSIGNMENT, to avoid array overflow.  Then those XIDs will be
    5004              :      * removed again when the top-level xact commits or aborts.
    5005              :      *
    5006              :      * It might be possible to track such XIDs to distinguish this case from
    5007              :      * actual errors, but it would be complicated and probably not worth it.
    5008              :      * So, just ignore the search result.
    5009              :      */
    5010        25672 :     (void) KnownAssignedXidsSearch(xid, true);
    5011        25672 : }
    5012              : 
    5013              : /*
    5014              :  * KnownAssignedXidsRemoveTree
    5015              :  *      Remove xid (if it's not InvalidTransactionId) and all the subxids.
    5016              :  *
    5017              :  * Caller must hold ProcArrayLock in exclusive mode.
    5018              :  */
    5019              : static void
    5020        23025 : KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids,
    5021              :                             TransactionId *subxids)
    5022              : {
    5023              :     int         i;
    5024              : 
    5025        23025 :     if (TransactionIdIsValid(xid))
    5026        23004 :         KnownAssignedXidsRemove(xid);
    5027              : 
    5028        25693 :     for (i = 0; i < nsubxids; i++)
    5029         2668 :         KnownAssignedXidsRemove(subxids[i]);
    5030              : 
    5031              :     /* Opportunistically compress the array */
    5032        23025 :     KnownAssignedXidsCompress(KAX_TRANSACTION_END, true);
    5033        23025 : }
    5034              : 
    5035              : /*
    5036              :  * Prune KnownAssignedXids up to, but *not* including xid. If xid is invalid
    5037              :  * then clear the whole table.
    5038              :  *
    5039              :  * Caller must hold ProcArrayLock in exclusive mode.
    5040              :  */
    5041              : static void
    5042          940 : KnownAssignedXidsRemovePreceding(TransactionId removeXid)
    5043              : {
    5044          940 :     ProcArrayStruct *pArray = procArray;
    5045          940 :     int         count = 0;
    5046              :     int         head,
    5047              :                 tail,
    5048              :                 i;
    5049              : 
    5050          940 :     if (!TransactionIdIsValid(removeXid))
    5051              :     {
    5052          114 :         elog(DEBUG4, "removing all KnownAssignedXids");
    5053          114 :         pArray->numKnownAssignedXids = 0;
    5054          114 :         pArray->headKnownAssignedXids = pArray->tailKnownAssignedXids = 0;
    5055          114 :         return;
    5056              :     }
    5057              : 
    5058          826 :     elog(DEBUG4, "prune KnownAssignedXids to %u", removeXid);
    5059              : 
    5060              :     /*
    5061              :      * Mark entries invalid starting at the tail.  Since array is sorted, we
    5062              :      * can stop as soon as we reach an entry >= removeXid.
    5063              :      */
    5064          826 :     tail = pArray->tailKnownAssignedXids;
    5065          826 :     head = pArray->headKnownAssignedXids;
    5066              : 
    5067          826 :     for (i = tail; i < head; i++)
    5068              :     {
    5069          195 :         if (KnownAssignedXidsValid[i])
    5070              :         {
    5071          195 :             TransactionId knownXid = KnownAssignedXids[i];
    5072              : 
    5073          195 :             if (TransactionIdFollowsOrEquals(knownXid, removeXid))
    5074          195 :                 break;
    5075              : 
    5076            0 :             if (!StandbyTransactionIdIsPrepared(knownXid))
    5077              :             {
    5078            0 :                 KnownAssignedXidsValid[i] = false;
    5079            0 :                 count++;
    5080              :             }
    5081              :         }
    5082              :     }
    5083              : 
    5084          826 :     pArray->numKnownAssignedXids -= count;
    5085              :     Assert(pArray->numKnownAssignedXids >= 0);
    5086              : 
    5087              :     /*
    5088              :      * Advance the tail pointer if we've marked the tail item invalid.
    5089              :      */
    5090          826 :     for (i = tail; i < head; i++)
    5091              :     {
    5092          195 :         if (KnownAssignedXidsValid[i])
    5093          195 :             break;
    5094              :     }
    5095          826 :     if (i >= head)
    5096              :     {
    5097              :         /* Array is empty, so we can reset both pointers */
    5098          631 :         pArray->headKnownAssignedXids = 0;
    5099          631 :         pArray->tailKnownAssignedXids = 0;
    5100              :     }
    5101              :     else
    5102              :     {
    5103          195 :         pArray->tailKnownAssignedXids = i;
    5104              :     }
    5105              : 
    5106              :     /* Opportunistically compress the array */
    5107          826 :     KnownAssignedXidsCompress(KAX_PRUNE, true);
    5108              : }
    5109              : 
    5110              : /*
    5111              :  * KnownAssignedXidsGet - Get an array of xids by scanning KnownAssignedXids.
    5112              :  * We filter out anything >= xmax.
    5113              :  *
    5114              :  * Returns the number of XIDs stored into xarray[].  Caller is responsible
    5115              :  * that array is large enough.
    5116              :  *
    5117              :  * Caller must hold ProcArrayLock in (at least) shared mode.
    5118              :  */
    5119              : static int
    5120            0 : KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax)
    5121              : {
    5122            0 :     TransactionId xtmp = InvalidTransactionId;
    5123              : 
    5124            0 :     return KnownAssignedXidsGetAndSetXmin(xarray, &xtmp, xmax);
    5125              : }
    5126              : 
    5127              : /*
    5128              :  * KnownAssignedXidsGetAndSetXmin - as KnownAssignedXidsGet, plus
    5129              :  * we reduce *xmin to the lowest xid value seen if not already lower.
    5130              :  *
    5131              :  * Caller must hold ProcArrayLock in (at least) shared mode.
    5132              :  */
    5133              : static int
    5134         1288 : KnownAssignedXidsGetAndSetXmin(TransactionId *xarray, TransactionId *xmin,
    5135              :                                TransactionId xmax)
    5136              : {
    5137         1288 :     int         count = 0;
    5138              :     int         head,
    5139              :                 tail;
    5140              :     int         i;
    5141              : 
    5142              :     /*
    5143              :      * Fetch head just once, since it may change while we loop. We can stop
    5144              :      * once we reach the initially seen head, since we are certain that an xid
    5145              :      * cannot enter and then leave the array while we hold ProcArrayLock.  We
    5146              :      * might miss newly-added xids, but they should be >= xmax so irrelevant
    5147              :      * anyway.
    5148              :      */
    5149         1288 :     tail = procArray->tailKnownAssignedXids;
    5150         1288 :     head = procArray->headKnownAssignedXids;
    5151              : 
    5152         1288 :     pg_read_barrier();          /* pairs with KnownAssignedXidsAdd */
    5153              : 
    5154         1312 :     for (i = tail; i < head; i++)
    5155              :     {
    5156              :         /* Skip any gaps in the array */
    5157          147 :         if (KnownAssignedXidsValid[i])
    5158              :         {
    5159          137 :             TransactionId knownXid = KnownAssignedXids[i];
    5160              : 
    5161              :             /*
    5162              :              * Update xmin if required.  Only the first XID need be checked,
    5163              :              * since the array is sorted.
    5164              :              */
    5165          274 :             if (count == 0 &&
    5166          137 :                 TransactionIdPrecedes(knownXid, *xmin))
    5167           14 :                 *xmin = knownXid;
    5168              : 
    5169              :             /*
    5170              :              * Filter out anything >= xmax, again relying on sorted property
    5171              :              * of array.
    5172              :              */
    5173          274 :             if (TransactionIdIsValid(xmax) &&
    5174          137 :                 TransactionIdFollowsOrEquals(knownXid, xmax))
    5175          123 :                 break;
    5176              : 
    5177              :             /* Add knownXid into output array */
    5178           14 :             xarray[count++] = knownXid;
    5179              :         }
    5180              :     }
    5181              : 
    5182         1288 :     return count;
    5183              : }
    5184              : 
    5185              : /*
    5186              :  * Get oldest XID in the KnownAssignedXids array, or InvalidTransactionId
    5187              :  * if nothing there.
    5188              :  */
    5189              : static TransactionId
    5190          373 : KnownAssignedXidsGetOldestXmin(void)
    5191              : {
    5192              :     int         head,
    5193              :                 tail;
    5194              :     int         i;
    5195              : 
    5196              :     /*
    5197              :      * Fetch head just once, since it may change while we loop.
    5198              :      */
    5199          373 :     tail = procArray->tailKnownAssignedXids;
    5200          373 :     head = procArray->headKnownAssignedXids;
    5201              : 
    5202          373 :     pg_read_barrier();          /* pairs with KnownAssignedXidsAdd */
    5203              : 
    5204          373 :     for (i = tail; i < head; i++)
    5205              :     {
    5206              :         /* Skip any gaps in the array */
    5207          147 :         if (KnownAssignedXidsValid[i])
    5208          147 :             return KnownAssignedXids[i];
    5209              :     }
    5210              : 
    5211          226 :     return InvalidTransactionId;
    5212              : }
    5213              : 
    5214              : /*
    5215              :  * Display KnownAssignedXids to provide debug trail
    5216              :  *
    5217              :  * Currently this is only called within startup process, so we need no
    5218              :  * special locking.
    5219              :  *
    5220              :  * Note this is pretty expensive, and much of the expense will be incurred
    5221              :  * even if the elog message will get discarded.  It's not currently called
    5222              :  * in any performance-critical places, however, so no need to be tenser.
    5223              :  */
    5224              : static void
    5225          119 : KnownAssignedXidsDisplay(int trace_level)
    5226              : {
    5227          119 :     ProcArrayStruct *pArray = procArray;
    5228              :     StringInfoData buf;
    5229              :     int         head,
    5230              :                 tail,
    5231              :                 i;
    5232          119 :     int         nxids = 0;
    5233              : 
    5234          119 :     tail = pArray->tailKnownAssignedXids;
    5235          119 :     head = pArray->headKnownAssignedXids;
    5236              : 
    5237          119 :     initStringInfo(&buf);
    5238              : 
    5239          129 :     for (i = tail; i < head; i++)
    5240              :     {
    5241           10 :         if (KnownAssignedXidsValid[i])
    5242              :         {
    5243           10 :             nxids++;
    5244           10 :             appendStringInfo(&buf, "[%d]=%u ", i, KnownAssignedXids[i]);
    5245              :         }
    5246              :     }
    5247              : 
    5248          119 :     elog(trace_level, "%d KnownAssignedXids (num=%d tail=%d head=%d) %s",
    5249              :          nxids,
    5250              :          pArray->numKnownAssignedXids,
    5251              :          pArray->tailKnownAssignedXids,
    5252              :          pArray->headKnownAssignedXids,
    5253              :          buf.data);
    5254              : 
    5255          119 :     pfree(buf.data);
    5256          119 : }
    5257              : 
    5258              : /*
    5259              :  * KnownAssignedXidsReset
    5260              :  *      Resets KnownAssignedXids to be empty
    5261              :  */
    5262              : static void
    5263            0 : KnownAssignedXidsReset(void)
    5264              : {
    5265            0 :     ProcArrayStruct *pArray = procArray;
    5266              : 
    5267            0 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    5268              : 
    5269            0 :     pArray->numKnownAssignedXids = 0;
    5270            0 :     pArray->tailKnownAssignedXids = 0;
    5271            0 :     pArray->headKnownAssignedXids = 0;
    5272              : 
    5273            0 :     LWLockRelease(ProcArrayLock);
    5274            0 : }
        

Generated by: LCOV version 2.0-1