PostgreSQL Source Code  git master
procarray.h File Reference
#include "storage/lock.h"
#include "storage/standby.h"
#include "utils/relcache.h"
#include "utils/snapshot.h"
Include dependency graph for procarray.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define PROCARRAY_VACUUM_FLAG
 
#define PROCARRAY_ANALYZE_FLAG
 
#define PROCARRAY_LOGICAL_DECODING_FLAG
 
#define PROCARRAY_SLOTS_XMIN
 
#define PROCARRAY_PROC_FLAGS_MASK
 
#define PROCARRAY_FLAGS_DEFAULT   PROCARRAY_LOGICAL_DECODING_FLAG
 
#define PROCARRAY_FLAGS_VACUUM   PROCARRAY_FLAGS_DEFAULT | PROCARRAY_VACUUM_FLAG
 
#define PROCARRAY_FLAGS_ANALYZE   PROCARRAY_FLAGS_DEFAULT | PROCARRAY_ANALYZE_FLAG
 
#define PROCARRAY_FLAGS_VACUUM_ANALYZE   PROCARRAY_FLAGS_DEFAULT | PROCARRAY_VACUUM_FLAG | PROCARRAY_ANALYZE_FLAG
 

Functions

Size ProcArrayShmemSize (void)
 
void CreateSharedProcArray (void)
 
void ProcArrayAdd (PGPROC *proc)
 
void ProcArrayRemove (PGPROC *proc, TransactionId latestXid)
 
void ProcArrayEndTransaction (PGPROC *proc, TransactionId latestXid)
 
void ProcArrayClearTransaction (PGPROC *proc)
 
void ProcArrayInitRecovery (TransactionId initializedUptoXID)
 
void ProcArrayApplyRecoveryInfo (RunningTransactions running)
 
void ProcArrayApplyXidAssignment (TransactionId topxid, int nsubxids, TransactionId *subxids)
 
void RecordKnownAssignedTransactionIds (TransactionId xid)
 
void ExpireTreeKnownAssignedTransactionIds (TransactionId xid, int nsubxids, TransactionId *subxids, TransactionId max_xid)
 
void ExpireAllKnownAssignedTransactionIds (void)
 
void ExpireOldKnownAssignedTransactionIds (TransactionId xid)
 
int GetMaxSnapshotXidCount (void)
 
int GetMaxSnapshotSubxidCount (void)
 
Snapshot GetSnapshotData (Snapshot snapshot)
 
bool ProcArrayInstallImportedXmin (TransactionId xmin, VirtualTransactionId *sourcevxid)
 
bool ProcArrayInstallRestoredXmin (TransactionId xmin, PGPROC *proc)
 
RunningTransactions GetRunningTransactionData (void)
 
bool TransactionIdIsInProgress (TransactionId xid)
 
bool TransactionIdIsActive (TransactionId xid)
 
TransactionId GetOldestXmin (Relation rel, int flags)
 
TransactionId GetOldestActiveTransactionId (void)
 
TransactionId GetOldestSafeDecodingTransactionId (bool catalogOnly)
 
VirtualTransactionIdGetVirtualXIDsDelayingChkpt (int *nvxids)
 
bool HaveVirtualXIDsDelayingChkpt (VirtualTransactionId *vxids, int nvxids)
 
PGPROCBackendPidGetProc (int pid)
 
PGPROCBackendPidGetProcWithLock (int pid)
 
int BackendXidGetPid (TransactionId xid)
 
bool IsBackendPid (int pid)
 
