]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/varsup.c
pgindent run for 8.2.
[postgresql] / src / backend / access / transam / varsup.c
1 /*-------------------------------------------------------------------------
2  *
3  * varsup.c
4  *        postgres OID & XID variables support routines
5  *
6  * Copyright (c) 2000-2006, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.75 2006/10/04 00:29:49 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/proc.h"
21 #include "utils/builtins.h"
22
23
24 /* Number of OIDs to prefetch (preallocate) per XLOG write */
25 #define VAR_OID_PREFETCH                8192
26
27 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
28 VariableCache ShmemVariableCache = NULL;
29
30
31 /*
32  * Allocate the next XID for my new transaction.
33  */
34 TransactionId
35 GetNewTransactionId(bool isSubXact)
36 {
37         TransactionId xid;
38
39         /*
40          * During bootstrap initialization, we return the special bootstrap
41          * transaction id.
42          */
43         if (IsBootstrapProcessingMode())
44                 return BootstrapTransactionId;
45
46         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
47
48         xid = ShmemVariableCache->nextXid;
49
50         /*
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
56          * warnings).
57          *
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.
60          */
61         if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit) &&
62                 TransactionIdIsValid(ShmemVariableCache->xidWarnLimit))
63         {
64                 if (IsUnderPostmaster &&
65                  TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
66                         ereport(ERROR,
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))));
72                 else
73                         ereport(WARNING,
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))));
79         }
80
81         /*
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.
87          *
88          * Extend pg_subtrans too.
89          */
90         ExtendCLOG(xid);
91         ExtendSUBTRANS(xid);
92
93         /*
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.
98          */
99         TransactionIdAdvance(ShmemVariableCache->nextXid);
100
101         /*
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.
106          *
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.
115          *
116          * The same comments apply to the subxact xid count and overflow fields.
117          *
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
120          * related fields.
121          *
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.)
131          */
132         if (MyProc != NULL)
133         {
134                 /*
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.
140                  */
141                 volatile PGPROC *myproc = MyProc;
142
143                 if (!isSubXact)
144                         myproc->xid = xid;
145                 else
146                 {
147                         int                     nxids = myproc->subxids.nxids;
148
149                         if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
150                         {
151                                 myproc->subxids.xids[nxids] = xid;
152                                 myproc->subxids.nxids = nxids + 1;
153                         }
154                         else
155                                 myproc->subxids.overflowed = true;
156                 }
157         }
158
159         LWLockRelease(XidGenLock);
160
161         return xid;
162 }
163
164 /*
165  * Read nextXid but don't allocate it.
166  */
167 TransactionId
168 ReadNewTransactionId(void)
169 {
170         TransactionId xid;
171
172         LWLockAcquire(XidGenLock, LW_SHARED);
173         xid = ShmemVariableCache->nextXid;
174         LWLockRelease(XidGenLock);
175
176         return xid;
177 }
178
179 /*
180  * Determine the last safe XID to allocate given the currently oldest
181  * datminxid (ie, the oldest XID that might exist in any database
182  * of our cluster).
183  */
184 void
185 SetTransactionIdLimit(TransactionId oldest_datminxid,
186                                           Name oldest_datname)
187 {
188         TransactionId xidWarnLimit;
189         TransactionId xidStopLimit;
190         TransactionId xidWrapLimit;
191         TransactionId curXid;
192
193         Assert(TransactionIdIsValid(oldest_datminxid));
194
195         /*
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
200          * matter.)
201          */
202         xidWrapLimit = oldest_datminxid + (MaxTransactionId >> 1);
203         if (xidWrapLimit < FirstNormalTransactionId)
204                 xidWrapLimit += FirstNormalTransactionId;
205
206         /*
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...)
213          */
214         xidStopLimit = xidWrapLimit - 1000000;
215         if (xidStopLimit < FirstNormalTransactionId)
216                 xidStopLimit -= FirstNormalTransactionId;
217
218         /*
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.)
227          */
228         xidWarnLimit = xidStopLimit - 10000000;
229         if (xidWarnLimit < FirstNormalTransactionId)
230                 xidWarnLimit -= FirstNormalTransactionId;
231
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);
240
241         /* Log the info */
242         ereport(DEBUG1,
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))
247                 ereport(WARNING,
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))));
253 }
254
255
256 /*
257  * GetNewObjectId -- allocate a new OID
258  *
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
264  * catalog/catalog.c.
265  */
266 Oid
267 GetNewObjectId(void)
268 {
269         Oid                     result;
270
271         LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
272
273         /*
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.
280          *
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.
288          */
289         if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
290         {
291                 if (IsPostmasterEnvironment)
292                 {
293                         /* wraparound in normal environment */
294                         ShmemVariableCache->nextOid = FirstNormalObjectId;
295                         ShmemVariableCache->oidCount = 0;
296                 }
297                 else
298                 {
299                         /* we may be bootstrapping, so don't enforce the full range */
300                         if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
301                         {
302                                 /* wraparound in standalone environment? */
303                                 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
304                                 ShmemVariableCache->oidCount = 0;
305                         }
306                 }
307         }
308
309         /* If we run out of logged for use oids then we must log more */
310         if (ShmemVariableCache->oidCount == 0)
311         {
312                 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
313                 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
314         }
315
316         result = ShmemVariableCache->nextOid;
317
318         (ShmemVariableCache->nextOid)++;
319         (ShmemVariableCache->oidCount)--;
320
321         LWLockRelease(OidGenLock);
322
323         return result;
324 }