PostgreSQL Source Code  git master
clog.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * clog.c
4  * PostgreSQL transaction-commit-log manager
5  *
6  * This module replaces the old "pg_log" access code, which treated pg_log
7  * essentially like a relation, in that it went through the regular buffer
8  * manager. The problem with that was that there wasn't any good way to
9  * recycle storage space for transactions so old that they'll never be
10  * looked up again. Now we use specialized access code so that the commit
11  * log can be broken into relatively small, independent segments.
12  *
13  * XLOG interactions: this module generates an XLOG record whenever a new
14  * CLOG page is initialized to zeroes. Other writes of CLOG come from
15  * recording of transaction commit or abort in xact.c, which generates its
16  * own XLOG records for these events and will re-perform the status update
17  * on redo; so we need make no additional XLOG entry here. For synchronous
18  * transaction commits, the XLOG is guaranteed flushed through the XLOG commit
19  * record before we are called to log a commit, so the WAL rule "write xlog
20  * before data" is satisfied automatically. However, for async commits we
21  * must track the latest LSN affecting each CLOG page, so that we can flush
22  * XLOG that far and satisfy the WAL rule. We don't have to worry about this
23  * for aborts (whether sync or async), since the post-crash assumption would
24  * be that such transactions failed anyway.
25  *
26  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
27  * Portions Copyright (c) 1994, Regents of the University of California
28  *
29  * src/backend/access/transam/clog.c
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34 
35 #include "access/clog.h"
36 #include "access/slru.h"
37 #include "access/transam.h"
38 #include "access/xlog.h"
39 #include "access/xloginsert.h"
40 #include "access/xlogutils.h"
41 #include "miscadmin.h"
42 #include "pg_trace.h"
43 #include "pgstat.h"
44 #include "storage/proc.h"
45 #include "storage/sync.h"
46 
47 /*
48  * Defines for CLOG page sizes. A page is the same BLCKSZ as is used
49  * everywhere else in Postgres.
50  *
51  * Note: because TransactionIds are 32 bits and wrap around at 0xFFFFFFFF,
52  * CLOG page numbering also wraps around at 0xFFFFFFFF/CLOG_XACTS_PER_PAGE,
53  * and CLOG segment numbering at
54  * 0xFFFFFFFF/CLOG_XACTS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need take no
55  * explicit notice of that fact in this module, except when comparing segment
56  * and page numbers in TruncateCLOG (see CLOGPagePrecedes).
57  */
58 
59 /* We need two bits per xact, so four xacts fit in a byte */
60 #define CLOG_BITS_PER_XACT 2
61 #define CLOG_XACTS_PER_BYTE 4
62 #define CLOG_XACTS_PER_PAGE (BLCKSZ * CLOG_XACTS_PER_BYTE)
63 #define CLOG_XACT_BITMASK ((1 << CLOG_BITS_PER_XACT) - 1)
64 
65 
66 /*
67  * Although we return an int64 the actual value can't currently exceed
68  * 0xFFFFFFFF/CLOG_XACTS_PER_PAGE.
69  */
70 static inline int64
72 {
73  return xid / (int64) CLOG_XACTS_PER_PAGE;
74 }
75 
76 #define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE)
77 #define TransactionIdToByte(xid) (TransactionIdToPgIndex(xid) / CLOG_XACTS_PER_BYTE)
78 #define TransactionIdToBIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_BYTE)
79 
80 /* We store the latest async LSN for each group of transactions */
81 #define CLOG_XACTS_PER_LSN_GROUP 32 /* keep this a power of 2 */
82 #define CLOG_LSNS_PER_PAGE (CLOG_XACTS_PER_PAGE / CLOG_XACTS_PER_LSN_GROUP)
83 
84 #define GetLSNIndex(slotno, xid) ((slotno) * CLOG_LSNS_PER_PAGE + \
85  ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
86 
87 /*
88  * The number of subtransactions below which we consider to apply clog group
89  * update optimization. Testing reveals that the number higher than this can
90  * hurt performance.
91  */
92 #define THRESHOLD_SUBTRANS_CLOG_OPT 5
93 
94 /*
95  * Link to shared-memory data structures for CLOG control
96  */
98 
99 #define XactCtl (&XactCtlData)
100 
101 
102 static int ZeroCLOGPage(int64 pageno, bool writeXlog);
103 static bool CLOGPagePrecedes(int64 page1, int64 page2);
104 static void WriteZeroPageXlogRec(int64 pageno);
105 static void WriteTruncateXlogRec(int64 pageno, TransactionId oldestXact,
106  Oid oldestXactDb);
107 static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
108  TransactionId *subxids, XidStatus status,
109  XLogRecPtr lsn, int64 pageno,
110  bool all_xact_same_page);
111 static void TransactionIdSetStatusBit(TransactionId xid, XidStatus status,
112  XLogRecPtr lsn, int slotno);
113 static void set_status_by_pages(int nsubxids, TransactionId *subxids,
114  XidStatus status, XLogRecPtr lsn);
116  XidStatus status, XLogRecPtr lsn, int64 pageno);
117 static void TransactionIdSetPageStatusInternal(TransactionId xid, int nsubxids,
118  TransactionId *subxids, XidStatus status,
119  XLogRecPtr lsn, int64 pageno);
120 
121 
122 /*
123  * TransactionIdSetTreeStatus
124  *
125  * Record the final state of transaction entries in the commit log for
126  * a transaction and its subtransaction tree. Take care to ensure this is
127  * efficient, and as atomic as possible.
128  *
129  * xid is a single xid to set status for. This will typically be
130  * the top level transactionid for a top level commit or abort. It can
131  * also be a subtransaction when we record transaction aborts.
132  *
133  * subxids is an array of xids of length nsubxids, representing subtransactions
134  * in the tree of xid. In various cases nsubxids may be zero.
135  *
136  * lsn must be the WAL location of the commit record when recording an async
137  * commit. For a synchronous commit it can be InvalidXLogRecPtr, since the
138  * caller guarantees the commit record is already flushed in that case. It
139  * should be InvalidXLogRecPtr for abort cases, too.
140  *
141  * In the commit case, atomicity is limited by whether all the subxids are in
142  * the same CLOG page as xid. If they all are, then the lock will be grabbed
143  * only once, and the status will be set to committed directly. Otherwise
144  * we must
145  * 1. set sub-committed all subxids that are not on the same page as the
146  * main xid
147  * 2. atomically set committed the main xid and the subxids on the same page
148  * 3. go over the first bunch again and set them committed
149  * Note that as far as concurrent checkers are concerned, main transaction
150  * commit as a whole is still atomic.
151  *
152  * Example:
153  * TransactionId t commits and has subxids t1, t2, t3, t4
154  * t is on page p1, t1 is also on p1, t2 and t3 are on p2, t4 is on p3
155  * 1. update pages2-3:
156  * page2: set t2,t3 as sub-committed
157  * page3: set t4 as sub-committed
158  * 2. update page1:
159  * page1: set t,t1 as committed
160  * 3. update pages2-3:
161  * page2: set t2,t3 as committed
162  * page3: set t4 as committed
163  *
164  * NB: this is a low-level routine and is NOT the preferred entry point
165  * for most uses; functions in transam.c are the intended callers.
166  *
167  * XXX Think about issuing POSIX_FADV_WILLNEED on pages that we will need,
168  * but aren't yet in cache, as well as hinting pages not to fall out of
169  * cache yet.
170  */
171 void
173  TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
174 {
175  int64 pageno = TransactionIdToPage(xid); /* get page of parent */
176  int i;
177 
179  status == TRANSACTION_STATUS_ABORTED);
180 
181  /*
182  * See how many subxids, if any, are on the same page as the parent, if
183  * any.
184  */
185  for (i = 0; i < nsubxids; i++)
186  {
187  if (TransactionIdToPage(subxids[i]) != pageno)
188  break;
189  }
190 
191  /*
192  * Do all items fit on a single page?
193  */
194  if (i == nsubxids)
195  {
196  /*
197  * Set the parent and all subtransactions in a single call
198  */
199  TransactionIdSetPageStatus(xid, nsubxids, subxids, status, lsn,
200  pageno, true);
201  }
202  else
203  {
204  int nsubxids_on_first_page = i;
205 
206  /*
207  * If this is a commit then we care about doing this correctly (i.e.
208  * using the subcommitted intermediate status). By here, we know
209  * we're updating more than one page of clog, so we must mark entries
210  * that are *not* on the first page so that they show as subcommitted
211  * before we then return to update the status to fully committed.
212  *
213  * To avoid touching the first page twice, skip marking subcommitted
214  * for the subxids on that first page.
215  */
216  if (status == TRANSACTION_STATUS_COMMITTED)
217  set_status_by_pages(nsubxids - nsubxids_on_first_page,
218  subxids + nsubxids_on_first_page,
220 
221  /*
222  * Now set the parent and subtransactions on same page as the parent,
223  * if any
224  */
225  pageno = TransactionIdToPage(xid);
226  TransactionIdSetPageStatus(xid, nsubxids_on_first_page, subxids, status,
227  lsn, pageno, false);
228 
229  /*
230  * Now work through the rest of the subxids one clog page at a time,
231  * starting from the second page onwards, like we did above.
232  */
233  set_status_by_pages(nsubxids - nsubxids_on_first_page,
234  subxids + nsubxids_on_first_page,
235  status, lsn);
236  }
237 }
238 
239 /*
240  * Helper for TransactionIdSetTreeStatus: set the status for a bunch of
241  * transactions, chunking in the separate CLOG pages involved. We never
242  * pass the whole transaction tree to this function, only subtransactions
243  * that are on different pages to the top level transaction id.
244  */
245 static void
246 set_status_by_pages(int nsubxids, TransactionId *subxids,
247  XidStatus status, XLogRecPtr lsn)
248 {
249  int64 pageno = TransactionIdToPage(subxids[0]);
250  int offset = 0;
251  int i = 0;
252 
253  Assert(nsubxids > 0); /* else the pageno fetch above is unsafe */
254 
255  while (i < nsubxids)
256  {
257  int num_on_page = 0;
258  int64 nextpageno;
259 
260  do
261  {
262  nextpageno = TransactionIdToPage(subxids[i]);
263  if (nextpageno != pageno)
264  break;
265  num_on_page++;
266  i++;
267  } while (i < nsubxids);
268 
270  num_on_page, subxids + offset,
271  status, lsn, pageno, false);
272  offset = i;
273  pageno = nextpageno;
274  }
275 }
276 
277 /*
278  * Record the final state of transaction entries in the commit log for all
279  * entries on a single page. Atomic only on this page.
280  */
281 static void
283  TransactionId *subxids, XidStatus status,
284  XLogRecPtr lsn, int64 pageno,
285  bool all_xact_same_page)
286 {
287  /* Can't use group update when PGPROC overflows. */
289  "group clog threshold less than PGPROC cached subxids");
290 
291  /*
292  * When there is contention on XactSLRULock, we try to group multiple
293  * updates; a single leader process will perform transaction status
294  * updates for multiple backends so that the number of times XactSLRULock
295  * needs to be acquired is reduced.
296  *
297  * For this optimization to be safe, the XID and subxids in MyProc must be
298  * the same as the ones for which we're setting the status. Check that
299  * this is the case.
300  *
301  * For this optimization to be efficient, we shouldn't have too many
302  * sub-XIDs and all of the XIDs for which we're adjusting clog should be
303  * on the same page. Check those conditions, too.
304  */
305  if (all_xact_same_page && xid == MyProc->xid &&
306  nsubxids <= THRESHOLD_SUBTRANS_CLOG_OPT &&
307  nsubxids == MyProc->subxidStatus.count &&
308  (nsubxids == 0 ||
309  memcmp(subxids, MyProc->subxids.xids,
310  nsubxids * sizeof(TransactionId)) == 0))
311  {
312  /*
313  * If we can immediately acquire XactSLRULock, we update the status of
314  * our own XID and release the lock. If not, try use group XID
315  * update. If that doesn't work out, fall back to waiting for the
316  * lock to perform an update for this transaction only.
317  */
318  if (LWLockConditionalAcquire(XactSLRULock, LW_EXCLUSIVE))
319  {
320  /* Got the lock without waiting! Do the update. */
321  TransactionIdSetPageStatusInternal(xid, nsubxids, subxids, status,
322  lsn, pageno);
323  LWLockRelease(XactSLRULock);
324  return;
325  }
326  else if (TransactionGroupUpdateXidStatus(xid, status, lsn, pageno))
327  {
328  /* Group update mechanism has done the work. */
329  return;
330  }
331 
332  /* Fall through only if update isn't done yet. */
333  }
334 
335  /* Group update not applicable, or couldn't accept this page number. */
336  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
337  TransactionIdSetPageStatusInternal(xid, nsubxids, subxids, status,
338  lsn, pageno);
339  LWLockRelease(XactSLRULock);
340 }
341 
342 /*
343  * Record the final state of transaction entry in the commit log
344  *
345  * We don't do any locking here; caller must handle that.
346  */
347 static void
349  TransactionId *subxids, XidStatus status,
350  XLogRecPtr lsn, int64 pageno)
351 {
352  int slotno;
353  int i;
354 
356  status == TRANSACTION_STATUS_ABORTED ||
358  Assert(LWLockHeldByMeInMode(XactSLRULock, LW_EXCLUSIVE));
359 
360  /*
361  * If we're doing an async commit (ie, lsn is valid), then we must wait
362  * for any active write on the page slot to complete. Otherwise our
363  * update could reach disk in that write, which will not do since we
364  * mustn't let it reach disk until we've done the appropriate WAL flush.
365  * But when lsn is invalid, it's OK to scribble on a page while it is
366  * write-busy, since we don't care if the update reaches disk sooner than
367  * we think.
368  */
369  slotno = SimpleLruReadPage(XactCtl, pageno, XLogRecPtrIsInvalid(lsn), xid);
370 
371  /*
372  * Set the main transaction id, if any.
373  *
374  * If we update more than one xid on this page while it is being written
375  * out, we might find that some of the bits go to disk and others don't.
376  * If we are updating commits on the page with the top-level xid that
377  * could break atomicity, so we subcommit the subxids first before we mark
378  * the top-level commit.
379  */
380  if (TransactionIdIsValid(xid))
381  {
382  /* Subtransactions first, if needed ... */
383  if (status == TRANSACTION_STATUS_COMMITTED)
384  {
385  for (i = 0; i < nsubxids; i++)
386  {
387  Assert(XactCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
388  TransactionIdSetStatusBit(subxids[i],
390  lsn, slotno);
391  }
392  }
393 
394  /* ... then the main transaction */
395  TransactionIdSetStatusBit(xid, status, lsn, slotno);
396  }
397 
398  /* Set the subtransactions */
399  for (i = 0; i < nsubxids; i++)
400  {
401  Assert(XactCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
402  TransactionIdSetStatusBit(subxids[i], status, lsn, slotno);
403  }
404 
405  XactCtl->shared->page_dirty[slotno] = true;
406 }
407 
408 /*
409  * When we cannot immediately acquire XactSLRULock in exclusive mode at
410  * commit time, add ourselves to a list of processes that need their XIDs
411  * status update. The first process to add itself to the list will acquire
412  * XactSLRULock in exclusive mode and set transaction status as required
413  * on behalf of all group members. This avoids a great deal of contention
414  * around XactSLRULock when many processes are trying to commit at once,
415  * since the lock need not be repeatedly handed off from one committing
416  * process to the next.
417  *
418  * Returns true when transaction status has been updated in clog; returns
419  * false if we decided against applying the optimization because the page
420  * number we need to update differs from those processes already waiting.
421  */
422 static bool
424  XLogRecPtr lsn, int64 pageno)
425 {
426  volatile PROC_HDR *procglobal = ProcGlobal;
427  PGPROC *proc = MyProc;
428  uint32 nextidx;
429  uint32 wakeidx;
430 
431  /* We should definitely have an XID whose status needs to be updated. */
433 
434  /*
435  * Add ourselves to the list of processes needing a group XID status
436  * update.
437  */
438  proc->clogGroupMember = true;
439  proc->clogGroupMemberXid = xid;
440  proc->clogGroupMemberXidStatus = status;
441  proc->clogGroupMemberPage = pageno;
442  proc->clogGroupMemberLsn = lsn;
443 
444  nextidx = pg_atomic_read_u32(&procglobal->clogGroupFirst);
445 
446  while (true)
447  {
448  /*
449  * Add the proc to list, if the clog page where we need to update the
450  * current transaction status is same as group leader's clog page.
451  *
452  * There is a race condition here, which is that after doing the below
453  * check and before adding this proc's clog update to a group, the
454  * group leader might have already finished the group update for this
455  * page and becomes group leader of another group. This will lead to a
456  * situation where a single group can have different clog page
457  * updates. This isn't likely and will still work, just maybe a bit
458  * less efficiently.
459  */
460  if (nextidx != INVALID_PGPROCNO &&
462  {
463  /*
464  * Ensure that this proc is not a member of any clog group that
465  * needs an XID status update.
466  */
467  proc->clogGroupMember = false;
469  return false;
470  }
471 
472  pg_atomic_write_u32(&proc->clogGroupNext, nextidx);
473 
475  &nextidx,
476  (uint32) proc->pgprocno))
477  break;
478  }
479 
480  /*
481  * If the list was not empty, the leader will update the status of our
482  * XID. It is impossible to have followers without a leader because the
483  * first process that has added itself to the list will always have
484  * nextidx as INVALID_PGPROCNO.
485  */
486  if (nextidx != INVALID_PGPROCNO)
487  {
488  int extraWaits = 0;
489 
490  /* Sleep until the leader updates our XID status. */
491  pgstat_report_wait_start(WAIT_EVENT_XACT_GROUP_UPDATE);
492  for (;;)
493  {
494  /* acts as a read barrier */
495  PGSemaphoreLock(proc->sem);
496  if (!proc->clogGroupMember)
497  break;
498  extraWaits++;
499  }
501 
503 
504  /* Fix semaphore count for any absorbed wakeups */
505  while (extraWaits-- > 0)
506  PGSemaphoreUnlock(proc->sem);
507  return true;
508  }
509 
510  /* We are the leader. Acquire the lock on behalf of everyone. */
511  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
512 
513  /*
514  * Now that we've got the lock, clear the list of processes waiting for
515  * group XID status update, saving a pointer to the head of the list.
516  * Trying to pop elements one at a time could lead to an ABA problem.
517  */
518  nextidx = pg_atomic_exchange_u32(&procglobal->clogGroupFirst,
520 
521  /* Remember head of list so we can perform wakeups after dropping lock. */
522  wakeidx = nextidx;
523 
524  /* Walk the list and update the status of all XIDs. */
525  while (nextidx != INVALID_PGPROCNO)
526  {
527  PGPROC *nextproc = &ProcGlobal->allProcs[nextidx];
528 
529  /*
530  * Transactions with more than THRESHOLD_SUBTRANS_CLOG_OPT sub-XIDs
531  * should not use group XID status update mechanism.
532  */
534 
536  nextproc->subxidStatus.count,
537  nextproc->subxids.xids,
538  nextproc->clogGroupMemberXidStatus,
539  nextproc->clogGroupMemberLsn,
540  nextproc->clogGroupMemberPage);
541 
542  /* Move to next proc in list. */
543  nextidx = pg_atomic_read_u32(&nextproc->clogGroupNext);
544  }
545 
546  /* We're done with the lock now. */
547  LWLockRelease(XactSLRULock);
548 
549  /*
550  * Now that we've released the lock, go back and wake everybody up. We
551  * don't do this under the lock so as to keep lock hold times to a
552  * minimum.
553  */
554  while (wakeidx != INVALID_PGPROCNO)
555  {
556  PGPROC *wakeproc = &ProcGlobal->allProcs[wakeidx];
557 
558  wakeidx = pg_atomic_read_u32(&wakeproc->clogGroupNext);
560 
561  /* ensure all previous writes are visible before follower continues. */
563 
564  wakeproc->clogGroupMember = false;
565 
566  if (wakeproc != MyProc)
567  PGSemaphoreUnlock(wakeproc->sem);
568  }
569 
570  return true;
571 }
572 
573 /*
574  * Sets the commit status of a single transaction.
575  *
576  * Must be called with XactSLRULock held
577  */
578 static void
580 {
581  int byteno = TransactionIdToByte(xid);
582  int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
583  char *byteptr;
584  char byteval;
585  char curval;
586 
587  byteptr = XactCtl->shared->page_buffer[slotno] + byteno;
588  curval = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
589 
590  /*
591  * When replaying transactions during recovery we still need to perform
592  * the two phases of subcommit and then commit. However, some transactions
593  * are already correctly marked, so we just treat those as a no-op which
594  * allows us to keep the following Assert as restrictive as possible.
595  */
596  if (InRecovery && status == TRANSACTION_STATUS_SUB_COMMITTED &&
598  return;
599 
600  /*
601  * Current state change should be from 0 or subcommitted to target state
602  * or we should already be there when replaying changes during recovery.
603  */
604  Assert(curval == 0 ||
606  status != TRANSACTION_STATUS_IN_PROGRESS) ||
607  curval == status);
608 
609  /* note this assumes exclusive access to the clog page */
610  byteval = *byteptr;
611  byteval &= ~(((1 << CLOG_BITS_PER_XACT) - 1) << bshift);
612  byteval |= (status << bshift);
613  *byteptr = byteval;
614 
615  /*
616  * Update the group LSN if the transaction completion LSN is higher.
617  *
618  * Note: lsn will be invalid when supplied during InRecovery processing,
619  * so we don't need to do anything special to avoid LSN updates during
620  * recovery. After recovery completes the next clog change will set the
621  * LSN correctly.
622  */
623  if (!XLogRecPtrIsInvalid(lsn))
624  {
625  int lsnindex = GetLSNIndex(slotno, xid);
626 
627  if (XactCtl->shared->group_lsn[lsnindex] < lsn)
628  XactCtl->shared->group_lsn[lsnindex] = lsn;
629  }
630 }
631 
632 /*
633  * Interrogate the state of a transaction in the commit log.
634  *
635  * Aside from the actual commit status, this function returns (into *lsn)
636  * an LSN that is late enough to be able to guarantee that if we flush up to
637  * that LSN then we will have flushed the transaction's commit record to disk.
638  * The result is not necessarily the exact LSN of the transaction's commit
639  * record! For example, for long-past transactions (those whose clog pages
640  * already migrated to disk), we'll return InvalidXLogRecPtr. Also, because
641  * we group transactions on the same clog page to conserve storage, we might
642  * return the LSN of a later transaction that falls into the same group.
643  *
644  * NB: this is a low-level routine and is NOT the preferred entry point
645  * for most uses; TransactionLogFetch() in transam.c is the intended caller.
646  */
647 XidStatus
649 {
650  int64 pageno = TransactionIdToPage(xid);
651  int byteno = TransactionIdToByte(xid);
652  int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
653  int slotno;
654  int lsnindex;
655  char *byteptr;
656  XidStatus status;
657 
658  /* lock is acquired by SimpleLruReadPage_ReadOnly */
659 
660  slotno = SimpleLruReadPage_ReadOnly(XactCtl, pageno, xid);
661  byteptr = XactCtl->shared->page_buffer[slotno] + byteno;
662 
663  status = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
664 
665  lsnindex = GetLSNIndex(slotno, xid);
666  *lsn = XactCtl->shared->group_lsn[lsnindex];
667 
668  LWLockRelease(XactSLRULock);
669 
670  return status;
671 }
672 
673 /*
674  * Number of shared CLOG buffers.
675  *
676  * On larger multi-processor systems, it is possible to have many CLOG page
677  * requests in flight at one time which could lead to disk access for CLOG
678  * page if the required page is not found in memory. Testing revealed that we
679  * can get the best performance by having 128 CLOG buffers, more than that it
680  * doesn't improve performance.
681  *
682  * Unconditionally keeping the number of CLOG buffers to 128 did not seem like
683  * a good idea, because it would increase the minimum amount of shared memory
684  * required to start, which could be a problem for people running very small
685  * configurations. The following formula seems to represent a reasonable
686  * compromise: people with very low values for shared_buffers will get fewer
687  * CLOG buffers as well, and everyone else will get 128.
688  */
689 Size
691 {
692  return Min(128, Max(4, NBuffers / 512));
693 }
694 
695 /*
696  * Initialization of shared memory for CLOG
697  */
698 Size
700 {
702 }
703 
704 void
706 {
707  XactCtl->PagePrecedes = CLOGPagePrecedes;
709  XactSLRULock, "pg_xact", LWTRANCHE_XACT_BUFFER,
710  SYNC_HANDLER_CLOG, false);
712 }
713 
714 /*
715  * This func must be called ONCE on system install. It creates
716  * the initial CLOG segment. (The CLOG directory is assumed to
717  * have been created by initdb, and CLOGShmemInit must have been
718  * called already.)
719  */
720 void
722 {
723  int slotno;
724 
725  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
726 
727  /* Create and zero the first page of the commit log */
728  slotno = ZeroCLOGPage(0, false);
729 
730  /* Make sure it's written out */
731  SimpleLruWritePage(XactCtl, slotno);
732  Assert(!XactCtl->shared->page_dirty[slotno]);
733 
734  LWLockRelease(XactSLRULock);
735 }
736 
737 /*
738  * Initialize (or reinitialize) a page of CLOG to zeroes.
739  * If writeXlog is true, also emit an XLOG record saying we did this.
740  *
741  * The page is not actually written, just set up in shared memory.
742  * The slot number of the new page is returned.
743  *
744  * Control lock must be held at entry, and will be held at exit.
745  */
746 static int
747 ZeroCLOGPage(int64 pageno, bool writeXlog)
748 {
749  int slotno;
750 
751  slotno = SimpleLruZeroPage(XactCtl, pageno);
752 
753  if (writeXlog)
754  WriteZeroPageXlogRec(pageno);
755 
756  return slotno;
757 }
758 
759 /*
760  * This must be called ONCE during postmaster or standalone-backend startup,
761  * after StartupXLOG has initialized ShmemVariableCache->nextXid.
762  */
763 void
765 {
767  int64 pageno = TransactionIdToPage(xid);
768 
769  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
770 
771  /*
772  * Initialize our idea of the latest page number.
773  */
774  XactCtl->shared->latest_page_number = pageno;
775 
776  LWLockRelease(XactSLRULock);
777 }
778 
779 /*
780  * This must be called ONCE at the end of startup/recovery.
781  */
782 void
783 TrimCLOG(void)
784 {
786  int64 pageno = TransactionIdToPage(xid);
787 
788  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
789 
790  /*
791  * Zero out the remainder of the current clog page. Under normal
792  * circumstances it should be zeroes already, but it seems at least
793  * theoretically possible that XLOG replay will have settled on a nextXID
794  * value that is less than the last XID actually used and marked by the
795  * previous database lifecycle (since subtransaction commit writes clog
796  * but makes no WAL entry). Let's just be safe. (We need not worry about
797  * pages beyond the current one, since those will be zeroed when first
798  * used. For the same reason, there is no need to do anything when
799  * nextXid is exactly at a page boundary; and it's likely that the
800  * "current" page doesn't exist yet in that case.)
801  */
802  if (TransactionIdToPgIndex(xid) != 0)
803  {
804  int byteno = TransactionIdToByte(xid);
805  int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
806  int slotno;
807  char *byteptr;
808 
809  slotno = SimpleLruReadPage(XactCtl, pageno, false, xid);
810  byteptr = XactCtl->shared->page_buffer[slotno] + byteno;
811 
812  /* Zero so-far-unused positions in the current byte */
813  *byteptr &= (1 << bshift) - 1;
814  /* Zero the rest of the page */
815  MemSet(byteptr + 1, 0, BLCKSZ - byteno - 1);
816 
817  XactCtl->shared->page_dirty[slotno] = true;
818  }
819 
820  LWLockRelease(XactSLRULock);
821 }
822 
823 /*
824  * Perform a checkpoint --- either during shutdown, or on-the-fly
825  */
826 void
828 {
829  /*
830  * Write dirty CLOG pages to disk. This may result in sync requests
831  * queued for later handling by ProcessSyncRequests(), as part of the
832  * checkpoint.
833  */
834  TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
835  SimpleLruWriteAll(XactCtl, true);
836  TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
837 }
838 
839 
840 /*
841  * Make sure that CLOG has room for a newly-allocated XID.
842  *
843  * NB: this is called while holding XidGenLock. We want it to be very fast
844  * most of the time; even when it's not so fast, no actual I/O need happen
845  * unless we're forced to write out a dirty clog or xlog page to make room
846  * in shared memory.
847  */
848 void
850 {
851  int64 pageno;
852 
853  /*
854  * No work except at first XID of a page. But beware: just after
855  * wraparound, the first XID of page zero is FirstNormalTransactionId.
856  */
857  if (TransactionIdToPgIndex(newestXact) != 0 &&
859  return;
860 
861  pageno = TransactionIdToPage(newestXact);
862 
863  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
864 
865  /* Zero the page and make an XLOG entry about it */
866  ZeroCLOGPage(pageno, true);
867 
868  LWLockRelease(XactSLRULock);
869 }
870 
871 
872 /*
873  * Remove all CLOG segments before the one holding the passed transaction ID
874  *
875  * Before removing any CLOG data, we must flush XLOG to disk, to ensure
876  * that any recently-emitted FREEZE_PAGE records have reached disk; otherwise
877  * a crash and restart might leave us with some unfrozen tuples referencing
878  * removed CLOG data. We choose to emit a special TRUNCATE XLOG record too.
879  * Replaying the deletion from XLOG is not critical, since the files could
880  * just as well be removed later, but doing so prevents a long-running hot
881  * standby server from acquiring an unreasonably bloated CLOG directory.
882  *
883  * Since CLOG segments hold a large number of transactions, the opportunity to
884  * actually remove a segment is fairly rare, and so it seems best not to do
885  * the XLOG flush unless we have confirmed that there is a removable segment.
886  */
887 void
888 TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
889 {
890  int64 cutoffPage;
891 
892  /*
893  * The cutoff point is the start of the segment containing oldestXact. We
894  * pass the *page* containing oldestXact to SimpleLruTruncate.
895  */
896  cutoffPage = TransactionIdToPage(oldestXact);
897 
898  /* Check to see if there's any files that could be removed */
900  return; /* nothing to remove */
901 
902  /*
903  * Advance oldestClogXid before truncating clog, so concurrent xact status
904  * lookups can ensure they don't attempt to access truncated-away clog.
905  *
906  * It's only necessary to do this if we will actually truncate away clog
907  * pages.
908  */
909  AdvanceOldestClogXid(oldestXact);
910 
911  /*
912  * Write XLOG record and flush XLOG to disk. We record the oldest xid
913  * we're keeping information about here so we can ensure that it's always
914  * ahead of clog truncation in case we crash, and so a standby finds out
915  * the new valid xid before the next checkpoint.
916  */
917  WriteTruncateXlogRec(cutoffPage, oldestXact, oldestxid_datoid);
918 
919  /* Now we can remove the old CLOG segment(s) */
920  SimpleLruTruncate(XactCtl, cutoffPage);
921 }
922 
923 
924 /*
925  * Decide whether a CLOG page number is "older" for truncation purposes.
926  *
927  * We need to use comparison of TransactionIds here in order to do the right
928  * thing with wraparound XID arithmetic. However, TransactionIdPrecedes()
929  * would get weird about permanent xact IDs. So, offset both such that xid1,
930  * xid2, and xid2 + CLOG_XACTS_PER_PAGE - 1 are all normal XIDs; this offset
931  * is relevant to page 0 and to the page preceding page 0.
932  *
933  * The page containing oldestXact-2^31 is the important edge case. The
934  * portion of that page equaling or following oldestXact-2^31 is expendable,
935  * but the portion preceding oldestXact-2^31 is not. When oldestXact-2^31 is
936  * the first XID of a page and segment, the entire page and segment is
937  * expendable, and we could truncate the segment. Recognizing that case would
938  * require making oldestXact, not just the page containing oldestXact,
939  * available to this callback. The benefit would be rare and small, so we
940  * don't optimize that edge case.
941  */
942 static bool
943 CLOGPagePrecedes(int64 page1, int64 page2)
944 {
945  TransactionId xid1;
946  TransactionId xid2;
947 
948  xid1 = ((TransactionId) page1) * CLOG_XACTS_PER_PAGE;
949  xid1 += FirstNormalTransactionId + 1;
950  xid2 = ((TransactionId) page2) * CLOG_XACTS_PER_PAGE;
951  xid2 += FirstNormalTransactionId + 1;
952 
953  return (TransactionIdPrecedes(xid1, xid2) &&
954  TransactionIdPrecedes(xid1, xid2 + CLOG_XACTS_PER_PAGE - 1));
955 }
956 
957 
958 /*
959  * Write a ZEROPAGE xlog record
960  */
961 static void
962 WriteZeroPageXlogRec(int64 pageno)
963 {
964  XLogBeginInsert();
965  XLogRegisterData((char *) (&pageno), sizeof(pageno));
966  (void) XLogInsert(RM_CLOG_ID, CLOG_ZEROPAGE);
967 }
968 
969 /*
970  * Write a TRUNCATE xlog record
971  *
972  * We must flush the xlog record to disk before returning --- see notes
973  * in TruncateCLOG().
974  */
975 static void
976 WriteTruncateXlogRec(int64 pageno, TransactionId oldestXact, Oid oldestXactDb)
977 {
978  XLogRecPtr recptr;
979  xl_clog_truncate xlrec;
980 
981  xlrec.pageno = pageno;
982  xlrec.oldestXact = oldestXact;
983  xlrec.oldestXactDb = oldestXactDb;
984 
985  XLogBeginInsert();
986  XLogRegisterData((char *) (&xlrec), sizeof(xl_clog_truncate));
987  recptr = XLogInsert(RM_CLOG_ID, CLOG_TRUNCATE);
988  XLogFlush(recptr);
989 }
990 
991 /*
992  * CLOG resource manager's routines
993  */
994 void
996 {
997  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
998 
999  /* Backup blocks are not used in clog records */
1000  Assert(!XLogRecHasAnyBlockRefs(record));
1001 
1002  if (info == CLOG_ZEROPAGE)
1003  {
1004  int64 pageno;
1005  int slotno;
1006 
1007  memcpy(&pageno, XLogRecGetData(record), sizeof(pageno));
1008 
1009  LWLockAcquire(XactSLRULock, LW_EXCLUSIVE);
1010 
1011  slotno = ZeroCLOGPage(pageno, false);
1012  SimpleLruWritePage(XactCtl, slotno);
1013  Assert(!XactCtl->shared->page_dirty[slotno]);
1014 
1015  LWLockRelease(XactSLRULock);
1016  }
1017  else if (info == CLOG_TRUNCATE)
1018  {
1019  xl_clog_truncate xlrec;
1020 
1021  memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_clog_truncate));
1022 
1024 
1026  }
1027  else
1028  elog(PANIC, "clog_redo: unknown op code %u", info);
1029 }
1030 
1031 /*
1032  * Entrypoint for sync.c to sync clog files.
1033  */
1034 int
1035 clogsyncfiletag(const FileTag *ftag, char *path)
1036 {
1037  return SlruSyncFileTag(XactCtl, ftag, path);
1038 }
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:306
#define pg_write_barrier()
Definition: atomics.h:154
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:253
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:236
static uint32 pg_atomic_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 newval)
Definition: atomics.h:287
unsigned int uint32
Definition: c.h:495
#define Min(x, y)
Definition: c.h:993
#define Max(x, y)
Definition: c.h:987
unsigned char uint8
Definition: c.h:493
#define MemSet(start, val, len)
Definition: c.h:1009
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:925
uint32 TransactionId
Definition: c.h:641
size_t Size
Definition: c.h:594
static void WriteZeroPageXlogRec(int64 pageno)
Definition: clog.c:962
static int ZeroCLOGPage(int64 pageno, bool writeXlog)
Definition: clog.c:747
#define CLOG_XACT_BITMASK
Definition: clog.c:63
#define CLOG_XACTS_PER_PAGE
Definition: clog.c:62
#define THRESHOLD_SUBTRANS_CLOG_OPT
Definition: clog.c:92
static void TransactionIdSetStatusBit(TransactionId xid, XidStatus status, XLogRecPtr lsn, int slotno)
Definition: clog.c:579
XidStatus TransactionIdGetStatus(TransactionId xid, XLogRecPtr *lsn)
Definition: clog.c:648
void TransactionIdSetTreeStatus(TransactionId xid, int nsubxids, TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
Definition: clog.c:172
void CLOGShmemInit(void)
Definition: clog.c:705
#define TransactionIdToBIndex(xid)
Definition: clog.c:78
Size CLOGShmemBuffers(void)
Definition: clog.c:690
void ExtendCLOG(TransactionId newestXact)
Definition: clog.c:849
void clog_redo(XLogReaderState *record)
Definition: clog.c:995
static bool CLOGPagePrecedes(int64 page1, int64 page2)
Definition: clog.c:943
void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
Definition: clog.c:888
Size CLOGShmemSize(void)
Definition: clog.c:699
static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids, TransactionId *subxids, XidStatus status, XLogRecPtr lsn, int64 pageno, bool all_xact_same_page)
Definition: clog.c:282
int clogsyncfiletag(const FileTag *ftag, char *path)
Definition: clog.c:1035
void BootStrapCLOG(void)
Definition: clog.c:721
#define CLOG_BITS_PER_XACT
Definition: clog.c:60
#define CLOG_LSNS_PER_PAGE
Definition: clog.c:82
static int64 TransactionIdToPage(TransactionId xid)
Definition: clog.c:71
#define TransactionIdToByte(xid)
Definition: clog.c:77
#define TransactionIdToPgIndex(xid)
Definition: clog.c:76
void StartupCLOG(void)
Definition: clog.c:764
static void set_status_by_pages(int nsubxids, TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
Definition: clog.c:246
static bool TransactionGroupUpdateXidStatus(TransactionId xid, XidStatus status, XLogRecPtr lsn, int64 pageno)
Definition: clog.c:423
static void TransactionIdSetPageStatusInternal(TransactionId xid, int nsubxids, TransactionId *subxids, XidStatus status, XLogRecPtr lsn, int64 pageno)
Definition: clog.c:348
#define GetLSNIndex(slotno, xid)
Definition: clog.c:84
void CheckPointCLOG(void)
Definition: clog.c:827
static SlruCtlData XactCtlData
Definition: clog.c:97
#define XactCtl
Definition: clog.c:99
void TrimCLOG(void)
Definition: clog.c:783
static void WriteTruncateXlogRec(int64 pageno, TransactionId oldestXact, Oid oldestXactDb)
Definition: clog.c:976
#define TRANSACTION_STATUS_IN_PROGRESS
Definition: clog.h:27
int XidStatus
Definition: clog.h:25
#define CLOG_ZEROPAGE
Definition: clog.h:56
#define TRANSACTION_STATUS_ABORTED
Definition: clog.h:29
#define TRANSACTION_STATUS_SUB_COMMITTED
Definition: clog.h:30
#define CLOG_TRUNCATE
Definition: clog.h:57
#define TRANSACTION_STATUS_COMMITTED
Definition: clog.h:28
#define PANIC
Definition: elog.h:42
int NBuffers
Definition: globals.c:138
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1964
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1366
@ LWTRANCHE_XACT_BUFFER
Definition: lwlock.h:181
@ LW_EXCLUSIVE
Definition: lwlock.h:116
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
unsigned int Oid
Definition: postgres_ext.h:31
#define INVALID_PGPROCNO
Definition: proc.h:85
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:38
int SimpleLruReadPage_ReadOnly(SlruCtl ctl, int64 pageno, TransactionId xid)
Definition: slru.c:523
void SimpleLruWritePage(SlruCtl ctl, int slotno)
Definition: slru.c:642
void SimpleLruWriteAll(SlruCtl ctl, bool allow_redirtied)
Definition: slru.c:1184
void SimpleLruInit(SlruCtl ctl, const char *name, int nslots, int nlsns, LWLock *ctllock, const char *subdir, int tranche_id, SyncRequestHandler sync_handler, bool long_segment_names)
Definition: slru.c:214
bool SlruScanDirectory(SlruCtl ctl, SlruScanCallback callback, void *data)
Definition: slru.c:1607
int SimpleLruReadPage(SlruCtl ctl, int64 pageno, bool write_ok, TransactionId xid)
Definition: slru.c:423
int SlruSyncFileTag(SlruCtl ctl, const FileTag *ftag, char *path)
Definition: slru.c:1647
int SimpleLruZeroPage(SlruCtl ctl, int64 pageno)
Definition: slru.c:308
void SimpleLruTruncate(SlruCtl ctl, int64 cutoffPage)
Definition: slru.c:1254
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition: slru.c:182
bool SlruScanDirCbReportPresence(SlruCtl ctl, char *filename, int64 segpage, void *data)
Definition: slru.c:1528
#define SlruPagePrecedesUnitTests(ctl, per_page)
Definition: slru.h:165
PGPROC * MyProc
Definition: proc.c:66
PROC_HDR * ProcGlobal
Definition: proc.c:78
Definition: sync.h:51
Definition: proc.h:162
XLogRecPtr clogGroupMemberLsn
Definition: proc.h:280
TransactionId clogGroupMemberXid
Definition: proc.h:275
int64 clogGroupMemberPage
Definition: proc.h:278
bool clogGroupMember
Definition: proc.h:273
pg_atomic_uint32 clogGroupNext
Definition: proc.h:274
XidStatus clogGroupMemberXidStatus
Definition: proc.h:276
XidCacheStatus subxidStatus
Definition: proc.h:254
TransactionId xid
Definition: proc.h:173
int pgprocno
Definition: proc.h:191
struct XidCache subxids
Definition: proc.h:256
PGSemaphore sem
Definition: proc.h:167
Definition: proc.h:360
PGPROC * allProcs
Definition: proc.h:362
pg_atomic_uint32 clogGroupFirst
Definition: proc.h:392
FullTransactionId nextXid
Definition: transam.h:220
uint8 count
Definition: proc.h:43
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:50
int64 pageno
Definition: clog.h:34
Oid oldestXactDb
Definition: clog.h:36
TransactionId oldestXact
Definition: clog.h:35
@ SYNC_HANDLER_CLOG
Definition: sync.h:38
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define FirstNormalTransactionId
Definition: transam.h:34
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
Definition: varsup.c:328
VariableCache ShmemVariableCache
Definition: varsup.c:34
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2619
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:365
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:475
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:417
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
bool InRecovery
Definition: xlogutils.c:53