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

Generated by: LCOV version 1.13