]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/varsup.c
Update copyright for 2015
[postgresql] / src / backend / access / transam / varsup.c
1 /*-------------------------------------------------------------------------
2  *
3  * varsup.c
4  *        postgres OID & XID variables support routines
5  *
6  * Copyright (c) 2000-2015, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        src/backend/access/transam/varsup.c
10  *
11  *-------------------------------------------------------------------------
12  */
13
14 #include "postgres.h"
15
16 #include "access/clog.h"
17 #include "access/commit_ts.h"
18 #include "access/subtrans.h"
19 #include "access/transam.h"
20 #include "access/xact.h"
21 #include "access/xlog.h"
22 #include "commands/dbcommands.h"
23 #include "miscadmin.h"
24 #include "postmaster/autovacuum.h"
25 #include "storage/pmsignal.h"
26 #include "storage/proc.h"
27 #include "utils/syscache.h"
28
29
30 /* Number of OIDs to prefetch (preallocate) per XLOG write */
31 #define VAR_OID_PREFETCH                8192
32
33 /* pointer to "variable cache" in shared memory (set up by shmem.c) */
34 VariableCache ShmemVariableCache = NULL;
35
36
37 /*
38  * Allocate the next XID for a new transaction or subtransaction.
39  *
40  * The new XID is also stored into MyPgXact before returning.
41  *
42  * Note: when this is called, we are actually already inside a valid
43  * transaction, since XIDs are now not allocated until the transaction
44  * does something.  So it is safe to do a database lookup if we want to
45  * issue a warning about XID wrap.
46  */
47 TransactionId
48 GetNewTransactionId(bool isSubXact)
49 {
50         TransactionId xid;
51
52         /*
53          * During bootstrap initialization, we return the special bootstrap
54          * transaction id.
55          */
56         if (IsBootstrapProcessingMode())
57         {
58                 Assert(!isSubXact);
59                 MyPgXact->xid = BootstrapTransactionId;
60                 return BootstrapTransactionId;
61         }
62
63         /* safety check, we should never get this far in a HS slave */
64         if (RecoveryInProgress())
65                 elog(ERROR, "cannot assign TransactionIds during recovery");
66
67         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
68
69         xid = ShmemVariableCache->nextXid;
70
71         /*----------
72          * Check to see if it's safe to assign another XID.  This protects against
73          * catastrophic data loss due to XID wraparound.  The basic rules are:
74          *
75          * If we're past xidVacLimit, start trying to force autovacuum cycles.
76          * If we're past xidWarnLimit, start issuing warnings.
77          * If we're past xidStopLimit, refuse to execute transactions, unless
78          * we are running in single-user mode (which gives an escape hatch
79          * to the DBA who somehow got past the earlier defenses).
80          *
81          * Note that this coding also appears in GetNewMultiXactId.
82          *----------
83          */
84         if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit))
85         {
86                 /*
87                  * For safety's sake, we release XidGenLock while sending signals,
88                  * warnings, etc.  This is not so much because we care about
89                  * preserving concurrency in this situation, as to avoid any
90                  * possibility of deadlock while doing get_database_name(). First,
91                  * copy all the shared values we'll need in this path.
92                  */
93                 TransactionId xidWarnLimit = ShmemVariableCache->xidWarnLimit;
94                 TransactionId xidStopLimit = ShmemVariableCache->xidStopLimit;
95                 TransactionId xidWrapLimit = ShmemVariableCache->xidWrapLimit;
96                 Oid                     oldest_datoid = ShmemVariableCache->oldestXidDB;
97
98                 LWLockRelease(XidGenLock);
99
100                 /*
101                  * To avoid swamping the postmaster with signals, we issue the autovac
102                  * request only once per 64K transaction starts.  This still gives
103                  * plenty of chances before we get into real trouble.
104                  */
105                 if (IsUnderPostmaster && (xid % 65536) == 0)
106                         SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
107
108                 if (IsUnderPostmaster &&
109                         TransactionIdFollowsOrEquals(xid, xidStopLimit))
110                 {
111                         char       *oldest_datname = get_database_name(oldest_datoid);
112
113                         /* complain even if that DB has disappeared */
114                         if (oldest_datname)
115                                 ereport(ERROR,
116                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
117                                                  errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
118                                                                 oldest_datname),
119                                                  errhint("Stop the postmaster and vacuum that database in single-user mode.\n"
120                                                                  "You might also need to commit or roll back old prepared transactions.")));
121                         else
122                                 ereport(ERROR,
123                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
124                                                  errmsg("database is not accepting commands to avoid wraparound data loss in database with OID %u",
125                                                                 oldest_datoid),
126                                                  errhint("Stop the postmaster and vacuum that database in single-user mode.\n"
127                                                                  "You might also need to commit or roll back old prepared transactions.")));
128                 }
129                 else if (TransactionIdFollowsOrEquals(xid, xidWarnLimit))
130                 {
131                         char       *oldest_datname = get_database_name(oldest_datoid);
132
133                         /* complain even if that DB has disappeared */
134                         if (oldest_datname)
135                                 ereport(WARNING,
136                                                 (errmsg("database \"%s\" must be vacuumed within %u transactions",
137                                                                 oldest_datname,
138                                                                 xidWrapLimit - xid),
139                                                  errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
140                                                                  "You might also need to commit or roll back old prepared transactions.")));
141                         else
142                                 ereport(WARNING,
143                                                 (errmsg("database with OID %u must be vacuumed within %u transactions",
144                                                                 oldest_datoid,
145                                                                 xidWrapLimit - xid),
146                                                  errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
147                                                                  "You might also need to commit or roll back old prepared transactions.")));
148                 }
149
150                 /* Re-acquire lock and start over */
151                 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
152                 xid = ShmemVariableCache->nextXid;
153         }
154
155         /*
156          * If we are allocating the first XID of a new page of the commit log,
157          * zero out that commit-log page before returning. We must do this while
158          * holding XidGenLock, else another xact could acquire and commit a later
159          * XID before we zero the page.  Fortunately, a page of the commit log
160          * holds 32K or more transactions, so we don't have to do this very often.
161          *
162          * Extend pg_subtrans and pg_commit_ts too.
163          */
164         ExtendCLOG(xid);
165         ExtendCommitTs(xid);
166         ExtendSUBTRANS(xid);
167
168         /*
169          * Now advance the nextXid counter.  This must not happen until after we
170          * have successfully completed ExtendCLOG() --- if that routine fails, we
171          * want the next incoming transaction to try it again.  We cannot assign
172          * more XIDs until there is CLOG space for them.
173          */
174         TransactionIdAdvance(ShmemVariableCache->nextXid);
175
176         /*
177          * We must store the new XID into the shared ProcArray before releasing
178          * XidGenLock.  This ensures that every active XID older than
179          * latestCompletedXid is present in the ProcArray, which is essential for
180          * correct OldestXmin tracking; see src/backend/access/transam/README.
181          *
182          * XXX by storing xid into MyPgXact without acquiring ProcArrayLock, we
183          * are relying on fetch/store of an xid to be atomic, else other backends
184          * might see a partially-set xid here.  But holding both locks at once
185          * would be a nasty concurrency hit.  So for now, assume atomicity.
186          *
187          * Note that readers of PGXACT xid fields should be careful to fetch the
188          * value only once, rather than assume they can read a value multiple
189          * times and get the same answer each time.
190          *
191          * The same comments apply to the subxact xid count and overflow fields.
192          *
193          * A solution to the atomic-store problem would be to give each PGXACT its
194          * own spinlock used only for fetching/storing that PGXACT's xid and
195          * related fields.
196          *
197          * If there's no room to fit a subtransaction XID into PGPROC, set the
198          * cache-overflowed flag instead.  This forces readers to look in
199          * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
200          * race-condition window, in that the new XID will not appear as running
201          * until its parent link has been placed into pg_subtrans. However, that
202          * will happen before anyone could possibly have a reason to inquire about
203          * the status of the XID, so it seems OK.  (Snapshots taken during this
204          * window *will* include the parent XID, so they will deliver the correct
205          * answer later on when someone does have a reason to inquire.)
206          */
207         {
208                 /*
209                  * Use volatile pointer to prevent code rearrangement; other backends
210                  * could be examining my subxids info concurrently, and we don't want
211                  * them to see an invalid intermediate state, such as incrementing
212                  * nxids before filling the array entry.  Note we are assuming that
213                  * TransactionId and int fetch/store are atomic.
214                  */
215                 volatile PGPROC *myproc = MyProc;
216                 volatile PGXACT *mypgxact = MyPgXact;
217
218                 if (!isSubXact)
219                         mypgxact->xid = xid;
220                 else
221                 {
222                         int                     nxids = mypgxact->nxids;
223
224                         if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
225                         {
226                                 myproc->subxids.xids[nxids] = xid;
227                                 mypgxact->nxids = nxids + 1;
228                         }
229                         else
230                                 mypgxact->overflowed = true;
231                 }
232         }
233
234         LWLockRelease(XidGenLock);
235
236         return xid;
237 }
238
239 /*
240  * Read nextXid but don't allocate it.
241  */
242 TransactionId
243 ReadNewTransactionId(void)
244 {
245         TransactionId xid;
246
247         LWLockAcquire(XidGenLock, LW_SHARED);
248         xid = ShmemVariableCache->nextXid;
249         LWLockRelease(XidGenLock);
250
251         return xid;
252 }
253
254 /*
255  * Determine the last safe XID to allocate given the currently oldest
256  * datfrozenxid (ie, the oldest XID that might exist in any database
257  * of our cluster), and the OID of the (or a) database with that value.
258  */
259 void
260 SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
261 {
262         TransactionId xidVacLimit;
263         TransactionId xidWarnLimit;
264         TransactionId xidStopLimit;
265         TransactionId xidWrapLimit;
266         TransactionId curXid;
267
268         Assert(TransactionIdIsNormal(oldest_datfrozenxid));
269
270         /*
271          * The place where we actually get into deep trouble is halfway around
272          * from the oldest potentially-existing XID.  (This calculation is
273          * probably off by one or two counts, because the special XIDs reduce the
274          * size of the loop a little bit.  But we throw in plenty of slop below,
275          * so it doesn't matter.)
276          */
277         xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
278         if (xidWrapLimit < FirstNormalTransactionId)
279                 xidWrapLimit += FirstNormalTransactionId;
280
281         /*
282          * We'll refuse to continue assigning XIDs in interactive mode once we get
283          * within 1M transactions of data loss.  This leaves lots of room for the
284          * DBA to fool around fixing things in a standalone backend, while not
285          * being significant compared to total XID space. (Note that since
286          * vacuuming requires one transaction per table cleaned, we had better be
287          * sure there's lots of XIDs left...)
288          */
289         xidStopLimit = xidWrapLimit - 1000000;
290         if (xidStopLimit < FirstNormalTransactionId)
291                 xidStopLimit -= FirstNormalTransactionId;
292
293         /*
294          * We'll start complaining loudly when we get within 10M transactions of
295          * the stop point.  This is kind of arbitrary, but if you let your gas
296          * gauge get down to 1% of full, would you be looking for the next gas
297          * station?  We need to be fairly liberal about this number because there
298          * are lots of scenarios where most transactions are done by automatic
299          * clients that won't pay attention to warnings. (No, we're not gonna make
300          * this configurable.  If you know enough to configure it, you know enough
301          * to not get in this kind of trouble in the first place.)
302          */
303         xidWarnLimit = xidStopLimit - 10000000;
304         if (xidWarnLimit < FirstNormalTransactionId)
305                 xidWarnLimit -= FirstNormalTransactionId;
306
307         /*
308          * We'll start trying to force autovacuums when oldest_datfrozenxid gets
309          * to be more than autovacuum_freeze_max_age transactions old.
310          *
311          * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range,
312          * so that xidVacLimit will be well before xidWarnLimit.
313          *
314          * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
315          * we don't have to worry about dealing with on-the-fly changes in its
316          * value.  It doesn't look practical to update shared state from a GUC
317          * assign hook (too many processes would try to execute the hook,
318          * resulting in race conditions as well as crashes of those not connected
319          * to shared memory).  Perhaps this can be improved someday.  See also
320          * SetMultiXactIdLimit.
321          */
322         xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
323         if (xidVacLimit < FirstNormalTransactionId)
324                 xidVacLimit += FirstNormalTransactionId;
325
326         /* Grab lock for just long enough to set the new limit values */
327         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
328         ShmemVariableCache->oldestXid = oldest_datfrozenxid;
329         ShmemVariableCache->xidVacLimit = xidVacLimit;
330         ShmemVariableCache->xidWarnLimit = xidWarnLimit;
331         ShmemVariableCache->xidStopLimit = xidStopLimit;
332         ShmemVariableCache->xidWrapLimit = xidWrapLimit;
333         ShmemVariableCache->oldestXidDB = oldest_datoid;
334         curXid = ShmemVariableCache->nextXid;
335         LWLockRelease(XidGenLock);
336
337         /* Log the info */
338         ereport(DEBUG1,
339                         (errmsg("transaction ID wrap limit is %u, limited by database with OID %u",
340                                         xidWrapLimit, oldest_datoid)));
341
342         /*
343          * If past the autovacuum force point, immediately signal an autovac
344          * request.  The reason for this is that autovac only processes one
345          * database per invocation.  Once it's finished cleaning up the oldest
346          * database, it'll call here, and we'll signal the postmaster to start
347          * another iteration immediately if there are still any old databases.
348          */
349         if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
350                 IsUnderPostmaster && !InRecovery)
351                 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
352
353         /* Give an immediate warning if past the wrap warn point */
354         if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit) && !InRecovery)
355         {
356                 char       *oldest_datname;
357
358                 /*
359                  * We can be called when not inside a transaction, for example during
360                  * StartupXLOG().  In such a case we cannot do database access, so we
361                  * must just report the oldest DB's OID.
362                  *
363                  * Note: it's also possible that get_database_name fails and returns
364                  * NULL, for example because the database just got dropped.  We'll
365                  * still warn, even though the warning might now be unnecessary.
366                  */
367                 if (IsTransactionState())
368                         oldest_datname = get_database_name(oldest_datoid);
369                 else
370                         oldest_datname = NULL;
371
372                 if (oldest_datname)
373                         ereport(WARNING,
374                         (errmsg("database \"%s\" must be vacuumed within %u transactions",
375                                         oldest_datname,
376                                         xidWrapLimit - curXid),
377                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
378                                          "You might also need to commit or roll back old prepared transactions.")));
379                 else
380                         ereport(WARNING,
381                                         (errmsg("database with OID %u must be vacuumed within %u transactions",
382                                                         oldest_datoid,
383                                                         xidWrapLimit - curXid),
384                                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
385                                                          "You might also need to commit or roll back old prepared transactions.")));
386         }
387 }
388
389
390 /*
391  * ForceTransactionIdLimitUpdate -- does the XID wrap-limit data need updating?
392  *
393  * We primarily check whether oldestXidDB is valid.  The cases we have in
394  * mind are that that database was dropped, or the field was reset to zero
395  * by pg_resetxlog.  In either case we should force recalculation of the
396  * wrap limit.  Also do it if oldestXid is old enough to be forcing
397  * autovacuums or other actions; this ensures we update our state as soon
398  * as possible once extra overhead is being incurred.
399  */
400 bool
401 ForceTransactionIdLimitUpdate(void)
402 {
403         TransactionId nextXid;
404         TransactionId xidVacLimit;
405         TransactionId oldestXid;
406         Oid                     oldestXidDB;
407
408         /* Locking is probably not really necessary, but let's be careful */
409         LWLockAcquire(XidGenLock, LW_SHARED);
410         nextXid = ShmemVariableCache->nextXid;
411         xidVacLimit = ShmemVariableCache->xidVacLimit;
412         oldestXid = ShmemVariableCache->oldestXid;
413         oldestXidDB = ShmemVariableCache->oldestXidDB;
414         LWLockRelease(XidGenLock);
415
416         if (!TransactionIdIsNormal(oldestXid))
417                 return true;                    /* shouldn't happen, but just in case */
418         if (!TransactionIdIsValid(xidVacLimit))
419                 return true;                    /* this shouldn't happen anymore either */
420         if (TransactionIdFollowsOrEquals(nextXid, xidVacLimit))
421                 return true;                    /* past VacLimit, don't delay updating */
422         if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(oldestXidDB)))
423                 return true;                    /* could happen, per comments above */
424         return false;
425 }
426
427
428 /*
429  * GetNewObjectId -- allocate a new OID
430  *
431  * OIDs are generated by a cluster-wide counter.  Since they are only 32 bits
432  * wide, counter wraparound will occur eventually, and therefore it is unwise
433  * to assume they are unique unless precautions are taken to make them so.
434  * Hence, this routine should generally not be used directly.  The only
435  * direct callers should be GetNewOid() and GetNewRelFileNode() in
436  * catalog/catalog.c.
437  */
438 Oid
439 GetNewObjectId(void)
440 {
441         Oid                     result;
442
443         /* safety check, we should never get this far in a HS slave */
444         if (RecoveryInProgress())
445                 elog(ERROR, "cannot assign OIDs during recovery");
446
447         LWLockAcquire(OidGenLock, LW_EXCLUSIVE);
448
449         /*
450          * Check for wraparound of the OID counter.  We *must* not return 0
451          * (InvalidOid); and as long as we have to check that, it seems a good
452          * idea to skip over everything below FirstNormalObjectId too. (This
453          * basically just avoids lots of collisions with bootstrap-assigned OIDs
454          * right after a wrap occurs, so as to avoid a possibly large number of
455          * iterations in GetNewOid.)  Note we are relying on unsigned comparison.
456          *
457          * During initdb, we start the OID generator at FirstBootstrapObjectId, so
458          * we only wrap if before that point when in bootstrap or standalone mode.
459          * The first time through this routine after normal postmaster start, the
460          * counter will be forced up to FirstNormalObjectId.  This mechanism
461          * leaves the OIDs between FirstBootstrapObjectId and FirstNormalObjectId
462          * available for automatic assignment during initdb, while ensuring they
463          * will never conflict with user-assigned OIDs.
464          */
465         if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId))
466         {
467                 if (IsPostmasterEnvironment)
468                 {
469                         /* wraparound, or first post-initdb assignment, in normal mode */
470                         ShmemVariableCache->nextOid = FirstNormalObjectId;
471                         ShmemVariableCache->oidCount = 0;
472                 }
473                 else
474                 {
475                         /* we may be bootstrapping, so don't enforce the full range */
476                         if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
477                         {
478                                 /* wraparound in standalone mode (unlikely but possible) */
479                                 ShmemVariableCache->nextOid = FirstNormalObjectId;
480                                 ShmemVariableCache->oidCount = 0;
481                         }
482                 }
483         }
484
485         /* If we run out of logged for use oids then we must log more */
486         if (ShmemVariableCache->oidCount == 0)
487         {
488                 XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
489                 ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
490         }
491
492         result = ShmemVariableCache->nextOid;
493
494         (ShmemVariableCache->nextOid)++;
495         (ShmemVariableCache->oidCount)--;
496
497         LWLockRelease(OidGenLock);
498
499         return result;
500 }