]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/clog.c
Revamp the WAL record format.
[postgresql] / src / backend / access / transam / clog.c
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-2014, 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
44 /*
45  * Defines for CLOG page sizes.  A page is the same BLCKSZ as is used
46  * everywhere else in Postgres.
47  *
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).
54  */
55
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)
61
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)
66
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)
70
71 #define GetLSNIndex(slotno, xid)        ((slotno) * CLOG_LSNS_PER_PAGE + \
72         ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
73
74
75 /*
76  * Link to shared-memory data structures for CLOG control
77  */
78 static SlruCtlData ClogCtlData;
79
80 #define ClogCtl (&ClogCtlData)
81
82
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);
94
95
96 /*
97  * TransactionIdSetTreeStatus
98  *
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.
102  *
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.
106  *
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.
109  *
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.
114  *
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
118  * we must
119  *       1. set sub-committed all subxids that are not on the same page as the
120  *              main xid
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.
125  *
126  * Example:
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
132  *              2. update page1:
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
139  *
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.
142  *
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
145  * cache yet.
146  */
147 void
148 TransactionIdSetTreeStatus(TransactionId xid, int nsubxids,
149                                         TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
150 {
151         int                     pageno = TransactionIdToPage(xid);              /* get page of parent */
152         int                     i;
153
154         Assert(status == TRANSACTION_STATUS_COMMITTED ||
155                    status == TRANSACTION_STATUS_ABORTED);
156
157         /*
158          * See how many subxids, if any, are on the same page as the parent, if
159          * any.
160          */
161         for (i = 0; i < nsubxids; i++)
162         {
163                 if (TransactionIdToPage(subxids[i]) != pageno)
164                         break;
165         }
166
167         /*
168          * Do all items fit on a single page?
169          */
170         if (i == nsubxids)
171         {
172                 /*
173                  * Set the parent and all subtransactions in a single call
174                  */
175                 TransactionIdSetPageStatus(xid, nsubxids, subxids, status, lsn,
176                                                                    pageno);
177         }
178         else
179         {
180                 int                     nsubxids_on_first_page = i;
181
182                 /*
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.
188                  *
189                  * To avoid touching the first page twice, skip marking subcommitted
190                  * for the subxids on that first page.
191                  */
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);
196
197                 /*
198                  * Now set the parent and subtransactions on same page as the parent,
199                  * if any
200                  */
201                 pageno = TransactionIdToPage(xid);
202                 TransactionIdSetPageStatus(xid, nsubxids_on_first_page, subxids, status,
203                                                                    lsn, pageno);
204
205                 /*
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.
208                  */
209                 set_status_by_pages(nsubxids - nsubxids_on_first_page,
210                                                         subxids + nsubxids_on_first_page,
211                                                         status, lsn);
212         }
213 }
214
215 /*
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.
220  */
221 static void
222 set_status_by_pages(int nsubxids, TransactionId *subxids,
223                                         XidStatus status, XLogRecPtr lsn)
224 {
225         int                     pageno = TransactionIdToPage(subxids[0]);
226         int                     offset = 0;
227         int                     i = 0;
228
229         while (i < nsubxids)
230         {
231                 int                     num_on_page = 0;
232
233                 while (TransactionIdToPage(subxids[i]) == pageno && i < nsubxids)
234                 {
235                         num_on_page++;
236                         i++;
237                 }
238
239                 TransactionIdSetPageStatus(InvalidTransactionId,
240                                                                    num_on_page, subxids + offset,
241                                                                    status, lsn, pageno);
242                 offset = i;
243                 pageno = TransactionIdToPage(subxids[offset]);
244         }
245 }
246
247 /*
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.
250  *
251  * Otherwise API is same as TransactionIdSetTreeStatus()
252  */
253 static void
254 TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
255                                                    TransactionId *subxids, XidStatus status,
256                                                    XLogRecPtr lsn, int pageno)
257 {
258         int                     slotno;
259         int                     i;
260
261         Assert(status == TRANSACTION_STATUS_COMMITTED ||
262                    status == TRANSACTION_STATUS_ABORTED ||
263                    (status == TRANSACTION_STATUS_SUB_COMMITTED && !TransactionIdIsValid(xid)));
264
265         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
266
267         /*
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
274          * we think.
275          */
276         slotno = SimpleLruReadPage(ClogCtl, pageno, XLogRecPtrIsInvalid(lsn), xid);
277
278         /*
279          * Set the main transaction id, if any.
280          *
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.
286          */
287         if (TransactionIdIsValid(xid))
288         {
289                 /* Subtransactions first, if needed ... */
290                 if (status == TRANSACTION_STATUS_COMMITTED)
291                 {
292                         for (i = 0; i < nsubxids; i++)
293                         {
294                                 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
295                                 TransactionIdSetStatusBit(subxids[i],
296                                                                                   TRANSACTION_STATUS_SUB_COMMITTED,
297                                                                                   lsn, slotno);
298                         }
299                 }
300
301                 /* ... then the main transaction */
302                 TransactionIdSetStatusBit(xid, status, lsn, slotno);
303         }
304
305         /* Set the subtransactions */
306         for (i = 0; i < nsubxids; i++)
307         {
308                 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
309                 TransactionIdSetStatusBit(subxids[i], status, lsn, slotno);
310         }
311
312         ClogCtl->shared->page_dirty[slotno] = true;
313
314         LWLockRelease(CLogControlLock);
315 }
316
317 /*
318  * Sets the commit status of a single transaction.
319  *
320  * Must be called with CLogControlLock held
321  */
322 static void
323 TransactionIdSetStatusBit(TransactionId xid, XidStatus status, XLogRecPtr lsn, int slotno)
324 {
325         int                     byteno = TransactionIdToByte(xid);
326         int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
327         char       *byteptr;
328         char            byteval;
329         char            curval;
330
331         byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
332         curval = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
333
334         /*
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.
339          */
340         if (InRecovery && status == TRANSACTION_STATUS_SUB_COMMITTED &&
341                 curval == TRANSACTION_STATUS_COMMITTED)
342                 return;
343
344         /*
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.
347          */
348         Assert(curval == 0 ||
349                    (curval == TRANSACTION_STATUS_SUB_COMMITTED &&
350                         status != TRANSACTION_STATUS_IN_PROGRESS) ||
351                    curval == status);
352
353         /* note this assumes exclusive access to the clog page */
354         byteval = *byteptr;
355         byteval &= ~(((1 << CLOG_BITS_PER_XACT) - 1) << bshift);
356         byteval |= (status << bshift);
357         *byteptr = byteval;
358
359         /*
360          * Update the group LSN if the transaction completion LSN is higher.
361          *
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
365          * LSN correctly.
366          */
367         if (!XLogRecPtrIsInvalid(lsn))
368         {
369                 int                     lsnindex = GetLSNIndex(slotno, xid);
370
371                 if (ClogCtl->shared->group_lsn[lsnindex] < lsn)
372                         ClogCtl->shared->group_lsn[lsnindex] = lsn;
373         }
374 }
375
376 /*
377  * Interrogate the state of a transaction in the commit log.
378  *
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.
387  *
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.
390  */
391 XidStatus
392 TransactionIdGetStatus(TransactionId xid, XLogRecPtr *lsn)
393 {
394         int                     pageno = TransactionIdToPage(xid);
395         int                     byteno = TransactionIdToByte(xid);
396         int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
397         int                     slotno;
398         int                     lsnindex;
399         char       *byteptr;
400         XidStatus       status;
401
402         /* lock is acquired by SimpleLruReadPage_ReadOnly */
403
404         slotno = SimpleLruReadPage_ReadOnly(ClogCtl, pageno, xid);
405         byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
406
407         status = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
408
409         lsnindex = GetLSNIndex(slotno, xid);
410         *lsn = ClogCtl->shared->group_lsn[lsnindex];
411
412         LWLockRelease(CLogControlLock);
413
414         return status;
415 }
416
417 /*
418  * Number of shared CLOG buffers.
419  *
420  * Testing during the PostgreSQL 9.2 development cycle revealed that on a
421  * large multi-processor system, it was possible to have more CLOG page
422  * requests in flight at one time than the numebr of CLOG buffers which existed
423  * at that time, which was hardcoded to 8.  Further testing revealed that
424  * performance dropped off with more than 32 CLOG buffers, possibly because
425  * the linear buffer search algorithm doesn't scale well.
426  *
427  * Unconditionally increasing the number of CLOG buffers to 32 did not seem
428  * like a good idea, because it would increase the minimum amount of shared
429  * memory required to start, which could be a problem for people running very
430  * small configurations.  The following formula seems to represent a reasonable
431  * compromise: people with very low values for shared_buffers will get fewer
432  * CLOG buffers as well, and everyone else will get 32.
433  *
434  * It is likely that some further work will be needed here in future releases;
435  * for example, on a 64-core server, the maximum number of CLOG requests that
436  * can be simultaneously in flight will be even larger.  But that will
437  * apparently require more than just changing the formula, so for now we take
438  * the easy way out.
439  */
440 Size
441 CLOGShmemBuffers(void)
442 {
443         return Min(32, Max(4, NBuffers / 512));
444 }
445
446 /*
447  * Initialization of shared memory for CLOG
448  */
449 Size
450 CLOGShmemSize(void)
451 {
452         return SimpleLruShmemSize(CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE);
453 }
454
455 void
456 CLOGShmemInit(void)
457 {
458         ClogCtl->PagePrecedes = CLOGPagePrecedes;
459         SimpleLruInit(ClogCtl, "CLOG Ctl", CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE,
460                                   CLogControlLock, "pg_clog");
461 }
462
463 /*
464  * This func must be called ONCE on system install.  It creates
465  * the initial CLOG segment.  (The CLOG directory is assumed to
466  * have been created by initdb, and CLOGShmemInit must have been
467  * called already.)
468  */
469 void
470 BootStrapCLOG(void)
471 {
472         int                     slotno;
473
474         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
475
476         /* Create and zero the first page of the commit log */
477         slotno = ZeroCLOGPage(0, false);
478
479         /* Make sure it's written out */
480         SimpleLruWritePage(ClogCtl, slotno);
481         Assert(!ClogCtl->shared->page_dirty[slotno]);
482
483         LWLockRelease(CLogControlLock);
484 }
485
486 /*
487  * Initialize (or reinitialize) a page of CLOG to zeroes.
488  * If writeXlog is TRUE, also emit an XLOG record saying we did this.
489  *
490  * The page is not actually written, just set up in shared memory.
491  * The slot number of the new page is returned.
492  *
493  * Control lock must be held at entry, and will be held at exit.
494  */
495 static int
496 ZeroCLOGPage(int pageno, bool writeXlog)
497 {
498         int                     slotno;
499
500         slotno = SimpleLruZeroPage(ClogCtl, pageno);
501
502         if (writeXlog)
503                 WriteZeroPageXlogRec(pageno);
504
505         return slotno;
506 }
507
508 /*
509  * This must be called ONCE during postmaster or standalone-backend startup,
510  * after StartupXLOG has initialized ShmemVariableCache->nextXid.
511  */
512 void
513 StartupCLOG(void)
514 {
515         TransactionId xid = ShmemVariableCache->nextXid;
516         int                     pageno = TransactionIdToPage(xid);
517
518         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
519
520         /*
521          * Initialize our idea of the latest page number.
522          */
523         ClogCtl->shared->latest_page_number = pageno;
524
525         LWLockRelease(CLogControlLock);
526 }
527
528 /*
529  * This must be called ONCE at the end of startup/recovery.
530  */
531 void
532 TrimCLOG(void)
533 {
534         TransactionId xid = ShmemVariableCache->nextXid;
535         int                     pageno = TransactionIdToPage(xid);
536
537         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
538
539         /*
540          * Re-Initialize our idea of the latest page number.
541          */
542         ClogCtl->shared->latest_page_number = pageno;
543
544         /*
545          * Zero out the remainder of the current clog page.  Under normal
546          * circumstances it should be zeroes already, but it seems at least
547          * theoretically possible that XLOG replay will have settled on a nextXID
548          * value that is less than the last XID actually used and marked by the
549          * previous database lifecycle (since subtransaction commit writes clog
550          * but makes no WAL entry).  Let's just be safe. (We need not worry about
551          * pages beyond the current one, since those will be zeroed when first
552          * used.  For the same reason, there is no need to do anything when
553          * nextXid is exactly at a page boundary; and it's likely that the
554          * "current" page doesn't exist yet in that case.)
555          */
556         if (TransactionIdToPgIndex(xid) != 0)
557         {
558                 int                     byteno = TransactionIdToByte(xid);
559                 int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
560                 int                     slotno;
561                 char       *byteptr;
562
563                 slotno = SimpleLruReadPage(ClogCtl, pageno, false, xid);
564                 byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
565
566                 /* Zero so-far-unused positions in the current byte */
567                 *byteptr &= (1 << bshift) - 1;
568                 /* Zero the rest of the page */
569                 MemSet(byteptr + 1, 0, BLCKSZ - byteno - 1);
570
571                 ClogCtl->shared->page_dirty[slotno] = true;
572         }
573
574         LWLockRelease(CLogControlLock);
575 }
576
577 /*
578  * This must be called ONCE during postmaster or standalone-backend shutdown
579  */
580 void
581 ShutdownCLOG(void)
582 {
583         /* Flush dirty CLOG pages to disk */
584         TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(false);
585         SimpleLruFlush(ClogCtl, false);
586         TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(false);
587 }
588
589 /*
590  * Perform a checkpoint --- either during shutdown, or on-the-fly
591  */
592 void
593 CheckPointCLOG(void)
594 {
595         /* Flush dirty CLOG pages to disk */
596         TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
597         SimpleLruFlush(ClogCtl, true);
598         TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
599 }
600
601
602 /*
603  * Make sure that CLOG has room for a newly-allocated XID.
604  *
605  * NB: this is called while holding XidGenLock.  We want it to be very fast
606  * most of the time; even when it's not so fast, no actual I/O need happen
607  * unless we're forced to write out a dirty clog or xlog page to make room
608  * in shared memory.
609  */
610 void
611 ExtendCLOG(TransactionId newestXact)
612 {
613         int                     pageno;
614
615         /*
616          * No work except at first XID of a page.  But beware: just after
617          * wraparound, the first XID of page zero is FirstNormalTransactionId.
618          */
619         if (TransactionIdToPgIndex(newestXact) != 0 &&
620                 !TransactionIdEquals(newestXact, FirstNormalTransactionId))
621                 return;
622
623         pageno = TransactionIdToPage(newestXact);
624
625         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
626
627         /* Zero the page and make an XLOG entry about it */
628         ZeroCLOGPage(pageno, true);
629
630         LWLockRelease(CLogControlLock);
631 }
632
633
634 /*
635  * Remove all CLOG segments before the one holding the passed transaction ID
636  *
637  * Before removing any CLOG data, we must flush XLOG to disk, to ensure
638  * that any recently-emitted HEAP_FREEZE records have reached disk; otherwise
639  * a crash and restart might leave us with some unfrozen tuples referencing
640  * removed CLOG data.  We choose to emit a special TRUNCATE XLOG record too.
641  * Replaying the deletion from XLOG is not critical, since the files could
642  * just as well be removed later, but doing so prevents a long-running hot
643  * standby server from acquiring an unreasonably bloated CLOG directory.
644  *
645  * Since CLOG segments hold a large number of transactions, the opportunity to
646  * actually remove a segment is fairly rare, and so it seems best not to do
647  * the XLOG flush unless we have confirmed that there is a removable segment.
648  */
649 void
650 TruncateCLOG(TransactionId oldestXact)
651 {
652         int                     cutoffPage;
653
654         /*
655          * The cutoff point is the start of the segment containing oldestXact. We
656          * pass the *page* containing oldestXact to SimpleLruTruncate.
657          */
658         cutoffPage = TransactionIdToPage(oldestXact);
659
660         /* Check to see if there's any files that could be removed */
661         if (!SlruScanDirectory(ClogCtl, SlruScanDirCbReportPresence, &cutoffPage))
662                 return;                                 /* nothing to remove */
663
664         /* Write XLOG record and flush XLOG to disk */
665         WriteTruncateXlogRec(cutoffPage);
666
667         /* Now we can remove the old CLOG segment(s) */
668         SimpleLruTruncate(ClogCtl, cutoffPage);
669 }
670
671
672 /*
673  * Decide which of two CLOG page numbers is "older" for truncation purposes.
674  *
675  * We need to use comparison of TransactionIds here in order to do the right
676  * thing with wraparound XID arithmetic.  However, if we are asked about
677  * page number zero, we don't want to hand InvalidTransactionId to
678  * TransactionIdPrecedes: it'll get weird about permanent xact IDs.  So,
679  * offset both xids by FirstNormalTransactionId to avoid that.
680  */
681 static bool
682 CLOGPagePrecedes(int page1, int page2)
683 {
684         TransactionId xid1;
685         TransactionId xid2;
686
687         xid1 = ((TransactionId) page1) * CLOG_XACTS_PER_PAGE;
688         xid1 += FirstNormalTransactionId;
689         xid2 = ((TransactionId) page2) * CLOG_XACTS_PER_PAGE;
690         xid2 += FirstNormalTransactionId;
691
692         return TransactionIdPrecedes(xid1, xid2);
693 }
694
695
696 /*
697  * Write a ZEROPAGE xlog record
698  */
699 static void
700 WriteZeroPageXlogRec(int pageno)
701 {
702         XLogBeginInsert();
703         XLogRegisterData((char *) (&pageno), sizeof(int));
704         (void) XLogInsert(RM_CLOG_ID, CLOG_ZEROPAGE);
705 }
706
707 /*
708  * Write a TRUNCATE xlog record
709  *
710  * We must flush the xlog record to disk before returning --- see notes
711  * in TruncateCLOG().
712  */
713 static void
714 WriteTruncateXlogRec(int pageno)
715 {
716         XLogRecPtr      recptr;
717
718         XLogBeginInsert();
719         XLogRegisterData((char *) (&pageno), sizeof(int));
720         recptr = XLogInsert(RM_CLOG_ID, CLOG_TRUNCATE);
721         XLogFlush(recptr);
722 }
723
724 /*
725  * CLOG resource manager's routines
726  */
727 void
728 clog_redo(XLogReaderState *record)
729 {
730         uint8           info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
731
732         /* Backup blocks are not used in clog records */
733         Assert(!XLogRecHasAnyBlockRefs(record));
734
735         if (info == CLOG_ZEROPAGE)
736         {
737                 int                     pageno;
738                 int                     slotno;
739
740                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
741
742                 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
743
744                 slotno = ZeroCLOGPage(pageno, false);
745                 SimpleLruWritePage(ClogCtl, slotno);
746                 Assert(!ClogCtl->shared->page_dirty[slotno]);
747
748                 LWLockRelease(CLogControlLock);
749         }
750         else if (info == CLOG_TRUNCATE)
751         {
752                 int                     pageno;
753
754                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
755
756                 /*
757                  * During XLOG replay, latest_page_number isn't set up yet; insert a
758                  * suitable value to bypass the sanity test in SimpleLruTruncate.
759                  */
760                 ClogCtl->shared->latest_page_number = pageno;
761
762                 SimpleLruTruncate(ClogCtl, pageno);
763         }
764         else
765                 elog(PANIC, "clog_redo: unknown op code %u", info);
766 }