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