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

Generated by: LCOV version 1.13