1 /*-------------------------------------------------------------------------
4 * postgres OID & XID variables support routines
6 * Copyright (c) 2000-2007, PostgreSQL Global Development Group
9 * $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.78 2007/02/15 23:23:22 alvherre Exp $
11 *-------------------------------------------------------------------------
16 #include "access/clog.h"
17 #include "access/subtrans.h"
18 #include "access/transam.h"
19 #include "miscadmin.h"
20 #include "postmaster/autovacuum.h"
21 #include "storage/pmsignal.h"
22 #include "storage/proc.h"
23 #include "utils/builtins.h"
26 /* Number of OIDs to prefetch (preallocate) per XLOG write */
27 #define VAR_OID_PREFETCH 8192
29 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
30 VariableCache ShmemVariableCache = NULL;
34 * Allocate the next XID for my new transaction.
37 GetNewTransactionId(bool isSubXact)
42 * During bootstrap initialization, we return the special bootstrap
45 if (IsBootstrapProcessingMode())
46 return BootstrapTransactionId;
48 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
50 xid = ShmemVariableCache->nextXid;
53 * Check to see if it's safe to assign another XID. This protects against
54 * catastrophic data loss due to XID wraparound. The basic rules are:
56 * If we're past xidVacLimit, start trying to force autovacuum cycles.
57 * If we're past xidWarnLimit, start issuing warnings.
58 * If we're past xidStopLimit, refuse to execute transactions, unless
59 * we are running in a standalone backend (which gives an escape hatch
60 * to the DBA who somehow got past the earlier defenses).
62 * Test is coded to fall out as fast as possible during normal operation,
63 * ie, when the vac limit is set and we haven't violated it.
66 if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit) &&
67 TransactionIdIsValid(ShmemVariableCache->xidVacLimit))
70 * To avoid swamping the postmaster with signals, we issue the
71 * autovac request only once per 64K transaction starts. This
72 * still gives plenty of chances before we get into real trouble.
74 if (IsUnderPostmaster && (xid % 65536) == 0)
75 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
77 if (IsUnderPostmaster &&
78 TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
80 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
81 errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
82 NameStr(ShmemVariableCache->limit_datname)),
83 errhint("Stop the postmaster and use a standalone backend to vacuum database \"%s\".",
84 NameStr(ShmemVariableCache->limit_datname))));
85 else if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit))
87 (errmsg("database \"%s\" must be vacuumed within %u transactions",
88 NameStr(ShmemVariableCache->limit_datname),
89 ShmemVariableCache->xidWrapLimit - xid),
90 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
91 NameStr(ShmemVariableCache->limit_datname))));
95 * If we are allocating the first XID of a new page of the commit log,
96 * zero out that commit-log page before returning. We must do this while
97 * holding XidGenLock, else another xact could acquire and commit a later
98 * XID before we zero the page. Fortunately, a page of the commit log
99 * holds 32K or more transactions, so we don't have to do this very often.
101 * Extend pg_subtrans too.
107 * Now advance the nextXid counter. This must not happen until after we
108 * have successfully completed ExtendCLOG() --- if that routine fails, we
109 * want the next incoming transaction to try it again. We cannot assign
110 * more XIDs until there is CLOG space for them.
112 TransactionIdAdvance(ShmemVariableCache->nextXid);
115 * We must store the new XID into the shared PGPROC array before releasing
116 * XidGenLock. This ensures that when GetSnapshotData calls
117 * ReadNewTransactionId, all active XIDs before the returned value of
118 * nextXid are already present in PGPROC. Else we have a race condition.
120 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
121 * relying on fetch/store of an xid to be atomic, else other backends
122 * might see a partially-set xid here. But holding both locks at once
123 * would be a nasty concurrency hit (and in fact could cause a deadlock
124 * against GetSnapshotData). So for now, assume atomicity. Note that
125 * readers of PGPROC xid field should be careful to fetch the value only
126 * once, rather than assume they can read it multiple times and get the
127 * same answer each time.
129 * The same comments apply to the subxact xid count and overflow fields.
131 * A solution to the atomic-store problem would be to give each PGPROC its
132 * own spinlock used only for fetching/storing that PGPROC's xid and
135 * If there's no room to fit a subtransaction XID into PGPROC, set the
136 * cache-overflowed flag instead. This forces readers to look in
137 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
138 * race-condition window, in that the new XID will not appear as running
139 * until its parent link has been placed into pg_subtrans. However, that
140 * will happen before anyone could possibly have a reason to inquire about
141 * the status of the XID, so it seems OK. (Snapshots taken during this
142 * window *will* include the parent XID, so they will deliver the correct
143 * answer later on when someone does have a reason to inquire.)
148 * Use volatile pointer to prevent code rearrangement; other backends
149 * could be examining my subxids info concurrently, and we don't want
150 * them to see an invalid intermediate state, such as incrementing
151 * nxids before filling the array entry. Note we are assuming that
152 * TransactionId and int fetch/store are atomic.
154 volatile PGPROC *myproc = MyProc;
160 int nxids = myproc->subxids.nxids;
162 if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
164 myproc->subxids.xids[nxids] = xid;
165 myproc->subxids.nxids = nxids + 1;
168 myproc->subxids.overflowed = true;
172 LWLockRelease(XidGenLock);
178 * Read nextXid but don't allocate it.
181 ReadNewTransactionId(void)
185 LWLockAcquire(XidGenLock, LW_SHARED);
186 xid = ShmemVariableCache->nextXid;
187 LWLockRelease(XidGenLock);
193 * Determine the last safe XID to allocate given the currently oldest
194 * datfrozenxid (ie, the oldest XID that might exist in any database
198 SetTransactionIdLimit(TransactionId oldest_datfrozenxid,
201 TransactionId xidVacLimit;
202 TransactionId xidWarnLimit;
203 TransactionId xidStopLimit;
204 TransactionId xidWrapLimit;
205 TransactionId curXid;
207 Assert(TransactionIdIsNormal(oldest_datfrozenxid));
210 * The place where we actually get into deep trouble is halfway around
211 * from the oldest potentially-existing XID. (This calculation is
212 * probably off by one or two counts, because the special XIDs reduce the
213 * size of the loop a little bit. But we throw in plenty of slop below,
214 * so it doesn't matter.)
216 xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
217 if (xidWrapLimit < FirstNormalTransactionId)
218 xidWrapLimit += FirstNormalTransactionId;
221 * We'll refuse to continue assigning XIDs in interactive mode once we get
222 * within 1M transactions of data loss. This leaves lots of room for the
223 * DBA to fool around fixing things in a standalone backend, while not
224 * being significant compared to total XID space. (Note that since
225 * vacuuming requires one transaction per table cleaned, we had better be
226 * sure there's lots of XIDs left...)
228 xidStopLimit = xidWrapLimit - 1000000;
229 if (xidStopLimit < FirstNormalTransactionId)
230 xidStopLimit -= FirstNormalTransactionId;
233 * We'll start complaining loudly when we get within 10M transactions of
234 * the stop point. This is kind of arbitrary, but if you let your gas
235 * gauge get down to 1% of full, would you be looking for the next gas
236 * station? We need to be fairly liberal about this number because there
237 * are lots of scenarios where most transactions are done by automatic
238 * clients that won't pay attention to warnings. (No, we're not gonna make
239 * this configurable. If you know enough to configure it, you know enough
240 * to not get in this kind of trouble in the first place.)
242 xidWarnLimit = xidStopLimit - 10000000;
243 if (xidWarnLimit < FirstNormalTransactionId)
244 xidWarnLimit -= FirstNormalTransactionId;
247 * We'll start trying to force autovacuums when oldest_datfrozenxid
248 * gets to be more than autovacuum_freeze_max_age transactions old.
250 * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane
251 * range, so that xidVacLimit will be well before xidWarnLimit.
253 * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
254 * we don't have to worry about dealing with on-the-fly changes in its
255 * value. It doesn't look practical to update shared state from a GUC
256 * assign hook (too many processes would try to execute the hook,
257 * resulting in race conditions as well as crashes of those not
258 * connected to shared memory). Perhaps this can be improved someday.
260 xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
261 if (xidVacLimit < FirstNormalTransactionId)
262 xidVacLimit += FirstNormalTransactionId;
264 /* Grab lock for just long enough to set the new limit values */
265 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
266 ShmemVariableCache->oldestXid = oldest_datfrozenxid;
267 ShmemVariableCache->xidVacLimit = xidVacLimit;
268 ShmemVariableCache->xidWarnLimit = xidWarnLimit;
269 ShmemVariableCache->xidStopLimit = xidStopLimit;
270 ShmemVariableCache->xidWrapLimit = xidWrapLimit;
271 namecpy(&ShmemVariableCache->limit_datname, oldest_datname);
272 curXid = ShmemVariableCache->nextXid;
273 LWLockRelease(XidGenLock);
277 (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
278 xidWrapLimit, NameStr(*oldest_datname))));
281 * If past the autovacuum force point, immediately signal an autovac
282 * request. The reason for this is that autovac only processes one
283 * database per invocation. Once it's finished cleaning up the oldest
284 * database, it'll call here, and we'll signal the postmaster to start
285 * another iteration immediately if there are still any old databases.
287 if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
289 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
291 /* Give an immediate warning if past the wrap warn point */
292 if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
294 (errmsg("database \"%s\" must be vacuumed within %u transactions",
295 NameStr(*oldest_datname),
296 xidWrapLimit - curXid),
297 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
298 NameStr(*oldest_datname))));
303 * GetNewObjectId -- allocate a new OID
305 * OIDs are generated by a cluster-wide counter. Since they are only 32 bits
306 * wide, counter wraparound will occur eventually, and therefore it is unwise
307 * to assume they are unique unless precautions are taken to make them so.
308 * Hence, this routine should generally not be used directly. The only
309 * direct callers should be GetNewOid() and GetNewRelFileNode() in
317 LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
320 * Check for wraparound of the OID counter. We *must* not return 0
321 * (InvalidOid); and as long as we have to check that, it seems a good
322 * idea to skip over everything below FirstNormalObjectId too. (This
323 * basically just avoids lots of collisions with bootstrap-assigned OIDs
324 * right after a wrap occurs, so as to avoid a possibly large number of
325 * iterations in GetNewOid.) Note we are relying on unsigned comparison.
327 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
328 * we only enforce wrapping to that point when in bootstrap or standalone
329 * mode. The first time through this routine after normal postmaster
330 * start, the counter will be forced up to FirstNormalObjectId. This
331 * mechanism leaves the OIDs between FirstBootstrapObjectId and
332 * FirstNormalObjectId available for automatic assignment during initdb,
333 * while ensuring they will never conflict with user-assigned OIDs.
335 if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
337 if (IsPostmasterEnvironment)
339 /* wraparound in normal environment */
340 ShmemVariableCache->nextOid = FirstNormalObjectId;
341 ShmemVariableCache->oidCount = 0;
345 /* we may be bootstrapping, so don't enforce the full range */
346 if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
348 /* wraparound in standalone environment? */
349 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
350 ShmemVariableCache->oidCount = 0;
355 /* If we run out of logged for use oids then we must log more */
356 if (ShmemVariableCache->oidCount == 0)
358 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
359 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
362 result = ShmemVariableCache->nextOid;
364 (ShmemVariableCache->nextOid)++;
365 (ShmemVariableCache->oidCount)--;
367 LWLockRelease(OidGenLock);