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.75 2006/10/04 00:29:49 momjian Exp $
11 *-------------------------------------------------------------------------
16 #include "access/clog.h"
17 #include "access/subtrans.h"
18 #include "access/transam.h"
19 #include "miscadmin.h"
20 #include "storage/proc.h"
21 #include "utils/builtins.h"
24 /* Number of OIDs to prefetch (preallocate) per XLOG write */
25 #define VAR_OID_PREFETCH 8192
27 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
28 VariableCache ShmemVariableCache = NULL;
32 * Allocate the next XID for my new transaction.
35 GetNewTransactionId(bool isSubXact)
40 * During bootstrap initialization, we return the special bootstrap
43 if (IsBootstrapProcessingMode())
44 return BootstrapTransactionId;
46 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
48 xid = ShmemVariableCache->nextXid;
51 * Check to see if it's safe to assign another XID. This protects against
52 * catastrophic data loss due to XID wraparound. The basic rules are:
53 * warn if we're past xidWarnLimit, and refuse to execute transactions if
54 * we're past xidStopLimit, unless we are running in a standalone backend
55 * (which gives an escape hatch to the DBA who ignored all those
58 * Test is coded to fall out as fast as possible during normal operation,
59 * ie, when the warn limit is set and we haven't violated it.
61 if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit) &&
62 TransactionIdIsValid(ShmemVariableCache->xidWarnLimit))
64 if (IsUnderPostmaster &&
65 TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
67 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
68 errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
69 NameStr(ShmemVariableCache->limit_datname)),
70 errhint("Stop the postmaster and use a standalone backend to vacuum database \"%s\".",
71 NameStr(ShmemVariableCache->limit_datname))));
74 (errmsg("database \"%s\" must be vacuumed within %u transactions",
75 NameStr(ShmemVariableCache->limit_datname),
76 ShmemVariableCache->xidWrapLimit - xid),
77 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
78 NameStr(ShmemVariableCache->limit_datname))));
82 * If we are allocating the first XID of a new page of the commit log,
83 * zero out that commit-log page before returning. We must do this while
84 * holding XidGenLock, else another xact could acquire and commit a later
85 * XID before we zero the page. Fortunately, a page of the commit log
86 * holds 32K or more transactions, so we don't have to do this very often.
88 * Extend pg_subtrans too.
94 * Now advance the nextXid counter. This must not happen until after we
95 * have successfully completed ExtendCLOG() --- if that routine fails, we
96 * want the next incoming transaction to try it again. We cannot assign
97 * more XIDs until there is CLOG space for them.
99 TransactionIdAdvance(ShmemVariableCache->nextXid);
102 * We must store the new XID into the shared PGPROC array before releasing
103 * XidGenLock. This ensures that when GetSnapshotData calls
104 * ReadNewTransactionId, all active XIDs before the returned value of
105 * nextXid are already present in PGPROC. Else we have a race condition.
107 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
108 * relying on fetch/store of an xid to be atomic, else other backends
109 * might see a partially-set xid here. But holding both locks at once
110 * would be a nasty concurrency hit (and in fact could cause a deadlock
111 * against GetSnapshotData). So for now, assume atomicity. Note that
112 * readers of PGPROC xid field should be careful to fetch the value only
113 * once, rather than assume they can read it multiple times and get the
114 * same answer each time.
116 * The same comments apply to the subxact xid count and overflow fields.
118 * A solution to the atomic-store problem would be to give each PGPROC its
119 * own spinlock used only for fetching/storing that PGPROC's xid and
122 * If there's no room to fit a subtransaction XID into PGPROC, set the
123 * cache-overflowed flag instead. This forces readers to look in
124 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
125 * race-condition window, in that the new XID will not appear as running
126 * until its parent link has been placed into pg_subtrans. However, that
127 * will happen before anyone could possibly have a reason to inquire about
128 * the status of the XID, so it seems OK. (Snapshots taken during this
129 * window *will* include the parent XID, so they will deliver the correct
130 * answer later on when someone does have a reason to inquire.)
135 * Use volatile pointer to prevent code rearrangement; other backends
136 * could be examining my subxids info concurrently, and we don't want
137 * them to see an invalid intermediate state, such as incrementing
138 * nxids before filling the array entry. Note we are assuming that
139 * TransactionId and int fetch/store are atomic.
141 volatile PGPROC *myproc = MyProc;
147 int nxids = myproc->subxids.nxids;
149 if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
151 myproc->subxids.xids[nxids] = xid;
152 myproc->subxids.nxids = nxids + 1;
155 myproc->subxids.overflowed = true;
159 LWLockRelease(XidGenLock);
165 * Read nextXid but don't allocate it.
168 ReadNewTransactionId(void)
172 LWLockAcquire(XidGenLock, LW_SHARED);
173 xid = ShmemVariableCache->nextXid;
174 LWLockRelease(XidGenLock);
180 * Determine the last safe XID to allocate given the currently oldest
181 * datminxid (ie, the oldest XID that might exist in any database
185 SetTransactionIdLimit(TransactionId oldest_datminxid,
188 TransactionId xidWarnLimit;
189 TransactionId xidStopLimit;
190 TransactionId xidWrapLimit;
191 TransactionId curXid;
193 Assert(TransactionIdIsValid(oldest_datminxid));
196 * The place where we actually get into deep trouble is halfway around
197 * from the oldest existing XID. (This calculation is probably off by one
198 * or two counts, because the special XIDs reduce the size of the loop a
199 * little bit. But we throw in plenty of slop below, so it doesn't
202 xidWrapLimit = oldest_datminxid + (MaxTransactionId >> 1);
203 if (xidWrapLimit < FirstNormalTransactionId)
204 xidWrapLimit += FirstNormalTransactionId;
207 * We'll refuse to continue assigning XIDs in interactive mode once we get
208 * within 1M transactions of data loss. This leaves lots of room for the
209 * DBA to fool around fixing things in a standalone backend, while not
210 * being significant compared to total XID space. (Note that since
211 * vacuuming requires one transaction per table cleaned, we had better be
212 * sure there's lots of XIDs left...)
214 xidStopLimit = xidWrapLimit - 1000000;
215 if (xidStopLimit < FirstNormalTransactionId)
216 xidStopLimit -= FirstNormalTransactionId;
219 * We'll start complaining loudly when we get within 10M transactions of
220 * the stop point. This is kind of arbitrary, but if you let your gas
221 * gauge get down to 1% of full, would you be looking for the next gas
222 * station? We need to be fairly liberal about this number because there
223 * are lots of scenarios where most transactions are done by automatic
224 * clients that won't pay attention to warnings. (No, we're not gonna make
225 * this configurable. If you know enough to configure it, you know enough
226 * to not get in this kind of trouble in the first place.)
228 xidWarnLimit = xidStopLimit - 10000000;
229 if (xidWarnLimit < FirstNormalTransactionId)
230 xidWarnLimit -= FirstNormalTransactionId;
232 /* Grab lock for just long enough to set the new limit values */
233 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
234 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
235 ShmemVariableCache->xidStopLimit = xidStopLimit;
236 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
237 namecpy(&ShmemVariableCache->limit_datname, oldest_datname);
238 curXid = ShmemVariableCache->nextXid;
239 LWLockRelease(XidGenLock);
243 (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
244 xidWrapLimit, NameStr(*oldest_datname))));
245 /* Give an immediate warning if past the wrap warn point */
246 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
248 (errmsg("database \"%s\" must be vacuumed within %u transactions",
249 NameStr(*oldest_datname),
250 xidWrapLimit - curXid),
251 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
252 NameStr(*oldest_datname))));
257 * GetNewObjectId -- allocate a new OID
259 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
260 * wide, counter wraparound will occur eventually, and therefore it is unwise
261 * to assume they are unique unless precautions are taken to make them so.
262 * Hence, this routine should generally not be used directly. The only
263 * direct callers should be GetNewOid() and GetNewRelFileNode() in
271 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
274 * Check for wraparound of the OID counter. We *must* not return 0
275 * (InvalidOid); and as long as we have to check that, it seems a good
276 * idea to skip over everything below FirstNormalObjectId too. (This
277 * basically just avoids lots of collisions with bootstrap-assigned OIDs
278 * right after a wrap occurs, so as to avoid a possibly large number of
279 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
281 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
282 * we only enforce wrapping to that point when in bootstrap or standalone
283 * mode. The first time through this routine after normal postmaster
284 * start, the counter will be forced up to FirstNormalObjectId. This
285 * mechanism leaves the OIDs between FirstBootstrapObjectId and
286 * FirstNormalObjectId available for automatic assignment during initdb,
287 * while ensuring they will never conflict with user-assigned OIDs.
289 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
291 if (IsPostmasterEnvironment)
293 /* wraparound in normal environment */
294 ShmemVariableCache->nextOid = FirstNormalObjectId;
295 ShmemVariableCache->oidCount = 0;
299 /* we may be bootstrapping, so don't enforce the full range */
300 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
302 /* wraparound in standalone environment? */
303 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
304 ShmemVariableCache->oidCount = 0;
309 /* If we run out of logged for use oids then we must log more */
310 if (ShmemVariableCache->oidCount == 0)
312 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
313 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
316 result = ShmemVariableCache->nextOid;
318 (ShmemVariableCache->nextOid)++;
319 (ShmemVariableCache->oidCount)--;
321 LWLockRelease(OidGenLock);