VirtualTransactionIdGetCurrentVirtualXIDs (TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
 
VirtualTransactionIdGetConflictingVirtualXIDs (TransactionId limitXmin, Oid dbOid)
 
pid_t CancelVirtualTransaction (VirtualTransactionId vxid, ProcSignalReason sigmode)
 
bool MinimumActiveBackends (int min)
 
int CountDBBackends (Oid databaseid)
 
int CountDBConnections (Oid databaseid)
 
void CancelDBBackends (Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 
int CountUserBackends (Oid roleid)
 
bool CountOtherDBBackends (Oid databaseId, int *nbackends, int *nprepared)
 
void TerminateOtherDBBackends (Oid databaseId)
 
void XidCacheRemoveRunningXids (TransactionId xid, int nxids, const TransactionId *xids, TransactionId latestXid)
 
void ProcArraySetReplicationSlotXmin (TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
 
void ProcArrayGetReplicationSlotXmin (TransactionId *xmin, TransactionId *catalog_xmin)
 

Macro Definition Documentation

◆ PROCARRAY_ANALYZE_FLAG

#define PROCARRAY_ANALYZE_FLAG
Value:
0x04 /* currently running
* analyze */

Definition at line 32 of file procarray.h.

◆ PROCARRAY_FLAGS_ANALYZE

#define PROCARRAY_FLAGS_ANALYZE   PROCARRAY_FLAGS_DEFAULT | PROCARRAY_ANALYZE_FLAG

Definition at line 54 of file procarray.h.

◆ PROCARRAY_FLAGS_DEFAULT

#define PROCARRAY_FLAGS_DEFAULT   PROCARRAY_LOGICAL_DECODING_FLAG

Definition at line 50 of file procarray.h.

Referenced by CreateCheckPoint(), CreateRestartPoint(), and XLogWalRcvSendHSFeedback().

◆ PROCARRAY_FLAGS_VACUUM

◆ PROCARRAY_FLAGS_VACUUM_ANALYZE

#define PROCARRAY_FLAGS_VACUUM_ANALYZE   PROCARRAY_FLAGS_DEFAULT | PROCARRAY_VACUUM_FLAG | PROCARRAY_ANALYZE_FLAG

Definition at line 56 of file procarray.h.

◆ PROCARRAY_LOGICAL_DECODING_FLAG

#define PROCARRAY_LOGICAL_DECODING_FLAG
Value:
0x10 /* currently doing logical
* decoding outside xact */

Definition at line 34 of file procarray.h.

◆ PROCARRAY_PROC_FLAGS_MASK

#define PROCARRAY_PROC_FLAGS_MASK
Value:
PROCARRAY_ANALYZE_FLAG | \
PROCARRAY_LOGICAL_DECODING_FLAG)
#define PROCARRAY_VACUUM_FLAG
Definition: procarray.h:30

Definition at line 44 of file procarray.h.

Referenced by GetOldestXmin().

◆ PROCARRAY_SLOTS_XMIN

#define PROCARRAY_SLOTS_XMIN
Value:
0x20 /* replication slot xmin,
* catalog_xmin */

Definition at line 37 of file procarray.h.

Referenced by GetOldestXmin(), and XLogWalRcvSendHSFeedback().

◆ PROCARRAY_VACUUM_FLAG

#define PROCARRAY_VACUUM_FLAG
Value:
0x02 /* currently running lazy
* vacuum */

Definition at line 30 of file procarray.h.

Function Documentation

◆ BackendPidGetProc()

PGPROC* BackendPidGetProc ( int  pid)

Definition at line 2365 of file procarray.c.

References BackendPidGetProcWithLock(), LW_SHARED, LWLockAcquire(), and LWLockRelease().

Referenced by IsBackendPid(), pg_signal_backend(), pg_stat_get_activity(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), ProcSendSignal(), TerminateOtherDBBackends(), and test_shm_mq_main().

2366 {
2367  PGPROC *result;
2368 
2369  if (pid == 0) /* never match dummy PGPROCs */
2370  return NULL;
2371 
2372  LWLockAcquire(ProcArrayLock, LW_SHARED);
2373 
2374  result = BackendPidGetProcWithLock(pid);
2375 
2376  LWLockRelease(ProcArrayLock);
2377 
2378  return result;
2379 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
PGPROC * BackendPidGetProcWithLock(int pid)
Definition: procarray.c:2388
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95

◆ BackendPidGetProcWithLock()

PGPROC* BackendPidGetProcWithLock ( int  pid)

Definition at line 2388 of file procarray.c.

References ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, and procArray.

Referenced by BackendPidGetProc(), and GetBlockerStatusData().

2389 {
2390  PGPROC *result = NULL;
2391  ProcArrayStruct *arrayP = procArray;
2392  int index;
2393 
2394  if (pid == 0) /* never match dummy PGPROCs */
2395  return NULL;
2396 
2397  for (index = 0; index < arrayP->numProcs; index++)
2398  {
2399  PGPROC *proc = &allProcs[arrayP->pgprocnos[index]];
2400 
2401  if (proc->pid == pid)
2402  {
2403  result = proc;
2404  break;
2405  }
2406  }
2407 
2408  return result;
2409 }
Definition: type.h:89
static PGPROC * allProcs
Definition: procarray.c:103
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ BackendXidGetPid()

int BackendXidGetPid ( TransactionId  xid)

Definition at line 2425 of file procarray.c.

References InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, and PGXACT::xid.

Referenced by pgrowlocks().

2426 {
2427  int result = 0;
2428  ProcArrayStruct *arrayP = procArray;
2429  int index;
2430 
2431  if (xid == InvalidTransactionId) /* never match invalid xid */
2432  return 0;
2433 
2434  LWLockAcquire(ProcArrayLock, LW_SHARED);
2435 
2436  for (index = 0; index < arrayP->numProcs; index++)
2437  {
2438  int pgprocno = arrayP->pgprocnos[index];
2439  PGPROC *proc = &allProcs[pgprocno];
2440  PGXACT *pgxact = &allPgXact[pgprocno];
2441 
2442  if (pgxact->xid == xid)
2443  {
2444  result = proc->pid;
2445  break;
2446  }
2447  }
2448 
2449  LWLockRelease(ProcArrayLock);
2450 
2451  return result;
2452 }
Definition: proc.h:222
TransactionId xid
Definition: proc.h:224
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define InvalidTransactionId
Definition: transam.h:31
static PGPROC * allProcs
Definition: procarray.c:103
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CancelDBBackends()

void CancelDBBackends ( Oid  databaseid,
ProcSignalReason  sigmode,
bool  conflictPending 
)

Definition at line 2819 of file procarray.c.

References VirtualTransactionId::backendId, PGPROC::databaseId, GET_VXID_FROM_PGPROC, InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, PGPROC::recoveryConflictPending, and SendProcSignal().

Referenced by ResolveRecoveryConflictWithDatabase(), and SendRecoveryConflictWithBufferPin().

2820 {
2821  ProcArrayStruct *arrayP = procArray;
2822  int index;
2823  pid_t pid = 0;
2824 
2825  /* tell all backends to die */
2826  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2827 
2828  for (index = 0; index < arrayP->numProcs; index++)
2829  {
2830  int pgprocno = arrayP->pgprocnos[index];
2831  PGPROC *proc = &allProcs[pgprocno];
2832 
2833  if (databaseid == InvalidOid || proc->databaseId == databaseid)
2834  {
2835  VirtualTransactionId procvxid;
2836 
2837  GET_VXID_FROM_PGPROC(procvxid, *proc);
2838 
2839  proc->recoveryConflictPending = conflictPending;
2840  pid = proc->pid;
2841  if (pid != 0)
2842  {
2843  /*
2844  * Kill the pid if it's still here. If not, that's what we
2845  * wanted so ignore any errors.
2846  */
2847  (void) SendProcSignal(pid, sigmode, procvxid.backendId);
2848  }
2849  }
2850  }
2851 
2852  LWLockRelease(ProcArrayLock);
2853 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:179
bool recoveryConflictPending
Definition: proc.h:127
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define InvalidOid
Definition: postgres_ext.h:36
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
BackendId backendId
Definition: lock.h:64
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CancelVirtualTransaction()

pid_t CancelVirtualTransaction ( VirtualTransactionId  vxid,
ProcSignalReason  sigmode 
)

Definition at line 2656 of file procarray.c.

References VirtualTransactionId::backendId, GET_VXID_FROM_PGPROC, VirtualTransactionId::localTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, PGPROC::recoveryConflictPending, and SendProcSignal().

Referenced by ResolveRecoveryConflictWithVirtualXIDs().

2657 {
2658  ProcArrayStruct *arrayP = procArray;
2659  int index;
2660  pid_t pid = 0;
2661 
2662  LWLockAcquire(ProcArrayLock, LW_SHARED);
2663 
2664  for (index = 0; index < arrayP->numProcs; index++)
2665  {
2666  int pgprocno = arrayP->pgprocnos[index];
2667  PGPROC *proc = &allProcs[pgprocno];
2668  VirtualTransactionId procvxid;
2669 
2670  GET_VXID_FROM_PGPROC(procvxid, *proc);
2671 
2672  if (procvxid.backendId == vxid.backendId &&
2673  procvxid.localTransactionId == vxid.localTransactionId)
2674  {
2675  proc->recoveryConflictPending = true;
2676  pid = proc->pid;
2677  if (pid != 0)
2678  {
2679  /*
2680  * Kill the pid if it's still here. If not, that's what we
2681  * wanted so ignore any errors.
2682  */
2683  (void) SendProcSignal(pid, sigmode, vxid.backendId);
2684  }
2685  break;
2686  }
2687  }
2688 
2689  LWLockRelease(ProcArrayLock);
2690 
2691  return pid;
2692 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
LocalTransactionId localTransactionId
Definition: lock.h:65
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:179
bool recoveryConflictPending
Definition: proc.h:127
static PGPROC * allProcs
Definition: procarray.c:103
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
BackendId backendId
Definition: lock.h:64
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CountDBBackends()

int CountDBBackends ( Oid  databaseid)

Definition at line 2758 of file procarray.c.

References PGPROC::databaseId, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, OidIsValid, ProcArrayStruct::pgprocnos, PGPROC::pid, and procArray.

Referenced by ResolveRecoveryConflictWithDatabase().

2759 {
2760  ProcArrayStruct *arrayP = procArray;
2761  int count = 0;
2762  int index;
2763 
2764  LWLockAcquire(ProcArrayLock, LW_SHARED);
2765 
2766  for (index = 0; index < arrayP->numProcs; index++)
2767  {
2768  int pgprocno = arrayP->pgprocnos[index];
2769  PGPROC *proc = &allProcs[pgprocno];
2770 
2771  if (proc->pid == 0)
2772  continue; /* do not count prepared xacts */
2773  if (!OidIsValid(databaseid) ||
2774  proc->databaseId == databaseid)
2775  count++;
2776  }
2777 
2778  LWLockRelease(ProcArrayLock);
2779 
2780  return count;
2781 }
#define OidIsValid(objectId)
Definition: c.h:645
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CountDBConnections()

int CountDBConnections ( Oid  databaseid)

Definition at line 2788 of file procarray.c.

References PGPROC::databaseId, PGPROC::isBackgroundWorker, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, OidIsValid, ProcArrayStruct::pgprocnos, PGPROC::pid, and procArray.

Referenced by CheckMyDatabase().

2789 {
2790  ProcArrayStruct *arrayP = procArray;
2791  int count = 0;
2792  int index;
2793 
2794  LWLockAcquire(ProcArrayLock, LW_SHARED);
2795 
2796  for (index = 0; index < arrayP->numProcs; index++)
2797  {
2798  int pgprocno = arrayP->pgprocnos[index];
2799  PGPROC *proc = &allProcs[pgprocno];
2800 
2801  if (proc->pid == 0)
2802  continue; /* do not count prepared xacts */
2803  if (proc->isBackgroundWorker)
2804  continue; /* do not count background workers */
2805  if (!OidIsValid(databaseid) ||
2806  proc->databaseId == databaseid)
2807  count++;
2808  }
2809 
2810  LWLockRelease(ProcArrayLock);
2811 
2812  return count;
2813 }
#define OidIsValid(objectId)
Definition: c.h:645
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool isBackgroundWorker
Definition: proc.h:120
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CountOtherDBBackends()

bool CountOtherDBBackends ( Oid  databaseId,
int *  nbackends,
int *  nprepared 
)

Definition at line 2909 of file procarray.c.

References CHECK_FOR_INTERRUPTS, PGPROC::databaseId, kill, LW_SHARED, LWLockAcquire(), LWLockRelease(), MAXAUTOVACPIDS, MyProc, ProcArrayStruct::numProcs, pg_usleep(), ProcArrayStruct::pgprocnos, PGPROC::pid, PROC_IS_AUTOVACUUM, procArray, and PGXACT::vacuumFlags.

Referenced by createdb(), dropdb(), movedb(), and RenameDatabase().

2910 {
2911  ProcArrayStruct *arrayP = procArray;
2912 
2913 #define MAXAUTOVACPIDS 10 /* max autovacs to SIGTERM per iteration */
2914  int autovac_pids[MAXAUTOVACPIDS];
2915  int tries;
2916 
2917  /* 50 tries with 100ms sleep between tries makes 5 sec total wait */
2918  for (tries = 0; tries < 50; tries++)
2919  {
2920  int nautovacs = 0;
2921  bool found = false;
2922  int index;
2923 
2925 
2926  *nbackends = *nprepared = 0;
2927 
2928  LWLockAcquire(ProcArrayLock, LW_SHARED);
2929 
2930  for (index = 0; index < arrayP->numProcs; index++)
2931  {
2932  int pgprocno = arrayP->pgprocnos[index];
2933  PGPROC *proc = &allProcs[pgprocno];
2934  PGXACT *pgxact = &allPgXact[pgprocno];
2935 
2936  if (proc->databaseId != databaseId)
2937  continue;
2938  if (proc == MyProc)
2939  continue;
2940 
2941  found = true;
2942 
2943  if (proc->pid == 0)
2944  (*nprepared)++;
2945  else
2946  {
2947  (*nbackends)++;
2948  if ((pgxact->vacuumFlags & PROC_IS_AUTOVACUUM) &&
2949  nautovacs < MAXAUTOVACPIDS)
2950  autovac_pids[nautovacs++] = proc->pid;
2951  }
2952  }
2953 
2954  LWLockRelease(ProcArrayLock);
2955 
2956  if (!found)
2957  return false; /* no conflicting backends, so done */
2958 
2959  /*
2960  * Send SIGTERM to any conflicting autovacuums before sleeping. We
2961  * postpone this step until after the loop because we don't want to
2962  * hold ProcArrayLock while issuing kill(). We have no idea what might
2963  * block kill() inside the kernel...
2964  */
2965  for (index = 0; index < nautovacs; index++)
2966  (void) kill(autovac_pids[index], SIGTERM); /* ignore any error */
2967 
2968  /* sleep, then try again */
2969  pg_usleep(100 * 1000L); /* 100ms */
2970  }
2971 
2972  return true; /* timed out, still conflicts */
2973 }
Definition: proc.h:222
PGPROC * MyProc
Definition: proc.c:67
#define kill(pid, sig)
Definition: win32_port.h:426
#define MAXAUTOVACPIDS
uint8 vacuumFlags
Definition: proc.h:233
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pg_usleep(long microsec)
Definition: signal.c:53
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
Definition: proc.h:95
int pid
Definition: proc.h:109
#define PROC_IS_AUTOVACUUM
Definition: proc.h:53

◆ CountUserBackends()

int CountUserBackends ( Oid  roleid)

Definition at line 2859 of file procarray.c.

References PGPROC::isBackgroundWorker, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, and PGPROC::roleId.

Referenced by InitializeSessionUserId().

2860 {
2861  ProcArrayStruct *arrayP = procArray;
2862  int count = 0;
2863  int index;
2864 
2865  LWLockAcquire(ProcArrayLock, LW_SHARED);
2866 
2867  for (index = 0; index < arrayP->numProcs; index++)
2868  {
2869  int pgprocno = arrayP->pgprocnos[index];
2870  PGPROC *proc = &allProcs[pgprocno];
2871 
2872  if (proc->pid == 0)
2873  continue; /* do not count prepared xacts */
2874  if (proc->isBackgroundWorker)
2875  continue; /* do not count background workers */
2876  if (proc->roleId == roleid)
2877  count++;
2878  }
2879 
2880  LWLockRelease(ProcArrayLock);
2881 
2882  return count;
2883 }
Oid roleId
Definition: proc.h:115
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool isBackgroundWorker
Definition: proc.h:120
static PGPROC * allProcs
Definition: procarray.c:103
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ CreateSharedProcArray()

void CreateSharedProcArray ( void  )

Definition at line 224 of file procarray.c.

References add_size(), PROC_HDR::allPgXact, PROC_HDR::allProcs, EnableHotStandby, ProcArrayStruct::headKnownAssignedXids, InvalidTransactionId, ProcArrayStruct::known_assigned_xids_lck, KnownAssignedXids, KnownAssignedXidsValid, ProcArrayStruct::lastOverflowedXid, LWLockRegisterTranche(), LWTRANCHE_PROC, ProcArrayStruct::maxKnownAssignedXids, ProcArrayStruct::maxProcs, mul_size(), ProcArrayStruct::numKnownAssignedXids, ProcArrayStruct::numProcs, offsetof, ProcArrayStruct::pgprocnos, PROCARRAY_MAXPROCS, ProcGlobal, ProcArrayStruct::replication_slot_catalog_xmin, ProcArrayStruct::replication_slot_xmin, ShmemInitStruct(), SpinLockInit, ProcArrayStruct::tailKnownAssignedXids, and TOTAL_MAX_CACHED_SUBXIDS.

Referenced by CreateSharedMemoryAndSemaphores().

225 {
226  bool found;
227 
228  /* Create or attach to the ProcArray shared structure */
230  ShmemInitStruct("Proc Array",
231  add_size(offsetof(ProcArrayStruct, pgprocnos),
232  mul_size(sizeof(int),
234  &found);
235 
236  if (!found)
237  {
238  /*
239  * We're the first - initialize.
240  */
241  procArray->numProcs = 0;
251  }
252 
255 
256  /* Create or attach to the KnownAssignedXids arrays too, if needed */
257  if (EnableHotStandby)
258  {
260  ShmemInitStruct("KnownAssignedXids",
261  mul_size(sizeof(TransactionId),
263  &found);
264  KnownAssignedXidsValid = (bool *)
265  ShmemInitStruct("KnownAssignedXidsValid",
266  mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS),
267  &found);
268  }
269 
271 }
#define PROCARRAY_MAXPROCS
uint32 TransactionId
Definition: c.h:514
PGXACT * allPgXact
Definition: proc.h:249
#define SpinLockInit(lock)
Definition: spin.h:60
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
slock_t known_assigned_xids_lck
Definition: procarray.c:81
PROC_HDR * ProcGlobal
Definition: proc.c:80
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:603
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
int maxKnownAssignedXids
Definition: procarray.c:77
#define InvalidTransactionId
Definition: transam.h:31
static PGPROC * allProcs
Definition: procarray.c:103
int numKnownAssignedXids
Definition: procarray.c:78
static bool * KnownAssignedXidsValid
Definition: procarray.c:110
TransactionId lastOverflowedXid
Definition: procarray.c:90
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
static PGXACT * allPgXact
Definition: procarray.c:104
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
#define TOTAL_MAX_CACHED_SUBXIDS
static TransactionId * KnownAssignedXids
Definition: procarray.c:109
bool EnableHotStandby
Definition: xlog.c:93
PGPROC * allProcs
Definition: proc.h:247
int tailKnownAssignedXids
Definition: procarray.c:79
#define offsetof(type, field)
Definition: c.h:662
int headKnownAssignedXids
Definition: procarray.c:80

◆ ExpireAllKnownAssignedTransactionIds()

void ExpireAllKnownAssignedTransactionIds ( void  )

Definition at line 3406 of file procarray.c.

References InvalidTransactionId, KnownAssignedXidsRemovePreceding(), LW_EXCLUSIVE, LWLockAcquire(), and LWLockRelease().

Referenced by ShutdownRecoveryTransactionEnvironment().

3407 {
3408  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3410  LWLockRelease(ProcArrayLock);
3411 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void KnownAssignedXidsRemovePreceding(TransactionId xid)
Definition: procarray.c:3855
#define InvalidTransactionId
Definition: transam.h:31
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ ExpireOldKnownAssignedTransactionIds()

void ExpireOldKnownAssignedTransactionIds ( TransactionId  xid)

Definition at line 3418 of file procarray.c.

References KnownAssignedXidsRemovePreceding(), LW_EXCLUSIVE, LWLockAcquire(), and LWLockRelease().

Referenced by ProcArrayApplyRecoveryInfo().

3419 {
3420  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3422  LWLockRelease(ProcArrayLock);
3423 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void KnownAssignedXidsRemovePreceding(TransactionId xid)
Definition: procarray.c:3855
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ ExpireTreeKnownAssignedTransactionIds()

void ExpireTreeKnownAssignedTransactionIds ( TransactionId  xid,
int  nsubxids,
TransactionId subxids,
TransactionId  max_xid 
)

Definition at line 3381 of file procarray.c.

References Assert, KnownAssignedXidsRemoveTree(), VariableCacheData::latestCompletedXid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ShmemVariableCache, STANDBY_INITIALIZED, standbyState, and TransactionIdPrecedes().

Referenced by xact_redo_abort(), and xact_redo_commit().

3383 {
3385 
3386  /*
3387  * Uses same locking as transaction commit
3388  */
3389  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3390 
3391  KnownAssignedXidsRemoveTree(xid, nsubxids, subxids);
3392 
3393  /* As in ProcArrayEndTransaction, advance latestCompletedXid */
3395  max_xid))
3397 
3398  LWLockRelease(ProcArrayLock);
3399 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
VariableCache ShmemVariableCache
Definition: varsup.c:34
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:3833
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
HotStandbyState standbyState
Definition: xlog.c:203
TransactionId latestCompletedXid
Definition: transam.h:182

◆ GetConflictingVirtualXIDs()

VirtualTransactionId* GetConflictingVirtualXIDs ( TransactionId  limitXmin,
Oid  dbOid 
)

Definition at line 2581 of file procarray.c.

References VirtualTransactionId::backendId, PGPROC::databaseId, ereport, errcode(), errmsg(), ERROR, GET_VXID_FROM_PGPROC, InvalidBackendId, InvalidLocalTransactionId, VirtualTransactionId::localTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), malloc, ProcArrayStruct::maxProcs, ProcArrayStruct::numProcs, OidIsValid, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, TransactionIdFollows(), TransactionIdIsValid, UINT32_ACCESS_ONCE, VirtualTransactionIdIsValid, and PGXACT::xmin.

Referenced by ResolveRecoveryConflictWithSnapshot(), and ResolveRecoveryConflictWithTablespace().

2582 {
2583  static VirtualTransactionId *vxids;
2584  ProcArrayStruct *arrayP = procArray;
2585  int count = 0;
2586  int index;
2587 
2588  /*
2589  * If first time through, get workspace to remember main XIDs in. We
2590  * malloc it permanently to avoid repeated palloc/pfree overhead. Allow
2591  * result space, remembering room for a terminator.
2592  */
2593  if (vxids == NULL)
2594  {
2595  vxids = (VirtualTransactionId *)
2596  malloc(sizeof(VirtualTransactionId) * (arrayP->maxProcs + 1));
2597  if (vxids == NULL)
2598  ereport(ERROR,
2599  (errcode(ERRCODE_OUT_OF_MEMORY),
2600  errmsg("out of memory")));
2601  }
2602 
2603  LWLockAcquire(ProcArrayLock, LW_SHARED);
2604 
2605  for (index = 0; index < arrayP->numProcs; index++)
2606  {
2607  int pgprocno = arrayP->pgprocnos[index];
2608  PGPROC *proc = &allProcs[pgprocno];
2609  PGXACT *pgxact = &allPgXact[pgprocno];
2610 
2611  /* Exclude prepared transactions */
2612  if (proc->pid == 0)
2613  continue;
2614 
2615  if (!OidIsValid(dbOid) ||
2616  proc->databaseId == dbOid)
2617  {
2618  /* Fetch xmin just once - can't change on us, but good coding */
2619  TransactionId pxmin = UINT32_ACCESS_ONCE(pgxact->xmin);
2620 
2621  /*
2622  * We ignore an invalid pxmin because this means that backend has
2623  * no snapshot currently. We hold a Share lock to avoid contention
2624  * with users taking snapshots. That is not a problem because the
2625  * current xmin is always at least one higher than the latest
2626  * removed xid, so any new snapshot would never conflict with the
2627  * test here.
2628  */
2629  if (!TransactionIdIsValid(limitXmin) ||
2630  (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin)))
2631  {
2632  VirtualTransactionId vxid;
2633 
2634  GET_VXID_FROM_PGPROC(vxid, *proc);
2635  if (VirtualTransactionIdIsValid(vxid))
2636  vxids[count++] = vxid;
2637  }
2638  }
2639  }
2640 
2641  LWLockRelease(ProcArrayLock);
2642 
2643  /* add the terminator */
2644  vxids[count].backendId = InvalidBackendId;
2646 
2647  return vxids;
2648 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
int errcode(int sqlerrcode)
Definition: elog.c:608
LocalTransactionId localTransactionId
Definition: lock.h:65
#define OidIsValid(objectId)
Definition: c.h:645
Definition: type.h:89
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ERROR
Definition: elog.h:43
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
#define ereport(elevel, rest)
Definition: elog.h:141
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:70
#define InvalidBackendId
Definition: backendid.h:23
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
BackendId backendId
Definition: lock.h:64
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define InvalidLocalTransactionId
Definition: lock.h:68
#define TransactionIdIsValid(xid)
Definition: transam.h:41
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ GetCurrentVirtualXIDs()

VirtualTransactionId* GetCurrentVirtualXIDs ( TransactionId  limitXmin,
bool  excludeXmin0,
bool  allDbs,
int  excludeVacuum,
int *  nvxids 
)

Definition at line 2493 of file procarray.c.

References PGPROC::databaseId, GET_VXID_FROM_PGPROC, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::maxProcs, MyDatabaseId, MyProc, ProcArrayStruct::numProcs, palloc(), ProcArrayStruct::pgprocnos, procArray, TransactionIdIsValid, TransactionIdPrecedesOrEquals(), UINT32_ACCESS_ONCE, PGXACT::vacuumFlags, VirtualTransactionIdIsValid, and PGXACT::xmin.

Referenced by WaitForOlderSnapshots().

2496 {
2497  VirtualTransactionId *vxids;
2498  ProcArrayStruct *arrayP = procArray;
2499  int count = 0;
2500  int index;
2501 
2502  /* allocate what's certainly enough result space */
2503  vxids = (VirtualTransactionId *)
2504  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2505 
2506  LWLockAcquire(ProcArrayLock, LW_SHARED);
2507 
2508  for (index = 0; index < arrayP->numProcs; index++)
2509  {
2510  int pgprocno = arrayP->pgprocnos[index];
2511  PGPROC *proc = &allProcs[pgprocno];
2512  PGXACT *pgxact = &allPgXact[pgprocno];
2513 
2514  if (proc == MyProc)
2515  continue;
2516 
2517  if (excludeVacuum & pgxact->vacuumFlags)
2518  continue;
2519 
2520  if (allDbs || proc->databaseId == MyDatabaseId)
2521  {
2522  /* Fetch xmin just once - might change on us */
2523  TransactionId pxmin = UINT32_ACCESS_ONCE(pgxact->xmin);
2524 
2525  if (excludeXmin0 && !TransactionIdIsValid(pxmin))
2526  continue;
2527 
2528  /*
2529  * InvalidTransactionId precedes all other XIDs, so a proc that
2530  * hasn't set xmin yet will not be rejected by this test.
2531  */
2532  if (!TransactionIdIsValid(limitXmin) ||
2533  TransactionIdPrecedesOrEquals(pxmin, limitXmin))
2534  {
2535  VirtualTransactionId vxid;
2536 
2537  GET_VXID_FROM_PGPROC(vxid, *proc);
2538  if (VirtualTransactionIdIsValid(vxid))
2539  vxids[count++] = vxid;
2540  }
2541  }
2542  }
2543 
2544  LWLockRelease(ProcArrayLock);
2545 
2546  *nvxids = count;
2547  return vxids;
2548 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
PGPROC * MyProc
Definition: proc.c:67
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
uint8 vacuumFlags
Definition: proc.h:233
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:70
static PGXACT * allPgXact
Definition: procarray.c:104
Oid MyDatabaseId
Definition: globals.c:85
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * palloc(Size size)
Definition: mcxt.c:949
#define TransactionIdIsValid(xid)
Definition: transam.h:41
Definition: proc.h:95

◆ GetMaxSnapshotSubxidCount()

int GetMaxSnapshotSubxidCount ( void  )

Definition at line 1463 of file procarray.c.

References TOTAL_MAX_CACHED_SUBXIDS.

Referenced by ExportSnapshot(), GetSnapshotData(), ImportSnapshot(), and SetTransactionSnapshot().

1464 {
1465  return TOTAL_MAX_CACHED_SUBXIDS;
1466 }
#define TOTAL_MAX_CACHED_SUBXIDS

◆ GetMaxSnapshotXidCount()

int GetMaxSnapshotXidCount ( void  )

Definition at line 1452 of file procarray.c.

References ProcArrayStruct::maxProcs.

Referenced by GetSnapshotData(), ImportSnapshot(), SetTransactionSnapshot(), and SnapBuildInitialSnapshot().

1453 {
1454  return procArray->maxProcs;
1455 }
static ProcArrayStruct * procArray
Definition: procarray.c:101

◆ GetOldestActiveTransactionId()

TransactionId GetOldestActiveTransactionId ( void  )

Definition at line 2111 of file procarray.c.

References Assert, LW_SHARED, LWLockAcquire(), LWLockRelease(), VariableCacheData::nextFullXid, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, procArray, RecoveryInProgress(), ShmemVariableCache, TransactionIdIsNormal, TransactionIdPrecedes(), UINT32_ACCESS_ONCE, PGXACT::xid, and XidFromFullTransactionId.

Referenced by CreateCheckPoint().

2112 {
2113  ProcArrayStruct *arrayP = procArray;
2114  TransactionId oldestRunningXid;
2115  int index;
2116 
2118 
2119  /*
2120  * Read nextXid, as the upper bound of what's still active.
2121  *
2122  * Reading a TransactionId is atomic, but we must grab the lock to make
2123  * sure that all XIDs < nextXid are already present in the proc array (or
2124  * have already completed), when we spin over it.
2125  */
2126  LWLockAcquire(XidGenLock, LW_SHARED);
2128  LWLockRelease(XidGenLock);
2129 
2130  /*
2131  * Spin over procArray collecting all xids and subxids.
2132  */
2133  LWLockAcquire(ProcArrayLock, LW_SHARED);
2134  for (index = 0; index < arrayP->numProcs; index++)
2135  {
2136  int pgprocno = arrayP->pgprocnos[index];
2137  PGXACT *pgxact = &allPgXact[pgprocno];
2138  TransactionId xid;
2139 
2140  /* Fetch xid just once - see GetNewTransactionId */
2141  xid = UINT32_ACCESS_ONCE(pgxact->xid);
2142 
2143  if (!TransactionIdIsNormal(xid))
2144  continue;
2145 
2146  if (TransactionIdPrecedes(xid, oldestRunningXid))
2147  oldestRunningXid = xid;
2148 
2149  /*
2150  * Top-level XID of a transaction is always less than any of its
2151  * subxids, so we don't need to check if any of the subxids are
2152  * smaller than oldestRunningXid
2153  */
2154  }
2155  LWLockRelease(ProcArrayLock);
2156 
2157  return oldestRunningXid;
2158 }
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xid
Definition: proc.h:224
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
FullTransactionId nextFullXid
Definition: transam.h:164
bool RecoveryInProgress(void)
Definition: xlog.c:7935
#define XidFromFullTransactionId(x)
Definition: transam.h:48
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
VariableCache ShmemVariableCache
Definition: varsup.c:34
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

◆ GetOldestSafeDecodingTransactionId()

TransactionId GetOldestSafeDecodingTransactionId ( bool  catalogOnly)

Definition at line 2177 of file procarray.c.

References Assert, LW_SHARED, LWLockAcquire(), LWLockHeldByMe(), LWLockRelease(), VariableCacheData::nextFullXid, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, procArray, RecoveryInProgress(), ProcArrayStruct::replication_slot_catalog_xmin, ProcArrayStruct::replication_slot_xmin, ShmemVariableCache, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), UINT32_ACCESS_ONCE, PGXACT::xid, and XidFromFullTransactionId.

Referenced by CreateInitDecodingContext(), and SnapBuildInitialSnapshot().

2178 {
2179  ProcArrayStruct *arrayP = procArray;
2180  TransactionId oldestSafeXid;
2181  int index;
2182  bool recovery_in_progress = RecoveryInProgress();
2183 
2184  Assert(LWLockHeldByMe(ProcArrayLock));
2185 
2186  /*
2187  * Acquire XidGenLock, so no transactions can acquire an xid while we're
2188  * running. If no transaction with xid were running concurrently a new xid
2189  * could influence the RecentXmin et al.
2190  *
2191  * We initialize the computation to nextXid since that's guaranteed to be
2192  * a safe, albeit pessimal, value.
2193  */
2194  LWLockAcquire(XidGenLock, LW_SHARED);
2196 
2197  /*
2198  * If there's already a slot pegging the xmin horizon, we can start with
2199  * that value, it's guaranteed to be safe since it's computed by this
2200  * routine initially and has been enforced since. We can always use the
2201  * slot's general xmin horizon, but the catalog horizon is only usable
2202  * when only catalog data is going to be looked at.
2203  */
2206  oldestSafeXid))
2207  oldestSafeXid = procArray->replication_slot_xmin;
2208 
2209  if (catalogOnly &&
2212  oldestSafeXid))
2213  oldestSafeXid = procArray->replication_slot_catalog_xmin;
2214 
2215  /*
2216  * If we're not in recovery, we walk over the procarray and collect the
2217  * lowest xid. Since we're called with ProcArrayLock held and have
2218  * acquired XidGenLock, no entries can vanish concurrently, since
2219  * PGXACT->xid is only set with XidGenLock held and only cleared with
2220  * ProcArrayLock held.
2221  *
2222  * In recovery we can't lower the safe value besides what we've computed
2223  * above, so we'll have to wait a bit longer there. We unfortunately can
2224  * *not* use KnownAssignedXidsGetOldestXmin() since the KnownAssignedXids
2225  * machinery can miss values and return an older value than is safe.
2226  */
2227  if (!recovery_in_progress)
2228  {
2229  /*
2230  * Spin over procArray collecting all min(PGXACT->xid)
2231  */
2232  for (index = 0; index < arrayP->numProcs; index++)
2233  {
2234  int pgprocno = arrayP->pgprocnos[index];
2235  PGXACT *pgxact = &allPgXact[pgprocno];
2236  TransactionId xid;
2237 
2238  /* Fetch xid just once - see GetNewTransactionId */
2239  xid = UINT32_ACCESS_ONCE(pgxact->xid);
2240 
2241  if (!TransactionIdIsNormal(xid))
2242  continue;
2243 
2244  if (TransactionIdPrecedes(xid, oldestSafeXid))
2245  oldestSafeXid = xid;
2246  }
2247  }
2248 
2249  LWLockRelease(XidGenLock);
2250 
2251  return oldestSafeXid;
2252 }
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
TransactionId xid
Definition: proc.h:224
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
FullTransactionId nextFullXid
Definition: transam.h:164
bool RecoveryInProgress(void)
Definition: xlog.c:7935
#define XidFromFullTransactionId(x)
Definition: transam.h:48
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
VariableCache ShmemVariableCache
Definition: varsup.c:34
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

◆ GetOldestXmin()

TransactionId GetOldestXmin ( Relation  rel,
int  flags 
)

Definition at line 1306 of file procarray.c.

References Assert, PGPROC::databaseId, FirstNormalTransactionId, InvalidTransactionId, KnownAssignedXidsGetOldestXmin(), VariableCacheData::latestCompletedXid, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NormalTransactionIdPrecedes, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, procArray, PROCARRAY_PROC_FLAGS_MASK, PROCARRAY_SLOTS_XMIN, RelationData::rd_rel, RecoveryInProgress(), RelationIsAccessibleInLogicalDecoding, ProcArrayStruct::replication_slot_catalog_xmin, ProcArrayStruct::replication_slot_xmin, ShmemVariableCache, TransactionIdAdvance, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), UINT32_ACCESS_ONCE, vacuum_defer_cleanup_age, PGXACT::vacuumFlags, PGXACT::xid, and PGXACT::xmin.

Referenced by acquire_sample_rows(), collect_corrupt_items(), CreateCheckPoint(), CreateRestartPoint(), heapam_index_build_range_scan(), statapprox_heap(), vac_update_datfrozenxid(), vacuum_set_xid_limits(), and XLogWalRcvSendHSFeedback().

1307 {
1308  ProcArrayStruct *arrayP = procArray;
1309  TransactionId result;
1310  int index;
1311  bool allDbs;
1312 
1313  TransactionId replication_slot_xmin = InvalidTransactionId;
1314  TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1315 
1316  /*
1317  * If we're not computing a relation specific limit, or if a shared
1318  * relation has been passed in, backends in all databases have to be
1319  * considered.
1320  */
1321  allDbs = rel == NULL || rel->rd_rel->relisshared;
1322 
1323  /* Cannot look for individual databases during recovery */
1324  Assert(allDbs || !RecoveryInProgress());
1325 
1326  LWLockAcquire(ProcArrayLock, LW_SHARED);
1327 
1328  /*
1329  * We initialize the MIN() calculation with latestCompletedXid + 1. This
1330  * is a lower bound for the XIDs that might appear in the ProcArray later,
1331  * and so protects us against overestimating the result due to future
1332  * additions.
1333  */
1335  Assert(TransactionIdIsNormal(result));
1336  TransactionIdAdvance(result);
1337 
1338  for (index = 0; index < arrayP->numProcs; index++)
1339  {
1340  int pgprocno = arrayP->pgprocnos[index];
1341  PGPROC *proc = &allProcs[pgprocno];
1342  PGXACT *pgxact = &allPgXact[pgprocno];
1343 
1344  if (pgxact->vacuumFlags & (flags & PROCARRAY_PROC_FLAGS_MASK))
1345  continue;
1346 
1347  if (allDbs ||
1348  proc->databaseId == MyDatabaseId ||
1349  proc->databaseId == 0) /* always include WalSender */
1350  {
1351  /* Fetch xid just once - see GetNewTransactionId */
1352  TransactionId xid = UINT32_ACCESS_ONCE(pgxact->xid);
1353 
1354  /* First consider the transaction's own Xid, if any */
1355  if (TransactionIdIsNormal(xid) &&
1356  TransactionIdPrecedes(xid, result))
1357  result = xid;
1358 
1359  /*
1360  * Also consider the transaction's Xmin, if set.
1361  *
1362  * We must check both Xid and Xmin because a transaction might
1363  * have an Xmin but not (yet) an Xid; conversely, if it has an
1364  * Xid, that could determine some not-yet-set Xmin.
1365  */
1366  xid = UINT32_ACCESS_ONCE(pgxact->xmin);
1367  if (TransactionIdIsNormal(xid) &&
1368  TransactionIdPrecedes(xid, result))
1369  result = xid;
1370  }
1371  }
1372 
1373  /*
1374  * Fetch into local variable while ProcArrayLock is held - the
1375  * LWLockRelease below is a barrier, ensuring this happens inside the
1376  * lock.
1377  */
1378  replication_slot_xmin = procArray->replication_slot_xmin;
1379  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1380 
1381  if (RecoveryInProgress())
1382  {
1383  /*
1384  * Check to see whether KnownAssignedXids contains an xid value older
1385  * than the main procarray.
1386  */
1388 
1389  LWLockRelease(ProcArrayLock);
1390 
1391  if (TransactionIdIsNormal(kaxmin) &&
1392  TransactionIdPrecedes(kaxmin, result))
1393  result = kaxmin;
1394  }
1395  else
1396  {
1397  /*
1398  * No other information needed, so release the lock immediately.
1399  */
1400  LWLockRelease(ProcArrayLock);
1401 
1402  /*
1403  * Compute the cutoff XID by subtracting vacuum_defer_cleanup_age,
1404  * being careful not to generate a "permanent" XID.
1405  *
1406  * vacuum_defer_cleanup_age provides some additional "slop" for the
1407  * benefit of hot standby queries on standby servers. This is quick
1408  * and dirty, and perhaps not all that useful unless the master has a
1409  * predictable transaction rate, but it offers some protection when
1410  * there's no walsender connection. Note that we are assuming
1411  * vacuum_defer_cleanup_age isn't large enough to cause wraparound ---
1412  * so guc.c should limit it to no more than the xidStopLimit threshold
1413  * in varsup.c. Also note that we intentionally don't apply
1414  * vacuum_defer_cleanup_age on standby servers.
1415  */
1416  result -= vacuum_defer_cleanup_age;
1417  if (!TransactionIdIsNormal(result))
1418  result = FirstNormalTransactionId;
1419  }
1420 
1421  /*
1422  * Check whether there are replication slots requiring an older xmin.
1423  */
1424  if (!(flags & PROCARRAY_SLOTS_XMIN) &&
1425  TransactionIdIsValid(replication_slot_xmin) &&
1426  NormalTransactionIdPrecedes(replication_slot_xmin, result))
1427  result = replication_slot_xmin;
1428 
1429  /*
1430  * After locks have been released and vacuum_defer_cleanup_age has been
1431  * applied, check whether we need to back up further to make logical
1432  * decoding possible. We need to do so if we're computing the global limit
1433  * (rel = NULL) or if the passed relation is a catalog relation of some
1434  * kind.
1435  */
1436  if (!(flags & PROCARRAY_SLOTS_XMIN) &&
1437  (rel == NULL ||
1439  TransactionIdIsValid(replication_slot_catalog_xmin) &&
1440  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, result))
1441  result = replication_slot_catalog_xmin;
1442 
1443  return result;
1444 }
#define TransactionIdAdvance(dest)
Definition: transam.h:75
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
TransactionId xid
Definition: proc.h:224
int vacuum_defer_cleanup_age
Definition: standby.c:39
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
Form_pg_class rd_rel
Definition: rel.h:83
bool RecoveryInProgress(void)
Definition: xlog.c:7935
uint8 vacuumFlags
Definition: proc.h:233
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define FirstNormalTransactionId
Definition: transam.h:34
#define PROCARRAY_SLOTS_XMIN
Definition: procarray.h:37
#define PROCARRAY_PROC_FLAGS_MASK
Definition: procarray.h:44
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
static PGXACT * allPgXact
Definition: procarray.c:104
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:578
Oid MyDatabaseId
Definition: globals.c:85
static TransactionId KnownAssignedXidsGetOldestXmin(void)
Definition: procarray.c:4005
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:98
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Definition: proc.h:95
TransactionId latestCompletedXid
Definition: transam.h:182

◆ GetRunningTransactionData()

RunningTransactions GetRunningTransactionData ( void  )

Definition at line 1937 of file procarray.c.

References Assert, ereport, errcode(), errmsg(), ERROR, RunningTransactionsData::latestCompletedXid, VariableCacheData::latestCompletedXid, LW_SHARED, LWLockAcquire(), malloc, VariableCacheData::nextFullXid, RunningTransactionsData::nextXid, ProcArrayStruct::numProcs, PGXACT::nxids, RunningTransactionsData::oldestRunningXid, PGXACT::overflowed, pg_read_barrier, ProcArrayStruct::pgprocnos, procArray, RecoveryInProgress(), ShmemVariableCache, RunningTransactionsData::subxcnt, RunningTransactionsData::subxid_overflow, PGPROC::subxids, TOTAL_MAX_CACHED_SUBXIDS, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), UINT32_ACCESS_ONCE, RunningTransactionsData::xcnt, PGXACT::xid, XidFromFullTransactionId, XidCache::xids, and RunningTransactionsData::xids.

Referenced by LogStandbySnapshot().

1938 {
1939  /* result workspace */
1940  static RunningTransactionsData CurrentRunningXactsData;
1941 
1942  ProcArrayStruct *arrayP = procArray;
1943  RunningTransactions CurrentRunningXacts = &CurrentRunningXactsData;
1944  TransactionId latestCompletedXid;
1945  TransactionId oldestRunningXid;
1946  TransactionId *xids;
1947  int index;
1948  int count;
1949  int subcount;
1950  bool suboverflowed;
1951 
1953 
1954  /*
1955  * Allocating space for maxProcs xids is usually overkill; numProcs would
1956  * be sufficient. But it seems better to do the malloc while not holding
1957  * the lock, so we can't look at numProcs. Likewise, we allocate much
1958  * more subxip storage than is probably needed.
1959  *
1960  * Should only be allocated in bgwriter, since only ever executed during
1961  * checkpoints.
1962  */
1963  if (CurrentRunningXacts->xids == NULL)
1964  {
1965  /*
1966  * First call
1967  */
1968  CurrentRunningXacts->xids = (TransactionId *)
1970  if (CurrentRunningXacts->xids == NULL)
1971  ereport(ERROR,
1972  (errcode(ERRCODE_OUT_OF_MEMORY),
1973  errmsg("out of memory")));
1974  }
1975 
1976  xids = CurrentRunningXacts->xids;
1977 
1978  count = subcount = 0;
1979  suboverflowed = false;
1980 
1981  /*
1982  * Ensure that no xids enter or leave the procarray while we obtain
1983  * snapshot.
1984  */
1985  LWLockAcquire(ProcArrayLock, LW_SHARED);
1986  LWLockAcquire(XidGenLock, LW_SHARED);
1987 
1988  latestCompletedXid = ShmemVariableCache->latestCompletedXid;
1989 
1991 
1992  /*
1993  * Spin over procArray collecting all xids
1994  */
1995  for (index = 0; index < arrayP->numProcs; index++)
1996  {
1997  int pgprocno = arrayP->pgprocnos[index];
1998  PGXACT *pgxact = &allPgXact[pgprocno];
1999  TransactionId xid;
2000 
2001  /* Fetch xid just once - see GetNewTransactionId */
2002  xid = UINT32_ACCESS_ONCE(pgxact->xid);
2003 
2004  /*
2005  * We don't need to store transactions that don't have a TransactionId
2006  * yet because they will not show as running on a standby server.
2007  */
2008  if (!TransactionIdIsValid(xid))
2009  continue;
2010 
2011  /*
2012  * Be careful not to exclude any xids before calculating the values of
2013  * oldestRunningXid and suboverflowed, since these are used to clean
2014  * up transaction information held on standbys.
2015  */
2016  if (TransactionIdPrecedes(xid, oldestRunningXid))
2017  oldestRunningXid = xid;
2018 
2019  if (pgxact->overflowed)
2020  suboverflowed = true;
2021 
2022  /*
2023  * If we wished to exclude xids this would be the right place for it.
2024  * Procs with the PROC_IN_VACUUM flag set don't usually assign xids,
2025  * but they do during truncation at the end when they get the lock and
2026  * truncate, so it is not much of a problem to include them if they
2027  * are seen and it is cleaner to include them.
2028  */
2029 
2030  xids[count++] = xid;
2031  }
2032 
2033  /*
2034  * Spin over procArray collecting all subxids, but only if there hasn't
2035  * been a suboverflow.
2036  */
2037  if (!suboverflowed)
2038  {
2039  for (index = 0; index < arrayP->numProcs; index++)
2040  {
2041  int pgprocno = arrayP->pgprocnos[index];
2042  PGPROC *proc = &allProcs[pgprocno];
2043  PGXACT *pgxact = &allPgXact[pgprocno];
2044  int nxids;
2045 
2046  /*
2047  * Save subtransaction XIDs. Other backends can't add or remove
2048  * entries while we're holding XidGenLock.
2049  */
2050  nxids = pgxact->nxids;
2051  if (nxids > 0)
2052  {
2053  /* barrier not really required, as XidGenLock is held, but ... */
2054  pg_read_barrier(); /* pairs with GetNewTransactionId */
2055 
2056  memcpy(&xids[count], (void *) proc->subxids.xids,
2057  nxids * sizeof(TransactionId));
2058  count += nxids;
2059  subcount += nxids;
2060 
2061  /*
2062  * Top-level XID of a transaction is always less than any of
2063  * its subxids, so we don't need to check if any of the
2064  * subxids are smaller than oldestRunningXid
2065  */
2066  }
2067  }
2068  }
2069 
2070  /*
2071  * It's important *not* to include the limits set by slots here because
2072  * snapbuild.c uses oldestRunningXid to manage its xmin horizon. If those
2073  * were to be included here the initial value could never increase because
2074  * of a circular dependency where slots only increase their limits when
2075  * running xacts increases oldestRunningXid and running xacts only
2076  * increases if slots do.
2077  */
2078 
2079  CurrentRunningXacts->xcnt = count - subcount;
2080  CurrentRunningXacts->subxcnt = subcount;
2081  CurrentRunningXacts->subxid_overflow = suboverflowed;
2083  CurrentRunningXacts->oldestRunningXid = oldestRunningXid;
2084  CurrentRunningXacts->latestCompletedXid = latestCompletedXid;
2085 
2086  Assert(TransactionIdIsValid(CurrentRunningXacts->nextXid));
2087  Assert(TransactionIdIsValid(CurrentRunningXacts->oldestRunningXid));
2088  Assert(TransactionIdIsNormal(CurrentRunningXacts->latestCompletedXid));
2089 
2090  /* We don't release the locks here, the caller is responsible for that */
2091 
2092  return CurrentRunningXacts;
2093 }
TransactionId oldestRunningXid
Definition: standby.h:76
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xid
Definition: proc.h:224
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
int errcode(int sqlerrcode)
Definition: elog.c:608
TransactionId * xids
Definition: standby.h:79
FullTransactionId nextFullXid
Definition: transam.h:164
bool RecoveryInProgress(void)
Definition: xlog.c:7935
#define XidFromFullTransactionId(x)
Definition: transam.h:48
TransactionId latestCompletedXid
Definition: standby.h:77
Definition: type.h:89
#define malloc(a)
Definition: header.h:50
#define ERROR
Definition: elog.h:43
uint8 nxids
Definition: proc.h:238
VariableCache ShmemVariableCache
Definition: varsup.c:34
static PGPROC * allProcs
Definition: procarray.c:103
struct XidCache subxids
Definition: proc.h:162
#define ereport(elevel, rest)
Definition: elog.h:141
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
bool overflowed
Definition: proc.h:234
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
#define TOTAL_MAX_CACHED_SUBXIDS
#define Assert(condition)
Definition: c.h:739
#define pg_read_barrier()
Definition: atomics.h:158
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
TransactionId nextXid
Definition: standby.h:75
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Definition: proc.h:95
TransactionId latestCompletedXid
Definition: transam.h:182

◆ GetSnapshotData()

Snapshot GetSnapshotData ( Snapshot  snapshot)

Definition at line 1505 of file procarray.c.

References SnapshotData::active_count, Assert, SnapshotData::copied, SnapshotData::curcid, ereport, errcode(), errmsg(), ERROR, FirstNormalTransactionId, GetCurrentCommandId(), GetMaxSnapshotSubxidCount(), GetMaxSnapshotXidCount(), GetSnapshotCurrentTimestamp(), GetXLogInsertRecPtr(), InvalidTransactionId, InvalidXLogRecPtr, KnownAssignedXidsGetAndSetXmin(), ProcArrayStruct::lastOverflowedXid, VariableCacheData::latestCompletedXid, SnapshotData::lsn, LW_SHARED, LWLockAcquire(), LWLockRelease(), MaintainOldSnapshotTimeMapping(), malloc, MyPgXact, NormalTransactionIdPrecedes, ProcArrayStruct::numProcs, PGXACT::nxids, old_snapshot_threshold, PGXACT::overflowed, pg_read_barrier, ProcArrayStruct::pgprocnos, PROC_IN_LOGICAL_DECODING, PROC_IN_VACUUM, procArray, RecentGlobalDataXmin, RecentGlobalXmin, RecentXmin, RecoveryInProgress(), SnapshotData::regd_count, ProcArrayStruct::replication_slot_catalog_xmin, ProcArrayStruct::replication_slot_xmin, ShmemVariableCache, SnapshotData::suboverflowed, SnapshotData::subxcnt, PGPROC::subxids, SnapshotData::subxip, SnapshotData::takenDuringRecovery, TransactionIdAdvance, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), TransactionIdPrecedesOrEquals(), TransactionXmin, UINT32_ACCESS_ONCE, vacuum_defer_cleanup_age, PGXACT::vacuumFlags, SnapshotData::whenTaken, SnapshotData::xcnt, PGXACT::xid, XidCache::xids, SnapshotData::xip, SnapshotData::xmax, SnapshotData::xmin, and PGXACT::xmin.

Referenced by GetLatestSnapshot(), GetNonHistoricCatalogSnapshot(), GetSerializableTransactionSnapshotInt(), GetTransactionSnapshot(), and SetTransactionSnapshot().

1506 {
1507  ProcArrayStruct *arrayP = procArray;
1508  TransactionId xmin;
1509  TransactionId xmax;
1510  TransactionId globalxmin;
1511  int index;
1512  int count = 0;
1513  int subcount = 0;
1514  bool suboverflowed = false;
1515  TransactionId replication_slot_xmin = InvalidTransactionId;
1516  TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1517 
1518  Assert(snapshot != NULL);
1519 
1520  /*
1521  * Allocating space for maxProcs xids is usually overkill; numProcs would
1522  * be sufficient. But it seems better to do the malloc while not holding
1523  * the lock, so we can't look at numProcs. Likewise, we allocate much
1524  * more subxip storage than is probably needed.
1525  *
1526  * This does open a possibility for avoiding repeated malloc/free: since
1527  * maxProcs does not change at runtime, we can simply reuse the previous
1528  * xip arrays if any. (This relies on the fact that all callers pass
1529  * static SnapshotData structs.)
1530  */
1531  if (snapshot->xip == NULL)
1532  {
1533  /*
1534  * First call for this snapshot. Snapshot is same size whether or not
1535  * we are in recovery, see later comments.
1536  */
1537  snapshot->xip = (TransactionId *)
1539  if (snapshot->xip == NULL)
1540  ereport(ERROR,
1541  (errcode(ERRCODE_OUT_OF_MEMORY),
1542  errmsg("out of memory")));
1543  Assert(snapshot->subxip == NULL);
1544  snapshot->subxip = (TransactionId *)
1546  if (snapshot->subxip == NULL)
1547  ereport(ERROR,
1548  (errcode(ERRCODE_OUT_OF_MEMORY),
1549  errmsg("out of memory")));
1550  }
1551 
1552  /*
1553  * It is sufficient to get shared lock on ProcArrayLock, even if we are
1554  * going to set MyPgXact->xmin.
1555  */
1556  LWLockAcquire(ProcArrayLock, LW_SHARED);
1557 
1558  /* xmax is always latestCompletedXid + 1 */
1561  TransactionIdAdvance(xmax);
1562 
1563  /* initialize xmin calculation with xmax */
1564  globalxmin = xmin = xmax;
1565 
1567 
1568  if (!snapshot->takenDuringRecovery)
1569  {
1570  int *pgprocnos = arrayP->pgprocnos;
1571  int numProcs;
1572 
1573  /*
1574  * Spin over procArray checking xid, xmin, and subxids. The goal is
1575  * to gather all active xids, find the lowest xmin, and try to record
1576  * subxids.
1577  */
1578  numProcs = arrayP->numProcs;
1579  for (index = 0; index < numProcs; index++)
1580  {
1581  int pgprocno = pgprocnos[index];
1582  PGXACT *pgxact = &allPgXact[pgprocno];
1583  TransactionId xid;
1584 
1585  /*
1586  * Skip over backends doing logical decoding which manages xmin
1587  * separately (check below) and ones running LAZY VACUUM.
1588  */
1589  if (pgxact->vacuumFlags &
1591  continue;
1592 
1593  /* Update globalxmin to be the smallest valid xmin */
1594  xid = UINT32_ACCESS_ONCE(pgxact->xmin);
1595  if (TransactionIdIsNormal(xid) &&
1596  NormalTransactionIdPrecedes(xid, globalxmin))
1597  globalxmin = xid;
1598 
1599  /* Fetch xid just once - see GetNewTransactionId */
1600  xid = UINT32_ACCESS_ONCE(pgxact->xid);
1601 
1602  /*
1603  * If the transaction has no XID assigned, we can skip it; it
1604  * won't have sub-XIDs either. If the XID is >= xmax, we can also
1605  * skip it; such transactions will be treated as running anyway
1606  * (and any sub-XIDs will also be >= xmax).
1607  */
1608  if (!TransactionIdIsNormal(xid)
1609  || !NormalTransactionIdPrecedes(xid, xmax))
1610  continue;
1611 
1612  /*
1613  * We don't include our own XIDs (if any) in the snapshot, but we
1614  * must include them in xmin.
1615  */
1616  if (NormalTransactionIdPrecedes(xid, xmin))
1617  xmin = xid;
1618  if (pgxact == MyPgXact)
1619  continue;
1620 
1621  /* Add XID to snapshot. */
1622  snapshot->xip[count++] = xid;
1623 
1624  /*
1625  * Save subtransaction XIDs if possible (if we've already
1626  * overflowed, there's no point). Note that the subxact XIDs must
1627  * be later than their parent, so no need to check them against
1628  * xmin. We could filter against xmax, but it seems better not to
1629  * do that much work while holding the ProcArrayLock.
1630  *
1631  * The other backend can add more subxids concurrently, but cannot
1632  * remove any. Hence it's important to fetch nxids just once.
1633  * Should be safe to use memcpy, though. (We needn't worry about
1634  * missing any xids added concurrently, because they must postdate
1635  * xmax.)
1636  *
1637  * Again, our own XIDs are not included in the snapshot.
1638  */
1639  if (!suboverflowed)
1640  {
1641  if (pgxact->overflowed)
1642  suboverflowed = true;
1643  else
1644  {
1645  int nxids = pgxact->nxids;
1646 
1647  if (nxids > 0)
1648  {
1649  PGPROC *proc = &allProcs[pgprocno];
1650 
1651  pg_read_barrier(); /* pairs with GetNewTransactionId */
1652 
1653  memcpy(snapshot->subxip + subcount,
1654  (void *) proc->subxids.xids,
1655  nxids * sizeof(TransactionId));
1656  subcount += nxids;
1657  }
1658  }
1659  }
1660  }
1661  }
1662  else
1663  {
1664  /*
1665  * We're in hot standby, so get XIDs from KnownAssignedXids.
1666  *
1667  * We store all xids directly into subxip[]. Here's why:
1668  *
1669  * In recovery we don't know which xids are top-level and which are
1670  * subxacts, a design choice that greatly simplifies xid processing.
1671  *
1672  * It seems like we would want to try to put xids into xip[] only, but
1673  * that is fairly small. We would either need to make that bigger or
1674  * to increase the rate at which we WAL-log xid assignment; neither is
1675  * an appealing choice.
1676  *
1677  * We could try to store xids into xip[] first and then into subxip[]
1678  * if there are too many xids. That only works if the snapshot doesn't
1679  * overflow because we do not search subxip[] in that case. A simpler
1680  * way is to just store all xids in the subxact array because this is
1681  * by far the bigger array. We just leave the xip array empty.
1682  *
1683  * Either way we need to change the way XidInMVCCSnapshot() works
1684  * depending upon when the snapshot was taken, or change normal
1685  * snapshot processing so it matches.
1686  *
1687  * Note: It is possible for recovery to end before we finish taking
1688  * the snapshot, and for newly assigned transaction ids to be added to
1689  * the ProcArray. xmax cannot change while we hold ProcArrayLock, so
1690  * those newly added transaction ids would be filtered away, so we
1691  * need not be concerned about them.
1692  */
1693  subcount = KnownAssignedXidsGetAndSetXmin(snapshot->subxip, &xmin,
1694  xmax);
1695 
1697  suboverflowed = true;
1698  }
1699 
1700 
1701  /*
1702  * Fetch into local variable while ProcArrayLock is held - the
1703  * LWLockRelease below is a barrier, ensuring this happens inside the
1704  * lock.
1705  */
1706  replication_slot_xmin = procArray->replication_slot_xmin;
1707  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1708 
1710  MyPgXact->xmin = TransactionXmin = xmin;
1711 
1712  LWLockRelease(ProcArrayLock);
1713 
1714  /*
1715  * Update globalxmin to include actual process xids. This is a slightly
1716  * different way of computing it than GetOldestXmin uses, but should give
1717  * the same result.
1718  */
1719  if (TransactionIdPrecedes(xmin, globalxmin))
1720  globalxmin = xmin;
1721 
1722  /* Update global variables too */
1726 
1727  /* Check whether there's a replication slot requiring an older xmin. */
1728  if (TransactionIdIsValid(replication_slot_xmin) &&
1729  NormalTransactionIdPrecedes(replication_slot_xmin, RecentGlobalXmin))
1730  RecentGlobalXmin = replication_slot_xmin;
1731 
1732  /* Non-catalog tables can be vacuumed if older than this xid */
1734 
1735  /*
1736  * Check whether there's a replication slot requiring an older catalog
1737  * xmin.
1738  */
1739  if (TransactionIdIsNormal(replication_slot_catalog_xmin) &&
1740  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, RecentGlobalXmin))
1741  RecentGlobalXmin = replication_slot_catalog_xmin;
1742 
1743  RecentXmin = xmin;
1744 
1745  snapshot->xmin = xmin;
1746  snapshot->xmax = xmax;
1747  snapshot->xcnt = count;
1748  snapshot->subxcnt = subcount;
1749  snapshot->suboverflowed = suboverflowed;
1750 
1751  snapshot->curcid = GetCurrentCommandId(false);
1752 
1753  /*
1754  * This is a new snapshot, so set both refcounts are zero, and mark it as
1755  * not copied in persistent memory.
1756  */
1757  snapshot->active_count = 0;
1758  snapshot->regd_count = 0;
1759  snapshot->copied = false;
1760 
1761  if (old_snapshot_threshold < 0)
1762  {
1763  /*
1764  * If not using "snapshot too old" feature, fill related fields with
1765  * dummy values that don't require any locking.
1766  */
1767  snapshot->lsn = InvalidXLogRecPtr;
1768  snapshot->whenTaken = 0;
1769  }
1770  else
1771  {
1772  /*
1773  * Capture the current time and WAL stream location in case this
1774  * snapshot becomes old enough to need to fall back on the special
1775  * "old snapshot" logic.
1776  */
1777  snapshot->lsn = GetXLogInsertRecPtr();
1778  snapshot->whenTaken = GetSnapshotCurrentTimestamp();
1779  MaintainOldSnapshotTimeMapping(snapshot->whenTaken, xmin);
1780  }
1781 
1782  return snapshot;
1783 }
#define TransactionIdAdvance(dest)
Definition: transam.h:75
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:57
uint32 TransactionId
Definition: c.h:514
bool copied
Definition: snapshot.h:185
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
TransactionId xid
Definition: proc.h:224
int vacuum_defer_cleanup_age
Definition: standby.c:39
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
XLogRecPtr lsn
Definition: snapshot.h:203
int errcode(int sqlerrcode)
Definition: elog.c:608
TransactionId RecentXmin
Definition: snapmgr.c:167
bool suboverflowed
Definition: snapshot.h:182
bool RecoveryInProgress(void)
Definition: xlog.c:7935
uint32 regd_count
Definition: snapshot.h:199
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:233
TransactionId TransactionXmin
Definition: snapmgr.c:166
Definition: type.h:89
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define PROC_IN_VACUUM
Definition: proc.h:54
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
#define FirstNormalTransactionId
Definition: transam.h:34
#define ERROR
Definition: elog.h:43
TimestampTz GetSnapshotCurrentTimestamp(void)
Definition: snapmgr.c:1720
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:11191
TransactionId RecentGlobalXmin
Definition: snapmgr.c:168
uint8 nxids
Definition: proc.h:238
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
static PGPROC * allProcs
Definition: procarray.c:103
TransactionId xmax
Definition: snapshot.h:158
TransactionId xmin
Definition: snapshot.h:157
TransactionId RecentGlobalDataXmin
Definition: snapmgr.c:169
struct XidCache subxids
Definition: proc.h:162
TransactionId lastOverflowedXid
Definition: procarray.c:90
#define ereport(elevel, rest)
Definition: elog.h:141
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:168
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
static PGXACT * allPgXact
Definition: procarray.c:104
bool overflowed
Definition: proc.h:234
CommandId curcid
Definition: snapshot.h:187
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:1452
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
#define Assert(condition)
Definition: c.h:739
#define pg_read_barrier()
Definition: atomics.h:158
bool takenDuringRecovery
Definition: snapshot.h:184
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static int KnownAssignedXidsGetAndSetXmin(TransactionId *xarray, TransactionId *xmin, TransactionId xmax)
Definition: procarray.c:3947
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:98
uint32 xcnt
Definition: snapshot.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
int old_snapshot_threshold
Definition: snapmgr.c:75
int GetMaxSnapshotSubxidCount(void)
Definition: procarray.c:1463
TimestampTz whenTaken
Definition: snapshot.h:202
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:745
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void MaintainOldSnapshotTimeMapping(TimestampTz whenTaken, TransactionId xmin)
Definition: snapmgr.c:1882
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Definition: proc.h:95
TransactionId * subxip
Definition: snapshot.h:180
uint32 active_count
Definition: snapshot.h:198
int32 subxcnt
Definition: snapshot.h:181
TransactionId latestCompletedXid
Definition: transam.h:182

◆ GetVirtualXIDsDelayingChkpt()

VirtualTransactionId* GetVirtualXIDsDelayingChkpt ( int *  nvxids)

Definition at line 2273 of file procarray.c.

References PGXACT::delayChkpt, GET_VXID_FROM_PGPROC, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::maxProcs, ProcArrayStruct::numProcs, palloc(), ProcArrayStruct::pgprocnos, procArray, and VirtualTransactionIdIsValid.

Referenced by CreateCheckPoint().

2274 {
2275  VirtualTransactionId *vxids;
2276  ProcArrayStruct *arrayP = procArray;
2277  int count = 0;
2278  int index;
2279 
2280  /* allocate what's certainly enough result space */
2281  vxids = (VirtualTransactionId *)
2282  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2283 
2284  LWLockAcquire(ProcArrayLock, LW_SHARED);
2285 
2286  for (index = 0; index < arrayP->numProcs; index++)
2287  {
2288  int pgprocno = arrayP->pgprocnos[index];
2289  PGPROC *proc = &allProcs[pgprocno];
2290  PGXACT *pgxact = &allPgXact[pgprocno];
2291 
2292  if (pgxact->delayChkpt)
2293  {
2294  VirtualTransactionId vxid;
2295 
2296  GET_VXID_FROM_PGPROC(vxid, *proc);
2297  if (VirtualTransactionIdIsValid(vxid))
2298  vxids[count++] = vxid;
2299  }
2300  }
2301 
2302  LWLockRelease(ProcArrayLock);
2303 
2304  *nvxids = count;
2305  return vxids;
2306 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
Definition: proc.h:222
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static PGPROC * allProcs
Definition: procarray.c:103
bool delayChkpt
Definition: proc.h:235
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:70
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * palloc(Size size)
Definition: mcxt.c:949
Definition: proc.h:95

◆ HaveVirtualXIDsDelayingChkpt()

bool HaveVirtualXIDsDelayingChkpt ( VirtualTransactionId vxids,
int  nvxids 
)

Definition at line 2318 of file procarray.c.

References PGXACT::delayChkpt, GET_VXID_FROM_PGPROC, i, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, procArray, VirtualTransactionIdEquals, and VirtualTransactionIdIsValid.

Referenced by CreateCheckPoint().

2319 {
2320  bool result = false;
2321  ProcArrayStruct *arrayP = procArray;
2322  int index;
2323 
2324  LWLockAcquire(ProcArrayLock, LW_SHARED);
2325 
2326  for (index = 0; index < arrayP->numProcs; index++)
2327  {
2328  int pgprocno = arrayP->pgprocnos[index];
2329  PGPROC *proc = &allProcs[pgprocno];
2330  PGXACT *pgxact = &allPgXact[pgprocno];
2331  VirtualTransactionId vxid;
2332 
2333  GET_VXID_FROM_PGPROC(vxid, *proc);
2334 
2335  if (pgxact->delayChkpt && VirtualTransactionIdIsValid(vxid))
2336  {
2337  int i;
2338 
2339  for (i = 0; i < nvxids; i++)
2340  {
2341  if (VirtualTransactionIdEquals(vxid, vxids[i]))
2342  {
2343  result = true;
2344  break;
2345  }
2346  }
2347  if (result)
2348  break;
2349  }
2350  }
2351 
2352  LWLockRelease(ProcArrayLock);
2353 
2354  return result;
2355 }
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:79
Definition: proc.h:222
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:73
static PGPROC * allProcs
Definition: procarray.c:103
bool delayChkpt
Definition: proc.h:235
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:70
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int i
Definition: proc.h:95

◆ IsBackendPid()

bool IsBackendPid ( int  pid)

Definition at line 2460 of file procarray.c.

References BackendPidGetProc().

Referenced by pg_stat_get_subscription().

2461 {
2462  return (BackendPidGetProc(pid) != NULL);
2463 }
PGPROC * BackendPidGetProc(int pid)
Definition: procarray.c:2365

◆ MinimumActiveBackends()

bool MinimumActiveBackends ( int  min)

Definition at line 2704 of file procarray.c.

References InvalidTransactionId, MyProc, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, PGPROC::waitLock, and PGXACT::xid.

Referenced by XLogFlush().

2705 {
2706  ProcArrayStruct *arrayP = procArray;
2707  int count = 0;
2708  int index;
2709 
2710  /* Quick short-circuit if no minimum is specified */
2711  if (min == 0)
2712  return true;
2713 
2714  /*
2715  * Note: for speed, we don't acquire ProcArrayLock. This is a little bit
2716  * bogus, but since we are only testing fields for zero or nonzero, it
2717  * should be OK. The result is only used for heuristic purposes anyway...
2718  */
2719  for (index = 0; index < arrayP->numProcs; index++)
2720  {
2721  int pgprocno = arrayP->pgprocnos[index];
2722  PGPROC *proc = &allProcs[pgprocno];
2723  PGXACT *pgxact = &allPgXact[pgprocno];
2724 
2725  /*
2726  * Since we're not holding a lock, need to be prepared to deal with
2727  * garbage, as someone could have incremented numProcs but not yet
2728  * filled the structure.
2729  *
2730  * If someone just decremented numProcs, 'proc' could also point to a
2731  * PGPROC entry that's no longer in the array. It still points to a
2732  * PGPROC struct, though, because freed PGPROC entries just go to the
2733  * free list and are recycled. Its contents are nonsense in that case,
2734  * but that's acceptable for this function.
2735  */
2736  if (pgprocno == -1)
2737  continue; /* do not count deleted entries */
2738  if (proc == MyProc)
2739  continue; /* do not count myself */
2740  if (pgxact->xid == InvalidTransactionId)
2741  continue; /* do not count if no XID assigned */
2742  if (proc->pid == 0)
2743  continue; /* do not count prepared xacts */
2744  if (proc->waitLock != NULL)
2745  continue; /* do not count if blocked on a lock */
2746  count++;
2747  if (count >= min)
2748  break;
2749  }
2750 
2751  return count >= min;
2752 }
Definition: proc.h:222
PGPROC * MyProc
Definition: proc.c:67
TransactionId xid
Definition: proc.h:224
Definition: type.h:89
#define InvalidTransactionId
Definition: transam.h:31
static PGPROC * allProcs
Definition: procarray.c:103
LOCK * waitLock
Definition: proc.h:139
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ ProcArrayAdd()

void ProcArrayAdd ( PGPROC proc)

Definition at line 277 of file procarray.c.

References ereport, errcode(), errmsg(), FATAL, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::maxProcs, memmove, ProcArrayStruct::numProcs, PGPROC::pgprocno, ProcArrayStruct::pgprocnos, and procArray.

Referenced by InitProcessPhase2(), and MarkAsPrepared().

278 {
279  ProcArrayStruct *arrayP = procArray;
280  int index;
281 
282  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
283 
284  if (arrayP->numProcs >= arrayP->maxProcs)
285  {
286  /*
287  * Oops, no room. (This really shouldn't happen, since there is a
288  * fixed supply of PGPROC structs too, and so we should have failed
289  * earlier.)
290  */
291  LWLockRelease(ProcArrayLock);
292  ereport(FATAL,
293  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
294  errmsg("sorry, too many clients already")));
295  }
296 
297  /*
298  * Keep the procs array sorted by (PGPROC *) so that we can utilize
299  * locality of references much better. This is useful while traversing the
300  * ProcArray because there is an increased likelihood of finding the next
301  * PGPROC structure in the cache.
302  *
303  * Since the occurrence of adding/removing a proc is much lower than the
304  * access to the ProcArray itself, the overhead should be marginal
305  */
306  for (index = 0; index < arrayP->numProcs; index++)
307  {
308  /*
309  * If we are the first PGPROC or if we have found our right position
310  * in the array, break
311  */
312  if ((arrayP->pgprocnos[index] == -1) || (arrayP->pgprocnos[index] > proc->pgprocno))
313  break;
314  }
315 
316  memmove(&arrayP->pgprocnos[index + 1], &arrayP->pgprocnos[index],
317  (arrayP->numProcs - index) * sizeof(int));
318  arrayP->pgprocnos[index] = proc->pgprocno;
319  arrayP->numProcs++;
320 
321  LWLockRelease(ProcArrayLock);
322 }
int errcode(int sqlerrcode)
Definition: elog.c:608
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define FATAL
Definition: elog.h:52
#define memmove(d, s, c)
Definition: c.h:1267
#define ereport(elevel, rest)
Definition: elog.h:141
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int pgprocno
Definition: proc.h:110
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ ProcArrayApplyRecoveryInfo()

void ProcArrayApplyRecoveryInfo ( RunningTransactions  running)

Definition at line 664 of file procarray.c.

References AdvanceNextFullTransactionIdPastXid(), Assert, DEBUG1, DEBUG3, elog, ERROR, ExpireOldKnownAssignedTransactionIds(), ExtendSUBTRANS(), FullTransactionIdIsValid, i, InvalidTransactionId, KnownAssignedXidsAdd(), KnownAssignedXidsDisplay(), KnownAssignedXidsReset(), ProcArrayStruct::lastOverflowedXid, RunningTransactionsData::latestCompletedXid, VariableCacheData::latestCompletedXid, latestObservedXid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), VariableCacheData::nextFullXid, RunningTransactionsData::nextXid, ProcArrayStruct::numKnownAssignedXids, RunningTransactionsData::oldestRunningXid, palloc(), pfree(), qsort, ShmemVariableCache, STANDBY_INITIALIZED, STANDBY_SNAPSHOT_PENDING, STANDBY_SNAPSHOT_READY, StandbyReleaseOldLocks(), standbySnapshotPendingXmin, standbyState, RunningTransactionsData::subxcnt, RunningTransactionsData::subxid_overflow, trace_recovery(), TransactionIdAdvance, TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), TransactionIdRetreat, RunningTransactionsData::xcnt, xidComparator(), and RunningTransactionsData::xids.

