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