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-2023, 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"
44 #include "storage/proc.h"
45 #include "storage/sync.h"
48 * Defines for CLOG page sizes. A page is the same BLCKSZ as is used
49 * everywhere else in Postgres.
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).
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)
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)
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)
74 #define GetLSNIndex(slotno, xid) ((slotno) * CLOG_LSNS_PER_PAGE + \
75 ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
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
82 #define THRESHOLD_SUBTRANS_CLOG_OPT 5
85 * Link to shared-memory data structures for CLOG control
87 static SlruCtlData XactCtlData
;
89 #define XactCtl (&XactCtlData)
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
,
97 static void TransactionIdSetPageStatus(TransactionId xid
, int nsubxids
,
98 TransactionId
*subxids
, XidStatus status
,
99 XLogRecPtr lsn
, int pageno
,
100 bool all_xact_same_page
);
101 static void TransactionIdSetStatusBit(TransactionId xid
, XidStatus status
,
102 XLogRecPtr lsn
, int slotno
);
103 static void set_status_by_pages(int nsubxids
, TransactionId
*subxids
,
104 XidStatus status
, XLogRecPtr lsn
);
105 static bool TransactionGroupUpdateXidStatus(TransactionId xid
,
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
);
113 * TransactionIdSetTreeStatus
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.
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.
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.
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.
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
135 * 1. set sub-committed all subxids that are not on the same page as the
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.
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
149 * page1: set t,t1 as committed
150 * 3. update pages2-3:
151 * page2: set t2,t3 as committed
152 * page3: set t4 as committed
154 * NB: this is a low-level routine and is NOT the preferred entry point
155 * for most uses; functions in transam.c are the intended callers.
157 * XXX Think about issuing POSIX_FADV_WILLNEED on pages that we will need,
158 * but aren't yet in cache, as well as hinting pages not to fall out of
162 TransactionIdSetTreeStatus(TransactionId xid
, int nsubxids
,
163 TransactionId
*subxids
, XidStatus status
, XLogRecPtr lsn
)
165 int pageno
= TransactionIdToPage(xid
); /* get page of parent */
168 Assert(status
== TRANSACTION_STATUS_COMMITTED
||
169 status
== TRANSACTION_STATUS_ABORTED
);
172 * See how many subxids, if any, are on the same page as the parent, if
175 for (i
= 0; i
< nsubxids
; i
++)
177 if (TransactionIdToPage(subxids
[i
]) != pageno
)
182 * Do all items fit on a single page?
187 * Set the parent and all subtransactions in a single call
189 TransactionIdSetPageStatus(xid
, nsubxids
, subxids
, status
, lsn
,
194 int nsubxids_on_first_page
= i
;
197 * If this is a commit then we care about doing this correctly (i.e.
198 * using the subcommitted intermediate status). By here, we know
199 * we're updating more than one page of clog, so we must mark entries
200 * that are *not* on the first page so that they show as subcommitted
201 * before we then return to update the status to fully committed.
203 * To avoid touching the first page twice, skip marking subcommitted
204 * for the subxids on that first page.
206 if (status
== TRANSACTION_STATUS_COMMITTED
)
207 set_status_by_pages(nsubxids
- nsubxids_on_first_page
,
208 subxids
+ nsubxids_on_first_page
,
209 TRANSACTION_STATUS_SUB_COMMITTED
, lsn
);
212 * Now set the parent and subtransactions on same page as the parent,
215 pageno
= TransactionIdToPage(xid
);
216 TransactionIdSetPageStatus(xid
, nsubxids_on_first_page
, subxids
, status
,
220 * Now work through the rest of the subxids one clog page at a time,
221 * starting from the second page onwards, like we did above.
223 set_status_by_pages(nsubxids
- nsubxids_on_first_page
,
224 subxids
+ nsubxids_on_first_page
,
230 * Helper for TransactionIdSetTreeStatus: set the status for a bunch of
231 * transactions, chunking in the separate CLOG pages involved. We never
232 * pass the whole transaction tree to this function, only subtransactions
233 * that are on different pages to the top level transaction id.
236 set_status_by_pages(int nsubxids
, TransactionId
*subxids
,
237 XidStatus status
, XLogRecPtr lsn
)
239 int pageno
= TransactionIdToPage(subxids
[0]);
243 Assert(nsubxids
> 0); /* else the pageno fetch above is unsafe */
252 nextpageno
= TransactionIdToPage(subxids
[i
]);
253 if (nextpageno
!= pageno
)
257 } while (i
< nsubxids
);
259 TransactionIdSetPageStatus(InvalidTransactionId
,
260 num_on_page
, subxids
+ offset
,
261 status
, lsn
, pageno
, false);
268 * Record the final state of transaction entries in the commit log for all
269 * entries on a single page. Atomic only on this page.
272 TransactionIdSetPageStatus(TransactionId xid
, int nsubxids
,
273 TransactionId
*subxids
, XidStatus status
,
274 XLogRecPtr lsn
, int pageno
,
275 bool all_xact_same_page
)
277 /* Can't use group update when PGPROC overflows. */
278 StaticAssertDecl(THRESHOLD_SUBTRANS_CLOG_OPT
<= PGPROC_MAX_CACHED_SUBXIDS
,
279 "group clog threshold less than PGPROC cached subxids");
282 * When there is contention on XactSLRULock, we try to group multiple
283 * updates; a single leader process will perform transaction status
284 * updates for multiple backends so that the number of times XactSLRULock
285 * needs to be acquired is reduced.
287 * For this optimization to be safe, the XID and subxids in MyProc must be
288 * the same as the ones for which we're setting the status. Check that
291 * For this optimization to be efficient, we shouldn't have too many
292 * sub-XIDs and all of the XIDs for which we're adjusting clog should be
293 * on the same page. Check those conditions, too.
295 if (all_xact_same_page
&& xid
== MyProc
->xid
&&
296 nsubxids
<= THRESHOLD_SUBTRANS_CLOG_OPT
&&
297 nsubxids
== MyProc
->subxidStatus
.count
&&
299 memcmp(subxids
, MyProc
->subxids
.xids
,
300 nsubxids
* sizeof(TransactionId
)) == 0))
303 * If we can immediately acquire XactSLRULock, we update the status of
304 * our own XID and release the lock. If not, try use group XID
305 * update. If that doesn't work out, fall back to waiting for the
306 * lock to perform an update for this transaction only.
308 if (LWLockConditionalAcquire(XactSLRULock
, LW_EXCLUSIVE
))
310 /* Got the lock without waiting! Do the update. */
311 TransactionIdSetPageStatusInternal(xid
, nsubxids
, subxids
, status
,
313 LWLockRelease(XactSLRULock
);
316 else if (TransactionGroupUpdateXidStatus(xid
, status
, lsn
, pageno
))
318 /* Group update mechanism has done the work. */
322 /* Fall through only if update isn't done yet. */
325 /* Group update not applicable, or couldn't accept this page number. */
326 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
327 TransactionIdSetPageStatusInternal(xid
, nsubxids
, subxids
, status
,
329 LWLockRelease(XactSLRULock
);
333 * Record the final state of transaction entry in the commit log
335 * We don't do any locking here; caller must handle that.
338 TransactionIdSetPageStatusInternal(TransactionId xid
, int nsubxids
,
339 TransactionId
*subxids
, XidStatus status
,
340 XLogRecPtr lsn
, int pageno
)
345 Assert(status
== TRANSACTION_STATUS_COMMITTED
||
346 status
== TRANSACTION_STATUS_ABORTED
||
347 (status
== TRANSACTION_STATUS_SUB_COMMITTED
&& !TransactionIdIsValid(xid
)));
348 Assert(LWLockHeldByMeInMode(XactSLRULock
, LW_EXCLUSIVE
));
351 * If we're doing an async commit (ie, lsn is valid), then we must wait
352 * for any active write on the page slot to complete. Otherwise our
353 * update could reach disk in that write, which will not do since we
354 * mustn't let it reach disk until we've done the appropriate WAL flush.
355 * But when lsn is invalid, it's OK to scribble on a page while it is
356 * write-busy, since we don't care if the update reaches disk sooner than
359 slotno
= SimpleLruReadPage(XactCtl
, pageno
, XLogRecPtrIsInvalid(lsn
), xid
);
362 * Set the main transaction id, if any.
364 * If we update more than one xid on this page while it is being written
365 * out, we might find that some of the bits go to disk and others don't.
366 * If we are updating commits on the page with the top-level xid that
367 * could break atomicity, so we subcommit the subxids first before we mark
368 * the top-level commit.
370 if (TransactionIdIsValid(xid
))
372 /* Subtransactions first, if needed ... */
373 if (status
== TRANSACTION_STATUS_COMMITTED
)
375 for (i
= 0; i
< nsubxids
; i
++)
377 Assert(XactCtl
->shared
->page_number
[slotno
] == TransactionIdToPage(subxids
[i
]));
378 TransactionIdSetStatusBit(subxids
[i
],
379 TRANSACTION_STATUS_SUB_COMMITTED
,
384 /* ... then the main transaction */
385 TransactionIdSetStatusBit(xid
, status
, lsn
, slotno
);
388 /* Set the subtransactions */
389 for (i
= 0; i
< nsubxids
; i
++)
391 Assert(XactCtl
->shared
->page_number
[slotno
] == TransactionIdToPage(subxids
[i
]));
392 TransactionIdSetStatusBit(subxids
[i
], status
, lsn
, slotno
);
395 XactCtl
->shared
->page_dirty
[slotno
] = true;
399 * When we cannot immediately acquire XactSLRULock in exclusive mode at
400 * commit time, add ourselves to a list of processes that need their XIDs
401 * status update. The first process to add itself to the list will acquire
402 * XactSLRULock in exclusive mode and set transaction status as required
403 * on behalf of all group members. This avoids a great deal of contention
404 * around XactSLRULock when many processes are trying to commit at once,
405 * since the lock need not be repeatedly handed off from one committing
406 * process to the next.
408 * Returns true when transaction status has been updated in clog; returns
409 * false if we decided against applying the optimization because the page
410 * number we need to update differs from those processes already waiting.
413 TransactionGroupUpdateXidStatus(TransactionId xid
, XidStatus status
,
414 XLogRecPtr lsn
, int pageno
)
416 volatile PROC_HDR
*procglobal
= ProcGlobal
;
417 PGPROC
*proc
= MyProc
;
421 /* We should definitely have an XID whose status needs to be updated. */
422 Assert(TransactionIdIsValid(xid
));
425 * Add ourselves to the list of processes needing a group XID status
428 proc
->clogGroupMember
= true;
429 proc
->clogGroupMemberXid
= xid
;
430 proc
->clogGroupMemberXidStatus
= status
;
431 proc
->clogGroupMemberPage
= pageno
;
432 proc
->clogGroupMemberLsn
= lsn
;
434 nextidx
= pg_atomic_read_u32(&procglobal
->clogGroupFirst
);
439 * Add the proc to list, if the clog page where we need to update the
440 * current transaction status is same as group leader's clog page.
442 * There is a race condition here, which is that after doing the below
443 * check and before adding this proc's clog update to a group, the
444 * group leader might have already finished the group update for this
445 * page and becomes group leader of another group. This will lead to a
446 * situation where a single group can have different clog page
447 * updates. This isn't likely and will still work, just maybe a bit
450 if (nextidx
!= INVALID_PGPROCNO
&&
451 ProcGlobal
->allProcs
[nextidx
].clogGroupMemberPage
!= proc
->clogGroupMemberPage
)
454 * Ensure that this proc is not a member of any clog group that
455 * needs an XID status update.
457 proc
->clogGroupMember
= false;
458 pg_atomic_write_u32(&proc
->clogGroupNext
, INVALID_PGPROCNO
);
462 pg_atomic_write_u32(&proc
->clogGroupNext
, nextidx
);
464 if (pg_atomic_compare_exchange_u32(&procglobal
->clogGroupFirst
,
466 (uint32
) proc
->pgprocno
))
471 * If the list was not empty, the leader will update the status of our
472 * XID. It is impossible to have followers without a leader because the
473 * first process that has added itself to the list will always have
474 * nextidx as INVALID_PGPROCNO.
476 if (nextidx
!= INVALID_PGPROCNO
)
480 /* Sleep until the leader updates our XID status. */
481 pgstat_report_wait_start(WAIT_EVENT_XACT_GROUP_UPDATE
);
484 /* acts as a read barrier */
485 PGSemaphoreLock(proc
->sem
);
486 if (!proc
->clogGroupMember
)
490 pgstat_report_wait_end();
492 Assert(pg_atomic_read_u32(&proc
->clogGroupNext
) == INVALID_PGPROCNO
);
494 /* Fix semaphore count for any absorbed wakeups */
495 while (extraWaits
-- > 0)
496 PGSemaphoreUnlock(proc
->sem
);
500 /* We are the leader. Acquire the lock on behalf of everyone. */
501 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
504 * Now that we've got the lock, clear the list of processes waiting for
505 * group XID status update, saving a pointer to the head of the list.
506 * Trying to pop elements one at a time could lead to an ABA problem.
508 nextidx
= pg_atomic_exchange_u32(&procglobal
->clogGroupFirst
,
511 /* Remember head of list so we can perform wakeups after dropping lock. */
514 /* Walk the list and update the status of all XIDs. */
515 while (nextidx
!= INVALID_PGPROCNO
)
517 PGPROC
*nextproc
= &ProcGlobal
->allProcs
[nextidx
];
520 * Transactions with more than THRESHOLD_SUBTRANS_CLOG_OPT sub-XIDs
521 * should not use group XID status update mechanism.
523 Assert(nextproc
->subxidStatus
.count
<= THRESHOLD_SUBTRANS_CLOG_OPT
);
525 TransactionIdSetPageStatusInternal(nextproc
->clogGroupMemberXid
,
526 nextproc
->subxidStatus
.count
,
527 nextproc
->subxids
.xids
,
528 nextproc
->clogGroupMemberXidStatus
,
529 nextproc
->clogGroupMemberLsn
,
530 nextproc
->clogGroupMemberPage
);
532 /* Move to next proc in list. */
533 nextidx
= pg_atomic_read_u32(&nextproc
->clogGroupNext
);
536 /* We're done with the lock now. */
537 LWLockRelease(XactSLRULock
);
540 * Now that we've released the lock, go back and wake everybody up. We
541 * don't do this under the lock so as to keep lock hold times to a
544 while (wakeidx
!= INVALID_PGPROCNO
)
546 PGPROC
*wakeproc
= &ProcGlobal
->allProcs
[wakeidx
];
548 wakeidx
= pg_atomic_read_u32(&wakeproc
->clogGroupNext
);
549 pg_atomic_write_u32(&wakeproc
->clogGroupNext
, INVALID_PGPROCNO
);
551 /* ensure all previous writes are visible before follower continues. */
554 wakeproc
->clogGroupMember
= false;
556 if (wakeproc
!= MyProc
)
557 PGSemaphoreUnlock(wakeproc
->sem
);
564 * Sets the commit status of a single transaction.
566 * Must be called with XactSLRULock held
569 TransactionIdSetStatusBit(TransactionId xid
, XidStatus status
, XLogRecPtr lsn
, int slotno
)
571 int byteno
= TransactionIdToByte(xid
);
572 int bshift
= TransactionIdToBIndex(xid
) * CLOG_BITS_PER_XACT
;
577 byteptr
= XactCtl
->shared
->page_buffer
[slotno
] + byteno
;
578 curval
= (*byteptr
>> bshift
) & CLOG_XACT_BITMASK
;
581 * When replaying transactions during recovery we still need to perform
582 * the two phases of subcommit and then commit. However, some transactions
583 * are already correctly marked, so we just treat those as a no-op which
584 * allows us to keep the following Assert as restrictive as possible.
586 if (InRecovery
&& status
== TRANSACTION_STATUS_SUB_COMMITTED
&&
587 curval
== TRANSACTION_STATUS_COMMITTED
)
591 * Current state change should be from 0 or subcommitted to target state
592 * or we should already be there when replaying changes during recovery.
594 Assert(curval
== 0 ||
595 (curval
== TRANSACTION_STATUS_SUB_COMMITTED
&&
596 status
!= TRANSACTION_STATUS_IN_PROGRESS
) ||
599 /* note this assumes exclusive access to the clog page */
601 byteval
&= ~(((1 << CLOG_BITS_PER_XACT
) - 1) << bshift
);
602 byteval
|= (status
<< bshift
);
606 * Update the group LSN if the transaction completion LSN is higher.
608 * Note: lsn will be invalid when supplied during InRecovery processing,
609 * so we don't need to do anything special to avoid LSN updates during
610 * recovery. After recovery completes the next clog change will set the
613 if (!XLogRecPtrIsInvalid(lsn
))
615 int lsnindex
= GetLSNIndex(slotno
, xid
);
617 if (XactCtl
->shared
->group_lsn
[lsnindex
] < lsn
)
618 XactCtl
->shared
->group_lsn
[lsnindex
] = lsn
;
623 * Interrogate the state of a transaction in the commit log.
625 * Aside from the actual commit status, this function returns (into *lsn)
626 * an LSN that is late enough to be able to guarantee that if we flush up to
627 * that LSN then we will have flushed the transaction's commit record to disk.
628 * The result is not necessarily the exact LSN of the transaction's commit
629 * record! For example, for long-past transactions (those whose clog pages
630 * already migrated to disk), we'll return InvalidXLogRecPtr. Also, because
631 * we group transactions on the same clog page to conserve storage, we might
632 * return the LSN of a later transaction that falls into the same group.
634 * NB: this is a low-level routine and is NOT the preferred entry point
635 * for most uses; TransactionLogFetch() in transam.c is the intended caller.
638 TransactionIdGetStatus(TransactionId xid
, XLogRecPtr
*lsn
)
640 int pageno
= TransactionIdToPage(xid
);
641 int byteno
= TransactionIdToByte(xid
);
642 int bshift
= TransactionIdToBIndex(xid
) * CLOG_BITS_PER_XACT
;
648 /* lock is acquired by SimpleLruReadPage_ReadOnly */
650 slotno
= SimpleLruReadPage_ReadOnly(XactCtl
, pageno
, xid
);
651 byteptr
= XactCtl
->shared
->page_buffer
[slotno
] + byteno
;
653 status
= (*byteptr
>> bshift
) & CLOG_XACT_BITMASK
;
655 lsnindex
= GetLSNIndex(slotno
, xid
);
656 *lsn
= XactCtl
->shared
->group_lsn
[lsnindex
];
658 LWLockRelease(XactSLRULock
);
664 * Number of shared CLOG buffers.
666 * On larger multi-processor systems, it is possible to have many CLOG page
667 * requests in flight at one time which could lead to disk access for CLOG
668 * page if the required page is not found in memory. Testing revealed that we
669 * can get the best performance by having 128 CLOG buffers, more than that it
670 * doesn't improve performance.
672 * Unconditionally keeping the number of CLOG buffers to 128 did not seem like
673 * a good idea, because it would increase the minimum amount of shared memory
674 * required to start, which could be a problem for people running very small
675 * configurations. The following formula seems to represent a reasonable
676 * compromise: people with very low values for shared_buffers will get fewer
677 * CLOG buffers as well, and everyone else will get 128.
680 CLOGShmemBuffers(void)
682 return Min(128, Max(4, NBuffers
/ 512));
686 * Initialization of shared memory for CLOG
691 return SimpleLruShmemSize(CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE
);
697 XactCtl
->PagePrecedes
= CLOGPagePrecedes
;
698 SimpleLruInit(XactCtl
, "Xact", CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE
,
699 XactSLRULock
, "pg_xact", LWTRANCHE_XACT_BUFFER
,
701 SlruPagePrecedesUnitTests(XactCtl
, CLOG_XACTS_PER_PAGE
);
705 * This func must be called ONCE on system install. It creates
706 * the initial CLOG segment. (The CLOG directory is assumed to
707 * have been created by initdb, and CLOGShmemInit must have been
715 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
717 /* Create and zero the first page of the commit log */
718 slotno
= ZeroCLOGPage(0, false);
720 /* Make sure it's written out */
721 SimpleLruWritePage(XactCtl
, slotno
);
722 Assert(!XactCtl
->shared
->page_dirty
[slotno
]);
724 LWLockRelease(XactSLRULock
);
728 * Initialize (or reinitialize) a page of CLOG to zeroes.
729 * If writeXlog is true, also emit an XLOG record saying we did this.
731 * The page is not actually written, just set up in shared memory.
732 * The slot number of the new page is returned.
734 * Control lock must be held at entry, and will be held at exit.
737 ZeroCLOGPage(int pageno
, bool writeXlog
)
741 slotno
= SimpleLruZeroPage(XactCtl
, pageno
);
744 WriteZeroPageXlogRec(pageno
);
750 * This must be called ONCE during postmaster or standalone-backend startup,
751 * after StartupXLOG has initialized ShmemVariableCache->nextXid.
756 TransactionId xid
= XidFromFullTransactionId(ShmemVariableCache
->nextXid
);
757 int pageno
= TransactionIdToPage(xid
);
759 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
762 * Initialize our idea of the latest page number.
764 XactCtl
->shared
->latest_page_number
= pageno
;
766 LWLockRelease(XactSLRULock
);
770 * This must be called ONCE at the end of startup/recovery.
775 TransactionId xid
= XidFromFullTransactionId(ShmemVariableCache
->nextXid
);
776 int pageno
= TransactionIdToPage(xid
);
778 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
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.)
792 if (TransactionIdToPgIndex(xid
) != 0)
794 int byteno
= TransactionIdToByte(xid
);
795 int bshift
= TransactionIdToBIndex(xid
) * CLOG_BITS_PER_XACT
;
799 slotno
= SimpleLruReadPage(XactCtl
, pageno
, false, xid
);
800 byteptr
= XactCtl
->shared
->page_buffer
[slotno
] + byteno
;
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);
807 XactCtl
->shared
->page_dirty
[slotno
] = true;
810 LWLockRelease(XactSLRULock
);
814 * Perform a checkpoint --- either during shutdown, or on-the-fly
820 * Write dirty CLOG pages to disk. This may result in sync requests
821 * queued for later handling by ProcessSyncRequests(), as part of the
824 TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
825 SimpleLruWriteAll(XactCtl
, true);
826 TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
831 * Make sure that CLOG has room for a newly-allocated XID.
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
839 ExtendCLOG(TransactionId newestXact
)
844 * No work except at first XID of a page. But beware: just after
845 * wraparound, the first XID of page zero is FirstNormalTransactionId.
847 if (TransactionIdToPgIndex(newestXact
) != 0 &&
848 !TransactionIdEquals(newestXact
, FirstNormalTransactionId
))
851 pageno
= TransactionIdToPage(newestXact
);
853 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
855 /* Zero the page and make an XLOG entry about it */
856 ZeroCLOGPage(pageno
, true);
858 LWLockRelease(XactSLRULock
);
863 * Remove all CLOG segments before the one holding the passed transaction ID
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.
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.
878 TruncateCLOG(TransactionId oldestXact
, Oid oldestxid_datoid
)
883 * The cutoff point is the start of the segment containing oldestXact. We
884 * pass the *page* containing oldestXact to SimpleLruTruncate.
886 cutoffPage
= TransactionIdToPage(oldestXact
);
888 /* Check to see if there's any files that could be removed */
889 if (!SlruScanDirectory(XactCtl
, SlruScanDirCbReportPresence
, &cutoffPage
))
890 return; /* nothing to remove */
893 * Advance oldestClogXid before truncating clog, so concurrent xact status
894 * lookups can ensure they don't attempt to access truncated-away clog.
896 * It's only necessary to do this if we will actually truncate away clog
899 AdvanceOldestClogXid(oldestXact
);
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.
907 WriteTruncateXlogRec(cutoffPage
, oldestXact
, oldestxid_datoid
);
909 /* Now we can remove the old CLOG segment(s) */
910 SimpleLruTruncate(XactCtl
, cutoffPage
);
915 * Decide whether a CLOG page number is "older" for truncation purposes.
917 * We need to use comparison of TransactionIds here in order to do the right
918 * thing with wraparound XID arithmetic. However, TransactionIdPrecedes()
919 * would get weird about permanent xact IDs. So, offset both such that xid1,
920 * xid2, and xid2 + CLOG_XACTS_PER_PAGE - 1 are all normal XIDs; this offset
921 * is relevant to page 0 and to the page preceding page 0.
923 * The page containing oldestXact-2^31 is the important edge case. The
924 * portion of that page equaling or following oldestXact-2^31 is expendable,
925 * but the portion preceding oldestXact-2^31 is not. When oldestXact-2^31 is
926 * the first XID of a page and segment, the entire page and segment is
927 * expendable, and we could truncate the segment. Recognizing that case would
928 * require making oldestXact, not just the page containing oldestXact,
929 * available to this callback. The benefit would be rare and small, so we
930 * don't optimize that edge case.
933 CLOGPagePrecedes(int page1
, int page2
)
938 xid1
= ((TransactionId
) page1
) * CLOG_XACTS_PER_PAGE
;
939 xid1
+= FirstNormalTransactionId
+ 1;
940 xid2
= ((TransactionId
) page2
) * CLOG_XACTS_PER_PAGE
;
941 xid2
+= FirstNormalTransactionId
+ 1;
943 return (TransactionIdPrecedes(xid1
, xid2
) &&
944 TransactionIdPrecedes(xid1
, xid2
+ CLOG_XACTS_PER_PAGE
- 1));
949 * Write a ZEROPAGE xlog record
952 WriteZeroPageXlogRec(int pageno
)
955 XLogRegisterData((char *) (&pageno
), sizeof(int));
956 (void) XLogInsert(RM_CLOG_ID
, CLOG_ZEROPAGE
);
960 * Write a TRUNCATE xlog record
962 * We must flush the xlog record to disk before returning --- see notes
966 WriteTruncateXlogRec(int pageno
, TransactionId oldestXact
, Oid oldestXactDb
)
969 xl_clog_truncate xlrec
;
971 xlrec
.pageno
= pageno
;
972 xlrec
.oldestXact
= oldestXact
;
973 xlrec
.oldestXactDb
= oldestXactDb
;
976 XLogRegisterData((char *) (&xlrec
), sizeof(xl_clog_truncate
));
977 recptr
= XLogInsert(RM_CLOG_ID
, CLOG_TRUNCATE
);
982 * CLOG resource manager's routines
985 clog_redo(XLogReaderState
*record
)
987 uint8 info
= XLogRecGetInfo(record
) & ~XLR_INFO_MASK
;
989 /* Backup blocks are not used in clog records */
990 Assert(!XLogRecHasAnyBlockRefs(record
));
992 if (info
== CLOG_ZEROPAGE
)
997 memcpy(&pageno
, XLogRecGetData(record
), sizeof(int));
999 LWLockAcquire(XactSLRULock
, LW_EXCLUSIVE
);
1001 slotno
= ZeroCLOGPage(pageno
, false);
1002 SimpleLruWritePage(XactCtl
, slotno
);
1003 Assert(!XactCtl
->shared
->page_dirty
[slotno
]);
1005 LWLockRelease(XactSLRULock
);
1007 else if (info
== CLOG_TRUNCATE
)
1009 xl_clog_truncate xlrec
;
1011 memcpy(&xlrec
, XLogRecGetData(record
), sizeof(xl_clog_truncate
));
1013 AdvanceOldestClogXid(xlrec
.oldestXact
);
1015 SimpleLruTruncate(XactCtl
, xlrec
.pageno
);
1018 elog(PANIC
, "clog_redo: unknown op code %u", info
);
1022 * Entrypoint for sync.c to sync clog files.
1025 clogsyncfiletag(const FileTag
*ftag
, char *path
)
1027 return SlruSyncFileTag(XactCtl
, ftag
, path
);