Referenced by standby_redo(), StartupXLOG(), and xlog_redo().

665 {
666  TransactionId *xids;
667  int nxids;
668  int i;
669 
674 
675  /*
676  * Remove stale transactions, if any.
677  */
679 
680  /*
681  * Remove stale locks, if any.
682  */
684 
685  /*
686  * If our snapshot is already valid, nothing else to do...
687  */
689  return;
690 
691  /*
692  * If our initial RunningTransactionsData had an overflowed snapshot then
693  * we knew we were missing some subxids from our snapshot. If we continue
694  * to see overflowed snapshots then we might never be able to start up, so
695  * we make another test to see if our snapshot is now valid. We know that
696  * the missing subxids are equal to or earlier than nextXid. After we
697  * initialise we continue to apply changes during recovery, so once the
698  * oldestRunningXid is later than the nextXid from the initial snapshot we
699  * know that we no longer have missing information and can mark the
700  * snapshot as valid.
701  */
703  {
704  /*
705  * If the snapshot isn't overflowed or if its empty we can reset our
706  * pending state and use this snapshot instead.
707  */
708  if (!running->subxid_overflow || running->xcnt == 0)
709  {
710  /*
711  * If we have already collected known assigned xids, we need to
712  * throw them away before we apply the recovery snapshot.
713  */
716  }
717  else
718  {
720  running->oldestRunningXid))
721  {
724  "recovery snapshots are now enabled");
725  }
726  else
728  "recovery snapshot waiting for non-overflowed snapshot or "
729  "until oldest active xid on standby is at least %u (now %u)",
731  running->oldestRunningXid);
732  return;
733  }
734  }
735 
737 
738  /*
739  * NB: this can be reached at least twice, so make sure new code can deal
740  * with that.
741  */
742 
743  /*
744  * Nobody else is running yet, but take locks anyhow
745  */
746  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
747 
748  /*
749  * KnownAssignedXids is sorted so we cannot just add the xids, we have to
750  * sort them first.
751  *
752  * Some of the new xids are top-level xids and some are subtransactions.
753  * We don't call SubTransSetParent because it doesn't matter yet. If we
754  * aren't overflowed then all xids will fit in snapshot and so we don't
755  * need subtrans. If we later overflow, an xid assignment record will add
756  * xids to subtrans. If RunningTransactionsData is overflowed then we
757  * don't have enough information to correctly update subtrans anyway.
758  */
759 
760  /*
761  * Allocate a temporary array to avoid modifying the array passed as
762  * argument.
763  */
764  xids = palloc(sizeof(TransactionId) * (running->xcnt + running->subxcnt));
765 
766  /*
767  * Add to the temp array any xids which have not already completed.
768  */
769  nxids = 0;
770  for (i = 0; i < running->xcnt + running->subxcnt; i++)
771  {
772  TransactionId xid = running->xids[i];
773 
774  /*
775  * The running-xacts snapshot can contain xids that were still visible
776  * in the procarray when the snapshot was taken, but were already
777  * WAL-logged as completed. They're not running anymore, so ignore
778  * them.
779  */
781  continue;
782 
783  xids[nxids++] = xid;
784  }
785 
786  if (nxids > 0)
787  {
789  {
790  LWLockRelease(ProcArrayLock);
791  elog(ERROR, "KnownAssignedXids is not empty");
792  }
793 
794  /*
795  * Sort the array so that we can add them safely into
796  * KnownAssignedXids.
797  */
798  qsort(xids, nxids, sizeof(TransactionId), xidComparator);
799 
800  /*
801  * Add the sorted snapshot into KnownAssignedXids. The running-xacts
802  * snapshot may include duplicated xids because of prepared
803  * transactions, so ignore them.
804  */
805  for (i = 0; i < nxids; i++)
806  {
807  if (i > 0 && TransactionIdEquals(xids[i - 1], xids[i]))
808  {
809  elog(DEBUG1,
810  "found duplicated transaction %u for KnownAssignedXids insertion",
811  xids[i]);
812  continue;
813  }
814  KnownAssignedXidsAdd(xids[i], xids[i], true);
815  }
816 
818  }
819 
820  pfree(xids);
821 
822  /*
823  * latestObservedXid is at least set to the point where SUBTRANS was
824  * started up to (cf. ProcArrayInitRecovery()) or to the biggest xid
825  * RecordKnownAssignedTransactionIds() was called for. Initialize
826  * subtrans from thereon, up to nextXid - 1.
827  *
828  * We need to duplicate parts of RecordKnownAssignedTransactionId() here,
829  * because we've just added xids to the known assigned xids machinery that
830  * haven't gone through RecordKnownAssignedTransactionId().
831  */
835  {
838  }
839  TransactionIdRetreat(latestObservedXid); /* = running->nextXid - 1 */
840 
841  /* ----------
842  * Now we've got the running xids we need to set the global values that
843  * are used to track snapshots as they evolve further.
844  *
845  * - latestCompletedXid which will be the xmax for snapshots
846  * - lastOverflowedXid which shows whether snapshots overflow
847  * - nextXid
848  *
849  * If the snapshot overflowed, then we still initialise with what we know,
850  * but the recovery snapshot isn't fully valid yet because we know there
851  * are some subxids missing. We don't know the specific subxids that are
852  * missing, so conservatively assume the last one is latestObservedXid.
853  * ----------
854  */
855  if (running->subxid_overflow)
856  {
858 
861  }
862  else
863  {
865 
867  }
868 
869  /*
870  * If a transaction wrote a commit record in the gap between taking and
871  * logging the snapshot then latestCompletedXid may already be higher than
872  * the value from the snapshot, so check before we use the incoming value.
873  */
875  running->latestCompletedXid))
877 
879 
880  LWLockRelease(ProcArrayLock);
881 
882  /* ShmemVariableCache->nextFullXid must be beyond any observed xid. */
884 
886 
889  elog(trace_recovery(DEBUG1), "recovery snapshots are now enabled");
890  else
892  "recovery snapshot waiting for non-overflowed snapshot or "
893  "until oldest active xid on standby is at least %u (now %u)",
895  running->oldestRunningXid);
896 }
#define TransactionIdAdvance(dest)
Definition: transam.h:75
static TransactionId latestObservedXid
Definition: procarray.c:111
TransactionId oldestRunningXid
Definition: standby.h:76
#define DEBUG1
Definition: elog.h:25
static void KnownAssignedXidsDisplay(int trace_level)
Definition: procarray.c:4040
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:262
#define DEBUG3
Definition: elog.h:23
#define FullTransactionIdIsValid(x)
Definition: transam.h:51
TransactionId * xids
Definition: standby.h:79
FullTransactionId nextFullXid
Definition: transam.h:164
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define TransactionIdRetreat(dest)
Definition: transam.h:92
int trace_recovery(int trace_level)
Definition: elog.c:3589
TransactionId latestCompletedXid
Definition: standby.h:77
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
void ExtendSUBTRANS(TransactionId newestXact)
Definition: subtrans.c:326
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
static void KnownAssignedXidsReset(void)
Definition: procarray.c:4078
int numKnownAssignedXids
Definition: procarray.c:78
TransactionId lastOverflowedXid
Definition: procarray.c:90
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid, bool exclusive_lock)
Definition: procarray.c:3583
TransactionId nextXid
Definition: standby.h:75
void * palloc(Size size)
Definition: mcxt.c:949
#define elog(elevel,...)
Definition: elog.h:228
int i
void ExpireOldKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3418
#define qsort(a, b, c, d)
Definition: port.h:488
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
static TransactionId standbySnapshotPendingXmin
Definition: procarray.c:118
HotStandbyState standbyState
Definition: xlog.c:203
void StandbyReleaseOldLocks(TransactionId oldxid)
Definition: standby.c:751
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:138
TransactionId latestCompletedXid
Definition: transam.h:182

