LCOV - differential code coverage report
Current view: top level - src/backend/storage/ipc - procarray.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 86.1 % 1433 1234 6 11 182 20 97 1117 9 77
Current Date: 2024-04-14 14:21:10 Functions: 88.6 % 79 70 2 7 1 33 36 1
Baseline: 16@8cea358b128 Branches: 61.4 % 986 605 27 4 350 16 39 550
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 96.0 % 50 48 2 48
(60,120] days: 100.0 % 4 4 4
(120,180] days: 91.2 % 34 31 3 31
(180,240] days: 93.3 % 15 14 1 14
(240..) days: 85.5 % 1330 1137 11 182 20 1117
Function coverage date bins:
[..60] days: 100.0 % 2 2 2
(240..) days: 88.3 % 77 68 2 7 1 31 36
Branch coverage date bins:
[..60] days: 68.4 % 38 26 12 26
(60,120] days: 50.0 % 4 2 2 2
(120,180] days: 40.0 % 20 8 12 8
(180,240] days: 75.0 % 4 3 1 3
(240..) days: 61.5 % 920 566 4 350 16 550

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

Generated by: LCOV version 2.1-beta2-3-g6141622