1 /*-------------------------------------------------------------------------
4 * postgres OID & XID variables support routines
6 * Copyright (c) 2000-2006, PostgreSQL Global Development Group
9 * $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.71 2006/07/10 16:20:49 alvherre Exp $
11 *-------------------------------------------------------------------------
16 #include "access/clog.h"
17 #include "access/subtrans.h"
18 #include "access/transam.h"
19 #include "miscadmin.h"
20 #include "storage/ipc.h"
21 #include "storage/proc.h"
22 #include "utils/builtins.h"
25 /* Number of OIDs to prefetch (preallocate) per XLOG write */
26 #define VAR_OID_PREFETCH 8192
28 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
29 VariableCache ShmemVariableCache = NULL;
33 * Allocate the next XID for my new transaction.
36 GetNewTransactionId(bool isSubXact)
41 * During bootstrap initialization, we return the special bootstrap
44 if (IsBootstrapProcessingMode())
45 return BootstrapTransactionId;
47 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
49 xid = ShmemVariableCache->nextXid;
52 * Check to see if it's safe to assign another XID. This protects against
53 * catastrophic data loss due to XID wraparound. The basic rules are:
54 * warn if we're past xidWarnLimit, and refuse to execute transactions if
55 * we're past xidStopLimit, unless we are running in a standalone backend
56 * (which gives an escape hatch to the DBA who ignored all those
59 * Test is coded to fall out as fast as possible during normal operation,
60 * ie, when the warn limit is set and we haven't violated it.
62 if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit) &&
63 TransactionIdIsValid(ShmemVariableCache->xidWarnLimit))
65 if (IsUnderPostmaster &&
66 TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
68 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
69 errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
70 NameStr(ShmemVariableCache->limit_datname)),
71 errhint("Stop the postmaster and use a standalone backend to vacuum database \"%s\".",
72 NameStr(ShmemVariableCache->limit_datname))));
75 (errmsg("database \"%s\" must be vacuumed within %u transactions",
76 NameStr(ShmemVariableCache->limit_datname),
77 ShmemVariableCache->xidWrapLimit - xid),
78 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
79 NameStr(ShmemVariableCache->limit_datname))));
83 * If we are allocating the first XID of a new page of the commit log,
84 * zero out that commit-log page before returning. We must do this while
85 * holding XidGenLock, else another xact could acquire and commit a later
86 * XID before we zero the page. Fortunately, a page of the commit log
87 * holds 32K or more transactions, so we don't have to do this very often.
89 * Extend pg_subtrans too.
95 * Now advance the nextXid counter. This must not happen until after we
96 * have successfully completed ExtendCLOG() --- if that routine fails, we
97 * want the next incoming transaction to try it again. We cannot assign
98 * more XIDs until there is CLOG space for them.
100 TransactionIdAdvance(ShmemVariableCache->nextXid);
103 * We must store the new XID into the shared PGPROC array before releasing
104 * XidGenLock. This ensures that when GetSnapshotData calls
105 * ReadNewTransactionId, all active XIDs before the returned value of
106 * nextXid are already present in PGPROC. Else we have a race condition.
108 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
109 * relying on fetch/store of an xid to be atomic, else other backends
110 * might see a partially-set xid here. But holding both locks at once
111 * would be a nasty concurrency hit (and in fact could cause a deadlock
112 * against GetSnapshotData). So for now, assume atomicity. Note that
113 * readers of PGPROC xid field should be careful to fetch the value only
114 * once, rather than assume they can read it multiple times and get the
115 * same answer each time.
117 * The same comments apply to the subxact xid count and overflow fields.
119 * A solution to the atomic-store problem would be to give each PGPROC its
120 * own spinlock used only for fetching/storing that PGPROC's xid and
123 * If there's no room to fit a subtransaction XID into PGPROC, set the
124 * cache-overflowed flag instead. This forces readers to look in
125 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
126 * race-condition window, in that the new XID will not appear as running
127 * until its parent link has been placed into pg_subtrans. However, that
128 * will happen before anyone could possibly have a reason to inquire about
129 * the status of the XID, so it seems OK. (Snapshots taken during this
130 * window *will* include the parent XID, so they will deliver the correct
131 * answer later on when someone does have a reason to inquire.)
139 if (MyProc->subxids.nxids < PGPROC_MAX_CACHED_SUBXIDS)
141 MyProc->subxids.xids[MyProc->subxids.nxids] = xid;
142 MyProc->subxids.nxids++;
145 MyProc->subxids.overflowed = true;
149 LWLockRelease(XidGenLock);
155 * Read nextXid but don't allocate it.
158 ReadNewTransactionId(void)
162 LWLockAcquire(XidGenLock, LW_SHARED);
163 xid = ShmemVariableCache->nextXid;
164 LWLockRelease(XidGenLock);
170 * Determine the last safe XID to allocate given the currently oldest
171 * datminxid (ie, the oldest XID that might exist in any database
175 SetTransactionIdLimit(TransactionId oldest_datminxid,
178 TransactionId xidWarnLimit;
179 TransactionId xidStopLimit;
180 TransactionId xidWrapLimit;
181 TransactionId curXid;
183 Assert(TransactionIdIsValid(oldest_datminxid));
186 * The place where we actually get into deep trouble is halfway around
187 * from the oldest existing XID. (This calculation is probably off by one
188 * or two counts, because the special XIDs reduce the size of the loop a
189 * little bit. But we throw in plenty of slop below, so it doesn't
192 xidWrapLimit = oldest_datminxid + (MaxTransactionId >> 1);
193 if (xidWrapLimit < FirstNormalTransactionId)
194 xidWrapLimit += FirstNormalTransactionId;
197 * We'll refuse to continue assigning XIDs in interactive mode once we get
198 * within 1M transactions of data loss. This leaves lots of room for the
199 * DBA to fool around fixing things in a standalone backend, while not
200 * being significant compared to total XID space. (Note that since
201 * vacuuming requires one transaction per table cleaned, we had better be
202 * sure there's lots of XIDs left...)
204 xidStopLimit = xidWrapLimit - 1000000;
205 if (xidStopLimit < FirstNormalTransactionId)
206 xidStopLimit -= FirstNormalTransactionId;
209 * We'll start complaining loudly when we get within 10M transactions of
210 * the stop point. This is kind of arbitrary, but if you let your gas
211 * gauge get down to 1% of full, would you be looking for the next gas
212 * station? We need to be fairly liberal about this number because there
213 * are lots of scenarios where most transactions are done by automatic
214 * clients that won't pay attention to warnings. (No, we're not gonna make
215 * this configurable. If you know enough to configure it, you know enough
216 * to not get in this kind of trouble in the first place.)
218 xidWarnLimit = xidStopLimit - 10000000;
219 if (xidWarnLimit < FirstNormalTransactionId)
220 xidWarnLimit -= FirstNormalTransactionId;
222 /* Grab lock for just long enough to set the new limit values */
223 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
224 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
225 ShmemVariableCache->xidStopLimit = xidStopLimit;
226 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
227 namecpy(&ShmemVariableCache->limit_datname, oldest_datname);
228 curXid = ShmemVariableCache->nextXid;
229 LWLockRelease(XidGenLock);
233 (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
234 xidWrapLimit, NameStr(*oldest_datname))));
235 /* Give an immediate warning if past the wrap warn point */
236 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
238 (errmsg("database \"%s\" must be vacuumed within %u transactions",
239 NameStr(*oldest_datname),
240 xidWrapLimit - curXid),
241 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
242 NameStr(*oldest_datname))));
247 * GetNewObjectId -- allocate a new OID
249 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
250 * wide, counter wraparound will occur eventually, and therefore it is unwise
251 * to assume they are unique unless precautions are taken to make them so.
252 * Hence, this routine should generally not be used directly. The only
253 * direct callers should be GetNewOid() and GetNewRelFileNode() in
261 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
264 * Check for wraparound of the OID counter. We *must* not return 0
265 * (InvalidOid); and as long as we have to check that, it seems a good
266 * idea to skip over everything below FirstNormalObjectId too. (This
267 * basically just avoids lots of collisions with bootstrap-assigned OIDs
268 * right after a wrap occurs, so as to avoid a possibly large number of
269 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
271 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
272 * we only enforce wrapping to that point when in bootstrap or standalone
273 * mode. The first time through this routine after normal postmaster
274 * start, the counter will be forced up to FirstNormalObjectId. This
275 * mechanism leaves the OIDs between FirstBootstrapObjectId and
276 * FirstNormalObjectId available for automatic assignment during initdb,
277 * while ensuring they will never conflict with user-assigned OIDs.
279 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
281 if (IsPostmasterEnvironment)
283 /* wraparound in normal environment */
284 ShmemVariableCache->nextOid = FirstNormalObjectId;
285 ShmemVariableCache->oidCount = 0;
289 /* we may be bootstrapping, so don't enforce the full range */
290 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
292 /* wraparound in standalone environment? */
293 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
294 ShmemVariableCache->oidCount = 0;
299 /* If we run out of logged for use oids then we must log more */
300 if (ShmemVariableCache->oidCount == 0)
302 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
303 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
306 result = ShmemVariableCache->nextOid;
308 (ShmemVariableCache->nextOid)++;
309 (ShmemVariableCache->oidCount)--;
311 LWLockRelease(OidGenLock);