◆ ProcArrayApplyXidAssignment()

void ProcArrayApplyXidAssignment ( TransactionId  topxid,
int  nsubxids,
TransactionId subxids 
)

Definition at line 903 of file procarray.c.

References Assert, i, InvalidTransactionId, KnownAssignedXidsRemoveTree(), ProcArrayStruct::lastOverflowedXid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), RecordKnownAssignedTransactionIds(), STANDBY_INITIALIZED, standbyState, SubTransSetParent(), TransactionIdLatest(), and TransactionIdPrecedes().

Referenced by xact_redo().

905 {
906  TransactionId max_xid;
907  int i;
908 
910 
911  max_xid = TransactionIdLatest(topxid, nsubxids, subxids);
912 
913  /*
914  * Mark all the subtransactions as observed.
915  *
916  * NOTE: This will fail if the subxid contains too many previously
917  * unobserved xids to fit into known-assigned-xids. That shouldn't happen
918  * as the code stands, because xid-assignment records should never contain
919  * more than PGPROC_MAX_CACHED_SUBXIDS entries.
920  */
922 
923  /*
924  * Notice that we update pg_subtrans with the top-level xid, rather than
925  * the parent xid. This is a difference between normal processing and
926  * recovery, yet is still correct in all cases. The reason is that
927  * subtransaction commit is not marked in clog until commit processing, so
928  * all aborted subtransactions have already been clearly marked in clog.
929  * As a result we are able to refer directly to the top-level
930  * transaction's state rather than skipping through all the intermediate
931  * states in the subtransaction tree. This should be the first time we
932  * have attempted to SubTransSetParent().
933  */
934  for (i = 0; i < nsubxids; i++)
935  SubTransSetParent(subxids[i], topxid);
936 
937  /* KnownAssignedXids isn't maintained yet, so we're done for now */
939  return;
940 
941  /*
942  * Uses same locking as transaction commit
943  */
944  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
945 
946  /*
947  * Remove subxids from known-assigned-xacts.
948  */
950 
951  /*
952  * Advance lastOverflowedXid to be at least the last of these subxids.
953  */
955  procArray->lastOverflowedXid = max_xid;
956 
957  LWLockRelease(ProcArrayLock);
958 }
uint32 TransactionId
Definition: c.h:514
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define InvalidTransactionId
Definition: transam.h:31
TransactionId lastOverflowedXid
Definition: procarray.c:90
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:3833
static ProcArrayStruct * procArray
Definition: procarray.c:101
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int i
void RecordKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3310
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74
HotStandbyState standbyState
Definition: xlog.c:203

