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