Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * varsup.c
4 : * postgres OID & XID variables support routines
5 : *
6 : * Copyright (c) 2000-2026, PostgreSQL Global Development Group
7 : *
8 : * IDENTIFICATION
9 : * src/backend/access/transam/varsup.c
10 : *
11 : *-------------------------------------------------------------------------
12 : */
13 :
14 : #include "postgres.h"
15 :
16 : #include "access/clog.h"
17 : #include "access/commit_ts.h"
18 : #include "access/subtrans.h"
19 : #include "access/transam.h"
20 : #include "access/xact.h"
21 : #include "access/xlogutils.h"
22 : #include "miscadmin.h"
23 : #include "postmaster/autovacuum.h"
24 : #include "storage/pmsignal.h"
25 : #include "storage/proc.h"
26 : #include "utils/lsyscache.h"
27 : #include "utils/syscache.h"
28 :
29 :
30 : /* Number of OIDs to prefetch (preallocate) per XLOG write */
31 : #define VAR_OID_PREFETCH 8192
32 :
33 : /* pointer to variables struct in shared memory */
34 : TransamVariablesData *TransamVariables = NULL;
35 :
36 :
37 : /*
38 : * Initialization of shared memory for TransamVariables.
39 : */
40 : Size
41 2207 : VarsupShmemSize(void)
42 : {
43 2207 : return sizeof(TransamVariablesData);
44 : }
45 :
46 : void
47 1180 : VarsupShmemInit(void)
48 : {
49 : bool found;
50 :
51 : /* Initialize our shared state struct */
52 1180 : TransamVariables = ShmemInitStruct("TransamVariables",
53 : sizeof(TransamVariablesData),
54 : &found);
55 1180 : if (!IsUnderPostmaster)
56 : {
57 : Assert(!found);
58 1180 : memset(TransamVariables, 0, sizeof(TransamVariablesData));
59 : }
60 : else
61 : Assert(found);
62 1180 : }
63 :
64 : /*
65 : * Allocate the next FullTransactionId for a new transaction or
66 : * subtransaction.
67 : *
68 : * The new XID is also stored into MyProc->xid/ProcGlobal->xids[] before
69 : * returning.
70 : *
71 : * Note: when this is called, we are actually already inside a valid
72 : * transaction, since XIDs are now not allocated until the transaction
73 : * does something. So it is safe to do a database lookup if we want to
74 : * issue a warning about XID wrap.
75 : */
76 : FullTransactionId
77 24535077 : GetNewTransactionId(bool isSubXact)
78 : {
79 : FullTransactionId full_xid;
80 : TransactionId xid;
81 :
82 : /*
83 : * Workers synchronize transaction state at the beginning of each parallel
84 : * operation, so we can't account for new XIDs after that point.
85 : */
86 24535077 : if (IsInParallelMode())
87 0 : elog(ERROR, "cannot assign TransactionIds during a parallel operation");
88 :
89 : /*
90 : * During bootstrap initialization, we return the special bootstrap
91 : * transaction id.
92 : */
93 24535077 : if (IsBootstrapProcessingMode())
94 : {
95 : Assert(!isSubXact);
96 51 : MyProc->xid = BootstrapTransactionId;
97 51 : ProcGlobal->xids[MyProc->pgxactoff] = BootstrapTransactionId;
98 51 : return FullTransactionIdFromEpochAndXid(0, BootstrapTransactionId);
99 : }
100 :
101 : /* safety check, we should never get this far in a HS standby */
102 24535026 : if (RecoveryInProgress())
103 0 : elog(ERROR, "cannot assign TransactionIds during recovery");
104 :
105 24535026 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
106 :
107 24535026 : full_xid = TransamVariables->nextXid;
108 24535026 : xid = XidFromFullTransactionId(full_xid);
109 :
110 : /*----------
111 : * Check to see if it's safe to assign another XID. This protects against
112 : * catastrophic data loss due to XID wraparound. The basic rules are:
113 : *
114 : * If we're past xidVacLimit, start trying to force autovacuum cycles.
115 : * If we're past xidWarnLimit, start issuing warnings.
116 : * If we're past xidStopLimit, refuse to execute transactions, unless
117 : * we are running in single-user mode (which gives an escape hatch
118 : * to the DBA who somehow got past the earlier defenses).
119 : *
120 : * Note that this coding also appears in GetNewMultiXactId.
121 : *----------
122 : */
123 24535026 : if (TransactionIdFollowsOrEquals(xid, TransamVariables->xidVacLimit))
124 : {
125 : /*
126 : * For safety's sake, we release XidGenLock while sending signals,
127 : * warnings, etc. This is not so much because we care about
128 : * preserving concurrency in this situation, as to avoid any
129 : * possibility of deadlock while doing get_database_name(). First,
130 : * copy all the shared values we'll need in this path.
131 : */
132 14767481 : TransactionId xidWarnLimit = TransamVariables->xidWarnLimit;
133 14767481 : TransactionId xidStopLimit = TransamVariables->xidStopLimit;
134 14767481 : TransactionId xidWrapLimit = TransamVariables->xidWrapLimit;
135 14767481 : Oid oldest_datoid = TransamVariables->oldestXidDB;
136 :
137 14767481 : LWLockRelease(XidGenLock);
138 :
139 : /*
140 : * To avoid swamping the postmaster with signals, we issue the autovac
141 : * request only once per 64K transaction starts. This still gives
142 : * plenty of chances before we get into real trouble.
143 : */
144 14767481 : if (IsUnderPostmaster && (xid % 65536) == 0)
145 131688 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
146 :
147 29534962 : if (IsUnderPostmaster &&
148 14767481 : TransactionIdFollowsOrEquals(xid, xidStopLimit))
149 : {
150 6 : char *oldest_datname = get_database_name(oldest_datoid);
151 :
152 : /* complain even if that DB has disappeared */
153 6 : if (oldest_datname)
154 6 : ereport(ERROR,
155 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
156 : errmsg("database is not accepting commands that assign new transaction IDs to avoid wraparound data loss in database \"%s\"",
157 : oldest_datname),
158 : errhint("Execute a database-wide VACUUM in that database.\n"
159 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
160 : else
161 0 : ereport(ERROR,
162 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
163 : errmsg("database is not accepting commands that assign new transaction IDs to avoid wraparound data loss in database with OID %u",
164 : oldest_datoid),
165 : errhint("Execute a database-wide VACUUM in that database.\n"
166 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
167 : }
168 14767475 : else if (TransactionIdFollowsOrEquals(xid, xidWarnLimit))
169 : {
170 167752 : char *oldest_datname = get_database_name(oldest_datoid);
171 :
172 : /* complain even if that DB has disappeared */
173 167752 : if (oldest_datname)
174 167752 : ereport(WARNING,
175 : (errmsg("database \"%s\" must be vacuumed within %u transactions",
176 : oldest_datname,
177 : xidWrapLimit - xid),
178 : errdetail("Approximately %.2f%% of transaction IDs are available for use.",
179 : (double) (xidWrapLimit - xid) / (MaxTransactionId / 2) * 100),
180 : errhint("To avoid transaction ID assignment failures, execute a database-wide VACUUM in that database.\n"
181 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
182 : else
183 0 : ereport(WARNING,
184 : (errmsg("database with OID %u must be vacuumed within %u transactions",
185 : oldest_datoid,
186 : xidWrapLimit - xid),
187 : errdetail("Approximately %.2f%% of transaction IDs are available for use.",
188 : (double) (xidWrapLimit - xid) / (MaxTransactionId / 2) * 100),
189 : errhint("To avoid XID assignment failures, execute a database-wide VACUUM in that database.\n"
190 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
191 : }
192 :
193 : /* Re-acquire lock and start over */
194 14767475 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
195 14767475 : full_xid = TransamVariables->nextXid;
196 14767475 : xid = XidFromFullTransactionId(full_xid);
197 : }
198 :
199 : /*
200 : * If we are allocating the first XID of a new page of the commit log,
201 : * zero out that commit-log page before returning. We must do this while
202 : * holding XidGenLock, else another xact could acquire and commit a later
203 : * XID before we zero the page. Fortunately, a page of the commit log
204 : * holds 32K or more transactions, so we don't have to do this very often.
205 : *
206 : * Extend pg_subtrans and pg_commit_ts too.
207 : */
208 24535020 : ExtendCLOG(xid);
209 24535020 : ExtendCommitTs(xid);
210 24535020 : ExtendSUBTRANS(xid);
211 :
212 : /*
213 : * Now advance the nextXid counter. This must not happen until after we
214 : * have successfully completed ExtendCLOG() --- if that routine fails, we
215 : * want the next incoming transaction to try it again. We cannot assign
216 : * more XIDs until there is CLOG space for them.
217 : */
218 24535020 : FullTransactionIdAdvance(&TransamVariables->nextXid);
219 :
220 : /*
221 : * We must store the new XID into the shared ProcArray before releasing
222 : * XidGenLock. This ensures that every active XID older than
223 : * latestCompletedXid is present in the ProcArray, which is essential for
224 : * correct OldestXmin tracking; see src/backend/access/transam/README.
225 : *
226 : * Note that readers of ProcGlobal->xids/PGPROC->xid should be careful to
227 : * fetch the value for each proc only once, rather than assume they can
228 : * read a value multiple times and get the same answer each time. Note we
229 : * are assuming that TransactionId and int fetch/store are atomic.
230 : *
231 : * The same comments apply to the subxact xid count and overflow fields.
232 : *
233 : * Use of a write barrier prevents dangerous code rearrangement in this
234 : * function; other backends could otherwise e.g. be examining my subxids
235 : * info concurrently, and we don't want them to see an invalid
236 : * intermediate state, such as an incremented nxids before the array entry
237 : * is filled.
238 : *
239 : * Other processes that read nxids should do so before reading xids
240 : * elements with a pg_read_barrier() in between, so that they can be sure
241 : * not to read an uninitialized array element; see
242 : * src/backend/storage/lmgr/README.barrier.
243 : *
244 : * If there's no room to fit a subtransaction XID into PGPROC, set the
245 : * cache-overflowed flag instead. This forces readers to look in
246 : * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
247 : * race-condition window, in that the new XID will not appear as running
248 : * until its parent link has been placed into pg_subtrans. However, that
249 : * will happen before anyone could possibly have a reason to inquire about
250 : * the status of the XID, so it seems OK. (Snapshots taken during this
251 : * window *will* include the parent XID, so they will deliver the correct
252 : * answer later on when someone does have a reason to inquire.)
253 : */
254 24535020 : if (!isSubXact)
255 : {
256 : Assert(ProcGlobal->subxidStates[MyProc->pgxactoff].count == 0);
257 : Assert(!ProcGlobal->subxidStates[MyProc->pgxactoff].overflowed);
258 : Assert(MyProc->subxidStatus.count == 0);
259 : Assert(!MyProc->subxidStatus.overflowed);
260 :
261 : /* LWLockRelease acts as barrier */
262 158319 : MyProc->xid = xid;
263 158319 : ProcGlobal->xids[MyProc->pgxactoff] = xid;
264 : }
265 : else
266 : {
267 24376701 : XidCacheStatus *substat = &ProcGlobal->subxidStates[MyProc->pgxactoff];
268 24376701 : int nxids = MyProc->subxidStatus.count;
269 :
270 : Assert(substat->count == MyProc->subxidStatus.count);
271 : Assert(substat->overflowed == MyProc->subxidStatus.overflowed);
272 :
273 24376701 : if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
274 : {
275 9332 : MyProc->subxids.xids[nxids] = xid;
276 9332 : pg_write_barrier();
277 9332 : MyProc->subxidStatus.count = substat->count = nxids + 1;
278 : }
279 : else
280 24367369 : MyProc->subxidStatus.overflowed = substat->overflowed = true;
281 : }
282 :
283 24535020 : LWLockRelease(XidGenLock);
284 :
285 24535020 : return full_xid;
286 : }
287 :
288 : /*
289 : * Read nextXid but don't allocate it.
290 : */
291 : FullTransactionId
292 344370 : ReadNextFullTransactionId(void)
293 : {
294 : FullTransactionId fullXid;
295 :
296 344370 : LWLockAcquire(XidGenLock, LW_SHARED);
297 344370 : fullXid = TransamVariables->nextXid;
298 344370 : LWLockRelease(XidGenLock);
299 :
300 344370 : return fullXid;
301 : }
302 :
303 : /*
304 : * Advance nextXid to the value after a given xid. The epoch is inferred.
305 : * This must only be called during recovery or from two-phase start-up code.
306 : */
307 : void
308 2935552 : AdvanceNextFullTransactionIdPastXid(TransactionId xid)
309 : {
310 : FullTransactionId newNextFullXid;
311 : TransactionId next_xid;
312 : uint32 epoch;
313 :
314 : /*
315 : * It is safe to read nextXid without a lock, because this is only called
316 : * from the startup process or single-process mode, meaning that no other
317 : * process can modify it.
318 : */
319 : Assert(AmStartupProcess() || !IsUnderPostmaster);
320 :
321 : /* Fast return if this isn't an xid high enough to move the needle. */
322 2935552 : next_xid = XidFromFullTransactionId(TransamVariables->nextXid);
323 2935552 : if (!TransactionIdFollowsOrEquals(xid, next_xid))
324 2909527 : return;
325 :
326 : /*
327 : * Compute the FullTransactionId that comes after the given xid. To do
328 : * this, we preserve the existing epoch, but detect when we've wrapped
329 : * into a new epoch. This is necessary because WAL records and 2PC state
330 : * currently contain 32 bit xids. The wrap logic is safe in those cases
331 : * because the span of active xids cannot exceed one epoch at any given
332 : * point in the WAL stream.
333 : */
334 26025 : TransactionIdAdvance(xid);
335 26025 : epoch = EpochFromFullTransactionId(TransamVariables->nextXid);
336 26025 : if (unlikely(xid < next_xid))
337 0 : ++epoch;
338 26025 : newNextFullXid = FullTransactionIdFromEpochAndXid(epoch, xid);
339 :
340 : /*
341 : * We still need to take a lock to modify the value when there are
342 : * concurrent readers.
343 : */
344 26025 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
345 26025 : TransamVariables->nextXid = newNextFullXid;
346 26025 : LWLockRelease(XidGenLock);
347 : }
348 :
349 : /*
350 : * Advance the cluster-wide value for the oldest valid clog entry.
351 : *
352 : * We must acquire XactTruncationLock to advance the oldestClogXid. It's not
353 : * necessary to hold the lock during the actual clog truncation, only when we
354 : * advance the limit, as code looking up arbitrary xids is required to hold
355 : * XactTruncationLock from when it tests oldestClogXid through to when it
356 : * completes the clog lookup.
357 : */
358 : void
359 1188 : AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
360 : {
361 1188 : LWLockAcquire(XactTruncationLock, LW_EXCLUSIVE);
362 1188 : if (TransactionIdPrecedes(TransamVariables->oldestClogXid,
363 : oldest_datfrozenxid))
364 : {
365 1137 : TransamVariables->oldestClogXid = oldest_datfrozenxid;
366 : }
367 1188 : LWLockRelease(XactTruncationLock);
368 1188 : }
369 :
370 : /*
371 : * Determine the last safe XID to allocate using the currently oldest
372 : * datfrozenxid (ie, the oldest XID that might exist in any database
373 : * of our cluster), and the OID of the (or a) database with that value.
374 : */
375 : void
376 2197 : SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
377 : {
378 : TransactionId xidVacLimit;
379 : TransactionId xidWarnLimit;
380 : TransactionId xidStopLimit;
381 : TransactionId xidWrapLimit;
382 : TransactionId curXid;
383 :
384 : Assert(TransactionIdIsNormal(oldest_datfrozenxid));
385 :
386 : /*
387 : * The place where we actually get into deep trouble is halfway around
388 : * from the oldest potentially-existing XID. (This calculation is
389 : * probably off by one or two counts, because the special XIDs reduce the
390 : * size of the loop a little bit. But we throw in plenty of slop below,
391 : * so it doesn't matter.)
392 : */
393 2197 : xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
394 2197 : if (xidWrapLimit < FirstNormalTransactionId)
395 0 : xidWrapLimit += FirstNormalTransactionId;
396 :
397 : /*
398 : * We'll refuse to continue assigning XIDs in interactive mode once we get
399 : * within 3M transactions of data loss. This leaves lots of room for the
400 : * DBA to fool around fixing things in a standalone backend, while not
401 : * being significant compared to total XID space. (VACUUM requires an XID
402 : * if it truncates at wal_level!=minimal. "VACUUM (ANALYZE)", which a DBA
403 : * might do by reflex, assigns an XID. Hence, we had better be sure
404 : * there's lots of XIDs left...) Also, at default BLCKSZ, this leaves two
405 : * completely-idle segments. In the event of edge-case bugs involving
406 : * page or segment arithmetic, idle segments render the bugs unreachable
407 : * outside of single-user mode.
408 : */
409 2197 : xidStopLimit = xidWrapLimit - 3000000;
410 2197 : if (xidStopLimit < FirstNormalTransactionId)
411 0 : xidStopLimit -= FirstNormalTransactionId;
412 :
413 : /*
414 : * We'll start complaining loudly when we get within 100M transactions of
415 : * data loss. This is kind of arbitrary, but if you let your gas gauge
416 : * get down to 5% of full, would you be looking for the next gas station?
417 : * We need to be fairly liberal about this number because there are lots
418 : * of scenarios where most transactions are done by automatic clients that
419 : * won't pay attention to warnings. (No, we're not gonna make this
420 : * configurable. If you know enough to configure it, you know enough to
421 : * not get in this kind of trouble in the first place.)
422 : */
423 2197 : xidWarnLimit = xidWrapLimit - 100000000;
424 2197 : if (xidWarnLimit < FirstNormalTransactionId)
425 0 : xidWarnLimit -= FirstNormalTransactionId;
426 :
427 : /*
428 : * We'll start trying to force autovacuums when oldest_datfrozenxid gets
429 : * to be more than autovacuum_freeze_max_age transactions old.
430 : *
431 : * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range,
432 : * so that xidVacLimit will be well before xidWarnLimit.
433 : *
434 : * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
435 : * we don't have to worry about dealing with on-the-fly changes in its
436 : * value. It doesn't look practical to update shared state from a GUC
437 : * assign hook (too many processes would try to execute the hook,
438 : * resulting in race conditions as well as crashes of those not connected
439 : * to shared memory). Perhaps this can be improved someday. See also
440 : * SetMultiXactIdLimit.
441 : */
442 2197 : xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
443 2197 : if (xidVacLimit < FirstNormalTransactionId)
444 0 : xidVacLimit += FirstNormalTransactionId;
445 :
446 : /* Grab lock for just long enough to set the new limit values */
447 2197 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
448 2197 : TransamVariables->oldestXid = oldest_datfrozenxid;
449 2197 : TransamVariables->xidVacLimit = xidVacLimit;
450 2197 : TransamVariables->xidWarnLimit = xidWarnLimit;
451 2197 : TransamVariables->xidStopLimit = xidStopLimit;
452 2197 : TransamVariables->xidWrapLimit = xidWrapLimit;
453 2197 : TransamVariables->oldestXidDB = oldest_datoid;
454 2197 : curXid = XidFromFullTransactionId(TransamVariables->nextXid);
455 2197 : LWLockRelease(XidGenLock);
456 :
457 : /* Log the info */
458 2197 : ereport(DEBUG1,
459 : (errmsg_internal("transaction ID wrap limit is %u, limited by database with OID %u",
460 : xidWrapLimit, oldest_datoid)));
461 :
462 : /*
463 : * If past the autovacuum force point, immediately signal an autovac
464 : * request. The reason for this is that autovac only processes one
465 : * database per invocation. Once it's finished cleaning up the oldest
466 : * database, it'll call here, and we'll signal the postmaster to start
467 : * another iteration immediately if there are still any old databases.
468 : */
469 2197 : if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
470 860 : IsUnderPostmaster && !InRecovery)
471 860 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
472 :
473 : /* Give an immediate warning if past the wrap warn point */
474 2197 : if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit) && !InRecovery)
475 : {
476 : char *oldest_datname;
477 :
478 : /*
479 : * We can be called when not inside a transaction, for example during
480 : * StartupXLOG(). In such a case we cannot do database access, so we
481 : * must just report the oldest DB's OID.
482 : *
483 : * Note: it's also possible that get_database_name fails and returns
484 : * NULL, for example because the database just got dropped. We'll
485 : * still warn, even though the warning might now be unnecessary.
486 : */
487 37 : if (IsTransactionState())
488 37 : oldest_datname = get_database_name(oldest_datoid);
489 : else
490 0 : oldest_datname = NULL;
491 :
492 37 : if (oldest_datname)
493 37 : ereport(WARNING,
494 : (errmsg("database \"%s\" must be vacuumed within %u transactions",
495 : oldest_datname,
496 : xidWrapLimit - curXid),
497 : errdetail("Approximately %.2f%% of transaction IDs are available for use.",
498 : (double) (xidWrapLimit - curXid) / (MaxTransactionId / 2) * 100),
499 : errhint("To avoid XID assignment failures, execute a database-wide VACUUM in that database.\n"
500 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
501 : else
502 0 : ereport(WARNING,
503 : (errmsg("database with OID %u must be vacuumed within %u transactions",
504 : oldest_datoid,
505 : xidWrapLimit - curXid),
506 : errdetail("Approximately %.2f%% of transaction IDs are available for use.",
507 : (double) (xidWrapLimit - curXid) / (MaxTransactionId / 2) * 100),
508 : errhint("To avoid XID assignment failures, execute a database-wide VACUUM in that database.\n"
509 : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
510 : }
511 2197 : }
512 :
513 :
514 : /*
515 : * ForceTransactionIdLimitUpdate -- does the XID wrap-limit data need updating?
516 : *
517 : * We primarily check whether oldestXidDB is valid. The cases we have in
518 : * mind are that that database was dropped, or the field was reset to zero
519 : * by pg_resetwal. In either case we should force recalculation of the
520 : * wrap limit. Also do it if oldestXid is old enough to be forcing
521 : * autovacuums or other actions; this ensures we update our state as soon
522 : * as possible once extra overhead is being incurred.
523 : */
524 : bool
525 2142 : ForceTransactionIdLimitUpdate(void)
526 : {
527 : TransactionId nextXid;
528 : TransactionId xidVacLimit;
529 : TransactionId oldestXid;
530 : Oid oldestXidDB;
531 :
532 : /* Locking is probably not really necessary, but let's be careful */
533 2142 : LWLockAcquire(XidGenLock, LW_SHARED);
534 2142 : nextXid = XidFromFullTransactionId(TransamVariables->nextXid);
535 2142 : xidVacLimit = TransamVariables->xidVacLimit;
536 2142 : oldestXid = TransamVariables->oldestXid;
537 2142 : oldestXidDB = TransamVariables->oldestXidDB;
538 2142 : LWLockRelease(XidGenLock);
539 :
540 2142 : if (!TransactionIdIsNormal(oldestXid))
541 0 : return true; /* shouldn't happen, but just in case */
542 2142 : if (!TransactionIdIsValid(xidVacLimit))
543 0 : return true; /* this shouldn't happen anymore either */
544 2142 : if (TransactionIdFollowsOrEquals(nextXid, xidVacLimit))
545 721 : return true; /* past xidVacLimit, don't delay updating */
546 1421 : if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(oldestXidDB)))
547 0 : return true; /* could happen, per comments above */
548 1421 : return false;
549 : }
550 :
551 :
552 : /*
553 : * GetNewObjectId -- allocate a new OID
554 : *
555 : * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
556 : * wide, counter wraparound will occur eventually, and therefore it is unwise
557 : * to assume they are unique unless precautions are taken to make them so.
558 : * Hence, this routine should generally not be used directly. The only direct
559 : * callers should be GetNewOidWithIndex() and GetNewRelFileNumber() in
560 : * catalog/catalog.c.
561 : */
562 : Oid
563 555105 : GetNewObjectId(void)
564 : {
565 : Oid result;
566 :
567 : /* safety check, we should never get this far in a HS standby */
568 555105 : if (RecoveryInProgress())
569 0 : elog(ERROR, "cannot assign OIDs during recovery");
570 :
571 555105 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
572 :
573 : /*
574 : * Check for wraparound of the OID counter. We *must* not return 0
575 : * (InvalidOid), and in normal operation we mustn't return anything below
576 : * FirstNormalObjectId since that range is reserved for initdb (see
577 : * IsCatalogRelationOid()). Note we are relying on unsigned comparison.
578 : *
579 : * During initdb, we start the OID generator at FirstGenbkiObjectId, so we
580 : * only wrap if before that point when in bootstrap or standalone mode.
581 : * The first time through this routine after normal postmaster start, the
582 : * counter will be forced up to FirstNormalObjectId. This mechanism
583 : * leaves the OIDs between FirstGenbkiObjectId and FirstNormalObjectId
584 : * available for automatic assignment during initdb, while ensuring they
585 : * will never conflict with user-assigned OIDs.
586 : */
587 555105 : if (TransamVariables->nextOid < ((Oid) FirstNormalObjectId))
588 : {
589 102561 : if (IsPostmasterEnvironment)
590 : {
591 : /* wraparound, or first post-initdb assignment, in normal mode */
592 391 : TransamVariables->nextOid = FirstNormalObjectId;
593 391 : TransamVariables->oidCount = 0;
594 : }
595 : else
596 : {
597 : /* we may be bootstrapping, so don't enforce the full range */
598 102170 : if (TransamVariables->nextOid < ((Oid) FirstGenbkiObjectId))
599 : {
600 : /* wraparound in standalone mode (unlikely but possible) */
601 0 : TransamVariables->nextOid = FirstNormalObjectId;
602 0 : TransamVariables->oidCount = 0;
603 : }
604 : }
605 : }
606 :
607 : /* If we run out of logged for use oids then we must log more */
608 555105 : if (TransamVariables->oidCount == 0)
609 : {
610 656 : XLogPutNextOid(TransamVariables->nextOid + VAR_OID_PREFETCH);
611 656 : TransamVariables->oidCount = VAR_OID_PREFETCH;
612 : }
613 :
614 555105 : result = TransamVariables->nextOid;
615 :
616 555105 : (TransamVariables->nextOid)++;
617 555105 : (TransamVariables->oidCount)--;
618 :
619 555105 : LWLockRelease(OidGenLock);
620 :
621 555105 : return result;
622 : }
623 :
624 : /*
625 : * SetNextObjectId
626 : *
627 : * This may only be called during initdb; it advances the OID counter
628 : * to the specified value.
629 : */
630 : static void
631 49 : SetNextObjectId(Oid nextOid)
632 : {
633 : /* Safety check, this is only allowable during initdb */
634 49 : if (IsPostmasterEnvironment)
635 0 : elog(ERROR, "cannot advance OID counter anymore");
636 :
637 : /* Taking the lock is, therefore, just pro forma; but do it anyway */
638 49 : LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
639 :
640 49 : if (TransamVariables->nextOid > nextOid)
641 0 : elog(ERROR, "too late to advance OID counter to %u, it is now %u",
642 : nextOid, TransamVariables->nextOid);
643 :
644 49 : TransamVariables->nextOid = nextOid;
645 49 : TransamVariables->oidCount = 0;
646 :
647 49 : LWLockRelease(OidGenLock);
648 49 : }
649 :
650 : /*
651 : * StopGeneratingPinnedObjectIds
652 : *
653 : * This is called once during initdb to force the OID counter up to
654 : * FirstUnpinnedObjectId. This supports letting initdb's post-bootstrap
655 : * processing create some pinned objects early on. Once it's done doing
656 : * so, it calls this (via pg_stop_making_pinned_objects()) so that the
657 : * remaining objects it makes will be considered un-pinned.
658 : */
659 : void
660 49 : StopGeneratingPinnedObjectIds(void)
661 : {
662 49 : SetNextObjectId(FirstUnpinnedObjectId);
663 49 : }
664 :
665 :
666 : #ifdef USE_ASSERT_CHECKING
667 :
668 : /*
669 : * Assert that xid is between [oldestXid, nextXid], which is the range we
670 : * expect XIDs coming from tables etc to be in.
671 : *
672 : * As TransamVariables->oldestXid could change just after this call without
673 : * further precautions, and as a wrapped-around xid could again fall within
674 : * the valid range, this assertion can only detect if something is definitely
675 : * wrong, but not establish correctness.
676 : *
677 : * This intentionally does not expose a return value, to avoid code being
678 : * introduced that depends on the return value.
679 : */
680 : void
681 : AssertTransactionIdInAllowableRange(TransactionId xid)
682 : {
683 : TransactionId oldest_xid;
684 : TransactionId next_xid;
685 :
686 : Assert(TransactionIdIsValid(xid));
687 :
688 : /* we may see bootstrap / frozen */
689 : if (!TransactionIdIsNormal(xid))
690 : return;
691 :
692 : /*
693 : * We can't acquire XidGenLock, as this may be called with XidGenLock
694 : * already held (or with other locks that don't allow XidGenLock to be
695 : * nested). That's ok for our purposes though, since we already rely on
696 : * 32bit reads to be atomic. While nextXid is 64 bit, we only look at the
697 : * lower 32bit, so a skewed read doesn't hurt.
698 : *
699 : * There's no increased danger of falling outside [oldest, next] by
700 : * accessing them without a lock. xid needs to have been created with
701 : * GetNewTransactionId() in the originating session, and the locks there
702 : * pair with the memory barrier below. We do however accept xid to be <=
703 : * to next_xid, instead of just <, as xid could be from the procarray,
704 : * before we see the updated nextXid value.
705 : */
706 : pg_memory_barrier();
707 : oldest_xid = TransamVariables->oldestXid;
708 : next_xid = XidFromFullTransactionId(TransamVariables->nextXid);
709 :
710 : Assert(TransactionIdFollowsOrEquals(xid, oldest_xid) ||
711 : TransactionIdPrecedesOrEquals(xid, next_xid));
712 : }
713 : #endif
|