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