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

Generated by: LCOV version 2.0-1