]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/clog.c
Update copyright notices for year 2012.
[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-2012, 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 "pg_trace.h"
39
40 /*
41  * Defines for CLOG page sizes.  A page is the same BLCKSZ as is used
42  * everywhere else in Postgres.
43  *
44  * Note: because TransactionIds are 32 bits and wrap around at 0xFFFFFFFF,
45  * CLOG page numbering also wraps around at 0xFFFFFFFF/CLOG_XACTS_PER_PAGE,
46  * and CLOG segment numbering at 0xFFFFFFFF/CLOG_XACTS_PER_SEGMENT.  We need
47  * take no explicit notice of that fact in this module, except when comparing
48  * segment and page numbers in TruncateCLOG (see CLOGPagePrecedes).
49  */
50
51 /* We need two bits per xact, so four xacts fit in a byte */
52 #define CLOG_BITS_PER_XACT      2
53 #define CLOG_XACTS_PER_BYTE 4
54 #define CLOG_XACTS_PER_PAGE (BLCKSZ * CLOG_XACTS_PER_BYTE)
55 #define CLOG_XACT_BITMASK       ((1 << CLOG_BITS_PER_XACT) - 1)
56
57 #define TransactionIdToPage(xid)        ((xid) / (TransactionId) CLOG_XACTS_PER_PAGE)
58 #define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE)
59 #define TransactionIdToByte(xid)        (TransactionIdToPgIndex(xid) / CLOG_XACTS_PER_BYTE)
60 #define TransactionIdToBIndex(xid)      ((xid) % (TransactionId) CLOG_XACTS_PER_BYTE)
61
62 /* We store the latest async LSN for each group of transactions */
63 #define CLOG_XACTS_PER_LSN_GROUP        32      /* keep this a power of 2 */
64 #define CLOG_LSNS_PER_PAGE      (CLOG_XACTS_PER_PAGE / CLOG_XACTS_PER_LSN_GROUP)
65
66 #define GetLSNIndex(slotno, xid)        ((slotno) * CLOG_LSNS_PER_PAGE + \
67         ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
68
69
70 /*
71  * Link to shared-memory data structures for CLOG control
72  */
73 static SlruCtlData ClogCtlData;
74
75 #define ClogCtl (&ClogCtlData)
76
77
78 static int      ZeroCLOGPage(int pageno, bool writeXlog);
79 static bool CLOGPagePrecedes(int page1, int page2);
80 static void WriteZeroPageXlogRec(int pageno);
81 static void WriteTruncateXlogRec(int pageno);
82 static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
83                                                    TransactionId *subxids, XidStatus status,
84                                                    XLogRecPtr lsn, int pageno);
85 static void TransactionIdSetStatusBit(TransactionId xid, XidStatus status,
86                                                   XLogRecPtr lsn, int slotno);
87 static void set_status_by_pages(int nsubxids, TransactionId *subxids,
88                                         XidStatus status, XLogRecPtr lsn);
89
90
91 /*
92  * TransactionIdSetTreeStatus
93  *
94  * Record the final state of transaction entries in the commit log for
95  * a transaction and its subtransaction tree. Take care to ensure this is
96  * efficient, and as atomic as possible.
97  *
98  * xid is a single xid to set status for. This will typically be
99  * the top level transactionid for a top level commit or abort. It can
100  * also be a subtransaction when we record transaction aborts.
101  *
102  * subxids is an array of xids of length nsubxids, representing subtransactions
103  * in the tree of xid. In various cases nsubxids may be zero.
104  *
105  * lsn must be the WAL location of the commit record when recording an async
106  * commit.      For a synchronous commit it can be InvalidXLogRecPtr, since the
107  * caller guarantees the commit record is already flushed in that case.  It
108  * should be InvalidXLogRecPtr for abort cases, too.
109  *
110  * In the commit case, atomicity is limited by whether all the subxids are in
111  * the same CLOG page as xid.  If they all are, then the lock will be grabbed
112  * only once, and the status will be set to committed directly.  Otherwise
113  * we must
114  *       1. set sub-committed all subxids that are not on the same page as the
115  *              main xid
116  *       2. atomically set committed the main xid and the subxids on the same page
117  *       3. go over the first bunch again and set them committed
118  * Note that as far as concurrent checkers are concerned, main transaction
119  * commit as a whole is still atomic.
120  *
121  * Example:
122  *              TransactionId t commits and has subxids t1, t2, t3, t4
123  *              t is on page p1, t1 is also on p1, t2 and t3 are on p2, t4 is on p3
124  *              1. update pages2-3:
125  *                                      page2: set t2,t3 as sub-committed
126  *                                      page3: set t4 as sub-committed
127  *              2. update page1:
128  *                                      set t1 as sub-committed,
129  *                                      then set t as committed,
130                                         then set t1 as committed
131  *              3. update pages2-3:
132  *                                      page2: set t2,t3 as committed
133  *                                      page3: set t4 as committed
134  *
135  * NB: this is a low-level routine and is NOT the preferred entry point
136  * for most uses; functions in transam.c are the intended callers.
137  *
138  * XXX Think about issuing FADVISE_WILLNEED on pages that we will need,
139  * but aren't yet in cache, as well as hinting pages not to fall out of
140  * cache yet.
141  */
142 void
143 TransactionIdSetTreeStatus(TransactionId xid, int nsubxids,
144                                         TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
145 {
146         int                     pageno = TransactionIdToPage(xid);              /* get page of parent */
147         int                     i;
148
149         Assert(status == TRANSACTION_STATUS_COMMITTED ||
150                    status == TRANSACTION_STATUS_ABORTED);
151
152         /*
153          * See how many subxids, if any, are on the same page as the parent, if
154          * any.
155          */
156         for (i = 0; i < nsubxids; i++)
157         {
158                 if (TransactionIdToPage(subxids[i]) != pageno)
159                         break;
160         }
161
162         /*
163          * Do all items fit on a single page?
164          */
165         if (i == nsubxids)
166         {
167                 /*
168                  * Set the parent and all subtransactions in a single call
169                  */
170                 TransactionIdSetPageStatus(xid, nsubxids, subxids, status, lsn,
171                                                                    pageno);
172         }
173         else
174         {
175                 int                     nsubxids_on_first_page = i;
176
177                 /*
178                  * If this is a commit then we care about doing this correctly (i.e.
179                  * using the subcommitted intermediate status).  By here, we know
180                  * we're updating more than one page of clog, so we must mark entries
181                  * that are *not* on the first page so that they show as subcommitted
182                  * before we then return to update the status to fully committed.
183                  *
184                  * To avoid touching the first page twice, skip marking subcommitted
185                  * for the subxids on that first page.
186                  */
187                 if (status == TRANSACTION_STATUS_COMMITTED)
188                         set_status_by_pages(nsubxids - nsubxids_on_first_page,
189                                                                 subxids + nsubxids_on_first_page,
190                                                                 TRANSACTION_STATUS_SUB_COMMITTED, lsn);
191
192                 /*
193                  * Now set the parent and subtransactions on same page as the parent,
194                  * if any
195                  */
196                 pageno = TransactionIdToPage(xid);
197                 TransactionIdSetPageStatus(xid, nsubxids_on_first_page, subxids, status,
198                                                                    lsn, pageno);
199
200                 /*
201                  * Now work through the rest of the subxids one clog page at a time,
202                  * starting from the second page onwards, like we did above.
203                  */
204                 set_status_by_pages(nsubxids - nsubxids_on_first_page,
205                                                         subxids + nsubxids_on_first_page,
206                                                         status, lsn);
207         }
208 }
209
210 /*
211  * Helper for TransactionIdSetTreeStatus: set the status for a bunch of
212  * transactions, chunking in the separate CLOG pages involved. We never
213  * pass the whole transaction tree to this function, only subtransactions
214  * that are on different pages to the top level transaction id.
215  */
216 static void
217 set_status_by_pages(int nsubxids, TransactionId *subxids,
218                                         XidStatus status, XLogRecPtr lsn)
219 {
220         int                     pageno = TransactionIdToPage(subxids[0]);
221         int                     offset = 0;
222         int                     i = 0;
223
224         while (i < nsubxids)
225         {
226                 int                     num_on_page = 0;
227
228                 while (TransactionIdToPage(subxids[i]) == pageno && i < nsubxids)
229                 {
230                         num_on_page++;
231                         i++;
232                 }
233
234                 TransactionIdSetPageStatus(InvalidTransactionId,
235                                                                    num_on_page, subxids + offset,
236                                                                    status, lsn, pageno);
237                 offset = i;
238                 pageno = TransactionIdToPage(subxids[offset]);
239         }
240 }
241
242 /*
243  * Record the final state of transaction entries in the commit log for
244  * all entries on a single page.  Atomic only on this page.
245  *
246  * Otherwise API is same as TransactionIdSetTreeStatus()
247  */
248 static void
249 TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
250                                                    TransactionId *subxids, XidStatus status,
251                                                    XLogRecPtr lsn, int pageno)
252 {
253         int                     slotno;
254         int                     i;
255
256         Assert(status == TRANSACTION_STATUS_COMMITTED ||
257                    status == TRANSACTION_STATUS_ABORTED ||
258                    (status == TRANSACTION_STATUS_SUB_COMMITTED && !TransactionIdIsValid(xid)));
259
260         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
261
262         /*
263          * If we're doing an async commit (ie, lsn is valid), then we must wait
264          * for any active write on the page slot to complete.  Otherwise our
265          * update could reach disk in that write, which will not do since we
266          * mustn't let it reach disk until we've done the appropriate WAL flush.
267          * But when lsn is invalid, it's OK to scribble on a page while it is
268          * write-busy, since we don't care if the update reaches disk sooner than
269          * we think.
270          */
271         slotno = SimpleLruReadPage(ClogCtl, pageno, XLogRecPtrIsInvalid(lsn), xid);
272
273         /*
274          * Set the main transaction id, if any.
275          *
276          * If we update more than one xid on this page while it is being written
277          * out, we might find that some of the bits go to disk and others don't.
278          * If we are updating commits on the page with the top-level xid that
279          * could break atomicity, so we subcommit the subxids first before we mark
280          * the top-level commit.
281          */
282         if (TransactionIdIsValid(xid))
283         {
284                 /* Subtransactions first, if needed ... */
285                 if (status == TRANSACTION_STATUS_COMMITTED)
286                 {
287                         for (i = 0; i < nsubxids; i++)
288                         {
289                                 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
290                                 TransactionIdSetStatusBit(subxids[i],
291                                                                                   TRANSACTION_STATUS_SUB_COMMITTED,
292                                                                                   lsn, slotno);
293                         }
294                 }
295
296                 /* ... then the main transaction */
297                 TransactionIdSetStatusBit(xid, status, lsn, slotno);
298         }
299
300         /* Set the subtransactions */
301         for (i = 0; i < nsubxids; i++)
302         {
303                 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
304                 TransactionIdSetStatusBit(subxids[i], status, lsn, slotno);
305         }
306
307         ClogCtl->shared->page_dirty[slotno] = true;
308
309         LWLockRelease(CLogControlLock);
310 }
311
312 /*
313  * Sets the commit status of a single transaction.
314  *
315  * Must be called with CLogControlLock held
316  */
317 static void
318 TransactionIdSetStatusBit(TransactionId xid, XidStatus status, XLogRecPtr lsn, int slotno)
319 {
320         int                     byteno = TransactionIdToByte(xid);
321         int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
322         char       *byteptr;
323         char            byteval;
324         char            curval;
325
326         byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
327         curval = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
328
329         /*
330          * When replaying transactions during recovery we still need to perform
331          * the two phases of subcommit and then commit. However, some transactions
332          * are already correctly marked, so we just treat those as a no-op which
333          * allows us to keep the following Assert as restrictive as possible.
334          */
335         if (InRecovery && status == TRANSACTION_STATUS_SUB_COMMITTED &&
336                 curval == TRANSACTION_STATUS_COMMITTED)
337                 return;
338
339         /*
340          * Current state change should be from 0 or subcommitted to target state
341          * or we should already be there when replaying changes during recovery.
342          */
343         Assert(curval == 0 ||
344                    (curval == TRANSACTION_STATUS_SUB_COMMITTED &&
345                         status != TRANSACTION_STATUS_IN_PROGRESS) ||
346                    curval == status);
347
348         /* note this assumes exclusive access to the clog page */
349         byteval = *byteptr;
350         byteval &= ~(((1 << CLOG_BITS_PER_XACT) - 1) << bshift);
351         byteval |= (status << bshift);
352         *byteptr = byteval;
353
354         /*
355          * Update the group LSN if the transaction completion LSN is higher.
356          *
357          * Note: lsn will be invalid when supplied during InRecovery processing,
358          * so we don't need to do anything special to avoid LSN updates during
359          * recovery. After recovery completes the next clog change will set the
360          * LSN correctly.
361          */
362         if (!XLogRecPtrIsInvalid(lsn))
363         {
364                 int                     lsnindex = GetLSNIndex(slotno, xid);
365
366                 if (XLByteLT(ClogCtl->shared->group_lsn[lsnindex], lsn))
367                         ClogCtl->shared->group_lsn[lsnindex] = lsn;
368         }
369 }
370
371 /*
372  * Interrogate the state of a transaction in the commit log.
373  *
374  * Aside from the actual commit status, this function returns (into *lsn)
375  * an LSN that is late enough to be able to guarantee that if we flush up to
376  * that LSN then we will have flushed the transaction's commit record to disk.
377  * The result is not necessarily the exact LSN of the transaction's commit
378  * record!      For example, for long-past transactions (those whose clog pages
379  * already migrated to disk), we'll return InvalidXLogRecPtr.  Also, because
380  * we group transactions on the same clog page to conserve storage, we might
381  * return the LSN of a later transaction that falls into the same group.
382  *
383  * NB: this is a low-level routine and is NOT the preferred entry point
384  * for most uses; TransactionLogFetch() in transam.c is the intended caller.
385  */
386 XidStatus
387 TransactionIdGetStatus(TransactionId xid, XLogRecPtr *lsn)
388 {
389         int                     pageno = TransactionIdToPage(xid);
390         int                     byteno = TransactionIdToByte(xid);
391         int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
392         int                     slotno;
393         int                     lsnindex;
394         char       *byteptr;
395         XidStatus       status;
396
397         /* lock is acquired by SimpleLruReadPage_ReadOnly */
398
399         slotno = SimpleLruReadPage_ReadOnly(ClogCtl, pageno, xid);
400         byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
401
402         status = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
403
404         lsnindex = GetLSNIndex(slotno, xid);
405         *lsn = ClogCtl->shared->group_lsn[lsnindex];
406
407         LWLockRelease(CLogControlLock);
408
409         return status;
410 }
411
412
413 /*
414  * Initialization of shared memory for CLOG
415  */
416 Size
417 CLOGShmemSize(void)
418 {
419         return SimpleLruShmemSize(NUM_CLOG_BUFFERS, CLOG_LSNS_PER_PAGE);
420 }
421
422 void
423 CLOGShmemInit(void)
424 {
425         ClogCtl->PagePrecedes = CLOGPagePrecedes;
426         SimpleLruInit(ClogCtl, "CLOG Ctl", NUM_CLOG_BUFFERS, CLOG_LSNS_PER_PAGE,
427                                   CLogControlLock, "pg_clog");
428 }
429
430 /*
431  * This func must be called ONCE on system install.  It creates
432  * the initial CLOG segment.  (The CLOG directory is assumed to
433  * have been created by initdb, and CLOGShmemInit must have been
434  * called already.)
435  */
436 void
437 BootStrapCLOG(void)
438 {
439         int                     slotno;
440
441         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
442
443         /* Create and zero the first page of the commit log */
444         slotno = ZeroCLOGPage(0, false);
445
446         /* Make sure it's written out */
447         SimpleLruWritePage(ClogCtl, slotno);
448         Assert(!ClogCtl->shared->page_dirty[slotno]);
449
450         LWLockRelease(CLogControlLock);
451 }
452
453 /*
454  * Initialize (or reinitialize) a page of CLOG to zeroes.
455  * If writeXlog is TRUE, also emit an XLOG record saying we did this.
456  *
457  * The page is not actually written, just set up in shared memory.
458  * The slot number of the new page is returned.
459  *
460  * Control lock must be held at entry, and will be held at exit.
461  */
462 static int
463 ZeroCLOGPage(int pageno, bool writeXlog)
464 {
465         int                     slotno;
466
467         slotno = SimpleLruZeroPage(ClogCtl, pageno);
468
469         if (writeXlog)
470                 WriteZeroPageXlogRec(pageno);
471
472         return slotno;
473 }
474
475 /*
476  * This must be called ONCE during postmaster or standalone-backend startup,
477  * after StartupXLOG has initialized ShmemVariableCache->nextXid.
478  */
479 void
480 StartupCLOG(void)
481 {
482         TransactionId xid = ShmemVariableCache->nextXid;
483         int                     pageno = TransactionIdToPage(xid);
484
485         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
486
487         /*
488          * Initialize our idea of the latest page number.
489          */
490         ClogCtl->shared->latest_page_number = pageno;
491
492         LWLockRelease(CLogControlLock);
493 }
494
495 /*
496  * This must be called ONCE at the end of startup/recovery.
497  */
498 void
499 TrimCLOG(void)
500 {
501         TransactionId xid = ShmemVariableCache->nextXid;
502         int                     pageno = TransactionIdToPage(xid);
503
504         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
505
506         /*
507          * Re-Initialize our idea of the latest page number.
508          */
509         ClogCtl->shared->latest_page_number = pageno;
510
511         /*
512          * Zero out the remainder of the current clog page.  Under normal
513          * circumstances it should be zeroes already, but it seems at least
514          * theoretically possible that XLOG replay will have settled on a nextXID
515          * value that is less than the last XID actually used and marked by the
516          * previous database lifecycle (since subtransaction commit writes clog
517          * but makes no WAL entry).  Let's just be safe. (We need not worry about
518          * pages beyond the current one, since those will be zeroed when first
519          * used.  For the same reason, there is no need to do anything when
520          * nextXid is exactly at a page boundary; and it's likely that the
521          * "current" page doesn't exist yet in that case.)
522          */
523         if (TransactionIdToPgIndex(xid) != 0)
524         {
525                 int                     byteno = TransactionIdToByte(xid);
526                 int                     bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
527                 int                     slotno;
528                 char       *byteptr;
529
530                 slotno = SimpleLruReadPage(ClogCtl, pageno, false, xid);
531                 byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
532
533                 /* Zero so-far-unused positions in the current byte */
534                 *byteptr &= (1 << bshift) - 1;
535                 /* Zero the rest of the page */
536                 MemSet(byteptr + 1, 0, BLCKSZ - byteno - 1);
537
538                 ClogCtl->shared->page_dirty[slotno] = true;
539         }
540
541         LWLockRelease(CLogControlLock);
542 }
543
544 /*
545  * This must be called ONCE during postmaster or standalone-backend shutdown
546  */
547 void
548 ShutdownCLOG(void)
549 {
550         /* Flush dirty CLOG pages to disk */
551         TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(false);
552         SimpleLruFlush(ClogCtl, false);
553         TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(false);
554 }
555
556 /*
557  * Perform a checkpoint --- either during shutdown, or on-the-fly
558  */
559 void
560 CheckPointCLOG(void)
561 {
562         /* Flush dirty CLOG pages to disk */
563         TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
564         SimpleLruFlush(ClogCtl, true);
565         TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
566 }
567
568
569 /*
570  * Make sure that CLOG has room for a newly-allocated XID.
571  *
572  * NB: this is called while holding XidGenLock.  We want it to be very fast
573  * most of the time; even when it's not so fast, no actual I/O need happen
574  * unless we're forced to write out a dirty clog or xlog page to make room
575  * in shared memory.
576  */
577 void
578 ExtendCLOG(TransactionId newestXact)
579 {
580         int                     pageno;
581
582         /*
583          * No work except at first XID of a page.  But beware: just after
584          * wraparound, the first XID of page zero is FirstNormalTransactionId.
585          */
586         if (TransactionIdToPgIndex(newestXact) != 0 &&
587                 !TransactionIdEquals(newestXact, FirstNormalTransactionId))
588                 return;
589
590         pageno = TransactionIdToPage(newestXact);
591
592         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
593
594         /* Zero the page and make an XLOG entry about it */
595         ZeroCLOGPage(pageno, !InRecovery);
596
597         LWLockRelease(CLogControlLock);
598 }
599
600
601 /*
602  * Remove all CLOG segments before the one holding the passed transaction ID
603  *
604  * Before removing any CLOG data, we must flush XLOG to disk, to ensure
605  * that any recently-emitted HEAP_FREEZE records have reached disk; otherwise
606  * a crash and restart might leave us with some unfrozen tuples referencing
607  * removed CLOG data.  We choose to emit a special TRUNCATE XLOG record too.
608  * Replaying the deletion from XLOG is not critical, since the files could
609  * just as well be removed later, but doing so prevents a long-running hot
610  * standby server from acquiring an unreasonably bloated CLOG directory.
611  *
612  * Since CLOG segments hold a large number of transactions, the opportunity to
613  * actually remove a segment is fairly rare, and so it seems best not to do
614  * the XLOG flush unless we have confirmed that there is a removable segment.
615  */
616 void
617 TruncateCLOG(TransactionId oldestXact)
618 {
619         int                     cutoffPage;
620
621         /*
622          * The cutoff point is the start of the segment containing oldestXact. We
623          * pass the *page* containing oldestXact to SimpleLruTruncate.
624          */
625         cutoffPage = TransactionIdToPage(oldestXact);
626
627         /* Check to see if there's any files that could be removed */
628         if (!SlruScanDirectory(ClogCtl, SlruScanDirCbReportPresence, &cutoffPage))
629                 return;                                 /* nothing to remove */
630
631         /* Write XLOG record and flush XLOG to disk */
632         WriteTruncateXlogRec(cutoffPage);
633
634         /* Now we can remove the old CLOG segment(s) */
635         SimpleLruTruncate(ClogCtl, cutoffPage);
636 }
637
638
639 /*
640  * Decide which of two CLOG page numbers is "older" for truncation purposes.
641  *
642  * We need to use comparison of TransactionIds here in order to do the right
643  * thing with wraparound XID arithmetic.  However, if we are asked about
644  * page number zero, we don't want to hand InvalidTransactionId to
645  * TransactionIdPrecedes: it'll get weird about permanent xact IDs.  So,
646  * offset both xids by FirstNormalTransactionId to avoid that.
647  */
648 static bool
649 CLOGPagePrecedes(int page1, int page2)
650 {
651         TransactionId xid1;
652         TransactionId xid2;
653
654         xid1 = ((TransactionId) page1) * CLOG_XACTS_PER_PAGE;
655         xid1 += FirstNormalTransactionId;
656         xid2 = ((TransactionId) page2) * CLOG_XACTS_PER_PAGE;
657         xid2 += FirstNormalTransactionId;
658
659         return TransactionIdPrecedes(xid1, xid2);
660 }
661
662
663 /*
664  * Write a ZEROPAGE xlog record
665  */
666 static void
667 WriteZeroPageXlogRec(int pageno)
668 {
669         XLogRecData rdata;
670
671         rdata.data = (char *) (&pageno);
672         rdata.len = sizeof(int);
673         rdata.buffer = InvalidBuffer;
674         rdata.next = NULL;
675         (void) XLogInsert(RM_CLOG_ID, CLOG_ZEROPAGE, &rdata);
676 }
677
678 /*
679  * Write a TRUNCATE xlog record
680  *
681  * We must flush the xlog record to disk before returning --- see notes
682  * in TruncateCLOG().
683  */
684 static void
685 WriteTruncateXlogRec(int pageno)
686 {
687         XLogRecData rdata;
688         XLogRecPtr      recptr;
689
690         rdata.data = (char *) (&pageno);
691         rdata.len = sizeof(int);
692         rdata.buffer = InvalidBuffer;
693         rdata.next = NULL;
694         recptr = XLogInsert(RM_CLOG_ID, CLOG_TRUNCATE, &rdata);
695         XLogFlush(recptr);
696 }
697
698 /*
699  * CLOG resource manager's routines
700  */
701 void
702 clog_redo(XLogRecPtr lsn, XLogRecord *record)
703 {
704         uint8           info = record->xl_info & ~XLR_INFO_MASK;
705
706         /* Backup blocks are not used in clog records */
707         Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
708
709         if (info == CLOG_ZEROPAGE)
710         {
711                 int                     pageno;
712                 int                     slotno;
713
714                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
715
716                 LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
717
718                 slotno = ZeroCLOGPage(pageno, false);
719                 SimpleLruWritePage(ClogCtl, slotno);
720                 Assert(!ClogCtl->shared->page_dirty[slotno]);
721
722                 LWLockRelease(CLogControlLock);
723         }
724         else if (info == CLOG_TRUNCATE)
725         {
726                 int                     pageno;
727
728                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
729
730                 /*
731                  * During XLOG replay, latest_page_number isn't set up yet; insert a
732                  * suitable value to bypass the sanity test in SimpleLruTruncate.
733                  */
734                 ClogCtl->shared->latest_page_number = pageno;
735
736                 SimpleLruTruncate(ClogCtl, pageno);
737         }
738         else
739                 elog(PANIC, "clog_redo: unknown op code %u", info);
740 }
741
742 void
743 clog_desc(StringInfo buf, uint8 xl_info, char *rec)
744 {
745         uint8           info = xl_info & ~XLR_INFO_MASK;
746
747         if (info == CLOG_ZEROPAGE)
748         {
749                 int                     pageno;
750
751                 memcpy(&pageno, rec, sizeof(int));
752                 appendStringInfo(buf, "zeropage: %d", pageno);
753         }
754         else if (info == CLOG_TRUNCATE)
755         {
756                 int                     pageno;
757
758                 memcpy(&pageno, rec, sizeof(int));
759                 appendStringInfo(buf, "truncate before: %d", pageno);
760         }
761         else
762                 appendStringInfo(buf, "UNKNOWN");
763 }