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