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