LCOV - code coverage report
Current view: top level - src/backend/access/transam - multixact.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 77.4 % 744 576
Test Date: 2026-11-23 21:16:22 Functions: 80.0 % 60 48
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 56.1 % 337 189

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * multixact.c
       4                 :             :  *      PostgreSQL multi-transaction-log manager
       5                 :             :  *
       6                 :             :  * The pg_multixact manager is a pg_xact-like manager that stores an array of
       7                 :             :  * MultiXactMember for each MultiXactId.  It is a fundamental part of the
       8                 :             :  * shared-row-lock implementation.  Each MultiXactMember is comprised of a
       9                 :             :  * TransactionId and a set of flag bits.  The name is a bit historical:
      10                 :             :  * originally, a MultiXactId consisted of more than one TransactionId (except
      11                 :             :  * in rare corner cases), hence "multi".  Nowadays, however, it's perfectly
      12                 :             :  * legitimate to have MultiXactIds that only include a single Xid.
      13                 :             :  *
      14                 :             :  * The meaning of the flag bits is opaque to this module, but they are mostly
      15                 :             :  * used in heapam.c to identify lock modes that each of the member transactions
      16                 :             :  * is holding on any given tuple.  This module just contains support to store
      17                 :             :  * and retrieve the arrays.
      18                 :             :  *
      19                 :             :  * We use two SLRU areas, one for storing the offsets at which the data
      20                 :             :  * starts for each MultiXactId in the other one.  This trick allows us to
      21                 :             :  * store variable length arrays of TransactionIds.  (We could alternatively
      22                 :             :  * use one area containing counts and TransactionIds, with valid MultiXactId
      23                 :             :  * values pointing at slots containing counts; but that way seems less robust
      24                 :             :  * since it would get completely confused if someone inquired about a bogus
      25                 :             :  * MultiXactId that pointed to an intermediate slot containing an XID.)
      26                 :             :  *
      27                 :             :  * XLOG interactions: this module generates a record whenever a new OFFSETs or
      28                 :             :  * MEMBERs page is initialized to zeroes, as well as an
      29                 :             :  * XLOG_MULTIXACT_CREATE_ID record whenever a new MultiXactId is defined.
      30                 :             :  * This module ignores the WAL rule "write xlog before data," because it
      31                 :             :  * suffices that actions recording a MultiXactId in a heap xmax do follow that
      32                 :             :  * rule.  The only way for the MXID to be referenced from any data page is for
      33                 :             :  * heap_lock_tuple() or heap_update() to have put it there, and each generates
      34                 :             :  * an XLOG record that must follow ours.  The normal LSN interlock between the
      35                 :             :  * data page and that XLOG record will ensure that our XLOG record reaches
      36                 :             :  * disk first.  If the SLRU members/offsets data reaches disk sooner than the
      37                 :             :  * XLOG records, we do not care; after recovery, no xmax will refer to it.  On
      38                 :             :  * the flip side, to ensure that all referenced entries _do_ reach disk, this
      39                 :             :  * module's XLOG records completely rebuild the data entered since the last
      40                 :             :  * checkpoint.  We flush and sync all dirty OFFSETs and MEMBERs pages to disk
      41                 :             :  * before each checkpoint is considered complete.
      42                 :             :  *
      43                 :             :  * Like clog.c, and unlike subtrans.c, we have to preserve state across
      44                 :             :  * crashes and ensure that MXID and offset numbering increases monotonically
      45                 :             :  * across a crash.  We do this in the same way as it's done for transaction
      46                 :             :  * IDs: the WAL record is guaranteed to contain evidence of every MXID we
      47                 :             :  * could need to worry about, and we just make sure that at the end of
      48                 :             :  * replay, the next-MXID and next-offset counters are at least as large as
      49                 :             :  * anything we saw during replay.
      50                 :             :  *
      51                 :             :  * We are able to remove segments no longer necessary by carefully tracking
      52                 :             :  * each table's used values: during vacuum, any multixact older than a certain
      53                 :             :  * value is removed; the cutoff value is stored in pg_class.  The minimum value
      54                 :             :  * across all tables in each database is stored in pg_database, and the global
      55                 :             :  * minimum across all databases is part of pg_control and is kept in shared
      56                 :             :  * memory.  Whenever that minimum is advanced, the SLRUs are truncated.
      57                 :             :  *
      58                 :             :  * When new multixactid values are to be created, care is taken that the
      59                 :             :  * counter does not fall within the wraparound horizon considering the global
      60                 :             :  * minimum value.
      61                 :             :  *
      62                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      63                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      64                 :             :  *
      65                 :             :  * src/backend/access/transam/multixact.c
      66                 :             :  *
      67                 :             :  *-------------------------------------------------------------------------
      68                 :             :  */
      69                 :             : #include "postgres.h"
      70                 :             : 
      71                 :             : #include "access/multixact.h"
      72                 :             : #include "access/multixact_internal.h"
      73                 :             : #include "access/slru.h"
      74                 :             : #include "access/twophase.h"
      75                 :             : #include "access/twophase_rmgr.h"
      76                 :             : #include "access/xlog.h"
      77                 :             : #include "access/xloginsert.h"
      78                 :             : #include "access/xlogutils.h"
      79                 :             : #include "miscadmin.h"
      80                 :             : #include "pg_trace.h"
      81                 :             : #include "pgstat.h"
      82                 :             : #include "postmaster/autovacuum.h"
      83                 :             : #include "storage/pmsignal.h"
      84                 :             : #include "storage/proc.h"
      85                 :             : #include "storage/procarray.h"
      86                 :             : #include "storage/subsystems.h"
      87                 :             : #include "utils/guc_hooks.h"
      88                 :             : #include "utils/injection_point.h"
      89                 :             : #include "utils/lsyscache.h"
      90                 :             : #include "utils/memutils.h"
      91                 :             : 
      92                 :             : 
      93                 :             : /*
      94                 :             :  * Thresholds used to keep members disk usage in check when multixids have a
      95                 :             :  * lot of members.  When MULTIXACT_MEMBER_LOW_THRESHOLD is reached, vacuum
      96                 :             :  * starts freezing multixids more aggressively, even if the normal multixid
      97                 :             :  * age limits haven't been reached yet.
      98                 :             :  */
      99                 :             : #define MULTIXACT_MEMBER_LOW_THRESHOLD      UINT64CONST(2000000000)
     100                 :             : #define MULTIXACT_MEMBER_HIGH_THRESHOLD     UINT64CONST(4000000000)
     101                 :             : 
     102                 :             : static inline MultiXactId
     103                 :      107792 : NextMultiXactId(MultiXactId multi)
     104                 :             : {
     105         [ +  + ]:      107792 :     return multi == MaxMultiXactId ? FirstMultiXactId : multi + 1;
     106                 :             : }
     107                 :             : 
     108                 :             : static inline MultiXactId
     109                 :           0 : PreviousMultiXactId(MultiXactId multi)
     110                 :             : {
     111         [ #  # ]:           0 :     return multi == FirstMultiXactId ? MaxMultiXactId : multi - 1;
     112                 :             : }
     113                 :             : 
     114                 :             : /*
     115                 :             :  * Links to shared-memory data structures for MultiXact control
     116                 :             :  */
     117                 :             : static bool MultiXactOffsetPagePrecedes(int64 page1, int64 page2);
     118                 :             : static int  MultiXactOffsetIoErrorDetail(const void *opaque_data);
     119                 :             : static bool MultiXactMemberPagePrecedes(int64 page1, int64 page2);
     120                 :             : static int  MultiXactMemberIoErrorDetail(const void *opaque_data);
     121                 :             : 
     122                 :             : static SlruDesc MultiXactOffsetSlruDesc;
     123                 :             : static SlruDesc MultiXactMemberSlruDesc;
     124                 :             : 
     125                 :             : #define MultiXactOffsetCtl  (&MultiXactOffsetSlruDesc)
     126                 :             : #define MultiXactMemberCtl  (&MultiXactMemberSlruDesc)
     127                 :             : 
     128                 :             : /*
     129                 :             :  * MultiXact state shared across all backends.  All this state is protected
     130                 :             :  * by MultiXactGenLock.  (We also use SLRU bank's lock of MultiXactOffset and
     131                 :             :  * MultiXactMember to guard accesses to the two sets of SLRU buffers.  For
     132                 :             :  * concurrency's sake, we avoid holding more than one of these locks at a
     133                 :             :  * time.)
     134                 :             :  */
     135                 :             : typedef struct MultiXactStateData
     136                 :             : {
     137                 :             :     /* next-to-be-assigned MultiXactId */
     138                 :             :     MultiXactId nextMXact;
     139                 :             : 
     140                 :             :     /* next-to-be-assigned offset */
     141                 :             :     MultiXactOffset nextOffset;
     142                 :             : 
     143                 :             :     /* Have we completed multixact startup? */
     144                 :             :     bool        finishedStartup;
     145                 :             : 
     146                 :             :     /*
     147                 :             :      * Oldest multixact that is still potentially referenced by a relation.
     148                 :             :      * Anything older than this should not be consulted.  These values are
     149                 :             :      * updated by vacuum.
     150                 :             :      */
     151                 :             :     MultiXactId oldestMultiXactId;
     152                 :             :     Oid         oldestMultiXactDB;
     153                 :             : 
     154                 :             :     /*
     155                 :             :      * Oldest multixact offset that is potentially referenced by a multixact
     156                 :             :      * referenced by a relation.
     157                 :             :      */
     158                 :             :     MultiXactOffset oldestOffset;
     159                 :             : 
     160                 :             :     /* support for anti-wraparound measures */
     161                 :             :     MultiXactId multiVacLimit;
     162                 :             :     MultiXactId multiWarnLimit;
     163                 :             :     MultiXactId multiStopLimit;
     164                 :             :     MultiXactId multiWrapLimit;
     165                 :             : 
     166                 :             :     /*
     167                 :             :      * Per-backend data starts here.  We have two arrays stored in the area
     168                 :             :      * immediately following the MultiXactStateData struct:
     169                 :             :      *
     170                 :             :      * OldestMemberMXactId[k] is the oldest MultiXactId each backend's current
     171                 :             :      * transaction(s) could possibly be a member of, or InvalidMultiXactId
     172                 :             :      * when the backend has no live transaction that could possibly be a
     173                 :             :      * member of a MultiXact.  Each backend sets its entry to the current
     174                 :             :      * nextMXact counter just before first acquiring a shared lock in a given
     175                 :             :      * transaction, and clears it at transaction end. (This works because only
     176                 :             :      * during or after acquiring a shared lock could an XID possibly become a
     177                 :             :      * member of a MultiXact, and that MultiXact would have to be created
     178                 :             :      * during or after the lock acquisition.)
     179                 :             :      *
     180                 :             :      * In the OldestMemberMXactId array, there's a slot for all normal
     181                 :             :      * backends (0..MaxBackends-1) followed by a slot for max_prepared_xacts
     182                 :             :      * prepared transactions.
     183                 :             :      *
     184                 :             :      * OldestVisibleMXactId[k] is the oldest MultiXactId each backend's
     185                 :             :      * current transaction(s) think is potentially live, or InvalidMultiXactId
     186                 :             :      * when not in a transaction or not in a transaction that's paid any
     187                 :             :      * attention to MultiXacts yet.  This is computed when first needed in a
     188                 :             :      * given transaction, and cleared at transaction end.  We can compute it
     189                 :             :      * as the minimum of the valid OldestMemberMXactId[] entries at the time
     190                 :             :      * we compute it (using nextMXact if none are valid).  Each backend is
     191                 :             :      * required not to attempt to access any SLRU data for MultiXactIds older
     192                 :             :      * than its own OldestVisibleMXactId[] setting; this is necessary because
     193                 :             :      * the relevant SLRU data can be concurrently truncated away.
     194                 :             :      *
     195                 :             :      * In the OldestVisibleMXactId array, there's a slot for all normal
     196                 :             :      * backends (0..MaxBackends-1) only. No slots for prepared transactions.
     197                 :             :      *
     198                 :             :      * The oldest valid value among all of the OldestMemberMXactId[] and
     199                 :             :      * OldestVisibleMXactId[] entries is considered by vacuum as the earliest
     200                 :             :      * possible value still having any live member transaction -- OldestMxact.
     201                 :             :      * Any value older than that is typically removed from tuple headers, or
     202                 :             :      * "frozen" via being replaced with a new xmax.  VACUUM can sometimes even
     203                 :             :      * remove an individual MultiXact xmax whose value is >= its OldestMxact
     204                 :             :      * cutoff, though typically only when no individual member XID is still
     205                 :             :      * running.  See FreezeMultiXactId for full details.
     206                 :             :      *
     207                 :             :      * Whenever VACUUM advances relminmxid, then either its OldestMxact cutoff
     208                 :             :      * or the oldest extant Multi remaining in the table is used as the new
     209                 :             :      * pg_class.relminmxid value (whichever is earlier).  The minimum of all
     210                 :             :      * relminmxid values in each database is stored in pg_database.datminmxid.
     211                 :             :      * In turn, the minimum of all of those values is stored in pg_control.
     212                 :             :      * This is used as the truncation point for pg_multixact when unneeded
     213                 :             :      * segments get removed by vac_truncate_clog() during vacuuming.
     214                 :             :      */
     215                 :             :     MultiXactId perBackendXactIds[FLEXIBLE_ARRAY_MEMBER];
     216                 :             : } MultiXactStateData;
     217                 :             : 
     218                 :             : /*
     219                 :             :  * Sizes of OldestMemberMXactId and OldestVisibleMXactId arrays.
     220                 :             :  */
     221                 :             : #define NumMemberSlots      (MaxBackends + max_prepared_xacts)
     222                 :             : #define NumVisibleSlots     MaxBackends
     223                 :             : 
     224                 :             : /* Pointers to the state data in shared memory */
     225                 :             : static MultiXactStateData *MultiXactState;
     226                 :             : static MultiXactId *OldestMemberMXactId;
     227                 :             : static MultiXactId *OldestVisibleMXactId;
     228                 :             : 
     229                 :             : static void MultiXactShmemRequest(void *arg);
     230                 :             : static void MultiXactShmemInit(void *arg);
     231                 :             : static void MultiXactShmemAttach(void *arg);
     232                 :             : 
     233                 :             : const ShmemCallbacks MultiXactShmemCallbacks = {
     234                 :             :     .request_fn = MultiXactShmemRequest,
     235                 :             :     .init_fn = MultiXactShmemInit,
     236                 :             :     .attach_fn = MultiXactShmemAttach,
     237                 :             : };
     238                 :             : 
     239                 :             : static inline MultiXactId *
     240                 :     5277452 : MyOldestMemberMXactIdSlot(void)
     241                 :             : {
     242                 :             :     /*
     243                 :             :      * The first MaxBackends entries in the OldestMemberMXactId array are
     244                 :             :      * reserved for regular backends.  MyProcNumber should index into one of
     245                 :             :      * them.
     246                 :             :      */
     247                 :             :     Assert(MyProcNumber >= 0 && MyProcNumber < MaxBackends);
     248                 :     5277452 :     return &OldestMemberMXactId[MyProcNumber];
     249                 :             : }
     250                 :             : 
     251                 :             : static inline MultiXactId *
     252                 :         158 : PreparedXactOldestMemberMXactIdSlot(ProcNumber procno)
     253                 :             : {
     254                 :             :     int         prepared_xact_idx;
     255                 :             : 
     256                 :             :     Assert(procno >= FIRST_PREPARED_XACT_PROC_NUMBER);
     257                 :         158 :     prepared_xact_idx = procno - FIRST_PREPARED_XACT_PROC_NUMBER;
     258                 :             : 
     259                 :             :     /*
     260                 :             :      * The first MaxBackends entries in the OldestMemberMXactId array are
     261                 :             :      * reserved for regular backends.  Prepared xacts come after them.
     262                 :             :      */
     263                 :             :     Assert(MaxBackends + prepared_xact_idx < NumMemberSlots);
     264                 :         158 :     return &OldestMemberMXactId[MaxBackends + prepared_xact_idx];
     265                 :             : }
     266                 :             : 
     267                 :             : static inline MultiXactId *
     268                 :      754703 : MyOldestVisibleMXactIdSlot(void)
     269                 :             : {
     270                 :             :     Assert(MyProcNumber >= 0 && MyProcNumber < NumVisibleSlots);
     271                 :      754703 :     return &OldestVisibleMXactId[MyProcNumber];
     272                 :             : }
     273                 :             : 
     274                 :             : /*
     275                 :             :  * Definitions for the backend-local MultiXactId cache.
     276                 :             :  *
     277                 :             :  * We use this cache to store known MultiXacts, so we don't need to go to
     278                 :             :  * SLRU areas every time.
     279                 :             :  *
     280                 :             :  * The cache lasts for the duration of a single transaction, the rationale
     281                 :             :  * for this being that most entries will contain our own TransactionId and
     282                 :             :  * so they will be uninteresting by the time our next transaction starts.
     283                 :             :  * (XXX not clear that this is correct --- other members of the MultiXact
     284                 :             :  * could hang around longer than we did.  However, it's not clear what a
     285                 :             :  * better policy for flushing old cache entries would be.)  FIXME actually
     286                 :             :  * this is plain wrong now that multixact's may contain update Xids.
     287                 :             :  *
     288                 :             :  * We allocate the cache entries in a memory context that is deleted at
     289                 :             :  * transaction end, so we don't need to do retail freeing of entries.
     290                 :             :  */
     291                 :             : typedef struct mXactCacheEnt
     292                 :             : {
     293                 :             :     MultiXactId multi;
     294                 :             :     int         nmembers;
     295                 :             :     dlist_node  node;
     296                 :             :     pg_attribute_counted_by(nmembers) MultiXactMember members[FLEXIBLE_ARRAY_MEMBER];
     297                 :             : } mXactCacheEnt;
     298                 :             : 
     299                 :             : #define MAX_CACHE_ENTRIES   256
     300                 :             : static dclist_head MXactCache = DCLIST_STATIC_INIT(MXactCache);
     301                 :             : static MemoryContext MXactContext = NULL;
     302                 :             : 
     303                 :             : #ifdef MULTIXACT_DEBUG
     304                 :             : #define debug_elog2(a,b) elog(a,b)
     305                 :             : #define debug_elog3(a,b,c) elog(a,b,c)
     306                 :             : #define debug_elog4(a,b,c,d) elog(a,b,c,d)
     307                 :             : #define debug_elog5(a,b,c,d,e) elog(a,b,c,d,e)
     308                 :             : #define debug_elog6(a,b,c,d,e,f) elog(a,b,c,d,e,f)
     309                 :             : #else
     310                 :             : #define debug_elog2(a,b)
     311                 :             : #define debug_elog3(a,b,c)
     312                 :             : #define debug_elog4(a,b,c,d)
     313                 :             : #define debug_elog5(a,b,c,d,e)
     314                 :             : #define debug_elog6(a,b,c,d,e,f)
     315                 :             : #endif
     316                 :             : 
     317                 :             : /* internal MultiXactId management */
     318                 :             : static void MultiXactIdSetOldestVisible(void);
     319                 :             : static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
     320                 :             :                                int nmembers, MultiXactMember *members);
     321                 :             : static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
     322                 :             : 
     323                 :             : /* MultiXact cache management */
     324                 :             : static int  mxactMemberComparator(const void *arg1, const void *arg2);
     325                 :             : static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members);
     326                 :             : static int  mXactCacheGetById(MultiXactId multi, MultiXactMember **members);
     327                 :             : static void mXactCachePut(MultiXactId multi, int nmembers,
     328                 :             :                           MultiXactMember *members);
     329                 :             : 
     330                 :             : /* management of SLRU infrastructure */
     331                 :             : 
     332                 :             : /* opaque_data type for MultiXactMemberIoErrorDetail */
     333                 :             : typedef struct MultiXactMemberSlruReadContext
     334                 :             : {
     335                 :             :     MultiXactId multi;
     336                 :             :     MultiXactOffset offset;
     337                 :             : } MultiXactMemberSlruReadContext;
     338                 :             : 
     339                 :             : static void ExtendMultiXactOffset(MultiXactId multi);
     340                 :             : static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers);
     341                 :             : static void SetOldestOffset(void);
     342                 :             : static bool find_multixact_start(MultiXactId multi, MultiXactOffset *result);
     343                 :             : static void WriteMTruncateXlogRec(Oid oldestMultiDB,
     344                 :             :                                   MultiXactId oldestMulti,
     345                 :             :                                   MultiXactOffset oldestOffset);
     346                 :             : 
     347                 :             : 
     348                 :             : /*
     349                 :             :  * MultiXactIdCreate
     350                 :             :  *      Construct a MultiXactId representing two TransactionIds.
     351                 :             :  *
     352                 :             :  * The two XIDs must be different, or be requesting different statuses.
     353                 :             :  *
     354                 :             :  * NB - we don't worry about our local MultiXactId cache here, because that
     355                 :             :  * is handled by the lower-level routines.
     356                 :             :  */
     357                 :             : MultiXactId
     358                 :        1134 : MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1,
     359                 :             :                   TransactionId xid2, MultiXactStatus status2)
     360                 :             : {
     361                 :             :     MultiXactId newMulti;
     362                 :             :     MultiXactMember members[2];
     363                 :             : 
     364                 :             :     Assert(TransactionIdIsValid(xid1));
     365                 :             :     Assert(TransactionIdIsValid(xid2));
     366                 :             : 
     367                 :             :     Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
     368                 :             : 
     369                 :             :     /* MultiXactIdSetOldestMember() must have been called already. */
     370                 :             :     Assert(MultiXactIdIsValid(*MyOldestMemberMXactIdSlot()));
     371                 :             : 
     372                 :             :     /*
     373                 :             :      * Note: unlike MultiXactIdExpand, we don't bother to check that both XIDs
     374                 :             :      * are still running.  In typical usage, xid2 will be our own XID and the
     375                 :             :      * caller just did a check on xid1, so it'd be wasted effort.
     376                 :             :      */
     377                 :             : 
     378                 :        1134 :     members[0].xid = xid1;
     379                 :        1134 :     members[0].status = status1;
     380                 :        1134 :     members[1].xid = xid2;
     381                 :        1134 :     members[1].status = status2;
     382                 :             : 
     383                 :        1134 :     newMulti = MultiXactIdCreateFromMembers(2, members);
     384                 :             : 
     385                 :             :     debug_elog3(DEBUG2, "Create: %s",
     386                 :             :                 mxid_to_string(newMulti, 2, members));
     387                 :             : 
     388                 :        1134 :     return newMulti;
     389                 :             : }
     390                 :             : 
     391                 :             : /*
     392                 :             :  * MultiXactIdExpand
     393                 :             :  *      Add a TransactionId to a pre-existing MultiXactId.
     394                 :             :  *
     395                 :             :  * If the TransactionId is already a member of the passed MultiXactId with the
     396                 :             :  * same status, just return it as-is.
     397                 :             :  *
     398                 :             :  * Note that we do NOT actually modify the membership of a pre-existing
     399                 :             :  * MultiXactId; instead we create a new one.  This is necessary to avoid
     400                 :             :  * a race condition against code trying to wait for one MultiXactId to finish;
     401                 :             :  * see notes in heapam.c.
     402                 :             :  *
     403                 :             :  * NB - we don't worry about our local MultiXactId cache here, because that
     404                 :             :  * is handled by the lower-level routines.
     405                 :             :  *
     406                 :             :  * Note: It is critical that MultiXactIds that come from an old cluster (i.e.
     407                 :             :  * one upgraded by pg_upgrade from a cluster older than this feature) are not
     408                 :             :  * passed in.
     409                 :             :  */
     410                 :             : MultiXactId
     411                 :       75557 : MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
     412                 :             : {
     413                 :             :     MultiXactId newMulti;
     414                 :             :     MultiXactMember *members;
     415                 :             :     MultiXactMember *newMembers;
     416                 :             :     int         nmembers;
     417                 :             :     int         i;
     418                 :             :     int         j;
     419                 :             :     bool        alreadyMember;
     420                 :             : 
     421                 :             :     Assert(MultiXactIdIsValid(multi));
     422                 :             :     Assert(TransactionIdIsValid(xid));
     423                 :             : 
     424                 :             :     /* MultiXactIdSetOldestMember() must have been called already. */
     425                 :             :     Assert(MultiXactIdIsValid(*MyOldestMemberMXactIdSlot()));
     426                 :             : 
     427                 :             :     debug_elog5(DEBUG2, "Expand: received multi %u, xid %u status %s",
     428                 :             :                 multi, xid, mxstatus_to_string(status));
     429                 :             : 
     430                 :             :     /*
     431                 :             :      * Note: we don't allow for old multis here.  The reason is that the only
     432                 :             :      * caller of this function does a check that the multixact is no longer
     433                 :             :      * running.
     434                 :             :      */
     435                 :       75557 :     nmembers = GetMultiXactIdMembers(multi, &members, false, false);
     436                 :             : 
     437         [ -  + ]:       75557 :     if (nmembers < 0)
     438                 :             :     {
     439                 :             :         MultiXactMember member;
     440                 :             : 
     441                 :             :         /*
     442                 :             :          * The MultiXactId is obsolete.  This can only happen if all the
     443                 :             :          * MultiXactId members stop running between the caller checking and
     444                 :             :          * passing it to us.  It would be better to return that fact to the
     445                 :             :          * caller, but it would complicate the API and it's unlikely to happen
     446                 :             :          * too often, so just deal with it by creating a singleton MultiXact.
     447                 :             :          */
     448                 :           0 :         member.xid = xid;
     449                 :           0 :         member.status = status;
     450                 :           0 :         newMulti = MultiXactIdCreateFromMembers(1, &member);
     451                 :             : 
     452                 :             :         debug_elog4(DEBUG2, "Expand: %u has no members, create singleton %u",
     453                 :             :                     multi, newMulti);
     454                 :           0 :         return newMulti;
     455                 :             :     }
     456                 :             : 
     457                 :             :     /*
     458                 :             :      * Determine which of the members of the MultiXactId are still of
     459                 :             :      * interest. This is any running transaction, and also any transaction
     460                 :             :      * that grabbed something stronger than just a lock and was committed. (An
     461                 :             :      * update that aborted is of no interest here; and having more than one
     462                 :             :      * update Xid in a multixact would cause errors elsewhere.)
     463                 :             :      *
     464                 :             :      * Removing dead members is not just an optimization: freezing of tuples
     465                 :             :      * whose Xmax are multis depends on this behavior.  This can also help the
     466                 :             :      * caller to calculate a weaker overall lock level for this multixid.  If
     467                 :             :      * e.g. the caller has already determined that the updating transaction is
     468                 :             :      * not running, it would be surprising for the result to still contain a
     469                 :             :      * member with MultiXactStatusUpdate.
     470                 :             :      *
     471                 :             :      * Note we have the same race condition here as above: j could be 0 at the
     472                 :             :      * end of the loop.
     473                 :             :      */
     474                 :       75557 :     newMembers = palloc_array(MultiXactMember, nmembers + 1);
     475                 :             : 
     476                 :       75557 :     alreadyMember = false;
     477         [ +  + ]:     1465997 :     for (i = 0, j = 0; i < nmembers; i++)
     478                 :             :     {
     479         [ +  + ]:     1390440 :         if (TransactionIdEquals(members[i].xid, xid) &&
     480         [ +  + ]:          62 :             (members[i].status == status))
     481                 :             :         {
     482                 :           4 :             alreadyMember = true;
     483                 :             :             debug_elog4(DEBUG2, "Expand: %u is already a member of %u",
     484                 :             :                         xid, multi);
     485                 :           4 :             newMembers[j].xid = xid;
     486                 :           4 :             newMembers[j++].status = status;
     487                 :             :         }
     488         [ +  + ]:     1390436 :         else if (TransactionIdIsInProgress(members[i].xid) ||
     489   [ +  +  -  + ]:       74717 :                  (ISUPDATE_from_mxstatus(members[i].status) &&
     490                 :          27 :                   TransactionIdDidCommit(members[i].xid)))
     491                 :             :         {
     492                 :     1315746 :             newMembers[j].xid = members[i].xid;
     493                 :     1315746 :             newMembers[j++].status = members[i].status;
     494                 :             :         }
     495                 :             :     }
     496                 :             : 
     497                 :             :     /*
     498                 :             :      * If the TransactionId is already a member of the MultiXactId with the
     499                 :             :      * same status, and there were no dead members to remove, just return the
     500                 :             :      * existing MultiXactId.  (The caching in MultiXactIdCreateFromMembers()
     501                 :             :      * would detect this case too, but let's save the effort.)
     502                 :             :      */
     503   [ +  +  -  + ]:       75557 :     if (alreadyMember && j == nmembers)
     504                 :             :     {
     505                 :           0 :         newMulti = multi;
     506                 :             :         debug_elog3(DEBUG2, "Expand: returning original multi %u", multi);
     507                 :             :     }
     508                 :             :     else
     509                 :             :     {
     510         [ +  + ]:       75557 :         if (!alreadyMember)
     511                 :             :         {
     512                 :       75553 :             newMembers[j].xid = xid;
     513                 :       75553 :             newMembers[j++].status = status;
     514                 :             :         }
     515                 :       75557 :         newMulti = MultiXactIdCreateFromMembers(j, newMembers);
     516                 :             :         debug_elog3(DEBUG2, "Expand: returning new multi %u", newMulti);
     517                 :             :     }
     518                 :             : 
     519                 :       75557 :     pfree(members);
     520                 :       75557 :     pfree(newMembers);
     521                 :             : 
     522                 :       75557 :     return newMulti;
     523                 :             : }
     524                 :             : 
     525                 :             : /*
     526                 :             :  * MultiXactIdIsRunning
     527                 :             :  *      Returns whether a MultiXactId is "running".
     528                 :             :  *
     529                 :             :  * We return true if at least one member of the given MultiXactId is still
     530                 :             :  * running.  Note that a "false" result is certain not to change,
     531                 :             :  * because it is not legal to add members to an existing MultiXactId.
     532                 :             :  *
     533                 :             :  * Caller is expected to have verified that the multixact does not come from
     534                 :             :  * a pg_upgraded share-locked tuple.
     535                 :             :  */
     536                 :             : bool
     537                 :      149884 : MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
     538                 :             : {
     539                 :             :     MultiXactMember *members;
     540                 :             :     int         nmembers;
     541                 :             :     int         i;
     542                 :             : 
     543                 :             :     debug_elog3(DEBUG2, "IsRunning %u?", multi);
     544                 :             : 
     545                 :             :     /*
     546                 :             :      * "false" here means we assume our callers have checked that the given
     547                 :             :      * multi cannot possibly come from a pg_upgraded database.
     548                 :             :      */
     549                 :      149884 :     nmembers = GetMultiXactIdMembers(multi, &members, false, isLockOnly);
     550                 :             : 
     551         [ +  + ]:      149884 :     if (nmembers <= 0)
     552                 :             :     {
     553                 :             :         debug_elog2(DEBUG2, "IsRunning: no members");
     554                 :         735 :         return false;
     555                 :             :     }
     556                 :             : 
     557                 :             :     /*
     558                 :             :      * Checking for myself is cheap compared to looking in shared memory;
     559                 :             :      * return true if any live subtransaction of the current top-level
     560                 :             :      * transaction is a member.
     561                 :             :      *
     562                 :             :      * This is not needed for correctness, it's just a fast path.
     563                 :             :      */
     564         [ +  + ]:     2891596 :     for (i = 0; i < nmembers; i++)
     565                 :             :     {
     566         [ +  + ]:     2742617 :         if (TransactionIdIsCurrentTransactionId(members[i].xid))
     567                 :             :         {
     568                 :             :             debug_elog3(DEBUG2, "IsRunning: I (%d) am running!", i);
     569                 :         170 :             pfree(members);
     570                 :         170 :             return true;
     571                 :             :         }
     572                 :             :     }
     573                 :             : 
     574                 :             :     /*
     575                 :             :      * This could be made faster by having another entry point in procarray.c,
     576                 :             :      * walking the PGPROC array only once for all the members.  But in most
     577                 :             :      * cases nmembers should be small enough that it doesn't much matter.
     578                 :             :      */
     579         [ +  + ]:      296203 :     for (i = 0; i < nmembers; i++)
     580                 :             :     {
     581         [ +  + ]:      296157 :         if (TransactionIdIsInProgress(members[i].xid))
     582                 :             :         {
     583                 :             :             debug_elog4(DEBUG2, "IsRunning: member %d (%u) is running",
     584                 :             :                         i, members[i].xid);
     585                 :      148933 :             pfree(members);
     586                 :      148933 :             return true;
     587                 :             :         }
     588                 :             :     }
     589                 :             : 
     590                 :          46 :     pfree(members);
     591                 :             : 
     592                 :             :     debug_elog3(DEBUG2, "IsRunning: %u is not running", multi);
     593                 :             : 
     594                 :          46 :     return false;
     595                 :             : }
     596                 :             : 
     597                 :             : /*
     598                 :             :  * MultiXactIdSetOldestMember
     599                 :             :  *      Save the oldest MultiXactId this transaction could be a member of.
     600                 :             :  *
     601                 :             :  * We set the OldestMemberMXactId for a given transaction the first time it's
     602                 :             :  * going to do some operation that might require a MultiXactId (tuple lock,
     603                 :             :  * update or delete).  We need to do this even if we end up using a
     604                 :             :  * TransactionId instead of a MultiXactId, because there is a chance that
     605                 :             :  * another transaction would add our XID to a MultiXactId.
     606                 :             :  *
     607                 :             :  * The value to set is the next-to-be-assigned MultiXactId, so this is meant to
     608                 :             :  * be called just before doing any such possibly-MultiXactId-able operation.
     609                 :             :  */
     610                 :             : void
     611                 :     4529606 : MultiXactIdSetOldestMember(void)
     612                 :             : {
     613         [ +  + ]:     4529606 :     if (!MultiXactIdIsValid(*MyOldestMemberMXactIdSlot()))
     614                 :             :     {
     615                 :             :         MultiXactId nextMXact;
     616                 :             : 
     617                 :             :         /*
     618                 :             :          * You might think we don't need to acquire a lock here, since
     619                 :             :          * fetching and storing of TransactionIds is probably atomic, but in
     620                 :             :          * fact we do: suppose we pick up nextMXact and then lose the CPU for
     621                 :             :          * a long time.  Someone else could advance nextMXact, and then
     622                 :             :          * another someone else could compute an OldestVisibleMXactId that
     623                 :             :          * would be after the value we are going to store when we get control
     624                 :             :          * back.  Which would be wrong.
     625                 :             :          *
     626                 :             :          * Note that a shared lock is sufficient, because it's enough to stop
     627                 :             :          * someone from advancing nextMXact; and nobody else could be trying
     628                 :             :          * to write to our OldestMember entry, only reading (and we assume
     629                 :             :          * storing it is atomic.)
     630                 :             :          */
     631                 :       92193 :         LWLockAcquire(MultiXactGenLock, LW_SHARED);
     632                 :             : 
     633                 :       92193 :         nextMXact = MultiXactState->nextMXact;
     634                 :             : 
     635                 :       92193 :         *MyOldestMemberMXactIdSlot() = nextMXact;
     636                 :             : 
     637                 :       92193 :         LWLockRelease(MultiXactGenLock);
     638                 :             : 
     639                 :             :         debug_elog4(DEBUG2, "MultiXact: setting OldestMember[%d] = %u",
     640                 :             :                     MyProcNumber, nextMXact);
     641                 :             :     }
     642                 :     4529606 : }
     643                 :             : 
     644                 :             : /*
     645                 :             :  * MultiXactIdSetOldestVisible
     646                 :             :  *      Save the oldest MultiXactId this transaction considers possibly live.
     647                 :             :  *
     648                 :             :  * We set the OldestVisibleMXactId for a given transaction the first time
     649                 :             :  * it's going to inspect any MultiXactId.  Once we have set this, we are
     650                 :             :  * guaranteed that SLRU data for MultiXactIds >= our own OldestVisibleMXactId
     651                 :             :  * won't be truncated away.
     652                 :             :  *
     653                 :             :  * The value to set is the oldest of nextMXact and all the valid per-backend
     654                 :             :  * OldestMemberMXactId[] entries.  Because of the locking we do, we can be
     655                 :             :  * certain that no subsequent call to MultiXactIdSetOldestMember can set
     656                 :             :  * an OldestMemberMXactId[] entry older than what we compute here.  Therefore
     657                 :             :  * there is no live transaction, now or later, that can be a member of any
     658                 :             :  * MultiXactId older than the OldestVisibleMXactId we compute here.
     659                 :             :  */
     660                 :             : static void
     661                 :       92505 : MultiXactIdSetOldestVisible(void)
     662                 :             : {
     663         [ +  + ]:       92505 :     if (!MultiXactIdIsValid(*MyOldestVisibleMXactIdSlot()))
     664                 :             :     {
     665                 :             :         MultiXactId oldestMXact;
     666                 :             :         int         i;
     667                 :             : 
     668                 :        3231 :         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
     669                 :             : 
     670                 :        3231 :         oldestMXact = MultiXactState->nextMXact;
     671         [ +  + ]:      412423 :         for (i = 0; i < NumMemberSlots; i++)
     672                 :             :         {
     673                 :      409192 :             MultiXactId thisoldest = OldestMemberMXactId[i];
     674                 :             : 
     675   [ +  +  +  + ]:      465160 :             if (MultiXactIdIsValid(thisoldest) &&
     676                 :       55968 :                 MultiXactIdPrecedes(thisoldest, oldestMXact))
     677                 :        5697 :                 oldestMXact = thisoldest;
     678                 :             :         }
     679                 :             : 
     680                 :        3231 :         *MyOldestVisibleMXactIdSlot() = oldestMXact;
     681                 :             : 
     682                 :        3231 :         LWLockRelease(MultiXactGenLock);
     683                 :             : 
     684                 :             :         debug_elog4(DEBUG2, "MultiXact: setting OldestVisible[%d] = %u",
     685                 :             :                     MyProcNumber, oldestMXact);
     686                 :             :     }
     687                 :       92505 : }
     688                 :             : 
     689                 :             : /*
     690                 :             :  * ReadNextMultiXactId
     691                 :             :  *      Return the next MultiXactId to be assigned, but don't allocate it
     692                 :             :  */
     693                 :             : MultiXactId
     694                 :      224179 : ReadNextMultiXactId(void)
     695                 :             : {
     696                 :             :     MultiXactId mxid;
     697                 :             : 
     698                 :             :     /* XXX we could presumably do this without a lock. */
     699                 :      224179 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
     700                 :      224179 :     mxid = MultiXactState->nextMXact;
     701                 :      224179 :     LWLockRelease(MultiXactGenLock);
     702                 :             : 
     703                 :      224179 :     return mxid;
     704                 :             : }
     705                 :             : 
     706                 :             : /*
     707                 :             :  * ReadMultiXactIdRange
     708                 :             :  *      Get the range of IDs that may still be referenced by a relation.
     709                 :             :  */
     710                 :             : void
     711                 :        1480 : ReadMultiXactIdRange(MultiXactId *oldest, MultiXactId *next)
     712                 :             : {
     713                 :        1480 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
     714                 :        1480 :     *oldest = MultiXactState->oldestMultiXactId;
     715                 :        1480 :     *next = MultiXactState->nextMXact;
     716                 :        1480 :     LWLockRelease(MultiXactGenLock);
     717                 :        1480 : }
     718                 :             : 
     719                 :             : 
     720                 :             : /*
     721                 :             :  * MultiXactIdCreateFromMembers
     722                 :             :  *      Make a new MultiXactId from the specified set of members
     723                 :             :  *
     724                 :             :  * Make XLOG, SLRU and cache entries for a new MultiXactId, recording the
     725                 :             :  * given TransactionIds as members.  Returns the newly created MultiXactId.
     726                 :             :  *
     727                 :             :  * NB: the passed members[] array will be sorted in-place.
     728                 :             :  */
     729                 :             : MultiXactId
     730                 :       76692 : MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
     731                 :             : {
     732                 :             :     MultiXactId multi;
     733                 :             :     MultiXactOffset offset;
     734                 :             :     xl_multixact_create xlrec;
     735                 :             : 
     736                 :             :     debug_elog3(DEBUG2, "Create: %s",
     737                 :             :                 mxid_to_string(InvalidMultiXactId, nmembers, members));
     738                 :             : 
     739                 :             :     /*
     740                 :             :      * See if the same set of members already exists in our cache; if so, just
     741                 :             :      * re-use that MultiXactId.  (Note: it might seem that looking in our
     742                 :             :      * cache is insufficient, and we ought to search disk to see if a
     743                 :             :      * duplicate definition already exists.  But since we only ever create
     744                 :             :      * MultiXacts containing our own XID, in most cases any such MultiXacts
     745                 :             :      * were in fact created by us, and so will be in our cache.  There are
     746                 :             :      * corner cases where someone else added us to a MultiXact without our
     747                 :             :      * knowledge, but it's not worth checking for.)
     748                 :             :      */
     749                 :       76692 :     multi = mXactCacheGetBySet(nmembers, members);
     750         [ +  + ]:       76692 :     if (MultiXactIdIsValid(multi))
     751                 :             :     {
     752                 :             :         debug_elog2(DEBUG2, "Create: in cache!");
     753                 :       71357 :         return multi;
     754                 :             :     }
     755                 :             : 
     756                 :             :     /* Verify that there is a single update Xid among the given members. */
     757                 :             :     {
     758                 :             :         int         i;
     759                 :        5335 :         bool        has_update = false;
     760                 :             : 
     761         [ +  + ]:      100120 :         for (i = 0; i < nmembers; i++)
     762                 :             :         {
     763         [ +  + ]:       94785 :             if (ISUPDATE_from_mxstatus(members[i].status))
     764                 :             :             {
     765         [ -  + ]:        2392 :                 if (has_update)
     766         [ #  # ]:           0 :                     elog(ERROR, "new multixact has more than one updating member: %s",
     767                 :             :                          mxid_to_string(InvalidMultiXactId, nmembers, members));
     768                 :        2392 :                 has_update = true;
     769                 :             :             }
     770                 :             :         }
     771                 :             :     }
     772                 :             : 
     773                 :             :     /* Load the injection point before entering the critical section */
     774                 :        5335 :     INJECTION_POINT_LOAD("multixact-create-from-members");
     775                 :             : 
     776                 :             :     /*
     777                 :             :      * Assign the MXID and offsets range to use, and make sure there is space
     778                 :             :      * in the OFFSETs and MEMBERs files.  NB: this routine does
     779                 :             :      * START_CRIT_SECTION().
     780                 :             :      *
     781                 :             :      * Note: unlike MultiXactIdCreate and MultiXactIdExpand, we do not check
     782                 :             :      * that we've called MultiXactIdSetOldestMember here.  This is because
     783                 :             :      * this routine is used in some places to create new MultiXactIds of which
     784                 :             :      * the current backend is not a member, notably during freezing of multis
     785                 :             :      * in vacuum.  During vacuum, in particular, it would be unacceptable to
     786                 :             :      * keep OldestMulti set, in case it runs for long.
     787                 :             :      */
     788                 :        5335 :     multi = GetNewMultiXactId(nmembers, &offset);
     789                 :             : 
     790                 :        5335 :     INJECTION_POINT_CACHED("multixact-create-from-members", NULL);
     791                 :             : 
     792                 :             :     /*
     793                 :             :      * Prevent checkpoints from starting between the WAL record and the update
     794                 :             :      * of the OFFSETs and MEMBERs pages.  Otherwise the checkpoint could flush
     795                 :             :      * the pages before they hold the new multixact, while recovery after a
     796                 :             :      * crash would begin after the WAL record, and the multixact would be lost
     797                 :             :      * even though data pages might already refer to it.
     798                 :             :      */
     799                 :             :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
     800                 :        5335 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START;
     801                 :             : 
     802                 :             :     /* Make an XLOG entry describing the new MXID. */
     803                 :        5335 :     xlrec.mid = multi;
     804                 :        5335 :     xlrec.moff = offset;
     805                 :        5335 :     xlrec.nmembers = nmembers;
     806                 :             : 
     807                 :             :     /*
     808                 :             :      * XXX Note: there's a lot of padding space in MultiXactMember.  We could
     809                 :             :      * find a more compact representation of this Xlog record -- perhaps all
     810                 :             :      * the status flags in one XLogRecData, then all the xids in another one?
     811                 :             :      * Not clear that it's worth the trouble though.
     812                 :             :      */
     813                 :        5335 :     XLogBeginInsert();
     814                 :        5335 :     XLogRegisterData(&xlrec, SizeOfMultiXactCreate);
     815                 :        5335 :     XLogRegisterData(members, nmembers * sizeof(MultiXactMember));
     816                 :             : 
     817                 :        5335 :     (void) XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_CREATE_ID);
     818                 :             : 
     819                 :             :     /* Now enter the information into the OFFSETs and MEMBERs logs */
     820                 :        5335 :     RecordNewMultiXact(multi, offset, nmembers, members);
     821                 :             : 
     822                 :        5335 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
     823                 :             : 
     824                 :             :     /* Done with critical section */
     825                 :        5335 :     END_CRIT_SECTION();
     826                 :             : 
     827                 :             :     /* Store the new MultiXactId in the local cache, too */
     828                 :        5335 :     mXactCachePut(multi, nmembers, members);
     829                 :             : 
     830                 :             :     debug_elog2(DEBUG2, "Create: all done");
     831                 :             : 
     832                 :        5335 :     return multi;
     833                 :             : }
     834                 :             : 
     835                 :             : /*
     836                 :             :  * RecordNewMultiXact
     837                 :             :  *      Write info about a new multixact into the offsets and members files
     838                 :             :  *
     839                 :             :  * This is broken out of MultiXactIdCreateFromMembers so that xlog replay can
     840                 :             :  * use it.
     841                 :             :  */
     842                 :             : static void
     843                 :        5344 : RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
     844                 :             :                    int nmembers, MultiXactMember *members)
     845                 :             : {
     846                 :             :     int64       pageno;
     847                 :             :     int64       prev_pageno;
     848                 :             :     int         entryno;
     849                 :             :     int         slotno;
     850                 :             :     MultiXactOffset *offptr;
     851                 :             :     MultiXactId next;
     852                 :             :     int64       next_pageno;
     853                 :             :     int         next_entryno;
     854                 :             :     MultiXactOffset *next_offptr;
     855                 :             :     MultiXactOffset next_offset;
     856                 :             :     LWLock     *lock;
     857                 :        5344 :     LWLock     *prevlock = NULL;
     858                 :             : 
     859                 :             :     /* position of this multixid in the offsets SLRU area  */
     860                 :        5344 :     pageno = MultiXactIdToOffsetPage(multi);
     861                 :        5344 :     entryno = MultiXactIdToOffsetEntry(multi);
     862                 :             : 
     863                 :             :     /* position of the next multixid */
     864                 :        5344 :     next = NextMultiXactId(multi);
     865                 :        5344 :     next_pageno = MultiXactIdToOffsetPage(next);
     866                 :        5344 :     next_entryno = MultiXactIdToOffsetEntry(next);
     867                 :             : 
     868                 :             :     /*
     869                 :             :      * Set the starting offset of this multixid's members.
     870                 :             :      *
     871                 :             :      * In the common case, it was already set by the previous
     872                 :             :      * RecordNewMultiXact call, as this was the next multixid of the previous
     873                 :             :      * multixid.  But if multiple backends are generating multixids
     874                 :             :      * concurrently, we might race ahead and get called before the previous
     875                 :             :      * multixid.
     876                 :             :      */
     877                 :        5344 :     lock = SimpleLruGetBankLock(MultiXactOffsetCtl, pageno);
     878                 :        5344 :     LWLockAcquire(lock, LW_EXCLUSIVE);
     879                 :             : 
     880                 :        5344 :     slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, &multi);
     881                 :        5344 :     offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
     882                 :        5344 :     offptr += entryno;
     883                 :             : 
     884         [ +  + ]:        5344 :     if (*offptr != offset)
     885                 :             :     {
     886                 :             :         /* should already be set to the correct value, or not at all */
     887                 :             :         Assert(*offptr == 0);
     888                 :           1 :         *offptr = offset;
     889                 :           1 :         MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
     890                 :             :     }
     891                 :             : 
     892                 :             :     /*
     893                 :             :      * Set the next multixid's offset to the end of this multixid's members.
     894                 :             :      */
     895         [ +  + ]:        5344 :     if (next_pageno == pageno)
     896                 :             :     {
     897                 :        5339 :         next_offptr = offptr + 1;
     898                 :             :     }
     899                 :             :     else
     900                 :             :     {
     901                 :             :         /* must be the first entry on the page */
     902                 :             :         Assert(next_entryno == 0 || next == FirstMultiXactId);
     903                 :             : 
     904                 :             :         /* Swap the lock for a lock on the next page */
     905                 :           5 :         LWLockRelease(lock);
     906                 :           5 :         lock = SimpleLruGetBankLock(MultiXactOffsetCtl, next_pageno);
     907                 :           5 :         LWLockAcquire(lock, LW_EXCLUSIVE);
     908                 :             : 
     909                 :           5 :         slotno = SimpleLruReadPage(MultiXactOffsetCtl, next_pageno, true, &next);
     910                 :           5 :         next_offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
     911                 :           5 :         next_offptr += next_entryno;
     912                 :             :     }
     913                 :             : 
     914                 :             :     /* Like in GetNewMultiXactId(), skip over offset 0 */
     915                 :        5344 :     next_offset = offset + nmembers;
     916         [ -  + ]:        5344 :     if (next_offset == 0)
     917                 :           0 :         next_offset = 1;
     918         [ +  - ]:        5344 :     if (*next_offptr != next_offset)
     919                 :             :     {
     920                 :             :         /* should already be set to the correct value, or not at all */
     921                 :             :         Assert(*next_offptr == 0);
     922                 :        5344 :         *next_offptr = next_offset;
     923                 :        5344 :         MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
     924                 :             :     }
     925                 :             : 
     926                 :             :     /* Release MultiXactOffset SLRU lock. */
     927                 :        5344 :     LWLockRelease(lock);
     928                 :             : 
     929                 :        5344 :     prev_pageno = -1;
     930                 :             : 
     931         [ +  + ]:      100146 :     for (int i = 0; i < nmembers; i++, offset++)
     932                 :             :     {
     933                 :             :         TransactionId *memberptr;
     934                 :             :         uint32     *flagsptr;
     935                 :             :         uint32      flagsval;
     936                 :             :         int         bshift;
     937                 :             :         int         flagsoff;
     938                 :             :         int         memberoff;
     939                 :             : 
     940                 :             :         Assert(members[i].status <= MultiXactStatusUpdate);
     941                 :             : 
     942                 :       94802 :         pageno = MXOffsetToMemberPage(offset);
     943                 :       94802 :         memberoff = MXOffsetToMemberOffset(offset);
     944                 :       94802 :         flagsoff = MXOffsetToFlagsOffset(offset);
     945                 :       94802 :         bshift = MXOffsetToFlagsBitShift(offset);
     946                 :             : 
     947         [ +  + ]:       94802 :         if (pageno != prev_pageno)
     948                 :             :         {
     949                 :        5398 :             MultiXactMemberSlruReadContext slru_read_context = {multi, offset};
     950                 :             : 
     951                 :             :             /*
     952                 :             :              * MultiXactMember SLRU page is changed so check if this new page
     953                 :             :              * fall into the different SLRU bank then release the old bank's
     954                 :             :              * lock and acquire lock on the new bank.
     955                 :             :              */
     956                 :        5398 :             lock = SimpleLruGetBankLock(MultiXactMemberCtl, pageno);
     957         [ +  - ]:        5398 :             if (lock != prevlock)
     958                 :             :             {
     959         [ +  + ]:        5398 :                 if (prevlock != NULL)
     960                 :          54 :                     LWLockRelease(prevlock);
     961                 :             : 
     962                 :        5398 :                 LWLockAcquire(lock, LW_EXCLUSIVE);
     963                 :        5398 :                 prevlock = lock;
     964                 :             :             }
     965                 :        5398 :             slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true,
     966                 :             :                                        &slru_read_context);
     967                 :        5398 :             prev_pageno = pageno;
     968                 :             :         }
     969                 :             : 
     970                 :       94802 :         memberptr = (TransactionId *)
     971                 :       94802 :             (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
     972                 :             : 
     973                 :       94802 :         *memberptr = members[i].xid;
     974                 :             : 
     975                 :       94802 :         flagsptr = (uint32 *)
     976                 :       94802 :             (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
     977                 :             : 
     978                 :       94802 :         flagsval = *flagsptr;
     979                 :       94802 :         flagsval &= ~(((1 << MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift);
     980                 :       94802 :         flagsval |= (members[i].status << bshift);
     981                 :       94802 :         *flagsptr = flagsval;
     982                 :             : 
     983                 :       94802 :         MultiXactMemberCtl->shared->page_dirty[slotno] = true;
     984                 :             :     }
     985                 :             : 
     986         [ +  - ]:        5344 :     if (prevlock != NULL)
     987                 :        5344 :         LWLockRelease(prevlock);
     988                 :        5344 : }
     989                 :             : 
     990                 :             : /*
     991                 :             :  * GetNewMultiXactId
     992                 :             :  *      Get the next MultiXactId.
     993                 :             :  *
     994                 :             :  * Also, reserve the needed amount of space in the "members" area.  The
     995                 :             :  * starting offset of the reserved space is returned in *offset.
     996                 :             :  *
     997                 :             :  * This may generate XLOG records for expansion of the offsets and/or members
     998                 :             :  * files.  Unfortunately, we have to do that while holding MultiXactGenLock
     999                 :             :  * to avoid race conditions --- the XLOG record for zeroing a page must appear
    1000                 :             :  * before any backend can possibly try to store data in that page!
    1001                 :             :  *
    1002                 :             :  * We start a critical section before advancing the shared counters.  The
    1003                 :             :  * caller must end the critical section after writing SLRU data.
    1004                 :             :  */
    1005                 :             : static MultiXactId
    1006                 :        5335 : GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
    1007                 :             : {
    1008                 :             :     MultiXactId result;
    1009                 :             :     MultiXactOffset nextOffset;
    1010                 :             : 
    1011                 :             :     debug_elog3(DEBUG2, "GetNew: for %d xids", nmembers);
    1012                 :             : 
    1013                 :             :     /* safety check, we should never get this far in a HS standby */
    1014         [ -  + ]:        5335 :     if (RecoveryInProgress())
    1015         [ #  # ]:           0 :         elog(ERROR, "cannot assign MultiXactIds during recovery");
    1016                 :             : 
    1017                 :        5335 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    1018                 :             : 
    1019                 :             :     /* Assign the MXID */
    1020                 :        5335 :     result = MultiXactState->nextMXact;
    1021                 :             : 
    1022                 :             :     /*----------
    1023                 :             :      * Check to see if it's safe to assign another MultiXactId.  This protects
    1024                 :             :      * against catastrophic data loss due to multixact wraparound.  The basic
    1025                 :             :      * rules are:
    1026                 :             :      *
    1027                 :             :      * If we're past multiVacLimit, start trying to force autovacuum cycles.
    1028                 :             :      * If we're past multiWarnLimit, start issuing warnings.
    1029                 :             :      * If we're past multiStopLimit, refuse to create new MultiXactIds.
    1030                 :             :      *
    1031                 :             :      * Note these are pretty much the same protections in GetNewTransactionId.
    1032                 :             :      *----------
    1033                 :             :      */
    1034         [ -  + ]:        5335 :     if (!MultiXactIdPrecedes(result, MultiXactState->multiVacLimit))
    1035                 :             :     {
    1036                 :             :         /*
    1037                 :             :          * For safety's sake, we release MultiXactGenLock while sending
    1038                 :             :          * signals, warnings, etc.  This is not so much because we care about
    1039                 :             :          * preserving concurrency in this situation, as to avoid any
    1040                 :             :          * possibility of deadlock while doing get_database_name(). First,
    1041                 :             :          * copy all the shared values we'll need in this path.
    1042                 :             :          */
    1043                 :           0 :         MultiXactId multiWarnLimit = MultiXactState->multiWarnLimit;
    1044                 :           0 :         MultiXactId multiStopLimit = MultiXactState->multiStopLimit;
    1045                 :           0 :         MultiXactId multiWrapLimit = MultiXactState->multiWrapLimit;
    1046                 :           0 :         Oid         oldest_datoid = MultiXactState->oldestMultiXactDB;
    1047                 :             : 
    1048                 :           0 :         LWLockRelease(MultiXactGenLock);
    1049                 :             : 
    1050         [ #  # ]:           0 :         if (IsUnderPostmaster &&
    1051         [ #  # ]:           0 :             !MultiXactIdPrecedes(result, multiStopLimit))
    1052                 :             :         {
    1053                 :           0 :             char       *oldest_datname = get_database_name(oldest_datoid);
    1054                 :             : 
    1055                 :             :             /*
    1056                 :             :              * Immediately kick autovacuum into action as we're already in
    1057                 :             :              * ERROR territory.
    1058                 :             :              */
    1059                 :           0 :             SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
    1060                 :             : 
    1061                 :             :             /* complain even if that DB has disappeared */
    1062         [ #  # ]:           0 :             if (oldest_datname)
    1063         [ #  # ]:           0 :                 ereport(ERROR,
    1064                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1065                 :             :                          errmsg("database is not accepting commands that assign new MultiXactIds to avoid wraparound data loss in database \"%s\"",
    1066                 :             :                                 oldest_datname),
    1067                 :             :                          errhint("Execute a database-wide VACUUM in that database.\n"
    1068                 :             :                                  "You might also need to commit or roll back old prepared transactions.")));
    1069                 :             :             else
    1070         [ #  # ]:           0 :                 ereport(ERROR,
    1071                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1072                 :             :                          errmsg("database is not accepting commands that assign new MultiXactIds to avoid wraparound data loss in database with OID %u",
    1073                 :             :                                 oldest_datoid),
    1074                 :             :                          errhint("Execute a database-wide VACUUM in that database.\n"
    1075                 :             :                                  "You might also need to commit or roll back old prepared transactions.")));
    1076                 :             :         }
    1077                 :             : 
    1078                 :             :         /*
    1079                 :             :          * To avoid swamping the postmaster with signals, we issue the autovac
    1080                 :             :          * request only once per 64K multis generated.  This still gives
    1081                 :             :          * plenty of chances before we get into real trouble.
    1082                 :             :          */
    1083   [ #  #  #  #  :           0 :         if (IsUnderPostmaster && ((result % 65536) == 0 || result == FirstMultiXactId))
                   #  # ]
    1084                 :           0 :             SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
    1085                 :             : 
    1086         [ #  # ]:           0 :         if (!MultiXactIdPrecedes(result, multiWarnLimit))
    1087                 :             :         {
    1088                 :           0 :             char       *oldest_datname = get_database_name(oldest_datoid);
    1089                 :             : 
    1090                 :             :             /* complain even if that DB has disappeared */
    1091         [ #  # ]:           0 :             if (oldest_datname)
    1092         [ #  # ]:           0 :                 ereport(WARNING,
    1093                 :             :                         (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
    1094                 :             :                                        "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
    1095                 :             :                                        multiWrapLimit - result,
    1096                 :             :                                        oldest_datname,
    1097                 :             :                                        multiWrapLimit - result),
    1098                 :             :                          errdetail("Approximately %.2f%% of MultiXactId space remains before wraparound.",
    1099                 :             :                                    (double) (multiWrapLimit - result) / (MaxMultiXactId / 2) * 100),
    1100                 :             :                          errhint("Execute a database-wide VACUUM in that database.\n"
    1101                 :             :                                  "You might also need to commit or roll back old prepared transactions.")));
    1102                 :             :             else
    1103         [ #  # ]:           0 :                 ereport(WARNING,
    1104                 :             :                         (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
    1105                 :             :                                        "database with OID %u must be vacuumed before %u more MultiXactIds are used",
    1106                 :             :                                        multiWrapLimit - result,
    1107                 :             :                                        oldest_datoid,
    1108                 :             :                                        multiWrapLimit - result),
    1109                 :             :                          errdetail("Approximately %.2f%% of MultiXactId space remains before wraparound.",
    1110                 :             :                                    (double) (multiWrapLimit - result) / (MaxMultiXactId / 2) * 100),
    1111                 :             :                          errhint("Execute a database-wide VACUUM in that database.\n"
    1112                 :             :                                  "You might also need to commit or roll back old prepared transactions.")));
    1113                 :             :         }
    1114                 :             : 
    1115                 :             :         /* Re-acquire lock and start over */
    1116                 :           0 :         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    1117                 :           0 :         result = MultiXactState->nextMXact;
    1118                 :             :     }
    1119                 :             : 
    1120                 :             :     /*
    1121                 :             :      * Make sure there is room for the next MXID in the file.  Assigning this
    1122                 :             :      * MXID sets the next MXID's offset already.
    1123                 :             :      */
    1124                 :        5335 :     ExtendMultiXactOffset(NextMultiXactId(result));
    1125                 :             : 
    1126                 :             :     /*
    1127                 :             :      * Reserve the members space, similarly to above.
    1128                 :             :      */
    1129                 :        5335 :     nextOffset = MultiXactState->nextOffset;
    1130                 :             : 
    1131                 :             :     /*
    1132                 :             :      * Offsets are 64-bit integers and will never wrap around.  Firstly, it
    1133                 :             :      * would take an unrealistic amount of time and resources to consume 2^64
    1134                 :             :      * offsets.  Secondly, multixid creation is WAL-logged, so you would run
    1135                 :             :      * out of LSNs before reaching offset wraparound.  Nevertheless, check for
    1136                 :             :      * wraparound as a sanity check.
    1137                 :             :      */
    1138         [ -  + ]:        5335 :     if (nextOffset + nmembers < nextOffset)
    1139         [ #  # ]:           0 :         ereport(ERROR,
    1140                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1141                 :             :                  errmsg("MultiXact members would wrap around")));
    1142                 :        5335 :     *offset = nextOffset;
    1143                 :             : 
    1144                 :        5335 :     ExtendMultiXactMember(nextOffset, nmembers);
    1145                 :             : 
    1146                 :             :     /*
    1147                 :             :      * Critical section from here until caller has written the data into the
    1148                 :             :      * just-reserved SLRU space; we don't want to error out with a partly
    1149                 :             :      * written MultiXact structure.  (In particular, failing to write our
    1150                 :             :      * start offset after advancing nextMXact would effectively corrupt the
    1151                 :             :      * previous MultiXact.)
    1152                 :             :      */
    1153                 :        5335 :     START_CRIT_SECTION();
    1154                 :             : 
    1155                 :             :     /*
    1156                 :             :      * Advance counters.  As in GetNewTransactionId(), this must not happen
    1157                 :             :      * until after file extension has succeeded!
    1158                 :             :      */
    1159                 :        5335 :     MultiXactState->nextMXact = NextMultiXactId(result);
    1160                 :        5335 :     MultiXactState->nextOffset += nmembers;
    1161                 :             : 
    1162                 :        5335 :     LWLockRelease(MultiXactGenLock);
    1163                 :             : 
    1164                 :             :     debug_elog4(DEBUG2, "GetNew: returning %u offset %" PRIu64,
    1165                 :             :                 result, *offset);
    1166                 :        5335 :     return result;
    1167                 :             : }
    1168                 :             : 
    1169                 :             : /*
    1170                 :             :  * GetMultiXactIdMembers
    1171                 :             :  *      Return the set of MultiXactMembers that make up a MultiXactId
    1172                 :             :  *
    1173                 :             :  * Return value is the number of members found, or -1 if there are none,
    1174                 :             :  * and *members is set to a newly palloc'ed array of members.  It's the
    1175                 :             :  * caller's responsibility to free it when done with it.
    1176                 :             :  *
    1177                 :             :  * from_pgupgrade must be passed as true if and only if only the multixact
    1178                 :             :  * corresponds to a value from a tuple that was locked in a 9.2-or-older
    1179                 :             :  * installation and later pg_upgrade'd (that is, the infomask is
    1180                 :             :  * HEAP_LOCKED_UPGRADED).  In this case, we know for certain that no members
    1181                 :             :  * can still be running, so we return -1 just like for an empty multixact
    1182                 :             :  * without any further checking.  It would be wrong to try to resolve such a
    1183                 :             :  * multixact: either the multixact is within the current valid multixact
    1184                 :             :  * range, in which case the returned result would be bogus, or outside that
    1185                 :             :  * range, in which case an error would be raised.
    1186                 :             :  *
    1187                 :             :  * In all other cases, the passed multixact must be within the known valid
    1188                 :             :  * range, that is, greater than or equal to oldestMultiXactId, and less than
    1189                 :             :  * nextMXact.  Otherwise, an error is raised.
    1190                 :             :  *
    1191                 :             :  * isLockOnly must be set to true if caller is certain that the given multi
    1192                 :             :  * is used only to lock tuples; can be false without loss of correctness,
    1193                 :             :  * but passing a true means we can return quickly without checking for
    1194                 :             :  * old updates.
    1195                 :             :  */
    1196                 :             : int
    1197                 :      550140 : GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members,
    1198                 :             :                       bool from_pgupgrade, bool isLockOnly)
    1199                 :             : {
    1200                 :             :     int64       pageno;
    1201                 :             :     int64       prev_pageno;
    1202                 :             :     int         entryno;
    1203                 :             :     int         slotno;
    1204                 :             :     MultiXactOffset *offptr;
    1205                 :             :     MultiXactOffset offset;
    1206                 :             :     MultiXactOffset nextMXOffset;
    1207                 :             :     int         length;
    1208                 :             :     MultiXactId oldestMXact;
    1209                 :             :     MultiXactId nextMXact;
    1210                 :             :     MultiXactMember *ptr;
    1211                 :             :     LWLock     *lock;
    1212                 :             : 
    1213                 :             :     debug_elog3(DEBUG2, "GetMembers: asked for %u", multi);
    1214                 :             : 
    1215   [ +  -  -  + ]:      550140 :     if (!MultiXactIdIsValid(multi) || from_pgupgrade)
    1216                 :             :     {
    1217                 :           0 :         *members = NULL;
    1218                 :           0 :         return -1;
    1219                 :             :     }
    1220                 :             : 
    1221                 :             :     /* See if the MultiXactId is in the local cache */
    1222                 :      550140 :     length = mXactCacheGetById(multi, members);
    1223         [ +  + ]:      550140 :     if (length >= 0)
    1224                 :             :     {
    1225                 :             :         debug_elog3(DEBUG2, "GetMembers: found %s in the cache",
    1226                 :             :                     mxid_to_string(multi, length, *members));
    1227                 :      457635 :         return length;
    1228                 :             :     }
    1229                 :             : 
    1230                 :             :     /* Set our OldestVisibleMXactId[] entry if we didn't already */
    1231                 :       92505 :     MultiXactIdSetOldestVisible();
    1232                 :             : 
    1233                 :             :     /*
    1234                 :             :      * If we know the multi is used only for locking and not for updates, then
    1235                 :             :      * we can skip checking if the value is older than our oldest visible
    1236                 :             :      * multi.  It cannot possibly still be running.
    1237                 :             :      */
    1238   [ +  +  +  + ]:       96224 :     if (isLockOnly &&
    1239                 :        3719 :         MultiXactIdPrecedes(multi, *MyOldestVisibleMXactIdSlot()))
    1240                 :             :     {
    1241                 :             :         debug_elog2(DEBUG2, "GetMembers: a locker-only multi is too old");
    1242                 :         736 :         *members = NULL;
    1243                 :         736 :         return -1;
    1244                 :             :     }
    1245                 :             : 
    1246                 :             :     /*
    1247                 :             :      * We check known limits on MultiXact before resorting to the SLRU area.
    1248                 :             :      *
    1249                 :             :      * An ID older than MultiXactState->oldestMultiXactId cannot possibly be
    1250                 :             :      * useful; it has already been removed, or will be removed shortly, by
    1251                 :             :      * truncation.  If one is passed, an error is raised.
    1252                 :             :      *
    1253                 :             :      * Also, an ID >= nextMXact shouldn't ever be seen here; if it is seen, it
    1254                 :             :      * implies undetected ID wraparound has occurred.  This raises a hard
    1255                 :             :      * error.
    1256                 :             :      *
    1257                 :             :      * Shared lock is enough here since we aren't modifying any global state.
    1258                 :             :      * Acquire it just long enough to grab the current counter values.
    1259                 :             :      */
    1260                 :       91769 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    1261                 :             : 
    1262                 :       91769 :     oldestMXact = MultiXactState->oldestMultiXactId;
    1263                 :       91769 :     nextMXact = MultiXactState->nextMXact;
    1264                 :             : 
    1265                 :       91769 :     LWLockRelease(MultiXactGenLock);
    1266                 :             : 
    1267         [ -  + ]:       91769 :     if (MultiXactIdPrecedes(multi, oldestMXact))
    1268         [ #  # ]:           0 :         ereport(ERROR,
    1269                 :             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    1270                 :             :                  errmsg("MultiXactId %u does no longer exist -- apparent wraparound",
    1271                 :             :                         multi)));
    1272                 :             : 
    1273         [ -  + ]:       91769 :     if (!MultiXactIdPrecedes(multi, nextMXact))
    1274         [ #  # ]:           0 :         ereport(ERROR,
    1275                 :             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    1276                 :             :                  errmsg("MultiXactId %u has not been created yet -- apparent wraparound",
    1277                 :             :                         multi)));
    1278                 :             : 
    1279                 :             :     /*
    1280                 :             :      * Find out the offset at which we need to start reading MultiXactMembers
    1281                 :             :      * and the number of members in the multixact.  We determine the latter as
    1282                 :             :      * the difference between this multixact's starting offset and the next
    1283                 :             :      * one's.
    1284                 :             :      */
    1285                 :       91769 :     pageno = MultiXactIdToOffsetPage(multi);
    1286                 :       91769 :     entryno = MultiXactIdToOffsetEntry(multi);
    1287                 :             : 
    1288                 :             :     /* Acquire the bank lock for the page we need. */
    1289                 :       91769 :     lock = SimpleLruGetBankLock(MultiXactOffsetCtl, pageno);
    1290                 :       91769 :     LWLockAcquire(lock, LW_EXCLUSIVE);
    1291                 :             : 
    1292                 :             :     /* read this multi's offset */
    1293                 :       91769 :     slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, &multi);
    1294                 :       91769 :     offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
    1295                 :       91769 :     offptr += entryno;
    1296                 :       91769 :     offset = *offptr;
    1297                 :             : 
    1298         [ -  + ]:       91769 :     if (offset == 0)
    1299         [ #  # ]:           0 :         ereport(ERROR,
    1300                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1301                 :             :                  errmsg("MultiXact %u has invalid offset", multi)));
    1302                 :             : 
    1303                 :             :     /* read next multi's offset */
    1304                 :             :     {
    1305                 :             :         MultiXactId tmpMXact;
    1306                 :             : 
    1307                 :             :         /* handle wraparound if needed */
    1308                 :       91769 :         tmpMXact = NextMultiXactId(multi);
    1309                 :             : 
    1310                 :       91769 :         prev_pageno = pageno;
    1311                 :             : 
    1312                 :       91769 :         pageno = MultiXactIdToOffsetPage(tmpMXact);
    1313                 :       91769 :         entryno = MultiXactIdToOffsetEntry(tmpMXact);
    1314                 :             : 
    1315         [ +  + ]:       91769 :         if (pageno != prev_pageno)
    1316                 :             :         {
    1317                 :             :             LWLock     *newlock;
    1318                 :             : 
    1319                 :             :             /*
    1320                 :             :              * Since we're going to access a different SLRU page, if this page
    1321                 :             :              * falls under a different bank, release the old bank's lock and
    1322                 :             :              * acquire the lock of the new bank.
    1323                 :             :              */
    1324                 :          13 :             newlock = SimpleLruGetBankLock(MultiXactOffsetCtl, pageno);
    1325         [ -  + ]:          13 :             if (newlock != lock)
    1326                 :             :             {
    1327                 :           0 :                 LWLockRelease(lock);
    1328                 :           0 :                 LWLockAcquire(newlock, LW_EXCLUSIVE);
    1329                 :           0 :                 lock = newlock;
    1330                 :             :             }
    1331                 :          13 :             slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, &tmpMXact);
    1332                 :             :         }
    1333                 :             : 
    1334                 :       91769 :         offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
    1335                 :       91769 :         offptr += entryno;
    1336                 :       91769 :         nextMXOffset = *offptr;
    1337                 :             :     }
    1338                 :             : 
    1339                 :       91769 :     LWLockRelease(lock);
    1340                 :       91769 :     lock = NULL;
    1341                 :             : 
    1342                 :             :     /* Sanity check the next offset */
    1343         [ -  + ]:       91769 :     if (nextMXOffset == 0)
    1344         [ #  # ]:           0 :         ereport(ERROR,
    1345                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1346                 :             :                  errmsg("MultiXact %u has invalid next offset", multi)));
    1347         [ -  + ]:       91769 :     if (nextMXOffset == offset)
    1348         [ #  # ]:           0 :         ereport(ERROR,
    1349                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1350                 :             :                  errmsg("MultiXact %u with offset (%" PRIu64 ") has zero members",
    1351                 :             :                         multi, offset)));
    1352         [ -  + ]:       91769 :     if (nextMXOffset < offset)
    1353         [ #  # ]:           0 :         ereport(ERROR,
    1354                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1355                 :             :                  errmsg("MultiXact %u has offset (%" PRIu64 ") greater than its next offset (%" PRIu64 ")",
    1356                 :             :                         multi, offset, nextMXOffset)));
    1357         [ -  + ]:       91769 :     if (nextMXOffset - offset > INT32_MAX)
    1358         [ #  # ]:           0 :         ereport(ERROR,
    1359                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1360                 :             :                  errmsg("MultiXact %u has too many members (%" PRIu64 ")",
    1361                 :             :                         multi, nextMXOffset - offset)));
    1362                 :       91769 :     length = nextMXOffset - offset;
    1363                 :             : 
    1364                 :             :     /* read the members */
    1365                 :       91769 :     ptr = palloc_array(MultiXactMember, length);
    1366                 :       91769 :     prev_pageno = -1;
    1367         [ +  + ]:     1828014 :     for (int i = 0; i < length; i++, offset++)
    1368                 :             :     {
    1369                 :             :         TransactionId *xactptr;
    1370                 :             :         uint32     *flagsptr;
    1371                 :             :         int         flagsoff;
    1372                 :             :         int         bshift;
    1373                 :             :         int         memberoff;
    1374                 :             : 
    1375                 :     1736245 :         pageno = MXOffsetToMemberPage(offset);
    1376                 :     1736245 :         memberoff = MXOffsetToMemberOffset(offset);
    1377                 :             : 
    1378         [ +  + ]:     1736245 :         if (pageno != prev_pageno)
    1379                 :             :         {
    1380                 :       91931 :             MultiXactMemberSlruReadContext slru_read_context = {multi, offset};
    1381                 :             :             LWLock     *newlock;
    1382                 :             : 
    1383                 :             :             /*
    1384                 :             :              * Since we're going to access a different SLRU page, if this page
    1385                 :             :              * falls under a different bank, release the old bank's lock and
    1386                 :             :              * acquire the lock of the new bank.
    1387                 :             :              */
    1388                 :       91931 :             newlock = SimpleLruGetBankLock(MultiXactMemberCtl, pageno);
    1389         [ +  - ]:       91931 :             if (newlock != lock)
    1390                 :             :             {
    1391         [ +  + ]:       91931 :                 if (lock)
    1392                 :         162 :                     LWLockRelease(lock);
    1393                 :       91931 :                 LWLockAcquire(newlock, LW_EXCLUSIVE);
    1394                 :       91931 :                 lock = newlock;
    1395                 :             :             }
    1396                 :       91931 :             slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true,
    1397                 :             :                                        &slru_read_context);
    1398                 :       91931 :             prev_pageno = pageno;
    1399                 :             :         }
    1400                 :             : 
    1401                 :     1736245 :         xactptr = (TransactionId *)
    1402                 :     1736245 :             (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
    1403                 :             :         Assert(TransactionIdIsValid(*xactptr));
    1404                 :             : 
    1405                 :     1736245 :         flagsoff = MXOffsetToFlagsOffset(offset);
    1406                 :     1736245 :         bshift = MXOffsetToFlagsBitShift(offset);
    1407                 :     1736245 :         flagsptr = (uint32 *) (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
    1408                 :             : 
    1409                 :     1736245 :         ptr[i].xid = *xactptr;
    1410                 :     1736245 :         ptr[i].status = (*flagsptr >> bshift) & MXACT_MEMBER_XACT_BITMASK;
    1411                 :             :     }
    1412                 :             : 
    1413                 :       91769 :     LWLockRelease(lock);
    1414                 :             : 
    1415                 :             :     /*
    1416                 :             :      * Copy the result into the local cache.
    1417                 :             :      */
    1418                 :       91769 :     mXactCachePut(multi, length, ptr);
    1419                 :             : 
    1420                 :             :     debug_elog3(DEBUG2, "GetMembers: no cache for %s",
    1421                 :             :                 mxid_to_string(multi, length, ptr));
    1422                 :       91769 :     *members = ptr;
    1423                 :       91769 :     return length;
    1424                 :             : }
    1425                 :             : 
    1426                 :             : /*
    1427                 :             :  * mxactMemberComparator
    1428                 :             :  *      qsort comparison function for MultiXactMember
    1429                 :             :  *
    1430                 :             :  * We can't use wraparound comparison for XIDs because that does not respect
    1431                 :             :  * the triangle inequality!  Any old sort order will do.
    1432                 :             :  */
    1433                 :             : static int
    1434                 :     3050819 : mxactMemberComparator(const void *arg1, const void *arg2)
    1435                 :             : {
    1436                 :     3050819 :     MultiXactMember member1 = *(const MultiXactMember *) arg1;
    1437                 :     3050819 :     MultiXactMember member2 = *(const MultiXactMember *) arg2;
    1438                 :             : 
    1439         [ +  + ]:     3050819 :     if (member1.xid > member2.xid)
    1440                 :          32 :         return 1;
    1441         [ +  + ]:     3050787 :     if (member1.xid < member2.xid)
    1442                 :     3050563 :         return -1;
    1443         [ +  + ]:         224 :     if (member1.status > member2.status)
    1444                 :          16 :         return 1;
    1445         [ +  - ]:         208 :     if (member1.status < member2.status)
    1446                 :         208 :         return -1;
    1447                 :           0 :     return 0;
    1448                 :             : }
    1449                 :             : 
    1450                 :             : /*
    1451                 :             :  * mXactCacheGetBySet
    1452                 :             :  *      returns a MultiXactId from the cache based on the set of
    1453                 :             :  *      TransactionIds that compose it, or InvalidMultiXactId if
    1454                 :             :  *      none matches.
    1455                 :             :  *
    1456                 :             :  * This is helpful, for example, if two transactions want to lock a huge
    1457                 :             :  * table.  By using the cache, the second will use the same MultiXactId
    1458                 :             :  * for the majority of tuples, thus keeping MultiXactId usage low (saving
    1459                 :             :  * both I/O and wraparound issues).
    1460                 :             :  *
    1461                 :             :  * NB: the passed members array will be sorted in-place.
    1462                 :             :  */
    1463                 :             : static MultiXactId
    1464                 :       76692 : mXactCacheGetBySet(int nmembers, MultiXactMember *members)
    1465                 :             : {
    1466                 :             :     dlist_iter  iter;
    1467                 :             : 
    1468                 :             :     debug_elog3(DEBUG2, "CacheGet: looking for %s",
    1469                 :             :                 mxid_to_string(InvalidMultiXactId, nmembers, members));
    1470                 :             : 
    1471                 :             :     /* sort the array so comparison is easy */
    1472                 :       76692 :     qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
    1473                 :             : 
    1474   [ +  -  +  + ]:      308405 :     dclist_foreach(iter, &MXactCache)
    1475                 :             :     {
    1476                 :      303070 :         mXactCacheEnt *entry = dclist_container(mXactCacheEnt, node,
    1477                 :             :                                                 iter.cur);
    1478                 :             : 
    1479         [ +  + ]:      303070 :         if (entry->nmembers != nmembers)
    1480                 :       85344 :             continue;
    1481                 :             : 
    1482                 :             :         /*
    1483                 :             :          * We assume the cache entries are sorted, and that the unused bits in
    1484                 :             :          * "status" are zeroed.
    1485                 :             :          */
    1486         [ +  + ]:      217726 :         if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
    1487                 :             :         {
    1488                 :             :             debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
    1489                 :       71357 :             dclist_move_head(&MXactCache, iter.cur);
    1490                 :       71357 :             return entry->multi;
    1491                 :             :         }
    1492                 :             :     }
    1493                 :             : 
    1494                 :             :     debug_elog2(DEBUG2, "CacheGet: not found :-(");
    1495                 :        5335 :     return InvalidMultiXactId;
    1496                 :             : }
    1497                 :             : 
    1498                 :             : /*
    1499                 :             :  * mXactCacheGetById
    1500                 :             :  *      returns the composing MultiXactMember set from the cache for a
    1501                 :             :  *      given MultiXactId, if present.
    1502                 :             :  *
    1503                 :             :  * If successful, *xids is set to the address of a palloc'd copy of the
    1504                 :             :  * MultiXactMember set.  Return value is number of members, or -1 on failure.
    1505                 :             :  */
    1506                 :             : static int
    1507                 :      550140 : mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
    1508                 :             : {
    1509                 :             :     dlist_iter  iter;
    1510                 :             : 
    1511                 :             :     debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
    1512                 :             : 
    1513   [ +  -  +  + ]:     4905997 :     dclist_foreach(iter, &MXactCache)
    1514                 :             :     {
    1515                 :     4813492 :         mXactCacheEnt *entry = dclist_container(mXactCacheEnt, node,
    1516                 :             :                                                 iter.cur);
    1517                 :             : 
    1518         [ +  + ]:     4813492 :         if (entry->multi == multi)
    1519                 :             :         {
    1520                 :             :             MultiXactMember *ptr;
    1521                 :             :             Size        size;
    1522                 :             : 
    1523                 :      457635 :             size = sizeof(MultiXactMember) * entry->nmembers;
    1524                 :      457635 :             ptr = (MultiXactMember *) palloc(size);
    1525                 :             : 
    1526                 :      457635 :             memcpy(ptr, entry->members, size);
    1527                 :             : 
    1528                 :             :             debug_elog3(DEBUG2, "CacheGet: found %s",
    1529                 :             :                         mxid_to_string(multi,
    1530                 :             :                                        entry->nmembers,
    1531                 :             :                                        entry->members));
    1532                 :             : 
    1533                 :             :             /*
    1534                 :             :              * Note we modify the list while not using a modifiable iterator.
    1535                 :             :              * This is acceptable only because we exit the iteration
    1536                 :             :              * immediately afterwards.
    1537                 :             :              */
    1538                 :      457635 :             dclist_move_head(&MXactCache, iter.cur);
    1539                 :             : 
    1540                 :      457635 :             *members = ptr;
    1541                 :      457635 :             return entry->nmembers;
    1542                 :             :         }
    1543                 :             :     }
    1544                 :             : 
    1545                 :             :     debug_elog2(DEBUG2, "CacheGet: not found");
    1546                 :       92505 :     return -1;
    1547                 :             : }
    1548                 :             : 
    1549                 :             : /*
    1550                 :             :  * mXactCachePut
    1551                 :             :  *      Add a new MultiXactId and its composing set into the local cache.
    1552                 :             :  */
    1553                 :             : static void
    1554                 :       97104 : mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
    1555                 :             : {
    1556                 :             :     mXactCacheEnt *entry;
    1557                 :             : 
    1558                 :             :     debug_elog3(DEBUG2, "CachePut: storing %s",
    1559                 :             :                 mxid_to_string(multi, nmembers, members));
    1560                 :             : 
    1561         [ +  + ]:       97104 :     if (MXactContext == NULL)
    1562                 :             :     {
    1563                 :             :         /* The cache only lives as long as the current transaction */
    1564                 :             :         debug_elog2(DEBUG2, "CachePut: initializing memory context");
    1565                 :        3384 :         MXactContext = AllocSetContextCreate(TopTransactionContext,
    1566                 :             :                                              "MultiXact cache context",
    1567                 :             :                                              ALLOCSET_SMALL_SIZES);
    1568                 :             :     }
    1569                 :             : 
    1570                 :             :     entry = (mXactCacheEnt *)
    1571                 :       97104 :         MemoryContextAlloc(MXactContext,
    1572                 :       97104 :                            offsetof(mXactCacheEnt, members) +
    1573                 :             :                            nmembers * sizeof(MultiXactMember));
    1574                 :             : 
    1575                 :       97104 :     entry->multi = multi;
    1576                 :       97104 :     entry->nmembers = nmembers;
    1577                 :       97104 :     memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
    1578                 :             : 
    1579                 :             :     /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
    1580                 :       97104 :     qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
    1581                 :             : 
    1582                 :       97104 :     dclist_push_head(&MXactCache, &entry->node);
    1583         [ +  + ]:       97104 :     if (dclist_count(&MXactCache) > MAX_CACHE_ENTRIES)
    1584                 :             :     {
    1585                 :             :         dlist_node *node;
    1586                 :             : 
    1587                 :        9478 :         node = dclist_tail_node(&MXactCache);
    1588                 :        9478 :         dclist_delete_from(&MXactCache, node);
    1589                 :             : 
    1590                 :        9478 :         entry = dclist_container(mXactCacheEnt, node, node);
    1591                 :             :         debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
    1592                 :             :                     entry->multi);
    1593                 :             : 
    1594                 :        9478 :         pfree(entry);
    1595                 :             :     }
    1596                 :       97104 : }
    1597                 :             : 
    1598                 :             : char *
    1599                 :      188088 : mxstatus_to_string(MultiXactStatus status)
    1600                 :             : {
    1601   [ +  -  -  -  :      188088 :     switch (status)
                +  -  - ]
    1602                 :             :     {
    1603                 :      183634 :         case MultiXactStatusForKeyShare:
    1604                 :      183634 :             return "keysh";
    1605                 :           0 :         case MultiXactStatusForShare:
    1606                 :           0 :             return "sh";
    1607                 :           0 :         case MultiXactStatusForNoKeyUpdate:
    1608                 :           0 :             return "fornokeyupd";
    1609                 :           0 :         case MultiXactStatusForUpdate:
    1610                 :           0 :             return "forupd";
    1611                 :        4454 :         case MultiXactStatusNoKeyUpdate:
    1612                 :        4454 :             return "nokeyupd";
    1613                 :           0 :         case MultiXactStatusUpdate:
    1614                 :           0 :             return "upd";
    1615                 :           0 :         default:
    1616         [ #  # ]:           0 :             elog(ERROR, "unrecognized multixact status %d", status);
    1617                 :             :             return "";
    1618                 :             :     }
    1619                 :             : }
    1620                 :             : 
    1621                 :             : char *
    1622                 :           0 : mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
    1623                 :             : {
    1624                 :             :     static char *str = NULL;
    1625                 :             :     StringInfoData buf;
    1626                 :             :     int         i;
    1627                 :             : 
    1628         [ #  # ]:           0 :     if (str != NULL)
    1629                 :           0 :         pfree(str);
    1630                 :             : 
    1631                 :           0 :     initStringInfo(&buf);
    1632                 :             : 
    1633                 :           0 :     appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
    1634                 :             :                      mxstatus_to_string(members[0].status));
    1635                 :             : 
    1636         [ #  # ]:           0 :     for (i = 1; i < nmembers; i++)
    1637                 :           0 :         appendStringInfo(&buf, ", %u (%s)", members[i].xid,
    1638                 :           0 :                          mxstatus_to_string(members[i].status));
    1639                 :             : 
    1640                 :           0 :     appendStringInfoChar(&buf, ']');
    1641                 :           0 :     str = MemoryContextStrdup(TopMemoryContext, buf.data);
    1642                 :           0 :     pfree(buf.data);
    1643                 :           0 :     return str;
    1644                 :             : }
    1645                 :             : 
    1646                 :             : /*
    1647                 :             :  * AtEOXact_MultiXact
    1648                 :             :  *      Handle transaction end for MultiXact
    1649                 :             :  *
    1650                 :             :  * This is called at top transaction commit or abort (we don't care which).
    1651                 :             :  */
    1652                 :             : void
    1653                 :      654916 : AtEOXact_MultiXact(void)
    1654                 :             : {
    1655                 :             :     /*
    1656                 :             :      * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
    1657                 :             :      * which should only be valid while within a transaction.
    1658                 :             :      *
    1659                 :             :      * We assume that storing a MultiXactId is atomic and so we need not take
    1660                 :             :      * MultiXactGenLock to do this.
    1661                 :             :      */
    1662                 :      654916 :     *MyOldestMemberMXactIdSlot() = InvalidMultiXactId;
    1663                 :      654916 :     *MyOldestVisibleMXactIdSlot() = InvalidMultiXactId;
    1664                 :             : 
    1665                 :             :     /*
    1666                 :             :      * Discard the local MultiXactId cache.  Since MXactContext was created as
    1667                 :             :      * a child of TopTransactionContext, we needn't delete it explicitly.
    1668                 :             :      */
    1669                 :      654916 :     MXactContext = NULL;
    1670                 :      654916 :     dclist_init(&MXactCache);
    1671                 :      654916 : }
    1672                 :             : 
    1673                 :             : /*
    1674                 :             :  * AtPrepare_MultiXact
    1675                 :             :  *      Save multixact state at 2PC transaction prepare
    1676                 :             :  *
    1677                 :             :  * In this phase, we only store our OldestMemberMXactId value in the two-phase
    1678                 :             :  * state file.
    1679                 :             :  */
    1680                 :             : void
    1681                 :         332 : AtPrepare_MultiXact(void)
    1682                 :             : {
    1683                 :         332 :     MultiXactId myOldestMember = *MyOldestMemberMXactIdSlot();
    1684                 :             : 
    1685         [ +  + ]:         332 :     if (MultiXactIdIsValid(myOldestMember))
    1686                 :          73 :         RegisterTwoPhaseRecord(TWOPHASE_RM_MULTIXACT_ID, 0,
    1687                 :             :                                &myOldestMember, sizeof(MultiXactId));
    1688                 :         332 : }
    1689                 :             : 
    1690                 :             : /*
    1691                 :             :  * PostPrepare_MultiXact
    1692                 :             :  *      Clean up after successful PREPARE TRANSACTION
    1693                 :             :  */
    1694                 :             : void
    1695                 :         332 : PostPrepare_MultiXact(FullTransactionId fxid)
    1696                 :             : {
    1697                 :             :     MultiXactId myOldestMember;
    1698                 :             : 
    1699                 :             :     /*
    1700                 :             :      * Transfer our OldestMemberMXactId value to the slot reserved for the
    1701                 :             :      * prepared transaction.
    1702                 :             :      */
    1703                 :         332 :     myOldestMember = *MyOldestMemberMXactIdSlot();
    1704         [ +  + ]:         332 :     if (MultiXactIdIsValid(myOldestMember))
    1705                 :             :     {
    1706                 :          73 :         ProcNumber  dummyProcNumber = TwoPhaseGetDummyProcNumber(fxid, false);
    1707                 :             : 
    1708                 :             :         /*
    1709                 :             :          * Even though storing MultiXactId is atomic, acquire lock to make
    1710                 :             :          * sure others see both changes, not just the reset of the slot of the
    1711                 :             :          * current backend. Using a volatile pointer might suffice, but this
    1712                 :             :          * isn't a hot spot.
    1713                 :             :          */
    1714                 :          73 :         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    1715                 :             : 
    1716                 :          73 :         *PreparedXactOldestMemberMXactIdSlot(dummyProcNumber) = myOldestMember;
    1717                 :          73 :         *MyOldestMemberMXactIdSlot() = InvalidMultiXactId;
    1718                 :             : 
    1719                 :          73 :         LWLockRelease(MultiXactGenLock);
    1720                 :             :     }
    1721                 :             : 
    1722                 :             :     /*
    1723                 :             :      * We don't need to transfer OldestVisibleMXactId value, because the
    1724                 :             :      * transaction is not going to be looking at any more multixacts once it's
    1725                 :             :      * prepared.
    1726                 :             :      *
    1727                 :             :      * We assume that storing a MultiXactId is atomic and so we need not take
    1728                 :             :      * MultiXactGenLock to do this.
    1729                 :             :      */
    1730                 :         332 :     *MyOldestVisibleMXactIdSlot() = InvalidMultiXactId;
    1731                 :             : 
    1732                 :             :     /*
    1733                 :             :      * Discard the local MultiXactId cache like in AtEOXact_MultiXact.
    1734                 :             :      */
    1735                 :         332 :     MXactContext = NULL;
    1736                 :         332 :     dclist_init(&MXactCache);
    1737                 :         332 : }
    1738                 :             : 
    1739                 :             : /*
    1740                 :             :  * multixact_twophase_recover
    1741                 :             :  *      Recover the state of a prepared transaction at startup
    1742                 :             :  */
    1743                 :             : void
    1744                 :           9 : multixact_twophase_recover(FullTransactionId fxid, uint16 info,
    1745                 :             :                            void *recdata, uint32 len)
    1746                 :             : {
    1747                 :           9 :     ProcNumber  dummyProcNumber = TwoPhaseGetDummyProcNumber(fxid, false);
    1748                 :             :     MultiXactId oldestMember;
    1749                 :             : 
    1750                 :             :     /*
    1751                 :             :      * Get the oldest member XID from the state file record, and set it in the
    1752                 :             :      * OldestMemberMXactId slot reserved for this prepared transaction.
    1753                 :             :      */
    1754                 :             :     Assert(len == sizeof(MultiXactId));
    1755                 :           9 :     oldestMember = *((MultiXactId *) recdata);
    1756                 :             : 
    1757                 :           9 :     *PreparedXactOldestMemberMXactIdSlot(dummyProcNumber) = oldestMember;
    1758                 :           9 : }
    1759                 :             : 
    1760                 :             : /*
    1761                 :             :  * multixact_twophase_postcommit
    1762                 :             :  *      Similar to AtEOXact_MultiXact but for COMMIT PREPARED
    1763                 :             :  */
    1764                 :             : void
    1765                 :          76 : multixact_twophase_postcommit(FullTransactionId fxid, uint16 info,
    1766                 :             :                               void *recdata, uint32 len)
    1767                 :             : {
    1768                 :          76 :     ProcNumber  dummyProcNumber = TwoPhaseGetDummyProcNumber(fxid, true);
    1769                 :             : 
    1770                 :             :     Assert(len == sizeof(MultiXactId));
    1771                 :             : 
    1772                 :          76 :     *PreparedXactOldestMemberMXactIdSlot(dummyProcNumber) = InvalidMultiXactId;
    1773                 :          76 : }
    1774                 :             : 
    1775                 :             : /*
    1776                 :             :  * multixact_twophase_postabort
    1777                 :             :  *      This is actually just the same as the COMMIT case.
    1778                 :             :  */
    1779                 :             : void
    1780                 :          32 : multixact_twophase_postabort(FullTransactionId fxid, uint16 info,
    1781                 :             :                              void *recdata, uint32 len)
    1782                 :             : {
    1783                 :          32 :     multixact_twophase_postcommit(fxid, info, recdata, len);
    1784                 :          32 : }
    1785                 :             : 
    1786                 :             : 
    1787                 :             : /*
    1788                 :             :  * Register shared memory needs for MultiXact.
    1789                 :             :  */
    1790                 :             : static void
    1791                 :        1362 : MultiXactShmemRequest(void *arg)
    1792                 :             : {
    1793                 :             :     Size        size;
    1794                 :             : 
    1795                 :             :     /*
    1796                 :             :      * Calculate the size of the MultiXactState struct, and the two
    1797                 :             :      * per-backend MultiXactId arrays.  They are carved out of the same
    1798                 :             :      * allocation.
    1799                 :             :      */
    1800                 :        1362 :     size = offsetof(MultiXactStateData, perBackendXactIds);
    1801                 :        1362 :     size = add_size(size,
    1802                 :        1362 :                     mul_size(sizeof(MultiXactId), NumMemberSlots));
    1803                 :        1362 :     size = add_size(size,
    1804                 :             :                     mul_size(sizeof(MultiXactId), NumVisibleSlots));
    1805                 :        1362 :     ShmemRequestStruct(.name = "Shared MultiXact State",
    1806                 :             :                        .size = size,
    1807                 :             :                        .ptr = (void **) &MultiXactState,
    1808                 :             :         );
    1809                 :             : 
    1810                 :        1362 :     SimpleLruRequest(.desc = &MultiXactOffsetSlruDesc,
    1811                 :             :                      .name = "multixact_offset",
    1812                 :             :                      .Dir = "pg_multixact/offsets",
    1813                 :             :                      .long_segment_names = false,
    1814                 :             : 
    1815                 :             :                      .nslots = multixact_offset_buffers,
    1816                 :             : 
    1817                 :             :                      .sync_handler = SYNC_HANDLER_MULTIXACT_OFFSET,
    1818                 :             :                      .PagePrecedes = MultiXactOffsetPagePrecedes,
    1819                 :             :                      .errdetail_for_io_error = MultiXactOffsetIoErrorDetail,
    1820                 :             : 
    1821                 :             :                      .buffer_tranche_id = LWTRANCHE_MULTIXACTOFFSET_BUFFER,
    1822                 :             :                      .bank_tranche_id = LWTRANCHE_MULTIXACTOFFSET_SLRU,
    1823                 :             :         );
    1824                 :             : 
    1825                 :        1362 :     SimpleLruRequest(.desc = &MultiXactMemberSlruDesc,
    1826                 :             :                      .name = "multixact_member",
    1827                 :             :                      .Dir = "pg_multixact/members",
    1828                 :             :                      .long_segment_names = true,
    1829                 :             : 
    1830                 :             :                      .nslots = multixact_member_buffers,
    1831                 :             : 
    1832                 :             :                      .sync_handler = SYNC_HANDLER_MULTIXACT_MEMBER,
    1833                 :             :                      .PagePrecedes = MultiXactMemberPagePrecedes,
    1834                 :             :                      .errdetail_for_io_error = MultiXactMemberIoErrorDetail,
    1835                 :             : 
    1836                 :             :                      .buffer_tranche_id = LWTRANCHE_MULTIXACTMEMBER_BUFFER,
    1837                 :             :                      .bank_tranche_id = LWTRANCHE_MULTIXACTMEMBER_SLRU,
    1838                 :             :         );
    1839                 :        1362 : }
    1840                 :             : 
    1841                 :             : static void
    1842                 :        1358 : MultiXactShmemInit(void *arg)
    1843                 :             : {
    1844                 :             :     SlruPagePrecedesUnitTests(MultiXactOffsetCtl, MULTIXACT_OFFSETS_PER_PAGE);
    1845                 :             : 
    1846                 :             :     /*
    1847                 :             :      * members SLRU doesn't call SimpleLruTruncate() or meet criteria for unit
    1848                 :             :      * tests
    1849                 :             :      */
    1850                 :             : 
    1851                 :             :     /* Set up array pointers */
    1852                 :        1358 :     OldestMemberMXactId = MultiXactState->perBackendXactIds;
    1853                 :        1358 :     OldestVisibleMXactId = OldestMemberMXactId + NumMemberSlots;
    1854                 :        1358 : }
    1855                 :             : 
    1856                 :             : static void
    1857                 :           0 : MultiXactShmemAttach(void *arg)
    1858                 :             : {
    1859                 :             :     /* Set up array pointers */
    1860                 :           0 :     OldestMemberMXactId = MultiXactState->perBackendXactIds;
    1861                 :           0 :     OldestVisibleMXactId = OldestMemberMXactId + NumMemberSlots;
    1862                 :           0 : }
    1863                 :             : 
    1864                 :             : /*
    1865                 :             :  * GUC check_hook for multixact_offset_buffers
    1866                 :             :  */
    1867                 :             : bool
    1868                 :        1403 : check_multixact_offset_buffers(int *newval, void **extra, GucSource source)
    1869                 :             : {
    1870                 :        1403 :     return check_slru_buffers("multixact_offset_buffers", newval);
    1871                 :             : }
    1872                 :             : 
    1873                 :             : /*
    1874                 :             :  * GUC check_hook for multixact_member_buffers
    1875                 :             :  */
    1876                 :             : bool
    1877                 :        1403 : check_multixact_member_buffers(int *newval, void **extra, GucSource source)
    1878                 :             : {
    1879                 :        1403 :     return check_slru_buffers("multixact_member_buffers", newval);
    1880                 :             : }
    1881                 :             : 
    1882                 :             : /*
    1883                 :             :  * This func must be called ONCE on system install.  It creates the initial
    1884                 :             :  * MultiXact segments.  (The MultiXacts directories are assumed to have been
    1885                 :             :  * created by initdb, and MultiXactShmemInit must have been called already.)
    1886                 :             :  */
    1887                 :             : void
    1888                 :          61 : BootStrapMultiXact(void)
    1889                 :             : {
    1890                 :             :     /* Zero the initial pages and flush them to disk */
    1891                 :          61 :     SimpleLruZeroAndWritePage(MultiXactOffsetCtl, 0);
    1892                 :          61 :     SimpleLruZeroAndWritePage(MultiXactMemberCtl, 0);
    1893                 :          61 : }
    1894                 :             : 
    1895                 :             : /*
    1896                 :             :  * This must be called ONCE during postmaster or standalone-backend startup.
    1897                 :             :  *
    1898                 :             :  * StartupXLOG has already established nextMXact/nextOffset by calling
    1899                 :             :  * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
    1900                 :             :  * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
    1901                 :             :  * replayed WAL.
    1902                 :             :  */
    1903                 :             : void
    1904                 :        1175 : StartupMultiXact(void)
    1905                 :             : {
    1906                 :        1175 :     MultiXactId multi = MultiXactState->nextMXact;
    1907                 :        1175 :     MultiXactOffset offset = MultiXactState->nextOffset;
    1908                 :             :     int64       pageno;
    1909                 :             : 
    1910                 :             :     /*
    1911                 :             :      * Initialize offset's idea of the latest page number.
    1912                 :             :      */
    1913                 :        1175 :     pageno = MultiXactIdToOffsetPage(multi);
    1914                 :        1175 :     pg_atomic_write_u64(&MultiXactOffsetCtl->shared->latest_page_number,
    1915                 :             :                         pageno);
    1916                 :             : 
    1917                 :             :     /*
    1918                 :             :      * Initialize member's idea of the latest page number.
    1919                 :             :      */
    1920                 :        1175 :     pageno = MXOffsetToMemberPage(offset);
    1921                 :        1175 :     pg_atomic_write_u64(&MultiXactMemberCtl->shared->latest_page_number,
    1922                 :             :                         pageno);
    1923                 :        1175 : }
    1924                 :             : 
    1925                 :             : /*
    1926                 :             :  * This must be called ONCE at the end of startup/recovery.
    1927                 :             :  */
    1928                 :             : void
    1929                 :        1101 : TrimMultiXact(void)
    1930                 :             : {
    1931                 :             :     MultiXactId nextMXact;
    1932                 :             :     MultiXactOffset offset;
    1933                 :             :     MultiXactId oldestMXact;
    1934                 :             :     Oid         oldestMXactDB;
    1935                 :             :     int64       pageno;
    1936                 :             :     int         entryno;
    1937                 :             :     int         flagsoff;
    1938                 :             : 
    1939                 :        1101 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    1940                 :        1101 :     nextMXact = MultiXactState->nextMXact;
    1941                 :        1101 :     offset = MultiXactState->nextOffset;
    1942                 :        1101 :     oldestMXact = MultiXactState->oldestMultiXactId;
    1943                 :        1101 :     oldestMXactDB = MultiXactState->oldestMultiXactDB;
    1944                 :        1101 :     LWLockRelease(MultiXactGenLock);
    1945                 :             : 
    1946                 :             :     /* Clean up offsets state */
    1947                 :             : 
    1948                 :             :     /*
    1949                 :             :      * (Re-)Initialize our idea of the latest page number for offsets.
    1950                 :             :      */
    1951                 :        1101 :     pageno = MultiXactIdToOffsetPage(nextMXact);
    1952                 :        1101 :     pg_atomic_write_u64(&MultiXactOffsetCtl->shared->latest_page_number,
    1953                 :             :                         pageno);
    1954                 :             : 
    1955                 :             :     /*
    1956                 :             :      * Set the offset of nextMXact on the offsets page.  This is normally done
    1957                 :             :      * in RecordNewMultiXact() of the previous multixact, but let's be sure
    1958                 :             :      * the next page exists, if the nextMXact was reset with pg_resetwal for
    1959                 :             :      * example.
    1960                 :             :      *
    1961                 :             :      * Zero out the remainder of the page.  See notes in TrimCLOG() for
    1962                 :             :      * background.  Unlike CLOG, some WAL record covers every pg_multixact
    1963                 :             :      * SLRU mutation.  Since, also unlike CLOG, we ignore the WAL rule "write
    1964                 :             :      * xlog before data," nextMXact successors may carry obsolete, nonzero
    1965                 :             :      * offset values.
    1966                 :             :      */
    1967                 :        1101 :     entryno = MultiXactIdToOffsetEntry(nextMXact);
    1968                 :             :     {
    1969                 :             :         int         slotno;
    1970                 :             :         MultiXactOffset *offptr;
    1971                 :        1101 :         LWLock     *lock = SimpleLruGetBankLock(MultiXactOffsetCtl, pageno);
    1972                 :             : 
    1973                 :        1101 :         LWLockAcquire(lock, LW_EXCLUSIVE);
    1974   [ +  +  +  + ]:        1101 :         if (entryno == 0 || nextMXact == FirstMultiXactId)
    1975                 :        1084 :             slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
    1976                 :             :         else
    1977                 :          17 :             slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, &nextMXact);
    1978                 :        1101 :         offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
    1979                 :        1101 :         offptr += entryno;
    1980                 :             : 
    1981                 :        1101 :         *offptr = offset;
    1982   [ +  +  +  - ]:        1101 :         if (entryno != 0 && (entryno + 1) * sizeof(MultiXactOffset) != BLCKSZ)
    1983   [ +  -  +  -  :        1721 :             MemSet(offptr + 1, 0, BLCKSZ - (entryno + 1) * sizeof(MultiXactOffset));
          +  -  +  +  +  
                      + ]
    1984                 :             : 
    1985                 :        1101 :         MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
    1986                 :        1101 :         LWLockRelease(lock);
    1987                 :             :     }
    1988                 :             : 
    1989                 :             :     /*
    1990                 :             :      * And the same for members.
    1991                 :             :      *
    1992                 :             :      * (Re-)Initialize our idea of the latest page number for members.
    1993                 :             :      */
    1994                 :        1101 :     pageno = MXOffsetToMemberPage(offset);
    1995                 :        1101 :     pg_atomic_write_u64(&MultiXactMemberCtl->shared->latest_page_number,
    1996                 :             :                         pageno);
    1997                 :             : 
    1998                 :             :     /*
    1999                 :             :      * Zero out the remainder of the current members page.  See notes in
    2000                 :             :      * TrimCLOG() for motivation.
    2001                 :             :      */
    2002                 :        1101 :     flagsoff = MXOffsetToFlagsOffset(offset);
    2003         [ +  + ]:        1101 :     if (flagsoff != 0)
    2004                 :             :     {
    2005                 :          15 :         MultiXactMemberSlruReadContext slru_read_context = {InvalidMultiXactId, offset};
    2006                 :             :         int         slotno;
    2007                 :             :         TransactionId *xidptr;
    2008                 :             :         int         memberoff;
    2009                 :          15 :         LWLock     *lock = SimpleLruGetBankLock(MultiXactMemberCtl, pageno);
    2010                 :             : 
    2011                 :          15 :         LWLockAcquire(lock, LW_EXCLUSIVE);
    2012                 :          15 :         memberoff = MXOffsetToMemberOffset(offset);
    2013                 :          15 :         slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, &slru_read_context);
    2014                 :          15 :         xidptr = (TransactionId *)
    2015                 :          15 :             (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
    2016                 :             : 
    2017   [ +  +  +  -  :          15 :         MemSet(xidptr, 0, BLCKSZ - memberoff);
          +  -  -  +  -  
                      - ]
    2018                 :             : 
    2019                 :             :         /*
    2020                 :             :          * Note: we don't need to zero out the flag bits in the remaining
    2021                 :             :          * members of the current group, because they are always reset before
    2022                 :             :          * writing.
    2023                 :             :          */
    2024                 :             : 
    2025                 :          15 :         MultiXactMemberCtl->shared->page_dirty[slotno] = true;
    2026                 :          15 :         LWLockRelease(lock);
    2027                 :             :     }
    2028                 :             : 
    2029                 :             :     /* signal that we're officially up */
    2030                 :        1101 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2031                 :        1101 :     MultiXactState->finishedStartup = true;
    2032                 :        1101 :     LWLockRelease(MultiXactGenLock);
    2033                 :             : 
    2034                 :             :     /* Now compute how far away the next multixid wraparound is. */
    2035                 :        1101 :     SetMultiXactIdLimit(oldestMXact, oldestMXactDB);
    2036                 :        1101 : }
    2037                 :             : 
    2038                 :             : /*
    2039                 :             :  * Get the MultiXact data to save in a checkpoint record
    2040                 :             :  */
    2041                 :             : void
    2042                 :        1864 : MultiXactGetCheckptMulti(bool is_shutdown,
    2043                 :             :                          MultiXactId *nextMulti,
    2044                 :             :                          MultiXactOffset *nextMultiOffset,
    2045                 :             :                          MultiXactId *oldestMulti,
    2046                 :             :                          Oid *oldestMultiDB)
    2047                 :             : {
    2048                 :        1864 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    2049                 :        1864 :     *nextMulti = MultiXactState->nextMXact;
    2050                 :        1864 :     *nextMultiOffset = MultiXactState->nextOffset;
    2051                 :        1864 :     *oldestMulti = MultiXactState->oldestMultiXactId;
    2052                 :        1864 :     *oldestMultiDB = MultiXactState->oldestMultiXactDB;
    2053                 :        1864 :     LWLockRelease(MultiXactGenLock);
    2054                 :             : 
    2055                 :             :     debug_elog6(DEBUG2,
    2056                 :             :                 "MultiXact: checkpoint is nextMulti %u, nextOffset %" PRIu64 ", oldestMulti %u in DB %u",
    2057                 :             :                 *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
    2058                 :        1864 : }
    2059                 :             : 
    2060                 :             : /*
    2061                 :             :  * Perform a checkpoint --- either during shutdown, or on-the-fly
    2062                 :             :  */
    2063                 :             : void
    2064                 :        2079 : CheckPointMultiXact(void)
    2065                 :             : {
    2066                 :             :     TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
    2067                 :             : 
    2068                 :             :     /*
    2069                 :             :      * Write dirty MultiXact pages to disk.  This may result in sync requests
    2070                 :             :      * queued for later handling by ProcessSyncRequests(), as part of the
    2071                 :             :      * checkpoint.
    2072                 :             :      */
    2073                 :        2079 :     SimpleLruWriteAll(MultiXactOffsetCtl, true);
    2074                 :        2079 :     SimpleLruWriteAll(MultiXactMemberCtl, true);
    2075                 :             : 
    2076                 :             :     TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
    2077                 :        2079 : }
    2078                 :             : 
    2079                 :             : /*
    2080                 :             :  * Set the next-to-be-assigned MultiXactId and offset
    2081                 :             :  *
    2082                 :             :  * This is used when we can determine the correct next ID/offset exactly
    2083                 :             :  * from a checkpoint record.  Although this is only called during bootstrap
    2084                 :             :  * and XLog replay, we take the lock in case any hot-standby backends are
    2085                 :             :  * examining the values.
    2086                 :             :  */
    2087                 :             : void
    2088                 :        1289 : MultiXactSetNextMXact(MultiXactId nextMulti,
    2089                 :             :                       MultiXactOffset nextMultiOffset)
    2090                 :             : {
    2091                 :             :     Assert(MultiXactIdIsValid(nextMulti));
    2092                 :             :     debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %" PRIu64,
    2093                 :             :                 nextMulti, nextMultiOffset);
    2094                 :             : 
    2095                 :        1289 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2096                 :        1289 :     MultiXactState->nextMXact = nextMulti;
    2097                 :        1289 :     MultiXactState->nextOffset = nextMultiOffset;
    2098                 :        1289 :     LWLockRelease(MultiXactGenLock);
    2099                 :        1289 : }
    2100                 :             : 
    2101                 :             : /*
    2102                 :             :  * Determine the last safe MultiXactId to allocate given the currently oldest
    2103                 :             :  * datminmxid (ie, the oldest MultiXactId that might exist in any database
    2104                 :             :  * of our cluster), and the OID of the (or a) database with that value.
    2105                 :             :  *
    2106                 :             :  * This also updates MultiXactState->oldestOffset, by looking up the offset of
    2107                 :             :  * MultiXactState->oldestMultiXactId.
    2108                 :             :  */
    2109                 :             : void
    2110                 :        3496 : SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid)
    2111                 :             : {
    2112                 :             :     MultiXactId multiVacLimit;
    2113                 :             :     MultiXactId multiWarnLimit;
    2114                 :             :     MultiXactId multiStopLimit;
    2115                 :             :     MultiXactId multiWrapLimit;
    2116                 :             :     MultiXactId curMulti;
    2117                 :             : 
    2118                 :             :     Assert(MultiXactIdIsValid(oldest_datminmxid));
    2119                 :             : 
    2120                 :             :     /*
    2121                 :             :      * We pretend that a wrap will happen halfway through the multixact ID
    2122                 :             :      * space, but that's not really true, because multixacts wrap differently
    2123                 :             :      * from transaction IDs.
    2124                 :             :      */
    2125                 :        3496 :     multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
    2126         [ -  + ]:        3496 :     if (multiWrapLimit < FirstMultiXactId)
    2127                 :           0 :         multiWrapLimit += FirstMultiXactId;
    2128                 :             : 
    2129                 :             :     /*
    2130                 :             :      * We'll refuse to continue assigning MultiXactIds once we get within 3M
    2131                 :             :      * multi of data loss.  See SetTransactionIdLimit.
    2132                 :             :      */
    2133                 :        3496 :     multiStopLimit = multiWrapLimit - 3000000;
    2134         [ -  + ]:        3496 :     if (multiStopLimit < FirstMultiXactId)
    2135                 :           0 :         multiStopLimit -= FirstMultiXactId;
    2136                 :             : 
    2137                 :             :     /*
    2138                 :             :      * We'll start complaining loudly when we get within 100M multis of data
    2139                 :             :      * loss.  This is kind of arbitrary, but if you let your gas gauge get
    2140                 :             :      * down to 5% of full, would you be looking for the next gas station?  We
    2141                 :             :      * need to be fairly liberal about this number because there are lots of
    2142                 :             :      * scenarios where most transactions are done by automatic clients that
    2143                 :             :      * won't pay attention to warnings.  (No, we're not gonna make this
    2144                 :             :      * configurable.  If you know enough to configure it, you know enough to
    2145                 :             :      * not get in this kind of trouble in the first place.)
    2146                 :             :      */
    2147                 :        3496 :     multiWarnLimit = multiWrapLimit - 100000000;
    2148         [ -  + ]:        3496 :     if (multiWarnLimit < FirstMultiXactId)
    2149                 :           0 :         multiWarnLimit -= FirstMultiXactId;
    2150                 :             : 
    2151                 :             :     /*
    2152                 :             :      * We'll start trying to force autovacuums when oldest_datminmxid gets to
    2153                 :             :      * be more than autovacuum_multixact_freeze_max_age mxids old.
    2154                 :             :      *
    2155                 :             :      * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
    2156                 :             :      * so that we don't have to worry about dealing with on-the-fly changes in
    2157                 :             :      * its value.  See SetTransactionIdLimit.
    2158                 :             :      */
    2159                 :        3496 :     multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
    2160         [ -  + ]:        3496 :     if (multiVacLimit < FirstMultiXactId)
    2161                 :           0 :         multiVacLimit += FirstMultiXactId;
    2162                 :             : 
    2163                 :             :     /* Grab lock for just long enough to set the new limit values */
    2164                 :        3496 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2165                 :        3496 :     MultiXactState->oldestMultiXactId = oldest_datminmxid;
    2166                 :        3496 :     MultiXactState->oldestMultiXactDB = oldest_datoid;
    2167                 :        3496 :     MultiXactState->multiVacLimit = multiVacLimit;
    2168                 :        3496 :     MultiXactState->multiWarnLimit = multiWarnLimit;
    2169                 :        3496 :     MultiXactState->multiStopLimit = multiStopLimit;
    2170                 :        3496 :     MultiXactState->multiWrapLimit = multiWrapLimit;
    2171                 :        3496 :     curMulti = MultiXactState->nextMXact;
    2172                 :        3496 :     LWLockRelease(MultiXactGenLock);
    2173                 :             : 
    2174                 :             :     /* Log the info */
    2175         [ +  + ]:        3496 :     ereport(DEBUG1,
    2176                 :             :             (errmsg_internal("MultiXactId wrap limit is %u, limited by database with OID %u",
    2177                 :             :                              multiWrapLimit, oldest_datoid)));
    2178                 :             : 
    2179                 :             :     /*
    2180                 :             :      * Computing the actual limits is only possible once the data directory is
    2181                 :             :      * in a consistent state. There's no need to compute the limits while
    2182                 :             :      * still replaying WAL - no decisions about new multis are made even
    2183                 :             :      * though multixact creations might be replayed. So we'll only do further
    2184                 :             :      * checks after TrimMultiXact() has been called.
    2185                 :             :      */
    2186         [ +  + ]:        3496 :     if (!MultiXactState->finishedStartup)
    2187                 :        1238 :         return;
    2188                 :             : 
    2189                 :             :     Assert(!InRecovery);
    2190                 :             : 
    2191                 :             :     /*
    2192                 :             :      * Offsets are 64-bits wide and never wrap around, so we don't need to
    2193                 :             :      * consider them for emergency autovacuum purposes.  But now that we're in
    2194                 :             :      * a consistent state, determine MultiXactState->oldestOffset.  It will be
    2195                 :             :      * used to adjust the freezing cutoff, to keep the members disk usage in
    2196                 :             :      * check.
    2197                 :             :      */
    2198                 :        2258 :     SetOldestOffset();
    2199                 :             : 
    2200                 :             :     /*
    2201                 :             :      * If past the autovacuum force point, immediately signal an autovac
    2202                 :             :      * request.  The reason for this is that autovac only processes one
    2203                 :             :      * database per invocation.  Once it's finished cleaning up the oldest
    2204                 :             :      * database, it'll call here, and we'll signal the postmaster to start
    2205                 :             :      * another iteration immediately if there are still any old databases.
    2206                 :             :      */
    2207   [ -  +  -  - ]:        2258 :     if (MultiXactIdPrecedes(multiVacLimit, curMulti) && IsUnderPostmaster)
    2208                 :           0 :         SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
    2209                 :             : 
    2210                 :             :     /* Give an immediate warning if past the wrap warn point */
    2211         [ -  + ]:        2258 :     if (MultiXactIdPrecedes(multiWarnLimit, curMulti))
    2212                 :             :     {
    2213                 :             :         char       *oldest_datname;
    2214                 :             : 
    2215                 :             :         /*
    2216                 :             :          * We can be called when not inside a transaction, for example during
    2217                 :             :          * StartupXLOG().  In such a case we cannot do database access, so we
    2218                 :             :          * must just report the oldest DB's OID.
    2219                 :             :          *
    2220                 :             :          * Note: it's also possible that get_database_name fails and returns
    2221                 :             :          * NULL, for example because the database just got dropped.  We'll
    2222                 :             :          * still warn, even though the warning might now be unnecessary.
    2223                 :             :          */
    2224         [ #  # ]:           0 :         if (IsTransactionState())
    2225                 :           0 :             oldest_datname = get_database_name(oldest_datoid);
    2226                 :             :         else
    2227                 :           0 :             oldest_datname = NULL;
    2228                 :             : 
    2229         [ #  # ]:           0 :         if (oldest_datname)
    2230         [ #  # ]:           0 :             ereport(WARNING,
    2231                 :             :                     (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
    2232                 :             :                                    "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
    2233                 :             :                                    multiWrapLimit - curMulti,
    2234                 :             :                                    oldest_datname,
    2235                 :             :                                    multiWrapLimit - curMulti),
    2236                 :             :                      errdetail("Approximately %.2f%% of MultiXactId space remains before wraparound.",
    2237                 :             :                                (double) (multiWrapLimit - curMulti) / (MaxMultiXactId / 2) * 100),
    2238                 :             :                      errhint("To avoid MultiXactId assignment failures, execute a database-wide VACUUM in that database.\n"
    2239                 :             :                              "You might also need to commit or roll back old prepared transactions.")));
    2240                 :             :         else
    2241         [ #  # ]:           0 :             ereport(WARNING,
    2242                 :             :                     (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
    2243                 :             :                                    "database with OID %u must be vacuumed before %u more MultiXactIds are used",
    2244                 :             :                                    multiWrapLimit - curMulti,
    2245                 :             :                                    oldest_datoid,
    2246                 :             :                                    multiWrapLimit - curMulti),
    2247                 :             :                      errdetail("Approximately %.2f%% of MultiXactId space remains before wraparound.",
    2248                 :             :                                (double) (multiWrapLimit - curMulti) / (MaxMultiXactId / 2) * 100),
    2249                 :             :                      errhint("To avoid MultiXactId assignment failures, execute a database-wide VACUUM in that database.\n"
    2250                 :             :                              "You might also need to commit or roll back old prepared transactions.")));
    2251                 :             :     }
    2252                 :             : }
    2253                 :             : 
    2254                 :             : /*
    2255                 :             :  * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
    2256                 :             :  * and similarly nextOffset is at least minMultiOffset.
    2257                 :             :  *
    2258                 :             :  * This is used when we can determine minimum safe values from an XLog
    2259                 :             :  * record (either an on-line checkpoint or an mxact creation log entry).
    2260                 :             :  * Although this is only called during XLog replay, we take the lock in case
    2261                 :             :  * any hot-standby backends are examining the values.
    2262                 :             :  */
    2263                 :             : void
    2264                 :         746 : MultiXactAdvanceNextMXact(MultiXactId minMulti,
    2265                 :             :                           MultiXactOffset minMultiOffset)
    2266                 :             : {
    2267                 :             :     Assert(MultiXactIdIsValid(minMulti));
    2268                 :             : 
    2269                 :         746 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2270         [ +  + ]:         746 :     if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
    2271                 :             :     {
    2272                 :             :         debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
    2273                 :           9 :         MultiXactState->nextMXact = minMulti;
    2274                 :             :     }
    2275         [ +  + ]:         746 :     if (MultiXactState->nextOffset < minMultiOffset)
    2276                 :             :     {
    2277                 :             :         debug_elog3(DEBUG2, "MultiXact: setting next offset to %" PRIu64,
    2278                 :             :                     minMultiOffset);
    2279                 :           9 :         MultiXactState->nextOffset = minMultiOffset;
    2280                 :             :     }
    2281                 :         746 :     LWLockRelease(MultiXactGenLock);
    2282                 :         746 : }
    2283                 :             : 
    2284                 :             : /*
    2285                 :             :  * Update our oldestMultiXactId value, but only if it's more recent than what
    2286                 :             :  * we had.
    2287                 :             :  *
    2288                 :             :  * This may only be called during WAL replay.
    2289                 :             :  */
    2290                 :             : void
    2291                 :         788 : MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
    2292                 :             : {
    2293                 :             :     Assert(InRecovery);
    2294                 :             : 
    2295         [ -  + ]:         788 :     if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
    2296                 :           0 :         SetMultiXactIdLimit(oldestMulti, oldestMultiDB);
    2297                 :         788 : }
    2298                 :             : 
    2299                 :             : /*
    2300                 :             :  * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
    2301                 :             :  *
    2302                 :             :  * NB: this is called while holding MultiXactGenLock.  We want it to be very
    2303                 :             :  * fast most of the time; even when it's not so fast, no actual I/O need
    2304                 :             :  * happen unless we're forced to write out a dirty log or xlog page to make
    2305                 :             :  * room in shared memory.
    2306                 :             :  */
    2307                 :             : static void
    2308                 :        5335 : ExtendMultiXactOffset(MultiXactId multi)
    2309                 :             : {
    2310                 :             :     int64       pageno;
    2311                 :             :     LWLock     *lock;
    2312                 :             : 
    2313                 :             :     /*
    2314                 :             :      * No work except at first MultiXactId of a page.  But beware: just after
    2315                 :             :      * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
    2316                 :             :      */
    2317   [ +  +  +  + ]:        5335 :     if (MultiXactIdToOffsetEntry(multi) != 0 &&
    2318                 :             :         multi != FirstMultiXactId)
    2319                 :        5330 :         return;
    2320                 :             : 
    2321                 :           5 :     pageno = MultiXactIdToOffsetPage(multi);
    2322                 :           5 :     lock = SimpleLruGetBankLock(MultiXactOffsetCtl, pageno);
    2323                 :             : 
    2324                 :           5 :     LWLockAcquire(lock, LW_EXCLUSIVE);
    2325                 :             : 
    2326                 :             :     /* Zero the page and make a WAL entry about it */
    2327                 :           5 :     SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
    2328                 :           5 :     XLogSimpleInsertInt64(RM_MULTIXACT_ID, XLOG_MULTIXACT_ZERO_OFF_PAGE,
    2329                 :             :                           pageno);
    2330                 :             : 
    2331                 :           5 :     LWLockRelease(lock);
    2332                 :             : }
    2333                 :             : 
    2334                 :             : /*
    2335                 :             :  * Make sure that MultiXactMember has room for the members of a newly-
    2336                 :             :  * allocated MultiXactId.
    2337                 :             :  *
    2338                 :             :  * Like the above routine, this is called while holding MultiXactGenLock;
    2339                 :             :  * same comments apply.
    2340                 :             :  */
    2341                 :             : static void
    2342                 :        5335 : ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
    2343                 :             : {
    2344                 :             :     /*
    2345                 :             :      * It's possible that the members span more than one page of the members
    2346                 :             :      * file, so we loop to ensure we consider each page.  The coding is not
    2347                 :             :      * optimal if the members span several pages, but that seems unusual
    2348                 :             :      * enough to not worry much about.
    2349                 :             :      */
    2350         [ +  + ]:       10724 :     while (nmembers > 0)
    2351                 :             :     {
    2352                 :             :         int         flagsoff;
    2353                 :             :         int         flagsbit;
    2354                 :             :         uint32      difference;
    2355                 :             : 
    2356                 :             :         /*
    2357                 :             :          * Only zero when at first entry of a page.
    2358                 :             :          */
    2359                 :        5389 :         flagsoff = MXOffsetToFlagsOffset(offset);
    2360                 :        5389 :         flagsbit = MXOffsetToFlagsBitShift(offset);
    2361   [ +  +  +  + ]:        5389 :         if (flagsoff == 0 && flagsbit == 0)
    2362                 :             :         {
    2363                 :             :             int64       pageno;
    2364                 :             :             LWLock     *lock;
    2365                 :             : 
    2366                 :          57 :             pageno = MXOffsetToMemberPage(offset);
    2367                 :          57 :             lock = SimpleLruGetBankLock(MultiXactMemberCtl, pageno);
    2368                 :             : 
    2369                 :          57 :             LWLockAcquire(lock, LW_EXCLUSIVE);
    2370                 :             : 
    2371                 :             :             /* Zero the page and make a WAL entry about it */
    2372                 :          57 :             SimpleLruZeroPage(MultiXactMemberCtl, pageno);
    2373                 :          57 :             XLogSimpleInsertInt64(RM_MULTIXACT_ID,
    2374                 :             :                                   XLOG_MULTIXACT_ZERO_MEM_PAGE, pageno);
    2375                 :             : 
    2376                 :          57 :             LWLockRelease(lock);
    2377                 :             :         }
    2378                 :             : 
    2379                 :             :         /* Compute the number of items till end of current page. */
    2380                 :        5389 :         difference = MULTIXACT_MEMBERS_PER_PAGE - offset % MULTIXACT_MEMBERS_PER_PAGE;
    2381                 :             : 
    2382                 :             :         /*
    2383                 :             :          * Advance to next page.  OK if nmembers goes negative.
    2384                 :             :          */
    2385                 :        5389 :         nmembers -= difference;
    2386                 :        5389 :         offset += difference;
    2387                 :             :     }
    2388                 :        5335 : }
    2389                 :             : 
    2390                 :             : /*
    2391                 :             :  * GetOldestMultiXactId
    2392                 :             :  *
    2393                 :             :  * Return the oldest MultiXactId that's still possibly still seen as live by
    2394                 :             :  * any running transaction.  Older ones might still exist on disk, but they no
    2395                 :             :  * longer have any running member transaction.
    2396                 :             :  *
    2397                 :             :  * It's not safe to truncate MultiXact SLRU segments on the value returned by
    2398                 :             :  * this function; however, it can be set as the new relminmxid for any table
    2399                 :             :  * that VACUUM knows has no remaining MXIDs < the same value.  It is only safe
    2400                 :             :  * to truncate SLRUs when no table can possibly still have a referencing MXID.
    2401                 :             :  */
    2402                 :             : MultiXactId
    2403                 :      167677 : GetOldestMultiXactId(void)
    2404                 :             : {
    2405                 :             :     MultiXactId oldestMXact;
    2406                 :             : 
    2407                 :             :     /*
    2408                 :             :      * This is the oldest valid value among all the OldestMemberMXactId[] and
    2409                 :             :      * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
    2410                 :             :      */
    2411                 :      167677 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    2412                 :      167677 :     oldestMXact = MultiXactState->nextMXact;
    2413         [ +  + ]:    20911467 :     for (int i = 0; i < NumMemberSlots; i++)
    2414                 :             :     {
    2415                 :             :         MultiXactId thisoldest;
    2416                 :             : 
    2417                 :    20743790 :         thisoldest = OldestMemberMXactId[i];
    2418   [ +  +  +  + ]:    20784323 :         if (MultiXactIdIsValid(thisoldest) &&
    2419                 :       40533 :             MultiXactIdPrecedes(thisoldest, oldestMXact))
    2420                 :          56 :             oldestMXact = thisoldest;
    2421                 :             :     }
    2422         [ +  + ]:    20798903 :     for (int i = 0; i < NumVisibleSlots; i++)
    2423                 :             :     {
    2424                 :             :         MultiXactId thisoldest;
    2425                 :             : 
    2426                 :    20631226 :         thisoldest = OldestVisibleMXactId[i];
    2427   [ +  +  +  + ]:    20631238 :         if (MultiXactIdIsValid(thisoldest) &&
    2428                 :          12 :             MultiXactIdPrecedes(thisoldest, oldestMXact))
    2429                 :           2 :             oldestMXact = thisoldest;
    2430                 :             :     }
    2431                 :             : 
    2432                 :      167677 :     LWLockRelease(MultiXactGenLock);
    2433                 :             : 
    2434                 :      167677 :     return oldestMXact;
    2435                 :             : }
    2436                 :             : 
    2437                 :             : /*
    2438                 :             :  * Calculate the oldest member offset and install it in MultiXactState, where
    2439                 :             :  * it can be used to adjust multixid freezing cutoffs.
    2440                 :             :  */
    2441                 :             : static void
    2442                 :        2258 : SetOldestOffset(void)
    2443                 :             : {
    2444                 :             :     MultiXactId oldestMultiXactId;
    2445                 :             :     MultiXactId nextMXact;
    2446                 :        2258 :     MultiXactOffset oldestOffset = 0;   /* placate compiler */
    2447                 :             :     MultiXactOffset nextOffset;
    2448                 :        2258 :     bool        oldestOffsetKnown = false;
    2449                 :             : 
    2450                 :             :     /*
    2451                 :             :      * NB: Have to prevent concurrent truncation, we might otherwise try to
    2452                 :             :      * lookup an oldestMulti that's concurrently getting truncated away.
    2453                 :             :      */
    2454                 :        2258 :     LWLockAcquire(MultiXactTruncationLock, LW_SHARED);
    2455                 :             : 
    2456                 :             :     /* Read relevant fields from shared memory. */
    2457                 :        2258 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    2458                 :        2258 :     oldestMultiXactId = MultiXactState->oldestMultiXactId;
    2459                 :        2258 :     nextMXact = MultiXactState->nextMXact;
    2460                 :        2258 :     nextOffset = MultiXactState->nextOffset;
    2461                 :             :     Assert(MultiXactState->finishedStartup);
    2462                 :        2258 :     LWLockRelease(MultiXactGenLock);
    2463                 :             : 
    2464                 :             :     /*
    2465                 :             :      * Determine the offset of the oldest multixact.  Normally, we can read
    2466                 :             :      * the offset from the multixact itself, but there's an important special
    2467                 :             :      * case: if there are no multixacts in existence at all, oldestMXact
    2468                 :             :      * obviously can't point to one.  It will instead point to the multixact
    2469                 :             :      * ID that will be assigned the next time one is needed.
    2470                 :             :      */
    2471         [ +  + ]:        2258 :     if (oldestMultiXactId == nextMXact)
    2472                 :             :     {
    2473                 :             :         /*
    2474                 :             :          * When the next multixact gets created, it will be stored at the next
    2475                 :             :          * offset.
    2476                 :             :          */
    2477                 :        2238 :         oldestOffset = nextOffset;
    2478                 :        2238 :         oldestOffsetKnown = true;
    2479                 :             :     }
    2480                 :             :     else
    2481                 :             :     {
    2482                 :             :         /*
    2483                 :             :          * Look up the offset at which the oldest existing multixact's members
    2484                 :             :          * are stored.  If we cannot find it, be careful not to fail, and
    2485                 :             :          * leave oldestOffset unchanged.  oldestOffset is initialized to zero
    2486                 :             :          * at system startup, which prevents truncating members until a proper
    2487                 :             :          * value is calculated.
    2488                 :             :          *
    2489                 :             :          * (We had bugs in early releases of PostgreSQL 9.3.X and 9.4.X where
    2490                 :             :          * the supposedly-earliest multixact might not really exist.  Those
    2491                 :             :          * should be long gone by now, so this should not fail, but let's
    2492                 :             :          * still be defensive.)
    2493                 :             :          */
    2494                 :             :         oldestOffsetKnown =
    2495                 :          20 :             find_multixact_start(oldestMultiXactId, &oldestOffset);
    2496                 :             : 
    2497         [ +  - ]:          20 :         if (oldestOffsetKnown)
    2498         [ -  + ]:          20 :             ereport(DEBUG1,
    2499                 :             :                     (errmsg_internal("oldest MultiXactId member is at offset %" PRIu64,
    2500                 :             :                                      oldestOffset)));
    2501                 :             :         else
    2502         [ #  # ]:           0 :             ereport(LOG,
    2503                 :             :                     (errmsg("MultiXact member truncation is disabled because oldest checkpointed MultiXact %u does not exist on disk",
    2504                 :             :                             oldestMultiXactId)));
    2505                 :             :     }
    2506                 :             : 
    2507                 :        2258 :     LWLockRelease(MultiXactTruncationLock);
    2508                 :             : 
    2509                 :             :     /* Install the computed value */
    2510         [ +  - ]:        2258 :     if (oldestOffsetKnown)
    2511                 :             :     {
    2512                 :        2258 :         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2513                 :        2258 :         MultiXactState->oldestOffset = oldestOffset;
    2514                 :        2258 :         LWLockRelease(MultiXactGenLock);
    2515                 :             :     }
    2516                 :        2258 : }
    2517                 :             : 
    2518                 :             : /*
    2519                 :             :  * Find the starting offset of the given MultiXactId.
    2520                 :             :  *
    2521                 :             :  * Returns false if the file containing the multi does not exist on disk.
    2522                 :             :  * Otherwise, returns true and sets *result to the starting member offset.
    2523                 :             :  *
    2524                 :             :  * This function does not prevent concurrent truncation, so if that's
    2525                 :             :  * required, the caller has to protect against that.
    2526                 :             :  */
    2527                 :             : static bool
    2528                 :          20 : find_multixact_start(MultiXactId multi, MultiXactOffset *result)
    2529                 :             : {
    2530                 :             :     MultiXactOffset offset;
    2531                 :             :     int64       pageno;
    2532                 :             :     int         entryno;
    2533                 :             :     int         slotno;
    2534                 :             :     MultiXactOffset *offptr;
    2535                 :             : 
    2536                 :             :     Assert(MultiXactState->finishedStartup);
    2537                 :             : 
    2538                 :          20 :     pageno = MultiXactIdToOffsetPage(multi);
    2539                 :          20 :     entryno = MultiXactIdToOffsetEntry(multi);
    2540                 :             : 
    2541                 :             :     /*
    2542                 :             :      * Write out dirty data, so PhysicalPageExists can work correctly.
    2543                 :             :      */
    2544                 :          20 :     SimpleLruWriteAll(MultiXactOffsetCtl, true);
    2545                 :          20 :     SimpleLruWriteAll(MultiXactMemberCtl, true);
    2546                 :             : 
    2547         [ -  + ]:          20 :     if (!SimpleLruDoesPhysicalPageExist(MultiXactOffsetCtl, pageno))
    2548                 :           0 :         return false;
    2549                 :             : 
    2550                 :             :     /* lock is acquired by SimpleLruReadPage_ReadOnly */
    2551                 :          20 :     slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno, &multi);
    2552                 :          20 :     offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
    2553                 :          20 :     offptr += entryno;
    2554                 :          20 :     offset = *offptr;
    2555                 :          20 :     LWLockRelease(SimpleLruGetBankLock(MultiXactOffsetCtl, pageno));
    2556                 :             : 
    2557                 :          20 :     *result = offset;
    2558                 :          20 :     return true;
    2559                 :             : }
    2560                 :             : 
    2561                 :             : /*
    2562                 :             :  * GetMultiXactInfo
    2563                 :             :  *
    2564                 :             :  * Returns information about the current MultiXact state, as of:
    2565                 :             :  * multixacts: Number of MultiXacts (nextMultiXactId - oldestMultiXactId)
    2566                 :             :  * nextOffset: Next-to-be-assigned offset
    2567                 :             :  * oldestMultiXactId: Oldest MultiXact ID still in use
    2568                 :             :  * oldestOffset: Oldest offset still in use
    2569                 :             :  */
    2570                 :             : void
    2571                 :      123191 : GetMultiXactInfo(uint32 *multixacts, MultiXactOffset *nextOffset,
    2572                 :             :                  MultiXactId *oldestMultiXactId, MultiXactOffset *oldestOffset)
    2573                 :             : {
    2574                 :             :     MultiXactId nextMultiXactId;
    2575                 :             : 
    2576                 :      123191 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    2577                 :      123191 :     *nextOffset = MultiXactState->nextOffset;
    2578                 :      123191 :     *oldestMultiXactId = MultiXactState->oldestMultiXactId;
    2579                 :      123191 :     nextMultiXactId = MultiXactState->nextMXact;
    2580                 :      123191 :     *oldestOffset = MultiXactState->oldestOffset;
    2581                 :      123191 :     LWLockRelease(MultiXactGenLock);
    2582                 :             : 
    2583                 :      123191 :     *multixacts = nextMultiXactId - *oldestMultiXactId;
    2584                 :      123191 : }
    2585                 :             : 
    2586                 :             : /*
    2587                 :             :  * Multixact members can be removed once the multixacts that refer to them
    2588                 :             :  * are older than every datminmxid.  autovacuum_multixact_freeze_max_age and
    2589                 :             :  * vacuum_multixact_freeze_table_age work together to make sure we never have
    2590                 :             :  * too many multixacts; we hope that, at least under normal circumstances,
    2591                 :             :  * this will also be sufficient to keep us from using too many offsets.
    2592                 :             :  * However, if the average multixact has many members, we might accumulate a
    2593                 :             :  * large amount of members, consuming disk space, while still using few enough
    2594                 :             :  * multixids that the multixid limits fail to trigger relminmxid advancement
    2595                 :             :  * by VACUUM.
    2596                 :             :  *
    2597                 :             :  * To prevent that, if the members space usage exceeds a threshold
    2598                 :             :  * (MULTIXACT_MEMBER_LOW_THRESHOLD), we effectively reduce
    2599                 :             :  * autovacuum_multixact_freeze_max_age to a value just less than the number of
    2600                 :             :  * multixacts in use.  We hope that this will quickly trigger autovacuuming on
    2601                 :             :  * the table or tables with the oldest relminmxid, thus allowing datminmxid
    2602                 :             :  * values to advance and removing some members.
    2603                 :             :  *
    2604                 :             :  * As the amount of the member space in use grows, we become more aggressive
    2605                 :             :  * in clamping this value.  That not only causes autovacuum to ramp up, but
    2606                 :             :  * also makes any manual vacuums the user issues more aggressive.  This
    2607                 :             :  * happens because vacuum_get_cutoffs() will clamp the freeze table and the
    2608                 :             :  * minimum freeze age cutoffs based on the effective
    2609                 :             :  * autovacuum_multixact_freeze_max_age this function returns.  At the extreme,
    2610                 :             :  * when the members usage reaches MULTIXACT_MEMBER_HIGH_THRESHOLD, we clamp
    2611                 :             :  * freeze_max_age to zero, and every vacuum of any table will freeze every
    2612                 :             :  * multixact.
    2613                 :             :  */
    2614                 :             : int
    2615                 :      123180 : MultiXactMemberFreezeThreshold(void)
    2616                 :             : {
    2617                 :             :     uint32      multixacts;
    2618                 :             :     uint32      victim_multixacts;
    2619                 :             :     double      fraction;
    2620                 :             :     int         result;
    2621                 :             :     MultiXactId oldestMultiXactId;
    2622                 :             :     MultiXactOffset oldestOffset;
    2623                 :             :     MultiXactOffset nextOffset;
    2624                 :             :     uint64      members;
    2625                 :             : 
    2626                 :             :     /* Read the current offsets and multixact usage. */
    2627                 :      123180 :     GetMultiXactInfo(&multixacts, &nextOffset, &oldestMultiXactId, &oldestOffset);
    2628                 :      123180 :     members = nextOffset - oldestOffset;
    2629                 :             : 
    2630                 :             :     /* If member space utilization is low, no special action is required. */
    2631         [ +  - ]:      123180 :     if (members <= MULTIXACT_MEMBER_LOW_THRESHOLD)
    2632                 :      123180 :         return autovacuum_multixact_freeze_max_age;
    2633                 :             : 
    2634                 :             :     /*
    2635                 :             :      * Compute a target for relminmxid advancement.  The number of multixacts
    2636                 :             :      * we try to eliminate from the system is based on how far we are past
    2637                 :             :      * MULTIXACT_MEMBER_LOW_THRESHOLD.
    2638                 :             :      *
    2639                 :             :      * The way this formula works is that when members is exactly at the low
    2640                 :             :      * threshold, fraction = 0.0, and we set freeze_max_age equal to
    2641                 :             :      * mxid_age(oldestMultiXactId).  As members grows further, towards the
    2642                 :             :      * high threshold, fraction grows linearly from 0.0 to 1.0, and the result
    2643                 :             :      * shrinks from mxid_age(oldestMultiXactId) to 0.  Beyond the high
    2644                 :             :      * threshold, fraction > 1.0 and the result is clamped to 0.
    2645                 :             :      */
    2646                 :           0 :     fraction = (double) (members - MULTIXACT_MEMBER_LOW_THRESHOLD) /
    2647                 :             :         (MULTIXACT_MEMBER_HIGH_THRESHOLD - MULTIXACT_MEMBER_LOW_THRESHOLD);
    2648                 :             : 
    2649                 :             :     /* fraction could be > 1.0, but lowest possible freeze age is zero */
    2650         [ #  # ]:           0 :     if (fraction >= 1.0)
    2651                 :           0 :         return 0;
    2652                 :             : 
    2653                 :           0 :     victim_multixacts = multixacts * fraction;
    2654                 :           0 :     result = multixacts - victim_multixacts;
    2655                 :             : 
    2656                 :             :     /*
    2657                 :             :      * Clamp to autovacuum_multixact_freeze_max_age, so that we never make
    2658                 :             :      * autovacuum less aggressive than it would otherwise be.
    2659                 :             :      */
    2660                 :           0 :     return Min(result, autovacuum_multixact_freeze_max_age);
    2661                 :             : }
    2662                 :             : 
    2663                 :             : 
    2664                 :             : /*
    2665                 :             :  * Delete members segments older than newOldestOffset
    2666                 :             :  */
    2667                 :             : static void
    2668                 :           0 : PerformMembersTruncation(MultiXactOffset newOldestOffset)
    2669                 :             : {
    2670                 :             :     /*
    2671                 :             :      * We step back one entry to avoid passing a cutoff page that hasn't been
    2672                 :             :      * created yet in the rare case that oldestOffset would be the first item
    2673                 :             :      * on a page and oldestOffset == nextOffset.  In that case, if we didn't
    2674                 :             :      * subtract one, we'd trigger SimpleLruTruncate's wraparound detection.
    2675                 :             :      */
    2676         [ #  # ]:           0 :     if (newOldestOffset <= 1)
    2677                 :           0 :         return;
    2678                 :           0 :     SimpleLruTruncate(MultiXactMemberCtl,
    2679                 :             :                       MXOffsetToMemberPage(newOldestOffset - 1));
    2680                 :             : }
    2681                 :             : 
    2682                 :             : /*
    2683                 :             :  * Delete offsets segments older than newOldestMulti
    2684                 :             :  */
    2685                 :             : static void
    2686                 :           0 : PerformOffsetsTruncation(MultiXactId newOldestMulti)
    2687                 :             : {
    2688                 :             :     /*
    2689                 :             :      * Like in PerformMembersTruncation(), step back one entry to avoid
    2690                 :             :      * passing a cutoff page that hasn't been created yet.
    2691                 :             :      */
    2692                 :           0 :     SimpleLruTruncate(MultiXactOffsetCtl,
    2693                 :             :                       MultiXactIdToOffsetPage(PreviousMultiXactId(newOldestMulti)));
    2694                 :           0 : }
    2695                 :             : 
    2696                 :             : /*
    2697                 :             :  * Remove all MultiXactOffset and MultiXactMember segments before the oldest
    2698                 :             :  * ones still of interest.
    2699                 :             :  *
    2700                 :             :  * This is only called on a primary as part of vacuum (via
    2701                 :             :  * vac_truncate_clog()). During recovery truncation is done by replaying
    2702                 :             :  * truncation WAL records logged here.
    2703                 :             :  *
    2704                 :             :  * newOldestMulti is the oldest currently required multixact, newOldestMultiDB
    2705                 :             :  * is one of the databases preventing newOldestMulti from increasing.
    2706                 :             :  */
    2707                 :             : void
    2708                 :        1157 : TruncateMultiXact(MultiXactId newOldestMulti, Oid newOldestMultiDB)
    2709                 :             : {
    2710                 :             :     MultiXactId oldestMulti;
    2711                 :             :     MultiXactId nextMulti;
    2712                 :             :     MultiXactOffset newOldestOffset;
    2713                 :             :     MultiXactOffset nextOffset;
    2714                 :             : 
    2715                 :             :     Assert(!RecoveryInProgress());
    2716                 :             :     Assert(MultiXactState->finishedStartup);
    2717                 :             :     Assert(MultiXactIdIsValid(newOldestMulti));
    2718                 :             : 
    2719                 :             :     /*
    2720                 :             :      * We can only allow one truncation to happen at once. Otherwise parts of
    2721                 :             :      * members might vanish while we're doing lookups or similar. There's no
    2722                 :             :      * need to have an interlock with creating new multis or such, since those
    2723                 :             :      * are constrained by the limits (which only grow, never shrink).
    2724                 :             :      */
    2725                 :        1157 :     LWLockAcquire(MultiXactTruncationLock, LW_EXCLUSIVE);
    2726                 :             : 
    2727                 :        1157 :     LWLockAcquire(MultiXactGenLock, LW_SHARED);
    2728                 :        1157 :     nextMulti = MultiXactState->nextMXact;
    2729                 :        1157 :     nextOffset = MultiXactState->nextOffset;
    2730                 :        1157 :     oldestMulti = MultiXactState->oldestMultiXactId;
    2731                 :        1157 :     LWLockRelease(MultiXactGenLock);
    2732                 :             : 
    2733                 :             :     /*
    2734                 :             :      * Make sure to only attempt truncation if there's values to truncate
    2735                 :             :      * away. In normal processing values shouldn't go backwards, but there's
    2736                 :             :      * some corner cases (due to bugs) where that's possible.
    2737                 :             :      */
    2738         [ +  - ]:        1157 :     if (MultiXactIdPrecedesOrEquals(newOldestMulti, oldestMulti))
    2739                 :             :     {
    2740                 :        1157 :         LWLockRelease(MultiXactTruncationLock);
    2741                 :        1157 :         return;
    2742                 :             :     }
    2743                 :             : 
    2744                 :             :     /*
    2745                 :             :      * Compute up to where to truncate MultiXactMember. Lookup the
    2746                 :             :      * corresponding member offset for newOldestMulti for that.
    2747                 :             :      */
    2748         [ #  # ]:           0 :     if (newOldestMulti == nextMulti)
    2749                 :             :     {
    2750                 :             :         /* there are NO MultiXacts */
    2751                 :           0 :         newOldestOffset = nextOffset;
    2752                 :             :     }
    2753         [ #  # ]:           0 :     else if (!find_multixact_start(newOldestMulti, &newOldestOffset))
    2754                 :             :     {
    2755         [ #  # ]:           0 :         ereport(LOG,
    2756                 :             :                 (errmsg("cannot truncate up to MultiXact %u because it does not exist on disk, skipping truncation",
    2757                 :             :                         newOldestMulti)));
    2758                 :           0 :         LWLockRelease(MultiXactTruncationLock);
    2759                 :           0 :         return;
    2760                 :             :     }
    2761                 :             : 
    2762                 :             :     /*
    2763                 :             :      * On crash, MultiXactIdCreateFromMembers() can leave behind multixids
    2764                 :             :      * that were not yet written out and hence have zero offset on disk. If
    2765                 :             :      * such a multixid becomes oldestMulti, we won't be able to look up its
    2766                 :             :      * offset. That should be rare, so we don't try to do anything smart about
    2767                 :             :      * it. Just skip the truncation, and hope that by the next truncation
    2768                 :             :      * attempt, oldestMulti has advanced to a valid multixid.
    2769                 :             :      */
    2770         [ #  # ]:           0 :     if (newOldestOffset == 0)
    2771                 :             :     {
    2772         [ #  # ]:           0 :         ereport(LOG,
    2773                 :             :                 (errmsg("cannot truncate up to MultiXact %u because it has invalid offset, skipping truncation",
    2774                 :             :                         newOldestMulti)));
    2775                 :           0 :         LWLockRelease(MultiXactTruncationLock);
    2776                 :           0 :         return;
    2777                 :             :     }
    2778                 :             : 
    2779         [ #  # ]:           0 :     elog(DEBUG1, "performing multixact truncation: "
    2780                 :             :          "oldestMulti %u (offsets segment %" PRIx64 "), "
    2781                 :             :          "oldestOffset %" PRIu64 " (members segment %" PRIx64 ")",
    2782                 :             :          newOldestMulti,
    2783                 :             :          MultiXactIdToOffsetSegment(newOldestMulti),
    2784                 :             :          newOldestOffset,
    2785                 :             :          MXOffsetToMemberSegment(newOldestOffset));
    2786                 :             : 
    2787                 :             :     /*
    2788                 :             :      * Do truncation, and the WAL logging of the truncation, in a critical
    2789                 :             :      * section. That way offsets/members cannot get out of sync anymore, i.e.
    2790                 :             :      * once consistent the newOldestMulti will always exist in members, even
    2791                 :             :      * if we crashed in the wrong moment.
    2792                 :             :      */
    2793                 :           0 :     START_CRIT_SECTION();
    2794                 :             : 
    2795                 :             :     /*
    2796                 :             :      * Prevent checkpoints from being scheduled concurrently. This is critical
    2797                 :             :      * because otherwise a truncation record might not be replayed after a
    2798                 :             :      * crash/basebackup, even though the state of the data directory would
    2799                 :             :      * require it.
    2800                 :             :      */
    2801                 :             :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
    2802                 :           0 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START;
    2803                 :             : 
    2804                 :             :     /* WAL log truncation */
    2805                 :           0 :     WriteMTruncateXlogRec(newOldestMultiDB, newOldestMulti, newOldestOffset);
    2806                 :             : 
    2807                 :             :     /*
    2808                 :             :      * Update in-memory limits before performing the truncation, while inside
    2809                 :             :      * the critical section: Have to do it before truncation, to prevent
    2810                 :             :      * concurrent lookups of those values. Has to be inside the critical
    2811                 :             :      * section as otherwise a future call to this function would error out,
    2812                 :             :      * while looking up the oldest member in offsets, if our caller crashes
    2813                 :             :      * before updating the limits.
    2814                 :             :      */
    2815                 :           0 :     LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
    2816                 :           0 :     MultiXactState->oldestMultiXactId = newOldestMulti;
    2817                 :           0 :     MultiXactState->oldestMultiXactDB = newOldestMultiDB;
    2818                 :           0 :     MultiXactState->oldestOffset = newOldestOffset;
    2819                 :           0 :     LWLockRelease(MultiXactGenLock);
    2820                 :             : 
    2821                 :             :     /* First truncate members */
    2822                 :           0 :     PerformMembersTruncation(newOldestOffset);
    2823                 :             : 
    2824                 :             :     /* Then offsets */
    2825                 :           0 :     PerformOffsetsTruncation(newOldestMulti);
    2826                 :             : 
    2827                 :           0 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
    2828                 :             : 
    2829                 :           0 :     END_CRIT_SECTION();
    2830                 :           0 :     LWLockRelease(MultiXactTruncationLock);
    2831                 :             : }
    2832                 :             : 
    2833                 :             : /*
    2834                 :             :  * Decide whether a MultiXactOffset page number is "older" for truncation
    2835                 :             :  * purposes.  Analogous to CLOGPagePrecedes().
    2836                 :             :  *
    2837                 :             :  * Offsetting the values is optional, because MultiXactIdPrecedes() has
    2838                 :             :  * translational symmetry.
    2839                 :             :  */
    2840                 :             : static bool
    2841                 :           0 : MultiXactOffsetPagePrecedes(int64 page1, int64 page2)
    2842                 :             : {
    2843                 :             :     MultiXactId multi1;
    2844                 :             :     MultiXactId multi2;
    2845                 :             : 
    2846                 :           0 :     multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
    2847                 :           0 :     multi1 += FirstMultiXactId + 1;
    2848                 :           0 :     multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
    2849                 :           0 :     multi2 += FirstMultiXactId + 1;
    2850                 :             : 
    2851   [ #  #  #  # ]:           0 :     return (MultiXactIdPrecedes(multi1, multi2) &&
    2852                 :           0 :             MultiXactIdPrecedes(multi1,
    2853                 :             :                                 multi2 + MULTIXACT_OFFSETS_PER_PAGE - 1));
    2854                 :             : }
    2855                 :             : 
    2856                 :             : /*
    2857                 :             :  * Decide whether a MultiXactMember page number is "older" for truncation
    2858                 :             :  * purposes.  There is no "invalid offset number" and members never wrap
    2859                 :             :  * around, so use the numbers verbatim.
    2860                 :             :  */
    2861                 :             : static bool
    2862                 :           0 : MultiXactMemberPagePrecedes(int64 page1, int64 page2)
    2863                 :             : {
    2864                 :           0 :     return page1 < page2;
    2865                 :             : }
    2866                 :             : 
    2867                 :             : static int
    2868                 :           0 : MultiXactOffsetIoErrorDetail(const void *opaque_data)
    2869                 :             : {
    2870                 :           0 :     MultiXactId multixid = *(const MultiXactId *) opaque_data;
    2871                 :             : 
    2872                 :           0 :     return errdetail("Could not access offset of multixact %u.", multixid);
    2873                 :             : }
    2874                 :             : 
    2875                 :             : static int
    2876                 :           0 : MultiXactMemberIoErrorDetail(const void *opaque_data)
    2877                 :             : {
    2878                 :           0 :     const MultiXactMemberSlruReadContext *context = opaque_data;
    2879                 :             : 
    2880         [ #  # ]:           0 :     if (MultiXactIdIsValid(context->multi))
    2881                 :           0 :         return errdetail("Could not access member of multixact %u at offset %" PRIu64 ".",
    2882                 :           0 :                          context->multi, context->offset);
    2883                 :             :     else
    2884                 :           0 :         return errdetail("Could not access multixact member at offset %" PRIu64 ".",
    2885                 :           0 :                          context->offset);
    2886                 :             : }
    2887                 :             : 
    2888                 :             : 
    2889                 :             : /*
    2890                 :             :  * Write a TRUNCATE xlog record
    2891                 :             :  *
    2892                 :             :  * We must flush the xlog record to disk before returning --- see notes in
    2893                 :             :  * TruncateCLOG().
    2894                 :             :  */
    2895                 :             : static void
    2896                 :           0 : WriteMTruncateXlogRec(Oid oldestMultiDB,
    2897                 :             :                       MultiXactId oldestMulti,
    2898                 :             :                       MultiXactOffset oldestOffset)
    2899                 :             : {
    2900                 :             :     XLogRecPtr  recptr;
    2901                 :             :     xl_multixact_truncate xlrec;
    2902                 :             : 
    2903                 :           0 :     xlrec.oldestMultiDB = oldestMultiDB;
    2904                 :           0 :     xlrec.oldestMulti = oldestMulti;
    2905                 :           0 :     xlrec.oldestOffset = oldestOffset;
    2906                 :             : 
    2907                 :           0 :     XLogBeginInsert();
    2908                 :           0 :     XLogRegisterData(&xlrec, SizeOfMultiXactTruncate);
    2909                 :           0 :     recptr = XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_TRUNCATE_ID);
    2910                 :           0 :     XLogFlush(recptr);
    2911                 :           0 : }
    2912                 :             : 
    2913                 :             : /*
    2914                 :             :  * MULTIXACT resource manager's routines
    2915                 :             :  */
    2916                 :             : void
    2917                 :           9 : multixact_redo(XLogReaderState *record)
    2918                 :             : {
    2919                 :           9 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    2920                 :             : 
    2921                 :             :     /* Backup blocks are not used in multixact records */
    2922                 :             :     Assert(!XLogRecHasAnyBlockRefs(record));
    2923                 :             : 
    2924         [ -  + ]:           9 :     if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
    2925                 :             :     {
    2926                 :             :         int64       pageno;
    2927                 :             : 
    2928                 :           0 :         memcpy(&pageno, XLogRecGetData(record), sizeof(pageno));
    2929                 :           0 :         SimpleLruZeroAndWritePage(MultiXactOffsetCtl, pageno);
    2930                 :             :     }
    2931         [ -  + ]:           9 :     else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
    2932                 :             :     {
    2933                 :             :         int64       pageno;
    2934                 :             : 
    2935                 :           0 :         memcpy(&pageno, XLogRecGetData(record), sizeof(pageno));
    2936                 :           0 :         SimpleLruZeroAndWritePage(MultiXactMemberCtl, pageno);
    2937                 :             :     }
    2938         [ +  - ]:           9 :     else if (info == XLOG_MULTIXACT_CREATE_ID)
    2939                 :             :     {
    2940                 :           9 :         xl_multixact_create *xlrec =
    2941                 :           9 :             (xl_multixact_create *) XLogRecGetData(record);
    2942                 :             :         TransactionId max_xid;
    2943                 :             :         int         i;
    2944                 :             : 
    2945                 :             :         /* Store the data back into the SLRU files */
    2946                 :           9 :         RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
    2947                 :           9 :                            xlrec->members);
    2948                 :             : 
    2949                 :             :         /* Make sure nextMXact/nextOffset are beyond what this record has */
    2950                 :           9 :         MultiXactAdvanceNextMXact(NextMultiXactId(xlrec->mid),
    2951                 :           9 :                                   xlrec->moff + xlrec->nmembers);
    2952                 :             : 
    2953                 :             :         /*
    2954                 :             :          * Make sure nextXid is beyond any XID mentioned in the record. This
    2955                 :             :          * should be unnecessary, since any XID found here ought to have other
    2956                 :             :          * evidence in the XLOG, but let's be safe.
    2957                 :             :          */
    2958                 :           9 :         max_xid = XLogRecGetXid(record);
    2959         [ +  + ]:          26 :         for (i = 0; i < xlrec->nmembers; i++)
    2960                 :             :         {
    2961         [ -  + ]:          17 :             if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
    2962                 :           0 :                 max_xid = xlrec->members[i].xid;
    2963                 :             :         }
    2964                 :             : 
    2965                 :           9 :         AdvanceNextFullTransactionIdPastXid(max_xid);
    2966                 :             :     }
    2967         [ #  # ]:           0 :     else if (info == XLOG_MULTIXACT_TRUNCATE_ID)
    2968                 :             :     {
    2969                 :             :         xl_multixact_truncate xlrec;
    2970                 :             : 
    2971                 :           0 :         memcpy(&xlrec, XLogRecGetData(record),
    2972                 :             :                SizeOfMultiXactTruncate);
    2973                 :             : 
    2974         [ #  # ]:           0 :         elog(DEBUG1, "replaying multixact truncation: "
    2975                 :             :              "oldestMulti %u (offsets segment %" PRIx64 "), "
    2976                 :             :              "oldestOffset %" PRIu64 " (members segment %" PRIx64 ")",
    2977                 :             :              xlrec.oldestMulti,
    2978                 :             :              MultiXactIdToOffsetSegment(xlrec.oldestMulti),
    2979                 :             :              xlrec.oldestOffset,
    2980                 :             :              MXOffsetToMemberSegment(xlrec.oldestOffset));
    2981                 :             : 
    2982                 :             :         /* should not be required, but more than cheap enough */
    2983                 :           0 :         LWLockAcquire(MultiXactTruncationLock, LW_EXCLUSIVE);
    2984                 :             : 
    2985                 :             :         /*
    2986                 :             :          * Advance the horizon values, so they're current at the end of
    2987                 :             :          * recovery.
    2988                 :             :          */
    2989                 :           0 :         SetMultiXactIdLimit(xlrec.oldestMulti, xlrec.oldestMultiDB);
    2990                 :             : 
    2991                 :           0 :         PerformMembersTruncation(xlrec.oldestOffset);
    2992                 :           0 :         PerformOffsetsTruncation(xlrec.oldestMulti);
    2993                 :             : 
    2994                 :           0 :         LWLockRelease(MultiXactTruncationLock);
    2995                 :             :     }
    2996                 :             :     else
    2997         [ #  # ]:           0 :         elog(PANIC, "multixact_redo: unknown op code %u", info);
    2998                 :           9 : }
    2999                 :             : 
    3000                 :             : /*
    3001                 :             :  * Entrypoint for sync.c to sync offsets files.
    3002                 :             :  */
    3003                 :             : int
    3004                 :           0 : multixactoffsetssyncfiletag(const FileTag *ftag, char *path)
    3005                 :             : {
    3006                 :           0 :     return SlruSyncFileTag(MultiXactOffsetCtl, ftag, path);
    3007                 :             : }
    3008                 :             : 
    3009                 :             : /*
    3010                 :             :  * Entrypoint for sync.c to sync members files.
    3011                 :             :  */
    3012                 :             : int
    3013                 :           0 : multixactmemberssyncfiletag(const FileTag *ftag, char *path)
    3014                 :             : {
    3015                 :           0 :     return SlruSyncFileTag(MultiXactMemberCtl, ftag, path);
    3016                 :             : }
        

Generated by: LCOV version 2.0-1