1 /*-------------------------------------------------------------------------
4 * postgres OID & XID variables support routines
6 * Copyright (c) 2000-2011, PostgreSQL Global Development Group
9 * src/backend/access/transam/varsup.c
11 *-------------------------------------------------------------------------
16 #include "access/clog.h"
17 #include "access/subtrans.h"
18 #include "access/transam.h"
19 #include "access/xact.h"
20 #include "commands/dbcommands.h"
21 #include "miscadmin.h"
22 #include "postmaster/autovacuum.h"
23 #include "storage/pmsignal.h"
24 #include "storage/predicate.h"
25 #include "storage/proc.h"
26 #include "utils/builtins.h"
27 #include "utils/syscache.h"
30 /* Number of OIDs to prefetch (preallocate) per XLOG write */
31 #define VAR_OID_PREFETCH 8192
33 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
34 VariableCache ShmemVariableCache = NULL;
38 * Allocate the next XID for a new transaction or subtransaction.
40 * The new XID is also stored into MyProc before returning.
42 * Note: when this is called, we are actually already inside a valid
43 * transaction, since XIDs are now not allocated until the transaction
44 * does something. So it is safe to do a database lookup if we want to
45 * issue a warning about XID wrap.
48 GetNewTransactionId(bool isSubXact)
53 * During bootstrap initialization, we return the special bootstrap
56 if (IsBootstrapProcessingMode())
59 MyProc->xid = BootstrapTransactionId;
60 return BootstrapTransactionId;
63 /* safety check, we should never get this far in a HS slave */
64 if (RecoveryInProgress())
65 elog(ERROR, "cannot assign TransactionIds during recovery");
67 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
69 xid = ShmemVariableCache->nextXid;
72 * Check to see if it's safe to assign another XID. This protects against
73 * catastrophic data loss due to XID wraparound. The basic rules are:
75 * If we're past xidVacLimit, start trying to force autovacuum cycles.
76 * If we're past xidWarnLimit, start issuing warnings.
77 * If we're past xidStopLimit, refuse to execute transactions, unless
78 * we are running in a standalone backend (which gives an escape hatch
79 * to the DBA who somehow got past the earlier defenses).
82 if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit))
85 * For safety's sake, we release XidGenLock while sending signals,
86 * warnings, etc. This is not so much because we care about
87 * preserving concurrency in this situation, as to avoid any
88 * possibility of deadlock while doing get_database_name(). First,
89 * copy all the shared values we'll need in this path.
91 TransactionId xidWarnLimit = ShmemVariableCache->xidWarnLimit;
92 TransactionId xidStopLimit = ShmemVariableCache->xidStopLimit;
93 TransactionId xidWrapLimit = ShmemVariableCache->xidWrapLimit;
94 Oid oldest_datoid = ShmemVariableCache->oldestXidDB;
96 LWLockRelease(XidGenLock);
99 * To avoid swamping the postmaster with signals, we issue the autovac
100 * request only once per 64K transaction starts. This still gives
101 * plenty of chances before we get into real trouble.
103 if (IsUnderPostmaster && (xid % 65536) == 0)
104 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
106 if (IsUnderPostmaster &&
107 TransactionIdFollowsOrEquals(xid, xidStopLimit))
109 char *oldest_datname = get_database_name(oldest_datoid);
111 /* complain even if that DB has disappeared */
114 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
115 errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
117 errhint("Stop the postmaster and use a standalone backend to vacuum that database.\n"
118 "You might also need to commit or roll back old prepared transactions.")));
121 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
122 errmsg("database is not accepting commands to avoid wraparound data loss in database with OID %u",
124 errhint("Stop the postmaster and use a standalone backend to vacuum that database.\n"
125 "You might also need to commit or roll back old prepared transactions.")));
127 else if (TransactionIdFollowsOrEquals(xid, xidWarnLimit))
129 char *oldest_datname = get_database_name(oldest_datoid);
131 /* complain even if that DB has disappeared */
134 (errmsg("database \"%s\" must be vacuumed within %u transactions",
137 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
138 "You might also need to commit or roll back old prepared transactions.")));
141 (errmsg("database with OID %u must be vacuumed within %u transactions",
144 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
145 "You might also need to commit or roll back old prepared transactions.")));
148 /* Re-acquire lock and start over */
149 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
150 xid = ShmemVariableCache->nextXid;
154 * If we are allocating the first XID of a new page of the commit log,
155 * zero out that commit-log page before returning. We must do this while
156 * holding XidGenLock, else another xact could acquire and commit a later
157 * XID before we zero the page. Fortunately, a page of the commit log
158 * holds 32K or more transactions, so we don't have to do this very often.
160 * Extend pg_subtrans too.
165 /* If it's top level, the predicate locking system also needs to know. */
167 RegisterPredicateLockingXid(xid);
170 * Now advance the nextXid counter. This must not happen until after we
171 * have successfully completed ExtendCLOG() --- if that routine fails, we
172 * want the next incoming transaction to try it again. We cannot assign
173 * more XIDs until there is CLOG space for them.
175 TransactionIdAdvance(ShmemVariableCache->nextXid);
178 * We must store the new XID into the shared ProcArray before releasing
179 * XidGenLock. This ensures that every active XID older than
180 * latestCompletedXid is present in the ProcArray, which is essential for
181 * correct OldestXmin tracking; see src/backend/access/transam/README.
183 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
184 * relying on fetch/store of an xid to be atomic, else other backends
185 * might see a partially-set xid here. But holding both locks at once
186 * would be a nasty concurrency hit. So for now, assume atomicity.
188 * Note that readers of PGPROC xid fields should be careful to fetch the
189 * value only once, rather than assume they can read a value multiple
190 * times and get the same answer each time.
192 * The same comments apply to the subxact xid count and overflow fields.
194 * A solution to the atomic-store problem would be to give each PGPROC its
195 * own spinlock used only for fetching/storing that PGPROC's xid and
198 * If there's no room to fit a subtransaction XID into PGPROC, set the
199 * cache-overflowed flag instead. This forces readers to look in
200 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
201 * race-condition window, in that the new XID will not appear as running
202 * until its parent link has been placed into pg_subtrans. However, that
203 * will happen before anyone could possibly have a reason to inquire about
204 * the status of the XID, so it seems OK. (Snapshots taken during this
205 * window *will* include the parent XID, so they will deliver the correct
206 * answer later on when someone does have a reason to inquire.)
210 * Use volatile pointer to prevent code rearrangement; other backends
211 * could be examining my subxids info concurrently, and we don't want
212 * them to see an invalid intermediate state, such as incrementing
213 * nxids before filling the array entry. Note we are assuming that
214 * TransactionId and int fetch/store are atomic.
216 volatile PGPROC *myproc = MyProc;
222 int nxids = myproc->subxids.nxids;
224 if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
226 myproc->subxids.xids[nxids] = xid;
227 myproc->subxids.nxids = nxids + 1;
230 myproc->subxids.overflowed = true;
234 LWLockRelease(XidGenLock);
240 * Read nextXid but don't allocate it.
243 ReadNewTransactionId(void)
247 LWLockAcquire(XidGenLock, LW_SHARED);
248 xid = ShmemVariableCache->nextXid;
249 LWLockRelease(XidGenLock);
255 * Determine the last safe XID to allocate given the currently oldest
256 * datfrozenxid (ie, the oldest XID that might exist in any database
257 * of our cluster), and the OID of the (or a) database with that value.
260 SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
262 TransactionId xidVacLimit;
263 TransactionId xidWarnLimit;
264 TransactionId xidStopLimit;
265 TransactionId xidWrapLimit;
266 TransactionId curXid;
268 Assert(TransactionIdIsNormal(oldest_datfrozenxid));
271 * The place where we actually get into deep trouble is halfway around
272 * from the oldest potentially-existing XID. (This calculation is
273 * probably off by one or two counts, because the special XIDs reduce the
274 * size of the loop a little bit. But we throw in plenty of slop below,
275 * so it doesn't matter.)
277 xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
278 if (xidWrapLimit < FirstNormalTransactionId)
279 xidWrapLimit += FirstNormalTransactionId;
282 * We'll refuse to continue assigning XIDs in interactive mode once we get
283 * within 1M transactions of data loss. This leaves lots of room for the
284 * DBA to fool around fixing things in a standalone backend, while not
285 * being significant compared to total XID space. (Note that since
286 * vacuuming requires one transaction per table cleaned, we had better be
287 * sure there's lots of XIDs left...)
289 xidStopLimit = xidWrapLimit - 1000000;
290 if (xidStopLimit < FirstNormalTransactionId)
291 xidStopLimit -= FirstNormalTransactionId;
294 * We'll start complaining loudly when we get within 10M transactions of
295 * the stop point. This is kind of arbitrary, but if you let your gas
296 * gauge get down to 1% of full, would you be looking for the next gas
297 * station? We need to be fairly liberal about this number because there
298 * are lots of scenarios where most transactions are done by automatic
299 * clients that won't pay attention to warnings. (No, we're not gonna make
300 * this configurable. If you know enough to configure it, you know enough
301 * to not get in this kind of trouble in the first place.)
303 xidWarnLimit = xidStopLimit - 10000000;
304 if (xidWarnLimit < FirstNormalTransactionId)
305 xidWarnLimit -= FirstNormalTransactionId;
308 * We'll start trying to force autovacuums when oldest_datfrozenxid gets
309 * to be more than autovacuum_freeze_max_age transactions old.
311 * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range,
312 * so that xidVacLimit will be well before xidWarnLimit.
314 * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
315 * we don't have to worry about dealing with on-the-fly changes in its
316 * value. It doesn't look practical to update shared state from a GUC
317 * assign hook (too many processes would try to execute the hook,
318 * resulting in race conditions as well as crashes of those not connected
319 * to shared memory). Perhaps this can be improved someday.
321 xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
322 if (xidVacLimit < FirstNormalTransactionId)
323 xidVacLimit += FirstNormalTransactionId;
325 /* Grab lock for just long enough to set the new limit values */
326 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
327 ShmemVariableCache->oldestXid = oldest_datfrozenxid;
328 ShmemVariableCache->xidVacLimit = xidVacLimit;
329 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
330 ShmemVariableCache->xidStopLimit = xidStopLimit;
331 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
332 ShmemVariableCache->oldestXidDB = oldest_datoid;
333 curXid = ShmemVariableCache->nextXid;
334 LWLockRelease(XidGenLock);
338 (errmsg("transaction ID wrap limit is %u, limited by database with OID %u",
339 xidWrapLimit, oldest_datoid)));
342 * If past the autovacuum force point, immediately signal an autovac
343 * request. The reason for this is that autovac only processes one
344 * database per invocation. Once it's finished cleaning up the oldest
345 * database, it'll call here, and we'll signal the postmaster to start
346 * another iteration immediately if there are still any old databases.
348 if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
349 IsUnderPostmaster && !InRecovery)
350 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
352 /* Give an immediate warning if past the wrap warn point */
353 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit) && !InRecovery)
355 char *oldest_datname;
358 * We can be called when not inside a transaction, for example during
359 * StartupXLOG(). In such a case we cannot do database access, so we
360 * must just report the oldest DB's OID.
362 * Note: it's also possible that get_database_name fails and returns
363 * NULL, for example because the database just got dropped. We'll
364 * still warn, even though the warning might now be unnecessary.
366 if (IsTransactionState())
367 oldest_datname = get_database_name(oldest_datoid);
369 oldest_datname = NULL;
373 (errmsg("database \"%s\" must be vacuumed within %u transactions",
375 xidWrapLimit - curXid),
376 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
377 "You might also need to commit or roll back old prepared transactions.")));
380 (errmsg("database with OID %u must be vacuumed within %u transactions",
382 xidWrapLimit - curXid),
383 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
384 "You might also need to commit or roll back old prepared transactions.")));
390 * ForceTransactionIdLimitUpdate -- does the XID wrap-limit data need updating?
392 * We primarily check whether oldestXidDB is valid. The cases we have in
393 * mind are that that database was dropped, or the field was reset to zero
394 * by pg_resetxlog. In either case we should force recalculation of the
395 * wrap limit. Also do it if oldestXid is old enough to be forcing
396 * autovacuums or other actions; this ensures we update our state as soon
397 * as possible once extra overhead is being incurred.
400 ForceTransactionIdLimitUpdate(void)
402 TransactionId nextXid;
403 TransactionId xidVacLimit;
404 TransactionId oldestXid;
407 /* Locking is probably not really necessary, but let's be careful */
408 LWLockAcquire(XidGenLock, LW_SHARED);
409 nextXid = ShmemVariableCache->nextXid;
410 xidVacLimit = ShmemVariableCache->xidVacLimit;
411 oldestXid = ShmemVariableCache->oldestXid;
412 oldestXidDB = ShmemVariableCache->oldestXidDB;
413 LWLockRelease(XidGenLock);
415 if (!TransactionIdIsNormal(oldestXid))
416 return true; /* shouldn't happen, but just in case */
417 if (!TransactionIdIsValid(xidVacLimit))
418 return true; /* this shouldn't happen anymore either */
419 if (TransactionIdFollowsOrEquals(nextXid, xidVacLimit))
420 return true; /* past VacLimit, don't delay updating */
421 if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(oldestXidDB)))
422 return true; /* could happen, per comments above */
428 * GetNewObjectId -- allocate a new OID
430 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
431 * wide, counter wraparound will occur eventually, and therefore it is unwise
432 * to assume they are unique unless precautions are taken to make them so.
433 * Hence, this routine should generally not be used directly. The only
434 * direct callers should be GetNewOid() and GetNewRelFileNode() in
442 /* safety check, we should never get this far in a HS slave */
443 if (RecoveryInProgress())
444 elog(ERROR, "cannot assign OIDs during recovery");
446 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
449 * Check for wraparound of the OID counter. We *must* not return 0
450 * (InvalidOid); and as long as we have to check that, it seems a good
451 * idea to skip over everything below FirstNormalObjectId too. (This
452 * basically just avoids lots of collisions with bootstrap-assigned OIDs
453 * right after a wrap occurs, so as to avoid a possibly large number of
454 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
456 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
457 * we only enforce wrapping to that point when in bootstrap or standalone
458 * mode. The first time through this routine after normal postmaster
459 * start, the counter will be forced up to FirstNormalObjectId. This
460 * mechanism leaves the OIDs between FirstBootstrapObjectId and
461 * FirstNormalObjectId available for automatic assignment during initdb,
462 * while ensuring they will never conflict with user-assigned OIDs.
464 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
466 if (IsPostmasterEnvironment)
468 /* wraparound in normal environment */
469 ShmemVariableCache->nextOid = FirstNormalObjectId;
470 ShmemVariableCache->oidCount = 0;
474 /* we may be bootstrapping, so don't enforce the full range */
475 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
477 /* wraparound in standalone environment? */
478 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
479 ShmemVariableCache->oidCount = 0;
484 /* If we run out of logged for use oids then we must log more */
485 if (ShmemVariableCache->oidCount == 0)
487 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
488 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
491 result = ShmemVariableCache->nextOid;
493 (ShmemVariableCache->nextOid)++;
494 (ShmemVariableCache->oidCount)--;
496 LWLockRelease(OidGenLock);