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