◆ ProcArrayClearTransaction()

void ProcArrayClearTransaction ( PGPROC proc)

Definition at line 601 of file procarray.c.

References PGXACT::delayChkpt, InvalidLocalTransactionId, InvalidTransactionId, PGPROC::lxid, PGXACT::nxids, PGXACT::overflowed, PGPROC::pgprocno, PROC_VACUUM_STATE_MASK, PGPROC::recoveryConflictPending, PGXACT::vacuumFlags, PGXACT::xid, and PGXACT::xmin.

Referenced by PrepareTransaction().

602 {
603  PGXACT *pgxact = &allPgXact[proc->pgprocno];
604 
605  /*
606  * We can skip locking ProcArrayLock here, because this action does not
607  * actually change anyone's view of the set of running XIDs: our entry is
608  * duplicate with the gxact that has already been inserted into the
609  * ProcArray.
610  */
611  pgxact->xid = InvalidTransactionId;
613  pgxact->xmin = InvalidTransactionId;
614  proc->recoveryConflictPending = false;
615 
616  /* redundant, but just in case */
618  pgxact->delayChkpt = false;
619 
620  /* Clear the subtransaction-XID cache too */
621  pgxact->nxids = 0;
622  pgxact->overflowed = false;
623 }
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
TransactionId xid
Definition: proc.h:224
uint8 vacuumFlags
Definition: proc.h:233
#define PROC_VACUUM_STATE_MASK
Definition: proc.h:62
bool recoveryConflictPending
Definition: proc.h:127
uint8 nxids
Definition: proc.h:238
#define InvalidTransactionId
Definition: transam.h:31
bool delayChkpt
Definition: proc.h:235
static PGXACT * allPgXact
Definition: procarray.c:104
bool overflowed
Definition: proc.h:234
int pgprocno
Definition: proc.h:110
#define InvalidLocalTransactionId
Definition: lock.h:68
LocalTransactionId lxid
Definition: proc.h:106

