LCOV - differential code coverage report
Current view: top level - src/backend/storage/ipc - procarray.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GIC GNC CBC DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 88.0 % 1429 1257 9 12 151 7 2 69 1179 22 64
Current Date: 2026-05-05 10:23:31 +0900 Functions: 91.0 % 78 71 3 1 3 19 52 1 8
Baseline: lcov-20260505-025707-baseline Branches: 63.3 % 1004 636 12 13 343 10 2 26 598 18 12
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 77.8 % 27 21 6 21
(30,360] days: 94.1 % 51 48 3 48
(360..) days: 87.9 % 1351 1188 12 151 7 2 1179
Function coverage date bins:
(7,30] days: 75.0 % 4 3 1 3
(30,360] days: 100.0 % 6 6 6
(360..) days: 91.2 % 68 62 2 1 3 10 52
Branch coverage date bins:
(7,30] days: 62.5 % 8 5 3 5
(30,360] days: 70.0 % 30 21 9 21
(360..) days: 63.1 % 966 610 13 343 10 2 598

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

Generated by: LCOV version 2.5.0-beta