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