]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/varsup.c
Restructure autovacuum in two processes: a dummy process, which runs
[postgresql] / src / backend / access / transam / varsup.c
1 /*-------------------------------------------------------------------------
2  *
3  * varsup.c
4  *        postgres OID & XID variables support routines
5  *
6  * Copyright (c) 2000-2007, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        $PostgreSQL: pgsql/src/backend/access/transam/varsup.c,v 1.78 2007/02/15 23:23:22 alvherre 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 "postmaster/autovacuum.h"
21 #include "storage/pmsignal.h"
22 #include "storage/proc.h"
23 #include "utils/builtins.h"
24
25
26 /* Number of OIDs to prefetch (preallocate) per XLOG write */
27 #define VAR_OID_PREFETCH                8192
28
29 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
30 VariableCache ShmemVariableCache = NULL;
31
32
33 /*
34  * Allocate the next XID for my new transaction.
35  */
36 TransactionId
37 GetNewTransactionId(bool isSubXact)
38 {
39         TransactionId xid;
40
41         /*
42          * During bootstrap initialization, we return the special bootstrap
43          * transaction id.
44          */
45         if (IsBootstrapProcessingMode())
46                 return BootstrapTransactionId;
47
48         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
49
50         xid = ShmemVariableCache->nextXid;
51
52         /*----------
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:
55          *
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).
61          *
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.
64          *----------
65          */
66         if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit) &&
67                 TransactionIdIsValid(ShmemVariableCache->xidVacLimit))
68         {
69                 /*
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.
73                  */
74                 if (IsUnderPostmaster && (xid % 65536) == 0)
75                         SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
76
77                 if (IsUnderPostmaster &&
78                  TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
79                         ereport(ERROR,
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))
86                         ereport(WARNING,
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))));
92         }
93
94         /*
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.
100          *
101          * Extend pg_subtrans too.
102          */
103         ExtendCLOG(xid);
104         ExtendSUBTRANS(xid);
105
106         /*
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.
111          */
112         TransactionIdAdvance(ShmemVariableCache->nextXid);
113
114         /*
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.
119          *
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.
128          *
129          * The same comments apply to the subxact xid count and overflow fields.
130          *
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
133          * related fields.
134          *
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.)
144          */
145         if (MyProc != NULL)
146         {
147                 /*
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.
153                  */
154                 volatile PGPROC *myproc = MyProc;
155
156                 if (!isSubXact)
157                         myproc->xid = xid;
158                 else
159                 {
160                         int                     nxids = myproc->subxids.nxids;
161
162                         if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
163                         {
164                                 myproc->subxids.xids[nxids] = xid;
165                                 myproc->subxids.nxids = nxids + 1;
166                         }
167                         else
168                                 myproc->subxids.overflowed = true;
169                 }
170         }
171
172         LWLockRelease(XidGenLock);
173
174         return xid;
175 }
176
177 /*
178  * Read nextXid but don't allocate it.
179  */
180 TransactionId
181 ReadNewTransactionId(void)
182 {
183         TransactionId xid;
184
185         LWLockAcquire(XidGenLock, LW_SHARED);
186         xid = ShmemVariableCache->nextXid;
187         LWLockRelease(XidGenLock);
188
189         return xid;
190 }
191
192 /*
193  * Determine the last safe XID to allocate given the currently oldest
194  * datfrozenxid (ie, the oldest XID that might exist in any database
195  * of our cluster).
196  */
197 void
198 SetTransactionIdLimit(TransactionId oldest_datfrozenxid,
199                                           Name oldest_datname)
200 {
201         TransactionId xidVacLimit;
202         TransactionId xidWarnLimit;
203         TransactionId xidStopLimit;
204         TransactionId xidWrapLimit;
205         TransactionId curXid;
206
207         Assert(TransactionIdIsNormal(oldest_datfrozenxid));
208
209         /*
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.)
215          */
216         xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
217         if (xidWrapLimit < FirstNormalTransactionId)
218                 xidWrapLimit += FirstNormalTransactionId;
219
220         /*
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...)
227          */
228         xidStopLimit = xidWrapLimit - 1000000;
229         if (xidStopLimit < FirstNormalTransactionId)
230                 xidStopLimit -= FirstNormalTransactionId;
231
232         /*
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.)
241          */
242         xidWarnLimit = xidStopLimit - 10000000;
243         if (xidWarnLimit < FirstNormalTransactionId)
244                 xidWarnLimit -= FirstNormalTransactionId;
245
246         /*
247          * We'll start trying to force autovacuums when oldest_datfrozenxid
248          * gets to be more than autovacuum_freeze_max_age transactions old.
249          *
250          * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane
251          * range, so that xidVacLimit will be well before xidWarnLimit.
252          *
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.
259          */
260         xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
261         if (xidVacLimit < FirstNormalTransactionId)
262                 xidVacLimit += FirstNormalTransactionId;
263
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);
274
275         /* Log the info */
276         ereport(DEBUG1,
277            (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
278                            xidWrapLimit, NameStr(*oldest_datname))));
279
280         /*
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.
286          */
287         if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
288                 IsUnderPostmaster)
289                 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
290
291         /* Give an immediate warning if past the wrap warn point */
292         if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
293                 ereport(WARNING,
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))));
299 }
300
301
302 /*
303  * GetNewObjectId -- allocate a new OID
304  *
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
310  * catalog/catalog.c.
311  */
312 Oid
313 GetNewObjectId(void)
314 {
315         Oid                     result;
316
317         LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
318
319         /*
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.
326          *
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.
334          */
335         if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
336         {
337                 if (IsPostmasterEnvironment)
338                 {
339                         /* wraparound in normal environment */
340                         ShmemVariableCache->nextOid = FirstNormalObjectId;
341                         ShmemVariableCache->oidCount = 0;
342                 }
343                 else
344                 {
345                         /* we may be bootstrapping, so don't enforce the full range */
346                         if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
347                         {
348                                 /* wraparound in standalone environment? */
349                                 ShmemVariableCache->nextOid = FirstBootstrapObjectId;
350                                 ShmemVariableCache->oidCount = 0;
351                         }
352                 }
353         }
354
355         /* If we run out of logged for use oids then we must log more */
356         if (ShmemVariableCache->oidCount == 0)
357         {
358                 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
359                 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
360         }
361
362         result = ShmemVariableCache->nextOid;
363
364         (ShmemVariableCache->nextOid)++;
365         (ShmemVariableCache->oidCount)--;
366
367         LWLockRelease(OidGenLock);
368
369         return result;
370 }