◆ ProcArrayEndTransaction()

void ProcArrayEndTransaction ( PGPROC proc,
TransactionId  latestXid 
)

Definition at line 398 of file procarray.c.

References Assert, PGXACT::delayChkpt, InvalidLocalTransactionId, InvalidTransactionId, LW_EXCLUSIVE, LWLockConditionalAcquire(), LWLockRelease(), PGPROC::lxid, PGXACT::nxids, PGXACT::overflowed, PGPROC::pgprocno, PROC_VACUUM_STATE_MASK, ProcArrayEndTransactionInternal(), ProcArrayGroupClearXid(), PGPROC::recoveryConflictPending, TransactionIdIsValid, PGXACT::vacuumFlags, PGXACT::xid, and PGXACT::xmin.

Referenced by AbortTransaction(), and CommitTransaction().

399 {
400  PGXACT *pgxact = &allPgXact[proc->pgprocno];
401 
402  if (TransactionIdIsValid(latestXid))
403  {
404  /*
405  * We must lock ProcArrayLock while clearing our advertised XID, so
406  * that we do not exit the set of "running" transactions while someone
407  * else is taking a snapshot. See discussion in
408  * src/backend/access/transam/README.
409  */
411 
412  /*
413  * If we can immediately acquire ProcArrayLock, we clear our own XID
414  * and release the lock. If not, use group XID clearing to improve
415  * efficiency.
416  */
417  if (LWLockConditionalAcquire(ProcArrayLock, LW_EXCLUSIVE))
418  {
419  ProcArrayEndTransactionInternal(proc, pgxact, latestXid);
420  LWLockRelease(ProcArrayLock);
421  }
422  else
423  ProcArrayGroupClearXid(proc, latestXid);
424  }
425  else
426  {
427  /*
428  * If we have no XID, we don't need to lock, since we won't affect
429  * anyone else's calculation of a snapshot. We might change their
430  * estimate of global xmin, but that's OK.
431  */
433 
435  pgxact->xmin = InvalidTransactionId;
436  /* must be cleared with xid/xmin: */
438  pgxact->delayChkpt = false; /* be sure this is cleared in abort */
439  proc->recoveryConflictPending = false;
440 
441  Assert(pgxact->nxids == 0);
442  Assert(pgxact->overflowed == false);
443  }
444 }
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
TransactionId xid
Definition: proc.h:224
static void ProcArrayGroupClearXid(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:486
uint8 vacuumFlags
Definition: proc.h:233
#define PROC_VACUUM_STATE_MASK
Definition: proc.h:62
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1294
bool recoveryConflictPending
Definition: proc.h:127
uint8 nxids
Definition: proc.h:238
#define InvalidTransactionId
Definition: transam.h:31
bool delayChkpt
Definition: proc.h:235
static PGXACT * allPgXact
Definition: procarray.c:104
bool overflowed
Definition: proc.h:234
static void ProcArrayEndTransactionInternal(PGPROC *proc, PGXACT *pgxact, TransactionId latestXid)
Definition: procarray.c:452
#define Assert(condition)
Definition: c.h:739
int pgprocno
Definition: proc.h:110
#define InvalidLocalTransactionId
Definition: lock.h:68
#define TransactionIdIsValid(xid)
Definition: transam.h:41
LocalTransactionId lxid
Definition: proc.h:106

◆ ProcArrayGetReplicationSlotXmin()

void ProcArrayGetReplicationSlotXmin ( TransactionId xmin,
TransactionId catalog_xmin 
)

Definition at line 3117 of file procarray.c.

References LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::replication_slot_catalog_xmin, and ProcArrayStruct::replication_slot_xmin.

Referenced by logical_begin_heap_rewrite(), and XLogWalRcvSendHSFeedback().

3119 {
3120  LWLockAcquire(ProcArrayLock, LW_SHARED);
3121 
3122  if (xmin != NULL)
3124 
3125  if (catalog_xmin != NULL)
3126  *catalog_xmin = procArray->replication_slot_catalog_xmin;
3127 
3128  LWLockRelease(ProcArrayLock);
3129 }
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ ProcArrayInitRecovery()

void ProcArrayInitRecovery ( TransactionId  initializedUptoXID)

Definition at line 633 of file procarray.c.

References Assert, latestObservedXid, STANDBY_INITIALIZED, standbyState, TransactionIdIsNormal, and TransactionIdRetreat.

Referenced by StartupXLOG().

634 {
636  Assert(TransactionIdIsNormal(initializedUptoXID));
637 
638  /*
639  * we set latestObservedXid to the xid SUBTRANS has been initialized up
640  * to, so we can extend it from that point onwards in
641  * RecordKnownAssignedTransactionIds, and when we get consistent in
642  * ProcArrayApplyRecoveryInfo().
643  */
644  latestObservedXid = initializedUptoXID;
646 }
static TransactionId latestObservedXid
Definition: procarray.c:111
#define TransactionIdRetreat(dest)
Definition: transam.h:92
#define Assert(condition)
Definition: c.h:739
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
HotStandbyState standbyState
Definition: xlog.c:203

◆ ProcArrayInstallImportedXmin()

bool ProcArrayInstallImportedXmin ( TransactionId  xmin,
VirtualTransactionId sourcevxid 
)

Definition at line 1796 of file procarray.c.

References Assert, VirtualTransactionId::backendId, PGPROC::backendId, PGPROC::databaseId, VirtualTransactionId::localTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), PGPROC::lxid, MyDatabaseId, MyPgXact, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PROC_IN_VACUUM, procArray, TransactionIdIsNormal, TransactionIdPrecedesOrEquals(), TransactionXmin, UINT32_ACCESS_ONCE, PGXACT::vacuumFlags, and PGXACT::xmin.

Referenced by GetSerializableTransactionSnapshotInt(), and SetTransactionSnapshot().

