1 /*-------------------------------------------------------------------------
4 * postgres OID & XID variables support routines
6 * Copyright (c) 2000-2014, 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/proc.h"
25 #include "utils/syscache.h"
28 /* Number of OIDs to prefetch (preallocate) per XLOG write */
29 #define VAR_OID_PREFETCH 8192
31 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
32 VariableCache ShmemVariableCache = NULL;
36 * Allocate the next XID for a new transaction or subtransaction.
38 * The new XID is also stored into MyPgXact before returning.
40 * Note: when this is called, we are actually already inside a valid
41 * transaction, since XIDs are now not allocated until the transaction
42 * does something. So it is safe to do a database lookup if we want to
43 * issue a warning about XID wrap.
46 GetNewTransactionId(bool isSubXact)
51 * During bootstrap initialization, we return the special bootstrap
54 if (IsBootstrapProcessingMode())
57 MyPgXact->xid = BootstrapTransactionId;
58 return BootstrapTransactionId;
61 /* safety check, we should never get this far in a HS slave */
62 if (RecoveryInProgress())
63 elog(ERROR, "cannot assign TransactionIds during recovery");
65 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
67 xid = ShmemVariableCache->nextXid;
70 * Check to see if it's safe to assign another XID. This protects against
71 * catastrophic data loss due to XID wraparound. The basic rules are:
73 * If we're past xidVacLimit, start trying to force autovacuum cycles.
74 * If we're past xidWarnLimit, start issuing warnings.
75 * If we're past xidStopLimit, refuse to execute transactions, unless
76 * we are running in single-user mode (which gives an escape hatch
77 * to the DBA who somehow got past the earlier defenses).
79 * Note that this coding also appears in GetNewMultiXactId.
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 vacuum that database in single-user mode.\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 vacuum that database in single-user mode.\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.
166 * Now advance the nextXid counter. This must not happen until after we
167 * have successfully completed ExtendCLOG() --- if that routine fails, we
168 * want the next incoming transaction to try it again. We cannot assign
169 * more XIDs until there is CLOG space for them.
171 TransactionIdAdvance(ShmemVariableCache->nextXid);
174 * We must store the new XID into the shared ProcArray before releasing
175 * XidGenLock. This ensures that every active XID older than
176 * latestCompletedXid is present in the ProcArray, which is essential for
177 * correct OldestXmin tracking; see src/backend/access/transam/README.
179 * XXX by storing xid into MyPgXact without acquiring ProcArrayLock, we
180 * are relying on fetch/store of an xid to be atomic, else other backends
181 * might see a partially-set xid here. But holding both locks at once
182 * would be a nasty concurrency hit. So for now, assume atomicity.
184 * Note that readers of PGXACT xid fields should be careful to fetch the
185 * value only once, rather than assume they can read a value multiple
186 * times and get the same answer each time.
188 * The same comments apply to the subxact xid count and overflow fields.
190 * A solution to the atomic-store problem would be to give each PGXACT its
191 * own spinlock used only for fetching/storing that PGXACT's xid and
194 * If there's no room to fit a subtransaction XID into PGPROC, set the
195 * cache-overflowed flag instead. This forces readers to look in
196 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
197 * race-condition window, in that the new XID will not appear as running
198 * until its parent link has been placed into pg_subtrans. However, that
199 * will happen before anyone could possibly have a reason to inquire about
200 * the status of the XID, so it seems OK. (Snapshots taken during this
201 * window *will* include the parent XID, so they will deliver the correct
202 * answer later on when someone does have a reason to inquire.)
206 * Use volatile pointer to prevent code rearrangement; other backends
207 * could be examining my subxids info concurrently, and we don't want
208 * them to see an invalid intermediate state, such as incrementing
209 * nxids before filling the array entry. Note we are assuming that
210 * TransactionId and int fetch/store are atomic.
212 volatile PGPROC *myproc = MyProc;
213 volatile PGXACT *mypgxact = MyPgXact;
219 int nxids = mypgxact->nxids;
221 if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
223 myproc->subxids.xids[nxids] = xid;
224 mypgxact->nxids = nxids + 1;
227 mypgxact->overflowed = true;
231 LWLockRelease(XidGenLock);
237 * Read nextXid but don't allocate it.
240 ReadNewTransactionId(void)
244 LWLockAcquire(XidGenLock, LW_SHARED);
245 xid = ShmemVariableCache->nextXid;
246 LWLockRelease(XidGenLock);
252 * Determine the last safe XID to allocate given the currently oldest
253 * datfrozenxid (ie, the oldest XID that might exist in any database
254 * of our cluster), and the OID of the (or a) database with that value.
257 SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
259 TransactionId xidVacLimit;
260 TransactionId xidWarnLimit;
261 TransactionId xidStopLimit;
262 TransactionId xidWrapLimit;
263 TransactionId curXid;
265 Assert(TransactionIdIsNormal(oldest_datfrozenxid));
268 * The place where we actually get into deep trouble is halfway around
269 * from the oldest potentially-existing XID. (This calculation is
270 * probably off by one or two counts, because the special XIDs reduce the
271 * size of the loop a little bit. But we throw in plenty of slop below,
272 * so it doesn't matter.)
274 xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
275 if (xidWrapLimit < FirstNormalTransactionId)
276 xidWrapLimit += FirstNormalTransactionId;
279 * We'll refuse to continue assigning XIDs in interactive mode once we get
280 * within 1M transactions of data loss. This leaves lots of room for the
281 * DBA to fool around fixing things in a standalone backend, while not
282 * being significant compared to total XID space. (Note that since
283 * vacuuming requires one transaction per table cleaned, we had better be
284 * sure there's lots of XIDs left...)
286 xidStopLimit = xidWrapLimit - 1000000;
287 if (xidStopLimit < FirstNormalTransactionId)
288 xidStopLimit -= FirstNormalTransactionId;
291 * We'll start complaining loudly when we get within 10M transactions of
292 * the stop point. This is kind of arbitrary, but if you let your gas
293 * gauge get down to 1% of full, would you be looking for the next gas
294 * station? We need to be fairly liberal about this number because there
295 * are lots of scenarios where most transactions are done by automatic
296 * clients that won't pay attention to warnings. (No, we're not gonna make
297 * this configurable. If you know enough to configure it, you know enough
298 * to not get in this kind of trouble in the first place.)
300 xidWarnLimit = xidStopLimit - 10000000;
301 if (xidWarnLimit < FirstNormalTransactionId)
302 xidWarnLimit -= FirstNormalTransactionId;
305 * We'll start trying to force autovacuums when oldest_datfrozenxid gets
306 * to be more than autovacuum_freeze_max_age transactions old.
308 * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range,
309 * so that xidVacLimit will be well before xidWarnLimit.
311 * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
312 * we don't have to worry about dealing with on-the-fly changes in its
313 * value. It doesn't look practical to update shared state from a GUC
314 * assign hook (too many processes would try to execute the hook,
315 * resulting in race conditions as well as crashes of those not connected
316 * to shared memory). Perhaps this can be improved someday. See also
317 * SetMultiXactIdLimit.
319 xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
320 if (xidVacLimit < FirstNormalTransactionId)
321 xidVacLimit += FirstNormalTransactionId;
323 /* Grab lock for just long enough to set the new limit values */
324 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
325 ShmemVariableCache->oldestXid = oldest_datfrozenxid;
326 ShmemVariableCache->xidVacLimit = xidVacLimit;
327 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
328 ShmemVariableCache->xidStopLimit = xidStopLimit;
329 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
330 ShmemVariableCache->oldestXidDB = oldest_datoid;
331 curXid = ShmemVariableCache->nextXid;
332 LWLockRelease(XidGenLock);
336 (errmsg("transaction ID wrap limit is %u, limited by database with OID %u",
337 xidWrapLimit, oldest_datoid)));
340 * If past the autovacuum force point, immediately signal an autovac
341 * request. The reason for this is that autovac only processes one
342 * database per invocation. Once it's finished cleaning up the oldest
343 * database, it'll call here, and we'll signal the postmaster to start
344 * another iteration immediately if there are still any old databases.
346 if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
347 IsUnderPostmaster && !InRecovery)
348 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
350 /* Give an immediate warning if past the wrap warn point */
351 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit) && !InRecovery)
353 char *oldest_datname;
356 * We can be called when not inside a transaction, for example during
357 * StartupXLOG(). In such a case we cannot do database access, so we
358 * must just report the oldest DB's OID.
360 * Note: it's also possible that get_database_name fails and returns
361 * NULL, for example because the database just got dropped. We'll
362 * still warn, even though the warning might now be unnecessary.
364 if (IsTransactionState())
365 oldest_datname = get_database_name(oldest_datoid);
367 oldest_datname = NULL;
371 (errmsg("database \"%s\" must be vacuumed within %u transactions",
373 xidWrapLimit - curXid),
374 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
375 "You might also need to commit or roll back old prepared transactions.")));
378 (errmsg("database with OID %u must be vacuumed within %u transactions",
380 xidWrapLimit - curXid),
381 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
382 "You might also need to commit or roll back old prepared transactions.")));
388 * ForceTransactionIdLimitUpdate -- does the XID wrap-limit data need updating?
390 * We primarily check whether oldestXidDB is valid. The cases we have in
391 * mind are that that database was dropped, or the field was reset to zero
392 * by pg_resetxlog. In either case we should force recalculation of the
393 * wrap limit. Also do it if oldestXid is old enough to be forcing
394 * autovacuums or other actions; this ensures we update our state as soon
395 * as possible once extra overhead is being incurred.
398 ForceTransactionIdLimitUpdate(void)
400 TransactionId nextXid;
401 TransactionId xidVacLimit;
402 TransactionId oldestXid;
405 /* Locking is probably not really necessary, but let's be careful */
406 LWLockAcquire(XidGenLock, LW_SHARED);
407 nextXid = ShmemVariableCache->nextXid;
408 xidVacLimit = ShmemVariableCache->xidVacLimit;
409 oldestXid = ShmemVariableCache->oldestXid;
410 oldestXidDB = ShmemVariableCache->oldestXidDB;
411 LWLockRelease(XidGenLock);
413 if (!TransactionIdIsNormal(oldestXid))
414 return true; /* shouldn't happen, but just in case */
415 if (!TransactionIdIsValid(xidVacLimit))
416 return true; /* this shouldn't happen anymore either */
417 if (TransactionIdFollowsOrEquals(nextXid, xidVacLimit))
418 return true; /* past VacLimit, don't delay updating */
419 if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(oldestXidDB)))
420 return true; /* could happen, per comments above */
426 * GetNewObjectId -- allocate a new OID
428 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
429 * wide, counter wraparound will occur eventually, and therefore it is unwise
430 * to assume they are unique unless precautions are taken to make them so.
431 * Hence, this routine should generally not be used directly. The only
432 * direct callers should be GetNewOid() and GetNewRelFileNode() in
440 /* safety check, we should never get this far in a HS slave */
441 if (RecoveryInProgress())
442 elog(ERROR, "cannot assign OIDs during recovery");
444 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
447 * Check for wraparound of the OID counter. We *must* not return 0
448 * (InvalidOid); and as long as we have to check that, it seems a good
449 * idea to skip over everything below FirstNormalObjectId too. (This
450 * basically just avoids lots of collisions with bootstrap-assigned OIDs
451 * right after a wrap occurs, so as to avoid a possibly large number of
452 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
454 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
455 * we only wrap if before that point when in bootstrap or standalone mode.
456 * The first time through this routine after normal postmaster start, the
457 * counter will be forced up to FirstNormalObjectId. This mechanism
458 * leaves the OIDs between FirstBootstrapObjectId and FirstNormalObjectId
459 * available for automatic assignment during initdb, while ensuring they
460 * will never conflict with user-assigned OIDs.
462 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
464 if (IsPostmasterEnvironment)
466 /* wraparound, or first post-initdb assignment, in normal mode */
467 ShmemVariableCache->nextOid = FirstNormalObjectId;
468 ShmemVariableCache->oidCount = 0;
472 /* we may be bootstrapping, so don't enforce the full range */
473 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
475 /* wraparound in standalone mode (unlikely but possible) */
476 ShmemVariableCache->nextOid = FirstNormalObjectId;
477 ShmemVariableCache->oidCount = 0;
482 /* If we run out of logged for use oids then we must log more */
483 if (ShmemVariableCache->oidCount == 0)
485 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
486 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
489 result = ShmemVariableCache->nextOid;
491 (ShmemVariableCache->nextOid)++;
492 (ShmemVariableCache->oidCount)--;
494 LWLockRelease(OidGenLock);