]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/varsup.c
Improve xid wraparound message (the server isn't really shut down, just
[postgresql] / src / backend / access / transam / varsup.c
1 /*-------------------------------------------------------------------------
2  *
3  * varsup.c
4  *        postgres OID & XID variables support routines
5  *
6  * Copyright (c) 2000-2005, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.66 2005/08/22 16:59:47 momjian Exp $
10  *
11  *-------------------------------------------------------------------------
12  */
13
14 #include "postgres.h"
15
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"
23
24
25 /* Number of OIDs to prefetch (preallocate) per XLOG write */
26 #define VAR_OID_PREFETCH                8192
27
28 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
29 VariableCache ShmemVariableCache = NULL;
30
31
32 /*
33  * Allocate the next XID for my new transaction.
34  */
35 TransactionId
36 GetNewTransactionId(bool isSubXact)
37 {
38         TransactionId xid;
39
40         /*
41          * During bootstrap initialization, we return the special bootstrap
42          * transaction id.
43          */
44         if (IsBootstrapProcessingMode())
45                 return BootstrapTransactionId;
46
47         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
48
49         xid = ShmemVariableCache->nextXid;
50
51         /*
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).
58          *
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.
61          */
62         if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit) &&
63                 TransactionIdIsValid(ShmemVariableCache->xidWarnLimit))
64         {
65                 if (IsUnderPostmaster &&
66                         TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
67                         ereport(ERROR,
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))));
73                 else
74                         ereport(WARNING,
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))));
80         }
81
82         /*
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
88          * do this very often.
89          *
90          * Extend pg_subtrans too.
91          */
92         ExtendCLOG(xid);
93         ExtendSUBTRANS(xid);
94
95         /*
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.
100          */
101         TransactionIdAdvance(ShmemVariableCache->nextXid);
102
103         /*
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
108          * condition.
109          *
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.
118          *
119          * The same comments apply to the subxact xid count and overflow fields.
120          *
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.
124          *
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.)
135          */
136         if (MyProc != NULL)
137         {
138                 if (!isSubXact)
139                         MyProc->xid = xid;
140                 else
141                 {
142                         if (MyProc->subxids.nxids < PGPROC_MAX_CACHED_SUBXIDS)
143                         {
144                                 MyProc->subxids.xids[MyProc->subxids.nxids] = xid;
145                                 MyProc->subxids.nxids++;
146                         }
147                         else
148                                 MyProc->subxids.overflowed = true;
149                 }
150         }
151
152         LWLockRelease(XidGenLock);
153
154         return xid;
155 }
156
157 /*
158  * Read nextXid but don't allocate it.
159  */
160 TransactionId
161 ReadNewTransactionId(void)
162 {
163         TransactionId xid;
164
165         LWLockAcquire(XidGenLock, LW_SHARED);
166         xid = ShmemVariableCache->nextXid;
167         LWLockRelease(XidGenLock);
168
169         return xid;
170 }
171
172 /*
173  * Determine the last safe XID to allocate given the currently oldest
174  * datfrozenxid (ie, the oldest XID that might exist in any database
175  * of our cluster).
176  */
177 void
178 SetTransactionIdLimit(TransactionId oldest_datfrozenxid,
179                                           Name oldest_datname)
180 {
181         TransactionId xidWarnLimit;
182         TransactionId xidStopLimit;
183         TransactionId xidWrapLimit;
184         TransactionId curXid;
185
186         Assert(TransactionIdIsValid(oldest_datfrozenxid));
187
188         /*
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.)
194          */
195         xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
196         if (xidWrapLimit < FirstNormalTransactionId)
197                 xidWrapLimit += FirstNormalTransactionId;
198
199         /*
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...)
206          */
207         xidStopLimit = xidWrapLimit - 1000000;
208         if (xidStopLimit < FirstNormalTransactionId)
209                 xidStopLimit -= FirstNormalTransactionId;
210
211         /*
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
220          * the first place.)
221          */
222         xidWarnLimit = xidStopLimit - 10000000;
223         if (xidWarnLimit < FirstNormalTransactionId)
224                 xidWarnLimit -= FirstNormalTransactionId;
225
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);
234
235         /* Log the info */
236         ereport(LOG,
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))
241                 ereport(WARNING,
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))));
247 }
248
249
250 /*
251  * GetNewObjectId -- allocate a new OID
252  *
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
258  * catalog/catalog.c.
259  */
260 Oid
261 GetNewObjectId(void)
262 {
263         Oid                     result;
264
265         LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
266
267         /*
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.
274          *
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.
282          */
283         if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
284         {
285                 if (IsPostmasterEnvironment)
286                 {
287                         /* wraparound in normal environment */
288                         ShmemVariableCache->nextOid = FirstNormalObjectId;
289                         ShmemVariableCache->oidCount = 0;
290                 }
291                 else
292                 {
293                         /* we may be bootstrapping, so don't enforce the full range */
294                         if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
295                         {
296                                 /* wraparound in standalone environment? */
297                                 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
298                                 ShmemVariableCache->oidCount = 0;
299                         }
300                 }
301         }
302
303         /* If we run out of logged for use oids then we must log more */
304         if (ShmemVariableCache->oidCount == 0)
305         {
306                 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
307                 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
308         }
309
310         result = ShmemVariableCache->nextOid;
311
312         (ShmemVariableCache->nextOid)++;
313         (ShmemVariableCache->oidCount)--;
314
315         LWLockRelease(OidGenLock);
316
317         return result;
318 }