1798 {
1799  bool result = false;
1800  ProcArrayStruct *arrayP = procArray;
1801  int index;
1802 
1804  if (!sourcevxid)
1805  return false;
1806 
1807  /* Get lock so source xact can't end while we're doing this */
1808  LWLockAcquire(ProcArrayLock, LW_SHARED);
1809 
1810  for (index = 0; index < arrayP->numProcs; index++)
1811  {
1812  int pgprocno = arrayP->pgprocnos[index];
1813  PGPROC *proc = &allProcs[pgprocno];
1814  PGXACT *pgxact = &allPgXact[pgprocno];
1815  TransactionId xid;
1816 
1817  /* Ignore procs running LAZY VACUUM */
1818  if (pgxact->vacuumFlags & PROC_IN_VACUUM)
1819  continue;
1820 
1821  /* We are only interested in the specific virtual transaction. */
1822  if (proc->backendId != sourcevxid->backendId)
1823  continue;
1824  if (proc->lxid != sourcevxid->localTransactionId)
1825  continue;
1826 
1827  /*
1828  * We check the transaction's database ID for paranoia's sake: if it's
1829  * in another DB then its xmin does not cover us. Caller should have
1830  * detected this already, so we just treat any funny cases as
1831  * "transaction not found".
1832  */
1833  if (proc->databaseId != MyDatabaseId)
1834  continue;
1835 
1836  /*
1837  * Likewise, let's just make real sure its xmin does cover us.
1838  */
1839  xid = UINT32_ACCESS_ONCE(pgxact->xmin);
1840  if (!TransactionIdIsNormal(xid) ||
1841  !TransactionIdPrecedesOrEquals(xid, xmin))
1842  continue;
1843 
1844  /*
1845  * We're good. Install the new xmin. As in GetSnapshotData, set
1846  * TransactionXmin too. (Note that because snapmgr.c called
1847  * GetSnapshotData first, we'll be overwriting a valid xmin here, so
1848  * we don't check that.)
1849  */
1850  MyPgXact->xmin = TransactionXmin = xmin;
1851 
1852  result = true;
1853  break;
1854  }
1855 
1856  LWLockRelease(ProcArrayLock);
1857 
1858  return result;
1859 }
BackendId backendId
Definition: proc.h:113
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
LocalTransactionId localTransactionId
Definition: lock.h:65
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:233
TransactionId TransactionXmin
Definition: snapmgr.c:166
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define PROC_IN_VACUUM
Definition: proc.h:54
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
Oid MyDatabaseId
Definition: globals.c:85
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
#define Assert(condition)
Definition: c.h:739
BackendId backendId
Definition: lock.h:64
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Definition: proc.h:95
LocalTransactionId lxid
Definition: proc.h:106

◆ ProcArrayInstallRestoredXmin()

bool ProcArrayInstallRestoredXmin ( TransactionId  xmin,
PGPROC proc 
)

Definition at line 1871 of file procarray.c.

References Assert, PGPROC::databaseId, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyDatabaseId, MyPgXact, PGPROC::pgprocno, TransactionIdIsNormal, TransactionIdPrecedesOrEquals(), TransactionXmin, UINT32_ACCESS_ONCE, and PGXACT::xmin.

Referenced by SetTransactionSnapshot().

1872 {
1873  bool result = false;
1874  TransactionId xid;
1875  PGXACT *pgxact;
1876 
1878  Assert(proc != NULL);
1879 
1880  /* Get lock so source xact can't end while we're doing this */
1881  LWLockAcquire(ProcArrayLock, LW_SHARED);
1882 
1883  pgxact = &allPgXact[proc->pgprocno];
1884 
1885  /*
1886  * Be certain that the referenced PGPROC has an advertised xmin which is
1887  * no later than the one we're installing, so that the system-wide xmin
1888  * can't go backwards. Also, make sure it's running in the same database,
1889  * so that the per-database xmin cannot go backwards.
1890  */
1891  xid = UINT32_ACCESS_ONCE(pgxact->xmin);
1892  if (proc->databaseId == MyDatabaseId &&
1893  TransactionIdIsNormal(xid) &&
1894  TransactionIdPrecedesOrEquals(xid, xmin))
1895  {
1896  MyPgXact->xmin = TransactionXmin = xmin;
1897  result = true;
1898  }
1899 
1900  LWLockRelease(ProcArrayLock);
1901 
1902  return result;
1903 }
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:228
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
PGXACT * MyPgXact
Definition: proc.c:68
TransactionId TransactionXmin
Definition: snapmgr.c:166
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
Oid databaseId
Definition: proc.h:114
static PGXACT * allPgXact
Definition: procarray.c:104
Oid MyDatabaseId
Definition: globals.c:85
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int pgprocno
Definition: proc.h:110
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

◆ ProcArrayRemove()

void ProcArrayRemove ( PGPROC proc,
TransactionId  latestXid 
)

Definition at line 335 of file procarray.c.

References Assert, elog, VariableCacheData::latestCompletedXid, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), memmove, ProcArrayStruct::numProcs, PGPROC::pgprocno, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, ShmemVariableCache, TransactionIdIsValid, TransactionIdPrecedes(), and PGXACT::xid.

Referenced by FinishPreparedTransaction(), and RemoveProcFromArray().

336 {
337  ProcArrayStruct *arrayP = procArray;
338  int index;
339 
340 #ifdef XIDCACHE_DEBUG
341  /* dump stats at backend shutdown, but not prepared-xact end */
342  if (proc->pid != 0)
343  DisplayXidCache();
344 #endif
345 
346  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
347 
348  if (TransactionIdIsValid(latestXid))
349  {
351 
352  /* Advance global latestCompletedXid while holding the lock */
354  latestXid))
356  }
357  else
358  {
359  /* Shouldn't be trying to remove a live transaction here */
361  }
362 
363  for (index = 0; index < arrayP->numProcs; index++)
364  {
365  if (arrayP->pgprocnos[index] == proc->pgprocno)
366  {
367  /* Keep the PGPROC array sorted. See notes above */
368  memmove(&arrayP->pgprocnos[index], &arrayP->pgprocnos[index + 1],
369  (arrayP->numProcs - index - 1) * sizeof(int));
370  arrayP->pgprocnos[arrayP->numProcs - 1] = -1; /* for debugging */
371  arrayP->numProcs--;
372  LWLockRelease(ProcArrayLock);
373  return;
374  }
375  }
376 
377  /* Oops */
378  LWLockRelease(ProcArrayLock);
379 
380  elog(LOG, "failed to find proc %p in ProcArray", proc);
381 }
TransactionId xid
Definition: proc.h:224
#define LOG
Definition: elog.h:26
Definition: type.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define memmove(d, s, c)
Definition: c.h:1267
VariableCache ShmemVariableCache
Definition: varsup.c:34
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int pgprocno
Definition: proc.h:110
#define elog(elevel,...)
Definition: elog.h:228
#define TransactionIdIsValid(xid)
Definition: transam.h:41
int pid
Definition: proc.h:109
TransactionId latestCompletedXid
Definition: transam.h:182

◆ ProcArraySetReplicationSlotXmin()

void ProcArraySetReplicationSlotXmin ( TransactionId  xmin,
TransactionId  catalog_xmin,
bool  already_locked 
)

Definition at line 3095 of file procarray.c.

References Assert, LW_EXCLUSIVE, LWLockAcquire(), LWLockHeldByMe(), LWLockRelease(), ProcArrayStruct::replication_slot_catalog_xmin, and ProcArrayStruct::replication_slot_xmin.

Referenced by ReplicationSlotsComputeRequiredXmin().

3097 {
3098  Assert(!already_locked || LWLockHeldByMe(ProcArrayLock));
3099 
3100  if (!already_locked)
3101  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3102 
3104  procArray->replication_slot_catalog_xmin = catalog_xmin;
3105 
3106  if (!already_locked)
3107  LWLockRelease(ProcArrayLock);
3108 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:95
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static ProcArrayStruct * procArray
Definition: procarray.c:101
TransactionId replication_slot_xmin
Definition: procarray.c:93
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ ProcArrayShmemSize()

Size ProcArrayShmemSize ( void  )

Definition at line 182 of file procarray.c.

References add_size(), EnableHotStandby, mul_size(), offsetof, ProcArrayStruct::pgprocnos, PROCARRAY_MAXPROCS, and TOTAL_MAX_CACHED_SUBXIDS.

Referenced by CreateSharedMemoryAndSemaphores().

183 {
184  Size size;
185 
186  /* Size of the ProcArray structure itself */
187 #define PROCARRAY_MAXPROCS (MaxBackends + max_prepared_xacts)
188 
189  size = offsetof(ProcArrayStruct, pgprocnos);
190  size = add_size(size, mul_size(sizeof(int), PROCARRAY_MAXPROCS));
191 
192  /*
193  * During Hot Standby processing we have a data structure called
194  * KnownAssignedXids, created in shared memory. Local data structures are
195  * also created in various backends during GetSnapshotData(),
196  * TransactionIdIsInProgress() and GetRunningTransactionData(). All of the
197  * main structures created in those functions must be identically sized,
198  * since we may at times copy the whole of the data structures around. We
199  * refer to this size as TOTAL_MAX_CACHED_SUBXIDS.
200  *
201  * Ideally we'd only create this structure if we were actually doing hot
202  * standby in the current run, but we don't know that yet at the time
203  * shared memory is being set up.
204  */
205 #define TOTAL_MAX_CACHED_SUBXIDS \
206  ((PGPROC_MAX_CACHED_SUBXIDS + 1) * PROCARRAY_MAXPROCS)
207 
208  if (EnableHotStandby)
209  {
210  size = add_size(size,
211  mul_size(sizeof(TransactionId),
213  size = add_size(size,
214  mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS));
215  }
216 
217  return size;
218 }
#define PROCARRAY_MAXPROCS
uint32 TransactionId
Definition: c.h:514
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
#define TOTAL_MAX_CACHED_SUBXIDS
size_t Size
Definition: c.h:467
bool EnableHotStandby
Definition: xlog.c:93
#define offsetof(type, field)
Definition: c.h:662

◆ RecordKnownAssignedTransactionIds()

void RecordKnownAssignedTransactionIds ( TransactionId  xid)

Definition at line 3310 of file procarray.c.

References AdvanceNextFullTransactionIdPastXid(), Assert, DEBUG4, elog, ExtendSUBTRANS(), KnownAssignedXidsAdd(), latestObservedXid, STANDBY_INITIALIZED, standbyState, trace_recovery(), TransactionIdAdvance, TransactionIdFollows(), TransactionIdIsValid, and TransactionIdPrecedes().

Referenced by ProcArrayApplyXidAssignment(), StartupXLOG(), xact_redo_abort(), and xact_redo_commit().

3311 {
3315 
3316  elog(trace_recovery(DEBUG4), "record known xact %u latestObservedXid %u",
3317  xid, latestObservedXid);
3318 
3319  /*
3320  * When a newly observed xid arrives, it is frequently the case that it is
3321  * *not* the next xid in sequence. When this occurs, we must treat the
3322  * intervening xids as running also.
3323  */
3325  {
3326  TransactionId next_expected_xid;
3327 
3328  /*
3329  * Extend subtrans like we do in GetNewTransactionId() during normal
3330  * operation using individual extend steps. Note that we do not need
3331  * to extend clog since its extensions are WAL logged.
3332  *
3333  * This part has to be done regardless of standbyState since we
3334  * immediately start assigning subtransactions to their toplevel
3335  * transactions.
3336  */
3337  next_expected_xid = latestObservedXid;
3338  while (TransactionIdPrecedes(next_expected_xid, xid))
3339  {
3340  TransactionIdAdvance(next_expected_xid);
3341  ExtendSUBTRANS(next_expected_xid);
3342  }
3343  Assert(next_expected_xid == xid);
3344 
3345  /*
3346  * If the KnownAssignedXids machinery isn't up yet, there's nothing
3347  * more to do since we don't track assigned xids yet.
3348  */
3350  {
3351  latestObservedXid = xid;
3352  return;
3353  }
3354 
3355  /*
3356  * Add (latestObservedXid, xid] onto the KnownAssignedXids array.
3357  */
3358  next_expected_xid = latestObservedXid;
3359  TransactionIdAdvance(next_expected_xid);
3360  KnownAssignedXidsAdd(next_expected_xid, xid, false);
3361 
3362  /*
3363  * Now we can advance latestObservedXid
3364  */
3365  latestObservedXid = xid;
3366 
3367  /* ShmemVariableCache->nextFullXid must be beyond any observed xid */
3369  next_expected_xid = latestObservedXid;
3370  TransactionIdAdvance(next_expected_xid);
3371  }
3372 }
#define TransactionIdAdvance(dest)
Definition: transam.h:75
static TransactionId latestObservedXid
Definition: procarray.c:111
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:514
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:262
#define DEBUG4
Definition: elog.h:22
int trace_recovery(int trace_level)
Definition: elog.c:3589
void ExtendSUBTRANS(TransactionId newestXact)
Definition: subtrans.c:326
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define Assert(condition)
Definition: c.h:739
static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid, bool exclusive_lock)
Definition: procarray.c:3583
#define elog(elevel,...)
Definition: elog.h:228
#define TransactionIdIsValid(xid)
Definition: transam.h:41
HotStandbyState standbyState
Definition: xlog.c:203

◆ TerminateOtherDBBackends()

void TerminateOtherDBBackends ( Oid  databaseId)

Definition at line 2987 of file procarray.c.

References BackendPidGetProc(), PGPROC::databaseId, ereport, errcode(), errdetail_plural(), errmsg(), ERROR, get_database_name(), GetUserId(), has_privs_of_role(), i, kill, lappend_int(), lfirst_int, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyProc, NIL, ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, PGPROC::roleId, superuser(), and superuser_arg().

Referenced by dropdb().

2988 {
2989  ProcArrayStruct *arrayP = procArray;
2990  List *pids = NIL;
2991  int nprepared = 0;
2992  int i;
2993 
2994  LWLockAcquire(ProcArrayLock, LW_SHARED);
2995 
2996  for (i = 0; i < procArray->numProcs; i++)
2997  {
2998  int pgprocno = arrayP->pgprocnos[i];
2999  PGPROC *proc = &allProcs[pgprocno];
3000 
3001  if (proc->databaseId != databaseId)
3002  continue;
3003  if (proc == MyProc)
3004  continue;
3005 
3006  if (proc->pid != 0)
3007  pids = lappend_int(pids, proc->pid);
3008  else
3009  nprepared++;
3010  }
3011 
3012  LWLockRelease(ProcArrayLock);
3013 
3014  if (nprepared > 0)
3015  ereport(ERROR,
3016  (errcode(ERRCODE_OBJECT_IN_USE),
3017  errmsg("database \"%s\" is being used by prepared transaction",
3018  get_database_name(databaseId)),
3019  errdetail_plural("There is %d prepared transaction using the database.",
3020  "There are %d prepared transactions using the database.",
3021  nprepared,
3022  nprepared)));
3023 
3024  if (pids)
3025  {
3026  ListCell *lc;
3027 
3028  /*
3029  * Check whether we have the necessary rights to terminate other
3030  * sessions. We don't terminate any session untill we ensure that we
3031  * have rights on all the sessions to be terminated. These checks are
3032  * the same as we do in pg_terminate_backend.
3033  *
3034  * In this case we don't raise some warnings - like "PID %d is not a
3035  * PostgreSQL server process", because for us already finished session
3036  * is not a problem.
3037  */
3038  foreach(lc, pids)
3039  {
3040  int pid = lfirst_int(lc);
3041  PGPROC *proc = BackendPidGetProc(pid);
3042 
3043  if (proc != NULL)
3044  {
3045  /* Only allow superusers to signal superuser-owned backends. */
3046  if (superuser_arg(proc->roleId) && !superuser())
3047  ereport(ERROR,
3048  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3049  (errmsg("must be a superuser to terminate superuser process"))));
3050 
3051  /* Users can signal backends they have role membership in. */
3052  if (!has_privs_of_role(GetUserId(), proc->roleId) &&
3053  !has_privs_of_role(GetUserId(), DEFAULT_ROLE_SIGNAL_BACKENDID))
3054  ereport(ERROR,
3055  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3056  (errmsg("must be a member of the role whose process is being terminated or member of pg_signal_backend"))));
3057  }
3058  }
3059 
3060  /*
3061  * There's a race condition here: once we release the ProcArrayLock,
3062  * it's possible for the session to exit before we issue kill. That
3063  * race condition possibility seems too unlikely to worry about. See
3064  * pg_signal_backend.
3065  */
3066  foreach(lc, pids)
3067  {
3068  int pid = lfirst_int(lc);
3069  PGPROC *proc = BackendPidGetProc(pid);
3070 
3071  if (proc != NULL)
3072  {
3073  /*
3074  * If we have setsid(), signal the backend's whole process
3075  * group
3076  */
3077 #ifdef HAVE_SETSID
3078  (void) kill(-pid, SIGTERM);
3079 #else
3080  (void) kill(pid, SIGTERM);
3081 #endif
3082  }
3083  }
3084  }
3085 }
#define NIL
Definition: pg_list.h:65
Oid GetUserId(void)
Definition: miscinit.c:380
PGPROC * BackendPidGetProc(int pid)
Definition: procarray.c:2365
PGPROC * MyProc
Definition: proc.c:67
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4900
Oid roleId
Definition: proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:608
bool superuser(void)
Definition: superuser.c:46
#define kill(pid, sig)
Definition: win32_port.h:426
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
static PGPROC * allProcs
Definition: procarray.c:103
Oid databaseId
Definition: proc.h:114
#define ereport(elevel, rest)
Definition: elog.h:141
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
List * lappend_int(List *list, int datum)
Definition: list.c:340
static ProcArrayStruct * procArray
Definition: procarray.c:101
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1047
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
Definition: proc.h:95
Definition: pg_list.h:50
int pid
Definition: proc.h:109

