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