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