◆ TransactionIdIsActive()

bool TransactionIdIsActive ( TransactionId  xid)

Definition at line 1207 of file procarray.c.

References i, LW_SHARED, LWLockAcquire(), LWLockRelease(), ProcArrayStruct::numProcs, ProcArrayStruct::pgprocnos, PGPROC::pid, procArray, RecentXmin, TransactionIdEquals, TransactionIdIsValid, TransactionIdPrecedes(), UINT32_ACCESS_ONCE, and PGXACT::xid.

1208 {
1209  bool result = false;
1210  ProcArrayStruct *arrayP = procArray;
1211  int i;
1212 
1213  /*
1214  * Don't bother checking a transaction older than RecentXmin; it could not
1215  * possibly still be running.
1216  */
1218  return false;
1219 
1220  LWLockAcquire(ProcArrayLock, LW_SHARED);
1221 
1222  for (i = 0; i < arrayP->numProcs; i++)
1223  {
1224  int pgprocno = arrayP->pgprocnos[i];
1225  PGPROC *proc = &allProcs[pgprocno];
1226  PGXACT *pgxact = &allPgXact[pgprocno];
1227  TransactionId pxid;
1228 
1229  /* Fetch xid just once - see GetNewTransactionId */
1230  pxid = UINT32_ACCESS_ONCE(pgxact->xid);
1231 
1232  if (!TransactionIdIsValid(pxid))
1233  continue;
1234 
1235  if (proc->pid == 0)
1236  continue; /* ignore prepared transactions */
1237 
1238  if (TransactionIdEquals(pxid, xid))
1239  {
1240  result = true;
1241  break;
1242  }
1243  }
1244 
1245  LWLockRelease(ProcArrayLock);
1246 
1247  return result;
1248 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
TransactionId xid
Definition: proc.h:224
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
TransactionId RecentXmin
Definition: snapmgr.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static PGPROC * allProcs
Definition: procarray.c:103
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int i
#define TransactionIdIsValid(xid)
Definition: transam.h:41
Definition: proc.h:95
int pid
Definition: proc.h:109

◆ TransactionIdIsInProgress()

bool TransactionIdIsInProgress ( TransactionId  xid)

Definition at line 987 of file procarray.c.

References Assert, ereport, errcode(), errmsg(), ERROR, i, KnownAssignedXidExists(), KnownAssignedXidsGet(), ProcArrayStruct::lastOverflowedXid, VariableCacheData::latestCompletedXid, LW_SHARED, LWLockAcquire(), LWLockRelease(), malloc, ProcArrayStruct::maxProcs, MyProc, ProcArrayStruct::numProcs, PGXACT::nxids, PGXACT::overflowed, pg_read_barrier, ProcArrayStruct::pgprocnos, procArray, RecentXmin, RecoveryInProgress(), ShmemVariableCache, SubTransGetTopmostTransaction(), PGPROC::subxids, TOTAL_MAX_CACHED_SUBXIDS, TransactionIdDidAbort(), TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TransactionIdIsKnownCompleted(), TransactionIdIsValid, TransactionIdPrecedes(), TransactionIdPrecedesOrEquals(), UINT32_ACCESS_ONCE, xc_by_child_xid_inc, xc_by_known_assigned_inc, xc_by_known_xact_inc, xc_by_latest_xid_inc, xc_by_main_xid_inc, xc_by_my_xact_inc, xc_by_recent_xmin_inc, xc_no_overflow_inc, xc_slow_answer_inc, PGXACT::xid, and XidCache::xids.

Referenced by check_safe_enum_use(), compute_new_xmax_infomask(), ConditionalXactLockTableWait(), Do_MultiXactIdWait(), DoesMultiXactIdConflict(), FreezeMultiXactId(), HeapTupleHeaderIsOnlyLocked(), HeapTupleSatisfiesDirty(), HeapTupleSatisfiesSelf(), HeapTupleSatisfiesToast(), HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesVacuum(), MultiXactIdExpand(), MultiXactIdIsRunning(), test_lockmode_for_conflict(), and XactLockTableWait().

988 {
989  static TransactionId *xids = NULL;
990  int nxids = 0;
991  ProcArrayStruct *arrayP = procArray;
992  TransactionId topxid;
993  int i,
994  j;
995 
996  /*
997  * Don't bother checking a transaction older than RecentXmin; it could not
998  * possibly still be running. (Note: in particular, this guarantees that
999  * we reject InvalidTransactionId, FrozenTransactionId, etc as not
1000  * running.)
1001  */
1003  {
1005  return false;
1006  }
1007 
1008  /*
1009  * We may have just checked the status of this transaction, so if it is
1010  * already known to be completed, we can fall out without any access to
1011  * shared memory.
1012  */
1014  {
1016  return false;
1017  }
1018 
1019  /*
1020  * Also, we can handle our own transaction (and subtransactions) without
1021  * any access to shared memory.
1022  */
1024  {
1026  return true;
1027  }
1028 
1029  /*
1030  * If first time through, get workspace to remember main XIDs in. We
1031  * malloc it permanently to avoid repeated palloc/pfree overhead.
1032  */
1033  if (xids == NULL)
1034  {
1035  /*
1036  * In hot standby mode, reserve enough space to hold all xids in the
1037  * known-assigned list. If we later finish recovery, we no longer need
1038  * the bigger array, but we don't bother to shrink it.
1039  */
1040  int maxxids = RecoveryInProgress() ? TOTAL_MAX_CACHED_SUBXIDS : arrayP->maxProcs;
1041 
1042  xids = (TransactionId *) malloc(maxxids * sizeof(TransactionId));
1043  if (xids == NULL)
1044  ereport(ERROR,
1045  (errcode(ERRCODE_OUT_OF_MEMORY),
1046  errmsg("out of memory")));
1047  }
1048 
1049  LWLockAcquire(ProcArrayLock, LW_SHARED);
1050 
1051  /*
1052  * Now that we have the lock, we can check latestCompletedXid; if the
1053  * target Xid is after that, it's surely still running.
1054  */
1056  {
1057  LWLockRelease(ProcArrayLock);
1059  return true;
1060  }
1061 
1062  /* No shortcuts, gotta grovel through the array */
1063  for (i = 0; i < arrayP->numProcs; i++)
1064  {
1065  int pgprocno = arrayP->pgprocnos[i];
1066  PGPROC *proc = &allProcs[pgprocno];
1067  PGXACT *pgxact = &allPgXact[pgprocno];
1068  TransactionId pxid;
1069  int pxids;
1070 
1071  /* Ignore my own proc --- dealt with it above */
1072  if (proc == MyProc)
1073  continue;
1074 
1075  /* Fetch xid just once - see GetNewTransactionId */
1076  pxid = UINT32_ACCESS_ONCE(pgxact->xid);
1077 
1078  if (!TransactionIdIsValid(pxid))
1079  continue;
1080 
1081  /*
1082  * Step 1: check the main Xid
1083  */
1084  if (TransactionIdEquals(pxid, xid))
1085  {
1086  LWLockRelease(ProcArrayLock);
1088  return true;
1089  }
1090 
1091  /*
1092  * We can ignore main Xids that are younger than the target Xid, since
1093  * the target could not possibly be their child.
1094  */
1095  if (TransactionIdPrecedes(xid, pxid))
1096  continue;
1097 
1098  /*
1099  * Step 2: check the cached child-Xids arrays
1100  */
1101  pxids = pgxact->nxids;
1102  pg_read_barrier(); /* pairs with barrier in GetNewTransactionId() */
1103  for (j = pxids - 1; j >= 0; j--)
1104  {
1105  /* Fetch xid just once - see GetNewTransactionId */
1106  TransactionId cxid = UINT32_ACCESS_ONCE(proc->subxids.xids[j]);
1107 
1108  if (TransactionIdEquals(cxid, xid))
1109  {
1110  LWLockRelease(ProcArrayLock);
1112  return true;
1113  }
1114  }
1115 
1116  /*
1117  * Save the main Xid for step 4. We only need to remember main Xids
1118  * that have uncached children. (Note: there is no race condition
1119  * here because the overflowed flag cannot be cleared, only set, while
1120  * we hold ProcArrayLock. So we can't miss an Xid that we need to
1121  * worry about.)
1122  */
1123  if (pgxact->overflowed)
1124  xids[nxids++] = pxid;
1125  }
1126 
1127  /*
1128  * Step 3: in hot standby mode, check the known-assigned-xids list. XIDs
1129  * in the list must be treated as running.
1130  */
1131  if (RecoveryInProgress())
1132  {
1133  /* none of the PGXACT entries should have XIDs in hot standby mode */
1134  Assert(nxids == 0);
1135 
1136  if (KnownAssignedXidExists(xid))
1137  {
1138  LWLockRelease(ProcArrayLock);
1140  return true;
1141  }
1142 
1143  /*
1144  * If the KnownAssignedXids overflowed, we have to check pg_subtrans
1145  * too. Fetch all xids from KnownAssignedXids that are lower than
1146  * xid, since if xid is a subtransaction its parent will always have a
1147  * lower value. Note we will collect both main and subXIDs here, but
1148  * there's no help for it.
1149  */
1151  nxids = KnownAssignedXidsGet(xids, xid);
1152  }
1153 
1154  LWLockRelease(ProcArrayLock);
1155 
1156  /*
1157  * If none of the relevant caches overflowed, we know the Xid is not
1158  * running without even looking at pg_subtrans.
1159  */
1160  if (nxids == 0)
1161  {
1163  return false;
1164  }
1165 
1166  /*
1167  * Step 4: have to check pg_subtrans.
1168  *
1169  * At this point, we know it's either a subtransaction of one of the Xids
1170  * in xids[], or it's not running. If it's an already-failed
1171  * subtransaction, we want to say "not running" even though its parent may
1172  * still be running. So first, check pg_xact to see if it's been aborted.
1173  */
1175 
1176  if (TransactionIdDidAbort(xid))
1177  return false;
1178 
1179  /*
1180  * It isn't aborted, so check whether the transaction tree it belongs to
1181  * is still running (or, more precisely, whether it was running when we
1182  * held ProcArrayLock).
1183  */
1184  topxid = SubTransGetTopmostTransaction(xid);
1185  Assert(TransactionIdIsValid(topxid));
1186  if (!TransactionIdEquals(topxid, xid))
1187  {
1188  for (i = 0; i < nxids; i++)
1189  {
1190  if (TransactionIdEquals(xids[i], topxid))
1191  return true;
1192  }
1193  }
1194 
1195  return false;
1196 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:853
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:150
PGPROC * MyProc
Definition: proc.c:67
TransactionId xid
Definition: proc.h:224
#define UINT32_ACCESS_ONCE(var)
Definition: procarray.c:66
#define xc_by_my_xact_inc()
Definition: procarray.c:148
int errcode(int sqlerrcode)
Definition: elog.c:608
TransactionId RecentXmin
Definition: snapmgr.c:167
bool RecoveryInProgress(void)
Definition: xlog.c:7935
#define xc_by_child_xid_inc()
Definition: procarray.c:151
bool TransactionIdIsKnownCompleted(TransactionId transactionId)
Definition: transam.c:238
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define xc_by_recent_xmin_inc()
Definition: procarray.c:146
#define xc_by_known_xact_inc()
Definition: procarray.c:147
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
#define ERROR
Definition: elog.h:43
#define xc_by_main_xid_inc()
Definition: procarray.c:150
#define xc_by_known_assigned_inc()
Definition: procarray.c:152
uint8 nxids
Definition: proc.h:238
VariableCache ShmemVariableCache
Definition: varsup.c:34
static PGPROC * allProcs
Definition: procarray.c:103
struct XidCache subxids
Definition: proc.h:162
TransactionId lastOverflowedXid
Definition: procarray.c:90
#define ereport(elevel, rest)
Definition: elog.h:141
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
#define xc_by_latest_xid_inc()
Definition: procarray.c:149
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static ProcArrayStruct * procArray
Definition: procarray.c:101
static PGXACT * allPgXact
Definition: procarray.c:104
static int KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax)
Definition: procarray.c:3933
bool overflowed
Definition: proc.h:234
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:98
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
#define TOTAL_MAX_CACHED_SUBXIDS
#define Assert(condition)
Definition: c.h:739
#define pg_read_barrier()
Definition: atomics.h:158
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define xc_no_overflow_inc()
Definition: procarray.c:153
static bool KnownAssignedXidExists(TransactionId xid)
Definition: procarray.c:3794
#define xc_slow_answer_inc()
Definition: procarray.c:154
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
#define TransactionIdIsValid(xid)
Definition: transam.h:41
Definition: proc.h:95
TransactionId latestCompletedXid
Definition: transam.h:182

◆ XidCacheRemoveRunningXids()

void XidCacheRemoveRunningXids ( TransactionId  xid,
int  nxids,
const TransactionId xids,
TransactionId  latestXid 
)

Definition at line 3148 of file procarray.c.

References Assert, elog, fprintf, i, VariableCacheData::latestCompletedXid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyPgXact, MyProc, PGXACT::nxids, ShmemVariableCache, PGPROC::subxids, TransactionIdEquals, TransactionIdIsValid, TransactionIdPrecedes(), WARNING, XidCacheRemove, and XidCache::xids.

Referenced by RecordTransactionAbort().

3151 {
3152  int i,
3153  j;
3154 
3156 
3157  /*
3158  * We must hold ProcArrayLock exclusively in order to remove transactions
3159  * from the PGPROC array. (See src/backend/access/transam/README.) It's
3160  * possible this could be relaxed since we know this routine is only used
3161  * to abort subtransactions, but pending closer analysis we'd best be
3162  * conservative.
3163  *
3164  * Note that we do not have to be careful about memory ordering of our own
3165  * reads wrt. GetNewTransactionId() here - only this process can modify
3166  * relevant fields of MyProc/MyPgXact. But we do have to be careful about
3167  * our own writes being well ordered.
3168  */
3169  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3170 
3171  /*
3172  * Under normal circumstances xid and xids[] will be in increasing order,
3173  * as will be the entries in subxids. Scan backwards to avoid O(N^2)
3174  * behavior when removing a lot of xids.
3175  */
3176  for (i = nxids - 1; i >= 0; i--)
3177  {
3178  TransactionId anxid = xids[i];
3179 
3180  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3181  {
3182  if (TransactionIdEquals(MyProc->subxids.xids[j], anxid))
3183  {
3184  XidCacheRemove(j);
3185  break;
3186  }
3187  }
3188 
3189  /*
3190  * Ordinarily we should have found it, unless the cache has
3191  * overflowed. However it's also possible for this routine to be
3192  * invoked multiple times for the same subtransaction, in case of an
3193  * error during AbortSubTransaction. So instead of Assert, emit a
3194  * debug warning.
3195  */
3196  if (j < 0 && !MyPgXact->overflowed)
3197  elog(WARNING, "did not find subXID %u in MyProc", anxid);
3198  }
3199 
3200  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3201  {
3202  if (TransactionIdEquals(MyProc->subxids.xids[j], xid))
3203  {
3204  XidCacheRemove(j);
3205  break;
3206  }
3207  }
3208  /* Ordinarily we should have found it, unless the cache has overflowed */
3209  if (j < 0 && !MyPgXact->overflowed)
3210  elog(WARNING, "did not find subXID %u in MyProc", xid);
3211 
3212  /* Also advance global latestCompletedXid while holding the lock */
3214  latestXid))
3216 
3217  LWLockRelease(ProcArrayLock);
3218 }
#define XidCacheRemove(i)
Definition: procarray.c:3132
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
PGPROC * MyProc
Definition: proc.c:67
PGXACT * MyPgXact
Definition: proc.c:68
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
uint8 nxids
Definition: proc.h:238
VariableCache ShmemVariableCache
Definition: varsup.c:34
struct XidCache subxids
Definition: proc.h:162
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define WARNING
Definition: elog.h:40
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define elog(elevel,...)
Definition: elog.h:228
int i
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TransactionId latestCompletedXid
Definition: transam.h:182