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  * Ooops, 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  /* Ooops */
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_clog.
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_clog 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  * If ignoreVacuum is TRUE then backends with the PROC_IN_VACUUM flag set are
1264  * ignored.
1265  *
1266  * This is used by VACUUM to decide which deleted tuples must be preserved in
1267  * the passed in table. For shared relations backends in all databases must be
1268  * considered, but for non-shared relations that's not required, since only
1269  * backends in my own database could ever see the tuples in them. Also, we can
1270  * ignore concurrently running lazy VACUUMs because (a) they must be working
1271  * on other tables, and (b) they don't need to do snapshot-based lookups.
1272  *
1273  * This is also used to determine where to truncate pg_subtrans. For that
1274  * backends in all databases have to be considered, so rel = NULL has to be
1275  * passed in.
1276  *
1277  * Note: we include all currently running xids in the set of considered xids.
1278  * This ensures that if a just-started xact has not yet set its snapshot,
1279  * when it does set the snapshot it cannot set xmin less than what we compute.
1280  * See notes in src/backend/access/transam/README.
1281  *
1282  * Note: despite the above, it's possible for the calculated value to move
1283  * backwards on repeated calls. The calculated value is conservative, so that
1284  * anything older is definitely not considered as running by anyone anymore,
1285  * but the exact value calculated depends on a number of things. For example,
1286  * if rel = NULL and there are no transactions running in the current
1287  * database, GetOldestXmin() returns latestCompletedXid. If a transaction
1288  * begins after that, its xmin will include in-progress transactions in other
1289  * databases that started earlier, so another call will return a lower value.
1290  * Nonetheless it is safe to vacuum a table in the current database with the
1291  * first result. There are also replication-related effects: a walsender
1292  * process can set its xmin based on transactions that are no longer running
1293  * in the master but are still being replayed on the standby, thus possibly
1294  * making the GetOldestXmin reading go backwards. In this case there is a
1295  * possibility that we lose data that the standby would like to have, but
1296  * there is little we can do about that --- data is only protected if the
1297  * walsender runs continuously while queries are executed on the standby.
1298  * (The Hot Standby code deals with such cases by failing standby queries
1299  * that needed to access already-removed data, so there's no integrity bug.)
1300  * The return value is also adjusted with vacuum_defer_cleanup_age, so
1301  * increasing that setting on the fly is another easy way to make
1302  * GetOldestXmin() move backwards, with no consequences for data integrity.
1303  */
1305 GetOldestXmin(Relation rel, bool ignoreVacuum)
1306 {
1307  ProcArrayStruct *arrayP = procArray;
1308  TransactionId result;
1309  int index;
1310  bool allDbs;
1311 
1312  volatile TransactionId replication_slot_xmin = InvalidTransactionId;
1313  volatile TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1314 
1315  /*
1316  * If we're not computing a relation specific limit, or if a shared
1317  * relation has been passed in, backends in all databases have to be
1318  * considered.
1319  */
1320  allDbs = rel == NULL || rel->rd_rel->relisshared;
1321 
1322  /* Cannot look for individual databases during recovery */
1323  Assert(allDbs || !RecoveryInProgress());
1324 
1325  LWLockAcquire(ProcArrayLock, LW_SHARED);
1326 
1327  /*
1328  * We initialize the MIN() calculation with latestCompletedXid + 1. This
1329  * is a lower bound for the XIDs that might appear in the ProcArray later,
1330  * and so protects us against overestimating the result due to future
1331  * additions.
1332  */
1334  Assert(TransactionIdIsNormal(result));
1335  TransactionIdAdvance(result);
1336 
1337  for (index = 0; index < arrayP->numProcs; index++)
1338  {
1339  int pgprocno = arrayP->pgprocnos[index];
1340  volatile PGPROC *proc = &allProcs[pgprocno];
1341  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1342 
1343  /*
1344  * Backend is doing logical decoding which manages xmin separately,
1345  * check below.
1346  */
1347  if (pgxact->vacuumFlags & PROC_IN_LOGICAL_DECODING)
1348  continue;
1349 
1350  if (ignoreVacuum && (pgxact->vacuumFlags & PROC_IN_VACUUM))
1351  continue;
1352 
1353  if (allDbs ||
1354  proc->databaseId == MyDatabaseId ||
1355  proc->databaseId == 0) /* always include WalSender */
1356  {
1357  /* Fetch xid just once - see GetNewTransactionId */
1358  TransactionId xid = pgxact->xid;
1359 
1360  /* First consider the transaction's own Xid, if any */
1361  if (TransactionIdIsNormal(xid) &&
1362  TransactionIdPrecedes(xid, result))
1363  result = xid;
1364 
1365  /*
1366  * Also consider the transaction's Xmin, if set.
1367  *
1368  * We must check both Xid and Xmin because a transaction might
1369  * have an Xmin but not (yet) an Xid; conversely, if it has an
1370  * Xid, that could determine some not-yet-set Xmin.
1371  */
1372  xid = pgxact->xmin; /* Fetch just once */
1373  if (TransactionIdIsNormal(xid) &&
1374  TransactionIdPrecedes(xid, result))
1375  result = xid;
1376  }
1377  }
1378 
1379  /* fetch into volatile var while ProcArrayLock is held */
1380  replication_slot_xmin = procArray->replication_slot_xmin;
1381  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1382 
1383  if (RecoveryInProgress())
1384  {
1385  /*
1386  * Check to see whether KnownAssignedXids contains an xid value older
1387  * than the main procarray.
1388  */
1390 
1391  LWLockRelease(ProcArrayLock);
1392 
1393  if (TransactionIdIsNormal(kaxmin) &&
1394  TransactionIdPrecedes(kaxmin, result))
1395  result = kaxmin;
1396  }
1397  else
1398  {
1399  /*
1400  * No other information needed, so release the lock immediately.
1401  */
1402  LWLockRelease(ProcArrayLock);
1403 
1404  /*
1405  * Compute the cutoff XID by subtracting vacuum_defer_cleanup_age,
1406  * being careful not to generate a "permanent" XID.
1407  *
1408  * vacuum_defer_cleanup_age provides some additional "slop" for the
1409  * benefit of hot standby queries on slave servers. This is quick and
1410  * dirty, and perhaps not all that useful unless the master has a
1411  * predictable transaction rate, but it offers some protection when
1412  * there's no walsender connection. Note that we are assuming
1413  * vacuum_defer_cleanup_age isn't large enough to cause wraparound ---
1414  * so guc.c should limit it to no more than the xidStopLimit threshold
1415  * in varsup.c. Also note that we intentionally don't apply
1416  * vacuum_defer_cleanup_age on standby servers.
1417  */
1418  result -= vacuum_defer_cleanup_age;
1419  if (!TransactionIdIsNormal(result))
1420  result = FirstNormalTransactionId;
1421  }
1422 
1423  /*
1424  * Check whether there are replication slots requiring an older xmin.
1425  */
1426  if (TransactionIdIsValid(replication_slot_xmin) &&
1427  NormalTransactionIdPrecedes(replication_slot_xmin, result))
1428  result = replication_slot_xmin;
1429 
1430  /*
1431  * After locks have been released and defer_cleanup_age has been applied,
1432  * check whether we need to back up further to make logical decoding
1433  * possible. We need to do so if we're computing the global limit (rel =
1434  * NULL) or if the passed relation is a catalog relation of some kind.
1435  */
1436  if ((rel == NULL ||
1438  TransactionIdIsValid(replication_slot_catalog_xmin) &&
1439  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, result))
1440  result = replication_slot_catalog_xmin;
1441 
1442  return result;
1443 }
1444 
1445 /*
1446  * GetMaxSnapshotXidCount -- get max size for snapshot XID array
1447  *
1448  * We have to export this for use by snapmgr.c.
1449  */
1450 int
1452 {
1453  return procArray->maxProcs;
1454 }
1455 
1456 /*
1457  * GetMaxSnapshotSubxidCount -- get max size for snapshot sub-XID array
1458  *
1459  * We have to export this for use by snapmgr.c.
1460  */
1461 int
1463 {
1464  return TOTAL_MAX_CACHED_SUBXIDS;
1465 }
1466 
1467 /*
1468  * GetSnapshotData -- returns information about running transactions.
1469  *
1470  * The returned snapshot includes xmin (lowest still-running xact ID),
1471  * xmax (highest completed xact ID + 1), and a list of running xact IDs
1472  * in the range xmin <= xid < xmax. It is used as follows:
1473  * All xact IDs < xmin are considered finished.
1474  * All xact IDs >= xmax are considered still running.
1475  * For an xact ID xmin <= xid < xmax, consult list to see whether
1476  * it is considered running or not.
1477  * This ensures that the set of transactions seen as "running" by the
1478  * current xact will not change after it takes the snapshot.
1479  *
1480  * All running top-level XIDs are included in the snapshot, except for lazy
1481  * VACUUM processes. We also try to include running subtransaction XIDs,
1482  * but since PGPROC has only a limited cache area for subxact XIDs, full
1483  * information may not be available. If we find any overflowed subxid arrays,
1484  * we have to mark the snapshot's subxid data as overflowed, and extra work
1485  * *may* need to be done to determine what's running (see XidInMVCCSnapshot()
1486  * in tqual.c).
1487  *
1488  * We also update the following backend-global variables:
1489  * TransactionXmin: the oldest xmin of any snapshot in use in the
1490  * current transaction (this is the same as MyPgXact->xmin).
1491  * RecentXmin: the xmin computed for the most recent snapshot. XIDs
1492  * older than this are known not running any more.
1493  * RecentGlobalXmin: the global xmin (oldest TransactionXmin across all
1494  * running transactions, except those running LAZY VACUUM). This is
1495  * the same computation done by GetOldestXmin(true, true).
1496  * RecentGlobalDataXmin: the global xmin for non-catalog tables
1497  * >= RecentGlobalXmin
1498  *
1499  * Note: this function should probably not be called with an argument that's
1500  * not statically allocated (see xip allocation below).
1501  */
1502 Snapshot
1504 {
1505  ProcArrayStruct *arrayP = procArray;
1506  TransactionId xmin;
1507  TransactionId xmax;
1508  TransactionId globalxmin;
1509  int index;
1510  int count = 0;
1511  int subcount = 0;
1512  bool suboverflowed = false;
1513  volatile TransactionId replication_slot_xmin = InvalidTransactionId;
1514  volatile TransactionId replication_slot_catalog_xmin = InvalidTransactionId;
1515 
1516  Assert(snapshot != NULL);
1517 
1518  /*
1519  * Allocating space for maxProcs xids is usually overkill; numProcs would
1520  * be sufficient. But it seems better to do the malloc while not holding
1521  * the lock, so we can't look at numProcs. Likewise, we allocate much
1522  * more subxip storage than is probably needed.
1523  *
1524  * This does open a possibility for avoiding repeated malloc/free: since
1525  * maxProcs does not change at runtime, we can simply reuse the previous
1526  * xip arrays if any. (This relies on the fact that all callers pass
1527  * static SnapshotData structs.)
1528  */
1529  if (snapshot->xip == NULL)
1530  {
1531  /*
1532  * First call for this snapshot. Snapshot is same size whether or not
1533  * we are in recovery, see later comments.
1534  */
1535  snapshot->xip = (TransactionId *)
1537  if (snapshot->xip == NULL)
1538  ereport(ERROR,
1539  (errcode(ERRCODE_OUT_OF_MEMORY),
1540  errmsg("out of memory")));
1541  Assert(snapshot->subxip == NULL);
1542  snapshot->subxip = (TransactionId *)
1544  if (snapshot->subxip == NULL)
1545  ereport(ERROR,
1546  (errcode(ERRCODE_OUT_OF_MEMORY),
1547  errmsg("out of memory")));
1548  }
1549 
1550  /*
1551  * It is sufficient to get shared lock on ProcArrayLock, even if we are
1552  * going to set MyPgXact->xmin.
1553  */
1554  LWLockAcquire(ProcArrayLock, LW_SHARED);
1555 
1556  /* xmax is always latestCompletedXid + 1 */
1559  TransactionIdAdvance(xmax);
1560 
1561  /* initialize xmin calculation with xmax */
1562  globalxmin = xmin = xmax;
1563 
1565 
1566  if (!snapshot->takenDuringRecovery)
1567  {
1568  int *pgprocnos = arrayP->pgprocnos;
1569  int numProcs;
1570 
1571  /*
1572  * Spin over procArray checking xid, xmin, and subxids. The goal is
1573  * to gather all active xids, find the lowest xmin, and try to record
1574  * subxids.
1575  */
1576  numProcs = arrayP->numProcs;
1577  for (index = 0; index < numProcs; index++)
1578  {
1579  int pgprocno = pgprocnos[index];
1580  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1581  TransactionId xid;
1582 
1583  /*
1584  * Backend is doing logical decoding which manages xmin
1585  * separately, check below.
1586  */
1587  if (pgxact->vacuumFlags & PROC_IN_LOGICAL_DECODING)
1588  continue;
1589 
1590  /* Ignore procs running LAZY VACUUM */
1591  if (pgxact->vacuumFlags & PROC_IN_VACUUM)
1592  continue;
1593 
1594  /* Update globalxmin to be the smallest valid xmin */
1595  xid = pgxact->xmin; /* fetch just once */
1596  if (TransactionIdIsNormal(xid) &&
1597  NormalTransactionIdPrecedes(xid, globalxmin))
1598  globalxmin = xid;
1599 
1600  /* Fetch xid just once - see GetNewTransactionId */
1601  xid = pgxact->xid;
1602 
1603  /*
1604  * If the transaction has no XID assigned, we can skip it; it
1605  * won't have sub-XIDs either. If the XID is >= xmax, we can also
1606  * skip it; such transactions will be treated as running anyway
1607  * (and any sub-XIDs will also be >= xmax).
1608  */
1609  if (!TransactionIdIsNormal(xid)
1610  || !NormalTransactionIdPrecedes(xid, xmax))
1611  continue;
1612 
1613  /*
1614  * We don't include our own XIDs (if any) in the snapshot, but we
1615  * must include them in xmin.
1616  */
1617  if (NormalTransactionIdPrecedes(xid, xmin))
1618  xmin = xid;
1619  if (pgxact == MyPgXact)
1620  continue;
1621 
1622  /* Add XID to snapshot. */
1623  snapshot->xip[count++] = xid;
1624 
1625  /*
1626  * Save subtransaction XIDs if possible (if we've already
1627  * overflowed, there's no point). Note that the subxact XIDs must
1628  * be later than their parent, so no need to check them against
1629  * xmin. We could filter against xmax, but it seems better not to
1630  * do that much work while holding the ProcArrayLock.
1631  *
1632  * The other backend can add more subxids concurrently, but cannot
1633  * remove any. Hence it's important to fetch nxids just once.
1634  * Should be safe to use memcpy, though. (We needn't worry about
1635  * missing any xids added concurrently, because they must postdate
1636  * xmax.)
1637  *
1638  * Again, our own XIDs are not included in the snapshot.
1639  */
1640  if (!suboverflowed)
1641  {
1642  if (pgxact->overflowed)
1643  suboverflowed = true;
1644  else
1645  {
1646  int nxids = pgxact->nxids;
1647 
1648  if (nxids > 0)
1649  {
1650  volatile PGPROC *proc = &allProcs[pgprocno];
1651 
1652  memcpy(snapshot->subxip + subcount,
1653  (void *) proc->subxids.xids,
1654  nxids * sizeof(TransactionId));
1655  subcount += nxids;
1656  }
1657  }
1658  }
1659  }
1660  }
1661  else
1662  {
1663  /*
1664  * We're in hot standby, so get XIDs from KnownAssignedXids.
1665  *
1666  * We store all xids directly into subxip[]. Here's why:
1667  *
1668  * In recovery we don't know which xids are top-level and which are
1669  * subxacts, a design choice that greatly simplifies xid processing.
1670  *
1671  * It seems like we would want to try to put xids into xip[] only, but
1672  * that is fairly small. We would either need to make that bigger or
1673  * to increase the rate at which we WAL-log xid assignment; neither is
1674  * an appealing choice.
1675  *
1676  * We could try to store xids into xip[] first and then into subxip[]
1677  * if there are too many xids. That only works if the snapshot doesn't
1678  * overflow because we do not search subxip[] in that case. A simpler
1679  * way is to just store all xids in the subxact array because this is
1680  * by far the bigger array. We just leave the xip array empty.
1681  *
1682  * Either way we need to change the way XidInMVCCSnapshot() works
1683  * depending upon when the snapshot was taken, or change normal
1684  * snapshot processing so it matches.
1685  *
1686  * Note: It is possible for recovery to end before we finish taking
1687  * the snapshot, and for newly assigned transaction ids to be added to
1688  * the ProcArray. xmax cannot change while we hold ProcArrayLock, so
1689  * those newly added transaction ids would be filtered away, so we
1690  * need not be concerned about them.
1691  */
1692  subcount = KnownAssignedXidsGetAndSetXmin(snapshot->subxip, &xmin,
1693  xmax);
1694 
1695  if (TransactionIdPrecedesOrEquals(xmin, procArray->lastOverflowedXid))
1696  suboverflowed = true;
1697  }
1698 
1699 
1700  /* fetch into volatile var while ProcArrayLock is held */
1701  replication_slot_xmin = procArray->replication_slot_xmin;
1702  replication_slot_catalog_xmin = procArray->replication_slot_catalog_xmin;
1703 
1705  MyPgXact->xmin = TransactionXmin = xmin;
1706 
1707  LWLockRelease(ProcArrayLock);
1708 
1709  /*
1710  * Update globalxmin to include actual process xids. This is a slightly
1711  * different way of computing it than GetOldestXmin uses, but should give
1712  * the same result.
1713  */
1714  if (TransactionIdPrecedes(xmin, globalxmin))
1715  globalxmin = xmin;
1716 
1717  /* Update global variables too */
1721 
1722  /* Check whether there's a replication slot requiring an older xmin. */
1723  if (TransactionIdIsValid(replication_slot_xmin) &&
1724  NormalTransactionIdPrecedes(replication_slot_xmin, RecentGlobalXmin))
1725  RecentGlobalXmin = replication_slot_xmin;
1726 
1727  /* Non-catalog tables can be vacuumed if older than this xid */
1729 
1730  /*
1731  * Check whether there's a replication slot requiring an older catalog
1732  * xmin.
1733  */
1734  if (TransactionIdIsNormal(replication_slot_catalog_xmin) &&
1735  NormalTransactionIdPrecedes(replication_slot_catalog_xmin, RecentGlobalXmin))
1736  RecentGlobalXmin = replication_slot_catalog_xmin;
1737 
1738  RecentXmin = xmin;
1739 
1740  snapshot->xmin = xmin;
1741  snapshot->xmax = xmax;
1742  snapshot->xcnt = count;
1743  snapshot->subxcnt = subcount;
1744  snapshot->suboverflowed = suboverflowed;
1745 
1746  snapshot->curcid = GetCurrentCommandId(false);
1747 
1748  /*
1749  * This is a new snapshot, so set both refcounts are zero, and mark it as
1750  * not copied in persistent memory.
1751  */
1752  snapshot->active_count = 0;
1753  snapshot->regd_count = 0;
1754  snapshot->copied = false;
1755 
1756  if (old_snapshot_threshold < 0)
1757  {
1758  /*
1759  * If not using "snapshot too old" feature, fill related fields with
1760  * dummy values that don't require any locking.
1761  */
1762  snapshot->lsn = InvalidXLogRecPtr;
1763  snapshot->whenTaken = 0;
1764  }
1765  else
1766  {
1767  /*
1768  * Capture the current time and WAL stream location in case this
1769  * snapshot becomes old enough to need to fall back on the special
1770  * "old snapshot" logic.
1771  */
1772  snapshot->lsn = GetXLogInsertRecPtr();
1773  snapshot->whenTaken = GetSnapshotCurrentTimestamp();
1774  MaintainOldSnapshotTimeMapping(snapshot->whenTaken, xmin);
1775  }
1776 
1777  return snapshot;
1778 }
1779 
1780 /*
1781  * ProcArrayInstallImportedXmin -- install imported xmin into MyPgXact->xmin
1782  *
1783  * This is called when installing a snapshot imported from another
1784  * transaction. To ensure that OldestXmin doesn't go backwards, we must
1785  * check that the source transaction is still running, and we'd better do
1786  * that atomically with installing the new xmin.
1787  *
1788  * Returns TRUE if successful, FALSE if source xact is no longer running.
1789  */
1790 bool
1792 {
1793  bool result = false;
1794  ProcArrayStruct *arrayP = procArray;
1795  int index;
1796 
1798  if (!TransactionIdIsNormal(sourcexid))
1799  return false;
1800 
1801  /* Get lock so source xact can't end while we're doing this */
1802  LWLockAcquire(ProcArrayLock, LW_SHARED);
1803 
1804  for (index = 0; index < arrayP->numProcs; index++)
1805  {
1806  int pgprocno = arrayP->pgprocnos[index];
1807  volatile PGPROC *proc = &allProcs[pgprocno];
1808  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1809  TransactionId xid;
1810 
1811  /* Ignore procs running LAZY VACUUM */
1812  if (pgxact->vacuumFlags & PROC_IN_VACUUM)
1813  continue;
1814 
1815  xid = pgxact->xid; /* fetch just once */
1816  if (xid != sourcexid)
1817  continue;
1818 
1819  /*
1820  * We check the transaction's database ID for paranoia's sake: if it's
1821  * in another DB then its xmin does not cover us. Caller should have
1822  * detected this already, so we just treat any funny cases as
1823  * "transaction not found".
1824  */
1825  if (proc->databaseId != MyDatabaseId)
1826  continue;
1827 
1828  /*
1829  * Likewise, let's just make real sure its xmin does cover us.
1830  */
1831  xid = pgxact->xmin; /* fetch just once */
1832  if (!TransactionIdIsNormal(xid) ||
1833  !TransactionIdPrecedesOrEquals(xid, xmin))
1834  continue;
1835 
1836  /*
1837  * We're good. Install the new xmin. As in GetSnapshotData, set
1838  * TransactionXmin too. (Note that because snapmgr.c called
1839  * GetSnapshotData first, we'll be overwriting a valid xmin here, so
1840  * we don't check that.)
1841  */
1842  MyPgXact->xmin = TransactionXmin = xmin;
1843 
1844  result = true;
1845  break;
1846  }
1847 
1848  LWLockRelease(ProcArrayLock);
1849 
1850  return result;
1851 }
1852 
1853 /*
1854  * ProcArrayInstallRestoredXmin -- install restored xmin into MyPgXact->xmin
1855  *
1856  * This is like ProcArrayInstallImportedXmin, but we have a pointer to the
1857  * PGPROC of the transaction from which we imported the snapshot, rather than
1858  * an XID.
1859  *
1860  * Returns TRUE if successful, FALSE if source xact is no longer running.
1861  */
1862 bool
1864 {
1865  bool result = false;
1866  TransactionId xid;
1867  volatile PGXACT *pgxact;
1868 
1870  Assert(proc != NULL);
1871 
1872  /* Get lock so source xact can't end while we're doing this */
1873  LWLockAcquire(ProcArrayLock, LW_SHARED);
1874 
1875  pgxact = &allPgXact[proc->pgprocno];
1876 
1877  /*
1878  * Be certain that the referenced PGPROC has an advertised xmin which is
1879  * no later than the one we're installing, so that the system-wide xmin
1880  * can't go backwards. Also, make sure it's running in the same database,
1881  * so that the per-database xmin cannot go backwards.
1882  */
1883  xid = pgxact->xmin; /* fetch just once */
1884  if (proc->databaseId == MyDatabaseId &&
1885  TransactionIdIsNormal(xid) &&
1886  TransactionIdPrecedesOrEquals(xid, xmin))
1887  {
1888  MyPgXact->xmin = TransactionXmin = xmin;
1889  result = true;
1890  }
1891 
1892  LWLockRelease(ProcArrayLock);
1893 
1894  return result;
1895 }
1896 
1897 /*
1898  * GetRunningTransactionData -- returns information about running transactions.
1899  *
1900  * Similar to GetSnapshotData but returns more information. We include
1901  * all PGXACTs with an assigned TransactionId, even VACUUM processes.
1902  *
1903  * We acquire XidGenLock and ProcArrayLock, but the caller is responsible for
1904  * releasing them. Acquiring XidGenLock ensures that no new XIDs enter the proc
1905  * array until the caller has WAL-logged this snapshot, and releases the
1906  * lock. Acquiring ProcArrayLock ensures that no transactions commit until the
1907  * lock is released.
1908  *
1909  * The returned data structure is statically allocated; caller should not
1910  * modify it, and must not assume it is valid past the next call.
1911  *
1912  * This is never executed during recovery so there is no need to look at
1913  * KnownAssignedXids.
1914  *
1915  * We don't worry about updating other counters, we want to keep this as
1916  * simple as possible and leave GetSnapshotData() as the primary code for
1917  * that bookkeeping.
1918  *
1919  * Note that if any transaction has overflowed its cached subtransactions
1920  * then there is no real need include any subtransactions. That isn't a
1921  * common enough case to worry about optimising the size of the WAL record,
1922  * and we may wish to see that data for diagnostic purposes anyway.
1923  */
1926 {
1927  /* result workspace */
1928  static RunningTransactionsData CurrentRunningXactsData;
1929 
1930  ProcArrayStruct *arrayP = procArray;
1931  RunningTransactions CurrentRunningXacts = &CurrentRunningXactsData;
1932  TransactionId latestCompletedXid;
1933  TransactionId oldestRunningXid;
1934  TransactionId *xids;
1935  int index;
1936  int count;
1937  int subcount;
1938  bool suboverflowed;
1939 
1941 
1942  /*
1943  * Allocating space for maxProcs xids is usually overkill; numProcs would
1944  * be sufficient. But it seems better to do the malloc while not holding
1945  * the lock, so we can't look at numProcs. Likewise, we allocate much
1946  * more subxip storage than is probably needed.
1947  *
1948  * Should only be allocated in bgwriter, since only ever executed during
1949  * checkpoints.
1950  */
1951  if (CurrentRunningXacts->xids == NULL)
1952  {
1953  /*
1954  * First call
1955  */
1956  CurrentRunningXacts->xids = (TransactionId *)
1958  if (CurrentRunningXacts->xids == NULL)
1959  ereport(ERROR,
1960  (errcode(ERRCODE_OUT_OF_MEMORY),
1961  errmsg("out of memory")));
1962  }
1963 
1964  xids = CurrentRunningXacts->xids;
1965 
1966  count = subcount = 0;
1967  suboverflowed = false;
1968 
1969  /*
1970  * Ensure that no xids enter or leave the procarray while we obtain
1971  * snapshot.
1972  */
1973  LWLockAcquire(ProcArrayLock, LW_SHARED);
1974  LWLockAcquire(XidGenLock, LW_SHARED);
1975 
1976  latestCompletedXid = ShmemVariableCache->latestCompletedXid;
1977 
1978  oldestRunningXid = ShmemVariableCache->nextXid;
1979 
1980  /*
1981  * Spin over procArray collecting all xids
1982  */
1983  for (index = 0; index < arrayP->numProcs; index++)
1984  {
1985  int pgprocno = arrayP->pgprocnos[index];
1986  volatile PGXACT *pgxact = &allPgXact[pgprocno];
1987  TransactionId xid;
1988 
1989  /* Fetch xid just once - see GetNewTransactionId */
1990  xid = pgxact->xid;
1991 
1992  /*
1993  * We don't need to store transactions that don't have a TransactionId
1994  * yet because they will not show as running on a standby server.
1995  */
1996  if (!TransactionIdIsValid(xid))
1997  continue;
1998 
1999  xids[count++] = xid;
2000 
2001  if (TransactionIdPrecedes(xid, oldestRunningXid))
2002  oldestRunningXid = xid;
2003 
2004  if (pgxact->overflowed)
2005  suboverflowed = true;
2006  }
2007 
2008  /*
2009  * Spin over procArray collecting all subxids, but only if there hasn't
2010  * been a suboverflow.
2011  */
2012  if (!suboverflowed)
2013  {
2014  for (index = 0; index < arrayP->numProcs; index++)
2015  {
2016  int pgprocno = arrayP->pgprocnos[index];
2017  volatile PGPROC *proc = &allProcs[pgprocno];
2018  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2019  int nxids;
2020 
2021  /*
2022  * Save subtransaction XIDs. Other backends can't add or remove
2023  * entries while we're holding XidGenLock.
2024  */
2025  nxids = pgxact->nxids;
2026  if (nxids > 0)
2027  {
2028  memcpy(&xids[count], (void *) proc->subxids.xids,
2029  nxids * sizeof(TransactionId));
2030  count += nxids;
2031  subcount += nxids;
2032 
2033  /*
2034  * Top-level XID of a transaction is always less than any of
2035  * its subxids, so we don't need to check if any of the
2036  * subxids are smaller than oldestRunningXid
2037  */
2038  }
2039  }
2040  }
2041 
2042  /*
2043  * It's important *not* to include the limits set by slots here because
2044  * snapbuild.c uses oldestRunningXid to manage its xmin horizon. If those
2045  * were to be included here the initial value could never increase because
2046  * of a circular dependency where slots only increase their limits when
2047  * running xacts increases oldestRunningXid and running xacts only
2048  * increases if slots do.
2049  */
2050 
2051  CurrentRunningXacts->xcnt = count - subcount;
2052  CurrentRunningXacts->subxcnt = subcount;
2053  CurrentRunningXacts->subxid_overflow = suboverflowed;
2054  CurrentRunningXacts->nextXid = ShmemVariableCache->nextXid;
2055  CurrentRunningXacts->oldestRunningXid = oldestRunningXid;
2056  CurrentRunningXacts->latestCompletedXid = latestCompletedXid;
2057 
2058  Assert(TransactionIdIsValid(CurrentRunningXacts->nextXid));
2059  Assert(TransactionIdIsValid(CurrentRunningXacts->oldestRunningXid));
2060  Assert(TransactionIdIsNormal(CurrentRunningXacts->latestCompletedXid));
2061 
2062  /* We don't release the locks here, the caller is responsible for that */
2063 
2064  return CurrentRunningXacts;
2065 }
2066 
2067 /*
2068  * GetOldestActiveTransactionId()
2069  *
2070  * Similar to GetSnapshotData but returns just oldestActiveXid. We include
2071  * all PGXACTs with an assigned TransactionId, even VACUUM processes.
2072  * We look at all databases, though there is no need to include WALSender
2073  * since this has no effect on hot standby conflicts.
2074  *
2075  * This is never executed during recovery so there is no need to look at
2076  * KnownAssignedXids.
2077  *
2078  * We don't worry about updating other counters, we want to keep this as
2079  * simple as possible and leave GetSnapshotData() as the primary code for
2080  * that bookkeeping.
2081  */
2084 {
2085  ProcArrayStruct *arrayP = procArray;
2086  TransactionId oldestRunningXid;
2087  int index;
2088 
2090 
2091  LWLockAcquire(ProcArrayLock, LW_SHARED);
2092 
2093  /*
2094  * It's okay to read nextXid without acquiring XidGenLock because (1) we
2095  * assume TransactionIds can be read atomically and (2) we don't care if
2096  * we get a slightly stale value. It can't be very stale anyway, because
2097  * the LWLockAcquire above will have done any necessary memory
2098  * interlocking.
2099  */
2100  oldestRunningXid = ShmemVariableCache->nextXid;
2101 
2102  /*
2103  * Spin over procArray collecting all xids and subxids.
2104  */
2105  for (index = 0; index < arrayP->numProcs; index++)
2106  {
2107  int pgprocno = arrayP->pgprocnos[index];
2108  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2109  TransactionId xid;
2110 
2111  /* Fetch xid just once - see GetNewTransactionId */
2112  xid = pgxact->xid;
2113 
2114  if (!TransactionIdIsNormal(xid))
2115  continue;
2116 
2117  if (TransactionIdPrecedes(xid, oldestRunningXid))
2118  oldestRunningXid = xid;
2119 
2120  /*
2121  * Top-level XID of a transaction is always less than any of its
2122  * subxids, so we don't need to check if any of the subxids are
2123  * smaller than oldestRunningXid
2124  */
2125  }
2126 
2127  LWLockRelease(ProcArrayLock);
2128 
2129  return oldestRunningXid;
2130 }
2131 
2132 /*
2133  * GetOldestSafeDecodingTransactionId -- lowest xid not affected by vacuum
2134  *
2135  * Returns the oldest xid that we can guarantee not to have been affected by
2136  * vacuum, i.e. no rows >= that xid have been vacuumed away unless the
2137  * transaction aborted. Note that the value can (and most of the time will) be
2138  * much more conservative than what really has been affected by vacuum, but we
2139  * currently don't have better data available.
2140  *
2141  * This is useful to initialize the cutoff xid after which a new changeset
2142  * extraction replication slot can start decoding changes.
2143  *
2144  * Must be called with ProcArrayLock held either shared or exclusively,
2145  * although most callers will want to use exclusive mode since it is expected
2146  * that the caller will immediately use the xid to peg the xmin horizon.
2147  */
2150 {
2151  ProcArrayStruct *arrayP = procArray;
2152  TransactionId oldestSafeXid;
2153  int index;
2154  bool recovery_in_progress = RecoveryInProgress();
2155 
2156  Assert(LWLockHeldByMe(ProcArrayLock));
2157 
2158  /*
2159  * Acquire XidGenLock, so no transactions can acquire an xid while we're
2160  * running. If no transaction with xid were running concurrently a new xid
2161  * could influence the RecentXmin et al.
2162  *
2163  * We initialize the computation to nextXid since that's guaranteed to be
2164  * a safe, albeit pessimal, value.
2165  */
2166  LWLockAcquire(XidGenLock, LW_SHARED);
2167  oldestSafeXid = ShmemVariableCache->nextXid;
2168 
2169  /*
2170  * If there's already a slot pegging the xmin horizon, we can start with
2171  * that value, it's guaranteed to be safe since it's computed by this
2172  * routine initially and has been enforced since.
2173  */
2176  oldestSafeXid))
2177  oldestSafeXid = procArray->replication_slot_catalog_xmin;
2178 
2179  /*
2180  * If we're not in recovery, we walk over the procarray and collect the
2181  * lowest xid. Since we're called with ProcArrayLock held and have
2182  * acquired XidGenLock, no entries can vanish concurrently, since
2183  * PGXACT->xid is only set with XidGenLock held and only cleared with
2184  * ProcArrayLock held.
2185  *
2186  * In recovery we can't lower the safe value besides what we've computed
2187  * above, so we'll have to wait a bit longer there. We unfortunately can
2188  * *not* use KnownAssignedXidsGetOldestXmin() since the KnownAssignedXids
2189  * machinery can miss values and return an older value than is safe.
2190  */
2191  if (!recovery_in_progress)
2192  {
2193  /*
2194  * Spin over procArray collecting all min(PGXACT->xid)
2195  */
2196  for (index = 0; index < arrayP->numProcs; index++)
2197  {
2198  int pgprocno = arrayP->pgprocnos[index];
2199  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2200  TransactionId xid;
2201 
2202  /* Fetch xid just once - see GetNewTransactionId */
2203  xid = pgxact->xid;
2204 
2205  if (!TransactionIdIsNormal(xid))
2206  continue;
2207 
2208  if (TransactionIdPrecedes(xid, oldestSafeXid))
2209  oldestSafeXid = xid;
2210  }
2211  }
2212 
2213  LWLockRelease(XidGenLock);
2214 
2215  return oldestSafeXid;
2216 }
2217 
2218 /*
2219  * GetVirtualXIDsDelayingChkpt -- Get the VXIDs of transactions that are
2220  * delaying checkpoint because they have critical actions in progress.
2221  *
2222  * Constructs an array of VXIDs of transactions that are currently in commit
2223  * critical sections, as shown by having delayChkpt set in their PGXACT.
2224  *
2225  * Returns a palloc'd array that should be freed by the caller.
2226  * *nvxids is the number of valid entries.
2227  *
2228  * Note that because backends set or clear delayChkpt without holding any lock,
2229  * the result is somewhat indeterminate, but we don't really care. Even in
2230  * a multiprocessor with delayed writes to shared memory, it should be certain
2231  * that setting of delayChkpt will propagate to shared memory when the backend
2232  * takes a lock, so we cannot fail to see a virtual xact as delayChkpt if
2233  * it's already inserted its commit record. Whether it takes a little while
2234  * for clearing of delayChkpt to propagate is unimportant for correctness.
2235  */
2238 {
2239  VirtualTransactionId *vxids;
2240  ProcArrayStruct *arrayP = procArray;
2241  int count = 0;
2242  int index;
2243 
2244  /* allocate what's certainly enough result space */
2245  vxids = (VirtualTransactionId *)
2246  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2247 
2248  LWLockAcquire(ProcArrayLock, LW_SHARED);
2249 
2250  for (index = 0; index < arrayP->numProcs; index++)
2251  {
2252  int pgprocno = arrayP->pgprocnos[index];
2253  volatile PGPROC *proc = &allProcs[pgprocno];
2254  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2255 
2256  if (pgxact->delayChkpt)
2257  {
2258  VirtualTransactionId vxid;
2259 
2260  GET_VXID_FROM_PGPROC(vxid, *proc);
2261  if (VirtualTransactionIdIsValid(vxid))
2262  vxids[count++] = vxid;
2263  }
2264  }
2265 
2266  LWLockRelease(ProcArrayLock);
2267 
2268  *nvxids = count;
2269  return vxids;
2270 }
2271 
2272 /*
2273  * HaveVirtualXIDsDelayingChkpt -- Are any of the specified VXIDs delaying?
2274  *
2275  * This is used with the results of GetVirtualXIDsDelayingChkpt to see if any
2276  * of the specified VXIDs are still in critical sections of code.
2277  *
2278  * Note: this is O(N^2) in the number of vxacts that are/were delaying, but
2279  * those numbers should be small enough for it not to be a problem.
2280  */
2281 bool
2283 {
2284  bool result = false;
2285  ProcArrayStruct *arrayP = procArray;
2286  int index;
2287 
2288  LWLockAcquire(ProcArrayLock, LW_SHARED);
2289 
2290  for (index = 0; index < arrayP->numProcs; index++)
2291  {
2292  int pgprocno = arrayP->pgprocnos[index];
2293  volatile PGPROC *proc = &allProcs[pgprocno];
2294  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2295  VirtualTransactionId vxid;
2296 
2297  GET_VXID_FROM_PGPROC(vxid, *proc);
2298 
2299  if (pgxact->delayChkpt && VirtualTransactionIdIsValid(vxid))
2300  {
2301  int i;
2302 
2303  for (i = 0; i < nvxids; i++)
2304  {
2305  if (VirtualTransactionIdEquals(vxid, vxids[i]))
2306  {
2307  result = true;
2308  break;
2309  }
2310  }
2311  if (result)
2312  break;
2313  }
2314  }
2315 
2316  LWLockRelease(ProcArrayLock);
2317 
2318  return result;
2319 }
2320 
2321 /*
2322  * BackendPidGetProc -- get a backend's PGPROC given its PID
2323  *
2324  * Returns NULL if not found. Note that it is up to the caller to be
2325  * sure that the question remains meaningful for long enough for the
2326  * answer to be used ...
2327  */
2328 PGPROC *
2330 {
2331  PGPROC *result;
2332 
2333  if (pid == 0) /* never match dummy PGPROCs */
2334  return NULL;
2335 
2336  LWLockAcquire(ProcArrayLock, LW_SHARED);
2337 
2338  result = BackendPidGetProcWithLock(pid);
2339 
2340  LWLockRelease(ProcArrayLock);
2341 
2342  return result;
2343 }
2344 
2345 /*
2346  * BackendPidGetProcWithLock -- get a backend's PGPROC given its PID
2347  *
2348  * Same as above, except caller must be holding ProcArrayLock. The found
2349  * entry, if any, can be assumed to be valid as long as the lock remains held.
2350  */
2351 PGPROC *
2353 {
2354  PGPROC *result = NULL;
2355  ProcArrayStruct *arrayP = procArray;
2356  int index;
2357 
2358  if (pid == 0) /* never match dummy PGPROCs */
2359  return NULL;
2360 
2361  for (index = 0; index < arrayP->numProcs; index++)
2362  {
2363  PGPROC *proc = &allProcs[arrayP->pgprocnos[index]];
2364 
2365  if (proc->pid == pid)
2366  {
2367  result = proc;
2368  break;
2369  }
2370  }
2371 
2372  return result;
2373 }
2374 
2375 /*
2376  * BackendXidGetPid -- get a backend's pid given its XID
2377  *
2378  * Returns 0 if not found or it's a prepared transaction. Note that
2379  * it is up to the caller to be sure that the question remains
2380  * meaningful for long enough for the answer to be used ...
2381  *
2382  * Only main transaction Ids are considered. This function is mainly
2383  * useful for determining what backend owns a lock.
2384  *
2385  * Beware that not every xact has an XID assigned. However, as long as you
2386  * only call this using an XID found on disk, you're safe.
2387  */
2388 int
2390 {
2391  int result = 0;
2392  ProcArrayStruct *arrayP = procArray;
2393  int index;
2394 
2395  if (xid == InvalidTransactionId) /* never match invalid xid */
2396  return 0;
2397 
2398  LWLockAcquire(ProcArrayLock, LW_SHARED);
2399 
2400  for (index = 0; index < arrayP->numProcs; index++)
2401  {
2402  int pgprocno = arrayP->pgprocnos[index];
2403  volatile PGPROC *proc = &allProcs[pgprocno];
2404  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2405 
2406  if (pgxact->xid == xid)
2407  {
2408  result = proc->pid;
2409  break;
2410  }
2411  }
2412 
2413  LWLockRelease(ProcArrayLock);
2414 
2415  return result;
2416 }
2417 
2418 /*
2419  * IsBackendPid -- is a given pid a running backend
2420  *
2421  * This is not called by the backend, but is called by external modules.
2422  */
2423 bool
2425 {
2426  return (BackendPidGetProc(pid) != NULL);
2427 }
2428 
2429 
2430 /*
2431  * GetCurrentVirtualXIDs -- returns an array of currently active VXIDs.
2432  *
2433  * The array is palloc'd. The number of valid entries is returned into *nvxids.
2434  *
2435  * The arguments allow filtering the set of VXIDs returned. Our own process
2436  * is always skipped. In addition:
2437  * If limitXmin is not InvalidTransactionId, skip processes with
2438  * xmin > limitXmin.
2439  * If excludeXmin0 is true, skip processes with xmin = 0.
2440  * If allDbs is false, skip processes attached to other databases.
2441  * If excludeVacuum isn't zero, skip processes for which
2442  * (vacuumFlags & excludeVacuum) is not zero.
2443  *
2444  * Note: the purpose of the limitXmin and excludeXmin0 parameters is to
2445  * allow skipping backends whose oldest live snapshot is no older than
2446  * some snapshot we have. Since we examine the procarray with only shared
2447  * lock, there are race conditions: a backend could set its xmin just after
2448  * we look. Indeed, on multiprocessors with weak memory ordering, the
2449  * other backend could have set its xmin *before* we look. We know however
2450  * that such a backend must have held shared ProcArrayLock overlapping our
2451  * own hold of ProcArrayLock, else we would see its xmin update. Therefore,
2452  * any snapshot the other backend is taking concurrently with our scan cannot
2453  * consider any transactions as still running that we think are committed
2454  * (since backends must hold ProcArrayLock exclusive to commit).
2455  */
2457 GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0,
2458  bool allDbs, int excludeVacuum,
2459  int *nvxids)
2460 {
2461  VirtualTransactionId *vxids;
2462  ProcArrayStruct *arrayP = procArray;
2463  int count = 0;
2464  int index;
2465 
2466  /* allocate what's certainly enough result space */
2467  vxids = (VirtualTransactionId *)
2468  palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
2469 
2470  LWLockAcquire(ProcArrayLock, LW_SHARED);
2471 
2472  for (index = 0; index < arrayP->numProcs; index++)
2473  {
2474  int pgprocno = arrayP->pgprocnos[index];
2475  volatile PGPROC *proc = &allProcs[pgprocno];
2476  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2477 
2478  if (proc == MyProc)
2479  continue;
2480 
2481  if (excludeVacuum & pgxact->vacuumFlags)
2482  continue;
2483 
2484  if (allDbs || proc->databaseId == MyDatabaseId)
2485  {
2486  /* Fetch xmin just once - might change on us */
2487  TransactionId pxmin = pgxact->xmin;
2488 
2489  if (excludeXmin0 && !TransactionIdIsValid(pxmin))
2490  continue;
2491 
2492  /*
2493  * InvalidTransactionId precedes all other XIDs, so a proc that
2494  * hasn't set xmin yet will not be rejected by this test.
2495  */
2496  if (!TransactionIdIsValid(limitXmin) ||
2497  TransactionIdPrecedesOrEquals(pxmin, limitXmin))
2498  {
2499  VirtualTransactionId vxid;
2500 
2501  GET_VXID_FROM_PGPROC(vxid, *proc);
2502  if (VirtualTransactionIdIsValid(vxid))
2503  vxids[count++] = vxid;
2504  }
2505  }
2506  }
2507 
2508  LWLockRelease(ProcArrayLock);
2509 
2510  *nvxids = count;
2511  return vxids;
2512 }
2513 
2514 /*
2515  * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs.
2516  *
2517  * Usage is limited to conflict resolution during recovery on standby servers.
2518  * limitXmin is supplied as either latestRemovedXid, or InvalidTransactionId
2519  * in cases where we cannot accurately determine a value for latestRemovedXid.
2520  *
2521  * If limitXmin is InvalidTransactionId then we want to kill everybody,
2522  * so we're not worried if they have a snapshot or not, nor does it really
2523  * matter what type of lock we hold.
2524  *
2525  * All callers that are checking xmins always now supply a valid and useful
2526  * value for limitXmin. The limitXmin is always lower than the lowest
2527  * numbered KnownAssignedXid that is not already a FATAL error. This is
2528  * because we only care about cleanup records that are cleaning up tuple
2529  * versions from committed transactions. In that case they will only occur
2530  * at the point where the record is less than the lowest running xid. That
2531  * allows us to say that if any backend takes a snapshot concurrently with
2532  * us then the conflict assessment made here would never include the snapshot
2533  * that is being derived. So we take LW_SHARED on the ProcArray and allow
2534  * concurrent snapshots when limitXmin is valid. We might think about adding
2535  * Assert(limitXmin < lowest(KnownAssignedXids))
2536  * but that would not be true in the case of FATAL errors lagging in array,
2537  * but we already know those are bogus anyway, so we skip that test.
2538  *
2539  * If dbOid is valid we skip backends attached to other databases.
2540  *
2541  * Be careful to *not* pfree the result from this function. We reuse
2542  * this array sufficiently often that we use malloc for the result.
2543  */
2546 {
2547  static VirtualTransactionId *vxids;
2548  ProcArrayStruct *arrayP = procArray;
2549  int count = 0;
2550  int index;
2551 
2552  /*
2553  * If first time through, get workspace to remember main XIDs in. We
2554  * malloc it permanently to avoid repeated palloc/pfree overhead. Allow
2555  * result space, remembering room for a terminator.
2556  */
2557  if (vxids == NULL)
2558  {
2559  vxids = (VirtualTransactionId *)
2560  malloc(sizeof(VirtualTransactionId) * (arrayP->maxProcs + 1));
2561  if (vxids == NULL)
2562  ereport(ERROR,
2563  (errcode(ERRCODE_OUT_OF_MEMORY),
2564  errmsg("out of memory")));
2565  }
2566 
2567  LWLockAcquire(ProcArrayLock, LW_SHARED);
2568 
2569  for (index = 0; index < arrayP->numProcs; index++)
2570  {
2571  int pgprocno = arrayP->pgprocnos[index];
2572  volatile PGPROC *proc = &allProcs[pgprocno];
2573  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2574 
2575  /* Exclude prepared transactions */
2576  if (proc->pid == 0)
2577  continue;
2578 
2579  if (!OidIsValid(dbOid) ||
2580  proc->databaseId == dbOid)
2581  {
2582  /* Fetch xmin just once - can't change on us, but good coding */
2583  TransactionId pxmin = pgxact->xmin;
2584 
2585  /*
2586  * We ignore an invalid pxmin because this means that backend has
2587  * no snapshot currently. We hold a Share lock to avoid contention
2588  * with users taking snapshots. That is not a problem because the
2589  * current xmin is always at least one higher than the latest
2590  * removed xid, so any new snapshot would never conflict with the
2591  * test here.
2592  */
2593  if (!TransactionIdIsValid(limitXmin) ||
2594  (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin)))
2595  {
2596  VirtualTransactionId vxid;
2597 
2598  GET_VXID_FROM_PGPROC(vxid, *proc);
2599  if (VirtualTransactionIdIsValid(vxid))
2600  vxids[count++] = vxid;
2601  }
2602  }
2603  }
2604 
2605  LWLockRelease(ProcArrayLock);
2606 
2607  /* add the terminator */
2608  vxids[count].backendId = InvalidBackendId;
2610 
2611  return vxids;
2612 }
2613 
2614 /*
2615  * CancelVirtualTransaction - used in recovery conflict processing
2616  *
2617  * Returns pid of the process signaled, or 0 if not found.
2618  */
2619 pid_t
2621 {
2622  ProcArrayStruct *arrayP = procArray;
2623  int index;
2624  pid_t pid = 0;
2625 
2626  LWLockAcquire(ProcArrayLock, LW_SHARED);
2627 
2628  for (index = 0; index < arrayP->numProcs; index++)
2629  {
2630  int pgprocno = arrayP->pgprocnos[index];
2631  volatile PGPROC *proc = &allProcs[pgprocno];
2632  VirtualTransactionId procvxid;
2633 
2634  GET_VXID_FROM_PGPROC(procvxid, *proc);
2635 
2636  if (procvxid.backendId == vxid.backendId &&
2637  procvxid.localTransactionId == vxid.localTransactionId)
2638  {
2639  proc->recoveryConflictPending = true;
2640  pid = proc->pid;
2641  if (pid != 0)
2642  {
2643  /*
2644  * Kill the pid if it's still here. If not, that's what we
2645  * wanted so ignore any errors.
2646  */
2647  (void) SendProcSignal(pid, sigmode, vxid.backendId);
2648  }
2649  break;
2650  }
2651  }
2652 
2653  LWLockRelease(ProcArrayLock);
2654 
2655  return pid;
2656 }
2657 
2658 /*
2659  * MinimumActiveBackends --- count backends (other than myself) that are
2660  * in active transactions. Return true if the count exceeds the
2661  * minimum threshold passed. This is used as a heuristic to decide if
2662  * a pre-XLOG-flush delay is worthwhile during commit.
2663  *
2664  * Do not count backends that are blocked waiting for locks, since they are
2665  * not going to get to run until someone else commits.
2666  */
2667 bool
2669 {
2670  ProcArrayStruct *arrayP = procArray;
2671  int count = 0;
2672  int index;
2673 
2674  /* Quick short-circuit if no minimum is specified */
2675  if (min == 0)
2676  return true;
2677 
2678  /*
2679  * Note: for speed, we don't acquire ProcArrayLock. This is a little bit
2680  * bogus, but since we are only testing fields for zero or nonzero, it
2681  * should be OK. The result is only used for heuristic purposes anyway...
2682  */
2683  for (index = 0; index < arrayP->numProcs; index++)
2684  {
2685  int pgprocno = arrayP->pgprocnos[index];
2686  volatile PGPROC *proc = &allProcs[pgprocno];
2687  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2688 
2689  /*
2690  * Since we're not holding a lock, need to be prepared to deal with
2691  * garbage, as someone could have incremented numProcs but not yet
2692  * filled the structure.
2693  *
2694  * If someone just decremented numProcs, 'proc' could also point to a
2695  * PGPROC entry that's no longer in the array. It still points to a
2696  * PGPROC struct, though, because freed PGPROC entries just go to the
2697  * free list and are recycled. Its contents are nonsense in that case,
2698  * but that's acceptable for this function.
2699  */
2700  if (pgprocno == -1)
2701  continue; /* do not count deleted entries */
2702  if (proc == MyProc)
2703  continue; /* do not count myself */
2704  if (pgxact->xid == InvalidTransactionId)
2705  continue; /* do not count if no XID assigned */
2706  if (proc->pid == 0)
2707  continue; /* do not count prepared xacts */
2708  if (proc->waitLock != NULL)
2709  continue; /* do not count if blocked on a lock */
2710  count++;
2711  if (count >= min)
2712  break;
2713  }
2714 
2715  return count >= min;
2716 }
2717 
2718 /*
2719  * CountDBBackends --- count backends that are using specified database
2720  */
2721 int
2723 {
2724  ProcArrayStruct *arrayP = procArray;
2725  int count = 0;
2726  int index;
2727 
2728  LWLockAcquire(ProcArrayLock, LW_SHARED);
2729 
2730  for (index = 0; index < arrayP->numProcs; index++)
2731  {
2732  int pgprocno = arrayP->pgprocnos[index];
2733  volatile PGPROC *proc = &allProcs[pgprocno];
2734 
2735  if (proc->pid == 0)
2736  continue; /* do not count prepared xacts */
2737  if (!OidIsValid(databaseid) ||
2738  proc->databaseId == databaseid)
2739  count++;
2740  }
2741 
2742  LWLockRelease(ProcArrayLock);
2743 
2744  return count;
2745 }
2746 
2747 /*
2748  * CountDBConnections --- counts database backends ignoring any background
2749  * worker processes
2750  */
2751 int
2753 {
2754  ProcArrayStruct *arrayP = procArray;
2755  int count = 0;
2756  int index;
2757 
2758  LWLockAcquire(ProcArrayLock, LW_SHARED);
2759 
2760  for (index = 0; index < arrayP->numProcs; index++)
2761  {
2762  int pgprocno = arrayP->pgprocnos[index];
2763  volatile PGPROC *proc = &allProcs[pgprocno];
2764 
2765  if (proc->pid == 0)
2766  continue; /* do not count prepared xacts */
2767  if (proc->isBackgroundWorker)
2768  continue; /* do not count background workers */
2769  if (!OidIsValid(databaseid) ||
2770  proc->databaseId == databaseid)
2771  count++;
2772  }
2773 
2774  LWLockRelease(ProcArrayLock);
2775 
2776  return count;
2777 }
2778 
2779 /*
2780  * CancelDBBackends --- cancel backends that are using specified database
2781  */
2782 void
2783 CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
2784 {
2785  ProcArrayStruct *arrayP = procArray;
2786  int index;
2787  pid_t pid = 0;
2788 
2789  /* tell all backends to die */
2790  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2791 
2792  for (index = 0; index < arrayP->numProcs; index++)
2793  {
2794  int pgprocno = arrayP->pgprocnos[index];
2795  volatile PGPROC *proc = &allProcs[pgprocno];
2796 
2797  if (databaseid == InvalidOid || proc->databaseId == databaseid)
2798  {
2799  VirtualTransactionId procvxid;
2800 
2801  GET_VXID_FROM_PGPROC(procvxid, *proc);
2802 
2803  proc->recoveryConflictPending = conflictPending;
2804  pid = proc->pid;
2805  if (pid != 0)
2806  {
2807  /*
2808  * Kill the pid if it's still here. If not, that's what we
2809  * wanted so ignore any errors.
2810  */
2811  (void) SendProcSignal(pid, sigmode, procvxid.backendId);
2812  }
2813  }
2814  }
2815 
2816  LWLockRelease(ProcArrayLock);
2817 }
2818 
2819 /*
2820  * CountUserBackends --- count backends that are used by specified user
2821  */
2822 int
2824 {
2825  ProcArrayStruct *arrayP = procArray;
2826  int count = 0;
2827  int index;
2828 
2829  LWLockAcquire(ProcArrayLock, LW_SHARED);
2830 
2831  for (index = 0; index < arrayP->numProcs; index++)
2832  {
2833  int pgprocno = arrayP->pgprocnos[index];
2834  volatile PGPROC *proc = &allProcs[pgprocno];
2835 
2836  if (proc->pid == 0)
2837  continue; /* do not count prepared xacts */
2838  if (proc->isBackgroundWorker)
2839  continue; /* do not count background workers */
2840  if (proc->roleId == roleid)
2841  count++;
2842  }
2843 
2844  LWLockRelease(ProcArrayLock);
2845 
2846  return count;
2847 }
2848 
2849 /*
2850  * CountOtherDBBackends -- check for other backends running in the given DB
2851  *
2852  * If there are other backends in the DB, we will wait a maximum of 5 seconds
2853  * for them to exit. Autovacuum backends are encouraged to exit early by
2854  * sending them SIGTERM, but normal user backends are just waited for.
2855  *
2856  * The current backend is always ignored; it is caller's responsibility to
2857  * check whether the current backend uses the given DB, if it's important.
2858  *
2859  * Returns TRUE if there are (still) other backends in the DB, FALSE if not.
2860  * Also, *nbackends and *nprepared are set to the number of other backends
2861  * and prepared transactions in the DB, respectively.
2862  *
2863  * This function is used to interlock DROP DATABASE and related commands
2864  * against there being any active backends in the target DB --- dropping the
2865  * DB while active backends remain would be a Bad Thing. Note that we cannot
2866  * detect here the possibility of a newly-started backend that is trying to
2867  * connect to the doomed database, so additional interlocking is needed during
2868  * backend startup. The caller should normally hold an exclusive lock on the
2869  * target DB before calling this, which is one reason we mustn't wait
2870  * indefinitely.
2871  */
2872 bool
2873 CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
2874 {
2875  ProcArrayStruct *arrayP = procArray;
2876 
2877 #define MAXAUTOVACPIDS 10 /* max autovacs to SIGTERM per iteration */
2878  int autovac_pids[MAXAUTOVACPIDS];
2879  int tries;
2880 
2881  /* 50 tries with 100ms sleep between tries makes 5 sec total wait */
2882  for (tries = 0; tries < 50; tries++)
2883  {
2884  int nautovacs = 0;
2885  bool found = false;
2886  int index;
2887 
2889 
2890  *nbackends = *nprepared = 0;
2891 
2892  LWLockAcquire(ProcArrayLock, LW_SHARED);
2893 
2894  for (index = 0; index < arrayP->numProcs; index++)
2895  {
2896  int pgprocno = arrayP->pgprocnos[index];
2897  volatile PGPROC *proc = &allProcs[pgprocno];
2898  volatile PGXACT *pgxact = &allPgXact[pgprocno];
2899 
2900  if (proc->databaseId != databaseId)
2901  continue;
2902  if (proc == MyProc)
2903  continue;
2904 
2905  found = true;
2906 
2907  if (proc->pid == 0)
2908  (*nprepared)++;
2909  else
2910  {
2911  (*nbackends)++;
2912  if ((pgxact->vacuumFlags & PROC_IS_AUTOVACUUM) &&
2913  nautovacs < MAXAUTOVACPIDS)
2914  autovac_pids[nautovacs++] = proc->pid;
2915  }
2916  }
2917 
2918  LWLockRelease(ProcArrayLock);
2919 
2920  if (!found)
2921  return false; /* no conflicting backends, so done */
2922 
2923  /*
2924  * Send SIGTERM to any conflicting autovacuums before sleeping. We
2925  * postpone this step until after the loop because we don't want to
2926  * hold ProcArrayLock while issuing kill(). We have no idea what might
2927  * block kill() inside the kernel...
2928  */
2929  for (index = 0; index < nautovacs; index++)
2930  (void) kill(autovac_pids[index], SIGTERM); /* ignore any error */
2931 
2932  /* sleep, then try again */
2933  pg_usleep(100 * 1000L); /* 100ms */
2934  }
2935 
2936  return true; /* timed out, still conflicts */
2937 }
2938 
2939 /*
2940  * ProcArraySetReplicationSlotXmin
2941  *
2942  * Install limits to future computations of the xmin horizon to prevent vacuum
2943  * and HOT pruning from removing affected rows still needed by clients with
2944  * replicaton slots.
2945  */
2946 void
2948  bool already_locked)
2949 {
2950  Assert(!already_locked || LWLockHeldByMe(ProcArrayLock));
2951 
2952  if (!already_locked)
2953  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2954 
2955  procArray->replication_slot_xmin = xmin;
2956  procArray->replication_slot_catalog_xmin = catalog_xmin;
2957 
2958  if (!already_locked)
2959  LWLockRelease(ProcArrayLock);
2960 }
2961 
2962 /*
2963  * ProcArrayGetReplicationSlotXmin
2964  *
2965  * Return the current slot xmin limits. That's useful to be able to remove
2966  * data that's older than those limits.
2967  */
2968 void
2970  TransactionId *catalog_xmin)
2971 {
2972  LWLockAcquire(ProcArrayLock, LW_SHARED);
2973 
2974  if (xmin != NULL)
2975  *xmin = procArray->replication_slot_xmin;
2976 
2977  if (catalog_xmin != NULL)
2978  *catalog_xmin = procArray->replication_slot_catalog_xmin;
2979 
2980  LWLockRelease(ProcArrayLock);
2981 }
2982 
2983 
2984 #define XidCacheRemove(i) \
2985  do { \
2986  MyProc->subxids.xids[i] = MyProc->subxids.xids[MyPgXact->nxids - 1]; \
2987  MyPgXact->nxids--; \
2988  } while (0)
2989 
2990 /*
2991  * XidCacheRemoveRunningXids
2992  *
2993  * Remove a bunch of TransactionIds from the list of known-running
2994  * subtransactions for my backend. Both the specified xid and those in
2995  * the xids[] array (of length nxids) are removed from the subxids cache.
2996  * latestXid must be the latest XID among the group.
2997  */
2998 void
3000  int nxids, const TransactionId *xids,
3001  TransactionId latestXid)
3002 {
3003  int i,
3004  j;
3005 
3007 
3008  /*
3009  * We must hold ProcArrayLock exclusively in order to remove transactions
3010  * from the PGPROC array. (See src/backend/access/transam/README.) It's
3011  * possible this could be relaxed since we know this routine is only used
3012  * to abort subtransactions, but pending closer analysis we'd best be
3013  * conservative.
3014  */
3015  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3016 
3017  /*
3018  * Under normal circumstances xid and xids[] will be in increasing order,
3019  * as will be the entries in subxids. Scan backwards to avoid O(N^2)
3020  * behavior when removing a lot of xids.
3021  */
3022  for (i = nxids - 1; i >= 0; i--)
3023  {
3024  TransactionId anxid = xids[i];
3025 
3026  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3027  {
3028  if (TransactionIdEquals(MyProc->subxids.xids[j], anxid))
3029  {
3030  XidCacheRemove(j);
3031  break;
3032  }
3033  }
3034 
3035  /*
3036  * Ordinarily we should have found it, unless the cache has
3037  * overflowed. However it's also possible for this routine to be
3038  * invoked multiple times for the same subtransaction, in case of an
3039  * error during AbortSubTransaction. So instead of Assert, emit a
3040  * debug warning.
3041  */
3042  if (j < 0 && !MyPgXact->overflowed)
3043  elog(WARNING, "did not find subXID %u in MyProc", anxid);
3044  }
3045 
3046  for (j = MyPgXact->nxids - 1; j >= 0; j--)
3047  {
3048  if (TransactionIdEquals(MyProc->subxids.xids[j], xid))
3049  {
3050  XidCacheRemove(j);
3051  break;
3052  }
3053  }
3054  /* Ordinarily we should have found it, unless the cache has overflowed */
3055  if (j < 0 && !MyPgXact->overflowed)
3056  elog(WARNING, "did not find subXID %u in MyProc", xid);
3057 
3058  /* Also advance global latestCompletedXid while holding the lock */
3060  latestXid))
3062 
3063  LWLockRelease(ProcArrayLock);
3064 }
3065 
3066 #ifdef XIDCACHE_DEBUG
3067 
3068 /*
3069  * Print stats about effectiveness of XID cache
3070  */
3071 static void
3072 DisplayXidCache(void)
3073 {
3074  fprintf(stderr,
3075  "XidCache: xmin: %ld, known: %ld, myxact: %ld, latest: %ld, mainxid: %ld, childxid: %ld, knownassigned: %ld, nooflo: %ld, slow: %ld\n",
3076  xc_by_recent_xmin,
3077  xc_by_known_xact,
3078  xc_by_my_xact,
3079  xc_by_latest_xid,
3080  xc_by_main_xid,
3081  xc_by_child_xid,
3082  xc_by_known_assigned,
3083  xc_no_overflow,
3084  xc_slow_answer);
3085 }
3086 #endif /* XIDCACHE_DEBUG */
3087 
3088 
3089 /* ----------------------------------------------
3090  * KnownAssignedTransactions sub-module
3091  * ----------------------------------------------
3092  */
3093 
3094 /*
3095  * In Hot Standby mode, we maintain a list of transactions that are (or were)
3096  * running in the master at the current point in WAL. These XIDs must be
3097  * treated as running by standby transactions, even though they are not in
3098  * the standby server's PGXACT array.
3099  *
3100  * We record all XIDs that we know have been assigned. That includes all the
3101  * XIDs seen in WAL records, plus all unobserved XIDs that we can deduce have
3102  * been assigned. We can deduce the existence of unobserved XIDs because we
3103  * know XIDs are assigned in sequence, with no gaps. The KnownAssignedXids
3104  * list expands as new XIDs are observed or inferred, and contracts when
3105  * transaction completion records arrive.
3106  *
3107  * During hot standby we do not fret too much about the distinction between
3108  * top-level XIDs and subtransaction XIDs. We store both together in the
3109  * KnownAssignedXids list. In backends, this is copied into snapshots in
3110  * GetSnapshotData(), taking advantage of the fact that XidInMVCCSnapshot()
3111  * doesn't care about the distinction either. Subtransaction XIDs are
3112  * effectively treated as top-level XIDs and in the typical case pg_subtrans
3113  * links are *not* maintained (which does not affect visibility).
3114  *
3115  * We have room in KnownAssignedXids and in snapshots to hold maxProcs *
3116  * (1 + PGPROC_MAX_CACHED_SUBXIDS) XIDs, so every master transaction must
3117  * report its subtransaction XIDs in a WAL XLOG_XACT_ASSIGNMENT record at
3118  * least every PGPROC_MAX_CACHED_SUBXIDS. When we receive one of these
3119  * records, we mark the subXIDs as children of the top XID in pg_subtrans,
3120  * and then remove them from KnownAssignedXids. This prevents overflow of
3121  * KnownAssignedXids and snapshots, at the cost that status checks for these
3122  * subXIDs will take a slower path through TransactionIdIsInProgress().
3123  * This means that KnownAssignedXids is not necessarily complete for subXIDs,
3124  * though it should be complete for top-level XIDs; this is the same situation
3125  * that holds with respect to the PGPROC entries in normal running.
3126  *
3127  * When we throw away subXIDs from KnownAssignedXids, we need to keep track of
3128  * that, similarly to tracking overflow of a PGPROC's subxids array. We do
3129  * that by remembering the lastOverflowedXID, ie the last thrown-away subXID.
3130  * As long as that is within the range of interesting XIDs, we have to assume
3131  * that subXIDs are missing from snapshots. (Note that subXID overflow occurs
3132  * on primary when 65th subXID arrives, whereas on standby it occurs when 64th
3133  * subXID arrives - that is not an error.)
3134  *
3135  * Should a backend on primary somehow disappear before it can write an abort
3136  * record, then we just leave those XIDs in KnownAssignedXids. They actually
3137  * aborted but we think they were running; the distinction is irrelevant
3138  * because either way any changes done by the transaction are not visible to
3139  * backends in the standby. We prune KnownAssignedXids when
3140  * XLOG_RUNNING_XACTS arrives, to forestall possible overflow of the
3141  * array due to such dead XIDs.
3142  */
3143 
3144 /*
3145  * RecordKnownAssignedTransactionIds
3146  * Record the given XID in KnownAssignedXids, as well as any preceding
3147  * unobserved XIDs.
3148  *
3149  * RecordKnownAssignedTransactionIds() should be run for *every* WAL record
3150  * associated with a transaction. Must be called for each record after we
3151  * have executed StartupCLOG() et al, since we must ExtendCLOG() etc..
3152  *
3153  * Called during recovery in analogy with and in place of GetNewTransactionId()
3154  */
3155 void
3157 {
3161 
3162  elog(trace_recovery(DEBUG4), "record known xact %u latestObservedXid %u",
3163  xid, latestObservedXid);
3164 
3165  /*
3166  * When a newly observed xid arrives, it is frequently the case that it is
3167  * *not* the next xid in sequence. When this occurs, we must treat the
3168  * intervening xids as running also.
3169  */
3171  {
3172  TransactionId next_expected_xid;
3173 
3174  /*
3175  * Extend subtrans like we do in GetNewTransactionId() during normal
3176  * operation using individual extend steps. Note that we do not need
3177  * to extend clog since its extensions are WAL logged.
3178  *
3179  * This part has to be done regardless of standbyState since we
3180  * immediately start assigning subtransactions to their toplevel
3181  * transactions.
3182  */
3183  next_expected_xid = latestObservedXid;
3184  while (TransactionIdPrecedes(next_expected_xid, xid))
3185  {
3186  TransactionIdAdvance(next_expected_xid);
3187  ExtendSUBTRANS(next_expected_xid);
3188  }
3189  Assert(next_expected_xid == xid);
3190 
3191  /*
3192  * If the KnownAssignedXids machinery isn't up yet, there's nothing
3193  * more to do since we don't track assigned xids yet.
3194  */
3196  {
3197  latestObservedXid = xid;
3198  return;
3199  }
3200 
3201  /*
3202  * Add (latestObservedXid, xid] onto the KnownAssignedXids array.
3203  */
3204  next_expected_xid = latestObservedXid;
3205  TransactionIdAdvance(next_expected_xid);
3206  KnownAssignedXidsAdd(next_expected_xid, xid, false);
3207 
3208  /*
3209  * Now we can advance latestObservedXid
3210  */
3211  latestObservedXid = xid;
3212 
3213  /* ShmemVariableCache->nextXid must be beyond any observed xid */
3214  next_expected_xid = latestObservedXid;
3215  TransactionIdAdvance(next_expected_xid);
3216  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
3217  ShmemVariableCache->nextXid = next_expected_xid;
3218  LWLockRelease(XidGenLock);
3219  }
3220 }
3221 
3222 /*
3223  * ExpireTreeKnownAssignedTransactionIds
3224  * Remove the given XIDs from KnownAssignedXids.
3225  *
3226  * Called during recovery in analogy with and in place of ProcArrayEndTransaction()
3227  */
3228 void
3230  TransactionId *subxids, TransactionId max_xid)
3231 {
3233 
3234  /*
3235  * Uses same locking as transaction commit
3236  */
3237  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3238 
3239  KnownAssignedXidsRemoveTree(xid, nsubxids, subxids);
3240 
3241  /* As in ProcArrayEndTransaction, advance latestCompletedXid */
3243  max_xid))
3245 
3246  LWLockRelease(ProcArrayLock);
3247 }
3248 
3249 /*
3250  * ExpireAllKnownAssignedTransactionIds
3251  * Remove all entries in KnownAssignedXids
3252  */
3253 void
3255 {
3256  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3258  LWLockRelease(ProcArrayLock);
3259 }
3260 
3261 /*
3262  * ExpireOldKnownAssignedTransactionIds
3263  * Remove KnownAssignedXids entries preceding the given XID
3264  */
3265 void
3267 {
3268  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3270  LWLockRelease(ProcArrayLock);
3271 }
3272 
3273 
3274 /*
3275  * Private module functions to manipulate KnownAssignedXids
3276  *
3277  * There are 5 main uses of the KnownAssignedXids data structure:
3278  *
3279  * * backends taking snapshots - all valid XIDs need to be copied out
3280  * * backends seeking to determine presence of a specific XID
3281  * * startup process adding new known-assigned XIDs
3282  * * startup process removing specific XIDs as transactions end
3283  * * startup process pruning array when special WAL records arrive
3284  *
3285  * This data structure is known to be a hot spot during Hot Standby, so we
3286  * go to some lengths to make these operations as efficient and as concurrent
3287  * as possible.
3288  *
3289  * The XIDs are stored in an array in sorted order --- TransactionIdPrecedes
3290  * order, to be exact --- to allow binary search for specific XIDs. Note:
3291  * in general TransactionIdPrecedes would not provide a total order, but
3292  * we know that the entries present at any instant should not extend across
3293  * a large enough fraction of XID space to wrap around (the master would
3294  * shut down for fear of XID wrap long before that happens). So it's OK to
3295  * use TransactionIdPrecedes as a binary-search comparator.
3296  *
3297  * It's cheap to maintain the sortedness during insertions, since new known
3298  * XIDs are always reported in XID order; we just append them at the right.
3299  *
3300  * To keep individual deletions cheap, we need to allow gaps in the array.
3301  * This is implemented by marking array elements as valid or invalid using
3302  * the parallel boolean array KnownAssignedXidsValid[]. A deletion is done
3303  * by setting KnownAssignedXidsValid[i] to false, *without* clearing the
3304  * XID entry itself. This preserves the property that the XID entries are
3305  * sorted, so we can do binary searches easily. Periodically we compress
3306  * out the unused entries; that's much cheaper than having to compress the
3307  * array immediately on every deletion.
3308  *
3309  * The actually valid items in KnownAssignedXids[] and KnownAssignedXidsValid[]
3310  * are those with indexes tail <= i < head; items outside this subscript range
3311  * have unspecified contents. When head reaches the end of the array, we
3312  * force compression of unused entries rather than wrapping around, since
3313  * allowing wraparound would greatly complicate the search logic. We maintain
3314  * an explicit tail pointer so that pruning of old XIDs can be done without
3315  * immediately moving the array contents. In most cases only a small fraction
3316  * of the array contains valid entries at any instant.
3317  *
3318  * Although only the startup process can ever change the KnownAssignedXids
3319  * data structure, we still need interlocking so that standby backends will
3320  * not observe invalid intermediate states. The convention is that backends
3321  * must hold shared ProcArrayLock to examine the array. To remove XIDs from
3322  * the array, the startup process must hold ProcArrayLock exclusively, for
3323  * the usual transactional reasons (compare commit/abort of a transaction
3324  * during normal running). Compressing unused entries out of the array
3325  * likewise requires exclusive lock. To add XIDs to the array, we just insert
3326  * them into slots to the right of the head pointer and then advance the head
3327  * pointer. This wouldn't require any lock at all, except that on machines
3328  * with weak memory ordering we need to be careful that other processors
3329  * see the array element changes before they see the head pointer change.
3330  * We handle this by using a spinlock to protect reads and writes of the
3331  * head/tail pointers. (We could dispense with the spinlock if we were to
3332  * create suitable memory access barrier primitives and use those instead.)
3333  * The spinlock must be taken to read or write the head/tail pointers unless
3334  * the caller holds ProcArrayLock exclusively.
3335  *
3336  * Algorithmic analysis:
3337  *
3338  * If we have a maximum of M slots, with N XIDs currently spread across
3339  * S elements then we have N <= S <= M always.
3340  *
3341  * * Adding a new XID is O(1) and needs little locking (unless compression
3342  * must happen)
3343  * * Compressing the array is O(S) and requires exclusive lock
3344  * * Removing an XID is O(logS) and requires exclusive lock
3345  * * Taking a snapshot is O(S) and requires shared lock
3346  * * Checking for an XID is O(logS) and requires shared lock
3347  *
3348  * In comparison, using a hash table for KnownAssignedXids would mean that
3349  * taking snapshots would be O(M). If we can maintain S << M then the
3350  * sorted array technique will deliver significantly faster snapshots.
3351  * If we try to keep S too small then we will spend too much time compressing,
3352  * so there is an optimal point for any workload mix. We use a heuristic to
3353  * decide when to compress the array, though trimming also helps reduce
3354  * frequency of compressing. The heuristic requires us to track the number of
3355  * currently valid XIDs in the array.
3356  */
3357 
3358 
3359 /*
3360  * Compress KnownAssignedXids by shifting valid data down to the start of the
3361  * array, removing any gaps.
3362  *
3363  * A compression step is forced if "force" is true, otherwise we do it
3364  * only if a heuristic indicates it's a good time to do it.
3365  *
3366  * Caller must hold ProcArrayLock in exclusive mode.
3367  */
3368 static void
3370 {
3371  /* use volatile pointer to prevent code rearrangement */
3372  volatile ProcArrayStruct *pArray = procArray;
3373  int head,
3374  tail;
3375  int compress_index;
3376  int i;
3377 
3378  /* no spinlock required since we hold ProcArrayLock exclusively */
3379  head = pArray->headKnownAssignedXids;
3380  tail = pArray->tailKnownAssignedXids;
3381 
3382  if (!force)
3383  {
3384  /*
3385  * If we can choose how much to compress, use a heuristic to avoid
3386  * compressing too often or not often enough.
3387  *
3388  * Heuristic is if we have a large enough current spread and less than
3389  * 50% of the elements are currently in use, then compress. This
3390  * should ensure we compress fairly infrequently. We could compress
3391  * less often though the virtual array would spread out more and
3392  * snapshots would become more expensive.
3393  */
3394  int nelements = head - tail;
3395 
3396  if (nelements < 4 * PROCARRAY_MAXPROCS ||
3397  nelements < 2 * pArray->numKnownAssignedXids)
3398  return;
3399  }
3400 
3401  /*
3402  * We compress the array by reading the valid values from tail to head,
3403  * re-aligning data to 0th element.
3404  */
3405  compress_index = 0;
3406  for (i = tail; i < head; i++)
3407  {
3408  if (KnownAssignedXidsValid[i])
3409  {
3410  KnownAssignedXids[compress_index] = KnownAssignedXids[i];
3411  KnownAssignedXidsValid[compress_index] = true;
3412  compress_index++;
3413  }
3414  }
3415 
3416  pArray->tailKnownAssignedXids = 0;
3417  pArray->headKnownAssignedXids = compress_index;
3418 }
3419 
3420 /*
3421  * Add xids into KnownAssignedXids at the head of the array.
3422  *
3423  * xids from from_xid to to_xid, inclusive, are added to the array.
3424  *
3425  * If exclusive_lock is true then caller already holds ProcArrayLock in
3426  * exclusive mode, so we need no extra locking here. Else caller holds no
3427  * lock, so we need to be sure we maintain sufficient interlocks against
3428  * concurrent readers. (Only the startup process ever calls this, so no need
3429  * to worry about concurrent writers.)
3430  */
3431 static void
3433  bool exclusive_lock)
3434 {
3435  /* use volatile pointer to prevent code rearrangement */
3436  volatile ProcArrayStruct *pArray = procArray;
3437  TransactionId next_xid;
3438  int head,
3439  tail;
3440  int nxids;
3441  int i;
3442 
3443  Assert(TransactionIdPrecedesOrEquals(from_xid, to_xid));
3444 
3445  /*
3446  * Calculate how many array slots we'll need. Normally this is cheap; in
3447  * the unusual case where the XIDs cross the wrap point, we do it the hard
3448  * way.
3449  */
3450  if (to_xid >= from_xid)
3451  nxids = to_xid - from_xid + 1;
3452  else
3453  {
3454  nxids = 1;
3455  next_xid = from_xid;
3456  while (TransactionIdPrecedes(next_xid, to_xid))
3457  {
3458  nxids++;
3459  TransactionIdAdvance(next_xid);
3460  }
3461  }
3462 
3463  /*
3464  * Since only the startup process modifies the head/tail pointers, we
3465  * don't need a lock to read them here.
3466  */
3467  head = pArray->headKnownAssignedXids;
3468  tail = pArray->tailKnownAssignedXids;
3469 
3470  Assert(head >= 0 && head <= pArray->maxKnownAssignedXids);
3471  Assert(tail >= 0 && tail < pArray->maxKnownAssignedXids);
3472 
3473  /*
3474  * Verify that insertions occur in TransactionId sequence. Note that even
3475  * if the last existing element is marked invalid, it must still have a
3476  * correctly sequenced XID value.
3477  */
3478  if (head > tail &&
3479  TransactionIdFollowsOrEquals(KnownAssignedXids[head - 1], from_xid))
3480  {
3482  elog(ERROR, "out-of-order XID insertion in KnownAssignedXids");
3483  }
3484 
3485  /*
3486  * If our xids won't fit in the remaining space, compress out free space
3487  */
3488  if (head + nxids > pArray->maxKnownAssignedXids)
3489  {
3490  /* must hold lock to compress */
3491  if (!exclusive_lock)
3492  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3493 
3495 
3496  head = pArray->headKnownAssignedXids;
3497  /* note: we no longer care about the tail pointer */
3498 
3499  if (!exclusive_lock)
3500  LWLockRelease(ProcArrayLock);
3501 
3502  /*
3503  * If it still won't fit then we're out of memory
3504  */
3505  if (head + nxids > pArray->maxKnownAssignedXids)
3506  elog(ERROR, "too many KnownAssignedXids");
3507  }
3508 
3509  /* Now we can insert the xids into the space starting at head */
3510  next_xid = from_xid;
3511  for (i = 0; i < nxids; i++)
3512  {
3513  KnownAssignedXids[head] = next_xid;
3514  KnownAssignedXidsValid[head] = true;
3515  TransactionIdAdvance(next_xid);
3516  head++;
3517  }
3518 
3519  /* Adjust count of number of valid entries */
3520  pArray->numKnownAssignedXids += nxids;
3521 
3522  /*
3523  * Now update the head pointer. We use a spinlock to protect this
3524  * pointer, not because the update is likely to be non-atomic, but to
3525  * ensure that other processors see the above array updates before they
3526  * see the head pointer change.
3527  *
3528  * If we're holding ProcArrayLock exclusively, there's no need to take the
3529  * spinlock.
3530  */
3531  if (exclusive_lock)
3532  pArray->headKnownAssignedXids = head;
3533  else
3534  {
3536  pArray->headKnownAssignedXids = head;
3538  }
3539 }
3540 
3541 /*
3542  * KnownAssignedXidsSearch
3543  *
3544  * Searches KnownAssignedXids for a specific xid and optionally removes it.
3545  * Returns true if it was found, false if not.
3546  *
3547  * Caller must hold ProcArrayLock in shared or exclusive mode.
3548  * Exclusive lock must be held for remove = true.
3549  */
3550 static bool
3552 {
3553  /* use volatile pointer to prevent code rearrangement */
3554  volatile ProcArrayStruct *pArray = procArray;
3555  int first,
3556  last;
3557  int head;
3558  int tail;
3559  int result_index = -1;
3560 
3561  if (remove)
3562  {
3563  /* we hold ProcArrayLock exclusively, so no need for spinlock */
3564  tail = pArray->tailKnownAssignedXids;
3565  head = pArray->headKnownAssignedXids;
3566  }
3567  else
3568  {
3569  /* take spinlock to ensure we see up-to-date array contents */
3571  tail = pArray->tailKnownAssignedXids;
3572  head = pArray->headKnownAssignedXids;
3574  }
3575 
3576  /*
3577  * Standard binary search. Note we can ignore the KnownAssignedXidsValid
3578  * array here, since even invalid entries will contain sorted XIDs.
3579  */
3580  first = tail;
3581  last = head - 1;
3582  while (first <= last)
3583  {
3584  int mid_index;
3585  TransactionId mid_xid;
3586 
3587  mid_index = (first + last) / 2;
3588  mid_xid = KnownAssignedXids[mid_index];
3589 
3590  if (xid == mid_xid)
3591  {
3592  result_index = mid_index;
3593  break;
3594  }
3595  else if (TransactionIdPrecedes(xid, mid_xid))
3596  last = mid_index - 1;
3597  else
3598  first = mid_index + 1;
3599  }
3600 
3601  if (result_index < 0)
3602  return false; /* not in array */
3603 
3604  if (!KnownAssignedXidsValid[result_index])
3605  return false; /* in array, but invalid */
3606 
3607  if (remove)
3608  {
3609  KnownAssignedXidsValid[result_index] = false;
3610 
3611  pArray->numKnownAssignedXids--;
3612  Assert(pArray->numKnownAssignedXids >= 0);
3613 
3614  /*
3615  * If we're removing the tail element then advance tail pointer over
3616  * any invalid elements. This will speed future searches.
3617  */
3618  if (result_index == tail)
3619  {
3620  tail++;
3621  while (tail < head && !KnownAssignedXidsValid[tail])
3622  tail++;
3623  if (tail >= head)
3624  {
3625  /* Array is empty, so we can reset both pointers */
3626  pArray->headKnownAssignedXids = 0;
3627  pArray->tailKnownAssignedXids = 0;
3628  }
3629  else
3630  {
3631  pArray->tailKnownAssignedXids = tail;
3632  }
3633  }
3634  }
3635 
3636  return true;
3637 }
3638 
3639 /*
3640  * Is the specified XID present in KnownAssignedXids[]?
3641  *
3642  * Caller must hold ProcArrayLock in shared or exclusive mode.
3643  */
3644 static bool
3646 {
3648 
3649  return KnownAssignedXidsSearch(xid, false);
3650 }
3651 
3652 /*
3653  * Remove the specified XID from KnownAssignedXids[].
3654  *
3655  * Caller must hold ProcArrayLock in exclusive mode.
3656  */
3657 static void
3659 {
3661 
3662  elog(trace_recovery(DEBUG4), "remove KnownAssignedXid %u", xid);
3663 
3664  /*
3665  * Note: we cannot consider it an error to remove an XID that's not
3666  * present. We intentionally remove subxact IDs while processing
3667  * XLOG_XACT_ASSIGNMENT, to avoid array overflow. Then those XIDs will be
3668  * removed again when the top-level xact commits or aborts.
3669  *
3670  * It might be possible to track such XIDs to distinguish this case from
3671  * actual errors, but it would be complicated and probably not worth it.
3672  * So, just ignore the search result.
3673  */
3674  (void) KnownAssignedXidsSearch(xid, true);
3675 }
3676 
3677 /*
3678  * KnownAssignedXidsRemoveTree
3679  * Remove xid (if it's not InvalidTransactionId) and all the subxids.
3680  *
3681  * Caller must hold ProcArrayLock in exclusive mode.
3682  */
3683 static void
3685  TransactionId *subxids)
3686 {
3687  int i;
3688 
3689  if (TransactionIdIsValid(xid))
3691 
3692  for (i = 0; i < nsubxids; i++)
3693  KnownAssignedXidsRemove(subxids[i]);
3694 
3695  /* Opportunistically compress the array */
3697 }
3698 
3699 /*
3700  * Prune KnownAssignedXids up to, but *not* including xid. If xid is invalid
3701  * then clear the whole table.
3702  *
3703  * Caller must hold ProcArrayLock in exclusive mode.
3704  */
3705 static void
3707 {
3708  /* use volatile pointer to prevent code rearrangement */
3709  volatile ProcArrayStruct *pArray = procArray;
3710  int count = 0;
3711  int head,
3712  tail,
3713  i;
3714 
3715  if (!TransactionIdIsValid(removeXid))
3716  {
3717  elog(trace_recovery(DEBUG4), "removing all KnownAssignedXids");
3718  pArray->numKnownAssignedXids = 0;
3719  pArray->headKnownAssignedXids = pArray->tailKnownAssignedXids = 0;
3720  return;
3721  }
3722 
3723  elog(trace_recovery(DEBUG4), "prune KnownAssignedXids to %u", removeXid);
3724 
3725  /*
3726  * Mark entries invalid starting at the tail. Since array is sorted, we
3727  * can stop as soon as we reach an entry >= removeXid.
3728  */
3729  tail = pArray->tailKnownAssignedXids;
3730  head = pArray->headKnownAssignedXids;
3731 
3732  for (i = tail; i < head; i++)
3733  {
3734  if (KnownAssignedXidsValid[i])
3735  {
3736  TransactionId knownXid = KnownAssignedXids[i];
3737 
3738  if (TransactionIdFollowsOrEquals(knownXid, removeXid))
3739  break;
3740 
3741  if (!StandbyTransactionIdIsPrepared(knownXid))
3742  {
3743  KnownAssignedXidsValid[i] = false;
3744  count++;
3745  }
3746  }
3747  }
3748 
3749  pArray->numKnownAssignedXids -= count;
3750  Assert(pArray->numKnownAssignedXids >= 0);
3751 
3752  /*
3753  * Advance the tail pointer if we've marked the tail item invalid.
3754  */
3755  for (i = tail; i < head; i++)
3756  {
3757  if (KnownAssignedXidsValid[i])
3758  break;
3759  }
3760  if (i >= head)
3761  {
3762  /* Array is empty, so we can reset both pointers */
3763  pArray->headKnownAssignedXids = 0;
3764  pArray->tailKnownAssignedXids = 0;
3765  }
3766  else
3767  {
3768  pArray->tailKnownAssignedXids = i;
3769  }
3770 
3771  /* Opportunistically compress the array */
3773 }
3774 
3775 /*
3776  * KnownAssignedXidsGet - Get an array of xids by scanning KnownAssignedXids.
3777  * We filter out anything >= xmax.
3778  *
3779  * Returns the number of XIDs stored into xarray[]. Caller is responsible
3780  * that array is large enough.
3781  *
3782  * Caller must hold ProcArrayLock in (at least) shared mode.
3783  */
3784 static int
3786 {
3788 
3789  return KnownAssignedXidsGetAndSetXmin(xarray, &xtmp, xmax);
3790 }
3791 
3792 /*
3793  * KnownAssignedXidsGetAndSetXmin - as KnownAssignedXidsGet, plus
3794  * we reduce *xmin to the lowest xid value seen if not already lower.
3795  *
3796  * Caller must hold ProcArrayLock in (at least) shared mode.
3797  */
3798 static int
3800  TransactionId xmax)
3801 {
3802  int count = 0;
3803  int head,
3804  tail;
3805  int i;
3806 
3807  /*
3808  * Fetch head just once, since it may change while we loop. We can stop
3809  * once we reach the initially seen head, since we are certain that an xid
3810  * cannot enter and then leave the array while we hold ProcArrayLock. We
3811  * might miss newly-added xids, but they should be >= xmax so irrelevant
3812  * anyway.
3813  *
3814  * Must take spinlock to ensure we see up-to-date array contents.
3815  */
3817  tail = procArray->tailKnownAssignedXids;
3818  head = procArray->headKnownAssignedXids;
3820 
3821  for (i = tail; i < head; i++)
3822  {
3823  /* Skip any gaps in the array */
3824  if (KnownAssignedXidsValid[i])
3825  {
3826  TransactionId knownXid = KnownAssignedXids[i];
3827 
3828  /*
3829  * Update xmin if required. Only the first XID need be checked,
3830  * since the array is sorted.
3831  */
3832  if (count == 0 &&
3833  TransactionIdPrecedes(knownXid, *xmin))
3834  *xmin = knownXid;
3835 
3836  /*
3837  * Filter out anything >= xmax, again relying on sorted property
3838  * of array.
3839  */
3840  if (TransactionIdIsValid(xmax) &&
3841  TransactionIdFollowsOrEquals(knownXid, xmax))
3842  break;
3843 
3844  /* Add knownXid into output array */
3845  xarray[count++] = knownXid;
3846  }
3847  }
3848 
3849  return count;
3850 }
3851 
3852 /*
3853  * Get oldest XID in the KnownAssignedXids array, or InvalidTransactionId
3854  * if nothing there.
3855  */
3856 static TransactionId
3858 {
3859  int head,
3860  tail;
3861  int i;
3862 
3863  /*
3864  * Fetch head just once, since it may change while we loop.
3865  */
3867  tail = procArray->tailKnownAssignedXids;
3868  head = procArray->headKnownAssignedXids;
3870 
3871  for (i = tail; i < head; i++)
3872  {
3873  /* Skip any gaps in the array */
3874  if (KnownAssignedXidsValid[i])
3875  return KnownAssignedXids[i];
3876  }
3877 
3878  return InvalidTransactionId;
3879 }
3880 
3881 /*
3882  * Display KnownAssignedXids to provide debug trail
3883  *
3884  * Currently this is only called within startup process, so we need no
3885  * special locking.
3886  *
3887  * Note this is pretty expensive, and much of the expense will be incurred
3888  * even if the elog message will get discarded. It's not currently called
3889  * in any performance-critical places, however, so no need to be tenser.
3890  */
3891 static void
3893 {
3894  /* use volatile pointer to prevent code rearrangement */
3895  volatile ProcArrayStruct *pArray = procArray;
3897  int head,
3898  tail,
3899  i;
3900  int nxids = 0;
3901 
3902  tail = pArray->tailKnownAssignedXids;
3903  head = pArray->headKnownAssignedXids;
3904 
3905  initStringInfo(&buf);
3906 
3907  for (i = tail; i < head; i++)
3908  {
3909  if (KnownAssignedXidsValid[i])
3910  {
3911  nxids++;
3912  appendStringInfo(&buf, "[%d]=%u ", i, KnownAssignedXids[i]);
3913  }
3914  }
3915 
3916  elog(trace_level, "%d KnownAssignedXids (num=%d tail=%d head=%d) %s",
3917  nxids,
3918  pArray->numKnownAssignedXids,
3919  pArray->tailKnownAssignedXids,
3920  pArray->headKnownAssignedXids,
3921  buf.data);
3922 
3923  pfree(buf.data);
3924 }
3925 
3926 /*
3927  * KnownAssignedXidsReset
3928  * Resets KnownAssignedXids to be empty
3929  */
3930 static void
3932 {
3933  /* use volatile pointer to prevent code rearrangement */
3934  volatile ProcArrayStruct *pArray = procArray;
3935 
3936  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
3937 
3938  pArray->numKnownAssignedXids = 0;
3939  pArray->tailKnownAssignedXids = 0;
3940  pArray->headKnownAssignedXids = 0;
3941 
3942  LWLockRelease(ProcArrayLock);
3943 }
#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:2984
static TransactionId latestObservedXid
Definition: procarray.c:107
bool ProcArrayInstallImportedXmin(TransactionId xmin, TransactionId sourcexid)
Definition: procarray.c:1791
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:2457
TransactionId oldestRunningXid
Definition: standby.h:76
bool procArrayGroupMember
Definition: proc.h:152
pid_t CancelVirtualTransaction(VirtualTransactionId vxid, ProcSignalReason sigmode)
Definition: procarray.c:2620
#define PROCARRAY_MAXPROCS
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int CountDBBackends(Oid databaseid)
Definition: procarray.c:2722
#define DEBUG1
Definition: elog.h:25
static void KnownAssignedXidsDisplay(int trace_level)
Definition: procarray.c:3892
#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:47
uint32 TransactionId
Definition: c.h:393
bool copied
Definition: snapshot.h:93
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:323
Definition: proc.h:197
#define DEBUG3
Definition: elog.h:23
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:772
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:147
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1830
TransactionId xmin
Definition: proc.h:203
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:2329
PGXACT * allPgXact
Definition: proc.h:224
PGPROC * MyProc
Definition: proc.c:67
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:995
TransactionId xid
Definition: proc.h:199
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
void SubTransSetParent(TransactionId xid, TransactionId parent, bool overwriteOK)
Definition: subtrans.c:76
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:2545
TransactionId replication_slot_catalog_xmin
Definition: procarray.c:91
XLogRecPtr lsn
Definition: snapshot.h:111
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2237
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:104
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:90
TransactionId * xids
Definition: standby.h:79
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7825
#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:3229
#define MAXAUTOVACPIDS
uint32 regd_count
Definition: snapshot.h:107
#define OidIsValid(objectId)
Definition: c.h:533
void ProcArrayGetReplicationSlotXmin(TransactionId *xmin, TransactionId *catalog_xmin)
Definition: procarray.c:2969
void ExpireAllKnownAssignedTransactionIds(void)
Definition: procarray.c:3254
PGXACT * MyPgXact
Definition: proc.c:68
int trace_recovery(int trace_level)
Definition: elog.c:3753
uint8 vacuumFlags
Definition: proc.h:208
#define PROC_VACUUM_STATE_MASK
Definition: proc.h:51
TransactionId TransactionXmin
Definition: snapmgr.c:164
TransactionId latestCompletedXid
Definition: standby.h:77
Definition: type.h:90
#define malloc(a)
Definition: header.h:45
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
bool isBackgroundWorker
Definition: proc.h:106
#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:2668
static void KnownAssignedXidsRemovePreceding(TransactionId xid)
Definition: procarray.c:3706
PGPROC * BackendPidGetProcWithLock(int pid)
Definition: procarray.c:2352
#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
int64 GetSnapshotCurrentTimestamp(void)
Definition: snapmgr.c:1631
void pfree(void *pointer)
Definition: mcxt.c:992
#define PROC_IN_VACUUM
Definition: proc.h:44
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:2752
#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:2999
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:312
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:331
#define FATAL
Definition: elog.h:52
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:11023
TransactionId nextXid
Definition: transam.h:117
void CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
Definition: procarray.c:2783
#define xc_by_main_xid_inc()
Definition: procarray.c:146
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1282
static char * buf
Definition: pg_test_fsync.c:65
bool recoveryConflictPending
Definition: proc.h:113
#define memmove(d, s, c)
Definition: c.h:1057
#define xc_by_known_assigned_inc()
Definition: procarray.c:148
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
uint8 nxids
Definition: proc.h:213
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:1295
static PGPROC * allProcs
Definition: procarray.c:99
Oid databaseId
Definition: proc.h:103
unsigned int uint32
Definition: c.h:265
TransactionId xmax
Definition: snapshot.h:66
TransactionId xmin
Definition: snapshot.h:65
static void KnownAssignedXidsReset(void)
Definition: procarray.c:3931
LOCK * waitLock
Definition: proc.h:125
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:148
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:210
#define INVALID_PGPROCNO
Definition: proc.h:66
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:76
static void KnownAssignedXidsRemoveTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:3684
pg_atomic_uint32 procArrayGroupNext
Definition: proc.h:154
Definition: proc.h:219
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:2389
#define InvalidBackendId
Definition: backendid.h:23
static PGXACT * allPgXact
Definition: procarray.c:100
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:556
static int KnownAssignedXidsGet(TransactionId *xarray, TransactionId xmax)
Definition: procarray.c:3785
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
Oid MyDatabaseId
Definition: globals.c:76
static TransactionId KnownAssignedXidsGetOldestXmin(void)
Definition: procarray.c:3857
bool overflowed
Definition: proc.h:209
void StandbyReleaseOldLocks(int nxids, TransactionId *xids)
Definition: standby.c:729
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:95
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:1451
TransactionId GetOldestXmin(Relation rel, bool ignoreVacuum)
Definition: procarray.c:1305
int pgprocnos[FLEXIBLE_ARRAY_MEMBER]
Definition: procarray.c:94
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:39
int64 whenTaken
Definition: snapshot.h:110
#define TOTAL_MAX_CACHED_SUBXIDS
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
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:92
size_t Size
Definition: c.h:352
Snapshot GetSnapshotData(Snapshot snapshot)
Definition: procarray.c:1503
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
void LWLockRegisterTranche(int tranche_id, char *tranche_name)
Definition: lwlock.c:591
static int KnownAssignedXidsGetAndSetXmin(TransactionId *xarray, TransactionId *xmin, TransactionId xmax)
Definition: procarray.c:3799
static void KnownAssignedXidsAdd(TransactionId from_xid, TransactionId to_xid, bool exclusive_lock)
Definition: procarray.c:3432
bool ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc)
Definition: procarray.c:1863
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:62
#define xc_no_overflow_inc()
Definition: procarray.c:149
bool EnableHotStandby
Definition: xlog.c:94
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:303
static void KnownAssignedXidsCompress(bool force)
Definition: procarray.c:3369
int CountUserBackends(Oid roleid)
Definition: procarray.c:2823
TransactionId GetOldestSafeDecodingTransactionId(void)
Definition: procarray.c:2149
static bool KnownAssignedXidExists(TransactionId xid)
Definition: procarray.c:3645
int pgprocno
Definition: proc.h:99
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:234
void ProcArrayInitRecovery(TransactionId initializedUptoXID)
Definition: procarray.c:633
uint32 xcnt
Definition: snapshot.h:77
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
struct ProcArrayStruct ProcArrayStruct
static bool KnownAssignedXidsSearch(TransactionId xid, bool remove)
Definition: procarray.c:3551
static void KnownAssignedXidsRemove(TransactionId xid)
Definition: procarray.c:3658
int old_snapshot_threshold
Definition: snapmgr.c:74
#define InvalidLocalTransactionId
Definition: lock.h:70
int i
void ExpireOldKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3266
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2083
bool IsBackendPid(int pid)
Definition: procarray.c:2424
#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:2947
int GetMaxSnapshotSubxidCount(void)
Definition: procarray.c:1462
RunningTransactions GetRunningTransactionData(void)
Definition: procarray.c:1925
void ProcArrayApplyXidAssignment(TransactionId topxid, int nsubxids, TransactionId *subxids)
Definition: procarray.c:911
PGPROC * allProcs
Definition: proc.h:222
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2873
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:686
#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
PGSemaphore sem
Definition: proc.h:90
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2282
void RecordKnownAssignedTransactionIds(TransactionId xid)
Definition: procarray.c:3156
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
int tailKnownAssignedXids
Definition: procarray.c:75
static TransactionId standbySnapshotPendingXmin
Definition: procarray.c:114
Definition: proc.h:84
int pid
Definition: proc.h:98
HotStandbyState standbyState
Definition: xlog.c:193
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:273
#define PROC_IS_AUTOVACUUM
Definition: proc.h:43
#define offsetof(type, field)
Definition: c.h:550
TransactionId procArrayGroupMemberXid
Definition: proc.h:160
Size ProcArrayShmemSize(void)
Definition: procarray.c:178
TransactionId * subxip
Definition: snapshot.h:88
uint32 active_count
Definition: snapshot.h:106
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:89
LocalTransactionId lxid
Definition: proc.h:95
TransactionId latestCompletedXid
Definition: transam.h:135
void MaintainOldSnapshotTimeMapping(int64 whenTaken, TransactionId xmin)
Definition: snapmgr.c:1793