1 /*-------------------------------------------------------------------------
4 * POSTGRES process array code.
7 * This module maintains arrays of PGPROC substructures, as well as associated
8 * arrays in ProcGlobal, for all active backends. Although there are several
9 * uses for this, the principal one is as a means of determining the set of
10 * currently running transactions.
12 * Because of various subtle race conditions it is critical that a backend
13 * hold the correct locks while setting or clearing its xid (in
14 * ProcGlobal->xids[]/MyProc->xid). See notes in
15 * src/backend/access/transam/README.
17 * The process arrays now also include structures representing prepared
18 * transactions. The xid and subxids fields of these are valid, as are the
19 * myProcLocks lists. They can be distinguished from regular backend PGPROCs
20 * at need by checking for pid == 0.
22 * During hot standby, we also keep a list of XIDs representing transactions
23 * that are known to be running on the primary (or more precisely, were running
24 * as of the current point in the WAL stream). This list is kept in the
25 * KnownAssignedXids array, and is updated by watching the sequence of
26 * arriving XIDs. This is necessary because if we leave those XIDs out of
27 * snapshots taken for standby queries, then they will appear to be already
28 * complete, leading to MVCC failures. Note that in hot standby, the PGPROC
29 * array represents standby processes, which by definition are not running
30 * transactions that have XIDs.
32 * It is perhaps possible for a backend on the primary to terminate without
33 * writing an abort record for its transaction. While that shouldn't really
34 * happen, it would tie up KnownAssignedXids indefinitely, so we protect
35 * ourselves by pruning the array when a valid list of running XIDs arrives.
37 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
38 * Portions Copyright (c) 1994, Regents of the University of California
42 * src/backend/storage/ipc/procarray.c
44 *-------------------------------------------------------------------------
50 #include "access/subtrans.h"
51 #include "access/transam.h"
52 #include "access/twophase.h"
53 #include "access/xact.h"
54 #include "access/xlogutils.h"
55 #include "catalog/catalog.h"
56 #include "catalog/pg_authid.h"
57 #include "commands/dbcommands.h"
58 #include "miscadmin.h"
60 #include "port/pg_lfind.h"
61 #include "storage/proc.h"
62 #include "storage/procarray.h"
63 #include "utils/acl.h"
64 #include "utils/builtins.h"
65 #include "utils/rel.h"
66 #include "utils/snapmgr.h"
68 #define UINT32_ACCESS_ONCE(var) ((uint32)(*((volatile uint32 *)&(var))))
70 /* Our shared memory area */
71 typedef struct ProcArrayStruct
73 int numProcs
; /* number of valid procs entries */
74 int maxProcs
; /* allocated size of procs array */
77 * Known assigned XIDs handling
79 int maxKnownAssignedXids
; /* allocated size of array */
80 int numKnownAssignedXids
; /* current # of valid entries */
81 int tailKnownAssignedXids
; /* index of oldest valid element */
82 int headKnownAssignedXids
; /* index of newest element, + 1 */
85 * Highest subxid that has been removed from KnownAssignedXids array to
86 * prevent overflow; or InvalidTransactionId if none. We track this for
87 * similar reasons to tracking overflowing cached subxids in PGPROC
88 * entries. Must hold exclusive ProcArrayLock to change this, and shared
91 TransactionId lastOverflowedXid
;
93 /* oldest xmin of any replication slot */
94 TransactionId replication_slot_xmin
;
95 /* oldest catalog xmin of any replication slot */
96 TransactionId replication_slot_catalog_xmin
;
98 /* indexes into allProcs[], has PROCARRAY_MAXPROCS entries */
99 int pgprocnos
[FLEXIBLE_ARRAY_MEMBER
];
103 * State for the GlobalVisTest* family of functions. Those functions can
104 * e.g. be used to decide if a deleted row can be removed without violating
105 * MVCC semantics: If the deleted row's xmax is not considered to be running
106 * by anyone, the row can be removed.
108 * To avoid slowing down GetSnapshotData(), we don't calculate a precise
109 * cutoff XID while building a snapshot (looking at the frequently changing
110 * xmins scales badly). Instead we compute two boundaries while building the
113 * 1) definitely_needed, indicating that rows deleted by XIDs >=
114 * definitely_needed are definitely still visible.
116 * 2) maybe_needed, indicating that rows deleted by XIDs < maybe_needed can
117 * definitely be removed
119 * When testing an XID that falls in between the two (i.e. XID >= maybe_needed
120 * && XID < definitely_needed), the boundaries can be recomputed (using
121 * ComputeXidHorizons()) to get a more accurate answer. This is cheaper than
122 * maintaining an accurate value all the time.
124 * As it is not cheap to compute accurate boundaries, we limit the number of
125 * times that happens in short succession. See GlobalVisTestShouldUpdate().
128 * There are three backend lifetime instances of this struct, optimized for
129 * different types of relations. As e.g. a normal user defined table in one
130 * database is inaccessible to backends connected to another database, a test
131 * specific to a relation can be more aggressive than a test for a shared
132 * relation. Currently we track four different states:
134 * 1) GlobalVisSharedRels, which only considers an XID's
135 * effects visible-to-everyone if neither snapshots in any database, nor a
136 * replication slot's xmin, nor a replication slot's catalog_xmin might
137 * still consider XID as running.
139 * 2) GlobalVisCatalogRels, which only considers an XID's
140 * effects visible-to-everyone if neither snapshots in the current
141 * database, nor a replication slot's xmin, nor a replication slot's
142 * catalog_xmin might still consider XID as running.
144 * I.e. the difference to GlobalVisSharedRels is that
145 * snapshot in other databases are ignored.
147 * 3) GlobalVisDataRels, which only considers an XID's
148 * effects visible-to-everyone if neither snapshots in the current
149 * database, nor a replication slot's xmin consider XID as running.
151 * I.e. the difference to GlobalVisCatalogRels is that
152 * replication slot's catalog_xmin is not taken into account.
154 * 4) GlobalVisTempRels, which only considers the current session, as temp
155 * tables are not visible to other sessions.
157 * GlobalVisTestFor(relation) returns the appropriate state
160 * The boundaries are FullTransactionIds instead of TransactionIds to avoid
161 * wraparound dangers. There e.g. would otherwise exist no procarray state to
162 * prevent maybe_needed to become old enough after the GetSnapshotData()
165 * The typedef is in the header.
167 struct GlobalVisState
169 /* XIDs >= are considered running by some backend */
170 FullTransactionId definitely_needed
;
172 /* XIDs < are not considered to be running by any backend */
173 FullTransactionId maybe_needed
;
177 * Result of ComputeXidHorizons().
179 typedef struct ComputeXidHorizonsResult
182 * The value of TransamVariables->latestCompletedXid when
183 * ComputeXidHorizons() held ProcArrayLock.
185 FullTransactionId latest_completed
;
188 * The same for procArray->replication_slot_xmin and
189 * procArray->replication_slot_catalog_xmin.
191 TransactionId slot_xmin
;
192 TransactionId slot_catalog_xmin
;
195 * Oldest xid that any backend might still consider running. This needs to
196 * include processes running VACUUM, in contrast to the normal visibility
197 * cutoffs, as vacuum needs to be able to perform pg_subtrans lookups when
198 * determining visibility, but doesn't care about rows above its xmin to
201 * This likely should only be needed to determine whether pg_subtrans can
202 * be truncated. It currently includes the effects of replication slots,
203 * for historical reasons. But that could likely be changed.
205 TransactionId oldest_considered_running
;
208 * Oldest xid for which deleted tuples need to be retained in shared
211 * This includes the effects of replication slots. If that's not desired,
212 * look at shared_oldest_nonremovable_raw;
214 TransactionId shared_oldest_nonremovable
;
217 * Oldest xid that may be necessary to retain in shared tables. This is
218 * the same as shared_oldest_nonremovable, except that is not affected by
219 * replication slot's catalog_xmin.
221 * This is mainly useful to be able to send the catalog_xmin to upstream
222 * streaming replication servers via hot_standby_feedback, so they can
223 * apply the limit only when accessing catalog tables.
225 TransactionId shared_oldest_nonremovable_raw
;
228 * Oldest xid for which deleted tuples need to be retained in non-shared
231 TransactionId catalog_oldest_nonremovable
;
234 * Oldest xid for which deleted tuples need to be retained in normal user
237 TransactionId data_oldest_nonremovable
;
240 * Oldest xid for which deleted tuples need to be retained in this
241 * session's temporary tables.
243 TransactionId temp_oldest_nonremovable
;
244 } ComputeXidHorizonsResult
;
247 * Return value for GlobalVisHorizonKindForRel().
249 typedef enum GlobalVisHorizonKind
255 } GlobalVisHorizonKind
;
258 * Reason codes for KnownAssignedXidsCompress().
260 typedef enum KAXCompressReason
262 KAX_NO_SPACE
, /* need to free up space at array end */
263 KAX_PRUNE
, /* we just pruned old entries */
264 KAX_TRANSACTION_END
, /* we just committed/removed some XIDs */
265 KAX_STARTUP_PROCESS_IDLE
, /* startup process is about to sleep */
269 static ProcArrayStruct
*procArray
;
271 static PGPROC
*allProcs
;
274 * Cache to reduce overhead of repeated calls to TransactionIdIsInProgress()
276 static TransactionId cachedXidIsNotInProgress
= InvalidTransactionId
;
279 * Bookkeeping for tracking emulated transactions in recovery
281 static TransactionId
*KnownAssignedXids
;
282 static bool *KnownAssignedXidsValid
;
283 static TransactionId latestObservedXid
= InvalidTransactionId
;
286 * If we're in STANDBY_SNAPSHOT_PENDING state, standbySnapshotPendingXmin is
287 * the highest xid that might still be running that we don't have in
290 static TransactionId standbySnapshotPendingXmin
;
293 * State for visibility checks on different types of relations. See struct
294 * GlobalVisState for details. As shared, catalog, normal and temporary
295 * relations can have different horizons, one such state exists for each.
297 static GlobalVisState GlobalVisSharedRels
;
298 static GlobalVisState GlobalVisCatalogRels
;
299 static GlobalVisState GlobalVisDataRels
;
300 static GlobalVisState GlobalVisTempRels
;
303 * This backend's RecentXmin at the last time the accurate xmin horizon was
304 * recomputed, or InvalidTransactionId if it has not. Used to limit how many
305 * times accurate horizons are recomputed. See GlobalVisTestShouldUpdate().
307 static TransactionId ComputeXidHorizonsResultLastXmin
;
309 #ifdef XIDCACHE_DEBUG
311 /* counters for XidCache measurement */
312 static long xc_by_recent_xmin
= 0;
313 static long xc_by_known_xact
= 0;
314 static long xc_by_my_xact
= 0;
315 static long xc_by_latest_xid
= 0;
316 static long xc_by_main_xid
= 0;
317 static long xc_by_child_xid
= 0;
318 static long xc_by_known_assigned
= 0;
319 static long xc_no_overflow
= 0;
320 static long xc_slow_answer
= 0;
322 #define xc_by_recent_xmin_inc() (xc_by_recent_xmin++)
323 #define xc_by_known_xact_inc() (xc_by_known_xact++)
324 #define xc_by_my_xact_inc() (xc_by_my_xact++)
325 #define xc_by_latest_xid_inc() (xc_by_latest_xid++)
326 #define xc_by_main_xid_inc() (xc_by_main_xid++)
327 #define xc_by_child_xid_inc() (xc_by_child_xid++)
328 #define xc_by_known_assigned_inc() (xc_by_known_assigned++)
329 #define xc_no_overflow_inc() (xc_no_overflow++)
330 #define xc_slow_answer_inc() (xc_slow_answer++)
332 static void DisplayXidCache(void);
333 #else /* !XIDCACHE_DEBUG */
335 #define xc_by_recent_xmin_inc() ((void) 0)
336 #define xc_by_known_xact_inc() ((void) 0)
337 #define xc_by_my_xact_inc() ((void) 0)
338 #define xc_by_latest_xid_inc() ((void) 0)
339 #define xc_by_main_xid_inc() ((void) 0)
340 #define xc_by_child_xid_inc() ((void) 0)
341 #define xc_by_known_assigned_inc() ((void) 0)
342 #define xc_no_overflow_inc() ((void) 0)
343 #define xc_slow_answer_inc() ((void) 0)
344 #endif /* XIDCACHE_DEBUG */
346 /* Primitives for KnownAssignedXids array handling for standby */
347 static void KnownAssignedXidsCompress(KAXCompressReason reason
, bool haveLock
);
348 static void KnownAssignedXidsAdd(TransactionId from_xid
, TransactionId to_xid
,
349 bool exclusive_lock
);
350 static bool KnownAssignedXidsSearch(TransactionId xid
, bool remove
);
351 static bool KnownAssignedXidExists(TransactionId xid
);
352 static void KnownAssignedXidsRemove(TransactionId xid
);
353 static void KnownAssignedXidsRemoveTree(TransactionId xid
, int nsubxids
,
354 TransactionId
*subxids
);
355 static void KnownAssignedXidsRemovePreceding(TransactionId removeXid
);
356 static int KnownAssignedXidsGet(TransactionId
*xarray
, TransactionId xmax
);
357 static int KnownAssignedXidsGetAndSetXmin(TransactionId
*xarray
,
360 static TransactionId
KnownAssignedXidsGetOldestXmin(void);
361 static void KnownAssignedXidsDisplay(int trace_level
);
362 static void KnownAssignedXidsReset(void);
363 static inline void ProcArrayEndTransactionInternal(PGPROC
*proc
, TransactionId latestXid
);
364 static void ProcArrayGroupClearXid(PGPROC
*proc
, TransactionId latestXid
);
365 static void MaintainLatestCompletedXid(TransactionId latestXid
);
366 static void MaintainLatestCompletedXidRecovery(TransactionId latestXid
);
368 static inline FullTransactionId
FullXidRelativeTo(FullTransactionId rel
,
370 static void GlobalVisUpdateApply(ComputeXidHorizonsResult
*horizons
);
373 * Report shared-memory space needed by ProcArrayShmemInit
376 ProcArrayShmemSize(void)
380 /* Size of the ProcArray structure itself */
381 #define PROCARRAY_MAXPROCS (MaxBackends + max_prepared_xacts)
383 size
= offsetof(ProcArrayStruct
, pgprocnos
);
384 size
= add_size(size
, mul_size(sizeof(int), PROCARRAY_MAXPROCS
));
387 * During Hot Standby processing we have a data structure called
388 * KnownAssignedXids, created in shared memory. Local data structures are
389 * also created in various backends during GetSnapshotData(),
390 * TransactionIdIsInProgress() and GetRunningTransactionData(). All of the
391 * main structures created in those functions must be identically sized,
392 * since we may at times copy the whole of the data structures around. We
393 * refer to this size as TOTAL_MAX_CACHED_SUBXIDS.
395 * Ideally we'd only create this structure if we were actually doing hot
396 * standby in the current run, but we don't know that yet at the time
397 * shared memory is being set up.
399 #define TOTAL_MAX_CACHED_SUBXIDS \
400 ((PGPROC_MAX_CACHED_SUBXIDS + 1) * PROCARRAY_MAXPROCS)
402 if (EnableHotStandby
)
404 size
= add_size(size
,
405 mul_size(sizeof(TransactionId
),
406 TOTAL_MAX_CACHED_SUBXIDS
));
407 size
= add_size(size
,
408 mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS
));
415 * Initialize the shared PGPROC array during postmaster startup.
418 ProcArrayShmemInit(void)
422 /* Create or attach to the ProcArray shared structure */
423 procArray
= (ProcArrayStruct
*)
424 ShmemInitStruct("Proc Array",
425 add_size(offsetof(ProcArrayStruct
, pgprocnos
),
426 mul_size(sizeof(int),
427 PROCARRAY_MAXPROCS
)),
433 * We're the first - initialize.
435 procArray
->numProcs
= 0;
436 procArray
->maxProcs
= PROCARRAY_MAXPROCS
;
437 procArray
->maxKnownAssignedXids
= TOTAL_MAX_CACHED_SUBXIDS
;
438 procArray
->numKnownAssignedXids
= 0;
439 procArray
->tailKnownAssignedXids
= 0;
440 procArray
->headKnownAssignedXids
= 0;
441 procArray
->lastOverflowedXid
= InvalidTransactionId
;
442 procArray
->replication_slot_xmin
= InvalidTransactionId
;
443 procArray
->replication_slot_catalog_xmin
= InvalidTransactionId
;
444 TransamVariables
->xactCompletionCount
= 1;
447 allProcs
= ProcGlobal
->allProcs
;
449 /* Create or attach to the KnownAssignedXids arrays too, if needed */
450 if (EnableHotStandby
)
452 KnownAssignedXids
= (TransactionId
*)
453 ShmemInitStruct("KnownAssignedXids",
454 mul_size(sizeof(TransactionId
),
455 TOTAL_MAX_CACHED_SUBXIDS
),
457 KnownAssignedXidsValid
= (bool *)
458 ShmemInitStruct("KnownAssignedXidsValid",
459 mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS
),
465 * Add the specified PGPROC to the shared array.
468 ProcArrayAdd(PGPROC
*proc
)
470 int pgprocno
= GetNumberFromPGProc(proc
);
471 ProcArrayStruct
*arrayP
= procArray
;
475 /* See ProcGlobal comment explaining why both locks are held */
476 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
477 LWLockAcquire(XidGenLock
, LW_EXCLUSIVE
);
479 if (arrayP
->numProcs
>= arrayP
->maxProcs
)
482 * Oops, no room. (This really shouldn't happen, since there is a
483 * fixed supply of PGPROC structs too, and so we should have failed
487 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
488 errmsg("sorry, too many clients already")));
492 * Keep the procs array sorted by (PGPROC *) so that we can utilize
493 * locality of references much better. This is useful while traversing the
494 * ProcArray because there is an increased likelihood of finding the next
495 * PGPROC structure in the cache.
497 * Since the occurrence of adding/removing a proc is much lower than the
498 * access to the ProcArray itself, the overhead should be marginal
500 for (index
= 0; index
< arrayP
->numProcs
; index
++)
502 int this_procno
= arrayP
->pgprocnos
[index
];
504 Assert(this_procno
>= 0 && this_procno
< (arrayP
->maxProcs
+ NUM_AUXILIARY_PROCS
));
505 Assert(allProcs
[this_procno
].pgxactoff
== index
);
507 /* If we have found our right position in the array, break */
508 if (this_procno
> pgprocno
)
512 movecount
= arrayP
->numProcs
- index
;
513 memmove(&arrayP
->pgprocnos
[index
+ 1],
514 &arrayP
->pgprocnos
[index
],
515 movecount
* sizeof(*arrayP
->pgprocnos
));
516 memmove(&ProcGlobal
->xids
[index
+ 1],
517 &ProcGlobal
->xids
[index
],
518 movecount
* sizeof(*ProcGlobal
->xids
));
519 memmove(&ProcGlobal
->subxidStates
[index
+ 1],
520 &ProcGlobal
->subxidStates
[index
],
521 movecount
* sizeof(*ProcGlobal
->subxidStates
));
522 memmove(&ProcGlobal
->statusFlags
[index
+ 1],
523 &ProcGlobal
->statusFlags
[index
],
524 movecount
* sizeof(*ProcGlobal
->statusFlags
));
526 arrayP
->pgprocnos
[index
] = GetNumberFromPGProc(proc
);
527 proc
->pgxactoff
= index
;
528 ProcGlobal
->xids
[index
] = proc
->xid
;
529 ProcGlobal
->subxidStates
[index
] = proc
->subxidStatus
;
530 ProcGlobal
->statusFlags
[index
] = proc
->statusFlags
;
534 /* adjust pgxactoff for all following PGPROCs */
536 for (; index
< arrayP
->numProcs
; index
++)
538 int procno
= arrayP
->pgprocnos
[index
];
540 Assert(procno
>= 0 && procno
< (arrayP
->maxProcs
+ NUM_AUXILIARY_PROCS
));
541 Assert(allProcs
[procno
].pgxactoff
== index
- 1);
543 allProcs
[procno
].pgxactoff
= index
;
547 * Release in reversed acquisition order, to reduce frequency of having to
548 * wait for XidGenLock while holding ProcArrayLock.
550 LWLockRelease(XidGenLock
);
551 LWLockRelease(ProcArrayLock
);
555 * Remove the specified PGPROC from the shared array.
557 * When latestXid is a valid XID, we are removing a live 2PC gxact from the
558 * array, and thus causing it to appear as "not running" anymore. In this
559 * case we must advance latestCompletedXid. (This is essentially the same
560 * as ProcArrayEndTransaction followed by removal of the PGPROC, but we take
561 * the ProcArrayLock only once, and don't damage the content of the PGPROC;
562 * twophase.c depends on the latter.)
565 ProcArrayRemove(PGPROC
*proc
, TransactionId latestXid
)
567 ProcArrayStruct
*arrayP
= procArray
;
571 #ifdef XIDCACHE_DEBUG
572 /* dump stats at backend shutdown, but not prepared-xact end */
577 /* See ProcGlobal comment explaining why both locks are held */
578 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
579 LWLockAcquire(XidGenLock
, LW_EXCLUSIVE
);
581 myoff
= proc
->pgxactoff
;
583 Assert(myoff
>= 0 && myoff
< arrayP
->numProcs
);
584 Assert(ProcGlobal
->allProcs
[arrayP
->pgprocnos
[myoff
]].pgxactoff
== myoff
);
586 if (TransactionIdIsValid(latestXid
))
588 Assert(TransactionIdIsValid(ProcGlobal
->xids
[myoff
]));
590 /* Advance global latestCompletedXid while holding the lock */
591 MaintainLatestCompletedXid(latestXid
);
593 /* Same with xactCompletionCount */
594 TransamVariables
->xactCompletionCount
++;
596 ProcGlobal
->xids
[myoff
] = InvalidTransactionId
;
597 ProcGlobal
->subxidStates
[myoff
].overflowed
= false;
598 ProcGlobal
->subxidStates
[myoff
].count
= 0;
602 /* Shouldn't be trying to remove a live transaction here */
603 Assert(!TransactionIdIsValid(ProcGlobal
->xids
[myoff
]));
606 Assert(!TransactionIdIsValid(ProcGlobal
->xids
[myoff
]));
607 Assert(ProcGlobal
->subxidStates
[myoff
].count
== 0);
608 Assert(ProcGlobal
->subxidStates
[myoff
].overflowed
== false);
610 ProcGlobal
->statusFlags
[myoff
] = 0;
612 /* Keep the PGPROC array sorted. See notes above */
613 movecount
= arrayP
->numProcs
- myoff
- 1;
614 memmove(&arrayP
->pgprocnos
[myoff
],
615 &arrayP
->pgprocnos
[myoff
+ 1],
616 movecount
* sizeof(*arrayP
->pgprocnos
));
617 memmove(&ProcGlobal
->xids
[myoff
],
618 &ProcGlobal
->xids
[myoff
+ 1],
619 movecount
* sizeof(*ProcGlobal
->xids
));
620 memmove(&ProcGlobal
->subxidStates
[myoff
],
621 &ProcGlobal
->subxidStates
[myoff
+ 1],
622 movecount
* sizeof(*ProcGlobal
->subxidStates
));
623 memmove(&ProcGlobal
->statusFlags
[myoff
],
624 &ProcGlobal
->statusFlags
[myoff
+ 1],
625 movecount
* sizeof(*ProcGlobal
->statusFlags
));
627 arrayP
->pgprocnos
[arrayP
->numProcs
- 1] = -1; /* for debugging */
631 * Adjust pgxactoff of following procs for removed PGPROC (note that
632 * numProcs already has been decremented).
634 for (int index
= myoff
; index
< arrayP
->numProcs
; index
++)
636 int procno
= arrayP
->pgprocnos
[index
];
638 Assert(procno
>= 0 && procno
< (arrayP
->maxProcs
+ NUM_AUXILIARY_PROCS
));
639 Assert(allProcs
[procno
].pgxactoff
- 1 == index
);
641 allProcs
[procno
].pgxactoff
= index
;
645 * Release in reversed acquisition order, to reduce frequency of having to
646 * wait for XidGenLock while holding ProcArrayLock.
648 LWLockRelease(XidGenLock
);
649 LWLockRelease(ProcArrayLock
);
654 * ProcArrayEndTransaction -- mark a transaction as no longer running
656 * This is used interchangeably for commit and abort cases. The transaction
657 * commit/abort must already be reported to WAL and pg_xact.
659 * proc is currently always MyProc, but we pass it explicitly for flexibility.
660 * latestXid is the latest Xid among the transaction's main XID and
661 * subtransactions, or InvalidTransactionId if it has no XID. (We must ask
662 * the caller to pass latestXid, instead of computing it from the PGPROC's
663 * contents, because the subxid information in the PGPROC might be
667 ProcArrayEndTransaction(PGPROC
*proc
, TransactionId latestXid
)
669 if (TransactionIdIsValid(latestXid
))
672 * We must lock ProcArrayLock while clearing our advertised XID, so
673 * that we do not exit the set of "running" transactions while someone
674 * else is taking a snapshot. See discussion in
675 * src/backend/access/transam/README.
677 Assert(TransactionIdIsValid(proc
->xid
));
680 * If we can immediately acquire ProcArrayLock, we clear our own XID
681 * and release the lock. If not, use group XID clearing to improve
684 if (LWLockConditionalAcquire(ProcArrayLock
, LW_EXCLUSIVE
))
686 ProcArrayEndTransactionInternal(proc
, latestXid
);
687 LWLockRelease(ProcArrayLock
);
690 ProcArrayGroupClearXid(proc
, latestXid
);
695 * If we have no XID, we don't need to lock, since we won't affect
696 * anyone else's calculation of a snapshot. We might change their
697 * estimate of global xmin, but that's OK.
699 Assert(!TransactionIdIsValid(proc
->xid
));
700 Assert(proc
->subxidStatus
.count
== 0);
701 Assert(!proc
->subxidStatus
.overflowed
);
703 proc
->vxid
.lxid
= InvalidLocalTransactionId
;
704 proc
->xmin
= InvalidTransactionId
;
706 /* be sure this is cleared in abort */
707 proc
->delayChkptFlags
= 0;
709 proc
->recoveryConflictPending
= false;
711 /* must be cleared with xid/xmin: */
712 /* avoid unnecessarily dirtying shared cachelines */
713 if (proc
->statusFlags
& PROC_VACUUM_STATE_MASK
)
715 Assert(!LWLockHeldByMe(ProcArrayLock
));
716 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
717 Assert(proc
->statusFlags
== ProcGlobal
->statusFlags
[proc
->pgxactoff
]);
718 proc
->statusFlags
&= ~PROC_VACUUM_STATE_MASK
;
719 ProcGlobal
->statusFlags
[proc
->pgxactoff
] = proc
->statusFlags
;
720 LWLockRelease(ProcArrayLock
);
726 * Mark a write transaction as no longer running.
728 * We don't do any locking here; caller must handle that.
731 ProcArrayEndTransactionInternal(PGPROC
*proc
, TransactionId latestXid
)
733 int pgxactoff
= proc
->pgxactoff
;
736 * Note: we need exclusive lock here because we're going to change other
737 * processes' PGPROC entries.
739 Assert(LWLockHeldByMeInMode(ProcArrayLock
, LW_EXCLUSIVE
));
740 Assert(TransactionIdIsValid(ProcGlobal
->xids
[pgxactoff
]));
741 Assert(ProcGlobal
->xids
[pgxactoff
] == proc
->xid
);
743 ProcGlobal
->xids
[pgxactoff
] = InvalidTransactionId
;
744 proc
->xid
= InvalidTransactionId
;
745 proc
->vxid
.lxid
= InvalidLocalTransactionId
;
746 proc
->xmin
= InvalidTransactionId
;
748 /* be sure this is cleared in abort */
749 proc
->delayChkptFlags
= 0;
751 proc
->recoveryConflictPending
= false;
753 /* must be cleared with xid/xmin: */
754 /* avoid unnecessarily dirtying shared cachelines */
755 if (proc
->statusFlags
& PROC_VACUUM_STATE_MASK
)
757 proc
->statusFlags
&= ~PROC_VACUUM_STATE_MASK
;
758 ProcGlobal
->statusFlags
[proc
->pgxactoff
] = proc
->statusFlags
;
761 /* Clear the subtransaction-XID cache too while holding the lock */
762 Assert(ProcGlobal
->subxidStates
[pgxactoff
].count
== proc
->subxidStatus
.count
&&
763 ProcGlobal
->subxidStates
[pgxactoff
].overflowed
== proc
->subxidStatus
.overflowed
);
764 if (proc
->subxidStatus
.count
> 0 || proc
->subxidStatus
.overflowed
)
766 ProcGlobal
->subxidStates
[pgxactoff
].count
= 0;
767 ProcGlobal
->subxidStates
[pgxactoff
].overflowed
= false;
768 proc
->subxidStatus
.count
= 0;
769 proc
->subxidStatus
.overflowed
= false;
772 /* Also advance global latestCompletedXid while holding the lock */
773 MaintainLatestCompletedXid(latestXid
);
775 /* Same with xactCompletionCount */
776 TransamVariables
->xactCompletionCount
++;
780 * ProcArrayGroupClearXid -- group XID clearing
782 * When we cannot immediately acquire ProcArrayLock in exclusive mode at
783 * commit time, add ourselves to a list of processes that need their XIDs
784 * cleared. The first process to add itself to the list will acquire
785 * ProcArrayLock in exclusive mode and perform ProcArrayEndTransactionInternal
786 * on behalf of all group members. This avoids a great deal of contention
787 * around ProcArrayLock when many processes are trying to commit at once,
788 * since the lock need not be repeatedly handed off from one committing
789 * process to the next.
792 ProcArrayGroupClearXid(PGPROC
*proc
, TransactionId latestXid
)
794 int pgprocno
= GetNumberFromPGProc(proc
);
795 PROC_HDR
*procglobal
= ProcGlobal
;
799 /* We should definitely have an XID to clear. */
800 Assert(TransactionIdIsValid(proc
->xid
));
802 /* Add ourselves to the list of processes needing a group XID clear. */
803 proc
->procArrayGroupMember
= true;
804 proc
->procArrayGroupMemberXid
= latestXid
;
805 nextidx
= pg_atomic_read_u32(&procglobal
->procArrayGroupFirst
);
808 pg_atomic_write_u32(&proc
->procArrayGroupNext
, nextidx
);
810 if (pg_atomic_compare_exchange_u32(&procglobal
->procArrayGroupFirst
,
817 * If the list was not empty, the leader will clear our XID. It is
818 * impossible to have followers without a leader because the first process
819 * that has added itself to the list will always have nextidx as
820 * INVALID_PROC_NUMBER.
822 if (nextidx
!= INVALID_PROC_NUMBER
)
826 /* Sleep until the leader clears our XID. */
827 pgstat_report_wait_start(WAIT_EVENT_PROCARRAY_GROUP_UPDATE
);
830 /* acts as a read barrier */
831 PGSemaphoreLock(proc
->sem
);
832 if (!proc
->procArrayGroupMember
)
836 pgstat_report_wait_end();
838 Assert(pg_atomic_read_u32(&proc
->procArrayGroupNext
) == INVALID_PROC_NUMBER
);
840 /* Fix semaphore count for any absorbed wakeups */
841 while (extraWaits
-- > 0)
842 PGSemaphoreUnlock(proc
->sem
);
846 /* We are the leader. Acquire the lock on behalf of everyone. */
847 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
850 * Now that we've got the lock, clear the list of processes waiting for
851 * group XID clearing, saving a pointer to the head of the list. Trying
852 * to pop elements one at a time could lead to an ABA problem.
854 nextidx
= pg_atomic_exchange_u32(&procglobal
->procArrayGroupFirst
,
855 INVALID_PROC_NUMBER
);
857 /* Remember head of list so we can perform wakeups after dropping lock. */
860 /* Walk the list and clear all XIDs. */
861 while (nextidx
!= INVALID_PROC_NUMBER
)
863 PGPROC
*nextproc
= &allProcs
[nextidx
];
865 ProcArrayEndTransactionInternal(nextproc
, nextproc
->procArrayGroupMemberXid
);
867 /* Move to next proc in list. */
868 nextidx
= pg_atomic_read_u32(&nextproc
->procArrayGroupNext
);
871 /* We're done with the lock now. */
872 LWLockRelease(ProcArrayLock
);
875 * Now that we've released the lock, go back and wake everybody up. We
876 * don't do this under the lock so as to keep lock hold times to a
877 * minimum. The system calls we need to perform to wake other processes
878 * up are probably much slower than the simple memory writes we did while
881 while (wakeidx
!= INVALID_PROC_NUMBER
)
883 PGPROC
*nextproc
= &allProcs
[wakeidx
];
885 wakeidx
= pg_atomic_read_u32(&nextproc
->procArrayGroupNext
);
886 pg_atomic_write_u32(&nextproc
->procArrayGroupNext
, INVALID_PROC_NUMBER
);
888 /* ensure all previous writes are visible before follower continues. */
891 nextproc
->procArrayGroupMember
= false;
893 if (nextproc
!= MyProc
)
894 PGSemaphoreUnlock(nextproc
->sem
);
899 * ProcArrayClearTransaction -- clear the transaction fields
901 * This is used after successfully preparing a 2-phase transaction. We are
902 * not actually reporting the transaction's XID as no longer running --- it
903 * will still appear as running because the 2PC's gxact is in the ProcArray
904 * too. We just have to clear out our own PGPROC.
907 ProcArrayClearTransaction(PGPROC
*proc
)
912 * Currently we need to lock ProcArrayLock exclusively here, as we
913 * increment xactCompletionCount below. We also need it at least in shared
914 * mode for pgproc->pgxactoff to stay the same below.
916 * We could however, as this action does not actually change anyone's view
917 * of the set of running XIDs (our entry is duplicate with the gxact that
918 * has already been inserted into the ProcArray), lower the lock level to
919 * shared if we were to make xactCompletionCount an atomic variable. But
920 * that doesn't seem worth it currently, as a 2PC commit is heavyweight
921 * enough for this not to be the bottleneck. If it ever becomes a
922 * bottleneck it may also be worth considering to combine this with the
923 * subsequent ProcArrayRemove()
925 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
927 pgxactoff
= proc
->pgxactoff
;
929 ProcGlobal
->xids
[pgxactoff
] = InvalidTransactionId
;
930 proc
->xid
= InvalidTransactionId
;
932 proc
->vxid
.lxid
= InvalidLocalTransactionId
;
933 proc
->xmin
= InvalidTransactionId
;
934 proc
->recoveryConflictPending
= false;
936 Assert(!(proc
->statusFlags
& PROC_VACUUM_STATE_MASK
));
937 Assert(!proc
->delayChkptFlags
);
940 * Need to increment completion count even though transaction hasn't
941 * really committed yet. The reason for that is that GetSnapshotData()
942 * omits the xid of the current transaction, thus without the increment we
943 * otherwise could end up reusing the snapshot later. Which would be bad,
944 * because it might not count the prepared transaction as running.
946 TransamVariables
->xactCompletionCount
++;
948 /* Clear the subtransaction-XID cache too */
949 Assert(ProcGlobal
->subxidStates
[pgxactoff
].count
== proc
->subxidStatus
.count
&&
950 ProcGlobal
->subxidStates
[pgxactoff
].overflowed
== proc
->subxidStatus
.overflowed
);
951 if (proc
->subxidStatus
.count
> 0 || proc
->subxidStatus
.overflowed
)
953 ProcGlobal
->subxidStates
[pgxactoff
].count
= 0;
954 ProcGlobal
->subxidStates
[pgxactoff
].overflowed
= false;
955 proc
->subxidStatus
.count
= 0;
956 proc
->subxidStatus
.overflowed
= false;
959 LWLockRelease(ProcArrayLock
);
963 * Update TransamVariables->latestCompletedXid to point to latestXid if
967 MaintainLatestCompletedXid(TransactionId latestXid
)
969 FullTransactionId cur_latest
= TransamVariables
->latestCompletedXid
;
971 Assert(FullTransactionIdIsValid(cur_latest
));
972 Assert(!RecoveryInProgress());
973 Assert(LWLockHeldByMe(ProcArrayLock
));
975 if (TransactionIdPrecedes(XidFromFullTransactionId(cur_latest
), latestXid
))
977 TransamVariables
->latestCompletedXid
=
978 FullXidRelativeTo(cur_latest
, latestXid
);
981 Assert(IsBootstrapProcessingMode() ||
982 FullTransactionIdIsNormal(TransamVariables
->latestCompletedXid
));
986 * Same as MaintainLatestCompletedXid, except for use during WAL replay.
989 MaintainLatestCompletedXidRecovery(TransactionId latestXid
)
991 FullTransactionId cur_latest
= TransamVariables
->latestCompletedXid
;
992 FullTransactionId rel
;
994 Assert(AmStartupProcess() || !IsUnderPostmaster
);
995 Assert(LWLockHeldByMe(ProcArrayLock
));
998 * Need a FullTransactionId to compare latestXid with. Can't rely on
999 * latestCompletedXid to be initialized in recovery. But in recovery it's
1000 * safe to access nextXid without a lock for the startup process.
1002 rel
= TransamVariables
->nextXid
;
1003 Assert(FullTransactionIdIsValid(TransamVariables
->nextXid
));
1005 if (!FullTransactionIdIsValid(cur_latest
) ||
1006 TransactionIdPrecedes(XidFromFullTransactionId(cur_latest
), latestXid
))
1008 TransamVariables
->latestCompletedXid
=
1009 FullXidRelativeTo(rel
, latestXid
);
1012 Assert(FullTransactionIdIsNormal(TransamVariables
->latestCompletedXid
));
1016 * ProcArrayInitRecovery -- initialize recovery xid mgmt environment
1018 * Remember up to where the startup process initialized the CLOG and subtrans
1019 * so we can ensure it's initialized gaplessly up to the point where necessary
1020 * while in recovery.
1023 ProcArrayInitRecovery(TransactionId initializedUptoXID
)
1025 Assert(standbyState
== STANDBY_INITIALIZED
);
1026 Assert(TransactionIdIsNormal(initializedUptoXID
));
1029 * we set latestObservedXid to the xid SUBTRANS has been initialized up
1030 * to, so we can extend it from that point onwards in
1031 * RecordKnownAssignedTransactionIds, and when we get consistent in
1032 * ProcArrayApplyRecoveryInfo().
1034 latestObservedXid
= initializedUptoXID
;
1035 TransactionIdRetreat(latestObservedXid
);
1039 * ProcArrayApplyRecoveryInfo -- apply recovery info about xids
1041 * Takes us through 3 states: Initialized, Pending and Ready.
1042 * Normal case is to go all the way to Ready straight away, though there
1043 * are atypical cases where we need to take it in steps.
1045 * Use the data about running transactions on the primary to create the initial
1046 * state of KnownAssignedXids. We also use these records to regularly prune
1047 * KnownAssignedXids because we know it is possible that some transactions
1048 * with FATAL errors fail to write abort records, which could cause eventual
1051 * See comments for LogStandbySnapshot().
1054 ProcArrayApplyRecoveryInfo(RunningTransactions running
)
1056 TransactionId
*xids
;
1057 TransactionId advanceNextXid
;
1061 Assert(standbyState
>= STANDBY_INITIALIZED
);
1062 Assert(TransactionIdIsValid(running
->nextXid
));
1063 Assert(TransactionIdIsValid(running
->oldestRunningXid
));
1064 Assert(TransactionIdIsNormal(running
->latestCompletedXid
));
1067 * Remove stale transactions, if any.
1069 ExpireOldKnownAssignedTransactionIds(running
->oldestRunningXid
);
1072 * Adjust TransamVariables->nextXid before StandbyReleaseOldLocks(),
1073 * because we will need it up to date for accessing two-phase transactions
1074 * in StandbyReleaseOldLocks().
1076 advanceNextXid
= running
->nextXid
;
1077 TransactionIdRetreat(advanceNextXid
);
1078 AdvanceNextFullTransactionIdPastXid(advanceNextXid
);
1079 Assert(FullTransactionIdIsValid(TransamVariables
->nextXid
));
1082 * Remove stale locks, if any.
1084 StandbyReleaseOldLocks(running
->oldestRunningXid
);
1087 * If our snapshot is already valid, nothing else to do...
1089 if (standbyState
== STANDBY_SNAPSHOT_READY
)
1093 * If our initial RunningTransactionsData had an overflowed snapshot then
1094 * we knew we were missing some subxids from our snapshot. If we continue
1095 * to see overflowed snapshots then we might never be able to start up, so
1096 * we make another test to see if our snapshot is now valid. We know that
1097 * the missing subxids are equal to or earlier than nextXid. After we
1098 * initialise we continue to apply changes during recovery, so once the
1099 * oldestRunningXid is later than the nextXid from the initial snapshot we
1100 * know that we no longer have missing information and can mark the
1101 * snapshot as valid.
1103 if (standbyState
== STANDBY_SNAPSHOT_PENDING
)
1106 * If the snapshot isn't overflowed or if its empty we can reset our
1107 * pending state and use this snapshot instead.
1109 if (running
->subxid_status
!= SUBXIDS_MISSING
|| running
->xcnt
== 0)
1112 * If we have already collected known assigned xids, we need to
1113 * throw them away before we apply the recovery snapshot.
1115 KnownAssignedXidsReset();
1116 standbyState
= STANDBY_INITIALIZED
;
1120 if (TransactionIdPrecedes(standbySnapshotPendingXmin
,
1121 running
->oldestRunningXid
))
1123 standbyState
= STANDBY_SNAPSHOT_READY
;
1125 "recovery snapshots are now enabled");
1129 "recovery snapshot waiting for non-overflowed snapshot or "
1130 "until oldest active xid on standby is at least %u (now %u)",
1131 standbySnapshotPendingXmin
,
1132 running
->oldestRunningXid
);
1137 Assert(standbyState
== STANDBY_INITIALIZED
);
1140 * NB: this can be reached at least twice, so make sure new code can deal
1145 * Nobody else is running yet, but take locks anyhow
1147 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
1150 * KnownAssignedXids is sorted so we cannot just add the xids, we have to
1153 * Some of the new xids are top-level xids and some are subtransactions.
1154 * We don't call SubTransSetParent because it doesn't matter yet. If we
1155 * aren't overflowed then all xids will fit in snapshot and so we don't
1156 * need subtrans. If we later overflow, an xid assignment record will add
1157 * xids to subtrans. If RunningTransactionsData is overflowed then we
1158 * don't have enough information to correctly update subtrans anyway.
1162 * Allocate a temporary array to avoid modifying the array passed as
1165 xids
= palloc(sizeof(TransactionId
) * (running
->xcnt
+ running
->subxcnt
));
1168 * Add to the temp array any xids which have not already completed.
1171 for (i
= 0; i
< running
->xcnt
+ running
->subxcnt
; i
++)
1173 TransactionId xid
= running
->xids
[i
];
1176 * The running-xacts snapshot can contain xids that were still visible
1177 * in the procarray when the snapshot was taken, but were already
1178 * WAL-logged as completed. They're not running anymore, so ignore
1181 if (TransactionIdDidCommit(xid
) || TransactionIdDidAbort(xid
))
1184 xids
[nxids
++] = xid
;
1189 if (procArray
->numKnownAssignedXids
!= 0)
1191 LWLockRelease(ProcArrayLock
);
1192 elog(ERROR
, "KnownAssignedXids is not empty");
1196 * Sort the array so that we can add them safely into
1197 * KnownAssignedXids.
1199 * We have to sort them logically, because in KnownAssignedXidsAdd we
1200 * call TransactionIdFollowsOrEquals and so on. But we know these XIDs
1201 * come from RUNNING_XACTS, which means there are only normal XIDs
1202 * from the same epoch, so this is safe.
1204 qsort(xids
, nxids
, sizeof(TransactionId
), xidLogicalComparator
);
1207 * Add the sorted snapshot into KnownAssignedXids. The running-xacts
1208 * snapshot may include duplicated xids because of prepared
1209 * transactions, so ignore them.
1211 for (i
= 0; i
< nxids
; i
++)
1213 if (i
> 0 && TransactionIdEquals(xids
[i
- 1], xids
[i
]))
1216 "found duplicated transaction %u for KnownAssignedXids insertion",
1220 KnownAssignedXidsAdd(xids
[i
], xids
[i
], true);
1223 KnownAssignedXidsDisplay(DEBUG3
);
1229 * latestObservedXid is at least set to the point where SUBTRANS was
1230 * started up to (cf. ProcArrayInitRecovery()) or to the biggest xid
1231 * RecordKnownAssignedTransactionIds() was called for. Initialize
1232 * subtrans from thereon, up to nextXid - 1.
1234 * We need to duplicate parts of RecordKnownAssignedTransactionId() here,
1235 * because we've just added xids to the known assigned xids machinery that
1236 * haven't gone through RecordKnownAssignedTransactionId().
1238 Assert(TransactionIdIsNormal(latestObservedXid
));
1239 TransactionIdAdvance(latestObservedXid
);
1240 while (TransactionIdPrecedes(latestObservedXid
, running
->nextXid
))
1242 ExtendSUBTRANS(latestObservedXid
);
1243 TransactionIdAdvance(latestObservedXid
);
1245 TransactionIdRetreat(latestObservedXid
); /* = running->nextXid - 1 */
1248 * Now we've got the running xids we need to set the global values that
1249 * are used to track snapshots as they evolve further.
1251 * - latestCompletedXid which will be the xmax for snapshots
1252 * - lastOverflowedXid which shows whether snapshots overflow
1255 * If the snapshot overflowed, then we still initialise with what we know,
1256 * but the recovery snapshot isn't fully valid yet because we know there
1257 * are some subxids missing. We don't know the specific subxids that are
1258 * missing, so conservatively assume the last one is latestObservedXid.
1261 if (running
->subxid_status
== SUBXIDS_MISSING
)
1263 standbyState
= STANDBY_SNAPSHOT_PENDING
;
1265 standbySnapshotPendingXmin
= latestObservedXid
;
1266 procArray
->lastOverflowedXid
= latestObservedXid
;
1270 standbyState
= STANDBY_SNAPSHOT_READY
;
1272 standbySnapshotPendingXmin
= InvalidTransactionId
;
1275 * If the 'xids' array didn't include all subtransactions, we have to
1276 * mark any snapshots taken as overflowed.
1278 if (running
->subxid_status
== SUBXIDS_IN_SUBTRANS
)
1279 procArray
->lastOverflowedXid
= latestObservedXid
;
1282 Assert(running
->subxid_status
== SUBXIDS_IN_ARRAY
);
1283 procArray
->lastOverflowedXid
= InvalidTransactionId
;
1288 * If a transaction wrote a commit record in the gap between taking and
1289 * logging the snapshot then latestCompletedXid may already be higher than
1290 * the value from the snapshot, so check before we use the incoming value.
1291 * It also might not yet be set at all.
1293 MaintainLatestCompletedXidRecovery(running
->latestCompletedXid
);
1296 * NB: No need to increment TransamVariables->xactCompletionCount here,
1297 * nobody can see it yet.
1300 LWLockRelease(ProcArrayLock
);
1302 KnownAssignedXidsDisplay(DEBUG3
);
1303 if (standbyState
== STANDBY_SNAPSHOT_READY
)
1304 elog(DEBUG1
, "recovery snapshots are now enabled");
1307 "recovery snapshot waiting for non-overflowed snapshot or "
1308 "until oldest active xid on standby is at least %u (now %u)",
1309 standbySnapshotPendingXmin
,
1310 running
->oldestRunningXid
);
1314 * ProcArrayApplyXidAssignment
1315 * Process an XLOG_XACT_ASSIGNMENT WAL record
1318 ProcArrayApplyXidAssignment(TransactionId topxid
,
1319 int nsubxids
, TransactionId
*subxids
)
1321 TransactionId max_xid
;
1324 Assert(standbyState
>= STANDBY_INITIALIZED
);
1326 max_xid
= TransactionIdLatest(topxid
, nsubxids
, subxids
);
1329 * Mark all the subtransactions as observed.
1331 * NOTE: This will fail if the subxid contains too many previously
1332 * unobserved xids to fit into known-assigned-xids. That shouldn't happen
1333 * as the code stands, because xid-assignment records should never contain
1334 * more than PGPROC_MAX_CACHED_SUBXIDS entries.
1336 RecordKnownAssignedTransactionIds(max_xid
);
1339 * Notice that we update pg_subtrans with the top-level xid, rather than
1340 * the parent xid. This is a difference between normal processing and
1341 * recovery, yet is still correct in all cases. The reason is that
1342 * subtransaction commit is not marked in clog until commit processing, so
1343 * all aborted subtransactions have already been clearly marked in clog.
1344 * As a result we are able to refer directly to the top-level
1345 * transaction's state rather than skipping through all the intermediate
1346 * states in the subtransaction tree. This should be the first time we
1347 * have attempted to SubTransSetParent().
1349 for (i
= 0; i
< nsubxids
; i
++)
1350 SubTransSetParent(subxids
[i
], topxid
);
1352 /* KnownAssignedXids isn't maintained yet, so we're done for now */
1353 if (standbyState
== STANDBY_INITIALIZED
)
1357 * Uses same locking as transaction commit
1359 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
1362 * Remove subxids from known-assigned-xacts.
1364 KnownAssignedXidsRemoveTree(InvalidTransactionId
, nsubxids
, subxids
);
1367 * Advance lastOverflowedXid to be at least the last of these subxids.
1369 if (TransactionIdPrecedes(procArray
->lastOverflowedXid
, max_xid
))
1370 procArray
->lastOverflowedXid
= max_xid
;
1372 LWLockRelease(ProcArrayLock
);
1376 * TransactionIdIsInProgress -- is given transaction running in some backend
1378 * Aside from some shortcuts such as checking RecentXmin and our own Xid,
1379 * there are four possibilities for finding a running transaction:
1381 * 1. The given Xid is a main transaction Id. We will find this out cheaply
1382 * by looking at ProcGlobal->xids.
1384 * 2. The given Xid is one of the cached subxact Xids in the PGPROC array.
1385 * We can find this out cheaply too.
1387 * 3. In Hot Standby mode, we must search the KnownAssignedXids list to see
1388 * if the Xid is running on the primary.
1390 * 4. Search the SubTrans tree to find the Xid's topmost parent, and then see
1391 * if that is running according to ProcGlobal->xids[] or KnownAssignedXids.
1392 * This is the slowest way, but sadly it has to be done always if the others
1393 * failed, unless we see that the cached subxact sets are complete (none have
1396 * ProcArrayLock has to be held while we do 1, 2, 3. If we save the top Xids
1397 * while doing 1 and 3, we can release the ProcArrayLock while we do 4.
1398 * This buys back some concurrency (and we can't retrieve the main Xids from
1399 * ProcGlobal->xids[] again anyway; see GetNewTransactionId).
1402 TransactionIdIsInProgress(TransactionId xid
)
1404 static TransactionId
*xids
= NULL
;
1405 static TransactionId
*other_xids
;
1406 XidCacheStatus
*other_subxidstates
;
1408 ProcArrayStruct
*arrayP
= procArray
;
1409 TransactionId topxid
;
1410 TransactionId latestCompletedXid
;
1416 * Don't bother checking a transaction older than RecentXmin; it could not
1417 * possibly still be running. (Note: in particular, this guarantees that
1418 * we reject InvalidTransactionId, FrozenTransactionId, etc as not
1421 if (TransactionIdPrecedes(xid
, RecentXmin
))
1423 xc_by_recent_xmin_inc();
1428 * We may have just checked the status of this transaction, so if it is
1429 * already known to be completed, we can fall out without any access to
1432 if (TransactionIdEquals(cachedXidIsNotInProgress
, xid
))
1434 xc_by_known_xact_inc();
1439 * Also, we can handle our own transaction (and subtransactions) without
1440 * any access to shared memory.
1442 if (TransactionIdIsCurrentTransactionId(xid
))
1444 xc_by_my_xact_inc();
1449 * If first time through, get workspace to remember main XIDs in. We
1450 * malloc it permanently to avoid repeated palloc/pfree overhead.
1455 * In hot standby mode, reserve enough space to hold all xids in the
1456 * known-assigned list. If we later finish recovery, we no longer need
1457 * the bigger array, but we don't bother to shrink it.
1459 int maxxids
= RecoveryInProgress() ? TOTAL_MAX_CACHED_SUBXIDS
: arrayP
->maxProcs
;
1461 xids
= (TransactionId
*) malloc(maxxids
* sizeof(TransactionId
));
1464 (errcode(ERRCODE_OUT_OF_MEMORY
),
1465 errmsg("out of memory")));
1468 other_xids
= ProcGlobal
->xids
;
1469 other_subxidstates
= ProcGlobal
->subxidStates
;
1471 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
1474 * Now that we have the lock, we can check latestCompletedXid; if the
1475 * target Xid is after that, it's surely still running.
1477 latestCompletedXid
=
1478 XidFromFullTransactionId(TransamVariables
->latestCompletedXid
);
1479 if (TransactionIdPrecedes(latestCompletedXid
, xid
))
1481 LWLockRelease(ProcArrayLock
);
1482 xc_by_latest_xid_inc();
1486 /* No shortcuts, gotta grovel through the array */
1487 mypgxactoff
= MyProc
->pgxactoff
;
1488 numProcs
= arrayP
->numProcs
;
1489 for (int pgxactoff
= 0; pgxactoff
< numProcs
; pgxactoff
++)
1496 /* Ignore ourselves --- dealt with it above */
1497 if (pgxactoff
== mypgxactoff
)
1500 /* Fetch xid just once - see GetNewTransactionId */
1501 pxid
= UINT32_ACCESS_ONCE(other_xids
[pgxactoff
]);
1503 if (!TransactionIdIsValid(pxid
))
1507 * Step 1: check the main Xid
1509 if (TransactionIdEquals(pxid
, xid
))
1511 LWLockRelease(ProcArrayLock
);
1512 xc_by_main_xid_inc();
1517 * We can ignore main Xids that are younger than the target Xid, since
1518 * the target could not possibly be their child.
1520 if (TransactionIdPrecedes(xid
, pxid
))
1524 * Step 2: check the cached child-Xids arrays
1526 pxids
= other_subxidstates
[pgxactoff
].count
;
1527 pg_read_barrier(); /* pairs with barrier in GetNewTransactionId() */
1528 pgprocno
= arrayP
->pgprocnos
[pgxactoff
];
1529 proc
= &allProcs
[pgprocno
];
1530 for (j
= pxids
- 1; j
>= 0; j
--)
1532 /* Fetch xid just once - see GetNewTransactionId */
1533 TransactionId cxid
= UINT32_ACCESS_ONCE(proc
->subxids
.xids
[j
]);
1535 if (TransactionIdEquals(cxid
, xid
))
1537 LWLockRelease(ProcArrayLock
);
1538 xc_by_child_xid_inc();
1544 * Save the main Xid for step 4. We only need to remember main Xids
1545 * that have uncached children. (Note: there is no race condition
1546 * here because the overflowed flag cannot be cleared, only set, while
1547 * we hold ProcArrayLock. So we can't miss an Xid that we need to
1550 if (other_subxidstates
[pgxactoff
].overflowed
)
1551 xids
[nxids
++] = pxid
;
1555 * Step 3: in hot standby mode, check the known-assigned-xids list. XIDs
1556 * in the list must be treated as running.
1558 if (RecoveryInProgress())
1560 /* none of the PGPROC entries should have XIDs in hot standby mode */
1563 if (KnownAssignedXidExists(xid
))
1565 LWLockRelease(ProcArrayLock
);
1566 xc_by_known_assigned_inc();
1571 * If the KnownAssignedXids overflowed, we have to check pg_subtrans
1572 * too. Fetch all xids from KnownAssignedXids that are lower than
1573 * xid, since if xid is a subtransaction its parent will always have a
1574 * lower value. Note we will collect both main and subXIDs here, but
1575 * there's no help for it.
1577 if (TransactionIdPrecedesOrEquals(xid
, procArray
->lastOverflowedXid
))
1578 nxids
= KnownAssignedXidsGet(xids
, xid
);
1581 LWLockRelease(ProcArrayLock
);
1584 * If none of the relevant caches overflowed, we know the Xid is not
1585 * running without even looking at pg_subtrans.
1589 xc_no_overflow_inc();
1590 cachedXidIsNotInProgress
= xid
;
1595 * Step 4: have to check pg_subtrans.
1597 * At this point, we know it's either a subtransaction of one of the Xids
1598 * in xids[], or it's not running. If it's an already-failed
1599 * subtransaction, we want to say "not running" even though its parent may
1600 * still be running. So first, check pg_xact to see if it's been aborted.
1602 xc_slow_answer_inc();
1604 if (TransactionIdDidAbort(xid
))
1606 cachedXidIsNotInProgress
= xid
;
1611 * It isn't aborted, so check whether the transaction tree it belongs to
1612 * is still running (or, more precisely, whether it was running when we
1613 * held ProcArrayLock).
1615 topxid
= SubTransGetTopmostTransaction(xid
);
1616 Assert(TransactionIdIsValid(topxid
));
1617 if (!TransactionIdEquals(topxid
, xid
) &&
1618 pg_lfind32(topxid
, xids
, nxids
))
1621 cachedXidIsNotInProgress
= xid
;
1626 * TransactionIdIsActive -- is xid the top-level XID of an active backend?
1628 * This differs from TransactionIdIsInProgress in that it ignores prepared
1629 * transactions, as well as transactions running on the primary if we're in
1630 * hot standby. Also, we ignore subtransactions since that's not needed
1634 TransactionIdIsActive(TransactionId xid
)
1636 bool result
= false;
1637 ProcArrayStruct
*arrayP
= procArray
;
1638 TransactionId
*other_xids
= ProcGlobal
->xids
;
1642 * Don't bother checking a transaction older than RecentXmin; it could not
1643 * possibly still be running.
1645 if (TransactionIdPrecedes(xid
, RecentXmin
))
1648 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
1650 for (i
= 0; i
< arrayP
->numProcs
; i
++)
1652 int pgprocno
= arrayP
->pgprocnos
[i
];
1653 PGPROC
*proc
= &allProcs
[pgprocno
];
1656 /* Fetch xid just once - see GetNewTransactionId */
1657 pxid
= UINT32_ACCESS_ONCE(other_xids
[i
]);
1659 if (!TransactionIdIsValid(pxid
))
1663 continue; /* ignore prepared transactions */
1665 if (TransactionIdEquals(pxid
, xid
))
1672 LWLockRelease(ProcArrayLock
);
1679 * Determine XID horizons.
1681 * This is used by wrapper functions like GetOldestNonRemovableTransactionId()
1682 * (for VACUUM), GetReplicationHorizons() (for hot_standby_feedback), etc as
1683 * well as "internally" by GlobalVisUpdate() (see comment above struct
1686 * See the definition of ComputeXidHorizonsResult for the various computed
1689 * For VACUUM separate horizons (used to decide which deleted tuples must
1690 * be preserved), for shared and non-shared tables are computed. For shared
1691 * relations backends in all databases must be considered, but for non-shared
1692 * relations that's not required, since only backends in my own database could
1693 * ever see the tuples in them. Also, we can ignore concurrently running lazy
1694 * VACUUMs because (a) they must be working on other tables, and (b) they
1695 * don't need to do snapshot-based lookups.
1697 * This also computes a horizon used to truncate pg_subtrans. For that
1698 * backends in all databases have to be considered, and concurrently running
1699 * lazy VACUUMs cannot be ignored, as they still may perform pg_subtrans
1702 * Note: we include all currently running xids in the set of considered xids.
1703 * This ensures that if a just-started xact has not yet set its snapshot,
1704 * when it does set the snapshot it cannot set xmin less than what we compute.
1705 * See notes in src/backend/access/transam/README.
1707 * Note: despite the above, it's possible for the calculated values to move
1708 * backwards on repeated calls. The calculated values are conservative, so
1709 * that anything older is definitely not considered as running by anyone
1710 * anymore, but the exact values calculated depend on a number of things. For
1711 * example, if there are no transactions running in the current database, the
1712 * horizon for normal tables will be latestCompletedXid. If a transaction
1713 * begins after that, its xmin will include in-progress transactions in other
1714 * databases that started earlier, so another call will return a lower value.
1715 * Nonetheless it is safe to vacuum a table in the current database with the
1716 * first result. There are also replication-related effects: a walsender
1717 * process can set its xmin based on transactions that are no longer running
1718 * on the primary but are still being replayed on the standby, thus possibly
1719 * making the values go backwards. In this case there is a possibility that
1720 * we lose data that the standby would like to have, but unless the standby
1721 * uses a replication slot to make its xmin persistent there is little we can
1722 * do about that --- data is only protected if the walsender runs continuously
1723 * while queries are executed on the standby. (The Hot Standby code deals
1724 * with such cases by failing standby queries that needed to access
1725 * already-removed data, so there's no integrity bug.)
1727 * Note: the approximate horizons (see definition of GlobalVisState) are
1728 * updated by the computations done here. That's currently required for
1729 * correctness and a small optimization. Without doing so it's possible that
1730 * heap vacuum's call to heap_page_prune_and_freeze() uses a more conservative
1731 * horizon than later when deciding which tuples can be removed - which the
1732 * code doesn't expect (breaking HOT).
1735 ComputeXidHorizons(ComputeXidHorizonsResult
*h
)
1737 ProcArrayStruct
*arrayP
= procArray
;
1738 TransactionId kaxmin
;
1739 bool in_recovery
= RecoveryInProgress();
1740 TransactionId
*other_xids
= ProcGlobal
->xids
;
1742 /* inferred after ProcArrayLock is released */
1743 h
->catalog_oldest_nonremovable
= InvalidTransactionId
;
1745 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
1747 h
->latest_completed
= TransamVariables
->latestCompletedXid
;
1750 * We initialize the MIN() calculation with latestCompletedXid + 1. This
1751 * is a lower bound for the XIDs that might appear in the ProcArray later,
1752 * and so protects us against overestimating the result due to future
1756 TransactionId initial
;
1758 initial
= XidFromFullTransactionId(h
->latest_completed
);
1759 Assert(TransactionIdIsValid(initial
));
1760 TransactionIdAdvance(initial
);
1762 h
->oldest_considered_running
= initial
;
1763 h
->shared_oldest_nonremovable
= initial
;
1764 h
->data_oldest_nonremovable
= initial
;
1767 * Only modifications made by this backend affect the horizon for
1768 * temporary relations. Instead of a check in each iteration of the
1769 * loop over all PGPROCs it is cheaper to just initialize to the
1770 * current top-level xid any.
1772 * Without an assigned xid we could use a horizon as aggressive as
1773 * GetNewTransactionId(), but we can get away with the much cheaper
1774 * latestCompletedXid + 1: If this backend has no xid there, by
1775 * definition, can't be any newer changes in the temp table than
1776 * latestCompletedXid.
1778 if (TransactionIdIsValid(MyProc
->xid
))
1779 h
->temp_oldest_nonremovable
= MyProc
->xid
;
1781 h
->temp_oldest_nonremovable
= initial
;
1785 * Fetch slot horizons while ProcArrayLock is held - the
1786 * LWLockAcquire/LWLockRelease are a barrier, ensuring this happens inside
1789 h
->slot_xmin
= procArray
->replication_slot_xmin
;
1790 h
->slot_catalog_xmin
= procArray
->replication_slot_catalog_xmin
;
1792 for (int index
= 0; index
< arrayP
->numProcs
; index
++)
1794 int pgprocno
= arrayP
->pgprocnos
[index
];
1795 PGPROC
*proc
= &allProcs
[pgprocno
];
1796 int8 statusFlags
= ProcGlobal
->statusFlags
[index
];
1800 /* Fetch xid just once - see GetNewTransactionId */
1801 xid
= UINT32_ACCESS_ONCE(other_xids
[index
]);
1802 xmin
= UINT32_ACCESS_ONCE(proc
->xmin
);
1805 * Consider both the transaction's Xmin, and its Xid.
1807 * We must check both because a transaction might have an Xmin but not
1808 * (yet) an Xid; conversely, if it has an Xid, that could determine
1809 * some not-yet-set Xmin.
1811 xmin
= TransactionIdOlder(xmin
, xid
);
1813 /* if neither is set, this proc doesn't influence the horizon */
1814 if (!TransactionIdIsValid(xmin
))
1818 * Don't ignore any procs when determining which transactions might be
1819 * considered running. While slots should ensure logical decoding
1820 * backends are protected even without this check, it can't hurt to
1821 * include them here as well..
1823 h
->oldest_considered_running
=
1824 TransactionIdOlder(h
->oldest_considered_running
, xmin
);
1827 * Skip over backends either vacuuming (which is ok with rows being
1828 * removed, as long as pg_subtrans is not truncated) or doing logical
1829 * decoding (which manages xmin separately, check below).
1831 if (statusFlags
& (PROC_IN_VACUUM
| PROC_IN_LOGICAL_DECODING
))
1834 /* shared tables need to take backends in all databases into account */
1835 h
->shared_oldest_nonremovable
=
1836 TransactionIdOlder(h
->shared_oldest_nonremovable
, xmin
);
1839 * Normally sessions in other databases are ignored for anything but
1840 * the shared horizon.
1842 * However, include them when MyDatabaseId is not (yet) set. A
1843 * backend in the process of starting up must not compute a "too
1844 * aggressive" horizon, otherwise we could end up using it to prune
1845 * still-needed data away. If the current backend never connects to a
1846 * database this is harmless, because data_oldest_nonremovable will
1847 * never be utilized.
1849 * Also, sessions marked with PROC_AFFECTS_ALL_HORIZONS should always
1850 * be included. (This flag is used for hot standby feedback, which
1851 * can't be tied to a specific database.)
1853 * Also, while in recovery we cannot compute an accurate per-database
1854 * horizon, as all xids are managed via the KnownAssignedXids
1857 if (proc
->databaseId
== MyDatabaseId
||
1858 MyDatabaseId
== InvalidOid
||
1859 (statusFlags
& PROC_AFFECTS_ALL_HORIZONS
) ||
1862 h
->data_oldest_nonremovable
=
1863 TransactionIdOlder(h
->data_oldest_nonremovable
, xmin
);
1868 * If in recovery fetch oldest xid in KnownAssignedXids, will be applied
1869 * after lock is released.
1872 kaxmin
= KnownAssignedXidsGetOldestXmin();
1875 * No other information from shared state is needed, release the lock
1876 * immediately. The rest of the computations can be done without a lock.
1878 LWLockRelease(ProcArrayLock
);
1882 h
->oldest_considered_running
=
1883 TransactionIdOlder(h
->oldest_considered_running
, kaxmin
);
1884 h
->shared_oldest_nonremovable
=
1885 TransactionIdOlder(h
->shared_oldest_nonremovable
, kaxmin
);
1886 h
->data_oldest_nonremovable
=
1887 TransactionIdOlder(h
->data_oldest_nonremovable
, kaxmin
);
1888 /* temp relations cannot be accessed in recovery */
1891 Assert(TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1892 h
->shared_oldest_nonremovable
));
1893 Assert(TransactionIdPrecedesOrEquals(h
->shared_oldest_nonremovable
,
1894 h
->data_oldest_nonremovable
));
1897 * Check whether there are replication slots requiring an older xmin.
1899 h
->shared_oldest_nonremovable
=
1900 TransactionIdOlder(h
->shared_oldest_nonremovable
, h
->slot_xmin
);
1901 h
->data_oldest_nonremovable
=
1902 TransactionIdOlder(h
->data_oldest_nonremovable
, h
->slot_xmin
);
1905 * The only difference between catalog / data horizons is that the slot's
1906 * catalog xmin is applied to the catalog one (so catalogs can be accessed
1907 * for logical decoding). Initialize with data horizon, and then back up
1908 * further if necessary. Have to back up the shared horizon as well, since
1909 * that also can contain catalogs.
1911 h
->shared_oldest_nonremovable_raw
= h
->shared_oldest_nonremovable
;
1912 h
->shared_oldest_nonremovable
=
1913 TransactionIdOlder(h
->shared_oldest_nonremovable
,
1914 h
->slot_catalog_xmin
);
1915 h
->catalog_oldest_nonremovable
= h
->data_oldest_nonremovable
;
1916 h
->catalog_oldest_nonremovable
=
1917 TransactionIdOlder(h
->catalog_oldest_nonremovable
,
1918 h
->slot_catalog_xmin
);
1921 * It's possible that slots backed up the horizons further than
1922 * oldest_considered_running. Fix.
1924 h
->oldest_considered_running
=
1925 TransactionIdOlder(h
->oldest_considered_running
,
1926 h
->shared_oldest_nonremovable
);
1927 h
->oldest_considered_running
=
1928 TransactionIdOlder(h
->oldest_considered_running
,
1929 h
->catalog_oldest_nonremovable
);
1930 h
->oldest_considered_running
=
1931 TransactionIdOlder(h
->oldest_considered_running
,
1932 h
->data_oldest_nonremovable
);
1935 * shared horizons have to be at least as old as the oldest visible in
1938 Assert(TransactionIdPrecedesOrEquals(h
->shared_oldest_nonremovable
,
1939 h
->data_oldest_nonremovable
));
1940 Assert(TransactionIdPrecedesOrEquals(h
->shared_oldest_nonremovable
,
1941 h
->catalog_oldest_nonremovable
));
1944 * Horizons need to ensure that pg_subtrans access is still possible for
1945 * the relevant backends.
1947 Assert(TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1948 h
->shared_oldest_nonremovable
));
1949 Assert(TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1950 h
->catalog_oldest_nonremovable
));
1951 Assert(TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1952 h
->data_oldest_nonremovable
));
1953 Assert(TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1954 h
->temp_oldest_nonremovable
));
1955 Assert(!TransactionIdIsValid(h
->slot_xmin
) ||
1956 TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1958 Assert(!TransactionIdIsValid(h
->slot_catalog_xmin
) ||
1959 TransactionIdPrecedesOrEquals(h
->oldest_considered_running
,
1960 h
->slot_catalog_xmin
));
1962 /* update approximate horizons with the computed horizons */
1963 GlobalVisUpdateApply(h
);
1967 * Determine what kind of visibility horizon needs to be used for a
1968 * relation. If rel is NULL, the most conservative horizon is used.
1970 static inline GlobalVisHorizonKind
1971 GlobalVisHorizonKindForRel(Relation rel
)
1974 * Other relkinds currently don't contain xids, nor always the necessary
1975 * logical decoding markers.
1978 rel
->rd_rel
->relkind
== RELKIND_RELATION
||
1979 rel
->rd_rel
->relkind
== RELKIND_MATVIEW
||
1980 rel
->rd_rel
->relkind
== RELKIND_TOASTVALUE
);
1982 if (rel
== NULL
|| rel
->rd_rel
->relisshared
|| RecoveryInProgress())
1983 return VISHORIZON_SHARED
;
1984 else if (IsCatalogRelation(rel
) ||
1985 RelationIsAccessibleInLogicalDecoding(rel
))
1986 return VISHORIZON_CATALOG
;
1987 else if (!RELATION_IS_LOCAL(rel
))
1988 return VISHORIZON_DATA
;
1990 return VISHORIZON_TEMP
;
1994 * Return the oldest XID for which deleted tuples must be preserved in the
1997 * If rel is not NULL the horizon may be considerably more recent than
1998 * otherwise (i.e. fewer tuples will be removable). In the NULL case a horizon
1999 * that is correct (but not optimal) for all relations will be returned.
2001 * This is used by VACUUM to decide which deleted tuples must be preserved in
2002 * the passed in table.
2005 GetOldestNonRemovableTransactionId(Relation rel
)
2007 ComputeXidHorizonsResult horizons
;
2009 ComputeXidHorizons(&horizons
);
2011 switch (GlobalVisHorizonKindForRel(rel
))
2013 case VISHORIZON_SHARED
:
2014 return horizons
.shared_oldest_nonremovable
;
2015 case VISHORIZON_CATALOG
:
2016 return horizons
.catalog_oldest_nonremovable
;
2017 case VISHORIZON_DATA
:
2018 return horizons
.data_oldest_nonremovable
;
2019 case VISHORIZON_TEMP
:
2020 return horizons
.temp_oldest_nonremovable
;
2023 /* just to prevent compiler warnings */
2024 return InvalidTransactionId
;
2028 * Return the oldest transaction id any currently running backend might still
2029 * consider running. This should not be used for visibility / pruning
2030 * determinations (see GetOldestNonRemovableTransactionId()), but for
2031 * decisions like up to where pg_subtrans can be truncated.
2034 GetOldestTransactionIdConsideredRunning(void)
2036 ComputeXidHorizonsResult horizons
;
2038 ComputeXidHorizons(&horizons
);
2040 return horizons
.oldest_considered_running
;
2044 * Return the visibility horizons for a hot standby feedback message.
2047 GetReplicationHorizons(TransactionId
*xmin
, TransactionId
*catalog_xmin
)
2049 ComputeXidHorizonsResult horizons
;
2051 ComputeXidHorizons(&horizons
);
2054 * Don't want to use shared_oldest_nonremovable here, as that contains the
2055 * effect of replication slot's catalog_xmin. We want to send a separate
2056 * feedback for the catalog horizon, so the primary can remove data table
2057 * contents more aggressively.
2059 *xmin
= horizons
.shared_oldest_nonremovable_raw
;
2060 *catalog_xmin
= horizons
.slot_catalog_xmin
;
2064 * GetMaxSnapshotXidCount -- get max size for snapshot XID array
2066 * We have to export this for use by snapmgr.c.
2069 GetMaxSnapshotXidCount(void)
2071 return procArray
->maxProcs
;
2075 * GetMaxSnapshotSubxidCount -- get max size for snapshot sub-XID array
2077 * We have to export this for use by snapmgr.c.
2080 GetMaxSnapshotSubxidCount(void)
2082 return TOTAL_MAX_CACHED_SUBXIDS
;
2086 * Helper function for GetSnapshotData() that checks if the bulk of the
2087 * visibility information in the snapshot is still valid. If so, it updates
2088 * the fields that need to change and returns true. Otherwise it returns
2091 * This very likely can be evolved to not need ProcArrayLock held (at very
2092 * least in the case we already hold a snapshot), but that's for another day.
2095 GetSnapshotDataReuse(Snapshot snapshot
)
2097 uint64 curXactCompletionCount
;
2099 Assert(LWLockHeldByMe(ProcArrayLock
));
2101 if (unlikely(snapshot
->snapXactCompletionCount
== 0))
2104 curXactCompletionCount
= TransamVariables
->xactCompletionCount
;
2105 if (curXactCompletionCount
!= snapshot
->snapXactCompletionCount
)
2109 * If the current xactCompletionCount is still the same as it was at the
2110 * time the snapshot was built, we can be sure that rebuilding the
2111 * contents of the snapshot the hard way would result in the same snapshot
2114 * As explained in transam/README, the set of xids considered running by
2115 * GetSnapshotData() cannot change while ProcArrayLock is held. Snapshot
2116 * contents only depend on transactions with xids and xactCompletionCount
2117 * is incremented whenever a transaction with an xid finishes (while
2118 * holding ProcArrayLock exclusively). Thus the xactCompletionCount check
2119 * ensures we would detect if the snapshot would have changed.
2121 * As the snapshot contents are the same as it was before, it is safe to
2122 * re-enter the snapshot's xmin into the PGPROC array. None of the rows
2123 * visible under the snapshot could already have been removed (that'd
2124 * require the set of running transactions to change) and it fulfills the
2125 * requirement that concurrent GetSnapshotData() calls yield the same
2128 if (!TransactionIdIsValid(MyProc
->xmin
))
2129 MyProc
->xmin
= TransactionXmin
= snapshot
->xmin
;
2131 RecentXmin
= snapshot
->xmin
;
2132 Assert(TransactionIdPrecedesOrEquals(TransactionXmin
, RecentXmin
));
2134 snapshot
->curcid
= GetCurrentCommandId(false);
2135 snapshot
->active_count
= 0;
2136 snapshot
->regd_count
= 0;
2137 snapshot
->copied
= false;
2138 snapshot
->lsn
= InvalidXLogRecPtr
;
2139 snapshot
->whenTaken
= 0;
2145 * GetSnapshotData -- returns information about running transactions.
2147 * The returned snapshot includes xmin (lowest still-running xact ID),
2148 * xmax (highest completed xact ID + 1), and a list of running xact IDs
2149 * in the range xmin <= xid < xmax. It is used as follows:
2150 * All xact IDs < xmin are considered finished.
2151 * All xact IDs >= xmax are considered still running.
2152 * For an xact ID xmin <= xid < xmax, consult list to see whether
2153 * it is considered running or not.
2154 * This ensures that the set of transactions seen as "running" by the
2155 * current xact will not change after it takes the snapshot.
2157 * All running top-level XIDs are included in the snapshot, except for lazy
2158 * VACUUM processes. We also try to include running subtransaction XIDs,
2159 * but since PGPROC has only a limited cache area for subxact XIDs, full
2160 * information may not be available. If we find any overflowed subxid arrays,
2161 * we have to mark the snapshot's subxid data as overflowed, and extra work
2162 * *may* need to be done to determine what's running (see XidInMVCCSnapshot()).
2164 * We also update the following backend-global variables:
2165 * TransactionXmin: the oldest xmin of any snapshot in use in the
2166 * current transaction (this is the same as MyProc->xmin).
2167 * RecentXmin: the xmin computed for the most recent snapshot. XIDs
2168 * older than this are known not running any more.
2170 * And try to advance the bounds of GlobalVis{Shared,Catalog,Data,Temp}Rels
2171 * for the benefit of the GlobalVisTest* family of functions.
2173 * Note: this function should probably not be called with an argument that's
2174 * not statically allocated (see xip allocation below).
2177 GetSnapshotData(Snapshot snapshot
)
2179 ProcArrayStruct
*arrayP
= procArray
;
2180 TransactionId
*other_xids
= ProcGlobal
->xids
;
2185 bool suboverflowed
= false;
2186 FullTransactionId latest_completed
;
2187 TransactionId oldestxid
;
2189 TransactionId myxid
;
2190 uint64 curXactCompletionCount
;
2192 TransactionId replication_slot_xmin
= InvalidTransactionId
;
2193 TransactionId replication_slot_catalog_xmin
= InvalidTransactionId
;
2195 Assert(snapshot
!= NULL
);
2198 * Allocating space for maxProcs xids is usually overkill; numProcs would
2199 * be sufficient. But it seems better to do the malloc while not holding
2200 * the lock, so we can't look at numProcs. Likewise, we allocate much
2201 * more subxip storage than is probably needed.
2203 * This does open a possibility for avoiding repeated malloc/free: since
2204 * maxProcs does not change at runtime, we can simply reuse the previous
2205 * xip arrays if any. (This relies on the fact that all callers pass
2206 * static SnapshotData structs.)
2208 if (snapshot
->xip
== NULL
)
2211 * First call for this snapshot. Snapshot is same size whether or not
2212 * we are in recovery, see later comments.
2214 snapshot
->xip
= (TransactionId
*)
2215 malloc(GetMaxSnapshotXidCount() * sizeof(TransactionId
));
2216 if (snapshot
->xip
== NULL
)
2218 (errcode(ERRCODE_OUT_OF_MEMORY
),
2219 errmsg("out of memory")));
2220 Assert(snapshot
->subxip
== NULL
);
2221 snapshot
->subxip
= (TransactionId
*)
2222 malloc(GetMaxSnapshotSubxidCount() * sizeof(TransactionId
));
2223 if (snapshot
->subxip
== NULL
)
2225 (errcode(ERRCODE_OUT_OF_MEMORY
),
2226 errmsg("out of memory")));
2230 * It is sufficient to get shared lock on ProcArrayLock, even if we are
2231 * going to set MyProc->xmin.
2233 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
2235 if (GetSnapshotDataReuse(snapshot
))
2237 LWLockRelease(ProcArrayLock
);
2241 latest_completed
= TransamVariables
->latestCompletedXid
;
2242 mypgxactoff
= MyProc
->pgxactoff
;
2243 myxid
= other_xids
[mypgxactoff
];
2244 Assert(myxid
== MyProc
->xid
);
2246 oldestxid
= TransamVariables
->oldestXid
;
2247 curXactCompletionCount
= TransamVariables
->xactCompletionCount
;
2249 /* xmax is always latestCompletedXid + 1 */
2250 xmax
= XidFromFullTransactionId(latest_completed
);
2251 TransactionIdAdvance(xmax
);
2252 Assert(TransactionIdIsNormal(xmax
));
2254 /* initialize xmin calculation with xmax */
2257 /* take own xid into account, saves a check inside the loop */
2258 if (TransactionIdIsNormal(myxid
) && NormalTransactionIdPrecedes(myxid
, xmin
))
2261 snapshot
->takenDuringRecovery
= RecoveryInProgress();
2263 if (!snapshot
->takenDuringRecovery
)
2265 int numProcs
= arrayP
->numProcs
;
2266 TransactionId
*xip
= snapshot
->xip
;
2267 int *pgprocnos
= arrayP
->pgprocnos
;
2268 XidCacheStatus
*subxidStates
= ProcGlobal
->subxidStates
;
2269 uint8
*allStatusFlags
= ProcGlobal
->statusFlags
;
2272 * First collect set of pgxactoff/xids that need to be included in the
2275 for (int pgxactoff
= 0; pgxactoff
< numProcs
; pgxactoff
++)
2277 /* Fetch xid just once - see GetNewTransactionId */
2278 TransactionId xid
= UINT32_ACCESS_ONCE(other_xids
[pgxactoff
]);
2281 Assert(allProcs
[arrayP
->pgprocnos
[pgxactoff
]].pgxactoff
== pgxactoff
);
2284 * If the transaction has no XID assigned, we can skip it; it
2285 * won't have sub-XIDs either.
2287 if (likely(xid
== InvalidTransactionId
))
2291 * We don't include our own XIDs (if any) in the snapshot. It
2292 * needs to be included in the xmin computation, but we did so
2295 if (pgxactoff
== mypgxactoff
)
2299 * The only way we are able to get here with a non-normal xid is
2300 * during bootstrap - with this backend using
2301 * BootstrapTransactionId. But the above test should filter that
2304 Assert(TransactionIdIsNormal(xid
));
2307 * If the XID is >= xmax, we can skip it; such transactions will
2308 * be treated as running anyway (and any sub-XIDs will also be >=
2311 if (!NormalTransactionIdPrecedes(xid
, xmax
))
2315 * Skip over backends doing logical decoding which manages xmin
2316 * separately (check below) and ones running LAZY VACUUM.
2318 statusFlags
= allStatusFlags
[pgxactoff
];
2319 if (statusFlags
& (PROC_IN_LOGICAL_DECODING
| PROC_IN_VACUUM
))
2322 if (NormalTransactionIdPrecedes(xid
, xmin
))
2325 /* Add XID to snapshot. */
2329 * Save subtransaction XIDs if possible (if we've already
2330 * overflowed, there's no point). Note that the subxact XIDs must
2331 * be later than their parent, so no need to check them against
2332 * xmin. We could filter against xmax, but it seems better not to
2333 * do that much work while holding the ProcArrayLock.
2335 * The other backend can add more subxids concurrently, but cannot
2336 * remove any. Hence it's important to fetch nxids just once.
2337 * Should be safe to use memcpy, though. (We needn't worry about
2338 * missing any xids added concurrently, because they must postdate
2341 * Again, our own XIDs are not included in the snapshot.
2346 if (subxidStates
[pgxactoff
].overflowed
)
2347 suboverflowed
= true;
2350 int nsubxids
= subxidStates
[pgxactoff
].count
;
2354 int pgprocno
= pgprocnos
[pgxactoff
];
2355 PGPROC
*proc
= &allProcs
[pgprocno
];
2357 pg_read_barrier(); /* pairs with GetNewTransactionId */
2359 memcpy(snapshot
->subxip
+ subcount
,
2361 nsubxids
* sizeof(TransactionId
));
2362 subcount
+= nsubxids
;
2371 * We're in hot standby, so get XIDs from KnownAssignedXids.
2373 * We store all xids directly into subxip[]. Here's why:
2375 * In recovery we don't know which xids are top-level and which are
2376 * subxacts, a design choice that greatly simplifies xid processing.
2378 * It seems like we would want to try to put xids into xip[] only, but
2379 * that is fairly small. We would either need to make that bigger or
2380 * to increase the rate at which we WAL-log xid assignment; neither is
2381 * an appealing choice.
2383 * We could try to store xids into xip[] first and then into subxip[]
2384 * if there are too many xids. That only works if the snapshot doesn't
2385 * overflow because we do not search subxip[] in that case. A simpler
2386 * way is to just store all xids in the subxip array because this is
2387 * by far the bigger array. We just leave the xip array empty.
2389 * Either way we need to change the way XidInMVCCSnapshot() works
2390 * depending upon when the snapshot was taken, or change normal
2391 * snapshot processing so it matches.
2393 * Note: It is possible for recovery to end before we finish taking
2394 * the snapshot, and for newly assigned transaction ids to be added to
2395 * the ProcArray. xmax cannot change while we hold ProcArrayLock, so
2396 * those newly added transaction ids would be filtered away, so we
2397 * need not be concerned about them.
2399 subcount
= KnownAssignedXidsGetAndSetXmin(snapshot
->subxip
, &xmin
,
2402 if (TransactionIdPrecedesOrEquals(xmin
, procArray
->lastOverflowedXid
))
2403 suboverflowed
= true;
2408 * Fetch into local variable while ProcArrayLock is held - the
2409 * LWLockRelease below is a barrier, ensuring this happens inside the
2412 replication_slot_xmin
= procArray
->replication_slot_xmin
;
2413 replication_slot_catalog_xmin
= procArray
->replication_slot_catalog_xmin
;
2415 if (!TransactionIdIsValid(MyProc
->xmin
))
2416 MyProc
->xmin
= TransactionXmin
= xmin
;
2418 LWLockRelease(ProcArrayLock
);
2420 /* maintain state for GlobalVis* */
2422 TransactionId def_vis_xid
;
2423 TransactionId def_vis_xid_data
;
2424 FullTransactionId def_vis_fxid
;
2425 FullTransactionId def_vis_fxid_data
;
2426 FullTransactionId oldestfxid
;
2429 * Converting oldestXid is only safe when xid horizon cannot advance,
2430 * i.e. holding locks. While we don't hold the lock anymore, all the
2431 * necessary data has been gathered with lock held.
2433 oldestfxid
= FullXidRelativeTo(latest_completed
, oldestxid
);
2435 /* Check whether there's a replication slot requiring an older xmin. */
2437 TransactionIdOlder(xmin
, replication_slot_xmin
);
2440 * Rows in non-shared, non-catalog tables possibly could be vacuumed
2441 * if older than this xid.
2443 def_vis_xid
= def_vis_xid_data
;
2446 * Check whether there's a replication slot requiring an older catalog
2450 TransactionIdOlder(replication_slot_catalog_xmin
, def_vis_xid
);
2452 def_vis_fxid
= FullXidRelativeTo(latest_completed
, def_vis_xid
);
2453 def_vis_fxid_data
= FullXidRelativeTo(latest_completed
, def_vis_xid_data
);
2456 * Check if we can increase upper bound. As a previous
2457 * GlobalVisUpdate() might have computed more aggressive values, don't
2458 * overwrite them if so.
2460 GlobalVisSharedRels
.definitely_needed
=
2461 FullTransactionIdNewer(def_vis_fxid
,
2462 GlobalVisSharedRels
.definitely_needed
);
2463 GlobalVisCatalogRels
.definitely_needed
=
2464 FullTransactionIdNewer(def_vis_fxid
,
2465 GlobalVisCatalogRels
.definitely_needed
);
2466 GlobalVisDataRels
.definitely_needed
=
2467 FullTransactionIdNewer(def_vis_fxid_data
,
2468 GlobalVisDataRels
.definitely_needed
);
2469 /* See temp_oldest_nonremovable computation in ComputeXidHorizons() */
2470 if (TransactionIdIsNormal(myxid
))
2471 GlobalVisTempRels
.definitely_needed
=
2472 FullXidRelativeTo(latest_completed
, myxid
);
2475 GlobalVisTempRels
.definitely_needed
= latest_completed
;
2476 FullTransactionIdAdvance(&GlobalVisTempRels
.definitely_needed
);
2480 * Check if we know that we can initialize or increase the lower
2481 * bound. Currently the only cheap way to do so is to use
2482 * TransamVariables->oldestXid as input.
2484 * We should definitely be able to do better. We could e.g. put a
2485 * global lower bound value into TransamVariables.
2487 GlobalVisSharedRels
.maybe_needed
=
2488 FullTransactionIdNewer(GlobalVisSharedRels
.maybe_needed
,
2490 GlobalVisCatalogRels
.maybe_needed
=
2491 FullTransactionIdNewer(GlobalVisCatalogRels
.maybe_needed
,
2493 GlobalVisDataRels
.maybe_needed
=
2494 FullTransactionIdNewer(GlobalVisDataRels
.maybe_needed
,
2496 /* accurate value known */
2497 GlobalVisTempRels
.maybe_needed
= GlobalVisTempRels
.definitely_needed
;
2501 Assert(TransactionIdPrecedesOrEquals(TransactionXmin
, RecentXmin
));
2503 snapshot
->xmin
= xmin
;
2504 snapshot
->xmax
= xmax
;
2505 snapshot
->xcnt
= count
;
2506 snapshot
->subxcnt
= subcount
;
2507 snapshot
->suboverflowed
= suboverflowed
;
2508 snapshot
->snapXactCompletionCount
= curXactCompletionCount
;
2510 snapshot
->curcid
= GetCurrentCommandId(false);
2513 * This is a new snapshot, so set both refcounts are zero, and mark it as
2514 * not copied in persistent memory.
2516 snapshot
->active_count
= 0;
2517 snapshot
->regd_count
= 0;
2518 snapshot
->copied
= false;
2519 snapshot
->lsn
= InvalidXLogRecPtr
;
2520 snapshot
->whenTaken
= 0;
2526 * ProcArrayInstallImportedXmin -- install imported xmin into MyProc->xmin
2528 * This is called when installing a snapshot imported from another
2529 * transaction. To ensure that OldestXmin doesn't go backwards, we must
2530 * check that the source transaction is still running, and we'd better do
2531 * that atomically with installing the new xmin.
2533 * Returns true if successful, false if source xact is no longer running.
2536 ProcArrayInstallImportedXmin(TransactionId xmin
,
2537 VirtualTransactionId
*sourcevxid
)
2539 bool result
= false;
2540 ProcArrayStruct
*arrayP
= procArray
;
2543 Assert(TransactionIdIsNormal(xmin
));
2547 /* Get lock so source xact can't end while we're doing this */
2548 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
2551 * Find the PGPROC entry of the source transaction. (This could use
2552 * GetPGProcByNumber(), unless it's a prepared xact. But this isn't
2553 * performance critical.)
2555 for (index
= 0; index
< arrayP
->numProcs
; index
++)
2557 int pgprocno
= arrayP
->pgprocnos
[index
];
2558 PGPROC
*proc
= &allProcs
[pgprocno
];
2559 int statusFlags
= ProcGlobal
->statusFlags
[index
];
2562 /* Ignore procs running LAZY VACUUM */
2563 if (statusFlags
& PROC_IN_VACUUM
)
2566 /* We are only interested in the specific virtual transaction. */
2567 if (proc
->vxid
.procNumber
!= sourcevxid
->procNumber
)
2569 if (proc
->vxid
.lxid
!= sourcevxid
->localTransactionId
)
2573 * We check the transaction's database ID for paranoia's sake: if it's
2574 * in another DB then its xmin does not cover us. Caller should have
2575 * detected this already, so we just treat any funny cases as
2576 * "transaction not found".
2578 if (proc
->databaseId
!= MyDatabaseId
)
2582 * Likewise, let's just make real sure its xmin does cover us.
2584 xid
= UINT32_ACCESS_ONCE(proc
->xmin
);
2585 if (!TransactionIdIsNormal(xid
) ||
2586 !TransactionIdPrecedesOrEquals(xid
, xmin
))
2590 * We're good. Install the new xmin. As in GetSnapshotData, set
2591 * TransactionXmin too. (Note that because snapmgr.c called
2592 * GetSnapshotData first, we'll be overwriting a valid xmin here, so
2593 * we don't check that.)
2595 MyProc
->xmin
= TransactionXmin
= xmin
;
2601 LWLockRelease(ProcArrayLock
);
2607 * ProcArrayInstallRestoredXmin -- install restored xmin into MyProc->xmin
2609 * This is like ProcArrayInstallImportedXmin, but we have a pointer to the
2610 * PGPROC of the transaction from which we imported the snapshot, rather than
2613 * Note that this function also copies statusFlags from the source `proc` in
2614 * order to avoid the case where MyProc's xmin needs to be skipped for
2615 * computing xid horizon.
2617 * Returns true if successful, false if source xact is no longer running.
2620 ProcArrayInstallRestoredXmin(TransactionId xmin
, PGPROC
*proc
)
2622 bool result
= false;
2625 Assert(TransactionIdIsNormal(xmin
));
2626 Assert(proc
!= NULL
);
2629 * Get an exclusive lock so that we can copy statusFlags from source proc.
2631 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
2634 * Be certain that the referenced PGPROC has an advertised xmin which is
2635 * no later than the one we're installing, so that the system-wide xmin
2636 * can't go backwards. Also, make sure it's running in the same database,
2637 * so that the per-database xmin cannot go backwards.
2639 xid
= UINT32_ACCESS_ONCE(proc
->xmin
);
2640 if (proc
->databaseId
== MyDatabaseId
&&
2641 TransactionIdIsNormal(xid
) &&
2642 TransactionIdPrecedesOrEquals(xid
, xmin
))
2645 * Install xmin and propagate the statusFlags that affect how the
2646 * value is interpreted by vacuum.
2648 MyProc
->xmin
= TransactionXmin
= xmin
;
2649 MyProc
->statusFlags
= (MyProc
->statusFlags
& ~PROC_XMIN_FLAGS
) |
2650 (proc
->statusFlags
& PROC_XMIN_FLAGS
);
2651 ProcGlobal
->statusFlags
[MyProc
->pgxactoff
] = MyProc
->statusFlags
;
2656 LWLockRelease(ProcArrayLock
);
2662 * GetRunningTransactionData -- returns information about running transactions.
2664 * Similar to GetSnapshotData but returns more information. We include
2665 * all PGPROCs with an assigned TransactionId, even VACUUM processes and
2666 * prepared transactions.
2668 * We acquire XidGenLock and ProcArrayLock, but the caller is responsible for
2669 * releasing them. Acquiring XidGenLock ensures that no new XIDs enter the proc
2670 * array until the caller has WAL-logged this snapshot, and releases the
2671 * lock. Acquiring ProcArrayLock ensures that no transactions commit until the
2674 * The returned data structure is statically allocated; caller should not
2675 * modify it, and must not assume it is valid past the next call.
2677 * This is never executed during recovery so there is no need to look at
2678 * KnownAssignedXids.
2680 * Dummy PGPROCs from prepared transaction are included, meaning that this
2681 * may return entries with duplicated TransactionId values coming from
2682 * transaction finishing to prepare. Nothing is done about duplicated
2683 * entries here to not hold on ProcArrayLock more than necessary.
2685 * We don't worry about updating other counters, we want to keep this as
2686 * simple as possible and leave GetSnapshotData() as the primary code for
2689 * Note that if any transaction has overflowed its cached subtransactions
2690 * then there is no real need include any subtransactions.
2693 GetRunningTransactionData(void)
2695 /* result workspace */
2696 static RunningTransactionsData CurrentRunningXactsData
;
2698 ProcArrayStruct
*arrayP
= procArray
;
2699 TransactionId
*other_xids
= ProcGlobal
->xids
;
2700 RunningTransactions CurrentRunningXacts
= &CurrentRunningXactsData
;
2701 TransactionId latestCompletedXid
;
2702 TransactionId oldestRunningXid
;
2703 TransactionId oldestDatabaseRunningXid
;
2704 TransactionId
*xids
;
2710 Assert(!RecoveryInProgress());
2713 * Allocating space for maxProcs xids is usually overkill; numProcs would
2714 * be sufficient. But it seems better to do the malloc while not holding
2715 * the lock, so we can't look at numProcs. Likewise, we allocate much
2716 * more subxip storage than is probably needed.
2718 * Should only be allocated in bgwriter, since only ever executed during
2721 if (CurrentRunningXacts
->xids
== NULL
)
2726 CurrentRunningXacts
->xids
= (TransactionId
*)
2727 malloc(TOTAL_MAX_CACHED_SUBXIDS
* sizeof(TransactionId
));
2728 if (CurrentRunningXacts
->xids
== NULL
)
2730 (errcode(ERRCODE_OUT_OF_MEMORY
),
2731 errmsg("out of memory")));
2734 xids
= CurrentRunningXacts
->xids
;
2736 count
= subcount
= 0;
2737 suboverflowed
= false;
2740 * Ensure that no xids enter or leave the procarray while we obtain
2743 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
2744 LWLockAcquire(XidGenLock
, LW_SHARED
);
2746 latestCompletedXid
=
2747 XidFromFullTransactionId(TransamVariables
->latestCompletedXid
);
2748 oldestDatabaseRunningXid
= oldestRunningXid
=
2749 XidFromFullTransactionId(TransamVariables
->nextXid
);
2752 * Spin over procArray collecting all xids
2754 for (index
= 0; index
< arrayP
->numProcs
; index
++)
2758 /* Fetch xid just once - see GetNewTransactionId */
2759 xid
= UINT32_ACCESS_ONCE(other_xids
[index
]);
2762 * We don't need to store transactions that don't have a TransactionId
2763 * yet because they will not show as running on a standby server.
2765 if (!TransactionIdIsValid(xid
))
2769 * Be careful not to exclude any xids before calculating the values of
2770 * oldestRunningXid and suboverflowed, since these are used to clean
2771 * up transaction information held on standbys.
2773 if (TransactionIdPrecedes(xid
, oldestRunningXid
))
2774 oldestRunningXid
= xid
;
2777 * Also, update the oldest running xid within the current database. As
2778 * fetching pgprocno and PGPROC could cause cache misses, we do cheap
2779 * TransactionId comparison first.
2781 if (TransactionIdPrecedes(xid
, oldestDatabaseRunningXid
))
2783 int pgprocno
= arrayP
->pgprocnos
[index
];
2784 PGPROC
*proc
= &allProcs
[pgprocno
];
2786 if (proc
->databaseId
== MyDatabaseId
)
2787 oldestDatabaseRunningXid
= xid
;
2790 if (ProcGlobal
->subxidStates
[index
].overflowed
)
2791 suboverflowed
= true;
2794 * If we wished to exclude xids this would be the right place for it.
2795 * Procs with the PROC_IN_VACUUM flag set don't usually assign xids,
2796 * but they do during truncation at the end when they get the lock and
2797 * truncate, so it is not much of a problem to include them if they
2798 * are seen and it is cleaner to include them.
2801 xids
[count
++] = xid
;
2805 * Spin over procArray collecting all subxids, but only if there hasn't
2806 * been a suboverflow.
2810 XidCacheStatus
*other_subxidstates
= ProcGlobal
->subxidStates
;
2812 for (index
= 0; index
< arrayP
->numProcs
; index
++)
2814 int pgprocno
= arrayP
->pgprocnos
[index
];
2815 PGPROC
*proc
= &allProcs
[pgprocno
];
2819 * Save subtransaction XIDs. Other backends can't add or remove
2820 * entries while we're holding XidGenLock.
2822 nsubxids
= other_subxidstates
[index
].count
;
2825 /* barrier not really required, as XidGenLock is held, but ... */
2826 pg_read_barrier(); /* pairs with GetNewTransactionId */
2828 memcpy(&xids
[count
], proc
->subxids
.xids
,
2829 nsubxids
* sizeof(TransactionId
));
2831 subcount
+= nsubxids
;
2834 * Top-level XID of a transaction is always less than any of
2835 * its subxids, so we don't need to check if any of the
2836 * subxids are smaller than oldestRunningXid
2843 * It's important *not* to include the limits set by slots here because
2844 * snapbuild.c uses oldestRunningXid to manage its xmin horizon. If those
2845 * were to be included here the initial value could never increase because
2846 * of a circular dependency where slots only increase their limits when
2847 * running xacts increases oldestRunningXid and running xacts only
2848 * increases if slots do.
2851 CurrentRunningXacts
->xcnt
= count
- subcount
;
2852 CurrentRunningXacts
->subxcnt
= subcount
;
2853 CurrentRunningXacts
->subxid_status
= suboverflowed
? SUBXIDS_IN_SUBTRANS
: SUBXIDS_IN_ARRAY
;
2854 CurrentRunningXacts
->nextXid
= XidFromFullTransactionId(TransamVariables
->nextXid
);
2855 CurrentRunningXacts
->oldestRunningXid
= oldestRunningXid
;
2856 CurrentRunningXacts
->oldestDatabaseRunningXid
= oldestDatabaseRunningXid
;
2857 CurrentRunningXacts
->latestCompletedXid
= latestCompletedXid
;
2859 Assert(TransactionIdIsValid(CurrentRunningXacts
->nextXid
));
2860 Assert(TransactionIdIsValid(CurrentRunningXacts
->oldestRunningXid
));
2861 Assert(TransactionIdIsNormal(CurrentRunningXacts
->latestCompletedXid
));
2863 /* We don't release the locks here, the caller is responsible for that */
2865 return CurrentRunningXacts
;
2869 * GetOldestActiveTransactionId()
2871 * Similar to GetSnapshotData but returns just oldestActiveXid. We include
2872 * all PGPROCs with an assigned TransactionId, even VACUUM processes.
2873 * We look at all databases, though there is no need to include WALSender
2874 * since this has no effect on hot standby conflicts.
2876 * This is never executed during recovery so there is no need to look at
2877 * KnownAssignedXids.
2879 * We don't worry about updating other counters, we want to keep this as
2880 * simple as possible and leave GetSnapshotData() as the primary code for
2884 GetOldestActiveTransactionId(void)
2886 ProcArrayStruct
*arrayP
= procArray
;
2887 TransactionId
*other_xids
= ProcGlobal
->xids
;
2888 TransactionId oldestRunningXid
;
2891 Assert(!RecoveryInProgress());
2894 * Read nextXid, as the upper bound of what's still active.
2896 * Reading a TransactionId is atomic, but we must grab the lock to make
2897 * sure that all XIDs < nextXid are already present in the proc array (or
2898 * have already completed), when we spin over it.
2900 LWLockAcquire(XidGenLock
, LW_SHARED
);
2901 oldestRunningXid
= XidFromFullTransactionId(TransamVariables
->nextXid
);
2902 LWLockRelease(XidGenLock
);
2905 * Spin over procArray collecting all xids and subxids.
2907 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
2908 for (index
= 0; index
< arrayP
->numProcs
; index
++)
2912 /* Fetch xid just once - see GetNewTransactionId */
2913 xid
= UINT32_ACCESS_ONCE(other_xids
[index
]);
2915 if (!TransactionIdIsNormal(xid
))
2918 if (TransactionIdPrecedes(xid
, oldestRunningXid
))
2919 oldestRunningXid
= xid
;
2922 * Top-level XID of a transaction is always less than any of its
2923 * subxids, so we don't need to check if any of the subxids are
2924 * smaller than oldestRunningXid
2927 LWLockRelease(ProcArrayLock
);
2929 return oldestRunningXid
;
2933 * GetOldestSafeDecodingTransactionId -- lowest xid not affected by vacuum
2935 * Returns the oldest xid that we can guarantee not to have been affected by
2936 * vacuum, i.e. no rows >= that xid have been vacuumed away unless the
2937 * transaction aborted. Note that the value can (and most of the time will) be
2938 * much more conservative than what really has been affected by vacuum, but we
2939 * currently don't have better data available.
2941 * This is useful to initialize the cutoff xid after which a new changeset
2942 * extraction replication slot can start decoding changes.
2944 * Must be called with ProcArrayLock held either shared or exclusively,
2945 * although most callers will want to use exclusive mode since it is expected
2946 * that the caller will immediately use the xid to peg the xmin horizon.
2949 GetOldestSafeDecodingTransactionId(bool catalogOnly
)
2951 ProcArrayStruct
*arrayP
= procArray
;
2952 TransactionId oldestSafeXid
;
2954 bool recovery_in_progress
= RecoveryInProgress();
2956 Assert(LWLockHeldByMe(ProcArrayLock
));
2959 * Acquire XidGenLock, so no transactions can acquire an xid while we're
2960 * running. If no transaction with xid were running concurrently a new xid
2961 * could influence the RecentXmin et al.
2963 * We initialize the computation to nextXid since that's guaranteed to be
2964 * a safe, albeit pessimal, value.
2966 LWLockAcquire(XidGenLock
, LW_SHARED
);
2967 oldestSafeXid
= XidFromFullTransactionId(TransamVariables
->nextXid
);
2970 * If there's already a slot pegging the xmin horizon, we can start with
2971 * that value, it's guaranteed to be safe since it's computed by this
2972 * routine initially and has been enforced since. We can always use the
2973 * slot's general xmin horizon, but the catalog horizon is only usable
2974 * when only catalog data is going to be looked at.
2976 if (TransactionIdIsValid(procArray
->replication_slot_xmin
) &&
2977 TransactionIdPrecedes(procArray
->replication_slot_xmin
,
2979 oldestSafeXid
= procArray
->replication_slot_xmin
;
2982 TransactionIdIsValid(procArray
->replication_slot_catalog_xmin
) &&
2983 TransactionIdPrecedes(procArray
->replication_slot_catalog_xmin
,
2985 oldestSafeXid
= procArray
->replication_slot_catalog_xmin
;
2988 * If we're not in recovery, we walk over the procarray and collect the
2989 * lowest xid. Since we're called with ProcArrayLock held and have
2990 * acquired XidGenLock, no entries can vanish concurrently, since
2991 * ProcGlobal->xids[i] is only set with XidGenLock held and only cleared
2992 * with ProcArrayLock held.
2994 * In recovery we can't lower the safe value besides what we've computed
2995 * above, so we'll have to wait a bit longer there. We unfortunately can
2996 * *not* use KnownAssignedXidsGetOldestXmin() since the KnownAssignedXids
2997 * machinery can miss values and return an older value than is safe.
2999 if (!recovery_in_progress
)
3001 TransactionId
*other_xids
= ProcGlobal
->xids
;
3004 * Spin over procArray collecting min(ProcGlobal->xids[i])
3006 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3010 /* Fetch xid just once - see GetNewTransactionId */
3011 xid
= UINT32_ACCESS_ONCE(other_xids
[index
]);
3013 if (!TransactionIdIsNormal(xid
))
3016 if (TransactionIdPrecedes(xid
, oldestSafeXid
))
3017 oldestSafeXid
= xid
;
3021 LWLockRelease(XidGenLock
);
3023 return oldestSafeXid
;
3027 * GetVirtualXIDsDelayingChkpt -- Get the VXIDs of transactions that are
3028 * delaying checkpoint because they have critical actions in progress.
3030 * Constructs an array of VXIDs of transactions that are currently in commit
3031 * critical sections, as shown by having specified delayChkptFlags bits set
3034 * Returns a palloc'd array that should be freed by the caller.
3035 * *nvxids is the number of valid entries.
3037 * Note that because backends set or clear delayChkptFlags without holding any
3038 * lock, the result is somewhat indeterminate, but we don't really care. Even
3039 * in a multiprocessor with delayed writes to shared memory, it should be
3040 * certain that setting of delayChkptFlags will propagate to shared memory
3041 * when the backend takes a lock, so we cannot fail to see a virtual xact as
3042 * delayChkptFlags if it's already inserted its commit record. Whether it
3043 * takes a little while for clearing of delayChkptFlags to propagate is
3044 * unimportant for correctness.
3046 VirtualTransactionId
*
3047 GetVirtualXIDsDelayingChkpt(int *nvxids
, int type
)
3049 VirtualTransactionId
*vxids
;
3050 ProcArrayStruct
*arrayP
= procArray
;
3056 /* allocate what's certainly enough result space */
3057 vxids
= (VirtualTransactionId
*)
3058 palloc(sizeof(VirtualTransactionId
) * arrayP
->maxProcs
);
3060 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3062 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3064 int pgprocno
= arrayP
->pgprocnos
[index
];
3065 PGPROC
*proc
= &allProcs
[pgprocno
];
3067 if ((proc
->delayChkptFlags
& type
) != 0)
3069 VirtualTransactionId vxid
;
3071 GET_VXID_FROM_PGPROC(vxid
, *proc
);
3072 if (VirtualTransactionIdIsValid(vxid
))
3073 vxids
[count
++] = vxid
;
3077 LWLockRelease(ProcArrayLock
);
3084 * HaveVirtualXIDsDelayingChkpt -- Are any of the specified VXIDs delaying?
3086 * This is used with the results of GetVirtualXIDsDelayingChkpt to see if any
3087 * of the specified VXIDs are still in critical sections of code.
3089 * Note: this is O(N^2) in the number of vxacts that are/were delaying, but
3090 * those numbers should be small enough for it not to be a problem.
3093 HaveVirtualXIDsDelayingChkpt(VirtualTransactionId
*vxids
, int nvxids
, int type
)
3095 bool result
= false;
3096 ProcArrayStruct
*arrayP
= procArray
;
3101 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3103 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3105 int pgprocno
= arrayP
->pgprocnos
[index
];
3106 PGPROC
*proc
= &allProcs
[pgprocno
];
3107 VirtualTransactionId vxid
;
3109 GET_VXID_FROM_PGPROC(vxid
, *proc
);
3111 if ((proc
->delayChkptFlags
& type
) != 0 &&
3112 VirtualTransactionIdIsValid(vxid
))
3116 for (i
= 0; i
< nvxids
; i
++)
3118 if (VirtualTransactionIdEquals(vxid
, vxids
[i
]))
3129 LWLockRelease(ProcArrayLock
);
3135 * ProcNumberGetProc -- get a backend's PGPROC given its proc number
3137 * The result may be out of date arbitrarily quickly, so the caller
3138 * must be careful about how this information is used. NULL is
3139 * returned if the backend is not active.
3142 ProcNumberGetProc(ProcNumber procNumber
)
3146 if (procNumber
< 0 || procNumber
>= ProcGlobal
->allProcCount
)
3148 result
= GetPGProcByNumber(procNumber
);
3150 if (result
->pid
== 0)
3157 * ProcNumberGetTransactionIds -- get a backend's transaction status
3159 * Get the xid, xmin, nsubxid and overflow status of the backend. The
3160 * result may be out of date arbitrarily quickly, so the caller must be
3161 * careful about how this information is used.
3164 ProcNumberGetTransactionIds(ProcNumber procNumber
, TransactionId
*xid
,
3165 TransactionId
*xmin
, int *nsubxid
, bool *overflowed
)
3169 *xid
= InvalidTransactionId
;
3170 *xmin
= InvalidTransactionId
;
3172 *overflowed
= false;
3174 if (procNumber
< 0 || procNumber
>= ProcGlobal
->allProcCount
)
3176 proc
= GetPGProcByNumber(procNumber
);
3178 /* Need to lock out additions/removals of backends */
3179 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3185 *nsubxid
= proc
->subxidStatus
.count
;
3186 *overflowed
= proc
->subxidStatus
.overflowed
;
3189 LWLockRelease(ProcArrayLock
);
3193 * BackendPidGetProc -- get a backend's PGPROC given its PID
3195 * Returns NULL if not found. Note that it is up to the caller to be
3196 * sure that the question remains meaningful for long enough for the
3197 * answer to be used ...
3200 BackendPidGetProc(int pid
)
3204 if (pid
== 0) /* never match dummy PGPROCs */
3207 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3209 result
= BackendPidGetProcWithLock(pid
);
3211 LWLockRelease(ProcArrayLock
);
3217 * BackendPidGetProcWithLock -- get a backend's PGPROC given its PID
3219 * Same as above, except caller must be holding ProcArrayLock. The found
3220 * entry, if any, can be assumed to be valid as long as the lock remains held.
3223 BackendPidGetProcWithLock(int pid
)
3225 PGPROC
*result
= NULL
;
3226 ProcArrayStruct
*arrayP
= procArray
;
3229 if (pid
== 0) /* never match dummy PGPROCs */
3232 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3234 PGPROC
*proc
= &allProcs
[arrayP
->pgprocnos
[index
]];
3236 if (proc
->pid
== pid
)
3247 * BackendXidGetPid -- get a backend's pid given its XID
3249 * Returns 0 if not found or it's a prepared transaction. Note that
3250 * it is up to the caller to be sure that the question remains
3251 * meaningful for long enough for the answer to be used ...
3253 * Only main transaction Ids are considered. This function is mainly
3254 * useful for determining what backend owns a lock.
3256 * Beware that not every xact has an XID assigned. However, as long as you
3257 * only call this using an XID found on disk, you're safe.
3260 BackendXidGetPid(TransactionId xid
)
3263 ProcArrayStruct
*arrayP
= procArray
;
3264 TransactionId
*other_xids
= ProcGlobal
->xids
;
3267 if (xid
== InvalidTransactionId
) /* never match invalid xid */
3270 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3272 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3274 if (other_xids
[index
] == xid
)
3276 int pgprocno
= arrayP
->pgprocnos
[index
];
3277 PGPROC
*proc
= &allProcs
[pgprocno
];
3284 LWLockRelease(ProcArrayLock
);
3290 * IsBackendPid -- is a given pid a running backend
3292 * This is not called by the backend, but is called by external modules.
3295 IsBackendPid(int pid
)
3297 return (BackendPidGetProc(pid
) != NULL
);
3302 * GetCurrentVirtualXIDs -- returns an array of currently active VXIDs.
3304 * The array is palloc'd. The number of valid entries is returned into *nvxids.
3306 * The arguments allow filtering the set of VXIDs returned. Our own process
3307 * is always skipped. In addition:
3308 * If limitXmin is not InvalidTransactionId, skip processes with
3310 * If excludeXmin0 is true, skip processes with xmin = 0.
3311 * If allDbs is false, skip processes attached to other databases.
3312 * If excludeVacuum isn't zero, skip processes for which
3313 * (statusFlags & excludeVacuum) is not zero.
3315 * Note: the purpose of the limitXmin and excludeXmin0 parameters is to
3316 * allow skipping backends whose oldest live snapshot is no older than
3317 * some snapshot we have. Since we examine the procarray with only shared
3318 * lock, there are race conditions: a backend could set its xmin just after
3319 * we look. Indeed, on multiprocessors with weak memory ordering, the
3320 * other backend could have set its xmin *before* we look. We know however
3321 * that such a backend must have held shared ProcArrayLock overlapping our
3322 * own hold of ProcArrayLock, else we would see its xmin update. Therefore,
3323 * any snapshot the other backend is taking concurrently with our scan cannot
3324 * consider any transactions as still running that we think are committed
3325 * (since backends must hold ProcArrayLock exclusive to commit).
3327 VirtualTransactionId
*
3328 GetCurrentVirtualXIDs(TransactionId limitXmin
, bool excludeXmin0
,
3329 bool allDbs
, int excludeVacuum
,
3332 VirtualTransactionId
*vxids
;
3333 ProcArrayStruct
*arrayP
= procArray
;
3337 /* allocate what's certainly enough result space */
3338 vxids
= (VirtualTransactionId
*)
3339 palloc(sizeof(VirtualTransactionId
) * arrayP
->maxProcs
);
3341 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3343 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3345 int pgprocno
= arrayP
->pgprocnos
[index
];
3346 PGPROC
*proc
= &allProcs
[pgprocno
];
3347 uint8 statusFlags
= ProcGlobal
->statusFlags
[index
];
3352 if (excludeVacuum
& statusFlags
)
3355 if (allDbs
|| proc
->databaseId
== MyDatabaseId
)
3357 /* Fetch xmin just once - might change on us */
3358 TransactionId pxmin
= UINT32_ACCESS_ONCE(proc
->xmin
);
3360 if (excludeXmin0
&& !TransactionIdIsValid(pxmin
))
3364 * InvalidTransactionId precedes all other XIDs, so a proc that
3365 * hasn't set xmin yet will not be rejected by this test.
3367 if (!TransactionIdIsValid(limitXmin
) ||
3368 TransactionIdPrecedesOrEquals(pxmin
, limitXmin
))
3370 VirtualTransactionId vxid
;
3372 GET_VXID_FROM_PGPROC(vxid
, *proc
);
3373 if (VirtualTransactionIdIsValid(vxid
))
3374 vxids
[count
++] = vxid
;
3379 LWLockRelease(ProcArrayLock
);
3386 * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs.
3388 * Usage is limited to conflict resolution during recovery on standby servers.
3389 * limitXmin is supplied as either a cutoff with snapshotConflictHorizon
3390 * semantics, or InvalidTransactionId in cases where caller cannot accurately
3391 * determine a safe snapshotConflictHorizon value.
3393 * If limitXmin is InvalidTransactionId then we want to kill everybody,
3394 * so we're not worried if they have a snapshot or not, nor does it really
3395 * matter what type of lock we hold. Caller must avoid calling here with
3396 * snapshotConflictHorizon style cutoffs that were set to InvalidTransactionId
3397 * during original execution, since that actually indicates that there is
3398 * definitely no need for a recovery conflict (the snapshotConflictHorizon
3399 * convention for InvalidTransactionId values is the opposite of our own!).
3401 * All callers that are checking xmins always now supply a valid and useful
3402 * value for limitXmin. The limitXmin is always lower than the lowest
3403 * numbered KnownAssignedXid that is not already a FATAL error. This is
3404 * because we only care about cleanup records that are cleaning up tuple
3405 * versions from committed transactions. In that case they will only occur
3406 * at the point where the record is less than the lowest running xid. That
3407 * allows us to say that if any backend takes a snapshot concurrently with
3408 * us then the conflict assessment made here would never include the snapshot
3409 * that is being derived. So we take LW_SHARED on the ProcArray and allow
3410 * concurrent snapshots when limitXmin is valid. We might think about adding
3411 * Assert(limitXmin < lowest(KnownAssignedXids))
3412 * but that would not be true in the case of FATAL errors lagging in array,
3413 * but we already know those are bogus anyway, so we skip that test.
3415 * If dbOid is valid we skip backends attached to other databases.
3417 * Be careful to *not* pfree the result from this function. We reuse
3418 * this array sufficiently often that we use malloc for the result.
3420 VirtualTransactionId
*
3421 GetConflictingVirtualXIDs(TransactionId limitXmin
, Oid dbOid
)
3423 static VirtualTransactionId
*vxids
;
3424 ProcArrayStruct
*arrayP
= procArray
;
3429 * If first time through, get workspace to remember main XIDs in. We
3430 * malloc it permanently to avoid repeated palloc/pfree overhead. Allow
3431 * result space, remembering room for a terminator.
3435 vxids
= (VirtualTransactionId
*)
3436 malloc(sizeof(VirtualTransactionId
) * (arrayP
->maxProcs
+ 1));
3439 (errcode(ERRCODE_OUT_OF_MEMORY
),
3440 errmsg("out of memory")));
3443 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3445 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3447 int pgprocno
= arrayP
->pgprocnos
[index
];
3448 PGPROC
*proc
= &allProcs
[pgprocno
];
3450 /* Exclude prepared transactions */
3454 if (!OidIsValid(dbOid
) ||
3455 proc
->databaseId
== dbOid
)
3457 /* Fetch xmin just once - can't change on us, but good coding */
3458 TransactionId pxmin
= UINT32_ACCESS_ONCE(proc
->xmin
);
3461 * We ignore an invalid pxmin because this means that backend has
3462 * no snapshot currently. We hold a Share lock to avoid contention
3463 * with users taking snapshots. That is not a problem because the
3464 * current xmin is always at least one higher than the latest
3465 * removed xid, so any new snapshot would never conflict with the
3468 if (!TransactionIdIsValid(limitXmin
) ||
3469 (TransactionIdIsValid(pxmin
) && !TransactionIdFollows(pxmin
, limitXmin
)))
3471 VirtualTransactionId vxid
;
3473 GET_VXID_FROM_PGPROC(vxid
, *proc
);
3474 if (VirtualTransactionIdIsValid(vxid
))
3475 vxids
[count
++] = vxid
;
3480 LWLockRelease(ProcArrayLock
);
3482 /* add the terminator */
3483 vxids
[count
].procNumber
= INVALID_PROC_NUMBER
;
3484 vxids
[count
].localTransactionId
= InvalidLocalTransactionId
;
3490 * CancelVirtualTransaction - used in recovery conflict processing
3492 * Returns pid of the process signaled, or 0 if not found.
3495 CancelVirtualTransaction(VirtualTransactionId vxid
, ProcSignalReason sigmode
)
3497 return SignalVirtualTransaction(vxid
, sigmode
, true);
3501 SignalVirtualTransaction(VirtualTransactionId vxid
, ProcSignalReason sigmode
,
3502 bool conflictPending
)
3504 ProcArrayStruct
*arrayP
= procArray
;
3508 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3510 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3512 int pgprocno
= arrayP
->pgprocnos
[index
];
3513 PGPROC
*proc
= &allProcs
[pgprocno
];
3514 VirtualTransactionId procvxid
;
3516 GET_VXID_FROM_PGPROC(procvxid
, *proc
);
3518 if (procvxid
.procNumber
== vxid
.procNumber
&&
3519 procvxid
.localTransactionId
== vxid
.localTransactionId
)
3521 proc
->recoveryConflictPending
= conflictPending
;
3526 * Kill the pid if it's still here. If not, that's what we
3527 * wanted so ignore any errors.
3529 (void) SendProcSignal(pid
, sigmode
, vxid
.procNumber
);
3535 LWLockRelease(ProcArrayLock
);
3541 * MinimumActiveBackends --- count backends (other than myself) that are
3542 * in active transactions. Return true if the count exceeds the
3543 * minimum threshold passed. This is used as a heuristic to decide if
3544 * a pre-XLOG-flush delay is worthwhile during commit.
3546 * Do not count backends that are blocked waiting for locks, since they are
3547 * not going to get to run until someone else commits.
3550 MinimumActiveBackends(int min
)
3552 ProcArrayStruct
*arrayP
= procArray
;
3556 /* Quick short-circuit if no minimum is specified */
3561 * Note: for speed, we don't acquire ProcArrayLock. This is a little bit
3562 * bogus, but since we are only testing fields for zero or nonzero, it
3563 * should be OK. The result is only used for heuristic purposes anyway...
3565 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3567 int pgprocno
= arrayP
->pgprocnos
[index
];
3568 PGPROC
*proc
= &allProcs
[pgprocno
];
3571 * Since we're not holding a lock, need to be prepared to deal with
3572 * garbage, as someone could have incremented numProcs but not yet
3573 * filled the structure.
3575 * If someone just decremented numProcs, 'proc' could also point to a
3576 * PGPROC entry that's no longer in the array. It still points to a
3577 * PGPROC struct, though, because freed PGPROC entries just go to the
3578 * free list and are recycled. Its contents are nonsense in that case,
3579 * but that's acceptable for this function.
3582 continue; /* do not count deleted entries */
3584 continue; /* do not count myself */
3585 if (proc
->xid
== InvalidTransactionId
)
3586 continue; /* do not count if no XID assigned */
3588 continue; /* do not count prepared xacts */
3589 if (proc
->waitLock
!= NULL
)
3590 continue; /* do not count if blocked on a lock */
3596 return count
>= min
;
3600 * CountDBBackends --- count backends that are using specified database
3603 CountDBBackends(Oid databaseid
)
3605 ProcArrayStruct
*arrayP
= procArray
;
3609 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3611 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3613 int pgprocno
= arrayP
->pgprocnos
[index
];
3614 PGPROC
*proc
= &allProcs
[pgprocno
];
3617 continue; /* do not count prepared xacts */
3618 if (!OidIsValid(databaseid
) ||
3619 proc
->databaseId
== databaseid
)
3623 LWLockRelease(ProcArrayLock
);
3629 * CountDBConnections --- counts database backends ignoring any background
3633 CountDBConnections(Oid databaseid
)
3635 ProcArrayStruct
*arrayP
= procArray
;
3639 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3641 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3643 int pgprocno
= arrayP
->pgprocnos
[index
];
3644 PGPROC
*proc
= &allProcs
[pgprocno
];
3647 continue; /* do not count prepared xacts */
3648 if (proc
->isBackgroundWorker
)
3649 continue; /* do not count background workers */
3650 if (!OidIsValid(databaseid
) ||
3651 proc
->databaseId
== databaseid
)
3655 LWLockRelease(ProcArrayLock
);
3661 * CancelDBBackends --- cancel backends that are using specified database
3664 CancelDBBackends(Oid databaseid
, ProcSignalReason sigmode
, bool conflictPending
)
3666 ProcArrayStruct
*arrayP
= procArray
;
3669 /* tell all backends to die */
3670 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
3672 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3674 int pgprocno
= arrayP
->pgprocnos
[index
];
3675 PGPROC
*proc
= &allProcs
[pgprocno
];
3677 if (databaseid
== InvalidOid
|| proc
->databaseId
== databaseid
)
3679 VirtualTransactionId procvxid
;
3682 GET_VXID_FROM_PGPROC(procvxid
, *proc
);
3684 proc
->recoveryConflictPending
= conflictPending
;
3689 * Kill the pid if it's still here. If not, that's what we
3690 * wanted so ignore any errors.
3692 (void) SendProcSignal(pid
, sigmode
, procvxid
.procNumber
);
3697 LWLockRelease(ProcArrayLock
);
3701 * CountUserBackends --- count backends that are used by specified user
3704 CountUserBackends(Oid roleid
)
3706 ProcArrayStruct
*arrayP
= procArray
;
3710 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3712 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3714 int pgprocno
= arrayP
->pgprocnos
[index
];
3715 PGPROC
*proc
= &allProcs
[pgprocno
];
3718 continue; /* do not count prepared xacts */
3719 if (proc
->isBackgroundWorker
)
3720 continue; /* do not count background workers */
3721 if (proc
->roleId
== roleid
)
3725 LWLockRelease(ProcArrayLock
);
3731 * CountOtherDBBackends -- check for other backends running in the given DB
3733 * If there are other backends in the DB, we will wait a maximum of 5 seconds
3734 * for them to exit. Autovacuum backends are encouraged to exit early by
3735 * sending them SIGTERM, but normal user backends are just waited for.
3737 * The current backend is always ignored; it is caller's responsibility to
3738 * check whether the current backend uses the given DB, if it's important.
3740 * Returns true if there are (still) other backends in the DB, false if not.
3741 * Also, *nbackends and *nprepared are set to the number of other backends
3742 * and prepared transactions in the DB, respectively.
3744 * This function is used to interlock DROP DATABASE and related commands
3745 * against there being any active backends in the target DB --- dropping the
3746 * DB while active backends remain would be a Bad Thing. Note that we cannot
3747 * detect here the possibility of a newly-started backend that is trying to
3748 * connect to the doomed database, so additional interlocking is needed during
3749 * backend startup. The caller should normally hold an exclusive lock on the
3750 * target DB before calling this, which is one reason we mustn't wait
3754 CountOtherDBBackends(Oid databaseId
, int *nbackends
, int *nprepared
)
3756 ProcArrayStruct
*arrayP
= procArray
;
3758 #define MAXAUTOVACPIDS 10 /* max autovacs to SIGTERM per iteration */
3759 int autovac_pids
[MAXAUTOVACPIDS
];
3762 /* 50 tries with 100ms sleep between tries makes 5 sec total wait */
3763 for (tries
= 0; tries
< 50; tries
++)
3769 CHECK_FOR_INTERRUPTS();
3771 *nbackends
= *nprepared
= 0;
3773 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3775 for (index
= 0; index
< arrayP
->numProcs
; index
++)
3777 int pgprocno
= arrayP
->pgprocnos
[index
];
3778 PGPROC
*proc
= &allProcs
[pgprocno
];
3779 uint8 statusFlags
= ProcGlobal
->statusFlags
[index
];
3781 if (proc
->databaseId
!= databaseId
)
3793 if ((statusFlags
& PROC_IS_AUTOVACUUM
) &&
3794 nautovacs
< MAXAUTOVACPIDS
)
3795 autovac_pids
[nautovacs
++] = proc
->pid
;
3799 LWLockRelease(ProcArrayLock
);
3802 return false; /* no conflicting backends, so done */
3805 * Send SIGTERM to any conflicting autovacuums before sleeping. We
3806 * postpone this step until after the loop because we don't want to
3807 * hold ProcArrayLock while issuing kill(). We have no idea what might
3808 * block kill() inside the kernel...
3810 for (index
= 0; index
< nautovacs
; index
++)
3811 (void) kill(autovac_pids
[index
], SIGTERM
); /* ignore any error */
3813 /* sleep, then try again */
3814 pg_usleep(100 * 1000L); /* 100ms */
3817 return true; /* timed out, still conflicts */
3821 * Terminate existing connections to the specified database. This routine
3822 * is used by the DROP DATABASE command when user has asked to forcefully
3823 * drop the database.
3825 * The current backend is always ignored; it is caller's responsibility to
3826 * check whether the current backend uses the given DB, if it's important.
3828 * If the target database has a prepared transaction or permissions checks
3829 * fail for a connection, this fails without terminating anything.
3832 TerminateOtherDBBackends(Oid databaseId
)
3834 ProcArrayStruct
*arrayP
= procArray
;
3839 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3841 for (i
= 0; i
< procArray
->numProcs
; i
++)
3843 int pgprocno
= arrayP
->pgprocnos
[i
];
3844 PGPROC
*proc
= &allProcs
[pgprocno
];
3846 if (proc
->databaseId
!= databaseId
)
3852 pids
= lappend_int(pids
, proc
->pid
);
3857 LWLockRelease(ProcArrayLock
);
3861 (errcode(ERRCODE_OBJECT_IN_USE
),
3862 errmsg("database \"%s\" is being used by prepared transactions",
3863 get_database_name(databaseId
)),
3864 errdetail_plural("There is %d prepared transaction using the database.",
3865 "There are %d prepared transactions using the database.",
3874 * Permissions checks relax the pg_terminate_backend checks in two
3875 * ways, both by omitting the !OidIsValid(proc->roleId) check:
3877 * - Accept terminating autovacuum workers, since DROP DATABASE
3878 * without FORCE terminates them.
3880 * - Accept terminating bgworkers. For bgworker authors, it's
3881 * convenient to be able to recommend FORCE if a worker is blocking
3882 * DROP DATABASE unexpectedly.
3884 * Unlike pg_terminate_backend, we don't raise some warnings - like
3885 * "PID %d is not a PostgreSQL server process", because for us already
3886 * finished session is not a problem.
3890 int pid
= lfirst_int(lc
);
3891 PGPROC
*proc
= BackendPidGetProc(pid
);
3895 if (superuser_arg(proc
->roleId
) && !superuser())
3897 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
3898 errmsg("permission denied to terminate process"),
3899 errdetail("Only roles with the %s attribute may terminate processes of roles with the %s attribute.",
3900 "SUPERUSER", "SUPERUSER")));
3902 if (!has_privs_of_role(GetUserId(), proc
->roleId
) &&
3903 !has_privs_of_role(GetUserId(), ROLE_PG_SIGNAL_BACKEND
))
3905 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
3906 errmsg("permission denied to terminate process"),
3907 errdetail("Only roles with privileges of the role whose process is being terminated or with privileges of the \"%s\" role may terminate this process.",
3908 "pg_signal_backend")));
3913 * There's a race condition here: once we release the ProcArrayLock,
3914 * it's possible for the session to exit before we issue kill. That
3915 * race condition possibility seems too unlikely to worry about. See
3916 * pg_signal_backend.
3920 int pid
= lfirst_int(lc
);
3921 PGPROC
*proc
= BackendPidGetProc(pid
);
3926 * If we have setsid(), signal the backend's whole process
3930 (void) kill(-pid
, SIGTERM
);
3932 (void) kill(pid
, SIGTERM
);
3940 * ProcArraySetReplicationSlotXmin
3942 * Install limits to future computations of the xmin horizon to prevent vacuum
3943 * and HOT pruning from removing affected rows still needed by clients with
3944 * replication slots.
3947 ProcArraySetReplicationSlotXmin(TransactionId xmin
, TransactionId catalog_xmin
,
3948 bool already_locked
)
3950 Assert(!already_locked
|| LWLockHeldByMe(ProcArrayLock
));
3952 if (!already_locked
)
3953 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
3955 procArray
->replication_slot_xmin
= xmin
;
3956 procArray
->replication_slot_catalog_xmin
= catalog_xmin
;
3958 if (!already_locked
)
3959 LWLockRelease(ProcArrayLock
);
3961 elog(DEBUG1
, "xmin required by slots: data %u, catalog %u",
3962 xmin
, catalog_xmin
);
3966 * ProcArrayGetReplicationSlotXmin
3968 * Return the current slot xmin limits. That's useful to be able to remove
3969 * data that's older than those limits.
3972 ProcArrayGetReplicationSlotXmin(TransactionId
*xmin
,
3973 TransactionId
*catalog_xmin
)
3975 LWLockAcquire(ProcArrayLock
, LW_SHARED
);
3978 *xmin
= procArray
->replication_slot_xmin
;
3980 if (catalog_xmin
!= NULL
)
3981 *catalog_xmin
= procArray
->replication_slot_catalog_xmin
;
3983 LWLockRelease(ProcArrayLock
);
3987 * XidCacheRemoveRunningXids
3989 * Remove a bunch of TransactionIds from the list of known-running
3990 * subtransactions for my backend. Both the specified xid and those in
3991 * the xids[] array (of length nxids) are removed from the subxids cache.
3992 * latestXid must be the latest XID among the group.
3995 XidCacheRemoveRunningXids(TransactionId xid
,
3996 int nxids
, const TransactionId
*xids
,
3997 TransactionId latestXid
)
4001 XidCacheStatus
*mysubxidstat
;
4003 Assert(TransactionIdIsValid(xid
));
4006 * We must hold ProcArrayLock exclusively in order to remove transactions
4007 * from the PGPROC array. (See src/backend/access/transam/README.) It's
4008 * possible this could be relaxed since we know this routine is only used
4009 * to abort subtransactions, but pending closer analysis we'd best be
4012 * Note that we do not have to be careful about memory ordering of our own
4013 * reads wrt. GetNewTransactionId() here - only this process can modify
4014 * relevant fields of MyProc/ProcGlobal->xids[]. But we do have to be
4015 * careful about our own writes being well ordered.
4017 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
4019 mysubxidstat
= &ProcGlobal
->subxidStates
[MyProc
->pgxactoff
];
4022 * Under normal circumstances xid and xids[] will be in increasing order,
4023 * as will be the entries in subxids. Scan backwards to avoid O(N^2)
4024 * behavior when removing a lot of xids.
4026 for (i
= nxids
- 1; i
>= 0; i
--)
4028 TransactionId anxid
= xids
[i
];
4030 for (j
= MyProc
->subxidStatus
.count
- 1; j
>= 0; j
--)
4032 if (TransactionIdEquals(MyProc
->subxids
.xids
[j
], anxid
))
4034 MyProc
->subxids
.xids
[j
] = MyProc
->subxids
.xids
[MyProc
->subxidStatus
.count
- 1];
4036 mysubxidstat
->count
--;
4037 MyProc
->subxidStatus
.count
--;
4043 * Ordinarily we should have found it, unless the cache has
4044 * overflowed. However it's also possible for this routine to be
4045 * invoked multiple times for the same subtransaction, in case of an
4046 * error during AbortSubTransaction. So instead of Assert, emit a
4049 if (j
< 0 && !MyProc
->subxidStatus
.overflowed
)
4050 elog(WARNING
, "did not find subXID %u in MyProc", anxid
);
4053 for (j
= MyProc
->subxidStatus
.count
- 1; j
>= 0; j
--)
4055 if (TransactionIdEquals(MyProc
->subxids
.xids
[j
], xid
))
4057 MyProc
->subxids
.xids
[j
] = MyProc
->subxids
.xids
[MyProc
->subxidStatus
.count
- 1];
4059 mysubxidstat
->count
--;
4060 MyProc
->subxidStatus
.count
--;
4064 /* Ordinarily we should have found it, unless the cache has overflowed */
4065 if (j
< 0 && !MyProc
->subxidStatus
.overflowed
)
4066 elog(WARNING
, "did not find subXID %u in MyProc", xid
);
4068 /* Also advance global latestCompletedXid while holding the lock */
4069 MaintainLatestCompletedXid(latestXid
);
4071 /* ... and xactCompletionCount */
4072 TransamVariables
->xactCompletionCount
++;
4074 LWLockRelease(ProcArrayLock
);
4077 #ifdef XIDCACHE_DEBUG
4080 * Print stats about effectiveness of XID cache
4083 DisplayXidCache(void)
4086 "XidCache: xmin: %ld, known: %ld, myxact: %ld, latest: %ld, mainxid: %ld, childxid: %ld, knownassigned: %ld, nooflo: %ld, slow: %ld\n",
4093 xc_by_known_assigned
,
4097 #endif /* XIDCACHE_DEBUG */
4100 * If rel != NULL, return test state appropriate for relation, otherwise
4101 * return state usable for all relations. The latter may consider XIDs as
4102 * not-yet-visible-to-everyone that a state for a specific relation would
4103 * already consider visible-to-everyone.
4105 * This needs to be called while a snapshot is active or registered, otherwise
4106 * there are wraparound and other dangers.
4108 * See comment for GlobalVisState for details.
4111 GlobalVisTestFor(Relation rel
)
4113 GlobalVisState
*state
= NULL
;
4115 /* XXX: we should assert that a snapshot is pushed or registered */
4118 switch (GlobalVisHorizonKindForRel(rel
))
4120 case VISHORIZON_SHARED
:
4121 state
= &GlobalVisSharedRels
;
4123 case VISHORIZON_CATALOG
:
4124 state
= &GlobalVisCatalogRels
;
4126 case VISHORIZON_DATA
:
4127 state
= &GlobalVisDataRels
;
4129 case VISHORIZON_TEMP
:
4130 state
= &GlobalVisTempRels
;
4134 Assert(FullTransactionIdIsValid(state
->definitely_needed
) &&
4135 FullTransactionIdIsValid(state
->maybe_needed
));
4141 * Return true if it's worth updating the accurate maybe_needed boundary.
4143 * As it is somewhat expensive to determine xmin horizons, we don't want to
4144 * repeatedly do so when there is a low likelihood of it being beneficial.
4146 * The current heuristic is that we update only if RecentXmin has changed
4147 * since the last update. If the oldest currently running transaction has not
4148 * finished, it is unlikely that recomputing the horizon would be useful.
4151 GlobalVisTestShouldUpdate(GlobalVisState
*state
)
4153 /* hasn't been updated yet */
4154 if (!TransactionIdIsValid(ComputeXidHorizonsResultLastXmin
))
4158 * If the maybe_needed/definitely_needed boundaries are the same, it's
4159 * unlikely to be beneficial to refresh boundaries.
4161 if (FullTransactionIdFollowsOrEquals(state
->maybe_needed
,
4162 state
->definitely_needed
))
4165 /* does the last snapshot built have a different xmin? */
4166 return RecentXmin
!= ComputeXidHorizonsResultLastXmin
;
4170 GlobalVisUpdateApply(ComputeXidHorizonsResult
*horizons
)
4172 GlobalVisSharedRels
.maybe_needed
=
4173 FullXidRelativeTo(horizons
->latest_completed
,
4174 horizons
->shared_oldest_nonremovable
);
4175 GlobalVisCatalogRels
.maybe_needed
=
4176 FullXidRelativeTo(horizons
->latest_completed
,
4177 horizons
->catalog_oldest_nonremovable
);
4178 GlobalVisDataRels
.maybe_needed
=
4179 FullXidRelativeTo(horizons
->latest_completed
,
4180 horizons
->data_oldest_nonremovable
);
4181 GlobalVisTempRels
.maybe_needed
=
4182 FullXidRelativeTo(horizons
->latest_completed
,
4183 horizons
->temp_oldest_nonremovable
);
4186 * In longer running transactions it's possible that transactions we
4187 * previously needed to treat as running aren't around anymore. So update
4188 * definitely_needed to not be earlier than maybe_needed.
4190 GlobalVisSharedRels
.definitely_needed
=
4191 FullTransactionIdNewer(GlobalVisSharedRels
.maybe_needed
,
4192 GlobalVisSharedRels
.definitely_needed
);
4193 GlobalVisCatalogRels
.definitely_needed
=
4194 FullTransactionIdNewer(GlobalVisCatalogRels
.maybe_needed
,
4195 GlobalVisCatalogRels
.definitely_needed
);
4196 GlobalVisDataRels
.definitely_needed
=
4197 FullTransactionIdNewer(GlobalVisDataRels
.maybe_needed
,
4198 GlobalVisDataRels
.definitely_needed
);
4199 GlobalVisTempRels
.definitely_needed
= GlobalVisTempRels
.maybe_needed
;
4201 ComputeXidHorizonsResultLastXmin
= RecentXmin
;
4205 * Update boundaries in GlobalVis{Shared,Catalog, Data}Rels
4206 * using ComputeXidHorizons().
4209 GlobalVisUpdate(void)
4211 ComputeXidHorizonsResult horizons
;
4213 /* updates the horizons as a side-effect */
4214 ComputeXidHorizons(&horizons
);
4218 * Return true if no snapshot still considers fxid to be running.
4220 * The state passed needs to have been initialized for the relation fxid is
4221 * from (NULL is also OK), otherwise the result may not be correct.
4223 * See comment for GlobalVisState for details.
4226 GlobalVisTestIsRemovableFullXid(GlobalVisState
*state
,
4227 FullTransactionId fxid
)
4230 * If fxid is older than maybe_needed bound, it definitely is visible to
4233 if (FullTransactionIdPrecedes(fxid
, state
->maybe_needed
))
4237 * If fxid is >= definitely_needed bound, it is very likely to still be
4238 * considered running.
4240 if (FullTransactionIdFollowsOrEquals(fxid
, state
->definitely_needed
))
4244 * fxid is between maybe_needed and definitely_needed, i.e. there might or
4245 * might not exist a snapshot considering fxid running. If it makes sense,
4246 * update boundaries and recheck.
4248 if (GlobalVisTestShouldUpdate(state
))
4252 Assert(FullTransactionIdPrecedes(fxid
, state
->definitely_needed
));
4254 return FullTransactionIdPrecedes(fxid
, state
->maybe_needed
);
4261 * Wrapper around GlobalVisTestIsRemovableFullXid() for 32bit xids.
4263 * It is crucial that this only gets called for xids from a source that
4264 * protects against xid wraparounds (e.g. from a table and thus protected by
4268 GlobalVisTestIsRemovableXid(GlobalVisState
*state
, TransactionId xid
)
4270 FullTransactionId fxid
;
4273 * Convert 32 bit argument to FullTransactionId. We can do so safely
4274 * because we know the xid has to, at the very least, be between
4275 * [oldestXid, nextXid), i.e. within 2 billion of xid. To avoid taking a
4276 * lock to determine either, we can just compare with
4277 * state->definitely_needed, which was based on those value at the time
4278 * the current snapshot was built.
4280 fxid
= FullXidRelativeTo(state
->definitely_needed
, xid
);
4282 return GlobalVisTestIsRemovableFullXid(state
, fxid
);
4286 * Convenience wrapper around GlobalVisTestFor() and
4287 * GlobalVisTestIsRemovableFullXid(), see their comments.
4290 GlobalVisCheckRemovableFullXid(Relation rel
, FullTransactionId fxid
)
4292 GlobalVisState
*state
;
4294 state
= GlobalVisTestFor(rel
);
4296 return GlobalVisTestIsRemovableFullXid(state
, fxid
);
4300 * Convenience wrapper around GlobalVisTestFor() and
4301 * GlobalVisTestIsRemovableXid(), see their comments.
4304 GlobalVisCheckRemovableXid(Relation rel
, TransactionId xid
)
4306 GlobalVisState
*state
;
4308 state
= GlobalVisTestFor(rel
);
4310 return GlobalVisTestIsRemovableXid(state
, xid
);
4314 * Convert a 32 bit transaction id into 64 bit transaction id, by assuming it
4315 * is within MaxTransactionId / 2 of XidFromFullTransactionId(rel).
4317 * Be very careful about when to use this function. It can only safely be used
4318 * when there is a guarantee that xid is within MaxTransactionId / 2 xids of
4319 * rel. That e.g. can be guaranteed if the caller assures a snapshot is
4320 * held by the backend and xid is from a table (where vacuum/freezing ensures
4321 * the xid has to be within that range), or if xid is from the procarray and
4322 * prevents xid wraparound that way.
4324 static inline FullTransactionId
4325 FullXidRelativeTo(FullTransactionId rel
, TransactionId xid
)
4327 TransactionId rel_xid
= XidFromFullTransactionId(rel
);
4329 Assert(TransactionIdIsValid(xid
));
4330 Assert(TransactionIdIsValid(rel_xid
));
4332 /* not guaranteed to find issues, but likely to catch mistakes */
4333 AssertTransactionIdInAllowableRange(xid
);
4335 return FullTransactionIdFromU64(U64FromFullTransactionId(rel
)
4336 + (int32
) (xid
- rel_xid
));
4340 /* ----------------------------------------------
4341 * KnownAssignedTransactionIds sub-module
4342 * ----------------------------------------------
4346 * In Hot Standby mode, we maintain a list of transactions that are (or were)
4347 * running on the primary at the current point in WAL. These XIDs must be
4348 * treated as running by standby transactions, even though they are not in
4349 * the standby server's PGPROC array.
4351 * We record all XIDs that we know have been assigned. That includes all the
4352 * XIDs seen in WAL records, plus all unobserved XIDs that we can deduce have
4353 * been assigned. We can deduce the existence of unobserved XIDs because we
4354 * know XIDs are assigned in sequence, with no gaps. The KnownAssignedXids
4355 * list expands as new XIDs are observed or inferred, and contracts when
4356 * transaction completion records arrive.
4358 * During hot standby we do not fret too much about the distinction between
4359 * top-level XIDs and subtransaction XIDs. We store both together in the
4360 * KnownAssignedXids list. In backends, this is copied into snapshots in
4361 * GetSnapshotData(), taking advantage of the fact that XidInMVCCSnapshot()
4362 * doesn't care about the distinction either. Subtransaction XIDs are
4363 * effectively treated as top-level XIDs and in the typical case pg_subtrans
4364 * links are *not* maintained (which does not affect visibility).
4366 * We have room in KnownAssignedXids and in snapshots to hold maxProcs *
4367 * (1 + PGPROC_MAX_CACHED_SUBXIDS) XIDs, so every primary transaction must
4368 * report its subtransaction XIDs in a WAL XLOG_XACT_ASSIGNMENT record at
4369 * least every PGPROC_MAX_CACHED_SUBXIDS. When we receive one of these
4370 * records, we mark the subXIDs as children of the top XID in pg_subtrans,
4371 * and then remove them from KnownAssignedXids. This prevents overflow of
4372 * KnownAssignedXids and snapshots, at the cost that status checks for these
4373 * subXIDs will take a slower path through TransactionIdIsInProgress().
4374 * This means that KnownAssignedXids is not necessarily complete for subXIDs,
4375 * though it should be complete for top-level XIDs; this is the same situation
4376 * that holds with respect to the PGPROC entries in normal running.
4378 * When we throw away subXIDs from KnownAssignedXids, we need to keep track of
4379 * that, similarly to tracking overflow of a PGPROC's subxids array. We do
4380 * that by remembering the lastOverflowedXid, ie the last thrown-away subXID.
4381 * As long as that is within the range of interesting XIDs, we have to assume
4382 * that subXIDs are missing from snapshots. (Note that subXID overflow occurs
4383 * on primary when 65th subXID arrives, whereas on standby it occurs when 64th
4384 * subXID arrives - that is not an error.)
4386 * Should a backend on primary somehow disappear before it can write an abort
4387 * record, then we just leave those XIDs in KnownAssignedXids. They actually
4388 * aborted but we think they were running; the distinction is irrelevant
4389 * because either way any changes done by the transaction are not visible to
4390 * backends in the standby. We prune KnownAssignedXids when
4391 * XLOG_RUNNING_XACTS arrives, to forestall possible overflow of the
4392 * array due to such dead XIDs.
4396 * RecordKnownAssignedTransactionIds
4397 * Record the given XID in KnownAssignedXids, as well as any preceding
4400 * RecordKnownAssignedTransactionIds() should be run for *every* WAL record
4401 * associated with a transaction. Must be called for each record after we
4402 * have executed StartupCLOG() et al, since we must ExtendCLOG() etc..
4404 * Called during recovery in analogy with and in place of GetNewTransactionId()
4407 RecordKnownAssignedTransactionIds(TransactionId xid
)
4409 Assert(standbyState
>= STANDBY_INITIALIZED
);
4410 Assert(TransactionIdIsValid(xid
));
4411 Assert(TransactionIdIsValid(latestObservedXid
));
4413 elog(DEBUG4
, "record known xact %u latestObservedXid %u",
4414 xid
, latestObservedXid
);
4417 * When a newly observed xid arrives, it is frequently the case that it is
4418 * *not* the next xid in sequence. When this occurs, we must treat the
4419 * intervening xids as running also.
4421 if (TransactionIdFollows(xid
, latestObservedXid
))
4423 TransactionId next_expected_xid
;
4426 * Extend subtrans like we do in GetNewTransactionId() during normal
4427 * operation using individual extend steps. Note that we do not need
4428 * to extend clog since its extensions are WAL logged.
4430 * This part has to be done regardless of standbyState since we
4431 * immediately start assigning subtransactions to their toplevel
4434 next_expected_xid
= latestObservedXid
;
4435 while (TransactionIdPrecedes(next_expected_xid
, xid
))
4437 TransactionIdAdvance(next_expected_xid
);
4438 ExtendSUBTRANS(next_expected_xid
);
4440 Assert(next_expected_xid
== xid
);
4443 * If the KnownAssignedXids machinery isn't up yet, there's nothing
4444 * more to do since we don't track assigned xids yet.
4446 if (standbyState
<= STANDBY_INITIALIZED
)
4448 latestObservedXid
= xid
;
4453 * Add (latestObservedXid, xid] onto the KnownAssignedXids array.
4455 next_expected_xid
= latestObservedXid
;
4456 TransactionIdAdvance(next_expected_xid
);
4457 KnownAssignedXidsAdd(next_expected_xid
, xid
, false);
4460 * Now we can advance latestObservedXid
4462 latestObservedXid
= xid
;
4464 /* TransamVariables->nextXid must be beyond any observed xid */
4465 AdvanceNextFullTransactionIdPastXid(latestObservedXid
);
4470 * ExpireTreeKnownAssignedTransactionIds
4471 * Remove the given XIDs from KnownAssignedXids.
4473 * Called during recovery in analogy with and in place of ProcArrayEndTransaction()
4476 ExpireTreeKnownAssignedTransactionIds(TransactionId xid
, int nsubxids
,
4477 TransactionId
*subxids
, TransactionId max_xid
)
4479 Assert(standbyState
>= STANDBY_INITIALIZED
);
4482 * Uses same locking as transaction commit
4484 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
4486 KnownAssignedXidsRemoveTree(xid
, nsubxids
, subxids
);
4488 /* As in ProcArrayEndTransaction, advance latestCompletedXid */
4489 MaintainLatestCompletedXidRecovery(max_xid
);
4491 /* ... and xactCompletionCount */
4492 TransamVariables
->xactCompletionCount
++;
4494 LWLockRelease(ProcArrayLock
);
4498 * ExpireAllKnownAssignedTransactionIds
4499 * Remove all entries in KnownAssignedXids and reset lastOverflowedXid.
4502 ExpireAllKnownAssignedTransactionIds(void)
4504 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
4505 KnownAssignedXidsRemovePreceding(InvalidTransactionId
);
4508 * Reset lastOverflowedXid. Currently, lastOverflowedXid has no use after
4509 * the call of this function. But do this for unification with what
4510 * ExpireOldKnownAssignedTransactionIds() do.
4512 procArray
->lastOverflowedXid
= InvalidTransactionId
;
4513 LWLockRelease(ProcArrayLock
);
4517 * ExpireOldKnownAssignedTransactionIds
4518 * Remove KnownAssignedXids entries preceding the given XID and
4519 * potentially reset lastOverflowedXid.
4522 ExpireOldKnownAssignedTransactionIds(TransactionId xid
)
4524 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
4527 * Reset lastOverflowedXid if we know all transactions that have been
4528 * possibly running are being gone. Not doing so could cause an incorrect
4529 * lastOverflowedXid value, which makes extra snapshots be marked as
4532 if (TransactionIdPrecedes(procArray
->lastOverflowedXid
, xid
))
4533 procArray
->lastOverflowedXid
= InvalidTransactionId
;
4534 KnownAssignedXidsRemovePreceding(xid
);
4535 LWLockRelease(ProcArrayLock
);
4539 * KnownAssignedTransactionIdsIdleMaintenance
4540 * Opportunistically do maintenance work when the startup process
4541 * is about to go idle.
4544 KnownAssignedTransactionIdsIdleMaintenance(void)
4546 KnownAssignedXidsCompress(KAX_STARTUP_PROCESS_IDLE
, false);
4551 * Private module functions to manipulate KnownAssignedXids
4553 * There are 5 main uses of the KnownAssignedXids data structure:
4555 * * backends taking snapshots - all valid XIDs need to be copied out
4556 * * backends seeking to determine presence of a specific XID
4557 * * startup process adding new known-assigned XIDs
4558 * * startup process removing specific XIDs as transactions end
4559 * * startup process pruning array when special WAL records arrive
4561 * This data structure is known to be a hot spot during Hot Standby, so we
4562 * go to some lengths to make these operations as efficient and as concurrent
4565 * The XIDs are stored in an array in sorted order --- TransactionIdPrecedes
4566 * order, to be exact --- to allow binary search for specific XIDs. Note:
4567 * in general TransactionIdPrecedes would not provide a total order, but
4568 * we know that the entries present at any instant should not extend across
4569 * a large enough fraction of XID space to wrap around (the primary would
4570 * shut down for fear of XID wrap long before that happens). So it's OK to
4571 * use TransactionIdPrecedes as a binary-search comparator.
4573 * It's cheap to maintain the sortedness during insertions, since new known
4574 * XIDs are always reported in XID order; we just append them at the right.
4576 * To keep individual deletions cheap, we need to allow gaps in the array.
4577 * This is implemented by marking array elements as valid or invalid using
4578 * the parallel boolean array KnownAssignedXidsValid[]. A deletion is done
4579 * by setting KnownAssignedXidsValid[i] to false, *without* clearing the
4580 * XID entry itself. This preserves the property that the XID entries are
4581 * sorted, so we can do binary searches easily. Periodically we compress
4582 * out the unused entries; that's much cheaper than having to compress the
4583 * array immediately on every deletion.
4585 * The actually valid items in KnownAssignedXids[] and KnownAssignedXidsValid[]
4586 * are those with indexes tail <= i < head; items outside this subscript range
4587 * have unspecified contents. When head reaches the end of the array, we
4588 * force compression of unused entries rather than wrapping around, since
4589 * allowing wraparound would greatly complicate the search logic. We maintain
4590 * an explicit tail pointer so that pruning of old XIDs can be done without
4591 * immediately moving the array contents. In most cases only a small fraction
4592 * of the array contains valid entries at any instant.
4594 * Although only the startup process can ever change the KnownAssignedXids
4595 * data structure, we still need interlocking so that standby backends will
4596 * not observe invalid intermediate states. The convention is that backends
4597 * must hold shared ProcArrayLock to examine the array. To remove XIDs from
4598 * the array, the startup process must hold ProcArrayLock exclusively, for
4599 * the usual transactional reasons (compare commit/abort of a transaction
4600 * during normal running). Compressing unused entries out of the array
4601 * likewise requires exclusive lock. To add XIDs to the array, we just insert
4602 * them into slots to the right of the head pointer and then advance the head
4603 * pointer. This doesn't require any lock at all, but on machines with weak
4604 * memory ordering, we need to be careful that other processors see the array
4605 * element changes before they see the head pointer change. We handle this by
4606 * using memory barriers when reading or writing the head/tail pointers (unless
4607 * the caller holds ProcArrayLock exclusively).
4609 * Algorithmic analysis:
4611 * If we have a maximum of M slots, with N XIDs currently spread across
4612 * S elements then we have N <= S <= M always.
4614 * * Adding a new XID is O(1) and needs no lock (unless compression must
4616 * * Compressing the array is O(S) and requires exclusive lock
4617 * * Removing an XID is O(logS) and requires exclusive lock
4618 * * Taking a snapshot is O(S) and requires shared lock
4619 * * Checking for an XID is O(logS) and requires shared lock
4621 * In comparison, using a hash table for KnownAssignedXids would mean that
4622 * taking snapshots would be O(M). If we can maintain S << M then the
4623 * sorted array technique will deliver significantly faster snapshots.
4624 * If we try to keep S too small then we will spend too much time compressing,
4625 * so there is an optimal point for any workload mix. We use a heuristic to
4626 * decide when to compress the array, though trimming also helps reduce
4627 * frequency of compressing. The heuristic requires us to track the number of
4628 * currently valid XIDs in the array (N). Except in special cases, we'll
4629 * compress when S >= 2N. Bounding S at 2N in turn bounds the time for
4630 * taking a snapshot to be O(N), which it would have to be anyway.
4635 * Compress KnownAssignedXids by shifting valid data down to the start of the
4636 * array, removing any gaps.
4638 * A compression step is forced if "reason" is KAX_NO_SPACE, otherwise
4639 * we do it only if a heuristic indicates it's a good time to do it.
4641 * Compression requires holding ProcArrayLock in exclusive mode.
4642 * Caller must pass haveLock = true if it already holds the lock.
4645 KnownAssignedXidsCompress(KAXCompressReason reason
, bool haveLock
)
4647 ProcArrayStruct
*pArray
= procArray
;
4654 /* Counters for compression heuristics */
4655 static unsigned int transactionEndsCounter
;
4656 static TimestampTz lastCompressTs
;
4658 /* Tuning constants */
4659 #define KAX_COMPRESS_FREQUENCY 128 /* in transactions */
4660 #define KAX_COMPRESS_IDLE_INTERVAL 1000 /* in ms */
4663 * Since only the startup process modifies the head/tail pointers, we
4664 * don't need a lock to read them here.
4666 head
= pArray
->headKnownAssignedXids
;
4667 tail
= pArray
->tailKnownAssignedXids
;
4668 nelements
= head
- tail
;
4671 * If we can choose whether to compress, use a heuristic to avoid
4672 * compressing too often or not often enough. "Compress" here simply
4673 * means moving the values to the beginning of the array, so it is not as
4674 * complex or costly as typical data compression algorithms.
4676 if (nelements
== pArray
->numKnownAssignedXids
)
4679 * When there are no gaps between head and tail, don't bother to
4680 * compress, except in the KAX_NO_SPACE case where we must compress to
4681 * create some space after the head.
4683 if (reason
!= KAX_NO_SPACE
)
4686 else if (reason
== KAX_TRANSACTION_END
)
4689 * Consider compressing only once every so many commits. Frequency
4690 * determined by benchmarks.
4692 if ((transactionEndsCounter
++) % KAX_COMPRESS_FREQUENCY
!= 0)
4696 * Furthermore, compress only if the used part of the array is less
4697 * than 50% full (see comments above).
4699 if (nelements
< 2 * pArray
->numKnownAssignedXids
)
4702 else if (reason
== KAX_STARTUP_PROCESS_IDLE
)
4705 * We're about to go idle for lack of new WAL, so we might as well
4706 * compress. But not too often, to avoid ProcArray lock contention
4709 if (lastCompressTs
!= 0)
4711 TimestampTz compress_after
;
4713 compress_after
= TimestampTzPlusMilliseconds(lastCompressTs
,
4714 KAX_COMPRESS_IDLE_INTERVAL
);
4715 if (GetCurrentTimestamp() < compress_after
)
4720 /* Need to compress, so get the lock if we don't have it. */
4722 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
4725 * We compress the array by reading the valid values from tail to head,
4726 * re-aligning data to 0th element.
4729 for (i
= tail
; i
< head
; i
++)
4731 if (KnownAssignedXidsValid
[i
])
4733 KnownAssignedXids
[compress_index
] = KnownAssignedXids
[i
];
4734 KnownAssignedXidsValid
[compress_index
] = true;
4738 Assert(compress_index
== pArray
->numKnownAssignedXids
);
4740 pArray
->tailKnownAssignedXids
= 0;
4741 pArray
->headKnownAssignedXids
= compress_index
;
4744 LWLockRelease(ProcArrayLock
);
4746 /* Update timestamp for maintenance. No need to hold lock for this. */
4747 lastCompressTs
= GetCurrentTimestamp();
4751 * Add xids into KnownAssignedXids at the head of the array.
4753 * xids from from_xid to to_xid, inclusive, are added to the array.
4755 * If exclusive_lock is true then caller already holds ProcArrayLock in
4756 * exclusive mode, so we need no extra locking here. Else caller holds no
4757 * lock, so we need to be sure we maintain sufficient interlocks against
4758 * concurrent readers. (Only the startup process ever calls this, so no need
4759 * to worry about concurrent writers.)
4762 KnownAssignedXidsAdd(TransactionId from_xid
, TransactionId to_xid
,
4763 bool exclusive_lock
)
4765 ProcArrayStruct
*pArray
= procArray
;
4766 TransactionId next_xid
;
4772 Assert(TransactionIdPrecedesOrEquals(from_xid
, to_xid
));
4775 * Calculate how many array slots we'll need. Normally this is cheap; in
4776 * the unusual case where the XIDs cross the wrap point, we do it the hard
4779 if (to_xid
>= from_xid
)
4780 nxids
= to_xid
- from_xid
+ 1;
4784 next_xid
= from_xid
;
4785 while (TransactionIdPrecedes(next_xid
, to_xid
))
4788 TransactionIdAdvance(next_xid
);
4793 * Since only the startup process modifies the head/tail pointers, we
4794 * don't need a lock to read them here.
4796 head
= pArray
->headKnownAssignedXids
;
4797 tail
= pArray
->tailKnownAssignedXids
;
4799 Assert(head
>= 0 && head
<= pArray
->maxKnownAssignedXids
);
4800 Assert(tail
>= 0 && tail
< pArray
->maxKnownAssignedXids
);
4803 * Verify that insertions occur in TransactionId sequence. Note that even
4804 * if the last existing element is marked invalid, it must still have a
4805 * correctly sequenced XID value.
4808 TransactionIdFollowsOrEquals(KnownAssignedXids
[head
- 1], from_xid
))
4810 KnownAssignedXidsDisplay(LOG
);
4811 elog(ERROR
, "out-of-order XID insertion in KnownAssignedXids");
4815 * If our xids won't fit in the remaining space, compress out free space
4817 if (head
+ nxids
> pArray
->maxKnownAssignedXids
)
4819 KnownAssignedXidsCompress(KAX_NO_SPACE
, exclusive_lock
);
4821 head
= pArray
->headKnownAssignedXids
;
4822 /* note: we no longer care about the tail pointer */
4825 * If it still won't fit then we're out of memory
4827 if (head
+ nxids
> pArray
->maxKnownAssignedXids
)
4828 elog(ERROR
, "too many KnownAssignedXids");
4831 /* Now we can insert the xids into the space starting at head */
4832 next_xid
= from_xid
;
4833 for (i
= 0; i
< nxids
; i
++)
4835 KnownAssignedXids
[head
] = next_xid
;
4836 KnownAssignedXidsValid
[head
] = true;
4837 TransactionIdAdvance(next_xid
);
4841 /* Adjust count of number of valid entries */
4842 pArray
->numKnownAssignedXids
+= nxids
;
4845 * Now update the head pointer. We use a write barrier to ensure that
4846 * other processors see the above array updates before they see the head
4847 * pointer change. The barrier isn't required if we're holding
4848 * ProcArrayLock exclusively.
4850 if (!exclusive_lock
)
4853 pArray
->headKnownAssignedXids
= head
;
4857 * KnownAssignedXidsSearch
4859 * Searches KnownAssignedXids for a specific xid and optionally removes it.
4860 * Returns true if it was found, false if not.
4862 * Caller must hold ProcArrayLock in shared or exclusive mode.
4863 * Exclusive lock must be held for remove = true.
4866 KnownAssignedXidsSearch(TransactionId xid
, bool remove
)
4868 ProcArrayStruct
*pArray
= procArray
;
4873 int result_index
= -1;
4875 tail
= pArray
->tailKnownAssignedXids
;
4876 head
= pArray
->headKnownAssignedXids
;
4879 * Only the startup process removes entries, so we don't need the read
4880 * barrier in that case.
4883 pg_read_barrier(); /* pairs with KnownAssignedXidsAdd */
4886 * Standard binary search. Note we can ignore the KnownAssignedXidsValid
4887 * array here, since even invalid entries will contain sorted XIDs.
4891 while (first
<= last
)
4894 TransactionId mid_xid
;
4896 mid_index
= (first
+ last
) / 2;
4897 mid_xid
= KnownAssignedXids
[mid_index
];
4901 result_index
= mid_index
;
4904 else if (TransactionIdPrecedes(xid
, mid_xid
))
4905 last
= mid_index
- 1;
4907 first
= mid_index
+ 1;
4910 if (result_index
< 0)
4911 return false; /* not in array */
4913 if (!KnownAssignedXidsValid
[result_index
])
4914 return false; /* in array, but invalid */
4918 KnownAssignedXidsValid
[result_index
] = false;
4920 pArray
->numKnownAssignedXids
--;
4921 Assert(pArray
->numKnownAssignedXids
>= 0);
4924 * If we're removing the tail element then advance tail pointer over
4925 * any invalid elements. This will speed future searches.
4927 if (result_index
== tail
)
4930 while (tail
< head
&& !KnownAssignedXidsValid
[tail
])
4934 /* Array is empty, so we can reset both pointers */
4935 pArray
->headKnownAssignedXids
= 0;
4936 pArray
->tailKnownAssignedXids
= 0;
4940 pArray
->tailKnownAssignedXids
= tail
;
4949 * Is the specified XID present in KnownAssignedXids[]?
4951 * Caller must hold ProcArrayLock in shared or exclusive mode.
4954 KnownAssignedXidExists(TransactionId xid
)
4956 Assert(TransactionIdIsValid(xid
));
4958 return KnownAssignedXidsSearch(xid
, false);
4962 * Remove the specified XID from KnownAssignedXids[].
4964 * Caller must hold ProcArrayLock in exclusive mode.
4967 KnownAssignedXidsRemove(TransactionId xid
)
4969 Assert(TransactionIdIsValid(xid
));
4971 elog(DEBUG4
, "remove KnownAssignedXid %u", xid
);
4974 * Note: we cannot consider it an error to remove an XID that's not
4975 * present. We intentionally remove subxact IDs while processing
4976 * XLOG_XACT_ASSIGNMENT, to avoid array overflow. Then those XIDs will be
4977 * removed again when the top-level xact commits or aborts.
4979 * It might be possible to track such XIDs to distinguish this case from
4980 * actual errors, but it would be complicated and probably not worth it.
4981 * So, just ignore the search result.
4983 (void) KnownAssignedXidsSearch(xid
, true);
4987 * KnownAssignedXidsRemoveTree
4988 * Remove xid (if it's not InvalidTransactionId) and all the subxids.
4990 * Caller must hold ProcArrayLock in exclusive mode.
4993 KnownAssignedXidsRemoveTree(TransactionId xid
, int nsubxids
,
4994 TransactionId
*subxids
)
4998 if (TransactionIdIsValid(xid
))
4999 KnownAssignedXidsRemove(xid
);
5001 for (i
= 0; i
< nsubxids
; i
++)
5002 KnownAssignedXidsRemove(subxids
[i
]);
5004 /* Opportunistically compress the array */
5005 KnownAssignedXidsCompress(KAX_TRANSACTION_END
, true);
5009 * Prune KnownAssignedXids up to, but *not* including xid. If xid is invalid
5010 * then clear the whole table.
5012 * Caller must hold ProcArrayLock in exclusive mode.
5015 KnownAssignedXidsRemovePreceding(TransactionId removeXid
)
5017 ProcArrayStruct
*pArray
= procArray
;
5023 if (!TransactionIdIsValid(removeXid
))
5025 elog(DEBUG4
, "removing all KnownAssignedXids");
5026 pArray
->numKnownAssignedXids
= 0;
5027 pArray
->headKnownAssignedXids
= pArray
->tailKnownAssignedXids
= 0;
5031 elog(DEBUG4
, "prune KnownAssignedXids to %u", removeXid
);
5034 * Mark entries invalid starting at the tail. Since array is sorted, we
5035 * can stop as soon as we reach an entry >= removeXid.
5037 tail
= pArray
->tailKnownAssignedXids
;
5038 head
= pArray
->headKnownAssignedXids
;
5040 for (i
= tail
; i
< head
; i
++)
5042 if (KnownAssignedXidsValid
[i
])
5044 TransactionId knownXid
= KnownAssignedXids
[i
];
5046 if (TransactionIdFollowsOrEquals(knownXid
, removeXid
))
5049 if (!StandbyTransactionIdIsPrepared(knownXid
))
5051 KnownAssignedXidsValid
[i
] = false;
5057 pArray
->numKnownAssignedXids
-= count
;
5058 Assert(pArray
->numKnownAssignedXids
>= 0);
5061 * Advance the tail pointer if we've marked the tail item invalid.
5063 for (i
= tail
; i
< head
; i
++)
5065 if (KnownAssignedXidsValid
[i
])
5070 /* Array is empty, so we can reset both pointers */
5071 pArray
->headKnownAssignedXids
= 0;
5072 pArray
->tailKnownAssignedXids
= 0;
5076 pArray
->tailKnownAssignedXids
= i
;
5079 /* Opportunistically compress the array */
5080 KnownAssignedXidsCompress(KAX_PRUNE
, true);
5084 * KnownAssignedXidsGet - Get an array of xids by scanning KnownAssignedXids.
5085 * We filter out anything >= xmax.
5087 * Returns the number of XIDs stored into xarray[]. Caller is responsible
5088 * that array is large enough.
5090 * Caller must hold ProcArrayLock in (at least) shared mode.
5093 KnownAssignedXidsGet(TransactionId
*xarray
, TransactionId xmax
)
5095 TransactionId xtmp
= InvalidTransactionId
;
5097 return KnownAssignedXidsGetAndSetXmin(xarray
, &xtmp
, xmax
);
5101 * KnownAssignedXidsGetAndSetXmin - as KnownAssignedXidsGet, plus
5102 * we reduce *xmin to the lowest xid value seen if not already lower.
5104 * Caller must hold ProcArrayLock in (at least) shared mode.
5107 KnownAssignedXidsGetAndSetXmin(TransactionId
*xarray
, TransactionId
*xmin
,
5116 * Fetch head just once, since it may change while we loop. We can stop
5117 * once we reach the initially seen head, since we are certain that an xid
5118 * cannot enter and then leave the array while we hold ProcArrayLock. We
5119 * might miss newly-added xids, but they should be >= xmax so irrelevant
5122 tail
= procArray
->tailKnownAssignedXids
;
5123 head
= procArray
->headKnownAssignedXids
;
5125 pg_read_barrier(); /* pairs with KnownAssignedXidsAdd */
5127 for (i
= tail
; i
< head
; i
++)
5129 /* Skip any gaps in the array */
5130 if (KnownAssignedXidsValid
[i
])
5132 TransactionId knownXid
= KnownAssignedXids
[i
];
5135 * Update xmin if required. Only the first XID need be checked,
5136 * since the array is sorted.
5139 TransactionIdPrecedes(knownXid
, *xmin
))
5143 * Filter out anything >= xmax, again relying on sorted property
5146 if (TransactionIdIsValid(xmax
) &&
5147 TransactionIdFollowsOrEquals(knownXid
, xmax
))
5150 /* Add knownXid into output array */
5151 xarray
[count
++] = knownXid
;
5159 * Get oldest XID in the KnownAssignedXids array, or InvalidTransactionId
5162 static TransactionId
5163 KnownAssignedXidsGetOldestXmin(void)
5170 * Fetch head just once, since it may change while we loop.
5172 tail
= procArray
->tailKnownAssignedXids
;
5173 head
= procArray
->headKnownAssignedXids
;
5175 pg_read_barrier(); /* pairs with KnownAssignedXidsAdd */
5177 for (i
= tail
; i
< head
; i
++)
5179 /* Skip any gaps in the array */
5180 if (KnownAssignedXidsValid
[i
])
5181 return KnownAssignedXids
[i
];
5184 return InvalidTransactionId
;
5188 * Display KnownAssignedXids to provide debug trail
5190 * Currently this is only called within startup process, so we need no
5193 * Note this is pretty expensive, and much of the expense will be incurred
5194 * even if the elog message will get discarded. It's not currently called
5195 * in any performance-critical places, however, so no need to be tenser.
5198 KnownAssignedXidsDisplay(int trace_level
)
5200 ProcArrayStruct
*pArray
= procArray
;
5207 tail
= pArray
->tailKnownAssignedXids
;
5208 head
= pArray
->headKnownAssignedXids
;
5210 initStringInfo(&buf
);
5212 for (i
= tail
; i
< head
; i
++)
5214 if (KnownAssignedXidsValid
[i
])
5217 appendStringInfo(&buf
, "[%d]=%u ", i
, KnownAssignedXids
[i
]);
5221 elog(trace_level
, "%d KnownAssignedXids (num=%d tail=%d head=%d) %s",
5223 pArray
->numKnownAssignedXids
,
5224 pArray
->tailKnownAssignedXids
,
5225 pArray
->headKnownAssignedXids
,
5232 * KnownAssignedXidsReset
5233 * Resets KnownAssignedXids to be empty
5236 KnownAssignedXidsReset(void)
5238 ProcArrayStruct
*pArray
= procArray
;
5240 LWLockAcquire(ProcArrayLock
, LW_EXCLUSIVE
);
5242 pArray
->numKnownAssignedXids
= 0;
5243 pArray
->tailKnownAssignedXids
= 0;
5244 pArray
->headKnownAssignedXids
= 0;
5246 LWLockRelease(ProcArrayLock
);