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