LCOV - code coverage report
Current view: top level - src/backend/access/transam - clog.c (source / functions) Hit Total Coverage
Test: PostgreSQL Lines: 185 242 76.4 %
Date: 2017-09-29 13:40:31 Functions: 19 22 86.4 %
Legend: Lines: hit not hit

          Line data    Source code
       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-2017, 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 "pgstat.h"
      43             : #include "pg_trace.h"
      44             : #include "storage/proc.h"
      45             : 
      46             : /*
      47             :  * Defines for CLOG page sizes.  A page is the same BLCKSZ as is used
      48             :  * everywhere else in Postgres.
      49             :  *
      50             :  * Note: because TransactionIds are 32 bits and wrap around at 0xFFFFFFFF,
      51             :  * CLOG page numbering also wraps around at 0xFFFFFFFF/CLOG_XACTS_PER_PAGE,
      52             :  * and CLOG segment numbering at
      53             :  * 0xFFFFFFFF/CLOG_XACTS_PER_PAGE/SLRU_PAGES_PER_SEGMENT.  We need take no
      54             :  * explicit notice of that fact in this module, except when comparing segment
      55             :  * and page numbers in TruncateCLOG (see CLOGPagePrecedes).
      56             :  */
      57             : 
      58             : /* We need two bits per xact, so four xacts fit in a byte */
      59             : #define CLOG_BITS_PER_XACT  2
      60             : #define CLOG_XACTS_PER_BYTE 4
      61             : #define CLOG_XACTS_PER_PAGE (BLCKSZ * CLOG_XACTS_PER_BYTE)
      62             : #define CLOG_XACT_BITMASK   ((1 << CLOG_BITS_PER_XACT) - 1)
      63             : 
      64             : #define TransactionIdToPage(xid)    ((xid) / (TransactionId) CLOG_XACTS_PER_PAGE)
      65             : #define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE)
      66             : #define TransactionIdToByte(xid)    (TransactionIdToPgIndex(xid) / CLOG_XACTS_PER_BYTE)
      67             : #define TransactionIdToBIndex(xid)  ((xid) % (TransactionId) CLOG_XACTS_PER_BYTE)
      68             : 
      69             : /* We store the latest async LSN for each group of transactions */
      70             : #define CLOG_XACTS_PER_LSN_GROUP    32  /* keep this a power of 2 */
      71             : #define CLOG_LSNS_PER_PAGE  (CLOG_XACTS_PER_PAGE / CLOG_XACTS_PER_LSN_GROUP)
      72             : 
      73             : #define GetLSNIndex(slotno, xid)    ((slotno) * CLOG_LSNS_PER_PAGE + \
      74             :     ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) / CLOG_XACTS_PER_LSN_GROUP)
      75             : 
      76             : /*
      77             :  * The number of subtransactions below which we consider to apply clog group
      78             :  * update optimization.  Testing reveals that the number higher than this can
      79             :  * hurt performance.
      80             :  */
      81             : #define THRESHOLD_SUBTRANS_CLOG_OPT 5
      82             : 
      83             : /*
      84             :  * Link to shared-memory data structures for CLOG control
      85             :  */
      86             : static SlruCtlData ClogCtlData;
      87             : 
      88             : #define ClogCtl (&ClogCtlData)
      89             : 
      90             : 
      91             : static int  ZeroCLOGPage(int pageno, bool writeXlog);
      92             : static bool CLOGPagePrecedes(int page1, int page2);
      93             : static void WriteZeroPageXlogRec(int pageno);
      94             : static void WriteTruncateXlogRec(int pageno, TransactionId oldestXact,
      95             :                      Oid oldestXidDb);
      96             : static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
      97             :                            TransactionId *subxids, XidStatus status,
      98             :                            XLogRecPtr lsn, int pageno,
      99             :                            bool all_xact_same_page);
     100             : static void TransactionIdSetStatusBit(TransactionId xid, XidStatus status,
     101             :                           XLogRecPtr lsn, int slotno);
     102             : static void set_status_by_pages(int nsubxids, TransactionId *subxids,
     103             :                     XidStatus status, XLogRecPtr lsn);
     104             : static bool TransactionGroupUpdateXidStatus(TransactionId xid,
     105             :                                 XidStatus status, XLogRecPtr lsn, int pageno);
     106             : static void TransactionIdSetPageStatusInternal(TransactionId xid, int nsubxids,
     107             :                                    TransactionId *subxids, XidStatus status,
     108             :                                    XLogRecPtr lsn, int pageno);
     109             : 
     110             : 
     111             : /*
     112             :  * TransactionIdSetTreeStatus
     113             :  *
     114             :  * Record the final state of transaction entries in the commit log for
     115             :  * a transaction and its subtransaction tree. Take care to ensure this is
     116             :  * efficient, and as atomic as possible.
     117             :  *
     118             :  * xid is a single xid to set status for. This will typically be
     119             :  * the top level transactionid for a top level commit or abort. It can
     120             :  * also be a subtransaction when we record transaction aborts.
     121             :  *
     122             :  * subxids is an array of xids of length nsubxids, representing subtransactions
     123             :  * in the tree of xid. In various cases nsubxids may be zero.
     124             :  *
     125             :  * lsn must be the WAL location of the commit record when recording an async
     126             :  * commit.  For a synchronous commit it can be InvalidXLogRecPtr, since the
     127             :  * caller guarantees the commit record is already flushed in that case.  It
     128             :  * should be InvalidXLogRecPtr for abort cases, too.
     129             :  *
     130             :  * In the commit case, atomicity is limited by whether all the subxids are in
     131             :  * the same CLOG page as xid.  If they all are, then the lock will be grabbed
     132             :  * only once, and the status will be set to committed directly.  Otherwise
     133             :  * we must
     134             :  *   1. set sub-committed all subxids that are not on the same page as the
     135             :  *      main xid
     136             :  *   2. atomically set committed the main xid and the subxids on the same page
     137             :  *   3. go over the first bunch again and set them committed
     138             :  * Note that as far as concurrent checkers are concerned, main transaction
     139             :  * commit as a whole is still atomic.
     140             :  *
     141             :  * Example:
     142             :  *      TransactionId t commits and has subxids t1, t2, t3, t4
     143             :  *      t is on page p1, t1 is also on p1, t2 and t3 are on p2, t4 is on p3
     144             :  *      1. update pages2-3:
     145             :  *                  page2: set t2,t3 as sub-committed
     146             :  *                  page3: set t4 as sub-committed
     147             :  *      2. update page1:
     148             :  *                  set t1 as sub-committed,
     149             :  *                  then set t as committed,
     150             :                     then set t1 as committed
     151             :  *      3. update pages2-3:
     152             :  *                  page2: set t2,t3 as committed
     153             :  *                  page3: set t4 as committed
     154             :  *
     155             :  * NB: this is a low-level routine and is NOT the preferred entry point
     156             :  * for most uses; functions in transam.c are the intended callers.
     157             :  *
     158             :  * XXX Think about issuing FADVISE_WILLNEED on pages that we will need,
     159             :  * but aren't yet in cache, as well as hinting pages not to fall out of
     160             :  * cache yet.
     161             :  */
     162             : void
     163       10602 : TransactionIdSetTreeStatus(TransactionId xid, int nsubxids,
     164             :                            TransactionId *subxids, XidStatus status, XLogRecPtr lsn)
     165             : {
     166       10602 :     int         pageno = TransactionIdToPage(xid);  /* get page of parent */
     167             :     int         i;
     168             : 
     169       10602 :     Assert(status == TRANSACTION_STATUS_COMMITTED ||
     170             :            status == TRANSACTION_STATUS_ABORTED);
     171             : 
     172             :     /*
     173             :      * See how many subxids, if any, are on the same page as the parent, if
     174             :      * any.
     175             :      */
     176       10626 :     for (i = 0; i < nsubxids; i++)
     177             :     {
     178          24 :         if (TransactionIdToPage(subxids[i]) != pageno)
     179           0 :             break;
     180             :     }
     181             : 
     182             :     /*
     183             :      * Do all items fit on a single page?
     184             :      */
     185       10602 :     if (i == nsubxids)
     186             :     {
     187             :         /*
     188             :          * Set the parent and all subtransactions in a single call
     189             :          */
     190       10602 :         TransactionIdSetPageStatus(xid, nsubxids, subxids, status, lsn,
     191             :                                    pageno, true);
     192             :     }
     193             :     else
     194             :     {
     195           0 :         int         nsubxids_on_first_page = i;
     196             : 
     197             :         /*
     198             :          * If this is a commit then we care about doing this correctly (i.e.
     199             :          * using the subcommitted intermediate status).  By here, we know
     200             :          * we're updating more than one page of clog, so we must mark entries
     201             :          * that are *not* on the first page so that they show as subcommitted
     202             :          * before we then return to update the status to fully committed.
     203             :          *
     204             :          * To avoid touching the first page twice, skip marking subcommitted
     205             :          * for the subxids on that first page.
     206             :          */
     207           0 :         if (status == TRANSACTION_STATUS_COMMITTED)
     208           0 :             set_status_by_pages(nsubxids - nsubxids_on_first_page,
     209           0 :                                 subxids + nsubxids_on_first_page,
     210             :                                 TRANSACTION_STATUS_SUB_COMMITTED, lsn);
     211             : 
     212             :         /*
     213             :          * Now set the parent and subtransactions on same page as the parent,
     214             :          * if any
     215             :          */
     216           0 :         pageno = TransactionIdToPage(xid);
     217           0 :         TransactionIdSetPageStatus(xid, nsubxids_on_first_page, subxids, status,
     218             :                                    lsn, pageno, false);
     219             : 
     220             :         /*
     221             :          * Now work through the rest of the subxids one clog page at a time,
     222             :          * starting from the second page onwards, like we did above.
     223             :          */
     224           0 :         set_status_by_pages(nsubxids - nsubxids_on_first_page,
     225           0 :                             subxids + nsubxids_on_first_page,
     226             :                             status, lsn);
     227             :     }
     228       10602 : }
     229             : 
     230             : /*
     231             :  * Helper for TransactionIdSetTreeStatus: set the status for a bunch of
     232             :  * transactions, chunking in the separate CLOG pages involved. We never
     233             :  * pass the whole transaction tree to this function, only subtransactions
     234             :  * that are on different pages to the top level transaction id.
     235             :  */
     236             : static void
     237           0 : set_status_by_pages(int nsubxids, TransactionId *subxids,
     238             :                     XidStatus status, XLogRecPtr lsn)
     239             : {
     240           0 :     int         pageno = TransactionIdToPage(subxids[0]);
     241           0 :     int         offset = 0;
     242           0 :     int         i = 0;
     243             : 
     244           0 :     while (i < nsubxids)
     245             :     {
     246           0 :         int         num_on_page = 0;
     247             : 
     248           0 :         while (TransactionIdToPage(subxids[i]) == pageno && i < nsubxids)
     249             :         {
     250           0 :             num_on_page++;
     251           0 :             i++;
     252             :         }
     253             : 
     254           0 :         TransactionIdSetPageStatus(InvalidTransactionId,
     255           0 :                                    num_on_page, subxids + offset,
     256             :                                    status, lsn, pageno, false);
     257           0 :         offset = i;
     258           0 :         pageno = TransactionIdToPage(subxids[offset]);
     259             :     }
     260           0 : }
     261             : 
     262             : /*
     263             :  * Record the final state of transaction entries in the commit log for all
     264             :  * entries on a single page.  Atomic only on this page.
     265             :  */
     266             : static void
     267       10602 : TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
     268             :                            TransactionId *subxids, XidStatus status,
     269             :                            XLogRecPtr lsn, int pageno,
     270             :                            bool all_xact_same_page)
     271             : {
     272             :     /* Can't use group update when PGPROC overflows. */
     273             :     StaticAssertStmt(THRESHOLD_SUBTRANS_CLOG_OPT <= PGPROC_MAX_CACHED_SUBXIDS,
     274             :                      "group clog threshold less than PGPROC cached subxids");
     275             : 
     276             :     /*
     277             :      * When there is contention on CLogControlLock, we try to group multiple
     278             :      * updates; a single leader process will perform transaction status
     279             :      * updates for multiple backends so that the number of times
     280             :      * CLogControlLock needs to be acquired is reduced.
     281             :      *
     282             :      * For this optimization to be safe, the XID in MyPgXact and the subxids
     283             :      * in MyProc must be the same as the ones for which we're setting the
     284             :      * status.  Check that this is the case.
     285             :      *
     286             :      * For this optimization to be efficient, we shouldn't have too many
     287             :      * sub-XIDs and all of the XIDs for which we're adjusting clog should be
     288             :      * on the same page.  Check those conditions, too.
     289             :      */
     290       10602 :     if (all_xact_same_page && xid == MyPgXact->xid &&
     291       10556 :         nsubxids <= THRESHOLD_SUBTRANS_CLOG_OPT &&
     292       21112 :         nsubxids == MyPgXact->nxids &&
     293       10556 :         memcmp(subxids, MyProc->subxids.xids,
     294             :                nsubxids * sizeof(TransactionId)) == 0)
     295             :     {
     296             :         /*
     297             :          * We don't try to do group update optimization if a process has
     298             :          * overflowed the subxids array in its PGPROC, since in that case we
     299             :          * don't have a complete list of XIDs for it.
     300             :          */
     301             :         Assert(THRESHOLD_SUBTRANS_CLOG_OPT <= PGPROC_MAX_CACHED_SUBXIDS);
     302             : 
     303             :         /*
     304             :          * If we can immediately acquire CLogControlLock, we update the status
     305             :          * of our own XID and release the lock.  If not, try use group XID
     306             :          * update.  If that doesn't work out, fall back to waiting for the
     307             :          * lock to perform an update for this transaction only.
     308             :          */
     309       10556 :         if (LWLockConditionalAcquire(CLogControlLock, LW_EXCLUSIVE))
     310             :         {
     311             :             /* Got the lock without waiting!  Do the update. */
     312       10540 :             TransactionIdSetPageStatusInternal(xid, nsubxids, subxids, status,
     313             :                                                lsn, pageno);
     314       10540 :             LWLockRelease(CLogControlLock);
     315       10540 :             return;
     316             :         }
     317          16 :         else if (TransactionGroupUpdateXidStatus(xid, status, lsn, pageno))
     318             :         {
     319             :             /* Group update mechanism has done the work. */
     320          16 :             return;
     321             :         }
     322             : 
     323             :         /* Fall through only if update isn't done yet. */
     324             :     }
     325             : 
     326             :     /* Group update not applicable, or couldn't accept this page number. */
     327          46 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     328          46 :     TransactionIdSetPageStatusInternal(xid, nsubxids, subxids, status,
     329             :                                        lsn, pageno);
     330          46 :     LWLockRelease(CLogControlLock);
     331             : }
     332             : 
     333             : /*
     334             :  * Record the final state of transaction entry in the commit log
     335             :  *
     336             :  * We don't do any locking here; caller must handle that.
     337             :  */
     338             : static void
     339       10602 : TransactionIdSetPageStatusInternal(TransactionId xid, int nsubxids,
     340             :                                    TransactionId *subxids, XidStatus status,
     341             :                                    XLogRecPtr lsn, int pageno)
     342             : {
     343             :     int         slotno;
     344             :     int         i;
     345             : 
     346       10602 :     Assert(status == TRANSACTION_STATUS_COMMITTED ||
     347             :            status == TRANSACTION_STATUS_ABORTED ||
     348             :            (status == TRANSACTION_STATUS_SUB_COMMITTED && !TransactionIdIsValid(xid)));
     349       10602 :     Assert(LWLockHeldByMeInMode(CLogControlLock, LW_EXCLUSIVE));
     350             : 
     351             :     /*
     352             :      * If we're doing an async commit (ie, lsn is valid), then we must wait
     353             :      * for any active write on the page slot to complete.  Otherwise our
     354             :      * update could reach disk in that write, which will not do since we
     355             :      * mustn't let it reach disk until we've done the appropriate WAL flush.
     356             :      * But when lsn is invalid, it's OK to scribble on a page while it is
     357             :      * write-busy, since we don't care if the update reaches disk sooner than
     358             :      * we think.
     359             :      */
     360       10602 :     slotno = SimpleLruReadPage(ClogCtl, pageno, XLogRecPtrIsInvalid(lsn), xid);
     361             : 
     362             :     /*
     363             :      * Set the main transaction id, if any.
     364             :      *
     365             :      * If we update more than one xid on this page while it is being written
     366             :      * out, we might find that some of the bits go to disk and others don't.
     367             :      * If we are updating commits on the page with the top-level xid that
     368             :      * could break atomicity, so we subcommit the subxids first before we mark
     369             :      * the top-level commit.
     370             :      */
     371       10602 :     if (TransactionIdIsValid(xid))
     372             :     {
     373             :         /* Subtransactions first, if needed ... */
     374       10602 :         if (status == TRANSACTION_STATUS_COMMITTED)
     375             :         {
     376        9897 :             for (i = 0; i < nsubxids; i++)
     377             :             {
     378          19 :                 Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
     379          19 :                 TransactionIdSetStatusBit(subxids[i],
     380             :                                           TRANSACTION_STATUS_SUB_COMMITTED,
     381             :                                           lsn, slotno);
     382             :             }
     383             :         }
     384             : 
     385             :         /* ... then the main transaction */
     386       10602 :         TransactionIdSetStatusBit(xid, status, lsn, slotno);
     387             :     }
     388             : 
     389             :     /* Set the subtransactions */
     390       10626 :     for (i = 0; i < nsubxids; i++)
     391             :     {
     392          24 :         Assert(ClogCtl->shared->page_number[slotno] == TransactionIdToPage(subxids[i]));
     393          24 :         TransactionIdSetStatusBit(subxids[i], status, lsn, slotno);
     394             :     }
     395             : 
     396       10602 :     ClogCtl->shared->page_dirty[slotno] = true;
     397       10602 : }
     398             : 
     399             : /*
     400             :  * When we cannot immediately acquire CLogControlLock in exclusive mode at
     401             :  * commit time, add ourselves to a list of processes that need their XIDs
     402             :  * status update.  The first process to add itself to the list will acquire
     403             :  * CLogControlLock in exclusive mode and set transaction status as required
     404             :  * on behalf of all group members.  This avoids a great deal of contention
     405             :  * around CLogControlLock when many processes are trying to commit at once,
     406             :  * since the lock need not be repeatedly handed off from one committing
     407             :  * process to the next.
     408             :  *
     409             :  * Returns true when transaction status has been updated in clog; returns
     410             :  * false if we decided against applying the optimization because the page
     411             :  * number we need to update differs from those processes already waiting.
     412             :  */
     413             : static bool
     414          16 : TransactionGroupUpdateXidStatus(TransactionId xid, XidStatus status,
     415             :                                 XLogRecPtr lsn, int pageno)
     416             : {
     417          16 :     volatile PROC_HDR *procglobal = ProcGlobal;
     418          16 :     PGPROC     *proc = MyProc;
     419             :     uint32      nextidx;
     420             :     uint32      wakeidx;
     421             : 
     422             :     /* We should definitely have an XID whose status needs to be updated. */
     423          16 :     Assert(TransactionIdIsValid(xid));
     424             : 
     425             :     /*
     426             :      * Add ourselves to the list of processes needing a group XID status
     427             :      * update.
     428             :      */
     429          16 :     proc->clogGroupMember = true;
     430          16 :     proc->clogGroupMemberXid = xid;
     431          16 :     proc->clogGroupMemberXidStatus = status;
     432          16 :     proc->clogGroupMemberPage = pageno;
     433          16 :     proc->clogGroupMemberLsn = lsn;
     434             : 
     435          16 :     nextidx = pg_atomic_read_u32(&procglobal->clogGroupFirst);
     436             : 
     437             :     while (true)
     438             :     {
     439             :         /*
     440             :          * Add the proc to list, if the clog page where we need to update the
     441             :          * current transaction status is same as group leader's clog page.
     442             :          *
     443             :          * There is a race condition here, which is that after doing the below
     444             :          * check and before adding this proc's clog update to a group, the
     445             :          * group leader might have already finished the group update for this
     446             :          * page and becomes group leader of another group. This will lead to a
     447             :          * situation where a single group can have different clog page
     448             :          * updates.  This isn't likely and will still work, just maybe a bit
     449             :          * less efficiently.
     450             :          */
     451          18 :         if (nextidx != INVALID_PGPROCNO &&
     452           1 :             ProcGlobal->allProcs[nextidx].clogGroupMemberPage != proc->clogGroupMemberPage)
     453             :         {
     454           0 :             proc->clogGroupMember = false;
     455           0 :             return false;
     456             :         }
     457             : 
     458          17 :         pg_atomic_write_u32(&proc->clogGroupNext, nextidx);
     459             : 
     460          17 :         if (pg_atomic_compare_exchange_u32(&procglobal->clogGroupFirst,
     461             :                                            &nextidx,
     462          17 :                                            (uint32) proc->pgprocno))
     463          16 :             break;
     464           1 :     }
     465             : 
     466             :     /*
     467             :      * If the list was not empty, the leader will update the status of our
     468             :      * XID. It is impossible to have followers without a leader because the
     469             :      * first process that has added itself to the list will always have
     470             :      * nextidx as INVALID_PGPROCNO.
     471             :      */
     472          16 :     if (nextidx != INVALID_PGPROCNO)
     473             :     {
     474           1 :         int         extraWaits = 0;
     475             : 
     476             :         /* Sleep until the leader updates our XID status. */
     477           1 :         pgstat_report_wait_start(WAIT_EVENT_CLOG_GROUP_UPDATE);
     478             :         for (;;)
     479             :         {
     480             :             /* acts as a read barrier */
     481           1 :             PGSemaphoreLock(proc->sem);
     482           1 :             if (!proc->clogGroupMember)
     483           1 :                 break;
     484           0 :             extraWaits++;
     485           0 :         }
     486           1 :         pgstat_report_wait_end();
     487             : 
     488           1 :         Assert(pg_atomic_read_u32(&proc->clogGroupNext) == INVALID_PGPROCNO);
     489             : 
     490             :         /* Fix semaphore count for any absorbed wakeups */
     491           2 :         while (extraWaits-- > 0)
     492           0 :             PGSemaphoreUnlock(proc->sem);
     493           1 :         return true;
     494             :     }
     495             : 
     496             :     /* We are the leader.  Acquire the lock on behalf of everyone. */
     497          15 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     498             : 
     499             :     /*
     500             :      * Now that we've got the lock, clear the list of processes waiting for
     501             :      * group XID status update, saving a pointer to the head of the list.
     502             :      * Trying to pop elements one at a time could lead to an ABA problem.
     503             :      */
     504          15 :     nextidx = pg_atomic_exchange_u32(&procglobal->clogGroupFirst,
     505             :                                      INVALID_PGPROCNO);
     506             : 
     507             :     /* Remember head of list so we can perform wakeups after dropping lock. */
     508          15 :     wakeidx = nextidx;
     509             : 
     510             :     /* Walk the list and update the status of all XIDs. */
     511          46 :     while (nextidx != INVALID_PGPROCNO)
     512             :     {
     513          16 :         PGPROC     *proc = &ProcGlobal->allProcs[nextidx];
     514          16 :         PGXACT     *pgxact = &ProcGlobal->allPgXact[nextidx];
     515             : 
     516             :         /*
     517             :          * Overflowed transactions should not use group XID status update
     518             :          * mechanism.
     519             :          */
     520          16 :         Assert(!pgxact->overflowed);
     521             : 
     522          32 :         TransactionIdSetPageStatusInternal(proc->clogGroupMemberXid,
     523          16 :                                            pgxact->nxids,
     524          16 :                                            proc->subxids.xids,
     525             :                                            proc->clogGroupMemberXidStatus,
     526             :                                            proc->clogGroupMemberLsn,
     527             :                                            proc->clogGroupMemberPage);
     528             : 
     529             :         /* Move to next proc in list. */
     530          16 :         nextidx = pg_atomic_read_u32(&proc->clogGroupNext);
     531             :     }
     532             : 
     533             :     /* We're done with the lock now. */
     534          15 :     LWLockRelease(CLogControlLock);
     535             : 
     536             :     /*
     537             :      * Now that we've released the lock, go back and wake everybody up.  We
     538             :      * don't do this under the lock so as to keep lock hold times to a
     539             :      * minimum.
     540             :      */
     541          46 :     while (wakeidx != INVALID_PGPROCNO)
     542             :     {
     543          16 :         PGPROC     *proc = &ProcGlobal->allProcs[wakeidx];
     544             : 
     545          16 :         wakeidx = pg_atomic_read_u32(&proc->clogGroupNext);
     546          16 :         pg_atomic_write_u32(&proc->clogGroupNext, INVALID_PGPROCNO);
     547             : 
     548             :         /* ensure all previous writes are visible before follower continues. */
     549          16 :         pg_write_barrier();
     550             : 
     551          16 :         proc->clogGroupMember = false;
     552             : 
     553          16 :         if (proc != MyProc)
     554           1 :             PGSemaphoreUnlock(proc->sem);
     555             :     }
     556             : 
     557          15 :     return true;
     558             : }
     559             : 
     560             : /*
     561             :  * Sets the commit status of a single transaction.
     562             :  *
     563             :  * Must be called with CLogControlLock held
     564             :  */
     565             : static void
     566       10645 : TransactionIdSetStatusBit(TransactionId xid, XidStatus status, XLogRecPtr lsn, int slotno)
     567             : {
     568       10645 :     int         byteno = TransactionIdToByte(xid);
     569       10645 :     int         bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
     570             :     char       *byteptr;
     571             :     char        byteval;
     572             :     char        curval;
     573             : 
     574       10645 :     byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
     575       10645 :     curval = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
     576             : 
     577             :     /*
     578             :      * When replaying transactions during recovery we still need to perform
     579             :      * the two phases of subcommit and then commit. However, some transactions
     580             :      * are already correctly marked, so we just treat those as a no-op which
     581             :      * allows us to keep the following Assert as restrictive as possible.
     582             :      */
     583       10645 :     if (InRecovery && status == TRANSACTION_STATUS_SUB_COMMITTED &&
     584             :         curval == TRANSACTION_STATUS_COMMITTED)
     585       10645 :         return;
     586             : 
     587             :     /*
     588             :      * Current state change should be from 0 or subcommitted to target state
     589             :      * or we should already be there when replaying changes during recovery.
     590             :      */
     591       10645 :     Assert(curval == 0 ||
     592             :            (curval == TRANSACTION_STATUS_SUB_COMMITTED &&
     593             :             status != TRANSACTION_STATUS_IN_PROGRESS) ||
     594             :            curval == status);
     595             : 
     596             :     /* note this assumes exclusive access to the clog page */
     597       10645 :     byteval = *byteptr;
     598       10645 :     byteval &= ~(((1 << CLOG_BITS_PER_XACT) - 1) << bshift);
     599       10645 :     byteval |= (status << bshift);
     600       10645 :     *byteptr = byteval;
     601             : 
     602             :     /*
     603             :      * Update the group LSN if the transaction completion LSN is higher.
     604             :      *
     605             :      * Note: lsn will be invalid when supplied during InRecovery processing,
     606             :      * so we don't need to do anything special to avoid LSN updates during
     607             :      * recovery. After recovery completes the next clog change will set the
     608             :      * LSN correctly.
     609             :      */
     610       10645 :     if (!XLogRecPtrIsInvalid(lsn))
     611             :     {
     612         406 :         int         lsnindex = GetLSNIndex(slotno, xid);
     613             : 
     614         406 :         if (ClogCtl->shared->group_lsn[lsnindex] < lsn)
     615         404 :             ClogCtl->shared->group_lsn[lsnindex] = lsn;
     616             :     }
     617             : }
     618             : 
     619             : /*
     620             :  * Interrogate the state of a transaction in the commit log.
     621             :  *
     622             :  * Aside from the actual commit status, this function returns (into *lsn)
     623             :  * an LSN that is late enough to be able to guarantee that if we flush up to
     624             :  * that LSN then we will have flushed the transaction's commit record to disk.
     625             :  * The result is not necessarily the exact LSN of the transaction's commit
     626             :  * record!  For example, for long-past transactions (those whose clog pages
     627             :  * already migrated to disk), we'll return InvalidXLogRecPtr.  Also, because
     628             :  * we group transactions on the same clog page to conserve storage, we might
     629             :  * return the LSN of a later transaction that falls into the same group.
     630             :  *
     631             :  * NB: this is a low-level routine and is NOT the preferred entry point
     632             :  * for most uses; TransactionLogFetch() in transam.c is the intended caller.
     633             :  */
     634             : XidStatus
     635       30583 : TransactionIdGetStatus(TransactionId xid, XLogRecPtr *lsn)
     636             : {
     637       30583 :     int         pageno = TransactionIdToPage(xid);
     638       30583 :     int         byteno = TransactionIdToByte(xid);
     639       30583 :     int         bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
     640             :     int         slotno;
     641             :     int         lsnindex;
     642             :     char       *byteptr;
     643             :     XidStatus   status;
     644             : 
     645             :     /* lock is acquired by SimpleLruReadPage_ReadOnly */
     646             : 
     647       30583 :     slotno = SimpleLruReadPage_ReadOnly(ClogCtl, pageno, xid);
     648       30583 :     byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
     649             : 
     650       30583 :     status = (*byteptr >> bshift) & CLOG_XACT_BITMASK;
     651             : 
     652       30583 :     lsnindex = GetLSNIndex(slotno, xid);
     653       30583 :     *lsn = ClogCtl->shared->group_lsn[lsnindex];
     654             : 
     655       30583 :     LWLockRelease(CLogControlLock);
     656             : 
     657       30583 :     return status;
     658             : }
     659             : 
     660             : /*
     661             :  * Number of shared CLOG buffers.
     662             :  *
     663             :  * On larger multi-processor systems, it is possible to have many CLOG page
     664             :  * requests in flight at one time which could lead to disk access for CLOG
     665             :  * page if the required page is not found in memory.  Testing revealed that we
     666             :  * can get the best performance by having 128 CLOG buffers, more than that it
     667             :  * doesn't improve performance.
     668             :  *
     669             :  * Unconditionally keeping the number of CLOG buffers to 128 did not seem like
     670             :  * a good idea, because it would increase the minimum amount of shared memory
     671             :  * required to start, which could be a problem for people running very small
     672             :  * configurations.  The following formula seems to represent a reasonable
     673             :  * compromise: people with very low values for shared_buffers will get fewer
     674             :  * CLOG buffers as well, and everyone else will get 128.
     675             :  */
     676             : Size
     677          10 : CLOGShmemBuffers(void)
     678             : {
     679          10 :     return Min(128, Max(4, NBuffers / 512));
     680             : }
     681             : 
     682             : /*
     683             :  * Initialization of shared memory for CLOG
     684             :  */
     685             : Size
     686           5 : CLOGShmemSize(void)
     687             : {
     688           5 :     return SimpleLruShmemSize(CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE);
     689             : }
     690             : 
     691             : void
     692           5 : CLOGShmemInit(void)
     693             : {
     694           5 :     ClogCtl->PagePrecedes = CLOGPagePrecedes;
     695           5 :     SimpleLruInit(ClogCtl, "clog", CLOGShmemBuffers(), CLOG_LSNS_PER_PAGE,
     696           5 :                   CLogControlLock, "pg_xact", LWTRANCHE_CLOG_BUFFERS);
     697           5 : }
     698             : 
     699             : /*
     700             :  * This func must be called ONCE on system install.  It creates
     701             :  * the initial CLOG segment.  (The CLOG directory is assumed to
     702             :  * have been created by initdb, and CLOGShmemInit must have been
     703             :  * called already.)
     704             :  */
     705             : void
     706           1 : BootStrapCLOG(void)
     707             : {
     708             :     int         slotno;
     709             : 
     710           1 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     711             : 
     712             :     /* Create and zero the first page of the commit log */
     713           1 :     slotno = ZeroCLOGPage(0, false);
     714             : 
     715             :     /* Make sure it's written out */
     716           1 :     SimpleLruWritePage(ClogCtl, slotno);
     717           1 :     Assert(!ClogCtl->shared->page_dirty[slotno]);
     718             : 
     719           1 :     LWLockRelease(CLogControlLock);
     720           1 : }
     721             : 
     722             : /*
     723             :  * Initialize (or reinitialize) a page of CLOG to zeroes.
     724             :  * If writeXlog is TRUE, also emit an XLOG record saying we did this.
     725             :  *
     726             :  * The page is not actually written, just set up in shared memory.
     727             :  * The slot number of the new page is returned.
     728             :  *
     729             :  * Control lock must be held at entry, and will be held at exit.
     730             :  */
     731             : static int
     732           2 : ZeroCLOGPage(int pageno, bool writeXlog)
     733             : {
     734             :     int         slotno;
     735             : 
     736           2 :     slotno = SimpleLruZeroPage(ClogCtl, pageno);
     737             : 
     738           2 :     if (writeXlog)
     739           1 :         WriteZeroPageXlogRec(pageno);
     740             : 
     741           2 :     return slotno;
     742             : }
     743             : 
     744             : /*
     745             :  * This must be called ONCE during postmaster or standalone-backend startup,
     746             :  * after StartupXLOG has initialized ShmemVariableCache->nextXid.
     747             :  */
     748             : void
     749           3 : StartupCLOG(void)
     750             : {
     751           3 :     TransactionId xid = ShmemVariableCache->nextXid;
     752           3 :     int         pageno = TransactionIdToPage(xid);
     753             : 
     754           3 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     755             : 
     756             :     /*
     757             :      * Initialize our idea of the latest page number.
     758             :      */
     759           3 :     ClogCtl->shared->latest_page_number = pageno;
     760             : 
     761           3 :     LWLockRelease(CLogControlLock);
     762           3 : }
     763             : 
     764             : /*
     765             :  * This must be called ONCE at the end of startup/recovery.
     766             :  */
     767             : void
     768           3 : TrimCLOG(void)
     769             : {
     770           3 :     TransactionId xid = ShmemVariableCache->nextXid;
     771           3 :     int         pageno = TransactionIdToPage(xid);
     772             : 
     773           3 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     774             : 
     775             :     /*
     776             :      * Re-Initialize our idea of the latest page number.
     777             :      */
     778           3 :     ClogCtl->shared->latest_page_number = pageno;
     779             : 
     780             :     /*
     781             :      * Zero out the remainder of the current clog page.  Under normal
     782             :      * circumstances it should be zeroes already, but it seems at least
     783             :      * theoretically possible that XLOG replay will have settled on a nextXID
     784             :      * value that is less than the last XID actually used and marked by the
     785             :      * previous database lifecycle (since subtransaction commit writes clog
     786             :      * but makes no WAL entry).  Let's just be safe. (We need not worry about
     787             :      * pages beyond the current one, since those will be zeroed when first
     788             :      * used.  For the same reason, there is no need to do anything when
     789             :      * nextXid is exactly at a page boundary; and it's likely that the
     790             :      * "current" page doesn't exist yet in that case.)
     791             :      */
     792           3 :     if (TransactionIdToPgIndex(xid) != 0)
     793             :     {
     794           3 :         int         byteno = TransactionIdToByte(xid);
     795           3 :         int         bshift = TransactionIdToBIndex(xid) * CLOG_BITS_PER_XACT;
     796             :         int         slotno;
     797             :         char       *byteptr;
     798             : 
     799           3 :         slotno = SimpleLruReadPage(ClogCtl, pageno, false, xid);
     800           3 :         byteptr = ClogCtl->shared->page_buffer[slotno] + byteno;
     801             : 
     802             :         /* Zero so-far-unused positions in the current byte */
     803           3 :         *byteptr &= (1 << bshift) - 1;
     804             :         /* Zero the rest of the page */
     805           3 :         MemSet(byteptr + 1, 0, BLCKSZ - byteno - 1);
     806             : 
     807           3 :         ClogCtl->shared->page_dirty[slotno] = true;
     808             :     }
     809             : 
     810           3 :     LWLockRelease(CLogControlLock);
     811           3 : }
     812             : 
     813             : /*
     814             :  * This must be called ONCE during postmaster or standalone-backend shutdown
     815             :  */
     816             : void
     817           3 : ShutdownCLOG(void)
     818             : {
     819             :     /* Flush dirty CLOG pages to disk */
     820             :     TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(false);
     821           3 :     SimpleLruFlush(ClogCtl, false);
     822             : 
     823             :     /*
     824             :      * fsync pg_xact to ensure that any files flushed previously are durably
     825             :      * on disk.
     826             :      */
     827           3 :     fsync_fname("pg_xact", true);
     828             : 
     829             :     TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(false);
     830           3 : }
     831             : 
     832             : /*
     833             :  * Perform a checkpoint --- either during shutdown, or on-the-fly
     834             :  */
     835             : void
     836          11 : CheckPointCLOG(void)
     837             : {
     838             :     /* Flush dirty CLOG pages to disk */
     839             :     TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(true);
     840          11 :     SimpleLruFlush(ClogCtl, true);
     841             : 
     842             :     /*
     843             :      * fsync pg_xact to ensure that any files flushed previously are durably
     844             :      * on disk.
     845             :      */
     846          11 :     fsync_fname("pg_xact", true);
     847             : 
     848             :     TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(true);
     849          11 : }
     850             : 
     851             : 
     852             : /*
     853             :  * Make sure that CLOG has room for a newly-allocated XID.
     854             :  *
     855             :  * NB: this is called while holding XidGenLock.  We want it to be very fast
     856             :  * most of the time; even when it's not so fast, no actual I/O need happen
     857             :  * unless we're forced to write out a dirty clog or xlog page to make room
     858             :  * in shared memory.
     859             :  */
     860             : void
     861       10625 : ExtendCLOG(TransactionId newestXact)
     862             : {
     863             :     int         pageno;
     864             : 
     865             :     /*
     866             :      * No work except at first XID of a page.  But beware: just after
     867             :      * wraparound, the first XID of page zero is FirstNormalTransactionId.
     868             :      */
     869       10625 :     if (TransactionIdToPgIndex(newestXact) != 0 &&
     870             :         !TransactionIdEquals(newestXact, FirstNormalTransactionId))
     871       21249 :         return;
     872             : 
     873           1 :     pageno = TransactionIdToPage(newestXact);
     874             : 
     875           1 :     LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
     876             : 
     877             :     /* Zero the page and make an XLOG entry about it */
     878           1 :     ZeroCLOGPage(pageno, true);
     879             : 
     880           1 :     LWLockRelease(CLogControlLock);
     881             : }
     882             : 
     883             : 
     884             : /*
     885             :  * Remove all CLOG segments before the one holding the passed transaction ID
     886             :  *
     887             :  * Before removing any CLOG data, we must flush XLOG to disk, to ensure
     888             :  * that any recently-emitted HEAP_FREEZE records have reached disk; otherwise
     889             :  * a crash and restart might leave us with some unfrozen tuples referencing
     890             :  * removed CLOG data.  We choose to emit a special TRUNCATE XLOG record too.
     891             :  * Replaying the deletion from XLOG is not critical, since the files could
     892             :  * just as well be removed later, but doing so prevents a long-running hot
     893             :  * standby server from acquiring an unreasonably bloated CLOG directory.
     894             :  *
     895             :  * Since CLOG segments hold a large number of transactions, the opportunity to
     896             :  * actually remove a segment is fairly rare, and so it seems best not to do
     897             :  * the XLOG flush unless we have confirmed that there is a removable segment.
     898             :  */
     899             : void
     900           2 : TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
     901             : {
     902             :     int         cutoffPage;
     903             : 
     904             :     /*
     905             :      * The cutoff point is the start of the segment containing oldestXact. We
     906             :      * pass the *page* containing oldestXact to SimpleLruTruncate.
     907             :      */
     908           2 :     cutoffPage = TransactionIdToPage(oldestXact);
     909             : 
     910             :     /* Check to see if there's any files that could be removed */
     911           2 :     if (!SlruScanDirectory(ClogCtl, SlruScanDirCbReportPresence, &cutoffPage))
     912           4 :         return;                 /* nothing to remove */
     913             : 
     914             :     /*
     915             :      * Advance oldestClogXid before truncating clog, so concurrent xact status
     916             :      * lookups can ensure they don't attempt to access truncated-away clog.
     917             :      *
     918             :      * It's only necessary to do this if we will actually truncate away clog
     919             :      * pages.
     920             :      */
     921           0 :     AdvanceOldestClogXid(oldestXact);
     922             : 
     923             :     /*
     924             :      * Write XLOG record and flush XLOG to disk. We record the oldest xid
     925             :      * we're keeping information about here so we can ensure that it's always
     926             :      * ahead of clog truncation in case we crash, and so a standby finds out
     927             :      * the new valid xid before the next checkpoint.
     928             :      */
     929           0 :     WriteTruncateXlogRec(cutoffPage, oldestXact, oldestxid_datoid);
     930             : 
     931             :     /* Now we can remove the old CLOG segment(s) */
     932           0 :     SimpleLruTruncate(ClogCtl, cutoffPage);
     933             : }
     934             : 
     935             : 
     936             : /*
     937             :  * Decide which of two CLOG page numbers is "older" for truncation purposes.
     938             :  *
     939             :  * We need to use comparison of TransactionIds here in order to do the right
     940             :  * thing with wraparound XID arithmetic.  However, if we are asked about
     941             :  * page number zero, we don't want to hand InvalidTransactionId to
     942             :  * TransactionIdPrecedes: it'll get weird about permanent xact IDs.  So,
     943             :  * offset both xids by FirstNormalTransactionId to avoid that.
     944             :  */
     945             : static bool
     946           2 : CLOGPagePrecedes(int page1, int page2)
     947             : {
     948             :     TransactionId xid1;
     949             :     TransactionId xid2;
     950             : 
     951           2 :     xid1 = ((TransactionId) page1) * CLOG_XACTS_PER_PAGE;
     952           2 :     xid1 += FirstNormalTransactionId;
     953           2 :     xid2 = ((TransactionId) page2) * CLOG_XACTS_PER_PAGE;
     954           2 :     xid2 += FirstNormalTransactionId;
     955             : 
     956           2 :     return TransactionIdPrecedes(xid1, xid2);
     957             : }
     958             : 
     959             : 
     960             : /*
     961             :  * Write a ZEROPAGE xlog record
     962             :  */
     963             : static void
     964           1 : WriteZeroPageXlogRec(int pageno)
     965             : {
     966           1 :     XLogBeginInsert();
     967           1 :     XLogRegisterData((char *) (&pageno), sizeof(int));
     968           1 :     (void) XLogInsert(RM_CLOG_ID, CLOG_ZEROPAGE);
     969           1 : }
     970             : 
     971             : /*
     972             :  * Write a TRUNCATE xlog record
     973             :  *
     974             :  * We must flush the xlog record to disk before returning --- see notes
     975             :  * in TruncateCLOG().
     976             :  */
     977             : static void
     978           0 : WriteTruncateXlogRec(int pageno, TransactionId oldestXact, Oid oldestXactDb)
     979             : {
     980             :     XLogRecPtr  recptr;
     981             :     xl_clog_truncate xlrec;
     982             : 
     983           0 :     xlrec.pageno = pageno;
     984           0 :     xlrec.oldestXact = oldestXact;
     985           0 :     xlrec.oldestXactDb = oldestXactDb;
     986             : 
     987           0 :     XLogBeginInsert();
     988           0 :     XLogRegisterData((char *) (&xlrec), sizeof(xl_clog_truncate));
     989           0 :     recptr = XLogInsert(RM_CLOG_ID, CLOG_TRUNCATE);
     990           0 :     XLogFlush(recptr);
     991           0 : }
     992             : 
     993             : /*
     994             :  * CLOG resource manager's routines
     995             :  */
     996             : void
     997           0 : clog_redo(XLogReaderState *record)
     998             : {
     999           0 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    1000             : 
    1001             :     /* Backup blocks are not used in clog records */
    1002           0 :     Assert(!XLogRecHasAnyBlockRefs(record));
    1003             : 
    1004           0 :     if (info == CLOG_ZEROPAGE)
    1005             :     {
    1006             :         int         pageno;
    1007             :         int         slotno;
    1008             : 
    1009           0 :         memcpy(&pageno, XLogRecGetData(record), sizeof(int));
    1010             : 
    1011           0 :         LWLockAcquire(CLogControlLock, LW_EXCLUSIVE);
    1012             : 
    1013           0 :         slotno = ZeroCLOGPage(pageno, false);
    1014           0 :         SimpleLruWritePage(ClogCtl, slotno);
    1015           0 :         Assert(!ClogCtl->shared->page_dirty[slotno]);
    1016             : 
    1017           0 :         LWLockRelease(CLogControlLock);
    1018             :     }
    1019           0 :     else if (info == CLOG_TRUNCATE)
    1020             :     {
    1021             :         xl_clog_truncate xlrec;
    1022             : 
    1023           0 :         memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_clog_truncate));
    1024             : 
    1025             :         /*
    1026             :          * During XLOG replay, latest_page_number isn't set up yet; insert a
    1027             :          * suitable value to bypass the sanity test in SimpleLruTruncate.
    1028             :          */
    1029           0 :         ClogCtl->shared->latest_page_number = xlrec.pageno;
    1030             : 
    1031           0 :         AdvanceOldestClogXid(xlrec.oldestXact);
    1032             : 
    1033           0 :         SimpleLruTruncate(ClogCtl, xlrec.pageno);
    1034             :     }
    1035             :     else
    1036           0 :         elog(PANIC, "clog_redo: unknown op code %u", info);
    1037           0 : }

Generated by: LCOV version 1.11