1 /*-------------------------------------------------------------------------
4 * postgres OID & XID variables support routines
6 * Copyright (c) 2000-2005, PostgreSQL Global Development Group
9 * $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.66 2005/08/22 16:59:47 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/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
53 * against catastrophic data loss due to XID wraparound. The basic
54 * rules are: warn if we're past xidWarnLimit, and refuse to execute
55 * transactions if we're past xidStopLimit, unless we are running in
56 * a standalone backend (which gives an escape hatch to the DBA who
57 * ignored all those warnings).
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 queries 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
85 * while holding XidGenLock, else another xact could acquire and
86 * commit a later XID before we zero the page. Fortunately, a page of
87 * the commit log holds 32K or more transactions, so we don't have to
90 * Extend pg_subtrans too.
96 * Now advance the nextXid counter. This must not happen until after
97 * we have successfully completed ExtendCLOG() --- if that routine
98 * fails, we want the next incoming transaction to try it again. We
99 * cannot assign more XIDs until there is CLOG space for them.
101 TransactionIdAdvance(ShmemVariableCache->nextXid);
104 * We must store the new XID into the shared PGPROC array before
105 * releasing XidGenLock. This ensures that when GetSnapshotData calls
106 * ReadNewTransactionId, all active XIDs before the returned value of
107 * nextXid are already present in PGPROC. Else we have a race
110 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
111 * relying on fetch/store of an xid to be atomic, else other backends
112 * might see a partially-set xid here. But holding both locks at once
113 * would be a nasty concurrency hit (and in fact could cause a
114 * deadlock against GetSnapshotData). So for now, assume atomicity.
115 * Note that readers of PGPROC xid field should be careful to fetch
116 * the value only once, rather than assume they can read it multiple
117 * times and get the same answer each time.
119 * The same comments apply to the subxact xid count and overflow fields.
121 * A solution to the atomic-store problem would be to give each PGPROC
122 * its own spinlock used only for fetching/storing that PGPROC's xid
123 * and related fields.
125 * If there's no room to fit a subtransaction XID into PGPROC, set the
126 * cache-overflowed flag instead. This forces readers to look in
127 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There
128 * is a race-condition window, in that the new XID will not appear as
129 * running until its parent link has been placed into pg_subtrans.
130 * However, that will happen before anyone could possibly have a
131 * reason to inquire about the status of the XID, so it seems OK.
132 * (Snapshots taken during this window *will* include the parent XID,
133 * so they will deliver the correct answer later on when someone does
134 * have a reason to inquire.)
142 if (MyProc->subxids.nxids < PGPROC_MAX_CACHED_SUBXIDS)
144 MyProc->subxids.xids[MyProc->subxids.nxids] = xid;
145 MyProc->subxids.nxids++;
148 MyProc->subxids.overflowed = true;
152 LWLockRelease(XidGenLock);
158 * Read nextXid but don't allocate it.
161 ReadNewTransactionId(void)
165 LWLockAcquire(XidGenLock, LW_SHARED);
166 xid = ShmemVariableCache->nextXid;
167 LWLockRelease(XidGenLock);
173 * Determine the last safe XID to allocate given the currently oldest
174 * datfrozenxid (ie, the oldest XID that might exist in any database
178 SetTransactionIdLimit(TransactionId oldest_datfrozenxid,
181 TransactionId xidWarnLimit;
182 TransactionId xidStopLimit;
183 TransactionId xidWrapLimit;
184 TransactionId curXid;
186 Assert(TransactionIdIsValid(oldest_datfrozenxid));
189 * The place where we actually get into deep trouble is halfway around
190 * from the oldest potentially-existing XID. (This calculation is
191 * probably off by one or two counts, because the special XIDs reduce the
192 * size of the loop a little bit. But we throw in plenty of slop below,
193 * so it doesn't matter.)
195 xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
196 if (xidWrapLimit < FirstNormalTransactionId)
197 xidWrapLimit += FirstNormalTransactionId;
200 * We'll refuse to continue assigning XIDs in interactive mode once
201 * we get within 1M transactions of data loss. This leaves lots
202 * of room for the DBA to fool around fixing things in a standalone
203 * backend, while not being significant compared to total XID space.
204 * (Note that since vacuuming requires one transaction per table
205 * cleaned, we had better be sure there's lots of XIDs left...)
207 xidStopLimit = xidWrapLimit - 1000000;
208 if (xidStopLimit < FirstNormalTransactionId)
209 xidStopLimit -= FirstNormalTransactionId;
212 * We'll start complaining loudly when we get within 10M transactions
213 * of the stop point. This is kind of arbitrary, but if you let your
214 * gas gauge get down to 1% of full, would you be looking for the
215 * next gas station? We need to be fairly liberal about this number
216 * because there are lots of scenarios where most transactions are
217 * done by automatic clients that won't pay attention to warnings.
218 * (No, we're not gonna make this configurable. If you know enough to
219 * configure it, you know enough to not get in this kind of trouble in
222 xidWarnLimit = xidStopLimit - 10000000;
223 if (xidWarnLimit < FirstNormalTransactionId)
224 xidWarnLimit -= FirstNormalTransactionId;
226 /* Grab lock for just long enough to set the new limit values */
227 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
228 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
229 ShmemVariableCache->xidStopLimit = xidStopLimit;
230 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
231 namecpy(&ShmemVariableCache->limit_datname, oldest_datname);
232 curXid = ShmemVariableCache->nextXid;
233 LWLockRelease(XidGenLock);
237 (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
238 xidWrapLimit, NameStr(*oldest_datname))));
239 /* Give an immediate warning if past the wrap warn point */
240 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
242 (errmsg("database \"%s\" must be vacuumed within %u transactions",
243 NameStr(*oldest_datname),
244 xidWrapLimit - curXid),
245 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
246 NameStr(*oldest_datname))));
251 * GetNewObjectId -- allocate a new OID
253 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
254 * wide, counter wraparound will occur eventually, and therefore it is unwise
255 * to assume they are unique unless precautions are taken to make them so.
256 * Hence, this routine should generally not be used directly. The only
257 * direct callers should be GetNewOid() and GetNewRelFileNode() in
265 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
268 * Check for wraparound of the OID counter. We *must* not return 0
269 * (InvalidOid); and as long as we have to check that, it seems a good
270 * idea to skip over everything below FirstNormalObjectId too. (This
271 * basically just avoids lots of collisions with bootstrap-assigned OIDs
272 * right after a wrap occurs, so as to avoid a possibly large number of
273 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
275 * During initdb, we start the OID generator at FirstBootstrapObjectId,
276 * so we only enforce wrapping to that point when in bootstrap or
277 * standalone mode. The first time through this routine after normal
278 * postmaster start, the counter will be forced up to FirstNormalObjectId.
279 * This mechanism leaves the OIDs between FirstBootstrapObjectId and
280 * FirstNormalObjectId available for automatic assignment during initdb,
281 * while ensuring they will never conflict with user-assigned OIDs.
283 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
285 if (IsPostmasterEnvironment)
287 /* wraparound in normal environment */
288 ShmemVariableCache->nextOid = FirstNormalObjectId;
289 ShmemVariableCache->oidCount = 0;
293 /* we may be bootstrapping, so don't enforce the full range */
294 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
296 /* wraparound in standalone environment? */
297 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
298 ShmemVariableCache->oidCount = 0;
303 /* If we run out of logged for use oids then we must log more */
304 if (ShmemVariableCache->oidCount == 0)
306 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
307 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
310 result = ShmemVariableCache->nextOid;
312 (ShmemVariableCache->nextOid)++;
313 (ShmemVariableCache->oidCount)--;
315 LWLockRelease(OidGenLock);