1 /*-------------------------------------------------------------------------
4 * PostgreSQL transaction-commit-log manager
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.
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.
26 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
27 * Portions Copyright (c) 1994, Regents of the University of California
29 * src/backend/access/transam/clog.c
31 *-------------------------------------------------------------------------
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"
45 * Defines for CLOG page sizes. A page is the same BLCKSZ as is used
46 * everywhere else in Postgres.
48 * Note: because TransactionIds are 32 bits and wrap around at 0xFFFFFFFF,
49 * CLOG page numbering also wraps around at 0xFFFFFFFF/CLOG_XACTS_PER_PAGE,
50 * and CLOG segment numbering at
51 * 0xFFFFFFFF/CLOG_XACTS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need take no
52 * explicit notice of that fact in this module, except when comparing segment
53 * and page numbers in TruncateCLOG (see CLOGPagePrecedes).
56 /* We need two bits per xact, so four xacts fit in a byte */
57 #define CLOG_BITS_PER_XACT 2
58 #define CLOG_XACTS_PER_BYTE 4
59 #define CLOG_XACTS_PER_PAGE (BLCKSZ * CLOG_XACTS_PER_BYTE)
60 #define CLOG_XACT_BITMASK ((1 << CLOG_BITS_PER_XACT) - 1)
62 #define TransactionIdToPage(xid) ((xid) / (TransactionId) CLOG_XACTS_PER_PAGE)
63 #define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE)
64 #define TransactionIdToByte(xid) (TransactionIdToPgIndex(xid) / CLOG_XACTS_PER_BYTE)
65 #define TransactionIdToBIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_BYTE)
67 /* We store the latest async LSN for each group of transactions */
68 #define CLOG_XACTS_PER_LSN_GROUP 32 /* keep this a power of 2 */
69 #define CLOG_LSNS_PER_PAGE (CLOG_XACTS_PER_PAGE / CLOG_XACTS_PER_LSN_GROUP)
71 #define GetLSNIndex(slotno, xid) ((slotno) * CLOG_LSNS_PER_PAGE + \
72 ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
76 * Link to shared-memory data structures for CLOG control
78 static SlruCtlData ClogCtlData;
80 #define ClogCtl (&ClogCtlData)
83 static int ZeroCLOGPage(int pageno, bool writeXlog);
84 static bool CLOGPagePrecedes(int page1, int page2);
85 static void WriteZeroPageXlogRec(int pageno);
86 static void WriteTruncateXlogRec(int pageno);
87 static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
88 TransactionId *subxids, XidStatus status,
89 XLogRecPtr lsn, int pageno);
90 static void TransactionIdSetStatusBit(TransactionId xid, XidStatus status,
91 XLogRecPtr lsn, int slotno);
92 static void set_status_by_pages(int nsubxids, TransactionId *subxids,
93 XidStatus status, XLogRecPtr lsn);
97 * TransactionIdSetTreeStatus
99 * Record the final state of transaction entries in the commit log for
100 * a transaction and its subtransaction tree. Take care to ensure this is
101 * efficient, and as atomic as possible.
103 * xid is a single xid to set status for. This will typically be
104 * the top level transactionid for a top level commit or abort. It can
105 * also be a subtransaction when we record transaction aborts.
107 * subxids is an array of xids of length nsubxids, representing subtransactions
108 * in the tree of xid. In various cases nsubxids may be zero.
110 * lsn must be the WAL location of the commit record when recording an async
111 * commit. For a synchronous commit it can be InvalidXLogRecPtr, since the
112 * caller guarantees the commit record is already flushed in that case. It
113 * should be InvalidXLogRecPtr for abort cases, too.
115 * In the commit case, atomicity is limited by whether all the subxids are in
116 * the same CLOG page as xid. If they all are, then the lock will be grabbed
117 * only once, and the status will be set to committed directly. Otherwise
119 * 1. set sub-committed all subxids that are not on the same page as the
121 * 2. atomically set committed the main xid and the subxids on the same page
122 * 3. go over the first bunch again and set them committed
123 * Note that as far as concurrent checkers are concerned, main transaction
124 * commit as a whole is still atomic.
127 * TransactionId t commits and has subxids t1, t2, t3, t4
128 * t is on page p1, t1 is also on p1, t2 and t3 are on p2, t4 is on p3
129 * 1. update pages2-3:
130 * page2: set t2,t3 as sub-committed
131 * page3: set t4 as sub-committed
133 * set t1 as sub-committed,
134 * then set t as committed,
135 then set t1 as committed
136 * 3. update pages2-3:
137 * page2: set t2,t3 as committed
138 * page3: set t4 as committed
140 * NB: this is a low-level routine and is NOT the preferred entry point
141 * for most uses; functions in transam.c are the intended callers.
143 * XXX Think about issuing FADVISE_WILLNEED on pages that we will need,
144 * but aren't yet in cache, as well as hinting pages not to fall out of
148 TransactionIdSetTreeStatus(TransactionId xid, int nsubxids,
149 TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
151 int pageno = TransactionIdToPage(xid); /* get page of parent */
154 Assert(status == TRANSACTION_STATUS_COMMITTED ||
155 status == TRANSACTION_STATUS_ABORTED);
158 * See how many subxids, if any, are on the same page as the parent, if
161 for (i = 0; i < nsubxids; i++)
163 if (TransactionIdToPage(subxids[i]) != pageno)
168 * Do all items fit on a single page?
173 * Set the parent and all subtransactions in a single call
175 TransactionIdSetPageStatus(xid, nsubxids, subxids, status, lsn,
180 int nsubxids_on_first_page = i;
183 * If this is a commit then we care about doing this correctly (i.e.
184 * using the subcommitted intermediate status). By here, we know
185 * we're updating more than one page of clog, so we must mark entries
186 * that are *not* on the first page so that they show as subcommitted
187 * before we then return to update the status to fully committed.
189 * To avoid touching the first page twice, skip marking subcommitted
190 * for the subxids on that first page.
192 if (status == TRANSACTION_STATUS_COMMITTED)
193 set_status_by_pages(nsubxids - nsubxids_on_first_page,
194 subxids + nsubxids_on_first_page,
195 TRANSACTION_STATUS_SUB_COMMITTED, lsn);
198 * Now set the parent and subtransactions on same page as the parent,
201 pageno = TransactionIdToPage(xid);
202 TransactionIdSetPageStatus(xid, nsubxids_on_first_page, subxids, status,
206 * Now work through the rest of the subxids one clog page at a time,
207 * starting from the second page onwards, like we did above.
209 set_status_by_pages(nsubxids - nsubxids_on_first_page,
210 subxids + nsubxids_on_first_page,
216 * Helper for TransactionIdSetTreeStatus: set the status for a bunch of
217 * transactions, chunking in the separate CLOG pages involved. We never
218 * pass the whole transaction tree to this function, only subtransactions
219 * that are on different pages to the top level transaction id.
222 set_status_by_pages(int nsubxids, TransactionId *subxids,
223 XidStatus status, XLogRecPtr lsn)
225 int pageno = TransactionIdToPage(subxids[0]);
233 while (TransactionIdToPage(subxids[i]) == pageno && i < nsubxids)
239 TransactionIdSetPageStatus(InvalidTransactionId,
240 num_on_page, subxids + offset,
241 status, lsn, pageno);
243 pageno = TransactionIdToPage(subxids[offset]);
248 * Record the final state of transaction entries in the commit log for
249 * all entries on a single page. Atomic only on this page.
251 * Otherwise API is same as TransactionIdSetTreeStatus()
254 TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
255 TransactionId *subxids, XidStatus status,
256 XLogRecPtr lsn, int pageno)
261 Assert(status == TRANSACTION_STATUS_COMMITTED ||
262 status == TRANSACTION_STATUS_ABORTED ||
263 (status == TRANSACTION_STATUS_SUB_COMMITTED && !TransactionIdIsValid(xid)));
265 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
268 * If we're doing an async commit (ie, lsn is valid), then we must wait
269 * for any active write on the page slot to complete. Otherwise our
270 * update could reach disk in that write, which will not do since we
271 * mustn't let it reach disk until we've done the appropriate WAL flush.
272 * But when lsn is invalid, it's OK to scribble on a page while it is
273 * write-busy, since we don't care if the update reaches disk sooner than
276 slotno = SimpleLruReadPage(ClogCtl, pageno, XLogRecPtrIsInvalid(lsn), xid);
279 * Set the main transaction id, if any.
281 * If we update more than one xid on this page while it is being written
282 * out, we might find that some of the bits go to disk and others don't.
283 * If we are updating commits on the page with the top-level xid that
284 * could break atomicity, so we subcommit the subxids first before we mark
285 * the top-level commit.
287 if (TransactionIdIsValid(xid))
289 /* Subtransactions first, if needed ... */
290 if (status == TRANSACTION_STATUS_COMMITTED)
292 for (i = 0; i < nsubxids; i++)
294 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
295 TransactionIdSetStatusBit(subxids[i],
296 TRANSACTION_STATUS_SUB_COMMITTED,
301 /* ... then the main transaction */
302 TransactionIdSetStatusBit(xid, status, lsn, slotno);
305 /* Set the subtransactions */
306 for (i = 0; i < nsubxids; i++)
308 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
309 TransactionIdSetStatusBit(subxids[i], status, lsn, slotno);
312 ClogCtl->shared->page_dirty[slotno] = true;
314 LWLockRelease(CLogControlLock);
318 * Sets the commit status of a single transaction.
320 * Must be called with CLogControlLock held
323 TransactionIdSetStatusBit(TransactionId xid, XidStatus status, XLogRecPtr lsn, int slotno)
325 int byteno = TransactionIdToByte(xid);
326 int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
331 byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
332 curval = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
335 * When replaying transactions during recovery we still need to perform
336 * the two phases of subcommit and then commit. However, some transactions
337 * are already correctly marked, so we just treat those as a no-op which
338 * allows us to keep the following Assert as restrictive as possible.
340 if (InRecovery && status == TRANSACTION_STATUS_SUB_COMMITTED &&
341 curval == TRANSACTION_STATUS_COMMITTED)
345 * Current state change should be from 0 or subcommitted to target state
346 * or we should already be there when replaying changes during recovery.
348 Assert(curval == 0 ||
349 (curval == TRANSACTION_STATUS_SUB_COMMITTED &&
350 status != TRANSACTION_STATUS_IN_PROGRESS) ||
353 /* note this assumes exclusive access to the clog page */
355 byteval &= ~(((1 << CLOG_BITS_PER_XACT) - 1) << bshift);
356 byteval |= (status << bshift);
360 * Update the group LSN if the transaction completion LSN is higher.
362 * Note: lsn will be invalid when supplied during InRecovery processing,
363 * so we don't need to do anything special to avoid LSN updates during
364 * recovery. After recovery completes the next clog change will set the
367 if (!XLogRecPtrIsInvalid(lsn))
369 int lsnindex = GetLSNIndex(slotno, xid);
371 if (ClogCtl->shared->group_lsn[lsnindex] < lsn)
372 ClogCtl->shared->group_lsn[lsnindex] = lsn;
377 * Interrogate the state of a transaction in the commit log.
379 * Aside from the actual commit status, this function returns (into *lsn)
380 * an LSN that is late enough to be able to guarantee that if we flush up to
381 * that LSN then we will have flushed the transaction's commit record to disk.
382 * The result is not necessarily the exact LSN of the transaction's commit
383 * record! For example, for long-past transactions (those whose clog pages
384 * already migrated to disk), we'll return InvalidXLogRecPtr. Also, because
385 * we group transactions on the same clog page to conserve storage, we might
386 * return the LSN of a later transaction that falls into the same group.
388 * NB: this is a low-level routine and is NOT the preferred entry point
389 * for most uses; TransactionLogFetch() in transam.c is the intended caller.
392 TransactionIdGetStatus(TransactionId xid, XLogRecPtr *lsn)
394 int pageno = TransactionIdToPage(xid);
395 int byteno = TransactionIdToByte(xid);
396 int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
402 /* lock is acquired by SimpleLruReadPage_ReadOnly */
404 slotno = SimpleLruReadPage_ReadOnly(ClogCtl, pageno, xid);
405 byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
407 status = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
409 lsnindex = GetLSNIndex(slotno, xid);
410 *lsn = ClogCtl->shared->group_lsn[lsnindex];
412 LWLockRelease(CLogControlLock);
418 * Number of shared CLOG buffers.
420 * On larger multi-processor systems, it is possible to have many CLOG page
421 * requests in flight at one time which could lead to disk access for CLOG
422 * page if the required page is not found in memory. Testing revealed that we
423 * can get the best performance by having 128 CLOG buffers, more than that it
424 * doesn't improve performance.
426 * Unconditionally keeping the number of CLOG buffers to 128 did not seem like
427 * a good idea, because it would increase the minimum amount of shared memory
428 * required to start, which could be a problem for people running very small
429 * configurations. The following formula seems to represent a reasonable
430 * compromise: people with very low values for shared_buffers will get fewer
431 * CLOG buffers as well, and everyone else will get 128.
434 CLOGShmemBuffers(void)
436 return Min(128, Max(4, NBuffers / 512));
440 * Initialization of shared memory for CLOG
445 return SimpleLruShmemSize(CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE);
451 ClogCtl->PagePrecedes = CLOGPagePrecedes;
452 SimpleLruInit(ClogCtl, "clog", CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE,
453 CLogControlLock, "pg_clog", LWTRANCHE_CLOG_BUFFERS);
457 * This func must be called ONCE on system install. It creates
458 * the initial CLOG segment. (The CLOG directory is assumed to
459 * have been created by initdb, and CLOGShmemInit must have been
467 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
469 /* Create and zero the first page of the commit log */
470 slotno = ZeroCLOGPage(0, false);
472 /* Make sure it's written out */
473 SimpleLruWritePage(ClogCtl, slotno);
474 Assert(!ClogCtl->shared->page_dirty[slotno]);
476 LWLockRelease(CLogControlLock);
480 * Initialize (or reinitialize) a page of CLOG to zeroes.
481 * If writeXlog is TRUE, also emit an XLOG record saying we did this.
483 * The page is not actually written, just set up in shared memory.
484 * The slot number of the new page is returned.
486 * Control lock must be held at entry, and will be held at exit.
489 ZeroCLOGPage(int pageno, bool writeXlog)
493 slotno = SimpleLruZeroPage(ClogCtl, pageno);
496 WriteZeroPageXlogRec(pageno);
502 * This must be called ONCE during postmaster or standalone-backend startup,
503 * after StartupXLOG has initialized ShmemVariableCache->nextXid.
508 TransactionId xid = ShmemVariableCache->nextXid;
509 int pageno = TransactionIdToPage(xid);
511 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
514 * Initialize our idea of the latest page number.
516 ClogCtl->shared->latest_page_number = pageno;
518 LWLockRelease(CLogControlLock);
522 * This must be called ONCE at the end of startup/recovery.
527 TransactionId xid = ShmemVariableCache->nextXid;
528 int pageno = TransactionIdToPage(xid);
530 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
533 * Re-Initialize our idea of the latest page number.
535 ClogCtl->shared->latest_page_number = pageno;
538 * Zero out the remainder of the current clog page. Under normal
539 * circumstances it should be zeroes already, but it seems at least
540 * theoretically possible that XLOG replay will have settled on a nextXID
541 * value that is less than the last XID actually used and marked by the
542 * previous database lifecycle (since subtransaction commit writes clog
543 * but makes no WAL entry). Let's just be safe. (We need not worry about
544 * pages beyond the current one, since those will be zeroed when first
545 * used. For the same reason, there is no need to do anything when
546 * nextXid is exactly at a page boundary; and it's likely that the
547 * "current" page doesn't exist yet in that case.)
549 if (TransactionIdToPgIndex(xid) != 0)
551 int byteno = TransactionIdToByte(xid);
552 int bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
556 slotno = SimpleLruReadPage(ClogCtl, pageno, false, xid);
557 byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
559 /* Zero so-far-unused positions in the current byte */
560 *byteptr &= (1 << bshift) - 1;
561 /* Zero the rest of the page */
562 MemSet(byteptr + 1, 0, BLCKSZ - byteno - 1);
564 ClogCtl->shared->page_dirty[slotno] = true;
567 LWLockRelease(CLogControlLock);
571 * This must be called ONCE during postmaster or standalone-backend shutdown
576 /* Flush dirty CLOG pages to disk */
577 TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(false);
578 SimpleLruFlush(ClogCtl, false);
579 TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(false);
583 * Perform a checkpoint --- either during shutdown, or on-the-fly
588 /* Flush dirty CLOG pages to disk */
589 TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
590 SimpleLruFlush(ClogCtl, true);
591 TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
596 * Make sure that CLOG has room for a newly-allocated XID.
598 * NB: this is called while holding XidGenLock. We want it to be very fast
599 * most of the time; even when it's not so fast, no actual I/O need happen
600 * unless we're forced to write out a dirty clog or xlog page to make room
604 ExtendCLOG(TransactionId newestXact)
609 * No work except at first XID of a page. But beware: just after
610 * wraparound, the first XID of page zero is FirstNormalTransactionId.
612 if (TransactionIdToPgIndex(newestXact) != 0 &&
613 !TransactionIdEquals(newestXact, FirstNormalTransactionId))
616 pageno = TransactionIdToPage(newestXact);
618 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
620 /* Zero the page and make an XLOG entry about it */
621 ZeroCLOGPage(pageno, true);
623 LWLockRelease(CLogControlLock);
628 * Remove all CLOG segments before the one holding the passed transaction ID
630 * Before removing any CLOG data, we must flush XLOG to disk, to ensure
631 * that any recently-emitted HEAP_FREEZE records have reached disk; otherwise
632 * a crash and restart might leave us with some unfrozen tuples referencing
633 * removed CLOG data. We choose to emit a special TRUNCATE XLOG record too.
634 * Replaying the deletion from XLOG is not critical, since the files could
635 * just as well be removed later, but doing so prevents a long-running hot
636 * standby server from acquiring an unreasonably bloated CLOG directory.
638 * Since CLOG segments hold a large number of transactions, the opportunity to
639 * actually remove a segment is fairly rare, and so it seems best not to do
640 * the XLOG flush unless we have confirmed that there is a removable segment.
643 TruncateCLOG(TransactionId oldestXact)
648 * The cutoff point is the start of the segment containing oldestXact. We
649 * pass the *page* containing oldestXact to SimpleLruTruncate.
651 cutoffPage = TransactionIdToPage(oldestXact);
653 /* Check to see if there's any files that could be removed */
654 if (!SlruScanDirectory(ClogCtl, SlruScanDirCbReportPresence, &cutoffPage))
655 return; /* nothing to remove */
657 /* Write XLOG record and flush XLOG to disk */
658 WriteTruncateXlogRec(cutoffPage);
660 /* Now we can remove the old CLOG segment(s) */
661 SimpleLruTruncate(ClogCtl, cutoffPage);
666 * Decide which of two CLOG page numbers is "older" for truncation purposes.
668 * We need to use comparison of TransactionIds here in order to do the right
669 * thing with wraparound XID arithmetic. However, if we are asked about
670 * page number zero, we don't want to hand InvalidTransactionId to
671 * TransactionIdPrecedes: it'll get weird about permanent xact IDs. So,
672 * offset both xids by FirstNormalTransactionId to avoid that.
675 CLOGPagePrecedes(int page1, int page2)
680 xid1 = ((TransactionId) page1) * CLOG_XACTS_PER_PAGE;
681 xid1 += FirstNormalTransactionId;
682 xid2 = ((TransactionId) page2) * CLOG_XACTS_PER_PAGE;
683 xid2 += FirstNormalTransactionId;
685 return TransactionIdPrecedes(xid1, xid2);
690 * Write a ZEROPAGE xlog record
693 WriteZeroPageXlogRec(int pageno)
696 XLogRegisterData((char *) (&pageno), sizeof(int));
697 (void) XLogInsert(RM_CLOG_ID, CLOG_ZEROPAGE);
701 * Write a TRUNCATE xlog record
703 * We must flush the xlog record to disk before returning --- see notes
707 WriteTruncateXlogRec(int pageno)
712 XLogRegisterData((char *) (&pageno), sizeof(int));
713 recptr = XLogInsert(RM_CLOG_ID, CLOG_TRUNCATE);
718 * CLOG resource manager's routines
721 clog_redo(XLogReaderState *record)
723 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
725 /* Backup blocks are not used in clog records */
726 Assert(!XLogRecHasAnyBlockRefs(record));
728 if (info == CLOG_ZEROPAGE)
733 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
735 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
737 slotno = ZeroCLOGPage(pageno, false);
738 SimpleLruWritePage(ClogCtl, slotno);
739 Assert(!ClogCtl->shared->page_dirty[slotno]);
741 LWLockRelease(CLogControlLock);
743 else if (info == CLOG_TRUNCATE)
747 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
750 * During XLOG replay, latest_page_number isn't set up yet; insert a
751 * suitable value to bypass the sanity test in SimpleLruTruncate.
753 ClogCtl->shared->latest_page_number = pageno;
755 SimpleLruTruncate(ClogCtl, pageno);
758 elog(PANIC, "clog_redo: unknown op code %u", info);