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