PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 the PGPROC and PGXACT structures for all
8  * active backends. Although there are several uses for this, the principal
9  * one is as a means of determining the set of currently running transactions.
10  *
11  * Because of various subtle race conditions it is critical that a backend
12  * hold the correct locks while setting or clearing its MyPgXact->xid field.
13  * See notes in src/backend/access/transam/README.
14  *
15  * The process arrays now also include structures representing prepared
16  * transactions. The xid and subxids fields of these are valid, as are the
17  * myProcLocks lists. They can be distinguished from regular backend PGPROCs
18  * at need by checking for pid == 0.
19  *
20  * During hot standby, we also keep a list of XIDs representing transactions
21  * that are known to be running in the master (or more precisely, were running
22  * as of the current point in the WAL stream). This list is kept in the
23  * KnownAssignedXids array, and is updated by watching the sequence of
24  * arriving XIDs. This is necessary because if we leave those XIDs out of
25  * snapshots taken for standby queries, then they will appear to be already
26  * complete, leading to MVCC failures. Note that in hot standby, the PGPROC
27  * array represents standby processes, which by definition are not running
28  * transactions that have XIDs.
29  *
30  * It is perhaps possible for a backend on the master to terminate without
31  * writing an abort record for its transaction. While that shouldn't really
32  * happen, it would tie up KnownAssignedXids indefinitely, so we protect
33  * ourselves by pruning the array when a valid list of running XIDs arrives.
34  *
35  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
36  * Portions Copyright (c) 1994, Regents of the University of California
37  *
38  *
39  * IDENTIFICATION
40  * src/backend/storage/ipc/procarray.c
41  *
42  *-------------------------------------------------------------------------
43  */
44 #include "postgres.h"
45 
46 #include <signal.h>
47 
48 #include "access/clog.h"
49 #include "access/subtrans.h"
50 #include "access/transam.h"
51 #include "access/twophase.h"
52 #include "access/xact.h"
53 #include "access/xlog.h"
54 #include "catalog/catalog.h"
55 #include "miscadmin.h"
56 #include "storage/proc.h"
57 #include "storage/procarray.h"
58 #include "storage/spin.h"
59 #include "utils/builtins.h"
60 #include "utils/rel.h"
61 #include "utils/snapmgr.h"
62 
63 
64 /* Our shared memory area */
65 typedef struct ProcArrayStruct
66 {
67  int numProcs; /* number of valid procs entries */
68  int maxProcs; /* allocated size of procs array */
69 
70  /*
71  * Known assigned XIDs handling
72  */
73  int maxKnownAssignedXids; /* allocated size of array */
74  int numKnownAssignedXids; /* current # of valid entries */
75  int tailKnownAssignedXids; /* index of oldest valid element */
76  int headKnownAssignedXids; /* index of newest element, + 1 */
77  slock_t known_assigned_xids_lck; /* protects head/tail pointers */
78 
79  /*
80  * Highest subxid that has been removed from KnownAssignedXids array to
81  * prevent overflow; or InvalidTransactionId if none. We track this for
82  * similar reasons to tracking overflowing cached subxids in PGXACT
83  * entries. Must hold exclusive ProcArrayLock to change this, and shared
84  * lock to read it.
85  */
87 
88  /* oldest xmin of any replication slot */
90  /* oldest catalog xmin of any replication slot */
92 
93  /* indexes into allPgXact[], has PROCARRAY_MAXPROCS entries */
94  int pgprocnos[FLEXIBLE_ARRAY_MEMBER];
96 
98 
99 static PGPROC *allProcs;
101 
102 /*
103  * Bookkeeping for tracking emulated transactions in recovery
104  */
108 
109 /*
110  * If we're in STANDBY_SNAPSHOT_PENDING state, standbySnapshotPendingXmin is
111  * the highest xid that might still be running that we don't have in
112  * KnownAssignedXids.
113  */
115 
116 #ifdef XIDCACHE_DEBUG
117 
118 /* counters for XidCache measurement */
119 static long xc_by_recent_xmin = 0;
120 static long xc_by_known_xact = 0;
121 static long xc_by_my_xact = 0;
122 static long xc_by_latest_xid = 0;
123 static long xc_by_main_xid = 0;
124 static long xc_by_child_xid = 0;
125 static long xc_by_known_assigned = 0;
126 static long xc_no_overflow = 0;
127 static long xc_slow_answer = 0;
128 
129 #define xc_by_recent_xmin_inc() (xc_by_recent_xmin++)
130 #define xc_by_known_xact_inc() (xc_by_known_xact++)
131 #define xc_by_my_xact_inc() (xc_by_my_xact++)
132 #define xc_by_latest_xid_inc() (xc_by_latest_xid++)
133 #define xc_by_main_xid_inc() (xc_by_main_xid++)
134 #define xc_by_child_xid_inc() (xc_by_child_xid++)
135 #define xc_by_known_assigned_inc() (xc_by_known_assigned++)
136 #define xc_no_overflow_inc() (xc_no_overflow++)
137 #define xc_slow_answer_inc() (xc_slow_answer++)
138 
139 static void DisplayXidCache(void);
140 #else /* !XIDCACHE_DEBUG */
141 
142 #define xc_by_recent_xmin_inc() ((void) 0)
143 #define xc_by_known_xact_inc() ((void) 0)
144 #define xc_by_my_xact_inc() ((void) 0)
145 #define xc_by_latest_xid_inc() ((void) 0)
146 #define xc_by_main_xid_inc() ((void) 0)
147 #define xc_by_child_xid_inc() ((void) 0)
148 #define xc_by_known_assigned_inc() ((void) 0)
149 #define xc_no_overflow_inc() ((void) 0)
150 #define xc_slow_answer_inc() ((void) 0)
151 #endif /* XIDCACHE_DEBUG */
152 
153 /* Primitives for KnownAssignedXids array handling for standby */
154 static void KnownAssignedXidsCompress(bool force);
155 static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid,
156  bool exclusive_lock);
157 static bool KnownAssignedXidsSearch(TransactionId xid, bool remove);
158 static bool KnownAssignedXidExists(TransactionId xid);
159 static void KnownAssignedXidsRemove(TransactionId xid);
160 static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids,
161  TransactionId *subxids);
163 static int KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax);
165  TransactionId *xmin,
166  TransactionId xmax);
168 static void KnownAssignedXidsDisplay(int trace_level);
169 static void KnownAssignedXidsReset(void);
170 static inline void ProcArrayEndTransactionInternal(PGPROC *proc,
171  PGXACT *pgxact, TransactionId latestXid);
172 static void ProcArrayGroupClearXid(PGPROC *proc, TransactionId latestXid);
173 
174 /*
175  * Report shared-memory space needed by CreateSharedProcArray.
176  */
177 Size
179 {
180  Size size;
181 
182  /* Size of the ProcArray structure itself */
183 #define PROCARRAY_MAXPROCS (MaxBackends + max_prepared_xacts)
184 
185  size = offsetof(ProcArrayStruct, pgprocnos);
186  size = add_size(size, mul_size(sizeof(int), PROCARRAY_MAXPROCS));
187 
188  /*
189  * During Hot Standby processing we have a data structure called
190  * KnownAssignedXids, created in shared memory. Local data structures are
191  * also created in various backends during GetSnapshotData(),
192  * TransactionIdIsInProgress() and GetRunningTransactionData(). All of the
193  * main structures created in those functions must be identically sized,
194  * since we may at times copy the whole of the data structures around. We
195  * refer to this size as TOTAL_MAX_CACHED_SUBXIDS.
196  *
197  * Ideally we'd only create this structure if we were actually doing hot
198  * standby in the current run, but we don't know that yet at the time
199  * shared memory is being set up.
200  */
201 #define TOTAL_MAX_CACHED_SUBXIDS \
202  ((PGPROC_MAX_CACHED_SUBXIDS + 1) * PROCARRAY_MAXPROCS)
203 
204  if (EnableHotStandby)
205  {
206  size = add_size(size,
207  mul_size(sizeof(TransactionId),
209  size = add_size(size,
210  mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS));
211  }
212 
213  return size;
214 }
215 
216 /*
217  * Initialize the shared PGPROC array during postmaster startup.
218  */
219 void
221 {
222  bool found;
223 
224  /* Create or attach to the ProcArray shared structure */
225  procArray = (ProcArrayStruct *)
226  ShmemInitStruct("Proc Array",
227  add_size(offsetof(ProcArrayStruct, pgprocnos),
228  mul_size(sizeof(int),
230  &found);
231 
232  if (!found)
233  {
234  /*
235  * We're the first - initialize.
236  */
237  procArray->numProcs = 0;
238  procArray->maxProcs = PROCARRAY_MAXPROCS;
241  procArray->numKnownAssignedXids = 0;
242  procArray->tailKnownAssignedXids = 0;
243  procArray->headKnownAssignedXids = 0;
246  }
247 
248  allProcs = ProcGlobal->allProcs;
249  allPgXact = ProcGlobal->allPgXact;
250 
251  /* Create or attach to the KnownAssignedXids arrays too, if needed */
252  if (EnableHotStandby)
253  {
255  ShmemInitStruct("KnownAssignedXids",
256  mul_size(sizeof(TransactionId),
258  &found);
259  KnownAssignedXidsValid = (bool *)
260  ShmemInitStruct("KnownAssignedXidsValid",
261  mul_size(sizeof(bool), TOTAL_MAX_CACHED_SUBXIDS),
262  &found);
263  }
264 
265  /* Register and initialize fields of ProcLWLockTranche */
267 }
268 
269 /*
270  * Add the specified PGPROC to the shared array.
271  */
272 void
274 {
275  ProcArrayStruct *arrayP = procArray;
276  int index;
277 
278  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
279 
280  if (arrayP->numProcs >= arrayP->maxProcs)
281  {
282  /*
283  * Oops, no room. (This really shouldn't happen, since there is a
284  * fixed supply of PGPROC structs too, and so we should have failed
285  * earlier.)
286  */
287  LWLockRelease(ProcArrayLock);
288  ereport(FATAL,
289  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
290  errmsg("sorry, too many clients already")));
291  }
292 
293  /*
294  * Keep the procs array sorted by (PGPROC *) so that we can utilize
295  * locality of references much better. This is useful while traversing the
296  * ProcArray because there is an increased likelihood of finding the next
297  * PGPROC structure in the cache.
298  *
299  * Since the occurrence of adding/removing a proc is much lower than the
300  * access to the ProcArray itself, the overhead should be marginal
301  */
302  for (index = 0; index < arrayP->numProcs; index++)
303  {
304  /*
305  * If we are the first PGPROC or if we have found our right position
306  * in the array, break
307  */
308  if ((arrayP->pgprocnos[index] == -1) || (arrayP->pgprocnos[index] > proc->pgprocno))
309  break;
310  }
311 
312  memmove(&arrayP->pgprocnos[index + 1], &arrayP->pgprocnos[index],
313  (arrayP->numProcs - index) * sizeof(int));
314  arrayP->pgprocnos[index] = proc->pgprocno;
315  arrayP->numProcs++;
316 
317  LWLockRelease(ProcArrayLock);
318 }
319 
320 /*
321  * Remove the specified PGPROC from the shared array.
322  *
323  * When latestXid is a valid XID, we are removing a live 2PC gxact from the
324  * array, and thus causing it to appear as "not running" anymore. In this
325  * case we must advance latestCompletedXid. (This is essentially the same
326  * as ProcArrayEndTransaction followed by removal of the PGPROC, but we take
327  * the ProcArrayLock only once, and don't damage the content of the PGPROC;
328  * twophase.c depends on the latter.)
329  */
330 void
332 {
333  ProcArrayStruct *arrayP = procArray;
334  int index;
335 
336 #ifdef XIDCACHE_DEBUG
337  /* dump stats at backend shutdown, but not prepared-xact end */
338  if (proc->pid != 0)
339  DisplayXidCache();
340 #endif
341 
342  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
343 
344  if (TransactionIdIsValid(latestXid))
345  {
346  Assert(TransactionIdIsValid(allPgXact[proc->pgprocno].xid));
347 
348  /* Advance global latestCompletedXid while holding the lock */
350  latestXid))
352  }
353  else
354  {
355  /* Shouldn't be trying to remove a live transaction here */
356  Assert(!TransactionIdIsValid(allPgXact[proc->pgprocno].xid));
357  }
358 
359  for (index = 0; index < arrayP->numProcs; index++)
360  {
361  if (arrayP->pgprocnos[index] == proc->pgprocno)
362  {
363  /* Keep the PGPROC array sorted. See notes above */
364  memmove(&arrayP->pgprocnos[index], &arrayP->pgprocnos[index + 1],
365  (arrayP->numProcs - index - 1) * sizeof(int));
366  arrayP->pgprocnos[arrayP->numProcs - 1] = -1; /* for debugging */
367  arrayP->numProcs--;
368  LWLockRelease(ProcArrayLock);
369  return;
370  }
371  }
372 
373  /* Oops */
374  LWLockRelease(ProcArrayLock);
375 
376  elog(LOG, "failed to find proc %p in ProcArray", proc);
377 }
378 
379 
380 /*
381  * ProcArrayEndTransaction -- mark a transaction as no longer running
382  *
383  * This is used interchangeably for commit and abort cases. The transaction
384  * commit/abort must already be reported to WAL and pg_xact.
385  *
386  * proc is currently always MyProc, but we pass it explicitly for flexibility.
387  * latestXid is the latest Xid among the transaction's main XID and
388  * subtransactions, or InvalidTransactionId if it has no XID. (We must ask
389  * the caller to pass latestXid, instead of computing it from the PGPROC's
390  * contents, because the subxid information in the PGPROC might be
391  * incomplete.)
392  */
393 void
395 {
396  PGXACT *pgxact = &allPgXact[proc->pgprocno];
397 
398  if (TransactionIdIsValid(latestXid))
399  {
400  /*
401  * We must lock ProcArrayLock while clearing our advertised XID, so
402  * that we do not exit the set of "running" transactions while someone
403  * else is taking a snapshot. See discussion in
404  * src/backend/access/transam/README.
405  */
406  Assert(TransactionIdIsValid(allPgXact[proc->pgprocno].xid));
407 
408  /*
409  * If we can immediately acquire ProcArrayLock, we clear our own XID
410  * and release the lock. If not, use group XID clearing to improve
411  * efficiency.
412  */
413  if (LWLockConditionalAcquire(ProcArrayLock, LW_EXCLUSIVE))
414  {
415  ProcArrayEndTransactionInternal(proc, pgxact, latestXid);
416  LWLockRelease(ProcArrayLock);
417  }
418  else
419  ProcArrayGroupClearXid(proc, latestXid);
420  }
421  else
422  {
423  /*
424  * If we have no XID, we don't need to lock, since we won't affect
425  * anyone else's calculation of a snapshot. We might change their
426  * estimate of global xmin, but that's OK.
427  */
428  Assert(!TransactionIdIsValid(allPgXact[proc->pgprocno].xid));
429 
431  pgxact->xmin = InvalidTransactionId;
432  /* must be cleared with xid/xmin: */
434  pgxact->delayChkpt = false; /* be sure this is cleared in abort */
435  proc->recoveryConflictPending = false;
436 
437  Assert(pgxact->nxids == 0);
438  Assert(pgxact->overflowed == false);
439  }
440 }
441 
442 /*
443  * Mark a write transaction as no longer running.
444  *
445  * We don't do any locking here; caller must handle that.
446  */
447 static inline void
449  TransactionId latestXid)
450 {
451  pgxact->xid = InvalidTransactionId;
453  pgxact->xmin = InvalidTransactionId;
454  /* must be cleared with xid/xmin: */
456  pgxact->delayChkpt = false; /* be sure this is cleared in abort */
457  proc->recoveryConflictPending = false;
458 
459  /* Clear the subtransaction-XID cache too while holding the lock */
460  pgxact->nxids = 0;
461  pgxact->overflowed = false;
462 
463  /* Also advance global latestCompletedXid while holding the lock */
465  latestXid))
467 }
468 
469 /*
470  * ProcArrayGroupClearXid -- group XID clearing
471  *
472  * When we cannot immediately acquire ProcArrayLock in exclusive mode at
473  * commit time, add ourselves to a list of processes that need their XIDs
474  * cleared. The first process to add itself to the list will acquire
475  * ProcArrayLock in exclusive mode and perform ProcArrayEndTransactionInternal
476  * on behalf of all group members. This avoids a great deal of contention
477  * around ProcArrayLock when many processes are trying to commit at once,
478  * since the lock need not be repeatedly handed off from one committing
479  * process to the next.
480  */
481 static void
483 {
484  volatile PROC_HDR *procglobal = ProcGlobal;
485  uint32 nextidx;
486  uint32 wakeidx;
487 
488  /* We should definitely have an XID to clear. */
489  Assert(TransactionIdIsValid(allPgXact[proc->pgprocno].xid));
490 
491  /* Add ourselves to the list of processes needing a group XID clear. */
492  proc->procArrayGroupMember = true;
493  proc->procArrayGroupMemberXid = latestXid;
494  while (true)
495  {
496  nextidx = pg_atomic_read_u32(&procglobal->procArrayGroupFirst);
497  pg_atomic_write_u32(&proc->procArrayGroupNext, nextidx);
498 
500  &nextidx,
501  (uint32) proc->pgprocno))
502  break;
503  }
504 
505  /*
506  * If the list was not empty, the leader will clear our XID. It is
507  * impossible to have followers without a leader because the first process
508  * that has added itself to the list will always have nextidx as
509  * INVALID_PGPROCNO.
510  */
511  if (nextidx != INVALID_PGPROCNO)
512  {
513  int extraWaits = 0;
514 
515  /* Sleep until the leader clears our XID. */
516  for (;;)
517  {
518  /* acts as a read barrier */
519  PGSemaphoreLock(proc->sem);
520  if (!proc->procArrayGroupMember)
521  break;
522  extraWaits++;
523  }
524 
526 
527  /* Fix semaphore count for any absorbed wakeups */
528  while (extraWaits-- > 0)
529  PGSemaphoreUnlock(proc->sem);
530  return;
531  }
532 
533  /* We are the leader. Acquire the lock on behalf of everyone. */
534  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
535 
536  /*
537  * Now that we've got the lock, clear the list of processes waiting for
538  * group XID clearing, saving a pointer to the head of the list. Trying
539  * to pop elements one at a time could lead to an ABA problem.
540  */
541  while (true)
542  {
543  nextidx = pg_atomic_read_u32(&procglobal->procArrayGroupFirst);
545  &nextidx,
547  break;
548  }
549 
550  /* Remember head of list so we can perform wakeups after dropping lock. */
551  wakeidx = nextidx;
552 
553  /* Walk the list and clear all XIDs. */
554  while (nextidx != INVALID_PGPROCNO)
555  {
556  PGPROC *proc = &allProcs[nextidx];
557  PGXACT *pgxact = &allPgXact[nextidx];
558 
560 
561  /* Move to next proc in list. */
562  nextidx = pg_atomic_read_u32(&proc->procArrayGroupNext);
563  }
564 
565  /* We're done with the lock now. */
566  LWLockRelease(ProcArrayLock);
567 
568  /*
569  * Now that we've released the lock, go back and wake everybody up. We
570  * don't do this under the lock so as to keep lock hold times to a
571  * minimum. The system calls we need to perform to wake other processes
572  * up are probably much slower than the simple memory writes we did while
573  * holding the lock.
574  */
575  while (wakeidx != INVALID_PGPROCNO)
576  {
577  PGPROC *proc = &allProcs[wakeidx];
578 
579  wakeidx = pg_atomic_read_u32(&proc->procArrayGroupNext);
581 
582  /* ensure all previous writes are visible before follower continues. */
584 
585  proc->procArrayGroupMember = false;
586 
587  if (proc != MyProc)
588  PGSemaphoreUnlock(proc->sem);
589  }
590 }
591 
592 /*
593  * ProcArrayClearTransaction -- clear the transaction fields
594  *
595  * This is used after successfully preparing a 2-phase transaction. We are
596  * not actually reporting the transaction's XID as no longer running --- it
597  * will still appear as running because the 2PC's gxact is in the ProcArray
598  * too. We just have to clear out our own PGXACT.
599  */
600 void
602 {
603  PGXACT *pgxact = &allPgXact[proc->pgprocno];
604 
605  /*
606  * We can skip locking ProcArrayLock here, because this action does not
607  * actually change anyone's view of the set of running XIDs: our entry is
608  * duplicate with the gxact that has already been inserted into the
609  * ProcArray.
610  */
611  pgxact->xid = InvalidTransactionId;
613  pgxact->xmin = InvalidTransactionId;
614  proc->recoveryConflictPending = false;
615 
616  /* redundant, but just in case */
618  pgxact->delayChkpt = false;
619 
620  /* Clear the subtransaction-XID cache too */
621  pgxact->nxids = 0;
622  pgxact->overflowed = false;
623 }
624 
625 /*
626  * ProcArrayInitRecovery -- initialize recovery xid mgmt environment
627  *
628  * Remember up to where the startup process initialized the CLOG and subtrans
629  * so we can ensure it's initialized gaplessly up to the point where necessary
630  * while in recovery.
631  */
632 void
634 {
636  Assert(TransactionIdIsNormal(initializedUptoXID));
637 
638  /*
639  * we set latestObservedXid to the xid SUBTRANS has been initialized up
640  * to, so we can extend it from that point onwards in
641  * RecordKnownAssignedTransactionIds, and when we get consistent in
642  * ProcArrayApplyRecoveryInfo().
643  */
644  latestObservedXid = initializedUptoXID;
646 }
647 
648 /*
649  * ProcArrayApplyRecoveryInfo -- apply recovery info about xids
650  *
651  * Takes us through 3 states: Initialized, Pending and Ready.
652  * Normal case is to go all the way to Ready straight away, though there
653  * are atypical cases where we need to take it in steps.
654  *
655  * Use the data about running transactions on master to create the initial
656  * state of KnownAssignedXids. We also use these records to regularly prune
657  * KnownAssignedXids because we know it is possible that some transactions
658  * with FATAL errors fail to write abort records, which could cause eventual
659  * overflow.
660  *
661  * See comments for LogStandbySnapshot().
662  */
663 void
665 {
666  TransactionId *xids;
667  int nxids;
668  TransactionId nextXid;
669  int i;
670 
675 
676  /*
677  * Remove stale transactions, if any.
678  */
680 
681  /*
682  * Remove stale locks, if any.
683  *
684  * Locks are always assigned to the toplevel xid so we don't need to care
685  * about subxcnt/subxids (and by extension not about ->suboverflowed).
686  */
687  StandbyReleaseOldLocks(running->xcnt, running->xids);
688 
689  /*
690  * If our snapshot is already valid, nothing else to do...
691  */
693  return;
694 
695  /*
696  * If our initial RunningTransactionsData had an overflowed snapshot then
697  * we knew we were missing some subxids from our snapshot. If we continue
698  * to see overflowed snapshots then we might never be able to start up, so
699  * we make another test to see if our snapshot is now valid. We know that
700  * the missing subxids are equal to or earlier than nextXid. After we
701  * initialise we continue to apply changes during recovery, so once the
702  * oldestRunningXid is later than the nextXid from the initial snapshot we
703  * know that we no longer have missing information and can mark the
704  * snapshot as valid.
705  */
707  {
708  /*
709  * If the snapshot isn't overflowed or if its empty we can reset our
710  * pending state and use this snapshot instead.
711  */
712  if (!running->subxid_overflow || running->xcnt == 0)
713  {
714  /*
715  * If we have already collected known assigned xids, we need to
716  * throw them away before we apply the recovery snapshot.
717  */
720  }
721  else
722  {
724  running->oldestRunningXid))
725  {
728  "recovery snapshots are now enabled");
729  }
730  else
732  "recovery snapshot waiting for non-overflowed snapshot or "
733  "until oldest active xid on standby is at least %u (now %u)",
735  running->oldestRunningXid);
736  return;
737  }
738  }
739 
741 
742  /*
743  * OK, we need to initialise from the RunningTransactionsData record.
744  *
745  * NB: this can be reached at least twice, so make sure new code can deal
746  * with that.
747  */
748 
749  /*
750  * Nobody else is running yet, but take locks anyhow
751  */
752  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
753 
754  /*
755  * KnownAssignedXids is sorted so we cannot just add the xids, we have to
756  * sort them first.
757  *
758  * Some of the new xids are top-level xids and some are subtransactions.
759  * We don't call SubtransSetParent because it doesn't matter yet. If we
760  * aren't overflowed then all xids will fit in snapshot and so we don't
761  * need subtrans. If we later overflow, an xid assignment record will add
762  * xids to subtrans. If RunningXacts is overflowed then we don't have
763  * enough information to correctly update subtrans anyway.
764  */
765 
766  /*
767  * Allocate a temporary array to avoid modifying the array passed as
768  * argument.
769  */
770  xids = palloc(sizeof(TransactionId) * (running->xcnt + running->subxcnt));
771 
772  /*
773  * Add to the temp array any xids which have not already completed.
774  */
775  nxids = 0;
776  for (i = 0; i < running->xcnt + running->subxcnt; i++)
777  {
778  TransactionId xid = running->xids[i];
779 
780  /*
781  * The running-xacts snapshot can contain xids that were still visible
782  * in the procarray when the snapshot was taken, but were already
783  * WAL-logged as completed. They're not running anymore, so ignore
784  * them.
785  */
787  continue;
788 
789  xids[nxids++] = xid;
790  }
791 
792  if (nxids > 0)
793  {
794  if (procArray->numKnownAssignedXids != 0)
795  {
796  LWLockRelease(ProcArrayLock);
797  elog(ERROR, "KnownAssignedXids is not empty");
798  }
799 
800  /*
801  * Sort the array so that we can add them safely into
802  * KnownAssignedXids.
803  */
804  qsort(xids, nxids, sizeof(TransactionId), xidComparator);
805 
806  /*
807  * Add the sorted snapshot into KnownAssignedXids
808  */
809  for (i = 0; i < nxids; i++)
810  KnownAssignedXidsAdd(xids[i], xids[i], true);
811 
813  }
814 
815  pfree(xids);
816 
817  /*
818  * latestObservedXid is at least set to the point where SUBTRANS was
819  * started up to (c.f. ProcArrayInitRecovery()) or to the biggest xid
820  * RecordKnownAssignedTransactionIds() was called for. Initialize
821  * subtrans from thereon, up to nextXid - 1.
822  *
823  * We need to duplicate parts of RecordKnownAssignedTransactionId() here,
824  * because we've just added xids to the known assigned xids machinery that
825  * haven't gone through RecordKnownAssignedTransactionId().
826  */
830  {
833  }
834  TransactionIdRetreat(latestObservedXid); /* = running->nextXid - 1 */
835 
836  /* ----------
837  * Now we've got the running xids we need to set the global values that
838  * are used to track snapshots as they evolve further.
839  *
840  * - latestCompletedXid which will be the xmax for snapshots
841  * - lastOverflowedXid which shows whether snapshots overflow
842  * - nextXid
843  *
844  * If the snapshot overflowed, then we still initialise with what we know,
845  * but the recovery snapshot isn't fully valid yet because we know there
846  * are some subxids missing. We don't know the specific subxids that are
847  * missing, so conservatively assume the last one is latestObservedXid.
848  * ----------
849  */
850  if (running->subxid_overflow)
851  {
853 
856  }
857  else
858  {
860 
862  }
863 
864  /*
865  * If a transaction wrote a commit record in the gap between taking and
866  * logging the snapshot then latestCompletedXid may already be higher than
867  * the value from the snapshot, so check before we use the incoming value.
868  */
870  running->latestCompletedXid))
872 
874 
875  LWLockRelease(ProcArrayLock);
876 
877  /*
878  * ShmemVariableCache->nextXid must be beyond any observed xid.
879  *
880  * We don't expect anyone else to modify nextXid, hence we don't need to
881  * hold a lock while examining it. We still acquire the lock to modify
882  * it, though.
883  */
884  nextXid = latestObservedXid;
885  TransactionIdAdvance(nextXid);
887  {
888  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
889  ShmemVariableCache->nextXid = nextXid;
890  LWLockRelease(XidGenLock);
891  }
892 
894 
897  elog(trace_recovery(DEBUG1), "recovery snapshots are now enabled");
898  else
900  "recovery snapshot waiting for non-overflowed snapshot or "
901  "until oldest active xid on standby is at least %u (now %u)",
903  running->oldestRunningXid);
904 }
905 
906 /*
907  * ProcArrayApplyXidAssignment
908  * Process an XLOG_XACT_ASSIGNMENT WAL record
909  */
910 void
912  int nsubxids, TransactionId *subxids)
913 {
914  TransactionId max_xid;
915  int i;
916 
918 
919  max_xid = TransactionIdLatest(topxid, nsubxids, subxids);
920 
921  /*
922  * Mark all the subtransactions as observed.
923  *
924  * NOTE: This will fail if the subxid contains too many previously
925  * unobserved xids to fit into known-assigned-xids. That shouldn't happen
926  * as the code stands, because xid-assignment records should never contain
927  * more than PGPROC_MAX_CACHED_SUBXIDS entries.
928  */
930 
931  /*
932  * Notice that we update pg_subtrans with the top-level xid, rather than
933  * the parent xid. This is a difference between normal processing and
934  * recovery, yet is still correct in all cases. The reason is that
935  * subtransaction commit is not marked in clog until commit processing, so
936  * all aborted subtransactions have already been clearly marked in clog.
937  * As a result we are able to refer directly to the top-level
938  * transaction's state rather than skipping through all the intermediate
939  * states in the subtransaction tree. This should be the first time we
940  * have attempted to SubTransSetParent().
941  */
942  for (i = 0; i < nsubxids; i++)
943  SubTransSetParent(subxids[i], topxid, false);
944 
945  /* KnownAssignedXids isn't maintained yet, so we're done for now */
947  return;
948 
949  /*
950  * Uses same locking as transaction commit
951  */
952  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
953 
954  /*
955  * Remove subxids from known-assigned-xacts.
956  */
958 
959  /*
960  * Advance lastOverflowedXid to be at least the last of these subxids.
961  */
962  if (TransactionIdPrecedes(procArray->lastOverflowedXid, max_xid))
963  procArray->lastOverflowedXid = max_xid;
964 
965  LWLockRelease(ProcArrayLock);
966 }
967 
968 /*
969  * TransactionIdIsInProgress -- is given transaction running in some backend
970  *
971  * Aside from some shortcuts such as checking RecentXmin and our own Xid,
972  * there are four possibilities for finding a running transaction:
973  *
974  * 1. The given Xid is a main transaction Id. We will find this out cheaply
975  * by looking at the PGXACT struct for each backend.
976  *
977  * 2. The given Xid is one of the cached subxact Xids in the PGPROC array.
978  * We can find this out cheaply too.
979  *
980  * 3. In Hot Standby mode, we must search the KnownAssignedXids list to see
981  * if the Xid is running on the master.
982  *
983  * 4. Search the SubTrans tree to find the Xid's topmost parent, and then see
984  * if that is running according to PGXACT or KnownAssignedXids. This is the
985  * slowest way, but sadly it has to be done always if the others failed,
986  * unless we see that the cached subxact sets are complete (none have
987  * overflowed).
988  *
989  * ProcArrayLock has to be held while we do 1, 2, 3. If we save the top Xids
990  * while doing 1 and 3, we can release the ProcArrayLock while we do 4.
991  * This buys back some concurrency (and we can't retrieve the main Xids from
992  * PGXACT again anyway; see GetNewTransactionId).
993  */
994 bool
996 {
997  static TransactionId *xids = NULL;
998  int nxids = 0;
999  ProcArrayStruct *arrayP = procArray;
1000  TransactionId topxid;
1001  int i,
1002  j;
1003 
1004  /*
1005  * Don't bother checking a transaction older than RecentXmin; it could not
1006  * possibly still be running. (Note: in particular, this guarantees that
1007  * we reject InvalidTransactionId, FrozenTransactionId, etc as not
1008  * running.)
1009  */
1011  {
1013  return false;
1014  }
1015 
1016  /*
1017  * We may have just checked the status of this transaction, so if it is
1018  * already known to be completed, we can fall out without any access to
1019  * shared memory.
1020  */
1022  {
1024  return false;
1025  }
1026 
1027  /*
1028  * Also, we can handle our own transaction (and subtransactions) without
1029  * any access to shared memory.
1030  */
1032  {
1034  return true;
1035  }
1036 
1037  /*
1038  * If first time through, get workspace to remember main XIDs in. We
1039  * malloc it permanently to avoid repeated palloc/pfree overhead.
1040  */
1041  if (xids == NULL)
1042  {
1043  /*
1044  * In hot standby mode, reserve enough space to hold all xids in the
1045  * known-assigned list. If we later finish recovery, we no longer need
1046  * the bigger array, but we don't bother to shrink it.
1047  */
1048  int maxxids = RecoveryInProgress() ? TOTAL_MAX_CACHED_SUBXIDS : arrayP->maxProcs;
1049 
1050  xids = (TransactionId *) malloc(maxxids * sizeof(TransactionId));
1051  if (xids == NULL)
1052  ereport(ERROR,
1053  (errcode(ERRCODE_OUT_OF_MEMORY),
1054  errmsg("out of memory")));
1055  }
1056 
1057  LWLockAcquire(ProcArrayLock, LW_SHARED);
1058 
1059  /*
1060  * Now that we have the lock, we can check latestCompletedXid; if the
1061  * target Xid is after that, it's surely still running.
1062  */
1064  {
1065  LWLockRelease(ProcArrayLock);
1067  return true;
1068  }
1069 
1070  /* No shortcuts, gotta grovel through the array */
1071  for (i = 0; i < arrayP->numProcs; i++)
1072  {
1073  int pgprocno = arrayP->pgprocnos[i];
1074  volatile PGPROC *proc = &allProcs[pgprocno];
1075  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1076  TransactionId pxid;
1077 
1078  /* Ignore my own proc --- dealt with it above */
1079  if (proc == MyProc)
1080  continue;
1081 
1082  /* Fetch xid just once - see GetNewTransactionId */
1083  pxid = pgxact->xid;
1084 
1085  if (!TransactionIdIsValid(pxid))
1086  continue;
1087 
1088  /*
1089  * Step 1: check the main Xid
1090  */
1091  if (TransactionIdEquals(pxid, xid))
1092  {
1093  LWLockRelease(ProcArrayLock);
1095  return true;
1096  }
1097 
1098  /*
1099  * We can ignore main Xids that are younger than the target Xid, since
1100  * the target could not possibly be their child.
1101  */
1102  if (TransactionIdPrecedes(xid, pxid))
1103  continue;
1104 
1105  /*
1106  * Step 2: check the cached child-Xids arrays
1107  */
1108  for (j = pgxact->nxids - 1; j >= 0; j--)
1109  {
1110  /* Fetch xid just once - see GetNewTransactionId */
1111  TransactionId cxid = proc->subxids.xids[j];
1112 
1113  if (TransactionIdEquals(cxid, xid))
1114  {
1115  LWLockRelease(ProcArrayLock);
1117  return true;
1118  }
1119  }
1120 
1121  /*
1122  * Save the main Xid for step 4. We only need to remember main Xids
1123  * that have uncached children. (Note: there is no race condition
1124  * here because the overflowed flag cannot be cleared, only set, while
1125  * we hold ProcArrayLock. So we can't miss an Xid that we need to
1126  * worry about.)
1127  */
1128  if (pgxact->overflowed)
1129  xids[nxids++] = pxid;
1130  }
1131 
1132  /*
1133  * Step 3: in hot standby mode, check the known-assigned-xids list. XIDs
1134  * in the list must be treated as running.
1135  */
1136  if (RecoveryInProgress())
1137  {
1138  /* none of the PGXACT entries should have XIDs in hot standby mode */
1139  Assert(nxids == 0);
1140 
1141  if (KnownAssignedXidExists(xid))
1142  {
1143  LWLockRelease(ProcArrayLock);
1145  return true;
1146  }
1147 
1148  /*
1149  * If the KnownAssignedXids overflowed, we have to check pg_subtrans
1150  * too. Fetch all xids from KnownAssignedXids that are lower than
1151  * xid, since if xid is a subtransaction its parent will always have a
1152  * lower value. Note we will collect both main and subXIDs here, but
1153  * there's no help for it.
1154  */
1155  if (TransactionIdPrecedesOrEquals(xid, procArray->lastOverflowedXid))
1156  nxids = KnownAssignedXidsGet(xids, xid);
1157  }
1158 
1159  LWLockRelease(ProcArrayLock);
1160 
1161  /*
1162  * If none of the relevant caches overflowed, we know the Xid is not
1163  * running without even looking at pg_subtrans.
1164  */
1165  if (nxids == 0)
1166  {
1168  return false;
1169  }
1170 
1171  /*
1172  * Step 4: have to check pg_subtrans.
1173  *
1174  * At this point, we know it's either a subtransaction of one of the Xids
1175  * in xids[], or it's not running. If it's an already-failed
1176  * subtransaction, we want to say "not running" even though its parent may
1177  * still be running. So first, check pg_xact to see if it's been aborted.
1178  */
1180 
1181  if (TransactionIdDidAbort(xid))
1182  return false;
1183 
1184  /*
1185  * It isn't aborted, so check whether the transaction tree it belongs to
1186  * is still running (or, more precisely, whether it was running when we
1187  * held ProcArrayLock).
1188  */
1189  topxid = SubTransGetTopmostTransaction(xid);
1190  Assert(TransactionIdIsValid(topxid));
1191  if (!TransactionIdEquals(topxid, xid))
1192  {
1193  for (i = 0; i < nxids; i++)
1194  {
1195  if (TransactionIdEquals(xids[i], topxid))
1196  return true;
1197  }
1198  }
1199 
1200  return false;
1201 }
1202 
1203 /*
1204  * TransactionIdIsActive -- is xid the top-level XID of an active backend?
1205  *
1206  * This differs from TransactionIdIsInProgress in that it ignores prepared
1207  * transactions, as well as transactions running on the master if we're in
1208  * hot standby. Also, we ignore subtransactions since that's not needed
1209  * for current uses.
1210  */
1211 bool
1213 {
1214  bool result = false;
1215  ProcArrayStruct *arrayP = procArray;
1216  int i;
1217 
1218  /*
1219  * Don't bother checking a transaction older than RecentXmin; it could not
1220  * possibly still be running.
1221  */
1223  return false;
1224 
1225  LWLockAcquire(ProcArrayLock, LW_SHARED);
1226 
1227  for (i = 0; i < arrayP->numProcs; i++)
1228  {
1229  int pgprocno = arrayP->pgprocnos[i];
1230  volatile PGPROC *proc = &allProcs[pgprocno];
1231  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1232  TransactionId pxid;
1233 
1234  /* Fetch xid just once - see GetNewTransactionId */
1235  pxid = pgxact->xid;
1236 
1237  if (!TransactionIdIsValid(pxid))
1238  continue;
1239 
1240  if (proc->pid == 0)
1241  continue; /* ignore prepared transactions */
1242 
1243  if (TransactionIdEquals(pxid, xid))
1244  {
1245  result = true;
1246  break;
1247  }
1248  }
1249 
1250  LWLockRelease(ProcArrayLock);
1251 
1252  return result;
1253 }
1254 
1255 
1256 /*
1257  * GetOldestXmin -- returns oldest transaction that was running
1258  * when any current transaction was started.
1259  *
1260  * If rel is NULL or a shared relation, all backends are considered, otherwise
1261  * only backends running in this database are considered.
1262  *
1263  * The flags are used to ignore the backends in calculation when any of the
1264  * corresponding flags is set. Typically, if you want to ignore ones with
1265  * PROC_IN_VACUUM flag, you can use PROCARRAY_FLAGS_VACUUM.
1266  *
1267  * This is used by VACUUM to decide which deleted tuples must be preserved in
1268  * the passed in table. For shared relations backends in all databases must be
1269  * considered, but for non-shared relations that's not required, since only
1270  * backends in my own database could ever see the tuples in them. Also, we can
1271  * ignore concurrently running lazy VACUUMs because (a) they must be working
1272  * on other tables, and (b) they don't need to do snapshot-based lookups.
1273  *
1274  * This is also used to determine where to truncate pg_subtrans. For that
1275  * backends in all databases have to be considered, so rel = NULL has to be
1276  * passed in.
1277  *
1278  * Note: we include all currently running xids in the set of considered xids.
1279  * This ensures that if a just-started xact has not yet set its snapshot,
1280  * when it does set the snapshot it cannot set xmin less than what we compute.
1281  * See notes in src/backend/access/transam/README.
1282  *
1283  * Note: despite the above, it's possible for the calculated value to move
1284  * backwards on repeated calls. The calculated value is conservative, so that
1285  * anything older is definitely not considered as running by anyone anymore,
1286  * but the exact value calculated depends on a number of things. For example,
1287  * if rel = NULL and there are no transactions running in the current
1288  * database, GetOldestXmin() returns latestCompletedXid. If a transaction
1289  * begins after that, its xmin will include in-progress transactions in other
1290  * databases that started earlier, so another call will return a lower value.
1291  * Nonetheless it is safe to vacuum a table in the current database with the
1292  * first result. There are also replication-related effects: a walsender
1293  * process can set its xmin based on transactions that are no longer running
1294  * in the master but are still being replayed on the standby, thus possibly
1295  * making the GetOldestXmin reading go backwards. In this case there is a
1296  * possibility that we lose data that the standby would like to have, but
1297  * unless the standby uses a replication slot to make its xmin persistent
1298  * there is little we can do about that --- data is only protected if the
1299  * walsender runs continuously while queries are executed on the standby.
1300  * (The Hot Standby code deals with such cases by failing standby queries
1301  * that needed to access already-removed data, so there's no integrity bug.)
1302  * The return value is also adjusted with vacuum_defer_cleanup_age, so
1303  * increasing that setting on the fly is another easy way to make
1304  * GetOldestXmin() move backwards, with no consequences for data integrity.
1305  */
1307 GetOldestXmin(Relation rel, int flags)
1308 {
1309  ProcArrayStruct *arrayP = procArray;
1311  int index;
1312  bool allDbs;
1313 
1314  volatile TransactionId replication_slot_xmin = InvalidTransactionId;
1315  volatile TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1316 
1317  /*
1318  * If we're not computing a relation specific limit, or if a shared
1319  * relation has been passed in, backends in all databases have to be
1320  * considered.
1321  */
1322  allDbs = rel == NULL || rel->rd_rel->relisshared;
1323 
1324  /* Cannot look for individual databases during recovery */
1325  Assert(allDbs || !RecoveryInProgress());
1326 
1327  LWLockAcquire(ProcArrayLock, LW_SHARED);
1328 
1329  /*
1330  * We initialize the MIN() calculation with latestCompletedXid + 1. This
1331  * is a lower bound for the XIDs that might appear in the ProcArray later,
1332  * and so protects us against overestimating the result due to future
1333  * additions.
1334  */
1336  Assert(TransactionIdIsNormal(result));
1337  TransactionIdAdvance(result);
1338 
1339  for (index = 0; index < arrayP->numProcs; index++)
1340  {
1341  int pgprocno = arrayP->pgprocnos[index];
1342  volatile PGPROC *proc = &allProcs[pgprocno];
1343  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1344 
1345  if (pgxact->vacuumFlags & flags)
1346  continue;
1347 
1348  if (allDbs ||
1349  proc->databaseId == MyDatabaseId ||
1350  proc->databaseId == 0) /* always include WalSender */
1351  {
1352  /* Fetch xid just once - see GetNewTransactionId */
1353  TransactionId xid = pgxact->xid;
1354 
1355  /* First consider the transaction's own Xid, if any */
1356  if (TransactionIdIsNormal(xid) &&
1357  TransactionIdPrecedes(xid, result))
1358  result = xid;
1359 
1360  /*
1361  * Also consider the transaction's Xmin, if set.
1362  *
1363  * We must check both Xid and Xmin because a transaction might
1364  * have an Xmin but not (yet) an Xid; conversely, if it has an
1365  * Xid, that could determine some not-yet-set Xmin.
1366  */
1367  xid = pgxact->xmin; /* Fetch just once */
1368  if (TransactionIdIsNormal(xid) &&
1369  TransactionIdPrecedes(xid, result))
1370  result = xid;
1371  }
1372  }
1373 
1374  /* fetch into volatile var while ProcArrayLock is held */
1375  replication_slot_xmin = procArray->replication_slot_xmin;
1376  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1377 
1378  if (RecoveryInProgress())
1379  {
1380  /*
1381  * Check to see whether KnownAssignedXids contains an xid value older
1382  * than the main procarray.
1383  */
1385 
1386  LWLockRelease(ProcArrayLock);
1387 
1388  if (TransactionIdIsNormal(kaxmin) &&
1389  TransactionIdPrecedes(kaxmin, result))
1390  result = kaxmin;
1391  }
1392  else
1393  {
1394  /*
1395  * No other information needed, so release the lock immediately.
1396  */
1397  LWLockRelease(ProcArrayLock);
1398 
1399  /*
1400  * Compute the cutoff XID by subtracting vacuum_defer_cleanup_age,
1401  * being careful not to generate a "permanent" XID.
1402  *
1403  * vacuum_defer_cleanup_age provides some additional "slop" for the
1404  * benefit of hot standby queries on slave servers. This is quick and
1405  * dirty, and perhaps not all that useful unless the master has a
1406  * predictable transaction rate, but it offers some protection when
1407  * there's no walsender connection. Note that we are assuming
1408  * vacuum_defer_cleanup_age isn't large enough to cause wraparound ---
1409  * so guc.c should limit it to no more than the xidStopLimit threshold
1410  * in varsup.c. Also note that we intentionally don't apply
1411  * vacuum_defer_cleanup_age on standby servers.
1412  */
1413  result -= vacuum_defer_cleanup_age;
1414  if (!TransactionIdIsNormal(result))
1415  result = FirstNormalTransactionId;
1416  }
1417 
1418  /*
1419  * Check whether there are replication slots requiring an older xmin.
1420  */
1421  if (TransactionIdIsValid(replication_slot_xmin) &&
1422  NormalTransactionIdPrecedes(replication_slot_xmin, result))
1423  result = replication_slot_xmin;
1424 
1425  /*
1426  * After locks have been released and defer_cleanup_age has been applied,
1427  * check whether we need to back up further to make logical decoding
1428  * possible. We need to do so if we're computing the global limit (rel =
1429  * NULL) or if the passed relation is a catalog relation of some kind.
1430  */
1431  if ((rel == NULL ||
1433  TransactionIdIsValid(replication_slot_catalog_xmin) &&
1434  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, result))
1435  result = replication_slot_catalog_xmin;
1436 
1437  return result;
1438 }
1439 
1440 /*
1441  * GetMaxSnapshotXidCount -- get max size for snapshot XID array
1442  *
1443  * We have to export this for use by snapmgr.c.
1444  */
1445 int
1447 {
1448  return procArray->maxProcs;
1449 }
1450 
1451 /*
1452  * GetMaxSnapshotSubxidCount -- get max size for snapshot sub-XID array
1453  *
1454  * We have to export this for use by snapmgr.c.
1455  */
1456 int
1458 {
1459  return TOTAL_MAX_CACHED_SUBXIDS;
1460 }
1461 
1462 /*
1463  * GetSnapshotData -- returns information about running transactions.
1464  *
1465  * The returned snapshot includes xmin (lowest still-running xact ID),
1466  * xmax (highest completed xact ID + 1), and a list of running xact IDs
1467  * in the range xmin <= xid < xmax. It is used as follows:
1468  * All xact IDs < xmin are considered finished.
1469  * All xact IDs >= xmax are considered still running.
1470  * For an xact ID xmin <= xid < xmax, consult list to see whether
1471  * it is considered running or not.
1472  * This ensures that the set of transactions seen as "running" by the
1473  * current xact will not change after it takes the snapshot.
1474  *
1475  * All running top-level XIDs are included in the snapshot, except for lazy
1476  * VACUUM processes. We also try to include running subtransaction XIDs,
1477  * but since PGPROC has only a limited cache area for subxact XIDs, full
1478  * information may not be available. If we find any overflowed subxid arrays,
1479  * we have to mark the snapshot's subxid data as overflowed, and extra work
1480  * *may* need to be done to determine what's running (see XidInMVCCSnapshot()
1481  * in tqual.c).
1482  *
1483  * We also update the following backend-global variables:
1484  * TransactionXmin: the oldest xmin of any snapshot in use in the
1485  * current transaction (this is the same as MyPgXact->xmin).
1486  * RecentXmin: the xmin computed for the most recent snapshot. XIDs
1487  * older than this are known not running any more.
1488  * RecentGlobalXmin: the global xmin (oldest TransactionXmin across all
1489  * running transactions, except those running LAZY VACUUM). This is
1490  * the same computation done by GetOldestXmin(true, true).
1491  * RecentGlobalDataXmin: the global xmin for non-catalog tables
1492  * >= RecentGlobalXmin
1493  *
1494  * Note: this function should probably not be called with an argument that's
1495  * not statically allocated (see xip allocation below).
1496  */
1497 Snapshot
1499 {
1500  ProcArrayStruct *arrayP = procArray;
1501  TransactionId xmin;
1502  TransactionId xmax;
1503  TransactionId globalxmin;
1504  int index;
1505  int count = 0;
1506  int subcount = 0;
1507  bool suboverflowed = false;
1508  volatile TransactionId replication_slot_xmin = InvalidTransactionId;
1509  volatile TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1510 
1511  Assert(snapshot != NULL);
1512 
1513  /*
1514  * Allocating space for maxProcs xids is usually overkill; numProcs would
1515  * be sufficient. But it seems better to do the malloc while not holding
1516  * the lock, so we can't look at numProcs. Likewise, we allocate much
1517  * more subxip storage than is probably needed.
1518  *
1519  * This does open a possibility for avoiding repeated malloc/free: since
1520  * maxProcs does not change at runtime, we can simply reuse the previous
1521  * xip arrays if any. (This relies on the fact that all callers pass
1522  * static SnapshotData structs.)
1523  */
1524  if (snapshot->xip == NULL)
1525  {
1526  /*
1527  * First call for this snapshot. Snapshot is same size whether or not
1528  * we are in recovery, see later comments.
1529  */
1530  snapshot->xip = (TransactionId *)
1532  if (snapshot->xip == NULL)
1533  ereport(ERROR,
1534  (errcode(ERRCODE_OUT_OF_MEMORY),
1535  errmsg("out of memory")));
1536  Assert(snapshot->subxip == NULL);
1537  snapshot->subxip = (TransactionId *)
1539  if (snapshot->subxip == NULL)
1540  ereport(ERROR,
1541  (errcode(ERRCODE_OUT_OF_MEMORY),
1542  errmsg("out of memory")));
1543  }
1544 
1545  /*
1546  * It is sufficient to get shared lock on ProcArrayLock, even if we are
1547  * going to set MyPgXact->xmin.
1548  */
1549  LWLockAcquire(ProcArrayLock, LW_SHARED);
1550 
1551  /* xmax is always latestCompletedXid + 1 */
1554  TransactionIdAdvance(xmax);
1555 
1556  /* initialize xmin calculation with xmax */
1557  globalxmin = xmin = xmax;
1558 
1560 
1561  if (!snapshot->takenDuringRecovery)
1562  {
1563  int *pgprocnos = arrayP->pgprocnos;
1564  int numProcs;
1565 
1566  /*
1567  * Spin over procArray checking xid, xmin, and subxids. The goal is
1568  * to gather all active xids, find the lowest xmin, and try to record
1569  * subxids.
1570  */
1571  numProcs = arrayP->numProcs;
1572  for (index = 0; index < numProcs; index++)
1573  {
1574  int pgprocno = pgprocnos[index];
1575  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1576  TransactionId xid;
1577 
1578  /*
1579  * Backend is doing logical decoding which manages xmin
1580  * separately, check below.
1581  */
1582  if (pgxact->vacuumFlags & PROC_IN_LOGICAL_DECODING)
1583  continue;
1584 
1585  /* Ignore procs running LAZY VACUUM */
1586  if (pgxact->vacuumFlags & PROC_IN_VACUUM)
1587  continue;
1588 
1589  /* Update globalxmin to be the smallest valid xmin */
1590  xid = pgxact->xmin; /* fetch just once */
1591  if (TransactionIdIsNormal(xid) &&
1592  NormalTransactionIdPrecedes(xid, globalxmin))
1593  globalxmin = xid;
1594 
1595  /* Fetch xid just once - see GetNewTransactionId */
1596  xid = pgxact->xid;
1597 
1598  /*
1599  * If the transaction has no XID assigned, we can skip it; it
1600  * won't have sub-XIDs either. If the XID is >= xmax, we can also
1601  * skip it; such transactions will be treated as running anyway
1602  * (and any sub-XIDs will also be >= xmax).
1603  */
1604  if (!TransactionIdIsNormal(xid)
1605  || !NormalTransactionIdPrecedes(xid, xmax))
1606  continue;
1607 
1608  /*
1609  * We don't include our own XIDs (if any) in the snapshot, but we
1610  * must include them in xmin.
1611  */
1612  if (NormalTransactionIdPrecedes(xid, xmin))
1613  xmin = xid;
1614  if (pgxact == MyPgXact)
1615  continue;
1616 
1617  /* Add XID to snapshot. */
1618  snapshot->xip[count++] = xid;
1619 
1620  /*
1621  * Save subtransaction XIDs if possible (if we've already
1622  * overflowed, there's no point). Note that the subxact XIDs must
1623  * be later than their parent, so no need to check them against
1624  * xmin. We could filter against xmax, but it seems better not to
1625  * do that much work while holding the ProcArrayLock.
1626  *
1627  * The other backend can add more subxids concurrently, but cannot
1628  * remove any. Hence it's important to fetch nxids just once.
1629  * Should be safe to use memcpy, though. (We needn't worry about
1630  * missing any xids added concurrently, because they must postdate
1631  * xmax.)
1632  *
1633  * Again, our own XIDs are not included in the snapshot.
1634  */
1635  if (!suboverflowed)
1636  {
1637  if (pgxact->overflowed)
1638  suboverflowed = true;
1639  else
1640  {
1641  int nxids = pgxact->nxids;
1642 
1643  if (nxids > 0)
1644  {
1645  volatile PGPROC *proc = &allProcs[pgprocno];
1646 
1647  memcpy(snapshot->subxip + subcount,
1648  (void *) proc->subxids.xids,
1649  nxids * sizeof(TransactionId));
1650  subcount += nxids;
1651  }
1652  }
1653  }
1654  }
1655  }
1656  else
1657  {
1658  /*
1659  * We're in hot standby, so get XIDs from KnownAssignedXids.
1660  *
1661  * We store all xids directly into subxip[]. Here's why:
1662  *
1663  * In recovery we don't know which xids are top-level and which are
1664  * subxacts, a design choice that greatly simplifies xid processing.
1665  *
1666  * It seems like we would want to try to put xids into xip[] only, but
1667  * that is fairly small. We would either need to make that bigger or
1668  * to increase the rate at which we WAL-log xid assignment; neither is
1669  * an appealing choice.
1670  *
1671  * We could try to store xids into xip[] first and then into subxip[]
1672  * if there are too many xids. That only works if the snapshot doesn't
1673  * overflow because we do not search subxip[] in that case. A simpler
1674  * way is to just store all xids in the subxact array because this is
1675  * by far the bigger array. We just leave the xip array empty.
1676  *
1677  * Either way we need to change the way XidInMVCCSnapshot() works
1678  * depending upon when the snapshot was taken, or change normal
1679  * snapshot processing so it matches.
1680  *
1681  * Note: It is possible for recovery to end before we finish taking
1682  * the snapshot, and for newly assigned transaction ids to be added to
1683  * the ProcArray. xmax cannot change while we hold ProcArrayLock, so
1684  * those newly added transaction ids would be filtered away, so we
1685  * need not be concerned about them.
1686  */
1687  subcount = KnownAssignedXidsGetAndSetXmin(snapshot->subxip, &xmin,
1688  xmax);
1689 
1690  if (TransactionIdPrecedesOrEquals(xmin, procArray->lastOverflowedXid))
1691  suboverflowed = true;
1692  }
1693 
1694 
1695  /* fetch into volatile var while ProcArrayLock is held */
1696  replication_slot_xmin = procArray->replication_slot_xmin;
1697  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1698 
1700  MyPgXact->xmin = TransactionXmin = xmin;
1701 
1702  LWLockRelease(ProcArrayLock);
1703 
1704  /*
1705  * Update globalxmin to include actual process xids. This is a slightly
1706  * different way of computing it than GetOldestXmin uses, but should give
1707  * the same result.
1708  */
1709  if (TransactionIdPrecedes(xmin, globalxmin))
1710  globalxmin = xmin;
1711 
1712  /* Update global variables too */
1716 
1717  /* Check whether there's a replication slot requiring an older xmin. */
1718  if (TransactionIdIsValid(replication_slot_xmin) &&
1719  NormalTransactionIdPrecedes(replication_slot_xmin, RecentGlobalXmin))
1720  RecentGlobalXmin = replication_slot_xmin;
1721 
1722  /* Non-catalog tables can be vacuumed if older than this xid */
1724 
1725  /*
1726  * Check whether there's a replication slot requiring an older catalog
1727  * xmin.
1728  */
1729  if (TransactionIdIsNormal(replication_slot_catalog_xmin) &&
1730  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, RecentGlobalXmin))
1731  RecentGlobalXmin = replication_slot_catalog_xmin;
1732 
1733  RecentXmin = xmin;
1734 
1735  snapshot->xmin = xmin;
1736  snapshot->xmax = xmax;
1737  snapshot->xcnt = count;
1738  snapshot->subxcnt = subcount;
1739  snapshot->suboverflowed = suboverflowed;
1740 
1741  snapshot->curcid = GetCurrentCommandId(false);
1742 
1743  /*
1744  * This is a new snapshot, so set both refcounts are zero, and mark it as
1745  * not copied in persistent memory.
1746  */
1747  snapshot->active_count = 0;
1748  snapshot->regd_count = 0;
1749  snapshot->copied = false;
1750 
1751  if (old_snapshot_threshold < 0)
1752  {
1753  /*
1754  * If not using "snapshot too old" feature, fill related fields with
1755  * dummy values that don't require any locking.
1756  */
1757  snapshot->lsn = InvalidXLogRecPtr;
1758  snapshot->whenTaken = 0;
1759  }
1760  else
1761  {
1762  /*
1763  * Capture the current time and WAL stream location in case this
1764  * snapshot becomes old enough to need to fall back on the special
1765  * "old snapshot" logic.
1766  */
1767  snapshot->lsn = GetXLogInsertRecPtr();
1768  snapshot->whenTaken = GetSnapshotCurrentTimestamp();
1769  MaintainOldSnapshotTimeMapping(snapshot->whenTaken, xmin);
1770  }
1771 
1772  return snapshot;
1773 }
1774 
1775 /*
1776  * ProcArrayInstallImportedXmin -- install imported xmin into MyPgXact->xmin
1777  *
1778  * This is called when installing a snapshot imported from another
1779  * transaction. To ensure that OldestXmin doesn't go backwards, we must
1780  * check that the source transaction is still running, and we'd better do
1781  * that atomically with installing the new xmin.
1782  *
1783  * Returns TRUE if successful, FALSE if source xact is no longer running.
1784  */
1785 bool
1787 {
1788  bool result = false;
1789  ProcArrayStruct *arrayP = procArray;
1790  int index;
1791 
1793  if (!TransactionIdIsNormal(sourcexid))
1794  return false;
1795 
1796  /* Get lock so source xact can't end while we're doing this */
1797  LWLockAcquire(ProcArrayLock, LW_SHARED);
1798 
1799  for (index = 0; index < arrayP->numProcs; index++)
1800  {
1801  int pgprocno = arrayP->pgprocnos[index];
1802  volatile PGPROC *proc = &allProcs[pgprocno];
1803  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1804  TransactionId xid;
1805 
1806  /* Ignore procs running LAZY VACUUM */
1807  if (pgxact->vacuumFlags & PROC_IN_VACUUM)
1808  continue;
1809 
1810  xid = pgxact->xid; /* fetch just once */
1811  if (xid != sourcexid)
1812  continue;
1813 
1814  /*
1815  * We check the transaction's database ID for paranoia's sake: if it's
1816  * in another DB then its xmin does not cover us. Caller should have
1817  * detected this already, so we just treat any funny cases as
1818  * "transaction not found".
1819  */
1820  if (proc->databaseId != MyDatabaseId)
1821  continue;
1822 
1823  /*
1824  * Likewise, let's just make real sure its xmin does cover us.
1825  */
1826  xid = pgxact->xmin; /* fetch just once */
1827  if (!TransactionIdIsNormal(xid) ||
1828  !TransactionIdPrecedesOrEquals(xid, xmin))
1829  continue;
1830 
1831  /*
1832  * We're good. Install the new xmin. As in GetSnapshotData, set
1833  * TransactionXmin too. (Note that because snapmgr.c called
1834  * GetSnapshotData first, we'll be overwriting a valid xmin here, so
1835  * we don't check that.)
1836  */
1837  MyPgXact->xmin = TransactionXmin = xmin;
1838 
1839  result = true;
1840  break;
1841  }
1842 
1843  LWLockRelease(ProcArrayLock);
1844 
1845  return result;
1846 }
1847 
1848 /*
1849  * ProcArrayInstallRestoredXmin -- install restored xmin into MyPgXact->xmin
1850  *
1851  * This is like ProcArrayInstallImportedXmin, but we have a pointer to the
1852  * PGPROC of the transaction from which we imported the snapshot, rather than
1853  * an XID.
1854  *
1855  * Returns TRUE if successful, FALSE if source xact is no longer running.
1856  */
1857 bool
1859 {
1860  bool result = false;
1861  TransactionId xid;
1862  volatile PGXACT *pgxact;
1863 
1865  Assert(proc != NULL);
1866 
1867  /* Get lock so source xact can't end while we're doing this */
1868  LWLockAcquire(ProcArrayLock, LW_SHARED);
1869 
1870  pgxact = &allPgXact[proc->pgprocno];
1871 
1872  /*
1873  * Be certain that the referenced PGPROC has an advertised xmin which is
1874  * no later than the one we're installing, so that the system-wide xmin
1875  * can't go backwards. Also, make sure it's running in the same database,
1876  * so that the per-database xmin cannot go backwards.
1877  */
1878  xid = pgxact->xmin; /* fetch just once */
1879  if (proc->databaseId == MyDatabaseId &&
1880  TransactionIdIsNormal(xid) &&
1881  TransactionIdPrecedesOrEquals(xid, xmin))
1882  {
1883  MyPgXact->xmin = TransactionXmin = xmin;
1884  result = true;
1885  }
1886 
1887  LWLockRelease(ProcArrayLock);
1888 
1889  return result;
1890 }
1891 
1892 /*
1893  * GetRunningTransactionData -- returns information about running transactions.
1894  *
1895  * Similar to GetSnapshotData but returns more information. We include
1896  * all PGXACTs with an assigned TransactionId, even VACUUM processes.
1897  *
1898  * We acquire XidGenLock and ProcArrayLock, but the caller is responsible for
1899  * releasing them. Acquiring XidGenLock ensures that no new XIDs enter the proc
1900  * array until the caller has WAL-logged this snapshot, and releases the
1901  * lock. Acquiring ProcArrayLock ensures that no transactions commit until the
1902  * lock is released.
1903  *
1904  * The returned data structure is statically allocated; caller should not
1905  * modify it, and must not assume it is valid past the next call.
1906  *
1907  * This is never executed during recovery so there is no need to look at
1908  * KnownAssignedXids.
1909  *
1910  * We don't worry about updating other counters, we want to keep this as
1911  * simple as possible and leave GetSnapshotData() as the primary code for
1912  * that bookkeeping.
1913  *
1914  * Note that if any transaction has overflowed its cached subtransactions
1915  * then there is no real need include any subtransactions. That isn't a
1916  * common enough case to worry about optimising the size of the WAL record,
1917  * and we may wish to see that data for diagnostic purposes anyway.
1918  */
1921 {
1922  /* result workspace */
1923  static RunningTransactionsData CurrentRunningXactsData;
1924 
1925  ProcArrayStruct *arrayP = procArray;
1926  RunningTransactions CurrentRunningXacts = &CurrentRunningXactsData;
1927  TransactionId latestCompletedXid;
1928  TransactionId oldestRunningXid;
1929  TransactionId *xids;
1930  int index;
1931  int count;
1932  int subcount;
1933  bool suboverflowed;
1934 
1936 
1937  /*
1938  * Allocating space for maxProcs xids is usually overkill; numProcs would
1939  * be sufficient. But it seems better to do the malloc while not holding
1940  * the lock, so we can't look at numProcs. Likewise, we allocate much
1941  * more subxip storage than is probably needed.
1942  *
1943  * Should only be allocated in bgwriter, since only ever executed during
1944  * checkpoints.
1945  */
1946  if (CurrentRunningXacts->xids == NULL)
1947  {
1948  /*
1949  * First call
1950  */
1951  CurrentRunningXacts->xids = (TransactionId *)
1953  if (CurrentRunningXacts->xids == NULL)
1954  ereport(ERROR,
1955  (errcode(ERRCODE_OUT_OF_MEMORY),
1956  errmsg("out of memory")));
1957  }
1958 
1959  xids = CurrentRunningXacts->xids;
1960 
1961  count = subcount = 0;
1962  suboverflowed = false;
1963 
1964  /*
1965  * Ensure that no xids enter or leave the procarray while we obtain
1966  * snapshot.
1967  */
1968  LWLockAcquire(ProcArrayLock, LW_SHARED);
1969  LWLockAcquire(XidGenLock, LW_SHARED);
1970 
1971  latestCompletedXid = ShmemVariableCache->latestCompletedXid;
1972 
1973  oldestRunningXid = ShmemVariableCache->nextXid;
1974 
1975  /*
1976  * Spin over procArray collecting all xids
1977  */
1978  for (index = 0; index < arrayP->numProcs; index++)
1979  {
1980  int pgprocno = arrayP->pgprocnos[index];
1981  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1982  TransactionId xid;
1983 
1984  /* Fetch xid just once - see GetNewTransactionId */
1985  xid = pgxact->xid;
1986 
1987  /*
1988  * We don't need to store transactions that don't have a TransactionId
1989  * yet because they will not show as running on a standby server.
1990  */
1991  if (!TransactionIdIsValid(xid))
1992  continue;
1993 
1994  xids[count++] = xid;
1995 
1996  if (TransactionIdPrecedes(xid, oldestRunningXid))
1997  oldestRunningXid = xid;
1998 
1999  if (pgxact->overflowed)
2000  suboverflowed = true;
2001  }
2002 
2003  /*
2004  * Spin over procArray collecting all subxids, but only if there hasn't
2005  * been a suboverflow.
2006  */
2007  if (!suboverflowed)
2008  {
2009  for (index = 0; index < arrayP->numProcs; index++)
2010  {
2011  int pgprocno = arrayP->pgprocnos[index];
2012  volatile PGPROC *proc = &allProcs[pgprocno];
2013  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2014  int nxids;
2015 
2016  /*
2017  * Save subtransaction XIDs. Other backends can't add or remove
2018  * entries while we're holding XidGenLock.
2019  */
2020  nxids = pgxact->nxids;
2021  if (nxids > 0)
2022  {
2023  memcpy(&xids[count], (void *) proc->subxids.xids,
2024  nxids * sizeof(TransactionId));
2025  count += nxids;
2026  subcount += nxids;
2027 
2028  /*
2029  * Top-level XID of a transaction is always less than any of
2030  * its subxids, so we don't need to check if any of the
2031  * subxids are smaller than oldestRunningXid
2032  */
2033  }
2034  }
2035  }
2036 
2037  /*
2038  * It's important *not* to include the limits set by slots here because
2039  * snapbuild.c uses oldestRunningXid to manage its xmin horizon. If those
2040  * were to be included here the initial value could never increase because
2041  * of a circular dependency where slots only increase their limits when
2042  * running xacts increases oldestRunningXid and running xacts only
2043  * increases if slots do.
2044  */
2045 
2046  CurrentRunningXacts->xcnt = count - subcount;
2047  CurrentRunningXacts->subxcnt = subcount;
2048  CurrentRunningXacts->subxid_overflow = suboverflowed;
2049  CurrentRunningXacts->nextXid = ShmemVariableCache->nextXid;
2050  CurrentRunningXacts->oldestRunningXid = oldestRunningXid;
2051  CurrentRunningXacts->latestCompletedXid = latestCompletedXid;
2052 
2053  Assert(TransactionIdIsValid(CurrentRunningXacts->nextXid));
2054  Assert(TransactionIdIsValid(CurrentRunningXacts->oldestRunningXid));
2055  Assert(TransactionIdIsNormal(CurrentRunningXacts->latestCompletedXid));
2056 
2057  /* We don't release the locks here, the caller is responsible for that */
2058 
2059  return CurrentRunningXacts;
2060 }
2061 
2062 /*
2063  * GetOldestActiveTransactionId()
2064  *
2065  * Similar to GetSnapshotData but returns just oldestActiveXid. We include
2066  * all PGXACTs with an assigned TransactionId, even VACUUM processes.
2067  * We look at all databases, though there is no need to include WALSender
2068  * since this has no effect on hot standby conflicts.
2069  *
2070  * This is never executed during recovery so there is no need to look at
2071  * KnownAssignedXids.
2072  *
2073  * We don't worry about updating other counters, we want to keep this as
2074  * simple as possible and leave GetSnapshotData() as the primary code for
2075  * that bookkeeping.
2076  */
2079 {
2080  ProcArrayStruct *arrayP = procArray;
2081  TransactionId oldestRunningXid;
2082  int index;
2083 
2085 
2086  LWLockAcquire(ProcArrayLock, LW_SHARED);
2087 
2088  /*
2089  * It's okay to read nextXid without acquiring XidGenLock because (1) we
2090  * assume TransactionIds can be read atomically and (2) we don't care if
2091  * we get a slightly stale value. It can't be very stale anyway, because
2092  * the LWLockAcquire above will have done any necessary memory
2093  * interlocking.
2094  */
2095  oldestRunningXid = ShmemVariableCache->nextXid;
2096 
2097  /*
2098  * Spin over procArray collecting all xids and subxids.
2099  */
2100  for (index = 0; index < arrayP->numProcs; index++)
2101  {
2102  int pgprocno = arrayP->pgprocnos[index];
2103  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2104  TransactionId xid;
2105 
2106  /* Fetch xid just once - see GetNewTransactionId */
2107  xid = pgxact->xid;
2108 
2109  if (!TransactionIdIsNormal(xid))
2110  continue;
2111 
2112  if (TransactionIdPrecedes(xid, oldestRunningXid))
2113  oldestRunningXid = xid;
2114 
2115  /*
2116  * Top-level XID of a transaction is always less than any of its
2117  * subxids, so we don't need to check if any of the subxids are
2118  * smaller than oldestRunningXid
2119  */
2120  }
2121 
2122  LWLockRelease(ProcArrayLock);
2123 
2124  return oldestRunningXid;
2125 }
2126 
2127 /*
2128  * GetOldestSafeDecodingTransactionId -- lowest xid not affected by vacuum
2129  *
2130  * Returns the oldest xid that we can guarantee not to have been affected by
2131  * vacuum, i.e. no rows >= that xid have been vacuumed away unless the
2132  * transaction aborted. Note that the value can (and most of the time will) be
2133  * much more conservative than what really has been affected by vacuum, but we
2134  * currently don't have better data available.
2135  *
2136  * This is useful to initialize the cutoff xid after which a new changeset
2137  * extraction replication slot can start decoding changes.
2138  *
2139  * Must be called with ProcArrayLock held either shared or exclusively,
2140  * although most callers will want to use exclusive mode since it is expected
2141  * that the caller will immediately use the xid to peg the xmin horizon.
2142  */
2145 {
2146  ProcArrayStruct *arrayP = procArray;
2147  TransactionId oldestSafeXid;
2148  int index;
2149  bool recovery_in_progress = RecoveryInProgress();
2150 
2151  Assert(LWLockHeldByMe(ProcArrayLock));
2152 
2153  /*
2154  * Acquire XidGenLock, so no transactions can acquire an xid while we're
2155  * running. If no transaction with xid were running concurrently a new xid
2156  * could influence the RecentXmin et al.
2157  *
2158  * We initialize the computation to nextXid since that's guaranteed to be
2159  * a safe, albeit pessimal, value.
2160  */
2161  LWLockAcquire(XidGenLock, LW_SHARED);
2162  oldestSafeXid = ShmemVariableCache->nextXid;
2163 
2164  /*
2165  * If there's already a slot pegging the xmin horizon, we can start with
2166  * that value, it's guaranteed to be safe since it's computed by this
2167  * routine initially and has been enforced since.
2168  */
2171  oldestSafeXid))
2172  oldestSafeXid = procArray->replication_slot_catalog_xmin;
2173 
2174  /*
2175  * If we're not in recovery, we walk over the procarray and collect the
2176  * lowest xid. Since we're called with ProcArrayLock held and have
2177  * acquired XidGenLock, no entries can vanish concurrently, since
2178  * PGXACT->xid is only set with XidGenLock held and only cleared with
2179  * ProcArrayLock held.
2180  *
2181  * In recovery we can't lower the safe value besides what we've computed
2182  * above, so we'll have to wait a bit longer there. We unfortunately can
2183  * *not* use KnownAssignedXidsGetOldestXmin() since the KnownAssignedXids
2184  * machinery can miss values and return an older value than is safe.
2185  */
2186  if (!recovery_in_progress)
2187  {
2188  /*
2189  * Spin over procArray collecting all min(PGXACT->xid)
2190  */
2191  for (index = 0; index < arrayP->numProcs; index++)
2192  {
2193  int pgprocno = arrayP->pgprocnos[index];
2194  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2195  TransactionId xid;
2196 
2197  /* Fetch xid just once - see GetNewTransactionId */
2198  xid = pgxact->xid;
2199 
2200  if (!TransactionIdIsNormal(xid))
2201  continue;
2202 
2203  if (TransactionIdPrecedes(xid, oldestSafeXid))
2204  oldestSafeXid = xid;
2205  }
2206  }
2207 
2208  LWLockRelease(XidGenLock);
2209 
2210  return oldestSafeXid;
2211 }
2212 
2213 /*
2214  * GetVirtualXIDsDelayingChkpt -- Get the VXIDs of transactions that are
2215  * delaying checkpoint because they have critical actions in progress.
2216  *
2217  * Constructs an array of VXIDs of transactions that are currently in commit
2218  * critical sections, as shown by having delayChkpt set in their PGXACT.
2219  *
2220  * Returns a palloc'd array that should be freed by the caller.
2221  * *nvxids is the number of valid entries.
2222  *
2223  * Note that because backends set or clear delayChkpt without holding any lock,
2224  * the result is somewhat indeterminate, but we don't really care. Even in
2225  * a multiprocessor with delayed writes to shared memory, it should be certain
2226  * that setting of delayChkpt will propagate to shared memory when the backend
2227  * takes a lock, so we cannot fail to see a virtual xact as delayChkpt if
2228  * it's already inserted its commit record. Whether it takes a little while
2229  * for clearing of delayChkpt to propagate is unimportant for correctness.
2230  */
2233 {
2234  VirtualTransactionId *vxids;
2235  ProcArrayStruct *arrayP = procArray;
2236  int count = 0;
2237  int index;
2238 
2239  /* allocate what's certainly enough result space */
2240  vxids = (VirtualTransactionId *)
2241  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2242 
2243  LWLockAcquire(ProcArrayLock, LW_SHARED);
2244 
2245  for (index = 0; index < arrayP->numProcs; index++)
2246  {
2247  int pgprocno = arrayP->pgprocnos[index];
2248  volatile PGPROC *proc = &allProcs[pgprocno];
2249  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2250 
2251  if (pgxact->delayChkpt)
2252  {
2253  VirtualTransactionId vxid;
2254 
2255  GET_VXID_FROM_PGPROC(vxid, *proc);
2256  if (VirtualTransactionIdIsValid(vxid))
2257  vxids[count++] = vxid;
2258  }
2259  }
2260 
2261  LWLockRelease(ProcArrayLock);
2262 
2263  *nvxids = count;
2264  return vxids;
2265 }
2266 
2267 /*
2268  * HaveVirtualXIDsDelayingChkpt -- Are any of the specified VXIDs delaying?
2269  *
2270  * This is used with the results of GetVirtualXIDsDelayingChkpt to see if any
2271  * of the specified VXIDs are still in critical sections of code.
2272  *
2273  * Note: this is O(N^2) in the number of vxacts that are/were delaying, but
2274  * those numbers should be small enough for it not to be a problem.
2275  */
2276 bool
2278 {
2279  bool result = false;
2280  ProcArrayStruct *arrayP = procArray;
2281  int index;
2282 
2283  LWLockAcquire(ProcArrayLock, LW_SHARED);
2284 
2285  for (index = 0; index < arrayP->numProcs; index++)
2286  {
2287  int pgprocno = arrayP->pgprocnos[index];
2288  volatile PGPROC *proc = &allProcs[pgprocno];
2289  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2290  VirtualTransactionId vxid;
2291 
2292  GET_VXID_FROM_PGPROC(vxid, *proc);
2293 
2294  if (pgxact->delayChkpt && VirtualTransactionIdIsValid(vxid))
2295  {
2296  int i;
2297 
2298  for (i = 0; i < nvxids; i++)
2299  {
2300  if (VirtualTransactionIdEquals(vxid, vxids[i]))
2301  {
2302  result = true;
2303  break;
2304  }
2305  }
2306  if (result)
2307  break;
2308  }
2309  }
2310 
2311  LWLockRelease(ProcArrayLock);
2312 
2313  return result;
2314 }
2315 
2316 /*
2317  * BackendPidGetProc -- get a backend's PGPROC given its PID
2318  *
2319  * Returns NULL if not found. Note that it is up to the caller to be
2320  * sure that the question remains meaningful for long enough for the
2321  * answer to be used ...
2322  */
2323 PGPROC *
2325 {
2326  PGPROC *result;
2327 
2328  if (pid == 0) /* never match dummy PGPROCs */
2329  return NULL;
2330 
2331  LWLockAcquire(ProcArrayLock, LW_SHARED);
2332 
2333  result = BackendPidGetProcWithLock(pid);
2334 
2335  LWLockRelease(ProcArrayLock);
2336 
2337  return result;
2338 }
2339 
2340 /*
2341  * BackendPidGetProcWithLock -- get a backend's PGPROC given its PID
2342  *
2343  * Same as above, except caller must be holding ProcArrayLock. The found
2344  * entry, if any, can be assumed to be valid as long as the lock remains held.
2345  */
2346 PGPROC *
2348 {
2349  PGPROC *result = NULL;
2350  ProcArrayStruct *arrayP = procArray;
2351  int index;
2352 
2353  if (pid == 0) /* never match dummy PGPROCs */
2354  return NULL;
2355 
2356  for (index = 0; index < arrayP->numProcs; index++)
2357  {
2358  PGPROC *proc = &allProcs[arrayP->pgprocnos[index]];
2359 
2360  if (proc->pid == pid)
2361  {
2362  result = proc;
2363  break;
2364  }
2365  }
2366 
2367  return result;
2368 }
2369 
2370 /*
2371  * BackendXidGetPid -- get a backend's pid given its XID
2372  *
2373  * Returns 0 if not found or it's a prepared transaction. Note that
2374  * it is up to the caller to be sure that the question remains
2375  * meaningful for long enough for the answer to be used ...
2376  *
2377  * Only main transaction Ids are considered. This function is mainly
2378  * useful for determining what backend owns a lock.
2379  *
2380  * Beware that not every xact has an XID assigned. However, as long as you
2381  * only call this using an XID found on disk, you're safe.
2382  */
2383 int
2385 {
2386  int result = 0;
2387  ProcArrayStruct *arrayP = procArray;
2388  int index;
2389 
2390  if (xid == InvalidTransactionId) /* never match invalid xid */
2391  return 0;
2392 
2393  LWLockAcquire(ProcArrayLock, LW_SHARED);
2394 
2395  for (index = 0; index < arrayP->numProcs; index++)
2396  {
2397  int pgprocno = arrayP->pgprocnos[index];
2398  volatile PGPROC *proc = &allProcs[pgprocno];
2399  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2400 
2401  if (pgxact->xid == xid)
2402  {
2403  result = proc->pid;
2404  break;
2405  }
2406  }
2407 
2408  LWLockRelease(ProcArrayLock);
2409 
2410  return result;
2411 }
2412 
2413 /*
2414  * IsBackendPid -- is a given pid a running backend
2415  *
2416  * This is not called by the backend, but is called by external modules.
2417  */
2418 bool
2420 {
2421  return (BackendPidGetProc(pid) != NULL);
2422 }
2423 
2424 
2425 /*
2426  * GetCurrentVirtualXIDs -- returns an array of currently active VXIDs.
2427  *
2428  * The array is palloc'd. The number of valid entries is returned into *nvxids.
2429  *
2430  * The arguments allow filtering the set of VXIDs returned. Our own process
2431  * is always skipped. In addition:
2432  * If limitXmin is not InvalidTransactionId, skip processes with
2433  * xmin > limitXmin.
2434  * If excludeXmin0 is true, skip processes with xmin = 0.
2435  * If allDbs is false, skip processes attached to other databases.
2436  * If excludeVacuum isn't zero, skip processes for which
2437  * (vacuumFlags & excludeVacuum) is not zero.
2438  *
2439  * Note: the purpose of the limitXmin and excludeXmin0 parameters is to
2440  * allow skipping backends whose oldest live snapshot is no older than
2441  * some snapshot we have. Since we examine the procarray with only shared
2442  * lock, there are race conditions: a backend could set its xmin just after
2443  * we look. Indeed, on multiprocessors with weak memory ordering, the
2444  * other backend could have set its xmin *before* we look. We know however
2445  * that such a backend must have held shared ProcArrayLock overlapping our
2446  * own hold of ProcArrayLock, else we would see its xmin update. Therefore,
2447  * any snapshot the other backend is taking concurrently with our scan cannot
2448  * consider any transactions as still running that we think are committed
2449  * (since backends must hold ProcArrayLock exclusive to commit).
2450  */
2452 GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0,
2453  bool allDbs, int excludeVacuum,
2454  int *nvxids)
2455 {
2456  VirtualTransactionId *vxids;
2457  ProcArrayStruct *arrayP = procArray;
2458  int count = 0;
2459  int index;
2460 
2461  /* allocate what's certainly enough result space */
2462  vxids = (VirtualTransactionId *)
2463  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2464 
2465  LWLockAcquire(ProcArrayLock, LW_SHARED);
2466 
2467  for (index = 0; index < arrayP->numProcs; index++)
2468  {
2469  int pgprocno = arrayP->pgprocnos[index];
2470  volatile PGPROC *proc = &allProcs[pgprocno];
2471  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2472 
2473  if (proc == MyProc)
2474  continue;
2475 
2476  if (excludeVacuum & pgxact->vacuumFlags)
2477  continue;
2478 
2479  if (allDbs || proc->databaseId == MyDatabaseId)
2480  {
2481  /* Fetch xmin just once - might change on us */
2482  TransactionId pxmin = pgxact->xmin;
2483 
2484  if (excludeXmin0 && !TransactionIdIsValid(pxmin))
2485  continue;
2486 
2487  /*
2488  * InvalidTransactionId precedes all other XIDs, so a proc that
2489  * hasn't set xmin yet will not be rejected by this test.
2490  */
2491  if (!TransactionIdIsValid(limitXmin) ||
2492  TransactionIdPrecedesOrEquals(pxmin, limitXmin))
2493  {
2494  VirtualTransactionId vxid;
2495 
2496  GET_VXID_FROM_PGPROC(vxid, *proc);
2497  if (VirtualTransactionIdIsValid(vxid))
2498  vxids[count++] = vxid;
2499  }
2500  }
2501  }
2502 
2503  LWLockRelease(ProcArrayLock);
2504 
2505  *nvxids = count;
2506  return vxids;
2507 }
2508 
2509 /*
2510  * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs.
2511  *
2512  * Usage is limited to conflict resolution during recovery on standby servers.
2513  * limitXmin is supplied as either latestRemovedXid, or InvalidTransactionId
2514  * in cases where we cannot accurately determine a value for latestRemovedXid.
2515  *
2516  * If limitXmin is InvalidTransactionId then we want to kill everybody,
2517  * so we're not worried if they have a snapshot or not, nor does it really
2518  * matter what type of lock we hold.
2519  *
2520  * All callers that are checking xmins always now supply a valid and useful
2521  * value for limitXmin. The limitXmin is always lower than the lowest
2522  * numbered KnownAssignedXid that is not already a FATAL error. This is
2523  * because we only care about cleanup records that are cleaning up tuple
2524  * versions from committed transactions. In that case they will only occur
2525  * at the point where the record is less than the lowest running xid. That
2526  * allows us to say that if any backend takes a snapshot concurrently with
2527  * us then the conflict assessment made here would never include the snapshot
2528  * that is being derived. So we take LW_SHARED on the ProcArray and allow
2529  * concurrent snapshots when limitXmin is valid. We might think about adding
2530  * Assert(limitXmin < lowest(KnownAssignedXids))
2531  * but that would not be true in the case of FATAL errors lagging in array,
2532  * but we already know those are bogus anyway, so we skip that test.
2533  *
2534  * If dbOid is valid we skip backends attached to other databases.
2535  *
2536  * Be careful to *not* pfree the result from this function. We reuse
2537  * this array sufficiently often that we use malloc for the result.
2538  */
2541 {
2542  static VirtualTransactionId *vxids;
2543  ProcArrayStruct *arrayP = procArray;
2544  int count = 0;
2545  int index;
2546 
2547  /*
2548  * If first time through, get workspace to remember main XIDs in. We
2549  * malloc it permanently to avoid repeated palloc/pfree overhead. Allow
2550  * result space, remembering room for a terminator.
2551  */
2552  if (vxids == NULL)
2553  {
2554  vxids = (VirtualTransactionId *)
2555  malloc(sizeof(VirtualTransactionId) * (arrayP->maxProcs + 1));
2556  if (vxids == NULL)
2557  ereport(ERROR,
2558  (errcode(ERRCODE_OUT_OF_MEMORY),
2559  errmsg("out of memory")));
2560  }
2561 
2562  LWLockAcquire(ProcArrayLock, LW_SHARED);
2563 
2564  for (index = 0; index < arrayP->numProcs; index++)
2565  {
2566  int pgprocno = arrayP->pgprocnos[index];
2567  volatile PGPROC *proc = &allProcs[pgprocno];
2568  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2569 
2570  /* Exclude prepared transactions */
2571  if (proc->pid == 0)
2572  continue;
2573 
2574  if (!OidIsValid(dbOid) ||
2575  proc->databaseId == dbOid)
2576  {
2577  /* Fetch xmin just once - can't change on us, but good coding */
2578  TransactionId pxmin = pgxact->xmin;
2579 
2580  /*
2581  * We ignore an invalid pxmin because this means that backend has
2582  * no snapshot currently. We hold a Share lock to avoid contention
2583  * with users taking snapshots. That is not a problem because the
2584  * current xmin is always at least one higher than the latest
2585  * removed xid, so any new snapshot would never conflict with the
2586  * test here.
2587  */
2588  if (!TransactionIdIsValid(limitXmin) ||
2589  (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin)))
2590  {
2591  VirtualTransactionId vxid;
2592 
2593  GET_VXID_FROM_PGPROC(vxid, *proc);
2594  if (VirtualTransactionIdIsValid(vxid))
2595  vxids[count++] = vxid;
2596  }
2597  }
2598  }
2599 
2600  LWLockRelease(ProcArrayLock);
2601 
2602  /* add the terminator */
2603  vxids[count].backendId = InvalidBackendId;
2605 
2606  return vxids;
2607 }
2608 
2609 /*
2610  * CancelVirtualTransaction - used in recovery conflict processing
2611  *
2612  * Returns pid of the process signaled, or 0 if not found.
2613  */
2614 pid_t
2616 {
2617  ProcArrayStruct *arrayP = procArray;
2618  int index;
2619  pid_t pid = 0;
2620 
2621  LWLockAcquire(ProcArrayLock, LW_SHARED);
2622 
2623  for (index = 0; index < arrayP->numProcs; index++)
2624  {
2625  int pgprocno = arrayP->pgprocnos[index];
2626  volatile PGPROC *proc = &allProcs[pgprocno];
2627  VirtualTransactionId procvxid;
2628 
2629  GET_VXID_FROM_PGPROC(procvxid, *proc);
2630 
2631  if (procvxid.backendId == vxid.backendId &&
2632  procvxid.localTransactionId == vxid.localTransactionId)
2633  {
2634  proc->recoveryConflictPending = true;
2635  pid = proc->pid;
2636  if (pid != 0)
2637  {
2638  /*
2639  * Kill the pid if it's still here. If not, that's what we
2640  * wanted so ignore any errors.
2641  */
2642  (void) SendProcSignal(pid, sigmode, vxid.backendId);
2643  }
2644  break;
2645  }
2646  }
2647 
2648  LWLockRelease(ProcArrayLock);
2649 
2650  return pid;
2651 }
2652 
2653 /*
2654  * MinimumActiveBackends --- count backends (other than myself) that are
2655  * in active transactions. Return true if the count exceeds the
2656  * minimum threshold passed. This is used as a heuristic to decide if
2657  * a pre-XLOG-flush delay is worthwhile during commit.
2658  *
2659  * Do not count backends that are blocked waiting for locks, since they are
2660  * not going to get to run until someone else commits.
2661  */
2662 bool
2664 {
2665  ProcArrayStruct *arrayP = procArray;
2666  int count = 0;
2667  int index;
2668 
2669  /* Quick short-circuit if no minimum is specified */
2670  if (min == 0)
2671  return true;
2672 
2673  /*
2674  * Note: for speed, we don't acquire ProcArrayLock. This is a little bit
2675  * bogus, but since we are only testing fields for zero or nonzero, it
2676  * should be OK. The result is only used for heuristic purposes anyway...
2677  */
2678  for (index = 0; index < arrayP->numProcs; index++)
2679  {
2680  int pgprocno = arrayP->pgprocnos[index];
2681  volatile PGPROC *proc = &allProcs[pgprocno];
2682  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2683 
2684  /*
2685  * Since we're not holding a lock, need to be prepared to deal with
2686  * garbage, as someone could have incremented numProcs but not yet
2687  * filled the structure.
2688  *
2689  * If someone just decremented numProcs, 'proc' could also point to a
2690  * PGPROC entry that's no longer in the array. It still points to a
2691  * PGPROC struct, though, because freed PGPROC entries just go to the
2692  * free list and are recycled. Its contents are nonsense in that case,
2693  * but that's acceptable for this function.
2694  */
2695  if (pgprocno == -1)
2696  continue; /* do not count deleted entries */
2697  if (proc == MyProc)
2698  continue; /* do not count myself */
2699  if (pgxact->xid == InvalidTransactionId)
2700  continue; /* do not count if no XID assigned */
2701  if (proc->pid == 0)
2702  continue; /* do not count prepared xacts */
2703  if (proc->waitLock != NULL)
2704  continue; /* do not count if blocked on a lock */
2705  count++;
2706  if (count >= min)
2707  break;
2708  }
2709 
2710  return count >= min;
2711 }
2712 
2713 /*
2714  * CountDBBackends --- count backends that are using specified database
2715  */
2716 int
2718 {
2719  ProcArrayStruct *arrayP = procArray;
2720  int count = 0;
2721  int index;
2722 
2723  LWLockAcquire(ProcArrayLock, LW_SHARED);
2724 
2725  for (index = 0; index < arrayP->numProcs; index++)
2726  {
2727  int pgprocno = arrayP->pgprocnos[index];
2728  volatile PGPROC *proc = &allProcs[pgprocno];
2729 
2730  if (proc->pid == 0)
2731  continue; /* do not count prepared xacts */
2732  if (!OidIsValid(databaseid) ||
2733  proc->databaseId == databaseid)
2734  count++;
2735  }
2736 
2737  LWLockRelease(ProcArrayLock);
2738 
2739  return count;
2740 }
2741 
2742 /*
2743  * CountDBConnections --- counts database backends ignoring any background
2744  * worker processes
2745  */
2746 int
2748 {
2749  ProcArrayStruct *arrayP = procArray;
2750  int count = 0;
2751  int index;
2752 
2753  LWLockAcquire(ProcArrayLock, LW_SHARED);
2754 
2755  for (index = 0; index < arrayP->numProcs; index++)
2756  {
2757  int pgprocno = arrayP->pgprocnos[index];
2758  volatile PGPROC *proc = &allProcs[pgprocno];
2759 
2760  if (proc->pid == 0)
2761  continue; /* do not count prepared xacts */
2762  if (proc->isBackgroundWorker)
2763  continue; /* do not count background workers */
2764  if (!OidIsValid(databaseid) ||
2765  proc->databaseId == databaseid)
2766  count++;
2767  }
2768 
2769  LWLockRelease(ProcArrayLock);
2770 
2771  return count;
2772 }
2773 
2774 /*
2775  * CancelDBBackends --- cancel backends that are using specified database
2776  */
2777 void
2778 CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
2779 {
2780  ProcArrayStruct *arrayP = procArray;
2781  int index;
2782  pid_t pid = 0;
2783 
2784  /* tell all backends to die */
2785  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2786 
2787  for (index = 0; index < arrayP->numProcs; index++)
2788  {
2789  int pgprocno = arrayP->pgprocnos[index];
2790  volatile PGPROC *proc = &allProcs[pgprocno];
2791 
2792  if (databaseid == InvalidOid || proc->databaseId == databaseid)
2793  {
2794  VirtualTransactionId procvxid;
2795 
2796  GET_VXID_FROM_PGPROC(procvxid, *proc);
2797 
2798  proc->recoveryConflictPending = conflictPending;
2799  pid = proc->pid;
2800  if (pid != 0)
2801  {
2802  /*
2803  * Kill the pid if it's still here. If not, that's what we
2804  * wanted so ignore any errors.
2805  */
2806  (void) SendProcSignal(pid, sigmode, procvxid.backendId);
2807  }
2808  }
2809  }
2810 
2811  LWLockRelease(ProcArrayLock);
2812 }
2813 
2814 /*
2815  * CountUserBackends --- count backends that are used by specified user
2816  */
2817 int
2819 {
2820  ProcArrayStruct *arrayP = procArray;
2821  int count = 0;
2822  int index;
2823 
2824  LWLockAcquire(ProcArrayLock, LW_SHARED);
2825 
2826  for (index = 0; index < arrayP->numProcs; index++)
2827  {
2828  int pgprocno = arrayP->pgprocnos[index];
2829  volatile PGPROC *proc = &allProcs[pgprocno];
2830 
2831  if (proc->pid == 0)
2832  continue; /* do not count prepared xacts */
2833  if (proc->isBackgroundWorker)
2834  continue; /* do not count background workers */
2835  if (proc->roleId == roleid)
2836  count++;
2837  }
2838 
2839  LWLockRelease(ProcArrayLock);
2840 
2841  return count;
2842 }
2843 
2844 /*
2845  * CountOtherDBBackends -- check for other backends running in the given DB
2846  *
2847  * If there are other backends in the DB, we will wait a maximum of 5 seconds
2848  * for them to exit. Autovacuum backends are encouraged to exit early by
2849  * sending them SIGTERM, but normal user backends are just waited for.
2850  *
2851  * The current backend is always ignored; it is caller's responsibility to
2852  * check whether the current backend uses the given DB, if it's important.
2853  *
2854  * Returns TRUE if there are (still) other backends in the DB, FALSE if not.
2855  * Also, *nbackends and *nprepared are set to the number of other backends
2856  * and prepared transactions in the DB, respectively.
2857  *
2858  * This function is used to interlock DROP DATABASE and related commands
2859  * against there being any active backends in the target DB --- dropping the
2860  * DB while active backends remain would be a Bad Thing. Note that we cannot
2861  * detect here the possibility of a newly-started backend that is trying to
2862  * connect to the doomed database, so additional interlocking is needed during
2863  * backend startup. The caller should normally hold an exclusive lock on the
2864  * target DB before calling this, which is one reason we mustn't wait
2865  * indefinitely.
2866  */
2867 bool
2868 CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
2869 {
2870  ProcArrayStruct *arrayP = procArray;
2871 
2872 #define MAXAUTOVACPIDS 10 /* max autovacs to SIGTERM per iteration */
2873  int autovac_pids[MAXAUTOVACPIDS];
2874  int tries;
2875 
2876  /* 50 tries with 100ms sleep between tries makes 5 sec total wait */
2877  for (tries = 0; tries < 50; tries++)
2878  {
2879  int nautovacs = 0;
2880  bool found = false;
2881  int index;
2882 
2884 
2885  *nbackends = *nprepared = 0;
2886 
2887  LWLockAcquire(ProcArrayLock, LW_SHARED);
2888 
2889  for (index = 0; index < arrayP->numProcs; index++)
2890  {
2891  int pgprocno = arrayP->pgprocnos[index];
2892  volatile PGPROC *proc = &allProcs[pgprocno];
2893  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2894 
2895  if (proc->databaseId != databaseId)
2896  continue;
2897  if (proc == MyProc)
2898  continue;
2899 
2900  found = true;
2901 
2902  if (proc->pid == 0)
2903  (*nprepared)++;
2904  else
2905  {
2906  (*nbackends)++;
2907  if ((pgxact->vacuumFlags & PROC_IS_AUTOVACUUM) &&
2908  nautovacs < MAXAUTOVACPIDS)
2909  autovac_pids[nautovacs++] = proc->pid;
2910  }
2911  }
2912 
2913  LWLockRelease(ProcArrayLock);
2914 
2915  if (!found)
2916  return false; /* no conflicting backends, so done */
2917 
2918  /*
2919  * Send SIGTERM to any conflicting autovacuums before sleeping. We
2920  * postpone this step until after the loop because we don't want to
2921  * hold ProcArrayLock while issuing kill(). We have no idea what might
2922  * block kill() inside the kernel...
2923  */
2924  for (index = 0; index < nautovacs; index++)
2925  (void) kill(autovac_pids[index], SIGTERM); /* ignore any error */
2926 
2927  /* sleep, then try again */
2928  pg_usleep(100 * 1000L); /* 100ms */
2929  }
2930 
2931  return true; /* timed out, still conflicts */
2932 }
2933 
2934 /*
2935  * ProcArraySetReplicationSlotXmin
2936  *
2937  * Install limits to future computations of the xmin horizon to prevent vacuum
2938  * and HOT pruning from removing affected rows still needed by clients with
2939  * replicaton slots.
2940  */
2941 void
2943  bool already_locked)
2944 {
2945  Assert(!already_locked || LWLockHeldByMe(ProcArrayLock));
2946 
2947  if (!already_locked)
2948  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2949 
2950  procArray->replication_slot_xmin = xmin;
2951  procArray->replication_slot_catalog_xmin = catalog_xmin;
2952 
2953  if (!already_locked)
2954  LWLockRelease(ProcArrayLock);
2955 }
2956 
2957 /*
2958  * ProcArrayGetReplicationSlotXmin
2959  *
2960  * Return the current slot xmin limits. That's useful to be able to remove
2961  * data that's older than those limits.
2962  */
2963 void
2965  TransactionId *catalog_xmin)
2966 {
2967  LWLockAcquire(ProcArrayLock, LW_SHARED);
2968 
2969  if (xmin != NULL)
2970  *xmin = procArray->replication_slot_xmin;
2971 
2972  if (catalog_xmin != NULL)
2973  *catalog_xmin = procArray->replication_slot_catalog_xmin;
2974 
2975  LWLockRelease(ProcArrayLock);
2976 }
2977 
2978 
2979 #define XidCacheRemove(i) \
2980  do { \
2981  MyProc->subxids.xids[i] = MyProc->subxids.xids[MyPgXact->nxids - 1]; \
2982  MyPgXact->nxids--; \
2983  } while (0)
2984 
2985 /*
2986  * XidCacheRemoveRunningXids
2987  *
2988  * Remove a bunch of TransactionIds from the list of known-running
2989  * subtransactions for my backend. Both the specified xid and those in
2990  * the xids[] array (of length nxids) are removed from the subxids cache.
2991  * latestXid must be the latest XID among the group.
2992  */
2993 void
2995  int nxids, const TransactionId *xids,
2996  TransactionId latestXid)
2997 {
2998  int i,
2999  j;
3000 
3002 
3003  /*
3004  * We must hold ProcArrayLock exclusively in order to remove transactions
3005  * from the PGPROC array. (See src/backend/access/transam/README.) It's
3006  * possible this could be relaxed since we know this routine is only used
3007  * to abort subtransactions, but pending closer analysis we'd best be
3008  * conservative.
3009  */
3010  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3011 
3012  /*
3013  * Under normal circumstances xid and xids[] will be in increasing order,
3014  * as will be the entries in subxids. Scan backwards to avoid O(N^2)
3015  * behavior when removing a lot of xids.
3016  */
3017  for (i = nxids - 1; i >= 0; i--)
3018  {
3019  TransactionId anxid = xids[i];
3020 
3021  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3022  {
3023  if (TransactionIdEquals(MyProc->subxids.xids[j], anxid))
3024  {
3025  XidCacheRemove(j);
3026  break;
3027  }
3028  }
3029 
3030  /*
3031  * Ordinarily we should have found it, unless the cache has
3032  * overflowed. However it's also possible for this routine to be
3033  * invoked multiple times for the same subtransaction, in case of an
3034  * error during AbortSubTransaction. So instead of Assert, emit a
3035  * debug warning.
3036  */
3037  if (j < 0 && !MyPgXact->overflowed)
3038  elog(WARNING, "did not find subXID %u in MyProc", anxid);
3039  }
3040 
3041  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3042  {
3043  if (TransactionIdEquals(MyProc->subxids.xids[j], xid))
3044  {
3045  XidCacheRemove(j);
3046  break;
3047  }
3048  }
3049  /* Ordinarily we should have found it, unless the cache has overflowed */
3050  if (j < 0 && !MyPgXact->overflowed)
3051  elog(WARNING, "did not find subXID %u in MyProc", xid);
3052 
3053  /* Also advance global latestCompletedXid while holding the lock */
3055  latestXid))
3057 
3058  LWLockRelease(ProcArrayLock);
3059 }
3060 
3061 #ifdef XIDCACHE_DEBUG
3062 
3063 /*
3064  * Print stats about effectiveness of XID cache
3065  */
3066 static void
3067 DisplayXidCache(void)
3068 {
3069  fprintf(stderr,
3070  "XidCache: xmin: %ld, known: %ld, myxact: %ld, latest: %ld, mainxid: %ld, childxid: %ld, knownassigned: %ld, nooflo: %ld, slow: %ld\n",
3071  xc_by_recent_xmin,
3072  xc_by_known_xact,
3073  xc_by_my_xact,
3074  xc_by_latest_xid,
3075  xc_by_main_xid,
3076  xc_by_child_xid,
3077  xc_by_known_assigned,
3078  xc_no_overflow,
3079  xc_slow_answer);
3080 }
3081 #endif /* XIDCACHE_DEBUG */
3082 
3083 
3084 /* ----------------------------------------------
3085  * KnownAssignedTransactions sub-module
3086  * ----------------------------------------------
3087  */
3088 
3089 /*
3090  * In Hot Standby mode, we maintain a list of transactions that are (or were)
3091  * running in the master at the current point in WAL. These XIDs must be
3092  * treated as running by standby transactions, even though they are not in
3093  * the standby server's PGXACT array.
3094  *
3095  * We record all XIDs that we know have been assigned. That includes all the
3096  * XIDs seen in WAL records, plus all unobserved XIDs that we can deduce have
3097  * been assigned. We can deduce the existence of unobserved XIDs because we
3098  * know XIDs are assigned in sequence, with no gaps. The KnownAssignedXids
3099  * list expands as new XIDs are observed or inferred, and contracts when
3100  * transaction completion records arrive.
3101  *
3102  * During hot standby we do not fret too much about the distinction between
3103  * top-level XIDs and subtransaction XIDs. We store both together in the
3104  * KnownAssignedXids list. In backends, this is copied into snapshots in
3105  * GetSnapshotData(), taking advantage of the fact that XidInMVCCSnapshot()
3106  * doesn't care about the distinction either. Subtransaction XIDs are
3107  * effectively treated as top-level XIDs and in the typical case pg_subtrans
3108  * links are *not* maintained (which does not affect visibility).
3109  *
3110  * We have room in KnownAssignedXids and in snapshots to hold maxProcs *
3111  * (1 + PGPROC_MAX_CACHED_SUBXIDS) XIDs, so every master transaction must
3112  * report its subtransaction XIDs in a WAL XLOG_XACT_ASSIGNMENT record at
3113  * least every PGPROC_MAX_CACHED_SUBXIDS. When we receive one of these
3114  * records, we mark the subXIDs as children of the top XID in pg_subtrans,
3115  * and then remove them from KnownAssignedXids. This prevents overflow of
3116  * KnownAssignedXids and snapshots, at the cost that status checks for these
3117  * subXIDs will take a slower path through TransactionIdIsInProgress().
3118  * This means that KnownAssignedXids is not necessarily complete for subXIDs,
3119  * though it should be complete for top-level XIDs; this is the same situation
3120  * that holds with respect to the PGPROC entries in normal running.
3121  *
3122  * When we throw away subXIDs from KnownAssignedXids, we need to keep track of
3123  * that, similarly to tracking overflow of a PGPROC's subxids array. We do
3124  * that by remembering the lastOverflowedXID, ie the last thrown-away subXID.
3125  * As long as that is within the range of interesting XIDs, we have to assume
3126  * that subXIDs are missing from snapshots. (Note that subXID overflow occurs
3127  * on primary when 65th subXID arrives, whereas on standby it occurs when 64th
3128  * subXID arrives - that is not an error.)
3129  *
3130  * Should a backend on primary somehow disappear before it can write an abort
3131  * record, then we just leave those XIDs in KnownAssignedXids. They actually
3132  * aborted but we think they were running; the distinction is irrelevant
3133  * because either way any changes done by the transaction are not visible to
3134  * backends in the standby. We prune KnownAssignedXids when
3135  * XLOG_RUNNING_XACTS arrives, to forestall possible overflow of the
3136  * array due to such dead XIDs.
3137  */
3138 
3139 /*
3140  * RecordKnownAssignedTransactionIds
3141  * Record the given XID in KnownAssignedXids, as well as any preceding
3142  * unobserved XIDs.
3143  *
3144  * RecordKnownAssignedTransactionIds() should be run for *every* WAL record
3145  * associated with a transaction. Must be called for each record after we
3146  * have executed StartupCLOG() et al, since we must ExtendCLOG() etc..
3147  *
3148  * Called during recovery in analogy with and in place of GetNewTransactionId()
3149  */
3150 void
3152 {
3156 
3157  elog(trace_recovery(DEBUG4), "record known xact %u latestObservedXid %u",
3158  xid, latestObservedXid);
3159 
3160  /*
3161  * When a newly observed xid arrives, it is frequently the case that it is
3162  * *not* the next xid in sequence. When this occurs, we must treat the
3163  * intervening xids as running also.
3164  */
3166  {
3167  TransactionId next_expected_xid;
3168 
3169  /*
3170  * Extend subtrans like we do in GetNewTransactionId() during normal
3171  * operation using individual extend steps. Note that we do not need
3172  * to extend clog since its extensions are WAL logged.
3173  *
3174  * This part has to be done regardless of standbyState since we
3175  * immediately start assigning subtransactions to their toplevel
3176  * transactions.
3177  */
3178  next_expected_xid = latestObservedXid;
3179  while (TransactionIdPrecedes(next_expected_xid, xid))
3180  {
3181  TransactionIdAdvance(next_expected_xid);
3182  ExtendSUBTRANS(next_expected_xid);
3183  }
3184  Assert(next_expected_xid == xid);
3185 
3186  /*
3187  * If the KnownAssignedXids machinery isn't up yet, there's nothing
3188  * more to do since we don't track assigned xids yet.
3189  */
3191  {
3192  latestObservedXid = xid;
3193  return;
3194  }
3195 
3196  /*
3197  * Add (latestObservedXid, xid] onto the KnownAssignedXids array.
3198  */
3199  next_expected_xid = latestObservedXid;
3200  TransactionIdAdvance(next_expected_xid);
3201  KnownAssignedXidsAdd(next_expected_xid, xid, false);
3202 
3203  /*
3204  * Now we can advance latestObservedXid
3205  */
3206  latestObservedXid = xid;
3207 
3208  /* ShmemVariableCache->nextXid must be beyond any observed xid */
3209  next_expected_xid = latestObservedXid;
3210  TransactionIdAdvance(next_expected_xid);
3211  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
3212  ShmemVariableCache->nextXid = next_expected_xid;
3213  LWLockRelease(XidGenLock);
3214  }
3215 }
3216 
3217 /*
3218  * ExpireTreeKnownAssignedTransactionIds
3219  * Remove the given XIDs from KnownAssignedXids.
3220  *
3221  * Called during recovery in analogy with and in place of ProcArrayEndTransaction()
3222  */
3223 void
3225  TransactionId *subxids, TransactionId max_xid)
3226 {
3228 
3229  /*
3230  * Uses same locking as transaction commit
3231  */
3232  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3233 
3234  KnownAssignedXidsRemoveTree(xid, nsubxids, subxids);
3235 
3236  /* As in ProcArrayEndTransaction, advance latestCompletedXid */
3238  max_xid))
3240 
3241  LWLockRelease(ProcArrayLock);
3242 }
3243 
3244 /*
3245  * ExpireAllKnownAssignedTransactionIds
3246  * Remove all entries in KnownAssignedXids
3247  */
3248 void
3250 {
3251  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3253  LWLockRelease(ProcArrayLock);
3254 }
3255 
3256 /*
3257  * ExpireOldKnownAssignedTransactionIds
3258  * Remove KnownAssignedXids entries preceding the given XID
3259  */
3260 void
3262 {
3263  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3265  LWLockRelease(ProcArrayLock);
3266 }
3267 
3268 
3269 /*
3270  * Private module functions to manipulate KnownAssignedXids
3271  *
3272  * There are 5 main uses of the KnownAssignedXids data structure:
3273  *
3274  * * backends taking snapshots - all valid XIDs need to be copied out
3275  * * backends seeking to determine presence of a specific XID
3276  * * startup process adding new known-assigned XIDs
3277  * * startup process removing specific XIDs as transactions end
3278  * * startup process pruning array when special WAL records arrive
3279  *
3280  * This data structure is known to be a hot spot during Hot Standby, so we
3281  * go to some lengths to make these operations as efficient and as concurrent
3282  * as possible.
3283  *
3284  * The XIDs are stored in an array in sorted order --- TransactionIdPrecedes
3285  * order, to be exact --- to allow binary search for specific XIDs. Note:
3286  * in general TransactionIdPrecedes would not provide a total order, but
3287  * we know that the entries present at any instant should not extend across
3288  * a large enough fraction of XID space to wrap around (the master would
3289  * shut down for fear of XID wrap long before that happens). So it's OK to
3290  * use TransactionIdPrecedes as a binary-search comparator.
3291  *
3292  * It's cheap to maintain the sortedness during insertions, since new known
3293  * XIDs are always reported in XID order; we just append them at the right.
3294  *
3295  * To keep individual deletions cheap, we need to allow gaps in the array.
3296  * This is implemented by marking array elements as valid or invalid using
3297  * the parallel boolean array KnownAssignedXidsValid[]. A deletion is done
3298  * by setting KnownAssignedXidsValid[i] to false, *without* clearing the
3299  * XID entry itself. This preserves the property that the XID entries are
3300  * sorted, so we can do binary searches easily. Periodically we compress
3301  * out the unused entries; that's much cheaper than having to compress the
3302  * array immediately on every deletion.
3303  *
3304  * The actually valid items in KnownAssignedXids[] and KnownAssignedXidsValid[]
3305  * are those with indexes tail <= i < head; items outside this subscript range
3306  * have unspecified contents. When head reaches the end of the array, we
3307  * force compression of unused entries rather than wrapping around, since
3308  * allowing wraparound would greatly complicate the search logic. We maintain
3309  * an explicit tail pointer so that pruning of old XIDs can be done without
3310  * immediately moving the array contents. In most cases only a small fraction
3311  * of the array contains valid entries at any instant.
3312  *
3313  * Although only the startup process can ever change the KnownAssignedXids
3314  * data structure, we still need interlocking so that standby backends will
3315  * not observe invalid intermediate states. The convention is that backends
3316  * must hold shared ProcArrayLock to examine the array. To remove XIDs from
3317  * the array, the startup process must hold ProcArrayLock exclusively, for
3318  * the usual transactional reasons (compare commit/abort of a transaction
3319  * during normal running). Compressing unused entries out of the array
3320  * likewise requires exclusive lock. To add XIDs to the array, we just insert
3321  * them into slots to the right of the head pointer and then advance the head
3322  * pointer. This wouldn't require any lock at all, except that on machines
3323  * with weak memory ordering we need to be careful that other processors
3324  * see the array element changes before they see the head pointer change.
3325  * We handle this by using a spinlock to protect reads and writes of the
3326  * head/tail pointers. (We could dispense with the spinlock if we were to
3327  * create suitable memory access barrier primitives and use those instead.)
3328  * The spinlock must be taken to read or write the head/tail pointers unless
3329  * the caller holds ProcArrayLock exclusively.
3330  *
3331  * Algorithmic analysis:
3332  *
3333  * If we have a maximum of M slots, with N XIDs currently spread across
3334  * S elements then we have N <= S <= M always.
3335  *
3336  * * Adding a new XID is O(1) and needs little locking (unless compression
3337  * must happen)
3338  * * Compressing the array is O(S) and requires exclusive lock
3339  * * Removing an XID is O(logS) and requires exclusive lock
3340  * * Taking a snapshot is O(S) and requires shared lock
3341  * * Checking for an XID is O(logS) and requires shared lock
3342  *
3343  * In comparison, using a hash table for KnownAssignedXids would mean that
3344  * taking snapshots would be O(M). If we can maintain S << M then the
3345  * sorted array technique will deliver significantly faster snapshots.
3346  * If we try to keep S too small then we will spend too much time compressing,
3347  * so there is an optimal point for any workload mix. We use a heuristic to
3348  * decide when to compress the array, though trimming also helps reduce
3349  * frequency of compressing. The heuristic requires us to track the number of
3350  * currently valid XIDs in the array.
3351  */
3352 
3353 
3354 /*
3355  * Compress KnownAssignedXids by shifting valid data down to the start of the
3356  * array, removing any gaps.
3357  *
3358  * A compression step is forced if "force" is true, otherwise we do it
3359  * only if a heuristic indicates it's a good time to do it.
3360  *
3361  * Caller must hold ProcArrayLock in exclusive mode.
3362  */
3363 static void
3365 {
3366  /* use volatile pointer to prevent code rearrangement */
3367  volatile ProcArrayStruct *pArray = procArray;
3368  int head,
3369  tail;
3370  int compress_index;
3371  int i;
3372 
3373  /* no spinlock required since we hold ProcArrayLock exclusively */
3374  head = pArray->headKnownAssignedXids;
3375  tail = pArray->tailKnownAssignedXids;
3376 
3377  if (!force)
3378  {
3379  /*
3380  * If we can choose how much to compress, use a heuristic to avoid
3381  * compressing too often or not often enough.
3382  *
3383  * Heuristic is if we have a large enough current spread and less than
3384  * 50% of the elements are currently in use, then compress. This
3385  * should ensure we compress fairly infrequently. We could compress
3386  * less often though the virtual array would spread out more and
3387  * snapshots would become more expensive.
3388  */
3389  int nelements = head - tail;
3390 
3391  if (nelements < 4 * PROCARRAY_MAXPROCS ||
3392  nelements < 2 * pArray->numKnownAssignedXids)
3393  return;
3394  }
3395 
3396  /*
3397  * We compress the array by reading the valid values from tail to head,
3398  * re-aligning data to 0th element.
3399  */
3400  compress_index = 0;
3401  for (i = tail; i < head; i++)
3402  {
3403  if (KnownAssignedXidsValid[i])
3404  {
3405  KnownAssignedXids[compress_index] = KnownAssignedXids[i];
3406  KnownAssignedXidsValid[compress_index] = true;
3407  compress_index++;
3408  }
3409  }
3410 
3411  pArray->tailKnownAssignedXids = 0;
3412  pArray->headKnownAssignedXids = compress_index;
3413 }
3414 
3415 /*
3416  * Add xids into KnownAssignedXids at the head of the array.
3417  *
3418  * xids from from_xid to to_xid, inclusive, are added to the array.
3419  *
3420  * If exclusive_lock is true then caller already holds ProcArrayLock in
3421  * exclusive mode, so we need no extra locking here. Else caller holds no
3422  * lock, so we need to be sure we maintain sufficient interlocks against
3423  * concurrent readers. (Only the startup process ever calls this, so no need
3424  * to worry about concurrent writers.)
3425  */
3426 static void
3428  bool exclusive_lock)
3429 {
3430  /* use volatile pointer to prevent code rearrangement */
3431  volatile ProcArrayStruct *pArray = procArray;
3432  TransactionId next_xid;
3433  int head,
3434  tail;
3435  int nxids;
3436  int i;
3437 
3438  Assert(TransactionIdPrecedesOrEquals(from_xid, to_xid));
3439 
3440  /*
3441  * Calculate how many array slots we'll need. Normally this is cheap; in
3442  * the unusual case where the XIDs cross the wrap point, we do it the hard
3443  * way.
3444  */
3445  if (to_xid >= from_xid)
3446  nxids = to_xid - from_xid + 1;
3447  else
3448  {
3449  nxids = 1;
3450  next_xid = from_xid;
3451  while (TransactionIdPrecedes(next_xid, to_xid))
3452  {
3453  nxids++;
3454  TransactionIdAdvance(next_xid);
3455  }
3456  }
3457 
3458  /*
3459  * Since only the startup process modifies the head/tail pointers, we
3460  * don't need a lock to read them here.
3461  */
3462  head = pArray->headKnownAssignedXids;
3463  tail = pArray->tailKnownAssignedXids;
3464 
3465  Assert(head >= 0 && head <= pArray->maxKnownAssignedXids);
3466  Assert(tail >= 0 && tail < pArray->maxKnownAssignedXids);
3467 
3468  /*
3469  * Verify that insertions occur in TransactionId sequence. Note that even
3470  * if the last existing element is marked invalid, it must still have a
3471  * correctly sequenced XID value.
3472  */
3473  if (head > tail &&
3474  TransactionIdFollowsOrEquals(KnownAssignedXids[head - 1], from_xid))
3475  {
3477  elog(ERROR, "out-of-order XID insertion in KnownAssignedXids");
3478  }
3479 
3480  /*
3481  * If our xids won't fit in the remaining space, compress out free space
3482  */
3483  if (head + nxids > pArray->maxKnownAssignedXids)
3484  {
3485  /* must hold lock to compress */
3486  if (!exclusive_lock)
3487  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3488 
3490 
3491  head = pArray->headKnownAssignedXids;
3492  /* note: we no longer care about the tail pointer */
3493 
3494  if (!exclusive_lock)
3495  LWLockRelease(ProcArrayLock);
3496 
3497  /*
3498  * If it still won't fit then we're out of memory
3499  */
3500  if (head + nxids > pArray->maxKnownAssignedXids)
3501  elog(ERROR, "too many KnownAssignedXids");
3502  }
3503 
3504  /* Now we can insert the xids into the space starting at head */
3505  next_xid = from_xid;
3506  for (i = 0; i < nxids; i++)
3507  {
3508  KnownAssignedXids[head] = next_xid;
3509  KnownAssignedXidsValid[head] = true;
3510  TransactionIdAdvance(next_xid);
3511  head++;
3512  }
3513 
3514  /* Adjust count of number of valid entries */
3515  pArray->numKnownAssignedXids += nxids;
3516 
3517  /*
3518  * Now update the head pointer. We use a spinlock to protect this
3519  * pointer, not because the update is likely to be non-atomic, but to
3520  * ensure that other processors see the above array updates before they
3521  * see the head pointer change.
3522  *
3523  * If we're holding ProcArrayLock exclusively, there's no need to take the
3524  * spinlock.
3525  */
3526  if (exclusive_lock)
3527  pArray->headKnownAssignedXids = head;
3528  else
3529  {
3531  pArray->headKnownAssignedXids = head;
3533  }
3534 }
3535 
3536 /*
3537  * KnownAssignedXidsSearch
3538  *
3539  * Searches KnownAssignedXids for a specific xid and optionally removes it.
3540  * Returns true if it was found, false if not.
3541  *
3542  * Caller must hold ProcArrayLock in shared or exclusive mode.
3543  * Exclusive lock must be held for remove = true.
3544  */
3545 static bool
3547 {
3548  /* use volatile pointer to prevent code rearrangement */
3549  volatile ProcArrayStruct *pArray = procArray;
3550  int first,
3551  last;
3552  int head;
3553  int tail;
3554  int result_index = -1;
3555 
3556  if (remove)
3557  {
3558  /* we hold ProcArrayLock exclusively, so no need for spinlock */
3559  tail = pArray->tailKnownAssignedXids;
3560  head = pArray->headKnownAssignedXids;
3561  }
3562  else
3563  {
3564  /* take spinlock to ensure we see up-to-date array contents */
3566  tail = pArray->tailKnownAssignedXids;
3567  head = pArray->headKnownAssignedXids;
3569  }
3570 
3571  /*
3572  * Standard binary search. Note we can ignore the KnownAssignedXidsValid
3573  * array here, since even invalid entries will contain sorted XIDs.
3574  */
3575  first = tail;
3576  last = head - 1;
3577  while (first <= last)
3578  {
3579  int mid_index;
3580  TransactionId mid_xid;
3581 
3582  mid_index = (first + last) / 2;
3583  mid_xid = KnownAssignedXids[mid_index];
3584 
3585  if (xid == mid_xid)
3586  {
3587  result_index = mid_index;
3588  break;
3589  }
3590  else if (TransactionIdPrecedes(xid, mid_xid))
3591  last = mid_index - 1;
3592  else
3593  first = mid_index + 1;
3594  }
3595 
3596  if (result_index < 0)
3597  return false; /* not in array */
3598 
3599  if (!KnownAssignedXidsValid[result_index])
3600  return false; /* in array, but invalid */
3601 
3602  if (remove)
3603  {
3604  KnownAssignedXidsValid[result_index] = false;
3605 
3606  pArray->numKnownAssignedXids--;
3607  Assert(pArray->numKnownAssignedXids >= 0);
3608 
3609  /*
3610  * If we're removing the tail element then advance tail pointer over
3611  * any invalid elements. This will speed future searches.
3612  */
3613  if (result_index == tail)
3614  {
3615  tail++;
3616  while (tail < head && !KnownAssignedXidsValid[tail])
3617  tail++;
3618  if (tail >= head)
3619  {
3620  /* Array is empty, so we can reset both pointers */
3621  pArray->headKnownAssignedXids = 0;
3622  pArray->tailKnownAssignedXids = 0;
3623  }
3624  else
3625  {
3626  pArray->tailKnownAssignedXids = tail;
3627  }
3628  }
3629  }
3630 
3631  return true;
3632 }
3633 
3634 /*
3635  * Is the specified XID present in KnownAssignedXids[]?
3636  *
3637  * Caller must hold ProcArrayLock in shared or exclusive mode.
3638  */
3639 static bool
3641 {
3643 
3644  return KnownAssignedXidsSearch(xid, false);
3645 }
3646 
3647 /*
3648  * Remove the specified XID from KnownAssignedXids[].
3649  *
3650  * Caller must hold ProcArrayLock in exclusive mode.
3651  */
3652 static void
3654 {
3656 
3657  elog(trace_recovery(DEBUG4), "remove KnownAssignedXid %u", xid);
3658 
3659  /*
3660  * Note: we cannot consider it an error to remove an XID that's not
3661  * present. We intentionally remove subxact IDs while processing
3662  * XLOG_XACT_ASSIGNMENT, to avoid array overflow. Then those XIDs will be
3663  * removed again when the top-level xact commits or aborts.
3664  *
3665  * It might be possible to track such XIDs to distinguish this case from
3666  * actual errors, but it would be complicated and probably not worth it.
3667  * So, just ignore the search result.
3668  */
3669  (void) KnownAssignedXidsSearch(xid, true);
3670 }
3671 
3672 /*
3673  * KnownAssignedXidsRemoveTree
3674  * Remove xid (if it's not InvalidTransactionId) and all the subxids.
3675  *
3676  * Caller must hold ProcArrayLock in exclusive mode.
3677  */
3678 static void
3680  TransactionId *subxids)
3681 {
3682  int i;
3683 
3684  if (TransactionIdIsValid(xid))
3686 
3687  for (i = 0; i < nsubxids; i++)
3688  KnownAssignedXidsRemove(subxids[i]);
3689 
3690  /* Opportunistically compress the array */
3692 }
3693 
3694 /*
3695  * Prune KnownAssignedXids up to, but *not* including xid. If xid is invalid
3696  * then clear the whole table.
3697  *
3698  * Caller must hold ProcArrayLock in exclusive mode.
3699  */
3700 static void
3702 {
3703  /* use volatile pointer to prevent code rearrangement */
3704  volatile ProcArrayStruct *pArray = procArray;
3705  int count = 0;
3706  int head,
3707  tail,
3708  i;
3709 
3710  if (!TransactionIdIsValid(removeXid))
3711  {
3712  elog(trace_recovery(DEBUG4), "removing all KnownAssignedXids");
3713  pArray->numKnownAssignedXids = 0;
3714  pArray->headKnownAssignedXids = pArray->tailKnownAssignedXids = 0;
3715  return;
3716  }
3717 
3718  elog(trace_recovery(DEBUG4), "prune KnownAssignedXids to %u", removeXid);
3719 
3720  /*
3721  * Mark entries invalid starting at the tail. Since array is sorted, we
3722  * can stop as soon as we reach an entry >= removeXid.
3723  */
3724  tail = pArray->tailKnownAssignedXids;
3725  head = pArray->headKnownAssignedXids;
3726 
3727  for (i = tail; i < head; i++)
3728  {
3729  if (KnownAssignedXidsValid[i])
3730  {
3731  TransactionId knownXid = KnownAssignedXids[i];
3732 
3733  if (TransactionIdFollowsOrEquals(knownXid, removeXid))
3734  break;
3735 
3736  if (!StandbyTransactionIdIsPrepared(knownXid))
3737  {
3738  KnownAssignedXidsValid[i] = false;
3739  count++;
3740  }
3741  }
3742  }
3743 
3744  pArray->numKnownAssignedXids -= count;
3745  Assert(pArray->numKnownAssignedXids >= 0);
3746 
3747  /*
3748  * Advance the tail pointer if we've marked the tail item invalid.
3749  */
3750  for (i = tail; i < head; i++)
3751  {
3752  if (KnownAssignedXidsValid[i])
3753  break;
3754  }
3755  if (i >= head)
3756  {
3757  /* Array is empty, so we can reset both pointers */
3758  pArray->headKnownAssignedXids = 0;
3759  pArray->tailKnownAssignedXids = 0;
3760  }
3761  else
3762  {
3763  pArray->tailKnownAssignedXids = i;
3764  }
3765 
3766  /* Opportunistically compress the array */
3768 }
3769 
3770 /*
3771  * KnownAssignedXidsGet - Get an array of xids by scanning KnownAssignedXids.
3772  * We filter out anything >= xmax.
3773  *
3774  * Returns the number of XIDs stored into xarray[]. Caller is responsible
3775  * that array is large enough.
3776  *
3777  * Caller must hold ProcArrayLock in (at least) shared mode.
3778  */
3779 static int
3781 {
3783 
3784  return KnownAssignedXidsGetAndSetXmin(xarray, &xtmp, xmax);
3785 }
3786 
3787 /*
3788  * KnownAssignedXidsGetAndSetXmin - as KnownAssignedXidsGet, plus
3789  * we reduce *xmin to the lowest xid value seen if not already lower.
3790  *
3791  * Caller must hold ProcArrayLock in (at least) shared mode.
3792  */
3793 static int
3795  TransactionId xmax)
3796 {
3797  int count = 0;
3798  int head,
3799  tail;
3800  int i;
3801 
3802  /*
3803  * Fetch head just once, since it may change while we loop. We can stop
3804  * once we reach the initially seen head, since we are certain that an xid
3805  * cannot enter and then leave the array while we hold ProcArrayLock. We
3806  * might miss newly-added xids, but they should be >= xmax so irrelevant
3807  * anyway.
3808  *
3809  * Must take spinlock to ensure we see up-to-date array contents.
3810  */
3812  tail = procArray->tailKnownAssignedXids;
3813  head = procArray->headKnownAssignedXids;
3815 
3816  for (i = tail; i < head; i++)
3817  {
3818  /* Skip any gaps in the array */
3819  if (KnownAssignedXidsValid[i])
3820  {
3821  TransactionId knownXid = KnownAssignedXids[i];
3822 
3823  /*
3824  * Update xmin if required. Only the first XID need be checked,
3825  * since the array is sorted.
3826  */
3827  if (count == 0 &&
3828  TransactionIdPrecedes(knownXid, *xmin))
3829  *xmin = knownXid;
3830 
3831  /*
3832  * Filter out anything >= xmax, again relying on sorted property
3833  * of array.
3834  */
3835  if (TransactionIdIsValid(xmax) &&
3836  TransactionIdFollowsOrEquals(knownXid, xmax))
3837  break;
3838 
3839  /* Add knownXid into output array */
3840  xarray[count++] = knownXid;
3841  }
3842  }
3843 
3844  return count;
3845 }
3846 
3847 /*
3848  * Get oldest XID in the KnownAssignedXids array, or InvalidTransactionId
3849  * if nothing there.
3850  */
3851 static TransactionId
3853 {
3854  int head,
3855  tail;
3856  int i;
3857 
3858  /*
3859  * Fetch head just once, since it may change while we loop.
3860  */
3862  tail = procArray->tailKnownAssignedXids;
3863  head = procArray->headKnownAssignedXids;
3865 
3866  for (i = tail; i < head; i++)
3867  {
3868  /* Skip any gaps in the array */
3869  if (KnownAssignedXidsValid[i])
3870  return KnownAssignedXids[i];
3871  }
3872 
3873  return InvalidTransactionId;
3874 }
3875 
3876 /*
3877  * Display KnownAssignedXids to provide debug trail
3878  *
3879  * Currently this is only called within startup process, so we need no
3880  * special locking.
3881  *
3882  * Note this is pretty expensive, and much of the expense will be incurred
3883  * even if the elog message will get discarded. It's not currently called
3884  * in any performance-critical places, however, so no need to be tenser.
3885  */
3886 static void
3888 {
3889  /* use volatile pointer to prevent code rearrangement */
3890  volatile ProcArrayStruct *pArray = procArray;
3892  int head,
3893  tail,
3894  i;
3895  int nxids = 0;
3896 
3897  tail = pArray->tailKnownAssignedXids;
3898  head = pArray->headKnownAssignedXids;
3899 
3900  initStringInfo(&buf);
3901 
3902  for (i = tail; i < head; i++)
3903  {
3904  if (KnownAssignedXidsValid[i])
3905  {
3906  nxids++;
3907  appendStringInfo(&buf, "[%d]=%u ", i, KnownAssignedXids[i]);
3908  }
3909  }
3910 
3911  elog(trace_level, "%d KnownAssignedXids (num=%d tail=%d head=%d) %s",
3912  nxids,
3913  pArray->numKnownAssignedXids,
3914  pArray->tailKnownAssignedXids,
3915  pArray->headKnownAssignedXids,
3916  buf.data);
3917 
3918  pfree(buf.data);
3919 }
3920 
3921 /*
3922  * KnownAssignedXidsReset
3923  * Resets KnownAssignedXids to be empty
3924  */
3925 static void
3927 {
3928  /* use volatile pointer to prevent code rearrangement */
3929  volatile ProcArrayStruct *pArray = procArray;
3930 
3931  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3932 
3933  pArray->numKnownAssignedXids = 0;
3934  pArray->tailKnownAssignedXids = 0;
3935  pArray->headKnownAssignedXids = 0;
3936 
3937  LWLockRelease(ProcArrayLock);
3938 }
#define TransactionIdAdvance(dest)
Definition: transam.h:48
int slock_t
Definition: s_lock.h:888
void ProcArrayApplyRecoveryInfo(RunningTransactions running)
Definition: procarray.c:664
#define XidCacheRemove(i)
Definition: procarray.c:2979
static TransactionId latestObservedXid
Definition: procarray.c:107
bool ProcArrayInstallImportedXmin(TransactionId xmin, TransactionId sourcexid)
Definition: procarray.c:1786
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:2452
TransactionId oldestRunningXid
Definition: standby.h:76
bool procArrayGroupMember
Definition: proc.h:157
pid_t CancelVirtualTransaction(VirtualTransactionId vxid, ProcSignalReason sigmode)
Definition: procarray.c:2615
#define PROCARRAY_MAXPROCS
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int CountDBBackends(Oid databaseid)
Definition: procarray.c:2717
#define DEBUG1
Definition: elog.h:25
static void KnownAssignedXidsDisplay(int trace_level)
Definition: procarray.c:3887
#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:52
uint32 TransactionId
Definition: c.h:397
bool copied
Definition: snapshot.h:94
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:323
Definition: proc.h:202
#define DEBUG3
Definition: elog.h:23
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:146
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
TransactionId xmin
Definition: proc.h:208
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:321
PGPROC * BackendPidGetProc(int pid)
Definition: procarray.c:2324
PGXACT * allPgXact
Definition: proc.h:229
PGPROC * MyProc
Definition: proc.c:67
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:995
TransactionId xid
Definition: proc.h:204
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
void SubTransSetParent(TransactionId xid, TransactionId parent, bool overwriteOK)
Definition: subtrans.c:75
int vacuum_defer_cleanup_age
Definition: standby.c:37
#define SpinLockInit(lock)
Definition: spin.h:60
VirtualTransactionId * GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid)
Definition: procarray.c:2540
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:91
XLogRecPtr lsn
Definition: snapshot.h:112
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2232
static void ProcArrayGroupClearXid(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:482
#define xc_by_my_xact_inc()
Definition: procarray.c:144
Oid roleId
Definition: proc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId RecentXmin
Definition: snapmgr.c:165
slock_t known_assigned_xids_lck
Definition: procarray.c:77
PROC_HDR * ProcGlobal
Definition: proc.c:80
bool suboverflowed
Definition: snapshot.h:91
TransactionId * xids
Definition: standby.h:79
return result
Definition: formatting.c:1618
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7863
#define TransactionIdRetreat(dest)
Definition: transam.h:56
LocalTransactionId localTransactionId
Definition: lock.h:66
void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:394
#define xc_by_child_xid_inc()
Definition: procarray.c:147
bool TransactionIdIsKnownCompleted(TransactionId transactionId)
Definition: transam.c:238
#define DEBUG4
Definition: elog.h:22
void ExpireTreeKnownAssignedTransactionIds(TransactionId xid, int nsubxids, TransactionId *subxids, TransactionId max_xid)
Definition: procarray.c:3224
#define MAXAUTOVACPIDS
uint32 regd_count
Definition: snapshot.h:108
#define OidIsValid(objectId)
Definition: c.h:538
void ProcArrayGetReplicationSlotXmin(TransactionId *xmin, TransactionId *catalog_xmin)
Definition: procarray.c:2964
void ExpireAllKnownAssignedTransactionIds(void)
Definition: procarray.c:3249
PGXACT * MyPgXact
Definition: proc.c:68
int trace_recovery(int trace_level)
Definition: elog.c:3753
uint8 vacuumFlags
Definition: proc.h:213
#define PROC_VACUUM_STATE_MASK
Definition: proc.h:56
TransactionId TransactionXmin
Definition: snapmgr.c:164
TransactionId latestCompletedXid
Definition: standby.h:77
Definition: type.h:90
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
bool isBackgroundWorker
Definition: proc.h:111
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:75
#define xc_by_recent_xmin_inc()
Definition: procarray.c:142
#define xc_by_known_xact_inc()
Definition: procarray.c:143
bool MinimumActiveBackends(int min)
Definition: procarray.c:2663
static void KnownAssignedXidsRemovePreceding(TransactionId xid)
Definition: procarray.c:3701
PGPROC * BackendPidGetProcWithLock(int pid)
Definition: procarray.c:2347
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:179
void pfree(void *pointer)
Definition: mcxt.c:950
#define PROC_IN_VACUUM
Definition: proc.h:49
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
int CountDBConnections(Oid databaseid)
Definition: procarray.c:2747
#define FirstNormalTransactionId
Definition: transam.h:34
#define ERROR
Definition: elog.h:43
void XidCacheRemoveRunningXids(TransactionId xid, int nxids, const TransactionId *xids, TransactionId latestXid)
Definition: procarray.c:2994
TimestampTz GetSnapshotCurrentTimestamp(void)
Definition: snapmgr.c:1634
void ProcArrayClearTransaction(PGPROC *proc)
Definition: procarray.c:601
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
void ExtendSUBTRANS(TransactionId newestXact)
Definition: subtrans.c:311
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:331
#define FATAL
Definition: elog.h:52
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:11089
TransactionId nextXid
Definition: transam.h:117
void CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
Definition: procarray.c:2778
#define xc_by_main_xid_inc()
Definition: procarray.c:146
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1283
static char * buf
Definition: pg_test_fsync.c:65
bool recoveryConflictPending
Definition: proc.h:118
#define memmove(d, s, c)
Definition: c.h:1058
#define xc_by_known_assigned_inc()
Definition: procarray.c:148
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
uint8 nxids
Definition: proc.h:218
VariableCache ShmemVariableCache
Definition: varsup.c:34
int maxKnownAssignedXids
Definition: procarray.c:73
#define InvalidTransactionId
Definition: transam.h:31
bool StandbyTransactionIdIsPrepared(TransactionId xid)
Definition: twophase.c:1297
static PGPROC * allProcs
Definition: procarray.c:99
Oid databaseId
Definition: proc.h:108
unsigned int uint32
Definition: c.h:268
TransactionId xmax
Definition: snapshot.h:67
TransactionId xmin
Definition: snapshot.h:66
static void KnownAssignedXidsReset(void)
Definition: procarray.c:3926
LOCK * waitLock
Definition: proc.h:130
int numKnownAssignedXids
Definition: procarray.c:74
TransactionId RecentGlobalDataXmin
Definition: snapmgr.c:167
static bool * KnownAssignedXidsValid
Definition: procarray.c:106
struct XidCache subxids
Definition: proc.h:153
TransactionId lastOverflowedXid
Definition: procarray.c:86
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
#define xc_by_latest_xid_inc()
Definition: procarray.c:145
bool delayChkpt
Definition: proc.h:215
#define INVALID_PGPROCNO
Definition: proc.h:71
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:77
static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:3679
pg_atomic_uint32 procArrayGroupNext
Definition: proc.h:159
Definition: proc.h:224
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
static ProcArrayStruct * procArray
Definition: procarray.c:97
#define WARNING
Definition: elog.h:40
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:72
#define SpinLockRelease(lock)
Definition: spin.h:64
TransactionId replication_slot_xmin
Definition: procarray.c:89
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
int BackendXidGetPid(TransactionId xid)
Definition: procarray.c:2384
#define InvalidBackendId
Definition: backendid.h:23
static PGXACT * allPgXact
Definition: procarray.c:100
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:560
static int KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax)
Definition: procarray.c:3780
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
Oid MyDatabaseId
Definition: globals.c:76
static TransactionId KnownAssignedXidsGetOldestXmin(void)
Definition: procarray.c:3852
bool overflowed
Definition: proc.h:214
void StandbyReleaseOldLocks(int nxids, TransactionId *xids)
Definition: standby.c:725
static void ProcArrayEndTransactionInternal(PGPROC *proc, PGXACT *pgxact, TransactionId latestXid)
Definition: procarray.c:448
#define InvalidOid
Definition: postgres_ext.h:36
CommandId curcid
Definition: snapshot.h:96
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:1446
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1307
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:94
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:39
#define TOTAL_MAX_CACHED_SUBXIDS
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static TransactionId * KnownAssignedXids
Definition: procarray.c:105
BackendId backendId
Definition: lock.h:65
void CreateSharedProcArray(void)
Definition: procarray.c:220
bool takenDuringRecovery
Definition: snapshot.h:93
size_t Size
Definition: c.h:356
Snapshot GetSnapshotData(Snapshot snapshot)
Definition: procarray.c:1498
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
void LWLockRegisterTranche(int tranche_id, char *tranche_name)
Definition: lwlock.c:592
static int KnownAssignedXidsGetAndSetXmin(TransactionId *xarray, TransactionId *xmin, TransactionId xmax)
Definition: procarray.c:3794
static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid, bool exclusive_lock)
Definition: procarray.c:3427
bool ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc)
Definition: procarray.c:1858
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:62
#define xc_no_overflow_inc()
Definition: procarray.c:149
bool EnableHotStandby
Definition: xlog.c:96
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:303
static void KnownAssignedXidsCompress(bool force)
Definition: procarray.c:3364
int CountUserBackends(Oid roleid)
Definition: procarray.c:2818
TransactionId GetOldestSafeDecodingTransactionId(void)
Definition: procarray.c:2144
static bool KnownAssignedXidExists(TransactionId xid)
Definition: procarray.c:3640
int pgprocno
Definition: proc.h:104
TransactionId nextXid
Definition: standby.h:75
bool TransactionIdIsActive(TransactionId xid)
Definition: procarray.c:1212
#define xc_slow_answer_inc()
Definition: procarray.c:150
pg_atomic_uint32 procArrayGroupFirst
Definition: proc.h:239
void ProcArrayInitRecovery(TransactionId initializedUptoXID)
Definition: procarray.c:633
uint32 xcnt
Definition: snapshot.h:78
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
struct ProcArrayStruct ProcArrayStruct
static bool KnownAssignedXidsSearch(TransactionId xid, bool remove)
Definition: procarray.c:3546
static void KnownAssignedXidsRemove(TransactionId xid)
Definition: procarray.c:3653
int old_snapshot_threshold
Definition: snapmgr.c:74
#define InvalidLocalTransactionId
Definition: lock.h:70
int i
void ExpireOldKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3261
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2078
bool IsBackendPid(int pid)
Definition: procarray.c:2419
#define pg_write_barrier()
Definition: atomics.h:161
ProcSignalReason
Definition: procsignal.h:30
void ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
Definition: procarray.c:2942
int GetMaxSnapshotSubxidCount(void)
Definition: procarray.c:1457
RunningTransactions GetRunningTransactionData(void)
Definition: procarray.c:1920
void ProcArrayApplyXidAssignment(TransactionId topxid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:911
TimestampTz whenTaken
Definition: snapshot.h:111
PGPROC * allProcs
Definition: proc.h:227
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2868
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:687
#define elog
Definition: elog.h:219
#define qsort(a, b, c, d)
Definition: port.h:440
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:268
void MaintainOldSnapshotTimeMapping(TimestampTz whenTaken, TransactionId xmin)
Definition: snapmgr.c:1796
PGSemaphore sem
Definition: proc.h:95
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2277
void RecordKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3151
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
int tailKnownAssignedXids
Definition: procarray.c:75
static TransactionId standbySnapshotPendingXmin
Definition: procarray.c:114
Definition: proc.h:89
int pid
Definition: proc.h:103
HotStandbyState standbyState
Definition: xlog.c:195
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:273
#define PROC_IS_AUTOVACUUM
Definition: proc.h:48
#define offsetof(type, field)
Definition: c.h:555
TransactionId procArrayGroupMemberXid
Definition: proc.h:165
Size ProcArrayShmemSize(void)
Definition: procarray.c:178
TransactionId * subxip
Definition: snapshot.h:89
uint32 active_count
Definition: snapshot.h:107
int headKnownAssignedXids
Definition: procarray.c:76
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:138
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:251
int32 subxcnt
Definition: snapshot.h:90
LocalTransactionId lxid
Definition: proc.h:100
TransactionId latestCompletedXid
Definition: transam.h:135