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